text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: globdoc.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:53:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <sot/clsids.hxx>
#include <svtools/moduleoptions.hxx>
#include <unomid.h>
#include "swtypes.hxx"
#include "shellio.hxx"
#include "globdoc.hxx"
#include "globdoc.hrc"
#include "cfgid.h"
/*--------------------------------------------------------------------
Beschreibung: Alle Filter registrieren
--------------------------------------------------------------------*/
TYPEINIT1(SwGlobalDocShell, SwDocShell);
//-------------------------------------------------------------------------
SFX_IMPL_OBJECTFACTORY( SwGlobalDocShell, SvGlobalName(SO3_SWGLOB_CLASSID), SFXOBJECTSHELL_STD_NORMAL|SFXOBJECTSHELL_HASMENU, "swriter/GlobalDocument" )
SwGlobalDocShell::SwGlobalDocShell(SfxObjectCreateMode eMode ) :
SwDocShell(eMode)
{
}
SwGlobalDocShell::~SwGlobalDocShell()
{
}
void SwGlobalDocShell::FillClass( SvGlobalName * pClassName,
sal_uInt32 * pClipFormat,
String * /*pAppName*/,
String * pLongUserName,
String * pUserName,
sal_Int32 nVersion ) const
{
if (nVersion == SOFFICE_FILEFORMAT_60)
{
*pClassName = SvGlobalName( SO3_SWGLOB_CLASSID_60 );
*pClipFormat = SOT_FORMATSTR_ID_STARWRITERGLOB_60;
*pLongUserName = SW_RESSTR(STR_WRITER_GLOBALDOC_FULLTYPE);
}
else if (nVersion == SOFFICE_FILEFORMAT_8)
{
*pClassName = SvGlobalName( SO3_SWGLOB_CLASSID_60 );
*pClipFormat = SOT_FORMATSTR_ID_STARWRITERGLOB_8;
*pLongUserName = SW_RESSTR(STR_WRITER_GLOBALDOC_FULLTYPE);
}
*pUserName = SW_RESSTR(STR_HUMAN_SWGLOBDOC_NAME);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.15.242); FILE MERGED 2008/03/31 16:58:25 rt 1.15.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: globdoc.cxx,v $
* $Revision: 1.16 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <sot/clsids.hxx>
#include <svtools/moduleoptions.hxx>
#include <unomid.h>
#include "swtypes.hxx"
#include "shellio.hxx"
#include "globdoc.hxx"
#include "globdoc.hrc"
#include "cfgid.h"
/*--------------------------------------------------------------------
Beschreibung: Alle Filter registrieren
--------------------------------------------------------------------*/
TYPEINIT1(SwGlobalDocShell, SwDocShell);
//-------------------------------------------------------------------------
SFX_IMPL_OBJECTFACTORY( SwGlobalDocShell, SvGlobalName(SO3_SWGLOB_CLASSID), SFXOBJECTSHELL_STD_NORMAL|SFXOBJECTSHELL_HASMENU, "swriter/GlobalDocument" )
SwGlobalDocShell::SwGlobalDocShell(SfxObjectCreateMode eMode ) :
SwDocShell(eMode)
{
}
SwGlobalDocShell::~SwGlobalDocShell()
{
}
void SwGlobalDocShell::FillClass( SvGlobalName * pClassName,
sal_uInt32 * pClipFormat,
String * /*pAppName*/,
String * pLongUserName,
String * pUserName,
sal_Int32 nVersion ) const
{
if (nVersion == SOFFICE_FILEFORMAT_60)
{
*pClassName = SvGlobalName( SO3_SWGLOB_CLASSID_60 );
*pClipFormat = SOT_FORMATSTR_ID_STARWRITERGLOB_60;
*pLongUserName = SW_RESSTR(STR_WRITER_GLOBALDOC_FULLTYPE);
}
else if (nVersion == SOFFICE_FILEFORMAT_8)
{
*pClassName = SvGlobalName( SO3_SWGLOB_CLASSID_60 );
*pClipFormat = SOT_FORMATSTR_ID_STARWRITERGLOB_8;
*pLongUserName = SW_RESSTR(STR_WRITER_GLOBALDOC_FULLTYPE);
}
*pUserName = SW_RESSTR(STR_HUMAN_SWGLOBDOC_NAME);
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2014, Planet Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "compositor.h"
/************************************************************************/
/* PLParseJson() */
/************************************************************************/
json_object *PLParseJson(const char *json_string)
{
json_tokener* jstok = NULL;
json_object* jsobj = NULL;
jstok = json_tokener_new();
jsobj = json_tokener_parse_ex(jstok, json_string, -1);
if( jstok->err != json_tokener_success)
{
CPLError( CE_Warning, CPLE_AppDefined,
"JSON parsing failure: %s (at offset %d)",
json_tokener_errors[jstok->err], jstok->char_offset);
json_tokener_free(jstok);
return NULL;
}
else
{
json_tokener_free(jstok);
return jsobj;
}
}
/************************************************************************/
/* PLFindJSONChild() */
/************************************************************************/
json_object *PLFindJSONChild(json_object *json, const char *path,
int create)
{
if( path == NULL || strlen(path) == 0)
return json;
CPLStringList path_items(CSLTokenizeStringComplex(path, ".", FALSE, FALSE));
int i;
for(i=0; i < path_items.size(); i++)
{
json_object *parent = json;
if(!json_object_is_type(parent, json_type_object))
return NULL;
json = json_object_object_get(parent, path_items[i]);
if(json == NULL)
{
if(!create)
return NULL;
json = json_object_new_object();
json_object_object_add(parent, path_items[i], json);
}
}
return json;
}
/************************************************************************/
/* PLGetJSONString() */
/************************************************************************/
CPLString PLGetJSONString(json_object *json, const char *path,
const char *default_value)
{
json_object *obj = PLFindJSONChild(json, path, FALSE);
if( obj == NULL)
{
if( default_value == NULL )
return "NULL";
else
return default_value;
}
else
{
return json_object_get_string(obj);
}
}
<commit_msg>start work on validator<commit_after>/**
* Copyright 2014, Planet Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "compositor.h"
/************************************************************************/
/* PLParseJson() */
/************************************************************************/
json_object *PLParseJson(const char *json_string)
{
json_tokener* jstok = NULL;
json_object* jsobj = NULL;
jstok = json_tokener_new();
jsobj = json_tokener_parse_ex(jstok, json_string, -1);
if( jstok->err != json_tokener_success)
{
CPLError( CE_Warning, CPLE_AppDefined,
"JSON parsing failure: %s (at offset %d)",
json_tokener_errors[jstok->err], jstok->char_offset);
json_tokener_free(jstok);
return NULL;
}
else
{
json_tokener_free(jstok);
return jsobj;
}
}
/************************************************************************/
/* PLFindJSONChild() */
/************************************************************************/
json_object *PLFindJSONChild(json_object *json, const char *path,
int create)
{
if( path == NULL || strlen(path) == 0)
return json;
CPLStringList path_items(CSLTokenizeStringComplex(path, ".", FALSE, FALSE));
int i;
for(i=0; i < path_items.size(); i++)
{
json_object *parent = json;
if(!json_object_is_type(parent, json_type_object))
return NULL;
json = json_object_object_get(parent, path_items[i]);
if(json == NULL)
{
if(!create)
return NULL;
json = json_object_new_object();
json_object_object_add(parent, path_items[i], json);
}
}
return json;
}
/************************************************************************/
/* PLGetJSONString() */
/************************************************************************/
CPLString PLGetJSONString(json_object *json, const char *path,
const char *default_value)
{
json_object *obj = PLFindJSONChild(json, path, FALSE);
if( obj == NULL)
{
if( default_value == NULL )
return "NULL";
else
return default_value;
}
else
{
return json_object_get_string(obj);
}
}
/************************************************************************/
/* PLValidateJSONNode() */
/* */
/* Should be something like: */
/* parm_name:[o,r]:[string,number,array,object],... */
/* */
/* eg. */
/* "output_file:r:string,quality_file:o:string" */
/************************************************************************/
void PLValidateJSONNode(json_object *node,
const char *definition)
{
CPLStringList parm_defs(CSLTokenizeString2(definition,",",0));
std::map<CPLString,CPLString> parmOptions;
std::map<CPLString,CPLString> parmTypes;
for( int iParm=0; iParm < parm_defs.size(); iParm++ )
{
CPLStringList parts(CSLTokenizeString2(parm_defs[iParm], ":", 0));
CPLAssert(parts.size() == 3);
parmOptions[parts[0]] = parts[1];
parmOptions[parts[0]] = parts[2];
}
}
<|endoftext|>
|
<commit_before>// SciTE - Scintilla based Text Editor
/** @file GTKMutex.cxx
** Define mutex
**/
// SciTE & Scintilla copyright 1998-2003 by Neil Hodgson <[email protected]>
// Copyright 2007 by Neil Hodgson <[email protected]>, from April White <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
// http://www.microsoft.com/msj/0797/win320797.aspx
#include "Mutex.h"
class GTKMutex : public Mutex {
private:
virtual void Lock() {}
virtual void Unlock() {}
GTKMutex() {}
virtual ~GTKMutex() {}
friend class Mutex;
};
Mutex *Mutex::Create() {
return new GTKMutex();
}
<commit_msg>Implement mutexes on GTK+.<commit_after>// SciTE - Scintilla based Text Editor
/** @file GTKMutex.cxx
** Define mutex
**/
// SciTE & Scintilla copyright 1998-2003 by Neil Hodgson <[email protected]>
// Copyright 2007 by Neil Hodgson <[email protected]>, from April White <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
// http://www.microsoft.com/msj/0797/win320797.aspx
#include <glib.h>
#include "Mutex.h"
class GTKMutex : public Mutex {
private:
GMutex m;
virtual void Lock() {
g_mutex_lock(&m);
}
virtual void Unlock() {
g_mutex_unlock(&m);
}
GTKMutex() {
g_mutex_init(&m);
}
virtual ~GTKMutex() {
g_mutex_clear(&m);
}
friend class Mutex;
};
Mutex *Mutex::Create() {
return new GTKMutex();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 BrewPi / Elco Jacobs
*
* This file is part of BrewPi.
*
* BrewPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BrewPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Pid.h"
Pid::Pid(TempSensorBasic * input,
ActuatorRange * output,
SetPoint * setPoint)
{
setConstants(temp_t(0.0), 0, 0);
p = decltype(p)::base_type(0);
i = decltype(i)::base_type(0);
d = decltype(p)::base_type(0);
inputError = decltype(inputError)::base_type(0);
derivative = decltype(derivative)::base_type(0);
integral = decltype(integral)::base_type(0);
failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read
setInputSensor(input);
setOutputActuator(output);
setSetPoint(setPoint);
setInputFilter(0);
// some filtering necessary due to quantization causing steps in the temperature
setDerivativeFilter(2);
actuatorIsNegative = false;
enabled = true;
previousSetPoint = temp_t::invalid();
// autotune = false;
// tuning = false;
// outputLag = 0;
// maxDerivative = 0.0;
}
void Pid::setConstants(temp_long_t kp,
uint16_t ti,
uint16_t td)
{
Kp = kp;
Ti = ti;
Td = td;
}
void Pid::update()
{
temp_t inputVal;
bool validSetPoint = true;
bool validSensor = true;
if( setPoint->read().isDisabledOrInvalid()){
validSetPoint = false;
}
inputVal = inputSensor -> read();
validSensor = !inputVal.isDisabledOrInvalid();
if (!validSensor){
// Could not read from input sensor
if (failedReadCount < 255){ // limit
failedReadCount++;
}
}
else{
if (failedReadCount > 60){ // filters are stale, re-initialize them
inputFilter.init(inputVal);
derivativeFilter.init(temp_precise_t(0.0));
}
failedReadCount = 0;
}
bool tooManyFailedReads = false;
if(validSensor){ // only update internal filters and inputError if input sensor is valid
inputFilter.add(inputVal);
if(validSetPoint){
temp_t currentSetPoint = setPoint->read();
if(previousSetPoint.isDisabledOrInvalid()){
previousSetPoint = currentSetPoint;
}
temp_precise_t previousError = inputFilter.readPrevOutput() - previousSetPoint;
temp_precise_t currentError = inputFilter.readOutput() - currentSetPoint;
temp_precise_t delta = currentError - previousError;
previousSetPoint = currentSetPoint;
inputError = currentError; // store input error, as temp_t, instead of temp_precise_t
// Add to derivative filter shifted, because of limited precision for such low values
// Limit to 0.125 degree per second, to prevent overflow in shift and to eliminate setpoint changes
// 128/1024 = 0.125 C/s.
temp_precise_t deltaClipped = delta;
temp_precise_t max = temp_precise_t::max() >> uint8_t(10);
temp_precise_t min = temp_precise_t::min() >> uint8_t(10);
if(deltaClipped > max){
deltaClipped = max;
}
else if(deltaClipped < min){
deltaClipped = min;
}
derivativeFilter.add(deltaClipped << uint8_t(10));
derivative = derivativeFilter.readOutput() >> uint8_t(10);
}
else{
derivativeFilter.add(temp_precise_t(0.0));
}
}
else{
if(failedReadCount > 10){
tooManyFailedReads = true; // after 10 failed reads, disable pid
}
}
if(!enabled || tooManyFailedReads || !validSetPoint){
inputError = temp_t::invalid();
p = decltype(p)(0.0);
i = decltype(i)(0.0);
d = decltype(p)(0.0);
return;
}
else{
// calculate PID parts.
p = Kp * -inputError;
i = (Ti != 0) ? (integral/Ti) : temp_long_t(0.0);
d = -Kp * (derivative * Td);
}
temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d);
// Get output to send to actuator. When actuator is a 'cooler', invert the result
temp_t output = (actuatorIsNegative) ? -pidResult : pidResult;
outputActuator -> setValue(output);
// get the value that is clipped to the actuator's range
output = outputActuator->getValue();
// When actuator is a 'cooler', invert the output again
output = (actuatorIsNegative) ? -output : output;
if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero.
integral = decltype(integral)::base_type(0);
}
else{
// update integral with anti-windup back calculation
// pidResult - output is zero when actuator is not saturated
// when the actuator is close the to pidResult (setpoint), disable anti-windup
// this prevens small fluctuations from keeping the integrator at zero
integral = integral + p;
temp_long_t antiWindup(temp_long_t::base_type(0));
if(pidResult != temp_long_t(output)){ // clipped to actuator min or max set in target actuator
antiWindup = pidResult - output;
antiWindup *= 5; // Anti windup gain is 5 when clipping to min/max
}
else{ // actuator could be not reaching set value due to physics or limits in its target actuator
// get the actual achieved value in actuator. This could differ due to slowness time/mutex limits
temp_t achievedOutput = outputActuator->readValue();
if(!achievedOutput.isDisabledOrInvalid()){ // only apply anti-windup when it is possible to read back the actual value
// When actuator is a 'cooler', invert the output again
achievedOutput = (actuatorIsNegative) ? -achievedOutput : achievedOutput;
temp_long_t closeThreshold = Kp;
temp_t noAntiWindupMin = output - closeThreshold;
temp_t noAntiWindupMax = output + closeThreshold;
// do not apply anti-windup if close to target. Always apply when actuator is at zero.
if(achievedOutput == temp_t(0.0) || achievedOutput < noAntiWindupMin || achievedOutput > noAntiWindupMax){
antiWindup = pidResult - achievedOutput;
antiWindup *= 3; // Anti windup gain is 3 for this kind of windup
}
}
}
// only apply anti-windup if it will decrease the integral and prevent crossing through zero
if(integral.sign() * antiWindup.sign() == 1){
if((integral - antiWindup).sign() != integral.sign()){
integral = decltype(integral)::base_type(0);
}
else{
integral -= antiWindup;
}
}
}
}
void Pid::setFiltering(uint8_t b){
inputFilter.setFiltering(b);
derivativeFilter.setFiltering(b);
}
uint8_t Pid::getFiltering(){
return inputFilter.getFiltering();
}
void Pid::setInputFilter(uint8_t b)
{
inputFilter.setFiltering(b);
}
void Pid::setDerivativeFilter(uint8_t b)
{
derivativeFilter.setFiltering(b);
}
bool Pid::setInputSensor(TempSensorBasic * s)
{
inputSensor = s;
temp_t t = s -> read();
if (t.isDisabledOrInvalid()){
return false; // could not read from sensor
}
inputFilter.init(t);
derivativeFilter.init(0.0);
return true;
}
bool Pid::setOutputActuator(ActuatorRange * a)
{
outputActuator = a;
return true;
}
/*
// Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method
// This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that.
void Pid::tune(temp output, temp previousOutput){
static uint16_t lagTimer = 0;
static temp tuningStartTemp = inputFilter.readOutput();
temp min = outputActuator->min();
temp max = outputActuator->max();
temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2
if(output == outputActuator->max() && previousOutput < tuningThreshold){
tuning = true; // only start tuning at a big step to the maximum output
}
// cancel tuning when the output is under the tuning threshold before maximum derivative is detected
if(output < tuningThreshold){
if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){
tuning = false; // only stop tuning if filters have had time to settle
}
}
// TODO: when this happens, check the filter delay and see if the maximum still has to come
// Detect when at max derivative, the time until this happens is the lag time
// Together with the maximum derivative, this is used to determine the PID parameters
if(tuning){ // only for heating now
// if the derivative of the input starts falling, we have hit an inflection point
// Also check that the derivative is positive
if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){
maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it
uint16_t filterDelay = derivativeFilter.getDelay();
uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay;
// set PID constants to have no overshoot
temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here
temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative;
if(riseTime < temp_long(0)){
riseTime = 0.0;
}
deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it
outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds
temp_long RL = derivative * deadTime;
if (RL < temp_long(0.25)){ // prevent divide by zero
Kp = 160.0;
}
else{
Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot
}
if(deadTime > temp_long(1)){
Ki = Kp/(deadTime+deadTime);
}
else{
Ki = Kp*temp_long(0.5);
}
Kd = Kp*deadTime*temp_long(0.33);
tuning = false; // tuning ready
}
else{
if(lagTimer < UINT16_MAX){
lagTimer++;
}
}
}
else{
lagTimer= 0;
tuningStartTemp = inputFilter.readOutput();
}
}
*/
<commit_msg>moved early return so that when PID is enabled, but intput invalid, the output actuator is zero<commit_after>/*
* Copyright 2015 BrewPi / Elco Jacobs
*
* This file is part of BrewPi.
*
* BrewPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BrewPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Pid.h"
Pid::Pid(TempSensorBasic * input,
ActuatorRange * output,
SetPoint * setPoint)
{
setConstants(temp_t(0.0), 0, 0);
p = decltype(p)::base_type(0);
i = decltype(i)::base_type(0);
d = decltype(p)::base_type(0);
inputError = decltype(inputError)::base_type(0);
derivative = decltype(derivative)::base_type(0);
integral = decltype(integral)::base_type(0);
failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read
setInputSensor(input);
setOutputActuator(output);
setSetPoint(setPoint);
setInputFilter(0);
// some filtering necessary due to quantization causing steps in the temperature
setDerivativeFilter(2);
actuatorIsNegative = false;
enabled = true;
previousSetPoint = temp_t::invalid();
// autotune = false;
// tuning = false;
// outputLag = 0;
// maxDerivative = 0.0;
}
void Pid::setConstants(temp_long_t kp,
uint16_t ti,
uint16_t td)
{
Kp = kp;
Ti = ti;
Td = td;
}
void Pid::update()
{
temp_t inputVal;
bool validSetPoint = true;
bool validSensor = true;
if( setPoint->read().isDisabledOrInvalid()){
validSetPoint = false;
}
inputVal = inputSensor -> read();
validSensor = !inputVal.isDisabledOrInvalid();
if (!validSensor){
// Could not read from input sensor
if (failedReadCount < 255){ // limit
failedReadCount++;
}
}
else{
if (failedReadCount > 60){ // filters are stale, re-initialize them
inputFilter.init(inputVal);
derivativeFilter.init(temp_precise_t(0.0));
}
failedReadCount = 0;
}
bool tooManyFailedReads = false;
if(validSensor){ // only update internal filters and inputError if input sensor is valid
inputFilter.add(inputVal);
if(validSetPoint){
temp_t currentSetPoint = setPoint->read();
if(previousSetPoint.isDisabledOrInvalid()){
previousSetPoint = currentSetPoint;
}
temp_precise_t previousError = inputFilter.readPrevOutput() - previousSetPoint;
temp_precise_t currentError = inputFilter.readOutput() - currentSetPoint;
temp_precise_t delta = currentError - previousError;
previousSetPoint = currentSetPoint;
inputError = currentError; // store input error, as temp_t, instead of temp_precise_t
// Add to derivative filter shifted, because of limited precision for such low values
// Limit to 0.125 degree per second, to prevent overflow in shift and to eliminate setpoint changes
// 128/1024 = 0.125 C/s.
temp_precise_t deltaClipped = delta;
temp_precise_t max = temp_precise_t::max() >> uint8_t(10);
temp_precise_t min = temp_precise_t::min() >> uint8_t(10);
if(deltaClipped > max){
deltaClipped = max;
}
else if(deltaClipped < min){
deltaClipped = min;
}
derivativeFilter.add(deltaClipped << uint8_t(10));
derivative = derivativeFilter.readOutput() >> uint8_t(10);
}
else{
derivativeFilter.add(temp_precise_t(0.0));
}
}
else{
if(failedReadCount > 10){
tooManyFailedReads = true; // after 10 failed reads, disable pid
}
}
if(!enabled || tooManyFailedReads || !validSetPoint){
inputError = temp_t::invalid();
p = decltype(p)(0.0);
i = decltype(i)(0.0);
d = decltype(p)(0.0);
}
else{
// calculate PID parts.
p = Kp * -inputError;
i = (Ti != 0) ? (integral/Ti) : temp_long_t(0.0);
d = -Kp * (derivative * Td);
}
if(!enabled){
return;
}
temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d);
// Get output to send to actuator. When actuator is a 'cooler', invert the result
temp_t output = (actuatorIsNegative) ? -pidResult : pidResult;
outputActuator -> setValue(output);
// get the value that is clipped to the actuator's range
output = outputActuator->getValue();
// When actuator is a 'cooler', invert the output again
output = (actuatorIsNegative) ? -output : output;
if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero.
integral = decltype(integral)::base_type(0);
}
else{
// update integral with anti-windup back calculation
// pidResult - output is zero when actuator is not saturated
// when the actuator is close the to pidResult (setpoint), disable anti-windup
// this prevens small fluctuations from keeping the integrator at zero
integral = integral + p;
temp_long_t antiWindup(temp_long_t::base_type(0));
if(pidResult != temp_long_t(output)){ // clipped to actuator min or max set in target actuator
antiWindup = pidResult - output;
antiWindup *= 5; // Anti windup gain is 5 when clipping to min/max
}
else{ // actuator could be not reaching set value due to physics or limits in its target actuator
// get the actual achieved value in actuator. This could differ due to slowness time/mutex limits
temp_t achievedOutput = outputActuator->readValue();
if(!achievedOutput.isDisabledOrInvalid()){ // only apply anti-windup when it is possible to read back the actual value
// When actuator is a 'cooler', invert the output again
achievedOutput = (actuatorIsNegative) ? -achievedOutput : achievedOutput;
temp_long_t closeThreshold = Kp;
temp_t noAntiWindupMin = output - closeThreshold;
temp_t noAntiWindupMax = output + closeThreshold;
// do not apply anti-windup if close to target. Always apply when actuator is at zero.
if(achievedOutput == temp_t(0.0) || achievedOutput < noAntiWindupMin || achievedOutput > noAntiWindupMax){
antiWindup = pidResult - achievedOutput;
antiWindup *= 3; // Anti windup gain is 3 for this kind of windup
}
}
}
// only apply anti-windup if it will decrease the integral and prevent crossing through zero
if(integral.sign() * antiWindup.sign() == 1){
if((integral - antiWindup).sign() != integral.sign()){
integral = decltype(integral)::base_type(0);
}
else{
integral -= antiWindup;
}
}
}
}
void Pid::setFiltering(uint8_t b){
inputFilter.setFiltering(b);
derivativeFilter.setFiltering(b);
}
uint8_t Pid::getFiltering(){
return inputFilter.getFiltering();
}
void Pid::setInputFilter(uint8_t b)
{
inputFilter.setFiltering(b);
}
void Pid::setDerivativeFilter(uint8_t b)
{
derivativeFilter.setFiltering(b);
}
bool Pid::setInputSensor(TempSensorBasic * s)
{
inputSensor = s;
temp_t t = s -> read();
if (t.isDisabledOrInvalid()){
return false; // could not read from sensor
}
inputFilter.init(t);
derivativeFilter.init(0.0);
return true;
}
bool Pid::setOutputActuator(ActuatorRange * a)
{
outputActuator = a;
return true;
}
/*
// Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method
// This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that.
void Pid::tune(temp output, temp previousOutput){
static uint16_t lagTimer = 0;
static temp tuningStartTemp = inputFilter.readOutput();
temp min = outputActuator->min();
temp max = outputActuator->max();
temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2
if(output == outputActuator->max() && previousOutput < tuningThreshold){
tuning = true; // only start tuning at a big step to the maximum output
}
// cancel tuning when the output is under the tuning threshold before maximum derivative is detected
if(output < tuningThreshold){
if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){
tuning = false; // only stop tuning if filters have had time to settle
}
}
// TODO: when this happens, check the filter delay and see if the maximum still has to come
// Detect when at max derivative, the time until this happens is the lag time
// Together with the maximum derivative, this is used to determine the PID parameters
if(tuning){ // only for heating now
// if the derivative of the input starts falling, we have hit an inflection point
// Also check that the derivative is positive
if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){
maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it
uint16_t filterDelay = derivativeFilter.getDelay();
uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay;
// set PID constants to have no overshoot
temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here
temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative;
if(riseTime < temp_long(0)){
riseTime = 0.0;
}
deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it
outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds
temp_long RL = derivative * deadTime;
if (RL < temp_long(0.25)){ // prevent divide by zero
Kp = 160.0;
}
else{
Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot
}
if(deadTime > temp_long(1)){
Ki = Kp/(deadTime+deadTime);
}
else{
Ki = Kp*temp_long(0.5);
}
Kd = Kp*deadTime*temp_long(0.33);
tuning = false; // tuning ready
}
else{
if(lagTimer < UINT16_MAX){
lagTimer++;
}
}
}
else{
lagTimer= 0;
tuningStartTemp = inputFilter.readOutput();
}
}
*/
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Tianjin University
* All rights reserved
*
* Author: Liang Kaiyuan
*/
/**
* @file
*
* Iso-X component and data structure
*/
#ifndef __ARCH_ARM_ISOX_HH__
#define __ARCH_ARM_ISOX_HH__
#include "arch/types.hh"
#include "arch/registers.hh"
#include "base/types.hh"
#include "arch/arm/table_walker.hh"
#define COMPMAX 1024
using namespace std;
/* Compartment Table Entry (CTEntry)
*
*/
typedef struct CTEntry
{
Addr comp_base;
size_t comp_size;
int page_count;
std::hash<std::string> comp_hash;
Addr cpt_base;
size_t cpt_size;
}CTEntry;
/* Physical Page Compartment Membership Vector (CMV)
*
*/
class CMV
{
private:
/* The number of physical pages*/
size_t page_count;
/* The bits of physical page*/
size_t page_bits;
bool *vectors;
public:
CMV(size_t page_count, size_t page_bits);
~CMV();
void setVector(Addr paddr, bool vec);
bool getVector(Addr paddr);
};
/* Compartment Table (CT)
*
*/
class CT
{
private:
CTEntry entries[COMPMAX];
public:
CT(void);
CTEntry& getEntry(int comp_id);
};
class IsoX
{
private:
/* Compartment membership vector */
CMV *cmv;
/* Compartment table*/
CT *ct;
/* Register pointing to
* base address of current compartment page table
*/
Addr cpt_base;
/* Register storing ID of current compartment */
int ccr_id;
/* Register storing CT entry
* corresponding to current active compartment
*/
CTEntry ccr_ct;
/* Processor state register*/
bool psr;
public:
IsoX();
/** Initialize Iso-X
* @page_cnt The number of physical pages used to initialize CMV
* @page_bits The bits of physical page used to initialize CMV
*/
void init(size_t page_cnt, size_t page_bits);
CTEntry& getEntry(int comp_id);
Addr readCPTBASEReg();
int readCCRIDReg();
CTEntry readCCRCTReg();
bool readPSRReg();
void setCPTBASEReg(Addr base);
void setCCRIDReg(int id);
void setPSRReg(bool mode);
bool isCompMode();
bool inComp(Addr vaddr);
bool getCMV(Addr paddr);
void setCMV(Addr paddr, bool vec);
void leaveComp();
};
static IsoX isox;
/* Arguments for Isox Instructions
*
*/
class IsoxArgus
{
private:
public:
IsoxArgus();
int comp_id;
Addr comp_base;
size_t comp_size;
Addr cpt_base;
size_t cpt_size;
Addr virt_addr;
Addr phys_addr;
int page_perms;
};
static IsoxArgus isoxargus;
#endif /*__ARCH_ARM_ISOX_HH__*/
<commit_msg>Add metapage for test, will be removed later<commit_after>/*
* Copyright (c) Tianjin University
* All rights reserved
*
* Author: Liang Kaiyuan
*/
/**
* @file
*
* Iso-X component and data structure
*/
#ifndef __ARCH_ARM_ISOX_HH__
#define __ARCH_ARM_ISOX_HH__
#include "arch/types.hh"
#include "arch/registers.hh"
#include "base/types.hh"
#include "arch/arm/table_walker.hh"
#define COMPMAX 1024
using namespace std;
/* Compartment Table Entry (CTEntry)
*
*/
typedef struct CTEntry
{
Addr comp_base;
size_t comp_size;
int page_count;
std::hash<std::string> comp_hash;
Addr cpt_base;
size_t cpt_size;
}CTEntry;
/* Physical Page Compartment Membership Vector (CMV)
*
*/
class CMV
{
private:
/* The number of physical pages*/
size_t page_count;
/* The bits of physical page*/
size_t page_bits;
bool *vectors;
public:
CMV(size_t page_count, size_t page_bits);
~CMV();
void setVector(Addr paddr, bool vec);
bool getVector(Addr paddr);
};
/* Compartment Table (CT)
*
*/
class CT
{
private:
CTEntry entries[COMPMAX];
public:
CT(void);
CTEntry& getEntry(int comp_id);
};
class IsoX
{
private:
/* Compartment membership vector */
CMV *cmv;
/* Compartment table*/
CT *ct;
/* Register pointing to
* base address of current compartment page table
*/
Addr cpt_base;
/* Register storing ID of current compartment */
int ccr_id;
/* Register storing CT entry
* corresponding to current active compartment
*/
CTEntry ccr_ct;
/* Processor state register*/
bool psr;
public:
IsoX();
/** Initialize Iso-X
* @page_cnt The number of physical pages used to initialize CMV
* @page_bits The bits of physical page used to initialize CMV
*/
void init(size_t page_cnt, size_t page_bits);
CTEntry& getEntry(int comp_id);
Addr readCPTBASEReg();
int readCCRIDReg();
CTEntry readCCRCTReg();
bool readPSRReg();
void setCPTBASEReg(Addr base);
void setCCRIDReg(int id);
void setPSRReg(bool mode);
bool isCompMode();
bool inComp(Addr vaddr);
bool getCMV(Addr paddr);
void setCMV(Addr paddr, bool vec);
void leaveComp();
};
static IsoX isox;
/* Arguments for Isox Instructions
*
*/
class IsoxArgus
{
private:
public:
IsoxArgus();
int comp_id;
Addr comp_base;
size_t comp_size;
Addr cpt_base;
size_t cpt_size;
Addr phys_addr;
size_t page_bits;
};
static IsoxArgus isoxargus;
/* Meta-page, currently just for testing
* will be removed later
*/
class MetaPage
{
private:
public:
MetaPage(){};
ThreadContext *tc;
string comp_pubkey;
string certify;
};
static MetaPage metapage;
#endif /*__ARCH_ARM_ISOX_HH__*/
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Christoph Bumiller
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "nv50_ir_util.h"
namespace nv50_ir {
void DLList::clear()
{
for (Item *next, *item = head.next; item != &head; item = next) {
next = item->next;
delete item;
}
head.next = head.prev = &head;
}
void
DLList::Iterator::erase()
{
Item *rem = pos;
if (rem == term)
return;
pos = pos->next;
DLLIST_DEL(rem);
delete rem;
}
void DLList::Iterator::moveToList(DLList& dest)
{
Item *item = pos;
assert(term != &dest.head);
assert(pos != term);
pos = pos->next;
DLLIST_DEL(item);
DLLIST_ADDHEAD(&dest.head, item);
}
bool
DLList::Iterator::insert(void *data)
{
Item *ins = new Item(data);
ins->next = pos->next;
ins->prev = pos;
pos->next->prev = ins;
pos->next = ins;
if (pos == term)
term = ins;
return true;
}
void
Stack::moveTo(Stack& that)
{
unsigned int newSize = this->size + that.size;
while (newSize > that.limit)
that.resize();
memcpy(&that.array[that.size], &array[0], this->size * sizeof(Item));
that.size = newSize;
this->size = 0;
}
Interval::~Interval()
{
clear();
}
void
Interval::clear()
{
for (Range *next, *r = head; r; r = next) {
next = r->next;
delete r;
}
}
bool
Interval::extend(int a, int b)
{
Range *r, **nextp = &head;
// NOTE: we need empty intervals for fixed registers
// if (a == b)
// return false;
assert(a <= b);
for (r = head; r; r = r->next) {
if (b < r->bgn)
break; // insert before
if (a > r->end) {
// insert after
nextp = &r->next;
continue;
}
// overlap
if (a < r->bgn) {
r->bgn = a;
if (b > r->end)
r->end = b;
r->coalesce(&tail);
return true;
}
if (b > r->end) {
r->end = b;
r->coalesce(&tail);
return true;
}
assert(a >= r->bgn);
assert(b <= r->end);
return true;
}
(*nextp) = new Range(a, b);
(*nextp)->next = r;
for (r = (*nextp); r->next; r = r->next);
tail = r;
return true;
}
bool Interval::contains(int pos)
{
for (Range *r = head; r && r->bgn <= pos; r = r->next)
if (r->end > pos)
return true;
return false;
}
bool Interval::overlaps(const Interval &iv) const
{
for (Range *rA = this->head; rA; rA = rA->next)
for (Range *rB = iv.head; rB; rB = rB->next)
if (rB->bgn < rA->end &&
rB->end > rA->bgn)
return true;
return false;
}
void Interval::unify(Interval &that)
{
assert(this != &that);
for (Range *next, *r = that.head; r; r = next) {
next = r->next;
this->extend(r->bgn, r->end);
delete r;
}
that.head = NULL;
}
void Interval::print() const
{
if (!head)
return;
INFO("[%i %i)", head->bgn, head->end);
for (const Range *r = head->next; r; r = r->next)
INFO(" [%i %i)", r->bgn, r->end);
INFO("\n");
}
void
BitSet::andNot(const BitSet &set)
{
assert(data && set.data);
assert(size >= set.size);
for (unsigned int i = 0; i < (set.size + 31) / 32; ++i)
data[i] &= ~set.data[i];
}
BitSet& BitSet::operator|=(const BitSet &set)
{
assert(data && set.data);
assert(size >= set.size);
for (unsigned int i = 0; i < (set.size + 31) / 32; ++i)
data[i] |= set.data[i];
return *this;
}
bool BitSet::allocate(unsigned int nBits, bool zero)
{
if (data && size < nBits) {
FREE(data);
data = NULL;
}
size = nBits;
if (!data)
data = reinterpret_cast<uint32_t *>(CALLOC((size + 31) / 32, 4));
if (zero)
memset(data, 0, (size + 7) / 8);
else
data[(size + 31) / 32 - 1] = 0; // clear unused bits (e.g. for popCount)
return data;
}
unsigned int BitSet::popCount() const
{
unsigned int count = 0;
for (unsigned int i = 0; i < (size + 31) / 32; ++i)
if (data[i])
count += util_bitcount(data[i]);
return count;
}
void BitSet::fill(uint32_t val)
{
unsigned int i;
for (i = 0; i < (size + 31) / 32; ++i)
data[i] = val;
if (val)
data[i] &= ~(0xffffffff << (size % 32)); // BE ?
}
void BitSet::setOr(BitSet *pA, BitSet *pB)
{
if (!pB) {
*this = *pA;
} else {
for (unsigned int i = 0; i < (size + 31) / 32; ++i)
data[i] = pA->data[i] | pB->data[i];
}
}
void BitSet::print() const
{
unsigned int n = 0;
INFO("BitSet of size %u:\n", size);
for (unsigned int i = 0; i < (size + 31) / 32; ++i) {
uint32_t bits = data[i];
while (bits) {
int pos = ffs(bits) - 1;
bits &= ~(1 << pos);
INFO(" %i", i * 32 + pos);
++n;
if ((n % 16) == 0)
INFO("\n");
}
}
if (n % 16)
INFO("\n");
}
} // namespace nv50_ir
<commit_msg>nv50/ir: Fix Interval::clear().<commit_after>/*
* Copyright 2011 Christoph Bumiller
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "nv50_ir_util.h"
namespace nv50_ir {
void DLList::clear()
{
for (Item *next, *item = head.next; item != &head; item = next) {
next = item->next;
delete item;
}
head.next = head.prev = &head;
}
void
DLList::Iterator::erase()
{
Item *rem = pos;
if (rem == term)
return;
pos = pos->next;
DLLIST_DEL(rem);
delete rem;
}
void DLList::Iterator::moveToList(DLList& dest)
{
Item *item = pos;
assert(term != &dest.head);
assert(pos != term);
pos = pos->next;
DLLIST_DEL(item);
DLLIST_ADDHEAD(&dest.head, item);
}
bool
DLList::Iterator::insert(void *data)
{
Item *ins = new Item(data);
ins->next = pos->next;
ins->prev = pos;
pos->next->prev = ins;
pos->next = ins;
if (pos == term)
term = ins;
return true;
}
void
Stack::moveTo(Stack& that)
{
unsigned int newSize = this->size + that.size;
while (newSize > that.limit)
that.resize();
memcpy(&that.array[that.size], &array[0], this->size * sizeof(Item));
that.size = newSize;
this->size = 0;
}
Interval::~Interval()
{
clear();
}
void
Interval::clear()
{
for (Range *next, *r = head; r; r = next) {
next = r->next;
delete r;
}
head = tail = NULL;
}
bool
Interval::extend(int a, int b)
{
Range *r, **nextp = &head;
// NOTE: we need empty intervals for fixed registers
// if (a == b)
// return false;
assert(a <= b);
for (r = head; r; r = r->next) {
if (b < r->bgn)
break; // insert before
if (a > r->end) {
// insert after
nextp = &r->next;
continue;
}
// overlap
if (a < r->bgn) {
r->bgn = a;
if (b > r->end)
r->end = b;
r->coalesce(&tail);
return true;
}
if (b > r->end) {
r->end = b;
r->coalesce(&tail);
return true;
}
assert(a >= r->bgn);
assert(b <= r->end);
return true;
}
(*nextp) = new Range(a, b);
(*nextp)->next = r;
for (r = (*nextp); r->next; r = r->next);
tail = r;
return true;
}
bool Interval::contains(int pos)
{
for (Range *r = head; r && r->bgn <= pos; r = r->next)
if (r->end > pos)
return true;
return false;
}
bool Interval::overlaps(const Interval &iv) const
{
for (Range *rA = this->head; rA; rA = rA->next)
for (Range *rB = iv.head; rB; rB = rB->next)
if (rB->bgn < rA->end &&
rB->end > rA->bgn)
return true;
return false;
}
void Interval::unify(Interval &that)
{
assert(this != &that);
for (Range *next, *r = that.head; r; r = next) {
next = r->next;
this->extend(r->bgn, r->end);
delete r;
}
that.head = NULL;
}
void Interval::print() const
{
if (!head)
return;
INFO("[%i %i)", head->bgn, head->end);
for (const Range *r = head->next; r; r = r->next)
INFO(" [%i %i)", r->bgn, r->end);
INFO("\n");
}
void
BitSet::andNot(const BitSet &set)
{
assert(data && set.data);
assert(size >= set.size);
for (unsigned int i = 0; i < (set.size + 31) / 32; ++i)
data[i] &= ~set.data[i];
}
BitSet& BitSet::operator|=(const BitSet &set)
{
assert(data && set.data);
assert(size >= set.size);
for (unsigned int i = 0; i < (set.size + 31) / 32; ++i)
data[i] |= set.data[i];
return *this;
}
bool BitSet::allocate(unsigned int nBits, bool zero)
{
if (data && size < nBits) {
FREE(data);
data = NULL;
}
size = nBits;
if (!data)
data = reinterpret_cast<uint32_t *>(CALLOC((size + 31) / 32, 4));
if (zero)
memset(data, 0, (size + 7) / 8);
else
data[(size + 31) / 32 - 1] = 0; // clear unused bits (e.g. for popCount)
return data;
}
unsigned int BitSet::popCount() const
{
unsigned int count = 0;
for (unsigned int i = 0; i < (size + 31) / 32; ++i)
if (data[i])
count += util_bitcount(data[i]);
return count;
}
void BitSet::fill(uint32_t val)
{
unsigned int i;
for (i = 0; i < (size + 31) / 32; ++i)
data[i] = val;
if (val)
data[i] &= ~(0xffffffff << (size % 32)); // BE ?
}
void BitSet::setOr(BitSet *pA, BitSet *pB)
{
if (!pB) {
*this = *pA;
} else {
for (unsigned int i = 0; i < (size + 31) / 32; ++i)
data[i] = pA->data[i] | pB->data[i];
}
}
void BitSet::print() const
{
unsigned int n = 0;
INFO("BitSet of size %u:\n", size);
for (unsigned int i = 0; i < (size + 31) / 32; ++i) {
uint32_t bits = data[i];
while (bits) {
int pos = ffs(bits) - 1;
bits &= ~(1 << pos);
INFO(" %i", i * 32 + pos);
++n;
if ((n % 16) == 0)
INFO("\n");
}
}
if (n % 16)
INFO("\n");
}
} // namespace nv50_ir
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/app_switches.h"
#include "app/gfx/gl/gl_implementation.h"
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/test/test_server.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif
static const size_t kPathBufSize = 2048;
using WebKit::WebScriptController;
namespace {
// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;
void RemoveSharedMemoryFile(std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(UTF8ToWide(filename));
#endif
}
} // namespace
int main(int argc, char* argv[]) {
base::EnableInProcessStackDumping();
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
scoped_ptr<base::Environment> env(base::Environment::Create());
bool suppress_error_dialogs = (
env->HasVar("CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
bool classic_theme =
parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#if defined(OS_WIN)
bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
// Stop compiler warnings about unused variables.
ux_theme = ux_theme;
#endif
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
bool allow_external_pages =
parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path =
parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(cache_path, cache_mode, layout_test_mode);
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
TestShellWebTheme::Engine engine;
#endif
if (classic_theme)
platform.SelectUnifiedTheme();
#if defined(OS_WIN)
if (generic_theme)
test_shell_webkit_init.SetThemeEngine(&engine);
#endif
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::string timeout_str = parsed_command_line.GetSwitchValueASCII(
test_shell::kTestShellTimeOut);
int timeout_ms;
base::StringToInt(timeout_str, &timeout_ms);
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Unless specifically requested otherwise, default to OSMesa for GL.
if (!parsed_command_line.HasSwitch(switches::kUseGL))
gfx::InitializeGLBindings(gfx::kGLImplementationOSMesaGL);
// Treat the first argument as the initial URL to open.
GURL starting_url;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("webkit");
path = path.AppendASCII("data");
path = path.AppendASCII("test_shell");
path = path.AppendASCII("index.html");
starting_url = net::FilePathToFileURL(path);
}
const std::vector<CommandLine::StringType>& args = parsed_command_line.args();
if (args.size() > 0) {
GURL url(args[0]);
if (url.is_valid()) {
starting_url = url;
} else {
// Treat as a relative file path.
FilePath path = FilePath(args[0]);
file_util::AbsolutePath(&path);
starting_url = net::FilePathToFileURL(path);
}
}
std::string js_flags =
parsed_command_line.GetSwitchValueASCII(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += " --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebScriptController::registerExtension(
extensions_v8::ProfilerExtension::Get());
}
if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
WebScriptController::registerExtension(
extensions_v8::HeapProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
std::string stats_filename = kStatsFilePrefix +
base::Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
RemoveSharedMemoryFile(stats_filename);
StatsTable *table = new StatsTable(stats_filename,
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(starting_url, &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebScriptController::registerExtension(
extensions_v8::PlaybackExtension::Get());
}
shell->Show(WebKit::WebNavigationPolicyNewWindow);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValuePath(
test_shell::kDumpPixels);
if (params.pixel_file_name.empty()) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (!starting_url.is_valid()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
// Set the current path to the directory that contains the test
// files. This is because certain test file may use the relative
// path.
GURL test_url(params.test_url);
FilePath test_file_path;
net::FileURLToFilePath(test_url, &test_file_path);
file_util::SetCurrentDirectory(test_file_path.DirName());
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = starting_url.spec();
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
// Flush any remaining messages before we kill ourselves.
// http://code.google.com/p/chromium/issues/detail?id=9500
MessageLoop::current()->RunAllPending();
} else {
MessageLoop::current()->Run();
}
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
RemoveSharedMemoryFile(stats_filename);
return 0;
}
<commit_msg>OS X - always use "classic theme" when running Layout tests<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/app_switches.h"
#include "app/gfx/gl/gl_implementation.h"
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/test/test_server.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif
static const size_t kPathBufSize = 2048;
using WebKit::WebScriptController;
namespace {
// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;
void RemoveSharedMemoryFile(std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(UTF8ToWide(filename));
#endif
}
} // namespace
int main(int argc, char* argv[]) {
base::EnableInProcessStackDumping();
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
scoped_ptr<base::Environment> env(base::Environment::Create());
bool suppress_error_dialogs = (
env->HasVar("CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
#if defined(OS_MACOSX)
// The "classic theme" flag is meaningless on OS X. But there is a bunch
// of code that sets up the environment for running pixel tests that only
// runs if it's set to true.
bool classic_theme = true;
#else
bool classic_theme =
parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#endif // !OS_MACOSX
#if defined(OS_WIN)
bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
// Stop compiler warnings about unused variables.
ux_theme = ux_theme;
#endif
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
bool allow_external_pages =
parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path =
parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(cache_path, cache_mode, layout_test_mode);
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
TestShellWebTheme::Engine engine;
#endif
if (classic_theme)
platform.SelectUnifiedTheme();
#if defined(OS_WIN)
if (generic_theme)
test_shell_webkit_init.SetThemeEngine(&engine);
#endif
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::string timeout_str = parsed_command_line.GetSwitchValueASCII(
test_shell::kTestShellTimeOut);
int timeout_ms;
base::StringToInt(timeout_str, &timeout_ms);
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Unless specifically requested otherwise, default to OSMesa for GL.
if (!parsed_command_line.HasSwitch(switches::kUseGL))
gfx::InitializeGLBindings(gfx::kGLImplementationOSMesaGL);
// Treat the first argument as the initial URL to open.
GURL starting_url;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("webkit");
path = path.AppendASCII("data");
path = path.AppendASCII("test_shell");
path = path.AppendASCII("index.html");
starting_url = net::FilePathToFileURL(path);
}
const std::vector<CommandLine::StringType>& args = parsed_command_line.args();
if (args.size() > 0) {
GURL url(args[0]);
if (url.is_valid()) {
starting_url = url;
} else {
// Treat as a relative file path.
FilePath path = FilePath(args[0]);
file_util::AbsolutePath(&path);
starting_url = net::FilePathToFileURL(path);
}
}
std::string js_flags =
parsed_command_line.GetSwitchValueASCII(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += " --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebScriptController::registerExtension(
extensions_v8::ProfilerExtension::Get());
}
if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
WebScriptController::registerExtension(
extensions_v8::HeapProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
std::string stats_filename = kStatsFilePrefix +
base::Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
RemoveSharedMemoryFile(stats_filename);
StatsTable *table = new StatsTable(stats_filename,
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(starting_url, &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebScriptController::registerExtension(
extensions_v8::PlaybackExtension::Get());
}
shell->Show(WebKit::WebNavigationPolicyNewWindow);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValuePath(
test_shell::kDumpPixels);
if (params.pixel_file_name.empty()) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (!starting_url.is_valid()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
// Set the current path to the directory that contains the test
// files. This is because certain test file may use the relative
// path.
GURL test_url(params.test_url);
FilePath test_file_path;
net::FileURLToFilePath(test_url, &test_file_path);
file_util::SetCurrentDirectory(test_file_path.DirName());
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = starting_url.spec();
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
// Flush any remaining messages before we kill ourselves.
// http://code.google.com/p/chromium/issues/detail?id=9500
MessageLoop::current()->RunAllPending();
} else {
MessageLoop::current()->Run();
}
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
RemoveSharedMemoryFile(stats_filename);
return 0;
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Various sanity tests with exceptions:
// - no memory leak when a custom scalar type trow an exceptions
// - todo: complete the list of tests!
#define EIGEN_STACK_ALLOCATION_LIMIT 100000000
#include "main.h"
struct my_exception
{
my_exception() {}
~my_exception() {}
};
class ScalarWithExceptions
{
public:
ScalarWithExceptions() { init(); }
ScalarWithExceptions(const float& _v) { init(); *v = _v; }
ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); }
~ScalarWithExceptions() {
delete v;
instances--;
}
void init() {
v = new float;
instances++;
}
ScalarWithExceptions operator+(const ScalarWithExceptions& other) const
{
countdown--;
if(countdown<=0)
throw my_exception();
return ScalarWithExceptions(*v+*other.v);
}
ScalarWithExceptions operator-(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions(*v-*other.v); }
ScalarWithExceptions operator*(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions((*v)*(*other.v)); }
ScalarWithExceptions& operator+=(const ScalarWithExceptions& other)
{ *v+=*other.v; return *this; }
ScalarWithExceptions& operator-=(const ScalarWithExceptions& other)
{ *v-=*other.v; return *this; }
ScalarWithExceptions& operator=(const ScalarWithExceptions& other)
{ *v = *(other.v); return *this; }
bool operator==(const ScalarWithExceptions& other) const
{ return *v==*other.v; }
bool operator!=(const ScalarWithExceptions& other) const
{ return *v!=*other.v; }
float* v;
static int instances;
static int countdown;
};
int ScalarWithExceptions::instances = 0;
int ScalarWithExceptions::countdown = 0;
#define CHECK_MEMLEAK(OP) { \
ScalarWithExceptions::countdown = 100; \
int before = ScalarWithExceptions::instances; \
bool exception_thrown = false; \
try { OP; } \
catch (my_exception) { \
exception_thrown = true; \
VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \
} \
VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \
}
void memoryleak()
{
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType;
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType;
{
int n = 50;
VectorType v0(n), v1(n);
MatrixType m0(n,n), m1(n,n), m2(n,n);
v0.setOnes(); v1.setOnes();
m0.setOnes(); m1.setOnes(); m2.setOnes();
CHECK_MEMLEAK(v0 = m0 * m1 * v1);
CHECK_MEMLEAK(m2 = m0 * m1 * m2);
CHECK_MEMLEAK((v0+v1).dot(v0+v1));
}
VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \
}
void test_exceptions()
{
CALL_SUBTEST( memoryleak() );
}
<commit_msg>Add a few missing standard functions for ScalarWithExceptions type.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Various sanity tests with exceptions:
// - no memory leak when a custom scalar type trow an exceptions
// - todo: complete the list of tests!
#define EIGEN_STACK_ALLOCATION_LIMIT 100000000
#include "main.h"
struct my_exception
{
my_exception() {}
~my_exception() {}
};
class ScalarWithExceptions
{
public:
ScalarWithExceptions() { init(); }
ScalarWithExceptions(const float& _v) { init(); *v = _v; }
ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); }
~ScalarWithExceptions() {
delete v;
instances--;
}
void init() {
v = new float;
instances++;
}
ScalarWithExceptions operator+(const ScalarWithExceptions& other) const
{
countdown--;
if(countdown<=0)
throw my_exception();
return ScalarWithExceptions(*v+*other.v);
}
ScalarWithExceptions operator-(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions(*v-*other.v); }
ScalarWithExceptions operator*(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions((*v)*(*other.v)); }
ScalarWithExceptions& operator+=(const ScalarWithExceptions& other)
{ *v+=*other.v; return *this; }
ScalarWithExceptions& operator-=(const ScalarWithExceptions& other)
{ *v-=*other.v; return *this; }
ScalarWithExceptions& operator=(const ScalarWithExceptions& other)
{ *v = *(other.v); return *this; }
bool operator==(const ScalarWithExceptions& other) const
{ return *v==*other.v; }
bool operator!=(const ScalarWithExceptions& other) const
{ return *v!=*other.v; }
float* v;
static int instances;
static int countdown;
};
ScalarWithExceptions real(const ScalarWithExceptions &x) { return x; }
ScalarWithExceptions imag(const ScalarWithExceptions & ) { return 0; }
ScalarWithExceptions conj(const ScalarWithExceptions &x) { return x; }
int ScalarWithExceptions::instances = 0;
int ScalarWithExceptions::countdown = 0;
#define CHECK_MEMLEAK(OP) { \
ScalarWithExceptions::countdown = 100; \
int before = ScalarWithExceptions::instances; \
bool exception_thrown = false; \
try { OP; } \
catch (my_exception) { \
exception_thrown = true; \
VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \
} \
VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \
}
void memoryleak()
{
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType;
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType;
{
int n = 50;
VectorType v0(n), v1(n);
MatrixType m0(n,n), m1(n,n), m2(n,n);
v0.setOnes(); v1.setOnes();
m0.setOnes(); m1.setOnes(); m2.setOnes();
CHECK_MEMLEAK(v0 = m0 * m1 * v1);
CHECK_MEMLEAK(m2 = m0 * m1 * m2);
CHECK_MEMLEAK((v0+v1).dot(v0+v1));
}
VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \
}
void test_exceptions()
{
CALL_SUBTEST( memoryleak() );
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
using namespace std;
using namespace cv;
void defaultDistribs( vector<Mat>& means, vector<Mat>& covs )
{
float mp0[] = {0.0f, 0.0f}, cp0[] = {0.67f, 0.0f, 0.0f, 0.67f};
float mp1[] = {5.0f, 0.0f}, cp1[] = {1.0f, 0.0f, 0.0f, 1.0f};
float mp2[] = {1.0f, 5.0f}, cp2[] = {1.0f, 0.0f, 0.0f, 1.0f};
Mat m0( 1, 2, CV_32FC1, mp0 ), c0( 2, 2, CV_32FC1, cp0 );
Mat m1( 1, 2, CV_32FC1, mp1 ), c1( 2, 2, CV_32FC1, cp1 );
Mat m2( 1, 2, CV_32FC1, mp2 ), c2( 2, 2, CV_32FC1, cp2 );
means.resize(3), covs.resize(3);
m0.copyTo(means[0]), c0.copyTo(covs[0]);
m1.copyTo(means[1]), c1.copyTo(covs[1]);
m2.copyTo(means[2]), c2.copyTo(covs[2]);
}
// generate points sets by normal distributions
void generateData( Mat& data, Mat& labels, const vector<int>& sizes, const vector<Mat>& means, const vector<Mat>& covs, int labelType )
{
vector<int>::const_iterator sit = sizes.begin();
int total = 0;
for( ; sit != sizes.end(); ++sit )
total += *sit;
assert( means.size() == sizes.size() && covs.size() == sizes.size() );
assert( !data.empty() && data.rows == total );
assert( data.type() == CV_32FC1 );
labels.create( data.rows, 1, labelType );
randn( data, Scalar::all(0.0), Scalar::all(1.0) );
vector<Mat>::const_iterator mit = means.begin(), cit = covs.begin();
int bi, ei = 0;
sit = sizes.begin();
for( int p = 0, l = 0; sit != sizes.end(); ++sit, ++mit, ++cit, l++ )
{
bi = ei;
ei = bi + *sit;
assert( mit->rows == 1 && mit->cols == data.cols );
assert( cit->rows == data.cols && cit->cols == data.cols );
for( int i = bi; i < ei; i++, p++ )
{
Mat r(1, data.cols, CV_32FC1, data.ptr<float>(i));
r = r * (*cit) + *mit;
if( labelType == CV_32FC1 )
labels.at<float>(p, 0) = (float)l;
else
labels.at<int>(p, 0) = l;
}
}
}
int maxIdx( const vector<int>& count )
{
int idx = -1;
int maxVal = -1;
vector<int>::const_iterator it = count.begin();
for( int i = 0; it != count.end(); ++it, i++ )
{
if( *it > maxVal)
{
maxVal = *it;
idx = i;
}
}
assert( idx >= 0);
return idx;
}
bool getLabelsMap( const Mat& labels, const vector<int>& sizes, vector<int>& labelsMap )
{
int total = 0, setCount = (int)sizes.size();
vector<int>::const_iterator sit = sizes.begin();
for( ; sit != sizes.end(); ++sit )
total += *sit;
assert( !labels.empty() );
assert( labels.rows == total && labels.cols == 1 );
assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 );
bool isFlt = labels.type() == CV_32FC1;
labelsMap.resize(setCount);
vector<int>::iterator lmit = labelsMap.begin();
vector<bool> buzy(setCount, false);
int bi, ei = 0;
for( sit = sizes.begin(); sit != sizes.end(); ++sit, ++lmit )
{
vector<int> count( setCount, 0 );
bi = ei;
ei = bi + *sit;
if( isFlt )
{
for( int i = bi; i < ei; i++ )
count[(int)labels.at<float>(i, 0)]++;
}
else
{
for( int i = bi; i < ei; i++ )
count[labels.at<int>(i, 0)]++;
}
*lmit = maxIdx( count );
if( buzy[*lmit] )
return false;
buzy[*lmit] = true;
}
return true;
}
float calcErr( const Mat& labels, const Mat& origLabels, const vector<int>& sizes, bool labelsEquivalent = true )
{
int err = 0;
assert( !labels.empty() && !origLabels.empty() );
assert( labels.cols == 1 && origLabels.cols == 1 );
assert( labels.rows == origLabels.rows );
assert( labels.type() == origLabels.type() );
assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 );
vector<int> labelsMap;
bool isFlt = labels.type() == CV_32FC1;
if( !labelsEquivalent )
{
getLabelsMap( labels, sizes, labelsMap );
for( int i = 0; i < labels.rows; i++ )
if( isFlt )
err += labels.at<float>(i, 0) != labelsMap[(int)origLabels.at<float>(i, 0)];
else
err += labels.at<int>(i, 0) != labelsMap[origLabels.at<int>(i, 0)];
}
else
{
for( int i = 0; i < labels.rows; i++ )
if( isFlt )
err += labels.at<float>(i, 0) != origLabels.at<float>(i, 0);
else
err += labels.at<int>(i, 0) != origLabels.at<int>(i, 0);
}
return (float)err / (float)labels.rows;
}
//--------------------------------------------------------------------------------------------
class CV_KMeansTest : public cvtest::BaseTest {
public:
CV_KMeansTest() {}
protected:
virtual void run( int start_from );
};
void CV_KMeansTest::run( int /*start_from*/ )
{
const int iters = 100;
int sizesArr[] = { 5000, 7000, 8000 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
Mat data( pointsCount, 2, CV_32FC1 ), labels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( data, labels, sizes, means, covs, CV_32SC1 );
int code = cvtest::TS::OK;
Mat bestLabels;
// 1. flag==KMEANS_PP_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_PP_CENTERS, noArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// 2. flag==KMEANS_RANDOM_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_RANDOM_CENTERS, noArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// 3. flag==KMEANS_USE_INITIAL_LABELS
labels.copyTo( bestLabels );
RNG rng;
for( int i = 0; i < 0.5f * pointsCount; i++ )
bestLabels.at<int>( rng.next() % pointsCount, 0 ) = rng.next() % 3;
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_USE_INITIAL_LABELS, noArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
//--------------------------------------------------------------------------------------------
class CV_KNearestTest : public cvtest::BaseTest {
public:
CV_KNearestTest() {}
protected:
virtual void run( int start_from );
};
void CV_KNearestTest::run( int /*start_from*/ )
{
int sizesArr[] = { 500, 700, 800 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
// train data
Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( trainData, trainLabels, sizes, means, covs, CV_32FC1 );
// test data
Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels;
generateData( testData, testLabels, sizes, means, covs, CV_32FC1 );
int code = cvtest::TS::OK;
KNearest knearest;
knearest.train( trainData, trainLabels );
knearest.find_nearest( testData, 4, &bestLabels );
if( calcErr( bestLabels, testLabels, sizes, true ) > 0.01f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy on test data" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
//--------------------------------------------------------------------------------------------
class CV_EMTest : public cvtest::BaseTest {
public:
CV_EMTest() {}
protected:
virtual void run( int start_from );
};
void CV_EMTest::run( int /*start_from*/ )
{
int sizesArr[] = { 5000, 7000, 8000 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
// train data
Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( trainData, trainLabels, sizes, means, covs, CV_32SC1 );
// test data
Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels;
generateData( testData, testLabels, sizes, means, covs, CV_32SC1 );
int code = cvtest::TS::OK;
ExpectationMaximization em;
CvEMParams params;
params.nclusters = 3;
em.train( trainData, Mat(), params, &bestLabels );
// check train error
if( calcErr( bestLabels, trainLabels, sizes, true ) > 0.002f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy on train data" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// check test error
bestLabels.create( testData.rows, 1, CV_32SC1 );
for( int i = 0; i < testData.rows; i++ )
{
Mat sample( 1, testData.cols, CV_32FC1, testData.ptr<float>(i));
bestLabels.at<int>(i,0) = (int)em.predict( sample, 0 );
}
if( calcErr( bestLabels, testLabels, sizes, true ) > 0.005f )
{
ts->printf( cvtest::TS::LOG, "bad accuracy on test data" );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
TEST(ML_KMeans, accuracy) { CV_KMeansTest test; test.safe_run(); }
TEST(ML_KNearest, accuracy) { CV_KNearestTest test; test.safe_run(); }
TEST(ML_EMTest, accuracy) { CV_EMTest test; test.safe_run(); }
<commit_msg>fixed em test<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
using namespace std;
using namespace cv;
void defaultDistribs( vector<Mat>& means, vector<Mat>& covs )
{
float mp0[] = {0.0f, 0.0f}, cp0[] = {0.67f, 0.0f, 0.0f, 0.67f};
float mp1[] = {5.0f, 0.0f}, cp1[] = {1.0f, 0.0f, 0.0f, 1.0f};
float mp2[] = {1.0f, 5.0f}, cp2[] = {1.0f, 0.0f, 0.0f, 1.0f};
Mat m0( 1, 2, CV_32FC1, mp0 ), c0( 2, 2, CV_32FC1, cp0 );
Mat m1( 1, 2, CV_32FC1, mp1 ), c1( 2, 2, CV_32FC1, cp1 );
Mat m2( 1, 2, CV_32FC1, mp2 ), c2( 2, 2, CV_32FC1, cp2 );
means.resize(3), covs.resize(3);
m0.copyTo(means[0]), c0.copyTo(covs[0]);
m1.copyTo(means[1]), c1.copyTo(covs[1]);
m2.copyTo(means[2]), c2.copyTo(covs[2]);
}
// generate points sets by normal distributions
void generateData( Mat& data, Mat& labels, const vector<int>& sizes, const vector<Mat>& means, const vector<Mat>& covs, int labelType )
{
vector<int>::const_iterator sit = sizes.begin();
int total = 0;
for( ; sit != sizes.end(); ++sit )
total += *sit;
assert( means.size() == sizes.size() && covs.size() == sizes.size() );
assert( !data.empty() && data.rows == total );
assert( data.type() == CV_32FC1 );
labels.create( data.rows, 1, labelType );
randn( data, Scalar::all(0.0), Scalar::all(1.0) );
vector<Mat>::const_iterator mit = means.begin(), cit = covs.begin();
int bi, ei = 0;
sit = sizes.begin();
for( int p = 0, l = 0; sit != sizes.end(); ++sit, ++mit, ++cit, l++ )
{
bi = ei;
ei = bi + *sit;
assert( mit->rows == 1 && mit->cols == data.cols );
assert( cit->rows == data.cols && cit->cols == data.cols );
for( int i = bi; i < ei; i++, p++ )
{
Mat r(1, data.cols, CV_32FC1, data.ptr<float>(i));
r = r * (*cit) + *mit;
if( labelType == CV_32FC1 )
labels.at<float>(p, 0) = (float)l;
else if( labelType == CV_32SC1 )
labels.at<int>(p, 0) = l;
else
CV_DbgAssert(0);
}
}
}
int maxIdx( const vector<int>& count )
{
int idx = -1;
int maxVal = -1;
vector<int>::const_iterator it = count.begin();
for( int i = 0; it != count.end(); ++it, i++ )
{
if( *it > maxVal)
{
maxVal = *it;
idx = i;
}
}
assert( idx >= 0);
return idx;
}
bool getLabelsMap( const Mat& labels, const vector<int>& sizes, vector<int>& labelsMap )
{
int total = 0, setCount = (int)sizes.size();
vector<int>::const_iterator sit = sizes.begin();
for( ; sit != sizes.end(); ++sit )
total += *sit;
assert( !labels.empty() );
assert( labels.rows == total && labels.cols == 1 );
assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 );
bool isFlt = labels.type() == CV_32FC1;
labelsMap.resize(setCount);
vector<int>::iterator lmit = labelsMap.begin();
vector<bool> buzy(setCount, false);
int bi, ei = 0;
for( sit = sizes.begin(); sit != sizes.end(); ++sit, ++lmit )
{
vector<int> count( setCount, 0 );
bi = ei;
ei = bi + *sit;
if( isFlt )
{
for( int i = bi; i < ei; i++ )
count[(int)labels.at<float>(i, 0)]++;
}
else
{
for( int i = bi; i < ei; i++ )
count[labels.at<int>(i, 0)]++;
}
*lmit = maxIdx( count );
if( buzy[*lmit] )
return false;
buzy[*lmit] = true;
}
return true;
}
float calcErr( const Mat& labels, const Mat& origLabels, const vector<int>& sizes, bool labelsEquivalent = true )
{
int err = 0;
assert( !labels.empty() && !origLabels.empty() );
assert( labels.cols == 1 && origLabels.cols == 1 );
assert( labels.rows == origLabels.rows );
assert( labels.type() == origLabels.type() );
assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 );
vector<int> labelsMap;
bool isFlt = labels.type() == CV_32FC1;
if( !labelsEquivalent )
{
getLabelsMap( labels, sizes, labelsMap );
for( int i = 0; i < labels.rows; i++ )
if( isFlt )
err += labels.at<float>(i, 0) != labelsMap[(int)origLabels.at<float>(i, 0)];
else
err += labels.at<int>(i, 0) != labelsMap[origLabels.at<int>(i, 0)];
}
else
{
for( int i = 0; i < labels.rows; i++ )
if( isFlt )
err += labels.at<float>(i, 0) != origLabels.at<float>(i, 0);
else
err += labels.at<int>(i, 0) != origLabels.at<int>(i, 0);
}
return (float)err / (float)labels.rows;
}
//--------------------------------------------------------------------------------------------
class CV_KMeansTest : public cvtest::BaseTest {
public:
CV_KMeansTest() {}
protected:
virtual void run( int start_from );
};
void CV_KMeansTest::run( int /*start_from*/ )
{
const int iters = 100;
int sizesArr[] = { 5000, 7000, 8000 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
Mat data( pointsCount, 2, CV_32FC1 ), labels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( data, labels, sizes, means, covs, CV_32SC1 );
int code = cvtest::TS::OK;
float err;
Mat bestLabels;
// 1. flag==KMEANS_PP_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_PP_CENTERS, noArray() );
err = calcErr( bestLabels, labels, sizes, false );
if( err > 0.01f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) if flag==KMEANS_PP_CENTERS.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// 2. flag==KMEANS_RANDOM_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_RANDOM_CENTERS, noArray() );
err = calcErr( bestLabels, labels, sizes, false );
if( err > 0.01f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) if flag==KMEANS_PP_CENTERS.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// 3. flag==KMEANS_USE_INITIAL_LABELS
labels.copyTo( bestLabels );
RNG rng;
for( int i = 0; i < 0.5f * pointsCount; i++ )
bestLabels.at<int>( rng.next() % pointsCount, 0 ) = rng.next() % 3;
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_USE_INITIAL_LABELS, noArray() );
err = calcErr( bestLabels, labels, sizes, false );
if( err > 0.01f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) if flag==KMEANS_PP_CENTERS.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
//--------------------------------------------------------------------------------------------
class CV_KNearestTest : public cvtest::BaseTest {
public:
CV_KNearestTest() {}
protected:
virtual void run( int start_from );
};
void CV_KNearestTest::run( int /*start_from*/ )
{
int sizesArr[] = { 500, 700, 800 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
// train data
Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( trainData, trainLabels, sizes, means, covs, CV_32FC1 );
// test data
Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels;
generateData( testData, testLabels, sizes, means, covs, CV_32FC1 );
int code = cvtest::TS::OK;
KNearest knearest;
knearest.train( trainData, trainLabels );
knearest.find_nearest( testData, 4, &bestLabels );
float err = calcErr( bestLabels, testLabels, sizes, true );
if( err > 0.01f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) on test data.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
//--------------------------------------------------------------------------------------------
class CV_EMTest : public cvtest::BaseTest {
public:
CV_EMTest() {}
protected:
virtual void run( int start_from );
};
void CV_EMTest::run( int /*start_from*/ )
{
int sizesArr[] = { 5000, 7000, 8000 };
int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2];
// train data
Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels;
vector<int> sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) );
vector<Mat> means, covs;
defaultDistribs( means, covs );
generateData( trainData, trainLabels, sizes, means, covs, CV_32SC1 );
// test data
Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels;
generateData( testData, testLabels, sizes, means, covs, CV_32SC1 );
int code = cvtest::TS::OK;
float err;
ExpectationMaximization em;
CvEMParams params;
params.nclusters = 3;
em.train( trainData, Mat(), params, &bestLabels );
// check train error
err = calcErr( bestLabels, trainLabels, sizes, false );
if( err > 0.002f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) on train data.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
// check test error
bestLabels.create( testData.rows, 1, CV_32SC1 );
for( int i = 0; i < testData.rows; i++ )
{
Mat sample( 1, testData.cols, CV_32FC1, testData.ptr<float>(i));
bestLabels.at<int>(i,0) = (int)em.predict( sample, 0 );
}
err = calcErr( bestLabels, testLabels, sizes, false );
if( err > 0.005f )
{
ts->printf( cvtest::TS::LOG, "Bad accuracy (%f) on test data.\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY;
}
ts->set_failed_test_info( code );
}
TEST(ML_KMeans, accuracy) { CV_KMeansTest test; test.safe_run(); }
TEST(ML_KNearest, accuracy) { CV_KNearestTest test; test.safe_run(); }
TEST(ML_EM, accuracy) { CV_EMTest test; test.safe_run(); }
<|endoftext|>
|
<commit_before>#include <assert.h>
#include <string.h>
#include <gcrypt.h>
#include <unistd.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#include "CEncrypt.h"
//https://gnupg.org/documentation/manuals/gcrypt/Working-with-cipher-handles.html#Working-with-cipher-handles
//https://gnupg.org/documentation/manuals/gcrypt/Key-Derivation.html#Key-Derivation
typedef struct
{
int32_t crc;
char magic[8];
uint16_t majorversion;
uint16_t minorversion;
uint8_t salt[32];
struct {
char username[128];
uint8_t key[32];
uint8_t enccheckbytes[32];
uint8_t checkbytes[32];
int32_t hashreps;
} user[4];
} TEncHeader;
void CEncrypt::PassToHash(const std::string &message, uint8_t salt[32], uint8_t passkey[32], int hashreps)
{
char *pass = getpass(message.c_str());
gpg_error_t ret = gcry_kdf_derive( pass, strlen(pass),
GCRY_KDF_PBKDF2, GCRY_MD_SHA256,
salt, 32, hashreps,
32, passkey);
memset(pass, 0, strlen(pass));
assert(ret == 0);
}
void CEncrypt::CreateEnc(int8_t *block)
{
printf("Create Encryption block\n");
uint8_t key[32];
gcry_randomize (key, 32, GCRY_STRONG_RANDOM);
TEncHeader *h = (TEncHeader*)block;
memset(h, 0, sizeof(blocksize));
h->majorversion = 1;
h->minorversion = 0;
strcpy(h->magic, "coverfs");
gcry_create_nonce (h->salt, 32);
h->user[0].hashreps = 1000;
strcpy(h->user[0].username, "poke");
gcry_create_nonce (h->user[0].enccheckbytes, 32);
uint8_t passkey[32];
PassToHash("Set Password for filesystem: ", h->salt, passkey, h->user[0].hashreps);
gpg_error_t ret;
gcry_cipher_hd_t hd;
ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0);
assert(ret == 0);
ret = gcry_cipher_setkey(hd, passkey, 32);
assert(ret == 0);
ret = gcry_cipher_encrypt (hd,
h->user[0].checkbytes, 32,
h->user[0].enccheckbytes, 32);
ret = gcry_cipher_encrypt (hd, h->user[0].key, 32, key, 32);
for(int i=0; i<32; i++) key[i] = 0x0;
gcry_cipher_close(hd);
gcry_md_hash_buffer(GCRY_MD_CRC32, &h->crc, (int8_t*)h+4, blocksize-4);
}
CEncrypt::CEncrypt(CAbstractBlockIO &bio)
{
assert(sizeof(TEncHeader) == 4+8+4+32+(128+32+32+32+4)*4);
assert(bio.blocksize >= 1024);
blocksize = bio.blocksize;
gpg_error_t ret;
ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
gcry_check_version (NULL);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
assert(gcry_md_get_algo_dlen (GCRY_MD_CRC32) == 4);
int8_t block[blocksize];
bio.Read(0, 1, block);
TEncHeader *h = (TEncHeader*)block;
if (strncmp(h->magic, "coverfs", 8) != 0)
{
CreateEnc(block);
bio.Write(0, 1, block);
}
int32_t crc;
gcry_md_hash_buffer(GCRY_MD_CRC32, &crc, (int8_t*)h+4, blocksize-4);
assert(h->crc == crc);
assert(h->majorversion == 1);
assert(h->minorversion == 0);
uint8_t passkey[32];
PassToHash("Password: ", h->salt, passkey, h->user[0].hashreps);
gcry_cipher_hd_t hd;
ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0);
assert(ret == 0);
ret = gcry_cipher_setkey(hd, passkey, 32);
assert(ret == 0);
uint8_t check[32];
ret = gcry_cipher_encrypt(hd, check, 32, h->user[0].enccheckbytes, 32);
assert(ret == 0);
if (memcmp(check, h->user[0].checkbytes, 32) != 0)
{
fprintf(stderr, "Error: Cannot decrypt filesystem. Did you type the right password?\n");
exit(1);
}
uint8_t key[32];
ret = gcry_cipher_decrypt(hd, key, 32, h->user[0].key, 32);
assert(ret == 0);
gcry_cipher_close(hd);
for(int i=0; i<4; i++)
{
ret = gcry_cipher_open(&hdblock[i], GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0);
assert(ret == 0);
ret = gcry_cipher_setkey(hdblock[i], key, 32);
assert(ret == 0);
}
memset(key, 0, 32);
memset(block, 0, blocksize);
}
void CEncrypt::Decrypt(const int blockidx, int8_t *d)
{
//printf("Decrypt blockidx %i\n", blockidx);
int32_t iv[4];
iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know this is bad
if (blockidx == 0) return;
for(int i=0; i<4; i++)
{
if (!mutex[i].try_lock()) continue;
gcry_cipher_setiv (hdblock[i], iv, 16);
gpg_error_t ret = gcry_cipher_decrypt(hdblock[i], d, blocksize, NULL, 0);
assert(ret == 0);
mutex[i].unlock();
return;
}
// all cipher handles are locked. Wait ...
mutex[0].lock();
gcry_cipher_setiv (hdblock[0], iv, 16);
gpg_error_t ret = gcry_cipher_decrypt(hdblock[0], d, blocksize, NULL, 0);
assert(ret == 0);
mutex[0].unlock();
}
void CEncrypt::Encrypt(const int blockidx, int8_t* d)
{
//printf("Encrypt blockidx %i\n", blockidx);
int32_t iv[4];
iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know, this is bad
if (blockidx == 0) return;
for(int i=0; i<4; i++)
{
if (!mutex[i].try_lock()) continue;
gcry_cipher_setiv (hdblock[i], iv, 16);
gpg_error_t ret = gcry_cipher_encrypt(hdblock[i], d, blocksize, 0, 0);
assert(ret == 0);
mutex[i].unlock();
return;
}
// all cipher handles are locked. Wait ...
mutex[1].lock();
gcry_cipher_setiv (hdblock[1], iv, 16);
gpg_error_t ret = gcry_cipher_encrypt(hdblock[1], d, blocksize, 0, 0);
assert(ret == 0);
mutex[1].unlock();
}
<commit_msg>Encrypt: Change to scrypt, prepare for XTS, better error handling<commit_after>#include <assert.h>
#include <string.h>
#include <gcrypt.h>
#include <unistd.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#include "CEncrypt.h"
//https://gnupg.org/documentation/manuals/gcrypt/Working-with-cipher-handles.html#Working-with-cipher-handles
//https://gnupg.org/documentation/manuals/gcrypt/Key-Derivation.html#Key-Derivation
typedef struct
{
int32_t crc;
char magic[8];
uint16_t majorversion;
uint16_t minorversion;
uint8_t salt[32];
struct {
char username[128];
uint8_t key[64];
uint8_t enccheckbytes[64];
uint8_t checkbytes[64];
int32_t hashreps;
} user[4];
} TEncHeader;
void GCryptCheckError(const char *function, gpg_error_t ret)
{
if (ret)
{
fprintf (stderr, "%s: Failure: %s/%s\n",
function,
gcry_strsource (ret),
gcry_strerror (ret));
exit(1);
}
}
void CEncrypt::PassToHash(const std::string &message, uint8_t salt[32], uint8_t passkey[64], int hashreps)
{
char *pass = getpass(message.c_str());
gpg_error_t ret = gcry_kdf_derive(
pass, strlen(pass),
GCRY_KDF_SCRYPT,
GCRY_MD_SHA256,
salt, 32,
hashreps,
64, passkey);
memset(pass, 0, strlen(pass));
GCryptCheckError("getpass", ret);
}
void CEncrypt::CreateEnc(int8_t *block)
{
printf("Create Encryption block\n");
uint8_t key[64];
gcry_randomize (key, 64, GCRY_STRONG_RANDOM);
TEncHeader *h = (TEncHeader*)block;
memset(h, 0, sizeof(blocksize));
h->majorversion = 1;
h->minorversion = 0;
strcpy(h->magic, "coverfs");
gcry_create_nonce (h->salt, 32);
h->user[0].hashreps = 500;
strcpy(h->user[0].username, "poke");
gcry_create_nonce (h->user[0].enccheckbytes, 64);
uint8_t passkey[64];
PassToHash("Set Password for filesystem: ", h->salt, passkey, h->user[0].hashreps);
gpg_error_t ret;
gcry_cipher_hd_t hd;
ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0);
GCryptCheckError("gcry_cipher_open", ret);
ret = gcry_cipher_setkey(hd, passkey, 32);
GCryptCheckError("gcry_cipher_setkey", ret);
ret = gcry_cipher_encrypt (hd,
h->user[0].checkbytes, 64,
h->user[0].enccheckbytes, 64);
GCryptCheckError("gcry_cipher_encrypt", ret);
ret = gcry_cipher_encrypt (hd, h->user[0].key, 64, key, 64);
GCryptCheckError("gcry_cipher_encrypt", ret);
for(int i=0; i<64; i++) key[i] = 0x0;
gcry_cipher_close(hd);
gcry_md_hash_buffer(GCRY_MD_CRC32, &h->crc, (int8_t*)h+4, blocksize-4);
}
CEncrypt::CEncrypt(CAbstractBlockIO &bio)
{
assert(sizeof(TEncHeader) == 4+8+4+32+(128+64+64+64+4)*4);
assert(bio.blocksize >= 1024);
blocksize = bio.blocksize;
gpg_error_t ret;
const char* gcryptversion = gcry_check_version (GCRYPT_VERSION);
if (gcryptversion == NULL)
{
fprintf(stderr, "Error: gcrypt version too old\n");
exit(1);
}
printf("gcrypt version %s\n", gcryptversion);
ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
GCryptCheckError("gcry_control", ret);
gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
assert(gcry_md_get_algo_dlen (GCRY_MD_CRC32) == 4);
int8_t block[blocksize];
bio.Read(0, 1, block);
TEncHeader *h = (TEncHeader*)block;
if (strncmp(h->magic, "coverfs", 8) != 0)
{
CreateEnc(block);
bio.Write(0, 1, block);
}
int32_t crc;
gcry_md_hash_buffer(GCRY_MD_CRC32, &crc, (int8_t*)h+4, blocksize-4);
assert(h->crc == crc);
assert(h->majorversion == 1);
assert(h->minorversion == 0);
uint8_t passkey[64];
PassToHash("Password: ", h->salt, passkey, h->user[0].hashreps);
gcry_cipher_hd_t hd;
ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0);
GCryptCheckError("gcry_cipher_open", ret);
ret = gcry_cipher_setkey(hd, passkey, 32);
GCryptCheckError("gcry_cipher_setkey", ret);
uint8_t check[64];
ret = gcry_cipher_encrypt(hd, check, 64, h->user[0].enccheckbytes, 64);
GCryptCheckError("gcry_cipher_encrypt", ret);
if (memcmp(check, h->user[0].checkbytes, 64) != 0)
{
fprintf(stderr, "Error: Cannot decrypt filesystem. Did you type the right password?\n");
exit(1);
}
uint8_t key[64];
ret = gcry_cipher_decrypt(hd, key, 64, h->user[0].key, 64);
GCryptCheckError("gcry_cipher_decrypt", ret);
gcry_cipher_close(hd);
for(int i=0; i<4; i++)
{
ret = gcry_cipher_open(&hdblock[i], GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0);
GCryptCheckError("gcry_cipher_open", ret);
ret = gcry_cipher_setkey(hdblock[i], key, 32);
GCryptCheckError("gcry_cipher_setkey", ret);
}
memset(key, 0, 64);
memset(block, 0, blocksize);
}
void CEncrypt::Decrypt(const int blockidx, int8_t *d)
{
//printf("Decrypt blockidx %i\n", blockidx);
int32_t iv[4];
iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know this is bad
if (blockidx == 0) return;
for(int i=0; i<4; i++)
{
if (!mutex[i].try_lock()) continue;
gcry_cipher_setiv (hdblock[i], iv, 16);
gpg_error_t ret = gcry_cipher_decrypt(hdblock[i], d, blocksize, NULL, 0);
GCryptCheckError("gcry_cipher_decrypt", ret);
mutex[i].unlock();
return;
}
// all cipher handles are locked. Wait ...
mutex[0].lock();
gcry_cipher_setiv (hdblock[0], iv, 16);
gpg_error_t ret = gcry_cipher_decrypt(hdblock[0], d, blocksize, NULL, 0);
GCryptCheckError("gcry_cipher_decrypt", ret);
mutex[0].unlock();
}
void CEncrypt::Encrypt(const int blockidx, int8_t* d)
{
//printf("Encrypt blockidx %i\n", blockidx);
int32_t iv[4];
iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know, this is bad
if (blockidx == 0) return;
for(int i=0; i<4; i++)
{
if (!mutex[i].try_lock()) continue;
gcry_cipher_setiv (hdblock[i], iv, 16);
gpg_error_t ret = gcry_cipher_encrypt(hdblock[i], d, blocksize, 0, 0);
GCryptCheckError("gcry_cipher_encrypt", ret);
mutex[i].unlock();
return;
}
// all cipher handles are locked. Wait ...
mutex[1].lock();
gcry_cipher_setiv (hdblock[1], iv, 16);
gpg_error_t ret = gcry_cipher_encrypt(hdblock[1], d, blocksize, 0, 0);
GCryptCheckError("gcry_cipher_encrypt", ret);
mutex[1].unlock();
}
<|endoftext|>
|
<commit_before>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include "catch.hpp"
#include <gfx/Canvas.h>
#include <iostream>
#include <gfx/displays/GDisplayMaschineMk1.h>
#include <gfx/displays/GDisplayMaschineMk2.h>
#include <gfx/displays/GDisplayMaschineMikro.h>
namespace sl
{
namespace cabl
{
namespace test
{
namespace
{
bool matchColorForAllPixels(const Canvas& canvas_, Canvas::Color color_)
{
for (unsigned x = 0U; x < canvas_.width(); x++)
{
for (unsigned y = 0U; y < canvas_.height(); y++)
{
if (color_ != canvas_.pixel(x, y))
{
return false;
}
}
}
return true;
}
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: constructor", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
CHECK(c.width() == 16);
CHECK(c.height() == 5);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: convenience functions", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
c.black();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.invert();
CHECK(matchColorForAllPixels(c, Canvas::Color::White));
c.invert();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.white();
CHECK(matchColorForAllPixels(c, Canvas::Color::White));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: pixel functions", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
c.black();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::White);
CHECK_FALSE(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(50, 2, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 20, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::None);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: allocation types and displays", "[gfx/Canvas]")
{
std::string expected;
GDisplayMaschineMikro c_0;
c_0.black();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::Black));
c_0.invert();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::White));
c_0.invert();
c_0.white();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::White));
GDisplayMaschineMK1 c_1;
c_1.black();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::Black));
c_1.invert();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::White));
c_1.invert();
c_1.white();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::White));
GDisplayMaschineMK2 c_2;
c_2.black();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::Black));
c_2.invert();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::White));
c_2.invert();
c_2.white();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::White));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing rectangles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawRect(1, 1, 14, 7, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░██████████████░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░██████████████░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::White, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::Black, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░░░░░░░░░░░░░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░░░░░░░░░░░░░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::White, Canvas::Color::White);
c.drawFilledRect(5, 0, 6, 9, Canvas::Color::Invert, Canvas::Color::Invert);
c.drawFilledRect(0, 3, 16, 3, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n░░░░░██████░░░░░"
"\n░████░░░░░░████░"
"\n░████░░░░░░████░"
"\n█░░░░██████░░░░█"
"\n█░░░░██████░░░░█"
"\n█░░░░██████░░░░█"
"\n░████░░░░░░████░"
"\n░████░░░░░░████░"
"\n░░░░░██████░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawRectRounded(1, 1, 14, 7, 3, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░██████████░░░"
"\n░░█░░░░░░░░░░█░░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░░█░░░░░░░░░░█░░"
"\n░░░██████████░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRectRounded( 1, 1, 14, 7, 3, Canvas::Color::White, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░██████████░░░"
"\n░░████████████░░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░░████████████░░"
"\n░░░██████████░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.white();
c.drawFilledRectRounded( 2, 2, 12, 5, 3, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n████████████████"
"\n████████████████"
"\n███░░░░░░░░░░███"
"\n██░░░░░░░░░░░░██"
"\n██░░░░░░░░░░░░██"
"\n██░░░░░░░░░░░░██"
"\n███░░░░░░░░░░███"
"\n████████████████"
"\n████████████████";
//CHECK(c.string("░", "█") == expected);
//\todo Fix rendering of filled rounded rectangles
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing triangles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White);
expected = "\n████████████████"
"\n█░░░░░░░░░░░░██░"
"\n█░░░░░░░░░░██░░░"
"\n█░░░░░░░░██░░░░░"
"\n█░░░░░░██░░░░░░░"
"\n█░░░░██░░░░░░░░░"
"\n█░░██░░░░░░░░░░░"
"\n███░░░░░░░░░░░░░"
"\n█░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White, Canvas::Color::White);
expected = "\n████████████████"
"\n███████████████░"
"\n█████████████░░░"
"\n███████████░░░░░"
"\n█████████░░░░░░░"
"\n███████░░░░░░░░░"
"\n█████░░░░░░░░░░░"
"\n███░░░░░░░░░░░░░"
"\n█░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White, Canvas::Color::White);
c.drawFilledTriangle(15, 8, 0, 0, 0, 8, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n░███████████████"
"\n░░█████████████░"
"\n░░░░█████████░░░"
"\n░░░░░░█████░░░░░"
"\n░░░░░░░░█░░░░░░░"
"\n░░░░░░░███░░░░░░"
"\n░░░░░███████░░░░"
"\n░░░███████████░░"
"\n░███████████████";
CHECK(c.string("░", "█") == expected);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing circles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawCircle(8, 4, 4, Canvas::Color::White);
expected = "\n░░░░░░░███░░░░░░"
"\n░░░░░██░░░██░░░░"
"\n░░░░░█░░░░░█░░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░░█░░░░░█░░░░"
"\n░░░░░██░░░██░░░░"
"\n░░░░░░░███░░░░░░";
CHECK(c.string("░", "█") == expected);
c.white();
c.drawFilledCircle(8, 4, 4, Canvas::Color::Black, Canvas::Color::Black);
expected = "\n███████░░░██████"
"\n█████░░░░░░░████"
"\n█████░░░░░░░████"
"\n████░░░░░░░░░███"
"\n████░░░░░░░░░███"
"\n████░░░░░░░░░███"
"\n█████░░░░░░░████"
"\n█████░░░░░░░████"
"\n███████░░░██████";
CHECK(c.string("░", "█") == expected);
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<commit_msg>fixed wrong includes<commit_after>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include "catch.hpp"
#include <gfx/Canvas.h>
#include <iostream>
#include <gfx/displays/GDisplayMaschineMK1.h>
#include <gfx/displays/GDisplayMaschineMK2.h>
#include <gfx/displays/GDisplayMaschineMikro.h>
namespace sl
{
namespace cabl
{
namespace test
{
namespace
{
bool matchColorForAllPixels(const Canvas& canvas_, Canvas::Color color_)
{
for (unsigned x = 0U; x < canvas_.width(); x++)
{
for (unsigned y = 0U; y < canvas_.height(); y++)
{
if (color_ != canvas_.pixel(x, y))
{
return false;
}
}
}
return true;
}
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: constructor", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
CHECK(c.width() == 16);
CHECK(c.height() == 5);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: convenience functions", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
c.black();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.invert();
CHECK(matchColorForAllPixels(c, Canvas::Color::White));
c.invert();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.white();
CHECK(matchColorForAllPixels(c, Canvas::Color::White));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: pixel functions", "[gfx/Canvas]")
{
Canvas c(16, 5, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
c.black();
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::White);
CHECK_FALSE(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(50, 2, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 20, Canvas::Color::Black);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
c.setPixel(5, 2, Canvas::Color::None);
CHECK(matchColorForAllPixels(c, Canvas::Color::Black));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: allocation types and displays", "[gfx/Canvas]")
{
std::string expected;
GDisplayMaschineMikro c_0;
c_0.black();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::Black));
c_0.invert();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::White));
c_0.invert();
c_0.white();
CHECK(matchColorForAllPixels(c_0, Canvas::Color::White));
GDisplayMaschineMK1 c_1;
c_1.black();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::Black));
c_1.invert();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::White));
c_1.invert();
c_1.white();
CHECK(matchColorForAllPixels(c_1, Canvas::Color::White));
GDisplayMaschineMK2 c_2;
c_2.black();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::Black));
c_2.invert();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::White));
c_2.invert();
c_2.white();
CHECK(matchColorForAllPixels(c_2, Canvas::Color::White));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing rectangles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawRect(1, 1, 14, 7, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░██████████████░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░██████████████░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::White, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::Black, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░░░░░░░░░░░░░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░████████████░░"
"\n░░░░░░░░░░░░░░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRect(1, 1, 14, 7, Canvas::Color::White, Canvas::Color::White);
c.drawFilledRect(5, 0, 6, 9, Canvas::Color::Invert, Canvas::Color::Invert);
c.drawFilledRect(0, 3, 16, 3, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n░░░░░██████░░░░░"
"\n░████░░░░░░████░"
"\n░████░░░░░░████░"
"\n█░░░░██████░░░░█"
"\n█░░░░██████░░░░█"
"\n█░░░░██████░░░░█"
"\n░████░░░░░░████░"
"\n░████░░░░░░████░"
"\n░░░░░██████░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawRectRounded(1, 1, 14, 7, 3, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░██████████░░░"
"\n░░█░░░░░░░░░░█░░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░█░░░░░░░░░░░░█░"
"\n░░█░░░░░░░░░░█░░"
"\n░░░██████████░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledRectRounded( 1, 1, 14, 7, 3, Canvas::Color::White, Canvas::Color::White);
expected = "\n░░░░░░░░░░░░░░░░"
"\n░░░██████████░░░"
"\n░░████████████░░"
"\n░██████████████░"
"\n░██████████████░"
"\n░██████████████░"
"\n░░████████████░░"
"\n░░░██████████░░░"
"\n░░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.white();
c.drawFilledRectRounded( 2, 2, 12, 5, 3, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n████████████████"
"\n████████████████"
"\n███░░░░░░░░░░███"
"\n██░░░░░░░░░░░░██"
"\n██░░░░░░░░░░░░██"
"\n██░░░░░░░░░░░░██"
"\n███░░░░░░░░░░███"
"\n████████████████"
"\n████████████████";
//CHECK(c.string("░", "█") == expected);
//\todo Fix rendering of filled rounded rectangles
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing triangles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White);
expected = "\n████████████████"
"\n█░░░░░░░░░░░░██░"
"\n█░░░░░░░░░░██░░░"
"\n█░░░░░░░░██░░░░░"
"\n█░░░░░░██░░░░░░░"
"\n█░░░░██░░░░░░░░░"
"\n█░░██░░░░░░░░░░░"
"\n███░░░░░░░░░░░░░"
"\n█░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White, Canvas::Color::White);
expected = "\n████████████████"
"\n███████████████░"
"\n█████████████░░░"
"\n███████████░░░░░"
"\n█████████░░░░░░░"
"\n███████░░░░░░░░░"
"\n█████░░░░░░░░░░░"
"\n███░░░░░░░░░░░░░"
"\n█░░░░░░░░░░░░░░░";
CHECK(c.string("░", "█") == expected);
c.black();
c.drawFilledTriangle(0, 0, 15, 0, 0, 8, Canvas::Color::White, Canvas::Color::White);
c.drawFilledTriangle(15, 8, 0, 0, 0, 8, Canvas::Color::Invert, Canvas::Color::Invert);
expected = "\n░███████████████"
"\n░░█████████████░"
"\n░░░░█████████░░░"
"\n░░░░░░█████░░░░░"
"\n░░░░░░░░█░░░░░░░"
"\n░░░░░░░███░░░░░░"
"\n░░░░░███████░░░░"
"\n░░░███████████░░"
"\n░███████████████";
CHECK(c.string("░", "█") == expected);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: drawing circles", "[gfx/Canvas]")
{
Canvas c(16, 9, Canvas::Allocation::OneBytePacksOneRowOfEightPixels);
std::string expected;
c.black();
c.drawCircle(8, 4, 4, Canvas::Color::White);
expected = "\n░░░░░░░███░░░░░░"
"\n░░░░░██░░░██░░░░"
"\n░░░░░█░░░░░█░░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░█░░░░░░░█░░░"
"\n░░░░░█░░░░░█░░░░"
"\n░░░░░██░░░██░░░░"
"\n░░░░░░░███░░░░░░";
CHECK(c.string("░", "█") == expected);
c.white();
c.drawFilledCircle(8, 4, 4, Canvas::Color::Black, Canvas::Color::Black);
expected = "\n███████░░░██████"
"\n█████░░░░░░░████"
"\n█████░░░░░░░████"
"\n████░░░░░░░░░███"
"\n████░░░░░░░░░███"
"\n████░░░░░░░░░███"
"\n█████░░░░░░░████"
"\n█████░░░░░░░████"
"\n███████░░░██████";
CHECK(c.string("░", "█") == expected);
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<|endoftext|>
|
<commit_before>/*
Custom Google Test assertions.
Copyright (c) 2012-2014, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest-extra.h"
#if FMT_USE_FILE_DESCRIPTORS
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#else
# include <io.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
# define S_IRUSR _S_IREAD
# define S_IWUSR _S_IWRITE
#endif // _WIN32
// Retries the expression while it evaluates to -1 and error equals to EINTR.
#define FMT_RETRY(result, expression) \
do { \
result = (expression); \
} while (result == -1 && errno == EINTR)
FileDescriptor::FileDescriptor(const char *path, int oflag) {
int mode = S_IRUSR | S_IWUSR;
#ifdef _WIN32
fd_ = -1;
_sopen_s(&fd_, path, oflag, _SH_DENYNO, mode);
#else
FMT_RETRY(fd_, open(path, oflag, mode));
#endif
if (fd_ == -1)
fmt::ThrowSystemError(errno, "cannot open file {}") << path;
}
void FileDescriptor::close() {
if (fd_ == -1)
return;
// Don't need to retry close in case of EINTR.
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
if (::FMT_POSIX(close(fd_)) != 0)
fmt::ReportSystemError(errno, "cannot close file");
}
FileDescriptor FileDescriptor::dup(int fd) {
int new_fd = 0;
FMT_RETRY(new_fd, ::FMT_POSIX(dup(fd)));
if (new_fd == -1)
fmt::ThrowSystemError(errno, "cannot duplicate file descriptor {}") << fd;
return FileDescriptor(new_fd);
}
void FileDescriptor::dup2(int fd) {
int result = 0;
FMT_RETRY(result, ::FMT_POSIX(dup2(fd_, fd)));
if (result == -1) {
fmt::ThrowSystemError(errno,
"cannot duplicate file descriptor {} to {}") << fd_ << fd;
}
}
void FileDescriptor::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT(true) {
int result = 0;
FMT_RETRY(result, ::FMT_POSIX(dup2(fd_, fd)));
if (result == -1)
ec = ErrorCode(errno);
}
void FileDescriptor::pipe(FileDescriptor &read_fd, FileDescriptor &write_fd) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_fd.close();
write_fd.close();
int fds[2] = {};
#ifdef _WIN32
// Make the default pipe capacity same as on Linux 2.6.11+.
enum { DEFAULT_CAPACITY = 65536 };
int result = _pipe(fds, DEFAULT_CAPACITY, _O_BINARY);
#else
int result = ::pipe(fds);
#endif
if (result != 0)
fmt::ThrowSystemError(errno, "cannot create pipe");
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_fd = FileDescriptor(fds[0]);
write_fd = FileDescriptor(fds[1]);
}
OutputRedirector::OutputRedirector(FILE *file) : file_(file) {
if (std::fflush(file) != 0)
fmt::ThrowSystemError(errno, "cannot flush stream");
int fd = fileno(file);
saved_fd_ = FileDescriptor::dup(fd);
FileDescriptor write_fd;
FileDescriptor::pipe(read_fd_, write_fd);
write_fd.dup2(fd);
}
OutputRedirector::~OutputRedirector() {
if (std::fflush(file_) != 0)
fmt::ReportSystemError(errno, "cannot flush stream");
ErrorCode ec;
saved_fd_.dup2(fileno(file_), ec);
if (ec.get())
fmt::ReportSystemError(errno, "cannot restore output");
}
std::string OutputRedirector::Read() {
// Restore output.
if (std::fflush(file_) != 0)
fmt::ThrowSystemError(errno, "cannot flush stream");
saved_fd_.dup2(fileno(file_));
// TODO: move to FileDescriptor
enum { BUFFER_SIZE = 100 };
char buffer[BUFFER_SIZE];
ssize_t result = read(read_fd_.get(), buffer, BUFFER_SIZE);
if (result == -1)
fmt::ThrowSystemError(errno, "cannot read file");
buffer[std::min<ssize_t>(BUFFER_SIZE - 1, result)] = '\0';
return buffer;
}
// TODO: test EXPECT_STDOUT and EXPECT_STDERR
#endif // FMT_USE_FILE_DESCRIPTORS
<commit_msg>Define ssize_t on Windows.<commit_after>/*
Custom Google Test assertions.
Copyright (c) 2012-2014, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest-extra.h"
#if FMT_USE_FILE_DESCRIPTORS
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#else
# include <io.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
# define S_IRUSR _S_IREAD
# define S_IWUSR _S_IWRITE
// The read function is defined as returning int on Windows.
typedef int ssize_t;
#endif // _WIN32
// Retries the expression while it evaluates to -1 and error equals to EINTR.
#define FMT_RETRY(result, expression) \
do { \
result = (expression); \
} while (result == -1 && errno == EINTR)
FileDescriptor::FileDescriptor(const char *path, int oflag) {
int mode = S_IRUSR | S_IWUSR;
#ifdef _WIN32
fd_ = -1;
_sopen_s(&fd_, path, oflag, _SH_DENYNO, mode);
#else
FMT_RETRY(fd_, open(path, oflag, mode));
#endif
if (fd_ == -1)
fmt::ThrowSystemError(errno, "cannot open file {}") << path;
}
void FileDescriptor::close() {
if (fd_ == -1)
return;
// Don't need to retry close in case of EINTR.
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
if (::FMT_POSIX(close(fd_)) != 0)
fmt::ReportSystemError(errno, "cannot close file");
}
FileDescriptor FileDescriptor::dup(int fd) {
int new_fd = 0;
FMT_RETRY(new_fd, ::FMT_POSIX(dup(fd)));
if (new_fd == -1)
fmt::ThrowSystemError(errno, "cannot duplicate file descriptor {}") << fd;
return FileDescriptor(new_fd);
}
void FileDescriptor::dup2(int fd) {
int result = 0;
FMT_RETRY(result, ::FMT_POSIX(dup2(fd_, fd)));
if (result == -1) {
fmt::ThrowSystemError(errno,
"cannot duplicate file descriptor {} to {}") << fd_ << fd;
}
}
void FileDescriptor::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT(true) {
int result = 0;
FMT_RETRY(result, ::FMT_POSIX(dup2(fd_, fd)));
if (result == -1)
ec = ErrorCode(errno);
}
void FileDescriptor::pipe(FileDescriptor &read_fd, FileDescriptor &write_fd) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_fd.close();
write_fd.close();
int fds[2] = {};
#ifdef _WIN32
// Make the default pipe capacity same as on Linux 2.6.11+.
enum { DEFAULT_CAPACITY = 65536 };
int result = _pipe(fds, DEFAULT_CAPACITY, _O_BINARY);
#else
int result = ::pipe(fds);
#endif
if (result != 0)
fmt::ThrowSystemError(errno, "cannot create pipe");
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_fd = FileDescriptor(fds[0]);
write_fd = FileDescriptor(fds[1]);
}
OutputRedirector::OutputRedirector(FILE *file) : file_(file) {
if (std::fflush(file) != 0)
fmt::ThrowSystemError(errno, "cannot flush stream");
int fd = fileno(file);
saved_fd_ = FileDescriptor::dup(fd);
FileDescriptor write_fd;
FileDescriptor::pipe(read_fd_, write_fd);
write_fd.dup2(fd);
}
OutputRedirector::~OutputRedirector() {
if (std::fflush(file_) != 0)
fmt::ReportSystemError(errno, "cannot flush stream");
ErrorCode ec;
saved_fd_.dup2(fileno(file_), ec);
if (ec.get())
fmt::ReportSystemError(errno, "cannot restore output");
}
std::string OutputRedirector::Read() {
// Restore output.
if (std::fflush(file_) != 0)
fmt::ThrowSystemError(errno, "cannot flush stream");
saved_fd_.dup2(fileno(file_));
// TODO: move to FileDescriptor
enum { BUFFER_SIZE = 100 };
char buffer[BUFFER_SIZE];
ssize_t result = read(read_fd_.get(), buffer, BUFFER_SIZE);
if (result == -1)
fmt::ThrowSystemError(errno, "cannot read file");
buffer[std::min<ssize_t>(BUFFER_SIZE - 1, result)] = '\0';
return buffer;
}
// TODO: test EXPECT_STDOUT and EXPECT_STDERR
#endif // FMT_USE_FILE_DESCRIPTORS
<|endoftext|>
|
<commit_before><?hh
namespace Hackdinium\Cli;
use Aura\Cli\CliFactory;
use Aura\Cli\Context;
use Aura\Cli\Status;
use Hackdinium\Kernel;
use Hackdinium\Server;
class Shell {
const ARG_KEY = 1;
const ARG_MODE = 2;
private Stdio $io;
private Context $context;
private GameHelp $help;
private Vector<string> $modes = Vector { 'training', 'arena' };
public function __construct(private array<string> $args = []) {
$f = new CliFactory();
$this->context = $f->newContext([ 'argv' => $args ]);
$this->io = $f->newStdio();
$this->help = new GameHelp(new Context\OptionFactory());
}
public function boot(Kernel $kernel) : void {
try {
$getopt = $this->getopt();
$this->startGame($kernel, $getopt);
} catch (\Exception $ex) {
$this->printUsage();
$this->renderException($ex);
exit(Status::USAGE);
}
}
public function println(string $message) : void {
$this->io->outln($message);
}
public function renderException(\Exception $ex) : void {
$this->fail(() ==> {
do {
$prev = $ex->getPrevious();
$this->io->errln($ex->getMessage());
$ex = $prev;
} while (null !== $ex);
});
}
private function fail((function():void) $output, ?int $code = null) : void {
$this->io->out('<<red>>');
$output();
if (null !== $code) {
exit($code);
}
$this->io->out('<<reset>>');
}
private function getopt() : Context\Getopt {
$getopt = $this->context->getopt($this->help->getOptions());
if ($getopt->hasErrors()) {
throw array_reduce($getopt->getErrors(), ($prev, $ex) ==> {
$ex->setPrevious($prev);
return $ex;
}, new \RuntimeException());
}
return $getopt;
}
private function makeServer(Context\Getopt $getopt) : Server {
$key = $getopt->get(self::ARG_KEY);
if (null === $key) {
throw new \InvalidArgumentException('You must specify your API key.');
}
return new Server($key, $getopt->get('-h', 'http://vindinium.org'));
}
private function printUsage(string $name = 'hackdinium') : void {
$this->io->outln($this->help->getHelp($name));
}
private function startGame(Kernel $kernel, Context\Getopt $getopt) : void {
$mode = $getopt->get(self::ARG_MODE, 'training');
if (-1 === $this->modes->linearSearch($mode)) {
throw new \InvalidArgumentException(sprintf('Mode "%s" must be one of %s', $mode, implode(',', $this->modes->toArray())));
}
$server = $this->makeServer($getopt);
if ('arena' === $mode) {
$kernel->arena($server, (int)$getopt->get('-t', PHP_INT_MAX));
} else {
$turns = (int) $getopt->get('-t', 200);
$map = $getopt->get('-m', null);
$kernel->training($server, ($server) ==> $server->training($turns, $map));
}
exit(Status::SUCCESS);
}
}
<commit_msg>Added exception trace to shell error output<commit_after><?hh
namespace Hackdinium\Cli;
use Aura\Cli\CliFactory;
use Aura\Cli\Context;
use Aura\Cli\Status;
use Hackdinium\Kernel;
use Hackdinium\Server;
class Shell {
const ARG_KEY = 1;
const ARG_MODE = 2;
private Stdio $io;
private Context $context;
private GameHelp $help;
private Vector<string> $modes = Vector { 'training', 'arena' };
public function __construct(private array<string> $args = []) {
$f = new CliFactory();
$this->context = $f->newContext([ 'argv' => $args ]);
$this->io = $f->newStdio();
$this->help = new GameHelp(new Context\OptionFactory());
}
public function boot(Kernel $kernel) : void {
try {
$getopt = $this->getopt();
$this->startGame($kernel, $getopt);
} catch (\Exception $ex) {
$this->printUsage();
$this->renderException($ex);
exit(Status::USAGE);
}
}
public function println(string $message) : void {
$this->io->outln($message);
}
public function renderException(\Exception $ex) : void {
$this->fail(() ==> {
do {
$prev = $ex->getPrevious();
$this->io->errln($ex->getMessage());
$this->io->errln($ex->getTraceAsString());
$ex = $prev;
} while (null !== $ex);
});
}
private function fail((function():void) $output, ?int $code = null) : void {
$this->io->out('<<red>>');
$output();
if (null !== $code) {
exit($code);
}
$this->io->out('<<reset>>');
}
private function getopt() : Context\Getopt {
$getopt = $this->context->getopt($this->help->getOptions());
if ($getopt->hasErrors()) {
throw array_reduce($getopt->getErrors(), ($prev, $ex) ==> {
$ex->setPrevious($prev);
return $ex;
}, new \RuntimeException());
}
return $getopt;
}
private function makeServer(Context\Getopt $getopt) : Server {
$key = $getopt->get(self::ARG_KEY);
if (null === $key) {
throw new \InvalidArgumentException('You must specify your API key.');
}
return new Server($key, $getopt->get('-h', 'http://vindinium.org'));
}
private function printUsage(string $name = 'hackdinium') : void {
$this->io->outln($this->help->getHelp($name));
}
private function startGame(Kernel $kernel, Context\Getopt $getopt) : void {
$mode = $getopt->get(self::ARG_MODE, 'training');
if (-1 === $this->modes->linearSearch($mode)) {
throw new \InvalidArgumentException(sprintf('Mode "%s" must be one of %s', $mode, implode(',', $this->modes->toArray())));
}
$server = $this->makeServer($getopt);
if ('arena' === $mode) {
$kernel->arena($server, (int)$getopt->get('-t', PHP_INT_MAX));
} else {
$turns = (int) $getopt->get('-t', 200);
$map = $getopt->get('-m', null);
$kernel->training($server, ($server) ==> $server->training($turns, $map));
}
exit(Status::SUCCESS);
}
}
<|endoftext|>
|
<commit_before>#include <osgGA/Version>
const char* osgGAGetVersion()
{
return "1.2";
}
const char* osgGAGetLibraryName()
{
return "OpenSceneGraph Gui Adapter Library";
}
<commit_msg>Fixed version function names and comment strings<commit_after>#include <osgViewer/Version>
const char* osgViewerGetVersion()
{
return "1.2";
}
const char* osgViewerGetLibraryName()
{
return "OpenSceneGraph Viewer Library";
}
<|endoftext|>
|
<commit_before>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <vector>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <kchashdb.h>
#include "Downloader.h"
#include "ExecUtil.h"
#include "FileLocker.h"
#include "FileUtil.h"
#include "MarcUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "TimeLimit.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname
<< "[--max-record-count count] [--skip-count count] marc_input marc_output full_text_db\n\n";
std::exit(EXIT_FAILURE);
}
void FileLockedComposeAndWriteRecord(FILE * const output, const std::string &output_filename,
const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data, std::shared_ptr<Leader> leader)
{
FileLocker file_locker(output_filename, FileLocker::WRITE_ONLY);
if (std::fseek(output, 0, SEEK_END) == -1)
Error("failed to seek to the end of \"" + output_filename + "\"!");
MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, leader);
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto _3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension"))
return true;
} else {
const auto z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->second, "Rezension"))
return true;
}
return false;
}
bool FoundAtLeastOneNonReviewLink(const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data)
{
ssize_t _856_index(MarcUtil::GetFieldIndex(dir_entries, "856"));
if (_856_index == -1)
return false;
const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size()));
for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) {
const Subfields subfields(field_data[_856_index]);
const auto u_begin_end(subfields.getIterators('u'));
if (u_begin_end.first == u_begin_end.second) // No subfield 'u'.
continue;
if (not IsProbablyAReview(subfields))
return true;
}
return false;
}
constexpr unsigned PROCESS_COUNT_HIGHWATER_MARK(10);
constexpr unsigned PROCESS_COUNT_LOWWATER_MARK(5);
// Returns the number of child processes that returned a non-zero exit code.
unsigned CleanUpZombies(const unsigned zombies_to_collect) {
unsigned child_reported_failure_count(0);
for (unsigned zombie_no(0); zombie_no < zombies_to_collect; ++zombie_no) {
int exit_code;
::wait(&exit_code);
if (exit_code != 0)
++child_reported_failure_count;
}
return child_reported_failure_count;
}
void ProcessRecords(const unsigned max_record_count, const unsigned skip_count, FILE * const input,
const std::string &input_filename, FILE * const output, const std::string &output_filename,
const std::string &db_filename)
{
std::shared_ptr<Leader> leader;
std::vector<DirectoryEntry> dir_entries;
std::vector<std::string> field_data;
std::string err_msg;
unsigned total_record_count(0), spawn_count(0), active_child_count(0), child_reported_failure_count(0);
long offset(0L), last_offset;
const std::string UPDATE_FULL_TEXT_DB_PATH(ExecUtil::Which("update_full_text_db"));
if (UPDATE_FULL_TEXT_DB_PATH.empty())
Error("can't find \"update_full_text_db\" in our $PATH!");
while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) {
last_offset = offset;
offset += leader->getRecordLength();
if (total_record_count == max_record_count)
break;
++total_record_count;
if (total_record_count <= skip_count)
continue;
if (not FoundAtLeastOneNonReviewLink(dir_entries, field_data)) {
FileLockedComposeAndWriteRecord(output, output_filename, dir_entries, field_data, leader);
continue;
}
ExecUtil::Exec(UPDATE_FULL_TEXT_DB_PATH,
{ std::to_string(last_offset), input_filename, output_filename, db_filename },
/* new_stdout = */"", ExecUtil::ExecMode::DETACH);
++active_child_count;
++spawn_count;
if (active_child_count > PROCESS_COUNT_HIGHWATER_MARK) {
child_reported_failure_count += CleanUpZombies(active_child_count - PROCESS_COUNT_LOWWATER_MARK);
active_child_count = PROCESS_COUNT_LOWWATER_MARK;
}
}
// Wait for stragglers:
child_reported_failure_count += CleanUpZombies(active_child_count);
if (not err_msg.empty())
Error(err_msg);
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Spawned " << spawn_count << " subprocesses.\n";
std::cerr << child_reported_failure_count << " children reported a failure!\n";
std::fclose(input);
std::fclose(output);
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4 and argc != 6 and argc != 8)
Usage();
++argv; // skip program name
// Process optional args:
unsigned max_record_count(UINT_MAX), skip_count(0);
while (argc > 4) {
if (std::strcmp(*argv, "--max-record-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &max_record_count) or max_record_count == 0)
Error("bad value for --max-record-count!");
argc -= 2;
} else if (std::strcmp(*argv, "--skip-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &skip_count))
Error("bad value for --skip-count!");
argc -= 2;
} else
Error("unknown flag: " + std::string(*argv));
}
const std::string marc_input_filename(*argv++);
FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb");
if (marc_input == nullptr)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(*argv++);
FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb");
if (marc_output == nullptr)
Error("can't open \"" + marc_output_filename + "\" for writing!");
const std::string db_filename(*argv);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE
| kyotocabinet::HashDB::OTRUNCATE))
Error("Failed to create and truncate database \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
db.close();
try {
ProcessRecords(max_record_count, skip_count, marc_input, marc_input_filename, marc_output,
marc_output_filename, db_filename);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<commit_msg>Added a new command-line flag to specify the high and low watermarks for spawned child processes.<commit_after>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <vector>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <kchashdb.h>
#include "Downloader.h"
#include "ExecUtil.h"
#include "FileLocker.h"
#include "FileUtil.h"
#include "MarcUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "TimeLimit.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname
<< "[--max-record-count count] [--skip-count count] [--process-count-low-and-high-watermarks low:high] "
<< "marc_input marc_output full_text_db\n"
<< " --process-count-low-and-high-watermarks sets the maximum and minimum number of spawned\n"
<< " child processes. When we hit the high water mark we wait for child processes to exit\n"
<< " until we reach the low watermark.\n\n";
std::exit(EXIT_FAILURE);
}
void FileLockedComposeAndWriteRecord(FILE * const output, const std::string &output_filename,
const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data, std::shared_ptr<Leader> leader)
{
FileLocker file_locker(output_filename, FileLocker::WRITE_ONLY);
if (std::fseek(output, 0, SEEK_END) == -1)
Error("failed to seek to the end of \"" + output_filename + "\"!");
MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, leader);
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto _3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension"))
return true;
} else {
const auto z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->second, "Rezension"))
return true;
}
return false;
}
bool FoundAtLeastOneNonReviewLink(const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data)
{
ssize_t _856_index(MarcUtil::GetFieldIndex(dir_entries, "856"));
if (_856_index == -1)
return false;
const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size()));
for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) {
const Subfields subfields(field_data[_856_index]);
const auto u_begin_end(subfields.getIterators('u'));
if (u_begin_end.first == u_begin_end.second) // No subfield 'u'.
continue;
if (not IsProbablyAReview(subfields))
return true;
}
return false;
}
// Returns the number of child processes that returned a non-zero exit code.
unsigned CleanUpZombies(const unsigned zombies_to_collect) {
unsigned child_reported_failure_count(0);
for (unsigned zombie_no(0); zombie_no < zombies_to_collect; ++zombie_no) {
int exit_code;
::wait(&exit_code);
if (exit_code != 0)
++child_reported_failure_count;
}
return child_reported_failure_count;
}
void ProcessRecords(const unsigned max_record_count, const unsigned skip_count, FILE * const input,
const std::string &input_filename, FILE * const output, const std::string &output_filename,
const std::string &db_filename, const unsigned process_count_low_watermark,
const unsigned process_count_high_watermark)
{
std::shared_ptr<Leader> leader;
std::vector<DirectoryEntry> dir_entries;
std::vector<std::string> field_data;
std::string err_msg;
unsigned total_record_count(0), spawn_count(0), active_child_count(0), child_reported_failure_count(0);
long offset(0L), last_offset;
const std::string UPDATE_FULL_TEXT_DB_PATH(ExecUtil::Which("update_full_text_db"));
if (UPDATE_FULL_TEXT_DB_PATH.empty())
Error("can't find \"update_full_text_db\" in our $PATH!");
while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) {
last_offset = offset;
offset += leader->getRecordLength();
if (total_record_count == max_record_count)
break;
++total_record_count;
if (total_record_count <= skip_count)
continue;
if (not FoundAtLeastOneNonReviewLink(dir_entries, field_data)) {
FileLockedComposeAndWriteRecord(output, output_filename, dir_entries, field_data, leader);
continue;
}
ExecUtil::Exec(UPDATE_FULL_TEXT_DB_PATH,
{ std::to_string(last_offset), input_filename, output_filename, db_filename },
/* new_stdout = */"", ExecUtil::ExecMode::DETACH);
++active_child_count;
++spawn_count;
if (active_child_count > process_count_high_watermark) {
child_reported_failure_count += CleanUpZombies(active_child_count - process_count_low_watermark);
active_child_count = process_count_low_watermark;
}
}
// Wait for stragglers:
child_reported_failure_count += CleanUpZombies(active_child_count);
if (not err_msg.empty())
Error(err_msg);
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Spawned " << spawn_count << " subprocesses.\n";
std::cerr << child_reported_failure_count << " children reported a failure!\n";
std::fclose(input);
std::fclose(output);
}
constexpr unsigned PROCESS_COUNT_DEFAULT_HIGH_WATERMARK(10);
constexpr unsigned PROCESS_COUNT_DEFAULT_LOW_WATERMARK(5);
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4 and argc != 6 and argc != 8 and argc != 10)
Usage();
++argv; // skip program name
// Process optional args:
unsigned max_record_count(UINT_MAX), skip_count(0);
unsigned process_count_low_watermark(PROCESS_COUNT_DEFAULT_LOW_WATERMARK),
process_count_high_watermark(PROCESS_COUNT_DEFAULT_HIGH_WATERMARK);
while (argc > 4) {
if (std::strcmp(*argv, "--max-record-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &max_record_count) or max_record_count == 0)
Error("bad value for --max-record-count!");
++argv;
argc -= 2;
} else if (std::strcmp(*argv, "--skip-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &skip_count))
Error("bad value for --skip-count!");
++argv;
argc -= 2;
} else if (std::strcmp("--process-count-low-and-high-watermarks", *argv) == 0) {
++argv;
char *arg_end(*argv + std::strlen(*argv));
char * const colon(std::find(*argv, arg_end, ':'));
if (colon == arg_end)
Error("bad argument to --process-count-low-and-high-watermarks: colon is missing!");
*colon = '\0';
if (not StringUtil::ToNumber(*argv, &process_count_low_watermark)
or not StringUtil::ToNumber(*argv, &process_count_high_watermark))
Error("low or high watermark is not an unsigned number!");
if (process_count_high_watermark > process_count_low_watermark)
Error("the high watermark must be larger than the low watermark!");
++argv;
argc -= 2;
} else
Error("unknown flag: " + std::string(*argv));
}
const std::string marc_input_filename(*argv++);
FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb");
if (marc_input == nullptr)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(*argv++);
FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb");
if (marc_output == nullptr)
Error("can't open \"" + marc_output_filename + "\" for writing!");
const std::string db_filename(*argv);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE
| kyotocabinet::HashDB::OTRUNCATE))
Error("Failed to create and truncate database \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
db.close();
try {
ProcessRecords(max_record_count, skip_count, marc_input, marc_input_filename, marc_output,
marc_output_filename, db_filename, process_count_low_watermark,
process_count_high_watermark);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "bh/bh.hpp"
#include "util/timing.hpp"
#include "util/argparse.hpp"
using namespace std;
using namespace bh;
using namespace argparse;
template <typename T>
T solve(int w, int h, int i)
{
multi_array<T> grid(h,w), center, north, south, east, west;
center = grid[_(1,-1,1)][_(1,-1,1)]; // Setup stencil
north = grid[_(0,-2,1)][_(1,-1,1)];
south = grid[_(2, h,1)][_(1,-1,1)];
east = grid[_(1,-1,1)][_(2, w,1)];
west = grid[_(1,-1,1)][_(0,-2,1)];
grid = 0.0; // Initialize grid
grid[_(1,h,1)][ 0] = -273.15; // .
grid[_(1,h,1)][-1] = -273.15; // .
grid[-1][_(0,w,1)] = -273.15; // .
grid[ 0][_(0,w,1)] = 40.0; // and border values.
for(int k=0; k<i; k++) { // Approximate
center = (T)0.2*(center+north+east+west+south);
}
return scalar(sum(grid));
}
int main(int argc, char* argv[])
{
const char usage[] = "usage: ./jacobi_solver --size=1000*1000*10 [--verbose]";
if (2>argc) {
cout << usage << endl;
return 1;
}
arguments_t args; // Parse command-line
if (!parse_args(argc, argv, args)) {
cout << "Err: Invalid argument(s)." << endl;
cout << usage << endl;
return 1;
}
if (3 > args.size.size()) {
cout << "Err: Not enough arguments." << endl;
cout << usage << endl;
return 1;
}
if (3 < args.size.size()) {
cout << "Err: Too many arguments." << endl;
cout << usage << endl;
return 1;
}
for(size_t i=0; i<3; i++) {
cout << args.size[i] << endl;
}
size_t start = sample_time();
double output = solve<double>(args.size[0], args.size[1], args.size[2]);
size_t end = sample_time();
// Output timing
cout << "{elapsed-time: "<< (end-start)/1000000.0 <<"";
if (args.verbose) { // and values.
cout << ", \"output\": [";
cout << output;
cout << "]";
}
cout << "}" << endl;
stop();
return 0;
}
<commit_msg>cppb: Added in-place update of operands via operand.update( other );<commit_after>#include <iostream>
#include "bh/bh.hpp"
#include "util/timing.hpp"
#include "util/argparse.hpp"
using namespace std;
using namespace bh;
using namespace argparse;
template <typename T>
T solve(int w, int h, int i)
{
multi_array<T> grid(h,w),
center, north, south, east, west;
center = grid[_(1,-1,1)][_(1,-1,1)]; // Setup stencil
north = grid[_(0,-2,1)][_(1,-1,1)];
south = grid[_(2, h,1)][_(1,-1,1)];
east = grid[_(1,-1,1)][_(2, w,1)];
west = grid[_(1,-1,1)][_(0,-2,1)];
grid = 0.0; // Initialize grid
grid[_(1,h,1)][ 0] = -273.15; // .
grid[_(1,h,1)][-1] = -273.15; // .
grid[-1][_(0,w,1)] = -273.15; // .
grid[ 0][_(0,w,1)] = 40.0; // and border values.
for(int k=0; k<i; k++) { // Approximate
center.update((T)0.2*(center+north+east+west+south));
}
return scalar(sum(grid));
}
int main(int argc, char* argv[])
{
const char usage[] = "usage: ./jacobi_solver --size=1000*1000*10 [--verbose]";
if (2>argc) {
cout << usage << endl;
return 1;
}
arguments_t args; // Parse command-line
if (!parse_args(argc, argv, args)) {
cout << "Err: Invalid argument(s)." << endl;
cout << usage << endl;
return 1;
}
if (3 > args.size.size()) {
cout << "Err: Not enough arguments." << endl;
cout << usage << endl;
return 1;
}
if (3 < args.size.size()) {
cout << "Err: Too many arguments." << endl;
cout << usage << endl;
return 1;
}
for(size_t i=0; i<3; i++) {
cout << args.size[i] << endl;
}
size_t start = sample_time();
double output = solve<double>(args.size[0], args.size[1], args.size[2]);
size_t end = sample_time();
// Output timing
cout << "{elapsed-time: "<< (end-start)/1000000.0 <<"";
if (args.verbose) { // and values.
cout << ", \"output\": [";
cout << output;
cout << "]";
}
cout << "}" << endl;
stop();
return 0;
}
<|endoftext|>
|
<commit_before>/** \file
* Implements a load recorder, useful for simulating loads to test
* CPU clock daemons and settings.
*/
#include "Options.hpp"
#include "types.hpp"
#include "constants.hpp"
#include "errors.hpp"
#include "utility.hpp"
#include "clas.hpp"
#include "version.hpp"
#include "sys/sysctl.hpp"
#include <iostream> /* std::cout, std::cerr */
#include <fstream> /* std::ofstream */
#include <chrono> /* std::chrono::steady_clock::now() */
#include <thread> /* std::this_thread::sleep_until() */
#include <memory> /* std::unique_ptr */
#include <sys/resource.h> /* CPUSTATES */
/**
* File local scope.
*/
namespace {
using nih::Option;
using nih::make_Options;
using constants::ACLINE;
using constants::FREQ;
using constants::FREQ_LEVELS;
using constants::CP_TIMES;
using types::ms;
using types::coreid_t;
using types::cptime_t;
using types::mhz_t;
using errors::Exit;
using errors::Exception;
using errors::fail;
using utility::to_value;
using utility::sprintf_safe;
using namespace utility::literals;
using clas::ival;
using sys::ctl::make_Sysctl;
using sys::ctl::make_Once;
using version::LOADREC_FEATURES;
using version::flag_t;
using namespace version::literals;
/**
* The set of supported features.
*
* This value is stored in load recordings to allow loadplay to correctly
* interpret the data.
*/
constexpr flag_t const FEATURES{
1_FREQ_TRACKING
};
/**
* The global state.
*/
struct {
bool verbose{false}; /**< Verbosity flag. */
ms duration{30000}; /**< Recording duration in ms. */
ms interval{25}; /**< Recording sample interval in ms. */
/**
* The output file stream to use if an outfilename is provided
* on the CLI.
*/
std::ofstream outfile{};
/**
* A pointer to the stream to use for output, either std::cout
* or outfile.
*/
std::ostream * out = &std::cout;
/**
* The user provided output file name.
*/
char const * outfilename{nullptr};
/**
* The number of CPU cores/threads.
*/
sys::ctl::SysctlOnce<coreid_t, 2> const ncpu{1U, {CTL_HW, HW_NCPU}};
} g;
/**
* An enum for command line parsing.
*/
enum class OE {
USAGE, /**< Print help */
IVAL_DURATION, /**< Set the duration of the recording */
IVAL_POLL, /**< Set polling interval */
FILE_OUTPUT, /**< Set output file */
FILE_PID, /**< Set PID file */
FLAG_VERBOSE, /**< Verbose output on stderr */
OPT_UNKNOWN, /**< Obligatory */
OPT_NOOPT, /**< Obligatory */
OPT_DASH, /**< Obligatory */
OPT_LDASH, /**< Obligatory */
OPT_DONE /**< Obligatory */
};
/**
* The short usage string.
*/
char const * const USAGE = "[-hv] [-d ival] [-p ival] [-o file]";
/**
* Definitions of command line options.
*/
Option<OE> const OPTIONS[]{
{OE::USAGE, 'h', "help", "", "Show usage and exit"},
{OE::FLAG_VERBOSE, 'v', "verbose", "", "Be verbose"},
{OE::IVAL_DURATION, 'd', "duration", "ival", "The duration of the recording"},
{OE::IVAL_POLL, 'p', "poll", "ival", "The polling interval"},
{OE::FILE_OUTPUT, 'o', "output", "file", "Output to file"},
{OE::FILE_PID, 'P', "pid", "file", "Ignored"},
};
/**
* Outputs the given message on stderr if g.verbose is set.
*
* @param msg
* The message to output
*/
inline void verbose(std::string const & msg) {
if (g.verbose) {
std::cerr << "loadrec: " << msg << '\n';
}
}
/**
* Set up output to the given file.
*/
void init() {
if (g.outfilename) {
g.outfile.open(g.outfilename);
if (!g.outfile.good()) {
fail(Exit::EWOPEN, errno,
"could not open file for writing: "_s + g.outfilename);
}
g.out = &g.outfile;
}
}
/**
* Parse command line arguments.
*
* @param argc,argv
* The command line arguments
*/
void read_args(int const argc, char const * const argv[]) {
auto getopt = make_Options(argc, argv, USAGE, OPTIONS);
while (true) switch (getopt()) {
case OE::USAGE:
std::cerr << getopt.usage();
throw Exception{Exit::OK, 0, ""};
case OE::FLAG_VERBOSE:
g.verbose = true;
break;
case OE::IVAL_DURATION:
g.duration = ival(getopt[1]);
break;
case OE::IVAL_POLL:
g.interval = ival(getopt[1]);
break;
case OE::FILE_OUTPUT:
g.outfilename = getopt[1];
break;
case OE::FILE_PID:
break;
case OE::OPT_UNKNOWN:
case OE::OPT_NOOPT:
case OE::OPT_DASH:
case OE::OPT_LDASH:
fail(Exit::ECLARG, 0, "unexpected command line argument: "_s +
getopt[0] + "\n\n" + getopt.usage());
case OE::OPT_DONE:
return;
}
}
/**
* Print the sysctls
*/
void print_sysctls() {
sys::ctl::Sysctl<> hw_acpi_acline;
try {
hw_acpi_acline = {ACLINE};
} catch (sys::sc_error<sys::ctl::error>) {
verbose("cannot read "_s + ACLINE);
}
*g.out << "%s=%ld\n"_fmt(LOADREC_FEATURES, FEATURES)
<< "hw.machine=" << make_Sysctl(CTL_HW, HW_MACHINE).get<char>().get() << '\n'
<< "hw.model=" << make_Sysctl(CTL_HW, HW_MODEL).get<char>().get() << '\n'
<< "hw.ncpu=" << g.ncpu << '\n'
<< ACLINE << '=' << make_Once(1U, hw_acpi_acline) << '\n';
for (coreid_t i = 0; i < g.ncpu; ++i) {
char mibname[40];
sprintf_safe(mibname, FREQ, i);
try {
sys::ctl::Sysctl<> ctl{mibname};
*g.out << mibname << '='
<< make_Once(0, ctl) << '\n';
} catch (sys::sc_error<sys::ctl::error> e) {
verbose("cannot access sysctl: "_s + mibname);
if (i == 0) {
fail(Exit::ENOFREQ, e,
"at least the first CPU core must report its clock frequency");
}
}
sprintf_safe(mibname, FREQ_LEVELS, i);
try {
sys::ctl::Sysctl<> ctl{mibname};
*g.out << mibname << '='
<< ctl.get<char>().get() << '\n';
} catch (sys::sc_error<sys::ctl::error>) {
/* do nada */
}
}
}
/**
* Report the load frames.
*
* This prints the time in ms since the last frame and the cp_times
* growth as a space separated list.
*/
void run() try {
/*
* Setup cptimes buffer for two samples.
*/
sys::ctl::Sysctl<> const cp_times_ctl = {CP_TIMES};
auto const columns = cp_times_ctl.size() / sizeof(cptime_t);
auto cp_times = std::unique_ptr<cptime_t[]>(
new cptime_t[2 * columns]{});
/*
* Setup clock frequency sources for each core.
*/
coreid_t const cores = columns / CPUSTATES;
auto corefreqs = std::unique_ptr<sys::ctl::Sync<mhz_t, sys::ctl::Sysctl<>>[]>(
new sys::ctl::Sync<mhz_t, sys::ctl::Sysctl<>>[cores]{});
for (coreid_t i = 0; i < cores; ++i) {
char mibname[40];
sprintf_safe(mibname, FREQ, i);
try {
corefreqs[i] = sys::ctl::Sysctl<>{mibname};
} catch (sys::sc_error<sys::ctl::error> e) {
if (i == 0) {
fail(Exit::ENOFREQ, e,
"at least the first CPU core must report its clock frequency");
}
/* Fall back to previous clock provider. */
corefreqs[i] = corefreqs[i - 1];
}
}
/*
* Record freq and cptimes.
*/
auto time = std::chrono::steady_clock::now();
auto last = time;
auto const stop = time + g.duration;
size_t sample = 0;
/* Takes a sample and prints it, avoids duplicating code
* behind the loop. */
auto const takeAndPrintSample = [&]() {
cp_times_ctl.get(&cp_times[sample * columns],
sizeof(cptime_t) * columns);
*g.out << std::chrono::duration_cast<ms>(time - last).count();
for (coreid_t i = 0; i < cores; ++i) {
*g.out << ' ' << static_cast<mhz_t>(corefreqs[i]);
}
for (int i = 0; i < columns; ++i) {
*g.out << ' '
<< cp_times[sample * columns + i] -
cp_times[((sample + 1) % 2) * columns + i];
}
};
while (time < stop) {
takeAndPrintSample();
*g.out << '\n';
sample = (sample + 1) % 2;
last = time;
std::this_thread::sleep_until(time += g.interval);
}
takeAndPrintSample();
*g.out << std::endl;
} catch (sys::sc_error<sys::ctl::error> e) {
fail(Exit::ESYSCTL, e, "failed to access sysctl: "_s + CP_TIMES);
}
} /* namespace */
/**
* Main routine, setup and execute daemon, print errors.
*
* @param argc,argv
* The command line arguments
* @return
* An exit code
* @see Exit
*/
int main(int argc, char * argv[]) {
try {
read_args(argc, argv);
init();
print_sysctls();
run();
} catch (Exception & e) {
if (e.msg != "") {
std::cerr << "loadrec: " << e.msg << '\n';
}
return to_value(e.exitcode);
} catch (sys::sc_error<sys::ctl::error> e) {
std::cerr << "loadrec: untreated sysctl failure: " << e.c_str() << '\n';
throw;
} catch (...) {
std::cerr << "loadrec: untreated failure\n";
throw;
}
}
<commit_msg>Avoid type mismatch in comparison<commit_after>/** \file
* Implements a load recorder, useful for simulating loads to test
* CPU clock daemons and settings.
*/
#include "Options.hpp"
#include "types.hpp"
#include "constants.hpp"
#include "errors.hpp"
#include "utility.hpp"
#include "clas.hpp"
#include "version.hpp"
#include "sys/sysctl.hpp"
#include <iostream> /* std::cout, std::cerr */
#include <fstream> /* std::ofstream */
#include <chrono> /* std::chrono::steady_clock::now() */
#include <thread> /* std::this_thread::sleep_until() */
#include <memory> /* std::unique_ptr */
#include <sys/resource.h> /* CPUSTATES */
/**
* File local scope.
*/
namespace {
using nih::Option;
using nih::make_Options;
using constants::ACLINE;
using constants::FREQ;
using constants::FREQ_LEVELS;
using constants::CP_TIMES;
using types::ms;
using types::coreid_t;
using types::cptime_t;
using types::mhz_t;
using errors::Exit;
using errors::Exception;
using errors::fail;
using utility::to_value;
using utility::sprintf_safe;
using namespace utility::literals;
using clas::ival;
using sys::ctl::make_Sysctl;
using sys::ctl::make_Once;
using version::LOADREC_FEATURES;
using version::flag_t;
using namespace version::literals;
/**
* The set of supported features.
*
* This value is stored in load recordings to allow loadplay to correctly
* interpret the data.
*/
constexpr flag_t const FEATURES{
1_FREQ_TRACKING
};
/**
* The global state.
*/
struct {
bool verbose{false}; /**< Verbosity flag. */
ms duration{30000}; /**< Recording duration in ms. */
ms interval{25}; /**< Recording sample interval in ms. */
/**
* The output file stream to use if an outfilename is provided
* on the CLI.
*/
std::ofstream outfile{};
/**
* A pointer to the stream to use for output, either std::cout
* or outfile.
*/
std::ostream * out = &std::cout;
/**
* The user provided output file name.
*/
char const * outfilename{nullptr};
/**
* The number of CPU cores/threads.
*/
sys::ctl::SysctlOnce<coreid_t, 2> const ncpu{1U, {CTL_HW, HW_NCPU}};
} g;
/**
* An enum for command line parsing.
*/
enum class OE {
USAGE, /**< Print help */
IVAL_DURATION, /**< Set the duration of the recording */
IVAL_POLL, /**< Set polling interval */
FILE_OUTPUT, /**< Set output file */
FILE_PID, /**< Set PID file */
FLAG_VERBOSE, /**< Verbose output on stderr */
OPT_UNKNOWN, /**< Obligatory */
OPT_NOOPT, /**< Obligatory */
OPT_DASH, /**< Obligatory */
OPT_LDASH, /**< Obligatory */
OPT_DONE /**< Obligatory */
};
/**
* The short usage string.
*/
char const * const USAGE = "[-hv] [-d ival] [-p ival] [-o file]";
/**
* Definitions of command line options.
*/
Option<OE> const OPTIONS[]{
{OE::USAGE, 'h', "help", "", "Show usage and exit"},
{OE::FLAG_VERBOSE, 'v', "verbose", "", "Be verbose"},
{OE::IVAL_DURATION, 'd', "duration", "ival", "The duration of the recording"},
{OE::IVAL_POLL, 'p', "poll", "ival", "The polling interval"},
{OE::FILE_OUTPUT, 'o', "output", "file", "Output to file"},
{OE::FILE_PID, 'P', "pid", "file", "Ignored"},
};
/**
* Outputs the given message on stderr if g.verbose is set.
*
* @param msg
* The message to output
*/
inline void verbose(std::string const & msg) {
if (g.verbose) {
std::cerr << "loadrec: " << msg << '\n';
}
}
/**
* Set up output to the given file.
*/
void init() {
if (g.outfilename) {
g.outfile.open(g.outfilename);
if (!g.outfile.good()) {
fail(Exit::EWOPEN, errno,
"could not open file for writing: "_s + g.outfilename);
}
g.out = &g.outfile;
}
}
/**
* Parse command line arguments.
*
* @param argc,argv
* The command line arguments
*/
void read_args(int const argc, char const * const argv[]) {
auto getopt = make_Options(argc, argv, USAGE, OPTIONS);
while (true) switch (getopt()) {
case OE::USAGE:
std::cerr << getopt.usage();
throw Exception{Exit::OK, 0, ""};
case OE::FLAG_VERBOSE:
g.verbose = true;
break;
case OE::IVAL_DURATION:
g.duration = ival(getopt[1]);
break;
case OE::IVAL_POLL:
g.interval = ival(getopt[1]);
break;
case OE::FILE_OUTPUT:
g.outfilename = getopt[1];
break;
case OE::FILE_PID:
break;
case OE::OPT_UNKNOWN:
case OE::OPT_NOOPT:
case OE::OPT_DASH:
case OE::OPT_LDASH:
fail(Exit::ECLARG, 0, "unexpected command line argument: "_s +
getopt[0] + "\n\n" + getopt.usage());
case OE::OPT_DONE:
return;
}
}
/**
* Print the sysctls
*/
void print_sysctls() {
sys::ctl::Sysctl<> hw_acpi_acline;
try {
hw_acpi_acline = {ACLINE};
} catch (sys::sc_error<sys::ctl::error>) {
verbose("cannot read "_s + ACLINE);
}
*g.out << "%s=%ld\n"_fmt(LOADREC_FEATURES, FEATURES)
<< "hw.machine=" << make_Sysctl(CTL_HW, HW_MACHINE).get<char>().get() << '\n'
<< "hw.model=" << make_Sysctl(CTL_HW, HW_MODEL).get<char>().get() << '\n'
<< "hw.ncpu=" << g.ncpu << '\n'
<< ACLINE << '=' << make_Once(1U, hw_acpi_acline) << '\n';
for (coreid_t i = 0; i < g.ncpu; ++i) {
char mibname[40];
sprintf_safe(mibname, FREQ, i);
try {
sys::ctl::Sysctl<> ctl{mibname};
*g.out << mibname << '='
<< make_Once(0, ctl) << '\n';
} catch (sys::sc_error<sys::ctl::error> e) {
verbose("cannot access sysctl: "_s + mibname);
if (i == 0) {
fail(Exit::ENOFREQ, e,
"at least the first CPU core must report its clock frequency");
}
}
sprintf_safe(mibname, FREQ_LEVELS, i);
try {
sys::ctl::Sysctl<> ctl{mibname};
*g.out << mibname << '='
<< ctl.get<char>().get() << '\n';
} catch (sys::sc_error<sys::ctl::error>) {
/* do nada */
}
}
}
/**
* Report the load frames.
*
* This prints the time in ms since the last frame and the cp_times
* growth as a space separated list.
*/
void run() try {
/*
* Setup cptimes buffer for two samples.
*/
sys::ctl::Sysctl<> const cp_times_ctl = {CP_TIMES};
auto const columns = cp_times_ctl.size() / sizeof(cptime_t);
auto cp_times = std::unique_ptr<cptime_t[]>(
new cptime_t[2 * columns]{});
/*
* Setup clock frequency sources for each core.
*/
coreid_t const cores = columns / CPUSTATES;
auto corefreqs = std::unique_ptr<sys::ctl::Sync<mhz_t, sys::ctl::Sysctl<>>[]>(
new sys::ctl::Sync<mhz_t, sys::ctl::Sysctl<>>[cores]{});
for (coreid_t i = 0; i < cores; ++i) {
char mibname[40];
sprintf_safe(mibname, FREQ, i);
try {
corefreqs[i] = sys::ctl::Sysctl<>{mibname};
} catch (sys::sc_error<sys::ctl::error> e) {
if (i == 0) {
fail(Exit::ENOFREQ, e,
"at least the first CPU core must report its clock frequency");
}
/* Fall back to previous clock provider. */
corefreqs[i] = corefreqs[i - 1];
}
}
/*
* Record freq and cptimes.
*/
auto time = std::chrono::steady_clock::now();
auto last = time;
auto const stop = time + g.duration;
size_t sample = 0;
/* Takes a sample and prints it, avoids duplicating code
* behind the loop. */
auto const takeAndPrintSample = [&]() {
cp_times_ctl.get(&cp_times[sample * columns],
sizeof(cptime_t) * columns);
*g.out << std::chrono::duration_cast<ms>(time - last).count();
for (coreid_t i = 0; i < cores; ++i) {
*g.out << ' ' << static_cast<mhz_t>(corefreqs[i]);
}
for (size_t i = 0; i < columns; ++i) {
*g.out << ' '
<< cp_times[sample * columns + i] -
cp_times[((sample + 1) % 2) * columns + i];
}
};
while (time < stop) {
takeAndPrintSample();
*g.out << '\n';
sample = (sample + 1) % 2;
last = time;
std::this_thread::sleep_until(time += g.interval);
}
takeAndPrintSample();
*g.out << std::endl;
} catch (sys::sc_error<sys::ctl::error> e) {
fail(Exit::ESYSCTL, e, "failed to access sysctl: "_s + CP_TIMES);
}
} /* namespace */
/**
* Main routine, setup and execute daemon, print errors.
*
* @param argc,argv
* The command line arguments
* @return
* An exit code
* @see Exit
*/
int main(int argc, char * argv[]) {
try {
read_args(argc, argv);
init();
print_sysctls();
run();
} catch (Exception & e) {
if (e.msg != "") {
std::cerr << "loadrec: " << e.msg << '\n';
}
return to_value(e.exitcode);
} catch (sys::sc_error<sys::ctl::error> e) {
std::cerr << "loadrec: untreated sysctl failure: " << e.c_str() << '\n';
throw;
} catch (...) {
std::cerr << "loadrec: untreated failure\n";
throw;
}
}
<|endoftext|>
|
<commit_before>#include "output_hds.h"
#include <mist/defines.h>
#include <mist/http_parser.h>
#include <mist/stream.h>
#include <unistd.h>
#include <mist/amf.h>
#include <mist/mp4_adobe.h>
namespace Mist {
void OutHDS::getTracks(){
/// \todo Why do we have only one audio track option?
videoTracks.clear();
audioTrack = 0;
for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){
if (it->second.codec == "H264" || it->second.codec == "H263" || it->second.codec == "VP6"){
videoTracks.insert(it->first);
}
if (it->second.codec == "AAC" || it->second.codec == "MP3"){
audioTrack = it->first;
}
}
}
///\brief Builds a bootstrap for use in HTTP Dynamic streaming.
///\param tid The track this bootstrap is generated for.
///\return The generated bootstrap.
std::string OutHDS::dynamicBootstrap(int tid){
updateMeta();
std::string empty;
MP4::ASRT asrt;
asrt.setUpdate(false);
asrt.setVersion(1);
//asrt.setQualityEntry(empty, 0);
if (myMeta.live){
asrt.setSegmentRun(1, 4294967295ul, 0);
}else{
asrt.setSegmentRun(1, myMeta.tracks[tid].fragments.size(), 0);
}
MP4::AFRT afrt;
afrt.setUpdate(false);
afrt.setVersion(1);
afrt.setTimeScale(1000);
//afrt.setQualityEntry(empty, 0);
MP4::afrt_runtable afrtrun;
int i = 0;
int j = 0;
if (myMeta.tracks[tid].fragments.size()){
unsigned int firstTime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments.begin()->getNumber()).getTime();
for (std::deque<DTSC::Fragment>::iterator it = myMeta.tracks[tid].fragments.begin(); it != myMeta.tracks[tid].fragments.end(); it++){
if (myMeta.vod || it->getDuration() > 0){
afrtrun.firstFragment = myMeta.tracks[tid].missedFrags + j + 1;
afrtrun.firstTimestamp = myMeta.tracks[tid].getKey(it->getNumber()).getTime() - firstTime;
if (it->getDuration() > 0){
afrtrun.duration = it->getDuration();
}else{
afrtrun.duration = myMeta.tracks[tid].lastms - afrtrun.firstTimestamp;
}
afrt.setFragmentRun(afrtrun, i);
i++;
}
j++;
}
}
MP4::ABST abst;
abst.setVersion(1);
abst.setBootstrapinfoVersion(1);
abst.setProfile(0);
abst.setUpdate(false);
abst.setTimeScale(1000);
abst.setLive(myMeta.live);
abst.setCurrentMediaTime(myMeta.tracks[tid].lastms);
abst.setSmpteTimeCodeOffset(0);
abst.setMovieIdentifier(streamName);
abst.setSegmentRunTable(asrt, 0);
abst.setFragmentRunTable(afrt, 0);
DEBUG_MSG(DLVL_VERYHIGH, "Sending bootstrap: %s", abst.toPrettyString(0).c_str());
return std::string((char*)abst.asBox(), (int)abst.boxedSize());
}
///\brief Builds an index file for HTTP Dynamic streaming.
///\return The index file for HTTP Dynamic Streaming.
std::string OutHDS::dynamicIndex(){
getTracks();
std::stringstream Result;
Result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl;
Result << " <manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">" << std::endl;
Result << " <id>" << streamName << "</id>" << std::endl;
Result << " <mimeType>video/mp4</mimeType>" << std::endl;
Result << " <deliveryType>streaming</deliveryType>" << std::endl;
if (myMeta.vod){
Result << " <duration>" << myMeta.tracks[*videoTracks.begin()].lastms / 1000 << ".000</duration>" << std::endl;
Result << " <streamType>recorded</streamType>" << std::endl;
}else{
Result << " <duration>0.00</duration>" << std::endl;
Result << " <streamType>live</streamType>" << std::endl;
}
for (std::set<int>::iterator it = videoTracks.begin(); it != videoTracks.end(); it++){
Result << " <bootstrapInfo "
"profile=\"named\" "
"id=\"boot" << (*it) << "\" "
"url=\"" << (*it) << ".abst\">"
"</bootstrapInfo>" << std::endl;
Result << " <media "
"url=\"" << (*it) << "-\" "
"bitrate=\"" << myMeta.tracks[(*it)].bps * 8 << "\" "
"bootstrapInfoId=\"boot" << (*it) << "\" "
"width=\"" << myMeta.tracks[(*it)].width << "\" "
"height=\"" << myMeta.tracks[(*it)].height << "\">" << std::endl;
Result << " <metadata>AgAKb25NZXRhRGF0YQMAAAk=</metadata>" << std::endl;
Result << " </media>" << std::endl;
}
Result << "</manifest>" << std::endl;
DEBUG_MSG(DLVL_HIGH, "Sending manifest: %s", Result.str().c_str());
return Result.str();
} //BuildManifest
OutHDS::OutHDS(Socket::Connection & conn) : Output(conn) {
audioTrack = 0;
playUntil = 0;
myConn.setHost(config->getString("ip"));
streamName = config->getString("streamname");
}
void OutHDS::onFail(){
HTTP_S.Clean(); //make sure no parts of old requests are left in any buffers
HTTP_S.SetBody("Stream not found. Sorry, we tried.");
HTTP_S.SendResponse("404", "Stream not found", myConn);
Output::onFail();
}
OutHDS::~OutHDS() {}
void OutHDS::init(Util::Config * cfg){
Output::init(cfg);
capa["name"] = "HDS";
capa["desc"] = "Enables HTTP protocol Adobe-specific dynamic streaming (also known as HDS).";
capa["deps"] = "HTTP";
capa["url_rel"] = "/dynamic/$/manifest.f4m";
capa["url_prefix"] = "/dynamic/$/";
capa["socket"] = "http_hds";
capa["codecs"][0u][0u].append("H264");
capa["codecs"][0u][0u].append("H263");
capa["codecs"][0u][0u].append("VP6");
capa["codecs"][0u][1u].append("AAC");
capa["codecs"][0u][1u].append("MP3");
capa["methods"][0u]["handler"] = "http";
capa["methods"][0u]["type"] = "flash/11";
capa["methods"][0u]["priority"] = 7ll;
cfg->addBasicConnectorOptions(capa);
config = cfg;
}
void OutHDS::sendNext(){
if (currentPacket.getTime() >= playUntil){
DEBUG_MSG(DLVL_DEVEL, "(%d) Done sending fragment", getpid() );
stop();
wantRequest = true;
HTTP_S.Chunkify("", 0, myConn);
return;
}
tag.DTSCLoader(currentPacket, myMeta.tracks[currentPacket.getTrackId()]);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
void OutHDS::onRequest(){
HTTP_R.Clean();
while (HTTP_R.Read(myConn)){
DEBUG_MSG(DLVL_DEVEL, "Received request: %s", HTTP_R.getUrl().c_str());
if (HTTP_R.url.find(".abst") != std::string::npos){
initialize();
std::string streamID = HTTP_R.url.substr(streamName.size() + 10);
streamID = streamID.substr(0, streamID.find(".abst"));
HTTP_S.Clean();
HTTP_S.SetBody(dynamicBootstrap(atoll(streamID.c_str())));
HTTP_S.SetHeader("Content-Type", "binary/octet");
HTTP_S.SetHeader("Cache-Control", "no-cache");
HTTP_S.SendResponse("200", "OK", myConn);
HTTP_R.Clean(); //clean for any possible next requests
continue;
}
if (HTTP_R.url.find("f4m") == std::string::npos){
initialize();
std::string tmp_qual = HTTP_R.url.substr(HTTP_R.url.find("/", 10) + 1);
unsigned int tid;
unsigned int fragNum;
tid = atoi(tmp_qual.substr(0, tmp_qual.find("Seg") - 1).c_str());
int temp;
temp = HTTP_R.url.find("Seg") + 3;
temp = HTTP_R.url.find("Frag") + 4;
fragNum = atoi(HTTP_R.url.substr(temp).c_str()) - 1;
DEBUG_MSG(DLVL_MEDIUM, "Video track %d, fragment %d\n", tid, fragNum);
if (!audioTrack){getTracks();}
unsigned int mstime = 0;
unsigned int mslen = 0;
if (fragNum < (unsigned int)myMeta.tracks[tid].missedFrags){
HTTP_S.Clean();
HTTP_S.SetBody("The requested fragment is no longer kept in memory on the server and cannot be served.\n");
HTTP_S.SendResponse("412", "Fragment out of range", myConn);
HTTP_R.Clean(); //clean for any possible next requests
std::cout << "Fragment " << fragNum << " too old" << std::endl;
continue;
}
if (fragNum > myMeta.tracks[tid].missedFrags + myMeta.tracks[tid].fragments.size() - 1){
HTTP_S.Clean();
HTTP_S.SetBody("Proxy, re-request this in a second or two.\n");
HTTP_S.SendResponse("208", "Ask again later", myConn);
HTTP_R.Clean(); //clean for any possible next requests
std::cout << "Fragment after fragment " << fragNum << " not available yet" << std::endl;
continue;
}
mstime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getNumber()).getTime();
mslen = myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getDuration();
selectedTracks.clear();
selectedTracks.insert(tid);
selectedTracks.insert(audioTrack);
seek(mstime);
playUntil = mstime + mslen;
HTTP_S.Clean();
HTTP_S.SetHeader("Content-Type", "video/mp4");
HTTP_S.StartResponse(HTTP_R, myConn);
//send the bootstrap
std::string bootstrap = dynamicBootstrap(tid);
HTTP_S.Chunkify(bootstrap, myConn);
//send a zero-size mdat, meaning it stretches until end of file.
HTTP_S.Chunkify("\000\000\000\000mdat", 8, myConn);
//send init data, if needed.
if (audioTrack > 0 && myMeta.tracks[audioTrack].init != ""){
if (tag.DTSCAudioInit(myMeta.tracks[audioTrack])){
tag.tagTime(mstime);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
}
if (tid > 0){
if (tag.DTSCVideoInit(myMeta.tracks[tid])){
tag.tagTime(mstime);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
}
parseData = true;
wantRequest = false;
}else{
initialize();
std::stringstream tmpstr;
myMeta.toPrettyString(tmpstr);
HTTP_S.Clean();
HTTP_S.SetHeader("Content-Type", "text/xml");
HTTP_S.SetHeader("Cache-Control", "no-cache");
HTTP_S.SetBody(dynamicIndex());
HTTP_S.SendResponse("200", "OK", myConn);
}
HTTP_R.Clean(); //clean for any possible next requests
}
}
}
<commit_msg>Fixed HDS without valid audio track.<commit_after>#include "output_hds.h"
#include <mist/defines.h>
#include <mist/http_parser.h>
#include <mist/stream.h>
#include <unistd.h>
#include <mist/amf.h>
#include <mist/mp4_adobe.h>
namespace Mist {
void OutHDS::getTracks(){
/// \todo Why do we have only one audio track option?
/// \todo We should really support all Flash-supported codecs in HDS. These lists are too short now.
videoTracks.clear();
audioTrack = 0;
for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){
if (it->second.codec == "H264" || it->second.codec == "H263" || it->second.codec == "VP6"){
videoTracks.insert(it->first);
}
if (it->second.codec == "AAC" || it->second.codec == "MP3"){
audioTrack = it->first;
}
}
}
///\brief Builds a bootstrap for use in HTTP Dynamic streaming.
///\param tid The track this bootstrap is generated for.
///\return The generated bootstrap.
std::string OutHDS::dynamicBootstrap(int tid){
updateMeta();
std::string empty;
MP4::ASRT asrt;
asrt.setUpdate(false);
asrt.setVersion(1);
//asrt.setQualityEntry(empty, 0);
if (myMeta.live){
asrt.setSegmentRun(1, 4294967295ul, 0);
}else{
asrt.setSegmentRun(1, myMeta.tracks[tid].fragments.size(), 0);
}
MP4::AFRT afrt;
afrt.setUpdate(false);
afrt.setVersion(1);
afrt.setTimeScale(1000);
//afrt.setQualityEntry(empty, 0);
MP4::afrt_runtable afrtrun;
int i = 0;
int j = 0;
if (myMeta.tracks[tid].fragments.size()){
unsigned int firstTime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments.begin()->getNumber()).getTime();
for (std::deque<DTSC::Fragment>::iterator it = myMeta.tracks[tid].fragments.begin(); it != myMeta.tracks[tid].fragments.end(); it++){
if (myMeta.vod || it->getDuration() > 0){
afrtrun.firstFragment = myMeta.tracks[tid].missedFrags + j + 1;
afrtrun.firstTimestamp = myMeta.tracks[tid].getKey(it->getNumber()).getTime() - firstTime;
if (it->getDuration() > 0){
afrtrun.duration = it->getDuration();
}else{
afrtrun.duration = myMeta.tracks[tid].lastms - afrtrun.firstTimestamp;
}
afrt.setFragmentRun(afrtrun, i);
i++;
}
j++;
}
}
MP4::ABST abst;
abst.setVersion(1);
abst.setBootstrapinfoVersion(1);
abst.setProfile(0);
abst.setUpdate(false);
abst.setTimeScale(1000);
abst.setLive(myMeta.live);
abst.setCurrentMediaTime(myMeta.tracks[tid].lastms);
abst.setSmpteTimeCodeOffset(0);
abst.setMovieIdentifier(streamName);
abst.setSegmentRunTable(asrt, 0);
abst.setFragmentRunTable(afrt, 0);
DEBUG_MSG(DLVL_VERYHIGH, "Sending bootstrap: %s", abst.toPrettyString(0).c_str());
return std::string((char*)abst.asBox(), (int)abst.boxedSize());
}
///\brief Builds an index file for HTTP Dynamic streaming.
///\return The index file for HTTP Dynamic Streaming.
std::string OutHDS::dynamicIndex(){
getTracks();
std::stringstream Result;
Result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl;
Result << " <manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">" << std::endl;
Result << " <id>" << streamName << "</id>" << std::endl;
Result << " <mimeType>video/mp4</mimeType>" << std::endl;
Result << " <deliveryType>streaming</deliveryType>" << std::endl;
if (myMeta.vod){
Result << " <duration>" << myMeta.tracks[*videoTracks.begin()].lastms / 1000 << ".000</duration>" << std::endl;
Result << " <streamType>recorded</streamType>" << std::endl;
}else{
Result << " <duration>0.00</duration>" << std::endl;
Result << " <streamType>live</streamType>" << std::endl;
}
for (std::set<int>::iterator it = videoTracks.begin(); it != videoTracks.end(); it++){
Result << " <bootstrapInfo "
"profile=\"named\" "
"id=\"boot" << (*it) << "\" "
"url=\"" << (*it) << ".abst\">"
"</bootstrapInfo>" << std::endl;
Result << " <media "
"url=\"" << (*it) << "-\" "
"bitrate=\"" << myMeta.tracks[(*it)].bps * 8 << "\" "
"bootstrapInfoId=\"boot" << (*it) << "\" "
"width=\"" << myMeta.tracks[(*it)].width << "\" "
"height=\"" << myMeta.tracks[(*it)].height << "\">" << std::endl;
Result << " <metadata>AgAKb25NZXRhRGF0YQMAAAk=</metadata>" << std::endl;
Result << " </media>" << std::endl;
}
Result << "</manifest>" << std::endl;
DEBUG_MSG(DLVL_HIGH, "Sending manifest: %s", Result.str().c_str());
return Result.str();
} //BuildManifest
OutHDS::OutHDS(Socket::Connection & conn) : Output(conn) {
audioTrack = 0;
playUntil = 0;
myConn.setHost(config->getString("ip"));
streamName = config->getString("streamname");
}
void OutHDS::onFail(){
HTTP_S.Clean(); //make sure no parts of old requests are left in any buffers
HTTP_S.SetBody("Stream not found. Sorry, we tried.");
HTTP_S.SendResponse("404", "Stream not found", myConn);
Output::onFail();
}
OutHDS::~OutHDS() {}
void OutHDS::init(Util::Config * cfg){
Output::init(cfg);
capa["name"] = "HDS";
capa["desc"] = "Enables HTTP protocol Adobe-specific dynamic streaming (also known as HDS).";
capa["deps"] = "HTTP";
capa["url_rel"] = "/dynamic/$/manifest.f4m";
capa["url_prefix"] = "/dynamic/$/";
capa["socket"] = "http_hds";
capa["codecs"][0u][0u].append("H264");
capa["codecs"][0u][0u].append("H263");
capa["codecs"][0u][0u].append("VP6");
capa["codecs"][0u][1u].append("AAC");
capa["codecs"][0u][1u].append("MP3");
capa["methods"][0u]["handler"] = "http";
capa["methods"][0u]["type"] = "flash/11";
capa["methods"][0u]["priority"] = 7ll;
cfg->addBasicConnectorOptions(capa);
config = cfg;
}
void OutHDS::sendNext(){
if (currentPacket.getTime() >= playUntil){
DEBUG_MSG(DLVL_DEVEL, "(%d) Done sending fragment", getpid() );
stop();
wantRequest = true;
HTTP_S.Chunkify("", 0, myConn);
return;
}
tag.DTSCLoader(currentPacket, myMeta.tracks[currentPacket.getTrackId()]);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
void OutHDS::onRequest(){
HTTP_R.Clean();
while (HTTP_R.Read(myConn)){
DEBUG_MSG(DLVL_DEVEL, "Received request: %s", HTTP_R.getUrl().c_str());
if (HTTP_R.url.find(".abst") != std::string::npos){
initialize();
std::string streamID = HTTP_R.url.substr(streamName.size() + 10);
streamID = streamID.substr(0, streamID.find(".abst"));
HTTP_S.Clean();
HTTP_S.SetBody(dynamicBootstrap(atoll(streamID.c_str())));
HTTP_S.SetHeader("Content-Type", "binary/octet");
HTTP_S.SetHeader("Cache-Control", "no-cache");
HTTP_S.SendResponse("200", "OK", myConn);
HTTP_R.Clean(); //clean for any possible next requests
continue;
}
if (HTTP_R.url.find("f4m") == std::string::npos){
initialize();
std::string tmp_qual = HTTP_R.url.substr(HTTP_R.url.find("/", 10) + 1);
unsigned int tid;
unsigned int fragNum;
tid = atoi(tmp_qual.substr(0, tmp_qual.find("Seg") - 1).c_str());
int temp;
temp = HTTP_R.url.find("Seg") + 3;
temp = HTTP_R.url.find("Frag") + 4;
fragNum = atoi(HTTP_R.url.substr(temp).c_str()) - 1;
DEBUG_MSG(DLVL_MEDIUM, "Video track %d, fragment %d\n", tid, fragNum);
if (!audioTrack){getTracks();}
unsigned int mstime = 0;
unsigned int mslen = 0;
if (fragNum < (unsigned int)myMeta.tracks[tid].missedFrags){
HTTP_S.Clean();
HTTP_S.SetBody("The requested fragment is no longer kept in memory on the server and cannot be served.\n");
HTTP_S.SendResponse("412", "Fragment out of range", myConn);
HTTP_R.Clean(); //clean for any possible next requests
std::cout << "Fragment " << fragNum << " too old" << std::endl;
continue;
}
if (fragNum > myMeta.tracks[tid].missedFrags + myMeta.tracks[tid].fragments.size() - 1){
HTTP_S.Clean();
HTTP_S.SetBody("Proxy, re-request this in a second or two.\n");
HTTP_S.SendResponse("208", "Ask again later", myConn);
HTTP_R.Clean(); //clean for any possible next requests
std::cout << "Fragment after fragment " << fragNum << " not available yet" << std::endl;
continue;
}
mstime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getNumber()).getTime();
mslen = myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getDuration();
selectedTracks.clear();
selectedTracks.insert(tid);
if (audioTrack){
selectedTracks.insert(audioTrack);
}
seek(mstime);
playUntil = mstime + mslen;
HTTP_S.Clean();
HTTP_S.SetHeader("Content-Type", "video/mp4");
HTTP_S.StartResponse(HTTP_R, myConn);
//send the bootstrap
std::string bootstrap = dynamicBootstrap(tid);
HTTP_S.Chunkify(bootstrap, myConn);
//send a zero-size mdat, meaning it stretches until end of file.
HTTP_S.Chunkify("\000\000\000\000mdat", 8, myConn);
//send init data, if needed.
if (audioTrack > 0 && myMeta.tracks[audioTrack].init != ""){
if (tag.DTSCAudioInit(myMeta.tracks[audioTrack])){
tag.tagTime(mstime);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
}
if (tid > 0){
if (tag.DTSCVideoInit(myMeta.tracks[tid])){
tag.tagTime(mstime);
HTTP_S.Chunkify(tag.data, tag.len, myConn);
}
}
parseData = true;
wantRequest = false;
}else{
initialize();
std::stringstream tmpstr;
myMeta.toPrettyString(tmpstr);
HTTP_S.Clean();
HTTP_S.SetHeader("Content-Type", "text/xml");
HTTP_S.SetHeader("Cache-Control", "no-cache");
HTTP_S.SetBody(dynamicIndex());
HTTP_S.SendResponse("200", "OK", myConn);
}
HTTP_R.Clean(); //clean for any possible next requests
}
}
}
<|endoftext|>
|
<commit_before>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <[email protected]>
Maintainer: <Michael Calmer> <[email protected]>
Purpose:
/-*/
#include <ca-mgm/CA.hpp>
#include <ca-mgm/DNObject.hpp>
#include <ca-mgm/CAConfig.hpp>
#include <ca-mgm/ValueRegExCheck.hpp>
#include <ca-mgm/Exception.hpp>
#include <map>
#include "DNObjectImpl.hpp"
#include "DNObject_Priv.hpp"
#include "Utils.hpp"
namespace CA_MGM_NAMESPACE
{
using namespace ca_mgm;
RDNObject::RDNObject()
: m_impl(new RDNObjectImpl())
{}
RDNObject::RDNObject(const RDNObject& rdn)
: m_impl(rdn.m_impl)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
m_impl = rdn.m_impl;
return *this;
}
void
RDNObject::setRDNValue(const std::string& value)
{
m_impl->value = value;
}
std::string
RDNObject::getType() const
{
return m_impl->type;
}
std::string
RDNObject::getOpenSSLType() const
{
std::map<std::string, std::string> opensslKeys;
opensslKeys["countryName"] = "C";
opensslKeys["stateOrProvinceName"] = "ST";
opensslKeys["localityName"] = "L";
opensslKeys["organizationName"] = "O";
opensslKeys["organizationalUnitName"] = "OU";
opensslKeys["commonName"] = "CN";
opensslKeys["emailAddress"] = "emailAddress";
//opensslKeys[""] = "";
std::string ret;
std::map<std::string, std::string>::const_iterator it = opensslKeys.find(m_impl->type);
if( it != opensslKeys.end())
{
ret = (*it).second;
}
else
{
LOGIT_ERROR("Invalid type:" << m_impl->type);
CA_MGM_THROW(ca_mgm::ValueException,
// %s is the invalid string for a DN type
str::form(__("Invalid type %s."), m_impl->type.c_str()).c_str());
}
return ret;
}
std::string
RDNObject::getValue() const
{
return m_impl->value;
}
std::string
RDNObject::getOpenSSLValue() const
{
if(m_impl->value.empty()) return std::string();
std::string ret = getOpenSSLType();
std::string v = str::escape(m_impl->value, '\\');
v = str::escape(v, '/');
//LOGIT_DEBUG("RDNObject::getOpenSSLValue Value: '" << m_impl->value << "' quoted: '" << v << "'");
ret += "=" + v;
return ret;
}
bool
RDNObject::valid() const
{
if(m_impl->type.empty())
{
LOGIT_DEBUG("type is empty");
return false;
}
// was UTF8Length
if(m_impl->min != 0 && m_impl->value.size() < m_impl->min)
{
LOGIT_DEBUG("value(" << m_impl->value <<
") is too small. Value has to be a minimal length of " <<
m_impl->min);
return false;
}
// was UTF8Length
if(m_impl->max != 0 && m_impl->value.size() > m_impl->max)
{
LOGIT_DEBUG("value(" << m_impl->value <<
") is too long. Value has to be a maximal length of " <<
m_impl->max);
return false;
}
return true;
}
std::vector<std::string>
RDNObject::verify() const
{
std::vector<std::string> result;
if(m_impl->type.empty())
{
result.push_back("type is empty");
}
// was UTF8Length
if(m_impl->min != 0 && m_impl->value.size() < m_impl->min)
{
result.push_back("Value(" + m_impl->value +
") is too small. Value has to be a minimal length of " +
str::numstring(m_impl->min));
}
// was UTF8Length
if(m_impl->max != 0 && m_impl->value.size() > m_impl->max)
{
result.push_back("Value(" + m_impl->value +
") is too long. Value has to be a maximal length of " +
str::numstring(m_impl->max));
}
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
std::vector<std::string>
RDNObject::dump() const
{
std::vector<std::string> result;
result.push_back("RDNObject::dump()");
result.push_back(m_impl->type + "=" + m_impl->value);
result.push_back("Prompt:" + m_impl->prompt);
result.push_back("Min:" + str::numstring(m_impl->min));
result.push_back("Max:" + str::numstring(m_impl->max));
return result;
}
bool
operator==(const RDNObject &l, const RDNObject &r)
{
if(l.getType() == r.getType() &&
l.getValue() == r.getValue())
{
return true;
}
else
{
return false;
}
}
bool
operator<(const RDNObject &l, const RDNObject &r)
{
if(l.getType() < r.getType())
{
return true;
}
else if(l.getType() == r.getType())
{
if(l.getValue() < r.getValue())
{
return true;
}
else
{
return false;
}
} else{
return false;
}
}
// ######################################################################
DNObject::DNObject()
: m_impl(new DNObjectImpl())
{
m_impl->dn.push_back(RDNObject_Priv("countryName", ""));
m_impl->dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
m_impl->dn.push_back(RDNObject_Priv("localityName", ""));
m_impl->dn.push_back(RDNObject_Priv("organizationName", ""));
m_impl->dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
m_impl->dn.push_back(RDNObject_Priv("commonName", ""));
m_impl->dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(CAConfig* caConfig, Type type)
: m_impl(new DNObjectImpl())
{
if(type == E_Client_Cert || type == E_Server_Cert ||
type == E_CA_Cert || type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
CA_MGM_THROW(ca_mgm::ValueException,
str::form(__("Wrong type: %d."), type).c_str());
}
bool p = caConfig->exists(type2Section(type, false), "distinguished_name");
if(!p)
{
LOGIT_ERROR("missing section 'distinguished_name' in config file");
CA_MGM_THROW(ca_mgm::SyntaxException,
__("Missing section 'distinguished_name' in the configuration file."));
}
std::string dnSect = caConfig->getValue(type2Section(type, false),
"distinguished_name");
StringList dnKeys = caConfig->getKeylist(dnSect);
if(dnKeys.empty())
{
LOGIT_ERROR("Can not parse Section " << dnSect);
CA_MGM_THROW(ca_mgm::SyntaxException,
str::form(__("Cannot parse section %s."), dnSect.c_str()).c_str());
}
StringList::const_iterator it = dnKeys.begin();
std::string fieldName;
std::string prompt;
std::string defaultValue;
std::string min("0");
std::string max("0");
for(; it != dnKeys.end(); ++it)
{
if(str::endsWithCI(*it, "_default"))
{
if(str::startsWithCI(*it, fieldName))
{
defaultValue = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else if(str::endsWithCI(*it, "_min"))
{
if(str::startsWithCI(*it, fieldName))
{
min = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else if(str::endsWithCI(*it, "_max"))
{
if(str::startsWithCI(*it, fieldName))
{
max = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else
{
// A new fieldName
//
// commit values
if(!fieldName.empty()) {
m_impl->dn.push_back(RDNObject_Priv(fieldName,
defaultValue,
prompt,
str::strtonum<uint32_t>(min),
str::strtonum<uint32_t>(max)));
}
// reset
prompt = std::string();
defaultValue = std::string();
min = std::string("0");
max = std::string("0");
fieldName = *it;
prompt = caConfig->getValue(dnSect, *it);
}
}
// commit the last values
if(!fieldName.empty())
{
m_impl->dn.push_back(RDNObject_Priv(fieldName,
defaultValue,
prompt,
str::strtonum<uint32_t>(min),
str::strtonum<uint32_t>(max)));
}
}
DNObject::DNObject(const std::list<RDNObject> &dn)
: m_impl(new DNObjectImpl())
{
m_impl->dn = dn;
std::vector<std::string> r = this->verify();
if(!r.empty())
{
CA_MGM_THROW(ca_mgm::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: m_impl(dn.m_impl)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
m_impl = dn.m_impl;
return *this;
}
void
DNObject::setDN(const std::list<RDNObject> &dn)
{
std::vector<std::string> r = checkRDNList(dn);
if(!r.empty())
{
LOGIT_ERROR(r[0]);
CA_MGM_THROW(ca_mgm::ValueException, r[0].c_str());
}
m_impl->dn = dn;
}
std::list<RDNObject>
DNObject::getDN() const
{
return m_impl->dn;
}
std::string
DNObject::getOpenSSLString() const
{
std::string ret;
std::list<RDNObject>::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
if(! (*it).getOpenSSLValue().empty())
{
ret += "/" + (*it).getOpenSSLValue();
}
}
return ret;
}
bool
DNObject::valid() const
{
if(m_impl->dn.empty())
{
LOGIT_DEBUG("empty DN");
return false;
}
std::vector<std::string> r = checkRDNList(m_impl->dn);
if(!r.empty())
{
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
std::vector<std::string>
DNObject::verify() const
{
std::vector<std::string> result;
if(m_impl->dn.empty())
{
result.push_back("empty DN");
}
appendArray(result, checkRDNList(m_impl->dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
std::vector<std::string>
DNObject::checkRDNList(const std::list<RDNObject>& list) const
{
std::vector<std::string> result;
std::list<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it)
{
appendArray(result, (*it).verify());
}
return result;
}
std::vector<std::string>
DNObject::dump() const
{
std::vector<std::string> result;
result.push_back("DNObject::dump()");
std::list< RDNObject >::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
appendArray(result, (*it).dump());
}
return result;
}
void
DNObject::commit2Config(CA& ca, Type type) const
{
if(!(type == E_Client_Req || type == E_Server_Req || E_CA_Req) )
{
LOGIT_ERROR("wrong type" << type);
CA_MGM_THROW(ca_mgm::ValueException,
str::form(__("Wrong type: %1."), type).c_str());
}
ca.getConfig()->deleteSection("req_distinguished_name_val");
std::list< RDNObject >::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
if(!it->getValue().empty())
{
ca.getConfig()->setValue("req_distinguished_name_val", it->getOpenSSLType(), it->getValue());
}
}
}
}
<commit_msg>parse domainComponent in subjects (bnc#738100)<commit_after>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <[email protected]>
Maintainer: <Michael Calmer> <[email protected]>
Purpose:
/-*/
#include <ca-mgm/CA.hpp>
#include <ca-mgm/DNObject.hpp>
#include <ca-mgm/CAConfig.hpp>
#include <ca-mgm/ValueRegExCheck.hpp>
#include <ca-mgm/Exception.hpp>
#include <map>
#include "DNObjectImpl.hpp"
#include "DNObject_Priv.hpp"
#include "Utils.hpp"
namespace CA_MGM_NAMESPACE
{
using namespace ca_mgm;
RDNObject::RDNObject()
: m_impl(new RDNObjectImpl())
{}
RDNObject::RDNObject(const RDNObject& rdn)
: m_impl(rdn.m_impl)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
m_impl = rdn.m_impl;
return *this;
}
void
RDNObject::setRDNValue(const std::string& value)
{
m_impl->value = value;
}
std::string
RDNObject::getType() const
{
return m_impl->type;
}
std::string
RDNObject::getOpenSSLType() const
{
std::map<std::string, std::string> opensslKeys;
opensslKeys["countryName"] = "C";
opensslKeys["stateOrProvinceName"] = "ST";
opensslKeys["localityName"] = "L";
opensslKeys["organizationName"] = "O";
opensslKeys["organizationalUnitName"] = "OU";
opensslKeys["commonName"] = "CN";
opensslKeys["emailAddress"] = "emailAddress";
opensslKeys["domainComponent"] = "DN";
std::string ret;
std::map<std::string, std::string>::const_iterator it = opensslKeys.find(m_impl->type);
if( it != opensslKeys.end())
{
ret = (*it).second;
}
else
{
LOGIT_ERROR("Invalid type:" << m_impl->type);
CA_MGM_THROW(ca_mgm::ValueException,
// %s is the invalid string for a DN type
str::form(__("Invalid type %s."), m_impl->type.c_str()).c_str());
}
return ret;
}
std::string
RDNObject::getValue() const
{
return m_impl->value;
}
std::string
RDNObject::getOpenSSLValue() const
{
if(m_impl->value.empty()) return std::string();
std::string ret = getOpenSSLType();
std::string v = str::escape(m_impl->value, '\\');
v = str::escape(v, '/');
//LOGIT_DEBUG("RDNObject::getOpenSSLValue Value: '" << m_impl->value << "' quoted: '" << v << "'");
ret += "=" + v;
return ret;
}
bool
RDNObject::valid() const
{
if(m_impl->type.empty())
{
LOGIT_DEBUG("type is empty");
return false;
}
// was UTF8Length
if(m_impl->min != 0 && m_impl->value.size() < m_impl->min)
{
LOGIT_DEBUG("value(" << m_impl->value <<
") is too small. Value has to be a minimal length of " <<
m_impl->min);
return false;
}
// was UTF8Length
if(m_impl->max != 0 && m_impl->value.size() > m_impl->max)
{
LOGIT_DEBUG("value(" << m_impl->value <<
") is too long. Value has to be a maximal length of " <<
m_impl->max);
return false;
}
return true;
}
std::vector<std::string>
RDNObject::verify() const
{
std::vector<std::string> result;
if(m_impl->type.empty())
{
result.push_back("type is empty");
}
// was UTF8Length
if(m_impl->min != 0 && m_impl->value.size() < m_impl->min)
{
result.push_back("Value(" + m_impl->value +
") is too small. Value has to be a minimal length of " +
str::numstring(m_impl->min));
}
// was UTF8Length
if(m_impl->max != 0 && m_impl->value.size() > m_impl->max)
{
result.push_back("Value(" + m_impl->value +
") is too long. Value has to be a maximal length of " +
str::numstring(m_impl->max));
}
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
std::vector<std::string>
RDNObject::dump() const
{
std::vector<std::string> result;
result.push_back("RDNObject::dump()");
result.push_back(m_impl->type + "=" + m_impl->value);
result.push_back("Prompt:" + m_impl->prompt);
result.push_back("Min:" + str::numstring(m_impl->min));
result.push_back("Max:" + str::numstring(m_impl->max));
return result;
}
bool
operator==(const RDNObject &l, const RDNObject &r)
{
if(l.getType() == r.getType() &&
l.getValue() == r.getValue())
{
return true;
}
else
{
return false;
}
}
bool
operator<(const RDNObject &l, const RDNObject &r)
{
if(l.getType() < r.getType())
{
return true;
}
else if(l.getType() == r.getType())
{
if(l.getValue() < r.getValue())
{
return true;
}
else
{
return false;
}
} else{
return false;
}
}
// ######################################################################
DNObject::DNObject()
: m_impl(new DNObjectImpl())
{
m_impl->dn.push_back(RDNObject_Priv("countryName", ""));
m_impl->dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
m_impl->dn.push_back(RDNObject_Priv("localityName", ""));
m_impl->dn.push_back(RDNObject_Priv("organizationName", ""));
m_impl->dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
m_impl->dn.push_back(RDNObject_Priv("commonName", ""));
m_impl->dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(CAConfig* caConfig, Type type)
: m_impl(new DNObjectImpl())
{
if(type == E_Client_Cert || type == E_Server_Cert ||
type == E_CA_Cert || type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
CA_MGM_THROW(ca_mgm::ValueException,
str::form(__("Wrong type: %d."), type).c_str());
}
bool p = caConfig->exists(type2Section(type, false), "distinguished_name");
if(!p)
{
LOGIT_ERROR("missing section 'distinguished_name' in config file");
CA_MGM_THROW(ca_mgm::SyntaxException,
__("Missing section 'distinguished_name' in the configuration file."));
}
std::string dnSect = caConfig->getValue(type2Section(type, false),
"distinguished_name");
StringList dnKeys = caConfig->getKeylist(dnSect);
if(dnKeys.empty())
{
LOGIT_ERROR("Can not parse Section " << dnSect);
CA_MGM_THROW(ca_mgm::SyntaxException,
str::form(__("Cannot parse section %s."), dnSect.c_str()).c_str());
}
StringList::const_iterator it = dnKeys.begin();
std::string fieldName;
std::string prompt;
std::string defaultValue;
std::string min("0");
std::string max("0");
for(; it != dnKeys.end(); ++it)
{
if(str::endsWithCI(*it, "_default"))
{
if(str::startsWithCI(*it, fieldName))
{
defaultValue = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else if(str::endsWithCI(*it, "_min"))
{
if(str::startsWithCI(*it, fieldName))
{
min = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else if(str::endsWithCI(*it, "_max"))
{
if(str::startsWithCI(*it, fieldName))
{
max = caConfig->getValue(dnSect, *it);
}
else
{
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
}
else
{
// A new fieldName
//
// commit values
if(!fieldName.empty()) {
m_impl->dn.push_back(RDNObject_Priv(fieldName,
defaultValue,
prompt,
str::strtonum<uint32_t>(min),
str::strtonum<uint32_t>(max)));
}
// reset
prompt = std::string();
defaultValue = std::string();
min = std::string("0");
max = std::string("0");
fieldName = *it;
prompt = caConfig->getValue(dnSect, *it);
}
}
// commit the last values
if(!fieldName.empty())
{
m_impl->dn.push_back(RDNObject_Priv(fieldName,
defaultValue,
prompt,
str::strtonum<uint32_t>(min),
str::strtonum<uint32_t>(max)));
}
}
DNObject::DNObject(const std::list<RDNObject> &dn)
: m_impl(new DNObjectImpl())
{
m_impl->dn = dn;
std::vector<std::string> r = this->verify();
if(!r.empty())
{
CA_MGM_THROW(ca_mgm::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: m_impl(dn.m_impl)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
m_impl = dn.m_impl;
return *this;
}
void
DNObject::setDN(const std::list<RDNObject> &dn)
{
std::vector<std::string> r = checkRDNList(dn);
if(!r.empty())
{
LOGIT_ERROR(r[0]);
CA_MGM_THROW(ca_mgm::ValueException, r[0].c_str());
}
m_impl->dn = dn;
}
std::list<RDNObject>
DNObject::getDN() const
{
return m_impl->dn;
}
std::string
DNObject::getOpenSSLString() const
{
std::string ret;
std::list<RDNObject>::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
if(! (*it).getOpenSSLValue().empty())
{
ret += "/" + (*it).getOpenSSLValue();
}
}
return ret;
}
bool
DNObject::valid() const
{
if(m_impl->dn.empty())
{
LOGIT_DEBUG("empty DN");
return false;
}
std::vector<std::string> r = checkRDNList(m_impl->dn);
if(!r.empty())
{
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
std::vector<std::string>
DNObject::verify() const
{
std::vector<std::string> result;
if(m_impl->dn.empty())
{
result.push_back("empty DN");
}
appendArray(result, checkRDNList(m_impl->dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
std::vector<std::string>
DNObject::checkRDNList(const std::list<RDNObject>& list) const
{
std::vector<std::string> result;
std::list<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it)
{
appendArray(result, (*it).verify());
}
return result;
}
std::vector<std::string>
DNObject::dump() const
{
std::vector<std::string> result;
result.push_back("DNObject::dump()");
std::list< RDNObject >::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
appendArray(result, (*it).dump());
}
return result;
}
void
DNObject::commit2Config(CA& ca, Type type) const
{
if(!(type == E_Client_Req || type == E_Server_Req || E_CA_Req) )
{
LOGIT_ERROR("wrong type" << type);
CA_MGM_THROW(ca_mgm::ValueException,
str::form(__("Wrong type: %1."), type).c_str());
}
ca.getConfig()->deleteSection("req_distinguished_name_val");
std::list< RDNObject >::const_iterator it = m_impl->dn.begin();
for(; it != m_impl->dn.end(); ++it)
{
if(!it->getValue().empty())
{
ca.getConfig()->setValue("req_distinguished_name_val", it->getOpenSSLType(), it->getValue());
}
}
}
}
<|endoftext|>
|
<commit_before>#include "WallFrictionModels.h"
#include "Numerics.h"
namespace WallFriction
{
Real
Churchill(Real Re, Real roughness, Real Dh)
{
Real Re_limit = std::max(Re, 10.0);
// Equation (4-167), page 171
Real a =
std::pow(2.475 * std::log(1.0 / (std::pow(7.0 / Re_limit, 0.9) + 0.27 * roughness / Dh)), 16);
// Equation (4-168), page 171
Real b = std::pow(3.753e4 / Re_limit, 16);
// Equation (4-166), page 171
return 2.0 * std::pow(std::pow(8.0 / Re_limit, 12) + 1.0 / std::pow(a + b, 1.5), 1.0 / 12.0);
}
}
<commit_msg>Fixed Churchill correlation constant<commit_after>#include "WallFrictionModels.h"
#include "Numerics.h"
namespace WallFriction
{
Real
Churchill(Real Re, Real roughness, Real Dh)
{
Real Re_limit = std::max(Re, 10.0);
Real a =
std::pow(2.457 * std::log(1.0 / (std::pow(7.0 / Re_limit, 0.9) + 0.27 * roughness / Dh)), 16);
Real b = std::pow(3.753e4 / Re_limit, 16);
return 2.0 * std::pow(std::pow(8.0 / Re_limit, 12) + 1.0 / std::pow(a + b, 1.5), 1.0 / 12.0);
}
}
<|endoftext|>
|
<commit_before>/**
* @file ct2ctml.cpp
* Driver for the system call to the python executable that converts
* cti files to ctml files (see \ref inputfiles).
*/
// Copyright 2001-2005 California Institute of Technology
#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"
#include <fstream>
#include <sstream>
#ifdef _WIN32
#include <windows.h>
#endif
using namespace Cantera;
using namespace std;
namespace ctml
{
//! return the full path to the Python interpreter.
/*!
* Use the environment variable PYTHON_CMD if it is set. If not, return
* the string 'python'.
*
* Note, there are hidden problems here that really direct us to use
* a full pathname for the location of python. Basically the system
* call will use the shell /bin/sh, in order to launch python.
* This default shell may not be the shell that the user is employing.
* Therefore, the default path to python may be different during
* a system call than during the default user shell environment.
* This is quite a headache. The answer is to always set the
* PYTHON_CMD environmental variable in the user environment to
* an absolute path to locate the python executable. Then this
* issue goes away.
*/
static string pypath()
{
string s = "python";
const char* py = getenv("PYTHON_CMD");
if (py) {
string sp = stripws(string(py));
if (sp.size() > 0) {
s = sp;
}
}
return s;
}
void ct2ctml(const char* file, const int debug)
{
string xml = ct2ctml_string(file);
string out_name = file;
#ifdef _WIN32
// For Windows, make the path POSIX compliant so code looking for directory
// separators is simpler. Just look for '/' not both '/' and '\\'
std::replace_if(out_name.begin(), out_name.end(),
std::bind2nd(std::equal_to<char>(), '\\'), '/') ;
#endif
size_t idir = out_name.rfind('/');
if (idir != npos) {
out_name = out_name.substr(idir+1, out_name.size());
}
size_t idot = out_name.rfind('.');
if (idot != npos) {
out_name = out_name.substr(0, idot) + ".xml";
} else {
out_name += ".xml";
}
std::ofstream out(out_name.c_str());
out << xml;
}
static std::string call_ctml_writer(const std::string& text, bool isfile)
{
std::string file, arg;
if (isfile) {
file = text;
arg = "r'" + text + "'";
} else {
file = "<string>";
arg = "text=r'''" + text + "'''";
}
#ifdef HAS_NO_PYTHON
/*
* Section to bomb out if python is not
* present in the computation environment.
*/
throw CanteraError("ct2ctml",
"python cti to ctml conversion requested for file, " + file +
", but not available in this computational environment");
#endif
string python_output, error_output;
int python_exit_code;
try {
exec_stream_t python;
python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
stringstream output_stream, error_stream;
std::vector<string> args;
args.push_back("-c");
args.push_back(
"from __future__ import print_function\n"
"import sys\n"
"try:\n"
" from cantera import ctml_writer\n"
"except ImportError:\n"
" print('sys.path: ' + repr(sys.path) + '\\n', file=sys.stderr)\n"
" raise\n"
"ctml_writer.convert(" + arg + ", outName='STDOUT')\n"
"sys.exit(0)\n");
python.start(pypath(), args.begin(), args.end());
std::string line;
while (python.out().good()) {
std::getline(python.out(), line);
output_stream << line << std::endl;
}
#ifdef _WIN32
// Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while
// reading from the stream.
Sleep(1);
#endif
while (python.err().good()) {
std::getline(python.err(), line);
error_stream << line << std::endl;
}
python.close();
python_exit_code = python.exit_code();
error_output = stripws(error_stream.str());
python_output = output_stream.str();
} catch (std::exception& err) {
// Report failure to execute Python
stringstream message;
message << "Error executing python while converting input file:\n";
message << "Python command was: '" << pypath() << "'\n";
message << err.what() << std::endl;
throw CanteraError("ct2ctml_string", message.str());
}
if (python_exit_code != 0) {
// Report a failure in the conversion process
stringstream message;
message << "Error converting input file \"" << file << "\" to CTML.\n";
message << "Python command was: '" << pypath() << "'\n";
message << "The exit code was: " << python_exit_code << "\n";
if (error_output.size() > 0) {
message << "-------------- start of converter log --------------\n";
message << error_output << std::endl;
message << "--------------- end of converter log ---------------";
} else {
message << "The command did not produce any output." << endl;
}
throw CanteraError("ct2ctml_string", message.str());
}
if (error_output.size() > 0) {
// Warn if there was any output from the conversion process
stringstream message;
message << "Warning: Unexpected output from CTI converter\n";
message << "-------------- start of converter log --------------\n";
message << error_output << std::endl;
message << "--------------- end of converter log ---------------\n";
writelog(message.str());
}
return python_output;
}
std::string ct2ctml_string(const std::string& file)
{
return call_ctml_writer(file, true);
}
std::string ct_string2ctml_string(const std::string& cti)
{
return call_ctml_writer(cti, false);
}
void ck2cti(const std::string& in_file, const std::string& thermo_file,
const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
/*
* Section to bomb out if python is not
* present in the computation environment.
*/
string ppath = in_file;
throw CanteraError("ct2ctml",
"python ck to cti conversion requested for file, " + ppath +
", but not available in this computational environment");
#endif
string python_output;
int python_exit_code;
try {
exec_stream_t python;
python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
python.start(pypath(), "-i");
stringstream output_stream;
ostream& pyin = python.in();
pyin << "if True:\n" << // Use this so that the rest is a single block
" import sys\n" <<
" sys.stderr = sys.stdout\n" <<
" try:\n" <<
" from cantera import ck2cti\n" <<
" except ImportError:\n" <<
" print('sys.path: ' + repr(sys.path))\n" <<
" raise\n"
" ck2cti.Parser().convertMech(r'" << in_file << "',";
if (thermo_file != "" && thermo_file != "-") {
pyin << " thermoFile=r'" << thermo_file << "',";
}
if (transport_file != "" && transport_file != "-") {
pyin << " transportFile=r'" << transport_file << "',";
}
pyin << " phaseName='" << id_tag << "',";
pyin << " permissive=True,";
pyin << " quiet=True)\n";
pyin << " sys.exit(0)\n\n";
pyin << "sys.exit(7)\n";
python.close_in();
std::string line;
while (python.out().good()) {
std::getline(python.out(), line);
output_stream << line << std::endl;;
}
python.close();
python_exit_code = python.exit_code();
python_output = stripws(output_stream.str());
} catch (std::exception& err) {
// Report failure to execute Python
stringstream message;
message << "Error executing python while converting input file:\n";
message << "Python command was: '" << pypath() << "'\n";
message << err.what() << std::endl;
throw CanteraError("ct2ctml", message.str());
}
if (python_exit_code != 0) {
// Report a failure in the conversion process
stringstream message;
message << "Error converting input file \"" << in_file << "\" to CTI.\n";
message << "Python command was: '" << pypath() << "'\n";
message << "The exit code was: " << python_exit_code << "\n";
if (python_output.size() > 0) {
message << "-------------- start of converter log --------------\n";
message << python_output << std::endl;
message << "--------------- end of converter log ---------------";
} else {
message << "The command did not produce any output." << endl;
}
throw CanteraError("ck2cti", message.str());
}
if (python_output.size() > 0) {
// Warn if there was any output from the conversion process
stringstream message;
message << "Warning: Unexpected output from CTI converter\n";
message << "-------------- start of converter log --------------\n";
message << python_output << std::endl;
message << "--------------- end of converter log ---------------\n";
writelog(message.str());
}
}
void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)
{
warn_deprecated("get_CTML_Tree", "To be removed after Cantera 2.2. "
"Use get_XML_File instead.");
XML_Node* src = get_XML_File(file);
src->copy(rootPtr);
}
Cantera::XML_Node getCtmlTree(const std::string& file)
{
warn_deprecated("getCtmlTree", "To be removed after Cantera 2.2. "
"Use get_XML_File instead.");
XML_Node root;
XML_Node* src = get_XML_File(file);
src->copy(&root);
return root;
}
}
<commit_msg>Fix compilation with Visual Studio 2013<commit_after>/**
* @file ct2ctml.cpp
* Driver for the system call to the python executable that converts
* cti files to ctml files (see \ref inputfiles).
*/
// Copyright 2001-2005 California Institute of Technology
#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"
#include <fstream>
#include <sstream>
#include <functional>
#ifdef _WIN32
#include <windows.h>
#endif
using namespace Cantera;
using namespace std;
namespace ctml
{
//! return the full path to the Python interpreter.
/*!
* Use the environment variable PYTHON_CMD if it is set. If not, return
* the string 'python'.
*
* Note, there are hidden problems here that really direct us to use
* a full pathname for the location of python. Basically the system
* call will use the shell /bin/sh, in order to launch python.
* This default shell may not be the shell that the user is employing.
* Therefore, the default path to python may be different during
* a system call than during the default user shell environment.
* This is quite a headache. The answer is to always set the
* PYTHON_CMD environmental variable in the user environment to
* an absolute path to locate the python executable. Then this
* issue goes away.
*/
static string pypath()
{
string s = "python";
const char* py = getenv("PYTHON_CMD");
if (py) {
string sp = stripws(string(py));
if (sp.size() > 0) {
s = sp;
}
}
return s;
}
void ct2ctml(const char* file, const int debug)
{
string xml = ct2ctml_string(file);
string out_name = file;
#ifdef _WIN32
// For Windows, make the path POSIX compliant so code looking for directory
// separators is simpler. Just look for '/' not both '/' and '\\'
std::replace_if(out_name.begin(), out_name.end(),
std::bind2nd(std::equal_to<char>(), '\\'), '/') ;
#endif
size_t idir = out_name.rfind('/');
if (idir != npos) {
out_name = out_name.substr(idir+1, out_name.size());
}
size_t idot = out_name.rfind('.');
if (idot != npos) {
out_name = out_name.substr(0, idot) + ".xml";
} else {
out_name += ".xml";
}
std::ofstream out(out_name.c_str());
out << xml;
}
static std::string call_ctml_writer(const std::string& text, bool isfile)
{
std::string file, arg;
if (isfile) {
file = text;
arg = "r'" + text + "'";
} else {
file = "<string>";
arg = "text=r'''" + text + "'''";
}
#ifdef HAS_NO_PYTHON
/*
* Section to bomb out if python is not
* present in the computation environment.
*/
throw CanteraError("ct2ctml",
"python cti to ctml conversion requested for file, " + file +
", but not available in this computational environment");
#endif
string python_output, error_output;
int python_exit_code;
try {
exec_stream_t python;
python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
stringstream output_stream, error_stream;
std::vector<string> args;
args.push_back("-c");
args.push_back(
"from __future__ import print_function\n"
"import sys\n"
"try:\n"
" from cantera import ctml_writer\n"
"except ImportError:\n"
" print('sys.path: ' + repr(sys.path) + '\\n', file=sys.stderr)\n"
" raise\n"
"ctml_writer.convert(" + arg + ", outName='STDOUT')\n"
"sys.exit(0)\n");
python.start(pypath(), args.begin(), args.end());
std::string line;
while (python.out().good()) {
std::getline(python.out(), line);
output_stream << line << std::endl;
}
#ifdef _WIN32
// Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while
// reading from the stream.
Sleep(1);
#endif
while (python.err().good()) {
std::getline(python.err(), line);
error_stream << line << std::endl;
}
python.close();
python_exit_code = python.exit_code();
error_output = stripws(error_stream.str());
python_output = output_stream.str();
} catch (std::exception& err) {
// Report failure to execute Python
stringstream message;
message << "Error executing python while converting input file:\n";
message << "Python command was: '" << pypath() << "'\n";
message << err.what() << std::endl;
throw CanteraError("ct2ctml_string", message.str());
}
if (python_exit_code != 0) {
// Report a failure in the conversion process
stringstream message;
message << "Error converting input file \"" << file << "\" to CTML.\n";
message << "Python command was: '" << pypath() << "'\n";
message << "The exit code was: " << python_exit_code << "\n";
if (error_output.size() > 0) {
message << "-------------- start of converter log --------------\n";
message << error_output << std::endl;
message << "--------------- end of converter log ---------------";
} else {
message << "The command did not produce any output." << endl;
}
throw CanteraError("ct2ctml_string", message.str());
}
if (error_output.size() > 0) {
// Warn if there was any output from the conversion process
stringstream message;
message << "Warning: Unexpected output from CTI converter\n";
message << "-------------- start of converter log --------------\n";
message << error_output << std::endl;
message << "--------------- end of converter log ---------------\n";
writelog(message.str());
}
return python_output;
}
std::string ct2ctml_string(const std::string& file)
{
return call_ctml_writer(file, true);
}
std::string ct_string2ctml_string(const std::string& cti)
{
return call_ctml_writer(cti, false);
}
void ck2cti(const std::string& in_file, const std::string& thermo_file,
const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
/*
* Section to bomb out if python is not
* present in the computation environment.
*/
string ppath = in_file;
throw CanteraError("ct2ctml",
"python ck to cti conversion requested for file, " + ppath +
", but not available in this computational environment");
#endif
string python_output;
int python_exit_code;
try {
exec_stream_t python;
python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
python.start(pypath(), "-i");
stringstream output_stream;
ostream& pyin = python.in();
pyin << "if True:\n" << // Use this so that the rest is a single block
" import sys\n" <<
" sys.stderr = sys.stdout\n" <<
" try:\n" <<
" from cantera import ck2cti\n" <<
" except ImportError:\n" <<
" print('sys.path: ' + repr(sys.path))\n" <<
" raise\n"
" ck2cti.Parser().convertMech(r'" << in_file << "',";
if (thermo_file != "" && thermo_file != "-") {
pyin << " thermoFile=r'" << thermo_file << "',";
}
if (transport_file != "" && transport_file != "-") {
pyin << " transportFile=r'" << transport_file << "',";
}
pyin << " phaseName='" << id_tag << "',";
pyin << " permissive=True,";
pyin << " quiet=True)\n";
pyin << " sys.exit(0)\n\n";
pyin << "sys.exit(7)\n";
python.close_in();
std::string line;
while (python.out().good()) {
std::getline(python.out(), line);
output_stream << line << std::endl;;
}
python.close();
python_exit_code = python.exit_code();
python_output = stripws(output_stream.str());
} catch (std::exception& err) {
// Report failure to execute Python
stringstream message;
message << "Error executing python while converting input file:\n";
message << "Python command was: '" << pypath() << "'\n";
message << err.what() << std::endl;
throw CanteraError("ct2ctml", message.str());
}
if (python_exit_code != 0) {
// Report a failure in the conversion process
stringstream message;
message << "Error converting input file \"" << in_file << "\" to CTI.\n";
message << "Python command was: '" << pypath() << "'\n";
message << "The exit code was: " << python_exit_code << "\n";
if (python_output.size() > 0) {
message << "-------------- start of converter log --------------\n";
message << python_output << std::endl;
message << "--------------- end of converter log ---------------";
} else {
message << "The command did not produce any output." << endl;
}
throw CanteraError("ck2cti", message.str());
}
if (python_output.size() > 0) {
// Warn if there was any output from the conversion process
stringstream message;
message << "Warning: Unexpected output from CTI converter\n";
message << "-------------- start of converter log --------------\n";
message << python_output << std::endl;
message << "--------------- end of converter log ---------------\n";
writelog(message.str());
}
}
void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)
{
warn_deprecated("get_CTML_Tree", "To be removed after Cantera 2.2. "
"Use get_XML_File instead.");
XML_Node* src = get_XML_File(file);
src->copy(rootPtr);
}
Cantera::XML_Node getCtmlTree(const std::string& file)
{
warn_deprecated("getCtmlTree", "To be removed after Cantera 2.2. "
"Use get_XML_File instead.");
XML_Node root;
XML_Node* src = get_XML_File(file);
src->copy(&root);
return root;
}
}
<|endoftext|>
|
<commit_before>#include <QCoreApplication>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include "Tests/Unit/Network/TestNetworkBalancer.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/ui/text/TestRunner.h>
using namespace std;
using namespace CppUnit;
//------------ Type and operation definitions problem #1 of TID Test -------------------------//
/* @brief Pair of two unsigned int elements */
typedef std::pair<unsigned int, unsigned int > t_PairIntInt;
/* @brief Pair of a strin element and a unsigned int element */
typedef std::pair<std::string, unsigned int > t_PairStrInt;
struct lexiComparePairFirst : public std::unary_function<t_PairIntInt, bool>
{
/**
* @brief The lexiComparePairFirst struct Definition of a lexicographical
* comparison procedure between to std::pair<uint, uint> elements
*/
bool operator ()( const t_PairIntInt& p1, const t_PairIntInt& p2 ) const
{
return std::to_string( p1.first ) < std::to_string( p2.first );
}
};
/* @brief Set of int-int pairs, with custom '<' operator comparison */
typedef std::set< t_PairIntInt, lexiComparePairFirst > t_OrderedSetIntInt;
/* @brief Set of string-int pairs, with standard '<' operator comparison */
typedef std::set< t_PairStrInt > t_OrderedSetStrInt;
int main(int argc, char *argv[])
{
//---------------- PROPOSED SOLUTION to problem #3 of TID Test ---------------------------//
// Initialice test runner
CppUnit::TextUi::TestRunner aRunner;
// Add network balancer test suite
aRunner.addTest( TestNetworkBalancer::suite() );
// Start test runner
aRunner.run();
//---------------- PROPOSED SOLUTION to problem #1 of TID Test ---------------------------//
// <STR, INT>
t_OrderedSetStrInt aSetStr;
// Fill in the map in an unordered fashion
aSetStr.insert( std::make_pair( "alpha", 2 ) );
aSetStr.insert( std::make_pair( "beta" , 3 ) );
aSetStr.insert( std::make_pair( "gamma" , 5 ) );
aSetStr.insert( std::make_pair( "alfalfa" , 1 ) );
aSetStr.insert( std::make_pair( "gama_alta" , 4 ) );
// Print str-int map
std::cout << "Map <str, int> contains:\n";
for( t_OrderedSetStrInt::iterator it = aSetStr.begin();
it !=aSetStr.end(); it++ )
{
std::cout << it->first << " => " << it->second << '\n';
}
std::cout << '\n';
// <INT, INT>
t_OrderedSetIntInt aSetInt;
// Fill in the map in an unordered fashion
aSetInt.insert( std::make_pair( 34, 3 ) );
aSetInt.insert( std::make_pair( 998 , 5 ) );
aSetInt.insert( std::make_pair( 14327 , 1 ) );
aSetInt.insert( std::make_pair( 335 , 2 ) );
aSetInt.insert( std::make_pair( 99799 , 4 ) );
// Print int-int map
std::cout << "Map <int, int> contains:\n";
for( t_OrderedSetIntInt::iterator it = aSetInt.begin();
it !=aSetInt.end(); it++ )
{
std::cout << it->first << " => " << it->second << '\n';
}
std::cout << '\n';
return( 0 );
}
<commit_msg>Corrected mistake in cout<commit_after>#include <QCoreApplication>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include "Tests/Unit/Network/TestNetworkBalancer.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/ui/text/TestRunner.h>
using namespace std;
using namespace CppUnit;
//------------ Type and operation definitions problem #1 of TID Test -------------------------//
/* @brief Pair of two unsigned int elements */
typedef std::pair<unsigned int, unsigned int > t_PairIntInt;
/* @brief Pair of a strin element and a unsigned int element */
typedef std::pair<std::string, unsigned int > t_PairStrInt;
struct lexiComparePairFirst : public std::unary_function<t_PairIntInt, bool>
{
/**
* @brief The lexiComparePairFirst struct Definition of a lexicographical
* comparison procedure between to std::pair<uint, uint> elements
*/
bool operator ()( const t_PairIntInt& p1, const t_PairIntInt& p2 ) const
{
return std::to_string( p1.first ) < std::to_string( p2.first );
}
};
/* @brief Set of int-int pairs, with custom '<' operator comparison */
typedef std::set< t_PairIntInt, lexiComparePairFirst > t_OrderedSetIntInt;
/* @brief Set of string-int pairs, with standard '<' operator comparison */
typedef std::set< t_PairStrInt > t_OrderedSetStrInt;
int main(int argc, char *argv[])
{
//---------------- PROPOSED SOLUTION to problem #3 of TID Test ---------------------------//
// Initialice test runner
CppUnit::TextUi::TestRunner aRunner;
// Add network balancer test suite
aRunner.addTest( TestNetworkBalancer::suite() );
// Start test runner
aRunner.run();
//---------------- PROPOSED SOLUTION to problem #1 of TID Test ---------------------------//
// <STR, INT>
t_OrderedSetStrInt aSetStr;
// Fill in the map in an unordered fashion
aSetStr.insert( std::make_pair( "alpha", 2 ) );
aSetStr.insert( std::make_pair( "beta" , 3 ) );
aSetStr.insert( std::make_pair( "gamma" , 5 ) );
aSetStr.insert( std::make_pair( "alfalfa" , 1 ) );
aSetStr.insert( std::make_pair( "gama_alta" , 4 ) );
// Print str-int map
std::cout << "Set <str, int> contains:\n";
for( t_OrderedSetStrInt::iterator it = aSetStr.begin();
it !=aSetStr.end(); it++ )
{
std::cout << it->first << " => " << it->second << '\n';
}
std::cout << '\n';
// <INT, INT>
t_OrderedSetIntInt aSetInt;
// Fill in the map in an unordered fashion
aSetInt.insert( std::make_pair( 34, 3 ) );
aSetInt.insert( std::make_pair( 998 , 5 ) );
aSetInt.insert( std::make_pair( 14327 , 1 ) );
aSetInt.insert( std::make_pair( 335 , 2 ) );
aSetInt.insert( std::make_pair( 99799 , 4 ) );
// Print int-int map
std::cout << "Set <int, int> contains:\n";
for( t_OrderedSetIntInt::iterator it = aSetInt.begin();
it !=aSetInt.end(); it++ )
{
std::cout << it->first << " => " << it->second << '\n';
}
std::cout << '\n';
return( 0 );
}
<|endoftext|>
|
<commit_before>//////////////
// Includes //
#include <iostream>
//////////
// Code //
int main() {
std::cout << "Hello world!\n";
return 0;
}
<commit_msg>Fleshed out the command-line front end.<commit_after>//////////////
// Includes //
#include <iostream>
#include "processing.hpp"
#include "graph.hpp"
#include "io.hpp"
//////////
// Code //
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "Proper usage: sinterklooser <data file>\n";
return 1;
}
Graph* g = loadGraph(std::string(argv[1]));
if (g == nullptr) {
std::cerr << "Could not load the file " << argv[1] << "!\n";
return 2;
}
printPairing(g, findPairing(g));
delete g;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
* All rights reserved.
*/
#include <random>
#include <cstdlib>
#include <iostream>
#include "common/log.h"
#include "procedural/terrain.h"
#include "procedural/radial_algorithm.h"
#include "procedural/lake_radial.h"
#include "luaint/common.h"
int main(int argc, char** argv)
{
using namespace game;
Scoped_Log_Init log_init{};
strat::Grid_Map map;
map.allocate({2048, 2048});
std::random_device rand_dev;
std::mt19937 prng{rand_dev()};
strat::Terrain_Params terrain_params;
terrain_params.seed = prng();
auto landmass_gen = std::make_unique<strat::Radial_Algorithm>();
landmass_gen->origin = map.extents / 2;
landmass_gen->radius = 724.0f;
landmass_gen->amplitude = 300.0f;
landmass_gen->frequency = 1.0f;
landmass_gen->persistence = .5f;
landmass_gen->lacunarity = 2.0f;
landmass_gen->octaves = 8;
landmass_gen->type = strat::Cell_Type::Land;
terrain_params.landmass_gen = std::move(landmass_gen);
auto natural_gen = std::make_unique<strat::Lake_Radial_Algorithm>();
natural_gen->max_lakes = 100;
natural_gen->lake_probability = .9f;
natural_gen->min_radius = 10.0f;
natural_gen->max_radius = 60.0f;
natural_gen->amplitude = 9.0f;
natural_gen->frequency = .7f;
natural_gen->persistence = .5f;
natural_gen->lacunarity = 2.0f;
natural_gen->octaves = 3;
terrain_params.natural_gen = std::move(natural_gen);
if(argc >= 2)
{
std::string dir_name = argv[1];
auto L = luaint::init_lua();
log_w("Amount of mod types %", luaint::num_mod_types(*L));
luaint::load_mod(*L, dir_name);
log_w("Number of registered mods %", luaint::registered_mods(*L));
luaint::uninit_lua(L);
}
strat::terrain_v1_map(map, terrain_params);
strat::write_png_heightmap(map, "terrain.png");
return 0;
}
<commit_msg>Change lake gen settings<commit_after>/*
* Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
* All rights reserved.
*/
#include <random>
#include <cstdlib>
#include <iostream>
#include "common/log.h"
#include "procedural/terrain.h"
#include "procedural/radial_algorithm.h"
#include "procedural/lake_radial.h"
#include "luaint/common.h"
int main(int argc, char** argv)
{
using namespace game;
Scoped_Log_Init log_init{};
strat::Grid_Map map;
map.allocate({2048, 2048});
std::random_device rand_dev;
std::mt19937 prng{rand_dev()};
strat::Terrain_Params terrain_params;
terrain_params.seed = prng();
auto landmass_gen = std::make_unique<strat::Radial_Algorithm>();
landmass_gen->origin = map.extents / 2;
landmass_gen->radius = 724.0f;
landmass_gen->amplitude = 300.0f;
landmass_gen->frequency = 1.0f;
landmass_gen->persistence = .5f;
landmass_gen->lacunarity = 2.0f;
landmass_gen->octaves = 8;
landmass_gen->type = strat::Cell_Type::Land;
terrain_params.landmass_gen = std::move(landmass_gen);
auto natural_gen = std::make_unique<strat::Lake_Radial_Algorithm>();
natural_gen->max_lakes = 30;
natural_gen->lake_probability = .333f;
natural_gen->min_radius = 40.0f;
natural_gen->max_radius = 100.0f;
natural_gen->amplitude = 35.0f;
natural_gen->frequency = .8f;
natural_gen->persistence = .5f;
natural_gen->lacunarity = 2.0f;
natural_gen->octaves = 3;
terrain_params.natural_gen = std::move(natural_gen);
if(argc >= 2)
{
std::string dir_name = argv[1];
auto L = luaint::init_lua();
log_w("Amount of mod types %", luaint::num_mod_types(*L));
luaint::load_mod(*L, dir_name);
log_w("Number of registered mods %", luaint::registered_mods(*L));
luaint::uninit_lua(L);
}
strat::terrain_v1_map(map, terrain_params);
strat::write_png_heightmap(map, "terrain.png");
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <chrono>
#include <cxxopts.hpp>
#include "mpihead.hpp"
#include "logging.hpp"
#include "epa.hpp"
#include "Binary_Fasta.hpp"
static void ensure_dir_has_slash(std::string& dir)
{
if (dir.length() > 0 && dir.back() != '/') {
dir += "/";
}
}
static std::vector<std::string> split_by_delimiter(const std::string & text, const std::string delim)
{
std::vector<std::string> parts;
size_t start = 0;
size_t end = 0;
do
{
end = text.find(delim, start);
end = (end != std::string::npos) ? end : text.length();
parts.emplace_back(text.substr(start, end - start));
start = end + delim.length();
} while (end != std::string::npos and start <= text.length());
return parts;
}
void exit_epa(int ret=EXIT_SUCCESS)
{
MPI_FINALIZE();
std::exit(ret);
}
int main(int argc, char** argv)
{
genesis::utils::Logging::log_to_stdout();
genesis::utils::Logging::max_level(genesis::utils::Logging::kInfo);
MPI_INIT(&argc, &argv);
std::string invocation("");
std::string sequence_type("DNA");
std::string model_id("GTR");
std::string sub_matrix("");
Options options;
for (int i = 0; i < argc; ++i) {
invocation += argv[i];
invocation += " ";
}
std::string query_file("");
std::string work_dir("");
std::string tree_file("");
std::string reference_file("");
std::string binary_file("");
std::string banner;
Model model;
try
{
cxxopts::Options cli(argv[0], "Massively-Parallel Evolutionary Placement Algorithm");
cli.add_options()
("help", "Display help.")
("v,version", "Display version.")
("verbose", "Display debug information.")
;
cli.add_options("Input")
("t,tree", "Path to Reference Tree file.", cxxopts::value<std::string>())
("s,ref-msa", "Path to Reference MSA file.", cxxopts::value<std::string>())
("q,query", "Path to Query MSA file.", cxxopts::value<std::string>())
("b,binary", "Path to Binary file.", cxxopts::value<std::string>())
;
cli.add_options("Output")
("w,outdir", "Path to output directory.",
cxxopts::value<std::string>()->default_value("./"))
("B,dump-binary",
"Binary Dump mode: write ref. tree in binary format then exit.")
("c,bfast",
"Convert the given fasta file to bfast format needed for running EPA-ng with MPI",
cxxopts::value<std::string>())
("filter-acc-lwr",
"Accumulated likelihood weight after which further placements are discarded.",
cxxopts::value<double>()->default_value("0.9999"))
("filter-min-lwr",
"Minimum likelihood weight below which a placement is discarded.",
cxxopts::value<double>())
("filter-min",
"Minimum number of placements per sequence to include in final output.",
cxxopts::value<unsigned int>()->default_value("1"))
("filter-max",
"Maximum number of placements per sequence to include in final output.",
cxxopts::value<unsigned int>())
;
cli.add_options("Compute")
("O,opt-ref-tree", "Optimize reference tree and model parameters.")
("raxml-blo",
"Employ old style of branch length optimization during thorough insertion as opposed to sliding approach. "
"WARNING: may significantly slow down computation.")
("no-repeats",
"Do NOT employ site repeats optimization. (not recommended, will increase memory footprint without improving runtime or quality) ")
("g,dyn-heur",
"Two-phase heuristic, determination of candidate edges using accumulative threshold.",
cxxopts::value<double>()->implicit_value("0.99"))
("G,fix-heur",
"Two-phase heuristic, determination of candidate edges by specified percentage of total edges.",
cxxopts::value<double>()->implicit_value("0.1"))
("m,model",
"Description string of the model to be used. Format: "
"<type>-<symmetries>-<rate/frequency model> Examples: -m DNA-GTR-EMPIRICAL, -m AA-GTR-BLOSUM62",
cxxopts::value<std::string>()->default_value("DNA-GTR-EMPIRICAL"))
("base-freqs",
"Base frequencies to be used. Must match alphabet size. Overwritten by -O. Example: "
"--base-freqs 0.2:0.3:0.25:0.25",
cxxopts::value<std::string>())
("sub-rates",
"Substitution rates to be used. Must correspond to alphabet size (e.g. 6 for DNA). Overwritten by -O. "
"Order: A-C, A-G, A-T, C-G, C-T, G-T "
"Example: --sub-rates 0.88:2.0:1.31:0.86:3.48:1.0",
cxxopts::value<std::string>())
("alpha",
"Alpha parameter to be used. Overwritten by -O. "
"Example: --alpha 0.634016",
cxxopts::value<double>())
;
cli.add_options("Pipeline")
("chunk-size",
"Number of query sequences to be read in at a time. May influence performance.",
cxxopts::value<unsigned int>()->default_value("1000"))
#ifdef __OMP
("T,threads",
"Number of threads to use. If 0 is passed as argument, program will run with the maximum number "
"of threads available.",
cxxopts::value<unsigned int>()->default_value("0"))
#endif
;
cli.parse(argc, argv);
if (cli.count("help")) {
std::cout << cli.help({"", "Input", "Output", "Compute", "Pipeline"});
exit_epa();
}
if (cli.count("verbose")) {
genesis::utils::Logging::max_level(genesis::utils::Logging::kDebug2);
}
if (cli.count("bfast")) {
LOG_INFO << "Converting given FASTA file to BFAST format.";
auto fasta = cli["bfast"].as<std::string>();
LOG_INFO << "Started " << genesis::utils::current_time();
Binary_Fasta::fasta_to_bfast(fasta);
LOG_INFO << "Finished " << genesis::utils::current_time();
exit_epa();
}
// check for valid input combinations
if (not(
( cli.count("tree") and cli.count("ref-msa") )
or ( cli.count("binary") and (cli.count("query") or cli.count("ref-msa")) )
)) {
LOG_INFO << "Must supply reference tree/msa either directly or as precomputed binary.";
exit_epa(EXIT_FAILURE);
}
if (cli.count("query")) query_file = cli["query"].as<std::string>();
if (cli.count("outdir")) work_dir = cli["outdir"].as<std::string>();
if (cli.count("tree")) tree_file = cli["tree"].as<std::string>();
if (cli.count("ref-msa")) reference_file = cli["ref-msa"].as<std::string>();
if (cli.count("binary"))
{
binary_file = cli["binary"].as<std::string>();
options.load_binary_mode = true;
}
if (cli.count("filter-acc-lwr"))
{
options.support_threshold = cli["filter-acc-lwr"].as<double>();
options.acc_threshold = true;
}
if (cli.count("filter-min-lwr"))
{
options.support_threshold = cli["filter-min-lwr"].as<double>();
options.acc_threshold = false;
}
if (cli.count("filter-min"))
{
options.filter_min = cli["filter-min"].as<unsigned int>();
}
if (cli.count("filter-max"))
{
options.filter_max = cli["filter-max"].as<unsigned int>();
}
if (options.filter_min > options.filter_max)
throw std::runtime_error{"filter-min must not exceed filter-max!"};
if (cli.count("fix-heur"))
{
options.prescoring_threshold = cli["fix-heur"].as<double>();
options.prescoring = options.prescoring_by_percentage = true;
}
if (cli.count("dyn-heur"))
{
options.prescoring_threshold = cli["dyn-heur"].as<double>();
if (options.prescoring) {
LOG_INFO << "Cannot use -G and -g concurrently! Running with -g " << options.prescoring_threshold ;
}
options.prescoring = true;
options.prescoring_by_percentage = false;
}
if (cli.count("opt-ref-tree")) options.opt_branches = options.opt_model = true;
if (cli.count("raxml-blo")) options.sliding_blo = false;
if (cli.count("no-repeats")) options.repeats = false;
if (cli.count("dump-binary")) options.dump_binary_mode = true;
if (cli.count("model"))
{
auto parts = split_by_delimiter(cli["model"].as<std::string>(), "-");
auto s = parts.size();
if (s > 3) {
throw std::runtime_error{"Supplied too many model arguments! Must be 3 or less."};
} else {
if (s >=1) {
sequence_type = parts[0];
}
if (s >= 2) {
model_id = parts[1];
}
if (s >= 3) {
sub_matrix = parts[2];
}
LOG_DBG << "Model descriptor: " << sequence_type << " "
<< model_id << " " << sub_matrix << " ";
}
}
model = Model(sequence_type, model_id, sub_matrix);
if (!options.opt_model)
{
if (cli.count("base-freqs"))
{
auto freq_strings = split_by_delimiter(cli["base-freqs"].as<std::string>(), ":");
std::vector<double> freqs;
for (auto& s : freq_strings)
freqs.push_back(std::stod(s));
model.base_frequencies(freqs);
}
if (cli.count("sub-rates"))
{
auto rate_strings = split_by_delimiter(cli["sub-rates"].as<std::string>(), ":");
std::vector<double> rates;
for (auto& s : rate_strings)
rates.push_back(std::stod(s));
model.substitution_rates(rates);
}
if (cli.count("alpha"))
{
model.alpha(cli["alpha"].as<double>());
}
}
if (cli.count("chunk-size")) options.chunk_size = cli["chunk-size"].as<unsigned int>();
if (cli.count("threads")) options.num_threads = cli["threads"].as<unsigned int>();
} catch (const cxxopts::OptionException& e) {
std::cout << "error parsing options: " << e.what() << std::endl;
exit_epa(EXIT_FAILURE);
}
//================================================================
//============ EPA =========================================
//================================================================
ensure_dir_has_slash(work_dir);
#ifdef __MPI
int local_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &local_rank);
if (local_rank != 0) {
genesis::utils::Logging::log_to_stdout(false);
}
genesis::utils::Logging::log_to_file(work_dir + std::to_string(local_rank) + ".epa_info.log");
#else
genesis::utils::Logging::log_to_file(work_dir + "epa_info.log");
#endif
banner += " _____ ______ _____ ";
banner += "\n| __ \\ | ____| __ \\ /\\ ";
banner += "\n| |__) |_____| |__ | |__) / \\ ";
banner += "\n| ___/______| __| | ___/ /\\ \\ ";
banner += "\n| | | |____| | / ____ \\";
banner += "\n|_| |______|_| /_/ \\_\\ \n";
LOG_INFO << banner;
MSA ref_msa;
if (reference_file.size()) {
ref_msa = build_MSA_from_file(reference_file);
}
// build the Tree
Tree tree;
if (options.load_binary_mode) {
LOG_INFO << "Loading from binary";
tree = Tree(binary_file, model, options);
} else {
// build the full tree with all possible clv's
tree = Tree(tree_file, ref_msa, model, options);
}
// build the query stream
MSA_Stream queries;
if (not options.dump_binary_mode) {
if (query_file.size() != 0) {
queries = MSA_Stream(query_file, options.chunk_size);
} else { // attempt to split msa if it is intermingled with (supposed) query sequences
throw std::runtime_error{"Combined MSA files not currently supported, please split them and specify using -s and -q."};
// MSA tmp;
// split_combined_msa(ref_msa, tmp, tree);
}
}
// dump to binary if specified
if (options.dump_binary_mode) {
LOG_INFO << "Writing to binary";
std::string dump_file(work_dir + "epa_binary_file");
dump_to_binary(tree, dump_file);
MPI_FINALIZE();
return EXIT_SUCCESS;
}
// start the placement process and write to file
auto start = std::chrono::high_resolution_clock::now();
// process(tree, queries, work_dir, options, invocation);
// tmp_pipeline_test(tree, queries, work_dir, options, invocation);
simple_mpi(tree, query_file, work_dir, options, invocation);
auto end = std::chrono::high_resolution_clock::now();
auto runtime = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
LOG_INFO << "Time spent placing: " << runtime << "s";
MPI_FINALIZE();
return EXIT_SUCCESS;
}
<commit_msg>added lots of useful info output<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <chrono>
#include <cxxopts.hpp>
#include "mpihead.hpp"
#include "logging.hpp"
#include "epa.hpp"
#include "Binary_Fasta.hpp"
static void ensure_dir_has_slash(std::string& dir)
{
if (dir.length() > 0 && dir.back() != '/') {
dir += "/";
}
}
static std::vector<std::string> split_by_delimiter(const std::string & text, const std::string delim)
{
std::vector<std::string> parts;
size_t start = 0;
size_t end = 0;
do
{
end = text.find(delim, start);
end = (end != std::string::npos) ? end : text.length();
parts.emplace_back(text.substr(start, end - start));
start = end + delim.length();
} while (end != std::string::npos and start <= text.length());
return parts;
}
void exit_epa(int ret=EXIT_SUCCESS)
{
MPI_FINALIZE();
std::exit(ret);
}
int main(int argc, char** argv)
{
genesis::utils::Logging::log_to_stdout();
genesis::utils::Logging::max_level(genesis::utils::Logging::kInfo);
MPI_INIT(&argc, &argv);
std::string invocation("");
std::string sequence_type("DNA");
std::string model_id("GTR");
std::string sub_matrix("");
Options options;
for (int i = 0; i < argc; ++i) {
invocation += argv[i];
invocation += " ";
}
std::string query_file("");
std::string work_dir("");
std::string tree_file("");
std::string reference_file("");
std::string binary_file("");
std::string banner;
Model model;
try
{
cxxopts::Options cli(argv[0], "Massively-Parallel Evolutionary Placement Algorithm");
cli.add_options()
("help", "Display help.")
("v,version", "Display version.")
("verbose", "Display debug information.")
;
cli.add_options("Input")
("t,tree", "Path to Reference Tree file.", cxxopts::value<std::string>())
("s,ref-msa", "Path to Reference MSA file.", cxxopts::value<std::string>())
("q,query", "Path to Query MSA file.", cxxopts::value<std::string>())
("b,binary", "Path to Binary file.", cxxopts::value<std::string>())
;
cli.add_options("Output")
("w,outdir", "Path to output directory.",
cxxopts::value<std::string>()->default_value("./"))
("B,dump-binary",
"Binary Dump mode: write ref. tree in binary format then exit.")
("c,bfast",
"Convert the given fasta file to bfast format needed for running EPA-ng with MPI",
cxxopts::value<std::string>())
("filter-acc-lwr",
"Accumulated likelihood weight after which further placements are discarded.",
cxxopts::value<double>()->default_value("0.9999"))
("filter-min-lwr",
"Minimum likelihood weight below which a placement is discarded.",
cxxopts::value<double>())
("filter-min",
"Minimum number of placements per sequence to include in final output.",
cxxopts::value<unsigned int>()->default_value("1"))
("filter-max",
"Maximum number of placements per sequence to include in final output.",
cxxopts::value<unsigned int>())
;
cli.add_options("Compute")
("O,opt-ref-tree", "Optimize reference tree and model parameters.")
("raxml-blo",
"Employ old style of branch length optimization during thorough insertion as opposed to sliding approach. "
"WARNING: may significantly slow down computation.")
("no-repeats",
"Do NOT employ site repeats optimization. (not recommended, will increase memory footprint without improving runtime or quality) ")
("g,dyn-heur",
"Two-phase heuristic, determination of candidate edges using accumulative threshold.",
cxxopts::value<double>()->implicit_value("0.99"))
("G,fix-heur",
"Two-phase heuristic, determination of candidate edges by specified percentage of total edges.",
cxxopts::value<double>()->implicit_value("0.1"))
("m,model",
"Description string of the model to be used. Format: "
"<type>-<symmetries>-<rate/frequency model> Examples: -m DNA-GTR-EMPIRICAL, -m AA-GTR-BLOSUM62",
cxxopts::value<std::string>()->default_value("DNA-GTR-EMPIRICAL"))
("base-freqs",
"Base frequencies to be used. Must match alphabet size. Overwritten by -O. Example: "
"--base-freqs 0.2:0.3:0.25:0.25",
cxxopts::value<std::string>())
("sub-rates",
"Substitution rates to be used. Must correspond to alphabet size (e.g. 6 for DNA). Overwritten by -O. "
"Order: A-C, A-G, A-T, C-G, C-T, G-T "
"Example: --sub-rates 0.88:2.0:1.31:0.86:3.48:1.0",
cxxopts::value<std::string>())
("alpha",
"Alpha parameter to be used. Overwritten by -O. "
"Example: --alpha 0.634016",
cxxopts::value<double>())
;
cli.add_options("Pipeline")
("chunk-size",
"Number of query sequences to be read in at a time. May influence performance.",
cxxopts::value<unsigned int>()->default_value("1000"))
#ifdef __OMP
("T,threads",
"Number of threads to use. If 0 is passed as argument, program will run with the maximum number "
"of threads available.",
cxxopts::value<unsigned int>()->default_value("0"))
#endif
;
cli.parse(argc, argv);
if (cli.count("help")) {
std::cout << cli.help({"", "Input", "Output", "Compute", "Pipeline"});
exit_epa();
}
if (cli.count("verbose")) {
LOG_INFO << "Selected: verbose (debug) output";
genesis::utils::Logging::max_level(genesis::utils::Logging::kDebug2);
}
if (cli.count("bfast")) {
LOG_INFO << "Converting given FASTA file to BFAST format.";
auto fasta = cli["bfast"].as<std::string>();
LOG_INFO << "Started " << genesis::utils::current_time();
Binary_Fasta::fasta_to_bfast(fasta);
LOG_INFO << "Finished " << genesis::utils::current_time();
exit_epa();
}
// check for valid input combinations
if (not(
( cli.count("tree") and cli.count("ref-msa") )
or ( cli.count("binary") and (cli.count("query") or cli.count("ref-msa")) )
)) {
LOG_INFO << "Must supply reference tree/msa either directly or as precomputed binary.";
exit_epa(EXIT_FAILURE);
}
if (cli.count("query")) {
query_file = cli["query"].as<std::string>();
LOG_INFO << "Selected: Query file: " << query_file;
}
if (cli.count("outdir")) {
work_dir = cli["outdir"].as<std::string>();
LOG_INFO << "Selected: Output dir: " << work_dir;
}
if (cli.count("tree")) {
tree_file = cli["tree"].as<std::string>();
LOG_INFO << "Selected: Tree file: " << tree_file;
}
if (cli.count("ref-msa")) {
reference_file = cli["ref-msa"].as<std::string>();
LOG_INFO << "Selected: Reference MSA: " << reference_file;
}
if (cli.count("binary")) {
binary_file = cli["binary"].as<std::string>();
options.load_binary_mode = true;
LOG_INFO << "Selected: Binary CLV store: " << binary_file;
}
if (cli.count("filter-acc-lwr"))
{
options.support_threshold = cli["filter-acc-lwr"].as<double>();
options.acc_threshold = true;
LOG_INFO << "Selected: Filtering by accumulated threshold: " << options.support_threshold;
}
if (cli.count("filter-min-lwr")) {
options.support_threshold = cli["filter-min-lwr"].as<double>();
options.acc_threshold = false;
LOG_INFO << "Selected: Filtering by minimum threshold: " << options.support_threshold;
}
if (cli.count("filter-min")) {
options.filter_min = cli["filter-min"].as<unsigned int>();
LOG_INFO << "Selected: Minimum number of placements per query: " << options.filter_min;
}
if (cli.count("filter-max")) {
options.filter_max = cli["filter-max"].as<unsigned int>();
LOG_INFO << "Selected: Maximum number of placements per query: " << options.filter_max;
}
if (options.filter_min > options.filter_max) {
throw std::runtime_error{"filter-min must not exceed filter-max!"};
}
if (cli.count("fix-heur")) {
options.prescoring_threshold = cli["fix-heur"].as<double>();
options.prescoring = options.prescoring_by_percentage = true;
LOG_INFO << "Selected: Prescoring by percentage of branches: " << options.prescoring_threshold;
}
if (cli.count("dyn-heur")) {
options.prescoring_threshold = cli["dyn-heur"].as<double>();
if (options.prescoring) {
LOG_INFO << "Cannot use -G and -g concurrently! Running with -g " << options.prescoring_threshold ;
}
options.prescoring = true;
options.prescoring_by_percentage = false;
LOG_INFO << "Selected: Prescoring by accumulated LWR threshold: " << options.prescoring_threshold;
}
if (cli.count("opt-ref-tree")) {
options.opt_branches = options.opt_model = true;
LOG_INFO << "Selected: Optimizing the reference tree branch lengths and model parameters";
if (options.load_binary_mode) {
LOG_INFO << "\tWARNING: this option is ignored as a binary CLV store was supplied!";
}
}
if (cli.count("raxml-blo")) {
options.sliding_blo = false;
LOG_INFO << "Selected: On query insertion, optimize branch lengths the way RAxML-EPA did it";
}
if (cli.count("no-repeats")) {
options.repeats = false;
LOG_INFO << "Selected: Using the non-repeats version of libpll/modules";
}
if (cli.count("dump-binary")) {
options.dump_binary_mode = true;
LOG_INFO << "Selected: Build reference tree and write it out as a binary CLV store (for MPI)";
LOG_INFO << "\tWARNING: this mode means that no placement will take place in this run";
}
if (cli.count("model")) {
auto parts = split_by_delimiter(cli["model"].as<std::string>(), "-");
auto s = parts.size();
if (s > 3) {
throw std::runtime_error{"Supplied too many model arguments! Must be 3 or less."};
} else {
if (s >=1) {
sequence_type = parts[0];
}
if (s >= 2) {
model_id = parts[1];
}
if (s >= 3) {
sub_matrix = parts[2];
}
LOG_DBG << "Model descriptor: " << sequence_type << " "
<< model_id << " " << sub_matrix << " ";
}
LOG_INFO << "Selected: Specified model: " << sequence_type << " "
<< model_id << " " << sub_matrix;
}
model = Model(sequence_type, model_id, sub_matrix);
if (!options.opt_model) {
if (cli.count("base-freqs")) {
auto freq_strings = split_by_delimiter(cli["base-freqs"].as<std::string>(), ":");
std::vector<double> freqs;
for (auto& s : freq_strings)
freqs.push_back(std::stod(s));
model.base_frequencies(freqs);
}
if (cli.count("sub-rates")) {
auto rate_strings = split_by_delimiter(cli["sub-rates"].as<std::string>(), ":");
std::vector<double> rates;
for (auto& s : rate_strings)
rates.push_back(std::stod(s));
model.substitution_rates(rates);
}
if (cli.count("alpha")) {
model.alpha(cli["alpha"].as<double>());
}
}
if (cli.count("chunk-size")) {
options.chunk_size = cli["chunk-size"].as<unsigned int>();
LOG_INFO << "Selected: Reading queries in chunks of: " << options.chunk_size;
}
if (cli.count("threads")) {
options.num_threads = cli["threads"].as<unsigned int>();
LOG_INFO << "Selected: Using threads: " << options.num_threads;
}
} catch (const cxxopts::OptionException& e) {
std::cout << "error parsing options: " << e.what() << std::endl;
exit_epa(EXIT_FAILURE);
}
//================================================================
//============ EPA =========================================
//================================================================
ensure_dir_has_slash(work_dir);
#ifdef __MPI
int local_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &local_rank);
if (local_rank != 0) {
genesis::utils::Logging::log_to_stdout(false);
}
genesis::utils::Logging::log_to_file(work_dir + std::to_string(local_rank) + ".epa_info.log");
#else
genesis::utils::Logging::log_to_file(work_dir + "epa_info.log");
#endif
banner += " _____ ______ _____ ";
banner += "\n| __ \\ | ____| __ \\ /\\ ";
banner += "\n| |__) |_____| |__ | |__) / \\ ";
banner += "\n| ___/______| __| | ___/ /\\ \\ ";
banner += "\n| | | |____| | / ____ \\";
banner += "\n|_| |______|_| /_/ \\_\\ \n";
LOG_INFO << banner;
MSA ref_msa;
if (reference_file.size()) {
ref_msa = build_MSA_from_file(reference_file);
}
// build the Tree
Tree tree;
if (options.load_binary_mode) {
LOG_INFO << "Loading from binary";
tree = Tree(binary_file, model, options);
} else {
// build the full tree with all possible clv's
tree = Tree(tree_file, ref_msa, model, options);
}
// build the query stream
MSA_Stream queries;
if (not options.dump_binary_mode) {
if (query_file.size() != 0) {
queries = MSA_Stream(query_file, options.chunk_size);
} else { // attempt to split msa if it is intermingled with (supposed) query sequences
throw std::runtime_error{"Combined MSA files not currently supported, please split them and specify using -s and -q."};
// MSA tmp;
// split_combined_msa(ref_msa, tmp, tree);
}
} else {
// dump to binary if specified
LOG_INFO << "Writing to binary";
std::string dump_file(work_dir + "epa_binary_file");
dump_to_binary(tree, dump_file);
exit_epa();
}
// start the placement process and write to file
auto start = std::chrono::high_resolution_clock::now();
// process(tree, queries, work_dir, options, invocation);
// tmp_pipeline_test(tree, queries, work_dir, options, invocation);
simple_mpi(tree, query_file, work_dir, options, invocation);
auto end = std::chrono::high_resolution_clock::now();
auto runtime = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
LOG_INFO << "Time spent placing: " << runtime << "s";
MPI_FINALIZE();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Port Object Decleration. Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*/
#ifndef __MEM_PORT_HH__
#define __MEM_PORT_HH__
#include <list>
#include <inttypes.h>
#include "base/misc.hh"
#include "base/range.hh"
#include "mem/packet.hh"
#include "mem/request.hh"
/** This typedef is used to clean up the parameter list of
* getDeviceAddressRanges() and getPeerAddressRanges(). It's declared
* outside the Port object since it's also used by some mem objects.
* Eventually we should move this typedef to wherever Addr is
* defined.
*/
typedef std::list<Range<Addr> > AddrRangeList;
typedef std::list<Range<Addr> >::iterator AddrRangeIter;
/**
* Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*
* Recv accesor functions are being called from the peer interface.
* Send accessor functions are being called from the device the port is
* associated with, and it will call the peer recv. accessor function.
*/
class Port
{
private:
/** Descriptive name (for DPRINTF output) */
const std::string portName;
public:
/**
* Constructor.
*
* @param _name Port name for DPRINTF output. Should include name
* of memory system object to which the port belongs.
*/
Port(const std::string &_name)
: portName(_name)
{ }
/** Return port name (for DPRINTF). */
const std::string &name() const { return portName; }
virtual ~Port() {};
// mey be better to use subclasses & RTTI?
/** Holds the ports status. Currently just that a range recomputation needs
* to be done. */
enum Status {
RangeChange
};
private:
/** A pointer to the peer port. Ports always come in pairs, that way they
can use a standardized interface to communicate between different
memory objects. */
Port *peer;
public:
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
void setPeer(Port *port);
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
Port *getPeer() { return peer; }
protected:
/** These functions are protected because they should only be
* called by a peer port, never directly by any outside object. */
/** Called to recive a timing call from the peer port. */
virtual bool recvTiming(Packet *pkt) = 0;
/** Called to recive a atomic call from the peer port. */
virtual Tick recvAtomic(Packet *pkt) = 0;
/** Called to recive a functional call from the peer port. */
virtual void recvFunctional(Packet *pkt) = 0;
/** Called to recieve a status change from the peer port. */
virtual void recvStatusChange(Status status) = 0;
/** Called by a peer port if the send was unsuccesful, and had to
wait. This shouldn't be valid for response paths (IO Devices).
so it is set to panic if it isn't already defined.
*/
virtual void recvRetry() { panic("??"); }
/** Called by a peer port in order to determine the block size of the
device connected to this port. It sometimes doesn't make sense for
this function to be called, a DMA interface doesn't really have a
block size, so it is defaulted to a panic.
*/
virtual int deviceBlockSize() { panic("??"); }
/** The peer port is requesting us to reply with a list of the ranges we
are responsible for.
@param resp is a list of ranges responded to
@param snoop is a list of ranges snooped
*/
virtual void getDeviceAddressRanges(AddrRangeList &resp,
AddrRangeList &snoop)
{ panic("??"); }
public:
/** Function called by associated memory device (cache, memory, iodevice)
in order to send a timing request to the port. Simply calls the peer
port receive function.
@return This function returns if the send was succesful in it's
recieve. If it was a failure, then the port will wait for a recvRetry
at which point it can possibly issue a successful sendTiming. This is used in
case a cache has a higher priority request come in while waiting for
the bus to arbitrate.
*/
bool sendTiming(Packet *pkt) { return peer->recvTiming(pkt); }
/** Function called by the associated device to send an atomic access,
an access in which the data is moved and the state is updated in one
cycle, without interleaving with other memory accesses.
*/
Tick sendAtomic(Packet *pkt)
{ return peer->recvAtomic(pkt); }
/** Function called by the associated device to send a functional access,
an access in which the data is instantly updated everywhere in the
memory system, without affecting the current state of any block or
moving the block.
*/
void sendFunctional(Packet *pkt)
{ return peer->recvFunctional(pkt); }
/** Called by the associated device to send a status change to the device
connected to the peer interface.
*/
void sendStatusChange(Status status) {peer->recvStatusChange(status); }
/** When a timing access doesn't return a success, some time later the
Retry will be sent.
*/
void sendRetry() { return peer->recvRetry(); }
/** Called by the associated device if it wishes to find out the blocksize
of the device on attached to the peer port.
*/
int peerBlockSize() { return peer->deviceBlockSize(); }
/** Called by the associated device if it wishes to find out the address
ranges connected to the peer ports devices.
*/
void getPeerAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
{ peer->getDeviceAddressRanges(resp, snoop); }
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void readBlob(Addr addr, uint8_t *p, int size);
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void writeBlob(Addr addr, uint8_t *p, int size);
/** Fill size bytes starting at addr with byte value val. This
should not need to be virtual, since it can be implemented in
terms of writeBlob(). However, it shouldn't be
performance-critical either, so it could be if we wanted to.
*/
virtual void memsetBlob(Addr addr, uint8_t val, int size);
private:
/** Internal helper function for read/writeBlob().
*/
void blobHelper(Addr addr, uint8_t *p, int size, Packet::Command cmd);
};
/** A simple functional port that is only meant for one way communication to
* physical memory. It is only meant to be used to load data into memory before
* the simulation begins.
*/
class FunctionalPort : public Port
{
public:
FunctionalPort(const std::string &_name)
: Port(_name)
{}
virtual bool recvTiming(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual Tick recvAtomic(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvFunctional(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvStatusChange(Status status) {}
template <typename T>
inline void write(Addr addr, T d)
{
writeBlob(addr, (uint8_t*)&d, sizeof(T));
}
template <typename T>
inline T read(Addr addr)
{
T d;
readBlob(addr, (uint8_t*)&d, sizeof(T));
return d;
}
};
#endif //__MEM_PORT_HH__
<commit_msg>Fix Port pointer initialization.<commit_after>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Port Object Decleration. Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*/
#ifndef __MEM_PORT_HH__
#define __MEM_PORT_HH__
#include <list>
#include <inttypes.h>
#include "base/misc.hh"
#include "base/range.hh"
#include "mem/packet.hh"
#include "mem/request.hh"
/** This typedef is used to clean up the parameter list of
* getDeviceAddressRanges() and getPeerAddressRanges(). It's declared
* outside the Port object since it's also used by some mem objects.
* Eventually we should move this typedef to wherever Addr is
* defined.
*/
typedef std::list<Range<Addr> > AddrRangeList;
typedef std::list<Range<Addr> >::iterator AddrRangeIter;
/**
* Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*
* Recv accesor functions are being called from the peer interface.
* Send accessor functions are being called from the device the port is
* associated with, and it will call the peer recv. accessor function.
*/
class Port
{
private:
/** Descriptive name (for DPRINTF output) */
const std::string portName;
/** A pointer to the peer port. Ports always come in pairs, that way they
can use a standardized interface to communicate between different
memory objects. */
Port *peer;
public:
/**
* Constructor.
*
* @param _name Port name for DPRINTF output. Should include name
* of memory system object to which the port belongs.
*/
Port(const std::string &_name)
: portName(_name), peer(NULL)
{ }
/** Return port name (for DPRINTF). */
const std::string &name() const { return portName; }
virtual ~Port() {};
// mey be better to use subclasses & RTTI?
/** Holds the ports status. Currently just that a range recomputation needs
* to be done. */
enum Status {
RangeChange
};
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
void setPeer(Port *port);
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
Port *getPeer() { return peer; }
protected:
/** These functions are protected because they should only be
* called by a peer port, never directly by any outside object. */
/** Called to recive a timing call from the peer port. */
virtual bool recvTiming(Packet *pkt) = 0;
/** Called to recive a atomic call from the peer port. */
virtual Tick recvAtomic(Packet *pkt) = 0;
/** Called to recive a functional call from the peer port. */
virtual void recvFunctional(Packet *pkt) = 0;
/** Called to recieve a status change from the peer port. */
virtual void recvStatusChange(Status status) = 0;
/** Called by a peer port if the send was unsuccesful, and had to
wait. This shouldn't be valid for response paths (IO Devices).
so it is set to panic if it isn't already defined.
*/
virtual void recvRetry() { panic("??"); }
/** Called by a peer port in order to determine the block size of the
device connected to this port. It sometimes doesn't make sense for
this function to be called, a DMA interface doesn't really have a
block size, so it is defaulted to a panic.
*/
virtual int deviceBlockSize() { panic("??"); }
/** The peer port is requesting us to reply with a list of the ranges we
are responsible for.
@param resp is a list of ranges responded to
@param snoop is a list of ranges snooped
*/
virtual void getDeviceAddressRanges(AddrRangeList &resp,
AddrRangeList &snoop)
{ panic("??"); }
public:
/** Function called by associated memory device (cache, memory, iodevice)
in order to send a timing request to the port. Simply calls the peer
port receive function.
@return This function returns if the send was succesful in it's
recieve. If it was a failure, then the port will wait for a recvRetry
at which point it can possibly issue a successful sendTiming. This is used in
case a cache has a higher priority request come in while waiting for
the bus to arbitrate.
*/
bool sendTiming(Packet *pkt) { return peer->recvTiming(pkt); }
/** Function called by the associated device to send an atomic access,
an access in which the data is moved and the state is updated in one
cycle, without interleaving with other memory accesses.
*/
Tick sendAtomic(Packet *pkt)
{ return peer->recvAtomic(pkt); }
/** Function called by the associated device to send a functional access,
an access in which the data is instantly updated everywhere in the
memory system, without affecting the current state of any block or
moving the block.
*/
void sendFunctional(Packet *pkt)
{ return peer->recvFunctional(pkt); }
/** Called by the associated device to send a status change to the device
connected to the peer interface.
*/
void sendStatusChange(Status status) {peer->recvStatusChange(status); }
/** When a timing access doesn't return a success, some time later the
Retry will be sent.
*/
void sendRetry() { return peer->recvRetry(); }
/** Called by the associated device if it wishes to find out the blocksize
of the device on attached to the peer port.
*/
int peerBlockSize() { return peer->deviceBlockSize(); }
/** Called by the associated device if it wishes to find out the address
ranges connected to the peer ports devices.
*/
void getPeerAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
{ peer->getDeviceAddressRanges(resp, snoop); }
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void readBlob(Addr addr, uint8_t *p, int size);
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void writeBlob(Addr addr, uint8_t *p, int size);
/** Fill size bytes starting at addr with byte value val. This
should not need to be virtual, since it can be implemented in
terms of writeBlob(). However, it shouldn't be
performance-critical either, so it could be if we wanted to.
*/
virtual void memsetBlob(Addr addr, uint8_t val, int size);
private:
/** Internal helper function for read/writeBlob().
*/
void blobHelper(Addr addr, uint8_t *p, int size, Packet::Command cmd);
};
/** A simple functional port that is only meant for one way communication to
* physical memory. It is only meant to be used to load data into memory before
* the simulation begins.
*/
class FunctionalPort : public Port
{
public:
FunctionalPort(const std::string &_name)
: Port(_name)
{}
virtual bool recvTiming(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual Tick recvAtomic(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvFunctional(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvStatusChange(Status status) {}
template <typename T>
inline void write(Addr addr, T d)
{
writeBlob(addr, (uint8_t*)&d, sizeof(T));
}
template <typename T>
inline T read(Addr addr)
{
T d;
readBlob(addr, (uint8_t*)&d, sizeof(T));
return d;
}
};
#endif //__MEM_PORT_HH__
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <chrono>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
using namespace ::std;
class I2CBus
{
public:
I2CBus(unsigned _busId)
:m_busFd(-1),
m_busPath()
{
ostringstream busDevName;
busDevName << "/dev/i2c-" << _busId;
m_busPath = busDevName.str();
m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC);
if (m_busFd == -1)
{
ostringstream os;
os << "cannot open i2c bus device " << m_busPath << ", error " << errno;
throw runtime_error(os.str());
}
}
~I2CBus()
{
if (m_busFd != -1)
::close(m_busFd);
}
int fd() const { return m_busFd; }
const string& path() const { return m_busPath; }
private:
int m_busFd;
string m_busPath;
};
class I2CDevice
{
public:
I2CDevice(unsigned _busId, unsigned _deviceId)
:m_i2cBus(_busId)
{
if (ioctl(m_i2cBus.fd(), I2C_SLAVE, _deviceId) == -1)
{
ostringstream os;
os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path() << ", error " << errno;
throw runtime_error(os.str());
}
}
int smbusAccess(uint8_t _readWrite, uint8_t _cmd, i2c_smbus_data& _data, size_t _bytes)
{
struct i2c_smbus_ioctl_data args;
args.read_write = _readWrite;
args.command = _cmd;
args.size = _bytes;
args.data = &_data;
return ioctl(m_i2cBus.fd(), I2C_SMBUS, &args);
}
private:
I2CBus m_i2cBus;
};
class MSPControl
{
public:
MSPControl(unsigned _busId, unsigned _deviceId)
:m_i2cDevice(_busId, _deviceId)
{
}
unsigned readWord(unsigned _addr)
{
i2c_smbus_data i2cData;
int res = m_i2cDevice.smbusAccess(I2C_SMBUS_READ, _addr, i2cData, I2C_SMBUS_WORD_DATA);
if (res != 0)
{
ostringstream os;
os << "failed ioctl(SMBUS_READ)";
throw runtime_error(os.str());
}
return i2cData.word;
}
private:
I2CDevice m_i2cDevice;
};
class GPIOControl
{
public:
GPIOControl(unsigned _gpio)
:m_gpioFd(-1),
m_gpioPath()
{
ostringstream gpioCtrlName;
gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value";
m_gpioPath = gpioCtrlName.str();
m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC);
if (m_gpioFd == -1)
{
ostringstream os;
os << "cannot open gpio control " << m_gpioPath;
throw runtime_error(os.str());
}
}
~GPIOControl()
{
if (m_gpioFd != -1)
::close(m_gpioFd);
}
void setValue(unsigned _val)
{
ostringstream valueStream;
valueStream << _val << endl;
const string& value = valueStream.str();
if (::write(m_gpioFd, value.c_str(), value.length()) != value.length())
{
ostringstream os;
os << "cannot set gpio value " << m_gpioPath;
throw runtime_error(os.str());
}
}
const string& path() const { return m_gpioPath; }
private:
int m_gpioFd;
string m_gpioPath;
};
class TrikCoilGun
{
public:
TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId,
unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd,
unsigned _gpioChargeControl, unsigned _gpioDischargeControl)
:m_mspControl(_mspBusId, _mspDeviceId),
m_mspCmdChargeLevel(_mspChargeLevelCmd),
m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd),
m_gpioChargeControl(_gpioChargeControl),
m_gpioDischargeControl(_gpioDischargeControl)
{
m_gpioChargeControl.setValue(0);
m_gpioDischargeControl.setValue(0);
}
~TrikCoilGun()
{
m_gpioChargeControl.setValue(0);
m_gpioDischargeControl.setValue(0);
}
void charge(unsigned _durationMs, unsigned _chargeLevel)
{
const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
const bool waitCharge = _durationMs == 0;
const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);
cerr << "Preparing for charge to level " << _chargeLevel << endl;
bool charging = false;
while (true)
{
if (!waitCharge && chrono::steady_clock::now() >= elapseAt)
break;
const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
if (currentChargeLevel >= _chargeLevel)
{
if (charging)
cerr << "Stop charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
charging = false;
if (waitCharge)
break;
m_gpioChargeControl.setValue(0);
}
else
{
if (!charging)
cerr << "Charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
charging = true;
m_gpioChargeControl.setValue(1);
}
usleep(1000);
}
cerr << "Charge done" << endl;
m_gpioChargeControl.setValue(0);
}
void discharge(unsigned _durationMs, unsigned _zeroChargeLevel)
{
const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
const bool waitDischarge = _durationMs == 0;
const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);
cerr << "Preparing for discharge from level " << m_mspControl.readWord(m_mspCmdChargeLevel)
<< " to level " << _zeroChargeLevel << endl;
while (true)
{
if (!waitDischarge && chrono::steady_clock::now() >= elapseAt)
break;
const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
if (currentChargeLevel <= _zeroChargeLevel)
{
cerr << "Discharged to level " << currentChargeLevel << ", target level " << _zeroChargeLevel << endl;
break;
}
m_gpioDischargeControl.setValue(1);
usleep(1000);
}
cerr << "Discharge done, current level " << m_mspControl.readWord(m_mspCmdChargeLevel)
<< ", target level " << _zeroChargeLevel << endl;
m_gpioDischargeControl.setValue(0);
}
void fire(unsigned _preDelayMs, unsigned _durationMs, unsigned _postDelayMs)
{
m_gpioChargeControl.setValue(0);
usleep(_preDelayMs * 1000);
cerr << "Fire!" << endl;
m_gpioDischargeControl.setValue(1);
usleep(_durationMs * 1000);
m_gpioDischargeControl.setValue(0);
cerr << "Fire done" << endl;
usleep(_postDelayMs * 1000);
}
private:
MSPControl m_mspControl;
unsigned m_mspCmdChargeLevel;
unsigned m_mspCmdDischargeCurrent;
GPIOControl m_gpioChargeControl;
GPIOControl m_gpioDischargeControl;
};
int printUsageHelp()
{
#warning TODO
return 1;
}
int main(int _argc, char* const _argv[])
{
static const char* s_optstring = "h";
static const struct option s_longopts[] = {
{ "help", no_argument, NULL, 0},
{ "msp-i2c-bus", required_argument, NULL, 0}, // 1
{ "msp-i2c-device", required_argument, NULL, 0},
{ "msp-i2c-charge-level", required_argument, NULL, 0},
{ "msp-i2c-discharge-current", required_argument, NULL, 0},
{ "gpio-charge", required_argument, NULL, 0}, // 5
{ "gpio-discharge", required_argument, NULL, 0},
{ "charge-duration", required_argument, NULL, 0}, // 7
{ "charge-level", required_argument, NULL, 0},
{ "fire-predelay", required_argument, NULL, 0}, // 9
{ "fire-duration", required_argument, NULL, 0},
{ "fire-postdelay", required_argument, NULL, 0},
{ "discharge-duration", required_argument, NULL, 0}, // 12
{ "discharge-level", required_argument, NULL, 0},
{ NULL, 0, NULL, 0},
};
int longopt;
int opt;
unsigned mspI2cBusId = 0x2;
unsigned mspI2cDeviceId = 0x48;
unsigned mspChargeLevelCmd = 0x25;
unsigned mspDischargeCurrentCmd = 0x24;
unsigned gpioChargeCtrl = 0x17;
unsigned gpioDischargeCtrl = 0x00;
unsigned chargeDurationMs = 0;
unsigned chargeLevel = 0x200;
unsigned firePreDelayMs = 10;
unsigned fireDurationMs = 10;
unsigned firePostDelayMs = 100;
unsigned dischargeDurationMs = 0;
unsigned dischargeLevel = 0x5;
while ((opt = getopt_long(_argc, _argv, s_optstring, s_longopts, &longopt)) != -1)
{
switch (opt)
{
case 'h': return printUsageHelp();
case 0:
switch (longopt)
{
case 0: return printUsageHelp();
case 1: mspI2cBusId = atoi(optarg); break;
case 2: mspI2cDeviceId = atoi(optarg); break;
case 3: mspChargeLevelCmd = atoi(optarg); break;
case 4: mspDischargeCurrentCmd = atoi(optarg); break;
case 5: gpioChargeCtrl = atoi(optarg); break;
case 6: gpioDischargeCtrl = atoi(optarg); break;
case 7: chargeDurationMs = atoi(optarg); break;
case 8: chargeLevel = atoi(optarg); break;
case 9: firePreDelayMs = atoi(optarg); break;
case 10: fireDurationMs = atoi(optarg); break;
case 11: firePostDelayMs = atoi(optarg); break;
case 12: dischargeDurationMs = atoi(optarg); break;
case 13: dischargeLevel = atoi(optarg); break;
default: return printUsageHelp();
}
break;
default: return printUsageHelp();
}
}
cout << "Charge duration " << chargeDurationMs << "ms, level " << chargeLevel << endl;
cout << "Fire pre-delay " << firePreDelayMs << "ms, duration " << fireDurationMs << "ms, post-delay " << firePostDelayMs << "ms" << endl;
cout << "Discharge duration " << dischargeDurationMs << "ms, level " << dischargeLevel << endl;
TrikCoilGun coilGun(mspI2cBusId, mspI2cDeviceId, mspChargeLevelCmd, mspDischargeCurrentCmd, gpioChargeCtrl, gpioDischargeCtrl);
coilGun.charge(chargeDurationMs, chargeLevel);
coilGun.fire(firePreDelayMs, fireDurationMs, firePostDelayMs);
coilGun.discharge(dischargeDurationMs, dischargeLevel);
}
<commit_msg>Fire duration measure altered<commit_after>#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <chrono>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
using namespace ::std;
class I2CBus
{
public:
I2CBus(unsigned _busId)
:m_busFd(-1),
m_busPath()
{
ostringstream busDevName;
busDevName << "/dev/i2c-" << _busId;
m_busPath = busDevName.str();
m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC);
if (m_busFd == -1)
{
ostringstream os;
os << "cannot open i2c bus device " << m_busPath << ", error " << errno;
throw runtime_error(os.str());
}
}
~I2CBus()
{
if (m_busFd != -1)
::close(m_busFd);
}
int fd() const { return m_busFd; }
const string& path() const { return m_busPath; }
private:
int m_busFd;
string m_busPath;
};
class I2CDevice
{
public:
I2CDevice(unsigned _busId, unsigned _deviceId)
:m_i2cBus(_busId)
{
if (ioctl(m_i2cBus.fd(), I2C_SLAVE, _deviceId) == -1)
{
ostringstream os;
os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path() << ", error " << errno;
throw runtime_error(os.str());
}
}
int smbusAccess(uint8_t _readWrite, uint8_t _cmd, i2c_smbus_data& _data, size_t _bytes)
{
struct i2c_smbus_ioctl_data args;
args.read_write = _readWrite;
args.command = _cmd;
args.size = _bytes;
args.data = &_data;
return ioctl(m_i2cBus.fd(), I2C_SMBUS, &args);
}
private:
I2CBus m_i2cBus;
};
class MSPControl
{
public:
MSPControl(unsigned _busId, unsigned _deviceId)
:m_i2cDevice(_busId, _deviceId)
{
}
unsigned readWord(unsigned _addr)
{
i2c_smbus_data i2cData;
int res = m_i2cDevice.smbusAccess(I2C_SMBUS_READ, _addr, i2cData, I2C_SMBUS_WORD_DATA);
if (res != 0)
{
ostringstream os;
os << "failed ioctl(SMBUS_READ)";
throw runtime_error(os.str());
}
return i2cData.word;
}
private:
I2CDevice m_i2cDevice;
};
class GPIOControl
{
public:
GPIOControl(unsigned _gpio)
:m_gpioFd(-1),
m_gpioPath()
{
ostringstream gpioCtrlName;
gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value";
m_gpioPath = gpioCtrlName.str();
m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC);
if (m_gpioFd == -1)
{
ostringstream os;
os << "cannot open gpio control " << m_gpioPath;
throw runtime_error(os.str());
}
}
~GPIOControl()
{
if (m_gpioFd != -1)
::close(m_gpioFd);
}
void setValue(unsigned _val)
{
ostringstream valueStream;
valueStream << _val << endl;
const string& value = valueStream.str();
if (::write(m_gpioFd, value.c_str(), value.length()) != value.length())
{
ostringstream os;
os << "cannot set gpio value " << m_gpioPath;
throw runtime_error(os.str());
}
}
const string& path() const { return m_gpioPath; }
private:
int m_gpioFd;
string m_gpioPath;
};
class TrikCoilGun
{
public:
TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId,
unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd,
unsigned _gpioChargeControl, unsigned _gpioDischargeControl)
:m_mspControl(_mspBusId, _mspDeviceId),
m_mspCmdChargeLevel(_mspChargeLevelCmd),
m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd),
m_gpioChargeControl(_gpioChargeControl),
m_gpioDischargeControl(_gpioDischargeControl)
{
m_gpioChargeControl.setValue(0);
m_gpioDischargeControl.setValue(0);
}
~TrikCoilGun()
{
m_gpioChargeControl.setValue(0);
m_gpioDischargeControl.setValue(0);
}
void charge(unsigned _durationMs, unsigned _chargeLevel)
{
const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
const bool waitCharge = _durationMs == 0;
const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);
cerr << "Preparing for charge to level " << _chargeLevel << endl;
bool charging = false;
while (true)
{
if (!waitCharge && chrono::steady_clock::now() >= elapseAt)
break;
const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
if (currentChargeLevel >= _chargeLevel)
{
if (charging)
cerr << "Stop charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
charging = false;
if (waitCharge)
break;
m_gpioChargeControl.setValue(0);
}
else
{
if (!charging)
cerr << "Charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
charging = true;
m_gpioChargeControl.setValue(1);
}
usleep(1000);
}
cerr << "Charge done" << endl;
m_gpioChargeControl.setValue(0);
}
void discharge(unsigned _durationMs, unsigned _zeroChargeLevel)
{
const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
const bool waitDischarge = _durationMs == 0;
const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);
cerr << "Preparing for discharge from level " << m_mspControl.readWord(m_mspCmdChargeLevel)
<< " to level " << _zeroChargeLevel << endl;
while (true)
{
if (!waitDischarge && chrono::steady_clock::now() >= elapseAt)
break;
const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
if (currentChargeLevel <= _zeroChargeLevel)
{
cerr << "Discharged to level " << currentChargeLevel << ", target level " << _zeroChargeLevel << endl;
break;
}
m_gpioDischargeControl.setValue(1);
usleep(1000);
}
cerr << "Discharge done, current level " << m_mspControl.readWord(m_mspCmdChargeLevel)
<< ", target level " << _zeroChargeLevel << endl;
m_gpioDischargeControl.setValue(0);
}
void fire(unsigned _preDelayMs, unsigned _durationUs, unsigned _postDelayMs)
{
m_gpioChargeControl.setValue(0);
usleep(_preDelayMs * 1000);
const chrono::steady_clock::time_point& stopFireAt = chrono::steady_clock::now() + chrono::duration<chrono::steady_clock::rep, chrono::microseconds::period>(_durationUs);
cerr << "Fire!" << endl;
m_gpioDischargeControl.setValue(1);
while (chrono::steady_clock::now() >= stopFireAt)
;
m_gpioDischargeControl.setValue(0);
cerr << "Fire done" << endl;
usleep(_postDelayMs * 1000);
}
private:
MSPControl m_mspControl;
unsigned m_mspCmdChargeLevel;
unsigned m_mspCmdDischargeCurrent;
GPIOControl m_gpioChargeControl;
GPIOControl m_gpioDischargeControl;
};
int printUsageHelp()
{
#warning TODO
return 1;
}
int main(int _argc, char* const _argv[])
{
static const char* s_optstring = "h";
static const struct option s_longopts[] = {
{ "help", no_argument, NULL, 0},
{ "msp-i2c-bus", required_argument, NULL, 0}, // 1
{ "msp-i2c-device", required_argument, NULL, 0},
{ "msp-i2c-charge-level", required_argument, NULL, 0},
{ "msp-i2c-discharge-current", required_argument, NULL, 0},
{ "gpio-charge", required_argument, NULL, 0}, // 5
{ "gpio-discharge", required_argument, NULL, 0},
{ "charge-duration", required_argument, NULL, 0}, // 7
{ "charge-level", required_argument, NULL, 0},
{ "fire-predelay", required_argument, NULL, 0}, // 9
{ "fire-duration", required_argument, NULL, 0},
{ "fire-duration-us", required_argument, NULL, 0},
{ "fire-postdelay", required_argument, NULL, 0},
{ "discharge-duration", required_argument, NULL, 0}, // 13
{ "discharge-level", required_argument, NULL, 0},
{ NULL, 0, NULL, 0},
};
int longopt;
int opt;
unsigned mspI2cBusId = 0x2;
unsigned mspI2cDeviceId = 0x48;
unsigned mspChargeLevelCmd = 0x25;
unsigned mspDischargeCurrentCmd = 0x24;
unsigned gpioChargeCtrl = 0x17;
unsigned gpioDischargeCtrl = 0x00;
unsigned chargeDurationMs = 0;
unsigned chargeLevel = 0x200;
unsigned firePreDelayMs = 10;
unsigned fireDurationUs = 1000;
unsigned firePostDelayMs = 100;
unsigned dischargeDurationMs = 0;
unsigned dischargeLevel = 0x5;
while ((opt = getopt_long(_argc, _argv, s_optstring, s_longopts, &longopt)) != -1)
{
switch (opt)
{
case 'h': return printUsageHelp();
case 0:
switch (longopt)
{
case 0: return printUsageHelp();
case 1: mspI2cBusId = atoi(optarg); break;
case 2: mspI2cDeviceId = atoi(optarg); break;
case 3: mspChargeLevelCmd = atoi(optarg); break;
case 4: mspDischargeCurrentCmd = atoi(optarg); break;
case 5: gpioChargeCtrl = atoi(optarg); break;
case 6: gpioDischargeCtrl = atoi(optarg); break;
case 7: chargeDurationMs = atoi(optarg); break;
case 8: chargeLevel = atoi(optarg); break;
case 9: firePreDelayMs = atoi(optarg); break;
case 10: fireDurationUs = 1000*atoi(optarg); break;
case 11: fireDurationUs = atoi(optarg); break;
case 12: firePostDelayMs = atoi(optarg); break;
case 13: dischargeDurationMs = atoi(optarg); break;
case 14: dischargeLevel = atoi(optarg); break;
default: return printUsageHelp();
}
break;
default: return printUsageHelp();
}
}
cout << "Charge duration " << chargeDurationMs << "ms, level " << chargeLevel << endl;
cout << "Fire pre-delay " << firePreDelayMs << "ms, duration " << fireDurationUs << "us, post-delay " << firePostDelayMs << "ms" << endl;
cout << "Discharge duration " << dischargeDurationMs << "ms, level " << dischargeLevel << endl;
TrikCoilGun coilGun(mspI2cBusId, mspI2cDeviceId, mspChargeLevelCmd, mspDischargeCurrentCmd, gpioChargeCtrl, gpioDischargeCtrl);
coilGun.charge(chargeDurationMs, chargeLevel);
coilGun.fire(firePreDelayMs, fireDurationUs, firePostDelayMs);
coilGun.discharge(dischargeDurationMs, dischargeLevel);
}
<|endoftext|>
|
<commit_before>/*
* lemonn_v
* 07.05.12
*/
#include <cstdlib>
#include <iostream>
#include <exception>
#include "Sound.hpp"
#include "JsManager.hpp"
#include "Bomberman.hpp"
#include "Error.hpp"
int main()
{
Bomberman bomberman;
time_t now;
time(&now);
srandom(now);
Sound::getMe();
JsManager::getMe();
try
{
bomberman.run();
}
catch (const std::exception & end)
{
std::cerr << end.what() << std::endl;
}
Sound::delMe();
JsManager::delMe();
return 0;
}
<commit_msg>exceptions check<commit_after>/*
* lemonn_v
* 07.05.12
*/
#include <cstdlib>
#include <iostream>
#include <exception>
#include "Sound.hpp"
#include "JsManager.hpp"
#include "Bomberman.hpp"
#include "Error.hpp"
int main()
{
try
{
Bomberman bomberman;
time_t now;
time(&now);
srandom(now);
Sound::getMe();
JsManager::getMe();
bomberman.run();
Sound::delMe();
JsManager::delMe();
}
catch (const EndOfGame & end)
{
}
catch (const std::exception & end)
{
std::cerr << end.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown error occured." << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "application.h"
#include "mainwindow.h"
#include <QApplication>
#include <QMainWindow>
int main(int argc, char *argv[])
{
// QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
app.setOrganizationName("lpd8-editor");
app.setApplicationName("lpd8-editor");
app.setApplicationVersion("0.0.0");
Application application;
MainWindow win(&application);
win.show();
// Application app;
return app.exec();
}
<commit_msg>Enable HiDPI rendering if supported<commit_after>#include "application.h"
#include "mainwindow.h"
#include <QApplication>
#include <QMainWindow>
int main(int argc, char *argv[])
{
#if QT_VERSION >= 0x050600
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QApplication app(argc, argv);
app.setOrganizationName("lpd8-editor");
app.setApplicationName("lpd8-editor");
app.setApplicationVersion("0.0.0");
Application application;
MainWindow win(&application);
win.show();
return app.exec();
}
<|endoftext|>
|
<commit_before>#include <graphics/types.h>
#include <graphics/exceptions.h>
#include <log/log.h>
#include <lodepng.h>
int main(int argc, char **argv) {
try {
graphics::Window window;
window.activate();
// initialize resources
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
const GLfloat vx_data[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
};
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof vx_data, vx_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
const char *const VERTEX_SHADER_CODE =
"#version 330 core\n"
"layout(location = 0) in vec2 position;\n"
"out vec2 texcoord;\n"
"uniform ivec2[2] viewcoords;\n"
"uniform ivec2[2] objcoords;\n"
"uniform vec2[2] texcoords;\n"
"uniform float depth = 0.0;\n"
"void main() {\n"
// convert screen space to NDC
// world space (pixels) = opos + position * osize
// screen space = world space - vpos
// 0-1 coordinates = screen space / vsize
// -1-1 coordinates = 2 * 0-1coords - 1
" gl_Position = vec4((objcoords[0] - viewcoords[0] + position * objcoords[1]) / vec2(viewcoords[1]) * 2.0 - 1.0, 0.0, 1.0);\n"
" gl_Position.y = -gl_Position.y;"
" texcoord = position;\n"
"}\n",
*const FRAGMENT_SHADER_CODE =
"#version 330 core\n"
"uniform sampler2D tex;\n"
"in vec2 texcoord;\n"
"out vec4 color;\n"
"void main() {\n"
" color = texture(tex, texcoord);\n"
"}\n";
glShaderSource(vs, 1, &VERTEX_SHADER_CODE, NULL);
glShaderSource(fs, 1, &FRAGMENT_SHADER_CODE, NULL);
glCompileShader(vs);
glCompileShader(fs);
// TODO: check status and info log
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
// TODO: check status and info log
glDetachShader(prog, vs);
glDetachShader(prog, fs);
glDeleteShader(vs);
glDeleteShader(fs);
glUseProgram(prog);
// set uniforms
GLuint vcloc = glGetUniformLocation(prog, "viewcoords"),
ocloc = glGetUniformLocation(prog, "objcoords"),
tcloc = glGetUniformLocation(prog, "texcoords");
GLint ibuffer[4] = {0, 0, 0, 0};
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
ibuffer[2] = ibuffer[3] = 320;
glUniform2iv(ocloc, 2, ibuffer);
GLfloat fbuffer[4] = {0.0f, 0.0f, 1.0f, 1.0f};
glUniform2fv(tcloc, 2, fbuffer);
// load texture
graphics::Texture tex("texture.png");
tex.activate();
GLuint tex_loc = glGetUniformLocation(prog, "tex");
glProgramUniform1i(prog, tex_loc, 0);
// game loop
while (window.running()) {
window.clear();
// update uniform
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// swap buffers
window.swapBuffers();
window.waitEvents();
}
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
} catch (const graphics::WindowCreationError &e) {
LOG_ERR(e.what());
return 1;
} catch (const std::exception &e) {
LOG_ERR("Critical failure: ", e.what());
return 1;
}
return 0;
}
<commit_msg>Texture coordinates<commit_after>#include <graphics/types.h>
#include <graphics/exceptions.h>
#include <log/log.h>
#include <lodepng.h>
int main(int argc, char **argv) {
try {
graphics::Window window;
window.activate();
// initialize resources
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
const GLfloat vx_data[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
};
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof vx_data, vx_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
const char *const VERTEX_SHADER_CODE =
"#version 330 core\n"
"layout(location = 0) in vec2 position;\n"
"out vec2 texcoord;\n"
"uniform ivec2[2] viewcoords;\n"
"uniform ivec2[2] objcoords;\n"
"uniform vec2[2] texcoords;\n"
"uniform float depth = 0.0;\n"
"void main() {\n"
// convert screen space to NDC
// world space (pixels) = opos + position * osize
// screen space = world space - vpos
// 0-1 coordinates = screen space / vsize
// -1-1 coordinates = 2 * 0-1coords - 1
" gl_Position = vec4((objcoords[0] - viewcoords[0] + position * objcoords[1]) / vec2(viewcoords[1]) * 2.0 - 1.0, 0.0, 1.0);\n"
" gl_Position.y = -gl_Position.y;"
" texcoord = texcoords[0] + position * texcoords[1];\n"
"}\n",
*const FRAGMENT_SHADER_CODE =
"#version 330 core\n"
"uniform sampler2D tex;\n"
"in vec2 texcoord;\n"
"out vec4 color;\n"
"void main() {\n"
" color = texture(tex, texcoord);\n"
"}\n";
glShaderSource(vs, 1, &VERTEX_SHADER_CODE, NULL);
glShaderSource(fs, 1, &FRAGMENT_SHADER_CODE, NULL);
glCompileShader(vs);
glCompileShader(fs);
// TODO: check status and info log
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
// TODO: check status and info log
glDetachShader(prog, vs);
glDetachShader(prog, fs);
glDeleteShader(vs);
glDeleteShader(fs);
glUseProgram(prog);
// set uniforms
GLuint vcloc = glGetUniformLocation(prog, "viewcoords"),
ocloc = glGetUniformLocation(prog, "objcoords"),
tcloc = glGetUniformLocation(prog, "texcoords");
GLint ibuffer[4] = {0, 0, 0, 0};
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
ibuffer[2] = ibuffer[3] = 320;
glUniform2iv(ocloc, 2, ibuffer);
GLfloat fbuffer[4] = {0.0f, 0.0f, 1.0f, 1.0f};
glUniform2fv(tcloc, 2, fbuffer);
// load texture
graphics::Texture tex("texture.png");
tex.activate();
GLuint tex_loc = glGetUniformLocation(prog, "tex");
glProgramUniform1i(prog, tex_loc, 0);
// game loop
while (window.running()) {
window.clear();
// update uniform
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// swap buffers
window.swapBuffers();
window.waitEvents();
}
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
} catch (const graphics::WindowCreationError &e) {
LOG_ERR(e.what());
return 1;
} catch (const std::exception &e) {
LOG_ERR("Critical failure: ", e.what());
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <exception>
#include <limits>
#include <stdint.h>
#include <stdlib.h>
#include "resultfilename.h"
#include "timer.h"
#include "test.h"
const unsigned kIterationPerDigit = 100000;
const unsigned kIterationForRandom = 100;
const unsigned kTrial = 10;
template <typename T>
struct Traits {
};
template <>
struct Traits<uint32_t> {
enum { kBufferSize = 11 };
enum { kMaxDigit = 10 };
static uint32_t Negate(uint32_t x) { return x; };
};
template <>
struct Traits<int32_t> {
enum { kBufferSize = 12 };
enum { kMaxDigit = 10 };
static int32_t Negate(int32_t x) { return -x; };
};
template <>
struct Traits<uint64_t> {
enum { kBufferSize = 21 };
enum { kMaxDigit = 20 };
static uint64_t Negate(uint64_t x) { return x; };
};
template <>
struct Traits<int64_t> {
enum { kBufferSize = 22 };
enum { kMaxDigit = 20 };
static int64_t Negate(int64_t x) { return -x; };
};
template <typename T>
static void VerifyValue(T value, void(*f)(T, char*), void(*g)(T, char*), const char* fname, const char* gname) {
char buffer1[Traits<T>::kBufferSize];
char buffer2[Traits<T>::kBufferSize];
f(value, buffer1);
g(value, buffer2);
if (strcmp(buffer1, buffer2) != 0) {
printf("\nError: %s -> %s, %s -> %s\n", fname, buffer1, gname, buffer2);
throw std::exception();
}
//puts(buffer1);
}
template <typename T>
static void Verify(void(*f)(T, char*), void(*g)(T, char*), const char* fname, const char* gname) {
printf("Verifying %s = %s ... ", fname, gname);
// Boundary cases
VerifyValue<T>(0, f, g, fname, gname);
VerifyValue<T>(std::numeric_limits<T>::min(), f, g, fname, gname);
VerifyValue<T>(std::numeric_limits<T>::max(), f, g, fname, gname);
// 2^n - 1, 2^n, 10^n - 1, 10^n until overflow
for (uint32_t power = 2; power <= 10; power += 8) {
T i = 1, last;
do {
VerifyValue<T>(i - 1, f, g, fname, gname);
VerifyValue<T>(i, f, g, fname, gname);
if (std::numeric_limits<T>::min() < 0) {
VerifyValue<T>(Traits<T>::Negate(i), f, g, fname, gname);
VerifyValue<T>(Traits<T>::Negate(i + 1), f, g, fname, gname);
}
last = i;
i *= power;
} while (last < i);
}
printf("OK\n");
}
void VerifyAll() {
const TestList& tests = TestManager::Instance().GetTests();
// Find naive for verification
const Test* naive = 0;
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
if (strcmp((*itr)->fname, "naive") == 0) {
naive = *itr;
break;
}
assert(naive != 0);
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) {
if (strcmp((*itr)->fname, "null") != 0) { // skip null
try {
Verify(naive->u32toa, (*itr)->u32toa, "naive_u32toa", (*itr)->fname);
Verify(naive->i32toa, (*itr)->i32toa, "naive_i32toa", (*itr)->fname);
Verify(naive->u64toa, (*itr)->u64toa, "naive_u64toa", (*itr)->fname);
Verify(naive->i64toa, (*itr)->i64toa, "naive_i64toa", (*itr)->fname);
}
catch (...) {
}
}
}
}
template <typename T>
void BenchSequential(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
printf("Benchmarking sequential %-20s ... ", fname);
char buffer[Traits<T>::kBufferSize];
double minDuration = std::numeric_limits<double>::max();
double maxDuration = 0.0;
T start = 1;
for (int digit = 1; digit <= Traits<T>::kMaxDigit; digit++) {
T end = (digit == Traits<T>::kMaxDigit) ? std::numeric_limits<T>::max() : start * 10;
double duration = std::numeric_limits<double>::max();
for (unsigned trial = 0; trial < kTrial; trial++) {
T v = start;
T sign = 1;
Timer timer;
timer.Start();
for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) {
f(v * sign, buffer);
sign = Traits<T>::Negate(sign);
if (++v == end)
v = start;
}
timer.Stop();
duration = std::min(duration, timer.GetElapsedMilliseconds());
}
duration *= 1e6 / kIterationPerDigit; // convert to nano second per operation
minDuration = std::min(minDuration, duration);
maxDuration = std::max(maxDuration, duration);
fprintf(fp, "%s_sequential,%s,%d,%f\n", type, fname, digit, duration);
start = end;
}
printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration);
}
template <class T>
class RandomData {
public:
static T* GetData() {
static RandomData singleton;
return singleton.mData;
}
static const size_t kCountPerDigit = 1000;
static const size_t kCount = kCountPerDigit * Traits<T>::kMaxDigit;
private:
RandomData() :
mData(new T[kCount])
{
T* p = mData;
T start = 1;
for (int digit = 1; digit <= Traits<T>::kMaxDigit; digit++) {
T end = (digit == Traits<T>::kMaxDigit) ? std::numeric_limits<T>::max() : start * 10;
T v = start;
T sign = 1;
for (size_t i = 0; i < kCountPerDigit; i++) {
*p++ = v * sign;
sign = Traits<T>::Negate(sign);
if (++v == end)
v = start;
}
start = end;
}
std::random_shuffle(mData, mData + kCount);
}
~RandomData() {
delete[] mData;
}
T* mData;
};
template <typename T>
void BenchRandom(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
printf("Benchmarking random %-20s ... ", fname);
char buffer[Traits<T>::kBufferSize];
T* data = RandomData<T>::GetData();
size_t n = RandomData<T>::kCount;
double duration = std::numeric_limits<double>::max();
for (unsigned trial = 0; trial < kTrial; trial++) {
Timer timer;
timer.Start();
for (unsigned iteration = 0; iteration < kIterationForRandom; iteration++)
for (size_t i = 0; i < n; i++)
f(data[i], buffer);
timer.Stop();
duration = std::min(duration, timer.GetElapsedMilliseconds());
}
duration *= 1e6 / (kIterationForRandom * n); // convert to nano second per operation
fprintf(fp, "%s_random,%s,0,%f\n", type, fname, duration);
printf("%8.3fns\n", duration);
}
template <typename T>
void Bench(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
BenchSequential(f, type, fname, fp);
BenchRandom(f, type, fname, fp);
}
void BenchAll() {
// Try to write to /result path, where template.php exists
FILE *fp;
if ((fp = fopen("../../result/template.php", "r")) != NULL) {
fclose(fp);
fp = fopen("../../result/" RESULT_FILENAME, "w");
}
else if ((fp = fopen("../result/template.php", "r")) != NULL) {
fclose(fp);
fp = fopen("../result/" RESULT_FILENAME, "w");
}
else
fp = fopen(RESULT_FILENAME, "w");
fprintf(fp, "Type,Function,Digit,Time(ns)\n");
const TestList& tests = TestManager::Instance().GetTests();
puts("u32toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->u32toa, "u32toa", (*itr)->fname, fp);
puts("");
puts("i32toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->i32toa, "i32toa", (*itr)->fname, fp);
puts("");
puts("u64toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->u64toa, "u64toa", (*itr)->fname, fp);
puts("");
puts("i64toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->i64toa, "i64toa", (*itr)->fname, fp);
fclose(fp);
}
int main() {
// sort tests
TestList& tests = TestManager::Instance().GetTests();
std::sort(tests.begin(), tests.end());
VerifyAll();
BenchAll();
}
<commit_msg>Fixed issue #26 https://github.com/miloyip/itoa-benchmark/issues/26<commit_after>#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <exception>
#include <limits>
#include <string>
#include <stdint.h>
#include <stdlib.h>
#include "resultfilename.h"
#include "timer.h"
#include "test.h"
const unsigned kIterationPerDigit = 100000;
const unsigned kIterationForRandom = 100;
const unsigned kTrial = 10;
template <typename T>
struct Traits {
};
template <>
struct Traits<uint32_t> {
enum { kBufferSize = 11 };
enum { kMaxDigit = 10 };
static uint32_t Negate(uint32_t x) { return x; };
};
template <>
struct Traits<int32_t> {
enum { kBufferSize = 12 };
enum { kMaxDigit = 10 };
static int32_t Negate(int32_t x) { return -x; };
};
template <>
struct Traits<uint64_t> {
enum { kBufferSize = 21 };
enum { kMaxDigit = 20 };
static uint64_t Negate(uint64_t x) { return x; };
};
template <>
struct Traits<int64_t> {
enum { kBufferSize = 22 };
enum { kMaxDigit = 20 };
static int64_t Negate(int64_t x) { return -x; };
};
template <typename T>
static void VerifyValue(T value, void(*f)(T, char*), void(*g)(T, char*), const char* fname, const char* gname) {
char buffer1[Traits<T>::kBufferSize];
char buffer2[Traits<T>::kBufferSize];
f(value, buffer1);
g(value, buffer2);
if (strcmp(buffer1, buffer2) != 0) {
printf("\nError: %s -> %s, %s -> %s\n", fname, buffer1, gname, buffer2);
throw std::exception();
}
//puts(buffer1);
}
template <typename T>
static void Verify(void(*f)(T, char*), void(*g)(T, char*), const char* fname, const char* gname) {
printf("Verifying %s = %s ... ", fname, gname);
// Boundary cases
VerifyValue<T>(0, f, g, fname, gname);
VerifyValue<T>(std::numeric_limits<T>::min(), f, g, fname, gname);
VerifyValue<T>(std::numeric_limits<T>::max(), f, g, fname, gname);
// 2^n - 1, 2^n, 10^n - 1, 10^n until overflow
for (uint32_t power = 2; power <= 10; power += 8) {
T i = 1, last;
do {
VerifyValue<T>(i - 1, f, g, fname, gname);
VerifyValue<T>(i, f, g, fname, gname);
if (std::numeric_limits<T>::min() < 0) {
VerifyValue<T>(Traits<T>::Negate(i), f, g, fname, gname);
VerifyValue<T>(Traits<T>::Negate(i + 1), f, g, fname, gname);
}
last = i;
i *= power;
} while (last < i);
}
printf("OK\n");
}
void VerifyAll() {
const TestList& tests = TestManager::Instance().GetTests();
// Find naive for verification
const Test* naive = 0;
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
if (strcmp((*itr)->fname, "naive") == 0) {
naive = *itr;
break;
}
assert(naive != 0);
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) {
if (strcmp((*itr)->fname, "null") != 0) { // skip null
try {
Verify(naive->u32toa, (*itr)->u32toa, "naive_u32toa", (*itr)->fname);
Verify(naive->i32toa, (*itr)->i32toa, "naive_i32toa", (*itr)->fname);
Verify(naive->u64toa, (*itr)->u64toa, "naive_u64toa", (*itr)->fname);
Verify(naive->i64toa, (*itr)->i64toa, "naive_i64toa", (*itr)->fname);
}
catch (...) {
}
}
}
}
template <typename T>
void BenchSequential(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
printf("Benchmarking sequential %-20s ... ", fname);
char buffer[Traits<T>::kBufferSize];
double minDuration = std::numeric_limits<double>::max();
double maxDuration = 0.0;
T start = 1;
for (int digit = 1; digit <= Traits<T>::kMaxDigit; digit++) {
T end = (digit == Traits<T>::kMaxDigit) ? std::numeric_limits<T>::max() : start * 10;
double duration = std::numeric_limits<double>::max();
for (unsigned trial = 0; trial < kTrial; trial++) {
T v = start;
T sign = 1;
Timer timer;
timer.Start();
for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) {
f(v * sign, buffer);
sign = Traits<T>::Negate(sign);
if (++v == end)
v = start;
}
timer.Stop();
duration = std::min(duration, timer.GetElapsedMilliseconds());
}
duration *= 1e6 / kIterationPerDigit; // convert to nano second per operation
minDuration = std::min(minDuration, duration);
maxDuration = std::max(maxDuration, duration);
fprintf(fp, "%s_sequential,%s,%d,%f\n", type, fname, digit, duration);
start = end;
}
printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration);
}
template <class T>
class RandomData {
public:
static T* GetData() {
static RandomData singleton;
return singleton.mData;
}
static const size_t kCountPerDigit = 1000;
static const size_t kCount = kCountPerDigit * Traits<T>::kMaxDigit;
private:
RandomData() :
mData(new T[kCount])
{
T* p = mData;
T start = 1;
for (int digit = 1; digit <= Traits<T>::kMaxDigit; digit++) {
T end = (digit == Traits<T>::kMaxDigit) ? std::numeric_limits<T>::max() : start * 10;
T v = start;
T sign = 1;
for (size_t i = 0; i < kCountPerDigit; i++) {
*p++ = v * sign;
sign = Traits<T>::Negate(sign);
if (++v == end)
v = start;
}
start = end;
}
std::random_shuffle(mData, mData + kCount);
}
~RandomData() {
delete[] mData;
}
T* mData;
};
template <typename T>
void BenchRandom(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
printf("Benchmarking random %-20s ... ", fname);
char buffer[Traits<T>::kBufferSize];
T* data = RandomData<T>::GetData();
size_t n = RandomData<T>::kCount;
double duration = std::numeric_limits<double>::max();
for (unsigned trial = 0; trial < kTrial; trial++) {
Timer timer;
timer.Start();
for (unsigned iteration = 0; iteration < kIterationForRandom; iteration++)
for (size_t i = 0; i < n; i++)
f(data[i], buffer);
timer.Stop();
duration = std::min(duration, timer.GetElapsedMilliseconds());
}
duration *= 1e6 / (kIterationForRandom * n); // convert to nano second per operation
fprintf(fp, "%s_random,%s,0,%f\n", type, fname, duration);
printf("%8.3fns\n", duration);
}
template <typename T>
void Bench(void(*f)(T, char*), const char* type, const char* fname, FILE* fp) {
BenchSequential(f, type, fname, fp);
BenchRandom(f, type, fname, fp);
}
void BenchAll() {
// Try to write to /result path, where template.php exists
FILE *fp;
if ((fp = fopen("../../result/template.php", "r")) != NULL) {
fclose(fp);
fp = fopen("../../result/" RESULT_FILENAME, "w");
}
else if ((fp = fopen("../result/template.php", "r")) != NULL) {
fclose(fp);
fp = fopen("../result/" RESULT_FILENAME, "w");
}
else
fp = fopen(RESULT_FILENAME, "w");
fprintf(fp, "Type,Function,Digit,Time(ns)\n");
const TestList& tests = TestManager::Instance().GetTests();
puts("u32toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->u32toa, "u32toa", (*itr)->fname, fp);
puts("");
puts("i32toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->i32toa, "i32toa", (*itr)->fname, fp);
puts("");
puts("u64toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->u64toa, "u64toa", (*itr)->fname, fp);
puts("");
puts("i64toa");
for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr)
Bench((*itr)->i64toa, "i64toa", (*itr)->fname, fp);
fclose(fp);
}
int main() {
// sort tests
TestList& tests = TestManager::Instance().GetTests();
std::sort(tests.begin(), tests.end(),
[](const Test* a, const Test* b) {
return std::string{a->fname} < std::string{b->fname};
});
VerifyAll();
BenchAll();
}
<|endoftext|>
|
<commit_before>/** Implementation of bytea (binary string) conversions.
*
* Copyright (c) 2003-2018, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/binarystring"
#include "pqxx/field"
using namespace pqxx::internal;
namespace
{
using unsigned_char = unsigned char;
using buffer = std::pair<unsigned char *, size_t>;
buffer to_buffer(const void *data, size_t len)
{
void *const output{malloc(len + 1)};
if (output == nullptr) throw std::bad_alloc{};
static_cast<char *>(output)[len] = '\0';
memcpy(static_cast<char *>(output), data, len);
return buffer{static_cast<unsigned char *>(output), len};
}
buffer to_buffer(const std::string &source)
{
return to_buffer(source.c_str(), source.size());
}
buffer unescape(const unsigned char escaped[])
{
#ifdef _WIN32
/* On Windows only, the return value from PQunescapeBytea() must be freed
* using PQfreemem. Copy to a buffer allocated by libpqxx, so that the
* binarystring's buffer can be freed uniformly,
*/
size_t unescaped_len = 0;
// TODO: Use make_unique once we require C++14. Sooo much easier.
std::unique_ptr<unsigned char, void(*)(unsigned char *)> A(
PQunescapeBytea(const_cast<unsigned char *>(escaped), &unescaped_len),
freepqmem_templated<unsigned char>);
void *data = A.get();
if (data == nullptr) throw std::bad_alloc{};
return to_buffer(data, unescaped_len);
#else
/* On non-Windows platforms, it's okay to free libpq-allocated memory using
* free(). No extra copy needed.
*/
buffer unescaped;
unescaped.first = PQunescapeBytea(
const_cast<unsigned char *>(escaped), &unescaped.second);
if (unescaped.first == nullptr) throw std::bad_alloc{};
return unescaped;
#endif
}
} // namespace
pqxx::binarystring::binarystring(const field &F) :
m_buf{make_smart_pointer()},
m_size{0}
{
buffer unescaped{unescape(reinterpret_cast<const_pointer>(F.c_str()))};
m_buf = make_smart_pointer(unescaped.first);
m_size = unescaped.second;
}
pqxx::binarystring::binarystring(const std::string &s) :
m_buf{make_smart_pointer()},
m_size{s.size()}
{
m_buf = make_smart_pointer(to_buffer(s).first);
}
pqxx::binarystring::binarystring(const void *binary_data, size_t len) :
m_buf{make_smart_pointer()},
m_size{len}
{
m_buf = make_smart_pointer(to_buffer(binary_data, len).first);
}
bool pqxx::binarystring::operator==(const binarystring &rhs) const noexcept
{
if (rhs.size() != size()) return false;
for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
return true;
}
pqxx::binarystring &pqxx::binarystring::operator=(const binarystring &rhs)
{
m_buf = rhs.m_buf;
m_size = rhs.m_size;
return *this;
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (m_size == 0)
throw std::out_of_range{"Accessing empty binarystring"};
throw std::out_of_range{
"binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")"};
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
m_buf.swap(rhs.m_buf);
// This part very obviously can't go wrong, so do it last
const auto s = m_size;
m_size = rhs.m_size;
rhs.m_size = s;
}
std::string pqxx::binarystring::str() const
{
return std::string{get(), m_size};
}
<commit_msg>Make use of std::mempcmp.<commit_after>/** Implementation of bytea (binary string) conversions.
*
* Copyright (c) 2003-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/binarystring"
#include "pqxx/field"
using namespace pqxx::internal;
namespace
{
using unsigned_char = unsigned char;
using buffer = std::pair<unsigned char *, size_t>;
buffer to_buffer(const void *data, size_t len)
{
void *const output{malloc(len + 1)};
if (output == nullptr) throw std::bad_alloc{};
static_cast<char *>(output)[len] = '\0';
memcpy(static_cast<char *>(output), data, len);
return buffer{static_cast<unsigned char *>(output), len};
}
buffer to_buffer(const std::string &source)
{
return to_buffer(source.c_str(), source.size());
}
buffer unescape(const unsigned char escaped[])
{
#ifdef _WIN32
/* On Windows only, the return value from PQunescapeBytea() must be freed
* using PQfreemem. Copy to a buffer allocated by libpqxx, so that the
* binarystring's buffer can be freed uniformly,
*/
size_t unescaped_len = 0;
// TODO: Use make_unique once we require C++14. Sooo much easier.
std::unique_ptr<unsigned char, void(*)(unsigned char *)> A(
PQunescapeBytea(const_cast<unsigned char *>(escaped), &unescaped_len),
freepqmem_templated<unsigned char>);
void *data = A.get();
if (data == nullptr) throw std::bad_alloc{};
return to_buffer(data, unescaped_len);
#else
/* On non-Windows platforms, it's okay to free libpq-allocated memory using
* free(). No extra copy needed.
*/
buffer unescaped;
unescaped.first = PQunescapeBytea(
const_cast<unsigned char *>(escaped), &unescaped.second);
if (unescaped.first == nullptr) throw std::bad_alloc{};
return unescaped;
#endif
}
} // namespace
pqxx::binarystring::binarystring(const field &F) :
m_buf{make_smart_pointer()},
m_size{0}
{
buffer unescaped{unescape(reinterpret_cast<const_pointer>(F.c_str()))};
m_buf = make_smart_pointer(unescaped.first);
m_size = unescaped.second;
}
pqxx::binarystring::binarystring(const std::string &s) :
m_buf{make_smart_pointer()},
m_size{s.size()}
{
m_buf = make_smart_pointer(to_buffer(s).first);
}
pqxx::binarystring::binarystring(const void *binary_data, size_t len) :
m_buf{make_smart_pointer()},
m_size{len}
{
m_buf = make_smart_pointer(to_buffer(binary_data, len).first);
}
bool pqxx::binarystring::operator==(const binarystring &rhs) const noexcept
{
if (rhs.size() != size()) return false;
return std::memcmp(data(), rhs.data(), size()) == 0;
}
pqxx::binarystring &pqxx::binarystring::operator=(const binarystring &rhs)
{
m_buf = rhs.m_buf;
m_size = rhs.m_size;
return *this;
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (m_size == 0)
throw std::out_of_range{"Accessing empty binarystring"};
throw std::out_of_range{
"binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")"};
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
m_buf.swap(rhs.m_buf);
// This part very obviously can't go wrong, so do it last
const auto s = m_size;
m_size = rhs.m_size;
rhs.m_size = s;
}
std::string pqxx::binarystring::str() const
{
return std::string{get(), m_size};
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_proxy_client_socket_pool.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/http/http_network_session.h"
#include "net/http/http_proxy_client_socket.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/client_socket_pool_base.h"
namespace net {
HttpProxySocketParams::HttpProxySocketParams(
const scoped_refptr<TCPSocketParams>& proxy_server,
const GURL& request_url,
HostPortPair endpoint,
scoped_refptr<HttpNetworkSession> session,
bool tunnel)
: tcp_params_(proxy_server),
request_url_(request_url),
endpoint_(endpoint),
session_(session),
tunnel_(tunnel) {
}
HttpProxySocketParams::~HttpProxySocketParams() {}
// HttpProxyConnectJobs will time out after this many seconds. Note this is on
// top of the timeout for the transport socket.
static const int kHttpProxyConnectJobTimeoutInSeconds = 30;
HttpProxyConnectJob::HttpProxyConnectJob(
const std::string& group_name,
const scoped_refptr<HttpProxySocketParams>& params,
const base::TimeDelta& timeout_duration,
const scoped_refptr<TCPClientSocketPool>& tcp_pool,
const scoped_refptr<HostResolver>& host_resolver,
Delegate* delegate,
NetLog* net_log)
: ConnectJob(group_name, timeout_duration, delegate,
BoundNetLog::Make(net_log, NetLog::SOURCE_CONNECT_JOB)),
params_(params),
tcp_pool_(tcp_pool),
resolver_(host_resolver),
ALLOW_THIS_IN_INITIALIZER_LIST(
callback_(this, &HttpProxyConnectJob::OnIOComplete)) {
}
HttpProxyConnectJob::~HttpProxyConnectJob() {}
LoadState HttpProxyConnectJob::GetLoadState() const {
switch (next_state_) {
case kStateTCPConnect:
case kStateTCPConnectComplete:
return tcp_socket_handle_->GetLoadState();
case kStateHttpProxyConnect:
case kStateHttpProxyConnectComplete:
return LOAD_STATE_ESTABLISHING_PROXY_TUNNEL;
default:
NOTREACHED();
return LOAD_STATE_IDLE;
}
}
int HttpProxyConnectJob::ConnectInternal() {
next_state_ = kStateTCPConnect;
return DoLoop(OK);
}
void HttpProxyConnectJob::OnIOComplete(int result) {
int rv = DoLoop(result);
if (rv != ERR_IO_PENDING)
NotifyDelegateOfCompletion(rv); // Deletes |this|
}
int HttpProxyConnectJob::DoLoop(int result) {
DCHECK_NE(next_state_, kStateNone);
int rv = result;
do {
State state = next_state_;
next_state_ = kStateNone;
switch (state) {
case kStateTCPConnect:
DCHECK_EQ(OK, rv);
rv = DoTCPConnect();
break;
case kStateTCPConnectComplete:
rv = DoTCPConnectComplete(rv);
break;
case kStateHttpProxyConnect:
DCHECK_EQ(OK, rv);
rv = DoHttpProxyConnect();
break;
case kStateHttpProxyConnectComplete:
rv = DoHttpProxyConnectComplete(rv);
break;
default:
NOTREACHED() << "bad state";
rv = ERR_FAILED;
break;
}
} while (rv != ERR_IO_PENDING && next_state_ != kStateNone);
return rv;
}
int HttpProxyConnectJob::DoTCPConnect() {
next_state_ = kStateTCPConnectComplete;
tcp_socket_handle_.reset(new ClientSocketHandle());
return tcp_socket_handle_->Init(
group_name(), params_->tcp_params(),
params_->tcp_params()->destination().priority(), &callback_, tcp_pool_,
net_log());
}
int HttpProxyConnectJob::DoTCPConnectComplete(int result) {
if (result != OK)
return result;
// Reset the timer to just the length of time allowed for HttpProxy handshake
// so that a fast TCP connection plus a slow HttpProxy failure doesn't take
// longer to timeout than it should.
ResetTimer(base::TimeDelta::FromSeconds(
kHttpProxyConnectJobTimeoutInSeconds));
next_state_ = kStateHttpProxyConnect;
return result;
}
int HttpProxyConnectJob::DoHttpProxyConnect() {
next_state_ = kStateHttpProxyConnectComplete;
const HostResolver::RequestInfo& tcp_destination =
params_->tcp_params()->destination();
HostPortPair proxy_server(tcp_destination.hostname(),
tcp_destination.port());
// Add a HttpProxy connection on top of the tcp socket.
socket_.reset(new HttpProxyClientSocket(tcp_socket_handle_.release(),
params_->request_url(),
params_->endpoint(),
proxy_server,
params_->session(),
params_->tunnel()));
return socket_->Connect(&callback_);
}
int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result) {
if (result == OK || result == ERR_PROXY_AUTH_REQUESTED)
set_socket(socket_.release());
return result;
}
ConnectJob*
HttpProxyClientSocketPool::HttpProxyConnectJobFactory::NewConnectJob(
const std::string& group_name,
const PoolBase::Request& request,
ConnectJob::Delegate* delegate) const {
return new HttpProxyConnectJob(group_name, request.params(),
ConnectionTimeout(), tcp_pool_, host_resolver_,
delegate, net_log_);
}
base::TimeDelta
HttpProxyClientSocketPool::HttpProxyConnectJobFactory::ConnectionTimeout()
const {
return tcp_pool_->ConnectionTimeout() +
base::TimeDelta::FromSeconds(kHttpProxyConnectJobTimeoutInSeconds);
}
HttpProxyClientSocketPool::HttpProxyClientSocketPool(
int max_sockets,
int max_sockets_per_group,
const scoped_refptr<ClientSocketPoolHistograms>& histograms,
const scoped_refptr<HostResolver>& host_resolver,
const scoped_refptr<TCPClientSocketPool>& tcp_pool,
NetLog* net_log)
: base_(max_sockets, max_sockets_per_group, histograms,
base::TimeDelta::FromSeconds(
ClientSocketPool::unused_idle_socket_timeout()),
base::TimeDelta::FromSeconds(kUsedIdleSocketTimeout),
new HttpProxyConnectJobFactory(tcp_pool, host_resolver, net_log)) {}
HttpProxyClientSocketPool::~HttpProxyClientSocketPool() {}
int HttpProxyClientSocketPool::RequestSocket(const std::string& group_name,
const void* socket_params,
RequestPriority priority,
ClientSocketHandle* handle,
CompletionCallback* callback,
const BoundNetLog& net_log) {
const scoped_refptr<HttpProxySocketParams>* casted_socket_params =
static_cast<const scoped_refptr<HttpProxySocketParams>*>(socket_params);
return base_.RequestSocket(group_name, *casted_socket_params, priority,
handle, callback, net_log);
}
void HttpProxyClientSocketPool::CancelRequest(
const std::string& group_name,
ClientSocketHandle* handle) {
base_.CancelRequest(group_name, handle);
}
void HttpProxyClientSocketPool::ReleaseSocket(const std::string& group_name,
ClientSocket* socket, int id) {
base_.ReleaseSocket(group_name, socket, id);
}
void HttpProxyClientSocketPool::Flush() {
base_.Flush();
}
void HttpProxyClientSocketPool::CloseIdleSockets() {
base_.CloseIdleSockets();
}
int HttpProxyClientSocketPool::IdleSocketCountInGroup(
const std::string& group_name) const {
return base_.IdleSocketCountInGroup(group_name);
}
LoadState HttpProxyClientSocketPool::GetLoadState(
const std::string& group_name, const ClientSocketHandle* handle) const {
return base_.GetLoadState(group_name, handle);
}
} // namespace net
<commit_msg>Mange ciricular reference to HttpNetworkTransaction in HttpProxyClientSocktPool.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_proxy_client_socket_pool.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/http/http_network_session.h"
#include "net/http/http_proxy_client_socket.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/client_socket_pool_base.h"
namespace net {
HttpProxySocketParams::HttpProxySocketParams(
const scoped_refptr<TCPSocketParams>& proxy_server,
const GURL& request_url,
HostPortPair endpoint,
scoped_refptr<HttpNetworkSession> session,
bool tunnel)
: tcp_params_(proxy_server),
request_url_(request_url),
endpoint_(endpoint),
session_(tunnel ? session : NULL),
tunnel_(tunnel) {
}
HttpProxySocketParams::~HttpProxySocketParams() {}
// HttpProxyConnectJobs will time out after this many seconds. Note this is on
// top of the timeout for the transport socket.
static const int kHttpProxyConnectJobTimeoutInSeconds = 30;
HttpProxyConnectJob::HttpProxyConnectJob(
const std::string& group_name,
const scoped_refptr<HttpProxySocketParams>& params,
const base::TimeDelta& timeout_duration,
const scoped_refptr<TCPClientSocketPool>& tcp_pool,
const scoped_refptr<HostResolver>& host_resolver,
Delegate* delegate,
NetLog* net_log)
: ConnectJob(group_name, timeout_duration, delegate,
BoundNetLog::Make(net_log, NetLog::SOURCE_CONNECT_JOB)),
params_(params),
tcp_pool_(tcp_pool),
resolver_(host_resolver),
ALLOW_THIS_IN_INITIALIZER_LIST(
callback_(this, &HttpProxyConnectJob::OnIOComplete)) {
}
HttpProxyConnectJob::~HttpProxyConnectJob() {}
LoadState HttpProxyConnectJob::GetLoadState() const {
switch (next_state_) {
case kStateTCPConnect:
case kStateTCPConnectComplete:
return tcp_socket_handle_->GetLoadState();
case kStateHttpProxyConnect:
case kStateHttpProxyConnectComplete:
return LOAD_STATE_ESTABLISHING_PROXY_TUNNEL;
default:
NOTREACHED();
return LOAD_STATE_IDLE;
}
}
int HttpProxyConnectJob::ConnectInternal() {
next_state_ = kStateTCPConnect;
return DoLoop(OK);
}
void HttpProxyConnectJob::OnIOComplete(int result) {
int rv = DoLoop(result);
if (rv != ERR_IO_PENDING)
NotifyDelegateOfCompletion(rv); // Deletes |this|
}
int HttpProxyConnectJob::DoLoop(int result) {
DCHECK_NE(next_state_, kStateNone);
int rv = result;
do {
State state = next_state_;
next_state_ = kStateNone;
switch (state) {
case kStateTCPConnect:
DCHECK_EQ(OK, rv);
rv = DoTCPConnect();
break;
case kStateTCPConnectComplete:
rv = DoTCPConnectComplete(rv);
break;
case kStateHttpProxyConnect:
DCHECK_EQ(OK, rv);
rv = DoHttpProxyConnect();
break;
case kStateHttpProxyConnectComplete:
rv = DoHttpProxyConnectComplete(rv);
break;
default:
NOTREACHED() << "bad state";
rv = ERR_FAILED;
break;
}
} while (rv != ERR_IO_PENDING && next_state_ != kStateNone);
return rv;
}
int HttpProxyConnectJob::DoTCPConnect() {
next_state_ = kStateTCPConnectComplete;
tcp_socket_handle_.reset(new ClientSocketHandle());
return tcp_socket_handle_->Init(
group_name(), params_->tcp_params(),
params_->tcp_params()->destination().priority(), &callback_, tcp_pool_,
net_log());
}
int HttpProxyConnectJob::DoTCPConnectComplete(int result) {
if (result != OK)
return result;
// Reset the timer to just the length of time allowed for HttpProxy handshake
// so that a fast TCP connection plus a slow HttpProxy failure doesn't take
// longer to timeout than it should.
ResetTimer(base::TimeDelta::FromSeconds(
kHttpProxyConnectJobTimeoutInSeconds));
next_state_ = kStateHttpProxyConnect;
return result;
}
int HttpProxyConnectJob::DoHttpProxyConnect() {
next_state_ = kStateHttpProxyConnectComplete;
const HostResolver::RequestInfo& tcp_destination =
params_->tcp_params()->destination();
HostPortPair proxy_server(tcp_destination.hostname(),
tcp_destination.port());
// Add a HttpProxy connection on top of the tcp socket.
socket_.reset(new HttpProxyClientSocket(tcp_socket_handle_.release(),
params_->request_url(),
params_->endpoint(),
proxy_server,
params_->session(),
params_->tunnel()));
int result = socket_->Connect(&callback_);
// Clear the circular reference to HttpNetworkSession (|params_| reference
// HttpNetworkSession, which reference HttpProxyClientSocketPool, which
// references |this|) here because it is safe to do so now but not at other
// points. This may cancel this ConnectJob.
params_ = NULL;
return result;
}
int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result) {
if (result == OK || result == ERR_PROXY_AUTH_REQUESTED)
set_socket(socket_.release());
return result;
}
ConnectJob*
HttpProxyClientSocketPool::HttpProxyConnectJobFactory::NewConnectJob(
const std::string& group_name,
const PoolBase::Request& request,
ConnectJob::Delegate* delegate) const {
return new HttpProxyConnectJob(group_name, request.params(),
ConnectionTimeout(), tcp_pool_, host_resolver_,
delegate, net_log_);
}
base::TimeDelta
HttpProxyClientSocketPool::HttpProxyConnectJobFactory::ConnectionTimeout()
const {
return tcp_pool_->ConnectionTimeout() +
base::TimeDelta::FromSeconds(kHttpProxyConnectJobTimeoutInSeconds);
}
HttpProxyClientSocketPool::HttpProxyClientSocketPool(
int max_sockets,
int max_sockets_per_group,
const scoped_refptr<ClientSocketPoolHistograms>& histograms,
const scoped_refptr<HostResolver>& host_resolver,
const scoped_refptr<TCPClientSocketPool>& tcp_pool,
NetLog* net_log)
: base_(max_sockets, max_sockets_per_group, histograms,
base::TimeDelta::FromSeconds(
ClientSocketPool::unused_idle_socket_timeout()),
base::TimeDelta::FromSeconds(kUsedIdleSocketTimeout),
new HttpProxyConnectJobFactory(tcp_pool, host_resolver, net_log)) {}
HttpProxyClientSocketPool::~HttpProxyClientSocketPool() {}
int HttpProxyClientSocketPool::RequestSocket(const std::string& group_name,
const void* socket_params,
RequestPriority priority,
ClientSocketHandle* handle,
CompletionCallback* callback,
const BoundNetLog& net_log) {
const scoped_refptr<HttpProxySocketParams>* casted_socket_params =
static_cast<const scoped_refptr<HttpProxySocketParams>*>(socket_params);
return base_.RequestSocket(group_name, *casted_socket_params, priority,
handle, callback, net_log);
}
void HttpProxyClientSocketPool::CancelRequest(
const std::string& group_name,
ClientSocketHandle* handle) {
base_.CancelRequest(group_name, handle);
}
void HttpProxyClientSocketPool::ReleaseSocket(const std::string& group_name,
ClientSocket* socket, int id) {
base_.ReleaseSocket(group_name, socket, id);
}
void HttpProxyClientSocketPool::Flush() {
base_.Flush();
}
void HttpProxyClientSocketPool::CloseIdleSockets() {
base_.CloseIdleSockets();
}
int HttpProxyClientSocketPool::IdleSocketCountInGroup(
const std::string& group_name) const {
return base_.IdleSocketCountInGroup(group_name);
}
LoadState HttpProxyClientSocketPool::GetLoadState(
const std::string& group_name, const ClientSocketHandle* handle) const {
return base_.GetLoadState(group_name, handle);
}
} // namespace net
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "XDisplay.h"
#include "XWindow.h"
#include "BzfEvent.h"
#include <string.h>
#include <X11/keysym.h>
#ifdef XIJOYSTICK
#include <stdlib.h>
static int ioErrorHandler(Display*)
{
abort();
return 0;
}
#endif
//
// XDisplay::Rep
//
XDisplay::Rep::Rep(const char* displayName) :
refCount(1),
display(NULL),
screen(0)
#ifdef XIJOYSTICK
,devices(NULL)
#endif
{
// open display
display = XOpenDisplay(displayName);
if (!display) return;
#ifdef XIJOYSTICK
int dummy;
if (XQueryExtension(display, "XInputExtension", &dummy, &dummy, &dummy)) {
devices = XListInputDevices(display, &ndevices);
XSetIOErrorHandler(ioErrorHandler);
}
#endif
// other initialization
screen = DefaultScreen(display);
}
XDisplay::Rep::~Rep()
{
#ifdef XIJOYSTICK
if (devices)
XFreeDeviceList(devices);
#endif
if (display) XCloseDisplay(display);
}
void XDisplay::Rep::ref()
{
refCount++;
}
void XDisplay::Rep::unref()
{
if (--refCount <= 0) delete this;
}
Window XDisplay::Rep::getRootWindow() const
{
return display ? RootWindow(display, screen) : None;
}
#ifdef XIJOYSTICK
int XDisplay::Rep::mapButton(int button) const
{
static const int map[] = { BzfKeyEvent::LeftMouse,
BzfKeyEvent::MiddleMouse,
BzfKeyEvent::RightMouse,
BzfKeyEvent::F1,
BzfKeyEvent::F2,
BzfKeyEvent::F3,
BzfKeyEvent::F4,
BzfKeyEvent::F5,
BzfKeyEvent::F6,
BzfKeyEvent::F7,
BzfKeyEvent::F8,
BzfKeyEvent::F9
};
if (button < 1 || button > 12)
return BzfKeyEvent::NoButton;
return map[button];
}
#endif
//
// XDisplay
//
XDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :
rep(NULL),
mode(_mode)
{
// open display
rep = new Rep(displayName);
// make default mode changer if one wasn't supplied
if (!mode)
mode = new XDisplayMode;
if (rep->getDisplay()) {
// get resolutions
int numModes, currentMode;
ResInfo** resInfo = mode->init(this, numModes, currentMode);
// if no modes then make default
if (!resInfo) {
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
DisplayWidth(rep->getDisplay(), rep->getScreen()),
DisplayHeight(rep->getDisplay(), rep->getScreen()), 0);
numModes = 1;
currentMode = 0;
}
// register modes
initResolutions(resInfo, numModes, currentMode);
}
}
XDisplay::~XDisplay()
{
setDefaultResolution();
delete mode;
rep->unref();
}
bool XDisplay::isValid() const
{
return rep->getDisplay() != NULL;
}
bool XDisplay::isEventPending() const
{
return (XPending(rep->getDisplay()) != 0);
}
bool XDisplay::getEvent(BzfEvent& event) const
{
XEvent xevent;
XNextEvent(rep->getDisplay(), &xevent);
switch (xevent.type) {
case Expose:
case ConfigureNotify:
case MotionNotify:
case MapNotify:
case UnmapNotify:
case ButtonPress:
case ButtonRelease:
case KeyPress:
case KeyRelease:
case ClientMessage:
event.window = XWindow::lookupWindow(xevent.xexpose.window);
if (!event.window) return false;
break;
default:
#ifdef XIJOYSTICK
if ((xevent.type != rep->getButtonPressType()) &&
(xevent.type != rep->getButtonReleaseType()))
#endif
return false;
}
switch (xevent.type) {
case Expose:
if (xevent.xexpose.count != 0) return false;
event.type = BzfEvent::Redraw;
break;
case ConfigureNotify: {
/* attempt to filter out non-size changes, but getSize() returns the
* current size so it always matches the size in the event.
int width, height;
event.window->getSize(width, height);
if (width == xevent.xconfigure.width &&
height == xevent.xconfigure.height)
return false;
*/
event.type = BzfEvent::Resize;
event.resize.width = xevent.xconfigure.width;
event.resize.height = xevent.xconfigure.height;
break;
}
case MotionNotify:
event.type = BzfEvent::MouseMove;
event.mouseMove.x = xevent.xmotion.x;
event.mouseMove.y = xevent.xmotion.y;
break;
case MapNotify:
event.type = BzfEvent::Map;
break;
case UnmapNotify:
event.type = BzfEvent::Unmap;
break;
case ButtonPress:
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case ButtonRelease:
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case KeyPress:
event.type = BzfEvent::KeyDown;
if (!getKey(xevent, event.keyDown)) return false;
break;
case KeyRelease:
event.type = BzfEvent::KeyUp;
if (!getKey(xevent, event.keyUp)) return false;
break;
case ClientMessage: {
XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;
if (cme->format == 32) {
if ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),
"WM_DELETE_WINDOW", true)) {
event.type = BzfEvent::Quit;
break;
}
}
return false;
}
#ifdef XIJOYSTICK
default:
if (xevent.type == rep->getButtonPressType()) {
XDeviceButtonEvent *button = (XDeviceButtonEvent*) &xevent;
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
event.keyDown.button = rep->mapButton(button->button);
if (event.keyDown.button == BzfKeyEvent::NoButton)
return false;
} else if (xevent.type == rep->getButtonReleaseType()) {
XDeviceButtonEvent *button = (XDeviceButtonEvent*) &xevent;
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
event.keyUp.button = rep->mapButton(button->button);
if (event.keyUp.button == BzfKeyEvent::NoButton)
return false;
}
#endif
}
return true;
}
bool XDisplay::getKey(const XEvent& xevent,
BzfKeyEvent& key) const
{
char buf[3];
KeySym keysym;
if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {
key.ascii = buf[0];
key.button = BzfKeyEvent::NoButton;
if (keysym == XK_Delete) {
key.ascii = 0;
key.button = BzfKeyEvent::Delete;
}
}
else {
key.ascii = 0;
switch (keysym) {
case XK_Pause: key.button = BzfKeyEvent::Pause; break;
case XK_Home: key.button = BzfKeyEvent::Home; break;
case XK_End: key.button = BzfKeyEvent::End; break;
case XK_Left: key.button = BzfKeyEvent::Left; break;
case XK_Right: key.button = BzfKeyEvent::Right; break;
case XK_Up: key.button = BzfKeyEvent::Up; break;
case XK_Down: key.button = BzfKeyEvent::Down; break;
case XK_Page_Up: key.button = BzfKeyEvent::PageUp; break;
case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;
case XK_Insert: key.button = BzfKeyEvent::Insert; break;
case XK_Delete: key.button = BzfKeyEvent::Delete; break;
case XK_F1: key.button = BzfKeyEvent::F1; break;
case XK_F2: key.button = BzfKeyEvent::F2; break;
case XK_F3: key.button = BzfKeyEvent::F3; break;
case XK_F4: key.button = BzfKeyEvent::F4; break;
case XK_F5: key.button = BzfKeyEvent::F5; break;
case XK_F6: key.button = BzfKeyEvent::F6; break;
case XK_F7: key.button = BzfKeyEvent::F7; break;
case XK_F8: key.button = BzfKeyEvent::F8; break;
case XK_F9: key.button = BzfKeyEvent::F9; break;
case XK_F10: key.button = BzfKeyEvent::F10; break;
case XK_F11: key.button = BzfKeyEvent::F11; break;
case XK_F12: key.button = BzfKeyEvent::F12; break;
default: return false;
}
}
key.shift = 0;
if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;
if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;
if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;
return true;
}
bool XDisplay::doSetResolution(int modeIndex)
{
return mode->set(modeIndex);
}
bool XDisplay::doSetDefaultResolution()
{
return mode->setDefault(getDefaultResolution());
}
//
// XDisplayMode
//
XDisplayMode::XDisplayMode()
{
// do nothing
}
XDisplayMode::~XDisplayMode()
{
// do nothing
}
XDisplayMode::ResInfo** XDisplayMode::init(XDisplay*, int&, int&)
{
// no switching
return NULL;
}
bool XDisplayMode::set(int)
{
// no switching
return false;
}
bool XDisplayMode::setDefault(int mode)
{
return set(mode);
}
// ex: shiftwidth=2 tabstop=8
<commit_msg>fix a couple more instances of naughty memory<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "XDisplay.h"
#include "XWindow.h"
#include "BzfEvent.h"
#include <string.h>
#include <X11/keysym.h>
#ifdef XIJOYSTICK
#include <stdlib.h>
static int ioErrorHandler(Display*)
{
abort();
return 0;
}
#endif
//
// XDisplay::Rep
//
XDisplay::Rep::Rep(const char* displayName) :
refCount(1),
display(NULL),
screen(0)
#ifdef XIJOYSTICK
,devices(NULL),
buttonPressType(0),
buttonReleaseType(0)
#endif
{
// open display
display = XOpenDisplay(displayName);
if (!display) return;
#ifdef XIJOYSTICK
int dummy;
if (XQueryExtension(display, "XInputExtension", &dummy, &dummy, &dummy)) {
devices = XListInputDevices(display, &ndevices);
XSetIOErrorHandler(ioErrorHandler);
}
#endif
// other initialization
screen = DefaultScreen(display);
}
XDisplay::Rep::~Rep()
{
#ifdef XIJOYSTICK
if (devices)
XFreeDeviceList(devices);
#endif
if (display) XCloseDisplay(display);
}
void XDisplay::Rep::ref()
{
refCount++;
}
void XDisplay::Rep::unref()
{
if (--refCount <= 0) delete this;
}
Window XDisplay::Rep::getRootWindow() const
{
return display ? RootWindow(display, screen) : None;
}
#ifdef XIJOYSTICK
int XDisplay::Rep::mapButton(int button) const
{
static const int map[] = { BzfKeyEvent::LeftMouse,
BzfKeyEvent::MiddleMouse,
BzfKeyEvent::RightMouse,
BzfKeyEvent::F1,
BzfKeyEvent::F2,
BzfKeyEvent::F3,
BzfKeyEvent::F4,
BzfKeyEvent::F5,
BzfKeyEvent::F6,
BzfKeyEvent::F7,
BzfKeyEvent::F8,
BzfKeyEvent::F9
};
if (button < 1 || button > 12)
return BzfKeyEvent::NoButton;
return map[button];
}
#endif
//
// XDisplay
//
XDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :
rep(NULL),
mode(_mode)
{
// open display
rep = new Rep(displayName);
// make default mode changer if one wasn't supplied
if (!mode)
mode = new XDisplayMode;
if (rep->getDisplay()) {
// get resolutions
int numModes, currentMode;
ResInfo** resInfo = mode->init(this, numModes, currentMode);
// if no modes then make default
if (!resInfo) {
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
DisplayWidth(rep->getDisplay(), rep->getScreen()),
DisplayHeight(rep->getDisplay(), rep->getScreen()), 0);
numModes = 1;
currentMode = 0;
}
// register modes
initResolutions(resInfo, numModes, currentMode);
}
}
XDisplay::~XDisplay()
{
setDefaultResolution();
delete mode;
rep->unref();
}
bool XDisplay::isValid() const
{
return rep->getDisplay() != NULL;
}
bool XDisplay::isEventPending() const
{
return (XPending(rep->getDisplay()) != 0);
}
bool XDisplay::getEvent(BzfEvent& event) const
{
XEvent xevent;
XNextEvent(rep->getDisplay(), &xevent);
switch (xevent.type) {
case Expose:
case ConfigureNotify:
case MotionNotify:
case MapNotify:
case UnmapNotify:
case ButtonPress:
case ButtonRelease:
case KeyPress:
case KeyRelease:
case ClientMessage:
event.window = XWindow::lookupWindow(xevent.xexpose.window);
if (!event.window) return false;
break;
default:
#ifdef XIJOYSTICK
if ((xevent.type != rep->getButtonPressType()) &&
(xevent.type != rep->getButtonReleaseType()))
#endif
return false;
}
switch (xevent.type) {
case Expose:
if (xevent.xexpose.count != 0) return false;
event.type = BzfEvent::Redraw;
break;
case ConfigureNotify: {
/* attempt to filter out non-size changes, but getSize() returns the
* current size so it always matches the size in the event.
int width, height;
event.window->getSize(width, height);
if (width == xevent.xconfigure.width &&
height == xevent.xconfigure.height)
return false;
*/
event.type = BzfEvent::Resize;
event.resize.width = xevent.xconfigure.width;
event.resize.height = xevent.xconfigure.height;
break;
}
case MotionNotify:
event.type = BzfEvent::MouseMove;
event.mouseMove.x = xevent.xmotion.x;
event.mouseMove.y = xevent.xmotion.y;
break;
case MapNotify:
event.type = BzfEvent::Map;
break;
case UnmapNotify:
event.type = BzfEvent::Unmap;
break;
case ButtonPress:
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case ButtonRelease:
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case KeyPress:
event.type = BzfEvent::KeyDown;
if (!getKey(xevent, event.keyDown)) return false;
break;
case KeyRelease:
event.type = BzfEvent::KeyUp;
if (!getKey(xevent, event.keyUp)) return false;
break;
case ClientMessage: {
XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;
if (cme->format == 32) {
if ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),
"WM_DELETE_WINDOW", true)) {
event.type = BzfEvent::Quit;
break;
}
}
return false;
}
#ifdef XIJOYSTICK
default:
if (xevent.type == rep->getButtonPressType()) {
XDeviceButtonEvent *button = (XDeviceButtonEvent*) &xevent;
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
event.keyDown.button = rep->mapButton(button->button);
if (event.keyDown.button == BzfKeyEvent::NoButton)
return false;
} else if (xevent.type == rep->getButtonReleaseType()) {
XDeviceButtonEvent *button = (XDeviceButtonEvent*) &xevent;
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
event.keyUp.button = rep->mapButton(button->button);
if (event.keyUp.button == BzfKeyEvent::NoButton)
return false;
}
#endif
}
return true;
}
bool XDisplay::getKey(const XEvent& xevent,
BzfKeyEvent& key) const
{
char buf[3];
KeySym keysym;
if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {
key.ascii = buf[0];
key.button = BzfKeyEvent::NoButton;
if (keysym == XK_Delete) {
key.ascii = 0;
key.button = BzfKeyEvent::Delete;
}
}
else {
key.ascii = 0;
switch (keysym) {
case XK_Pause: key.button = BzfKeyEvent::Pause; break;
case XK_Home: key.button = BzfKeyEvent::Home; break;
case XK_End: key.button = BzfKeyEvent::End; break;
case XK_Left: key.button = BzfKeyEvent::Left; break;
case XK_Right: key.button = BzfKeyEvent::Right; break;
case XK_Up: key.button = BzfKeyEvent::Up; break;
case XK_Down: key.button = BzfKeyEvent::Down; break;
case XK_Page_Up: key.button = BzfKeyEvent::PageUp; break;
case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;
case XK_Insert: key.button = BzfKeyEvent::Insert; break;
case XK_Delete: key.button = BzfKeyEvent::Delete; break;
case XK_F1: key.button = BzfKeyEvent::F1; break;
case XK_F2: key.button = BzfKeyEvent::F2; break;
case XK_F3: key.button = BzfKeyEvent::F3; break;
case XK_F4: key.button = BzfKeyEvent::F4; break;
case XK_F5: key.button = BzfKeyEvent::F5; break;
case XK_F6: key.button = BzfKeyEvent::F6; break;
case XK_F7: key.button = BzfKeyEvent::F7; break;
case XK_F8: key.button = BzfKeyEvent::F8; break;
case XK_F9: key.button = BzfKeyEvent::F9; break;
case XK_F10: key.button = BzfKeyEvent::F10; break;
case XK_F11: key.button = BzfKeyEvent::F11; break;
case XK_F12: key.button = BzfKeyEvent::F12; break;
default: return false;
}
}
key.shift = 0;
if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;
if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;
if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;
return true;
}
bool XDisplay::doSetResolution(int modeIndex)
{
return mode->set(modeIndex);
}
bool XDisplay::doSetDefaultResolution()
{
return mode->setDefault(getDefaultResolution());
}
//
// XDisplayMode
//
XDisplayMode::XDisplayMode()
{
// do nothing
}
XDisplayMode::~XDisplayMode()
{
// do nothing
}
XDisplayMode::ResInfo** XDisplayMode::init(XDisplay*, int&, int&)
{
// no switching
return NULL;
}
bool XDisplayMode::set(int)
{
// no switching
return false;
}
bool XDisplayMode::setDefault(int mode)
{
return set(mode);
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>
#include <clocale>
#include <cstdlib>
#include <string.h>
#include <malloc.h>
#include "editor.h"
#include "lua_primitives.h"
/**
* Get the character at the cursor position.
*/
int at_lua(lua_State *L)
{
/*
* Get the buffer.
*/
Editor *e = Editor::instance();
Buffer *buffer = e->current_buffer();
/*
* Get the cursor position.
*/
int x = buffer->cx + buffer->coloff;
int y = buffer->cy + buffer->rowoff ;
/*
* Read the character
*/
wchar_t c = (mvinch(y, x) & A_CHARTEXT);
/*
* Convert to ASCII
*/
std::wstring tmp;
tmp += c;
char *str = new char[255];
sprintf(str, "%ls", tmp.c_str());
lua_pushstring(L, str);
delete(str);
return 1;
}
/**
* Get the height of the drawing-area - minus the two line footer.
*/
int height_lua(lua_State *L)
{
Editor *e = Editor::instance();
lua_pushnumber(L, e->height());
return 1;
}
/**
* Get the width of the screen.
*/
int width_lua(lua_State *L)
{
Editor *e = Editor::instance();
lua_pushnumber(L, e->width());
return 1;
}
<commit_msg>Fix `at()` to work correctly.<commit_after>
#include <clocale>
#include <cstdlib>
#include <string.h>
#include <malloc.h>
#include "editor.h"
#include "lua_primitives.h"
/**
* Get the character at the cursor position.
*/
int at_lua(lua_State *L)
{
/*
* Get the buffer.
*/
Editor *e = Editor::instance();
Buffer *buffer = e->current_buffer();
/*
* Get the cursor position.
*/
int x = buffer->cx + buffer->coloff;
int y = buffer->cy + buffer->rowoff ;
/*
* Default return value.
*/
std::wstring res;
/*
* Get the row.
*/
erow *row;
if ( y < buffer->rows.size() )
row = buffer->rows.at(y);
if ( row )
{
int len = row->chars->size();
if ( x < len )
{
res = row->chars->at( x );
}
}
char *str = new char[2];
sprintf(str, "%ls", res.c_str());
lua_pushstring(L, str);
delete(str);
return 1;
}
/**
* Get the height of the drawing-area - minus the two line footer.
*/
int height_lua(lua_State *L)
{
Editor *e = Editor::instance();
lua_pushnumber(L, e->height());
return 1;
}
/**
* Get the width of the screen.
*/
int width_lua(lua_State *L)
{
Editor *e = Editor::instance();
lua_pushnumber(L, e->width());
return 1;
}
<|endoftext|>
|
<commit_before># include <iostream>
# include <cstdlib>
# include <cstdio>
# include <cstring>
# include <unistd.h>
# include <sys/types.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <arpa/inet.h>
# include <netinet/in.h>
# include <microhttpd.h>
# include "webcli.hpp"
void print_usage(const char *program_name)
{
std::cerr<<"Usage: "<<program_name<<" [-he] [-p PORT] [-c FILE]"<<std::endl;
std::cerr<<"\t -h: start http daemon" << std::endl;
std::cerr<<"\t -e: if no command was given, just echo back the request" << std::endl;
std::cerr<<"\t -p PORT: use PORT for http daemon" << std::endl;
std::cerr<<"\t -c FILE: read commadns from FILE" << std::endl;
}
int http_callback(void *cls,
MHD_Connection *connection,
const char *url,
const char *method, const char *version,
const char *upload_data, size_t *upload_data_size,
void **con_cls)
{
WebCLI *webcli = (WebCLI*)cls;
MHD_Response *response;
int return_value;
const char *query = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "q");
std::string result;
if(!query)
{
result = webcli->resolveCommand(std::string());
}
else
{
result = webcli->resolveCommand(std::string(query));
}
std::cerr<<query<<" -> "<<result<<std::endl;
response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
if(!response) { std::cerr<<1<<std::endl; return MHD_NO; }
if(MHD_add_response_header(response, "Location", result.c_str()) == MHD_NO)
{
MHD_destroy_response(response);
return MHD_NO;
}
return_value = MHD_queue_response(connection, MHD_HTTP_FOUND, response);
MHD_destroy_response(response);
return return_value;
}
int main(int argc, char**argv)
{
bool enable_http = false;
bool echo = false;
unsigned short http_port = 8023;
const char *commands_file = "~/.webcli-commands";
int opt;
while((opt = getopt(argc, argv, "hep:c:")) != -1)
{
switch(opt)
{
case 'h':
enable_http = true;
break;
case 'e':
echo = true;
break;
case 'p':
http_port = atoi(optarg);
break;
case 'c':
commands_file = optarg;
break;
default:
print_usage(argv[0]);
return -1;
}
}
WebCLI webcli(commands_file, echo);
if(enable_http)
{
MHD_Daemon *daemon;
sockaddr_in localhost;
memset(&localhost, 0, sizeof(localhost));
localhost.sin_family = AF_INET;
localhost.sin_addr.s_addr = inet_addr("127.0.0.1");
localhost.sin_port = htons(http_port);
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, http_port, NULL, NULL, &http_callback, &webcli, MHD_OPTION_SOCK_ADDR, &localhost, MHD_OPTION_END);
if(!daemon)
{
std::cerr<<"Failed to start http daemon, exiting"<<std::endl;
return -1;
}
getchar();
MHD_stop_daemon(daemon);
}
else
{
std::string line;
while(std::getline(std::cin, line))
{
std::cout << webcli.resolveCommand(line) << std::endl;
}
}
return 0;
}
<commit_msg>added workexp for commands file<commit_after># include <iostream>
# include <cstdlib>
# include <cstdio>
# include <cstring>
# include <unistd.h>
# include <wordexp.h>
# include <sys/types.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <arpa/inet.h>
# include <netinet/in.h>
# include <microhttpd.h>
# include "webcli.hpp"
void print_usage(const char *program_name)
{
std::cerr<<"Usage: "<<program_name<<" [-he] [-p PORT] [-c FILE]"<<std::endl;
std::cerr<<"\t -h: start http daemon" << std::endl;
std::cerr<<"\t -e: if no command was given, just echo back the request" << std::endl;
std::cerr<<"\t -p PORT: use PORT for http daemon" << std::endl;
std::cerr<<"\t -c FILE: read commadns from FILE" << std::endl;
}
int http_callback(void *cls,
MHD_Connection *connection,
const char *url,
const char *method, const char *version,
const char *upload_data, size_t *upload_data_size,
void **con_cls)
{
WebCLI *webcli = (WebCLI*)cls;
MHD_Response *response;
int return_value;
const char *query = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "q");
std::string result;
if(!query)
{
result = webcli->resolveCommand(std::string());
}
else
{
result = webcli->resolveCommand(std::string(query));
}
std::cerr<<query<<" -> "<<result<<std::endl;
response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
if(!response) { std::cerr<<1<<std::endl; return MHD_NO; }
if(MHD_add_response_header(response, "Location", result.c_str()) == MHD_NO)
{
MHD_destroy_response(response);
return MHD_NO;
}
return_value = MHD_queue_response(connection, MHD_HTTP_FOUND, response);
MHD_destroy_response(response);
return return_value;
}
int main(int argc, char**argv)
{
bool enable_http = false;
bool echo = false;
unsigned short http_port = 8023;
const char *commands_file = "~/.webcli-commands";
int opt;
while((opt = getopt(argc, argv, "hep:c:")) != -1)
{
switch(opt)
{
case 'h':
enable_http = true;
break;
case 'e':
echo = true;
break;
case 'p':
http_port = atoi(optarg);
break;
case 'c':
commands_file = optarg;
break;
default:
print_usage(argv[0]);
return -1;
}
}
wordexp_t exp_result;
wordexp(commands_file, &exp_result, 0);
WebCLI webcli(exp_result.we_wordv[0], echo);
if(enable_http)
{
MHD_Daemon *daemon;
sockaddr_in localhost;
memset(&localhost, 0, sizeof(localhost));
localhost.sin_family = AF_INET;
localhost.sin_addr.s_addr = inet_addr("127.0.0.1");
localhost.sin_port = htons(http_port);
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, http_port, NULL, NULL, &http_callback, &webcli, MHD_OPTION_SOCK_ADDR, &localhost, MHD_OPTION_END);
if(!daemon)
{
std::cerr<<"Failed to start http daemon, exiting"<<std::endl;
return -1;
}
getchar();
MHD_stop_daemon(daemon);
}
else
{
std::string line;
while(std::getline(std::cin, line))
{
std::cout << webcli.resolveCommand(line) << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
#include "../lib.hh"
#include "catch.hpp"
using namespace vick;
using vick::move::mvcol;
TEST_CASE("mvcol", "[mvcol]") {
contents contents({"asert"});
visual_setup _;
mvcol(contents, 3);
CHECK(contents.y == 0);
CHECK(contents.x == 3);
mvcol(contents, 10); // doesn't do anything
CHECK(contents.y == 0);
CHECK(contents.y == 0);
mvcol(contents, 0);
CHECK(contents.y == 0);
CHECK(contents.x == 0);
}
<commit_msg>Fix testing same condition twice (copy paste)<commit_after>/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
#include "../lib.hh"
#include "catch.hpp"
using namespace vick;
using vick::move::mvcol;
TEST_CASE("mvcol", "[mvcol]") {
contents contents({"asert"});
visual_setup _;
mvcol(contents, 3);
CHECK(contents.y == 0);
CHECK(contents.x == 3);
mvcol(contents, 10); // doesn't do anything
CHECK(contents.y == 0);
CHECK(contents.x == 3);
mvcol(contents, 0);
CHECK(contents.y == 0);
CHECK(contents.x == 0);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include "mutation_reader.hh"
#include "mutation_assertions.hh"
// Intended to be called in a seastar thread
class reader_assertions {
mutation_reader _reader;
dht::partition_range _pr;
public:
reader_assertions(mutation_reader reader)
: _reader(std::move(reader))
{ }
reader_assertions& produces(const dht::decorated_key& dk) {
_reader().then([&] (auto sm) {
if (!sm) {
BOOST_FAIL(sprint("Expected: %s, got end of stream", dk));
}
if (!sm->decorated_key().equal(*sm->schema(), dk)) {
BOOST_FAIL(sprint("Expected: %s, got: %s", dk, sm->decorated_key()));
}
}).get0();
return *this;
}
reader_assertions& produces(mutation m) {
_reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([this, m = std::move(m)] (mutation_opt&& mo) mutable {
BOOST_REQUIRE(bool(mo));
assert_that(*mo).is_equal_to(m);
}).get0();
return *this;
}
mutation_assertion next_mutation() {
return _reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([] (mutation_opt&& mo) mutable {
BOOST_REQUIRE(bool(mo));
return mutation_assertion(std::move(*mo));
}).get0();
}
template<typename RangeOfMutations>
reader_assertions& produces(const RangeOfMutations& mutations) {
for (auto&& m : mutations) {
produces(m);
}
return *this;
}
reader_assertions& produces_end_of_stream() {
_reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([this] (mutation_opt&& mo) mutable {
if (bool(mo)) {
BOOST_FAIL(sprint("Expected end of stream, got %s", *mo));
}
}).get0();
return *this;
}
reader_assertions& fast_forward_to(const dht::partition_range& pr) {
_pr = pr;
_reader.fast_forward_to(_pr).get0();
return *this;
}
};
inline
reader_assertions assert_that(mutation_reader r) {
return { std::move(r) };
}
<commit_msg>tests: mutation_reader_assertions: Add produces_eos_or_empty_mutation()<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include "mutation_reader.hh"
#include "mutation_assertions.hh"
// Intended to be called in a seastar thread
class reader_assertions {
mutation_reader _reader;
dht::partition_range _pr;
public:
reader_assertions(mutation_reader reader)
: _reader(std::move(reader))
{ }
reader_assertions& produces(const dht::decorated_key& dk) {
_reader().then([&] (auto sm) {
if (!sm) {
BOOST_FAIL(sprint("Expected: %s, got end of stream", dk));
}
if (!sm->decorated_key().equal(*sm->schema(), dk)) {
BOOST_FAIL(sprint("Expected: %s, got: %s", dk, sm->decorated_key()));
}
}).get0();
return *this;
}
reader_assertions& produces(mutation m) {
_reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([this, m = std::move(m)] (mutation_opt&& mo) mutable {
BOOST_REQUIRE(bool(mo));
assert_that(*mo).is_equal_to(m);
}).get0();
return *this;
}
mutation_assertion next_mutation() {
return _reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([] (mutation_opt&& mo) mutable {
BOOST_REQUIRE(bool(mo));
return mutation_assertion(std::move(*mo));
}).get0();
}
template<typename RangeOfMutations>
reader_assertions& produces(const RangeOfMutations& mutations) {
for (auto&& m : mutations) {
produces(m);
}
return *this;
}
reader_assertions& produces_end_of_stream() {
_reader().then([] (auto sm) {
return mutation_from_streamed_mutation(std::move(sm));
}).then([this] (mutation_opt&& mo) mutable {
if (bool(mo)) {
BOOST_FAIL(sprint("Expected end of stream, got %s", *mo));
}
}).get0();
return *this;
}
reader_assertions& produces_eos_or_empty_mutation() {
BOOST_TEST_MESSAGE("Expecting eos or empty mutation");
auto sm = _reader().get0();
mutation_opt mo = mutation_from_streamed_mutation(std::move(sm)).get0();
if (mo) {
if (!mo->partition().empty()) {
BOOST_FAIL(sprint("Mutation is not empty: %s", *mo));
}
}
return *this;
}
reader_assertions& fast_forward_to(const dht::partition_range& pr) {
_pr = pr;
_reader.fast_forward_to(_pr).get0();
return *this;
}
};
inline
reader_assertions assert_that(mutation_reader r) {
return { std::move(r) };
}
<|endoftext|>
|
<commit_before>/*!
* Copyright 2014 by Contributors
* \file cli_main.cc
* \brief The command line interface program of xgboost.
* This file is not included in dynamic library.
*/
// Copyright 2014 by Contributors
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX
#include <xgboost/learner.h>
#include <xgboost/data.h>
#include <xgboost/logging.h>
#include <dmlc/timer.h>
#include <iomanip>
#include <ctime>
#include <string>
#include <cstdio>
#include <cstring>
#include <vector>
#include "./common/sync.h"
#include "./common/config.h"
namespace xgboost {
enum CLITask {
kTrain = 0,
kDump2Text = 1,
kPredict = 2
};
struct CLIParam : public dmlc::Parameter<CLIParam> {
/*! \brief the task name */
int task;
/*! \brief whether silent */
int silent;
/*! \brief whether evaluate training statistics */
bool eval_train;
/*! \brief number of boosting iterations */
int num_round;
/*! \brief the period to save the model, 0 means only save the final round model */
int save_period;
/*! \brief the path of training set */
std::string train_path;
/*! \brief path of test dataset */
std::string test_path;
/*! \brief the path of test model file, or file to restart training */
std::string model_in;
/*! \brief the path of final model file, to be saved */
std::string model_out;
/*! \brief the path of directory containing the saved models */
std::string model_dir;
/*! \brief name of predict file */
std::string name_pred;
/*! \brief data split mode */
int dsplit;
/*!\brief limit number of trees in prediction */
int ntree_limit;
/*!\brief whether to directly output margin value */
bool pred_margin;
/*! \brief whether dump statistics along with model */
int dump_stats;
/*! \brief name of feature map */
std::string name_fmap;
/*! \brief name of dump file */
std::string name_dump;
/*! \brief the paths of validation data sets */
std::vector<std::string> eval_data_paths;
/*! \brief the names of the evaluation data used in output log */
std::vector<std::string> eval_data_names;
/*! \brief all the configurations */
std::vector<std::pair<std::string, std::string> > cfg;
// declare parameters
DMLC_DECLARE_PARAMETER(CLIParam) {
// NOTE: declare everything except eval_data_paths.
DMLC_DECLARE_FIELD(task).set_default(kTrain)
.add_enum("train", kTrain)
.add_enum("dump", kDump2Text)
.add_enum("pred", kPredict)
.describe("Task to be performed by the CLI program.");
DMLC_DECLARE_FIELD(silent).set_default(0).set_range(0, 2)
.describe("Silent level during the task.");
DMLC_DECLARE_FIELD(eval_train).set_default(false)
.describe("Whether evaluate on training data during training.");
DMLC_DECLARE_FIELD(num_round).set_default(10).set_lower_bound(1)
.describe("Number of boosting iterations");
DMLC_DECLARE_FIELD(save_period).set_default(0).set_lower_bound(0)
.describe("The period to save the model, 0 means only save final model.");
DMLC_DECLARE_FIELD(train_path).set_default("NULL")
.describe("Training data path.");
DMLC_DECLARE_FIELD(test_path).set_default("NULL")
.describe("Test data path.");
DMLC_DECLARE_FIELD(model_in).set_default("NULL")
.describe("Input model path, if any.");
DMLC_DECLARE_FIELD(model_out).set_default("NULL")
.describe("Output model path, if any.");
DMLC_DECLARE_FIELD(model_dir).set_default("./")
.describe("Output directory of period checkpoint.");
DMLC_DECLARE_FIELD(name_pred).set_default("pred.txt")
.describe("Name of the prediction file.");
DMLC_DECLARE_FIELD(dsplit).set_default(0)
.add_enum("auto", 0)
.add_enum("col", 1)
.add_enum("row", 2)
.describe("Data split mode.");
DMLC_DECLARE_FIELD(ntree_limit).set_default(0).set_lower_bound(0)
.describe("Number of trees used for prediction, 0 means use all trees.");
DMLC_DECLARE_FIELD(pred_margin).set_default(false)
.describe("Whether to predict margin value instead of probability.");
DMLC_DECLARE_FIELD(dump_stats).set_default(false)
.describe("Whether dump the model statistics.");
DMLC_DECLARE_FIELD(name_fmap).set_default("NULL")
.describe("Name of the feature map file.");
DMLC_DECLARE_FIELD(name_dump).set_default("dump.txt")
.describe("Name of the output dump text file.");
// alias
DMLC_DECLARE_ALIAS(train_path, data);
DMLC_DECLARE_ALIAS(test_path, test:data);
DMLC_DECLARE_ALIAS(name_fmap, fmap);
}
// customized configure function of CLIParam
inline void Configure(const std::vector<std::pair<std::string, std::string> >& cfg) {
this->cfg = cfg;
this->InitAllowUnknown(cfg);
for (const auto& kv : cfg) {
if (!strncmp("eval[", kv.first.c_str(), 5)) {
char evname[256];
CHECK_EQ(sscanf(kv.first.c_str(), "eval[%[^]]", evname), 1)
<< "must specify evaluation name for display";
eval_data_names.push_back(std::string(evname));
eval_data_paths.push_back(kv.second);
}
}
// constraint.
if (name_pred == "stdout") {
save_period = 0;
silent = 1;
}
if (dsplit == 0 && rabit::IsDistributed()) {
dsplit = 2;
}
if (rabit::GetRank() != 0) {
silent = 2;
}
}
};
DMLC_REGISTER_PARAMETER(CLIParam);
void CLITrain(const CLIParam& param) {
if (rabit::IsDistributed()) {
std::string pname = rabit::GetProcessorName();
LOG(CONSOLE) << "start " << pname << ":" << rabit::GetRank();
}
// load in data.
std::unique_ptr<DMatrix> dtrain(
DMatrix::Load(param.train_path, param.silent != 0, param.dsplit == 2));
std::vector<std::unique_ptr<DMatrix> > deval;
std::vector<DMatrix*> cache_mats, eval_datasets;
cache_mats.push_back(dtrain.get());
for (size_t i = 0; i < param.eval_data_names.size(); ++i) {
deval.emplace_back(
DMatrix::Load(param.eval_data_paths[i], param.silent != 0, param.dsplit == 2));
eval_datasets.push_back(deval.back().get());
cache_mats.push_back(deval.back().get());
}
std::vector<std::string> eval_data_names = param.eval_data_names;
if (param.eval_train) {
eval_datasets.push_back(dtrain.get());
eval_data_names.push_back(std::string("train"));
}
// initialize the learner.
std::unique_ptr<Learner> learner(Learner::Create(cache_mats));
learner->Configure(param.cfg);
int version = rabit::LoadCheckPoint(learner.get());
if (version == 0) {
// initializ the model if needed.
if (param.model_in != "NULL") {
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
} else {
learner->InitModel();
}
}
// start training.
const double start = dmlc::GetTime();
for (int i = version / 2; i < param.num_round; ++i) {
double elapsed = dmlc::GetTime() - start;
if (version % 2 == 0) {
if (param.silent == 0) {
LOG(CONSOLE) << "boosting round " << i << ", " << elapsed << " sec elapsed";
}
learner->UpdateOneIter(i, dtrain.get());
if (learner->AllowLazyCheckPoint()) {
rabit::LazyCheckPoint(learner.get());
} else {
rabit::CheckPoint(learner.get());
}
version += 1;
}
CHECK_EQ(version, rabit::VersionNumber());
std::string res = learner->EvalOneIter(i, eval_datasets, eval_data_names);
if (rabit::IsDistributed()) {
if (rabit::GetRank() == 0) {
LOG(TRACKER) << res;
}
} else {
if (param.silent < 2) {
LOG(CONSOLE) << res;
}
}
if (param.save_period != 0 &&
(i + 1) % param.save_period == 0 &&
rabit::GetRank() == 0) {
std::ostringstream os;
os << param.model_dir << '/'
<< std::setfill('0') << std::setw(4)
<< i + 1 << ".model";
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(os.str().c_str(), "w"));
learner->Save(fo.get());
}
if (learner->AllowLazyCheckPoint()) {
rabit::LazyCheckPoint(learner.get());
} else {
rabit::CheckPoint(learner.get());
}
version += 1;
CHECK_EQ(version, rabit::VersionNumber());
}
// always save final round
if ((param.save_period == 0 || param.num_round % param.save_period != 0) &&
param.model_out != "NONE" &&
rabit::GetRank() == 0) {
std::ostringstream os;
if (param.model_out == "NULL") {
os << param.model_dir << '/'
<< std::setfill('0') << std::setw(4)
<< param.num_round << ".model";
} else {
os << param.model_out;
}
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(os.str().c_str(), "w"));
learner->Save(fo.get());
}
if (param.silent == 0) {
double elapsed = dmlc::GetTime() - start;
LOG(CONSOLE) << "update end, " << elapsed << " sec in all";
}
}
void CLIDump2Text(const CLIParam& param) {
FeatureMap fmap;
if (param.name_fmap != "NULL") {
std::unique_ptr<dmlc::Stream> fs(
dmlc::Stream::Create(param.name_fmap.c_str(), "r"));
dmlc::istream is(fs.get());
fmap.LoadText(is);
}
// load model
CHECK_NE(param.model_in, "NULL")
<< "Must specifiy model_in for dump";
std::unique_ptr<Learner> learner(Learner::Create({}));
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
// dump data
std::vector<std::string> dump = learner->Dump2Text(fmap, param.dump_stats);
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(param.name_dump.c_str(), "w"));
dmlc::ostream os(fo.get());
for (size_t i = 0; i < dump.size(); ++i) {
os << "booster[" << i << "]:\n";
os << dump[i];
}
// force flush before fo destruct.
os.set_stream(nullptr);
}
void CLIPredict(const CLIParam& param) {
CHECK_NE(param.test_path, "NULL")
<< "Test dataset parameter test:data must be specified.";
// load data
std::unique_ptr<DMatrix> dtest(
DMatrix::Load(param.test_path, param.silent != 0, param.dsplit == 2));
// load model
CHECK_NE(param.model_in, "NULL")
<< "Must specifiy model_in for dump";
std::unique_ptr<Learner> learner(Learner::Create({}));
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
if (param.silent == 0) {
LOG(CONSOLE) << "start prediction...";
}
std::vector<float> preds;
learner->Predict(dtest.get(), param.pred_margin, &preds, param.ntree_limit);
if (param.silent == 0) {
LOG(CONSOLE) << "writing prediction to " << param.name_pred;
}
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(param.name_pred.c_str(), "w"));
dmlc::ostream os(fo.get());
for (float p : preds) {
os << p << '\n';
}
// force flush before fo destruct.
os.set_stream(nullptr);
}
int CLIRunTask(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: <config>\n");
return 0;
}
rabit::Init(argc, argv);
std::vector<std::pair<std::string, std::string> > cfg;
cfg.push_back(std::make_pair("seed", "0"));
common::ConfigIterator itr(argv[1]);
while (itr.Next()) {
cfg.push_back(std::make_pair(std::string(itr.name()), std::string(itr.val())));
}
for (int i = 2; i < argc; ++i) {
char name[256], val[256];
if (sscanf(argv[i], "%[^=]=%s", name, val) == 2) {
cfg.push_back(std::make_pair(std::string(name), std::string(val)));
}
}
CLIParam param;
param.Configure(cfg);
switch (param.task) {
case kTrain: CLITrain(param); break;
case kDump2Text: CLIDump2Text(param); break;
case kPredict: CLIPredict(param); break;
}
rabit::Finalize();
return 0;
}
} // namespace xgboost
int main(int argc, char *argv[]) {
return xgboost::CLIRunTask(argc, argv);
}
<commit_msg>Fix continue training in CLI<commit_after>/*!
* Copyright 2014 by Contributors
* \file cli_main.cc
* \brief The command line interface program of xgboost.
* This file is not included in dynamic library.
*/
// Copyright 2014 by Contributors
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX
#include <xgboost/learner.h>
#include <xgboost/data.h>
#include <xgboost/logging.h>
#include <dmlc/timer.h>
#include <iomanip>
#include <ctime>
#include <string>
#include <cstdio>
#include <cstring>
#include <vector>
#include "./common/sync.h"
#include "./common/config.h"
namespace xgboost {
enum CLITask {
kTrain = 0,
kDump2Text = 1,
kPredict = 2
};
struct CLIParam : public dmlc::Parameter<CLIParam> {
/*! \brief the task name */
int task;
/*! \brief whether silent */
int silent;
/*! \brief whether evaluate training statistics */
bool eval_train;
/*! \brief number of boosting iterations */
int num_round;
/*! \brief the period to save the model, 0 means only save the final round model */
int save_period;
/*! \brief the path of training set */
std::string train_path;
/*! \brief path of test dataset */
std::string test_path;
/*! \brief the path of test model file, or file to restart training */
std::string model_in;
/*! \brief the path of final model file, to be saved */
std::string model_out;
/*! \brief the path of directory containing the saved models */
std::string model_dir;
/*! \brief name of predict file */
std::string name_pred;
/*! \brief data split mode */
int dsplit;
/*!\brief limit number of trees in prediction */
int ntree_limit;
/*!\brief whether to directly output margin value */
bool pred_margin;
/*! \brief whether dump statistics along with model */
int dump_stats;
/*! \brief name of feature map */
std::string name_fmap;
/*! \brief name of dump file */
std::string name_dump;
/*! \brief the paths of validation data sets */
std::vector<std::string> eval_data_paths;
/*! \brief the names of the evaluation data used in output log */
std::vector<std::string> eval_data_names;
/*! \brief all the configurations */
std::vector<std::pair<std::string, std::string> > cfg;
// declare parameters
DMLC_DECLARE_PARAMETER(CLIParam) {
// NOTE: declare everything except eval_data_paths.
DMLC_DECLARE_FIELD(task).set_default(kTrain)
.add_enum("train", kTrain)
.add_enum("dump", kDump2Text)
.add_enum("pred", kPredict)
.describe("Task to be performed by the CLI program.");
DMLC_DECLARE_FIELD(silent).set_default(0).set_range(0, 2)
.describe("Silent level during the task.");
DMLC_DECLARE_FIELD(eval_train).set_default(false)
.describe("Whether evaluate on training data during training.");
DMLC_DECLARE_FIELD(num_round).set_default(10).set_lower_bound(1)
.describe("Number of boosting iterations");
DMLC_DECLARE_FIELD(save_period).set_default(0).set_lower_bound(0)
.describe("The period to save the model, 0 means only save final model.");
DMLC_DECLARE_FIELD(train_path).set_default("NULL")
.describe("Training data path.");
DMLC_DECLARE_FIELD(test_path).set_default("NULL")
.describe("Test data path.");
DMLC_DECLARE_FIELD(model_in).set_default("NULL")
.describe("Input model path, if any.");
DMLC_DECLARE_FIELD(model_out).set_default("NULL")
.describe("Output model path, if any.");
DMLC_DECLARE_FIELD(model_dir).set_default("./")
.describe("Output directory of period checkpoint.");
DMLC_DECLARE_FIELD(name_pred).set_default("pred.txt")
.describe("Name of the prediction file.");
DMLC_DECLARE_FIELD(dsplit).set_default(0)
.add_enum("auto", 0)
.add_enum("col", 1)
.add_enum("row", 2)
.describe("Data split mode.");
DMLC_DECLARE_FIELD(ntree_limit).set_default(0).set_lower_bound(0)
.describe("Number of trees used for prediction, 0 means use all trees.");
DMLC_DECLARE_FIELD(pred_margin).set_default(false)
.describe("Whether to predict margin value instead of probability.");
DMLC_DECLARE_FIELD(dump_stats).set_default(false)
.describe("Whether dump the model statistics.");
DMLC_DECLARE_FIELD(name_fmap).set_default("NULL")
.describe("Name of the feature map file.");
DMLC_DECLARE_FIELD(name_dump).set_default("dump.txt")
.describe("Name of the output dump text file.");
// alias
DMLC_DECLARE_ALIAS(train_path, data);
DMLC_DECLARE_ALIAS(test_path, test:data);
DMLC_DECLARE_ALIAS(name_fmap, fmap);
}
// customized configure function of CLIParam
inline void Configure(const std::vector<std::pair<std::string, std::string> >& cfg) {
this->cfg = cfg;
this->InitAllowUnknown(cfg);
for (const auto& kv : cfg) {
if (!strncmp("eval[", kv.first.c_str(), 5)) {
char evname[256];
CHECK_EQ(sscanf(kv.first.c_str(), "eval[%[^]]", evname), 1)
<< "must specify evaluation name for display";
eval_data_names.push_back(std::string(evname));
eval_data_paths.push_back(kv.second);
}
}
// constraint.
if (name_pred == "stdout") {
save_period = 0;
silent = 1;
}
if (dsplit == 0 && rabit::IsDistributed()) {
dsplit = 2;
}
if (rabit::GetRank() != 0) {
silent = 2;
}
}
};
DMLC_REGISTER_PARAMETER(CLIParam);
void CLITrain(const CLIParam& param) {
if (rabit::IsDistributed()) {
std::string pname = rabit::GetProcessorName();
LOG(CONSOLE) << "start " << pname << ":" << rabit::GetRank();
}
// load in data.
std::unique_ptr<DMatrix> dtrain(
DMatrix::Load(param.train_path, param.silent != 0, param.dsplit == 2));
std::vector<std::unique_ptr<DMatrix> > deval;
std::vector<DMatrix*> cache_mats, eval_datasets;
cache_mats.push_back(dtrain.get());
for (size_t i = 0; i < param.eval_data_names.size(); ++i) {
deval.emplace_back(
DMatrix::Load(param.eval_data_paths[i], param.silent != 0, param.dsplit == 2));
eval_datasets.push_back(deval.back().get());
cache_mats.push_back(deval.back().get());
}
std::vector<std::string> eval_data_names = param.eval_data_names;
if (param.eval_train) {
eval_datasets.push_back(dtrain.get());
eval_data_names.push_back(std::string("train"));
}
// initialize the learner.
std::unique_ptr<Learner> learner(Learner::Create(cache_mats));
int version = rabit::LoadCheckPoint(learner.get());
if (version == 0) {
// initializ the model if needed.
if (param.model_in != "NULL") {
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
learner->Configure(param.cfg);
} else {
learner->Configure(param.cfg);
learner->InitModel();
}
}
// start training.
const double start = dmlc::GetTime();
for (int i = version / 2; i < param.num_round; ++i) {
double elapsed = dmlc::GetTime() - start;
if (version % 2 == 0) {
if (param.silent == 0) {
LOG(CONSOLE) << "boosting round " << i << ", " << elapsed << " sec elapsed";
}
learner->UpdateOneIter(i, dtrain.get());
if (learner->AllowLazyCheckPoint()) {
rabit::LazyCheckPoint(learner.get());
} else {
rabit::CheckPoint(learner.get());
}
version += 1;
}
CHECK_EQ(version, rabit::VersionNumber());
std::string res = learner->EvalOneIter(i, eval_datasets, eval_data_names);
if (rabit::IsDistributed()) {
if (rabit::GetRank() == 0) {
LOG(TRACKER) << res;
}
} else {
if (param.silent < 2) {
LOG(CONSOLE) << res;
}
}
if (param.save_period != 0 &&
(i + 1) % param.save_period == 0 &&
rabit::GetRank() == 0) {
std::ostringstream os;
os << param.model_dir << '/'
<< std::setfill('0') << std::setw(4)
<< i + 1 << ".model";
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(os.str().c_str(), "w"));
learner->Save(fo.get());
}
if (learner->AllowLazyCheckPoint()) {
rabit::LazyCheckPoint(learner.get());
} else {
rabit::CheckPoint(learner.get());
}
version += 1;
CHECK_EQ(version, rabit::VersionNumber());
}
// always save final round
if ((param.save_period == 0 || param.num_round % param.save_period != 0) &&
param.model_out != "NONE" &&
rabit::GetRank() == 0) {
std::ostringstream os;
if (param.model_out == "NULL") {
os << param.model_dir << '/'
<< std::setfill('0') << std::setw(4)
<< param.num_round << ".model";
} else {
os << param.model_out;
}
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(os.str().c_str(), "w"));
learner->Save(fo.get());
}
if (param.silent == 0) {
double elapsed = dmlc::GetTime() - start;
LOG(CONSOLE) << "update end, " << elapsed << " sec in all";
}
}
void CLIDump2Text(const CLIParam& param) {
FeatureMap fmap;
if (param.name_fmap != "NULL") {
std::unique_ptr<dmlc::Stream> fs(
dmlc::Stream::Create(param.name_fmap.c_str(), "r"));
dmlc::istream is(fs.get());
fmap.LoadText(is);
}
// load model
CHECK_NE(param.model_in, "NULL")
<< "Must specifiy model_in for dump";
std::unique_ptr<Learner> learner(Learner::Create({}));
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
// dump data
std::vector<std::string> dump = learner->Dump2Text(fmap, param.dump_stats);
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(param.name_dump.c_str(), "w"));
dmlc::ostream os(fo.get());
for (size_t i = 0; i < dump.size(); ++i) {
os << "booster[" << i << "]:\n";
os << dump[i];
}
// force flush before fo destruct.
os.set_stream(nullptr);
}
void CLIPredict(const CLIParam& param) {
CHECK_NE(param.test_path, "NULL")
<< "Test dataset parameter test:data must be specified.";
// load data
std::unique_ptr<DMatrix> dtest(
DMatrix::Load(param.test_path, param.silent != 0, param.dsplit == 2));
// load model
CHECK_NE(param.model_in, "NULL")
<< "Must specifiy model_in for dump";
std::unique_ptr<Learner> learner(Learner::Create({}));
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(param.model_in.c_str(), "r"));
learner->Load(fi.get());
if (param.silent == 0) {
LOG(CONSOLE) << "start prediction...";
}
std::vector<float> preds;
learner->Predict(dtest.get(), param.pred_margin, &preds, param.ntree_limit);
if (param.silent == 0) {
LOG(CONSOLE) << "writing prediction to " << param.name_pred;
}
std::unique_ptr<dmlc::Stream> fo(
dmlc::Stream::Create(param.name_pred.c_str(), "w"));
dmlc::ostream os(fo.get());
for (float p : preds) {
os << p << '\n';
}
// force flush before fo destruct.
os.set_stream(nullptr);
}
int CLIRunTask(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: <config>\n");
return 0;
}
rabit::Init(argc, argv);
std::vector<std::pair<std::string, std::string> > cfg;
cfg.push_back(std::make_pair("seed", "0"));
common::ConfigIterator itr(argv[1]);
while (itr.Next()) {
cfg.push_back(std::make_pair(std::string(itr.name()), std::string(itr.val())));
}
for (int i = 2; i < argc; ++i) {
char name[256], val[256];
if (sscanf(argv[i], "%[^=]=%s", name, val) == 2) {
cfg.push_back(std::make_pair(std::string(name), std::string(val)));
}
}
CLIParam param;
param.Configure(cfg);
switch (param.task) {
case kTrain: CLITrain(param); break;
case kDump2Text: CLIDump2Text(param); break;
case kPredict: CLIPredict(param); break;
}
rabit::Finalize();
return 0;
}
} // namespace xgboost
int main(int argc, char *argv[]) {
return xgboost::CLIRunTask(argc, argv);
}
<|endoftext|>
|
<commit_before>#include "checksum.h"
#include "filesystem.h"
#include "ifile.h"
#include <fstream>
namespace platform {
boost::uint32_t fileChecksum( std::string const& filename )
{
boost::uint32_t checksum(0);
std::string data;
// case 1: is it in data.pkg?
Filesys& fs( Filesys::Get() );
std::auto_ptr<File> f( fs.Open( filename ) );
if ( NULL == f.get() )
{
// case 2: is it a regular file?
std::ifstream ifs( filename );
if ( !ifs.good() )
{
return checksum;
}
std::stringstream ss;
ss << ifs.rdbuf();
data = ss.str();
ifs.close();
}
else
{
f->ReadAll( data );
}
boost::crc_32_type result;
result.process_bytes( data.data(), data.length() );
checksum = result.checksum();
return checksum;
}
}
<commit_msg>add EOL conversion for win <-> linux checksum interoperability<commit_after>#include "checksum.h"
#include "filesystem.h"
#include "ifile.h"
#include <fstream>
namespace platform {
boost::uint32_t fileChecksum( std::string const& filename )
{
boost::uint32_t checksum(0);
std::string data;
// case 1: is it in data.pkg?
Filesys& fs( Filesys::Get() );
std::auto_ptr<File> f( fs.Open( filename ) );
if ( NULL == f.get() )
{
// case 2: is it a regular file?
std::ifstream ifs( filename );
if ( !ifs.good() )
{
return checksum;
}
std::stringstream ss;
ss << ifs.rdbuf();
data = ss.str();
ifs.close();
}
else
{
f->ReadAll( data );
}
std::string dataNoEol("");
size_t eolPos = 0;
// convert EOL \r\n (win) to \r (UNIX-like including Mac OS) to make checksum checking cross platform
while( true )
{
size_t last = eolPos;
eolPos = data.find("\r\n", last );
if ( std::string::npos != eolPos )
{
dataNoEol += (data.substr( last, eolPos-last )+'\n');
eolPos++;
}
else
{
break;
}
}
boost::crc_32_type result;
result.process_bytes( dataNoEol.data(), dataNoEol.length() );
checksum = result.checksum();
return checksum;
}
}
<|endoftext|>
|
<commit_before>#include <string>
#include <fstream>
#include <lua.hpp>
#include <luabind/luabind.hpp>
#include "externals/json/json.h"
#include "animatedimage.h"
#include "button.h"
#include "camera.h"
#include "color.h"
#include "entity.h"
#include "input.h"
#include "math.h"
#include "motionstate.h"
#include "physics.h"
#include "rect.h"
#include "state.h"
#include "statemanager.h"
#include "text.h"
#include "timer.h"
#include "vectors.h"
#include "window.h"
#include "debug.h"
#include "luac/luacscript.h"
#include "luascript.h"
LuaScript::LuaScript() : mL(nullptr), mFile(""){
}
LuaScript::LuaScript(std::string script) : mL(nullptr), mFile(""){
OpenScript(script);
}
LuaScript::~LuaScript(){
Close();
}
void LuaScript::OpenScript(const std::string &script){
//If the new script name is valid, open it
if (script != ""){
//Close currently open script if one is open
Close();
mFile = script;
mL = lua_open();
luaL_openlibs(mL);
luabind::open(mL);
AddLoader(LuaC::LuaScriptLib::requireLib);
AddLoader(LuaC::LuaScriptLib::requireScript);
luaL_dofile(mL, mFile.c_str());
}
}
void LuaScript::Close(){
if (Open()){
lua_close(mL);
mL = nullptr;
}
}
lua_State* LuaScript::Get(){
return mL;
}
std::string LuaScript::File() const {
return mFile;
}
bool LuaScript::Open() const {
return (mL != nullptr);
}
void LuaScript::AddLoader(int (*loader)(lua_State*)){
//Get the package.loaders table
lua_getfield(mL, LUA_GLOBALSINDEX, "package");
//Stack: package table
//Get the loaders table
lua_getfield(mL, -1, "loaders");
//Stack: package table, loaders table
//Remove the package table
lua_remove(mL, -2);
//Stack: loaders table
//Count the # of loaders
int n = 0;
//We push nil so we can know when we hit the end
lua_pushnil(mL);
//Go through the loaders table and count # entries
while (lua_next(mL, -2) != 0){
lua_pop(mL, 1);
++n;
}
//Stack: loaders table
//Add our function
lua_pushinteger(mL, n + 1);
//Stack: loaders table, index to add fcn to
lua_pushcfunction(mL, loader);
//Stack: loaders table, index to add fcn to, fcn
//Add it to the loaders table
lua_rawset(mL, -3);
//Stack: loaders table
//Pop the table off
lua_pop(mL, 1);
}<commit_msg>Have checked through all existing Lua Libs they should all be ok<commit_after>#include <string>
#include <fstream>
#include <lua.hpp>
#include <luabind/luabind.hpp>
#include "externals/json/json.h"
#include "animatedimage.h"
#include "button.h"
#include "camera.h"
#include "color.h"
#include "entity.h"
#include "input.h"
#include "math.h"
#include "motionstate.h"
#include "physics.h"
#include "rect.h"
#include "state.h"
#include "statemanager.h"
#include "text.h"
#include "timer.h"
#include "vectors.h"
#include "window.h"
#include "debug.h"
#include "luac/luacscript.h"
#include "luascript.h"
LuaScript::LuaScript() : mL(nullptr), mFile(""){
}
LuaScript::LuaScript(std::string script) : mL(nullptr), mFile(""){
OpenScript(script);
}
LuaScript::~LuaScript(){
Close();
}
void LuaScript::OpenScript(const std::string &script){
//If the new script name is valid, open it
if (script != ""){
//Close currently open script if one is open
Close();
mFile = script;
mL = lua_open();
luaL_openlibs(mL);
luabind::open(mL);
AddLoader(LuaC::LuaScriptLib::requireLib);
AddLoader(LuaC::LuaScriptLib::requireScript);
luaL_dofile(mL, mFile.c_str());
}
}
void LuaScript::Close(){
if (Open()){
lua_close(mL);
mL = nullptr;
}
}
lua_State* LuaScript::Get(){
return mL;
}
std::string LuaScript::File() const {
return mFile;
}
bool LuaScript::Open() const {
return (mL != nullptr);
}
void LuaScript::AddLoader(int (*loader)(lua_State*)){
//We want to get the package.loaders table and add a new entry
lua_getfield(mL, LUA_GLOBALSINDEX, "package");
//Stack: package table
//Get the loaders table
lua_getfield(mL, -1, "loaders");
//Stack: package table, loaders table
//Remove the package table
lua_remove(mL, -2);
//Stack: loaders table
//Count the # of loaders
int n = 0;
//We push nil so we can know when we hit the end
lua_pushnil(mL);
//Go through the loaders table and count # entries
while (lua_next(mL, -2) != 0){
lua_pop(mL, 1);
++n;
}
//Stack: loaders table
//Add our function
lua_pushinteger(mL, n + 1);
//Stack: loaders table, index to add fcn to
lua_pushcfunction(mL, loader);
//Stack: loaders table, index to add fcn to, fcn
//Add it to the loaders table
lua_rawset(mL, -3);
//Stack: loaders table
//Pop the table off
lua_pop(mL, 1);
}<|endoftext|>
|
<commit_before>/*
* CliqueGTest.cpp
*
* Created on: 08.12.2014
* Author: henningm
*/
#include "CliqueGTest.h"
#include "../MaxClique.h"
#include "../../io/METISGraphReader.h"
#include "../../io/SNAPGraphReader.h"
#include "../../auxiliary/Log.h"
#include "../../io/EdgeListReader.h"
namespace NetworKit {
//TEST_F(CliqueGTest, testMaxClique1) {
// SNAPGraphReader sreader;
// Graph G1 = sreader.read("input/email-Enron.txt");
// MaxClique mc1(G1);
// count maxCliqueSize1 = mc1.run();
// EXPECT_EQ(20, maxCliqueSize1);
// METISGraphReader mreader;
// Graph G2 = mreader.read("input/kkt_power.graph");
// MaxClique mc2(G2);
// count maxCliqueSize2 = mc2.run();
// EXPECT_EQ(11, maxCliqueSize2);
//}
TEST_F(CliqueGTest, testMaxCliqueOnSmallerGraphs) {
EdgeListReader r(' ',1,"%");
Graph gKeller = r.read("input/keller4.edgelist");
Graph gJohnson = r.read("input/johnson8-4-4.edgelist");
Graph gHamming = r.read("input/hamming6-4.edgelist");
MaxClique mcKeller(gKeller);
MaxClique mcJohnson(gJohnson);
MaxClique mcHamming(gHamming);
//count maxCliqueSizeKeller = mcKeller.run();
mcJohnson.run();
count maxCliqueSizeJohnson = mcJohnson.getMaxCliqueSize();
mcHamming.run();
count maxCliqueSizeHamming = mcHamming.getMaxCliqueSize();
//EXPECT_EQ(11,maxCliqueSizeKeller) << "maximum clique size on graph keller4 is not correct";
EXPECT_EQ(14u,maxCliqueSizeJohnson) << "maximum clique size on graph johnson8-4-4 is not correct";
EXPECT_EQ(4u,maxCliqueSizeHamming) << "maximum clique size on graph hamming6-4 is not correct";
std::unordered_set<node> cliqueJohnson = mcJohnson.getMaxClique();
std::unordered_set<node> cliqueHamming = mcHamming.getMaxClique();
EXPECT_EQ(14u, cliqueJohnson.size());
EXPECT_EQ(4u, cliqueHamming.size());
}
} /* namespace NetworKit */
<commit_msg>eliminated compiler warnings<commit_after>/*
* CliqueGTest.cpp
*
* Created on: 08.12.2014
* Author: henningm
*/
#include "CliqueGTest.h"
#include "../MaxClique.h"
#include "../../io/METISGraphReader.h"
#include "../../io/SNAPGraphReader.h"
#include "../../auxiliary/Log.h"
#include "../../io/EdgeListReader.h"
namespace NetworKit {
TEST_F(CliqueGTest, testMaxCliqueOnSmallerGraphs) {
EdgeListReader r(' ',1,"%");
Graph gJohnson = r.read("input/johnson8-4-4.edgelist");
Graph gHamming = r.read("input/hamming6-4.edgelist");
MaxClique mcJohnson(gJohnson);
MaxClique mcHamming(gHamming);
mcJohnson.run();
count maxCliqueSizeJohnson = mcJohnson.getMaxCliqueSize();
mcHamming.run();
count maxCliqueSizeHamming = mcHamming.getMaxCliqueSize();
EXPECT_EQ(14u,maxCliqueSizeJohnson) << "maximum clique size on graph johnson8-4-4 is not correct";
EXPECT_EQ(4u,maxCliqueSizeHamming) << "maximum clique size on graph hamming6-4 is not correct";
std::unordered_set<node> cliqueJohnson = mcJohnson.getMaxClique();
std::unordered_set<node> cliqueHamming = mcHamming.getMaxClique();
EXPECT_EQ(14u, cliqueJohnson.size());
EXPECT_EQ(4u, cliqueHamming.size());
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2007 Simon Peter, <[email protected]>, et al.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* playertest.cpp - Test AdPlug replayers, by Simon Peter <[email protected]>
*/
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include "../src/adplug.h"
#include "../src/opl.h"
#ifdef MSDOS
# define DIR_DELIM "\\"
#else
# define DIR_DELIM "/"
#endif
/***** Local variables *****/
// List of all filenames to test
static const char *filelist[] = {
"SONG1.sng", // Adlib Tracker
"2001.MKJ", // MK-Jamz
"ADAGIO.DFM", // Digital-FM
"adlibsp.s3m", // Scream Tracker 3
"ALLOYRUN.RAD", // Reality AdLib Tracker
"ARAB.BAM", // Bob's AdLib Music
"BEGIN.KSM", // Ken Silverman
"BOOTUP.M", // Ultima 6
"CHILD1.XSM", // eXtra Simple Music
"DTM-TRK1.DTM", // DeFy Adlib Tracker
"fdance03.dmo", // TwinTrack
"ice_thnk.sci", // Sierra
"inc.raw", // RAW
"loudness.lds", // Loudness
"MARIO.A2M", // AdLib Tracker 2
"mi2.laa", // LucasArts
"michaeld.cmf", // Creative Music Format
"PLAYMUS1.SNG", // SNGPlay
"rat.xad", // xad: rat
"REVELAT.SNG", // Faust Music Creator
"SAILOR.CFF", // Boomtracker
"samurai.dro", // DOSBox
"SCALES.SA2", // Surprise! Adlib Tracker 2
"SMKEREM.HSC", // HSC-Tracker
"TOCCATA.MAD", // Mlat Adlib Tracker
"TUBES.SAT", // Surprise! Adlib Tracker
"TU_BLESS.AMD", // AMUSIC
"VIB_VOL3.D00", // EdLib Packed
"WONDERIN.WLF", // Apogee
"bmf1_2.xad", // xad: BMF
"flash.xad", // xad: flash
"HIP_D.ROL", // Visual Composer
"hybrid.xad", // xad: hybrid
"hyp.xad", // xad: hyp
"psi1.xad", // xad: PSI
"SATNIGHT.HSP", // HSC Packed
"blaster2.msc", // AdLib MSCplay
"RI051.RIX", // Softstar RIX OPL Music
"DUNE19.ADL", // Westwood ADL
"DEMO4.JBM", // JBM Adlib Music
NULL
};
// String holding the relative path to the source directory
static char *srcdir;
/***** Testopl *****/
class Testopl: public Copl
{
public:
Testopl(const std::string filename)
{
f = fopen(filename.c_str(), "w");
if(!f) std::cerr << "Error opening for writing: " << filename << std::endl;
currType = TYPE_OPL3;
}
virtual ~Testopl()
{
if(f) fclose(f);
}
void update(CPlayer *p)
{
if(!f) return;
fprintf(f, "r%.2f\n", p->getrefresh());
}
// template methods
void write(int reg, int val)
{
if(reg > 255 || val > 255 || reg < 0 || val < 0)
std::cerr << "Warning: The player is writing data out of range! (reg = "
<< std::hex << reg << ", val = " << val << ")\n";
if(!f) return;
fprintf(f, "%x <- %x\n", reg, val);
}
void setchip(int n)
{
Copl::setchip(n);
if(!f) return;
fprintf(f, "setchip(%d)\n", n);
}
void init()
{
if(!f) return;
fprintf(f, "init\n");
}
private:
FILE *f;
};
/***** Local functions *****/
static bool diff(const std::string fn1, const std::string fn2)
/*
* Compares files 'fn1' and 'fn2' line by line and returns true if they are
* equal or false otherwise. A line is at most 79 characters in length or the
* comparison will fail.
*/
{
FILE *f1, *f2;
bool retval = true;
// open both files
if(!(f1 = fopen(fn1.c_str(), "r"))) return false;
if(!(f2 = fopen(fn2.c_str(), "r"))) { fclose(f1); return false; }
// compare both files line by line
char *s1 = (char *)malloc(80), *s2 = (char *)malloc(80);
while(!(feof(f1) || feof(f2))) {
fgets(s1, 80, f1);
fgets(s2, 80, f2);
if(strncmp(s1, s2, 79)) {
retval = false;
break;
}
}
free(s1), free(s2);
if(feof(f1) != feof(f2))
retval = false;
// close both files
fclose(f1), fclose(f2);
return retval;
}
static bool testplayer(const std::string filename)
/*
* Tests playback of file 'filename' by comparing its RAW output with a
* prerecorded original and returns true if they match, false otherwise.
*/
{
std::string fn = std::string(srcdir) + DIR_DELIM + filename;
#ifdef __WATCOMC__
std::string testfn = tmpnam(NULL);
#else
std::string testfn = filename + ".test";
#endif
std::string reffn = fn.substr(0, fn.find_last_of(".")) + ".ref";
Testopl *opl = new Testopl(testfn);
CPlayer *p = CAdPlug::factory(fn, opl);
if(!p) {
std::cout << "Error loading: " << fn << std::endl;
delete opl; return false;
}
// Output file information
std::cout << "Testing format: " << p->gettype() << " - ";
// Write whole file to disk
while(p->update())
opl->update(p);
delete p;
delete opl;
if(diff(reffn, testfn)) {
std::cout << "OK\n";
remove(std::string(testfn).c_str());
return true;
} else {
std::cout << "FAIL\n";
return false;
}
}
/***** Main program *****/
int main(int argc, char *argv[])
{
int i;
bool retval = true;
// Set path to source directory
srcdir = getenv("srcdir");
if(!srcdir) srcdir = ".";
// Try all files one by one
if(argc > 1) {
for(i = 1; i < argc; i++)
if(!testplayer(argv[i]))
retval = false;
} else
for(i = 0; filelist[i] != NULL; i++)
if(!testplayer(filelist[i]))
retval = false;
return retval ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Fixed undefined reference to strncmp() error and deprecated string conversion warning.<commit_after>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2008 Simon Peter, <[email protected]>, et al.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* playertest.cpp - Test AdPlug replayers, by Simon Peter <[email protected]>
*/
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <string>
#include "../src/adplug.h"
#include "../src/opl.h"
#ifdef MSDOS
# define DIR_DELIM "\\"
#else
# define DIR_DELIM "/"
#endif
/***** Local variables *****/
// List of all filenames to test
static const char *filelist[] = {
"SONG1.sng", // Adlib Tracker
"2001.MKJ", // MK-Jamz
"ADAGIO.DFM", // Digital-FM
"adlibsp.s3m", // Scream Tracker 3
"ALLOYRUN.RAD", // Reality AdLib Tracker
"ARAB.BAM", // Bob's AdLib Music
"BEGIN.KSM", // Ken Silverman
"BOOTUP.M", // Ultima 6
"CHILD1.XSM", // eXtra Simple Music
"DTM-TRK1.DTM", // DeFy Adlib Tracker
"fdance03.dmo", // TwinTrack
"ice_thnk.sci", // Sierra
"inc.raw", // RAW
"loudness.lds", // Loudness
"MARIO.A2M", // AdLib Tracker 2
"mi2.laa", // LucasArts
"michaeld.cmf", // Creative Music Format
"PLAYMUS1.SNG", // SNGPlay
"rat.xad", // xad: rat
"REVELAT.SNG", // Faust Music Creator
"SAILOR.CFF", // Boomtracker
"samurai.dro", // DOSBox
"SCALES.SA2", // Surprise! Adlib Tracker 2
"SMKEREM.HSC", // HSC-Tracker
"TOCCATA.MAD", // Mlat Adlib Tracker
"TUBES.SAT", // Surprise! Adlib Tracker
"TU_BLESS.AMD", // AMUSIC
"VIB_VOL3.D00", // EdLib Packed
"WONDERIN.WLF", // Apogee
"bmf1_2.xad", // xad: BMF
"flash.xad", // xad: flash
"HIP_D.ROL", // Visual Composer
"hybrid.xad", // xad: hybrid
"hyp.xad", // xad: hyp
"psi1.xad", // xad: PSI
"SATNIGHT.HSP", // HSC Packed
"blaster2.msc", // AdLib MSCplay
"RI051.RIX", // Softstar RIX OPL Music
"DUNE19.ADL", // Westwood ADL
"DEMO4.JBM", // JBM Adlib Music
NULL
};
// String holding the relative path to the source directory
static const char *srcdir;
/***** Testopl *****/
class Testopl: public Copl
{
public:
Testopl(const std::string filename)
{
f = fopen(filename.c_str(), "w");
if(!f) std::cerr << "Error opening for writing: " << filename << std::endl;
currType = TYPE_OPL3;
}
virtual ~Testopl()
{
if(f) fclose(f);
}
void update(CPlayer *p)
{
if(!f) return;
fprintf(f, "r%.2f\n", p->getrefresh());
}
// template methods
void write(int reg, int val)
{
if(reg > 255 || val > 255 || reg < 0 || val < 0)
std::cerr << "Warning: The player is writing data out of range! (reg = "
<< std::hex << reg << ", val = " << val << ")\n";
if(!f) return;
fprintf(f, "%x <- %x\n", reg, val);
}
void setchip(int n)
{
Copl::setchip(n);
if(!f) return;
fprintf(f, "setchip(%d)\n", n);
}
void init()
{
if(!f) return;
fprintf(f, "init\n");
}
private:
FILE *f;
};
/***** Local functions *****/
static bool diff(const std::string fn1, const std::string fn2)
/*
* Compares files 'fn1' and 'fn2' line by line and returns true if they are
* equal or false otherwise. A line is at most 79 characters in length or the
* comparison will fail.
*/
{
FILE *f1, *f2;
bool retval = true;
// open both files
if(!(f1 = fopen(fn1.c_str(), "r"))) return false;
if(!(f2 = fopen(fn2.c_str(), "r"))) { fclose(f1); return false; }
// compare both files line by line
char *s1 = (char *)malloc(80), *s2 = (char *)malloc(80);
while(!(feof(f1) || feof(f2))) {
fgets(s1, 80, f1);
fgets(s2, 80, f2);
if(strncmp(s1, s2, 79)) {
retval = false;
break;
}
}
free(s1), free(s2);
if(feof(f1) != feof(f2))
retval = false;
// close both files
fclose(f1), fclose(f2);
return retval;
}
static bool testplayer(const std::string filename)
/*
* Tests playback of file 'filename' by comparing its RAW output with a
* prerecorded original and returns true if they match, false otherwise.
*/
{
std::string fn = std::string(srcdir) + DIR_DELIM + filename;
#ifdef __WATCOMC__
std::string testfn = tmpnam(NULL);
#else
std::string testfn = filename + ".test";
#endif
std::string reffn = fn.substr(0, fn.find_last_of(".")) + ".ref";
Testopl *opl = new Testopl(testfn);
CPlayer *p = CAdPlug::factory(fn, opl);
if(!p) {
std::cout << "Error loading: " << fn << std::endl;
delete opl; return false;
}
// Output file information
std::cout << "Testing format: " << p->gettype() << " - ";
// Write whole file to disk
while(p->update())
opl->update(p);
delete p;
delete opl;
if(diff(reffn, testfn)) {
std::cout << "OK\n";
remove(std::string(testfn).c_str());
return true;
} else {
std::cout << "FAIL\n";
return false;
}
}
/***** Main program *****/
int main(int argc, char *argv[])
{
int i;
bool retval = true;
// Set path to source directory
srcdir = getenv("srcdir");
if(!srcdir) srcdir = ".";
// Try all files one by one
if(argc > 1) {
for(i = 1; i < argc; i++)
if(!testplayer(argv[i]))
retval = false;
} else
for(i = 0; filelist[i] != NULL; i++)
if(!testplayer(filelist[i]))
retval = false;
return retval ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is [email protected]
//
#include "TouchEvent.h"
#include "../graphics/Bitmap.h"
#include "../graphics/Filterfill.h"
#include "../graphics/Pixel8.h"
#include "../base/Logger.h"
using namespace std;
namespace avg {
TouchEvent::TouchEvent(int id, Type EventType, BlobPtr pBlob, const IntPoint& Pos,
Source source, const DPoint& speed, const IntPoint& lastDownPos)
: CursorEvent(id, EventType, Pos, source),
m_pBlob(pBlob),
m_Speed(speed)
{
setLastDownPos(lastDownPos);
}
TouchEvent::~TouchEvent()
{
}
CursorEventPtr TouchEvent::cloneAs(Type EventType) const
{
TouchEventPtr pClone(new TouchEvent(*this));
pClone->m_Type = EventType;
return pClone;
}
const DPoint& TouchEvent::getSpeed() const
{
return m_Speed;
}
const BlobPtr TouchEvent::getBlob() const
{
return m_pBlob;
}
const DPoint & TouchEvent::getMajorAxis() const
{
const DPoint & Axis0 = m_pBlob->getScaledBasis(0);
const DPoint & Axis1 = m_pBlob->getScaledBasis(1);
if (calcDist(Axis0, DPoint(0,0)) > calcDist(Axis1, DPoint(0,0))) {
return Axis0;
} else {
return Axis1;
}
}
const DPoint & TouchEvent::getMinorAxis() const
{
const DPoint & Axis0 = m_pBlob->getScaledBasis(0);
const DPoint & Axis1 = m_pBlob->getScaledBasis(1);
if (calcDist(Axis0, DPoint(0,0)) > calcDist(Axis1, DPoint(0,0))) {
return Axis1;
} else {
return Axis0;
}
}
ContourSeq TouchEvent::getContour()
{
return m_pBlob->getContour();
}
void TouchEvent::addRelatedEvent(TouchEventPtr pEvent)
{
m_RelatedEvents.push_back(pEvent);
}
vector<TouchEventPtr> TouchEvent::getRelatedEvents() const
{
vector<TouchEventPtr> pRelatedEvents;
vector<TouchEventWeakPtr>::const_iterator it;
for (it=m_RelatedEvents.begin(); it != m_RelatedEvents.end(); ++it) {
pRelatedEvents.push_back((*it).lock());
}
return pRelatedEvents;
}
void TouchEvent::trace()
{
Event::trace();
if(m_pBlob) {
AVG_TRACE(Logger::EVENTS2, "pos: " << m_Position
<< ", ID: " << getCursorID()
<< ", Area: " << m_pBlob->getArea()
<< ", Eccentricity: " << m_pBlob->getEccentricity());
}
else {
AVG_TRACE(Logger::EVENTS2, "pos: " << m_Position
<< ", ID: " << getCursorID());
}
}
}
<commit_msg>Reverted bogus change to TouchEvent.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is [email protected]
//
#include "TouchEvent.h"
#include "../graphics/Bitmap.h"
#include "../graphics/Filterfill.h"
#include "../graphics/Pixel8.h"
#include "../base/Logger.h"
using namespace std;
namespace avg {
TouchEvent::TouchEvent(int id, Type EventType, BlobPtr pBlob, const IntPoint& Pos,
Source source, const DPoint& speed, const IntPoint& lastDownPos)
: CursorEvent(id, EventType, Pos, source),
m_pBlob(pBlob),
m_Speed(speed)
{
setLastDownPos(lastDownPos);
}
TouchEvent::~TouchEvent()
{
}
CursorEventPtr TouchEvent::cloneAs(Type EventType) const
{
TouchEventPtr pClone(new TouchEvent(*this));
pClone->m_Type = EventType;
return pClone;
}
const DPoint& TouchEvent::getSpeed() const
{
return m_Speed;
}
const BlobPtr TouchEvent::getBlob() const
{
return m_pBlob;
}
const DPoint & TouchEvent::getMajorAxis() const
{
const DPoint & Axis0 = m_pBlob->getScaledBasis(0);
const DPoint & Axis1 = m_pBlob->getScaledBasis(1);
if (calcDist(Axis0, DPoint(0,0)) > calcDist(Axis1, DPoint(0,0))) {
return Axis0;
} else {
return Axis1;
}
}
const DPoint & TouchEvent::getMinorAxis() const
{
const DPoint & Axis0 = m_pBlob->getScaledBasis(0);
const DPoint & Axis1 = m_pBlob->getScaledBasis(1);
if (calcDist(Axis0, DPoint(0,0)) > calcDist(Axis1, DPoint(0,0))) {
return Axis1;
} else {
return Axis0;
}
}
ContourSeq TouchEvent::getContour()
{
return m_pBlob->getContour();
}
void TouchEvent::addRelatedEvent(TouchEventPtr pEvent)
{
m_RelatedEvents.push_back(pEvent);
}
vector<TouchEventPtr> TouchEvent::getRelatedEvents() const
{
vector<TouchEventPtr> pRelatedEvents;
vector<TouchEventWeakPtr>::const_iterator it;
for (it=m_RelatedEvents.begin(); it != m_RelatedEvents.end(); ++it) {
pRelatedEvents.push_back((*it).lock());
}
return pRelatedEvents;
}
void TouchEvent::trace()
{
Event::trace();
AVG_TRACE(Logger::EVENTS2, "pos: " << m_Position
<< ", ID: " << getCursorID()
<< ", Area: " << m_pBlob->getArea()
<< ", Eccentricity: " << m_pBlob->getEccentricity());
}
}
<|endoftext|>
|
<commit_before>/**
* LED Strip host.
*
* Turns LEDs red (for now)
*/
#include "Arduino.h"
#include <FastLED.h>
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
#define NUM_LEDS 300
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
int count = 0;
void setup()
{
// Init fastled
pinMode(LED_BUILTIN, OUTPUT);
FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
for (int i=0;i<NUM_LEDS;i++)
leds[i] = CRGB::White;
FastLED.show();
}
void loop()
{
// turn the LED on (HIGH is the voltage level)
digitalWrite(LED_BUILTIN, HIGH);
int i = 0;
for (;i<count;i++)
leds[i] = CRGB::Blue;
for (;i<NUM_LEDS;i++)
leds[i] = CRGB::Green;
count = (count+1) % NUM_LEDS;
FastLED.show();
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
<commit_msg>Use hue<commit_after>/**
* LED Strip host.
*
* Turns LEDs red (for now)
*/
#include "Arduino.h"
#include <FastLED.h>
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
#define NUM_LEDS 300
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
void setup()
{
// Init fastled
pinMode(LED_BUILTIN, OUTPUT);
FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
for (int i=0;i<NUM_LEDS;i++)
leds[i] = CRGB::White;
FastLED.show();
}
void loop()
{
// create rainbow hue
static uint8_t hue = 0;
FastLED.showColor(CHSV(hue++, 255, 255));
delay(30);
}
<|endoftext|>
|
<commit_before>// The main application file
#include "BaseTypes.hpp"
#include "DVMBase.hpp"
#include "XmlHandler.hpp"
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <time.h>
#include <boost/program_options.hpp>
int main(int argc, char *argv[])
{
try {
// Deal with command line options
namespace po = boost::program_options;
po::options_description desc("DVM++ commandline options");
desc.add_options()("help,h", "prints this help message")(
"input-file,f", po::value<std::string>(), "input xml file")(
"example-xml", "prints an example xml to stdout or file");
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
vm);
po::notify(vm);
if (vm.empty()) {
std::cout << desc << "\n";
return 1;
}
if (vm.count("example-xml")) {
XmlHandler xml;
// The input file option will capture the positional argument for
// the name of the example xml so we can just use it!
std::string file = "-";
if (vm.count("input-file")) {
file = vm["input-file"].as<std::string>();
}
xml.writeExample(file);
return 1;
}
XmlHandler xml(vm["input-file"].as<std::string>());
std::string experiment_name, domain_type;
// FileNames file_names;
std::cout
<< "=============================================================="
<< std::endl;
std::cout << "Running the ICL DVM Test code Cpp version." << std::endl;
std::cout
<< "=============================================================="
<< std::endl;
std::cout << "Successfully loaded XML input file" << std::endl;
// Deal with time - this is horrible!
time_t rawtime;
struct tm *ptm;
time(&rawtime);
ptm = gmtime(&rawtime);
std::ostringstream os;
os << ptm->tm_year + 1900 << "_";
if (ptm->tm_mon + 1 < 10) {
os << "0";
}
os << ptm->tm_mon + 1 << "_";
if (ptm->tm_mday < 10) {
os << "0";
}
os << ptm->tm_mday << "_";
if (ptm->tm_hour + 1 < 10) {
os << "0";
}
os << ptm->tm_hour + 1 << "_";
if (ptm->tm_min < 10) {
os << "0";
}
os << ptm->tm_min << "_";
if (ptm->tm_sec < 10) {
os << "0";
}
os << ptm->tm_sec;
std::string stamp = os.str();
std::cout << "File timestamp is " << os.str() << std::endl;
DVMBase dvm(xml);
dvm.init(xml, stamp);
dvm.init_outputs();
clock_t start;
double cpu_time;
start = clock();
/// Solve the problem
dvm.solve();
// output the cpu time on screen
cpu_time = (clock() - start) / (double)CLOCKS_PER_SEC;
std::cout << "Used CPU time is : " << cpu_time << std::endl;
auto outdir = xml.getStringAttribute("io", "output_dir");
outdir = (outdir.back() == '/') ? outdir : outdir + '/';
xml.save(outdir + stamp + "_xml_in.xml");
} catch (char *str) {
std::cout << "Exception thrown: " << str << std::endl;
} catch (std::string str) {
std::cout << "Exception thrown: " << str << std::endl;
} catch (...) {
std::cout << "Unhandled exception type" << std::endl;
}
std::cout << "Completed DVM computations succesfully" << std::endl;
return 0;
}
<commit_msg>Print the real elapsed time rather than cpu time<commit_after>// The main application file
#include "BaseTypes.hpp"
#include "DVMBase.hpp"
#include "XmlHandler.hpp"
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <time.h>
#include <chrono>
#include <boost/program_options.hpp>
int main(int argc, char *argv[])
{
try {
// Deal with command line options
namespace po = boost::program_options;
po::options_description desc("DVM++ commandline options");
desc.add_options()("help,h", "prints this help message")(
"input-file,f", po::value<std::string>(), "input xml file")(
"example-xml", "prints an example xml to stdout or file");
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
vm);
po::notify(vm);
if (vm.empty()) {
std::cout << desc << "\n";
return 1;
}
if (vm.count("example-xml")) {
XmlHandler xml;
// The input file option will capture the positional argument for
// the name of the example xml so we can just use it!
std::string file = "-";
if (vm.count("input-file")) {
file = vm["input-file"].as<std::string>();
}
xml.writeExample(file);
return 1;
}
XmlHandler xml(vm["input-file"].as<std::string>());
std::string experiment_name, domain_type;
// FileNames file_names;
std::cout
<< "=============================================================="
<< std::endl;
std::cout << "Running the ICL DVM Test code Cpp version." << std::endl;
std::cout
<< "=============================================================="
<< std::endl;
std::cout << "Successfully loaded XML input file" << std::endl;
// Deal with time - this is horrible!
time_t rawtime;
struct tm *ptm;
time(&rawtime);
ptm = gmtime(&rawtime);
std::ostringstream os;
os << ptm->tm_year + 1900 << "_";
if (ptm->tm_mon + 1 < 10) {
os << "0";
}
os << ptm->tm_mon + 1 << "_";
if (ptm->tm_mday < 10) {
os << "0";
}
os << ptm->tm_mday << "_";
if (ptm->tm_hour + 1 < 10) {
os << "0";
}
os << ptm->tm_hour + 1 << "_";
if (ptm->tm_min < 10) {
os << "0";
}
os << ptm->tm_min << "_";
if (ptm->tm_sec < 10) {
os << "0";
}
os << ptm->tm_sec;
std::string stamp = os.str();
std::cout << "File timestamp is " << os.str() << std::endl;
DVMBase dvm(xml);
dvm.init(xml, stamp);
dvm.init_outputs();
auto start = std::chrono::system_clock::now();
/// Solve the problem
dvm.solve();
// output the cpu time on screen
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start;
std::cout << "\nRuntime : " << elapsed.count() << "s\n";
auto outdir = xml.getStringAttribute("io", "output_dir");
outdir = (outdir.back() == '/') ? outdir : outdir + '/';
xml.save(outdir + stamp + "_xml_in.xml");
} catch (char *str) {
std::cout << "Exception thrown: " << str << std::endl;
} catch (std::string str) {
std::cout << "Exception thrown: " << str << std::endl;
} catch (...) {
std::cout << "Unhandled exception type" << std::endl;
}
std::cout << "Completed DVM computations succesfully" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int argc, char **argv)
{
bool finish = false;
int semicolon= 0;
int ampersand = 0;
int pipe = 0;
string command = "";
vector <string> commands;
//login name and host info prompt
string login = getlogin();
cout << login << "@";
char hostarray[64];
gethostname(hostarray, 64);
cout << hostarray;
//ready prompt
cout << "$ ";
//take in command from user
getline(cin, command);
// cout << command << endl;
//tokenizer init
char_separator<char> delim(" ;&|#",";&|#", keep_empty_tokens);
tokenizer< char_separator<char> > mytok(command, delim);
//token check
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
cout << "(" << *it << ")" << " ";
}
cout << "listed the arguements" << endl;
//command list formatting
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
//cout << *it << endl;
if(*it == "#")
{
break;
}
else if(*it == ""); //do nothing
else if(*it == ";")
{
semicolon++;
if(semicolon > 1)
{
cout << "syntax error 1";
return -1;
}
else if(semicolon == 1)
{
if(ampersand == 0 && pipe == 0)
{
commands.push_back(";");
semicolon = 0;
}
else
{
cout << "syntax error 5";
return -1;
}
}
}
else if(*it == "&")
{
ampersand++;
if(ampersand > 2)
{
cout << "syntax error 2";
return -1;
}
else if(ampersand == 2)
{
if(semicolon == 0 && pipe == 0)
{
commands.push_back("&&");
ampersand = 0;
}
else
{
cout << "syntax error 6";
return -1;
}
}
}
else if(*it == "|")
{
pipe++;
if(pipe > 2)
{
cout << "syntax error 3";
return -1;
}
else if(pipe == 2)
{
if(semicolon == 0 && ampersand == 0)
{
commands.push_back("||");
pipe = 0;
}
else
{
cout << "syntax error 7";
return -1;
}
}
}
else
{
if(semicolon != 0 || ampersand != 0 || pipe != 0)
{
cout << "syntax error 4";
cout << semicolon << " " << ampersand << " " << pipe << endl;
return -1;
}
else
commands.push_back(*it);
}
}
//check commands
for(int i = 0; i < commands.size(); i++)
{
cout << "(" << commands.at(i) << ") ";
}
cout << "combined arguements into groups" << endl;
//add commands to command line arguements
//exec commands
// for(int i = 0; i < commands.size(); i++)
// {
// if(commands.at(i) == "exit ");
// {
// finish = true;
// cout << "ending session...";
// break;
// }
// command = commands.at(i);
// execvp(command, argv);
// }
//shell termination
if(finish)
{
cout << "good-bye!" << endl;
//break;
}
return 0;
}
<commit_msg>fixed pass in list of exec args<commit_after>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int argc, char **argv)
{
bool finish = false;
//rshell loop
while(!finish)
{
int semicolon= 0;
int ampersand = 0;
int pipe = 0;
string command = "";
vector <string> commands;
vector <char *> args;
vector <vector <char *> > execArgs;
vector <char *> com;
//login name and host info prompt
string login = getlogin();
cout << login << "@";
char hostarray[64];
gethostname(hostarray, 64);
cout << hostarray;
//ready prompt
cout << "$ ";
//take in command from user
getline(cin, command);
// cout << command << endl;
//tokenizer init
char_separator<char> delim(" ;&|#",";&|#", keep_empty_tokens);
tokenizer< char_separator<char> > mytok(command, delim);
//token check
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
cout << "(" << *it << ")" << " ";
}
cout << "listed the arguements" << endl;
//command list formatting
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
//cout << *it << endl;
if(*it == "#")
{
break;
}
else if(*it == ""); //do nothing
else if(*it == ";")
{
semicolon++;
if(semicolon > 1)
{
cout << "syntax error 1";
return -1;
}
else if(semicolon == 1)
{
if(ampersand == 0 && pipe == 0)
{
commands.push_back(";");
semicolon = 0;
}
else
{
cout << "syntax error 5";
return -1;
}
}
}
else if(*it == "&")
{
ampersand++;
if(ampersand > 2)
{
cout << "syntax error 2";
return -1;
}
else if(ampersand == 2)
{
if(semicolon == 0 && pipe == 0)
{
commands.push_back("&&");
ampersand = 0;
}
else
{
cout << "syntax error 6";
return -1;
}
}
}
else if(*it == "|")
{
pipe++;
if(pipe > 2)
{
cout << "syntax error 3";
return -1;
}
else if(pipe == 2)
{
if(semicolon == 0 && ampersand == 0)
{
commands.push_back("||");
pipe = 0;
}
else
{
cout << "syntax error 7";
return -1;
}
}
}
else
{
if(semicolon != 0 || ampersand != 0 || pipe != 0)
{
cout << "syntax error 4";
cout << semicolon << " " << ampersand << " " << pipe << endl;
return -1;
}
else
commands.push_back(*it);
}
}
//check commands
for(int i = 0; i < commands.size(); i++)
{
cout << "(" << commands.at(i) << ") ";
}
cout << "combined arguements into groups" << endl;
//add commands to command line arguements
for(int i = 0; i < commands.size(); i++)
{
args.push_back(const_cast<char*>(commands.at(i).c_str()));
execArgs.push_back(args);
args.clear();
}
for(int i = 0; i < execArgs.size(); i++)
{
com = execArgs.at(i);
}
//exec commands
for(int i = 0; i < com.size(); i++)
{
if(strncmp(com[i], "exit", 4) == 0)
{
finish = true;
cout << "ending session...";
break;
}
// command = commands.at(i);
// execvp(command, argv);
}
//shell termination
if(finish)
{
cout << "good-bye!" << endl;
break;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/create.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
#include <boost/exception/get_error_info.hpp>
using namespace flusspferd;
namespace {
typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;
struct exception
: flusspferd::exception
{
exception(std::string const &what)
: std::runtime_error(what), flusspferd::exception(what)
{ }
char const *what() throw() {
if(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {
std::string what_ = flusspferd::exception::what();
what_ += ": ";
what_ += curl_easy_strerror(*code);
return what_.c_str();
}
else {
return flusspferd::exception::what();
}
}
};
void global_init(long flags) {
CURLcode ret = curl_global_init(flags);
if(ret != 0) {
throw flusspferd::exception(std::string("curl_global_init: ") +
curl_easy_strerror(ret));
}
}
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
)
{
CURL *handle;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
byte_array data(object(),
reinterpret_cast<byte_array::element_type*>(ptr),
size*nmemb);
arguments arg;
arg.push_back(value(data));
arg.push_back(value(size));
value v = self.writecallback.call(arg);
return v.to_number();
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init())
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd)
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
void perform() {
CURLcode res = curl_easy_perform(get());
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *const uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *const esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(What) \
case What : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
do_setopt(What, x.arg[1].to_number()); \
break
#define OPT_FUNCTION(What, Data, Callback, Func) \
case What : { \
if(x.arg.size() != 2) { \
throw flusspferd::exception("curl_easy_setopt: Expected two arguments"); \
} \
if(!x.arg[1].is_object()) { \
throw flusspferd::exception("curl_easy_setopt: Expected a function as second parameter"); \
} \
object callback = x.arg[1].get_object(); \
if(callback == default_function) { \
do_setopt(What, 0x0); \
Callback = object(); \
} \
else { \
do_setopt(Data, this); \
do_setopt(What, Func); \
Callback = callback; \
} \
} \
break
#define OPT_DATAFUNCTION(What, Prefix) \
OPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )
private:
template<typename T>
void do_setopt(CURLoption what, T data) {
CURLcode res = curl_easy_setopt(get(), what, data);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
public:
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
// Behaviour Options
OPT_NUMBER(CURLOPT_VERBOSE);
OPT_NUMBER(CURLOPT_HEADER);
OPT_NUMBER(CURLOPT_NOPROGRESS);
OPT_NUMBER(CURLOPT_NOSIGNAL);
// Callback Options
OPT_DATAFUNCTION(CURLOPT_WRITE, write);
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_DATAFUNCTION
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
static object default_function;
};
object Easy::default_function;
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<Easy>(cURL);
// Behaviour Options
cURL.define_property("OPT_VERBOSE", value((int)CURLOPT_VERBOSE),
read_only_property | permanent_property);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_NOPROGRESS", value((int)CURLOPT_NOPROGRESS),
read_only_property | permanent_property);
cURL.define_property("OPT_NOSIGNAL", value((int)CURLOPT_NOSIGNAL),
read_only_property | permanent_property);
// Callback Options
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
/*
CURLOPT_READFUNCTION
CURLOPT_IOCTLFUNCTION
CURLOPT_SEEKFUNCTION
CURLOPT_SOCKOPTFUNCTION
CURLOPT_OPENSOCKETFUNCTION
...
*/
cURL.define_property("defaultFunction", value(Easy::default_function),
read_only_property | permanent_property);
}
}
<commit_msg>curl: fixed `what'<commit_after>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/create.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
#include <boost/exception/get_error_info.hpp>
using namespace flusspferd;
namespace {
typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;
struct exception
: flusspferd::exception
{
exception(std::string const &what)
: std::runtime_error(what), flusspferd::exception(what)
{ }
char const *what() const throw() {
if(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {
std::string what_ = flusspferd::exception::what();
what_ += ": ";
what_ += curl_easy_strerror(*code);
return what_.c_str();
}
else {
return flusspferd::exception::what();
}
}
};
void global_init(long flags) {
CURLcode ret = curl_global_init(flags);
if(ret != 0) {
throw flusspferd::exception(std::string("curl_global_init: ") +
curl_easy_strerror(ret));
}
}
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
)
{
CURL *handle;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
byte_array data(object(),
reinterpret_cast<byte_array::element_type*>(ptr),
size*nmemb);
arguments arg;
arg.push_back(value(data));
arg.push_back(value(size));
value v = self.writecallback.call(arg);
return v.to_number();
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init())
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd)
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
void perform() {
CURLcode res = curl_easy_perform(get());
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *const uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *const esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(What) \
case What : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
do_setopt(What, x.arg[1].to_number()); \
break
#define OPT_FUNCTION(What, Data, Callback, Func) \
case What : { \
if(x.arg.size() != 2) { \
throw flusspferd::exception("curl_easy_setopt: Expected two arguments"); \
} \
if(!x.arg[1].is_object()) { \
throw flusspferd::exception("curl_easy_setopt: Expected a function as second parameter"); \
} \
object callback = x.arg[1].get_object(); \
if(callback == default_function) { \
do_setopt(What, 0x0); \
Callback = object(); \
} \
else { \
do_setopt(Data, this); \
do_setopt(What, Func); \
Callback = callback; \
} \
} \
break
#define OPT_DATAFUNCTION(What, Prefix) \
OPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )
private:
template<typename T>
void do_setopt(CURLoption what, T data) {
CURLcode res = curl_easy_setopt(get(), what, data);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
public:
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
// Behaviour Options
OPT_NUMBER(CURLOPT_VERBOSE);
OPT_NUMBER(CURLOPT_HEADER);
OPT_NUMBER(CURLOPT_NOPROGRESS);
OPT_NUMBER(CURLOPT_NOSIGNAL);
// Callback Options
OPT_DATAFUNCTION(CURLOPT_WRITE, write);
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_DATAFUNCTION
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
static object default_function;
};
object Easy::default_function;
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<Easy>(cURL);
// Behaviour Options
cURL.define_property("OPT_VERBOSE", value((int)CURLOPT_VERBOSE),
read_only_property | permanent_property);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_NOPROGRESS", value((int)CURLOPT_NOPROGRESS),
read_only_property | permanent_property);
cURL.define_property("OPT_NOSIGNAL", value((int)CURLOPT_NOSIGNAL),
read_only_property | permanent_property);
// Callback Options
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
/*
CURLOPT_READFUNCTION
CURLOPT_IOCTLFUNCTION
CURLOPT_SEEKFUNCTION
CURLOPT_SOCKOPTFUNCTION
CURLOPT_OPENSOCKETFUNCTION
...
*/
cURL.define_property("defaultFunction", value(Easy::default_function),
read_only_property | permanent_property);
}
}
<|endoftext|>
|
<commit_before>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/create.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
#include <boost/exception/get_error_info.hpp>
using namespace flusspferd;
namespace {
typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;
struct exception
: flusspferd::exception
{
exception(std::string const &what)
: std::runtime_error(what), flusspferd::exception(what)
{ }
char const *what() const throw() {
if(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {
std::string what_ = flusspferd::exception::what();
what_ += ": ";
what_ += curl_easy_strerror(*code);
return what_.c_str();
}
else {
return flusspferd::exception::what();
}
}
};
void global_init(long flags) {
CURLcode ret = curl_global_init(flags);
if(ret != 0) {
throw flusspferd::exception(std::string("curl_global_init: ") + curl_easy_strerror(ret));
}
}
class Easy;
FLUSSPFERD_CLASS_DESCRIPTION
(
EasyOpt,
(constructor_name, "EasyOpt")
(full_name, "cURL.Easy.EasyOpt")
(constructible, false)
)
{
Easy &parent;
public:
EasyOpt(flusspferd::object const &self, Easy &parent) : base_type(self), parent(parent) { }
static EasyOpt &create(Easy &p) {
return flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p));
}
protected:
bool property_resolve(value const &id, unsigned access);
};
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
(properties,
("options", getter, get_opt))
)
{
CURL *handle;
EasyOpt &opt;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
byte_array data(object(),
reinterpret_cast<byte_array::element_type*>(ptr),
size*nmemb);
arguments arg;
arg.push_back(value(data));
arg.push_back(value(size));
value v = self.writecallback.call(arg);
return v.to_number();
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
EasyOpt &get_opt() { return opt; }
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd), opt(EasyOpt::create(*this))
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
void perform() {
CURLcode res = curl_easy_perform(get());
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *const uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *const esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(What) \
case What : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
do_setopt(What, x.arg[1].to_number()); \
break
#define OPT_FUNCTION(What, Data, Callback, Func) \
case What : { \
if(x.arg.size() != 2) { \
throw flusspferd::exception("curl_easy_setopt: Expected two arguments"); \
} \
if(!x.arg[1].is_object()) { \
throw flusspferd::exception("curl_easy_setopt: Expected a function as second parameter"); \
} \
object callback = x.arg[1].get_object(); \
if(callback == default_function) { \
do_setopt(What, 0x0); \
Callback = object(); \
} \
else { \
do_setopt(Data, this); \
do_setopt(What, Func); \
Callback = callback; \
} \
} \
break
#define OPT_DATAFUNCTION(What, Prefix) \
OPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )
private:
template<typename T>
void do_setopt(CURLoption what, T data) {
CURLcode res = curl_easy_setopt(get(), what, data);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
public:
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
// Behaviour Options
OPT_NUMBER(CURLOPT_VERBOSE);
OPT_NUMBER(CURLOPT_HEADER);
OPT_NUMBER(CURLOPT_NOPROGRESS);
OPT_NUMBER(CURLOPT_NOSIGNAL);
// Callback Options
OPT_DATAFUNCTION(CURLOPT_WRITE, write);
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_DATAFUNCTION
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
static object default_function;
};
object Easy::default_function;
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
bool EasyOpt::property_resolve(value const &id, unsigned) {
(void)id;
return false;
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<EasyOpt>(cURL);
load_class<Easy>(cURL);
// Behaviour Options
cURL.define_property("OPT_VERBOSE", value((int)CURLOPT_VERBOSE),
read_only_property | permanent_property);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_NOPROGRESS", value((int)CURLOPT_NOPROGRESS),
read_only_property | permanent_property);
cURL.define_property("OPT_NOSIGNAL", value((int)CURLOPT_NOSIGNAL),
read_only_property | permanent_property);
// Callback Options
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
/*
CURLOPT_READFUNCTION
CURLOPT_IOCTLFUNCTION
CURLOPT_SEEKFUNCTION
CURLOPT_SOCKOPTFUNCTION
CURLOPT_OPENSOCKETFUNCTION
...
*/
cURL.define_property("defaultFunction", value(Easy::default_function),
read_only_property | permanent_property);
}
}
<commit_msg>curl: added opt to trace (fix segfault issue)<commit_after>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/create.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
#include <boost/exception/get_error_info.hpp>
using namespace flusspferd;
namespace {
typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;
struct exception
: flusspferd::exception
{
exception(std::string const &what)
: std::runtime_error(what), flusspferd::exception(what)
{ }
char const *what() const throw() {
if(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {
std::string what_ = flusspferd::exception::what();
what_ += ": ";
what_ += curl_easy_strerror(*code);
return what_.c_str();
}
else {
return flusspferd::exception::what();
}
}
};
void global_init(long flags) {
CURLcode ret = curl_global_init(flags);
if(ret != 0) {
throw flusspferd::exception(std::string("curl_global_init: ") + curl_easy_strerror(ret));
}
}
class Easy;
FLUSSPFERD_CLASS_DESCRIPTION
(
EasyOpt,
(constructor_name, "EasyOpt")
(full_name, "cURL.Easy.EasyOpt")
(constructible, false)
)
{
Easy &parent;
public:
EasyOpt(flusspferd::object const &self, Easy &parent)
: base_type(self), parent(parent)
{ }
static EasyOpt &create(Easy &p) {
return flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p));
}
protected:
bool property_resolve(value const &id, unsigned access);
};
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
(properties,
("options", getter, get_opt))
)
{
CURL *handle;
EasyOpt &opt;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
byte_array data(object(),
reinterpret_cast<byte_array::element_type*>(ptr),
size*nmemb);
arguments arg;
arg.push_back(value(data));
arg.push_back(value(size));
value v = self.writecallback.call(arg);
return v.to_number();
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
trc("options", opt);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
EasyOpt &get_opt() {
return opt;
}
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd), opt(EasyOpt::create(*this))
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
void perform() {
CURLcode res = curl_easy_perform(get());
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *const uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *const esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(What) \
case What : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
do_setopt(What, x.arg[1].to_number()); \
break
#define OPT_FUNCTION(What, Data, Callback, Func) \
case What : { \
if(x.arg.size() != 2) { \
throw flusspferd::exception("curl_easy_setopt: Expected two arguments"); \
} \
if(!x.arg[1].is_object()) { \
throw flusspferd::exception("curl_easy_setopt: Expected a function as second parameter"); \
} \
object callback = x.arg[1].get_object(); \
if(callback == default_function) { \
do_setopt(What, 0x0); \
Callback = object(); \
} \
else { \
do_setopt(Data, this); \
do_setopt(What, Func); \
Callback = callback; \
} \
} \
break
#define OPT_DATAFUNCTION(What, Prefix) \
OPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )
private:
template<typename T>
void do_setopt(CURLoption what, T data) {
CURLcode res = curl_easy_setopt(get(), what, data);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror(res));
}
}
public:
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
// Behaviour Options
OPT_NUMBER(CURLOPT_VERBOSE);
OPT_NUMBER(CURLOPT_HEADER);
OPT_NUMBER(CURLOPT_NOPROGRESS);
OPT_NUMBER(CURLOPT_NOSIGNAL);
// Callback Options
OPT_DATAFUNCTION(CURLOPT_WRITE, write);
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_DATAFUNCTION
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
static object default_function;
};
object Easy::default_function;
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
bool EasyOpt::property_resolve(value const &id, unsigned) {
return false;
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<EasyOpt>(cURL);
load_class<Easy>(cURL);
// Behaviour Options
cURL.define_property("OPT_VERBOSE", value((int)CURLOPT_VERBOSE),
read_only_property | permanent_property);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_NOPROGRESS", value((int)CURLOPT_NOPROGRESS),
read_only_property | permanent_property);
cURL.define_property("OPT_NOSIGNAL", value((int)CURLOPT_NOSIGNAL),
read_only_property | permanent_property);
// Callback Options
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
/*
CURLOPT_READFUNCTION
CURLOPT_IOCTLFUNCTION
CURLOPT_SEEKFUNCTION
CURLOPT_SOCKOPTFUNCTION
CURLOPT_OPENSOCKETFUNCTION
...
*/
cURL.define_property("defaultFunction", value(Easy::default_function),
read_only_property | permanent_property);
}
}
<|endoftext|>
|
<commit_before>#ifndef MY_MODEL_HH
#define MY_MODEL_HH
#include <QAbstractListModel>
#include <QAbstractTableModel>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QList>
#include <QModelIndex>
#include <QPixmap>
#include <QVariant>
class MyData: public QObject
{
Q_OBJECT
public:
MyData();
MyData(const QFileInfo & fileInfo);
MyData(const QFileInfo & fileInfo, const QPixmap & thumbnail, int checkState = Qt::Checked);
MyData(const MyData &) = default;
void loadThumbnailAsync(const QFileInfo & fileInfo);
QFileInfo m_fileInfo;
QPixmap m_thumbnail;
int m_checkState;
signals:
void thumbnailLoaded(const QFileInfo & fileInfo);
};
//bool operator==(const MyData & lhs, const MyData & rhs );
class MyModel: public QAbstractListModel
{
Q_OBJECT
public:
MyModel(QObject * parent = NULL);
~MyModel();
int rowCount(const QModelIndex & parent = QModelIndex()) const override;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex & index) const override;
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override;
QStringList mimeTypes() const override;
QMimeData * mimeData(const QModelIndexList & indexes) const override;
bool dropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent) override;
Qt::DropActions supportedDropActions() const override;
bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex()) override;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()) override;
bool moveRows(const QModelIndex & sourceParent, int sourceRow, int count, const QModelIndex & destinationParent, int destinationChild) override;
bool canDropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent) const override;
void rotateLeft(const QModelIndex & index);
bool addRow(MyData * data);
bool removeSelected();
//QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
//QHash<int, QByteArray> QAbstractItemModel::roleNames() const;
public slots:
void selectAll(int state);
void rotateChecked();
//private slots:
// void loadThumbnailAsync(const QFileInfo & file_path);
private slots:
void UpdateThumbnail(const QFileInfo & fileInfo);
void retrieveFiles(const QString & path = QString());
private:
QModelIndex findByFilePath(const QFileInfo & file_path);
// QList elements should be copyable QObject and subclasses arn't
QList<MyData *> m_files;
QFileSystemWatcher m_watcher;
// QList<QFileInfo> filesInfo_;
// QList<QPixmap> thumbnails_;
// QList<int> checkState_;
};
#endif
<commit_msg>first commit on develop<commit_after>#ifndef MY_MODEL_HH
#define MY_MODEL_HH
#include <QAbstractListModel>
#include <QAbstractTableModel>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QList>
#include <QModelIndex>
#include <QPixmap>
#include <QVariant>
class MyData: public QObject
{
Q_OBJECT
public:
MyData();
MyData(const QFileInfo & fileInfo);
MyData(const QFileInfo & fileInfo, const QPixmap & thumbnail, int checkState = Qt::Checked);
MyData(const MyData &) = default;
void loadThumbnailAsync(const QFileInfo & fileInfo);
QFileInfo m_fileInfo;
QPixmap m_thumbnail;
int m_checkState;
signals:
void thumbnailLoaded(const QFileInfo & fileInfo);
};
//bool operator==(const MyData & lhs, const MyData & rhs );
class MyModel: public QAbstractListModel
{
Q_OBJECT
public:
MyModel(QObject * parent = NULL);
~MyModel();
int rowCount(const QModelIndex & parent = QModelIndex()) const override;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex & index) const override;
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override;
QStringList mimeTypes() const override;
QMimeData * mimeData(const QModelIndexList & indexes) const override;
bool dropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent) override;
Qt::DropActions supportedDropActions() const override;
bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex()) override;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()) override;
bool moveRows(const QModelIndex & sourceParent, int sourceRow, int count, const QModelIndex & destinationParent, int destinationChild) override;
bool canDropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent) const override;
void rotateLeft(const QModelIndex & index);
bool addRow(MyData * data);
bool removeSelected();
//QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
//QHash<int, QByteArray> QAbstractItemModel::roleNames() const;
public slots:
void selectAll(int state);
void rotateChecked();
private slots:
void UpdateThumbnail(const QFileInfo & fileInfo);
void retrieveFiles(const QString & path = QString());
private:
QModelIndex findByFilePath(const QFileInfo & file_path);
// QList elements should be copyable QObject and subclasses arn't
QList<MyData *> m_files;
QFileSystemWatcher m_watcher;
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>Make PyUNO objects hashable<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "poTextBox.h"
namespace po { namespace scene {
TextBoxRef TextBox::create()
{
return TextBoxRef(new TextBox(ci::TextBox()));
}
TextBoxRef TextBox::create(ci::TextBox ciTextBox)
{
return TextBoxRef(new TextBox(ciTextBox));
}
TextBoxRef TextBox::create(ci::TextBox ciTextBox, ci::gl::Texture::Format format)
{
TextBoxRef ref(new TextBox(ciTextBox));
ref->setFormat(format);
return ref;
}
TextBox::TextBox(ci::TextBox ciTextBox)
: mCiTextBox(ciTextBox)
, mUseTextBounds(false)
, mHasFormat(false)
{
render();
}
void TextBox::draw()
{
if (mTexture) {
ci::gl::enableAlphaBlending();
ci::gl::color(ci::ColorA(getFillColor(), getAppliedAlpha()));
ci::gl::draw(mTexture);
}
}
void TextBox::setCiTextBox(ci::TextBox &ciTextBox)
{
mCiTextBox = ciTextBox;
render();
mUseTextBounds = mCiTextBox.getSize().y == ci::TextBox::GROW ? true : false;
}
void TextBox::render()
{
mCiTextBox.setPremultiplied(true);
if (mHasFormat) {
mTexture = ci::gl::Texture::create(mCiTextBox.render(), mFormat);
}
else {
mTexture = ci::gl::Texture::create(mCiTextBox.render());
}
}
ci::Rectf TextBox::getBounds()
{
if(mTexture)
{
return mTexture->getBounds();
} else {
return ci::Rectf();
}
}
void TextBox::setFormat(ci::gl::Texture::Format format)
{
mFormat = format;
mHasFormat = true;
render();
}
} } // namespace po::scene<commit_msg>poTextBox: premultiplied should be set before passing ciTextBox to poTextBox<commit_after>/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "poTextBox.h"
namespace po { namespace scene {
TextBoxRef TextBox::create()
{
return TextBoxRef(new TextBox(ci::TextBox()));
}
TextBoxRef TextBox::create(ci::TextBox ciTextBox)
{
return TextBoxRef(new TextBox(ciTextBox));
}
TextBoxRef TextBox::create(ci::TextBox ciTextBox, ci::gl::Texture::Format format)
{
TextBoxRef ref(new TextBox(ciTextBox));
ref->setFormat(format);
return ref;
}
TextBox::TextBox(ci::TextBox ciTextBox)
: mCiTextBox(ciTextBox)
, mUseTextBounds(false)
, mHasFormat(false)
{
render();
}
void TextBox::draw()
{
if (mTexture) {
ci::gl::enableAlphaBlending();
ci::gl::color(ci::ColorA(getFillColor(), getAppliedAlpha()));
ci::gl::draw(mTexture);
}
}
void TextBox::setCiTextBox(ci::TextBox &ciTextBox)
{
mCiTextBox = ciTextBox;
render();
mUseTextBounds = mCiTextBox.getSize().y == ci::TextBox::GROW ? true : false;
}
void TextBox::render()
{
if (mHasFormat) {
mTexture = ci::gl::Texture::create(mCiTextBox.render(), mFormat);
}
else {
mTexture = ci::gl::Texture::create(mCiTextBox.render());
}
}
ci::Rectf TextBox::getBounds()
{
if(mTexture)
{
return mTexture->getBounds();
} else {
return ci::Rectf();
}
}
void TextBox::setFormat(ci::gl::Texture::Format format)
{
mFormat = format;
mHasFormat = true;
render();
}
} } // namespace po::scene<|endoftext|>
|
<commit_before>#include <unistd.h>
#include "rpc/server.h"
#include "rpc/client.h"
#include "benchmark_service.h"
using namespace base;
using namespace rpc;
using namespace benchmark;
TEST(issue, 7) {
const int rpc_id = 1987;
PollMgr* poll = new PollMgr(1);
ThreadPool* thrpool = new ThreadPool(4);
Server *svr = new Server(poll, thrpool);
// directly release poll to make sure it has ref_count of 1
// other other hand, thrpool is kept till end of program, with ref_count of 2
poll->release();
svr->reg(rpc_id, [] (Request* req, ServerConnection* sconn) {
sconn->run_async([req, sconn] {
Log::debug("rpc called");
::usleep(500 * 1000);
Log::debug("rpc replying");
sconn->begin_reply(req);
// reply nothing
sconn->end_reply();
delete req;
sconn->release();
Log::debug("rpc replied");
});
});
svr->start("127.0.0.1:7891");
PollMgr* poll_clnt = new PollMgr(1);
Client* clnt = new Client(poll_clnt);
clnt->connect("127.0.0.1:7891");
Client* clnt2 = new Client(poll_clnt);
clnt2->connect("127.0.0.1:7891");
Client* clnt3 = new Client(poll_clnt);
clnt3->connect("127.0.0.1:7891");
Client* clnt4 = new Client(poll_clnt);
clnt4->connect("127.0.0.1:7891");
Future* fu = clnt->begin_request(rpc_id);
clnt->end_request();
fu->timed_wait(0.1);
fu = clnt2->begin_request(rpc_id);
clnt2->end_request();
fu->timed_wait(0.1);
fu = clnt3->begin_request(rpc_id);
clnt3->end_request();
fu->timed_wait(0.1);
fu = clnt4->begin_request(rpc_id);
clnt4->end_request();
// wait a little bit to make sure RPC got sent instead of cancelled
fu->timed_wait(0.1);
clnt->close_and_release();
clnt2->close_and_release();
clnt3->close_and_release();
clnt4->close_and_release();
poll_clnt->release();
Log::debug("killing server");
delete svr;
Log::debug("killed server");
// thrpool is kept till end of program, with ref_count of 2
thrpool->release();
}
TEST(issue, 8) {
BenchmarkService svc;
Server *svr = new Server;
PollMgr* clnt_poll = new PollMgr(1);
svr->reg(&svc);
svr->start("0.0.0.0:9876");
Client* clnt = new Client(clnt_poll);
clnt->connect("127.0.0.1:9876");
BenchmarkProxy bp(clnt);
Future* fu = bp.async_sleep(2);
fu->timed_wait(0.1);
fu->release();
clnt->close_and_release();
delete svr;
clnt_poll->release();
}
<commit_msg>fix leak<commit_after>#include <unistd.h>
#include "rpc/server.h"
#include "rpc/client.h"
#include "benchmark_service.h"
using namespace base;
using namespace rpc;
using namespace benchmark;
TEST(issue, 7) {
const int rpc_id = 1987;
PollMgr* poll = new PollMgr(1);
ThreadPool* thrpool = new ThreadPool(4);
Server *svr = new Server(poll, thrpool);
// directly release poll to make sure it has ref_count of 1
// other other hand, thrpool is kept till end of program, with ref_count of 2
poll->release();
svr->reg(rpc_id, [] (Request* req, ServerConnection* sconn) {
sconn->run_async([req, sconn] {
Log::debug("rpc called");
::usleep(500 * 1000);
Log::debug("rpc replying");
sconn->begin_reply(req);
// reply nothing
sconn->end_reply();
delete req;
sconn->release();
Log::debug("rpc replied");
});
});
svr->start("127.0.0.1:7891");
PollMgr* poll_clnt = new PollMgr(1);
Client* clnt = new Client(poll_clnt);
clnt->connect("127.0.0.1:7891");
Client* clnt2 = new Client(poll_clnt);
clnt2->connect("127.0.0.1:7891");
Client* clnt3 = new Client(poll_clnt);
clnt3->connect("127.0.0.1:7891");
Client* clnt4 = new Client(poll_clnt);
clnt4->connect("127.0.0.1:7891");
Future* fu = clnt->begin_request(rpc_id);
clnt->end_request();
fu->timed_wait(0.1);
fu->release();
fu = clnt2->begin_request(rpc_id);
clnt2->end_request();
fu->timed_wait(0.1);
fu->release();
fu = clnt3->begin_request(rpc_id);
clnt3->end_request();
fu->timed_wait(0.1);
fu->release();
fu = clnt4->begin_request(rpc_id);
clnt4->end_request();
// wait a little bit to make sure RPC got sent instead of cancelled
fu->timed_wait(0.1);
fu->release();
clnt->close_and_release();
clnt2->close_and_release();
clnt3->close_and_release();
clnt4->close_and_release();
poll_clnt->release();
Log::debug("killing server");
delete svr;
Log::debug("killed server");
// thrpool is kept till end of program, with ref_count of 2
thrpool->release();
}
TEST(issue, 8) {
BenchmarkService svc;
Server *svr = new Server;
PollMgr* clnt_poll = new PollMgr(1);
svr->reg(&svc);
svr->start("0.0.0.0:9876");
Client* clnt = new Client(clnt_poll);
clnt->connect("127.0.0.1:9876");
BenchmarkProxy bp(clnt);
Future* fu = bp.async_sleep(2);
fu->timed_wait(0.1);
fu->release();
clnt->close_and_release();
delete svr;
clnt_poll->release();
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexForth.cxx
** Lexer for FORTH
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
ch == ')' );
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}
static inline bool IsANumChar(int ch) {
return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}
static inline bool IsASpaceChar(int ch) {
return (ch < 0x80) && isspace(ch);
}
static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
Accessor &styler) {
WordList &control = *keywordLists[0];
WordList &keyword = *keywordLists[1];
WordList &defword = *keywordLists[2];
WordList &preword1 = *keywordLists[3];
WordList &preword2 = *keywordLists[4];
WordList &strings = *keywordLists[5];
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Determine if the current state should terminate.
if (sc.state == SCE_FORTH_COMMENT) {
if (sc.atLineEnd) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_COMMENT_ML) {
if (sc.ch == ')') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
// handle numbers here too, because what we thought was a number might
// turn out to be a keyword e.g. 2DUP
if (IsASpaceChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
if (control.InList(s)) {
sc.ChangeState(SCE_FORTH_CONTROL);
} else if (keyword.InList(s)) {
sc.ChangeState(SCE_FORTH_KEYWORD);
} else if (defword.InList(s)) {
sc.ChangeState(SCE_FORTH_DEFWORD);
} else if (preword1.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD1);
} else if (preword2.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD2);
} else if (strings.InList(s)) {
sc.ChangeState(SCE_FORTH_STRING);
newState = SCE_FORTH_STRING;
}
sc.SetState(newState);
}
if (sc.state == SCE_FORTH_NUMBER) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
}else if (sc.state == SCE_FORTH_STRING) {
if (sc.ch == '\"') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_LOCALE) {
if (sc.ch == '}') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_DEFWORD) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_FORTH_DEFAULT) {
if (sc.ch == '\\'){
sc.SetState(SCE_FORTH_COMMENT);
} else if (sc.ch == '(' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext))) {
sc.SetState(SCE_FORTH_COMMENT_ML);
} else if ( (sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
// number starting with $ is a hex number
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
sc.Forward();
} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
// number starting with % is binary
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
sc.Forward();
} else if ( isascii(sc.ch) &&
(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
){
sc.SetState(SCE_FORTH_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_FORTH_IDENTIFIER);
} else if (sc.ch == '{') {
sc.SetState(SCE_FORTH_LOCALE);
} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
// highlight word definitions e.g. : GCD ( n n -- n ) ..... ;
// ^ ^^^
sc.SetState(SCE_FORTH_DEFWORD);
while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
sc.Forward();
} else if (sc.ch == ';' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext)) ) {
// mark the ';' that ends a word
sc.SetState(SCE_FORTH_DEFWORD);
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}
}
sc.Complete();
}
static void FoldForthDoc(unsigned int, int, int, WordList *[],
Accessor &) {
}
static const char * const forthWordLists[] = {
"control keywords",
"keywords",
"definition words",
"prewords with one argument",
"prewords with two arguments",
"string definition keywords",
0,
};
LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);
<commit_msg>Bug #2806565 FORTH lexer is too keen to mark things as numbers.<commit_after>// Scintilla source code edit control
/** @file LexForth.cxx
** Lexer for FORTH
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
ch == ')' );
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}
static inline bool IsANumChar(int ch) {
return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}
static inline bool IsASpaceChar(int ch) {
return (ch < 0x80) && isspace(ch);
}
static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
Accessor &styler) {
WordList &control = *keywordLists[0];
WordList &keyword = *keywordLists[1];
WordList &defword = *keywordLists[2];
WordList &preword1 = *keywordLists[3];
WordList &preword2 = *keywordLists[4];
WordList &strings = *keywordLists[5];
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Determine if the current state should terminate.
if (sc.state == SCE_FORTH_COMMENT) {
if (sc.atLineEnd) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_COMMENT_ML) {
if (sc.ch == ')') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
// handle numbers here too, because what we thought was a number might
// turn out to be a keyword e.g. 2DUP
if (IsASpaceChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
if (control.InList(s)) {
sc.ChangeState(SCE_FORTH_CONTROL);
} else if (keyword.InList(s)) {
sc.ChangeState(SCE_FORTH_KEYWORD);
} else if (defword.InList(s)) {
sc.ChangeState(SCE_FORTH_DEFWORD);
} else if (preword1.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD1);
} else if (preword2.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD2);
} else if (strings.InList(s)) {
sc.ChangeState(SCE_FORTH_STRING);
newState = SCE_FORTH_STRING;
}
sc.SetState(newState);
}
if (sc.state == SCE_FORTH_NUMBER) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
} else if (!IsANumChar(sc.ch)) {
sc.ChangeState(SCE_FORTH_IDENTIFIER);
}
}
}else if (sc.state == SCE_FORTH_STRING) {
if (sc.ch == '\"') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_LOCALE) {
if (sc.ch == '}') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_DEFWORD) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_FORTH_DEFAULT) {
if (sc.ch == '\\'){
sc.SetState(SCE_FORTH_COMMENT);
} else if (sc.ch == '(' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext))) {
sc.SetState(SCE_FORTH_COMMENT_ML);
} else if ( (sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
// number starting with $ is a hex number
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
sc.Forward();
} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
// number starting with % is binary
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
sc.Forward();
} else if ( isascii(sc.ch) &&
(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
){
sc.SetState(SCE_FORTH_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_FORTH_IDENTIFIER);
} else if (sc.ch == '{') {
sc.SetState(SCE_FORTH_LOCALE);
} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
// highlight word definitions e.g. : GCD ( n n -- n ) ..... ;
// ^ ^^^
sc.SetState(SCE_FORTH_DEFWORD);
while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
sc.Forward();
} else if (sc.ch == ';' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext)) ) {
// mark the ';' that ends a word
sc.SetState(SCE_FORTH_DEFWORD);
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}
}
sc.Complete();
}
static void FoldForthDoc(unsigned int, int, int, WordList *[],
Accessor &) {
}
static const char * const forthWordLists[] = {
"control keywords",
"keywords",
"definition words",
"prewords with one argument",
"prewords with two arguments",
"string definition keywords",
0,
};
LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);
<|endoftext|>
|
<commit_before>#ifndef _options_hpp_INCLUDED
#define _options_hpp_INCLUDED
/*------------------------------------------------------------------------*/
// The 'check' option has by default '0' in optimized compilation, but for
// debugging and testing we want to set it to '1', by default. Setting
// 'check' to '1' for instance triggers saving all the original clauses for
// checking witnesses and also learned clauses if a solution is provided.
#ifndef NDEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
/*------------------------------------------------------------------------*/
// Some of the 'OPTION' macros below should only be included if certain
// compile time options are enabled. This has the effect, that for instance
// if 'LOGGING' is defined, and thus logging code is included, then also the
// 'log' option is defined. Otherwise the 'log' option is not included.
#ifdef LOGGING
#define LOGOPT OPTION
#else
#define LOGOPT(ARGS...) /**/
#endif
#ifdef QUIET
#define QUTOPT(ARGS...) /**/
#else
#define QUTOPT OPTION
#endif
/*------------------------------------------------------------------------*/
// In order to add new option, simply add a new line below.
#define OPTIONS \
\
/* NAME TYPE, VAL, LO, HI, USAGE */ \
\
OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \
OPTION(arenacompact, bool, 0, 0, 1, "keep clauses compact") \
OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \
OPTION(binary, bool, 1, 0, 1, "use binary proof format") \
OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \
OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \
OPTION(compact, bool, 1, 0, 1, "enable compactification") \
OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \
OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \
OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \
OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \
OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \
OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \
OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \
OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \
OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \
OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \
OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \
OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \
OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \
OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \
OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \
OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \
OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \
OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \
OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \
OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \
OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \
OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \
OPTION(leak, bool, 1, 0, 1, "leak solver memory") \
LOGOPT(log, bool, 0, 0, 1, "enable logging") \
LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \
OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \
OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \
OPTION(posize, int, 4, 4,1e9, "size for saving position") \
OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \
OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \
OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \
OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \
OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \
OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \
OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \
OPTION(profile, int, 2, 0, 4, "profiling level") \
QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \
OPTION(reduceglue, bool, 1, 0, 1, "reduce on glue first") \
OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \
OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \
OPTION(restart, bool, 1, 0, 1, "enable restarting") \
OPTION(restartint, int, 4, 1,1e9, "restart base interval") \
OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \
OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \
OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \
OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \
OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \
OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \
OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \
OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \
OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \
OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \
OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \
OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \
OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \
OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \
OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \
OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \
OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \
QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \
OPTION(vivify, bool, 1, 0, 1, "vivification") \
OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \
OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \
OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \
OPTION(witness, bool, 1, 0, 1, "print witness") \
/*------------------------------------------------------------------------*/
namespace CaDiCaL {
class Internal;
class Options {
Internal * internal;
bool set ( int &, const char *, const char *, const int, const int);
bool set ( bool &, const char *, const char *, const bool, const bool);
bool set (double &, const char *, const char *, const double, const double);
const char * match (const char *, const char *);
public:
// Makes options directly accessible, e.g., for instance declares the
// member 'bool Options.restart' here. This will give fast and type save
// access to option values (internally). In principle one could make all
// options simply 'double' though, but that requires double conversions
// during accessing options at run-time and disregards the intended types,
// e.g., one would need to allow fractional values for actual integer
// or boolean options. Keeping the different types makes the output of
// 'print' and 'usage' also more appealing (since correctly typed values
// are printed).
#define OPTION(N,T,V,L,H,D) \
T N;
OPTIONS
#undef OPTION
Options (Internal *);
// This sets the value of an option assuming a 'long' command line
// argument form. The argument 'arg' thus should look like
//
// "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>"
//
// where 'NAME' is one of the option names above. Returns 'true' if the
// option was parsed and set correctly. For boolean values we strictly
// only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int'
// type options we parse "<VAL>" with 'atoi' and force the resulting 'int'
// value to the 'LO' and 'HI' range and similarly for 'double' type
// options using 'atof'. If the string is not a valid 'int' for 'int'
// options or a 'double' value for 'double' options, then the function
// returns 'false'.
//
bool set (const char * arg);
// Interface to options using in a certain sense non-type-safe 'double'
// values even for 'int' and 'bool'. However, 'double' can hold a 'bool'
// as well an 'int' value precisely, e.g., if the result of 'get' is cast
// down again by the client. This would only fail for 64 byte 'long',
// which we currently do not support as option type.
//
bool has (const char * name);
double get (const char * name);
bool set (const char * name, double);
void print (); // print current values in command line form
static void usage (); // print usage message for all options
};
};
#endif
<commit_msg>switched arenacompact on again<commit_after>#ifndef _options_hpp_INCLUDED
#define _options_hpp_INCLUDED
/*------------------------------------------------------------------------*/
// The 'check' option has by default '0' in optimized compilation, but for
// debugging and testing we want to set it to '1', by default. Setting
// 'check' to '1' for instance triggers saving all the original clauses for
// checking witnesses and also learned clauses if a solution is provided.
#ifndef NDEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
/*------------------------------------------------------------------------*/
// Some of the 'OPTION' macros below should only be included if certain
// compile time options are enabled. This has the effect, that for instance
// if 'LOGGING' is defined, and thus logging code is included, then also the
// 'log' option is defined. Otherwise the 'log' option is not included.
#ifdef LOGGING
#define LOGOPT OPTION
#else
#define LOGOPT(ARGS...) /**/
#endif
#ifdef QUIET
#define QUTOPT(ARGS...) /**/
#else
#define QUTOPT OPTION
#endif
/*------------------------------------------------------------------------*/
// In order to add new option, simply add a new line below.
#define OPTIONS \
\
/* NAME TYPE, VAL, LO, HI, USAGE */ \
\
OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \
OPTION(arenacompact, bool, 1, 0, 1, "keep clauses compact") \
OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \
OPTION(binary, bool, 1, 0, 1, "use binary proof format") \
OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \
OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \
OPTION(compact, bool, 1, 0, 1, "enable compactification") \
OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \
OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \
OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \
OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \
OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \
OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \
OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \
OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \
OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \
OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \
OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \
OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \
OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \
OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \
OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \
OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \
OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \
OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \
OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \
OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \
OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \
OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \
OPTION(leak, bool, 1, 0, 1, "leak solver memory") \
LOGOPT(log, bool, 0, 0, 1, "enable logging") \
LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \
OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \
OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \
OPTION(posize, int, 4, 4,1e9, "size for saving position") \
OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \
OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \
OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \
OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \
OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \
OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \
OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \
OPTION(profile, int, 2, 0, 4, "profiling level") \
QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \
OPTION(reduceglue, bool, 1, 0, 1, "reduce on glue first") \
OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \
OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \
OPTION(restart, bool, 1, 0, 1, "enable restarting") \
OPTION(restartint, int, 4, 1,1e9, "restart base interval") \
OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \
OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \
OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \
OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \
OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \
OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \
OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \
OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \
OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \
OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \
OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \
OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \
OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \
OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \
OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \
OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \
OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \
QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \
OPTION(vivify, bool, 1, 0, 1, "vivification") \
OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \
OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \
OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \
OPTION(witness, bool, 1, 0, 1, "print witness") \
/*------------------------------------------------------------------------*/
namespace CaDiCaL {
class Internal;
class Options {
Internal * internal;
bool set ( int &, const char *, const char *, const int, const int);
bool set ( bool &, const char *, const char *, const bool, const bool);
bool set (double &, const char *, const char *, const double, const double);
const char * match (const char *, const char *);
public:
// Makes options directly accessible, e.g., for instance declares the
// member 'bool Options.restart' here. This will give fast and type save
// access to option values (internally). In principle one could make all
// options simply 'double' though, but that requires double conversions
// during accessing options at run-time and disregards the intended types,
// e.g., one would need to allow fractional values for actual integer
// or boolean options. Keeping the different types makes the output of
// 'print' and 'usage' also more appealing (since correctly typed values
// are printed).
#define OPTION(N,T,V,L,H,D) \
T N;
OPTIONS
#undef OPTION
Options (Internal *);
// This sets the value of an option assuming a 'long' command line
// argument form. The argument 'arg' thus should look like
//
// "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>"
//
// where 'NAME' is one of the option names above. Returns 'true' if the
// option was parsed and set correctly. For boolean values we strictly
// only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int'
// type options we parse "<VAL>" with 'atoi' and force the resulting 'int'
// value to the 'LO' and 'HI' range and similarly for 'double' type
// options using 'atof'. If the string is not a valid 'int' for 'int'
// options or a 'double' value for 'double' options, then the function
// returns 'false'.
//
bool set (const char * arg);
// Interface to options using in a certain sense non-type-safe 'double'
// values even for 'int' and 'bool'. However, 'double' can hold a 'bool'
// as well an 'int' value precisely, e.g., if the result of 'get' is cast
// down again by the client. This would only fail for 64 byte 'long',
// which we currently do not support as option type.
//
bool has (const char * name);
double get (const char * name);
bool set (const char * name, double);
void print (); // print current values in command line form
static void usage (); // print usage message for all options
};
};
#endif
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "SharedInt.h"
#include "Singleton.h"
GTEST_TEST(BasicTest, DefaultConstructed)
{
SharedInt::AllowAllocations(false);
EXPECT_EQ(0, SharedInt::ReferenceCount());
SharedInt a, b, c;
EXPECT_EQ(0, a.value());
EXPECT_EQ(0, b.value());
EXPECT_EQ(0, c.value());
EXPECT_EQ(1, SharedInt::ReferenceCount());
// No heap memory has been allocated so far.
EXPECT_EQ(0, SharedInt::AllocatedCount());
//All three variables point to the shared null
EXPECT_EQ(a.d.pointer, b.d.pointer);
EXPECT_EQ(b.d.pointer, c.d.pointer);
}
GTEST_TEST(BasicTest, StandardUsage)
{
{
EXPECT_EQ(0, SharedInt::AllocatedCount());
// ReferenceCount will include the "shared null" object,
// so it will always be 1 larger than expected.
EXPECT_EQ(1, SharedInt::ReferenceCount());
SharedInt x(1), y(2), z(3);
// No variables have been allocated on the heap.
EXPECT_EQ(0, SharedInt::AllocatedCount());
EXPECT_EQ(3+1, SharedInt::ReferenceCount());
// Check their values
EXPECT_EQ(1, x.value());
EXPECT_EQ(2, y.value());
EXPECT_EQ(3, z.value());
y = x;
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
z = y;
EXPECT_EQ(1+1, SharedInt::ReferenceCount());
// Now two have been freed, and all three point to the same value(1).
EXPECT_EQ(1, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
// The following line changes x, but leaves y and z unchanged.
x.setValue(4);
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
EXPECT_EQ(4, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
}
// Check that all memory has been freed
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Arrays)
{
SharedInt::AllowAllocations(false);
static const int Size = 256;
// The following line triggers no heap allocation:
SharedInt array[Size];
EXPECT_EQ(1, SharedInt::ReferenceCount());
// Check that a single element has the size of one pointer:
EXPECT_EQ(sizeof(void*), sizeof(array)/Size);
std::vector<SharedInt> vector(100);
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Failure)
{
struct Data { int value = 0; };
COW<Data> d;
// Access should work on a default constructed object.
d->value = 1;
}
GTEST_TEST(BasicTest, Count)
{
COW<int> a(2);
EXPECT_EQ(2, a.constData());
EXPECT_EQ(1, a.count());
COW<int> b = COW<int>(4);
EXPECT_EQ(4, b.constData());
EXPECT_EQ(1, b.count());
COW<int> c = a;
EXPECT_EQ(2, a.count());
EXPECT_EQ(2, c.count());
EXPECT_EQ(c.constData(), a.constData());
a.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
EXPECT_EQ(2, a.constData());
EXPECT_EQ(4, b.constData());
EXPECT_EQ(2, c.constData());
c.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
}
static int ctor_count = 0;
static int copy_count = 0;
static int forwarding_count = 0;
static int assignment_count = 0;
GTEST_TEST(BasicTest, perfectForwarding)
{
struct ConstructorTester
{
ConstructorTester()
{
ctor_count++;
}
ConstructorTester(const ConstructorTester&)
{
copy_count++;
}
ConstructorTester(ConstructorTester&&)
{
forwarding_count++;
}
ConstructorTester& operator=(const ConstructorTester&)
{
assignment_count++;
return *this;
}
static ConstructorTester get()
{
ConstructorTester tmp;
return std::move(tmp);
}
};
EXPECT_EQ(0, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> a, b, c;
EXPECT_EQ(1, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> d(ConstructorTester::get());
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_NE(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
a = c;
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, assignment_count);
b.data() = d.constData();
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(1, copy_count);
EXPECT_EQ(1, assignment_count);
}
struct ThereCanBeOnlyOne
{
int value = 1;
static int count;
ThereCanBeOnlyOne()
{
EXPECT_EQ(count, 0);
count++;
}
// MOCK_METHOD0(MakeSureDtorIsCalled, void());
~ThereCanBeOnlyOne()
{
EXPECT_EQ(count, 1);
//MakeSureDtorIsCalled();
--count;
}
ThereCanBeOnlyOne(const ThereCanBeOnlyOne&)=delete;
ThereCanBeOnlyOne& operator=(const ThereCanBeOnlyOne&)=delete;
};
int ThereCanBeOnlyOne::count=0;
GTEST_TEST(BasicTest, Singleton)
{
EXPECT_EQ(ThereCanBeOnlyOne::count, 0);
ThereCanBeOnlyOne& one = Singleton<ThereCanBeOnlyOne>::get();
EXPECT_EQ(ThereCanBeOnlyOne::count, 1);
EXPECT_EQ(one.value, 1);
ThereCanBeOnlyOne& two = Singleton<ThereCanBeOnlyOne>::get();
EXPECT_EQ(ThereCanBeOnlyOne::count, 1);
one.value = 2;
EXPECT_EQ(one.value, 2);
EXPECT_EQ(two.value, 2);
// TODO: make the following line work,
// Otherwise we are not testing that the dtor is called.
// EXPECT_CALL(one, MakeSureDtorIsCalled());
}
<commit_msg>Fixed MSVC 2013 ICE.<commit_after>#include "gtest/gtest.h"
#include "SharedInt.h"
#include "Singleton.h"
GTEST_TEST(BasicTest, DefaultConstructed)
{
SharedInt::AllowAllocations(false);
EXPECT_EQ(0, SharedInt::ReferenceCount());
SharedInt a, b, c;
EXPECT_EQ(0, a.value());
EXPECT_EQ(0, b.value());
EXPECT_EQ(0, c.value());
EXPECT_EQ(1, SharedInt::ReferenceCount());
// No heap memory has been allocated so far.
EXPECT_EQ(0, SharedInt::AllocatedCount());
//All three variables point to the shared null
EXPECT_EQ(a.d.pointer, b.d.pointer);
EXPECT_EQ(b.d.pointer, c.d.pointer);
}
GTEST_TEST(BasicTest, StandardUsage)
{
{
EXPECT_EQ(0, SharedInt::AllocatedCount());
// ReferenceCount will include the "shared null" object,
// so it will always be 1 larger than expected.
EXPECT_EQ(1, SharedInt::ReferenceCount());
SharedInt x(1), y(2), z(3);
// No variables have been allocated on the heap.
EXPECT_EQ(0, SharedInt::AllocatedCount());
EXPECT_EQ(3+1, SharedInt::ReferenceCount());
// Check their values
EXPECT_EQ(1, x.value());
EXPECT_EQ(2, y.value());
EXPECT_EQ(3, z.value());
y = x;
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
z = y;
EXPECT_EQ(1+1, SharedInt::ReferenceCount());
// Now two have been freed, and all three point to the same value(1).
EXPECT_EQ(1, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
// The following line changes x, but leaves y and z unchanged.
x.setValue(4);
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
EXPECT_EQ(4, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
}
// Check that all memory has been freed
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Arrays)
{
SharedInt::AllowAllocations(false);
static const int Size = 256;
// The following line triggers no heap allocation:
SharedInt array[Size];
EXPECT_EQ(1, SharedInt::ReferenceCount());
// Check that a single element has the size of one pointer:
EXPECT_EQ(sizeof(void*), sizeof(array)/Size);
std::vector<SharedInt> vector(100);
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
struct Data { int value = 0; };
GTEST_TEST(BasicTest, Failure)
{
COW<Data> d;
// Access should work on a default constructed object.
d->value = 1;
}
GTEST_TEST(BasicTest, Count)
{
COW<int> a(2);
EXPECT_EQ(2, a.constData());
EXPECT_EQ(1, a.count());
COW<int> b = COW<int>(4);
EXPECT_EQ(4, b.constData());
EXPECT_EQ(1, b.count());
COW<int> c = a;
EXPECT_EQ(2, a.count());
EXPECT_EQ(2, c.count());
EXPECT_EQ(c.constData(), a.constData());
a.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
EXPECT_EQ(2, a.constData());
EXPECT_EQ(4, b.constData());
EXPECT_EQ(2, c.constData());
c.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
}
static int ctor_count = 0;
static int copy_count = 0;
static int forwarding_count = 0;
static int assignment_count = 0;
GTEST_TEST(BasicTest, perfectForwarding)
{
struct ConstructorTester
{
ConstructorTester()
{
ctor_count++;
}
ConstructorTester(const ConstructorTester&)
{
copy_count++;
}
ConstructorTester(ConstructorTester&&)
{
forwarding_count++;
}
ConstructorTester& operator=(const ConstructorTester&)
{
assignment_count++;
return *this;
}
static ConstructorTester get()
{
ConstructorTester tmp;
return std::move(tmp);
}
};
EXPECT_EQ(0, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> a, b, c;
EXPECT_EQ(1, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> d(ConstructorTester::get());
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_NE(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
a = c;
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, assignment_count);
b.data() = d.constData();
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(1, copy_count);
EXPECT_EQ(1, assignment_count);
}
struct ThereCanBeOnlyOne
{
int value = 1;
static int count;
ThereCanBeOnlyOne()
{
EXPECT_EQ(count, 0);
count++;
}
// MOCK_METHOD0(MakeSureDtorIsCalled, void());
~ThereCanBeOnlyOne()
{
EXPECT_EQ(count, 1);
//MakeSureDtorIsCalled();
--count;
}
ThereCanBeOnlyOne(const ThereCanBeOnlyOne&)=delete;
ThereCanBeOnlyOne& operator=(const ThereCanBeOnlyOne&)=delete;
};
int ThereCanBeOnlyOne::count=0;
GTEST_TEST(BasicTest, Singleton)
{
EXPECT_EQ(ThereCanBeOnlyOne::count, 0);
ThereCanBeOnlyOne& one = Singleton<ThereCanBeOnlyOne>::get();
EXPECT_EQ(ThereCanBeOnlyOne::count, 1);
EXPECT_EQ(one.value, 1);
ThereCanBeOnlyOne& two = Singleton<ThereCanBeOnlyOne>::get();
EXPECT_EQ(ThereCanBeOnlyOne::count, 1);
one.value = 2;
EXPECT_EQ(one.value, 2);
EXPECT_EQ(two.value, 2);
// TODO: make the following line work,
// Otherwise we are not testing that the dtor is called.
// EXPECT_CALL(one, MakeSureDtorIsCalled());
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2005/03/01
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// Licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//----------------------------------------------------------------------------
#include "log.h"
#include <stdlib.h>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
using namespace KFS;
log4cpp::Category* KFS::MsgLogger::logger = NULL;
void
MsgLogger::Init(const char *filename, log4cpp::Priority::Value priority)
{
log4cpp::Appender* appender;
log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
layout->setConversionPattern("%d{%m-%d-%Y %H:%M:%S.%l} %p - %m %n");
if (filename != NULL) {
// set the max. log file size to be 100M before it rolls over
// to the next; save the last 10 log files.
appender = new log4cpp::RollingFileAppender("default", std::string(filename),
100 * 1024 * 1024, 10);
}
else
appender = new log4cpp::OstreamAppender("default", &std::cout);
appender->setLayout(layout);
logger = &(log4cpp::Category::getInstance(std::string("kfs")));
logger->addAppender(appender);
// logger->setAdditivity(false);
logger->setPriority(priority);
}
void MsgLogger::SetLevel(log4cpp::Priority::Value priority) {
logger->setPriority(priority);
}
<commit_msg> -- If a file isn't specified for output of log messages, send the output to cerr rather than cout. Otheriwse, tools that cat data from the file will also see client log output.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2005/03/01
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// Licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//----------------------------------------------------------------------------
#include "log.h"
#include <stdlib.h>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
using namespace KFS;
log4cpp::Category* KFS::MsgLogger::logger = NULL;
void
MsgLogger::Init(const char *filename, log4cpp::Priority::Value priority)
{
log4cpp::Appender* appender;
log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
layout->setConversionPattern("%d{%m-%d-%Y %H:%M:%S.%l} %p - %m %n");
if (filename != NULL) {
// set the max. log file size to be 100M before it rolls over
// to the next; save the last 10 log files.
appender = new log4cpp::RollingFileAppender("default", std::string(filename),
100 * 1024 * 1024, 10);
}
else
appender = new log4cpp::OstreamAppender("default", &std::cerr);
appender->setLayout(layout);
logger = &(log4cpp::Category::getInstance(std::string("kfs")));
logger->addAppender(appender);
// logger->setAdditivity(false);
logger->setPriority(priority);
}
void MsgLogger::SetLevel(log4cpp::Priority::Value priority) {
logger->setPriority(priority);
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cstdio>
#include <string>
#if defined __WIN32__
# include <Windows.h>
#endif
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#define CTRL_PRESSED SDL_GetModState() & KMOD_LCTRL
#define bit bool
#include "io.h"
void msg(std::string message, std::string title) {
#if defined __WIN32__
MessageBox(NULL, message.c_str(), title.c_str());
#elif defined __linux__
// TODO Show a graphical error
printf("%s: %s", title.c_str(), message.c_str());
#endif
}
void error(int error, std::string message) {
#if defined __WIN32__
MessageBox(NULL, message.c_str(), "Error", MB_ICONERROR);
#elif defined __linux__
// TODO:Show a graphical error
printf("Error %d: %s", error, message.c_str());
#endif
exit(error);
}
char tiles[256*30];
uint16_t tiles_w = 256, tiles_h = 30;
int ply_x, ply_y;
float x_vel, y_vel;
char mapeditor_selectedtile = 0;
bool mapeditor_show = false;
bool mapeditor_drawterrain = true;
bool mapeditor_editmode = 0; // 0 = tiles, 1 = entities
bool mapeditor_filedialog_show = false;
bool mapeditor_filedialog_selected = 0;
bool mapeditor_filedialog_type = 0; // 0 == Load, 1 == Save
int mapeditor_camerax, mapeditor_cameray;
std::string mapeditor_filedialog_filename = "";
void draw_sprite(short srcx, short srcy, short dstx, short dsty, unsigned short w, unsigned short h, SDL_Surface *srcs, SDL_Surface *dsts) {
SDL_Rect src = { .x = srcx, .y = srcy, .w = w, .h = h };
SDL_Rect dst = { .x = dstx, .y = dsty };
SDL_BlitSurface(srcs, &src, dsts, &dst);
}
void draw_string(std::string text, int x, int y, SDL_Surface *txt, SDL_Surface *screen) {
for (int c : text) {
draw_sprite((c % 16) * 24, (c / 16) * 24, x, y, 24, 24, txt, screen);
x += 24;
}
}
int main(int argc, char** argv) {
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
error(1, std::string("Unable to initialize SDL - ") + SDL_GetError());
if (Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096) < 0)
error(4, std::string("Unable to initialize SDL_mixer - ") + SDL_GetError());
// Make sure SDL cleans up before exit
atexit(SDL_Quit);
// Create a new window
SDL_Surface* screen = SDL_SetVideoMode(768, 720, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
if (!screen)
error(2, std::string("Unable to set 768x720 video - ") + SDL_GetError());
// Load the textures
SDL_Surface *tmp = SDL_LoadBMP("sprites/sprites.bmp");
if (!tmp) error(3, std::string("Couldn't load texture sprites.bmp"));
SDL_Surface *s_sprites = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_sprites, SDL_SRCCOLORKEY, SDL_MapRGB(s_sprites->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/map.bmp");
if (!tmp) error(3, std::string("Couldn't load texture map.bmp"));
SDL_Surface *s_map = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_map, SDL_SRCCOLORKEY, SDL_MapRGB(s_map->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/mapeditor.bmp");
if (!tmp) error(3, std::string("Couldn't load texture mapeditor.bmp"));
SDL_Surface *s_mapeditor = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_mapeditor, SDL_SRCCOLORKEY, SDL_MapRGB(s_mapeditor->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/gui.bmp");
if (!tmp) error(3, std::string("Couldn't load texture font.bmp"));
SDL_Surface *s_gui = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_gui, SDL_SRCCOLORKEY, SDL_MapRGB(s_gui->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/entities.bmp");
if (!tmp) error(3, std::string("Couldn't load texture entities.bmp"));
SDL_Surface *s_entities = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_entities, SDL_SRCCOLORKEY, SDL_MapRGB(s_entities->format, 0xFF, 0x00, 0xFF));
Mix_Music *music = Mix_LoadMUS("music.wav");
if (music) {
Mix_PlayMusic(music, -1);
}
// Start the main loop
bool done = false;
while (!done)
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
done = true;
break;
case SDL_KEYDOWN:
// TODO Clean this up
if (CTRL_PRESSED) {
switch (event.key.keysym.sym) {
case SDLK_q:
done = true; // Ctrl+Q quits the game
break;
case SDLK_e:
mapeditor_show = !mapeditor_show; // Ctrl+E toggles the map editor
break;
}
}
if (mapeditor_show) {
if (mapeditor_filedialog_show) {
// If both mapeditor and filedialog are up
switch (event.key.keysym.sym) {
case SDLK_RIGHT:
case SDLK_LEFT:
mapeditor_filedialog_selected = !mapeditor_filedialog_selected;
break;
case SDLK_BACKSPACE:
// Remove the last character from the filename
if (mapeditor_filedialog_filename.size() > 0)
mapeditor_filedialog_filename.pop_back();
break;
case SDLK_SPACE:
// Add a space to the filename
mapeditor_filedialog_filename += ' ';
break;
case SDLK_RETURN:
if (mapeditor_filedialog_selected == 0) { // If the save/load button is selected
int i;
if (mapeditor_filedialog_type == 1) { // If it's a save dialog
if ((i = export_file(mapeditor_filedialog_filename, tiles, tiles_w, tiles_h)) < 0)
msg("Couldn't export: Error " + i, "Error");
else
mapeditor_filedialog_show = false;
} else { // If it's a load dialog
if ((i = import_file(mapeditor_filedialog_filename, tiles, &tiles_w, &tiles_h)) < 0)
msg("Couldn't import: error " + i, "Error");
else
mapeditor_filedialog_show = false;
}
} else { // If the cancel button is selected
mapeditor_filedialog_show = false; // Just close the dialog
}
}
if ((event.key.keysym.sym >= SDLK_a) && (event.key.keysym.sym <= SDLK_z))
mapeditor_filedialog_filename += event.key.keysym.sym + ((event.key.keysym.mod & KMOD_SHIFT) ? -32 : 0);
} else {
// If mapeditor is up and filedialog isn't
switch (event.key.keysym.sym) {
case SDLK_s:
mapeditor_filedialog_type = 1;
mapeditor_filedialog_show = true;
break;
case SDLK_o:
mapeditor_filedialog_type = 0;
mapeditor_filedialog_show = true;
break;
}
}
}
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_WHEELUP) {
if (mapeditor_show) {
if (--mapeditor_selectedtile == -1) mapeditor_selectedtile++;
}
} else if (event.button.button == SDL_BUTTON_WHEELDOWN) {
if (mapeditor_show) {
if (++mapeditor_selectedtile == 0) mapeditor_selectedtile--;
}
} else if (event.button.button == SDL_BUTTON_LEFT) {
if (mapeditor_show) {
}
}
case SDL_MOUSEMOTION:
if (event.motion.state == SDL_BUTTON(SDL_BUTTON_MIDDLE) && mapeditor_show) {
if ((mapeditor_camerax + event.motion.xrel) <= 0 && (mapeditor_camerax + event.motion.xrel) > -tiles_w * 24 + 768) mapeditor_camerax += event.motion.xrel;
if ((mapeditor_cameray + event.motion.yrel) <= 0 && (mapeditor_cameray + event.motion.yrel) > -tiles_h * 24 + 720) mapeditor_cameray += event.motion.yrel;
}
}
}
// Clear screen
SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
if (mapeditor_show) {
draw_sprite(0, 96, 0, 0, 240, 24, s_map, screen);
for (int j = 0; j < 256; j++) { // horizontal
for (int i = 0; i < 30; i++) { // vertical
int tile = tiles[i*256+j];
draw_sprite((tile % 16)*24, (tile / 16)*24, (j * 24) + mapeditor_camerax, (i * 24) + mapeditor_cameray, 24, 24, s_mapeditor, screen);
}
}
if (!mapeditor_filedialog_show) {
int x, y, state = SDL_GetMouseState(&x, &y);
if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
tiles[(event.button.y-mapeditor_cameray)/24*256 + (event.button.x-mapeditor_camerax)/24] = mapeditor_selectedtile;
else if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
tiles[(event.button.y-mapeditor_cameray)/24*256 + (event.button.x-mapeditor_camerax)/24] = 0;
draw_sprite((mapeditor_selectedtile % 16)*24, (mapeditor_selectedtile / 16)*24, ((x-mapeditor_camerax) / 24 * 24) + mapeditor_camerax, ((y-mapeditor_cameray) / 24 * 24) + mapeditor_cameray, 24, 24, s_mapeditor, screen);
} else {
// Draw the background
draw_sprite(0, 0, 72, 312, 24, 24, s_gui, screen);
draw_sprite(24, 0, 672, 312, 24, 24, s_gui, screen);
draw_sprite(48, 0, 72, 408, 24, 24, s_gui, screen);
draw_sprite(72, 0, 672, 408, 24, 24, s_gui, screen);
for (int i = 96; i <= 648; i += 24)
for (int j = 312; j <= 408; j += 24)
draw_sprite(96, 0, i, j, 24, 24, s_gui, screen);
for (int i = 336; i <= 384; i += 24) {
draw_sprite(96, 0, 72, i, 24, 24, s_gui, screen);
draw_sprite(96, 0, 672, i, 24, 24, s_gui, screen);
}
// Draw the button and textbox backgrounds
int tb_sprite, saveload_sprite, cancel_sprite;
switch (mapeditor_filedialog_selected) {
case 0: saveload_sprite = 120; tb_sprite = cancel_sprite = 144; break;
case 1: cancel_sprite = 120; tb_sprite = saveload_sprite = 144; break;
}
for (int i = 96; i <= 648; i += 24) draw_sprite(tb_sprite, 0, i, 360, 24, 24, s_gui, screen);
for (int i = 120; i <= 240; i += 24) draw_sprite(saveload_sprite, 0, i, 408, 24, 24, s_gui, screen);
for (int i = 456; i <= 624; i += 24) draw_sprite(cancel_sprite, 0, i, 408, 24, 24, s_gui, screen);
// Draw the strings
draw_string("Enter map name", 216, 312, s_gui, screen);
draw_string(mapeditor_filedialog_type ? "Save" : "Load", 144, 408, s_gui, screen);
draw_string("Cancel", 480, 408, s_gui, screen);
draw_string(mapeditor_filedialog_filename, 120, 360, s_gui, screen);
}
}
if (!mapeditor_show) {
// TODO:Draw the background
// Draw the terrain
for (int j = 0; j < 256; j++) { // horizontal
for (int i = 0; i < 30; i++) { // vertical
int tile = tiles[i*256+j];
draw_sprite((tile % 16)*24, (tile / 16)*24, j * 24, i * 24, 24, 24, s_map, screen);
}
}
// Draw the player
int target_x = ply_x + x_vel;
int target_y = ply_y + y_vel;
// TODO:Collision detection
ply_x = target_x;
ply_y = target_y;
draw_sprite(0, 0, ply_x * 3, ply_y * 3, 48, 72, s_sprites, screen);
// TODO:Draw the enemies
// TODO:Draw the foreground
}
// Swap the buffers (and update the screen)
SDL_Flip(screen);
}
// Free bitmaps
SDL_FreeSurface(s_sprites);
return 0;
}
// TODO:Make a game out of this
<commit_msg>Replaced spaces with tabs<commit_after>#include <cstdlib>
#include <cstdio>
#include <string>
#if defined __WIN32__
# include <Windows.h>
#endif
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#define CTRL_PRESSED SDL_GetModState() & KMOD_LCTRL
#define bit bool
#include "io.h"
void msg(std::string message, std::string title) {
#if defined __WIN32__
MessageBox(NULL, message.c_str(), title.c_str());
#elif defined __linux__
// TODO Show a graphical error
printf("%s: %s", title.c_str(), message.c_str());
#endif
}
void error(int error, std::string message) {
#if defined __WIN32__
MessageBox(NULL, message.c_str(), "Error", MB_ICONERROR);
#elif defined __linux__
// TODO:Show a graphical error
printf("Error %d: %s", error, message.c_str());
#endif
exit(error);
}
char tiles[256*30];
uint16_t tiles_w = 256, tiles_h = 30;
int ply_x, ply_y;
float x_vel, y_vel;
char mapeditor_selectedtile = 0;
bool mapeditor_show = false;
bool mapeditor_drawterrain = true;
bool mapeditor_editmode = 0; // 0 = tiles, 1 = entities
bool mapeditor_filedialog_show = false;
bool mapeditor_filedialog_selected = 0;
bool mapeditor_filedialog_type = 0; // 0 == Load, 1 == Save
int mapeditor_camerax, mapeditor_cameray;
std::string mapeditor_filedialog_filename = "";
void draw_sprite(short srcx, short srcy, short dstx, short dsty, unsigned short w, unsigned short h, SDL_Surface *srcs, SDL_Surface *dsts) {
SDL_Rect src = { .x = srcx, .y = srcy, .w = w, .h = h };
SDL_Rect dst = { .x = dstx, .y = dsty };
SDL_BlitSurface(srcs, &src, dsts, &dst);
}
void draw_string(std::string text, int x, int y, SDL_Surface *txt, SDL_Surface *screen) {
for (int c : text) {
draw_sprite((c % 16) * 24, (c / 16) * 24, x, y, 24, 24, txt, screen);
x += 24;
}
}
int main(int argc, char** argv) {
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
error(1, std::string("Unable to initialize SDL - ") + SDL_GetError());
if (Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096) < 0)
error(4, std::string("Unable to initialize SDL_mixer - ") + SDL_GetError());
// Make sure SDL cleans up before exit
atexit(SDL_Quit);
// Create a new window
SDL_Surface* screen = SDL_SetVideoMode(768, 720, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
if (!screen)
error(2, std::string("Unable to set 768x720 video - ") + SDL_GetError());
// Load the textures
SDL_Surface *tmp = SDL_LoadBMP("sprites/sprites.bmp");
if (!tmp) error(3, std::string("Couldn't load texture sprites.bmp"));
SDL_Surface *s_sprites = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_sprites, SDL_SRCCOLORKEY, SDL_MapRGB(s_sprites->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/map.bmp");
if (!tmp) error(3, std::string("Couldn't load texture map.bmp"));
SDL_Surface *s_map = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_map, SDL_SRCCOLORKEY, SDL_MapRGB(s_map->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/mapeditor.bmp");
if (!tmp) error(3, std::string("Couldn't load texture mapeditor.bmp"));
SDL_Surface *s_mapeditor = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_mapeditor, SDL_SRCCOLORKEY, SDL_MapRGB(s_mapeditor->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/gui.bmp");
if (!tmp) error(3, std::string("Couldn't load texture font.bmp"));
SDL_Surface *s_gui = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_gui, SDL_SRCCOLORKEY, SDL_MapRGB(s_gui->format, 0xFF, 0x00, 0xFF));
tmp = SDL_LoadBMP("sprites/entities.bmp");
if (!tmp) error(3, std::string("Couldn't load texture entities.bmp"));
SDL_Surface *s_entities = SDL_DisplayFormat(tmp); SDL_FreeSurface(tmp);
SDL_SetColorKey(s_entities, SDL_SRCCOLORKEY, SDL_MapRGB(s_entities->format, 0xFF, 0x00, 0xFF));
Mix_Music *music = Mix_LoadMUS("music.wav");
if (music) {
Mix_PlayMusic(music, -1);
}
// Start the main loop
bool done = false;
while (!done)
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
done = true;
break;
case SDL_KEYDOWN:
// TODO Clean this up
if (CTRL_PRESSED) {
switch (event.key.keysym.sym) {
case SDLK_q:
done = true; // Ctrl+Q quits the game
break;
case SDLK_e:
mapeditor_show = !mapeditor_show; // Ctrl+E toggles the map editor
break;
}
}
if (mapeditor_show) {
if (mapeditor_filedialog_show) {
// If both mapeditor and filedialog are up
switch (event.key.keysym.sym) {
case SDLK_RIGHT:
case SDLK_LEFT:
mapeditor_filedialog_selected = !mapeditor_filedialog_selected;
break;
case SDLK_BACKSPACE:
// Remove the last character from the filename
if (mapeditor_filedialog_filename.size() > 0)
mapeditor_filedialog_filename.pop_back();
break;
case SDLK_SPACE:
// Add a space to the filename
mapeditor_filedialog_filename += ' ';
break;
case SDLK_RETURN:
if (mapeditor_filedialog_selected == 0) { // If the save/load button is selected
int i;
if (mapeditor_filedialog_type == 1) { // If it's a save dialog
if ((i = export_file(mapeditor_filedialog_filename, tiles, tiles_w, tiles_h)) < 0)
msg("Couldn't export: Error " + i, "Error");
else
mapeditor_filedialog_show = false;
} else { // If it's a load dialog
if ((i = import_file(mapeditor_filedialog_filename, tiles, &tiles_w, &tiles_h)) < 0)
msg("Couldn't import: error " + i, "Error");
else
mapeditor_filedialog_show = false;
}
} else { // If the cancel button is selected
mapeditor_filedialog_show = false; // Just close the dialog
}
}
if ((event.key.keysym.sym >= SDLK_a) && (event.key.keysym.sym <= SDLK_z))
mapeditor_filedialog_filename += event.key.keysym.sym + ((event.key.keysym.mod & KMOD_SHIFT) ? -32 : 0);
} else {
// If mapeditor is up and filedialog isn't
switch (event.key.keysym.sym) {
case SDLK_s:
mapeditor_filedialog_type = 1;
mapeditor_filedialog_show = true;
break;
case SDLK_o:
mapeditor_filedialog_type = 0;
mapeditor_filedialog_show = true;
break;
}
}
}
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_WHEELUP) {
if (mapeditor_show) {
if (--mapeditor_selectedtile == -1) mapeditor_selectedtile++;
}
} else if (event.button.button == SDL_BUTTON_WHEELDOWN) {
if (mapeditor_show) {
if (++mapeditor_selectedtile == 0) mapeditor_selectedtile--;
}
} else if (event.button.button == SDL_BUTTON_LEFT) {
if (mapeditor_show) {
}
}
case SDL_MOUSEMOTION:
if (event.motion.state == SDL_BUTTON(SDL_BUTTON_MIDDLE) && mapeditor_show) {
if ((mapeditor_camerax + event.motion.xrel) <= 0 && (mapeditor_camerax + event.motion.xrel) > -tiles_w * 24 + 768) mapeditor_camerax += event.motion.xrel;
if ((mapeditor_cameray + event.motion.yrel) <= 0 && (mapeditor_cameray + event.motion.yrel) > -tiles_h * 24 + 720) mapeditor_cameray += event.motion.yrel;
}
}
}
// Clear screen
SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
if (mapeditor_show) {
draw_sprite(0, 96, 0, 0, 240, 24, s_map, screen);
for (int j = 0; j < 256; j++) { // horizontal
for (int i = 0; i < 30; i++) { // vertical
int tile = tiles[i*256+j];
draw_sprite((tile % 16)*24, (tile / 16)*24, (j * 24) + mapeditor_camerax, (i * 24) + mapeditor_cameray, 24, 24, s_mapeditor, screen);
}
}
if (!mapeditor_filedialog_show) {
int x, y, state = SDL_GetMouseState(&x, &y);
if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
tiles[(event.button.y-mapeditor_cameray)/24*256 + (event.button.x-mapeditor_camerax)/24] = mapeditor_selectedtile;
else if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
tiles[(event.button.y-mapeditor_cameray)/24*256 + (event.button.x-mapeditor_camerax)/24] = 0;
draw_sprite((mapeditor_selectedtile % 16)*24, (mapeditor_selectedtile / 16)*24, ((x-mapeditor_camerax) / 24 * 24) + mapeditor_camerax, ((y-mapeditor_cameray) / 24 * 24) + mapeditor_cameray, 24, 24, s_mapeditor, screen);
} else {
// Draw the background
draw_sprite(0, 0, 72, 312, 24, 24, s_gui, screen);
draw_sprite(24, 0, 672, 312, 24, 24, s_gui, screen);
draw_sprite(48, 0, 72, 408, 24, 24, s_gui, screen);
draw_sprite(72, 0, 672, 408, 24, 24, s_gui, screen);
for (int i = 96; i <= 648; i += 24)
for (int j = 312; j <= 408; j += 24)
draw_sprite(96, 0, i, j, 24, 24, s_gui, screen);
for (int i = 336; i <= 384; i += 24) {
draw_sprite(96, 0, 72, i, 24, 24, s_gui, screen);
draw_sprite(96, 0, 672, i, 24, 24, s_gui, screen);
}
// Draw the button and textbox backgrounds
int tb_sprite, saveload_sprite, cancel_sprite;
switch (mapeditor_filedialog_selected) {
case 0: saveload_sprite = 120; tb_sprite = cancel_sprite = 144; break;
case 1: cancel_sprite = 120; tb_sprite = saveload_sprite = 144; break;
}
for (int i = 96; i <= 648; i += 24) draw_sprite(tb_sprite, 0, i, 360, 24, 24, s_gui, screen);
for (int i = 120; i <= 240; i += 24) draw_sprite(saveload_sprite, 0, i, 408, 24, 24, s_gui, screen);
for (int i = 456; i <= 624; i += 24) draw_sprite(cancel_sprite, 0, i, 408, 24, 24, s_gui, screen);
// Draw the strings
draw_string("Enter map name", 216, 312, s_gui, screen);
draw_string(mapeditor_filedialog_type ? "Save" : "Load", 144, 408, s_gui, screen);
draw_string("Cancel", 480, 408, s_gui, screen);
draw_string(mapeditor_filedialog_filename, 120, 360, s_gui, screen);
}
}
if (!mapeditor_show) {
// TODO:Draw the background
// Draw the terrain
for (int j = 0; j < 256; j++) { // horizontal
for (int i = 0; i < 30; i++) { // vertical
int tile = tiles[i*256+j];
draw_sprite((tile % 16)*24, (tile / 16)*24, j * 24, i * 24, 24, 24, s_map, screen);
}
}
// Draw the player
int target_x = ply_x + x_vel;
int target_y = ply_y + y_vel;
// TODO:Collision detection
ply_x = target_x;
ply_y = target_y;
draw_sprite(0, 0, ply_x * 3, ply_y * 3, 48, 72, s_sprites, screen);
// TODO:Draw the enemies
// TODO:Draw the foreground
}
// Swap the buffers (and update the screen)
SDL_Flip(screen);
}
// Free bitmaps
SDL_FreeSurface(s_sprites);
return 0;
}
// TODO:Make a game out of this
<|endoftext|>
|
<commit_before>#include "./test.h"
#include "../src/camera.h"
TEST(Test_Camera, ConstructorFromMatricesWithDefaultValues)
{
Camera expected;
expected.resize(1, 1);
Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
expected.getOrigin());
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);
// just to recalculate the view matrix from the angles and test them
camera.changeAzimuth(0);
EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_TRUE(camera.needsResizing());
camera.resize(1, 1);
EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
camera.getProjectionMatrix(), 1e-5f);
}
TEST(Test_Camera, ConstructorFromMatricesAfterRotation)
{
Camera expected;
expected.resize(1, 1);
expected.changeAzimuth(M_PI * 0.25f);
Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
expected.getOrigin());
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);
// just to recalculate the view matrix from the angles and test them
camera.changeAzimuth(0);
EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
camera.getProjectionMatrix(), 1e-5f);
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_TRUE(camera.needsResizing());
}
<commit_msg>Add test for animation to current view matrix.<commit_after>#include "./test.h"
#include "../src/camera.h"
TEST(Test_Camera, ConstructorFromMatricesWithDefaultValues)
{
Camera expected;
expected.resize(1, 1);
Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
expected.getOrigin());
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);
// just to recalculate the view matrix from the angles and test them
camera.changeAzimuth(0);
EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_TRUE(camera.needsResizing());
camera.resize(1, 1);
EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
camera.getProjectionMatrix(), 1e-5f);
}
TEST(Test_Camera, ConstructorFromMatricesAfterRotation)
{
Camera expected;
expected.resize(1, 1);
expected.changeAzimuth(M_PI * 0.25f);
Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
expected.getOrigin());
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);
// just to recalculate the view matrix from the angles and test them
camera.changeAzimuth(0);
EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
camera.getProjectionMatrix(), 1e-5f);
EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
EXPECT_TRUE(camera.needsResizing());
}
TEST(Test_Camera, AnimationToTheSamePosition)
{
Camera camera;
Eigen::Matrix4f viewMatrix = camera.getViewMatrix();
camera.startAnimation(viewMatrix, 1.0f);
camera.updateAnimation(1.0f);
EXPECT_Matrix4f_NEAR(viewMatrix, camera.getViewMatrix(), 1e-5f);
}
<|endoftext|>
|
<commit_before>//
// Created by kanairen on 2016/06/15.
//
#include <map>
#include <memory>
#include "config.h"
#include "Data.h"
#include "MNIST.h"
#include "ShapeMap.h"
#include "layer/SoftMaxLayer.h"
#include "layer/ConvLayer.h"
#include "layer/MaxPoolLayer.h"
#include "Model.h"
#include "Optimizer.h"
#include "util/StringUtil.h"
#include "tinyxml/tinyxml2.h"
using tinyxml2::XMLDocument;
using tinyxml2::XMLElement;
using tinyxml2::XMLNode;
#ifdef CONV_NET_CPP_DEBUG
class DataSetHelper {
private:
DataSetHelper() = delete;
DataSetHelper(const DataSetHelper &dataset_helper) = delete;
virtual ~DataSetHelper() = default;
public:
enum Type : long {
MNIST_ = 0x00,
BAND_SHAPE_MAP = 0x01,
};
static DataSet<float, int> *get_dataset(int id, char *argv[]) {
switch (id) {
case MNIST_:
return new MNIST(argv[2], argv[3], argv[4], argv[5]);
case BAND_SHAPE_MAP:
return new ShapeMapSet(argv[2], argv[3]);
default:
error_and_exit(
"DataSetHelper::get_dataset : failed to get dataset.");
return nullptr;
}
}
};
typedef float (*ACTIVATION)(float);
class ActivationHelper {
private:
ActivationHelper() = delete;
ActivationHelper(const ActivationHelper &activation_helper) = delete;
virtual ~ActivationHelper() = default;
public:
enum Type : long {
SIGMOID = 0x00,
RELU = 0x01,
};
static ACTIVATION get_activation(int id) {
switch (id) {
case SIGMOID:
return sigmoid;
case RELU:
return relu;
default:
error_and_exit(
"ActivationHelper::get_activation() : failed to get activate function.");
return nullptr;
}
}
static ACTIVATION get_g_activation(int id) {
switch (id) {
case SIGMOID:
return g_sigmoid;
case RELU:
return g_relu;
default:
error_and_exit(
"ActivationHelper::get_grad_activation() : failed to get activate function.");
return nullptr;
}
}
};
namespace xmlkey {
constexpr char FULL_CONNECT[] = "full_connect";
constexpr char SOFTMAX[] = "softmax";
constexpr char N_HIDDEN[] = "n_hidden";
constexpr char ACTIVATION_ID[] = "activation_id";
constexpr char IS_WEIGHT_RAND_INIT_ENABLED[] = "is_weight_rand_init_enabled";
constexpr char WEIGHT_CONSTANT_VALUE[] = "weight_constant_value";
constexpr char IS_DROPOUT_ENABLED[] = "is_dropout_enabled";
constexpr char DROPOUT_RATE[] = "dropout_rate";
}
std::map<string, string> params_common(XMLElement *elem) {
return {
{xmlkey::IS_WEIGHT_RAND_INIT_ENABLED, elem->FirstChildElement(
xmlkey::IS_WEIGHT_RAND_INIT_ENABLED)->GetText()},
{xmlkey::WEIGHT_CONSTANT_VALUE, elem->FirstChildElement(
xmlkey::WEIGHT_CONSTANT_VALUE)->GetText()},
{xmlkey::IS_DROPOUT_ENABLED, elem->FirstChildElement(
xmlkey::IS_DROPOUT_ENABLED)->GetText()},
{xmlkey::DROPOUT_RATE, elem->FirstChildElement(
xmlkey::DROPOUT_RATE)->GetText()},
};
}
std::map<string, string> params_layer(XMLElement *elem) {
std::map<string, string> &&map = params_common(elem);
map[xmlkey::N_HIDDEN] = elem->FirstChildElement(
xmlkey::N_HIDDEN)->GetText();
map[xmlkey::ACTIVATION_ID] = elem->FirstChildElement(
xmlkey::ACTIVATION_ID)->GetText();
return map;
};
std::map<string, string> params_softmax(XMLElement *elem) {
return params_common(elem);
};
Layer_ *new_layer(XMLElement *xml_layer, int n_data, int n_in) {
if (strncmp(xml_layer->Name(), xmlkey::FULL_CONNECT, 2) != 0) {
error_and_exit("new_layer(): a xml element in arguments is incorrect.");
}
std::map<string, string> &&map = params_layer(xml_layer);
// n-hidden
int n_hidden = atoi(map[xmlkey::N_HIDDEN].c_str());
// activation
ACTIVATION act = ActivationHelper::get_activation(
atoi(map[xmlkey::ACTIVATION_ID].c_str()));
// grad-activation
ACTIVATION g_act = ActivationHelper::get_g_activation(
atoi(map[xmlkey::ACTIVATION_ID].c_str()));
// weight initialization setting
bool is_weight_rand_init_enabled = atob(
map[xmlkey::IS_WEIGHT_RAND_INIT_ENABLED].c_str());
float weight_constant_value = std::atof(
map[xmlkey::WEIGHT_CONSTANT_VALUE].c_str());
// dropout setting
bool is_dropout_enabled = atob(map[xmlkey::IS_DROPOUT_ENABLED].c_str());
float dropout_rate = std::atof(map[xmlkey::DROPOUT_RATE].c_str());
return new Layer_(n_data, n_in, n_hidden, act, g_act,
is_weight_rand_init_enabled, weight_constant_value,
is_dropout_enabled, dropout_rate);
}
SoftMaxLayer_ *new_softmax_layer(XMLElement *xml_layer, int n_data, int n_in,
int n_class) {
if (xml_layer->Name() == xmlkey::SOFTMAX) {
error_and_exit(
"new_softmax_layer(): a xml element in arguments is incorrect.");
}
std::map<string, string> &&map = params_softmax(xml_layer);
// weight initialization setting
bool is_weight_rand_init_enabled = atob(
map[xmlkey::IS_WEIGHT_RAND_INIT_ENABLED].c_str());
float weight_constant_value = std::atof(
map[xmlkey::WEIGHT_CONSTANT_VALUE].c_str());
// dropout setting
bool is_dropout_enabled = atob(map[xmlkey::IS_DROPOUT_ENABLED].c_str());
float dropout_rate = std::atof(map[xmlkey::DROPOUT_RATE].c_str());
return new SoftMaxLayer_(n_data, n_in, n_class, is_weight_rand_init_enabled,
weight_constant_value, is_dropout_enabled,
dropout_rate);
}
// コマンドライン引数にmnistへのパスを渡す
int main(int argc, char *argv[]) {
/*
* XML Parse
*/
XMLDocument xml;
xml.LoadFile(argv[1]);
// xml:root
XMLElement *xml_root = xml.FirstChildElement("root");
// xml:n_iteration
XMLElement *xml_n_iteration = xml_root->FirstChildElement("n_iteration");
// xml:learning_rate
XMLElement *xml_lr = xml_root->FirstChildElement("learning_rate");
// xml:data_set
XMLElement *xml_data_set = xml_root->FirstChildElement("data_set");
XMLElement *xml_data_set_id = xml_data_set->FirstChildElement("id");
XMLElement *xml_data_set_is_shuffled = xml_data_set->FirstChildElement(
"is_shuffled");
XMLElement *xml_batch_size = xml_data_set->FirstChildElement("batch_size");
// xml:layer_params
std::vector<std::pair<string, string>> layer_params;
XMLElement *xml_nets = xml_root->FirstChildElement("nets");
/*
* Getting Start
*/
// DataSet
std::unique_ptr<DataSet<float, int>> data_set(DataSetHelper::get_dataset(
std::atoi(xml_data_set_id->GetText()), argv));
// shuffle
ShapeMapSet::shuffle(data_set->x_train, data_set->y_train);
ShapeMapSet::shuffle(data_set->x_test, data_set->y_test);
// Parameters for learning
int n_class = data_set->get_n_cls(); // N-class
int n_iter = std::atoi(xml_n_iteration->GetText()); // N-Iteration
int batch_size = std::atoi(xml_batch_size->GetText());
float learning_rate = (float) std::atof(xml_lr->GetText());
// Layers
vector<Layer_ *> layers;
int n_in = data_set->data_size();
XMLNode *node = xml_nets->FirstChild();
while (node != nullptr) {
XMLElement *xml_nets_elem = node->ToElement();
if (std::strcmp(xml_nets_elem->Name(), xmlkey::FULL_CONNECT) == 0) {
layers.push_back(new_layer(xml_nets_elem, batch_size, n_in));
} else if (std::strcmp(xml_nets_elem->Name(), xmlkey::SOFTMAX) == 0) {
layers.push_back(new_softmax_layer(xml_nets_elem, batch_size, n_in,
n_class));
} else {
error_and_exit("failed to set layer.");
}
node = node->NextSibling();
n_in = layers.back()->get_n_out();
}
// optimize
optimize_(*data_set, layers, learning_rate, batch_size, n_iter,
n_class, argv[argc - 2], argv[argc - 1]);
}
#endif<commit_msg>add コマンドライン引数チェックをmain関数冒頭に追加<commit_after>//
// Created by kanairen on 2016/06/15.
//
#include <map>
#include <memory>
#include "config.h"
#include "Data.h"
#include "MNIST.h"
#include "ShapeMap.h"
#include "layer/SoftMaxLayer.h"
#include "layer/ConvLayer.h"
#include "layer/MaxPoolLayer.h"
#include "Model.h"
#include "Optimizer.h"
#include "util/StringUtil.h"
#include "tinyxml/tinyxml2.h"
using tinyxml2::XMLDocument;
using tinyxml2::XMLElement;
using tinyxml2::XMLNode;
#ifdef CONV_NET_CPP_DEBUG
class DataSetHelper {
private:
DataSetHelper() = delete;
DataSetHelper(const DataSetHelper &dataset_helper) = delete;
virtual ~DataSetHelper() = default;
public:
enum Type : long {
MNIST_ = 0x00,
BAND_SHAPE_MAP = 0x01,
};
static DataSet<float, int> *get_dataset(int id, char *argv[]) {
switch (id) {
case MNIST_:
return new MNIST(argv[2], argv[3], argv[4], argv[5]);
case BAND_SHAPE_MAP:
return new ShapeMapSet(argv[2], argv[3]);
default:
error_and_exit(
"DataSetHelper::get_dataset : failed to get dataset.");
return nullptr;
}
}
};
typedef float (*ACTIVATION)(float);
class ActivationHelper {
private:
ActivationHelper() = delete;
ActivationHelper(const ActivationHelper &activation_helper) = delete;
virtual ~ActivationHelper() = default;
public:
enum Type : long {
SIGMOID = 0x00,
RELU = 0x01,
};
static ACTIVATION get_activation(int id) {
switch (id) {
case SIGMOID:
return sigmoid;
case RELU:
return relu;
default:
error_and_exit(
"ActivationHelper::get_activation() : failed to get activate function.");
return nullptr;
}
}
static ACTIVATION get_g_activation(int id) {
switch (id) {
case SIGMOID:
return g_sigmoid;
case RELU:
return g_relu;
default:
error_and_exit(
"ActivationHelper::get_grad_activation() : failed to get activate function.");
return nullptr;
}
}
};
namespace xmlkey {
constexpr char FULL_CONNECT[] = "full_connect";
constexpr char SOFTMAX[] = "softmax";
constexpr char N_HIDDEN[] = "n_hidden";
constexpr char ACTIVATION_ID[] = "activation_id";
constexpr char IS_WEIGHT_RAND_INIT_ENABLED[] = "is_weight_rand_init_enabled";
constexpr char WEIGHT_CONSTANT_VALUE[] = "weight_constant_value";
constexpr char IS_DROPOUT_ENABLED[] = "is_dropout_enabled";
constexpr char DROPOUT_RATE[] = "dropout_rate";
}
std::map<string, string> params_common(XMLElement *elem) {
return {
{xmlkey::IS_WEIGHT_RAND_INIT_ENABLED, elem->FirstChildElement(
xmlkey::IS_WEIGHT_RAND_INIT_ENABLED)->GetText()},
{xmlkey::WEIGHT_CONSTANT_VALUE, elem->FirstChildElement(
xmlkey::WEIGHT_CONSTANT_VALUE)->GetText()},
{xmlkey::IS_DROPOUT_ENABLED, elem->FirstChildElement(
xmlkey::IS_DROPOUT_ENABLED)->GetText()},
{xmlkey::DROPOUT_RATE, elem->FirstChildElement(
xmlkey::DROPOUT_RATE)->GetText()},
};
}
std::map<string, string> params_layer(XMLElement *elem) {
std::map<string, string> &&map = params_common(elem);
map[xmlkey::N_HIDDEN] = elem->FirstChildElement(
xmlkey::N_HIDDEN)->GetText();
map[xmlkey::ACTIVATION_ID] = elem->FirstChildElement(
xmlkey::ACTIVATION_ID)->GetText();
return map;
};
std::map<string, string> params_softmax(XMLElement *elem) {
return params_common(elem);
};
Layer_ *new_layer(XMLElement *xml_layer, int n_data, int n_in) {
if (strncmp(xml_layer->Name(), xmlkey::FULL_CONNECT, 2) != 0) {
error_and_exit("new_layer(): a xml element in arguments is incorrect.");
}
std::map<string, string> &&map = params_layer(xml_layer);
// n-hidden
int n_hidden = atoi(map[xmlkey::N_HIDDEN].c_str());
// activation
ACTIVATION act = ActivationHelper::get_activation(
atoi(map[xmlkey::ACTIVATION_ID].c_str()));
// grad-activation
ACTIVATION g_act = ActivationHelper::get_g_activation(
atoi(map[xmlkey::ACTIVATION_ID].c_str()));
// weight initialization setting
bool is_weight_rand_init_enabled = atob(
map[xmlkey::IS_WEIGHT_RAND_INIT_ENABLED].c_str());
float weight_constant_value = std::atof(
map[xmlkey::WEIGHT_CONSTANT_VALUE].c_str());
// dropout setting
bool is_dropout_enabled = atob(map[xmlkey::IS_DROPOUT_ENABLED].c_str());
float dropout_rate = std::atof(map[xmlkey::DROPOUT_RATE].c_str());
return new Layer_(n_data, n_in, n_hidden, act, g_act,
is_weight_rand_init_enabled, weight_constant_value,
is_dropout_enabled, dropout_rate);
}
SoftMaxLayer_ *new_softmax_layer(XMLElement *xml_layer, int n_data, int n_in,
int n_class) {
if (xml_layer->Name() == xmlkey::SOFTMAX) {
error_and_exit(
"new_softmax_layer(): a xml element in arguments is incorrect.");
}
std::map<string, string> &&map = params_softmax(xml_layer);
// weight initialization setting
bool is_weight_rand_init_enabled = atob(
map[xmlkey::IS_WEIGHT_RAND_INIT_ENABLED].c_str());
float weight_constant_value = std::atof(
map[xmlkey::WEIGHT_CONSTANT_VALUE].c_str());
// dropout setting
bool is_dropout_enabled = atob(map[xmlkey::IS_DROPOUT_ENABLED].c_str());
float dropout_rate = std::atof(map[xmlkey::DROPOUT_RATE].c_str());
return new SoftMaxLayer_(n_data, n_in, n_class, is_weight_rand_init_enabled,
weight_constant_value, is_dropout_enabled,
dropout_rate);
}
int main(int argc, char *argv[]) {
/*
* Check Command Line Arguments
*/
if (argc != 6) {
string message = "\n The number of arguments is too ";
if (argc > 6) {
message += "much! \n\n";
} else {
message += "short! \n\n";
}
message += " *.out [config xml path] "
"[training data path] [test data path] "
"[training log path] [test log path]";
error_and_exit(message);
}
/*
* XML Parse
*/
XMLDocument xml;
xml.LoadFile(argv[1]);
// xml:root
XMLElement *xml_root = xml.FirstChildElement("root");
// xml:n_iteration
XMLElement *xml_n_iteration = xml_root->FirstChildElement("n_iteration");
// xml:learning_rate
XMLElement *xml_lr = xml_root->FirstChildElement("learning_rate");
// xml:data_set
XMLElement *xml_data_set = xml_root->FirstChildElement("data_set");
XMLElement *xml_data_set_id = xml_data_set->FirstChildElement("id");
XMLElement *xml_data_set_is_shuffled = xml_data_set->FirstChildElement(
"is_shuffled");
XMLElement *xml_batch_size = xml_data_set->FirstChildElement("batch_size");
// xml:layer_params
std::vector<std::pair<string, string>> layer_params;
XMLElement *xml_nets = xml_root->FirstChildElement("nets");
/*
* Getting Start
*/
// DataSet
std::unique_ptr<DataSet<float, int>> data_set(DataSetHelper::get_dataset(
std::atoi(xml_data_set_id->GetText()), argv));
// shuffle
ShapeMapSet::shuffle(data_set->x_train, data_set->y_train);
ShapeMapSet::shuffle(data_set->x_test, data_set->y_test);
// Parameters for learning
int n_class = data_set->get_n_cls(); // N-class
int n_iter = std::atoi(xml_n_iteration->GetText()); // N-Iteration
int batch_size = std::atoi(xml_batch_size->GetText());
float learning_rate = (float) std::atof(xml_lr->GetText());
// Layers
vector<Layer_ *> layers;
int n_in = data_set->data_size();
XMLNode *node = xml_nets->FirstChild();
while (node != nullptr) {
XMLElement *xml_nets_elem = node->ToElement();
if (std::strcmp(xml_nets_elem->Name(), xmlkey::FULL_CONNECT) == 0) {
layers.push_back(new_layer(xml_nets_elem, batch_size, n_in));
} else if (std::strcmp(xml_nets_elem->Name(), xmlkey::SOFTMAX) == 0) {
layers.push_back(new_softmax_layer(xml_nets_elem, batch_size, n_in,
n_class));
} else {
error_and_exit("failed to set layer.");
}
node = node->NextSibling();
n_in = layers.back()->get_n_out();
}
// optimize
optimize_(*data_set, layers, learning_rate, batch_size, n_iter,
n_class, argv[argc - 2], argv[argc - 1]);
}
#endif<|endoftext|>
|
<commit_before>//
// pfilter.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 05/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#include "pfilter.h"
#include <iostream>
namespace EpiGenPfilter {
double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) {
double loglik = 0.0;
int num_groups = options.num_groups;
int num_particles = options.particles;
int init_seed = options.seed;
int total_dt = options.total_dt;
double sim_dt = options.sim_dt;
int total_steps = ceil((double)total_dt/(double)options.pfilter_every);
int add_dt = 0;
double ESS_threshold = options.pfilter_threshold*(double)num_particles;
Likelihood likelihood_calc;
// std::vector <Parameter> values;// (options.num_threads, model_params);
// for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params);
// for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i));
std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0));
for (int i=0; i!=options.num_threads; ++i) {
for (int j=0; j!=model_params.get_total_params(); ++j) {
values[i][j] = model_params.get(j);
}
}
// printf("Size of values = %d\n",values.size());
double reporting_rate = 1.0;
if (model_params.param_exists("reporting")) {
reporting_rate = model_params.get("reporting");
}
std::vector <std::string> param_names = model_params.get_names_vector();
std::vector <std::vector<std::string> > param_names_threads (options.num_threads);
if (model_params.param_exists("time_before_data")) {
add_dt = model_params.get("time_before_data");
}
if (options.save_traj) {
if (add_dt > 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
}
else if (add_dt < 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every);
}
else {
particles.start_particle_tracing(total_dt, num_groups);
}
}
std::vector <Model> models;
for (int i=0; i<options.num_threads; ++i) {
models.push_back(sim_model);
}
std::vector <int> add_dt_threads (options.num_threads, add_dt);
std::vector <int> start_dt_threads (options.num_threads, 0);
std::vector <int> end_dt_threads (options.num_threads, add_dt);
std::vector <double> dt_threads (options.num_threads, sim_dt);
std::vector <int> total_dt_threads(options.num_threads, total_dt);
std::vector <double> reporting_rate_threads(options.num_threads, reporting_rate);
std::vector <int> num_groups_threads(options.num_threads, num_groups);
// Simulate model and calculate likelihood assuming no observed data
if (model_params.param_exists("time_before_data")) {
if (add_dt > 0) {
omp_set_num_threads(options.num_threads);
// std::vector <Trajectory *> curr_trajs;
// for (int i=0; i!=num_particles; ++i) {
// curr_trajs.push_back(particles.get_traj(i));
// }
#pragma omp parallel for shared(particles, values)
for (int i=0; i<num_particles; i++) {
int tn = omp_get_thread_num();
gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 );
gsl_rng_set( r, omp_get_thread_num() + i );
// Adjust length of trajectory
particles.get_traj(i)->resize(add_dt, num_groups);
models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), 0, add_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r);
if (options.which_likelihood<2) {
double w = likelihood_calc.binomial_lik(reporting_rate_threads[tn], particles.get_traj(i)->get_total_traj(), add_dt_threads[tn]+total_dt_threads[tn], 0, add_dt_threads[tn], num_groups_threads[tn], false);
particles.set_weight(w, i, false);
}
if (options.save_traj) {
particles.save_traj_to_matrix(i, 0, add_dt);
particles.save_ancestry(i, 0, add_dt);
}
}
}
}
init_seed += num_particles;
int t=0;
int start_dt;
int end_dt;
for (t=0; t!=total_steps; ++t) {
// std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0);
start_dt = t*options.pfilter_every;
end_dt = std::min(total_dt, (t+1)*options.pfilter_every);
std::fill(start_dt_threads.begin(), start_dt_threads.end(), start_dt);
std::fill(end_dt_threads.begin(), end_dt_threads.end(), end_dt);
omp_set_num_threads(options.num_threads);
#pragma omp parallel for shared (particles, values)
for (int i=0; i<num_particles; i++) {
int tn = omp_get_thread_num();
gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 );
gsl_rng_set( r, omp_get_thread_num() + i );
// Adjust length of trajectory
// if (tn==0) std::cout << i << ' ' << std::endl;
particles.get_traj(i)->resize(end_dt-start_dt, options.num_groups);
models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), start_dt_threads[tn], end_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r);
double w = 1.0;
double temp = 0.0;
if (options.which_likelihood<2) {
double A = particles.get_traj(i)->get_total_traj();
temp = likelihood_calc.binomial_lik(reporting_rate_threads[tn], A, epi_data.get_data_ptr(0), add_dt_threads[tn]+total_dt_threads[tn], start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], num_groups_threads[tn], false);
w *= temp;
// we[i] = log(temp);
}
if (options.which_likelihood != 1) {
temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(0, 0), particles.get_traj(i)->get_traj_ptr(1, 0),
tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0),
start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], false);
w *= temp;
// wg[i] = log(temp);
}
particles.set_weight(w, i, true);
if (options.save_traj) {
particles.save_traj_to_matrix(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]);
particles.save_ancestry(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]);
}
}
// std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl;
double curr_ESS = particles.get_ESS();
if (curr_ESS < ESS_threshold) {
double total_weight = particles.get_total_weight();
if (total_weight == 0.0) {
loglik += -0.1*std::numeric_limits<double>::max();
// std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl;
std::cout << "stop time: " << end_dt << std::endl;
break;
} else {
loglik += log(total_weight) - log(num_particles);
}
particles.resample(options.rng[0]);
}
else {
particles.reset_parents();
}
}
if (options.save_traj) {
output_traj.resize((total_dt+add_dt), num_groups);
//if (loglik > -0.1*std::numeric_limits<double>::max()) {
particles.retrace_traj(output_traj, options.rng[0]);
//}
}
for (int i=0; i!=num_particles; ++i) {
particles.get_traj(i)->reset();
}
std::vector < std::vector<double> >().swap(values);
return (loglik);
}
}
<commit_msg>updated particle filter<commit_after>//
// pfilter.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 05/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#include "pfilter.h"
#include <iostream>
namespace EpiGenPfilter {
double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) {
int thread_max = omp_get_max_threads();
gsl_rng** rngs = new gsl_rng*[thread_max];
for (int thread = 0; thread < thread_max; thread++) {
rngs[thread] = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rngs[thread], omp_get_thread_num() + thread);
}
double loglik = 0.0;
int num_groups = options.num_groups;
int num_particles = options.particles;
int init_seed = options.seed;
int total_dt = options.total_dt;
double sim_dt = options.sim_dt;
int total_steps = ceil((double)total_dt/(double)options.pfilter_every);
int add_dt = 0;
double ESS_threshold = options.pfilter_threshold*(double)num_particles;
Likelihood likelihood_calc;
// std::vector <Parameter> values;// (options.num_threads, model_params);
// for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params);
// for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i));
std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0));
for (int i=0; i!=options.num_threads; ++i) {
for (int j=0; j!=model_params.get_total_params(); ++j) {
values[i][j] = model_params.get(j);
}
}
// printf("Size of values = %d\n",values.size());
double reporting_rate = 1.0;
if (model_params.param_exists("reporting")) {
reporting_rate = model_params.get("reporting");
}
std::vector <std::string> param_names = model_params.get_names_vector();
std::vector <std::vector<std::string> > param_names_threads (options.num_threads);
if (model_params.param_exists("time_before_data")) {
add_dt = model_params.get("time_before_data");
}
if (options.save_traj) {
if (add_dt > 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
}
else if (add_dt < 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every);
}
else {
particles.start_particle_tracing(total_dt, num_groups);
}
}
std::vector <Model> models;
for (int i=0; i<options.num_threads; ++i) {
models.push_back(sim_model);
}
std::vector <int> add_dt_threads (options.num_threads, add_dt);
std::vector <int> start_dt_threads (options.num_threads, 0);
std::vector <int> end_dt_threads (options.num_threads, add_dt);
std::vector <double> dt_threads (options.num_threads, sim_dt);
std::vector <int> total_dt_threads(options.num_threads, total_dt);
std::vector <double> reporting_rate_threads(options.num_threads, reporting_rate);
std::vector <int> num_groups_threads(options.num_threads, num_groups);
// Simulate model and calculate likelihood assuming no observed data
if (model_params.param_exists("time_before_data")) {
if (add_dt > 0) {
omp_set_num_threads(options.num_threads);
// std::vector <Trajectory *> curr_trajs;
// for (int i=0; i!=num_particles; ++i) {
// curr_trajs.push_back(particles.get_traj(i));
// }
#pragma omp parallel for shared(particles, values) schedule(static,1)
for (int tn = 0; tn < thread_max; tn++) {
for (int i = tn; i < num_particles; i += thread_max) {
// Adjust length of trajectory
particles.get_traj(i)->resize(add_dt, num_groups);
models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), 0, add_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], rngs[tn]);
if (options.which_likelihood < 2) {
double w = likelihood_calc.binomial_lik(reporting_rate_threads[tn], particles.get_traj(i)->get_total_traj(), add_dt_threads[tn] + total_dt_threads[tn], 0, add_dt_threads[tn], num_groups_threads[tn], false);
particles.set_weight(w, i, false);
}
if (options.save_traj) {
particles.save_traj_to_matrix(i, 0, add_dt);
particles.save_ancestry(i, 0, add_dt);
}
}
}
}
}
init_seed += num_particles;
int t=0;
int start_dt;
int end_dt;
for (t = 0; t != total_steps; ++t) {
// std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0);
start_dt = t*options.pfilter_every;
end_dt = std::min(total_dt, (t + 1)*options.pfilter_every);
std::fill(start_dt_threads.begin(), start_dt_threads.end(), start_dt);
std::fill(end_dt_threads.begin(), end_dt_threads.end(), end_dt);
omp_set_num_threads(options.num_threads);
#pragma omp parallel for shared (particles, values) schedule(static,1)
for (int tn = 0; tn < thread_max; tn++) {
for (int i = tn; i < num_particles; i+=thread_max) {
// Adjust length of trajectory
// if (tn==0) std::cout << i << ' ' << std::endl;
particles.get_traj(i)->resize(end_dt - start_dt, options.num_groups);
models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), start_dt_threads[tn], end_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], rngs[tn]);
double w = 1.0;
double temp = 0.0;
if (options.which_likelihood < 2) {
double A = particles.get_traj(i)->get_total_traj();
temp = likelihood_calc.binomial_lik(reporting_rate_threads[tn], A, epi_data.get_data_ptr(0), add_dt_threads[tn] + total_dt_threads[tn], start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], num_groups_threads[tn], false);
w *= temp;
// we[i] = log(temp);
}
if (options.which_likelihood != 1) {
temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(0, 0), particles.get_traj(i)->get_traj_ptr(1, 0),
tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0),
start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], false);
w *= temp;
// wg[i] = log(temp);
}
particles.set_weight(w, i, true);
if (options.save_traj) {
particles.save_traj_to_matrix(i, start_dt_threads[tn] + add_dt_threads[tn], end_dt_threads[tn] + add_dt_threads[tn]);
particles.save_ancestry(i, start_dt_threads[tn] + add_dt_threads[tn], end_dt_threads[tn] + add_dt_threads[tn]);
}
}
}
// std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl;
double curr_ESS = particles.get_ESS();
if (curr_ESS < ESS_threshold) {
double total_weight = particles.get_total_weight();
if (total_weight == 0.0) {
loglik += -0.1*std::numeric_limits<double>::max();
// std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl;
std::cout << "stop time: " << end_dt << std::endl;
break;
} else {
loglik += log(total_weight) - log(num_particles);
}
particles.resample(options.rng[0]);
}
else {
particles.reset_parents();
}
}
if (options.save_traj) {
output_traj.resize((total_dt+add_dt), num_groups);
//if (loglik > -0.1*std::numeric_limits<double>::max()) {
particles.retrace_traj(output_traj, options.rng[0]);
//}
}
for (int i=0; i!=num_particles; ++i) {
particles.get_traj(i)->reset();
}
std::vector < std::vector<double> >().swap(values);
for (int thread = 0; thread < thread_max; thread++) {
gsl_rng_free(rngs[thread]);
}
delete[] rngs;
return (loglik);
}
}
<|endoftext|>
|
<commit_before>/*
* File: main.cpp
* Author: vlad
*
* Created on December 12, 2013, 10:38 PM
*/
#include <iostream>
#include "qpp.h"
#include "internal.h"
//#include "matlab.h" // support for MATLAB
// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping
// TODO: optimize syspermute: column major ordering + ?Eigen::Map?
// TODO: Rewrite partial trace without syspermute IMPORTANT!!!!
// TODO: check agains zero-size matrices (i.e. non-initialized)
// TODO: logic_error / runtime_error
using namespace std;
using namespace qpp;
using namespace qpp::types;
//int main(int argc, char **argv)
int main()
{
cout << "Starting qpp..." << endl;
_init();
// Display formatting
cout << std::fixed; // use fixed format for nice formatting
// cout << std::scientific;
cout << std::setprecision(4); // only for fixed or scientific modes
// statistics tests
cout << endl << "Statistics tests." << endl;
std::vector<cplx> ampl = { 1. + ct::ii, 1. - ct::ii };
cmat va(1, 3);
va << 1, 1. + ct::ii, 1. + 2. * ct::ii;
stat::DiscreteDistributionFromComplex dc(va);
cout << "The probabilities are: [";
internal::_disp_container(dc.probabilities());
cout << "]" << endl;
// other tests
size_t n = 12; // number of qubits
size_t N = std::pow(2, n);
vector<size_t> dims; // local dimensions
for (size_t i = 0; i < n; i++)
dims.push_back(2);
cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "."
<< endl;
// TIMING
Timer t, total; // start the timer, automatic tic() in the constructor
// Matrix initialization
cout << endl << "Matrix initialization timing." << endl;
cmat randcmat = cmat::Random(N, N);
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// Lazy matrix product
cout << endl << "Lazy matrix product timing." << endl;
auto b = randcmat * randcmat;
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// Matrix product
cout << endl << "Matrix product timing." << endl;
t.tic(); // reset the chronometer
cmat prodmat;
prodmat = randcmat * randcmat; // need this (otherwise lazy evaluation)
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// ptrace2 timing
cout << endl << "ptrace2 timing." << endl;
t.tic(); // reset the chronometer
// trace away half of the qubits
ptrace2(randcmat, { (size_t) std::sqrt(N), (size_t) std::sqrt(N) });
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// ptrace SLOW SLOW SLOW (because of syspermute, do it without)
cout << endl << "ptrace timing." << endl;
vector<size_t> subsys_ptrace = { 0 }; // trace away the first qubit
cout << "Subsytem(s): [";
internal::_disp_container(subsys_ptrace);
cout << "]" << endl;
t.tic();
ptrace(randcmat, subsys_ptrace, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
// ptranspose
cout << endl << "ptranspose timing." << endl;
vector<size_t> subsys_ptranspose; // partially transpose all subsystems
for (size_t i = 0; i < n; i++)
subsys_ptranspose.push_back(i);
cout << "Subsytem(s): [";
internal::_disp_container(subsys_ptranspose);
cout << "]" << endl;
t.tic();
ptranspose(randcmat, subsys_ptranspose, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
// syspermute SLOW SLOW SLOW
cout << endl << "syspermute timing." << endl;
vector<size_t> perm; // left-shift all subsystems by 1
for (size_t i = 0; i < n; i++)
perm.push_back((i + 1) % n);
cout << "Subsytem(s): [";
internal::_disp_container(perm);
cout << "]" << endl;
t.tic();
syspermute(randcmat, perm, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
total.toc(); // read the total running time
cout << endl << "Total time: " << total.seconds() << " seconds." << endl;
// END TIMING
cout << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
* File: main.cpp
* Author: vlad
*
* Created on December 12, 2013, 10:38 PM
*/
#include <iostream>
#include "qpp.h"
#include "internal.h"
//#include "matlab.h" // support for MATLAB
// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping
// TODO: optimize syspermute: column major ordering + ?Eigen::Map?
// TODO: Rewrite partial trace without syspermute IMPORTANT!!!!
// TODO: check agains zero-size matrices (i.e. non-initialized)
using namespace std;
using namespace qpp;
using namespace qpp::types;
//int main(int argc, char **argv)
int main()
{
cout << "Starting qpp..." << endl;
_init();
// Display formatting
cout << std::fixed; // use fixed format for nice formatting
// cout << std::scientific;
cout << std::setprecision(4); // only for fixed or scientific modes
// statistics tests
cout << endl << "Statistics tests." << endl;
std::vector<cplx> ampl = { 1. + ct::ii, 1. - ct::ii };
cmat va(1, 3);
va << 1, 1. + ct::ii, 1. + 2. * ct::ii;
stat::DiscreteDistributionFromComplex dc(va);
cout << "The probabilities are: [";
internal::_disp_container(dc.probabilities());
cout << "]" << endl;
// other tests
size_t n = 12; // number of qubits
size_t N = std::pow(2, n);
vector<size_t> dims; // local dimensions
for (size_t i = 0; i < n; i++)
dims.push_back(2);
cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "."
<< endl;
// TIMING
Timer t, total; // start the timer, automatic tic() in the constructor
// Matrix initialization
cout << endl << "Matrix initialization timing." << endl;
cmat randcmat = cmat::Random(N, N);
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// Lazy matrix product
cout << endl << "Lazy matrix product timing." << endl;
auto b = randcmat * randcmat;
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// Matrix product
cout << endl << "Matrix product timing." << endl;
t.tic(); // reset the chronometer
cmat prodmat;
prodmat = randcmat * randcmat; // need this (otherwise lazy evaluation)
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// ptrace2 timing
cout << endl << "ptrace2 timing." << endl;
t.tic(); // reset the chronometer
// trace away half of the qubits
ptrace2(randcmat, { (size_t) std::sqrt(N), (size_t) std::sqrt(N) });
t.toc(); // read the time
cout << "Took " << t << " seconds." << endl;
// ptrace SLOW SLOW SLOW (because of syspermute, do it without)
cout << endl << "ptrace timing." << endl;
vector<size_t> subsys_ptrace = { 0 }; // trace away the first qubit
cout << "Subsytem(s): [";
internal::_disp_container(subsys_ptrace);
cout << "]" << endl;
t.tic();
ptrace(randcmat, subsys_ptrace, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
// ptranspose
cout << endl << "ptranspose timing." << endl;
vector<size_t> subsys_ptranspose; // partially transpose all subsystems
for (size_t i = 0; i < n; i++)
subsys_ptranspose.push_back(i);
cout << "Subsytem(s): [";
internal::_disp_container(subsys_ptranspose);
cout << "]" << endl;
t.tic();
ptranspose(randcmat, subsys_ptranspose, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
// syspermute SLOW SLOW SLOW
cout << endl << "syspermute timing." << endl;
vector<size_t> perm; // left-shift all subsystems by 1
for (size_t i = 0; i < n; i++)
perm.push_back((i + 1) % n);
cout << "Subsytem(s): [";
internal::_disp_container(perm);
cout << "]" << endl;
t.tic();
syspermute(randcmat, perm, dims);
t.toc();
cout << "Took " << t << " seconds." << endl;
total.toc(); // read the total running time
cout << endl << "Total time: " << total.seconds() << " seconds." << endl;
// END TIMING
cout << "Exiting qpp..." << endl;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2014 Toshiaki Takada
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <iostream>
#include <iomanip>
#include <readline/readline.h>
#include <readline/history.h>
#include "project.hpp"
#include "cli_tree.hpp"
#include "cli_readline.hpp"
#include "cli.hpp"
const boost::regex CliReadline::re_white_space("^([[:space:]]*)");
const boost::regex CliReadline::re_white_space_only("^([[:space:]]*)$");
const boost::regex CliReadline::re_command_string("^[^[:space:]]+");
bool
CliNodeMatchStateCriterion(CliNodeMatchStatePair n, CliNodeMatchStatePair m)
{
return n.second < m.second;
}
size_t
CliReadline::match_token(string& input, CliNode *curr,
CliNodeMatchStateVector& state_vec)
{
CliNode *next;
CliNodeMatchStateVector matched_vec;
for (CliNodeVector::iterator it = curr->next_.begin();
it != curr->next_.end(); ++it)
{
next = (*it);
MatchState state;
state = next->cli_match(input);
if (state != match_none)
{
CliNodeMatchStatePair p = make_pair(next, state);
matched_vec.push_back(p);
}
}
// Sort by type of match.
if (matched_vec.size() > 1)
sort(matched_vec.begin(), matched_vec.end(), CliNodeMatchStateCriterion);
state_vec = matched_vec;
return matched_vec.size();
}
bool
CliReadline::get_token(string& str, string& token)
{
boost::smatch m;
if (boost::regex_search(str, m, re_command_string))
{
token = m[0];
str = m.suffix();
return true;
}
return false;
}
bool
CliReadline::skip_spaces(string& str)
{
boost::smatch m;
if (boost::regex_search(str, m, re_white_space))
{
str = m.suffix();
return true;
}
return false;
}
void
CliReadline::fill_matched_vec(CliNode *node,
CliNodeMatchStateVector& matched_vec)
{
for (CliNodeVector::iterator it = node->next_.begin();
it != node->next_.end(); ++it)
{
MatchState state = match_partial;
CliNodeMatchStatePair p = make_pair(*it, state);
matched_vec.push_back(p);
}
}
void
CliReadline::filter_matched(CliNodeMatchStateVector& matched_vec)
{
CliNodeMatchStateVector vec;
MatchState state;
if (matched_vec.size() <= 1)
return;
state = matched_vec[0].second;
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); )
{
if (it->second != state)
it = matched_vec.erase(it);
else
++it;
}
}
// Return true if command can be completed.
bool
CliReadline::parse(string& line, CliNode *curr,
CliNodeMatchStateVector& matched_vec)
{
boost::smatch m;
string token;
// bool is_cmd = false;
matched_vec.clear();
if (!skip_spaces(line))
return curr->cmd_;
fill_matched_vec(curr, matched_vec);
if (!get_token(line, token))
return curr->cmd_;
match_token(token, curr, matched_vec);
if (line.begin() != line.end())
{
filter_matched(matched_vec);
if (matched_vec.size() == 1)
return parse(line, matched_vec[0].first, matched_vec);
}
if (matched_vec.size() == 1)
curr = matched_vec[0].first;
return curr->cmd_;
}
void
CliReadline::describe_line(CliNode *node, size_t max_len_token)
{
size_t max_len_help;
const char *cli_token = node->cli_token();
string help(node->help());
string substr;
// No enough space to show help, just print without folding.
if (cli_->ws_.ws_col < max_len_token + 5)
{
cout << " " << left << setw(max_len_token + 2)
<< cli_token << node->help() << endl;
return;
}
max_len_help = cli_->ws_.ws_col - (max_len_token + 5);
while (help.size() > max_len_help)
{
const char *s = help.c_str();
const char *p = s + max_len_help;
while (*p != ' ' && p != s)
p--;
if (p == s)
break;
size_t length = (size_t)(p - s);
substr = help.substr(0, length);
cout << " " << left << setw(max_len_token + 2)
<< cli_token << substr << endl;
help = help.substr(length + 1);
cli_token = " ";
}
cout << " " << left << setw(max_len_token + 2)
<< cli_token << help << endl;
}
int
CliReadline::describe()
{
// current mode.
CliTree *tree = cli_->current_mode();
CliNode *candidate;
CliNodeMatchStateVector matched_vec;
string line(" ");
bool is_cmd = false;
line += rl_line_buffer;
cout << "?" << endl;
is_cmd = parse(line, tree->top_, matched_vec);
if (!is_cmd && matched_vec.size() == 0)
{
cout << "% Unrecognized command" << endl << endl;
}
else
{
size_t max_len = 0;
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
{
candidate = it->first;
size_t len = strlen(candidate->cli_token());
if (max_len < len)
max_len = len;
}
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
describe_line(it->first, max_len);
if (is_cmd)
cout << " <cr>" << endl;
}
cout << cli_->prompt();
cout << rl_line_buffer;
return 0;
}
int
readline_describe(int, int)
{
return Cli::readline().describe();
}
static char *
readline_completion_dummy(const char *, int)
{
return NULL;
}
char *
CliReadline::completion_matches(const char *text, int state)
{
CliTree *tree = cli_->current_mode();
CliNodeMatchStateVector matched_vec;
string line(" ");
line += rl_line_buffer;
// No input.
if (rl_end == 0)
{
cout << endl << endl;
cout << cli_->prompt();
return NULL;
}
if (state == 0)
{
matched_strvec_ = NULL;
matched_index_ = 0;
parse(line, tree->top_, matched_vec);
if (matched_vec.size() == 0)
{
cout << endl;
cout << "% Unrecognized command" << endl << endl;
cout << cli_->prompt();
cout << rl_line_buffer;
}
else
{
int i = 0;
matched_strvec_ =
(char **)calloc(matched_vec.size() + 1, sizeof(char *));
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
{
CliNode *node = it->first;
if (node->type_ == CliTree::keyword)
matched_strvec_[i++] = strdup(node->cli_token());
}
}
}
if (matched_strvec_ && matched_strvec_[matched_index_])
return matched_strvec_[matched_index_++];
return NULL;
}
char *
readline_completion_matches(const char *text, int state)
{
return Cli::readline().completion_matches(text, state);
}
char **
CliReadline::completion(const char *text, int start, int end)
{
return rl_completion_matches(text, readline_completion_matches);
}
char **
readline_completion(const char *text, int start, int end)
{
return Cli::readline().completion(text, start, end);
}
void
CliReadline::init(Cli *cli)
{
cli_ = cli;
rl_bind_key('?', readline_describe);
rl_completion_entry_function = readline_completion_dummy;
rl_attempted_completion_function = readline_completion;
rl_completion_append_character = '\0';
}
char *
CliReadline::gets()
{
// Clear readline read buffer first.
if (buf_)
{
free(buf_);
buf_ = NULL;
}
// Read a line.
buf_ = readline(cli_->prompt());
// Add history.
if (buf_ && buf_[0] != '\0')
add_history(buf_);
return buf_;
}
bool
CliReadline::execute()
{
// current mode.
CliTree *tree = cli_->current_mode();
CliNodeMatchStateVector matched_vec;
string line(" ");
bool is_cmd = false;
boost::smatch m;
line += rl_line_buffer;
if (!boost::regex_search(line, m, re_white_space_only))
{
is_cmd = parse(line, tree->top_, matched_vec);
if (!is_cmd)
{
if (matched_vec.size() == 0)
cout << "% Unrecognized command" << endl << endl;
else if (matched_vec.size() > 1)
cout << "% Ambiguous command" << endl << endl;
else
cout << "% Incomplete command" << endl << endl;
}
else
{
CliNode *node = matched_vec[0].first;
if (node->next_mode_.size() != 0)
{
cli_->mode_set(node->next_mode_);
cout << "next mode " << node->next_mode_ << endl;
}
cout << "command: " << node->def_token_ << endl;
}
}
return true;
}
<commit_msg>Fix completion/describe and execution. And now it looks almost complete.<commit_after>//
// Copyright (c) 2014 Toshiaki Takada
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <iostream>
#include <iomanip>
#include <readline/readline.h>
#include <readline/history.h>
#include "project.hpp"
#include "cli_tree.hpp"
#include "cli_readline.hpp"
#include "cli.hpp"
const boost::regex CliReadline::re_white_space("^([[:space:]]*)");
const boost::regex CliReadline::re_white_space_only("^([[:space:]]*)$");
const boost::regex CliReadline::re_command_string("^[^[:space:]]+");
bool
CliNodeMatchStateCriterion(CliNodeMatchStatePair n, CliNodeMatchStatePair m)
{
return n.second < m.second;
}
size_t
CliReadline::match_token(string& input, CliNode *curr,
CliNodeMatchStateVector& state_vec)
{
CliNode *next;
CliNodeMatchStateVector matched_vec;
for (CliNodeVector::iterator it = curr->next_.begin();
it != curr->next_.end(); ++it)
{
next = (*it);
MatchState state;
state = next->cli_match(input);
if (state != match_none)
{
CliNodeMatchStatePair p = make_pair(next, state);
matched_vec.push_back(p);
}
}
// Sort by type of match.
if (matched_vec.size() > 1)
sort(matched_vec.begin(), matched_vec.end(), CliNodeMatchStateCriterion);
state_vec = matched_vec;
return matched_vec.size();
}
bool
CliReadline::get_token(string& str, string& token)
{
boost::smatch m;
if (boost::regex_search(str, m, re_command_string))
{
token = m[0];
str = m.suffix();
return true;
}
return false;
}
bool
CliReadline::skip_spaces(string& str)
{
boost::smatch m;
if (boost::regex_search(str, m, re_white_space))
{
str = m.suffix();
return true;
}
return false;
}
void
CliReadline::fill_matched_vec(CliNode *node,
CliNodeMatchStateVector& matched_vec)
{
for (CliNodeVector::iterator it = node->next_.begin();
it != node->next_.end(); ++it)
{
MatchState state = match_partial;
CliNodeMatchStatePair p = make_pair(*it, state);
matched_vec.push_back(p);
}
}
void
CliReadline::filter_matched(CliNodeMatchStateVector& matched_vec)
{
CliNodeMatchStateVector vec;
MatchState state;
if (matched_vec.size() <= 1)
return;
state = matched_vec[0].second;
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); )
{
if (it->second != state)
it = matched_vec.erase(it);
else
++it;
}
}
// Return true if command can be completed.
bool
CliReadline::parse(string& line, CliNode *curr,
CliNodeMatchStateVector& matched_vec)
{
boost::smatch m;
string token;
// bool is_cmd = false;
matched_vec.clear();
if (!skip_spaces(line))
return curr->cmd_;
fill_matched_vec(curr, matched_vec);
if (!get_token(line, token))
return curr->cmd_;
match_token(token, curr, matched_vec);
if (line.begin() != line.end())
{
filter_matched(matched_vec);
if (matched_vec.size() == 1)
return parse(line, matched_vec[0].first, matched_vec);
}
if (matched_vec.size() == 1)
curr = matched_vec[0].first;
return curr->cmd_;
}
void
CliReadline::describe_line(CliNode *node, size_t max_len_token)
{
size_t max_len_help;
const char *cli_token = node->cli_token();
string help(node->help());
string substr;
// No enough space to show help, just print without folding.
if (cli_->ws_.ws_col < max_len_token + 5)
{
cout << " " << left << setw(max_len_token + 2)
<< cli_token << node->help() << endl;
return;
}
max_len_help = cli_->ws_.ws_col - (max_len_token + 5);
while (help.size() > max_len_help)
{
const char *s = help.c_str();
const char *p = s + max_len_help;
while (*p != ' ' && p != s)
p--;
if (p == s)
break;
size_t length = (size_t)(p - s);
substr = help.substr(0, length);
cout << " " << left << setw(max_len_token + 2)
<< cli_token << substr << endl;
help = help.substr(length + 1);
cli_token = " ";
}
cout << " " << left << setw(max_len_token + 2)
<< cli_token << help << endl;
}
int
CliReadline::describe()
{
// current mode.
CliTree *tree = cli_->current_mode();
CliNode *candidate;
CliNodeMatchStateVector matched_vec;
string line(" ");
bool is_cmd = false;
line += rl_line_buffer;
cout << "?" << endl;
is_cmd = parse(line, tree->top_, matched_vec);
if (!is_cmd && matched_vec.size() == 0)
{
cout << "% Unrecognized command" << endl << endl;
}
else
{
size_t max_len = 0;
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
{
candidate = it->first;
size_t len = strlen(candidate->cli_token());
if (max_len < len)
max_len = len;
}
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
describe_line(it->first, max_len);
if (is_cmd)
cout << " <cr>" << endl;
}
cout << cli_->prompt();
cout << rl_line_buffer;
return 0;
}
int
readline_describe(int, int)
{
return Cli::readline().describe();
}
static char *
readline_completion_dummy(const char *, int)
{
return NULL;
}
char *
CliReadline::completion_matches(const char *text, int state)
{
CliTree *tree = cli_->current_mode();
CliNodeMatchStateVector matched_vec;
string line(" ");
bool is_cmd = false;
line += rl_line_buffer;
// No input.
if (rl_end == 0)
{
cout << endl << endl;
cout << cli_->prompt();
return NULL;
}
if (state == 0)
{
matched_strvec_ = NULL;
matched_index_ = 0;
is_cmd = parse(line, tree->top_, matched_vec);
if (matched_vec.size() == 0)
{
cout << endl;
if (!is_cmd)
cout << "% Unrecognized command" << endl << endl;
cout << cli_->prompt();
cout << rl_line_buffer;
}
else
{
int i = 0;
matched_strvec_ =
(char **)calloc(matched_vec.size() + 1, sizeof(char *));
for (CliNodeMatchStateVector::iterator it = matched_vec.begin();
it != matched_vec.end(); ++it)
{
CliNode *node = it->first;
if (node->type_ == CliTree::keyword)
matched_strvec_[i++] = strdup(node->cli_token());
}
}
}
if (matched_strvec_ && matched_strvec_[matched_index_])
return matched_strvec_[matched_index_++];
return NULL;
}
char *
readline_completion_matches(const char *text, int state)
{
return Cli::readline().completion_matches(text, state);
}
char **
CliReadline::completion(const char *text, int start, int end)
{
return rl_completion_matches(text, readline_completion_matches);
}
char **
readline_completion(const char *text, int start, int end)
{
return Cli::readline().completion(text, start, end);
}
void
CliReadline::init(Cli *cli)
{
cli_ = cli;
rl_bind_key('?', readline_describe);
rl_completion_entry_function = readline_completion_dummy;
rl_attempted_completion_function = readline_completion;
rl_completion_append_character = '\0';
}
char *
CliReadline::gets()
{
// Clear readline read buffer first.
if (buf_)
{
free(buf_);
buf_ = NULL;
}
// Read a line.
buf_ = readline(cli_->prompt());
// Add history.
if (buf_ && buf_[0] != '\0')
add_history(buf_);
return buf_;
}
bool
CliReadline::execute()
{
// current mode.
CliTree *tree = cli_->current_mode();
CliNodeMatchStateVector matched_vec;
string line(" ");
bool is_cmd = false;
boost::smatch m;
line += rl_line_buffer;
if (!boost::regex_search(line, m, re_white_space_only))
{
is_cmd = parse(line, tree->top_, matched_vec);
filter_matched(matched_vec);
if (matched_vec.size() == 1)
is_cmd = matched_vec[0].first->cmd_;
if (!is_cmd)
{
if (matched_vec.size() == 0)
cout << "% Unrecognized command" << endl << endl;
else if (matched_vec.size() > 1)
cout << "% Ambiguous command" << endl << endl;
else
cout << "% Incomplete command" << endl << endl;
}
else
{
CliNode *node = matched_vec[0].first;
if (node->next_mode_.size() != 0)
{
cli_->mode_set(node->next_mode_);
cout << "next mode " << node->next_mode_ << endl;
}
cout << "command: " << node->def_token_ << endl;
}
}
return true;
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
}
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, CommaSeparated);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
boost::timer::auto_cpu_timer t;
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations]();
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
#pragma omp parallel default(shared)
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
int *localHistogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
++localHistogram[currentSystem->endingBitString];
}
delete [] localHistogram;
gsl_rng_free(localRNG);
}//End parallel
for(int k=0; k<first_pass_iterations; k++) {
histogram[systems[k].endingBitString]++;
}
delete [] systems;
//time_t stop_time = time(NULL);
//std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
delete [] histogram;
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//Make sure we don't accidentally share a seed.
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
gsl_rng_free(localRNG);
}
delete [] p_prime;
delete [] p;
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
<commit_msg>Set maximum number of threads.<commit_after>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
}
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
omp_set_num_threads(8);
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, CommaSeparated);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
boost::timer::auto_cpu_timer t;
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations]();
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
#pragma omp parallel default(shared)
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
int *localHistogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
++localHistogram[currentSystem->endingBitString];
}
delete [] localHistogram;
gsl_rng_free(localRNG);
}//End parallel
for(int k=0; k<first_pass_iterations; k++) {
histogram[systems[k].endingBitString]++;
}
delete [] systems;
//time_t stop_time = time(NULL);
//std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
delete [] histogram;
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//Make sure we don't accidentally share a seed.
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
gsl_rng_free(localRNG);
}
delete [] p_prime;
delete [] p;
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
<|endoftext|>
|
<commit_before>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace opencc {
/**
* A class that wraps type T into a nullable type.
*/
template<typename T>
class Optional {
public:
/**
* The constructor of Optional.
*/
Optional(T actual) : isNull(false), data(actual) {
}
/**
* Returns true if the instance is null.
*/
bool IsNull() const {
return isNull;
}
/**
* Returns the containing data of the instance.
*/
const T& Get() const {
return data;
}
/**
* Constructs a null instance.
*/
static Optional<T> Null() {
return Optional();
}
private:
Optional() : isNull(true) {
}
bool isNull;
T data;
};
}
<commit_msg>Implement template specialization for Optional<T*><commit_after>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace opencc {
/**
* A class that wraps type T into a nullable type.
*/
template<typename T>
class Optional {
public:
/**
* The constructor of Optional.
*/
Optional(T actual) : isNull(false), data(actual) {
}
/**
* Returns true if the instance is null.
*/
bool IsNull() const {
return isNull;
}
/**
* Returns the containing data of the instance.
*/
const T& Get() const {
return data;
}
/**
* Constructs a null instance.
*/
static Optional<T> Null() {
return Optional();
}
private:
Optional() : isNull(true) {
}
bool isNull;
T data;
};
template<typename T>
class Optional<T*> {
private:
Optional() : data(nullptr) {
}
typedef T* TPtr;
TPtr data;
public:
Optional(TPtr actual) : data(actual) {
}
bool IsNull() const {
return data == nullptr;
}
const TPtr& Get() const {
return data;
}
static Optional<TPtr> Null() {
return Optional();
}
};
}<|endoftext|>
|
<commit_before>#include "consoletools.h"
#include "client.h"
#include "log/logger.h"
#include "settings.h"
#include "controller/logincontroller.h"
#include "controller/taskcontroller.h"
#include "controller/configcontroller.h"
#include "types.h"
#include "webrequester.h"
#include "network/requests/registerdevicerequest.h"
#include "network/responses/registerdeviceresponse.h"
#include "log/filelogger.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QTimer>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <unistd.h>
#include <errno.h>
#endif // Q_OS_UNIX
LOGGER(main);
struct LoginData
{
enum Type
{
AnonymousRegister,
Register,
Login
};
Type type;
QString userId;
QString password;
};
class DeviceRegistrationWatcher : public QObject
{
Q_OBJECT
public:
DeviceRegistrationWatcher(LoginController *controller)
: m_controller(controller)
{
connect(controller, SIGNAL(finished()), this, SLOT(onLoginOrRegistrationFinished()));
connect(&m_requester, SIGNAL(statusChanged(WebRequester::Status)), this, SLOT(onStatusChanged(WebRequester::Status)));
m_requester.setRequest(&m_request);
m_requester.setResponse(&m_response);
}
private slots:
void onLoginOrRegistrationFinished()
{
// Already registered?
if (m_controller->registeredDevice())
{
return;
}
LOG_INFO("Automatically registering device");
m_requester.setUrl(QString("https://%1").arg(Client::instance()->settings()->config()->supervisorAddress()));
m_requester.start();
}
void onStatusChanged(WebRequester::Status status)
{
switch (status)
{
case WebRequester::Error:
LOG_DEBUG(QString("Device registration failed, quitting. (%1)").arg(m_requester.errorString()));
qApp->quit();
break;
case WebRequester::Finished:
LOG_INFO("Device successfully registered");
Client::instance()->taskController()->fetchTasks();
break;
default:
break;
}
}
protected:
LoginController *m_controller;
WebRequester m_requester;
RegisterDeviceRequest m_request;
RegisterDeviceResponse m_response;
};
class LoginWatcher : public QObject
{
Q_OBJECT
public:
LoginWatcher(LoginController *controller)
: m_controller(controller)
{
connect(controller, SIGNAL(statusChanged()), this, SLOT(onStatusChanged()));
}
private slots:
void onStatusChanged()
{
switch (m_controller->status())
{
case LoginController::Error:
LOG_ERROR("Login/Registration failed, quitting.");
qApp->quit();
break;
case LoginController::Finished:
LOG_INFO("Login successful");
deleteLater();
break;
default:
break;
}
}
protected:
LoginController *m_controller;
};
class ConfigWatcher : public QObject
{
Q_OBJECT
public:
ConfigWatcher(Client *client, LoginData loginData)
: m_client(client)
, m_loginData(loginData)
{
connect(m_client->configController(), SIGNAL(finished()), this, SLOT(onStatusChanged()));
}
private slots:
void onStatusChanged()
{
switch (m_client->configController()->status())
{
case ConfigController::Error:
LOG_ERROR("Getting config failed, quitting.");
qApp->quit();
break;
case ConfigController::Finished:
LOG_DEBUG("Getting config successful");
deleteLater();
if (!m_loginData.password.isEmpty())
{
switch (m_loginData.type)
{
case LoginData::Register:
m_client->loginController()->registration(m_loginData.userId, m_loginData.password);
break;
case LoginData::Login:
m_client->settings()->setUserId(m_loginData.userId);
m_client->settings()->setPassword(m_loginData.password);
m_client->loginController()->login();
break;
default:
break;
}
}
else if (m_loginData.type == LoginData::AnonymousRegister)
{
m_client->loginController()->anonymousRegistration();
}
else
{
if (!m_client->autoLogin())
{
LOG_ERROR("No login data found for autologin");
qApp->quit();
}
}
break;
default:
break;
}
}
protected:
Client *m_client;
LoginData m_loginData;
};
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik");
QCoreApplication::setOrganizationName("HS-Augsburg");
QCoreApplication::setApplicationName("mPlaneClient");
QCoreApplication::setApplicationVersion(Client::version());
QCoreApplication app(argc, argv);
Logger::addAppender(new FileLogger);
QTextStream out(stdout);
QCommandLineParser parser;
parser.setApplicationDescription("GLIMPSE console client\r\nWebsite: http://www.measure-it.net\r\nCopyright: Revised BSD License");
parser.addHelpOption();
parser.addVersionOption();
#ifdef Q_OS_UNIX
QCommandLineOption userOption("user", "Run as user", "user");
parser.addOption(userOption);
//QCommandLineOption groupOption("group", "Run as group", "group");
//parser.addOption(groupOption);
QCommandLineOption daemonOption("daemon", "Run as daemon");
parser.addOption(daemonOption);
//QCommandLineOption pidFileOption("pidfile", "Set the pidfile", "path");
//parser.addOption(pidFileOption);
#endif // Q_OS_UNIX
QCommandLineOption registerAnonymous("register-anonymous", "Register anonymous on server");
parser.addOption(registerAnonymous);
QCommandLineOption registerOption("register", "Register on server", "mail");
parser.addOption(registerOption);
QCommandLineOption loginOption("login", "Login on server", "mail");
parser.addOption(loginOption);
QCommandLineOption passiveOption("passive", "Passive probe which does not receive tasks", "0/1");
parser.addOption(passiveOption);
QCommandLineOption trafficOption("traffic", "Traffic limit per month (0 to deactivate traffic limit)", "MB");
parser.addOption(trafficOption);
parser.process(app);
if (parser.isSet(registerOption) && parser.isSet(registerAnonymous))
{
out << "'--register' and '--register-anonymous' cannot be set on the same time.\n";
return 1;
}
if ((parser.isSet(registerAnonymous) || parser.isSet(registerOption)) && parser.isSet(loginOption))
{
out << "'--register(-anonymous)' and '--login' cannot be set on the same time.\n";
return 1;
}
QCommandLineOption *passwordOption = NULL;
LoginData loginData;
if (parser.isSet(registerOption))
{
loginData.type = LoginData::Register;
passwordOption = ®isterOption;
loginData.userId = parser.value(*passwordOption).toUtf8();
}
if (parser.isSet(loginOption))
{
loginData.type = LoginData::Login;
passwordOption = &loginOption;
loginData.userId = parser.value(*passwordOption).toUtf8();
}
if (parser.isSet(registerAnonymous))
{
loginData.type = LoginData::AnonymousRegister;
}
if (passwordOption)
{
ConsoleTools tools;
do
{
out << '[' << argv[0] << ']' << " Password: ";
out.flush();
loginData.password = tools.readPassword();
}
while (loginData.password.isEmpty());
}
#ifdef Q_OS_UNIX
if (parser.isSet(userOption))
{
QByteArray user = parser.value(userOption).toLatin1();
passwd *pwd = getpwnam(user.constData());
if (pwd)
{
if (-1 == setuid(pwd->pw_uid))
{
out << "Cannot set uid to " << pwd->pw_uid << ": " << strerror(errno) << "\n";
return 1;
}
else
{
LOG_DEBUG(QString("User id set to %1 (%2)").arg(pwd->pw_uid).arg(QString::fromLatin1(user)));
}
}
else
{
out << "No user named " << QString::fromLatin1(user) << " found\n";
return 1;
}
}
// NOTE: This should be the last option since this creates a process fork!
if (parser.isSet(daemonOption))
{
pid_t pid = fork();
if (pid == -1)
{
out << "fork() failed: " << strerror(errno) << "\n";
}
else if (pid > 0)
{
// Fork successful, we're exiting now
out << "Daemon started with pid " << pid << "\n";
return 0;
}
else
{
// Child process
umask(0);
pid_t sid = setsid();
if (sid < 0)
{
return 1;
}
//chdir("/");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
}
#endif // Q_OS_UNIX
// If there may be anything left, we flush it before the client starts
out.flush();
// Initialize the client instance
Client *client = Client::instance();
LOG_INFO(QString("Glimpse version %1").arg(Client::version()));
if (parser.isSet(passiveOption))
{
int setPassive = parser.value(passiveOption).toInt();
client->settings()->setPassive((bool) setPassive);
}
if (parser.isSet(trafficOption))
{
int setTraffic = parser.value(trafficOption).toInt();
if (setTraffic != 0)
{
client->settings()->setAvailableTraffic(setTraffic * 1024 * 1024);
client->settings()->setAvailableMobileTraffic(setTraffic * 1024 * 1024);
client->settings()->setTrafficBudgetManagerActive(true);
}
else
{
client->settings()->setTrafficBudgetManagerActive(false);
}
}
if (!client->init())
{
LOG_ERROR("Client initialization failed")
return 1;
}
new LoginWatcher(client->loginController());
new DeviceRegistrationWatcher(client->loginController());
new ConfigWatcher(client, loginData);
int value = app.exec();
out << "Application shutting down.\n";
Client::instance()->deleteLater();
QTimer::singleShot(1, &app, SLOT(quit()));
app.exec();
return value;
}
#include "main.moc"
<commit_msg>exit after registration (features #290)<commit_after>#include "consoletools.h"
#include "client.h"
#include "log/logger.h"
#include "settings.h"
#include "controller/logincontroller.h"
#include "controller/taskcontroller.h"
#include "controller/configcontroller.h"
#include "types.h"
#include "webrequester.h"
#include "network/requests/registerdevicerequest.h"
#include "network/responses/registerdeviceresponse.h"
#include "log/filelogger.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QTimer>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <unistd.h>
#include <errno.h>
#endif // Q_OS_UNIX
LOGGER(main);
struct LoginData
{
enum Type
{
AnonymousRegister,
Register,
Login
};
Type type;
QString userId;
QString password;
};
class DeviceRegistrationWatcher : public QObject
{
Q_OBJECT
public:
DeviceRegistrationWatcher(LoginController *controller)
: m_controller(controller)
{
connect(controller, SIGNAL(finished()), this, SLOT(onLoginOrRegistrationFinished()));
connect(&m_requester, SIGNAL(statusChanged(WebRequester::Status)), this, SLOT(onStatusChanged(WebRequester::Status)));
m_requester.setRequest(&m_request);
m_requester.setResponse(&m_response);
}
private slots:
void onLoginOrRegistrationFinished()
{
// Already registered?
if (m_controller->registeredDevice())
{
return;
}
LOG_INFO("Automatically registering device");
m_requester.setUrl(QString("https://%1").arg(Client::instance()->settings()->config()->supervisorAddress()));
m_requester.start();
}
void onStatusChanged(WebRequester::Status status)
{
switch (status)
{
case WebRequester::Error:
LOG_DEBUG(QString("Device registration failed, quitting. (%1)").arg(m_requester.errorString()));
qApp->quit();
break;
case WebRequester::Finished:
LOG_INFO("Device successfully registered");
qApp->quit();
break;
default:
break;
}
}
protected:
LoginController *m_controller;
WebRequester m_requester;
RegisterDeviceRequest m_request;
RegisterDeviceResponse m_response;
};
class LoginWatcher : public QObject
{
Q_OBJECT
public:
LoginWatcher(LoginController *controller)
: m_controller(controller)
{
connect(controller, SIGNAL(statusChanged()), this, SLOT(onStatusChanged()));
}
private slots:
void onStatusChanged()
{
switch (m_controller->status())
{
case LoginController::Error:
LOG_ERROR("Login/Registration failed, quitting.");
qApp->quit();
break;
case LoginController::Finished:
LOG_INFO("Login successful");
deleteLater();
break;
default:
break;
}
}
protected:
LoginController *m_controller;
};
class ConfigWatcher : public QObject
{
Q_OBJECT
public:
ConfigWatcher(Client *client, LoginData loginData)
: m_client(client)
, m_loginData(loginData)
{
connect(m_client->configController(), SIGNAL(finished()), this, SLOT(onStatusChanged()));
}
private slots:
void onStatusChanged()
{
switch (m_client->configController()->status())
{
case ConfigController::Error:
LOG_ERROR("Getting config failed, quitting.");
qApp->quit();
break;
case ConfigController::Finished:
LOG_DEBUG("Getting config successful");
deleteLater();
if (!m_loginData.password.isEmpty())
{
switch (m_loginData.type)
{
case LoginData::Register:
m_client->loginController()->registration(m_loginData.userId, m_loginData.password);
break;
case LoginData::Login:
m_client->settings()->setUserId(m_loginData.userId);
m_client->settings()->setPassword(m_loginData.password);
m_client->loginController()->login();
break;
default:
break;
}
}
else if (m_loginData.type == LoginData::AnonymousRegister)
{
m_client->loginController()->anonymousRegistration();
}
else
{
if (!m_client->autoLogin())
{
LOG_ERROR("No login data found for autologin");
qApp->quit();
}
}
break;
default:
break;
}
}
protected:
Client *m_client;
LoginData m_loginData;
};
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik");
QCoreApplication::setOrganizationName("HS-Augsburg");
QCoreApplication::setApplicationName("mPlaneClient");
QCoreApplication::setApplicationVersion(Client::version());
QCoreApplication app(argc, argv);
Logger::addAppender(new FileLogger);
QTextStream out(stdout);
QCommandLineParser parser;
parser.setApplicationDescription("GLIMPSE console client\r\nWebsite: http://www.measure-it.net\r\nCopyright: Revised BSD License");
parser.addHelpOption();
parser.addVersionOption();
#ifdef Q_OS_UNIX
QCommandLineOption userOption("user", "Run as user", "user");
parser.addOption(userOption);
//QCommandLineOption groupOption("group", "Run as group", "group");
//parser.addOption(groupOption);
QCommandLineOption daemonOption("daemon", "Run as daemon");
parser.addOption(daemonOption);
//QCommandLineOption pidFileOption("pidfile", "Set the pidfile", "path");
//parser.addOption(pidFileOption);
#endif // Q_OS_UNIX
QCommandLineOption registerAnonymous("register-anonymous", "Register anonymous on server");
parser.addOption(registerAnonymous);
QCommandLineOption registerOption("register", "Register on server", "mail");
parser.addOption(registerOption);
QCommandLineOption loginOption("login", "Login on server", "mail");
parser.addOption(loginOption);
QCommandLineOption passiveOption("passive", "Passive probe which does not receive tasks", "0/1");
parser.addOption(passiveOption);
QCommandLineOption trafficOption("traffic", "Traffic limit per month (0 to deactivate traffic limit)", "MB");
parser.addOption(trafficOption);
parser.process(app);
if (parser.isSet(registerOption) && parser.isSet(registerAnonymous))
{
out << "'--register' and '--register-anonymous' cannot be set on the same time.\n";
return 1;
}
if ((parser.isSet(registerAnonymous) || parser.isSet(registerOption)) && parser.isSet(loginOption))
{
out << "'--register(-anonymous)' and '--login' cannot be set on the same time.\n";
return 1;
}
QCommandLineOption *passwordOption = NULL;
LoginData loginData;
if (parser.isSet(registerOption))
{
loginData.type = LoginData::Register;
passwordOption = ®isterOption;
loginData.userId = parser.value(*passwordOption).toUtf8();
}
if (parser.isSet(loginOption))
{
loginData.type = LoginData::Login;
passwordOption = &loginOption;
loginData.userId = parser.value(*passwordOption).toUtf8();
}
if (parser.isSet(registerAnonymous))
{
loginData.type = LoginData::AnonymousRegister;
}
if (passwordOption)
{
ConsoleTools tools;
do
{
out << '[' << argv[0] << ']' << " Password: ";
out.flush();
loginData.password = tools.readPassword();
}
while (loginData.password.isEmpty());
}
#ifdef Q_OS_UNIX
if (parser.isSet(userOption))
{
QByteArray user = parser.value(userOption).toLatin1();
passwd *pwd = getpwnam(user.constData());
if (pwd)
{
if (-1 == setuid(pwd->pw_uid))
{
out << "Cannot set uid to " << pwd->pw_uid << ": " << strerror(errno) << "\n";
return 1;
}
else
{
LOG_DEBUG(QString("User id set to %1 (%2)").arg(pwd->pw_uid).arg(QString::fromLatin1(user)));
}
}
else
{
out << "No user named " << QString::fromLatin1(user) << " found\n";
return 1;
}
}
// NOTE: This should be the last option since this creates a process fork!
if (parser.isSet(daemonOption))
{
pid_t pid = fork();
if (pid == -1)
{
out << "fork() failed: " << strerror(errno) << "\n";
}
else if (pid > 0)
{
// Fork successful, we're exiting now
out << "Daemon started with pid " << pid << "\n";
return 0;
}
else
{
// Child process
umask(0);
pid_t sid = setsid();
if (sid < 0)
{
return 1;
}
//chdir("/");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
}
#endif // Q_OS_UNIX
// If there may be anything left, we flush it before the client starts
out.flush();
// Initialize the client instance
Client *client = Client::instance();
LOG_INFO(QString("Glimpse version %1").arg(Client::version()));
if (parser.isSet(passiveOption))
{
int setPassive = parser.value(passiveOption).toInt();
client->settings()->setPassive((bool) setPassive);
}
if (parser.isSet(trafficOption))
{
int setTraffic = parser.value(trafficOption).toInt();
if (setTraffic != 0)
{
client->settings()->setAvailableTraffic(setTraffic * 1024 * 1024);
client->settings()->setAvailableMobileTraffic(setTraffic * 1024 * 1024);
client->settings()->setTrafficBudgetManagerActive(true);
}
else
{
client->settings()->setTrafficBudgetManagerActive(false);
}
}
if (!client->init())
{
LOG_ERROR("Client initialization failed")
return 1;
}
new LoginWatcher(client->loginController());
new DeviceRegistrationWatcher(client->loginController());
new ConfigWatcher(client, loginData);
int value = app.exec();
out << "Application shutting down.\n";
Client::instance()->deleteLater();
QTimer::singleShot(1, &app, SLOT(quit()));
app.exec();
return value;
}
#include "main.moc"
<|endoftext|>
|
<commit_before>#include <gtkmm/application.h>
#include <gtkmm/messagedialog.h>
#include <iostream>
#include <iterator>
#include <fstream>
#include <chrono>
#include <cstdlib>
#include <cassert>
#include <exception>
#include <stdexcept>
#include "get_DPI_scale.hpp"
#include "defs.hpp"
#include "Program_mode.hpp"
#include "Start_menu_window.hpp"
namespace {
void init_names()
{
using Input_it = std::istream_iterator<std::string>;
{
std::ifstream input_stream(FIRSTNAMES);
g_firstnames.emplace(Input_it{input_stream}, Input_it{});
}
{
std::ifstream input_stream(LASTNAMES);
g_lastnames.emplace(Input_it{input_stream}, Input_it{});
}
}
void init_globals()
{
g_DPI_scale.emplace(get_DPI_scale());
std::cerr << PROGNAME ": DPI scale = " << *g_DPI_scale << "\n";
using namespace std::chrono;
g_RNE.emplace(steady_clock::now().time_since_epoch().count());
init_names();
}
}
int main(int argc, char* argv[])
{
init_globals();
Program_mode program_mode = Program_mode::start_menu;
bool running = true;
while (running) {
auto app = Gtk::Application::create("veltas.distrotycoon");
try {
switch (program_mode) {
case Program_mode::start_menu: {
Start_menu_window start_menu_window;
app->run(start_menu_window);
assert(app > 0);
program_mode = start_menu_window.get_next_mode();
} break;
case Program_mode::load_game: {
/*
Load_game_window load_game_window;
app->run(load_game_window);
program_mode = load_game_window.get_next_mode();
*/
throw std::runtime_error("Not implemented");
} break;
case Program_mode::playing: {
/*
Playing_window playing;
app->run(playing);
program_mode = playing.get_next_mode();
*/
throw std::runtime_error("Not implemented");
} break;
case Program_mode::end: {
running = false;
} break;
}
} catch (std::exception& e) {
Gtk::MessageDialog message_dialog{
"Uncaught exception error",
false,
Gtk::MESSAGE_ERROR
};
message_dialog.set_secondary_text(std::string{"Error: "} + e.what());
message_dialog.run();
app->release();
return EXIT_FAILURE;
}
}
}
<commit_msg>src/main.cpp: Remove erroneous free function<commit_after>#include <gtkmm/application.h>
#include <gtkmm/messagedialog.h>
#include <iostream>
#include <iterator>
#include <fstream>
#include <chrono>
#include <cstdlib>
#include <cassert>
#include <exception>
#include <stdexcept>
#include "get_DPI_scale.hpp"
#include "defs.hpp"
#include "Program_mode.hpp"
#include "Start_menu_window.hpp"
namespace {
void init_names()
{
using Input_it = std::istream_iterator<std::string>;
{
std::ifstream input_stream(FIRSTNAMES);
g_firstnames.emplace(Input_it{input_stream}, Input_it{});
}
{
std::ifstream input_stream(LASTNAMES);
g_lastnames.emplace(Input_it{input_stream}, Input_it{});
}
}
void init_globals()
{
g_DPI_scale.emplace(get_DPI_scale());
std::cerr << PROGNAME ": DPI scale = " << *g_DPI_scale << "\n";
using namespace std::chrono;
g_RNE.emplace(steady_clock::now().time_since_epoch().count());
init_names();
}
}
int main(int argc, char* argv[])
{
init_globals();
Program_mode program_mode = Program_mode::start_menu;
bool running = true;
while (running) {
try {
auto app = Gtk::Application::create("veltas.distrotycoon");
switch (program_mode) {
case Program_mode::start_menu: {
Start_menu_window start_menu_window;
app->run(start_menu_window);
assert(app > 0);
program_mode = start_menu_window.get_next_mode();
} break;
case Program_mode::load_game: {
/*
Load_game_window load_game_window;
app->run(load_game_window);
program_mode = load_game_window.get_next_mode();
// */
throw std::runtime_error("Not implemented");
} break;
case Program_mode::playing: {
/*
Playing_window playing;
app->run(playing);
program_mode = playing.get_next_mode();
// */
throw std::runtime_error("Not implemented");
} break;
case Program_mode::end: {
running = false;
} break;
}
} catch (std::exception& e) {
Gtk::MessageDialog message_dialog{
"Uncaught exception error",
false,
Gtk::MESSAGE_ERROR
};
message_dialog.set_secondary_text(std::string{"Error: "} + e.what());
message_dialog.run();
return EXIT_FAILURE;
}
}
}
<|endoftext|>
|
<commit_before>/* Rapicorn
* Copyright (C) 2006 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#ifndef __RAPICORN_H__
#define __RAPICORN_H__
#include <rapicorn-core/rapicornconfig.h>
#include <rapicorn-core/rapicorncpu.hh>
#include <rapicorn-core/rapicorndebugtools.hh>
#include <rapicorn-core/enumdefs.hh>
#include <rapicorn-core/rapicornmsg.hh>
#include <rapicorn-core/rapicornmarkup.hh>
#include <rapicorn-core/rapicornmath.hh>
#include <rapicorn-core/rapicornutf8.hh>
#include <rapicorn-core/rapicornutils.hh>
#include <rapicorn-core/rapicornsignal.hh>
#include <rapicorn-core/rapicornthread.hh>
#include <rapicorn-core/rapicornxml.hh>
#endif /* __RAPICORN_H__ */
/* vim:set ts=8 sts=2 sw=2: */
<commit_msg>rapicorn-core/rapicorncore.hh: sorted include statements<commit_after>/* Rapicorn
* Copyright (C) 2006 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#ifndef __RAPICORN_H__
#define __RAPICORN_H__
#include <rapicorn-core/rapicornconfig.h>
#include <rapicorn-core/enumdefs.hh>
#include <rapicorn-core/rapicorncpu.hh>
#include <rapicorn-core/rapicorndebugtools.hh>
#include <rapicorn-core/rapicornmarkup.hh>
#include <rapicorn-core/rapicornmath.hh>
#include <rapicorn-core/rapicornmsg.hh>
#include <rapicorn-core/rapicornsignal.hh>
#include <rapicorn-core/rapicornthread.hh>
#include <rapicorn-core/rapicornutf8.hh>
#include <rapicorn-core/rapicornutils.hh>
#include <rapicorn-core/rapicornxml.hh>
#endif /* __RAPICORN_H__ */
/* vim:set ts=8 sts=2 sw=2: */
<|endoftext|>
|
<commit_before>#include "pcl/filters/crop_box.h"
#include "pcl/conversions.h"
#include "pcl_conversions/pcl_conversions.h"
#include "ros/ros.h"
#include "rapid_perception/box3d_roi_server.h"
#include "sensor_msgs/PointCloud2.h"
#include "rapid_msgs/CaptureRoi3D.h"
#include "rapid_msgs/Roi3D.h"
#include "tf/transform_listener.h"
#include <Eigen/Dense>
class CaptureRoi {
public:
CaptureRoi();
void Start();
void set_cloud(sensor_msgs::PointCloud2ConstPtr cloud);
void set_roi(const rapid_msgs::Roi3D& roi);
sensor_msgs::PointCloud2 Capture();
void CloudCallback(const sensor_msgs::PointCloud2ConstPtr& msg);
bool ServeCapture(rapid_msgs::CaptureRoi3DRequest& req,
rapid_msgs::CaptureRoi3DResponse& res);
private:
ros::NodeHandle nh_;
tf::StampedTransform cloud_to_base_;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcl_cloud_;
rapid_msgs::Roi3D roi_;
rapid::perception::Box3DRoiServer marker_server_;
tf::TransformListener tf_listener_;
ros::Publisher output_pub_;
};
CaptureRoi::CaptureRoi()
: nh_(),
cloud_to_base_(),
pcl_cloud_(new pcl::PointCloud<pcl::PointXYZRGB>()),
roi_(),
marker_server_("roi1"),
tf_listener_(),
output_pub_(
nh_.advertise<sensor_msgs::PointCloud2>("cloud_out", 1, true)) {}
void CaptureRoi::Start() { marker_server_.Start(); }
void CaptureRoi::set_cloud(sensor_msgs::PointCloud2ConstPtr cloud) {
pcl::fromROSMsg(*cloud, *pcl_cloud_);
}
void CaptureRoi::set_roi(const rapid_msgs::Roi3D& roi) { roi_ = roi; }
sensor_msgs::PointCloud2 CaptureRoi::Capture() {
pcl::CropBox<pcl::PointXYZRGB> crop_;
crop_.setInputCloud(pcl_cloud_);
// Set cloud -> ROI rotation
const geometry_msgs::Quaternion& roi_q = roi_.transform.rotation;
Eigen::Quaternionf roi_rot(roi_q.w, roi_q.x, roi_q.y, roi_q.z);
const tf::Quaternion& cloud_q = cloud_to_base_.getRotation();
Eigen::Quaternionf cloud_rot(cloud_q.w(), cloud_q.x(), cloud_q.y(),
cloud_q.z());
Eigen::Affine3f transform((cloud_rot * roi_rot).toRotationMatrix());
crop_.setTransform(transform);
// Set cloud -> ROI translation
const tf::Vector3& cloud_t = -1 * cloud_to_base_.getOrigin();
const geometry_msgs::Vector3& roi_t = roi_.transform.translation;
Eigen::Vector3f translation(cloud_t.x() + roi_t.x, cloud_t.y() + roi_t.y,
cloud_t.z() + roi_t.z);
crop_.setTranslation(translation);
// Set dimensions
Eigen::Vector4f min_pt(-roi_.dimensions.x / 2, -roi_.dimensions.y / 2,
-roi_.dimensions.z / 2, 0);
crop_.setMin(min_pt);
Eigen::Vector4f max_pt(roi_.dimensions.x / 2, roi_.dimensions.y / 2,
roi_.dimensions.z / 2, 0);
crop_.setMax(max_pt);
pcl::PointCloud<pcl::PointXYZRGB> output;
crop_.filter(output);
sensor_msgs::PointCloud2 output_ros;
pcl::toROSMsg(output, output_ros);
return output_ros;
}
void CaptureRoi::CloudCallback(const sensor_msgs::PointCloud2ConstPtr& msg) {
try {
tf_listener_.lookupTransform("base_link", msg->header.frame_id,
msg->header.stamp, cloud_to_base_);
set_cloud(msg);
} catch (tf::TransformException e) {
}
}
bool CaptureRoi::ServeCapture(rapid_msgs::CaptureRoi3DRequest& req,
rapid_msgs::CaptureRoi3DResponse& res) {
roi_ = marker_server_.roi();
const sensor_msgs::PointCloud2& output = Capture();
output_pub_.publish(output);
res.cloud = Capture();
return true;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "roi3d_main");
ros::AsyncSpinner spinner(4);
spinner.start();
ros::NodeHandle nh;
CaptureRoi capture_server;
ros::Subscriber pc_sub =
nh.subscribe("cloud_in", 1, &CaptureRoi::CloudCallback, &capture_server);
ros::ServiceServer save_srv = nh.advertiseService(
"capture_roi", &CaptureRoi::ServeCapture, &capture_server);
capture_server.Start();
ros::waitForShutdown();
return 0;
}
void cloud_callback(const sensor_msgs::PointCloud2ConstPtr& msg) { return; }
bool capture_roi(rapid_msgs::CaptureRoi3DRequest& req,
rapid_msgs::CaptureRoi3DResponse& res) {
return true;
}
<commit_msg>Removed unused code.<commit_after>#include "pcl/filters/crop_box.h"
#include "pcl/conversions.h"
#include "pcl_conversions/pcl_conversions.h"
#include "ros/ros.h"
#include "rapid_perception/box3d_roi_server.h"
#include "sensor_msgs/PointCloud2.h"
#include "rapid_msgs/CaptureRoi3D.h"
#include "rapid_msgs/Roi3D.h"
#include "tf/transform_listener.h"
#include <Eigen/Dense>
class CaptureRoi {
public:
CaptureRoi();
void Start();
void set_cloud(sensor_msgs::PointCloud2ConstPtr cloud);
void set_roi(const rapid_msgs::Roi3D& roi);
sensor_msgs::PointCloud2 Capture();
void CloudCallback(const sensor_msgs::PointCloud2ConstPtr& msg);
bool ServeCapture(rapid_msgs::CaptureRoi3DRequest& req,
rapid_msgs::CaptureRoi3DResponse& res);
private:
ros::NodeHandle nh_;
tf::StampedTransform cloud_to_base_;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcl_cloud_;
rapid_msgs::Roi3D roi_;
rapid::perception::Box3DRoiServer marker_server_;
tf::TransformListener tf_listener_;
ros::Publisher output_pub_;
};
CaptureRoi::CaptureRoi()
: nh_(),
cloud_to_base_(),
pcl_cloud_(new pcl::PointCloud<pcl::PointXYZRGB>()),
roi_(),
marker_server_("roi1"),
tf_listener_(),
output_pub_(
nh_.advertise<sensor_msgs::PointCloud2>("cloud_out", 1, true)) {}
void CaptureRoi::Start() { marker_server_.Start(); }
void CaptureRoi::set_cloud(sensor_msgs::PointCloud2ConstPtr cloud) {
pcl::fromROSMsg(*cloud, *pcl_cloud_);
}
void CaptureRoi::set_roi(const rapid_msgs::Roi3D& roi) { roi_ = roi; }
sensor_msgs::PointCloud2 CaptureRoi::Capture() {
pcl::CropBox<pcl::PointXYZRGB> crop_;
crop_.setInputCloud(pcl_cloud_);
// Set cloud -> ROI rotation
const geometry_msgs::Quaternion& roi_q = roi_.transform.rotation;
Eigen::Quaternionf roi_rot(roi_q.w, roi_q.x, roi_q.y, roi_q.z);
const tf::Quaternion& cloud_q = cloud_to_base_.getRotation();
Eigen::Quaternionf cloud_rot(cloud_q.w(), cloud_q.x(), cloud_q.y(),
cloud_q.z());
Eigen::Affine3f transform((cloud_rot * roi_rot).toRotationMatrix());
crop_.setTransform(transform);
// Set cloud -> ROI translation
const tf::Vector3& cloud_t = -1 * cloud_to_base_.getOrigin();
const geometry_msgs::Vector3& roi_t = roi_.transform.translation;
Eigen::Vector3f translation(cloud_t.x() + roi_t.x, cloud_t.y() + roi_t.y,
cloud_t.z() + roi_t.z);
crop_.setTranslation(translation);
// Set dimensions
Eigen::Vector4f min_pt(-roi_.dimensions.x / 2, -roi_.dimensions.y / 2,
-roi_.dimensions.z / 2, 0);
crop_.setMin(min_pt);
Eigen::Vector4f max_pt(roi_.dimensions.x / 2, roi_.dimensions.y / 2,
roi_.dimensions.z / 2, 0);
crop_.setMax(max_pt);
pcl::PointCloud<pcl::PointXYZRGB> output;
crop_.filter(output);
sensor_msgs::PointCloud2 output_ros;
pcl::toROSMsg(output, output_ros);
return output_ros;
}
void CaptureRoi::CloudCallback(const sensor_msgs::PointCloud2ConstPtr& msg) {
try {
tf_listener_.lookupTransform("base_link", msg->header.frame_id,
msg->header.stamp, cloud_to_base_);
set_cloud(msg);
} catch (tf::TransformException e) {
}
}
bool CaptureRoi::ServeCapture(rapid_msgs::CaptureRoi3DRequest& req,
rapid_msgs::CaptureRoi3DResponse& res) {
roi_ = marker_server_.roi();
const sensor_msgs::PointCloud2& output = Capture();
output_pub_.publish(output);
res.cloud = Capture();
return true;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "roi3d_main");
ros::AsyncSpinner spinner(4);
spinner.start();
ros::NodeHandle nh;
CaptureRoi capture_server;
ros::Subscriber pc_sub =
nh.subscribe("cloud_in", 1, &CaptureRoi::CloudCallback, &capture_server);
ros::ServiceServer save_srv = nh.advertiseService(
"capture_roi", &CaptureRoi::ServeCapture, &capture_server);
capture_server.Start();
ros::waitForShutdown();
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <gtest/gtest.h>
using namespace std;
void init_test();
TEST(async_rpc, test_dummy_future) {
init_test();
};
#if 0
//A --> B --> C
B --> D
A <-- B
//X --> A --> B
#endif
struct Req {
int req_value;
};
struct Rsp {
int rsp_value;
};
struct RspC {
int rspc_value;
};
template<typename T>
struct Cell {
typedef std::function<void(T&)> callback_type;
bool has_value_ {false};
T value_;
void set_value(T& t) {
//TODO: invoke callback
if (callback_)
callback_(t);
}
void bind(callback_type callback) {
if (this->has_value_) {
callback(value_);
} else {
callback_ = callback;
}
}
callback_type callback_;
};
struct BuzzMath {
Cell<Rsp> next_prime_number_sync(const Req &req_value);
Cell<Rsp> next_prime_number_async(const Req &req_value);
};
Cell<RspC> result_cell_of_c;
struct CccMath {
Cell<RspC> next_prime_number_async(const Req &req_value) {
// RspC rsp_c;
// rsp_c.rspc_value = 32;
// auto rsp_ret = Cell<RspC>();
// rsp_ret.value_ = rsp_c;
// rsp_ret.has_value_ = true;
//return Cell<RspC>();
return result_cell_of_c;
}
};
Cell<Rsp> BuzzMath::next_prime_number_async(const Req &req_value) {
Cell<Rsp> result;
////B ----> C
//interface_on_c.method_x(111);
CccMath cccMath;
result_cell_of_c = cccMath.next_prime_number_async(req_value);
result_cell_of_c.bind(
[](RspC& rsp_c){
cout << "got result of rsp_c, value:" << rsp_c.rspc_value << endl;
}
);
return result;
}
Cell<Rsp> BuzzMath::next_prime_number_sync(const Req &req_value) {
Rsp rsp; rsp.rsp_value = 29;
Cell<Rsp> rsp_ret = Cell<Rsp>();
rsp_ret.value_ = rsp;
rsp_ret.has_value_ = true;
return rsp_ret;
}
void init_test() {
BuzzMath buzz;
Req req = {23};
Cell<Rsp> rpc_ret = buzz.next_prime_number_sync(req);
rpc_ret.bind(
[](Rsp &) {
cout << "B buzz.next_prime_number_sync: send result msg to sender." << endl;
}
);
Cell<Rsp> rpc_ret_async = buzz.next_prime_number_async(req);
rpc_ret_async.bind(
[](Rsp &) {
cout << "in callback" << endl;
}
);
RspC rsp_c {22};
result_cell_of_c.set_value(rsp_c);
//C---------->B (msg)
//Rsp rsp; rsp.rsp_value = 31;
//TODO: 1 find rpc_ret_async
//rpc_ret_async.set_value(rsp);
//TODO: timeout
}
//TODO: get/generate context_id from msg<commit_msg>add dummy testing<commit_after>#include <iostream>
#include <gtest/gtest.h>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// rc <---- rpc_result
// rd <---- rpc_result
// a <---- (b <--- rc) && (rd)
TEST(async_rpc, test_______________aaa) {
};
////////////////////////////////////////////////////////////////////////////////
void init_test();
TEST(async_rpc, test_dummy_future) {
init_test();
};
#if 0
//A --> B --> C
B --> D
A <-- B
//X --> A --> B
#endif
struct Req {
int req_value;
};
struct Rsp {
int rsp_value;
};
struct RspC {
int rspc_value;
};
template<typename T>
struct Cell {
typedef std::function<void(T&)> callback_type;
bool has_value_ {false};
T value_;
void set_value(T& t) {
if (callback_)
callback_(t);
}
void bind(callback_type callback) {
if (this->has_value_) {
callback(value_);
} else {
callback_ = callback;
}
}
callback_type callback_;
};
struct BuzzMath {
Cell<Rsp> next_prime_number_sync(const Req &req_value);
Cell<Rsp> next_prime_number_async(const Req &req_value);
};
Cell<RspC> result_cell_of_c;
struct CccMath {
Cell<RspC> c_next_prime_value(const Req &req_value) {
return result_cell_of_c;
}
};
Cell<Rsp> result_of_b;
Cell<Rsp> BuzzMath::next_prime_number_async(const Req &req_value) {
CccMath cccMath;
result_cell_of_c = cccMath.c_next_prime_value(req_value);
result_cell_of_c.bind(
[](RspC& rsp_c){
cout << "got result of rsp_c, value:" << rsp_c.rspc_value << endl;
Rsp rsp_b {rsp_c.rspc_value * 2};
result_of_b.set_value(rsp_b);
}
);
return result_of_b;
}
Cell<Rsp> BuzzMath::next_prime_number_sync(const Req &req_value) {
Rsp rsp; rsp.rsp_value = 29;
Cell<Rsp> rsp_ret = Cell<Rsp>();
rsp_ret.value_ = rsp;
rsp_ret.has_value_ = true;
return rsp_ret;
}
void init_test() {
BuzzMath buzz;
Req req = {23};
Cell<Rsp> rpc_ret = buzz.next_prime_number_sync(req);
rpc_ret.bind(
[](Rsp &) {
cout << "B buzz.next_prime_number_sync: send result msg to sender." << endl;
}
);
result_of_b = buzz.next_prime_number_async(req);
result_of_b.bind(
[](Rsp& rsp) {
cout << "in callback of B: got value:" << rsp.rsp_value << endl;
}
);
RspC rsp_c {22};
result_cell_of_c.set_value(rsp_c);
}
//TODO: get/generate context_id from msg
<|endoftext|>
|
<commit_before>#include "evaluate_circuit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace qflex {
namespace {
class GetOutputStatesTest : public testing::Test {
public:
void TestOutputExpectations() {
get_output_states(&input_, ordering_, &final_qubits_, &output_states_);
EXPECT_EQ(final_qubits_, expected_final_qubits_);
EXPECT_EQ(output_states_, expected_output_states_);
}
protected:
QflexInput input_;
std::vector<std::vector<int>> final_qubits_, expected_final_qubits_;
std::vector<std::string> output_states_, expected_output_states_;
std::list<ContractionOperation> ordering_;
};
// ExpandPatch should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresExpandPatch) {
ordering_.emplace_back(ExpandPatch("a", {0, 0}));
ordering_.emplace_back(ExpandPatch("a", {0, 1}));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// MergePatches should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresMergePatches) {
ordering_.emplace_back(MergePatches("a", "b"));
ordering_.emplace_back(MergePatches("b", "c"));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// Non-terminal cuts should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresNonTerminalCuts) {
ordering_.emplace_back(CutIndex({{0, 0}, {0, 1}}, {1, 2}));
ordering_.emplace_back(CutIndex({{0, 0}, {1, 0}}, {3}));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// Terminal cuts are listed in index order, inline with other qubits.
TEST_F(GetOutputStatesTest, TerminalCutsOrderedNormally) {
input_.grid.I = 3;
input_.grid.J = 2;
input_.final_state = "xx00x0";
ordering_.emplace_back(CutIndex({{0, 1}}, {0}));
ordering_.emplace_back(CutIndex({{0, 0}}, {0, 1}));
ordering_.emplace_back(CutIndex({{2, 0}}, {1}));
expected_final_qubits_ = {{0, 1}, {0, 0}, {2, 0}};
expected_output_states_ = {"000010", "100010"};
TestOutputExpectations();
}
// Terminal cuts with no values will be evaluated as "0" and "1", since output
// states can only be one of those two values.
TEST_F(GetOutputStatesTest, BlankCutValuesEvaluateBothStates) {
input_.grid.I = 2;
input_.grid.J = 2;
input_.final_state = "xxx";
ordering_.emplace_back(CutIndex({{0, 1}}));
ordering_.emplace_back(CutIndex({{0, 0}}));
ordering_.emplace_back(CutIndex({{1, 0}}));
expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};
expected_output_states_ = {"000", "001", "100", "101",
"010", "011", "110", "111"};
TestOutputExpectations();
}
// When a mixture of operations are applied, only terminal cuts affect the
// output states.
TEST_F(GetOutputStatesTest, OnlyUseTerminalCuts) {
input_.grid.I = 3;
input_.grid.J = 2;
input_.grid.qubits_off.push_back({2, 0});
input_.final_state = "0000x";
ordering_.emplace_back(CutIndex({{0, 1}, {1, 1}}, {1, 2}));
ordering_.emplace_back(ExpandPatch("a", {0, 1}));
ordering_.emplace_back(ExpandPatch("a", {0, 0}));
ordering_.emplace_back(ExpandPatch("a", {1, 0}));
ordering_.emplace_back(CutIndex({{2, 1}}));
ordering_.emplace_back(ExpandPatch("b", {2, 1}));
ordering_.emplace_back(ExpandPatch("b", {1, 1}));
ordering_.emplace_back(MergePatches("a", "b"));
expected_final_qubits_ = {{2, 1}};
expected_output_states_ = {"00000", "00001"};
TestOutputExpectations();
}
// Nullptr input in get_output_states()
TEST(GetOutputStatesExceptionTest, InvalidInput) {
QflexInput input;
std::list<ContractionOperation> ordering;
std::vector<std::vector<int>> final_qubits;
std::vector<std::string> output_states;
// Input cannot be null pointer.
try {
get_output_states(nullptr, ordering, &final_qubits, &output_states);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Input must be non-null."));
}
// Final qubits cannot be null pointer.
try {
get_output_states(&input, ordering, nullptr, &output_states);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Final qubits must be non-null"));
}
// Output states cannot be null pointer.
try {
get_output_states(&input, ordering, &final_qubits, nullptr);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Output states must be non-null"));
}
}
// Grid layout with trailing whitespace.
constexpr char kTestGrid_3x4[] = R"(0 1 1 0
1 1 1 1
0 1 0 0)";
constexpr char kTestGrid_6x2[] = R"(0 1
1 0
1 1
1 1
0 1
0 0)";
TEST(ReadGridTest, ValidGrid3x4) {
std::stringstream stream(kTestGrid_3x4);
QflexGrid grid;
grid.load(stream);
std::vector<std::vector<int>> expected_off = {
{0, 0}, {0, 3}, {2, 0}, {2, 2}, {2, 3}};
EXPECT_EQ(grid.qubits_off, expected_off);
}
TEST(ReadGridTest, ValidGrid6x2) {
std::stringstream stream(kTestGrid_6x2);
QflexGrid grid;
grid.load(stream);
std::vector<std::vector<int>> expected_off = {
{0, 0}, {1, 1}, {4, 0}, {5, 0}, {5, 1}};
EXPECT_EQ(grid.qubits_off, expected_off);
}
// Below are config strings for a simple grid with one "off" qubit and one cut:
// 0 - 1
// | x --> cut between (0,1) and (1,1)
// 2 - 3
// |
// 4 5 --> qubit at (2,0) is off; (2,1) is in final region.
// This circuit should return the input string with amplitude ~= 1 when summing
// over the cut values, but only when the output of (2,1) is a zero.
constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 t 0
1 t 1
1 t 2
1 t 3
1 t 5
2 cz 0 1
3 cx 0 2
4 cx 1 3
5 cz 2 3
6 cz 3 5
11 cz 0 1
12 cx 0 2
13 cx 1 3
14 cz 2 3
15 cx 3 5
17 h 0
17 h 1
17 h 2
17 h 3
17 h 5)";
constexpr char kSimpleOrdering[] = R"(#
cut () 1 3
expand a 1
expand a 0
expand a 2
cut () 5
expand b 5
expand b 3
merge a b
)";
constexpr char kSimpleGrid[] = R"(1 1
1 1
0 1)";
// Perform a full evaluation of a very simple circuit.
TEST(EvaluateCircuitTest, SimpleCircuit) {
std::stringstream circuit_data(kSimpleCircuit);
std::stringstream ordering_data(kSimpleOrdering);
std::stringstream grid_data(kSimpleGrid);
QflexInput input;
input.grid.I = 3;
input.grid.J = 2;
input.circuit.load(circuit_data);
input.ordering.load(ordering_data);
input.grid.load(grid_data);
input.initial_state = "00000";
input.final_state = "1100x";
std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
EvaluateCircuit(&input);
ASSERT_EQ(amplitudes.size(), 2);
EXPECT_EQ(amplitudes[0].first, "11000");
EXPECT_EQ(amplitudes[1].first, "11001");
EXPECT_NEAR(amplitudes[0].second.real(), 0.10669, 1e-5);
EXPECT_NEAR(amplitudes[0].second.imag(), 0.04419, 1e-5);
EXPECT_NEAR(amplitudes[1].second.real(), -0.01831, 1e-5);
EXPECT_NEAR(amplitudes[1].second.imag(), -0.25758, 1e-5);
}
// Nullptr input in EvaluateCircuit()
TEST(EvaluateCircuitExceptionTest, InvalidInput) {
// Input cannot be null pointer.
try {
EvaluateCircuit(nullptr);
FAIL() << "Expected EvaluateCircuit() to throw an exception.";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Input must be non-null"));
}
}
} // namespace
} // namespace qflex
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Add temporary test.<commit_after>#include "evaluate_circuit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace qflex {
namespace {
class GetOutputStatesTest : public testing::Test {
public:
void TestOutputExpectations() {
get_output_states(&input_, ordering_, &final_qubits_, &output_states_);
EXPECT_EQ(final_qubits_, expected_final_qubits_);
EXPECT_EQ(output_states_, expected_output_states_);
}
protected:
QflexInput input_;
std::vector<std::vector<int>> final_qubits_, expected_final_qubits_;
std::vector<std::string> output_states_, expected_output_states_;
std::list<ContractionOperation> ordering_;
};
// ExpandPatch should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresExpandPatch) {
ordering_.emplace_back(ExpandPatch("a", {0, 0}));
ordering_.emplace_back(ExpandPatch("a", {0, 1}));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// MergePatches should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresMergePatches) {
ordering_.emplace_back(MergePatches("a", "b"));
ordering_.emplace_back(MergePatches("b", "c"));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// Non-terminal cuts should not affect output states.
TEST_F(GetOutputStatesTest, IgnoresNonTerminalCuts) {
ordering_.emplace_back(CutIndex({{0, 0}, {0, 1}}, {1, 2}));
ordering_.emplace_back(CutIndex({{0, 0}, {1, 0}}, {3}));
expected_final_qubits_ = {};
expected_output_states_ = {""};
TestOutputExpectations();
}
// Terminal cuts are listed in index order, inline with other qubits.
TEST_F(GetOutputStatesTest, TerminalCutsOrderedNormally) {
input_.grid.I = 3;
input_.grid.J = 2;
input_.final_state = "xx00x0";
ordering_.emplace_back(CutIndex({{0, 1}}, {0}));
ordering_.emplace_back(CutIndex({{0, 0}}, {0, 1}));
ordering_.emplace_back(CutIndex({{2, 0}}, {1}));
expected_final_qubits_ = {{0, 1}, {0, 0}, {2, 0}};
expected_output_states_ = {"000010", "100010"};
TestOutputExpectations();
}
// Terminal cuts with no values will be evaluated as "0" and "1", since output
// states can only be one of those two values.
TEST_F(GetOutputStatesTest, BlankCutValuesEvaluateBothStates) {
input_.grid.I = 2;
input_.grid.J = 2;
input_.final_state = "xxx";
ordering_.emplace_back(CutIndex({{0, 1}}));
ordering_.emplace_back(CutIndex({{0, 0}}));
ordering_.emplace_back(CutIndex({{1, 0}}));
expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};
expected_output_states_ = {"000", "001", "100", "101",
"010", "011", "110", "111"};
TestOutputExpectations();
}
// When a mixture of operations are applied, only terminal cuts affect the
// output states.
TEST_F(GetOutputStatesTest, OnlyUseTerminalCuts) {
input_.grid.I = 3;
input_.grid.J = 2;
input_.grid.qubits_off.push_back({2, 0});
input_.final_state = "0000x";
ordering_.emplace_back(CutIndex({{0, 1}, {1, 1}}, {1, 2}));
ordering_.emplace_back(ExpandPatch("a", {0, 1}));
ordering_.emplace_back(ExpandPatch("a", {0, 0}));
ordering_.emplace_back(ExpandPatch("a", {1, 0}));
ordering_.emplace_back(CutIndex({{2, 1}}));
ordering_.emplace_back(ExpandPatch("b", {2, 1}));
ordering_.emplace_back(ExpandPatch("b", {1, 1}));
ordering_.emplace_back(MergePatches("a", "b"));
expected_final_qubits_ = {{2, 1}};
expected_output_states_ = {"00000", "00001"};
TestOutputExpectations();
}
// Nullptr input in get_output_states()
TEST(GetOutputStatesExceptionTest, InvalidInput) {
QflexInput input;
std::list<ContractionOperation> ordering;
std::vector<std::vector<int>> final_qubits;
std::vector<std::string> output_states;
// Input cannot be null pointer.
try {
get_output_states(nullptr, ordering, &final_qubits, &output_states);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Input must be non-null."));
}
// Final qubits cannot be null pointer.
try {
get_output_states(&input, ordering, nullptr, &output_states);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Final qubits must be non-null"));
}
// Output states cannot be null pointer.
try {
get_output_states(&input, ordering, &final_qubits, nullptr);
FAIL()
<< "Expected get_output_states() to throw an exception, but it didn't";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Output states must be non-null"));
}
}
// Grid layout with trailing whitespace.
constexpr char kTestGrid_3x4[] = R"(0 1 1 0
1 1 1 1
0 1 0 0)";
constexpr char kTestGrid_6x2[] = R"(0 1
1 0
1 1
1 1
0 1
0 0)";
TEST(ReadGridTest, ValidGrid3x4) {
std::stringstream stream(kTestGrid_3x4);
QflexGrid grid;
grid.load(stream);
std::vector<std::vector<int>> expected_off = {
{0, 0}, {0, 3}, {2, 0}, {2, 2}, {2, 3}};
EXPECT_EQ(grid.qubits_off, expected_off);
}
TEST(ReadGridTest, ValidGrid6x2) {
std::stringstream stream(kTestGrid_6x2);
QflexGrid grid;
grid.load(stream);
std::vector<std::vector<int>> expected_off = {
{0, 0}, {1, 1}, {4, 0}, {5, 0}, {5, 1}};
EXPECT_EQ(grid.qubits_off, expected_off);
}
// Below are config strings for a simple grid with one "off" qubit and one cut:
// 0 - 1
// | x --> cut between (0,1) and (1,1)
// 2 - 3
// |
// 4 5 --> qubit at (2,0) is off; (2,1) is in final region.
// This circuit should return the input string with amplitude ~= 1 when summing
// over the cut values, but only when the output of (2,1) is a zero.
constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 t 0
1 t 1
1 t 2
1 t 3
1 t 5
2 cz 0 1
3 cx 0 2
4 cx 1 3
5 cz 2 3
6 cz 3 5
11 cz 0 1
12 cx 0 2
13 cx 1 3
14 cz 2 3
15 cx 3 5
17 h 0
17 h 1
17 h 2
17 h 3
17 h 5)";
constexpr char kSimpleOrdering[] = R"(#
cut () 1 3
expand a 1
expand a 0
expand a 2
cut () 5
expand b 5
expand b 3
merge a b
)";
constexpr char kSimpleGrid[] = R"(1 1
1 1
0 1)";
// Perform a full evaluation of a very simple circuit.
TEST(EvaluateCircuitTest, SimpleCircuit) {
std::stringstream circuit_data(kSimpleCircuit);
std::stringstream ordering_data(kSimpleOrdering);
std::stringstream grid_data(kSimpleGrid);
QflexInput input;
input.circuit.load(circuit_data);
input.ordering.load(ordering_data);
input.grid.load(grid_data);
input.initial_state = "00000";
input.final_state = "1100x";
std::vector<std::pair<std::string, std::complex<double>>> amplitudes;
try {
amplitudes = EvaluateCircuit(&input);
} catch (const std::string &err) {
std::cerr << err << std::endl;
std::rethrow_exception(std::current_exception());
}
ASSERT_EQ(amplitudes.size(), 2);
EXPECT_EQ(amplitudes[0].first, "11000");
EXPECT_EQ(amplitudes[1].first, "11001");
EXPECT_NEAR(amplitudes[0].second.real(), 0.10669, 1e-5);
EXPECT_NEAR(amplitudes[0].second.imag(), 0.04419, 1e-5);
EXPECT_NEAR(amplitudes[1].second.real(), -0.01831, 1e-5);
EXPECT_NEAR(amplitudes[1].second.imag(), -0.25758, 1e-5);
}
// Nullptr input in EvaluateCircuit()
TEST(EvaluateCircuitExceptionTest, InvalidInput) {
// Input cannot be null pointer.
try {
EvaluateCircuit(nullptr);
FAIL() << "Expected EvaluateCircuit() to throw an exception.";
} catch (std::string msg) {
EXPECT_THAT(msg, testing::HasSubstr("Input must be non-null"));
}
}
} // namespace
} // namespace qflex
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/*
* opencog/spatial/StructGraph.cc
*
* Copyright (C) 2002-2011 OpenCog Foundation
* All Rights Reserved
* Author(s): Shujing Ke
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "StructGraph .h"
<commit_msg>commented out include StructGraph.h (apparently a missing or obsolete)<commit_after>/*
* opencog/spatial/StructGraph.cc
*
* Copyright (C) 2002-2011 OpenCog Foundation
* All Rights Reserved
* Author(s): Shujing Ke
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// #include "StructGraph.h"
<|endoftext|>
|
<commit_before>#include "braincloud/internal/RTTComms.h"
#include "braincloud/BrainCloudClient.h"
#include "braincloud/IRTTCallback.h"
#include "braincloud/IRTTConnectCallback.h"
#include "braincloud/internal/ITCPSocket.h"
#if (TARGET_OS_WATCH != 1)
#include "braincloud/internal/IWebSocket.h"
#endif
#include "braincloud/internal/TimeUtil.h"
#include <iostream>
#include <thread>
namespace BrainCloud
{
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type)
: _type(type)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const std::string& message)
: _type(type)
, _message(message)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const Json::Value& json)
: _type(type)
, _json(json)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const Json::Value& json, const std::string& message)
: _type(type)
, _message(message)
, _json(json)
{
}
RTTComms::RTTComms(BrainCloudClient* in_client)
: _isInitialized(false)
, _client(in_client)
, _loggingEnabled(false)
, _connectCallback(NULL)
, _socket(NULL)
, _rttConnectionStatus(RTTConnectionStatus::Disconnected)
, _receivingRunning(false)
, _heartbeatRunning(false)
, _useWebSocket(true)
, _heartbeatSeconds(30)
, _lastHeartbeatTime(0)
{
}
RTTComms::~RTTComms()
{
shutdown();
}
void RTTComms::initialize()
{
_isInitialized = true;
}
bool RTTComms::isInitialized() const
{
return _isInitialized;
}
void RTTComms::shutdown()
{
resetCommunication();
_isInitialized = false;
}
void RTTComms::resetCommunication()
{
if (isRTTEnabled())
{
_rttConnectionStatus = RTTConnectionStatus::Disconnecting;
closeSocket();
_eventQueueMutex.lock();
_callbackEventQueue.clear();
_eventQueueMutex.unlock();
_rttConnectionStatus = RTTConnectionStatus::Disconnected;
}
}
void RTTComms::closeSocket()
{
std::unique_lock<std::mutex> lock(_socketMutex);
if (_socket)
{
_socket->close();
// We wait for the recv/send threads to shutdown
_heartBeatMutex.lock();
_heartbeatCondition.notify_one();
_heartBeatMutex.unlock();
if (_receivingRunning || _heartbeatRunning)
{
_threadsCondition.wait(lock, [this]()
{
return !(_receivingRunning || _heartbeatRunning);
});
}
delete _socket;
_socket = NULL;
}
}
void RTTComms::enableRTT(IRTTConnectCallback* in_callback, bool in_useWebSocket)
{
if(isRTTEnabled())
{
return;
}
else
{
_connectCallback = in_callback;
_useWebSocket = in_useWebSocket;
_appId = _client->getAppId();
_sessionId = _client->getSessionId();
_profileId = _client->getAuthenticationService()->getProfileId();
_client->getRTTService()->requestClientConnection(this);
}
}
void RTTComms::disableRTT()
{
if(!isRTTEnabled())
{
return;
}
else
{
resetCommunication();
}
}
bool RTTComms::isRTTEnabled()
{
return _rttConnectionStatus == RTTConnectionStatus::Connected;
}
RTTComms::RTTConnectionStatus RTTComms::getConnectionStatus()
{
return _rttConnectionStatus;
}
bool RTTComms::getLoggingEnabled()
{
return _loggingEnabled;
}
void RTTComms::enableLogging(bool isEnabled)
{
_loggingEnabled = isEnabled;
}
const std::string& RTTComms::getConnectionId()
{
return _connectionId;
}
void RTTComms::runCallbacks()
{
_eventQueueMutex.lock();
auto eventsCopy = _callbackEventQueue;
_callbackEventQueue.clear();
_eventQueueMutex.unlock();
for (int i = 0; i < (int)eventsCopy.size(); ++i)
{
const RTTCallback& callback = eventsCopy[i];
switch (callback._type)
{
case RTTCallbackType::ConnectSuccess:
{
if (_connectCallback)
{
_connectCallback->rttConnectSuccess();
}
break;
}
case RTTCallbackType::ConnectFailure:
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure(callback._message);
}
break;
}
case RTTCallbackType::Event:
{
std::string serviceName = callback._json["service"].asString();
std::map<std::string, IRTTCallback*>::iterator it = _callbacks.find(serviceName);
if (it != _callbacks.end())
{
it->second->rttCallback(callback._message);
}
break;
}
}
}
}
void RTTComms::registerRTTCallback(const ServiceName& serviceName, IRTTCallback* in_callback)
{
_callbacks[serviceName.getValue()] = in_callback;
}
void RTTComms::deregisterRTTCallback(const ServiceName& serviceName)
{
std::map<std::string, IRTTCallback*>::iterator it = _callbacks.find(serviceName.getValue());
if (it != _callbacks.end())
{
_callbacks.erase(it);
}
}
void RTTComms::deregisterAllRTTCallbacks()
{
_callbacks.clear();
}
// IServerCallback
void RTTComms::serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, const std::string& jsonData)
{
if (serviceName == ServiceName::RTTRegistration)
{
Json::Reader reader;
Json::Value json;
reader.parse(jsonData, json);
processRTTMessage(serviceOperation, json);
}
}
void RTTComms::serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, const std::string& jsonError)
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure(jsonError);
}
}
void RTTComms::serverWarning(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, int numRetries, const std::string& statusMessage)
{
}
void RTTComms::processRTTMessage(const ServiceOperation& serviceOperation, const Json::Value& jsonData)
{
if (serviceOperation == ServiceOperation::RequestClientConnection)
{
const Json::Value& data = jsonData["data"];
_endpoint = getEndpointToUse(data["endpoints"]);
if (_endpoint.isNull())
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure("No endpoint available");
return;
}
}
_auth = data["auth"];
connect();
}
}
Json::Value RTTComms::getEndpointToUse(const Json::Value& endpoints) const
{
if (_useWebSocket)
{
// 1st choice: websocket + ssl
// 2nd: websocket
Json::Value endpoint = getEndpointForType(endpoints, "ws", true);
if (!endpoint.isNull())
{
return endpoint;
}
return getEndpointForType(endpoints, "ws", false);
}
else
{
// 1st choice: tcp
// 2nd: tcp + ssl (not implemented yet)
Json::Value endpoint = getEndpointForType(endpoints, "tcp", false);
if (!endpoint.isNull())
{
return endpoint;
}
return getEndpointForType(endpoints, "tcp", true);
}
}
Json::Value RTTComms::getEndpointForType(const Json::Value& endpoints, const std::string& type, bool wantSsl)
{
for (int i = 0; i < (int)endpoints.size(); ++i)
{
const Json::Value& endpoint = endpoints[i];
const std::string protocol = endpoint["protocol"].asString();
if (protocol == type)
{
if (wantSsl)
{
if (endpoint["ssl"].asBool())
{
return endpoint;
}
}
else
{
return endpoint;
}
}
}
return Json::nullValue;
}
void RTTComms::connect()
{
_rttConnectionStatus = RTTConnectionStatus::Connecting;
#if (TARGET_OS_WATCH != 1)
std::thread connectionThread([this]
{
std::string host = _endpoint["host"].asString();
int port = _endpoint["port"].asInt();
std::map<std::string, std::string> headers;
std::vector<std::string> keys = _auth.getMemberNames();
for (int i = 0; i < (int)keys.size(); ++i)
{
headers[keys[i]] = _auth[keys[i]].asString();
}
{
{
std::unique_lock<std::mutex> lock(_socketMutex);
if (_useWebSocket)
{
if (_endpoint["ssl"].asBool())
{
host = "wss://" + host;
}
else
{
host = "ws://" + host;
}
// Add headers to the query URL
if (!headers.empty())
{
host += "?";
for (std::map<std::string, std::string>::iterator it = headers.begin(); it != headers.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
if (host.back() != '?')
{
host += "&";
}
host += key + "=" + value;
}
}
_socket = IWebSocket::create(host, port, headers);
}
else
{
_socket = ITCPSocket::create(host, port);
}
}
if (!_socket->isValid())
{
closeSocket();
failedToConnect();
_rttConnectionStatus = RTTConnectionStatus::Disconnected;
return;
}
_rttConnectionStatus = RTTConnectionStatus::Connected;
}
_lastHeartbeatTime = TimeUtil::getCurrentTimeMillis();
if (_loggingEnabled)
{
std::cout << "RTT: connected" << std::endl;
}
onSocketConnected();
});
connectionThread.detach();
#else
failedToConnect();
#endif
}
void RTTComms::failedToConnect()
{
std::string host;
int port = 0;
if (!_endpoint.isNull())
{
host = _endpoint["host"].asString();
port = _endpoint["port"].asInt();
}
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::ConnectFailure, "Failed to connect to RTT Event server: " + host + ":" + std::to_string(port)));
_eventQueueMutex.unlock();
}
Json::Value RTTComms::buildConnectionRequest(const std::string& protocol)
{
Json::Value json;
json["operation"] = "CONNECT";
json["service"] = "rtt";
Json::Value system;
system["protocol"] = protocol;
system["platform"] = "C++";
Json::Value jsonData;
jsonData["appId"] = _appId;
jsonData["profileId"] = _profileId;
jsonData["sessionId"] = _sessionId;
jsonData["auth"] = _auth;
jsonData["system"] = system;
json["data"] = jsonData;
return json;
}
void RTTComms::onSocketConnected()
{
startReceiving();
if (!send(buildConnectionRequest("tcp")))
{
failedToConnect();
}
}
bool RTTComms::send(const Json::Value& jsonData)
{
Json::StyledWriter writer;
std::string message = writer.write(jsonData);
if (_loggingEnabled)
{
std::cout << "RTT SEND " << message << std::endl;
}
std::unique_lock<std::mutex> lock(_socketMutex);
if (isRTTEnabled())
{
_socket->send(message);
}
return true;
}
void RTTComms::startReceiving()
{
_receivingRunning = true;
std::thread receiveThread([this]
{
while (isRTTEnabled())
{
std::string message = _socket->recv();
if (message.empty())
{
break;
}
onRecv(message);
}
std::unique_lock<std::mutex> lock(_socketMutex);
_receivingRunning = false;
_threadsCondition.notify_one();
});
receiveThread.detach();
}
void RTTComms::startHeartbeat()
{
_heartbeatRunning = true;
std::thread heartbeatThread([this]
{
Json::Value jsonHeartbeat;
jsonHeartbeat["operation"] = "HEARTBEAT";
jsonHeartbeat["service"] = "rtt";
std::unique_lock<std::mutex> lock(_heartBeatMutex);
while (isRTTEnabled())
{
int64_t sleepTime = ((int64_t)_heartbeatSeconds * 1000) - (TimeUtil::getCurrentTimeMillis() - _lastHeartbeatTime);
if (sleepTime > 0)
{
_heartbeatCondition.wait_for(lock, std::chrono::milliseconds(sleepTime));
}
else
{
send(jsonHeartbeat);
_lastHeartbeatTime = TimeUtil::getCurrentTimeMillis();
}
}
_heartbeatRunning = false;
_threadsCondition.notify_one();
});
heartbeatThread.detach();
}
void RTTComms::onRecv(const std::string& message)
{
if (_loggingEnabled)
{
std::cout << "RTT RECV: " << message << std::endl;
}
Json::Reader reader;
Json::Value jsonData;
if (!reader.parse(message, jsonData))
{
failedToConnect();
return;
}
std::string serviceName = jsonData["service"].asString();
printf("serviceName: %s", serviceName.c_str());
processRttMessage(jsonData, message);
}
void RTTComms::processRttMessage(const Json::Value& json, const std::string& message)
{
std::string serviceName = json["service"].asString();
std::string operation = json["operation"].asString();
if (serviceName == "rtt" && operation == "CONNECT")
{
_heartbeatSeconds = json["data"].get("heartbeatSeconds", 30).asInt();
_connectionId = json["data"]["cxId"].asString();
startHeartbeat();
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::ConnectSuccess));
_eventQueueMutex.unlock();
}
else
{
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::Event, json, message));
_eventQueueMutex.unlock();
}
}
};
<commit_msg>Missed catch for enableRtt and disableRtt<commit_after>#include "braincloud/internal/RTTComms.h"
#include "braincloud/BrainCloudClient.h"
#include "braincloud/IRTTCallback.h"
#include "braincloud/IRTTConnectCallback.h"
#include "braincloud/internal/ITCPSocket.h"
#if (TARGET_OS_WATCH != 1)
#include "braincloud/internal/IWebSocket.h"
#endif
#include "braincloud/internal/TimeUtil.h"
#include <iostream>
#include <thread>
namespace BrainCloud
{
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type)
: _type(type)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const std::string& message)
: _type(type)
, _message(message)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const Json::Value& json)
: _type(type)
, _json(json)
{
}
RTTComms::RTTCallback::RTTCallback(RTTCallbackType type, const Json::Value& json, const std::string& message)
: _type(type)
, _message(message)
, _json(json)
{
}
RTTComms::RTTComms(BrainCloudClient* in_client)
: _isInitialized(false)
, _client(in_client)
, _loggingEnabled(false)
, _connectCallback(NULL)
, _socket(NULL)
, _rttConnectionStatus(RTTConnectionStatus::Disconnected)
, _receivingRunning(false)
, _heartbeatRunning(false)
, _useWebSocket(true)
, _heartbeatSeconds(30)
, _lastHeartbeatTime(0)
{
}
RTTComms::~RTTComms()
{
shutdown();
}
void RTTComms::initialize()
{
_isInitialized = true;
}
bool RTTComms::isInitialized() const
{
return _isInitialized;
}
void RTTComms::shutdown()
{
resetCommunication();
_isInitialized = false;
}
void RTTComms::resetCommunication()
{
if (isRTTEnabled())
{
_rttConnectionStatus = RTTConnectionStatus::Disconnecting;
closeSocket();
_eventQueueMutex.lock();
_callbackEventQueue.clear();
_eventQueueMutex.unlock();
_rttConnectionStatus = RTTConnectionStatus::Disconnected;
}
}
void RTTComms::closeSocket()
{
std::unique_lock<std::mutex> lock(_socketMutex);
if (_socket)
{
_socket->close();
// We wait for the recv/send threads to shutdown
_heartBeatMutex.lock();
_heartbeatCondition.notify_one();
_heartBeatMutex.unlock();
if (_receivingRunning || _heartbeatRunning)
{
_threadsCondition.wait(lock, [this]()
{
return !(_receivingRunning || _heartbeatRunning);
});
}
delete _socket;
_socket = NULL;
}
}
void RTTComms::enableRTT(IRTTConnectCallback* in_callback, bool in_useWebSocket)
{
if(isRTTEnabled() || _rttConnectionStatus == RTTConnectionStatus::Connecting)
{
return;
}
else
{
_connectCallback = in_callback;
_useWebSocket = in_useWebSocket;
_appId = _client->getAppId();
_sessionId = _client->getSessionId();
_profileId = _client->getAuthenticationService()->getProfileId();
_client->getRTTService()->requestClientConnection(this);
}
}
void RTTComms::disableRTT()
{
if(!isRTTEnabled() || _rttConnectionStatus == RTTConnectionStatus::Disconnecting)
{
return;
}
else
{
resetCommunication();
}
}
bool RTTComms::isRTTEnabled()
{
return _rttConnectionStatus == RTTConnectionStatus::Connected;
}
RTTComms::RTTConnectionStatus RTTComms::getConnectionStatus()
{
return _rttConnectionStatus;
}
bool RTTComms::getLoggingEnabled()
{
return _loggingEnabled;
}
void RTTComms::enableLogging(bool isEnabled)
{
_loggingEnabled = isEnabled;
}
const std::string& RTTComms::getConnectionId()
{
return _connectionId;
}
void RTTComms::runCallbacks()
{
_eventQueueMutex.lock();
auto eventsCopy = _callbackEventQueue;
_callbackEventQueue.clear();
_eventQueueMutex.unlock();
for (int i = 0; i < (int)eventsCopy.size(); ++i)
{
const RTTCallback& callback = eventsCopy[i];
switch (callback._type)
{
case RTTCallbackType::ConnectSuccess:
{
if (_connectCallback)
{
_connectCallback->rttConnectSuccess();
}
break;
}
case RTTCallbackType::ConnectFailure:
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure(callback._message);
}
break;
}
case RTTCallbackType::Event:
{
std::string serviceName = callback._json["service"].asString();
std::map<std::string, IRTTCallback*>::iterator it = _callbacks.find(serviceName);
if (it != _callbacks.end())
{
it->second->rttCallback(callback._message);
}
break;
}
}
}
}
void RTTComms::registerRTTCallback(const ServiceName& serviceName, IRTTCallback* in_callback)
{
_callbacks[serviceName.getValue()] = in_callback;
}
void RTTComms::deregisterRTTCallback(const ServiceName& serviceName)
{
std::map<std::string, IRTTCallback*>::iterator it = _callbacks.find(serviceName.getValue());
if (it != _callbacks.end())
{
_callbacks.erase(it);
}
}
void RTTComms::deregisterAllRTTCallbacks()
{
_callbacks.clear();
}
// IServerCallback
void RTTComms::serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, const std::string& jsonData)
{
if (serviceName == ServiceName::RTTRegistration)
{
Json::Reader reader;
Json::Value json;
reader.parse(jsonData, json);
processRTTMessage(serviceOperation, json);
}
}
void RTTComms::serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, const std::string& jsonError)
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure(jsonError);
}
}
void RTTComms::serverWarning(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, int numRetries, const std::string& statusMessage)
{
}
void RTTComms::processRTTMessage(const ServiceOperation& serviceOperation, const Json::Value& jsonData)
{
if (serviceOperation == ServiceOperation::RequestClientConnection)
{
const Json::Value& data = jsonData["data"];
_endpoint = getEndpointToUse(data["endpoints"]);
if (_endpoint.isNull())
{
if (_connectCallback)
{
_connectCallback->rttConnectFailure("No endpoint available");
return;
}
}
_auth = data["auth"];
connect();
}
}
Json::Value RTTComms::getEndpointToUse(const Json::Value& endpoints) const
{
if (_useWebSocket)
{
// 1st choice: websocket + ssl
// 2nd: websocket
Json::Value endpoint = getEndpointForType(endpoints, "ws", true);
if (!endpoint.isNull())
{
return endpoint;
}
return getEndpointForType(endpoints, "ws", false);
}
else
{
// 1st choice: tcp
// 2nd: tcp + ssl (not implemented yet)
Json::Value endpoint = getEndpointForType(endpoints, "tcp", false);
if (!endpoint.isNull())
{
return endpoint;
}
return getEndpointForType(endpoints, "tcp", true);
}
}
Json::Value RTTComms::getEndpointForType(const Json::Value& endpoints, const std::string& type, bool wantSsl)
{
for (int i = 0; i < (int)endpoints.size(); ++i)
{
const Json::Value& endpoint = endpoints[i];
const std::string protocol = endpoint["protocol"].asString();
if (protocol == type)
{
if (wantSsl)
{
if (endpoint["ssl"].asBool())
{
return endpoint;
}
}
else
{
return endpoint;
}
}
}
return Json::nullValue;
}
void RTTComms::connect()
{
_rttConnectionStatus = RTTConnectionStatus::Connecting;
#if (TARGET_OS_WATCH != 1)
std::thread connectionThread([this]
{
std::string host = _endpoint["host"].asString();
int port = _endpoint["port"].asInt();
std::map<std::string, std::string> headers;
std::vector<std::string> keys = _auth.getMemberNames();
for (int i = 0; i < (int)keys.size(); ++i)
{
headers[keys[i]] = _auth[keys[i]].asString();
}
{
{
std::unique_lock<std::mutex> lock(_socketMutex);
if (_useWebSocket)
{
if (_endpoint["ssl"].asBool())
{
host = "wss://" + host;
}
else
{
host = "ws://" + host;
}
// Add headers to the query URL
if (!headers.empty())
{
host += "?";
for (std::map<std::string, std::string>::iterator it = headers.begin(); it != headers.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
if (host.back() != '?')
{
host += "&";
}
host += key + "=" + value;
}
}
_socket = IWebSocket::create(host, port, headers);
}
else
{
_socket = ITCPSocket::create(host, port);
}
}
if (!_socket->isValid())
{
closeSocket();
failedToConnect();
_rttConnectionStatus = RTTConnectionStatus::Disconnected;
return;
}
_rttConnectionStatus = RTTConnectionStatus::Connected;
}
_lastHeartbeatTime = TimeUtil::getCurrentTimeMillis();
if (_loggingEnabled)
{
std::cout << "RTT: connected" << std::endl;
}
onSocketConnected();
});
connectionThread.detach();
#else
failedToConnect();
#endif
}
void RTTComms::failedToConnect()
{
std::string host;
int port = 0;
if (!_endpoint.isNull())
{
host = _endpoint["host"].asString();
port = _endpoint["port"].asInt();
}
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::ConnectFailure, "Failed to connect to RTT Event server: " + host + ":" + std::to_string(port)));
_eventQueueMutex.unlock();
}
Json::Value RTTComms::buildConnectionRequest(const std::string& protocol)
{
Json::Value json;
json["operation"] = "CONNECT";
json["service"] = "rtt";
Json::Value system;
system["protocol"] = protocol;
system["platform"] = "C++";
Json::Value jsonData;
jsonData["appId"] = _appId;
jsonData["profileId"] = _profileId;
jsonData["sessionId"] = _sessionId;
jsonData["auth"] = _auth;
jsonData["system"] = system;
json["data"] = jsonData;
return json;
}
void RTTComms::onSocketConnected()
{
startReceiving();
if (!send(buildConnectionRequest("tcp")))
{
failedToConnect();
}
}
bool RTTComms::send(const Json::Value& jsonData)
{
Json::StyledWriter writer;
std::string message = writer.write(jsonData);
if (_loggingEnabled)
{
std::cout << "RTT SEND " << message << std::endl;
}
std::unique_lock<std::mutex> lock(_socketMutex);
if (isRTTEnabled())
{
_socket->send(message);
}
return true;
}
void RTTComms::startReceiving()
{
_receivingRunning = true;
std::thread receiveThread([this]
{
while (isRTTEnabled())
{
std::string message = _socket->recv();
if (message.empty())
{
break;
}
onRecv(message);
}
std::unique_lock<std::mutex> lock(_socketMutex);
_receivingRunning = false;
_threadsCondition.notify_one();
});
receiveThread.detach();
}
void RTTComms::startHeartbeat()
{
_heartbeatRunning = true;
std::thread heartbeatThread([this]
{
Json::Value jsonHeartbeat;
jsonHeartbeat["operation"] = "HEARTBEAT";
jsonHeartbeat["service"] = "rtt";
std::unique_lock<std::mutex> lock(_heartBeatMutex);
while (isRTTEnabled())
{
int64_t sleepTime = ((int64_t)_heartbeatSeconds * 1000) - (TimeUtil::getCurrentTimeMillis() - _lastHeartbeatTime);
if (sleepTime > 0)
{
_heartbeatCondition.wait_for(lock, std::chrono::milliseconds(sleepTime));
}
else
{
send(jsonHeartbeat);
_lastHeartbeatTime = TimeUtil::getCurrentTimeMillis();
}
}
_heartbeatRunning = false;
_threadsCondition.notify_one();
});
heartbeatThread.detach();
}
void RTTComms::onRecv(const std::string& message)
{
if (_loggingEnabled)
{
std::cout << "RTT RECV: " << message << std::endl;
}
Json::Reader reader;
Json::Value jsonData;
if (!reader.parse(message, jsonData))
{
failedToConnect();
return;
}
std::string serviceName = jsonData["service"].asString();
printf("serviceName: %s", serviceName.c_str());
processRttMessage(jsonData, message);
}
void RTTComms::processRttMessage(const Json::Value& json, const std::string& message)
{
std::string serviceName = json["service"].asString();
std::string operation = json["operation"].asString();
if (serviceName == "rtt" && operation == "CONNECT")
{
_heartbeatSeconds = json["data"].get("heartbeatSeconds", 30).asInt();
_connectionId = json["data"]["cxId"].asString();
startHeartbeat();
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::ConnectSuccess));
_eventQueueMutex.unlock();
}
else
{
_eventQueueMutex.lock();
_callbackEventQueue.push_back(RTTCallback(RTTCallbackType::Event, json, message));
_eventQueueMutex.unlock();
}
}
};
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2018 Anon authors, see AUTHORS file.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "aws_http.h"
#include "dns_lookup.h"
#include "http_client.h"
#include <aws/core/http/standard/StandardHttpRequest.h>
#include <aws/core/http/standard/StandardHttpResponse.h>
#include <aws/core/http/Scheme.h>
using namespace Aws::Http;
namespace
{
class http_client : public HttpClient
{
static std::string normalize(const std::string &path)
{
if (path.find("//") == 0)
return path.substr(1);
return path;
}
public:
http_client(const std::shared_ptr<aws_http_client_factory::epc_map> &maps, const std::shared_ptr<tls_context> &tls)
: _maps(maps),
_tls(tls)
{
}
~http_client() {}
std::shared_ptr<endpoint_cluster> get_epc(const Aws::String &url) const
{
URI uri(url);
auto key = uri.GetAuthority() + ":" + std::to_string(uri.GetPort());
fiber_lock l(_maps->_mtx);
auto &m = _maps->_epc_map;
auto epc = m.find(key);
if (epc != m.end())
return epc->second;
auto newepc = endpoint_cluster::create(uri.GetAuthority().c_str(), uri.GetPort(),
uri.GetScheme() == Scheme::HTTPS, _tls.get());
newepc->disable_retries();
newepc->set_max_io_block_time(120);
return m[key] = newepc;
}
void MakeRequest(const std::shared_ptr<Standard::StandardHttpResponse>& resp,
HttpRequest &request,
URI uri,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter,
int recursion) const
{
if (recursion > 4) {
resp->SetResponseCode(HttpResponseCode::INTERNAL_SERVER_ERROR);
return;
}
auto body = request.GetContentBody();
auto method = request.GetMethod();
std::ostringstream str;
str << HttpMethodMapper::GetNameForHttpMethod(method) << " " << normalize(uri.GetPath())
<< uri.GetQueryString() << " HTTP/1.1\r\n";
auto headers = request.GetHeaders();
for (auto &h : headers)
str << h.first << ": " << h.second << "\r\n";
if (body && !request.HasHeader(CONTENT_LENGTH_HEADER))
{
str << "transfer-encoding: identity\r\n";
str << "content-length: " << request.GetContentLength() << "\r\n";
}
std::ostringstream strd;
if (body)
strd << body->rdbuf();
anon_log("sending:\n" << str.str() << "\nplus " << strd.str().size() << " bytes of body content");
str << "\r\n";
if (body)
str << body->rdbuf();
auto message = str.str();
auto read_body = method != HttpMethod::HTTP_HEAD;
get_epc(uri.GetURIString())->with_connected_pipe([this, &request, &resp, &message, read_body, readLimiter, writeLimiter, recursion](const pipe_t *pipe) -> bool {
// anon_log("sending...\n\n" << message << "\n");
pipe->write(message.c_str(), message.size());
http_client_response re;
re.parse(*pipe, read_body, false/*throw_on_server_error*/);
if ((re.status_code == 301 || re.status_code == 302) && re.headers.contains_header("location")) {
MakeRequest(resp, request, URI(re.headers.get_header("location").str()), readLimiter, writeLimiter, recursion+1);
}
else {
resp->SetResponseCode(static_cast<HttpResponseCode>(re.status_code));
for (auto &h : re.headers.headers)
resp->AddHeader(h.first.str(), h.second.str());
for (auto &data : re.body)
resp->GetResponseBody().write(&data[0], data.size());
}
return re.should_keep_alive;
});
}
std::shared_ptr<HttpResponse> MakeRequest(HttpRequest &request,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter) const override
{
auto resp = std::make_shared<Standard::StandardHttpResponse>(request);
try
{
MakeRequest(resp, request, request.GetUri(), readLimiter, writeLimiter, 0);
}
#if ANON_LOG_NET_TRAFFIC > 0
catch (const std::exception &exc)
{
anon_log("failure to write request: " << exc.what());
resp.reset();
}
#endif
catch (...)
{
#if ANON_LOG_NET_TRAFFIC > 0
anon_log("unknown failure to write request");
#endif
resp.reset();
}
return std::static_pointer_cast<HttpResponse>(resp);
}
std::shared_ptr<HttpResponse> MakeRequest(const std::shared_ptr<HttpRequest> &request,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter) const override
{
return MakeRequest(*request, readLimiter, writeLimiter);
}
std::shared_ptr<aws_http_client_factory::epc_map> _maps;
std::shared_ptr<tls_context> _tls;
};
} // namespace
/////////////////////////////////////////////////////////////////////////////////////////////////
aws_http_client_factory::aws_http_client_factory()
: _maps(std::make_shared<epc_map>()),
_tls(std::make_shared<tls_context>(true /*client*/, nullptr /*verify_cert*/, "/etc/ssl/certs" /*verify_loc*/, nullptr, nullptr, 5))
{
}
std::shared_ptr<HttpClient> aws_http_client_factory::CreateHttpClient(const Aws::Client::ClientConfiguration &clientConfiguration) const
{
return std::static_pointer_cast<HttpClient>(std::make_shared<http_client>(_maps, _tls));
}
std::shared_ptr<HttpRequest> aws_http_client_factory::CreateHttpRequest(const Aws::String &uri, HttpMethod method, const Aws::IOStreamFactory &streamFactory) const
{
auto req = std::static_pointer_cast<HttpRequest>(std::make_shared<Standard::StandardHttpRequest>(uri, method));
req->SetResponseStreamFactory(streamFactory);
return req;
}
std::shared_ptr<HttpRequest> aws_http_client_factory::CreateHttpRequest(const URI &uri, HttpMethod method, const Aws::IOStreamFactory &streamFactory) const
{
auto req = std::static_pointer_cast<HttpRequest>(std::make_shared<Standard::StandardHttpRequest>(uri, method));
req->SetResponseStreamFactory(streamFactory);
return req;
}
<commit_msg>more logging tweaks<commit_after>/*
Copyright (c) 2018 Anon authors, see AUTHORS file.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "aws_http.h"
#include "dns_lookup.h"
#include "http_client.h"
#include <aws/core/http/standard/StandardHttpRequest.h>
#include <aws/core/http/standard/StandardHttpResponse.h>
#include <aws/core/http/Scheme.h>
using namespace Aws::Http;
namespace
{
class http_client : public HttpClient
{
static std::string normalize(const std::string &path)
{
if (path.find("//") == 0)
return path.substr(1);
return path;
}
public:
http_client(const std::shared_ptr<aws_http_client_factory::epc_map> &maps, const std::shared_ptr<tls_context> &tls)
: _maps(maps),
_tls(tls)
{
}
~http_client() {}
std::shared_ptr<endpoint_cluster> get_epc(const Aws::String &url) const
{
URI uri(url);
auto key = uri.GetAuthority() + ":" + std::to_string(uri.GetPort());
fiber_lock l(_maps->_mtx);
auto &m = _maps->_epc_map;
auto epc = m.find(key);
if (epc != m.end())
return epc->second;
auto newepc = endpoint_cluster::create(uri.GetAuthority().c_str(), uri.GetPort(),
uri.GetScheme() == Scheme::HTTPS, _tls.get());
newepc->disable_retries();
newepc->set_max_io_block_time(120);
return m[key] = newepc;
}
void MakeRequest(const std::shared_ptr<Standard::StandardHttpResponse>& resp,
HttpRequest &request,
URI uri,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter,
int recursion) const
{
if (recursion > 4) {
resp->SetResponseCode(HttpResponseCode::INTERNAL_SERVER_ERROR);
return;
}
auto body = request.GetContentBody();
auto method = request.GetMethod();
std::ostringstream str;
str << HttpMethodMapper::GetNameForHttpMethod(method) << " " << normalize(uri.GetPath())
<< uri.GetQueryString() << " HTTP/1.1\r\n";
auto headers = request.GetHeaders();
for (auto &h : headers)
str << h.first << ": " << h.second << "\r\n";
if (body && !request.HasHeader(CONTENT_LENGTH_HEADER))
{
str << "transfer-encoding: identity\r\n";
str << "content-length: " << request.GetContentLength() << "\r\n";
}
str << "\r\n";
auto header_str = str.str();
if (body)
str << body->rdbuf();
auto message = str.str();
anon_log("sending:\n" << header_str << "plus " << (message.size() - header_str.size()) << " bytes of body content");
auto read_body = method != HttpMethod::HTTP_HEAD;
get_epc(uri.GetURIString())->with_connected_pipe([this, &request, &resp, &message, read_body, readLimiter, writeLimiter, recursion](const pipe_t *pipe) -> bool {
// anon_log("sending...\n\n" << message << "\n");
pipe->write(message.c_str(), message.size());
http_client_response re;
re.parse(*pipe, read_body, false/*throw_on_server_error*/);
if ((re.status_code == 301 || re.status_code == 302) && re.headers.contains_header("location")) {
MakeRequest(resp, request, URI(re.headers.get_header("location").str()), readLimiter, writeLimiter, recursion+1);
}
else {
resp->SetResponseCode(static_cast<HttpResponseCode>(re.status_code));
for (auto &h : re.headers.headers)
resp->AddHeader(h.first.str(), h.second.str());
for (auto &data : re.body)
resp->GetResponseBody().write(&data[0], data.size());
}
return re.should_keep_alive;
});
}
std::shared_ptr<HttpResponse> MakeRequest(HttpRequest &request,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter) const override
{
auto resp = std::make_shared<Standard::StandardHttpResponse>(request);
try
{
MakeRequest(resp, request, request.GetUri(), readLimiter, writeLimiter, 0);
}
#if ANON_LOG_NET_TRAFFIC > 0
catch (const std::exception &exc)
{
anon_log("failure to write request: " << exc.what());
resp.reset();
}
#endif
catch (...)
{
#if ANON_LOG_NET_TRAFFIC > 0
anon_log("unknown failure to write request");
#endif
resp.reset();
}
return std::static_pointer_cast<HttpResponse>(resp);
}
std::shared_ptr<HttpResponse> MakeRequest(const std::shared_ptr<HttpRequest> &request,
Aws::Utils::RateLimits::RateLimiterInterface *readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface *writeLimiter) const override
{
return MakeRequest(*request, readLimiter, writeLimiter);
}
std::shared_ptr<aws_http_client_factory::epc_map> _maps;
std::shared_ptr<tls_context> _tls;
};
} // namespace
/////////////////////////////////////////////////////////////////////////////////////////////////
aws_http_client_factory::aws_http_client_factory()
: _maps(std::make_shared<epc_map>()),
_tls(std::make_shared<tls_context>(true /*client*/, nullptr /*verify_cert*/, "/etc/ssl/certs" /*verify_loc*/, nullptr, nullptr, 5))
{
}
std::shared_ptr<HttpClient> aws_http_client_factory::CreateHttpClient(const Aws::Client::ClientConfiguration &clientConfiguration) const
{
return std::static_pointer_cast<HttpClient>(std::make_shared<http_client>(_maps, _tls));
}
std::shared_ptr<HttpRequest> aws_http_client_factory::CreateHttpRequest(const Aws::String &uri, HttpMethod method, const Aws::IOStreamFactory &streamFactory) const
{
auto req = std::static_pointer_cast<HttpRequest>(std::make_shared<Standard::StandardHttpRequest>(uri, method));
req->SetResponseStreamFactory(streamFactory);
return req;
}
std::shared_ptr<HttpRequest> aws_http_client_factory::CreateHttpRequest(const URI &uri, HttpMethod method, const Aws::IOStreamFactory &streamFactory) const
{
auto req = std::static_pointer_cast<HttpRequest>(std::make_shared<Standard::StandardHttpRequest>(uri, method));
req->SetResponseStreamFactory(streamFactory);
return req;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <iostream>
#include <vector>
// glm additional header to generate transformation matrices directly.
#include <glm/gtc/matrix_transform.hpp>
#include <cstring> // For memcopy depending on the platform.
#include "helpers/ProgramUtilities.h"
#include "Renderer.h"
Renderer::Renderer(){}
Renderer::~Renderer(){}
void Renderer::init(int width, int height){
// Initialize the timer.
_timer = glfwGetTime();
// Setup projection matrix.
_camera.screen(width, height);
// Setup the framebuffer.
_framebuffer = Framebuffer(width, height);
_framebuffer.setup();
// Query the renderer identifier, and the supported OpenGL version.
const GLubyte* renderer = glGetString(GL_RENDERER);
const GLubyte* version = glGetString(GL_VERSION);
std::cout << "Renderer: " << renderer << std::endl;
std::cout << "OpenGL version supported: " << version << std::endl;
checkGLError();
// GL options
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
checkGLError();
// Setup light
_light.position = glm::vec4(0.0f); // position will be updated at each frame
_light.shininess = 250.0f;
_light.Ia = glm::vec4(0.3f, 0.3f, 0.3f, 0.0f);
_light.Id = glm::vec4(0.8f, 0.8f,0.8f, 0.0f);
_light.Is = glm::vec4(1.0f, 1.0f, 1.0f, 0.0f);
// Setup material
_material.Ka = glm::vec4(0.3f,0.2f,0.0f,0.0f);
_material.Kd = glm::vec4(1.0f, 0.5f, 0.0f, 0.0f);
_material.Ks = glm::vec4(1.0f, 1.0f, 1.0f,0.0f);
// Generate the buffer.
glGenBuffers(1, &_ubo);
// Bind the buffer.
glBindBuffer(GL_UNIFORM_BUFFER, _ubo);
// We need to know the alignment size if we want to store two uniform blocks in the same uniform buffer.
GLint uboAlignSize = 0;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uboAlignSize);
// Compute the padding for the second block, it needs to be a multiple of uboAlignSize (typically uboAlignSize will be 256.)
GLuint padding = 4*sizeof(glm::vec4) + 1*sizeof(float);
padding = ((padding/uboAlignSize)+1)*uboAlignSize;
// Allocate enough memory to hold the Light struct and Material structures.
glBufferData(GL_UNIFORM_BUFFER, padding + 3 * sizeof(glm::vec4), NULL, GL_DYNAMIC_DRAW);
// Bind the range allocated to the light.
glBindBufferRange(GL_UNIFORM_BUFFER, 0, _ubo, 0, 4*sizeof(glm::vec4) + sizeof(float));
// Submit the data.
glBufferSubData(GL_UNIFORM_BUFFER, 0, 4*sizeof(glm::vec4) + sizeof(float), &_light);
// Bind the range allocated to the material.
glBindBufferRange(GL_UNIFORM_BUFFER, 1, _ubo, padding, 3*sizeof(glm::vec4));
// Submit the data.
glBufferSubData(GL_UNIFORM_BUFFER, padding, 3*sizeof(glm::vec4), &_material);
glBindBuffer(GL_UNIFORM_BUFFER,0);
// Initialize objects.
_suzanne.init();
_dragon.init();
_skybox.init();
_screen.init(_framebuffer.textureId());
checkGLError();
}
void Renderer::draw(){
// Compute the time elapsed since last frame
float elapsed = glfwGetTime() - _timer;
_timer = glfwGetTime();
// Physics simulation
physics(elapsed);
// Update the light position (in view space).
// Bind the buffer.
glBindBuffer(GL_UNIFORM_BUFFER, _ubo);
// Obtain a handle to the underlying memory.
GLvoid * ptr = glMapBuffer(GL_UNIFORM_BUFFER,GL_WRITE_ONLY);
// Copy the light position.
std::memcpy(ptr, &(_light.position[0]), sizeof(glm::vec4));
// Unmap, unbind.
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
// Draw the scene inside the framebuffer.
_framebuffer.bind();
glViewport(0, 0, _framebuffer._width, _framebuffer._height);
// Set the clear color to white.
glClearColor(1.0f,1.0f,1.0f,0.0f);
// Clear the color and depth buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw objects.
_suzanne.draw(elapsed, _camera._view, _camera._projection);
_dragon.draw(elapsed, _camera._view, _camera._projection);
_skybox.draw(elapsed, _camera._view, _camera._projection);
// Unbind the framebuffer, we now use the default framebuffer.
_framebuffer.unbind();
// Only the final target should be in the sRGB space.
glEnable(GL_FRAMEBUFFER_SRGB);
// Draw the fullscreen quad
glViewport(0,0,_camera._screenSize[0],_camera._screenSize[1]);
// Set the clear color to black.
glClearColor(0.0f,0.0f,0.0f,0.0f);
// Clear the color and depth buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the screen quad.
_screen.draw(_timer);
glDisable(GL_FRAMEBUFFER_SRGB);
// Update timer
_timer = glfwGetTime();
}
void Renderer::physics(float elapsedTime){
_camera.update(elapsedTime);
// Compute the light position in view space.
_light.position = _camera._view * glm::vec4(2.0f,2.0f,2.0f,1.0f);
}
void Renderer::clean(){
// Clean objects.
_suzanne.clean();
_dragon.clean();
_skybox.clean();
_screen.clean();
_framebuffer.clean();
}
void Renderer::resize(int width, int height){
//Update the size of the viewport.
glViewport(0, 0, width, height);
// Update the projection matrix.
_camera.screen(width, height);
// Resize the framebuffer.
_framebuffer.resize(width, height);
}
void Renderer::keyPressed(int key, int action){
if(action == GLFW_PRESS){
_camera.key(key, true);
} else if(action == GLFW_RELEASE) {
_camera.key(key, false);
}
}
void Renderer::buttonPressed(int button, int action, double x, double y){
if (button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS) {
_camera.mouse(MouseMode::Start,x, y);
} else if (action == GLFW_RELEASE) {
_camera.mouse(MouseMode::End, 0.0, 0.0);
}
} else {
std::cout << "Button: " << button << ", action: " << action << std::endl;
}
}
void Renderer::mousePosition(int x, int y, bool leftPress, bool rightPress){
if (leftPress){
_camera.mouse(MouseMode::Move, float(x), float(y));
}
}
<commit_msg>Fixed: slow glMapBuffer<commit_after>#include <stdio.h>
#include <iostream>
#include <vector>
// glm additional header to generate transformation matrices directly.
#include <glm/gtc/matrix_transform.hpp>
#include <cstring> // For memcopy depending on the platform.
#include "helpers/ProgramUtilities.h"
#include "Renderer.h"
Renderer::Renderer(){}
Renderer::~Renderer(){}
void Renderer::init(int width, int height){
// Initialize the timer.
_timer = glfwGetTime();
// Setup projection matrix.
_camera.screen(width, height);
// Setup the framebuffer.
_framebuffer = Framebuffer(width, height);
_framebuffer.setup();
// Query the renderer identifier, and the supported OpenGL version.
const GLubyte* renderer = glGetString(GL_RENDERER);
const GLubyte* version = glGetString(GL_VERSION);
std::cout << "Renderer: " << renderer << std::endl;
std::cout << "OpenGL version supported: " << version << std::endl;
checkGLError();
// GL options
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
checkGLError();
// Setup light
_light.position = glm::vec4(0.0f); // position will be updated at each frame
_light.shininess = 250.0f;
_light.Ia = glm::vec4(0.3f, 0.3f, 0.3f, 0.0f);
_light.Id = glm::vec4(0.8f, 0.8f,0.8f, 0.0f);
_light.Is = glm::vec4(1.0f, 1.0f, 1.0f, 0.0f);
// Setup material
_material.Ka = glm::vec4(0.3f,0.2f,0.0f,0.0f);
_material.Kd = glm::vec4(1.0f, 0.5f, 0.0f, 0.0f);
_material.Ks = glm::vec4(1.0f, 1.0f, 1.0f,0.0f);
// Generate the buffer.
glGenBuffers(1, &_ubo);
// Bind the buffer.
glBindBuffer(GL_UNIFORM_BUFFER, _ubo);
// We need to know the alignment size if we want to store two uniform blocks in the same uniform buffer.
GLint uboAlignSize = 0;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uboAlignSize);
// Compute the padding for the second block, it needs to be a multiple of uboAlignSize (typically uboAlignSize will be 256.)
GLuint padding = 4*sizeof(glm::vec4) + 1*sizeof(float);
padding = ((padding/uboAlignSize)+1)*uboAlignSize;
// Allocate enough memory to hold the Light struct and Material structures.
glBufferData(GL_UNIFORM_BUFFER, padding + 3 * sizeof(glm::vec4), NULL, GL_DYNAMIC_DRAW);
// Bind the range allocated to the light.
glBindBufferRange(GL_UNIFORM_BUFFER, 0, _ubo, 0, 4*sizeof(glm::vec4) + sizeof(float));
// Submit the data.
glBufferSubData(GL_UNIFORM_BUFFER, 0, 4*sizeof(glm::vec4) + sizeof(float), &_light);
// Bind the range allocated to the material.
glBindBufferRange(GL_UNIFORM_BUFFER, 1, _ubo, padding, 3*sizeof(glm::vec4));
// Submit the data.
glBufferSubData(GL_UNIFORM_BUFFER, padding, 3*sizeof(glm::vec4), &_material);
glBindBuffer(GL_UNIFORM_BUFFER,0);
// Initialize objects.
_suzanne.init();
_dragon.init();
_skybox.init();
_screen.init(_framebuffer.textureId());
checkGLError();
}
void Renderer::draw(){
// Compute the time elapsed since last frame
float elapsed = glfwGetTime() - _timer;
_timer = glfwGetTime();
// Physics simulation
physics(elapsed);
// Update the light position (in view space).
// Bind the buffer.
glBindBuffer(GL_UNIFORM_BUFFER, _ubo);
// Obtain a handle to the underlying memory.
// We force the GPU to consider the memory region as unsynchronized:
// even if it is used, it will be overwritten. Here the light position
// evolve in a continuous manner so we can take this risk.
GLvoid * ptr = glMapBufferRange(GL_UNIFORM_BUFFER,0,sizeof(glm::vec4),GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
// Copy the light position.
std::memcpy(ptr, &(_light.position[0]), sizeof(glm::vec4));
// Unmap, unbind.
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
// Draw the scene inside the framebuffer.
_framebuffer.bind();
glViewport(0, 0, _framebuffer._width, _framebuffer._height);
// Set the clear color to white.
glClearColor(1.0f,1.0f,1.0f,0.0f);
// Clear the color and depth buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw objects.
_suzanne.draw(elapsed, _camera._view, _camera._projection);
_dragon.draw(elapsed, _camera._view, _camera._projection);
_skybox.draw(elapsed, _camera._view, _camera._projection);
// Unbind the framebuffer, we now use the default framebuffer.
_framebuffer.unbind();
// Only the final target should be in the sRGB space.
glEnable(GL_FRAMEBUFFER_SRGB);
// Draw the fullscreen quad
glViewport(0,0,_camera._screenSize[0],_camera._screenSize[1]);
// Set the clear color to black.
glClearColor(0.0f,0.0f,0.0f,0.0f);
// Clear the color and depth buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the screen quad.
_screen.draw(_timer);
glDisable(GL_FRAMEBUFFER_SRGB);
// Update timer
_timer = glfwGetTime();
}
void Renderer::physics(float elapsedTime){
_camera.update(elapsedTime);
// Compute the light position in view space.
_light.position = _camera._view * glm::vec4(2.0f,2.0f,2.0f,1.0f);
}
void Renderer::clean(){
// Clean objects.
_suzanne.clean();
_dragon.clean();
_skybox.clean();
_screen.clean();
_framebuffer.clean();
}
void Renderer::resize(int width, int height){
//Update the size of the viewport.
glViewport(0, 0, width, height);
// Update the projection matrix.
_camera.screen(width, height);
// Resize the framebuffer.
_framebuffer.resize(width, height);
}
void Renderer::keyPressed(int key, int action){
if(action == GLFW_PRESS){
_camera.key(key, true);
} else if(action == GLFW_RELEASE) {
_camera.key(key, false);
}
}
void Renderer::buttonPressed(int button, int action, double x, double y){
if (button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS) {
_camera.mouse(MouseMode::Start,x, y);
} else if (action == GLFW_RELEASE) {
_camera.mouse(MouseMode::End, 0.0, 0.0);
}
} else {
std::cout << "Button: " << button << ", action: " << action << std::endl;
}
}
void Renderer::mousePosition(int x, int y, bool leftPress, bool rightPress){
if (leftPress){
_camera.mouse(MouseMode::Move, float(x), float(y));
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014 - 2015 Tolga Cakir <[email protected]>
*
* This source file is part of Game Capture HD Linux driver and is distributed
* under the MIT License. For more information, see LICENSE file.
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <unistd.h>
#include <gchd.hpp>
#include <process.hpp>
#include <streamer.hpp>
int main(int argc, char *argv[]) {
// object for managing runtime information
Process process;
// object for storing device settings
Settings settings;
// commandline-specific settings
std::string pidPath = "/var/run/gchd.pid";
std::string outputPath = "/tmp/gchd.ts";
bool useFifo = true;
// handling command-line options
int opt;
// TODO show help information
while ((opt = getopt(argc, argv, ":c:di:o:p:r:")) != -1) {
switch (opt) {
case 'c':
if (std::string(optarg) == "yuv") {
settings.setColorSpace(ColorSpace::YUV);
break;
} else if (std::string(optarg) == "rgb") {
settings.setColorSpace(ColorSpace::RGB);
break;
}
std::cerr << "Unknown colorspace argument.";
case 'd':
useFifo = false;
break;
case 'i':
if (std::string(optarg) == "composite") {
settings.setInputSource(InputSource::Composite);
break;
} else if (std::string(optarg) == "component") {
settings.setInputSource(InputSource::Component);
break;
} else if (std::string(optarg) == "hdmi") {
settings.setInputSource(InputSource::HDMI);
break;
}
std::cerr << "Unknown input source argument." << std::endl;
return EXIT_FAILURE;
case 'o':
outputPath = std::string(optarg);
break;
case 'p':
pidPath = std::string(optarg);
break;
case 'r':
if (std::string(optarg) == "ntsc") {
settings.setResolution(Resolution::NTSC);
break;
} else if (std::string(optarg) == "pal") {
settings.setResolution(Resolution::PAL);
break;
} else if (std::string(optarg) == "720") {
settings.setResolution(Resolution::HD720);
break;
} else if (std::string(optarg) == "1080") {
settings.setResolution(Resolution::HD1080);
break;
}
std::cerr << "Unknown resolution argument." << std::endl;
return EXIT_FAILURE;
case ':':
std::cerr << "Missing argument." << std::endl;
return EXIT_FAILURE;
case '?':
std::cerr << "Unrecognized option." << std::endl;
return EXIT_FAILURE;
default:
std::cerr << "Unexpected error." << std::endl;
return EXIT_FAILURE;
}
}
// TODO not ready for primetime yet, program needs to be restarted too
// often at the moment
// create PID file for single instance mechanism
// if (process.createPid(pidPath)) {
// return EXIT_FAILURE;
// }
GCHD gchd(&settings);
// device initialization
if(gchd.init()) {
return EXIT_FAILURE;
}
// helper class for streaming audio and video from device
Streamer streamer(&process);
if (useFifo) {
if (streamer.createFifo(outputPath)) {
return EXIT_FAILURE;
}
// when FIFO file has been opened
streamer.streamToFifo(&gchd);
} else {
streamer.streamToDisk(&gchd, outputPath);
}
std::cerr << "Terminating." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>added commandline help screen<commit_after>/**
* Copyright (c) 2014 - 2015 Tolga Cakir <[email protected]>
*
* This source file is part of Game Capture HD Linux driver and is distributed
* under the MIT License. For more information, see LICENSE file.
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <gchd.hpp>
#include <process.hpp>
#include <streamer.hpp>
void help(std::string program) {
std::cerr << "Usage: " << program << " [options]" << std::endl
<< std::endl
<< "Options:" << std::endl
<< " -c <color-space> Color Space settings [default: yuv]" << std::endl
<< " -d Capture to <output> instead of using FIFO" << std::endl
<< " -i <input-source> Input Source [default: hdmi]" << std::endl
<< " -o <output> Output Path [default: /tmp/gchd.ts]" << std::endl
<< " -p <pid-path> PID path [default: /var/run/gchd.pid]" << std::endl
<< " -r <resolution> Resolution of Input Source [default: 1080]" << std::endl;
}
void usage(std::string program, std::string optarg, std::string option, const std::vector<std::string> arguments) {
std::cerr << "Invalid argument '" << optarg << "' for '" << option << "'" << std::endl
<< "Valid arguments are:" << std::endl;
// print list of valid arguments
for (auto it : arguments) {
std::cerr << " - '" << it << "'" << std::endl;
}
std::cerr << "Try '" << program << " -h' for more information." << std::endl;
}
int main(int argc, char *argv[]) {
// set program name
// TODO move to Process class
std::string program(argv[0]);
if (program.empty()) {
program = "gchd";
}
// object for managing runtime information
Process process;
// object for storing device settings
Settings settings;
// commandline-specific settings
std::string pidPath = "/var/run/gchd.pid";
std::string outputPath = "/tmp/gchd.ts";
bool useFifo = true;
// handling command-line options
int opt;
while ((opt = getopt(argc, argv, ":c:dhi:o:p:r:")) != -1) {
switch (opt) {
case 'c': {
if (std::string(optarg) == "yuv") {
settings.setColorSpace(ColorSpace::YUV);
break;
} else if (std::string(optarg) == "rgb") {
settings.setColorSpace(ColorSpace::RGB);
break;
}
const std::vector<std::string> arguments = {"yuv", "rgb"};
usage(program, optarg, "-c", arguments);
return EXIT_FAILURE;
}
case 'd':
useFifo = false;
break;
case 'h':
help(program);
return EXIT_SUCCESS;
case 'i': {
if (std::string(optarg) == "composite") {
settings.setInputSource(InputSource::Composite);
break;
} else if (std::string(optarg) == "component") {
settings.setInputSource(InputSource::Component);
break;
} else if (std::string(optarg) == "hdmi") {
settings.setInputSource(InputSource::HDMI);
break;
}
const std::vector<std::string> arguments = {"composite", "component", "hdmi"};
usage(program, optarg, "-i", arguments);
return EXIT_FAILURE;
}
case 'o':
outputPath = std::string(optarg);
break;
case 'p':
pidPath = std::string(optarg);
break;
case 'r': {
if (std::string(optarg) == "ntsc") {
settings.setResolution(Resolution::NTSC);
break;
} else if (std::string(optarg) == "pal") {
settings.setResolution(Resolution::PAL);
break;
} else if (std::string(optarg) == "720") {
settings.setResolution(Resolution::HD720);
break;
} else if (std::string(optarg) == "1080") {
settings.setResolution(Resolution::HD1080);
break;
}
const std::vector<std::string> arguments = {"ntsc", "pal", "720", "1080"};
usage(program, optarg, "-r", arguments);
return EXIT_FAILURE;
}
case ':':
std::cerr << "Missing argument." << std::endl;
return EXIT_FAILURE;
case '?':
std::cerr << "Unknown option." << std::endl;
return EXIT_FAILURE;
default:
std::cerr << "Unexpected error." << std::endl;
return EXIT_FAILURE;
}
}
// TODO not ready for primetime yet, program needs to be restarted too
// often at the moment
// create PID file for single instance mechanism
// if (process.createPid(pidPath)) {
// return EXIT_FAILURE;
// }
GCHD gchd(&settings);
// device initialization
if(gchd.init()) {
return EXIT_FAILURE;
}
// helper class for streaming audio and video from device
Streamer streamer(&process);
// TODO move to Streamer class. Let it decide, what to do.
if (useFifo) {
if (streamer.createFifo(outputPath)) {
return EXIT_FAILURE;
}
// when FIFO file has been opened
streamer.streamToFifo(&gchd);
} else {
streamer.streamToDisk(&gchd, outputPath);
}
std::cerr << "Terminating." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <fstream>
#include <memory>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include "player_factory.hpp"
#include "exception.hpp"
#include "state/state_manager.hpp"
#include "state/main_menu_state.hpp"
namespace po = boost::program_options;
namespace logging = boost::log;
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, boost::log::sources::logger)
int init(int argc, char **argv);
int main(int argc, char **argv)
{
if (init(argc, argv) < 0) {
return EXIT_FAILURE;
}
boost::log::sources::logger &lg = my_logger::get();
BOOST_LOG_SEV(lg, logging::trivial::info) << "initializing game";
std::shared_ptr<Quoridor::StateManager> stm(new Quoridor::StateManager);
std::shared_ptr<Quoridor::IState> menu_state(new Quoridor::MainMenuState(stm));
stm->change_state(std::shared_ptr<Quoridor::IState>(menu_state));
stm->draw();
while (stm->is_running()) {
stm->handle_events();
stm->draw();
}
return EXIT_SUCCESS;
}
int init(int argc, char **argv)
{
std::string logfile;
po::options_description options("Options");
options.add_options()
(
"log,l",
po::value<std::string>(&logfile)->default_value("quoridor.log"),
"logging file"
)
(
"help,h",
"show help message"
);
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, options), vm);
}
catch (po::error &e) {
std::cerr << e.what() << std::endl;
return -1;
}
po::notify(vm);
if (vm.count("help")) {
std::cout << options << std::endl;
return -1;
}
typedef boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend> text_sink;
boost::shared_ptr<text_sink> sink = boost::make_shared<text_sink>();
sink->locked_backend()->add_stream(boost::make_shared<std::ofstream>("quoridor.log"));
sink->locked_backend()->auto_flush(true);
boost::log::core::get()->add_sink(sink);
return 0;
}
<commit_msg>Minimize MainMenu state scope<commit_after>#include <cstdlib>
#include <fstream>
#include <memory>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include "player_factory.hpp"
#include "exception.hpp"
#include "state/state_manager.hpp"
#include "state/main_menu_state.hpp"
namespace po = boost::program_options;
namespace logging = boost::log;
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, boost::log::sources::logger)
int init(int argc, char **argv);
int main(int argc, char **argv)
{
if (init(argc, argv) < 0) {
return EXIT_FAILURE;
}
boost::log::sources::logger &lg = my_logger::get();
BOOST_LOG_SEV(lg, logging::trivial::info) << "initializing game";
std::shared_ptr<Quoridor::StateManager> stm(new Quoridor::StateManager);
stm->change_state(std::shared_ptr<Quoridor::IState>(new Quoridor::MainMenuState(stm)));
stm->draw();
while (stm->is_running()) {
stm->handle_events();
stm->draw();
}
return EXIT_SUCCESS;
}
int init(int argc, char **argv)
{
std::string logfile;
po::options_description options("Options");
options.add_options()
(
"log,l",
po::value<std::string>(&logfile)->default_value("quoridor.log"),
"logging file"
)
(
"help,h",
"show help message"
);
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, options), vm);
}
catch (po::error &e) {
std::cerr << e.what() << std::endl;
return -1;
}
po::notify(vm);
if (vm.count("help")) {
std::cout << options << std::endl;
return -1;
}
typedef boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend> text_sink;
boost::shared_ptr<text_sink> sink = boost::make_shared<text_sink>();
sink->locked_backend()->add_stream(boost::make_shared<std::ofstream>("quoridor.log"));
sink->locked_backend()->auto_flush(true);
boost::log::core::get()->add_sink(sink);
return 0;
}
<|endoftext|>
|
<commit_before>#include "Course.h"
#include "CourseCont.h"
#include "Options.h"
#include "Scheduler.h"
#include <iostream>
CourseSched Scheduler::generateSchedule(CourseCont<Course>& courseList, Options &opts){
CourseSched schedule;
courseList.sort();
courseList.begin();
bool reachEnd = false;
for(int i = 0; i < opts.getNumCourses() && !reachEnd;){
reachEnd = courseList.get().equal(courseList.last());
Course add, comp;
bool labAdded = true;
add = comp = courseList.get();
if(add.labs.size() > 0){
labAdded = false;
add.labs.begin();
while(!labAdded){
try{
Lab temp = add.labs.get();
temp.addPadding(opts.getBreakPadding());
schedule.findConflict(&temp);
schedule.addLab(add.labs.get());
labAdded = true;
}catch(const TimeConflict &expt){
add.labs.next();
if(add.labs.get().equal(add.labs.first())){
break;
}
}
}
}
try{
if(labAdded){
comp.addPadding(opts.getBreakPadding());
schedule.findConflict(&comp); //will throw and skip if conflict
schedule.addCourse(add);
}
i++;
}catch(const TimeConflict &expt){
if(add.labs.size() > 0){
//since the course has a lab, and the course couldn't be added, we need to remove
//the last lab in the schedul container, since we can't add the class it belongs to.
schedule.labs.end();
schedule.labs.erase();
}
}catch(const EmptyContainer &epct){
break;
}
courseList.next();
}
return schedule;
}<commit_msg>added some comments to the code<commit_after>#include "Course.h"
#include "CourseCont.h"
#include "Options.h"
#include "Scheduler.h"
#include <iostream>
CourseSched Scheduler::generateSchedule(CourseCont<Course>& courseList, Options &opts){
CourseSched schedule;
courseList.sort();
courseList.begin();
bool reachEnd = false;
for(int i = 0; i < opts.getNumCourses() && !reachEnd;){
//if the current course is the last course in the container, exit the scheduler after trying to add this course.
reachEnd = courseList.get().equal(courseList.last());
Course add, comp;
bool labAdded = true;
add = comp = courseList.get();
//check to see if we can add the lab for this course, if there is a lab.
if(add.labs.size() > 0){
labAdded = false;
add.labs.begin();
while(!labAdded){
try{
//Need a temporary lab to check with padding.
Lab temp = add.labs.get();
temp.addPadding(opts.getBreakPadding());
schedule.findConflict(&temp);
//no time conflict, add the actual lab
schedule.addLab(add.labs.get());
labAdded = true;
}catch(const TimeConflict &expt){
add.labs.next();
if(add.labs.get().equal(add.labs.first())){
break;
}
}
}
}
try{
//if we can't add the lab, don't add the course
if(labAdded){
comp.addPadding(opts.getBreakPadding());
schedule.findConflict(&comp); //will throw and skip if conflict
schedule.addCourse(add);
}
i++;
}catch(const TimeConflict &expt){
if(add.labs.size() > 0){
//since the course has a lab, and the course couldn't be added, we need to remove
//the last lab in the schedul container, since we can't add the class it belongs to.
schedule.labs.end();
schedule.labs.erase();
}
}catch(const EmptyContainer &epct){
break;
}
courseList.next();
}
return schedule;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO MEDIUM PRIORITY There is some flicker still when refreshing Report
// tabs on Windows.
// TODO HIGH PRIORITY Incorporate user guide installation into "make package"
// instructions.
// TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of ComboBox and TextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.
// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.
/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.
// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or else provide an easy way for users to sign up to a mailing
// list that keeps them informed about updates. Also note we had to manually
// add "SetOverwrite on" to the CMake NSIS template file, to ensure the
// generated installer will overwrite existing files when doing updates. This
// is not ideal.
// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.
// TODO MEDIUM PRIORITY Give user the option to export to CSV.
// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.
// TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially
// for DraftJournalListCtrl. This make it easier for users on laptops.
// TODO HIGH PRIORITY Incorporate instructions for making user guide into
// README.rst.
// TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to
// create a shortcut to the file on their Desktop (assuming they didn't
// actually create the file in their desktop).
#include "app.hpp"
#include <wx/app.h>
wxIMPLEMENT_APP(dcm::App);
<commit_msg>Removed an obsolete TODO.<commit_after>/*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO MEDIUM PRIORITY There is some flicker still when refreshing Report
// tabs on Windows.
// TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of ComboBox and TextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.
// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.
/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.
// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or else provide an easy way for users to sign up to a mailing
// list that keeps them informed about updates. Also note we had to manually
// add "SetOverwrite on" to the CMake NSIS template file, to ensure the
// generated installer will overwrite existing files when doing updates. This
// is not ideal.
// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.
// TODO MEDIUM PRIORITY Give user the option to export to CSV.
// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.
// TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially
// for DraftJournalListCtrl. This make it easier for users on laptops.
// TODO HIGH PRIORITY Incorporate instructions for making user guide into
// README.rst.
// TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to
// create a shortcut to the file on their Desktop (assuming they didn't
// actually create the file in their desktop).
#include "app.hpp"
#include <wx/app.h>
wxIMPLEMENT_APP(dcm::App);
<|endoftext|>
|
<commit_before>/* Copyright 2009-2016 Francesco Biscani ([email protected])
This file is part of the mp++ library.
The mp++ library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any
later version.
or both in parallel, as here.
The mp++ library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the mp++ library. If not,
see https://www.gnu.org/licenses/. */
// std::index_sequence and std::make_index_sequence implementation, from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
#ifndef MPPP_TEST_UTILS_HPP
#define MPPP_TEST_UTILS_HPP
#include <cassert>
#include <cstddef>
#include <gmp.h>
#include <initializer_list>
#include <limits>
#include <locale>
#include <mp++.hpp>
#include <random>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace mppp_test
{
// std::index_sequence and std::make_index_sequence implementation for C++11. These are available
// in the std library in C++14. Implementation taken from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
template <std::size_t... Ints>
struct index_sequence {
using type = index_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept
{
return sizeof...(Ints);
}
};
inline namespace impl
{
template <class Sequence1, class Sequence2>
struct merge_and_renumber;
template <std::size_t... I1, std::size_t... I2>
struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
: index_sequence<I1..., (sizeof...(I1) + I2)...> {
};
}
template <std::size_t N>
struct make_index_sequence
: merge_and_renumber<typename make_index_sequence<N / 2>::type, typename make_index_sequence<N - N / 2>::type> {
};
template <>
struct make_index_sequence<0> : index_sequence<> {
};
template <>
struct make_index_sequence<1> : index_sequence<0> {
};
inline namespace impl
{
template <typename T, typename F, std::size_t... Is>
void apply_to_each_item(T &&t, const F &f, index_sequence<Is...>)
{
(void)std::initializer_list<int>{0, (void(f(std::get<Is>(std::forward<T>(t)))), 0)...};
}
}
// Tuple for_each(). Execute the functor f on each element of the input Tuple.
// https://isocpp.org/blog/2015/01/for-each-arg-eric-niebler
// https://www.reddit.com/r/cpp/comments/2tffv3/for_each_argumentsean_parent/
// https://www.reddit.com/r/cpp/comments/33b06v/for_each_in_tuple/
template <class Tuple, class F>
void tuple_for_each(Tuple &&t, const F &f)
{
apply_to_each_item(std::forward<Tuple>(t), f,
make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
}
inline namespace impl
{
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, int>::type = 0>
inline long long lex_cast_tr(T n)
{
return static_cast<long long>(n);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, int>::type = 0>
inline unsigned long long lex_cast_tr(T n)
{
return static_cast<unsigned long long>(n);
}
template <typename T, typename std::enable_if<!std::is_integral<T>::value, int>::type = 0>
inline const T &lex_cast_tr(const T &x)
{
return x;
}
}
// Lexical cast: retrieve the string representation of input object x.
template <typename T>
inline std::string lex_cast(const T &x)
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << lex_cast_tr(x);
return oss.str();
}
inline std::string lex_cast(const mppp::mppp_impl::mpz_raii &m)
{
return mppp::mppp_impl::mpz_to_str(&m.m_mpz);
}
// Set mpz to random value with n limbs. Top limb is divided by div.
inline void random_integer(mppp::mppp_impl::mpz_raii &m, unsigned n, std::mt19937 &rng, ::mp_limb_t div = 1u)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
std::uniform_int_distribution<::mp_limb_t> dist(0u, std::numeric_limits<::mp_limb_t>::max());
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast((dist(rng) & GMP_NUMB_MASK) / div).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(dist(rng) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
// Set mpz to the max value with n limbs.
inline void max_integer(mppp::mppp_impl::mpz_raii &m, unsigned n)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
}
// A macro for checking that an expression throws a specific exception object satisfying a predicate.
#define REQUIRE_THROWS_PREDICATE(expr, exc, pred) \
{ \
bool thrown_checked = false; \
try { \
expr; \
} catch (const exc &e) { \
if (pred(e)) { \
thrown_checked = true; \
} \
} \
REQUIRE(thrown_checked); \
}
#endif
<commit_msg>Tentative fix for MSVC ICE in tests.<commit_after>/* Copyright 2009-2016 Francesco Biscani ([email protected])
This file is part of the mp++ library.
The mp++ library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any
later version.
or both in parallel, as here.
The mp++ library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the mp++ library. If not,
see https://www.gnu.org/licenses/. */
// std::index_sequence and std::make_index_sequence implementation, from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
#ifndef MPPP_TEST_UTILS_HPP
#define MPPP_TEST_UTILS_HPP
#include <cassert>
#include <cstddef>
#include <gmp.h>
#include <initializer_list>
#include <limits>
#include <locale>
#include <mp++.hpp>
#include <random>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace mppp_test
{
// std::index_sequence and std::make_index_sequence implementation for C++11. These are available
// in the std library in C++14. Implementation taken from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
template <std::size_t... Ints>
struct index_sequence {
using type = index_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept
{
return sizeof...(Ints);
}
};
inline namespace impl
{
template <class Sequence1, class Sequence2>
struct merge_and_renumber;
template <std::size_t... I1, std::size_t... I2>
struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
: index_sequence<I1..., (sizeof...(I1) + I2)...> {
};
}
template <std::size_t N>
struct make_index_sequence
: merge_and_renumber<typename make_index_sequence<N / 2>::type, typename make_index_sequence<N - N / 2>::type> {
};
template <>
struct make_index_sequence<0> : index_sequence<> {
};
template <>
struct make_index_sequence<1> : index_sequence<0> {
};
inline namespace impl
{
template <typename T, typename F, std::size_t... Is>
void apply_to_each_item(T &&t, const F &f, index_sequence<Is...>)
{
(void)std::initializer_list<int>{0, (void(f(std::get<Is>(std::forward<T>(t)))), 0)...};
}
}
// Tuple for_each(). Execute the functor f on each element of the input Tuple.
// https://isocpp.org/blog/2015/01/for-each-arg-eric-niebler
// https://www.reddit.com/r/cpp/comments/2tffv3/for_each_argumentsean_parent/
// https://www.reddit.com/r/cpp/comments/33b06v/for_each_in_tuple/
template <class Tuple, class F>
void tuple_for_each(Tuple &&t, const F &f)
{
apply_to_each_item(std::forward<Tuple>(t), f,
make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
}
inline namespace impl
{
template <typename T>
struct is_mp_integer
{
static const bool value = false;
};
template <std::size_t SSize>
struct is_mp_integer<mppp::mp_integer<SSize>>
{
static const bool value = true;
};
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, int>::type = 0>
inline long long lex_cast_tr(T n)
{
return static_cast<long long>(n);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, int>::type = 0>
inline unsigned long long lex_cast_tr(T n)
{
return static_cast<unsigned long long>(n);
}
template <typename T, typename std::enable_if<is_mp_integer<T>::value, int>::type = 0>
inline std::string lex_cast_tr(const T &x)
{
return x.to_string();
}
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
inline T lex_cast_tr(const T &x)
{
return x;
}
}
// Lexical cast: retrieve the string representation of input object x.
template <typename T>
inline std::string lex_cast(const T &x)
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << lex_cast_tr(x);
return oss.str();
}
inline std::string lex_cast(const mppp::mppp_impl::mpz_raii &m)
{
return mppp::mppp_impl::mpz_to_str(&m.m_mpz);
}
// Set mpz to random value with n limbs. Top limb is divided by div.
inline void random_integer(mppp::mppp_impl::mpz_raii &m, unsigned n, std::mt19937 &rng, ::mp_limb_t div = 1u)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
std::uniform_int_distribution<::mp_limb_t> dist(0u, std::numeric_limits<::mp_limb_t>::max());
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast((dist(rng) & GMP_NUMB_MASK) / div).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(dist(rng) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
// Set mpz to the max value with n limbs.
inline void max_integer(mppp::mppp_impl::mpz_raii &m, unsigned n)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
}
// A macro for checking that an expression throws a specific exception object satisfying a predicate.
#define REQUIRE_THROWS_PREDICATE(expr, exc, pred) \
{ \
bool thrown_checked = false; \
try { \
expr; \
} catch (const exc &e) { \
if (pred(e)) { \
thrown_checked = true; \
} \
} \
REQUIRE(thrown_checked); \
}
#endif
<|endoftext|>
|
<commit_before>#include <windows.h>
#include <regstr.h>
#include "Error.h"
#include "Settings.h"
#define REGSTR_PATH_PLUSSCR (REGSTR_PATH_SETUP "\\Screen Savers")
#define REGSTR_PATH_CONFIG ("Software\\" TEAMNAME "\\" APPNAME)
HWND CSettings::hwnd;
DWORD CSettings::PasswordDelay;
DWORD CSettings::MouseThreshold;
BOOL CSettings::MuteSound;
POINT CSettings::InitCursorPos;
DWORD CSettings::InitTime;
BOOL CSettings::IsDialogActive;
BOOL CSettings::ReallyClose;
BOOL CSettings::PasswordOK;
//user settings:
int CSettings::VideoMode;
int CSettings::DetailLevel;
BOOL CSettings::DefaultRes;
BOOL CSettings::ClockOn;
BOOL CSettings::PlanetInfo;
char CSettings::DataDir[MAX_PATH];
char CSettings::DataFile[MAX_PATH];
BOOL CSettings::RandomDataFile;
CSettings::stardrs_s CSettings::filechain;
int CSettings::numfiles;
CSettings::CSettings()
{
}
CSettings::~CSettings()
{
}
void CSettings::Init()
{
hwnd=NULL;
PasswordDelay=0;
MouseThreshold=0;
MuteSound=FALSE;
ZeroMemory(&InitCursorPos,sizeof(InitCursorPos));
InitTime=0;
IsDialogActive=FALSE;
ReallyClose=FALSE;
PasswordOK=FALSE;
/////
VideoMode=0;
DetailLevel=0;
DefaultRes=TRUE;
ClockOn=FALSE;
PlanetInfo=FALSE;
DataDir[0]=0;
DataFile[0]=0;
RandomDataFile=TRUE;
filechain.next=filechain.prev=&filechain;
strcpy(filechain.filename,APPNAME);
strcpy(filechain.systemname,APPNAME);
numfiles=0;
}
void CSettings::Free()
{
stardrs_s *drs=filechain.next;
while (drs!=&filechain)
{
drs=drs->next;
free(drs->prev);
}
Init();
}
void CSettings::ReadGeneralRegistry()
{
PasswordDelay=15;
MouseThreshold=64;
IsDialogActive=FALSE;
LONG res; HKEY skey; DWORD valtype, valsize, val;
res=RegOpenKeyEx(HKEY_CURRENT_USER,REGSTR_PATH_PLUSSCR,0,KEY_ALL_ACCESS,&skey);
if (res!=ERROR_SUCCESS) return;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Password Delay",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) PasswordDelay=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Mouse Threshold",0,&valtype,(LPBYTE)&val,&valsize);if (res==ERROR_SUCCESS) MouseThreshold=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Mute Sound",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) MuteSound=val;
RegCloseKey(skey);
}
void CSettings::ReadConfigRegistry()
{
VideoMode=1;
DetailLevel=1;
DefaultRes=TRUE;
ClockOn=TRUE;
PlanetInfo=TRUE;
strcpy(DataDir,".");
strcpy(DataFile,"");
RandomDataFile=TRUE;
LONG res; HKEY skey; DWORD valtype, valsize, val;
char strval[sizeof(DataDir)];
res=RegOpenKeyEx(HKEY_LOCAL_MACHINE,REGSTR_PATH_CONFIG,0,KEY_ALL_ACCESS,&skey);
if (res!=ERROR_SUCCESS) return;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Video Mode",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) VideoMode=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Detail Level",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) DetailLevel=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Clock On",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) ClockOn=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Planet Info",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) PlanetInfo=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Default Resolution",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) DefaultRes=val;
valsize=sizeof(strval); res=RegQueryValueEx(skey,"Data Directory",0,&valtype,(LPBYTE)strval,&valsize); if (res==ERROR_SUCCESS) strcpy(DataDir,strval);
valsize=sizeof(strval); res=RegQueryValueEx(skey,"Data File",0,&valtype,(LPBYTE)strval,&valsize); if (res==ERROR_SUCCESS) strcpy(DataFile,strval);
RegCloseKey(skey);
RandomDataFile=(DataFile[0]==0);
}
void CSettings::WriteConfigRegistry()
{
if (RandomDataFile)
DataFile[0]=0;
LONG res; HKEY skey; DWORD val, disp;
char strval[sizeof(DataDir)];
res=RegCreateKeyEx(HKEY_LOCAL_MACHINE,REGSTR_PATH_CONFIG,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&skey,&disp);
if (res!=ERROR_SUCCESS) return;
val=VideoMode; RegSetValueEx(skey,"Video Mode",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=DetailLevel; RegSetValueEx(skey,"Detail Level",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=ClockOn; RegSetValueEx(skey,"Clock On",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=PlanetInfo; RegSetValueEx(skey,"Planet Info",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=DefaultRes; RegSetValueEx(skey,"Default Resolution",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
strcpy(strval,DataDir); RegSetValueEx(skey,"Data Directory",0,REG_SZ,(CONST BYTE*)strval,sizeof(strval));
strcpy(strval,DataFile); RegSetValueEx(skey,"Data File",0,REG_SZ,(CONST BYTE*)strval,sizeof(strval));
RegCloseKey(skey);
}
void CSettings::CloseSaverWindow()
{
ReallyClose=TRUE;
PostMessage(hwnd,WM_CLOSE,0,0);
}
void CSettings::StartDialog()
{
IsDialogActive=TRUE;
SendMessage(hwnd,WM_SETCURSOR,0,0);
}
void CSettings::EndDialog()
{
IsDialogActive=FALSE;
SendMessage(hwnd,WM_SETCURSOR,0,0);
GetCursorPos(&InitCursorPos);
}
bool CSettings::BuildFileList()
{
bool res=true;
stardrs_s *newsystem;
char srchstr[MAX_PATH];
char systemname[SYSTEM_NAME_SIZE];
strcpy(srchstr,DataDir);
strcat(srchstr,"\\*.DRS");
char filename[MAX_PATH];
WIN32_FIND_DATA wfd;
HANDLE h=FindFirstFile(srchstr,&wfd);
BOOL b=(h!=INVALID_HANDLE_VALUE);
while (b)
{
strcpy(filename,wfd.cFileName);
*strrchr(filename,'.')=0;
if (CBody::LoadSystemName(filename,systemname,true))
{
newsystem=(stardrs_s*)malloc(sizeof(stardrs_s));
if (!newsystem)
{
CError::LogError(ERROR_CODE,"Failed to list star systems - memory allocation error.");
res=false;
break;
}
strcpy(newsystem->filename,filename);
strcpy(newsystem->systemname,systemname);
newsystem->prev=filechain.prev;
newsystem->next=&filechain;
filechain.prev->next=newsystem;
filechain.prev=newsystem;
numfiles++;
}
b=FindNextFile(h,&wfd);
}
FindClose(h);
return res;
}
void CSettings::RandomizeDataFile()
{
int i;
stardrs_s *file;
if (!numfiles)
return;
srand((unsigned int)timeGetTime());
int num=rand()%numfiles;
for (i=0, file=filechain.next; i<num; i++)
{
file=file->next;
}
strcpy(DataFile,file->filename);
}
<commit_msg>Default video mode is now 1024x768.<commit_after>#include <windows.h>
#include <regstr.h>
#include "Error.h"
#include "Settings.h"
#define REGSTR_PATH_PLUSSCR (REGSTR_PATH_SETUP "\\Screen Savers")
#define REGSTR_PATH_CONFIG ("Software\\" TEAMNAME "\\" APPNAME)
HWND CSettings::hwnd;
DWORD CSettings::PasswordDelay;
DWORD CSettings::MouseThreshold;
BOOL CSettings::MuteSound;
POINT CSettings::InitCursorPos;
DWORD CSettings::InitTime;
BOOL CSettings::IsDialogActive;
BOOL CSettings::ReallyClose;
BOOL CSettings::PasswordOK;
//user settings:
int CSettings::VideoMode;
int CSettings::DetailLevel;
BOOL CSettings::DefaultRes;
BOOL CSettings::ClockOn;
BOOL CSettings::PlanetInfo;
char CSettings::DataDir[MAX_PATH];
char CSettings::DataFile[MAX_PATH];
BOOL CSettings::RandomDataFile;
CSettings::stardrs_s CSettings::filechain;
int CSettings::numfiles;
CSettings::CSettings()
{
}
CSettings::~CSettings()
{
}
void CSettings::Init()
{
hwnd=NULL;
PasswordDelay=0;
MouseThreshold=0;
MuteSound=FALSE;
ZeroMemory(&InitCursorPos,sizeof(InitCursorPos));
InitTime=0;
IsDialogActive=FALSE;
ReallyClose=FALSE;
PasswordOK=FALSE;
/////
VideoMode=0;
DetailLevel=0;
DefaultRes=TRUE;
ClockOn=FALSE;
PlanetInfo=FALSE;
DataDir[0]=0;
DataFile[0]=0;
RandomDataFile=TRUE;
filechain.next=filechain.prev=&filechain;
strcpy(filechain.filename,APPNAME);
strcpy(filechain.systemname,APPNAME);
numfiles=0;
}
void CSettings::Free()
{
stardrs_s *drs=filechain.next;
while (drs!=&filechain)
{
drs=drs->next;
free(drs->prev);
}
Init();
}
void CSettings::ReadGeneralRegistry()
{
PasswordDelay=15;
MouseThreshold=64;
IsDialogActive=FALSE;
LONG res; HKEY skey; DWORD valtype, valsize, val;
res=RegOpenKeyEx(HKEY_CURRENT_USER,REGSTR_PATH_PLUSSCR,0,KEY_ALL_ACCESS,&skey);
if (res!=ERROR_SUCCESS) return;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Password Delay",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) PasswordDelay=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Mouse Threshold",0,&valtype,(LPBYTE)&val,&valsize);if (res==ERROR_SUCCESS) MouseThreshold=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Mute Sound",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) MuteSound=val;
RegCloseKey(skey);
}
void CSettings::ReadConfigRegistry()
{
VideoMode=2;
DetailLevel=1;
DefaultRes=TRUE;
ClockOn=TRUE;
PlanetInfo=TRUE;
strcpy(DataDir,".");
strcpy(DataFile,"");
RandomDataFile=TRUE;
LONG res; HKEY skey; DWORD valtype, valsize, val;
char strval[sizeof(DataDir)];
res=RegOpenKeyEx(HKEY_LOCAL_MACHINE,REGSTR_PATH_CONFIG,0,KEY_ALL_ACCESS,&skey);
if (res!=ERROR_SUCCESS) return;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Video Mode",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) VideoMode=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Detail Level",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) DetailLevel=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Clock On",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) ClockOn=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Planet Info",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) PlanetInfo=val;
valsize=sizeof(val); res=RegQueryValueEx(skey,"Default Resolution",0,&valtype,(LPBYTE)&val,&valsize); if (res==ERROR_SUCCESS) DefaultRes=val;
valsize=sizeof(strval); res=RegQueryValueEx(skey,"Data Directory",0,&valtype,(LPBYTE)strval,&valsize); if (res==ERROR_SUCCESS) strcpy(DataDir,strval);
valsize=sizeof(strval); res=RegQueryValueEx(skey,"Data File",0,&valtype,(LPBYTE)strval,&valsize); if (res==ERROR_SUCCESS) strcpy(DataFile,strval);
RegCloseKey(skey);
RandomDataFile=(DataFile[0]==0);
}
void CSettings::WriteConfigRegistry()
{
if (RandomDataFile)
DataFile[0]=0;
LONG res; HKEY skey; DWORD val, disp;
char strval[sizeof(DataDir)];
res=RegCreateKeyEx(HKEY_LOCAL_MACHINE,REGSTR_PATH_CONFIG,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&skey,&disp);
if (res!=ERROR_SUCCESS) return;
val=VideoMode; RegSetValueEx(skey,"Video Mode",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=DetailLevel; RegSetValueEx(skey,"Detail Level",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=ClockOn; RegSetValueEx(skey,"Clock On",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=PlanetInfo; RegSetValueEx(skey,"Planet Info",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
val=DefaultRes; RegSetValueEx(skey,"Default Resolution",0,REG_DWORD,(CONST BYTE*)&val,sizeof(val));
strcpy(strval,DataDir); RegSetValueEx(skey,"Data Directory",0,REG_SZ,(CONST BYTE*)strval,sizeof(strval));
strcpy(strval,DataFile); RegSetValueEx(skey,"Data File",0,REG_SZ,(CONST BYTE*)strval,sizeof(strval));
RegCloseKey(skey);
}
void CSettings::CloseSaverWindow()
{
ReallyClose=TRUE;
PostMessage(hwnd,WM_CLOSE,0,0);
}
void CSettings::StartDialog()
{
IsDialogActive=TRUE;
SendMessage(hwnd,WM_SETCURSOR,0,0);
}
void CSettings::EndDialog()
{
IsDialogActive=FALSE;
SendMessage(hwnd,WM_SETCURSOR,0,0);
GetCursorPos(&InitCursorPos);
}
bool CSettings::BuildFileList()
{
bool res=true;
stardrs_s *newsystem;
char srchstr[MAX_PATH];
char systemname[SYSTEM_NAME_SIZE];
strcpy(srchstr,DataDir);
strcat(srchstr,"\\*.DRS");
char filename[MAX_PATH];
WIN32_FIND_DATA wfd;
HANDLE h=FindFirstFile(srchstr,&wfd);
BOOL b=(h!=INVALID_HANDLE_VALUE);
while (b)
{
strcpy(filename,wfd.cFileName);
*strrchr(filename,'.')=0;
if (CBody::LoadSystemName(filename,systemname,true))
{
newsystem=(stardrs_s*)malloc(sizeof(stardrs_s));
if (!newsystem)
{
CError::LogError(ERROR_CODE,"Failed to list star systems - memory allocation error.");
res=false;
break;
}
strcpy(newsystem->filename,filename);
strcpy(newsystem->systemname,systemname);
newsystem->prev=filechain.prev;
newsystem->next=&filechain;
filechain.prev->next=newsystem;
filechain.prev=newsystem;
numfiles++;
}
b=FindNextFile(h,&wfd);
}
FindClose(h);
return res;
}
void CSettings::RandomizeDataFile()
{
int i;
stardrs_s *file;
if (!numfiles)
return;
srand((unsigned int)timeGetTime());
int num=rand()%numfiles;
for (i=0, file=filechain.next; i<num; i++)
{
file=file->next;
}
strcpy(DataFile,file->filename);
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Variable.hpp"
#include "Utils.hpp"
#include "Value.hpp"
#include "il/Operands.hpp"
#include "il/Operand.hpp"
using std::map;
using std::string;
using std::endl;
using std::vector;
using namespace eddic;
Variable::Variable(const std::string& name, Type type, Position position) : m_name(name), m_type(type), m_position(position) {}
Variable::Variable(const std::string& name, Type type, Position position, std::shared_ptr<Value> value) : m_name(name), m_type(type), m_position(position), m_value(value) {}
std::string Variable::name() const {
return m_name;
}
Type Variable::type() const {
return m_type;
}
Position Variable::position() const {
return m_position;
}
std::shared_ptr<Value> Variable::value() const {
return m_value;
}
std::shared_ptr<Operand> Variable::toIntegerOperand(){
//TODO Assert that type is int
if(m_position.isStack()){//TODO Rename in a way that we can understand that it is a variable
return createBaseStackOperand(-1 * m_position.offset());
} else if(m_position.isParameter()){
return createBaseStackOperand(m_position.offset());
} else if(m_position.isGlobal()){
return createGlobalOperand(m_position.name());
}
throw "ERROR";
}
std::pair<OperandPtr, OperandPtr> Variable::toStringOperand(){
//TODO Assert that type is string
//TODO Verify
if(m_position.isStack()){//TODO Rename in a way that we can understand that it is a variable
return make_pair(
createBaseStackOperand(-1 * m_position.offset()),
createBaseStackOperand(-1 * m_position.offset() - 4)
);
} else if(m_position.isParameter()){
return make_pair(
createBaseStackOperand(m_position.offset()),
createBaseStackOperand(m_position.offset() + 4)
);
} else if(m_position.isGlobal()){
return make_pair(
createGlobalOperand(m_position.name()),
createGlobalOperand(m_position.name(), 4)
);
}
throw "ERROR";
}
<commit_msg>Fix little bug with global variables<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Variable.hpp"
#include "Utils.hpp"
#include "Value.hpp"
#include "il/Operands.hpp"
#include "il/Operand.hpp"
using std::map;
using std::string;
using std::endl;
using std::vector;
using namespace eddic;
Variable::Variable(const std::string& name, Type type, Position position) : m_name(name), m_type(type), m_position(position) {}
Variable::Variable(const std::string& name, Type type, Position position, std::shared_ptr<Value> value) : m_name(name), m_type(type), m_position(position), m_value(value) {}
std::string Variable::name() const {
return m_name;
}
Type Variable::type() const {
return m_type;
}
Position Variable::position() const {
return m_position;
}
std::shared_ptr<Value> Variable::value() const {
return m_value;
}
std::shared_ptr<Operand> Variable::toIntegerOperand(){
//TODO Assert that type is int
if(m_position.isStack()){//TODO Rename in a way that we can understand that it is a variable
return createBaseStackOperand(-1 * m_position.offset());
} else if(m_position.isParameter()){
return createBaseStackOperand(m_position.offset());
} else if(m_position.isGlobal()){
return createGlobalOperand("VI" + m_position.name());
}
throw "ERROR";
}
std::pair<OperandPtr, OperandPtr> Variable::toStringOperand(){
//TODO Assert that type is string
//TODO Verify
if(m_position.isStack()){//TODO Rename in a way that we can understand that it is a variable
return make_pair(
createBaseStackOperand(-1 * m_position.offset()),
createBaseStackOperand(-1 * m_position.offset() - 4)
);
} else if(m_position.isParameter()){
return make_pair(
createBaseStackOperand(m_position.offset()),
createBaseStackOperand(m_position.offset() + 4)
);
} else if(m_position.isGlobal()){
return make_pair(
createGlobalOperand("VS" + m_position.name()),
createGlobalOperand("VS" + m_position.name(), 4)
);
}
throw "ERROR";
}
<|endoftext|>
|
<commit_before>#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include "flutter/gtk_plugin_registrant.h"
#include "window_configuration.h"
int main(int argc, char** argv) {
gtk_init(&argc, &argv);
GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
gtk_widget_show(GTK_WIDGET(window));
gtk_widget_set_size_request(GTK_WIDGET(window), kFlutterWindowWidth,
kFlutterWindowHeight);
gtk_window_set_title(window, kFlutterWindowTitle);
g_autoptr(FlDartProject) project = fl_dart_project_new("data");
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
gtk_main();
return 0;
}
<commit_msg>Use GtkApplication (#748)<commit_after>#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include "flutter/gtk_plugin_registrant.h"
#include "window_configuration.h"
G_DECLARE_FINAL_TYPE(FlApplication, fl_application, FL, APPLICATION,
GtkApplication)
struct _FlApplication {
GtkApplication parent_instance;
};
G_DEFINE_TYPE(FlApplication, fl_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void fl_application_activate(GApplication* application) {
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
gtk_widget_show(GTK_WIDGET(window));
gtk_widget_set_size_request(GTK_WIDGET(window), kFlutterWindowWidth,
kFlutterWindowHeight);
gtk_window_set_title(window, kFlutterWindowTitle);
g_autoptr(FlDartProject) project = fl_dart_project_new("data");
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
static void fl_application_class_init(FlApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = fl_application_activate;
}
static void fl_application_init(FlApplication* self) {}
static FlApplication* fl_application_new() {
return FL_APPLICATION(g_object_new(fl_application_get_type(), nullptr));
}
int main(int argc, char** argv) {
g_autoptr(FlApplication) app = fl_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
using namespace std;
void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first, bool &multiple) {
x.clear();
y.clear();
for(unsigned int i = 0; i < userinput.size() - 1; i++) {
if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
x.push_back(0);
y.push_back(i);
}
else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
x.push_back(1);
y.push_back(i);
}
else if((userinput.at(i) == ';')) {
x.push_back(2);
y.push_back(i);
}
}
y.push_back(userinput.size());
for(unsigned int i = 0; i < y.size() - 1; i++) {
if(y.at(i + 1) == y.at(i) + 1)
multiple = true;
//if((userinput.find("&") != string::npos || userinput.find("|") != string::npos) && x.size() == 0)
// multiple = true;
}
if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
first = true;
x.push_back(userinput.size());
}
int main() {
string userinput;
string login;
if(!getlogin())
perror("getlogin");
else
login = getlogin();
char hostname[128];
if(gethostname(hostname, sizeof hostname))
perror("gethostname");
bool ext = false;
string exit_status = "exit";
while(!ext) {
cout << getlogin() << "@" << hostname << " $ ";
char *command_a;
char *command;
getline(cin, userinput);
if(userinput.find("#") != string::npos)
userinput.erase(userinput.find("#"), userinput.size());
command = new char[userinput.size()];
vector<int> c_pat;
vector<int> c_pos;
bool first = false;
bool multiple = false;
if(userinput.size() != 0)
connectors(userinput, c_pat, c_pos, first, multiple);
int x = 0;
unsigned int b = 0;
int y = 0;
char *arg[100000];
int status;
if(userinput.size() != 0) {
while(userinput.substr(x, 1) != "") {
if(multiple) {
cout << "Error: Incorrect connector config" << endl;
break;
}
if(first) {
cout << "Error: file does not exist" << endl;
break;
}
strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
command_a = strtok(command, "&;| \t");
while(command_a != NULL) {
arg[b] = command_a;
command_a = strtok(NULL, "&;| \t");
b++;
}
if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
ext = true;
break;
}
int i = fork();
if(i == -1)
perror("fork");
if(i == 0) {
if(execvp(arg[0], arg) == -1) {
perror("execvp");
exit(-1);
}
exit(0);
}
wait(&status);
x = c_pos.at(y);
unsigned int help = c_pat.at(y);
for(unsigned int i = 0; i < b; i++)
arg[i] = NULL;
if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2)
y++;
else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos))
y++;
else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos))
y++;
else
break;
b = 0;
}
}
}
return 0;
}
<commit_msg>fixed connector order I think, will notify if bugs<commit_after>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
using namespace std;
void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first, bool &multiple) {
x.clear();
y.clear();
for(unsigned int i = 0; i < userinput.size() - 1; i++) {
if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
x.push_back(0);
y.push_back(i);
}
else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
x.push_back(1);
y.push_back(i);
}
else if((userinput.at(i) == ';')) {
x.push_back(2);
y.push_back(i);
}
}
y.push_back(userinput.size());
for(unsigned int i = 0; i < y.size() - 1; i++) {
if(y.at(i + 1) == y.at(i) + 1)
multiple = true;
//if((userinput.find("&") != string::npos || userinput.find("|") != string::npos) && x.size() == 0)
// multiple = true;
}
if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
first = true;
x.push_back(userinput.size());
}
int main() {
string userinput;
string login;
if(!getlogin())
perror("getlogin");
else
login = getlogin();
char hostname[128];
if(gethostname(hostname, sizeof hostname))
perror("gethostname");
bool ext = false;
string exit_status = "exit";
while(!ext) {
cout << getlogin() << "@" << hostname << " $ ";
char *command_a;
char *command;
getline(cin, userinput);
if(userinput.find("#") != string::npos)
userinput.erase(userinput.find("#"), userinput.size());
command = new char[userinput.size()];
vector<int> c_pat;
vector<int> c_pos;
bool first = false;
bool multiple = false;
if(userinput.size() != 0)
connectors(userinput, c_pat, c_pos, first, multiple);
int x = 0;
unsigned int b = 0;
int y = 0;
char *arg[100000];
int status;
if(userinput.size() != 0) {
while(userinput.substr(x, 1) != "") {
if(multiple) {
cout << "Error: Incorrect connector config" << endl;
break;
}
if(first) {
cout << "Error: file does not exist" << endl;
break;
}
strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
command_a = strtok(command, "&;| \t");
while(command_a != NULL) {
arg[b] = command_a;
command_a = strtok(NULL, "&;| \t");
b++;
}
if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
ext = true;
break;
}
int i = fork();
if(i == -1)
perror("fork");
if(i == 0) {
if(execvp(arg[0], arg) == -1) {
perror("execvp");
exit(-1);
}
exit(0);
}
wait(&status);
x = c_pos.at(y);
unsigned int help = c_pat.at(y);
for(unsigned int i = 0; i < b; i++)
arg[i] = NULL;
if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2)
y++;
else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos)) {
x = c_pos.at(y + 1);
y+=2;
}
else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos)) {
x = c_pos.at(y + 1);
y+=2;
}
else
break;
b = 0;
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <SFML/Graphics.hpp>
#include "../include/Config.h"
#include "../include/World.h"
#include "../include/Camera.h"
#include "../include/Player.h"
#include "../include/Collision.h"
#include "../include/AnimatedProps.h"
#include "../include/SoundManager.h"
#include "../include/Shader.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
//Random numbers
srand(time(NULL));
//Initialize our objects
Config config;
SoundManager soundmngr;
Shader shader;
//Load our worlds
World grassland;
World farmland;
World rockland;
//Animated props
World animPropsWorld;
AnimatedProps animprops;
//Store a different set of collision
//boxes for different events.
Collision grasslandCollision(sf::Color::Black);
Collision farmlandCollision(sf::Color::Black);
Collision animPropsCollision(sf::Color::Black);
Collision rocklandCollision{sf::Color::Black};
Collision collision; //Bounds checking
//Audio collision boxes
Collision grasslandGrass(sf::Color::Green);
Collision grasslandShrubs(sf::Color::Blue);
Collision farmlandGrass{sf::Color::White};
Collision farmlandRoad{sf::Color::Yellow};
Collision farmlandCropAndShrub{sf::Color::Red};
Collision rocklandDirt{sf::Color::Magenta};
Collision rocklandGrass{sf::Color::Cyan};
//Camera and player
Camera camera;
Player player;
//Initialize SFML
sf::Event event;
sf::RenderWindow window(sf::VideoMode(config.getScreenWidth(),\
config.getScreenHeight()),\
config.getAppName());
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
//Are we running the game?
bool isRunning = true;
//Load our levels
if (!grassland.loadNewLevel("map/grassland.map", "textures/level/grassland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: grassland.map";
return -1;
}
if (!farmland.loadNewLevel("map/farmland.map", "textures/level/farmland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: farmland.map";
return -1;
}
if (!rockland.loadNewLevel("map/rockland.map", "textures/level/rockland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: rockland.map";
return -1;
}
if (!animPropsWorld.loadNewLevel("map/animprops.map", "textures/level/animatedprops.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: animprops.map";
return -1;
}
//We need a sprite to display our cloud background image
sf::Sprite cloudsBackground;
sf::Texture cloudsTexture;
cloudsTexture.setRepeated(true);
cloudsTexture.loadFromFile("textures/level/clouds.png");
cloudsBackground.setTexture(cloudsTexture);
cloudsBackground.setTextureRect(sf::IntRect(0, 0, config.getScreenWidth() * 4,
config.getScreenHeight() * 4));
cloudsBackground.setPosition(-500, -500);
//Init the player
player.sprite.setPosition(32, 32);
player.setTexture("textures/entity/player.anim.png");
player.sprite.setTextureRect(sf::IntRect(0, 0, 22, 32));
//Init the camera
camera.setCamCenter(player.sprite.getPosition());
//Position our worlds
rockland.setPosition(512, 0);
farmland.setPosition(0, -512);
animPropsWorld.setPosition(0, -512);
//Position the animated prop
animprops.windmill.setPosition(128, -192);
//Position collision boxes
grasslandCollision.positionCollisionBoxes(grassland.currentLevel, config.objectsInGrassland, 0, 0);
farmlandCollision.positionCollisionBoxes(farmland.currentLevel, config.objectsInFarmland, 0, -512);
animPropsCollision.positionCollisionBoxes(animPropsWorld.currentLevel, config.objectsInAnimprop, 0, -512);
rocklandCollision.positionCollisionBoxes(rockland.currentLevel, config.objectsInRockland, 512, 0);
//Audio collision boxes
grasslandGrass.positionCollisionBoxes(grassland.currentLevel, config.grasslandGrass, 0, 0);
grasslandShrubs.positionCollisionBoxes(grassland.currentLevel, config.grasslandShrubs, 0, 0);
farmlandGrass.positionCollisionBoxes(farmland.currentLevel, config.farmlandGrass, 0, -512);
farmlandRoad.positionCollisionBoxes(farmland.currentLevel, config.farmlandRoad, 0, -512);
farmlandCropAndShrub.positionCollisionBoxes(farmland.currentLevel, config.farmlandCropAndShrub, 0, -512);
rocklandDirt.positionCollisionBoxes(rockland.currentLevel, config.rocklandDirt, 512, 0);
rocklandGrass.positionCollisionBoxes(rockland.currentLevel, config.rocklandGrass, 512, 0);
//Register our sounds with the sound manager.
//Footsteps sounds, to go into bnkFootsteps (defined in SoundManager.h).
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps01.wav", "footsteps01");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps02.wav", "footsteps02");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps03.wav", "footsteps03");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps04.wav", "footsteps04");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps05.wav", "footsteps05");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps06.wav", "footsteps06");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps07.wav", "footsteps07");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps08.wav", "footsteps08");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps09.wav", "footsteps09");
//Game loop.
while (isRunning) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
isRunning = false;
}
player.handlePlayerEvents(event);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
//player.isActive = false;
//shader.deathShape.setPosition(player.sprite.getPosition().x, player.sprite.getPosition().y);
grassland.changeLevelData(5, 9);
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
//player.isActive = true;
}
}
//Clear, move, and draw
window.clear();
window.draw(cloudsBackground);
window.setView(camera.getCamera());
for (int i = 0; i < grasslandCollision.MAX_COLLISION_BOXES; ++i) {
if (grasslandCollision.collVector[i]->isTouching) {
grassland.changeLevelData(i, 9);
std::cout << grasslandCollision.collVector[i]->id << "\n";
}
}
//Check our audio collision
if (player.isActive) {
if (player.checkAudioCollsion(grasslandGrass) && player.isWalking) {
int randomNumber = rand() % 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(grasslandShrubs) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandGrass) && player.isWalking) {
int randomNumber = rand() % 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandCropAndShrub) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandRoad) && player.isWalking) {
int randomNumber = rand() % (9 - 6) + 6;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(rocklandGrass) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(rocklandDirt) && player.isWalking) {
int randomNumber = rand() % (9 - 6) + 6;
soundmngr.playFootsteps(randomNumber);
}
}
//Regular collision checking
player.checkCollision(farmlandCollision, camera);
player.checkCollision(animPropsCollision, camera);
player.checkCollision(grasslandCollision, camera);
player.checkCollision(rocklandCollision, camera);
//Draw the worlds
window.draw(farmland);
window.draw(grassland);
window.draw(rockland);
//Draw the animated sprite on top of the world
animprops.animate();
window.draw(animPropsWorld);
window.draw(animprops.windmill);
//Draw collision boxes
/*
for (int i = 0; i < collision.MAX_COLLISION_BOXES; ++i) {
window.draw(*collision.collVector[i]);
window.draw(*grasslandCollision.collVector[i]);
window.draw(*grasslandGrass.collVector[i]);
window.draw(*grasslandShrubs.collVector[i]);
window.draw(*farmlandCollision.collVector[i]);
window.draw(*farmlandGrass.collVector[i]);
window.draw(*farmlandRoad.collVector[i]);
window.draw(*farmlandCropAndShrub.collVector[i]);
window.draw(*animPropsCollision.collVector[i]);
window.draw(*rocklandCollision.collVector[i]);
window.draw(*rocklandDirt.collVector[i]);
window.draw(*rocklandGrass.collVector[i]);
}
//*/
//Animate and render the player,
//above the collision boxes.
if (player.isActive) {
player.animate();
player.movePlayer();
camera.moveCam(player.position.x, player.position.y);
window.draw(player.sprite);
}
//Draw shader testing stuff and fluffs.
/*
if (!player.isActive) {
window.draw(shader.deathShape, &shader.deathShader);
}
//*/
//Run the application
window.display();
}
return 0;
}
<commit_msg>More screwing with shit<commit_after>#include <SFML/Graphics.hpp>
#include "../include/Config.h"
#include "../include/World.h"
#include "../include/Camera.h"
#include "../include/Player.h"
#include "../include/Collision.h"
#include "../include/AnimatedProps.h"
#include "../include/SoundManager.h"
#include "../include/Shader.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
//Random numbers
srand(time(NULL));
//Initialize our objects
Config config;
SoundManager soundmngr;
Shader shader;
//Load our worlds
World grassland;
World farmland;
World rockland;
//Animated props
World animPropsWorld;
AnimatedProps animprops;
//Store a different set of collision
//boxes for different events.
Collision grasslandCollision(sf::Color::Black);
Collision farmlandCollision(sf::Color::Black);
Collision animPropsCollision(sf::Color::Black);
Collision rocklandCollision{sf::Color::Black};
Collision collision; //Bounds checking
//Audio collision boxes
Collision grasslandGrass(sf::Color::Green);
Collision grasslandShrubs(sf::Color::Blue);
Collision farmlandGrass{sf::Color::White};
Collision farmlandRoad{sf::Color::Yellow};
Collision farmlandCropAndShrub{sf::Color::Red};
Collision rocklandDirt{sf::Color::Magenta};
Collision rocklandGrass{sf::Color::Cyan};
//Camera and player
Camera camera;
Player player;
//Initialize SFML
sf::Event event;
sf::RenderWindow window(sf::VideoMode(config.getScreenWidth(),\
config.getScreenHeight()),\
config.getAppName());
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
//Are we running the game?
bool isRunning = true;
//Load our levels
if (!grassland.loadNewLevel("map/grassland.map", "textures/level/grassland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: grassland.map";
return -1;
}
if (!farmland.loadNewLevel("map/farmland.map", "textures/level/farmland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: farmland.map";
return -1;
}
if (!rockland.loadNewLevel("map/rockland.map", "textures/level/rockland.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: rockland.map";
return -1;
}
if (!animPropsWorld.loadNewLevel("map/animprops.map", "textures/level/animatedprops.png")) {
std::cerr << "FATAL ERROR: Missing required mapfile: animprops.map";
return -1;
}
//We need a sprite to display our cloud background image
sf::Sprite cloudsBackground;
sf::Texture cloudsTexture;
cloudsTexture.setRepeated(true);
cloudsTexture.loadFromFile("textures/level/clouds.png");
cloudsBackground.setTexture(cloudsTexture);
cloudsBackground.setTextureRect(sf::IntRect(0, 0, config.getScreenWidth() * 4,
config.getScreenHeight() * 4));
cloudsBackground.setPosition(-500, -500);
//Init the player
player.sprite.setPosition(32, 32);
player.setTexture("textures/entity/player.anim.png");
player.sprite.setTextureRect(sf::IntRect(0, 0, 22, 32));
//Init the camera
camera.setCamCenter(player.sprite.getPosition());
//Position our worlds
rockland.setPosition(512, 0);
farmland.setPosition(0, -512);
animPropsWorld.setPosition(0, -512);
//Position the animated prop
animprops.windmill.setPosition(128, -192);
//Position collision boxes
grasslandCollision.positionCollisionBoxes(grassland.currentLevel, config.objectsInGrassland, 0, 0);
farmlandCollision.positionCollisionBoxes(farmland.currentLevel, config.objectsInFarmland, 0, -512);
animPropsCollision.positionCollisionBoxes(animPropsWorld.currentLevel, config.objectsInAnimprop, 0, -512);
rocklandCollision.positionCollisionBoxes(rockland.currentLevel, config.objectsInRockland, 512, 0);
//Audio collision boxes
grasslandGrass.positionCollisionBoxes(grassland.currentLevel, config.grasslandGrass, 0, 0);
grasslandShrubs.positionCollisionBoxes(grassland.currentLevel, config.grasslandShrubs, 0, 0);
farmlandGrass.positionCollisionBoxes(farmland.currentLevel, config.farmlandGrass, 0, -512);
farmlandRoad.positionCollisionBoxes(farmland.currentLevel, config.farmlandRoad, 0, -512);
farmlandCropAndShrub.positionCollisionBoxes(farmland.currentLevel, config.farmlandCropAndShrub, 0, -512);
rocklandDirt.positionCollisionBoxes(rockland.currentLevel, config.rocklandDirt, 512, 0);
rocklandGrass.positionCollisionBoxes(rockland.currentLevel, config.rocklandGrass, 512, 0);
//Register our sounds with the sound manager.
//Footsteps sounds, to go into bnkFootsteps (defined in SoundManager.h).
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps01.wav", "footsteps01");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps02.wav", "footsteps02");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps03.wav", "footsteps03");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps04.wav", "footsteps04");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps05.wav", "footsteps05");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps06.wav", "footsteps06");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps07.wav", "footsteps07");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps08.wav", "footsteps08");
soundmngr.registerNewSound(soundmngr.bnkFootsteps, "audio/footsteps09.wav", "footsteps09");
//Game loop.
while (isRunning) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
isRunning = false;
}
player.handlePlayerEvents(event);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
//player.isActive = false;
//shader.deathShape.setPosition(player.sprite.getPosition().x, player.sprite.getPosition().y);
grassland.changeLevelData(5, 9);
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
//player.isActive = true;
}
}
//Clear, move, and draw
window.clear();
window.draw(cloudsBackground);
window.setView(camera.getCamera());
for (int i = 0; i < grasslandCollision.MAX_COLLISION_BOXES; ++i) {
if (grasslandCollision.collVector[i]->isTouching) {
grassland.changeLevelData(i, 9);
grasslandCollision.collVector[i]->bbox.setPosition(-9999, 9999);
std::cout << grasslandCollision.collVector[i]->id << "\n";
}
}
//Check our audio collision
if (player.isActive) {
if (player.checkAudioCollsion(grasslandGrass) && player.isWalking) {
int randomNumber = rand() % 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(grasslandShrubs) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandGrass) && player.isWalking) {
int randomNumber = rand() % 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandCropAndShrub) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(farmlandRoad) && player.isWalking) {
int randomNumber = rand() % (9 - 6) + 6;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(rocklandGrass) && player.isWalking) {
int randomNumber = rand() % (6 - 3) + 3;
soundmngr.playFootsteps(randomNumber);
}
if (player.checkAudioCollsion(rocklandDirt) && player.isWalking) {
int randomNumber = rand() % (9 - 6) + 6;
soundmngr.playFootsteps(randomNumber);
}
}
//Regular collision checking
player.checkCollision(farmlandCollision, camera);
player.checkCollision(animPropsCollision, camera);
player.checkCollision(grasslandCollision, camera);
player.checkCollision(rocklandCollision, camera);
//Draw the worlds
window.draw(farmland);
window.draw(grassland);
window.draw(rockland);
//Draw the animated sprite on top of the world
animprops.animate();
window.draw(animPropsWorld);
window.draw(animprops.windmill);
//Draw collision boxes
/*
for (int i = 0; i < collision.MAX_COLLISION_BOXES; ++i) {
window.draw(*collision.collVector[i]);
window.draw(*grasslandCollision.collVector[i]);
window.draw(*grasslandGrass.collVector[i]);
window.draw(*grasslandShrubs.collVector[i]);
window.draw(*farmlandCollision.collVector[i]);
window.draw(*farmlandGrass.collVector[i]);
window.draw(*farmlandRoad.collVector[i]);
window.draw(*farmlandCropAndShrub.collVector[i]);
window.draw(*animPropsCollision.collVector[i]);
window.draw(*rocklandCollision.collVector[i]);
window.draw(*rocklandDirt.collVector[i]);
window.draw(*rocklandGrass.collVector[i]);
}
//*/
//Animate and render the player,
//above the collision boxes.
if (player.isActive) {
player.animate();
player.movePlayer();
camera.moveCam(player.position.x, player.position.y);
window.draw(player.sprite);
}
//Draw shader testing stuff and fluffs.
/*
if (!player.isActive) {
window.draw(shader.deathShape, &shader.deathShader);
}
//*/
//Run the application
window.display();
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <iomanip>
#include <sstream>
#if defined(__linux__) || defined(__FreeBSD__)
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <net/if_dl.h>
#endif
#if defined(__linux__)
#define AF_LINK AF_PACKET
#endif
#include <boost/algorithm/string/trim.hpp>
#include "osquery/tables/networking/utils.h"
namespace osquery {
namespace tables {
std::string ipAsString(const struct sockaddr* in) {
char dst[INET6_ADDRSTRLEN] = {0};
void* in_addr = nullptr;
if (in->sa_family == AF_INET) {
in_addr = (void*)&(((struct sockaddr_in*)in)->sin_addr);
} else if (in->sa_family == AF_INET6) {
in_addr = (void*)&(((struct sockaddr_in6*)in)->sin6_addr);
} else {
return "";
}
inet_ntop(in->sa_family, in_addr, dst, sizeof(dst));
std::string address(dst);
boost::trim(address);
return address;
}
std::string ipAsString(const struct in_addr* in) {
char dst[INET6_ADDRSTRLEN] = {0};
inet_ntop(AF_INET, in, dst, sizeof(dst));
std::string address(dst);
boost::trim(address);
return address;
}
inline short addBits(unsigned char byte) {
short bits = 0;
for (int i = 7; i >= 0; --i) {
if ((byte & (1 << i)) == 0) {
break;
}
bits++;
}
return bits;
}
int netmaskFromIP(const struct sockaddr* in) {
int mask = 0;
if (in->sa_family == AF_INET6) {
auto in6 = (struct sockaddr_in6*)in;
for (size_t i = 0; i < 16; i++) {
mask += addBits(in6->sin6_addr.s6_addr[i]);
}
} else {
auto in4 = (struct sockaddr_in*)in;
auto address = reinterpret_cast<char*>(&in4->sin_addr.s_addr);
for (size_t i = 0; i < 4; i++) {
mask += addBits(address[i]);
}
}
return mask;
}
inline std::string macAsString(const char* addr) {
std::stringstream mac;
for (size_t i = 0; i < 6; i++) {
mac << std::hex << std::setfill('0') << std::setw(2);
mac << (int)((uint8_t)addr[i]);
if (i != 5) {
mac << ":";
}
}
return mac.str();
}
std::string macAsString(const struct ifaddrs* addr) {
static std::string blank_mac = "00:00:00:00:00:00";
if (addr->ifa_addr == nullptr) {
// No link or MAC exists.
return blank_mac;
}
#if defined(__linux__)
if (addr->ifa_name == nullptr) {
return blank_mac;
}
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;
memcpy(ifr.ifr_name, addr->ifa_name, IFNAMSIZ);
int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (socket_fd < 0) {
return blank_mac;
}
ioctl(socket_fd, SIOCGIFHWADDR, &ifr);
close(socket_fd);
return macAsString(ifr.ifr_hwaddr.sa_data);
#else
auto sdl = (struct sockaddr_dl*)addr->ifa_addr;
if (sdl->sdl_alen != 6) {
// Do not support MAC address that are not 6 bytes...
return blank_mac;
}
return macAsString(&sdl->sdl_data[sdl->sdl_nlen]);
#endif
}
}
}
<commit_msg>Properly format IPv6 addresses with scopes (#4464)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <iomanip>
#include <sstream>
#include <netdb.h>
#if defined(__linux__) || defined(__FreeBSD__)
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <net/if_dl.h>
#endif
#if defined(__linux__)
#define AF_LINK AF_PACKET
#endif
#include <boost/algorithm/string/trim.hpp>
#include "osquery/tables/networking/utils.h"
namespace osquery {
namespace tables {
std::string ipAsString(const struct sockaddr* in) {
char dst[INET6_ADDRSTRLEN] = {0};
size_t addrlen = in->sa_family == AF_INET ? sizeof(struct sockaddr_in)
: sizeof(struct sockaddr_in6);
if (getnameinfo(in, addrlen, dst, sizeof(dst), nullptr, 0, NI_NUMERICHOST) !=
0) {
return "";
}
std::string address(dst);
boost::trim(address);
return address;
}
std::string ipAsString(const struct in_addr* in) {
struct sockaddr_in addr;
addr.sin_addr = *in;
addr.sin_family = AF_INET;
addr.sin_port = 0;
#ifdef __MAC__
addr.sin_len = sizeof(sockaddr_in);
#endif
return ipAsString(reinterpret_cast<struct sockaddr*>(&addr));
}
inline short addBits(unsigned char byte) {
short bits = 0;
for (int i = 7; i >= 0; --i) {
if ((byte & (1 << i)) == 0) {
break;
}
bits++;
}
return bits;
}
int netmaskFromIP(const struct sockaddr* in) {
int mask = 0;
if (in->sa_family == AF_INET6) {
auto in6 = (struct sockaddr_in6*)in;
for (size_t i = 0; i < 16; i++) {
mask += addBits(in6->sin6_addr.s6_addr[i]);
}
} else {
auto in4 = (struct sockaddr_in*)in;
auto address = reinterpret_cast<char*>(&in4->sin_addr.s_addr);
for (size_t i = 0; i < 4; i++) {
mask += addBits(address[i]);
}
}
return mask;
}
inline std::string macAsString(const char* addr) {
std::stringstream mac;
for (size_t i = 0; i < 6; i++) {
mac << std::hex << std::setfill('0') << std::setw(2);
mac << (int)((uint8_t)addr[i]);
if (i != 5) {
mac << ":";
}
}
return mac.str();
}
std::string macAsString(const struct ifaddrs* addr) {
static std::string blank_mac = "00:00:00:00:00:00";
if (addr->ifa_addr == nullptr) {
// No link or MAC exists.
return blank_mac;
}
#if defined(__linux__)
if (addr->ifa_name == nullptr) {
return blank_mac;
}
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;
memcpy(ifr.ifr_name, addr->ifa_name, IFNAMSIZ);
int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (socket_fd < 0) {
return blank_mac;
}
ioctl(socket_fd, SIOCGIFHWADDR, &ifr);
close(socket_fd);
return macAsString(ifr.ifr_hwaddr.sa_data);
#else
auto sdl = (struct sockaddr_dl*)addr->ifa_addr;
if (sdl->sdl_alen != 6) {
// Do not support MAC address that are not 6 bytes...
return blank_mac;
}
return macAsString(&sdl->sdl_data[sdl->sdl_nlen]);
#endif
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/znc.h>
#include <signal.h>
#if defined(HAVE_LIBSSL) && defined(HAVE_PTHREAD)
#include <znc/Threads.h>
#include <openssl/crypto.h>
static std::vector<CMutex> lock_cs;
static void locking_callback(int mode, int type, const char *file, int line) {
if(mode & CRYPTO_LOCK) {
lock_cs[type].lock();
} else {
lock_cs[type].unlock();
}
}
static unsigned long thread_id_callback() {
return (unsigned long)pthread_self();
}
static CRYPTO_dynlock_value *dyn_create_callback(const char *file, int line) {
return (CRYPTO_dynlock_value*)new CMutex;
}
static void dyn_lock_callback(int mode, CRYPTO_dynlock_value *dlock, const char *file, int line) {
CMutex *mtx = (CMutex*)dlock;
if(mode & CRYPTO_LOCK) {
mtx->lock();
} else {
mtx->unlock();
}
}
static void dyn_destroy_callback(CRYPTO_dynlock_value *dlock, const char *file, int line) {
CMutex *mtx = (CMutex*)dlock;
delete mtx;
}
static void thread_setup() {
lock_cs.resize(CRYPTO_num_locks());
CRYPTO_set_id_callback(&thread_id_callback);
CRYPTO_set_locking_callback(&locking_callback);
CRYPTO_set_dynlock_create_callback(&dyn_create_callback);
CRYPTO_set_dynlock_lock_callback(&dyn_lock_callback);
CRYPTO_set_dynlock_destroy_callback(&dyn_destroy_callback);
}
#else
#define thread_setup()
#endif
using std::cout;
using std::endl;
using std::set;
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#define no_argument 0
#define required_argument 1
#define optional_argument 2
struct option {
const char *a;
int opt;
int *flag;
int val;
};
static inline int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *, int *)
{
return getopt(argc, argv, optstring);
}
#endif
static const struct option g_LongOpts[] = {
{ "help", no_argument, 0, 'h' },
{ "version", no_argument, 0, 'v' },
{ "debug", no_argument, 0, 'D' },
{ "foreground", no_argument, 0, 'f' },
{ "no-color", no_argument, 0, 'n' },
{ "allow-root", no_argument, 0, 'r' },
{ "makeconf", no_argument, 0, 'c' },
{ "makepass", no_argument, 0, 's' },
{ "makepem", no_argument, 0, 'p' },
{ "datadir", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
static void GenerateHelp(const char *appname) {
CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage("\t-h, --help List available command line options (this page)");
CUtils::PrintMessage("\t-v, --version Output version information and exit");
CUtils::PrintMessage("\t-f, --foreground Don't fork into the background");
CUtils::PrintMessage("\t-D, --debug Output debugging information (Implies -f)");
CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output");
CUtils::PrintMessage("\t-r, --allow-root Don't complain if ZNC is run as root");
CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config");
CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL");
#endif /* HAVE_LIBSSL */
CUtils::PrintMessage("\t-d, --datadir Set a different ZNC repository (default is ~/.znc)");
}
static void die(int sig) {
signal(SIGPIPE, SIG_DFL);
CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
CZNC::DestroyInstance();
exit(sig);
}
static void signalHandler(int sig) {
switch (sig) {
case SIGHUP:
CUtils::PrintMessage("Caught SIGHUP");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_REHASH);
break;
case SIGUSR1:
CUtils::PrintMessage("Caught SIGUSR1");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE);
break;
default:
CUtils::PrintMessage("WTF? Signal handler called for a signal it doesn't know?");
}
}
static bool isRoot() {
// User root? If one of these were root, we could switch the others to root, too
return (geteuid() == 0 || getuid() == 0);
}
static void seedPRNG() {
struct timeval tv;
unsigned int seed;
// Try to find a seed which can't be as easily guessed as only time()
if (gettimeofday(&tv, NULL) == 0) {
seed = (unsigned int)tv.tv_sec;
// This is in [0:1e6], which means that roughly 20 bits are
// actually used, let's try to shuffle the high bits.
seed ^= uint32_t((tv.tv_usec << 10) | tv.tv_usec);
} else
seed = (unsigned int)time(NULL);
seed ^= rand();
seed ^= getpid();
srand(seed);
}
int main(int argc, char** argv) {
CString sConfig;
CString sDataDir = "";
thread_setup();
seedPRNG();
CDebug::SetStdoutIsTTY(isatty(1));
int iArg, iOptIndex = -1;
bool bMakeConf = false;
bool bMakePass = false;
bool bAllowRoot = false;
bool bForeground = false;
#ifdef ALWAYS_RUN_IN_FOREGROUND
bForeground = true;
#endif
#ifdef HAVE_LIBSSL
bool bMakePem = false;
#endif
while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, &iOptIndex)) != -1) {
switch (iArg) {
case 'h':
GenerateHelp(argv[0]);
return 0;
case 'v':
cout << CZNC::GetTag() << endl;
cout << CZNC::GetCompileOptionsString() << endl;
return 0;
case 'n':
CDebug::SetStdoutIsTTY(false);
break;
case 'r':
bAllowRoot = true;
break;
case 'c':
bMakeConf = true;
break;
case 's':
bMakePass = true;
break;
case 'p':
#ifdef HAVE_LIBSSL
bMakePem = true;
break;
#else
CUtils::PrintError("ZNC is compiled without SSL support.");
return 1;
#endif /* HAVE_LIBSSL */
case 'd':
sDataDir = CString(optarg);
break;
case 'f':
bForeground = true;
break;
case 'D':
bForeground = true;
CDebug::SetDebug(true);
break;
case '?':
default:
GenerateHelp(argv[0]);
return 1;
}
}
if (optind < argc) {
CUtils::PrintError("Specifying a config file as an argument isn't supported anymore.");
CUtils::PrintError("Use --datadir instead.");
return 1;
}
CZNC::CreateInstance();
CZNC* pZNC = &CZNC::Get();
pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);
#ifdef HAVE_LIBSSL
if (bMakePem) {
pZNC->WritePemFile();
CZNC::DestroyInstance();
return 0;
}
#endif /* HAVE_LIBSSL */
if (bMakePass) {
CString sSalt;
CUtils::PrintMessage("Type your new password.");
CString sHash = CUtils::GetSaltedHashPass(sSalt);
CUtils::PrintMessage("Kill ZNC process, if it's running.");
CUtils::PrintMessage("Then replace password in the <User> section of your config with this:");
// Not PrintMessage(), to remove [**] from the beginning, to ease copypasting
std::cout << "<Pass password>" << std::endl;
std::cout << "\tMethod = " << CUtils::sDefaultHash << std::endl;
std::cout << "\tHash = " << sHash << std::endl;
std::cout << "\tSalt = " << sSalt << std::endl;
std::cout << "</Pass>" << std::endl;
CUtils::PrintMessage("After that start ZNC again, and you should be able to login with the new password.");
CZNC::DestroyInstance();
return 0;
}
{
set<CModInfo> ssGlobalMods;
set<CModInfo> ssUserMods;
set<CModInfo> ssNetworkMods;
CUtils::PrintAction("Checking for list of available modules");
pZNC->GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule);
pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule);
pZNC->GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule);
if (ssGlobalMods.empty() && ssUserMods.empty() && ssNetworkMods.empty()) {
CUtils::PrintStatus(false, "");
CUtils::PrintError("No modules found. Perhaps you didn't install ZNC properly?");
CUtils::PrintError("Read http://wiki.znc.in/Installation for instructions.");
if (!CUtils::GetBoolInput("Do you really want to run ZNC without any modules?", false)) {
CZNC::DestroyInstance();
return 1;
}
}
CUtils::PrintStatus(true, "");
}
if (isRoot()) {
CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid");
CUtils::PrintError("reasons for this and it can, in theory, cause great damage!");
if (!bAllowRoot) {
CZNC::DestroyInstance();
return 1;
}
CUtils::PrintError("You have been warned.");
CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root.");
CUtils::PrintError("ZNC will start in 30 seconds.");
sleep(30);
}
if (bMakeConf) {
if (!pZNC->WriteNewConfig(sConfig)) {
CZNC::DestroyInstance();
return 0;
}
/* Fall through to normal bootup */
}
CString sConfigError;
if (!pZNC->ParseConfig(sConfig, sConfigError)) {
CUtils::PrintError("Unrecoverable config error.");
CZNC::DestroyInstance();
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
CZNC::DestroyInstance();
return 1;
}
if (bForeground) {
int iPid = getpid();
CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
} else {
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
CZNC::DestroyInstance();
return 1;
}
if (iPid > 0) {
// We are the parent. We are done and will go to bed.
CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
/* Don't destroy pZNC here or it will delete the pid file. */
return 0;
}
/* fcntl() locks don't necessarily propagate to forked()
* children. Reacquire the lock here. Use the blocking
* call to avoid race condition with parent exiting.
*/
if (!pZNC->WaitForChildLock()) {
CUtils::PrintError("Child was unable to obtain lock on config file.");
CZNC::DestroyInstance();
return 1;
}
// Redirect std in/out/err to /dev/null
close(0); open("/dev/null", O_RDONLY);
close(1); open("/dev/null", O_WRONLY);
close(2); open("/dev/null", O_WRONLY);
CDebug::SetStdoutIsTTY(false);
// We are the child. There is no way we can be a process group
// leader, thus setsid() must succeed.
setsid();
// Now we are in our own process group and session (no
// controlling terminal). We are independent!
}
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);
sa.sa_handler = signalHandler;
sigaction(SIGHUP, &sa, (struct sigaction*) NULL);
sigaction(SIGUSR1, &sa, (struct sigaction*) NULL);
// Once this signal is caught, the signal handler is reset
// to SIG_DFL. This avoids endless loop with signals.
sa.sa_flags = SA_RESETHAND;
sa.sa_handler = die;
sigaction(SIGINT, &sa, (struct sigaction*) NULL);
sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
sigaction(SIGTERM, &sa, (struct sigaction*) NULL);
int iRet = 0;
try {
pZNC->Loop();
} catch (const CException& e) {
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
break;
case CException::EX_Restart: {
// strdup() because GCC is stupid
char *args[] = {
strdup(argv[0]),
strdup("--datadir"),
strdup(pZNC->GetZNCPath().c_str()),
NULL,
NULL,
NULL,
NULL
};
int pos = 3;
if (CDebug::Debug())
args[pos++] = strdup("--debug");
else if (bForeground)
args[pos++] = strdup("--foreground");
if (!CDebug::StdoutIsTTY())
args[pos++] = strdup("--no-color");
if (bAllowRoot)
args[pos++] = strdup("--allow-root");
// The above code adds 3 entries to args tops
// which means the array should be big enough
CZNC::DestroyInstance();
execvp(args[0], args);
CUtils::PrintError("Unable to restart ZNC [" + CString(strerror(errno)) + "]");
} /* Fall through */
default:
iRet = 1;
}
}
CZNC::DestroyInstance();
return iRet;
}
<commit_msg>Revert "Initialize OpenSSL locking functions"<commit_after>/*
* Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/znc.h>
#include <signal.h>
using std::cout;
using std::endl;
using std::set;
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#define no_argument 0
#define required_argument 1
#define optional_argument 2
struct option {
const char *a;
int opt;
int *flag;
int val;
};
static inline int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *, int *)
{
return getopt(argc, argv, optstring);
}
#endif
static const struct option g_LongOpts[] = {
{ "help", no_argument, 0, 'h' },
{ "version", no_argument, 0, 'v' },
{ "debug", no_argument, 0, 'D' },
{ "foreground", no_argument, 0, 'f' },
{ "no-color", no_argument, 0, 'n' },
{ "allow-root", no_argument, 0, 'r' },
{ "makeconf", no_argument, 0, 'c' },
{ "makepass", no_argument, 0, 's' },
{ "makepem", no_argument, 0, 'p' },
{ "datadir", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
static void GenerateHelp(const char *appname) {
CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage("\t-h, --help List available command line options (this page)");
CUtils::PrintMessage("\t-v, --version Output version information and exit");
CUtils::PrintMessage("\t-f, --foreground Don't fork into the background");
CUtils::PrintMessage("\t-D, --debug Output debugging information (Implies -f)");
CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output");
CUtils::PrintMessage("\t-r, --allow-root Don't complain if ZNC is run as root");
CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config");
CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL");
#endif /* HAVE_LIBSSL */
CUtils::PrintMessage("\t-d, --datadir Set a different ZNC repository (default is ~/.znc)");
}
static void die(int sig) {
signal(SIGPIPE, SIG_DFL);
CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
CZNC::DestroyInstance();
exit(sig);
}
static void signalHandler(int sig) {
switch (sig) {
case SIGHUP:
CUtils::PrintMessage("Caught SIGHUP");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_REHASH);
break;
case SIGUSR1:
CUtils::PrintMessage("Caught SIGUSR1");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE);
break;
default:
CUtils::PrintMessage("WTF? Signal handler called for a signal it doesn't know?");
}
}
static bool isRoot() {
// User root? If one of these were root, we could switch the others to root, too
return (geteuid() == 0 || getuid() == 0);
}
static void seedPRNG() {
struct timeval tv;
unsigned int seed;
// Try to find a seed which can't be as easily guessed as only time()
if (gettimeofday(&tv, NULL) == 0) {
seed = (unsigned int)tv.tv_sec;
// This is in [0:1e6], which means that roughly 20 bits are
// actually used, let's try to shuffle the high bits.
seed ^= uint32_t((tv.tv_usec << 10) | tv.tv_usec);
} else
seed = (unsigned int)time(NULL);
seed ^= rand();
seed ^= getpid();
srand(seed);
}
int main(int argc, char** argv) {
CString sConfig;
CString sDataDir = "";
seedPRNG();
CDebug::SetStdoutIsTTY(isatty(1));
int iArg, iOptIndex = -1;
bool bMakeConf = false;
bool bMakePass = false;
bool bAllowRoot = false;
bool bForeground = false;
#ifdef ALWAYS_RUN_IN_FOREGROUND
bForeground = true;
#endif
#ifdef HAVE_LIBSSL
bool bMakePem = false;
#endif
while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, &iOptIndex)) != -1) {
switch (iArg) {
case 'h':
GenerateHelp(argv[0]);
return 0;
case 'v':
cout << CZNC::GetTag() << endl;
cout << CZNC::GetCompileOptionsString() << endl;
return 0;
case 'n':
CDebug::SetStdoutIsTTY(false);
break;
case 'r':
bAllowRoot = true;
break;
case 'c':
bMakeConf = true;
break;
case 's':
bMakePass = true;
break;
case 'p':
#ifdef HAVE_LIBSSL
bMakePem = true;
break;
#else
CUtils::PrintError("ZNC is compiled without SSL support.");
return 1;
#endif /* HAVE_LIBSSL */
case 'd':
sDataDir = CString(optarg);
break;
case 'f':
bForeground = true;
break;
case 'D':
bForeground = true;
CDebug::SetDebug(true);
break;
case '?':
default:
GenerateHelp(argv[0]);
return 1;
}
}
if (optind < argc) {
CUtils::PrintError("Specifying a config file as an argument isn't supported anymore.");
CUtils::PrintError("Use --datadir instead.");
return 1;
}
CZNC::CreateInstance();
CZNC* pZNC = &CZNC::Get();
pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);
#ifdef HAVE_LIBSSL
if (bMakePem) {
pZNC->WritePemFile();
CZNC::DestroyInstance();
return 0;
}
#endif /* HAVE_LIBSSL */
if (bMakePass) {
CString sSalt;
CUtils::PrintMessage("Type your new password.");
CString sHash = CUtils::GetSaltedHashPass(sSalt);
CUtils::PrintMessage("Kill ZNC process, if it's running.");
CUtils::PrintMessage("Then replace password in the <User> section of your config with this:");
// Not PrintMessage(), to remove [**] from the beginning, to ease copypasting
std::cout << "<Pass password>" << std::endl;
std::cout << "\tMethod = " << CUtils::sDefaultHash << std::endl;
std::cout << "\tHash = " << sHash << std::endl;
std::cout << "\tSalt = " << sSalt << std::endl;
std::cout << "</Pass>" << std::endl;
CUtils::PrintMessage("After that start ZNC again, and you should be able to login with the new password.");
CZNC::DestroyInstance();
return 0;
}
{
set<CModInfo> ssGlobalMods;
set<CModInfo> ssUserMods;
set<CModInfo> ssNetworkMods;
CUtils::PrintAction("Checking for list of available modules");
pZNC->GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule);
pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule);
pZNC->GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule);
if (ssGlobalMods.empty() && ssUserMods.empty() && ssNetworkMods.empty()) {
CUtils::PrintStatus(false, "");
CUtils::PrintError("No modules found. Perhaps you didn't install ZNC properly?");
CUtils::PrintError("Read http://wiki.znc.in/Installation for instructions.");
if (!CUtils::GetBoolInput("Do you really want to run ZNC without any modules?", false)) {
CZNC::DestroyInstance();
return 1;
}
}
CUtils::PrintStatus(true, "");
}
if (isRoot()) {
CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid");
CUtils::PrintError("reasons for this and it can, in theory, cause great damage!");
if (!bAllowRoot) {
CZNC::DestroyInstance();
return 1;
}
CUtils::PrintError("You have been warned.");
CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root.");
CUtils::PrintError("ZNC will start in 30 seconds.");
sleep(30);
}
if (bMakeConf) {
if (!pZNC->WriteNewConfig(sConfig)) {
CZNC::DestroyInstance();
return 0;
}
/* Fall through to normal bootup */
}
CString sConfigError;
if (!pZNC->ParseConfig(sConfig, sConfigError)) {
CUtils::PrintError("Unrecoverable config error.");
CZNC::DestroyInstance();
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
CZNC::DestroyInstance();
return 1;
}
if (bForeground) {
int iPid = getpid();
CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
} else {
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
CZNC::DestroyInstance();
return 1;
}
if (iPid > 0) {
// We are the parent. We are done and will go to bed.
CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
/* Don't destroy pZNC here or it will delete the pid file. */
return 0;
}
/* fcntl() locks don't necessarily propagate to forked()
* children. Reacquire the lock here. Use the blocking
* call to avoid race condition with parent exiting.
*/
if (!pZNC->WaitForChildLock()) {
CUtils::PrintError("Child was unable to obtain lock on config file.");
CZNC::DestroyInstance();
return 1;
}
// Redirect std in/out/err to /dev/null
close(0); open("/dev/null", O_RDONLY);
close(1); open("/dev/null", O_WRONLY);
close(2); open("/dev/null", O_WRONLY);
CDebug::SetStdoutIsTTY(false);
// We are the child. There is no way we can be a process group
// leader, thus setsid() must succeed.
setsid();
// Now we are in our own process group and session (no
// controlling terminal). We are independent!
}
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);
sa.sa_handler = signalHandler;
sigaction(SIGHUP, &sa, (struct sigaction*) NULL);
sigaction(SIGUSR1, &sa, (struct sigaction*) NULL);
// Once this signal is caught, the signal handler is reset
// to SIG_DFL. This avoids endless loop with signals.
sa.sa_flags = SA_RESETHAND;
sa.sa_handler = die;
sigaction(SIGINT, &sa, (struct sigaction*) NULL);
sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
sigaction(SIGTERM, &sa, (struct sigaction*) NULL);
int iRet = 0;
try {
pZNC->Loop();
} catch (const CException& e) {
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
break;
case CException::EX_Restart: {
// strdup() because GCC is stupid
char *args[] = {
strdup(argv[0]),
strdup("--datadir"),
strdup(pZNC->GetZNCPath().c_str()),
NULL,
NULL,
NULL,
NULL
};
int pos = 3;
if (CDebug::Debug())
args[pos++] = strdup("--debug");
else if (bForeground)
args[pos++] = strdup("--foreground");
if (!CDebug::StdoutIsTTY())
args[pos++] = strdup("--no-color");
if (bAllowRoot)
args[pos++] = strdup("--allow-root");
// The above code adds 3 entries to args tops
// which means the array should be big enough
CZNC::DestroyInstance();
execvp(args[0], args);
CUtils::PrintError("Unable to restart ZNC [" + CString(strerror(errno)) + "]");
} /* Fall through */
default:
iRet = 1;
}
}
CZNC::DestroyInstance();
return iRet;
}
<|endoftext|>
|
<commit_before>
#include "DebugHandler.h"
#include "HelloWorld.h"
#include "Manager.h"
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char** argv)
{
QCoreApplication application(argc, argv);
application.setApplicationName("FastCgiQt");
FastCgiQt::DebugHandler handler;
FastCgiQt::Manager manager(&HelloWorld::instance);
return application.exec();
}
<commit_msg>commented that the debug handler is non-necessary<commit_after>
#include "DebugHandler.h"
#include "HelloWorld.h"
#include "Manager.h"
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char** argv)
{
QCoreApplication application(argc, argv);
application.setApplicationName("FastCgiQt");
FastCgiQt::DebugHandler handler; // not neccessary - redirects q{Debug,Fatal,Critical} to syslog
FastCgiQt::Manager manager(&HelloWorld::instance);
return application.exec();
}
<|endoftext|>
|
<commit_before>#include "mempeek_ast.h"
#include "mempeek_exceptions.h"
#include "console.h"
#if defined( YYDEBUG ) && YYDEBUG != 0
#include "mempeek_parser.h"
#include "parser.h"
#endif
#include <iostream>
#include <string.h>
#include <signal.h>
using namespace std;
static void signal_handler( int )
{
ASTNode::set_terminate();
}
static void parse( const char* str, bool is_file )
{
ASTNode::clear_terminate();
signal( SIGABRT, signal_handler );
signal( SIGINT, signal_handler );
signal( SIGTERM, signal_handler );
try {
ASTNode* yyroot = ASTNode::parse( str, is_file );
#ifdef ASTDEBUG
cout << "executing ASTNode[" << yyroot << "]" << endl;
#endif
yyroot->execute();
delete yyroot;
}
catch( ASTExceptionBreak& ) {
// nothing to do
}
catch( ASTExceptionTerminate& ) {
cout << endl << "terminated execution" << endl;
}
catch( const ASTCompileException& ex ) {
cerr << ex.get_location() << "compile error: " << ex.what() << endl;
}
catch( const ASTRuntimeException& ex ) {
cerr << ex.get_location() << "runtime error: " << ex.what() << endl;
}
catch( ... ) {
signal( SIGABRT, SIG_DFL );
signal( SIGINT, SIG_DFL );
signal( SIGTERM, SIG_DFL );
throw;
}
signal( SIGABRT, SIG_DFL );
signal( SIGINT, SIG_DFL );
signal( SIGTERM, SIG_DFL );
}
int main( int argc, char** argv )
{
#if defined( YYDEBUG ) && YYDEBUG != 0
yydebug = 1;
#endif
Console console( "mempeek", "~/.mempeek_history" );
MMap::enable_signal_handler();
try {
bool is_interactive = false;
bool has_commands = false;
for( int i = 1; i < argc; i++ )
{
if( strcmp( argv[i], "-i" ) == 0 ) is_interactive = true;
else if( strcmp( argv[i], "-I" ) == 0 ) {
if( ++i >= argc ) {
cerr << "missing include path" << endl;
break;
}
ASTNode::add_include_path( argv[i] );
}
else if( strcmp( argv[i], "-c" ) == 0 ) {
if( ++i >= argc ) {
cerr << "missing command" << endl;
break;
}
// TODO: parser should treat EOF as end of statement
string cmd = string( argv[i] ) + '\n';
parse( cmd.c_str(), false );
has_commands = true;
}
else {
parse( argv[i], true );
}
}
if( is_interactive || !has_commands ) {
for(;;) {
string line = console.get_line();
parse( line.c_str(), false );
}
}
}
catch( ASTExceptionQuit ) {
// nothing to do
}
return 0;
}
<commit_msg>do not enter interactive mode when running scripts<commit_after>#include "mempeek_ast.h"
#include "mempeek_exceptions.h"
#include "console.h"
#if defined( YYDEBUG ) && YYDEBUG != 0
#include "mempeek_parser.h"
#include "parser.h"
#endif
#include <iostream>
#include <string.h>
#include <signal.h>
using namespace std;
static void signal_handler( int )
{
ASTNode::set_terminate();
}
static void parse( const char* str, bool is_file )
{
ASTNode::clear_terminate();
signal( SIGABRT, signal_handler );
signal( SIGINT, signal_handler );
signal( SIGTERM, signal_handler );
try {
ASTNode* yyroot = ASTNode::parse( str, is_file );
#ifdef ASTDEBUG
cout << "executing ASTNode[" << yyroot << "]" << endl;
#endif
yyroot->execute();
delete yyroot;
}
catch( ASTExceptionBreak& ) {
// nothing to do
}
catch( ASTExceptionTerminate& ) {
cout << endl << "terminated execution" << endl;
}
catch( const ASTCompileException& ex ) {
cerr << ex.get_location() << "compile error: " << ex.what() << endl;
}
catch( const ASTRuntimeException& ex ) {
cerr << ex.get_location() << "runtime error: " << ex.what() << endl;
}
catch( ... ) {
signal( SIGABRT, SIG_DFL );
signal( SIGINT, SIG_DFL );
signal( SIGTERM, SIG_DFL );
throw;
}
signal( SIGABRT, SIG_DFL );
signal( SIGINT, SIG_DFL );
signal( SIGTERM, SIG_DFL );
}
int main( int argc, char** argv )
{
#if defined( YYDEBUG ) && YYDEBUG != 0
yydebug = 1;
#endif
Console console( "mempeek", "~/.mempeek_history" );
MMap::enable_signal_handler();
try {
bool is_interactive = false;
bool has_commands = false;
for( int i = 1; i < argc; i++ )
{
if( strcmp( argv[i], "-i" ) == 0 ) is_interactive = true;
else if( strcmp( argv[i], "-I" ) == 0 ) {
if( ++i >= argc ) {
cerr << "missing include path" << endl;
break;
}
ASTNode::add_include_path( argv[i] );
}
else if( strcmp( argv[i], "-c" ) == 0 ) {
if( ++i >= argc ) {
cerr << "missing command" << endl;
break;
}
// TODO: parser should treat EOF as end of statement
string cmd = string( argv[i] ) + '\n';
parse( cmd.c_str(), false );
has_commands = true;
}
else {
parse( argv[i], true );
has_commands = true;
}
}
if( is_interactive || !has_commands ) {
for(;;) {
string line = console.get_line();
parse( line.c_str(), false );
}
}
}
catch( ASTExceptionQuit ) {
// nothing to do
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "Base/Renderer.hpp"
int main() {
Renderer* renderer = Renderer::makeRenderer(Renderer::BACKEND::OpenGL);
return 0;
}
<commit_msg>Fix memory leak<commit_after>#include "Base/Renderer.hpp"
int main() {
Renderer* renderer = Renderer::makeRenderer(Renderer::BACKEND::OpenGL);
delete renderer;
return 0;
}
<|endoftext|>
|
<commit_before>/* main.cpp */
//-----------------------------------------------------------------------
//include files
//-----------------------------------------------------------------------
#include <iostream>
#include <oauth.h>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <opencv2/opencv.hpp>
#include <opencv2/superres/optical_flow.hpp>
#include "sequentialCaptCurrBuffer.h"
#include "sequentialCalcDiffImg.h"
#include "sequentialCalcOptFlow.h"
#include "detectMotionObject.h"
#include "tweet.h"
#include "webclient.h"
// #include "mykey.h"
#include "jphacks_key.h"
//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------
//***********************************************************************
// Function : main |
//***********************************************************************
int main(void)
{
// buffering off for debug on pty
setvbuf( stdout, NULL, _IONBF, BUFSIZ );
WebClient::initialize();
TwitterClient tc(c_key, c_sec, t_key, t_sec);
std::string filename("../../skeleton.png");
cv::Mat src = cv::imread(filename);
// current frame の連続取得(別スレッド)
cv::Mat curr_tmp;
bool break_flag = false;
thread cap_th( sequentialCaptCurrBuffer, ref(curr_tmp), ref(break_flag));
while( curr_tmp.empty() ){
sleep(0);
}
// 画像差分の連続算出(別スレッド)
cv::Mat diff_tmp;
thread diff_th( sequentialCalcDiffImg, ref(curr_tmp), ref(diff_tmp), ref(break_flag));
while( diff_tmp.empty() ){
sleep(0);
}
// // optical flow の連続算出(別スレッド)
// cv::Mat flow_tmp;
// thread optflow_th( sequentialCalcOptFlow, ref(curr_tmp), ref(flow_tmp), ref(break_flag));
// while( flow_tmp.empty() ){
// sleep(0);
// }
while( cv::waitKey(1) != '\x1b' ) {
cap_mtx.lock();
cv::Mat curr = curr_tmp.clone();
cap_mtx.unlock();
diff_mtx.lock();
cv::Mat diff = diff_tmp.clone();
diff_mtx.unlock();
cv::imshow("diff", diff);
// opt_flow_mtx.lock();
// cv::Mat flow = flow_tmp.clone();
// opt_flow_mtx.unlock();
// // optical flow to RGB
// cv::Mat flow_rgb;
// optFlow2RGB( flow, flow_rgb );
// // 表示
// cv::imshow("optical flow", flow_rgb);
// // グレースケール
// cv::Mat gray;
// cv::cvtColor( flow_rgb, gray, CV_BGR2GRAY);
vector<cv::Rect> detected_obj;
detectMotionObject(curr, diff, detected_obj);
}
// スレッドの終了
break_flag = true;
cap_th.join();
diff_th.join();
// optflow_th.join();
//return ( tc.tweet(message, src) ) ? 0 : 1;
return 0;
}
<commit_msg>optical flow での結果が良くないためコメントアウト<commit_after>/* main.cpp */
//-----------------------------------------------------------------------
//include files
//-----------------------------------------------------------------------
#include <iostream>
#include <oauth.h>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <opencv2/opencv.hpp>
#include <opencv2/superres/optical_flow.hpp>
#include "sequentialCaptCurrBuffer.h"
#include "sequentialCalcDiffImg.h"
#include "sequentialCalcOptFlow.h"
#include "optFlow2RGB.h"
#include "detectMotionObject.h"
#include "tweet.h"
#include "webclient.h"
// #include "mykey.h"
#include "jphacks_key.h"
//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------
//***********************************************************************
// Function : main |
//***********************************************************************
int main(void)
{
// buffering off for debug on pty
setvbuf( stdout, NULL, _IONBF, BUFSIZ );
WebClient::initialize();
TwitterClient tc(c_key, c_sec, t_key, t_sec);
std::string filename("../../skeleton.png");
cv::Mat src = cv::imread(filename);
// current frame の連続取得(別スレッド)
cv::Mat curr_tmp;
bool break_flag = false;
thread cap_th( sequentialCaptCurrBuffer, ref(curr_tmp), ref(break_flag));
while( curr_tmp.empty() ){
sleep(0);
}
// 画像差分の連続算出(別スレッド)
cv::Mat diff_tmp;
thread diff_th( sequentialCalcDiffImg, ref(curr_tmp), ref(diff_tmp), ref(break_flag));
while( diff_tmp.empty() ){
sleep(0);
}
// // optical flow の連続算出(別スレッド)
// cv::Mat flow_tmp;
// thread optflow_th( sequentialCalcOptFlow, ref(curr_tmp), ref(flow_tmp), ref(break_flag));
// while( flow_tmp.empty() ){
// sleep(0);
// }
while( cv::waitKey(1) != '\x1b' ) {
cap_mtx.lock();
cv::Mat curr = curr_tmp.clone();
cap_mtx.unlock();
diff_mtx.lock();
cv::Mat diff = diff_tmp.clone();
diff_mtx.unlock();
cv::imshow("diff", diff);
// opt_flow_mtx.lock();
// cv::Mat flow = flow_tmp.clone();
// opt_flow_mtx.unlock();
// // optical flow to RGB
// cv::Mat flow_rgb;
// optFlow2RGB( flow, flow_rgb );
// // 表示
// cv::imshow("optical flow", flow_rgb);
// // グレースケール
// cv::Mat gray;
// cv::cvtColor( flow_rgb, gray, CV_BGR2GRAY);
vector<cv::Rect> detected_obj_diff, detected_obj_optflow;
detectMotionObject(curr, diff, detected_obj_diff);
// detectMotionObject(curr, gray, detected_obj_optflow);
for(auto i: detected_obj_diff){
cv::rectangle(curr, i.tl(), i.br(), cv::Scalar(255, 0, 0), 2, CV_AA);
}
// for(auto i: detected_obj_optflow){
// cv::rectangle(curr, i.tl(), i.br(), cv::Scalar(0, 255, 0), 2, CV_AA);
// }
cv::imshow("dist", curr);
}
// スレッドの終了
break_flag = true;
cap_th.join();
diff_th.join();
// optflow_th.join();
//return ( tc.tweet(message, src) ) ? 0 : 1;
return 0;
}
<|endoftext|>
|
<commit_before>
/*
Author(s):
Vincent Heins
Description:
This is the main file!?
I mean, i know this file is a BIT shitty but who cares...
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <curl/curl.h>
#include <mutex>
#include <thread>
/*struct MemStruct
{
char * memory;
size_t size;
};
class FReqs
{
public:
std::string URLGet(const char * input);
//std::string URLPost(char *input);
private:
//static size_t writer(void *contents, size_t size, size_t nmemb, void *userp);
//static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in);
};
*/
/*std::string FReqs::URLGet(const char * input)
{
std::cout << input << "\n";
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL;
curl = curl_easy_init();
std::cout << input << "\n";
std::string str;
if (curl)
{
std::cout << input << "\n";
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, input);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter);
res = curl_easy_perform(curl);
std::cout << input << "\n";
if (res == CURLE_OK)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if ((CURLE_OK == res) && ct)
return str;
}
}
return str;
}*/
//like the example from https://curl.haxx.se/libcurl/c/getinmemory.html
static size_t CallbackWriter(void *contents, size_t size, size_t nmemb, void *buf)
{
((std::string *)buf)->append((char *)contents, size * nmemb);
return size * nmemb;
};
std::string fetchGET(/*char *output, const int &outputSize,*/ const char *function)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
curl = curl_easy_init();
std::string str;
if (curl)
{
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, function);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter);
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
/*if ((CURLE_OK == res) && ct)
break;*/
}
}
str.resize(10240);
/*const char * c_str = str.c_str();
strncpy(output, c_str, str.size());*/
return str;
};
struct FetchResult
{
bool finished;
int key;
std::string result;
};
class FetchResulting
{
public:
std::mutex resMtx;
std::vector<FetchResult> results;
};
FetchResulting *fres;
void newThread(const char *function)
{
std::thread fetchRequest(fetchResult, function);
};
void fetchResult(const char * function)
{
fres->resMtx->lock();
FetchResult *nRes;
nRes.finished = false;
nRes.key = fres->results->size();
fres->results->push_back(&nRes);
fres->resMtx->unlock();
nRes.result = fetchGET(function);
nRes.finished = true;
};
#ifdef __GNUC__
__attribute__((constructor)) void a3urlfetch_initialization()
{
std::cout << "Sentence which should be displayed on server whilst initializing!"
<< "\n";
};
extern "C" {
void RVExtension(char *output, int outputSize, const char *function);
};
void RVExtension(char *output, int outputSize, const char *function)
{
newThread(function);
};
#elif _MSC_VER
#include <windows.h>
#include <shellapi.h>
bool APIENTRY DllMain(HMODULE hMod, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
//call of dll
}
break;
case DLL_PROCESS_DETACH:
{
//stop of dll
}
break;
};
return true;
};
extern "C" {
_declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function);
};
void __stdcall RVExtension(char *output, int outputSize, const char *function)
{
outputSize = -1;
fhandle->callExtension(output, outputSize, function);
};
#endif
<commit_msg>Changed main.cpp<commit_after>
/*
Author(s):
Vincent Heins
Description:
This is the main file!?
I mean, i know this file is a BIT shitty but who cares...
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <curl/curl.h>
#include <mutex>
#include <thread>
/*struct MemStruct
{
char * memory;
size_t size;
};
class FReqs
{
public:
std::string URLGet(const char * input);
//std::string URLPost(char *input);
private:
//static size_t writer(void *contents, size_t size, size_t nmemb, void *userp);
//static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in);
};
*/
/*std::string FReqs::URLGet(const char * input)
{
std::cout << input << "\n";
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL;
curl = curl_easy_init();
std::cout << input << "\n";
std::string str;
if (curl)
{
std::cout << input << "\n";
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, input);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter);
res = curl_easy_perform(curl);
std::cout << input << "\n";
if (res == CURLE_OK)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if ((CURLE_OK == res) && ct)
return str;
}
}
return str;
}*/
//like the example from https://curl.haxx.se/libcurl/c/getinmemory.html
static size_t CallbackWriter(void *contents, size_t size, size_t nmemb, void *buf)
{
((std::string *)buf)->append((char *)contents, size * nmemb);
return size * nmemb;
};
std::string fetchGET(/*char *output, const int &outputSize,*/ const char *function)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
curl = curl_easy_init();
std::string str;
if (curl)
{
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, function);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter);
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
/*if ((CURLE_OK == res) && ct)
break;*/
}
}
str.resize(10240);
/*const char * c_str = str.c_str();
strncpy(output, c_str, str.size());*/
return str;
};
struct FetchResult
{
bool finished;
int key;
std::string result;
};
class FetchResulting
{
public:
std::mutex resMtx;
std::vector<FetchResult> results;
};
FetchResulting *fres;
void fetchResult(const char * function)
{
fres->resMtx->lock();
FetchResult *nRes;
nRes.finished = false;
nRes.key = fres->results->size();
fres->results->push_back(&nRes);
fres->resMtx->unlock();
nRes.result = fetchGET(function);
nRes.finished = true;
};
void newThread(const char *function)
{
std::thread fetchRequest(fetchResult, function);
};
#ifdef __GNUC__
__attribute__((constructor)) void a3urlfetch_initialization()
{
std::cout << "Sentence which should be displayed on server whilst initializing!"
<< "\n";
};
extern "C" {
void RVExtension(char *output, int outputSize, const char *function);
};
void RVExtension(char *output, int outputSize, const char *function)
{
newThread(function);
};
#elif _MSC_VER
#include <windows.h>
#include <shellapi.h>
bool APIENTRY DllMain(HMODULE hMod, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
//call of dll
}
break;
case DLL_PROCESS_DETACH:
{
//stop of dll
}
break;
};
return true;
};
extern "C" {
_declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function);
};
void __stdcall RVExtension(char *output, int outputSize, const char *function)
{
outputSize = -1;
fhandle->callExtension(output, outputSize, function);
};
#endif
<|endoftext|>
|
<commit_before>#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "net/net.h"
#include "net/addr.h"
char const *gHostPort = "5413";
char const *gClientPort = "5414";
//-------------------------------------------------------------------------------------------------------
static std::string WindowsErrorAsString( DWORD error_id )
{
if (error_id != 0) {
LPSTR buffer;
DWORD size = FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_id,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)(&buffer),
0, NULL );
std::string msg( buffer, size );
LocalFree( buffer );
return msg;
} else {
return "";
}
}
//-------------------------------------------------------------------------------------------------------
static bool PrintAddress( addrinfo *addr, void* )
{
char addr_name[INET6_ADDRSTRLEN];
GetAddressName( addr_name, INET6_ADDRSTRLEN, addr->ai_addr );
printf("Address family[%i] type[%i] %s\n", addr->ai_family, addr->ai_socktype, addr_name );
return false;
}
//-------------------------------------------------------------------------------------------------------
// This method of looping through addresses is going to be important for both
// hosting and connection.
static void ListAddressesForHost( char const *host_name, char const *service )
{
addrinfo *addr = AllocAddressesForHost( host_name, service, AF_UNSPEC, SOCK_STREAM, true );
ForEachAddress( addr, PrintAddress, nullptr );
freeaddrinfo(addr);
}
//-------------------------------------------------------------------------------------------------------
static bool TryToBind( addrinfo *addr, void *sock_ptr )
{
SOCKET *sock = (SOCKET*)sock_ptr;
SOCKET host_sock = INVALID_SOCKET;
char addr_name[INET6_ADDRSTRLEN];
GetAddressName( addr_name, INET6_ADDRSTRLEN, addr->ai_addr );
printf("Attempt to bind on: %s\n", addr_name);
host_sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (host_sock != INVALID_SOCKET) {
if (bind(host_sock, addr->ai_addr, (int)(addr->ai_addrlen)) == SOCKET_ERROR) {
closesocket(host_sock);
host_sock = INVALID_SOCKET;
return false;
}
else {
// Connecting on address
printf("Bound to : %s\n", addr_name);
*sock = host_sock;
return true;
}
} else {
printf( "Failed to create socket?!\n" );
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static bool TryToConnect(addrinfo *addr, void *sock_ptr)
{
SOCKET *sock = (SOCKET*)sock_ptr;
SOCKET host_sock = INVALID_SOCKET;
char addr_name[INET6_ADDRSTRLEN];
GetAddressName(addr_name, INET6_ADDRSTRLEN, addr->ai_addr);
printf("Attempt to connect to: %s\n", addr_name);
host_sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (host_sock != INVALID_SOCKET) {
if (connect(host_sock, addr->ai_addr, (int)(addr->ai_addrlen)) == SOCKET_ERROR) {
closesocket(host_sock);
host_sock = INVALID_SOCKET;
return false;
}
else {
// Connecting on address
printf("Connected to : %s\n", addr_name);
*sock = host_sock;
return true;
}
}
else {
printf("Failed to create socket?!\n");
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static SOCKET BindAddress( char const *ip, char const *port, int family = AF_UNSPEC, int type = SOCK_STREAM )
{
SOCKET host_sock = INVALID_SOCKET;
addrinfo *addr = AllocAddressesForHost( ip, port, family, type, true );
ForEachAddress( addr, TryToBind, &host_sock );
FreeAddresses(addr);
return host_sock;
}
//-------------------------------------------------------------------------------------------------------
static void NetworkHost( char const *port )
{
char const *host_name = AllocLocalHostName();
SOCKET sock = BindAddress( host_name, port, AF_INET, SOCK_DGRAM );
FreeLocalHostName(host_name);
if (sock == INVALID_SOCKET) {
printf( "Failed to create listen socket.\n" );
return;
}
// Don't need to listen for DGRAM sockets
/*
// For setting blocking status
u_long non_blocking = 1;
ioctlsocket( sock, FIONBIO, &non_blocking )
*/
printf( "Waiting for messages...\n" );
sockaddr_storage their_addr;
char buffer[2048];
for (;;) {
int addr_size = sizeof(their_addr);
int recvd = recvfrom( sock, buffer, 2048, 0, (sockaddr*)&their_addr, &addr_size );
char from_name[128];
GetAddressName( from_name, 128, (sockaddr*)&their_addr );
if (recvd > 0) {
buffer[recvd] = NULL;
printf( "Received Message[%s] from %s\n", buffer, from_name );
} else {
int error = WSAGetLastError();
printf( "recvfrom error: %i, %i\n", recvd, error );
}
}
closesocket(sock);
}
class SpamHelper
{
public:
SOCKET sock;
char const *msg;
};
static bool SpamMessage( addrinfo *addr, void *user_arg )
{
SpamHelper *helper = (SpamHelper*)user_arg;
int sent = sendto( helper->sock, helper->msg, strlen(helper->msg), 0,
addr->ai_addr, addr->ai_addrlen );
char name[128];
GetAddressName( name, 128, addr->ai_addr );
printf( "Spammed %iB message to [%s]\n", sent, name );
if (sent <= 0) {
printf( "Error: %i\n", WSAGetLastError() );
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static void NetworkClient( char const *target, char const *port, char const *msg )
{
char const *host_name = AllocLocalHostName();
SOCKET sock = BindAddress(host_name, gClientPort, AF_INET, SOCK_DGRAM);
FreeLocalHostName(host_name);
if (sock == INVALID_SOCKET) {
printf( "Could not bind adddress.\n" );
return;
}
SpamHelper helper;
helper.sock = sock;
helper.msg = msg;
addrinfo *spam = AllocAddressesForHost( target, port, AF_UNSPEC, SOCK_DGRAM, false );
ForEachAddress( spam, SpamMessage, &helper );
FreeAddresses( spam );
closesocket( sock );
}
//-------------------------------------------------------------------------------------------------------
int main( int argc, char const **argv )
{
if (!NetSystemInit()) {
printf( "Failed to initialize net system.\n" );
_getch();
return false;
}
// List Addresses
char const *hostname = AllocLocalHostName();
ListAddressesForHost( hostname, gHostPort );
FreeLocalHostName(hostname);
// Host/Client Logic
if ((argc <= 1) || (_strcmpi( argv[1], "sock" ) == 0)) {
printf( "Hosting...\n" );
NetworkHost( gHostPort );
} else if (argc > 2) {
char const *addr = argv[1];
char const *msg = argv[2];
printf( "Sending message \"%s\" to [%s]\n", msg, addr );
NetworkClient( addr, gHostPort, msg );
} else {
printf( "Either past \"sock\" or \"<addr> <msg>\"\n" );
}
NetSystemDeinit();
printf( "Press any key to continue...\n" );
_getch();
return 0;
}
<commit_msg>Quick broadcast example. Last bit of socket mystery people need for the assignment.<commit_after>#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "net/net.h"
#include "net/addr.h"
char const *gHostPort = "5413";
char const *gClientPort = "5414";
//-------------------------------------------------------------------------------------------------------
static std::string WindowsErrorAsString( DWORD error_id )
{
if (error_id != 0) {
LPSTR buffer;
DWORD size = FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_id,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)(&buffer),
0, NULL );
std::string msg( buffer, size );
LocalFree( buffer );
return msg;
} else {
return "";
}
}
//-------------------------------------------------------------------------------------------------------
static bool PrintAddress( addrinfo *addr, void* )
{
char addr_name[INET6_ADDRSTRLEN];
GetAddressName( addr_name, INET6_ADDRSTRLEN, addr->ai_addr );
printf("Address family[%i] type[%i] %s\n", addr->ai_family, addr->ai_socktype, addr_name );
return false;
}
//-------------------------------------------------------------------------------------------------------
// This method of looping through addresses is going to be important for both
// hosting and connection.
static void ListAddressesForHost( char const *host_name, char const *service )
{
addrinfo *addr = AllocAddressesForHost( host_name, service, AF_UNSPEC, SOCK_STREAM, true );
ForEachAddress( addr, PrintAddress, nullptr );
freeaddrinfo(addr);
}
//-------------------------------------------------------------------------------------------------------
static bool TryToBind( addrinfo *addr, void *sock_ptr )
{
SOCKET *sock = (SOCKET*)sock_ptr;
SOCKET host_sock = INVALID_SOCKET;
char addr_name[INET6_ADDRSTRLEN];
GetAddressName( addr_name, INET6_ADDRSTRLEN, addr->ai_addr );
printf("Attempt to bind on: %s\n", addr_name);
host_sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (host_sock != INVALID_SOCKET) {
if (bind(host_sock, addr->ai_addr, (int)(addr->ai_addrlen)) == SOCKET_ERROR) {
closesocket(host_sock);
host_sock = INVALID_SOCKET;
return false;
}
else {
// Connecting on address
printf("Bound to : %s\n", addr_name);
*sock = host_sock;
return true;
}
} else {
printf( "Failed to create socket?!\n" );
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static bool TryToConnect(addrinfo *addr, void *sock_ptr)
{
SOCKET *sock = (SOCKET*)sock_ptr;
SOCKET host_sock = INVALID_SOCKET;
char addr_name[INET6_ADDRSTRLEN];
GetAddressName(addr_name, INET6_ADDRSTRLEN, addr->ai_addr);
printf("Attempt to connect to: %s\n", addr_name);
host_sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (host_sock != INVALID_SOCKET) {
if (connect(host_sock, addr->ai_addr, (int)(addr->ai_addrlen)) == SOCKET_ERROR) {
closesocket(host_sock);
host_sock = INVALID_SOCKET;
return false;
}
else {
// Connecting on address
printf("Connected to : %s\n", addr_name);
*sock = host_sock;
return true;
}
}
else {
printf("Failed to create socket?!\n");
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static SOCKET BindAddress( char const *ip, char const *port, int family = AF_UNSPEC, int type = SOCK_STREAM )
{
SOCKET host_sock = INVALID_SOCKET;
addrinfo *addr = AllocAddressesForHost( ip, port, family, type, true );
ForEachAddress( addr, TryToBind, &host_sock );
FreeAddresses(addr);
return host_sock;
}
//-------------------------------------------------------------------------------------------------------
static void NetworkHost( char const *port )
{
char const *host_name = AllocLocalHostName();
SOCKET sock = BindAddress( host_name, port, AF_INET, SOCK_DGRAM );
FreeLocalHostName(host_name);
if (sock == INVALID_SOCKET) {
printf( "Failed to create listen socket.\n" );
return;
}
// Don't need to listen for DGRAM sockets
/*
// For setting blocking status
u_long non_blocking = 1;
ioctlsocket( sock, FIONBIO, &non_blocking )
*/
printf( "Waiting for messages...\n" );
sockaddr_storage their_addr;
char buffer[2048];
for (;;) {
int addr_size = sizeof(their_addr);
int recvd = recvfrom( sock, buffer, 2048, 0, (sockaddr*)&their_addr, &addr_size );
char from_name[128];
GetAddressName( from_name, 128, (sockaddr*)&their_addr );
if (recvd > 0) {
buffer[recvd] = NULL;
printf( "Received Message[%s] from %s\n", buffer, from_name );
} else {
int error = WSAGetLastError();
printf( "recvfrom error: %i, %i\n", recvd, error );
}
}
closesocket(sock);
}
class SpamHelper
{
public:
SOCKET sock;
char const *msg;
};
static bool SpamMessage( addrinfo *addr, void *user_arg )
{
SpamHelper *helper = (SpamHelper*)user_arg;
int sent = sendto( helper->sock, helper->msg, strlen(helper->msg), 0,
addr->ai_addr, addr->ai_addrlen );
char name[128];
GetAddressName( name, 128, addr->ai_addr );
printf( "Spammed %iB message to [%s]\n", sent, name );
if (sent <= 0) {
printf( "Error: %i\n", WSAGetLastError() );
}
return false;
}
//-------------------------------------------------------------------------------------------------------
static void NetworkClient( char const *target, char const *port, char const *msg )
{
char const *host_name = AllocLocalHostName();
SOCKET sock = BindAddress(host_name, gClientPort, AF_INET, SOCK_DGRAM);
FreeLocalHostName(host_name);
if (sock == INVALID_SOCKET) {
printf( "Could not bind adddress.\n" );
return;
}
SpamHelper helper;
helper.sock = sock;
helper.msg = msg;
addrinfo *spam = AllocAddressesForHost( target, port, AF_UNSPEC, SOCK_DGRAM, false );
ForEachAddress( spam, SpamMessage, &helper );
FreeAddresses( spam );
closesocket( sock );
}
static void NetworkBroadcast( char const *msg )
{
SOCKET sock = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP );
sockaddr_in addr;
memset( &addr, 0, sizeof(addr) );
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addr.sin_port = htons(0);
addr.sin_family = PF_INET;
int broadcast = 1;
int error = setsockopt( sock, SOL_SOCKET, SO_BROADCAST, (char*)&broadcast, sizeof(broadcast) );
if (error == SOCKET_ERROR) {
printf( "Failed to set broadcast. %u\n", WSAGetLastError() );
closesocket(sock);
return;
}
error = bind( sock, (sockaddr*)&addr, sizeof(addr) );
if (error == SOCKET_ERROR) {
printf( "Failed to bind broadcast. %u\n", WSAGetLastError() );
closesocket(sock);
return;
}
sockaddr_in out_addr;
memset( &out_addr, 0, sizeof(out_addr) );
out_addr.sin_addr.S_un.S_addr = htonl(-1);
out_addr.sin_port = htons(5413);
out_addr.sin_family = PF_INET;
int sent = sendto( sock, msg, strlen(msg), 0, (sockaddr*)&out_addr, sizeof(out_addr) );
printf( "Broadcast message: %i sent.\n", sent );
closesocket(sock);
}
//-------------------------------------------------------------------------------------------------------
int main( int argc, char const **argv )
{
if (!NetSystemInit()) {
printf( "Failed to initialize net system.\n" );
_getch();
return false;
}
// List Addresses
char const *hostname = AllocLocalHostName();
ListAddressesForHost( hostname, gHostPort );
FreeLocalHostName(hostname);
// Host/Client Logic
if ((argc <= 1) || (_strcmpi( argv[1], "sock" ) == 0)) {
printf( "Hosting...\n" );
NetworkHost( gHostPort );
} else if (argc > 2) {
char const *addr = argv[1];
char const *msg = argv[2];
printf( "Sending message \"%s\" to [%s]\n", msg, addr );
NetworkClient( addr, gHostPort, msg );
} else {
char const *msg = argv[1];
printf( "Broadcast message \"%s\".\n", msg );
NetworkBroadcast( msg );
}
NetSystemDeinit();
printf( "Press any key to continue...\n" );
_getch();
return 0;
}
<|endoftext|>
|
<commit_before>#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <lua/lua.hpp>
#include <vector>
#include <fmt/format.h>
#include "terrian_config.hpp"
#include "matrixstacksingleton.hpp"
#include "IPolygon.hpp"
#include "polygon.hpp"
#include "logiccontext.hpp"
#include "visualcontext.hpp"
#include "heightmap.hpp"
#include "line.hpp"
#include "triangle.hpp"
#include "circle.hpp"
#include "addtodrawqueue.hpp"
#include "luae/script.hpp"
#include "luae/scriptmanager.hpp"
#include "luae/scriptheightmap.hpp"
#include "luae/scriptriangle.hpp"
#include "luae/scriptmouse.hpp"
//For stringifying preprocessor values
#define xstr(s) str(s)
#define str(s) #s
#define concat(first, second) first second
static struct LogicContext logicContext;
static glm::vec3 ray_world;
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
glm::vec3 up = glm::vec3(glm::vec4(0.0, 1.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 down = glm::vec3(glm::vec4(0.0, -1.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 left = glm::vec3(glm::vec4(-1.0, 0.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 right = glm::vec3(glm::vec4(1.0, 0.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 back = glm::vec3(glm::vec4(0.0, 0.0, -1.0, 1.0) * logicContext.modelview);
glm::vec3 forward = glm::vec3(glm::vec4(0.0, 0.0, 1.0, 1.0) * logicContext.modelview);
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS){
printf("Triangle 1 Model Matrix: %s\n", glm::to_string(logicContext.modelview).c_str());
}
if(key == GLFW_KEY_R && action == GLFW_RELEASE){
logicContext.modelview = glm::mat4();
}
if(key == GLFW_KEY_LEFT && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, up);
}
else if(key == GLFW_KEY_RIGHT && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, down);
}
else if(key == GLFW_KEY_LEFT && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, left * 0.1f);
}
else if(key == GLFW_KEY_RIGHT && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, right * 0.1f);
}
if(key == GLFW_KEY_UP && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, up * 0.1f);
}
else if(key == GLFW_KEY_DOWN && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, down * 0.1f);
}
else if(key == GLFW_KEY_UP && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, left);
}
else if(key == GLFW_KEY_DOWN && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, right);
}else if(key == GLFW_KEY_UP && mods == GLFW_MOD_CONTROL){
logicContext.modelview = glm::translate(logicContext.modelview, back * 0.1f);
}else if(key == GLFW_KEY_DOWN && mods == GLFW_MOD_CONTROL){
logicContext.modelview = glm::translate(logicContext.modelview, forward * 0.1f);
}
}
static void calcWorldPickRay(GLFWwindow *window){
//Build ray from mouse
double mouseX;
double mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
glm::vec4 ray_clip = glm::vec4((2.0f * mouseX) / VisualContext::width - 1.0f, 1.0f - (2.0f * mouseY) / VisualContext::height, -1.0f, 1.0f);
glm::vec4 ray_eye = glm::inverse(VisualContext::projection_matrix) * ray_clip;
ray_eye.z = -1.0f;
ray_eye.w = 1.0f;
ray_world = glm::vec3(glm::inverse(logicContext.modelview) * ray_eye);
// ray_world = glm::normalize(ray_world);
}
int main(void) {
GLFWwindow *window = VisualContext::CreateGLFWWindow(key_callback);
GLuint shader_program = VisualContext::make_shader_program(concat(xstr(SHADERS_DIR), "/shader.vert"), concat(xstr(SHADERS_DIR), "/shader.frag"));
glUseProgram(shader_program);
GLuint vertShaderLocation = glGetAttribLocation(shader_program, "vert");
GLuint uloc_project = glGetUniformLocation(shader_program, "project");
GLuint uloc_modelview = glGetUniformLocation(shader_program, "modelview");
std::vector<IPolygon*> drawQueue;
AddToDrawQueueCommand::SetQueue(&drawQueue);
/* Compute the projection matrix */
VisualContext::projection_matrix = glm::perspective(VisualContext::view_angle, VisualContext::aspect_ratio, VisualContext::z_near, VisualContext::z_far);
logicContext.uloc_modelview = uloc_modelview;
/* Set the camera position */
logicContext.modelview = glm::translate(logicContext.modelview, glm::vec3(0.0f, 0.0f, -20.0f));
logicContext.modelview = glm::rotate(logicContext.modelview, 0.0f, glm::vec3(-1.0f, 0.0f, 0.0f));
/*
HeightmapSettings heightmapSettings;
heightmapSettings.widthDensity = 10;
heightmapSettings.origin = glm::vec3(0.0f, 0.0f, 0.0f);
Heightmap heightmap(heightmapSettings);
heightmap.build(heightmapSettings);
heightmap.setShaderLocations(vertShaderLocation);
heightmap.rotate(glm::vec3(1,0,0), -1.57f);
*/
glViewport(0,0,VisualContext::width, VisualContext::height);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
Luae::ScriptTriangle::AddToLib();
Luae::ScriptMouse::AddToLib();
Luae::ScriptMouse::SetWindow(window);
Luae::ScriptMouse::SetLogicContex(&logicContext);
Line worldLine;
worldLine.buildStatic();
worldLine.setShaderLocations(vertShaderLocation);
Circle circle;
circle.translate(glm::vec3(0.0f,0.0f,10.0f));
circle.buildStatic();
Circle circle2;
circle2.translate(glm::vec3(5.0f,0.0f,10.0f));
circle2.buildStatic();
circle.setShaderLocations(vertShaderLocation);
lua_State* l = Luae::ScriptManager::instance()->getState();
Luae::Script* script = Luae::Script::Load("triangle_drawing.lua");
script->call("init");
//lua_getglobal(l, "triangle");
//Triangle* triangle = *(Triangle**)lua_touserdata(l,-1);
//drawQueue.push_back(triangle);
// AddToDrawQueueCommand addTriangle(triangle);
// addTriangle.execute();
glEnable(GL_MULTISAMPLE);
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT, GL_FILL);
glUniformMatrix4fv(uloc_project, 1, GL_FALSE, glm::value_ptr(VisualContext::projection_matrix));
calcWorldPickRay(window);
glm::vec3 rayWordEndPoint = glm::vec3(glm::vec4(0.0f, 0.0f, -100.0f, 1.0f) * logicContext.modelview);
worldLine.setStartEnd(ray_world, rayWordEndPoint);
worldLine.update(&logicContext);
worldLine.draw(&logicContext);
circle.update(&logicContext);
circle.draw(&logicContext);
circle2.update(&logicContext);
circle2.draw(&logicContext);
script->call("update");
//triangle->update(&logicContext);
//triangle->draw(&logicContext);
for(std::vector<IPolygon*>::iterator drawHost = drawQueue.begin();
drawHost != drawQueue.end();
drawHost++){
glDisable(GL_CULL_FACE);
(*drawHost)->update(&logicContext);
(*drawHost)->draw(&logicContext);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
delete script;
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
<commit_msg>Added destruction of matrixstack<commit_after>#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <lua/lua.hpp>
#include <vector>
#include <fmt/format.h>
#include "terrian_config.hpp"
#include "matrixstacksingleton.hpp"
#include "IPolygon.hpp"
#include "polygon.hpp"
#include "logiccontext.hpp"
#include "visualcontext.hpp"
#include "heightmap.hpp"
#include "line.hpp"
#include "triangle.hpp"
#include "circle.hpp"
#include "addtodrawqueue.hpp"
#include "luae/script.hpp"
#include "luae/scriptmanager.hpp"
#include "luae/scriptheightmap.hpp"
#include "luae/scriptriangle.hpp"
#include "luae/scriptmouse.hpp"
//For stringifying preprocessor values
#define xstr(s) str(s)
#define str(s) #s
#define concat(first, second) first second
static struct LogicContext logicContext;
static glm::vec3 ray_world;
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
glm::vec3 up = glm::vec3(glm::vec4(0.0, 1.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 down = glm::vec3(glm::vec4(0.0, -1.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 left = glm::vec3(glm::vec4(-1.0, 0.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 right = glm::vec3(glm::vec4(1.0, 0.0, 0.0, 1.0) * logicContext.modelview);
glm::vec3 back = glm::vec3(glm::vec4(0.0, 0.0, -1.0, 1.0) * logicContext.modelview);
glm::vec3 forward = glm::vec3(glm::vec4(0.0, 0.0, 1.0, 1.0) * logicContext.modelview);
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS){
printf("Triangle 1 Model Matrix: %s\n", glm::to_string(logicContext.modelview).c_str());
}
if(key == GLFW_KEY_R && action == GLFW_RELEASE){
logicContext.modelview = glm::mat4();
}
if(key == GLFW_KEY_LEFT && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, up);
}
else if(key == GLFW_KEY_RIGHT && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, down);
}
else if(key == GLFW_KEY_LEFT && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, left * 0.1f);
}
else if(key == GLFW_KEY_RIGHT && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, right * 0.1f);
}
if(key == GLFW_KEY_UP && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, up * 0.1f);
}
else if(key == GLFW_KEY_DOWN && mods == 0){
logicContext.modelview = glm::translate(logicContext.modelview, down * 0.1f);
}
else if(key == GLFW_KEY_UP && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, left);
}
else if(key == GLFW_KEY_DOWN && mods == GLFW_MOD_SHIFT){
logicContext.modelview = glm::rotate(logicContext.modelview, 0.1f, right);
}else if(key == GLFW_KEY_UP && mods == GLFW_MOD_CONTROL){
logicContext.modelview = glm::translate(logicContext.modelview, back * 0.1f);
}else if(key == GLFW_KEY_DOWN && mods == GLFW_MOD_CONTROL){
logicContext.modelview = glm::translate(logicContext.modelview, forward * 0.1f);
}
}
static void calcWorldPickRay(GLFWwindow *window){
//Build ray from mouse
double mouseX;
double mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
glm::vec4 ray_clip = glm::vec4((2.0f * mouseX) / VisualContext::width - 1.0f, 1.0f - (2.0f * mouseY) / VisualContext::height, -1.0f, 1.0f);
glm::vec4 ray_eye = glm::inverse(VisualContext::projection_matrix) * ray_clip;
ray_eye.z = -1.0f;
ray_eye.w = 1.0f;
ray_world = glm::vec3(glm::inverse(logicContext.modelview) * ray_eye);
// ray_world = glm::normalize(ray_world);
}
int main(void) {
GLFWwindow *window = VisualContext::CreateGLFWWindow(key_callback);
GLuint shader_program = VisualContext::make_shader_program(concat(xstr(SHADERS_DIR), "/shader.vert"), concat(xstr(SHADERS_DIR), "/shader.frag"));
glUseProgram(shader_program);
GLuint vertShaderLocation = glGetAttribLocation(shader_program, "vert");
GLuint uloc_project = glGetUniformLocation(shader_program, "project");
GLuint uloc_modelview = glGetUniformLocation(shader_program, "modelview");
std::vector<IPolygon*> drawQueue;
AddToDrawQueueCommand::SetQueue(&drawQueue);
/* Compute the projection matrix */
VisualContext::projection_matrix = glm::perspective(VisualContext::view_angle, VisualContext::aspect_ratio, VisualContext::z_near, VisualContext::z_far);
logicContext.uloc_modelview = uloc_modelview;
/* Set the camera position */
logicContext.modelview = glm::translate(logicContext.modelview, glm::vec3(0.0f, 0.0f, -20.0f));
logicContext.modelview = glm::rotate(logicContext.modelview, 0.0f, glm::vec3(-1.0f, 0.0f, 0.0f));
/*
HeightmapSettings heightmapSettings;
heightmapSettings.widthDensity = 10;
heightmapSettings.origin = glm::vec3(0.0f, 0.0f, 0.0f);
Heightmap heightmap(heightmapSettings);
heightmap.build(heightmapSettings);
heightmap.setShaderLocations(vertShaderLocation);
heightmap.rotate(glm::vec3(1,0,0), -1.57f);
*/
glViewport(0,0,VisualContext::width, VisualContext::height);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
Luae::ScriptTriangle::AddToLib();
Luae::ScriptMouse::AddToLib();
Luae::ScriptMouse::SetWindow(window);
Luae::ScriptMouse::SetLogicContex(&logicContext);
Line worldLine;
worldLine.buildStatic();
worldLine.setShaderLocations(vertShaderLocation);
Circle circle;
circle.translate(glm::vec3(0.0f,0.0f,10.0f));
circle.buildStatic();
Circle circle2;
circle2.translate(glm::vec3(5.0f,0.0f,10.0f));
circle2.buildStatic();
circle.setShaderLocations(vertShaderLocation);
lua_State* l = Luae::ScriptManager::instance()->getState();
Luae::Script* script = Luae::Script::Load("triangle_drawing.lua");
script->call("init");
//lua_getglobal(l, "triangle");
//Triangle* triangle = *(Triangle**)lua_touserdata(l,-1);
//drawQueue.push_back(triangle);
// AddToDrawQueueCommand addTriangle(triangle);
// addTriangle.execute();
glEnable(GL_MULTISAMPLE);
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT, GL_FILL);
glUniformMatrix4fv(uloc_project, 1, GL_FALSE, glm::value_ptr(VisualContext::projection_matrix));
calcWorldPickRay(window);
glm::vec3 rayWordEndPoint = glm::vec3(glm::vec4(0.0f, 0.0f, -100.0f, 1.0f) * logicContext.modelview);
worldLine.setStartEnd(ray_world, rayWordEndPoint);
worldLine.update(&logicContext);
worldLine.draw(&logicContext);
circle.update(&logicContext);
circle.draw(&logicContext);
circle2.update(&logicContext);
circle2.draw(&logicContext);
script->call("update");
//triangle->update(&logicContext);
//triangle->draw(&logicContext);
for(std::vector<IPolygon*>::iterator drawHost = drawQueue.begin();
drawHost != drawQueue.end();
drawHost++){
glDisable(GL_CULL_FACE);
(*drawHost)->update(&logicContext);
(*drawHost)->draw(&logicContext);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
delete script;
MatrixStackSingleton::Destroy();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
int main()
{
std::cout << "AuralGlitch is a standalone audio sampler and effects program built in C++.\n";
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
int main()
{
std::cout << "AuralGlitch is a standalone audio sampler and effects program for OS X built in C++.\n";
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 alexi [email protected]
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "server.hpp"
Server::Server ( const unsigned int &port ) :
//server_protocol_(nullptr),
tcp_socketFd_ ( socket ( PF_INET, SOCK_STREAM, 0 ) ),
udp_socketFd_ ( socket ( PF_INET, SOCK_DGRAM, 0 ) ),
ready_ ( false )
{
/* Initialize socket structure */
bzero ( ( char * ) &tcp_sin_, sizeof ( tcp_sin_ ) );
bzero ( ( char * ) &udp_sin_, sizeof ( udp_sin_ ) );
tcp_sin_.sin_addr.s_addr = INADDR_ANY;
udp_sin_.sin_addr.s_addr = INADDR_ANY;
udp_sin_.sin_port = htons(port);
tcp_sin_.sin_port = htons (port);
// clear sockaddr_in to sockaddr padding buffer
memset ( &tcp_sin_.sin_zero, 0, sizeof ( tcp_sin_.sin_zero ) );
memset ( &udp_sin_.sin_zero, 0, sizeof ( udp_sin_.sin_zero ) );
int bind_tcp = bind ( tcp_socketFd_, ( struct sockaddr * ) &tcp_sin_, sizeof ( tcp_sin_ ) );
int bind_udp = bind ( udp_socketFd_, ( struct sockaddr * ) &udp_sin_, sizeof ( udp_sin_ ) );
if ( bind_tcp && bind_udp != 0 )
{
std::stringstream msg;
msg << " Binding error" << std::endl;
errno = EACCES;
perror ( msg.str().c_str() );
exit ( errno );
}
else
{
ready_ = true;
}
}
void Server::setProtocol ( std::unique_ptr<IProtocol> protocol )
{
server_protocol_ = std::move ( protocol ); //FIXME: // Disable copy from lvalue.
}
void foo()
{
std::cout <<"Hello foo!" << std::endl;
}
void Server::run()
{
std::cout << "Server runnn!!" << std::endl;
if ( !ready_ ) return;
//TODO: Mind backlog argument (max conn pending)
listen ( tcp_socketFd_, 500 );
if ( errno != 0 )
{
perror ( "Error" );
std::cout << "socket failed!!" << std::endl;
return;
}
std::vector<std::thread> threads;
threads.push_back(std::thread(&Server::tcp_conn_handle, this));
threads.push_back(std::thread(&Server::udp_handler, this));
std::for_each(threads.begin(), threads.end(),
std::mem_fn(&std::thread::join));
std::cout << "Shutdown server" << std::endl;
}
void Server::tcp_conn_handle()
{
int slave_sock;
unsigned int sin_len = sizeof ( tcp_sin_ );
while ( true )
{
slave_sock = accept ( tcp_socketFd_, ( struct sockaddr * ) &tcp_sin_, &sin_len );
if ( slave_sock < 0 ) break;
std::thread t ( &Server::tcp_conn_worker, this, std::cref(slave_sock) );
t.detach();
}
}
void Server::tcp_conn_worker ( const int& ssock )
{
std::vector<char> buf ( buf_sz_/sizeof ( char ) );
int q = 10;
while ( q > 1 )
{
q = read ( ssock, buf.data(), buf_sz_ );
if (q<2) break; //FIXME
server_protocol_->process_data ( {std::begin ( buf ), std::end ( buf ) } );
std::cout << *server_protocol_;
int k = write ( ssock, buf.data(), q );
if ( k==-1 ) break;
buf.clear();
buf.resize ( buf_sz_/sizeof ( char ) );
}
close ( ssock );
}
void Server::udp_handler()
{
std::cout << "udp handler" << std::endl;
std::vector<char> udp_buf( buf_sz_/sizeof(char) );
std::shared_ptr<std::vector<char>> buf (new std::vector<char>(buf_sz_/sizeof(char)));
sockaddr_in cli_addr;
unsigned int cli_addrlen = sizeof(cli_addr);
while(true){
int k = recvfrom(udp_socketFd_, udp_buf.data(), buf_sz_, 0, (struct sockaddr*)&cli_addr, &cli_addrlen);
std::thread(&Server::udp_worker, this, udp_buf, std::cref(k), cli_addr).detach();
udp_buf.resize ( buf_sz_/sizeof ( char ) );
}
}
void Server::udp_worker(std::vector<char> data, const int& data_len, sockaddr_in cli)
{
std::cout << "udp worker" << std::endl;
server_protocol_->process_data ( {std::begin(data), std::end(data)} );
std::cout << *server_protocol_;
// int k = write( udp_socketFd_, data.data(), data_len );
int k = sendto(udp_socketFd_, data.data(), data_len, 0, (struct sockaddr*)&cli, sizeof(cli));
if (k <= 0)
{
std::cout << "udp connection lost: " << inet_ntoa(cli.sin_addr) << std::endl;
}
}
Server::~Server()
{
std::cout << "Server destructor" << std::endl;
if ( tcp_socketFd_ > 0 )
{
std::cout << "closing tcp" << std::endl;
close ( tcp_socketFd_ );
}
if ( udp_socketFd_ > 0 )
{
std::cout << "closing udp" << std::endl;
close ( udp_socketFd_ );
}
}
<commit_msg> UDP false processing fix<commit_after>/*
* Copyright (c) 2017 alexi [email protected]
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "server.hpp"
Server::Server ( const unsigned int &port ) :
//server_protocol_(nullptr),
tcp_socketFd_ ( socket ( PF_INET, SOCK_STREAM, 0 ) ),
udp_socketFd_ ( socket ( PF_INET, SOCK_DGRAM, 0 ) ),
ready_ ( false )
{
/* Initialize socket structure */
bzero ( ( char * ) &tcp_sin_, sizeof ( tcp_sin_ ) );
bzero ( ( char * ) &udp_sin_, sizeof ( udp_sin_ ) );
tcp_sin_.sin_addr.s_addr = INADDR_ANY;
udp_sin_.sin_addr.s_addr = INADDR_ANY;
udp_sin_.sin_port = htons(port);
tcp_sin_.sin_port = htons (port);
// clear sockaddr_in to sockaddr padding buffer
memset ( &tcp_sin_.sin_zero, 0, sizeof ( tcp_sin_.sin_zero ) );
memset ( &udp_sin_.sin_zero, 0, sizeof ( udp_sin_.sin_zero ) );
int bind_tcp = bind ( tcp_socketFd_, ( struct sockaddr * ) &tcp_sin_, sizeof ( tcp_sin_ ) );
int bind_udp = bind ( udp_socketFd_, ( struct sockaddr * ) &udp_sin_, sizeof ( udp_sin_ ) );
if ( bind_tcp && bind_udp != 0 )
{
std::stringstream msg;
msg << " Binding error" << std::endl;
errno = EACCES;
perror ( msg.str().c_str() );
exit ( errno );
}
else
{
ready_ = true;
}
}
void Server::setProtocol ( std::unique_ptr<IProtocol> protocol )
{
server_protocol_ = std::move ( protocol ); //FIXME: // Disable copy from lvalue.
}
void foo()
{
std::cout <<"Hello foo!" << std::endl;
}
void Server::run()
{
std::cout << "Server runnn!!" << std::endl;
if ( !ready_ ) return;
//TODO: Mind backlog argument (max conn pending)
listen ( tcp_socketFd_, 500 );
if ( errno != 0 )
{
perror ( "Error" );
std::cout << "socket failed!!" << std::endl;
return;
}
std::vector<std::thread> threads;
threads.push_back(std::thread(&Server::tcp_conn_handle, this));
threads.push_back(std::thread(&Server::udp_handler, this));
std::for_each(threads.begin(), threads.end(),
std::mem_fn(&std::thread::join));
std::cout << "Shutdown server" << std::endl;
}
void Server::tcp_conn_handle()
{
int slave_sock;
unsigned int sin_len = sizeof ( tcp_sin_ );
while ( true )
{
slave_sock = accept ( tcp_socketFd_, ( struct sockaddr * ) &tcp_sin_, &sin_len );
if ( slave_sock < 0 ) break;
std::thread t ( &Server::tcp_conn_worker, this, std::cref(slave_sock) );
t.detach();
}
}
void Server::tcp_conn_worker ( const int& ssock )
{
std::vector<char> buf ( buf_sz_/sizeof ( char ) );
int q = 10;
while ( q > 1 )
{
q = read ( ssock, buf.data(), buf_sz_ );
if (q<2) break; //FIXME
server_protocol_->process_data ( {std::begin ( buf ), std::end ( buf ) } );
std::cout << *server_protocol_;
int k = write ( ssock, buf.data(), q );
if ( k==-1 ) break;
buf.clear();
buf.resize ( buf_sz_/sizeof ( char ) );
}
close ( ssock );
}
void Server::udp_handler()
{
std::cout << "udp handler" << std::endl;
std::vector<char> udp_buf( buf_sz_/sizeof(char) );
std::shared_ptr<std::vector<char>> buf (new std::vector<char>(buf_sz_/sizeof(char)));
sockaddr_in cli_addr;
unsigned int cli_addrlen = sizeof(cli_addr);
while(true){
int k = recvfrom(udp_socketFd_, udp_buf.data(), buf_sz_, 0, (struct sockaddr*)&cli_addr, &cli_addrlen);
if(k<2) continue;
std::thread(&Server::udp_worker, this, udp_buf, std::cref(k), cli_addr).detach();
udp_buf.resize ( buf_sz_/sizeof ( char ) );
}
}
void Server::udp_worker(std::vector<char> data, const int& data_len, sockaddr_in cli)
{
std::cout << "udp worker" << std::endl;
server_protocol_->process_data ( {std::begin(data), std::end(data)} );
std::cout << *server_protocol_;
// int k = write( udp_socketFd_, data.data(), data_len );
int k = sendto(udp_socketFd_, data.data(), data_len, 0, (struct sockaddr*)&cli, sizeof(cli));
if (k <= 0)
{
std::cout << "udp connection lost: " << inet_ntoa(cli.sin_addr) << std::endl;
}
}
Server::~Server()
{
std::cout << "Server destructor" << std::endl;
if ( tcp_socketFd_ > 0 )
{
std::cout << "closing tcp" << std::endl;
close ( tcp_socketFd_ );
}
if ( udp_socketFd_ > 0 )
{
std::cout << "closing udp" << std::endl;
close ( udp_socketFd_ );
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <pulse/error.h>
#include <pulse/simple.h>
using namespace std;
int main() {
pa_simple *s;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16NE;
ss.channels = 2;
ss.rate = 44100;
s = pa_simple_new(NULL, // Use the default server.
"Fooapp", // Our application's name.
PA_STREAM_PLAYBACK,
NULL, // Use the default device.
"Music", // Description of our stream.
&ss, // Our sample format.
NULL, // Use default channel map
NULL, // Use default buffering attributes.
NULL // Ignore error code.
);
cout << "HELLO JS" << endl;
cout << "HELLO JS" << endl;
}
<commit_msg>white noise <commit_after>#include <iostream>
#include <pulse/error.h>
#include <pulse/simple.h>
#include <cstdlib>
using namespace std;
int main() {
pa_simple *s;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16NE;
ss.channels = 2;
ss.rate = 44100;
s = pa_simple_new(NULL, // Use the default server.
"Fooapp", // Our application's name.
PA_STREAM_PLAYBACK,
NULL, // Use the default device.
"Music", // Description of our stream.
&ss, // Our sample format.
NULL, // Use default channel map
NULL, // Use default buffering attributes.
NULL // Ignore error code.
);
while(true) {
unsigned int superSong[200];
for (int j = 0; j < 200; j++) {
int i = rand() % 1000;
superSong[j] = i;
}
int errorCode;
pa_simple_write(s, superSong, 200, &errorCode);
cout << "HELLO JS" << endl;
cout << "HELLO JS" << endl;
}
}
<|endoftext|>
|
<commit_before>#include "visgoth.hpp"
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include "sys/socket.h"
#include "collectd.hpp"
#include "HappyHTTP/happyhttp.h"
#include "../json11/json11.hpp"
#include "../helpers.hpp"
using namespace std;
using namespace json11;
static int BUF_SIZE = 1024;
Visgoth::Visgoth() {}
Json Visgoth::get_collectd_stats()
{
unordered_map<string, float> float_values;
vector<string> lines = collectd.list();
for (auto l_it = lines.begin(); l_it != lines.end(); l_it++)
{
string list_key = split(*l_it, ' ')[1]; // stamp key
for (auto k_it = collectd_keys.begin(); k_it != collectd_keys.end(); k_it++)
{
string collectd_key = k_it->second;
string visgoth_key = k_it->first;
if (list_key.find(collectd_key) != string::npos)
{
vector<string> glines = collectd.get(list_key);
for (auto g_it = glines.begin(); g_it != glines.end(); g_it++)
{
vector<string> vals = split(*g_it, ' '); // v1=x v2=y
for (auto v_it = vals.begin(); v_it != vals.end(); v_it++)
{
vector<string> value_vec = split(*v_it, '='); // v1=x
string value = value_vec[0];
float float_val = stof(value_vec[1]);
float_values[visgoth_key + "-" + value] += float_val;
}
}
}
}
}
return Json(float_values);
}
void OnBegin(const happyhttp::Response* r, void* userdata)
{
}
void OnData(const happyhttp::Response* r, void* userdata, const unsigned char* data, int n)
{
n = min(n, BUF_SIZE);
strncpy((char*) userdata, reinterpret_cast<const char*>(data), n);
}
void OnComplete(const happyhttp::Response* r, void* userdata)
{
}
uint Visgoth::get_extent(Json profile_data)
{
Json collectd_data = get_collectd_stats();
Json request_data = Json::object {
{"client_profile", profile_data},
{"server_profile", collectd_data},
};
string request = Json(request_data).dump();
const char* body = request.c_str();
int body_size = request.size();
const char* headers[] =
{
"Connection", "close",
"Content-type", "application/json",
"Accept", "application/json",
0
};
char* response = (char*) malloc(sizeof(char) * 1024);
happyhttp::Connection conn("127.0.0.1", 5000);
conn.setcallbacks(OnBegin, OnData, OnComplete, (void*) response);
conn.request("POST",
"/visgoth/get_extent",
headers,
(const unsigned char*)body,
body_size);
while(conn.outstanding())
conn.pump();
string err;
Json json_response = Json::parse(response, err);
uint extent = json_response["extent"].int_value();
if (extent == 0) {
cout << "WARNING: No extent provided from Visgoth" << endl;
}
free(response);
return extent;
}
<commit_msg>Null-terminate the response string from flask server to webserver<commit_after>#include "visgoth.hpp"
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include "sys/socket.h"
#include "collectd.hpp"
#include "HappyHTTP/happyhttp.h"
#include "../json11/json11.hpp"
#include "../helpers.hpp"
using namespace std;
using namespace json11;
static int BUF_SIZE = 1024;
Visgoth::Visgoth() {}
Json Visgoth::get_collectd_stats()
{
unordered_map<string, float> float_values;
vector<string> lines = collectd.list();
for (auto l_it = lines.begin(); l_it != lines.end(); l_it++)
{
string list_key = split(*l_it, ' ')[1]; // stamp key
for (auto k_it = collectd_keys.begin(); k_it != collectd_keys.end(); k_it++)
{
string collectd_key = k_it->second;
string visgoth_key = k_it->first;
if (list_key.find(collectd_key) != string::npos)
{
vector<string> glines = collectd.get(list_key);
for (auto g_it = glines.begin(); g_it != glines.end(); g_it++)
{
vector<string> vals = split(*g_it, ' '); // v1=x v2=y
for (auto v_it = vals.begin(); v_it != vals.end(); v_it++)
{
vector<string> value_vec = split(*v_it, '='); // v1=x
string value = value_vec[0];
float float_val = stof(value_vec[1]);
float_values[visgoth_key + "-" + value] += float_val;
}
}
}
}
}
return Json(float_values);
}
void OnBegin(const happyhttp::Response* r, void* userdata)
{
}
void OnData(const happyhttp::Response* r, void* userdata, const unsigned char* data, int n)
{
n = min(n, BUF_SIZE);
strncpy((char*) userdata, reinterpret_cast<const char*>(data), n);
((char *) userdata)[n] = '\0';
}
void OnComplete(const happyhttp::Response* r, void* userdata)
{
}
uint Visgoth::get_extent(Json profile_data)
{
Json collectd_data = get_collectd_stats();
Json request_data = Json::object {
{"client_profile", profile_data},
{"server_profile", collectd_data},
};
string request = Json(request_data).dump();
const char* body = request.c_str();
int body_size = request.size();
const char* headers[] =
{
"Connection", "close",
"Content-type", "application/json",
"Accept", "application/json",
0
};
char* response = (char*) malloc(sizeof(char) * 1024);
happyhttp::Connection conn("127.0.0.1", 5000);
conn.setcallbacks(OnBegin, OnData, OnComplete, (void*) response);
conn.request("POST",
"/visgoth/get_extent",
headers,
(const unsigned char*)body,
body_size);
while(conn.outstanding())
conn.pump();
string err;
Json json_response = Json::parse(response, err);
uint extent = json_response["extent"].int_value();
if (extent == 0) {
cout << "WARNING: No extent provided from Visgoth" << endl;
}
free(response);
return extent;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <chrono>
#include "args.h"
#include "load_scene.h"
#include "render/render_target.h"
#include "driver.h"
#ifdef BUILD_PREVIEWER
#include "previewer.h"
#endif
const static std::string USAGE =
"Usage for prj1:\n\
----------------------------\n\
-f <file> - Specify the scene file to render\n\
-o <prefix> - Specify the prefix name for the output files\n\
color is written to <prefix>.ppm and depth to\n\
<prefix>.pgm\n\
-n <num> - Optional: specify the number of threads to render with,\n\
this number will be rounded up to the nearest even number.\n\
A warning will be printed if we can't evenly partition the\n\
image into <num> rectangles for rendering. Default is 1.\n\
-h - Show this help information\n"
#ifdef BUILD_PREVIEWER
+ std::string{"-p - Show a live preview of the image as it's rendered.\n\
Rendering performance is not measured in this mode\n"}
#endif
+ std::string{"----------------------------\n"};
int main(int argc, char **argv){
if (flag(argv, argv + argc, "-h")){
std::cout << USAGE;
return 0;
}
if (!flag(argv, argv + argc, "-f")){
std::cerr << "Error: No scene file passed\n"
<< USAGE;
return 1;
}
if (!flag(argv, argv + argc, "-o")){
std::cerr << "Error: No output filename passed\n"
<< USAGE;
return 1;
}
int n_threads = 1;
if (flag(argv, argv + argc, "-n")){
n_threads = get_param<int>(argv, argv + argc, "-n");
if (n_threads > 1 && n_threads % 2 != 0){
std::cerr << "Warning: num threads not even, increasing thread count by 1\n";
++n_threads;
}
}
std::string scene_file = get_param<std::string>(argv, argv + argc, "-f");
std::string out_file = get_param<std::string>(argv, argv + argc, "-o");
Scene scene = load_scene(scene_file);
Driver driver{scene, n_threads};
#ifdef BUILD_PREVIEWER
if (flag(argv, argv + argc, "-p")){
//The user might abort before rendering completes or we could encounter
//an SDL/OpenGL error, so don't save the images if the render doesn't complete
if (render_with_preview(driver)){
RenderTarget &target = scene.get_render_target();
target.save_image(out_file + ".ppm");
target.save_depth(out_file + ".pgm");
}
return 0;
}
else {
#endif
auto start = std::chrono::high_resolution_clock::now();
//While the driver is rendering defer priority to the worker threads
driver.render();
while (!driver.done()){
std::this_thread::yield();
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = end - start;
std::cout << "Rendering took: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count()
<< "ms\n";
#ifdef BUILD_PREVIEWER
}
#endif
RenderTarget &target = scene.get_render_target();
target.save_image(out_file + ".ppm");
target.save_depth(out_file + ".pgm");
return 0;
}
<commit_msg>Make file output optional when building with preview<commit_after>#include <iostream>
#include <string>
#include <chrono>
#include "args.h"
#include "load_scene.h"
#include "render/render_target.h"
#include "driver.h"
#ifdef BUILD_PREVIEWER
#include "previewer.h"
#endif
const static std::string USAGE =
"Usage for prj1:\n\
----------------------------\n\
-f <file> - Specify the scene file to render\n\
-o <prefix> - Specify the prefix name for the output files\n\
color is written to <prefix>.ppm and depth to\n\
<prefix>.pgm\n\
-n <num> - Optional: specify the number of threads to render with,\n\
this number will be rounded up to the nearest even number.\n\
A warning will be printed if we can't evenly partition the\n\
image into <num> rectangles for rendering. Default is 1.\n\
-h - Show this help information\n"
#ifdef BUILD_PREVIEWER
+ std::string{"-p - Show a live preview of the image as it's rendered.\n\
Rendering performance is not measured in this mode\n"}
#endif
+ std::string{"----------------------------\n"};
int main(int argc, char **argv){
if (flag(argv, argv + argc, "-h")){
std::cout << USAGE;
return 0;
}
if (!flag(argv, argv + argc, "-f")){
std::cerr << "Error: No scene file passed\n"
<< USAGE;
return 1;
}
//if we built the previewer it's valid to not specify a file output but
//we need some way to output
#ifdef BUILD_PREVIEWER
if (!flag(argv, argv + argc, "-o") && !flag(argv, argv + argc, "-p")){
std::cerr << "Error: No output medium specified\n"
<< USAGE;
return 1;
}
#else
if (!flag(argv, argv + argc, "-o")){
std::cerr << "Error: No output filename passed\n"
<< USAGE;
return 1;
}
#endif
int n_threads = 1;
if (flag(argv, argv + argc, "-n")){
n_threads = get_param<int>(argv, argv + argc, "-n");
if (n_threads > 1 && n_threads % 2 != 0){
std::cerr << "Warning: num threads not even, increasing thread count by 1\n";
++n_threads;
}
}
std::string scene_file = get_param<std::string>(argv, argv + argc, "-f");
Scene scene = load_scene(scene_file);
Driver driver{scene, n_threads};
#ifdef BUILD_PREVIEWER
if (flag(argv, argv + argc, "-p")){
//The user might abort before rendering completes or we could encounter
//an SDL/OpenGL error, so don't save the images if the render doesn't complete
//Also need to validate that file output was turned on if we're running the previewer
if (render_with_preview(driver) && flag(argv, argv + argc, "-o")){
std::string out_file = get_param<std::string>(argv, argv + argc, "-o");
RenderTarget &target = scene.get_render_target();
target.save_image(out_file + ".ppm");
target.save_depth(out_file + ".pgm");
}
return 0;
}
else {
#endif
auto start = std::chrono::high_resolution_clock::now();
//While the driver is rendering defer priority to the worker threads
driver.render();
while (!driver.done()){
std::this_thread::yield();
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = end - start;
std::cout << "Rendering took: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count()
<< "ms\n";
#ifdef BUILD_PREVIEWER
}
#endif
std::string out_file = get_param<std::string>(argv, argv + argc, "-o");
RenderTarget &target = scene.get_render_target();
target.save_image(out_file + ".ppm");
target.save_depth(out_file + ".pgm");
return 0;
}
<|endoftext|>
|
<commit_before>#include <string>
#include <serial/serial.h>
using namespace serial;
using std::string;
int main(){
Serial port1("/dev/ttyS0");
port1.close();
return 1;
}
<commit_msg>add cmake files and configurations and serial port library<commit_after>#include <string>
#include <serial/serial.h>
using namespace serial;
using std::string;
int main(){
Serial port1("/dev/ttyS0");
port1.close();
return 1;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.