hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
75ff34fbbb9647902584e07132df7b43d76b229a | 878 | cpp | C++ | chapter08/chapter08_ex08.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 170 | 2015-05-02T18:08:38.000Z | 2018-07-31T11:35:17.000Z | chapter08/chapter08_ex08.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 7 | 2017-01-16T02:25:20.000Z | 2018-07-20T12:57:30.000Z | chapter08/chapter08_ex08.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 105 | 2015-05-28T11:52:19.000Z | 2018-07-17T14:11:25.000Z | // Chapter 08, exercise 08: write simple function randint() to produce random
// numbers
// Exercise 09: write function that produces random number in a given range
#include "../lib_files/std_lib_facilities.h"
#include<climits>
unsigned int X_n = 0;
// initialise seed with clock
void init_seed()
{
X_n = 66779;
}
// produces a pseudo-random number in the range [0:INT_MAX]
int randint()
{
X_n = (48271*X_n) % INT_MAX;
return X_n;
}
// return pseudo-random int between a and b
int rand_in_range(int a, int b)
{
if (b <= a) error("b must be larger than a");
int r = randint();
return a + double(r)/INT_MAX*(b-a);
}
int main()
try
{
init_seed();
for (int i = 0; i<1000; ++i)
cout << rand_in_range(950,1000) << endl;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| 19.511111 | 77 | 0.628702 | TingeOGinge |
75fff73f97639f162f565889a3aea4836e672bdf | 8,705 | cpp | C++ | admin/wmi/wbem/providers/msiprovider/dll/filespecification.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/providers/msiprovider/dll/filespecification.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/providers/msiprovider/dll/filespecification.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // FileSpecification.cpp: implementation of the CFileSpecification class.
//
// Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "FileSpecification.h"
#include "ExtendString.h"
#include "ExtendQuery.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileSpecification::CFileSpecification(CRequestObject *pObj, IWbemServices *pNamespace,
IWbemContext *pCtx):CGenericClass(pObj, pNamespace, pCtx)
{
}
CFileSpecification::~CFileSpecification()
{
}
HRESULT CFileSpecification::CreateObject(IWbemObjectSink *pHandler, ACTIONTYPE atAction)
{
HRESULT hr = WBEM_S_NO_ERROR;
MSIHANDLE hView = NULL;
MSIHANDLE hRecord = NULL;
MSIHANDLE hSEView = NULL;
MSIHANDLE hSERecord = NULL;
int i = -1;
WCHAR wcBuf[BUFF_SIZE];
WCHAR wcProductCode[39];
WCHAR wcID[39];
DWORD dwBufSize;
bool bMatch = false;
UINT uiStatus;
bool bGotID = false;
WCHAR wcFile[BUFF_SIZE];
WCHAR wcTestCode[39];
//These will change from class to class
bool bCheck;
INSTALLSTATE piInstalled;
int iState;
SetSinglePropertyPath(L"CheckID");
//improve getobject performance by optimizing the query
if(atAction != ACTIONTYPE_ENUM)
{
// we are doing GetObject so we need to be reinitialized
hr = WBEM_E_NOT_FOUND;
BSTR bstrCompare;
int iPos = -1;
bstrCompare = SysAllocString ( L"CheckID" );
if ( bstrCompare )
{
if(FindIn(m_pRequest->m_Property, bstrCompare, &iPos))
{
if ( ::SysStringLen ( m_pRequest->m_Value[iPos] ) < BUFF_SIZE )
{
//Get the action we're looking for
wcscpy(wcBuf, m_pRequest->m_Value[iPos]);
// safe operation if wcslen ( wcBuf ) > 38
if ( wcslen ( wcBuf ) > 38 )
{
wcscpy(wcTestCode, &(wcBuf[(wcslen(wcBuf) - 38)]));
}
else
{
// we are not good to go, they have sent us longer string
SysFreeString ( bstrCompare );
throw hr;
}
// safe because lenght has been tested already in condition
RemoveFinalGUID(m_pRequest->m_Value[iPos], wcFile);
bGotID = true;
}
else
{
// we are not good to go, they have sent us longer string
SysFreeString ( bstrCompare );
throw hr;
}
}
SysFreeString ( bstrCompare );
}
else
{
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
}
}
Query wcQuery;
wcQuery.Append ( 1, L"select distinct `File`, `Component_`, `FileName`, `FileSize`, `Version`, `Language`, `Attributes`, `Sequence` from File" );
//optimize for GetObject
if ( bGotID )
{
wcQuery.Append ( 3, L" where `File`=\'", wcFile, L"\'" );
}
QueryExt wcQuery1 ( L"select distinct `ComponentId` from Component where `Component`=\'" );
LPWSTR Buffer = NULL;
LPWSTR dynBuffer = NULL;
DWORD dwDynBuffer = 0L;
while(!bMatch && m_pRequest->Package(++i) && (hr != WBEM_E_CALL_CANCELLED))
{
// safe operation:
// Package ( i ) returns NULL ( tested above ) or valid WCHAR [39]
wcscpy(wcProductCode, m_pRequest->Package(i));
if((atAction == ACTIONTYPE_ENUM) || (bGotID && (_wcsicmp(wcTestCode, wcProductCode) == 0))){
//Open our database
try
{
if ( GetView ( &hView, wcProductCode, wcQuery, L"File", FALSE, FALSE ) )
{
uiStatus = g_fpMsiViewFetch(hView, &hRecord);
while(!bMatch && (uiStatus != ERROR_NO_MORE_ITEMS) && (hr != WBEM_E_CALL_CANCELLED)){
CheckMSI(uiStatus);
if(FAILED(hr = SpawnAnInstance(&m_pObj))) throw hr;
//----------------------------------------------------
dwBufSize = BUFF_SIZE;
GetBufferToPut ( hRecord, 1, dwBufSize, wcBuf, dwDynBuffer, dynBuffer, Buffer );
PutKeyProperty ( m_pObj, pCheckID, Buffer, &bCheck, m_pRequest, 1, wcProductCode );
if ( dynBuffer && dynBuffer [ 0 ] != 0 )
{
dynBuffer [ 0 ] = 0;
}
//====================================================
dwBufSize = BUFF_SIZE;
PutPropertySpecial ( hRecord, 3, dwBufSize, wcBuf, dwDynBuffer, dynBuffer, FALSE, 2, pCaption, pDescription );
PutProperty(m_pObj, pFileSize, g_fpMsiRecordGetInteger(hRecord, 4));
dwBufSize = BUFF_SIZE;
PutPropertySpecial ( hRecord, 5, dwBufSize, wcBuf, dwDynBuffer, dynBuffer, pVersion );
dwBufSize = BUFF_SIZE;
PutPropertySpecial ( hRecord, 6, dwBufSize, wcBuf, dwDynBuffer, dynBuffer, pLanguage );
PutProperty(m_pObj, pAttributes, g_fpMsiRecordGetInteger(hRecord, 7));
PutProperty(m_pObj, pSequence, g_fpMsiRecordGetInteger(hRecord, 8));
dwBufSize = BUFF_SIZE;
GetBufferToPut ( hRecord, 2, dwBufSize, wcBuf, dwDynBuffer, dynBuffer, Buffer );
PutProperty(m_pObj, pName, Buffer);
// make query on fly
wcQuery1.Append ( 2, Buffer, L"\'" );
if ( dynBuffer && dynBuffer [ 0 ] != 0 )
{
dynBuffer [ 0 ] = 0;
}
if(ERROR_SUCCESS == g_fpMsiDatabaseOpenViewW( msidata.GetDatabase (), wcQuery1, &hSEView)){
if(ERROR_SUCCESS == g_fpMsiViewExecute(hSEView, 0)){
try{
if ( ERROR_SUCCESS == g_fpMsiViewFetch(hSEView, &hSERecord)){
dwBufSize = BUFF_SIZE;
GetBufferToPut ( hSERecord, 1, dwBufSize, wcID, dwDynBuffer, dynBuffer, Buffer );
if ( ValidateComponentID ( Buffer, wcProductCode ) )
{
PutProperty(m_pObj, pSoftwareElementID, Buffer);
dwBufSize = BUFF_SIZE;
wcscpy(wcBuf, L"");
piInstalled = g_fpMsiGetComponentPathW(wcProductCode, Buffer, wcBuf, &dwBufSize);
if ( dynBuffer && dynBuffer [ 0 ] != 0 )
{
dynBuffer [ 0 ] = 0;
}
SoftwareElementState(piInstalled, &iState);
PutProperty(m_pObj, pSoftwareElementState, iState);
PutProperty(m_pObj, pTargetOperatingSystem, GetOS());
dwBufSize = BUFF_SIZE;
CheckMSI(g_fpMsiGetProductPropertyW(msidata.GetProduct (), L"ProductVersion", wcBuf,
&dwBufSize));
PutProperty(m_pObj, pVersion, wcBuf);
//----------------------------------------------------
if(bCheck) bMatch = true;
if((atAction != ACTIONTYPE_GET) || bMatch){
hr = pHandler->Indicate(1, &m_pObj);
}
}
}
}catch(...){
g_fpMsiViewClose(hSEView);
g_fpMsiCloseHandle(hSEView);
g_fpMsiCloseHandle(hSERecord);
throw;
}
g_fpMsiViewClose(hSEView);
g_fpMsiCloseHandle(hSEView);
g_fpMsiCloseHandle(hSERecord);
}
}
m_pObj->Release();
m_pObj = NULL;
g_fpMsiCloseHandle(hRecord);
uiStatus = g_fpMsiViewFetch(hView, &hRecord);
}
}
}
catch(...)
{
if ( dynBuffer )
{
delete [] dynBuffer;
dynBuffer = NULL;
}
g_fpMsiCloseHandle(hRecord);
g_fpMsiViewClose(hView);
g_fpMsiCloseHandle(hView);
msidata.CloseDatabase ();
msidata.CloseProduct ();
if(m_pObj)
{
m_pObj->Release();
m_pObj = NULL;
}
throw;
}
g_fpMsiCloseHandle(hRecord);
g_fpMsiViewClose(hView);
g_fpMsiCloseHandle(hView);
msidata.CloseDatabase ();
msidata.CloseProduct ();
}
}
if ( dynBuffer )
{
delete [] dynBuffer;
dynBuffer = NULL;
}
return hr;
} | 29.811644 | 150 | 0.512809 | npocmaka |
2f022cfc429074cdf20faae1311b88792a063797 | 9,848 | cpp | C++ | examples/nonholonomic-car-demo.cpp | NEU-ZJX/Global-Trajectory-Optimization | 43654a829014a1f3fa57f28c94f7101b5d4b54ca | [
"MIT"
] | 10 | 2018-10-06T05:11:24.000Z | 2021-08-06T09:07:41.000Z | examples/nonholonomic-car-demo.cpp | HansRobo/Global-Trajectory-Optimization | 43654a829014a1f3fa57f28c94f7101b5d4b54ca | [
"MIT"
] | null | null | null | examples/nonholonomic-car-demo.cpp | HansRobo/Global-Trajectory-Optimization | 43654a829014a1f3fa57f28c94f7101b5d4b54ca | [
"MIT"
] | 6 | 2018-10-06T13:39:36.000Z | 2022-01-23T15:05:26.000Z |
#include <glc_planner_core.h>
namespace example{
////////////////////////////////////////////////////////
/////////Discretization of Control Inputs///////////////
////////////////////////////////////////////////////////
class ControlInputs2D : public glc::Inputs{
public:
//uniformly spaced points on a circle
ControlInputs2D(int num_inputs){
std::valarray<double> u(2);
for(int i=0;i<num_inputs;i++){
u[0]=sin(2.0*i*M_PI/num_inputs);
u[1]=cos(2.0*i*M_PI/num_inputs);
addInputSample(u);
}
}
};
////////////////////////////////////////////////////////
///////////////Goal Checking Interface//////////////////
////////////////////////////////////////////////////////
class SphericalGoal: public glc::GoalRegion{
double goal_radius, goal_radius_sqr;
std::valarray<double> error;
std::valarray<double> x_g;
int resolution;
public:
SphericalGoal(const int& _state_dim,
const double& _goal_radius,
int _resolution):
x_g(_state_dim,0.0),
resolution(_resolution),
goal_radius(_goal_radius),
error(_state_dim,0.0)
{
goal_radius_sqr=glc::sqr(goal_radius);
}
//Returns true if traj intersects goal and sets t to the first time at which the trajectory is in the goal
bool inGoal(const std::shared_ptr<glc::InterpolatingPolynomial>& traj, double& time) override {
time=traj->initialTime();
double dt=(traj->numberOfIntervals()*traj->intervalLength())/resolution;
for(int i=0;i<resolution;i++){
time+=dt;//don't need to check t0 since it was part of last traj
error=x_g-traj->at(time);
if(glc::dot(error,error) < goal_radius_sqr){
return true;}
}
return false;
}
void setRadius(double r){
goal_radius = r;
goal_radius_sqr = r*r;
}
double getRadius(){return goal_radius;}
void setGoal(std::valarray<double>& _x_g){x_g=_x_g;}
std::valarray<double> getGoal(){return x_g;}
};
////////////////////////////////////////////////////////
/////////////////Dynamic Model//////////////////////////
////////////////////////////////////////////////////////
class SingleIntegrator : public glc::RungeKuttaTwo{
public:
SingleIntegrator(const double& max_time_step_): glc::RungeKuttaTwo(0.0,max_time_step_,2) {}
void flow(std::valarray<double>& dx, const std::valarray<double>& x, const std::valarray<double>& u) override {dx=u;}
double getLipschitzConstant(){return 0.0;}
};
////////////////////////////////////////////////////////
/////////////////Cost Function//////////////////////////
////////////////////////////////////////////////////////
class ArcLength: public glc::CostFunction
{
double sample_resolution;
public:
ArcLength(int _sample_resolution) : glc::CostFunction(0.0),sample_resolution(double(_sample_resolution)){}
double cost(const std::shared_ptr<glc::InterpolatingPolynomial>& traj,
const std::shared_ptr<glc::InterpolatingPolynomial>& control,
double t0,
double tf) const {
double c(0);
double t = traj->initialTime();
double dt = (tf-t0)/sample_resolution;
for(int i=0;i<sample_resolution;i++){
c+=glc::norm2(traj->at(t+dt)-traj->at(t));
t+=dt;
}
return c;
}
};
class CarControlInputs: public glc::Inputs{
public:
//uniformly spaced points on a circle
CarControlInputs(int num_steering_angles){
//Make all pairs (forward_speed,steering_angle)
std::valarray<double> car_speeds({1.0});//Pure path planning
std::valarray<double> steering_angles = glc::linearSpace(-0.0625*M_PI,0.0625*M_PI,num_steering_angles);
std::valarray<double> control_input(2);
for(double& vel : car_speeds){
for(double& ang : steering_angles ){
control_input[0]=vel;
control_input[1]=ang;
addInputSample(control_input);
}
}
}
};
////////////////////////////////////////////////////////
///////////////Goal Checking Interface//////////////////
////////////////////////////////////////////////////////
class Sphericalgoal: public glc::GoalRegion{
double radius_sqr;
std::valarray<double> center;
int resolution;
public:
Sphericalgoal(double& _goal_radius_sqr,
std::valarray<double>& _goal_center,
int _resolution):
resolution(_resolution),
center(_goal_center),
radius_sqr(_goal_radius_sqr){}
//Returns true if traj intersects goal and sets t to the first time at which the trajectory is in the goal
bool inGoal(const std::shared_ptr<glc::InterpolatingPolynomial>& traj, double& time) override {
time=traj->initialTime();
double dt=(traj->numberOfIntervals()*traj->intervalLength())/resolution;
for(int i=0;i<resolution;i++){
time+=dt;//don't need to check t0 since it was part of last traj
std::valarray<double> state = traj->at(time);
if(glc::sqr(state[0]-center[0]) + glc::sqr(state[1]-center[1]) < radius_sqr){return true;}
}
return false;
}
};
////////////////////////////////////////////////////////
////////Problem Specific Admissible Heuristic///////////
////////////////////////////////////////////////////////
class EuclideanHeuristic : public glc::Heuristic{
double radius;
std::valarray<double> goal;
public:
EuclideanHeuristic(std::valarray<double>& _goal,double _radius):radius(_radius),goal(_goal){}
double costToGo(const std::valarray<double>& state)const{
return std::max(0.0,sqrt(glc::sqr(goal[0]-state[0])+glc::sqr(goal[1]-state[1]))-radius);//offset by goal radius
}
};
////////////////////////////////////////////////////////
/////////////////Dynamic Model//////////////////////////
////////////////////////////////////////////////////////
class CarNonholonomicConstraint : public glc::RungeKuttaTwo {
public:
CarNonholonomicConstraint(const double& _max_time_step): RungeKuttaTwo(1.0,_max_time_step,3) {}
void flow(std::valarray<double>& dx, const std::valarray<double>& x, const std::valarray<double>& u) override {
dx[0]=u[0]*cos(x[2]);
dx[1]=u[0]*sin(x[2]);
dx[2]=u[1];
}
double getLipschitzConstant(){return lipschitz_constant;}
};
////////////////////////////////////////////////////////
/////////////////State Constraints//////////////////////
////////////////////////////////////////////////////////
class PlanarDemoObstacles: public glc::Obstacles{
int resolution;
std::valarray<double> center1;
std::valarray<double> center2;
public:
PlanarDemoObstacles(int _resolution):resolution(_resolution),center1({3.0,2.0}),center2({6.0,8.0}){}
bool collisionFree(const std::shared_ptr<glc::InterpolatingPolynomial>& traj) override {
double t=traj->initialTime();
double dt=(traj->numberOfIntervals()*traj->intervalLength())/resolution;
std::valarray<double> state;
for(int i=0;i<resolution;i++){
t+=dt;//don't need to check t0 since it was part of last traj
state=traj->at(t);
//Disk shaped obstacles
if(glc::sqr(state[0]-center1[0])+glc::sqr(state[1]-center1[1]) <= 4.0 or
glc::sqr(state[0]-center2[0])+glc::sqr(state[1]-center2[1]) <= 4.0 )
{
return false;
}
}
return true;
}
};
}//namespace example
////////////////////////////////////////////////////////
///////////////Run a planning query in main/////////////
////////////////////////////////////////////////////////
int main()
{
using namespace example;
//Motion planning algorithm parameters
glc::Parameters alg_params;
alg_params.res=21;
alg_params.control_dim = 2;
alg_params.state_dim = 3;
alg_params.depth_scale = 100;
alg_params.dt_max = 5.0;
alg_params.max_iter = 50000;
alg_params.time_scale = 20;
alg_params.partition_scale = 60;
alg_params.x0 = std::valarray<double>({0.0,0.0,M_PI/2.0});
//Create a dynamic model
CarNonholonomicConstraint dynamic_model(alg_params.dt_max);
//Create the control inputs
CarControlInputs controls(alg_params.res);
//Create the cost function
ArcLength performance_objective(4);
//Create instance of goal region
double goal_radius_sqr(.25);
std::valarray<double> goal_center({10.0,10.0});
Sphericalgoal goal(goal_radius_sqr,goal_center,10);
//Create the obstacles
PlanarDemoObstacles obstacles(10);
//Create a heuristic for the current goal
EuclideanHeuristic heuristic(goal_center,sqrt(goal_radius_sqr));
glc::Planner planner(&obstacles,
&goal,
&dynamic_model,
&heuristic,
&performance_objective,
alg_params,
controls.readInputs());
//Run the planner and print solution
glc::PlannerOutput out;
planner.plan(out);
if(out.solution_found){
std::vector<std::shared_ptr<const glc::Node>> path = planner.pathToRoot(true);
std::shared_ptr<glc::InterpolatingPolynomial> solution = planner.recoverTraj( path );
solution->printSpline(20, "Solution");
glc::trajectoryToFile("nonholonomic_car_demo.txt","./",solution,500);
glc::nodesToFile("nonholonomic_car_demo_nodes.txt","./",planner.partition_labels);
}
return 0;
}
| 37.731801 | 122 | 0.540008 | NEU-ZJX |
2f097be0d94bd131c172291d33733ee81f03f9da | 4,002 | cpp | C++ | src/Lexer/Lexeme.cpp | AlexRoar/SxTree | 7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e | [
"MIT"
] | null | null | null | src/Lexer/Lexeme.cpp | AlexRoar/SxTree | 7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e | [
"MIT"
] | null | null | null | src/Lexer/Lexeme.cpp | AlexRoar/SxTree | 7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e | [
"MIT"
] | null | null | null | /*
* =================================================
* Copyright © 2021
* Aleksandr Dremov
*
* This code has been written by Aleksandr Dremov
* Check license agreement of this project to evade
* possible illegal use.
* =================================================
*/
#include <cassert>
#include <sstream>
#include <string>
#include "Lexer/Lexeme.h"
namespace SxTree::Lexer {
using std::string;
Lexeme::Lexeme(const Lexeme &other) = default;
Lexeme::Lexeme(const string *sourceText, unsigned lexType, size_t startInd, size_t lexSize) noexcept:
source(sourceText),
type(lexType),
start(startInd),
size(lexSize){
}
void Lexeme::connect(const Lexeme &other, unsigned newType) noexcept {
if (other.size == 0) {
type = newType;
return;
}
if (other.start < start)
leftConnect(other, newType);
else
rightConnect(other, newType);
}
void Lexeme::leftConnect(const Lexeme &other, unsigned newType) noexcept {
assert((other.start + other.size <= start) && "Invalid lexemes placement");
const size_t margin = start - (other.start + other.size);
start = other.start;
size += other.size + margin;
type = newType;
}
void Lexeme::rightConnect(const Lexeme &other, unsigned newType) noexcept {
assert((other.start >= start + size) && "Invalid lexemes placement");
const size_t margin = other.start - (size + start);
size += other.size + margin;
type = newType;
}
Lexeme::Lexeme(const Lexeme &first, const Lexeme &second, unsigned lexType) noexcept :
source(first.source),
type(first.type),
start(first.start),
size(first.size){
connect(second, lexType);
}
Lexeme::Lexeme(const Lexeme &first, const Lexeme &second) noexcept:
source(first.source),
type(first.type),
start(first.start),
size(first.size){
assert(first.type == second.type);
connect(second, second.type);
}
void Lexeme::operator+=(const Lexeme &other) noexcept {
assert(type == other.type);
connect(other, other.type);
}
Lexeme Lexeme::operator+(const Lexeme &other) const noexcept {
assert(type == other.type);
return Lexeme(*this, other);
}
Lexeme::Lexeme(Lexeme &&other) noexcept:
source(other.source),
type(other.type),
start(other.start),
size(other.size){
other.type = 0;
other.source = nullptr;
other.start = other.size = 0;
}
bool Lexeme::operator==(const Lexeme &other) const noexcept {
if (other.size == size && size == 0)
return true;
if (!type || !source || other.type || other.source)
return false;
return other.start == start && other.size == size && type == other.type && source == other.source;
}
Lexeme Lexeme::zero() {
return Lexeme(nullptr, 0, 0, 0);
}
void Lexeme::setType(unsigned pString) noexcept{
type = pString;
}
string Lexeme::to_string() const {
std::stringstream ss;
ss << "Lexeme<id=" << type << ", start=" << start << ", size=" << (size) << ">";
return ss.str();
}
string Lexeme::to_stringTypeDereference(string (*to_string)(unsigned)) const {
std::stringstream ss;
ss << "Lexeme<id=" << to_string(type) << ", start=" << start << ", size=" << (size) << ">";
return ss.str();
}
unsigned Lexeme::getType() const {
return type;
}
[[maybe_unused]] size_t Lexeme::getStart() const {
return start;
}
size_t Lexeme::getSize() const {
return size;
}
string Lexeme::valueString() const{
assert(source && "Source can't be nullptr");
return source->substr(start, size);
}
} | 29.426471 | 106 | 0.555972 | AlexRoar |
2f0b35c112d2ae16e99f4262343dc034b7aed4fa | 295 | cpp | C++ | lib/store/DM.cpp | beebus/CPUfactory4 | 64d9300dae6e9553fd3fb250fba6357159d7b8e2 | [
"BSD-3-Clause"
] | 1 | 2019-04-16T14:14:49.000Z | 2019-04-16T14:14:49.000Z | lib/store/DM.cpp | beebus/CPUfactory4 | 64d9300dae6e9553fd3fb250fba6357159d7b8e2 | [
"BSD-3-Clause"
] | null | null | null | lib/store/DM.cpp | beebus/CPUfactory4 | 64d9300dae6e9553fd3fb250fba6357159d7b8e2 | [
"BSD-3-Clause"
] | 2 | 2019-05-04T21:21:08.000Z | 2019-08-30T18:19:44.000Z | // Copyright 2018 Roie R. Black
#include "DM.h"
#include <iostream>
#include <string>
// constructor
DM::DM(std::string n):Component(n) {
this->add_in_pin("MAR");
this->add_in_pin("IN");
this->add_out_pin("OUT");
}
// TICK: perform component processing
void DM::tick(int ctrl) {
}
| 18.4375 | 37 | 0.657627 | beebus |
2f137773e438c14119bec747174ff6cbb6d7e89e | 1,308 | cpp | C++ | 131_Palindrome_Partitioning.cpp | AvadheshChamola/LeetCode | b0edabfa798c4e204b015f4c367bfc5acfbd8277 | [
"MIT"
] | null | null | null | 131_Palindrome_Partitioning.cpp | AvadheshChamola/LeetCode | b0edabfa798c4e204b015f4c367bfc5acfbd8277 | [
"MIT"
] | null | null | null | 131_Palindrome_Partitioning.cpp | AvadheshChamola/LeetCode | b0edabfa798c4e204b015f4c367bfc5acfbd8277 | [
"MIT"
] | null | null | null | /*
131. Palindrome Partitioning
Medium
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward as forward.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [["a"]]
Constraints:
1 <= s.length <= 16
s contains only lowercase English letters.
*/
class Solution {
bool isPalindrome(const string &s, int start,int end){
while(start<=end){
if(s[start++]!=s[end--]){
return false;
}
}
return true;
}
void dfs( vector<vector<string>> &res,vector<string> &path,const string &s,int index){
if(index==s.size()){
res.push_back(path);
return;
}
for(int i=index;i<s.size();i++){
if(isPalindrome(s,index,i)){
path.push_back(s.substr(index,i-index+1));
dfs(res,path,s,i+1);
path.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
if(s.size()==0) return res;
vector<string> path;
dfs(res,path,s,0);
return res;
}
};
| 25.647059 | 139 | 0.552752 | AvadheshChamola |
2f13e1691d49d5cf4d2356a1c442923c6c675ffa | 4,736 | cpp | C++ | projects/PolyhedralModel/projects/spmd-generator/polydriver/polyhedral-utils.cpp | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 4 | 2017-12-19T17:15:00.000Z | 2021-02-05T12:25:50.000Z | projects/PolyhedralModel/projects/spmd-generator/polydriver/polyhedral-utils.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | null | null | null | projects/PolyhedralModel/projects/spmd-generator/polydriver/polyhedral-utils.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 2 | 2019-02-19T01:27:51.000Z | 2019-02-19T12:29:49.000Z |
#include "polydriver/polyhedral-utils.hpp"
#include "rose/Attribute.hpp"
#include "rose/Parser.hpp"
#include "rose/Exception-rose.hpp"
namespace PolyhedricAnnotation {
/**************/
/* Containers */
/**************/
/* PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> */
template <>
PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> & getPolyhedralProgram<SgStatement, SgExprStatement, RoseVariable>(const SgStatement * arg) {
PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> * res = dynamic_cast<PolyhedralProgramAttribute<SgStatement> *>(arg->getAttribute("PolyhedricAnnotation::PolyhedralProgram"));
if (!res)
throw Exception::RoseAttributeMissing("PolyhedricAnnotation::PolyhedralProgram", arg);
return *res;
}
template <>
void setPolyhedralProgram<SgStatement, SgExprStatement, RoseVariable>(SgStatement * arg) {
new PolyhedralProgramAttribute<SgStatement>(arg);
}
/* Domain<SgStatement, SgExprStatement, RoseVariable> */
template <>
Domain<SgStatement, SgExprStatement, RoseVariable> & getDomain<SgStatement, SgExprStatement, RoseVariable>(const SgExprStatement * arg) {
Domain<SgStatement, SgExprStatement, RoseVariable> * res = dynamic_cast<DomainAttribute<SgStatement> *>(arg->getAttribute("PolyhedricAnnotation::Domain"));
if (!res) {
throw Exception::RoseAttributeMissing("PolyhedricAnnotation::Domain", arg);
}
return *res;
}
template <>
void setDomain<SgStatement, SgExprStatement, RoseVariable>(
PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> & polyhedral_program,
SgExprStatement * expression,
size_t nbr_iterators
) {
new DomainAttribute<SgStatement>(polyhedral_program, expression, nbr_iterators);
}
/* Scattering<SgStatement, SgExprStatement, RoseVariable> */
template <>
Scattering<SgStatement, SgExprStatement, RoseVariable> & getScattering<SgStatement, SgExprStatement, RoseVariable>(const SgExprStatement * arg) {
Scattering<SgStatement, SgExprStatement, RoseVariable> * res = dynamic_cast<ScatteringAttribute<SgStatement> *>(arg->getAttribute("PolyhedricAnnotation::Scattering"));
if (!res) {
throw Exception::RoseAttributeMissing("PolyhedricAnnotation::Scattering", arg);
}
return *res;
}
template <>
void setScattering<SgStatement, SgExprStatement, RoseVariable>(
PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> & polyhedral_program,
SgExprStatement * expression,
size_t nbr_iterators
) {
new ScatteringAttribute<SgStatement>(polyhedral_program, expression, nbr_iterators);
}
/* DataAccess<SgStatement, SgExprStatement, RoseVariable> */
template <>
DataAccess<SgStatement, SgExprStatement, RoseVariable> & getDataAccess<SgStatement, SgExprStatement, RoseVariable>(const SgExprStatement * arg) {
DataAccess<SgStatement, SgExprStatement, RoseVariable> * res = dynamic_cast<DataAccessAttribute<SgStatement> *>(arg->getAttribute("PolyhedricAnnotation::DataAccess"));
if (!res) {
throw Exception::RoseAttributeMissing("PolyhedricAnnotation::DataAccess", arg);
}
return *res;
}
template <>
void setDataAccess<SgStatement, SgExprStatement, RoseVariable>(
PolyhedralProgram<SgStatement, SgExprStatement, RoseVariable> & polyhedral_program,
SgExprStatement * expression,
size_t nbr_iterators
) {
new DataAccessAttribute<SgStatement>(polyhedral_program, expression, nbr_iterators);
}
template <>
void makeAccessAnnotation<SgStatement, SgExprStatement, RoseVariable>(
SgExprStatement * expression,
PolyhedricAnnotation::DataAccess<SgStatement, SgExprStatement, RoseVariable> & data_access
) {
makeAccessAnnotationSage<SgStatement>(expression, data_access);
}
}
std::ostream & operator << (std::ostream & out, SgStatement & arg) {
out << arg.unparseToString();
return out;
}
std::ostream & operator << (std::ostream & out, const SgStatement & arg) {
out << arg.unparseToString();
return out;
}
const Polyhedron & getDomain(const std::pair<SgExprStatement *, size_t> obj) {
return PolyhedricAnnotation::getDomain<SgStatement, SgExprStatement, RoseVariable>(obj.first).getDomainPolyhedron();
}
const std::vector<LinearExpression_ppl> & getScattering(const std::pair<SgExprStatement *, size_t> obj) {
return PolyhedricAnnotation::getScattering<SgStatement, SgExprStatement, RoseVariable>(obj.first).getScattering();
}
size_t getDimension(const std::pair<SgExprStatement *, size_t> obj) {
return PolyhedricAnnotation::getDomain<SgStatement, SgExprStatement, RoseVariable>(obj.first).getNumberOfIterators();
}
size_t getExtraDimension(const std::pair<SgExprStatement *, size_t> obj) {
return PolyhedricAnnotation::getDomain<SgStatement, SgExprStatement, RoseVariable>(obj.first).getNumberOfGlobals();
}
| 37.888 | 190 | 0.774704 | maurizioabba |
2f16d0d651ce51c3da4780057264f884aacf19cc | 6,354 | cpp | C++ | master/core/third/cxxtools/demo/rpcserver.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/cxxtools/demo/rpcserver.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/cxxtools/demo/rpcserver.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:49.000Z | 2018-12-27T03:20:31.000Z | /*
* Copyright (C) 2009,2011 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Cxxtools implements a rpc framework, which can run with 4 protocols.
Xmlrpc is a simple xml based standard protocol. The spec can be found at
http://www.xmlrpc.org/.
Json rpc is a json based standard protocol. The sepc can be found at
http://json-rpc.org. Json is less verbose than xml and therefore jsonrpc is a
little faster than xmlrpc.
Json rpc comes in cxxtools in 2 flavours: raw and http.
And last but not least cxxtools has a own non standard binary protocol. It is
faster than xmlrpc or jsonrpc but works only with cxxtools.
This demo program implements a server, which runs all 4 flavours in a single
event loop.
*/
#include <iostream>
#include <cxxtools/arg.h>
#include <cxxtools/log.h>
#include <cxxtools/xmlrpc/service.h>
#include <cxxtools/http/server.h>
#include <cxxtools/bin/rpcserver.h>
#include <cxxtools/json/rpcserver.h>
#include <cxxtools/json/httpservice.h>
#include <cxxtools/eventloop.h>
////////////////////////////////////////////////////////////////////////
// This defines functions, which we want to be called remotely.
//
// Parameters and return values of the functions, which can be exported must be
// serializable and deserializable with the cxxtools serialization framework.
// For all standard types including container classes in the standard library
// proper operators are defined in cxxtools.
//
std::string echo(const std::string& message)
{
std::cout << message << std::endl;
return message;
}
double add(double a1, double a2)
{
return a1 + a2;
}
////////////////////////////////////////////////////////////////////////
// main
//
int main(int argc, char* argv[])
{
try
{
// initialize logging - this reads the file log.xml from the current directory
log_init();
// read the command line options
// option -i <ip-address> defines the ip address of the interface, where the
// server waits for connections. Default is empty, which tells the server to
// listen on all local interfaces
cxxtools::Arg<std::string> ip(argc, argv, 'i');
// option -p <number> specifies the port, where http requests are expected.
// This port is valid for xmlrpc and json over http. It defaults to 7002.
cxxtools::Arg<unsigned short> port(argc, argv, 'p', 7002);
// option -b <number> specifies the port, where the binary server waits for
// requests. It defaults to port 7003.
cxxtools::Arg<unsigned short> bport(argc, argv, 'b', 7003);
// option -j <number> specifies the port, where the json server wait for
// requests. It defaults to port 7004.
cxxtools::Arg<unsigned short> jport(argc, argv, 'j', 7004);
std::cout << "run rpcecho server\n"
<< "http protocol on port "<< port.getValue() << "\n"
<< "binary protocol on port " << bport.getValue() << "\n"
<< "json protocol on port " << jport.getValue() << std::endl;
// create an event loop
cxxtools::EventLoop loop;
// the http server is instantiated with an ip address and a port number
// It will be used for xmlrpc and json over http on different urls.
cxxtools::http::Server httpServer(loop, ip, port);
////////////////////////////////////////////////////////////////////////
// Xmlrpc
// we create an instance of the service class
cxxtools::xmlrpc::Service xmlrpcService;
// we register our functions
xmlrpcService.registerFunction("echo", echo);
xmlrpcService.registerFunction("add", add);
// ... and register the service under a url
httpServer.addService("/xmlrpc", xmlrpcService);
////////////////////////////////////////////////////////////////////////
// Binary rpc
// for the binary rpc server we define a binary server
cxxtools::bin::RpcServer binServer(loop, ip, bport);
// and register the functions in the server
binServer.registerFunction("echo", echo);
binServer.registerFunction("add", add);
////////////////////////////////////////////////////////////////////////
// Json rpc
// for the json rpc server we define a json server
cxxtools::json::RpcServer jsonServer(loop, ip, jport);
// and register the functions in the server
jsonServer.registerFunction("echo", echo);
jsonServer.registerFunction("add", add);
////////////////////////////////////////////////////////////////////////
// Json rpc over http
// for json over http we need a service object
cxxtools::json::HttpService jsonhttpService;
// we register our functions
jsonhttpService.registerFunction("echo", echo);
jsonhttpService.registerFunction("add", add);
// ... and register the service under a url
httpServer.addService("/jsonrpc", jsonhttpService);
////////////////////////////////////////////////////////////////////////
// Run
// now start the servers by running the event loop
loop.run();
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
| 35.497207 | 82 | 0.64542 | importlib |
2f1b82ad36e933c47b74254aed15f5d1e3f5cb8f | 3,354 | cc | C++ | client/common/charsetutils.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | client/common/charsetutils.cc | DalavanCloud/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | client/common/charsetutils.cc | DalavanCloud/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2014 Google 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.
*/
// This file contains the implementation of CharsetUtils classes, which declares
// static methods for charset operations. See comments before each method
// for details.
#include "common/charsetutils.h"
namespace ime_goopy {
// Convert Simplified Chinese string into Traditional Chinese
// source: Simplified Chinese string
// target: buffer to translate result
std::wstring CharsetUtils::Simplified2Traditional(const std::wstring& source) {
int len = static_cast<int>(source.size());
WCHAR* target_str = new WCHAR[len + 1];
// translate simplified chinese into traditional chinese
LCID lcid = MAKELCID(
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED),
SORT_CHINESE_PRCP);
LCMapString(lcid, LCMAP_TRADITIONAL_CHINESE,
source.c_str(), len, target_str, len);
target_str[len]= L'\0';
std::wstring target = target_str;
delete[] target_str;
return target;
}
// Convert Traditional Chinese string into Simplified Chinese
// source: Traditional Chinese string
// target: buffer to translate result
std::wstring CharsetUtils::Traditional2Simplified(const std::wstring& source) {
int len = static_cast<int>(source.size());
WCHAR* target_str = new WCHAR[len + 1];
// translate Traditional Chinese into Simplified Chinese
LCID lcid = MAKELCID(
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED),
SORT_CHINESE_BIG5);
LCMapString(lcid, LCMAP_SIMPLIFIED_CHINESE,
source.c_str(), len, target_str, len);
target_str[len]= L'\0';
std::wstring target = target_str;
delete[] target_str;
return target;
}
// Convert Unicode string into UTF8
// source: Traditional Chinese string
// target: buffer to translate result
std::wstring CharsetUtils::Unicode2UTF8Escaped(const std::wstring& source) {
std::wstring output;
int len = WideCharToMultiByte(CP_UTF8, 0, source.c_str(),
static_cast<int>(source.size()),
NULL, 0, NULL, NULL);
if (len == 0) return output;
char* utf8_string = new char[len];
if (!utf8_string) return output;
WideCharToMultiByte(CP_UTF8, 0, source.c_str(),
static_cast<int>(source.size()), utf8_string,
len, NULL, NULL);
output = UTF8ToWstringEscaped(utf8_string, len);
delete[] utf8_string;
return output;
}
// Convert utf8 encoded string to wstring.
// source: utf8 encoded string buffer pointer
// length: buffer length
std::wstring CharsetUtils::UTF8ToWstringEscaped(
const char* source, int length) {
std::wstring output;
wchar_t ch[10] = {0};
for (int i = 0; i < length; ++i) {
wsprintf(ch, L"%%%2X",
static_cast<UINT>(static_cast<BYTE>(source[i])));
output += ch;
}
return output;
}
} // namespace ime_goopy
| 34.9375 | 80 | 0.705128 | zamorajavi |
2f1ea34e1ec57d9bf981a0ff47629286ebdb1b2d | 1,010 | cpp | C++ | src/cpu.cpp | KhaledYassin/CppND-System-Monitor-Project-Updated | 9830ca4f7b877151b5c987b23d7682215363abdb | [
"MIT"
] | null | null | null | src/cpu.cpp | KhaledYassin/CppND-System-Monitor-Project-Updated | 9830ca4f7b877151b5c987b23d7682215363abdb | [
"MIT"
] | null | null | null | src/cpu.cpp | KhaledYassin/CppND-System-Monitor-Project-Updated | 9830ca4f7b877151b5c987b23d7682215363abdb | [
"MIT"
] | null | null | null | #include "cpu.h"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "processor.h"
const std::string CPU::kProcessesName = "processes";
const std::string CPU::kRunningProcessesName = "procs_running";
CPU::CPU(const std::string name) { this->name_ = name; }
std::map<std::string, Processor>& CPU::GetCores() { return cores_; }
void CPU::AddCore(const std::string name) { cores_[name] = Processor(name); }
bool CPU::CoreExists(const std::string name) {
return cores_.find(name) != cores_.end();
}
int CPU::GetTotalProcesses() { return total_processes_; }
int CPU::GetRunningProcesses() { return procs_running_; }
void CPU::UpdateStatistics() {
Processor::UpdateStatistics();
std::for_each(cores_.begin(), cores_.end(),
[](auto& core) { core.second.UpdateStatistics(); });
total_processes_ = metrics_[kProcessesName].GetValue();
procs_running_ = metrics_[kRunningProcessesName].GetValue();
} | 28.857143 | 77 | 0.709901 | KhaledYassin |
2f2094af3f619c1ac5179d0720e71d505601969b | 1,134 | cpp | C++ | C++/merge_sort.cpp | Shubham56-droid/DataStruture-and-algroithms-in-C- | d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2 | [
"MIT"
] | 80 | 2021-10-05T08:30:07.000Z | 2022-03-04T19:42:53.000Z | C++/merge_sort.cpp | Shubham56-droid/DataStruture-and-algroithms-in-C- | d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2 | [
"MIT"
] | 182 | 2021-10-05T08:50:50.000Z | 2022-01-31T17:53:04.000Z | C++/merge_sort.cpp | Shubham56-droid/DataStruture-and-algroithms-in-C- | d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2 | [
"MIT"
] | 104 | 2021-10-05T08:45:31.000Z | 2022-01-24T10:16:37.000Z | #include <bits/stdc++.h>
using namespace std;
void merge(int *arr, int l, int mid, int r)
{
int n1 = mid - l + 1, n2 = r - mid;
int a[n1], b[n2];
for (int i = 0; i < n1; i++)
{
a[i] = arr[l + i];
}
for (int i = 0; i < n2; i++)
{
b[i] = arr[mid + 1 + i];
}
int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
{
if (a[i] < b[j])
{
arr[k] = a[i];
k++, i++;
}
else
{
arr[k] = b[j];
k++, j++;
}
}
while (i < n1)
{
arr[k] = a[i];
k++, i++;
}
while (j < n2)
{
arr[k] = b[j];
k++, j++;
}
}
void mergesort(int *arr, int l, int r)
{
if (l >= r)
return;
int mid = (l + r) / 2;
mergesort(arr, l, mid);
mergesort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
mergesort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
//Time complexity: T(n)=T(n/2)+n total=nlogn | 18.590164 | 44 | 0.354497 | Shubham56-droid |
2f20a05df79a73a1d0c5be0b2c1734c021acba4b | 5,479 | hh | C++ | source/Utilities/shared/CalibrationYaml.hh | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | source/Utilities/shared/CalibrationYaml.hh | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | source/Utilities/shared/CalibrationYaml.hh | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | /**
* @file shared/CalibrationYaml.hh
*
* Copyright 2013
* Carnegie Robotics, LLC
* 4501 Hatfield Street, Pittsburgh, PA 15201
* http://www.carnegierobotics.com
*
* 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 Carnegie Robotics, LLC 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 CARNEGIE ROBOTICS, LLC 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.
*
**/
#ifndef CALIBRATION_YAML_HH
#define CALIBRATION_YAML_HH
#include <stdint.h>
#include <iostream>
#include <string>
#include <vector>
template<typename T>
std::ostream& writeMatrix (std::ostream& stream, std::string const& name, uint32_t rows, uint32_t columns, T const* data)
{
stream << name << ": !!opencv-matrix\n";
stream << " rows: " << rows << "\n";
stream << " cols: " << columns << "\n";
stream << " dt: d\n";
stream << " data: [ ";
stream.precision (17);
stream << std::scientific;
for (uint32_t i = 0; i < rows; i++)
{
if (i != 0)
{
stream << ",\n";
stream << " ";
}
for (uint32_t j = 0; j < columns; j++)
{
if (j != 0)
{
stream << ", ";
}
stream << data[i * columns + j];
}
}
stream << " ]\n";
return stream;
}
class Expect
{
private:
std::string m_value;
public:
Expect (std::string const& value) :
m_value (value)
{
}
std::string const& value () const
{
return this->m_value;
}
};
std::istream& operator >> (std::istream& stream, Expect const& expect)
{
stream >> std::ws;
for (std::string::const_iterator iter = expect.value ().begin (); iter != expect.value ().end (); ++iter)
{
if (*iter == ' ')
{
stream >> std::ws;
continue;
}
if (stream.get () != *iter)
{
stream.clear (std::ios_base::failbit);
break;
}
}
return stream;
}
template<typename T>
std::istream& operator >> (std::istream& stream, std::vector<T>& data)
{
char input;
while (stream.good ())
{
input = 0;
stream >> input;
if (input == '[')
{
stream >> data;
}
else
{
stream.putback (input);
T value;
stream >> value;
data.push_back (value);
}
input = 0;
stream >> input;
if (input == ']')
{
break;
}
else if (input != ',')
{
stream.clear (std::ios_base::failbit);
break;
}
}
return stream;
}
std::istream& parseYaml (std::istream& stream, std::map<std::string, std::vector<float> >& data)
{
char input;
while (stream.good ())
{
input = 0;
stream >> input;
if (input == '%')
{
std::string comment;
std::getline (stream, comment);
continue;
}
stream.putback (input);
std::string name;
stream >> name;
if (name.empty ())
{
break;
}
if (name[name.size () - 1] != ':')
{
stream.clear (std::ios_base::failbit);
break;
}
name.resize (name.size () - 1);
std::vector<float> arrayContents;
arrayContents.clear ();
input = 0;
stream >> input;
if (input == '[')
{
stream >> arrayContents;
}
else
{
stream.putback (input);
uint32_t rows = 0;
uint32_t columns = 0;
stream >> Expect ("!!opencv-matrix");
stream >> Expect ("rows:") >> rows;
stream >> Expect ("cols:") >> columns;
stream >> Expect ("dt: d");
stream >> Expect ("data: [") >> arrayContents;
}
if (stream.good())
{
data.insert (std::make_pair(name, arrayContents));
}
else
{
fprintf (stderr, "Error parsing data near array \"%s\"", name.c_str());
}
}
return stream;
}
#endif //CALIBRATION_YAML_HH
| 25.602804 | 121 | 0.548275 | DArpinoRobotics |
2f2116da52f0819186c50970bd8dc5b4ce95ad6b | 857 | cpp | C++ | src/util/os_structs.cpp | dulingzhi/D2RMH | f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2 | [
"MIT"
] | 125 | 2021-10-31T05:55:12.000Z | 2022-03-30T09:15:29.000Z | src/util/os_structs.cpp | dulingzhi/D2RMH | f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2 | [
"MIT"
] | 93 | 2021-10-31T11:19:37.000Z | 2022-03-31T13:25:54.000Z | src/util/os_structs.cpp | dulingzhi/D2RMH | f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2 | [
"MIT"
] | 57 | 2021-10-30T08:45:05.000Z | 2022-03-30T04:11:21.000Z | /*
* Copyright (c) 2021 Soar Qin<soarchin@gmail.com>
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
#include "os_structs.h"
extern "C" {
#if defined(_M_IX86)
NtWow64QueryInformationProcess64Proc NtWow64QueryInformationProcess64;
NtWow64ReadVirtualMemory64Proc NtWow64ReadVirtualMemory64;
static HMODULE getNtDllMod() {
static HMODULE ntdllMod = LoadLibraryA("ntdll.dll");
return ntdllMod;
}
#endif
void osInit() {
#if defined(_M_IX86)
NtWow64QueryInformationProcess64 =
(NtWow64QueryInformationProcess64Proc)GetProcAddress(getNtDllMod(), "NtWow64QueryInformationProcess64");
NtWow64ReadVirtualMemory64 =
(NtWow64ReadVirtualMemory64Proc)GetProcAddress(getNtDllMod(), "NtWow64ReadVirtualMemory64");
#endif
}
}
| 25.969697 | 112 | 0.770128 | dulingzhi |
2f241a83937550facec49079a4c99c4ee60e0fce | 2,451 | cpp | C++ | cccc/tests/lexer/location_spec.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | cccc/tests/lexer/location_spec.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | cccc/tests/lexer/location_spec.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | #include <test_suite.hpp>
#include <gtest/gtest.h>
#define MYTEST(Y) TEST(lexer_locations, locations_ ## Y)
using namespace mhc4;
static const std::string f = "location.c";
const test_suite ts(f);
std::ostream& operator<<(std::ostream& os, const token& tok)
{
return os << tok.to_string();
}
MYTEST(lf_0)
{
auto vec = ts.lex_all("test\na", 6);
EXPECT_EQ(ts.get_identifier_token("test", 1, 1), vec[0]);
EXPECT_EQ(ts.get_identifier_token("a", 2, 1), vec[1]);
}
MYTEST(lf_1)
{
auto vec = ts.lex_all("\n 123", 5);
EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]);
}
MYTEST(cr_0)
{
auto vec = ts.lex_all("hi\rho", 5);
EXPECT_EQ(ts.get_identifier_token("hi", 1, 1), vec[0]);
EXPECT_EQ(ts.get_identifier_token("ho", 2, 1), vec[1]);
}
MYTEST(cr_1)
{
auto vec = ts.lex_all("\r 123", 5);
EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]);
}
MYTEST(crlf_0)
{
auto vec = ts.lex_all("Welt\r\nHallo", 11);
EXPECT_EQ(ts.get_identifier_token("Welt", 1, 1), vec[0]);
EXPECT_EQ(ts.get_identifier_token("Hallo", 2, 1), vec[1]);
}
MYTEST(crlf_1)
{
auto vec = ts.lex_all("\r\n 123", 6);
EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]);
}
MYTEST(column)
{
auto vec = ts.lex_all("ab 12", 5);
EXPECT_EQ(ts.get_identifier_token("ab", 1, 1), vec[0]);
EXPECT_EQ(ts.get_numeric_token("12", 1, 4), vec[1]);
}
MYTEST(row_0)
{
auto vec = ts.lex_all("\nHello", 6);
EXPECT_EQ(ts.get_identifier_token("Hello", 2, 1), vec[0]);
}
MYTEST(row_1)
{
auto vec = ts.lex_all("\n\nHello\n\n", 8);
EXPECT_EQ(ts.get_identifier_token("Hello", 3, 1), vec[0]);
}
MYTEST(fail_location_0)
{
try
{
ts.lex_all("\n''", 3);
ASSERT_FALSE(true) << "Expected lexing to fail for \"''\"";
}
catch(std::invalid_argument& arg)
{
EXPECT_EQ(f + ":2:2: error: Couldn\'t lex \"''\"", arg.what());
}
}
MYTEST(fail_location_1)
{
try
{
ts.lex_all("Hallo =\n ''", 12);
ASSERT_FALSE(true) << "Expected lexing to fail for \"''\"";
}
catch(std::invalid_argument& arg)
{
EXPECT_EQ(f + ":2:4: error: Couldn\'t lex \"''\"", arg.what());
}
}
MYTEST(fail_location_2)
{
try
{
ts.lex_all(" ''", 3);
ASSERT_FALSE(true) << "Expected lexing to fail for \"''\"";
}
catch(std::invalid_argument& arg)
{
EXPECT_EQ(f + ":1:3: error: Couldn\'t lex \"''\"", arg.what());
}
}
| 21.690265 | 71 | 0.585883 | DasNaCl |
2f2a2b68d981188819dce2b84abf38b75f5d04b3 | 679 | cpp | C++ | AcWing/LeetCode究极班/135.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | AcWing/LeetCode究极班/135.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | AcWing/LeetCode究极班/135.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
public:
vector<int> w;
int n;
vector<int> f; // 记忆化搜索
int candy(vector<int>& ratings) {
w = ratings;
n = ratings.size();
f.resize(n, -1); // -1表示没计算过
// 计算每个人分的糖果
int res = 0;
for (int i = 0; i < n; i ++ )
res += dp(i);
return res;
}
int dp(int x) {
if (f[x] != -1)
return f[x];
f[x] = 1; // 至少分一个糖果
if (x - 1 >= 0 && w[x] > w[x - 1])
f[x] = max(f[x], dp(x - 1) + 1); // 因为x-1和x+1也不一定算过,所以这里还是要写dp,不能写f
if (x + 1 < n && w[x] > w[x + 1])
f[x] = max(f[x], dp(x + 1) + 1);
return f[x];
}
}; | 23.413793 | 79 | 0.384389 | LauZyHou |
2f2c9683ffc93dc586d8d2eb08f1a7fd96ae2473 | 2,441 | cpp | C++ | rescan_file_task.cpp | tim77/qt-virustotal-uploader | d616ab0d709ff3be2eeb062d76e2338d8c2d22dd | [
"Apache-2.0"
] | 227 | 2015-04-16T03:23:15.000Z | 2022-03-28T15:54:04.000Z | rescan_file_task.cpp | tim77/qt-virustotal-uploader | d616ab0d709ff3be2eeb062d76e2338d8c2d22dd | [
"Apache-2.0"
] | 10 | 2016-04-30T18:19:43.000Z | 2021-11-17T01:41:30.000Z | rescan_file_task.cpp | tim77/qt-virustotal-uploader | d616ab0d709ff3be2eeb062d76e2338d8c2d22dd | [
"Apache-2.0"
] | 75 | 2015-03-17T16:29:00.000Z | 2022-03-05T09:19:14.000Z | /*
Copyright 2014 VirusTotal S.L. All rights reserved.
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 <QDebug>
#include <jansson.h>
#include "rescan_file_task.h"
#include "VtFile.h"
#include "VtResponse.h"
#include "qvtfile.h"
#include "vt-log.h"
RescanFileTask::RescanFileTask(QVtFile *f)
{
file = f;
}
#define RESP_BUF_SIZE 255
void RescanFileTask::run(void)
{
int ret;
struct VtFile *api = VtFile_new();
struct VtResponse *response;
char *str = NULL;
char buf[RESP_BUF_SIZE+1] = { 0, };
int response_code;
// connect(this, SIGNAL(LogMsg(int,int,QString)),file, SLOT(RelayLogMsg(int,int,QString)));
VtFile_setApiKey(api, file->GetApiKey().toStdString().c_str());
ret = VtFile_rescanHash(api,
QString(file->GetSha256().toHex()).toStdString().c_str(),
0, 0, 0, NULL, false);
if (ret) {
qDebug() << "Error opening fetching report " << QString(file->GetSha256().toHex()) << " " << ret;
file->SetState(kWaitForReport);
emit LogMsg(VT_LOG_ERR, ret, "Error fetching report");
} else {
response = VtFile_getResponse(api);
str = VtResponse_toJSONstr(response, VT_JSON_FLAG_INDENT);
if (str) {
qDebug() << "report Response: " << str;
free(str);
}
VtResponse_getVerboseMsg(response, buf, RESP_BUF_SIZE);
qDebug() << "Buff: " << buf;
file->SetVerboseMsg(buf);
ret = VtResponse_getResponseCode(response, &response_code);
if (!ret) {
qDebug() << "report response code: " << response_code;
if (response_code == 0) {
file->SetState(kError);
goto free_response;
}
}
str = VtResponse_getString(response, "permalink");
if (str) {
file->SetPermalink(str);
free(str);
}
str = VtResponse_getString(response, "scan_id");
if (str) {
file->SetScanId(str);
free(str);
}
file->SetState(kWaitForReport);
free_response:
VtResponse_put(&response);
}
VtFile_put(&api);
}
| 26.824176 | 103 | 0.671856 | tim77 |
2f2f997852d864206d1a80fd3be31ec589d7f589 | 663 | cpp | C++ | freshman/midterm3/p3w2d.cpp | tsung1271232/581_homework | 36b36b3380ed5161b3e28e3b7999a1d620736da1 | [
"MIT"
] | null | null | null | freshman/midterm3/p3w2d.cpp | tsung1271232/581_homework | 36b36b3380ed5161b3e28e3b7999a1d620736da1 | [
"MIT"
] | null | null | null | freshman/midterm3/p3w2d.cpp | tsung1271232/581_homework | 36b36b3380ed5161b3e28e3b7999a1d620736da1 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long int number;
while(1)
{
cin>>number;
if(number==0)
break;
long long int table[300][300]= {},coun[300][300]= {};
for(int i=1; i<=number; i++)
for(int j=1; j<=number; j++)
cin>>table[i][j];
coun[1][1]=table[1][1];
for(int i=1; i<=number; i++)
for(int j=1; j<=number; j++)
{
long long int add=(coun[i-1][j]>=coun[i][j-1])?coun[i-1][j]:coun[i][j-1];
coun[i][j]=add+table[i][j];
}
cout<<coun[number][number]<<endl;
}
}
| 24.555556 | 89 | 0.432881 | tsung1271232 |
2f33ff3c7d9e9a30e14c39cfa65ffeb535bae601 | 28,614 | cpp | C++ | kvbc/src/kvbc_app_filter/kvbc_app_filter.cpp | evdzhurov/concord-bft | 2e4fdabe0228b51d4d43398158e97d4e36ff974a | [
"Apache-2.0"
] | null | null | null | kvbc/src/kvbc_app_filter/kvbc_app_filter.cpp | evdzhurov/concord-bft | 2e4fdabe0228b51d4d43398158e97d4e36ff974a | [
"Apache-2.0"
] | null | null | null | kvbc/src/kvbc_app_filter/kvbc_app_filter.cpp | evdzhurov/concord-bft | 2e4fdabe0228b51d4d43398158e97d4e36ff974a | [
"Apache-2.0"
] | null | null | null | // Concord
//
// Copyright (c) 2021 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the subcomponent's license, as noted in the LICENSE
// file.
//
// Filtered access to the KV Blockchain.
#include "kvbc_app_filter/kvbc_app_filter.h"
#include <boost/detail/endian.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <cassert>
#include <chrono>
#include <exception>
#include <optional>
#include <sstream>
#include "Logger.hpp"
#include "concord_kvbc.pb.h"
#include "kv_types.hpp"
#include "kvbc_app_filter/kvbc_key_types.h"
#include "openssl_crypto.hpp"
using namespace std::chrono_literals;
using std::map;
using std::optional;
using std::string;
using std::stringstream;
using boost::lockfree::spsc_queue;
using com::vmware::concord::kvbc::ValueWithTrids;
using concord::kvbc::BlockId;
using concord::kvbc::categorization::ImmutableInput;
using concord::kvbc::InvalidBlockRange;
using concord::util::openssl_utils::computeSHA256Hash;
using concord::util::openssl_utils::kExpectedSHA256HashLengthInBytes;
namespace concord {
namespace kvbc {
uint64_t KvbAppFilter::getOldestGlobalEventGroupId() const { return getValueFromLatestTable(kGlobalEgIdKeyOldest); }
uint64_t KvbAppFilter::getNewestPublicEventGroupId() const { return getValueFromLatestTable(kPublicEgIdKeyNewest); }
std::optional<kvbc::categorization::EventGroup> KvbAppFilter::getNewestPublicEventGroup() const {
const auto newest_pub_eg_id = getNewestPublicEventGroupId();
if (newest_pub_eg_id == 0) {
// No public event group ID.
return std::nullopt;
}
const auto [global_eg_id, _] = getValueFromTagTable(kPublicEgId, newest_pub_eg_id);
(void)_;
return getEventGroup(global_eg_id);
}
optional<BlockId> KvbAppFilter::getOldestEventGroupBlockId() {
uint64_t global_eg_id_oldest = getOldestGlobalEventGroupId();
const auto opt = rostorage_->getLatestVersion(concord::kvbc::categorization::kExecutionEventGroupDataCategory,
concordUtils::toBigEndianStringBuffer(global_eg_id_oldest));
if (not opt.has_value()) {
return std::nullopt;
}
return {opt->version};
}
KvbFilteredUpdate::OrderedKVPairs KvbAppFilter::filterKeyValuePairs(const kvbc::categorization::ImmutableInput &kvs) {
KvbFilteredUpdate::OrderedKVPairs filtered_kvs;
for (auto &[prefixed_key, value] : kvs.kv) {
// Remove the Block ID prefix from the key before using it.
ConcordAssertGE(prefixed_key.size(), sizeof(kvbc::BlockId));
auto key = prefixed_key.size() == sizeof(kvbc::BlockId) ? std::string{} : prefixed_key.substr(sizeof(BlockId));
// If no TRIDs attached then everyone is allowed to view the pair
// Otherwise, check against the client id
if (value.tags.size() > 0) {
bool contains_client_id = false;
for (const auto &trid : value.tags) {
if (trid.compare(client_id_) == 0) {
contains_client_id = true;
break;
}
}
if (!contains_client_id) {
continue;
}
}
ValueWithTrids proto;
if (!proto.ParseFromArray(value.data.c_str(), value.data.length())) {
continue;
}
// We expect a value - this should never trigger
if (!proto.has_value()) {
std::stringstream msg;
msg << "Couldn't decode value with trids " << key;
throw KvbReadError(msg.str());
}
auto val = proto.release_value();
filtered_kvs.push_back({std::move(key), std::move(*val)});
delete val;
}
return filtered_kvs;
}
KvbFilteredEventGroupUpdate::EventGroup KvbAppFilter::filterEventsInEventGroup(
EventGroupId event_group_id, const kvbc::categorization::EventGroup &event_group) {
KvbFilteredEventGroupUpdate::EventGroup filtered_event_group;
filtered_event_group.record_time = event_group.record_time;
for (auto event : event_group.events) {
// If no TRIDs attached then everyone is allowed to view the pair
// Otherwise, check against the client id
if (event.tags.size() > 0) {
bool contains_client_id = false;
for (const auto &trid : event.tags) {
if (trid.compare(client_id_) == 0) {
contains_client_id = true;
break;
}
}
if (!contains_client_id) {
continue;
}
}
// Event data encodes ValueWithTrids
// Extract the value, and assign it to event.data
ValueWithTrids proto;
if (!proto.ParseFromArray(event.data.c_str(), event.data.length())) {
continue;
}
// We expect a value - this should never trigger
if (!proto.has_value()) {
std::stringstream msg;
msg << "Couldn't decode value with trids for event_group_id" << event_group_id;
throw KvbReadError(msg.str());
}
auto val = proto.release_value();
event.data.assign(std::move(*val));
filtered_event_group.events.emplace_back(std::move(event));
delete val;
}
return filtered_event_group;
}
KvbFilteredUpdate KvbAppFilter::filterUpdate(const KvbUpdate &update) {
auto &[block_id, cid, updates, _] = update;
return KvbFilteredUpdate{block_id, cid, filterKeyValuePairs(updates)};
}
std::optional<KvbFilteredEventGroupUpdate> KvbAppFilter::filterEventGroupUpdate(const EgUpdate &update) {
auto &[event_group_id, event_group, _] = update;
KvbFilteredEventGroupUpdate filtered_update{event_group_id, filterEventsInEventGroup(event_group_id, event_group)};
// Ignore empty event groups
if (filtered_update.event_group.events.empty()) {
return std::nullopt;
}
return filtered_update;
}
string KvbAppFilter::hashUpdate(const KvbFilteredUpdate &update) {
// Note we store the hashes of the keys and values in an std::map as an
// intermediate step in the computation of the update hash so the map can be
// used to deterministically order the key-value pairs' hashes before they are
// concatenated for the computation of the update hash. The deterministic
// ordering is necessary since two updates with the same set of key-value
// pairs in different orders are considered equivalent so their hashes need to
// match.
map<string, string> entry_hashes;
auto &[block_id, _, updates] = update;
for (const auto &[key, value] : updates) {
string key_hash = computeSHA256Hash(key.data(), key.length());
ConcordAssertLT(entry_hashes.count(key_hash), 1);
entry_hashes[key_hash] = computeSHA256Hash(value.data(), value.length());
}
string concatenated_entry_hashes;
concatenated_entry_hashes.reserve(sizeof(BlockId) + 2 * updates.size() * kExpectedSHA256HashLengthInBytes);
#ifdef BOOST_LITTLE_ENDIAN
concatenated_entry_hashes.append(reinterpret_cast<const char *>(&(block_id)), sizeof(block_id));
#else // BOOST_LITTLE_ENDIAN not defined in this case
#ifndef BOOST_BIG_ENDIAN
static_assert(false,
"Cannot determine endianness (needed for Thin Replica "
"mechanism hash function).");
#endif // BOOST_BIG_ENDIAN defined
const char *block_id_as_bytes = reinterpret_cast<cosnt char *>(&(block_id));
for (size_t i = 1; i <= sizeof(block_id); ++i) {
concatenated_entry_hashes.append((block_id_as_bytes + (sizeof(block_id) - i)), 1);
}
#endif // if BOOST_LITTLE_ENDIAN defined/else
for (const auto &kvp_hashes : entry_hashes) {
concatenated_entry_hashes.append(kvp_hashes.first);
concatenated_entry_hashes.append(kvp_hashes.second);
}
return computeSHA256Hash(concatenated_entry_hashes);
}
string KvbAppFilter::hashEventGroupUpdate(const KvbFilteredEventGroupUpdate &update) {
// Note we store the hashes of the events in an std::set as an
// intermediate step in the computation of the update hash so the set can be
// used to deterministically order the events' hashes before they are
// concatenated for the computation of the update hash. The deterministic
// ordering is necessary since two updates with the same set of events
// in different orders are considered equivalent so their hashes need to
// match.
std::set<string> entry_hashes;
auto &[event_group_id, event_group] = update;
for (const auto &event : event_group.events) {
string event_hash = computeSHA256Hash(event.data);
ConcordAssertLT(entry_hashes.count(event_hash), 1);
entry_hashes.emplace(event_hash);
}
string concatenated_entry_hashes;
concatenated_entry_hashes.reserve(sizeof(EventGroupId) +
event_group.events.size() * kExpectedSHA256HashLengthInBytes);
#ifdef BOOST_LITTLE_ENDIAN
concatenated_entry_hashes.append(reinterpret_cast<const char *>(&(event_group_id)), sizeof(event_group_id));
#else // BOOST_LITTLE_ENDIAN not defined in this case
#ifndef BOOST_BIG_ENDIAN
static_assert(false,
"Cannot determine endianness (needed for Thin Replica "
"mechanism hash function).");
#endif // BOOST_BIG_ENDIAN defined
const char *event_group_id_as_bytes = reinterpret_cast<const char *>(&(event_group_id));
for (size_t i = 1; i <= sizeof(event_group_id); ++i) {
concatenated_entry_hashes.append((event_group_id_as_bytes + (sizeof(event_group_id) - i)), 1);
}
#endif // if BOOST_LITTLE_ENDIAN defined/else
for (const auto &event_hash : entry_hashes) {
concatenated_entry_hashes.append(event_hash);
}
return computeSHA256Hash(concatenated_entry_hashes);
}
void KvbAppFilter::readBlockRange(BlockId block_id_start,
BlockId block_id_end,
spsc_queue<KvbFilteredUpdate> &queue_out,
const std::atomic_bool &stop_execution) {
if (block_id_start > block_id_end || block_id_end > rostorage_->getLastBlockId()) {
throw InvalidBlockRange(block_id_start, block_id_end);
}
BlockId block_id(block_id_start);
LOG_DEBUG(logger_, "readBlockRange block " << block_id << " to " << block_id_end);
for (; block_id <= block_id_end; ++block_id) {
std::string cid;
auto events = getBlockEvents(block_id, cid);
if (!events) {
std::stringstream msg;
msg << "Couldn't retrieve block events for block id " << block_id;
throw KvbReadError(msg.str());
}
KvbFilteredUpdate update{block_id, cid, filterKeyValuePairs(*events)};
while (!stop_execution) {
if (queue_out.push(update)) {
break;
}
}
if (stop_execution) {
LOG_WARN(logger_, "readBlockRange was stopped");
break;
}
}
}
uint64_t KvbAppFilter::getValueFromLatestTable(const std::string &key) const {
const auto opt = rostorage_->getLatest(kvbc::categorization::kExecutionEventGroupLatestCategory, key);
if (not opt) {
LOG_DEBUG(logger_, "External event group ID for key \"" << key << "\" doesn't exist yet");
// In case there are no public or private event groups for a client, return 0.
// Note: `0` is an invalid event group id
return 0;
}
auto val = std::get_if<concord::kvbc::categorization::VersionedValue>(&(opt.value()));
if (not val) {
std::stringstream msg;
msg << "Failed to convert stored external event group id for key \"" << key << "\" to versioned value";
throw std::runtime_error(msg.str());
}
return concordUtils::fromBigEndianBuffer<uint64_t>(val->data.data());
}
TagTableValue KvbAppFilter::getValueFromTagTable(const std::string &tag, uint64_t pvt_eg_id) const {
auto key = tag + kTagTableKeySeparator + concordUtils::toBigEndianStringBuffer(pvt_eg_id);
const auto opt = rostorage_->getLatest(concord::kvbc::categorization::kExecutionEventGroupTagCategory, key);
if (not opt) {
std::stringstream msg;
msg << "Failed to get event group id from tag table for key " << key;
LOG_WARN(logger_, msg.str());
throw std::runtime_error(msg.str());
}
const auto val = std::get_if<concord::kvbc::categorization::ImmutableValue>(&(opt.value()));
if (not val) {
std::stringstream msg;
msg << "Failed to convert stored event group id from tag table for key \"" << key << "\" to immutable value";
LOG_ERROR(logger_, msg.str());
throw std::runtime_error(msg.str());
}
std::string_view result{val->data};
auto offset = sizeof(uint64_t);
uint64_t global_eg_id = concordUtils::fromBigEndianBuffer<uint64_t>(result.substr(0, offset).data());
uint64_t external_tag_eg_id =
concordUtils::fromBigEndianBuffer<uint64_t>(result.substr(offset + kTagTableKeySeparator.size()).data());
// Every tag-table entry must have a valid global event group id
// If this table was pruned then only valid entries remain which still need to have a proper event group id
ConcordAssertNE(global_eg_id, 0);
return {global_eg_id, external_tag_eg_id};
}
// We don't store external event group ids and need to compute them at runtime.
// This function returns the oldest external event group id that the user can request.
// Due to pruning, it depends on the oldest public event group and the oldest private event group available.
uint64_t KvbAppFilter::oldestExternalEventGroupId() const {
uint64_t public_oldest = getValueFromLatestTable(kPublicEgIdKeyOldest);
uint64_t private_oldest = getValueFromLatestTable(client_id_ + "_oldest");
if (!public_oldest && !private_oldest) return 0;
// If public or private was fully pruned then we have to account for those event groups as well
if (!public_oldest) return private_oldest + getValueFromLatestTable(kPublicEgIdKeyNewest);
if (!private_oldest) return public_oldest + getValueFromLatestTable(client_id_ + "_newest");
// Adding public and private results in an external event group id including two query-able event groups
// (the oldest private and the oldest public).
// However, we are only interested in the oldest external and not the second oldest. Hence, we have to subtract 1.
return public_oldest + private_oldest - 1;
}
// This function returns the newest external event group id that the user can request.
// Note, the newest external event group ids will not be updated by pruning.
uint64_t KvbAppFilter::newestExternalEventGroupId() const {
uint64_t public_newest = getValueFromLatestTable(kPublicEgIdKeyNewest);
uint64_t private_newest = getValueFromLatestTable(client_id_ + "_newest");
return public_newest + private_newest;
}
FindGlobalEgIdResult KvbAppFilter::findGlobalEventGroupId(uint64_t external_event_group_id) const {
auto external_oldest = oldestExternalEventGroupId();
auto external_newest = newestExternalEventGroupId();
ConcordAssertNE(external_oldest, 0); // Everything pruned or was never created
ConcordAssertLE(external_oldest, external_event_group_id);
ConcordAssertGE(external_newest, external_event_group_id);
uint64_t public_start = getValueFromLatestTable(kPublicEgIdKeyOldest);
uint64_t public_end = getValueFromLatestTable(kPublicEgIdKeyNewest);
uint64_t private_start = getValueFromLatestTable(client_id_ + "_oldest");
uint64_t private_end = getValueFromLatestTable(client_id_ + "_newest");
if (not private_start and not private_end) {
// requested external event group id == public event group id
uint64_t global_id;
std::tie(global_id, std::ignore) = getValueFromTagTable(kPublicEgId, external_event_group_id);
return {global_id, true, private_end, external_event_group_id};
} else if (not public_start and not public_end) {
// requested external event group id == private event group id
uint64_t global_id;
std::tie(global_id, std::ignore) = getValueFromTagTable(client_id_, external_event_group_id);
return {global_id, false, external_event_group_id, public_end};
}
// Binary search in private event groups
uint64_t window_size;
auto window_start = private_start;
auto window_end = private_end;
// Cursors inside the search window; All point to the same entry
// client_id_ <separator> current_pvt_eg_id => current_global_eg_id <separator> current_ext_eg_id
auto [current_pvt_eg_id, current_global_eg_id, current_ext_eg_id] = std::make_tuple(0ull, 0ull, 0ull);
while (window_start && window_start <= window_end) {
window_size = window_end - window_start + 1;
current_pvt_eg_id = window_start + (window_size / 2);
std::tie(current_global_eg_id, current_ext_eg_id) = getValueFromTagTable(client_id_, current_pvt_eg_id);
// Either we found it or read the last possible entry in the window
if (current_ext_eg_id == external_event_group_id || window_size == 1) break;
// Adjust the window excluding the entry we just checked
if (external_event_group_id > current_ext_eg_id) {
window_start = current_pvt_eg_id + 1;
} else if (external_event_group_id < current_ext_eg_id) {
window_end = current_pvt_eg_id - 1;
}
}
if (current_ext_eg_id == external_event_group_id) {
return {current_global_eg_id, false, current_pvt_eg_id, external_event_group_id - current_pvt_eg_id};
}
// At this point, we exhausted all private entries => it has to be a public event group
uint64_t global_eg_id;
// If all private event groups were pruned then we need to adjust current_* to point to the last private event group
if (private_start == 0) {
ConcordAssertNE(private_end, 0);
current_pvt_eg_id = private_end;
current_ext_eg_id = private_end + public_start - 1;
}
if (external_event_group_id < current_ext_eg_id) {
auto num_pub_egs = current_ext_eg_id - current_pvt_eg_id;
auto pub_eg_id = num_pub_egs - (current_ext_eg_id - external_event_group_id - 1);
std::tie(global_eg_id, std::ignore) = getValueFromTagTable(kPublicEgId, pub_eg_id);
return {global_eg_id, true, current_pvt_eg_id - 1, pub_eg_id};
}
ConcordAssertGT(external_event_group_id, current_ext_eg_id);
auto num_pub_egs = current_ext_eg_id - current_pvt_eg_id;
auto pub_eg_id = num_pub_egs + (external_event_group_id - current_ext_eg_id);
std::tie(global_eg_id, std::ignore) = getValueFromTagTable(kPublicEgId, pub_eg_id);
return {global_eg_id, true, current_pvt_eg_id, pub_eg_id};
}
void KvbAppFilter::readEventGroups(EventGroupId external_eg_id_start,
const std::function<bool(KvbFilteredEventGroupUpdate &&)> &process_update) {
ConcordAssertGT(external_eg_id_start, 0);
uint64_t newest_public_eg_id = getNewestPublicEventGroupId();
uint64_t newest_private_eg_id = getValueFromLatestTable(client_id_ + "_newest");
uint64_t oldest_external_eg_id = oldestExternalEventGroupId();
uint64_t newest_external_eg_id = newestExternalEventGroupId();
if (not oldest_external_eg_id) {
std::stringstream msg;
msg << "Event groups do not exist for client: " << client_id_ << " yet.";
LOG_ERROR(logger_, msg.str());
throw std::runtime_error(msg.str());
}
if (external_eg_id_start < oldest_external_eg_id || external_eg_id_start > newest_external_eg_id) {
throw InvalidEventGroupRange(external_eg_id_start, oldest_external_eg_id, newest_external_eg_id);
}
auto [global_eg_id, is_previous_public, private_eg_id, public_eg_id] = findGlobalEventGroupId(external_eg_id_start);
uint64_t ext_eg_id = external_eg_id_start;
uint64_t next_pvt_eg_id = private_eg_id + 1;
uint64_t next_pub_eg_id = public_eg_id + 1;
// The next public or private event group might not exist or got pruned
// In this case, set to max so that the comparison will be lost later
uint64_t pvt_external_id;
uint64_t pvt_global_id;
try {
std::tie(pvt_global_id, pvt_external_id) = getValueFromTagTable(client_id_, next_pvt_eg_id);
} catch (const std::exception &e) {
pvt_global_id = std::numeric_limits<uint64_t>::max();
}
uint64_t pub_global_id;
try {
std::tie(pub_global_id, std::ignore) = getValueFromTagTable(kPublicEgId, next_pub_eg_id);
} catch (const std::exception &e) {
pub_global_id = std::numeric_limits<uint64_t>::max();
}
while (ext_eg_id <= newest_external_eg_id) {
// Get events and filter
auto event_group = getEventGroup(global_eg_id);
if (event_group.events.empty()) {
std::stringstream msg;
msg << "EventGroup empty/doesn't exist for global event group " << global_eg_id;
throw KvbReadError(msg.str());
}
KvbFilteredEventGroupUpdate update{ext_eg_id, filterEventsInEventGroup(global_eg_id, event_group)};
// Process update and stop producing more updates if anything goes wrong
if (not process_update(std::move(update))) break;
if (ext_eg_id == newest_external_eg_id) break;
// Update next public or private ids; Only one needs to be udpated
if (is_previous_public) {
if (next_pub_eg_id > newest_public_eg_id) {
pub_global_id = std::numeric_limits<uint64_t>::max();
} else {
std::tie(pub_global_id, std::ignore) = getValueFromTagTable(kPublicEgId, next_pub_eg_id);
}
} else {
if (next_pvt_eg_id > newest_private_eg_id) {
pvt_global_id = std::numeric_limits<uint64_t>::max();
} else {
std::tie(pvt_global_id, pvt_external_id) = getValueFromTagTable(client_id_, next_pvt_eg_id);
}
}
// No need to continue if both next counters point into the future
if (pvt_global_id == std::numeric_limits<uint64_t>::max() && pub_global_id == std::numeric_limits<uint64_t>::max())
break;
// The lesser global event group id is the next update for the client
if (pvt_global_id < pub_global_id) {
global_eg_id = pvt_global_id;
is_previous_public = false;
ConcordAssertEQ(ext_eg_id + 1, pvt_external_id);
next_pvt_eg_id++;
} else {
global_eg_id = pub_global_id;
is_previous_public = true;
next_pub_eg_id++;
}
ext_eg_id += 1;
}
setLastEgIdsRead(ext_eg_id, global_eg_id);
}
void KvbAppFilter::readEventGroupRange(EventGroupId external_eg_id_start,
spsc_queue<KvbFilteredEventGroupUpdate> &queue_out,
const std::atomic_bool &stop_execution) {
auto process = [&](KvbFilteredEventGroupUpdate &&update) {
while (!stop_execution) {
if (queue_out.push(update)) break;
}
if (stop_execution) return false;
return true;
};
readEventGroups(external_eg_id_start, process);
}
string KvbAppFilter::readBlockHash(BlockId block_id) {
if (block_id > rostorage_->getLastBlockId()) {
throw InvalidBlockRange(block_id, block_id);
}
std::string cid;
auto events = getBlockEvents(block_id, cid);
if (!events) {
std::stringstream msg;
msg << "Couldn't retrieve block events for block id " << block_id;
throw KvbReadError(msg.str());
}
KvbFilteredUpdate filtered_update{block_id, cid, filterKeyValuePairs(*events)};
return hashUpdate(filtered_update);
}
string KvbAppFilter::readEventGroupHash(EventGroupId external_eg_id) {
uint64_t oldest_external_eg_id = oldestExternalEventGroupId();
uint64_t newest_external_eg_id = newestExternalEventGroupId();
if (not oldest_external_eg_id) {
std::stringstream msg;
msg << "Event groups do not exist for client: " << client_id_ << " yet.";
LOG_ERROR(logger_, msg.str());
throw std::runtime_error(msg.str());
}
if (external_eg_id == 0) {
throw InvalidEventGroupId(external_eg_id);
}
if (external_eg_id < oldest_external_eg_id || external_eg_id > newest_external_eg_id) {
throw InvalidEventGroupRange(external_eg_id, oldest_external_eg_id, newest_external_eg_id);
}
auto result = findGlobalEventGroupId(external_eg_id);
LOG_DEBUG(logger_, "external_eg_id " << external_eg_id << " global_id " << result.global_id);
auto event_group = getEventGroup(result.global_id);
if (event_group.events.empty()) {
std::stringstream msg;
msg << "Couldn't retrieve block event groups for event_group_id " << result.global_id;
throw KvbReadError(msg.str());
}
KvbFilteredEventGroupUpdate filtered_update{external_eg_id, filterEventsInEventGroup(result.global_id, event_group)};
setLastEgIdsRead(external_eg_id, result.global_id);
return hashEventGroupUpdate(filtered_update);
}
string KvbAppFilter::readBlockRangeHash(BlockId block_id_start, BlockId block_id_end) {
if (block_id_start > block_id_end || block_id_end > rostorage_->getLastBlockId()) {
throw InvalidBlockRange(block_id_start, block_id_end);
}
BlockId block_id(block_id_start);
LOG_DEBUG(logger_, "readBlockRangeHash block " << block_id << " to " << block_id_end);
string concatenated_update_hashes;
concatenated_update_hashes.reserve((1 + block_id_end - block_id) * kExpectedSHA256HashLengthInBytes);
for (; block_id <= block_id_end; ++block_id) {
std::string cid;
auto events = getBlockEvents(block_id, cid);
if (!events) {
std::stringstream msg;
msg << "Couldn't retrieve block events for block id " << block_id;
throw KvbReadError(msg.str());
}
KvbFilteredUpdate filtered_update{block_id, cid, filterKeyValuePairs(*events)};
concatenated_update_hashes.append(hashUpdate(filtered_update));
}
return computeSHA256Hash(concatenated_update_hashes);
}
string KvbAppFilter::readEventGroupRangeHash(EventGroupId external_eg_id_start) {
auto external_eg_id_end = newestExternalEventGroupId();
string concatenated_hashes;
concatenated_hashes.reserve((1 + external_eg_id_end - external_eg_id_start) * kExpectedSHA256HashLengthInBytes);
auto process = [&](KvbFilteredEventGroupUpdate &&update) {
concatenated_hashes.append(hashEventGroupUpdate(update));
return true;
};
readEventGroups(external_eg_id_start, process);
return computeSHA256Hash(concatenated_hashes);
}
std::optional<kvbc::categorization::ImmutableInput> KvbAppFilter::getBlockEvents(kvbc::BlockId block_id,
std::string &cid) {
if (auto opt = getOldestEventGroupBlockId()) {
if (block_id >= opt.value()) {
throw NoLegacyEvents();
}
}
const auto updates = rostorage_->getBlockUpdates(block_id);
if (!updates) {
LOG_ERROR(logger_, "Couldn't get block updates");
return {};
}
// get cid
const auto &internal_map =
std::get<kvbc::categorization::VersionedInput>(
updates.value().categoryUpdates(concord::kvbc::categorization::kConcordInternalCategoryId)->get())
.kv;
auto it = internal_map.find(cid_key_);
if (it != internal_map.end()) {
cid = it->second.data;
}
// Not all blocks have events.
auto immutable = updates.value().categoryUpdates(concord::kvbc::categorization::kExecutionEventsCategory);
if (!immutable) {
return kvbc::categorization::ImmutableInput{};
}
return std::get<kvbc::categorization::ImmutableInput>(immutable->get());
}
kvbc::categorization::EventGroup KvbAppFilter::getEventGroup(kvbc::EventGroupId global_event_group_id) const {
LOG_DEBUG(logger_,
" Get EventGroup, global_event_group_id: " << global_event_group_id << " for client: " << client_id_);
// get event group
const auto opt = rostorage_->getLatest(concord::kvbc::categorization::kExecutionEventGroupDataCategory,
concordUtils::toBigEndianStringBuffer(global_event_group_id));
if (not opt) {
stringstream msg;
msg << "Failed to get global event group " << global_event_group_id;
LOG_ERROR(logger_, msg.str());
throw std::runtime_error(msg.str());
}
const auto imm_val = std::get_if<concord::kvbc::categorization::ImmutableValue>(&(opt.value()));
if (not imm_val) {
stringstream msg;
msg << "Failed to convert stored global event group " << global_event_group_id;
LOG_ERROR(logger_, msg.str());
throw std::runtime_error(msg.str());
}
// TODO: Can we avoid copying?
const std::vector<uint8_t> input_vec(imm_val->data.begin(), imm_val->data.end());
concord::kvbc::categorization::EventGroup event_group_out;
concord::kvbc::categorization::deserialize(input_vec, event_group_out);
if (event_group_out.events.empty()) {
LOG_ERROR(logger_, "Couldn't get event group updates");
return kvbc::categorization::EventGroup{};
}
return event_group_out;
}
void KvbAppFilter::setLastEgIdsRead(uint64_t last_ext_eg_id_read, uint64_t last_global_eg_id_read) {
last_ext_and_global_eg_id_read_ = std::make_pair(last_ext_eg_id_read, last_global_eg_id_read);
}
std::pair<uint64_t, uint64_t> KvbAppFilter::getLastEgIdsRead() { return last_ext_and_global_eg_id_read_; }
} // namespace kvbc
} // namespace concord
| 41.171223 | 119 | 0.726428 | evdzhurov |
2f377ec0c59dcc50e6f5c659ac7ef33dcd8d4643 | 2,835 | cpp | C++ | JTS/CF-B/SPOJ-TOE1/test.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | 2 | 2019-03-18T16:06:10.000Z | 2019-04-07T23:17:06.000Z | JTS/CF-B/SPOJ-TOE1/test.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | null | null | null | JTS/CF-B/SPOJ-TOE1/test.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | 1 | 2019-03-18T16:06:52.000Z | 2019-03-18T16:06:52.000Z | // Date : 2019-03-27
// Author : Rahul Sharma
// Problem : https://www.spoj.com/problems/TOE1/
#include <iostream>
#include <string>
#include <cmath>
#include <unordered_set>
#include <vector>
using namespace std;
unordered_set<string> bs;
void gen(string& b, int m = 9) {
if (!m) {
bs.insert(b);
return;
}
char t = (m & 1) ? 'X' : 'O';
for (int i = 0; i < 9; i++) {
if (b[i] == '.') {
b[i] = t;
bs.insert(b);
int r = 3 * (i / 3), c = i % 3;
bool win = (b[r] == t && b[r + 1] == t && b[r + 2] == t) ||
(b[c] == t && b[c + 3] == t && b[c + 6] == t) ||
(b[0] == t && b[4] == t && b[8] == t) ||
(b[2] == t && b[4] == t && b[6] == t);
if (!win)
gen(b, m - 1);
b[i] = '.';
}
}
}
bool is_ttt(vector<string> m) {
int nx = 0, no = 0;
for (auto& r : m) {
for (auto& c : r)
if (c == 'X')
nx++;
else if (c == 'O')
no++;
}
if (no < nx - 1 || no > nx)
return false;
bool wx = false, wo = false;
for (int i = 0; i < 3; i++) {
if (m[i][0] == m[i][1] && m[i][1] == m[i][2]) {
if (m[i][0] == 'X')
wx = true;
else if (m[i][0] == 'O')
wo = true;
}
if (m[0][i] == m[1][i] && m[1][i] == m[2][i]) {
if (m[0][i] == 'X')
wx = true;
else if (m[0][i] == 'O')
wo = true;
}
}
if (m[0][0] == m[1][1] && m[1][1] == m[2][2]) {
if (m[1][1] == 'X')
wx = true;
else if (m[1][1] == 'O')
wo = true;
}
if (m[2][0] == m[1][1] && m[1][1] == m[0][2]) {
if (m[1][1] == 'X')
wx = true;
else if (m[1][1] == 'O')
wo = true;
}
if ((wx && wo) || (wx && nx != no + 1) || (wo && nx != no))
return false;
return true;
}
void test() {
const char* s = ".XO";
int comb = pow(3, 9);
for (int i = 0; i < comb; i++) {
string b = ".........";
for (int j = i, k = 0; k < 9; k++, j /= 3)
b[k] = s[j % 3];
vector<string> m;
m.push_back(b.substr(0, 3));
m.push_back(b.substr(3, 3));
m.push_back(b.substr(6, 3));
bool res1 = bs.find(b) != bs.end();
bool res2 = is_ttt(m);
if (res1 != res2) {
cout << b << ' ' << res1 << " != " << res2 << '\n';
for (auto& r : m)
cout << r << '\n';
break;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
string s(9, '.');
bs.insert(s);
gen(s);
cout << bs.size() << '\n';
test();
}
| 25.088496 | 71 | 0.332275 | rahulsrma26 |
2f3a585f8c11acc29e89a9df2c33acfef6177282 | 3,328 | cpp | C++ | Kiwano/base/Object.cpp | nomango96/Kiwano | 51b4078624fcd6370aa9c30eb5048a538cd1877c | [
"MIT"
] | 1 | 2019-07-17T03:25:52.000Z | 2019-07-17T03:25:52.000Z | Kiwano/base/Object.cpp | nomango96/Kiwano | 51b4078624fcd6370aa9c30eb5048a538cd1877c | [
"MIT"
] | null | null | null | Kiwano/base/Object.cpp | nomango96/Kiwano | 51b4078624fcd6370aa9c30eb5048a538cd1877c | [
"MIT"
] | null | null | null | // Copyright (c) 2016-2018 Kiwano - Nomango
//
// 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 "Object.h"
#include "logs.h"
#include <typeinfo>
namespace kiwano
{
namespace
{
bool tracing_leaks = false;
Array<Object*> tracing_objects;
}
unsigned int Object::last_object_id = 0;
Object::Object()
: tracing_leak_(false)
, user_data_(nullptr)
, name_(nullptr)
, id_(++last_object_id)
{
#ifdef KGE_DEBUG
Object::__AddObjectToTracingList(this);
#endif
}
Object::~Object()
{
if (name_)
delete name_;
#ifdef KGE_DEBUG
Object::__RemoveObjectFromTracingList(this);
#endif
}
void * Object::GetUserData() const
{
return user_data_;
}
void Object::SetUserData(void * data)
{
user_data_ = data;
}
void Object::SetName(String const & name)
{
if (IsName(name))
return;
if (name.empty())
{
if (name_)
name_->clear();
return;
}
if (!name_)
{
name_ = new (std::nothrow) String(name);
return;
}
*name_ = name;
}
String Object::DumpObject()
{
String name = typeid(*this).name();
return String::format(L"{ class=\"%s\" id=%d refcount=%d name=\"%s\" }",
name.c_str(), GetObjectID(), GetRefCount(), GetName().c_str());
}
void Object::StartTracingLeaks()
{
tracing_leaks = true;
}
void Object::StopTracingLeaks()
{
tracing_leaks = false;
}
void Object::DumpTracingObjects()
{
KGE_LOG(L"-------------------------- All Objects --------------------------");
for (const auto object : tracing_objects)
{
KGE_LOG(L"%s", object->DumpObject().c_str());
}
KGE_LOG(L"------------------------- Total size: %d -------------------------", tracing_objects.size());
}
Array<Object*>& kiwano::Object::__GetTracingObjects()
{
return tracing_objects;
}
void Object::__AddObjectToTracingList(Object * obj)
{
#ifdef KGE_DEBUG
if (tracing_leaks && !obj->tracing_leak_)
{
obj->tracing_leak_ = true;
tracing_objects.push_back(obj);
}
#endif
}
void Object::__RemoveObjectFromTracingList(Object * obj)
{
#ifdef KGE_DEBUG
if (tracing_leaks && obj->tracing_leak_)
{
obj->tracing_leak_ = false;
auto iter = std::find(tracing_objects.begin(), tracing_objects.end(), obj);
if (iter != tracing_objects.end())
{
tracing_objects.erase(iter);
}
}
#endif
}
}
| 21.470968 | 105 | 0.669772 | nomango96 |
2f40517f93ad032b8dbaf5a6baeb4c2f1f3aa05e | 3,310 | cc | C++ | ui/events/ozone/gamepad/generic_gamepad_mapping_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ui/events/ozone/gamepad/generic_gamepad_mapping_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ui/events/ozone/gamepad/generic_gamepad_mapping_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 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 "ui/events/ozone/gamepad/generic_gamepad_mapping.h"
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
#include <memory>
#include <queue>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/event.h"
#include "ui/events/ozone/device/device_manager.h"
#include "ui/events/ozone/evdev/event_converter_test_util.h"
#include "ui/events/ozone/evdev/event_device_info.h"
#include "ui/events/ozone/evdev/event_device_test_util.h"
#include "ui/events/ozone/evdev/event_device_util.h"
#include "ui/events/ozone/evdev/event_factory_evdev.h"
#include "ui/events/ozone/gamepad/gamepad_event.h"
#include "ui/events/ozone/gamepad/gamepad_observer.h"
#include "ui/events/ozone/gamepad/gamepad_provider_ozone.h"
#include "ui/events/ozone/gamepad/static_gamepad_mapping.h"
#include "ui/events/ozone/gamepad/webgamepad_constants.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/events/platform/platform_event_dispatcher.h"
#include "ui/events/platform/platform_event_source.h"
namespace ui {
class GenericGamepadMappingTest : public testing::Test {
public:
GenericGamepadMappingTest() {}
void CompareGamepadMapper(const GamepadMapper* l_mapper,
const GamepadMapper* r_mapper) {
bool l_result, r_result;
GamepadEventType l_mapped_type, r_mapped_type;
uint16_t l_mapped_code, r_mapped_code;
for (uint16_t code = BTN_MISC; code < KEY_MAX; code++) {
l_result = l_mapper->Map(EV_KEY, code, &l_mapped_type, &l_mapped_code);
r_result = r_mapper->Map(EV_KEY, code, &r_mapped_type, &r_mapped_code);
EXPECT_EQ(l_result, r_result) << " Current Code: " << code;
if (l_result) {
EXPECT_EQ(l_mapped_type, r_mapped_type);
EXPECT_EQ(r_mapped_code, r_mapped_code);
}
}
for (uint16_t code = ABS_X; code < ABS_MAX; code++) {
l_result = l_mapper->Map(EV_ABS, code, &l_mapped_type, &l_mapped_code);
r_result = r_mapper->Map(EV_ABS, code, &r_mapped_type, &r_mapped_code);
EXPECT_EQ(l_result, r_result);
if (l_result) {
EXPECT_EQ(l_mapped_type, r_mapped_type);
EXPECT_EQ(r_mapped_code, r_mapped_code);
}
}
}
void TestCompatableWithCapabilities(const DeviceCapabilities& cap) {
ui::EventDeviceInfo devinfo;
CapabilitiesToDeviceInfo(cap, &devinfo);
std::unique_ptr<GamepadMapper> static_mapper(
GetStaticGamepadMapper(devinfo.vendor_id(), devinfo.product_id()));
std::unique_ptr<GamepadMapper> generic_mapper =
BuildGenericGamepadMapper(devinfo);
CompareGamepadMapper(static_mapper.get(), generic_mapper.get());
}
};
TEST_F(GenericGamepadMappingTest, XInputGamepad) {
TestCompatableWithCapabilities(kXboxGamepad);
}
TEST_F(GenericGamepadMappingTest, HJCGamepad) {
TestCompatableWithCapabilities(kHJCGamepad);
}
} // namespace ui
| 35.978261 | 77 | 0.743505 | zipated |
2f458e81dce4bc144b554479b1386b6fc5291401 | 2,124 | cpp | C++ | Game/Game.cpp | dwarfcrank/FantasyQuest | e5a35a8631dc056db8ffbc114354244b1530eaa6 | [
"MIT"
] | 1 | 2020-05-09T20:03:04.000Z | 2020-05-09T20:03:04.000Z | Game/Game.cpp | dwarfcrank/FantasyQuest | e5a35a8631dc056db8ffbc114354244b1530eaa6 | [
"MIT"
] | null | null | null | Game/Game.cpp | dwarfcrank/FantasyQuest | e5a35a8631dc056db8ffbc114354244b1530eaa6 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Game.h"
#include "Common.h"
#include "InputMap.h"
#include "Renderer.h"
#include "Transform.h"
#include "Mesh.h"
#include "File.h"
#include "Scene.h"
#include "Camera.h"
#include "Math.h"
#include <SDL2/SDL.h>
#include <fmt/format.h>
#include <type_traits>
#include <d3d11.h>
#include <DirectXMath.h>
#include <d3dcompiler.h>
#include <wrl.h>
#include <chrono>
using namespace math;
GameBase::GameBase(InputMap& inputs) :
m_inputs(inputs)
{
}
Game::Game(Scene& scene, InputMap& inputs) :
GameBase(inputs), scene(scene)
{
auto doBind = [this](SDL_Keycode k, float& target, float value) {
m_inputs.key(k)
.down([&target, value] { target = value; })
.up([&target] { target = 0.0f; });
};
doBind(SDLK_q, angle, -turnSpeed);
doBind(SDLK_e, angle, turnSpeed);
doBind(SDLK_d, velocity.x, moveSpeed);
doBind(SDLK_a, velocity.x, -moveSpeed);
doBind(SDLK_w, velocity.z, moveSpeed);
doBind(SDLK_s, velocity.z, -moveSpeed);
doBind(SDLK_LEFT, lightVelocity.x, -moveSpeed);
doBind(SDLK_RIGHT, lightVelocity.x, moveSpeed);
doBind(SDLK_UP, lightVelocity.z, moveSpeed);
doBind(SDLK_DOWN, lightVelocity.z, -moveSpeed);
doBind(SDLK_r, lightVelocity.y, moveSpeed);
doBind(SDLK_f, lightVelocity.y, -moveSpeed);
m_inputs.onMouseMove([this](const SDL_MouseMotionEvent& event) {
if ((event.state & SDL_BUTTON_RMASK) || (SDL_GetModState() & KMOD_LCTRL)) {
auto x = static_cast<float>(event.xrel) / 450.0f;
auto y = static_cast<float>(event.yrel) / 450.0f;
m_camera.rotate(y, x);
}
});
}
bool Game::update(float dt)
{
bool running = true;
m_camera.move(Vector<View>(velocity.x, velocity.y, velocity.z) * dt);
m_camera.move(Vector<World>(lightVelocity.x, lightVelocity.y, lightVelocity.z) * dt);
m_camera.rotate(0.0f, angle * dt);
return running;
}
void Game::render(IRenderer* r)
{
}
const Camera& Game::getCamera() const
{
return m_camera;
}
| 25.285714 | 90 | 0.629473 | dwarfcrank |
2f466dd0f7ac366d24718c6c25d6899f434d4072 | 8,206 | cpp | C++ | Tissue/ias_TissueIO.cpp | torressancheza/ias | a63cbf4798ce3c91d4282ac25808970c1f272a5a | [
"MIT"
] | 2 | 2021-04-08T06:24:31.000Z | 2022-03-31T10:07:15.000Z | Tissue/ias_TissueIO.cpp | torressancheza/ias | a63cbf4798ce3c91d4282ac25808970c1f272a5a | [
"MIT"
] | null | null | null | Tissue/ias_TissueIO.cpp | torressancheza/ias | a63cbf4798ce3c91d4282ac25808970c1f272a5a | [
"MIT"
] | null | null | null | // **************************************************************************************************
// ias - Interacting Active Surfaces
// Project homepage: https://github.com/torressancheza/ias
// Copyright (c) 2020 Alejandro Torres-Sanchez, Max Kerr Winter and Guillaume Salbreux
// **************************************************************************************************
// ias is licenced under the MIT licence:
// https://github.com/torressancheza/ias/blob/master/licence.txt
// **************************************************************************************************
#include <fstream>
#include <thread>
#include "ias_Tissue.h"
namespace ias
{
void Tissue::saveVTK(std::string prefix,std::string suffix)
{
using namespace std;
#pragma omp parallel for
for(int i = 0; i < int(_cells.size()); i++)
_cells[i]->saveVTK(prefix+std::to_string(int(_cells[i]->getCellField("cellId")+0.5))+suffix+".vtu");
vector<int> cellLabels;
for(auto c: _cells)
cellLabels.push_back(int(c->getCellField("cellId")+0.5));
vector<int> glo_cellLbls(_nCells);
MPI_Gatherv(cellLabels.data(), cellLabels.size(), MPI_INT, glo_cellLbls.data(), _nCellPart.data(), _offsetPart.data(), MPI_INT, 0, _comm);
if (_myPart == 0)
{
string vtmname = prefix+suffix + ".vtm";
ofstream file;
file.open(vtmname);
file << "<VTKFile type=\"vtkMultiBlockDataSet\" version=\"1.0\"" << endl;
file << "byte_order=\"LittleEndian\" header_type=\"UInt64\">" << endl;
file << "<vtkMultiBlockDataSet>"<< endl;
for(int i = 0; i < _nCells; i++)
{
file << "<DataSet index=\"" << glo_cellLbls[i] << "\" ";
file << "name=\"" << glo_cellLbls[i] << "\" ";
file << "file=\"" << prefix+std::to_string(glo_cellLbls[i])+suffix+".vtu";
file << "\"></DataSet>" << endl;
}
file << "</vtkMultiBlockDataSet>" << endl;
file <<"<FieldData>" << endl;
for(int i = 0; i < _tissFields.size(); i++)
{
file <<"<DataArray type=\"Float64\" Name=\"" << _tissFieldNames[i] <<"\" NumberOfTuples=\"1\" format=\"ascii\" RangeMin=\"" << _tissFields(i) << "\" RangeMax=\"" << _tissFields(i) << "\">" << endl;
file << _tissFields(i) << endl;
file << "</DataArray>" << endl;
}
file << "</FieldData>" << endl;
file << "</VTKFile>" << endl;
file.close();
}
MPI_Barrier(_comm);
}
void Tissue::loadVTK(std::string location,std::string filename, BasisFunctionType bfType)
{
using namespace std;
using Teuchos::RCP;
using Teuchos::rcp;
int nCells = 0;
vector<string> fileNames;
vector<double> fieldValues;
if (_myPart == 0)
{
string name = location+filename + ".vtm";
ifstream file;
string line;
file.open(name);
if (! file.is_open())
throw runtime_error("Could not open file "+name+".");
string errormsg = "Tissue::loadVTK: the file " + name + " is not in a format accepted by ias.";
//Read first line
getline(file,line);
if(line != "<VTKFile type=\"vtkMultiBlockDataSet\" version=\"1.0\"")
throw runtime_error(errormsg);
getline(file,line);
if(line != "byte_order=\"LittleEndian\" header_type=\"UInt64\">")
throw runtime_error(errormsg);
getline(file,line);
if(line != "<vtkMultiBlockDataSet>")
throw runtime_error(errormsg);
while(getline (file,line))
{
if(line.find("<DataSet", 0) == 0)
{
size_t first = line.find("file=\"");
size_t last = line.find("\"><");
string file = line.substr(first+6,last-(first+6));
fileNames.push_back(file);
nCells++;
}
else
{
break;
}
}
if(line != "</vtkMultiBlockDataSet>")
throw runtime_error(errormsg);
getline (file,line);
if(line != "<FieldData>")
throw runtime_error(errormsg);
while(getline (file,line))
{
if(line.find("<DataArray", 0) == 0)
{
size_t first = line.find("Name=\"");
size_t last = line.find("\" NumberOfTuples");
string name = line.substr(first+6,last-(first+6));
_tissFieldNames.push_back(name);
getline (file,line);
double value{};
std::istringstream s( line );
s >> value;
fieldValues.push_back(value);
getline (file,line);
if(line != "</DataArray>")
throw runtime_error(errormsg);
}
else
{
break;
}
}
file.close();
}
MPI_Bcast(&nCells, 1, MPI_INT, 0, _comm);
int nTissFields{};
nTissFields = _tissFieldNames.size();
MPI_Bcast(&nTissFields, 1, MPI_INT, 0, _comm);
string tissFieldNames{};
vector<char> v_tissFieldNames;
if(_myPart == 0)
{
for(auto s: _tissFieldNames)
tissFieldNames += s + ",";
v_tissFieldNames = vector<char>(tissFieldNames.begin(),tissFieldNames.end());
}
int sizeTissFieldNames = v_tissFieldNames.size();
MPI_Bcast(&sizeTissFieldNames, 1, MPI_INT, 0, _comm);
v_tissFieldNames.resize(sizeTissFieldNames);
MPI_Bcast(v_tissFieldNames.data(), sizeTissFieldNames, MPI_CHAR, 0, _comm);
tissFieldNames = string(v_tissFieldNames.begin(),v_tissFieldNames.end());
_tissFieldNames.clear();
std::istringstream ss(tissFieldNames);
std::string token;
while(std::getline(ss, token, ','))
_tissFieldNames.push_back(token);
fieldValues.resize(nTissFields);
MPI_Bcast(fieldValues.data(), nTissFields, MPI_DOUBLE, 0, _comm);
_tissFields.resize(nTissFields);
for(int i = 0; i < nTissFields; i++)
_tissFields(i) = fieldValues[i];
fileNames.resize(nCells);
for(int i = 0; i < nCells; i++)
{
int fnamesize = fileNames[i].size();
MPI_Bcast(&fnamesize, 1, MPI_INT, 0, _comm);
if (_myPart != 0)
fileNames[i].resize(fnamesize);
MPI_Bcast(const_cast<char*>(fileNames[i].data()), fnamesize, MPI_CHAR, 0, _comm);
}
_nCells = nCells;
int baseLocItem = _nCells / _nParts;
int remain_nItem = _nCells - baseLocItem * _nParts;
int currOffs = 0;
for (int p = 0; p < _nParts; p++)
{
int p_locnitem = (p < remain_nItem) ? (baseLocItem + 1) : (baseLocItem);
_nCellPart[p] = p_locnitem;
_offsetPart[p] = currOffs;
currOffs += p_locnitem;
}
_offsetPart[_nParts] = _nCells;
int loc_nCells = _nCellPart[_myPart];
for(int i = 0; i < loc_nCells; i++)
{
RCP<Cell> cell = rcp(new Cell());
cell->loadVTK(location+fileNames[getGlobalIdx(i)]);
cell->setBasisFunctionType(bfType);
cell->Update();
_cells.emplace_back(cell);
}
MPI_Barrier(_comm);
}
}
| 35.991228 | 213 | 0.469413 | torressancheza |
2f492448200f371994c36eebc26cdc03494638b8 | 1,284 | cpp | C++ | src/tMain.cpp | veljkolazic17/DOS_threads | 0f5c065850143469862f1f5cb69d076a4dbd986c | [
"MIT"
] | null | null | null | src/tMain.cpp | veljkolazic17/DOS_threads | 0f5c065850143469862f1f5cb69d076a4dbd986c | [
"MIT"
] | null | null | null | src/tMain.cpp | veljkolazic17/DOS_threads | 0f5c065850143469862f1f5cb69d076a4dbd986c | [
"MIT"
] | null | null | null | /*
* tMain.cpp
*
* Created on: Jul 1, 2021
* Author: OS1
*/
#include "../h/tMain.h"
#include "../h/ttools.h"
#include "../h/IVTEntry.h"
#include "../h/Iterator.h"
unsigned tMain::started = 0;
int userMain(int args,char* argv[]);
void tMain::run(){
this->retback = userMain(args,argv);
}
tMain::tMain(int args,char** argv){
this->args = args;
this->argv = argv;
this->retback = -1;
}
tMain::~tMain(){
this->waitToComplete();
}
Thread* tMain::clone() const{
tMain* klon = new tMain(this->args,this->argv);
klon->retback = this->retback;
return klon;
}
int tMain::getRetback()const{
return this->retback;
}
int tMain::execute(int args,char**argv){
if(!started){
initDefaultWrapper();
inic();
tMain tmain(args,argv);
tmain.start();
tmain.waitToComplete();
int retback = tmain.getRetback();
restore();
tMain::started = 1;
return retback;
}
//TODO pitanje da li linija ispod treba da stoji
tMain::restoreIVT();
return -1;
}
void tMain::restoreIVT(){
Iterator* iterator = new Iterator((List*)Shared::IVTEntries);
IVTEntry* entry = NULL;
while((entry = (IVTEntry*)iterator->iterateNext()) != NULL){
delete entry;
}
Shared::IVTEntries->purge();
delete iterator;
}
| 18.882353 | 63 | 0.61838 | veljkolazic17 |
2f4f64ca40b575480983d6d30bc1ac115aee7c6e | 5,563 | hpp | C++ | cpp/include/eop/intrinsics.hpp | asefahmed56/elements-of-programming | 2176d4a086ad52d73f1dc3c0cd7a97351766efd7 | [
"MIT"
] | 1 | 2020-04-09T06:16:48.000Z | 2020-04-09T06:16:48.000Z | cpp/include/eop/intrinsics.hpp | asefahmed56/elements-of-programming | 2176d4a086ad52d73f1dc3c0cd7a97351766efd7 | [
"MIT"
] | null | null | null | cpp/include/eop/intrinsics.hpp | asefahmed56/elements-of-programming | 2176d4a086ad52d73f1dc3c0cd7a97351766efd7 | [
"MIT"
] | null | null | null | #ifndef EOP_INTRINSICS_HPP
#define EOP_INTRINSICS_HPP
#include "concepts.hpp"
namespace eop
{
/**
* @brief Method for construction
*
* Precondition: $v$ refers to raw memory, not an object
* Postcondition: $v$ is in a partially-formed state
*
* @tparam ContainerType A container to store heterogeneous
* constructible types
* @tparam _Tp A constructible type
* @tparam Args Other constructible types
* @param p The container, passed by constant lvalue reference
*/
template < template< typename, typename... > class ContainerType,
constructible _Tp, constructible... Args >
void construct(const ContainerType<_Tp, Args...>& p)
{
static_assert(std::is_constructible_v<_Tp>
&& std::is_constructible_v<Args...>);
for (const auto& v : p)
{
new (&v) _Tp();
}
}
/**
* @brief Method for construction, with an initializer for
* members
*
* Precondition: $v$ refers to raw memory, not an object
* Postcondition: Default makes $v = initializer$
* Override $\func{construct}$ to specialize construction
* of part of a container
*
* @tparam ContainerType A container to store heterogeneous
* constructible types
* @tparam _Tp A constructible type
* @tparam Args Other constructible types
* @tparam U An
* @param p The container, passed by constant lvalue reference
* @param initializer The initializer, passed by constant lvalue
* reference
*/
template < template< typename, typename... > class ContainerType,
constructible _Tp, constructible... Args, constructible U >
void construct(const ContainerType<_Tp, Args...>& p, const U& initializer)
{
static_assert(std::is_constructible_v<_Tp>
&& std::is_constructible_v<Args...>);
for (const auto& v : p)
{
new (&v) _Tp(initializer);
}
}
/**
* @brief Method for destruction
*
* Precondition: $v$ is in a partially-formed state
* Postcondition: $v$ refers to raw memory, not an object
*
* @tparam ContainerType A container to store heterogeneous
* destructible types
* @tparam _Tp A destructible type
* @tparam Args Other destructible types
* @param p The container, passed by constant lvalue reference
*/
template < template< typename, typename... > class ContainerType,
destructible _Tp, destructible... Args >
void destruct(const ContainerType<_Tp, Args...>& p)
{
static_assert(std::is_destructible_v<_Tp>
&& std::is_destructible_v<Args...>);
for (const auto& v : p)
{
v.~_Tp();
}
}
/**
* @brief Method for destruction, with a finalizer for members
*
* Precondition: $v$ is in a partially-formed state
* Postcondition: $v$ refers to raw memory, not an object
* Override $\func{destruct}$ to specialize destruction of
* part of a container
*
* @tparam ContainerType A container to store heterogeneous
* destructible types
* @tparam _Tp A destructible type
* @tparam Args Other destructible types
* @tparam U A finalizer
* @param p The container, passed by constant lvalue reference
* @param finalizer The finalizer, passed by lvalue reference
*/
template< template< typename, typename... > class ContainerType,
destructible _Tp, destructible... Args, destructible U >
void destruct(const ContainerType<_Tp, Args...>& p, U& finalizer)
{
static_assert(std::is_destructible_v<_Tp>
&& std::is_destructible_v<Args...>);
for (const auto& v : p)
{
destruct(v);
}
}
/**
* @brief Prefix notation for a raw pointer
*
*/
template< typename _Tp >
using raw_ptr = _Tp*;
/**
* @brief Address method to construct a raw
* pointer from a memory location
*
* @tparam _Tp An object type for a partially formed object
* from which a pointer type is constructed
*/
template< partially_formed _Tp >
eop::raw_ptr<_Tp> ptr_construct(_Tp&& x)
{
static_assert(eop::is_partially_formed_v<_Tp>);
return &x;
}
/**
* @brief Forwarding method to construct a unique
* pointer
*
* @tparam _Tp An object type for a partially formed object
* from which a unique pointer is constructed
* @tparam Args Argument types
* @param args Arguments
* @return std::unique_ptr<_Tp>
*/
template< partially_formed _Tp, partially_formed... Args >
std::unique_ptr<_Tp> ptr_construct(Args&&... args)
{
static_assert(eop::is_partially_formed_v<_Tp>);
return std::unique_ptr<_Tp>(construct(_Tp(std::forward<Args>(args)...)));
}
/**
* @brief Forwarding method to construct a shared
* pointer
*
* @tparam _Tp An object type for a partially formed object from
* which a shared pointer is constructed
* @tparam Args Argument types
* @param args Arguments
* @return std::shared_ptr<_Tp>
*/
template< partially_formed _Tp, partially_formed... Args >
std::shared_ptr<_Tp> ptr_construct(Args&&... args)
{
static_assert(eop::is_partially_formed_v<_Tp>);
return std::shared_ptr<_Tp>(construct(_Tp(std::forward<Args>(args)...)));
}
} // namespace eop
#endif // !EOP_IMTRINSICS_HPP | 32.723529 | 81 | 0.621967 | asefahmed56 |
016969c07f9e49fbba7a6a2b7ba8d588e708fef2 | 944 | hpp | C++ | include/nbtpp/tags/tagintarray.hpp | M4xi1m3/nbtpp | dfb69f2d4b52d60f54c1132047ae4a86816a5dd4 | [
"MIT"
] | null | null | null | include/nbtpp/tags/tagintarray.hpp | M4xi1m3/nbtpp | dfb69f2d4b52d60f54c1132047ae4a86816a5dd4 | [
"MIT"
] | null | null | null | include/nbtpp/tags/tagintarray.hpp | M4xi1m3/nbtpp | dfb69f2d4b52d60f54c1132047ae4a86816a5dd4 | [
"MIT"
] | null | null | null | #ifndef NBTPP_TAGS_TAGINTARRAY_HPP_
#define NBTPP_TAGS_TAGINTARRAY_HPP_
#include "../tag.hpp"
#include <vector>
namespace nbtpp {
namespace tags {
class tag_intarray: public tag {
public:
tag_intarray(std::string name) : tag(name, tag_type::TAG_Int_Array), m_value() {
}
tag_intarray(std::string name, const std::vector<int32_t>& data) : tag(name, tag_type::TAG_Byte_Array), m_value(data) {
}
virtual ~tag_intarray() {
}
void append(int32_t val) {
m_value.push_back(val);
}
inline const std::vector<int32_t>& value() const {
return m_value;
}
inline void assign(int32_t* array, size_t count) {
m_value.assign(array, array + count);
}
private:
std::vector<int32_t> m_value;
};
}
}
#endif
| 21.953488 | 131 | 0.541314 | M4xi1m3 |
016c679fcde0745331f83466ad7d22c792f30040 | 2,678 | cpp | C++ | frequency.cpp | scross99/cryptanalysis-gui | a3149972f1877889172bee9e969f3dc8b243e6ae | [
"MIT"
] | null | null | null | frequency.cpp | scross99/cryptanalysis-gui | a3149972f1877889172bee9e969f3dc8b243e6ae | [
"MIT"
] | null | null | null | frequency.cpp | scross99/cryptanalysis-gui | a3149972f1877889172bee9e969f3dc8b243e6ae | [
"MIT"
] | null | null | null | #include <wx/wx.h>
#include <wx/listctrl.h>
#include <cstdlib>
#include <iostream>
#include "frequency.h"
#include "ids.h"
#include "english.h"
BEGIN_EVENT_TABLE(WA_Frequency, wxPanel)
EVT_TEXT(frequency_txt, WA_Frequency::on_txt_changed)
END_EVENT_TABLE()
WA_Frequency::WA_Frequency(wxWindow * parent) : wxPanel(parent, wxID_ANY){
txt = new wxTextCtrl(this, frequency_txt, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE);
list = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT);
list->InsertColumn(0, wxT("Char"), wxLIST_FORMAT_CENTER);
list->InsertColumn(1, wxT("Freq"), wxLIST_FORMAT_CENTER);
list->InsertColumn(2, wxT("Match"), wxLIST_FORMAT_CENTER);
main_sizer = new wxBoxSizer(wxHORIZONTAL);
main_sizer->Add(txt, 2, wxEXPAND | wxALL, 3);
main_sizer->Add(list, 1, wxEXPAND | wxALL, 3);
SetAutoLayout(TRUE);
SetSizer(main_sizer);
}
static int wxCALLBACK freq_comp(long item1, long item2, long sortData){
if(item1 > item2){
return -1;
}else if(item1 < item2){
return 1;
}else{
return 0;
}
return 0;
}
void WA_Frequency::on_txt_changed(wxCommandEvent& event){
unsigned int freq[256];
wxString data = txt->GetValue();
unsigned int len = data.Len();
unsigned int next_id = 0;
unsigned int total_freq = 0;
//char a, b;
/*double eng_freq[] = {0.12702, 0.09056, 0.08167, 0.07507,
0.06966, 0.06749, 0.06327, 0.06094,
0.05987, 0.04253, 0.04025, 0.02782,
0.02758, 0.02406, 0.02360, 0.02228,
0.02015, 0.01974, 0.01929, 0.01492,
0.00978, 0.00772, 0.00153, 0.00150,
0.00095, 0.00074};*/
char eng_cfreq[] = {'e', 't', 'a', 'o', 'i', 'n', 's', 'h', 'r', 'd', 'l', 'c', 'u',
'm', 'w', 'f', 'g', 'y', 'p', 'b', 'v', 'k', 'j', 'x', 'q', 'z'};
list->DeleteAllItems();
//initialise frequency array to 0
for(unsigned int p = 0; p < 256; p++){
freq[p] = 0;
}
//calculate the frequency of each character
for(unsigned int i = 0; i < len; i++){
if(!isspace(data[i])){
freq[int(data[i])]++;
total_freq++;
}
}
//add frequencies to list
for(unsigned int w = 0; w < 256; w++){
if(freq[w] > 0){
list->InsertItem(next_id, wxString::Format(wxT("%c"), char(w)));
list->SetItemData(next_id, long(freq[w]));
list->SetItem(next_id, 1, wxString::Format(wxT("%.2f%%"), float(100 * freq[w]) / float(total_freq)));
list->SetItem(next_id, 2, wxT("?"));
next_id++;
}
}
list->SortItems(freq_comp, 0);
for(unsigned int q = 0; q < 26; q++){
list->SetItem(q, 2, wxString::Format(wxT("%c"), eng_cfreq[q]));
}
}
WA_Frequency::~WA_Frequency(){
}
| 27.050505 | 105 | 0.616878 | scross99 |
016faea80610f6deace15bd1cb0149f4b47d79bf | 2,131 | hpp | C++ | src/petuum_ps/oplog/oplog_partition.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | 370 | 2015-06-30T09:46:17.000Z | 2017-01-21T07:14:00.000Z | src/petuum_ps/oplog/oplog_partition.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | 3 | 2016-11-08T19:45:19.000Z | 2016-11-11T13:21:19.000Z | src/petuum_ps/oplog/oplog_partition.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | 159 | 2015-07-03T05:58:31.000Z | 2016-12-29T20:59:01.000Z | // Author: jinliang
#pragma once
#include <petuum_ps/oplog/abstract_oplog.hpp>
#include <libcuckoo/cuckoohash_map.hh>
#include <petuum_ps_common/util/striped_lock.hpp>
namespace petuum {
class OpLogPartition : public AbstractOpLog {
public:
OpLogPartition(int32_t capacity, const AbstractRow *sample_row,
size_t dense_row_oplog_capacity,
int32_t row_oplog_type);
~OpLogPartition();
void RegisterThread() { }
void DeregisterThread() { }
void FlushOpLog() { }
// exclusive access
bool Inc(int32_t row_id, int32_t column_id, const void *delta);
bool BatchInc(int32_t row_id, const int32_t *column_ids,
const void *deltas, int32_t num_updates);
bool DenseBatchInc(int32_t row_id, const void *updates,
int32_t index_st, int32_t num_updates);
// Guaranteed exclusive accesses to the same row id.
bool FindOpLog(int32_t row_id, OpLogAccessor *oplog_accessor);
// return true if a new row oplog is created
bool FindInsertOpLog(int32_t row_id, OpLogAccessor *oplog_accessor);
// oplog_accessor aquires the lock on the row whether or not the
// row oplog exists.
bool FindAndLock(int32_t row_id, OpLogAccessor *oplog_accessor);
// Not mutual exclusive but is less expensive than FIndOpLog above as it does
// not use any lock.
AbstractRowOpLog *FindOpLog(int32_t row_id);
AbstractRowOpLog *FindInsertOpLog(int32_t row_id);
// Mutual exclusive accesses
bool GetEraseOpLog(int32_t row_id, AbstractRowOpLog **row_oplog_ptr);
bool GetEraseOpLogIf(int32_t row_id, GetOpLogTestFunc test,
void *test_args, AbstractRowOpLog **row_oplog_ptr);
bool GetInvalidateOpLogMeta(int32_t row_id, RowOpLogMeta *row_oplog_meta);
AbstractAppendOnlyBuffer *GetAppendOnlyBuffer();
void PutBackBuffer(AbstractAppendOnlyBuffer* buff);
private:
const size_t update_size_;
StripedLock<int32_t> locks_;
cuckoohash_map<int32_t, AbstractRowOpLog*> oplog_map_;
const AbstractRow *sample_row_;
const size_t dense_row_oplog_capacity_;
CreateRowOpLog::CreateRowOpLogFunc CreateRowOpLog_;
};
} // namespace petuum
| 33.825397 | 79 | 0.755045 | daiwei89 |
017157ae72a7def5c133dd4127665f444dda75e7 | 2,625 | cpp | C++ | src/AppLines/b3CopyProperty.cpp | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/AppLines/b3CopyProperty.cpp | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/AppLines/b3CopyProperty.cpp | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-07T15:58:38.000Z | 2022-01-07T15:58:38.000Z | /*
**
** $Filename: b3CopyProperty.cpp $
** $Release: Dortmund 2005 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Select shape property copy modes
**
** (C) Copyright 2005 Steffen A. Mork
** All Rights Reserved
**
**
*/
/*************************************************************************
** **
** Lines III includes **
** **
*************************************************************************/
#include "AppLinesInclude.h"
#include "b3CopyProperty.h"
/*************************************************************************
** **
** DlgCopyProperties implementation **
** **
*************************************************************************/
void b3CopyPropertyInfo::b3Add(
b3Shape *srcShape,
b3Shape *dstShape,
b3Base<b3Item> *srcBase,
b3Base<b3Item> *dstBase)
{
b3CopyPropertyItem item;
srcShape->b3Store();
item.m_Original.b3InitBase(srcBase->b3GetClass());
item.m_Cloned.b3InitBase(srcBase->b3GetClass());
item.m_DstBase = dstBase;
item.m_Shape = dstShape;
b3World::b3CloneBase(srcBase,&item.m_Cloned);
m_Shapes.b3Add(item);
}
void b3CopyPropertyInfo::b3Undo()
{
b3_count i,max = m_Shapes.b3GetCount();
for (i = 0;i < max;i++)
{
b3CopyPropertyItem &item = m_Shapes[i];
item.m_Cloned.b3MoveFrom(item.m_DstBase);
item.m_DstBase->b3MoveFrom(&item.m_Original);
b3RecomputeShape(item.m_Shape, item.m_DstBase->b3GetClass());
}
}
void b3CopyPropertyInfo::b3Redo()
{
b3_count i,max = m_Shapes.b3GetCount();
for (i = 0;i < max;i++)
{
b3CopyPropertyItem &item = m_Shapes[i];
item.m_Original.b3MoveFrom(item.m_DstBase);
item.m_DstBase->b3MoveFrom(&item.m_Cloned);
b3RecomputeShape(item.m_Shape, item.m_DstBase->b3GetClass());
}
}
void b3CopyPropertyInfo::b3Delete(b3_bool done)
{
b3_count i,max = m_Shapes.b3GetCount();
if (done)
{
for (i = 0;i < max;i++)
{
m_Shapes[i].m_Original.b3Free();
}
}
else
{
for (i = 0;i < max;i++)
{
m_Shapes[i].m_Cloned.b3Free();
}
}
}
void b3CopyPropertyInfo::b3RecomputeShape(b3Shape *shape,b3_u32 surface_class)
{
switch(surface_class)
{
case CLASS_MATERIAL:
shape->b3RecomputeMaterial();
break;
case CLASS_CONDITION:
shape->b3RecomputeIndices();
break;
}
}
| 23.4375 | 78 | 0.508571 | stmork |
017294bdd75e366ade8483a96b4009bdd8b258bd | 723 | cpp | C++ | Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void fl() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
// freopen("ot.txt", "w", stdout);
#else
// freopen("jumping.in", "r", stdin); // HERE
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////
// snippet :: dinp , dhelp , dvec , lli , dfor , dcons , dbit
int main() { // dfil
fl(); //TODO
int n, l, r;
string a, b;
cin >> n >> a, b = a;
if (n & 1)
l = r = (n / 2);
else
l = r = ((n - 2) / 2), r++;
bool fl = 1;
for (auto ch : a) {
if ((n & 1) and l == r)
b[l] = ch, l--, r++;
else if (fl)
b[l] = ch, fl ^= 1, l--;
else if (!fl)
b[r] = ch, fl ^= 1, r++;
}
cout << b;
return 0;
}
| 20.083333 | 96 | 0.410788 | mohamedGamalAbuGalala |
0173df37d6ce5df5d2b00719a7859743b786c0f8 | 2,393 | cpp | C++ | src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 3 | 2015-03-07T15:41:18.000Z | 2015-11-05T05:07:45.000Z | src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 1 | 2015-04-12T11:50:33.000Z | 2015-04-12T21:13:19.000Z | src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 5 | 2015-01-13T17:14:41.000Z | 2015-05-25T16:54:26.000Z | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "TiUIProgressBarProxy.h"
#include "TiUIProgressBar.h"
namespace TiUI {
TiUIProgressBarProxy::TiUIProgressBarProxy(const char* name) : Ti::TiViewProxy(name)
{
createPropertySetterGetter("color", _setColor, _getColor);
createPropertySetterGetter("font", _setFont, _getFont);
createPropertySetterGetter("max", _setMax, _getMax);
createPropertySetterGetter("message", _setMessage, _getMessage);
createPropertySetterGetter("min", _setMin, _getMin);
createPropertySetterGetter("style", _setStyle, _getStyle);
createPropertySetterGetter("value", _setValue, _getValue);
_progressBar = new TiUIProgressBar(this);
setView(_progressBar);
}
TiUIProgressBarProxy::~TiUIProgressBarProxy()
{
}
void TiUIProgressBarProxy::setColor(Ti::TiValue)
{
// Not supported
}
void TiUIProgressBarProxy::setFont(Ti::TiValue)
{
// Not supported
}
void TiUIProgressBarProxy::setMax(Ti::TiValue val)
{
_progressBar->setMaxValue((float)val.toNumber());
}
void TiUIProgressBarProxy::setMessage(Ti::TiValue)
{
// Not supported
}
void TiUIProgressBarProxy::setMin(Ti::TiValue val)
{
_progressBar->setMinValue((float)val.toNumber());
}
void TiUIProgressBarProxy::setStyle(Ti::TiValue)
{
}
void TiUIProgressBarProxy::setValue(Ti::TiValue val)
{
_progressBar->setValue((float)val.toNumber());
}
Ti::TiValue TiUIProgressBarProxy::getColor()
{
// Not supported
Ti::TiValue val;
val.setUndefined();
return val;
}
Ti::TiValue TiUIProgressBarProxy::getFont()
{
// Not supported
Ti::TiValue val;
val.setUndefined();
return val;
}
Ti::TiValue TiUIProgressBarProxy::getMax()
{
Ti::TiValue val;
val.setNumber(_progressBar->getMaxValue());
return val;
}
Ti::TiValue TiUIProgressBarProxy::getMessage()
{
// Not supported
Ti::TiValue val;
val.setUndefined();
return val;
}
Ti::TiValue TiUIProgressBarProxy::getMin()
{
// Not supported
Ti::TiValue val;
val.setNumber(_progressBar->getMinValue());
return val;
}
Ti::TiValue TiUIProgressBarProxy::getStyle()
{
// Not supported
Ti::TiValue val;
val.setUndefined();
return val;
}
Ti::TiValue TiUIProgressBarProxy::getValue()
{
Ti::TiValue val;
val.setNumber(_progressBar->getValue());
return val;
}
}
| 22.364486 | 84 | 0.754283 | ssaracut |
01749a8cb48abff3e178b53309c6b048c7c420eb | 10,913 | cpp | C++ | test/quantile_bai_unittest.cpp | gostevehoward/quantile-cs | 12bad0fe9843e1a7263f667f95933c3d28825d87 | [
"MIT"
] | 1 | 2019-11-27T18:40:38.000Z | 2019-11-27T18:40:38.000Z | test/quantile_bai_unittest.cpp | gostevehoward/quantilecs | 12bad0fe9843e1a7263f667f95933c3d28825d87 | [
"MIT"
] | null | null | null | test/quantile_bai_unittest.cpp | gostevehoward/quantilecs | 12bad0fe9843e1a7263f667f95933c3d28825d87 | [
"MIT"
] | null | null | null | #include <random>
#include "quantile_bai.h"
#include "gtest/gtest.h"
namespace {
TEST(BanditModelTest, Bernoulli) {
std::mt19937_64 rng(123);
auto model = BanditModel::NITHBernoulli(2, .5, .1);
double draw = model.sample_arm(0, rng);
EXPECT_TRUE(draw == 0.0 || draw == 1.0);
}
TEST(BanditModelTest, Uniform) {
std::mt19937_64 rng(123);
auto model = BanditModel::NITHUniform(2, 1);
double draw1 = model.sample_arm(0, rng);
EXPECT_LE(1, draw1);
EXPECT_LE(draw1, 2);
double draw2 = model.sample_arm(0, rng);
EXPECT_NE(draw1, draw2);
double draw3 = model.sample_arm(1, rng);
EXPECT_LE(0, draw3);
EXPECT_LE(draw3, 1);
}
TEST(BanditModelTest, Cauchy) {
std::mt19937_64 rng(123);
auto model = BanditModel::NITHCauchy(2, 2e6);
double draw1 = model.sample_arm(0, rng);
EXPECT_LE(1e6, draw1);
double draw2 = model.sample_arm(0, rng);
EXPECT_NE(draw1, draw2);
double draw3 = model.sample_arm(1, rng);
EXPECT_LE(draw3, 1e6);
}
TEST(SzorenyiCITest, Radius) {
SzorenyiCI ci;
EXPECT_NEAR(ci.radius(100, .05), 0.2588138, 1e-5);
}
TEST(BetaBinomialCITest, Radius) {
// expected values based on R confseq package
// beta_binomial_mixture_bound(100*.5*.5, .05, 10*.5*.5, .5, .5) / 100
BetaBinomialCI ci(0.5, 10, .05);
EXPECT_NEAR(ci.radius(100, .05), 0.1599309, 1e-5);
// beta_binomial_mixture_bound(100*.9*.1, .05, 10*.9*.1, .9, .1) / 100
BetaBinomialCI ci2(0.9, 10, .05);
EXPECT_NEAR(ci2.radius(100, .05), 0.08109037, 1e-5);
}
TEST(StitchedCITest, Radius) {
// expected values based on R confseq package
// poly_stitching_bound(100*.5*.5, .05, 10*.5*.5, c=(1 - 2 * .5) / 3,
// eta=2.04) / 100
StitchedCI ci(0.5, 10, 2.04, 1.4);
EXPECT_NEAR(ci.radius(100, .05), 0.178119, 1e-5);
// poly_stitching_bound(100*.9*.1, .05, 10*.9*.1, c=(1 - 2 * .9) / 3,
// eta=2.04) / 100
StitchedCI ci2(0.9, 10, 2.04, 1.4);
EXPECT_NEAR(ci2.radius(100, .05), 0.0888042, 1e-5);
}
TEST(TreeTrackerTest, BasicUse) {
TreeTracker tracker;
EXPECT_EQ(tracker.size(), 0);
tracker.insert(1);
EXPECT_EQ(tracker.size(), 1);
tracker.insert(2);
EXPECT_EQ(tracker.get_order_statistic(1), 1);
EXPECT_EQ(tracker.get_order_statistic(2), 2);
for (int i = 3; i <= 50; i++) {
tracker.insert(i);
}
for (int i = 100; i >= 51; i--) {
tracker.insert(i);
}
for (int i = 3; i <= 100; i++) {
EXPECT_EQ(tracker.get_order_statistic(i), i);
EXPECT_EQ(tracker.count_less_or_equal(i), i);
EXPECT_EQ(tracker.count_less(i), i - 1);
}
}
TEST(TreeTrackerTest, TieHandling) {
TreeTracker tracker;
tracker.insert(0);
tracker.insert(1);
tracker.insert(0);
EXPECT_EQ(tracker.get_order_statistic(1), 0);
EXPECT_EQ(tracker.get_order_statistic(2), 0);
EXPECT_EQ(tracker.count_less(0), 0);
EXPECT_EQ(tracker.count_less_or_equal(0), 2);
EXPECT_EQ(tracker.get_order_statistic(3), 1);
EXPECT_EQ(tracker.count_less(1), 2);
EXPECT_EQ(tracker.count_less_or_equal(1), 3);
}
class TestCI : public ConfidenceInterval {
double radius(const int, const double) const override {
return 0.1;
}
};
TEST(QuantileCITrackerTest, BasicUse) {
auto make_os_tracker = []() {return std::make_unique<TreeTracker>();};
QuantileCITracker tracker(2, 0.59, 0.1, make_os_tracker,
std::make_unique<TestCI>(),
std::make_unique<TestCI>(),
std::make_unique<TestCI>(),
std::make_unique<TestCI>());
EXPECT_EQ(tracker.num_arms(), 2);
for (int i = 1; i <= 10; i++) {
tracker.insert(0, i);
}
EXPECT_EQ(tracker.point_estimate(0, false), 6);
EXPECT_EQ(tracker.upper_bound(0, .05, false), 7);
EXPECT_EQ(tracker.lower_bound(0, .05, false), 5);
EXPECT_EQ(tracker.point_estimate(0, true), 7);
EXPECT_EQ(tracker.upper_bound(0, .05, true), 8);
EXPECT_EQ(tracker.lower_bound(0, .05, true), 6);
for (int i = 11; i <= 100; i++) {
tracker.insert(0, i);
}
EXPECT_EQ(tracker.point_estimate(0, false), 60);
EXPECT_EQ(tracker.upper_bound(0, .05, false), 70);
EXPECT_EQ(tracker.point_estimate(0, true), 70);
}
struct CIValues {
double point_estimate = 0;
double lower_bound = -1;
double upper_bound = 1;
};
class FakeCITracker : public QuantileCIInterface {
public:
void insert(const int arm_index, const double value) override {
values_[arm_index].push_back(value);
}
double lower_bound(const int arm_index, const double error_rate,
const bool add_epsilon) const override {
return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index]
.lower_bound;
}
double upper_bound(const int arm_index, const double error_rate,
const bool add_epsilon) const override {
return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index]
.upper_bound;
}
double point_estimate(const int arm_index, const bool add_epsilon) const
override {
return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index]
.point_estimate;
}
int num_arms() const override {return 3;}
std::vector<double> values_[3];
CIValues p_ci_values[3];
CIValues p_epsilon_ci_values[3];
};
TEST(QpacAgent, BasicUse) {
auto tracker_unique_ptr = std::make_unique<FakeCITracker>();
FakeCITracker* tracker = tracker_unique_ptr.get();
QpacAgent agent(0.05, std::move(tracker_unique_ptr));
for (int i = 0; i < 3; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
}
for (int arm = 0; arm < 3; arm++) {
EXPECT_EQ(tracker->values_[arm].size(), 1);
EXPECT_EQ(tracker->values_[arm][0], arm);
}
// eliminate arm 0
tracker->p_epsilon_ci_values[0].upper_bound = -2;
for (int i = 0; i < 3; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(tracker->values_[0].size(), 2);
for (int i = 0; i < 4; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(tracker->values_[0].size(), 2);
EXPECT_EQ(tracker->values_[1].size(), 4);
EXPECT_EQ(tracker->values_[2].size(), 4);
// choose arm 2
tracker->p_epsilon_ci_values[2].lower_bound = 2;
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), 2);
}
class FakeOrderStatisticTracker : public OrderStatisticTracker {
public:
void insert(const double value) override {
inserted_values_.push_back(value);
}
double get_order_statistic(const int order_index) const
override {
auto search = order_stats_.find(order_index);
if (search != order_stats_.end()) {
return search->second;
} else {
return 0;
}
}
int count_less_or_equal(const double value) const
override {
assert(false);
return -1;
}
int count_less(const double value) const override {
assert(false);
return -1;
}
int size() const override {
return inserted_values_.size();
}
std::vector<double> inserted_values_;
std::unordered_map<int,double> order_stats_;
};
int m_k(int num_samples) {
return floor(.5 * num_samples - sqrt(3 * .5 * num_samples * 24.26684)) + 1;
}
TEST(DoubledMaxQAgent, BasicUse) {
std::vector<FakeOrderStatisticTracker*> trackers;
auto make_os_tracker = [&trackers]() {
auto tracker_unique_ptr = std::make_unique<FakeOrderStatisticTracker>();
trackers.push_back(tracker_unique_ptr.get());
return tracker_unique_ptr;
};
DoubledMaxQAgent agent(3, 0.05, 0.1, 0.5, make_os_tracker);
// 6*log(3*log(-20*.5*log(.05)/.1^2, 2)) - log(.05)
// L_D = 24.26684
// floor(3*24.26684 / .5) + 1
const int N_0 = 146;
// 10 * .5 * 24.26684 / .1^2
// stopping sample size = 12133.42
// make arm 2 the highest after the initial round
trackers[2]->order_stats_[N_0 - m_k(N_0) + 1] = 1;
// initial sampling N_0 times from each arm
for (int i = 0; i < N_0 * 3; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
}
for (int arm = 0; arm < 3; arm++) {
EXPECT_EQ(trackers[arm]->size(), N_0);
EXPECT_EQ(trackers[arm]->inserted_values_[0], arm);
}
EXPECT_EQ(agent.get_arm_to_sample(), 2);
// another N_0 samples from arm 2
trackers[2]->order_stats_[2 * N_0 - m_k(2 * N_0) + 1] = 1;
for (int i = 0; i < N_0; i++) {
EXPECT_EQ(agent.get_arm_to_sample(), 2);
EXPECT_EQ(agent.update(2, 0), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(trackers[2]->size(), 2 * N_0);
EXPECT_EQ(agent.get_arm_to_sample(), 2);
// another 2*N_0 samples from arm 2, then switch to arm 1
trackers[1]->order_stats_[N_0 - m_k(N_0) + 1] = 2;
for (int i = 0; i < 2 * N_0; i++) {
EXPECT_EQ(agent.get_arm_to_sample(), 2);
EXPECT_EQ(agent.update(2, 0), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(agent.get_arm_to_sample(), 1);
// take N_0 samples from arm 1
trackers[1]->order_stats_[2 * N_0 - m_k(2*N_0) + 1] = 2;
for (int i = 0; i < N_0; i++) {
EXPECT_EQ(agent.get_arm_to_sample(), 1);
EXPECT_EQ(agent.update(1, 0), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(trackers[2]->size(), 4 * N_0);
EXPECT_EQ(trackers[1]->size(), 2 * N_0);
// log(12134 / 146, 2) = 6.4
// so sample seven rounds total from arm 1, hence 2^7 * 146 = 18688 samples
// before stopping
for (int k = 2; k <= 7; k++) {
trackers[1]->order_stats_[pow(2, k) * N_0 - m_k(pow(2, k) * N_0) + 1] = 2;
}
for (int i = 0; i < 18688 - 2 * N_0 - 1; i++) {
EXPECT_EQ(agent.get_arm_to_sample(), 1);
EXPECT_EQ(agent.update(1, 0), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(agent.get_arm_to_sample(), 1);
EXPECT_EQ(agent.update(1, 0), 1);
}
TEST(LucbAgent, BasicUse) {
auto tracker_unique_ptr = std::make_unique<FakeCITracker>();
FakeCITracker* tracker = tracker_unique_ptr.get();
LucbAgent agent(0.05, std::move(tracker_unique_ptr));
for (int i = 0; i < 3; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED);
}
for (int arm = 0; arm < 3; arm++) {
EXPECT_EQ(tracker->values_[arm].size(), 1);
EXPECT_EQ(tracker->values_[arm][0], arm);
}
// best arm = 1, best competitor = 2
tracker->p_epsilon_ci_values[1].lower_bound = 2;
tracker->p_ci_values[2].upper_bound = 3;
for (int i = 0; i < 2; i++) {
int arm = agent.get_arm_to_sample();
EXPECT_EQ(agent.update(arm, 0), Agent::NO_ARM_SELECTED);
}
EXPECT_EQ(tracker->values_[0].size(), 1);
EXPECT_EQ(tracker->values_[1].size(), 2);
EXPECT_EQ(tracker->values_[2].size(), 2);
// now stop with best arm 2
tracker->p_epsilon_ci_values[2].lower_bound = 4;
tracker->p_ci_values[1].upper_bound = 3;
int arm = agent.get_arm_to_sample();
EXPECT_TRUE(arm == 1 || arm == 2);
EXPECT_EQ(agent.update(arm, 0), 2);
}
} // namespace
| 30.313889 | 78 | 0.652525 | gostevehoward |
017561a52f0207591485d5ec7be8f3b67f30003e | 18,513 | cpp | C++ | src/app/voltdb/voltdb_src/src/ee/executors/insertexecutor.cpp | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/src/ee/executors/insertexecutor.cpp | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/src/ee/executors/insertexecutor.cpp | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* 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 "common/ExecuteWithMpMemory.h"
#include "expressions/functionexpression.h"
#include "insertexecutor.h"
#include "plannodes/insertnode.h"
#include "storage/ConstraintFailureException.h"
#include "storage/tableutil.h"
#include "storage/temptable.h"
namespace voltdb {
int64_t InsertExecutor::s_modifiedTuples;
std::string InsertExecutor::s_errorMessage{};
std::mutex InsertExecutor::s_errorMessageUpdateLocker{};
bool InsertExecutor::p_init(AbstractPlanNode* abstractNode, const ExecutorVector& executorVector) {
VOLT_TRACE("init Insert Executor");
m_node = dynamic_cast<InsertPlanNode*>(abstractNode);
vassert(m_node);
vassert(m_node->getTargetTable());
vassert(m_node->getInputTableCount() == (m_node->isInline() ? 0 : 1));
Table* targetTable = m_node->getTargetTable();
m_isUpsert = m_node->isUpsert();
//
// The insert node's input schema is fixed. But
// if this is an inline node we don't set it here.
// We let the parent node set it in p_execute_init.
//
// Also, we don't want to set the input table for inline
// insert nodes.
//
if ( ! m_node->isInline()) {
setDMLCountOutputTable(executorVector.limits());
m_inputTable = dynamic_cast<AbstractTempTable*>(m_node->getInputTable()); //input table should be temptable
vassert(m_inputTable);
} else {
m_inputTable = NULL;
}
// Target table can be StreamedTable or PersistentTable and must not be NULL
PersistentTable *persistentTarget = dynamic_cast<PersistentTable*>(targetTable);
m_partitionColumn = -1;
StreamedTable *streamTarget = dynamic_cast<StreamedTable*>(targetTable);
m_hasStreamView = false;
if (streamTarget != NULL) {
m_isStreamed = true;
//See if we have any views.
m_hasStreamView = streamTarget->hasViews();
m_partitionColumn = streamTarget->partitionColumn();
}
if (m_isUpsert) {
VOLT_TRACE("init Upsert Executor actually");
vassert( ! m_node->isInline() );
if (m_isStreamed) {
VOLT_ERROR("UPSERT is not supported for Stream table %s", targetTable->name().c_str());
}
// look up the tuple whether it exists already
if (persistentTarget->primaryKeyIndex() == NULL) {
VOLT_ERROR("No primary keys were found in our target table '%s'",
targetTable->name().c_str());
}
}
if (persistentTarget) {
m_partitionColumn = persistentTarget->partitionColumn();
m_replicatedTableOperation = persistentTarget->isReplicatedTable();
}
m_multiPartition = m_node->isMultiPartition();
m_sourceIsPartitioned = m_node->sourceIsPartitioned();
// allocate memory for template tuple, set defaults for all columns
m_templateTupleStorage.init(targetTable->schema());
TableTuple tuple = m_templateTupleStorage.tuple();
std::set<int> fieldsExplicitlySet(m_node->getFieldMap().begin(), m_node->getFieldMap().end());
// These default values are used for an INSERT including the INSERT sub-case of an UPSERT.
// The defaults are purposely ignored in favor of existing column values
// for the UPDATE subcase of an UPSERT.
m_node->initTupleWithDefaultValues(m_engine, &m_memoryPool, fieldsExplicitlySet, tuple, m_nowFields);
return true;
}
bool InsertExecutor::p_execute_init_internal(const TupleSchema *inputSchema,
AbstractTempTable *newOutputTable, TableTuple &temp_tuple) {
vassert(m_node == dynamic_cast<InsertPlanNode*>(m_abstractNode));
vassert(m_node);
vassert(inputSchema);
vassert(m_node->isInline() || (m_inputTable == dynamic_cast<AbstractTempTable*>(m_node->getInputTable())));
vassert(m_node->isInline() || m_inputTable);
// Target table can be StreamedTable or PersistentTable and must not be NULL
// Update target table reference from table delegate
m_targetTable = m_node->getTargetTable();
vassert(m_targetTable);
vassert(nullptr != dynamic_cast<PersistentTable*>(m_targetTable) ||
nullptr != dynamic_cast<StreamedTable*>(m_targetTable));
m_persistentTable = m_isStreamed ?
NULL : static_cast<PersistentTable*>(m_targetTable);
vassert((!m_persistentTable && !m_replicatedTableOperation) ||
m_replicatedTableOperation == m_persistentTable->isReplicatedTable());
m_upsertTuple = TableTuple(m_targetTable->schema());
VOLT_TRACE("INPUT TABLE: %s\n", m_node->isInline() ? "INLINE" : m_inputTable->debug().c_str());
// Note that we need to clear static trackers: ENG-17091
// https://issues.voltdb.com/browse/ENG-17091?focusedCommentId=50362&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-50362
// count the number of successful inserts
m_modifiedTuples = 0;
m_tmpOutputTable = newOutputTable;
vassert(m_tmpOutputTable);
m_count_tuple = m_tmpOutputTable->tempTuple();
// For export tables with no partition column,
// if the data is from a replicated source,
// only insert into one partition (0).
// Other partitions can just return a 0 modified tuple count.
// OTOH, if the data is coming from a (sub)query with
// partitioned tables, perform the insert on every partition.
if (m_partitionColumn == -1 && m_isStreamed && m_multiPartition &&
!m_sourceIsPartitioned && m_engine->getPartitionId() != 0) {
m_count_tuple.setNValue(0, ValueFactory::getBigIntValue(0L));
// put the tuple into the output table
m_tmpOutputTable->insertTuple(m_count_tuple);
return false;
}
m_templateTuple = m_templateTupleStorage.tuple();
for (auto iter: m_nowFields) {
m_templateTuple.setNValue(iter, NValue::callConstant<FUNC_CURRENT_TIMESTAMP>());
}
VOLT_DEBUG("Initializing insert executor to insert into %s table %s",
static_cast<PersistentTable*>(m_targetTable)->isReplicatedTable() ? "replicated" : "partitioned",
m_targetTable->name().c_str());
VOLT_DEBUG("This is a %s insert on partition with id %d",
m_node->isInline() ? "inline"
: (m_node->getChildren()[0]->getPlanNodeType() == PlanNodeType::Materialize ?
"single-row" : "multi-row"),
m_engine->getPartitionId());
VOLT_DEBUG("Offset of partition column is %d", m_partitionColumn);
//
// Return a tuple whose schema we can use as an
// input.
//
m_tempPool = ExecutorContext::getTempStringPool();
char *storage = static_cast<char *>(m_tempPool->allocateZeroes(inputSchema->tupleLength() + TUPLE_HEADER_SIZE));
temp_tuple = TableTuple(storage, inputSchema);
return true;
}
bool InsertExecutor::p_execute_init(const TupleSchema *inputSchema,
AbstractTempTable *newOutputTable, TableTuple &temp_tuple) {
bool rslt = p_execute_init_internal(inputSchema, newOutputTable, temp_tuple);
if (m_replicatedTableOperation &&
SynchronizedThreadLock::countDownGlobalTxnStartCount(m_engine->isLowestSite())) {
// Need to set this here for inlined inserts in case there are no inline inserts
// and finish is called right after this
s_modifiedTuples = 0;
SynchronizedThreadLock::signalLowestSiteFinished();
}
return rslt;
}
void InsertExecutor::p_execute_tuple_internal(TableTuple &tuple) {
const std::vector<int>& fieldMap = m_node->getFieldMap();
std::size_t mapSize = fieldMap.size();
for (int i = 0; i < mapSize; ++i) {
// Most executors will just call setNValue instead of
// setNValueAllocateForObjectCopies.
//
// However, We need to call
// setNValueAllocateForObjectCopies here. Sometimes the
// input table's schema has an inlined string field, and
// it's being assigned to the target table's non-inlined
// string field. In this case we need to tell the NValue
// where to allocate the string data.
// For an "upsert", this templateTuple setup has two effects --
// It sets the primary key column(s) and it sets the
// updated columns to their new values.
// If the primary key value (combination) is new, the
// templateTuple is the exact combination of new values
// and default values required by the insert.
// If the primary key value (combination) already exists,
// only the NEW values stored on the templateTuple get updated
// in the existing tuple and its other columns keep their existing
// values -- the DEFAULT values that are stored in templateTuple
// DO NOT get copied to an existing tuple.
m_templateTuple.setNValueAllocateForObjectCopies(
fieldMap[i], tuple.getNValue(i), m_tempPool);
}
VOLT_TRACE("Inserting tuple '%s' into target table '%s' with table schema: %s",
m_templateTuple.debug(m_targetTable->name()).c_str(), m_targetTable->name().c_str(),
m_targetTable->schema()->debug().c_str());
// If there is a partition column for the target table
if (m_partitionColumn != -1) {
// get the value for the partition column
NValue value = m_templateTuple.getNValue(m_partitionColumn);
bool isLocal = m_engine->isLocalSite(value);
// if it doesn't map to this partiton
if (!isLocal) {
if (m_multiPartition) {
// The same row is presumed to also be generated
// on some other partition, where the partition key
// belongs.
return;
}
// When a streamed table has no views, let an SP insert execute.
// This is backward compatible with when there were only export
// tables with no views on them.
// When there are views, be strict and throw mispartitioned
// tuples to force partitioned data to be generated only
// where partitioned view rows are maintained.
if (!m_isStreamed || m_hasStreamView) {
throw ConstraintFailureException(m_targetTable, m_templateTuple,
"Mispartitioned tuple in single-partition insert statement.");
}
}
}
if (m_isUpsert) {
// upsert execution logic
vassert(m_persistentTable->primaryKeyIndex() != NULL);
TableTuple existsTuple = m_persistentTable->lookupTupleByValues(m_templateTuple);
if (!existsTuple.isNullTuple()) {
// The tuple exists already, update (only) the templateTuple columns
// that were initialized from the input tuple via the field map.
// Technically, this includes setting primary key values,
// but they are getting set to equivalent values, so that's OK.
// A simple setNValue works here because any required object
// allocations were handled when copying the input values into
// the templateTuple.
m_upsertTuple.move(m_templateTuple.address());
TableTuple &tempTuple = m_persistentTable->copyIntoTempTuple(existsTuple);
for (int i = 0; i < mapSize; ++i) {
tempTuple.setNValue(fieldMap[i], m_templateTuple.getNValue(fieldMap[i]));
}
m_persistentTable->updateTupleWithSpecificIndexes(
existsTuple, tempTuple, m_persistentTable->allIndexes());
// successfully updated
++m_modifiedTuples;
return;
}
// else, the primary key did not match,
// so fall through to the "insert" logic
}
m_targetTable->insertTuple(m_templateTuple);
VOLT_TRACE("Target table:\n%s\n", m_targetTable->debug().c_str());
// successfully inserted
++m_modifiedTuples;
}
void InsertExecutor::p_execute_tuple(TableTuple &tuple) {
// This should only be called from inlined insert executors because we have to change contexts every time
ConditionalSynchronizedExecuteWithMpMemory possiblySynchronizedUseMpMemory(
m_replicatedTableOperation, m_engine->isLowestSite(),
[]() {
s_modifiedTuples = -1l;
s_errorMessage.clear();
});
if (possiblySynchronizedUseMpMemory.okToExecute()) {
p_execute_tuple_internal(tuple);
if (m_replicatedTableOperation) {
s_modifiedTuples = m_modifiedTuples;
}
} else if (s_modifiedTuples == -1) {
// An exception was thrown on the lowest site thread and we need to throw here as well so
// all threads are in the same state
throwSerializableTypedEEException(
VoltEEExceptionType::VOLT_EE_EXCEPTION_TYPE_REPLICATED_TABLE,
"Replicated table insert threw an unknown exception on other thread for table %s",
m_targetTable->name().c_str());
}
}
void InsertExecutor::p_execute_finish() {
if (m_replicatedTableOperation) {
// Use the static value assigned above to propagate the result to the other engines
// that skipped the replicated table work
vassert(s_modifiedTuples != -1);
m_modifiedTuples = s_modifiedTuples;
}
m_count_tuple.setNValue(0, ValueFactory::getBigIntValue(m_modifiedTuples));
// put the tuple into the output table
m_tmpOutputTable->insertTuple(m_count_tuple);
// add to the planfragments count of modified tuples
m_engine->addToTuplesModified(m_modifiedTuples);
VOLT_DEBUG("Finished inserting %" PRId64 " tuples", m_modifiedTuples);
VOLT_TRACE("InsertExecutor output table:\n%s\n", m_tmpOutputTable->debug().c_str());
VOLT_TRACE("InsertExecutor target table:\n%s\n", m_targetTable->debug().c_str());
}
bool InsertExecutor::p_execute(const NValueArray ¶ms) {
//
// See p_execute_init above. If we are inserting a
// replicated table into an export table with no partition column,
// we only insert on one site. For all other sites we just
// do nothing.
//
TableTuple inputTuple;
const TupleSchema *inputSchema = m_inputTable->schema();
if (p_execute_init_internal(inputSchema, m_tmpOutputTable, inputTuple)) {
ConditionalSynchronizedExecuteWithMpMemory possiblySynchronizedUseMpMemory(
m_replicatedTableOperation, m_engine->isLowestSite(),
[]() { s_modifiedTuples = -1l; });
if (possiblySynchronizedUseMpMemory.okToExecute()) {
//
// An insert is quite simple really. We just loop through our m_inputTable
// and insert any tuple that we find into our targetTable. It doesn't get any easier than that!
//
TableIterator iterator = m_inputTable->iterator();
try {
while (iterator.next(inputTuple)) {
p_execute_tuple_internal(inputTuple);
}
} catch (ConstraintFailureException const& e) {
if (m_replicatedTableOperation) {
s_errorMessage = e.what();
}
throw;
}
if (m_replicatedTableOperation) {
s_modifiedTuples = m_modifiedTuples;
}
} else if (s_modifiedTuples == -1) {
// An exception was thrown on the lowest site thread and we need to throw here as well so
// all threads are in the same state
char msg[4096];
if (!s_errorMessage.empty()) {
std::lock_guard<std::mutex> g(s_errorMessageUpdateLocker);
strcpy(msg, s_errorMessage.c_str());
} else {
snprintf(msg, sizeof msg,
"Replicated table insert threw an unknown exception on other thread for table %s",
m_targetTable->name().c_str());
}
msg[sizeof msg - 1] = '\0';
VOLT_DEBUG("%s", msg);
// NOTE!!! Cannot throw any other types like ConstraintFailureException
throw SerializableEEException(VoltEEExceptionType::VOLT_EE_EXCEPTION_TYPE_REPLICATED_TABLE, msg);
}
}
p_execute_finish();
return true;
}
InsertExecutor *getInlineInsertExecutor(const AbstractPlanNode *node) {
InsertExecutor *answer = NULL;
InsertPlanNode *insertNode = dynamic_cast<InsertPlanNode *>(node->getInlinePlanNode(PlanNodeType::Insert));
if (insertNode) {
answer = dynamic_cast<InsertExecutor *>(insertNode->getExecutor());
}
return answer;
}
}
| 44.395683 | 156 | 0.67693 | OpenMPDK |
017749506f9ca6e648e0c0787bacc0178bd9e649 | 14,148 | cpp | C++ | opt/nomad/src/Algos/Mads/Poll.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 31 | 2019-02-05T16:39:18.000Z | 2022-03-11T23:14:11.000Z | opt/nomad/src/Algos/Mads/Poll.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 20 | 2020-04-13T09:22:53.000Z | 2021-08-16T16:14:13.000Z | opt/nomad/src/Algos/Mads/Poll.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 6 | 2020-04-21T17:43:47.000Z | 2021-03-10T04:12:34.000Z | /*---------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */
/* */
/* NOMAD - Version 4 has been created by */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* The copyright of NOMAD - version 4 is owned by */
/* Charles Audet - Polytechnique Montreal */
/* Sebastien Le Digabel - Polytechnique Montreal */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */
/* NSERC (Natural Sciences and Engineering Research Council of Canada), */
/* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */
/* for Data Valorization) */
/* */
/* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */
/* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */
/* and Exxon Mobil. */
/* */
/* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */
/* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */
/* Exxon Mobil. */
/* */
/* Contact information: */
/* Polytechnique Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* */
/* This program 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 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 Lesser General Public License */
/* for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*---------------------------------------------------------------------------------*/
#include "../../Algos/AlgoStopReasons.hpp"
#include "../../Algos/Mads/DoublePollMethod.hpp"
#include "../../Algos/Mads/NP1UniPollMethod.hpp"
#include "../../Algos/Mads/Ortho2NPollMethod.hpp"
#include "../../Algos/Mads/OrthoNPlus1NegPollMethod.hpp"
#include "../../Algos/Mads/Poll.hpp"
#include "../../Algos/Mads/SinglePollMethod.hpp"
#include "../../Algos/SubproblemManager.hpp"
#include "../../Output/OutputQueue.hpp"
#include "../../Type/DirectionType.hpp"
#ifdef TIME_STATS
#include "../../Util/Clock.hpp"
// Initialize static variables
double NOMAD::Poll::_pollTime;
double NOMAD::Poll::_pollEvalTime;
#endif // TIME_STATS
void NOMAD::Poll::init()
{
setStepType(NOMAD::StepType::POLL);
verifyParentNotNull();
// Compute primary and secondary poll centers
std::vector<NOMAD::EvalPoint> primaryCenters, secondaryCenters;
computePrimarySecondaryPollCenters(primaryCenters, secondaryCenters);
// Add poll methods for primary polls
for (auto pollCenter : primaryCenters)
{
for (auto pollMethod : createPollMethods(true, pollCenter))
{
_pollMethods.push_back(pollMethod);
}
}
// Add poll methods for secondary polls
for (auto pollCenter : secondaryCenters)
{
for (auto pollMethod : createPollMethods(false, pollCenter))
{
_pollMethods.push_back(pollMethod);
}
}
}
void NOMAD::Poll::startImp()
{
// Sanity check.
verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false);
}
bool NOMAD::Poll::runImp()
{
bool pollSuccessful = false;
std::string s;
// Sanity check. The runImp function should be called only when trial points are generated and evaluated for each search method separately.
verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false);
// Go through all poll methods to generate points.
OUTPUT_DEBUG_START
s = "Generate points for " + getName();
AddOutputDebug(s);
OUTPUT_DEBUG_END
#ifdef TIME_STATS
double pollStartTime = NOMAD::Clock::getCPUTime();
double pollEvalStartTime = NOMAD::EvcInterface::getEvaluatorControl()->getEvalTime();
#endif // TIME_STATS
// 1- Generate points for all poll methods
generateTrialPoints();
// 2- Evaluate points
bool isOrthoNP1 = false;
for (auto dirType : _runParams->getAttributeValue<NOMAD::DirectionTypeList>("DIRECTION_TYPE"))
{
if ( NOMAD::DirectionType::ORTHO_NP1_NEG == dirType
|| NOMAD::DirectionType::ORTHO_NP1_QUAD == dirType)
{
isOrthoNP1 = true;
}
}
if ( ! _stopReasons->checkTerminate() )
{
size_t keepN = NOMAD::INF_SIZE_T;
if (isOrthoNP1)
{
// Keep only N points on the 2N points generated.
keepN = _pbParams->getAttributeValue<size_t>("DIMENSION");
}
// The StepType argument ensures that all points from secondary poll will
// kept, since they were generated with a POLL_METHOD_DOUBLE StepType.
evalTrialPoints(this, keepN, NOMAD::StepType::POLL_METHOD_ORTHO_NPLUS1_NEG);
pollSuccessful = (getSuccessType() >= NOMAD::SuccessType::FULL_SUCCESS);
}
// 3- Second evaluation pass: Ortho N+1
if (!_stopReasons->checkTerminate() && !pollSuccessful && isOrthoNP1)
{
// Generate point for N+1th direction.
// Provide evaluated trial points, then erase them to ensure that they
// are not re-evaluated, then put them back for postProcessing().
auto evaluatedTrialPoints = getTrialPoints();
clearTrialPoints();
// We only want to use points that were generated by step POLL_METHOD_ORTHO_NPLUS1_NEG.
NOMAD::EvalPointSet inputTrialPoints;
for (auto trialPoint: evaluatedTrialPoints)
{
if (NOMAD::StepType::POLL_METHOD_ORTHO_NPLUS1_NEG == trialPoint.getGenStep())
{
inputTrialPoints.insert(trialPoint);
}
}
generateTrialPointsNPlus1(inputTrialPoints);
// Evaluate point.
if (getTrialPointsCount() > 0)
{
evalTrialPoints(this);
pollSuccessful = (getSuccessType() >= NOMAD::SuccessType::FULL_SUCCESS);
}
// Add back trial points that are already evaluated.
for (auto trialPoint: evaluatedTrialPoints)
{
insertTrialPoint(trialPoint);
}
}
#ifdef TIME_STATS
_pollTime += NOMAD::Clock::getCPUTime() - pollStartTime;
_pollEvalTime += NOMAD::EvcInterface::getEvaluatorControl()->getEvalTime() - pollEvalStartTime;
#endif // TIME_STATS
OUTPUT_INFO_START
s = getName();
s += (pollSuccessful) ? " is successful" : " is not successful";
s += ". Stop reason: ";
s += _stopReasons->getStopReasonAsString() ;
AddOutputInfo(s);
OUTPUT_INFO_END
return pollSuccessful;
}
void NOMAD::Poll::endImp()
{
// Sanity check. The endImp function should be called only when trial points are generated and evaluated for each search method separately.
verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false);
// Compute hMax and update Barrier.
postProcessing();
}
// Generate new points to evaluate
// Note: Used whether MEGA_SEARCH_POLL is true or false.
void NOMAD::Poll::generateTrialPoints()
{
for (auto pollMethod : _pollMethods)
{
if (_stopReasons->checkTerminate())
{
break;
}
pollMethod->generateTrialPoints();
// Pass the points from Poll method to Poll for later evaluation
auto pollMethodPoints = pollMethod->getTrialPoints();
for (auto point : pollMethodPoints)
{
insertTrialPoint(point);
}
}
// Stopping criterion
if (0 == getTrialPointsCount())
{
auto madsStopReasons = NOMAD::AlgoStopReasons<NOMAD::MadsStopType>::get(_stopReasons);
madsStopReasons->set(NOMAD::MadsStopType::MESH_PREC_REACHED);
}
}
void NOMAD::Poll::generateTrialPointsNPlus1(const NOMAD::EvalPointSet& inputTrialPoints)
{
for (auto pollMethod : _pollMethods)
{
if (_stopReasons->checkTerminate())
{
break;
}
if (!pollMethod->hasNPlus1())
{
continue;
}
// Provide the evaluated trial
// points to the PollMethod for n+1th point generation.
pollMethod->generateTrialPointsNPlus1(inputTrialPoints);
// Add the n+1th point to trial points.
for (auto point : pollMethod->getTrialPoints())
{
insertTrialPoint(point);
}
}
}
void NOMAD::Poll::computePrimarySecondaryPollCenters(
std::vector<NOMAD::EvalPoint> &primaryCenters,
std::vector<NOMAD::EvalPoint> &secondaryCenters) const
{
auto barrier = getMegaIterationBarrier();
if (nullptr != barrier)
{
auto firstXFeas = barrier->getFirstXFeas();
auto firstXInf = barrier->getFirstXInf();
bool primaryIsInf = false;
NOMAD::Double rho = _runParams->getAttributeValue<NOMAD::Double>("RHO");
// Negative rho means make no distinction between primary and secondary polls.
bool usePrimarySecondary = (rho >= 0) && (nullptr != firstXFeas) && (nullptr != firstXInf);
if (usePrimarySecondary)
{
auto evc = NOMAD::EvcInterface::getEvaluatorControl();
auto evalType = evc->getEvalType();
auto computeType = evc->getComputeType();
NOMAD::Double fFeas = firstXFeas->getF(evalType, computeType);
NOMAD::Double fInf = firstXInf->getF(evalType, computeType);
if (fFeas.isDefined() && fInf.isDefined()
&& (fFeas - rho) > fInf)
{
// xFeas' f is too large, use xInf as primary poll instead.
primaryIsInf = true;
}
}
if (usePrimarySecondary)
{
if (primaryIsInf)
{
primaryCenters = barrier->getAllXInf();
secondaryCenters = barrier->getAllXFeas();
}
else
{
primaryCenters = barrier->getAllXFeas();
secondaryCenters = barrier->getAllXInf();
}
}
else
{
// All points are primary centers.
primaryCenters = barrier->getAllPoints();
}
}
}
std::vector<std::shared_ptr<NOMAD::PollMethodBase>> NOMAD::Poll::createPollMethods(const bool isPrimary, const NOMAD::EvalPoint& frameCenter) const
{
std::vector<std::shared_ptr<NOMAD::PollMethodBase>> pollMethods;
// Select the poll methods to be executed
NOMAD::DirectionTypeList dirTypes;
if (isPrimary)
{
dirTypes = _runParams->getAttributeValue<DirectionTypeList>("DIRECTION_TYPE");
}
else
{
dirTypes = _runParams->getAttributeValue<DirectionTypeList>("DIRECTION_TYPE_SECONDARY_POLL");
}
for (auto dirType : dirTypes)
{
std::shared_ptr<NOMAD::PollMethodBase> pollMethod;
switch (dirType)
{
case DirectionType::ORTHO_2N:
pollMethod = std::make_shared<NOMAD::Ortho2NPollMethod>(this, frameCenter);
break;
case DirectionType::ORTHO_NP1_NEG:
pollMethod = std::make_shared<NOMAD::OrthoNPlus1NegPollMethod>(this, frameCenter);
break;
case DirectionType::NP1_UNI:
pollMethod = std::make_shared<NOMAD::NP1UniPollMethod>(this, frameCenter);
break;
case DirectionType::DOUBLE:
pollMethod = std::make_shared<NOMAD::DoublePollMethod>(this, frameCenter);
break;
case DirectionType::SINGLE:
pollMethod = std::make_shared<NOMAD::SinglePollMethod>(this, frameCenter);
break;
default:
throw NOMAD::Exception(__FILE__, __LINE__,"Poll method" + directionTypeToString(dirType) + " is not available.");
break;
}
pollMethods.push_back(pollMethod);
}
return pollMethods;
}
| 39.741573 | 147 | 0.556192 | scikit-quant |
0177b1a5e739a0eef4cbf6ab6f8e3cbcd699183c | 4,671 | cpp | C++ | tests/filemanager/copy.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/filemanager/copy.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/filemanager/copy.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <nomagic.h>
#include "move_copy_test.h"
#include "copy.h"
using fm::filemanager::test::Copy_test;
START_TEST(should_copy_a_file_to_a_file)
{
Copy_test test;
test.test_should_move_or_copy_a_file_to_a_file();
}
END_TEST
START_TEST(should_copy_a_file_to_a_filepath)
{
Copy_test test;
test.test_should_move_a_file_to_a_filepath();
}
END_TEST
START_TEST(should_copy_a_file_to_a_directory)
{
Copy_test test;
test.test_should_move_a_file_to_a_directory();
}
END_TEST
START_TEST(should_copy_a_directory_to_a_directory)
{
Copy_test test(true);
test.test_should_move_a_directory_to_a_directory();
}
END_TEST
START_TEST(should_not_copy_similar_files)
{
Copy_test test;
test.test_should_not_move_similar_files();
}
END_TEST
START_TEST(should_not_copy_a_file_to_a_dir_when_a_dir_exists)
{
Copy_test test;
test.test_should_not_move_a_file_to_a_dir_when_a_dir_exists();
}
END_TEST
START_TEST(should_not_copy_a_file_to_an_impossible_path)
{
Copy_test test;
test.test_should_not_move_a_file_to_an_impossible_path();
}
END_TEST
START_TEST(should_copy_a_directory_to_a_directory_path)
{
Copy_test test(true);
test.test_should_move_a_directory_to_a_directory_path();
}
END_TEST
START_TEST(should_not_copy_a_directory_to_an_impossible_path)
{
Copy_test test(true);
test.test_should_not_move_a_directory_to_an_impossible_path();
}
END_TEST
START_TEST(should_not_copy_a_directory_to_its_an_ancestor)
{
Copy_test test(true);
test.test_should_not_move_a_directory_to_its_an_ancestor();
}
END_TEST
START_TEST(should_not_copy_a_file_when_it_looks_like_a_dir)
{
Copy_test test;
test.test_should_not_move_a_file_when_it_looks_like_a_dir();
}
END_TEST
START_TEST(should_not_copy_a_dir_when_it_looks_like_a_file)
{
Copy_test test(true);
test.test_should_not_move_a_dir_when_it_looks_like_a_file();
}
END_TEST
START_TEST(copy_a_file_mapping_without_its_real_file)
{
Copy_test test;
test.test_move_a_file_mapping_without_its_real_file();
}
END_TEST
START_TEST(copy_a_dir_mapping_without_its_real_dir)
{
Copy_test test(true);
test.test_move_a_dir_mapping_without_its_real_dir();
}
END_TEST
START_TEST(should_not_copy_a_dir_to_a_dir_which_does_not_exist)
{
Copy_test test(true);
test.test_should_not_move_a_dir_to_a_dir_which_does_not_exist();
}
END_TEST
START_TEST(copy_a_dir_to_a_dirpath_where_there_is_a_dir)
{
Copy_test test(true);
test.test_move_a_dir_to_a_dirpath_where_there_is_a_dir();
}
END_TEST
START_TEST(should_not_copy_a_file_to_a_dest_file_which_does_not_exist)
{
Copy_test test;
test.test_should_not_move_a_file_to_a_dest_file_which_does_not_exist();
}
END_TEST
START_TEST(copy_a_file_to_a_path_where_there_is_a_file)
{
Copy_test test;
test.test_move_a_file_to_a_path_where_there_is_a_file();
}
END_TEST
START_TEST(should_not_copy_a_file_to_a_dir_which_does_not_exist)
{
Copy_test test;
test.test_should_not_move_a_file_to_a_dir_which_does_not_exist();
}
END_TEST
START_TEST(copy_a_file_to_a_dir_which_does_not_have_any_mappings)
{
Copy_test test;
test.test_move_a_file_to_a_dir_which_does_not_have_any_mappings();
}
END_TEST
namespace fm {
namespace filemanager {
namespace test {
TCase* create_copy_tcase()
{
TCase* tcase(tcase_create("copy"));
tcase_add_test(tcase, should_copy_a_file_to_a_file);
tcase_add_test(tcase, should_copy_a_file_to_a_filepath);
tcase_add_test(tcase, should_copy_a_file_to_a_directory);
tcase_add_test(tcase, should_copy_a_directory_to_a_directory);
tcase_add_test(tcase, should_not_copy_similar_files);
tcase_add_test(tcase,
should_not_copy_a_file_to_a_dir_when_a_dir_exists);
tcase_add_test(tcase, should_not_copy_a_file_to_an_impossible_path);
tcase_add_test(tcase, should_copy_a_directory_to_a_directory_path);
tcase_add_test(tcase,
should_not_copy_a_directory_to_an_impossible_path);
tcase_add_test(tcase, should_not_copy_a_directory_to_its_an_ancestor);
tcase_add_test(tcase, should_not_copy_a_file_when_it_looks_like_a_dir);
tcase_add_test(tcase, should_not_copy_a_dir_when_it_looks_like_a_file);
tcase_add_test(tcase, copy_a_file_mapping_without_its_real_file);
tcase_add_test(tcase, copy_a_dir_mapping_without_its_real_dir);
tcase_add_test(tcase,
should_not_copy_a_dir_to_a_dir_which_does_not_exist);
tcase_add_test(tcase, copy_a_dir_to_a_dirpath_where_there_is_a_dir);
tcase_add_test(tcase,
should_not_copy_a_file_to_a_dest_file_which_does_not_exist);
tcase_add_test(tcase, copy_a_file_to_a_path_where_there_is_a_file);
tcase_add_test(tcase,
should_not_copy_a_file_to_a_dir_which_does_not_exist);
tcase_add_test(tcase,
copy_a_file_to_a_dir_which_does_not_have_any_mappings);
return tcase;
}
} // test
} // filemanager
} // fm
| 24.97861 | 72 | 0.863413 | sugawaray |
0183d939af51b8eb3c5f498bc3ea123b34bfe91e | 676 | cpp | C++ | test/fuzzer/TraceMallocThreadedTest.cpp | hnakamur/golang-1.13-race-detector-runtime-deb | d72346b69f3b54fa522bc1cdfae7ee67d27db89c | [
"MIT"
] | 27 | 2021-02-18T01:05:06.000Z | 2022-03-29T05:34:37.000Z | test/fuzzer/TraceMallocThreadedTest.cpp | hnakamur/golang-1.13-race-detector-runtime-deb | d72346b69f3b54fa522bc1cdfae7ee67d27db89c | [
"MIT"
] | 5 | 2018-08-16T08:36:55.000Z | 2019-09-30T18:12:05.000Z | test/fuzzer/TraceMallocThreadedTest.cpp | hnakamur/golang-1.13-race-detector-runtime-deb | d72346b69f3b54fa522bc1cdfae7ee67d27db89c | [
"MIT"
] | 25 | 2018-02-15T16:02:54.000Z | 2022-03-23T14:55:25.000Z | // This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// Check that allocation tracing from different threads does not cause
// interleaving of stack traces.
#include <assert.h>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <thread>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
auto C = [&] {
void * volatile a = malloc(5639);
free((void *)a);
};
std::thread T[] = {std::thread(C), std::thread(C), std::thread(C),
std::thread(C), std::thread(C), std::thread(C)};
for (auto &X : T)
X.join();
return 0;
}
| 28.166667 | 73 | 0.652367 | hnakamur |
018e0bb14cb6c52ef92d31df5bea008c850ec038 | 31,826 | cpp | C++ | camera/hal/intel/ipu3/psl/ipu3/SyncManager.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | camera/hal/intel/ipu3/psl/ipu3/SyncManager.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | camera/hal/intel/ipu3/psl/ipu3/SyncManager.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | /*
* Copyright (C) 2018 Intel Corporation
*
* 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.
*/
#define LOG_TAG "SyncManager"
#include "SyncManager.h"
#include "MediaController.h"
#include "MediaEntity.h"
#include "LogHelper.h"
#include "PerformanceTraces.h"
#include "Camera3GFXFormat.h"
#include "CaptureUnit.h"
namespace cros {
namespace intel {
#define MAX_SETTINGS_QUEUE_SIZE (SETTINGS_POOL_SIZE / 2)
SyncManager::SyncManager(int32_t cameraId,
std::shared_ptr<MediaController> mediaCtl,
ISofListener *sofListener,
ISettingsSyncListener *listener):
mCameraId(cameraId),
mMediaCtl(mediaCtl),
mSofListener(sofListener),
mSensorType(SENSOR_TYPE_NONE),
mSensorOp(nullptr),
mFrameSyncSource(FRAME_SYNC_NA),
mCameraThread("SyncManager"),
mStarted(false),
mExposureDelay(0),
mGainDelay(0),
mDigiGainOnSensor(false),
mCurrentSettingIdentifier(0),
mPollErrorTimes(0),
mErrCb(nullptr),
mUseDiscreteDg(false)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
mCapInfo = getIPU3CameraCapInfo(cameraId);
if (!mCameraThread.Start()) {
LOGE("Camera thread failed to start");
}
}
SyncManager::~SyncManager()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status;
status = stop();
if (status != NO_ERROR) {
LOGE("Error stopping sync manager during destructor");
}
mCameraThread.Stop();
if (mFrameSyncSource != FRAME_SYNC_NA) {
// both EOF and SOF are from the ISYS receiver
if (mIsysReceiverSubdev != nullptr)
mIsysReceiverSubdev->UnsubscribeEvent(mFrameSyncSource);
mFrameSyncSource = FRAME_SYNC_NA;
}
if (mSensorOp != nullptr)
mSensorOp = nullptr;
mQueuedSettings.clear();
}
/**
* based on the type of the mediacontroller entity, the correct subdev
* will be chosen. Here, are treated 4 entities.
* sensor side: pixel array
* ISYS side: isys receiver
*
* \param[IN] entity: pointer to media entity struct
* \param[IN] type: type of the subdev
*
* \return OK on success, BAD_VALUE on error
*/
status_t SyncManager::setSubdev(std::shared_ptr<MediaEntity> entity, sensorEntityType type)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
std::shared_ptr<cros::V4L2Subdevice> subdev = nullptr;
entity->getDevice((std::shared_ptr<cros::V4L2Device>&) subdev);
switch (type) {
case SUBDEV_PIXEL_ARRAY:
if (entity->getType() != SUBDEV_SENSOR) {
LOGE("%s is not sensor subdevice", entity->getName());
return BAD_VALUE;
}
mPixelArraySubdev = subdev;
break;
case SUBDEV_ISYSRECEIVER:
if (entity->getType() != SUBDEV_GENERIC) {
LOGE("%s is not Isys receiver subdevice\n", entity->getName());
}
mIsysReceiverSubdev = subdev;
break;
default:
LOGE("Entity type (%d) not existing", type);
return BAD_VALUE;
}
return OK;
}
/**
* wrapper to retrieve media entity and set the appropriate subdev
*
* \param[IN] name given name of the entity
* \param[IN] type type of the subdev
*
* \return OK on success, BAD_VALUE on error
*/
status_t SyncManager::setMediaEntity(const std::string &name,
const sensorEntityType type)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
std::shared_ptr<MediaEntity> mediaEntity = nullptr;
std::string entityName;
const IPU3CameraCapInfo *cap = getIPU3CameraCapInfo(mCameraId);
if (cap == nullptr) {
LOGE("Failed to get cameraCapInfo");
return UNKNOWN_ERROR;
}
//The entity port of ipu3-csi2 is dynamical,
//get ipu3-csi2 0 or 1 from pixel entity sink.
if (type == SUBDEV_ISYSRECEIVER) {
const char* pixelType = "pixel_array";
entityName = cap->getMediaCtlEntityName(pixelType);
status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str());
if (mediaEntity == nullptr || status != NO_ERROR) {
LOGE("Could not retrieve media entity %s", entityName.c_str());
return UNKNOWN_ERROR;
}
std::vector<string> names;
names.clear();
status = mMediaCtl->getSinkNamesForEntity(mediaEntity, names);
if (names.size()== 0 || status != NO_ERROR) {
LOGE("Could not retrieve sink name of media entity %s",
entityName.c_str());
return UNKNOWN_ERROR;
}
LOG1("camera %d using csi port: %s\n", mCameraId, names[0].c_str());
entityName = names[0];
} else {
entityName = cap->getMediaCtlEntityName(name);
}
LOG1("found entityName: %s\n", entityName.c_str());
if (entityName == "none" && name == "pixel_array") {
LOGE("No %s in this Sensor. Should not happen", entityName.c_str());
return UNKNOWN_ERROR;
} else if (entityName == "none") {
LOG1("No %s in this Sensor. Should not happen", entityName.c_str());
} else {
status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str());
if (mediaEntity == nullptr || status != NO_ERROR) {
LOGE("Could not retrieve media entity %s", entityName.c_str());
return UNKNOWN_ERROR;
}
status = setSubdev(mediaEntity, type);
if (status != OK) {
LOGE("Cannot set %s subdev", entityName.c_str());
return status;
}
}
return status;
}
/**
* Enqueue init message to message queue.
*
* \param[IN] exposureDelay exposure delay
* \param[IN] gainDelay gain delay
*
* \return status of synchronous messaging.
*/
status_t SyncManager::init(int32_t exposureDelay, int32_t gainDelay)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
MessageInit msg;
/**
* The delay we want to store is the relative between exposure and gain
* Usually exposure time delay is bigger. The model currently
* does not support the other case. We have not seen any sensor that
* does this.
*/
if (exposureDelay >= gainDelay) {
msg.gainDelay = exposureDelay - gainDelay;
} else {
LOGE("analog Gain delay bigger than exposure... not supported - BUG");
msg.gainDelay = 0;
}
msg.exposureDelay = exposureDelay;
status_t status = NO_ERROR;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleInit, base::Unretained(this),
base::Passed(std::move(msg)));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
void SyncManager::registerErrorCallback(IErrorCallback *errCb)
{
LOG1("@%s, errCb:%p", __FUNCTION__, errCb);
mErrCb = errCb;
}
/**
* function to init the SyncManager.
* set subdev.
* create sensor object, pollerthread object.
* register sensor events.
*/
status_t SyncManager::handleInit(MessageInit msg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
mExposureDelay = msg.exposureDelay;
mGainDelay = msg.gainDelay;
mDigiGainOnSensor = mCapInfo->digiGainOnSensor();
mSensorType = (SensorType)mCapInfo->sensorType();
// set pixel array
status = setMediaEntity("pixel_array", SUBDEV_PIXEL_ARRAY);
if (status != NO_ERROR) {
LOGE("Cannot set pixel array");
goto exit;
}
status = createSensorObj();
if (status != NO_ERROR) {
LOGE("Failed to create sensor object");
goto exit;
}
/* WA for using discrete digital gain */
if (mCapInfo->mAgMaxRatio && mCapInfo->mAgMultiplier) {
if (mSensorOp->createDiscreteDgMap(&mUseDiscreteDg))
LOG2("%s no discrete DG for this sensor", __FUNCTION__);
}
mQueuedSettings.clear();
mDelayedAGains.clear();
mDelayedDGains.clear();
exit:
return status;
}
/**
* method to check what type of driver the kernel
* is using and create sensor object based on it.
* at the moment, either SMIA or CRL.
*
* \return OK if success.
*/
status_t SyncManager::createSensorObj()
{
status_t status = OK;
if (mPixelArraySubdev == nullptr) {
LOGE("Pixel array sub device not set");
return UNKNOWN_ERROR;
}
mSensorOp = std::make_shared<SensorHwOp>(mPixelArraySubdev);
return status;
}
/**
* get sensor mode data after init.
*
* \param[OUT] desc sensor descriptor data
*
* \return OK, if sensor mode data retrieval was successful with good values
* \return UNKNOWN_ERROR if pixel clock value was bad
* \return Other non-OK value depending on error case
*/
status_t SyncManager::getSensorModeData(ia_aiq_exposure_sensor_descriptor &desc)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
MessageSensorModeData msg;
msg.desc = &desc;
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleGetSensorModeData,
base::Unretained(this), base::Passed(std::move(msg)));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
/**
* retrieve mode data (descriptor) from sensor
*
* \param[in] msg holding pointer to descriptor pointer
*/
status_t SyncManager::handleGetSensorModeData(MessageSensorModeData msg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
int integration_step = 0;
int integration_max = 0;
int pixel = 0;
unsigned int vBlank = 0;
ia_aiq_exposure_sensor_descriptor *desc;
desc = msg.desc;
status = mSensorOp->getPixelRate(pixel);
if (status != NO_ERROR) {
LOGE("Failed to get pixel clock");
return status;
} else if (pixel == 0) {
LOGE("Bad pixel clock value: %d", pixel);
return UNKNOWN_ERROR;
}
desc->pixel_clock_freq_mhz = (float)pixel / 1000000;
unsigned int pixel_periods_per_line = 0, line_periods_per_field = 0;
status = mSensorOp->updateMembers();
if (status != NO_ERROR) {
LOGE("Failed to update members");
return status;
}
status = mSensorOp->getMinimumFrameDuration(pixel_periods_per_line,
line_periods_per_field);
if (status != NO_ERROR) {
LOGE("Failed to get frame Durations");
return status;
}
desc->pixel_periods_per_line = pixel_periods_per_line > USHRT_MAX ?
USHRT_MAX: pixel_periods_per_line;
desc->line_periods_per_field = line_periods_per_field > USHRT_MAX ?
USHRT_MAX: line_periods_per_field;
int coarse_int_time_min = -1;
status = mSensorOp->getExposureRange(coarse_int_time_min,
integration_max, integration_step);
if (status != NO_ERROR) {
LOGE("Failed to get Exposure Range");
return status;
}
desc->coarse_integration_time_min = CLIP(coarse_int_time_min, SHRT_MAX, 0);
LOG2("%s: Exposure range coarse :min = %d, max = %d, step = %d",
__FUNCTION__,
desc->coarse_integration_time_min,
integration_max, integration_step);
desc->coarse_integration_time_max_margin = mCapInfo->getCITMaxMargin();
//INFO: fine integration is not supported by v4l2
desc->fine_integration_time_min = 0;
desc->fine_integration_time_max_margin = desc->pixel_periods_per_line;
status = mSensorOp->getVBlank(vBlank);
desc->line_periods_vertical_blanking = vBlank > USHRT_MAX ? USHRT_MAX: vBlank;
LOG2("%s: pixel clock = %f ppl = %d, lpf =%d, int_min = %d, int_max_range %d",
__FUNCTION__,
desc->pixel_clock_freq_mhz,
desc->pixel_periods_per_line,
desc->line_periods_per_field,
desc->coarse_integration_time_min,
desc->coarse_integration_time_max_margin);
return status;
}
/**
* enqueue to message queue parameter setting
*
* \param[in] settings Capture settings
*
* \return status for enqueueing message
*/
status_t SyncManager::setParameters(std::shared_ptr<CaptureUnitSettings> settings)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleSetParams, base::Unretained(this),
base::Passed(std::move(settings)));
mCameraThread.PostTaskAsync<status_t>(FROM_HERE, closure);
return OK;
}
/**
*
* Queue new settings that will be consumed on next SOF
*
* \param[in] msg holding settings
*
* \return OK
*/
status_t SyncManager::handleSetParams(std::shared_ptr<CaptureUnitSettings> settings)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
LOGP("%s add one hold for %p in mCaptureUnitSettingsPool", __FUNCTION__, settings.get());
mQueuedSettings.push_back(std::move(settings));
if (mQueuedSettings.size() > MAX_SETTINGS_QUEUE_SIZE) {
LOGP("%s size>max delete one hold for %p in mCaptureUnitSettingsPool",
__FUNCTION__, mQueuedSettings.begin()->get());
mQueuedSettings.erase(mQueuedSettings.begin());
}
return OK;
}
/**
*
* Set the sensor frame timing calculation width and height
*
* \param[in] width sensor frame timing calculation width
* \param[in] height sensor frame timing calculation height
*
* \return OK
*/
status_t SyncManager::setSensorFT(int width, int height)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
MessageSensorFT msg;
msg.width = width;
msg.height = height;
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleSetSensorFT,
base::Unretained(this), base::Passed(std::move(msg)));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
status_t SyncManager::handleSetSensorFT(MessageSensorFT msg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
status_t status = OK;
int width = msg.width;
int height = msg.height;
if (mSensorOp.get() == nullptr) {
LOGE("SensorHwOp class not initialized");
return UNKNOWN_ERROR;
}
status = mSensorOp->setSensorFT(width, height);
if (status != NO_ERROR) {
LOGE("Failed to set sensor config");
return UNKNOWN_ERROR;
}
return status;
}
/**
* Process work to do on SOF event detection
*
* \param[in] msg holding SOF event data.
*
*
* \return status for work done
*/
status_t SyncManager::handleSOF(MessageFrameEvent msg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
status_t status = OK;
if (!mStarted) {
LOGD("SOF[%d] received while closing- ignoring", msg.exp_id);
return OK;
}
// Poll again
mPollerThread->pollRequest(0, IPU3_EVENT_POLL_TIMEOUT,
(std::vector<std::shared_ptr<cros::V4L2Device>>*) &mDevicesToPoll);
if (CC_UNLIKELY(mQueuedSettings.empty())) {
LOG2("SOF[%d] Arrived and sensor does not have settings queued",
msg.exp_id);
// TODO: this will become an error once we fix capture unit to run at
// sensor rate.
// delete all gain from old previous client request.
mDelayedAGains.clear();
mDelayedDGains.clear();
} else {
mCurrentSettingIdentifier = mQueuedSettings[0]->settingsIdentifier;
ia_aiq_exposure_sensor_parameters &expParams =
*mQueuedSettings[0]->aiqResults.aeResults.exposures[0].sensor_exposure;
LOG2("Applying settings @exp_id %d in Effect @ %d",
msg.exp_id, msg.exp_id + mExposureDelay);
status = applySensorParams(expParams);
if (status != NO_ERROR)
LOGE("Failed to apply sensor parameters.");
int mode = mCapInfo->getSensorTestPatternMode(mQueuedSettings[0]->testPatternMode);
status = mSensorOp->setTestPattern(mode);
CheckError((status != NO_ERROR), status, "@%s, Fail to set test pattern mode = %d [%d]!",
__FUNCTION__, mQueuedSettings[0]->testPatternMode, status);
/**
* Mark the exposure id where this settings should be in effect.
* this is used by the control unit to find the correct settings
* for stats.
* Then remove it from the Q.
*/
mQueuedSettings[0]->inEffectFrom = msg.exp_id + mExposureDelay;
LOGP("%s sof come, delete one hold for %p in mCaptureUnitSettingsPool",
__FUNCTION__, mQueuedSettings.begin()->get());
mQueuedSettings.erase(mQueuedSettings.begin());
}
return status;
}
/**
* Process work to do on EOF event detection
*
* \param[in] msg holding EOF event data.
*
*
* \return status for work done
*/
status_t SyncManager::handleEOF()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
/**
* We are not getting EOF yet, but once we do ...
* TODO: In this case we should check the time before we apply the settings
* to make sure we apply them after blanking.
*/
return OK;
}
/**
* Apply current ae results to sensor
*
* \param[in] expParams sensor exposure parameters to apply
* \param[in] noDelay apply directly sensor parameters
* \return status of IOCTL to sensor AE settings.
*/
status_t SyncManager::applySensorParams(ia_aiq_exposure_sensor_parameters &expParams,
bool noDelay)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
status_t status = OK;
uint16_t aGain, dGain;
uint16_t analog_gain_code_global = expParams.analog_gain_code_global;
uint16_t digital_gain_global = expParams.digital_gain_global;
// Frame duration
status |= mSensorOp->setFrameDuration(expParams.line_length_pixels,
expParams.frame_length_lines);
// Discrete digital gain, seperate total gain = AG x DG
if (mUseDiscreteDg && mCapInfo->mAgMaxRatio && mCapInfo->mAgMultiplier) {
int ag_product, analog_gain_code, analog_gain_divisor;
uint16_t total_gain = expParams.analog_gain_code_global;
uint16_t digital_gain = (total_gain + (mCapInfo->mAgMaxRatio * mCapInfo->mAgMultiplier)
- 1) / (mCapInfo->mAgMaxRatio * mCapInfo->mAgMultiplier);
uint16_t digital_gain_idx;
bool ag_fail = false;
LOG2("%s total gain:%d, target dg:%d", __FUNCTION__, total_gain, digital_gain);
mSensorOp->getDiscreteDg(&digital_gain, &digital_gain_idx);
if (digital_gain == 0) {
LOGE("%s DG==0, wrong, at least 1", __FUNCTION__);
digital_gain = 1;
digital_gain_idx = 0;
}
// total gain = (AG * AgMultiplier) * DG => ag_product * DG
ag_product = total_gain / digital_gain;
// Set DG idx to digital gain, driver will covert it to DG code
digital_gain_global = digital_gain_idx;
/*
* SMIA: AG = (m0*X + c0)/(m1*X + c1), which X = AG code for reg setting.
* => AG*m1*X + AG * c1 = m0 * X + c0 => X= (c0 - AG * c1) / (AG * m1 - m0)
* => X = (AgMultiplier * (c0 - AG * c1)) / (AgMultiplier * (AG * m1 - m0)) for the
* more precise gain code.
*/
analog_gain_divisor = (ag_product * mCapInfo->mSMIAm1) -
(mCapInfo->mAgMultiplier * mCapInfo->mSMIAm0);
if (analog_gain_divisor) {
analog_gain_code = ((mCapInfo->mAgMultiplier * mCapInfo->mSMIAc0) -
(ag_product * mCapInfo->mSMIAc1)) / analog_gain_divisor;
if (analog_gain_code >= 0)
analog_gain_code_global = (uint16_t)analog_gain_code;
else
ag_fail = true;
} else {
ag_fail = true;
}
if (ag_fail)
LOGE("%s, wrong AG, m0 or m1: %d, %d", __FUNCTION__,
mCapInfo->mSMIAm0, mCapInfo->mSMIAm1);
LOG2("%s new AG:%d, DG:%d", __FUNCTION__, analog_gain_code_global, digital_gain_global);
}
// gain
mDelayedAGains.push_back(analog_gain_code_global);
mDelayedDGains.push_back(digital_gain_global);
aGain = mDelayedAGains[0];
dGain = mDelayedDGains[0];
if (mDelayedAGains.size() > mGainDelay) {
mDelayedAGains.erase(mDelayedAGains.begin());
mDelayedDGains.erase(mDelayedDGains.begin());
}
if (mDigiGainOnSensor == false)
dGain = 0;
status |= mSensorOp->setGains(noDelay ? expParams.analog_gain_code_global : aGain,
noDelay ? expParams.digital_gain_global : dGain);
// set exposure at last in order to trigger sensor driver apply all exp settings
status |= mSensorOp->setExposure(expParams.coarse_integration_time,
expParams.fine_integration_time);
return status;
}
/**
* enqueue request to start
*
* \return value of success for enqueueing message
*/
status_t SyncManager::start()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleStart, base::Unretained(this));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
/**
*
* Request start of polling to sensor sync events
*/
status_t SyncManager::handleStart()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
if (mStarted) {
LOGW("SyncManager already started");
return OK;
}
status = initSynchronization();
if (CC_UNLIKELY(status != NO_ERROR)) {
LOGE("Failed to initialize CSI synchronization");
return UNKNOWN_ERROR;
}
if (!mQueuedSettings.empty()) {
ia_aiq_exposure_sensor_parameters &expParams =
*mQueuedSettings[0]->aiqResults.aeResults.exposures[0].sensor_exposure;
LOG1("Applying FIRST settings");
status = applySensorParams(expParams);
if (CC_UNLIKELY(status != NO_ERROR)) {
LOGE("Failed to apply sensor parameters.");
}
/**
* Mark the exposure id where this settings should be in effect
*/
mQueuedSettings[0]->inEffectFrom = 0;
mQueuedSettings.erase(mQueuedSettings.begin());
}
mStarted = true;
mPollErrorTimes = 0;
// Start to poll
mPollerThread->pollRequest(0, IPU3_EVENT_POLL_TIMEOUT,
(std::vector<std::shared_ptr<cros::V4L2Device>>*) &mDevicesToPoll);
return OK;
}
/**
* enqueue requeue request for isStarted
*
* \return value of success for enqueueing message
*/
status_t SyncManager::isStarted(bool &started)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
MessageIsStarted msg;
msg.value = &started;
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleIsStarted,
base::Unretained(this), base::Passed(std::move(msg)));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
/**
* tells if the event is taken into account or not.
*
* \return OK
*/
status_t SyncManager::handleIsStarted(MessageIsStarted msg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
*msg.value = mStarted;
return OK;
}
/**
* enqueue request to stop
*
* \return value of success for enqueueing message
*/
status_t SyncManager::stop()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleStop, base::Unretained(this));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
/**
* empty queues and request stop.
*
* De initializes synchronization mechanism.
*
* \return OK
*/
status_t SyncManager::handleStop()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
if (mStarted) {
status = mPollerThread->flush(true);
if (status != NO_ERROR)
LOGE("could not flush Sensor pollerThread");
mStarted = false;
}
status = deInitSynchronization();
return status;
}
/**
* enqueue request to flush the queue of polling requests
* synchronous call
*
* \return flush status from Pollerthread.
*/
status_t SyncManager::flush()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleFlush, base::Unretained(this));
mCameraThread.PostTaskSync<status_t>(FROM_HERE, closure, &status);
return status;
}
/**
* empty queues and request of sensor settings
*/
status_t SyncManager::handleFlush()
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL1, LOG_TAG);
status_t status = OK;
if (mPollerThread)
status = mPollerThread->flush(true);
mQueuedSettings.clear();
return status;
}
int SyncManager::getCurrentCameraId(void)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
return mCameraId;
}
/**
* gets notification everytime an event is triggered
* in the PollerThread SyncManager is subscribed.
*
* \param[in] pollEventMsg containing information on poll data
*
* \return status on parsing poll data validity
*/
status_t SyncManager::notifyPollEvent(PollEventMessage *pollEventMsg)
{
HAL_TRACE_CALL(CAMERA_DEBUG_LOG_LEVEL2, LOG_TAG);
struct v4l2_event event;
MessageFrameEvent msg;
status_t status = OK;
CLEAR(event);
if (pollEventMsg == nullptr || pollEventMsg->data.activeDevices == nullptr)
return BAD_VALUE;
if (pollEventMsg->id == POLL_EVENT_ID_ERROR) {
LOGE("Polling Failed for frame id: %d, ret was %d",
pollEventMsg->data.reqId,
pollEventMsg->data.pollStatus);
// Poll again if poll error times is less than the threshold.
if (mPollErrorTimes++ < POLL_REQUEST_TRY_TIMES) {
status = mPollerThread->pollRequest(0, IPU3_EVENT_POLL_TIMEOUT,
(std::vector<std::shared_ptr<cros::V4L2Device>>*) &mDevicesToPoll);
return status;
} else if (mErrCb) {
// return a error message if poll failed happens 5 times in succession
mErrCb->deviceError();
return UNKNOWN_ERROR;
}
} else if (pollEventMsg->data.activeDevices->empty()) {
LOG1("%s Polling from Flush: succeeded", __FUNCTION__);
// TODO flush actions.
} else {
//cannot be anything else than event if ending up here.
do {
mPollErrorTimes = 0;
status = mIsysReceiverSubdev->DequeueEvent(&event);
if (status < 0) {
LOGE("dequeueing event failed");
break;
}
msg.timestamp.tv_sec = event.timestamp.tv_sec;
msg.timestamp.tv_usec = (event.timestamp.tv_nsec / 1000);
msg.exp_id = event.u.frame_sync.frame_sequence;
msg.reqId = pollEventMsg->data.reqId;
if (mFrameSyncSource == FRAME_SYNC_SOF) {
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleSOF,
base::Unretained(this),
base::Passed(std::move(msg)));
mCameraThread.PostTaskAsync<status_t>(FROM_HERE, closure);
} else if (mFrameSyncSource == FRAME_SYNC_EOF) {
base::Callback<status_t()> closure =
base::Bind(&SyncManager::handleEOF,
base::Unretained(this));
mCameraThread.PostTaskAsync<status_t>(FROM_HERE, closure);
} else {
LOGE("Unhandled frame sync source : %d", mFrameSyncSource);
}
LOG2("%s: EVENT, MessageId: %d, activedev: %lu, reqId: %d, seq: %u, frame sequence: %u",
__FUNCTION__, pollEventMsg->id, pollEventMsg->data.activeDevices->size(),
pollEventMsg->data.reqId, event.sequence, event.u.frame_sync.frame_sequence);
// notify SOF event
mSofListener->notifySofEvent(event.u.frame_sync.frame_sequence, event.timestamp);
} while (event.pending > 0);
}
return OK;
}
/**
* Open the sync sub-device (CSI receiver).
* Subscribe to SOF events.
* Create and initialize the poller thread to poll SOF events from it.
*
* \return OK
* \return UNKNOWN_ERROR If we could not find the CSI receiver sub-device.
* \return NO_DATA If we could not allocate the PollerThread
*/
status_t SyncManager::initSynchronization()
{
status_t status = OK;
mDevicesToPoll.clear();
/*
* find the sub-device that represent the csi receiver, open it and keep a
* reference in mIsysReceiverSubdev
*/
status = setMediaEntity("csi_receiver", SUBDEV_ISYSRECEIVER);
if (CC_UNLIKELY(status != NO_ERROR)) {
LOGE("Cannot find the isys csi-receiver");
return UNKNOWN_ERROR;
}
if (CC_UNLIKELY(mIsysReceiverSubdev == nullptr)) {
LOGE("ISYS Receiver Sub device to poll is nullptr");
return UNKNOWN_ERROR;
}
/*
* SOF is checked first and preferred to EOF, because it provides a better
* timing on how to apply the parameters and doesn't include any
* calculation.
*/
status = mIsysReceiverSubdev->SubscribeEvent(FRAME_SYNC_SOF);
if (status != NO_ERROR) {
LOG1("SOF event not supported on ISYS receiver node, trying EOF");
status = mIsysReceiverSubdev->SubscribeEvent(FRAME_SYNC_EOF);
if (status != NO_ERROR) {
LOGE("EOF event not existing on ISYS receiver node, FAIL");
return status;
}
mFrameSyncSource = FRAME_SYNC_EOF;
LOG1("%s: Using EOF event", __FUNCTION__);
} else {
mFrameSyncSource = FRAME_SYNC_SOF;
LOG1("%s: Using SOF event", __FUNCTION__);
}
mDevicesToPoll.push_back(mIsysReceiverSubdev);
mPollerThread.reset(new PollerThread("SensorPollerThread"));
status = mPollerThread->init((std::vector<std::shared_ptr<cros::V4L2Device>>&)mDevicesToPoll,
this, POLLPRI | POLLIN | POLLERR, false);
if (status != NO_ERROR)
LOGE("Failed to init PollerThread in sync manager");
return status;
}
/**
*
* Un-subscribe from the events
* Delete the poller thread.
* Clear list of devices to poll.
*
* NOTE: It assumes that the poller thread is stopped.
* \return OK
*/
status_t SyncManager::deInitSynchronization()
{
if (mIsysReceiverSubdev) {
if (mFrameSyncSource != FRAME_SYNC_NA)
mIsysReceiverSubdev->UnsubscribeEvent(mFrameSyncSource);
mIsysReceiverSubdev->Close();
mIsysReceiverSubdev.reset();
mFrameSyncSource = FRAME_SYNC_NA;
}
if (mPollerThread)
mPollerThread->requestExitAndWait();
mPollerThread.reset();
mDevicesToPoll.clear();
return OK;
}
} // namespace intel
} // namespace cros
| 32.17998 | 100 | 0.640797 | strassek |
018e76deee8bdabaf65f1b68d555a51946186eaa | 1,508 | cpp | C++ | paxos/acceptor.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 26 | 2020-01-31T18:12:44.000Z | 2022-02-07T01:46:07.000Z | paxos/acceptor.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 17 | 2020-01-30T20:40:35.000Z | 2021-12-22T18:43:21.000Z | paxos/acceptor.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 6 | 2019-12-24T15:30:45.000Z | 2021-07-06T19:47:30.000Z | #include "paxos/acceptor.h"
#include "paxos/simulated_multi_paxos.h"
namespace slog {
using internal::Envelope;
using internal::Request;
using internal::Response;
Acceptor::Acceptor(SimulatedMultiPaxos& sender) : sender_(sender), ballot_(0) {}
void Acceptor::HandleRequest(const internal::Envelope& req) {
switch (req.request().type_case()) {
case Request::TypeCase::kPaxosAccept:
ProcessAcceptRequest(req.request().paxos_accept(), req.from());
break;
case Request::TypeCase::kPaxosCommit:
ProcessCommitRequest(req.request().paxos_commit(), req.from());
break;
default:
break;
}
}
void Acceptor::ProcessAcceptRequest(const internal::PaxosAcceptRequest& req, MachineId from_machine_id) {
if (req.ballot() < ballot_) {
return;
}
ballot_ = req.ballot();
auto env = sender_.NewEnvelope();
auto accept_response = env->mutable_response()->mutable_paxos_accept();
accept_response->set_ballot(ballot_);
accept_response->set_slot(req.slot());
sender_.SendSameChannel(move(env), from_machine_id);
}
void Acceptor::ProcessCommitRequest(const internal::PaxosCommitRequest& req, MachineId from_machine_id) {
// TODO: If leader election is implemented, this is where we erase
// memory about an accepted value
auto env = sender_.NewEnvelope();
auto commit_response = env->mutable_response()->mutable_paxos_commit();
commit_response->set_slot(req.slot());
sender_.SendSameChannel(move(env), from_machine_id);
}
} // namespace slog | 32.085106 | 105 | 0.732095 | plsmaop |
018f1dd975cb089e6fd899c8cf8bb936aebc7ab4 | 24,067 | cpp | C++ | mplapack/reference/Rlaqtr.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 26 | 2019-03-20T04:06:03.000Z | 2022-03-02T10:21:01.000Z | mplapack/reference/Rlaqtr.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2019-03-04T03:32:41.000Z | 2021-12-01T07:47:25.000Z | mplapack/reference/Rlaqtr.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2019-03-09T17:50:26.000Z | 2022-03-10T19:46:20.000Z | /*
* Copyright (c) 2008-2021
* Nakata, Maho
* 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 AUTHOR 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 AUTHOR 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 <mpblas.h>
#include <mplapack.h>
void Rlaqtr(bool const ltran, bool const lreal, INTEGER const n, REAL *t, INTEGER const ldt, REAL *b, REAL const w, REAL &scale, REAL *x, REAL *work, INTEGER &info) {
bool notran = false;
REAL eps = 0.0;
REAL smlnum = 0.0;
const REAL one = 1.0;
REAL bignum = 0.0;
REAL d[4];
INTEGER ldd = 2;
REAL xnorm = 0.0;
REAL smin = 0.0;
const REAL zero = 0.0;
INTEGER j = 0;
INTEGER i = 0;
INTEGER n2 = 0;
INTEGER n1 = 0;
INTEGER k = 0;
REAL xmax = 0.0;
INTEGER jnext = 0;
INTEGER j1 = 0;
INTEGER j2 = 0;
REAL xj = 0.0;
REAL tjj = 0.0;
REAL tmp = 0.0;
REAL rec = 0.0;
REAL v[4];
INTEGER ldv = 2;
REAL scaloc = 0.0;
INTEGER ierr = 0;
REAL sminw = 0.0;
REAL z = 0.0;
REAL sr = 0.0;
REAL si = 0.0;
//
// -- LAPACK auxiliary routine --
// -- LAPACK is a software package provided by Univ. of Tennessee, --
// -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
//
// .. Scalar Arguments ..
// ..
// .. Array Arguments ..
// ..
//
// =====================================================================
//
// .. Parameters ..
// ..
// .. Local Scalars ..
// ..
// .. Local Arrays ..
// ..
// .. External Functions ..
// ..
// .. External Subroutines ..
// ..
// .. Intrinsic Functions ..
// ..
// .. Executable Statements ..
//
// Do not test the input parameters for errors
//
notran = !ltran;
info = 0;
//
// Quick return if possible
//
if (n == 0) {
return;
}
//
// Set constants to control overflow
//
eps = Rlamch("P");
smlnum = Rlamch("S") / eps;
bignum = one / smlnum;
//
xnorm = Rlange("M", n, n, t, ldt, d);
if (!lreal) {
xnorm = max({xnorm, REAL(abs(w)), REAL(Rlange("M", n, 1, b, n, d))});
}
smin = max(smlnum, REAL(eps * xnorm));
//
// Compute 1-norm of each column of strictly upper triangular
// part of T to control overflow in triangular solver.
//
work[1 - 1] = zero;
for (j = 2; j <= n; j = j + 1) {
work[j - 1] = Rasum(j - 1, &t[(j - 1) * ldt], 1);
}
//
if (!lreal) {
for (i = 2; i <= n; i = i + 1) {
work[i - 1] += abs(b[i - 1]);
}
}
//
n2 = 2 * n;
n1 = n;
if (!lreal) {
n1 = n2;
}
k = iRamax(n1, x, 1);
xmax = abs(x[k - 1]);
scale = one;
//
if (xmax > bignum) {
scale = bignum / xmax;
Rscal(n1, scale, x, 1);
xmax = bignum;
}
//
if (lreal) {
//
if (notran) {
//
// Solve T*p = scale*c
//
jnext = n;
for (j = n; j >= 1; j = j - 1) {
if (j > jnext) {
goto statement_30;
}
j1 = j;
j2 = j;
jnext = j - 1;
if (j > 1) {
if (t[(j - 1) + ((j - 1) - 1) * ldt] != zero) {
j1 = j - 1;
jnext = j - 2;
}
}
//
if (j1 == j2) {
//
// Meet 1 by 1 diagonal block
//
// Scale to avoid overflow when computing
// x(j) = b(j)/T(j,j)
//
xj = abs(x[j1 - 1]);
tjj = abs(t[(j1 - 1) + (j1 - 1) * ldt]);
tmp = t[(j1 - 1) + (j1 - 1) * ldt];
if (tjj < smin) {
tmp = smin;
tjj = smin;
info = 1;
}
//
if (xj == zero) {
goto statement_30;
}
//
if (tjj < one) {
if (xj > bignum * tjj) {
rec = one / xj;
Rscal(n, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
x[j1 - 1] = x[j1 - 1] / tmp;
xj = abs(x[j1 - 1]);
//
// Scale x if necessary to avoid overflow when adding a
// multiple of column j1 of T.
//
if (xj > one) {
rec = one / xj;
if (work[j1 - 1] > (bignum - xmax) * rec) {
Rscal(n, rec, x, 1);
scale = scale * rec;
}
}
if (j1 > 1) {
Raxpy(j1 - 1, -x[j1 - 1], &t[(j1 - 1) * ldt], 1, x, 1);
k = iRamax(j1 - 1, x, 1);
xmax = abs(x[k - 1]);
}
//
} else {
//
// Meet 2 by 2 diagonal block
//
// Call 2 by 2 linear system solve, to take
// care of possible overflow by scaling factor.
//
d[(1 - 1)] = x[j1 - 1];
d[(2 - 1)] = x[j2 - 1];
Rlaln2(false, 2, 1, smin, one, &t[(j1 - 1) + (j1 - 1) * ldt], ldt, one, one, d, 2, zero, zero, v, 2, scaloc, xnorm, ierr);
if (ierr != 0) {
info = 2;
}
//
if (scaloc != one) {
Rscal(n, scaloc, x, 1);
scale = scale * scaloc;
}
x[j1 - 1] = v[(1 - 1)];
x[j2 - 1] = v[(2 - 1)];
//
// Scale V(1,1) (= X(J1)) and/or V(2,1) (=X(J2))
// to avoid overflow in updating right-hand side.
//
xj = max(abs(v[(1 - 1)]), abs(v[(2 - 1)]));
if (xj > one) {
rec = one / xj;
if (max(work[j1 - 1], work[j2 - 1]) > (bignum - xmax) * rec) {
Rscal(n, rec, x, 1);
scale = scale * rec;
}
}
//
// Update right-hand side
//
if (j1 > 1) {
Raxpy(j1 - 1, -x[j1 - 1], &t[(j1 - 1) * ldt], 1, x, 1);
Raxpy(j1 - 1, -x[j2 - 1], &t[(j2 - 1) * ldt], 1, x, 1);
k = iRamax(j1 - 1, x, 1);
xmax = abs(x[k - 1]);
}
//
}
//
statement_30:;
}
//
} else {
//
// Solve T**T*p = scale*c
//
jnext = 1;
for (j = 1; j <= n; j = j + 1) {
if (j < jnext) {
goto statement_40;
}
j1 = j;
j2 = j;
jnext = j + 1;
if (j < n) {
if (t[((j + 1) - 1) + (j - 1) * ldt] != zero) {
j2 = j + 1;
jnext = j + 2;
}
}
//
if (j1 == j2) {
//
// 1 by 1 diagonal block
//
// Scale if necessary to avoid overflow in forming the
// right-hand side element by inner product.
//
xj = abs(x[j1 - 1]);
if (xmax > one) {
rec = one / xmax;
if (work[j1 - 1] > (bignum - xj) * rec) {
Rscal(n, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
//
x[j1 - 1] = x[j1 - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, x, 1);
//
xj = abs(x[j1 - 1]);
tjj = abs(t[(j1 - 1) + (j1 - 1) * ldt]);
tmp = t[(j1 - 1) + (j1 - 1) * ldt];
if (tjj < smin) {
tmp = smin;
tjj = smin;
info = 1;
}
//
if (tjj < one) {
if (xj > bignum * tjj) {
rec = one / xj;
Rscal(n, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
x[j1 - 1] = x[j1 - 1] / tmp;
xmax = max(xmax, REAL(abs(x[j1 - 1])));
//
} else {
//
// 2 by 2 diagonal block
//
// Scale if necessary to avoid overflow in forming the
// right-hand side elements by inner product.
//
xj = max(abs(x[j1 - 1]), abs(x[j2 - 1]));
if (xmax > one) {
rec = one / xmax;
if (max(work[j2 - 1], work[j1 - 1]) > (bignum - xj) * rec) {
Rscal(n, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
//
d[(1 - 1)] = x[j1 - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, x, 1);
d[(2 - 1)] = x[j2 - 1] - Rdot(j1 - 1, &t[(j2 - 1) * ldt], 1, x, 1);
//
Rlaln2(true, 2, 1, smin, one, &t[(j1 - 1) + (j1 - 1) * ldt], ldt, one, one, d, 2, zero, zero, v, 2, scaloc, xnorm, ierr);
if (ierr != 0) {
info = 2;
}
//
if (scaloc != one) {
Rscal(n, scaloc, x, 1);
scale = scale * scaloc;
}
x[j1 - 1] = v[(1 - 1)];
x[j2 - 1] = v[(2 - 1)];
xmax = max({REAL(abs(x[j1 - 1])), REAL(abs(x[j2 - 1])), xmax});
//
}
statement_40:;
}
}
//
} else {
//
sminw = max(REAL(eps * abs(w)), smin);
if (notran) {
//
// Solve (T + iB)*(p+iq) = c+id
//
jnext = n;
for (j = n; j >= 1; j = j - 1) {
if (j > jnext) {
goto statement_70;
}
j1 = j;
j2 = j;
jnext = j - 1;
if (j > 1) {
if (t[(j - 1) + ((j - 1) - 1) * ldt] != zero) {
j1 = j - 1;
jnext = j - 2;
}
}
//
if (j1 == j2) {
//
// 1 by 1 diagonal block
//
// Scale if necessary to avoid overflow in division
//
z = w;
if (j1 == 1) {
z = b[1 - 1];
}
xj = abs(x[j1 - 1]) + abs(x[(n + j1) - 1]);
tjj = abs(t[(j1 - 1) + (j1 - 1) * ldt]) + abs(z);
tmp = t[(j1 - 1) + (j1 - 1) * ldt];
if (tjj < sminw) {
tmp = sminw;
tjj = sminw;
info = 1;
}
//
if (xj == zero) {
goto statement_70;
}
//
if (tjj < one) {
if (xj > bignum * tjj) {
rec = one / xj;
Rscal(n2, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
Rladiv(x[j1 - 1], x[(n + j1) - 1], tmp, z, sr, si);
x[j1 - 1] = sr;
x[(n + j1) - 1] = si;
xj = abs(x[j1 - 1]) + abs(x[(n + j1) - 1]);
//
// Scale x if necessary to avoid overflow when adding a
// multiple of column j1 of T.
//
if (xj > one) {
rec = one / xj;
if (work[j1 - 1] > (bignum - xmax) * rec) {
Rscal(n2, rec, x, 1);
scale = scale * rec;
}
}
//
if (j1 > 1) {
Raxpy(j1 - 1, -x[j1 - 1], &t[(j1 - 1) * ldt], 1, x, 1);
Raxpy(j1 - 1, -x[(n + j1) - 1], &t[(j1 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
//
x[1 - 1] += b[j1 - 1] * x[(n + j1) - 1];
x[(n + 1) - 1] = x[(n + 1) - 1] - b[j1 - 1] * x[j1 - 1];
//
xmax = zero;
for (k = 1; k <= j1 - 1; k = k + 1) {
xmax = max(xmax, REAL(abs(x[k - 1]) + abs(x[(k + n) - 1])));
}
}
//
} else {
//
// Meet 2 by 2 diagonal block
//
d[(1 - 1)] = x[j1 - 1];
d[(2 - 1)] = x[j2 - 1];
d[(2 - 1) * ldd] = x[(n + j1) - 1];
d[(2 - 1) + (2 - 1) * ldd] = x[(n + j2) - 1];
Rlaln2(false, 2, 2, sminw, one, &t[(j1 - 1) + (j1 - 1) * ldt], ldt, one, one, d, 2, zero, -w, v, 2, scaloc, xnorm, ierr);
if (ierr != 0) {
info = 2;
}
//
if (scaloc != one) {
Rscal(2 * n, scaloc, x, 1);
scale = scaloc * scale;
}
x[j1 - 1] = v[(1 - 1)];
x[j2 - 1] = v[(2 - 1)];
x[(n + j1) - 1] = v[(2 - 1) * ldv];
x[(n + j2) - 1] = v[(2 - 1) + (2 - 1) * ldv];
//
// Scale X(J1), .... to avoid overflow in
// updating right hand side.
//
xj = max(abs(v[(1 - 1)]) + abs(v[(2 - 1) * ldv]), abs(v[(2 - 1)]) + abs(v[(2 - 1) + (2 - 1) * ldv]));
if (xj > one) {
rec = one / xj;
if (max(work[j1 - 1], work[j2 - 1]) > (bignum - xmax) * rec) {
Rscal(n2, rec, x, 1);
scale = scale * rec;
}
}
//
// Update the right-hand side.
//
if (j1 > 1) {
Raxpy(j1 - 1, -x[j1 - 1], &t[(j1 - 1) * ldt], 1, x, 1);
Raxpy(j1 - 1, -x[j2 - 1], &t[(j2 - 1) * ldt], 1, x, 1);
//
Raxpy(j1 - 1, -x[(n + j1) - 1], &t[(j1 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
Raxpy(j1 - 1, -x[(n + j2) - 1], &t[(j2 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
//
x[1 - 1] += b[j1 - 1] * x[(n + j1) - 1] + b[j2 - 1] * x[(n + j2) - 1];
x[(n + 1) - 1] = x[(n + 1) - 1] - b[j1 - 1] * x[j1 - 1] - b[j2 - 1] * x[j2 - 1];
//
xmax = zero;
for (k = 1; k <= j1 - 1; k = k + 1) {
xmax = max(REAL(abs(x[k - 1]) + abs(x[(k + n) - 1])), xmax);
}
}
//
}
statement_70:;
}
//
} else {
//
// Solve (T + iB)**T*(p+iq) = c+id
//
jnext = 1;
for (j = 1; j <= n; j = j + 1) {
if (j < jnext) {
goto statement_80;
}
j1 = j;
j2 = j;
jnext = j + 1;
if (j < n) {
if (t[((j + 1) - 1) + (j - 1) * ldt] != zero) {
j2 = j + 1;
jnext = j + 2;
}
}
//
if (j1 == j2) {
//
// 1 by 1 diagonal block
//
// Scale if necessary to avoid overflow in forming the
// right-hand side element by inner product.
//
xj = abs(x[j1 - 1]) + abs(x[(j1 + n) - 1]);
if (xmax > one) {
rec = one / xmax;
if (work[j1 - 1] > (bignum - xj) * rec) {
Rscal(n2, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
//
x[j1 - 1] = x[j1 - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, x, 1);
x[(n + j1) - 1] = x[(n + j1) - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
if (j1 > 1) {
x[j1 - 1] = x[j1 - 1] - b[j1 - 1] * x[(n + 1) - 1];
x[(n + j1) - 1] += b[j1 - 1] * x[1 - 1];
}
xj = abs(x[j1 - 1]) + abs(x[(j1 + n) - 1]);
//
z = w;
if (j1 == 1) {
z = b[1 - 1];
}
//
// Scale if necessary to avoid overflow in
// complex division
//
tjj = abs(t[(j1 - 1) + (j1 - 1) * ldt]) + abs(z);
tmp = t[(j1 - 1) + (j1 - 1) * ldt];
if (tjj < sminw) {
tmp = sminw;
tjj = sminw;
info = 1;
}
//
if (tjj < one) {
if (xj > bignum * tjj) {
rec = one / xj;
Rscal(n2, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
Rladiv(x[j1 - 1], x[(n + j1) - 1], tmp, -z, sr, si);
x[j1 - 1] = sr;
x[(j1 + n) - 1] = si;
xmax = max(REAL(abs(x[j1 - 1]) + abs(x[(j1 + n) - 1])), xmax);
//
} else {
//
// 2 by 2 diagonal block
//
// Scale if necessary to avoid overflow in forming the
// right-hand side element by inner product.
//
xj = max(abs(x[j1 - 1]) + abs(x[(n + j1) - 1]), abs(x[j2 - 1]) + abs(x[(n + j2) - 1]));
if (xmax > one) {
rec = one / xmax;
if (max(work[j1 - 1], work[j2 - 1]) > (bignum - xj) / xmax) {
Rscal(n2, rec, x, 1);
scale = scale * rec;
xmax = xmax * rec;
}
}
//
d[(1 - 1)] = x[j1 - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, x, 1);
d[(2 - 1)] = x[j2 - 1] - Rdot(j1 - 1, &t[(j2 - 1) * ldt], 1, x, 1);
d[(2 - 1) * ldd] = x[(n + j1) - 1] - Rdot(j1 - 1, &t[(j1 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
d[(2 - 1) + (2 - 1) * ldd] = x[(n + j2) - 1] - Rdot(j1 - 1, &t[(j2 - 1) * ldt], 1, &x[(n + 1) - 1], 1);
d[(1 - 1)] = d[(1 - 1)] - b[j1 - 1] * x[(n + 1) - 1];
d[(2 - 1)] = d[(2 - 1)] - b[j2 - 1] * x[(n + 1) - 1];
d[(2 - 1) * ldd] += b[j1 - 1] * x[1 - 1];
d[(2 - 1) + (2 - 1) * ldd] += b[j2 - 1] * x[1 - 1];
//
Rlaln2(true, 2, 2, sminw, one, &t[(j1 - 1) + (j1 - 1) * ldt], ldt, one, one, d, 2, zero, w, v, 2, scaloc, xnorm, ierr);
if (ierr != 0) {
info = 2;
}
//
if (scaloc != one) {
Rscal(n2, scaloc, x, 1);
scale = scaloc * scale;
}
x[j1 - 1] = v[(1 - 1)];
x[j2 - 1] = v[(2 - 1)];
x[(n + j1) - 1] = v[(2 - 1) * ldv];
x[(n + j2) - 1] = v[(2 - 1) + (2 - 1) * ldv];
xmax = max({REAL(abs(x[j1 - 1]) + abs(x[(n + j1) - 1])), REAL(abs(x[j2 - 1]) + abs(x[(n + j2) - 1])), xmax});
//
}
//
statement_80:;
}
//
}
//
}
//
// End of Rlaqtr
//
}
| 39.006483 | 166 | 0.279636 | Ndersam |
018f628d208b152da9e47284a479d912d22f2f03 | 453 | cpp | C++ | src/platform.cpp | matias310396/sonic | 0bfbdd02ad1f1bff04b74b913199b9b7bc45c343 | [
"MIT"
] | null | null | null | src/platform.cpp | matias310396/sonic | 0bfbdd02ad1f1bff04b74b913199b9b7bc45c343 | [
"MIT"
] | null | null | null | src/platform.cpp | matias310396/sonic | 0bfbdd02ad1f1bff04b74b913199b9b7bc45c343 | [
"MIT"
] | null | null | null | #include "../include/platform.hpp"
using namespace engine;
void Platform::on_event(GameEvent game_event){
std::string event_name = game_event.game_event_name;
Image* platform_image = dynamic_cast<Image*>(images[0]);
if(event_name == "MOVE_LEFT" && !GameObject::on_limit_of_level){
position.first += 10;
}else if(event_name == "MOVE_RIGHT" && !GameObject::on_limit_of_level){
position.first -= 10;
}
}
void Platform::update(){}
| 23.842105 | 73 | 0.706402 | matias310396 |
019228dfe8b5d4b0bb0029b7bcac44bbf217b8af | 893 | cpp | C++ | 1237/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | 1237/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | 1237/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int T;
scanf("%d", &T);
while(T--){
int D, Q, L, H;
string M;
vector<pair<string, pair<int, int>>> db;
scanf("%d", &D);
while(D--){
cin >> M >> L >> H;
db.push_back(make_pair(M, make_pair(L,H)));
}
/*for(int i = 0; i < db.size(); i++){
cout << db[i].first << " " << db[i].second.first << " " << db[i].second.second << "\n";
}*/
scanf("%d", &Q);
int q;
while(Q--){
int ans, ans_count = 0;
scanf("%d", &q);
for(int i = 0; i < db.size(); i++){
if((q >= db[i].second.first) && (q <= db[i].second.second)){
ans_count++;
ans = i;
if(ans_count > 1)
break;
}
}
if(ans_count == 1){
printf("%s\n", db[ans].first.c_str());
} else{
printf("UNDETERMINED\n");
}
}
if(T != 0)
printf("\n");
}
return 0;
}
| 16.537037 | 91 | 0.469205 | sabingoyek |
0194c378e1a5adc0f8e2c33bc437e8560f28e74b | 314 | hpp | C++ | include/chip8/memory/stack.hpp | lance21/chip8 | 6797755845b73ee1a6be5c7b3970cb1c271a114b | [
"MIT"
] | null | null | null | include/chip8/memory/stack.hpp | lance21/chip8 | 6797755845b73ee1a6be5c7b3970cb1c271a114b | [
"MIT"
] | null | null | null | include/chip8/memory/stack.hpp | lance21/chip8 | 6797755845b73ee1a6be5c7b3970cb1c271a114b | [
"MIT"
] | null | null | null | #ifndef STACK_HPP
#define STACK_HPP
#include <cstdint>
namespace chip8 {
namespace memory {
class Stack {
private:
uint8_t stack_pointer_;
uint16_t stack_[16];
public:
Stack();
uint8_t getStackPointer() const;
uint16_t pop();
void push( const uint16_t return_address);
};
}
}
#endif
| 12.076923 | 46 | 0.687898 | lance21 |
019559d84072d03e66c173fa38129cb1dbd03e9c | 2,306 | cpp | C++ | src/masking.cpp | davidchall/ipaddress | 3a2a84e245eaf73aadfe0bf3692af27a622bc220 | [
"MIT"
] | 23 | 2020-03-06T01:26:49.000Z | 2022-03-17T11:09:58.000Z | src/masking.cpp | davidchall/ipaddress | 3a2a84e245eaf73aadfe0bf3692af27a622bc220 | [
"MIT"
] | 41 | 2020-02-09T18:34:09.000Z | 2022-01-14T05:18:07.000Z | src/masking.cpp | davidchall/ipaddress | 3a2a84e245eaf73aadfe0bf3692af27a622bc220 | [
"MIT"
] | 2 | 2020-03-12T14:45:37.000Z | 2020-04-08T12:43:11.000Z | #include <Rcpp.h>
#include <ipaddress.h>
#include <ipaddress/to_string.h>
#include "warn.h"
using namespace Rcpp;
using namespace ipaddress;
// [[Rcpp::export]]
List wrap_netmask(IntegerVector in_prefix_length, LogicalVector in_is_ipv6) {
// initialize vectors
std::size_t vsize = in_is_ipv6.size();
std::vector<IpAddress> output(vsize);
if (static_cast<std::size_t>(in_prefix_length.size()) != vsize) {
stop("Prefix length and IPv6 status must have same length"); // # nocov
}
for (std::size_t i=0; i<vsize; ++i) {
if (i % 10000 == 0) {
checkUserInterrupt();
}
if (in_is_ipv6[i] == NA_LOGICAL || in_prefix_length[i] == NA_INTEGER) {
output[i] = IpAddress::make_na();
} else {
output[i] = prefix_to_netmask(in_prefix_length[i], in_is_ipv6[i]);
}
}
return encode_addresses(output);
}
// [[Rcpp::export]]
List wrap_hostmask(IntegerVector in_prefix_length, LogicalVector in_is_ipv6) {
// initialize vectors
std::size_t vsize = in_is_ipv6.size();
std::vector<IpAddress> output(vsize);
if (static_cast<std::size_t>(in_prefix_length.size()) != vsize) {
stop("Prefix length and IPv6 status must have same length"); // # nocov
}
for (std::size_t i=0; i<vsize; ++i) {
if (i % 10000 == 0) {
checkUserInterrupt();
}
if (in_is_ipv6[i] == NA_LOGICAL || in_prefix_length[i] == NA_INTEGER) {
output[i] = IpAddress::make_na();
} else {
output[i] = prefix_to_hostmask(in_prefix_length[i], in_is_ipv6[i]);
}
}
return encode_addresses(output);
}
// [[Rcpp::export]]
IntegerVector wrap_prefix_from_mask(List address_r) {
std::vector<IpAddress> address = decode_addresses(address_r);
// initialize vectors
std::size_t vsize = address.size();
IntegerVector output(vsize);
for (std::size_t i=0; i<vsize; ++i) {
if (i % 10000 == 0) {
checkUserInterrupt();
}
if (address[i].is_na()) {
output[i] = NA_INTEGER;
} else {
int prefix = netmask_to_prefix(address[i]);
if (prefix < 0) {
prefix = hostmask_to_prefix(address[i]);
}
if (prefix < 0) {
warnOnRow(i, to_string(address[i]), "invalid netmask/hostmask");
output[i] = NA_INTEGER;
} else {
output[i] = prefix;
}
}
}
return output;
}
| 24.795699 | 78 | 0.632264 | davidchall |
019585181381bdc8accf87cc69e80e64ac949e34 | 1,069 | hpp | C++ | Lib/Chip/ATSAM3N0B.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | Lib/Chip/ATSAM3N0B.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | Lib/Chip/ATSAM3N0B.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cstdint>
#include <Chip/CM3/Atmel/ATSAM3N0B/SPI.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/TC0.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/TWI0.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/TWI1.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/PWM.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/USART0.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/USART1.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/ADC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/DACC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/MATRIX.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/PMC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/UART0.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/CHIPID.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/UART1.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/EFC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/PIOA.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/PIOB.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/RSTC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/SUPC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/RTT.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/WDT.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/RTC.hpp>
#include <Chip/CM3/Atmel/ATSAM3N0B/GPBR.hpp>
| 41.115385 | 46 | 0.776427 | operativeF |
01996a166cc70b0e8d688b1063eb8988ea976732 | 3,441 | cpp | C++ | sharedcpp/libeditcore/gpu_texture_cache.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 3 | 2020-11-11T04:08:19.000Z | 2021-04-27T01:07:42.000Z | sharedcpp/libeditcore/gpu_texture_cache.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 2 | 2020-09-22T20:42:16.000Z | 2020-11-11T04:08:57.000Z | sharedcpp/libeditcore/gpu_texture_cache.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 11 | 2020-07-04T03:03:18.000Z | 2022-03-17T10:19:19.000Z | #include "./gpu_texture_cache.h"
#define LOG_TAG "GPUTextureCache"
/******************* GPUTextureCache class *******************/
GPUTextureCache::GPUTextureCache() {
}
GPUTextureCache::~GPUTextureCache() {
}
//初始化静态成员
GPUTextureCache* GPUTextureCache::instance = new GPUTextureCache();
GPUTextureCache* GPUTextureCache::GetInstance() {
return instance;
}
void GPUTextureCache::destroy() {
map<string, list<GPUTexture*> >::iterator queueItor;
for (queueItor = textureQueueCache.begin(); queueItor != textureQueueCache.end(); ++queueItor) {
list<GPUTexture*>::iterator texItor;
for (texItor = (queueItor->second).begin(); texItor != (queueItor->second).end(); ++texItor) {
GPUTexture* texture = *texItor;
texture->dealloc();
delete texture;
}
(queueItor->second).clear();
}
textureQueueCache.clear();
}
GPUTexture* GPUTextureCache::fetchTexture(int width, int height) {
GPUTexture* texture = NULL;
string queueKey = getQueueKey(width, height);
map<string, list<GPUTexture*> >::iterator itor;
itor = textureQueueCache.find(queueKey);
if (itor != textureQueueCache.end()) {
//找到了
if ((itor->second).size() > 0) {
texture = (itor->second).front();
(itor->second).pop_front();
} else {
texture = new GPUTexture();
texture->init(width, height);
}
} else {
//没找到
LOGI("没找到 textureQueue");
list<GPUTexture*> textureQueue;
texture = new GPUTexture();
texture->init(width, height);
textureQueueCache[queueKey] = textureQueue;
}
// LOGI("texture from cache : %d", texture->getTexId());
return texture;
}
void GPUTextureCache::returnTextureToCache(GPUTexture* texture) {
// LOGI("texture return cache : %d", texture->getTexId());
string queueKey = getQueueKey(texture->getWidth(), texture->getHeight());
map<string, list<GPUTexture*> >::iterator itor;
itor = textureQueueCache.find(queueKey);
if (itor != textureQueueCache.end()) {
(itor->second).push_back(texture);
} else {
LOGI("unreachable code...");
}
}
string GPUTextureCache::getQueueKey(int width, int height) {
string queueKey = "tex_";
char widthBuffer[8];
sprintf(widthBuffer, "%d", width);
queueKey.append(string(widthBuffer));
queueKey.append("_");
char heightBuffer[8];
sprintf(heightBuffer, "%d", height);
queueKey.append(string(heightBuffer));
return queueKey;
}
/******************* GPUTexture class *******************/
GPUTexture::GPUTexture() {
}
GPUTexture::~GPUTexture() {
}
void GPUTexture::init(int width, int height) {
this->width = width;
this->height = height;
this->createTexture(width, height);
referenceCount = 0;
}
void GPUTexture::dealloc(){
glDeleteTextures(1, &texId);
}
GLuint GPUTexture::createTexture(GLsizei width, GLsizei height) {
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return texId;
}
void GPUTexture::lock() {
referenceCount++;
}
void GPUTexture::unLock() {
referenceCount--;
if (referenceCount < 1) {
GPUTextureCache::GetInstance()->returnTextureToCache(this);
}
}
void GPUTexture::clearAllLocks() {
referenceCount = 0;
}
| 26.674419 | 97 | 0.70619 | daimaren |
019cd4e4d0c828c058f79ead42439e16b12dd270 | 2,584 | cpp | C++ | utils/write_updater.cpp | openharmony-gitee-mirror/update_updater | 72393623a6aa9d08346da98433bb3bdbe5f07120 | [
"Apache-2.0"
] | null | null | null | utils/write_updater.cpp | openharmony-gitee-mirror/update_updater | 72393623a6aa9d08346da98433bb3bdbe5f07120 | [
"Apache-2.0"
] | null | null | null | utils/write_updater.cpp | openharmony-gitee-mirror/update_updater | 72393623a6aa9d08346da98433bb3bdbe5f07120 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:07:24.000Z | 2021-09-13T12:07:24.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 <iostream>
#include "fs_manager/mount.h"
#include "misc_info/misc_info.h"
#include "securec.h"
#include "updater/updater_const.h"
using namespace std;
using namespace updater;
int main(int argc, char **argv)
{
if (argc == 1) {
cout << "Please input correct command, examples :" << endl;
cout << "updater : write_updater updater /data/updater/updater.zip" << endl;
cout << "factory_reset : write_updater user_factory_reset" << endl;
cout << "clear command : write_updater clear" << endl;
return -1;
}
if (strcmp(argv[1], "updater") == 0) {
struct UpdateMessage boot {};
if (argv[WRITE_SECOND_CMD] != nullptr) {
if (snprintf_s(boot.update, sizeof(boot.update), sizeof(boot.update) - 1, "--update_package=%s",
argv[WRITE_SECOND_CMD]) == -1) {
cout << "WriteUpdaterMessage snprintf_s failed!" << endl;
return -1;
}
}
bool ret = WriteUpdaterMessage(MISC_FILE, boot);
if (!ret) {
cout << "WriteUpdaterMessage failed!" << endl;
return -1;
}
} else if (strcmp(argv[1], "user_factory_reset") == 0) {
struct UpdateMessage boot {};
if (strncpy_s(boot.update, sizeof(boot.update), "--user_wipe_data", sizeof(boot.update) - 1) != 0) {
cout << "strncpy_s failed!" << endl;
return -1;
}
bool ret = WriteUpdaterMessage(MISC_FILE, boot);
if (!ret) {
cout << "WriteUpdaterMessage failed!" << endl;
return -1;
}
} else if (strcmp(argv[1], "clear") == 0) {
struct UpdateMessage boot {};
bool ret = WriteUpdaterMessage(MISC_FILE, boot);
if (!ret) {
cout << "WriteUpdaterMessage failed!" << endl;
return -1;
}
} else {
cout << "Please input correct command!" << endl;
return -1;
}
return 0;
}
| 35.888889 | 108 | 0.594427 | openharmony-gitee-mirror |
01a1e24acf88e53592372de597bff526883fba94 | 15,802 | hpp | C++ | SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Deathworm_AnimBlueprint_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// AnimBlueprintGeneratedClass Deathworm_AnimBlueprint.Deathworm_AnimBlueprint_C
// 0x0628 (0x0968 - 0x0340)
class UDeathworm_AnimBlueprint_C : public UAnimInstance
{
public:
struct FAnimNode_Root AnimGraphNode_Root_CFF4A96944B38C20EDC066BC94E1B628; // 0x0340(0x0028)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_E7146F694055C55380B001AE63B41257;// 0x0368(0x0018)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_96F8291C41157B73A8AC088C90822FC3;// 0x0380(0x0018)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_A9E899CC48521880815FB3B7877D0742;// 0x0398(0x0018)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_9EBD37104522759DFF931D95455F88F9;// 0x03B0(0x0018)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_399D803B4896CBDB7046B08FCDA1C387;// 0x03C8(0x0018)
struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_F2AD59AE49B82A3361FE04B3A84705F1;// 0x03E0(0x0018)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_4B4E4832493212299A9477AFECEEFB61;// 0x03F8(0x0030)
struct FAnimNode_Root AnimGraphNode_StateResult_47081A314FF2E60BCE1F5FB7EDB9CD3A;// 0x0428(0x0028)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_C4D91D7B4021DD0E1549D79C4B5E5573;// 0x0450(0x0030)
struct FAnimNode_Root AnimGraphNode_StateResult_314750614B6C27F1EB1EDE81E9736224;// 0x0480(0x0028)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_0E8E130240F31222C619F39B5D0A0CDE;// 0x04A8(0x0030)
struct FAnimNode_Root AnimGraphNode_StateResult_51AE0A424EDCC223F1BC6885CF6E682D;// 0x04D8(0x0028)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_C18A56A64B5B3673FE7802BDC3B545DA;// 0x0500(0x0030)
struct FAnimNode_Root AnimGraphNode_StateResult_D063D6CD41C9FC0E94E5FCBBCA43DBC6;// 0x0530(0x0028)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_0B1F9D9E48D03E816115DDB638E47754;// 0x0558(0x0030)
struct FAnimNode_Root AnimGraphNode_StateResult_AFFD668343AA995AB5D2E39C39BA8D97;// 0x0588(0x0028)
struct FAnimNode_StateMachine AnimGraphNode_StateMachine_A81CFC5D460FCD67115E908E42AC62E0;// 0x05B0(0x0060)
struct FAnimNode_Slot AnimGraphNode_Slot_B368E5AF43AD0F656248FE8C8D11260E; // 0x0610(0x0038)
struct FAnimNode_Slot AnimGraphNode_Slot_CE55327E41443ED752B5FF9F20E338A9; // 0x0648(0x0038)
struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_3753B438428D02A6D7BEAD8631918275;// 0x0680(0x00B0)
struct FAnimNode_ConvertLocalToComponentSpace AnimGraphNode_LocalToComponentSpace_4AEF33F54406DA03A703DEB5A3D293CE;// 0x0730(0x0028)
struct FAnimNode_ConvertComponentToLocalSpace AnimGraphNode_ComponentToLocalSpace_D563D4BE4EF47EDA4E429E8885891D3D;// 0x0758(0x0028)
struct FAnimNode_RotationOffsetBlendSpace AnimGraphNode_RotationOffsetBlendSpace_F716FD4C42C6EEFDA55329A375324A6C;// 0x0780(0x00F8)
bool bIsUnderground; // 0x0878(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsDead; // 0x0879(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x2]; // 0x087A(0x0002) MISSED OFFSET
struct FRotator RootRotationOffset; // 0x087C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector RootLocationOffset; // 0x0888(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator TargetRotation; // 0x0894(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AimYaw; // 0x08A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AimPitch; // 0x08A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AimOffsetYawScale; // 0x08A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AimOffsetPitchScale; // 0x08AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PopUpPlayRate; // 0x08B0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue; // 0x08B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue; // 0x08B8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue; // 0x08B9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue2; // 0x08BA(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue; // 0x08BB(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue2; // 0x08BC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData01[0x3]; // 0x08BD(0x0003) MISSED OFFSET
double CallFunc_GetGameTimeInSeconds_ReturnValue; // 0x08C0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APawn* CallFunc_TryGetPawnOwner_ReturnValue; // 0x08C8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_Subtract_DoubleDouble_ReturnValue; // 0x08D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue3; // 0x08D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData02[0x3]; // 0x08D9(0x0003) MISSED OFFSET
float CallFunc_Conv_DoubleToFloat_ReturnValue; // 0x08DC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue; // 0x08E0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue; // 0x08E1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData03[0x2]; // 0x08E2(0x0002) MISSED OFFSET
float K2Node_Select_ReturnValue; // 0x08E4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_Select_CmpSuccess; // 0x08E8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData04[0x3]; // 0x08E9(0x0003) MISSED OFFSET
float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue2; // 0x08EC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue2; // 0x08F0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData05[0x3]; // 0x08F1(0x0003) MISSED OFFSET
float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue3; // 0x08F4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue3; // 0x08F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue3; // 0x08F9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData06[0x2]; // 0x08FA(0x0002) MISSED OFFSET
float K2Node_Event_DeltaTimeX; // 0x08FC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APawn* CallFunc_TryGetPawnOwner_ReturnValue2; // 0x0900(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class ADeathworm_Character_BP_C* K2Node_DynamicCast_AsDeathworm_Character_BP_C; // 0x0908(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x0910(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData07[0x3]; // 0x0911(0x0003) MISSED OFFSET
struct FRotator CallFunc_GetAimOffsets_RootRotOffset; // 0x0914(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_GetAimOffsets_TheRootYawSpeed; // 0x0920(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetAimOffsets_RootLocOffset; // 0x0924(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_GetAimOffsets_ReturnValue; // 0x0930(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch; // 0x093C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw; // 0x0940(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll; // 0x0944(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Divide_FloatFloat_ReturnValue; // 0x0948(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Divide_FloatFloat_ReturnValue2; // 0x094C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue; // 0x0950(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue; // 0x0954(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FClamp_ReturnValue; // 0x0958(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue2; // 0x095C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue2; // 0x0960(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FClamp_ReturnValue2; // 0x0964(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass Deathworm_AnimBlueprint.Deathworm_AnimBlueprint_C");
return ptr;
}
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3462();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3461();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3460();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3459();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3458();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3457();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_SequencePlayer_7942();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_ModifyBone_1080();
void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_RotationOffsetBlendSpace_390();
void BlueprintUpdateAnimation(float* DeltaTimeX);
void ExecuteUbergraph_Deathworm_AnimBlueprint(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 121.553846 | 208 | 0.611378 | 2bite |
01a29daa6672644661a43c4c1ada09267e97f7a0 | 345 | cpp | C++ | testcases/hh.p.cpp | qwerty472123/CPreprecessor | 21bcf11d9478938ec977684f348caeaccbf56efd | [
"MIT"
] | 2 | 2021-02-05T06:12:34.000Z | 2021-05-31T10:59:32.000Z | testcases/hh.p.cpp | qwerty472123/CPreprocessor | 21bcf11d9478938ec977684f348caeaccbf56efd | [
"MIT"
] | null | null | null | testcases/hh.p.cpp | qwerty472123/CPreprocessor | 21bcf11d9478938ec977684f348caeaccbf56efd | [
"MIT"
] | null | null | null | # 1 "hh.c"
# 1 "a a.h"
hello
# 2 "hh.c"
check
# 1 "aa.c"
int main() {
9 3;
3()<a;
<a a.h>
'aa'
puts(<a);
const int a=19;
"aaaaa"
int a,v,c,d,w;
"hello worl\nd";
asm ( "1\n1" : "=r"(a), "=v"(v) : "=x"(c),"=dd"(w):"mem""ory" );
{
int <a=1;
}
}
<a() __asm__ ( "1\n1" ); | 7.5 | 66 | 0.344928 | qwerty472123 |
01a80cbbc25aa7a4dd190bfaf3af3a6b5f94bf54 | 5,543 | cpp | C++ | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <gui/live_data_display_screen/CityInfo.hpp>
#include "BitmapDatabase.hpp"
#include <texts/TextKeysAndLanguages.hpp>
#include <touchgfx/Color.hpp>
#include <stdlib.h>
CityInfo::CityInfo()
{
textColor = 0x0;
background.setXY(0, 0);
cityName.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF));
cityName.setTypedText(TypedText(T_WEATHER_CITY_0));
cityName.setPosition(16, 10, 130, 24);
cityNameDropShadow.setColor(Color::getColorFrom24BitRGB(0x0, 0x0, 0x0));
cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_0));
cityNameDropShadow.setPosition(cityName.getX() + 1, cityName.getY() + 1, cityName.getWidth(), cityName.getHeight());
cityNameDropShadow.setAlpha(128);
timeAndDate.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF));
timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_0));
timeAndDate.setPosition(16, 14 + cityName.getTextHeight(), 150, 20);
timeAndDateDropShadow.setColor(Color::getColorFrom24BitRGB(0x0, 0x0, 0x0));
timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_0));
timeAndDateDropShadow.setPosition(timeAndDate.getX() + 1, timeAndDate.getY() + 1, timeAndDate.getWidth(), timeAndDate.getHeight());
timeAndDateDropShadow.setAlpha(128);
largeTemperature.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF));
largeTemperature.setTypedText(TypedText(T_WEATHER_LARGE_TEMPERATURE));
largeTemperature.setPosition(66, 46, 150, 110);
Unicode::snprintf(largeTemperatureBuffer, 4, "%d", 0);
largeTemperature.setWildcard(largeTemperatureBuffer);
largeTemperatureDropShadow.setColor(Color::getColorFrom24BitRGB(0x00, 0x00, 0x00));
largeTemperatureDropShadow.setTypedText(TypedText(T_WEATHER_LARGE_TEMPERATURE));
largeTemperatureDropShadow.setPosition(largeTemperature.getX() + 1, largeTemperature.getY() + 2, largeTemperature.getWidth(), largeTemperature.getHeight());
largeTemperatureDropShadow.setWildcard(largeTemperatureBuffer);
largeTemperatureDropShadow.setAlpha(128);
add(background);
add(cityNameDropShadow);
add(cityName);
add(timeAndDateDropShadow);
add(timeAndDate);
add(largeTemperatureDropShadow);
add(largeTemperature);
}
void CityInfo::setBitmap(BitmapId bg)
{
background.setBitmap(Bitmap(bg));
setWidth(background.getWidth());
setHeight(background.getHeight());
}
/* Setup the CityInfo with some static city information
* In a real world example this data would be live updated
* and come from the model, but in this demo it is just hard coded.
*/
void CityInfo::setCity(Cities c)
{
city = c;
switch (city)
{
case COPENHAGEN:
cityName.setTypedText(TypedText(T_WEATHER_CITY_0));
cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_0));
timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_0));
timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_0));
startTemperature = 12;
break;
case MUMBAI:
cityName.setTypedText(TypedText(T_WEATHER_CITY_1));
cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_1));
timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_1));
timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_1));
startTemperature = 32;
break;
case HONG_KONG:
cityName.setTypedText(TypedText(T_WEATHER_CITY_2));
cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_2));
timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_2));
timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_2));
startTemperature = 24;
break;
case NEW_YORK:
cityName.setTypedText(TypedText(T_WEATHER_CITY_3));
cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_3));
timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_3));
timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_3));
startTemperature = 16;
break;
default:
break;
}
setTemperature(startTemperature);
cityName.invalidate();
cityNameDropShadow.invalidate();
timeAndDate.invalidate();
timeAndDateDropShadow.invalidate();
}
void CityInfo::setTemperature(int16_t newTemperature)
{
currentTemperature = newTemperature;
Unicode::snprintf(largeTemperatureBuffer, 4, "%d", currentTemperature);
largeTemperature.invalidate();
largeTemperatureDropShadow.invalidate();
}
void CityInfo::adjustTemperature()
{
// Make sure that the temperature does not drift too far from the starting point
if (currentTemperature - 2 == startTemperature)
{
setTemperature(currentTemperature - 1);
}
else if (currentTemperature + 2 == startTemperature)
{
setTemperature(currentTemperature + 1);
}
else
{
setTemperature(currentTemperature + ((rand() % 2) ? 1 : -1));
}
}
| 35.305732 | 160 | 0.707379 | hwiwonl |
01aa903c12681817cb94b6eee532b1dd17fd3171 | 660 | cpp | C++ | test/testRandom.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | test/testRandom.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | test/testRandom.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <random>
#include <cmath>
using namespace std;
int NUMROL = 10000;
int NUMBIN = 100;
int BINSZE = 0.1;
int main() {
default_random_engine ENGINE;
normal_distribution<float> norm(0.0, 1.0);
int rand[NUMBIN], rSqr[NUMBIN];
float rVal, rSqT = 0;
for(int i = 0; i < NUMBIN; ++i)
rand[i] = 0;
for(int i = 0; i < NUMROL; ++i) {
rVal = norm(ENGINE);
if(abs(rVal) < (BINSZE * NUMBIN / 2))
++rand[int(floor((rVal + BINSZE * NUMBIN / 2) / BINSZE))];
rSqT += rVal * rVal;
}
cout << rSqT / NUMROL << endl;
for(int i = 0; i < NUMBIN; ++i)
//cout << i << "\t" << rand[i] << endl;
return 0;
}
| 20 | 64 | 0.566667 | htran118 |
01ab1caa9d18c97066657389a92ab8e27e3a9e95 | 1,282 | cpp | C++ | Nidrobb/Unitests/ToolboxTest.cpp | elias-hanna/Nidrobb | 9de4b1bd63384a7c5969537be594f3248fd5c41b | [
"MIT"
] | null | null | null | Nidrobb/Unitests/ToolboxTest.cpp | elias-hanna/Nidrobb | 9de4b1bd63384a7c5969537be594f3248fd5c41b | [
"MIT"
] | null | null | null | Nidrobb/Unitests/ToolboxTest.cpp | elias-hanna/Nidrobb | 9de4b1bd63384a7c5969537be594f3248fd5c41b | [
"MIT"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ToolboxTest
#include <boost/test/unit_test.hpp>
#include "../Toolbox.hpp"
BOOST_AUTO_TEST_SUITE (CreateRect)
BOOST_AUTO_TEST_CASE (Positive)
{
int x = 10, y=20, w = 30, h=40;
SDL_Rect* r = createRect(x,y,w,h);
BOOST_REQUIRE(r != nullptr); //Bloquant
BOOST_REQUIRE(r->x==x);
BOOST_REQUIRE(r->y==y);
BOOST_REQUIRE(r->w==w);
BOOST_REQUIRE(r->h==h);
delete r;
}
BOOST_AUTO_TEST_CASE (Nul)
{
int x = 0, y=0, w = 0, h=0;
SDL_Rect* r = createRect(x,y,w,h);
BOOST_REQUIRE(r != nullptr);
BOOST_REQUIRE(r->x==x);
BOOST_REQUIRE(r->y==y);
BOOST_REQUIRE(r->w==w);
BOOST_REQUIRE(r->h==h);
delete r;
}
BOOST_AUTO_TEST_CASE (Negative)
{
int x = -10, y=-20, w = -30, h=-40;
SDL_Rect* r = createRect(x,y,w,h);
BOOST_REQUIRE(r != nullptr);
BOOST_REQUIRE(r->x==x);
BOOST_REQUIRE(r->y==y);
BOOST_CHECK(r->w>=0); //Devrait pas autoriser w, h <0
BOOST_CHECK(r->h>=0); //Non bloquant
delete r;
}
BOOST_AUTO_TEST_SUITE_END( )
BOOST_AUTO_TEST_SUITE (OperatorPrint)
BOOST_AUTO_TEST_CASE (SDLRect)
{
int x = 10, y=20, w = 30, h=40;
SDL_Rect* r = createRect(x,y,w,h);
BOOST_REQUIRE(r != nullptr);
std::cout<<"Rect : "<<x<<"/"<<y<<" - "<<w<<"/"<<h<<" = "<<*r<<std::endl;
delete r;
}
BOOST_AUTO_TEST_SUITE_END( ) | 19.424242 | 73 | 0.652886 | elias-hanna |
01aca3435e599ebfcee6deb9b9daeeae63e33674 | 20,234 | cpp | C++ | test/rocprim/test_block_reduce.cpp | saadrahim/rocPRIM | 4c8bc629b298f33e0c0df07b61f9b30503a84f27 | [
"MIT"
] | null | null | null | test/rocprim/test_block_reduce.cpp | saadrahim/rocPRIM | 4c8bc629b298f33e0c0df07b61f9b30503a84f27 | [
"MIT"
] | null | null | null | test/rocprim/test_block_reduce.cpp | saadrahim/rocPRIM | 4c8bc629b298f33e0c0df07b61f9b30503a84f27 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 <vector>
// Google Test
#include <gtest/gtest.h>
// rocPRIM API
#include <rocprim/rocprim.hpp>
#include "test_utils.hpp"
#define HIP_CHECK(error) ASSERT_EQ(static_cast<hipError_t>(error), hipSuccess)
namespace rp = rocprim;
template<class T, class BinaryOp>
T apply(BinaryOp binary_op, const T& a, const T& b)
{
return binary_op(a, b);
}
// Params for tests
template<
class T,
unsigned int BlockSize = 256U,
unsigned int ItemsPerThread = 1U,
rp::block_reduce_algorithm Algorithm = rp::block_reduce_algorithm::using_warp_reduce,
class BinaryOp = rocprim::plus<T>
>
struct params
{
using type = T;
using binary_op_type = BinaryOp;
static constexpr rp::block_reduce_algorithm algorithm = Algorithm;
static constexpr unsigned int block_size = BlockSize;
static constexpr unsigned int items_per_thread = ItemsPerThread;
};
// ---------------------------------------------------------
// Test for reduce ops taking single input value
// ---------------------------------------------------------
template<class Params>
class RocprimBlockReduceSingleValueTests : public ::testing::Test
{
public:
using type = typename Params::type;
using binary_op_type = typename Params::binary_op_type;
static constexpr rp::block_reduce_algorithm algorithm = Params::algorithm;
static constexpr unsigned int block_size = Params::block_size;
};
typedef ::testing::Types<
// -----------------------------------------------------------------------
// rocprim::block_reduce_algorithm::using_warp_reduce
// -----------------------------------------------------------------------
params<int, 64U>,
params<int, 128U>,
params<int, 192U>,
params<int, 256U>,
params<int, 512U>,
params<int, 1024U>,
params<int, 65U>,
params<int, 37U>,
params<int, 129U>,
params<int, 162U>,
params<int, 255U>,
// uint tests
params<unsigned int, 64U>,
params<unsigned int, 256U>,
params<unsigned int, 377U>,
// char tests
params<char, 64U>,
params<char, 256U>,
params<char, 377U>,
// half tests
params<rp::half, 64U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
params<rp::half, 256U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
params<rp::half, 377U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
// long tests
params<long, 64U>,
params<long, 256U>,
params<long, 377U>,
// -----------------------------------------------------------------------
// rocprim::block_reduce_algorithm::raking_reduce
// -----------------------------------------------------------------------
params<int, 64U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 128U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 192U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 256U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 512U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 1024U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<char, 64U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<char, 128U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<char, 192U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<char, 256U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<rp::half, 64U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<rp::half, 128U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<rp::half, 192U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<rp::half, 256U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<unsigned long, 65U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<long, 37U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<short, 162U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<unsigned int, 255U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<int, 377U, 1, rp::block_reduce_algorithm::raking_reduce>,
params<unsigned char, 377U, 1, rp::block_reduce_algorithm::raking_reduce>
> SingleValueTestParams;
TYPED_TEST_CASE(RocprimBlockReduceSingleValueTests, SingleValueTestParams);
template<
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
void reduce_kernel(T* device_output, T* device_output_reductions)
{
const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x;
T value = device_output[index];
rp::block_reduce<T, BlockSize, Algorithm> breduce;
breduce.reduce(value, value, BinaryOp());
if(hipThreadIdx_x == 0)
{
device_output_reductions[hipBlockIdx_x] = value;
}
}
TYPED_TEST(RocprimBlockReduceSingleValueTests, Reduce)
{
using T = typename TestFixture::type;
using binary_op_type = typename TestFixture::binary_op_type;
constexpr auto algorithm = TestFixture::algorithm;
constexpr size_t block_size = TestFixture::block_size;
// Given block size not supported
if(block_size > test_utils::get_max_block_size())
{
return;
}
const size_t size = block_size * 113;
const size_t grid_size = size / block_size;
// Generate data
std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50);
std::vector<T> output_reductions(size / block_size);
// Calculate expected results on host
std::vector<T> expected_reductions(output_reductions.size(), 0);
binary_op_type binary_op;
for(size_t i = 0; i < output.size() / block_size; i++)
{
T value = 0;
for(size_t j = 0; j < block_size; j++)
{
auto idx = i * block_size + j;
value = apply(binary_op, value, output[idx]);
}
expected_reductions[i] = value;
}
// Preparing device
T* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T)));
T* device_output_reductions;
HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T)));
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_kernel<block_size, algorithm, T, binary_op_type>),
dim3(grid_size), dim3(block_size), 0, 0,
device_output, device_output_reductions
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
test_utils::assert_eq(output_reductions, expected_reductions);
HIP_CHECK(hipFree(device_output));
HIP_CHECK(hipFree(device_output_reductions));
}
template<
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class T
>
__global__
void reduce_multiplies_kernel(T* device_output, T* device_output_reductions)
{
const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x;
T value = device_output[index];
rp::block_reduce<T, BlockSize, Algorithm> breduce;
breduce.reduce(value, value, rocprim::multiplies<T>());
if(hipThreadIdx_x == 0)
{
device_output_reductions[hipBlockIdx_x] = value;
}
}
template<class T>
T host_multiplies(const T& x, const T& y)
{
return x * y;
}
rp::half host_multiplies(const rp::half&, const rp::half&)
{
// Used to allow compilation of tests with half
return rp::half(); // Any value since half is not tested in ReduceMultiplies
}
TYPED_TEST(RocprimBlockReduceSingleValueTests, ReduceMultiplies)
{
using T = typename TestFixture::type;
constexpr auto algorithm = TestFixture::algorithm;
constexpr size_t block_size = TestFixture::block_size;
// Half not tested here
if(std::is_same<T, rp::half>::value)
{
return;
}
// Given block size not supported
if(block_size > test_utils::get_max_block_size())
{
return;
}
const size_t size = block_size * 113;
const size_t grid_size = size / block_size;
// Generate data
std::vector<T> output(size, 1);
auto two_places = test_utils::get_random_data<unsigned int>(size/32, 0, size-1);
for(auto i : two_places)
{
output[i] = T(2);
}
std::vector<T> output_reductions(size / block_size);
// Calculate expected results on host
std::vector<T> expected_reductions(output_reductions.size(), 0);
for(size_t i = 0; i < output.size() / block_size; i++)
{
T value = 1;
for(size_t j = 0; j < block_size; j++)
{
auto idx = i * block_size + j;
value = host_multiplies(value, output[idx]);
}
expected_reductions[i] = value;
}
// Preparing device
T* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T)));
T* device_output_reductions;
HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T)));
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_multiplies_kernel<block_size, algorithm, T>),
dim3(grid_size), dim3(block_size), 0, 0,
device_output, device_output_reductions
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
test_utils::assert_eq(output_reductions, expected_reductions);
HIP_CHECK(hipFree(device_output));
HIP_CHECK(hipFree(device_output_reductions));
}
TYPED_TEST_CASE(RocprimBlockReduceSingleValueTests, SingleValueTestParams);
template<
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
void reduce_valid_kernel(T* device_output, T* device_output_reductions, const unsigned int valid_items)
{
const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x;
T value = device_output[index];
rp::block_reduce<T, BlockSize, Algorithm> breduce;
breduce.reduce(value, value, valid_items, BinaryOp());
if(hipThreadIdx_x == 0)
{
device_output_reductions[hipBlockIdx_x] = value;
}
}
TYPED_TEST(RocprimBlockReduceSingleValueTests, ReduceValid)
{
using T = typename TestFixture::type;
using binary_op_type = typename TestFixture::binary_op_type;
constexpr auto algorithm = TestFixture::algorithm;
constexpr size_t block_size = TestFixture::block_size;
const unsigned int valid_items = test_utils::get_random_value(block_size - 10, block_size);
// Given block size not supported
if(block_size > test_utils::get_max_block_size())
{
return;
}
const size_t size = block_size * 113;
const size_t grid_size = size / block_size;
// Generate data
std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50);
std::vector<T> output_reductions(size / block_size);
// Calculate expected results on host
std::vector<T> expected_reductions(output_reductions.size(), 0);
binary_op_type binary_op;
for(size_t i = 0; i < output.size() / block_size; i++)
{
T value = 0;
for(size_t j = 0; j < valid_items; j++)
{
auto idx = i * block_size + j;
value = apply(binary_op, value, output[idx]);
}
expected_reductions[i] = value;
}
// Preparing device
T* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T)));
T* device_output_reductions;
HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T)));
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_valid_kernel<block_size, algorithm, T, binary_op_type>),
dim3(grid_size), dim3(block_size), 0, 0,
device_output, device_output_reductions, valid_items
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
test_utils::assert_eq(output_reductions, expected_reductions);
HIP_CHECK(hipFree(device_output));
HIP_CHECK(hipFree(device_output_reductions));
}
template<class Params>
class RocprimBlockReduceInputArrayTests : public ::testing::Test
{
public:
using type = typename Params::type;
using binary_op_type = typename Params::binary_op_type;
static constexpr unsigned int block_size = Params::block_size;
static constexpr rocprim::block_reduce_algorithm algorithm = Params::algorithm;
static constexpr unsigned int items_per_thread = Params::items_per_thread;
};
typedef ::testing::Types<
// -----------------------------------------------------------------------
// rocprim::block_reduce_algorithm::using_warp_reduce
// -----------------------------------------------------------------------
params<float, 6U, 32>,
params<float, 32, 2>,
params<unsigned int, 256, 3>,
params<int, 512, 4>,
params<float, 1024, 1>,
params<float, 37, 2>,
params<float, 65, 5>,
params<float, 162, 7>,
params<float, 255, 15>,
params<char, 1024, 1>,
params<char, 37, 2>,
params<char, 65, 5>,
params<rp::half, 1024, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
params<rp::half, 37, 2, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
params<rp::half, 65, 5, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>,
// -----------------------------------------------------------------------
// rocprim::block_reduce_algorithm::raking_reduce
// -----------------------------------------------------------------------
params<float, 6U, 32, rp::block_reduce_algorithm::raking_reduce>,
params<float, 32, 2, rp::block_reduce_algorithm::raking_reduce>,
params<int, 256, 3, rp::block_reduce_algorithm::raking_reduce>,
params<unsigned int, 512, 4, rp::block_reduce_algorithm::raking_reduce>,
params<float, 1024, 1, rp::block_reduce_algorithm::raking_reduce>,
params<float, 37, 2, rp::block_reduce_algorithm::raking_reduce>,
params<float, 65, 5, rp::block_reduce_algorithm::raking_reduce>,
params<float, 162, 7, rp::block_reduce_algorithm::raking_reduce>,
params<float, 255, 15, rp::block_reduce_algorithm::raking_reduce>,
params<char, 1024, 1, rp::block_reduce_algorithm::raking_reduce>,
params<char, 37, 2, rp::block_reduce_algorithm::raking_reduce>,
params<char, 65, 5, rp::block_reduce_algorithm::raking_reduce>,
params<rp::half, 1024, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<rp::half, 37, 2, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>,
params<rp::half, 65, 5, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>
> InputArrayTestParams;
TYPED_TEST_CASE(RocprimBlockReduceInputArrayTests, InputArrayTestParams);
template<
unsigned int BlockSize,
unsigned int ItemsPerThread,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
void reduce_array_kernel(T* device_output, T* device_output_reductions)
{
const unsigned int index = ((hipBlockIdx_x * BlockSize) + hipThreadIdx_x) * ItemsPerThread;
// load
T in_out[ItemsPerThread];
for(unsigned int j = 0; j < ItemsPerThread; j++)
{
in_out[j] = device_output[index + j];
}
rp::block_reduce<T, BlockSize, Algorithm> breduce;
T reduction;
breduce.reduce(in_out, reduction, BinaryOp());
if(hipThreadIdx_x == 0)
{
device_output_reductions[hipBlockIdx_x] = reduction;
}
}
TYPED_TEST(RocprimBlockReduceInputArrayTests, Reduce)
{
using T = typename TestFixture::type;
using binary_op_type = typename TestFixture::binary_op_type;
constexpr auto algorithm = TestFixture::algorithm;
constexpr size_t block_size = TestFixture::block_size;
constexpr size_t items_per_thread = TestFixture::items_per_thread;
// Given block size not supported
if(block_size > test_utils::get_max_block_size())
{
return;
}
const size_t items_per_block = block_size * items_per_thread;
const size_t size = items_per_block * 37;
const size_t grid_size = size / items_per_block;
// Generate data
std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50);
// Output reduce results
std::vector<T> output_reductions(size / block_size, 0);
// Calculate expected results on host
std::vector<T> expected_reductions(output_reductions.size(), 0);
binary_op_type binary_op;
for(size_t i = 0; i < output.size() / items_per_block; i++)
{
T value = 0;
for(size_t j = 0; j < items_per_block; j++)
{
auto idx = i * items_per_block + j;
value = apply(binary_op, value, output[idx]);
}
expected_reductions[i] = value;
}
// Preparing device
T* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T)));
T* device_output_reductions;
HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T)));
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
HIP_CHECK(
hipMemcpy(
device_output_reductions, output_reductions.data(),
output_reductions.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_array_kernel<block_size, items_per_thread, algorithm, T, binary_op_type>),
dim3(grid_size), dim3(block_size), 0, 0,
device_output, device_output_reductions
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
test_utils::assert_near(output_reductions, expected_reductions, 0.05);
HIP_CHECK(hipFree(device_output));
HIP_CHECK(hipFree(device_output_reductions));
}
| 34.64726 | 105 | 0.661708 | saadrahim |
01acc91ff0f87252de65216ec877bd878fbbb682 | 913 | cpp | C++ | src/IsoGame/Play/Rooms/ShooterRoom.cpp | Harry09/IsoGame | 7320bee14197b66a96f432d4071537b3bb892c13 | [
"MIT"
] | null | null | null | src/IsoGame/Play/Rooms/ShooterRoom.cpp | Harry09/IsoGame | 7320bee14197b66a96f432d4071537b3bb892c13 | [
"MIT"
] | null | null | null | src/IsoGame/Play/Rooms/ShooterRoom.cpp | Harry09/IsoGame | 7320bee14197b66a96f432d4071537b3bb892c13 | [
"MIT"
] | null | null | null | #include "ShooterRoom.h"
#include <Common\Random.h>
#include <Play\Objects\Entities\Enemies\Shooter.h>
#include <Play\Objects\Rock.h>
ShooterRoom::ShooterRoom(Map *parent, const sf::Vector2i &pos)
: Room(parent, pos)
{
m_isRoomClear = false;
m_roomType = Room::ENEMY;
auto playZone = GetPlayZone();
Random random;
for (int i = 0; i < random.Get<int>(1, 3); ++i)
{
float x = random.Get<float>(playZone.left, playZone.left + playZone.width);
float y = random.Get<float>(playZone.top, playZone.top + playZone.height);
AddObject(new Shooter(sf::Vector2f(x, y)));
}
for (int i = 0; i < random.Get<int>(4, 6); ++i)
{
float x = random.Get<float>(playZone.left, playZone.left + playZone.width);
float y = random.Get<float>(playZone.top, playZone.top + playZone.height);
AddObject(new Rock(sf::Vector2f(x, y)));
}
m_roomColor = sf::Color(0x5C6BC0FF);
}
ShooterRoom::~ShooterRoom()
{
}
| 21.738095 | 77 | 0.67908 | Harry09 |
01af6663d4e513c5d9e6eb067655257b87986187 | 2,282 | cpp | C++ | LeetCodeCPP/212. Word Search II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | 1 | 2019-03-29T03:33:56.000Z | 2019-03-29T03:33:56.000Z | LeetCodeCPP/212. Word Search II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | LeetCodeCPP/212. Word Search II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// 212. Word Search II
//
// Created by admin on 2019/6/13.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class TrieNode{
public:
TrieNode *next[26];
string word;
TrieNode(){
word="";
memset(next,NULL,sizeof(next));
}
};
class Solution {
private:
TrieNode * buildTrieNode(vector<string>& words){
TrieNode* root=new TrieNode();
for(string word:words){
TrieNode* cur=root;
for(char c:word){
if(cur->next[c-'a']==NULL){
cur->next[c-'a']=new TrieNode();
}
cur=cur->next[c-'a'];
}
cur->word=word;
}
return root;
}
void dfs(vector<vector<char>>& board,int i,int j,TrieNode *cur,vector<string> &ret){
const char c=board[i][j];
if(c=='#' || cur->next[c-'a']==NULL){
return;
}
cur=cur->next[c-'a'];
if(cur->word!=""){ //防止重复
ret.push_back(cur->word);
cur->word="";
}
board[i][j]='#';
if(i>0) dfs(board,i-1,j,cur,ret);
if(j>0) dfs(board,i,j-1,cur,ret);
if(i<board.size()-1) dfs(board,i+1,j,cur,ret);
if(j<board[0].size()-1) dfs(board,i,j+1,cur,ret);
board[i][j]=c;
}
public:
vector<string> findWords(vector<vector<char>>& board,vector<string> &words) {
int m=board.size();
if(m==0){
return {};
}
int n=board[0].size();
if(n==0){
return {};
}
TrieNode* root=buildTrieNode(words);
vector<string> ret;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
dfs(board,i,j,root,ret);
}
}
return ret;
}
};
int main(int argc, const char * argv[]) {
vector<vector<char>> input1={{'o','a','a','n'},{'e','t','a','e'},{'i','h','k','r'},{'i','f','l','v'}};
vector<string> input2={"oath","pea","eat","rain"};
Solution so=Solution();
vector<string> ret=so.findWords(input1, input2);
for(auto r:ret){
cout<<r<<" ";
}
cout<<endl;
return 0;
}
| 23.525773 | 107 | 0.468449 | 18600130137 |
01af913d446d653333760ee24a0a8a473afc85dc | 3,400 | hpp | C++ | include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TextMeshProUGUI
class TextMeshProUGUI;
}
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Button
class Button;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: Vector3SO
class Vector3SO;
// Forward declaring type: VRPlatformHelper
class VRPlatformHelper;
// Forward declaring type: PlayerSpecificSettings
class PlayerSpecificSettings;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: CanvasGroup
class CanvasGroup;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: ButtonBinder
class ButtonBinder;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: PlayerHeightSettingsController
class PlayerHeightSettingsController : public UnityEngine::MonoBehaviour {
public:
// private TMPro.TextMeshProUGUI _text
// Offset: 0x18
TMPro::TextMeshProUGUI* text;
// private UnityEngine.UI.Button _setButton
// Offset: 0x20
UnityEngine::UI::Button* setButton;
// private Vector3SO _roomCenter
// Offset: 0x28
GlobalNamespace::Vector3SO* roomCenter;
// private UnityEngine.CanvasGroup _canvasGroup
// Offset: 0x30
UnityEngine::CanvasGroup* canvasGroup;
// private VRPlatformHelper _vrPlatformHelper
// Offset: 0x38
GlobalNamespace::VRPlatformHelper* vrPlatformHelper;
// private PlayerSpecificSettings _playerSettings
// Offset: 0x40
GlobalNamespace::PlayerSpecificSettings* playerSettings;
// private HMUI.ButtonBinder _buttonBinder
// Offset: 0x48
HMUI::ButtonBinder* buttonBinder;
// public System.Void set_interactable(System.Boolean value)
// Offset: 0xBDED84
void set_interactable(bool value);
// protected System.Void Awake()
// Offset: 0xBDEE1C
void Awake();
// public System.Void Init(PlayerSpecificSettings playerSettings)
// Offset: 0xBDEEE0
void Init(GlobalNamespace::PlayerSpecificSettings* playerSettings);
// private System.Void AutoSetHeight()
// Offset: 0xBDEFAC
void AutoSetHeight();
// private System.Void RefreshUI()
// Offset: 0xBDEF08
void RefreshUI();
// public System.Void .ctor()
// Offset: 0xBDF058
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static PlayerHeightSettingsController* New_ctor();
}; // PlayerHeightSettingsController
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::PlayerHeightSettingsController*, "", "PlayerHeightSettingsController");
#pragma pack(pop)
| 35.051546 | 111 | 0.726471 | Futuremappermydud |
01afe0535cfe3ca9df69abddfc03bbfe3764613f | 7,739 | cpp | C++ | tests/src/types/src/types_test.cpp | hymanat/Karabiner-Elements | af955113ee0a5990ba52a467cad43a9f590b2e79 | [
"Unlicense"
] | 1 | 2021-11-09T10:28:50.000Z | 2021-11-09T10:28:50.000Z | tests/src/types/src/types_test.cpp | bland328/Karabiner-Elements | 328df25e09837cd29023def17d552830bf6cdba2 | [
"Unlicense"
] | null | null | null | tests/src/types/src/types_test.cpp | bland328/Karabiner-Elements | 328df25e09837cd29023def17d552830bf6cdba2 | [
"Unlicense"
] | null | null | null | #include <catch2/catch.hpp>
#include "types.hpp"
TEST_CASE("make_key_code") {
REQUIRE(krbn::make_key_code("spacebar") == krbn::key_code::spacebar);
REQUIRE(krbn::make_key_code("unknown") == std::nullopt);
REQUIRE(krbn::make_key_code_name(krbn::key_code::spacebar) == std::string("spacebar"));
REQUIRE(krbn::make_key_code_name(krbn::key_code::left_option) == std::string("left_alt"));
REQUIRE(krbn::make_key_code_name(krbn::key_code::extra_) == std::string("(number:65536)"));
REQUIRE(krbn::make_hid_usage_page(krbn::key_code(1234)) == krbn::hid_usage_page::keyboard_or_keypad);
REQUIRE(krbn::make_hid_usage(krbn::key_code(1234)) == krbn::hid_usage(1234));
{
auto actual = krbn::make_key_code(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad),
krbn::hid_usage(kHIDUsage_KeyboardTab));
REQUIRE(*actual == krbn::key_code(kHIDUsage_KeyboardTab));
}
{
auto actual = krbn::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorTopCase),
krbn::hid_usage(krbn::kHIDUsage_AV_TopCase_KeyboardFn));
REQUIRE(*actual == krbn::key_code::fn);
}
{
auto actual = krbn::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorKeyboard),
krbn::hid_usage(krbn::kHIDUsage_AppleVendorKeyboard_Function));
REQUIRE(*actual == krbn::key_code::fn);
}
{
auto actual = krbn::make_key_code(krbn::hid_usage_page::keyboard_or_keypad,
krbn::hid_usage(1234));
REQUIRE(*actual == krbn::key_code(1234));
}
{
auto actual = krbn::make_key_code(krbn::hid_usage_page(kHIDPage_Button),
krbn::hid_usage(1));
REQUIRE(actual == std::nullopt);
}
// from_json
{
nlohmann::json json("escape");
REQUIRE(krbn::key_code(json) == krbn::key_code::escape);
}
{
nlohmann::json json(static_cast<uint32_t>(krbn::key_code::escape));
REQUIRE(krbn::key_code(json) == krbn::key_code::escape);
}
{
nlohmann::json json;
REQUIRE_THROWS_AS(
krbn::key_code(json),
pqrs::json::unmarshal_error);
REQUIRE_THROWS_WITH(
krbn::key_code(json),
"json must be string or number, but is `null`");
}
{
nlohmann::json json("unknown_value");
REQUIRE_THROWS_AS(
krbn::key_code(json),
pqrs::json::unmarshal_error);
REQUIRE_THROWS_WITH(
krbn::key_code(json),
"unknown key_code: `\"unknown_value\"`");
}
}
TEST_CASE("make_key_code (modifier_flag)") {
REQUIRE(krbn::make_key_code(krbn::modifier_flag::zero) == std::nullopt);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::caps_lock) == krbn::key_code::caps_lock);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_control) == krbn::key_code::left_control);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_shift) == krbn::key_code::left_shift);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_option) == krbn::key_code::left_option);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_command) == krbn::key_code::left_command);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_control) == krbn::key_code::right_control);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_shift) == krbn::key_code::right_shift);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_option) == krbn::key_code::right_option);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_command) == krbn::key_code::right_command);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::fn) == krbn::key_code::fn);
REQUIRE(krbn::make_key_code(krbn::modifier_flag::end_) == std::nullopt);
}
TEST_CASE("make_modifier_flag") {
REQUIRE(krbn::make_modifier_flag(krbn::key_code::caps_lock) == std::nullopt);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_control) == krbn::modifier_flag::left_control);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_shift) == krbn::modifier_flag::left_shift);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_option) == krbn::modifier_flag::left_option);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_command) == krbn::modifier_flag::left_command);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_control) == krbn::modifier_flag::right_control);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_shift) == krbn::modifier_flag::right_shift);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_option) == krbn::modifier_flag::right_option);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_command) == krbn::modifier_flag::right_command);
REQUIRE(krbn::make_modifier_flag(krbn::key_code::fn) == krbn::modifier_flag::fn);
REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)) == std::nullopt);
REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardErrorRollOver)) == std::nullopt);
REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardLeftShift)) == krbn::modifier_flag::left_shift);
REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::button, krbn::hid_usage(1)) == std::nullopt);
}
TEST_CASE("make_consumer_key_code") {
REQUIRE(krbn::make_consumer_key_code("mute") == krbn::consumer_key_code::mute);
REQUIRE(!krbn::make_consumer_key_code("unknown"));
REQUIRE(krbn::make_consumer_key_code_name(krbn::consumer_key_code::mute) == std::string("mute"));
REQUIRE(krbn::make_consumer_key_code_name(krbn::consumer_key_code(12345)) == std::string("(number:12345)"));
REQUIRE(krbn::make_consumer_key_code(krbn::hid_usage_page::consumer, krbn::hid_usage::csmr_mute) == krbn::consumer_key_code::mute);
REQUIRE(!krbn::make_consumer_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)));
REQUIRE(krbn::make_hid_usage_page(krbn::consumer_key_code::mute) == krbn::hid_usage_page::consumer);
REQUIRE(krbn::make_hid_usage(krbn::consumer_key_code::mute) == krbn::hid_usage::csmr_mute);
// from_json
{
nlohmann::json json("mute");
REQUIRE(krbn::consumer_key_code(json) == krbn::consumer_key_code::mute);
}
{
nlohmann::json json(static_cast<uint32_t>(krbn::consumer_key_code::mute));
REQUIRE(krbn::consumer_key_code(json) == krbn::consumer_key_code::mute);
}
{
nlohmann::json json;
REQUIRE_THROWS_AS(
krbn::consumer_key_code(json),
pqrs::json::unmarshal_error);
REQUIRE_THROWS_WITH(
krbn::key_code(json),
"json must be string or number, but is `null`");
}
{
nlohmann::json json("unknown_value");
REQUIRE_THROWS_AS(
krbn::consumer_key_code(json),
pqrs::json::unmarshal_error);
REQUIRE_THROWS_WITH(
krbn::consumer_key_code(json),
"unknown consumer_key_code: `\"unknown_value\"`");
}
}
TEST_CASE("make_pointing_button") {
REQUIRE(krbn::make_pointing_button("button1") == krbn::pointing_button::button1);
REQUIRE(!krbn::make_pointing_button("unknown"));
REQUIRE(krbn::make_pointing_button_name(krbn::pointing_button::button1) == std::string("button1"));
REQUIRE(krbn::make_pointing_button_name(krbn::pointing_button(12345)) == std::string("(number:12345)"));
{
auto actual = krbn::make_pointing_button(krbn::hid_usage_page(kHIDPage_Button),
krbn::hid_usage(1));
REQUIRE(*actual == krbn::pointing_button::button1);
}
{
auto actual = krbn::make_pointing_button(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad),
krbn::hid_usage(kHIDUsage_KeyboardTab));
REQUIRE(actual == std::nullopt);
}
}
| 46.90303 | 159 | 0.70513 | hymanat |
01b1224e96bd6bea7444be3a10d1e36c64bd2b44 | 168 | hpp | C++ | lib/language_framework.hpp | s9rA16Bf4/language_framework | 231b3a615be88f080329c98bfc46502e9d3777e6 | [
"MIT"
] | null | null | null | lib/language_framework.hpp | s9rA16Bf4/language_framework | 231b3a615be88f080329c98bfc46502e9d3777e6 | [
"MIT"
] | null | null | null | lib/language_framework.hpp | s9rA16Bf4/language_framework | 231b3a615be88f080329c98bfc46502e9d3777e6 | [
"MIT"
] | null | null | null | #ifndef MAIN_HPP
#define MAIN_HPP 1
#define FRAMEWORK_VERSION "1.0"
#include "custom.hpp"
// Base headers
#include "interpreter.hpp"
#include "function.hpp"
#endif
| 12.923077 | 31 | 0.744048 | s9rA16Bf4 |
01ba0c69d7e84f272c22ff4df5725eef1e7bee88 | 346 | hpp | C++ | approach_boost_serialization/bus_group_ser.hpp | noahleft/serialization | 731ebcee68339960308a86b25cf3c11ba815043e | [
"MIT"
] | null | null | null | approach_boost_serialization/bus_group_ser.hpp | noahleft/serialization | 731ebcee68339960308a86b25cf3c11ba815043e | [
"MIT"
] | null | null | null | approach_boost_serialization/bus_group_ser.hpp | noahleft/serialization | 731ebcee68339960308a86b25cf3c11ba815043e | [
"MIT"
] | null | null | null |
#ifndef BUS_GROUP_SER_HPP
#define BUS_GROUP_SER_HPP
#include "bus_group.hpp"
#include "bus_route_ser.hpp"
#include <boost/serialization/vector.hpp>
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive & ar, bus_group & obj, const unsigned int version) {
ar & obj.groups;
}
}
}
#endif | 18.210526 | 79 | 0.725434 | noahleft |
01bfc931d9d88c120c9f536aa2b045582dea02ff | 3,699 | cpp | C++ | utils/resoursecontainer.cpp | PLUkraine/Battle-City-Qt | 65eafe10cd86a79474a2dd1a2b3ea7d94450d59a | [
"MIT"
] | 1 | 2021-11-17T14:55:01.000Z | 2021-11-17T14:55:01.000Z | utils/resoursecontainer.cpp | PLUkraine/Battle-City-Qt | 65eafe10cd86a79474a2dd1a2b3ea7d94450d59a | [
"MIT"
] | null | null | null | utils/resoursecontainer.cpp | PLUkraine/Battle-City-Qt | 65eafe10cd86a79474a2dd1a2b3ea7d94450d59a | [
"MIT"
] | null | null | null | #include "resoursecontainer.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QDebug>
#include <iostream>
ResBag &ResBag::get()
{
static ResBag container;
return container;
}
QImage *ResBag::tankSprite()
{
return &m_tankSprite;
}
QImage *ResBag::bulletSprite()
{
return &m_bulletSprite;
}
QImage *ResBag::tilesSptites()
{
return m_tileSprites;
}
qreal ResBag::tankSize() const
{
return m_tankSize;
}
qreal ResBag::tileSize() const
{
return m_tileSize;
}
qreal ResBag::bulletSize() const
{
return m_bulletSize;
}
qreal ResBag::tankSpeed() const
{
return m_tankSpeed;
}
qreal ResBag::bulletSpeed() const
{
return m_bulletSpeed;
}
qreal ResBag::bulletDamage() const
{
return m_bulletDamage;
}
qreal ResBag::tankHealth() const
{
return m_tankHealth;
}
qreal *ResBag::tileHealth()
{
return m_tileHealth;
}
qreal ResBag::weaponCooldown() const
{
return m_weaponCooldown;
}
bool *ResBag::tileSolidness()
{
return m_tileSolidness;
}
int ResBag::timerInterval() const
{
return m_timerInterval;
}
int ResBag::playerTankHealth() const
{
return m_playerTankHealth;
}
QImage *ResBag::playerTankSprite()
{
return &m_playerTankSprite;
}
int ResBag::explosionDuration() const
{
return m_explosionDuration;
}
QImage *ResBag::explosionSprite()
{
return &m_explosionSprite;
}
ResBag::ResBag()
{
m_tileSprites[0] = QImage(":/sprites/air.png");
m_tileSprites[1] = QImage(":/sprites/wall.png");
m_tileSprites[2] = QImage(":/sprites/base.png");
m_tileSprites[3] = QImage(":/sprites/steel_wall.png");
m_tankSprite = QImage(":/sprites/tank_sprites.png");
m_bulletSprite = QImage(":/sprites/bullet.png");
m_playerTankSprite = QImage(":/sprites/player_sprites.png");
m_explosionSprite = QImage(":/sprites/explosion.png");
readConfigs();
}
void ResBag::readConfigs()
{
QFile file(":/config/gameconfig.json");
if (!file.exists())
handleError("File doesn't exist!");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray val = file.readAll();
file.close();
QJsonParseError er;
QJsonObject root = QJsonDocument::fromJson(val, &er).object();
if (er.error != QJsonParseError::NoError)
handleError("Error while reading config: " + er.errorString());
// read tank info
QJsonObject tank = root["tank"].toObject();
m_tankSize = tank["size"].toDouble();
m_tankHealth = tank["health"].toInt();
m_tankSpeed = tank["speed"].toDouble();
// read tile info
QJsonObject tile = root["tile"].toObject();
m_tileSize = tile["size"].toDouble();
QJsonArray data = tile["health"].toArray();
for (int i=0; i<data.count(); ++i) {
m_tileHealth[i] = data[i].toInt();
}
data = tile["solid"].toArray();
for (int i=0; i<data.count(); ++i) {
m_tileSolidness[i] = data[i].toBool();
}
// read bullet info
QJsonObject bullet = root["bullet"].toObject();
m_bulletSize = bullet["size"].toDouble();
m_bulletSpeed = bullet["speed"].toDouble();
m_bulletDamage = bullet["damage"].toInt();
// read weapon info
QJsonObject stdWeapon = root["standardWeapon"].toObject();
m_weaponCooldown = stdWeapon["cooldown"].toInt();
// read game info
m_timerInterval = root["game"].toObject()["timerInterval"].toInt();
// read player info
m_playerTankHealth = root["player"].toObject()["health"].toInt();
// read explosions info
m_explosionDuration = root["explosion"].toObject()["duration"].toInt();
}
void ResBag::handleError(QString message)
{
std::cerr << message.toStdString();
exit(1);
}
| 20.898305 | 75 | 0.664504 | PLUkraine |
01c5bea11288edf66001a4d5712488b6b7f5e786 | 3,572 | cpp | C++ | play_motion/play_motion/src/run_motion_node.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 7 | 2018-10-24T14:52:20.000Z | 2021-01-12T14:59:00.000Z | play_motion/play_motion/src/run_motion_node.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | null | null | null | play_motion/play_motion/src/run_motion_node.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 17 | 2019-09-29T10:22:41.000Z | 2021-04-08T12:38:37.000Z | /*
* Software License Agreement (Modified BSD License)
*
* Copyright (c) 2016, PAL Robotics, S.L.
* 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 PAL Robotics, S.L. 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.
*/
/** \author Jordi Pages. */
// C++ standard headers
#include <exception>
#include <string>
// Boost headers
#include <boost/shared_ptr.hpp>
// ROS headers
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <play_motion_msgs/PlayMotionAction.h>
// C++ standard headers
#include <cstdlib>
int main(int argc, char** argv)
{
// Init the ROS node
ros::init(argc, argv, "run_motion");
if ( argc < 2 )
{
ROS_INFO(" ");
ROS_INFO("Usage:");
ROS_INFO(" ");
ROS_INFO("\trosrun run_motion run_motion MOTION_NAME");
ROS_INFO(" ");
ROS_INFO("\twhere MOTION_NAME must be one of the motions listed in: ");
ROS_INFO_STREAM(std::system("rosparam list /play_motion/motions | grep joints | cut -d'/' -f4"));
ROS_INFO(" ");
return EXIT_FAILURE;
}
ROS_INFO("Starting run_motion application ...");
// Precondition: Valid clock
ros::NodeHandle nh;
if (!ros::Time::waitForValid(ros::WallDuration(10.0))) // NOTE: Important when using simulated clock
{
ROS_FATAL("Timed-out waiting for valid time.");
return EXIT_FAILURE;
}
actionlib::SimpleActionClient<play_motion_msgs::PlayMotionAction> client("/play_motion", true);
ROS_INFO("Waiting for Action Server ...");
client.waitForServer();
play_motion_msgs::PlayMotionGoal goal;
goal.motion_name = argv[1];
goal.skip_planning = false;
goal.priority = 0;
ROS_INFO_STREAM("Sending goal with motion: " << argv[1]);
client.sendGoal(goal);
ROS_INFO("Waiting for result ...");
bool actionOk = client.waitForResult(ros::Duration(30.0));
actionlib::SimpleClientGoalState state = client.getState();
if ( actionOk )
{
ROS_INFO_STREAM("Action finished successfully with state: " << state.toString());
}
else
{
ROS_ERROR_STREAM("Action failed with state: " << state.toString());
}
return EXIT_SUCCESS;
}
| 31.892857 | 103 | 0.707167 | hect1995 |
01cba97435271210885bf306469f7fe834e61162 | 1,133 | hpp | C++ | modules/services/pathfinder_cpp/bld/fsa.hpp | memristor/mep2 | bc5cddacba3d740f791f3454b8cb51bda83ce202 | [
"MIT"
] | 5 | 2018-11-27T15:15:00.000Z | 2022-02-10T21:44:13.000Z | modules/services/pathfinder_cpp/fsa.hpp | memristor/mep2 | bc5cddacba3d740f791f3454b8cb51bda83ce202 | [
"MIT"
] | 2 | 2018-10-20T15:48:40.000Z | 2018-11-20T05:11:33.000Z | modules/services/pathfinder_cpp/fsa.hpp | memristor/mep2 | bc5cddacba3d740f791f3454b8cb51bda83ce202 | [
"MIT"
] | 1 | 2020-02-07T12:44:47.000Z | 2020-02-07T12:44:47.000Z | #ifndef FSA_H
#define FSA_H
#include <cstring>
#include <iostream>
template <class T, int N = 100>
class FixedSizeAllocator
{
private:
struct FSAElem {
T userElement;
FSAElem *pNext;
};
FSAElem *m_pFirstFree;
int m_pMemory[(sizeof(FSAElem) * N) / sizeof(int) + 1];
public:
FixedSizeAllocator(bool clear_memory = false) {
m_pFirstFree = (FSAElem*)m_pMemory;
if(clear_memory) memset( m_pMemory, 0, sizeof(FSAElem) * N );
FSAElem *elem = m_pFirstFree;
for(unsigned int i=0; i<N; i++) {
elem->pNext = elem+1;
elem++;
}
(elem-1)->pNext = NULL;
}
template<class... Args>
T* alloc(Args&&... args) {
FSAElem *pNewNode;
if(!m_pFirstFree) {
std::cout << "NULLLLL !!!!!!! " << typeid(T).name() << " " << T::ref_count << "\n";
return NULL;
} else {
pNewNode = m_pFirstFree;
new (&pNewNode->userElement) T(args...);
m_pFirstFree = m_pFirstFree->pNext;
}
return reinterpret_cast<T*>(pNewNode);
}
void free(T *user_data) {
FSAElem *pNode = reinterpret_cast<FSAElem*>(user_data);
user_data->~T();
pNode->pNext = m_pFirstFree;
m_pFirstFree = pNode;
}
};
#endif
| 21.377358 | 86 | 0.633716 | memristor |
01d47a71ae639e745b34f274d99721d93d2b7a23 | 2,900 | cpp | C++ | Queue/Deque_Using_Circular_Array.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Queue/Deque_Using_Circular_Array.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Queue/Deque_Using_Circular_Array.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //Circular linked list using Array
#include<iostream>
#include<vector>
using namespace std;
struct CLL{
vector<int> arr;
int rear = -1;
int beg = -1;
int n = 0;
CLL(int n){
arr.resize(n);
this->n = n;
}
};
bool isFull(CLL* head){
if( head->beg == head->rear+1 ||
head->beg == 0 && head->rear == head->n-1)
return true;
else
return false;
}
bool isEmpty(CLL *head){
if(head->beg == -1 )
return true;
else
return false;
}
//for displaying the elements
void disp(CLL *head){
for(int i = 0; i<head->n; i++)
cout<<head->arr[i]<<" ";
cout<<endl;
}
//for insertion in End
void insertEnd(CLL *head,int data){
cout<<endl<<"*********************PUSH******************\n";
cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isFull(head))
return;
if(head->beg == -1)
head->beg =head->rear = 0;
else if(head->rear == head->n - 1)
head->rear = 0;
else
head->rear ++;
head->arr[head->rear] = data;
cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//insertion at Begining
void insertBegin(CLL *head,int data){
cout<<endl<<"*********************PUSH******************\n";
cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isFull(head))
return;
if(head->beg == -1)
head->beg =head->rear = 0;
//update the writable index for front position
else if(head->beg == 0)
head->beg = head->n -1;
else
head->beg --;
//push the element
head->arr[head->beg] = data;
cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//for deletion in begining
void delBegin(CLL *head){
cout<<endl<<"*********************POP******************\n";
cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isEmpty(head))
return;
if(head->beg == head->rear)
head->beg =head->rear = -1;
else if(head->beg == head->n -1)
head->beg = 0;
else
head->beg++;
cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//deleteion at end
void deleteEnd(CLL *head){
cout<<endl<<"*********************POP******************\n";
cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isEmpty(head))
return;
if(head->beg == head->rear)
head->beg = head->rear = -1;
else if(head->rear == 0)
head->rear = head->n -1 ;
else
head->rear--;
cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
int main(){
CLL *head = new CLL(5);
insertEnd(head,1);
insertEnd(head,2);
insertEnd(head,3);
delBegin(head);
delBegin(head);
//insertEnd(head,3);
insertEnd(head,4);
insertEnd(head,5);
insertEnd(head,6);
insertEnd(head,7);
insertEnd(head,8);
disp(head);
cout<<" **beg:"<<head->beg<<" rear:"<<head->rear<<endl;
delBegin(head);
delBegin(head);
delBegin(head);
deleteEnd(head);deleteEnd(head);
insertBegin(head,44);
insertEnd(head,55);
disp(head);
return 0;
}
| 20.714286 | 76 | 0.574828 | susantabiswas |
01d54580e79e3924267e5bf7b4ffc5a53ca7df96 | 1,300 | hpp | C++ | boost/spirit/home/support.hpp | mike-code/boost_1_38_0 | 7ff8b2069344ea6b0b757aa1f0778dfb8526df3c | [
"BSL-1.0"
] | 14 | 2017-03-07T00:14:33.000Z | 2022-02-09T00:59:22.000Z | boost/spirit/home/support.hpp | xin3liang/platform_external_boost | ac861f8c0f33538060790a8e50701464ca9982d3 | [
"BSL-1.0"
] | 11 | 2016-11-22T13:14:55.000Z | 2021-12-14T00:56:51.000Z | boost/spirit/home/support.hpp | xin3liang/platform_external_boost | ac861f8c0f33538060790a8e50701464ca9982d3 | [
"BSL-1.0"
] | 6 | 2016-11-07T13:38:45.000Z | 2021-04-04T12:13:31.000Z | /*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_SUPPORT_SEPTEMBER_26_2008_0340AM)
#define BOOST_SPIRIT_SUPPORT_SEPTEMBER_26_2008_0340AM
#include<boost/spirit/home/support/argument.hpp>
#include<boost/spirit/home/support/as_variant.hpp>
#include<boost/spirit/home/support/ascii.hpp>
#include<boost/spirit/home/support/attribute_of.hpp>
#include<boost/spirit/home/support/attribute_transform.hpp>
#include<boost/spirit/home/support/char_class.hpp>
#include<boost/spirit/home/support/component.hpp>
#include<boost/spirit/home/support/iso8859_1.hpp>
#include<boost/spirit/home/support/meta_grammar.hpp>
#include<boost/spirit/home/support/modifier.hpp>
#include<boost/spirit/home/support/multi_pass.hpp>
#include<boost/spirit/home/support/placeholders.hpp>
#include<boost/spirit/home/support/safe_bool.hpp>
#include<boost/spirit/home/support/standard.hpp>
#include<boost/spirit/home/support/standard_wide.hpp>
#include<boost/spirit/home/support/unused.hpp>
#endif
| 44.827586 | 80 | 0.715385 | mike-code |
01d57fb1fe3a45a224d7776f878e3eb2a5c76ffb | 5,766 | hpp | C++ | sdk/components/ElPack/Code/Source/ElPrinterPreview.hpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 10 | 2021-05-04T06:40:27.000Z | 2022-01-20T20:24:28.000Z | sdk/components/ElPack/Code/Source/ElPrinterPreview.hpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | sdk/components/ElPack/Code/Source/ElPrinterPreview.hpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2020-05-17T10:01:14.000Z | 2020-09-11T20:17:27.000Z | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'ElPrinterPreview.pas' rev: 6.00
#ifndef ElPrinterPreviewHPP
#define ElPrinterPreviewHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <ElEdits.hpp> // Pascal unit
#include <ElXPThemedControl.hpp> // Pascal unit
#include <Types.hpp> // Pascal unit
#include <ElCombos.hpp> // Pascal unit
#include <ElHook.hpp> // Pascal unit
#include <ElList.hpp> // Pascal unit
#include <ElSpin.hpp> // Pascal unit
#include <ElPrinter.hpp> // Pascal unit
#include <Printers.hpp> // Pascal unit
#include <ElTools.hpp> // Pascal unit
#include <ElACtrls.hpp> // Pascal unit
#include <StdCtrls.hpp> // Pascal unit
#include <ElPopBtn.hpp> // Pascal unit
#include <ElStatBar.hpp> // Pascal unit
#include <ElToolbar.hpp> // Pascal unit
#include <ElPanel.hpp> // Pascal unit
#include <ExtCtrls.hpp> // Pascal unit
#include <Dialogs.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Graphics.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Elprinterpreview
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TElPrinterPreviewDlg;
class PASCALIMPLEMENTATION TElPrinterPreviewDlg : public Forms::TForm
{
typedef Forms::TForm inherited;
__published:
Eltoolbar::TElToolBar* Toolbar;
Forms::TScrollBox* ScrollBox;
Elstatbar::TElStatusBar* StatusBar;
Eltoolbar::TElToolButton* PrintBtn;
Eltoolbar::TElToolButton* ElToolButton2;
Eltoolbar::TElToolButton* OnePageBtn;
Eltoolbar::TElToolButton* MultipageBtn;
Eltoolbar::TElToolButton* ElToolButton1;
Eltoolbar::TElToolButton* SaveBtn;
Eltoolbar::TElToolButton* ElToolButton3;
Dialogs::TPrintDialog* PrintDialog;
Eltoolbar::TElToolButton* PrintSetupBtn;
Eltoolbar::TElToolButton* PrevPageBtn;
Eltoolbar::TElToolButton* ElToolButton5;
Eltoolbar::TElToolButton* NextPageBtn;
Elspin::TElSpinEdit* PageSpin;
Dialogs::TPrinterSetupDialog* PrinterSetupDialog;
Dialogs::TSaveDialog* SaveDialog;
Elpopbtn::TElGraphicButton* CloseBtn;
Elpanel::TElPanel* PagesPanel;
Elpanel::TElPanel* MainPagePanel;
Elhook::TElHook* ElHook1;
Elcombos::TElComboBox* ScaleCombo;
void __fastcall PrintBtnClick(System::TObject* Sender);
void __fastcall ScrollBoxResize(System::TObject* Sender);
void __fastcall MainPagePanelPaint(System::TObject* Sender);
void __fastcall PageSpinChange(System::TObject* Sender);
void __fastcall FormCreate(System::TObject* Sender);
void __fastcall FormDestroy(System::TObject* Sender);
void __fastcall ScaleComboExit(System::TObject* Sender);
void __fastcall NextPageBtnClick(System::TObject* Sender);
void __fastcall PrintSetupBtnClick(System::TObject* Sender);
void __fastcall CloseBtnClick(System::TObject* Sender);
void __fastcall SaveBtnClick(System::TObject* Sender);
void __fastcall FormShow(System::TObject* Sender);
void __fastcall PrevPageBtnClick(System::TObject* Sender);
void __fastcall ScComboKeyDown(System::TObject* Sender, Word &Key, Classes::TShiftState Shift);
void __fastcall ElHook1AfterProcess(System::TObject* Sender, Messages::TMessage &Msg, bool &Handled);
void __fastcall FormResize(System::TObject* Sender);
void __fastcall ScaleComboChange(System::TObject* Sender);
void __fastcall MultipageBtnClick(System::TObject* Sender);
void __fastcall OnePageBtnClick(System::TObject* Sender);
private:
int FScale;
int FCurrentPage;
int FTotalPages;
Ellist::TElList* Panels;
int PagePanels;
int HorzPages;
int VertPages;
Elprinter::TElPrinter* FPrinter;
int FScaleIdx;
int FRealIdx;
void __fastcall SetCurrentPage(int Value);
void __fastcall SetTotalPages(int Value);
void __fastcall SetScale(int Value);
protected:
void __fastcall UpdatePageNumbers(void);
void __fastcall UpdatePanels(void);
void __fastcall UpdateMultiPage(void);
public:
void __fastcall SetData(Elprinter::TElPrinter* Printer);
__property int CurrentPage = {read=FCurrentPage, write=SetCurrentPage, nodefault};
__property int TotalPages = {read=FTotalPages, write=SetTotalPages, nodefault};
__property int Scale = {read=FScale, write=SetScale, nodefault};
public:
#pragma option push -w-inl
/* TCustomForm.Create */ inline __fastcall virtual TElPrinterPreviewDlg(Classes::TComponent* AOwner) : Forms::TForm(AOwner) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.CreateNew */ inline __fastcall virtual TElPrinterPreviewDlg(Classes::TComponent* AOwner, int Dummy) : Forms::TForm(AOwner, Dummy) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.Destroy */ inline __fastcall virtual ~TElPrinterPreviewDlg(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWinControl.CreateParented */ inline __fastcall TElPrinterPreviewDlg(HWND ParentWindow) : Forms::TForm(ParentWindow) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE TElPrinterPreviewDlg* ElPrinterPreviewDlg;
} /* namespace Elprinterpreview */
using namespace Elprinterpreview;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // ElPrinterPreview
| 38.44 | 150 | 0.723205 | acidicMercury8 |
01d5c788095fbab27a97f5f1d5c7ba0767d668b4 | 1,475 | hpp | C++ | AI-and-Analytics/End-to-end-Workloads/LidarObjectDetection-PointPillars/include/pointpillars/scan.hpp | tiwaria1/oneAPI-samples | 18310adf63c7780715f24034acfb0bf01d15521f | [
"MIT"
] | 310 | 2020-07-09T01:00:11.000Z | 2022-03-31T17:52:14.000Z | AI-and-Analytics/End-to-end-Workloads/LidarObjectDetection-PointPillars/include/pointpillars/scan.hpp | tiwaria1/oneAPI-samples | 18310adf63c7780715f24034acfb0bf01d15521f | [
"MIT"
] | 438 | 2020-06-30T23:25:19.000Z | 2022-03-31T00:37:13.000Z | AI-and-Analytics/End-to-end-Workloads/LidarObjectDetection-PointPillars/include/pointpillars/scan.hpp | junxnone/oneAPI-samples | f414747b5676688d690655c6043b71577027fc19 | [
"MIT"
] | 375 | 2020-06-04T22:58:24.000Z | 2022-03-30T11:04:18.000Z | /*
* Copyright 2018-2019 Autoware Foundation. All rights reserved.
* Copyright (c) 2019-2021 Intel Corporation (oneAPI modifications)
*
* 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
#include <CL/sycl.hpp>
#include <cstdint>
namespace pointpillars {
// Prefix sum in 2D coordinates
//
// These functions calculate the cumulative sum along X or Y in a 2D array
//
// X--->
// W
// Y o-------------
// | |
// | H |
// v |
// |
//
// For details about the algorithm please check:
// Sengupta, Shubhabrata & Lefohn, Aaron & Owens, John. (2006). A Work-Efficient Step-Efficient Prefix Sum Algorithm.
//
// Prefix in x-direction, calculates the cumulative sum along x
void ScanX(int *dev_output, const int *dev_input, int w, int h, int n);
// Prefix in y-direction, calculates the cumulative sum along y
void ScanY(int *dev_output, const int *dev_input, int w, int h, int n);
} // namespace pointpillars
| 31.382979 | 119 | 0.690847 | tiwaria1 |
01d720531878bd2fe18bf2ebd3f132f11388b591 | 3,447 | cpp | C++ | Engine/Source/FishEditor/UI/UIGameObjectHeader.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Source/FishEditor/UI/UIGameObjectHeader.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Source/FishEditor/UI/UIGameObjectHeader.cpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #include "UIGameObjectHeader.hpp"
#include "ui_UIGameObjectHeader.h"
#include <FishEngine/GameObject.hpp>
#include <FishEngine/LayerMask.hpp>
#include <FishEngine/TagManager.hpp>
#include "UIDebug.hpp"
UIGameObjectHeader::UIGameObjectHeader(QWidget *parent) :
QWidget(parent),
ui(new Ui::UIGameObjectHeader)
{
ui->setupUi(this);
connect(ui->layer,
static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this,
&UIGameObjectHeader::OnLayerChanged);
connect(ui->tag,
static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this,
&UIGameObjectHeader::OnTagChanged);
connect(ui->activeCheckBox,
&QCheckBox::toggled,
this,
&UIGameObjectHeader::OnActiveCheckBoxChanged);
connect(ui->nameEdit,
&QLineEdit::editingFinished,
this,
&UIGameObjectHeader::OnNameChanged);
}
UIGameObjectHeader::~UIGameObjectHeader()
{
delete ui;
}
void UIGameObjectHeader::Bind(std::shared_ptr<FishEngine::GameObject> go)
{
if (m_changed)
{
LogInfo("[UpdateInspector] changed from UI");
go->setName(m_name);
go->setLayer(m_layerIndex);
//go->setTag();
go->m_tagIndex = m_tagIndex;
go->SetActive(m_isActive);
m_changed = false;
return;
}
if (m_isActive != go->activeSelf())
{
m_isActive = go->activeSelf();
LOG;
ui->activeCheckBox->blockSignals(true);
ui->activeCheckBox->setChecked(m_isActive);
ui->activeCheckBox->blockSignals(false);
}
if (m_name != go->name())
{
m_name = go->name();
LOG;
ui->nameEdit->blockSignals(true);
ui->nameEdit->setText(m_name.c_str());
ui->nameEdit->blockSignals(false);
}
// update Layer items
if (m_layerDirtyFlag != FishEngine::LayerMask::s_editorFlag)
{
LogInfo("[UpdateInspector] Update Layers");
QStringList layers;
auto const & layerNames = FishEngine::LayerMask::allLayerNames();
for (auto const & n : layerNames)
{
if (!n.empty())
layers << n.c_str();
}
ui->layer->blockSignals(true);
ui->layer->clear();
ui->layer->addItems(layers);
ui->layer->blockSignals(false);
m_layerDirtyFlag = FishEngine::LayerMask::s_editorFlag;
}
if (m_layerIndex != go->layer())
{
m_layerIndex = go->layer();
LOG;
ui->layer->blockSignals(true);
ui->layer->setCurrentIndex(m_layerIndex);
ui->layer->blockSignals(false);
}
// update Tag items
if (m_tagDirtyFlag != FishEngine::TagManager::s_editorFlag)
{
LogInfo("[UpdateInspector] Update Tags");
QStringList tags;
//auto const & all_tags = FishEngine::TagManager::s_tags;
for (auto const & n : FishEngine::TagManager::s_tags)
{
if (!n.empty())
tags << n.c_str();
}
ui->tag->blockSignals(true);
ui->tag->clear();
ui->tag->addItems(tags);
ui->tag->blockSignals(false);
m_tagDirtyFlag = FishEngine::TagManager::s_editorFlag;
}
if (m_tagIndex != go->m_tagIndex)
{
m_tagIndex = go->m_tagIndex;
LOG;
ui->tag->blockSignals(true);
ui->tag->setCurrentIndex(m_tagIndex);
ui->tag->blockSignals(false);
}
}
void UIGameObjectHeader::OnNameChanged()
{
auto name = ui->nameEdit->text().toStdString();
if (m_name != name)
{
m_name = name;
LOG;
m_changed = true;
}
}
void UIGameObjectHeader::OnActiveCheckBoxChanged(bool active)
{
m_isActive = active;
LOG;
m_changed = true;
}
void UIGameObjectHeader::OnLayerChanged(int index)
{
m_layerIndex = index;
LOG;
m_changed = true;
}
void UIGameObjectHeader::OnTagChanged(int index)
{
m_tagIndex = index;
LOG;
m_changed = true;
}
| 21.147239 | 73 | 0.695968 | ValtoGameEngines |
01dae4597e51fbaae1349b408354461803c38b19 | 4,852 | cpp | C++ | 2.0/SensorPlacement.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | 7 | 2021-10-29T20:29:48.000Z | 2022-03-03T01:38:45.000Z | 2.0/SensorPlacement.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | null | null | null | 2.0/SensorPlacement.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 The Android Open Source Project
* Copyright (C) 2020 STMicroelectronics
*
* 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 <cmath>
#include <IConsole.h>
#include "SensorPlacement.h"
SensorPlacement::SensorPlacement(void)
: data({ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f })
{
}
/**
* getPayload: return the payload of the sensor placement (4x3 matrix)
*
* Return value: array of 12 elements representing the 4x3 matrix.
*/
const std::array<float, 12> &SensorPlacement::getPayload(void) const
{
return data;
}
/**
* loadFromProp: load the sensor placement data from system properties
* @sensorType: sensor type.
*/
void SensorPlacement::loadFromProp(stm::core::SensorType sensorType)
{
stm::core::PropertiesManager& propertiesManager = stm::core::PropertiesManager::getInstance();
std::array<float, 3> sensorPosition;
Matrix<3, 3, float> rotMatrix;
using stm::core::SensorType;
switch (sensorType) {
case SensorType::ACCELEROMETER:
case SensorType::ACCELEROMETER_UNCALIBRATED:
case SensorType::GRAVITY:
case SensorType::LINEAR_ACCELERATION:
rotMatrix = propertiesManager.getRotationMatrix(SensorType::ACCELEROMETER);
sensorPosition = propertiesManager.getSensorPlacement(SensorType::ACCELEROMETER);
break;
case SensorType::MAGNETOMETER:
case SensorType::MAGNETOMETER_UNCALIBRATED:
case SensorType::GEOMAGNETIC_ROTATION_VECTOR:
rotMatrix = propertiesManager.getRotationMatrix(SensorType::MAGNETOMETER);
sensorPosition = propertiesManager.getSensorPlacement(SensorType::MAGNETOMETER);
break;
case SensorType::GYROSCOPE:
case SensorType::GYROSCOPE_UNCALIBRATED:
case SensorType::ORIENTATION:
case SensorType::ROTATION_VECTOR:
case SensorType::GAME_ROTATION_VECTOR:
rotMatrix = propertiesManager.getRotationMatrix(SensorType::GYROSCOPE);
sensorPosition = propertiesManager.getSensorPlacement(SensorType::GYROSCOPE);
break;
case SensorType::PRESSURE:
rotMatrix = propertiesManager.getRotationMatrix(sensorType);
sensorPosition = propertiesManager.getSensorPlacement(sensorType);
break;
default:
return;
}
if (!invertRotationMatrix(rotMatrix)) {
stm::core::IConsole& console = stm::core::IConsole::getInstance();
console.error("failed to invert the rotation matrix, check input matrix!");
return;
}
int counter = 0;
for (auto row = 0U; row < 3; ++row) {
for (auto col = 0U; col < 3; ++col) {
data[counter++] = rotMatrix[row][col];
}
data[counter++] = sensorPosition[row];
}
}
bool SensorPlacement::invertRotationMatrix(Matrix<3, 3, float>& matrix)
{
Matrix<3, 3, float> invMatrix;
invMatrix[0][0] = matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1];
invMatrix[1][0] = -(matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]);
invMatrix[2][0] = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0];
float determinant = matrix[0][0] * invMatrix[0][0] +
matrix[0][1] * invMatrix[1][0] +
matrix[0][2] * invMatrix[2][0];
if (determinant < 1e-6) {
return false;
}
invMatrix[1][1] = matrix[2][2] * matrix[0][0] - matrix[2][0] * matrix[0][2];
invMatrix[2][1] = -(matrix[2][1] * matrix[0][0] - matrix[2][0] * matrix[0][1]);
invMatrix[2][2] = matrix[1][1] * matrix[0][0] - matrix[1][0] * matrix[0][1];
if ((std::fabs(matrix[0][1] - matrix[1][0]) < 1e-6) &&
(std::fabs(matrix[0][2] - matrix[2][0]) < 1e-6) &&
(std::fabs(matrix[1][2] - matrix[2][1]) < 1e-6)) {
invMatrix[0][1] = invMatrix[1][0];
invMatrix[0][2] = invMatrix[2][0];
invMatrix[1][2] = invMatrix[2][1];
} else {
invMatrix[0][1] = -(matrix[2][2] * matrix[0][1] - matrix[2][1] * matrix[0][2]);
invMatrix[0][2] = matrix[1][2] * matrix[0][1] - matrix[1][1] * matrix[0][2];
invMatrix[1][2] = -(matrix[1][2] * matrix[0][0] - matrix[1][0] * matrix[0][2]);
}
for (auto row = 0; row < 3; ++row) {
for (auto col = 0; col < 3; ++col) {
invMatrix[row][col] /= determinant;
}
}
matrix = invMatrix;
return true;
} | 35.940741 | 98 | 0.634996 | STMicroelectronics |
01dcf6d7a7b9d9eb39557865ab2878023d65ec3a | 1,931 | cpp | C++ | src/Engine/UI/ListGUI.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | src/Engine/UI/ListGUI.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | src/Engine/UI/ListGUI.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | #include "ListGUILocal.h"
void ListGUILocal::StateChanged()
{
if (!_stateUpdates)
return;
int i;
for (i = 0; i < Num(); i++)
_gui->SetStateString(va("%s_item_%i", _name.c_str(), i), (*this)[i].c_str());
for (i = Num(); i < _water; i++)
_gui->SetStateString(va("%s_item_%i", m_name.c_str(), i), "");
_water = Num();
_gui->StateChanged(Sys_Milliseconds());
}
int ListGUILocal::GetNumSelections()
{
return _gui->State().GetInt(va("%s_numsel", _name.c_str()));
}
int ListGUILocal::GetSelection(char *s, int size, int _sel) const
{
if (s)
s[0] = '\0';
int sel = _gui->State().GetInt(va("%s_sel_%i", _name.c_str(), _sel), "-1");
if (sel == -1 || sel >= _ids.Num())
return -1;
if (s)
idStr::snPrintf(s, size, _gui->State().GetString(va("%s_item_%i", _name.c_str(), sel), ""));
// don't let overflow
if (sel >= _ids.Num())
sel = 0;
_gui->SetStateInt(va("%s_selid_0", _name.c_str()), _ids[sel]);
return m_ids[sel];
}
void ListGUILocal::SetSelection(int sel)
{
_gui->SetStateInt(va("%s_sel_0", _name.c_str()), sel);
StateChanged();
}
void ListGUILocal::Add(int id, const string &s)
{
int i = _ids.FindIndex(id);
if (i == -1) {
Append(s);
m_ids.Append(id);
}
else
(*this)[i] = s;
StateChanged();
}
void ListGUILocal::Push(const string &s)
{
Append(s);
_ids.Append(_ids.Num());
StateChanged();
}
bool ListGUILocal::Del(int id)
{
int i = _ids.FindIndex(id);
if (i == -1)
return false;
_ids.RemoveIndex(i);
this->RemoveIndex(i);
StateChanged();
return true;
}
void ListGUILocal::Clear() {
_ids.Clear();
vector<string, TAG_OLD_UI>::Clear();
if (_gui) // will clear all the GUI variables and will set m_water back to 0
StateChanged();
}
bool ListGUILocal::IsConfigured() const { return (_gui != nullptr); }
void ListGUILocal::SetStateChanges(bool enable)
{
_stateUpdates = enable;
StateChanged();
}
void ListGUILocal::Shutdown()
{
_gui = nullptr;
_name.Clear();
Clear();
}
| 20.542553 | 94 | 0.640601 | BclEx |
01dea22851ce7efe9a2305c72028f7b12edadc08 | 5,978 | hpp | C++ | src/util/raft/node.hpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | 1 | 2022-02-07T22:36:36.000Z | 2022-02-07T22:36:36.000Z | src/util/raft/node.hpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | null | null | null | src/util/raft/node.hpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | null | null | null | // Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OPENCBDC_TX_SRC_RAFT_NODE_H_
#define OPENCBDC_TX_SRC_RAFT_NODE_H_
#include "console_logger.hpp"
#include "state_manager.hpp"
#include "util/common/config.hpp"
#include "util/network/connection_manager.hpp"
#include <libnuraft/nuraft.hxx>
namespace cbdc::raft {
/// A NuRaft state machine execution result.
using result_type = nuraft::cmd_result<nuraft::ptr<nuraft::buffer>>;
/// Function type for raft state machine execution result callbacks.
using callback_type
= std::function<void(result_type& r,
nuraft::ptr<std::exception>& err)>;
/// \brief A node in a raft cluster.
///
/// Wrapper for replicated state machine functionality using raft from the
/// external library NuRaft. Builds a cluster with other raft
/// nodes. Uses NuRaft to durably replicate log entries between a quorum of
/// raft nodes. Callers provide a state machine to execute the log entries
/// and return the execution result.
class node {
public:
node() = delete;
node(const node&) = delete;
auto operator=(const node&) -> node& = delete;
node(node&&) = delete;
auto operator=(node&&) -> node& = delete;
/// Constructor.
/// \param node_id identifier of the node in the raft cluster. Must be
/// 0 or greater.
/// \param raft_endpoint TCP endpoint upon which to listen for incoming raft
/// connections.
/// \param node_type name of the raft cluster this node will be part
/// of.
/// \param blocking true if replication calls should block until the
/// state machine makes an execution result available.
/// \param sm pointer to the state machine replicated by the cluster.
/// \param asio_thread_pool_size number of threads for processing raft
/// messages. Set to 0 to use the number
/// of cores on the system.
/// \param logger log instance NuRaft should use.
/// \param raft_cb NuRaft callback to report raft events.
node(int node_id,
const network::endpoint_t& raft_endpoint,
const std::string& node_type,
bool blocking,
nuraft::ptr<nuraft::state_machine> sm,
size_t asio_thread_pool_size,
std::shared_ptr<logging::log> logger,
nuraft::cb_func::func_type raft_cb);
~node();
/// Initializes the NuRaft instance with the given state machine and
/// raft parameters.
/// \param raft_params NuRaft-specific parameters for the raft node.
/// \return true if the raft node initialized successfully.
auto init(const nuraft::raft_params& raft_params) -> bool;
/// Connect to each of the given raft nodes and join them to the
/// cluster. If this node is not node 0, this method blocks until
/// node 0 joins this node to the cluster.
/// \param raft_servers node endpoints of the other raft nodes in the
/// cluster.
/// \return true if adding the nodes to the raft cluster succeeded.
auto
build_cluster(const std::vector<network::endpoint_t>& raft_servers)
-> bool;
/// Indicates whether this node is the current raft leader.
/// \return true if this node is the leader.
[[nodiscard]] auto is_leader() const -> bool;
/// Replicates the given log entry in the cluster. Calls the given
/// callback with the state machine execution result.
/// \param new_log log entry to replicate.
/// \param result_fn callback function to call asynchronously with the
/// state machine execution result.
/// \return true if the log entry was accepted for replication.
[[nodiscard]] auto replicate(nuraft::ptr<nuraft::buffer> new_log,
const callback_type& result_fn) const
-> bool;
/// Replicates the provided log entry and returns the results from the
/// state machine if the replication was successful. The method will
/// block until the result is available or replication has failed.
/// \param new_log raft log entry to replicate
/// \return result from state machine or empty optional if replication
/// failed
[[nodiscard]] auto
replicate_sync(const nuraft::ptr<nuraft::buffer>& new_log) const
-> std::optional<nuraft::ptr<nuraft::buffer>>;
/// Returns the last replicated log index.
/// \return log index.
[[nodiscard]] auto last_log_idx() const -> uint64_t;
/// Returns a pointer to the state machine replicated by this raft
/// node.
/// \return pointer to the state machine.
[[nodiscard]] auto get_sm() const -> nuraft::state_machine*;
/// Shut down the NuRaft instance.
void stop();
private:
uint32_t m_node_id;
bool m_blocking;
int m_port;
nuraft::ptr<nuraft::logger> m_raft_logger;
nuraft::ptr<state_manager> m_smgr;
nuraft::ptr<nuraft::state_machine> m_sm;
nuraft::raft_launcher m_launcher;
nuraft::ptr<nuraft::raft_server> m_raft_instance;
nuraft::asio_service::options m_asio_opt;
nuraft::raft_server::init_options m_init_opts;
[[nodiscard]] auto add_cluster_nodes(
const std::vector<network::endpoint_t>& raft_servers) const
-> bool;
};
}
#endif // OPENCBDC_TX_SRC_RAFT_NODE_H_
| 43.007194 | 84 | 0.620442 | vipinsun |
01e311d5e32d8ad2ab4cf442fdd81a5f30d2f25c | 781 | cpp | C++ | POINTMEE.cpp | Himanshu1801/codechef | 100785c10f49e5200e82e68f10d7a6213b31b821 | [
"Apache-2.0"
] | null | null | null | POINTMEE.cpp | Himanshu1801/codechef | 100785c10f49e5200e82e68f10d7a6213b31b821 | [
"Apache-2.0"
] | null | null | null | POINTMEE.cpp | Himanshu1801/codechef | 100785c10f49e5200e82e68f10d7a6213b31b821 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
int x[n],y[n];
int count=0,k,a,b;
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>x[i];
cin>>y[i];
}
for (int i = 0; i < n; i++)
{
if (/* condition */)
{
x[i]=x[i]+k;
count++;
}
else if (/* condition */)
{
y[i]=y[i]+k;
count++;
}
else if (/* condition */)
{
x[i]=x[i]+k;
y[i]=y[i]+k;
count++;
}
else if (/* condition */)
{
x[i]=x[i]+k;
y[i]=y[i]-k;
count++;
}
}
}
return 0;
} | 16.617021 | 36 | 0.289373 | Himanshu1801 |
01e63b3d3b4f3693998e7cba41be6caf0e4e662e | 6,728 | cpp | C++ | third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistrationContext.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistrationContext.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistrationContext.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | /*
* Copyright (C) 2013 Google Inc. 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.
* 3. Neither the name of Google Inc. 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.
*/
#include "core/dom/custom/V0CustomElementRegistrationContext.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/custom/V0CustomElement.h"
#include "core/dom/custom/V0CustomElementDefinition.h"
#include "core/dom/custom/V0CustomElementScheduler.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLUnknownElement.h"
#include "core/svg/SVGUnknownElement.h"
namespace blink {
V0CustomElementRegistrationContext::V0CustomElementRegistrationContext()
: m_candidates(V0CustomElementUpgradeCandidateMap::create()) {}
void V0CustomElementRegistrationContext::registerElement(
Document* document,
V0CustomElementConstructorBuilder* constructorBuilder,
const AtomicString& type,
V0CustomElement::NameSet validNames,
ExceptionState& exceptionState) {
V0CustomElementDefinition* definition = m_registry.registerElement(
document, constructorBuilder, type, validNames, exceptionState);
if (!definition)
return;
// Upgrade elements that were waiting for this definition.
V0CustomElementUpgradeCandidateMap::ElementSet* upgradeCandidates =
m_candidates->takeUpgradeCandidatesFor(definition->descriptor());
if (!upgradeCandidates)
return;
for (const auto& candidate : *upgradeCandidates)
V0CustomElement::define(candidate, definition);
}
Element* V0CustomElementRegistrationContext::createCustomTagElement(
Document& document,
const QualifiedName& tagName) {
DCHECK(V0CustomElement::isValidName(tagName.localName()));
Element* element;
if (HTMLNames::xhtmlNamespaceURI == tagName.namespaceURI()) {
element = HTMLElement::create(tagName, document);
} else if (SVGNames::svgNamespaceURI == tagName.namespaceURI()) {
element = SVGUnknownElement::create(tagName, document);
} else {
// XML elements are not custom elements, so return early.
return Element::create(tagName, &document);
}
element->setV0CustomElementState(Element::V0WaitingForUpgrade);
resolveOrScheduleResolution(element, nullAtom);
return element;
}
void V0CustomElementRegistrationContext::didGiveTypeExtension(
Element* element,
const AtomicString& type) {
resolveOrScheduleResolution(element, type);
}
void V0CustomElementRegistrationContext::resolveOrScheduleResolution(
Element* element,
const AtomicString& typeExtension) {
// If an element has a custom tag name it takes precedence over
// the "is" attribute (if any).
const AtomicString& type = V0CustomElement::isValidName(element->localName())
? element->localName()
: typeExtension;
DCHECK(!type.isNull());
V0CustomElementDescriptor descriptor(type, element->namespaceURI(),
element->localName());
DCHECK_EQ(element->getV0CustomElementState(), Element::V0WaitingForUpgrade);
V0CustomElementScheduler::resolveOrScheduleResolution(this, element,
descriptor);
}
void V0CustomElementRegistrationContext::resolve(
Element* element,
const V0CustomElementDescriptor& descriptor) {
V0CustomElementDefinition* definition = m_registry.find(descriptor);
if (definition) {
V0CustomElement::define(element, definition);
} else {
DCHECK_EQ(element->getV0CustomElementState(), Element::V0WaitingForUpgrade);
m_candidates->add(descriptor, element);
}
}
void V0CustomElementRegistrationContext::setIsAttributeAndTypeExtension(
Element* element,
const AtomicString& type) {
DCHECK(element);
DCHECK(!type.isEmpty());
element->setAttribute(HTMLNames::isAttr, type);
setTypeExtension(element, type);
}
void V0CustomElementRegistrationContext::setTypeExtension(
Element* element,
const AtomicString& type) {
if (!element->isHTMLElement() && !element->isSVGElement())
return;
V0CustomElementRegistrationContext* context =
element->document().registrationContext();
if (!context)
return;
if (element->isV0CustomElement()) {
// This can happen if:
// 1. The element has a custom tag, which takes precedence over
// type extensions.
// 2. Undoing a command (eg ReplaceNodeWithSpan) recycles an
// element but tries to overwrite its attribute list.
return;
}
// Custom tags take precedence over type extensions
DCHECK(!V0CustomElement::isValidName(element->localName()));
if (!V0CustomElement::isValidName(type))
return;
element->setV0CustomElementState(Element::V0WaitingForUpgrade);
context->didGiveTypeExtension(element,
element->document().convertLocalName(type));
}
bool V0CustomElementRegistrationContext::nameIsDefined(
const AtomicString& name) const {
return m_registry.nameIsDefined(name);
}
void V0CustomElementRegistrationContext::setV1(
const CustomElementRegistry* v1) {
m_registry.setV1(v1);
}
DEFINE_TRACE(V0CustomElementRegistrationContext) {
visitor->trace(m_candidates);
visitor->trace(m_registry);
}
} // namespace blink
| 36.172043 | 80 | 0.740785 | google-ar |
01e69ef705f15f6c4b90c8afae2b1e1ed68d18aa | 5,895 | cpp | C++ | cpp/tools/networked-storage/main.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | cpp/tools/networked-storage/main.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | cpp/tools/networked-storage/main.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | //
// main.cpp
//
// Created by Peter Gusev on 9 October 2018.
// Copyright 2013-2018 Regents of the University of California
//
#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <execinfo.h>
#include <boost/asio.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
#include <ndn-cpp/threadsafe-face.hpp>
#include <ndn-cpp/security/key-chain.hpp>
#include <ndn-cpp/security/certificate/identity-certificate.hpp>
#include <ndn-cpp/util/memory-content-cache.hpp>
#include <ndn-cpp/security/pib/pib-memory.hpp>
#include <ndn-cpp/security/tpm/tpm-back-end-memory.hpp>
#include <ndn-cpp/security/policy/no-verify-policy-manager.hpp>
#include "../../contrib/docopt/docopt.h"
#include "../../include/name-components.hpp"
#include "../../include/simple-log.hpp"
#include "../../include/storage-engine.hpp"
static const char USAGE[] =
R"(Networked Storage.
Usage:
networked-storage <db_path> [--verbose]
Arguments:
<db_path> Path to persistent storage DB
Options:
-v --verbose Verbose output
)";
using namespace std;
using namespace ndn;
using namespace ndnrtc;
static bool mustExit = false;
void registerPrefix(boost::shared_ptr<Face> &face, const Name &prefix,
boost::shared_ptr<StorageEngine> storage);
void handler(int sig)
{
void *array[10];
size_t size;
if (sig == SIGABRT || sig == SIGSEGV)
{
fprintf(stderr, "Received signal %d:\n", sig);
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
else
mustExit = true;
}
int main(int argc, char **argv)
{
signal(SIGABRT, handler);
signal(SIGSEGV, handler);
signal(SIGINT, &handler);
signal(SIGUSR1, &handler);
ndnlog::new_api::Logger::initAsyncLogging();
map<string, docopt::value> args
= docopt::docopt(USAGE,
{ argv + 1, argv + argc },
true, // show help if requested
(string("Netowkred Storage ")+string(PACKAGE_VERSION)).c_str()); // version string
// for(auto const& arg : args) {
// cout << arg.first << " " << arg.second << endl;
// }
ndnlog::new_api::Logger::getLogger("").setLogLevel(args["--verbose"].asBool() ? ndnlog::NdnLoggerDetailLevelAll : ndnlog::NdnLoggerDetailLevelDefault);
int err = 0;
boost::asio::io_service io;
boost::shared_ptr<boost::asio::io_service::work> work(boost::make_shared<boost::asio::io_service::work>(io));
boost::thread t([&io, &err]() {
try
{
io.run();
}
catch (exception &e)
{
LogError("") << "Caught exception while running: " << e.what() << endl;
err = 1;
}
});
// setup storage
boost::shared_ptr<StorageEngine> storage =
boost::make_shared<StorageEngine>(args["<db_path>"].asString(), true);
// setup face and keychain
boost::shared_ptr<Face> face = boost::make_shared<ThreadsafeFace>(io);
boost::shared_ptr<KeyChain> keyChain = boost::make_shared<KeyChain>();
face->setCommandSigningInfo(*keyChain, keyChain->getDefaultCertificateName());
LogInfo("") << "Scanning available prefixes..." << std::endl;
storage->scanForLongestPrefixes(io, [&face, storage](const vector<Name>& pp){
LogInfo("") << "Scan completed. total keys: " << storage->getKeysNum()
<< ", payload size ~ " << storage->getPayloadSize()/1024/1024
<< "MB, number of longest prefixes: " << pp.size() << endl;
for (auto n:pp)
LogInfo("") << "\t" << n << endl;
for (auto n:pp)
registerPrefix(face, n, storage);
});
{
while (!(err || mustExit))
{
usleep(10);
}
}
LogInfo("") << "Shutting down gracefully..." << endl;
keyChain.reset();
face->shutdown();
face.reset();
work.reset();
t.join();
io.stop();
LogInfo("") << "done" << endl;
}
void registerPrefix(boost::shared_ptr<Face> &face, const Name &prefix,
boost::shared_ptr<StorageEngine> storage)
{
LogInfo("") << "Registering prefix " << prefix << std::endl;
face->registerPrefix(prefix,
[storage](const boost::shared_ptr<const Name> &prefix,
const boost::shared_ptr<const Interest> &interest,
Face &face, uint64_t, const boost::shared_ptr<const InterestFilter> &)
{
LogTrace("") << "Incoming interest " << interest->getName() << std::endl;
boost::shared_ptr<Data> d = storage->read(*interest);
if (d)
{
LogTrace("") << "Retrieved data of size " << d->getContent().size()
<< ": " << d->getName() << std::endl;
face.putData(*d);
}
else
LogTrace("") << "no data for " << interest->getName() << std::endl;
},
[](const boost::shared_ptr<const Name> &prefix)
{
LogError("") << "Prefix registration failure (" << prefix << ")" << std::endl;
},
[](const boost::shared_ptr<const Name> &p, uint64_t)
{
LogInfo("") << "Successfully registered prefix " << *p << std::endl;
});
} | 33.117978 | 155 | 0.543172 | luckiday |
5434c523ba9205b5e96f81960fd54474a4ec1f6d | 4,893 | cpp | C++ | cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #include "VisualScriptPropertyGet.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
namespace godot {
VisualScriptPropertyGet::___method_bindings VisualScriptPropertyGet::___mb = {};
void VisualScriptPropertyGet::___init_method_bindings() {
___mb.mb__get_type_cache = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "_get_type_cache");
___mb.mb__set_type_cache = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "_set_type_cache");
___mb.mb_get_base_path = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_path");
___mb.mb_get_base_script = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_script");
___mb.mb_get_base_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_type");
___mb.mb_get_basic_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_basic_type");
___mb.mb_get_call_mode = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_call_mode");
___mb.mb_get_index = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_index");
___mb.mb_get_property = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_property");
___mb.mb_set_base_path = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_path");
___mb.mb_set_base_script = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_script");
___mb.mb_set_base_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_type");
___mb.mb_set_basic_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_basic_type");
___mb.mb_set_call_mode = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_call_mode");
___mb.mb_set_index = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_index");
___mb.mb_set_property = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_property");
}
VisualScriptPropertyGet *VisualScriptPropertyGet::_new()
{
return (VisualScriptPropertyGet *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"VisualScriptPropertyGet")());
}
Variant::Type VisualScriptPropertyGet::_get_type_cache() const {
return (Variant::Type) ___godot_icall_int(___mb.mb__get_type_cache, (const Object *) this);
}
void VisualScriptPropertyGet::_set_type_cache(const int64_t type_cache) {
___godot_icall_void_int(___mb.mb__set_type_cache, (const Object *) this, type_cache);
}
NodePath VisualScriptPropertyGet::get_base_path() const {
return ___godot_icall_NodePath(___mb.mb_get_base_path, (const Object *) this);
}
String VisualScriptPropertyGet::get_base_script() const {
return ___godot_icall_String(___mb.mb_get_base_script, (const Object *) this);
}
String VisualScriptPropertyGet::get_base_type() const {
return ___godot_icall_String(___mb.mb_get_base_type, (const Object *) this);
}
Variant::Type VisualScriptPropertyGet::get_basic_type() const {
return (Variant::Type) ___godot_icall_int(___mb.mb_get_basic_type, (const Object *) this);
}
VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const {
return (VisualScriptPropertyGet::CallMode) ___godot_icall_int(___mb.mb_get_call_mode, (const Object *) this);
}
String VisualScriptPropertyGet::get_index() const {
return ___godot_icall_String(___mb.mb_get_index, (const Object *) this);
}
String VisualScriptPropertyGet::get_property() const {
return ___godot_icall_String(___mb.mb_get_property, (const Object *) this);
}
void VisualScriptPropertyGet::set_base_path(const NodePath base_path) {
___godot_icall_void_NodePath(___mb.mb_set_base_path, (const Object *) this, base_path);
}
void VisualScriptPropertyGet::set_base_script(const String base_script) {
___godot_icall_void_String(___mb.mb_set_base_script, (const Object *) this, base_script);
}
void VisualScriptPropertyGet::set_base_type(const String base_type) {
___godot_icall_void_String(___mb.mb_set_base_type, (const Object *) this, base_type);
}
void VisualScriptPropertyGet::set_basic_type(const int64_t basic_type) {
___godot_icall_void_int(___mb.mb_set_basic_type, (const Object *) this, basic_type);
}
void VisualScriptPropertyGet::set_call_mode(const int64_t mode) {
___godot_icall_void_int(___mb.mb_set_call_mode, (const Object *) this, mode);
}
void VisualScriptPropertyGet::set_index(const String index) {
___godot_icall_void_String(___mb.mb_set_index, (const Object *) this, index);
}
void VisualScriptPropertyGet::set_property(const String property) {
___godot_icall_void_String(___mb.mb_set_property, (const Object *) this, property);
}
} | 46.160377 | 227 | 0.816677 | GDNative-Gradle |
5434eb1c9eef69e0c99ae961ec0f1838d61fb243 | 22,097 | cc | C++ | gazebo/gui/model/ModelCreator.cc | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 45 | 2015-07-17T10:14:22.000Z | 2022-03-30T19:25:36.000Z | gazebo/gui/model/ModelCreator.cc | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-04-15T07:14:26.000Z | 2021-04-15T07:14:26.000Z | gazebo/gui/model/ModelCreator.cc | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 64 | 2015-04-18T07:10:14.000Z | 2022-02-21T13:15:41.000Z | /*
* Copyright 2013 Open Source Robotics Foundation
*
* 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 <sstream>
#include <boost/filesystem.hpp>
#include "gazebo/common/KeyEvent.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/rendering/UserCamera.hh"
#include "gazebo/rendering/Visual.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/math/Quaternion.hh"
#include "gazebo/transport/Publisher.hh"
#include "gazebo/transport/Node.hh"
#include "gazebo/physics/Inertial.hh"
#include "gazebo/gui/Actions.hh"
#include "gazebo/gui/KeyEventHandler.hh"
#include "gazebo/gui/MouseEventHandler.hh"
#include "gazebo/gui/GuiEvents.hh"
#include "gazebo/gui/GuiIface.hh"
#include "gazebo/gui/ModelManipulator.hh"
#include "gazebo/gui/model/JointMaker.hh"
#include "gazebo/gui/model/ModelCreator.hh"
using namespace gazebo;
using namespace gui;
/////////////////////////////////////////////////
ModelCreator::ModelCreator()
{
this->modelName = "";
this->modelTemplateSDF.reset(new sdf::SDF);
this->modelTemplateSDF->SetFromString(this->GetTemplateSDFString());
this->boxCounter = 0;
this->cylinderCounter = 0;
this->sphereCounter = 0;
this->modelCounter = 0;
this->node = transport::NodePtr(new transport::Node());
this->node->Init();
this->makerPub = this->node->Advertise<msgs::Factory>("~/factory");
this->requestPub = this->node->Advertise<msgs::Request>("~/request");
this->jointMaker = new JointMaker();
connect(g_deleteAct, SIGNAL(DeleteSignal(const std::string &)), this,
SLOT(OnDelete(const std::string &)));
this->Reset();
}
/////////////////////////////////////////////////
ModelCreator::~ModelCreator()
{
this->Reset();
this->node->Fini();
this->node.reset();
this->modelTemplateSDF.reset();
this->requestPub.reset();
this->makerPub.reset();
delete jointMaker;
}
/////////////////////////////////////////////////
std::string ModelCreator::CreateModel()
{
this->Reset();
return this->modelName;
}
/////////////////////////////////////////////////
void ModelCreator::AddJoint(JointMaker::JointType _type)
{
this->Stop();
if (this->jointMaker)
this->jointMaker->CreateJoint(_type);
}
/////////////////////////////////////////////////
std::string ModelCreator::AddBox(const math::Vector3 &_size,
const math::Pose &_pose)
{
if (!this->modelVisual)
{
this->Reset();
}
std::ostringstream linkNameStream;
linkNameStream << "unit_box_" << this->boxCounter++;
std::string linkName = linkNameStream.str();
rendering::VisualPtr linkVisual(new rendering::Visual(linkName,
this->modelVisual));
linkVisual->Load();
std::ostringstream visualName;
visualName << linkName << "_visual";
rendering::VisualPtr visVisual(new rendering::Visual(visualName.str(),
linkVisual));
sdf::ElementPtr visualElem = this->modelTemplateSDF->root
->GetElement("model")->GetElement("link")->GetElement("visual");
visualElem->GetElement("material")->GetElement("script")
->GetElement("name")->Set("Gazebo/GreyTransparent");
sdf::ElementPtr geomElem = visualElem->GetElement("geometry");
geomElem->ClearElements();
((geomElem->AddElement("box"))->AddElement("size"))->Set(_size);
visVisual->Load(visualElem);
linkVisual->SetPose(_pose);
if (_pose == math::Pose::Zero)
{
linkVisual->SetPosition(math::Vector3(_pose.pos.x, _pose.pos.y,
_pose.pos.z + _size.z/2));
}
this->CreatePart(visVisual);
this->mouseVisual = linkVisual;
return linkName;
}
/////////////////////////////////////////////////
std::string ModelCreator::AddSphere(double _radius,
const math::Pose &_pose)
{
if (!this->modelVisual)
this->Reset();
std::ostringstream linkNameStream;
linkNameStream << "unit_sphere_" << this->sphereCounter++;
std::string linkName = linkNameStream.str();
rendering::VisualPtr linkVisual(new rendering::Visual(
linkName, this->modelVisual));
linkVisual->Load();
std::ostringstream visualName;
visualName << linkName << "_visual";
rendering::VisualPtr visVisual(new rendering::Visual(visualName.str(),
linkVisual));
sdf::ElementPtr visualElem = this->modelTemplateSDF->root
->GetElement("model")->GetElement("link")->GetElement("visual");
visualElem->GetElement("material")->GetElement("script")
->GetElement("name")->Set("Gazebo/GreyTransparent");
sdf::ElementPtr geomElem = visualElem->GetElement("geometry");
geomElem->ClearElements();
((geomElem->AddElement("sphere"))->GetElement("radius"))->Set(_radius);
visVisual->Load(visualElem);
linkVisual->SetPose(_pose);
if (_pose == math::Pose::Zero)
{
linkVisual->SetPosition(math::Vector3(_pose.pos.x, _pose.pos.y,
_pose.pos.z + _radius));
}
this->CreatePart(visVisual);
this->mouseVisual = linkVisual;
return linkName;
}
/////////////////////////////////////////////////
std::string ModelCreator::AddCylinder(double _radius, double _length,
const math::Pose &_pose)
{
if (!this->modelVisual)
this->Reset();
std::ostringstream linkNameStream;
linkNameStream << "unit_cylinder_" << this->cylinderCounter++;
std::string linkName = linkNameStream.str();
rendering::VisualPtr linkVisual(new rendering::Visual(
linkName, this->modelVisual));
linkVisual->Load();
std::ostringstream visualName;
visualName << linkName << "_visual";
rendering::VisualPtr visVisual(new rendering::Visual(visualName.str(),
linkVisual));
sdf::ElementPtr visualElem = this->modelTemplateSDF->root
->GetElement("model")->GetElement("link")->GetElement("visual");
visualElem->GetElement("material")->GetElement("script")
->GetElement("name")->Set("Gazebo/GreyTransparent");
sdf::ElementPtr geomElem = visualElem->GetElement("geometry");
geomElem->ClearElements();
sdf::ElementPtr cylinderElem = geomElem->AddElement("cylinder");
(cylinderElem->GetElement("radius"))->Set(_radius);
(cylinderElem->GetElement("length"))->Set(_length);
visVisual->Load(visualElem);
linkVisual->SetPose(_pose);
if (_pose == math::Pose::Zero)
{
linkVisual->SetPosition(math::Vector3(_pose.pos.x, _pose.pos.y,
_pose.pos.z + _length/2));
}
this->CreatePart(visVisual);
this->mouseVisual = linkVisual;
return linkName;
}
/////////////////////////////////////////////////
std::string ModelCreator::AddCustom(const std::string &_path,
const math::Vector3 &_scale, const math::Pose &_pose)
{
if (!this->modelVisual)
this->Reset();
std::string path = _path;
std::ostringstream linkNameStream;
linkNameStream << "custom_" << this->customCounter++;
std::string linkName = linkNameStream.str();
rendering::VisualPtr linkVisual(new rendering::Visual(this->modelName + "::" +
linkName, this->modelVisual));
linkVisual->Load();
std::ostringstream visualName;
visualName << linkName << "_visual";
rendering::VisualPtr visVisual(new rendering::Visual(visualName.str(),
linkVisual));
sdf::ElementPtr visualElem = this->modelTemplateSDF->root
->GetElement("model")->GetElement("link")->GetElement("visual");
visualElem->GetElement("material")->GetElement("script")
->GetElement("name")->Set("Gazebo/GreyTransparent");
sdf::ElementPtr geomElem = visualElem->GetElement("geometry");
geomElem->ClearElements();
sdf::ElementPtr meshElem = geomElem->AddElement("mesh");
meshElem->GetElement("scale")->Set(_scale);
meshElem->GetElement("uri")->Set(path);
visVisual->Load(visualElem);
linkVisual->SetPose(_pose);
if (_pose == math::Pose::Zero)
{
linkVisual->SetPosition(math::Vector3(_pose.pos.x, _pose.pos.y,
_pose.pos.z + _scale.z/2));
}
this->CreatePart(visVisual);
this->mouseVisual = linkVisual;
return linkName;
}
/////////////////////////////////////////////////
void ModelCreator::CreatePart(const rendering::VisualPtr &_visual)
{
PartData *part = new PartData;
part->name = _visual->GetName();
part->visuals.push_back(_visual);
part->gravity = true;
part->selfCollide = false;
part->kinematic = false;
part->inertial = new physics::Inertial;
part->sensorData = new SensorData;
this->allParts[part->name] = part;
}
/////////////////////////////////////////////////
void ModelCreator::RemovePart(const std::string &_partName)
{
if (!this->modelVisual)
{
this->Reset();
return;
}
if (this->allParts.find(_partName) == this->allParts.end())
return;
PartData *part = this->allParts[_partName];
if (!part)
return;
for (unsigned int i = 0; i < part->visuals.size(); ++i)
{
rendering::VisualPtr vis = part->visuals[i];
rendering::VisualPtr visParent = vis->GetParent();
rendering::ScenePtr scene = vis->GetScene();
scene->RemoveVisual(vis);
if (visParent)
scene->RemoveVisual(visParent);
}
delete part->inertial;
delete part->sensorData;
this->allParts.erase(_partName);
}
/////////////////////////////////////////////////
void ModelCreator::Reset()
{
if (!gui::get_active_camera() ||
!gui::get_active_camera()->GetScene())
return;
KeyEventHandler::Instance()->AddPressFilter("model_part",
boost::bind(&ModelCreator::OnKeyPressPart, this, _1));
MouseEventHandler::Instance()->AddReleaseFilter("model_part",
boost::bind(&ModelCreator::OnMouseReleasePart, this, _1));
MouseEventHandler::Instance()->AddMoveFilter("model_part",
boost::bind(&ModelCreator::OnMouseMovePart, this, _1));
MouseEventHandler::Instance()->AddDoubleClickFilter("model_part",
boost::bind(&ModelCreator::OnMouseDoubleClickPart, this, _1));
this->jointMaker->Reset();
this->selectedVis.reset();
std::stringstream ss;
ss << "defaultModel_" << this->modelCounter++;
this->modelName = ss.str();
rendering::ScenePtr scene = gui::get_active_camera()->GetScene();
this->isStatic = false;
this->autoDisable = true;
while (this->allParts.size() > 0)
this->RemovePart(this->allParts.begin()->first);
this->allParts.clear();
if (this->modelVisual)
scene->RemoveVisual(this->modelVisual);
this->modelVisual.reset(new rendering::Visual(this->modelName,
scene->GetWorldVisual()));
this->modelVisual->Load();
this->modelPose = math::Pose::Zero;
this->modelVisual->SetPose(this->modelPose);
scene->AddVisual(this->modelVisual);
}
/////////////////////////////////////////////////
void ModelCreator::SetModelName(const std::string &_modelName)
{
this->modelName = _modelName;
}
/////////////////////////////////////////////////
std::string ModelCreator::GetModelName() const
{
return this->modelName;
}
/////////////////////////////////////////////////
void ModelCreator::SetStatic(bool _static)
{
this->isStatic = _static;
}
/////////////////////////////////////////////////
void ModelCreator::SetAutoDisable(bool _auto)
{
this->autoDisable = _auto;
}
/////////////////////////////////////////////////
void ModelCreator::SaveToSDF(const std::string &_savePath)
{
std::ofstream savefile;
boost::filesystem::path path;
path = boost::filesystem::operator/(_savePath, this->modelName + ".sdf");
savefile.open(path.string().c_str());
if (savefile.is_open())
{
savefile << this->modelSDF->ToString();
savefile.close();
}
else
{
gzerr << "Unable to open file for writing: '" << path.string().c_str()
<< "'. Possibly a permission issue." << std::endl;
}
}
/////////////////////////////////////////////////
void ModelCreator::FinishModel()
{
event::Events::setSelectedEntity("", "normal");
this->Reset();
this->CreateTheEntity();
}
/////////////////////////////////////////////////
void ModelCreator::CreateTheEntity()
{
msgs::Factory msg;
msg.set_sdf(this->modelSDF->ToString());
this->makerPub->Publish(msg);
}
/////////////////////////////////////////////////
std::string ModelCreator::GetTemplateSDFString()
{
std::ostringstream newModelStr;
newModelStr << "<sdf version ='" << SDF_VERSION << "'>"
<< "<model name='template_model'>"
<< "<pose>0 0 0.0 0 0 0</pose>"
<< "<link name ='link'>"
<< "<visual name ='visual'>"
<< "<pose>0 0 0.0 0 0 0</pose>"
<< "<geometry>"
<< "<box>"
<< "<size>1.0 1.0 1.0</size>"
<< "</box>"
<< "</geometry>"
<< "<material>"
<< "<script>"
<< "<uri>file://media/materials/scripts/gazebo.material</uri>"
<< "<name>Gazebo/Grey</name>"
<< "</script>"
<< "</material>"
<< "</visual>"
<< "</link>"
<< "<static>true</static>"
<< "</model>"
<< "</sdf>";
return newModelStr.str();
}
/////////////////////////////////////////////////
void ModelCreator::AddPart(PartType _type)
{
this->Stop();
this->addPartType = _type;
if (_type != PART_NONE)
{
switch (_type)
{
case PART_BOX:
{
this->AddBox();
break;
}
case PART_SPHERE:
{
this->AddSphere();
break;
}
case PART_CYLINDER:
{
this->AddCylinder();
break;
}
default:
{
gzwarn << "Unknown part type '" << _type << "'. " <<
"Part not added" << std::endl;
break;
}
}
}
}
/////////////////////////////////////////////////
void ModelCreator::Stop()
{
if (this->addPartType != PART_NONE && this->mouseVisual)
{
for (unsigned int i = 0; i < this->mouseVisual->GetChildCount(); ++i)
this->RemovePart(this->mouseVisual->GetChild(0)->GetName());
this->mouseVisual.reset();
}
if (this->jointMaker)
this->jointMaker->Stop();
}
/////////////////////////////////////////////////
void ModelCreator::OnDelete(const std::string &_part)
{
if (_part == this->modelName)
{
this->Reset();
return;
}
if (this->jointMaker)
this->jointMaker->RemoveJointsByPart(_part);
this->RemovePart(_part);
}
/////////////////////////////////////////////////
bool ModelCreator::OnKeyPressPart(const common::KeyEvent &_event)
{
if (_event.key == Qt::Key_Escape)
{
this->Stop();
}
else if (_event.key == Qt::Key_Delete)
{
if (this->selectedVis)
{
this->OnDelete(this->selectedVis->GetName());
this->selectedVis.reset();
}
}
return false;
}
/////////////////////////////////////////////////
bool ModelCreator::OnMouseReleasePart(const common::MouseEvent &_event)
{
if (_event.button != common::MouseEvent::LEFT)
return false;
if (this->mouseVisual)
{
emit PartAdded();
this->mouseVisual.reset();
this->AddPart(PART_NONE);
return true;
}
// In mouse normal mode, let users select a part if the parent model
// is currently selected.
rendering::VisualPtr vis = gui::get_active_camera()->GetVisual(_event.pos);
if (vis)
{
if (this->allParts.find(vis->GetName()) !=
this->allParts.end())
{
if (gui::get_active_camera()->GetScene()->GetSelectedVisual()
== this->modelVisual || this->selectedVis)
{
if (this->selectedVis)
this->selectedVis->SetHighlighted(false);
else
event::Events::setSelectedEntity("", "normal");
this->selectedVis = vis;
this->selectedVis->SetHighlighted(true);
return true;
}
}
else if (this->selectedVis)
{
this->selectedVis->SetHighlighted(false);
this->selectedVis.reset();
}
}
return false;
}
/////////////////////////////////////////////////
bool ModelCreator::OnMouseMovePart(const common::MouseEvent &_event)
{
if (!this->mouseVisual)
return false;
if (!gui::get_active_camera())
return false;
math::Pose pose = this->mouseVisual->GetWorldPose();
pose.pos = ModelManipulator::GetMousePositionOnPlane(
gui::get_active_camera(), _event);
if (!_event.shift)
{
pose.pos = ModelManipulator::SnapPoint(pose.pos);
}
pose.pos.z = this->mouseVisual->GetWorldPose().pos.z;
this->mouseVisual->SetWorldPose(pose);
return true;
}
/////////////////////////////////////////////////
bool ModelCreator::OnMouseDoubleClickPart(const common::MouseEvent &_event)
{
rendering::VisualPtr vis = gui::get_active_camera()->GetVisual(_event.pos);
if (vis)
{
if (this->allParts.find(vis->GetName()) != this->allParts.end())
{
// TODO part inspector code goes here
return true;
}
}
return false;
}
/////////////////////////////////////////////////
JointMaker *ModelCreator::GetJointMaker() const
{
return this->jointMaker;
}
/////////////////////////////////////////////////
void ModelCreator::GenerateSDF()
{
sdf::ElementPtr modelElem;
sdf::ElementPtr linkElem;
sdf::ElementPtr visualElem;
sdf::ElementPtr collisionElem;
this->modelSDF.reset(new sdf::SDF);
this->modelSDF->SetFromString(this->GetTemplateSDFString());
modelElem = this->modelSDF->root->GetElement("model");
linkElem = modelElem->GetElement("link");
sdf::ElementPtr templateLinkElem = linkElem->Clone();
sdf::ElementPtr templateVisualElem = templateLinkElem->GetElement(
"visual")->Clone();
sdf::ElementPtr templateCollisionElem = templateLinkElem->GetElement(
"collision")->Clone();
modelElem->ClearElements();
std::stringstream visualNameStream;
std::stringstream collisionNameStream;
modelElem->GetAttribute("name")->Set(this->modelName);
boost::unordered_map<std::string, PartData *>::iterator partsIt;
// set center of all parts to be origin
math::Vector3 mid;
for (partsIt = this->allParts.begin(); partsIt != this->allParts.end();
++partsIt)
{
PartData *part = partsIt->second;
rendering::VisualPtr visual = part->visuals[0];
mid += visual->GetParent()->GetWorldPose().pos;
}
mid /= this->allParts.size();
this->origin.pos = mid;
modelElem->GetElement("pose")->Set(this->origin);
// loop through all parts and generate sdf
for (partsIt = this->allParts.begin(); partsIt != this->allParts.end();
++partsIt)
{
visualNameStream.str("");
collisionNameStream.str("");
PartData *part = partsIt->second;
rendering::VisualPtr visual = part->visuals[0];
sdf::ElementPtr newLinkElem = templateLinkElem->Clone();
visualElem = newLinkElem->GetElement("visual");
collisionElem = newLinkElem->GetElement("collision");
newLinkElem->GetAttribute("name")->Set(visual->GetParent()->GetName());
newLinkElem->GetElement("pose")->Set(visual->GetParent()->GetWorldPose()
- this->origin);
newLinkElem->GetElement("gravity")->Set(part->gravity);
newLinkElem->GetElement("self_collide")->Set(part->selfCollide);
newLinkElem->GetElement("kinematic")->Set(part->kinematic);
sdf::ElementPtr inertialElem = newLinkElem->GetElement("inertial");
inertialElem->GetElement("mass")->Set(part->inertial->GetMass());
inertialElem->GetElement("pose")->Set(part->inertial->GetPose());
sdf::ElementPtr inertiaElem = inertialElem->GetElement("inertia");
inertiaElem->GetElement("ixx")->Set(part->inertial->GetIXX());
inertiaElem->GetElement("iyy")->Set(part->inertial->GetIYY());
inertiaElem->GetElement("izz")->Set(part->inertial->GetIZZ());
inertiaElem->GetElement("ixy")->Set(part->inertial->GetIXY());
inertiaElem->GetElement("ixz")->Set(part->inertial->GetIXZ());
inertiaElem->GetElement("iyz")->Set(part->inertial->GetIYZ());
modelElem->InsertElement(newLinkElem);
visualElem->GetAttribute("name")->Set(visual->GetParent()->GetName()
+ "_visual");
collisionElem->GetAttribute("name")->Set(visual->GetParent()->GetName()
+ "_collision");
visualElem->GetElement("pose")->Set(visual->GetPose());
collisionElem->GetElement("pose")->Set(visual->GetPose());
sdf::ElementPtr geomElem = visualElem->GetElement("geometry");
geomElem->ClearElements();
math::Vector3 scale = visual->GetScale();
if (visual->GetParent()->GetName().find("unit_box") != std::string::npos)
{
sdf::ElementPtr boxElem = geomElem->AddElement("box");
(boxElem->GetElement("size"))->Set(scale);
}
else if (visual->GetParent()->GetName().find("unit_cylinder")
!= std::string::npos)
{
sdf::ElementPtr cylinderElem = geomElem->AddElement("cylinder");
(cylinderElem->GetElement("radius"))->Set(scale.x/2.0);
(cylinderElem->GetElement("length"))->Set(scale.z);
}
else if (visual->GetParent()->GetName().find("unit_sphere")
!= std::string::npos)
{
sdf::ElementPtr sphereElem = geomElem->AddElement("sphere");
(sphereElem->GetElement("radius"))->Set(scale.x/2.0);
}
else if (visual->GetParent()->GetName().find("custom")
!= std::string::npos)
{
sdf::ElementPtr customElem = geomElem->AddElement("mesh");
(customElem->GetElement("scale"))->Set(scale);
(customElem->GetElement("uri"))->Set(visual->GetMeshName());
}
sdf::ElementPtr geomElemClone = geomElem->Clone();
geomElem = collisionElem->GetElement("geometry");
geomElem->ClearElements();
geomElem->InsertElement(geomElemClone->GetFirstElement());
}
// Add joint sdf elements
this->jointMaker->GenerateSDF();
sdf::ElementPtr jointsElem = this->jointMaker->GetSDF();
sdf::ElementPtr jointElem;
if (jointsElem->HasElement("joint"))
jointElem = jointsElem->GetElement("joint");
while (jointElem)
{
modelElem->InsertElement(jointElem->Clone());
jointElem = jointElem->GetNextElement("joint");
}
// Model settings
modelElem->GetElement("static")->Set(this->isStatic);
modelElem->GetElement("allow_auto_disable")->Set(this->autoDisable);
}
| 28.809648 | 80 | 0.62461 | hyunoklee |
54351f4440753e19b57f08ecd4efe7a84ee98cb3 | 1,011 | cpp | C++ | kakao_test_2017/A.cpp | sjnov11/Coding-Tests | 8f98723f842357ee771f3842d46211bc9d92ff29 | [
"MIT"
] | null | null | null | kakao_test_2017/A.cpp | sjnov11/Coding-Tests | 8f98723f842357ee771f3842d46211bc9d92ff29 | [
"MIT"
] | null | null | null | kakao_test_2017/A.cpp | sjnov11/Coding-Tests | 8f98723f842357ee771f3842d46211bc9d92ff29 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
void go(int n, int arr1[], int arr2[]) {
int map1[16][16], map2[16][16];
memset(map1, 0, sizeof(int) * 16 * 16);
memset(map2, 0, sizeof(int) * 16 * 16);
for (int i = 0; i < n; i++) {
cout << "row " << i << endl;
for (int j = 0; j < n; j++) {
cout << n-j-1<< " : " << arr1[i] << " / " << arr1[i] % 2<< endl;
map1[i][n - j - 1] = arr1[i] % 2;
arr1[i] /= 2;
if (arr1[i] == 0) break;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map2[i][n - j - 1] = arr2[i] % 2;
arr2[i] /= 2;
if (arr2[i] == 0) break;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map1[i][j] | map2[i][j])
cout << "#";
else
cout << " ";
}
cout << "\n";
}
}
int main() {
/*int n = 5;
int arr1[5] = { 9, 20, 28, 18, 11 };
int arr2[5] = { 30, 1, 21, 17, 28 };*/
int n = 6;
int arr1[6] = { 46, 33, 33, 22, 31, 50 };
int arr2[6] = { 27, 56, 19, 14, 14, 10 };
go(n, arr1, arr2);
} | 21.0625 | 67 | 0.431256 | sjnov11 |
5436c6328408f5a3fe6c20d9842c05735a61d00d | 3,406 | cc | C++ | old/graphics/vulkan/handle.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | null | null | null | old/graphics/vulkan/handle.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | null | null | null | old/graphics/vulkan/handle.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | 1 | 2019-06-04T04:43:24.000Z | 2019-06-04T04:43:24.000Z | // Copyright 2018, Cristián Donoso.
// This code has a BSD license. See LICENSE.
#include "warhol/graphics/vulkan/handle.h"
#include "warhol/graphics/vulkan/context.h"
#include "warhol/graphics/vulkan/utils.h"
namespace warhol {
namespace vulkan {
template <>
void Handle<VkInstance>::InternalClear() {
if (has_value() && context_)
vkDestroyInstance(handle_, nullptr);
}
template <>
void Handle<VkDebugUtilsMessengerEXT>::InternalClear() {
if (has_value() && context_)
DestroyDebugUtilsMessengerEXT(*context_->instance, handle_, nullptr);
}
template <>
void Handle<VkSurfaceKHR>::InternalClear() {
if (has_value() && context_)
vkDestroySurfaceKHR(*context_->instance, handle_, nullptr);
}
template <>
void Handle<VkDevice>::InternalClear() {
if (has_value() && context_)
vkDestroyDevice(handle_, nullptr);
}
template <>
void Handle<VkSwapchainKHR>::InternalClear() {
if (has_value() && context_)
vkDestroySwapchainKHR(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkImage>::InternalClear() {
if (has_value() && context_)
vkDestroyImage(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkImageView>::InternalClear() {
if (has_value() && context_)
vkDestroyImageView(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkSampler>::InternalClear() {
if (has_value() && context_)
vkDestroySampler(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkRenderPass>::InternalClear() {
if (has_value() && context_)
vkDestroyRenderPass(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkPipelineLayout>::InternalClear() {
if (has_value() && context_)
vkDestroyPipelineLayout(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkPipeline>::InternalClear() {
if (has_value() && context_)
vkDestroyPipeline(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkFramebuffer>::InternalClear() {
if (has_value() && context_)
vkDestroyFramebuffer(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkCommandPool>::InternalClear() {
if (has_value() && context_)
vkDestroyCommandPool(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkCommandBuffer>::InternalClear() {
if (has_value() && context_ && extra_handle_) {
vkFreeCommandBuffers(*context_->device, (VkCommandPool)extra_handle_,
1, &handle_);
}
}
template <>
void Handle<VkSemaphore>::InternalClear() {
if (has_value() && context_)
vkDestroySemaphore(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkFence>::InternalClear() {
if (has_value() && context_)
vkDestroyFence(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkBuffer>::InternalClear() {
if (has_value() && context_)
vkDestroyBuffer(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkDeviceMemory>::InternalClear() {
if (has_value() && context_)
vkFreeMemory(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkDescriptorSetLayout>::InternalClear() {
if (has_value() && context_)
vkDestroyDescriptorSetLayout(*context_->device, handle_, nullptr);
}
template <>
void Handle<VkDescriptorPool>::InternalClear() {
if (has_value() && context_)
vkDestroyDescriptorPool(*context_->device, handle_, nullptr);
}
} // namespace vulkan
} // namespace warhol
| 25.044118 | 73 | 0.710217 | cristiandonosoc |
543958ce939943536c24a895401e3308fc1800ee | 1,683 | cc | C++ | tensorflow_lite_support/cc/task/text/clu_lib/tflite_test_utils.cc | ccen-stripe/tflite-support | a92abc7eb8bd08c1fb8b26fecf394e0f8fcf3654 | [
"Apache-2.0"
] | null | null | null | tensorflow_lite_support/cc/task/text/clu_lib/tflite_test_utils.cc | ccen-stripe/tflite-support | a92abc7eb8bd08c1fb8b26fecf394e0f8fcf3654 | [
"Apache-2.0"
] | null | null | null | tensorflow_lite_support/cc/task/text/clu_lib/tflite_test_utils.cc | ccen-stripe/tflite-support | a92abc7eb8bd08c1fb8b26fecf394e0f8fcf3654 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow_lite_support/cc/task/text/clu_lib/tflite_test_utils.h"
#include <initializer_list>
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/string_util.h"
namespace tflite::task::text::clu {
template <>
void PopulateTfLiteTensorValue<std::string>(
const std::initializer_list<std::string> values, TfLiteTensor* tensor) {
tflite::DynamicBuffer buf;
for (const std::string& s : values) {
buf.AddString(s.data(), s.length());
}
buf.WriteToTensor(tensor, /*new_shape=*/nullptr);
}
size_t NumTotalFromShape(const std::initializer_list<int>& shape) {
size_t num_total;
if (shape.size() > 0)
num_total = 1;
else
num_total = 0;
for (const int dim : shape) num_total *= dim;
return num_total;
}
TfLiteTensor* UniqueTfLiteTensor::get() { return tensor_; }
UniqueTfLiteTensor::~UniqueTfLiteTensor() { TfLiteTensorFree(tensor_); }
template <>
TfLiteType TypeToTfLiteType<std::string>() {
return kTfLiteString;
}
} // namespace tflite::task::text::clu
| 30.6 | 80 | 0.711824 | ccen-stripe |
543d711f052d02af3325c57cdf30c5b549c14389 | 508 | cc | C++ | poj/2/2327.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/2/2327.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/2/2327.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
using namespace std;
int main()
{
int N;
while (scanf("%d", &N) != EOF && N != 0) {
double Pl, Pr;
scanf("%lf %lf", &Pl, &Pr);
vector<double> dp(N+1, 1e10);
dp[0] = 0;
for (int i = 1; i <= N; i++) {
for (int j = 0; j < i; j++) {
const double El = dp[j], Er = dp[i-j-1];
const double n = (1 + Pl*El + Pr*Er)/(1 - Pl - Pr);
dp[i] = min(dp[i], El + Er + n);
}
}
printf("%.2f\n", dp[N]);
}
return 0;
}
| 20.32 | 59 | 0.437008 | eagletmt |
5442027c3bbcc94269ca326ae3ff6b33d702e997 | 9,524 | cpp | C++ | 2.0/SensorsDataProxyManager.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | 7 | 2021-10-29T20:29:48.000Z | 2022-03-03T01:38:45.000Z | 2.0/SensorsDataProxyManager.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | null | null | null | 2.0/SensorsDataProxyManager.cpp | STMicroelectronics/st-mems-android-linux-sensors-hal | a12f3d9806b8851d17c331bc07acafae9dcb2d3b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 The Android Open Source Project
* Copyright (C) 2020 STMicroelectronics
*
* 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 <cerrno>
#include <string>
#include <sstream>
#include <IUtils.h>
#include "SensorsDataProxyManager.h"
stm::core::IUtils &utils = stm::core::IUtils::getInstance();
/**
* reset: reset the status of the proxy manager
*/
void SensorsDataProxyManager::reset(void)
{
mSensorToChannel.clear();
mChannelToSensor.clear();
}
/**
* addChannel: add channel that can be used for binding with sensor/s
* @channelHandle: unique channel handle.
*
* Return value: 0 on success, else a negative error code.
*/
int SensorsDataProxyManager::addChannel(int32_t channelHandle)
{
auto search_channel = mChannelToSensor.find(channelHandle);
if (search_channel != mChannelToSensor.end()) {
return -EADDRINUSE;
}
auto ret = mChannelToSensor.insert(std::make_pair(channelHandle, std::unordered_set<int32_t>()));
return ret.second ? 0 : -ENOMEM;
}
/**
* removeChannel: remove channel, must not be in use (bind-ed to sensor/s)
* @channelHandle: channel handle to be removed.
*
* Return value: 0 on success, else a negative error code.
*/
int SensorsDataProxyManager::removeChannel(int32_t channelHandle)
{
auto search_channel = mChannelToSensor.find(channelHandle);
if (search_channel == mChannelToSensor.end()) {
return 0;
}
if (!search_channel->second.empty()) {
return -EBUSY;
}
mChannelToSensor.erase(channelHandle);
return 0;
}
/**
* registerSensorToChannel: bind a sensor and a channel
* @sensorHandle: sensor handle to bind.
* @channelHandle: channel handle to bind.
*
* Return value: 0 on success, else a negative error code.
*/
int SensorsDataProxyManager::registerSensorToChannel(int32_t sensorHandle,
int32_t channelHandle)
{
auto search_channel = mChannelToSensor.find(channelHandle);
if (search_channel == mChannelToSensor.end()) {
return -EINVAL;
}
auto search_sensor = search_channel->second.find(sensorHandle);
if (search_sensor != search_channel->second.end()) {
return 0;
}
auto search_sensor_2 = mSensorToChannel.find(sensorHandle);
if (search_sensor_2 == mSensorToChannel.end()) {
auto ret = mSensorToChannel.insert(std::make_pair(sensorHandle,
std::unordered_map<int32_t, struct ProxyData>()));
if (!ret.second) {
return -ENOMEM;
}
search_sensor_2 = ret.first;
}
auto search_channel_2 = search_sensor_2->second.find(channelHandle);
if (search_channel_2 != search_sensor_2->second.end()) {
return -EINVAL;
}
struct ProxyData pdata;
pdata.pollrateNs = 0;
pdata.samplesCounter = 0;
search_channel->second.insert(sensorHandle);
search_sensor_2->second.insert(std::make_pair(channelHandle, std::move(pdata)));
return 0;
}
/**
* unregisterSensorFromChannel: remove binding from sensor and channel
* @sensorHandle: sensor handle.
* @channelHandle: channel handle.
*
* Return value: 0 on success, else a negative error code.
*/
int SensorsDataProxyManager::unregisterSensorFromChannel(int32_t sensorHandle,
int32_t channelHandle)
{
auto search_channel = mChannelToSensor.find(channelHandle);
if (search_channel == mChannelToSensor.end()) {
return -EINVAL;
}
auto search_sensor_2 = mSensorToChannel.find(sensorHandle);
if (search_sensor_2 == mSensorToChannel.end()) {
return -EINVAL;
}
search_channel->second.erase(sensorHandle);
search_sensor_2->second.erase(channelHandle);
return 0;
}
/**
* configureSensorInChannel: set new pollrate for a sensor in a specific channel
* @sensorHandle: sensor handle.
* @channelHandle: channel handle.
* @pollrateNs: pollrate in nanoseconds.
*
* Return value: 0 on success, else a negative error code.
*/
int SensorsDataProxyManager::configureSensorInChannel(int32_t sensorHandle,
int32_t channelHandle,
int64_t pollrateNs)
{
auto search_sensor = mSensorToChannel.find(sensorHandle);
if (search_sensor == mSensorToChannel.end()) {
return -EINVAL;
}
auto search_channel = search_sensor->second.find(channelHandle);
if (search_channel == search_sensor->second.end()) {
return -ENODEV;
}
struct PollrateSwitchData switchData;
switchData.timestampOfChange = utils.getTime();
switchData.pollrateNs = pollrateNs;
search_channel->second.switchDataFifo.push_back(std::move(switchData));
return 0;
}
/**
* getMaxPollrateNs: get the maximum pollrate requested for a sensor
* @sensorHandle: sensor handle.
*
* Return value: max pollrate in nanoseconds, 0 if sensor is disabled.
*/
int64_t SensorsDataProxyManager::getMaxPollrateNs(int32_t sensorHandle) const
{
int64_t max = INT64_MAX;
auto search_sensor = mSensorToChannel.find(sensorHandle);
if (search_sensor == mSensorToChannel.end()) {
return 0;
}
for (auto &ch : search_sensor->second) {
const struct ProxyData &pdata = ch.second;
int64_t pollrateNs;
if (pdata.switchDataFifo.empty()) {
pollrateNs = pdata.pollrateNs;
} else {
const struct PollrateSwitchData &switchDataLast = pdata.switchDataFifo.back();
pollrateNs = switchDataLast.pollrateNs;
}
if ((max > pollrateNs) && (pollrateNs > 0)) {
max = pollrateNs;
}
}
return max == INT64_MAX ? 0 : max;
}
/**
* getChannels: obtain list of channels where a sensor is currently registered on
* @sensorHandle: sensor handle.
*
* Return value: list of channels handles.
*/
std::vector<int32_t> SensorsDataProxyManager::getChannels(int32_t sensorHandle) const
{
std::vector<int32_t> channelsHandles;
auto search_sensor = mSensorToChannel.find(sensorHandle);
if (search_sensor == mSensorToChannel.end()) {
return channelsHandles;
}
for (auto &ch : search_sensor->second) {
channelsHandles.push_back(ch.first);
}
return channelsHandles;
}
/**
* getRegisteredSensorsInChannel: obtain list of sensors currently registered on a channel
* @channelHandle: channel handle.
*
* Return value: list of sensors handles.
*/
std::vector<int32_t> SensorsDataProxyManager::getRegisteredSensorsInChannel(int32_t channelHandle) const
{
std::vector<int32_t> sensorsHandles;
auto search_channel = mChannelToSensor.find(channelHandle);
for (auto &sh : search_channel->second) {
sensorsHandles.push_back(sh);
}
return sensorsHandles;
}
/**
* getValidPushChannels: list if channels where the current sensor sample must be pushed to
* @timestamp: timestamp of current sensor sample.
* @sensorHandle: sensor handle.
* @pollrateNs: current pollrate of the sensor stream.
*
* Return value: list of channels handles.
*/
std::vector<int32_t> SensorsDataProxyManager::getValidPushChannels(int64_t timestamp,
int32_t sensorHandle,
int64_t pollrateNs)
{
std::vector<int32_t> channelsHandles;
auto search_sensor = mSensorToChannel.find(sensorHandle);
if (search_sensor == mSensorToChannel.end()) {
return channelsHandles;
}
for (auto &ch : search_sensor->second) {
struct ProxyData &pdata = ch.second;
int oldDivisor = calculateDecimator(pdata.pollrateNs, pollrateNs);
while (!pdata.switchDataFifo.empty()) {
struct PollrateSwitchData &switchData = pdata.switchDataFifo.front();
if (timestamp >= switchData.timestampOfChange) {
pdata.pollrateNs = switchData.pollrateNs;
pdata.switchDataFifo.pop_front();
} else {
break;
}
}
int divisor = calculateDecimator(pdata.pollrateNs, pollrateNs);
if (divisor) {
if (oldDivisor != divisor) {
pdata.samplesCounter = divisor - 1;
}
if (++pdata.samplesCounter >= divisor) {
pdata.samplesCounter = 0;
channelsHandles.push_back(ch.first);
}
}
}
return channelsHandles;
}
/**
* calculateDecimator: calculate decimator factor
* @dividend: dividend.
* @divisor: divisor.
*
* Return value: >= 1 if divisor is greater than 0. 0 if divisor is also 0.
*/
int SensorsDataProxyManager::calculateDecimator(int64_t dividend, int64_t divisor) const
{
if (!divisor) {
return 0;
}
int quotient = dividend / divisor;
if (quotient < 1) {
quotient = 1;
}
return quotient;
}
| 29.669782 | 108 | 0.657287 | STMicroelectronics |
54424ca3f829733d999104dc15d838e545f5958e | 11,142 | cc | C++ | src/Molecule_Lib/geometric_constraints.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | 6 | 2020-08-17T15:02:14.000Z | 2022-01-21T19:27:56.000Z | src/Molecule_Lib/geometric_constraints.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | null | null | null | src/Molecule_Lib/geometric_constraints.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | null | null | null | #include "geometric_constraints.h"
namespace geometric_constraints {
using std::cerr;
// Initialize with arbitrary values that will prevent matching anything.
AllowedRange::AllowedRange() {
_min_value = 1.0;
_max_value = 0.0;
}
std::ostream&
operator<< (std::ostream& output, const AllowedRange& arange) {
output << "AllowedRange [" << arange._min_value << ',' << arange._max_value << ']';
return output;
}
int
AllowedRange::BuildFromProto(const GeometricConstraints::Range& proto) {
_min_value = proto.min();
_max_value = proto.max();
// If an upper bound is not specified, assume infinite.
if (_min_value > 0.0 && _max_value == 0.0) {
_max_value = std::numeric_limits<float>::max();
}
if (_min_value > _max_value) {
cerr << "AllowedRange::BuildFromProto:invalid range " << *this << '\n';
return 0;
}
if (proto.one_time_scaling_factor() != 0.0) {
_min_value *= proto.one_time_scaling_factor();
_max_value *= proto.one_time_scaling_factor();
}
return 1;
}
int
ConstraintBaseClass::IsValid() const {
// Unset is a valid state.
if (!_allowed_range.Active() && _atoms.empty()) {
return 1;
}
const int natoms = _atoms.number_elements();
if (natoms < 2) // The DistanceConstraint has 2 atoms.
return 0;
if (natoms > 4) // Torsion has 4 atoms.
return 0;
// We have atoms specified, but no _allowed_range.
if (!_allowed_range.Active()) {
return 0;
}
// Are all the atom numbers unique?
for (int i = 0; i < natoms; ++i) {
int a1 = _atoms[i];
for (int j = i + 1; j < natoms; ++j) {
if (_atoms[j] == a1)
return 0;
}
}
return 1;
}
int
ConstraintBaseClass::SetAtoms(int a1, int a2) {
return (_atoms.add_if_not_already_present(a1)> 0) +
(_atoms.add_if_not_already_present(a2)> 0);
}
int
ConstraintBaseClass::SetAtoms(int a1, int a2, int a3) {
return (_atoms.add_if_not_already_present(a1)> 0) +
(_atoms.add_if_not_already_present(a2)> 0) +
(_atoms.add_if_not_already_present(a3)> 0);
}
int
ConstraintBaseClass::SetAtoms(int a1, int a2, int a3, int a4) {
return (_atoms.add_if_not_already_present(a1)> 0) +
(_atoms.add_if_not_already_present(a2)> 0) +
(_atoms.add_if_not_already_present(a3)> 0) +
(_atoms.add_if_not_already_present(a4)> 0);
}
int
ConstraintBaseClass::AtomNumbersPresent(resizable_array<int>& atom_numbers) const {
int rc = 0;
for (int a : _atoms) {
rc += atom_numbers.add_if_not_already_present(a);
}
return rc;
}
std::ostream& operator<<(std::ostream& output, const ConstraintBaseClass& constraint) {
for (int i : constraint._atoms) {
output << ' ' << i;
}
output << ' ' << constraint._allowed_range;
return output;
}
int
DistanceConstraint::BuildFromProto(const GeometricConstraints::Distance& proto) {
if (! _allowed_range.BuildFromProto(proto.range())) {
cerr << "DistanceConstraint::BuildFromProto:invalid range " << proto.ShortDebugString() << '\n';
return 0;
}
if (SetAtoms(proto.a1(), proto.a2()) != 2) {
cerr << "DistanceConstraint::BuildFromProto:invalid atom numbers " << proto.ShortDebugString() << '\n';
return 0;
}
if (! IsValid()) {
cerr << "DistanceConstraint::BuildFromProto:invalid " << *this << '\n';
return 0;
}
return 1;
}
std::ostream& operator<< (std::ostream& output, const DistanceConstraint& constraint) {
const ConstraintBaseClass& me = constraint;
output << "DistanceConstraint:atoms " << me;
return output;
}
int
DistanceConstraint::Matches(const Molecule& m) {
return _allowed_range.Matches(m.distance_between_atoms(_atoms[0], _atoms[1]));
}
int
DistanceConstraint::Matches(const Molecule& m, const Set_of_Atoms& embedding) {
return _allowed_range.Matches(m.distance_between_atoms(embedding[_atoms[0]], embedding[_atoms[1]]));
}
int
BondAngleConstraint::BuildFromProto(const GeometricConstraints::BondAngle& proto) {
if (! _allowed_range.BuildFromProto(proto.range())) {
cerr << "DistanceConstraint::BuildFromProto:invalid range " << proto.ShortDebugString() << '\n';
return 0;
}
if (SetAtoms(proto.a1(), proto.a2(), proto.a3()) != 3) {
cerr << "BondAngle::BuildFromProto:invalid atom numbers " << proto.ShortDebugString() << '\n';
return 0;
}
if (! IsValid()) {
cerr << "BondAngleConstraint::BuildFromProto:invalid " << *this << '\n';
return 0;
}
return 1;
}
std::ostream&
operator<< (std::ostream& output, const BondAngleConstraint& constraint) {
const ConstraintBaseClass& me = constraint;
output << "BondAngleConstraint:atoms " << me;
return output;
}
int
BondAngleConstraint::Matches(const Molecule& m) {
//std::cerr << "Angle is " << m.bond_angle(_a1, _a2, _a3) << " radians " << _allowed_range << '\n';
return _allowed_range.Matches(m.bond_angle(_atoms[0], _atoms[1], _atoms[2]));
}
int
BondAngleConstraint::Matches(const Molecule& m, const Set_of_Atoms& embedding) {
return _allowed_range.Matches(m.bond_angle(embedding[_atoms[0]], embedding[_atoms[1]], embedding[_atoms[2]]));
}
int
TorsionAngleConstraint::BuildFromProto(const GeometricConstraints::TorsionAngle& proto) {
if (! _allowed_range.BuildFromProto(proto.range())) {
cerr << "DistanceConstraint::BuildFromProto:invalid range " << proto.ShortDebugString() << '\n';
return 0;
}
if (SetAtoms(proto.a1(), proto.a2(), proto.a3(), proto.a4()) != 4) {
cerr << "TorsionAngle::BuildFromProto:invalid atom numbers " << proto.ShortDebugString() << '\n';
return 0;
}
if (! IsValid()) {
cerr << "TorsionAngle::BuildFromProto:invalid " << *this << '\n';
return 0;
}
return 1;
}
std::ostream&
operator<< (std::ostream& output, const TorsionAngleConstraint& constraint) {
const ConstraintBaseClass& me = constraint;
output << "TorsionAngleConstraint:atoms " << me;
return output;
}
int
TorsionAngleConstraint::Matches(const Molecule& m) {
return _allowed_range.Matches(m.dihedral_angle(_atoms[0], _atoms[1], _atoms[2], _atoms[3]));
}
int
TorsionAngleConstraint::Matches(const Molecule& m, const Set_of_Atoms& embedding) {
return _allowed_range.Matches(m.dihedral_angle(embedding[_atoms[0]], embedding[_atoms[1]], embedding[_atoms[2]], embedding[_atoms[3]]));
}
SetOfGeometricConstraints::SetOfGeometricConstraints() {
_active = 0;
_number_to_match = 0;
}
// The number of constraints across all different kinds.
int
SetOfGeometricConstraints::_number_constraints() const {
return _distances.number_elements() +
_bond_angles.number_elements() +
_torsion_angles.number_elements();
}
int
SetOfGeometricConstraints::IsValid() const {
int nset = _number_constraints();
if (_number_to_match > nset) {
return 0;
}
if (nset == 0 &&_number_to_match > 0) {
return 0;
}
return 1;
}
int
SetOfGeometricConstraints::BuildFromProto(const GeometricConstraints::SetOfConstraints& proto) {
if (proto.number_to_match() > 0) {
_number_to_match = proto.number_to_match();
}
for (const auto& dist : proto.distances()) {
std::unique_ptr<DistanceConstraint> c = std::make_unique<DistanceConstraint>();
if (! c->BuildFromProto(dist)) {
cerr << "SetOfConstraints::BuildFromProto:bad distance " << dist.ShortDebugString() << '\n';
return 0;
}
_distances << c.release();
}
for (const auto& angle : proto.bond_angles()) {
std::unique_ptr<BondAngleConstraint> c = std::make_unique<BondAngleConstraint>();
if (! c->BuildFromProto(angle)) {
cerr << "SetOfConstraints::BuildFromProto:bad angle " << angle.ShortDebugString() << '\n';
return 0;
}
_bond_angles << c.release();
}
for (const auto& torsion : proto.torsion_angles()) {
std::unique_ptr<TorsionAngleConstraint> c = std::make_unique<TorsionAngleConstraint>();
if (! c->BuildFromProto(torsion)) {
cerr << "SetOfConstraints::BuildFromProto:bad torsion " << torsion.ShortDebugString() << '\n';
return 0;
}
_torsion_angles << c.release();
}
_active = 1;
if (_number_to_match == 0) {
_number_to_match = _number_constraints();
}
return IsValid();
}
int
SetOfGeometricConstraints::Matches(const Molecule& m) const {
int matched_here = 0;
for (auto c : _distances) {
if (c->Matches(m)) {
matched_here++;
if (matched_here >= _number_to_match) {
return matched_here;
}
}
}
for (auto c : _bond_angles) {
if (c->Matches(m)) {
matched_here++;
if (matched_here >= _number_to_match) {
return matched_here;
}
}
}
for (auto c : _torsion_angles) {
if (c->Matches(m)) {
matched_here++;
if (matched_here >= _number_to_match) {
return matched_here;
}
}
}
return 0;
}
int
SetOfGeometricConstraints::Matches(const Molecule& m, const Set_of_Atoms& embedding) const {
int matched_here = 0;
#ifdef DEBUG_CONSTRAINTS_MATCHES
std::cerr << "Checking " << _distances.size() << " distance_constraints\n";
#endif
for (auto c : _distances) {
if (c->Matches(m, embedding)) {
matched_here++;
#ifdef DEBUG_CONSTRAINTS_MATCHES
cerr << "distance constaint matched, now " << matched_here << " matches\n";
#endif
if (matched_here >= _number_to_match) {
return matched_here;
}
}
#ifdef DEBUG_CONSTRAINTS_MATCHES
else {
cerr << "Constraint " << *c << " did not match\n";
const auto atoms = c->Atoms();
std::cerr << "dist " << m.distance_between_atoms(embedding[atoms[0]], embedding[atoms[1]]) << '\n';
}
#endif
}
for (auto c : _bond_angles) {
if (c->Matches(m, embedding)) {
matched_here++;
if (matched_here >= _number_to_match) {
return matched_here;
}
}
}
for (auto c : _torsion_angles) {
if (c->Matches(m, embedding)) {
matched_here++;
if (matched_here >= _number_to_match) {
return matched_here;
}
}
}
#ifdef DEBUG_CONSTRAINTS_MATCHES
std::cerr << "only matched " << matched_here << " items\n";
#endif
return 0;
}
template <typename T>
void
write_constraints(const resizable_array_p<T>& constraints, std::ostream& output) {
for (const T * constraint : constraints) {
output << ' ' << *constraint;
}
output << '\n';
}
void
SetOfGeometricConstraints::DebugPrint(std::ostream& output) const {
output << "SetOfGeometricConstraints\n";
if (_distances.size()) {
output << " distances";
write_constraints(_distances, output);
}
if (_bond_angles.size()) {
output << " bond angles";
write_constraints(_bond_angles, output);
}
if (_torsion_angles.size()) {
output << " torsion angles";
write_constraints(_torsion_angles, output);
}
output << "must match " << _number_to_match << '\n';
}
resizable_array<int>
SetOfGeometricConstraints::AtomNumbersPresent() const {
resizable_array<int> result;
for (const auto * c : _distances) {
c->AtomNumbersPresent(result);
}
for (const auto * c : _bond_angles) {
c->AtomNumbersPresent(result);
}
for (const auto * c : _torsion_angles) {
c->AtomNumbersPresent(result);
}
return result;
}
} // namespace geometric_constraints
| 27.109489 | 138 | 0.66532 | IanAWatson |
54426de9ef2b728b2868e7a5316d38c2af5cac61 | 974 | cpp | C++ | Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp | hebohang/HEngine | 82f40797a7cfabaa11aeeb7797fba70551d18017 | [
"MIT"
] | null | null | null | Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp | hebohang/HEngine | 82f40797a7cfabaa11aeeb7797fba70551d18017 | [
"MIT"
] | null | null | null | Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp | hebohang/HEngine | 82f40797a7cfabaa11aeeb7797fba70551d18017 | [
"MIT"
] | null | null | null | #include "hepch.h"
#include "OrthographicCamera.h"
#include <glm/gtc/matrix_transform.hpp>
namespace HEngine
{
OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top)
: mProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), mViewMatrix(1.0f)
{
mViewProjectionMatrix = mProjectionMatrix * mViewMatrix;
}
void OrthographicCamera::SetProjection(float left, float right, float bottom, float top)
{
mProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f);
mViewProjectionMatrix = mProjectionMatrix * mViewMatrix;
}
void OrthographicCamera::RecalculateViewMatrix()
{
glm::mat4 transform = glm::translate(glm::mat4(1.0f), mPosition) *
glm::rotate(glm::mat4(1.0f), glm::radians(mRotation), glm::vec3(0, 0, 1));
mViewMatrix = glm::inverse(transform);
mViewProjectionMatrix = mProjectionMatrix * mViewMatrix;
}
} | 34.785714 | 97 | 0.678645 | hebohang |
5444a52093a712adccddf081f06a8f4564d37db6 | 12,633 | cpp | C++ | FrameSkippingFilter.cpp | CSIR-RTVC/FrameSkippingFilter | a907161384b0bbe670dabcf2b78ad57bd348ec1b | [
"BSD-3-Clause"
] | null | null | null | FrameSkippingFilter.cpp | CSIR-RTVC/FrameSkippingFilter | a907161384b0bbe670dabcf2b78ad57bd348ec1b | [
"BSD-3-Clause"
] | null | null | null | FrameSkippingFilter.cpp | CSIR-RTVC/FrameSkippingFilter | a907161384b0bbe670dabcf2b78ad57bd348ec1b | [
"BSD-3-Clause"
] | 1 | 2021-01-08T18:26:49.000Z | 2021-01-08T18:26:49.000Z | /** @file
MODULE : FrameSkippingFilter
FILE NAME : FrameSkippingFilter.cpp
DESCRIPTION : This filter skips a specified number of frames depending on the parameter denoted by "skipFrame"
LICENSE: Software License Agreement (BSD License)
Copyright (c) 2014, CSIR
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 CSIR 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.
===========================================================================
*/
#include "stdafx.h"
#include "FrameSkippingFilter.h"
#include <cassert>
#include <set>
#include <dvdmedia.h>
// timestamp unit is in 10^-7
const double TIMESTAMP_FACTOR = 10000000.0;
FrameSkippingFilter::FrameSkippingFilter(LPUNKNOWN pUnk, HRESULT *pHr)
: CTransInPlaceFilter(NAME("CSIR VPP Frame Skipping Filter"), pUnk, CLSID_VPP_FrameSkippingFilter, pHr, false),
m_uiSkipFrameNumber(0),
m_uiTotalFrames(1),
m_uiCurrentFrame(0),
m_dSkipRatio(1.0),
m_dTargetFrameRate(0.0),
m_bIsTimeSet(false),
m_dTimeFrame(0.0),
m_dTimeCurrent(0.0),
m_dTargetTimeFrame(0.0),
m_tStart(0),
m_tStop(0)
{
// Init parameters
initParameters();
}
FrameSkippingFilter::~FrameSkippingFilter()
{
}
CUnknown * WINAPI FrameSkippingFilter::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
FrameSkippingFilter *pFilter = new FrameSkippingFilter(pUnk, pHr);
if (pFilter == NULL)
{
*pHr = E_OUTOFMEMORY;
}
return pFilter;
}
STDMETHODIMP FrameSkippingFilter::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
if (riid == (IID_ISettingsInterface))
{
return GetInterface((ISettingsInterface*) this, ppv);
}
if (riid == (IID_ISpecifyPropertyPages))
{
return GetInterface(static_cast<ISpecifyPropertyPages*>(this), ppv);
}
else
{
return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv);
}
}
HRESULT FrameSkippingFilter::Transform(IMediaSample *pSample)
{
/* Check for other streams and pass them on */
// don't skip control info
AM_SAMPLE2_PROPERTIES * const pProps = m_pInput->SampleProps();
if (pProps->dwStreamId != AM_STREAM_MEDIA) {
return S_OK;
}
// select mode
if (m_uiFrameSkippingMode == FSKIP_ACHIEVE_TARGET_RATE)
{
if (m_dTargetFrameRate != 0.0)
{
assert(m_dTargetFrameRate > 0.0);
//set initial time frame
m_dTargetTimeFrame = (1 / m_dTargetFrameRate); // timestamp unit is in 10^-7
HRESULT hr = pSample->GetTime(&m_tStart, &m_tStop);
if (SUCCEEDED(hr))
{
//m_bIsTimeSet runs only once with each rendering to initialize the 1st targetTimeFrame
if (!m_bIsTimeSet)
{
m_dTimeCurrent = m_tStart / TIMESTAMP_FACTOR;
m_dTimeFrame = m_dTimeCurrent + m_dTargetTimeFrame;
m_bIsTimeSet = true;
return S_OK;
}
else
{
m_dTimeCurrent = m_tStart / TIMESTAMP_FACTOR;
if (m_dTimeCurrent > m_dTimeFrame)
{
int multiplier = static_cast<int>(ceil((m_dTimeCurrent - m_dTimeFrame) / m_dTargetTimeFrame));
if (multiplier == 0) { multiplier = 1; }
m_dTimeFrame += (m_dTargetTimeFrame *multiplier);
return S_OK;
}
else
{
return S_FALSE;
}
}
}
else
{
return hr;
}
}
else
{
return S_OK;
}
}
else if (m_uiFrameSkippingMode == FSKIP_SKIP_X_FRAMES_EVERY_Y)
{
if (m_vFramesToBeSkipped.empty())
return S_OK;
int iSkip = m_vFramesToBeSkipped[m_uiCurrentFrame++];
if (m_uiCurrentFrame >= m_vFramesToBeSkipped.size())
{
m_uiCurrentFrame = 0;
}
if (iSkip == 1)
{
return S_FALSE;
}
return S_OK;
}
else
{
assert(false);
return S_OK;
}
#if 0
// adjust frame duration here?
BYTE *pBufferIn, *pBufferOut;
HRESULT hr = pSample->GetPointer(&pBufferIn);
if (FAILED(hr))
{
return hr;
}
VIDEOINFOHEADER *pVih1 = (VIDEOINFOHEADER*)mtIn->pbFormat;
m_dSkipRatio
#endif
}
DEFINE_GUID(MEDIASUBTYPE_I420, 0x30323449, 0x0000, 0x0010, 0x80, 0x00,
0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
HRESULT FrameSkippingFilter::CheckInputType(const CMediaType* mtIn)
{
// Check the major type.
if (mtIn->majortype != MEDIATYPE_Video)
{
return VFW_E_TYPE_NOT_ACCEPTED;
}
if (
(mtIn->subtype != MEDIASUBTYPE_RGB24) && (mtIn->subtype != MEDIASUBTYPE_RGB32) && (mtIn->subtype != MEDIASUBTYPE_I420)
)
{
return VFW_E_TYPE_NOT_ACCEPTED;
}
if (mtIn->formattype != FORMAT_VideoInfo)
{
return VFW_E_TYPE_NOT_ACCEPTED;
}
return S_OK;
}
HRESULT FrameSkippingFilter::Run(REFERENCE_TIME tStart)
{
if (m_uiFrameSkippingMode == FSKIP_SKIP_X_FRAMES_EVERY_Y)
{
m_vFramesToBeSkipped.clear();
int iSkip = 0, iTotal = 0;
bool res = lowestRatio(m_dSourceFrameRate, m_dTargetFrameRate, iSkip, iTotal);
if (res)
{
m_uiSkipFrameNumber = iSkip;
m_uiTotalFrames = iTotal;
// calculate which frames should be dropped
if (m_uiSkipFrameNumber < m_uiTotalFrames && m_uiSkipFrameNumber > 0)
{
double dRatio = m_uiTotalFrames / static_cast<double>(m_uiSkipFrameNumber);
std::set<int> toBeSkipped;
std::set<int> toBePlayed;
// populate to be skipped: note that this index is 1-indexed
for (size_t iCount = 1; iCount <= m_uiSkipFrameNumber; ++iCount)
{
#if _MSC_VER > 1600
int iToBeSkipped = static_cast<int>(round(iCount * dRatio));
#else
int iToBeSkipped = static_cast<int>(floor(iCount * dRatio + 0.5));
#endif
toBeSkipped.insert(iToBeSkipped);
}
// populate to be played
for (size_t iCount = 1; iCount <= m_uiTotalFrames; ++iCount)
{
auto found = toBeSkipped.find(iCount);
if (found == toBeSkipped.end())
{
toBePlayed.insert(iCount);
m_vFramesToBeSkipped.push_back(0);
}
else
{
m_vFramesToBeSkipped.push_back(1);
}
}
}
else
{
// invalid input
m_vFramesToBeSkipped.clear();
}
}
}
return CTransInPlaceFilter::Run(tStart);
}
HRESULT FrameSkippingFilter::Stop(void)
{
m_uiCurrentFrame = 0;
m_vFramesToBeSkipped.clear();
m_bIsTimeSet = false;
return CTransInPlaceFilter::Stop();
}
CBasePin* FrameSkippingFilter::GetPin(int n)
{
HRESULT hr = S_OK;
// Create an input pin if not already done
if (m_pInput == NULL) {
m_pInput = new CTransInPlaceInputPin(NAME("TransInPlace input pin")
, this // Owner filter
, &hr // Result code
, L"Input" // Pin name
);
// Constructor for CTransInPlaceInputPin can't fail
ASSERT(SUCCEEDED(hr));
}
// Create an output pin if not already done
if (m_pInput != NULL && m_pOutput == NULL) {
m_pOutput = new FrameSkippingOutputPin(NAME("Frame skipping output pin")
, this // Owner filter
, &hr // Result code
, L"Output" // Pin name
);
// a failed return code should delete the object
ASSERT(SUCCEEDED(hr));
if (m_pOutput == NULL) {
delete m_pInput;
m_pInput = NULL;
}
}
// Return the appropriate pin
ASSERT(n >= 0 && n <= 1);
if (n == 0) {
return m_pInput;
}
else if (n == 1) {
return m_pOutput;
}
else {
return NULL;
}
} // GetPin
STDMETHODIMP FrameSkippingFilter::SetParameter(const char* type, const char* value)
{
HRESULT hr = CSettingsInterface::SetParameter(type, value);
if (SUCCEEDED(hr))
{
if (m_uiTotalFrames > 0)
m_dSkipRatio = m_uiSkipFrameNumber / static_cast<double>(m_uiTotalFrames);
else
m_dSkipRatio = 0.0;
}
return hr;
}
FrameSkippingOutputPin::FrameSkippingOutputPin
(__in_opt LPCTSTR pObjectName
, __inout CTransInPlaceFilter *pFilter
, __inout HRESULT *phr
, __in_opt LPCWSTR pName
)
: CTransInPlaceOutputPin(pObjectName, pFilter, phr, pName)
{
}
// EnumMediaTypes
// - pass through to our downstream filter
STDMETHODIMP FrameSkippingOutputPin::EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum)
{
HRESULT hr = CTransInPlaceOutputPin::EnumMediaTypes(ppEnum);
if (SUCCEEDED(hr))
{
// modify frame duration
AM_MEDIA_TYPE *pmt = NULL;
while (hr = (*ppEnum)->Next(1, &pmt, NULL), hr == S_OK)
{
adjustAverageTimePerFrameInVideoInfoHeader(pmt);
}
}
return hr;
} // EnumMediaTypes
HRESULT
FrameSkippingOutputPin::SetMediaType(const CMediaType* pmtOut)
{
const AM_MEDIA_TYPE* pMediaType = pmtOut;
adjustAverageTimePerFrameInVideoInfoHeader(const_cast<AM_MEDIA_TYPE*>(pMediaType));
return CTransInPlaceOutputPin::SetMediaType(pmtOut);
}
inline void FrameSkippingOutputPin::adjustAverageTimePerFrameInVideoInfoHeader(AM_MEDIA_TYPE * pmt)
{
if (((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio > 0.0)
{
if ((FORMAT_VideoInfo == pmt->formattype))
{
VIDEOINFOHEADER* pV = (VIDEOINFOHEADER*)pmt->pbFormat;
REFERENCE_TIME duration = static_cast<REFERENCE_TIME>(pV->AvgTimePerFrame / ((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio);
pV->AvgTimePerFrame = duration;
}
else if ((FORMAT_VideoInfo2 == pmt->formattype))
{
VIDEOINFOHEADER2* pV = (VIDEOINFOHEADER2*)pmt->pbFormat;
REFERENCE_TIME duration = static_cast<REFERENCE_TIME>(pV->AvgTimePerFrame / ((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio);
pV->AvgTimePerFrame = duration;
}
}
}
bool FrameSkippingFilter::lowestRatio(double SourceFrameRate, double targetFrameRate, int& iSkipFrame, int& tTotalFrames)
{
if (targetFrameRate > SourceFrameRate)
{
return false;
}
const double EPSILON = 0.0001;
if (SourceFrameRate - targetFrameRate < EPSILON)
{
iSkipFrame = 0;
tTotalFrames = 0;
return true;
}
//get rid of the floating point
//limited to 1 decimal for now
if (fmod(targetFrameRate, 1) != 0 || fmod(SourceFrameRate, 1) != 0)
{
targetFrameRate = targetFrameRate * 10;
SourceFrameRate = SourceFrameRate * 10;
}
double targetFrameRateTemp(round(targetFrameRate)), SourceFrameRateTemp(round(SourceFrameRate));
//Logic to find the greatest common factor
while (true)
{
(targetFrameRateTemp > SourceFrameRateTemp) ? targetFrameRateTemp = remainder(targetFrameRateTemp, SourceFrameRateTemp) :
SourceFrameRateTemp = remainder(SourceFrameRateTemp, targetFrameRateTemp);
if (targetFrameRateTemp < 0)
{
targetFrameRateTemp += SourceFrameRateTemp;
}
else if (SourceFrameRateTemp < 0)
{
SourceFrameRateTemp += targetFrameRateTemp;
}
if (targetFrameRateTemp <= 0 || SourceFrameRateTemp <= 0)
{
break;
}
}
// Divide by the GCF to get the lowest ratio
if (targetFrameRateTemp == 0)
{
iSkipFrame = (unsigned int)((SourceFrameRate - targetFrameRate) / SourceFrameRateTemp);
tTotalFrames = (unsigned int)(SourceFrameRate / SourceFrameRateTemp);
}
else if (SourceFrameRateTemp == 0)
{
iSkipFrame = (unsigned int)((SourceFrameRate - targetFrameRate) / targetFrameRateTemp);
tTotalFrames = (unsigned int)(SourceFrameRate / targetFrameRateTemp);
}
else
{
//The previous loop prevent this from happening
}
return true;
}
| 27.949115 | 204 | 0.675849 | CSIR-RTVC |
544516bca1bac9c8226de0bed344538bd0577e45 | 5,681 | cpp | C++ | Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp | Bodka0904/Dot_Engine | 1db28c56eeecefaed8aa3f1d87932765d5b16dd4 | [
"Apache-2.0"
] | null | null | null | Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp | Bodka0904/Dot_Engine | 1db28c56eeecefaed8aa3f1d87932765d5b16dd4 | [
"Apache-2.0"
] | 7 | 2019-06-04T06:28:21.000Z | 2019-06-05T05:49:55.000Z | Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp | Bodka0904/Dot_Engine | 1db28c56eeecefaed8aa3f1d87932765d5b16dd4 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "LevelEditor.h"
#include "Dot/Renderer/RenderSystem.h"
#include "Dot/Core/Input.h"
#include "Dot/Core/AssetManager.h"
namespace Dot {
LevelEditor::LevelEditor()
{
m_Default = std::make_shared<DefaultUI>();
m_TerrainEditor = std::make_shared<TerrainEditorUI>();
m_DefaultID = GuiApplication::Get()->AddBlock(m_Default);
m_Default->m_TerrainEditorID = GuiApplication::Get()->AddBlock(m_TerrainEditor);
GuiApplication::Get()->SwitchBlock(m_DefaultID);
}
LevelEditor::~LevelEditor()
{
}
void LevelEditor::OnUpdate(float ts)
{
m_Default->m_CamController->OnUpdate(ts * 250.0f);
}
void LevelEditor::OnRender()
{
GuiApplication::Get()->GetCurrent()->OnRender();
}
void LevelEditor::DefaultUI::OnAttach()
{
m_StaticShader = AssetManager::Get()->GetShader("StaticShader");
m_CamController = std::make_shared<Dot::CameraController>(glm::perspectiveFov(glm::radians(45.0f), float(Dot::Input::GetWindowSize().first) * 0.72f, float(Dot::Input::GetWindowSize().second) * 0.72f, 0.1f, 10000.0f));
m_Light = std::make_shared<Dot::Light>();
m_Light->position = glm::vec3(0.0f, 30.0f, 0.0f);
m_Light->color = glm::vec3(0.7f, 0.7f, 0.7f);
m_Light->strength = 1.0f;
m_RenderSystem = ECSManager::Get()->GetSystem<RenderSystem>();
Dot::Layout layout{
{glm::vec2(0.0f,0.0f),glm::vec2(0.2f,1.0f),{
{Dot::ElementType::PANEL,0.3f,"Panel"},
{Dot::ElementType::PANEL,0.3f,"Panel1"},
{Dot::ElementType::PANEL,0.4f,"Panel2"}
}},
{glm::vec2(0.2f,0.0f),glm::vec2(0.6f,1.0f),{
{Dot::ElementType::PANEL,0.08f,"Panel5"},
{Dot::ElementType::WINDOW,0.72f,"Scene"},
{Dot::ElementType::CONSOLE,0.2f,"Console"},
}},
{glm::vec2(0.8f,0.0f),glm::vec2(0.2f,1.0f),{
{Dot::ElementType::PANEL,0.5f,"Panel3"},
{Dot::ElementType::PANEL,0.7f,"Panel4"},
}}
};
SetLayout(layout);
GetPanel("Panel")->AddWidget("Button1", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
GetPanel("Panel")->AddWidget("Button2", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
GetPanel("Panel")->AddWidget("Button3", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
GetPanel("Panel")->AddWidget("Slider", Dot::Slider::Create("slider", glm::vec2(0), glm::vec2(200, 30), glm::vec3(1, 1, 1), &m_Value, -10, 20));
GetPanel("Panel")->AddWidget("Checkbox", Dot::CheckBox::Create("checkbox", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
GetPanel("Panel")->AddWidget("TextArea", Dot::TextArea::Create("textarea", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
GetPanel("Panel")->AddWidget("TextArea1", Dot::TextArea::Create("textarea1", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
GetPanel("Panel")->AddWidget("TextArea2", Dot::TextArea::Create("textarea2", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
GetPanel("Panel")->AddWidget("TextArea3", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
GetPanel("Panel")->AddWidget("Dropdown", Dot::Dropdown::Create("drop", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1)));
GetPanel("Panel5")->AddWidget("Dropdown1", Dot::Dropdown::Create("drop", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1)));
//GetPanel("Panel1")->AddWidget("TextArea3", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
//GetPanel("Panel1")->AddWidget("TextArea4", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0)));
//GetPanel("Panel1")->AddWidget("ArrButton", Dot::ArrowButton::Create("arrbutton", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
//GetPanel("Panel1")->AddWidget("ArrButton2", Dot::ArrowButton::Create("arrbutton", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1)));
Dot::Logger::Get()->ConnectConsole(GetConsole("Console"));
GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test1");
GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test2");
GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test3");
GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test4");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test1");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test2");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test3");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test4");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test5");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test6");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test7");
GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test8");
}
void LevelEditor::DefaultUI::OnUpdate()
{
if (GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").Clicked(1))
{
GuiApplication::Get()->SwitchBlock(m_TerrainEditorID);
}
}
void LevelEditor::DefaultUI::OnEvent(Event& event)
{
}
void LevelEditor::DefaultUI::OnRender()
{
for (auto win : m_Window)
{
win.second->ActivateRenderTarget();
Renderer::Clear(glm::vec4(1, 1, 1, 0));
m_RenderSystem->BeginScene(m_CamController->GetCamera(), m_Light);
{
m_RenderSystem->Render();
}
m_RenderSystem->EndScene(m_StaticShader);
//SceneManager::Get()->GetCurretScene()->OnRender();
}
RenderCommand::SetDefaultRenderTarget();
}
} | 45.448 | 219 | 0.655694 | Bodka0904 |
5445d64b96580e2ea8b77dda8289c0189275a2f2 | 3,615 | cpp | C++ | Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp | SKT-ThingPlug/thingplug-device-sdk-C | fcb12ee172265f882787cc993bd6c5bbe9d876cf | [
"Apache-2.0"
] | 9 | 2017-06-14T11:19:09.000Z | 2020-04-11T08:01:06.000Z | Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp | SKT-ThingPlug/thingplug-device-sdk-C | fcb12ee172265f882787cc993bd6c5bbe9d876cf | [
"Apache-2.0"
] | null | null | null | Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp | SKT-ThingPlug/thingplug-device-sdk-C | fcb12ee172265f882787cc993bd6c5bbe9d876cf | [
"Apache-2.0"
] | 15 | 2017-04-17T00:17:20.000Z | 2021-06-26T04:12:39.000Z | /**
* @file getTime.cpp
*
* @brief Arduino get Time API
*
* Copyright (C) 2016. SPTek,All Rights Reserved.
* Written 2016,by SPTek
*/
#include <Arduino.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <TimeLib.h>
#include "GetTime.h"
EthernetUDP Udp;
unsigned int localPort = 8888; // local port to listen for UDP packets
IPAddress timeServer(132, 163, 4, 101);
const int timeZone = 0; // Central European Time
//const int timeZone = -5; // Eastern Standard Time (USA)
//const int timeZone = -4; // Eastern Daylight Time (USA)
//const int timeZone = -8; // Pacific Standard Time (USA)
//const int timeZone = -7; // Pacific Daylight Time (USA)
/*-------- NTn coe ----------*/
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
time_t getNtpTime()
{
while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
sendNTPpacket(timeServer);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}
void setNtpTime()
{
Udp.begin(localPort);
Serial.println("waiting for sync");
setSyncProvider(getNtpTime);
}
int getHour()
{
return hour();
}
int getMinute()
{
return minute();
}
int getSecond()
{
return second();
}
int getYear()
{
return year();
}
int getMonth()
{
return month();
}
int getDay()
{
return day();
}
/*-------- DISPLAY code ----------*/
void digitalClockDisplay()
{
// digital clock display of the time
Serial.print(hour());
Serial.print(" ");
Serial.print(minute());
Serial.print(" ");
Serial.print(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.println();
}
| 26.386861 | 84 | 0.636515 | SKT-ThingPlug |
544883955e804df11c3ec0c3d75b36934ff48805 | 3,592 | cpp | C++ | modules/voting/voting.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | modules/voting/voting.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | modules/voting/voting.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | /************************************************************************************
*
* Sporks, the learning, scriptable Discord bot!
*
* Copyright 2019 Craig Edwards <support@sporks.gg>
*
* 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 <sporks/bot.h>
#include <sporks/modules.h>
#include <string>
#include <cstdint>
#include <fstream>
#include <streambuf>
#include <sporks/stringops.h>
#include <sporks/database.h>
/**
* Provides a role on the home server when someone votes for the bot on various websites such as top.gg
*/
class VotingModule : public Module
{
public:
VotingModule(Bot* instigator, ModuleLoader* ml) : Module(instigator, ml)
{
ml->Attach({ I_OnPresenceUpdate }, this);
}
virtual ~VotingModule()
{
}
virtual std::string GetVersion()
{
/* NOTE: This version string below is modified by a pre-commit hook on the git repository */
std::string version = "$ModVer 5$";
return "1.0." + version.substr(8,version.length() - 9);
}
virtual std::string GetDescription()
{
return "Awards roles in exchange for votes";
}
virtual bool OnPresenceUpdate()
{
db::resultset rs_votes = db::query("SELECT id, snowflake_id, UNIX_TIMESTAMP(vote_time) AS vote_time, origin, rolegiven FROM infobot_votes", {});
aegis::guild* home = bot->core.find_guild(from_string<int64_t>(Bot::GetConfig("home"), std::dec));
if (home) {
/* Process removals first */
for (auto vote = rs_votes.begin(); vote != rs_votes.end(); ++vote) {
int64_t member_id = from_string<int64_t>((*vote)["snowflake_id"], std::dec);
aegis::user* user = bot->core.find_user(member_id);
if (user) {
if ((*vote)["rolegiven"] == "1") {
/* Role was already given, take away the role and remove the vote IF the date is too far in the past.
* Votes last 24 hours.
*/
uint64_t role_timestamp = from_string<uint64_t>((*vote)["vote_time"], std::dec);
if (time(NULL) - role_timestamp > 86400) {
db::query("DELETE FROM infobot_votes WHERE id = ?", {(*vote)["id"]});
home->remove_guild_member_role(member_id, from_string<int64_t>(Bot::GetConfig("vote_role"), std::dec));
bot->core.log->info("Removing vanity role from {}", member_id);
}
}
}
}
/* Now additions, so that if they've re-voted, it doesnt remove it */
for (auto vote = rs_votes.begin(); vote != rs_votes.end(); ++vote) {
int64_t member_id = from_string<int64_t>((*vote)["snowflake_id"], std::dec);
aegis::user* user = bot->core.find_user(member_id);
if (user) {
if ((*vote)["rolegiven"] == "0") {
/* Role not yet given, give the role and set rolegiven to 1 */
bot->core.log->info("Adding vanity role to {}", member_id);
home->add_guild_member_role(member_id, from_string<int64_t>(Bot::GetConfig("vote_role"), std::dec));
db::query("UPDATE infobot_votes SET rolegiven = 1 WHERE snowflake_id = ?", {(*vote)["snowflake_id"]});
}
}
}
}
return true;
}
};
ENTRYPOINT(VotingModule);
| 35.564356 | 146 | 0.639477 | Clyde-Beep |
5448b945fb8e76168c988f03baf438ae659f8164 | 45,905 | cpp | C++ | hookflash-core/core/hookflash/stack/cpp/stack_PeerFilePrivate.cpp | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | 1 | 2020-02-19T09:55:55.000Z | 2020-02-19T09:55:55.000Z | hookflash-core/core/hookflash/stack/cpp/stack_PeerFilePrivate.cpp | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | null | null | null | hookflash-core/core/hookflash/stack/cpp/stack_PeerFilePrivate.cpp | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | null | null | null | /*
Copyright (c) 2012, SMB Phone Inc.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include <hookflash/stack/internal/stack_PeerContactProfile.h>
#include <hookflash/stack/internal/stack_PeerFiles.h>
#include <hookflash/stack/internal/stack_PeerFilePublic.h>
#include <hookflash/stack/internal/stack_PeerFilePrivate.h>
#include <hookflash/services/ICanonicalXML.h>
#include <hookflash/services/IHelper.h>
#include <zsLib/Log.h>
#include <zsLib/XML.h>
#include <zsLib/Numeric.h>
#include <zsLib/zsHelpers.h>
#include <cryptopp/osrng.h>
#include <cryptopp/rsa.h>
#include <cryptopp/queue.h>
#include <cryptopp/base64.h>
#include <cryptopp/filters.h>
#include <cryptopp/sha.h>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/secblock.h>
#include <cryptopp/hex.h>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#define HOOKFLASH_GENERATE_REAL_RSA_KEYS
namespace hookflash { namespace stack { ZS_DECLARE_SUBSYSTEM(hookflash_stack) } }
namespace hookflash
{
namespace stack
{
namespace internal
{
using zsLib::Numeric;
using zsLib::Stringize;
using CryptoPP::CFB_Mode;
typedef zsLib::BYTE BYTE;
typedef zsLib::UINT UINT;
typedef zsLib::ULONG ULONG;
typedef zsLib::CSTR CSTR;
typedef zsLib::String String;
typedef zsLib::AutoRecursiveLock AutoRecursiveLock;
typedef zsLib::XML::Text Text;
typedef zsLib::XML::TextPtr TextPtr;
typedef zsLib::XML::ElementPtr ElementPtr;
typedef zsLib::XML::Document Document;
typedef zsLib::XML::DocumentPtr DocumentPtr;
typedef CryptoPP::ByteQueue ByteQueue;
typedef CryptoPP::Base64Encoder Base64Encoder;
typedef CryptoPP::Base64Decoder Base64Decoder;
typedef CryptoPP::StringSink StringSink;
typedef CryptoPP::Weak::MD5 MD5;
typedef CryptoPP::SecByteBlock SecureByteBlock;
typedef CryptoPP::AES AES;
typedef CryptoPP::SHA256 SHA256;
typedef CryptoPP::SHA1 SHA1;
typedef CryptoPP::AutoSeededRandomPool AutoSeededRandomPool;
typedef CryptoPP::HexEncoder HexEncoder;
typedef CryptoPP::RSA::PrivateKey CryptoPP_PrivateKey;
typedef CryptoPP::RSA::PublicKey CryptoPP_PublicKey;
typedef CryptoPP::RSASSA_PKCS1v15_SHA_Signer CryptoPP_Signer;
typedef PeerFilePrivate::RSAPrivateKeyPtr RSAPrivateKeyPtr;
typedef PeerFilePublic::RSAPublicKey RSAPublicKey;
typedef PeerFilePublic::RSAPublicKeyPtr RSAPublicKeyPtr;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark (helpers)
#pragma mark
//-----------------------------------------------------------------------
String convertToBase64(
const BYTE *buffer,
ULONG bufferLengthInBytes
)
{
String result;
Base64Encoder encoder(new StringSink(result), false);
encoder.Put(buffer, bufferLengthInBytes);
encoder.MessageEnd();
return result;
}
//-----------------------------------------------------------------------
void convertFromBase64(
const String &input,
SecureByteBlock &output
)
{
ByteQueue queue;
queue.Put((BYTE *)input.c_str(), input.size());
ByteQueue *outputQueue = new ByteQueue;
Base64Decoder decoder(outputQueue);
queue.CopyTo(decoder);
decoder.MessageEnd();
size_t outputLengthInBytes = (size_t)outputQueue->CurrentSize();
output.CleanNew(outputLengthInBytes);
outputQueue->Get(output, outputLengthInBytes);
}
//-----------------------------------------------------------------------
static void getKeyInformation(
const char *prefix,
const char *password,
const String &saltAsBase64,
BYTE *aesIV,
BYTE *aesKey
)
{
if (!password) password = "";
SecureByteBlock saltBinary;
convertFromBase64(saltAsBase64, saltBinary);
// need the salt as a hash (for use as the IV in the AES ecoder)
MD5 saltMD5;
saltMD5.Update(saltBinary, saltBinary.size());
saltMD5.Final(aesIV);
SecureByteBlock key(32);
SHA256 keySHA256;
keySHA256.Update((const BYTE *)prefix, strlen( prefix));
keySHA256.Update((const BYTE *)":", strlen(":"));
keySHA256.Update(saltBinary, saltBinary.size());
keySHA256.Update((const BYTE *)":", strlen(":"));
keySHA256.Update((const BYTE *)password, strlen(password));
keySHA256.Final(key);
memcpy(aesKey, key, 32);
}
//-----------------------------------------------------------------------
String encryptToBase64(
const char *prefix,
const char *password,
const String &saltAsBase64,
const BYTE *buffer,
ULONG length
)
{
SecureByteBlock output(length);
BYTE iv[AES::BLOCKSIZE];
SecureByteBlock key(32);
getKeyInformation(prefix, password, saltAsBase64, &(iv[0]), key);
CFB_Mode<AES>::Encryption cfbEncryption(key, key.size(), iv);
cfbEncryption.ProcessData(output, buffer, length);
String result = convertToBase64(output, output.size());
return result;
}
//-----------------------------------------------------------------------
static void decryptFromBase64(
const char *prefix,
const char *password,
const String &saltAsBase64,
const String &input,
SecureByteBlock &output
)
{
output.New(0);
if (input.isEmpty()) return;
ByteQueue *outputQueue = new ByteQueue;
Base64Decoder decoder(outputQueue);
decoder.Put((const BYTE *)(input.c_str()), input.size());
decoder.MessageEnd();
size_t outputLengthInBytes = (size_t)outputQueue->CurrentSize();
if (0 == outputLengthInBytes) return;
SecureByteBlock inputRaw(outputLengthInBytes);
output.CleanNew(outputLengthInBytes);
outputQueue->Get(inputRaw, outputLengthInBytes);
BYTE iv[AES::BLOCKSIZE];
SecureByteBlock key(32);
getKeyInformation(prefix, password, saltAsBase64, &(iv[0]), key);
CFB_Mode<AES>::Decryption cfbDecryption(key, key.size(), iv);
cfbDecryption.ProcessData(output, inputRaw, outputLengthInBytes);
}
//-----------------------------------------------------------------------
void decryptAndNulTerminateFromBase64(
const char *prefix,
const char *password,
const String &saltAsBase64,
const String &input,
SecureByteBlock &output
)
{
output.CleanNew(1);
if (input.isEmpty()) return;
ByteQueue *outputQueue = new ByteQueue;
Base64Decoder decoder(outputQueue);
decoder.Put((const BYTE *)(input.c_str()), input.size());
decoder.MessageEnd();
size_t outputLengthInBytes = (size_t)outputQueue->CurrentSize();
if (0 == outputLengthInBytes) return;
SecureByteBlock inputRaw(outputLengthInBytes);
output.CleanNew(outputLengthInBytes+1);
outputQueue->Get(inputRaw, outputLengthInBytes);
BYTE iv[AES::BLOCKSIZE];
SecureByteBlock key(32);
getKeyInformation(prefix, password, saltAsBase64, &(iv[0]), key);
CFB_Mode<AES>::Decryption cfbDecryption(key, key.size(), iv);
cfbDecryption.ProcessData(output, inputRaw, outputLengthInBytes);
}
//-----------------------------------------------------------------------
static void actualSignElement(
ElementPtr element,
RSAPrivateKeyPtr privateKey
)
{
ZS_THROW_INVALID_ARGUMENT_IF(!privateKey)
ElementPtr parent = element->getParentElement();
ZS_THROW_INVALID_USAGE_IF(!parent) // can only sign an element that is within an existing "bundle" element...
String id = element->getAttributeValue("id");
if (!id.isEmpty()) {
// strip off any old signatures
try {
ElementPtr oldSignature = parent->findFirstChildElement("Signature");
ElementPtr nextSignature;
for (; oldSignature; oldSignature = nextSignature) {
nextSignature = oldSignature->getNextSiblingElement();
try {
if ("Signature" != oldSignature->getValue()) continue;
ElementPtr referenceElement = oldSignature->findFirstChildElementChecked("SignedInfo")->findFirstChildElementChecked("Reference");
String existingID = referenceElement->getAttributeValue("id");
if (id != existingID) {
ZS_LOG_WARNING(Debug, "Found signature but reference ids do not match, searching=" + id + ", found=" + existingID)
continue;
}
ZS_LOG_TRACE("Found existing signature object and stripping it, reference=" + existingID)
// found it... strip it
oldSignature->orphan();
break;
} catch(zsLib::XML::Exceptions::CheckFailed &) {
}
}
} catch (zsLib::XML::Exceptions::CheckFailed &) {
}
} else {
id = services::IHelper::randomString(20);
element->setAttribute("id", id);
}
static const char *skeletonSignature =
"<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n"
" <SignedInfo>\n"
" <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" />\n"
" <Reference>\n"
" <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" />\n"
" <DigestValue></DigestValue>\n"
" </Reference>\n"
" </SignedInfo>\n"
" <SignatureValue></SignatureValue>\n"
"</Signature>";
DocumentPtr signDoc = Document::create();
signDoc->parse(skeletonSignature);
ElementPtr signatureEl = signDoc->getFirstChildElementChecked();
signatureEl->orphan();
ElementPtr signedInfoEl = signatureEl->getFirstChildElementChecked();
ElementPtr reference = signedInfoEl->findFirstChildElementChecked("Reference");
reference->setAttribute("URI", String("#") + id);
String canonicalXML = hookflash::services::ICanonicalXML::convert(element);
SecureByteBlock hashRaw(20);
SHA1 sha1;
sha1.Update((const BYTE *)(canonicalXML.c_str()), canonicalXML.size());
sha1.Final(hashRaw);
String hash = convertToBase64(hashRaw, hashRaw.size());
ElementPtr digestValue = reference->findFirstChildElementChecked("DigestValue");
TextPtr digestText = Text::create();
digestText->setValue(hash);
digestValue->adoptAsFirstChild(digestText);
//.....................................................................
// compute the signature on the canonical XML of the SignedInfo
String canonicalSignedInfo = hookflash::services::ICanonicalXML::convert(signedInfoEl);
SecureByteBlock signature(20);
privateKey->sign(canonicalSignedInfo, signature);
// singed hash value
String signatureAsBase64 = convertToBase64(signature, signature.size());
ElementPtr signatureValue = signatureEl->findFirstChildElementChecked("SignatureValue");
TextPtr signatureText = Text::create();
signatureText->setValue(signatureAsBase64);
signatureValue->adoptAsFirstChild(signatureText);
element->adoptAsNextSibling(signatureEl);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate
#pragma mark
//-----------------------------------------------------------------------
PeerFilePrivate::PeerFilePrivate(PeerFilesPtr peerFiles) :
mID(zsLib::createPUID()),
mOuter(peerFiles)
{
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate => IPeerFilePrivate
#pragma mark
//-----------------------------------------------------------------------
ElementPtr PeerFilePrivate::saveToXML() const
{
AutoRecursiveLock lock(mLock);
if (!mDocument) return ElementPtr();
ElementPtr peerRoot = mDocument->getFirstChildElement();
if (!peerRoot) return ElementPtr();
return (peerRoot->clone())->toElementChecked();
}
//-----------------------------------------------------------------------
IPeerFilesPtr PeerFilePrivate::getPeerFiles() const
{
AutoRecursiveLock lock(mLock);
return mOuter.lock();
}
//-----------------------------------------------------------------------
UINT PeerFilePrivate::getVersionNumber() const
{
AutoRecursiveLock lock(mLock);
if (!mDocument) return 0;
ElementPtr peerRoot = mDocument->getFirstChildElement();
if (!peerRoot) return 0;
String version = peerRoot->getAttributeValue("version");
try {
return (Numeric<UINT>(version));
} catch(Numeric<UINT>::ValueOutOfRange &) {
}
return 0;
}
//-----------------------------------------------------------------------
bool PeerFilePrivate::containsSection(const char *sectionID) const
{
AutoRecursiveLock lock(mLock);
return findSection(sectionID);
}
//-----------------------------------------------------------------------
bool PeerFilePrivate::verifyPassword(const char *password) const
{
if (!password) password = "";
String salt = getSaltAsBase64();
if (salt.isEmpty()) return false;
ElementPtr sectionBElement = findSection("A");
ElementPtr secretProofElement = sectionBElement->findFirstChildElement("secretProof");
String secretProofInBase64 = secretProofElement->getText();
SecureByteBlock calculatedHashSecret(32); // the caculated hash secret
SecureByteBlock secretProofRaw;
convertFromBase64(secretProofInBase64, secretProofRaw);
if (calculatedHashSecret.size() != secretProofRaw.size()) return false;
{
SecureByteBlock rawSalt;
convertFromBase64(salt, rawSalt);
SecureByteBlock hashProof(32);
SHA256 shaProof;
shaProof.Update((const BYTE *)"proof:", strlen("proof:"));
shaProof.Update((const BYTE *)password, strlen(password));
shaProof.Final(hashProof);
SHA256 shaSecret;
shaSecret.Update((const BYTE *)"secret:", strlen("secret:"));
shaSecret.Update(rawSalt, rawSalt.size());
shaSecret.Update((const BYTE *)":", strlen(":"));
shaSecret.Update(hashProof, hashProof.size());
shaSecret.Final(calculatedHashSecret);
}
return (0 == memcmp(secretProofRaw, calculatedHashSecret, calculatedHashSecret.size()));
}
//-----------------------------------------------------------------------
void PeerFilePrivate::getPrivateKeyInPCKS8(
const char *password,
SecureByteBlock &outRaw
) const
{
outRaw.New(0);
if (!verifyPassword(password)) return;
ElementPtr sectionBElement = findSection("B");
if (!sectionBElement) return;
ElementPtr encryptedPrivateKeyElement = sectionBElement->findFirstChildElement("encryptedPrivateKey");
if (!encryptedPrivateKeyElement) return;
String encryptedPrivateKeyElementAsBase64 = encryptedPrivateKeyElement->getText();
decryptFromBase64("privatekey", password, getSaltAsBase64(), encryptedPrivateKeyElementAsBase64, outRaw);
}
//-----------------------------------------------------------------------
String PeerFilePrivate::getContactProfileSecret(const char *password) const
{
if (!verifyPassword(password)) return String();
ElementPtr sectionBElement = findSection("B");
if (!sectionBElement) return String();
ElementPtr encryptedContactProfileSecretElement = sectionBElement->findFirstChildElement("encryptedContactProfileSecret");
if (!encryptedContactProfileSecretElement) return String();
SecureByteBlock outRaw;
String encryptedContactProfileSecretElementAsBase64 = encryptedContactProfileSecretElement->getText();
decryptAndNulTerminateFromBase64("profile", password, getSaltAsBase64(), encryptedContactProfileSecretElementAsBase64, outRaw);
return (CSTR)((const BYTE *)outRaw);
}
//-----------------------------------------------------------------------
ElementPtr PeerFilePrivate::getCaptcha(const char *password) const
{
return ElementPtr();
}
//-----------------------------------------------------------------------
void PeerFilePrivate::signElement(ElementPtr elementToSign)
{
if (!mPrivateKey) {
ZS_LOG_ERROR(Basic, log("unable to sign element as private key is missing"))
}
actualSignElement(elementToSign, mPrivateKey);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate => friend PeerFiles
#pragma mark
//-----------------------------------------------------------------------
PeerFilesPtr PeerFilePrivate::generate(
PeerFilesPtr peerFiles,
const char *password,
ElementPtr signedSalt
)
{
PeerFilePrivatePtr pThis(new PeerFilePrivate(peerFiles));
pThis->mThisWeak = pThis;
pThis->mOuter = peerFiles;
pThis->generate(password, signedSalt);
peerFiles->mThisWeak = peerFiles;
return peerFiles;
}
//-----------------------------------------------------------------------
PeerFilesPtr PeerFilePrivate::loadFromXML(
PeerFilesPtr peerFiles,
const char *password,
ElementPtr peerFileRootElement
)
{
PeerFilePrivatePtr pThis(new PeerFilePrivate(peerFiles));
pThis->mThisWeak = pThis;
pThis->mOuter = peerFiles;
bool loaded = pThis->loadFromXML(password, peerFileRootElement);
if (!loaded)
return PeerFilesPtr();
peerFiles->mThisWeak = peerFiles;
return peerFiles;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate => (internal)
#pragma mark
//-----------------------------------------------------------------------
String PeerFilePrivate::log(const char *message) const
{
return String("PeerFilePrivate [") + Stringize<PUID>(mID).string() + "] " + message;
}
//-----------------------------------------------------------------------
void PeerFilePrivate::generate(
const char *password,
ElementPtr signedSalt
)
{
if (!password) password = "";
AutoSeededRandomPool rng;
String salt;
String privateString;
String publicString;
String contactID;
String contactProfileSecret = services::IHelper::randomString(32);
std::string contactSalt;
// generate salt
{
SecureByteBlock saltRaw(32);
rng.GenerateBlock(saltRaw, saltRaw.size());
salt = convertToBase64(saltRaw, saltRaw.size());
SecureByteBlock contactSaltRaw(32);
rng.GenerateBlock(contactSaltRaw, contactSaltRaw.size());
contactSalt = convertToBase64(contactSaltRaw, contactSaltRaw.size());
}
#ifdef HOOKFLASH_GENERATE_REAL_RSA_KEYS
RSAPublicKeyPtr publicKey;
SecureByteBlock publicKeyBuffer;
#endif //HOOKFLASH_GENERATE_REAL_RSA_KEYS
{
#ifdef HOOKFLASH_GENERATE_REAL_RSA_KEYS
SecureByteBlock byteBlock;
mPrivateKey = RSAPrivateKey::generate(publicKeyBuffer);
if (!mPrivateKey) {
ZS_THROW_BAD_STATE(log("failed to generate a private/public key pair"))
}
mPrivateKey->save(byteBlock);
publicKey = RSAPublicKey::load(publicKeyBuffer);
if (!publicKey) {
ZS_THROW_BAD_STATE(log("failed to load a public key from previously generated private key"))
}
#else
// generate fake private key and encrypt it immediately
SecureByteBlock byteBlock(100);
rng.GenerateBlock(byteBlock, byteBlock.size());
#endif //HOOKFLASH_GENERATE_REAL_RSA_KEYS
privateString = encryptToBase64("privatekey", password, salt, byteBlock, byteBlock.size());
}
{
#ifdef HOOKFLASH_GENERATE_REAL_RSA_KEYS
SecureByteBlock &byteBlock = publicKeyBuffer;
#else
// generate fake public key
SecureByteBlock byteBlock(100);
rng.GenerateBlock(byteBlock, byteBlock.size());
#endif //HOOKFLASH_GENERATE_REAL_RSA_KEYS
publicString = convertToBase64(byteBlock, byteBlock.size());
}
static const char *skeletonPublicPeer =
"<peer version=\"1\">\n\n"
"<sectionBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <section id=\"A\">\n"
" <cipher>sha1/aes256</cipher>\n"
" <data></data>\n"
" </section>\n"
"</sectionBundle>\n\n"
"<sectionBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <section id=\"B\">\n"
" <contact />\n"
" <findSecret />\n"
" <uris>\n"
" <uri>peer://hookflash.com/contact:</uri>\n"
" </uris>\n"
" </section>\n"
"</sectionBundle>\n\n"
"<sectionBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <section id=\"C\">\n"
" <contact />\n"
" <uris>\n"
" </uris>\n"
" <identities>\n"
" </identities>\n"
" </section>\n"
"</sectionBundle>\n\n"
"</peer>\n";
static const char *skeletonKeyInfo =
"<KeyInfo>\n"
" <X509Data>\n"
" <X509Certificate></X509Certificate>\n"
" </X509Data>\n"
"</KeyInfo>\n";
static const char *skeletonPrivatePeer =
"<privatePeer version=\"1\">\n\n"
"<sectionBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <section id=\"A\">\n"
" <cipher>sha1/aes256</cipher>\n"
" <contact />\n"
" <salt />\n"
" <secretProof />\n"
" </section>\n"
"</sectionBundle>\n\n"
"<sectionBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <section id=\"B\">\n"
" <encryptedPrivateKey />\n"
" <encryptedPeer cipher=\"sha256/aes256\" />\n"
" <encryptedContactProfileSecret />\n"
" <encryptedPrivateData />\n"
" </section>\n"
"</sectionBundle>\n\n"
"</privatePeer>";
static const char *contactProfileSkeleton =
"<contactProfileBundle xmlns=\"http://www.hookflash.com/openpeer/1.0/message\">\n"
" <contactProfile version=\"1\">\n"
" <public>\n"
" <profile />\n"
" </public>\n"
" <private>\n"
" <salt />\n"
" <proof cipher=\"sha256/aes256\" />\n"
" <encryptedPeer cipher=\"sha256/aes256\" />\n"
" <encryptedProfile cipher=\"sha256/aes256\" />\n"
" <contactProfileSecret cipher=\"sha256/aes256\" />\n"
" </private>\n"
" </contactProfile>\n"
"</contactProfileBundle>\n";
mDocument = Document::create();
mDocument->parse(skeletonPrivatePeer);
DocumentPtr publicDoc = Document::create();
publicDoc->parse(skeletonPublicPeer);
DocumentPtr contactProfileDoc = Document::create();
contactProfileDoc->parse(contactProfileSkeleton);
// build public section A
{
// doc->peer->sectionBundle->section A
ElementPtr sectionABundle = publicDoc->getFirstChildElementChecked()->getFirstChildElementChecked();
// sectionBundle->section A
ElementPtr sectionA = sectionABundle->getFirstChildElementChecked();
// sectionA->cipher
ElementPtr cipher = sectionA->getFirstChildElementChecked();
// cipher->adoptAsNextSibling(signedSalt->clone());
actualSignElement(sectionA, mPrivateKey);
// going to put key info inside the signature
ElementPtr signature = sectionA->getNextSiblingElementChecked();
signature->getFirstChildElementChecked();
DocumentPtr keyInfoDoc = Document::create();
keyInfoDoc->parse(skeletonKeyInfo);
ElementPtr keyInfo = keyInfoDoc->getFirstChildElementChecked();
// KeyInfo->X509Data->X509Certificate
ElementPtr x509Certificate = keyInfo->getFirstChildElementChecked()->getFirstChildElementChecked();
TextPtr x509Text = Text::create();
x509Text->setValue(publicString);
x509Certificate->adoptAsLastChild(x509Text);
keyInfo->orphan();
signature->adoptAsLastChild(keyInfo);
String canonicalSectionA = hookflash::services::ICanonicalXML::convert(sectionABundle);
// calculate the hash of section A - which is the contact ID
{
SecureByteBlock contactIDRaw(32);
SHA256 contactIDSHA256;
contactIDSHA256.Update((const BYTE *)canonicalSectionA.c_str(), canonicalSectionA.size());
contactIDSHA256.Final(contactIDRaw);
HexEncoder encoder(new StringSink(contactID));
encoder.Put(contactIDRaw, contactIDRaw.size());
encoder.MessageEnd();
}
}
//std::cout << (publicDoc->write()).get() << "\n";
// build public section B
{
ElementPtr sectionBBundleElement = publicDoc->getFirstChildElementChecked()->getFirstChildElementChecked()->getNextSiblingElementChecked();
ElementPtr contactElement = sectionBBundleElement->getFirstChildElementChecked()->getFirstChildElementChecked();
contactElement->setAttribute("id", contactID);
String findSecret = services::IHelper::randomString(32);
ElementPtr findSecretElement = contactElement->getNextSiblingElementChecked();
TextPtr findSecretText = Text::create();
findSecretText->setValue(findSecret);
findSecretElement->adoptAsLastChild(findSecretText);
TextPtr uriText = findSecretElement->getNextSiblingElementChecked()->getFirstChildElementChecked()->getFirstChildChecked()->toTextChecked();
uriText->setValue(uriText->getValue() + contactID);
actualSignElement(sectionBBundleElement->getFirstChildElementChecked(), mPrivateKey);
}
//std::cout << (publicDoc->write()).get() << "\n";
// build public section C
{
ElementPtr sectionBBundleElement = publicDoc->getFirstChildElementChecked()->getFirstChildElementChecked()->getNextSiblingElementChecked()->getNextSiblingElementChecked();
ElementPtr contactElement = sectionBBundleElement->getFirstChildElementChecked()->getFirstChildElementChecked();
contactElement->setAttribute("id", contactID);
actualSignElement(sectionBBundleElement->getFirstChildElementChecked(), mPrivateKey);
}
//std::cout << (publicDoc->write()).get() << "\n";
// build private section A
{
ElementPtr sectionAElement = mDocument->getFirstChildElementChecked()->getFirstChildElementChecked()->getFirstChildElementChecked();
ElementPtr contactElement = sectionAElement->getFirstChildElementChecked()->getNextSiblingElementChecked();
contactElement->setAttribute("id", contactID);
ElementPtr saltElement = contactElement->getNextSiblingElementChecked();
TextPtr saltText = Text::create();
saltText->setValue(salt);
saltElement->adoptAsLastChild(saltText);
ElementPtr secretProofElement = saltElement->getNextSiblingElementChecked();
TextPtr secretProofText = Text::create();
// calculate the secret proof
{
SecureByteBlock rawSalt;
convertFromBase64(salt, rawSalt);
SecureByteBlock hashProof(32);
SHA256 sha256Proof;
sha256Proof.Update((const BYTE *)"proof:", strlen("proof:"));
sha256Proof.Update((const BYTE *)password, strlen(password));
sha256Proof.Final(hashProof);
SecureByteBlock hashSecret(32);
SHA256 sha256Secret;
sha256Secret.Update((const BYTE *)"secret:", strlen("secret:"));
sha256Secret.Update(rawSalt, rawSalt.size());
sha256Secret.Update((const BYTE *)":", strlen(":"));
sha256Secret.Update(hashProof, hashProof.size());
sha256Secret.Final(hashSecret);
String secret = convertToBase64(hashSecret, hashSecret.size());
secretProofText->setValue(secret);
secretProofElement->adoptAsLastChild(secretProofText);
}
ElementPtr sectionBElement = mDocument->getFirstChildElementChecked()->getFirstChildElementChecked()->getNextSiblingElementChecked()->getFirstChildElementChecked();
ElementPtr encryptedPrivateKeyElement = sectionBElement->getFirstChildElementChecked();
TextPtr encryptedPrivateKeyText = Text::create();
encryptedPrivateKeyText->setValue(privateString);
encryptedPrivateKeyElement->adoptAsLastChild(encryptedPrivateKeyText);
ElementPtr encryptedPeerElement = encryptedPrivateKeyElement->getNextSiblingElementChecked();
boost::shared_array<char> publicPeerAsString;
publicPeerAsString = publicDoc->write();
String encryptedPeerString = encryptToBase64("peer", password, salt, (const BYTE *)publicPeerAsString.get(), strlen(publicPeerAsString.get()));
TextPtr encryptPeerText = Text::create();
encryptPeerText->setValue(encryptedPeerString);
encryptedPeerElement->adoptAsLastChild(encryptPeerText);
ElementPtr encryptedContactProfileSecretElement = encryptedPeerElement->getNextSiblingElementChecked();
String encryptedContactProfileSecretString = encryptToBase64("profile", password, salt, (const BYTE *)contactProfileSecret.c_str(), contactProfileSecret.size());
TextPtr encryptContactProfileSecretText = Text::create();
encryptContactProfileSecretText->setValue(encryptedContactProfileSecretString);
encryptedContactProfileSecretElement->adoptAsLastChild(encryptContactProfileSecretText);
actualSignElement(sectionAElement, mPrivateKey);
actualSignElement(sectionBElement, mPrivateKey);
}
//std::cout << (mDocument->write()).get() << "\n";
// build contact profile
{
ElementPtr contactProfileElement = contactProfileDoc->getFirstChildElementChecked()->getFirstChildElementChecked();
contactProfileElement->setAttribute("id", contactID);
ElementPtr publicElement = contactProfileElement->getFirstChildElementChecked();
publicElement->adoptAsLastChild(publicDoc->getFirstChildElementChecked()->clone());
ElementPtr privateElement = publicElement->getNextSiblingElementChecked();
ElementPtr saltElement = privateElement->getFirstChildElementChecked();
TextPtr saltText = Text::create();
saltText->setValue(contactSalt);
saltElement->adoptAsLastChild(saltText);
SecureByteBlock contactProofHash(32);
SHA256 contactProof;
contactProof.Update((const BYTE *)"proof:", strlen("proof:"));
contactProof.Update((const BYTE *)contactProfileSecret.c_str(), contactProfileSecret.size());
contactProof.Final(contactProofHash);
String contactProofInBase64 = convertToBase64(contactProofHash, contactProofHash.size());
ElementPtr proofElement = saltElement->getNextSiblingElementChecked();
TextPtr proofText = Text::create();
proofText->setValue(contactProofInBase64);
proofElement->adoptAsLastChild(proofText);
ElementPtr encryptedPeerElement = proofElement->getNextSiblingElementChecked();
boost::shared_array<char> publicPeerAsString;
publicPeerAsString = publicDoc->write();
String encryptedPeerString = encryptToBase64("peer", contactProfileSecret, contactSalt, (const BYTE *)publicPeerAsString.get(), strlen(publicPeerAsString.get()));
TextPtr encryptPeerText = Text::create();
encryptPeerText->setValue(encryptedPeerString);
encryptedPeerElement->adoptAsLastChild(encryptPeerText);
const char *emptyProfile = "<profile />";
ElementPtr encryptedProfileElement = encryptedPeerElement->getNextSiblingElementChecked();
String encryptedProfileString = encryptToBase64("profile", contactProfileSecret, contactSalt, (const BYTE *)emptyProfile, strlen(emptyProfile));
TextPtr encryptProfileText = Text::create();
encryptProfileText->setValue(encryptedProfileString);
encryptedProfileElement->adoptAsLastChild(encryptProfileText);
ElementPtr contactProfileSecretElement = encryptedProfileElement->getNextSiblingElementChecked();
TextPtr contactProfileSecretText = Text::create();
contactProfileSecretText->setValue(contactProfileSecret);
contactProfileSecretElement->adoptAsLastChild(contactProfileSecretText);
actualSignElement(contactProfileElement, mPrivateKey);
}
//std::cout << (contactProfileDoc->write()).get() << "\n";
(mOuter.lock())->mPrivate = mThisWeak.lock();
(mOuter.lock())->mPublic = PeerFilePublic::createFromPreGenerated(mOuter.lock(), publicDoc, publicKey);
(mOuter.lock())->mContactProfile = PeerContactProfile::createFromPreGenerated(mOuter.lock(), contactProfileDoc);
}
//-----------------------------------------------------------------------
bool PeerFilePrivate::loadFromXML(
const char *password,
ElementPtr peerFileRootElement
)
{
if (!peerFileRootElement) return false;
if (NULL == password) return false;
mDocument = Document::create();
mDocument->adoptAsLastChild(peerFileRootElement->clone());
if (!verifyPassword(password)) {
ZS_LOG_ERROR(Basic, log("Password does not verify properly for private peer file"))
return false;
}
ElementPtr sectionBElement = findSection("B");
if (!sectionBElement) return false;
ElementPtr encryptedPeerElement = sectionBElement->findFirstChildElement("encryptedPeer");
if (!encryptedPeerElement) return false;
SecureByteBlock outRaw;
String encryptedPeerAsBase64 = encryptedPeerElement->getText();
decryptAndNulTerminateFromBase64("peer", password, getSaltAsBase64(), encryptedPeerAsBase64, outRaw);
String decodedXML = (CSTR)((const BYTE *)outRaw);
if (decodedXML.isEmpty()) return false;
DocumentPtr publicDoc = Document::create();
publicDoc->parse(decodedXML);
PeerFilePublicPtr publicFile = PeerFilePublic::createFromPreGenerated(mOuter.lock(), publicDoc, RSAPublicKeyPtr());
if (!publicFile) return false;
(mOuter.lock())->mPrivate = mThisWeak.lock();
(mOuter.lock())->mPublic = publicFile;
if (!publicFile->containsSection("A")) return false;
SecureByteBlock privateKeyBuffer;
getPrivateKeyInPCKS8(password, privateKeyBuffer);
if (privateKeyBuffer.SizeInBytes() < 1) {
ZS_LOG_ERROR(Basic, log("failed to load private key from XML"))
return false;
}
mPrivateKey = RSAPrivateKey::load(privateKeyBuffer);
if (!mPrivateKey) {
ZS_LOG_ERROR(Basic, log("loading of private key failed to validate"))
return false;
}
return true;
}
//-----------------------------------------------------------------------
String PeerFilePrivate::getSaltAsBase64() const
{
ElementPtr sectionAElement = findSection("A");
if (!sectionAElement) return String();
ElementPtr saltElement = sectionAElement->findFirstChildElement("salt");
if (!saltElement) return String();
return saltElement->getText();
}
//-----------------------------------------------------------------------
ElementPtr PeerFilePrivate::findSection(const char *sectionID) const
{
if (!mDocument) return ElementPtr();
ElementPtr peerRoot = mDocument->getFirstChildElement();
if (!peerRoot) return ElementPtr();
ElementPtr sectionBundleElement = peerRoot->getFirstChildElement();
while (sectionBundleElement) {
ElementPtr sectionElement = sectionBundleElement->getFirstChildElement();
if (sectionElement) {
String id = sectionElement->getAttributeValue("id");
if (id == sectionID) return sectionElement;
}
sectionBundleElement = sectionBundleElement->getNextSiblingElement();
}
return ElementPtr();
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate::RSAPrivateKey
#pragma mark
//-----------------------------------------------------------------------
PeerFilePrivate::RSAPrivateKey::RSAPrivateKey()
{
}
//-------------------------------------------------------------------
#pragma mark
#pragma mark PeerFilePrivate::RSAPrivateKey => friend PeerFilePrivate
#pragma mark
//-----------------------------------------------------------------------
RSAPrivateKeyPtr PeerFilePrivate::RSAPrivateKey::generate(SecureByteBlock &outPublicKeyBuffer)
{
AutoSeededRandomPool rng;
RSAPrivateKeyPtr pThis(new RSAPrivateKey);
pThis->mPrivateKey.GenerateRandomWithKeySize(rng, 2048);
if (!pThis->mPrivateKey.Validate(rng, 3)) {
ZS_LOG_ERROR(Basic, "failed to generate a new private key")
return RSAPrivateKeyPtr();
}
CryptoPP_PublicKey rsaPublic(pThis->mPrivateKey);
if (!rsaPublic.Validate(rng, 3)) {
ZS_LOG_ERROR(Basic, "Failed to generate a public key for the new private key")
return RSAPrivateKeyPtr();
}
ByteQueue byteQueue;
rsaPublic.Save(byteQueue);
size_t outputLengthInBytes = (size_t)byteQueue.CurrentSize();
outPublicKeyBuffer.CleanNew(outputLengthInBytes);
byteQueue.Get(outPublicKeyBuffer, outputLengthInBytes);
return pThis;
}
//-----------------------------------------------------------------------
RSAPrivateKeyPtr PeerFilePrivate::RSAPrivateKey::load(const SecureByteBlock &buffer)
{
AutoSeededRandomPool rng;
ByteQueue byteQueue;
byteQueue.LazyPut(buffer.BytePtr(), buffer.SizeInBytes());
byteQueue.FinalizeLazyPut();
RSAPrivateKeyPtr pThis(new RSAPrivateKey());
try {
pThis->mPrivateKey.Load(byteQueue);
if (!pThis->mPrivateKey.Validate(rng, 3)) {
ZS_LOG_ERROR(Basic, "Failed to load an existing private key")
return RSAPrivateKeyPtr();
}
} catch (CryptoPP::Exception &e) {
ZS_LOG_ERROR(Basic, String("cryptography library threw an exception, reason=") + e.what())
return RSAPrivateKeyPtr();
}
return pThis;
}
//-----------------------------------------------------------------------
void PeerFilePrivate::RSAPrivateKey::save(SecureByteBlock &outBuffer) const
{
ByteQueue byteQueue;
mPrivateKey.Save(byteQueue);
size_t outputLengthInBytes = (size_t)byteQueue.CurrentSize();
outBuffer.CleanNew(outputLengthInBytes);
byteQueue.Get(outBuffer, outputLengthInBytes);
}
//-----------------------------------------------------------------------
void PeerFilePrivate::RSAPrivateKey::sign(
const String &inStrDataToSign,
SecureByteBlock &outSignatureResult
) const
{
AutoSeededRandomPool rng;
CryptoPP_Signer signer(mPrivateKey);
size_t length = signer.MaxSignatureLength();
outSignatureResult.CleanNew(length);
signer.SignMessage(rng, (const BYTE *)(inStrDataToSign.c_str()), inStrDataToSign.length(), outSignatureResult);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
}
}
}
| 40.373791 | 181 | 0.564078 | ilin-in |
544a45e9ba7d9dedbdacaf31bca8f2dd4a89b1bc | 3,641 | cpp | C++ | Project/jsonHandler.cpp | Wasdns/Deputy | d59301f22bbea60da4ba7aa0076e1eabbf2756b4 | [
"Apache-2.0"
] | null | null | null | Project/jsonHandler.cpp | Wasdns/Deputy | d59301f22bbea60da4ba7aa0076e1eabbf2756b4 | [
"Apache-2.0"
] | null | null | null | Project/jsonHandler.cpp | Wasdns/Deputy | d59301f22bbea60da4ba7aa0076e1eabbf2756b4 | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <fstream>
#include <iostream>
#include <jsoncpp/json/json.h>
#include "definition.h"
#include "jsonHandler.h"
using namespace std;
extern students student[310];
extern departments department[25];
extern addmitted addmitted_department[25];
/*
* Function Name: processJSON
* Used to process input JSON file
*/
bool jsonHandler::processJSON(const char* jsonFile) {
Json::Reader reader;
Json::Value root;
// open the JSON file
ifstream stream;
stream.open(jsonFile, ios::binary);
int studentNumber = 300, departmentNumber = 20;
if (reader.parse(stream, root)) {
// the input student number != 300, raise exception
if (root["students"].size() != studentNumber) {
cout << "Error: Student Number doesn't match!" << endl;
return false;
}
// the input department number != 20, raise exception
if (root["departments"].size() != departmentNumber) {
cout << "Error: Department Number doesn't match!" << endl;
return false;
}
string student_number;
int applications_department_number, tag_number, free_time_number;
// initial each of the students
for (int i = 0; i < studentNumber; i++) {
// for each of the instances, initialing corresponding fields
student_number = root["students"][i]["student_no"].asString();
student[i].student_number = student_number;
applications_department_number = root["students"][i]["applications_department"].size();
student[i].applications_department_number = applications_department_number;
tag_number = root["students"][i]["tags"].size();
student[i].tag_number = tag_number;
free_time_number = root["students"][i]["free_time"].size();
student[i].free_time_number = free_time_number;
// initialing the applications_department of each of the students
for (int j = 0; j < applications_department_number; j++) {
student[i].applications_department[j] = root["students"][i]["applications_department"][j].asString();
}
// initialing the tag of each of the students
for (int j = 0; j < tag_number; j++) {
student[i].tags[j] = root["students"][i]["tags"][j].asString();
}
// initialing the free_time of each of the students
for (int j = 0; j < free_time_number; j++) {
student[i].free_time[j] = root["students"][i]["free_time"][j].asString();
}
}
string department_number;
int member_limit = 0, event_schedules_number;
tag_number = 0;
// initialing each of the departments
for (int i = 0; i < departmentNumber; i++) {
// for each of the instances, initialing corresponding fields
department_number = root["departments"][i]["department_no"].asString();
department[i].department_number = department_number;
member_limit = root["departments"][i]["member_limit"].asInt();
department[i].member_limit = member_limit;
tag_number = root["departments"][i]["tags"].size();
department[i].tag_number = tag_number;
event_schedules_number = root["departments"][i]["event_schedules"].size();
department[i].event_schedules_number = event_schedules_number;
// initialing the tag of each of the departments
for (int j = 0; j < tag_number; j++) {
department[i].tags[j] = root["departments"][i]["tags"][j].asString();
}
// initialing the event_schedules of each of the departments
for (int j = 0; j < event_schedules_number; j++) {
department[i].event_schedules[j] = root["departments"][i]["event_schedules"][j].asString();
}
}
} else { // raise parsing error
cout << "Error: Reader parsing error!" << endl;
cout << reader.getFormattedErrorMessages() << endl;
return false;
}
stream.close();
return true;
}
| 32.221239 | 105 | 0.691843 | Wasdns |
544af50cfdbbf197a44da8d367117dfb3fb8cf87 | 15,531 | cc | C++ | Launchers/RunP2PAlgo.cc | LBNL-UCB-STI/routing-framework | 8dc1f5c008384051132bf5819056584700623417 | [
"MIT"
] | 32 | 2017-11-11T15:19:57.000Z | 2021-11-16T04:41:54.000Z | Launchers/RunP2PAlgo.cc | kirilsol/routing-framework | 80026caeddf84ef939742f33fcc69e865c51dbeb | [
"MIT"
] | 1 | 2020-05-17T07:21:56.000Z | 2020-05-17T07:21:56.000Z | Launchers/RunP2PAlgo.cc | kirilsol/routing-framework | 80026caeddf84ef939742f33fcc69e865c51dbeb | [
"MIT"
] | 10 | 2017-10-17T01:34:09.000Z | 2022-02-10T06:19:30.000Z | #include <chrono>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <csv.h>
#include <routingkit/nested_dissection.h>
#include "Algorithms/CCH/CCH.h"
#include "Algorithms/CCH/CCHMetric.h"
#include "Algorithms/CCH/EliminationTreeQuery.h"
#include "Algorithms/CH/CH.h"
#include "Algorithms/CH/CHQuery.h"
#include "Algorithms/Dijkstra/BiDijkstra.h"
#include "Algorithms/Dijkstra/Dijkstra.h"
#include "DataStructures/Graph/Attributes/LatLngAttribute.h"
#include "DataStructures/Graph/Attributes/LengthAttribute.h"
#include "DataStructures/Graph/Attributes/TravelTimeAttribute.h"
#include "DataStructures/Graph/Graph.h"
#include "DataStructures/Labels/BasicLabelSet.h"
#include "DataStructures/Labels/ParentInfo.h"
#include "DataStructures/Partitioning/SeparatorDecomposition.h"
#include "Tools/CommandLine/CommandLineParser.h"
#include "Tools/StringHelpers.h"
#include "Tools/Timer.h"
inline void printUsage() {
std::cout <<
"Usage: RunP2PAlgo -a CH -o <file> -g <file>\n"
" RunP2PAlgo -a CCH -o <file> -g <file> [-b <balance>]\n\n"
" RunP2PAlgo -a CCH-custom -o <file> -g <file> -s <file> [-n <num>]\n\n"
" RunP2PAlgo -a Dij -o <file> -g <file> -d <file>\n"
" RunP2PAlgo -a Bi-Dij -o <file> -g <file> -d <file>\n"
" RunP2PAlgo -a CH -o <file> -h <file> -d <file>\n"
" RunP2PAlgo -a CCH-Dij -o <file> -g <file> -d <file> -s <file>\n"
" RunP2PAlgo -a CCH-tree -o <file> -g <file> -d <file> -s <file>\n\n"
"Runs the preprocessing, customization or query phase of various point-to-point\n"
"shortest-path algorithms, such as Dijkstra, bidirectional search, CH, and CCH.\n\n"
" -l use physical lengths as metric (default: travel times)\n"
" -no-stall do not use the stall-on-demand technique\n"
" -a <algo> run algorithm <algo>\n"
" -b <balance> balance parameter in % for nested dissection (default: 30)\n"
" -n <num> run customization <num> times (default: 1000)\n"
" -g <file> input graph in binary format\n"
" -s <file> separator decomposition of input graph\n"
" -h <file> weighted contraction hierarchy\n"
" -d <file> file that contains OD pairs (queries)\n"
" -o <file> place output in <file>\n"
" -help display this help and exit\n";
}
// Some helper aliases.
using VertexAttributes = VertexAttrs<LatLngAttribute>;
using EdgeAttributes = EdgeAttrs<LengthAttribute, TravelTimeAttribute>;
using InputGraph = StaticGraph<VertexAttributes, EdgeAttributes>;
using LabelSet = BasicLabelSet<0, ParentInfo::NO_PARENT_INFO>;
// The query algorithms.
using Dij = Dijkstra<InputGraph, TravelTimeAttribute, LabelSet>;
using BiDij = BiDijkstra<Dij>;
template <bool useStalling>
using CCHDij = CHQuery<LabelSet, useStalling>;
using CCHTree = EliminationTreeQuery<LabelSet>;
// Writes the header line of the output CSV file.
template <typename AlgoT>
inline void writeHeaderLine(std::ofstream& out, AlgoT&) {
out << "distance,query_time" << '\n';
}
// Writes a record line of the output CSV file, containing statistics about a single query.
template <typename AlgoT>
inline void writeRecordLine(std::ofstream& out, AlgoT& algo, const int, const int64_t elapsed) {
out << algo.getDistance() << ',' << elapsed << '\n';
}
template <>
inline void writeRecordLine(std::ofstream& out, Dij& algo, const int dst, const int64_t elapsed) {
out << algo.getDistance(dst) << ',' << elapsed << '\n';
}
// Runs the specified P2P algorithm on the given OD pairs.
template <typename AlgoT, typename T>
inline void runQueries(AlgoT& algo, const std::string& demand, std::ofstream& out, T translate) {
Timer timer;
int src, dst, rank;
using TrimPolicy = io::trim_chars<>;
using QuotePolicy = io::no_quote_escape<','>;
using OverflowPolicy = io::throw_on_overflow;
using CommentPolicy = io::single_line_comment<'#'>;
io::CSVReader<3, TrimPolicy, QuotePolicy, OverflowPolicy, CommentPolicy> demandFile(demand);
const auto ignore = io::ignore_extra_column | io::ignore_missing_column;
demandFile.read_header(ignore, "origin", "destination", "dijkstra_rank");
const auto hasRanks = demandFile.has_column("dijkstra_rank");
if (hasRanks) out << "dijkstra_rank,";
writeHeaderLine(out, algo);
while (demandFile.read_row(src, dst, rank)) {
src = translate(src);
dst = translate(dst);
timer.restart();
algo.run(src, dst);
const auto elapsed = timer.elapsed<std::chrono::nanoseconds>();
if (hasRanks) out << rank << ',';
writeRecordLine(out, algo, dst, elapsed);
}
}
// Invoked when the user wants to run the query phase of a P2P algorithm.
inline void runQueries(const CommandLineParser& clp) {
const auto useLengths = clp.isSet("l");
const auto noStalling = clp.isSet("no-stall");
const auto algorithmName = clp.getValue<std::string>("a");
const auto graphFileName = clp.getValue<std::string>("g");
const auto sepFileName = clp.getValue<std::string>("s");
const auto chFileName = clp.getValue<std::string>("h");
const auto demandFileName = clp.getValue<std::string>("d");
auto outputFileName = clp.getValue<std::string>("o");
// Open the output CSV file.
if (!endsWith(outputFileName, ".csv"))
outputFileName += ".csv";
std::ofstream outputFile(outputFileName);
if (!outputFile.good())
throw std::invalid_argument("file cannot be opened -- '" + outputFileName + ".csv'");
if (algorithmName == "Dij") {
// Run the query phase of Dijkstra's algorithm.
std::ifstream graphFile(graphFileName, std::ios::binary);
if (!graphFile.good())
throw std::invalid_argument("file not found -- '" + graphFileName + "'");
InputGraph graph(graphFile);
graphFile.close();
if (useLengths)
FORALL_EDGES(graph, e)
graph.travelTime(e) = graph.length(e);
outputFile << "# Graph: " << graphFileName << '\n';
outputFile << "# OD pairs: " << demandFileName << '\n';
Dij algo(graph);
runQueries(algo, demandFileName, outputFile, [](const int v) { return v; });
} else if (algorithmName == "Bi-Dij") {
// Run the query phase of bidirectional search.
std::ifstream graphFile(graphFileName, std::ios::binary);
if (!graphFile.good())
throw std::invalid_argument("file not found -- '" + graphFileName + "'");
InputGraph graph(graphFile);
graphFile.close();
if (useLengths)
FORALL_EDGES(graph, e)
graph.travelTime(e) = graph.length(e);
outputFile << "# Graph: " << graphFileName << '\n';
outputFile << "# OD pairs: " << demandFileName << '\n';
InputGraph reverseGraph = graph.getReverseGraph();
BiDij algo(graph, reverseGraph);
runQueries(algo, demandFileName, outputFile, [](const int v) { return v; });
} else if (algorithmName == "CH") {
// Run the query phase of CH.
std::ifstream chFile(chFileName, std::ios::binary);
if (!chFile.good())
throw std::invalid_argument("file not found -- '" + chFileName + "'");
CH ch(chFile);
chFile.close();
outputFile << "# CH: " << chFileName << '\n';
outputFile << "# OD pairs: " << demandFileName << '\n';
if (noStalling) {
CCHDij<false> algo(ch);
runQueries(algo, demandFileName, outputFile, [&](const int v) { return ch.rank(v); });
} else {
CCHDij<true> algo(ch);
runQueries(algo, demandFileName, outputFile, [&](const int v) { return ch.rank(v); });
}
} else if (algorithmName == "CCH-Dij") {
// Run the Dijkstra-based query phase of CCH.
std::ifstream graphFile(graphFileName, std::ios::binary);
if (!graphFile.good())
throw std::invalid_argument("file not found -- '" + graphFileName + "'");
InputGraph graph(graphFile);
graphFile.close();
std::ifstream sepFile(sepFileName, std::ios::binary);
if (!sepFile.good())
throw std::invalid_argument("file not found -- '" + sepFileName + "'");
SeparatorDecomposition sepDecomp;
sepDecomp.readFrom(sepFile);
sepFile.close();
CCH cch;
cch.preprocess(graph, sepDecomp);
CCHMetric metric(cch, useLengths ? &graph.length(0) : &graph.travelTime(0));
const auto minCH = metric.buildMinimumWeightedCH();
outputFile << "# Graph: " << graphFileName << '\n';
outputFile << "# Separator: " << sepFileName << '\n';
outputFile << "# OD pairs: " << demandFileName << '\n';
if (noStalling) {
CCHDij<false> algo(minCH);
runQueries(algo, demandFileName, outputFile, [&](const int v) { return minCH.rank(v); });
} else {
CCHDij<true> algo(minCH);
runQueries(algo, demandFileName, outputFile, [&](const int v) { return minCH.rank(v); });
}
} else if (algorithmName == "CCH-tree") {
// Run the elimination-tree-based query phase of CCH.
std::ifstream graphFile(graphFileName, std::ios::binary);
if (!graphFile.good())
throw std::invalid_argument("file not found -- '" + graphFileName + "'");
InputGraph graph(graphFile);
graphFile.close();
std::ifstream sepFile(sepFileName, std::ios::binary);
if (!sepFile.good())
throw std::invalid_argument("file not found -- '" + sepFileName + "'");
SeparatorDecomposition sepDecomp;
sepDecomp.readFrom(sepFile);
sepFile.close();
CCH cch;
cch.preprocess(graph, sepDecomp);
CCHMetric metric(cch, useLengths ? &graph.length(0) : &graph.travelTime(0));
const auto minCH = metric.buildMinimumWeightedCH();
outputFile << "# Graph: " << graphFileName << '\n';
outputFile << "# Separator: " << sepFileName << '\n';
outputFile << "# OD pairs: " << demandFileName << '\n';
CCHTree algo(minCH, cch.getEliminationTree());
runQueries(algo, demandFileName, outputFile, [&](const int v) { return minCH.rank(v); });
} else {
throw std::invalid_argument("invalid P2P algorithm -- '" + algorithmName + "'");
}
}
// Invoked when the user wants to run the preprocessing or customization phase of a P2P algorithm.
inline void runPreprocessing(const CommandLineParser& clp) {
const auto useLengths = clp.isSet("l");
const auto imbalance = clp.getValue<int>("b", 30);
const auto numCustomRuns = clp.getValue<int>("n", 1000);
const auto algorithmName = clp.getValue<std::string>("a");
const auto graphFileName = clp.getValue<std::string>("g");
const auto sepFileName = clp.getValue<std::string>("s");
auto outputFileName = clp.getValue<std::string>("o");
// Read the input graph.
std::ifstream graphFile(graphFileName, std::ios::binary);
if (!graphFile.good())
throw std::invalid_argument("file not found -- '" + graphFileName + "'");
InputGraph graph(graphFile);
graphFile.close();
if (useLengths)
FORALL_EDGES(graph, e)
graph.travelTime(e) = graph.length(e);
if (algorithmName == "CH") {
// Run the preprocessing phase of CH.
if (!endsWith(outputFileName, ".ch.bin"))
outputFileName += ".ch.bin";
std::ofstream outputFile(outputFileName, std::ios::binary);
if (!outputFile.good())
throw std::invalid_argument("file cannot be opened -- '" + outputFileName);
CH ch;
ch.preprocess<TravelTimeAttribute>(graph);
ch.writeTo(outputFile);
} else if (algorithmName == "CCH") {
// Run the preprocessing phase of CCH.
if (imbalance < 0)
throw std::invalid_argument("invalid imbalance -- '" + std::to_string(imbalance) + "'");
// Convert the input graph to RoutingKit's graph representation.
std::vector<float> lats(graph.numVertices());
std::vector<float> lngs(graph.numVertices());
std::vector<unsigned int> tails(graph.numEdges());
std::vector<unsigned int> heads(graph.numEdges());
FORALL_VERTICES(graph, u) {
lats[u] = graph.latLng(u).latInDeg();
lngs[u] = graph.latLng(u).lngInDeg();
FORALL_INCIDENT_EDGES(graph, u, e) {
tails[e] = u;
heads[e] = graph.edgeHead(e);
}
}
// Compute a separator decomposition for the input graph.
const auto fragment = RoutingKit::make_graph_fragment(graph.numVertices(), tails, heads);
auto computeSep = [&](const RoutingKit::GraphFragment& fragment) {
const auto cut = inertial_flow(fragment, imbalance, lats, lngs);
return derive_separator_from_cut(fragment, cut.is_node_on_side);
};
const auto decomp = compute_separator_decomposition(fragment, computeSep);
// Convert the separator decomposition to our representation.
SeparatorDecomposition sepDecomp;
for (const auto& n : decomp.tree) {
SeparatorDecomposition::Node node;
node.leftChild = n.left_child;
node.rightSibling = n.right_sibling;
node.firstSeparatorVertex = n.first_separator_vertex;
node.lastSeparatorVertex = n.last_separator_vertex;
sepDecomp.tree.push_back(node);
}
sepDecomp.order.assign(decomp.order.begin(), decomp.order.end());
if (!endsWith(outputFileName, ".sep.bin"))
outputFileName += ".sep.bin";
std::ofstream outputFile(outputFileName, std::ios::binary);
if (!outputFile.good())
throw std::invalid_argument("file cannot be opened -- '" + outputFileName);
sepDecomp.writeTo(outputFile);
} else if (algorithmName == "CCH-custom") {
// Run the customization phase of CCH.
std::ifstream sepFile(sepFileName, std::ios::binary);
if (!sepFile.good())
throw std::invalid_argument("file not found -- '" + sepFileName + "'");
SeparatorDecomposition decomp;
decomp.readFrom(sepFile);
sepFile.close();
if (!endsWith(outputFileName, ".csv"))
outputFileName += ".csv";
std::ofstream outputFile(outputFileName);
if (!outputFile.good())
throw std::invalid_argument("file cannot be opened -- '" + outputFileName + ".csv'");
outputFile << "# Graph: " << graphFileName << '\n';
outputFile << "# Separator: " << sepFileName << '\n';
outputFile << "basic_customization,perfect_customization,construction,total_time\n";
CCH cch;
cch.preprocess(graph, decomp);
Timer timer;
int basicCustom, perfectCustom, construct, tot;
for (auto i = 0; i < numCustomRuns; ++i) {
{
CCHMetric metric(cch, &graph.travelTime(0));
timer.restart();
metric.customize();
basicCustom = timer.elapsed<std::chrono::microseconds>();
timer.restart();
metric.runPerfectCustomization();
perfectCustom = timer.elapsed<std::chrono::microseconds>();
}
{
CCHMetric metric(cch, &graph.travelTime(0));
timer.restart();
metric.buildMinimumWeightedCH();
tot = timer.elapsed<std::chrono::microseconds>();
}
construct = tot - basicCustom - perfectCustom;
outputFile << basicCustom << ',' << perfectCustom << ',' << construct << ',' << tot << '\n';
}
} else {
throw std::invalid_argument("invalid P2P algorithm -- '" + algorithmName + "'");
}
}
int main(int argc, char* argv[]) {
try {
CommandLineParser clp(argc, argv);
if (clp.isSet("help"))
printUsage();
else if (clp.isSet("d"))
runQueries(clp);
else
runPreprocessing(clp);
} catch (std::exception& e) {
std::cerr << argv[0] << ": " << e.what() << std::endl;
std::cerr << "Try '" << argv[0] <<" -help' for more information." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 38.253695 | 98 | 0.652437 | LBNL-UCB-STI |
544b77d96f7fff2b482d1abc1c2720a9f259ee1c | 202 | cpp | C++ | qtglgame/mainwindow.cpp | Darkness-ua/cube-labyrinth-game | 3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2 | [
"Unlicense"
] | null | null | null | qtglgame/mainwindow.cpp | Darkness-ua/cube-labyrinth-game | 3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2 | [
"Unlicense"
] | null | null | null | qtglgame/mainwindow.cpp | Darkness-ua/cube-labyrinth-game | 3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include "mainwindow.h"
#include "window.h"
using namespace std;
MainWindow::MainWindow()
{
setWindowTitle(tr("QT GLGame"));
setCentralWidget(new Window(this));
}
| 10.631579 | 39 | 0.678218 | Darkness-ua |
544c6659570a114807c6baf19bf6fe201eb2f5b6 | 6,079 | cpp | C++ | ort/cv/ssd_mobilenetv1.cpp | Imudassir77/lite.ai.toolkit | 3b62ccfea7d3b9f8e010b08a5092a798bc45cf56 | [
"MIT"
] | 1 | 2021-08-09T09:13:49.000Z | 2021-08-09T09:13:49.000Z | ort/cv/ssd_mobilenetv1.cpp | Imudassir77/lite.ai.toolkit | 3b62ccfea7d3b9f8e010b08a5092a798bc45cf56 | [
"MIT"
] | null | null | null | ort/cv/ssd_mobilenetv1.cpp | Imudassir77/lite.ai.toolkit | 3b62ccfea7d3b9f8e010b08a5092a798bc45cf56 | [
"MIT"
] | 1 | 2021-08-10T03:58:55.000Z | 2021-08-10T03:58:55.000Z | //
// Created by DefTruth on 2021/6/5.
//
#include "ssd_mobilenetv1.h"
#include "ort/core/ort_utils.h"
using ortcv::SSDMobileNetV1;
SSDMobileNetV1::SSDMobileNetV1(const std::string &_onnx_path, unsigned int _num_threads) :
log_id(_onnx_path.data()), num_threads(_num_threads)
{
#ifdef LITE_WIN32
std::wstring _w_onnx_path(ortcv::utils::to_wstring(_onnx_path));
onnx_path = _w_onnx_path.data();
#else
onnx_path = _onnx_path.data();
#endif
ort_env = Ort::Env(ORT_LOGGING_LEVEL_ERROR, log_id);
// 0. session options
Ort::SessionOptions session_options;
session_options.SetIntraOpNumThreads(num_threads);
session_options.SetGraphOptimizationLevel(
GraphOptimizationLevel::ORT_ENABLE_EXTENDED);
session_options.SetLogSeverityLevel(4);
// 1. session
ort_session = new Ort::Session(ort_env, onnx_path, session_options);
Ort::AllocatorWithDefaultOptions allocator;
// 2. input name & input dims
num_inputs = ort_session->GetInputCount();
input_node_names.resize(num_inputs);
// 3. initial input node dims.
input_node_dims.push_back({batch_size, input_height, input_width, 3}); // NHWC
input_tensor_sizes.push_back(batch_size * input_height * input_width * 3);
input_values_handler.resize(batch_size * input_height * input_width * 3);
for (unsigned int i = 0; i < num_inputs; ++i)
input_node_names[i] = ort_session->GetInputName(i, allocator);
// 4. output names & output dimms
num_outputs = ort_session->GetOutputCount();
output_node_names.resize(num_outputs);
for (unsigned int i = 0; i < num_outputs; ++i)
output_node_names[i] = ort_session->GetOutputName(i, allocator);
#if LITEORT_DEBUG
this->print_debug_string();
#endif
}
SSDMobileNetV1::~SSDMobileNetV1()
{
if (ort_session)
delete ort_session;
ort_session = nullptr;
}
void SSDMobileNetV1::print_debug_string()
{
std::cout << "LITEORT_DEBUG LogId: " << onnx_path << "\n";
std::cout << "=============== Inputs ==============\n";
for (unsigned int i = 0; i < num_inputs; ++i)
for (unsigned int j = 0; j < input_node_dims.at(i).size(); ++j)
std::cout << "Input: " << i << " Name: "
<< input_node_names.at(i) << " Dim: " << j << " :"
<< input_node_dims.at(i).at(j) << std::endl;
std::cout << "=============== Outputs ==============\n";
for (unsigned int i = 0; i < num_outputs; ++i)
std::cout << "Dynamic Output " << i << ": " << output_node_names[i] << std::endl;
}
Ort::Value SSDMobileNetV1::transform(const cv::Mat &mat)
{
cv::Mat canvas = mat.clone();
cv::resize(canvas, canvas, cv::Size(input_width, input_height));
cv::cvtColor(canvas, canvas, cv::COLOR_BGR2RGB); // uint8 hwc
// HWC
std::memcpy(input_values_handler.data(), canvas.data,
input_tensor_sizes.at(0) * sizeof(uchar));
return Ort::Value::CreateTensor<uchar>(memory_info_handler, input_values_handler.data(),
input_tensor_sizes.at(0),
input_node_dims.at(0).data(),
input_node_dims.at(0).size());
}
void SSDMobileNetV1::detect(const cv::Mat &mat, std::vector<types::Boxf> &detected_boxes,
float score_threshold, float iou_threshold,
unsigned int topk, unsigned int nms_type)
{
if (mat.empty()) return;
const unsigned int img_height = mat.rows;
const unsigned int img_width = mat.cols;
// 1. make input tensor
Ort::Value input_tensor = this->transform(mat);
// 2. inference nums & boxes & scores & classes.
auto output_tensors = ort_session->Run(
Ort::RunOptions{nullptr}, input_node_names.data(),
&input_tensor, num_inputs, output_node_names.data(),
num_outputs
);
// 3. rescale & exclude.
std::vector<types::Boxf> bbox_collection;
this->generate_bboxes(bbox_collection, output_tensors, score_threshold, img_height, img_width);
// 4. hard|blend nms with topk.
this->nms(bbox_collection, detected_boxes, iou_threshold, topk, nms_type);
}
void SSDMobileNetV1::generate_bboxes(std::vector<types::Boxf> &bbox_collection,
std::vector<Ort::Value> &output_tensors,
float score_threshold, float img_height,
float img_width)
{
Ort::Value &bboxes = output_tensors.at(0); // (1,?,4)
Ort::Value &labels = output_tensors.at(1); // (1,?)
Ort::Value &scores = output_tensors.at(2); // (1,?)
Ort::Value &nums = output_tensors.at(3); // (1,) float32
auto num_selected = static_cast<unsigned int>(nums.At<float>({0}));
bbox_collection.clear();
for (unsigned int i = 0; i < num_selected; ++i)
{
float conf = scores.At<float>({0, i});
if (conf < score_threshold) continue;
auto label = static_cast<unsigned int>(labels.At<float>({0, i}) - 1.);
types::Boxf box;
box.y1 = bboxes.At<float>({0, i, 0}) * (float) img_height;
box.x1 = bboxes.At<float>({0, i, 1}) * (float) img_width;
box.y2 = bboxes.At<float>({0, i, 2}) * (float) img_height;
box.x2 = bboxes.At<float>({0, i, 3}) * (float) img_width;
box.score = conf;
box.label = label;
box.label_text = class_names[label];
box.flag = true;
bbox_collection.push_back(box);
}
#if LITEORT_DEBUG
auto boxes_dims = bboxes.GetTypeInfo().GetTensorTypeAndShapeInfo().GetShape();
const unsigned int num_anchors = boxes_dims.at(1);
std::cout << "detected num_anchors: " << num_anchors << "\n";
std::cout << "generate_bboxes num: " << bbox_collection.size() << "\n";
#endif
}
void SSDMobileNetV1::nms(std::vector<types::Boxf> &input, std::vector<types::Boxf> &output,
float iou_threshold, unsigned int topk, unsigned int nms_type)
{
if (nms_type == NMS::BLEND) ortcv::utils::blending_nms(input, output, iou_threshold, topk);
else if (nms_type == NMS::OFFSET) ortcv::utils::offset_nms(input, output, iou_threshold, topk);
else ortcv::utils::hard_nms(input, output, iou_threshold, topk);
}
| 30.243781 | 97 | 0.645007 | Imudassir77 |
544d342b8f19e6d2d4bcc3802decf00f46005130 | 566 | hpp | C++ | cannon/utils/class_forward.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | cannon/utils/class_forward.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | 46 | 2021-01-12T23:03:52.000Z | 2021-10-01T17:29:01.000Z | cannon/utils/class_forward.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | #pragma once
#ifndef CANNON_UTILS_CLASS_FORWARD_H
#define CANNON_UTILS_CLASS_FORWARD_H
/*!
* \file cannon/utils/class_forward.hpp
* \brief File containing class forward macro.
*/
#include <memory>
/*!
* \def CANNON_CLASS_FORWARD
* \brief Macro that forward declares a class, <Class>Ptr, <Class>ConstPtr.
*/
#define CANNON_CLASS_FORWARD(C) \
class C; \
typedef std::shared_ptr<C> C##Ptr; \
typedef std::shared_ptr<const C> C##ConstPrt;
#endif /* ifndef CANNON_UTILS_CLASS_FORWARD_H */
| 25.727273 | 75 | 0.651943 | cannontwo |
544da4164e82942921678c6efe91b09e5dbe30fc | 3,877 | cpp | C++ | c++/src/algo/winmask/seq_masker_ostat_ascii.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/algo/winmask/seq_masker_ostat_ascii.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/algo/winmask/seq_masker_ostat_ascii.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: seq_masker_ostat_ascii.cpp 183994 2010-02-23 20:20:11Z morgulis $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksandr Morgulis
*
* File Description:
* Implementation of CSeqMaskerUStatAscii class.
*
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbistd.hpp>
#include <algo/winmask/seq_masker_ostat_ascii.hpp>
BEGIN_NCBI_SCOPE
//------------------------------------------------------------------------------
const char *
CSeqMaskerOstatAscii::CSeqMaskerOstatAsciiException::GetErrCodeString() const
{
switch( GetErrCode() )
{
case eBadOrder: return "bad unit order";
default: return CException::GetErrCodeString();
}
}
//------------------------------------------------------------------------------
CSeqMaskerOstatAscii::CSeqMaskerOstatAscii( const string & name )
: CSeqMaskerOstat(
name.empty() ?
static_cast<CNcbiOstream&>(NcbiCout) :
static_cast<CNcbiOstream&>(*new CNcbiOfstream( name.c_str() )),
name.empty() ? false : true )
{}
//------------------------------------------------------------------------------
CSeqMaskerOstatAscii::CSeqMaskerOstatAscii( CNcbiOstream & os )
: CSeqMaskerOstat( os, false )
{}
//------------------------------------------------------------------------------
CSeqMaskerOstatAscii::~CSeqMaskerOstatAscii()
{
}
//------------------------------------------------------------------------------
void CSeqMaskerOstatAscii::doSetUnitSize( Uint4 us )
{ out_stream << us << endl; }
//------------------------------------------------------------------------------
void CSeqMaskerOstatAscii::doSetUnitCount( Uint4 unit, Uint4 count )
{
static Uint4 punit = 0;
if( unit != 0 && unit <= punit )
{
CNcbiOstrstream ostr;
ostr << "current unit " << hex << unit << "; "
<< "previous unit " << hex << punit;
string s = CNcbiOstrstreamToString(ostr);
NCBI_THROW( CSeqMaskerOstatAsciiException, eBadOrder, s );
}
out_stream << hex << unit << " " << dec << count << "\n";
punit = unit;
}
//------------------------------------------------------------------------------
void CSeqMaskerOstatAscii::doSetComment( const string & msg )
{ out_stream << "#" << msg << "\n"; }
//------------------------------------------------------------------------------
void CSeqMaskerOstatAscii::doSetParam( const string & name, Uint4 value )
{ out_stream << ">" << name << " " << value << "\n"; }
//------------------------------------------------------------------------------
void CSeqMaskerOstatAscii::doSetBlank() { out_stream << "\n"; }
END_NCBI_SCOPE
| 36.92381 | 80 | 0.522569 | OpenHero |
544f44564b1242558cae6856ed2a55fe46627295 | 1,573 | cpp | C++ | 1]. DSA/2]. Algorithms/02]. Sorting Algorithms/C++/_1)_Merge Sort On 2 Linked Lists.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 6,969 | 2021-05-29T11:38:30.000Z | 2022-03-31T19:31:49.000Z | 1]. DSA/2]. Algorithms/02]. Sorting Algorithms/C++/_1)_Merge Sort On 2 Linked Lists.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 75 | 2021-06-15T07:59:43.000Z | 2022-02-22T14:21:52.000Z | 1]. DSA/2]. Algorithms/02]. Sorting Algorithms/C++/_1)_Merge Sort On 2 Linked Lists.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 1,524 | 2021-05-29T16:03:36.000Z | 2022-03-31T17:46:13.000Z | #include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
data=d;
next=NULL;
}
};
void insertatend(node*&head,int d){
if(head==NULL){
head= new node(d);
return;
}
node *n=new node(d);
node* temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=n;
}
node* insert_list(){
node*head=NULL;
int d;
cin>>d;
while(d!=-1){
insertatend(head,d);
cin>>d;
}
return head;
}
node* midpoint(node* head){
if(head==NULL||head->next==NULL)
return head;
node* slow=head;
node* fast=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
node* merge(node*a,node*b){
if(a==NULL)
return b;
if(b==NULL)
return a;
node* c=NULL;
if(a->data<b->data){
c=a;
c->next=merge(a->next,b);
}
else{
c=b;
c->next=merge(a,b->next);
}
return c;
}
node* mergesort(node*head){
if(head==NULL||head->next==NULL)
return head;
node* mid= midpoint(head);
node* a=head;
node*b=mid->next;
mid->next=NULL;
a=mergesort(a);
b=mergesort(b);
node* c=merge(a,b);
return c;
}
void printlist(node* head){
while(head!=NULL)
{
cout<<head->data<<"->";
head=head->next;
}
}
int main(){
node* head=NULL;
head=insert_list();
printlist(head);
cout<<endl;
node* c=mergesort(head);
printlist(c);
}
| 18.08046 | 40 | 0.516847 | MLinesCode |
544f9984d5a43d4550d1c6589d487b50b95e9c90 | 11,503 | cpp | C++ | src/DSArray/src/DSArray.cpp | haraisao/OpenHRI_Audio | 473ec87855de35afef9eccb411bfe6ecf069be37 | [
"MIT"
] | 1 | 2020-03-30T03:00:08.000Z | 2020-03-30T03:00:08.000Z | src/DSArray/src/DSArray.cpp | haraisao/OpenHRI_Audio | 473ec87855de35afef9eccb411bfe6ecf069be37 | [
"MIT"
] | null | null | null | src/DSArray/src/DSArray.cpp | haraisao/OpenHRI_Audio | 473ec87855de35afef9eccb411bfe6ecf069be37 | [
"MIT"
] | 1 | 2020-03-30T03:02:09.000Z | 2020-03-30T03:02:09.000Z | // -*- C++ -*-
/*!
* @file DSArray.cpp
* @author Isao Hara(isao-hara@aist.go.jp)
*
* Copyright (C)
* All rights reserved.
*
*/
#include "DSArray.h"
// use speex's internal fft functions
extern "C" {
void *spx_fft_init(int size);
void spx_fft_destroy(void *table);
void spx_fft_float(void *table, float *in, float *out);
void spx_ifft_float(void *table, float *in, float *out);
}
// Module specification
// <rtc-template block="module_spec">
const char* rtcomponent_spec[] =
{
"implementation_id", "DSArray",
"type_name", "DSArray",
"description", "DS Array",
"version", "2.0.0",
"vendor", "AIST",
"category", "OpenHRI",
"component_type", "STATIC",
"activity_type", "PERIODIC",
"kind", "DataFlowComponent",
"max_instance", "1",
"language", "C++",
"lang_type", "compile",
"conf.default.SampleRate", "16000",
"conf.__constraints__.SampleRate", "x >= 1",
"conf.__type__.SampleRate", "int",
"conf.__description__.SampleRate", "入力音声データのサンプリング周波数(Hz)",
"conf.default.ChannelNumbers", "4",
"conf.__constraints__.ChannelNumbers", "x >= 2",
"conf.__type__.ChannelNumbers", "int",
""
};
// </rtc-template>
/*!
* @brief constructor
* @param manager Maneger Object
*/
DSArray::DSArray(RTC::Manager* manager)
// <rtc-template block="initializer">
: RTC::DataFlowComponentBase(manager),
m_micIn("mic", m_mic),
m_resultOut("result", m_result)
// </rtc-template>
{
}
/*!
* @brief destructor
*/
DSArray::~DSArray()
{
}
int DSArray::ccf(short *base, short *data)
{
int i;
int cnt = 0;
float max = 0;
float *out0 = new float[WINLEN];
float *out1 = new float[WINLEN];
float *fft0 = new float[WINLEN*2];
float *fft1 = new float[WINLEN*2];
for ( i = 0; i < WINLEN; i++ ) {
out0[i] = (float)base[i];
out1[i] = (float)data[i];
}
ApplyWindowFloat(WINLEN, window, out0);
ApplyWindowFloat(WINLEN, window, out1);
spx_fft_float(fft, out0, fft0);
spx_fft_float(fft, out1, fft1);
for ( i = 0; i < WINLEN*2; i++ ) {
fft0[i] = fft0[i] * fft1[i];
}
spx_ifft_float(fft, fft0, out0);
for ( i = 0; i < SEARCHMAX; i++ ) {
if ( max < out0[i] ) {
max = out0[i];
cnt = i;
}
}
delete[] out0;
delete[] out1;
delete[] fft0;
delete[] fft1;
return cnt;
}
int DSArray::CrossCorrelation(short *base, short *data)
{
int i,j;
int cnt = SEARCHMAX;
long max = WINLEN*2*700;
long sum[SEARCHMAX];
for ( i = 0; i < SEARCHMAX; i++ ) {
sum[i] = 0;
for ( j = 0; j+SEARCHMAX < WINLEN; j++ ) {
sum[i] += abs(base[j] + data[i+j]);
}
if ( max < sum[i] ) {
max = sum[i];
cnt = i;
}
}
// std::cout << "max = " << max << std::endl;
return cnt;
}
RTC::ReturnCode_t DSArray::onInitialize()
{
RTC_DEBUG(("onInitialize start"));
RTC_INFO(("DSArray : DS Array"));
// Registration: InPort/OutPort/Service
// <rtc-template block="registration">
// Set DataPort buffers
addInPort("mic", m_micIn);
m_micIn.addConnectorDataListener(ON_BUFFER_WRITE,
new MicDataListener("ON_BUFFER_WRITE", this), false);
addOutPort("result", m_resultOut);
// Set service provider to Ports
// Set service consumers to Ports
// Set CORBA Service Ports
// </rtc-template>
bindParameter("SampleRate", m_SampleRate, "16000");
bindParameter("ChannelNumbers", m_ChannelNumbers, "4");
RTC_DEBUG(("onInitialize finish"));
return RTC::RTC_OK;
}
RTC::ReturnCode_t DSArray::onFinalize()
{
RTC_DEBUG(("onFinalize start"));
is_active = false;
BufferClr();
RTC_DEBUG(("onFinalize finish"));
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t DSArray::onStartup(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onShutdown(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
RTC::ReturnCode_t DSArray::onActivated(RTC::UniqueId ec_id)
{
RTC_DEBUG(("onActivated start"));
is_active = true;
m_horizon = true;
int i = 0;
BufferClr();
m_micinfo = new mic_info[m_ChannelNumbers];
char fname[] = "micset.csv";
std::ifstream stream(fname);
if ( stream.is_open() ) {
float wk_x,wk_y,wk_z;
double dwk;
char str[256];
while ( stream.getline( str, 256 ) ) {
if ( str[0] == '#' ) continue;
if ( sscanf( str, "%f,%f,%f", &wk_x, &wk_y, &wk_z ) == 3 ) {
m_micinfo[i].x = (double)wk_x;
m_micinfo[i].y = (double)wk_y;
m_micinfo[i].z = (double)wk_z;
if (( wk_y != 0.0 ) || ( wk_z != 0.0 )) {
m_horizon = false;
}
dwk = sqrt( wk_x * wk_x + wk_y * wk_y );
if ( m_micinfo[i].x < 0 ) {
if ( m_micinfo[i].y < 0) {
m_micinfo[i].xy_rad = acos( (double)wk_y/dwk ) * -1;
} else {
m_micinfo[i].xy_rad = asin( (double)wk_x/dwk );
}
} else {
m_micinfo[i].xy_rad = acos( (double)wk_y/dwk );
}
dwk = sqrt( wk_y * wk_y + wk_z * wk_z );
if ( m_micinfo[i].y < 0 ) {
if ( m_micinfo[i].z < 0 ) {
m_micinfo[i].yz_rad = acos( (double)wk_z/dwk ) * -1;
} else {
m_micinfo[i].yz_rad = asin( (double)wk_y/dwk );
}
} else {
m_micinfo[i].yz_rad = acos( (double)wk_z/dwk );
}
}
RTC_INFO(("mic %i angle = %f [deg]", i, m_micinfo[i].xy_rad * 180 / M_PI));
std::cout << "mic " << i << " : (" << m_micinfo[i].x << "," << m_micinfo[i].y << "," << m_micinfo[i].z << ") angle " << m_micinfo[i].xy_rad * 180 / M_PI << "[deg]" << std::endl;
i++;
if ( i >= m_ChannelNumbers ) break;
}
stream.close();
}
if ( m_horizon == true ) {
for ( i = 0; i < m_ChannelNumbers; i++ ) {
m_micinfo[i].xy_rad = 0;
m_micinfo[i].yz_rad = 0;
}
}
window = CreateWindowFloat(WINLEN, Hamming);
// windowd = CreateWindowDouble(WINLEN, Hamming);
fft = spx_fft_init(WINLEN);
RTC_DEBUG(("onActivated finish"));
return RTC::RTC_OK;
}
void DSArray::BufferClr(void)
{
RTC_DEBUG(("BufferClr start"));
m_mutex.lock();
RTC_DEBUG(("BufferClr:mutex lock"));
if ( fft != NULL ) {
spx_fft_destroy(fft);
fft = NULL;
}
if ( !m_data.empty() ) {
m_data.clear(); //!< queue buffer clear
}
m_mutex.unlock();
RTC_DEBUG(("BufferClr:mutex unlock"));
RTC_DEBUG(("BufferClr finish"));
}
void DSArray::RcvBuffer(TimedOctetSeq data)
{
RTC_DEBUG(("RcvBuffer start"));
if ( is_active == true ) {
m_mutex.lock();
RTC_DEBUG(("RcvBuffer:mutex lock"));
int length = data.data.length();
short wk;
unsigned char wk0, wk1;
for (int i = 0; i < length/2; i++) {
wk0 = (unsigned char)data.data[i*2];
wk1 = (unsigned char)data.data[i*2+1];
wk = (short)(wk1 << 8) + (short)wk0;
m_data.push_back(wk);
}
m_mutex.unlock();
RTC_DEBUG(("RcvBuffer:mutex unlock"));
}
RTC_DEBUG(("RcvBuffer finish"));
return;
}
RTC::ReturnCode_t DSArray::onDeactivated(RTC::UniqueId ec_id)
{
RTC_DEBUG(("onDeactivated start"));
try {
is_active = false;
BufferClr();
delete[] m_micinfo;
} catch (...) {
RTC_WARN(("%s", "onDeactivated error"));
}
RTC_DEBUG(("onDeactivated finish"));
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t DSArray::onAborting(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onError(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onReset(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
RTC::ReturnCode_t DSArray::onExecute(RTC::UniqueId ec_id)
{
RTC_DEBUG(("onExecute start"));
if ( (int)m_data.size() > ( m_ChannelNumbers * WINLEN ) ) {
// if ( ( !m_data.empty() ) && ( m_data.size() > ( m_ChannelNumbers * WINLEN ) ) ) {
m_mutex.lock();
double dwk;
double angle,angle0,angle1,deg;
int cnt = 0;
int i,j = 0;
int dt,dtmin,micnum;
short **buffer = new short*[m_ChannelNumbers];
for ( i = 0; i < m_ChannelNumbers; i++ ) {
buffer[i] = new short[WINLEN];
}
for ( i = 0; i < WINLEN; i++ ) {
for ( j = 0; j < m_ChannelNumbers; j++ ) {
buffer[j][i] = m_data.front();
m_data.pop_front();
}
}
m_mutex.unlock();
deg = 0;
cnt = 0;
dtmin = SEARCHMAX;
for ( i = 0; i < m_ChannelNumbers; i++ ) {
angle0 = m_micinfo[i].xy_rad;
// for ( j = i + 1; j < m_ChannelNumbers; j++ ) {
for ( j = 0; j < m_ChannelNumbers; j++ ) {
if ( i == j ) continue;
angle1 = m_micinfo[j].xy_rad;
if ( fabs( angle0 ) > fabs( angle1 ) ) {
angle = angle0;
} else {
angle = angle1;
}
/* dt = ccf(buffer[i], buffer[j]);*/
dt = CrossCorrelation(buffer[i], buffer[j]);
// if ( ( dt == 0 ) || ( dt == SEARCHMAX ) ) continue;
if ( dt == SEARCHMAX ) continue;
if ( dtmin > dt ) {
dtmin = dt;
micnum = j;
}
// std::cout << "mic = " << i << " - " << j << " dt = " << dt << std::endl;
/* 理論値:ch0=47,ch1=13,ch2=0,ch3=13,ch4=47 */
dwk = sqrt(pow((m_micinfo[i].x - m_micinfo[j].x), 2.0) + pow((m_micinfo[i].y - m_micinfo[j].y), 2.0));
dwk = dt * SONIC / dwk / m_SampleRate;
if ( (dwk > 1 ) || ( dwk < -1 ) ) continue;
angle = asin(dwk);
if ( ( angle0 == 0 ) && ( angle1 == 0 ) ) {
if ( m_micinfo[i].x < m_micinfo[j].x ) angle *= -1;
} else {
if ( ( abs(angle0) > M_PI/2 ) || ( abs(angle1) > M_PI/2 ) ) {
if ( ( angle0 > 0 ) && ( angle1 < 0 ) ) {
angle1 = angle1 + 2*M_PI;
} else if ( ( angle0 < 0 ) && ( angle1 > 0 ) ) {
angle1 = angle1 - 2*M_PI;
}
}
if ( angle0 < angle1 ) {
angle = angle0 + (angle1 - angle0)/2 - angle;
} else {
angle = angle1 + (angle0 - angle1)/2 + angle;
}
}
// std::cout << "mic = " << i << " - " << j << ": dt = " << dt << ", angle = " << angle * 180 / M_PI << "[°]" << std::endl;
deg += angle;
cnt++;
}
}
// if ( ( micnum < m_ChannelNumbers - 1 ) && ( m_horizon == true ) ) {
// deg *= -1;
// }
// if ( cnt > 2 ) {
if ( cnt > 0 ) {
deg = deg / cnt;
deg = deg * 180 / M_PI;
std::cout << " angle = " << deg << "[°]" << std::endl;
m_result.data = deg;
setTimestamp( m_result );
m_resultOut.write();
}
for ( i = 0; i < m_ChannelNumbers; i++ ) {
delete[] buffer[i];
}
delete[] buffer;
}
RTC_DEBUG(("onExecute finish"));
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t DSArray::onStateUpdate(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onRateChanged(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onAction(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t DSArray::onModeChanged(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
extern "C"
{
void DSArrayInit(RTC::Manager* manager)
{
int i, j;
for (i = 0; strlen(rtcomponent_spec[i]) != 0; i++);
char** spec_intl = new char*[i + 1];
for (j = 0; j < i; j++) {
spec_intl[j] = (char *)rtcomponent_spec[j];
}
spec_intl[i] = (char *)"";
coil::Properties profile((const char **)spec_intl);
manager->registerFactory(profile,
RTC::Create<DSArray>,
RTC::Delete<DSArray>);
}
};
| 24.115304 | 184 | 0.545249 | haraisao |
54516c9b4b8be7b382d990a59303084266303a4e | 29,680 | cpp | C++ | parser/parser.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | parser/parser.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | 2 | 2019-05-07T22:49:31.000Z | 2021-08-20T20:03:53.000Z | parser/parser.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | #include <string.h>
#include <fstream>
#include "parser.h"
#include "DataAdvice-pimpl.h"
#include "DataAdvice-pskel.h"
#include "model/dataadvice.h"
#include "runtypeparser.h"
#include <QApplication>
#include <QFileInfo>
#include <QDebug>
#include "QDjango.h"
#include "saveerror.h"
Parser::Parser(QString filePath, QObject *parent):
QObject(parent)
, filePath(filePath)
{
m_cancel = std::make_unique<bool>();
}
Parser::~Parser()
{
}
std::string Parser::findXsdPath()
{
QString xsdName = "DataAdvice.xsd";
auto xsdPath = QApplication::applicationDirPath() + "/" + xsdName;
QFileInfo check_file(xsdPath);
if (check_file.exists() && check_file.isReadable())
{
return (QString("file:///") + xsdPath.replace(" ","%20")).toStdString();
}
else
{
QDir dir = QDir(filePath);
dir.cdUp();
xsdPath = dir.canonicalPath() + "/" + xsdName;
check_file = QFileInfo(xsdPath);
if (check_file.exists() && check_file.isReadable())
return (QString("file:///") + xsdPath.replace(" ", "%20")).toStdString();
else
throw QString("DataAdvice.xsd was not found.");
}
}
void Parser::import()
{
*m_cancel = false;
if (!QDjango::createTables())
{
this->message(QString("Did not create tables (this is okay if the tables already exist)"));
}
try
{
if (!QDjango::database().transaction())
throw SaveError("Failed to create transaction.");
message("Populating lookup tables...");
model::PropertyClassValueType::populate();
model::minortaxing::JurisdictionType::populate();
message("Done.");
message(QString("Importing records from ") + filePath + "...");
std::unique_ptr<model::DataAdvice> dataAdvice;
try
{
dataAdvice = readFile(filePath.toStdString(), findXsdPath(), false);
}
catch (SaveError &err)
{
QDjango::database().rollback();
emit message(err.text());
emit finished(false);
return;
}
catch (QString& err)
{
QDjango::database().rollback();
emit message(err);
emit finished(false);
return;
}
catch ( ... )
{
QDjango::database().rollback();
qDebug() << "Stopped parsing the file.";
emit finished(false);
return;
}
writeMetadata(dataAdvice);
emit folioSaved(-1); // set progressbar to indeterminate
if (!QDjango::database().commit())
throw SaveError("Failed to commit transaction.");
message("Successfully imported the data file.");
emit finished(true);
}
catch (SaveError &err)
{
this->message(err.text());
emit finished(false);
}
}
void Parser::writeMetadata(const std::unique_ptr<model::DataAdvice> &summary)
{
model::ImportMeta meta;
meta.setImportDate(QDate::currentDate());
meta.setRunDate(summary->runDate());
meta.setRunType(summary->runType());
if (!meta.save())
throw SaveError(meta.lastError().text());
}
void Parser::cancel()
{
*m_cancel = true;
}
std::unique_ptr<model::DataAdvice> Parser::getFileInfo()
{
auto xsdPath = findXsdPath();
auto advice = readFile(filePath.toStdString(), findXsdPath(), true);
return advice;
}
std::unique_ptr<model::DataAdvice> Parser::readFile(const std::string& path, const std::string& xsdPath, bool forSummary)
{
// use a stream so we can calculate progress based on
// position in the file stream
std::ifstream file;
long long size;
file.open(path, std::ios::in | std::ios::ate); // open input stream at end of file
if (file.is_open())
{
size = file.tellg();
file.seekg(0, file.beg);
qDebug() << "size of size_t: " << sizeof(size_t);
}
else
{
char *errbuf = new char[32];
strerror_s(errbuf, 32, errno);
throw(QString("Failed to open file.") + QString(errbuf));
}
std::unique_ptr<::dataadvice::DataAdvice_pskel> DataAdvice_p;
//auto parser = registerParser(forSummary);
::xml_schema::integerImpl integer_p;
::dataadvice::RunTypeImpl RunType_p;
::xml_schema::dateImpl date_p;
::dataadvice::AssessmentAreaCollectionImpl AssessmentAreaCollection_p;
::dataadvice::AssessmentAreaImpl AssessmentArea_p;
::dataadvice::AssessmentAreaCodeImpl AssessmentAreaCode_p;
::dataadvice::String255Impl String255_p;
::dataadvice::JurisdictionCollectionImpl JurisdictionCollection_p;
::dataadvice::JurisdictionImpl Jurisdiction_p;
::dataadvice::JurisdictionCodeImpl JurisdictionCode_p;
::dataadvice::FolioRecordCollectionImpl FolioRecordCollection_p;
::dataadvice::FolioRecordImpl FolioRecord_p(file, size);
::dataadvice::FolioRollNumberImpl FolioRollNumber_p;
::dataadvice::ActionCodeImpl ActionCode_p;
::dataadvice::String32Impl String32_p;
::dataadvice::FolioLookupCodeItemImpl FolioLookupCodeItem_p;
::dataadvice::LookupCodeImpl LookupCode_p;
::dataadvice::FolioString255ItemImpl FolioString255Item_p;
::dataadvice::FolioActionImpl FolioAction_p;
::dataadvice::FolioAddImpl FolioAdd_p;
::dataadvice::FolioRenumberImpl FolioRenumber_p;
::dataadvice::FolioDeleteImpl FolioDelete_p;
::dataadvice::FolioAddressCollectionImpl FolioAddressCollection_p;
::dataadvice::FolioAddressImpl FolioAddress_p;
::dataadvice::FolioBooleanItemImpl FolioBooleanItem_p;
::xml_schema::booleanImpl boolean_p;
::dataadvice::UniqueIDImpl UniqueID_p;
::dataadvice::OwnershipGroupCollectionImpl OwnershipGroupCollection_p;
::dataadvice::OwnershipGroupImpl OwnershipGroup_p;
::dataadvice::FolioUniqueIDItemImpl FolioUniqueIDItem_p;
::dataadvice::FolioDateItemImpl FolioDateItem_p;
::dataadvice::OwnerCollectionImpl OwnerCollection_p;
::dataadvice::OwnerImpl Owner_p;
::dataadvice::FolioString1ItemImpl FolioString1Item_p;
::dataadvice::String1Impl String1_p;
::dataadvice::FormattedMailingAddressImpl FormattedMailingAddress_p;
::dataadvice::FormattedMailingAddressLineImpl FormattedMailingAddressLine_p;
::dataadvice::String40Impl String40_p;
::dataadvice::MailingAddressImpl MailingAddress_p;
::dataadvice::LegalDescriptionCollectionImpl LegalDescriptionCollection_p;
::dataadvice::LegalDescriptionImpl LegalDescription_p;
::dataadvice::FolioString1024ItemImpl FolioString1024Item_p;
::dataadvice::String1024Impl String1024_p;
::dataadvice::FolioDescriptionImpl FolioDescription_p;
::dataadvice::NeighbourhoodImpl Neighbourhood_p;
::dataadvice::LandMeasurementImpl LandMeasurement_p;
::dataadvice::SpecialDistrictImpl SpecialDistrict_p;
::dataadvice::ManualClassImpl ManualClass_p;
::dataadvice::FolioDecimalItemImpl FolioDecimalItem_p;
::xml_schema::decimalImpl decimal_p;
::dataadvice::SaleCollectionImpl SaleCollection_p;
::dataadvice::SaleImpl Sale_p;
::dataadvice::PropertyValuesImpl PropertyValues_p;
::dataadvice::PropertyClassValuesCollectionImpl PropertyClassValuesCollection_p;
::dataadvice::PropertyClassValuesCollectionImpl PropertyClassValuesSummaryCollection_p;
::dataadvice::PropertyClassValuesImpl PropertyClassValues_p;
::dataadvice::PropertyClassCodeImpl PropertyClassCode_p;
::dataadvice::PropertySubClassCodeImpl PropertySubClassCode_p;
::dataadvice::ValuationImpl Valuation_p;
::dataadvice::ValuationCollectionImpl ValuationCollection_p;
::dataadvice::ValuesByETCImpl ValuesByETC_p;
::dataadvice::FolioAmendmentCollectionImpl FolioAmendmentCollection_p;
::dataadvice::FolioAmendmentImpl FolioAmendment_p;
::dataadvice::MinorTaxingImpl MinorTaxing_p;
::dataadvice::MinorTaxingJurisdictionCollectionImpl MinorTaxingJurisdictionCollection_p;
::dataadvice::MinorTaxingJurisdictionImpl MinorTaxingJurisdiction_p;
::dataadvice::FarmCollectionImpl FarmCollection_p;
::dataadvice::FarmImpl Farm_p;
::dataadvice::ManufacturedHomeCollectionImpl ManufacturedHomeCollection_p;
::dataadvice::ManufacturedHomeImpl ManufacturedHome_p;
::dataadvice::ManagedForestCollectionImpl ManagedForestCollection_p;
::dataadvice::ManagedForestImpl ManagedForest_p;
::dataadvice::OilAndGasCollectionImpl OilAndGasCollection_p;
::dataadvice::OilAndGasImpl OilAndGas_p;
::dataadvice::LandCharacteristicCollectionImpl LandCharacteristicCollection_p;
::dataadvice::LandCharacteristicImpl LandCharacteristic_p;
::dataadvice::DeliverySummaryImpl DeliverySummary_p;
::dataadvice::FolioGroupValuesImpl FolioGroupValues_p;
::dataadvice::AmendmentReasonCountCollectionImpl AmendmentReasonCountCollection_p;
::dataadvice::AmendmentReasonCountImpl AmendmentReasonCount_p;
::dataadvice::DeleteReasonCountCollectionImpl DeleteReasonCountCollection_p;
::dataadvice::DeleteReasonCountImpl DeleteReasonCount_p;
::dataadvice::VersionImpl Version_p;
// set the cancel flag
FolioRecord_p.setCancelFlag(*m_cancel);
// Connect the parsers together.
//
if (forSummary)
{
DataAdvice_p = std::make_unique<dataadvice::RunTypeParser>();
DataAdvice_p->RunType_parser(RunType_p);
DataAdvice_p->EndDate_parser(date_p);
DataAdvice_p->Version_parser(Version_p);
DataAdvice_p->StartDate_parser(date_p);
DataAdvice_p->RunDate_parser(date_p);
//DataAdvice_p->ReportSummary_parser(DeliverySummary_p);
}
else
{
DataAdvice_p = std::make_unique<::dataadvice::DataAdviceImpl>();
DataAdvice_p->parsers (integer_p,
integer_p,
RunType_p,
date_p,
date_p,
AssessmentAreaCollection_p,
DeliverySummary_p,
Version_p,
UniqueID_p,
UniqueID_p,
date_p);
AssessmentAreaCollection_p.parsers (AssessmentArea_p);
AssessmentArea_p.parsers (AssessmentAreaCode_p,
String255_p,
JurisdictionCollection_p,
DeliverySummary_p);
JurisdictionCollection_p.parsers (Jurisdiction_p);
Jurisdiction_p.parsers (JurisdictionCode_p,
String255_p,
FolioRecordCollection_p,
DeliverySummary_p);
FolioRecordCollection_p.parsers (FolioRecord_p);
FolioRecord_p.parsers (FolioRollNumber_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioAction_p,
FolioAddressCollection_p,
OwnershipGroupCollection_p,
LegalDescriptionCollection_p,
FolioDescription_p,
SaleCollection_p,
PropertyValues_p,
FolioAmendmentCollection_p,
MinorTaxing_p,
FarmCollection_p,
ManufacturedHomeCollection_p,
ManagedForestCollection_p,
OilAndGasCollection_p,
LandCharacteristicCollection_p,
UniqueID_p);
FolioRollNumber_p.parsers (ActionCode_p,
String32_p);
FolioLookupCodeItem_p.parsers (ActionCode_p,
LookupCode_p);
FolioString255Item_p.parsers (ActionCode_p,
String255_p);
FolioAction_p.parsers (FolioAdd_p,
FolioDelete_p);
FolioAdd_p.parsers (FolioRenumber_p);
FolioRenumber_p.parsers (AssessmentAreaCode_p,
String255_p,
JurisdictionCode_p,
String255_p,
String32_p);
FolioDelete_p.parsers (FolioRenumber_p,
LookupCode_p,
String255_p);
FolioAddressCollection_p.parsers (ActionCode_p,
FolioAddress_p);
FolioAddress_p.parsers (ActionCode_p,
FolioBooleanItem_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
UniqueID_p);
FolioBooleanItem_p.parsers (ActionCode_p,
boolean_p);
OwnershipGroupCollection_p.parsers (ActionCode_p,
OwnershipGroup_p);
OwnershipGroup_p.parsers (ActionCode_p,
FolioUniqueIDItem_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioDateItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
OwnerCollection_p,
FormattedMailingAddress_p,
MailingAddress_p);
FolioUniqueIDItem_p.parsers (ActionCode_p,
UniqueID_p);
FolioDateItem_p.parsers (ActionCode_p,
date_p);
OwnerCollection_p.parsers (ActionCode_p,
Owner_p);
Owner_p.parsers (ActionCode_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString1Item_p,
FolioString255Item_p,
FolioUniqueIDItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
UniqueID_p);
FolioString1Item_p.parsers (ActionCode_p,
String1_p);
FormattedMailingAddress_p.parsers (ActionCode_p,
FormattedMailingAddressLine_p,
FormattedMailingAddressLine_p,
FormattedMailingAddressLine_p,
FormattedMailingAddressLine_p,
FormattedMailingAddressLine_p,
FormattedMailingAddressLine_p,
UniqueID_p);
FormattedMailingAddressLine_p.parsers (ActionCode_p,
String40_p);
MailingAddress_p.parsers (ActionCode_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
UniqueID_p);
LegalDescriptionCollection_p.parsers (ActionCode_p,
LegalDescription_p);
LegalDescription_p.parsers (ActionCode_p,
FolioString1024Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString1024Item_p,
UniqueID_p);
FolioString1024Item_p.parsers (ActionCode_p,
String1024_p);
FolioDescription_p.parsers (ActionCode_p,
Neighbourhood_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioBooleanItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioString255Item_p,
LandMeasurement_p,
SpecialDistrict_p,
SpecialDistrict_p,
SpecialDistrict_p,
ManualClass_p);
Neighbourhood_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString255Item_p);
LandMeasurement_p.parsers (ActionCode_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p);
SpecialDistrict_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString255Item_p);
ManualClass_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioDecimalItem_p);
FolioDecimalItem_p.parsers (ActionCode_p,
decimal_p);
SaleCollection_p.parsers (ActionCode_p,
Sale_p);
Sale_p.parsers (ActionCode_p,
FolioString255Item_p,
FolioDateItem_p,
FolioDecimalItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioDateItem_p,
FolioDecimalItem_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
UniqueID_p);
PropertyValues_p.parsers (PropertyClassValuesCollection_p,
PropertyClassValuesCollection_p,
PropertyClassValuesCollection_p,
ValuationCollection_p);
PropertyClassValuesCollection_p.parsers (PropertyClassValues_p);
PropertyClassValues_p.parsers (PropertyClassCode_p,
String255_p,
PropertySubClassCode_p,
String255_p,
Valuation_p,
Valuation_p,
Valuation_p);
Valuation_p.parsers (decimal_p,
decimal_p);
ValuationCollection_p.parsers (ValuesByETC_p);
ValuesByETC_p.parsers (LookupCode_p,
String255_p,
PropertyClassCode_p,
String255_p,
decimal_p,
decimal_p);
FolioAmendmentCollection_p.parsers (ActionCode_p,
FolioAmendment_p);
FolioAmendment_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioLookupCodeItem_p,
FolioString255Item_p,
FolioDateItem_p,
FolioString1Item_p,
UniqueID_p);
MinorTaxing_p.parsers (ActionCode_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p,
MinorTaxingJurisdictionCollection_p);
MinorTaxingJurisdictionCollection_p.parsers (ActionCode_p,
MinorTaxingJurisdiction_p);
MinorTaxingJurisdiction_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString1Item_p,
FolioString255Item_p,
UniqueID_p);
FarmCollection_p.parsers (ActionCode_p,
Farm_p);
Farm_p.parsers (ActionCode_p,
FolioString255Item_p,
UniqueID_p);
ManufacturedHomeCollection_p.parsers (ActionCode_p,
ManufacturedHome_p);
ManufacturedHome_p.parsers (ActionCode_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
FolioString255Item_p,
UniqueID_p);
ManagedForestCollection_p.parsers (ActionCode_p,
ManagedForest_p);
ManagedForest_p.parsers (ActionCode_p,
FolioString255Item_p,
UniqueID_p);
OilAndGasCollection_p.parsers (ActionCode_p,
OilAndGas_p);
OilAndGas_p.parsers (ActionCode_p,
FolioString255Item_p,
UniqueID_p);
LandCharacteristicCollection_p.parsers (ActionCode_p,
LandCharacteristic_p);
LandCharacteristic_p.parsers (ActionCode_p,
FolioLookupCodeItem_p,
FolioString255Item_p);
DeliverySummary_p.parsers (integer_p,
integer_p,
integer_p,
FolioGroupValues_p,
FolioGroupValues_p,
FolioGroupValues_p,
PropertyClassValuesSummaryCollection_p,
PropertyClassValuesSummaryCollection_p,
PropertyClassValuesSummaryCollection_p,
AmendmentReasonCountCollection_p,
DeleteReasonCountCollection_p);
FolioGroupValues_p.parsers (decimal_p,
decimal_p);
AmendmentReasonCountCollection_p.parsers (AmendmentReasonCount_p);
AmendmentReasonCount_p.parsers (LookupCode_p,
String255_p,
integer_p);
DeleteReasonCountCollection_p.parsers (DeleteReasonCount_p);
DeleteReasonCount_p.parsers (LookupCode_p,
String255_p,
integer_p);
}
// connect signals
connect(&FolioRecord_p, &dataadvice::FolioRecordImpl::folioSaved, this, &Parser::folioSaved);
connect(&FolioRecord_p, &dataadvice::FolioRecordImpl::message, this, &Parser::message);
connect(dynamic_cast<dataadvice::DataAdviceImpl *>(DataAdvice_p.get()), &dataadvice::DataAdviceImpl::message, this, &Parser::message);
// configure XSD location
::xml_schema::document doc_p (*DataAdvice_p,
"http://data.bcassessment.ca/DataAdvice/Formats/DAX/DataAdvice.xsd",
"DataAdvice");
::xml_schema::properties props;
props.schema_location(
"http://data.bcassessment.ca/DataAdvice/Formats/DAX/DataAdvice.xsd",
xsdPath);
try {
DataAdvice_p->pre();
doc_p.parse(file, 0, props);
file.close();
return std::unique_ptr<model::DataAdvice>(DataAdvice_p->post_DataAdvice());
}
catch (const ::xml_schema::parsing& e)
{
file.close();
qDebug() << e.what();
for (auto &&d: e.diagnostics())
{
qDebug() << "Parse error on line " << d.line() << ", column " << d.column();
qDebug() << QString::fromStdString(d.message());
emit message(QString("Parse error on line ")
+ QString::number(d.line())
+ ", column "
+ QString::number(d.column()));
emit message(QString::fromStdString(d.message()));
}
throw QString(*e.what());
}
catch (const ::xml_schema::exception& e)
{
file.close();
qDebug() << e.what();
message(QString("Parse error: ") + QString(*e.what()));
throw e.what();
}
catch (const std::ios_base::failure&)
{
file.close();
qDebug() << "IO failue.";
emit message(QString("IO Failure"));
throw QString("IO Failure");
}
catch (dataadvice::StopParsing&)
{
file.close();
qDebug() << "Stopped parsing";
//this is terrible, and should be refactored
if (forSummary)
return DataAdvice_p->post_DataAdvice();
else
throw;
}
}
| 41.980198 | 138 | 0.519474 | rdffg |
5451aa66c0eca9573d252c8fd44441d31c5295f9 | 1,351 | cpp | C++ | QtChartsDemo/PieChart/widget.cpp | mahuifa/QMDemo | 430844c0167c7374550c6133b38c5e8485f506d6 | [
"Apache-2.0"
] | null | null | null | QtChartsDemo/PieChart/widget.cpp | mahuifa/QMDemo | 430844c0167c7374550c6133b38c5e8485f506d6 | [
"Apache-2.0"
] | null | null | null | QtChartsDemo/PieChart/widget.cpp | mahuifa/QMDemo | 430844c0167c7374550c6133b38c5e8485f506d6 | [
"Apache-2.0"
] | null | null | null | #include "widget.h"
#include <QPieSeries>
QT_CHARTS_USE_NAMESPACE // 引入命名空间,必须放在ui_widget.h前
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->setWindowTitle("QtCharts绘图-饼图Demo");
initChart();
}
Widget::~Widget()
{
delete ui;
}
/**
* @brief 初始化绘制饼图,饼图和圆环图的绘制方式基本一样,只是
* 不通过setHoleSize设置大于孔径,默认为0,就是没有孔径
*/
void Widget::initChart()
{
QPieSeries* series = new QPieSeries(); // 创建一个饼图对象(设置孔径就是圆环)
series->append("星期一", 1); // 添加饼图切片
series->append("星期二", 2);
series->append("星期三", 3);
series->append("星期四", 4);
series->append("星期五", 5);
QPieSlice* slice = series->slices().at(1); // 获取饼图中某一个切片(在绘制圆环图Demo中是通过appent函数获取,这里换一种方式)
slice->setExploded(); // 将切片分离饼图
slice->setLabelVisible(); // 显示当前切片的标签
slice->setPen(QPen(Qt::darkGreen, 2)); // 设置画笔颜色和粗细
slice->setBrush(Qt::green); // 设置切片背景色
QChart* chart = ui->chartView->chart(); // 获取QChartView中默认的QChart
chart->addSeries(series); // 将创建好的饼图对象添加进QChart
chart->setTitle("饼图标题"); // 设置图表标题
ui->chartView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿
}
| 30.022222 | 100 | 0.571429 | mahuifa |
54523956a8077c86a3c7c26a0225ee22dcaf5ffb | 551 | cpp | C++ | EquilibriumPointInArray/main.cpp | Kapil706/GeeksForGeeks.Cpp- | 3251fe2caf29e485656626d758058bd968e50ae1 | [
"MIT"
] | 1 | 2019-07-31T16:47:51.000Z | 2019-07-31T16:47:51.000Z | EquilibriumPointInArray/main.cpp | Kapil706/GeeksForGeeks.Cpp- | 3251fe2caf29e485656626d758058bd968e50ae1 | [
"MIT"
] | null | null | null | EquilibriumPointInArray/main.cpp | Kapil706/GeeksForGeeks.Cpp- | 3251fe2caf29e485656626d758058bd968e50ae1 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int EqPoint(int arr[],int n){
int sum=0;
for(int i=0;i<n;i++){
sum += arr[i];
}
int l_sum=0;
for(int i=0;i<n;i++){
if(l_sum==sum-arr[i]){
return i+1;
}
l_sum += arr[i];
sum -= arr[i];
}
return -1;
}
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){cin>>arr[i];}
cout<<EqPoint(arr,n);
}
return 0;
} | 8.746032 | 42 | 0.395644 | Kapil706 |
5454c944abe007f82b0e3871a02707b18b713dd0 | 457 | hpp | C++ | core/world/filter/Filter.hpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | 2 | 2022-02-21T08:23:02.000Z | 2022-03-17T10:01:40.000Z | core/world/filter/Filter.hpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | 43 | 2022-02-21T13:07:08.000Z | 2022-03-22T11:02:16.000Z | core/world/filter/Filter.hpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | null | null | null | #ifndef MAD_CORE_WORLD_FILTER_FILTER_HPP
#define MAD_CORE_WORLD_FILTER_FILTER_HPP
#include <world/entity/Entity.hpp>
#include <memory>
#include <vector>
namespace mad::core {
struct Filter {
enum class Type {
Id,
True
};
explicit Filter(Type new_type) : type(new_type) {
}
virtual ~Filter() = default;
const Type type;
};
}
#endif //MAD_CORE_WORLD_FILTER_FILTER_HPP
| 15.233333 | 57 | 0.621444 | PlatformerTeam |
5457dd67633d2d84e3c2f7bd495184dbb65e145b | 5,683 | cpp | C++ | addons/support/config.cpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 1 | 2020-06-07T00:45:49.000Z | 2020-06-07T00:45:49.000Z | addons/support/config.cpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 27 | 2020-05-24T11:09:56.000Z | 2020-05-25T12:28:10.000Z | addons/support/config.cpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 2 | 2020-05-31T08:52:45.000Z | 2021-04-16T23:16:37.000Z | #include "script_component.hpp"
class CfgPatches {
class ADDON {
name = COMPONENT_NAME;
units[] = {};
weapons[] = {};
requiredVersion = REQUIRED_VERSION;
requiredAddons[] = {"a3cs_common", "A3_Ui_F"};
author = ECSTRING(main,Author);
authors[] = {"SzwedzikPL"};
url = ECSTRING(main,URL);
VERSION_CONFIG;
};
};
/*
class RscText;
class RscTitle;
class RscListBox;
class RscControlsGroup;
class RscMapControl;
class RscButtonMenu;
class RscButtonMenuCancel;
class GVAR(RscSupportPanel) {
onLoad = QUOTE(uiNamespace setVariable [ARR_2(QQGVAR(RscSupportPanel), _this select 0)];);
onUnload = QUOTE(uiNamespace setVariable [ARR_2(QQGVAR(RscSupportPanel), displayNull)];);
idd = -1;
movingEnable = 1;
enableSimulation = 1;
enableDisplay = 1;
class controlsBackground {
class titleBackground: RscText {
idc = IDC_RSCSUPPORTPANEL_TITLEBG;
x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "53 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorBackground[] = {
"(profilenamespace getvariable ['GUI_BCG_RGB_R', 0.13])",
"(profilenamespace getvariable ['GUI_BCG_RGB_G', 0.54])",
"(profilenamespace getvariable ['GUI_BCG_RGB_B', 0.21])",
"(profilenamespace getvariable ['GUI_BCG_RGB_A', 0.8])"
};
};
class mainBackground: RscText {
idc = IDC_RSCSUPPORTPANEL_MAINBG;
x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "2.1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "53 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "20.8 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorBackground[] = {0, 0, 0, 0.69999999};
};
};
class Controls {
class title: RscTitle {
idc = IDC_RSCSUPPORTPANEL_TITLE;
text = CSTRING(Title);
x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class assetTitle: RscTitle {
idc = IDC_RSCSUPPORTPANEL_ASSETTITLE;
text = "";
x = "8.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "24 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class assetsList: RscListBox {
IDC = IDC_RSCSUPPORTPANEL_ASSETS;
x = "-6.3 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class propertiesGroup: RscControlsGroup {
IDC = IDC_RSCSUPPORTPANEL_PROPERTIES;
x = "8.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class positionMap: RscMapControl {
idc = IDC_RSCSUPPORTPANEL_MAP;
x = "23.7 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "22.5 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorBackground[] = {1, 1, 1, 1};
showCountourInterval = 0;
scaleDefault = 0.1;
drawObjects = 0;
showMarkers = 0;
showTacticalPing = 0;
};
class sendMission: RscButtonMenu {
idc = IDC_RSCSUPPORTPANEL_BUTTONSEND;
text = CSTRING(SendMission);
x = "38.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "23 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "8 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class cancelDialog: RscButtonMenuCancel {
text = ECSTRING(Common,Close);
x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)";
y = "23 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)";
w = "6.25 * (((safezoneW / safezoneH) min 1.2) / 40)";
h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
};
};
*/
| 47.756303 | 138 | 0.575224 | Krzyciu |
5459e92dbd7eae9afe87f31967020dba55bfc527 | 5,131 | hxx | C++ | opencascade/ShapeUpgrade.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/ShapeUpgrade.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/ShapeUpgrade.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 1998-06-03
// Created by: data exchange team
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapeUpgrade_HeaderFile
#define _ShapeUpgrade_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <TColGeom_HSequenceOfBoundedCurve.hxx>
#include <TColGeom2d_HSequenceOfBoundedCurve.hxx>
class Geom_BSplineCurve;
class Geom2d_BSplineCurve;
class ShapeUpgrade_Tool;
class ShapeUpgrade_EdgeDivide;
class ShapeUpgrade_ClosedEdgeDivide;
class ShapeUpgrade_WireDivide;
class ShapeUpgrade_FaceDivide;
class ShapeUpgrade_ClosedFaceDivide;
class ShapeUpgrade_FaceDivideArea;
class ShapeUpgrade_ShapeDivide;
class ShapeUpgrade_ShapeDivideArea;
class ShapeUpgrade_ShapeDivideContinuity;
class ShapeUpgrade_ShapeDivideAngle;
class ShapeUpgrade_ShapeConvertToBezier;
class ShapeUpgrade_ShapeDivideClosed;
class ShapeUpgrade_ShapeDivideClosedEdges;
class ShapeUpgrade_SplitCurve;
class ShapeUpgrade_SplitCurve2d;
class ShapeUpgrade_SplitCurve2dContinuity;
class ShapeUpgrade_ConvertCurve2dToBezier;
class ShapeUpgrade_SplitCurve3d;
class ShapeUpgrade_SplitCurve3dContinuity;
class ShapeUpgrade_ConvertCurve3dToBezier;
class ShapeUpgrade_SplitSurface;
class ShapeUpgrade_SplitSurfaceContinuity;
class ShapeUpgrade_SplitSurfaceAngle;
class ShapeUpgrade_ConvertSurfaceToBezierBasis;
class ShapeUpgrade_SplitSurfaceArea;
class ShapeUpgrade_ShellSewing;
class ShapeUpgrade_FixSmallCurves;
class ShapeUpgrade_FixSmallBezierCurves;
class ShapeUpgrade_RemoveLocations;
class ShapeUpgrade_RemoveInternalWires;
class ShapeUpgrade_UnifySameDomain;
//! This package provides tools
//! for splitting and converting shapes by some criteria. It
//! provides modifications of the kind when one topological
//! object can be converted or splitted to several ones. In
//! particular this package contains high level API classes which perform:
//! converting geometry of shapes up to given continuity,
//! splitting revolutions by U to segments less than given value,
//! converting to beziers,
//! splitting closed faces.
class ShapeUpgrade
{
public:
DEFINE_STANDARD_ALLOC
//! Unifies same domain faces and edges of specified shape
Standard_EXPORT static Standard_Boolean C0BSplineToSequenceOfC1BSplineCurve (const Handle(Geom_BSplineCurve)& BS, Handle(TColGeom_HSequenceOfBoundedCurve)& seqBS);
//! Converts C0 B-Spline curve into sequence of C1 B-Spline curves.
//! This method splits B-Spline at the knots with multiplicities
//! equal to degree, i.e. unlike method
//! GeomConvert::C0BSplineToArrayOfC1BSplineCurve this one does not
//! use any tolerance and therefore does not change the geometry of
//! B-Spline.
//! Returns True if C0 B-Spline was successfully splitted, else
//! returns False (if BS is C1 B-Spline).
Standard_EXPORT static Standard_Boolean C0BSplineToSequenceOfC1BSplineCurve (const Handle(Geom2d_BSplineCurve)& BS, Handle(TColGeom2d_HSequenceOfBoundedCurve)& seqBS);
protected:
private:
friend class ShapeUpgrade_Tool;
friend class ShapeUpgrade_EdgeDivide;
friend class ShapeUpgrade_ClosedEdgeDivide;
friend class ShapeUpgrade_WireDivide;
friend class ShapeUpgrade_FaceDivide;
friend class ShapeUpgrade_ClosedFaceDivide;
friend class ShapeUpgrade_FaceDivideArea;
friend class ShapeUpgrade_ShapeDivide;
friend class ShapeUpgrade_ShapeDivideArea;
friend class ShapeUpgrade_ShapeDivideContinuity;
friend class ShapeUpgrade_ShapeDivideAngle;
friend class ShapeUpgrade_ShapeConvertToBezier;
friend class ShapeUpgrade_ShapeDivideClosed;
friend class ShapeUpgrade_ShapeDivideClosedEdges;
friend class ShapeUpgrade_SplitCurve;
friend class ShapeUpgrade_SplitCurve2d;
friend class ShapeUpgrade_SplitCurve2dContinuity;
friend class ShapeUpgrade_ConvertCurve2dToBezier;
friend class ShapeUpgrade_SplitCurve3d;
friend class ShapeUpgrade_SplitCurve3dContinuity;
friend class ShapeUpgrade_ConvertCurve3dToBezier;
friend class ShapeUpgrade_SplitSurface;
friend class ShapeUpgrade_SplitSurfaceContinuity;
friend class ShapeUpgrade_SplitSurfaceAngle;
friend class ShapeUpgrade_ConvertSurfaceToBezierBasis;
friend class ShapeUpgrade_SplitSurfaceArea;
friend class ShapeUpgrade_ShellSewing;
friend class ShapeUpgrade_FixSmallCurves;
friend class ShapeUpgrade_FixSmallBezierCurves;
friend class ShapeUpgrade_RemoveLocations;
friend class ShapeUpgrade_RemoveInternalWires;
friend class ShapeUpgrade_UnifySameDomain;
};
#endif // _ShapeUpgrade_HeaderFile
| 34.668919 | 169 | 0.846619 | valgur |