blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
00ad84d6a625b65506bdf893f5e9ab780ace5134
0a9c8206f6a5992d4d4630a83380c3ac187603b8
/Triangle.h
8392248ffcaeb853f384780be035d91c9c1279ce
[]
no_license
ericktberg/RayTracer
1757eb7d3ce52a51e13e67979e4b0c021793e349
4d5c323eb1643a0c134449bd3e221e8a90e16c25
refs/heads/master
2021-01-15T20:09:36.266384
2016-10-20T10:40:39
2016-10-20T10:40:39
99,846,471
0
0
null
null
null
null
UTF-8
C++
false
false
1,114
h
Triangle.h
#pragma once #include "Object.h" #include "Ray3D.h" #include "UVCoord.h" #include "Vector3D.h" #include "Vertex.h" #include <vector> namespace object{ class Triangle : public Object { public: //References vertices only. Change vertices at source to modify vertex locations. Triangle(const Vertex* v1, const Vertex* v2, const Vertex* v3); ~Triangle(); void addVertex(const Vertex* new_vertex); void add_uv_coords(UVCoord uv1, UVCoord uv2, UVCoord uv3); void add_vertex_normals(Vector3D vn1, Vector3D vn2, Vector3D vn3); double rayCollision(const Ray3D& ray) const; Vector3D getNormal(const Point3D& surfacePoint) const; UVCoord get_uv(const Point3D& intersection) const; int has_uvs() const; private: std::vector<double> get_barycentric(const Point3D& intersection) const; std::vector<const Vertex*> vertices_; //limit 3. Order determines normal face normal direction. std::vector<Vector3D> vertex_normals_; std::vector<UVCoord> uvs_; //Barycentric coordinates. p0 = vertices_.at(0) Vector3D e1_; //p1 - p0 Vector3D e2_; //p2 - p0 Vector3D normal_; //e1 X e2 }; }
15ec50fc4a59f72f758ffb09dae5f03f426e63f6
ac550c8c10749650de10fe31e2b646e476822867
/reference/bdwy/c-breeze/src/backend/arch_info.cc
5ecfa8c92f04a2674ea89b0e16941b94b7cf5e98
[]
no_license
jeversmann/undergradotaters
321a88600add4a318e42a026e47e87080486fce5
63ad3ffa6c4dd049b5b033970823d43f5f37bf9d
refs/heads/master
2021-01-23T21:45:29.474918
2015-09-24T23:31:28
2015-09-24T23:31:28
33,013,262
0
0
null
null
null
null
UTF-8
C++
false
false
19,678
cc
arch_info.cc
#include "c_breeze.h" #include "arch_info.h" #include "arch_info_parser.h" // because I'm lazy typedef arch_info::register_info register_info; typedef arch_info::register_info_list register_info_list; // these are needed so that we can parse Kill list in Lir2Asm record register_info arch_info::pseudo_reg_dest( (unsigned int)-2, "dest" ); register_info arch_info::pseudo_reg_src1( (unsigned int)-4, "src1" ); register_info arch_info::pseudo_reg_src2( (unsigned int)-5, "src2" ); // for handling errors when we parse the desc #define PARSE_ERROR( format ) \ CBZ::Fail( __FILE__, __LINE__, \ cbz_util::string_format( "error parsing architecture spec (near line %d): ", _currentLine ) ); \ arch_info::arch_info() { // internal initial values _nextRegId = 0; // init our state reset_info(); } arch_info::~arch_info() { } void arch_info::reset_info() { // we are no longer valid _valid = false; // kill everything _asmLineComment.clear(); _asmRegPrefixAdd.clear(); _asmRegPrefixRemove.clear(); _asmRegPrefixRemoveSplit.clear(); _asmConstPrefix.clear(); _regsAll.clear(); _regMap.clear(); _regsGpr.clear(); _regsFpr.clear(); _regSp = NULL; _regFp = NULL; _regsParamFixed.clear(); _regsParamFloat.clear(); _regRetvalFixed = NULL; _regRetvalFloat = NULL; _regDataTypeGpr = vt_unknown; _regDataTypeFpr = vt_unknown; _dataSizeLong = 8; _dataSizeInt = 4; _dataSizeShort= 2; _dataSizeDouble = 8; _dataSizeFloat = 4; _dataSizePtr = 4; _maxDataAlign = (unsigned int)-1; _dataAlignChar = 1; _dataAlignShort = 2; _dataAlignInt = 4; _dataAlignLong = 8; _dataAlignFloat = 4; _dataAlignDouble = 8; _dataAlignPtr = 4; _stackFrameMinSize = 0; _stackExtraTop = 0; _stackExtraBottom = 0; _stackAlign = 0; _stackFormalsOffset = 0; _emulate3Address = false; _Lir2Asm_records.clear(); _Lir2Asm_mnemonicLookup.clear(); } const char * arch_info::get_asm_line_comment() const { return _asmLineComment.c_str(); } const char * arch_info::get_asm_const_prefix() const { return _asmConstPrefix.c_str(); } const register_info_list & arch_info::get_all_regs() const { return _regsAll; } const register_info_list & arch_info::get_regs_gpr() const { return _regsGpr; } const register_info_list & arch_info::get_regs_fpr() const { return _regsFpr; } const register_info* arch_info::get_reg_sp() const { return _regSp; } const register_info* arch_info::get_reg_fp() const { return _regFp; } const register_info_list & arch_info::get_regs_param_fixed() const { return _regsParamFixed; } const register_info_list & arch_info::get_regs_param_float() const { return _regsParamFloat; } const register_info* arch_info::get_reg_retval_fixed() const { return _regRetvalFixed; } const register_info* arch_info::get_reg_retval_float() const { return _regRetvalFloat; } const register_info_list & arch_info::get_regs_caller_save() const { return _regsCallerSave; } const register_info_list & arch_info::get_regs_callee_save() const { return _regsCalleeSave; } lir_var_type arch_info::get_reg_data_type_gpr() const { return _regDataTypeGpr; } lir_var_type arch_info::get_reg_data_type_fpr() const { return _regDataTypeFpr; } bool arch_info::get_reg_name( const Register & reg, string & name, bool wantPrefixAdd, bool wantPrefixRemove ) { // check bounds first int num = reg.num(); if ( num < 0 || num >= (int)_regsAll.size() ) return false; // return its name, after prefix munging name = _regsAll[num]->_name; if ( wantPrefixAdd ) name = _asmRegPrefixAdd + name; if ( wantPrefixRemove ) for ( size_t i = 0; i < _asmRegPrefixRemoveSplit.size(); ++i ) if ( name.find( _asmRegPrefixRemoveSplit[i] ) == 0 ) name.erase( 0, _asmRegPrefixRemoveSplit[i].size() ); return true; } bool arch_info::get_reg_by_index( int realRegIndex, Register & reg ) { // check bounds first if ( realRegIndex < 0 || realRegIndex >= (int)_regsAll.size() ) return false; // just grab it by pointer reg = get_register( _regsAll[realRegIndex] ); return true; } unsigned int arch_info::get_data_size( lir_var_type vt ) const { switch ( vt ) { case vt_char: case vt_uchar: return 1; case vt_short: case vt_ushort: return get_data_size_short(); case vt_int: case vt_uint: return get_data_size_int(); case vt_long: case vt_ulong: return get_data_size_long(); case vt_float: return get_data_size_float(); case vt_double: return get_data_size_double(); case vt_pointer: return get_data_size_ptr(); default: // we have no idea how big this is CBZFAIL(( "ERROR: can't determine data size for low-level type %d.", vt )); assert( false ); return 0; } } unsigned int arch_info::get_max_data_align() const { // did we already compute it? if ( _maxDataAlign != -1 ) return _maxDataAlign; // compute it _maxDataAlign = _dataAlignChar; if ( _maxDataAlign < _dataAlignShort ) _maxDataAlign = _dataAlignShort; if ( _maxDataAlign < _dataAlignInt ) _maxDataAlign = _dataAlignInt; if ( _maxDataAlign < _dataAlignLong ) _maxDataAlign = _dataAlignLong; if ( _maxDataAlign < _dataAlignFloat ) _maxDataAlign = _dataAlignFloat; if ( _maxDataAlign < _dataAlignDouble ) _maxDataAlign = _dataAlignDouble; if ( _maxDataAlign < _dataAlignPtr ) _maxDataAlign = _dataAlignPtr; return _maxDataAlign; } unsigned int arch_info::get_data_align( lir_var_type vt ) const { switch ( vt ) { case vt_char: case vt_uchar: return get_data_align_char(); case vt_short: case vt_ushort: return get_data_align_short(); case vt_int: case vt_uint: return get_data_align_int(); case vt_long: case vt_ulong: return get_data_align_long(); case vt_float: return get_data_align_float(); case vt_double: return get_data_align_double(); case vt_pointer: return get_data_align_ptr(); case vt_aggr: return get_max_data_align(); default: // we have no idea how to align this CBZFAIL(( "ERROR: can't determine alignment for low-level type %d.", vt )); assert( false ); return 0; } } bool arch_info::get_code_for_instruction( const LirInst * pInst, vector<string> & lines ) { // find the Lir2Asm for this instruction Lir2Asm * pLir2Asm = NULL; if ( ! get_Lir2Asm_for_instruction( pInst, &pLir2Asm ) || ! pLir2Asm ) return false; // copy the lines cbz_util::vector_copy( pLir2Asm->_codeTemplate, lines ); // make replacements make_template_replacements( pInst, pLir2Asm, lines ); // do formatting - labels are left-justified, all others indented from left edge if ( pInst->instruction != mn_Label ) { int i, sz = (int)lines.size(); for ( i = 0; i < sz; ++i ) { // add some space if it is not a label (assume anything with colon char is label) if ( lines[i].find( ':' ) == -1 ) lines[i].insert( 0, 4, ' ' ); } } return true; } bool arch_info::get_instruction_kill_regs( const LirInst * pInst, register_info_list & killRegs ) { // find the Lir2Asm for this instruction Lir2Asm * pLir2Asm = NULL; if ( ! get_Lir2Asm_for_instruction( pInst, &pLir2Asm ) || ! pLir2Asm ) return false; // copy the register info cbz_util::vector_copy( pLir2Asm->_killRegs, killRegs ); return true; } bool arch_info::types_need_conversion( lir_var_type vtsrc, lir_var_type vtdest ) { // get a lir2asm for it - if we have none, pretend we need conversion so we'll fail later Lir2Asm * l2a = NULL; if ( ! get_Lir2Asm_for_instruction( mn_ConvertType, vtsrc, vtdest, false, &l2a ) || ! l2a ) return true; // are there any instructions for it? if so, we need conversion. return (l2a->_codeTemplate.size() != 0); } bool arch_info::instruction_supports_immediate( mnemonic instruction, lir_var_type vt, const constant & c ) { // no strings as immediates if ( c.is_str() ) return false; // get a lir2asm for it - if we have one, it's supported Lir2Asm * l2a = NULL; return ( get_Lir2Asm_for_instruction( instruction, vt, vt_unknown, true, &l2a ) && l2a != NULL ); } bool arch_info::find_register_info( const char * name, register_info *& regInfoFound ) const { // find this one in our set of registers register_info_map::const_iterator it = _regMap.find( name ); if ( it == _regMap.end() ) return false; // give them what we found regInfoFound = (*it).second; return true; } Register arch_info::get_register( const register_info * pInfo ) { // the value we'll return Register ret; if ( ! pInfo ) return ret; // copy id and type ret.num( pInfo->_id ); ret.type( pInfo->_type ); return ret; } bool arch_info::get_Lir2Asm_for_instruction( const LirInst * pInst, Lir2Asm ** ppLir2Asm ) { // use other version return get_Lir2Asm_for_instruction( pInst->instruction, pInst->vtPrimary, pInst->vtConvert, pInst->opnd2._is_const, ppLir2Asm ); } bool arch_info::get_Lir2Asm_for_instruction( mnemonic inst, lir_var_type vtsrc, lir_var_type vtdest, bool isImmed, Lir2Asm ** ppLir2Asm ) { // find list of possibles for this guy map_menmonic_to_record_set::const_iterator it = _Lir2Asm_mnemonicLookup.find( inst ); if ( it == _Lir2Asm_mnemonicLookup.end() ) return false; // find actual match const vector<int> & possibles = it->second; int sz = (int)possibles.size(); for ( int i = 0; i < sz; ++i ) { // sanity check - the values in possibles should be array indices assert( possibles[i] >= 0 && possibles[i] < (int)_Lir2Asm_records.size() ); Lir2Asm & l2a = _Lir2Asm_records[ possibles[i] ]; // this thing had better handle this instruction assert( -1 != cbz_util::vector_find( l2a._lirInstTypes, inst ) ); // does this template specify an immediate? if ( l2a._immed != Lir2Asm::Immed_NA ) { // make sure immediate-ness is matched if ( l2a._immed == Lir2Asm::Immed_No && isImmed ) continue; else if ( l2a._immed == Lir2Asm::Immed_Yes && ! isImmed ) continue; } // data types match? (if this thing listed no data types, it matches any type) if ( vtsrc != vt_unknown && l2a._dataTypes.size() > 0 && -1 == cbz_util::vector_find( l2a._dataTypes, vtsrc ) ) continue; // conversion types match? (conversion types must be explicitly listed) if ( vtdest != vt_unknown && -1 == cbz_util::vector_find( l2a._convertToTypes, vtdest ) ) continue; // this one matches *ppLir2Asm = &l2a; return true; } return false; } void arch_info::make_template_replacements( const LirInst * pInst, Lir2Asm * pLir2Asm, code_template & outputTemplate ) { // generate strings for each various token string dest, op1, op2, base, offset, target, stacksize, str; if ( pInst->has_dest() ) dest = pInst->dest.to_string(); if ( pInst->has_opnd1() ) op1 = pInst->opnd1.to_string(); if ( pInst->has_opnd2( false ) ) op2 = pInst->opnd2.to_string( false, true ); if ( pInst->has_base() ) base = pInst->memBase.to_string(); if ( pInst->has_offset( false ) ) offset = pInst->memOffset.to_string( false, false ); if ( pInst->nodeExtra && pInst->nodeExtra->typ() == Proc ) stacksize = cbz_util::string_format( "%d", ((procNode*)(pInst->nodeExtra))->stack_frame_size() ); // always read a target and static data target = pInst->target; str = pInst->dataString; // make replacements in template int i, sz = (int)outputTemplate.size(); for ( i = 0; i < sz; ++i ) { // fix various parts of template cbz_util::string_replace( outputTemplate[i], "$dest", dest ); cbz_util::string_replace( outputTemplate[i], "$opnd1", op1 ); cbz_util::string_replace( outputTemplate[i], "$opnd2", op2 ); cbz_util::string_replace( outputTemplate[i], "$base", base ); cbz_util::string_replace( outputTemplate[i], "$offset", offset ); cbz_util::string_replace( outputTemplate[i], "$target", target ); cbz_util::string_replace( outputTemplate[i], "$stacksize", stacksize ); cbz_util::string_replace( outputTemplate[i], "$string", str ); // fixup any register names that were formatted @name int reg, szregs = (int)_regsAll.size(); for ( reg = 0; reg < szregs; ++reg ) { string handyName = '@' + _regsAll[reg]->_name; string realName; get_reg_name( *_regsAll[reg], realName, true, true ); cbz_util::string_replace( outputTemplate[i], handyName, realName ); } } } bool arch_info::load_arch_info( const char * pFileName ) { int i, sz; // reset ourself first reset_info(); // let our parser do the work arch_info_parser parser; if ( ! parser.parse( pFileName, this ) ) return false; ///////////////////////////// // setup register stuff // setup type info for registers _regSp->_type = reg_stack_ptr; _regFp->_type = reg_frame_ptr; sz = (int)_regsGpr.size(); for ( i = 0; i < sz; ++i ) _regsGpr[i]->_type = reg_gpr; sz = (int)_regsFpr.size(); for ( i = 0; i < sz; ++i ) _regsFpr[i]->_type = reg_fpr; //////////////////// // sanity checks #define ARCHWARN( expr ) \ cout << cbz_util::string_format expr << endl; if ( _regsAll.size() < 1 ) ARCHWARN(( "WARNING: architecture does not appear to have any registers!!" )); if ( _regsGpr.size() < 1 ) ARCHWARN(( "WARNING: architecture does not appear to have any integer registers!!" )); if ( ! _regSp || ! _regSp->is_valid() ) ARCHWARN(( "WARNING: architecture does not appear to have a stack pointer register!!" )); if ( ! _regFp || ! _regFp->is_valid() ) ARCHWARN(( "WARNING: architecture does not appear to have a frame pointer register!!" )); if ( _regDataTypeGpr == vt_unknown ) ARCHWARN(( "WARNING: invalid data type specified for general-purpose registers!!" )); if ( _regDataTypeFpr == vt_unknown ) ARCHWARN(( "WARNING: invalid data type specified for floating-point registers!!" )); if ( _dataSizeShort <= 0 ) ARCHWARN(( "WARNING: size of short integer (%d) appears to be ridiculous!!", _dataSizeShort )); if ( _dataSizeInt <= 0 ) ARCHWARN(( "WARNING: size of integer (%d) appears to be ridiculous!!", _dataSizeInt )); if ( _dataSizeLong <= 0 ) ARCHWARN(( "WARNING: size of long integer (%d) appears to be ridiculous!!", _dataSizeLong )); if ( _dataSizeFloat <= 0 ) ARCHWARN(( "WARNING: size of float (%d) appears to be ridiculous!!", _dataSizeFloat )); if ( _dataSizeDouble <= 0 ) ARCHWARN(( "WARNING: size of double float (%d) appears to be ridiculous!!", _dataSizeDouble )); if ( _dataSizePtr <= 0 ) ARCHWARN(( "WARNING: size of pointer (%d) appears to be ridiculous!!", _dataSizePtr )); // currently we don't handle the case that our data sizes and the target data sizes don't match if ( sizeof(short) != _dataSizeShort ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'short'. " "This is currently not handled properly by the backend." )); if ( sizeof(int) != _dataSizeInt ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'int'. " "This is currently not handled properly by the backend." )); if ( sizeof(long) != _dataSizeLong ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'long'. " "This is currently not handled properly by the backend." )); if ( sizeof(float) != _dataSizeFloat ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'float'. " "This is currently not handled properly by the backend." )); if ( sizeof(double) != _dataSizeDouble ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'double'. " "This is currently not handled properly by the backend." )); if ( sizeof(void*) != _dataSizePtr ) ARCHWARN(( "WARNING: compiler data size does not match target data size for type 'pointer'. " "This is currently not handled properly by the backend." )); if ( _dataAlignChar <= 0 ) ARCHWARN(( "WARNING: alignment of character (%d) appears to be ridiculous!!", _dataAlignChar )); if ( _dataAlignShort <= 0 ) ARCHWARN(( "WARNING: alignment of short integer (%d) appears to be ridiculous!!", _dataAlignShort )); if ( _dataAlignInt <= 0 ) ARCHWARN(( "WARNING: alignment of integer (%d) appears to be ridiculous!!", _dataAlignInt )); if ( _dataAlignLong <= 0 ) ARCHWARN(( "WARNING: alignment of long integer (%d) appears to be ridiculous!!", _dataAlignLong )); if ( _dataAlignFloat <= 0 ) ARCHWARN(( "WARNING: alignment of float (%d) appears to be ridiculous!!", _dataAlignFloat )); if ( _dataAlignDouble <= 0 ) ARCHWARN(( "WARNING: alignment of double float (%d) appears to be ridiculous!!", _dataAlignDouble )); if ( _dataAlignPtr <= 0 ) ARCHWARN(( "WARNING: alignment of pointer (%d) appears to be ridiculous!!", _dataAlignPtr )); if ( _stackFrameMinSize < 0 ) ARCHWARN(( "WARNING: stack frame minimum size (%d) appears to be ridiculous!!", _stackFrameMinSize )); if ( _stackAlign < 0 ) ARCHWARN(( "WARNING: stack alignment value (%d) appears to be ridiculous!!", _stackAlign )); if ( _stackFrameMinSize != 0 && _stackAlign != 0 && (_stackFrameMinSize % _stackAlign) != 0 ) ARCHWARN(( "WARNING: stack frame minimum size is not a multiple of stack alignment!!" )); // make sure caller-save and callee-save are disjoint and that all regs are in one list or another register_info_list::iterator it = _regsAll.begin(); for ( ; it != _regsAll.end(); ++it ) { register_info * info = *it; if ( ! info ) continue; // assume neither bool caller = false, callee = false; // see if it's a callee-save register_info_list::iterator calleeIt = _regsCalleeSave.begin(); for ( ; calleeIt != _regsCalleeSave.end(); ++calleeIt ) if ( info == *calleeIt ) { callee = true; break; } // see if it's a caller-save register_info_list::iterator callerIt = _regsCallerSave.begin(); for ( ; callerIt != _regsCallerSave.end(); ++callerIt ) if ( info == *callerIt ) { caller = true; break; } // it should be saved by someone (except fp, sp, retFixed, and retFloat) if ( ! caller && ! callee && info != _regFp && info != _regSp && info != _regRetvalFixed && info != _regRetvalFloat ) ARCHWARN(( "WARNING: register %s is not caller-save or callee-save - is this the intent?", info->_name.c_str() )); // but not by both... if ( caller && callee ) ARCHWARN(( "WARNING: register %s is both caller-save and callee-save - is this the intent?", info->_name.c_str() )); // fp and sp must be handled by arch template code - we do not save them for you if ( (caller || callee) && (info == _regFp || info == _regSp) ) ARCHWARN(( "WARNING: register %s should be handled by architecture template because it is the frame/stack pointer.", info->_name.c_str() )); // retFixed and retFloat should probably be caller-save but for now they are neither if ( (caller || callee) && (info == _regRetvalFixed || info == _regRetvalFloat) ) ARCHWARN(( "WARNING: return-value register %s is volatile and will not be saved even though marked as caller/callee save.", info->_name.c_str() )); } #undef ARCHWARN //////////////////////////////////////////////// // other stuff // split up prefix remove stuff - treat as comma-separated list if ( ! _asmRegPrefixRemove.empty() ) { int len = _asmRegPrefixRemove.size() + 2; char * split = new char[ len ]; strcpy( split, _asmRegPrefixRemove.c_str() ); split[ len-1 ] = 0; char *p1 = split, *p2 = strchr(p1, ','); while ( (p2 = strchr(p1, ',')) ) { // kill the comma and add what was before it to array *p2 = 0; _asmRegPrefixRemoveSplit.push_back( p1 ); p1 = p2 + 1; } _asmRegPrefixRemoveSplit.push_back( p1 ); delete [] split; } //////////////////////////////////////////////// // show all of this to the user // title cout << endl; cout << "will compile for architecture: " << _archName.c_str() << endl; cout << endl; // we are valid now _valid = true; return true; }
5b588b1ea8d9fe015179ab2b410bfafa31be14f2
9c73501c5a8413753ed5776299fe1f62a0a2659e
/src/Settings/Equations/T_i.cpp
f505c27d63fcaa244d5faf711c04428792488a7b
[ "MIT" ]
permissive
anymodel/DREAM-1
5d1ac63ffc48157f110ef672036d801442a2c917
eba9fabddfa4ef439737807ef30978a52ab55afb
refs/heads/master
2023-08-23T05:01:13.867792
2021-10-28T19:45:33
2021-10-28T19:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,291
cpp
T_i.cpp
#include "DREAM/Equations/Fluid/IonSpeciesIdentityTerm.hpp" #include "DREAM/Equations/Fluid/IonSpeciesTransientTerm.hpp" #include "DREAM/Equations/Fluid/MaxwellianCollisionalEnergyTransferTerm.hpp" #include "DREAM/Settings/SimulationGenerator.hpp" #include "FVM/Equation/Operator.hpp" /** * Implementation of equations governing the evolution of the * ion heat W_i = 1.5 * N_i * T_i, which satisfy * dW_i/dt = Q_ie + sum_j Q_ij * with the collisional energy transfer Q_ij summed over all ion species j * and the exchange Q_ie with electrons. This ion heat is not * charge-state resolved, so that each species only has one temperature. */ using namespace DREAM; using namespace std; #define MODULENAME "eqsys/n_i" void SimulationGenerator::ConstructEquation_T_i(EquationSystem *eqsys, Settings *s){ /** * if the electron heat W_cold is evolved self-consistently, * also evolve the ion heat W_i. Otherwise set it to constant. */ enum OptionConstants::uqty_T_cold_eqn TcoldType = (enum OptionConstants::uqty_T_cold_eqn)s->GetInteger("eqsys/T_cold/type"); if(TcoldType==OptionConstants::UQTY_T_COLD_EQN_PRESCRIBED) ConstructEquation_T_i_trivial(eqsys, s); else if (TcoldType == OptionConstants::UQTY_T_COLD_SELF_CONSISTENT) ConstructEquation_T_i_selfconsistent(eqsys, s); else throw SettingsException( "T_i: Unrecognized equation type for '%s': %d.", OptionConstants::UQTY_T_COLD, TcoldType ); // Initialize heat from ion densities and input ion temperatures real_t *Ti_init = LoadDataIonR(MODULENAME, eqsys->GetFluidGrid()->GetRadialGrid(), s, eqsys->GetIonHandler()->GetNZ(), "initialTi"); const real_t *Ni_init = eqsys->GetUnknownHandler()->GetUnknownInitialData(eqsys->GetUnknownID(OptionConstants::UQTY_NI_DENS)); for(len_t it=0; it<eqsys->GetIonHandler()->GetNZ()*eqsys->GetFluidGrid()->GetNr(); it++) Ti_init[it] *= 1.5*Constants::ec*Ni_init[it]; eqsys->SetInitialValue(eqsys->GetUnknownID(OptionConstants::UQTY_WI_ENER), Ti_init); } /** * Set a trivial equation W_i = constant for all ion species */ void SimulationGenerator::ConstructEquation_T_i_trivial(EquationSystem *eqsys, Settings* /*s*/){ const len_t id_Wi = eqsys->GetUnknownID(OptionConstants::UQTY_WI_ENER); FVM::Operator *Op = new FVM::Operator(eqsys->GetFluidGrid()); for(len_t iz=0; iz<eqsys->GetIonHandler()->GetNZ(); iz++) Op->AddTerm( new IonSpeciesTransientTerm(eqsys->GetFluidGrid(), iz, id_Wi) ); eqsys->SetOperator(id_Wi, id_Wi, Op, "dW_i/dt = 0"); } /** * Implements the self-consistent evolution of ion heat W_i for each species */ void SimulationGenerator::ConstructEquation_T_i_selfconsistent(EquationSystem *eqsys, Settings* /*s*/){ const len_t id_Wi = eqsys->GetUnknownID(OptionConstants::UQTY_WI_ENER); const len_t id_Wcold = eqsys->GetUnknownID(OptionConstants::UQTY_W_COLD); FVM::Grid *fluidGrid = eqsys->GetFluidGrid(); IonHandler *ionHandler = eqsys->GetIonHandler(); FVM::UnknownQuantityHandler *unknowns = eqsys->GetUnknownHandler(); const len_t nZ = ionHandler->GetNZ(); FVM::Operator *Op_Wij = new FVM::Operator(fluidGrid); FVM::Operator *Op_Wie = new FVM::Operator(fluidGrid); CoulombLogarithm *lnLambda = eqsys->GetREFluid()->GetLnLambda(); for(len_t iz=0; iz<nZ; iz++){ Op_Wij->AddTerm( new IonSpeciesTransientTerm(fluidGrid, iz, id_Wi, -1.0) ); for(len_t jz=0; jz<nZ; jz++){ if(jz==iz) // the term is trivial =0 for self collisions and can be skipped continue; Op_Wij->AddTerm( new MaxwellianCollisionalEnergyTransferTerm( fluidGrid, iz, true, jz, true, unknowns, lnLambda, ionHandler) ); } Op_Wie->AddTerm( new MaxwellianCollisionalEnergyTransferTerm( fluidGrid, iz, true, 0, false, unknowns, lnLambda, ionHandler) ); } eqsys->SetOperator(id_Wi, id_Wi, Op_Wij, "dW_i/dt = sum_j Q_ij + Q_ie"); eqsys->SetOperator(id_Wi, id_Wcold, Op_Wie); }
b9619ed14f0a55c8cc25efd586492f8f3432f687
8383fef8376b6710388811bb3a48035627e9419f
/src/main/cpp/libtiv.hpp
310e4bdf0e6048fa6863370c9791fef6270655a6
[ "Apache-2.0" ]
permissive
hiro-ogawa/TerminalImageViewer
58d520b4bdc14ddd6e2f5e0d770f6bd734923394
914dc186b6ab37724c2d8b5329574a44bed8daa0
refs/heads/master
2021-04-10T13:30:45.090772
2020-03-21T08:55:30
2020-03-21T08:55:51
248,937,620
0
0
Apache-2.0
2020-03-21T08:43:39
2020-03-21T08:43:38
null
UTF-8
C++
false
false
108
hpp
libtiv.hpp
#include <string> #include <opencv2/opencv.hpp> std::vector<std::string> emit_image(const cv::Mat &image);
63aebf99b004cb7a0c96544439409309bc51f337
384cd3cb5e72d48449773f562a5512fd3a7d8b34
/tableslocation.h
361b9cd1f9344ed466a32e5d7cae54e0a84719d2
[]
no_license
iKeJung/DES-with-QT
72341cbd31281e750a3d631bcebad6246982f1dc
dc55b051e90643a62a7c1fca43a6286bada9aad1
refs/heads/master
2020-03-30T02:34:24.610973
2018-09-27T23:29:34
2018-09-27T23:29:34
150,637,680
0
0
null
null
null
null
UTF-8
C++
false
false
568
h
tableslocation.h
#ifndef TABLESLOCATION_H #define TABLESLOCATION_H #include <QString> #include <QStringList> class TablesLocation { public: TablesLocation(); static const QString path; static const QString expandWord; static const QString keyShift; static const QString permute1; static const QString permute2; static const QString permuteKey1; static const QString permuteKey2; static const QString permuteSbox; static const QStringList sBox; }; #endif // TABLESLOCATION_H
f2982ebccacad56980f2c4a974b158e884117261
0e3d2ce96340e6d27a85569956a1b47d100e881f
/data/offline/makeUSCorrections.cxx
bcad1d7624a0818bcfb72c42140388cd5b596979
[]
no_license
rhanniga/lambda-over-hadron
1314d949c13f7299211d9be89dd280e50e70ae1d
18df5543ddd3a2b270fba8d2c6680a43d866cd9a
refs/heads/master
2023-08-28T14:02:10.149532
2023-08-15T01:25:22
2023-08-15T01:25:22
243,051,085
2
0
null
null
null
null
UTF-8
C++
false
false
19,174
cxx
makeUSCorrections.cxx
void makeUSCorrections(string inputFile){ TFile* input = new TFile(inputFile.c_str()); TH2D* hLambda2Dpeak = (TH2D*)input->Get("hLambda2Dpeak"); TH2D* hLambda2DLside = (TH2D*)input->Get("hLambda2DLside"); TH2D* hLambda2DRside = (TH2D*)input->Get("hLambda2DRside"); TH2D* hLambdaLS2Dpeak = (TH2D*)input->Get("hLambdaLS2Dpeak"); TH2D* hLambdaLS2DLside = (TH2D*)input->Get("hLambdaLS2DLside"); TH2D* hLambdaLS2DRside = (TH2D*)input->Get("hLambdaLS2DRside"); TH2D* trigDistSameUS = (TH2D*)input->Get("fTrigSameUSDist"); TH2D* trigDistSameLS = (TH2D*)input->Get("fTrigSameLSDist"); hLambda2Dpeak->SetName("uncorrectedhLambda2Dpeak"); TH2D* hLambdaBGPeakRegionL = (TH2D*)hLambda2DLside->Clone("hLambdaBGPeakRegionL"); hLambdaBGPeakRegionL->Scale(1.0/(hLambda2DLside->Integral(hLambda2DLside->GetXaxis()->FindBin(-1.2), hLambda2DLside->GetXaxis()->FindBin(1.2), 1, hLambda2DLside->GetYaxis()->GetNbins()))); hLambdaBGPeakRegionL->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* hLambdaBGPeakRegionL_deta = (TH1D*)hLambdaBGPeakRegionL->ProjectionX("hLambdaBGPeakRegionL_deta", 1, hLambdaBGPeakRegionL->GetYaxis()->GetNbins()); TH1D* hLambdaBGPeakRegionL_dphi = (TH1D*)hLambdaBGPeakRegionL->ProjectionY("hLambdaBGPeakRegionL_dphi", hLambdaBGPeakRegionL->GetXaxis()->FindBin(-1.2), hLambdaBGPeakRegionL->GetXaxis()->FindBin(1.2)); TH2D* hLambdaBGPeakRegionR = (TH2D*)hLambda2DRside->Clone("hLambdaBGPeakRegionR"); hLambdaBGPeakRegionR->Scale(1.0/(hLambda2DRside->Integral(hLambda2DRside->GetXaxis()->FindBin(-1.2), hLambda2DRside->GetXaxis()->FindBin(1.2), 1, hLambda2DRside->GetYaxis()->GetNbins()))); hLambdaBGPeakRegionR->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* hLambdaBGPeakRegionR_deta = (TH1D*)hLambdaBGPeakRegionR->ProjectionX("hLambdaBGPeakRegionR_deta", 1, hLambdaBGPeakRegionR->GetYaxis()->GetNbins()); TH1D* hLambdaBGPeakRegionR_dphi = (TH1D*)hLambdaBGPeakRegionR->ProjectionY("hLambdaBGPeakRegionR_dphi", hLambdaBGPeakRegionR->GetXaxis()->FindBin(-1.2), hLambdaBGPeakRegionR->GetXaxis()->FindBin(1.2)); TH2D* hLambdaBGPeakRegion = (TH2D*)hLambdaBGPeakRegionL->Clone("hLambdaBGPeakregion"); hLambdaBGPeakRegion->Add(hLambdaBGPeakRegionR); hLambdaBGPeakRegion->Scale(0.5); hLambdaBGPeakRegion->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* hLambdaBGPeakRegion_deta = (TH1D*)hLambdaBGPeakRegion->ProjectionX("hLambdaBGPeakRegion_deta", 1, hLambdaBGPeakRegion->GetYaxis()->GetNbins()); TH1D* hLambdaBGPeakRegion_dphi = (TH1D*)hLambdaBGPeakRegion->ProjectionY("hLambdaBGPeakRegion_dphi", hLambdaBGPeakRegion->GetXaxis()->FindBin(-1.2), hLambdaBGPeakRegion->GetXaxis()->FindBin(1.2)); //US residual checks between SB average and the Left and Right separately TH2D* resLeftVsAvg = (TH2D*)hLambdaBGPeakRegionL->Clone("resLeftVsAvg"); resLeftVsAvg->Add(hLambdaBGPeakRegion, -1.0); resLeftVsAvg->Divide(hLambdaBGPeakRegionL); resLeftVsAvg->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resLeftVsAvg_deta = (TH1D*)hLambdaBGPeakRegionL_deta->Clone("resLeftVsAvg_deta"); resLeftVsAvg_deta->Add(hLambdaBGPeakRegion_deta, -1.0); resLeftVsAvg_deta->Divide(hLambdaBGPeakRegionL_deta); resLeftVsAvg_deta->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resLeftVsAvg_dphi = (TH1D*)hLambdaBGPeakRegionL_dphi->Clone("resLeftVsAvg_dphi"); resLeftVsAvg_dphi->Add(hLambdaBGPeakRegion_dphi, -1.0); resLeftVsAvg_dphi->Divide(hLambdaBGPeakRegionL_dphi); TH2D* resRightVsAvg = (TH2D*)hLambdaBGPeakRegionR->Clone("resRightVsAbg"); resRightVsAvg->Add(hLambdaBGPeakRegion, -1.0); resRightVsAvg->Divide(hLambdaBGPeakRegionR); resRightVsAvg->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resRightVsAvg_deta = (TH1D*)hLambdaBGPeakRegionR_deta->Clone("resRightVsAvg_deta"); resRightVsAvg_deta->Add(hLambdaBGPeakRegion_deta, -1.0); resRightVsAvg_deta->Divide(hLambdaBGPeakRegionR_deta); resRightVsAvg_deta->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resRightVsAvg_dphi = (TH1D*)hLambdaBGPeakRegionR_dphi->Clone("resRightVsAvg_dphi"); resRightVsAvg_dphi->Add(hLambdaBGPeakRegion_dphi, -1.0); resRightVsAvg_dphi->Divide(hLambdaBGPeakRegionR_dphi); Float_t leftscale = hLambda2DLside->Integral(hLambda2DLside->GetXaxis()->FindBin(-1.2), hLambda2DLside->GetXaxis()->FindBin(1.2), 1, hLambda2DLside->GetYaxis()->GetNbins())/hLambdaLS2DLside->Integral(hLambda2DLside->GetXaxis()->FindBin(-1.2), hLambda2DLside->GetXaxis()->FindBin(1.2), 1, hLambda2DLside->GetYaxis()->GetNbins()); TH2D* LLSsubhLambda2DLside = (TH2D*)hLambda2DLside->Clone("LLSsubhLambda2DLside"); TH2D* LLSsubhLambda2Dpeak = (TH2D*)hLambda2Dpeak->Clone("LLSsubhLambda2Dpeak"); LLSsubhLambda2DLside->Add(hLambdaLS2DLside, -1.0*leftscale); //LLSsubhLambda2DLside->Divide(hLambdaLS2DLside); //LLSsubhLambda2DLside->Scale(1.0/leftscale); LLSsubhLambda2Dpeak->Add(hLambdaLS2Dpeak, -1.0*leftscale); TH1D* LLSsubhLambda2DLside_deta = LLSsubhLambda2DLside->ProjectionX("LLSsubhLambda2DLside_deta", 1, LLSsubhLambda2DLside->GetYaxis()->GetNbins()); TH1D* LLSsubhLambda2DLside_dphi = LLSsubhLambda2DLside->ProjectionY("LLSsubhLambda2DLside_dphi", LLSsubhLambda2DLside->GetXaxis()->FindBin(-1.2), LLSsubhLambda2DLside->GetXaxis()->FindBin(1.2)); //Float_t rightscale = hLambda2DRside->Integral(1, hLambda2DRside->GetXaxis()->GetNbins(), 1, hLambda2DRside->GetYaxis()->GetNbins())/hLambdaLS2DRside->Integral(1, hLambda2DRside->GetXaxis()->GetNbins(), 1, hLambda2DRside->GetYaxis()->GetNbins()); gStyle->SetOptStat(0); Float_t rightscale = hLambda2DRside->Integral(hLambda2DRside->GetXaxis()->FindBin(-1.2), hLambda2DRside->GetXaxis()->FindBin(1.2), 1, hLambda2DRside->GetYaxis()->GetNbins())/hLambdaLS2DRside->Integral(hLambda2DRside->GetXaxis()->FindBin(-1.2), hLambda2DRside->GetXaxis()->FindBin(1.2), 1, hLambda2DRside->GetYaxis()->GetNbins()); TH2D* RLSsubhLambda2DRside = (TH2D*)hLambda2DRside->Clone("RLSsubhLambda2DRside"); TH2D* RLSsubhLambda2Dpeak = (TH2D*)hLambda2Dpeak->Clone("RLSsubhLambda2Dpeak"); TH2D* RLSsubhLambda2DRsideScaled = (TH2D*)hLambda2DRside->Clone("RLSsubhLambda2DRsideScaled"); RLSsubhLambda2DRsideScaled->GetXaxis()->SetRangeUser(-1.2, 1.2); RLSsubhLambda2DRsideScaled->Scale(rightscale); TH1D* RLSsubhLambdaDPhiRsideScaled = RLSsubhLambda2DRsideScaled->ProjectionY(); RLSsubhLambdaDPhiRsideScaled->SetTitle("h-#Lambda^{0} scaled R-sideband #Delta#varphi distribution"); RLSsubhLambdaDPhiRsideScaled->SetLineColor(6); RLSsubhLambdaDPhiRsideScaled->SetLineWidth(3); RLSsubhLambdaDPhiRsideScaled->SetMarkerColor(6); TCanvas *presCanvas = new TCanvas("presCanvas", "Presentation Canvas", 0, 10, 1600, 1200); presCanvas->cd(); RLSsubhLambdaDPhiRsideScaled->Draw(); RLSsubhLambda2DRside->Add(hLambdaLS2DRside, -1.0*rightscale); //RLSsubhLambda2DRside->Divide(hLambdaLS2DRside); //RLSsubhLambda2DRside->Scale(1.0/rightscale); RLSsubhLambda2Dpeak->Add(hLambdaLS2Dpeak, -1.0*rightscale); RLSsubhLambda2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* RLSsubhLambda2DRside_deta = RLSsubhLambda2DRside->ProjectionX("RLSsubhLambda2DRside_deta", 1, RLSsubhLambda2DRside->GetYaxis()->GetNbins()); TH1D* RLSsubhLambda2DRside_dphi = RLSsubhLambda2DRside->ProjectionY("RLSsubhLambda2DRside_dphi", RLSsubhLambda2DRside->GetXaxis()->FindBin(-1.2), RLSsubhLambda2DRside->GetXaxis()->FindBin(1.2)); TH1D* RLSsubhLambda2Dpeak_deta = RLSsubhLambda2Dpeak->ProjectionX("RLSsubhLambda2Dpeak_deta", 1, RLSsubhLambda2Dpeak->GetYaxis()->GetNbins()); TH1D* RLSsubhLambda2Dpeak_dphi = RLSsubhLambda2Dpeak->ProjectionY("RLSsubhLambda2Dpeak_dphi", RLSsubhLambda2Dpeak->GetXaxis()->FindBin(-1.2), RLSsubhLambda2Dpeak->GetXaxis()->FindBin(1.2)); TH1D* scales = new TH1D("scales", "scales", 2, -1, 1); scales->SetBinContent(1, leftscale); scales->SetBinContent(2, rightscale); TH2D* rebinRLSsubhLambda2Dpeak = (TH2D*)RLSsubhLambda2Dpeak->Clone("rebinRLSsubhLambda2Dpeak"); rebinRLSsubhLambda2Dpeak->Rebin2D(2, 2); //Using US estimate for BG to subtract off the from the peak region: Float_t scaleUS = (rightscale)*hLambdaLS2Dpeak->Integral(hLambdaLS2Dpeak->GetXaxis()->FindBin(-1.2), hLambdaLS2Dpeak->GetXaxis()->FindBin(1.2), 1, hLambdaLS2Dpeak->GetYaxis()->GetNbins()); Float_t scaletest = (rightscale)*hLambda2Dpeak->Integral(hLambda2Dpeak->GetXaxis()->FindBin(-1.2), hLambda2Dpeak->GetXaxis()->FindBin(1.2), 1, hLambda2Dpeak->GetYaxis()->GetNbins()); printf("\n\nscaleUS = %e\n\ntestscale = %e \n\n", scaleUS, scaletest); //avg of right and left US sideband tests TH2D* AvgUSsubhLambda2Dpeak = (TH2D*)hLambda2Dpeak->Clone("AvgUSsubhLambda2Dpeak"); AvgUSsubhLambda2Dpeak->Add(hLambdaBGPeakRegion, -1.0*scaleUS); AvgUSsubhLambda2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* AvgUSsubhLambda2Dpeak_deta = (TH1D*)AvgUSsubhLambda2Dpeak->ProjectionX("AvgUSsubhLambda2Dpeak_deta", 1, AvgUSsubhLambda2Dpeak->GetYaxis()->GetNbins()); TH1D* AvgUSsubhLambda2Dpeak_dphi = (TH1D*)AvgUSsubhLambda2Dpeak->ProjectionY("AvgUSsubhLambda2Dpeak_dphi", AvgUSsubhLambda2Dpeak->GetXaxis()->FindBin(-1.2), AvgUSsubhLambda2Dpeak->GetXaxis()->FindBin(1.2)); TH2D* AvgUSsubhLambda2Dpeakleftscale = (TH2D*)hLambda2Dpeak->Clone("AvgUSsubhLambda2Dpeakleftscale"); AvgUSsubhLambda2Dpeakleftscale->Add(hLambdaBGPeakRegion, -1.0*scaleUS*leftscale/rightscale); AvgUSsubhLambda2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* AvgUSsubhLambda2Dpeakleftscale_deta = (TH1D*)AvgUSsubhLambda2Dpeakleftscale->ProjectionX("AvgUSsubhLambda2Dpeakleftscale_deta", 1, AvgUSsubhLambda2Dpeakleftscale->GetYaxis()->GetNbins()); TH1D* AvgUSsubhLambda2Dpeakleftscale_dphi = (TH1D*)AvgUSsubhLambda2Dpeakleftscale->ProjectionY("AvgUSsubhLambda2Dpeakleftscale_dphi", AvgUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(-1.2), AvgUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(1.2)); TH2D* AvgUSsubhLambda2Dpeakavgscale = (TH2D*)hLambda2Dpeak->Clone("AvgUSsubhLambda2Dpeakavgscale"); AvgUSsubhLambda2Dpeakavgscale->Add(hLambdaBGPeakRegion, -1.0*scaleUS*(leftscale + rightscale)/(2.0*rightscale)); AvgUSsubhLambda2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* AvgUSsubhLambda2Dpeakavgscale_deta = (TH1D*)AvgUSsubhLambda2Dpeakavgscale->ProjectionX("AvgUSsubhLambda2Dpeakavgscale_deta", 1, AvgUSsubhLambda2Dpeakavgscale->GetYaxis()->GetNbins()); TH1D* AvgUSsubhLambda2Dpeakavgscale_dphi = (TH1D*)AvgUSsubhLambda2Dpeakavgscale->ProjectionY("AvgUSsubhLambda2Dpeakavgscale_dphi", AvgUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(-1.2), AvgUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(1.2)); //right side US sideband tests TH2D* RSUSsubhLambda2Dpeak = (TH2D*)hLambda2Dpeak->Clone("RSUSsubhLambda2Dpeak"); RSUSsubhLambda2Dpeak->Add(hLambdaBGPeakRegionR, -1.0*scaleUS); RSUSsubhLambda2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* RSUSsubhLambda2Dpeak_deta = (TH1D*)RSUSsubhLambda2Dpeak->ProjectionX("RSUSsubhLambda2Dpeak_deta", 1, RSUSsubhLambda2Dpeak->GetYaxis()->GetNbins()); TH1D* RSUSsubhLambda2Dpeak_dphi = (TH1D*)RSUSsubhLambda2Dpeak->ProjectionY("RSUSsubhLambda2Dpeak_dphi", RSUSsubhLambda2Dpeak->GetXaxis()->FindBin(-1.2), RSUSsubhLambda2Dpeak->GetXaxis()->FindBin(1.2)); TH2D* RSUSsubhLambda2Dpeakleftscale = (TH2D*)hLambda2Dpeak->Clone("RSUSsubhLambda2Dpeakleftscale"); RSUSsubhLambda2Dpeakleftscale->Add(hLambdaBGPeakRegionR, -1.0*scaleUS*leftscale/rightscale); RSUSsubhLambda2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* RSUSsubhLambda2Dpeakleftscale_deta = (TH1D*)RSUSsubhLambda2Dpeakleftscale->ProjectionX("RSUSsubhLambda2Dpeakleftscale_deta", 1, RSUSsubhLambda2Dpeakleftscale->GetYaxis()->GetNbins()); TH1D* RSUSsubhLambda2Dpeakleftscale_dphi = (TH1D*)RSUSsubhLambda2Dpeakleftscale->ProjectionY("RSUSsubhLambda2Dpeakleftscale_dphi", RSUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(-1.2), RSUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(1.2)); // //GOTO HERE // TH2D* RSUSsubhLambda2Dpeakavgscale = (TH2D*)hLambda2Dpeak->Clone("RSUSsubhLambda2Dpeakavgscale"); // RSUSsubhLambda2Dpeakavgscale->Add(hLambdaBGPeakRegionR, -1.0*scaleUS*(leftscale+rightscale)/(2.0*rightscale)); // RSUSsubhLambda2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2); // TH1D* RSUSsubhLambda2Dpeakavgscale_deta = (TH1D*)RSUSsubhLambda2Dpeakavgscale->ProjectionX("RSUSsubhLambda2Dpeakavgscale_deta", 1, RSUSsubhLambda2Dpeakavgscale->GetYaxis()->GetNbins()); // TH1D* RSUSsubhLambda2Dpeakavgscale_dphi = (TH1D*)RSUSsubhLambda2Dpeakavgscale->ProjectionY("RSUSsubhLambda2Dpeakavgscale_dphi", RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(1.2)); // //END GOTO double signalOverTotalArray[3] = {0.3620, 0.4584, 0.5214}; // have to change this for each multiplicity bin double scaleFactorArray[3] = {0.731, 0.706, 0.735}; // have to change this for each multiplicity bin and for each method... TH2D* RSUSsubhLambda2Dpeakavgscale = (TH2D*)hLambda2Dpeak->Clone("RSUSsubhLambda2Dpeakavgscale"); // Using BG = TOTAL - SIGNAL = TOTAL(1-S/TOTAL) double bgIntegral = RSUSsubhLambda2Dpeakavgscale->Integral(RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(1.2), 1, RSUSsubhLambda2Dpeakavgscale->GetYaxis()->GetNbins())*(1 - signalOverTotalArray[2]); RSUSsubhLambda2Dpeakavgscale->Add(hLambdaBGPeakRegionR, -1.0*bgIntegral); RSUSsubhLambda2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* RSUSsubhLambda2Dpeakavgscale_deta = (TH1D*)RSUSsubhLambda2Dpeakavgscale->ProjectionX("RSUSsubhLambda2Dpeakavgscale_deta", 1, RSUSsubhLambda2Dpeakavgscale->GetYaxis()->GetNbins()); TH1D* RSUSsubhLambda2Dpeakavgscale_dphi = (TH1D*)RSUSsubhLambda2Dpeakavgscale->ProjectionY("RSUSsubhLambda2Dpeakavgscale_dphi", RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(1.2)); //left side US sideband tests TH2D* LSUSsubhLambda2Dpeak = (TH2D*)hLambda2Dpeak->Clone("LSUSsubhLambda2Dpeak"); LSUSsubhLambda2Dpeak->Add(hLambdaBGPeakRegionL, -1.0*scaleUS); LSUSsubhLambda2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* LSUSsubhLambda2Dpeak_deta = (TH1D*)LSUSsubhLambda2Dpeak->ProjectionX("LSUSsubhLambda2Dpeak_deta", 1, LSUSsubhLambda2Dpeak->GetYaxis()->GetNbins()); TH1D* LSUSsubhLambda2Dpeak_dphi = (TH1D*)LSUSsubhLambda2Dpeak->ProjectionY("LSUSsubhLambda2Dpeak_dphi", LSUSsubhLambda2Dpeak->GetXaxis()->FindBin(-1.2), LSUSsubhLambda2Dpeak->GetXaxis()->FindBin(1.2)); TH2D* LSUSsubhLambda2Dpeakleftscale = (TH2D*)hLambda2Dpeak->Clone("LSUSsubhLambda2Dpeakleftscale"); LSUSsubhLambda2Dpeakleftscale->Add(hLambdaBGPeakRegionL, -1.0*scaleUS*leftscale/rightscale); LSUSsubhLambda2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* LSUSsubhLambda2Dpeakleftscale_deta = (TH1D*)LSUSsubhLambda2Dpeakleftscale->ProjectionX("LSUSsubhLambda2Dpeakleftscale_deta", 1, LSUSsubhLambda2Dpeakleftscale->GetYaxis()->GetNbins()); TH1D* LSUSsubhLambda2Dpeakleftscale_dphi = (TH1D*)LSUSsubhLambda2Dpeakleftscale->ProjectionY("LSUSsubhLambda2Dpeakleftscale_dphi", LSUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(-1.2), LSUSsubhLambda2Dpeakleftscale->GetXaxis()->FindBin(1.2)); TH2D* LSUSsubhLambda2Dpeakavgscale = (TH2D*)hLambda2Dpeak->Clone("LSUSsubhLambda2Dpeakavgscale"); LSUSsubhLambda2Dpeakavgscale->Add(hLambdaBGPeakRegionL, -1.0*scaleUS*(leftscale+rightscale)/(2.0*rightscale)); LSUSsubhLambda2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* LSUSsubhLambda2Dpeakavgscale_deta = (TH1D*)LSUSsubhLambda2Dpeakavgscale->ProjectionX("LSUSsubhLambda2Dpeakavgscale_deta", 1, LSUSsubhLambda2Dpeakavgscale->GetYaxis()->GetNbins()); TH1D* LSUSsubhLambda2Dpeakavgscale_dphi = (TH1D*)LSUSsubhLambda2Dpeakavgscale->ProjectionY("LSUSsubhLambda2Dpeakavgscale_dphi", LSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(-1.2), LSUSsubhLambda2Dpeakavgscale->GetXaxis()->FindBin(1.2)); TH2D* resUSvsLS = (TH2D*)AvgUSsubhLambda2Dpeak->Clone("resUSvsLS"); resUSvsLS->Add(RLSsubhLambda2Dpeak, -1.0); resUSvsLS->Divide(AvgUSsubhLambda2Dpeak); resUSvsLS->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resUSvsLS_deta = (TH1D*)AvgUSsubhLambda2Dpeak_deta->Clone("resUSvsLS_deta"); resUSvsLS_deta->Add(RLSsubhLambda2Dpeak_deta, -1.0); resUSvsLS_deta->Divide(AvgUSsubhLambda2Dpeak_deta); resUSvsLS_deta->GetXaxis()->SetRangeUser(-1.2, 1.2); TH1D* resUSvsLS_dphi = (TH1D*)AvgUSsubhLambda2Dpeak_dphi->Clone("resUSvsLS_dphi"); resUSvsLS_dphi->Add(RLSsubhLambda2Dpeak_dphi, -1.0); resUSvsLS_dphi->Divide(AvgUSsubhLambda2Dpeak_dphi); TFile* output = new TFile(Form("US_syst_%s", inputFile.c_str()), "RECREATE"); LLSsubhLambda2DLside->Write(); LLSsubhLambda2DLside_deta->Write(); LLSsubhLambda2DLside_dphi->Write(); LLSsubhLambda2Dpeak->Write(); RLSsubhLambda2DRside->Write(); RLSsubhLambda2DRside_deta->Write(); RLSsubhLambda2DRside_dphi->Write(); RLSsubhLambda2Dpeak->Write(); RLSsubhLambda2Dpeak_deta->Write(); RLSsubhLambda2Dpeak_dphi->Write(); rebinRLSsubhLambda2Dpeak->Write(); scales->Write(); hLambda2Dpeak->Write(); hLambdaBGPeakRegionL->Write(); hLambdaBGPeakRegionL_deta->Write(); hLambdaBGPeakRegionL_dphi->Write(); hLambdaBGPeakRegionR->Write(); hLambdaBGPeakRegionR_deta->Write(); hLambdaBGPeakRegionR_dphi->Write(); hLambdaBGPeakRegion->Write(); hLambdaBGPeakRegion_deta->Write(); hLambdaBGPeakRegion_dphi->Write(); resLeftVsAvg->Write(); resLeftVsAvg_deta->Write(); resLeftVsAvg_dphi->Write(); resRightVsAvg->Write(); resRightVsAvg_deta->Write(); resRightVsAvg_dphi->Write(); AvgUSsubhLambda2Dpeak->Write(); AvgUSsubhLambda2Dpeak_deta->Write(); AvgUSsubhLambda2Dpeak_dphi->Write(); AvgUSsubhLambda2Dpeakleftscale->Write(); AvgUSsubhLambda2Dpeakleftscale_deta->Write(); AvgUSsubhLambda2Dpeakleftscale_dphi->Write(); AvgUSsubhLambda2Dpeakavgscale->Write(); AvgUSsubhLambda2Dpeakavgscale_deta->Write(); AvgUSsubhLambda2Dpeakavgscale_dphi->Write(); RSUSsubhLambda2Dpeak->Write(); RSUSsubhLambda2Dpeak_deta->Write(); RSUSsubhLambda2Dpeak_dphi->Write(); RSUSsubhLambda2Dpeakleftscale->Write(); RSUSsubhLambda2Dpeakleftscale_deta->Write(); RSUSsubhLambda2Dpeakleftscale_dphi->Write(); RSUSsubhLambda2Dpeakavgscale->Write(); RSUSsubhLambda2Dpeakavgscale_deta->Write(); RSUSsubhLambda2Dpeakavgscale_dphi->Write(); LSUSsubhLambda2Dpeak->Write(); LSUSsubhLambda2Dpeak_deta->Write(); LSUSsubhLambda2Dpeak_dphi->Write(); LSUSsubhLambda2Dpeakleftscale->Write(); LSUSsubhLambda2Dpeakleftscale_deta->Write(); LSUSsubhLambda2Dpeakleftscale_dphi->Write(); LSUSsubhLambda2Dpeakavgscale->Write(); LSUSsubhLambda2Dpeakavgscale_deta->Write(); LSUSsubhLambda2Dpeakavgscale_dphi->Write(); resUSvsLS->Write(); resUSvsLS_deta->Write(); resUSvsLS_dphi->Write(); }
6f7c2aade884970aa0e9601e01eb55ca1c6c14ac
c32b19fc3f7d9ab74d57c3df2a3060e46f4a3599
/src/app/Toolbar.h
3d0ac8050ce52e97d7b691de465b393e6c3995d7
[ "MIT", "BSD-3-Clause" ]
permissive
jarllarsson/loppan
c364e3ae776ae55f84e7f3c8d7fc21570647086c
64676c950facfedd88b4b5fbc589610251fb0c2b
refs/heads/master
2020-07-26T06:05:49.515730
2015-04-25T16:29:54
2015-04-25T16:29:54
34,569,995
0
0
null
null
null
null
UTF-8
C++
false
false
2,675
h
Toolbar.h
#pragma once #include <windows.h> #include <string> #include <vector> #include <AntTweakBar.h> #include <ColorPalettes.h> #include <IContextProcessable.h> // ======================================================================================= // Toolbar // ======================================================================================= ///--------------------------------------------------------------------------------------- /// \brief Wrapper for AntTweakBar /// /// # Toolbar /// /// 18-6-2014 Jarl Larsson ///--------------------------------------------------------------------------------------- class Toolbar : public IContextProcessable { public: class Bar { public: Bar(const std::string& p_name) { m_name = p_name; m_bar = TwNewBar(m_name.c_str()); } ~Bar() { //delete m_bar; } std::string m_name; TwBar* m_bar; }; enum BarType { PLAYER, PERFORMANCE, CHARACTER }; enum VarType { FLOAT = TwType::TW_TYPE_FLOAT, DOUBLE = TwType::TW_TYPE_DOUBLE, BOOL = TwType::TW_TYPE_BOOLCPP, INT = TwType::TW_TYPE_INT32, UNSIGNED_INT = TwType::TW_TYPE_UINT32, SHORT = TwType::TW_TYPE_INT16, UNSIGNED_SHORT = TwType::TW_TYPE_UINT16, DIR = TwType::TW_TYPE_DIR3F, QUAT = TwType::TW_TYPE_QUAT4F, COL_RGB = TwType::TW_TYPE_COLOR3F, COL_RGBA = TwType::TW_TYPE_COLOR4F, STRING = TwType::TW_TYPE_STDSTRING }; Toolbar(void* p_device); virtual ~Toolbar(); void init(); virtual bool processEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void setWindowSize(int p_width, int p_height); void draw(); void addReadOnlyVariable(BarType p_barType, const char* p_name, VarType p_type, const void *p_var, const char* p_misc=""); void addReadWriteVariable(BarType p_barType, const char* p_name, VarType p_type, void *p_var, const char* p_misc = ""); void addSeparator(BarType p_barType, const char* p_name, const char* p_misc = ""); void addButton(BarType p_barType, const char* p_name, TwButtonCallback p_callback, void *p_inputData, const char* p_misc = ""); void addLabel(BarType p_barType, const char* p_name, const char* p_misc=""); void clearBar(BarType p_barType); void defineBarParams(BarType p_type, const char* p_params); void defineBarParams(BarType p_type, float p_min, float p_max, float p_stepSz, const char* p_params); void defineBarParams(BarType p_type, int p_min, int p_max, const char* p_params); void defineBarParams(BarType p_type, const Color3f& p_color, const char* p_params); TwBar* getBar(BarType p_type); protected: private: std::vector<Bar> m_bars; }; void TW_CALL boolButton(void* p_bool);
4810e4efe8ea6e7c7c82e2f40b8dae97f6aea0fa
14ff708f2e64be57425a36a47ce4c90c582f79f6
/src/terrain/point.h
68d2277d424e4d0a28fe1de660e974285db9b60c
[]
no_license
sachabest/mini-minecraft
9904ee0047638270d67ccd95cb31d73588cab9b9
d2fc2961e10ca9f4ce2b09d8989bf721a5a07926
refs/heads/master
2021-03-24T12:48:59.509798
2016-04-29T02:49:32
2016-04-29T02:49:32
55,613,019
0
0
null
null
null
null
UTF-8
C++
false
false
175
h
point.h
#ifndef POINT_H #define POINT_H class Point { public: Point(float x, float y); bool operator<(const Point &p) const; float x; float y; }; #endif // POINT_H
384f5272344d767a0e50c25419dd1d822d150708
336808e58978077d8c86b661c331d83dad689ad0
/DAout/examples/AnalogToHeadphone/AnalogToHeadphone.ino
db5bd7e8451851222a6bca2386a3aba6f2024876
[ "BSD-3-Clause" ]
permissive
FyberLabs/FlexModules_Arduino
f39eed54babf187c8e0a996cf63b396a2d229226
092e7faad3013cb887baebc7a257df0de80273d5
refs/heads/master
2021-01-23T20:13:02.766495
2015-11-12T08:21:05
2015-11-12T08:21:05
34,784,792
5
0
null
null
null
null
UTF-8
C++
false
false
3,010
ino
AnalogToHeadphone.ino
/**************************************************************************************** This is a library for the Fyber Labs DAout Flex Module AnalogToHeadphone Copyright (c) 2015 Fyber Labs Inc. 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. *****************************************************************************************/ // Enables headphone output only from analog input // Based on usage examples in http://www.ti.com/lit/ug/slau456/slau456.pdf // //Example Register Setup to Play AINL and AINR Through Headphone Output // I2C Script to Setup the device in Playback Mode // This script set AINL and AINR inputs routed to only HP Driver // Key: w 30 XX YY ==> write to I2C address 0x30, to register 0xXX, data 0xYY #include "FyberLabs_TAS2521.h" using namespace TAS2521; setup() { FyberLabs_TAS2521 DAout; // Assert Software reset (P0, R1, D0=1) DAout.begin(); // LDO output programmed as 1.8V and Level shifters powered up. (P1, R2, D5-D4=00, D3=0) DAout.setLDOControl(LDO_1_8V); // Master Reference Powered on (P1, R1, D4=1) DAout.setMasterReferencePowerUp(); // Enable AINL and AINR (P1, R9, D1-D0=11) w 30 09 03 DAout.setAINLInputOn(); DAout.setAINRInputOn(); // AINL/R to HP driver not via Mixer P (P1, R12, D1-D0=11) w 30 0C 03 DAout.setHPOUTAINLAttenuator(); DAout.setHPOUTAINRAttenuator(); // HP Volume, 0dB Gain (P1, R22, D6-D0=0000000) W 30 16 00 DAout.setHPOUTVolume(0); // Not enable HP Out Mixer, AINL Volume, 0dB Gain (P1, R24, D7=0, D6-D0=0000000) // W 30 18 00 DAout.setAINLRMixerPandMixerMForceOff(); DAout.setAINLVolume(0x00); // Enable AINL and AINR and Power up HP (P1, R9, D5=1, D1-D0=11) w 30 09 23 DAout.setOutputHPLPowerUp(); DAout.setAINLInputOn(); DAout.setAINRInputOn(); // Unmute HP with 0dB gain (P1, R16, D4=1) w 30 10 00 DAout.setHPOUTDriverGain(0x00); DAout.setHPOUTDriverUnmuted(); } loop() { }
42fadbdbe99eea60451fef86339d0b525444d6b8
5d9f2abf62c6b542ad7932bed9b3f1ca2d707160
/main.cpp
2a3293d31c4fd80812bab64fbda42d12ba88f5d8
[]
no_license
Thening/dessin-en-Abymes
613407260968bfee4cd5420f1ad34cc183fda7e0
b88ef46e588ffd84d5e1ce6d6c11745299179ce4
refs/heads/master
2020-03-29T11:45:52.574898
2018-09-22T11:09:52
2018-09-22T11:09:52
149,869,478
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,534
cpp
main.cpp
#include <stdlib.h> #include <stdio.h> #include <SDL/SDL.h> #define nbcare 3 #define c 400 SDL_Surface *affichage; void echangerEntiers(int* x, int* y) { int t = *x; *x = *y; *y = t; } void setPixel(int x, int y, Uint8 coul) { *((Uint32*)(affichage->pixels) + x + y * affichage->w) = coul; } void setPixelVerif(int x, int y, Uint32 coul) { if (x >= 0 && x < affichage->w && y >= 0 && y < affichage->h) setPixel(x, y, coul); } void lines(int x1, int y1, int x2, int y2, Uint32 coul) { int d, dx, dy, aincr, bincr, xincr, yincr, x, y; if (abs(x2 - x1) < abs(y2 - y1)) { /* parcours par l'axe vertical */ if (y1 > y2) { echangerEntiers(&x1, &x2); echangerEntiers(&y1, &y2); } xincr = x2 > x1 ? 1 : -1; dy = y2 - y1; dx = abs(x2 - x1); d = 2 * dx - dy; aincr = 2 * (dx - dy); bincr = 2 * dx; x = x1; y = y1; setPixelVerif(x, y, coul); for (y = y1+1; y <= y2; ++y) { if (d >= 0) { x += xincr; d += aincr; } else d += bincr; setPixelVerif(x, y, coul); } } else { /* parcours par l'axe horizontal */ if (x1 > x2) { echangerEntiers(&x1, &x2); echangerEntiers(&y1, &y2); } yincr = y2 > y1 ? 1 : -1; dx = x2 - x1; dy = abs(y2 - y1); d = 2 * dy - dx; aincr = 2 * (dy - dx); bincr = 2 * dy; x = x1; y = y1; setPixelVerif(x, y, coul); for (x = x1+1; x <= x2; ++x) { if (d >= 0) { y += yincr; d += aincr; } else d += bincr; setPixelVerif(x, y, coul); } } SDL_Delay(1000); SDL_Flip(affichage); } void Dessin(int a,int o,int cote,int n) { lines(a,o,a+cote/2,o,SDL_MapRGB(affichage->format, 13,43,76)); lines(a+cote/2,o,a+cote/4,o+cote/4,SDL_MapRGB(affichage->format, 255,255,255)); if(n>1) { Dessin(a+cote/4,o+cote/4,cote/2,n-1); } lines(a+cote/4,o+cote/4,a,o+cote/2,SDL_MapRGB(affichage->format, 255,255,255)); lines(a,o+cote/2,a+cote/2,o+cote,SDL_MapRGB(affichage->format, 255,255,255)); lines(a+cote/2,o+cote,a+cote,o+cote/2,SDL_MapRGB(affichage->format, 255,255,255)); lines(a+cote,o+cote/2,a+cote/2,o,SDL_MapRGB(affichage->format, 255,255,255)); lines(a+cote/2,o,a+cote,o,SDL_MapRGB(affichage->format, 13,43,76)); lines(a+cote,o,a+cote,o+cote,SDL_MapRGB(affichage->format, 13,43,76)); lines(a+cote,o+cote,a,o+cote,SDL_MapRGB(affichage->format, 13,43,76)); lines(a,o+cote,a,o,SDL_MapRGB(affichage->format, 13,43,76)); } void initSDL(void) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Erreur à l'initialisation de la SDL : %s\n", SDL_GetError()); exit(EXIT_FAILURE); } atexit(SDL_Quit); affichage = SDL_SetVideoMode(600, 600, 32, SDL_SWSURFACE); if (affichage == NULL) { fprintf(stderr, "Impossible d'activer le mode graphique : %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_WM_SetCaption("Dessin en abymes", NULL); } void pause() { int continuer = 1; SDL_Event event; while (continuer) { SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: continuer = 0; } } } int main(int argc, char *argv[]) { int a=100; int o=100; initSDL(); // SDL_Init(SDL_INIT_VIDEO); // SDL_FillRect(affichage, NULL, SDL_MapRGB(affichage->format, 0,0,0)); Dessin(a,o,c,nbcare); SDL_Flip(affichage); pause(); SDL_FreeSurface(affichage); SDL_Quit(); return EXIT_SUCCESS; }
3ce924c72879032c9fa1e094b9983fe8c228fa86
b4cb3760b0b96e9093106e2ea646d8459f4ce1f6
/quickSort.cpp
79f99f56962dc2daaa0e5d1cfc9378d461619097
[]
no_license
ngoquanghuy99/C-CPP-problems-and-solutions
461526ab9ec2cafa280031f94720a87926793539
ca3e06be1c84ca9b7ad09f7464be71020defd223
refs/heads/master
2022-11-06T14:43:07.800730
2020-06-16T12:16:32
2020-06-16T12:16:32
135,458,944
3
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
quickSort.cpp
#include<iostream> #include<conio.h> using namespace std; int n = 11; int arr[] = {5,9,4,12,10,444,345,958,2,4,3}; void quicksort(int* arr, int leftIndex, int rightIndex){ int i = leftIndex; int j= rightIndex; int pivot = arr[(leftIndex + rightIndex)/2]; while(i<=j){ while(arr[i] < pivot) i++; while(arr[j]> pivot) j--; if(i<=j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++;j--; } if(i<rightIndex) quicksort(arr,i,rightIndex); if(j>leftIndex) quicksort(arr,leftIndex,j); } } int main(){ quicksort(arr,0,10); freopen("QUICKSORT.OUT","w",stdout); for(int i=0;i<11;i++){ cout<<arr[i]<<" "; } return 0; }
d33d946327690442304b31d8e059fafc8256e58e
646cbe14cce0578da42cdc79c6467108ce3e5753
/board.cpp
cf3091db9a23fcc45f59247de8861b6e7902539d
[]
no_license
jeffreyan11/go-engine
16484c79e52597038762791e5d9672716250b5d7
02ec4782c0570ecf077a8bd513c0d4501ac6655c
refs/heads/master
2021-01-21T13:56:51.435086
2016-06-02T07:14:39
2016-06-02T07:14:39
50,217,190
4
0
null
null
null
null
UTF-8
C++
false
false
36,032
cpp
board.cpp
#include <iostream> #include <random> #include "board.h" int boardSize = 19; int arraySize = 21; // Zobrist hashing table, initialized at startup // 2 * 25 * 25 = 1250 entries, 2 per color for a max 25 x 25 board static uint64_t zobristTable[1250]; void initZobristTable() { std::mt19937_64 rng (74623982906748ULL); for (int i = 0; i < 1250; i++) zobristTable[i] = rng(); } // Returns an array index for the pieces array given the coordinates for a // move (x, y). inline int index(int x, int y) { return x + y * arraySize; } // Returns an indexing to the zobrist table. inline int zobristIndex(Player p, int x, int y) { return (p-1) + 2 * (x-1) + 2 * (y-1) * boardSize; } Board::Board() { init(); } Board::Board(const Board &other) { pieces = new Stone[arraySize*arraySize]; for (int i = 0; i < arraySize*arraySize; i++) { pieces[i] = other.pieces[i]; } blackCaptures = other.blackCaptures; whiteCaptures = other.whiteCaptures; zobristKey = other.zobristKey; nextID = other.nextID; chainID = new int[arraySize*arraySize]; for (int i = 0; i < arraySize*arraySize; i++) chainID[i] = other.chainID[i]; unsigned int numChains = other.chainList.size(); for (unsigned int i = 0; i < numChains; i++) { Chain *node = other.chainList.get(i); chainList.add(new Chain(*(node))); } } Board::~Board() { deinit(); } //------------------------------------------------------------------------------ //------------------------Move Generation and Handling-------------------------- //------------------------------------------------------------------------------ /* * Updates the board with a move. Assumes that the move is legal. */ void Board::doMove(Player p, Move m) { if (m == MOVE_PASS) return; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] == EMPTY); assert(chainID[index(x, y)] == 0); pieces[index(x, y)] = p; zobristKey ^= zobristTable[zobristIndex(p, x, y)]; Player victim = otherPlayer(p); Stone east = pieces[index(x+1, y)]; Stone west = pieces[index(x-1, y)]; Stone north = pieces[index(x, y+1)]; Stone south = pieces[index(x, y-1)]; int connectionCount = (east == p) + (west == p) + (north == p) + (south == p); // If the stone placed is a new chain if (connectionCount == 0) { // Record which chain this square is a part of chainID[index(x, y)] = nextID; // Add this chain to the list of chains Chain *cargo = new Chain(p, nextID); cargo->add(m); cargo->liberties = 0; if (east == EMPTY) cargo->addLiberty(coordToMove(x+1, y)); if (west == EMPTY) cargo->addLiberty(coordToMove(x-1, y)); if (north == EMPTY) cargo->addLiberty(coordToMove(x, y+1)); if (south == EMPTY) cargo->addLiberty(coordToMove(x, y-1)); chainList.add(cargo); nextID++; } // If the stone placed is added to an existing chain else if (connectionCount == 1) { // Find the ID of the chain we are adding this stone to int thisID; if (east == p) thisID = chainID[index(x+1, y)]; else if (west == p) thisID = chainID[index(x-1, y)]; else if (north == p) thisID = chainID[index(x, y+1)]; else thisID = chainID[index(x, y-1)]; chainID[index(x, y)] = thisID; Chain *node = nullptr; searchChainsByID(node, thisID); node->add(m); // The new stone occupies a previous liberty, but adds on however many // liberties it itself has node->removeLiberty(node->findLiberty(m)); updateLiberty(node, x, y); } // If the stone possibly connects two existing chains else { int eastID = (east == p) * chainID[index(x+1, y)]; int westID = (west == p) * chainID[index(x-1, y)]; int northID = (north == p) * chainID[index(x, y+1)]; int southID = (south == p) * chainID[index(x, y-1)]; Chain *node = nullptr; bool added = false; if (eastID) { chainID[index(x, y)] = eastID; searchChainsByID(node, eastID); node->add(m); node->removeLiberty(node->findLiberty(m)); updateLiberty(node, x, y); added = true; } if (westID) { if (added) { // If two stones from the same chain are adjacent, do nothing // If they are from different chains, we need to combine... if (westID != eastID) mergeChains(node, westID, m); } else { chainID[index(x, y)] = westID; searchChainsByID(node, westID); node->add(m); node->removeLiberty(node->findLiberty(m)); updateLiberty(node, x, y); added = true; } } if (northID) { if (added) { if (northID != eastID && northID != westID) mergeChains(node, northID, m); } else { chainID[index(x, y)] = northID; searchChainsByID(node, northID); node->add(m); node->removeLiberty(node->findLiberty(m)); updateLiberty(node, x, y); added = true; } } if (southID) { if (added) { if (southID != eastID && southID != westID && southID != northID) mergeChains(node, southID, m); } else { chainID[index(x, y)] = southID; searchChainsByID(node, southID); node->add(m); node->removeLiberty(node->findLiberty(m)); updateLiberty(node, x, y); added = true; } } } // Update opponent liberties int eastID = (east == victim) * chainID[index(x+1, y)]; int westID = (west == victim) * chainID[index(x-1, y)]; int northID = (north == victim) * chainID[index(x, y+1)]; int southID = (south == victim) * chainID[index(x, y-1)]; if (eastID) { Chain *node = nullptr; int nodeIndex = searchChainsByID(node, eastID); node->removeLiberty(node->findLiberty(m)); if (node->liberties == 0) captureChain(node, nodeIndex); } if (westID && westID != eastID) { Chain *node = nullptr; int nodeIndex = searchChainsByID(node, westID); node->removeLiberty(node->findLiberty(m)); if (node->liberties == 0) captureChain(node, nodeIndex); } if (northID && northID != eastID && northID != westID) { Chain *node = nullptr; int nodeIndex = searchChainsByID(node, northID); node->removeLiberty(node->findLiberty(m)); if (node->liberties == 0) captureChain(node, nodeIndex); } if (southID && southID != eastID && southID != westID && southID != northID) { Chain *node = nullptr; int nodeIndex = searchChainsByID(node, southID); node->removeLiberty(node->findLiberty(m)); if (node->liberties == 0) captureChain(node, nodeIndex); } // Check for a suicide int selfID = chainID[index(x, y)]; Chain *node = nullptr; int nodeIndex = searchChainsByID(node, selfID); if (node->liberties == 0) captureChain(node, nodeIndex); // A debugging check assert(!checkChains()); // Check if p captured any of the other player's stones with move m /* doCaptures<true>(victim, coordToMove(x+1, y)); doCaptures<true>(victim, coordToMove(x-1, y)); doCaptures<true>(victim, coordToMove(x, y+1)); doCaptures<true>(victim, coordToMove(x, y-1)); // Check if p suicided with move m doCaptures<true>(p, coordToMove(x, y)); */ } bool Board::isMoveValid(Player p, Move m) { if (m == MOVE_PASS) return true; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] == EMPTY); // First check if the move makes a capture, since if so then // it cannot possibly be a suicide Player victim = otherPlayer(p); int eastID = (pieces[index(x+1, y)] == victim) * chainID[index(x+1, y)]; int westID = (pieces[index(x-1, y)] == victim) * chainID[index(x-1, y)]; int northID = (pieces[index(x, y+1)] == victim) * chainID[index(x, y+1)]; int southID = (pieces[index(x, y-1)] == victim) * chainID[index(x, y-1)]; if (eastID) { Chain *node = nullptr; searchChainsByID(node, eastID); if (node->liberties == 1) return true; } if (westID) { Chain *node = nullptr; searchChainsByID(node, westID); if (node->liberties == 1) return true; } if (northID) { Chain *node = nullptr; searchChainsByID(node, northID); if (node->liberties == 1) return true; } if (southID) { Chain *node = nullptr; searchChainsByID(node, southID); if (node->liberties == 1) return true; } if (isEye(victim, m)) return false; pieces[index(x, y)] = p; // Suicides are illegal if (pieces[index(x+1, y)] && pieces[index(x-1, y)] && pieces[index(x, y+1)] && pieces[index(x, y-1)]) { if (doCaptures<false>(p, coordToMove(x, y))) { pieces[index(x, y)] = EMPTY; return false; } } pieces[index(x, y)] = EMPTY; return true; } /* * Returns a list of every possible legal move in the current board state. * This function does not account for suicides and ko rule. */ MoveList Board::getLegalMoves(Player p) { MoveList result; for (int j = 1; j <= boardSize; j++) { for (int i = 1; i <= boardSize; i++) { // All empty squares are legal moves if (pieces[index(i, j)] == EMPTY) result.add(coordToMove(i, j)); } } return result; } //------------------------------------------------------------------------------ //---------------------------Chain Update Algorithms---------------------------- //------------------------------------------------------------------------------ // Finds the pointer to the Chain struct with the given id, and returns the // index of that pointer in chainList. inline int Board::searchChainsByID(Chain *&node, int id) { for (unsigned int i = 0; i < chainList.size(); i++) { if (chainList.get(i)->id == id) { node = chainList.get(i); return i; } } return -1; } // Updates liberties of a chain after a single stone has been added to the chain void Board::updateLiberty(Chain *node, int x, int y) { Stone east = pieces[index(x+1, y)]; Stone west = pieces[index(x-1, y)]; Stone north = pieces[index(x, y+1)]; Stone south = pieces[index(x, y-1)]; // If the square is empty and not already a liberty of the chain if (east == EMPTY && node->findLiberty(coordToMove(x+1, y)) == -1) node->addLiberty(coordToMove(x+1, y)); if (west == EMPTY && node->findLiberty(coordToMove(x-1, y)) == -1) node->addLiberty(coordToMove(x-1, y)); if (north == EMPTY && node->findLiberty(coordToMove(x, y+1)) == -1) node->addLiberty(coordToMove(x, y+1)); if (south == EMPTY && node->findLiberty(coordToMove(x, y-1)) == -1) node->addLiberty(coordToMove(x, y-1)); } // Merges two chains void Board::mergeChains(Chain *node, int otherID, Move m) { // Find the chain to merge into the first chain Chain *temp = nullptr; int tempIndex = searchChainsByID(temp, otherID); // Update the chain id array when merging for (int i = 0; i < temp->size; i++) { Move idChange = temp->squares[i]; chainID[index(getX(idChange), getY(idChange))] = node->id; node->add(idChange); } // Remove the move played from the other list of liberties temp->removeLiberty(temp->findLiberty(m)); // And then merge the two lists for (int i = 0; i < temp->liberties; i++) { // If the liberty is not a repeat if (node->findLiberty(temp->libertyList[i]) == -1) node->addLiberty(temp->libertyList[i]); } // Delete the chain "temp" now since it has been fully merged in delete temp; chainList.removeFast(tempIndex); } // Performs a capture on a chain and updates the board, adjacent liberties, etc. // To be called on a chain that has no liberties void Board::captureChain(Chain *node, int nodeIndex) { Player victim = node->color; if (victim == BLACK) whiteCaptures += node->size; else blackCaptures += node->size; for (int i = 0; i < node->size; i++) { int rx = getX(node->squares[i]); int ry = getY(node->squares[i]); pieces[index(rx, ry)] = EMPTY; chainID[index(rx, ry)] = 0; zobristKey ^= zobristTable[zobristIndex(node->color, rx, ry)]; // Add this square to adjacent chains' liberties int addID = chainID[index(rx+1, ry)]; if (addID && addID != node->id) { Chain *temp = nullptr; searchChainsByID(temp, addID); if (temp->findLiberty(coordToMove(rx, ry)) == -1) temp->addLiberty(coordToMove(rx, ry)); } addID = chainID[index(rx-1, ry)]; if (addID && addID != node->id && addID != chainID[index(rx+1, ry)]) { Chain *temp = nullptr; searchChainsByID(temp, addID); if (temp->findLiberty(coordToMove(rx, ry)) == -1) temp->addLiberty(coordToMove(rx, ry)); } addID = chainID[index(rx, ry+1)]; if (addID && addID != node->id && addID != chainID[index(rx+1, ry)] && addID != chainID[index(rx-1, ry)]) { Chain *temp = nullptr; searchChainsByID(temp, addID); if (temp->findLiberty(coordToMove(rx, ry)) == -1) temp->addLiberty(coordToMove(rx, ry)); } addID = chainID[index(rx, ry-1)]; if (addID && addID != node->id && addID != chainID[index(rx+1, ry)] && addID != chainID[index(rx-1, ry)] && addID != chainID[index(rx, ry+1)]) { Chain *temp = nullptr; searchChainsByID(temp, addID); if (temp->findLiberty(coordToMove(rx, ry)) == -1) temp->addLiberty(coordToMove(rx, ry)); } } // Remove this chain since it has been captured delete node; chainList.removeFast(nodeIndex); } // For debugging // Checks that the chains in chainList are consistent with the pieces and // chainID arrays bool Board::checkChains() { bool result = false; int *temp = new int[arraySize*arraySize]; int *tempPieces = new int[arraySize*arraySize]; for (int i = 0; i < arraySize*arraySize; i++) temp[i] = chainID[i]; for (int i = 0; i < arraySize*arraySize; i++) tempPieces[i] = pieces[i]; for (unsigned int j = 0; j < chainList.size(); j++) { Chain *node = chainList.get(j); for (int i = 0; i < node->size; i++) { Move m = node->squares[i]; if (temp[index(getX(m), getY(m))] == 0 || tempPieces[index(getX(m), getY(m))] == 0) { result = true; break; } temp[index(getX(m), getY(m))] = 0; tempPieces[index(getX(m), getY(m))] = 0; } } delete[] temp; delete[] tempPieces; return result; } //------------------------------------------------------------------------------ //-------------------------Region Detection Algorithms-------------------------- //------------------------------------------------------------------------------ // Given a victim color and seed square, detects whether the square is part of // a connected group of stones of victim color that are surrounded, and performs // the capture if necessary. // Returns the number of stones captured in this region. template <bool updateBoard> int Board::doCaptures(Player victim, Move seed) { if (pieces[index(getX(seed), getY(seed))] != victim) return 0; Stone *visited = new Stone[arraySize*arraySize]; for (int i = 0; i < arraySize*arraySize; i++) { visited[i] = 0; } MoveList captured; if (isSurrounded(victim, EMPTY, getX(seed), getY(seed), visited, captured)) { if (updateBoard) { for (unsigned int i = 0; i < captured.size(); i++) { Move m = captured.get(i); pieces[index(getX(m), getY(m))] = EMPTY; zobristKey ^= zobristTable[zobristIndex(victim, getX(m), getY(m))]; } // Record how many pieces were captured for scoring purposes if (victim == BLACK) whiteCaptures += captured.size(); else blackCaptures += captured.size(); } } delete[] visited; return captured.size(); } // Given a coordinate as a move, and a victim color, recursively determines // whether the victim on this square is part of a surrounded chain // Precondition: (x, y) is of color victim bool Board::isSurrounded(Player victim, Player open, int x, int y, Stone *visited, MoveList &captured) { visited[index(x, y)] = 1; Stone east = pieces[index(x+1, y)]; // If we are next to a non-blocker and non-victim, then we are not surrounded if (east == open) return false; // If we next to victim, we need to recursively see if the entire group // is surrounded else if (east == victim && visited[index(x+1, y)] == 0) if (!isSurrounded(victim, open, x+1, y, visited, captured)) return false; // Else the piece is surrounded by a blocker or edge Stone west = pieces[index(x-1, y)]; if (west == open) return false; else if (west == victim && visited[index(x-1, y)] == 0) if (!isSurrounded(victim, open, x-1, y, visited, captured)) return false; Stone north = pieces[index(x, y+1)]; if (north == open) return false; else if (north == victim && visited[index(x, y+1)] == 0) if (!isSurrounded(victim, open, x, y+1, visited, captured)) return false; Stone south = pieces[index(x, y-1)]; if (south == open) return false; else if (south == victim && visited[index(x, y-1)] == 0) if (!isSurrounded(victim, open, x, y-1, visited, captured)) return false; // If we got here, we are surrounded on all four sides captured.add(coordToMove(x, y)); return true; } // Counts the territory each side owns void Board::countTerritory(int &whiteTerritory, int &blackTerritory) { whiteTerritory = 0; blackTerritory = 0; Stone *visited = new Stone[arraySize*arraySize]; Stone *territory = new Stone[arraySize*arraySize]; Stone *region = new Stone[arraySize*arraySize]; // Count territory for both sides for (Player p = BLACK; p <= WHITE; p++) { // Reset the visited array for (int i = 0; i < arraySize*arraySize; i++) visited[i] = 0; // Main loop for (int j = 1; j <= boardSize; j++) { for (int i = 1; i <= boardSize; i++) { // Don't recount territory if (visited[index(i, j)]) continue; // Only use empty squares as seeds if (pieces[index(i, j)]) continue; if (isEye(p, coordToMove(i, j))) { visited[index(i, j)] = 1; if (p == BLACK) blackTerritory++; else whiteTerritory++; continue; } for (int k = 0; k < arraySize*arraySize; k++) territory[k] = 0; int territorySize = 0; int boundarySize = 0; getTerritory(p, i, j, visited, territory, territorySize, boundarySize); // Check if territory was actually sectioned off if (territorySize + boundarySize == boardSize*boardSize) continue; // Detect life/death of internal stones // Initialize region to 0 if territory is 1, and vice versa // This acts as our "visited" array, so that we only explore areas // inside the territory // bool isContested = false; // for (int n = 1; n <= boardSize; n++) { // for (int m = 1; m <= boardSize; m++) { // if (!territory[index(m, n)]) // continue; // if (pieces[index(m, n)] == otherPlayer(p)) { // isContested = true; // break; // } // } // } // if (!isContested) { // if (p == BLACK) // blackTerritory += territorySize; // else // whiteTerritory += territorySize; // } for (int k = 0; k < arraySize*arraySize; k++) region[k] = territory[k] ^ 1; int internalRegions = 0; for (int n = 1; n <= boardSize; n++) { for (int m = 1; m <= boardSize; m++) { if (region[index(m, n)]) continue; if (pieces[index(m, n)]) continue; MoveList eye; if (isSurrounded(EMPTY, p, m, n, region, eye)) internalRegions++; } } int territoryCount = 0; if (internalRegions == 0) { territoryCount += territorySize; // Score dead stones for (int k = 0; k < arraySize*arraySize; k++) if (territory[k] && pieces[k] == otherPlayer(p)) territoryCount++; } if (p == BLACK) blackTerritory += territoryCount; else whiteTerritory += territoryCount; } } } delete[] visited; delete[] territory; delete[] region; } // Given a seed square, determines whether the square is part of territory owned // by color blocker. void Board::getTerritory(Player blocker, int x, int y, Stone *visited, Stone *territory, int &territorySize, int &boundarySize) { visited[index(x, y)] = 1; // Record the boundary of the region we are flood filling if (pieces[index(x, y)] == blocker) { boundarySize++; return; } Stone east = pieces[index(x+1, y)]; // Flood fill outwards if (east != -1 && visited[index(x+1, y)] == 0) getTerritory(blocker, x+1, y, visited, territory, territorySize, boundarySize); // Else we are on the edge of the board Stone west = pieces[index(x-1, y)]; if (west != -1 && visited[index(x-1, y)] == 0) getTerritory(blocker, x-1, y, visited, territory, territorySize, boundarySize); Stone north = pieces[index(x, y+1)]; if (north != -1 && visited[index(x, y+1)] == 0) getTerritory(blocker, x, y+1, visited, territory, territorySize, boundarySize); Stone south = pieces[index(x, y-1)]; if (south != -1 && visited[index(x, y-1)] == 0) getTerritory(blocker, x, y-1, visited, territory, territorySize, boundarySize); territory[index(x, y)] = 1; territorySize++; } bool Board::isEye(Player p, Move m) { if (m == MOVE_PASS) return false; int x = getX(m); int y = getY(m); if ((pieces[index(x+1, y)] == p || pieces[index(x+1, y)] == -1) && (pieces[index(x-1, y)] == p || pieces[index(x-1, y)] == -1) && (pieces[index(x, y+1)] == p || pieces[index(x, y+1)] == -1) && (pieces[index(x, y-1)] == p || pieces[index(x, y-1)] == -1)) return true; return false; } // Given the last move made, returns true if that move put an own chain // into atari bool Board::isInAtari(Move m) { if (m == MOVE_PASS) return false; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] != EMPTY); Chain *node = nullptr; searchChainsByID(node, chainID[index(x, y)]); if (node->liberties == 1) return true; return false; } // Given a square of the last move made, returns the move to capture // the chain with that square, if any. Otherwise, returns MOVE_PASS. Move Board::getPotentialCapture(Move m) { if (m == MOVE_PASS) return MOVE_PASS; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] != EMPTY); Chain *node = nullptr; searchChainsByID(node, chainID[index(x, y)]); if (node->liberties == 1) return node->libertyList[0]; return MOVE_PASS; } // Given the square of the last move made, see if any chains of // player p have been put into atari and try to escape if possible Move Board::getPotentialEscape(Player p, Move m) { if (m == MOVE_PASS) return MOVE_PASS; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] != EMPTY); if (pieces[index(x+1, y)] == p) { Chain *node = nullptr; searchChainsByID(node, chainID[index(x+1, y)]); if (node->liberties == 1) { Move esc = node->libertyList[0]; int ex = getX(esc); int ey = getY(esc); if (pieces[index(ex+1, ey)] == p && chainID[index(ex+1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex+1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex-1, ey)] == p && chainID[index(ex-1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex-1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey+1)] == p && chainID[index(ex, ey+1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey+1)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey-1)] == p && chainID[index(ex, ey-1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey-1)]); if (conn->liberties > 2) return esc; } } } if (pieces[index(x-1, y)] == p) { Chain *node = nullptr; searchChainsByID(node, chainID[index(x-1, y)]); if (node->liberties == 1) { Move esc = node->libertyList[0]; int ex = getX(esc); int ey = getY(esc); if (pieces[index(ex+1, ey)] == p && chainID[index(ex+1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex+1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex-1, ey)] == p && chainID[index(ex-1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex-1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey+1)] == p && chainID[index(ex, ey+1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey+1)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey-1)] == p && chainID[index(ex, ey-1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey-1)]); if (conn->liberties > 2) return esc; } } } if (pieces[index(x, y+1)] == p) { Chain *node = nullptr; searchChainsByID(node, chainID[index(x, y+1)]); if (node->liberties == 1) { Move esc = node->libertyList[0]; int ex = getX(esc); int ey = getY(esc); if (pieces[index(ex+1, ey)] == p && chainID[index(ex+1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex+1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex-1, ey)] == p && chainID[index(ex-1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex-1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey+1)] == p && chainID[index(ex, ey+1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey+1)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey-1)] == p && chainID[index(ex, ey-1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey-1)]); if (conn->liberties > 2) return esc; } } } if (pieces[index(x, y-1)] == p) { Chain *node = nullptr; searchChainsByID(node, chainID[index(x, y-1)]); if (node->liberties == 1) { Move esc = node->libertyList[0]; int ex = getX(esc); int ey = getY(esc); if (pieces[index(ex+1, ey)] == p && chainID[index(ex+1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex+1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex-1, ey)] == p && chainID[index(ex-1, ey)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex-1, ey)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey+1)] == p && chainID[index(ex, ey+1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey+1)]); if (conn->liberties > 2) return esc; } if (pieces[index(ex, ey-1)] == p && chainID[index(ex, ey-1)] != node->id) { Chain *conn = nullptr; searchChainsByID(conn, chainID[index(ex, ey-1)]); if (conn->liberties > 2) return esc; } } } return MOVE_PASS; } MoveList Board::getLocalMoves(Move m) { MoveList localMoves; if (m == MOVE_PASS) return localMoves; int x = getX(m); int y = getY(m); assert(pieces[index(x, y)] != EMPTY); Chain *node = nullptr; searchChainsByID(node, chainID[index(x, y)]); for (int i = 0; i < node->liberties; i++) localMoves.add(node->libertyList[i]); if (chainID[index(x+1, y)] && chainID[index(x+1, y)] != chainID[index(x, y)]) { node = nullptr; searchChainsByID(node, chainID[index(x+1, y)]); for (int i = 0; i < node->liberties; i++) localMoves.add(node->libertyList[i]); } if (chainID[index(x-1, y)] && chainID[index(x-1, y)] != chainID[index(x, y)] && chainID[index(x-1, y)] != chainID[index(x+1, y)]) { node = nullptr; searchChainsByID(node, chainID[index(x-1, y)]); for (int i = 0; i < node->liberties; i++) localMoves.add(node->libertyList[i]); } if (chainID[index(x, y+1)] && chainID[index(x, y+1)] != chainID[index(x, y)] && chainID[index(x, y+1)] != chainID[index(x+1, y)] && chainID[index(x, y+1)] != chainID[index(x-1, y)]) { node = nullptr; searchChainsByID(node, chainID[index(x, y+1)]); for (int i = 0; i < node->liberties; i++) localMoves.add(node->libertyList[i]); } if (chainID[index(x, y-1)] && chainID[index(x, y-1)] != chainID[index(x, y)] && chainID[index(x, y-1)] != chainID[index(x+1, y)] && chainID[index(x, y-1)] != chainID[index(x-1, y)] && chainID[index(x, y-1)] != chainID[index(x, y+1)]) { node = nullptr; searchChainsByID(node, chainID[index(x, y-1)]); for (int i = 0; i < node->liberties; i++) localMoves.add(node->libertyList[i]); } return localMoves; } int Board::getCapturedStones(Player p) { return (p == BLACK) ? blackCaptures : whiteCaptures; } bool Board::isEmpty() { return (chainList.size() == 0); } uint64_t Board::getZobristKey() { return zobristKey; } //------------------------------------------------------------------------------ //---------------------------Misc Utility Functions----------------------------- //------------------------------------------------------------------------------ // Initializes a board to empty void Board::init() { pieces = new Stone[arraySize*arraySize]; // Initialize the board to empty for (int i = 0; i < arraySize*arraySize; i++) pieces[i] = EMPTY; // Initialize the edges to -1 for (int i = 0; i < arraySize; i++) { pieces[index(0, i)] = -1; pieces[index(arraySize-1, i)] = -1; pieces[index(i, 0)] = -1; pieces[index(i, arraySize-1)] = -1; } blackCaptures = 0; whiteCaptures = 0; zobristKey = 0; nextID = 1; chainID = new int[arraySize*arraySize]; for (int i = 0; i < arraySize*arraySize; i++) chainID[i] = 0; } void Board::deinit() { delete[] pieces; delete[] chainID; for (unsigned int i = 0; i < chainList.size(); i++) delete chainList.get(i); chainList.clear(); } // Resets a board object completely. void Board::reset() { deinit(); init(); } // Prints a board state to terminal for debugging void Board::prettyPrint() { // Since the y axis indexing is inverted for (int j = boardSize; j >= 1; j--) { if (j >= 10) std::cout << j << " "; else std::cout << " " << j << " "; for (int i = 1; i <= boardSize; i++) { if (pieces[index(i, j)] == EMPTY) std::cout << ". "; else if (pieces[index(i, j)] == BLACK) std::cout << "B "; else std::cout << "W "; } if (j >= 10) std::cout << j << " "; else std::cout << " " << j << " "; std::cout << std::endl; } } // The same as prettyPrint, but to std:cerr void Board::errorPrint() { // Since the y axis indexing is inverted for (int j = boardSize; j >= 1; j--) { if (j >= 10) std::cerr << j << " "; else std::cerr << " " << j << " "; for (int i = 1; i <= boardSize; i++) { if (pieces[index(i, j)] == EMPTY) std::cerr << ". "; else if (pieces[index(i, j)] == BLACK) std::cerr << "B "; else std::cerr << "W "; } if (j >= 10) std::cerr << j << " "; else std::cerr << " " << j << " "; std::cerr << std::endl; } }
a4bd80e6455e721a85d6df9ed4b8f8a7f4fb7012
0421bc55fe0928ce76ab1f45fc3cdfd7f8b6a9b0
/gauntlet/C_Gold.cpp
df970bd9320c6bf8ce7cf0eb75eff853376f8c35
[]
no_license
GandhiGames/gauntlet
f3ce79cdf85468bc456f0536283a25b516408fe8
17ebe9143e2371de47d8a158971d92b4bfaeac9b
refs/heads/master
2021-01-20T11:39:15.554575
2017-09-25T12:54:30
2017-09-25T12:54:30
101,512,609
0
0
null
null
null
null
UTF-8
C++
false
false
547
cpp
C_Gold.cpp
#include "PCH.h" #include "C_Gold.h" #include "Object.h" C_Gold::C_Gold(Object* owner) : Component(owner, true) { } C_Gold::~C_Gold() { } void C_Gold::LoadDependencies(Object* owner) { m_points = owner->GetComponent<C_PointsOnPickup>(); } void C_Gold::OnCollisionEnter(Object* owner, Object* other) { if (other->m_tag->Get() == PLAYER_TAG) { other->GetComponent<C_Inventory>()->m_gold += m_points->GetValue(); //TODO: re-implement this. // Play gold collect sound effect. //PlaySound(m_coinPickupSound); owner->Destroy(); } }
549d8e75defdbc78caa8310d929798a539f69747
1c08d6013afeb2736f3b778587b7688dddde8436
/src/simulator.cpp
aaaa0254aa80dfa28656a93e4595ea00fe54b086
[]
no_license
danalmanzee/cse-network-simulator
4475a7c818220c8f91bf2f678305654b3a18df9a
3632c46226bd270ee5ae3165da4e7ea622f1d95d
refs/heads/master
2021-09-02T06:02:40.880629
2017-12-30T22:21:17
2017-12-30T22:21:17
115,826,079
0
0
null
null
null
null
UTF-8
C++
false
false
5,170
cpp
simulator.cpp
#include <iostream> #include <iomanip> #include <fstream> #include "buffer.hpp" #include "generator.hpp" #include "router.hpp" #include "server.hpp" #include "simulator.hpp" using namespace std; using NodeCreateFunc = Simulator::NodeCreateFunc; Simulator::Simulator() : _next_client(0), _next_event(0) { // Register types. _creators = { {"Poisson", _make_generic_generator_creator<Poisson>()}, {"FIFO", _make_generic_creator<FIFO>()}, {"ServerCst", _make_generic_creator<ServerCst>()}, {"ServerNormal", _make_generic_creator<ServerNormal>()}, {"ServerExp", _make_generic_creator<ServerExp>()}, {"Dispatch", _make_generic_creator<Dispatch>()}, {"Exit", _make_generic_creator<ServerExit>()} }; // Fallback names and types. _names.insert(std::make_pair(nullptr, "?")); _types.insert(std::make_pair(nullptr, "?")); } void Simulator::read(const char *fn) { ifstream file(fn); string line; while (getline(file, line)) { const char *s = line.c_str(); string name(1, *s++); char op = *s++; if (op == '=') create_node(name, s); else if (op == '-' && *s++ == '>') direct_node(name, s); else cerr << "Unknown line: " << line << endl; } } void Simulator::create_node(const std::string &name, const std::string &type) { size_t ppos = type.find('('); size_t endpos = type.rfind(')'); string tname = type.substr(0, ppos); string targs = (ppos < endpos) ? type.substr(ppos + 1, (endpos - ppos) - 1) : ""; auto it = _creators.find(tname); if (it != _creators.end()) { auto node = it->second(targs); _nodes.insert(std::make_pair(name, node)); _names.insert(std::make_pair(node, name)); _types.insert(std::make_pair(node, tname)); } } void Simulator::direct_node(const std::string &src, const std::string &dst) { direct_node(get_node(src), get_node(dst)); } void Simulator::direct_node(const std::shared_ptr<Node> &src, const std::shared_ptr<Node> &dst) { if (src) src->set_dst(dst); } void Simulator::add_generator(const std::shared_ptr<Generator> &gen) { if (gen) _generators.emplace_back(gen); } std::shared_ptr<Client> Simulator::add_client() { std::ostringstream o; o << "C" << _next_client++; std::shared_ptr<Client> client(new Client(this, o.str())); // Private constructor. _clients.push_back(client); log(client) << "client created." << std::endl; return client; } void Simulator::add_event(const Event &event) { _events.push(event); log() << "Added event " << _next_event++ << " at time " << event.get_time() << std::endl; } void Simulator::print_nodes() const { for (auto it : _nodes) { std::cout << it.first << " --> "; it.second->print(); } } std::shared_ptr<Node> Simulator::get_node(const std::string &name) const { auto it = _nodes.find(name); if (it != _nodes.end()) return it->second; else return nullptr; } const std::string &Simulator::get_name(const std::shared_ptr<Node> &node) const { auto it = _names.find(node); if (it != _names.end()) return it->second; else return get_name(nullptr); } const std::string &Simulator::get_type(const std::shared_ptr<Node> &node) const { auto it = _types.find(node); if (it != _types.end()) return it->second; else return get_type(nullptr); } const std::string &Simulator::get_client_name(const std::shared_ptr<Client> &client) const { static const std::string null_client_name = "C?"; return client ? client->get_name() : null_client_name; } double Simulator::get_time() const { return _time; } void Simulator::run(double duration) { std::cout << "Running simulation for " << duration << " units." << std::endl; // Generate. for (const auto &gen : _generators) { auto evt = gen->generate_event(); add_event(evt); std::cout << "Added event: " << _events.size() << " at time " << evt.get_time() << std::endl; } // Simulate. while (!_events.empty()) { cleanup(); auto evt = _events.top(); double time = evt.get_time(); if (time > duration) break; _time = time; _events.pop(); log() << "processing next event." << std::endl; evt.trigger(); } log() << "simulation ended." << std::endl; // Print stats. for (auto it : _nodes) { it.second->print_stats(); } } void Simulator::cleanup() { for (auto it = _clients.begin(); it != _clients.end();) { if ((*it).use_count() < 2) { log(*it) << "left the network." << std::endl; it = _clients.erase(it); } else ++it; } } std::ostream &Simulator::log() { return std::cout << "[sim/" << _time << "] "; } std::ostream &Simulator::log(const std::shared_ptr<Client> &client) { return std::cout << "[sim/" << _time << '/' << get_client_name(client) << "] "; }
752681c000c669f60742a11bb807684fdd7fd73e
5984b9f212cd5bc4f7b80637cf6124eb837ce85d
/Lab6/Dacia.h
798515e2aea7eedb0520c05de4cbace069b347bf
[]
no_license
DideaBogdan/POO-2021-B2_Didea_Bogdan_Marius
452655203cc3382ffb90d05bd962f778d4a48dba
fd7729b875609c028e7b94de5cc72a3f21445626
refs/heads/main
2023-08-18T01:53:08.928609
2021-04-21T18:16:29
2021-04-21T18:16:29
339,751,657
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
Dacia.h
#pragma once #include "Car.h" class Dacia : public Car { virtual int Fuel() override; virtual int FuelConsumption() override; virtual int AverageSpeed(Weather w) override; virtual const char* Name() override; };
77f1988ab490a9dee2c6ca39932e1710cbaca0de
6bb9adc7a8bae33598b8d53124005477a615a111
/CPP/aralik-sayi-toplam.cpp
4ad56ee5690b645b4d3c49f208485e596c0e5731
[]
no_license
SebinLi028/Cesitli-Programlar
abd420d712fba9e6c67e09fa6bb928bbb3d4b9fb
990faf3c640bbcead81cc91efea36a7823354052
refs/heads/master
2021-09-12T04:39:08.549866
2018-04-14T09:38:39
2018-04-14T09:38:39
123,432,899
0
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
aralik-sayi-toplam.cpp
#include <iostream> using namespace std; int main(void) { int number, sum = 0; cout << "enter a number less than 100: "; cin >> number; while (number < 100) { sum += number; number++; } cout << "Sum: " << sum << endl << endl; system("PAUSE"); return 0; }
8c211dca752de9d7e6b53506fb121aef7ad9b933
ece30e7058d8bd42bc13c54560228bd7add50358
/DataCollector/mozilla/xulrunner-sdk/include/nsIProxiedChannel.h
61289288b49e5727d5d20c51a817bf6a84eca516
[ "Apache-2.0" ]
permissive
andrasigneczi/TravelOptimizer
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
b08805f97f0823fd28975a36db67193386aceb22
refs/heads/master
2022-07-22T02:07:32.619451
2018-12-03T13:58:21
2018-12-03T13:58:21
53,926,539
1
0
Apache-2.0
2022-07-06T20:05:38
2016-03-15T08:16:59
C++
UTF-8
C++
false
false
2,604
h
nsIProxiedChannel.h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIProxiedChannel.idl */ #ifndef __gen_nsIProxiedChannel_h__ #define __gen_nsIProxiedChannel_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIProxyInfo; /* forward declaration */ /* starting interface: nsIProxiedChannel */ #define NS_IPROXIEDCHANNEL_IID_STR "6238f134-8c3f-4354-958f-dfd9d54a4446" #define NS_IPROXIEDCHANNEL_IID \ {0x6238f134, 0x8c3f, 0x4354, \ { 0x95, 0x8f, 0xdf, 0xd9, 0xd5, 0x4a, 0x44, 0x46 }} class NS_NO_VTABLE nsIProxiedChannel : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROXIEDCHANNEL_IID) /* readonly attribute nsIProxyInfo proxyInfo; */ NS_IMETHOD GetProxyInfo(nsIProxyInfo * *aProxyInfo) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIProxiedChannel, NS_IPROXIEDCHANNEL_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIPROXIEDCHANNEL \ NS_IMETHOD GetProxyInfo(nsIProxyInfo * *aProxyInfo) override; /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIPROXIEDCHANNEL(_to) \ NS_IMETHOD GetProxyInfo(nsIProxyInfo * *aProxyInfo) override { return _to GetProxyInfo(aProxyInfo); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIPROXIEDCHANNEL(_to) \ NS_IMETHOD GetProxyInfo(nsIProxyInfo * *aProxyInfo) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProxyInfo(aProxyInfo); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsProxiedChannel : public nsIProxiedChannel { public: NS_DECL_ISUPPORTS NS_DECL_NSIPROXIEDCHANNEL nsProxiedChannel(); private: ~nsProxiedChannel(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsProxiedChannel, nsIProxiedChannel) nsProxiedChannel::nsProxiedChannel() { /* member initializers and constructor code */ } nsProxiedChannel::~nsProxiedChannel() { /* destructor code */ } /* readonly attribute nsIProxyInfo proxyInfo; */ NS_IMETHODIMP nsProxiedChannel::GetProxyInfo(nsIProxyInfo * *aProxyInfo) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIProxiedChannel_h__ */
88dcaaaae8a632b032901c1f358992c0085be08e
3e2019e6ca4384630e2c4ca863dfc56a77eda75e
/fondamenti_di_programmazione/temi-esame/appello_29-06-2016/compito.h
32417252b3145b6a035e2ea018bce71f67f3d8a6
[]
no_license
soras19/Ing-Informatica_Unipi
4c01d56664e1f703e7b2e42be2c16d1913a8b7ac
2e8a064797a80c7bdda78837b9dbf294623ca705
refs/heads/master
2020-04-05T09:58:20.325603
2019-01-29T16:02:18
2019-01-29T16:02:18
156,782,571
2
1
null
null
null
null
UTF-8
C++
false
false
480
h
compito.h
#ifndef COMPITO_H_INCLUDED #define COMPITO_H_INCLUDED #include <iostream> using namespace std; class Scrabble{ int N; char** tabella; // funzioni di utility int str_size(const char*); public: Scrabble& operator=(const Scrabble&); Scrabble(int Ne); bool esiste(const char* str); void aggiungi(const char* str, int r, int c, const char dir); friend ostream& operator<<(ostream& os, const Scrabble& s); //SECONDA PARTE // }; #endif
9fb57f54bd19ac86d86e22389a0628291499fd2c
cb807ad6134e68e0ec74f39c2e8e12734e9d3c88
/💡 Arrays-Sum Of Two Arrays.cpp
ae55dd8d62d1f0499b401e2bdcee5d30a8c584e6
[]
no_license
BlazeAxel99/hacker-block-cb-cpp-
0e91e5d90be45ab962fe7e2caddb8dc11cc390ff
f3a63c14ec974ed00eb02c83193a3364d5e6792b
refs/heads/master
2023-02-20T07:15:30.307778
2021-01-20T14:06:59
2021-01-20T14:06:59
289,300,574
1
1
null
null
null
null
UTF-8
C++
false
false
1,463
cpp
💡 Arrays-Sum Of Two Arrays.cpp
/* Take as input N, the size of array. Take N more inputs and store that in an array. Take as input M, the size of second array and take M more inputs and store that in second array. Write a function that returns the sum of two arrays. Print the value returned. Input Format Constraints Length of Array should be between 1 and 1000. Output Format Sample Input 4 1 0 2 9 5 3 4 5 6 7 Sample Output 3, 5, 5, 9, 6, END Explanation Sum of [1, 0, 2, 9] and [3, 4, 5, 6, 7] is [3, 5, 5, 9, 6] and the first digit represents carry over , if any (0 here ) . */ #include<iostream> using namespace std; void calculate(int a[], int b[], int n, int m) { int sum[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; while (j >= 0) { s = a[i] + b[j] + carry; sum[k] = (s % 10); carry = s / 10; k--; i--; j--; } while (i >= 0) { s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; if (carry) cout<<carry<<", "; for (int i = 0; i <= n - 1; i++) { cout<<sum[i]<<", "; } cout<<"END"; // return ans / 10; } void compare(int a[], int b[], int n, int m) { if (n >= m) calculate(a, b, n, m); else calculate(b, a, m, n); } int main() { int a[10001],b[10001]; int n,m; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } cin>>m; for(int i=0;i<m;i++){ cin>>b[i]; } compare(a, b, n, m); return 0; }
cabeaed5d2be5369568993c428035426e157bff7
2cdf738778eaadf37e4cc0e6e5686dc36d058744
/src/parameters_panel.cpp
faba3e28d8939636105deb2ccac15b1450d3a94e
[]
no_license
biberino/fraktal_kundschafter
c47116c2293d889e1bd7e0472f350de9a1a8cc35
e55cf18598e4975c5312f8a34078904914da3042
refs/heads/master
2023-06-11T03:07:34.155347
2023-05-27T15:48:38
2023-05-27T15:48:38
140,421,629
0
0
null
null
null
null
UTF-8
C++
false
false
2,900
cpp
parameters_panel.cpp
#include "parameters_panel.hpp" #include <iostream> Parameters_panel::Parameters_panel(/* args */) { _lbl_max_iter.set_text("Anzahl Iterationen:"); _lbl_koppl.set_text("Verkopplungskonstante:"); _lbl_width.set_text("Auflösung X:"); _lbl_height.set_text("Auflösung Y:"); _lbl_gen_param.set_text("Generischer Parameter:"); _lbl_bailout.set_text("Fluchtradius"); _lbl_startpoint_real.set_text("Startwert/Julia Realanteil:"); _lbl_startpoint_imag.set_text("Startwert/Julia Imaginäranteil:"); attach(_lbl_max_iter, 0, 0, 1, 1); attach(_txt_max_iter, 0, 1, 1, 1); attach(_lbl_koppl, 1, 0, 1, 1); attach(_txt_koppl, 1, 1, 1, 1); attach(_lbl_width, 0, 2, 1, 1); attach(_txt_width, 0, 3, 1, 1); attach(_lbl_height, 1, 2, 1, 1); attach(_txt_height, 1, 3, 1, 1); attach(_lbl_gen_param, 0, 4, 1, 1); attach(_txt_gen_param, 0, 5, 1, 1); attach(_lbl_bailout, 1, 4, 1, 1); attach(_txt_bailout, 1, 5, 1, 1); attach(_lbl_startpoint_real, 0, 6, 1, 1); attach(_txt_startpoint_real, 0, 7, 1, 1); attach(_lbl_startpoint_imag, 1, 6, 1, 1); attach(_txt_startpoint_imag, 1, 7, 1, 1); /** DEFAULTS **/ _txt_width.set_text("1200"); _txt_height.set_text("800"); _txt_max_iter.set_text("50"); _txt_koppl.set_text("0.0"); _txt_gen_param.set_text("1.0"); _txt_bailout.set_text("2.0"); _txt_startpoint_real.set_text("0.0"); _txt_startpoint_imag.set_text("0.0"); show_all_children(); } Parameters_panel::~Parameters_panel() { } Parameters_Info Parameters_panel::get_data() { Parameters_Info info; try { info.max_iter = std::stoi(_txt_max_iter.get_text()); info.koppl = std::stod(_txt_koppl.get_text()); info.res.x = std::stod(_txt_width.get_text()); info.res.y = std::stod(_txt_height.get_text()); info.gen_param = std::stod(_txt_gen_param.get_text()); info.bailout = std::stod(_txt_bailout.get_text()); info.startpoint = complex_type(std::stod(_txt_startpoint_real.get_text()), std::stod(_txt_startpoint_imag.get_text())); std::cout << "DEBUG " << info.koppl << '\n'; } catch (const std::exception &e) { std::cout << e.what() << '\n'; } return info; } void Parameters_panel::set_data(Parameters_Info info) { _txt_max_iter.set_text(std::to_string(info.max_iter)); std::cout << info.koppl << std::endl; _txt_koppl.set_text(std::to_string(info.koppl)); _txt_width.set_text(std::to_string(info.res.x)); _txt_height.set_text(std::to_string(info.res.y)); _txt_gen_param.set_text(std::to_string(info.gen_param)); _txt_bailout.set_text(std::to_string(info.bailout)); _txt_startpoint_real.set_text(std::to_string(info.startpoint.real())); _txt_startpoint_imag.set_text(std::to_string(info.startpoint.imag())); }
49fe3da5e7f441f5a1d3ece25d204266a1e6381c
b623b1b5ccc3a6c4003a85b8a84fb7c8b92d6875
/dll/InitializeHooks.cpp
16ca15070c8a8befcea1a5ffede5aad1d015cfed
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
namreeb/wowreeb
bb2983bccc48aa1101362ca81c561f2e73465bb7
6096851265887efe0d7875002aa2e2f731d6729d
refs/heads/master
2023-05-11T22:52:04.850255
2022-12-29T00:14:41
2022-12-29T00:14:41
92,789,856
51
27
null
null
null
null
UTF-8
C++
false
false
13,217
cpp
InitializeHooks.cpp
/* MIT License Copyright (c) 2018-2023 namreeb http://github.com/namreeb legal@namreeb.org 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. */ #pragma comment(lib, "asmjit.lib") #pragma comment(lib, "udis86.lib") #include "InitializeHooks.hpp" #include <cstdint> #include <hadesmem/patcher.hpp> namespace { enum class Version { Classic = 0, TBC, WotLK, Cata32, Cata64, Total }; enum class Offset { CVar__Set = 0, RealmListCVar, Idle, CGlueMgr__m_pendingServerAlert, Login, FoV, Total }; PVOID GetAddress(Version version, Offset offset) { static constexpr std::uint32_t offsets[static_cast<int>( Version::Total)][static_cast<int>(Offset::Total)] = { // clang-format off // Classic { 0x23DF50, 0x82812C, 0x6B930, 0x741E28, 0x6AFB0, 0x4089B4 }, // TBC { 0x23F6C0, 0x943330, 0x70160, 0x807DB8, 0x6E560, 0x4B5A04 }, // WotLK { 0x3668C0, 0x879D00, 0xDAB40, 0x76AF88, 0xD8A30, 0x5E8D88 }, // Cata32 { 0x2553B0, 0x9BE800, 0x405310, 0xABBF04, 0x400240, 0x00, // not supported. let me know if anyone actually wants this }, // Cata64 { 0x2F61D0, 0xCA4328, 0x51A7C0, 0xDACCA8, 0x514100, 0x00, // not supported. let me know if anyone actually wants this } // clang-format on }; auto const baseAddress = reinterpret_cast<std::uint8_t*>(::GetModuleHandle(nullptr)); return baseAddress + offsets[static_cast<int>(version)][static_cast<int>(offset)]; } } // namespace namespace Classic { class CVar { }; using SetT = bool (__thiscall CVar::*)(const char*, char, char, char, char); using IdleT = int(__cdecl*)(); using LoginT = void(__fastcall*)(char*, char*); int IdleHook(hadesmem::PatchDetourBase* detour, GameSettings* settings) { auto const idle = detour->GetTrampolineT<IdleT>(); auto const ret = idle(); // if we are no longer waiting for the server alert, proceed with // configuration if (!*reinterpret_cast<std::uint32_t*>( GetAddress(Version::Classic, Offset::CGlueMgr__m_pendingServerAlert))) { auto const cvar = *reinterpret_cast<CVar**>( GetAddress(Version::Classic, Offset::RealmListCVar)); auto const set = hadesmem::detail::AliasCast<SetT>( GetAddress(Version::Classic, Offset::CVar__Set)); (cvar->*set)(settings->AuthServer, 1, 0, 1, 0); detour->Remove(); if (settings->CredentialsSet) { auto const login = hadesmem::detail::AliasCast<LoginT>( GetAddress(Version::Classic, Offset::Login)); login(settings->Username, settings->Password); } settings->LoadComplete = true; } return ret; } void ApplyClientInitHook(GameSettings* settings) { // just to make sure the value is initialized *reinterpret_cast<std::uint32_t*>( GetAddress(Version::Classic, Offset::CGlueMgr__m_pendingServerAlert)) = 1; auto const proc = hadesmem::Process(::GetCurrentProcessId()); auto const idleOrig = hadesmem::detail::AliasCast<IdleT>( GetAddress(Version::Classic, Offset::Idle)); auto idleDetour = new hadesmem::PatchDetour<IdleT>( proc, idleOrig, [settings](hadesmem::PatchDetourBase* detour) { return IdleHook(detour, settings); }); idleDetour->Apply(); if (settings->FoVSet) { auto const pFov = GetAddress(Version::Classic, Offset::FoV); std::vector<std::uint8_t> patchData(sizeof(settings->FoV)); memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV)); auto patch = new hadesmem::PatchRaw(proc, pFov, patchData); patch->Apply(); } } } // namespace Classic namespace TBC { class CVar { }; using SetT = bool (__thiscall CVar::*)(const char*, char, char, char, char); using IdleT = int(__cdecl*)(); using LoginT = void(__cdecl*)(char*, char*); int IdleHook(hadesmem::PatchDetourBase* detour, GameSettings* settings) { auto const idle = detour->GetTrampolineT<IdleT>(); auto const ret = idle(); // if we are no longer waiting for the server alert, proceed with // configuration if (!*reinterpret_cast<std::uint32_t*>( GetAddress(Version::TBC, Offset::CGlueMgr__m_pendingServerAlert))) { auto const cvar = *reinterpret_cast<CVar**>( GetAddress(Version::TBC, Offset::RealmListCVar)); auto const set = hadesmem::detail::AliasCast<SetT>( GetAddress(Version::TBC, Offset::CVar__Set)); (cvar->*set)(settings->AuthServer, 1, 0, 1, 0); detour->Remove(); if (settings->CredentialsSet) { auto const login = hadesmem::detail::AliasCast<LoginT>( GetAddress(Version::TBC, Offset::Login)); login(settings->Username, settings->Password); } settings->LoadComplete = true; } return ret; } void ApplyClientInitHook(GameSettings* settings) { // just to make sure the value is initialized *reinterpret_cast<std::uint32_t*>( GetAddress(Version::TBC, Offset::CGlueMgr__m_pendingServerAlert)) = 1; auto const proc = hadesmem::Process(::GetCurrentProcessId()); auto const idleOrig = hadesmem::detail::AliasCast<IdleT>( GetAddress(Version::TBC, Offset::Idle)); auto idleDetour = new hadesmem::PatchDetour<IdleT>( proc, idleOrig, [settings](hadesmem::PatchDetourBase* detour) { return IdleHook(detour, settings); }); idleDetour->Apply(); if (settings->FoVSet) { auto const pFov = GetAddress(Version::TBC, Offset::FoV); std::vector<std::uint8_t> patchData(sizeof(settings->FoV)); memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV)); auto patch = new hadesmem::PatchRaw(proc, pFov, patchData); patch->Apply(); } } } // namespace TBC namespace WOTLK { class CVar { }; using SetT = bool (__thiscall CVar::*)(const char*, char, char, char, char); using IdleT = int(__cdecl*)(); using LoginT = void(__cdecl*)(char*, char*); int IdleHook(hadesmem::PatchDetourBase* detour, GameSettings* settings) { auto const idle = detour->GetTrampolineT<IdleT>(); auto const ret = idle(); // if we are no longer waiting for the server alert, proceed with // configuration if (!*reinterpret_cast<std::uint32_t*>( GetAddress(Version::WotLK, Offset::CGlueMgr__m_pendingServerAlert))) { auto const cvar = *reinterpret_cast<CVar**>( GetAddress(Version::WotLK, Offset::RealmListCVar)); auto const set = hadesmem::detail::AliasCast<SetT>( GetAddress(Version::WotLK, Offset::CVar__Set)); (cvar->*set)(settings->AuthServer, 1, 0, 1, 0); detour->Remove(); if (settings->CredentialsSet) { auto const login = hadesmem::detail::AliasCast<LoginT>( GetAddress(Version::WotLK, Offset::Login)); login(settings->Username, settings->Password); } settings->LoadComplete = true; } return ret; } void ApplyClientInitHook(GameSettings* settings) { // just to make sure the value is initialized *reinterpret_cast<std::uint32_t*>( GetAddress(Version::WotLK, Offset::CGlueMgr__m_pendingServerAlert)) = 1; auto const proc = hadesmem::Process(::GetCurrentProcessId()); auto const idleOrig = hadesmem::detail::AliasCast<IdleT>( GetAddress(Version::WotLK, Offset::Idle)); auto idleDetour = new hadesmem::PatchDetour<IdleT>( proc, idleOrig, [settings](hadesmem::PatchDetourBase* detour) { return IdleHook(detour, settings); }); idleDetour->Apply(); if (settings->FoVSet) { auto const pFov = GetAddress(Version::WotLK, Offset::FoV); std::vector<std::uint8_t> patchData(sizeof(settings->FoV)); memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV)); auto patch = new hadesmem::PatchRaw(proc, pFov, patchData); patch->Apply(); } } } // namespace WOTLK namespace Cata32 { class CVar { }; using SetT = bool (__thiscall CVar::*)(const char*, char, char, char, char); using IdleT = int(__cdecl*)(); using LoginT = void(__cdecl*)(char*, char*); int IdleHook(hadesmem::PatchDetourBase* detour, GameSettings* settings) { auto const idle = detour->GetTrampolineT<IdleT>(); auto const ret = idle(); // if we are no longer waiting for the server alert, proceed with // configuration if (!*reinterpret_cast<std::uint32_t*>( GetAddress(Version::Cata32, Offset::CGlueMgr__m_pendingServerAlert))) { auto const cvar = *reinterpret_cast<CVar**>( GetAddress(Version::Cata32, Offset::RealmListCVar)); auto const set = hadesmem::detail::AliasCast<SetT>( GetAddress(Version::Cata32, Offset::CVar__Set)); (cvar->*set)(settings->AuthServer, 1, 0, 1, 0); detour->Remove(); if (settings->CredentialsSet) { auto const login = hadesmem::detail::AliasCast<LoginT>( GetAddress(Version::Cata32, Offset::Login)); login(settings->Username, settings->Password); } settings->LoadComplete = true; } return ret; } void ApplyClientInitHook(GameSettings* settings) { // just to make sure the value is initialized *reinterpret_cast<std::uint32_t*>( GetAddress(Version::Cata32, Offset::CGlueMgr__m_pendingServerAlert)) = 1; auto const proc = hadesmem::Process(::GetCurrentProcessId()); auto const idleOrig = hadesmem::detail::AliasCast<IdleT>( GetAddress(Version::Cata32, Offset::Idle)); auto idleDetour = new hadesmem::PatchDetour<IdleT>( proc, idleOrig, [settings](hadesmem::PatchDetourBase* detour) { return IdleHook(detour, settings); }); idleDetour->Apply(); } } // namespace Cata32 namespace Cata64 { class CVar { }; using SetT = bool (__fastcall CVar::*)(const char*, char, char, char, char); using IdleT = int(__stdcall*)(); using LoginT = void(__fastcall*)(char*, char*); int IdleHook(hadesmem::PatchDetourBase* detour, GameSettings* settings) { auto const idle = detour->GetTrampolineT<IdleT>(); auto const ret = idle(); // if we are no longer waiting for the server alert, proceed with // configuration if (!*reinterpret_cast<std::uint32_t*>( GetAddress(Version::Cata64, Offset::CGlueMgr__m_pendingServerAlert))) { auto const cvar = *reinterpret_cast<CVar**>( GetAddress(Version::Cata64, Offset::RealmListCVar)); auto const set = hadesmem::detail::AliasCast<SetT>( GetAddress(Version::Cata64, Offset::CVar__Set)); (cvar->*set)(settings->AuthServer, 1, 0, 1, 0); detour->Remove(); if (settings->CredentialsSet) { auto const login = hadesmem::detail::AliasCast<LoginT>( GetAddress(Version::Cata64, Offset::Login)); login(settings->Username, settings->Password); } settings->LoadComplete = true; } return ret; } void ApplyClientInitHook(GameSettings* settings) { // just to make sure the value is initialized *reinterpret_cast<std::uint32_t*>( GetAddress(Version::Cata64, Offset::CGlueMgr__m_pendingServerAlert)) = 1; auto const proc = hadesmem::Process(::GetCurrentProcessId()); auto const idleOrig = hadesmem::detail::AliasCast<IdleT>( GetAddress(Version::Cata64, Offset::Idle)); auto idleDetour = new hadesmem::PatchDetour<IdleT>( proc, idleOrig, [settings](hadesmem::PatchDetourBase* detour) { return IdleHook(detour, settings); }); idleDetour->Apply(); } } // namespace Cata64
ef828e96e766bc354f3494f4c4742cc2ad3bb8a1
c1d7a2de68d4e4ad50e4684396d744d24affefde
/win_game/Threading/MutexLock.cpp
2a16352cf1f8d448e4a92acfdd07a20e5394c678
[]
no_license
dzoidx/Vulkan-UI-Editor
aad235b280a5ed822c52b3c2469bce23e266c8b0
59df698a191dade1ea6f4bd558a387d526ecabb5
refs/heads/main
2023-07-31T01:58:50.993495
2021-09-08T07:37:40
2021-09-08T07:38:15
404,239,889
2
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
MutexLock.cpp
#include "MutexLock.h" MutexLock::MutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } MutexLock::MutexLock() : mutex_(nullptr) {} MutexLock::~MutexLock() { Unlock(); } void MutexLock::Lock(Mutex* mutex) { if (mutex_) return; mutex_ = mutex; mutex_->Lock(); } void MutexLock::Unlock() { if (mutex_) { mutex_->Unlock(); mutex_ = nullptr; } }
1e3568abcb43c5bf5b05a1d5fb2c6aa4291786e7
55fc0e953ddd07963d290ed56ab25ff3646fe111
/StiGame/gui/effects/EffectListener.cpp
c77f4a093dd5135c0c3771d0f9784b5ad11eb22a
[ "MIT" ]
permissive
jordsti/stigame
71588674640a01fd37336238126fb4500f104f42
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
refs/heads/master
2020-05-20T12:54:58.985367
2015-06-10T20:55:41
2015-06-10T20:55:41
22,086,407
12
3
null
null
null
null
UTF-8
C++
false
false
262
cpp
EffectListener.cpp
#include "EffectListener.h" namespace StiGame { namespace Gui { namespace Effects { EffectListener::EffectListener() { } EffectListener::~EffectListener() { } void EffectListener::handleEvent(EffectEventThrower *src, EffectEventArgs *args) { } } } }
7a66073f4100c0cada9f5f8cff4c1463425e5445
ebd5c4632bb5f85c9e3311fd70f6f1bf92fae53f
/PORMain/panda/include/pythonTask.h
13874bc31725e9c99dbad800ca2635e7891ef58a
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
BrandonAlex/Pirates-Online-Retribution
7f881a64ec74e595aaf62e78a39375d2d51f4d2e
980b7448f798e255eecfb6bd2ebb67b299b27dd7
refs/heads/master
2020-04-02T14:22:28.626453
2018-10-24T15:33:17
2018-10-24T15:33:17
154,521,816
2
1
null
null
null
null
UTF-8
C++
false
false
2,602
h
pythonTask.h
// Filename: pythonTask.h // Created by: drose (16Sep08) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef PYTHONTASK_H #define PYTHONTASK_H #include "pandabase.h" #include "asyncTask.h" #ifdef HAVE_PYTHON //////////////////////////////////////////////////////////////////// // Class : PythonTask // Description : This class exists to allow association of a Python // function with the AsyncTaskManager. //////////////////////////////////////////////////////////////////// class EXPCL_PANDA_PIPELINE PythonTask : public AsyncTask { PUBLISHED: PythonTask(PyObject *function = Py_None, const string &name = string()); virtual ~PythonTask(); ALLOC_DELETED_CHAIN(PythonTask); void set_function(PyObject *function); PyObject *get_function(); void set_args(PyObject *args, bool append_task); PyObject *get_args(); void set_upon_death(PyObject *upon_death); PyObject *get_upon_death(); void set_owner(PyObject *owner); PyObject *get_owner(); int __setattr__(const string &attr_name, PyObject *v); int __setattr__(const string &attr_name); PyObject *__getattr__(const string &attr_name) const; protected: virtual bool is_runnable(); virtual DoneStatus do_task(); DoneStatus do_python_task(); virtual void upon_birth(AsyncTaskManager *manager); virtual void upon_death(AsyncTaskManager *manager, bool clean_exit); private: void register_to_owner(); void unregister_from_owner(); void call_owner_method(const char *method_name); void call_function(PyObject *function); private: PyObject *_function; PyObject *_args; bool _append_task; PyObject *_upon_death; PyObject *_owner; bool _registered_to_owner; PyObject *_dict; PyObject *_generator; public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { AsyncTask::init_type(); register_type(_type_handle, "PythonTask", AsyncTask::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; #include "pythonTask.I" #endif // HAVE_PYTHON #endif
0877f15cee3a1eafede31fcd88b072c7a10a7204
8d2f0d78ca8566081c90615354e8a2d8cea6352d
/encryptutils.h
e71d2fa66e304b68e681a3c602a342ca93023145
[ "CC0-1.0" ]
permissive
michaelnpsp/WifiMouseServer
320eaefed9571860444cffdc29258278366d7475
4e3a0ad3745edad704cbb3ead0b30a742887a302
refs/heads/master
2022-11-11T09:48:01.367905
2020-06-28T20:31:17
2020-06-28T20:31:17
275,452,782
6
1
NOASSERTION
2020-06-27T21:03:02
2020-06-27T21:03:01
null
UTF-8
C++
false
false
342
h
encryptutils.h
#ifndef ENCRYPTUTILS_H #define ENCRYPTUTILS_H #include <QByteArray> #include <QString> namespace EncryptUtils { QByteArray makeHash16(QByteArray toHash); QByteArray decryptBytes(QByteArray data, QByteArray key, QByteArray iv); QByteArray encryptBytes(QByteArray data, QByteArray key, QByteArray iv); } #endif // ENCRYPTUTILS_H
c32eefef51108b2606e828bc8065c62409b52635
118aa6bdb9f3beba4bef627977122bd3402b4501
/ProjetC++/src/Soldier.cpp
f1fbd077a8b30440af2d8d27ff0bfbab8baa597d
[]
no_license
OlivierNappert/Game-TowerDefense
edca31f7b07874e8222fb8a5ebe55fedcf62b01c
c95329e6449cc9523c563587666a97bfa442b99e
refs/heads/master
2021-01-23T02:06:13.402681
2017-03-23T15:36:48
2017-03-23T15:36:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
920
cpp
Soldier.cpp
#include "../include/Soldier.hpp" /* Sodier& Soldier::operator=(const Soldier& obj) { Soldier temp(copy); std::swap(temp.hp, hp); std::swap(temp.pa, pa); std::swap(temp.pm, pm); std::swap(temp.attackValue, attackValue); std::swap(temp.moveValue, moveValue); std::swap(temp.range, range); std::swap(temp.cost, cost); std::swap(temp.pos, pos); std::swap(temp.unitID, unitID); std::swap(temp.superSoldier, superSoldier); return *this; } */ void Soldier::refresh(){ pa = superSoldier ? 2 : 1; pm = 1; } int Soldier::action1(){ return ATTACK; } int Soldier::action2(){ return MOVE; } int Soldier::action3(){ if(pa > 0 || superSoldier) return ATTACK; return IDLE; } void Soldier::setSuperSoldier(){ superSoldier = true; name = "SSoldier"; } Soldier* Soldier::clone(){ return new Soldier(hp,pa,pm,attackValue,moveValue,range,cost,unitID); }
809bb381f3ad1722a0d953d0e9da345788ff2df8
f871b2c9f4c25f7f43c4148ae98dc8371f4c8892
/emptyExample/src/npBox.cpp
644b572c99733b6b6fdd3042f23a35b399b9f801
[]
no_license
kalwalt/npDeferredS
4f9d345fb0f37c9b17f6480df6d1ee4f3330a020
7cf10c47118332e2309ae3a98614b890fafb6e52
refs/heads/master
2021-01-18T06:34:36.005634
2012-12-26T22:03:27
2012-12-26T22:03:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,198
cpp
npBox.cpp
#include "npBox.h" void npBox::setup(npMaterial mat, float w , float h,float d ) { width =w; height =h; depth =d; material = mat; hasColor = false; hasUV = false; stride =6; if (material.hasColor) { hasColor =true; r =material.r; g =material.g; b =material.b; stride +=3; }if (material.hasUV) { hasUV =true; stride +=2; } numVertices =24; vertices = new float[numVertices*stride ]; numIndices =36; indices =new unsigned int [ numIndices]; vertcount =0; indcount =0; indPos =0; float w2 =w/2.0f; float h2 =h/2.0f; float d2 =d/2.0f; //top addPlane(ofVec3f(-w2,h2,-d2),ofVec3f(w2,h2,-d2),ofVec3f(w2,h2,d2),ofVec3f(-w2,h2,d2),ofVec3f(0,1,0)); //bottem addPlane(ofVec3f(-w2,-h2,-d2),ofVec3f(w2,-h2,-d2),ofVec3f(w2,-h2,d2),ofVec3f(-w2,-h2,d2),ofVec3f(0,-1,0)); //front addPlane(ofVec3f(-w2,h2,d2),ofVec3f(w2,h2,d2),ofVec3f(w2,-h2,d2),ofVec3f(-w2,-h2,d2),ofVec3f(0,0,1)); //back addPlane(ofVec3f(-w2,h2,-d2),ofVec3f(w2,h2,-d2),ofVec3f(w2,-h2,-d2),ofVec3f(-w2,-h2,-d2),ofVec3f(0,0,-1)); //right addPlane(ofVec3f(w2,-h2,-d2),ofVec3f(w2,-h2,d2),ofVec3f(w2,h2,d2),ofVec3f(w2,h2,-d2),ofVec3f(1,0,0)); //left addPlane(ofVec3f(-w2,-h2,-d2),ofVec3f(-w2,-h2,d2),ofVec3f(-w2,h2,d2),ofVec3f(-w2,h2,-d2),ofVec3f(-1,0,0)); createBuffers(); delete [ ] indices; indices =NULL; delete []vertices; vertices =NULL; } void npBox::addPlane(const ofVec3f &p1,const ofVec3f &p2,const ofVec3f &p3,const ofVec3f &p4,const ofVec3f &normal) { indices[indPos++ ] = indcount; indices[indPos++]= indcount+1; indices[indPos++] = indcount+3; indices[indPos++ ] = indcount+1; indices[indPos++]= indcount+2; indices[indPos++] = indcount+3; indcount+=4; //p1 vertices[vertcount++] = p1.x ; vertices[vertcount++] = p1.y ; vertices[vertcount++] = p1.z; vertices[vertcount++] = normal.x; vertices[vertcount++] = normal.y; vertices[vertcount++] = normal.z; if (hasColor) { vertices[vertcount++] = r; vertices[vertcount++] = g; vertices[vertcount++] = b; } if (hasUV) { cout << "implement UV Sphere "; vertices[vertcount++] = 0; vertices[vertcount++] = 0; } //p2 vertices[vertcount++] = p2.x ; vertices[vertcount++] = p2.y ; vertices[vertcount++] = p2.z; vertices[vertcount++] = normal.x; vertices[vertcount++] = normal.y; vertices[vertcount++] = normal.z; if (hasColor) { vertices[vertcount++] = r; vertices[vertcount++] = g; vertices[vertcount++] = b; } if (hasUV) { cout << "implement UV Sphere "; vertices[vertcount++] = 0; vertices[vertcount++] = 0; } //p3 vertices[vertcount++] = p3.x ; vertices[vertcount++] = p3.y ; vertices[vertcount++] = p3.z; vertices[vertcount++] = normal.x; vertices[vertcount++] = normal.y; vertices[vertcount++] = normal.z; if (hasColor) { vertices[vertcount++] = r; vertices[vertcount++] = g; vertices[vertcount++] = b; } if (hasUV) { cout << "implement UV Sphere "; vertices[vertcount++] = 0; vertices[vertcount++] = 0; } //p4 vertices[vertcount++] = p4.x ; vertices[vertcount++] = p4.y ; vertices[vertcount++] = p4.z; vertices[vertcount++] = normal.x; vertices[vertcount++] = normal.y; vertices[vertcount++] = normal.z; if (hasColor) { vertices[vertcount++] = r; vertices[vertcount++] = g; vertices[vertcount++] = b; } if (hasUV) { cout << "implement UV Sphere "; vertices[vertcount++] = 0; vertices[vertcount++] = 0; } } void npBox::makePhysicsBox() { fCollisionShape = new btBoxShape(btVector3(width/2,height/2,depth/2)); ofVec4f q =quat.asVec4(); btDefaultMotionState* fMotionState =new btDefaultMotionState(btTransform(btQuaternion(q.x,q.y,q.z,q.w),btVector3(x,y,z))); btScalar mass = 0; btVector3 fallInertia(0.0,0.0,0.1); fCollisionShape->calculateLocalInertia(mass,fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fMotionState,fCollisionShape,fallInertia); fRigidBody = new btRigidBody(fallRigidBodyCI); }
6d4bdb27503767cdc9396e104b71e19a08639679
d3e028b03d4908139c0dcc6549a82e26cb971097
/2016-08-07/I.cpp
9e43cf0b12403c3da8623b1a8cb6902c294a24ac
[]
no_license
gzgreg/ACM
064c99bc2f8f32ee973849631291bedfcda38247
1187c5f9e02ca5a1ec85e68891134f7d57cf6693
refs/heads/master
2020-05-21T20:27:46.976555
2018-06-30T18:16:36
2018-06-30T18:16:36
62,960,665
6
2
null
null
null
null
UTF-8
C++
false
false
1,103
cpp
I.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; #define endl '\n' int n; pii rotate(pii curr) { return {curr.second, n - 1 - curr.first}; } int main(){ ios::sync_with_stdio(0); cin >> n; set<pii> grille; set<pii> unseen; char grid[n][n]; memset(grid, '6', sizeof grid); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { char curr; cin >> curr; unseen.insert({i, j}); if(curr == '.') { grille.insert({i, j}); } } } string code; cin >> code; if(grille.size() != n*n/4) { cout << "invalid grille" << endl; return 0; } int idx = 0; for(int i = 0; i < 4; i++) { set<pii> newGrille; for(pii curr : grille) { unseen.erase(curr); newGrille.insert(rotate(curr)); grid[curr.first][curr.second] = code[idx]; idx++; } grille = newGrille; } if(!unseen.empty()) { cout << "invalid grille" << endl; } else { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout << grid[i][j]; } } cout << endl; } return 0; }
07fb7094f9c2169c6d1c3b1c2555b046313bf319
62d48af115ea9d14bc5a7dd85212e616a48dcac6
/src/sharedLibraries/headers/FinalSelection.h
cafb497a0840d84dd28b70b879945ca6d758aeec
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
asu-cactus/lachesis
ab1ab1704e4f0f2d6aef1a2bff2dc99ea8f09337
92efa7b124a23894485a900bb394670487051948
refs/heads/master
2023-03-05T11:41:35.016673
2021-02-14T21:50:32
2021-02-14T21:50:32
151,744,205
2
0
Apache-2.0
2021-02-14T16:37:54
2018-10-05T15:49:15
C++
UTF-8
C++
false
false
664
h
FinalSelection.h
#ifndef FINAL_SELECTION_H #define FINAL_SELECTION_H #include "Lambda.h" #include "LambdaCreationFunctions.h" #include "SelectionComp.h" #include "DepartmentTotal.h" #include "PDBVector.h" #include "PDBString.h" using namespace pdb; class FinalSelection : public SelectionComp<double, DepartmentTotal> { public: ENABLE_DEEP_COPY FinalSelection() {} Lambda<bool> getSelection(Handle<DepartmentTotal> checkMe) override { return makeLambdaFromMethod(checkMe, checkSales); } Lambda<Handle<double>> getProjection(Handle<DepartmentTotal> checkMe) override { return makeLambdaFromMethod(checkMe, getTotSales); } }; #endif
f52978ed12bc53f55a851ac832677660d0a53304
77ff0d5fe2ec8057f465a3dd874d36c31e20b889
/libraries/GRL/Network Flow/decrease_one_cap_path.cpp
eec2eef2fcfa1a1d108345e8709d9b1d81fb52e6
[]
no_license
kei1107/algorithm
cc4ff5fe6bc52ccb037966fae5af00c789b217cc
ddf5911d6678d8b110d42957f15852bcd8fef30c
refs/heads/master
2021-11-23T08:34:48.672024
2021-11-06T13:33:29
2021-11-06T13:33:29
105,986,370
2
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,314
cpp
decrease_one_cap_path.cpp
#define INF 1<<30 #define LINF 1LL60 struct edge { int to; // 行き先 int cap; // 容量 int rev; // 逆辺 edge() {} edge(int to, int cap, int rev) :to(to), cap(cap), rev(rev) {} }; vector<vector<edge>> G; // グラフの隣接リスト表現 vector<int> used; // DFSですでに調べたらフラグ vector<vector<int>> one_path; // 幅1の道の場所記録 // fromからtoへ向かう容量capの辺をグラフに追加する void add_edge(int from, int to, int cap) { if (cap == 1) { one_path[from].push_back(G[from].size()); one_path[to].push_back(G[to].size()); } G[from].push_back(edge(to, cap, G[to].size())); G[to].push_back(edge(from, cap, G[from].size() - 1)); } // 増加パスをDFSで探す int dfs(int v, int t, int f) { if (v == t) return f; used[v] = true; for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (!used[e.to] && e.cap > 0) { int d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } // sからtへの最大流を求める int max_flow(int s, int t) { int flow = 0; for (;;) { fill(used.begin(), used.end(), 0); int f = dfs(s, t, INF); if (f == 0) return flow; flow += f; } } /* 幅1のパス(u,v)を u->vのルートではなく、別ルートから辿れるか確認 ex.( u->s->t->v) */ bool check(int u, int v, int rev) { if (u == v)return true; used[u] = true; for (int i = 0; i < G[u].size();i++) { if (used[G[u][i].to] == true) continue; if (G[u][i].cap <= 0) continue; if (G[u][i].to == rev)continue; if (check(G[u][i].to, v, u))return true; } return false; } /* use example / max_flow < F = 10000 */ int main() { cin.tie(0); ios::sync_with_stdio(false); int V, E; cin >> V >> E; int F = 10000; G.resize(V); used.resize(V); one_path.resize(V); for (int i = 0; i < E;i++) { int s, t, c; cin >> s >> t >> c; add_edge(s, t, c); } int f = max_flow(0, V - 1); for (int i = 0; i < V;i++) { bool break_flag = false; for (int j = 0; j < one_path[i].size();j++) { if (G[i][one_path[i][j]].cap == 0) { fill(used.begin(), used.end(), 0); if (!check(i, G[i][one_path[i][j]].to, -1)) { f--; break_flag = true; break; } } } if (break_flag)break; } cout << ((f > F) ? -1 : f) << endl; return 0; }
64573c37dba9a8f24883f7a2152961c742d24b03
7030bdc16a529c04ebacc9d18c5eff9251320ca9
/stable/player/util/upnp/upnpdom/v1_02/include/NodeAct.h
102b2ffbd0fff23a49650b2c5c3350a99f1062b2
[]
no_license
pleasemarkdarkly/iomega_hipzip
cd770e6cf1b1e719098d5e33e810d897249c0f69
ee741ddf30d3f0875420384837ba8eb9581f5bf2
refs/heads/master
2021-05-24T18:53:04.662340
2020-04-07T08:22:21
2020-04-07T08:22:21
253,705,949
4
0
null
null
null
null
UTF-8
C++
false
false
3,187
h
NodeAct.h
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000 Intel Corporation // 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 name of Intel Corporation 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 INTEL 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. // /////////////////////////////////////////////////////////////////////////// // $Revision: 1.6 $ // $Date: 2000/08/18 15:38:54 $ #ifndef _NODEACT_H_ #define _NODEACT_H_ #include <string.h> #include <util/upnp/upnpdom/Node.h> #include <util/upnp/upnpdom/all.h> #include <util/upnp/upnpdom/DOMException.h> #include <util/upnp/genlib/noexceptions.h> #include <util/debug/debug.h> class Node; class NodeAct { public: int RefCount; NodeAct(NODE_TYPE nt,char *NodeName, char *NodeValue, Node * myCreator); NodeAct(const NodeAct &other, bool deep); ~NodeAct(); NodeAct* cloneNode(bool deep); #ifndef FORCE_NO_EXCEPTIONS void appendChild(NodeAct *newChild); void insertBefore(NodeAct *newChild, NodeAct *refChild); void replaceChild(NodeAct *newChild, NodeAct *oldChild); #endif // FORCE_NO_EXCEPTIONS EDERRCODE appendChildNoEx(NodeAct *newChild); EDERRCODE insertBeforeNoEx(NodeAct *newChild, NodeAct *refChild); EDERRCODE replaceChildNoEx(NodeAct *newChild, NodeAct *oldChild); void removeChild(NodeAct *oldChild); EDERRCODE removeChildNoEx(NodeAct *oldChild); bool findNode(NodeAct *find); void setName(char *n); void setValue(char *v); char *NA_NodeName; char *NA_NodeValue; NODE_TYPE NA_NodeType; Node *Creator; NodeAct *ParentNode; NodeAct *FirstChild; NodeAct *LastChild; NodeAct *OwnerNode; NodeAct *NextSibling; NodeAct *PrevSibling; NodeAct *FirstAttr; NodeAct *LastAttr; private: void deleteNodeTree(NodeAct *na); bool findNodeFromRef(NodeAct *from, NodeAct *find); #ifdef DEBUG_CLEANUP bool m_bDeleted; #endif }; #endif
c09268ac35064d4646303e566e3a2f2efe682e92
017f4a4aa14b740d84cc5ed7817ff904bbf2258d
/WPI_3_IMGD_3000_Game_Engine/BAM productions Blades of the High Seas/dragonfly/src/Position.cpp
62b20177ab31eb1079e00eb9ddd9b0e392be20b2
[]
no_license
ezraezra101/coursework
ff4ea60c924c3d4c4f43ae444156ced2d5dd482f
7048a8fa16db897e31b73c2ac497659389943e26
refs/heads/master
2020-06-06T02:59:56.422594
2019-06-18T21:56:04
2019-06-18T21:56:04
192,617,463
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
Position.cpp
#include "Position.h" df::Position::Position(int init_x, int init_y) { x = init_x; y = init_y; } df::Position::Position() { x = 0; y = 0; } void df::Position::setX(int new_x) { x = new_x; } int df::Position::getX() const { return x; } void df::Position::setY(int new_y) { y = new_y; } int df::Position::getY() const { return y; } void df::Position::setXY(int new_x, int new_y) { x = new_x; y = new_y; }
65bf241000470f7e602e300cabccef477ef9793c
b9b966952e88619c9c5d754fea0f0e25fdb1a219
/libcaf_net/caf/net/http/with.hpp
f209ef65ff8b20dedca80cfc81e19ed81d237a4d
[]
permissive
actor-framework/actor-framework
7b152504b95b051db292696a803b2add6dbb484d
dd16d703c91e359ef421f04a848729f4fd652d08
refs/heads/master
2023-08-23T18:22:34.479331
2023-08-23T09:31:36
2023-08-23T09:31:36
1,439,738
2,842
630
BSD-3-Clause
2023-09-14T17:33:55
2011-03-04T14:59:50
C++
UTF-8
C++
false
false
1,717
hpp
with.hpp
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/net/dsl/base.hpp" #include "caf/net/dsl/generic_config.hpp" #include "caf/net/dsl/has_accept.hpp" #include "caf/net/dsl/has_connect.hpp" #include "caf/net/dsl/has_context.hpp" #include "caf/net/http/config.hpp" #include "caf/net/http/request.hpp" #include "caf/net/http/router.hpp" #include "caf/net/http/server_factory.hpp" #include "caf/net/multiplexer.hpp" #include "caf/net/ssl/context.hpp" #include "caf/net/tcp_accept_socket.hpp" #include "caf/fwd.hpp" #include <cstdint> namespace caf::net::http { /// Entry point for the `with(...)` DSL. class with_t : public extend<dsl::base, with_t>:: // with<dsl::has_accept, dsl::has_context> { public: template <class... Ts> explicit with_t(multiplexer* mpx) : config_(make_counted<base_config>(mpx)) { // nop } with_t(with_t&&) noexcept = default; with_t(const with_t&) noexcept = default; with_t& operator=(with_t&&) noexcept = default; with_t& operator=(const with_t&) noexcept = default; /// @private base_config& config() { return *config_; } /// @private template <class T, class... Ts> auto make(dsl::server_config_tag<T> token, Ts&&... xs) { return server_factory{token, *config_, std::forward<Ts>(xs)...}; } private: intrusive_ptr<base_config> config_; }; inline with_t with(actor_system& sys) { return with_t{multiplexer::from(sys)}; } inline with_t with(multiplexer* mpx) { return with_t{mpx}; } } // namespace caf::net::http
c0c1f266c319aeebbf56a51718202b864b7a48d8
5a1568a5df5bdad68cd6f26428a50b49b7c08835
/CGT521YetAgain/CGTLibrary/PhongLight.h
864c8a7f8bab6e635ce44964db79e016a9bd7772
[]
no_license
nemediano/OpenGLHomeworks
15936971762b2d1334e77a1ff2f023ed850365ac
281013b3303701a4f30c7b25bbd9880d2bc5e9f0
refs/heads/master
2021-01-18T21:57:50.764201
2017-06-13T22:48:50
2017-06-13T22:48:50
41,044,699
0
0
null
null
null
null
UTF-8
C++
false
false
510
h
PhongLight.h
#ifndef PHONG_LIGHT_H_ #define PHONG_LIGHT_H_ namespace lighting { class PhongLight { private: glm::vec3 m_La; glm::vec3 m_Ls; glm::vec3 m_Ld; public: PhongLight(); PhongLight(const PhongLight& other); PhongLight(const glm::vec3& La, const glm::vec3& Ld, const glm::vec3& Ls); void setLa(const glm::vec3& La); void setLd(const glm::vec3& Ld); void setLs(const glm::vec3& Ls); glm::vec3 getLa() const; glm::vec3 getLd() const; glm::vec3 getLs() const; ~PhongLight(); }; } #endif
9a2bab4f781fea817838719fac1b042a0edbd700
98b1e51f55fe389379b0db00365402359309186a
/homework_6/problem_2/10x10/0.153/T
9220a7920b1527542e43579b974e20497de6fed8
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
2,037
T
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.153"; object T; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 1 0 0 0]; internalField nonuniform List<scalar> 100 ( 49.4043 7.48373 -2.09865 -1.9579 -0.817861 -0.248574 -0.0614096 -0.0129509 -0.00240539 -0.000352505 92.6801 49.791 19.5384 6.03377 1.53218 0.329182 0.0609976 0.00987133 0.00140609 0.000159955 106.68 79.5561 41.0954 16.053 5.03484 1.32026 0.297842 0.0590315 0.0104733 0.00148622 110.12 92.9842 52.6485 21.9932 7.26346 1.98587 0.464032 0.0948277 0.0172935 0.00251019 110.755 97.566 57.0545 24.4089 8.21196 2.27936 0.53948 0.111489 0.0205389 0.00300621 110.834 98.8364 58.3795 25.1702 8.52119 2.37766 0.565326 0.11731 0.0216929 0.00318513 110.835 99.1346 58.7112 25.3682 8.60388 2.40456 0.572543 0.118964 0.0220263 0.00323753 110.833 99.1956 58.782 25.4112 8.62203 2.41049 0.574135 0.119328 0.0220994 0.00324896 110.832 99.2063 58.7974 25.4224 8.62758 2.41258 0.574779 0.119496 0.0221372 0.00325552 110.832 99.2089 58.7957 25.4182 8.62436 2.41103 0.574215 0.119331 0.0220968 0.00324787 ) ; boundaryField { left { type fixedValue; value uniform 100; } right { type zeroGradient; } up { type zeroGradient; } down { type fixedValue; value uniform 0; } frontAndBack { type empty; } } // ************************************************************************* //
5df7bbb9d6e76dcd052c351246734da363fd2146
2f768d02ff8d25b723a0ab2428f8a8dcdefb3e11
/huffman/decompress.cpp
98e6be369c36792f6aa264dd2328d52d31681746
[ "MIT" ]
permissive
cuklev/huffman-archiver-cpp
7ac3f92d5d5a5a44e1a2018bde20057a89b6af2d
c2c2ac8e11e6957f3d68c895c5d36bccf93b7271
refs/heads/master
2021-01-11T14:35:15.983219
2017-02-03T15:25:43
2017-02-03T15:25:43
80,166,968
6
1
null
2017-02-03T10:13:45
2017-01-26T23:48:26
C++
UTF-8
C++
false
false
807
cpp
decompress.cpp
#include "decompress.hpp" #include "huffman.hpp" void dfs(BinaryRead& bin_in, HuffmanNode* const node) { if(bin_in()) { putChar(node, bin_in.readUnalignedByte()); } else { dfs(bin_in, makeLeftChild(node)); dfs(bin_in, makeRightChild(node)); } } void decompress(BinaryRead& bin_in, std::ostreambuf_iterator<char>& out_iterator) { auto bytes_left = bin_in.readUnalignedUInt64(); if(bytes_left == 0) return; auto root = makeNode(); dfs(bin_in, root); if(auto result = isLeaf(root)) { while(bytes_left > 0) { *out_iterator = result.value(); --bytes_left; } return; } auto node = root; while(true) { node = goDown(node, bin_in()); if(auto result = isLeaf(node)) { *out_iterator = result.value(); --bytes_left; if(bytes_left == 0) break; node = root; } } }
61192dcedc6b656efede68bf29e0281ac7ab6b68
2f71acd47b352909ca2c978ad472a082ee79857c
/src/tenkei/024.cpp
914ab313ee3ed67d815634d287ef84d2666a70e5
[]
no_license
imoted/atCoder
0706c8b188a0ce72c0be839a35f96695618d0111
40864bca57eba640b1e9bd7df439d56389643100
refs/heads/master
2022-05-24T20:54:14.658853
2022-03-05T08:23:49
2022-03-05T08:23:49
219,258,307
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
024.cpp
// This file is a "Hello, world!" in C++ language by GCC for wandbox. #include <iostream> #include <cstdlib> #include <vector> int main() { int n, k; std::cin >> n >> k; std::vector<int> a(n); std::vector<int> b(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } for (int i = 0; i < n; i++) { std::cin >> b[i]; } int ans = 0; for (int i = 0; i < n; i++) { ans += std::abs(a[i] - b[i]); } if ((k - ans) % 2 == 0 && (k - ans) >= 0) std::cout << "Yes" << std::endl; else std::cout << "No" << std::endl; }
5e5ec934563284dfafdca15007da24d9c9cb7469
ad471c614aa777622e6a1c2c433cbc8d0a544df1
/main.cpp
90d45afc097c05e3656fa5f5b62521bc4c10be6b
[]
no_license
SilverCV/SDL2Player
85a3bddc6630e19d11abe9f8a9a82769899bcd85
2891495c45d08b70c0d4f3c2eb813308e1ea488e
refs/heads/main
2023-01-04T19:22:58.230649
2020-11-10T01:02:22
2020-11-10T01:02:22
311,504,863
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
cpp
main.cpp
#include <SDL2/SDL.h> #include <iostream> int WIDTH = 640; int HEIGHT = 480; int thread_exit = 0; int fresh(void *data){ while (thread_exit==0){ SDL_Event event; event.type = SDL_DISPLAYEVENT; SDL_PushEvent(&event); SDL_Delay(40); } } int main(int argc, char *argv[]) { //初始化 if (SDL_Init(SDL_INIT_EVERYTHING)) { std::cout << "fail to init sdl " << SDL_GetError() << std::endl; return -1; } //窗口 SDL_Window *p_window = SDL_CreateWindow("yuv player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_RESIZABLE); if (p_window == NULL) { std::cout << "fail to create window" << std::endl; return -1; } //渲染 SDL_Renderer *p_render = SDL_CreateRenderer(p_window, -1, 0); if (p_render == NULL){ std::cout << "fail to create render" << SDL_GetError() << std::endl; return -1; } //纹理 SDL_Texture *p_texture = SDL_CreateTexture(p_render,SDL_PIXELFORMAT_IYUV,SDL_TEXTUREACCESS_STREAMING,WIDTH,HEIGHT); if (p_texture == NULL){ std::cout << "fail to create texture " << SDL_GetError() << std::endl; return -1; } SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = WIDTH; rect.h = HEIGHT; //读取文件 FILE *fp = fopen(argv[1],"rb+"); uint8_t buffer[WIDTH*HEIGHT*12/8]; SDL_Thread *p_refresh = SDL_CreateThread(fresh,NULL,NULL); while(true){ SDL_Event event; SDL_WaitEvent(&event); if(event.type == SDL_DISPLAYEVENT) { //读取yuv数据 if (fread(buffer, 1, WIDTH * HEIGHT * 12 / 8, fp) != WIDTH * HEIGHT * 12 / 8) { fseek(fp, 0, SEEK_SET); fread(buffer, 1, WIDTH * HEIGHT * 12 / 8, fp); } //更新和播放 SDL_UpdateTexture(p_texture, NULL, buffer, WIDTH); SDL_RenderClear(p_render); SDL_RenderCopy(p_render, p_texture, NULL, &rect); SDL_RenderPresent(p_render); SDL_Delay(40); }else if (event.type == SDL_WINDOWEVENT){ SDL_GetWindowSize(p_window,&WIDTH,&HEIGHT); } else if (event.type == SDL_QUIT){ break; } } fclose(fp); SDL_DestroyTexture(p_texture); SDL_DestroyRenderer(p_render); SDL_DestroyWindow(p_window); SDL_Quit(); return 0; }
44a5b376dcc7ea41ccf1107fa71c065c838fd55b
533eebd4de3add199cd263d710361d2d56c5b299
/tree_mutex.h
92d1077e5a047e1938f67d19acf4753c80b23126
[]
no_license
pavelstrokan/parallel
6b1dc6773f94c7780503bc5e60bcfbd3a45a2bd6
33323ffd3d512b46d35941ff1b9c4186655913bc
refs/heads/master
2021-01-01T05:13:07.283915
2016-05-26T22:58:08
2016-05-26T22:58:08
56,264,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,590
h
tree_mutex.h
#include <thread> #include <iostream> #include <vector> #include <atomic> #include <array> class peterson_mutex{ public: peterson_mutex() { want[0].store(false); want[1].store(false); victim.store(0); } void lock (size_t index); void unlock(size_t index); private: std::array<std::atomic<bool>, 2> want; std::atomic<size_t> victim; }; void peterson_mutex::lock (size_t index) { want[index].store(true); victim.store(index); while(want[1 - index].load() && victim.load() == index) { std::this_thread::yield(); } } void peterson_mutex::unlock(size_t index) { want[index].store(false); } class tree_mutex { public: tree_mutex(size_t n): num(n), tree(2 * two_pow(n) - 1) {} void lock(size_t index); void unlock(size_t index); private: size_t num; std::vector<peterson_mutex> tree; int two_pow(int n) { int pow = 1; while(pow < (n + 1) / 2) pow *= 2; return pow; } }; void tree_mutex::lock(size_t index) { size_t id = tree.size() + index; while(id != 0) { tree[(id - 1) / 2].lock((id + 1) & 1); id = (id - 1) / 2; } } void tree_mutex::unlock(size_t index) { size_t depth = 0; while ((1 << depth) < num) depth++; size_t mutex_id = 0; for (int i = depth - 1; i >= 0; i--) { size_t bit = (index >> i) & 1; tree[mutex_id].unlock(bit); mutex_id = mutex_id * 2 + bit + 1; } }
b067000077b1d3e3a0c2a6d2bf3a166a30722218
81d62bdfac49eebbaae975b7721f638b811fc15d
/Library.cpp
87a07ab9344470b31f4ec342f1df33a69f6aa23b
[]
no_license
taedud/LibSys
8fa7abe0782996f3e2d57138f2523a5bf32913b3
0ee09f3dfe2484e8e6c8ebbee8c5cde14652b810
refs/heads/master
2023-01-13T22:27:33.561551
2020-11-20T08:59:42
2020-11-20T08:59:42
314,497,390
0
0
null
null
null
null
UTF-8
C++
false
false
1,953
cpp
Library.cpp
#include "Library.hpp" #include <list> #include <string.h> #include <string> Book::Book() { memset(this->name, 0x00, MAX_NAME_LEN + 1); memset(this->category, 0x00, MAX_NAME_LEN + 1); this->year = 0; this->month = 0; this->day = 0; this->ryear = 0; this->rmonth = 0; this->rday = 0; } Book::Book(std::string name, std::string category) { memcpy(this->name, name.c_str(), MAX_NAME_LEN); memcpy(this->category, category.c_str(), MAX_NAME_LEN); this->year = 0; this->month = 0; this->day = 0; this->ryear = 0; this->rmonth = 0; this->rday = 0; } Book::Book(std::string name, std::string category, int year, int month, int day, int ryear, int rmonth, int rday) { memcpy(this->name, name.c_str(), MAX_NAME_LEN); memcpy(this->category, category.c_str(), MAX_NAME_LEN); this->year = year; this->month = month; this->day = day; this->ryear = ryear; this->rmonth = rmonth; this->rday = rday; } void Book::setName(std::string name) { memcpy(this->name, name.c_str(), MAX_NAME_LEN); } void Book::setCategory(std::string category) { memcpy(this->category, category.c_str(), MAX_NAME_LEN); } void Book::setYear(int year) { this->year = year; } void Book::setMonth(int month) { this->month = month; } void Book::setDay(int day) { this->day = day; } void Book::setRyear(int ryear) { this->ryear = ryear; } void Book::setRmonth(int rmonth) { this->rmonth = rmonth; } void Book::setRday(int rday) { this->rday = rday; } std::string Book::getName(void) { return std::string(this->name); } std::string Book::getCategory(void) { return std::string(this->category); } int Book::getYear(void) { return this->year; } int Book::getMonth(void) { return this->month; } int Book::getDay(void) { return this->day; } int Book::getRyear(void) { return this->ryear; } int Book::getRmonth(void) { return this->rmonth; } int Book::getRday(void) { return this->rday; }
7c6c78077ee8092154d86d5e8c6e9dc700a0c8a9
20a831d3cb5788f31d607d48bd6e3cc68a860556
/auto_nav/src/agri_costmap_layer_v2.cpp
97250e59384b31666cdb87ddc60273bbc1baf7e9
[]
no_license
vigneshrajap/vision-based-navigation-agri-fields
8f17affc2c9e80bc1b325060a25e2a0bf2640781
c179dff7eb3d25179b2995412aeaf5f6d950c6ff
refs/heads/master
2022-01-17T05:55:04.278192
2022-01-14T11:10:51
2022-01-14T11:10:51
208,878,598
12
3
null
null
null
null
UTF-8
C++
false
false
10,197
cpp
agri_costmap_layer_v2.cpp
#include "agri_costmap_layer_v2.h" PLUGINLIB_EXPORT_CLASS(custom_layer::AgriCostmapLayer_v2, costmap_2d::Layer) namespace custom_layer{ void AgriCostmapLayer_v2::onInitialize() { ros::NodeHandle g_nh; current_ = true; vec_sub = g_nh.subscribe("vector_poses", 100, &AgriCostmapLayer_v2::vecposeCallback, this); curr_node_sub = g_nh.subscribe("current_node", 100, &AgriCostmapLayer_v2::currnodeCallback, this); ros::Rate r(10); while (g_nh.ok()&&(vector_receive==0)){ ros::spinOnce(); if(costmap_status==1){ dsrv_ = new dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>(g_nh); dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>::CallbackType f = boost::bind( &AgriCostmapLayer_v2::reconfigureCB, this, _1, _2); dsrv_->setCallback(f); costmap_status= 0; } // std::cout << costmap_status << " " << enabled_ << " " << vector_receive << std::endl; r.sleep(); } } AgriCostmapLayer_v2::~AgriCostmapLayer_v2(){ if(dsrv_) delete dsrv_; } void AgriCostmapLayer_v2::reconfigureCB(auto_nav::custom_costmap_paramsConfig &config, uint32_t level){ Total_Layers = config.Total_Layers; Layer.resize(Total_Layers); x_.resize(Total_Layers); y_.resize(Total_Layers); if(0<Layer.size()) Layer[0] = config.FirstLayer; if(1<Layer.size()) Layer[1] = config.SecondLayer; if(2<Layer.size()) Layer[2] = config.ThirdLayer; if(3<Layer.size()) Layer[3] = config.FourthLayer; if(4<Layer.size()) Layer[4] = config.FifthLayer; costmap_height = config.Costmap_Height; costmap_width = config.Cost_Propagation_Area; costmap_radius = config.Costmap_Radius; pts = config.TotalSegmentPts; P.resize(pts*2); if(costmap_status==1) //(costmap_status==1)&& enabled_ = config.enabled; else enabled_ = false; //if(on_curved_lane == 0) costmap_width = config.Cost_Propagation_Area; //if(on_curved_lane == 1) costmap_width = 0.9; // ROS_INFO("Agri-Costmaps is up!!"); } void AgriCostmapLayer_v2::vecposeCallback (const geometry_msgs::PoseArray::ConstPtr& vec_msg){ if(vec_msg->poses.size()>0){ vec.resize(vec_msg->poses.size()); yaw_a.resize(vec_msg->poses.size()); for(int v=0; v < vec_msg->poses.size(); v++){ cv::Point2f vec_c(vec_msg->poses[v].position.x, vec_msg->poses[v].position.y); vec.push_back(vec_c); yaw_a.push_back(tf::getYaw(vec_msg->poses[0].orientation)); } if(vector_receive==0){ costmap_status = 1; //temp vector_receive = 1; } } } // Vec callback void AgriCostmapLayer_v2::currnodeCallback(const std_msgs::String::ConstPtr& curr_node_msg){ // Current Topological Node str_name = curr_node_msg->data; // if((str_name=="WayPoint59")){ // Entering curves Frogn_Fields: WayPoint1 Polytunnels:WayPoint134 // costmap_status = 1; // // dsrv_ = new dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>(nh); // dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>::CallbackType f = boost::bind( // &AgriCostmapLayer_v2::reconfigureCB, this, _1, _2); // dsrv_->setCallback(f); // } // // if((str_name=="WayPoint34")){ // Entering curves Frogn_Fields: WayPoint2 Polytunnels:WayPoint99 // costmap_status = 0; // dsrv_ = new dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>(nh); // dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>::CallbackType f = boost::bind( // &AgriCostmapLayer_v2::reconfigureCB, this, _1, _2); // dsrv_->setCallback(f); // } // // if((str_name=="WayPoint6")){ // Entering curves // on_curved_lane = 0; // // dsrv_ = new dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>(nh); // dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>::CallbackType f = boost::bind( // &AgriCostmapLayer_v2::reconfigureCB, this, _1, _2); // dsrv_->setCallback(f); // } // // if((str_name=="WayPoint4")){ // Entering curves // on_curved_lane = 1; // // dsrv_ = new dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>(nh); // dynamic_reconfigure::Server<auto_nav::custom_costmap_paramsConfig>::CallbackType f = boost::bind( // &AgriCostmapLayer_v2::reconfigureCB, this, _1, _2); // dsrv_->setCallback(f); // } } cv::Point2f AgriCostmapLayer_v2::rotate_vector(cv::Point2f vec_pt, cv::Point2f l_pt, float vec_yaw){ // Rotate the points around the vector cv::Point2f l_pt_rot; double c = cos(vec_yaw), s = sin(vec_yaw); l_pt_rot.x = vec_pt.x+(c*(l_pt.x-vec_pt.x)-s*(l_pt.y-vec_pt.y)); l_pt_rot.y = vec_pt.y+(s*(l_pt.x-vec_pt.x)+c*(l_pt.y-vec_pt.y)); return l_pt_rot; } void AgriCostmapLayer_v2::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y, double* max_x, double* max_y) { if (!enabled_) return; if(Total_Layers>0){ //update the area around the costmap layer *min_x = std::min(robot_x+10*Total_Layers*costmap_height, robot_x-10*Total_Layers*costmap_height); *min_y = std::min(robot_y+10*Total_Layers*costmap_width, robot_y-10*Total_Layers*costmap_width); *max_x = std::max(robot_x+10*Total_Layers*costmap_height, robot_x-10*Total_Layers*costmap_height); *max_y = std::max(robot_y+10*Total_Layers*costmap_width, robot_y-10*Total_Layers*costmap_width); } } // updateBounds void AgriCostmapLayer_v2::updateCosts(costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j){ if (!enabled_) return; unsigned int mx, my; double cell_size = master_grid.getResolution(); for(int v = 0; v < vec.size(); v++){ // Each Vector Pose Loop // Rotate the lines around the pose vector std::vector<cv::Point2f> P_i; P_i.resize(4); P_i[0] = cv::Point2f(vec[v].x-costmap_height, vec[v].y-costmap_width); P_i[1] = cv::Point2f(vec[v].x+costmap_height, vec[v].y-costmap_width); P_i[2] = cv::Point2f(vec[v].x-costmap_height, vec[v].y+costmap_width); P_i[3] = cv::Point2f(vec[v].x+costmap_height, vec[v].y+costmap_width); for(int p=0;p<pts; p++){ // Line Segments for L1 and L2 P[2*p] = (P_i[0]*(1-(float(p)/pts)))+(P_i[1]*(float(p)/pts)); //L1_e1 P[2*p] = rotate_vector(vec[v], P[(2*p)], yaw_a[v]); // rotate the line points by vector P[(2*p)+1] = (P_i[2]*(1-(float(p)/pts)))+(P_i[3]*(float(p)/pts)); //L2_e1 P[(2*p)+1] = rotate_vector(vec[v], P[(2*p)+1], yaw_a[v]); // rotate the line points by vector } for (int k = 0; k < P.size(); k++) // Update the costs of each grid cell { if(master_grid.worldToMap(P[k].x, P[k].y, mx, my)) // Update the line points as grid cells { if(master_grid.getCost(mx, my)==FREE_SPACE) { master_grid.setCost(mx, my, Layer[0]); } } } // Update the costs of each grid cell // for(int w = 1; w < x_.size(); w++) // revert the size of the circle co-ordinates array for next iteration // { // x_[w].resize(0); y_[w].resize(0); // } // // std::vector<cv::Point2f> topLeft, topRight, bottomLeft, bottomRight; // topLeft.resize(0); topRight.resize(0); bottomLeft.resize(0); bottomRight.resize(0); // std::vector<cv::Point2f> l1, l2; // std::vector<double> x_t, y_t; // // for(int q = 0; q < P.size(); q++) // Line Segments for L1 and L2 // { // // for(int n = 1; n < Total_Layers; n++) // Each Costmap Layer // { // // // Create the boundaries for the designated radius // topLeft.push_back(cv::Point2f(P[q].x+n*costmap_radius, P[q].y+n*costmap_radius)); // topRight.push_back(cv::Point2f(P[q].x+n*costmap_radius, P[q].y-n*costmap_radius)); // bottomLeft.push_back(cv::Point2f(P[q].x-n*costmap_radius, P[q].y+n*costmap_radius)); // bottomRight.push_back(cv::Point2f(P[q].x-n*costmap_radius, P[q].y-n*costmap_radius)); // // l1.resize(0); l2.resize(0); x_t.resize(0); y_t.resize(0); // // // Find the circle co-ordinates according to costmap radius // for(int r = 0; r < pts; r++) // rect co-ordinates // { // l1.push_back((topLeft.back()*(1-(float(r)/pts)))+(bottomLeft.back()*(float(r)/pts))); // l2.push_back((topRight.back()*(1-(float(r)/pts)))+(bottomRight.back()*(float(r)/pts))); // // for(int u = 0; u < pts; u++) // { // x_t.push_back((l1.back().x*(1-(float(u)/pts)))+(l2.back().x*(float(u)/pts))); // y_t.push_back((l1.back().y*(1-(float(u)/pts)))+(l2.back().y*(float(u)/pts))); // // if(sqrt(pow(x_t.back()-P[q].x,2)+pow(y_t.back()-P[q].y,2))<(n*costmap_radius)) // circle co-ordinates // { // x_[n].push_back(x_t.back()); // y_[n].push_back(y_t.back()); // } // // } // // } // rect co-ordinates // // } // Each Costmap Layer // // } // Line Segments for L1 and L2 // // for(int n = 1; n < Total_Layers; n++) // Each Costmap Layer // { // // if((x_[n].size()>0)&&(y_[n].size()>0)) // UpdateBounds check // { // // // Assign the cost from circle co-ordinates // for(int i = 0; i < x_[n].size(); i++) // { // // //for(int j = 0; j < y_[n].size(); j++) // //{ // // if(master_grid.worldToMap(x_[n][i], y_[n][i], mx, my)) // Update the line points as grid cells // { // if(master_grid.getCost(mx, my)==FREE_SPACE) // { // master_grid.setCost(mx, my, Layer[n]); // } // } // // //} // // } // // } // UpdateBounds check // // } // Each Costmap Layer } // For loop for each vector poses } // updateCosts } // end namespace
2c5e9bb79a4ff5be6e60075a337b0673b93ca750
b9f8f7d126677e98c09aa17d09a070af316be59d
/背包九讲/4_多重背包问题.cpp
60336b92d8cd3761fa6f9bf88ff5190a56386dbc
[]
no_license
BinXUU/alg-daily
9295479fe8f1c49b7ae3f38614efdcd5b466582e
c927b9a66ca75d27fd9d6465e5793dda8eadbb8c
refs/heads/master
2022-02-25T15:31:56.383583
2019-10-05T03:34:01
2019-10-05T03:34:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
4_多重背包问题.cpp
#include <iostream> #include <stdio.h> #include <string.h> #include <vector> #include <algorithm> #include <queue> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; const int M = 1e3 + 10; const int mod = 1e9 + 7; int weight[M],value[M],nums[M]; //优化一:二维数组变为一维数组 // int dp[M][M]; int dp[M]; int n,total; //O(NV) int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int add_w=0,add_v=0; cin>>n>>total; for (int i = 1; i <= n; i++) cin>>weight[i]>>value[i]>>nums[i]; for (int i = 1; i <=n ; i++) { for (int j = total; j >=0; j--) { for (int k = 0; k <nums[i]; k++) { add_w+=weight[i]; add_v+=value[i]; if(j-add_w<0){break;} dp[j]=max(dp[j-add_w]+add_v,dp[j]); } add_w=0; add_v=0; } } cout<<dp[total]; return 0; }
180bd6260a45366fef13dd981a00c4d4a789dbad
539f01f2c2b4bcc019738d829aadff3f3ea84d5e
/WebPuppeteerTab.cpp
a7f8c148993373b194279a8f2213ffca04ee8d4d
[ "MIT" ]
permissive
MagicalTux/webpuppeteer
2e4ec9ba439e3d815c837ceab1ee57fbcb6f936b
cb41410d3efc70681c9409fc185b6cb444af5ad6
refs/heads/master
2021-01-13T02:31:34.063401
2019-01-21T04:41:10
2019-01-21T04:41:10
5,094,886
6
2
null
null
null
null
UTF-8
C++
false
false
18,611
cpp
WebPuppeteerTab.cpp
#include "WebPuppeteerTab.hpp" #include "WebPuppeteerWebElement.hpp" #include "WebPuppeteer.hpp" #include <QEventLoop> #include <QWebFrame> #include <QPainter> #include <QPrinter> #include <QWebView> #include <QNetworkReply> #include <QEvent> #include <QKeyEvent> #include <QTimer> #include <QBuffer> #include <QTemporaryFile> #include "TimeoutTrigger.hpp" WebPuppeteerTabNetSpy::WebPuppeteerTabNetSpy(QObject *parent): QNetworkAccessManager(parent) { connect(this, SIGNAL(finished(QNetworkReply*)), this, SLOT(spyFinished(QNetworkReply*))); cnx_count = 0; cnx_index = 0; data_output = NULL; } int WebPuppeteerTabNetSpy::getCount() const { return cnx_count; } void WebPuppeteerTabNetSpy::setOutputFile(QFile *output) { if (data_output != NULL) { data_output->close(); data_output->deleteLater(); } data_output = output; if (data_output != NULL) { // write version qint64 p = 1+8+8+8; data_output->write((const char *)&p, sizeof(p)); data_output->write(QByteArray(1, '\xff')); // version // timestamp qint64 t = QDateTime::currentMSecsSinceEpoch(); data_output->write((const char *)&t, sizeof(t)); // query id (zero) p = 0; data_output->write((const char *)&p, sizeof(p)); // version p = 0x01; data_output->write((const char *)&p, sizeof(p)); } } QNetworkReply *WebPuppeteerTabNetSpy::createRequest(Operation op, const QNetworkRequest &oreq, QIODevice *outgoingData) { cnx_index += 1; // we end duplicating request :( QNetworkRequest req = oreq; req.setAttribute(QNetworkRequest::User, cnx_index); if (data_output != NULL) { // store request in output file QByteArray op_str; // fetch HTTP operation switch (op) { case QNetworkAccessManager::HeadOperation: op_str = "HEAD"; break; case QNetworkAccessManager::GetOperation: op_str = "GET"; break; case QNetworkAccessManager::PutOperation: op_str = "PUT"; break; case QNetworkAccessManager::PostOperation: op_str = "POST"; break; case QNetworkAccessManager::DeleteOperation: op_str = "DELETE"; break; case QNetworkAccessManager::CustomOperation: op_str = req.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray(); break; case QNetworkAccessManager::UnknownOperation: op_str = "????"; break; } // store request, first store size qint64 p = 0; data_output->write((const char *)&p, sizeof(p)); // keep start of record position in memory p = data_output->pos() - sizeof(p); // write request data_output->write(QByteArray(1, '\x01')); // write time qint64 t = QDateTime::currentMSecsSinceEpoch(); data_output->write((const char *)&t, sizeof(t)); data_output->write((const char *)&cnx_index, sizeof(cnx_index)); data_output->write(op_str + QByteArray(1, 0) + req.url().toEncoded() + QByteArray(1, 0)); // write headers QList<QByteArray> h = req.rawHeaderList(); // header count int h_size = h.size(); data_output->write((const char *)&h_size, sizeof(h_size)); // each request header for (int i = 0; i < h.size(); ++i) { data_output->write(h.at(i) + QByteArray(1, 0) + req.rawHeader(h.at(i)) + QByteArray(1, 0)); } // write body, if any if (outgoingData != NULL) { qint64 out_pos = outgoingData->pos(); qint64 out_end = outgoingData->size(); qint64 out_len = out_end - out_pos; data_output->write((const char *)&out_len, sizeof(out_len)); if (out_len > 0) { // write actual data char buf[8192]; while(true) { qint64 c = outgoingData->read((char*)&buf, sizeof(buf)); if (c == 0) { break; } if (c == -1) { // wtf? qDebug("error reading outgoingData"); break; } data_output->write((const char*)&buf, c); } // reset position to initial state (hopefully seekable) outgoingData->seek(out_pos); } } // now write size of record qint64 final_pos = data_output->pos(); qint64 d_size = final_pos - p - sizeof(p); data_output->seek(p); data_output->write((const char*)&d_size, sizeof(d_size)); data_output->seek(final_pos); } //qDebug("Req: %s %s", qPrintable(op_str), qPrintable(req.url().toString())); QNetworkReply *reply = QNetworkAccessManager::createRequest(op, req, outgoingData); if (data_output != NULL) { connect(reply, SIGNAL(readyRead()), this, SLOT(spyConnectionData())); connect(reply, SIGNAL(metaDataChanged()), this, SLOT(spyMetaData())); } if (cnx_count == 0) started(); cnx_count++; return reply; } void WebPuppeteerTabNetSpy::spyMetaData() { if (data_output == NULL) { return; } QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); qint64 id = reply->request().attribute(QNetworkRequest::User).value<qint64>(); // store all headers via rawHeaderPairs() QBuffer *buf = new QBuffer(); buf->open(QBuffer::ReadWrite); // metadata update buf->write(QByteArray(1, '\x03')); // write time qint64 t = QDateTime::currentMSecsSinceEpoch(); buf->write((const char *)&t, sizeof(t)); // write request id buf->write((const char *)&id, sizeof(id)); int http_status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QByteArray http_reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(); buf->write((const char *)&http_status_code, sizeof(http_status_code)); buf->write(http_reason + QByteArray(1, 0)); // write headers const QList<QNetworkReply::RawHeaderPair> &headers = reply->rawHeaderPairs(); // headers count int h_size = headers.size(); buf->write((const char *)&h_size, sizeof(h_size)); for(int i = 0; i < headers.length(); i++) { const QPair<QByteArray,QByteArray> &v = headers.at(i); buf->write(v.first + QByteArray(1, 0) + v.second + QByteArray(1, 0)); } const QByteArray &b = buf->data(); qint64 p = b.length(); data_output->write((const char *)&p, sizeof(p)); data_output->write(b); } void WebPuppeteerTabNetSpy::spyConnectionData() { if (data_output == NULL) { return; } QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); qint64 ba = reply->bytesAvailable(); if (ba == 0) { return; } qint64 id = reply->request().attribute(QNetworkRequest::User).value<qint64>(); //qDebug("SPY: #%lld pos %lld ba %lld", id, reply->pos(), ba); // we're assuming other recipient of QNetworkReply bytesAvailable() signal will always consume the whole buffer QByteArray sdata = reply->peek(ba); // write partial response data qint64 p = 1+8+8+ba; // qint64 + qint64 + ba data_output->write((const char *)&p, sizeof(p)); data_output->write(QByteArray(1, '\x02')); // write time qint64 t = QDateTime::currentMSecsSinceEpoch(); data_output->write((const char *)&t, sizeof(t)); // write request id data_output->write((const char *)&id, sizeof(id)); // write data data_output->write(sdata, ba); } void WebPuppeteerTabNetSpy::spyFinished(QNetworkReply*reply) { if (data_output != NULL) { qint64 id = reply->request().attribute(QNetworkRequest::User).value<qint64>(); qint64 p = 1+8+8; data_output->write((const char *)&p, sizeof(p)); data_output->write(QByteArray(1, '\x04')); // end of request // write time qint64 t = QDateTime::currentMSecsSinceEpoch(); data_output->write((const char *)&t, sizeof(t)); // write request id data_output->write((const char *)&id, sizeof(id)); data_output->flush(); } cnx_count--; if (cnx_count == 0) allFinished(); } WebPuppeteerTab::WebPuppeteerTab(WebPuppeteer *_parent): QWebPage(_parent) { parent = _parent; spy = new WebPuppeteerTabNetSpy(this); // define standard values setViewportSize(QSize(1024,768)); setForwardUnsupportedContent(true); setNetworkAccessManager(spy); connect(this, SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(downloadFile(QNetworkReply*))); connect(networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,const QList<QSslError>&)), this, SLOT(handleSslErrors(QNetworkReply*,const QList<QSslError>&))); } bool WebPuppeteerTab::saveNetwork(const QString &filename) { if (filename == "") { spy->setOutputFile(NULL); // will cause previous qfile to be closed return true; } QFile *f = new QFile(filename); if (!f->open(QIODevice::WriteOnly | QIODevice::Truncate)) { qDebug("saveNetwork: failed to create output file %s", qPrintable(filename)); return false; } spy->setOutputFile(f); return true; } QWebPage *WebPuppeteerTab::createWindow(WebWindowType) { // we don't care about the type, since modal has no meaning here WebPuppeteerTab *tab = new WebPuppeteerTab(parent); // inherit settings tab->user_agent = user_agent; queue.append(tab); return tab; } QScriptValue WebPuppeteerTab::getNewWindow() { if (queue.size() == 0) return parent->engine().nullValue(); return parent->engine().newQObject(queue.takeFirst(), QScriptEngine::ScriptOwnership); } void WebPuppeteerTab::trustCertificate(const QString &hash) { trusted_certificates.insert(QByteArray::fromHex(hash.toLatin1())); } void WebPuppeteerTab::handleSslErrors(QNetworkReply *reply,const QList<QSslError>&list) { bool ignore_ok = true; for(int i = 0; i < list.size(); i++) { bool this_ignore_ok = false; switch(list.at(i).error()) { case QSslError::UnableToGetLocalIssuerCertificate: case QSslError::CertificateUntrusted: case QSslError::UnableToVerifyFirstCertificate: { QByteArray hash = list.at(i).certificate().digest(QCryptographicHash::Sha1); if (trusted_certificates.contains(hash)) { this_ignore_ok = true; // qDebug("Ignorable SSL error"); } else { qDebug("The following error could be ignored by calling tab.trustCertificate(\"%s\")", hash.toHex().data()); } } default: break; } if (!this_ignore_ok) { qDebug("SSL Error: %d %s", list.at(i).error(), qPrintable(list.at(i).errorString())); ignore_ok = false; } } if (ignore_ok) { // qDebug("Ignoring SSL errors"); reply->ignoreSslErrors(); } } bool WebPuppeteerTab::shouldInterruptJavaScript() { return true; } void WebPuppeteerTab::javaScriptAlert(QWebFrame*, const QString &msg) { qDebug("Got javascript alert: %s", qPrintable(msg)); } bool WebPuppeteerTab::javaScriptConfirm(QWebFrame*, const QString &msg) { qDebug("Got javascript confirm: %s", qPrintable(msg)); return true; } bool WebPuppeteerTab::javaScriptPrompt(QWebFrame *, const QString &msg, const QString &defaultValue, QString *result) { qDebug("Got javascript prompt: %s", qPrintable(msg)); *result = defaultValue; return false; } bool WebPuppeteerTab::supportsExtension(Extension e) { switch(e) { case QWebPage::ChooseMultipleFilesExtension: return true; case QWebPage::ErrorPageExtension: return true; default: return false; } } bool WebPuppeteerTab::extension(Extension e, ExtensionOption *option, ExtensionReturn *output) { switch(e) { case QWebPage::ChooseMultipleFilesExtension: { if (output == NULL) return false; //ChooseMultipleFilesExtensionReturn *ret = (ChooseMultipleFilesExtensionReturn*)output; // TODO return true; } case QWebPage::ErrorPageExtension: { ErrorPageExtensionOption *opt = (ErrorPageExtensionOption*)option; ErrorPageExtensionReturn *ret = (ErrorPageExtensionReturn*)output; qDebug("HTTP error %d: %s", opt->error, qPrintable(opt->errorString)); if (ret != 0) { ret->baseUrl = QUrl("http://localhost/"); ret->contentType = "text/html"; ret->encoding = "UTF-8"; ret->content = "<h1>Load error</h1><p>Could not load page :(</p>"; } return true; } default: return false; } } void WebPuppeteerTab::downloadFile(QNetworkReply*reply) { // Won't be finished at this point, need to connect() to reply signals to detect end of download // Just in case, check if reply->isFinished() if (reply->isFinished()) { downloadFileFinished(reply); } connect(reply, SIGNAL(finished()), this, SLOT(downloadFileFinished())); } void WebPuppeteerTab::downloadFileFinished(QNetworkReply*reply) { if (reply == NULL) reply = qobject_cast<QNetworkReply*>(sender()); if (reply->error() != QNetworkReply::NoError) { qDebug("error downloading file: %d", reply->error()); return; } QString filename = reply->request().url().path(); int idx = filename.lastIndexOf('/'); if (idx != -1) filename = filename.mid(idx+1); QScriptValue arr = parent->engine().newObject(); arr.setProperty("filename", filename); arr.setProperty("filedata", QString::fromLatin1(reply->readAll().toBase64())); file_queue.append(arr); qDebug("File download success: %s", qPrintable(filename)); } QScriptValue WebPuppeteerTab::getDownloadedFile() { if (file_queue.isEmpty()) return parent->engine().nullValue(); return file_queue.takeFirst(); } WebPuppeteer *WebPuppeteerTab::getParent() { return parent; } bool WebPuppeteerTab::load(const QString &url, int timeout) { mainFrame()->load(QUrl(url)); return wait(timeout); } void WebPuppeteerTab::waitFinish(int idle) { QEventLoop e; TimeoutTrigger t(idle); connect(&t, SIGNAL(timeout()), &e, SLOT(quit())); connect(networkAccessManager(), SIGNAL(started()), &t, SLOT(start())); connect(networkAccessManager(), SIGNAL(allFinished()), &t, SLOT(end())); // if something pending, stop timer if (static_cast<WebPuppeteerTabNetSpy*>(networkAccessManager())->getCount() > 0) t.start(); e.exec(); } bool WebPuppeteerTab::post(const QString &url, const QString &post, const QString content_type, int timeout) { QNetworkRequest req(url); req.setHeader(QNetworkRequest::ContentTypeHeader, content_type); mainFrame()->load(req, QNetworkAccessManager::PostOperation, post.toUtf8()); return wait(timeout); } bool WebPuppeteerTab::browse(const QString &url, int timeout) { mainFrame()->load(mainFrame()->url().resolved(QUrl(url))); return wait(timeout); } void WebPuppeteerTab::back() { triggerAction(QWebPage::Back); } void WebPuppeteerTab::reload(bool force_no_cache) { if (force_no_cache) { triggerAction(QWebPage::ReloadAndBypassCache); } else { triggerAction(QWebPage::Reload); } } void WebPuppeteerTab::setReturnBool(bool r) { return_bool = r; } bool WebPuppeteerTab::screenshot(const QString &filename) { // disable scrollbars, not as anyone is going to use them anyway mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); QImage img(viewportSize(), QImage::Format_RGB32); QPainter paint(&img); mainFrame()->render(&paint); paint.end(); mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded); mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded); return img.save(filename); } bool WebPuppeteerTab::fullshot(const QString &filename) { // disable scrollbars, not as anyone is going to use them anyway mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); QImage img(mainFrame()->contentsSize(), QImage::Format_RGB32); QPainter paint(&img); mainFrame()->render(&paint); paint.end(); mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded); mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded); return img.save(filename); } bool WebPuppeteerTab::print(const QString &filename) { QPrinter print; print.setOutputFileName(filename); print.setOutputFormat(QPrinter::PdfFormat); print.setPaperSize(QPrinter::A4); // print.setPageMargins(0, 0, 0, 0, QPrinter::Inch); // we know our page is 72dpi, how many dpi do we need on the printer to fit it ? // int dpi = (mainFrame()->contentsSize().width() * print.paperSize(QPrinter::Inch).width() / 72.0) * 1.06; // print.setResolution(dpi); // QPainter print_p(&print); // QSize size = mainFrame()->contentsSize(); // mainFrame()->render(&print_p, QWebFrame::ContentsLayer, QRegion(0, 0, size.width(), size.height())); // print_p.end(); mainFrame()->print(&print); return true; } QString WebPuppeteerTab::printBase64() { QTemporaryFile t; if (!t.open()) return QString(); if (!print(t.fileName())) return QString(); QByteArray data = t.readAll(); t.remove(); return QString::fromLatin1(data.toBase64()); } QScriptValue WebPuppeteerTab::eval(const QString &js) { return parent->engine().newVariant(mainFrame()->evaluateJavaScript(js)); } QScriptValue WebPuppeteerTab::document() { return parent->engine().newQObject(new WebPuppeteerWebElement(this, mainFrame()->documentElement()), QScriptEngine::ScriptOwnership); } void WebPuppeteerTab::interact() { QEventLoop e; QWebView *v = new QWebView(); v->resize(QSize(1280,1024)); v->setAttribute(Qt::WA_DeleteOnClose, true); connect(v, SIGNAL(destroyed(QObject*)), &e, SLOT(quit())); v->setPage(this); v->show(); e.exec(); } QScriptValue WebPuppeteerTab::get(const QString &url) { QNetworkRequest req(url); QNetworkReply *rep = networkAccessManager()->get(req); QEventLoop e; connect(rep, SIGNAL(finished()), &e, SLOT(quit())); e.exec(); if (rep->error() != QNetworkReply::NoError) { qDebug("GET error: %s", qPrintable(rep->errorString())); rep->deleteLater(); return parent->engine().currentContext()->throwError(QScriptContext::UnknownError, rep->errorString()); } return parent->engine().newVariant((rep->readAll())); } bool WebPuppeteerTab::wait(int timeout) { QEventLoop e; connect(this, SIGNAL(loadFinished(bool)), &e, SLOT(quit())); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setReturnBool(bool))); if (timeout > 0) QTimer::singleShot(timeout*1000, &e, SLOT(quit())); return_bool = false; e.exec(); return return_bool; } void WebPuppeteerTab::type(const QString &text) { QKeyEvent ev(QEvent::KeyPress, 0, Qt::NoModifier, text); event(&ev); } void WebPuppeteerTab::typeEnter() { QKeyEvent ev(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier); event(&ev); } void WebPuppeteerTab::typeTab() { QKeyEvent ev(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier); event(&ev); } QString WebPuppeteerTab::getHtml() { return mainFrame()->toHtml(); } void WebPuppeteerTab::overrideUserAgent(const QString &ua) { user_agent = ua; } void WebPuppeteerTab::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) { qDebug("JavaScript %s:%d: %s", qPrintable(sourceID), lineNumber, qPrintable(message)); } QString WebPuppeteerTab::userAgentForUrl(const QUrl&) const { if (user_agent.isEmpty()) return "Mozilla/5.0 (%Platform%%Security%%Subplatform%) AppleWebKit/%WebKitVersion% (KHTML, like Gecko) %AppVersion Safari/%WebKitVersion%"; return user_agent; } void WebPuppeteerTab::setDefaultCharset(const QString &charset) { settings()->setDefaultTextEncoding(charset); }
fd23011c2031637ca414fb8ecfd93fb81efbb4bf
3b21f6436c53d9c74d345a3b4fb743e3ce1e1a41
/Volume_1/160/factor.cpp
5c336e9901a93a35aa40b972b0cd2d09927dc055
[]
no_license
wilson100hong/UVAOJ
c8202e0e844b82f7a9861b9844b1092eb1468cfc
fa88f79f38ce1261fcb72fb452648d488db49f2f
refs/heads/master
2022-02-10T17:16:47.802137
2022-02-08T06:18:12
2022-02-08T06:18:12
9,843,018
0
2
null
null
null
null
UTF-8
C++
false
false
1,169
cpp
factor.cpp
#include <iostream> using namespace std; #define MAX_N 101 int prime[MAX_N]; int prime_cnt; void init() { bool p[MAX_N]; for (int i = 0; i < MAX_N; ++i) p[i] = true; for (int i = 2; i < MAX_N; ++i) { if (p[i]) { int j = i * 2; while (j < MAX_N) { p[j] = false; j += i; } } } prime_cnt = 0; for (int i = 2; i < MAX_N; ++i) { if (p[i]) { prime[prime_cnt] = i; prime_cnt++; } } } int main() { init(); int n; int answer[MAX_N]; while (cin >> n) { if (n == 0) break; for (int i = 0; i < MAX_N; ++i) answer[i] = 0; for (int i = 2; i <= n; ++i) { int num = i; int p = 0; while (num != 1 && p < prime_cnt) { if (num % prime[p] == 0) { answer[p]++; num /= prime[p]; } else{ p++; } } } // TODO: width cout.width(3); cout << n << "! ="; int i = 0; while(answer[i] != 0) { if (i != 0 && i % 15 == 0) cout << endl << " "; // TODO: width cout.width(3); cout << answer[i]; i++; } cout << endl; } return 0; }
03ccf0364d1aa7d72169603c3e2a4f3d1d73d51e
8bfbccc253fde3850d96959fc747c38e698c8736
/examples/demo/objectdemo/objectdemo.cpp
2e351413b13e4bfa1f1817bddbe2b526d6bcce71
[]
no_license
sidneydijkstra/PADEngine
b61cd89056e4b4ad19a94660419d1eccf34fda2c
4499c64d4c14bf42f597e6f06c19da733de84255
refs/heads/master
2023-05-10T15:23:41.044506
2021-05-18T13:38:42
2021-05-18T13:38:42
297,615,673
0
1
null
2021-01-18T14:35:39
2020-09-22T10:33:50
C
UTF-8
C++
false
false
615
cpp
objectdemo.cpp
#include "objectdemo.h" ObjectDemo::ObjectDemo(std::string _name) : Scene(_name) { Entity* obj = new Entity(); obj->getMesh()->loadObject("assets/viking_room.obj"); obj->getTexture()->loadTexture("assets/viking_room.png"); this->addChild(obj); list.push_back(obj); } void ObjectDemo::update() { this->getCamera()->move3D(5.0f); if (Input::getKeyDown(KeyCode::Q)) SceneManager::getInstance()->setCurrentScene("shader_demo"); if (Input::getKeyDown(KeyCode::E)) SceneManager::getInstance()->setCurrentScene("light_demo"); } ObjectDemo::~ObjectDemo() { for (auto e : list) delete e; list.clear(); }
b563fe8dc8877c761bc3786e08d34628b864d78e
2e7f8237976e765ef6b9aac864e4e1a23b36acb7
/include/script/objects/NullObject.h
ca58e9a4ed27e10a825b5edaa698147c78cb5166
[]
no_license
kopaka1822/CppScriptEngine
794c4b5e8dfcd2c75997023ebf7b73dbd24db4b2
1073c86e5116c4d3cf244d8cb2ae8563ac674393
refs/heads/master
2021-06-25T03:06:01.671335
2020-11-24T08:39:49
2020-11-24T08:39:49
170,923,776
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
NullObject.h
#pragma once #include "ScriptObject.h" namespace script { /// \brief represents the null constant. This class is a singleton class NullObject final : public ScriptObject { NullObject() = default; public: std::string toString() const override final; ScriptObjectPtr clone() const override final; static ScriptObjectPtr get(); }; }
24ca7d11b0b5ea3d48627fa47a94c4fc654e8773
dc94d3c5536ce2439e4909a8c83497683eeb8de2
/6_4_textLCD/main.cpp
f43f3966e71056349756f34e431227002f779cb4
[]
no_license
AndyLun/mbed06
81d66efe8d2d60df7c3f34f9645d381617e7b6a4
8ad0a340d8a438a438b2fa6a2fdf99e56d968c49
refs/heads/master
2021-05-26T02:37:42.649444
2020-04-08T09:28:54
2020-04-08T09:28:54
254,019,008
0
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
main.cpp
#include "LCD.h" int main() { LCD_init(); // call the initialise function display_to_LCD(0x48); // ‘H’ display_to_LCD(0x45); // ‘E’ display_to_LCD(0x4C); // ‘L’ display_to_LCD(0x4C); // ‘L’ display_to_LCD(0x4F); // ‘O’ for (char x = 0x30; x <= 0x39; x++) { display_to_LCD(x); // display numbers 0-9 } }
d61749ca2a718aeaefd414951a9180df7dace2b1
ec665a8581db1920da99adb09877b434255960fb
/plugins/MacAU/Channel9/Channel9.cpp
ea6c3ec6e6f14a6c7bc9a5312783ee44a2db66a8
[ "MIT" ]
permissive
airwindows/airwindows
92621f774f7a28fb66da84c1ec5a40c2c7124935
5375d64df5dc3dd4970ae6b3e91b7c8a255bbbe1
refs/heads/master
2023-08-03T12:21:56.984065
2023-07-30T01:02:46
2023-07-30T01:02:46
118,393,739
643
92
MIT
2023-03-16T15:43:55
2018-01-22T02:05:08
C++
WINDOWS-1252
C++
false
false
14,523
cpp
Channel9.cpp
/* * File: Channel9.cpp * * Version: 1.0 * * Created: 1/4/21 * * Copyright: Copyright © 2021 Airwindows, Airwindows uses the MIT license * * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in * consideration of your agreement to the following terms, and your use, installation, modification * or redistribution of this Apple software constitutes acceptance of these terms. If you do * not agree with these terms, please do not use, install, modify or redistribute this Apple * software. * * In consideration of your agreement to abide by the following terms, and subject to these terms, * Apple grants you a personal, non-exclusive license, under Apple's copyrights in this * original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the * Apple Software, with or without modifications, in source and/or binary forms; provided that if you * redistribute the Apple Software in its entirety and without modifications, you must retain this * notice and the following text and disclaimers in all such redistributions of the Apple Software. * Neither the name, trademarks, service marks or logos of Apple Computer, Inc. may be used to * endorse or promote products derived from the Apple Software without specific prior written * permission from Apple. Except as expressly stated in this notice, no other rights or * licenses, express or implied, are granted by Apple herein, including but not limited to any * patent rights that may be infringed by your derivative works or by other works in which the * Apple Software may be incorporated. * * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR * IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE * OR IN COMBINATION WITH YOUR PRODUCTS. * * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER * UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN * IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /*============================================================================= Channel9.cpp =============================================================================*/ #include "Channel9.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ COMPONENT_ENTRY(Channel9) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::Channel9 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Channel9::Channel9(AudioUnit component) : AUEffectBase(component) { CreateElements(); Globals()->UseIndexedParameters(kNumberOfParameters); SetParameter(kParam_One, kDefaultValue_ParamOne ); SetParameter(kParam_Two, kDefaultValue_ParamTwo ); SetParameter(kParam_Three, kDefaultValue_ParamThree ); #if AU_DEBUG_DISPATCHER mDebugDispatcher = new AUDebugDispatcher (this); #endif } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::GetParameterValueStrings //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Channel9::GetParameterValueStrings(AudioUnitScope inScope, AudioUnitParameterID inParameterID, CFArrayRef * outStrings) { if ((inScope == kAudioUnitScope_Global) && (inParameterID == kParam_One)) //ID must be actual name of parameter identifier, not number { if (outStrings == NULL) return noErr; CFStringRef strings [] = { kMenuItem_Neve, kMenuItem_API, kMenuItem_SSL, kMenuItem_Teac, kMenuItem_Mackie, }; *outStrings = CFArrayCreate ( NULL, (const void **) strings, (sizeof (strings) / sizeof (strings [0])), NULL ); return noErr; } return kAudioUnitErr_InvalidProperty; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::GetParameterInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Channel9::GetParameterInfo(AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ) { ComponentResult result = noErr; outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable | kAudioUnitParameterFlag_IsReadable; if (inScope == kAudioUnitScope_Global) { switch(inParameterID) { case kParam_One: AUBase::FillInParameterName (outParameterInfo, kParameterOneName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Indexed; outParameterInfo.minValue = kNeve; outParameterInfo.maxValue = kMackie; outParameterInfo.defaultValue = kDefaultValue_ParamOne; break; case kParam_Two: AUBase::FillInParameterName (outParameterInfo, kParameterTwoName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Percent; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 200.0; outParameterInfo.defaultValue = kDefaultValue_ParamTwo; break; case kParam_Three: AUBase::FillInParameterName (outParameterInfo, kParameterThreeName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamThree; break; default: result = kAudioUnitErr_InvalidParameter; break; } } else { result = kAudioUnitErr_InvalidParameter; } return result; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::GetPropertyInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Channel9::GetPropertyInfo (AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32 & outDataSize, Boolean & outWritable) { return AUEffectBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::GetProperty //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Channel9::GetProperty( AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void * outData ) { return AUEffectBase::GetProperty (inID, inScope, inElement, outData); } // Channel9::Initialize //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Channel9::Initialize() { ComponentResult result = AUEffectBase::Initialize(); if (result == noErr) Reset(kAudioUnitScope_Global, 0); return result; } #pragma mark ____Channel9EffectKernel //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::Channel9Kernel::Reset() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Channel9::Channel9Kernel::Reset() { fpd = 1.0; while (fpd < 16386) fpd = rand()*UINT32_MAX; iirSampleA = iirSampleB = 0.0; flip = false; lastSampleA = lastSampleB = lastSampleC = 0.0; for (int x = 0; x < 11; x++) {biquadA[x] = 0.0;biquadB[x] = 0.0;} } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Channel9::Channel9Kernel::Process //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Channel9::Channel9Kernel::Process( const Float32 *inSourceP, Float32 *inDestP, UInt32 inFramesToProcess, UInt32 inNumChannels, bool &ioSilence ) { UInt32 nSampleFrames = inFramesToProcess; const Float32 *sourceP = inSourceP; Float32 *destP = inDestP; Float64 overallscale = 1.0; overallscale /= 44100.0; overallscale *= GetSampleRate(); int console = (int) GetParameter( kParam_One ); Float64 density = GetParameter( kParam_Two )/100.0; //0-2 Float64 phattity = density - 1.0; if (density > 1.0) density = 1.0; //max out at full wet for Spiral aspect if (phattity < 0.0) phattity = 0.0; // Float64 nonLin = 5.0-density; //number is smaller for more intense, larger for more subtle Float64 output = GetParameter( kParam_Three ); Float64 iirAmount = 0.005832; Float64 threshold = 0.33362176; Float64 cutoff = 28811.0; switch (console) { case 1: iirAmount = 0.005832; threshold = 0.33362176; cutoff = 28811.0; break; //Neve case 2: iirAmount = 0.004096; threshold = 0.59969536; cutoff = 27216.0; break; //API case 3: iirAmount = 0.004913; threshold = 0.84934656; cutoff = 23011.0; break; //SSL case 4: iirAmount = 0.009216; threshold = 0.149; cutoff = 18544.0; break; //Teac case 5: iirAmount = 0.011449; threshold = 0.092; cutoff = 19748.0; break; //Mackie } iirAmount /= overallscale; //we've learned not to try and adjust threshold for sample rate biquadB[0] = biquadA[0] = cutoff / GetSampleRate(); biquadA[1] = 1.618033988749894848204586; biquadB[1] = 0.618033988749894848204586; double K = tan(M_PI * biquadA[0]); //lowpass double norm = 1.0 / (1.0 + K / biquadA[1] + K * K); biquadA[2] = K * K * norm; biquadA[3] = 2.0 * biquadA[2]; biquadA[4] = biquadA[2]; biquadA[5] = 2.0 * (K * K - 1.0) * norm; biquadA[6] = (1.0 - K / biquadA[1] + K * K) * norm; K = tan(M_PI * biquadA[0]); norm = 1.0 / (1.0 + K / biquadB[1] + K * K); biquadB[2] = K * K * norm; biquadB[3] = 2.0 * biquadB[2]; biquadB[4] = biquadB[2]; biquadB[5] = 2.0 * (K * K - 1.0) * norm; biquadB[6] = (1.0 - K / biquadB[1] + K * K) * norm; while (nSampleFrames-- > 0) { double inputSample = *sourceP; if (fabs(inputSample)<1.18e-23) inputSample = fpd * 1.18e-17; if (biquadA[0] < 0.49999) { double tempSample = biquadA[2]*inputSample+biquadA[3]*biquadA[7]+biquadA[4]*biquadA[8]-biquadA[5]*biquadA[9]-biquadA[6]*biquadA[10]; biquadA[8] = biquadA[7]; biquadA[7] = inputSample; if (fabs(tempSample)<1.18e-37) tempSample = 0.0; inputSample = tempSample; biquadA[10] = biquadA[9]; biquadA[9] = inputSample; //DF1 } Float64 dielectricScale = fabs(2.0-((inputSample+nonLin)/nonLin)); if (flip) { if (fabs(iirSampleA)<1.18e-37) iirSampleA = 0.0; iirSampleA = (iirSampleA * (1.0 - (iirAmount * dielectricScale))) + (inputSample * iirAmount * dielectricScale); inputSample = inputSample - iirSampleA; } else { if (fabs(iirSampleB)<1.18e-37) iirSampleB = 0.0; iirSampleB = (iirSampleB * (1.0 - (iirAmount * dielectricScale))) + (inputSample * iirAmount * dielectricScale); inputSample = inputSample - iirSampleB; } //highpass section including capacitor modeling nonlinearity double drySample = inputSample; if (inputSample > 1.0) inputSample = 1.0; if (inputSample < -1.0) inputSample = -1.0; double phatSample = sin(inputSample * 1.57079633); inputSample *= 1.2533141373155; //clip to 1.2533141373155 to reach maximum output, or 1.57079633 for pure sine 'phat' version double distSample = sin(inputSample * fabs(inputSample)) / ((fabs(inputSample) == 0.0) ?1:fabs(inputSample)); inputSample = distSample; //purest form is full Spiral if (density < 1.0) inputSample = (drySample*(1-density))+(distSample*density); //fade Spiral aspect if (phattity > 0.0) inputSample = (inputSample*(1-phattity))+(phatSample*phattity); //apply original Density on top Float64 clamp = (lastSampleB - lastSampleC) * 0.381966011250105; clamp -= (lastSampleA - lastSampleB) * 0.6180339887498948482045; clamp += inputSample - lastSampleA; //regular slew clamping added lastSampleC = lastSampleB; lastSampleB = lastSampleA; lastSampleA = inputSample; //now our output relates off lastSampleB if (clamp > threshold) inputSample = lastSampleB + threshold; if (-clamp > threshold) inputSample = lastSampleB - threshold; //slew section lastSampleA = (lastSampleA*0.381966011250105)+(inputSample*0.6180339887498948482045); //split the difference between raw and smoothed for buffer flip = !flip; if (output < 1.0) { inputSample *= output; } if (biquadB[0] < 0.49999) { double tempSample = biquadB[2]*inputSample+biquadB[3]*biquadB[7]+biquadB[4]*biquadB[8]-biquadB[5]*biquadB[9]-biquadB[6]*biquadB[10]; biquadB[8] = biquadB[7]; biquadB[7] = inputSample; if (fabs(tempSample)<1.18e-37) tempSample = 0.0; inputSample = tempSample; biquadB[10] = biquadB[9]; biquadB[9] = inputSample; //DF1 } //begin 32 bit floating point dither int expon; frexpf((float)inputSample, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSample += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); //end 32 bit floating point dither *destP = inputSample; sourceP += inNumChannels; destP += inNumChannels; } }
08ec9a11b4b752b40d2304b8d25cd461ccb7f61c
a559df3ae294163ce2cb04436d51af6f440b81df
/dynamic_programming/min_cost_climbing_stairs.cc
103f8e58eb68c9874a27e89253d79a9a05125b35
[]
no_license
saileshnankani/Algorithms-and-Data-Structures
270fed7f37c1968bce2dc7ee480804245ab4dffd
584f1a3b1d9a0f5278a405aadfc66cfffa112626
refs/heads/master
2021-07-16T08:15:46.435413
2020-01-03T18:41:36
2020-01-03T18:41:36
202,796,542
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
cc
min_cost_climbing_stairs.cc
#include <iostream> #include <vector> #include <unordered_map> using namespace std; unordered_map<int,int> memo; int minClimb(vector<int>&cost, int begin){ if(begin>=cost.size()){ return 0; } if(memo.find(begin)!=memo.end()){ return memo[begin]; } int first = cost[begin] + minClimb(cost,begin+1); int second = cost[begin] + minClimb(cost,begin+2); memo[begin] = min(first,second); return memo[begin]; } // top-down approach int minCostClimbingStairs_down(vector<int>& cost) { return min(minClimb(cost,0),minClimb(cost,1)); } int min(int a, int b){ return a < b ? a : b; } // bottom-up approach, int minCostClimbingStairs_up(vector<int>& cost) { int f1 = 0, f2 = 0; for(int i=0; i<cost.size(); i++){ int f0 = cost[i] + min(f1,f2); f2 = f1; f1 = f0; } return min(f1,f2); } int main(){ vector<int> test = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; cout<<minCostClimbingStairs_down(test)<<endl; cout<<minCostClimbingStairs_up(test)<<endl; }
86e0eaa87af9757c84f3affdea0614911e972597
32df434a59d94f7e1a39f84d204018850c6094f8
/ports/nacl-spawn/nacl_spawn.cc
a334a392d0b703a2e353e149dfd8989b3bcda031
[ "GPL-2.0-or-later", "LicenseRef-scancode-mit-old-style", "MPL-1.1", "ImageMagick", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GFDL-1.2-only", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "LGPL-2.0-or-later", "GPL-1.0-or-later", "Libpng", "LicenseRef-scan...
permissive
kosyak/naclports_samsung-smart-tv
b9eeba2f292d9e35da771c5939d98cf58b46df02
a33cb6a6118a3899b0b8f5e4cb7e0d264b3f305d
refs/heads/master
2022-10-15T00:41:16.671774
2014-05-07T14:38:44
2014-05-07T14:38:44
18,762,387
0
1
BSD-3-Clause
2022-10-08T08:41:12
2014-04-14T13:54:01
C
UTF-8
C++
false
false
7,651
cc
nacl_spawn.cc
// Copyright (c) 2014 The Native Client Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Emulates spawning/waiting process by asking JavaScript to do so. #include <assert.h> #include <errno.h> #include <libgen.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <string> #include <vector> #include "ppapi/cpp/instance.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/var_array.h" #include "ppapi/cpp/var_dictionary.h" #include "ppapi_simple/ps_instance.h" #if defined(__GLIBC__) # include "library_dependencies.h" #endif #include "path_util.h" extern char** environ; struct NaClSpawnReply { pthread_mutex_t mu; pthread_cond_t cond; // Zero or positive on success or -errno on failure. int result; }; static std::string GetCwd() { char cwd[PATH_MAX + 1]; // TODO(hamaji): Remove this #if and always call getcwd. // https://code.google.com/p/naclports/issues/detail?id=109 #if defined(__GLIBC__) if (!getwd(cwd)) #else if (!getcwd(cwd, PATH_MAX)) #endif assert(0); return cwd; } static std::string GetAbsPath(const std::string& path) { assert(!path.empty()); if (path[0] == '/') return path; else return GetCwd() + '/' + path; } // Returns a unique request ID to make all request strings different // from each other. static std::string GetRequestId() { static int64_t req_id = 0; static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mu); int64_t id = ++req_id; pthread_mutex_unlock(&mu); char buf[64]; sprintf(buf, "%lld", id); return buf; } // Handle reply from JavaScript. The key is the request string and the // value is Zero or positive on success or -errno on failure. The // user_data must be an instance of NaClSpawnReply. static void HandleNaClSpawnReply(const pp::Var& key, const pp::Var& value, void* user_data) { if (!key.is_string() || !value.is_int()) { fprintf(stderr, "Invalid parameter for HandleNaClSpawnReply\n"); fprintf(stderr, "key=%s\n", key.DebugString().c_str()); fprintf(stderr, "value=%s\n", value.DebugString().c_str()); } assert(key.is_string()); assert(value.is_int()); NaClSpawnReply* reply = static_cast<NaClSpawnReply*>(user_data); pthread_mutex_lock(&reply->mu); reply->result = value.AsInt(); pthread_cond_signal(&reply->cond); pthread_mutex_unlock(&reply->mu); } // Sends a spawn/wait request to JavaScript and returns the result. static int SendRequest(pp::VarDictionary* req) { const std::string& req_id = GetRequestId(); req->Set("id", req_id); NaClSpawnReply reply; pthread_mutex_init(&reply.mu, NULL); pthread_cond_init(&reply.cond, NULL); PSInstance* instance = PSInstance::GetInstance(); instance->RegisterMessageHandler(req_id, &HandleNaClSpawnReply, &reply); instance->PostMessage(*req); pthread_mutex_lock(&reply.mu); pthread_cond_wait(&reply.cond, &reply.mu); pthread_mutex_unlock(&reply.mu); pthread_cond_destroy(&reply.cond); pthread_mutex_destroy(&reply.mu); instance->RegisterMessageHandler(req_id, NULL, &reply); return reply.result; } // Adds a file into nmf. |key| is the key for open_resource IRT or // "program". |filepath| is not a URL yet. JavaScript code is // responsible to fix them. static void AddFileToNmf(const std::string& key, const std::string& filepath, pp::VarDictionary* dict) { #if defined(__x86_64__) static const char kArch[] = "x86-64"; #elif defined(__i686__) static const char kArch[] = "x86-32"; #elif defined(__arm__) static const char kArch[] = "arm"; #elif defined(__pnacl__) static const char kArch[] = "pnacl"; #else # error "Unknown architecture" #endif pp::VarDictionary url; url.Set("url", filepath); pp::VarDictionary arch; arch.Set(kArch, url); dict->Set(key, arch); } static void AddNmfToRequestForShared( std::string prog, const std::vector<std::string>& dependencies, pp::VarDictionary* req) { pp::VarDictionary nmf; pp::VarDictionary files; const char* prog_base = basename(&prog[0]); for (size_t i = 0; i < dependencies.size(); i++) { std::string dep = dependencies[i]; const std::string& abspath = GetAbsPath(dep); const char* base = basename(&dep[0]); // nacl_helper does not pass the name of program and the dynamic // loader always uses "main.nexe" as the main binary. if (!strcmp(prog_base, base)) base = "main.nexe"; AddFileToNmf(base, abspath, &files); } nmf.Set("files", files); #if defined(__x86_64__) static const char kDynamicLoader[] = "lib64/runnable-ld.so"; #else static const char kDynamicLoader[] = "lib32/runnable-ld.so"; #endif AddFileToNmf("program", kDynamicLoader, &nmf); req->Set("nmf", nmf); } static void AddNmfToRequestForStatic(const std::string& prog, pp::VarDictionary* req) { pp::VarDictionary nmf; AddFileToNmf("program", GetAbsPath(prog), &nmf); req->Set("nmf", nmf); } // Adds a NMF to the request if |prog| is stored in HTML5 filesystem. static bool AddNmfToRequest(std::string prog, pp::VarDictionary* req) { if (prog.find('/') == std::string::npos) { bool found = false; const char* path_env = getenv("PATH"); std::vector<std::string> paths; GetPaths(path_env, &paths); if (paths.empty() || !GetFileInPaths(prog, paths, &prog)) { // If the path does not contain a slash and we cannot find it // from PATH, we use NMF served with the JavaScript. return true; } } if (access(prog.c_str(), R_OK) != 0) { errno = ENOENT; return false; } #if defined(__GLIBC__) std::vector<std::string> dependencies; if (!FindLibraryDependencies(prog, &dependencies)) return false; if (!dependencies.empty()) { AddNmfToRequestForShared(prog, dependencies, req); return true; } // No dependencies means the main binary is statically linked. #endif AddNmfToRequestForStatic(prog, req); return true; } // Spawn a new NaCl process by asking JavaScript. This function lacks // a lot of features posix_spawn supports (e.g., handling FDs). // Returns 0 on success. On error -1 is returned and errno will be set // appropriately. extern "C" int nacl_spawn_simple(const char** argv) { assert(argv[0]); pp::VarDictionary req; req.Set("command", "nacl_spawn"); pp::VarArray args; for (int i = 0; argv[i]; i++) args.Set(i, argv[i]); req.Set("args", args); pp::VarArray envs; for (int i = 0; environ[i]; i++) envs.Set(i, environ[i]); req.Set("envs", envs); req.Set("cwd", GetCwd()); if (!AddNmfToRequest(argv[0], &req)) { errno = ENOENT; return -1; } int result = SendRequest(&req); if (result < 0) { errno = -result; return -1; } return result; } // Waits for the specified pid. The semantics of this function is as // same as waitpid, though this implementation has some restrictions. // Returns 0 on success. On error -1 is returned and errno will be set // appropriately. extern "C" int nacl_waitpid(int pid, int* status, int options) { // We only support waiting for a single process. assert(pid > 0); // No options are supported yet. assert(options == 0); pp::VarDictionary req; req.Set("command", "nacl_wait"); req.Set("pid", pid); int result = SendRequest(&req); if (result < 0) { errno = -result; return -1; } // WEXITSTATUS(s) is defined as ((s >> 8) & 0xff). if (status) *status = (result & 0xff) << 8; return 0; }
1ad247e604958725e81879f9227f3d7bdd3bda2a
4f29e4e3314a931aa963e4dfde0e264b982f4914
/Sample of problemSolving/A. Maximum in Table 509A/main.cpp
c2cd71e68c1d967d97fd9be728b9874e03b45d62
[]
no_license
MostafaAbdallah/My-projects
61c09f879e081304018f9fd7cdb2442828740297
137b6bea8970aec290b41414f0dd402c7965c50d
refs/heads/master
2020-03-28T18:35:44.013130
2020-01-06T12:22:22
2020-01-06T12:22:22
13,528,409
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
main.cpp
/** Problem Name: A. Maximum in Table 509 A Target: 2D Array (Vector) **/ #include <iostream> #include <vector> using namespace std; int main() { int n = 0; int maxnum = 1; cin>>n; int **t = new int*[n]; for(int i = 0; i < n; ++i){ t[i] = new int[n]; } for(int i = 0; i < n; ++i){ t[0][i] = 1; t[i][0] = 1; } for(int i = 1; i < n; ++i){ for(int j = 1; j < n; ++j){ // cout<<t[i-1][j] << "----" << t[i][j-1] <<endl; t[i][j] = t[i-1][j] + t[i][j-1] ; if(t[i][j] > maxnum) maxnum = t[i][j]; } } cout << maxnum <<endl; return 0; }
a243655f9b42376e4a125004ec3ae77a23a7dce2
c55a9a501537ec8a822d81ed56251aedaa4c53a5
/makefile/imos_sdk_xml.h
cac0667336e4ce39fe68d18341448720cb9863a8
[]
no_license
haofeng0928/VideoAnalyze
acba4683534a3a69ef80160d1cc1ff319582a606
441fb181028aa5f58b28b1e650fdcea1b4787ea4
refs/heads/master
2020-05-03T03:38:02.290862
2019-03-29T12:49:48
2019-03-29T12:49:48
178,403,054
0
0
null
null
null
null
GB18030
C++
false
false
44,120
h
imos_sdk_xml.h
/******************************************************************************* Copyright (c) 2008-2013, Zhejiang Uniview Technology Co., Ltd. All rights reserved. -------------------------------------------------------------------------------- imos_sdk_xml.h Project Code: imos sdk Module Name: imos sdk Date Created: 2011-10-24 Author: chengjian/03354 Description: xml构造解析框架代码,继承自IMOS_ActiveX控件工程,非本次编写代码 -------------------------------------------------------------------------------- Modification History DATE NAME DESCRIPTION -------------------------------------------------------------------------------- YYYY-MM-DD *******************************************************************************/ #ifndef IMOS_SDK_XML_H #define IMOS_SDK_XML_H #include "string" #include "sstream" #include "vector" #include "imos_public.h" #include "libxml/parser.h" #include "dllimport.h" #define IMOS_SDK_XML_QUOT "'" /*lint -save -e* */ /* 标准库容器前置申明 */ namespace std{ template<class _Ty, class _Ax> class vector; template<class _Ty, class _Ax> class list; template<class _Ty, class _Ax> class deque; template<class _Kty,class _Pr, class _Alloc> class set; template<class _Kty,class _Pr, class _Alloc> class multiset; } /* 基础工具类 */ namespace IMOS_SDK_XML { namespace UTILITY { /* true类型 */ struct TRUE_TYPE{}; /* false类型 */ struct FALSE_TYPE{}; /* 类型选择元函数 */ template<bool bFlag, class T1, class T2> struct SelType { typedef T1 type; }; template<class T1, class T2> struct SelType<false, T1, T2> { typedef T2 type; }; /* 判断T是否为char类型的元函数 */ template<class T> struct SIsCharType { static long test(...); static char test(const CHAR *); static char test(const UCHAR *); enum {value = (sizeof(test((T *)0)) == sizeof(char))}; }; /* 判断T是否为内置类型的元函数 */ template<class T> struct SIsInnerType { static long test(...); #define ADD_INNER_TYPE(type) static char test(type *) ADD_INNER_TYPE(CHAR); ADD_INNER_TYPE(UCHAR); ADD_INNER_TYPE(SHORT); ADD_INNER_TYPE(USHORT); ADD_INNER_TYPE(LONG_REAL); ADD_INNER_TYPE(ULONG_REAL); #ifndef WIN32 ADD_INNER_TYPE(LONG_32); ADD_INNER_TYPE(ULONG_32); #endif ADD_INNER_TYPE(DLONG); ADD_INNER_TYPE(DULONG); ADD_INNER_TYPE(std::string); ADD_INNER_TYPE(const CHAR); ADD_INNER_TYPE(const UCHAR); ADD_INNER_TYPE(const SHORT); ADD_INNER_TYPE(const USHORT); #ifndef WIN32 ADD_INNER_TYPE(const LONG_32); ADD_INNER_TYPE(const ULONG_32); #endif ADD_INNER_TYPE(const LONG_REAL); ADD_INNER_TYPE(const ULONG_REAL); ADD_INNER_TYPE(const DLONG); ADD_INNER_TYPE(const DULONG); ADD_INNER_TYPE(const std::string); enum {value = (sizeof(test((T *)0)) == sizeof(char))}; }; /* 判断T是否为stl容器类型的元函数 */ template<class T> struct SIsContainType { static long test(...); #define ADD_CONTAIN_TYPE(type) template<class V, class A> static char test(type<V, A> *) #define ADD_MAP_CONTAIN_TYPE(type) template<class V, class P, class A> static char test(type<V, P, A> *) ADD_CONTAIN_TYPE(std::vector); ADD_CONTAIN_TYPE(std::list); ADD_CONTAIN_TYPE(std::deque); ADD_MAP_CONTAIN_TYPE(std::set); ADD_MAP_CONTAIN_TYPE(std::multiset); enum {value = (sizeof(test((T *)0)) == sizeof(char))}; }; /* 判断T是否为内置数组类型的元函数 */ template<class T> struct SIsArrayType { static long test(...); template<class K, int N> static char test(const K (*)[N]); enum {value = (sizeof(test((T *)0)) == sizeof(char))}; }; /* 判断T是否为char数组类型的元函数 */ template<class T> struct SIsCharArrayType { static long test(...); template<int N> static char test(const CHAR (*)[N]); template<int N> static char test(const UCHAR (*)[N]); enum {value = (sizeof(test((T *)0)) == sizeof(char))}; }; /* 获取数组T的子元素类型的元函数 */ template<class T> struct SArrayInnerType { template<class K> struct STypeWrapper{ typedef FALSE_TYPE type; }; template <class E> struct STypeWrapper<E**>{ typedef E type; }; template <class E, int N> struct STypeWrapper<E(*)[N]>{ typedef E type; }; typedef typename STypeWrapper<T*>::type type; }; /* 获取指针指向数据的元函数,可以处理多级指针 */ struct SGetPointToData { template<class E> struct STypeWrapper{ typedef E type; static type &value(E&v){return v;} static bool is_null(E&v){return false;} }; template <class E> struct STypeWrapper<E*>{ typedef typename STypeWrapper<E>::type type; static type &value(E*v){return STypeWrapper<E>::value(*v);} static bool is_null(E*v){return (v==NULL) || STypeWrapper<E>::is_null(*v);} }; template <class E> struct STypeWrapper<E* const> : STypeWrapper<E*>{}; /* 判断是否为空指针 */ template<class T> static bool is_null(T &v) { return STypeWrapper<T>::is_null(v); } /* 取得指针指向数据的引用 */ template<class T> static typename STypeWrapper<T>::type &value(T &v) { return STypeWrapper<T>::value(v); } }; /* 空元组 */ struct NullElement { }; /* 字符串或字符数组元组 */ struct ACElement { const char *pcEleName; const char *pcValue; LONG_32 lLen; }; /* 基础类型元组 */ template<class T> struct SElement { const char *pcEleName; const T *pValue; }; /* 结构类型元组 */ template<class T> struct MElement { const char *pcEleName; const T* pstValue; }; /* stl容器类型元组 */ template<class T> struct VContainElement { enum {isInnerType = SIsInnerType<typename T::value_type>::value}; const char *pcEleName; T *poContain; }; /* 数组类型元组,T为数组元素类型,bIsInType表示T是否为基础类型 */ template<class T, bool bIsInType> struct VElement { const char *pcEleName; const T* pstValue; LONG_32 lCount; }; /* 数组类型元组,T为数组元素类型,bIsInType表示T是否为基础类型 */ template<class T, bool bIsInType> struct VOutElement { const char *pcEleName; const T* pstValue; LONG_32 *plCount; }; /* 数组类型元组 */ template<class T> struct VMElement { const char *pcEleName; const T* pstValue; int index; }; /* 属性元组,继承了元素元组的实现 */ template<class E> struct Attribute : public E { Attribute(const E &e) : E(e) { } }; /* 节点内容元组,继承了元素元组的实现 */ template<class E> struct NodeContent : public E { NodeContent(const E &e) : E(e) { } }; /* 封装元组类型推导逻辑 */ template<class T> struct ElementTypeHelp { /* 推导非内置数组类型的元组类型 */ typedef typename SelType<SIsInnerType<T>::value, SElement<T>, typename SelType<SIsContainType<T>::value, VContainElement<T>, MElement<T> >::type >::type result1; /* 推导内置数组类型的元组类型 */ typedef typename SelType<SIsCharType<T>::value, ACElement, VElement<T, false> >::type result2; /* 推导内置数组类型的元组类型 */ typedef typename SelType<SIsCharType<T>::value, ACElement, VElement<T, SIsInnerType<T>::value> >::type result3; /* 推导属性或者内容元组,这类元组的类型只可能是基础类型或者字符数组 */ typedef typename SelType<SIsCharArrayType<T>::value, ACElement, typename SelType<SIsInnerType<T>::value, SElement<T>, NullElement >::type >::type result4; /* 推导非字符数组的C数组元组类型 */ typedef VOutElement<typename SArrayInnerType<T>::type, false> result5; }; /* 属性元组构造函数 */ template<class T> Attribute<typename ElementTypeHelp<T>::result4> ATTRIBUTE(const char * pcName, const T &stValue) { return Attribute<typename ElementTypeHelp<T>::result4>(ELEMENT(pcName, stValue)); } /* 内容元组构造函数 */ template<class T> NodeContent<typename ElementTypeHelp<T>::result4> CONTENT(const T &stValue) { return NodeContent<typename ElementTypeHelp<T>::result4>(ELEMENT("", stValue)); } /* 非内置数组类型元组构造函数 */ template<class T> typename ElementTypeHelp<T>::result1 ELEMENT(const char * pcName, const T &stValue) { typename ElementTypeHelp<T>::result1 stElem = {pcName, (T*)&stValue}; return stElem; } /* 内置数组退化的指针类型元组构造函数 */ template<class T> typename ElementTypeHelp<T>::result2 ELEMENT(const char * pcName, const T *pstValueList, LONG_32 lCount) { typename ElementTypeHelp<T>::result2 stElem = {pcName, pstValueList, lCount}; return stElem; } /* 字符串指针类型元组构造函数 */ //inline ACElement ELEMENT(const char * pcName, const char * pcStr) //{ // ACElement stElem = {pcName, pcStr, IMOS_strlen(pcStr)}; // return stElem; //} /* 内置数组类型元组构造函数 */ template<class T, int N> typename ElementTypeHelp<T>::result3 ELEMENT(const char * pcName, const T (&astValueList)[N]) { typename ElementTypeHelp<T>::result3 stElem = {pcName, astValueList, N}; return stElem; } /* 非字符数组的C数组类型元组构造函数 */ template<class T> typename ElementTypeHelp<T>::result5 ELEMENT(const char * pcName, T &stValueList, LONG_32 *plCount) { return ELEMENT(pcName, stValueList, plCount, (typename SelType<SIsArrayType<T>::value, TRUE_TYPE, FALSE_TYPE>::type *)0); } /* 非字符数组的C数组类型元组构造函数实现 */ template<class T> VOutElement<T, false> ELEMENT(const char * pcName, const T *pstValueList, LONG_32 *plCount, FALSE_TYPE*) { VOutElement<T, false> stElem = {pcName, pstValueList, plCount}; return stElem; } /* 非字符数组的C数组类型元组构造函数实现 */ template<class T, int N> VOutElement<T, false> ELEMENT(const char * pcName, T (&astValueList)[N], LONG_32 *plCount, TRUE_TYPE*) { *plCount = N; VOutElement<T, false> stElem = {pcName, astValueList, plCount}; return stElem; } template<class T> VMElement<T> ELEMENT(const char * pcName, LONG_32 idx, const T &stValue) { VMElement<T> stElem = {pcName, &stValue, idx}; return stElem; } } } /* xml构造接口 */ namespace IMOS_SDK_XML { namespace UTILITY { /* 一组重载的将不同类型元组转换为xml片段的函数 */ inline std::ostringstream & operator << (std::ostringstream &ostrXml, const NullElement &) { return ostrXml; } template<class T> std::ostringstream & operator << (std::ostringstream &ostrXml, const VContainElement<T> &oElem) { toxml(ostrXml, oElem, (typename SelType<VContainElement<T>::isInnerType, TRUE_TYPE, FALSE_TYPE>::type*)0); return ostrXml; } template<class T> VOID toxml (std::ostringstream &ostrXml, const VContainElement<T> &oElem, TRUE_TYPE*) { ostrXml << "<" << oElem.pcEleName << " count="IMOS_SDK_XML_QUOT << oElem.poContain->size() << IMOS_SDK_XML_QUOT">" << "<![CDATA["; typename T::const_iterator it = oElem.poContain->begin(); for (; it != oElem.poContain->end(); ++it) { ostrXml << *it << "\t"; } ostrXml << "]]></" << oElem.pcEleName << ">"; } template<class T> VOID toxml (std::ostringstream &ostrXml, const VContainElement<T> &oElem, FALSE_TYPE*) { typename T::const_iterator it = oElem.poContain->begin(); for (; it != oElem.poContain->end(); ++it) { ostrXml << ELEMENT(oElem.pcEleName, SGetPointToData::value(*it)); } } template<class T> std::ostringstream & operator << (std::ostringstream &ostrXml, const VElement<T, true> &oElem) { ostrXml << "<" << oElem.pcEleName << " count="IMOS_SDK_XML_QUOT << oElem.lCount << IMOS_SDK_XML_QUOT">"; for (LONG_32 i=0; i<oElem.lCount; ++i) { ostrXml << oElem.pstValue[i] << " "; } ostrXml << "</" << oElem.pcEleName << ">"; return ostrXml; } template<class T> std::ostringstream & operator << (std::ostringstream &ostrXml, const VElement<T, false> &oElem) { for (LONG_32 i=0; i<oElem.lCount; ++i) { ostrXml << ELEMENT(oElem.pcEleName, SGetPointToData::value(oElem.pstValue[i])); } return ostrXml; } template<class T> std::ostringstream & operator << (std::ostringstream &ostrXml, const MElement<T> oElem) { ostrXml << "<" << oElem.pcEleName << ">"; xmlTempl(ostrXml, *oElem.pstValue); ostrXml << "</" << oElem.pcEleName << ">"; return ostrXml; } template<class T> std::ostringstream & operator << (std::ostringstream &ostrXml, const SElement<T> &oElem) { ostrXml << "<" << oElem.pcEleName << ">" << *oElem.pValue << "</" << oElem.pcEleName << ">"; return ostrXml; } inline std::ostringstream & operator << (std::ostringstream &ostrXml, const ACElement &oElem) { if (oElem.pcValue[0] == '\0') { ostrXml << "<" << oElem.pcEleName << "/>"; } else { ostrXml << "<" << oElem.pcEleName << ">"; for (LONG_32 i=0; i<oElem.lLen; ++i) { switch(oElem.pcValue[i]) { case '&': ostrXml << "&amp;"; break; case '>': ostrXml << "&gt;"; break; case '<': ostrXml << "&lt;"; break; case '\'': ostrXml << "&apos;"; break; case '\"': ostrXml << "&quot;"; break; case '\0': i = oElem.lLen-1; break; default: ostrXml << oElem.pcValue[i]; }; } ostrXml << "</" << oElem.pcEleName << ">"; } return ostrXml; } inline std::ostringstream & operator << (std::ostringstream &ostrXml, const SElement<std::string> &oElem) { ACElement oACElem = {oElem.pcEleName, oElem.pValue->c_str(), oElem.pValue->size()}; return (ostrXml << oACElem); } /* 将一到多个元组构造为完整xml的函数 */ template<class T1, class T2=NullElement, class T3=NullElement, class T4=NullElement, class T5=NullElement, class T6=NullElement> struct MultiElemXmlBuild { static std::string build(const char *pcRootTagName="", const T1 &stElement1=T1(), const T2 &stElement2=T2(), const T3 &stElement3=T3(), const T4 &stElement4=T4(), const T5 &stElement5=T5(), const T6 &stElement6=T6()) { std::ostringstream ostrXml; ostrXml << "<?xml version="IMOS_SDK_XML_QUOT"1.0"IMOS_SDK_XML_QUOT"?>" << "<" << pcRootTagName << ">"; ostrXml << stElement1 << stElement2 << stElement3 << stElement4 << stElement5 << stElement6 << "</" << pcRootTagName << ">"; return ostrXml.str(); } }; } using namespace UTILITY; /* 把结构的数据转换为xml */ template<class T> std::string buildXml(const T &stData, const char *pcTagName = NULL) { if (NULL == pcTagName) { pcTagName = "data"; } return buildSingleEleXml(ELEMENT(pcTagName, stData)); } /* 单个元组的数据转换为xml */ template<class T> std::string buildSingleEleXml(const T &stElem) { std::ostringstream ostrXml; ostrXml << "<?xml version="IMOS_SDK_XML_QUOT"1.0"IMOS_SDK_XML_QUOT"?>"; ostrXml << stElem; return ostrXml.str(); } /* 以下一组函数将一到多个元组的数据转换为xml */ template<class T1> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1) { return MultiElemXmlBuild<T1>::build(pcRootTagName, stElement1); } template<class T1, class T2> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1, const T2 &stElement2) { return MultiElemXmlBuild<T1, T2>::build(pcRootTagName, stElement1, stElement2); } template<class T1, class T2, class T3> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3) { return MultiElemXmlBuild<T1, T2, T3>::build(pcRootTagName, stElement1, stElement2, stElement3); } template<class T1, class T2, class T3, class T4> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4) { return MultiElemXmlBuild<T1, T2, T3, T4>::build(pcRootTagName, stElement1, stElement2, stElement3, stElement4); } template<class T1, class T2, class T3, class T4, class T5> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5) { return MultiElemXmlBuild<T1, T2, T3, T4, T5>::build(pcRootTagName, stElement1, stElement2, stElement3, stElement4, stElement5); } template<class T1, class T2, class T3, class T4, class T5, class T6> std::string buildMultiEleXml(const char *pcRootTagName, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5, const T6 &stElement6) { return MultiElemXmlBuild<T1, T2, T3, T4, T5, T6>::build(pcRootTagName, stElement1, stElement2, stElement3, stElement4, stElement5, stElement6); } } /* xml解析接口 */ namespace IMOS_SDK_XML { namespace UTILITY { /* libxml2库函数的动态加载类 */ struct libxml : DLL<libxml> { ADD_FUN(xmlParseFile, XMLPUBFUN xmlDocPtr (XMLCALL*)(const char *filename)) ADD_FUN(xmlParseMemory, XMLPUBFUN xmlDocPtr (XMLCALL *)(const char *, int)) ADD_FUN(xmlReadMemory, XMLPUBFUN xmlDocPtr (XMLCALL *)(const char *, int , const char *, const char *, int)) ADD_FUN(xmlFreeDoc, XMLPUBFUN void (XMLCALL *)(xmlDocPtr)) ADD_FUN(xmlDocGetRootElement, XMLPUBFUN xmlNodePtr (XMLCALL *)(xmlDocPtr)) ADD_FUN(xmlNodeGetContent, XMLPUBFUN xmlChar * (XMLCALL *)(xmlNodePtr)) ADD_FUN(xmlMemGet, XMLPUBFUN int (XMLCALL *)(xmlFreeFunc *, xmlMallocFunc *, xmlReallocFunc *, xmlStrdupFunc *)) ADD_FUN(xmlGetProp, XMLPUBFUN xmlChar * (XMLCALL*)(xmlNodePtr, const xmlChar *)) ADD_FUN(xmlHasProp, XMLPUBFUN xmlAttrPtr (XMLCALL*)(xmlNodePtr, const xmlChar *)) ADD_FUN_UNLOAD(xmlFree, xmlFreeFunc) }; /* 封装一组xml解析操作 */ class CXmlParseHelp { public: /* 构造函数 */ CXmlParseHelp() { m_pDoc = NULL; } /* 析构函数 */ ~CXmlParseHelp() { if (NULL != m_pDoc) { try { libxml::methods.xmlFreeDoc(m_pDoc); m_pDoc = NULL; } catch (...) { } } } /* 加载libxml2库 */ static bool loadXmlLib(const std::string & strDllPath) { if (!libxml::loadDll(strDllPath.c_str())) { return false; } libxml::methods.xmlMemGet(&libxml::methods.xmlFree, NULL, NULL, NULL); if (NULL == libxml::methods.xmlFree) { libxml::unloadDll(); return false; } return true; } /* 卸载libxml2库 */ static void freeXmlLib() { libxml::unloadDll(); return; } /* 读xml文件 */ xmlNodePtr readXmlFile(const char *pcFilePath) { if ((NULL == libxml::methods.xmlParseFile) || (NULL == libxml::methods.xmlDocGetRootElement)) { return NULL; } /* 读入文件内容 */ m_pDoc = libxml::methods.xmlParseFile(pcFilePath); xmlNodePtr pRootNode = NULL; /* 获取根节点 */ if ((NULL == m_pDoc) || (NULL == (pRootNode = libxml::methods.xmlDocGetRootElement(m_pDoc)))) { return NULL; } return pRootNode; } /* 读xml字符串 */ xmlNodePtr readXmlString(const char *pcXml, ULONG_32 ulLen) { if ((NULL == libxml::methods.xmlParseMemory) || (NULL == libxml::methods.xmlDocGetRootElement)) { return NULL; } /* 读入xml字符串 */ m_pDoc = libxml::methods.xmlParseMemory(pcXml, (int)ulLen); xmlNodePtr pRootNode = NULL; /* 获取根节点 */ if ((NULL == m_pDoc) || (NULL == (pRootNode = libxml::methods.xmlDocGetRootElement(m_pDoc)))) { return NULL; } return pRootNode; } /* 查找指定名称的子节点 */ static xmlNodePtr searchXmlSubNode(IN xmlNodePtr pParentNode, IN const std::string &strSubNodeName) { if (NULL == pParentNode) { return NULL; } /* 遍历每个子节点 */ xmlNodePtr pCurNode = pParentNode->xmlChildrenNode; while (NULL != pCurNode) { /* 找到名字相同的节点,则返回 */ if ((const char*)pCurNode->name == strSubNodeName) { return pCurNode; } pCurNode = pCurNode->next; } return NULL; } /* 读取指定名称的字符串属性值 */ static bool getXmlNodeAttribute(IN xmlNodePtr pNode, IN const std::string &strName, OUT const std::string &strContent) { if ((NULL == pNode) || (NULL == libxml::methods.xmlGetProp) || (NULL == libxml::methods.xmlFree)) { return false; } /* 获取节点的值 */ CHAR *pcKey = (CHAR *) libxml::methods.xmlGetProp(pNode, (const xmlChar*)strName.c_str()); if (NULL == pcKey) { return false; } (std::string&)strContent = pcKey; /* 释放内存 */ libxml::methods.xmlFree((xmlChar *) pcKey); return true; } /* 读取指定名称的字符属性值 */ static bool getXmlNodeAttribute(IN xmlNodePtr pNode, IN const std::string &strName, OUT const char &lValue) { std::string strContent; if (!getXmlNodeAttribute(pNode, strName, strContent)) { return false; } (char &)lValue = strContent.at(0); return true; } /* 读取指定名称的整形属性值 */ template <class T> static bool getXmlNodeAttribute(IN xmlNodePtr pNode, IN const std::string &strName, OUT const T &lValue) { std::string strContent; if (!getXmlNodeAttribute(pNode, strName, strContent)) { return false; } if (sizeof(T) == sizeof(DLONG)) { (T&)lValue = (T)IMOS_atodul(strContent.c_str()); } else { (T&)lValue = (T)IMOS_atol(strContent.c_str()); } return true; } /* 读取xml节点的文本内容 */ static bool getXmlNodeContent(IN xmlNodePtr pNode, OUT const std::string &strContent) { if ((NULL == pNode) || (NULL == libxml::methods.xmlNodeGetContent) || (NULL == libxml::methods.xmlFree)) { return false; } /* 获取节点的值 */ CHAR *pcKey = (CHAR *) libxml::methods.xmlNodeGetContent(pNode); if (NULL == pcKey) { return false; } (std::string&)strContent = pcKey; /* 释放内存 */ libxml::methods.xmlFree((xmlChar *) pcKey); return true; } /* 读取xml节点CHAR类型文本内容 */ static bool getXmlNodeContent(IN xmlNodePtr pNode, OUT const char &lValue) { std::string strContent; if (!getXmlNodeContent(pNode, strContent)) { return false; } (char &)lValue = strContent.at(0); return true; } /* 读取xml节点整形文本内容 */ template <class T> static bool getXmlNodeContent(IN xmlNodePtr pNode, OUT const T &lValue) { std::string strContent; if (!getXmlNodeContent(pNode, strContent)) { return false; } if (sizeof(T) == sizeof(DLONG)) { (T&)lValue = (T)IMOS_atodul(strContent.c_str()); } else { (T&)lValue = (T)IMOS_atol(strContent.c_str()); } return true; } /* 获取当前节点下指定名称的所有子节点 */ static void getXmlSubNodes(IN xmlNodePtr pNode, IN const CHAR *pcSubNodeName, OUT std::vector<xmlNodePtr> &oSubNodes) { if ((NULL == pNode) || (NULL == pcSubNodeName)) { return; } pNode = pNode->xmlChildrenNode; while (NULL != pNode) { if ((const char*)pNode->name == std::string(pcSubNodeName)) { oSubNodes.push_back(pNode); } pNode = pNode->next; } return; } private: xmlDocPtr m_pDoc; }; /* 包含多个元组的xml解析函数 */ template<class T1, class T2=NullElement, class T3=NullElement, class T4=NullElement, class T5=NullElement, class T6=NullElement> struct MultiElemXmlParse { /* 解析内存xml字符串 */ static bool parse(const char *pcXml="", const T1 &stElement1=T1(), const T2 &stElement2=T2(), const T3 &stElement3=T3(), const T4 &stElement4=T4(), const T5 &stElement5=T5(), const T6 &stElement6=T6()) { CXmlParseHelp oParser; xmlNodePtr pRootNode = oParser.readXmlString(pcXml, (ULONG_32) strlen(pcXml)); return (NULL != pRootNode) && (pRootNode << stElement1) && (pRootNode << stElement2) && (pRootNode << stElement3) && (pRootNode << stElement4) && (pRootNode << stElement5) && (pRootNode << stElement6); } /* 解析xml文件 */ static bool parseFile(const char *pcFilePath, const T1 &stElement1=T1(), const T2 &stElement2=T2(), const T3 &stElement3=T3(), const T4 &stElement4=T4(), const T5 &stElement5=T5(), const T6 &stElement6=T6()) { CXmlParseHelp oParser; xmlNodePtr pRootNode = oParser.readXmlFile(pcFilePath); return (NULL != pRootNode) && (pRootNode << stElement1) && (pRootNode << stElement2) && (pRootNode << stElement3) && (pRootNode << stElement4) && (pRootNode << stElement5) && (pRootNode << stElement6); } }; /* 读取空元组 */ inline bool operator << (xmlNodePtr /*pParentNode*/, const NullElement &/*oElem*/) { return true; } /* 读取非数组类型元素元组 */ template<class T> bool operator << (xmlNodePtr pParentNode, const T &oElem) { xmlNodePtr pNode = CXmlParseHelp::searchXmlSubNode(pParentNode, oElem.pcEleName); if (NULL == pNode) { return false; } return readElem(pNode, oElem); } /* 读取非字符数组类型属性元组 */ template<class E> bool operator << (xmlNodePtr pParentNode, const Attribute<E> &oElem) { return CXmlParseHelp::getXmlNodeAttribute(pParentNode, oElem.pcEleName, *oElem.pValue); } /* 读取字符数组类型属性元组 */ inline bool operator << (xmlNodePtr pParentNode, const Attribute<ACElement> &oElem) { std::string strValue; if (!CXmlParseHelp::getXmlNodeAttribute(pParentNode, oElem.pcEleName, strValue)) { return false; } strncpy((char*)oElem.pcValue, strValue.c_str(), (unsigned int)oElem.lLen); return true; } /* 读取非字符数组类型内容元组 */ template<class E> bool operator << (xmlNodePtr pParentNode, const NodeContent<E> &oElem) { return CXmlParseHelp::getXmlNodeContent(pParentNode, *oElem.pValue); } /* 读取字符数组类型内容元组 */ inline bool operator << (xmlNodePtr pParentNode, const NodeContent<ACElement> &oElem) { std::string strValue; if (!CXmlParseHelp::getXmlNodeContent(pParentNode, strValue)) { return false; } strncpy((char*)oElem.pcValue, strValue.c_str(), (unsigned int)oElem.lLen); return true; } /* 读取非字符数组类型元素元组,不需要指定数组长度 */ template<class T, bool bInner> bool operator << (xmlNodePtr pParentNode, const VElement<T, bInner> &oElem) { VOutElement<T, bInner> oOutElem = {oElem.pcEleName, oElem.pstValue, (LONG_32*)&oElem.lCount}; return readElem(pParentNode, oOutElem); } /* 读取非字符数组类型元素元组,需要指定数组长度 */ template<class T, bool bInner> bool operator << (xmlNodePtr pParentNode, const VOutElement<T, bInner> &oElem) { return readElem(pParentNode, oElem); } /* 读取stl容器类型元素元组 */ template<class TContain> bool operator << (xmlNodePtr pParentNode, const VContainElement<TContain> &oElem) { return readElem(pParentNode, oElem); } /* 读取基础类型元素元组 */ template<class T> bool readElem(xmlNodePtr pNode, const SElement<T> &oElem) { return CXmlParseHelp::getXmlNodeContent(pNode, *oElem.pValue); } /* 读取字符数组类型元素元组 */ inline bool readElem(xmlNodePtr pNode, const ACElement &oElem) { std::string strContent; if (!CXmlParseHelp::getXmlNodeContent(pNode, strContent)) { return false; } strncpy((char*)oElem.pcValue, strContent.c_str(), (unsigned int)oElem.lLen); return true; } /* 读取基础类型数组的元素元组 */ template<class T> bool readElem(xmlNodePtr pNode, const VOutElement<T, true> &oElem) { std::string strContent; if (!CXmlParseHelp::getXmlNodeContent(pNode, strContent)) { return false; } std::istringstream istr(strContent); LONG_32 lValue = 0; int i=0; for (; (!(istr >> lValue).eof()) && (i < *oElem.plCount); ++i) { (T&)oElem.pstValue[i] = (T)lValue; } *oElem.plCount = i; return true; } /* 读取结构类型数组的元素元组 */ template<class T> bool readElem(xmlNodePtr pNode, const VOutElement<T, false> &oElem) { std::vector<xmlNodePtr> oSubNodes; CXmlParseHelp::getXmlSubNodes(pNode, oElem.pcEleName, oSubNodes); size_t i=0; for (; (i<oSubNodes.size()) && (i<(size_t)*oElem.plCount); ++i) { if (!readElem(oSubNodes[i], ELEMENT(oElem.pcEleName, oElem.pstValue[i]))) { return false; } } *oElem.plCount = i; return true; } /* 读取结构类型数组的元素元组 */ template<class T> bool readElem(xmlNodePtr pNode, const VMElement<T> &oElem) { std::vector<xmlNodePtr> oSubNodes; CXmlParseHelp::getXmlSubNodes(pNode, oElem.pcEleName, oSubNodes); if (oSubNodes.size() <= (size_t)oElem.index) { return false; } return xmlTempl(oSubNodes[oElem.index], (T&)(*oElem.pstValue)); } /* 读取结构类型的元素元组 */ template<class T> bool readElem(xmlNodePtr pNode, const MElement<T> &oElem) { return xmlTempl(pNode, (T&)*oElem.pstValue); } /* 读取stl容器类型元素元组 */ template<class TContain> bool readElem(xmlNodePtr pNode, const VContainElement<TContain> &oElem) { std::vector<xmlNodePtr> oSubNodes; CXmlParseHelp::getXmlSubNodes(pNode, oElem.pcEleName, oSubNodes); for (size_t i=0; i<oSubNodes.size(); ++i) { typename TContain::value_type value; if (!readElem(oSubNodes[i], ELEMENT(oElem.pcEleName, value))) { return false; } oElem.poContain->insert(oElem.poContain->end(),value); } return true; } } using namespace UTILITY; /* 解析xml字符串到结构 */ template<class T> bool parseXml(const CHAR *pcXml, const CHAR *pcTagName, T &oData) { return parseSingleEleXml(pcXml, ELEMENT(pcTagName, oData)); } /* 解析xml文件到结构 */ template<class T> bool parseXmlFile(const CHAR *pcFile, const CHAR *pcTagName, T &oData) { return parseSingleEleXmlFile(pcFile, ELEMENT(pcTagName, oData)); } /* 解析xml字符串到单个的元组 */ template<class T> bool parseSingleEleXml(const CHAR *pcXml, const T &stElem) { /* 调用xml解析模块接口获取xml文档结构及文档根元素 */ CXmlParseHelp oParser; xmlNodePtr pRootNode = oParser.readXmlString(pcXml, (ULONG_32) strlen(pcXml)); if ((stElem.pcEleName != NULL) && (stElem.pcEleName[0] != '\0')) { return (NULL != pRootNode) && (pRootNode << stElem); } else { return (NULL != pRootNode) && readElem(pRootNode, stElem); } } /* 解析xml字符串到一到多个元组 */ template<class T> bool parseMultiEleXml(const char *pcXml, const T &stElement) { return MultiElemXmlParse<T>::parse(pcXml, stElement); } template<class T1, class T2> bool parseMultiEleXml(const char *pcXml, const T1 &stElement1, const T2 &stElement2) { return MultiElemXmlParse<T1, T2>::parse(pcXml, stElement1, stElement2); } template<class T1, class T2, class T3> bool parseMultiEleXml(const char *pcXml, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3) { return MultiElemXmlParse<T1, T2, T3>::parse(pcXml, stElement1, stElement2, stElement3); } template<class T1, class T2, class T3, class T4> bool parseMultiEleXml(const char *pcXml, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4) { return MultiElemXmlParse<T1, T2, T3, T4>::parse(pcXml, stElement1, stElement2, stElement3, stElement4); } template<class T1, class T2, class T3, class T4, class T5> bool parseMultiEleXml(const char *pcXml, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5) { return MultiElemXmlParse<T1, T2, T3, T4, T5>::parse(pcXml, stElement1, stElement2, stElement3, stElement4, stElement5); } template<class T1, class T2, class T3, class T4, class T5, class T6> bool parseMultiEleXml(const char *pcXml, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5, const T6 &stElement6) { return MultiElemXmlParse<T1, T2, T3, T4, T5, T6>::parse(pcXml, stElement1, stElement2, stElement3, stElement4, stElement5, stElement6); } /* 解析xml文件到单个的元组 */ template<class T> bool parseSingleEleXmlFile(const CHAR *pcFilePath, const T &stElem) { /* 调用xml解析模块接口获取xml文档结构及文档根元素 */ CXmlParseHelp oParser; xmlNodePtr pRootNode = oParser.readXmlFile(pcFilePath); if ((stElem.pcEleName != NULL) && (stElem.pcEleName[0] != '\0')) { return (NULL != pRootNode) && (pRootNode << stElem); } else { return (NULL != pRootNode) && readElem(pRootNode, stElem); } } /* 解析xml文件到一到多个元组 */ template<class T> bool parseMultiEleXmlFile(const char *pcPath, const T &stElement) { return MultiElemXmlParse<T>::parseFile(pcPath, stElement); } template<class T1, class T2> bool parseMultiEleXmlFile(const char *pcPath, const T1 &stElement1, const T2 &stElement2) { return MultiElemXmlParse<T1, T2>::parseFile(pcPath, stElement1, stElement2); } template<class T1, class T2, class T3> bool parseMultiEleXmlFile(const char *pcPath, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3) { return MultiElemXmlParse<T1, T2, T3>::parseFile(pcPath, stElement1, stElement2, stElement3); } template<class T1, class T2, class T3, class T4> bool parseMultiEleXmlFile(const char *pcPath, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4) { return MultiElemXmlParse<T1, T2, T3, T4>::parseFile(pcPath, stElement1, stElement2, stElement3, stElement4); } template<class T1, class T2, class T3, class T4, class T5> bool parseMultiEleXmlFile(const char *pcPath, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5) { return MultiElemXmlParse<T1, T2, T3, T4, T5>::parseFile(pcPath, stElement1, stElement2, stElement3, stElement4, stElement5); } template<class T1, class T2, class T3, class T4, class T5, class T6> bool parseMultiEleXmlFile(const char *pcPath, const T1 &stElement1, const T2 &stElement2, const T3 &stElement3, const T4 &stElement4, const T5 &stElement5, const T6 &stElement6) { return MultiElemXmlParse<T1, T2, T3, T4, T5, T6>::parseFile(pcPath, stElement1, stElement2, stElement3, stElement4, stElement5, stElement6); } } /*lint -restore */ #endif //IMOS_SDK_XML_H
b91cff6742ecc987394405bb3f38fcd3a3da7339
e8dccc2e674b70506509bb017363d37dd0b875fe
/new start/arduino_using_library_ledcontrol/arduino_using_library_ledcontrol.ino
3aad49f1802d23df40ab29187ef7b1c1a2755428
[]
no_license
Theara-Seng/simple_arduino_testing
d74089a982b8c8e8ab8c6d4cf1c129d00703a551
2c3884420c6576ebf8e440e4ed9f800508bca239
refs/heads/main
2023-04-01T11:19:38.630587
2021-04-13T05:02:52
2021-04-13T05:02:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,951
ino
arduino_using_library_ledcontrol.ino
#include <LedControl.h> int DIN = 12; int CS = 11; int CLK = 10; byte E[8] = {0x3C,0x20,0x20,0x3C,0x20,0x20,0x20,0x3C}; byte L[8] = {0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x3E}; byte C[8] = {0x1C,0x20,0x20,0x20,0x20,0x20,0x20,0x1C}; byte T[8] = {0x7C,0x10,0x10,0x10,0x10,0x10,0x10,0x10}; byte R[8] = {0x38,0x24,0x24,0x28,0x30,0x28,0x24,0x24}; byte O[8] = {0x1C,0x22,0x22,0x22,0x22,0x22,0x22,0x1C}; byte N[8] = {0x42,0x62,0x52,0x52,0x4A,0x46,0x46,0x42}; byte I[8] = {0x38,0x10,0x10,0x10,0x10,0x10,0x10,0x38}; byte S[8] = {0x1C,0x20,0x20,0x10,0x08,0x04,0x04,0x38}; byte H[8] = {0x22,0x22,0x22,0x3E,0x22,0x22,0x22,0x22}; byte U[8] = {0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x1C,}; byte B[8] = {0x38,0x24,0x24,0x38,0x38,0x24,0x24,0x38}; byte smile[8]= {0x3C,0x42,0xA5,0x81,0xA5,0x99,0x42,0x3C}; byte neutral[8]= {0x3C,0x42,0xA5,0x81,0xBD,0x81,0x42,0x3C}; byte frown[8]= {0x3C,0x42,0xA5,0x81,0x99,0xA5,0x42,0x3C}; LedControl lc=LedControl(12,11,10,1); void setup(){ lc.shutdown(0,false); lc.setIntensity(0,5); lc.clearDisplay(0); } void loop() { printByte(smile); delay(1000); printByte(neutral); delay(1000); printByte(frown); delay(1000); printByte(E); delay(1000); printByte(L); delay(1000); printByte(E); delay(1000); printByte(C); delay(1000); printByte(T); delay(1000); printByte(R); delay(1000); printByte(O); delay(1000); printByte(N); delay(1000); printByte(I); delay(1000); printByte(C); delay(1000); printByte(S); delay(1000); // lc.clearDisplay(0); // delay(1000); printByte(H); delay(1000); printByte(U); delay(1000); printByte(B); delay(1000); // lc.clearDisplay(0); // delay(1000); } void printByte(byte character []) { int i = 0; for(i=0;i<8;i++) { lc.setRow(0,i,character[i]); } }
6be1fa035ad929635731ebee0a4c1c6937cf19f2
b0bfa899191d57adc5599d3bf3d1df5776bf6e9e
/notes/Monday - 0614/Lab_4/Lab_4_header.h
5544e6815845634e15e17463a07583b76200a933
[]
no_license
chris-womack/dataStructures
2e71cc6e0ee9baf43825c83a90bff2f5fe5d221d
717d50a767287643da08d8693d57ed368bd5125c
refs/heads/master
2021-01-01T16:40:02.517650
2014-09-14T00:59:14
2014-09-14T00:59:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
Lab_4_header.h
#ifndef LAB_4_HEADER_H_INCLUDED #define LAB_4_HEADER_H_INCLUDED class City{ private: std::string place; std::string Msg; City *next; City *prev; public: City(std::string, std::string); // constructor ~City(); // destructor // get and set next City *getNext(); void setNext(City *n); // get and set previous City *getPrev(); void setPrev(City *n); // get and set message std::string getMsg(); void setMsg(std::string); // get and set Place std::string getPlace(); void setPlace(std::string); // transmit function void transmitMsg(City*, std::string, int, int*); // delete node function void delete_node(std::string, City*); // add funtion void add_node(City*, City*); }; #endif // LAB_4_HEADER_H_INCLUDED
479c4b848f2949e04191ad148d530ff497fdc153
793fe5717a9dee3a474e6fb43f3edf9320bea8e8
/tests/is_alpha_digit.cc
99757bd4bd4c87724f4e4d57630154baba36807b
[ "MIT" ]
permissive
mahdavipanah/stringplus
1ea764e870be14c130031083bc8c8ad4e85cd967
cb958b7696bb14c42b115f21b69f296c355fb723
refs/heads/master
2021-01-10T19:44:19.860122
2020-09-17T22:37:49
2020-09-17T22:37:49
37,009,984
12
0
null
null
null
null
UTF-8
C++
false
false
278
cc
is_alpha_digit.cc
#include "Catch/catch.hpp" #include "../src/stringplus.h" using namespace stringplus; TEST_CASE( "is_alpha_digit", "[is_alpha_digit]" ) { REQUIRE( is_alpha_digit("1234") == true ); REQUIRE( is_alpha_digit("34n4") == true ); REQUIRE( is_alpha_digit("34n[") == false ); }
416c5caea6860395a2b0faa3e50acb48d874e63a
02df8a9b10c2f22ddfb69baaf411ab77f2c8396d
/include/prim/seadStringBuilder.h
786c9ca8af2c6ae77931dc1388c82d543f7b74fd
[]
no_license
AlexApps99/sead
0297789ad23362c7291b48d58a3ae2515bf1162d
f0c36b99d4f379e8ce36f0845be0211bb9bf4acb
refs/heads/master
2023-07-15T22:15:06.262714
2021-08-16T10:18:31
2021-08-16T10:23:49
396,732,798
0
0
null
2021-08-16T10:03:30
2021-08-16T10:03:29
null
UTF-8
C++
false
false
11,106
h
seadStringBuilder.h
#pragma once #include <cstdarg> #include "prim/seadSafeString.h" namespace sead { class Heap; template <typename T> class StringBuilderBase { public: static StringBuilderBase* create(s32 buffer_size, Heap* heap, s32 alignment); static StringBuilderBase* create(const T* str, Heap* heap, s32 alignment); StringBuilderBase(const StringBuilderBase<T>& other) = delete; class iterator { public: explicit iterator(const StringBuilderBase* builder) : mBuilder(builder), mIndex(0) {} iterator(const StringBuilderBase* string, s32 index) : mBuilder(string), mIndex(index) {} bool operator==(const iterator& rhs) const { return mBuilder == rhs.mBuilder && mIndex == rhs.mIndex; } bool operator!=(const iterator& rhs) const { return !(rhs == *this); } iterator& operator++() { return mIndex++, *this; } iterator& operator--() { return mIndex--, *this; } const char& operator*() const { return mBuilder->at(mIndex); } const StringBuilderBase* getBuilder() const { return mBuilder; } s32 getIndex() const { return mIndex; } protected: const StringBuilderBase* mBuilder; s32 mIndex; }; iterator begin() const { return iterator(this, 0); } iterator end() const { return iterator(this, mLength); } // TODO: tokenBegin, tokenEnd operator SafeStringBase<T>() const { return cstr(); } s32 getLength() const { return mLength; } s32 calcLength() const { return getLength(); } s32 getBufferSize() const { return mBufferSize; } const T* cstr() const; const T& at(s32 idx) const; const T& operator[](s32 idx) const { return at(idx); } SafeStringBase<T> getPart(s32 at) const; SafeStringBase<T> getPart(const iterator& it) const; bool include(T c) const; bool include(const T* str) const; s32 findIndex(const T* str) const { return findIndex(str, 0); } s32 findIndex(const T* str, s32 start_pos) const; s32 rfindIndex(const T* str) const; bool isEmpty() const { return mLength == 0; } bool startsWith(const T* prefix) const; bool endsWith(const T* suffix) const; bool isEqual(const T* str) const; s32 comparen(const T* str, s32 n) const; void clear(); /// Copy up to copyLength characters to the beginning of the string, then writes NUL. /// @param src Source string /// @param copy_length Number of characters from src to copy (must not cause a buffer overflow) s32 copy(const T* src, s32 copy_length = -1); /// Copy up to copyLength characters to the specified position, then writes NUL if the copy /// makes this string longer. /// @param at Start position (-1 for end of string) /// @param src Source string /// @param copyLength Number of characters from src to copy (must not cause a buffer overflow) s32 copyAt(s32 at, const T* src, s32 copy_length = -1); /// Copy up to copyLength characters to the beginning of the string, then writes NUL. /// Silently truncates the source string if the buffer is too small. /// @param src Source string /// @param copyLength Number of characters from src to copy s32 cutOffCopy(const T* src, s32 copy_length = -1); /// Copy up to copyLength characters to the specified position, then writes NUL if the copy /// makes this string longer. /// Silently truncates the source string if the buffer is too small. /// @param at Start position (-1 for end of string) /// @param src Source string /// @param copyLength Number of characters from src to copy s32 cutOffCopyAt(s32 at, const T* src, s32 copy_length = -1); /// Copy up to copyLength characters to the specified position, then *always* writes NUL. /// @param at Start position (-1 for end of string) /// @param src Source string /// @param copyLength Number of characters from src to copy (must not cause a buffer overflow) s32 copyAtWithTerminate(s32 at, const T* src, s32 copy_length = -1); s32 format(const T* format, ...); s32 formatV(const T* format, std::va_list args) { mLength = formatImpl_(mBuffer, mBufferSize, format, args); return mLength; } s32 appendWithFormat(const T* format, ...); s32 appendWithFormatV(const T* format, std::va_list args) { const s32 ret = formatImpl_(mBuffer + mLength, mBufferSize - mLength, format, args); mLength += ret; return ret; } /// Append append_length characters from str. s32 append(const T* str, s32 append_length); /// Append a character. s32 append(T c) { return append(c, 1); } /// Append a character n times. s32 append(T c, s32 n); /// Remove num characters from the end of the string. /// @return the number of characters that were removed s32 chop(s32 chop_num); /// Remove the last character if it is equal to c. /// @return the number of characters that were removed s32 chopMatchedChar(T c); /// Remove the last character if it is equal to any of the specified characters. /// @param characters List of characters to remove /// @return the number of characters that were removed s32 chopMatchedChar(const T* characters); /// Remove the last character if it is unprintable. /// @warning The behavior of this function is not standard: a character is considered /// unprintable if it is <= 0x20 or == 0x7F. In particular, the space character is unprintable. /// @return the number of characters that were removed s32 chopUnprintableAsciiChar(); /// Remove trailing characters that are in the specified list. /// @param characters List of characters to remove /// @return the number of characters that were removed s32 rstrip(const T* characters); /// Remove trailing characters that are unprintable. /// @warning The behavior of this function is not standard: a character is considered /// unprintable if it is <= 0x20 or == 0x7F. In particular, the space character is unprintable. /// @return the number of characters that were removed s32 rstripUnprintableAsciiChars(); /// Trim a string to only keep trimLength characters. /// @return the new length s32 trim(s32 trim_length); /// Trim a string to only keep trimLength characters. /// @return the new length s32 trimMatchedString(const T* str); /// @return the number of characters that were replaced s32 replaceChar(T old_char, T new_char); /// @return the number of characters that were replaced s32 replaceCharList(const SafeStringBase<T>& old_chars, const SafeStringBase<T>& new_chars); s32 convertFromMultiByteString(const char* str, s32 str_length); s32 convertFromWideCharString(const char16* str, s32 str_length); s32 cutOffAppend(const T* str, s32 append_length); s32 cutOffAppend(T c, s32 num); s32 prepend(const T* str, s32 prepend_length); s32 prepend(T c, s32 num); protected: StringBuilderBase(T* buffer, s32 buffer_size) : mBuffer(buffer), mLength(0), mBufferSize(buffer_size) { mBuffer[0] = SafeStringBase<T>::cNullChar; } static StringBuilderBase<T>* createImpl_(s32 buffer_size, Heap* heap, s32 alignment); static s32 formatImpl_(T* dst, s32 dst_size, const T* format, std::va_list arg); template <typename OtherType> s32 convertFromOtherType_(const OtherType* src, s32 src_size); T* getMutableStringTop_() const { return mBuffer; } T* mBuffer; s32 mLength; s32 mBufferSize; }; using StringBuilder = StringBuilderBase<char>; using WStringBuilder = StringBuilderBase<char16>; template <s32 N> class FixedStringBuilder : public StringBuilder { public: FixedStringBuilder() : StringBuilder(mStorage, N) {} private: char mStorage[N]; }; template <typename T> inline const T* StringBuilderBase<T>::cstr() const { return mBuffer; } // UNCHECKED template <typename T> inline const T& StringBuilderBase<T>::at(s32 idx) const { if (idx < 0 || idx > mLength) { SEAD_ASSERT_MSG(false, "index(%d) out of range[0, %d]", idx, mLength); return SafeStringBase<T>::cNullChar; } return mBuffer[idx]; } // UNCHECKED template <typename T> inline SafeStringBase<T> StringBuilderBase<T>::getPart(s32 at) const { if (at < 0 || at > mLength) { SEAD_ASSERT_MSG(false, "index(%d) out of range[0, %d]", at, mLength); return SafeStringBase<T>::cEmptyString; } return SafeStringBase<T>(mBuffer + at); } // UNCHECKED template <typename T> inline SafeStringBase<T> StringBuilderBase<T>::getPart(const StringBuilderBase::iterator& it) const { return getPart(it.getIndex()); } // UNCHECKED template <typename T> inline bool StringBuilderBase<T>::include(T c) const { for (s32 i = 0; i < mLength; ++i) { if (mBuffer[i] == c) return true; } return false; } // UNCHECKED template <typename T> inline bool StringBuilderBase<T>::include(const T* str) const { return findIndex(str) != -1; } // UNCHECKED template <typename T> inline s32 StringBuilderBase<T>::findIndex(const T* str, s32 start_pos) const { const s32 len = calcLength(); if (start_pos < 0 || start_pos > len) { SEAD_ASSERT_MSG(false, "start_pos(%d) out of range[0, %d]", start_pos, len); return -1; } const s32 sub_str_len = calcStrLength_(str); for (s32 i = start_pos; i <= len - sub_str_len; ++i) { if (SafeStringBase<T>(&mBuffer[i]).comparen(str, sub_str_len) == 0) return i; } return -1; } // UNCHECKED template <typename T> inline s32 StringBuilderBase<T>::rfindIndex(const T* str) const { const s32 len = calcLength(); const s32 sub_str_len = calcStrLength_(str); for (s32 i = len - sub_str_len; i >= 0; --i) { if (SafeStringBase<T>(&mBuffer[i]).comparen(str, sub_str_len) == 0) return i; } return -1; } // UNCHECKED template <typename T> inline bool StringBuilderBase<T>::startsWith(const T* prefix) const { return findIndex(prefix) == 0; } // UNCHECKED template <typename T> inline bool StringBuilderBase<T>::isEqual(const T* str) const { for (s32 i = 0; i < mLength; i++) { if (str[i] == SafeStringBase<T>::cNullChar) return false; if (mBuffer[i] != str[i]) return false; } return true; } // UNCHECKED template <typename T> inline s32 StringBuilderBase<T>::comparen(const T* str, s32 n) const { if (n > mLength) { SEAD_ASSERT_MSG(false, "paramater(%d) out of bounds [0, %d]", n, mLength); n = mLength; } for (s32 i = 0; i < n; ++i) { if (mBuffer[i] < str[i]) return -1; if (mBuffer[i] > str[i]) return 1; if (str[i] == SafeStringBase<T>::cNullChar) return 1; } return 0; } // UNCHECKED template <typename T> inline void StringBuilderBase<T>::clear() { mBuffer[0] = SafeStringBase<T>::cNullChar; mLength = 0; } } // namespace sead
7c383ca6d87f5ea852f9901338ab618fc55ae32a
f7469cd0ec11ac05e173aca7749630a852cbf0b9
/Tham lam/DSA03018.cpp
5d9f8a66a0c094658fceb4aedd97cfcff3a85661
[]
no_license
hieunvPTIT/CTDL2021
9e1b83a343f25991b6b12b8b03085c906591fb69
dc3ab1580138bfee2ec85165706358b2e8b72015
refs/heads/main
2023-06-10T14:15:58.608845
2021-06-28T18:07:12
2021-06-28T18:07:12
381,121,937
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
DSA03018.cpp
#include<bits/stdc++.h> using namespace std; int n; void input(){ cin>>n; } void solve(){ string result; // n = 4a+ 7b; 0<= a <= n/4; 0<=b<= n/7 int a=0,b=0; for(int i = 0; i<=n/4; i++){ if((n-4*i)%7 == 0){ a=i; b=(n-4*i)/7; while(a--) cout<<4; while(b--) cout<<7; cout<<"\n"; return; } } cout<<-1<<"\n"; } int main(){ int t = 1; cin>>t; while(t--){ input(); solve(); } return 0; }
ca9fabdac8a64fc1fb4f41c1cdbbe26d878828b6
32e84e2838d147644adabe35c878b30d8580bb07
/ProjectThree/ProjectThree/src/Entity.cpp
aae1efb00a38dbfc11ee54920907bbfc49e4f29e
[]
no_license
ShnapDozer/ProjectThree
470a78219356daab588618f83eda4a3820fc17c3
dd0e9cd70dfb8debb9b7768d6a85612beffa8057
refs/heads/master
2023-06-23T13:12:54.196428
2023-04-01T21:02:11
2023-04-01T21:02:11
247,796,887
0
0
null
2023-04-01T21:02:12
2020-03-16T19:12:19
C++
UTF-8
C++
false
false
3,782
cpp
Entity.cpp
#include "Entity.h" //-----------------------------------------------Entity---------------------------------------------------- //--------------------------------------------------------------------------------------------------------- Entity::Entity(std::string name, const sf::Vector2f& posS) : life(true), collision(false), posA(posS), Name(name) { Members[name] = &Main; } bool Entity::Collision() const { return collision; } bool Entity::Check_Collision(const std::vector<TmxObject> &Solid_Vec) const { for (auto it : Solid_Vec) { if (P_intersectRect(it.Polygon, Main.GetRect())) return true; } return false; } sf::Vector2f Entity::GetPoss() const { return posA; } sf::FloatRect Entity::GetRect() const { return Main.GetRect(); } std::string Entity::GetName() const { return Name; } void Entity::AddAnim(std::string name, std::string file, float speed, int frames) { Main.create(name, file, speed, frames, true); } void Entity::SetAnim_Mg(AnimManager &A) { Main = std::move(A); Members[Name] = &Main; } void Entity::ChoiseAnim(std::string Name) { Main.set(Name); } void Entity::Draw(sf::RenderTarget& target) { Main.draw(target, posA); } std::map<std::string, AnimManager*> Entity::GetMembers() { return Members; } //-----------------------------------------------Hero------------------------------------------------------ //--------------------------------------------------------------------------------------------------------- Hero::Hero(std::string name, const sf::Vector2f& posS) : Entity(name, posS) {} void Hero::Update(float time, const sf::Vector2f& map_Pos, bool ImGui, const std::vector<TmxObject>& Solid_Vec) { if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left) && !ImGui) { rotation_rad = std::atan2(map_Pos.y - posA.y, map_Pos.x - posA.x); rotation_grad = rotation_rad * 180.f / 3.1415; vector = (pow(map_Pos.y - posA.y, 2)) + (pow(map_Pos.x - posA.x, 2)); if (false) { State = state::up_left; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { State = state::up_right; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { State = state::down_left; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { State = state::down_right; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { State = state::left; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { State = state::right; } else if (rotation_grad <= -80 && rotation_grad >= -100) { State = state::up; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { State = state::down; } else State = state::stay; if (vector < 10000) { dx = 0.05 * std::cos(std::atan2(map_Pos.y - posA.y, map_Pos.x - posA.x)); dy = 0.05 * std::sin(std::atan2(map_Pos.y - posA.y, map_Pos.x - posA.x)); } else { dx = 0.1 * std::cos(std::atan2(map_Pos.y - posA.y, map_Pos.x - posA.x)); dy = 0.1 * std::sin(std::atan2(map_Pos.y - posA.y, map_Pos.x - posA.x)); } } Main.tick(time); collision = Check_Collision(Solid_Vec); posA.x += dx * time; posA.y += dy * time; dx = 0; dy = 0; } std::map<std::string, float> Hero::GetAllState() const { std::map<std::string, float> AllState; AllState["X"] = posA.x; AllState["Y"] = posA.y; AllState["Is Life"] = life; AllState["Collision"] = collision; AllState["Rotation"] = rotation_grad; AllState["Vector"] = vector; return AllState; } //----------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------
d0150bd5b0299e3042010c2261d56c4277ee7ba4
897f30b2aa252863b8b6eb148008dc3ceb4af962
/IN_OpenCV/Timer.cpp
6db7be6375dc06b714b6042faddd87ffa9b024b1
[]
no_license
wazka/KinectScanner
ae33a02680f3bd125085e7a48ce068c886313552
76a3c8c4abadc7e1c151614bd12fc72a52ebb15e
refs/heads/master
2020-12-31T04:56:20.004564
2016-05-29T22:39:23
2016-05-29T22:39:23
59,506,677
1
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
Timer.cpp
#include "Timer.h" Timer::Timer() { if (QueryPerformanceFrequency(&frequency) == 0) { initialized = false; return; } initialized = true; } double Timer::AbsoluteTime() { if (initialized == false) return 0; LARGE_INTEGER systemTime; if (QueryPerformanceCounter(&systemTime) == 0) return 0; double realTime = (double)systemTime.QuadPart / (double)frequency.QuadPart; return realTime; }
b5c44a2b065ab13fcd48a5d864f12e2d0f7beb80
892c2a05b916a9449dd702fce6ed483cc0765d55
/include/pac-man-bot/reach_search.h
af660fe93098cd9b9e6f827c788b2941c308d496
[]
no_license
KSU-IEEE/behaviors
d14dd2d08989ddf0be6a12834733a9e3e8ee5c30
ae395ca6a7b56196555b0461957a0dd6400ac85b
refs/heads/main
2023-03-21T00:20:02.006391
2021-03-13T14:51:11
2021-03-13T14:51:11
323,131,358
0
0
null
2021-03-12T06:24:22
2020-12-20T17:50:43
C++
UTF-8
C++
false
false
1,776
h
reach_search.h
#ifndef REACH_SEARCH_H #define REACH_SEARCH_H #include <pac-man-bot/ground_search.h> /************************************************** pac-man-bot::reach_search This class is used to search over the walls in the pac-man-bot arena. To do this, we will take in the distance sent from the arm to monitor when an block passes from underneath it to grab. This also inherits from ground_search because there were a lot of similarities between the two. Bc of this, it has the same fsm as class. search_done_ Set when the search state in the fsm finishes ================================================== CONNECTIONS subscribers: ALL_SUBS_FROM_GROUND_SEARCH publishers: publishes to topics **************************************************/ namespace behaviors { namespace pac_man_behs { class reach_search : public ground_search { public: reach_search(); ~reach_search(); // override - from base_behavior // bool control_loop() override; // not needed, same fsm as ground_search void set_params() override; void nodelet_init() override; // override - from ground_search bool move() override; bool search() override; // returns true when finding a block bool grabBlock() override; // returns true when returned back to staritng position // utils std::pair<float, float> calcBounds(); std::pair<float, float> getInitial(); private: // constants std::pair<float, float> LOCATION_A = {4, 11.5}; std::pair<float, float> LOCATION_B = {39.5, 11.5}; std::pair<float, float> LOCATION_C = {115, 11.5}; std::pair<float, float> LOCATION_D = {4, 27.5}; std::pair<float, float> LOCATION_E = {69, 27.5}; }; // reach_search } // pac_man_behs } // behaviors #endif // REACH_SEARCH_H
98648a6cadf23c74159a577701e0e3cd15125a19
de241e745d6f4193d1c3785d76309d3f5fe813ce
/test/distancematrix.cpp
c8302f2b2d2818d77f7d2c0db5b976926493a72d
[ "BSD-3-Clause" ]
permissive
ahasgw/Helium
23f10825960ec39bfa2dcb9586aa4e1232ea203b
5af83de373e56c18b537ff68946cd568a9a88ef8
refs/heads/master
2020-12-13T18:27:17.402352
2017-09-22T09:37:43
2017-09-22T09:37:43
46,963,215
0
0
null
2015-11-27T06:19:40
2015-11-27T06:19:40
null
UTF-8
C++
false
false
1,002
cpp
distancematrix.cpp
#include <Helium/distancematrix.h> #include "test.h" using namespace Helium; int main() { SymmetricDistanceMatrix m1(3, 0, 99); COMPARE(0, m1(0, 0)); COMPARE(99, m1(0, 1)); COMPARE(99, m1(0, 2)); COMPARE(99, m1(1, 0)); COMPARE(0, m1(1, 1)); COMPARE(99, m1(1, 2)); COMPARE(99, m1(2, 0)); COMPARE(99, m1(2, 1)); COMPARE(0, m1(2, 2)); m1(0, 0) = 1; m1(1, 0) = 2; m1(1, 1) = 3; m1(2, 0) = 4; m1(2, 1) = 5; m1(2, 2) = 6; COMPARE(1, m1(0, 0)); COMPARE(2, m1(0, 1)); COMPARE(4, m1(0, 2)); COMPARE(2, m1(1, 0)); COMPARE(3, m1(1, 1)); COMPARE(5, m1(1, 2)); COMPARE(4, m1(2, 0)); COMPARE(5, m1(2, 1)); COMPARE(6, m1(2, 2)); m1(0, 0) = 10; m1(0, 1) = 20; m1(0, 2) = 30; m1(1, 1) = 40; m1(1, 2) = 50; m1(2, 2) = 60; COMPARE(10, m1(0, 0)); COMPARE(20, m1(0, 1)); COMPARE(30, m1(0, 2)); COMPARE(20, m1(1, 0)); COMPARE(40, m1(1, 1)); COMPARE(50, m1(1, 2)); COMPARE(30, m1(2, 0)); COMPARE(50, m1(2, 1)); COMPARE(60, m1(2, 2)); }
b77710e0127855c3c26c04804337413fcb7219e6
c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29
/src/module-wx.new/generated/Class_wx_FileCtrlEvent.cpp
aec82e1253ef85f39b1cb1c928a8ecef8ad9ad97
[]
no_license
gura-lang/gura
972725895c93c22e0ec87c17166df4d15bdbe338
03aff5e2b7fe4f761a16400ae7cc6fa7fec73a47
refs/heads/master
2021-01-25T08:04:38.269289
2020-05-09T12:42:23
2020-05-09T12:42:23
7,141,465
25
0
null
null
null
null
UTF-8
C++
false
false
5,833
cpp
Class_wx_FileCtrlEvent.cpp
//---------------------------------------------------------------------------- // wxFileCtrlEvent //---------------------------------------------------------------------------- #include "stdafx.h" Gura_BeginModuleScope(wx) //---------------------------------------------------------------------------- // Gura interfaces for wxFileCtrlEvent //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Object implementation for wxFileCtrlEvent //---------------------------------------------------------------------------- Object_wx_FileCtrlEvent::~Object_wx_FileCtrlEvent() { } Object *Object_wx_FileCtrlEvent::Clone() const { return nullptr; } String Object_wx_FileCtrlEvent::ToString(bool exprFlag) { String rtn("<wx.FileCtrlEvent:"); if (GetEntity() == nullptr) { rtn += "invalid>"; } else { char buff[64]; ::sprintf(buff, "%p>", GetEntity()); rtn += buff; } return rtn; } //---------------------------------------------------------------------------- // Constructor implementation //---------------------------------------------------------------------------- Gura_DeclareFunctionAlias(__FileCtrlEvent, "FileCtrlEvent") { SetFuncAttr(VTYPE_any, RSLTMODE_Normal, FLAG_None); //DeclareArg(env, "type", VTYPE_number, OCCUR_Once); //DeclareArg(env, "evtObject", VTYPE_number, OCCUR_Once); //DeclareArg(env, "id", VTYPE_number, OCCUR_Once); SetClassToConstruct(Gura_UserClass(wx_FileCtrlEvent)); DeclareBlock(OCCUR_ZeroOrOnce); } Gura_ImplementFunction(__FileCtrlEvent) { //wxEventType type = arg.GetNumber(0) //wxObject* evtObject = arg.GetNumber(1) //int id = arg.GetNumber(2) //wxFileCtrlEvent(type, evtObject, id); return Value::Nil; } //---------------------------------------------------------------------------- // Method implementation //---------------------------------------------------------------------------- Gura_DeclareMethodAlias(wx_FileCtrlEvent, __GetDirectory, "GetDirectory") { SetFuncAttr(VTYPE_any, RSLTMODE_Normal, FLAG_None); } Gura_ImplementMethod(wx_FileCtrlEvent, __GetDirectory) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //wxString _rtn = pThis->GetEntity()->GetDirectory(); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __GetFile, "GetFile") { SetFuncAttr(VTYPE_any, RSLTMODE_Normal, FLAG_None); } Gura_ImplementMethod(wx_FileCtrlEvent, __GetFile) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //wxString _rtn = pThis->GetEntity()->GetFile(); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __GetFiles, "GetFiles") { SetFuncAttr(VTYPE_any, RSLTMODE_Normal, FLAG_None); } Gura_ImplementMethod(wx_FileCtrlEvent, __GetFiles) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //wxArrayString _rtn = pThis->GetEntity()->GetFiles(); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __GetFilterIndex, "GetFilterIndex") { SetFuncAttr(VTYPE_any, RSLTMODE_Normal, FLAG_None); } Gura_ImplementMethod(wx_FileCtrlEvent, __GetFilterIndex) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //int _rtn = pThis->GetEntity()->GetFilterIndex(); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __SetFiles, "SetFiles") { SetFuncAttr(VTYPE_any, RSLTMODE_Void, FLAG_None); //DeclareArg(env, "files", VTYPE_number, OCCUR_Once); } Gura_ImplementMethod(wx_FileCtrlEvent, __SetFiles) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //const wxArrayString& files = arg.GetNumber(0) //pThis->GetEntity()->SetFiles(files); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __SetDirectory, "SetDirectory") { SetFuncAttr(VTYPE_any, RSLTMODE_Void, FLAG_None); //DeclareArg(env, "directory", VTYPE_number, OCCUR_Once); } Gura_ImplementMethod(wx_FileCtrlEvent, __SetDirectory) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //const wxString& directory = arg.GetNumber(0) //pThis->GetEntity()->SetDirectory(directory); return Value::Nil; } Gura_DeclareMethodAlias(wx_FileCtrlEvent, __SetFilterIndex, "SetFilterIndex") { SetFuncAttr(VTYPE_any, RSLTMODE_Void, FLAG_None); //DeclareArg(env, "index", VTYPE_number, OCCUR_Once); } Gura_ImplementMethod(wx_FileCtrlEvent, __SetFilterIndex) { Object_wx_FileCtrlEvent *pThis = Object_wx_FileCtrlEvent::GetObjectThis(arg); if (pThis->IsInvalid(env)) return Value::Nil; //int index = arg.GetNumber(0) //pThis->GetEntity()->SetFilterIndex(index); return Value::Nil; } //---------------------------------------------------------------------------- // Class implementation for wxFileCtrlEvent //---------------------------------------------------------------------------- Gura_ImplementUserInheritableClass(wx_FileCtrlEvent) { // Constructor assignment Gura_AssignFunction(__FileCtrlEvent); // Method assignment Gura_AssignMethod(wx_FileCtrlEvent, __GetDirectory); Gura_AssignMethod(wx_FileCtrlEvent, __GetFile); Gura_AssignMethod(wx_FileCtrlEvent, __GetFiles); Gura_AssignMethod(wx_FileCtrlEvent, __GetFilterIndex); Gura_AssignMethod(wx_FileCtrlEvent, __SetFiles); Gura_AssignMethod(wx_FileCtrlEvent, __SetDirectory); Gura_AssignMethod(wx_FileCtrlEvent, __SetFilterIndex); } Gura_ImplementDescendantCreator(wx_FileCtrlEvent) { return new Object_wx_FileCtrlEvent((pClass == nullptr)? this : pClass, nullptr, nullptr, OwnerFalse); } Gura_EndModuleScope(wx)
230b9fcbc2a955692b08e288cc96ec4c23277182
79e15180945b36c328e55e445081401bf160218b
/Part2/Old interface files/Tenant.h
09c14cacdf82f309dafb5d575d41b52643eccaa9
[]
no_license
vandor5676/COMP3140_GroupProject
d976dd23a0d4f3a3b8a3cb05a532eeca573d5de4
d4070f8c025b49fceed76b0d8d58c836a080914b
refs/heads/main
2023-01-30T18:22:51.568544
2020-12-03T02:10:19
2020-12-03T02:10:19
310,679,082
0
0
null
2020-12-02T00:06:52
2020-11-06T18:44:00
C++
UTF-8
C++
false
false
925
h
Tenant.h
#pragma once //#include "Tenant.h" #include "Person.h" #include <iostream> #include <ctime> /* - Team Project: Stage #1 - Dayton Butler - T00258753 - November 12, 2020 - COMP 3140 */ using namespace std; class Tenant: public Person { private: string job; int unitNumber; time_t moveInDate; double monthlyFee; bool isMonthPaid; public: // Constructors/Deconstructors Tenant(); Tenant(string name, int age, string gender, string job, int unitNumber, time_t moveInDate, double monthlyFee, bool isMonthPaid); Tenant(const Tenant& tenant); ~Tenant(); // Getters/Setters string getJob() const; int getUnitNumber() const; time_t getMoveInDate() const; double getMonthlyFee() const; bool getIsMonthPaid() const; void setJob(string job); void setUnitNumber(int unitNumber); void setMoveInDate(time_t moveInDate); void setMonthlyFee(double monthlyFee); void setIsMonthPaid(bool isMonthPaid); void profile(); };
b92ee2f77482e03f04502fa143cfd908b2d9f6d6
afcd06153c085b1784954c19dbbe4fc0bfd6a56d
/qpainter_and_math/CGALDemo.cpp
abaa04cc17c4f778c3860ce16cef4bd4125f8095
[]
no_license
ngzqqb/chapter01
f1d3c360dfb76d922d07ca4b3de1fd1ba86dd00c
7d38cb87093994a01ea427052bd267107cdd5e03
refs/heads/master
2020-05-09T13:44:41.580399
2019-07-19T13:03:22
2019-07-19T13:03:22
181,165,081
0
0
null
null
null
null
UTF-8
C++
false
false
5,951
cpp
CGALDemo.cpp
#include "CGALDemo.hpp" #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Constrained_Delaunay_triangulation_2.h> #include <CGAL/Triangulation_face_base_with_info_2.h> #include <CGAL/Exact_circular_kernel_2.h> #include <CGAL/Polygon_2.h> #include "DrawCircleByThreePoint.hpp" namespace sstd { template<typename B, typename E> inline static auto drawPolygon(QGraphicsScene * argScene, B argPos, const E argEnd, const QPen & argPen = {}, const QBrush & argBrush = {}) { QVector<QPointF> varPoints; for (; argPos != argEnd; ++argPos) { varPoints.push_back({ argPos->x(),argPos->y() }); } return argScene->addPolygon({ std::move(varPoints) }, argPen, argBrush); } inline const QColor globalPolygonBoundColor{ 200,10,10 }; class FaceInfo2 { public: inline FaceInfo2() { } int nesting_level{ 0 }; inline bool in_domain() const { return (nesting_level & 1) != 0; } private: sstd_class(FaceInfo2); }; using K = CGAL::Exact_predicates_inexact_constructions_kernel; using Vb = CGAL::Triangulation_vertex_base_2<K>; using Fbb = CGAL::Triangulation_face_base_with_info_2<FaceInfo2, K>; using Fb = CGAL::Constrained_triangulation_face_base_2<K, Fbb>; using TDS = CGAL::Triangulation_data_structure_2<Vb, Fb>; using Itag = CGAL::Exact_predicates_tag; using CDT = CGAL::Constrained_Delaunay_triangulation_2<K, TDS, Itag>; using Point = CDT::Point; using Polygon_2 = CGAL::Polygon_2<K>; inline void mark_domains(CDT& ct, CDT::Face_handle start, int index, std::list<CDT::Edge>& border) { if (start->info().nesting_level != -1) { return; } std::list<CDT::Face_handle> queue; queue.push_back(start); while (!queue.empty()) { CDT::Face_handle fh = queue.front(); queue.pop_front(); if (fh->info().nesting_level == -1) { fh->info().nesting_level = index; for (int i = 0; i < 3; ++i) { CDT::Edge e(fh, i); CDT::Face_handle n = fh->neighbor(i); if (n->info().nesting_level == -1) { if (ct.is_constrained(e)) { border.push_back(e); } else { queue.push_back(n); } } } } } } /* 1.将所有三角形域标记为-1; 2.将所有与非限定性边相邻的三角形域标记为0; 3.如果一个标记为-1的域与一个标记为非-1的域相邻于限定性边,则非-1域+1; 对于限定性三角形,nesting_level为偶数,则为外,为奇数则为内。 */ inline void mark_domains(CDT& cdt) { for (CDT::All_faces_iterator it = cdt.all_faces_begin(); it != cdt.all_faces_end(); ++it) { it->info().nesting_level = -1; } std::list<CDT::Edge> border; mark_domains(cdt, cdt.infinite_face(), 0, border); while (!border.empty()) { CDT::Edge e = border.front(); border.pop_front(); CDT::Face_handle n = e.first->neighbor(e.second); if (n->info().nesting_level == -1) { mark_domains(cdt, n, e.first->info().nesting_level + 1, border); } } } CGALDemo::CGALDemo() : SubWindowBasic(QStringLiteral("CGALDemo")) { auto varScene = this->scene(); CDT varCDT; /*准备数据 ... */ Polygon_2 polygon1; polygon1.push_back(Point(0, 0)); polygon1.push_back(Point(100, -50)); polygon1.push_back(Point(200, 0)); polygon1.push_back(Point(200, 200)); polygon1.push_back(Point(0, 200)); Polygon_2 polygon2; polygon2.push_back(Point(50, 50)); polygon2.push_back(Point(150, 50)); polygon2.push_back(Point(150, 150)); polygon2.push_back(Point(50, 150)); /*绘制多边形边界 ... */ drawPolygon(varScene, polygon1.vertices_begin(), polygon1.vertices_end(), globalPolygonBoundColor)->setZValue(100); drawPolygon(varScene, polygon2.vertices_begin(), polygon2.vertices_end(), globalPolygonBoundColor)->setZValue(100); CDT cdt; cdt.insert_constraint(polygon1.vertices_begin(), polygon1.vertices_end(), true/*要求闭合曲线*/); cdt.insert_constraint(polygon2.vertices_begin(), polygon2.vertices_end(), true/*要求闭合曲线*/); mark_domains(cdt); auto varFace = cdt.finite_faces_begin(); const auto varFaceEnd = cdt.finite_faces_end(); std::array< QPointF, 3 > varTriangle; for (; varFace != varFaceEnd; ++varFace) { if (!varFace->info().in_domain()) { continue; } for (int varI = 0; varI < 3; ++varI) { const auto & varPoint = varFace->vertex(varI)->point(); varTriangle[varI].setX(varPoint.x()); varTriangle[varI].setY(varPoint.y()); } drawPolygon(varScene, varTriangle.begin(), varTriangle.end(), { QColor{},2 }, QColor{ 200,200,200 }); drawCircleByThreePoint(varScene, varTriangle[0], varTriangle[1], varTriangle[2], { QColor{100,100,100},1.2 }) ->setZValue(998); } } }/*namespace sstd*/ /*endl_input_of_latex_for_clanguage_lick*/ // https://doc.cgal.org/latest/Triangulation_2/ // https://doc.cgal.org/latest/Triangulation_2/classCGAL_1_1Constrained__triangulation__2.html // https://doc.cgal.org/latest/Circular_kernel_2/index.html
ddcbdfa290880fce2e72924a9fc109ee11967051
a54ca44c3a5eaf3b090bbcf7b03e9e13ecdee013
/Paradox/src/System/Component/Transform.hpp
bef17121c67d8dac2549a99608c15dc30f26e716
[]
no_license
sysfce2/SFML_Paradox
2a891a15fa24a22d23173e510393dde706afb572
d7ee266f79e7d145311f0877b03980b1351a08a7
refs/heads/master
2023-03-16T09:51:34.770766
2018-11-25T22:38:25
2018-11-25T22:38:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
170
hpp
Transform.hpp
#pragma once // SFML #include <SFML/System/Vector2.hpp> namespace paradox { struct Transform { sf::Vector2f position; sf::Vector2f scale; float rotation; }; }
aa80827bebb4b7525c14c113a2d029cd40f6fb60
0f62e5c87982c4c0a0d05b5c16d779d335bdb959
/HiddenLayer.h
57bcefba2247ab4787cb086fdb5a0009e0f51cd5
[]
no_license
sherryshare/dlpc
b657714287b6e761af59dd3295d869122f1e368f
a2918c9fbbc42ee752d1b764a5f33f617547a45b
refs/heads/master
2021-01-23T22:36:56.317409
2014-03-21T03:41:06
2014-03-21T03:41:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
HiddenLayer.h
#ifndef DLPC_HIDDENLAYER_H_ #define DLPC_HIDDENLAYER_H_ #include "utils.h" namespace dlpc { template<class T> class HiddenLayer { public: HiddenLayer(int, int, int, double**, double*); ~HiddenLayer(); void sample_h_given_v(T*, T*); public: int n_in;//any other way to change? int n_out; double **W;//vj->hi <=> w[i][j] double *b; protected: double output(T*, double*, double); protected: int batch_size;//batch size };//end class HiddenLayer }//end namespace dlpc #include <HiddenLayer.cpp> #endif
23d1d4776fabcd9b76d178273b194b1686f7b62a
3f0424e00a1c3fd3428bf633b52ec0c206734d64
/pi_copterVS/Stabilization.cpp
a230a3e80448fd8dcfae9323a5c64907e7771102
[]
no_license
2cool/pi_copterVS
60d1f4323aefc9bfcea3ef0a43747605e733138c
7d3c3eacfcec3dc85f538479d23422f8ee93f99a
refs/heads/master
2021-01-19T07:52:18.033978
2017-11-15T17:24:38
2017-11-15T17:24:38
87,581,101
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
9,616
cpp
Stabilization.cpp
// // // #include "define.h" #include "WProgram.h" #include "Stabilization.h" #include "AP_PID.h" #include "mpu.h" #include "MS5611.h" #include "Autopilot.h" #include "GPS.h" #include "debug.h" #include "Balance.h" #include "Prog.h" #include "Log.h" void StabilizationClass::init(){ accXY_stabKP = 0.2f;//0.5 accXY_stabKP_Rep = 1.0f / accXY_stabKP; set_acc_xy_speed_kp(5); set_acc_xy_speed_kI(2); set_acc_xy_speed_imax(Balance.get_max_angle()); max_speed_xy = MAX_HOR_SPEED; XY_KF_DIST = 0.1f; XY_KF_SPEED = 0.1f; //-------------------------------------------------------------------------- last_accZ = 1; //Z_CF_DIST = 0.03; //Z_CF_SPEED = 0.005; Z_CF_DIST = 0.03; Z_CF_SPEED = 0.005; accZ_stabKP = 1;//єто било ошибочное решение. било 0.2 в прошлом году стояло 0.5. короче он улетел. accZ_stabKP_Rep = 1.0f / accZ_stabKP; pids[ACCZ_SPEED].kP(0.1f); pids[ACCZ_SPEED].kI(0.06f); pids[ACCZ_SPEED].imax(MAX_THROTTLE_-HOVER_THROTHLE); max_stab_z_P = MAX_VER_SPEED_PLUS; max_stab_z_M = MAX_VER_SPEED_MINUS; XY_FILTER = 0.06; Z_FILTER = 0.1; sX=sY=sZ = 0; speedZ = speedX = speedY = mc_pitch=mc_roll=mc_z=0; fprintf(Debug.out_stream,"stab init\n"); } //bool flx = false, fly = false; float StabilizationClass::accxy_stab(float dist, float maxA, float timeL) { return sqrt(2 * maxA*dist) - maxA*timeL; } float StabilizationClass::accxy_stab_rep(float speed, float maxA, float timeL) { float t = speed / maxA + timeL; return 0.5*maxA*t*t; } //33 max speed on pressureat 110000 const float air_drag_k = 9.8f / (float)(PRESSURE_AT_0 * 33 * 33); float air_drag(const float speed){ return abs(speed)*speed*MS5611.pressure*air_drag_k; } float air_drag_wind(const float a){ float w=(float)sqrt(abs(a / (MS5611.pressure*air_drag_k))); return (a < 0) ? -w : w; } void StabilizationClass::setDefaultMaxSpeeds(){//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! max_speed_xy = MAX_HOR_SPEED; max_stab_z_P = MAX_VER_SPEED_PLUS; max_stab_z_M = MAX_VER_SPEED_MINUS; } void StabilizationClass::init_XY(const float sx, const float sy){ sX = sx; sY = sy; //resset_xy_integrator(); // gps_sec = GPS.loc.mseconds; } int cnnnnn = 0; #define MAX_A 1 void StabilizationClass::set_XY_2_GPS_XY() { sX = GPS.loc.dX; sY = GPS.loc.dY; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //float old_gps_bearing = 0, cos_bear = 1, sin_bear = 0; void StabilizationClass::XY(float &pitch, float&roll,bool onlyUpdate){ //#ifdef FALSE_WIRE // const float ax = -Mpu.accX; // const float ay = -Mpu.accY; //#else const float ax = (-Mpu.cosYaw*Mpu.accX + Mpu.sinYaw*Mpu.accY); const float ay = (-Mpu.cosYaw*Mpu.accY - Mpu.sinYaw*Mpu.accX); //#endif //--------------------------------------------------------prediction sX += Mpu.dt*(speedX + ax*Mpu.dt*0.5f); speedX += (ax*Mpu.dt); sY += Mpu.dt*(speedY + ay*Mpu.dt*0.5f); speedY += (ay*Mpu.dt); // -------------------------------------------------------corection sX += (GPS.loc.dX - sX)*XY_KF_DIST; speedX += (GPS.loc.speedX - speedX)*XY_KF_SPEED; //-------------------------------------------------------- sY += (GPS.loc.dY - sY)*XY_KF_DIST; speedY += (GPS.loc.speedY - speedY)*XY_KF_SPEED; if (Log.writeTelemetry) { Log.loadByte(LOG::STABXY); Log.loadFloat(sX); Log.loadFloat(speedX); Log.loadFloat(sY); Log.loadFloat(speedY); } if (onlyUpdate) { mc_pitch = mc_roll = 0; return; } float stabX, stabY; if (Autopilot.progState() && Prog.intersactionFlag){ stabX = Prog.stabX; stabY = Prog.stabY; } else{ const float dist = (float)sqrt(sX*sX + sY*sY); const float max_speed = min(getSpeed_XY(dist),max_speed_xy); stabX = abs((GPS.loc.cosDirection)*max_speed); if (sX < 0) stabX *= -1.0f; stabY = abs((GPS.loc.sinDirection)*max_speed); if (sY < 0) stabY *= -1.0f; } float glob_pitch, glob_roll; float need_acx = constrain((stabX + speedX), -7, 7); float need_acy = constrain((stabY + speedY), -7, 7); mc_pitch += ((need_acx + Mpu.e_accX) - mc_pitch)*XY_FILTER; mc_roll += ((need_acy + Mpu.e_accY) - mc_roll)*XY_FILTER;; glob_pitch = -pids[ACCX_SPEED].get_pid(mc_pitch, Mpu.dt); glob_roll = pids[ACCY_SPEED].get_pid(mc_roll, Mpu.dt); //----------------------------------------------------------------преобр. в относительную систему координат pitch = Mpu.cosYaw*glob_pitch - Mpu.sinYaw*glob_roll; roll = Mpu.cosYaw*glob_roll + Mpu.sinYaw*glob_pitch ; /* if ((cnnnnn & 3) == 0) { Debug.load(0, (sX )*0.1, (sY)*0.1); //Debug.load(1, speedX, speedY); Debug.dump(); } cnnnnn++; */ } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float old_altitude = 0; void StabilizationClass::init_Z(){ sZ = MS5611.altitude(); //speedZ = speedz; //Stabilization.resset_z(); } float deltaZ = 0; int tttcnt = 0; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float StabilizationClass::Z(bool onlyUpdate){///////////////////////////////////////////////////////////// float alt = MS5611.altitude(); sZ += Mpu.dt*(speedZ + Mpu.accZ*Mpu.dt*0.5f); sZ += (alt - sZ)*Z_CF_DIST; speedZ += Mpu.accZ*Mpu.dt; speedZ += (MS5611.speed - speedZ)*Z_CF_SPEED; if (Log.writeTelemetry) { Log.loadByte(LOG::STABZ); Log.loadFloat(sZ); Log.loadFloat(speedZ); } if (onlyUpdate) { mc_z = 0; return 0; } //добавить плавний старт //float accZ = Autopilot.get_throttle(); float stab = getSpeed_Z(Autopilot.fly_at_altitude() - sZ); stab = constrain(stab, max_stab_z_M, max_stab_z_P); mc_z += (stab - speedZ - mc_z)*Z_FILTER; float fZ = HOVER_THROTHLE + pids[ACCZ_SPEED].get_pid(mc_z, Mpu.dt)*Balance.powerK(); // if (++tttcnt == 3){ // tttcnt = 0; //Debug.load(0, speedZ,speedZf);// (MS5611.altitude - Autopilot.flyAtAltitude)); // Debug.load(0, Autopilot.flyAtAltitude - sZ, stab - speedZ); //Debug.dump(); //Serial.println(pids[ACCZ_SPEED].get_integrator()); //Debug.dump(fZ, sZ, Autopilot.flyAtAltitude, 0); //Out.println(fZ); // } //if (millis() - Autopilot.start_time < 5000 && (sZ - Autopilot.fly_at_altitude())>2) // Autopilot.motors_do_on(false, e_ESK_ERROR); return fZ; } void StabilizationClass::resset_z(){ pids[ACCZ_SPEED].reset_I(); pids[ACCZ_SPEED].set_integrator(max(HOVER_THROTHLE,Autopilot.get_throttle()) - HOVER_THROTHLE); } void StabilizationClass::resset_xy_integrator(){ pids[ACCX_SPEED].reset_I(); pids[ACCY_SPEED].reset_I(); } string StabilizationClass::get_z_set(){ ostringstream convert; convert<<\ accZ_stabKP<<","<<pids[ACCZ_SPEED].kP()<<","<<\ pids[ACCZ_SPEED].kI()<<","<<pids[ACCZ_SPEED].imax()<<","<<\ max_stab_z_P<<","<<max_stab_z_M<<","<<\ Z_CF_SPEED<<","<<Z_CF_DIST<<","<< Z_FILTER; string ret = convert.str(); return string(ret); } void StabilizationClass::setZ(const float *ar){ int error = 1; if (ar[SETTINGS_ARRAY_SIZE] == SETTINGS_IS_OK){ error = 0; float t; uint8_t i = 0; error += Commander._set(ar[i++], accZ_stabKP); accZ_stabKP_Rep = 1.0f / accZ_stabKP; t = pids[ACCZ_SPEED].kP(); if ((error += Commander._set(ar[i++],t))==0) pids[ACCZ_SPEED].kP(t); t = pids[ACCZ_SPEED].kI(); if ((error += Commander._set(ar[i++], t))==0) pids[ACCZ_SPEED].kI(t); t = pids[ACCZ_SPEED].imax(); if ((error += Commander._set(ar[i++], t))==0) pids[ACCZ_SPEED].imax(t); error += Commander._set(ar[i++], max_stab_z_P); error += Commander._set(ar[i++], max_stab_z_M); error += Commander._set(ar[i++], Z_CF_SPEED); error += Commander._set(ar[i++], Z_CF_DIST); t = Z_FILTER; if ((error += Commander._set(ar[i++], t)) == 0) Z_FILTER=t; //resset_z(); fprintf(Debug.out_stream,"Stabilization Z set:\n"); for (uint8_t ii = 0; ii < i; ii++){ fprintf(Debug.out_stream,"%f,",ar[ii]); } fprintf(Debug.out_stream,"%f\n",ar[i]); } if (error>0){ fprintf(Debug.out_stream,"Stab Z set Error\n"); } } string StabilizationClass::get_xy_set(){ ostringstream convert; convert<<\ accXY_stabKP<<","<<pids[ACCX_SPEED].kP()<<","<<\ pids[ACCX_SPEED].kI()<<","<<pids[ACCX_SPEED].imax()<<","<<\ max_speed_xy<<","<<XY_KF_SPEED<<","<<XY_KF_DIST<<","<< XY_FILTER; string ret = convert.str(); return string(ret); } void StabilizationClass::setXY(const float *ar){ int error = 1; if (ar[SETTINGS_ARRAY_SIZE] == SETTINGS_IS_OK){ error = 0; float t; uint8_t i = 0; error += Commander._set(ar[i++], accXY_stabKP); accXY_stabKP_Rep = 1.0f / accXY_stabKP; t = pids[ACCX_SPEED].kP(); if ((error += Commander._set(ar[i++], t))==0) set_acc_xy_speed_kp(t); t = pids[ACCX_SPEED].kI(); if ((error += Commander._set(ar[i++], t))==0) set_acc_xy_speed_kI(t); t = pids[ACCX_SPEED].imax(); if ((error += Commander._set(ar[i++], t))==0) set_acc_xy_speed_imax(t); error += Commander._set(ar[i++], max_speed_xy); error += Commander._set(ar[i++], XY_KF_SPEED); error += Commander._set(ar[i++], XY_KF_DIST); t = XY_FILTER; if ((error += Commander._set(ar[i++], t))==0) XY_FILTER=t; //resset_xy_integrator(); fprintf(Debug.out_stream,"Stabilization XY set:\n"); for (uint8_t ii = 0; ii < i; ii++){ fprintf(Debug.out_stream,"%f,",ar[ii]); } fprintf(Debug.out_stream,"%f\n",ar[i]); } if (error>0) { fprintf(Debug.out_stream,"Stab XY set Error\n"); } } StabilizationClass Stabilization;
364e01f7740adb849315254d6da32bd560878af3
7f3d55675a5732501bb2ad0931b73a90b54b5c3b
/fakecoins/grader/fakecoins.h
d8a2c0d3f99ecd25cb5feabe1a75f0fcff02033c
[]
no_license
Alaxe/interactive-training
c4b9e74e1980516277bc4d689f9314dec9c47e0a
0277e3f2401ca4274a45ca1f89fe4556d4e53cb9
refs/heads/master
2021-06-24T07:23:17.898609
2017-09-07T16:06:23
2017-09-07T16:06:23
101,668,300
1
1
null
null
null
null
UTF-8
C++
false
false
151
h
fakecoins.h
#ifndef FAKECOINS_H #define FAKECOINS_H #include <vector> int compare_coins(std::vector<int> a, std::vector<int> b); int find_heavier(int n); #endif
4cf3fc9aea2bc867c6317b4fa9dfa740d8184a82
d43aab4146efe35ca06b06e110c61f5c47e9bc1e
/src/model_detector.h
23dc058fb9506cfb0b5ce085c39593675c60d7dd
[]
no_license
glstr/conversion_ccg
e8981c54540655c2e1f7fc4dac189e667650d747
3dfb37c860ff48ab7bf9e99d09d1bf033642a5f2
refs/heads/master
2020-04-09T11:18:19.930282
2019-05-05T05:52:51
2019-05-05T05:52:51
160,304,964
0
0
null
null
null
null
UTF-8
C++
false
false
110
h
model_detector.h
#pragma once class ModelDetector { public: ModelDetector(void) {} virtual ~ModelDetector(void) {} }
b8cd8779dfcc8d7460324967f431565ff8c9e514
ca03f257af0e4fb6a4afc04b374c4e61db37fa47
/CAFrogger/Game.h
3e9f19ed7a7738fafd8c3bfc7c530b75aaf91e46
[]
no_license
chriscoo/CA-Frogger
42df80d2bb57ab735b3c4ea806b2205a94466d7d
91662ea86ce47e60b40020d232ad000deae021b1
refs/heads/master
2020-03-21T00:53:21.176210
2016-11-22T14:20:00
2016-11-22T14:20:00
74,777,697
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
Game.h
#pragma once #include <SFML\Graphics.hpp> #include "TextureHolder.h" #include "World.h" #include "PlayerControl.h" namespace GEX { class Game { public: Game(); void run(); private: void processInputs(); //real time events(movement) void update(sf::Time dt); void render(); void updateStats(sf::Time dt); //sf::RectangleShape getDrawableBounds(); private: sf::RenderWindow _window; World _world; PlayerControl _player; sf::Font _font; sf::Text _statText; }; }
3e209a8e31dcf065a78a327d82aa8dad818ac6d9
96a26094f47d4001202d490d1a1722b4debbf768
/temperature.cpp
44c65407fad36e0d8657f824885dce825c93d3f1
[]
no_license
LeyangYu1996/EC500_IoTControlSys
4d29e769655e3e54d3f3e4e810aa22737c273273
1022fd91aea54c279e97b6333369537a0916ef0d
refs/heads/master
2020-09-07T06:44:52.138227
2019-12-15T18:16:53
2019-12-15T18:16:53
220,689,976
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
temperature.cpp
#include <stdio.h> #include <fcntl.h> #include <linux/i2c-dev.h> #include <errno.h> #include <cstring> #include <sys/ioctl.h> #include <unistd.h> #define I2C_ADDR 0x23 int main(void) { while(1){ int fd; char buf[3]; char val,value; float flight; fd=open("/dev/i2c-1",O_RDWR); if(fd<0) { printf("打开文件错误:%s\r\n",strerror(errno)); return 1; } if(ioctl( fd,I2C_SLAVE,I2C_ADDR)<0 ) { printf("ioctl 错误 : %s\r\n",strerror(errno));return 1; } val=0x01; if(write(fd,&val,1)<0) { printf("上电失败\r\n"); } val=0x11; if(write(fd,&val,1)<0) { printf("开启高分辨率模式2\r\n"); } usleep(200000); if(read(fd,&buf,3)){ flight=(buf[0]*256+buf[1])*0.5/1.2; printf("光照度: %6.2flx\r\n",flight); } else{ printf("读取错误\r\n"); } } }
d41c06ffc4957dd787b5ea5481d333a2976b50d6
849bbd9d6a7d1b440375e954f75692c971013d29
/Code/Scripts/LFA/remembrall.cpp
717e3d2cca6e0b723965eda418dbba537bfde034
[]
no_license
fhmourao/remembrallFramework
b410ff5781786bf8557296b04a1437000aeb488c
589a60a30cfc2b29987d23f54acc5c5c7537f308
refs/heads/master
2020-06-26T09:23:51.724448
2017-07-24T00:01:48
2017-07-24T00:01:48
97,011,412
0
0
null
null
null
null
UTF-8
C++
false
false
2,397
cpp
remembrall.cpp
/************************************************************************ remembrall.cpp ************************************************************************/ #include "remembrall.h" int main(int argc, char **argv){ std::string buffer; std::string line; char *outputFileName; std::ofstream outputFile; char *testFileName; std::ifstream testFile; char *trainFileName; std::ifstream trainFile; float percentageOfHistory; int contextSize; int recommendationSize; long int testMoment; unsigned int userId; vector<myPair> forgottenItems; HashOfHashes trainingData; User currentUser = User(); if( !(getArguments(&trainFileName, &testFileName, &outputFileName, percentageOfHistory, contextSize, argc, argv)) ){ return 1; } //load training data loadTraingData(trainFileName, trainingData); //open test file trainFile.open(trainFileName); if( !(trainFile.is_open()) ) { std::cout << "\n\t***Error opening input file: " << trainFileName << "\n\n"; exit(-1); } //open test file testFile.open(testFileName); if( !(testFile.is_open()) ) { std::cout << "\n\t***Error opening input file: " << testFileName << "\n\n"; exit(-1); } //open output file outputFile.open(outputFileName); if( !(outputFile.is_open()) ) { std::cout << "\n\t***Error opening input file: " << outputFileName << "\n\n"; exit(-1); } //read test file recommendationSize = 1; while( !testFile.eof() ){ //retrieve next user getline(testFile, line); if(line.size() == 0) break; std::stringstream ss(line); //get userId ss >> buffer; userId = atoi(buffer.c_str()); //get test moment ss >> buffer; testMoment = atol(buffer.c_str()); //verify if is a new user if(userId != currentUser.getUserId()){ //build internal data struct currentUser = User(userId); // load user historic currentUser.setUserHistory(userId, trainFile); recommendationSize = int(percentageOfHistory * (float) currentUser.getHistorySize() + 0.5); } // recommend forgotten items recommendForgottenItems(testMoment, forgottenItems, contextSize, trainingData, currentUser); // print recommendations in output file printRecommendations(currentUser, testMoment, forgottenItems, recommendationSize, outputFile); forgottenItems.clear(); } testFile.close(); trainFile.close(); outputFile.close(); return 0; }
c0271456a665eacfddf92cd922c370e13f5ffaca
8fbc9b8b88f2a6a1314a1ded44aaea17fa509fb1
/src/libs/librocmdr/inc/util/SplitIndices.h
10a3f1f6c6a4ddbea257babf7bee187fb6dd58ae
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
mfranberg/rocmdr
944d83c567e779f9bf333c4751234f7aed8c40cf
856cd3ce739f5daa91740dfa3448fdba62b3c033
refs/heads/master
2021-01-02T22:38:49.259004
2015-03-05T13:11:17
2015-03-05T13:11:17
2,260,417
0
0
null
null
null
null
UTF-8
C++
false
false
628
h
SplitIndices.h
/* * SplitIndices.h * * Created on: Aug 30, 2012 * Author: fmattias */ #ifndef SPLITINDICES_H_ #define SPLITINDICES_H_ #include <utility> /** * Simple class that represents a range of iterations. */ typedef std::pair<size_t, size_t> Range; /** * Determines which indices a partial iterator with the * given index should iterate over. * * @param start Start iteration. * @param stop Stop iteration. * @param index Index of this partial iterator. * @param numParts Number of partial iterators. */ Range splitIndices(size_t start, size_t stop, size_t index, size_t numParts); #endif /* SPLITINDICES_H_ */
dcdff014dd055ca5d4fe1c8f06bae2e09b4dba12
c795e7b8bdd6c081613783bcf210a46f23bf58ef
/BlackJack/player.h
37d59434dbbb1e6a907af4f4a32079f85391eee4
[]
no_license
RohitJhander/ArtificialIntelligence
22f1b09be3496eb6efa64dfc6565a98898b40833
d97f34f229e4d115b3836ed14ed0b68f1d2001d2
refs/heads/master
2020-12-30T13:40:24.252486
2017-05-14T13:26:55
2017-05-14T13:26:55
91,244,371
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
player.h
#ifndef __PLAYER_H_INCLUDED__ #define __PLAYER_H_INCLUDED__ #include <vector> #include <utility> #include "globals.h" // State Space void createStateSpace(); void readDealerMaps(); // Transition vector<transition> getPossibleTransitions(state,action); // Reward double reward(int); // Graph void createGraph(); // Policy void computePolicyWithoutSplit(double); void computePolicyWithSplit(); // Utility void printState(state); void printAction(action); void printPolicy(); void printPolicyWithSplit(); #endif
9e0a9fd95accca9376413d4abe178a0cbb972676
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/gmake-examples/test-DevCppDLL/main.cpp
a75f2e6c6275792edf3279f46d6d5c66d7fbd350
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
GB18030
C++
false
false
740
cpp
main.cpp
#include <Windows.h> #include <tchar.h> #include <iostream> struct IXyz { virtual int Foo(int n) = 0; virtual void Release() = 0; }; extern "C" IXyz* WINAPI GetXyz(); int _tmain(int /*argc*/, _TCHAR* /*argv*/[]) { //_tsetlocale(LC_ALL, _T("")); //std::wcout.imbue(std::locale("")); setlocale(LC_ALL, ""); std::ios_base::sync_with_stdio(false); // 缺少的话,wcout wchar_t 会漏掉中文 std::wcin.imbue(std::locale("")); std::wcout.imbue(std::locale("")); // 1. COM-like usage. IXyz* pXyz = GetXyz(); if(pXyz) { int retval = pXyz->Foo(42); std::cout << retval << std::endl; pXyz->Release(); } return 0; }
11557b7d345831cd13a0f5b8c58e26aa534c54f0
b63e2b0b963328c33d99f0cd0ea87684bbdb20a6
/Source/AdvGamesProgramming/EnemyCharacter.cpp
b5a7bd9e5d65edb18519f416284cded6d8427821
[]
no_license
SV3N77/Advance-Games-Programming
249ce3857e628c36cf2461280fa07bf2f2eb86af
9d616eec93b8869f3809f83540d4efa9c5a9a73f
refs/heads/master
2023-01-02T20:15:46.016011
2020-11-01T10:54:47
2020-11-01T10:54:47
291,460,336
0
0
null
null
null
null
UTF-8
C++
false
false
8,150
cpp
EnemyCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "EnemyCharacter.h" #include "EngineUtils.h" #include "Engine/World.h" // Sets default values AEnemyCharacter::AEnemyCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; CurrentAgentState = AgentState::PATROL; } // Called when the game starts or when spawned void AEnemyCharacter::BeginPlay() { Super::BeginPlay(); PerceptionComponent = FindComponentByClass<UAIPerceptionComponent>(); if (!PerceptionComponent) { UE_LOG(LogTemp, Error, TEXT("NO PERCEPTION COMPONENT FOUND")) } PerceptionComponent->OnTargetPerceptionUpdated.AddDynamic(this, &AEnemyCharacter::SensePlayer); HealthComponent = FindComponentByClass<UHealthComponent>(); DetectedActor = nullptr; bCanSeeActor = false; bHeardActor = false; // initialise the variable to false } void AEnemyCharacter::AgentPatrol() { if (Path.Num() == 0 && Manager != nullptr) { Path = Manager->GeneratePath(CurrentNode, Manager->AllNodes[FMath::RandRange(0, Manager->AllNodes.Num() - 1)]); } } void AEnemyCharacter::AgentEngage() { if (Path.Num() == 0 && Manager != nullptr) { if ((GetActorLocation() - CurrentNode->GetActorLocation()).IsNearlyZero(150.0f)) { Path = Manager->GeneratePath(CurrentNode, Manager->FindNearestNode(DetectedActor->GetActorLocation())); } } if (bCanSeeActor) { DirectionToTarget = DetectedActor->GetActorLocation() - this->GetActorLocation(); Fire(DirectionToTarget); } } void AEnemyCharacter::AgentEvade() { if (Path.Num() == 0 && Manager != nullptr) { if ((GetActorLocation() - CurrentNode->GetActorLocation()).IsNearlyZero(150.0f)) { Path = Manager->GeneratePath(CurrentNode, Manager->FindFurthestNode(DetectedActor->GetActorLocation())); } } if (bCanSeeActor) { DirectionToTarget = DetectedActor->GetActorLocation() - this->GetActorLocation(); Fire(DirectionToTarget); } } void AEnemyCharacter::AgentInvestigate() { FTimerHandle DelayHandle; if (bHeardActor == true) // if the AI hears the player's whistle { if (Path.Num() == 0 && Manager != nullptr) { if ((GetActorLocation() - CurrentNode->GetActorLocation()).IsNearlyZero(150.0f)) { Path = Manager->GeneratePath(CurrentNode, Manager->FindNearestNode(DetectedActor->GetActorLocation())); // generate a path to the location of the sound //GetWorldTimerManager().SetTimer(DelayHandle, this, &AEnemyCharacter::AgentPatrol, 5.0f, false); // add a delay when the AI investigates the location of the sound, before returning to PATROL (not working) } } } } void AEnemyCharacter::SensePlayer(AActor* ActorSensed, FAIStimulus Stimulus) { if(Stimulus.WasSuccessfullySensed()) { if(Stimulus.Tag.IsEqual("Noise")) { DetectedActor = ActorSensed; bHeardActor = true; UE_LOG(LogTemp, Warning, TEXT("Player Heard")) } else { DetectedActor = ActorSensed; bCanSeeActor = true; UE_LOG(LogTemp, Warning, TEXT("Player Detected")) } } else { bHeardActor = false; bCanSeeActor = false; } /* //Getting the Senses ID from enemy character HearingSenseID = UAISense::GetSenseID<UAISense_Hearing>(); SightSenseID = UAISense::GetSenseID<UAISense_Sight>(); //Runs if the perception component of the hearing sense ID is not pointing to null if (PerceptionComponent->GetSenseConfig(HearingSenseID) != nullptr) { //Supposed to get the perception info of the freshest trace of hearing sense ID const FActorPerceptionInfo* HeardPerceptionInfo = PerceptionComponent->GetFreshestTrace(HearingSenseID); //Supposed to run when there is an active stimulus of heardperceptioninfo towards the target stimulus if (HeardPerceptionInfo != nullptr && PerceptionComponent->HasActiveStimulus(*HeardPerceptionInfo->Target, HearingSenseID)) { //Supposed to get the location of stimulus StimulusLocation = HeardPerceptionInfo->GetStimulusLocation(HearingSenseID); bHeardActor = true; UE_LOG(LogTemp, Warning, TEXT("Player Detected")) } } else if (PerceptionComponent->GetSenseConfig(SightSenseID) != nullptr) { //supposed to get the perception info for sight const FActorPerceptionInfo* SightPerceptionInfo = PerceptionComponent->GetFreshestTrace(SightSenseID); //when there is an active stimulus of SightPerceptionInfo towards the target stimulus if (SightPerceptionInfo != nullptr && PerceptionComponent->HasActiveStimulus(*SightPerceptionInfo->Target, SightSenseID)) { bCanSeeActor = true; UE_LOG(LogTemp, Warning, TEXT("Player Detected")) } } else { bHeardActor = false; bCanSeeActor = false; UE_LOG(LogTemp, Warning, TEXT("Player Lost")) }*/ /*{ if (Stimulus.WasSuccessfullySensed()) { DetectedActor = ActorSensed; bCanSeeActor = true; UE_LOG(LogTemp, Warning, TEXT("Player Detected")) } else { bCanSeeActor = false; UE_LOG(LogTemp, Warning, TEXT("Player Lost")) } }*/ } //I tried to do this with the onperceptionupdated function but wasn't able to covert it from blueprints to c++ /* void AEnemyCharacter::SensePlayer(TArray<AActor*>& ActorSensed ) { for (AActor* Actor : ActorSensed) { //PerceptionInfo = PerceptionComponent->GetActorInfo(Actor&); //PerceptionComponent->GetActorsPerception(Actor, PerceptionInfo); } }*/ void AEnemyCharacter::MoveAlongPath() { if (Path.Num() > 0 && Manager != nullptr) { //UE_LOG(LogTemp, Display, TEXT("Current Node: %s"), *CurrentNode->GetName()) if ((GetActorLocation() - CurrentNode->GetActorLocation()).IsNearlyZero(1500.0f)) { UE_LOG(LogTemp, Display, TEXT("At Node %s"), *CurrentNode->GetName()) CurrentNode = Path.Pop(); } else { FVector WorldDirection = CurrentNode->GetActorLocation() - GetActorLocation(); WorldDirection.Normalize(); //UE_LOG(LogTemp, Display, TEXT("The World Direction(X:%f,Y:%f,Z:%f)"), WorldDirection.X, WorldDirection.Y, WorldDirection.Z) AddMovementInput(WorldDirection, 1.0f); //Get the AI to face in the direction of travel. FRotator FaceDirection = WorldDirection.ToOrientationRotator(); FaceDirection.Roll = 0.f; FaceDirection.Pitch = 0.f; //FaceDirection.Yaw -= 90.0f; SetActorRotation(FaceDirection); } } } // Called every frame void AEnemyCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (CurrentAgentState == AgentState::PATROL) { if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() >= 0.4f) { CurrentAgentState = AgentState::ENGAGE; Path.Empty(); } else if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() < 0.4f) { Path.Empty(); CurrentAgentState = AgentState::EVADE; } else if (bHeardActor == true) { Path.Empty(); CurrentAgentState = AgentState::INVESTIGATE; } AgentPatrol(); } else if (CurrentAgentState == AgentState::ENGAGE) { if (bCanSeeActor == false) { CurrentAgentState = AgentState::PATROL; } else if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() < 0.4f) { Path.Empty(); CurrentAgentState = AgentState::EVADE; } AgentEngage(); } else if (CurrentAgentState == AgentState::EVADE) { if (bCanSeeActor == false) { CurrentAgentState = AgentState::PATROL; } else if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() >= 0.4f) { CurrentAgentState = AgentState::ENGAGE; Path.Empty(); } AgentEvade(); } else if (CurrentAgentState == AgentState::INVESTIGATE) { if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() >= 0.4f) { CurrentAgentState = AgentState::ENGAGE; Path.Empty(); } else if (bCanSeeActor == true && HealthComponent->HealthPercentageRemaining() < 0.4f) { Path.Empty(); CurrentAgentState = AgentState::EVADE; } AgentInvestigate(); } MoveAlongPath(); //Fire(FVector::ZeroVector); } // Called to bind functionality to input void AEnemyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); }
9e441ea93a0e26ff5a302da8ed58ed325335d361
7a36a0652fe0704b4b27f644653e7b0f7e72060f
/TianShan/ContentStore/CacheStoreImpl.cpp
7e04144e84aab7532e6abe57d95905ab3ddb6ebd
[]
no_license
darcyg/CXX
1ee13c1765f1987e293c15b9cbc51ae625ac3a2e
ef288ad0e1624ed0582839f2a5a0ef66073d415e
refs/heads/master
2020-04-06T04:27:11.940141
2016-12-29T03:49:56
2016-12-29T03:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
125,907
cpp
CacheStoreImpl.cpp
// =========================================================================== // Copyright (c) 2006 by // ZQ Interactive, Inc., Shanghai, PRC., // All Rights Reserved. Unpublished rights reserved under the copyright // laws of the United States. // // The software contained on this media is proprietary to and embodies the // confidential technology of ZQ Interactive, Inc. Possession, use, // duplication or dissemination of the software and media is authorized only // pursuant to a valid written license from ZQ Interactive, Inc. // // This software is furnished under a license and may be used and copied // only in accordance with the terms of such license and with the inclusion // of the above copyright notice. This software or any other copies thereof // may not be provided or otherwise made available to any other person. No // title to and ownership of the software is hereby transferred. // // The information in this software is subject to change without notice and // should not be construed as a commitment by ZQ Interactive, Inc. // // Ident : $Id: CacheStoreImpl.cpp $ // Branch: $Name: $ // Author: Hui Shao // Desc : // // Revision History: // --------------------------------------------------------------------------- // $Log: /ZQProjs/TianShan/ContentStore/CacheStoreImpl.cpp $ // // 128 4/03/15 2:39p Hui.shao // thirdPartyCache for Squid // // 127 1/23/15 11:44a Hui.shao // _bProxySessionBook: 1) original CDNSS w/CacheStore set to true, 2) // StreamSegmenter and C2FE set to false // // 126 5/15/14 10:13a Hongquan.zhang // // 125 5/14/14 3:07p Hui.shao // for C2Streaming with index content exposed // // 124 12/11/13 7:43p Hui.shao // added hashed folder calculation // // 123 9/26/13 11:23a Hui.shao // logging // // 122 7/10/13 4:03p Hui.shao // enh#18206 - CacheServer selection policy per UML-E's local-read cost // needs considered // // 121 4/17/13 5:01p Hui.shao // // 120 12/20/12 8:57a Li.huang // // 119 12/19/12 5:23p Hui.shao // // 118 11/26/12 2:51p Hui.shao // added snmp counters to export // // 117 9/20/12 1:37p Hui.shao // // 116 9/20/12 10:26a Hui.shao // // 115 9/19/12 5:30p Hui.shao // // 114 9/19/12 3:13p Hui.shao // // 113 9/18/12 2:07p Hui.shao // enh#16995 - Serve the cached copy that is catching up the PWE copy on // source storage // // 112 9/12/12 12:44p Hui.shao // // 111 9/12/12 11:28a Hui.shao // forced to enable edgeMode of ContentStore if CacheStore is applied // // 110 9/06/12 7:13p Hui.shao // // 109 9/06/12 6:48p Hui.shao // // 108 9/06/12 5:49p Hui.shao // // 107 9/05/12 2:55p Hui.shao // refreshing ContentDB that may be out of date // // 106 9/05/12 12:06p Hui.shao // flag logging // // 105 9/04/12 3:05p Hui.shao // // 103 9/03/12 3:24p Hui.shao // // 102 8/30/12 11:46a Hui.shao // // 101 8/09/12 5:15p Hui.shao // NULL pointer test for linux // // 100 8/09/12 12:21p Hui.shao // corrected logging // // 99 8/06/12 9:39p Hui.shao // // 98 8/06/12 9:36p Hui.shao // // 97 8/06/12 8:48p Hui.shao // export _freeSpacePercent as configurable // // 96 8/06/12 8:36p Hui.shao // // 95 8/06/12 5:19p Hui.shao // // 94 8/06/12 12:50p Hui.shao // store::OnTimer to call ensureSpace() // // 93 8/02/12 5:31p Hui.shao // // 92 8/02/12 4:33p Hui.shao // adjusted PWE proto per portalLocateContent() may returns c2http // // 91 8/02/12 3:17p Hui.shao // quit forwarding if any contentEdge throws ClientError // // 90 7/31/12 12:28p Hui.shao // uncount missed content unless it is confirmed availabe at source // storage // // 89 7/27/12 10:27a Hui.shao // changed maxSpace from GB to MB // // 88 7/26/12 7:20p Hui.shao // enh#16577 to limit max diskspace via configuration // // 87 7/26/12 6:43p Hui.shao // firxed domain barker/probe's bind address // // 86 7/26/12 11:44a Hui.shao // added entry to update load // // 85 7/25/12 4:19p Hui.shao // quit creating stream if local absent and failed to locate at source // storage // // 84 7/25/12 4:12p Hui.shao // added api to list hot locals // // 83 7/25/12 3:56p Li.huang // fix bug 16726 // // 82 7/24/12 2:47p Hui.shao // stat counters on hitrate // // 81 7/19/12 7:36p Hui.shao // adjusted counter list compress logic // // 80 7/19/12 6:06p Hui.shao // // 79 7/19/12 5:35p Hui.shao // added and refer to store-wide rootVolName // // 78 7/19/12 5:16p Hui.shao // // 77 7/18/12 6:57p Hui.shao // // 76 7/18/12 1:54p Li.huang // // 75 7/18/12 10:29a Li.huang // // 74 6/29/12 10:57a Li.huang // // 73 6/28/12 2:53p Hui.shao // // 72 6/28/12 2:26p Li.huang // // 71 6/28/12 1:24p Li.huang // // 70 6/28/12 12:08p Li.huang // // 69 6/28/12 11:43a Li.huang // // 68 6/28/12 11:26a Li.huang // // 67 6/28/12 11:15a Hui.shao // // 66 6/28/12 11:08a Li.huang // // 65 6/28/12 11:05a Li.huang // // 64 6/27/12 6:41p Li.huang // // 63 6/27/12 6:03p Hui.shao // // 61 6/27/12 5:24p Hui.shao // // 59 6/26/12 6:20p Li.huang // // 58 6/26/12 5:26p Hui.shao // // 57 6/26/12 5:03p Hui.shao // FWU to faster find other folders for free space // // 56 6/26/12 2:55p Hui.shao // // 55 6/20/12 7:24p Hui.shao // // 54 6/20/12 4:56p Li.huang // // 53 6/20/12 3:14p Hui.shao // // 52 6/19/12 3:43p Li.huang // // 51 6/19/12 2:58p Li.huang // // 50 6/15/12 3:05p Hui.shao // folder space // // 49 6/14/12 5:15p Hui.shao // // 48 6/14/12 4:36p Hui.shao // // 47 6/13/12 7:50p Hui.shao // some log printing // // 46 6/13/12 6:20p Hui.shao // // 45 6/13/12 11:42a Li.huang // // 44 6/12/12 4:35p Li.huang // // 43 6/12/12 2:48p Hui.shao // // 42 6/12/12 2:12p Hui.shao // // 41 6/11/12 8:16p Hui.shao // // 40 6/11/12 5:20p Li.huang // // 39 6/07/12 6:00p Hui.shao // // 38 6/07/12 11:30a Hui.shao // configuration schema // // 37 6/06/12 4:43p Hui.shao // // 36 6/06/12 4:03p Hui.shao // to print the count result in the log // // 35 5/29/12 2:21p Hui.shao // added new portal portalBookTransferSession() // // 34 5/11/12 2:50p Li.huang // // 33 5/10/12 6:50p Hui.shao // kick off cache missed content per popularity // // 32 4/27/12 6:38p Hui.shao // CacheTask lifetime func // // 31 4/27/12 3:37p Build // // 30 4/26/12 6:32p Hui.shao // the map of external source stores: reg exp of pid => c2 interface // // 29 4/25/12 4:36p Hui.shao // drafted most unpopular list of TopFolder // // 28 4/25/12 11:10a Hui.shao // // 27 4/23/12 3:19p Hui.shao // // 26 4/23/12 2:55p Hui.shao // configuration of up/down stream NIC, determin the destIP in // cacheContent() automatically // // 25 4/18/12 6:47p Hui.shao // // 24 4/17/12 11:18a Hui.shao // for the content::provision() parameters // // 23 4/16/12 5:06p Li.huang // // 22 4/16/12 4:11p Hui.shao // // 21 4/13/12 1:36p Hui.shao // enabled exportContentAsStream() with external CDNSS // // 20 4/11/12 10:37a Li.huang // // 19 4/09/12 2:28p Hui.shao // // 18 4/09/12 2:23p Hui.shao // // 17 3/26/12 3:58p Li.huang // // 16 3/22/12 5:13p Hui.shao // // 15 1/19/12 12:09p Hui.shao // // 14 1/18/12 6:24p Li.huang // // 13 1/18/12 1:50p Hui.shao // linkable // // 12 1/17/12 11:35a Hui.shao // linkable // // 11 1/16/12 10:35p Hui.shao // defined the counter and topfolder at ice level // // 10 1/16/12 1:22p Hui.shao // // 9 1/13/12 2:24p Hui.shao // splitted counter and folder into separate cpp files // // 8 1/12/12 7:02p Hui.shao // // 7 1/06/12 2:55p Hui.shao // // 6 1/06/12 2:01p Hui.shao // // 5 1/06/12 11:53a Hui.shao // // 4 12/30/11 2:28p Hui.shao // // 3 12/29/11 8:27p Hui.shao // cacheContent() // // 2 12/22/11 3:30p Hui.shao // the try-catches // // 1 12/22/11 1:38p Hui.shao // created // =========================================================================== #include "CacheStoreImpl.h" #include "MD5CheckSumUtil.h" #include "CacheCmds.h" #include "ContentState.h" #include "ContentCmds.h" #include "urlstr.h" #include "../CDNLib/CDNDefines.h" #include "TianShanIceHelper.h" #include <set> // for multiset extern "C" { #ifdef ZQ_OS_MSWIN #include <io.h> #else #include <sys/stat.h> #endif #include <math.h> }; #ifndef min # define min(_X, _Y) ((_X>_Y)?_Y:_X) #endif #define RoundToKbps(_bps) ((_bps +999)/1000) #define CATEGORY_CacheTask "CacheTask" #define CATEGORY_TopFolder "TopFolder" #define SUBFILE_EXTNAME_index "index" #define INSTANCE_DEFAULT_PWR (1.1) #define MEM_EVICTOR namespace ZQTianShan { namespace ContentStore { #define storelog (_log) #ifndef FUNCNAME #define FUNCNAME(_FN) #_FN "() " #endif // __FUNCNAME__ // ----------------------------- // CacheStoreImpl utilities // ----------------------------- bool CacheStoreImpl::_calcHashKey(CacheStoreImpl::HashKey& key, const char* buf, uint len) { if (NULL == buf) return false; if (len <=0) len = strlen(buf); memset(&key.bytes, 0x00, sizeof(key.bytes)); ZQ::common::md5 encoder; encoder.Update((unsigned char*)buf, len); encoder.Finalize(); memcpy(&key.bytes, encoder.Digest(), sizeof(key.bytes)); return true; } std::string CacheStoreImpl::_contentHashKeyToFolder(const HashKey& contentHKey, std::string& topFolderName, std::string& leafFolderName) { char buf[32] = "\0"; uint8 t=0, l=1; for (int i =0; i < 8; i++) { t ^= contentHKey.bytes.b[2*i]; l ^= contentHKey.bytes.b[2*i+1]; } t &= CACHE_FOLDER_MASK; l &= CACHE_FOLDER_MASK; snprintf(buf, sizeof(buf)-2, TOP_FOLDER_FMT, t); topFolderName = buf; snprintf(buf, sizeof(buf)-2, LEAF_FOLDER_FMT, l); leafFolderName = buf; return std::string(LOGIC_FNSEPS) + topFolderName + LOGIC_FNSEPS + leafFolderName + LOGIC_FNSEPS; } uint64 CacheStoreImpl::_calcRawDistance(const HashKey& contentKey, const HashKey& storeKey) { uint64 sqrSum =0; for (int i=0; i < sizeof(HashKey) / sizeof(uint16); i++) { int32 diff = contentKey.words.w[i] - storeKey.words.w[i]; sqrSum += diff*diff; } return sqrSum; } // ----------------------------- // module CacheStoreImpl // ----------------------------- CacheStoreImpl::CacheStoreImpl(ZQ::common::Log& log, ZQ::common::Log& eventlog, const char* serviceName, ContentStoreImpl& contentStore, ::TianShanIce::Streamer::StreamServicePrx pStreamSevice, ZQ::common::NativeThreadPool& thpool) : _contentStore(contentStore), _adapter(contentStore._adapter), _log(log), _eventlog(eventlog), _thpool(thpool), _prxStreamService(pStreamSevice), _watchDog(log, thpool, contentStore._adapter, "CacheStore"), _probe(*this), _barker(*this), _maxCandidates(0), _flags(0), _acMissed(NULL), _acHotLocals(NULL), _stampLocalCounterFlushed(0), // _acMissed("Missed"), _acHotLocals("HotLocal"), _groupAddr(CACHESTORE_DEFAULT_GROUPIP), _groupPort(CACHESTORE_DEFAULT_GROUPPORT), _maxSpaceMB(0), _freeSpacePercent(10), _pwrRanking(INSTANCE_DEFAULT_PWR), _prevLoadThreshold(CACHE_LOADTHRSH_DEFAULT_PREV), _successorLoadThreshold(CACHE_LOADTHRSH_DEFAULT_SUCR), _maxUnpopular(CACHE_DEFAULT_UnpopularSize), _penaltyOfFwdFail(PENALTY_FORWARD_FAILED_DEFAULT), _defaultProvSessionBitrateKbps(DEFAULT_PROV_SPEED_Kbps), _minBitratePercent(0), _paidLength(DEFAULT_PAID_LEN), _defaultTransferServerPort(12000), _catchUpRTminPercent(50), _catchUpRT(60000), _bProxySessionBook(true), _thirdPartyCache(false) { // _acMissed.name="Missed", _acHotLocals.name="HotLocal"; _serviceName = (NULL == serviceName) ? serviceName : "CacheStore"; _acMissed = new AccessRegistrarImpl(*this, "Missed"); _acHotLocals = new AccessRegistrarImpl(*this, "HotLocal"); _usedProvisionKbps = 0; _heatbeatInterval = 1000; _stampLastScanMissed = ZQ::common::now(); // When this CacheStore layer is enabled, the under layer ContentStore must has the following enabled // a) edge mode // b) InServiceCheck _contentStore._edgeMode = true; _contentStore._enableInServiceCheck = 1; resetCounters(); } CacheStoreImpl::~CacheStoreImpl() { } bool CacheStoreImpl::doInit() { try { // step 1. initialize _thisDescriptor _thisDescriptor.desc.netId = _contentStore._netId; _thisDescriptor.desc.domain = _contentStore._replicaGroupId; _thisDescriptor.desc.state = ::TianShanIce::stNotProvisioned; _thisDescriptor.desc.loadStream = _thisDescriptor.desc.loadCacheWrite =_thisDescriptor.desc.loadImport =0; _thisDescriptor.desc.stampAsOf = 0; //TODO: string _thisDescriptor.desc.sessionInterface; ///< the session interface that can setup stream sessions of contents on the CacheStore _calcHashKey(_thisDescriptor.cskey, _thisDescriptor.desc.netId.c_str(), _thisDescriptor.desc.netId.length()); _thisDescriptor.penalty = 0; _thisDescriptor.stampLastPenalty = 0; _thisDescriptor.stampStartup = ZQ::common::now(); // step 2. call to initialize the portal layer initializePortal(*this); // step 3. to open/initialize the database openDB(); _factory = new CacheFactory(*this); /* { // step 3.1 TODO: #pragma message ( __TODO__ "read configuration to build up _extSourceStores by calling _extSourceStores::set() or setDefault()") SourceStores::StoreInfo si; si.sessionInterface = "c2http://10.15.10.64:10080/"; // dummy test data, should be replaced _extSourceStores.setDefault(si); } */ // step 4. call to initialize the hash folders if (!_initFolders()) return false; // step 5. to initialize the distance and load-weight tables if (_prevLoadThreshold <= _successorLoadThreshold) { _prevLoadThreshold = CACHE_LOADTHRSH_DEFAULT_PREV; _successorLoadThreshold = CACHE_LOADTHRSH_DEFAULT_SUCR; } int i; for (i =0; i < CACHE_SCOPED_INSTANCE_MAX; i ++) { double t = pow((double)i+1, (double) _pwrRanking); _distSqrByRankTbl[i] = (float) ((t>=1.0) ? (1.0- 1/t) : 1.0); _distSqrByRankTbl[i] *= _distSqrByRankTbl[i]; } _loadWeightTbl[0] =1; for (i =1; i < CACHE_SCOPED_INSTANCE_MAX; i ++) { double r = _distSqrByRankTbl[i-1] + _prevLoadThreshold * _prevLoadThreshold; r -= _distSqrByRankTbl[i]; if (_successorLoadThreshold >0) r /= _successorLoadThreshold * _successorLoadThreshold; _loadWeightTbl[i] = r; } // step 6. to start the probe and barker _probe.start(); _barker.start(); // step 7. start the watch dog _watchDog.start(); // step 8. start serving serve(true); proxy(); // to initialize _thisDescriptor.desc.theStore } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, doInit, "failed to initialize cotentStore")); return false; } return true; } void CacheStoreImpl::doUninit( ) { // stop the probe and barker _probe.stop(); _barker.stop(); _watchDog.quit(); serve(false); _thisDescriptor.desc.state = ::TianShanIce::stOutOfService; uninitializePortal(*this); closeDB(); _closeFolders(); } void CacheStoreImpl::openDB(const char* runtimeDBPath) { closeDB(); if (NULL == runtimeDBPath || strlen(runtimeDBPath) <=0) _dbRuntimePath = _contentStore._dbPath; else _dbRuntimePath = runtimeDBPath; if (FNSEPC != _dbRuntimePath[_dbRuntimePath.length()-1]) _dbRuntimePath += FNSEPS; // step 1. about the topFolder DB try { // open the Indexes _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, openDB, "opening database at path: %s"), _dbRuntimePath.c_str()); #ifdef ZQ_OS_MSWIN ::CreateDirectory(_dbRuntimePath.c_str(), NULL); #else mkdir(_dbRuntimePath.c_str(), 0777); #endif std::vector<Freeze::IndexPtr> indices; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, openDB, "opening " CATEGORY_TopFolder)); #ifdef MEM_EVICTOR _eTopFolder = new MemoryServantLocator(_adapter, CATEGORY_TopFolder); #elif ICE_INT_VERSION / 100 >= 303 _eTopFolder = ::Freeze::createBackgroundSaveEvictor(_adapter, cacheTaskDbPathname, CATEGORY_TopFolder, 0, indices); #else _eTopFolder = Freeze::createEvictor(_adapter, cacheTaskDbPathname, CATEGORY_TopFolder, 0, indices); #endif _adapter->addServantLocator(_eTopFolder, CATEGORY_TopFolder); _eTopFolder->setSize(CACHE_FOLDER_SIZE+10); } catch(const Ice::Exception& ex) { ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 1001, "openDB() DB[topfolder] caught exception[%s]"), ex.ice_name().c_str()); } catch(...) { ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 1001, "openDB() DB[topfolder] caught exception")); } IdentCollection identities; #ifndef MEM_EVICTOR identities.clear(); try { ::Freeze::EvictorIteratorPtr itptr = _eTopFolder->getIterator("", 100); while (itptr->hasNext()) identities.push_back(itptr->next()); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, openDB, "failed to enumerates TopFolders")); } c=0; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, openDB, "%d TopFolders found from DB"), identities.size()); for (it = identities.begin(); it <identities.end(); it ++) { try { ::TianShanIce::Storage::CacheTaskPrx task = IdentityToObj(CacheTask, *it); task->OnRestore(); c++; } catch(...) {} } _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, openDB, "%d of %d TopFolders restored"), c, identities.size()); #endif // MEM_EVICTOR for _eTopFolder // step 1. about the CacheTask DB if (!_thirdPartyCache) { _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, openDB, "ignore DB[CacheTask] per taking 3rd-party cache")); return; } try { std::string cacheTaskDbPathname = createDBFolder(_log, _serviceName.c_str(), _dbRuntimePath.c_str(), CATEGORY_CacheTask, 100*1000); Ice::PropertiesPtr proper = _adapter->getCommunicator()->getProperties(); std::string dbAttrPrefix = std::string("Freeze.DbEnv.") + cacheTaskDbPathname; proper->setProperty(dbAttrPrefix + ".DbRecoverFatal", "1"); proper->setProperty(dbAttrPrefix + ".DbPrivate", "0"); proper->setProperty(dbAttrPrefix + ".OldLogsAutoDelete", "1"); std::vector<Freeze::IndexPtr> indices; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, openDB, "opening database " CATEGORY_CacheTask)); #if ICE_INT_VERSION / 100 >= 303 _eCacheTask = ::Freeze::createBackgroundSaveEvictor(_adapter, cacheTaskDbPathname, CATEGORY_CacheTask, 0, indices); #else _eCacheTask = Freeze::createEvictor(_adapter, cacheTaskDbPathname, CATEGORY_CacheTask, 0, indices); #endif proper->setProperty("Freeze.Evictor." CATEGORY_CacheTask ".PageSize", "8192"); proper->setProperty("Freeze.Evictor." CATEGORY_CacheTask ".$default.BtreeMinKey", "20"); _adapter->addServantLocator(_eCacheTask, CATEGORY_CacheTask); _eCacheTask->setSize(200); } catch(const Ice::Exception& ex) { ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 1001, "openDB() DB[CacheTask] caught exception[%s]"), ex.ice_name().c_str()); } catch(...) { ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 1001, "openDB() DB[CacheTask] caught unknown exception")); } _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, openDB, "restoring CacheTasks")); try { ::Freeze::EvictorIteratorPtr itptr = _eCacheTask->getIterator("", 100); while (itptr->hasNext()) identities.push_back(itptr->next()); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, openDB, "failed to enumerates CacheTasks")); } IdentCollection::iterator it; int c=0; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, openDB, "%d CacheTask(s) found from DB"), identities.size()); for (it = identities.begin(); it <identities.end(); it ++) { try { ::TianShanIce::Storage::CacheTaskPrx task = IdentityToObj(CacheTask, *it); task->OnRestore(); c++; } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, openDB, "restoring CacheTask[%s] caught exception[%s]"), it->name.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, openDB, "restoring CacheTask[%s] caught exception"), it->name.c_str()); } } _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, openDB, "%d of %d CacheTasks restored"), c, identities.size()); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, openDB, "database ready")); } void CacheStoreImpl::closeDB() { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, closeDB, "closing local database")); _eCacheTask = NULL; _eTopFolder = NULL; // not very necessary when MEM_EVICTOR } ::TianShanIce::Storage::CacheStorePrx CacheStoreImpl::proxy(bool collocationOptim) { try { if (!_thisDescriptor.desc.theStore) { //_thisPrx is only modified here static ZQ::common::Mutex thisProxyLocker; ZQ::common::MutexGuard gd(thisProxyLocker); if (!_thisDescriptor.desc.theStore) { _thisDescriptor.desc.theStore = ::TianShanIce::Storage::CacheStorePrx::checkedCast(_adapter->createProxy(_localId)); _thisPrxStr = _adapter->getCommunicator()->proxyToString(_thisDescriptor.desc.theStore); } } // if (collocationOptim) return _thisDescriptor.desc.theStore; // return ::TianShanIce::Storage::CacheStorePrx::checkedCast(_thisDescriptor.desc.theStore->ice_collocationOptimized(false)); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, proxy, "caught exception[%s]"), ex.ice_name().c_str()); } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, proxy, "caught exception")); } return NULL; } void CacheStoreImpl::serve(bool enable) { if (enable && _localId.name.empty()) { try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, serve, "adding the interface[%s] on to the adapter[%s]"), SERVICE_NAME_CacheStore, _adapter->getName().c_str()); _localId = _adapter->getCommunicator()->stringToIdentity(SERVICE_NAME_CacheStore); _contentStore._adapter->ZQADAPTER_ADD(_contentStore._adapter->getCommunicator(), this, SERVICE_NAME_CacheStore); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, serve, "caught exception[%s]"), ex.ice_name().c_str()); } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, serve, "caught exception")); } _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, serve, "adding self under watching")); _watchDog.watch(_localId, 0); _thisDescriptor.desc.state = ::TianShanIce::stInService; } else if (!_localId.name.empty()) { _thisDescriptor.desc.state = ::TianShanIce::stOutOfService; try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, serve, "withdrawing the interface[%s] from the adapter[%s}"), SERVICE_NAME_CacheStore, _contentStore._adapter->getName().c_str()); _contentStore._adapter->remove(_localId); _localId.name = ""; } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, serve, "caught exception[%s]"), ex.ice_name().c_str()); } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, serve, "caught exception")); } } } ::std::string CacheStoreImpl::getAdminUri(const ::Ice::Current& c) { #pragma message ( __TODO__ "impl here") ZQTianShan::_IceThrow<TianShanIce::NotImplemented> (_log, EXPFMT(CacheStore, 9999, "Not implemented yet")); return std::string(""); } ::TianShanIce::State CacheStoreImpl::getState(const ::Ice::Current& c) { return _thisDescriptor.desc.state; } ::TianShanIce::Storage::ContentStorePrx CacheStoreImpl::theContentStore(const ::Ice::Current& c) { return _contentStore.proxy(); } bool CacheStoreImpl::_initFolders() { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _initFolders, "preparing %dx%d subfolder structure"), CACHE_FOLDER_SIZE, CACHE_FOLDER_SIZE); // ::TianShanIce::Storage::VolumePrx root; try { _rootVol = TianShanIce::Storage::VolumeExPrx::uncheckedCast(_contentStore.proxy(true)->openVolume(DEFAULT_VOLUME_STRING)); _rootVolName = _rootVol->getVolumeName(); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "opening root volume caught exception[%s]"), ex.ice_name().c_str()); } catch(...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "opening root volume caught exception")); } if (!_rootVol) return false; bool succ = true; ::TianShanIce::Storage::FolderPrx tfolder; for (int t=0; succ && t < CACHE_FOLDER_SIZE; t++) { char topFolderName[64]; snprintf(topFolderName, sizeof(topFolderName) -2, TOP_FOLDER_FMT, t); try { tfolder = _rootVol->openSubFolder(topFolderName, true, 0); if (!tfolder) succ = false; } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "initializing tf[%s] caught exception[%s]"), topFolderName, ex.ice_name().c_str()); succ =false; continue; } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "initializing tf[%s] caught exception"), topFolderName); succ =false; continue; } /* for (int l=0; succ && l < CACHE_FOLDER_SIZE; l++) { ::TianShanIce::Storage::FolderPrx lfolder; char folderName[64]; snprintf(folderName, sizeof(folderName) -2, LEAF_FOLDER_FMT, l); try { lfolder = tfolder->openSubFolder(folderName, true, 0); if (!lfolder) succ = false; } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "initializing lf[%s] caught exception[%s]"), folderName, ex.ice_name().c_str()); succ =false; continue; } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "initializing lf[%s] caught exception"), folderName); succ =false; continue; } } */ ::Ice::Identity identTop; identTop.name = topFolderName; identTop.category = CATEGORY_TopFolder; ::TianShanIce::Storage::TopFolderPrx topFolder; try { topFolder = IdentityToObj2(TopFolder, identTop); } catch(const Ice::ObjectNotExistException&) { #ifndef MEM_EVICTOR storelog(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _initFolders, "no DB record TF[%s] pre-exists"), topFolderName); #endif // MEM_EVICTOR } catch(...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "checking DB record TF[%s] caught exception"), topFolderName); succ =false; } if (succ && !topFolder) { try { TianShanIce::Storage::TopFolderPtr pTF = new TopFolderImpl(*this); if (!pTF) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "failed to initialize tf[%s] on allocating"), topFolderName); return false; } pTF->ident = identTop; pTF->stampLastRefresh = 0; pTF->maxUnpopular = _maxUnpopular; // pTF->totalSpaceMB = pTF->_freeSpaceMB =0; pTF->usedSpaceMB =0; pTF->contentsOfleaves.resize(CACHE_FOLDER_SIZE); pTF->contentSubtotal =0; _eTopFolder->add(pTF, pTF->ident); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "adding TF[%s] caught exception[%s]"), topFolderName, ex.ice_name().c_str()); succ =false; } catch( ...) { storelog(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, _initFolders, "adding TF[%s] caught exception"), topFolderName); succ =false; } } if (succ) _watchDog.watch(identTop, 1000); } _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, _initFolders, "%s preparing %dx%d subfolder structure"), succ? "finished": "failed at", CACHE_FOLDER_SIZE, CACHE_FOLDER_SIZE); return succ; } void CacheStoreImpl::_closeFolders() { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _closeFolders, "closing folders")); // _topFolders.clear(); _eTopFolder = NULL; } static bool lessRawDist(::TianShanIce::Storage::CacheCandidate i, ::TianShanIce::Storage::CacheCandidate j) { return (i.rawContDistance < j.rawContDistance); } static bool lessIntegratedDist(::TianShanIce::Storage::CacheCandidate i, ::TianShanIce::Storage::CacheCandidate j) { return (i.distance < j.distance); } ::TianShanIce::Storage::CacheCandidates CacheStoreImpl::getCandidatesOfContent(const ::std::string& contentName, bool withLoadConsidered, const ::Ice::Current& c) { ::TianShanIce::Storage::CacheCandidates candidates; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getCandidatesOfContent, "content[%s] withLoadConsidered[%c]"), contentName.c_str(), withLoadConsidered? 'T': 'F'); // step 1. generate the hash key of content name HashKey contentKey; if (contentName.empty() || std::string::npos != contentName.find(ILLEGAL_NAME_CHARS) || !_calcHashKey(contentKey, contentName.c_str(), contentName.length())) ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheStore, 400, "getCandidatesOfContent() invalid contentName[%s] to query"), contentName.c_str()); // step 2. get the store list of neighborhood CacheStoreListInt stores; if (_listNeighorsEx(stores, true, _heatbeatInterval) <=0) ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 500, "getCandidatesOfContent() content[%s] _listNeighorsEx() returns empty list"), contentName.c_str()); // step 3. calculate the raw distances for (CacheStoreListInt::iterator it = stores.begin(); it < stores.end(); it++) { ::TianShanIce::Storage::CacheCandidate cc; cc.distance = -1; cc.isContentEdge = false; cc.csd = it->desc; cc.isSelf = (0 ==_contentStore._netId.compare(cc.csd.netId)); if (!cc.isSelf && it->penalty >0) { if (CacheStoreImpl::sfLoggingDomainMessages & _flags) _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getCandidatesOfContent, "content[%s] skip candidate[%s] per its penalty[%d]"), contentName.c_str(), cc.csd.netId.c_str(), it->penalty); continue; } cc.rawContDistance = _calcRawDistance(contentKey, it->cskey); candidates.push_back(cc); } ::std::sort(candidates.begin(), candidates.end(), lessRawDist); candidates[0].isContentEdge = true; if (!withLoadConsidered) return candidates; // step 3. apply the load into distances ::TianShanIce::Storage::CacheCandidates tmpCandidates; for (size_t i = 0; i < candidates.size(); i++) { // it is unnecessary to enumlate all the known store in the neighorhood if (_maxCandidates >0 && i >= _maxCandidates) break; #pragma message ( __TODO__ "fix units and adjust _maxCandidates here " ) ::TianShanIce::Storage::CacheCandidate& tmpCand = candidates[i]; double d = _distSqrByRankTbl[i]; if (tmpCand.csd.loadStream > CACHE_LOAD_MAX) tmpCand.csd.loadStream = CACHE_LOAD_MAX; if (tmpCand.csd.loadImport > CACHE_LOAD_MAX) tmpCand.csd.loadImport = CACHE_LOAD_MAX; if (tmpCand.csd.loadCacheWrite > CACHE_LOAD_MAX) tmpCand.csd.loadCacheWrite = CACHE_LOAD_MAX; float integratedLoad = max((float)tmpCand.csd.loadStream / CACHE_LOAD_MAX, (float)tmpCand.csd.loadImport / CACHE_LOAD_MAX); // candidate of content will not consider the write load of the node: integratedLoad = max(integratedLoad, (float)tmpCand.csd.loadCacheWrite / CACHE_LOAD_MAX); d += (double) integratedLoad * integratedLoad * _loadWeightTbl[i]; tmpCand.distance = (Ice::Int) (d * CACHE_DIST_MAX); tmpCandidates.push_back(tmpCand); } candidates = tmpCandidates; ::std::sort(candidates.begin(), candidates.end(), lessIntegratedDist); if (CacheStoreImpl::sfLoggingDomainMessages & _flags) { std::string candstr; char buf[100]; int64 stampNow = ZQ::common::now(); for (::TianShanIce::Storage::CacheCandidates::iterator itC = candidates.begin(); itC < candidates.end(); itC++) { snprintf(buf, sizeof(buf)-2, "%s[%d/%d/%d@%d]%d, ", itC->csd.netId.c_str(), itC->csd.loadStream, itC->csd.loadImport, itC->csd.loadCacheWrite, (long) (stampNow -itC->csd.stampAsOf), itC->distance); candstr += buf; } _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, getCandidatesOfContent, "content[%s] candidates %s load: %s"), contentName.c_str(), withLoadConsidered? "w/": "w/o", candstr.c_str()); } return candidates; } // typedef std::queue<TianShanIce::Storage::CacheCandidate, TianShanIce::Storage::CacheCandidates> CacheCandidateQueue; static void cbLogLine(const char* line, void* pCtx) { CacheStoreImpl* pStore = (CacheStoreImpl*) pCtx; if (!pStore) return; pStore->_log(ZQ::common::Log::L_DEBUG, CLOGFMT(CacheStore, "%s"), line); } ::TianShanIce::Streamer::StreamPrx CacheStoreImpl::exportContentAsStream(const ::std::string& contentName, const ::std::string& subFileIn, ::Ice::Int idleStreamTimeout, ::Ice::Int cacheStoreDepth, const ::TianShanIce::SRM::ResourceMap& resourceRequirement, const ::TianShanIce::Properties& params, const ::Ice::Current& c) { ::TianShanIce::Streamer::StreamPrx stream; ::TianShanIce::SRM::ResourceMap resRequirement = resourceRequirement; // make a writeable copy std::string requestSig = std::string("sub[") +subFileIn +"]"; ::TianShanIce::Properties::const_iterator itParam = params.find(SYS_PROP("clientSession")); char buf[100]; if (params.end() != itParam) requestSig += std::string("csess[") + itParam->second + "]"; else if (c.con) { snprintf(buf, sizeof(buf)-2, "%p(%d)", c.con.get(), c.requestId); requestSig += buf; } if (sfLoggingResource & _flags) { snprintf(buf, sizeof(buf)-2, "content[%s] %s resRequirement", contentName.c_str(), requestSig.c_str()); dumpResourceMap(resRequirement, buf, cbLogLine, this); } itParam = params.find(SYS_PROP("client")); if (params.end() != itParam) requestSig += std::string("cilent[") + itParam->second + "]"; bool bExposeIndex = false; itParam = params.find(SYS_PROP("exposeIndex")); if (params.end() != itParam && 0 != atol(itParam->second.c_str())) bExposeIndex = true; #define EXPSTRMFMT(_X) FLOGFMT(CacheStore, exportContentAsStream, "content[%s] %s " _X), contentName.c_str(), requestSig.c_str() int64 stampStart = ZQ::common::now(); std::string strmstr; std::string subFile = subFileIn; if (contentName.empty() || std::string::npos != contentName.find(ILLEGAL_NAME_CHARS)) ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheStore, 400, "exportContentAsStream() invalid contentName[%s] to query"), contentName.c_str()); // step 1. forward the invocation to the contentEdge if needed bool bHandleLocally = (cacheStoreDepth >0); TianShanIce::Storage::CacheCandidates candidates; if (bHandleLocally) _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("initialize with local exporting per depth[%d]"), cacheStoreDepth); else candidates = getCandidatesOfContent(contentName, true, c); int64 stampNow = ZQ::common::now(); int64 stampList = stampNow; int32 latency = 0; // step 1.1 select from the candidates size_t i =0, totalCands = candidates.size(); for (i =0; !bHandleLocally && !candidates.empty() && (_maxCandidates <=0 || i <_maxCandidates) ; i++) { // take the first item of the list TianShanIce::Storage::CacheCandidate topCand = *candidates.begin(); candidates.erase(candidates.begin()); // quit scanning if the top pick is self if (topCand.isSelf) { bHandleLocally = true; _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("self[%s] becomes the top pick of from %d/%d candidates, quit forwarding"), _contentStore._netId.c_str(), i+1, totalCands); break; } int penalty =0; // try to forward the exportContentAsStream() to the ContentEdge int64 stampStartForwarding = ZQ::common::now(); try { stream = NULL; #pragma message ( __TODO__ "quit if the subtotal latency (stampStartForwarding - stampStart) has exceeded a number of msec") if (topCand.csd.theStore) { std::string storeEp = _adapter->getCommunicator()->proxyToString(topCand.csd.theStore); _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("forwarding to %d-th ContentEdge[%s]/load[%d] via endpoint[%s]"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, storeEp.c_str()); stream = topCand.csd.theStore->exportContentAsStream(contentName, subFile, idleStreamTimeout, cacheStoreDepth+1, resRequirement, params); _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("forward tried to %d-th ContentEdge[%s]/load[%d] => strm %s"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, stream? "created" : "null"); } else _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("%d-th ContentEdge[%s]/[%d] has NULL store"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream); stampNow = ZQ::common::now(); if (stream) { countExport(ec_forward, (int32)(stampNow - stampStartForwarding)); strmstr = _adapter->getCommunicator()->proxyToString(stream); _log(ZQ::common::Log::L_INFO, EXPSTRMFMT("successfully exported as stream[%s] from %d-th ContentEdge[%s]/load[%d], latency[%lld/%lld]ms"), strmstr.c_str(), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, stampNow - stampStartForwarding, stampNow - stampStart); return stream; } } catch(const ::TianShanIce::ClientError& ex) { // if any top candidate indicate errors in inputted parameter, quit the loop to try the next candidates _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("quit trying candidates per %d-th ContentEdge[%s]/load[%d] threw %s: %s"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, ex.ice_name().c_str(), ex.message.c_str()); return NULL; } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("caught exception at forwarding to %d-th ContentEdge[%s]/load[%d], %s: %s"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::SocketException& ex) { penalty = _penaltyOfFwdFail; _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("caught exception at forwarding to %d-th ContentEdge[%s]/load[%d], %s, charge penalty[%d]"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, ex.ice_name().c_str(), penalty); } catch(const Ice::TimeoutException& ex) { penalty = 1; _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("caught exception at forwarding to %d-th ContentEdge[%s]/load[%d], %s, charge penalty[%d]"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, ex.ice_name().c_str(), penalty); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("caught exception at forwarding to %d-th ContentEdge[%s]/load[%d], %s"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream, ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("caught exception at forwarding to %d-th ContentEdge[%s]/load[%d]"), i+1, topCand.csd.netId.c_str(), topCand.csd.loadStream); } countExport(ec_forward, (int32)(ZQ::common::now() - stampStartForwarding), false); OnForwardFailed(topCand.csd.netId, penalty); } stampNow = ZQ::common::now(); if (!bHandleLocally && !stream) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("failed to find CacheStore to host the request after %i tries and [%llu]msec"), i, stampNow - stampList); return NULL; } _log(ZQ::common::Log::L_INFO, EXPSTRMFMT("finished finding external CacheStore: %i tries and [%llu]msec; creating stream locally"), i, stampNow - stampStart); // step 2. read the resourceRequirement, adjust if needed // step 2.1 prepare the local PlaylistItemSetupInfo meanwhile TianShanIce::Streamer::PlaylistItemSetupInfo plisi; plisi.inTimeOffset = plisi.outTimeOffset = 0; plisi.criticalStart = 0; plisi.spliceIn = plisi.spliceOut = plisi.forceNormal = false; std::string hashFolderName = getFolderNameOfContent(contentName, c); plisi.contentName = _rootVolName + hashFolderName + contentName; if (subFile.empty()) subFile = "*"; else { size_t pos = subFile.find_first_not_of("."); if (0 != pos) subFile = subFile.substr(pos); } TianShanIce::Properties contentNameToken; portalContentNameToken(*this, contentName, contentNameToken); // fill the name tokens into the prviate data of playlist item for (TianShanIce::Properties::iterator itCT =contentNameToken.begin(); itCT != contentNameToken.end(); itCT++) ZQTianShan::Util::updateValueMapData( plisi.privateData, itCT->first, itCT->second); { ::TianShanIce::Variant v; v.bRange = false; v.type = ::TianShanIce::vtStrings; v.strs.push_back(subFile); MAPSET(::TianShanIce::ValueMap, plisi.privateData, CDN_SUBTYPE, v); MAPSET(::TianShanIce::ValueMap, plisi.privateData, CDN_EXTENSIONNAME, v); std::string tmpstr = std::string(CDN_SUBTYPE "[") +subFile +"] "; // copy the attended params for (::TianShanIce::Properties::const_iterator itParam = params.begin(); itParam !=params.end(); itParam++) { v.strs.clear(); v.strs.push_back(itParam->second); tmpstr += itParam->first + "[" + itParam->second + "] "; MAPSET(::TianShanIce::ValueMap, plisi.privateData, itParam->first, v); } // take the portal the chop the content name into token and metadata, such as PID, PAID and so on for (TianShanIce::Properties::iterator itToken = contentNameToken.begin(); itToken != contentNameToken.end(); itToken++) { tmpstr += itToken->first + "[" + itToken->second + "] "; v.strs.push_back(itToken->second); MAPSET(::TianShanIce::ValueMap, plisi.privateData, itToken->first, v); } _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("=> %s"), tmpstr.c_str()); } bool bStreamFromLocalContent = false; ::TianShanIce::Storage::ContentState localReplicaState = ::TianShanIce::Storage::csNotProvisioned; int32 transferBitrate = -1; std::string extSessionInterface; TianShanIce::Properties strmParams; if (!_thirdPartyCache) { // step 2.2 check if there is local content replica ::TianShanIce::Storage::ContentPrx content; try { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("checking local replica[%s]"), plisi.contentName.c_str()); _contentStore.openFolderEx(_rootVolName + hashFolderName, true, 0, c); // to ensure the subfolder exists content = _contentStore.openContentByFullname(plisi.contentName, c); if (content) { TianShanIce::Properties metaData = content->getMetaData(); TianShanIce::Properties::iterator itMD = metaData.find(SYS_PROP(State)); if (metaData.end() != itMD) localReplicaState = ContentStateBase::stateId(itMD->second.c_str()); itMD = metaData.find(METADATA_BitRate); if (metaData.end() != itMD) transferBitrate = atol(itMD->second.c_str()); _log(ZQ::common::Log::L_INFO, EXPSTRMFMT("found local replica[%s:%s(%d)] encoded bitrate[%d]"), plisi.contentName.c_str(), ContentStateBase::stateStr(localReplicaState), localReplicaState, transferBitrate); } } catch(const Ice::ObjectNotExistException& ex) { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("accessing local replica[%s], caught %s"), plisi.contentName.c_str(), ex.ice_name().c_str()); content = NULL; } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("accessing local replica[%s], caught %s: %s"), plisi.contentName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("accessing local replica[%s], caught %s"), plisi.contentName.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("accessing local replica[%s], caught exception"), plisi.contentName.c_str()); } // step 2.3 adjust the resource[rtTsUpstreamBandwidth] per the status of local content replica _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("adjusting resource[UpstreamBandwidth] per state[%s(%d)]"), ContentStateBase::stateStr(localReplicaState), localReplicaState); std::string strmUsage; switch (localReplicaState) { case ::TianShanIce::Storage::csProvisioningStreamable: case ::TianShanIce::Storage::csInService: // local replica is fully residented, no need for upstream resource _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("local replica[%s:%s(%d)] wipe resource TsUpstreamBandwidth"), plisi.contentName.c_str(), ContentStateBase::stateStr(localReplicaState), localReplicaState); OnLocalContentRequested(contentName, subFile); // trigger the couting too { ZQ::common::MutexGuard g(_lockerNeighbors); if (_maxLocalStreamKbps <=0 || ( (_usedLocalStreamKbps + RoundToKbps(transferBitrate)) < _maxLocalStreamKbps && _usedLocalStreamKbps < (_maxLocalStreamKbps*0.95)) ) bStreamFromLocalContent = true; char tmp[100]; snprintf(tmp, sizeof(tmp)-2, "%d+%d /%d", _usedLocalStreamKbps, RoundToKbps(transferBitrate), _maxLocalStreamKbps); strmUsage = tmp; } break; case ::TianShanIce::Storage::csNotProvisioned: // should count the missed only after the content is confirmed available on remote source storage // OnMissedContentRequested(contentName, subFile); // trigger the counting too // Note: no "break;" here default: break; } // switch (localReplicaState) _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("determined StreamFromLocalContent[%c] per state[%s(%d)] and stream-usage[%s]"), bStreamFromLocalContent?'T':'F', ContentStateBase::stateStr(localReplicaState), localReplicaState, strmUsage.c_str()); } // !_thirdPartyCache if (bStreamFromLocalContent) resRequirement.erase(::TianShanIce::SRM::rtTsUpstreamBandwidth); else { ::TianShanIce::SRM::ResourceMap::iterator itRes = resRequirement.find(::TianShanIce::SRM::rtTsUpstreamBandwidth); if (resRequirement.end() == itRes) ZQTianShan::_IceThrow<TianShanIce::ClientError> (_log, EXPFMT(CacheStore, 400, "exportContentAsStream() content[%s] local replica[%s:%s(%d)] failed at no resource TsUpstreamBandwidth specified"), contentName.c_str(), plisi.contentName.c_str(), ContentStateBase::stateStr(localReplicaState), localReplicaState); ::TianShanIce::ValueMap& upstrmdata = itRes->second.resourceData; if (upstrmdata.end() != upstrmdata.find("bandwidth")) { ::TianShanIce::Variant& vBR = upstrmdata["bandwidth"]; if (vBR.lints.size() >0) transferBitrate = (int32) vBR.lints[0]; } { ::TianShanIce::Variant v; v.type = ::TianShanIce::vtStrings; v.bRange = false; v.strs.push_back(_upStreamBindIP); MAPSET(::TianShanIce::ValueMap, itRes->second.resourceData, "bindAddress", v); } int64 stampStartExtLocate = ZQ::common::now(); //TODO: ?? take some default "bandwidth" if the input resourceRequirement doesn't carry it if (upstrmdata.end() == upstrmdata.find("sessionURL")) // ELSE: the inputd resource requirement has already specified sessionURL, take it and ignore sessionInterface { // the input resource requirement has NOT specified sessionURL, associated it if (upstrmdata.end() != upstrmdata.find("sessionInterface")) { ::TianShanIce::Variant& v = upstrmdata["sessionInterface"]; if (v.strs.size() >0 && std::string::npos == v.strs[0].find_first_of("$")) { extSessionInterface = v.strs[0]; _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("client requested to take sessionInterface[%s]"), extSessionInterface.c_str()); } } if (extSessionInterface.empty()) { // no sessionInterface specified by the input resource requirement _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("looking up the external session interface")); extSessionInterface = findExternalSessionInterfaceByContent(contentName, contentNameToken); if (!extSessionInterface.empty()) { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("found the external session interface[%s], adding it to res[TsUpstreamBandwidth]"), extSessionInterface.c_str()); ::TianShanIce::Variant v; v.type = ::TianShanIce::vtStrings; v.bRange = false; v.strs.push_back(extSessionInterface); MAPSET(::TianShanIce::ValueMap, upstrmdata, "sessionInterface", v); } else if (_bProxySessionBook) ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 400, "exportContentAsStream() failed to find external session interface for contentName[%s] to query"), contentName.c_str()); //TODO: possible to map multiple sessionInterface for a PID?? } if (_bProxySessionBook && !extSessionInterface.empty() && 0 != subFile.compare("*")) // this is an external source library { std::string sessionURL; _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("calling portal for sessionURL")); int nRetCode = portalBookTransferSession(*this, sessionURL, contentNameToken, subFile, extSessionInterface, transferBitrate, strmParams); if (0 == nRetCode) { ::TianShanIce::Variant v; v.type = ::TianShanIce::vtStrings; v.bRange = false; v.strs.push_back(sessionURL); MAPSET(::TianShanIce::ValueMap, upstrmdata, "sessionURL", v); _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("reserved tranferSession[%s], adding it to res[TsUpstreamBandwidth]"), sessionURL.c_str()); countExport(ec_remoteLocate, (int32)(ZQ::common::now() - stampStartExtLocate)); if (::TianShanIce::Storage::csNotProvisioned == localReplicaState) OnMissedContentRequested(contentName, subFile); // trigger the counting too } else { countExport(ec_remoteLocate, (int32)(ZQ::common::now() - stampStartExtLocate), false); ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheStore, nRetCode, "exportContentAsStream() content[%s] failed to locate at source storage[%s]"), contentName.c_str(), extSessionInterface.c_str()); } } } } // if (!bStreamFromLocalContent) // step 3. call StreamService to create stream if (!_prxStreamService) { _log(ZQ::common::Log::L_WARNING, EXPSTRMFMT("failed at creating local stream per no StreamService attached")); return NULL; } int64 stampStartLocal = stampNow; ::TianShanIce::Streamer::PlaylistPrx playlist; try { char buf[64]; snprintf(buf, sizeof(buf)-2, "%d", idleStreamTimeout); MAPSET(::TianShanIce::Properties, strmParams, SYS_PROP(IdleTimeout), buf); if (bExposeIndex) MAPSET(::TianShanIce::Properties, strmParams, SYS_PROP(exposeIndex), "1"); if (sfLoggingResource & _flags) { snprintf(buf, sizeof(buf)-2, "content[%s] %s localstrm res", contentName.c_str(), requestSig.c_str()); dumpResourceMap(resRequirement, buf, cbLogLine, this); } _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("creating stream on local streamer")); stream = _prxStreamService->createStreamByResource(resRequirement, strmParams); #ifndef EXTERNAL_STREAMSVC // this cacheStore IS embedded with a StreamSvc stream = ::TianShanIce::Streamer::StreamPrx::uncheckedCast(stream->ice_collocationOptimized(false)); #endif //EXTERNAL_STREAMSVC playlist = ::TianShanIce::Streamer::PlaylistPrx::checkedCast(stream); } catch(const ::TianShanIce::BaseException& ex) { stream = NULL; _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("creating local stream caught %s: %s"), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { stream = NULL; _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("creating local stream caught %s"), ex.ice_name().c_str()); } catch(...) { stream = NULL; _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("creating local stream caught exception")); } stampNow = ZQ::common::now(); if (!playlist) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("failed to create local stream, took %llu/%llumsec"), stampNow - stampStartLocal, stampNow - stampStart); countExport(ec_local, (int32)(stampNow - stampStartLocal), false); return NULL; } strmstr = _adapter->getCommunicator()->proxyToString(stream); // step 4. render and commit the stream bool bDirtyContentStoreDB =false; int64 stampCreated = stampNow; try { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("replica[%s] is being rendered onto local stream[%s]"), plisi.contentName.c_str(), strmstr.c_str()); playlist->pushBack(1, plisi); // always take userCtrlNum =1 int64 stampRendered = ZQ::common::now(); _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("committing local stream[%s]"), strmstr.c_str()); playlist->commit(); stampNow = ZQ::common::now(); countExport(ec_local, (int32)(stampNow - stampStartLocal)); _log(ZQ::common::Log::L_INFO, EXPSTRMFMT("prepared local stream[%s], took total [%d]msec: scan[%d]msec localcreate[%d]msec render[%d]msec commit[%d]msec"), strmstr.c_str(), (int)(stampNow-stampStart), (int)(stampStartLocal-stampList), (int)(stampCreated -stampStartLocal), (int)(stampRendered -stampCreated), (int)(stampNow -stampRendered)); return stream; } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("preparing stream[%s] caught %s(%d): %s"), strmstr.c_str(), ex.ice_name().c_str(), ex.errorCode, ex.message.c_str()); if (404 == ex.errorCode && bStreamFromLocalContent) bDirtyContentStoreDB = true; } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("preparing stream[%s] caught %s"), strmstr.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("preparing stream[%s] caught exception"), strmstr.c_str()); } // when program reach here, the stream creating has already failed, destory the stream if created stampNow = ZQ::common::now(); countExport(ec_local, (int32)(stampNow - stampStartLocal), false); if (bDirtyContentStoreDB) { ::Ice::Identity identFolder; identFolder.category = DBFILENAME_Volume; identFolder.name = _rootVolName + hashFolderName; // cut off the ending / size_t pos = identFolder.name.find_last_not_of("/\\"); if (pos < identFolder.name.length()) identFolder.name = identFolder.name.substr(0, pos+1); _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("ContentDB may be out-of-date at folder[%s]"), identFolder.name.c_str()); try { // the ContentStore DB may be out of date with the file system because long time no sync // try to start sync it // step 1. read the SYS_PROP(StampLastSyncWithFileSystem) ::TianShanIce::Storage::FolderPrx folder = _contentStore.openFolderEx(identFolder.name, true, 0, c); ::TianShanIce::Storage::VolumeExPrx vol = ::TianShanIce::Storage::VolumeExPrx::checkedCast(folder); #ifndef EXTERNAL_STREAMSVC // this cacheStore IS embedded with a StreamSvc vol = ::TianShanIce::Storage::VolumeExPrx::checkedCast(folder->ice_collocationOptimized(false)); #endif //EXTERNAL_STREAMSVC ::TianShanIce::Storage::VolumeInfo vi = vol->getInfo(); int64 stampLastSync =0; ::TianShanIce::Properties::iterator itMD = vi.metaData.find(SYS_PROP(StampLastSyncWithFileSystem)); if (vi.metaData.end() != itMD) { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("ContentDB may be out-of-date at folder[%s], lastSyncFs[%s]"), identFolder.name.c_str(), itMD->second.c_str()); stampLastSync = ZQ::common::TimeUtil::ISO8601ToTime(itMD->second.c_str()); } // issue a SyncFSCmd to refresh sync if (stampLastSync < stampNow - 30*60*1000) // half hr { _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("refreshing ContentDB at folder[%s] that may be out-of-date"), identFolder.name.c_str()); (new ZQTianShan::ContentStore::SyncFSCmd(_contentStore, identFolder))->execute(); // update a dummy stamp to avoid sync too many times ::TianShanIce::Properties newMD; ZQTianShan::TimeToUTC(stampNow -10*60*1000, buf, sizeof(buf) -2); MAPSET(::TianShanIce::Properties, newMD, SYS_PROP(StampLastSyncWithFileSystem), buf); vol->setMetaData(newMD); } else { ::Ice::Identity identContent; identContent.category = DBFILENAME_Content; identContent.name = plisi.contentName; _log(ZQ::common::Log::L_DEBUG, EXPSTRMFMT("refreshing attributes of local Content[%s] that may be out-of-date"), identContent.name.c_str()); (new ZQTianShan::ContentStore::PopulateFileAttrsCmd(_contentStore, identContent))->execute(); } } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("refreshing out-of-date ContentDB at folder[%s] caught %s: %s"), identFolder.name.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("refreshing out-of-date ContentDB at folder[%s] caught %s"), identFolder.name.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("refreshing out-of-date ContentDB at folder[%s] caught exception"), identFolder.name.c_str()); } } _log(ZQ::common::Log::L_WARNING, EXPSTRMFMT("local stream[%s] failed to complete render and commit, giving it up"), strmstr.c_str()); try { if (stream) stream->destroy(); } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("destroying stream[%s] caught %s: %s"), strmstr.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("destroying stream[%s] caught %s"), strmstr.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, EXPSTRMFMT("destroying stream[%s] caught exception"), strmstr.c_str()); } stream = NULL; return stream; } void CacheStoreImpl::resetCounters() { ZQ::common::MutexGuard g(_lkCounters); memset(_exportCounters, 0x00, sizeof(_exportCounters)); _exportCounters[ec_forward].name = "FowardWithinDomain"; _exportCounters[ec_remoteLocate].name = "RemoteLocate"; _exportCounters[ec_local].name = "LocalStream"; _stampMesureSince = ZQ::common::now(); } void CacheStoreImpl::countExport(ecIndex ecIdx, int32 latencyMsec, bool succ) { bool resetNeeded = false; do { ExportCount& ec = _exportCounters[ecIdx % ec_max]; ZQ::common::MutexGuard g(_lkCounters); if (++ec.count <=0) { resetNeeded = true; break; } if (!succ && ++ec.failCount <=0) { resetNeeded = true; break; } if ((ec.latencyTotal+=latencyMsec) <=0) { resetNeeded = true; break; } if (ec.latencyMax < latencyMsec) ec.latencyMax = latencyMsec; } while(0); if (resetNeeded) resetCounters(); } ::TianShanIce::Storage::ContentAccess CacheStoreImpl::getAccessCount(const ::std::string& contentName, const ::Ice::Current& c) { ::TianShanIce::Storage::AccessCounter counter; counter.base.contentName = contentName; counter.base.accessCount = 0; counter.base.stampLatest = counter.base.stampSince =0; if (_acMissed->get(contentName, counter)) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getAccessCount, "content[%s] found in the missed content list"), contentName.c_str()); return counter.base; } if (_acHotLocals->get(contentName, counter)) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getAccessCount, "content[%s] found in the hot local list"), contentName.c_str()); return counter.base; } counter.base.accessCount = 0; counter.base.stampLatest = counter.base.stampSince =0; try { std::string replicaName = _rootVolName + getFolderNameOfContent(contentName, c); replicaName += contentName; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getAccessCount, "content[%s] looking up the contentStore DB, localReplica[%s]"), contentName.c_str(), replicaName.c_str()); ::TianShanIce::Storage::ContentPrx content = _contentStore.openContentByFullname(replicaName, c); ::TianShanIce::Properties metaData; if (!content) return counter.base; int64 stampNow = ZQ::common::now(); metaData = content->getMetaData(); ::TianShanIce::Properties::iterator itMD = metaData.find(METADATA_AccessCount); if (metaData.end() != itMD) counter.base.accessCount = atoi(itMD->second.c_str()); else counter.base.accessCount = 0; itMD = metaData.find(METADATA_AccessCountSince); if (metaData.end() != itMD) counter.base.stampSince = ZQ::common::TimeUtil::ISO8601ToTime(itMD->second.c_str()); else counter.base.stampSince = stampNow; itMD = metaData.find(METADATA_AccessCountLatest); if (metaData.end() != itMD) counter.base.stampLatest = ZQ::common::TimeUtil::ISO8601ToTime(itMD->second.c_str()); else counter.base.stampLatest = stampNow; } catch(const ::Ice::ObjectNotExistException&) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getAccessCount, "content[%s] access ContentDB caught ObjectNotExistException"), contentName.c_str()); } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getAccessCount, "content[%s] access ContentDB caught %s: %s"), contentName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getAccessCount, "content[%s] access ContentDB caught %s"), contentName.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getAccessCount, "content[%s] access ContentDB caught exception"), contentName.c_str()); } return counter.base; } void CacheStoreImpl::addAccessCount(const ::std::string& contentName, ::Ice::Int countToAdd, const ::std::string& since, const ::Ice::Current& c) { if (countToAdd <=0) return; #pragma message ( __TODO__ "impl here") } void CacheStoreImpl::listMissedContents_async(const ::TianShanIce::Storage::AMD_CacheStore_listMissedContentsPtr& amdCB, ::Ice::Int maxNum, const ::Ice::Current& c) { try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, listMissedContents, "maxNum[%d]"), maxNum); (new ListMissedContentsCmd(*this, amdCB, maxNum))->exec(); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getMissedContentList, "failed to generate ListMissedContentsCmd")); amdCB->ice_exception(::TianShanIce::ServerError("CacheStore", 501, "failed to generate ListMissedContentsCmd")); } } void CacheStoreImpl::listHotLocals_async(const ::TianShanIce::Storage::AMD_CacheStore_listHotLocalsPtr& amdCB, ::Ice::Int maxNum, const ::Ice::Current& c) { try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, listHotLocals, "maxNum[%d]"), maxNum); (new ListHotLocalsCmd(*this, amdCB, maxNum))->exec(); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getMissedContentList, "failed to generate ListMissedContentsCmd")); amdCB->ice_exception(::TianShanIce::ServerError("CacheStore", 501, "failed to generate ListMissedContentsCmd")); } } void CacheStoreImpl::setAccessThreshold(::Ice::Int timeWinOfPopular, ::Ice::Int countOfPopular, ::Ice::Int hotTimeWin, const ::Ice::Current& c) { ZQ::common::MutexGuard g(_cfgLock); _timeWinOfPopular = timeWinOfPopular; _countOfPopular = countOfPopular; _hotTimeWin = hotTimeWin; } void CacheStoreImpl::getAccessThreshold(::Ice::Int& timeWinOfPopular, ::Ice::Int& countOfPopular, ::Ice::Int& hotTimeWin, const ::Ice::Current& c) { ZQ::common::MutexGuard g(_cfgLock); timeWinOfPopular = _timeWinOfPopular; countOfPopular = _countOfPopular; hotTimeWin = _hotTimeWin; } void CacheStoreImpl::_readStoreSpace(int64& freeMB, int64& totalMB) { // assuming all the cache folders are under a same volume, and share the same space limitation do { static int64 stampLastSpaceCheck =0; static int64 sharedFreeSpaceMB=0, sharedTotalSpaceMB=0; static ZQ::common::Mutex lkSpaceCheck; int64 stampNow = ZQ::common::now(); if (sharedTotalSpaceMB <=0 || stampNow - stampLastSpaceCheck > 1000*10) { ZQ::common::MutexGuard g(lkSpaceCheck); if (sharedTotalSpaceMB >0 && stampNow - stampLastSpaceCheck <= 1000*10) break; try { _rootVol->getCapacity(sharedFreeSpaceMB, sharedTotalSpaceMB); stampLastSpaceCheck = stampNow; if (_freeSpacePercent <5) _freeSpacePercent = 5; else if (_freeSpacePercent >50) _freeSpacePercent =50; if (_maxSpaceMB >0) { int64 diffMB = sharedTotalSpaceMB - _maxSpaceMB; if (diffMB > sharedFreeSpaceMB) { sharedTotalSpaceMB = _maxSpaceMB; sharedFreeSpaceMB -=diffMB; } else if (diffMB >0) { sharedTotalSpaceMB = _maxSpaceMB; sharedFreeSpaceMB = 0; } } storelog(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _readStoreSpace, "read volume space[F%lld/T%lld]MB"), sharedFreeSpaceMB, sharedTotalSpaceMB); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _readStoreSpace, "read volume space caught exception[%s]"), ex.ice_name().c_str()); } catch(...) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _readStoreSpace, "read volume space caught exception")); } } freeMB = sharedFreeSpaceMB; totalMB = sharedTotalSpaceMB; } while (0); } bool CacheStoreImpl::_ensureSpace(long neededMB, const std::string& forTopFolderName) { // check if there is free enough space for this caching Ice::Long totalMB=0, freeMB=0, usedMB=0; Ice::Long sizeToFreeMB =neededMB; // _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "size[%d]MB under TF[%s]"), neededMB, forTopFolderName.c_str()); ::Ice::Identity identTop; identTop.category = CATEGORY_TopFolder; if (forTopFolderName.empty()) { // no specific to folder is given, initialize the sizeToFreeMB by _maxSpaceMB _readStoreSpace(freeMB, totalMB); sizeToFreeMB = totalMB * _freeSpacePercent /100 + neededMB - freeMB; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "read space usage: [%lld]MB <= usage[U%lld/T%lld/F%lld]MB -[%lld]MB"), neededMB, usedMB, totalMB, freeMB, (sizeToFreeMB >0 ? sizeToFreeMB:0)); if (totalMB <=0) return false; } else { try { identTop.name = forTopFolderName; ::TianShanIce::Storage::TopFolderPrx topFolder = IdentityToObj(TopFolder, identTop); if (!topFolder->getSpaceUsage(totalMB, freeMB, usedMB)) return false; sizeToFreeMB = totalMB * _freeSpacePercent /100 + neededMB - freeMB; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "TF[%s] read space usage: [%lld]MB <= usage[U%lld/T%lld/F%lld]MB -[%lld]MB"), forTopFolderName.c_str(), neededMB, usedMB, totalMB, freeMB, (sizeToFreeMB >0 ? sizeToFreeMB:0)); if (totalMB <=0) return false; if (sizeToFreeMB <=0) return true; Ice::Long confirmedMB =0; if (topFolder && sizeToFreeMB >0) topFolder->freeForSpace(sizeToFreeMB, confirmedMB); sizeToFreeMB -=confirmedMB; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "TF[%s] confirmed to free %lldMB for needed %lldMB"), forTopFolderName.c_str(), confirmedMB, neededMB); } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _ensureSpace, "TF[%s] caught exception[%s]"), forTopFolderName.c_str(), ex.ice_name().c_str()); } catch(...) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _ensureSpace, "TF[%s] caught exception"), forTopFolderName.c_str()); } } if (sizeToFreeMB <=0) return true; FWUSequence fwuseq = _sortFolderByFWU(); if (fwuseq.size() <=0) _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _ensureSpace, "empty folder list by sorting FWUs")); for (size_t i =0; i < fwuseq.size() && sizeToFreeMB >0; i++) { if (!forTopFolderName.empty() && 0 == forTopFolderName.compare(fwuseq[i].topFolderName)) continue; try { identTop.name = fwuseq[i].topFolderName; if (_flags & CacheStoreImpl::sfLoggingUnpopularScan) _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "calling TF[%s] to free space[%lld]MB"), identTop.name.c_str(), sizeToFreeMB); ::TianShanIce::Storage::TopFolderPrx topFolder = IdentityToObj(TopFolder, identTop); Ice::Long confirmedMB =0; if (topFolder) topFolder->freeForSpace(sizeToFreeMB, confirmedMB); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, _ensureSpace, "neighbor TF[%s] confirmed to free space[%lld] for [%lld]MB"), identTop.name.c_str(), confirmedMB, sizeToFreeMB); sizeToFreeMB -=confirmedMB; } catch(const Ice::Exception& ex) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _ensureSpace, "neighbor TF[%s] caught exception[%s]"), fwuseq[i].topFolderName.c_str(), ex.ice_name().c_str()); } catch(...) { storelog(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, _ensureSpace, "neighbor TF[%s] caught exception"), fwuseq[i].topFolderName.c_str()); } } return (sizeToFreeMB <=0); } #define bpsToFileSizeMB(bps, sec) (((int64)bps * sec /8 + 1024*1024 -1) /1024/1024) void CacheStoreImpl::cacheContent(const ::std::string& contentName, const ::TianShanIce::Storage::CacheStorePrx& sourceCS, const ::TianShanIce::Properties& params, const ::Ice::Current& c) { if (_thirdPartyCache) return; ::TianShanIce::Storage::CacheStorePrx sourceStore = sourceCS; //step 0. validate the input parameters if (contentName.empty() || std::string::npos != contentName.find(ILLEGAL_NAME_CHARS)) ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheStore, 400, "cacheContent() invalid contentName[%s]"), contentName.c_str()); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] sig[%s]"), contentName.c_str(), invokeSignature(c).c_str()); int64 stampNow = ZQ::common::now(); /* std::string startTime = startTimeStr; if (startTimeStr.empty() || stampNow > ZQ::common::TimeUtil::ISO8601ToTime(startTimeStr.c_str())) { char buf[40]; if (ZQ::common::TimeUtil::TimeToUTC(stampNow, buf, sizeof(buf) -2)) startTime = buf; _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, cacheContent, "content[%s] adjusted startTime[%s] to [%s]"), contentName.c_str(), startTimeStr.c_str(), startTime.c_str()); } */ // step 1. start with a CacheTask CacheTaskImpl::Ptr pTask = newCacheTask(contentName); // booked the bw according to available resource if (!pTask) ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 500, "cacheContent() contentName[%s] failed to allocate CacheTask"), contentName.c_str()); if (pTask->bwMax <=0) { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 500, "cacheContent() contentName[%s] server run out of propagation bandwidth"), contentName.c_str()); } // step 2 validate if the content has or is being cached locally, otherwise create a new content // take the portal the chop the content name into token and metadata, such as PID, PAID and so on portalContentNameToken(*this, contentName, pTask->nameFields); std::string replicaName; std::string topFolderName, leafFolderName; do { std::string folderName; ::TianShanIce::Storage::FolderPrx folder; try { folderName = _content2FolderName(contentName, topFolderName, leafFolderName); // ::TianShanIce::Storage::VolumePrx vol = _contentStore.proxy(true)->openVolume(DEFAULT_VOLUME_STRING); // folder = vol->openSubFolder(top, true, 0); // folder = folder->openSubFolder(leaf, true, 0); folder = _contentStore.openFolderEx(topFolderName + LOGIC_FNSEPS + leafFolderName, true, 0, ::Ice::Current()); } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] opening folder[%s] caught %s: %s"), contentName.c_str(), folderName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] opening folder[%s] caught %s"), contentName.c_str(), folderName.c_str(), ex.ice_name().c_str()); } catch( ...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] opening folder[%s] caught exception"), contentName.c_str(), folderName.c_str()); } if (!folder) { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 500, "cacheContent() content[%s] failed to access folder[%s]"), contentName.c_str(), folderName.c_str()); } replicaName = folderName + contentName; ::TianShanIce::Storage::ContentState state = TianShanIce::Storage::csNotProvisioned; try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] checking if localreplica[%s] exists"), contentName.c_str(), replicaName.c_str()); pTask->localContent = ::TianShanIce::Storage::UnivContentPrx::uncheckedCast(folder->openContent(contentName, "", false)); if (pTask->localContent) state = pTask->localContent->getState(); } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] checking if localreplica[%s] exists caught %s: %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch (const Ice::ObjectNotExistException&) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] localreplica[%s] doesn't exist"), contentName.c_str(), replicaName.c_str()); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] checking if localreplica[%s] exists caught %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] checking if localreplica[%s] exists caught exception"), contentName.c_str(), replicaName.c_str()); } if (pTask->localContent) // replica already exists { if (TianShanIce::Storage::csNotProvisioned == state) break; // good to call provision() again, otherwise give up with exception pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::InvalidStateOfArt> (_log, EXPFMT(CacheStore, 500, "cacheContent() content[%s] localReplica[%s] already exist with state[%s(%d)]"), contentName.c_str(), replicaName.c_str(), ContentStateBase::stateStr(state), state); } // no local replica if reaches here, create one try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] creating replica under hash folder[%s]"), contentName.c_str(), folderName.c_str()); pTask->localContent = ::TianShanIce::Storage::UnivContentPrx::uncheckedCast(folder->openContent(contentName, "", true)); if (pTask->localContent) _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] a replica has been created under hash folder[%s]"), contentName.c_str(), folderName.c_str()); pTask->localContent->setUserMetaData2(pTask->nameFields); // adding the name fields as user metadata of the content } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] creating localreplica[%s] caught %s: %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] creating localreplica[%s] caught %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheFolder, cacheContent, "content[%s] creating localreplica[%s] caught exception"), contentName.c_str(), replicaName.c_str()); } } while (0); // double check if a replica has been opened to call provision() if (!pTask->localContent) { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 500, "cacheContent() content[%s] failed to open localReplica[%s] to cache"), contentName.c_str(), replicaName.c_str()); } // step 3. build up the resource for exportAsStream from the source CacheStore int64 stampLast = stampNow; stampNow = ZQ::common::now(); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] read localReplica[%s], took %lldmsec, preparing resources"), contentName.c_str(), replicaName.c_str(), stampNow - stampLast); ::TianShanIce::SRM::Resource resDownstreamBandwidth, resUpstreamBandwidth, resEthernetInterface; resDownstreamBandwidth.status = TianShanIce::SRM::rsRequested; resUpstreamBandwidth.status = TianShanIce::SRM::rsRequested; // step 3.1 set the propagation speed { ::TianShanIce::Variant v; v.type = ::TianShanIce::vtLongs; if (pTask->bwMin < pTask->bwMax) { v.bRange = true; v.lints.push_back(pTask->bwMin); v.lints.push_back(pTask->bwMax); } else { v.bRange = false; v.lints.push_back(pTask->bwMin); } MAPSET(::TianShanIce::ValueMap, resDownstreamBandwidth.resourceData, "bandwidth", v); MAPSET(::TianShanIce::ValueMap, resUpstreamBandwidth.resourceData, "bandwidth", v); } // step 3.2 determin the sessionInterface of the external storage // for the resource of rtTsUpstreamBandwidth std::string extSessionInterface; do { if (sourceStore) break; // no necessary to have rtTsUpstreamBandwidth if propagate from another CacheStore _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] looking up the external session interface"), contentName.c_str()); extSessionInterface = findExternalSessionInterfaceByContent(contentName, pTask->nameFields); if (extSessionInterface.empty()) _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, cacheContent, "content[%s] failed to find external session interface"), contentName.c_str()); else { ::TianShanIce::Variant v; v.type = ::TianShanIce::vtStrings; v.bRange = false; v.strs.push_back(extSessionInterface); MAPSET(::TianShanIce::ValueMap, resUpstreamBandwidth.resourceData, "sessionInterface", v); } } while(0); // end of rtTsUpstreamBandwidth // step 3.3 By default assume this caching is from the external domain, // set the upstream interface as the destIP of resEthernetInterface for SS::exportContentAsStream() { ::TianShanIce::Variant v; v.type = ::TianShanIce::vtStrings; v.bRange = false; v.strs.push_back(_upStreamBindIP); MAPSET(::TianShanIce::ValueMap, resEthernetInterface.resourceData, "destIP", v); } // step 4. try to create the source stream exported from other CacheStore std::string srcStreamStr; // case 4.1 if the input parameter specified a source CacheStore if (sourceStore) { std::string tmpstr = _adapter->getCommunicator()->proxyToString(sourceStore); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] asking specified source CacheStore[%s] to export content"), contentName.c_str(), tmpstr.c_str()); try { std::string srcStoreNetId = sourceStore->theContentStore()->getNetId(); bool bSourceStoreInNeighborhood = false; { ::ZQ::common::MutexGuard gd(_lockerNeighbors); bSourceStoreInNeighborhood = (_neighbors.end() != _neighbors.find(srcStoreNetId)); } if (bSourceStoreInNeighborhood) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] the source CacheStore[%s][%s] is in neighborhood, taking the downStreamIp[%s] to duplicate content"), contentName.c_str(), srcStoreNetId.c_str(), tmpstr.c_str(), _downStreamBindIP.c_str()); ::TianShanIce::Variant& v = resEthernetInterface.resourceData["destIP"]; v.strs.clear(); v.strs.push_back(_downStreamBindIP); } } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, cacheContent, "content[%s] communicate source CacheStore[%s] caught %s"), contentName.c_str(), tmpstr.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, cacheContent, "content[%s] communicate source CacheStore[%s] caught exception"), contentName.c_str(), tmpstr.c_str()); } ::TianShanIce::SRM::ResourceMap exportResources; MAPSET(::TianShanIce::SRM::ResourceMap, exportResources, TianShanIce::SRM::rtTsDownstreamBandwidth, resDownstreamBandwidth); MAPSET(::TianShanIce::SRM::ResourceMap, exportResources, TianShanIce::SRM::rtEthernetInterface, resEthernetInterface); try { stampNow = ZQ::common::now(); pTask->srcStream = sourceStore->exportContentAsStream(contentName, "", 20000, 1, exportResources, params); srcStreamStr = _adapter->getCommunicator()->proxyToString(pTask->srcStream); stampLast = stampNow; stampNow = ZQ::common::now(); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] source CacheStore[%s] exported content as stream[%s], took %lldmsec"), contentName.c_str(), tmpstr.c_str(), srcStreamStr.c_str(), stampNow - stampLast); } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from CacheStore[%s] caught %s: %s"), contentName.c_str(), tmpstr.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from CacheStore[%s] caught %s"), contentName.c_str(), tmpstr.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from CacheStore[%s] caught exception"), contentName.c_str(), tmpstr.c_str()); } if (!pTask->srcStream) // when the sourceStore is specified, it must be a propagation between the CacheStore instances { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheStore, 400, "cacheContent() content[%s] failed to export from specified CacheStore[%s]"), contentName.c_str(), tmpstr.c_str()); } } else if (sfEnableNeighborhoodPropagation & _flags) { // case 4.2 if the configuration prioritize propagation among neighborhood ::TianShanIce::Variant& v = resEthernetInterface.resourceData["destIP"]; v.strs.clear(); v.strs.push_back(_downStreamBindIP); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] trying to propagate among neighborhood, adjusted to take downStreamIp[%s] to duplicate content"), contentName.c_str(), _downStreamBindIP.c_str()); ::TianShanIce::SRM::ResourceMap exportResources; MAPSET(::TianShanIce::SRM::ResourceMap, exportResources, TianShanIce::SRM::rtTsDownstreamBandwidth, resDownstreamBandwidth); MAPSET(::TianShanIce::SRM::ResourceMap, exportResources, TianShanIce::SRM::rtEthernetInterface, resEthernetInterface); bool importFromExtBySelf = false; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] sourceStore not specified, determining one from the neighborhood"), contentName.c_str()); stampNow = ZQ::common::now(); TianShanIce::Storage::CacheCandidates candidates = getCandidatesOfContent(contentName, true, c); for (size_t i=0; !importFromExtBySelf && i < candidates.size(); i++) { if (candidates[i].isSelf) { importFromExtBySelf = true; break; } if (!candidates[i].csd.theStore && candidates[i].csd.loadStream >= CACHE_LOAD_MAX) continue; std::string tmpstr = _adapter->getCommunicator()->proxyToString(candidates[i].csd.theStore); try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] asking candidate CacheStore[%s] w/ load[%d] to export the content"), contentName.c_str(), tmpstr.c_str(), candidates[i].csd.loadStream); pTask->srcStream = candidates[i].csd.theStore->exportContentAsStream(contentName, "", 20000, 1, exportResources, params); stampNow = ZQ::common::now(); if (pTask->srcStream) { sourceStore = candidates[i].csd.theStore; srcStreamStr = _adapter->getCommunicator()->proxyToString(pTask->srcStream); stampLast = stampNow; stampNow = ZQ::common::now(); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] candidate CacheStore[%s] w/ load[%d] exported as stream[%s], took %lldmsec after [%d] tries"), contentName.c_str(), tmpstr.c_str(), candidates[i].csd.loadStream, srcStreamStr.c_str(), stampNow - stampLast, i); break; } } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from candidate CacheStore[%s] caught %s: %s"), contentName.c_str(), tmpstr.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from candidate CacheStore[%s] caught %s"), contentName.c_str(), tmpstr.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] export from candidate CacheStore[%s] caught exception"), contentName.c_str(), tmpstr.c_str()); } } } // step 5 prepare input parameters for Content::provision() stampLast = stampNow; stampNow = ZQ::common::now(); if (pTask->srcStream) { // step 1. read the parameters of the stream _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] reading parameters of src stream[%s]"), contentName.c_str(), srcStreamStr.c_str()); ::TianShanIce::SRM::ResourceMap resOfStrm = pTask->srcStream->getResources(); ::TianShanIce::SRM::ResourceMap::iterator itRes = resOfStrm.find(TianShanIce::SRM::rtTsDownstreamBandwidth); if (resOfStrm.end() != itRes) { ::TianShanIce::ValueMap& resData = itRes->second.resourceData; ::TianShanIce::ValueMap::iterator itV = resData.find("sessionURL"); if (resData.end() != itV && itV->second.strs.size() >0) pTask->urlSrcStream = itV->second.strs[0]; itV = resData.find("bandwidth"); if (resData.end() != itV && itV->second.lints.size() >0) pTask->bwCommitted = (Ice::Int) itV->second.lints[0]; } // no necessary to check if the src stream is PWE because we didn't give the resource of UpstreamBandwidth. // the source CacheStore should reject exportContentAsStream() if it has not had the content InService // convert the urlSrcStream to c2http:// if (pTask->urlSrcStream.empty()) { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 400, "cacheContent() content[%s] failed to read URL from source stream[%s]"), contentName.c_str(), srcStreamStr.c_str()); } std::string tmpstr = pTask->urlSrcStream; ZQ::common::URLStr url(tmpstr.c_str()); std::string proto = url.getProtocol(); transform(proto.begin(), proto.end(), proto.begin(), tolower); // replace the http:// with c2http if (0 == proto.compare("http")) url.setProtocol("c2http"); // append with a flag saying the source stream can cover multiple member files url.setVar("fileset", "true"); pTask->urlSrcStream = url.generate(); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] src stream[%s] converted the url[%s] to [%s]"), contentName.c_str(), srcStreamStr.c_str(), tmpstr.c_str(), pTask->urlSrcStream.c_str()); } else { // step 1 call portal to SETUP a C2 session from the external storage _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] locating via external interface[%s]"), contentName.c_str(), extSessionInterface.c_str()); int nRetCode = portalLocateContent(*this, extSessionInterface, *pTask); if (nRetCode > 0) { pTask->destroy(c); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, nRetCode, "cacheContent() content[%s] failed to locate at external source storage[%s]"), contentName.c_str(), extSessionInterface.c_str()); } std::string tmpstr = pTask->urlSrcStream; ZQ::common::URLStr url(tmpstr.c_str()); // replace the http:// with c2http:// or c2pull:// std::string proto = url.getProtocol(); transform(proto.begin(), proto.end(), proto.begin(), tolower); if (0 == proto.compare("http") || 0 == proto.compare("c2http")) url.setProtocol(pTask->isSrcPWE ? "c2pull" : "c2http"); pTask->urlSrcStream = url.generate(); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] converted the source url[%s] to [%s] per PWE[%c] range[%lld~%lld]"), contentName.c_str(), tmpstr.c_str(), pTask->urlSrcStream.c_str(), pTask->isSrcPWE?'T':'F', pTask->startOffset, pTask->endOffset); } // validate the paramters gathered in CacheTask if (pTask->bwMax> 0 && pTask->bwCommitted > pTask->bwMax) { pTask->destroy(c); // cancel the CacheTask, old: withdrawCacheTask(pTask); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 400, "cacheContent() content[%s] CacheTask is withdrawn per bitrate[%d] of src stream beyonded max[%d], please adjust defaultProvSessionBitrateKbps and/or minBitratePercent"), contentName.c_str(), pTask->bwCommitted, pTask->bwMax); } // read the fileSize in MB long fileSizeMB =0; if (pTask->startOffset >=0 && pTask->endOffset > pTask->startOffset) fileSizeMB = (long) ((pTask->endOffset - pTask->startOffset) >> 20); if (pTask->isSrcPWE && pTask->bwMax > pTask->bwCommitted) { // play magic here for enh#16995 Serve the cached copy that is catching up the PWE copy on source storage int64 bpsCatchUp = 0; if (_catchUpRT > 5000) // 5 sec in minimal bpsCatchUp = (pTask->endOffset -pTask->startOffset) *8 / _catchUpRT *1000; long bpsAhead = pTask->bwCommitted * _catchUpRTminPercent /100; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] replic[%s] source PWE available range[%lld~%lld] mpeg[%d]bps, bpsCatchUp[%d]bps per catchUpRT[%d]msec, bpsAhead[%d]bps per %d%%"), contentName.c_str(), replicaName.c_str(), pTask->startOffset, pTask->endOffset, pTask->bwCommitted, bpsCatchUp, _catchUpRT, bpsAhead, _catchUpRTminPercent); if (bpsCatchUp < bpsAhead) bpsCatchUp = bpsAhead; if (bpsCatchUp >0) { if (bpsCatchUp > pTask->bwMax - pTask->bwCommitted) bpsCatchUp = pTask->bwMax - pTask->bwCommitted; // determin the streamable playtime char streamablePlaytime[16]; snprintf(streamablePlaytime, sizeof(streamablePlaytime)-2, "%lld", (int64)((pTask->endOffset -pTask->startOffset) *8 / bpsCatchUp *1000)); ::TianShanIce::Properties metaData; MAPSET(::TianShanIce::Properties, metaData, METADATA_EstimatedStreamable, streamablePlaytime); pTask->localContent->setUserMetaData2(metaData); // adjust the bwCommitted _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] replic[%s] source PWE available[%d]MB, adding overahead[%d]bps to transferRate[%d]bps per minCatchup[%d]%% catchUpTime[%d]msec, estimated streamable [%s]ms"), contentName.c_str(), replicaName.c_str(), fileSizeMB, bpsCatchUp, pTask->bwCommitted, _catchUpRTminPercent, _catchUpRT, streamablePlaytime); pTask->bwCommitted += bpsCatchUp; } } if (fileSizeMB <=0 && pTask->bwMin >0) // guess the file has 1/2hr if no fileSizeMB is specified fileSizeMB = bpsToFileSizeMB(pTask->bwMin, 60*30); // check if there is free enough space for this caching _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] replic[%s] ensuring for filesize[%d]MB @[%d~%d]bps"), contentName.c_str(), replicaName.c_str(), fileSizeMB, pTask->bwMin, pTask->bwCommitted); _ensureSpace(fileSizeMB, topFolderName); // step 6 prepare input parameters for Content::provision() try { stampNow = ZQ::common::now(); char buf[64]; ZQ::common::TimeUtil::TimeToUTC(stampNow+500, buf, sizeof(buf)-2); pTask->scheduledStart = buf; ZQ::common::TimeUtil::TimeToUTC(stampNow+2*3600*1000, buf, sizeof(buf)-2); pTask->scheduledEnd = buf; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, cacheContent, "content[%s] provisioning replica[%s] via src[%s] srcContentType[%s] @[%d]bps, %s~%s"), contentName.c_str(), replicaName.c_str(), pTask->urlSrcStream.c_str(), pTask->srcContentType.c_str(), pTask->bwCommitted, pTask->scheduledStart.c_str(), pTask->scheduledEnd.c_str()); pTask->localContent->provision(pTask->urlSrcStream, pTask->srcContentType, false, pTask->scheduledStart, pTask->scheduledEnd, pTask->bwCommitted); ::TianShanIce::Storage::CacheTaskPrx task = commitCacheTask(pTask); // stampLast = stampNow; stampNow = ZQ::common::now(); // pTask->stampCommitted = stampNow; _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, cacheContent, "content[%s] provision replica[%s] via src[%s]/type[%s] @[%d]bps, took %lldmsec"), contentName.c_str(), replicaName.c_str(), pTask->urlSrcStream.c_str(), pTask->srcContentType.c_str(), pTask->bwCommitted, stampNow-stampLast); if (task) return; // all set } catch(const ::TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] replica[%s]::provision() caught %s: %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] replica[%s]::provision() caught %s"), contentName.c_str(), replicaName.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, cacheContent, "content[%s] replica[%s]::provision() caught exception"), contentName.c_str(), replicaName.c_str()); } // provision() failed if reach here pTask->destroy(c); // cancel the CacheTask, old: withdrawCacheTask(pTask); ZQTianShan::_IceThrow<TianShanIce::ServerError> (_log, EXPFMT(CacheStore, 400, "cacheContent() content[%s] replica[%s]::provision() failed"), contentName.c_str(), replicaName.c_str()); } ::Ice::Long CacheStoreImpl::calculateCacheDistance(const ::std::string& contentName, const ::std::string& storeNetId, const ::Ice::Current& c) { HashKey contentKey, storeKey; if (!_calcHashKey(contentKey, contentName.c_str(), contentName.length())) return -1; if (!_calcHashKey(storeKey, storeNetId.c_str(), storeNetId.length())) return -1; return _calcRawDistance(contentKey, storeKey); } ::std::string CacheStoreImpl::_content2FolderName(const ::std::string& contentName, std::string& topFolderName, std::string& leafFolderName) { topFolderName = leafFolderName = ""; HashKey contentKey; if (!_calcHashKey(contentKey, contentName.c_str(), contentName.length())) return ""; return _contentHashKeyToFolder(contentKey, topFolderName, leafFolderName); } ::std::string CacheStoreImpl::getFolderNameOfContent(const ::std::string& contentName, const ::Ice::Current& c) { std::string top, leaf; return _content2FolderName(contentName, top, leaf); } ::std::string CacheStoreImpl::getFileNameOfLocalContent(const ::std::string& contentName, const ::std::string& subfile, const ::Ice::Current& c) { std::string hashedPathName = _rootVolName + getFolderNameOfContent(contentName, c); hashedPathName += contentName; std::string filepathname; try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, getFileNameOfLocalContent, "content[%s] reading LocalContent[%s]"), contentName.c_str(), hashedPathName.c_str()); ::TianShanIce::Storage::UnivContentPrx content = ::TianShanIce::Storage::UnivContentPrx::checkedCast(_contentStore.openContentByFullname(hashedPathName, c)); if (!content) ZQTianShan::_IceThrow<TianShanIce::EntityNotFound> (_log, EXPFMT(CacheStore, 404, "getFileNameOfLocalContent() content[%s] not found"), hashedPathName.c_str()); filepathname = content->getMainFilePathname(); if (!subfile.empty() && std::string::npos == subfile.find('*')) filepathname += portalSubfileToFileExtname(*this, subfile); } catch(const TianShanIce::BaseException& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getFileNameOfLocalContent, "content[%s] failed to access LocalContent[%s], caught %s: %s"), contentName.c_str(), hashedPathName.c_str(), ex.ice_name().c_str(), ex.message.c_str()); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getFileNameOfLocalContent, "content[%s] failed to access LocalContent[%s], caught %s"), contentName.c_str(), hashedPathName.c_str(), ex.ice_name().c_str()); } catch (...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, getFileNameOfLocalContent, "content[%s] failed to access LocalContent[%s], caught exception"), contentName.c_str(), hashedPathName.c_str()); } return filepathname; } CacheTaskImpl::Ptr CacheStoreImpl::newCacheTask(const std::string& contentName) { ZQ::common::MutexGuard g(_taskLocker); CacheTaskMap::iterator it = _taskMap.find(contentName); if (_taskMap.end() != _taskMap.find(contentName)) { char buf[60]; ZQ::common::TimeUtil::TimeToUTC(it->second->stampCreated, buf, sizeof(buf)); _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, newCacheTask, "content[%s] a previous CacheTask already created at %s"), contentName.c_str(), buf); return NULL; } CacheTaskImpl::Ptr pTask = new CacheTaskImpl(*this); pTask->ident.name = contentName; pTask->ident.category = CATEGORY_CacheTask; pTask->srcContentType = ::TianShanIce::Storage::ctMPEG2TS; pTask->isSrcPWE = false; pTask->bwMin = _defaultProvSessionBitrateKbps *1000; pTask->bwMax = 0; pTask->bwCommitted = 0; pTask->stampCreated = ZQ::common::now(); pTask->stampCommitted = 0; pTask->stampStopped = 0; pTask->startOffset = pTask->endOffset =0; int64 freeProvisionbps = _totalProvisionKbps - _usedProvisionKbps; freeProvisionbps *= 1000; // from Kbps to bps if (pTask->bwMin > freeProvisionbps) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, newCacheTask, "content[%s] runs out of propagation bandwidth"), contentName.c_str()); return NULL; } if (_minBitratePercent <=0) pTask->bwMax = pTask->bwMin; else { if (_minBitratePercent > 20) _minBitratePercent = 20; pTask->bwMax = (Ice::Int) (freeProvisionbps * _minBitratePercent /100); if (pTask->bwMax < pTask->bwMin) pTask->bwMax = pTask->bwMin; // adjust bwMax to be no greater than bwMin*10 if (pTask->bwMin >0 && pTask->bwMax > pTask->bwMin *10) pTask->bwMax = pTask->bwMin *10; } if (pTask->bwMax > freeProvisionbps) pTask->bwMax = (Ice::Int) freeProvisionbps; _usedProvisionKbps += RoundToKbps(pTask->bwMax); if (_totalProvisionKbps >0) _thisDescriptor.desc.loadCacheWrite =(long) (MAX_LOAD * _usedProvisionKbps /_totalProvisionKbps); MAPSET(CacheTaskMap, _taskMap, pTask->ident.name, pTask); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, newCacheTask, "content[%s] reserved cacheTask[%p] w/ bw[%d~%d]; usage now[%lld/%lld]Kbps"), contentName.c_str(), pTask.get(), pTask->bwMin, pTask->bwMax, _usedProvisionKbps, _totalProvisionKbps); return pTask; } ::TianShanIce::Storage::CacheTaskPrx CacheStoreImpl::commitCacheTask(CacheTaskImpl::Ptr& pTask) { if (_thirdPartyCache) return NULL; ::TianShanIce::Storage::CacheTaskPrx task; if (!pTask->localContent) ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (_log, EXPFMT(CacheTask, 401, "commit() content[%s] NULL localContent"), pTask->ident.name.c_str()); pTask->provisionSess = pTask->localContent->getProvisionSession(); if (!pTask->provisionSess) ZQTianShan::_IceThrow<TianShanIce::InvalidStateOfArt> (_log, EXPFMT(CacheTask, 402, "commit() content[%s] NULL ProvisionSession"), pTask->ident.name.c_str()); std::string provSessStr = _adapter->getCommunicator()->proxyToString(pTask->provisionSess); pTask->stampCommitted = ZQ::common::now(); int64 oldUsed =0; { ZQ::common::MutexGuard g(_taskLocker); oldUsed = _usedProvisionKbps; _usedProvisionKbps -= RoundToKbps(pTask->bwMax); _usedProvisionKbps += RoundToKbps(pTask->bwCommitted); if (_totalProvisionKbps >0) _thisDescriptor.desc.loadCacheWrite = (long) (MAX_LOAD * _usedProvisionKbps /_totalProvisionKbps); } try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, commit, "adding task[%s] to DB"), pTask->ident.name.c_str()); _eCacheTask->add(pTask, pTask->ident); task = IdentityToObj(CacheTask, pTask->ident); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, commit, "content[%s] task[%p] committed [%d]bps, provision session[%s] BWUsage[%lld=>U%lld/T%lld]Kbps"), pTask->ident.name.c_str(), pTask.get(), pTask->bwCommitted, provSessStr.c_str(), oldUsed, _usedProvisionKbps, _totalProvisionKbps); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheTask, commit, "adding task[%s] caught %s"), pTask->ident.name.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheTask, commit, "adding task[%s] caught exception"), pTask->ident.name.c_str()); } if (!task) { ZQ::common::MutexGuard g(_taskLocker); _taskMap.erase(pTask->ident.name); _usedProvisionKbps -= RoundToKbps(pTask->bwCommitted); if (_totalProvisionKbps >0) _thisDescriptor.desc.loadCacheWrite = (long) (MAX_LOAD * _usedProvisionKbps /_totalProvisionKbps); _log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheStore, commit, "content[%s] task[%p] committed failed, provision session[%s] BWUsage[%lld=>U%lld/T%lld]Kbps"), pTask->ident.name.c_str(), pTask.get(), provSessStr.c_str(), oldUsed, _usedProvisionKbps, _totalProvisionKbps); return NULL; } _watchDog.watch(pTask->ident, PROVISION_PING_INTERVAL); return task; } void CacheStoreImpl::withdrawCacheTask(CacheTaskImpl::Ptr& pTask) { if (_thirdPartyCache) return; if (!pTask) return; /* if (pTask->stampCommitted >0) { try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, withdrawCacheTask, "content[%s] removing task from DB"), pTask->ident.name.c_str()); _eCacheTask->remove(pTask->ident); } catch(const ::Ice::Exception& ex) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, withdrawCacheTask, "content[%s] removing task from DB caught[%s]"), pTask->ident.name.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, withdrawCacheTask, "content[%s] removing task from DB caught exception"), pTask->ident.name.c_str()); } } ZQ::common::MutexGuard g(_taskLocker); _taskMap.erase(pTask->ident.name); if (pTask->stampCommitted >0) _freeProvisionBW += pTask->bwCommitted; else _freeProvisionBW += pTask->bwMax; _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, withdrawCacheTask, "content[%s] removing task withdrawn"), pTask->ident.name.c_str()); */ } /* void CacheStoreImpl::_countAccess(AccessCounters& caCounters, const std::string& contentName, const std::string& subfile) { if (0 == subfile.compare(SUBFILE_EXTNAME_INDEX)) return; ZQ::common::MutexGuard g(caCounters.lkMap); int64 stampNow = ZQ::common::now(); ContentAccessMap::iterator it = caCounters.caMap.find(contentName); if (caCounters.caMap.end() == it) { _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, FUNCNAME "content[%s] not in %s, adding it in CacheCounter[%s]"), contentName.c_str(), caCounters.name.c_str()); ActiveContent ac; ac.contentName = contentName; ac.folderName = getFolderNameOfContent(contentName, Ice::Current()); ac.countSince = ac.knownSince = stampNow; ac.accessCount = ac.fileSizeMB = 0; ac.localState = TianShanIce::Storage::csNotProvisioned; ac.countLatest = stampNow; MAPSET(ContentAccessMap, caCounters.caMap, contentName, ac); it = caCounters.caMap.find(contentName); } if (caCounters.caMap.end() == it) return; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, FUNCNAME "content[%s] subfile[%s] increasing %s[%d]"), contentName.c_str(), subfile.c_str(), caCounters.name.c_str()); it->second.accessCount++; it->second.countLatest = stampNow; } */ void CacheStoreImpl::OnLocalContentRequested(const std::string& contentName, const std::string& subfile) { // _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnLocalContentRequested, "content[%s] subfile[%s]"), contentName.c_str(), subfile.c_str()); if (0 == subfile.compare(SUBFILE_EXTNAME_index)) return; TianShanIce::Storage::ContentAccess ac = _acHotLocals->count(contentName, subfile, 1); char buf[128]; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnLocalContentRequested, "subfile[%s] %s"), subfile.c_str(), AccessRegistrarImpl::ContentAccessStr(ac, buf, sizeof(buf)-1)); } void CacheStoreImpl::OnMissedContentRequested(const std::string& contentName, const std::string& subfile) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnMissedContentRequested, "content[%s] subfile[%s]"), contentName.c_str(), subfile.c_str()); if (0 == subfile.compare(SUBFILE_EXTNAME_index)) return; TianShanIce::Storage::ContentAccess ac = _acMissed->count(contentName, subfile, 1); char buf[128]; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnMissedContentRequested, "subfile[%s] %s"), subfile.c_str(), AccessRegistrarImpl::ContentAccessStr(ac, buf, sizeof(buf)-1)); /* ZQ::common::MutexGuard g(_acMissed.lkMap); int64 stampNow = ZQ::common::now(); ContentAccessMap::iterator it = _acMissed.acMap.find(contentName); if (_acMissed.acMap.end() == it) { _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, FUNCNAME "content[%s] not in _acMissed.acMap, adding it in"), contentName.c_str()); ActiveContent ac; ac.contentName = contentName; ac.folderName = getFolderNameOfContent(contentName, Ice::Current()); ac.countSince = ac.knownSince = ZQ::common::now(); ac.accessCount = 1; ac.fileSizeMB = 0; ac.localState = TianShanIce::Storage::csNotProvisioned; ac.countLatest = stampNow; MAPSET(ContentAccessMap, _acMissed.acMap, contentName, ac); it = _acMissed.acMap.find(contentName); } if (_acMissed.acMap.end() == it) return; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, FUNCNAME "content[%s] subfile[%s] increasing counter[%d]"), contentName.c_str(), subfile.c_str(), it->second.accessCount); it->second.accessCount++; it->second.countLatest = ZQ::common::now(); */ } void CacheStoreImpl::OnContentCreated(const std::string& contentReplicaName) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnContentCreated, "contentReplica[%s]"), contentReplicaName.c_str()); #pragma message ( __TODO__ "impl here") } void CacheStoreImpl::OnContentDestroyed(const std::string& contentReplicaName) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnContentDestroyed, "removing contentReplica[%s] from unpopular list"), contentReplicaName.c_str()); size_t pos = contentReplicaName.find(CACHE_FOLDER_PREFIX "T"); if (std::string::npos == pos) return; Ice::Identity identTF; identTF.category = CATEGORY_TopFolder; identTF.name = contentReplicaName.substr(pos, strlen(CACHE_FOLDER_PREFIX "T00")); try { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnContentDestroyed, "removing contentReplica[%s] from TF[%s]'s list"), contentReplicaName.c_str(), identTF.name.c_str()); ::TianShanIce::Storage::TopFolderPrx topFolder = IdentityToObj(TopFolder, identTF); topFolder->eraseFromUnpopular(contentReplicaName); } catch(const Ice::Exception& ex) { _log(ZQ::common::Log::L_WARNING,FLOGFMT(CacheStore, OnContentDestroyed, "removing contentReplica[%s] from TF[%s]'s list caught exception[%s]"), contentReplicaName.c_str(), identTF.name.c_str(), ex.ice_name().c_str()); } catch(...) { _log(ZQ::common::Log::L_WARNING,FLOGFMT(CacheStore, OnContentDestroyed, "removing contentReplica[%s] from TF[%s]'s list caught exception"), contentReplicaName.c_str(), identTF.name.c_str()); } } void CacheStoreImpl::OnContentStateChanged(const std::string& contentReplicaName, const ::TianShanIce::Storage::ContentState previousState, const ::TianShanIce::Storage::ContentState newState) { size_t posCN = contentReplicaName.find_last_not_of("/"); std::string contentName = contentReplicaName.substr(posCN+1); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnContentStateChanged, "content[%s] localReplica[%s] state(%d=>%d)"), contentName.c_str(), contentReplicaName.c_str(), previousState, newState); ::TianShanIce::Storage::AccessCounter counter; bool bInMissed = _acMissed->get(contentName, counter); if (bInMissed) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnContentStateChanged, "content[%s] pre-existed in _acMissed state(%d)"), contentName.c_str(), newState); counter.localState = newState; } /* ZQ::common::MutexGuard g(_acMissed.lkMap); ContentAccessMap::iterator it = _acMissed.caMap.find(contentName); if (_acMissed.caMap.end() != it) { _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, FUNCNAME "content[%s] updating _acMissed.acMap state(%d)"), contentName.c_str(), contentReplicaName.c_str(), newState); it ->second.localState = newState; } */ int64 stampNow = ZQ::common::now(); switch (newState) { case ::TianShanIce::Storage::csNotProvisioned: case ::TianShanIce::Storage::csProvisioning: case ::TianShanIce::Storage::csProvisioningStreamable: if (!bInMissed) { _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, OnContentStateChanged, "content[%s] localReplica[%s] state(%d) not in _acMissed, adding it in"), contentName.c_str(), contentReplicaName.c_str(), newState); ::TianShanIce::Storage::AccessCounter ac; ac.base.contentName = contentName; ac.base.accessCount = 1; ac.base.stampSince = stampNow; ac.base.stampLatest = stampNow; std::string top, leaf; ac.folderName = CacheStoreImpl::_content2FolderName(contentName, top, leaf); ac.knownSince = stampNow; ac.fileSizeMB = 0; ac.localState = newState; _acMissed->set(counter); } break; case ::TianShanIce::Storage::csInService: if (bInMissed) { _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, OnContentStateChanged, "content[%s] localReplica[%s] state(%d) is in _acMissed, removing it"), contentName.c_str(), contentReplicaName.c_str(), newState); _acMissed->erase(contentName); } break; case ::TianShanIce::Storage::csOutService: break; case ::TianShanIce::Storage::csCleaning: break; default: break; } } #define DEFAULT_STORE_ONTIMER_INTERVAL (1000*60) // start with 1min void CacheStoreImpl::OnTimer(const ::Ice::Current& c) { // _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "")); int64 stampNow = ZQ::common::now(); // put a dummy long watching and overwrite later, just to make sure that the store is always under watching _watchDog.watch(_localId, DEFAULT_STORE_ONTIMER_INTERVAL *8); uint32 nextSleep = DEFAULT_STORE_ONTIMER_INTERVAL; try { int32 flushedTime = (int32) (stampNow - _stampLocalCounterFlushed); if (flushedTime >= (int32) max(DEFAULT_STORE_ONTIMER_INTERVAL, _timeWinOfPopular/4)) { _stampLocalCounterFlushed = stampNow; ::TianShanIce::Storage::ContentCounterList listToFlush, listEvicted; // step 1. for the missed list: // a) evict those long-time no order contents from watching list // b) ignore the list to flush _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "refreshing the counters of missed contents")); _sizeMissed = _acMissed->compress(_timeWinOfPopular, _timeWinOfPopular, _reqsMissedInWin, listToFlush, listEvicted, c); _log((listEvicted.size() >0 ? ZQ::common::Log::L_INFO : ZQ::common::Log::L_DEBUG), FLOGFMT(CacheStore, OnTimer, "refreshed the counters of missed contents, %d evicted, %d left"), listEvicted.size(), _sizeMissed); listToFlush.clear(); listEvicted.clear(); // step 2. for the hot local list: // a) evict those long-time no order contents from watching list // b) compress the counts piror to this monitor time window and flush counter into content DB _sizeHotLocals = _acHotLocals->compress(_timeWinOfPopular, flushedTime, _reqsHotLocalsInWin, listToFlush, listEvicted, c); if ((listEvicted.size()+listToFlush.size()) >0) _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, OnTimer, "flushed the cached counter of local hot contents, %d to flush, %d evicted, %d left"), listToFlush.size(), listEvicted.size(), _sizeHotLocals); for (::TianShanIce::Storage::ContentCounterList::iterator it = listToFlush.begin(); it < listToFlush.end(); it++) { FlushAccessCounterCmd* pCmd = FlushAccessCounterCmd::newCmd(*this, *it); if (pCmd) pCmd->exec(); } } if (_countOfPopular <1) // _countOfPopular must be greater than 0 _countOfPopular =1; // #pragma message ( __TODO__ "step 3. check if the top populars in the missed list are necessary to cache into local") do { if (stampNow - _stampLastScanMissed < min(_hotTimeWin, _timeWinOfPopular/2)) break; // no necessary to scan the missed _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "scanning for popular contents to cache, missed size[%d]"), _acMissed->size()); ::TianShanIce::Storage::ContentCounterList popularMissedList; try { stampNow = ZQ::common::now(); _acMissed->sort(_timeWinOfPopular, false, _countOfPopular, popularMissedList, c); _stampLastScanMissed = ZQ::common::now(); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, OnTimer, "%d missed contents under watching, sort took %lldmsec"), popularMissedList.size(), _stampLastScanMissed - stampNow); } catch(...) { _log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheStore, OnTimer, "sort missed contents caught exception")); } for (::TianShanIce::Storage::ContentCounterList::iterator it =popularMissedList.begin(); it < popularMissedList.end(); it++) { if (it->base.accessCount < _countOfPopular) continue; // can be "break" here in theory // create a command to cache this content to local std::string strSince, strLatest; char buf[128]; if (ZQ::common::TimeUtil::TimeToUTC(it->base.stampSince, buf, sizeof(buf)-2)) strSince = buf; if (ZQ::common::TimeUtil::TimeToUTC(it->base.stampLatest, buf, sizeof(buf)-2)) strLatest = buf; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "content[%s] counted %d during[%s~%s] met threshold %d, issuing command to cache it"), it->base.contentName.c_str(), it->base.accessCount, strSince.c_str(), strLatest.c_str(), _countOfPopular); try { ZQ::common::MutexGuard g(_taskLocker); if (_taskMap.end() != _taskMap.find(it->base.contentName)) continue; // the cache task has been previously created, skip (new ImportContentCmd(*this, it->base.contentName))->exec(); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "content[%s] counted %d during[%s~%s] met threshold %d, acquired to cache to local"), it->base.contentName.c_str(), it->base.accessCount, strSince.c_str(), strLatest.c_str(), _countOfPopular); } catch(...) {} } } while (0); } catch (...) {} int64 freeMB=0, totalMB=0; _readStoreSpace(freeMB, totalMB); // adjust the interval of OnTimer() if (totalMB >0 && freeMB < totalMB *2/10) nextSleep = min(nextSleep, 10*1000); _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnTimer, "checking space[F%lld/T%lld]MB"), freeMB, totalMB); _ensureSpace(0); _watchDog.watch(_localId, nextSleep); } void CacheStoreImpl::penalize(CacheStoreDsptr& store, int penaltyToCharge) { int64 stampNow = ZQ::common::now(); int old = store.penalty; store.penalty = old + penaltyToCharge; // - (stampNow - store.desc.stampAsOf) / _heatbeatInterval; if (store.penalty <0) store.penalty =0; else if (_penaltyMax >0 && store.penalty > (int)_penaltyMax) store.penalty = _penaltyMax; if (penaltyToCharge >0) store.stampLastPenalty = stampNow; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, penalize, "neighor[%s] pen[%d] to [%d]"), store.desc.netId.c_str(), old, store.penalty); } void CacheStoreImpl::OnForwardFailed(std::string storeNetId, int penaltyToCharge) { ::ZQ::common::MutexGuard gd(_lockerNeighbors); CacheStoreImpl::CacheStoreMap::iterator it = _neighbors.find(storeNetId); if (_neighbors.end() == it) return; int pen =1; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, OnForwardFailed, "charging neighor[%s] by penalty[%d]"), storeNetId.c_str(), pen); penalize(it->second, pen); } std::string CacheStoreImpl::findExternalSessionInterfaceByContent(const std::string& contentName, const TianShanIce::Properties& nameFields) { std::string providerId; TianShanIce::Properties::const_iterator itMD = nameFields.find(METADATA_ProviderId); if (nameFields.end() != itMD) providerId = itMD->second; return findExternalSessionInterfaceByProvider(providerId); } std::string CacheStoreImpl::findExternalSessionInterfaceByProvider(const std::string& providerId) { SourceStores::StoreInfo si; _extSourceStores.find(providerId, si); return si.sessionInterface; } ::TianShanIce::Storage::CacheStoreList CacheStoreImpl::listNeighors(::Ice::Int heatbeatInterval, const ::Ice::Current& c) { ::TianShanIce::Storage::CacheStoreList result; CacheStoreListInt list; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, listNeighors, "")); _listNeighorsEx(list, heatbeatInterval); for (CacheStoreListInt::iterator it = list.begin(); it < list.end(); it++) result.push_back(it->desc); _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, listNeighors, "%d neighbors found"), result.size()); return result; } int CacheStoreImpl::_listNeighorsEx(CacheStoreListInt& list, bool includeSelf, uint32 heatbeatInterval) { if (heatbeatInterval < _heatbeatInterval) heatbeatInterval = _heatbeatInterval; list.clear(); int64 stampExp = ZQ::common::now() - (long) (heatbeatInterval * 1.5); ::ZQ::common::MutexGuard gd(_lockerNeighbors); for (CacheStoreImpl::CacheStoreMap::iterator it = _neighbors.begin(); it != _neighbors.end(); it++) { if (it->second.desc.stampAsOf < stampExp) continue; list.push_back(it->second); } if (includeSelf) list.push_back(_thisDescriptor); return list.size(); } void CacheStoreImpl::queryReplicas_async(const ::TianShanIce::AMD_ReplicaQuery_queryReplicasPtr& amdCB, const ::std::string& category, const ::std::string& groupId, bool localOnly, const ::Ice::Current& c) { // redirect to ContentStore _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, queryReplicas, "redirecting to local ContentStore")); _contentStore.queryReplicas_async(amdCB, category, groupId, localOnly, c); } struct LessFWU { bool operator() (const CacheStoreImpl::FWU& A, const CacheStoreImpl::FWU& B) { return (A.minAccessCount < B.minAccessCount); } }; typedef std::multiset<CacheStoreImpl::FWU, LessFWU> SortedFWU; CacheStoreImpl::FWUSequence CacheStoreImpl::_sortFolderByFWU() { SortedFWU sortedFWU; FWUSequence fwuseq; { ZQ::common::MutexGuard g(_lkFWU); for (FWUMap::iterator it = _fwuMap.begin(); it != _fwuMap.end(); it++) sortedFWU.insert(it->second); } for (SortedFWU::iterator it = sortedFWU.begin(); it != sortedFWU.end(); it++) fwuseq.push_back(*it); return fwuseq; } void CacheStoreImpl::_updateFWU(const CacheStoreImpl::FWU& fwu) { ZQ::common::MutexGuard g(_lkFWU); if (fwu.unpopularSize >0) MAPSET(CacheStoreImpl::FWUMap, _fwuMap, fwu.topFolderName, fwu); else _fwuMap.erase(fwu.topFolderName); } void CacheStoreImpl::updateStreamLoad(uint32 usedBwLocalStreamKbps, uint32 maxBwLocalStreamKbps, uint32 usedBwPassThruKbps, uint32 maxBwPassThruKbps) { if (usedBwLocalStreamKbps <=0) usedBwLocalStreamKbps =0; if (usedBwPassThruKbps <=0) usedBwPassThruKbps =0; // step 1. determine loadStream for downstream interface uint32 usedDownBw = usedBwLocalStreamKbps + usedBwPassThruKbps; uint32 totalDownBw = MAX(maxBwLocalStreamKbps, maxBwPassThruKbps); // if (maxBwLocalStreamKbps >0 && maxBwPassThruKbps>0) // totalDownBw = maxBwLocalStreamKbps + maxBwPassThruKbps; ZQ::common::MutexGuard g(_lockerNeighbors); if (totalDownBw <= 0) _thisDescriptor.desc.loadStream =0; else if (usedDownBw >= totalDownBw) _thisDescriptor.desc.loadStream = MAX_LOAD; else _thisDescriptor.desc.loadStream = MAX_LOAD * usedDownBw / totalDownBw; // step 2. deterime the load of uplink interface uint32 usedImportKbps = usedBwPassThruKbps + _usedProvisionKbps; uint32 totalImportKbps = MAX(maxBwPassThruKbps, _totalProvisionKbps); if (totalImportKbps <=0) _thisDescriptor.desc.loadImport =0; else if (usedImportKbps >= totalImportKbps) _thisDescriptor.desc.loadImport = MAX_LOAD; else _thisDescriptor.desc.loadImport = MAX_LOAD * usedImportKbps / totalImportKbps; _usedLocalStreamKbps = usedBwLocalStreamKbps; _maxLocalStreamKbps = maxBwLocalStreamKbps; _usedPassThruKbps = usedBwPassThruKbps; _maxPassThruKbps = maxBwPassThruKbps; _log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheStore, updateStreamLoad, "local-stream[%d/%d] pass-thru[%d/%d]=> streamLoad[%d] importLoad[%d]"), usedBwLocalStreamKbps, maxBwLocalStreamKbps, usedBwPassThruKbps, maxBwPassThruKbps, _thisDescriptor.desc.loadStream, _thisDescriptor.desc.loadImport); } // ----------------------------- // class CacheTaskImpl // ----------------------------- /* ::TianShanIce::Storage::CacheTaskPrx CacheTaskImpl::commit() { if (!localContent) ZQTianShan::_IceThrow<TianShanIce::InvalidParameter> (MOLOG, EXPFMT(CacheTask, 401, "commit() content[%s] NULL localContent"), ident.name.c_str()); provisionSess = localContent->getProvisionSession(); if (!provisionSess) ZQTianShan::_IceThrow<TianShanIce::InvalidStateOfArt> (MOLOG, EXPFMT(CacheTask, 402, "commit() content[%s] NULL ProvisionSession"), ident.name.c_str()); std::string provSessStr = _store->_adapter->getCommunicator()->proxyToString(provisionSess); stampCommitted = ZQ::common::now(); try { _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, commit, "adding task[%s] to DB"), ident.name.c_str()); _eCacheTask->add(pTask, pTask->ident); ZQ::common::MutexGuard g(_taskLocker); _freeProvisionBW += pTask->bwMax; _freeProvisionBW -= pTask->bwCommitted; _log(ZQ::common::Log::L_INFO, FLOGFMT(CacheStore, commit, "task [%s] committed, provision session[%s]"), ident.name.c_str(), provSessStr.c_str()); return IdentityToObj(CacheTask, ident); } catch (...) {} } */ void CacheTaskImpl::OnRestore(const ::Ice::Current& c) { { RLock sync(*this); _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, OnRestore, "task[%s]"), ident.name.c_str()); ZQ::common::MutexGuard g(_store._taskLocker); if (_store._taskMap.end() == _store._taskMap.find(ident.name)) { int64 bwToUsed = (stampCommitted >0) ? bwCommitted : bwMax; _store._usedProvisionKbps += RoundToKbps(bwToUsed); if (_store._totalProvisionKbps >0) _store._thisDescriptor.desc.loadCacheWrite = (long) (MAX_LOAD * _store._usedProvisionKbps /_store._totalProvisionKbps); MAPSET(CacheStoreImpl::CacheTaskMap, _store._taskMap, ident.name, this); } } ::Ice::Current newc =c; MAPSET(::Ice::Context, newc.ctx, "signature", "OnRestore()"); OnTimer(newc); } void CacheTaskImpl::destroy(const ::Ice::Current& c) { if (!_store._eCacheTask) return; try { WLock sync(*this); _store._eCacheTask->remove(ident); _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, destroy, "content[%s] task removed from DB"), ident.name.c_str()); } catch(const Ice::ObjectNotExistException&) { // do nothing } catch(const Ice::NotRegisteredException&) { // do nothing } catch(const ::Ice::Exception& ex) { _store._log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheTask, destroy, "content[%s] removing task from DB caught[%s]"), ident.name.c_str(), ex.ice_name().c_str()); } catch(...) { _store._log(ZQ::common::Log::L_ERROR, FLOGFMT(CacheTask, destroy, "content[%s] removing task from DB caught exception"), ident.name.c_str()); } ZQ::common::MutexGuard g(_store._taskLocker); _store._taskMap.erase(ident.name); int64 bwToFree = (stampCommitted >0) ? bwCommitted : bwMax; _store._usedProvisionKbps -= RoundToKbps(bwToFree); if (_store._totalProvisionKbps >0) _store._thisDescriptor.desc.loadCacheWrite = (long) (MAX_LOAD * _store._usedProvisionKbps / _store._totalProvisionKbps); _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, destroy, "content[%s] freed task[%p] w/ [%lld]bps, now BW usage[U%lld/T%lld]Kbps"), ident.name.c_str(), this, bwToFree, _store._usedProvisionKbps, _store._totalProvisionKbps); } void CacheTaskImpl::OnTimer(const ::Ice::Current& c) { int64 stampNow = ZQ::common::now(); bool bDestroyNeeded = false; do { RLock sync(*this); // _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, OnTimer, "content[%s] task[%p]"), ident.name.c_str(), this); _store._watchDog.watch(ident, PROVISION_PING_INTERVAL); if (!provisionSess) { if (stampCreated < (stampNow - 2*60*1000)) { _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, OnTimer, "content[%s] task[%p] destroying per no provision session attached"), ident.name.c_str(), this); bDestroyNeeded = true; } break; } std::string strPS; try { strPS = _store._adapter->getCommunicator()->proxyToString(provisionSess); provisionSess->ice_ping(); _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, OnTimer, "task[%p] ProvisionSession[%s] still running"), this, strPS.c_str()); } catch(const ::Freeze::DatabaseException& ex) { _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, OnTimer, "task[%p] ping ProvisionSession[%s] caught %s"), this, strPS.c_str(), ex.ice_name().c_str()); } catch(const ::Ice::ObjectNotExistException&) { _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, OnTimer, "task[%p] ProvisionSession[%s] gone, cleaning task"), this, strPS.c_str()); bDestroyNeeded = true; } catch(const ::Ice::Exception& ex) { _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, OnTimer, "task[%p] ping ProvisionSession[%s] caught %s"), this, strPS.c_str(), ex.ice_name().c_str()); } catch(...) { _store._log(ZQ::common::Log::L_INFO, FLOGFMT(CacheTask, OnTimer, "task[%p] ping ProvisionSession[%s] caught exception"), this, strPS.c_str()); } } while(0); if (localContent) { ::Ice::Context::const_iterator itCtx = c.ctx.find("signature"); if (bDestroyNeeded || (c.ctx.end() != itCtx && 0 == itCtx->second.compare("OnRestore()"))) { try { _store._log(ZQ::common::Log::L_DEBUG, FLOGFMT(CacheTask, OnTimer, "task[%p] force content[%s] to populate attributes per cache completion or restored"), this, ident.name.c_str()); localContent->populateAttrsFromFilesystem(); } catch(...) { _store._log(ZQ::common::Log::L_WARNING, FLOGFMT(CacheTask, OnTimer, "task[%p] force content[%s] to populate attributes caught exception"), this, ident.name.c_str()); } } } if (bDestroyNeeded) return destroy(c); } }} // namespace
d952069a6edf9de097b6a9bbe5dc0c2df8638fa2
7a9ab3a236ecf4b2eddb6c4fe4c0c0c333a0fb26
/src/model/factory/include/data_list_factory.h
1781f00667f309693124437e76fa5ad18c055c44
[ "Apache-2.0" ]
permissive
AO-StreetArt/CLyman
d7f2f434551a724c62ea6b80318028992ba2d1ef
b4f3c6fce1c41fb47a6a9d89bb40c05466d0d092
refs/heads/v2
2021-01-24T06:47:20.703805
2019-04-27T01:51:24
2019-04-27T01:51:24
55,323,959
1
0
NOASSERTION
2019-04-17T05:22:39
2016-04-03T01:20:47
C++
UTF-8
C++
false
false
1,346
h
data_list_factory.h
/* Apache2 License Notice Copyright 2017 Alex Barry 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 "model/list/include/object_list_interface.h" #include "model/list/include/json_object_list.h" #include "model/list/include/property_list_interface.h" #include "model/list/include/json_property_list.h" #ifndef SRC_API_INCLUDE_DATA_LIST_FACTORY_H_ #define SRC_API_INCLUDE_DATA_LIST_FACTORY_H_ // The DataListFactory allows for creation of new instances of the // ObjectListInterface class DataListFactory { public: // Create an empty ObjectListInterface which converts to JSON ObjectListInterface* build_json_object_list() {return new JsonObjectList;} // Create an empty ObjectListInterface which converts to JSON PropertyListInterface* build_json_property_list() {return new JsonPropertyList;} }; #endif // SRC_API_INCLUDE_DATA_LIST_FACTORY_H_
6ec1085f57067adee7428eb02e53b50500607937
63ca73071cc8300708f5e1374b45646f8c9f206d
/arduino_app/Controller.h
6951057b3184860f60aa42f6e8e98ada0f0c8303
[]
no_license
bartlettc22/desertviper
427696b5dc437308cf5dcf93f19e1820eff37411
a89dc185b2f971046501451931da01770082572f
refs/heads/master
2021-01-21T04:55:10.722996
2015-07-09T02:50:58
2015-07-09T02:50:58
34,994,918
1
0
null
null
null
null
UTF-8
C++
false
false
6,993
h
Controller.h
#ifndef Controller_h #define Controller_h // Libraries #include <Arduino.h> #include "I2Cdev.h" #include "HMC5883L.h" #include "MPU6050.h" #include <math.h> #include "Kalman.h" #include "SFE_BMP180.h" // Motor Controller PINs // Motor 1 = Rear Wheels // Motor 2 = Front Wheels #define PIN_MOTOR_FRONT_INA 4 #define PIN_MOTOR_FRONT_INB 9 #define PIN_MOTOR_FRONT_ENDIAG A1 #define PIN_MOTOR_FRONT_PWM 6 #define PIN_MOTOR_FRONT_CS 3 #define PIN_MOTOR_REAR_INA 7 #define PIN_MOTOR_REAR_INB 8 #define PIN_MOTOR_REAR_ENDIAG A0 #define PIN_MOTOR_REAR_PWM 5 #define PIN_MOTOR_REAR_CS 2 // Hall Effect (Tick) Sensor PINS #define PIN_HALL 2 // PIN # #define INRPT_HALL 0 // INTERRUPT # (PIN2 = Interrupt 0, PIN 3 = Interrupt 1) // RF Receiver #define PIN_RF 3 // RF Receiver VT - Any button pressed #define INRPT_RF 1 #define PIN_RF_A 24 // RF Receiver D2 #define INRPT_RF_A 4 #define PIN_RF_B 25 // RF Receiver D0 #define INRPT_RF_B 5 #define PIN_RF_C 27 // RF Receiver D3 #define PIN_RF_D 26 // RF Receiver D1 // Steering Controller Motor/Potentiometer #define PIN_STEER_PWM 10 // Steering Motor Speed Control (PWM) #define PIN_STEER_INA1 22 // Steering Motor Direction/Input 1 #define PIN_STEER_INB1 23 // Steering Motor Direction/Input 2 //#define PIN_STEER_EN1DIAG1 1 // Steering Motor Standby/Sleep #define PIN_STEER_POT 15 // Steering Motor Position Potentiometer // Range Sensor #define PIN_RANGE_TRIG 46 #define PIN_RANGE_ECHO 47 #define MOTOR_FRONT 0 #define MOTOR_REAR 1 #define MOTOR_BOTH 2 #define MOTOR_STEER 3 #define MOTOR_DIRECTION_CW 0 // Forward/Right #define MOTOR_DIRECTION_CCW 1 // Reverse/Left #define MOTOR_DIRECTION_COAST 2 #define MOTOR_DIRECTION_BRAKE_LOW 3 #define MOTOR_DIRECTION_BRAKE_HIGH 4 #define MOTOR_DIRECTION_DISABLE 5 class Ctrl { public: /* * Empty Constructor */ Ctrl(){} ; /* * Initialize I/Os, shift register, and set configuration settings */ void init(); // Initialize controllers/sensors void run(); // Run controller/sensor step functions void MotorControl(unsigned char motor_index, unsigned char direction, int speed); /* * Control primary drive motors * * @param motor Specify which motor to control (DRIVE_MOTOR_FRONT, DRIVE_MOTOR_REAR, DRIVE_MOTOR_BOTH) * @param direction Specify which direction to drive (DRIVE_MOTOR_FORWARD, DRIVE_MOTOR_REVERSE, DRIVE_DIRECTION_BRAKE_LOW, DRIVE_DIRECTION_BRAKE_HIGH) * @param speed Specify speed to drive (0 to 1, for example 0.5 drives at half speed) */ void Drive(unsigned char motor, unsigned char direction, float speed); /* * Control steering motors * * @param direction Specify which direction to drive (DRIVE_MOTOR_FORWARD, DRIVE_MOTOR_REVERSE, DRIVE_DIRECTION_BRAKE_LOW, DRIVE_DIRECTION_BRAKE_HIGH) * @param speed Specify speed to drive (0 to 1, for example 0.5 drives at half speed) * @param amount Specify how hard to turnt the wheels (0 to 1, for example 1 is full turn, 0.5 is half turn) */ void Turn(unsigned char direction, int speed); void CalibrateSteering(); void checkSteering(); void checkDrive(); void getRange(); void getHeading(); float distanceTraveled(); void calcRangeTimeout(); void readAccelGyro(); void getPressure(); int __motorINAPIN[3] = {PIN_MOTOR_FRONT_INA, PIN_MOTOR_REAR_INA, 0}; int __motorINBPIN[3] = {PIN_MOTOR_FRONT_INB, PIN_MOTOR_REAR_INB, 0}; int __motorPWMPin[3] = {PIN_MOTOR_FRONT_PWM, PIN_MOTOR_REAR_PWM, 0}; int __motorRamp[3] = {3000, 3000, 3000}; int __motorCurrentSpeed[3] = {0, 0, 0}; int __motorGoalSpeed[3] = {0, 0, 0}; int __motorDirection[3] = {MOTOR_DIRECTION_BRAKE_LOW, MOTOR_DIRECTION_BRAKE_LOW, MOTOR_DIRECTION_BRAKE_LOW}; float __motorAcc[3] = {0.0, 0.0, 0.0}; unsigned long __motorAccTime[3] = {0, 0, 0}; // Front/Rear/Steering motor ramp-up (acceleration) speed (milliseconds to get from 0-100%) int __frontMotorRamp = 3000; int __rearMotorRamp = 3000; int __steerMotorRamp = 3000; // Front/Rear/Steering motor current speed (in %) float _frontCurrentSpeed = 0.0; float _rearCurrentSpeed = 0.0; float _steerCurrentSpeed = 0.0; // Front/Rear/Steering motor goal speed (in %) float _frontGoalSpeed = 0.0; float _rearGoalSpeed = 0.0; float _steerGoalSpeed = 0.0; // Front/Rear/Steering motor current direction (in %) float _frontDirection = 0.0; float _rearDirection = 0.0; float _steerDirection = 0.0; // Potentiometer Tolerance for maintaining position (in analog) int __potMaintainTolerance = 10; int _potValue; int _frontCurrent; bool _frontFault; int _rearCurrent; bool _rearFault; // Hall Effect Sensor config/readings unsigned long _ticks = 0; float __tickDistance = 8.0316; // Range sensor config/readings unsigned int __speedOfSound = 33350; // cm/s unsigned int __rangeMin = 2; // cm unsigned int __rangeMax = 400; // cm unsigned long __rangeTimeout = 1000000; unsigned int _rangeDuration; // us float _rangeDistance; // cm /* Potentiometer Edge Values (Right - Left) Base: 0 - 1023 Casing: ~100 - ~910 Wheels: ~352 - ~630 Ideal: 380 - 610 */ int _POT_LEFT_MAX = 800; //688 int _POT_RIGHT_MAX = 200; // 431 int _potCenter = 472; // 560 int _turnAmountPot = 0; // Potentiometer value for 1% turn int _turnLeftGoal = _POT_LEFT_MAX; int _turnRightGoal = _POT_RIGHT_MAX; int _turningDirection = MOTOR_DIRECTION_BRAKE_LOW; int _turningSpeed = 255; String _turningStatus = ""; // RF Receiver volatile bool _RF_A = false; volatile bool _RF_B = false; // Compass int16_t _headingX; int16_t _headingY; int16_t _headingZ; float _heading; int __degreeCorrection = 90; // Accelerometer/Gyro Values int16_t _ax, _ay, _az; int16_t _gx, _gy, _gz; // Pressure Sensor float __altitude = 1655.0; // meters double _altitudeDiff; // Calculated altitude difference double _baselinePressure; double _temperature; double _temperatureF; double _pressure; // Absolute pressure reading in mb double _pressureHG; // Absolute pressure reading in inches of HG double _pressure0; // Altitude adjusted pressure reading in mb double _pressure0HG; // Altitude adjusted pressure reading in inches of HG HMC5883L compass; MPU6050 accelgyro; SFE_BMP180 pressure; bool setKill = false; private: int _potGoal; bool _turn_command_changed; }; extern Ctrl Controller; #endif
da978d4b417e472474c1cb4a4babe9201a1a66f6
29b81bdc013d76b057a2ba12e912d6d4c5b033ef
/boost/include/boost/numeric/odeint/integrate/integrate_n_steps.hpp
b00d9c754fb4f1e31c51e6325b45f6da55fd3d2d
[]
no_license
GSIL-Monitor/third_dependences
864d2ad73955ffe0ce4912966a4f0d1c60ebd960
888ebf538db072a92d444a9e5aaa5e18b0f11083
refs/heads/master
2020-04-17T07:32:49.546337
2019-01-18T08:47:28
2019-01-18T08:47:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
integrate_n_steps.hpp
version https://git-lfs.github.com/spec/v1 oid sha256:84372575aaf46943b4fb03b947ec7da511bbe8d18b6029a8499e834d091bd0d4 size 7175
5800143cfb323914df2cc59b1d740398e74f4fc1
867cc5a0a33a87f474f98faa2a91146209febeaa
/webots_ros2_driver/include/webots_ros2_driver/plugins/dynamic/Ros2RGBD.hpp
678d71e3b2fda53bdc6c2dbcb7ce6e605f96f919
[ "Apache-2.0" ]
permissive
cyberbotics/webots_ros2
ab242db5b43ad5248f5324b5a816de31932e2762
e5f890ecff54aa1763e8917980de78a19c093cb1
refs/heads/master
2023-08-26T20:27:52.081847
2023-08-10T13:23:24
2023-08-10T13:23:24
201,006,807
324
130
Apache-2.0
2023-09-12T21:54:39
2019-08-07T08:25:55
C
UTF-8
C++
false
false
1,444
hpp
Ros2RGBD.hpp
// Copyright 1996-2023 Cyberbotics 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. #ifndef ROS2_RGBD_HPP #define ROS2_RGBD_HPP #include <unordered_map> #include <sensor_msgs/msg/point_cloud2.hpp> #include <webots_ros2_driver/WebotsNode.hpp> #include <webots_ros2_driver/plugins/Ros2SensorPlugin.hpp> namespace webots_ros2_driver { class Ros2RGBD : public Ros2SensorPlugin { public: void init(webots_ros2_driver::WebotsNode *node, std::unordered_map<std::string, std::string> &parameters) override; void step() override; private: void publishData(); rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr mPublisher; WbDeviceTag mCamera; WbDeviceTag mRangeFinder; int mWidth; int mHeight; double mCenterX; double mCenterY; double mFocalLengthX; double mFocalLengthY; sensor_msgs::msg::PointCloud2 mMessage; }; } // namespace webots_ros2_driver #endif
c0198986c79984cb488c5381c74915cc62e8678d
b33fb5b0223955ae1ff7ad48688270d2e884d51e
/Library/SimTools/GeometricMGOperations.cpp
eba7125a5d54c7854c05684eb9ba9e1a25f42852
[ "MIT" ]
permissive
OrionQuest/2DFluid
fa0102092eac8bb163b97cd1957f69c4acd9778b
e6872eec78d3f220d3b586998d30a20cd7a9d540
refs/heads/master
2020-07-04T06:08:44.564925
2019-08-13T16:22:33
2019-08-13T16:22:33
202,181,681
1
0
null
2019-08-13T16:17:12
2019-08-13T16:17:11
null
UTF-8
C++
false
false
35,383
cpp
GeometricMGOperations.cpp
#include "GeometricMGOperations.h" #include "tbb/tbb.h" using namespace tbb; Vec2i getChildCell(Vec2i cell, const int childIndex) { assert(childIndex < 4); cell *= 2; for (int axis : {0, 1}) { if (childIndex & (1 << axis)) ++cell[axis]; } return cell; } void GeometricMGOperations::dampedJacobiPoissonSmoother(UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const Real dx) { assert(solution.size() == rhs.size() & solution.size() == cellLabels.size()); // TODO: fix MG code to remove dependency on dx Real gridScalar = 1. / Util::sqr(dx); UniformGrid<Real> tempSolution = solution; int totalVoxels = solution.size()[0] * solution.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = solution.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real count = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < solution.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= tempSolution(adjacentCell); ++count; } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) ++count; } laplacian += count * tempSolution(cell); laplacian *= gridScalar; Real residual = rhs(cell) - laplacian; residual /= (count * gridScalar); solution(cell) += 2. / 3. * residual; } } }); } void GeometricMGOperations::dampedJacobiWeightedPoissonSmoother(UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const VectorGrid<Real> &gradientWeights, const Real dx) { assert(solution.size() == rhs.size() & solution.size() == cellLabels.size()); Real gridScalar = 1. / Util::sqr(dx); UniformGrid<Real> tempSolution = solution; int totalVoxels = solution.size()[0] * solution.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = solution.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real diagonal = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); Vec2i face = cellToFace(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < solution.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= gradientWeights(face, axis) * tempSolution(adjacentCell); diagonal += gradientWeights(face, axis); } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) diagonal += gradientWeights(face, axis); else assert(gradientWeights(face, axis) == 0); } laplacian += diagonal * tempSolution(cell); laplacian *= gridScalar; Real residual = rhs(cell) - laplacian; residual /= (diagonal * gridScalar); solution(cell) += 2. / 3. * residual; } } }); } void GeometricMGOperations::dampedJacobiPoissonSmoother(UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const std::vector<Vec2i> &boundaryCells, const Real dx) { assert(solution.size() == rhs.size() & solution.size() == cellLabels.size()); Real gridScalar = 1. / Util::sqr(dx); std::vector<Real> tempSolution(boundaryCells.size(), 0); parallel_for(blocked_range<int>(0, boundaryCells.size(), tbbGrainSize), [&](const blocked_range<int> &range) { for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = boundaryCells[cellIndex]; assert(cellLabels(cell) == CellLabels::INTERIOR); Real laplacian = 0; Real count = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < solution.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= solution(adjacentCell); ++count; } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) ++count; } laplacian += count * solution(cell); laplacian *= gridScalar; Real residual = rhs(cell) - laplacian; residual /= (count * gridScalar); tempSolution[cellIndex] = solution(cell) + 2. / 3. * residual; } }); parallel_for(blocked_range<int>(0, boundaryCells.size(), tbbGrainSize), [&](const blocked_range<int> &range) { for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = boundaryCells[cellIndex]; solution(cell) = tempSolution[cellIndex]; } }); } void GeometricMGOperations::dampedJacobiWeightedPoissonSmoother(UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const std::vector<Vec2i> &boundaryCells, const VectorGrid<Real> &gradientWeights, const Real dx) { assert(solution.size() == rhs.size() & solution.size() == cellLabels.size()); Real gridScalar = 1. / Util::sqr(dx); std::vector<Real> tempSolution(boundaryCells.size(), 0); parallel_for(blocked_range<int>(0, boundaryCells.size(), tbbGrainSize), [&](const blocked_range<int> &range) { for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = boundaryCells[cellIndex]; assert(cellLabels(cell) == CellLabels::INTERIOR); Real laplacian = 0; Real diagonal = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); Vec2i face = cellToFace(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < solution.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= gradientWeights(face, axis) * solution(adjacentCell); diagonal += gradientWeights(face, axis); } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) diagonal += gradientWeights(face, axis); else assert(gradientWeights(face, axis) == 0); } laplacian += diagonal * solution(cell); laplacian *= gridScalar; Real residual = rhs(cell) - laplacian; residual /= (diagonal * gridScalar); tempSolution[cellIndex] = solution(cell) + 2. / 3. * residual; } }); parallel_for(blocked_range<int>(0, boundaryCells.size(), tbbGrainSize), [&](const blocked_range<int> &range) { for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = boundaryCells[cellIndex]; solution(cell) = tempSolution[cellIndex]; } }); } void GeometricMGOperations::applyPoissonMatrix(UniformGrid<Real> &destination, const UniformGrid<Real> &source, const UniformGrid<CellLabels> &cellLabels, const Real dx) { assert(destination.size() == source.size() && source.size() == cellLabels.size()); Real gridScalar = 1. / Util::sqr(dx); int totalVoxels = destination.size()[0] * destination.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destination.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real count = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < destination.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= source(adjacentCell); ++count; } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) ++count; } laplacian += count * source(cell); laplacian *= gridScalar; destination(cell) = laplacian; } } }); } void GeometricMGOperations::applyWeightedPoissonMatrix(UniformGrid<Real> &destination, const UniformGrid<Real> &source, const UniformGrid<CellLabels> &cellLabels, const VectorGrid<Real> &gradientWeights, const Real dx) { assert(destination.size() == source.size() && source.size() == cellLabels.size()); assert(gradientWeights.sampleType() == VectorGridSettings::SampleType::STAGGERED && gradientWeights.size(0)[0] == destination.size()[0] + 1 && gradientWeights.size(0)[1] == destination.size()[1] && gradientWeights.size(1)[0] == destination.size()[0] && gradientWeights.size(1)[1] == destination.size()[1] + 1); Real gridScalar = 1. / Util::sqr(dx); int totalVoxels = destination.size()[0] * destination.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destination.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real diagonal = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); Vec2i face = cellToFace(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < destination.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= gradientWeights(face, axis) * source(adjacentCell); diagonal += gradientWeights(face, axis); } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) diagonal += gradientWeights(face, axis); else assert(gradientWeights(face, axis) == 0); } laplacian += diagonal * source(cell); laplacian *= gridScalar; destination(cell) = laplacian; } } }); } void GeometricMGOperations::computePoissonResidual(UniformGrid<Real> &residual, const UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const Real dx) { assert(residual.size() == solution.size() && residual.size() == rhs.size() & residual.size() == cellLabels.size()); Real gridScalar = 1. / Util::sqr(dx); int totalVoxels = residual.size()[0] * residual.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = residual.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real count = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < residual.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= solution(adjacentCell); ++count; } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) ++count; } laplacian += count * solution(cell); laplacian *= gridScalar; residual(cell) = rhs(cell) - laplacian; } } }); } void GeometricMGOperations::computeWeightedPoissonResidual(UniformGrid<Real> &residual, const UniformGrid<Real> &solution, const UniformGrid<Real> &rhs, const UniformGrid<CellLabels> &cellLabels, const VectorGrid<Real> &gradientWeights, const Real dx) { assert(residual.size() == solution.size() && residual.size() == rhs.size() & residual.size() == cellLabels.size()); assert(gradientWeights.sampleType() == VectorGridSettings::SampleType::STAGGERED && gradientWeights.size(0)[0] == residual.size()[0] + 1 && gradientWeights.size(0)[1] == residual.size()[1] && gradientWeights.size(1)[0] == residual.size()[0] && gradientWeights.size(1)[1] == residual.size()[1] + 1); Real gridScalar = 1. / Util::sqr(dx); int totalVoxels = residual.size()[0] * residual.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = residual.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) { Real laplacian = 0; Real diagonal = 0; for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); Vec2i face = cellToFace(cell, axis, direction); assert(adjacentCell[axis] >= 0 && adjacentCell[axis] < residual.size()[axis]); if (cellLabels(adjacentCell) == CellLabels::INTERIOR) { laplacian -= gradientWeights(face, axis) * solution(adjacentCell); diagonal += gradientWeights(face, axis); } else if (cellLabels(adjacentCell) == CellLabels::DIRICHLET) diagonal += gradientWeights(face, axis); else assert(gradientWeights(face, axis) == 0); } laplacian += diagonal * solution(cell); laplacian *= gridScalar; residual(cell) = rhs(cell) - laplacian; } } }); } static Real restrictionWeights[4][4] = {{1. / 64., 3. / 64., 3. / 64., 1. / 64.}, {3. / 64., 9. / 64., 9. / 64., 3. / 64.}, {3. / 64., 9. / 64., 9. / 64., 3. / 64.}, {1. / 64., 3. / 64., 3. / 64., 1. / 64.} }; void GeometricMGOperations::downsample(UniformGrid<Real> &destinationGrid, const UniformGrid<Real> &sourceGrid, const UniformGrid<CellLabels> &destinationCellLabels, const UniformGrid<CellLabels> &sourceCellLabels) { // Make sure both source and destination grid are powers of 2 and one level apart. assert(2 * destinationGrid.size() == sourceGrid.size()); assert(destinationGrid.size() == destinationCellLabels.size()); assert(sourceGrid.size() == sourceCellLabels.size()); assert(destinationGrid.size()[0] % 2 == 0 && destinationGrid.size()[1] % 2 == 0 && sourceGrid.size()[0] % 2 == 0 && sourceGrid.size()[1] % 2 == 0); int totalVoxels = destinationCellLabels.size()[0] * destinationCellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destinationCellLabels.unflatten(flatIndex); if (destinationCellLabels(cell) == CellLabels::INTERIOR) { // Iterator over source cells Real sampleValue = 0; Vec2i startCell = 2 * cell - Vec2i(1); forEachVoxelRange(Vec2i(0), Vec2i(4), [&](const Vec2i &sampleIndex) { Vec2i sampleCell = startCell + sampleIndex; assert(sampleCell[0] >= 0 && sampleCell[0] < sourceGrid.size()[0] && sampleCell[1] >= 0 && sampleCell[1] < sourceGrid.size()[1]); if (sourceCellLabels(sampleCell) == CellLabels::INTERIOR) sampleValue += restrictionWeights[sampleIndex[0]][sampleIndex[1]] * sourceGrid(sampleCell); }); destinationGrid(cell) = sampleValue; } } }); } void GeometricMGOperations::upsample(UniformGrid<Real> &destinationGrid, const UniformGrid<Real> &sourceGrid, const UniformGrid<CellLabels> &destinationCellLabels, const UniformGrid<CellLabels> &sourceCellLabels) { // Make sure both source and destination grid are powers of 2 and one level apart. assert(destinationGrid.size() / 2 == sourceGrid.size()); assert(destinationGrid.size() == destinationCellLabels.size()); assert(sourceGrid.size() == sourceCellLabels.size()); assert(destinationGrid.size()[0] % 2 == 0 && destinationGrid.size()[1] % 2 == 0 && sourceGrid.size()[0] % 2 == 0 && sourceGrid.size()[1] % 2 == 0); int totalVoxels = destinationCellLabels.size()[0] * destinationCellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destinationCellLabels.unflatten(flatIndex); if (destinationCellLabels(cell) == CellLabels::INTERIOR) { // Iterator over source cells Real sampleValue = 0; Vec2R samplePoint = .5 * (Vec2R(cell) + Vec2R(.5)) - Vec2R(.5); Vec2i startCell = Vec2i(samplePoint); Vec2R interpWeight = samplePoint - Vec2R(startCell); // Hard code interpolation Real v00 = (sourceCellLabels(startCell) == CellLabels::INTERIOR) ? sourceGrid(startCell) : 0; Real v01 = (sourceCellLabels(startCell + Vec2i(0, 1)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(0, 1)) : 0; Real v10 = (sourceCellLabels(startCell + Vec2i(1, 0)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(1, 0)) : 0; Real v11 = (sourceCellLabels(startCell + Vec2i(1, 1)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(1, 1)) : 0; destinationGrid(cell) = Util::bilerp(v00, v10, v01, v11, interpWeight[0], interpWeight[1]); } } }); } void GeometricMGOperations::upsampleAndAdd(UniformGrid<Real> &destinationGrid, const UniformGrid<Real> &sourceGrid, const UniformGrid<CellLabels> &destinationCellLabels, const UniformGrid<CellLabels> &sourceCellLabels) { // Make sure both source and destination grid are powers of 2 and one level apart. assert(destinationGrid.size() / 2 == sourceGrid.size()); assert(destinationGrid.size() == destinationCellLabels.size()); assert(sourceGrid.size() == sourceCellLabels.size()); assert(destinationGrid.size()[0] % 2 == 0 && destinationGrid.size()[1] % 2 == 0 && sourceGrid.size()[0] % 2 == 0 && sourceGrid.size()[1] % 2 == 0); int totalVoxels = destinationCellLabels.size()[0] * destinationCellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destinationCellLabels.unflatten(flatIndex); if (destinationCellLabels(cell) == CellLabels::INTERIOR) { // Iterator over source cells Real sampleValue = 0; Vec2R samplePoint = .5 * (Vec2R(cell) + Vec2R(.5)) - Vec2R(.5); Vec2i startCell = Vec2i(samplePoint); Vec2R interpWeight = samplePoint - Vec2R(startCell); // Hard code interpolation Real v00 = (sourceCellLabels(startCell) == CellLabels::INTERIOR) ? sourceGrid(startCell) : 0; Real v01 = (sourceCellLabels(startCell + Vec2i(0, 1)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(0, 1)) : 0; Real v10 = (sourceCellLabels(startCell + Vec2i(1, 0)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(1, 0)) : 0; Real v11 = (sourceCellLabels(startCell + Vec2i(1, 1)) == CellLabels::INTERIOR) ? sourceGrid(startCell + Vec2i(1, 1)) : 0; destinationGrid(cell) += Util::bilerp(v00, v10, v01, v11, interpWeight[0], interpWeight[1]); } } }); } UniformGrid<GeometricMGOperations::CellLabels> GeometricMGOperations::buildCoarseCellLabels(const UniformGrid<CellLabels> &sourceCellLabels) { assert(sourceCellLabels.size()[0] % 2 == 0 && sourceCellLabels.size()[1] % 2 == 0); UniformGrid<CellLabels> destinationCellLabels(sourceCellLabels.size() / 2, CellLabels::EXTERIOR); int totalVoxels = destinationCellLabels.size()[0] * destinationCellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destinationCellLabels.unflatten(flatIndex); // Iterate over the destination cell's children. Vec2i childCell = 2 * cell; bool hasDirichletChild = false; bool hasInteriorChild = false; for (int cellIndex = 0; cellIndex < 4; ++cellIndex) { Vec2i localCell = cellToNode(childCell, cellIndex); if (sourceCellLabels(localCell) == CellLabels::DIRICHLET) { hasDirichletChild = true; break; } else if (sourceCellLabels(localCell) == CellLabels::INTERIOR) hasInteriorChild = true; } if (hasDirichletChild) destinationCellLabels(cell) = CellLabels::DIRICHLET; else if (hasInteriorChild) destinationCellLabels(cell) = CellLabels::INTERIOR; else destinationCellLabels(cell) = CellLabels::EXTERIOR; } }); return destinationCellLabels; } UniformGrid<GeometricMGOperations::CellLabels> GeometricMGOperations::buildBoundaryCellLabels(const UniformGrid<CellLabels> &sourceCellLabels, int boundaryWidth) { assert(sourceCellLabels.size()[0] % 2 == 0 && sourceCellLabels.size()[1] % 2 == 0); UniformGrid<CellLabels> boundaryCellLabels(sourceCellLabels.size(), CellLabels::EXTERIOR); UniformGrid<MarkedCells> visitedCells(sourceCellLabels.size(), MarkedCells::UNVISITED); int totalVoxels = sourceCellLabels.size()[0] * sourceCellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = sourceCellLabels.unflatten(flatIndex); if (sourceCellLabels(cell) == CellLabels::INTERIOR) { for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); if (sourceCellLabels(adjacentCell) == CellLabels::DIRICHLET || sourceCellLabels(adjacentCell) == CellLabels::EXTERIOR) { boundaryCellLabels(cell) = CellLabels::BOUNDARY; visitedCells(cell) = MarkedCells::VISITED; } } } } }); for (int layer = 1; layer < boundaryWidth; ++layer) { parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = sourceCellLabels.unflatten(flatIndex); if (visitedCells(cell) == MarkedCells::VISITED) visitedCells(cell) = MarkedCells::FINISHED; } }); parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = sourceCellLabels.unflatten(flatIndex); if (boundaryCellLabels(cell) == CellLabels::BOUNDARY && visitedCells(cell) == MarkedCells::FINISHED) { for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); if (sourceCellLabels(adjacentCell) == CellLabels::INTERIOR && visitedCells(adjacentCell) == MarkedCells::UNVISITED) { boundaryCellLabels(adjacentCell) = CellLabels::BOUNDARY; visitedCells(adjacentCell) = MarkedCells::VISITED; } } } } }); } return boundaryCellLabels; } std::vector<Vec2i> GeometricMGOperations::buildBoundaryCells(const UniformGrid<CellLabels> &sourceCellLabels, int boundaryWidth) { assert(sourceCellLabels.size()[0] % 2 == 0 && sourceCellLabels.size()[1] % 2 == 0); UniformGrid<MarkedCells> visitedCells(sourceCellLabels.size(), MarkedCells::UNVISITED); using ParallelBoundaryCellListType = enumerable_thread_specific<std::vector<Vec2i>>; ParallelBoundaryCellListType parallelBoundaryCellList; int totalVoxels = sourceCellLabels.size()[0] * sourceCellLabels.size()[1]; // Build initial layer parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { auto &localBoundaryCellList = parallelBoundaryCellList.local(); for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = sourceCellLabels.unflatten(flatIndex); if (sourceCellLabels(cell) == CellLabels::INTERIOR) { bool isBoundary = false; for (int axis = 0; axis < 2 && !isBoundary; ++axis) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); if (sourceCellLabels(adjacentCell) == CellLabels::DIRICHLET || sourceCellLabels(adjacentCell) == CellLabels::EXTERIOR) { isBoundary = true; break; } } if (isBoundary) localBoundaryCellList.push_back(cell); } } }); std::vector<std::vector<Vec2i>> perLayerboundaryCells(boundaryWidth); // Pre-allocate memory int cellCount = 0; parallelBoundaryCellList.combine_each([&cellCount](const std::vector<Vec2i> &localList) { cellCount += localList.size(); }); perLayerboundaryCells[0].reserve(cellCount); // Insert cells parallelBoundaryCellList.combine_each([&perLayerboundaryCells](const std::vector<Vec2i> &localList) { perLayerboundaryCells[0].insert(perLayerboundaryCells[0].end(), localList.begin(), localList.end()); }); auto vecCompare = [](const Vec2i &vec0, const Vec2i &vec1) { if (vec0[0] < vec1[0]) return true; else if (vec0[0] == vec1[0] && vec0[1] < vec1[1]) return true; return false; }; parallel_sort(perLayerboundaryCells[0].begin(), perLayerboundaryCells[0].end(), vecCompare); std::vector<Vec2i> preSortedTempList; for (int layer = 1; layer < boundaryWidth; ++layer) { // Set cells to visited int localCellCount = perLayerboundaryCells[layer - 1].size(); parallel_for(blocked_range<int>(0, localCellCount, tbbGrainSize), [&](const blocked_range<int> &range) { for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = perLayerboundaryCells[layer - 1][cellIndex]; visitedCells(cell) = MarkedCells::FINISHED; } }); parallelBoundaryCellList.clear(); parallel_for(blocked_range<int>(0, localCellCount, tbbGrainSize), [&](const blocked_range<int> &range) { auto &localBoundaryCellList = parallelBoundaryCellList.local(); for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex) { Vec2i cell = perLayerboundaryCells[layer - 1][cellIndex]; assert(visitedCells(cell) == MarkedCells::FINISHED); for (int axis : {0, 1}) for (int direction : {0, 1}) { Vec2i adjacentCell = cellToCell(cell, axis, direction); if (sourceCellLabels(adjacentCell) == CellLabels::INTERIOR && visitedCells(adjacentCell) == MarkedCells::UNVISITED) { localBoundaryCellList.push_back(adjacentCell); } } } }); // // Collect new layer // // Pre-allocate memory cellCount = 0; parallelBoundaryCellList.combine_each([&cellCount](const std::vector<Vec2i> &localList) { cellCount += localList.size(); }); preSortedTempList.clear(); preSortedTempList.reserve(cellCount); // Insert cells into a temporary list parallelBoundaryCellList.combine_each([&preSortedTempList](const std::vector<Vec2i> &localList) { preSortedTempList.insert(preSortedTempList.end(), localList.begin(), localList.end()); }); // Sort temporary list and copy without duplicates to the final list parallel_sort(preSortedTempList.begin(), preSortedTempList.end(), vecCompare); parallelBoundaryCellList.clear(); parallel_for(blocked_range<int>(0, preSortedTempList.size(), tbbGrainSize), [&](const blocked_range<int> &range) { auto &localBoundaryCellList = parallelBoundaryCellList.local(); const int endCell = range.end(); int startCell = range.begin(); if (startCell > 0 && preSortedTempList[startCell] == preSortedTempList[startCell - 1]) { Vec2i localCell = preSortedTempList[startCell]; while (startCell != endCell && localCell == preSortedTempList[startCell]) ++startCell; if (startCell == endCell) return; } Vec2i oldCell(-1); for (int cellIndex = startCell; cellIndex < endCell; ++cellIndex) { Vec2i newCell = preSortedTempList[cellIndex]; if (oldCell != newCell) { localBoundaryCellList.push_back(newCell); oldCell = newCell; } } }); // Collect final list cellCount = 0; parallelBoundaryCellList.combine_each([&cellCount](const std::vector<Vec2i> &localList) { cellCount += localList.size(); }); assert(perLayerboundaryCells[layer].empty()); perLayerboundaryCells[layer].reserve(cellCount); // Insert cells into a temporary list parallelBoundaryCellList.combine_each([&perLayerboundaryCells, &layer](const std::vector<Vec2i> &localList) { perLayerboundaryCells[layer].insert(perLayerboundaryCells[layer].end(), localList.begin(), localList.end()); }); // Sort temporary list and copy without duplicates to the final list parallel_sort(perLayerboundaryCells[layer].begin(), perLayerboundaryCells[layer].end(), vecCompare); } std::vector<Vec2i> finalBoundaryLayerCells; int finalCellCount = 0; for (int layer = 0; layer < boundaryWidth; ++layer) finalCellCount += perLayerboundaryCells[layer].size(); finalBoundaryLayerCells.reserve(finalCellCount); for (int layer = 0; layer < boundaryWidth; ++layer) finalBoundaryLayerCells.insert(finalBoundaryLayerCells.end(), perLayerboundaryCells[layer].begin(), perLayerboundaryCells[layer].end()); parallel_sort(finalBoundaryLayerCells.begin(), finalBoundaryLayerCells.end(), vecCompare); return finalBoundaryLayerCells; } bool GeometricMGOperations::unitTestCoarsening(const UniformGrid<CellLabels> &coarseCellLabels, const UniformGrid<CellLabels> &fineCellLabels) { // The coarse cell grid must be exactly have the size of the fine cell grid. if (2 * coarseCellLabels.size() != fineCellLabels.size()) return false; if (coarseCellLabels.size()[0] % 2 != 0 || coarseCellLabels.size()[1] % 2 != 0 || fineCellLabels.size()[0] % 2 != 0 || fineCellLabels.size()[1] % 2 != 0) return false; { bool testPassed = true; forEachVoxelRange(Vec2i(0), fineCellLabels.size(), [&](const Vec2i &fineCell) { Vec2i coarseCell = fineCell / 2; if (!testPassed) return; // If the fine cell is Dirichlet, it's coarse cell equivalent has to also be Dirichlet if (fineCellLabels(fineCell) == CellLabels::DIRICHLET) { if (coarseCellLabels(coarseCell) != CellLabels::DIRICHLET) testPassed = false; } else if (fineCellLabels(fineCell) == CellLabels::INTERIOR) { // If the fine cell is interior, the coarse cell can be either // interior or Dirichlet (if a sibling cell is Dirichlet). if (coarseCellLabels(coarseCell) == CellLabels::EXTERIOR) testPassed = false; } }); if(!testPassed) return false; } { bool testPassed = true; forEachVoxelRange(Vec2i(0), coarseCellLabels.size(), [&](const Vec2i &coarseCell) { if (!testPassed) return; bool foundDirichletChild = false; bool foundInteriorChild = false; bool foundExteriorChild = false; for (int childIndex = 0; childIndex < 4; ++childIndex) { Vec2i fineCell = getChildCell(coarseCell, childIndex); auto fineLabel = fineCellLabels(fineCell); if (fineLabel == CellLabels::DIRICHLET) foundDirichletChild = true; else if (fineLabel == CellLabels::INTERIOR) foundInteriorChild = true; else if (fineLabel == CellLabels::EXTERIOR) foundExteriorChild = true; } auto coarseLabel = coarseCellLabels(coarseCell); if (coarseLabel == CellLabels::DIRICHLET) { if (!foundDirichletChild) testPassed = false; } else if (coarseLabel == CellLabels::INTERIOR) { if (foundDirichletChild || !foundInteriorChild) testPassed = false; } else if (coarseLabel == CellLabels::EXTERIOR) { if (foundDirichletChild || foundInteriorChild || !foundExteriorChild) testPassed = false; } }); if(!testPassed) return false; } return true; } double GeometricMGOperations::dotProduct(const UniformGrid<Real> &aVectorGrid, const UniformGrid<Real> &bVectorGrid, const UniformGrid<CellLabels> &cellLabels) { double dotValue = 0; forEachVoxelRange(Vec2i(0), cellLabels.size(), [&](const Vec2i &cell) { if (cellLabels(cell) == CellLabels::INTERIOR) dotValue += aVectorGrid(cell) * bVectorGrid(cell); }); return dotValue; } void GeometricMGOperations::addToVector(UniformGrid<Real> &destination, const UniformGrid<Real> &source, const UniformGrid<CellLabels> &cellLabels, const Real scale) { assert(destination.size() == source.size() && source.size() == cellLabels.size()); int totalVoxels = destination.size()[0] * destination.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destination.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) destination(cell) += scale * source(cell); } }); } void GeometricMGOperations::addToVector(UniformGrid<Real> &destination, const UniformGrid<Real> &source, const UniformGrid<Real> &scaledSource, const UniformGrid<CellLabels> &cellLabels, const Real scale) { assert(destination.size() == source.size() && source.size() == scaledSource.size() && scaledSource.size() == cellLabels.size()); int totalVoxels = destination.size()[0] * destination.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = destination.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) destination(cell) = source(cell) + scale * scaledSource(cell); } }); } double GeometricMGOperations::l2Norm(const UniformGrid<Real> &vectorGrid, const UniformGrid<CellLabels> &cellLabels) { double squaredNorm = 0; forEachVoxelRange(Vec2i(0), cellLabels.size(), [&](const Vec2i &cell) { if (cellLabels(cell) == CellLabels::INTERIOR) squaredNorm += Util::sqr(vectorGrid(cell)); }); return std::sqrt(squaredNorm); } double GeometricMGOperations::lInfinityNorm(const UniformGrid<Real> &vectorGrid, const UniformGrid<CellLabels> &cellLabels) { using ParallelReal = enumerable_thread_specific<Real>; ParallelReal parallelReal(Real(0)); int totalVoxels = cellLabels.size()[0] * cellLabels.size()[1]; parallel_for(blocked_range<int>(0, totalVoxels, tbbGrainSize), [&](const blocked_range<int> &range) { Real &localMaxError = parallelReal.local(); for (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex) { Vec2i cell = cellLabels.unflatten(flatIndex); if (cellLabels(cell) == CellLabels::INTERIOR) localMaxError += std::max((Real)fabs(vectorGrid(cell)), localMaxError); } }); Real maxError = 0; parallelReal.combine_each([&maxError](const Real localMaxError) { maxError = std::max(maxError, localMaxError); }); return maxError; }
47739e2b000a96d694bc0bcbfb331808e28f4cf9
ba3c3fb341f3f74daba9b301f4972875a0f7f420
/etats.cpp
ec907c7f577c11a0254ba0e777356b2fd73dc1ae
[]
no_license
Grimlix/Labo08_Tresor
3f9f0aa132659c01655c3fb5f3eefb439709e661
6f06cbc30aca3401cba0d2b237eda51a10934735
refs/heads/master
2021-08-28T23:34:32.640270
2017-12-13T08:44:22
2017-12-13T08:44:22
113,027,271
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
cpp
etats.cpp
#include "etats.h" #include "aleatoire.h" #include "carte.h" #include <cstdlib> bool estMort(int nbrePas) { const int pasMaximum = HAUTEUR * LARGEUR; return (nbrePas > pasMaximum); } bool estDansLac(int chercheurs[][Elements::NB_PROPRIETES], int lacs[][Terrains::NB_PROPRIETES], size_t numChercheur) { // on configure les variables x et y actuelles du chercheur int x = chercheurs[numChercheur][Elements::Proprietes::x]; int y = chercheurs[numChercheur][Elements::Proprietes::y]; int centreLacX; int centreLacY; int rayonLac; // vu qu'il y a plusieurs lacs, il faut vérifier avec les 3 lacs. // on configure comme pour le chercheur, les variables x et y au centre du lac for(int lac = 0; lac < NB_LACS; ++lac) { centreLacX = lacs[lac][Elements::Proprietes::x]; centreLacY = lacs[lac][Elements::Proprietes::y]; rayonLac = lacs[lac][Terrains::Proprietes::rayon]; // si le chercheur est dans le rayon d'un lac il s'est noyé if(distancePoint(x, y, centreLacX, centreLacY) <= rayonLac) return true; } return false; } bool estPerdu(int positionChercheur[][Elements::NB_PROPRIETES], size_t numChercheur) { const int largeurMin = 0; const int longueurMin = 0; int longueurMax = LARGEUR; int largeurMax = HAUTEUR; int x = positionChercheur[numChercheur][Elements::Proprietes::x]; int y = positionChercheur[numChercheur][Elements::Proprietes::y]; return (x < largeurMin || x > largeurMax || y < longueurMin || y > longueurMax); } bool estRiche(int chercheurs[][Elements::NB_PROPRIETES], int tresors[][Elements::NB_PROPRIETES], size_t numChercheur) { int xC = chercheurs[numChercheur][Elements::Proprietes::x]; int yC = chercheurs[numChercheur][Elements::Proprietes::y]; // on utilise que un tresor, mais si on voulait en rajouter il faudrait juste changer $ // la variable NB_TRESORS for(int tresor = 0; tresor < NB_TRESORS; ++tresor) { int xT = tresors[tresor][Elements::Proprietes::x]; int yT = tresors[tresor][Elements::Proprietes::y]; if(xC == xT && yC == yT) return true; } return false; }
edd0ab583e9b1193fe36e9f89ce3c91564d60672
04b017097f7f669465ba059f582880a9b64010c4
/tree_serialization_lib/tests/NodeValue.t.cpp
372b403a3c5de0ebb4402cf6bde9b4b5eedfb47d
[ "MIT" ]
permissive
Zenikolas/tree-serialization
c30023c6f4951a39a7453b9979f426660f1ce547
b4ee04a154e2a3f705433cb70a31612d2c69f7f1
refs/heads/master
2023-01-14T13:03:24.237010
2020-11-21T17:43:38
2020-11-21T17:43:38
306,456,912
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
NodeValue.t.cpp
#include <gtest/gtest.h> #include <netinet/in.h> #include "NodeValue.h" using namespace treesl; //void testBody(NodeValue& value, const std::string& expectedOutput) { // std::stringstream sstream; // ASSERT_EQ(NodeError::SUCCESS, value.serialize(sstream)); // auto [dvalue, errorCode] = NodeValue::deserialize(sstream); // ASSERT_EQ(errorCode, NodeError::SUCCESS); // ASSERT_EQ(value, dvalue); // // std::stringstream pStream; // value.print(pStream); // ASSERT_EQ(expectedOutput, pStream.str()); //} // //TEST(NodeValueTest, IntTest) { // NodeValue value(100); // // testBody(value, std::string("100")); //} // //TEST(NodeValueTest, DoubleTest) { // double expectedValue = 100.87662; // NodeValue value(expectedValue); // testBody(value, std::string("100.877")); // by default double precision is 3 digits //} // //TEST(NodeValueTest, StringTest) { // const std::string expectedString = "100dqwdw90.876"; // NodeValue value(expectedString); // // testBody(value, expectedString); //}
a3bd3aae7c15fe742c7cb0664e236233fadd9e3c
2b3f5bdab41f08a690f3d74559bab2a433ab0335
/src/util/vector2d.cpp
6f7977972df3acad8f391991ce8b33a2b27687f9
[]
no_license
drmorr0/PlanetsNuK
1db9bf025216f57a688022b1769514fe823acc7a
9c15758cbae83060b4ba177890a01a9aabee8475
refs/heads/master
2021-01-21T14:43:26.320837
2016-07-05T05:56:02
2016-07-05T05:56:02
58,293,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
vector2d.cpp
// vector2d.cpp: David R. Morrison, March 2014 // Implementation for the 2d vector #include "util/vector2d.h" #include <cmath> Vector2D& Vector2D::operator+=(const Vector2D& rhs) { x += rhs.x; y += rhs.y; return *this; } Vector2D& Vector2D::operator-=(const Vector2D& rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vector2D& Vector2D::operator*=(double scalar) { x *= scalar; y *= scalar; return *this; } Vector2D& Vector2D::operator/=(double scalar) { x /= scalar; y /= scalar; return *this; } double length(const Vector2D& v) { return sqrt(v.x * v.x + v.y * v.y); } void normalize(Vector2D& v) { v /= length(v); } const Vector2D operator+(const Vector2D& v1, const Vector2D& v2) { return Vector2D(v1.x + v2.x, v1.y + v2.y); } const Vector2D operator-(const Vector2D& v1, const Vector2D& v2) { return (v1 + (-1 * v2)); } const Vector2D operator*(double scalar, const Vector2D& v) { return Vector2D(scalar * v.x, scalar * v.y); } const Vector2D operator*(const Vector2D& v, double scalar) { return operator*(scalar, v); } const Vector2D operator/(const Vector2D& v, double scalar) { return Vector2D(v.x / scalar, v.y / scalar); }
0e62a291221bb463ecb0a8e81e5c4d227be3daac
d542e4d4379b305751c3bcc93c796e2fa7495229
/100道题/36.cpp
12cf435b884dbbe62aad1c35ba8a6858ce1c2622
[]
no_license
Yrshyx/C
a51d9e2fa0c7c3cd6962941692fe51cea2c3578f
3e083261fa4f72ced3f98acd368708eb4077b028
refs/heads/master
2020-09-10T14:19:04.060644
2020-02-27T06:55:23
2020-02-27T06:55:23
221,714,092
0
0
null
null
null
null
GB18030
C++
false
false
1,022
cpp
36.cpp
#include <stdio.h> int main() { char a=0,b=0; printf("请输入星期的首字母:"); scanf("%s",&a); if (a=='S'||a=='s') { printf("请输入第二个字母"); scanf("%s",&b); if (b=='a'||b=='A') { printf("\n星期六\n"); }else if (b=='u'||b=='U') { printf("\n星期日\n"); }else { printf("无此星期!"); } }else if (a=='m'||a=='M') { printf("\r\n星期一\r\n"); }else if (a=='t'||a=='T') { printf("请输入第二个字母"); scanf("%s",&b); if (b=='h'||b=='H') { printf("\r\n星期四\r\n"); }else if (b=='u'||b=='U') { printf("\r\n星期二\r\n"); }else { printf("无此星期!"); } }else if (a=='w'||a=='W') { printf("\r\n星期三\r\n"); }else if (a=='f'||a=='F') { printf("\r\n星期五\r\n"); }else { printf("\r\nError input!\r\n"); } return 0; }
c772dcc0514862ff86c198c0941cb01cf8b261b2
916b35804291b7755916e839acd085d217aba3dd
/ABC/abc059/a.cpp
2b55d1ead2183aaf2d742ec3f65f58d24289d278
[ "MIT" ]
permissive
EnsekiTT/atcoder
65088869d2934103e22784d689e4b66346144516
6b40332d1b2493d1b6c00c9f1912895a67a3bbcb
refs/heads/master
2021-07-02T20:21:01.931182
2020-10-03T18:15:53
2020-10-03T18:15:53
181,162,050
0
0
MIT
2019-04-15T17:38:23
2019-04-13T11:39:26
C++
UTF-8
C++
false
false
295
cpp
a.cpp
#include<iostream> #include<string> #include <algorithm> using namespace std; int main() { string s1, s2, s3; cin >> s1 >> s2 >> s3; char c1 = s1[0] - 'a' + 'A'; char c2 = s2[0] - 'a' + 'A'; char c3 = s3[0] - 'a' + 'A'; cout << c1 << c2 << c3 << endl; return 0; }
cd6d3ee51119f0c79f14e9a77d423a12dbac9322
8a1f074b4f6464986eeea6b443003007a8db4579
/DX11_200216/FrameWork/Render/Model/StaticModel.h
6203773993240974ad5b152721e57ff3b90fcd95
[]
no_license
ljm3994/TeraGame
26719244f670169bf4246d3179fdfa0521fa942c
08f680dec95b6efdf3f533231e46aa879efe6f28
refs/heads/master
2022-11-26T16:26:14.633346
2020-08-04T18:29:51
2020-08-04T18:29:51
285,057,001
0
0
null
null
null
null
UTF-8
C++
false
false
470
h
StaticModel.h
#pragma once class StaticModel : public ModelInstance { vector<StaticMeshDesc*> meshs; D3DXVECTOR3 Min, Max; public: StaticModel(string FileName, string ShaderFile, bool isCollision, UINT instanceCount); ~StaticModel(); virtual void Update(float DeltaTime) override; virtual void Render() override; virtual void ReadMesh(string FileName) override; StaticMeshDesc* GetMeshData(int Index) { return meshs[Index]; } UINT GetMeshCount() { return meshs.size(); } };
5093efcbc14a4306936c45cf4b5e0929f0813501
070220e82b5d89e18b93d6ef34d702d2119575ed
/lc7importunix/include/ShadowImporter.h
1e6dafdcf8a42fa3ec98caf53ada5f24494f798a
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Brute-f0rce/l0phtcrack
2eb4e51f36fd28c9119269881d5e66e6a6dac533
25f681c07828e5e68e0dd788d84cc13c154aed3d
refs/heads/main
2023-08-19T16:41:06.137715
2021-10-17T01:06:21
2021-10-17T01:06:21
418,568,833
2
0
null
null
null
null
UTF-8
C++
false
false
1,725
h
ShadowImporter.h
#ifndef __INC_SHADOWIMPORTER_H #define __INC_SHADOWIMPORTER_H class ShadowImporter { public: private: friend class ImportShadowConfig; quint32 m_account_limit; ILC7UnixImporter *m_pimp_oldpasswd; ILC7UnixImporter *m_pimp_linux_passwdshadow; ILC7UnixImporter *m_pimp_linux_shadow; ILC7UnixImporter *m_pimp_solaris_passwdshadow; ILC7UnixImporter *m_pimp_solaris_shadow; ILC7UnixImporter *m_pimp_bsd_passwdmasterpasswd; ILC7UnixImporter *m_pimp_bsd_masterpasswd; ILC7UnixImporter *m_pimp_aix_passwdsecuritypasswdsecurityuser; ILC7UnixImporter *m_pimp_aix_passwdsecuritypasswd; ILC7UnixImporter *m_pimp_aix_securitypasswd; QList<ILC7UnixImporter *> m_importers; QMap<QString, ILC7UnixImporter *> m_importers_by_name; void RegisterImporter(ILC7UnixImporter *pimp); void RegisterImporters(); ////// ILC7AccountList *m_accountlist; ILC7CommandControl *m_ctrl; LC7Remediations m_remediations; void UpdateStatus(QString statustext, quint32 cur, bool statuslog=true); public: enum IMPORT_FLAGS { exclude_none = 0, exclude_expired = 1, exclude_disabled = 2, exclude_lockedout = 4 }; protected: bool IncludedInFlags(LC7Account & acct, IMPORT_FLAGS flags); public: ShadowImporter(ILC7AccountList *accountlist, ILC7CommandControl *ctrl); ~ShadowImporter(); void SetAccountLimit(quint32 alim); void SetRemediations(const LC7Remediations & remediations); void GetPasswdImporters(QList<ILC7UnixImporter *> & passwd_importers); ILC7UnixImporter *GetPasswdImporter(QString name); bool DoImport(QString importer_name, QStringList filenames, FOURCC hashtype, IMPORT_FLAGS flags, QString & error, bool & cancelled); }; #endif
d8e5fe2a46a2680c8a8ab35cd20bd2688b55770e
31d65730c038c45c1b231a43c41d3654f88ea8d9
/1949/solve.cpp
5003e5d814f15c2842b1f7a884dd64f934aa4927
[]
no_license
wizleysw/backjoon
383ae80ad3bd5d95cafd4cb1326e9dd5e7ffeba6
6672d9a23171ffeff35d32ca0bd0811e866e6385
refs/heads/master
2021-07-06T15:50:00.290024
2021-04-24T08:46:18
2021-04-24T08:46:18
230,577,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
solve.cpp
// https://www.acmicpc.net/problem/1949 // 우수 마을 // Written in C++ langs // 2020. 08. 25. // Wizley #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> VILLAGE; vector<vector<int>> ROAD; vector<bool> VISITED(10001, false); int DP[10002][2]; int N; void getTotal(int pos){ VISITED[pos] = true; for(auto next: ROAD[pos]){ if(VISITED[next]) continue; getTotal(next); // 현재 마을이 우수 마을인 경우 // 다음 마을이 우수 마을로 선택될 수 없음 DP[pos][1] += DP[next][0]; // 현재 마을이 우수 마을이 아닌 경우는 // 다음 마을이 우수 마을이거나 우수마을이 아닌 경우 중 큰 값 DP[pos][0] += max(DP[next][1], DP[next][0]); } // 현재 마을이 우수 마을인 경우 사람 수를 더 해줌 DP[pos][1] += VILLAGE[pos]; } int main(){ ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> N; VILLAGE.resize(N+1); ROAD.resize(N+1); for(int i=1; i<=N; i++){ cin >> VILLAGE[i]; } int a, b; for(int i=0; i<N-1; i++){ cin >> a >> b; ROAD[a].push_back(b); ROAD[b].push_back(a); } getTotal(1); cout << max(DP[1][0], DP[1][1]) << "\n"; return 0; }
6a1fc5e488f681231c5e3621c706b592c6dacafc
b378d72e949b1ccd0acea75ccbb32018904576a4
/WWW/solutions/135.re
89fea57410f610a9b5964a63c2c5cfd68c440bcc
[ "MIT" ]
permissive
wanatpj/guarana
c1eeef7297fc771919ae362d3323b9fd339f17a7
1a3f95fedca93130698cdcf48668afdf2360d6be
refs/heads/master
2020-04-05T11:43:39.293238
2017-07-08T22:21:08
2017-07-08T22:21:08
81,142,049
0
1
null
null
null
null
UTF-8
C++
false
false
20
re
135.re
1 0 1 0 1 16 1 2868
11282a6b9164b90c7ed38638cd7c82a78ca62650
07e6a99812661a3907d06158ea818372ec9b4a03
/leetcode backtracking51.cpp
42031dd98c5dec3300be513c27b402d7470caf7e
[]
no_license
mjxyiyao/myblog
fcdc2872fde7e3dbae1d9c74111a18dc65ac0340
1bf469ee7d2edd8e7d8c5dd71fe05beba0054805
refs/heads/master
2022-02-20T02:22:06.554293
2019-10-08T07:05:05
2019-10-08T07:05:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
leetcode backtracking51.cpp
//Leetcode 51 N-queens class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; int dp[n]; //用来记录以前所有行中的列,dp[i]记录的是第i行的第j列 vector<string> temp(n, string (n, '.')); helper(res, temp, dp, 0, n);//从第0行开始,直到递归到第n行结束 return res; } private: void helper(vector<vector<string>> &res, vector<string> &temp, int dp[], int row, int n){ if (row == n) { res.push_back(temp); return; } for (int col = 0; col < n; col++) { if (valid(dp, row, col)){ dp[row] = col; temp[row][col] = 'Q'; helper(res, temp, dp, row+1, n); temp[row][col] = '.'; } } } bool valid(int dp[], int row, int col){ for (int i = 0; i < row; i++){ if(dp[i]==col || abs(row-i)==abs(dp[i]-col)) { return false; } } return true; } };
8b763e2db6c7b09e01e3068f4b3dd95a67cf7c0b
1cc24932455ba33319b0b8ad07cc41addef31735
/Lab7/Top.h
8bd1d9492199c05807f671a2b82186abb65d9f43
[]
no_license
sbogdasha/kubik
050529e70f51821f163d5da3ec0754c35dc287f8
0f702deed1289e9ae48958aad90dd576dc86948d
refs/heads/master
2021-07-24T18:24:50.042482
2021-01-14T13:09:36
2021-01-14T13:09:36
236,342,947
0
0
null
null
null
null
UTF-8
C++
false
false
445
h
Top.h
#pragma once #include <string> #include <iostream> #include <vector> using namespace std; class Top { public: Top(); Top(char _name); ~Top(); char GetName(); bool AddEdge(Top *t1, Top *t2); void printTop(); int Size(); Top* GetAdjTopByNum(int _num); void Rename(char c); //?????????????? ??? ??'???? ? t1 ?? t2 void RedirectAdj(Top* t1, Top* t2); private: char name; vector<Top*> adjList; };
4a5f22f70686c49e90f5a6416430a0044bf8905f
38985b8f8118646a93f24bce8778fade1a8ae05a
/Game/OgreExhibition/source/CreationState.cpp
636bcc6e53d5477bff519d3f1c46b7ac0959afa9
[]
no_license
whztt07/OgreFireworksimulation
838cc0b8dbbc72b698c85706b9c726cbcacef53a
4f8e832ae6f01a0d3c0c50dd0deb8af3e2e2535a
refs/heads/master
2021-01-17T11:03:41.922671
2014-05-11T08:48:57
2014-05-11T08:48:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,761
cpp
CreationState.cpp
#include "CreationState.h" #define HUMAN_CHARACTERS false //----------------------------------------------- CreationState::CreationState() { mQuit = false; mFrameEvent = Ogre::FrameEvent(); mLMouseDown = false; mRMouseDown = false; mMoveScale = 0.0f; mTranslateVector = Ogre::Vector3::ZERO; mRecast = NULL; mDetourTileCache = NULL; mDebugDraw = true; mNavMeshNode = NULL; mDebugDraw = false; mCurrentObject = NULL; mWall = false; } //----------------------------------------------- void CreationState::enter() { mOgre->mLog->logMessage( "Entering CreationState..." ); createSceneManager(); createCamera(); setViewport(); createScene(); buildGUI(); } //----------------------------------------------- void CreationState::createSceneManager( void ) { mSceneMgr = mOgre->mRoot->createSceneManager( Ogre::ST_EXTERIOR_CLOSE, "ExhibitionSceneMgr" ); mSceneMgr->setAmbientLight( Ogre::ColourValue( 0.7f, 0.7f, 0.7f ) ); mOgre->mSceneMgr = mSceneMgr; } //----------------------------------------------- void CreationState::createCamera( void ) { if ( mSceneMgr ) { mCamera = mSceneMgr->createCamera( "ExhibitionCam" ); mCamera->setPosition( Ogre::Vector3( 0, 300, 750 ) ); mCamera->lookAt( Ogre::Vector3( 750, 0, 750 ) ); mCamera->setNearClipDistance( 0.05f ); mOgre->mCamera = mCamera; } } //----------------------------------------------- void CreationState::setViewport( void ) { mOgre->mViewport->setCamera( mCamera ); mOgre->mViewport->setBackgroundColour( Ogre::ColourValue( 0.0f, 0.0f, 0.0f, 1.0f ) ); mCamera->setAspectRatio( Ogre::Real( mOgre->mViewport->getActualWidth() ) / Ogre::Real( mOgre->mViewport->getActualHeight() ) ); } //----------------------------------------------- void CreationState::buildGUI( void ) { mOgre->mTrayMgr->destroyAllWidgets(); //mOgre->mTrayMgr->showFrameStats( OgreBites::TL_BOTTOMLEFT ); //mOgre->mTrayMgr->showLogo( OgreBites::TL_BOTTOMRIGHT ); mOgre->mTrayMgr->showCursor(); Ogre::StringVector obstacleMenuList; obstacleMenuList.push_back( "Pot" ); obstacleMenuList.push_back( "Box" ); obstacleMenuList.push_back( "Exhibition1" ); obstacleMenuList.push_back( "Exhibition2" ); obstacleMenuList.push_back( "Exhibition3" ); obstacleMenuList.push_back( "Exhibition4" ); obstacleMenuList.push_back( "Exhibition5" ); obstacleMenuList.push_back( "Exhibition6" ); obstacleMenuList.push_back( "Exhibition7" ); obstacleMenuList.push_back( "Exhibition8" ); obstacleMenuList.push_back( "Exhibition9" ); obstacleMenuList.push_back( "Exhibition10" ); obstacleMenuList.push_back( "Exhibition11" ); obstacleMenuList.push_back( "Exhibition12" ); obstacleMenuList.push_back( "Exhibition13" ); mOgre->mTrayMgr->createThickSelectMenu( OgreBites::TL_TOPRIGHT, "obstacleMenu", "obstacle", 200, 5, obstacleMenuList ); mOgre->mTrayMgr->createSeparator( OgreBites::TL_TOPRIGHT, "seperator1", 200.0f ); debugDrawBox = mOgre->mTrayMgr->createCheckBox( OgreBites::TL_TOPRIGHT, "debugDrawBox", "Tile (v)", 200 ); logoBox = mOgre->mTrayMgr->createCheckBox( OgreBites::TL_TOPRIGHT, "logoBox", "Logo", 200 ); frameStatesBox = mOgre->mTrayMgr->createCheckBox( OgreBites::TL_TOPRIGHT, "frameStatesBox", "frameStates", 200 ); debugDrawBox->setChecked( true ); logoBox->setChecked( false ); frameStatesBox->setChecked( false ); mOgre->mTrayMgr->createSeparator( OgreBites::TL_TOPRIGHT, "seperator2", 200.0f ); mOgre->mTrayMgr->createLabel( OgreBites::TL_TOP, "MenuLbl", "SimulationState-Creation mode", 300 ); mOgre->mTrayMgr->createButton( OgreBites::TL_TOPRIGHT, "SaveBtn", "save", 200 ); mOgre->mTrayMgr->createButton( OgreBites::TL_TOPRIGHT, "ClearBtn", "clear", 200 ); mOgre->mTrayMgr->createButton( OgreBites::TL_TOPRIGHT, "LoadBtn", "load", 200 ); detail_btn = mOgre->mTrayMgr->createButton( OgreBites::TL_TOPRIGHT, "DetailBtn", "Detail", 200 ); delete_btn = mOgre->mTrayMgr->createButton( OgreBites::TL_NONE, "DeleteBtn", "Delete(Del)", 150 ); rotate_btn = mOgre->mTrayMgr->createButton( OgreBites::TL_NONE, "RotateBtn", "Rotate", 150 ); showDynamicBotton( false ); } //----------------------------------------------- void CreationState::createScene() { mSceneMgr->setAmbientLight( Ogre::ColourValue( 0.5, 0.5, 0.5 ) ); mSceneMgr->setShadowTechnique( Ogre::SHADOWTYPE_STENCIL_ADDITIVE ); Ogre::Plane plane( Ogre::Vector3::UNIT_Y, 0 ); Ogre::MeshManager::getSingleton().createPlane( "ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 1500, 1500, 150, 150, true, 1, 30, 30, Ogre::Vector3::UNIT_Z ); Ogre::Entity* entGround = mSceneMgr->createEntity( "GroundEntity", "ground" ); mSceneMgr->getRootSceneNode()->createChildSceneNode( Ogre::Vector3( 750, 0, 750 ) )->attachObject( entGround ); entGround->setMaterialName( "Dirt" ); entGround->setCastShadows( false ); entGround->setQueryFlags( MAP_MASK ); mNavmeshEnts.push_back( entGround ); // Add obstacle //--------------------------------------------------------------------------- //add entity //Ogre::Entity* ent = mSceneMgr->createEntity( "End", "Pot.mesh" ); //Ogre::SceneNode* mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode( "End1Node", Ogre::Vector3( 100, 0, 100 ) ); //mNode->setScale( 5, 5, 5 ); //mNode->attachObject( ent ); //ent->setCastShadows( true ); //mNavmeshEnts.push_back( ent ); // Add obstacle //---------------------------------------------------------------------- OgreRecastConfigParams recastParams = OgreRecastConfigParams(); recastParams.setCellSize( 10 ); recastParams.setCellHeight( 10 ); recastParams.setAgentMaxSlope( 45 ); recastParams.setAgentHeight( 40 ); recastParams.setAgentMaxClimb( 15 ); recastParams.setAgentRadius( 10 ); recastParams.setEdgeMaxLen( 2 ); recastParams.setEdgeMaxError( 1.3f ); recastParams.setRegionMinSize( 50 ); recastParams.setRegionMergeSize( 20 ); recastParams.setDetailSampleDist( 5 ); recastParams.setDetailSampleMaxError( 5 ); mRecast = new OgreRecast( mSceneMgr, recastParams ); // Use default configuration mDetourTileCache = new OgreDetourTileCache( mRecast ); mDetourTileCache->TileCacheBuild( mNavmeshEnts ); mDetourTileCache->drawNavMesh(); mNavMeshNode = (Ogre::SceneNode*)mSceneMgr->getRootSceneNode()->getChild("RecastSN"); mNavMeshNode->setVisible( true ); mObstacleMgr = new ObstacleManager( mSceneMgr, recastParams.getAgentRadius(), mDetourTileCache ); //---------------------------------------------------------------------- Ogre::Light* pointLight = mSceneMgr->createLight( "pointLight" ); pointLight->setType( Ogre::Light::LT_POINT ); pointLight->setPosition( Ogre::Vector3( 750, 5000, 750 ) ); pointLight->setDiffuseColour( 1.0, 1.0, 1.0 ); pointLight->setSpecularColour( 1.0, 1.0, 1.0 ); } //----------------------------------------------- void CreationState::exit( void ) { mOgre->mLog->logMessage( "Leaving CreationState..." ); if ( mSceneMgr ) { mSceneMgr->destroyCamera( mCamera ); mOgre->mRoot->destroySceneManager( mSceneMgr ); } mNavmeshEnts.clear(); mOgre->mTrayMgr->clearAllTrays(); mOgre->mTrayMgr->destroyAllWidgets(); mOgre->mTrayMgr->setListener( 0 ); } //----------------------------------------------- bool CreationState::pause( void ) { mOgre->mLog->logMessage( "Pausing CreationState..." ); return true; } //----------------------------------------------- void CreationState::resume() { mOgre->mLog->logMessage( "Resuming CreationState..." ); setViewport(); buildGUI(); mQuit = false; } //----------------------------------------------- void CreationState::moveCamera() { mCamera->moveRelative( mTranslateVector / 10 ); } //----------------------------------------------- void CreationState::getInput() { if ( mOgre->mKeyboard->isKeyDown( OIS::KC_A ) ) mTranslateVector.x = -mMoveScale; if ( mOgre->mKeyboard->isKeyDown( OIS::KC_D ) ) mTranslateVector.x = mMoveScale; if ( mOgre->mKeyboard->isKeyDown( OIS::KC_W ) ) mTranslateVector.z = -mMoveScale; if ( mOgre->mKeyboard->isKeyDown( OIS::KC_S ) ) mTranslateVector.z = mMoveScale; } //----------------------------------------------- bool CreationState::keyPressed( const OIS::KeyEvent &keyEventRef ) { if ( mOgre->mKeyboard->isKeyDown( OIS::KC_ESCAPE ) ) { pushAppState( findByName( "PauseState" ) ); return true; } //create obstacle if ( mOgre->mKeyboard->isKeyDown( OIS::KC_SPACE ) ) { Ogre::Vector3 rayHitPoint; if ( queryCursorPosition( rayHitPoint ) ) mObstacleMgr->createObstacle( rayHitPoint, mObstacleType ); setDebugVisibility( mDebugDraw ); } if ( mOgre->mKeyboard->isKeyDown( OIS::KC_Z ) ) { mWall = !mWall; } if ( mOgre->mKeyboard->isKeyDown( OIS::KC_V ) ) { setDebugVisibility( !mDebugDraw ); debugDrawBox->setChecked( !debugDrawBox->isChecked() ); } mOgre->keyPressed( keyEventRef ); return true; } //----------------------------------------------- bool CreationState::keyReleased( const OIS::KeyEvent &keyEventRef ) { mOgre->keyReleased( keyEventRef ); return true; } //----------------------------------------------- bool CreationState::mouseMoved(const OIS::MouseEvent &evt) { if ( mOgre->mTrayMgr->injectMouseMove( evt ) ) return true; if ( mRMouseDown ) { mCamera->yaw( Ogre::Degree( evt.state.X.rel * -0.1f ) ); mCamera->pitch( Ogre::Degree( evt.state.Y.rel * -0.1f ) ); } if( mWall ) { Ogre::Vector3 rayHitPoint; if ( queryCursorPosition( rayHitPoint ) ) mObstacleMgr->createObstacle( rayHitPoint, BOX ); setDebugVisibility( mDebugDraw ); } return true; } //----------------------------------------------- bool CreationState::mousePressed( const OIS::MouseEvent &evt, OIS::MouseButtonID id ) { if ( mOgre->mTrayMgr->injectMouseDown( evt, id ) ) return true; if ( id == OIS::MB_Left ) mLMouseDown = true; else if ( id == OIS::MB_Right ) mRMouseDown = true; //select obstacle if ( mLMouseDown ) { if( mCurrentObject ) mCurrentObject->showBoundingBox( false ); Ogre::Vector3 rayHitPoint; Ogre::MovableObject* rayHitObject; //select obstacle if ( queryCursorPosition( rayHitPoint, OBSTACLE_MASK, false, &rayHitObject ) ) { mCurrentObject = rayHitObject->getParentSceneNode(); mCurrentObject->showBoundingBox( true ); mCurrentIdentity = rayHitObject->getName(); showDynamicBotton( true ); } //move obstacle else if ( mCurrentObject && queryCursorPosition( rayHitPoint ) ) { mObstacleMgr->updatePosition( mCurrentIdentity, rayHitPoint ); setDebugVisibility( mDebugDraw ); mCurrentObject->showBoundingBox( false ); mCurrentObject = NULL; showDynamicBotton( false ); } } return true; } //----------------------------------------------- bool CreationState::mouseReleased( const OIS::MouseEvent &evt, OIS::MouseButtonID id ) { if ( mOgre->mTrayMgr->injectMouseUp( evt, id ) ) return true; if ( id == OIS::MB_Left ) mLMouseDown = false; else if ( id == OIS::MB_Right ) mRMouseDown = false; return true; } //----------------------------------------------- void CreationState::update( double timeSinceLastFrame ) { mFrameEvent.timeSinceLastFrame = timeSinceLastFrame; mOgre->mTrayMgr->frameRenderingQueued( mFrameEvent ); mDetourTileCache->handleUpdate( timeSinceLastFrame ); mMoveScale = 2000 * timeSinceLastFrame; mTranslateVector = Ogre::Vector3::ZERO; getInput(); moveCamera(); if(mQuit == true) { shutdown(); } } //----------------------------------------------- void CreationState::buttonHit(OgreBites::Button *button) { if( button->getName() == "SaveBtn" ) { mOgre->mLog->logMessage( "press SaveBtn" ); mObstacleMgr->saveObstaclesToFile(); } else if( button->getName() == "ClearBtn" ) { mOgre->mLog->logMessage( "press ClearBtn" ); mObstacleMgr->clearObstacles(); mCurrentObject = 0; //for dynamic button setDebugVisibility( mDebugDraw ); } else if( button->getName() == "LoadBtn" ) { mOgre->mLog->logMessage( "press LoadBtn" ); if( !mObstacleMgr->loadObstaclesFromFile() ) mOgre->mTrayMgr->showOkDialog( "error", "No any saved file" ); } else if( button->getName() == "DetailBtn" ) { mOgre->mLog->logMessage( "press DetailBtn" ); mObstacleMgr->showObstacleDetail(); } else if( button->getName() == "DeleteBtn" ) { mOgre->mLog->logMessage( "press DeleteBtn" ); mObstacleMgr->deleteObstacle( mCurrentIdentity ); mCurrentObject = NULL; showDynamicBotton( false ); } else if( button->getName() == "RotateBtn" ) { mOgre->mLog->logMessage( "press RotateBtn" ); mObstacleMgr->rotateObstacle( mCurrentIdentity, mCurrentObject->getOrientation() ); } } //----------------------------------------------- void CreationState::checkBoxToggled( OgreBites::CheckBox* box ) { if( box->getName() == "debugDrawBox" ) setDebugVisibility( box->isChecked() ? true : false ); else if( box->getName() == "logoBox" ) { if( logoBox->isChecked() ) mOgre->mTrayMgr->showLogo( OgreBites::TL_BOTTOMRIGHT ); else mOgre->mTrayMgr->hideLogo(); } else if( box->getName() == "frameStatesBox" ) { if( frameStatesBox->isChecked() ) mOgre->mTrayMgr->showFrameStats( OgreBites::TL_BOTTOMLEFT ); else mOgre->mTrayMgr->hideFrameStats(); } } //----------------------------------------------- void CreationState::itemSelected( OgreBites::SelectMenu* menu ) { if( menu->getName() == "obstacleMenu" ) switch( menu->getSelectionIndex() ) { case 0: mObstacleType = POT1; break; case 15: mObstacleType = POT2; break; case 1: mObstacleType = BOX; break; case 2: mObstacleType = TABLE1; break; case 3: mObstacleType = CHAIR1; break; } } //----------------------------------------------- bool CreationState::queryCursorPosition(Ogre::Vector3 &rayHitPoint, unsigned long queryflags, bool clipToNavmesh, Ogre::MovableObject **rayHitObject) { Ogre::Ray mouseRay = mOgre->mTrayMgr->getCursorRay( mCamera ); Ogre::MovableObject *hitObject; if ( rayQueryPointInScene( mouseRay, queryflags, rayHitPoint, &hitObject ) ) { if ( clipToNavmesh ) mRecast->findNearestPointOnNavmesh( rayHitPoint, rayHitPoint ); if ( rayHitObject ) *rayHitObject = hitObject; return true; } return false; } //----------------------------------------------- bool CreationState::rayQueryPointInScene( Ogre::Ray ray, unsigned long queryMask, Ogre::Vector3 &result, Ogre::MovableObject **foundMovable ) { mRayScnQuery = mSceneMgr->createRayQuery( ray, queryMask ); //mRayScnQuery->setRay( ray ); mRayScnQuery->setSortByDistance( true ); Ogre::RaySceneQueryResult& query_result = mRayScnQuery->execute(); Ogre::Real closest_distance = -1.0f; Ogre::Vector3 closest_result; Ogre::MovableObject *closest_movable; for ( size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++ ) { if( ( closest_distance >= 0.0f) && ( closest_distance < query_result[ qr_idx ].distance ) ) break; if ( ( query_result[ qr_idx ].movable != NULL ) && ( ( query_result[ qr_idx ].movable->getMovableType().compare( "Entity" ) == 0 ) || query_result[ qr_idx ].movable->getMovableType().compare( "ManualObject" ) == 0 ) ) { size_t vertex_count; size_t index_count; Ogre::Vector3 *vertices; unsigned long *indices; if ( query_result[ qr_idx ].movable->getMovableType().compare( "Entity" ) == 0 ) { Ogre::Entity *pentity = static_cast< Ogre::Entity* > ( query_result[ qr_idx ].movable ); InputGeom::getMeshInformation( pentity->getMesh(), vertex_count, vertices, index_count, indices, pentity->getParentNode()->_getDerivedPosition(), pentity->getParentNode()->_getDerivedOrientation(), pentity->getParentNode()->_getDerivedScale() ); } else { Ogre::ManualObject *pmanual = static_cast< Ogre::ManualObject* >( query_result[ qr_idx ].movable ); InputGeom::getManualMeshInformation( pmanual, vertex_count, vertices, index_count, indices, pmanual->getParentNode()->_getDerivedPosition(), pmanual->getParentNode()->_getDerivedOrientation(), pmanual->getParentNode()->_getDerivedScale() ); } bool new_closest_found = false; for (int i = 0; i < static_cast< int > ( index_count ); i += 3 ) { // check for a hit against this triangle std::pair< bool, Ogre::Real > hit = Ogre::Math::intersects( ray, vertices[ indices[ i ] ], vertices[ indices[ i + 1 ] ], vertices[ indices[ i + 2 ] ], true, false ); // if it was a hit check if its the closest if ( hit.first ) if ( ( closest_distance < 0.0f ) || ( hit.second < closest_distance ) ) { closest_distance = hit.second; new_closest_found = true; } } delete[] vertices; delete[] indices; if ( new_closest_found ) { closest_result = ray.getPoint( closest_distance ); if( query_result[ qr_idx ].movable != NULL ) closest_movable = query_result[ qr_idx ].movable; } } } if ( closest_distance >= 0.0f ) { result = closest_result; *foundMovable = closest_movable; return true; } else return false; } //----------------------------------------------- void CreationState::showDynamicBotton( bool whether_show ) { if( whether_show ) { delete_btn->show(); rotate_btn->show(); mOgre->mTrayMgr->moveWidgetToTray( delete_btn, OgreBites::TL_BOTTOM, 0 ); mOgre->mTrayMgr->moveWidgetToTray( rotate_btn, OgreBites::TL_BOTTOM, 0 ); } else { delete_btn->hide(); rotate_btn->hide(); mOgre->mTrayMgr->moveWidgetToTray( delete_btn, OgreBites::TL_NONE, 0 ); mOgre->mTrayMgr->moveWidgetToTray( rotate_btn, OgreBites::TL_NONE, 0 ); } } //----------------------------------------------- void CreationState::setDebugVisibility( bool visible ) { mDebugDraw = visible; mNavMeshNode->setVisible( visible ); }
183d7f1ebc3ba70d7ca087de2d8178166ca7f57b
5f1e63a3c044c1ef391d43167b236f426172d35b
/solutions/0322.coin-change/coin-change.cpp
838da1de70fd9aac523b22e7c769f8cde7911df8
[ "MIT" ]
permissive
mjl20130901/LeetCode-CPP-Solutions
3a1cc5a93ad6efbd95b95594783ec5d456572d7b
57cac895a0747545e63f79a28619610ff301c2d9
refs/heads/master
2020-07-07T11:45:22.712961
2019-08-18T08:55:00
2019-08-18T08:55:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
cpp
coin-change.cpp
/* * @lc app=leetcode id=322 lang=cpp * * [322] Coin Change * * https://leetcode.com/problems/coin-change/description/ * * algorithms * Medium (31.16%) * Likes: 1986 * Dislikes: 78 * Total Accepted: 218.6K * Total Submissions: 700.9K * Testcase Example: '[1,2,5]\n11' * * You are given coins of different denominations and a total amount of money * amount. Write a function to compute the fewest number of coins that you need * to make up that amount. If that amount of money cannot be made up by any * combination of the coins, return -1. * * Example 1: * * * Input: coins = [1, 2, 5], amount = 11 * Output: 3 * Explanation: 11 = 5 + 5 + 1 * * Example 2: * * * Input: coins = [2], amount = 3 * Output: -1 * * * Note: * You may assume that you have an infinite number of each kind of coin. * */ #include <algorithm> #include <vector> using namespace std; class Solution { public: int coinChange(vector<int> &coins, int amount) { vector<int> dp(amount + 1, INT_MAX - 1); dp.front() = 0; for (int i = 1; i <= amount; ++i) for (int coin : coins) if (i >= coin) dp[i] = min(dp[i], dp[i - coin] + 1); return dp.back() == INT_MAX - 1 ? -1 : dp.back(); } };
e198cc6cbb98cfd4a18bb679760d92bb875ce306
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/hackathon/atlas_builder_release/pointcloud_atlas_builder_plugin/dialog_pointcloudatlas_build_atlas.cpp
ae6490f76a27bd1c2c9a9ebf318b1ec3cf859abb
[ "MIT" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
7,613
cpp
dialog_pointcloudatlas_build_atlas.cpp
/* * Copyright (c)2011 Fuhui Long (Janelia Farm, Howard Hughes Medical Institute). * All rights reserved. % Jan 20, 2012 */ #include "dialog_pointcloudatlas_build_atlas.h" #include <QtGui> #include <QFileInfo> #include <QFile> #include <QFileDialog> // ----------------------------------- // functions of the input interface // ----------------------------------- PointCloudAtlas_BuildAtlasDialog::PointCloudAtlas_BuildAtlasDialog(apoAtlasBuilderInfo &p) { create(p); } void PointCloudAtlas_BuildAtlasDialog::fetchData(apoAtlasBuilderInfo &p) { p.linkerFileName = lineEdit_linker_file->text().trimmed(); p.regTargetFileName = lineEdit_ref_file->text().trimmed(); p.refMarkerCptCellNameFile = lineEdit_refmarkercpt_file->text().trimmed(); p.ratio = atof(lineEdit_stack_ratio->text().trimmed().toStdString().c_str()); p.forceAddCellFileName = lineEdit_forceadd_celllist_file->text().trimmed(); if (radioButton_saveregtag->isChecked()==true) p.saveRegDataTag = 1; else p.saveRegDataTag = 0; } void PointCloudAtlas_BuildAtlasDialog::create(apoAtlasBuilderInfo &p) { setupUi(this); //default values and events lineEdit_linker_file->setText(""); lineEdit_ref_file->setText(""); lineEdit_forceadd_celllist_file->setText(""); lineEdit_stack_ratio->setText("0"); if (p.saveRegDataTag == true) radioButton_saveregtag->setChecked(true); else radioButton_saveregtag->setChecked(false); // select the input linker file connect(lineEdit_linker_file, SIGNAL(textChanged(const QString &)), this, SLOT(change_linker_file(const QString &))); connect(pushButton_linker_file, SIGNAL(clicked()), this, SLOT(select_linker_file())); // select the registration target file connect(lineEdit_ref_file, SIGNAL(textChanged(const QString &)), this, SLOT(change_target_file(const QString &))); connect(pushButton_ref_file, SIGNAL(clicked()), this, SLOT(select_target_file())); // select the reference marker control point file connect(lineEdit_refmarkercpt_file, SIGNAL(textChanged(const QString &)), this, SLOT(change_refmarkercpt_file(const QString &))); connect(pushButton_refmarkercpt_file, SIGNAL(clicked()), this, SLOT(select_refmarkercpt_file())); // select the force added cell file connect(lineEdit_forceadd_celllist_file, SIGNAL(textChanged(const QString &)), this, SLOT(change_forceadded_cell_file(const QString &))); connect(pushButton_forceadd_celllist_file, SIGNAL(clicked()), this, SLOT(select_forceadded_cell_file())); // button for ending the window connect(pushButton_ok, SIGNAL(clicked()), this, SLOT(accept())); //this will get a result code "Accepted" connect(pushButton_cancel, SIGNAL(clicked()), this, SLOT(reject())); //enable or not the finish button check_completeness_of_info(); } void PointCloudAtlas_BuildAtlasDialog::change_linker_file(const QString & s) { QFileInfo info(s.trimmed()); if (!s.trimmed().isEmpty() && (!info.exists() || !info.isFile())) label_linker_file->setText("<font color=\"red\">Select a linker file: </font>"); //FL 20091027 else label_linker_file->setText("Select a linker file: "); //FL 20091027 //enable or not the finish button check_completeness_of_info(); } void PointCloudAtlas_BuildAtlasDialog::select_linker_file() { QString s; QFileInfo info(lineEdit_linker_file->text().trimmed()); s = QFileDialog::getOpenFileName(0, tr("Select a linker file:"), info.dir().path()); if (!s.isEmpty()) { lineEdit_linker_file->setText(s); } } void PointCloudAtlas_BuildAtlasDialog::change_target_file(const QString & s) { QFileInfo info(s.trimmed()); if (!s.trimmed().isEmpty() && (!info.exists() || !info.isFile())) label_ref_file->setText("<font color=\"red\">Select a target file for registration:</font>"); //FL 20091027 else label_ref_file->setText("Select a target file for registration:"); //FL 20091027 //enable or not the finish button check_completeness_of_info(); } void PointCloudAtlas_BuildAtlasDialog::select_target_file() { QString s; QFileInfo info(lineEdit_ref_file->text().trimmed()); s = QFileDialog::getOpenFileName(0, tr("Select a target file for registration:"), info.dir().path()); if (!s.isEmpty()) { lineEdit_ref_file->setText(s); } } void PointCloudAtlas_BuildAtlasDialog::change_forceadded_cell_file(const QString & s) { QFileInfo info(s.trimmed()); if (!s.trimmed().isEmpty() && (!info.exists() || !info.isFile())) label_forceadd_celllist_file->setText("<font color=\"red\">Select force added cell file:</font>"); //FL 20091027 else label_forceadd_celllist_file->setText("Select force added cell file:"); //FL 20091027 //enable or not the finish button check_completeness_of_info(); } void PointCloudAtlas_BuildAtlasDialog::select_forceadded_cell_file() { QString s; QFileInfo info(lineEdit_forceadd_celllist_file->text().trimmed()); s = QFileDialog::getOpenFileName(0, tr("Select force added cell file:"), info.dir().path()); if (!s.isEmpty()) { lineEdit_forceadd_celllist_file->setText(s); } } void PointCloudAtlas_BuildAtlasDialog::change_refmarkercpt_file(const QString & s) { QFileInfo info(s.trimmed()); if (!s.trimmed().isEmpty() && (!info.exists() || !info.isFile())) label_refmarkercpt_file->setText("<font color=\"red\">Reference marker control point file for registration: </font>"); else label_refmarkercpt_file->setText("Reference marker control point file for registration: "); //enable or not the finish button check_completeness_of_info(); } void PointCloudAtlas_BuildAtlasDialog::select_refmarkercpt_file() { QString s; QFileInfo info(lineEdit_refmarkercpt_file->text().trimmed()); s = QFileDialog::getOpenFileName(0, tr("Select the reference marker control point file for registration:")); if (!s.isEmpty()) { lineEdit_refmarkercpt_file->setText(s); } } void PointCloudAtlas_BuildAtlasDialog::check_completeness_of_info() { bool b_info_complete=true; QFileInfo info; if (lineEdit_linker_file->text().trimmed().isEmpty()) { b_info_complete=false; label_linker_file->setText("<font color=\"red\">Select a linker file:</font>"); //FL 20091026 } else { label_linker_file->setText("<font color=\"black\">Select a linker file:</font>"); //FL 20091026 } if (lineEdit_ref_file->text().trimmed().isEmpty()) { b_info_complete=false; label_ref_file->setText("<font color=\"red\">Select a target file for registration:</font>"); } else { label_ref_file->setText("<font color=\"black\">Select a target file for registration:</font>"); } if (lineEdit_refmarkercpt_file->text().trimmed().isEmpty()) { b_info_complete=false; label_refmarkercpt_file->setText("<font color=\"red\">Reference marker control point file for registration:</font>"); } else { label_refmarkercpt_file->setText("<font color=\"black\">Reference marker control point file for registration:</font>"); } if (lineEdit_forceadd_celllist_file->text().trimmed().isEmpty()) { b_info_complete=false; label_forceadd_celllist_file->setText("<font color=\"red\">Select force added cell file:</font>"); } else { label_forceadd_celllist_file->setText("<font color=\"black\">Select force added cell file:</font>"); } printf("b_info_complete=%d\n", b_info_complete); //set the two push button states pushButton_ok->setEnabled(b_info_complete); }
7ce986510e5a8a65c34cd4ee84ca617a3c38323a
3b379f81604986b5768a4420632ed1c27ce98242
/leetcode216.cpp
90355c5c9ac2b8700fce5cfffc8481137331e477
[ "MIT" ]
permissive
SJTUGavinLiu/Leetcodes
a7866e945d5699be40012f527d2080047582b172
99d4010bc34e78d22e3c8b6436e4489a7d1338da
refs/heads/master
2021-07-24T03:26:56.258953
2020-07-19T03:59:09
2020-07-19T03:59:09
199,461,174
0
0
null
null
null
null
UTF-8
C++
false
false
941
cpp
leetcode216.cpp
class Solution { vector<vector<int>> res; vector<int> tmp; public: bool helper(int beg, int remain, int num) { //cout << beg << '\t' << remain << '\t' << num << endl; if((19-num)*num < 2 * remain) return true; if( (9-beg+1) < num) return false; if(num == 1) { if(remain < beg) return false; tmp.push_back(remain); res.push_back(tmp); tmp.pop_back(); return true; } while(1) { tmp.push_back(beg); if(!helper(beg+1,remain-beg, num-1)) { tmp.pop_back(); break; } tmp.pop_back(); beg++; } return true; } vector<vector<int>> combinationSum3(int k, int n) { if(k > 9 || n > 45) return {}; helper(1, n, k); return res; } };
5169137a1e696001941e35920ea63d50740b4ec4
8f562df81e7c5adef7762f8e24eff85724812c20
/include/DebugProtocolServer.hpp
be950cafbed40b68e27021a3a2d895d4688f1777
[ "MIT" ]
permissive
advpl/vscode-debug-protocol-cxx
f2b9b57d8c3c3e10c9342b30d6f3fa202144eb56
f0221e9c13b3f1a01774eb1edc3348cd18261630
refs/heads/master
2022-08-04T12:34:28.491304
2022-07-26T19:56:18
2022-07-26T19:56:18
106,063,297
2
2
MIT
2020-02-05T13:49:54
2017-10-07T01:26:31
C++
UTF-8
C++
false
false
476
hpp
DebugProtocolServer.hpp
#ifndef DEBUG_PROTOCOL_SERVER_H #define DEBUG_PROTOCOL_SERVER_H #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/utility/string_ref.hpp> #include <iostream> #include <chrono> #include <thread> #include "JSONRPCDispatcher.hpp" #include "JSONOutput.hpp" namespace vscode_debug { void run (std::istream &input, JSONOutput &Out, JSONRPCDispatcher &Dispatcher,bool &IsDone); } #endif
431ae90e364fc08c2bcd119e8932df2d0e337346
197669277d60179aab8a52046f7a589a651e7709
/P2/src/nBitSubtractor/main.cpp
c77b32263640f1a2fe4b6a2d0368505815556e9b
[]
no_license
jamesstocktonj1/AdvancedProgramming-1204
6f14f2ee5e7f36b666c0e8de829589c73a495525
2563e0226d79f3b32ce3e2a93d77da240766b9eb
refs/heads/main
2023-05-08T21:38:51.501001
2021-05-16T11:42:26
2021-05-16T11:42:26
367,864,377
1
0
null
null
null
null
UTF-8
C++
false
false
2,781
cpp
main.cpp
#include <iostream> #include <math.h> using namespace std; #define N 8 bool AND(bool a, bool b); bool OR(bool a, bool b); bool XOR(bool a, bool b); void printState(bool n); void printBin(bool n); void printByte(bool *n); bool readBit(void); void readNum(bool *bin); bool readSymbol(void); void halfAdder(bool a, bool b, bool &s, bool &c); void fullAdder(bool a, bool b, bool Cin, bool &s, bool &c); void convertTwosComplement(bool *bin); int main() { bool a[N]; bool b[N]; bool c[N + 1] = {false, }; bool sum[N]; bool carry; cout << "Input number 1: "; readNum(a); cout << "Number 1: "; printByte(a); cout << endl; cout << "Input number 2: "; readNum(b); cout << "Number 2: "; printByte(b); cout << endl; cout << "Input Carry: "; c[0] = readBit(); cout << "Input Sign: "; if(readSymbol()) { convertTwosComplement(b); } cout << "Inverted B: "; printByte(b); for(int i=0; i<N; i++) { fullAdder(a[i], b[i], c[i], sum[i], c[i+1]); } cout << "\n\nSum: "; printByte(sum); cout << endl; cout << "Carry: "; printBin(c[N]); cout << endl; return 1; } void printState(bool n) { cout << ((n) ? "True" : "False") << endl; } void printBin(bool n) { cout << ((n) ? "1" : "0"); } void printByte(bool *n) { for(int i=1; i<=N; i++) { printBin(n[N - i]); } } bool readBit() { char buf; cin >> buf; if(buf == '1') { return true; } else { return false; } } //modified for 2s complement void readNum(bool *bin) { int num; cin >> num; bool neg = (num < 0); for(int i=0; i<N-1; i++) { bin[i] = num % 2; num = num / 2; } if(neg) { convertTwosComplement(bin); } else { bin[N-1] = false; } } bool readSymbol() { char sym; cin >> sym; if(sym == '-') { return true; } else { return false; } } void convertTwosComplement(bool *bin) { bool cr[N+1]; bool n1[N] = {1, 0, 0, 0, 0, 0, 0, 0}; bool temp[N]; //invert all bits for(int i=0; i<N; i++) { bin[i] = !bin[i]; } //add 1 to complement for(int i=0; i<N; i++) { fullAdder(bin[i], n1[i], cr[i], temp[i], cr[i+1]); bin[i] = temp[i]; } } bool AND(bool a, bool b) { return a && b; } bool OR(bool a, bool b) { return a || b; } bool XOR(bool a, bool b) { return (a != b); } void halfAdder(bool a, bool b, bool &s, bool &c) { s = XOR(a, b); c = AND(a, b); } void fullAdder(bool a, bool b, bool Cin, bool &s, bool &c) { bool c1, c2, s1; halfAdder(a, b, s1, c1); halfAdder(Cin, s1, s, c2); c = OR(c1, c2); }
c6a854b5ee62409207b502b1641f0c3642504487
82af875dd6ae85907c4bceed23c872e4f5c42aa6
/Code/Try/096/096/096.cpp
b0bd4a32dfd4eeacba3c6f428295a1de04e348b6
[]
no_license
L41homebisee/LearnCpp_LanguageWithZeroFoundationMRKJ
74cb77c4f79fcf6d5cd0326222b875a11dfaca4b
aae958412c6796a4a8ea385c88d4b13c6047c102
refs/heads/master
2023-03-17T16:09:17.047090
2021-03-02T13:19:26
2021-03-02T13:19:26
null
0
0
null
null
null
null
GB18030
C++
false
false
755
cpp
096.cpp
// Try.cpp : Defines the entry point for the console application. // #include <iostream> /* 假设数字0表示灯泡没亮,数字1表示灯泡亮着,有6个灯泡排列成一行组成一个以为数 组a{1,0,0,1,0,0},查找倒数第一个亮着的灯泡位置,并显示该灯泡前一个灯泡是否亮着。 */ using namespace std; int main(int argc, char* argv[]) { int a[6] = { 1,0,0,1,0,0 }; int indexLast; for (indexLast = 5; indexLast >= 0; indexLast--) { if (a[indexLast] == 1) { break; } } cout << "倒数第一个亮着的灯泡为:" << indexLast << endl; int *p = &a[indexLast]; p--; if (*p == 1) { cout << "前一个灯泡亮着" << endl; } else { cout << "前一个灯泡没亮" << endl; } return 0; }