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
c4c6008a2042da56baa6d95df5fa2b043e8bfe39
5ee245f619ab0a8eda1bf7033340879c619808c4
/ALL/Camera.cpp
87b3de11e9191f14e03ba96b62ae1497df0d8144
[]
no_license
Tekh-ops/opengl-3d-engine
a55a9debd556cb469cf13b57d5dd342a9d48e4a0
9d3d3125630300c12da9dc3b5ec6500b473e715f
refs/heads/master
2021-12-06T06:02:55.241551
2015-10-04T20:42:39
2015-10-04T20:42:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,169
cpp
Camera.cpp
#include "Camera.h" Camera::Camera(glm::vec3 position, glm::vec3 direction) { //Create the camera direction and position this->direction = direction; this->position = position; //Create the mouse x and y xPos = 0; yPos = 0; //Create the viewing angles EulerAngle angles = EulerAngle(); angles.toAngles(this->direction - this->position); this->pitch = angles.getPitch(); this->yaw = angles.getYaw(); this->roll = 0; fprintf(stdout, "Pitch: %f, Yaw: %f", pitch, yaw); //Set the speed variables speed = 3; sensitivity = 0.02; //Create the projection variables fov = 45.0; minDistance = 0.1; maxDistance = 100.0; } Camera::Camera(glm::vec3 position, float yaw, float pitch, float roll) { //Create the camera direction and position direction = glm::vec3(0, 0, 0); this->position = position; //Create the mouse x and y xPos = 0; yPos = 0; //Create the viewing angles this->yaw = yaw; this->pitch = pitch; this->roll = 0; //Set the speed variables speed = 3; sensitivity = 0.02; //Create the projection variables fov = 45.0; minDistance = 0.1; maxDistance = 100.0; } Camera::Camera(glm::vec3 position) { //Create the camera direction and position direction = glm::vec3(0, 0, 0); this->position = position; //Create the mouse x and y xPos = 0; yPos = 0; //Create the viewing angles pitch = 0; yaw = 90; //Set the speed variables speed = 3; sensitivity = 0.02; //Create the projection variables fov = 45.0; minDistance = 0.1; maxDistance = 100.0; } Camera::Camera() { //Create the camera direction and position direction = glm::vec3(0, 0, 0); position = glm::vec3(0, 0, 0); //Create the mouse x and y xPos = 0; yPos = 0; //Create the viewing angles pitch = 45; yaw = 135; //Set the speed variables speed = 3; sensitivity = 0.02; //Create the projection variables fov = 45.0; minDistance = 0.1; maxDistance = 100.0; } Camera::~Camera() { } //Calculate the view matrix from the mouse positions void Camera::calculateViewMatrix(Window window) { //Get the mouse positions xPos, yPos; glfwGetCursorPos(window.getWindow(), &xPos, &yPos); //Reset the mouse position int width, height; glfwGetWindowSize(window.getWindow(), &width, &height); glfwSetCursorPos(window.getWindow(), width / 2, height / 2); //Calculate the change in the x and y position double deltaXPos = xPos - (width / 2); double deltaYPos = yPos - (height / 2); //Calculate the pitch and yaw values from the change in x and y pitch += deltaYPos * sensitivity; yaw += deltaXPos * sensitivity; //Create the EulerAngles object to convert the angles into a direction vector EulerAngle angles = EulerAngle(yaw, pitch, 0); //Check the pitch and yaw values and stop them from inversing angles.constrain(); //Get the direction vector from the angles direction = angles.toVector(); //Movement speed and perpendicular vector to direction vector glm::vec3 speed = glm::vec3(0.1, 0.1, 0.1); glm::vec3 right = glm::cross(direction, glm::vec3(0, 1, 0)); //Calculate the position and movement if (glfwGetKey(window.getWindow(), GLFW_KEY_W) == GLFW_PRESS) { position -= (direction * speed); } if (glfwGetKey(window.getWindow(), GLFW_KEY_S) == GLFW_PRESS) { position += (direction * speed); } if (glfwGetKey(window.getWindow(), GLFW_KEY_D) == GLFW_PRESS) { position -= (right * speed); } if (glfwGetKey(window.getWindow(), GLFW_KEY_A) == GLFW_PRESS) { position += (right * speed); } //Create the view matrix from the position and direction view = glm::lookAt( position, position - direction, glm::vec3(0, 1, 0) ); } //Create the projection matrix void Camera::calculateProjectionMatrix(Window window) { int width, height; glfwGetWindowSize(window.getWindow(), &width, &height); //Calculate the projection projection = glm::perspective(fov, (float)width / (float)height, minDistance, maxDistance); } //Return the view matrix glm::mat4 Camera::getViewMatrix() { return this->view; } //Return the projection matrix glm::mat4 Camera::getProjectionMatrix() { return this->projection; } //Set the field of view for the camera void Camera::setFOV(int fov) { this->fov = fov; }
ffd9d54ce9e366ce52bbc475db514ed90b78ec08
4f3f59031a782e7a9c2a9e95ab39890b234968a2
/source/mutableSources32/warps/dsp/oscillator.cc
2278e62f1d67d7dceda4f532c19faaa587218b74
[ "MIT" ]
permissive
joelyoungblood/vb.mi-dev
23c3ec81fb1dbd22e92af8cee3833835862b4949
af141104699fba2aa35938f33300f5e3b42dffb4
refs/heads/master
2023-07-13T12:24:34.106004
2021-08-22T18:06:01
2021-08-22T18:06:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,862
cc
oscillator.cc
// Copyright 2014 Emilie Gillet. // // Author: Emilie Gillet (emilie.o.gillet@gmail.com) // // 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. // // See http://creativecommons.org/licenses/MIT/ for more information. // // ----------------------------------------------------------------------------- // // Oscillator. #include "warps/dsp/oscillator.h" #include "stmlib/dsp/parameter_interpolator.h" #include "stmlib/utils/random.h" namespace warps { using namespace stmlib; const float kToFloat = 1.0f / 4294967296.0f; const float kToUint32 = 4294967296.0f; void Oscillator::Init(float sample_rate) { one_hertz_ = 1.0f / sample_rate; next_sample_ = 0.0f; phase_ = 0.0f; phase_increment_ = 100.0f * one_hertz_; hp_state_ = 0.0f; lp_state_ = 0.0f; lp_state_tri_ = 0.0f; next_sample_tri_ = 0.0f; phase_tri_ = 0.0f; high_ = false; external_input_level_ = 0.0f; filter_.Init(); } float Oscillator::Render( OscillatorShape shape, float note, float* modulation, float* out, size_t size) { return (this->*fn_table_[shape])(note, modulation, out, size); } float Oscillator::RenderSine( float note, float* modulation, float* out, size_t size) { float phase = phase_; ParameterInterpolator phase_increment( &phase_increment_, note * one_hertz_, //midi_to_increment(note), //vb, re-interpret note as frequency size); while (size--) { phase += phase_increment.Next(); if (phase >= 1.0f) { phase -= 1.0f; } uint32_t modulated_phase = static_cast<uint32_t>(phase * kToUint32); modulated_phase += static_cast<int32_t>(*modulation++ * 0.5f * kToUint32); uint32_t integral = modulated_phase >> 22; float fractional = static_cast<float>(modulated_phase << 10) * kToFloat; float a = lut_sin[integral]; float b = lut_sin[integral + 1]; *out++ = a + (b - a) * fractional; } phase_ = phase; return 1.0f; } // vb, add a separate render function for triangle waves float Oscillator::RenderPolyblepTri( float note, float* modulation, float* out, size_t size) { float phase = phase_tri_; ParameterInterpolator phase_increment( &phase_increment_, note * one_hertz_, size); float next_sample = next_sample_tri_; bool high = high_; float lp_state = lp_state_tri_; while (size--) { float this_sample = next_sample; next_sample = 0.0f; float modulated_increment = phase_increment.Next() * (1.0f + *modulation++); if (modulated_increment <= 0.0f) { modulated_increment = 1.0e-7; } phase += modulated_increment; if (!high && phase >= 0.5f) { float t = (phase - 0.5f) / modulated_increment; this_sample += ThisBlepSample(t); next_sample += NextBlepSample(t); high = true; } if (phase >= 1.0f) { phase -= 1.0f; float t = phase / modulated_increment; this_sample -= ThisBlepSample(t); next_sample -= NextBlepSample(t); high = false; } const float integrator_coefficient = modulated_increment * 0.0625f; next_sample += phase < 0.5f ? 0.0f : 1.0f; this_sample = 128.0f * (this_sample - 0.5f); lp_state += integrator_coefficient * (this_sample - lp_state); *out++ = lp_state; } high_ = high; phase_tri_ = phase; next_sample_tri_ = next_sample; lp_state_tri_ = lp_state; return 1.0f; } template<OscillatorShape shape> float Oscillator::RenderPolyblep( float note, float* modulation, float* out, size_t size) { float phase = phase_; ParameterInterpolator phase_increment( &phase_increment_, note * one_hertz_, //midi_to_increment(note), //vb, re-interpret note as frequency size); float next_sample = next_sample_; // bool high = high_; float lp_state = lp_state_; float hp_state = hp_state_; while (size--) { float this_sample = next_sample; next_sample = 0.0f; float modulated_increment = phase_increment.Next() * (1.0f + *modulation++); if (modulated_increment <= 0.0f) { modulated_increment = 1.0e-7; } phase += modulated_increment; // if (shape == OSCILLATOR_SHAPE_TRIANGLE) { // if (!high && phase >= 0.5f) { // float t = (phase - 0.5f) / modulated_increment; // this_sample += ThisBlepSample(t); // next_sample += NextBlepSample(t); // high = true; // } // if (phase >= 1.0f) { // phase -= 1.0f; // float t = phase / modulated_increment; // this_sample -= ThisBlepSample(t); // next_sample -= NextBlepSample(t); // high = false; // } // const float integrator_coefficient = modulated_increment * 0.0625f; // next_sample += phase < 0.5f ? 0.0f : 1.0f; // this_sample = 128.0f * (this_sample - 0.5f); // lp_state += integrator_coefficient * (this_sample - lp_state); // *out++ = lp_state; // } else { if (phase >= 1.0f) { phase -= 1.0f; float t = phase / modulated_increment; this_sample -= ThisBlepSample(t); next_sample -= NextBlepSample(t); } next_sample += phase; if (shape == OSCILLATOR_SHAPE_SAW) { this_sample = this_sample * 2.0f - 1.0f; // Slight roll-off of high frequencies - prevent high components near // 48kHz that are not eliminated by the upsampling filter. lp_state += 0.3f * (this_sample - lp_state); *out++ = lp_state; } else { lp_state += 0.25f * ((hp_state - this_sample) - lp_state); *out++ = 4.0f * lp_state; hp_state = this_sample; } // } } // high_ = high; phase_ = phase; next_sample_ = next_sample; lp_state_ = lp_state; hp_state_ = hp_state; return shape == OSCILLATOR_SHAPE_PULSE ? 0.025f / (0.0002f + phase_increment_) : 1.0f; } float Oscillator::Duck( const float* internal, const float* external, float* destination, size_t size) { float level = external_input_level_; for (size_t i = 0; i < size; ++i) { float error = external[i] * external[i] - level; level += ((error > 0.0f) ? 0.01f : 0.0001f) * error; float internal_gain = 1.0f - 32.0f * level; if (internal_gain <= 0.0f) { internal_gain = 0.0f; } destination[i] = external[i] + internal_gain * (internal[i] - external[i]); } external_input_level_ = level; return level; } float Oscillator::RenderNoise( float note, float* modulation, float* out, size_t size) { for (size_t i = 0; i < size; ++i) { float noise = static_cast<float>(stmlib::Random::GetWord()) * kToFloat; out[i] = 2.0f * noise - 1.0f; } Duck(out, modulation, out, size); // filter_.set_f_q<FREQUENCY_ACCURATE>(midi_to_increment(note) * 4.0f, 1.0f); filter_.set_f_q<FREQUENCY_ACCURATE>(note * one_hertz_ * 4.0f, 1.0f); filter_.Process<FILTER_MODE_LOW_PASS>(out, out, size); // vb boost output a little for low cf values float boost = 1.0f / (note * 0.001); CONSTRAIN(boost, 1.0f, 20.0f); return boost; //1.0f; } /* static */ Oscillator::RenderFn Oscillator::fn_table_[] = { &Oscillator::RenderSine, &Oscillator::RenderPolyblepTri, //&Oscillator::RenderPolyblep<OSCILLATOR_SHAPE_TRIANGLE>, &Oscillator::RenderPolyblep<OSCILLATOR_SHAPE_SAW>, &Oscillator::RenderPolyblep<OSCILLATOR_SHAPE_PULSE>, &Oscillator::RenderNoise, }; } // namespace warps
549c9c66671ec5efc5afdedf84a8c287ce590436
11e97f87deb25babb4a32c80941e7ff4e476c92a
/HVT/HRT_430T/LotUnit.cpp
f96bd4b8ef6fcf1198a95a390de730c83d75f7d6
[]
no_license
xhyangxianjun/Builder6-program
b9d03d98658db5a5a8cf1586210a373bc391dc48
a12d811d7a5fa3dba6d3e8c05989a41cb89783de
refs/heads/master
2022-04-03T00:25:47.274355
2019-09-19T08:26:56
2019-09-19T08:26:56
null
0
0
null
null
null
null
UHC
C++
false
false
45,366
cpp
LotUnit.cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include <stdio.h> #include "LotUnit.h" #include "SLogUnit.h" #include "UserIni.h" #include "UserFile.h" #include "OptionMan.h" #include "Timer.h" #include "DataMan.h" #include "SortingTool.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #define SPC_FOLDER "d:\\Spc\\" AnsiString g_sLotNo[MAX_LOT_CNT] ; void PushLotNo (AnsiString _sLotNo) { for(int i = 0 ; i < MAX_LOT_CNT ; i++) { if(g_sLotNo[i] == "") { g_sLotNo[i] = _sLotNo ; return; } } } AnsiString GetLotNo (void ) //참조만. { return g_sLotNo[0] ; } AnsiString PopLotNo (void ) { AnsiString sLotNo = g_sLotNo[0] ; int i; for(i = 0 ; i < MAX_LOT_CNT - 1 ; i++) { g_sLotNo[i] = g_sLotNo[i+1] ; } g_sLotNo[i] = ""; return sLotNo ; } void DeleteLotNo(AnsiString _sLotNo) { for(int i = 0 ; i < MAX_LOT_CNT ; i++) { if(_sLotNo == g_sLotNo[i]){ g_sLotNo[i] = "" ; for(int j = i ; j < MAX_LOT_CNT - 1; i++) { g_sLotNo[j] = g_sLotNo[j+1] ; } } } } void DeleteLotNo(int _iLotNo) { for(int i = _iLotNo ; i < MAX_LOT_CNT - 1 ; i++) { g_sLotNo[i] = g_sLotNo[i+1] ; } } void DeleteLotNoAll (void ) { for(int i = 0 ; i < MAX_LOT_CNT ; i++) { g_sLotNo[i] = ""; } } int GetLotCnt(void) { int i ; for(i = 0 ; i < MAX_LOT_CNT ; i++) { if(g_sLotNo[i] == "") break ; } return i ; } CLot LT; __fastcall CLot::CLot(void) { //Init. Flag. m_bLotOpen = false; //Init. Buffer. ClearLotInfo(); ClearDayInfo(); LoadLotInfo(); LoadDayInfo(); if(!FileExists(LOG_FOLDER)) CreateDir(LOG_FOLDER); } __fastcall CLot::~CLot(void) { SaveLotInfo(); SaveDayInfo(); // Trace("",""); } void __fastcall CLot::ClearLotInfo(void) { memset(&LotInfo , 0 , sizeof(SLotInfo)); for(int i = 0 ; i < MAX_LOT_CNT ; i++) g_sLotNo[i] == ""; } void __fastcall CLot::ClearDayInfo(void) { memset(&DayInfo , 0 , sizeof(SDayInfo)); } //Lot Processing. void __fastcall CLot::LotOpen (AnsiString _sLotNo , AnsiString _sJobFile , AnsiString _sOperator) { AnsiString sTempJobFile = LotInfo.sJobFile ; AnsiString sTempOperator = LotInfo.sOperator ; ClearLotInfo(); LotInfo.sLotNo = _sLotNo ; if(_sJobFile == "" ) LotInfo.sJobFile = sTempJobFile ; else LotInfo.sJobFile = _sJobFile ; if(_sOperator == "" ) LotInfo.sOperator = sTempOperator ; else LotInfo.sOperator = _sOperator ; LotInfo.iCrntLotNo = 0 ; LotInfo.dStartTime = Now(); //for(int i = 0 ; i < MAX_ARAY ; i++) { // DM.ARAY[i].SetStat(csEmpty) ; //} //Set Lot Open Flag. m_bLotOpen = true ; } //Lot Processing. /*void __fastcall CLot::LotOpen (AnsiString _sLotNo) { LotInfo.sLotNo = _sLotNo ; //Set Lot Open Flag. m_bLotOpen = true ; }*/ AnsiString __fastcall CLot::GetLotNo () { return LotInfo.sLotNo ; } void __fastcall CLot::LotEnd (void) { //Check already opened Lot. if (!m_bLotOpen) return; //Set EndTime. LotInfo.dEndTime = Now(); //Reset Lot Flag. m_bLotOpen = false; m_bLotEnd = true ; // WriteLotLog(); //Check Retest Mode. STL._iBinCnt = 0 ; //빈 카운트 0번으로 셋팅함. Trace("SEQ","Lot Finished" ); FM_MsgOk("Confirm" , "LOT IS FINISHED" ); m_bLotEnd = false ; } void __fastcall CLot::DispLotInfo(TPanel * _pnLotNo , TPanel * _pnJobFile , TPanel * _pnOperator , TPanel * _pnStartTime, TPanel * _pnEndTime , TPanel * _pnRunTime , TPanel * _pnIdleTime , TPanel * _pnJamTime , TPanel * _pnTotalTime, TPanel * _pnStrpUPEH , TPanel * _pnChipUPEH , TPanel * _pnStrpUPH , TPanel * _pnChipUPH , TPanel * _pnWorkStrp , TPanel * _pnWorkChip , TPanel * _pnFailChip ) { TDateTime tTemp ; if(_pnLotNo ) _pnLotNo -> Caption = LotInfo.sLotNo ;//g_sLotNo[0] ; if(_pnJobFile ) _pnJobFile -> Caption = LotInfo.sJobFile ; if(_pnOperator) _pnOperator -> Caption = LotInfo.sOperator ; tTemp.Val = LotInfo.dStartTime ; if(_pnStartTime) _pnStartTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = LotInfo.dEndTime ; if(_pnEndTime ) _pnEndTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = LotInfo.dRunTime ; if(_pnRunTime ) _pnRunTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = LotInfo.dIdleTime ; if(_pnIdleTime ) _pnIdleTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = LotInfo.dJamTime ; if(_pnJamTime ) _pnJamTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = LotInfo.dTotalTime ; if(_pnTotalTime) _pnTotalTime -> Caption = tTemp.FormatString("hh:nn:ss") ; if(_pnStrpUPEH) _pnStrpUPEH -> Caption = LotInfo.iStrpUPEH ; if(_pnChipUPEH) _pnChipUPEH -> Caption = LotInfo.iChipUPEH ; if(_pnStrpUPH ) _pnStrpUPH -> Caption = LotInfo.iStrpUPH ; if(_pnChipUPH ) _pnChipUPH -> Caption = LotInfo.iChipUPH ; if(_pnWorkStrp) _pnWorkStrp -> Caption = LotInfo.iWorkStrp ; if(_pnWorkChip) _pnWorkChip -> Caption = LotInfo.iWorkChip ; if(_pnFailChip) _pnFailChip -> Caption = LotInfo.iFailChip ; } void __fastcall CLot::DispDayInfo(TPanel * _pnRunTime , TPanel * _pnIdleTime , TPanel * _pnJamTime , TPanel * _pnTotalTime , TPanel * _pnStrpUPEH , TPanel * _pnChipUPEH , TPanel * _pnStrpUPH , TPanel * _pnChipUPH , TPanel * _pnWorkStrp , TPanel * _pnWorkChip , TPanel * _pnFailChip , TPanel * _pnWorkLot ) { TDateTime tTemp ; tTemp.Val = DayInfo.dRunTime ; if(_pnRunTime ) _pnRunTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = DayInfo.dIdleTime ; if(_pnIdleTime ) _pnIdleTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = DayInfo.dJamTime ; if(_pnJamTime ) _pnJamTime -> Caption = tTemp.FormatString("hh:nn:ss") ; tTemp.Val = DayInfo.dTotalTime ; if(_pnTotalTime) _pnTotalTime -> Caption = tTemp.FormatString("hh:nn:ss") ; if(_pnStrpUPEH) _pnStrpUPEH -> Caption = DayInfo.iStrpUPEH ; if(_pnChipUPEH) _pnChipUPEH -> Caption = DayInfo.iChipUPEH ; if(_pnStrpUPH ) _pnStrpUPH -> Caption = DayInfo.iStrpUPH ; if(_pnChipUPH ) _pnChipUPH -> Caption = DayInfo.iChipUPH ; if(_pnWorkStrp) _pnWorkStrp -> Caption = DayInfo.iWorkStrp ; if(_pnWorkChip) _pnWorkChip -> Caption = DayInfo.iWorkChip ; if(_pnFailChip) _pnFailChip -> Caption = DayInfo.iFailChip ; if(_pnWorkLot ) _pnWorkLot -> Caption = DayInfo.iLotCnt ; } //File Processing. void __fastcall CLot::LoadLotInfo() { //Local Var. TUserINI UserINI; AnsiString Path; AnsiString TempStr ; TDateTime TempTime; //Make Dir. Path = ExtractFilePath(Application->ExeName) + "SeqData\\" + "LotInfo.ini"; //Current Lot Informations. UserINI.Load(Path.c_str() , "Member " , "m_bLotOpen " , m_bLotOpen ); UserINI.Load(Path.c_str() , "LotInfo" , "sLotNo " , LotInfo.sLotNo ); UserINI.Load(Path.c_str() , "LotInfo" , "sJobFile " , LotInfo.sJobFile ); UserINI.Load(Path.c_str() , "LotInfo" , "iLotMgzCnt " , LotInfo.iLotMgzCnt ); UserINI.Load(Path.c_str() , "LotInfo" , "sOperator " , LotInfo.sOperator ); UserINI.Load(Path.c_str() , "LotInfo" , "dStartTime " , LotInfo.dStartTime ); UserINI.Load(Path.c_str() , "LotInfo" , "dEndTime " , LotInfo.dEndTime ); UserINI.Load(Path.c_str() , "LotInfo" , "dRunTime " , LotInfo.dRunTime ); UserINI.Load(Path.c_str() , "LotInfo" , "dIdleTime " , LotInfo.dIdleTime ); UserINI.Load(Path.c_str() , "LotInfo" , "dJamTime " , LotInfo.dJamTime ); UserINI.Load(Path.c_str() , "LotInfo" , "dTotalTime " , LotInfo.dTotalTime ); UserINI.Load(Path.c_str() , "LotInfo" , "iStrpUPEH " , LotInfo.iStrpUPEH ); UserINI.Load(Path.c_str() , "LotInfo" , "iChipUPEH " , LotInfo.iChipUPEH ); UserINI.Load(Path.c_str() , "LotInfo" , "iStrpUPH " , LotInfo.iStrpUPH ); UserINI.Load(Path.c_str() , "LotInfo" , "iChipUPH " , LotInfo.iChipUPH ); UserINI.Load(Path.c_str() , "LotInfo" , "iWorkStrp " , LotInfo.iWorkStrp ); UserINI.Load(Path.c_str() , "LotInfo" , "iWorkChip " , LotInfo.iWorkChip ); // UserINI.Load(Path.c_str() , "LotInfo" , "iGood " , LotInfo.iGood ); // UserINI.Load(Path.c_str() , "LotInfo" , "iFail " , LotInfo.iFail ); for(int i = 0 ; i < MAX_LOT_CNT ; i++) UserINI.Load(Path.c_str() , "LotNoQue" , "g_sLotNo"+AnsiString(i) , g_sLotNo[i] ); } void __fastcall CLot::SaveLotInfo() { //Local Var. TUserINI UserINI; AnsiString Path; AnsiString TempStr ; TDateTime TempTime; //Make Dir. Path = ExtractFilePath(Application->ExeName) + "SeqData\\" + "LotInfo.ini"; //Current Lot Informations. UserINI.Save(Path.c_str() , "Member " , "m_bLotOpen " , m_bLotOpen ); UserINI.Save(Path.c_str() , "LotInfo" , "sLotNo " , LotInfo.sLotNo ); UserINI.Save(Path.c_str() , "LotInfo" , "sJobFile " , LotInfo.sJobFile ); UserINI.Save(Path.c_str() , "LotInfo" , "iLotMgzCnt " , LotInfo.iLotMgzCnt ); UserINI.Save(Path.c_str() , "LotInfo" , "sOperator " , LotInfo.sOperator ); UserINI.Save(Path.c_str() , "LotInfo" , "dStartTime " , LotInfo.dStartTime ); UserINI.Save(Path.c_str() , "LotInfo" , "dEndTime " , LotInfo.dEndTime ); UserINI.Save(Path.c_str() , "LotInfo" , "dRunTime " , LotInfo.dRunTime ); UserINI.Save(Path.c_str() , "LotInfo" , "dIdleTime " , LotInfo.dIdleTime ); UserINI.Save(Path.c_str() , "LotInfo" , "dJamTime " , LotInfo.dJamTime ); UserINI.Save(Path.c_str() , "LotInfo" , "dTotalTime " , LotInfo.dTotalTime ); UserINI.Save(Path.c_str() , "LotInfo" , "iStrpUPEH " , LotInfo.iStrpUPEH ); UserINI.Save(Path.c_str() , "LotInfo" , "iChipUPEH " , LotInfo.iChipUPEH ); UserINI.Save(Path.c_str() , "LotInfo" , "iStrpUPH " , LotInfo.iStrpUPH ); UserINI.Save(Path.c_str() , "LotInfo" , "iChipUPH " , LotInfo.iChipUPH ); UserINI.Save(Path.c_str() , "LotInfo" , "iWorkStrp " , LotInfo.iWorkStrp ); UserINI.Save(Path.c_str() , "LotInfo" , "iWorkChip " , LotInfo.iWorkChip ); // UserINI.Save(Path.c_str() , "LotInfo" , "iGood " , LotInfo.iGood ); // UserINI.Save(Path.c_str() , "LotInfo" , "iFail " , LotInfo.iFail ); for(int i = 0 ; i < MAX_LOT_CNT ; i++) UserINI.Save(Path.c_str() , "LotNoQue" , "g_sLotNo"+AnsiString(i) , g_sLotNo[i] ); } void __fastcall CLot::LoadDayInfo() { //Local Var. TUserINI UserINI; AnsiString Path; AnsiString TempStr ; TDateTime TempTime; //Make Dir. Path = ExtractFilePath(Application->ExeName) + "SeqData\\" + "DayInfo.ini"; //Current Lot Informations. UserINI.Load(Path.c_str() , "DayInfo" , "dRunTime " , DayInfo.dRunTime ); UserINI.Load(Path.c_str() , "DayInfo" , "dIdleTime " , DayInfo.dIdleTime ); UserINI.Load(Path.c_str() , "DayInfo" , "dJamTime " , DayInfo.dJamTime ); UserINI.Load(Path.c_str() , "DayInfo" , "dTotalTime" , DayInfo.dTotalTime ); UserINI.Load(Path.c_str() , "DayInfo" , "iStrpUPEH " , DayInfo.iStrpUPEH ); UserINI.Load(Path.c_str() , "DayInfo" , "iChipUPEH " , DayInfo.iChipUPEH ); UserINI.Load(Path.c_str() , "DayInfo" , "iStrpUPH " , DayInfo.iStrpUPH ); UserINI.Load(Path.c_str() , "DayInfo" , "iChipUPH " , DayInfo.iChipUPH ); UserINI.Load(Path.c_str() , "DayInfo" , "iWorkStrp " , DayInfo.iWorkStrp ); UserINI.Load(Path.c_str() , "DayInfo" , "iWorkChip " , DayInfo.iWorkChip ); UserINI.Load(Path.c_str() , "DayInfo" , "iFailChip " , DayInfo.iFailChip ); UserINI.Load(Path.c_str() , "DayInfo" , "iLotCnt " , DayInfo.iLotCnt ); // UserINI.Load(Path.c_str() , "DayInfo" , "iGood " , DayInfo.iGood ); // UserINI.Load(Path.c_str() , "DayInfo" , "iFail " , DayInfo.iFail ); } void __fastcall CLot::SaveDayInfo() { //Local Var. TUserINI UserINI; AnsiString Path; AnsiString TempStr ; TDateTime TempTime; //Make Dir. Path = ExtractFilePath(Application->ExeName) + "SeqData\\" + "DayInfo.ini"; //Current Lot Informations. UserINI.Save(Path.c_str() , "DayInfo" , "dRunTime " , DayInfo.dRunTime ); UserINI.Save(Path.c_str() , "DayInfo" , "dIdleTime " , DayInfo.dIdleTime ); UserINI.Save(Path.c_str() , "DayInfo" , "dJamTime " , DayInfo.dJamTime ); UserINI.Save(Path.c_str() , "DayInfo" , "dTotalTime" , DayInfo.dTotalTime ); UserINI.Save(Path.c_str() , "DayInfo" , "iStrpUPEH " , DayInfo.iStrpUPEH ); UserINI.Save(Path.c_str() , "DayInfo" , "iChipUPEH " , DayInfo.iChipUPEH ); UserINI.Save(Path.c_str() , "DayInfo" , "iStrpUPH " , DayInfo.iStrpUPH ); UserINI.Save(Path.c_str() , "DayInfo" , "iChipUPH " , DayInfo.iChipUPH ); UserINI.Save(Path.c_str() , "DayInfo" , "iWorkStrp " , DayInfo.iWorkStrp ); UserINI.Save(Path.c_str() , "DayInfo" , "iWorkChip " , DayInfo.iWorkChip ); UserINI.Save(Path.c_str() , "DayInfo" , "iFailChip " , DayInfo.iFailChip ); UserINI.Save(Path.c_str() , "DayInfo" , "iLotCnt " , DayInfo.iLotCnt ); // UserINI.Save(Path.c_str() , "DayInfo" , "iGood " , DayInfo.iGood ); // UserINI.Save(Path.c_str() , "DayInfo" , "iFail " , DayInfo.iFail ); } void __fastcall CLot::WriteLotDayLog() { //Local Var. int hFile ; AnsiString Path ; AnsiString Temp ; TDateTime CurrDateTime; TDateTime tTemp ; bool bNewDay ; DelPastLotLog(); //Set Path. CurrDateTime = Now(); Temp = CurrDateTime.CurrentDate().FormatString("yyyymmdd"); Path = LOG_FOLDER ;//".csv"; if(!UserFile.FileExist(Path)) CreateDir(Path); Path = LOG_FOLDER + Temp + ".csv"; bNewDay = !UserFile.FileExist(Path); //새로운 날인지 확인하고 UserFile.DeleteFiles(Path); // 지운다. //File Open. hFile = FileOpen(Path.c_str() , fmOpenWrite); if (hFile == -1) { hFile = FileCreate(Path.c_str()); if (hFile == -1) return; Temp = "Day(Time)," ; Temp += "RunTime," ; Temp += "IdleTime," ; Temp += "JamTime," ; Temp += "TotalTime," ; Temp += "StrpUPEH," ; Temp += "ChipUPEH," ; Temp += "StrpUPH," ; Temp += "ChipUPH," ; Temp += "WorkStrp," ; Temp += "WorkChip," ; Temp += "FailChip," ; Temp += "LotCnt," ; Temp += "\r\n" ; FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , Temp.c_str() , Temp.Length()); if(bNewDay) { //새로운 날이면 전날 마지막 돌리던 물량 데이터 인계 받음. tTemp.Val = DayInfo.dRunTime ; Trace("DayInfo.dRunTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dIdleTime ; Trace("DayInfo.dIdleTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dJamTime ; Trace("DayInfo.dJamTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dTotalTime ; Trace("DayInfo.dTotalTime",tTemp.FormatString("hh:nn:ss").c_str()); Trace("DayInfo.iStrpUPEH" ,AnsiString(DayInfo.iStrpUPEH ).c_str()); Trace("DayInfo.iChipUPEH" ,AnsiString(DayInfo.iChipUPEH ).c_str()); Trace("DayInfo.iStrpUPH" ,AnsiString(DayInfo.iStrpUPH ).c_str()); Trace("DayInfo.iChipUPH" ,AnsiString(DayInfo.iChipUPH ).c_str()); Trace("DayInfo.iWorkStrp" ,AnsiString(DayInfo.iWorkStrp ).c_str()); Trace("DayInfo.iWorkChip" ,AnsiString(DayInfo.iWorkChip ).c_str()); Trace("DayInfo.iFailChip" ,AnsiString(DayInfo.iFailChip ).c_str()); Trace("DayInfo.iLotCnt" ,AnsiString(DayInfo.iLotCnt ).c_str()); DayInfo.dRunTime = LotInfo.dRunTime ; DayInfo.dIdleTime = LotInfo.dIdleTime ; DayInfo.dJamTime = LotInfo.dJamTime ; DayInfo.dTotalTime = LotInfo.dTotalTime ; DayInfo.iStrpUPEH = LotInfo.iStrpUPEH ; DayInfo.iChipUPEH = LotInfo.iChipUPEH ; DayInfo.iStrpUPH = LotInfo.iStrpUPH ; DayInfo.iChipUPH = LotInfo.iChipUPH ; DayInfo.iWorkStrp = LotInfo.iWorkStrp ; DayInfo.iWorkChip = LotInfo.iWorkChip ; DayInfo.iFailChip = LotInfo.iFailChip ; DayInfo.iLotCnt = 1 ; Trace("After Change" ,"------------------------------------"); tTemp.Val = DayInfo.dRunTime ; Trace("DayInfo.dRunTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dIdleTime ; Trace("DayInfo.dIdleTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dJamTime ; Trace("DayInfo.dJamTime" ,tTemp.FormatString("hh:nn:ss").c_str()); tTemp.Val = DayInfo.dTotalTime ; Trace("DayInfo.dTotalTime",tTemp.FormatString("hh:nn:ss").c_str()); Trace("DayInfo.iStrpUPEH" ,AnsiString(DayInfo.iStrpUPEH ).c_str()); Trace("DayInfo.iChipUPEH" ,AnsiString(DayInfo.iChipUPEH ).c_str()); Trace("DayInfo.iStrpUPH" ,AnsiString(DayInfo.iStrpUPH ).c_str()); Trace("DayInfo.iChipUPH" ,AnsiString(DayInfo.iChipUPH ).c_str()); Trace("DayInfo.iWorkStrp" ,AnsiString(DayInfo.iWorkStrp ).c_str()); Trace("DayInfo.iWorkChip" ,AnsiString(DayInfo.iWorkChip ).c_str()); Trace("DayInfo.iFailChip" ,AnsiString(DayInfo.iFailChip ).c_str()); Trace("DayInfo.iLotCnt" ,AnsiString(DayInfo.iLotCnt ).c_str()); } } //Save. Temp = CurrDateTime.FormatString("yy.mm.dd(hh:nn:ss)") + "," ; tTemp.Val = DayInfo.dRunTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = DayInfo.dIdleTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = DayInfo.dJamTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = DayInfo.dTotalTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; Temp += (AnsiString)DayInfo.iStrpUPEH + ","; Temp += (AnsiString)DayInfo.iChipUPEH + ","; Temp += (AnsiString)DayInfo.iStrpUPH + ","; Temp += (AnsiString)DayInfo.iChipUPH + ","; Temp += (AnsiString)DayInfo.iWorkStrp + ","; Temp += (AnsiString)DayInfo.iWorkChip + ","; Temp += (AnsiString)DayInfo.iFailChip + ","; Temp += (AnsiString)DayInfo.iLotCnt + ","; Temp += (AnsiString)"\r\n" ; FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , Temp.c_str() , Temp.Length()); //Close File. FileClose(hFile); } void __fastcall CLot::WriteLotLog() { //Local Var. int hFile ; AnsiString Path ; AnsiString Temp ; TDateTime CurrDateTime; DelPastLotLog(); //Set Path. CurrDateTime = Now(); Temp = CurrDateTime.CurrentDate().FormatString("yyyymmdd"); Path = LOG_FOLDER + Temp ;//".csv"; if(!UserFile.FileExist(Path)) { CreateDir(Path); //ClearDayInfo() ; // //DayInfo.dRunTime = LotInfo.dRunTime ; //DayInfo.dIdleTime = LotInfo.dIdleTime ; //DayInfo.dJamTime = LotInfo.dJamTime ; //DayInfo.dTotalTime = LotInfo.dTotalTime ; // //DayInfo.iStrpUPEH = LotInfo.iStrpUPEH ; //DayInfo.iChipUPEH = LotInfo.iChipUPEH ; //DayInfo.iStrpUPH = LotInfo.iStrpUPH ; //DayInfo.iChipUPH = LotInfo.iChipUPH ; // //DayInfo.iWorkStrp = LotInfo.iWorkStrp ; //DayInfo.iWorkChip = LotInfo.iWorkChip ; //DayInfo.iFailChip = LotInfo.iFailChip ; // //DayInfo.iLotCnt = 1 ; } Path = LOG_FOLDER + Temp + "\\" + LotInfo.sLotNo + ".csv"; //File Open. hFile = FileOpen(Path.c_str() , fmOpenWrite); if (hFile == -1) { hFile = FileCreate(Path.c_str()); if (hFile == -1) return; Temp = "Day(Time),"; Temp += "LotNo," ; Temp += "JobFile," ; Temp += "Operator," ; Temp += "StartTime,"; Temp += "EndTime," ; Temp += "RunTime," ; Temp += "IdleTime," ; Temp += "JamTime," ; Temp += "TotalTime,"; Temp += "StrpUPEH," ; Temp += "ChipUPEH," ; Temp += "StrpUPH," ; Temp += "ChipUPH," ; Temp += "WorkStrp," ; Temp += "WorkChip," ; Temp += "FailChip," ; // Temp += "iGood" ; // Temp += "iFail" ; Temp += "\r\n" ; FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , Temp.c_str() , Temp.Length()); } TDateTime tTemp ; //Save. Temp = CurrDateTime.FormatString("yy.mm.dd(hh:nn:ss)") + "," ; Temp += (AnsiString)LotInfo.sLotNo + ","; Temp += (AnsiString)LotInfo.sJobFile + ","; Temp += (AnsiString)LotInfo.sOperator + ","; tTemp.Val = LotInfo.dStartTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = LotInfo.dEndTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = LotInfo.dRunTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = LotInfo.dIdleTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = LotInfo.dJamTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; tTemp.Val = LotInfo.dTotalTime ; Temp += tTemp.FormatString("hh:nn:ss") + ","; Temp += (AnsiString)LotInfo.iStrpUPEH + "," ; Temp += (AnsiString)LotInfo.iChipUPEH + "," ; Temp += (AnsiString)LotInfo.iStrpUPH + "," ; Temp += (AnsiString)LotInfo.iChipUPH + "," ; Temp += (AnsiString)LotInfo.iWorkStrp + "," ; Temp += (AnsiString)LotInfo.iWorkChip + "," ; Temp += (AnsiString)LotInfo.iFailChip + "," ; Temp += (AnsiString)"\r\n" ; FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , Temp.c_str() , Temp.Length()); //Close File. FileClose(hFile); } void __fastcall CLot::DelPastLotLog() { UserFile.ClearDirDate(LOG_FOLDER , Now() - 30); } //Update Lot Efficiency. void __fastcall CLot::Update(EN_SEQ_STAT Stat) { static int iCnt = 0 ; iCnt++; // if(iCnt < 100) return ; iCnt = 0 ; static TDateTime tPreTime = Now(); TDateTime tCrntTime = Now(); double dGapTime = tCrntTime.Val - tPreTime.Val ; AnsiString sDate = tCrntTime.CurrentDate(); if(tCrntTime.CurrentDate() != tPreTime.CurrentDate()) { //ClearDayInfo() ; } switch(Stat) { case ssInit : DayInfo.dIdleTime += dGapTime ; LotInfo.dIdleTime += dGapTime ; break ; case ssWarning : DayInfo.dIdleTime += dGapTime ; LotInfo.dIdleTime += dGapTime ; break ; case ssError : DayInfo.dJamTime += dGapTime ; LotInfo.dJamTime += dGapTime ; break ; case ssRunning : DayInfo.dRunTime += dGapTime ; LotInfo.dRunTime += dGapTime ; break ; case ssStop : DayInfo.dIdleTime += dGapTime ; LotInfo.dIdleTime += dGapTime ; break ; case ssMaint : DayInfo.dIdleTime += dGapTime ; LotInfo.dIdleTime += dGapTime ; break ; case ssRunWarn : DayInfo.dRunTime += dGapTime ; LotInfo.dRunTime += dGapTime ; break ; case ssWorkEnd : DayInfo.dIdleTime += dGapTime ; LotInfo.dIdleTime += dGapTime ; break ; } double dTotalTime = LotInfo.dIdleTime + LotInfo.dJamTime + LotInfo.dRunTime ; LotInfo.dTotalTime += dGapTime ; DayInfo.dTotalTime += dGapTime ; //Lot Info if(LotInfo.dRunTime) {LotInfo.iChipUPH = LotInfo.iWorkChip / (LotInfo.dRunTime * 24) ;} else {LotInfo.iChipUPH = 0 ; } if(LotInfo.dRunTime) {LotInfo.iStrpUPH = LotInfo.iWorkStrp / (LotInfo.dRunTime * 24) ;} else {LotInfo.iStrpUPH = 0 ; } if(LotInfo.dTotalTime) {LotInfo.iChipUPEH = LotInfo.iWorkChip / (LotInfo.dTotalTime * 24) ;} else {LotInfo.iChipUPEH = 0 ; } if(LotInfo.dTotalTime) {LotInfo.iStrpUPEH = LotInfo.iWorkStrp / (LotInfo.dTotalTime * 24) ;} else {LotInfo.iStrpUPEH = 0 ; } //Day Info if(DayInfo.dRunTime) {DayInfo.iChipUPH = DayInfo.iWorkChip / (DayInfo.dRunTime * 24) ;} else {DayInfo.iChipUPH = 0 ; } if(DayInfo.dRunTime) {DayInfo.iStrpUPH = DayInfo.iWorkStrp / (DayInfo.dRunTime * 24) ;} else {DayInfo.iStrpUPH = 0 ; } if(DayInfo.dTotalTime) {DayInfo.iChipUPEH = DayInfo.iWorkChip / (DayInfo.dTotalTime * 24) ;} else {DayInfo.iChipUPEH = 0 ; } if(DayInfo.dTotalTime) {DayInfo.iStrpUPEH = DayInfo.iWorkStrp / (DayInfo.dTotalTime * 24) ;} else {DayInfo.iStrpUPEH = 0 ; } tPreTime = tCrntTime ; } void __fastcall CLot::UpdateDate(TStringGrid * _sgDate) { UserFile.GridSearchDir(LOG_FOLDER , _sgDate , 1 , false); // 디렉토리 읽어와서 날짜와 알파벳 순으로 정렬 } void __fastcall CLot::UpdateLotName(TStringGrid * _sgDate , TStringGrid * _sgLot) { AnsiString sDay ,sPath ; sDay = _sgDate->Cells[1][_sgDate -> Row] ; sPath = LOG_FOLDER + sDay + "\\" ; UserFile.GridSearchFile(sPath , _sgLot , 1 , true); // 디렉토리 읽어와서 날짜와 알파벳 순으로 정렬 } void __fastcall CLot::DispLotDate(TStringGrid * _sgDate , TStringGrid * _sgLot , TStringGrid * _sgLotInfo) { AnsiString sDay = _sgDate -> Cells[1][ _sgDate -> Row] ; AnsiString sPath = LOG_FOLDER + sDay + "\\" + _sgLot -> Cells[1][ _sgLot -> Row]; //StringGrid Clear for(int i =0 ; i < _sgLotInfo->ColCount ; i++ ) { for(int j =1 ; j < _sgLotInfo->RowCount ; j++ ) { _sgLotInfo -> Cells[i][j] = "" ; } } _sgLotInfo -> ColCount = 18 ; _sgLotInfo -> RowCount = 100 ;//UserFile.SearchDir(sPath) + 1 ; // _sgLotInfo -> FixedCols = 1 ; //_sgLotInfo -> FixedRows = 1 ; _sgLotInfo -> DefaultColWidth = 80 ; _sgLotInfo -> DefaultRowHeight = 25 ; _sgLotInfo -> ColWidths[0] = 30 ; _sgLotInfo -> ColWidths[1] = 145 ; _sgLotInfo -> ColWidths[2] = 210 ; _sgLotInfo -> ColWidths[3] = 150 ; AnsiString strName, str = ""; AnsiString sRowStr = ""; AnsiString sItmStr = ""; int hwnd, flen; int iRowCnt = 0 ; int iColCnt = 0 ; char *pfbuf; hwnd = FileOpen(sPath.c_str(), fmOpenRead) ; if(hwnd == NULL) return; flen = FileSeek(hwnd,0,2); FileSeek(hwnd,0,0); pfbuf = new char[flen+1]; memset(pfbuf , 0 , sizeof(char)*(flen+1)); FileRead(hwnd, pfbuf, flen); FileClose(hwnd); str = pfbuf ; while (str.Pos("\r\n")) { str.Delete(str.Pos("\r\n") , 2 ) ; if(iRowCnt > 100 ) return ; iRowCnt++ ; } _sgLotInfo -> RowCount = iRowCnt ; str = pfbuf ; iRowCnt = 0 ; while (str.Pos("\r\n")) { sRowStr = str.SubString(1 , str.Pos("\r\n")) ; str.Delete(1,str.Pos("\r\n")+1) ; iColCnt = 0 ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = iRowCnt ; while (sRowStr.Pos(",")){ iColCnt++ ; sItmStr = sRowStr.SubString(0,sRowStr.Pos(",")-1) ; sRowStr.Delete(1,sRowStr.Pos(",")) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; } iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos("\r\n" - 1 )) ; sRowStr.Delete(1,sRowStr.Pos("\r\n" - 1 )) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; // _sgLotInfo -> Cells[iColCnt][iRowCnt] = sRowStr ; iRowCnt++; } _sgLotInfo -> FixedCols = 1 ; } void __fastcall CLot::DispLotDate(AnsiString sFDataTime , AnsiString sUDataTime , TStringGrid * _sgLotInfo) { AnsiString sPath ; AnsiString sFPath , sFile ,sData = ""; AnsiString sTemp; int iRowCnt , iColCnt ; int iR , iFCol = -1 , iLCol = -1 ; int hwnd, flen; char *pfbuf; if(sFDataTime.ToIntDef(-1) > sUDataTime.ToIntDef(-2)) return ; for(int i =0 ; i < _sgLotInfo->ColCount ; i++ ) { for(int j =1 ; j < _sgLotInfo->RowCount ; j++ ) { _sgLotInfo -> Cells[i][j] = "" ; } } _sgLotInfo -> ColCount = 18 ; _sgLotInfo -> DefaultColWidth = 80 ; _sgLotInfo -> DefaultRowHeight = 25 ; _sgLotInfo -> ColWidths[0] = 30 ; _sgLotInfo -> ColWidths[1] = 145 ; _sgLotInfo -> ColWidths[2] = 210 ; m_pLotFolder = new TStringGrid(Application); m_pLotFile = new TStringGrid(Application); sPath = LOG_FOLDER ; UserFile.GridSearchDir(sPath , m_pLotFolder , 0 , false); // 디렉토리 읽어와서 날짜와 알파벳 순으로 정렬 iRowCnt = m_pLotFolder->RowCount ; for(int i=0 ; i<iRowCnt ; i++){ if( m_pLotFolder->Cells[1][i] == sFDataTime ) iFCol = i ; if( m_pLotFolder->Cells[1][i] == sUDataTime ) iLCol = i ; } if(iFCol == -1 ) { for(int i=0 ; i<iRowCnt ; i++){ if(m_pLotFolder->Cells[1][i].ToIntDef(0) > sFDataTime.ToIntDef(0) && m_pLotFolder->Cells[1][i].ToIntDef(0) <= sUDataTime.ToIntDef(0)) { iFCol = i ; break; } } } if(iLCol == -1 ) { for(int i=iRowCnt -1 ; i >= 1 ; i--){ if(m_pLotFolder->Cells[1][i].ToIntDef(0) < sUDataTime.ToIntDef(0) && m_pLotFolder->Cells[1][i].ToIntDef(0) >= sFDataTime.ToIntDef(0)) { iLCol = i ; break; } } } if(iFCol == -1 ) return ; if(iLCol == -1 ) return ; iR = iLCol - iFCol ; AnsiString sTemp1,sTemp2; for(int i=iFCol ; i<=iLCol ; i++){ sFPath= sPath + m_pLotFolder->Cells[1][i] + "\\"; UserFile.GridSearchFile(sFPath , m_pLotFile , 1 , false); // 디렉토리 읽어와서 날짜와 알파벳 순으로 정렬 for(int j=0 ; j<m_pLotFile->RowCount ; j++) { sTemp1 = m_pLotFile ->Cells[1][j] ; sFile += sFPath + sTemp1 + ","; } } // for(int i=iFCol ; i<=iLCol ; i++){ AnsiString sFileSub ; while(sFile.Pos(",")) { sFileSub = sFile.SubString(1,sFile.Pos(",")-1); sFile.Delete(1, sFile.Pos(",") ); sFPath= sFileSub; hwnd = FileOpen(sFPath.c_str(), fmOpenRead) ; if(hwnd == NULL) return ; flen = FileSeek(hwnd,0,2); FileSeek(hwnd,0,0); pfbuf = new char[flen+1]; memset(pfbuf , 0 , sizeof(char)*(flen+1)); FileRead(hwnd, pfbuf, flen); FileClose(hwnd); sTemp = pfbuf ; sTemp.Delete(1,sTemp.Pos("\r\n")+1); sData += sTemp; } // } // int iRowCnt = 0, iColCnt =0 ; AnsiString sRowStr, sItmStr ; iRowCnt = 1; while(sData.Pos("\r\n")){ sRowStr = sData.SubString(1, sData.Pos("\r\n")) ; sData.Delete(1,sData.Pos("\r\n")+1) ; iColCnt = 0 ; _sgLotInfo->Cells[iColCnt][iRowCnt] = iRowCnt ; while (sRowStr.Pos(",")){ iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos(",")-1) ; sRowStr.Delete(1,sRowStr.Pos(",")) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; } iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos("\r\n" - 1 )) ; sRowStr.Delete(1,sRowStr.Pos("\r\n" - 1 )) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; iRowCnt ++ ; } _sgLotInfo -> RowCount = iRowCnt ; return ; } void __fastcall CLot::SaveLotData (AnsiString sFDataTime , AnsiString sUDataTime , TStringGrid * _sgLotInfo) { AnsiString sPath , sTemp , sData , sFPath; int hFile; int hwnd, flen; if(sFDataTime.ToIntDef(-1) > sUDataTime.ToIntDef(-2)) return ; TDateTime CurrDateTime = Now();; //Set Path. sTemp = "LotInfo" ; sPath = SPC_FOLDER + sTemp;//".csv"; //Set File Path. sFPath = sPath + "\\" + sFDataTime + "-" + sUDataTime + ".csv"; if(!DirectoryExists(sPath)) UserFile.CreateDir(sPath.c_str()); //Set Data. sData = sFDataTime + "," + sUDataTime + "," + CurrDateTime.CurrentDateTime().FormatString("yyyymmdd(hh:nn)") + "\r\n"; for(int i=0; i<_sgLotInfo->RowCount; i++){ for(int j=0; j<_sgLotInfo->ColCount; j++){ sData += _sgLotInfo -> Cells[j][i] + "," ; } sData += "\r\n" ; } hFile = FileOpen(sFPath.c_str() , fmOpenWrite); if (hFile == -1) { hFile = FileCreate(sFPath.c_str()); if (hFile == -1) { Trace("Err",(sFPath + "is Can't made").c_str()); return ; } } FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , sData.c_str() , sData.Length()); //Close File. FileClose(hFile); return ; } void __fastcall CLot::DispLotDayDate (TStringGrid * _sgLotName , TStringGrid * _sgLotInfo) { AnsiString sPath = LOG_FOLDER ; AnsiString sFPath = LOG_FOLDER + _sgLotName -> Cells[1][ _sgLotName -> Row] ; for(int i =0 ; i < _sgLotInfo->ColCount ; i++ ) { for(int j =1 ; j < _sgLotInfo->RowCount ; j++ ) { _sgLotInfo -> Cells[i][j] = "" ; } } _sgLotInfo -> ColCount = 13;//29 ; _sgLotInfo -> DefaultColWidth = 80 ; _sgLotInfo -> DefaultRowHeight = 25 ; _sgLotInfo -> ColWidths[0] = 30 ; _sgLotInfo -> ColWidths[1] = 145 ; _sgLotInfo -> ColWidths[2] = 90 ; AnsiString strName, str = ""; AnsiString sRowStr = ""; AnsiString sItmStr = ""; int hwnd, flen; int iRowCnt = 0 ; int iColCnt = 0 ; char *pfbuf; hwnd = FileOpen(sFPath.c_str(), fmOpenRead) ; if(hwnd == NULL) return; flen = FileSeek(hwnd,0,2); FileSeek(hwnd,0,0); pfbuf = new char[flen+1]; memset(pfbuf , 0 , sizeof(char)*(flen+1)); FileRead(hwnd, pfbuf, flen); FileClose(hwnd); str = pfbuf ; iRowCnt = 0 ; while (str.Pos("\r\n")) { sRowStr = str.SubString(1 , str.Pos("\r\n")) ; str.Delete(1,str.Pos("\r\n")+1) ; iColCnt = 0 ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = iRowCnt ; while (sRowStr.Pos(",")){ iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos(",")-1) ; sRowStr.Delete(1,sRowStr.Pos(",")) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; } iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos("\r\n" - 1 )) ; sRowStr.Delete(1,sRowStr.Pos("\r\n" - 1 )) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; iRowCnt++; } _sgLotInfo -> RowCount = iRowCnt ; } void __fastcall CLot::DispLotDayDate (AnsiString sFDataTime , AnsiString sUDataTime , TStringGrid * _sgLotInfo) { AnsiString sPath; AnsiString sFPath , sFile ,sData = ""; AnsiString sTemp; int iRowCnt , iColCnt ; int iR , iFCol = -1 , iLCol = -1 ; int hwnd, flen; char *pfbuf; if(sFDataTime.ToIntDef(-1) > sUDataTime.ToIntDef(-2)) return ; for(int i =0 ; i < _sgLotInfo->ColCount ; i++ ) { for(int j =1 ; j < _sgLotInfo->RowCount ; j++ ) { _sgLotInfo -> Cells[i][j] = "" ; } } _sgLotInfo -> ColCount = 13;//33 ; _sgLotInfo -> DefaultColWidth = 80 ; _sgLotInfo -> DefaultRowHeight = 25 ; _sgLotInfo -> ColWidths[0] = 30 ; _sgLotInfo -> ColWidths[1] = 145 ; _sgLotInfo -> ColWidths[2] = 90 ; m_pLotFile = new TStringGrid(Application); sPath = LOG_FOLDER ; UserFile.GridSearchFile(sPath , m_pLotFile , 0 , false); // 디렉토리 읽어와서 날짜와 알파벳 순으로 정렬 iRowCnt = m_pLotFile->RowCount ; // sFDataTime += ".csv" ; // sUDataTime += ".csv" ; for(int i=0 ; i<iRowCnt ; i++){ if( m_pLotFile->Cells[1][i].SubString(0,8) == sFDataTime ) iFCol = i ; if( m_pLotFile->Cells[1][i].SubString(0,8) == sUDataTime ) iLCol = i ; } if(iFCol == -1 ) { for(int i=0 ; i<iRowCnt ; i++){ sTemp = m_pLotFile->Cells[1][i].SubString(0,8); if(sTemp.ToIntDef(0) > sFDataTime.ToIntDef(0) && sTemp.ToIntDef(0) <= sUDataTime.ToIntDef(0)) { iFCol = i ; break; } } } if(iLCol == -1 ) { for(int i=iRowCnt -1 ; i >= 1 ; i--){ sTemp = m_pLotFile->Cells[1][i].SubString(0,8); if(sTemp.ToIntDef(0) < sUDataTime.ToIntDef(0) && sTemp.ToIntDef(0) >= sFDataTime.ToIntDef(0)) { iLCol = i ; break; } } } if(iFCol == -1 ) return ; if(iLCol == -1 ) return ; AnsiString sTemp1,sTemp2; for(int i=iFCol ; i<=iLCol ; i++){ sFPath= sPath + m_pLotFile->Cells[1][i] ; sFile += sFPath + ","; } if(iFCol == -1 ) { for(int i=0 ; i<iRowCnt ; i++){ if(m_pLotFile->Cells[1][i].ToIntDef(0) > sFDataTime.ToIntDef(0) && m_pLotFile->Cells[1][i].ToIntDef(0) <= sUDataTime.ToIntDef(0)) { iFCol = i ; break; } } } // for(int i=iFCol ; i<=iLCol ; i++){ AnsiString sFileSub ; while(sFile.Pos(",")) { sFileSub = sFile.SubString(1,sFile.Pos(",")-1); sFile.Delete(1, sFile.Pos(",") ); sFPath= sFileSub; hwnd = FileOpen(sFPath.c_str(), fmOpenRead) ; if(hwnd == NULL) continue ; flen = FileSeek(hwnd,0,2); FileSeek(hwnd,0,0); pfbuf = new char[flen+1]; memset(pfbuf , 0 , sizeof(char)*(flen+1)); FileRead(hwnd, pfbuf, flen); FileClose(hwnd); sTemp = pfbuf ; sTemp.Delete(1,sTemp.Pos("\r\n")+1); sData += sTemp; } // } // int iRowCnt = 0, iColCnt =0 ; AnsiString sRowStr, sItmStr ; iRowCnt = 1; while(sData.Pos("\r\n")){ sRowStr = sData.SubString(1, sData.Pos("\r\n")) ; sData.Delete(1,sData.Pos("\r\n")+1) ; iColCnt = 0 ; _sgLotInfo->Cells[iColCnt][iRowCnt] = iRowCnt ; while (sRowStr.Pos(",")){ iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos(",")-1) ; sRowStr.Delete(1,sRowStr.Pos(",")) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; } iColCnt++ ; sItmStr = sRowStr.SubString(1,sRowStr.Pos("\r\n" - 1 )) ; sRowStr.Delete(1,sRowStr.Pos("\r\n" - 1 )) ; _sgLotInfo -> Cells[iColCnt][iRowCnt] = sItmStr ; iRowCnt ++ ; } _sgLotInfo -> RowCount = iRowCnt ; return ; } void __fastcall CLot::SaveLotDayData (AnsiString sFDataTime , AnsiString sUDataTime , TStringGrid * _sgLotInfo) { AnsiString sPath , sTemp , sData , sFPath; int hFile; int hwnd, flen; if(sFDataTime.ToIntDef(-1) > sUDataTime.ToIntDef(-2)) return ; TDateTime CurrDateTime = Now();; //Set Path. sTemp = "LotDayInfo" ; sPath = SPC_FOLDER + sTemp;//".csv"; //Set File Path. sFPath = sPath + "\\" + sFDataTime + "-" + sUDataTime + ".csv"; if(!DirectoryExists(sPath)) UserFile.CreateDir(sPath.c_str()); //Set Data. sData = sFDataTime + "," + sUDataTime + "," + CurrDateTime.CurrentDateTime().FormatString("yyyymmdd(hh:nn)") + "\r\n"; for(int i=0; i<_sgLotInfo->RowCount; i++){ for(int j=0; j<_sgLotInfo->ColCount; j++){ sData += _sgLotInfo -> Cells[j][i] + "," ; } sData += "\r\n" ; } hFile = FileOpen(sFPath.c_str() , fmOpenWrite); if (hFile == -1) { hFile = FileCreate(sFPath.c_str()); if (hFile == -1) { Trace("Err",(sFPath + "is Can't made").c_str()); return ; } } FileSeek (hFile , 0 , SEEK_END ); FileWrite(hFile , sData.c_str() , sData.Length()); //Close File. FileClose(hFile); return ; } bool __fastcall CLot::WriteArayData(EN_ARAY_ID riId ) //매거진 1개 일때만 랏드당 매거진 2개 이상 고려 안함. { //Local Var. TUserINI UserINI; AnsiString sPath , sArayName ; AnsiString sLotNo , sMgzNo , sSlotNo; AnsiString sTemp ; AnsiString sTemp2 ; AnsiString sRslt ; TDateTime CurrDateTime; int iMgzNo , iSlotNo ; DelPastLotLog(); //Set Path. // if(riId == riWRK ) sArayName = "Buffer"; // else if(riId == riWK1 ) sArayName = "Vision1"; // else if(riId == riWK2 ) sArayName = "Vision2"; // else if(riId == riPSB ) sArayName = "Trim"; if( DM.ARAY[riId].GetLotNo() == "" ) sLotNo = "NoLot"; else sLotNo = DM.ARAY[riId].GetLotNo(); iSlotNo = DM.ARAY[riId].GetID().ToIntDef(9999)%100 ; iMgzNo = DM.ARAY[riId].GetID().ToIntDef(9999)/100 ; sPath = LOG_FOLDER + CurrDateTime.CurrentDate().FormatString("yyyymmdd") + "\\" + sLotNo + "\\" + (String)iMgzNo ; if(!DirectoryExists(sPath)) UserFile.CreateDir(sPath.c_str()); sPath = sPath + "\\" + (String)iSlotNo + ".ini" ; for(int r = 0 ; r < OM.DevInfo.iRowCnt ; r++) { sRslt = "" ; for(int c = 0 ; c < OM.DevInfo.iColCnt ; c++) { //sRslt += IntToHex(((int)DM.ARAY[riId].GetStat(r,c)) , 2) ; sTemp2 = (int)DM.ARAY[riId].GetStat(r,c) ; sTemp2 = sTemp2.sprintf("%02d",(int)DM.ARAY[riId].GetStat(r,c)) + "_"; sRslt += sTemp2 ; } sTemp.printf("R%02d", r); UserINI.Save(sPath.c_str() , "Data" , sTemp , sRslt ); } UserINI.Save(sPath.c_str() , "ETC" , "ID" , DM.ARAY[riId].GetID().ToIntDef(9999) ); UserINI.Save(sPath.c_str() , "ETC" , "LotNo" , DM.ARAY[riId].GetLotNo() ); UserINI.Save(sPath.c_str() , "ETC" , "Row" , OM.DevInfo.iRowCnt ); UserINI.Save(sPath.c_str() , "ETC" , "Col" , OM.DevInfo.iColCnt ); return true ; } bool __fastcall CLot::ReadArayData (AnsiString sPath , EN_ARAY_ID riId) //매거진 1개 일때만 랏드당 매거진 2개 이상 고려 안함. { //Local Var. TUserINI UserINI; AnsiString sTemp ; AnsiString sVal ; AnsiString sRslt ; AnsiString sId ; AnsiString sLotNo ; int iRow , iCol ; AnsiString sTemp2= "" ; if(!FileExists(sPath)) return false ; UserINI.Load(sPath.c_str() , "ETC" , "ID" , &sId ); UserINI.Load(sPath.c_str() , "ETC" , "LotNo" , &sLotNo ); UserINI.Load(sPath.c_str() , "ETC" , "Row" , &iRow ); UserINI.Load(sPath.c_str() , "ETC" , "Col" , &iCol ); DM.ARAY[riSPC].SetMaxColRow(iCol,iRow ); for(int r = 0 ; r < iRow ; r++) { sTemp.printf("R%02d", r); UserINI.Load(sPath.c_str() , "Data" , sTemp , sRslt ); for(int c = 0 ; c < iCol ; c++) { //sVal = "0x"+sRslt.SubString(c+1,1) ; sVal = sRslt.SubString(1,2) ; sRslt.Delete(1,3) ; DM.ARAY[riId].SetStat(r,c,(EN_CHIP_STAT)StrToInt(sVal) ); sTemp2 = sVal+"," ; } } DM.ARAY[riId].SetID (sId ); DM.ARAY[riId].SetLotNo(sLotNo); // UserFile.DeleteFiles(sPath); Trace("Rcv Array",sTemp2.c_str()) ; return true ; }
fe2246cdd6637f119f0860cf6c02920597835670
16c26427f96e466ca831cfa6ac1dfb4c10ea5ca9
/Old/ArduinoLibraries_021319/libraries/BeckI2cLib/BeckI2cLib.cpp
eaff52a1f471440d5f885d0c4cd316cc195ec67e
[]
no_license
lbeck37/Arduino
7f43fa593a83d0e8b3383376b5195ec87d9e162b
de350beb32943a56ff5ea80ae52f9868abc918a8
refs/heads/master
2021-10-11T23:03:50.471548
2021-10-09T13:00:30
2021-10-09T13:00:30
35,703,269
1
0
null
2020-08-31T23:34:16
2015-05-16T00:29:26
G-code
UTF-8
C++
false
false
6,689
cpp
BeckI2cLib.cpp
//BeckI2cLib.cpp #include <BeckI2cLib.h> #include <Wire.h> /* //******* MPU-6050 6-axis accelerometer and gyro const int MPU= 0x68; // I2C address of the MPU-6050 int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ; //Gyro defines const int sXAxis = 0; const int sYAxis = 1; const int sZAxis = 2; const int sNumAxis = 3; const int sAccel = 0; const int sRotation = 1; const int sTemperature = 2; const int sNumGyroTypes = 3; const uint32_t ulGyroReadTime = 500; //Gyro reads spaced by this. uint32_t ulNextGyroTime = 0; //msec when the gyro will be read boolean bGyroChanged = false; INT16 asGyro[sNumGyroTypes][sNumAxis]; //Was int */ const UINT8 ucADS1115_Address = 0x48; const UINT16 usDefaultSingleChanReadConfig= ADS1015_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val) ADS1015_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val) ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val) ADS1015_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val) ADS1015_REG_CONFIG_DR_1600SPS | // 1600 samples per second (default) ADS1015_REG_CONFIG_MODE_SINGLE | // Single-shot mode (default) ADS1015_REG_CONFIG_OS_SINGLE; // Single-shot start conversion //********************************************************************************* //Local function protos void WriteI2cRegister (UINT8 ucI2cAddress, UINT8 ucRegister, UINT16 usValue); INT16 ReadI2cRegister (UINT8 ucI2cAddress, UINT8 ucRegister); //Writes 16-bits to the specified destination register //void WriteI2cRegister(uint8_t i2cAddress, uint8_t reg, uint16_t value) { void WriteI2cRegister(UINT8 ucI2cAddress, UINT8 ucRegister, UINT16 usValue) { Wire.beginTransmission(ucI2cAddress); Wire.write(ucRegister); Wire.write((UINT8)(usValue >> 8)); //High byte Wire.write((UINT8)(usValue & 0xFF)); //Low byte Wire.endTransmission(); } //WriteI2cRegister //Reads 16-bits from the specified source register //static uint16_t ReadI2cRegister(uint8_t i2cAddress, uint8_t reg) { INT16 ReadI2cRegister(UINT8 ucI2cAddress, UINT8 ucRegister) { Wire.beginTransmission(ucI2cAddress); Wire.write(ucRegister); //Was ADS1015_REG_POINTER_CONVERT Wire.endTransmission(); //Read the high byte and then the low byte Wire.requestFrom(ucI2cAddress, (UINT8)2); INT16 sReturn= ((Wire.read() << 8) | Wire.read()); return sReturn; } //ReadI2cRegister //********************************************************************************* //Exported functions INT16 sSetup_I2C() { Wire.begin(); return 1; } //sSetup_I2C INT16 sSetup_ADS1115() { return 1; } //sSetup_ADS1115 double dRead_ADS1115(INT16 sChannel, adsGain_t eGain) { UINT16 usConfig= usDefaultSingleChanReadConfig; usConfig |= eGain; switch (sChannel) { case (0): usConfig |= ADS1015_REG_CONFIG_MUX_SINGLE_0; break; case (1): usConfig |= ADS1015_REG_CONFIG_MUX_SINGLE_1; break; case (2): usConfig |= ADS1015_REG_CONFIG_MUX_SINGLE_2; break; case (3): usConfig |= ADS1015_REG_CONFIG_MUX_SINGLE_3; break; default: String szLogString="dRead_ADS1115(): Bad switch"; LogToBoth(szLogString, sChannel); break; } //switch WriteI2cRegister(ucADS1115_Address, ADS1015_REG_POINTER_CONFIG, usConfig); delay(50); //Adafruit code only delays for 8. INT16 sVoltCount= ReadI2cRegister(ucADS1115_Address, ADS1015_REG_POINTER_CONVERT); double dVoltsRead= (sVoltCount * 4.096) / 32768.0; return(dVoltsRead); } //dRead_ADS1115 /* INT16 sSetup_Gyro() { //Serial << sLC++ <<"sSetupGyro(): Begin"<< endl; BLog("sSetup_Gyro(): Begin"); Wire.beginTransmission(MPU); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); //Initialize the data array. for (int sDataType= sAccel; sDataType < sNumGyroTypes; sDataType++) { for (int sAxis= sXAxis; sAxis < sNumAxis; sAxis++) { asGyro[sDataType][sAxis]= 0; } //for sDataType } //for sAxis return 1; } //sSetup_Gyro void Read_Gyro() { INT16 asGyroReading[sNumGyroTypes][sNumAxis]; //boolean bApplySmoothing= APPLY_SMOOTHING; if (millis() > ulNextGyroTime) { Wire.beginTransmission(MPU); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); //Wire.requestFrom(MPU,14,true); // request a total of 14 registers //bool bTrue= true; Wire.requestFrom((uint8_t)MPU, (size_t)14, (bool)true); // request a total of 14 registers // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L) // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) asGyroReading[sAccel][sXAxis]= Wire.read()<<8|Wire.read(); asGyroReading[sAccel][sYAxis]= Wire.read()<<8|Wire.read(); asGyroReading[sAccel][sZAxis]= Wire.read()<<8|Wire.read(); asGyroReading[sTemperature][sXAxis]= Wire.read()<<8|Wire.read(); asGyroReading[sRotation][sXAxis]=Wire.read()<<8|Wire.read(); asGyroReading[sRotation][sYAxis]=Wire.read()<<8|Wire.read(); asGyroReading[sRotation][sZAxis]=Wire.read()<<8|Wire.read(); //Initialize missing temperature fields. for (int sAxis= sYAxis; sAxis < sNumAxis; sAxis++) { asGyroReading[sTemperature][sAxis]= 0; } //for //Apply low-pass filter to data for (int sDataType= sAccel; sDataType < sNumGyroTypes; sDataType++) { for (int sAxis= sXAxis; sAxis < sNumAxis; sAxis++) { #if APPLY_SMOOTHING asGyro[sDataType][sAxis]= FILTER_FUNC(asGyroReading[sDataType][sAxis], pusSmoothingMemory[sDataType][sAxis]); #else asGyro[sDataType][sAxis]= asGyroReading[sDataType][sAxis]; #endif } //for sDataType } //for sAxis //The following is for bringing up gyro String szLogString="Read_Gyro(): AccelZ"; INT16 sAccelZaxis= asGyro[sAccel][sZAxis]; LogToBoth(szLogString, sAccelZaxis); bGyroChanged= true; ulNextGyroTime= millis() + ulGyroReadTime; } //if (millis()>ulNextGyroTime) return; } //Read_Gyro */ //Last line.
afc1f85a617653672412adea527952b80fe596c4
cee50b83750498fe360fd8f30392856dbdc697ef
/삼성_SW역량테스트_기출/SM_BOJ20056_마법사_상어와_파이어볼.cpp
179a5616034bca5159096ac31779604ed2f32a98
[]
no_license
NanyoungKim/Coding_Test_Practice
f4c95a2e5f608d1747c59864e46e18ecaf54dde9
e9e9c20117ccebf06ea0a300e1db8d8badecb522
refs/heads/master
2023-06-10T10:37:24.049012
2021-07-05T14:08:29
2021-07-05T14:08:29
265,776,499
0
0
null
null
null
null
UTF-8
C++
false
false
4,377
cpp
SM_BOJ20056_마법사_상어와_파이어볼.cpp
// // SM_BOJ20056_마법사_상어와_파이어볼.cpp // Coding_Test_Practice // // Created by 김난영 on 2021/04/05. // Copyright © 2021 KimNanyoung. All rights reserved. // #include <iostream> #include <vector> #include <string.h> #include <queue> using namespace std; class Ball{ public: int r,c,m, s, d; Ball(); Ball(int r, int c, int m, int s, int d){ this->r = r; this->c = c; this->m = m; this->s = s; this->d = d; } }; int N,M,K; vector<Ball> map[51][51]; vector<Ball> ballVec; int dr[8] = {-1,-1,0,1,1,1,0,-1}; int dc[8] = {0,1,1,1,0,-1,-1,-1}; int dArr[4] = {0}; void initdArr(bool isEorO){ if(isEorO){ dArr[0] = 0; dArr[1] = 2; dArr[2] = 4; dArr[3] = 6; } else{ dArr[0] = 1; dArr[1] = 3; dArr[2] = 5; dArr[3] = 7; } } bool isAllEorO(int row, int col){ //모두 짝수거나 홀수인지 체크 int evenNum=0; for(int i = 0; i<map[row][col].size(); i++){ Ball fireball = map[row][col][i]; if(fireball.d%2==0){ evenNum++; } } if(evenNum==map[row][col].size()) return true; //모두 짝수이면 int oddNum=0; for(int i = 0; i<map[row][col].size(); i++){ Ball fireball = map[row][col][i]; if(fireball.d%2==1){ oddNum++; } } if(oddNum==map[row][col].size()) return true; return false; } int modFunc(int x){ if(x>0){ x = x%N; } else{ while(x<=0){ //x가 0보다 커지면 stop x+=N; } } return x; } int main(){ cin >> N >> M >> K; for(int i = 1; i<=M; i++){ int r,c,m,s,d; scanf("%d%d%d%d%d", &r, &c, &m, &s, &d); map[r][c].push_back(Ball(r,c,m,s,d)); } for(int move=0; move<K; move++){ vector<Ball> tmp; //1번 : 모든 파이어볼 자신 방향, 속력 만큼 이동 for(int i = 1; i<=N; i++){ for(int j = 1; j<=N; j++){ if(map[i][j].size()==0) continue; vector<Ball>::iterator iter; for(iter=map[i][j].begin(); iter!=map[i][j].end(); iter++){ Ball ball = *iter; int nr = i + dr[ball.d] * ball.s; int nc = j + dc[ball.d] * ball.s; if(nr<1 || nr>N ){ nr = modFunc(nr); if(nr==0){nr = N;} } if(nc<1 || nc>N) { nc = modFunc(nc); if(nc==0){nc = N;} } tmp.push_back(Ball(nr,nc,ball.m, ball.s, ball.d)); map[i][j].erase(iter); --iter; } } } for(int i = 0; i<tmp.size(); i++){ Ball ball = tmp[i]; map[ball.r][ball.c].push_back(ball); } //2번 for(int i = 1; i<=N; i++){ for(int j = 1; j<=N; j++){ vector<Ball> tmpBallVec = map[i][j]; if(tmpBallVec.size()>=2){ int sumM=0, sumS=0; bool EorO = isAllEorO(i, j); for(int k=0; k<tmpBallVec.size(); k++){ //그 칸에 있는 볼 개수만큼 sumM += map[i][j][k].m; sumS += map[i][j][k].s; } //정리 if(sumM/5==0) { map[i][j].clear(); //2. 그 칸에 있던 볼들 클리어 } else{ map[i][j].clear(); initdArr(EorO); for(int f = 0; f<4; f++){ //파이어 볼 4개로 나눠짐 map[i][j].push_back(Ball(i,j,sumM/5, sumS/tmpBallVec.size(), dArr[f])); } } } } } } int answer = 0; for(int i = 1; i<=N; i++){ for(int j = 1; j<=N; j++){ for(int k = 0; k<map[i][j].size(); k++){ answer += map[i][j][k].m; } } } cout << answer; return 0; }
bbad45fc74447e80d61a3c4eb742e734e334ae24
727a4f69396018f8db516c214fabe92e046f80ba
/Code/11028233_MeshDeformation/System.cpp
1e372b6688eafcff143db024c03be3e455059340
[]
no_license
aleksejleskin/MeshlessDeformation
7aa075d5998222cc204b40a10f74cbe74e1b74c4
909634bcf2488f973937afc400246f2282019279
refs/heads/master
2021-01-02T08:14:06.464541
2014-08-20T00:30:05
2014-08-20T00:30:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,096
cpp
System.cpp
#include "System.h" namespace { System* tmpSystem = 0; } //Call the windows procedure before the initalise has been called // this needs to be done so we can have the window proc private LRESULT CALLBACK ForwardProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { return tmpSystem->WndProc(hwnd, message, wParam, lParam); } System::System(int windowWidth, int windowHeight) : m_windowWidth(windowWidth), m_windowHeight(windowHeight), m_hwnd(0), m_hInstance(0), m_shutdown(false), m_windowName("Project: GreenLight"), m_resizing(false) { //assign the tmpSystem which called the forward Prox //to this instance tmpSystem = this; } System::~System() { if(!m_shutdown) { Shutdown(); } } bool System::Initialise(HINSTANCE hInstance, HINSTANCE pInstance, LPWSTR cmdLine, int cmdShow) { //Initalise the window if(!InitialiseWindow(hInstance, pInstance, cmdLine, cmdShow)) { MessageBoxA(NULL, "Failed to initialise the window", "ERROR", MB_OK | MB_ICONERROR); return false; } //Initalise D3D if(!m_dxGraphics.InitialiseDX(m_hwnd,m_windowWidth, m_windowHeight)) { MessageBoxA(NULL, "Failed to initialise D3D", "ERROR", MB_OK | MB_ICONERROR); return false; } //Initalise DInput if(!m_directInput.InitialiseDirectInput(m_hInstance, m_hwnd)) { MessageBoxA(NULL, "Failed to initialise DInput", "ERROR", MB_OK | MB_ICONERROR); return false; } return true; } //Main window procedure LRESULT System::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (TwEventWin(hwnd, message, wParam, lParam)) return 0; // Event has been handled by AntTweakBar PAINTSTRUCT paintStruct; HDC hdc; switch(message) { case WM_PAINT: hdc = BeginPaint(hwnd, &paintStruct); EndPaint(hwnd, &paintStruct); break; case WM_SIZE: //RESIZE BUFFERS WHEN WINDOW CHANGED m_windowWidth = LOWORD(lParam); m_dxGraphics.SetWindowWidth(m_windowWidth); m_windowHeight = HIWORD(lParam); m_dxGraphics.SetWindowHeight(m_windowHeight); if(m_dxGraphics.GetDevice()) { if( wParam == SIZE_MAXIMIZED) { m_dxGraphics.Rebuild(hwnd); } if(!m_resizing) { m_dxGraphics.Rebuild(hwnd); } } break; case WM_ENTERSIZEMOVE: //check to see if the user is resizing the window m_resizing = true; break; case WM_EXITSIZEMOVE: //check to see if the user has stopped resizing the window m_resizing = false; m_dxGraphics.Rebuild(hwnd); break; case WM_MENUCHAR: //stops beeping when we alt enter to go fullscreen return MAKELRESULT(0, MNC_CLOSE); case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, message, wParam, lParam); break; } return 0; } void System::Shutdown() { if(!m_shutdown) { m_dxGraphics.Shutdown(); m_shutdown = true; } } bool System::Done() { //If the message = quit then exit the game loop if(m_msg.message == WM_QUIT) { return true; } //Check the next message and process it if(PeekMessage(&m_msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&m_msg); DispatchMessage(&m_msg); } return false; } bool System::InitialiseWindow(HINSTANCE hInstance, HINSTANCE pInstance, LPWSTR cmdLine, int cmdShow) { m_hInstance = hInstance; UNREFERENCED_PARAMETER(cmdLine); UNREFERENCED_PARAMETER(pInstance); //Set up the window using this class desc WNDCLASSEX wnd = { 0 }; wnd.cbSize = sizeof(WNDCLASSEX); wnd.style = CS_HREDRAW | CS_VREDRAW; wnd.lpfnWndProc = ForwardProc; wnd.hInstance = m_hInstance; wnd.hCursor = LoadCursor(NULL, IDC_ARROW); wnd.hbrBackground = (HBRUSH)(COLOR_WINDOW); wnd.lpszMenuName = NULL; wnd.lpszClassName = "wndClass"; //If the class fails to register then return false, (in Debug will also throw a messagebox error) if(!RegisterClassEx(&wnd)) { #if defined (DEBUG) || (_DEBUG) MessageBox(NULL, "The window class failed to register!", "ERROR!", MB_OK | MB_ICONERROR); #endif return false; } //Describe the window dimensions using the RECT struct RECT rc = {0, 0, m_windowWidth, m_windowHeight}; //Creates the window using the previous class we made m_hwnd = CreateWindowA("wndClass", m_windowName.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, (rc.right - rc.left), (rc.bottom - rc.top) , NULL, NULL, m_hInstance, NULL); //If the window failed to create return false (in Debug will also throw a messagebox error) if(!m_hwnd) { #if defined (DEBUG) || (_DEBUG) MessageBox(NULL, "The window failed to create", "ERROR!", MB_OK | MB_ICONERROR); #endif return false; } //Display the window ShowWindow(m_hwnd, cmdShow); return true; } HINSTANCE System::GetHinstance() { return m_hInstance; } HWND System::GetHwnd() { return m_hwnd; } MSG System::GetMsg() { return m_msg; } int System::GetWindowWidth() const { return m_windowWidth; } int System::GetWindowHeight() const { return m_windowHeight; } float System::GetAspectRatio() const { return (float) m_windowWidth / m_windowHeight; } DxGraphics* System::GetDX() { return &m_dxGraphics; } Timer* System::GetGameTimer() { return &m_gameTimer; } DirectInput* System::GetDirectInput() { return &m_directInput; }
5e84554349fda58800977b50248336093564404d
04d6e7e9aa214bc31399f0a5c9f45a827a73e119
/Arduino/Sketches/waterLevelRF/waterLevelRF_RX/waterLevelRF_RX.ino
815c388773b5c541f4b1d3c5e6b3d53e84eb9843
[]
no_license
cbrekkeseter/workspace
5ec7e63030b10209926abbbd0774699ac9bc3cbc
289e193fcb62335535a016f31b81767e24ce5dbc
refs/heads/master
2020-04-02T02:12:27.440589
2018-10-20T11:18:56
2018-10-20T11:18:56
153,897,257
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
ino
waterLevelRF_RX.ino
//RX module on water level system //Written By : Christoffer Brekkeseter // 1buzzer.03.201blueLed #include <VirtualWire.h> /************Defines***************/ #define ledPin 13 #define buzzer 7 #define blueLed 6 #define loSensor 5 #define midSensor 4 #define highSensor 3 #define RX_pin 2 /************Constants************/ const int outputPin[] = {loSensor, midSensor, highSensor, blueLed, buzzer}; const int timerLimit = 20000; const int blinkTimerLimit = 2000; /************Variables************/ int prevCase = 0; int currentCommand, previousCommand; long timer, blinkTimer; void setup() { vw_set_rx_pin(RX_pin); vw_setup(2000); // Bits per sec // set output pins for (int i = 0; i < sizeof(outputPin) / sizeof(int); i++) { pinMode(outputPin[i], OUTPUT); } vw_rx_start(); // Start the receiver PLL running } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) // Non-blocking { timer = millis(); digitalWrite(ledPin, HIGH); digitalWrite(blueLed, LOW); /**************************ALL LEDS OFF************************/ if (buf[0] == '0') { for (int i = 0; i < sizeof(outputPin) / sizeof(int); i++) { digitalWrite(outputPin[i], LOW); } currentCommand = 0; } /****************************loSensor**************************/ if (buf[0] == '1') currentCommand = 1; /****************************midSensor*************************/ if (buf[0] == '2') currentCommand = 2; /****************************highSensor**************************/ if (buf[0] == '3') currentCommand = 3; /****************************TESTFUNC**************************/ if (buf[0] == '4') { for (int i = 0; i < 6; i++) { digitalWrite(blueLed, !digitalRead(blueLed)); tone(buzzer, 1200); delay(500); } noTone(buzzer); } // indicating led on board delay(20); digitalWrite(ledPin, LOW); } if (currentCommand != previousCommand) { tone(buzzer, 1200); delay(100); noTone(buzzer); } // If tank is getting full if (currentCommand == 3) { for (int i = 0; i < 2; i++) { for (int i = 0; i < currentCommand; i++) { digitalWrite(outputPin[i], HIGH); } delay(50); for (int i = 0; i < currentCommand; i++) { digitalWrite(outputPin[i], LOW); } tone(buzzer, 1200); delay(100); noTone(buzzer); } } // // if no signal is received if ((millis() - timer) > timerLimit) { timer = millis(); digitalWrite(blueLed, HIGH); for (int i = 0; i < 3; i++) { tone(buzzer, 1200); delay(50); noTone(buzzer); delay(50); } } if ((previousCommand != currentCommand) || (millis() - blinkTimer) > blinkTimerLimit) { // light leds for (int i = 0; i < currentCommand; i++) { digitalWrite(outputPin[i], HIGH); delay(50); } // shut off leds delay(150); for (int i = 0; i < currentCommand; i++) { digitalWrite(outputPin[i], LOW); } blinkTimer = millis(); } previousCommand = currentCommand; }
1445eb60dbeaaa805168a769600f54eab8642919
09a74a6a65f74f8602a36982f5a52903857944cf
/threadpool.h
692669075e6fc6392d23391c17fb9be847c911d2
[]
no_license
YJYandHCX/cpp-static-http-server
76d2996669d7841a3845e042350b3e553bf680ae
f6ab5542eca3e972624ca24e2651a0daed65043b
refs/heads/master
2020-11-29T08:08:54.386626
2019-12-25T08:50:23
2019-12-25T08:50:23
230,066,084
1
0
null
null
null
null
GB18030
C++
false
false
1,846
h
threadpool.h
#pragma once #include <vector> #include <thread> #include <condition_variable> #include <mutex> #include <deque> #include <atomic> //#include <windows.h> #include <iostream> #include <unistd.h> #include "http_req.h" #define T HTTP_R* using namespace std; class ThreadPool { public: //ThreadPool(); ThreadPool(int mtn, int mr); ~ThreadPool(); void stop(); bool addTask(HTTP_R* a); void run(int id); private: int m_thread_num; // max thread numbers vector<thread> threads; int m_request; // max requests numbers deque<HTTP_R*> tasks_que; // task deque std::mutex mu; condition_variable cond; atomic<bool>is_stop; }; ThreadPool::ThreadPool(int mtn, int mr) { m_thread_num = mtn; m_request = mr; is_stop = false; for (int i = 0; i < m_thread_num; i++) { auto tmp = thread(&ThreadPool::run, this, i); tmp.detach(); //全部设置成分离线程 threads.push_back(move(tmp));//因为线程是不能拷贝的,所以只能用移动语义 } } ThreadPool::~ThreadPool() {is_stop = true;}; void ThreadPool::stop() { is_stop = true; usleep(10000); return; } bool ThreadPool::addTask(HTTP_R* a) { unique_lock<mutex> l(mu, try_to_lock); if (l) { int size = tasks_que.size(); if (size >= m_request) { l.unlock(); return false; } //a->process(); tasks_que.push_back(a); l.unlock(); return true; } return false; } void ThreadPool::run(int id) { cout << this_thread::get_id() << " " << id << endl; while (!is_stop) { unique_lock<mutex> l(mu, try_to_lock); if (l) { if (!tasks_que.empty()) { auto req = tasks_que.front(); tasks_que.pop_front(); l.unlock(); cout << "this is thread: " << id << endl; req->do_process(); } else { l.unlock(); } } } return; }
e40f228f815f2281579bc772576a4577570a857d
a600f7f7833a549996dc14b051e4ec56e540b7bf
/src/dashboard.h
f8948ba603b388754654a7cef2b97a0595195212
[]
no_license
Alex-Canales/Topology-Taker
aeb2413edf398b7f84f81da516f2950d061aff50
49861854d2dff473c3e947fbe996ac1bcb7fd389
refs/heads/master
2016-09-01T14:46:59.308389
2016-01-08T16:38:57
2016-01-08T16:38:57
45,270,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
dashboard.h
#ifndef _DASHBOARD_H_ #define _DASHBOARD_H_ #include <string> #include <curl/curl.h> // Defining error code #define DASHBOARD_CONNECTION_ERROR -1 #define DASHBOARD_FALSE 0 #define DASHBOARD_TRUE 1 //TODO: implement error code for each function /** * Used to communicate to the machine. * Because of the callback functions, everything is static. Plus this class * is unique in this program. */ class Dashboard { public: static std::string baseURL; static CURL *curl; static struct curl_slist *headers; static bool isRunningHolder; //Do not check this variable directly! static void (*callback)(bool, float, float, float); // Parsing the data received on the URL /status static size_t dataParserPosition(char* buf, size_t size, size_t nmemb, void* up); static void initialize(std::string baseURL, void (*callbackGetPosition)(bool, float, float, float)); static void cleanAll(); static void setBaseURL(std::string url); //xxx.xxx.xxx.xxx:xxxx static void setCallback(void (*callbackGetPosition)(bool, float, float, float)); static bool getPosition(); static bool setPosition(float x, float y, float z); static bool sendGCodeCommand(char *command); static size_t dataParserStatus(char* buf, size_t size, size_t nmemb, void* up); static int isRunning(); //Test if the machine is running (the state) }; #endif
600594bcb1daa7713205748defc87b16a59935a8
38a03ad3621a3b276f8e9782f6970caed438074d
/src/raytrace.cpp
3566332d6a87c743d10296dc2249ef4f15ee30a0
[]
no_license
bmatejek/Graphics
8f181062b433a4d5e857aee4227aaecaecaa4092
f84062362ff0839bd5d0f6342ca32543a94a6bfa
refs/heads/master
2021-05-29T19:20:57.459996
2013-05-14T05:12:08
2013-05-14T05:12:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,732
cpp
raytrace.cpp
// Source file for raytracing code // Include files #include "R2/R2.h" #include "R3/R3.h" #include "R3Scene.h" #include "raytrace.h" #include <limits> using namespace std; //////////////////////////////////////////////////////////////////////// // Create image from scene // // This is the main ray tracing function called from raypro // // "width" and "height" indicate the size of the ray traced image // (keep these small during debugging to speed up your code development cycle) // // "max_depth" indicates the maximum number of secondary reflections/transmissions to trace for any ray // (i.e., stop tracing a ray if it has already been reflected max_depth times -- // 0 means direct illumination, 1 means one bounce, etc.) // // "num_primary_rays_per_pixel" indicates the number of random rays to generate within // each pixel during antialiasing. This argument can be ignored if antialiasing is not implemented. // // "num_distributed_rays_per_intersection" indicates the number of secondary rays to generate // for each surface intersection if distributed ray tracing is implemented. // It can be ignored otherwise. // //////////////////////////////////////////////////////////////////////// //quadratic formula, first answer, -1 if no answer static double Quad1(double a, double b, double c) { double d = b*b-4*a*c; if (d < 0) return -1; double total = (-b + sqrt(d))/(2*a); return total; } //quadratic formula, second answer, -1 if no answer static double Quad2(double a, double b, double c) { double d = b*b-4*a*c; if (d < 0) return -1; double total = (-b - sqrt(d))/(2*a); return total; } // create rays through a pixel, as in lecture R3Ray ConstructRayThroughPixel(int x, int y, int width, int height, R3Point eye, R3Vector towards, R3Vector up, R3Vector right, double xfov, double yfov) { R3Point p = towards.Point(); p.Rotate(up,xfov*(1-(2.0*x)/width)); p.Rotate(right,-1*(yfov*(1-(2.0*y)/height))); return R3Ray(eye,eye+p); } // Create the specular ray, by mirroring over tangent plane R3Ray SpecularRay(R3Ray r, R3Intersect hit) { R3Point p = hit.pos; R3Vector vect = R3Vector(r.Vector()); R3Plane plane = R3Plane(hit.norm,0); vect.Mirror(plane); return R3Ray(p, vect); } // Create Transmission ray, by simply changing the hit position R3Ray TransmissionRay(R3Ray r, R3Intersect hit) { R3Point p = hit.pos; R3Vector vect = R3Vector(r.Vector()); return R3Ray(p, vect); } // Create Refraction Ray using Snell's law R3Ray RefractionRay(R3Ray r, R3Intersect hit, double indexinc, double indexout) { R3Vector n = hit.norm; R3Vector l = r.Vector(); n.Normalize(); l.Normalize(); l *= -1; double cosi = n.Dot(l); double sini = sqrt(1-cosi*cosi); double sinr = indexinc*sini / indexout; double cosr = sqrt(1-sinr*sinr); R3Vector t = (indexinc*cosi/indexout - cosr)*n - indexinc*l/indexout; R3Point p = hit.pos; t.Normalize(); return R3Ray(p, t); } // find intersection with plane, as in lecture R3Intersect PlaneIntersect(R3Ray r, R3Plane p) { R3Intersect sect = R3Intersect(); R3Point p0 = r.Start(); R3Vector V = r.Vector(); R3Vector N = p.Normal(); double d = p.D(); // parallel lines if (V.Dot(N) == 0) { sect.intersected = false; return sect; } double t = -1*(N.Dot(p0.Vector())+d)/(V.Dot(N)); R3Vector posv = p0.Vector()+t*V; R3Point pos = posv.Point(); sect.intersected = true; sect.pos = pos; sect.norm = N; if (sect.norm.Dot(r.Vector()) > 0) sect.norm *= -1; sect.t = t; return sect; } // intersection with cylinder R3Intersect CylinderIntersect(R3Ray r, R3Cylinder cyl) { // circular part R3Intersect sect = R3Intersect(); sect.intersected = false; sect.t = -1; double x0 = r.Start().X(); double z0 = r.Start().Z(); double xc = cyl.Center().X(); double yc = cyl.Center().Y(); double zc = cyl.Center().Z(); double xr = r.Vector().X(); double zr = r.Vector().Z(); double rad = cyl.Radius(); double a = zr*zr+xr*xr; double b = 2*xr*(x0-xc)+2*zr*(z0-zc); double c = (x0-xc)*(x0-xc)+(z0-zc)*(z0-zc)-rad*rad; double t1 = Quad1(a,b,c); double t2 = Quad2(a,b,c); double t = min(t1,t2); // if one answer is negative, either ray starts inside, or never hits if (t < 0) { if (t1 < 0 && t2 < 0) return sect; t = max(t1,t2); } R3Point pt = r.Point(t); if (yc - rad/2 < pt.Y() && pt.Y() < yc + rad/2) { sect.intersected = true; sect.t = t; sect.pos = pt; R3Vector v = pt - cyl.Center(); v.SetY(0); v.Normalize(); sect.norm = v; } R3Intersect secttop = R3Intersect(); secttop.intersected = false; secttop.t = -1; // top face R3Point ptop = cyl.Center() + R3Point(0,cyl.Height()/2,0); R3Vector normal = R3Vector(0,1,0); R3Plane pltop = R3Plane(ptop,normal); secttop = PlaneIntersect(r,pltop); double d = R3Distance(secttop.pos, ptop); if (d > cyl.Radius()) { secttop.intersected = false; } R3Intersect sectbottom = R3Intersect(); sectbottom.intersected = false; sectbottom.t = -1; // bottom face R3Point pbottom = cyl.Center() + R3Point(0,-cyl.Height()/2,0); normal = R3Vector(0,-1,0); R3Plane plbottom = R3Plane(pbottom,normal); sectbottom = PlaneIntersect(r,plbottom); d = R3Distance(sectbottom.pos, pbottom); if (d > cyl.Radius()) { sectbottom.intersected = false; } if (secttop.intersected && !sect.intersected) sect = secttop; if (secttop.intersected && sect.intersected) { if (secttop.t < sect.t) sect = secttop; } if (sectbottom.intersected && !sect.intersected) sect = sectbottom; if (sectbottom.intersected && sect.intersected) { if (sectbottom.t < sect.t) sect = sectbottom; } return sect; } // intersect with cone R3Intersect ConeIntersect(R3Ray r, R3Cone cone) { R3Intersect sect = R3Intersect(); sect.intersected = false; sect.t = -1; double eps = 1e-12; double h = cone.Height(); double px = cone.Center().X(); double py = cone.Center().Y() + h/2; double pz = cone.Center().Z(); double rx = r.Start().X(); double ry = r.Start().Y(); double rz = r.Start().Z(); double vx = r.Vector().X(); double vy = r.Vector().Y(); double vz = r.Vector().Z(); double rad = cone.Radius(); double a = vx*vx/rad/rad + vz*vz/rad/rad-vy*vy/h/h; double b = 2*(px-rx)*(-1*vx)/rad/rad + 2*(pz-rz)*(-1*vz)/rad/rad - 2*(py-ry)*(-1*vy)/h/h; double c = (px-rx)*(px-rx)/rad/rad +(pz-rz)*(pz-rz)/rad/rad -(py-ry)*(py-ry)/h/h; double t1 = Quad1(a,b,c); double t2 = Quad2(a,b,c); double t = min(t1,t2); if (t < -eps) { if (t1 < -eps && t2 < -eps) return sect; t = max(t1,t2); } R3Point pt = r.Point(t); if (pt.Y() > py || pt.Y() < py - h) { sect.intersected = false; } else { sect.intersected = true; sect.t = t; sect.pos = pt; R3Vector v = pt - cone.Center(); v.SetY(0); v.Normalize(); sect.norm = v; } R3Intersect basesect = R3Intersect(); basesect.intersected = false; basesect.t = -1; R3Point midbase = R3Point(px,py-h,pz); R3Plane plane = R3Plane(midbase,R3Vector(0,-1,0)); basesect = PlaneIntersect(r,plane); if (R3Distance(basesect.pos,midbase) > rad) { basesect.intersected = false; } if (basesect.intersected && sect.intersected) { if (basesect.t < sect.t) return basesect; return sect; } if (basesect.intersected) { return basesect; } return sect; return sect; } // intersect with box R3Intersect BoxIntersect(R3Ray r, R3Box b) { double eps = 1e-12; R3Plane *p = new R3Plane[6]; p[0] = R3Plane(b.Min(), R3Vector(0,0,-1)); p[1] = R3Plane(b.Min(), R3Vector(0,-1,0)); p[2] = R3Plane(b.Min(), R3Vector(-1,0,0)); p[3] = R3Plane(b.Max(), R3Vector(0,0,1)); p[4] = R3Plane(b.Max(), R3Vector(0,1,0)); p[5] = R3Plane(b.Max(), R3Vector(1,0,0)); R3Intersect answer = R3Intersect(); answer.intersected = false; double tmin = std::numeric_limits<double>::infinity(); R3Intersect *i = new R3Intersect[6]; for (int j = 0; j < 6; j++) { i[j] = PlaneIntersect(r,p[j]); if (i[j].intersected == true) { if (i[j].t < tmin && i[j].t > 0) { if (j % 3 == 0) { if (i[j].pos.X() > b.Min().X() -eps && i[j].pos.X() < b.Max().X() +eps ) { if (i[j].pos.Y() > b.Min().Y() -eps && i[j].pos.Y() < b.Max().Y() +eps) { answer = i[j]; tmin = i[j].t; } } } else if (j % 3 == 1) { if (i[j].pos.X() > b.Min().X() -eps && i[j].pos.X() < b.Max().X()+eps ) { if (i[j].pos.Z() > b.Min().Z()-eps && i[j].pos.Z() < b.Max().Z()+eps ) { answer = i[j]; tmin = i[j].t; } } } else if (j % 3 == 2) { if (i[j].pos.Z() > b.Min().Z()-eps && i[j].pos.Z() < b.Max().Z()+eps ) { if (i[j].pos.Y() > b.Min().Y()-eps && i[j].pos.Y() < b.Max().Y() +eps) { answer = i[j]; tmin = i[j].t; } } } } } } return answer; } // intersect with a triangle, geometrically as in lecture R3Intersect TriIntersect(R3Ray r, R3MeshFace f) { R3Plane plane = f.plane; R3Intersect sect = PlaneIntersect(r,plane); if (sect.intersected == false) return sect; for (int i = 0; i < 3; i++) { R3Vector p0 = r.Start().Vector(); R3Vector v1 = f.vertices[i]->position.Vector() + (-1)*p0; R3Vector v2 = f.vertices[(i+1)%3]->position.Vector() + (-1)*p0; v2.Cross(v1); R3Vector n1 = v2; n1.Normalize(); R3Plane p = R3Plane(r.Start(),n1); if (R3SignedDistance(p,sect.pos) < 0) { sect.intersected = false; return sect; } } return sect; } // intersect with a triangle mesh, by going through all the triangles R3Intersect TriMeshIntersect(R3Ray r, R3Mesh m) { double currentmin = std::numeric_limits<double>::infinity(); R3Intersect finalsect; finalsect.intersected = false; finalsect.t = currentmin; for (int i = 0; i < m.NFaces(); i++) { R3MeshFace *f = m.Face(i); R3Intersect sect = TriIntersect(r,*f); if (sect.intersected == true) { if (sect.t < currentmin && sect.t > 0) { currentmin = sect.t; finalsect = sect; } } } return finalsect; } // intersect with a sphere, as in lecture R3Intersect SphereInt(R3Ray r, R3Sphere s) { double eps = 1e-12; R3Intersect i = R3Intersect(); double d = R3Distance(s.Center(),r); if (d > s.Radius()) { i.intersected = false; } else if (R3Distance(r.Start()+eps*r.Vector(),s.Center()) < s.Radius()) { i.intersected = true; double xc = r.Start().X() - s.Center().X(); double yc = r.Start().Y() - s.Center().Y(); double zc = r.Start().Z() - s.Center().Z(); double xt = r.Vector().X(); double yt = r.Vector().Y(); double zt = r.Vector().Z(); double a = xt*xt + yt*yt + zt*zt; double b = 2*xt*xc + 2*yt*yc + 2*zt*zc; double c = xc*xc+ yc*yc + zc*zc- s.Radius()*s.Radius(); double q1 = Quad1(a,b,c); double q2 = Quad2(a,b,c); // checks inside or if never hits if (q1 > 0) { i.t = q1; i.pos = R3Point(r.Start()+q1*r.Vector()); i.norm = -1*R3Vector(i.pos.X()-s.Center().X(),i.pos.Y()-s.Center().Y(),i.pos.Z()-s.Center().Z()); i.norm.Normalize(); } else { i.t = q2; i.pos = R3Point(r.Start()+q2*r.Vector()); i.norm = -1*R3Vector(i.pos.X()-s.Center().X(),i.pos.Y()-s.Center().Y(),i.pos.Z()-s.Center().Z()); i.norm.Normalize(); } return i; } // two hits else { i.intersected = true; //necessary dist double nec = sqrt(s.Radius()*s.Radius() - d*d); R3Vector v = R3Vector(s.Center()-r.Start()); v.Project(r.Vector()); double currt; if (r.Vector().X() != 0) currt = v.X()/r.Vector().X(); else if (r.Vector().Y() != 0) currt = v.Y()/r.Vector().Y(); else currt = v.Z()/r.Vector().Z(); double distpert = r.Vector().Length(); double realt = currt - nec/distpert; i.t = realt; i.pos = R3Point(r.Start()+realt*r.Vector()); i.norm = R3Vector(i.pos.X()-s.Center().X(),i.pos.Y()-s.Center().Y(),i.pos.Z()-s.Center().Z()); i.norm.Normalize(); } return i; } // find intensity at a point given a light, using formulas from lecture R3Rgb Intensity(R3Light light, R3Point p) { // directional light R3Rgb i0 = light.color; if (light.type == R3_DIRECTIONAL_LIGHT) { return i0; } double kc = light.constant_attenuation; double kl = light.linear_attenuation; double kq = light.quadratic_attenuation; double d = R3Distance(light.position, p); // point light if (light.type == R3_POINT_LIGHT) { return (i0 / (kc + kl*d + kq*d*d)); } // spot light if (light.type == R3_SPOT_LIGHT) { R3Vector vectd = light.direction; R3Vector vectl = p - light.position; vectd.Normalize(); vectl.Normalize(); double dot = vectd.Dot(vectl); double acost = acos(dot); if (acost > light.angle_cutoff) return R3Rgb(0,0,0,0); R3Rgb ret = i0*(pow(dot,light.angle_attenuation))/(kc + kl*d + kq*d*d); return ret; } return i0; } // calculate diffuse intensity from lecture R3Rgb DiffuseIntensity(R3Intersect sect, R3Light light, R3Material mat) { R3Vector l = (light.position-sect.pos); if (light.type == R3_DIRECTIONAL_LIGHT) { l = -1*light.direction; } l.Normalize(); sect.norm.Normalize(); // if on wrong side of the material, gives 0 light if (sect.norm.Dot(l) < 0) return R2Pixel(0,0,0,0); R3Rgb total = mat.kd*Intensity(light,sect.pos)*(sect.norm.Dot(l)); total.Clamp(); return total; } // calcualte specular intensity from lecture R3Rgb SpecularIntensity(R3Intersect sect, R3Light light, R3Material mat, R3Point camera) { R3Vector r = (sect.pos-light.position); r.Normalize(); if (light.type == R3_DIRECTIONAL_LIGHT) { r = light.direction; } R3Plane p = R3Plane(sect.norm,0); r.Mirror(p); R3Vector v = camera - sect.pos; r.Normalize(); v.Normalize(); // if on wrong side, give 0 light if (v.Dot(r) < 0) return R2Pixel(0,0,0,0); R3Rgb total = mat.ks*pow((v.Dot(r)),mat.shininess)*Intensity(light,sect.pos); total.Clamp(); return total; } // goes through scene, finds closest intersection and returns it R3Intersect ComputeIntersect(R3Scene *scene, R3Node *node, R3Ray *r) { //Check for intersection with shape R3Intersect shape_intersection; // do transformation R3Matrix trans = node->transformation; trans.Invert(); (*r).Transform(trans); // find intersection of current shape if (node->shape != NULL) { if (node->shape->type == R3_BOX_SHAPE) { shape_intersection = BoxIntersect(*r, *node->shape->box); shape_intersection.node = node; } else if (node->shape->type == R3_SPHERE_SHAPE) { shape_intersection = SphereInt(*r, *node->shape->sphere); shape_intersection.node = node; } else if (node->shape->type == R3_MESH_SHAPE) { shape_intersection = TriMeshIntersect(*r, *node->shape->mesh); shape_intersection.node = node; } else if (node->shape->type == R3_CYLINDER_SHAPE) { shape_intersection = CylinderIntersect(*r, *node->shape->cylinder); shape_intersection.node = node; } else if (node->shape->type == R3_CONE_SHAPE) { shape_intersection = ConeIntersect(*r, *node->shape->cone); shape_intersection.node = node; } } // if node was null, no closests intersection, go on to children and find closests else { R3Intersect closest = R3Intersect(); closest.intersected = false; closest.t = std::numeric_limits<double>::infinity(); for (unsigned int i = 0; i < node->children.size(); i++) { R3Intersect boxsect = BoxIntersect(*r,node->children[i]->bbox); if (boxsect.intersected && boxsect.t < closest.t) { R3Intersect childsect = ComputeIntersect(scene, node->children[i],r); if (childsect.intersected == true) { if (childsect.t < closest.t) { if (childsect.t > 1e-12) closest = childsect; } } } } // uninvert trans.Invert(); closest.pos.Transform(trans); closest.norm.Transform(trans); (*r).Transform(trans); closest.t = R3Distance(closest.pos, (*r).Start()); return closest; } // if no children, uninvert and return the shapes intersection if (node->children.size() == 0) { trans.Invert(); (*r).Transform(trans); return shape_intersection; } // if it didnt intersect the bounding shape, no need to keep going if (shape_intersection.intersected == false) { trans.Invert(); (*r).Transform(trans); return shape_intersection; } // if we are here, the node is a bounding shape for the other things, so the closest should be infinitely far away. Look through children and find closest if it exists. R3Intersect closest = R3Intersect(); closest.intersected = false; closest.t = std::numeric_limits<double>::infinity(); for (unsigned int i = 0; i < node->children.size(); i++) { R3Intersect boxsect = BoxIntersect(*r,node->children[i]->bbox); if (boxsect.intersected && boxsect.t < closest.t) { R3Intersect childsect = ComputeIntersect(scene, node->children[i],r); if (childsect.intersected == true) { if (childsect.t < closest.t) { if (childsect.t > 1e-12) closest = childsect; } } } } trans.Invert(); closest.pos.Transform(trans); closest.norm.Transform(trans); (*r).Transform(trans); closest.t = R3Distance(closest.pos, (*r).Start()); return closest; } // find the Vector the points towards a light given a point and a light source. R3Vector LightVect(R3Light *light, R3Point p) { R3Vector v; if (light->type == R3_DIRECTIONAL_LIGHT) { v = light->direction; v.Normalize(); return v; } v = p - light->position; v.Normalize(); return v; } // finds a ray going towards a light given a point and light source R3Ray LightRay(R3Light *light, R3Point p) { return R3Ray(p, -1*LightVect(light,p)); } // finds the distance to a certain light double LightDist(R3Light *light, R3Point p) { if (light->type == R3_DIRECTIONAL_LIGHT) return std::numeric_limits<double>::infinity(); return R3Distance(light->position,p); } // calcualte phong illumination as in lecture R3Rgb Phong(R3Scene *scene, R3Ray r, R3Intersect hit) { R3Rgb total = R2Pixel(0,0,0,0); total += (hit.node->material->ka)*(scene->ambient); total += (hit.node->material->emission); for (int i = 0; i < scene->NLights(); i++) { R3Light *light = scene->Light(i); // calculate shadow, if shadow ray intersects and distance is closer than distance to light, cast shadow double shadown = 1.0; R3Ray shadowray = LightRay(light,hit.pos); R3Intersect shadowsect = ComputeIntersect(scene, scene->Root(), &shadowray); if (shadowsect.intersected == true) { if (shadowsect.t < LightDist(light,hit.pos)) shadown = 0.0; } total += shadown*DiffuseIntensity(hit, *light, *hit.node->material); if (&hit != NULL) { if(light != NULL && hit.node->material != NULL) { total += shadown*SpecularIntensity(hit, *light, *hit.node->material,r.Start()); } } } return total; } // computes the radiance given a ray and scene R3Rgb ComputeRadiance(R3Scene *scene, R3Ray ray, int max_depth, double currentindex) { //return R3Rgb(0,0,0,0); R3Intersect hit = ComputeIntersect(scene, scene->Root(),&ray); return ComputeRadiance(scene,ray,hit,max_depth, currentindex); } // computes radiance given a ray, scene and intersection, using phong illumination and other properties R3Rgb ComputeRadiance(R3Scene *scene, R3Ray r, R3Intersect hit, int max_depth, double currentindex) { if (hit.intersected == false) { return scene->background; } assert(hit.node != NULL); assert(hit.node->material != NULL); R3Rgb total = R2Pixel(0,0,0,0); total += Phong(scene, r, hit); if (max_depth > 0) { R3Rgb spec = ComputeRadiance(scene, SpecularRay(r,hit), max_depth-1,currentindex); total += (hit.node->material->ks)*spec; R3Rgb refract; if (currentindex == hit.node->material->indexofrefraction) { refract = ComputeRadiance(scene, RefractionRay(r,hit,currentindex,1), max_depth-1,1); } else { refract = ComputeRadiance(scene, RefractionRay(r,hit,currentindex,hit.node->material->indexofrefraction), max_depth-1,hit.node->material->indexofrefraction); } total += (hit.node->material->kt)*refract; R3Rgb trans = ComputeRadiance(scene, TransmissionRay(r,hit), max_depth-1,hit.node->material->indexofrefraction); total += (hit.node->material->kt)*trans; } return total; } // Makes picture by calling get color on reach ray, setting color of pixel. R2Image *RenderImage(R3Scene *scene, int width, int height, int max_depth, int num_primary_rays_per_pixel, int num_distributed_rays_per_intersection) { // Allocate image R2Image *image = new R2Image(width, height); if (!image) { fprintf(stderr, "Unable to allocate image\n"); return NULL; } for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { R3Ray r = ConstructRayThroughPixel(i,j,width,height,scene->Camera().eye,scene->Camera().towards,scene->Camera().up,scene->Camera().right,scene->Camera().xfov, scene->Camera().yfov); double currentindex = 1.0; R3Rgb radiance = ComputeRadiance(scene, r, max_depth, currentindex); image->SetPixel(i,j,radiance); } } return image; }
4daa2ec50b359d730282a46ebf645ced77a3cef6
e44bbf8b00b060f30043e00f5394aa075d81ae73
/src/DisplayBoard.cpp
1e106ee87f23e0c7409be6d11ac7218d790055e3
[]
no_license
jzych/LogicalImages
ddec86b73435ae58e57f5a415d0001212526239a
bd791102dcb0ebecaac0d3cc0045ee40bf3a09d1
refs/heads/master
2021-06-14T22:33:38.961057
2021-04-07T15:00:49
2021-04-07T15:00:49
182,974,596
0
0
null
2021-04-07T15:00:50
2019-04-23T08:53:52
C++
UTF-8
C++
false
false
5,290
cpp
DisplayBoard.cpp
#include "DisplayBoard.hpp" #include <algorithm> namespace { const char HORIZONTAL = '-'; const char VERTICAL = '|'; const char INTERSECTION = '+'; const char PADDING = ' '; std::string drawPadding(const unsigned int width, const char sign = PADDING); std::string drawEndLine(const unsigned int widthRows, const unsigned int width = 0); std::string drawBoardLine(const unsigned int width, const BLine & boardLine = {}); std::string drawColumns(const unsigned int maxElementsInRows, const unsigned int sizeCols, const unsigned int heightCol, const std::vector<std::string> & stringClues); std::vector<std::string> getFormattedColumns(const unsigned int sizeCols, const Lines & cluesCols); std::string drawRowOfColumns(const unsigned pos, const std::vector<std::string> & clues); std::string drawRow(const unsigned int maxElementsInRows, const Line & row); } namespace DisplayBoard { std::string display(const Board& b) { auto width = b.getSizeRows(); auto height = b.getSizeCols(); auto widthRows = b.getLongestCluesLenghtInRows(); auto heightCol = b.getLongestCluesLenghtInCols(); const Lines cluesRows = b.getCluesRows(); std::stringstream output; output << drawColumns(widthRows, width, heightCol, getFormattedColumns(heightCol, b.getCluesCols())); output << drawEndLine(widthRows, width) << "\n"; for (int i = 0; i < height; i++) { if(cluesRows.size() != height) output << drawRow(widthRows, {}); else output << drawRow(widthRows, cluesRows.at(i)); output << drawBoardLine(width, b.getBoardLines().at(i)) << "\n"; } output << drawEndLine(widthRows, width); return output.str() + "\n"; } } namespace { std::string drawPadding(const unsigned int width, const char sign /*= PADDING*/) { std::string result; for (auto it = 0; it < (width * 2); it++) result += sign; return result; } std::string drawEndLine(const unsigned int widthRows, const unsigned int width) { std::string result {INTERSECTION}; for (auto it = 0; it < (widthRows *2); it++) result += HORIZONTAL; result += INTERSECTION; if(width > 0) { for (auto it = 0; it < (width *2); it++) result += HORIZONTAL; result += INTERSECTION; } return result; } std::string drawBoardLine(const unsigned int width, const BLine & boardLine) { std::string result {VERTICAL}; for (const auto & it : boardLine) { result += static_cast<char>(it); result += static_cast<char>(it); } result += VERTICAL; return result; } std::string drawColumns(const unsigned int maxElementsInRows, const unsigned int sizeCols, const unsigned int heightCol, const std::vector<std::string> & stringClues) { std::string columns; columns += PADDING + drawPadding(maxElementsInRows); columns += drawEndLine(sizeCols) + "\n"; for (int i = heightCol; i > 0; --i) { columns += PADDING + drawPadding(maxElementsInRows); columns += VERTICAL; columns += drawRowOfColumns(i, stringClues); columns += VERTICAL; columns += "\n"; } return columns; } std::vector<std::string> getFormattedColumns(const unsigned int sizeCols, const Lines & cluesCols) { std::vector<std::string> stringLines; if(not cluesCols.empty()) for(const auto & clueCol : cluesCols) { std::string strline {}; std::transform(clueCol.begin(), clueCol.end(), std::back_inserter(strline), [&](const auto i) { return std::to_string(i).at(0); }); if(strline.size() < sizeCols) while (strline.size() != sizeCols) { strline.push_back(PADDING); } stringLines.emplace_back(strline); } return stringLines; } std::string drawRowOfColumns(const unsigned pos, const std::vector<std::string> & clues) { std::string columns; if(not clues.empty()) for(const auto & line : clues) { columns += PADDING; columns += line.at(pos - 1); } return columns; } std::string drawRow(const unsigned int maxElementsInRows, const Line & row) { std::string rows; rows += VERTICAL; if(row.empty()) { rows += drawPadding(maxElementsInRows); } else { if(row.size() < maxElementsInRows) { for(int i = maxElementsInRows - row.size(); i > 0; i--) { rows.push_back(PADDING); rows.push_back(PADDING); } } std::for_each(row.begin(), row.end(), [&](auto i) { rows += PADDING + std::to_string(i); }); } return rows; } }
21006cd02a9d41d37be3b6ba0b70f69798935716
3e410c5ef45cf03f979845d69207f0d11076350c
/Gen1.hpp
fd0a7ba497ec598adf331d96a282f8b6c7fc33df
[]
no_license
TheSpiritXIII/PokeCPP
dbb737e4871b98ba3ab0886e69b07fa3283516e0
eacbcac4f8f3bcea2832236f4151569086cc8b55
refs/heads/master
2016-09-03T06:22:29.551106
2014-11-22T01:36:37
2014-11-22T01:36:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
hpp
Gen1.hpp
/* * Copyright (c) 2014 Daniel Hrabovcak * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. **/ #pragma once #include "Monster.hpp" #include "Nature.hpp" namespace PokeCPP { namespace Gen1 { class Bulbasaur : public Monster { public: Bulbasaur(); virtual bool can_evolve_level_up(size_t) const; virtual Monster evolve_level_up(size_t) const; inline bool met_evolve_conditions() const { return get_level() == 16; } }; /*class Ivysaur : public Monster { public: Ivysaur(); virtual bool can_evolve_level_up(size_t) const; virtual Monster evolve_level_up(size_t) const; inline bool met_evolve_conditions() const { return get_level() == 32; } }; class Venusaur : public Monster { public: Venusaur(); };*/ } }
9924ffd7a0d3d6a2ab2f12203b4a9a670e826db3
22f57701df31b3182f3bcb83da729ecc584f8fb6
/December-21/c++_MaddyDinesh_currencyconvertor.cpp
3a9c3014f3d8695d4ecab4ee8a6beb9056e88591
[]
no_license
Prashant-Bharaj/A-December-of-Algorithms
e88640c711abbe2e6cac71cb4652dac243984484
7bbd56572f4ddc9648e90615ee810765544c56e4
refs/heads/master
2023-08-05T15:37:20.362561
2021-09-19T05:51:53
2021-09-19T05:51:53
287,055,360
0
0
null
2020-08-12T15:53:05
2020-08-12T15:53:04
null
UTF-8
C++
false
false
835
cpp
c++_MaddyDinesh_currencyconvertor.cpp
#include <iostream> using namespace std; int main() { // 1$ =.72 euro, 1$=0.60gbp, 1$ = 102.15 yen, 1$ = 1.10 CAD float AMOUNT; cout<<"Enter the amount in Dollar($):- "; cin>>AMOUNT; int select; cout<<" Enter 1 to convert the amount to EURO \n Enter 2 to convert the amount to GBP \n Enter 3 to convert the amount to YEN \n enter 4 to convert the amount to CAD"<<endl; cin>>select; switch(select) { case 1: cout<<AMOUNT<<" $ = "<<(AMOUNT*0.72)<<" EURO"<<endl; break; case 2: cout<<AMOUNT<<" $ = "<<(AMOUNT*0.60)<<" GBP"<<endl; break; case 3: cout<<AMOUNT<<" $ = "<<(AMOUNT*102.15)<<" YEN"<<endl; break; case 4: cout<<AMOUNT<<" $ = "<<(AMOUNT*1.10)<<" CAD"<<endl; break; } return 0; }
f9ba9404ddf63354ab4935c22b14b7f23f97dddf
fa594a758b73fd036ba0d047c91907d07c7b06b4
/ESP32_LCD_screen/ESP32_LCD_screen.ino
9d5442ba4425a704e1843a5c5ac3e17f64d6ac21
[]
no_license
RiverSchenck/Development
029e87b526ec17958bad351e246663326987bb12
0a84c9edec508ce58a376673ad0cb0b0738aaf71
refs/heads/master
2021-12-10T22:04:05.645131
2021-12-01T18:18:34
2021-12-01T18:18:34
143,210,081
0
0
null
null
null
null
UTF-8
C++
false
false
396
ino
ESP32_LCD_screen.ino
#include<LiquidCrystal.h> //VSS GRND //VDD + //V0 variable resistor (contrast) //RS pin 22 //RW GRND //Enable pin 23 //D4 pin 5 //D5 pin 18 //D6 pin 19 //D7 pin 21 //A 220 resistor (led) //K led GRND LiquidCrystal lcd(22, 23, 5, 18, 19, 21); void setup() { lcd.begin(16, 2); lcd.clear(); lcd.print("2x16 LCD Display"); } void loop() { lcd.setCursor(0,1); lcd.print("TEST"); }
5b2d9313dd368ab86d22e7ddac5a26d26cdbee10
5bef53b0dc9539a4953919f75fde1f0ebd20e9fb
/CF/4D.cpp
1591fcf1b831bcc50a156da4a3c941fa81539550
[]
no_license
atrin-hojjat/CompetetiveProgramingCodes
54c8b94092f7acf40d379e42e1f2c0fe8dab9b32
6a02071c3869b8e7cd873ddf7a3a2d678aec6d91
refs/heads/master
2020-11-25T10:51:23.200000
2020-10-08T11:12:09
2020-10-08T11:12:09
228,626,397
1
0
null
null
null
null
UTF-8
C++
false
false
1,971
cpp
4D.cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 5000 + 500 + 50 + 5; struct Envs { int h, w; int I; bool ok = true; } envs[MAXN]; const int Max = 1e6 + 6.66; queue<pair<int, pair<int, int>>> seg_queue; pair<int, int> seg[Max << 1]; int prv[Max]; void init_segment() { for(int i = 0; i < (Max << 1); i++) seg[i] = {0, -1}; } void alter(int i, pair<int, int> x) { i += Max; for(seg[i] = max(seg[i], x); i > 1; i >>= 1) seg[i >> 1] = max(seg[i], seg[i ^ 1]); } void push_to_queue(pair<int, pair<int, int>> xx) { seg_queue.push(xx); } void apply_queue() { while(seg_queue.size()) { alter(seg_queue.front().first, seg_queue.front().second); seg_queue.pop(); } } pair<int, int> get(int l, int r) { pair<int, int> ans = {0, -1}; for(l += Max, r += Max; l < r; l >>= 1, r >>= 1) { if(l & 1) ans = max(ans, seg[l++]); if(r & 1) ans = max(ans, seg[--r]); } return ans; } int main() { int n, H, W; scanf("%d %d %d", &n, &W, &H); W++, H++; for(int i = 0; i < n; i++) { scanf("%d %d", &envs[i].w, &envs[i].h); envs[i].I = i + 1; if(envs[i].w < W || envs[i].h < H) envs[i].ok = false; } sort(envs, envs + n, [](Envs x, Envs y) { return (x.ok ? (y.ok ? x.h < y.h : false) : (y.ok ? true : false)); }); memset(prv, -1, sizeof prv); int prv_h = 1; int st = -1; int mx_ans = 0; init_segment(); for(int i = 0; i < n; i++) { if(!envs[i].ok) continue; if(envs[i].h != prv_h) { apply_queue(); prv_h = envs[i].h; } pair<int, int> res = get(0, envs[i].w); prv[envs[i].I] = res.second; push_to_queue({envs[i].w, {++res.first, envs[i].I}}); if(res.first > mx_ans) { mx_ans = res.first; st = envs[i].I; } } printf("%d\n", mx_ans); vector<int> vv; while(~st) { vv.push_back(st); st = prv[st]; } reverse(vv.begin(), vv.end()); for(auto x : vv) printf("%d%c", x, " \n"[x == vv.back()]); return 0; }
549593a26bc1f88746ee5164acc80821e8258924
abda34c1a06cde902690b463933cd78613590b31
/erp_Hotel_GFP/ajouter_entretien_mach.h
283934d0e0028b2530586ef86da9c85e85bfb46b
[]
no_license
awfeequdng/erp_Hotel_GFP
ed01926269515d158040f24d8b19c32faf1d515b
e6fa2644f58d5e114d82a7b13395ffec04189eeb
refs/heads/master
2021-01-23T06:01:38.312101
2016-10-24T16:43:05
2016-10-24T16:43:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
740
h
ajouter_entretien_mach.h
#ifndef AJOUTER_ENTRETIEN_MACH_H #define AJOUTER_ENTRETIEN_MACH_H #include <QDialog> namespace Ui { class ajouter_entretien_mach; } class ajouter_entretien_mach : public QDialog { Q_OBJECT public: virtual void combomachines(); virtual void combotech(); explicit ajouter_entretien_mach(QWidget *parent = 0); ~ajouter_entretien_mach(); private slots: void on_menu_Pb_clicked(); void on_actualise_clicked(); void on_envoye_PB_clicked(); void on_id_entretien_LE_cursorPositionChanged(); void on_id_mach_2_CB_highlighted(const QString &arg1); void on_id_tech_CB_highlighted(const QString &arg1); private: Ui::ajouter_entretien_mach *ui; }; #endif // AJOUTER_ENTRETIEN_MACH_H
5d88c83310f041de901b606113feb978616692b1
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5688567749672960_0/C++/jumpwmk/counterculture.cpp
b85dedebae3b867f1ddbffd777305a6087dade6d
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
674
cpp
counterculture.cpp
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; char x[100]; int mic[1000100]; int main() { int q,j,k,len,cnt; long long i,n,tmp=0; // freopen("test.in","r",stdin); // freopen("test.out","w",stdout); scanf("%d",&q); for(k=1;k<=q;k++) { cnt=0; scanf("%lld",&n); i=0; for(i=1;i<=n;i++) mic[i]=10000100; for(i=1;i<=n;i++) { if(mic[i-1]+1 < mic[i]) mic[i]=mic[i-1]+1; sprintf(x,"%lld",i); len=strlen(x); reverse(x,x+len); sscanf(x,"%lld",&tmp); if(tmp <= n && mic[i]+1 < mic[tmp]) mic[tmp]=mic[i]+1; } printf("Case #%d: %d\n",k,mic[n]); } return 0; }
1492d14af9ffe1c93b240e570709a2316ae056fe
ef5ee8466039bc7ba05633e4d3b2b00d8e96e6d5
/final/final_final_year_project_common1.ino
0598a79c40d4c3903c0ed600b879602f3bc035da
[]
no_license
noxiddd/Sound_Burst_Detection
95d82ace515d2b50cf81f6f464a77aa70c58453e
fc68cfc3e62cc429d689881d15c223ee632676c9
refs/heads/master
2020-06-29T12:20:48.665865
2017-04-26T08:59:37
2017-04-26T08:59:37
74,427,689
0
0
null
null
null
null
UTF-8
C++
false
false
10,065
ino
final_final_year_project_common1.ino
#define LIN_OUT8 1//use the lin out function #define FHT_N 32 // set to 32 point fht///define before fht.h #include <FHT.h> /* This code runs on the common devices(ones with only nrf24l01+) It sends data to main module via nrf with distance info for now it will only detect impulse sounds(clap) */ //#include <fhtConfig.h> #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <math.h> #define soundPin A0 #define manual_send 5 int sound_buf[256]={0};//stores the sound values int sound_buffer_index=0;//current positions of the sound buffer index RF24 radio(7, 8); const byte rxAddr[6] = "00002"; char t[4]; char h='z'; String g="upp"; unsigned long i=0; unsigned long times=i; unsigned long impulse_start; unsigned long impulse_end; int re=0; int rise=0;//rise of peak detected? int diff=0;//adc differnces in values int pulse_time=251; int positve_peak=0; int negative_peak=0; unsigned int peak=0; int maxVolt=0;//maximum voltage heard long maxVolt_time=0; int q; int ambient_voltage_accumulate=0; int ambient_voltage=0; unsigned long ambient_voltage_time=0; int ambient_voltage_count=0; double signalEnergy=0; double max_signalEnergy=0; unsigned long max_signalEnergy_time=0; double energy_hold=0; int take_signal_time=1;//true or false 0 true 1 false void setup() { // put your setup code here, to run once: Serial.begin(57600); radio.begin(); radio.setRetries(15, 15); radio.openWritingPipe(rxAddr); radio.stopListening(); Serial.println("begin"); //radio.setDataRate(RF24_250KBPS); radio.setPALevel(RF24_PA_MAX);//trasnmit distance maximum, but uses more power pinMode(9, OUTPUT); pinMode(2, OUTPUT); //TIMSK0 = 0; // turn off timer0 for lower jitter ADCSRA = 0xe5 ; // set the adc to free running mode ADMUX = 0x40; // use adc0 DIDR0 = 0x01; // turn off the digital input for adc0 // delay(15000);//wait for noise to go away } int reference_fht[16]={2,45,55,19,8,19,11,3,9,9,4,3,6,5,1,1};//specrtum against which detection test is done float fht_reorder_hold[FHT_N]={0}; float fht_run_hold[FHT_N]={0}; float fht_window_hold[FHT_N]={0}; float fht_lin8_hold[FHT_N]={0};//hold the value so operations can go on float fht_hold[FHT_N]={0};//hold the value so operations can go on float distance=0; char distance2[32] = {0};//distance from mod03 int toggle=0;//to measure sampling rate int incre=1;//controls fht processes int allow_fht=0; int do_nrf_send=0; void loop() { digitalWrite(9,LOW); digitalWrite(2,LOW); if(gunshot_detected()) {//Serial.print("Here"); digitalWrite(2,HIGH); distance=getDist(maxVolt); if(distance<0) { distance=0.1; } //Serial.println(distance2); //dtostrf(getDist(signalEnergy), 4, 2, distance2); dtostrf(getDist02(max_signalEnergy), 4, 2, distance2); //Serial.print(" "); strcat (distance2," n");// module one //Serial.println(distance2); //radio.write(&distance2, sizeof(distance2)); digitalWrite(9,HIGH); } if (millis()-max_signalEnergy_time>1000) { if(do_nrf_send==1) { Serial.println("send to nrf"); do_nrf_send=0; /* radio.write(&distance2, sizeof(distance2)); Serial.println("sent to nrf"); */ //Serial.println("sent to nrf"); } max_signalEnergy=0; take_signal_time=1; } } double getDist02(int volts)//input adc values { double dist; dist=(log(9976.370441/volts))/(0.6126089054); return dist; } void visualizer() { for(int i=0;i<FHT_N/2;i++) { Serial.print(i); Serial.print(" "); Serial.print("#"); for(int y=0;y<fht_lin_out8[i];y++) { if(y<10) { Serial.print(" "); } Serial.print("#"); } Serial.println(" "); } } double getDist(int energy)//input adc values { double dist; dist=(log(19396.67306/energy))/(0.9125233908); return dist; } double correlation() { double corrxy=0;//correlation value double corrxx=0; double corryy=0; double corr=0;//final correlation value double mult=0; for(int i=0;i<FHT_N/2;i++) { corrxy=(reference_fht[i]*fht_lin_out8[i])+corrxy; } for(int j=0;j<FHT_N/2;j++) { corrxx=(reference_fht[j]*reference_fht[j])+corrxx; } for(int k=0;k<FHT_N/2;k++) { corryy=(fht_lin_out8[k]*fht_lin_out8[k])+corryy; } mult=corrxx*corryy; corr=corrxy/sqrt(mult); return corr;//corryy; } int gunshot_detected() { cli(); // UDRE interrupt slows this way down on arduino1.0 for (int i = 0 ; i < FHT_N ; i++) { // save 32 samples while(!(ADCSRA & 0x10)); // wait for adc to be ready ADCSRA = 0xf5; // restart adc byte m = ADCL; // fetch adc data byte j = ADCH; int k = (j << 8) | m; // form into an int k -= 0x0200; // form into a signed int k <<= 6; // form into a 16b signed int fht_input[i] = k; // put real data into bins if(fht_input[i]>maxVolt) { maxVolt=fht_input[i]; maxVolt_time=millis(); } } fht_window(); // window the data for better frequency response fht_reorder(); // reorder the data before doing the fht fht_run(); // process the data in the fht fht_mag_lin8(); sei(); //Serial.print("Energy: "); // Serial.println(signalEnergy); energy_hold=getSignalEnergy(); if(max_signalEnergy<energy_hold) { max_signalEnergy=energy_hold; if (take_signal_time==1) { max_signalEnergy_time=millis(); take_signal_time=0; } } signalEnergy=getSignalEnergy(); if(abs(correlation())>0.9)//threshold { do_nrf_send=1;//send return 1;//gunshot detected } else { return 0;//no gunshot } } void ambiency(int i)//supposed to find nominal values for volatge and detect peak over that { if (abs(ambient_voltage-fht_input[i])>60)//threshold { allow_fht=1; } else { allow_fht=0; } if ((millis()-ambient_voltage_time)>100) { ambient_voltage_time=millis(); ambient_voltage_accumulate=fht_input[i]+ambient_voltage_accumulate; ambient_voltage_count++; } else { ambient_voltage=ambient_voltage_accumulate/ambient_voltage_count; Serial.print("ambient volatge: "); Serial.println(ambient_voltage); ambient_voltage_count=0; } } void faster_fht() { if(incre==1) { fht_window(); // window the data for better frequency response memcpy(fht_window_hold,fht_input,FHT_N); incre++; } else if(incre==2) { memcpy(fht_hold,fht_input,FHT_N);//hold on this for me memcpy(fht_input,fht_window_hold,FHT_N); fht_reorder(); // reorder the data before doing the fht memcpy(fht_reorder_hold,fht_input,FHT_N); memcpy(fht_input,fht_hold,FHT_N); fht_window(); // window the data for better frequency response memcpy(fht_window_hold,fht_input,FHT_N); incre++; } else if (incre==3) { memcpy(fht_hold,fht_input,FHT_N);//hold on this for me memcpy(fht_input,fht_reorder_hold,FHT_N); fht_run(); // process the data in the fht memcpy(fht_run_hold,fht_input,FHT_N); memcpy(fht_input,fht_window_hold,FHT_N); fht_reorder(); // reorder the data before doing the fht memcpy(fht_reorder_hold,fht_input,FHT_N); memcpy(fht_input,fht_hold,FHT_N); fht_window(); // window the data for better frequency response memcpy(fht_window_hold,fht_input,FHT_N); incre++; } else if(incre==4) { memcpy(fht_hold,fht_input,FHT_N);//hold on this for me memcpy(fht_input,fht_run_hold,FHT_N); fht_mag_lin8();//then goes to fht lin_out memcpy(fht_input,fht_reorder_hold,FHT_N); fht_run(); // process the data in the fht memcpy(fht_run_hold,fht_input,FHT_N); memcpy(fht_input,fht_window_hold,FHT_N); fht_reorder(); // reorder the data before doing the fht memcpy(fht_reorder_hold,fht_input,FHT_N); memcpy(fht_input,fht_hold,FHT_N); fht_window(); // window the data for better frequency response memcpy(fht_window_hold,fht_input,FHT_N); incre=1; } } void checkSampleFreq() { for (int i = 0 ; i < FHT_N ; i++) { // save 32 samples while(!(ADCSRA & 0x10)); // wait for adc to be ready ADCSRA = 0xf5; // restart adc byte m = ADCL; // fetch adc data byte j = ADCH; int k = (j << 8) | m; // form into an int k -= 0x0200; // form into a signed int k <<= 6; // form into a 16b signed int fht_input[i] = k; // put real data into bins if(fht_input[i]>maxVolt) { maxVolt=fht_input[i]; maxVolt_time=millis(); } if(toggle==0) { toggle=1; digitalWrite(9,HIGH); } else { toggle=0; digitalWrite(9,LOW); } } } double getSignalEnergy() {double temp=0; for(int i=0;i<FHT_N/2;i++) { temp=(fht_lin_out8[i]*fht_lin_out8[i])+temp; } if(temp<0) { temp=0; } return 2*temp; }
15bef9aa24cb6bf39ba8d1e389524f62acf411f0
14cd82ceb0ed01235ac8c7208219fc4df7a7b1d2
/Introduction to Progamming/Lab Projects/lab12/secondDigit.cpp
9563d54a64d1fd4588ec8e23b8d61eaa4848e8fd
[]
no_license
OliverAkhtar/Projects
947000000e1ce1d653c58b705143b6cbe1cf4a3b
c2bcfa51886de155843aa79a4d6968d6ad0bf641
refs/heads/master
2021-01-10T15:55:45.933009
2017-11-15T21:12:22
2017-11-15T21:12:22
49,913,736
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
secondDigit.cpp
/*This program prints the 2 digit of a user inputted postive integer of at least 3 digits.*/ #include <iostream> using namespace std; int main() { int n; cout << "Enter a positive integer with at least 3 digits: "; cin >> n; if (n < 1) return 0; if (n <100) return 0; while (n > 100) n = n/10; n = n%10; cout << "The second digit is: " << n; return 0; }
cb1c929f2519a63e5808026bebfb4189076a0991
41a958a3a0c14646b4a9a5c5187f96aadd61ff2b
/src/main.cpp
1b8493fc69fc327b48b7ed5351c157939454ebab
[]
no_license
ashrasmun/vector-vs-list
fb933c4d5cdf9ef0a79f45cc606e6cce2de2fde0
8d93de632513f7c46cc42213d519a23366dc821c
refs/heads/master
2020-06-04T15:25:48.981226
2019-06-29T20:38:12
2019-06-29T20:38:12
192,081,150
0
0
null
null
null
null
UTF-8
C++
false
false
4,347
cpp
main.cpp
#include <iostream> #include <vector> #include <list> #include <chrono> #include <map> // Complex class definition class SomeComplexClass; class Something { public: Something() {} private: std::string complexStr; std::map< std::pair< std::string, int>, std::map< int, std::string > > justSomeWeirdMap; }; class Base { public: virtual ~Base() {} virtual void someVirtualMethod() {} virtual void someVirtualMethod1() {} virtual void someVirtualMethod2() {} virtual void someVirtualMethod3() {} virtual void someVirtualMethod4() {} virtual void someVirtualMethod5() {} virtual void someVirtualMethod6() {} virtual void someVirtualMethod7() {} virtual void someVirtualMethod8() {} virtual void someVirtualMethod9() {} virtual void someVirtualMethod10() {} virtual void someVirtualMethod11() {} static void someStaticMethod() {} static constexpr int someConstexprInt = 0; }; class SomeComplexClass : public Base { friend class Something; public: SomeComplexClass() {} virtual void someVirtualMethod() {} private: void somePrivateMethod(int test1, char test2) { test1 = static_cast<int>(test2); intMember += test1; strMember = std::to_string(intMember); } virtual void someVirtualMethod1() {} virtual void someVirtualMethod2() {} virtual void someVirtualMethod3() {} virtual void someVirtualMethod4() {} virtual void someVirtualMethod5() {} virtual void someVirtualMethod6() {} virtual void someVirtualMethod7() {} virtual void someVirtualMethod8() {} virtual void someVirtualMethod9() {} virtual void someVirtualMethod10() {} virtual void someVirtualMethod11() {} std::string strMember = ""; int intMember = 0; Something justSomething; }; // !Complex class definition template<typename Container> std::chrono::duration<double> benchmark_container_insertion(int number_of_elements_to_insert) { using namespace std::chrono; Container container; typename Container::value_type element; const auto beginning = steady_clock().now(); for (int i = 0; i < number_of_elements_to_insert; ++i) container.push_back(element); const auto after_insert = steady_clock().now(); return after_insert - beginning; } void printInsertionTime(const std::string& containerName, int N, std::chrono::duration<double> time) { std::cout << containerName << " insertion time for " << N << " elements\n"; std::cout << time.count() << "\n\n"; } template<typename UnderlyingType> void benchmark_insertion_into_containers(int n) { const auto vector_insertion_duration = benchmark_container_insertion<std::vector<UnderlyingType>>(n); printInsertionTime("Vector", n, vector_insertion_duration); const auto list_insertion_duration = benchmark_container_insertion<std::list<UnderlyingType>>(n); printInsertionTime("List", n, list_insertion_duration); } void printSurroundedWith(const std::string& message, char surroundingCharacter) { for (size_t i = 0; i < message.size() + 3; ++i) std::cout << surroundingCharacter; std::cout << surroundingCharacter << '\n'; std::cout << surroundingCharacter << ' ' << message << ' ' << surroundingCharacter << '\n'; for (size_t i = 0; i < message.size() + 3; ++i) std::cout << surroundingCharacter; std::cout << surroundingCharacter << "\n\n"; } void benchmark_simple() { printSurroundedWith("Benchmarking insertion to containers for simple types (int)", '='); benchmark_insertion_into_containers<int>(100); benchmark_insertion_into_containers<int>(10000); benchmark_insertion_into_containers<int>(1000000); benchmark_insertion_into_containers<int>(100000000); } void benchmark_complex() { printSurroundedWith("Benchmarking insertion to containers for complex types (SomeComplexClass)", '='); benchmark_insertion_into_containers<SomeComplexClass>(100); benchmark_insertion_into_containers<SomeComplexClass>(10000); benchmark_insertion_into_containers<SomeComplexClass>(1000000); benchmark_insertion_into_containers<SomeComplexClass>(100000000); } int main() { benchmark_simple(); benchmark_complex(); return 0; }
f6f41e6b4136059aad1fa9aa8215278ccf4d3587
1627fcbfee56cf762b4d5d0a275e74e5eba93560
/lunarlady/SoundSystem.cpp
d18fbf6629784b3f080d2ad36836e3efe9ed82f3
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
madeso/infection-survivors
c47ff50092d4cdd7b0c2976bb0d49a8aee2a128a
654fc5405dcecccaa7e54f1fdbfec379e0c185da
refs/heads/master
2021-01-18T13:58:45.692267
2014-09-22T17:38:12
2014-09-22T17:38:12
24,337,330
0
0
null
null
null
null
UTF-8
C++
false
false
16,123
cpp
SoundSystem.cpp
#include "fmod.hpp" #include "fmod_errors.h" #include "sgl/sgl_Assert.hpp" #include "lunarlady/System.hpp" #include "lunarlady/Game.hpp" #include "lunarlady/Log.hpp" #include "lunarlady/Script.hpp" #include "lunarlady/File.hpp" #include "lunarlady/Xml.hpp" #include "lunarlady/StringUtils.hpp" #include "lunarlady/Display.hpp" #include "lunarlady/Config.hpp" #include "lunarlady/Error.hpp" #include "physfs.h" namespace lunarlady { class SoundSystem; namespace { std::string GetNameAndVersion() { const unsigned int major = 0x0000FFFF & (FMOD_VERSION>>16); const unsigned int minor = 0x000000FF & (FMOD_VERSION>>8); const unsigned int dev = 0x000000FF & (FMOD_VERSION>>0); std::stringstream str; str << "FMOD Ex v" << std::hex << major << "." << std::hex << minor << ":" << std::hex << dev; return str.str(); } SoundSystem* gSoundSystem = 0; } FMOD_RESULT F_CALLBACK Open(const char *name, int unicode, unsigned int *filesize, void **handle, void **userdata) { if (name) { if ( !PHYSFS_exists(name) ) { return FMOD_ERR_FILE_NOTFOUND; } PHYSFS_file* fp = PHYSFS_openRead(name); if( !fp ) { return FMOD_ERR_FILE_BAD; } *filesize = PHYSFS_fileLength(fp); *userdata = (void *)0x12345678; *handle = fp; } return FMOD_OK; } FMOD_RESULT F_CALLBACK Close(void *handle, void *userdata) { if (!handle) { return FMOD_ERR_INVALID_PARAM; } PHYSFS_file* fp = (PHYSFS_file*) handle; PHYSFS_close(fp); return FMOD_OK; } FMOD_RESULT F_CALLBACK Read(void *handle, void *buffer, unsigned int sizebytes, unsigned int *bytesread, void *userdata) { if (!handle) { return FMOD_ERR_INVALID_PARAM; } if (bytesread) { PHYSFS_file* fp = (PHYSFS_file*) handle; *bytesread = (int)PHYSFS_read(fp, buffer, 1, sizebytes); if (*bytesread < sizebytes) { return FMOD_ERR_FILE_EOF; } } return FMOD_OK; } FMOD_RESULT F_CALLBACK Seek(void *handle, unsigned int pos, void *userdata) { if (!handle) { return FMOD_ERR_INVALID_PARAM; } PHYSFS_file* fp = (PHYSFS_file*) handle; //fseek((FILE *)handle, pos, SEEK_SET); int result = PHYSFS_seek(fp, pos); if( result == 0 ) { return FMOD_ERR_FILE_COULDNOTSEEK; } return FMOD_OK; } typedef std::list<std::string> SoundSource; typedef std::map<std::string, std::string> SoundDefinitionMap2; typedef std::map<std::string, SoundSource> SoundDefinitionMap3; typedef std::map<std::string, FMOD::Sound*> StringSoundMap; typedef std::map<std::string, FMOD::Channel*> StringChannelMap; std::string AsValidPath(const std::string& iPath) { if( EndsWith(iPath, "/") ) { return iPath; } else { return iPath + "/"; } } class SoundSystem : public System { public: SoundSystem() : System(GetNameAndVersion()), mSystem(0) { Assert(!gSoundSystem, "Already has a sound system"); test( FMOD::System_Create(&mSystem), "creating system" ); Assert(mSystem, "internal error, bug?"); // A buffer of 0 means all reads go directly to the pointer specified. 2048 bytes is the size of a CD sector on most CD ISO formats so it is chosen as the default, for optimal reading speed from CD media. test(mSystem->setFileSystem(Open, Close, Read, Seek, 2048), "setting file system"); test( mSystem->init(100, FMOD_INIT_NORMAL, 0), "initializing system" ); gSoundSystem = this; test(mSystem->getMasterChannelGroup(&mMasterChannel), "getting master channel group"); test(mSystem->createChannelGroup("interface", &mInterfaceChannel), "creating interface channel group"); test(mSystem->createChannelGroup("music", &mMusicChannel), "creating music channel group"); test( mMasterChannel->addGroup(mInterfaceChannel), "adding interface group"); test( mMasterChannel->addGroup(mMusicChannel), "adding music group"); loadConfig(); loadDefinitionsDirectory("sfx/"); } ~SoundSystem() { Assert(gSoundSystem, "Need a sound system"); try { Assert(mSystem, "internal error, bug?"); saveConfig(); test(mInterfaceChannel->release(), "releasing interface channel"); test(mMusicChannel->release(), "releasing music channel"); test(mSystem->release(), "releasing system"); } catch(...) { } gSoundSystem = 0; } FMOD::Channel* getPlayingStreamChannel2(const std::string& iStreamId) { StringChannelMap::iterator result = mPlayingStreams.find(iStreamId); if( result == mPlayingStreams.end() ) return 0; else return result->second; } void playStream2(const std::string& iStreamId, const std::string& iFileName, bool iLoop) { Assert(mSystem, "internal error, bug?"); FMOD::Sound* sound = 0; FMOD::Channel* channel = getPlayingStreamChannel2(iStreamId); if( channel ) { bool playing = false; test(channel->isPlaying(&playing), "getting isplaying from stream channel"); if( playing ) { bool paused = false; test( channel->getPaused(&paused), "getting paused state" ); if( !paused ) { stopStream2(iStreamId); channel = 0; } } } if( channel == 0 ) { test(mSystem->createStream(iFileName.c_str(), FMOD_DEFAULT | FMOD_2D, 0, &sound), "loading sound"); if( iLoop ) { test(sound->setMode(FMOD_LOOP_NORMAL), "setting loop normal"); } test(mSystem->playSound(FMOD_CHANNEL_FREE, sound, true, &channel), "playing sound"); test( channel->setChannelGroup(mMusicChannel), "setting stream to music channel"); } test(channel->setPaused(false), "setting paused on channel"); mPlayingStreams[iStreamId] = channel; } void pauseStream2(const std::string& iStreamId) { FMOD::Channel* channel = getPlayingStreamChannel2(iStreamId); if( channel ) { test(channel->setPaused(true), "setting paused on channel"); } } void stopStream2(const std::string& iStreamId) { FMOD::Channel* channel = getPlayingStreamChannel2(iStreamId); if( channel ) { FMOD::Sound* sound = 0; test(channel->getCurrentSound(&sound), "destroying stream, getting sound"); test(channel->stop(), "stopping channel"); mPlayingStreams[iStreamId] = 0; sound->release(); } } void step(real iTime) { Assert(mSystem, "internal error, bug?"); test(mSystem->update(), "updating"); float cpu = 0; test(mSystem->getCPUUsage(NULL, NULL, NULL, &cpu), "grabbing cpu usage"); int memory = 0; test(FMOD::Memory_GetStats(&memory, NULL), "getting memroy stats"); DisplayPrecision("fmod cpu", cpu, 1, true); DisplayPrecision("fmod mem", memory/1024.0, 1, true); } void test(FMOD_RESULT iResult, const std::string& iDescription) { if( iResult != FMOD_OK ) { std::stringstream str; str << "FMOD error! (" << iResult << ") " << FMOD_ErrorString(iResult) << " while " << iDescription; LOG1( str.str() ); throw str.str(); } } void loadDefinitionsDirectory(const std::string& iDirectory) { std::vector<std::string> files; GetFileListing(iDirectory, &files); const std::size_t count = files.size(); for(std::size_t fileIndex=0; fileIndex<count; ++fileIndex) { const std::string file = files[fileIndex]; if( EndsWith(file, ".sfx") ) { loadDefinitionsFile(file); } } } void loadDefinitionsFile(const std::string& iFile) { ReadFile file(iFile); TiXmlDocument document(iFile.c_str()); document.Parse(file.getBuffer(), 0, TIXML_ENCODING_LEGACY); loadDefinitions(document.FirstChildElement("sounds"), ""); } void loadDefinitions(TiXmlElement* iContainer, const std::string& iBase) { if( !iContainer ) return; std::string name=""; // handle base for(TiXmlElement* child=iContainer->FirstChildElement("base"); child; child=child->NextSiblingElement("base") ) { const char* src = child->Attribute("src"); std::string base = iBase; if( src ) { base = AsValidPath(base+src); } loadDefinitions(child, base); } // directory for(TiXmlElement* child=iContainer->FirstChildElement("directory"); child; child=child->NextSiblingElement("directory") ) { const char* src = child->Attribute("src"); if( !src ) { throw SoundError("Directory element missing source attribute"); } loadDefinitionsDirectory( AsValidPath(iBase + src) ); } // sound for(TiXmlElement* child=iContainer->FirstChildElement("sound"); child; child=child->NextSiblingElement("sound") ) { const char* name = child->Attribute("name"); if( !name ) { throw SoundError("Missing name-attribute for sound element"); } const char* src = child->Attribute("src"); if( src ) { mDefinedSounds2d[name] = iBase + src; } else { SoundSource& soundSource = mDefinedSounds3d[name]; for(TiXmlElement* file=child->FirstChildElement("file"); file; file=file->NextSiblingElement("file") ) { const char* src = file->Attribute("src"); if( !src ) { throw SoundError("File element missing source attribute"); } soundSource.push_back(iBase + src); } } } } void playSound2(const std::string& iSoundId) { StringSoundMap::iterator res = mLoadedSounds2d.find(iSoundId); if( res == mLoadedSounds2d.end() ) { throw SoundError("sound id isn't preloaded"); } FMOD::Sound* sound = res->second; FMOD::Channel* channel = 0; test( mSystem->playSound(FMOD_CHANNEL_FREE, sound, false, &channel), "playing sound-id" ); test(channel->setChannelGroup(mInterfaceChannel), "setting sound to interface channel"); } void preloadSound2(const std::string& iSoundId) { if( mLoadedSounds2d.find(iSoundId) != mLoadedSounds2d.end() ) return; SoundDefinitionMap2::iterator res = mDefinedSounds2d.find(iSoundId); if( res == mDefinedSounds2d.end() ) { throw SoundError("Failed to preload sound, since id is missing"); } const std::string fileName = res->second; FMOD::Sound* sound = 0; test(mSystem->createSound(fileName.c_str(), FMOD_DEFAULT | FMOD_2D, 0, &sound), "preloading sound"); mLoadedSounds2d.insert( StringSoundMap::value_type(iSoundId, sound) ); } real getMasterVolume() { return getVolume(mMasterChannel); } real getInterfaceVolume() { return getVolume(mInterfaceChannel); } real getMusicVolume() { return getVolume(mMusicChannel); } void setMasterVolume(real iVolume) { setVolume(mMasterChannel, iVolume); } void setInterfaceVolume(real iVolume) { setVolume(mInterfaceChannel, iVolume); } void setMusicVolume(real iVolume) { setVolume(mMusicChannel, iVolume); } void saveConfig() { SetReal("volume.master", getMasterVolume()); SetReal("volume.interface", getInterfaceVolume()); SetReal("volume.music", getMusicVolume()); } void loadConfig() { setMasterVolume( GetReal("volume.master") ); setInterfaceVolume( GetReal("volume.interface") ); setMusicVolume( GetReal("volume.music") ); } private: real getVolume(FMOD::ChannelGroup* iGroup) { float volume = 0; test(iGroup->getVolume(&volume), "getting volume from group"); return volume; } void setVolume(FMOD::ChannelGroup* iGroup, real iVolume) { const float volume = iVolume; test(iGroup->setVolume(volume), "setting volume for group"); } FMOD::System* mSystem; FMOD::ChannelGroup* mMasterChannel; FMOD::ChannelGroup* mInterfaceChannel; FMOD::ChannelGroup* mMusicChannel; //FMOD::ChannelGroup* mEffectChannel; //FMOD::ChannelGroup* mVoiceChannel; //FMOD::ChannelGroup* mConversationChannel; SoundDefinitionMap2 mDefinedSounds2d; SoundDefinitionMap3 mDefinedSounds3d; StringSoundMap mLoadedSounds2d; StringChannelMap mPlayingStreams; }; void PlayStream2(const std::string iStreamId, const std::string iFileName, bool iLoop) { Assert(gSoundSystem, "Need a sound system"); gSoundSystem->playStream2(iStreamId, iFileName, iLoop); } void PauseStream2(const std::string iStreamId) { Assert(gSoundSystem, "Need a sound system"); gSoundSystem->pauseStream2(iStreamId); } void StopStream2(const std::string iStreamId) { Assert(gSoundSystem, "Need a sound system"); gSoundSystem->stopStream2(iStreamId); } void PlaySound2(const std::string iSoundId) { Assert(gSoundSystem, "Need a sound system"); gSoundSystem->playSound2(iSoundId); } void PreloadSound2(const std::string iSoundId) { Assert(gSoundSystem, "Need a sound system"); gSoundSystem->preloadSound2(iSoundId); } void PlayStream2ScriptFunction(FunctionArgs& iArgs) { const int args = ArgCount(iArgs); if( args != 3) ArgReportError(iArgs, "syntax: (string id, string path, bool loop)"); ArgVarString(id, iArgs, 0); ArgVarString(file, iArgs, 1); ArgVarInt(loop, iArgs, 2); try { PlayStream2(id, file, loop==1); } catch(const std::runtime_error& error) { ArgError(iArgs, error.what()); ArgReportError(iArgs, "Failed to stream2 " << file ); } } void PauseStream2ScriptFunction(FunctionArgs& iArgs) { const int args = ArgCount(iArgs); if( args != 1) ArgReportError(iArgs, "syntax: (string id)"); ArgVarString(id, iArgs, 0); PauseStream2(id); } void StopStream2ScriptFunction(FunctionArgs& iArgs) { const int args = ArgCount(iArgs); if( args != 1) ArgReportError(iArgs, "syntax: (string id)"); ArgVarString(id, iArgs, 0); StopStream2(id); } void PlaySound2ScriptFunction(FunctionArgs& iArgs) { const int args = ArgCount(iArgs); if( args != 1) ArgReportError(iArgs, "Need 1 string sound-id argument"); ArgVarString(file, iArgs, 0); try { PlaySound2(file); } catch(const std::runtime_error& error) { ArgError(iArgs, error.what()); ArgReportError(iArgs, "Failed to play sound2 " << file ); } } void PreloadSound2ScriptFunction(FunctionArgs& iArgs) { const int args = ArgCount(iArgs); if( args != 1) ArgReportError(iArgs, "Need 1 string sound-id argument"); ArgVarString(file, iArgs, 0); try { PreloadSound2(file); } catch(const std::runtime_error& error) { ArgError(iArgs, error.what()); ArgReportError(iArgs, "Failed to preload sound2 " << file ); } } SCRIPT_FUNCTION(playStream2, PlayStream2ScriptFunction, "Starts to play a stream, if playing it is reset, if paused it continues"); SCRIPT_FUNCTION(pauseStream2, PauseStream2ScriptFunction, "Pauses a stream, to unpause use playStream2"); SCRIPT_FUNCTION(stopStream2, StopStream2ScriptFunction, "Stops a stream"); SCRIPT_FUNCTION(playSound2, PlaySound2ScriptFunction, "Plays a sound id, must be pre-loaded"); SCRIPT_FUNCTION(preloadSound2, PreloadSound2ScriptFunction, "Preloads a sound"); void MasterVolumeScriptFunction(FunctionArgs& iArgs) { Assert(gSoundSystem, "Need a sound system"); if( ArgCount(iArgs) == 0 ) { const real value = gSoundSystem->getMasterVolume(); Return(iArgs, value); } else { if( ArgCount(iArgs) != 1 ) { ArgReportError(iArgs, "Need 1 or 0 floating arguments range, 0-1"); } else { ArgVarReal(volume, iArgs, 0); gSoundSystem->setMasterVolume(volume); } } } SCRIPT_FUNCTION(masterVolume, MasterVolumeScriptFunction, "sets or gets the master volume, range 0-1"); void InterfaceVolumeScriptFunction(FunctionArgs& iArgs) { Assert(gSoundSystem, "Need a sound system"); if( ArgCount(iArgs) == 0 ) { const real value = gSoundSystem->getInterfaceVolume(); Return(iArgs, value); } else { if( ArgCount(iArgs) != 1 ) { ArgReportError(iArgs, "Need 1 or 0 floating arguments range, 0-1"); } else { ArgVarReal(volume, iArgs, 0); gSoundSystem->setInterfaceVolume(volume); } } } SCRIPT_FUNCTION(interfaceVolume, InterfaceVolumeScriptFunction, "sets or gets the interface volume, range 0-1"); void MusicVolumeScriptFunction(FunctionArgs& iArgs) { Assert(gSoundSystem, "Need a sound system"); if( ArgCount(iArgs) == 0 ) { const real value = gSoundSystem->getMusicVolume(); Return(iArgs, value); } else { if( ArgCount(iArgs) != 1 ) { ArgReportError(iArgs, "Need 1 or 0 floating arguments range, 0-1"); } else { ArgVarReal(volume, iArgs, 0); gSoundSystem->setMusicVolume(volume); } } } SCRIPT_FUNCTION(musicVolume, MusicVolumeScriptFunction, "sets or gets the music volume, range 0-1"); LL_SYSTEM(SoundSystem, 1000); }
3fc3e363beda1aadcd13e4d94eae15f7548c231e
37c7b76656aa90b23b7ce643d985ad5c4cef30ab
/Arrays/Group multiple occurrence of array elements ordered by first occurrence.cpp
318ccca5baadb9d7cdca80ea3ffcb0c259ceca42
[]
no_license
abhiramdapke/Independent-projects
82695397344aa8f0098ec1682abdb667d314c8a1
6e8f36e1b9dc8dfbea12c38c3ab85a7d961d3c0a
refs/heads/master
2020-12-19T08:42:54.904218
2020-08-12T20:50:09
2020-08-12T20:50:09
235,684,714
2
1
null
null
null
null
UTF-8
C++
false
false
684
cpp
Group multiple occurrence of array elements ordered by first occurrence.cpp
#include <iostream> #include <vector> using namespace std; int main() { int arr[] = {1,1,2,5,3,5,6,1,2,3,4,4}; int n = sizeof(arr)/sizeof(arr[0]); bool *visited = new bool[n]; for (int i=0; i<n; i++) visited[i] = false; for (int i=0; i<n; i++) { if (!visited[i]) { cout << arr[i] << " "; for (int j=i+1; j<n; j++) { if (arr[i] == arr[j]) { cout << arr[i] << " "; visited[j] = true; } } } } delete [] visited; return 0; }
f1712ce20f86c7f9c9e46ad345614e9d1054c308
4649fba2cf0ca2834eba97a84ee40e67f97f4b4c
/examples/mbew-example-video-osg.cpp
d027893da221fd7b4b157038aaa35723f702f531
[]
no_license
AlphaPixel/mbew
90adb911cf729ed8c852f3cdf81e546dc6283c34
aaf054c1dd0a2571156549753727605a5a60baaf
refs/heads/master
2021-01-12T04:19:10.698489
2016-12-28T22:58:39
2016-12-28T22:58:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,022
cpp
mbew-example-video-osg.cpp
#include "mbew.h" #include <osg/Math> #include <osg/Geometry> #include <osg/TextureRectangle> #include <osg/Geode> #include <osg/BlendFunc> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <iostream> class MBEWUpdateCallback: public osg::Drawable::UpdateCallback { public: MBEWUpdateCallback(mbew_t m, mbew_num_t width, mbew_num_t height): _m(m), _width(width), _height(height) { } virtual void update(osg::NodeVisitor* nv, osg::Drawable* drawable) { osg::Image* image = _getImage(drawable); if(!image) return; if(mbew_iterate(_m, MBEW_ITER_VIDEO_ONLY | MBEW_ITER_FORMAT_RGB | MBEW_ITER_SYNC)) { if(!mbew_iter_sync(_m, _time.elapsedTime_n())) return; image->setImage( _width, _height, 1, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE, static_cast<unsigned char*>(mbew_iter_video_rgb(_m)), osg::Image::NO_DELETE ); image->dirty(); } else { mbew_reset(_m); _time.reset(); } } protected: osg::Image* _getImage(osg::Drawable* drawable) { osg::StateSet* ss = drawable->getStateSet(); if(!ss) return NULL; osg::StateAttribute* sa = ss->getTextureAttribute(0, osg::StateAttribute::TEXTURE); if(!sa) return NULL; osg::Texture* tex = sa->asTexture(); if(!tex) return NULL; osg::Image* image = dynamic_cast<osg::Image*>(tex->getImage(0)); if(!image) return NULL; return image; } private: mbew_t _m; mbew_num_t _width; mbew_num_t _height; osg::ElapsedTime _time; }; int main(int argc, char** argv) { osgViewer::Viewer viewer; mbew_t m = mbew_create(MBEW_SRC_FILE, argv[1]); mbew_status_t status; if((status = mbew_status(m))) { std::cout << "Error opening context: " << argv[1] << std::endl; std::cout << "Status was: " << mbew_string(MBEW_TYPE_STATUS, status) << std::endl; return 1; } if(!mbew_property(m, MBEW_PROP_VIDEO).b) { std::cout << "File contains no video." << std::endl; return 1; } mbew_num_t width = mbew_property(m, MBEW_PROP_VIDEO_WIDTH).num; mbew_num_t height = mbew_property(m, MBEW_PROP_VIDEO_HEIGHT).num; osg::Image* image = new osg::Image(); osg::Geode* geode = new osg::Geode(); osg::TextureRectangle* texture = new osg::TextureRectangle(); osg::Geometry* geom = osg::createTexturedQuadGeometry( osg::Vec3(0.0f, 0.0f, 0.0f), osg::Vec3(width, 0.0f, 0.0f), osg::Vec3(0.0f, 0.0f, height), width, height, 0.0f, 0.0f ); texture->setImage(image); texture->setDataVariance(osg::Object::DYNAMIC); osg::StateSet* state = geom->getOrCreateStateSet(); state->setTextureAttributeAndModes( 0, texture, osg::StateAttribute::ON); state->setMode(GL_BLEND, osg::StateAttribute::ON); state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); geom->setUpdateCallback(new MBEWUpdateCallback(m, width, height)); geode->addDrawable(geom); viewer.setSceneData(geode); viewer.setUpViewInWindow(50, 50, width + 40, height + 40); viewer.addEventHandler(new osgViewer::StatsHandler()); int r = viewer.run(); mbew_destroy(m); return r; }
5d672cf76c2539463eb4d732a571bfbd4d922928
3d4776f1f1f44420a4deeaed408a6495fae6af13
/src/window.cpp
574220743ad1f3ba1602debab546107920fe3e32
[]
no_license
QuantScientist3/RT-Raytracing
8785ba6f82295484a7328e5b1356e9609aad9492
e6287fb7f15b3b79186150b2687eeadfe3c69a8d
refs/heads/master
2021-01-20T21:46:19.370282
2014-08-07T20:17:29
2014-08-07T20:17:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,037
cpp
window.cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <unistd.h> #ifdef CUDA_FOUND #include "devices/cudadevice.h" #endif /* CUDA_FOUND */ #include "devices/cpudevice.h" #include "devices/opencl.h" #include "util/camera.h" #include "scene.h" #include "session.h" #define WIDTH 640 #define HEIGHT 480 namespace { GLFWwindow* window; Camera cam(WIDTH, HEIGHT); #ifdef CUDA_FOUND Device* device = new CUDADevice; #else Device* device = new OpenCL; #endif Scene* scene = new Scene(&cam); RenderSession session(device, scene); /** * Time independent keyboard function */ void key_callback(GLFWwindow * window, int key, int scancode, int action, int mods) { switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, 1); break; } } /** * Focus callback function */ void focus_callback(GLFWwindow * window, int focused) { if (focused) { double middle_x = WIDTH/2.0; double middle_y = HEIGHT/2.0; glfwSetCursorPos(window, middle_x, middle_y); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } } void handle_mouse() { double middle_x = WIDTH/2.0; double middle_y = HEIGHT/2.0; double x, y; glfwGetCursorPos(window, &x, &y); if (x < WIDTH && y < HEIGHT) { double dx = x - middle_x; double dy = y - middle_y; if (dx == 0.f && dy == 0.f) return; cam.lookAt(x, HEIGHT - y); } glfwSetCursorPos(window, middle_x, middle_y); } /** * Time dependent keyboard function */ void handle_keyboard(float dt) { if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) cam.move({-1, 0, 0}, dt); if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) cam.move({ 1, 0, 0}, dt); if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) cam.move({ 0, 0, 1}, dt); if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) cam.move({ 0, 0, -1}, dt); if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) cam.move({ 0, 1, 0}, dt); if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS) cam.move({ 0, -1, 0}, dt); } void handle_input(float dt) { handle_keyboard(dt); handle_mouse(); } } int main(int argc, char* argv[]) { // Initialise GLFW if (!glfwInit()) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } // Open a window and create its OpenGL context window = glfwCreateWindow(WIDTH, HEIGHT, "Raytracer", NULL, NULL); // FIXME: glfwCreateWindow causes the race condition! // Find a way to block until succesfull window creation... usleep(50000); if( window == NULL ){ std::cerr << "Failed to open GLFW window.\n" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } // Initialize OpenCL //if (device->init() != CL_SUCCESS) { // std::cerr << "Failed to initialize OpenCL" << std::endl; // return -1; //} //scene->setCamera(&cam); // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set the keyboard callback for time independent keyboard handling glfwSetKeyCallback(window, &key_callback); glfwSetWindowFocusCallback(window, &focus_callback); // Initialize our vertex buffer GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, vbo); glBufferData(GL_PIXEL_UNPACK_BUFFER, WIDTH * HEIGHT * 3, 0, GL_DYNAMIC_DRAW); // Set the timer to zero glfwSetTime(0.0); double prev = 0; unsigned frames = 0; do { session.render(); // Draw the buffer onto the off screen buffer glDrawPixels(WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, 0); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); double cur = glfwGetTime(); handle_input(cur - prev); //std::cout << "FPS: " << ++frames / cur << "\r"; //std::flush(std::cout); prev = cur; } while(!glfwWindowShouldClose(window)); std::cout << std::endl; // Close OpenGL window and terminate GLFW glfwTerminate(); }
c7c2e3b453cfffa40a5fa55de660e8de54de1312
f2cce248057bb2f78ff53c47aaca74da04dd04bb
/ProjAlocaDinamicaMem/AlocaDinamicaMem.cpp
e25e5dd7eb835b67c07b81aeeddc931296b6b750
[]
no_license
DEVanderAJR/dev-c
69864c9e5da5baa05a2b435d4bfbc227e5303ca8
2a6c8e041e00effd856a6697c15a2acee507484a
refs/heads/master
2020-05-18T04:01:39.147651
2019-04-30T00:19:48
2019-04-30T00:19:48
184,162,565
1
0
null
null
null
null
ISO-8859-1
C++
false
false
1,426
cpp
AlocaDinamicaMem.cpp
/* Exemplo de Alocação dinâmica de Memória - Escrever um program para o conjunto de númros inteiros( o nº 0 indica fim de entradfa de dados e não deve ser considerado). Ao final , imprimir todos os números lidos.*/ #include <stdlib.h> #include <iostream> #include <windows.h> using namespace std; void step(){ Sleep(500); } void stop(){ system("Pause>>null"); } void pass(int x){ if(x==1){ printf("\n");} if(x==2){ printf("\n"); } } struct elementar{ int numer; elementar *ptr; }*inicio,*aux; void main(){ static int xx; //elementar *inicio,*aux;//variáveis ponteiros(*),para controlar a alocação dinâmica na memória; cout<<"Digite o nº: [0->para exit]"<<endl; cin>>xx; inicio=NULL;//INICIANDO O PONTEIRO inicio com NULL(vazio); while(xx!=0){ aux=inicio;//Se inicio é igual a NULL,NULL tambem será atribuido á variável aux; inicio=new(elementar);//(int*)malloc(sizeof(elementar));//Usando malloc para criar uma estrutura dinamicamente; //Também pode ser usada a função NEW, para criar, a estrutura dinâmica, e DELETE,para esvaziar a pilha de memória.(O mesmo que free(variavel(*)); inicio->numer=xx;//Usando a variável numer dentro da estrutura elementar,para atribuí-la o valor int de xx; printf("Digite o nº:[0->para exit]");pass(1); scanf_s("%d",&xx);} aux=inicio; while(aux!=NULL){ printf("%d",aux->ptr);pass(1); delete aux; aux=inicio;} stop();}
1776288a4d1522df209cca254d948e68e788234d
c4603dd6010b0f1121f2eefcb6318e6acf35e659
/Server/RefreshWalkableTilesAction.cpp
0c9865c7ccc8c116a0ec7d179cfb23438b989311
[ "MIT" ]
permissive
nandos13/NetworkingGame
8aef7ddf62844ffb13081c70726a3a68462d76c3
d15a307be4e48e84d9466ab2300f659f940df08e
refs/heads/master
2021-01-18T15:27:20.746898
2017-06-07T02:53:31
2017-06-07T02:53:31
86,654,883
2
0
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
RefreshWalkableTilesAction.cpp
#include "RefreshWalkableTilesAction.h" #include "Character.h" #include "Game.h" void RefreshWalkableTilesAction::_Execute(float dTime) { m_owner->Set1PointWalkableTiles(m_1PTileList); m_owner->Set2PointWalkableTiles(m_2PTileList); // Complete action CompleteSelf(); } RefreshWalkableTilesAction::RefreshWalkableTilesAction(Character* owner, std::list<MapVec3> list1P, std::list<MapVec3> list2P) : BaseAction(owner) { m_actionType = 4; m_1PTileList = list1P; m_2PTileList = list2P; } RefreshWalkableTilesAction::~RefreshWalkableTilesAction() { } #ifndef NETWORK_SERVER RefreshWalkableTilesAction * RefreshWalkableTilesAction::Read(RakNet::BitStream & bsIn) { // Read character ID short characterID = 0; bsIn.Read(characterID); // Find character by ID Character* c = Game::GetInstance()->FindCharacterByID(characterID); // Error check if (c == nullptr) { printf("Error: Could not find character with id: %d\n", characterID); return nullptr; } // Read 1-point move list std::list<MapVec3> list1P; unsigned int size1P = 0; bsIn.Read(size1P); for (unsigned int i = 0; i < size1P; i++) { MapVec3 pos = MapVec3(0); pos.Read(bsIn); list1P.push_back(pos); } // Read 2-point move list std::list<MapVec3> list2P; unsigned int size2P = 0; bsIn.Read(size2P); for (unsigned int i = 0; i < size2P; i++) { MapVec3 pos = MapVec3(0); pos.Read(bsIn); list2P.push_back(pos); } RefreshWalkableTilesAction* rwtA = new RefreshWalkableTilesAction(c, list1P, list2P); return rwtA; } #endif #ifdef NETWORK_SERVER void RefreshWalkableTilesAction::Write(RakNet::BitStream & bs) { // Write character index bs.Write(m_owner->GetID()); // Write 1-point distance list bs.Write((unsigned int)m_1PTileList.size()); for (auto& iter = m_1PTileList.begin(); iter != m_1PTileList.end(); iter++) (*iter).Write(bs); // Write 2-point distance list bs.Write((unsigned int)m_2PTileList.size()); for (auto& iter = m_2PTileList.begin(); iter != m_2PTileList.end(); iter++) (*iter).Write(bs); } #endif
c073656c73cbc2e6bd0ffc083549c6a24c76eca5
5e9fcc3cef85371d2dffe7de1a5d115efce0a817
/Coursera c++/course 3/Macros Update field.hpp
a5be7425a904c17420d4239f74c0051115b9a549
[]
no_license
ekaterin17/Coursera-cpp
8b754077109b931376afced3371fecf1dd12f444
1cf98a7ee58f3c9a434cc87369fc0e1e3e8f2eb2
refs/heads/master
2023-02-08T17:10:17.534093
2020-01-26T13:14:53
2020-01-26T13:14:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
315
hpp
Macros Update field.hpp
// // Macros Update field.hpp // Coursera c++ // // Created by Екатерина Кузина on 24/07/2019. // Copyright © 2019 Екатерина Кузина. All rights reserved. // #ifndef Macros_Update_field_hpp #define Macros_Update_field_hpp #include <stdio.h> #endif /* Macros_Update_field_hpp */
6a4a2f79a1a0443c0021c461cab3c3225ebe709d
5dc4d4d3bd209b0d7e54c383b83f725ab2ca97fd
/Codeforces/1325/D.cpp
daa1c4bd22c307d9728a52df04ae11f495addd48
[ "MIT" ]
permissive
mohit200008/CodeBank
3f599e0d0be4d472666a4e754c4578d440251677
061f3c1c7c61370fd2c41fc1d76262d403d16f34
refs/heads/main
2023-09-03T02:38:21.935473
2021-10-22T08:32:43
2021-10-22T08:32:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
D.cpp
/* "Won't stop until I'm phenomenal." - Phenomenal, Eminem */ #include<bits/stdc++.h> using namespace std; typedef long long int ll; #define ff first #define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define ss second #define all(c) c.begin(),c.end() #define endl "\n" #define test() int t; cin>>t; while(t--) #define fl(i,a,b) for(int i = a ; i <b ;i++) #define get(a) fl(i,0,a.size()) cin>>a[i]; #define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl; #define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl; const ll INF = 2e18; const int inf = 2e9; const int mod1 = 1e9 + 7; int main(){ Shazam; ll x,s; cin>>x>>s; if(x > s || (s-x)&1){ cout<<-1<<endl; return 0; } vector<ll> ans(3); ans[0] = x; ll diff = s-x; while(diff){ int bit = 62; for(; bit ; bit--){ if((1LL<<bit) <= diff){ bit--; break; } } assert(bit!=-1); { if((x)&(1LL<<bit)){ ans[1] += (1LL<<bit); ans[2] += (1LL<<bit); } else{ ans[0] += (1LL<<bit); ans[1] += (1LL<<bit); } diff-=2LL*(1LL<<bit); } } while( ans.back() == 0){ ans.pop_back(); } cout<<ans.size()<<endl; for(ll i : ans) cout<<i <<" "; cout<<endl; return 0; }
91b1bda92ba24062d45d12c7c325ff79f40dd5ff
c8db8e55473f2622d81bdd6449c033638014197a
/ElementalStats.cpp
9ceb849fa43ca33d5b4446808b35fc9eccd492f0
[]
no_license
rjlacanlaled/Elemental-Battle
4fba19d6a6fb4d002839ed37db1840a1d1cdea96
41eb72186a9c2967e704c31c803e2391b9e83d11
refs/heads/main
2023-03-27T10:48:24.524668
2021-03-26T12:02:37
2021-03-26T12:02:37
351,767,660
0
0
null
null
null
null
UTF-8
C++
false
false
9,816
cpp
ElementalStats.cpp
// // ElementalStats.cpp // Phase 1 - Practical - ElementalApp // // Created by RJ Lacanlale on 11/28/20. // Copyright © 2020 RJ Lacanlale. All rights reserved. // #include "ElementalStats.h" #include "Random.h" #include <string> using namespace std; // Global variables needed by some methods int hpLimit = 999; int otherStatLimit = 300; //sm = StatsManipulator instance //inp = InputValidator instance ElementalStats::ElementalStats(){ sm = new StatsManipulator(); inp = new InputValidator(); } // Generates random stats depending on the range given Stats* ElementalStats::generateRandomStats(Range* range){ Stats* randomStats = new Stats(); sm->addAllStats(randomStats, range); randomStats->mHp = randomStats->mHp * 5; return randomStats; } // Generates random stats depending on the element type Stats* ElementalStats::generateRandomStats(Element element, Range* range, int elementalBonus){ Stats* randomStats = generateRandomStats(range); switch (element) { case EARTH: sm->multiplyStat(VIT, randomStats, elementalBonus); break; case FIRE: sm->multiplyStat(INT, randomStats, elementalBonus); break; case WATER: sm->multiplyStat(DEX, randomStats, elementalBonus); break; case WIND: sm->multiplyStat(AGI, randomStats, elementalBonus); break; case ALL: case NONE: sm->multiplyAllStats(randomStats, elementalBonus * 14); break; default: throw invalid_argument("Element type not found!"); break; } return randomStats; } // Calculates the damage of the attacking player against the defending player // and takes into consideration the element type and adds bonus damage accordingly int ElementalStats::calculateDamage(Stats* attackerStats, Stats* defenderStats, ElementType* attackerElemType, ElementType* defenderElemType, int dmgBonusPercentage){ Range dmgRange; dmgRange.setLow(attackerStats->mInt - (defenderStats->mVit / 2)) ; dmgRange.setHigh(attackerStats->mInt - (defenderStats->mVit / 4)); if(dmgRange.getLow() < 1){ dmgRange.setLow(1); } if(dmgRange.getHigh() < 3){ dmgRange.setHigh(3); } if(attackerElemType->getStrength() == defenderElemType->getType() || attackerElemType->getType() == ALL){ dmgRange.setLow((dmgRange.getLow() * (dmgBonusPercentage + 100)) / 100); dmgRange.setHigh((dmgRange.getHigh() * (dmgBonusPercentage + 100))/ 100); } return Random(dmgRange); } // Calculates the hitrate of the attacking player/monster int ElementalStats::calculateHitRate(Stats* attackerStats, Stats* defenderStats){ int hitRate = (attackerStats->mDex / defenderStats->mAgi) * 100; if(hitRate > 80){ hitRate = 80; }else if(hitRate < 20){ hitRate = 20; } return hitRate; } // Rolls from 1 to 100 and compares it from the chancePercentage value given bool ElementalStats::hasChance(int chancePercentage){ if(Random(1, 100) < chancePercentage){ return true; }else{ return false; } } // Increases a stat depending on the other stat and element type int ElementalStats::increaseElementStatsFromAnotherStats(ElementType* elementType, Stats* stats, Stats* anotherStats, int percentage){ int amountToAdd = 0; amountToAdd = sm->getStatAmountByPercentage(HP, anotherStats, 35); if(stats->mHp + amountToAdd > hpLimit){ stats->mHp = hpLimit; }else{ sm->addStat(HP, stats, amountToAdd); } switch (elementType->getType()) { case EARTH: amountToAdd = sm->getStatAmountByPercentage(VIT, anotherStats, percentage); if(stats->mVit + amountToAdd > otherStatLimit){ stats->mVit = otherStatLimit; }else{ sm->addStat(VIT, stats, amountToAdd); } break; case FIRE: amountToAdd = sm->getStatAmountByPercentage(INT, anotherStats, percentage); if(stats->mInt + amountToAdd > otherStatLimit){ stats->mInt = otherStatLimit; }else{ sm->addStat(INT, stats, amountToAdd); } break; case WATER: amountToAdd = sm->getStatAmountByPercentage(DEX, anotherStats, percentage); if(stats->mDex + amountToAdd > otherStatLimit){ stats->mDex = otherStatLimit; }else{ sm->addStat(DEX, stats, amountToAdd); } break; case WIND: amountToAdd = sm->getStatAmountByPercentage(AGI, anotherStats, percentage); if(stats->mAgi + amountToAdd > otherStatLimit){ stats->mAgi = otherStatLimit; }else{ sm->addStat(AGI, stats, amountToAdd); } break; default: throw invalid_argument("Element type not found!"); break; } return amountToAdd; } // Checks whether a stat is higher than the other bool ElementalStats::isStatHigher(Stat stat, Stats* stat1, Stats* stat2){ bool isHigher = false; switch (stat) { case HP: if(stat1->mHp >= stat2->mHp){ isHigher = true; } break; case AGI: if(stat1->mAgi >= stat2->mAgi){ isHigher = true; } break; case DEX: if(stat1->mDex >= stat2->mDex){ isHigher = true; } break; case INT: if(stat1->mInt >= stat2->mInt){ isHigher = true; } break; case VIT: if(stat1->mVit >= stat2->mVit){ isHigher = true; } break; default: throw new invalid_argument("Stat not found!"); break; } return isHigher; } // Gets the actual value of higher stat from comparing 2 stats int ElementalStats::getHigherStat(Stat stat, Stats* oldStat, Stats* newStat){ int higher = 0; switch (stat) { case HP: if(isStatHigher(HP, oldStat, newStat)){ higher = oldStat->mHp; }else{ higher = newStat->mHp; } break; case AGI: if(isStatHigher(AGI, oldStat, newStat)){ higher = oldStat->mAgi; }else{ higher = newStat->mAgi; } break; case DEX: if(isStatHigher(DEX, oldStat, newStat)){ higher = oldStat->mDex; }else{ higher = newStat->mDex; } break; case INT: if(isStatHigher(INT, oldStat, newStat)){ higher = oldStat->mInt; }else{ higher = newStat->mInt; } break; case VIT: if(isStatHigher(VIT, oldStat, newStat)){ higher = oldStat->mVit; }else{ higher = newStat->mVit; } break; default: throw new invalid_argument("Stat not found!"); break; } return higher; } // Gets the higher stat from 2 differnt stats and returns it Stats* ElementalStats::getHigherStats(Stats* oldStat, Stats* newStat){ newStat->mHp = getHigherStat(HP, oldStat, newStat); newStat->mAgi = getHigherStat(AGI, oldStat, newStat); newStat->mDex = getHigherStat(DEX, oldStat, newStat); newStat->mInt = getHigherStat(INT, oldStat, newStat); newStat->mVit = getHigherStat(VIT, oldStat, newStat); return newStat; } // Display stats with the element type void ElementalStats::displayElementalStats(Stats* stats, ElementType* elementType){ printf("%-12s%-12s\n", "ELEMENT TYPE: ", elementType->toString(elementType->getType()).c_str()); printf("%-8s%-6s%-3s%-6s%-8s\n", "STRENGTH >> ", elementType->toString(elementType->getStrength()).c_str(), " | ", elementType->toString(elementType->getWeakness()).c_str(), " << WEAKNESS"); sm->displayStats(stats); }
339a8015702ded62eb4c3e30dcbe9273bc246b9d
85fb629bca868126c7583947516f56aa13124cfc
/inclassdef.cpp
682d563930a4412f0db0ad058e5228ad11164497
[]
no_license
yin8086/cpp11
207e64e7e6dceddb7fbecd3b0a272c075969e2b7
a5e9175e41b09b2db672cc37ac9ee3daefbc17a1
refs/heads/master
2021-01-22T04:40:28.748070
2013-02-26T03:47:30
2013-02-26T03:47:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
inclassdef.cpp
#include<iostream> using namespace std; struct Sales_data { int mema=4; float memb{4.34}; Sales_data()=default; Sales_data(int a, float b):mema(a),memb(b){} }; int main() { Sales_data sa; Sales_data sb(5,3.55); cout<<sa.mema<<' '<<sa.memb<<endl; cout<<sb.mema<<' '<<sb.memb<<endl; }
c5690ce28c7dd759342228359c42f6ed8297781a
45bf672454afe49b3a370e2a10f6f263837f61fd
/LED8/LED8.ino
70d2f6c7c2a772e0af807162e3b9410e169e877a
[]
no_license
BCRCO/arduino-projects-collection-a
14665c98cb932f85f221e46f67a66dcc0627ad17
1cb197a6b5045a0e379ef1fced308da5e4d99611
refs/heads/main
2023-04-19T11:55:40.011335
2021-05-07T21:47:20
2021-05-07T21:47:20
365,358,996
0
0
null
null
null
null
UTF-8
C++
false
false
393
ino
LED8.ino
//BCR int LP[] = {2, 3, 4, 5, 6, 7, 8, 9}; int OL = 7; void setup() { for (int i = 0; i < 8; i++) { pinMode(LP[i], OUTPUT); } } void loop() { OAT(); } void OAT() { int DT = 100; for (int i = 0; i <= 7; i ++ ) { int OL = i - 1; if (i == 0) { OL = 7; } digitalWrite(LP [i], HIGH); digitalWrite(LP [OL], LOW); delay(50); } }
31ec033f402554633c1309196570afeaa63f0367
0d906075ab29e3e0d48f985007db6d1d2e78caf9
/Test/testupnp/UPNPDevInfo.cpp
561521c33bd6ca706f18619c71563e83a78b1e36
[]
no_license
chenyue0102/mytestchenyue
b3010bf84f46f8b285c3a4bfe926b63bcf5ecb51
ce4dc403dcbbaee513150c823f3a26501ef1ff55
refs/heads/master
2023-08-30T23:31:33.419958
2023-08-25T09:53:05
2023-08-25T09:53:05
32,462,298
0
0
null
2023-07-20T12:15:34
2015-03-18T14:03:46
C++
UTF-8
C++
false
false
6,899
cpp
UPNPDevInfo.cpp
#include "UPNPDevInfo.h" #include <regex> #include <assert.h> extern "C" { #include "miniupnpc.h" #include "miniwget.h" } #include "UPNPProtocolSerialize.h" #include "UPNPServiceAVTransport.h" #include "UPNPServiceConnectionManager.h" #include "UPNPServiceRenderingControl.h" #include "UPNPServiceKaiShu.h" UPNPDevInfo::UPNPDevInfo() : mETarget(ETargetUnkwn) , mEType(ETypeUnkwn) , mVersion(0) { } UPNPDevInfo::~UPNPDevInfo() { } void UPNPDevInfo::setDevInfo(const char *descURL, const char *st, const char *usn, unsigned int scope_id) { mDescURL = descURL; mST = st; mUSN = usn; parseST(mST); mUUID = getUUIDFromUSN(mUSN); sendGetDeviceDescriptionDocument(mDescURL); } void UPNPDevInfo::sendGetDeviceDescriptionDocument(const std::string &url) { char *descXML = nullptr; do { char lanaddr[40] = { 0 }; int descXMLsize = 0; if (nullptr == (descXML = (char*)miniwget_getaddr(url.c_str(), &descXMLsize, lanaddr, _countof(lanaddr), 0, NULL))) { assert(false); break; } if (!SerializeHelper::UnpackValue(descXML, descXMLsize, mUPNPDDDRoot, SerializeExport::EnumSerializeFormatXml)) { assert(false); break; } //获取通信控制的url地址,如果URLBase为空,则使用获取设备描述文档的url std::string strUrl; if (mUPNPDDDRoot.URLBase.empty()) { strUrl = url; } else { strUrl = mUPNPDDDRoot.URLBase; } const int MAXHOSTNAMELEN = 64;//定义在miniwget.c中 char hostname[MAXHOSTNAMELEN + 1] = { 0 }; unsigned short port = 0; char *path = nullptr; unsigned int scope_id = 0; if (0 == parseURL(strUrl.c_str(), hostname, &port, &path, &scope_id)) { strUrl += '/'; if (0 == parseURL(strUrl.c_str(), hostname, &port, &path, &scope_id)) { assert(false); break; } } std::regex expr(R"(^urn:(\S+):service:(\S+):([0-9]+)$)", std::regex::ECMAScript | std::regex::icase); for (auto &service : mUPNPDDDRoot.device.serviceList) { //urn:schemas-upnp-org:service:AVTransport:1 std::smatch matchResult; if (std::regex_match(service.serviceType, matchResult, expr) && matchResult.size() == 4) { std::string strType = matchResult[2]; EType type = getType(strType); switch (type) { case ETypeMediaRenderer: break; case ETypeConnectionManager: mUPNPServiceConnectionManager = std::make_shared<UPNPServiceConnectionManager>(); mUPNPServiceConnectionManager->setService(service, hostname, port, scope_id); break; case ETypeAVTransport: { mAVTransport = std::make_shared<UPNPServiceAVTransport>(); mAVTransport->setService(service, hostname, port, scope_id); //std::string metaData;// = R"(<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/" xmlns:sec="http://www.sec.co.kr/"><item id="video-item-755" parentID="1" restricted="0"><dc:title>V91016-201954</dc:title><dc:creator>&lt;unknown&gt;</dc:creator><upnp:class>object.item.videoItem</upnp:class><upnp:albumArtURI>http://10.0.28.173:8192/storage/emulated/0/msi/.videothumb/video_thumb_video-item-755.png</upnp:albumArtURI><dc:description/><res protocolInfo="http-get:*:video/m3u8:*" size="90836128" duration="0:0:42" resolution="1920x1080">https://cdn.kaishuhezi.com/mcourse/m3u8/71e5c57d-a4b2-44a4-845e-9c92bfcabeaa/index.m3u8</res></item></DIDL-Lite>)"; //mAVTransport->SetAVTransportURI("0", "https://cdn.kaishuhezi.com/mcourse/m3u8/71e5c57d-a4b2-44a4-845e-9c92bfcabeaa/index.m3u8", metaData); break; } case ETypeRenderingControl: { mUPNPServiceRenderingControl = std::make_shared<UPNPServiceRenderingControl>(); mUPNPServiceRenderingControl->setService(service, hostname, port, scope_id); break; } case ETypeKaiShu: { mUPNPServiceKaiShu = std::make_shared<UPNPServiceKaiShu>(); mUPNPServiceKaiShu->setService(service, hostname, port, scope_id); break; } default: break; } } } } while (false); if (nullptr != descXML) { free(descXML); descXML = nullptr; } } UPNPServiceAVTransport * UPNPDevInfo::getAVTransport() { return mAVTransport.get(); } UPNPServiceConnectionManager* UPNPDevInfo::getConnectionManager() { return mUPNPServiceConnectionManager.get(); } UPNPServiceRenderingControl* UPNPDevInfo::getRenderingControl() { return mUPNPServiceRenderingControl.get(); } UPNPServiceKaiShu* UPNPDevInfo::getKaiShu() { return mUPNPServiceKaiShu.get();; } void UPNPDevInfo::parseST(const std::string &st) { //upnp:rootdevice 根设备 //uuid:device - UUID 表示本设备的uuid表示位device - uuid //urn : schema - upnp - org : device : device - Type : version 表示本设备类型为device - type设备,版本是version //urn : schema - upnp - org : service : service - Type : version 表示服务类型为service - type的设备,版本是version const char *strRootDevice = "upnp:rootdevice"; const char *strUUID = "uuid:"; if (0 == _stricmp(st.c_str(), strRootDevice)) { mETarget = ETargetRootDevice; } else if (0 == _strnicmp(st.c_str(), strUUID, strlen(strUUID))) { mETarget = ETargetUUID; } else { //urn:schemas-upnp-org:device:MediaRenderer:1 std::regex expr(R"(^urn:(\S+):(device|service):(\S+):([0-9]+)$)", std::regex::ECMAScript | std::regex::icase); std::smatch matchResult; if (std::regex_match(st, matchResult, expr) && matchResult.size() == 5) { //第一个为匹配的全项 std::string deviceOrServer = matchResult[2]; if (0 == _stricmp(deviceOrServer.c_str(), "device")) { mETarget = ETargetDevice; } else if (0 == _stricmp(deviceOrServer.c_str(), "service")) { mETarget = ETargetServer; } else { mETarget = ETargetUnkwn; assert(false); } std::string type = matchResult[3]; mEType = getType(type); std::string version = matchResult[4]; mVersion = atoi(version.c_str()); } } } std::string UPNPDevInfo::getUUIDFromUSN(const std::string & usn) { std::string uuid; //uuid:F7CA5454-3F48-4390-8009-283ee448c1ab::upnp:rootdevice std::regex expr(R"(^uuid:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\S*$)", std::regex::ECMAScript | std::regex::icase); std::smatch matchResult; if (std::regex_match(usn, matchResult, expr) && matchResult.size() == 2) { uuid = matchResult[1]; } return uuid; } EType UPNPDevInfo::getType(const std::string & type) { std::pair<EType, const char*> idNames[] = { { ETypeMediaRenderer,"MediaRenderer" }, { ETypeConnectionManager,"ConnectionManager" }, { ETypeAVTransport,"AVTransport" }, { ETypeRenderingControl,"RenderingControl" }, { ETypeKaiShu,"KaiShuStory" }, }; EType ret = ETypeUnkwn; for (auto &pair : idNames) { if (0 == _stricmp(pair.second, type.c_str())) { ret = pair.first; break; } } return ret; }
78470e05d8828de43aa62509f1ba88b2465e06a1
6c66f928a42f891a8b585015b2f71e44ac7b9f8d
/TutIntV30/Act1DosBB.h
c0e3dc32907ca380a9d80ab4197fdfbc68fc6c02
[]
no_license
FelipeSegovia/TutInt
5857e20d3aa0b5c10a61a788c2f73d3bde888c75
7b30644d2f9b0ca0f8901da4e70d7b2ff607c53a
refs/heads/master
2020-03-17T19:10:19.103492
2018-05-17T17:53:22
2018-05-17T17:53:22
133,848,477
0
0
null
null
null
null
ISO-8859-1
C++
false
false
37,227
h
Act1DosBB.h
#pragma once #include "BaseDeDatos.h" #include "AgenteControlador.h" #include "TiempoMI.h" #include "TiempoGUI.h" namespace TutIntV30 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Resumen de Act1DosBB /// </summary> public ref class Act1DosBB : public System::Windows::Forms::Form { public: Act1DosBB(void) { InitializeComponent(); // //TODO: agregar código de constructor aquí // } Act1DosBB(Form^ f, BaseDeDatos^ manejador, AgenteControlador* control) { form = f; manejadorBD = manejador; controlador = control; InitializeComponent(); inicializarTam(); this->Size = System::Drawing::Size(1050, 598); this->Show(); } protected: /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> ~Act1DosBB() { if (components) { delete components; } } private: int contAyuda = 0; private: BaseDeDatos ^ manejadorBD; private: AgenteControlador * controlador; private: int segundos, minutos, horas; // Para el form private: TiempoGUI ^ t_actividad, ^t_item1, ^t_item2, ^t_item3, ^t_item4; private: Thread ^ hiloAct; private: System::Windows::Forms::Form^ form; private: int wVolver, hVolver, wListo, hListo, wAyuda, hAyuda; private: bool listoOrca = false, listoCoral = false, listoAlga = false, listoPulpo = false; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::Panel^ panel6; private: System::Windows::Forms::PictureBox^ pictureBox7; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::PictureBox^ picMinimizar; private: System::Windows::Forms::PictureBox^ picCerrar; private: System::Windows::Forms::Panel^ panelPrincipal; private: System::Windows::Forms::PictureBox^ btnAyuda; private: System::Windows::Forms::Panel^ panel5; private: System::Windows::Forms::PictureBox^ btnListo; private: System::Windows::Forms::PictureBox^ btnVolver; private: System::Windows::Forms::Panel^ panel4; private: System::Windows::Forms::Label^ instruccion2; private: System::Windows::Forms::Panel^ panel1; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::PictureBox^ pictureBox2; private: System::Windows::Forms::PictureBox^ pictureBox3; private: System::Windows::Forms::PictureBox^ pictureBox4; private: System::Windows::Forms::Label^ lblOrca; private: System::Windows::Forms::Label^ lblAlga; private: System::Windows::Forms::Label^ lblPulpo; private: System::Windows::Forms::Label^ lblCoral; private: System::Windows::Forms::TextBox^ textOrca; private: System::Windows::Forms::TextBox^ textAlga; private: System::Windows::Forms::TextBox^ textPulpo; private: System::Windows::Forms::TextBox^ textCoral; private: System::Windows::Forms::Label^ instruccion1; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Variable del diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Act1DosBB::typeid)); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->panel6 = (gcnew System::Windows::Forms::Panel()); this->pictureBox7 = (gcnew System::Windows::Forms::PictureBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->picMinimizar = (gcnew System::Windows::Forms::PictureBox()); this->picCerrar = (gcnew System::Windows::Forms::PictureBox()); this->panelPrincipal = (gcnew System::Windows::Forms::Panel()); this->btnAyuda = (gcnew System::Windows::Forms::PictureBox()); this->panel5 = (gcnew System::Windows::Forms::Panel()); this->btnListo = (gcnew System::Windows::Forms::PictureBox()); this->btnVolver = (gcnew System::Windows::Forms::PictureBox()); this->panel4 = (gcnew System::Windows::Forms::Panel()); this->instruccion1 = (gcnew System::Windows::Forms::Label()); this->instruccion2 = (gcnew System::Windows::Forms::Label()); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->label2 = (gcnew System::Windows::Forms::Label()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); this->pictureBox3 = (gcnew System::Windows::Forms::PictureBox()); this->pictureBox4 = (gcnew System::Windows::Forms::PictureBox()); this->lblOrca = (gcnew System::Windows::Forms::Label()); this->textOrca = (gcnew System::Windows::Forms::TextBox()); this->lblAlga = (gcnew System::Windows::Forms::Label()); this->lblCoral = (gcnew System::Windows::Forms::Label()); this->lblPulpo = (gcnew System::Windows::Forms::Label()); this->textAlga = (gcnew System::Windows::Forms::TextBox()); this->textCoral = (gcnew System::Windows::Forms::TextBox()); this->textPulpo = (gcnew System::Windows::Forms::TextBox()); this->panel6->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picMinimizar))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picCerrar))->BeginInit(); this->panelPrincipal->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnAyuda))->BeginInit(); this->panel5->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnListo))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnVolver))->BeginInit(); this->panel4->SuspendLayout(); this->panel1->SuspendLayout(); this->tableLayoutPanel1->SuspendLayout(); this->panel2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->BeginInit(); this->SuspendLayout(); // // timer1 // this->timer1->Interval = 1; this->timer1->Tick += gcnew System::EventHandler(this, &Act1DosBB::timer1_Tick); // // panel6 // this->panel6->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel6.BackgroundImage"))); this->panel6->Controls->Add(this->pictureBox7); this->panel6->Controls->Add(this->label1); this->panel6->Controls->Add(this->picMinimizar); this->panel6->Controls->Add(this->picCerrar); this->panel6->Dock = System::Windows::Forms::DockStyle::Top; this->panel6->Location = System::Drawing::Point(0, 0); this->panel6->Margin = System::Windows::Forms::Padding(1); this->panel6->Name = L"panel6"; this->panel6->Size = System::Drawing::Size(832, 31); this->panel6->TabIndex = 5; // // pictureBox7 // this->pictureBox7->BackColor = System::Drawing::Color::Transparent; this->pictureBox7->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox7.BackgroundImage"))); this->pictureBox7->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox7->Location = System::Drawing::Point(5, 2); this->pictureBox7->Margin = System::Windows::Forms::Padding(1); this->pictureBox7->Name = L"pictureBox7"; this->pictureBox7->Size = System::Drawing::Size(31, 28); this->pictureBox7->TabIndex = 33; this->pictureBox7->TabStop = false; // // label1 // this->label1->AutoSize = true; this->label1->BackColor = System::Drawing::Color::Transparent; this->label1->Font = (gcnew System::Drawing::Font(L"Lucida Sans", 16, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label1->ForeColor = System::Drawing::Color::White; this->label1->Location = System::Drawing::Point(35, 3); this->label1->Margin = System::Windows::Forms::Padding(1, 0, 1, 0); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(100, 25); this->label1->TabIndex = 32; this->label1->Text = L"TUTINT"; // // picMinimizar // this->picMinimizar->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->picMinimizar->BackColor = System::Drawing::Color::Transparent; this->picMinimizar->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"picMinimizar.BackgroundImage"))); this->picMinimizar->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->picMinimizar->Location = System::Drawing::Point(767, 2); this->picMinimizar->Margin = System::Windows::Forms::Padding(1); this->picMinimizar->Name = L"picMinimizar"; this->picMinimizar->Size = System::Drawing::Size(27, 26); this->picMinimizar->TabIndex = 31; this->picMinimizar->TabStop = false; this->picMinimizar->Click += gcnew System::EventHandler(this, &Act1DosBB::picMinimizar_Click); // // picCerrar // this->picCerrar->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->picCerrar->BackColor = System::Drawing::Color::Transparent; this->picCerrar->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"picCerrar.BackgroundImage"))); this->picCerrar->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->picCerrar->Location = System::Drawing::Point(800, 2); this->picCerrar->Margin = System::Windows::Forms::Padding(1); this->picCerrar->Name = L"picCerrar"; this->picCerrar->Size = System::Drawing::Size(27, 26); this->picCerrar->TabIndex = 30; this->picCerrar->TabStop = false; this->picCerrar->Click += gcnew System::EventHandler(this, &Act1DosBB::picCerrar_Click); // // panelPrincipal // this->panelPrincipal->BackColor = System::Drawing::Color::Transparent; this->panelPrincipal->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panelPrincipal.BackgroundImage"))); this->panelPrincipal->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panelPrincipal->Controls->Add(this->btnAyuda); this->panelPrincipal->Controls->Add(this->panel5); this->panelPrincipal->Controls->Add(this->panel4); this->panelPrincipal->Controls->Add(this->panel1); this->panelPrincipal->Dock = System::Windows::Forms::DockStyle::Fill; this->panelPrincipal->Location = System::Drawing::Point(0, 0); this->panelPrincipal->Margin = System::Windows::Forms::Padding(1); this->panelPrincipal->Name = L"panelPrincipal"; this->panelPrincipal->Size = System::Drawing::Size(832, 494); this->panelPrincipal->TabIndex = 4; // // btnAyuda // this->btnAyuda->BackColor = System::Drawing::Color::Transparent; this->btnAyuda->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnAyuda.BackgroundImage"))); this->btnAyuda->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnAyuda->Location = System::Drawing::Point(12, 38); this->btnAyuda->Margin = System::Windows::Forms::Padding(1); this->btnAyuda->Name = L"btnAyuda"; this->btnAyuda->Size = System::Drawing::Size(183, 112); this->btnAyuda->TabIndex = 11; this->btnAyuda->TabStop = false; this->btnAyuda->Click += gcnew System::EventHandler(this, &Act1DosBB::btnAyuda_Click); this->btnAyuda->MouseLeave += gcnew System::EventHandler(this, &Act1DosBB::btnAyuda_MouseLeave); this->btnAyuda->MouseHover += gcnew System::EventHandler(this, &Act1DosBB::btnAyuda_MouseHover); // // panel5 // this->panel5->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel5.BackgroundImage"))); this->panel5->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel5->Controls->Add(this->btnListo); this->panel5->Controls->Add(this->btnVolver); this->panel5->Location = System::Drawing::Point(17, 324); this->panel5->Margin = System::Windows::Forms::Padding(1); this->panel5->Name = L"panel5"; this->panel5->Size = System::Drawing::Size(207, 230); this->panel5->TabIndex = 10; // // btnListo // this->btnListo->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnListo.BackgroundImage"))); this->btnListo->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnListo->Enabled = false; this->btnListo->Location = System::Drawing::Point(25, 90); this->btnListo->Margin = System::Windows::Forms::Padding(1); this->btnListo->Name = L"btnListo"; this->btnListo->Size = System::Drawing::Size(171, 66); this->btnListo->TabIndex = 1; this->btnListo->TabStop = false; this->btnListo->Visible = false; this->btnListo->Click += gcnew System::EventHandler(this, &Act1DosBB::btnListo_Click); this->btnListo->MouseLeave += gcnew System::EventHandler(this, &Act1DosBB::btnListo_MouseLeave); this->btnListo->MouseHover += gcnew System::EventHandler(this, &Act1DosBB::btnListo_MouseHover); // // btnVolver // this->btnVolver->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnVolver.BackgroundImage"))); this->btnVolver->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnVolver->Location = System::Drawing::Point(10, 23); this->btnVolver->Margin = System::Windows::Forms::Padding(1); this->btnVolver->Name = L"btnVolver"; this->btnVolver->Size = System::Drawing::Size(181, 69); this->btnVolver->TabIndex = 0; this->btnVolver->TabStop = false; this->btnVolver->Click += gcnew System::EventHandler(this, &Act1DosBB::btnVolver_Click); this->btnVolver->MouseLeave += gcnew System::EventHandler(this, &Act1DosBB::btnVolver_MouseLeave); this->btnVolver->MouseHover += gcnew System::EventHandler(this, &Act1DosBB::btnVolver_MouseHover); // // panel4 // this->panel4->BackColor = System::Drawing::Color::Transparent; this->panel4->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel4.BackgroundImage"))); this->panel4->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel4->Controls->Add(this->instruccion1); this->panel4->Controls->Add(this->instruccion2); this->panel4->Location = System::Drawing::Point(196, 32); this->panel4->Margin = System::Windows::Forms::Padding(1); this->panel4->Name = L"panel4"; this->panel4->Size = System::Drawing::Size(839, 41); this->panel4->TabIndex = 7; // // instruccion1 // this->instruccion1->AutoSize = true; this->instruccion1->BackColor = System::Drawing::Color::Transparent; this->instruccion1->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 16.125F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->instruccion1->ForeColor = System::Drawing::Color::White; this->instruccion1->Location = System::Drawing::Point(34, 3); this->instruccion1->Margin = System::Windows::Forms::Padding(1, 0, 1, 0); this->instruccion1->Name = L"instruccion1"; this->instruccion1->Size = System::Drawing::Size(600, 31); this->instruccion1->TabIndex = 5; this->instruccion1->Text = L"Contemos la cantidad de letras que tiene cada palabra"; // // instruccion2 // this->instruccion2->AutoSize = true; this->instruccion2->BackColor = System::Drawing::Color::Transparent; this->instruccion2->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 16.125F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->instruccion2->ForeColor = System::Drawing::Color::White; this->instruccion2->Location = System::Drawing::Point(32, 4); this->instruccion2->Margin = System::Windows::Forms::Padding(1, 0, 1, 0); this->instruccion2->Name = L"instruccion2"; this->instruccion2->Size = System::Drawing::Size(811, 31); this->instruccion2->TabIndex = 4; this->instruccion2->Text = L"Debes contar cuántas letras tiene cada palabra y anotarlo en el cuadrado"; this->instruccion2->Visible = false; // // panel1 // this->panel1->BackColor = System::Drawing::Color::Transparent; this->panel1->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel1.BackgroundImage"))); this->panel1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel1->Controls->Add(this->tableLayoutPanel1); this->panel1->Location = System::Drawing::Point(266, 75); this->panel1->Margin = System::Windows::Forms::Padding(1); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(732, 512); this->panel1->TabIndex = 0; // // tableLayoutPanel1 // this->tableLayoutPanel1->ColumnCount = 3; this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 33.33333F))); this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 33.33334F))); this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 33.33334F))); this->tableLayoutPanel1->Controls->Add(this->panel2, 2, 0); this->tableLayoutPanel1->Controls->Add(this->pictureBox1, 0, 1); this->tableLayoutPanel1->Controls->Add(this->pictureBox2, 0, 2); this->tableLayoutPanel1->Controls->Add(this->pictureBox3, 0, 3); this->tableLayoutPanel1->Controls->Add(this->pictureBox4, 0, 4); this->tableLayoutPanel1->Controls->Add(this->lblOrca, 1, 1); this->tableLayoutPanel1->Controls->Add(this->textOrca, 2, 1); this->tableLayoutPanel1->Controls->Add(this->lblAlga, 1, 3); this->tableLayoutPanel1->Controls->Add(this->lblCoral, 1, 2); this->tableLayoutPanel1->Controls->Add(this->lblPulpo, 1, 4); this->tableLayoutPanel1->Controls->Add(this->textAlga, 2, 3); this->tableLayoutPanel1->Controls->Add(this->textCoral, 2, 2); this->tableLayoutPanel1->Controls->Add(this->textPulpo, 2, 4); this->tableLayoutPanel1->Location = System::Drawing::Point(105, 73); this->tableLayoutPanel1->Margin = System::Windows::Forms::Padding(2); this->tableLayoutPanel1->Name = L"tableLayoutPanel1"; this->tableLayoutPanel1->RowCount = 5; this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 11.11111F))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.22222F))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.22222F))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.22222F))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.22222F))); this->tableLayoutPanel1->Size = System::Drawing::Size(545, 369); this->tableLayoutPanel1->TabIndex = 0; // // panel2 // this->panel2->Controls->Add(this->label2); this->panel2->Dock = System::Windows::Forms::DockStyle::Fill; this->panel2->Location = System::Drawing::Point(364, 2); this->panel2->Margin = System::Windows::Forms::Padding(2); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(179, 36); this->panel2->TabIndex = 0; // // label2 // this->label2->AutoSize = true; this->label2->BackColor = System::Drawing::Color::Transparent; this->label2->Dock = System::Windows::Forms::DockStyle::Fill; this->label2->Font = (gcnew System::Drawing::Font(L"Century Gothic", 16, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label2->ForeColor = System::Drawing::Color::Black; this->label2->Location = System::Drawing::Point(0, 0); this->label2->Margin = System::Windows::Forms::Padding(2, 0, 2, 0); this->label2->Name = L"label2"; this->label2->Padding = System::Windows::Forms::Padding(7, 6, 7, 6); this->label2->Size = System::Drawing::Size(196, 38); this->label2->TabIndex = 1; this->label2->Text = L"TOTAL DE LETRAS"; // // pictureBox1 // this->pictureBox1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)); this->pictureBox1->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox1.BackgroundImage"))); this->pictureBox1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox1->Location = System::Drawing::Point(20, 42); this->pictureBox1->Margin = System::Windows::Forms::Padding(2); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(140, 77); this->pictureBox1->TabIndex = 1; this->pictureBox1->TabStop = false; // // pictureBox2 // this->pictureBox2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)); this->pictureBox2->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox2.BackgroundImage"))); this->pictureBox2->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox2->Location = System::Drawing::Point(31, 123); this->pictureBox2->Margin = System::Windows::Forms::Padding(2); this->pictureBox2->Name = L"pictureBox2"; this->pictureBox2->Size = System::Drawing::Size(118, 77); this->pictureBox2->TabIndex = 2; this->pictureBox2->TabStop = false; // // pictureBox3 // this->pictureBox3->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)); this->pictureBox3->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox3.BackgroundImage"))); this->pictureBox3->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox3->Location = System::Drawing::Point(39, 204); this->pictureBox3->Margin = System::Windows::Forms::Padding(2); this->pictureBox3->Name = L"pictureBox3"; this->pictureBox3->Size = System::Drawing::Size(103, 77); this->pictureBox3->TabIndex = 3; this->pictureBox3->TabStop = false; // // pictureBox4 // this->pictureBox4->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)); this->pictureBox4->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox4.BackgroundImage"))); this->pictureBox4->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox4->Location = System::Drawing::Point(20, 285); this->pictureBox4->Margin = System::Windows::Forms::Padding(2); this->pictureBox4->Name = L"pictureBox4"; this->pictureBox4->Size = System::Drawing::Size(140, 82); this->pictureBox4->TabIndex = 4; this->pictureBox4->TabStop = false; // // lblOrca // this->lblOrca->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->lblOrca->AutoSize = true; this->lblOrca->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblOrca->ForeColor = System::Drawing::Color::OrangeRed; this->lblOrca->Location = System::Drawing::Point(183, 40); this->lblOrca->Margin = System::Windows::Forms::Padding(2, 0, 2, 0); this->lblOrca->Name = L"lblOrca"; this->lblOrca->Size = System::Drawing::Size(177, 81); this->lblOrca->TabIndex = 5; this->lblOrca->Text = L"ORCA"; this->lblOrca->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; // // textOrca // this->textOrca->Anchor = System::Windows::Forms::AnchorStyles::None; this->textOrca->BackColor = System::Drawing::Color::OrangeRed; this->textOrca->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textOrca->ForeColor = System::Drawing::Color::White; this->textOrca->Location = System::Drawing::Point(420, 48); this->textOrca->Margin = System::Windows::Forms::Padding(2); this->textOrca->Name = L"textOrca"; this->textOrca->Size = System::Drawing::Size(66, 64); this->textOrca->TabIndex = 9; this->textOrca->TextAlign = System::Windows::Forms::HorizontalAlignment::Center; this->textOrca->Click += gcnew System::EventHandler(this, &Act1DosBB::textOrca_Click); this->textOrca->TextChanged += gcnew System::EventHandler(this, &Act1DosBB::textOrca_TextChanged); this->textOrca->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Act1DosBB::textOrca_KeyPress); // // lblAlga // this->lblAlga->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->lblAlga->AutoSize = true; this->lblAlga->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblAlga->Location = System::Drawing::Point(183, 202); this->lblAlga->Margin = System::Windows::Forms::Padding(2, 0, 2, 0); this->lblAlga->Name = L"lblAlga"; this->lblAlga->Size = System::Drawing::Size(177, 81); this->lblAlga->TabIndex = 6; this->lblAlga->Text = L"ALGA"; this->lblAlga->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; // // lblCoral // this->lblCoral->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->lblCoral->AutoSize = true; this->lblCoral->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblCoral->Location = System::Drawing::Point(183, 121); this->lblCoral->Margin = System::Windows::Forms::Padding(2, 0, 2, 0); this->lblCoral->Name = L"lblCoral"; this->lblCoral->Size = System::Drawing::Size(177, 81); this->lblCoral->TabIndex = 8; this->lblCoral->Text = L"CORAL"; this->lblCoral->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; // // lblPulpo // this->lblPulpo->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->lblPulpo->AutoSize = true; this->lblPulpo->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblPulpo->Location = System::Drawing::Point(183, 283); this->lblPulpo->Margin = System::Windows::Forms::Padding(2, 0, 2, 0); this->lblPulpo->Name = L"lblPulpo"; this->lblPulpo->Size = System::Drawing::Size(177, 86); this->lblPulpo->TabIndex = 7; this->lblPulpo->Text = L"PULPO"; this->lblPulpo->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; // // textAlga // this->textAlga->Anchor = System::Windows::Forms::AnchorStyles::None; this->textAlga->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textAlga->Location = System::Drawing::Point(420, 210); this->textAlga->Margin = System::Windows::Forms::Padding(2); this->textAlga->Name = L"textAlga"; this->textAlga->Size = System::Drawing::Size(66, 64); this->textAlga->TabIndex = 10; this->textAlga->TextAlign = System::Windows::Forms::HorizontalAlignment::Center; this->textAlga->Click += gcnew System::EventHandler(this, &Act1DosBB::textAlga_Click); this->textAlga->TextChanged += gcnew System::EventHandler(this, &Act1DosBB::textAlga_TextChanged); this->textAlga->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Act1DosBB::textAlga_KeyPress); // // textCoral // this->textCoral->Anchor = System::Windows::Forms::AnchorStyles::None; this->textCoral->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textCoral->Location = System::Drawing::Point(420, 129); this->textCoral->Margin = System::Windows::Forms::Padding(2); this->textCoral->Name = L"textCoral"; this->textCoral->Size = System::Drawing::Size(66, 64); this->textCoral->TabIndex = 12; this->textCoral->TextAlign = System::Windows::Forms::HorizontalAlignment::Center; this->textCoral->Click += gcnew System::EventHandler(this, &Act1DosBB::textCoral_Click); this->textCoral->TextChanged += gcnew System::EventHandler(this, &Act1DosBB::textCoral_TextChanged); this->textCoral->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Act1DosBB::textCoral_KeyPress); // // textPulpo // this->textPulpo->Anchor = System::Windows::Forms::AnchorStyles::None; this->textPulpo->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textPulpo->Location = System::Drawing::Point(420, 294); this->textPulpo->Margin = System::Windows::Forms::Padding(2); this->textPulpo->Name = L"textPulpo"; this->textPulpo->Size = System::Drawing::Size(66, 64); this->textPulpo->TabIndex = 11; this->textPulpo->TextAlign = System::Windows::Forms::HorizontalAlignment::Center; this->textPulpo->Click += gcnew System::EventHandler(this, &Act1DosBB::textPulpo_Click); this->textPulpo->TextChanged += gcnew System::EventHandler(this, &Act1DosBB::textPulpo_TextChanged); this->textPulpo->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Act1DosBB::textPulpo_KeyPress); // // Act1DosBB // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(832, 494); this->Controls->Add(this->panel6); this->Controls->Add(this->panelPrincipal); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None; this->Margin = System::Windows::Forms::Padding(2); this->Name = L"Act1DosBB"; this->Opacity = 0; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen; this->Text = L"Act1DosBB"; this->Activated += gcnew System::EventHandler(this, &Act1DosBB::Act1DosBB_Activated); this->Deactivate += gcnew System::EventHandler(this, &Act1DosBB::Act1DosBB_Deactivate); this->Load += gcnew System::EventHandler(this, &Act1DosBB::Act1DosBB_Load); this->panel6->ResumeLayout(false); this->panel6->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picMinimizar))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picCerrar))->EndInit(); this->panelPrincipal->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnAyuda))->EndInit(); this->panel5->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnListo))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnVolver))->EndInit(); this->panel4->ResumeLayout(false); this->panel4->PerformLayout(); this->panel1->ResumeLayout(false); this->tableLayoutPanel1->ResumeLayout(false); this->tableLayoutPanel1->PerformLayout(); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->EndInit(); this->ResumeLayout(false); } #pragma endregion private: void inicializarTam(); private: void comprobarRespuestas(); private: void sonidoInicial(); private: void cambiarColor(); private: System::Void btnAyuda_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void btnAyuda_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnAyuda_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void picCerrar_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void picMinimizar_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void Act1DosBB_Load(System::Object^ sender, System::EventArgs^ e); private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e); private: System::Void Act1DosBB_Activated(System::Object^ sender, System::EventArgs^ e); private: System::Void Act1DosBB_Deactivate(System::Object^ sender, System::EventArgs^ e); private: System::Void tiempo_respuesta(int numItem, TiempoGUI^ tr_item, System::Windows::Forms::TextBox^ textBox); private: vector<TiempoMI*> obtenerTiempoItems(); private: System::Void textOrca_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e); private: System::Void textPulpo_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e); private: System::Void textCoral_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e); private: System::Void textAlga_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e); private: System::Void textOrca_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void textPulpo_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void textCoral_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void textAlga_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void textOrca_TextChanged(System::Object^ sender, System::EventArgs^ e); private: System::Void textPulpo_TextChanged(System::Object^ sender, System::EventArgs^ e); private: System::Void textCoral_TextChanged(System::Object^ sender, System::EventArgs^ e); private: System::Void textAlga_TextChanged(System::Object^ sender, System::EventArgs^ e); }; }
d65a66bbb29854bee78db62512f7f8e9215f7194
4f28872d770b538d0d592ef350f31dedf446491e
/@HC_DAYZ/addons/dayz_code/Configs/CfgVehicles.hpp
1024df1af358edc103a98755661d30b0abae6662
[]
no_license
SurvivalOperations/HardCorps
5e28f62f395df07ef960d9bae323f7ccea8f00bf
2237cec52003060599331f846849434be8d4d1b0
refs/heads/master
2021-01-10T22:22:33.298171
2013-12-11T19:50:27
2013-12-11T19:50:27
13,457,768
0
2
null
null
null
null
UTF-8
C++
false
false
4,912
hpp
CfgVehicles.hpp
class CfgVehicles { class AllVehicles; class Air : AllVehicles { class NewTurret; class ViewPilot; class AnimationSources; }; class Helicopter : Air { class HitPoints; class Turrets { class MainTurret: NewTurret { class Turrets; class ViewOptics; }; }; }; //External Class class SkodaBase; class ATV_Base_EP1; class RubberBoat; class UAZ_Unarmed_Base; class HMMWV_Base; class AH6_Base_EP1; class An2_Base_EP1; class TT650_Base; class V3S_Base; class SUV_Base_EP1; class Ship; //class Bag_Base_EP1; //class Bag_Base_BAF; class House { class DestructionEffects; }; class SpawnableWreck : House {}; class Strategic; class NonStrategic; class Land_Fire; class Animal; class Pastor; #include "CfgVehicles\RepairParts.hpp" //names for all reapir parts. Needs moving to hitpoints //ZEDS #include "CfgVehicles\Zeds\Zeds.hpp" //old type zeds #include "CfgVehicles\Zeds\ViralZeds.hpp" //Viral type zeds #include "CfgVehicles\Zeds\WildZeds.hpp" //Viral type zeds //Survivor Skins #include "CfgVehicles\Skins.hpp" //Bags #include "CfgVehicles\Bags.hpp" //DZAnimal and DZ_Fin #include "CfgVehicles\Animal.hpp" //Includes all DayZ Vehilces //Car's #include "CfgVehicles\Car\HMMWV.hpp" #include "CfgVehicles\Car\CAR_HATCHBACK.hpp" #include "CfgVehicles\Car\UAZ_CDF.hpp" #include "CfgVehicles\Car\CAR_SEDAN.hpp" #include "CfgVehicles\Car\V3S_Civ.hpp" #include "CfgVehicles\Car\SUV_DZ.hpp" //Helicopter's #include "CfgVehicles\Helicopter\MI17.hpp" #include "CfgVehicles\Helicopter\UH1H.hpp" #include "CfgVehicles\Helicopter\UH1H2.hpp" #include "CfgVehicles\Helicopter\AH6X.hpp" #include "CfgVehicles\Helicopter\MH6J_DZ.hpp" //Wreck's #include "CfgVehicles\Helicopter\MI8Wreck.hpp" #include "CfgVehicles\Helicopter\UH1Wreck.hpp" #include "CfgVehicles\Helicopter\UH60Wreck.hpp" //Plane's #include "CfgVehicles\Plane\AN2_DZ.hpp" //Bikes #include "CfgVehicles\Bikes\ATV_US_EP1.hpp" #include "CfgVehicles\Bikes\ATV_CZ_EP1.hpp" #include "CfgVehicles\Bikes\TT650_Ins.hpp" //Boat #include "CfgVehicles\Boat\PBX.hpp" #include "CfgVehicles\Boat\Fishing_Boat.hpp" //Includes all Building Stuff // This parent class is made to make referring to these objects easier later with allMissionObjects #include "CfgVehicles\Buildings\HouseDZ.hpp" //Fire #include "CfgVehicles\Buildings\Land_Fire.hpp" //Buildings #include "CfgVehicles\Buildings\Land_A_Crane_02b.hpp" #include "CfgVehicles\Buildings\Land_A_FuelStation_Feed.hpp" #include "CfgVehicles\Buildings\Land_A_TVTower_Mid.hpp" #include "CfgVehicles\Buildings\Land_A_TVTower_Top.hpp" #include "CfgVehicles\Buildings\Land_Farm_WTower.hpp" #include "CfgVehicles\Buildings\Land_HouseB_Tenement.hpp" #include "CfgVehicles\Buildings\Land_Ind_MalyKomin.hpp" #include "CfgVehicles\Buildings\Land_komin.hpp" #include "CfgVehicles\Buildings\Land_majak.hpp" #include "CfgVehicles\Buildings\Land_Mil_ControlTower.hpp" #include "CfgVehicles\Buildings\Land_NAV_Lighthouse.hpp" #include "CfgVehicles\Buildings\Land_NavigLight.hpp" #include "CfgVehicles\Buildings\Land_Rail_Semafor.hpp" #include "CfgVehicles\Buildings\Land_Rail_Zavora.hpp" #include "CfgVehicles\Buildings\Land_runway_edgelight.hpp" #include "CfgVehicles\Buildings\Land_Stoplight.hpp" #include "CfgVehicles\Buildings\Land_telek1.hpp" #include "CfgVehicles\Buildings\Land_VASICore.hpp" #include "CfgVehicles\Buildings\Land_Vysilac_FM.hpp" //camo #include "CfgVehicles\CamoNetting.hpp" //WeaponHolder #include "CfgVehicles\WeaponHolder.hpp" //itemBox's #include "CfgVehicles\CardboardBox.hpp" //Tents,storage #include "CfgVehicles\Storage.hpp" // Traps #include "CfgVehicles\Traps.hpp" //Antihack #include "CfgVehicles\antihack_logic.hpp" #include "CfgVehicles\antihack_plants.hpp" //WorldPlants class Building; class Plant_Base: Building { scope = 2; displayname = "Plant Sphere 100cm"; favouritezones = "(meadow) * (forest) * (1 - houses) * (1 - sea)"; }; class Dayz_Plant1: Plant_Base { displayname = $STR_ITEM_NAME_comfrey; output = "equip_comfreyleafs"; outamount = "1"; favouritezones = "(meadow) * (forest) * (1 - houses) * (1 - sea)"; model = "z\addons\dayz_communityassets\models\comfrey_up_mid.p3d"; }; class Dayz_Plant2: Plant_Base { displayname = $STR_ITEM_NAME_comfrey; output = "equip_comfreyleafs"; outamount = "1"; favouritezones = "(meadow) * (forest) * (1 - houses) * (1 - sea)"; model = "z\addons\dayz_communityassets\models\comfrey_up_small.p3d"; }; class Dayz_Plant3: Plant_Base { displayname = $STR_ITEM_NAME_comfrey; output = "equip_comfreyleafs"; outamount = "1"; favouritezones = "(meadow) * (forest) * (1 - houses) * (1 - sea)"; model = "z\addons\dayz_communityassets\models\comfrey_up.p3d"; }; }; class CfgNonAIVehicles { #include "CfgVehicles\StreetLamps.hpp" };
f3895bd91af038643c6fa6c0c7f0835270a7a549
dc7efcff1991aa6a0e18bfa61dd600998b1e8ffe
/src/renderer/GameTexture.cpp
c8e6a5679af8f26df40cde86021f02339e0557b9
[ "MIT" ]
permissive
suijingfeng/bsp_vulkan
ce0ea68ec5dd2eef18ce512a226d4c8d1c80f344
8f96b164b30d6860e2a2861e1809bf693f0c8de0
refs/heads/master
2020-03-18T04:19:26.149795
2018-05-21T21:47:27
2018-05-21T21:47:27
134,281,827
2
0
null
null
null
null
UTF-8
C++
false
false
1,476
cpp
GameTexture.cpp
#include "RenderContext.hpp" #include "GameTexture.hpp" #include "stb_image.h" extern RenderContext g_renderContext; GameTexture::GameTexture(const char *filename) { VkFormatProperties fp = {}; vkGetPhysicalDeviceFormatProperties(g_renderContext.device.physical, VK_FORMAT_R8G8B8_UNORM, &fp); // force rgba if rgb format is not supported by the device if (fp.optimalTilingFeatures > 0) { m_textureData = stbi_load(filename, &m_width, &m_height, &m_components, STBI_default); } else { m_textureData = stbi_load(filename, &m_width, &m_height, &m_components, STBI_rgb_alpha); m_components = 4; } } GameTexture::~GameTexture() { if (m_textureData != nullptr) stbi_image_free(m_textureData); vk::releaseTexture(g_renderContext.device, m_vkTexture); } bool GameTexture::Load(const VkCommandPool &commandPool, bool filtering) { // texture already loaded or doesn't exist if (!m_textureData) return false; if (!filtering) { m_vkTexture.minFilter = VK_FILTER_NEAREST; m_vkTexture.magFilter = VK_FILTER_NEAREST; } m_vkTexture.format = m_components == 3 ? VK_FORMAT_R8G8B8_UNORM : VK_FORMAT_R8G8B8A8_UNORM; vk::createTexture(g_renderContext.device, commandPool, &m_vkTexture, m_textureData, m_width, m_height); stbi_image_free(m_textureData); m_textureData = nullptr; return true; }
9eacf9ab565752bb289d42ae76f8cff341057af3
f48e59cf18c2aa9d4db664e2db1617b8026ab7cb
/DemxEngine/Entity.cpp
98f2663f586a27d9c44280da7fd13dd432df1c62
[]
no_license
demian-floreani/DemxEngine
cade252fec9aabc4fbc56f5606aea3668ea5012c
4799e87427ac9148f97d84d9b4b36ea54289c610
refs/heads/master
2020-05-17T01:22:24.615089
2019-05-18T10:08:16
2019-05-18T10:08:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,568
cpp
Entity.cpp
#include "stdafx.h" #include "Shader.h" #include "Entity.h" /** * @brief Constructor for entity * * @author Demian Floreani * * @param[in] drawType How to draw the entity. GL_TRIANGLES is the default method. * * @return None */ Demx::Entity::Entity( GLuint drawType ) { VAO = 0; IB = 0; distance = 0.0f; hasTransparency = GL_FALSE; resetModelMatrix(); this->drawType = drawType; model = ""; name = ""; shader = "main"; glModel = nullptr; castShadow = GL_TRUE; } Demx::Entity::~Entity() { } /** * @brief Query if entity is a model * * @author Demian Floreani * * @return GLboolean If true the entity is a loaded model */ GLboolean Demx::Entity::isModel() { return glModel != nullptr; } /** * @brief Query if entity uses indexed drawing * * @author Demian Floreani * * @return GLboolean If true indexed drawing is used */ GLboolean Demx::Entity::isIndexed() { return indices.size() != 0; } /** * @brief Set if the entity casts a shadow * * @author Demian Floreani * * @param[in] castShadow If set to true the entity casts a shadow * * @return None */ GLvoid Demx::Entity::setCastShadow( GLboolean castShadow ) { this->castShadow = castShadow; } /** * @brief Query if entity is casting a shadow * * @author Demian Floreani * * @return GLboolean If true entity is casting a shadow */ GLboolean Demx::Entity::isCastingShadow() { return castShadow; } /** * @brief Specify what happens before drawing the entity. This can be overloaded by derived classes. * * @author Demian Floreani * * @param[in] Shader* A pointer to a shader program * * @return None */ GLvoid Demx::Entity::onStartDraw( Demx::Shader* program ) { } /** * @brief Specify what happens after drawing the entity. This can be overloaded by derived classes. * * @author Demian Floreani * * @return None */ GLvoid Demx::Entity::onEndDraw() { } /** * @brief Add a position vertex to the user defined mesh. * * @author Demian Floreani * * @param[in] position VEC3 representing a 3D vertex * * @return None */ GLvoid Demx::Entity::position( VEC3 position ) { this->vertices.push_back( position ); } /** * @brief Add a texture mapping to the user defined mesh. * * @author Demian Floreani * * @param[in] mapping VEC2 representing a texture coordinate * * @return None */ GLvoid Demx::Entity::map( VEC2 mapping ) { this->mappings.push_back( mapping ); } /** * @brief Add a normal to the user defined mesh. * * @author Demian Floreani * * @param[in] normal VEC3 representing a normal vector * * @return None */ GLvoid Demx::Entity::normal( VEC3 normal ) { this->normals.push_back( normal ); } /** * @brief Add a triangle to the user defined mesh. The Normals of the triangle will be also calculated. * * @author Demian Floreani * * @param[in] v1 First triangle * @param[in] v2 Second triangle * @param[in] v3 Third triangle * * @return None */ GLvoid Demx::Entity::triangle( VEC3 v1, VEC3 v2, VEC3 v3 ) { this->position( v1 ); this->position( v2 ); this->position( v3 ); // calculate the normal of the triangle VEC3 triangleNormal = NORMALIZE( glm::cross( v2 - v1, v3 - v1 ) ); for( int i = 0; i < 3; ++i ) this->normal( triangleNormal ); } /** * @brief Set the normal for a triangle face. Only works when drawing in triangle mode. * * @author Demian Floreani * * @param[in] normal VEC3 representing a nomal vector. * * @return None */ GLvoid Demx::Entity::setFaceNormal( VEC3 normal ) { switch( this->drawType ) { case GL_TRIANGLES: for( GLuint i = 0; i < 3; ++i ) this->normal( normal ); return; case GL_TRIANGLE_STRIP: for( GLuint i = 0; i < 4; ++i ) this->normal( normal ); return; } } /** * @brief Set a material. * * @author Demian Floreani * * @param[in] material Name of the material. * * @return None */ GLvoid Demx::Entity::setMaterial( std::string material ) { this->material = material; } /** * @brief Move the entity * * @author Demian Floreani * * @param[in] destination A VEC3 specifying the destination position * @param[in] speed The speed of movement * @param[in] timeDelta The time delta to allow time based movement * * @return None */ GLvoid Demx::Entity::move( const VEC3& destination, GLfloat speed, GLfloat timeDelta ) { VEC3 direction = NORMALIZE( destination - this->getPosition() ); VEC3 pos = this->getPosition(); if( glm::distance( destination, this->getPosition() ) >= 0.1f ) { this->translate( direction * speed * timeDelta ); } } /** * @brief Set the entity name * * @author Demian Floreani * * @param[in] name String * * @return None */ GLvoid Demx::Entity::setName( const std::string& name ) { this->name = name; } /** * @brief Reset the model matrix to an identity matrix * * @author Demian Floreani * * @return None */ GLvoid Demx::Entity::resetModelMatrix() { modelMatrix = MAT4( 1.0f ); } /** * @brief Translate the entity by an amount specified by a 3D vector * * @author Demian Floreani * * @param[in] vector The amount to translate * * @return None */ GLvoid Demx::Entity::translate( const VEC3& vector ) { modelMatrix = glm::translate( modelMatrix, vector ); } /** * @brief Rotate the entity by an amount specified by a 3D vector * * @author Demian Floreani * * @param[in] angle The amount in degrees to rotate * @param[in] axis The axis around which to rotate * * @return None */ GLvoid Demx::Entity::rotate( GLfloat angle, const VEC3& axis ) { modelMatrix = glm::rotate( modelMatrix, angle, axis ); } /** * @brief Scale the entity by an amount specified by a 3D vector * * @author Demian Floreani * * @param[in] vector The amount to scale * * @return None */ GLvoid Demx::Entity::scale( const VEC3& vector ) { modelMatrix = glm::scale( modelMatrix, vector ); } /** * @brief Scale the entity by an amount specified by a float * * @author Demian Floreani * * @param[in] value The amount to scale * * @return None */ GLvoid Demx::Entity::scaleAll( GLfloat value ) { modelMatrix = glm::scale( modelMatrix, VEC3( value, value, value ) ); } /** * @brief Set the position of the entity in world coordinates * * @author Demian Floreani * * @param[in] pos VEC3 representing a position * * @return None */ GLvoid Demx::Entity::setPosition( const VEC3& pos ) { modelMatrix[3][0] = pos.x; modelMatrix[3][1] = pos.y; modelMatrix[3][2] = pos.z; } /** * @brief Get the position of the entity in world coordinates * * @author Demian Floreani * * @return VEC3 The position of the entity */ VEC3 Demx::Entity::getPosition() { return VEC3( modelMatrix[3][0], modelMatrix[3][1], modelMatrix[3][2] ); } /** * @brief Get the entity's current model matrix * * @author Demian Floreani * * @return MAT4 The model matrix */ MAT4 Demx::Entity::getModelMatrix() { return this->modelMatrix; } /** * @brief Get the entity's current normal matrix. This is computed as the transpose inverse of the model matrix. * * @author Demian Floreani * * @return MAT4 The normal matrix */ MAT4 Demx::Entity::getNormalMatrix() { return glm::transpose( glm::inverse( this->modelMatrix ) ); } /** * @brief Setup the entity's Axis Aligned Bounding Box * * @author Demian Floreani * * @param[in] vertices The vertices in 3D to use to setup the AABB * * @return None */ GLvoid Demx::Entity::setupAABB( const std::vector<VEC3>& vertices ) { box.setup( vertices ); } /** * @brief Setup the entity's Axis Aligned Bounding Box * * @author Demian Floreani * * @param[in] vertices The vertices in 4D to use to setup the AABB * * @return None */ GLvoid Demx::Entity::setupAABB( const std::vector<VEC4>& vertices ) { box.setup( vertices ); }
4253f56ac8b2c3c54960e915715844a52cdc931e
c91125a66de73a62994e371c5fc65c0e4890349a
/Week_14/6-5/boolean_retrieval/BoolRe.hpp
67a014bd25ec4a368a137d782c044ba93c88157e
[]
no_license
darthvade/PersonalExerciseNew
f65a4188a61ac1ce14ed79a3fcfb798e3228ee19
44b04e032afa0a66664154c8abdb9d73ee19791a
refs/heads/master
2016-08-05T03:54:56.991079
2014-12-22T14:12:39
2014-12-22T14:12:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,753
hpp
BoolRe.hpp
/* * 实现布尔检索查询(AND、OR、AND_NOT) */ #include <vector> namespace BoolRe { //AND运算 std::vector<int> Merge_And(const std::vector<int> &va, const std::vector<int> &vb) { std::vector<int> result; auto itera = va.begin(); auto iterb = vb.begin(); while(itera != va.end() && iterb != vb.end()) { if(*itera == *iterb) { result.push_back(*itera); ++itera; ++iterb; continue; } else if (*itera < *iterb) { ++itera; continue; } else { ++iterb; continue; } } return result; } //OR运算 std::vector<int> Merge_Or(const std::vector<int> &va, const std::vector<int> &vb) { std::vector<int> result; auto itera = va.begin(); auto iterb = vb.begin(); while(itera != va.end() && iterb != vb.end()) { if(*itera == *iterb) { result.push_back(*itera); ++itera; ++iterb; continue; } else if (*itera < *iterb) { result.push_back(*itera); ++itera; continue; } else { result.push_back(*iterb); ++iterb; continue; } } while(itera != va.end()) { result.push_back(*itera); ++itera; } while(iterb != vb.end()) { result.push_back(*iterb); ++iterb; } return result; } //AND_NOT运算 std::vector<int> Merge_AndNot(const std::vector<int> &va, const std::vector<int> &vb) { std::vector<int> result; auto itera = va.begin(); auto iterb = vb.begin(); while(itera != va.end() && iterb != vb.end()) { if(*itera == *iterb) { ++itera; ++iterb; continue; } else if(*itera < *iterb) { result.push_back(*itera); ++itera; continue; } else { ++iterb; continue; } } while(itera != va.end()) { result.push_back(*itera); ++itera; } return result; } }
126ffb86ef71116f114ed4b8b043bb145288b1b7
d770cb8c7ebf61c034414a16c0db69b017541dcd
/A. Colorful Stones (Simplified Edition)/main.cpp
84877ca061909e9a67a2ff6f67a6659cd4ea0d6d
[]
no_license
omarsaidkamel/Problem-Solving
f2ceca69b2b3e47dc13227670b5262a2af19bcc1
ac09c0d18f057de55a3218d33f6743bf5d33ad58
refs/heads/main
2023-06-21T18:43:06.741935
2021-07-21T09:04:02
2021-07-21T09:04:02
386,615,312
0
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
main.cpp
#include <iostream> using namespace std; string s,m;int x; int main() { cin>>s>>m; for(int i=0;i<m.size();i++) { if(s[x]==m[i]) {x++;} } cout<<x+1; return 0; }
c53f3eedbd2dcd7c0da6034fb4aa7945553f8d33
8d3753fb220a49ef19c8f4448ffdfbcd3dbdfe4f
/Andromeda/Graphics/Camera3d.cpp
cf602afb8c37f552af81d05c9e639d1a5a4e95ee
[ "MIT" ]
permissive
DrakonPL/Andromeda-Lib
b504b8016351eab20ac06d00bd8a6d1bcbbe690f
47cd3b74a736b21050222ef57c45e326304e85a6
refs/heads/master
2023-07-10T16:43:09.807545
2021-08-24T12:23:49
2021-08-24T12:23:49
164,689,145
2
1
null
null
null
null
UTF-8
C++
false
false
2,625
cpp
Camera3d.cpp
#include <Andromeda/Graphics/Camera3d.h> namespace Andromeda { namespace Graphics { Camera3d::Camera3d(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = -90.0f, float pitch = 0.0f) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(3.0f), MouseSensitivity(0.25f), Zoom(45.0f) { Position = position; WorldUp = up; Yaw = yaw; Pitch = pitch; UpdateCameraVectors(); } Camera3d::Camera3d(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(3.0f), MouseSensitivity(0.25f), Zoom(45.0f) { Position = glm::vec3(posX, posY, posZ); WorldUp = glm::vec3(upX, upY, upZ); Yaw = yaw; Pitch = pitch; UpdateCameraVectors(); } glm::mat4 Camera3d::GetViewMatrix() { return glm::lookAt(Position, Position + Front, Up); } glm::vec3 Camera3d::GetFrontVector() { return Front; } void Camera3d::ProcessKeyboard(CameraMovementEnum direction, float deltaTime) { float velocity = this->MovementSpeed * deltaTime; if (direction == FORWARD) Position += Front * velocity; if (direction == BACKWARD) Position -= Front * velocity; if (direction == LEFT) Position -= Right * velocity; if (direction == RIGHT) Position += Right * velocity; } void Camera3d::ProcessMouseMovement(float xoffset, float yoffset, bool constrainPitch = true) { xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; Yaw += xoffset; Pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Eular angles UpdateCameraVectors(); } void Camera3d::ProcessMouseScroll(float yoffset) { if (Zoom >= 1.0f && Zoom <= 45.0f) Zoom -= yoffset; if (Zoom <= 1.0f) Zoom = 1.0f; if (Zoom >= 45.0f) Zoom = 45.0f; } void Camera3d::UpdateCameraVectors() { glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); Front = glm::normalize(front); // Also re-calculate the Right and Up vector Right = glm::normalize(glm::cross(Front, WorldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up = glm::normalize(glm::cross(Right, Front)); } } }
a7a30697b36539efb539c55e583847de962c7c18
4e6d31fa86b4ac8dc95a1de8eb590aeedff46745
/Binary Trees/preorder_traversal_recursive.cpp
f6021d34d20f4e44d590d36cae862a20dfa7beba
[]
no_license
nikitagalayda/cpp-practice
a160ac9055c7a570c25081857fa775c0131211f8
b84d79b87ab9f648532a6c7cc2abeea8a4b8020e
refs/heads/master
2020-04-20T19:56:22.926809
2019-04-14T11:15:58
2019-04-14T11:15:58
169,062,747
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
preorder_traversal_recursive.cpp
/* Description: Pre-order traversal of a binary tree. Time Complexity: O(N), where N is the number of nodes in the tree, and each node of the tree is visited once. */ /* * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <vector> class Solution { private: std::vector<int> visited; public: std::vector<int> preorderTraversal(TreeNode* root) { TreeNode *curr_node = root; if(curr_node) { visited.push_back(curr_node->val); preorderTraversal(curr_node->left); preorderTraversal(curr_node->right); } return visited; } };
51a5c38a6e8c6d09cd6b38fa357dfd23a244ee62
9ce6d8295e8e5d09c14f6dc44c926137aabd9cf9
/mbed/mbed_I2C_modules communication/main.cpp
222d2b0d03b80e1fc52337e5c6d263efcbc60dd0
[]
no_license
anwar-hegazy/ARM
9be11c81e1f2c751540e4e618f39f1d867067708
c8708a92b2650ceb22a1e537ee6840509066b74e
refs/heads/master
2021-01-20T04:54:22.090740
2016-02-28T19:53:13
2016-02-28T19:53:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,710
cpp
main.cpp
#include "mbed.h" //#include <math.h> #include "DRV8830.h" // Include the MiniMoto library #include "TMP102.h" // Include Temperature Sensor library #include "PCF8574.h" // Include I/O Expander library #include "PCF8591.h" // Include 8-bit A/D Converter library (4 channel) // SDA, SCL for LPC1768 #define SDA1 p28 #define SCL1 p27 #define FAULTn 16 // fault detection Pin void changeMotorSpeed(int); int DRV8830address = 0xD0; // A1 = 1, A0 = 1 (default address setting for DRV8830 Motor Driver ) int TMP102address = 0x90; // A0 = 0 uint8_t PCF8591address = 0x92;// A2 = 0, A1 = 0, A0 = 1 //int ArduinoProMicroAddress = 0x50; int PCF8574Address = 0x70;// 0x70 is for PCF8574A and 0x40 for PCF8574 int current_speed; Serial pc(USBTX, USBRX); // tx, rx DRV8830 motor1(DRV8830address); TMP102 temperature(SDA1, SCL1, TMP102address); //A0 pin is connected to ground PCF8574 io_expander(SDA1,SCL1,PCF8574Address); I2C i2c_bus(SDA1,SCL1); // declaration for PCF8591 PCF8591 adc_dac(&i2c_bus,PCF8591address); //PCF8591_AnalogOut anaOut(&i2c_bus); PCF8591_AnalogIn anaIn(&i2c_bus,PCF8591_ADC1,PCF8591address); int main() { int expander_data; uint8_t adc_data; // store the value from selected channel of PCF8591 float current_temperature; float last_temperature; int direction = 1; int current_motor_speed_control = 0; int last_motor_speed_control = 0; current_speed = 30; io_expander.write(0xFF); wait(0.1); last_temperature = temperature.read(); while(1) { current_temperature = temperature.read(); pc.printf("Temperature: %f\n\r", current_temperature); if(current_temperature>last_temperature+0.5){ changeMotorSpeed(20); } else if(current_temperature<last_temperature-0.5){ changeMotorSpeed(-20); } last_temperature = current_temperature; wait(0.1); expander_data = io_expander.read(); pc.printf("Digital Sensor: %d\n\r", expander_data); if (expander_data > 220) { // firstly connect digital sensor or button to Pin P7 of PCF8574 pc.printf("Motor Forward\n\r"); direction = 1; } else { pc.printf("Motor Reverse\n\r"); direction = -1; } wait(0.1); adc_data = adc_dac.read(PCF8591_ADC1); // read A/D value for Channel 1 pc.printf("Distance Sensor: %d\n\r", adc_data); if(adc_data<15){ // do nothing } else if(adc_data<30){ current_speed = 63; } else if(adc_data<50){ current_speed = 35; } else if(adc_data<100){ current_speed = 20; } else if(adc_data<190){ current_speed = 10; } else{ current_speed = 63; } current_motor_speed_control = current_speed*direction; if(current_motor_speed_control!=last_motor_speed_control){ motor1.drive(current_motor_speed_control, DRV8830address); last_motor_speed_control = current_motor_speed_control; } /* pc.printf("Stop\n"); motor1.stop(DRV8830address); wait(3); pc.printf("Brake\n"); motor1.brake(DRV8830address); */ wait(1); }// while (1) }// int main() void changeMotorSpeed(int step){ if(step>0){ current_speed = current_speed + step; motor1.drive(current_speed, DRV8830address); } else if((current_speed+step)>0){ current_speed = current_speed + step; motor1.drive(current_speed, DRV8830address); } else{ current_speed = 8; } }// void changeMotorSpeed(int step)
fcee47dd842675380f8ce7cca004e60262e08c20
0ad1e75df68fb14976c79c8921249dcd6e74f967
/sadfsdfsdfsf.cpp
d9383ad29a497bc76d0557466d32e16ae817545e
[]
no_license
variablemayank/competetive-programming-codes
9010d215832f4937735d6b35b1df35df0f8a59e6
71bbc70049089fcc24444471dd4504b1d29c371f
refs/heads/master
2021-09-06T04:17:29.052221
2018-02-02T08:57:56
2018-02-02T08:57:56
119,955,414
1
1
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
sadfsdfsdfsf.cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string s; cin>>s; int flag ; if(s=="Even") flag =1; else flag =2; int n; cin>>n; int arr[17]; for(int i=1;i<=n;i++) cin>>arr[i]; if(n==1 ) { if(flag == 2) cout<<"Monk\n"; else { cout<<"Mariam\n"; } } else if(n==2) { int var =arr[1]|arr[2]; if(var%2==0 &&flag ==1) { cout<<"Monk\n"; } else if(var&1 && flag==2) { cout<<"Monk\n"; } else { cout<<"Mariam\n"; } } else if(n==3) { int var = arr[1]|arr[2]; var = var^arr[3]; if(var%2==0 &&flag ==1) { cout<<"Monk\n"; } else if(var&1 && flag==2) { cout<<"Monk\n"; } else { cout<<"Mariam\n"; } } else { bool check = false; int evencount =0; int oddcount =0; long long oxa =0; for(int i=1;i<=n;i++) { for(int a=i+1;a<=n;a++) { for(int c =a+1;c<=n;c++) { for(int d= c+1;d<=n;d++) { oxa += ((((arr[i]|arr[a])^arr[c])+arr[d])); } } } if(oxa%2==0) { if(flag ==1) { cout<<"Monk\n"; } } else if(oxa&1) { if(flag ==2) { cout<<"Monk\n"; } } else { cout<<"Mariam\n"; } } } } }
5ba16b9978f87f998a7638b96cf15765abbe8cb2
97ada4553a0e32f7920031591da9d9b2c49fec17
/BullCowGame/FBullCowGame.cpp
d49a468d6538ac1dbe29b6383ceb295b9a968b9b
[]
no_license
andreyfaraponov/BullsAndCowsGame
e83d1d6bff2543db0f854f304f1cc2048fe0a8d2
6454b615cee64591b77b109bc13d9f8b328221bc
refs/heads/master
2020-12-15T00:04:05.303905
2020-01-20T20:12:20
2020-01-20T20:12:20
234,919,893
0
0
null
null
null
null
UTF-8
C++
false
false
2,301
cpp
FBullCowGame.cpp
#include "FBullCowGame.h" #include <map> #define TMap std::map int32 FBullCowGame::GetMaxTries() const { return _maxTries; } int32 FBullCowGame::GetCurrentTry() const { return _currentTry; } int32 FBullCowGame::GetHiddenWordLength() const {return hiddenWord.length();} bool FBullCowGame::IsGameWon() const { return b_GameIsWon; } FBullCowGame::FBullCowGame() { FBullCowGame::Reset(); } FBullCowGame::~FBullCowGame() { } FBullCowGame::FBullCowGame(FBullCowGame&) { } FBullCowGame& FBullCowGame::operator=(const FBullCowGame& e) { return *(new FBullCowGame()); } void FBullCowGame::Reset() { constexpr int32 MAX_TRIES = 8; _maxTries = MAX_TRIES; _currentTry = 1; const FString HIDDEN_WORLD = "planet"; hiddenWord = HIDDEN_WORLD; b_GameIsWon = false; } EGuessStatus FBullCowGame::CheckGuessValidity(FString val1) const { if (val1.length() != FBullCowGame::GetHiddenWordLength()) { return EGuessStatus::WRONG_LENGTH; } else if (FBullCowGame::IsUppercase(val1)) { return EGuessStatus::NOT_LOWERCASE; } else if (!FBullCowGame::IsIsogram(val1)) { return EGuessStatus::NOT_ISOGRAM; } return EGuessStatus::OK; } FBullCowCount FBullCowGame::SubmitValidGuess(FString guess) { ++FBullCowGame::_currentTry; FBullCowCount bullCowCount; int32 wordLength = hiddenWord.length(); int32 guessWordLength = guess.length(); for (int32 i = 0; i < wordLength; i++) { for (int32 j = 0; j < wordLength && j < guessWordLength; j++) { if (guess[j] == hiddenWord[i]) { if (i == j) { ++bullCowCount.bulls; } else { ++bullCowCount.cows; } } } } b_GameIsWon = bullCowCount.bulls == FBullCowGame::GetHiddenWordLength(); return bullCowCount; } bool FBullCowGame::IsIsogram(FString word) const { if (word.length() <= 1) return true; TMap<char, bool> letterSeen; for (auto letter : word) { letter = tolower(letter); if (letterSeen[letter]) { return false; } else { letterSeen[letter] = true; } } return true; } bool FBullCowGame::IsUppercase(FString word) const { if (word.length() <= 1) return true; TMap<char, bool> letterSeen; for (auto letter : word) { if (isupper(letter)) { return true; } } return false; }
79d6a5b358ccbf6b162f707cd8fad7f1cbe773b0
119c1dd2b61764210064511d8ab5be252b8b7c8f
/450 DSA Questions/06 Binary Trees/3CheckForBalancedTree.cpp
35ef2e2c9551ed7914c3b518e71f84282b6b8dd1
[]
no_license
jasveen18/CP-krle-placement-lag-jayegi
2557309a9dfc4feb01dbdc867a67f1ccc4f10868
8db92e5c3a7d08edfc34d8223af6c080aa3e4721
refs/heads/main
2023-07-29T09:39:36.270193
2021-09-03T15:19:22
2021-09-03T15:19:22
430,816,168
1
1
null
2021-11-22T18:10:13
2021-11-22T18:10:13
null
UTF-8
C++
false
false
675
cpp
3CheckForBalancedTree.cpp
/****************************************** * AUTHOR : ARPIT * * NICK : arpitfalcon * * INSTITUTION : BIT MESRA * ******************************************/ // Problem Statement - Function to check whether a binary tree is balanced or not. int heightOfTree(Node* root, bool &balance) { if (root == NULL) return 0; int leftHeight = heightOfTree(root->left, balance); int rightHeight = heightOfTree(root->right, balance); balance = balance and ((abs(leftHeight - rightHeight)) <= 1); return max(leftHeight, rightHeight) + 1; } bool isBalanced(Node *root) { bool isBalance = true; heightOfTree(root, isBalance); return isBalance; }
9947a8ef432b0711567b255f5696fcef340c069d
b6d5ff41a3d642b98f4062cd5304f4ac1c646a9e
/tree.cpp
bea344dac8398c0fc0fc25b28c5571d94a438cf2
[]
no_license
tyralyn/cloaked-wookie
f7ee13d9ce8e2f1b1b1cdea20906e1b5666ace80
dd0f9a1f58fc3e1aa8869db4db5f7d01534d9940
refs/heads/master
2021-01-10T19:48:46.266335
2014-02-09T08:23:30
2014-02-09T08:23:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,754
cpp
tree.cpp
#include "tree.h" tree::tree(int n) { numEdges = n-1; edgeCount = 0; edges = new edge*[numEdges]; } tree::~tree() { for (int i = 0; i<numEdges-1; i++) delete edges[i]; } void tree::addEdge(edge* e) { edges[edgeCount]=e; e->v1->inTree = true;//!e->v1->inTree; e->v2->inTree = true;//!e->v2->inTree; edgeCount++; } void tree::printTree() { cout<<"printing tree: "<<numEdges<<endl; for (int i = 0; i<edgeCount; i++) { cout<<"[ "<<edges[i]->weight<<" : ("<<edges[i]->v1->x<<", "<<edges[i]->v1->y<<") ("<<edges[i]->v2->x<<", "<<edges[i]->v2->y<<") : "<<edges[i]->v1->inTree<<" "<<edges[i]->v2->inTree<<"] \n"; } cout<<endl; } void tree::printResults() { for (int i = 0; i<edgeCount; i++) { cout<<edges[i]->v1->vertexIndex<<" "<<edges[i]->v2->vertexIndex<<endl; } } int tree::getPartitionIndex(int leftIndex, int rightIndex) { int medianIndex = leftIndex+((int)(rightIndex-leftIndex)/2); return medianIndex; } void tree::swap(int index1, int index2) { edge* hold = edges[index1]; edges[index1]=edges[index2]; edges[index2]=hold; } int tree::partitionX(int leftIndex, int rightIndex, int pivotIndex){ double pivotValue = edges[pivotIndex]->v1->vertexIndex; //cout<<pivotValue<<endl; swap(pivotIndex, rightIndex); int swappingIndex = leftIndex; for (int i=leftIndex; i<rightIndex; i++) { if (edges[i]->v1->vertexIndex <= pivotValue) { swap(i, swappingIndex); swappingIndex++; } } swap(swappingIndex, rightIndex); return swappingIndex; } void tree::quicksortX(int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { int pivotIndex = getPartitionIndex(leftIndex, rightIndex); int newPivotIndex = partitionX(leftIndex, rightIndex, pivotIndex); quicksortX(leftIndex, newPivotIndex-1); quicksortX(newPivotIndex+1, rightIndex); } } int tree::partitionY(int leftIndex, int rightIndex, int pivotIndex){ double pivotValue = edges[pivotIndex]->v2->vertexIndex; //cout<<pivotValue<<endl; swap(pivotIndex, rightIndex); int swappingIndex = leftIndex; for (int i=leftIndex; i<rightIndex; i++) { if (edges[i]->v2->vertexIndex <= pivotValue) { swap(i, swappingIndex); swappingIndex++; } } swap(swappingIndex, rightIndex); return swappingIndex; } void tree::quicksortY(int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { int pivotIndex = getPartitionIndex(leftIndex, rightIndex); int newPivotIndex = partitionY(leftIndex, rightIndex, pivotIndex); quicksortY(leftIndex, newPivotIndex-1); quicksortY(newPivotIndex+1, rightIndex); } } void tree::sortY() { int a(0), b(0), val(0); for (int i = 0; i<edgeCount; i++) { if (edges[i]->v1->vertexIndex != val) { quicksortY(a,b); val = edges[i]->v1->vertexIndex; a = i; b=i; } else { b++; } } }
3658a422883589f32cc66a088d7c0a07d0cefecd
bdbe2f10d1148db97143d2dedefff177666d36d9
/sipXsqa/include/sqa/sqaclient.h
77d3ea16bef5b8588c78078c96b0813f1274239e
[]
no_license
sipXcom/sipxecs
8af5dabc8814d977b9608329942f68f6ea92ff8a
fa1a46c0ec298cbc198d71e18592a0f8386019d6
refs/heads/release-21.04-centos7
2023-01-28T21:07:21.293495
2021-10-14T12:54:41
2021-10-14T12:54:41
30,837,643
36
114
null
2023-01-10T10:33:38
2015-02-15T18:48:43
C++
UTF-8
C++
false
false
28,161
h
sqaclient.h
/* * Copyright (c) eZuce, Inc. All rights reserved. * Contributed to SIPfoundry under a Contributor Agreement * * This software is free software; you can redistribute it and/or modify it under * the terms of the Affero General Public License (AGPL) as published by the * Free Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. */ #ifndef SQACLIENT_H #define SQACLIENT_H #ifndef EXCLUDE_SQA_INLINES #include "sqa/StateQueueClient.h" #include <boost/lexical_cast.hpp> #endif #include <map> #include <vector> #include <string> #ifdef SWIG %module sqaclient %{ #include "sqaclient.h" %} %newobject SQAWatcher::watch(); %newobject *::get; %newobject *::mget; %newobject SQAWorker::fetchTask(); %include "std_vector.i" %include "std_string.i" %include "std_map.i" namespace std { %template(StringToStringMap) map<string, string>; } #endif #define SQA_DEFAULT_TCP_TIMEOUT 100 class SQALogger { public: SQALogger(); void initialize(const char* file, int level); std::string getHostName(); std::string getCurrentTask(); std::string getProcessName(); std::string getFilterNames(); protected: std::string hostName; std::string taskName; std::string processName; std::string filterNames; }; class SQAEvent { public: SQAEvent(); SQAEvent(const SQAEvent& data); SQAEvent(const std::string& id_, const std::string& data_); ~SQAEvent(); char* id; char* data; int data_len; int id_len; }; class SQAWatcher { public: SQAWatcher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); SQAWatcher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); ~SQAWatcher(); // // Returns the local IP address of the client // const char* getLocalAddress(); // // Returns true if the client is connected to SQA // bool isConnected(); // // Terminate the event loop // void terminate(); // // Returns the next event published by SQA. This Function // will block if there is no event in queue // SQAEvent* watch(); // // Set a value in the event queue workspace // void set(int workspace, const char* name, const char* data, int expires); // // Get a value from the event queue workspace // char* get(int workspace, const char* name); // // Set the value of a map item. If the item or map does not exist // they will be created // void mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires); // // Return a particular map element // char* mget(int workspace, const char* mapId, const char* dataId); // // Increment the value of an integer belong to a map // bool mgeti(int workspace, const char* mapId, const char* dataId, int& data); // // Get a map of string to string values stored in sqa // std::map<std::string, std::string> mgetAll(int workspace, const char* name); private: SQAWatcher(const SQAWatcher& copy); uintptr_t _connection; }; class SQAPublisher { public: SQAPublisher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); SQAPublisher( const char* applicationId, // Unique application ID that will identify this watcher to SQA int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); ~SQAPublisher(); bool isConnected(); bool publish(const char* id, const char* data, bool noresponse); bool publish(const char* id, const char* data, int len, bool noresponse); bool publishAndPersist(int workspace, const char* id, const char* data, int expires); // // Returns the local IP address of the client // const char* getLocalAddress(); // // Set a value in the event queue workspace // void set(int workspace, const char* name, const char* data, int expires); // // Get a value from the event queue workspace // char* get(int workspace, const char* name); // // Set the value of a map item. If the item or map does not exist // they will be created // void mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires); // // Return a particular map element // char* mget(int workspace, const char* mapId, const char* dataId); // // Increment the value of an integer belong to a map // bool mgeti(int workspace, const char* mapId, const char* dataId, int& data); // // Get a map of string to string values stored in sqa // std::map<std::string, std::string> mgetAll(int workspace, const char* name); private: SQAPublisher(const SQAPublisher& copy); uintptr_t _connection; }; class SQAWorker { public: SQAWorker( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); SQAWorker( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); ~SQAWorker(); // // Returns the local IP address of the client // const char* getLocalAddress(); // // Returns true if the client is connected to SQA // bool isConnected(); // // Returns the next event published by SQA. This Function // will block if there is no event in queue // SQAEvent* fetchTask(); // // Delete the task from the cache. This must be called after fetchTask() // work is done // void deleteTask(const char* id); // // Set a value in the event queue workspace // void set(int workspace, const char* name, const char* data, int expires); // // Get a value from the event queue workspace // char* get(int workspace, const char* name); // // Set the value of a map item. If the item or map does not exist // they will be created // void mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires); // // Return a particular map element // char* mget(int workspace, const char* mapId, const char* dataId); // // Increment the value of an integer belong to a map // bool mgeti(int workspace, const char* mapId, const char* dataId, int& data); // // Get a map of string to string values stored in sqa // std::map<std::string, std::string> mgetAll(int workspace, const char* name); private: SQAWorker(const SQAWorker& copy); uintptr_t _connection; }; class SQADealer { public: SQADealer( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); SQADealer( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ); ~SQADealer(); // // Returns the local IP address of the client // const char* getLocalAddress(); // // Returns true if the client is connected to SQA // bool isConnected(); // // Deal a new task // bool deal(const char* data, int expires); // // Deal and publish a task // bool dealAndPublish(const char* data, int expires); // // Set a value in the event queue workspace // void set(int workspace, const char* name, const char* data, int expires); // // Get a value from the event queue workspace // char* get(int workspace, const char* name); // // Set the value of a map item. If the item or map does not exist // they will be created // void mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires); // // Return a particular map element // char* mget(int workspace, const char* mapId, const char* dataId); // // Increment the value of an integer belong to a map // bool mgeti(int workspace, const char* mapId, const char* dataId, int& data); // // Get a map of string to string values stored in sqa // std::map<std::string, std::string> mgetAll(int workspace, const char* name); private: SQADealer(const SQADealer& copy); uintptr_t _connection; }; #ifndef EXCLUDE_SQA_INLINES // // Inline implementation of SQAEvent class // inline SQAEvent::SQAEvent() : id(0), data(0), data_len(0), id_len(0) { } inline SQAEvent::~SQAEvent() { if (NULL != id) { delete [] id; id = NULL; } if (NULL != data) { delete [] data; data = NULL; } } inline SQAEvent::SQAEvent(const SQAEvent& ev) { id_len = ev.id_len; id = new char[id_len + 1]; ::memcpy(id, ev.id, id_len); id[id_len] = '\0'; data_len = ev.data_len; data = new char[data_len + 1]; ::memcpy(data, ev.data, data_len); data[data_len] = '\0'; } inline SQAEvent::SQAEvent(const std::string& id_, const std::string& data_) { id_len = id_.size(); id = new char[id_len + 1]; std::copy(id_.begin(), id_.end(), id); id[id_len] = '\0'; data_len = data_.size(); data = new char[data_len + 1]; std::copy(data_.begin(), data_.end(), data); data[data_len] = '\0'; } // // Inline implementation for SQAWatcher class // inline SQAWatcher::SQAWatcher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "reg" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Watcher, applicationId, serviceAddress, servicePort, eventId, poolSize, readTimeout, writeTimeout)); } inline SQAWatcher::SQAWatcher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "reg" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Watcher, applicationId, eventId, poolSize, readTimeout, writeTimeout)); } inline SQAWatcher::SQAWatcher(const SQAWatcher& copy) { } inline SQAWatcher::~SQAWatcher() { delete reinterpret_cast<StateQueueClient*>(_connection); } inline const char* SQAWatcher::getLocalAddress() { return reinterpret_cast<StateQueueClient*>(_connection)->getLocalAddress().c_str(); } inline bool SQAWatcher::isConnected() { return reinterpret_cast<StateQueueClient*>(_connection)->isConnected(); } inline void SQAWatcher::terminate() { reinterpret_cast<StateQueueClient*>(_connection)->terminate(); } inline SQAEvent* SQAWatcher::watch() { std::string id; std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->watch(id, data)) return 0; SQAEvent* pEvent = new SQAEvent(id, data); return pEvent; } // // Set a value in the event queue workspace // inline void SQAWatcher::set(int workspace, const char* name, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->set(workspace, name, data, expires); } // // Get a value from the event queue workspace // inline char* SQAWatcher::get(int workspace, const char* name) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->get(workspace, name, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline void SQAWatcher::mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->mset(workspace, mapId, dataId, data, expires); } inline char* SQAWatcher::mget(int workspace, const char* mapId, const char* dataId) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mget(workspace, mapId, dataId, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline bool SQAWatcher::mgeti(int workspace, const char* mapId, const char* dataId, int& incremented) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgeti(workspace, mapId, dataId, data)) return false; try { incremented = boost::lexical_cast<int>(data); return true; } catch(...) { return false; } } inline std::map<std::string, std::string> SQAWatcher::mgetAll(int workspace, const char* name) { std::map<std::string, std::string> smap; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgetm(workspace, name, smap)); return smap; } // // Inline implmentation of the SQA Publisher class // inline SQAPublisher::SQAPublisher( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Publisher, applicationId, serviceAddress, servicePort, "publisher", poolSize, readTimeout, writeTimeout)); } inline SQAPublisher::SQAPublisher( const char* applicationId, // Unique application ID that will identify this watcher to SQA int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Publisher, applicationId, "publisher", poolSize, readTimeout, writeTimeout)); } inline SQAPublisher::SQAPublisher(const SQAPublisher& copy) { } inline SQAPublisher::~SQAPublisher() { delete reinterpret_cast<StateQueueClient*>(_connection); } inline const char* SQAPublisher::getLocalAddress() { return reinterpret_cast<StateQueueClient*>(_connection)->getLocalAddress().c_str(); } inline bool SQAPublisher::isConnected() { return reinterpret_cast<StateQueueClient*>(_connection)->isConnected(); } inline bool SQAPublisher::publish(const char* id, const char* data, bool noresponse) { return reinterpret_cast<StateQueueClient*>(_connection)->publish(id, data, noresponse); } inline bool SQAPublisher::publish(const char* id, const char* data, int len, bool noresponse) { return reinterpret_cast<StateQueueClient*>(_connection)->publish(id, data, len, noresponse); } inline bool SQAPublisher::publishAndPersist(int workspace, const char* id, const char* data, int expires) { return reinterpret_cast<StateQueueClient*>(_connection)->publishAndPersist(workspace, id, data, expires); } inline void SQAPublisher::set(int workspace, const char* name, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->set(workspace, name, data, expires); } // // Get a value from the event queue workspace // inline char* SQAPublisher::get(int workspace, const char* name) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->get(workspace, name, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline void SQAPublisher::mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->mset(workspace, mapId, dataId, data, expires); } inline char* SQAPublisher::mget(int workspace, const char* mapId, const char* dataId) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mget(workspace, mapId, dataId, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline bool SQAPublisher::mgeti(int workspace, const char* mapId, const char* dataId, int& incremented) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgeti(workspace, mapId, dataId, data)) return 0; try { incremented = boost::lexical_cast<int>(data); return true; } catch(...) { return false; } } inline std::map<std::string, std::string> SQAPublisher::mgetAll(int workspace, const char* name) { std::map<std::string, std::string> smap; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgetm(workspace, name, smap)); return smap; } // // Inline implementation for SQA Dealer class // inline SQADealer::SQADealer( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Publisher, applicationId, serviceAddress, servicePort, eventId, poolSize, readTimeout, writeTimeout)); } inline SQADealer::SQADealer( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Publisher, applicationId, eventId, poolSize, readTimeout, writeTimeout)); } inline SQADealer::SQADealer(const SQADealer& copy) { } inline SQADealer::~SQADealer() { delete reinterpret_cast<StateQueueClient*>(_connection); } inline const char* SQADealer::getLocalAddress() { return reinterpret_cast<StateQueueClient*>(_connection)->getLocalAddress().c_str(); } inline bool SQADealer::isConnected() { return reinterpret_cast<StateQueueClient*>(_connection)->isConnected(); } inline bool SQADealer::deal(const char* data, int expires) { return reinterpret_cast<StateQueueClient*>(_connection)->enqueue(data, expires); } inline bool SQADealer::dealAndPublish(const char* data, int expires) { return reinterpret_cast<StateQueueClient*>(_connection)->enqueue(data, expires, true); } inline void SQADealer::set(int workspace, const char* name, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->set(workspace, name, data, expires); } // // Get a value from the event queue workspace // inline char* SQADealer::get(int workspace, const char* name) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->get(workspace, name, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline void SQADealer::mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->mset(workspace, mapId, dataId, data, expires); } inline char* SQADealer::mget(int workspace, const char* mapId, const char* dataId) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mget(workspace, mapId, dataId, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline bool SQADealer::mgeti(int workspace, const char* mapId, const char* dataId, int& incremented) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgeti(workspace, mapId, dataId, data)) return 0; try { incremented = boost::lexical_cast<int>(data); return true; } catch(...) { return false; } } inline std::map<std::string, std::string> SQADealer::mgetAll(int workspace, const char* name) { std::map<std::string, std::string> smap; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgetm(workspace, name, smap)); return smap; } // // Inline implementation for SQAWorker class // inline SQAWorker::SQAWorker( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* serviceAddress, // The IP address of the SQA const char* servicePort, // The port where SQA is listening for connections const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Worker, applicationId, serviceAddress, servicePort, eventId, poolSize, readTimeout, writeTimeout)); } inline SQAWorker::SQAWorker( const char* applicationId, // Unique application ID that will identify this watcher to SQA const char* eventId, // Event ID of the event being watched. Example: "sqa.not" int poolSize, // Number of active connections to SQA int readTimeout, // read timeout for the control socket int writeTimeout // write timeout for the control socket ) { _connection = (uintptr_t)(new StateQueueClient( StateQueueClient::Worker, applicationId, eventId, poolSize, readTimeout, writeTimeout)); } inline SQAWorker::SQAWorker(const SQAWorker& copy) { } inline SQAWorker::~SQAWorker() { delete reinterpret_cast<StateQueueClient*>(_connection); } inline const char* SQAWorker::getLocalAddress() { return reinterpret_cast<StateQueueClient*>(_connection)->getLocalAddress().c_str(); } inline bool SQAWorker::isConnected() { return reinterpret_cast<StateQueueClient*>(_connection)->isConnected(); } inline SQAEvent* SQAWorker::fetchTask() { std::string id; std::string data; SQAEvent* pEvent = new SQAEvent(); if (!reinterpret_cast<StateQueueClient*>(_connection)->pop(id, data)) return pEvent; pEvent->id = (char*)malloc(id.size()); ::memcpy(pEvent->id, id.data(), id.size()); pEvent->data = (char*)malloc(data.size()); ::memcpy(pEvent->data, data.data(), data.size()); pEvent->data_len = data.size(); pEvent->id_len = id.size(); return pEvent; } inline void SQAWorker::deleteTask(const char* id) { reinterpret_cast<StateQueueClient*>(_connection)->erase(id); } inline void SQAWorker::set(int workspace, const char* name, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->set(workspace, name, data, expires); } // // Get a value from the event queue workspace // inline char* SQAWorker::get(int workspace, const char* name) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->get(workspace, name, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline void SQAWorker::mset(int workspace, const char* mapId, const char* dataId, const char* data, int expires) { reinterpret_cast<StateQueueClient*>(_connection)->mset(workspace, mapId, dataId, data, expires); } inline char* SQAWorker::mget(int workspace, const char* mapId, const char* dataId) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mget(workspace, mapId, dataId, data)) return 0; char* buff = (char*)malloc(data.size() + 1); ::memset(buff, 0x00, data.size() + 1); ::memcpy(buff, data.c_str(), data.size() + 1); return buff; } inline bool SQAWorker::mgeti(int workspace, const char* mapId, const char* dataId, int& incremented) { std::string data; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgeti(workspace, mapId, dataId, data)) return 0; try { incremented = boost::lexical_cast<int>(data); return true; } catch(...) { return false; } } inline std::map<std::string, std::string> SQAWorker::mgetAll(int workspace, const char* name) { std::map<std::string, std::string> smap; if (!reinterpret_cast<StateQueueClient*>(_connection)->mgetm(workspace, name, smap)); return smap; } inline SQALogger::SQALogger() { hostName = "sqa"; taskName = "sqa-task"; processName = "sqaclient"; } inline void SQALogger::initialize(const char* file, int level) { Os::Logger::instance().initialize<SQALogger>(level, file, *this); } inline std::string SQALogger::getHostName() { return hostName; } inline std::string SQALogger::getCurrentTask() { return taskName; } inline std::string SQALogger::getProcessName() { return processName; } inline std::string SQALogger::getFilterNames() { return filterNames; } #endif //EXCLUDE_SQA_INLINES #endif /* SQACLIENT_H */
57ef75a9d53e5f5a1b52e21fc9e9f6474fd2cdb8
9f48878caa37ac5f2ccf938fc476efa47c89c644
/tests/Unit/Framework/SetupLocalPythonEnvironment.cpp
33b81a002f3c85c3e280d0a71be08091ad6acb51
[ "MIT" ]
permissive
sxs-collaboration/spectre
34f7733ab4c75dbca2f432028145fed110c9ef24
96f573cf158201f712da2bfb3378edf497a35a0d
refs/heads/develop
2023-08-19T11:18:18.465609
2023-08-19T04:24:25
2023-08-19T04:24:25
87,570,510
149
190
NOASSERTION
2023-09-14T20:10:35
2017-04-07T17:28:20
C++
UTF-8
C++
false
false
3,215
cpp
SetupLocalPythonEnvironment.cpp
// Distributed under the MIT License. // See LICENSE.txt for details. #include <boost/preprocessor.hpp> #include <codecvt> // IWYU pragma: keep #include <locale> // IWYU pragma: keep #include <string> #include <vector> #ifndef PY_ARRAY_UNIQUE_SYMBOL #define PY_ARRAY_UNIQUE_SYMBOL SPECTRE_PY_API #endif #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <numpy/arrayobject.h> // IWYU pragma: keep #include "Framework/PyppFundamentals.hpp" #include "Framework/SetupLocalPythonEnvironment.hpp" #include "Informer/InfoFromBuild.hpp" #include "Utilities/ErrorHandling/FloatingPointExceptions.hpp" #include "Utilities/FileSystem.hpp" namespace pypp { SetupLocalPythonEnvironment::SetupLocalPythonEnvironment( const std::string &cur_dir_relative_to_unit_test_path) { // We have to clean up the Python environment only after all tests have // finished running, since there could be multiple tests run in a single // executable launch. This is done in TestMain(Charm).cpp. if (not initialized) { // Don't produce the __pycache__ dir (python 3.2 and newer) or the .pyc // files (python 2.7) in the tests directory to avoid cluttering the source // tree. The overhead of not having the compile files is <= 0.01s Py_DontWriteBytecodeFlag = 1; Py_Initialize(); // clang-tidy: Do not use const-cast PyObject* pyob_old_paths = PySys_GetObject(const_cast<char*>("path")); // NOLINT const auto old_paths = pypp::from_py_object<std::vector<std::string>>(pyob_old_paths); std::string new_path = unit_test_src_path() + cur_dir_relative_to_unit_test_path; if (not file_system::check_if_dir_exists(new_path)) { ERROR_NO_TRACE("Trying to add path '" << new_path << "' to the python environment during setup " "but this directory does not exist. Maybe " "you have a typo in your path?"); } // Add directory for installed packages (see CMakeLists.txt for details) new_path += ":"; new_path += PYTHON_SITELIB; for (const auto& p : old_paths) { new_path += ":"; new_path += p; } #if PY_MAJOR_VERSION == 3 PySys_SetPath(std::wstring_convert<std::codecvt_utf8<wchar_t>>() .from_bytes(new_path) .c_str()); #else // clang-tidy: Do not use const-cast PySys_SetPath(const_cast<char*>(new_path.c_str())); // NOLINT #endif // On some python versions init_numpy() can throw an FPE, this occurred at // least with python 3.6, numpy 1.14.2. ScopedFpeState disable_fpes(false); init_numpy(); disable_fpes.restore_exceptions(); } initialized = true; } #if PY_MAJOR_VERSION == 3 std::nullptr_t SetupLocalPythonEnvironment::init_numpy() { import_array(); return nullptr; } #else void SetupLocalPythonEnvironment::init_numpy() { import_array(); } #endif void SetupLocalPythonEnvironment::finalize_env() { if (not finalized and initialized) { Py_Finalize(); } finalized = true; } bool SetupLocalPythonEnvironment::initialized = false; bool SetupLocalPythonEnvironment::finalized = false; } // namespace pypp
6e249c63532cd21644f747d5cf896e50d293342f
88ee3a44b4977d67dfb0699471bfbcf8c1213356
/tp2/src/backend-multi/RWLock.cpp
522958295a5331204d0e2825409d6e8db98f0424
[]
no_license
fbeuter/os
12918856c3d1e94a4fcb9c898bc3e43d6ffd0744
4b75a80949a103bd8c9ebee1108da43abfc5c23c
refs/heads/master
2021-05-31T09:31:08.728417
2015-11-05T23:52:47
2015-11-05T23:52:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,878
cpp
RWLock.cpp
#include "RWLock.h" /* IMPORTANTE: Se brinda una implementación básica del Read-Write Locks que hace uso de la implementación provista por pthreads. Está dada para que puedan utilizarla durante la adaptación del backend de mono a multi jugador de modo de poder concentrarse en la resolución de un problema a la vez. Una vez que su adaptación esté andando DEBEN hacer su propia implementación de Read-Write Locks utilizando únicamente Variables de Condición. */ RWLock :: RWLock() { pthread_mutex_init(&(this->lock_mutex), NULL); pthread_mutex_init(&(this->lock_writer), NULL); pthread_mutex_init(&(this->lock_reader), NULL); pthread_cond_init (&(this->condition), NULL); writer = false; readers = 0; } void RWLock :: rlock() { pthread_mutex_lock(&(this->lock_mutex)); while (writer) pthread_cond_wait(&(this->condition), &(this->lock_mutex)); pthread_mutex_lock(&(this->lock_reader)); readers++; pthread_mutex_unlock(&(this->lock_reader)); pthread_mutex_unlock(&(this->lock_mutex)); } void RWLock :: wlock() { pthread_mutex_lock(&(this->lock_mutex)); while (writer) pthread_cond_wait(&(this->condition), &(this->lock_mutex)); pthread_mutex_lock(&(this->lock_writer)); writer = true; pthread_mutex_unlock(&(this->lock_writer)); while (readers > 0) pthread_cond_wait(&(this->condition), &(this->lock_mutex)); pthread_mutex_unlock(&(this->lock_mutex)); } void RWLock :: runlock() { pthread_mutex_lock(&(this->lock_mutex)); pthread_mutex_lock(&(this->lock_reader)); readers--; pthread_mutex_unlock(&(this->lock_reader)); if (readers == 0) pthread_cond_broadcast(&(this->condition)); pthread_mutex_unlock(&(this->lock_mutex)); } void RWLock :: wunlock() { pthread_mutex_lock(&(this->lock_writer)); writer = false; pthread_mutex_unlock(&(this->lock_writer)); pthread_cond_broadcast(&(this->condition)); }
4c3e7fba6beea2788d15b02859c2f4c47c8521de
6ff16eb5530dfbf1828fa5905c448d913336d895
/CIS17AFinal/CSC17A_Final/final1/main.cpp
db84b84f15ab99a8257caa75b2e3bc16cae2275a
[]
no_license
dharo/HaroDavid_CSC17A_48130
067b08a4560fd808967fec8667a2a27d57bd642e
dbd8beb1e8f5f26a80b36ded26570f64c6336364
refs/heads/master
2016-09-10T17:58:42.957506
2014-12-13T01:00:24
2014-12-13T01:00:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
main.cpp
/* main.cpp Author: davidharo Final_Prob1 */ //Libraries #include <iostream> #include "Prob1Random.h" using namespace std; //Function Prototypes //execute main int main () { unsigned char n=5; unsigned char rndseq[]={16,34,57,79,144}; Prob1Random a(n,rndseq); int ntimes=100000; srand(time(0)); for(int i=1;i<=ntimes;i++){ a.randFromSet(); } int *x=a.getFreq(); unsigned char *y=a.getSet(); for(int i=0;i<n;i++){ cout<<int(y[i])<<" occurred "<<x[i]<<" times"<<endl; } cout<<"The total number of random numbers is "<<a.getNumRand()<<endl; return 0; }//exit
cd3897d362dbb89919db416bf1e9728e82c59ef0
872770c5323aa17120f2f708a1f0be09e663c9a8
/Elastos/Framework/Droid/eco/inc/core/appwidget/CAppWidgetManager.h
be790c63f360b10345a48ab2ddf127be8b91fea0
[]
no_license
xianjimli/Elastos
76a12b58db23dbf32ecbcefdaf6179510362dd21
f9f019d266a7e685544596b365cfbc05bda9cb70
refs/heads/master
2021-01-11T08:26:17.180908
2013-08-21T02:31:17
2013-08-21T02:31:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,592
h
CAppWidgetManager.h
#ifndef __CAPPWIDGETMANAGER_H__ #define __CAPPWIDGETMANAGER_H__ #include "_CAppWidgetManager.h" #include "ext/frameworkdef.h" #include <elastos/AutoPtr.h> #include <elastos/Mutex.h> #include <elastos/HashMap.h> _ELASTOS_NAMESPACE_BEGIN template<> struct Hash<AutoPtr<IContext> > { size_t operator()(AutoPtr<IContext> s) const { assert(s != NULL); return (size_t)s.Get(); } }; _ELASTOS_NAMESPACE_END using namespace Elastos::Core::Threading; CarClass(CAppWidgetManager) { public: /** * Get the AppWidgetManager instance to use for the supplied {@link android.content.Context * Context} object. */ static CARAPI GetInstance( /* [in] */ IContext* context, /* [out] */ IAppWidgetManager** appWidgetManager); /** * Set the RemoteViews to use for the specified appWidgetIds. * * <p> * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, * and outside of the handler. * This method will only work when called from the uid that owns the AppWidget provider. * * @param appWidgetIds The AppWidget instances for which to set the RemoteViews. * @param views The RemoteViews object to show. */ CARAPI UpdateAppWidget( /* [in] */ const ArrayOf<Int32>& appWidgetIds, /* [in] */ IRemoteViews* views); /** * Set the RemoteViews to use for the specified appWidgetId. * * <p> * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, * and outside of the handler. * This method will only work when called from the uid that owns the AppWidget provider. * * @param appWidgetId The AppWidget instance for which to set the RemoteViews. * @param views The RemoteViews object to show. */ CARAPI UpdateAppWidgetEx( /* [in] */ Int32 appWidgetId, /* [in] */ IRemoteViews* views); /** * Set the RemoteViews to use for all AppWidget instances for the supplied AppWidget provider. * * <p> * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, * and outside of the handler. * This method will only work when called from the uid that owns the AppWidget provider. * * @param provider The {@link ComponentName} for the {@link * android.content.BroadcastReceiver BroadcastReceiver} provider * for your AppWidget. * @param views The RemoteViews object to show. */ CARAPI UpdateAppWidgetEx2( /* [in] */ IComponentName* provider, /* [in] */ IRemoteViews* views); /** * Return a list of the AppWidget providers that are currently installed. */ CARAPI GetInstalledProviders( /* [out] */ IObjectContainer** providerInfos); /** * Get the available info about the AppWidget. * * @return A appWidgetId. If the appWidgetId has not been bound to a provider yet, or * you don't have access to that appWidgetId, null is returned. */ CARAPI GetAppWidgetInfo( /* [in] */ Int32 appWidgetId, /* [out] */ IAppWidgetProviderInfo** info); /** * Set the component for a given appWidgetId. * * <p class="note">You need the APPWIDGET_LIST permission. This method is to be used by the * AppWidget picker. * * @param appWidgetId The AppWidget instance for which to set the RemoteViews. * @param provider The {@link android.content.BroadcastReceiver} that will be the AppWidget * provider for this AppWidget. */ CARAPI BindAppWidgetId( /* [in] */ Int32 appWidgetId, /* [in] */ IComponentName* provider); /** * Get the list of appWidgetIds that have been bound to the given AppWidget * provider. * * @param provider The {@link android.content.BroadcastReceiver} that is the * AppWidget provider to find appWidgetIds for. */ CARAPI GetAppWidgetIds( /* [in] */ IComponentName* provider, /* [out, callee] */ ArrayOf<Int32>** appWidgetIds); CARAPI constructor( /* [in] */ IContext* context); public: static const CString TAG; static HashMap<AutoPtr<IContext>, AutoPtr<IAppWidgetManager> > sManagerCache; static Mutex sManagerCacheLock; static AutoPtr<IAppWidgetService> sService; AutoPtr<IContext> mContext; private: AutoPtr<IDisplayMetrics> mDisplayMetrics; }; #endif //__CAPPWIDGETMANAGER_H__
18dbfd6a068b1b599172862fcef8d5bab159c49f
9df24e9110f06ea1004588c87a908c68497b22c0
/vijos/P1142.cpp
cdae7c8deff1811fc042ea9df04a270b42921d28
[]
no_license
zhangz5434/code
b98f9df50f9ec687342737a4a2eaa9ef5bbf5579
def5fdcdc19c01f34ab08c5f27fe9d1b7253ba4f
refs/heads/master
2020-07-02T17:24:14.355545
2019-03-13T12:39:45
2019-03-13T12:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,568
cpp
P1142.cpp
/* 两种做法 Orz反正我不会 第一 建棵树直接模拟即可,每次找花费最小的位置插入,结果是正确的 第二 动态规划 f[i][j]表示i个物品,使用j个指针的最小费用 f[i][j]=min{f[j-1]+g[t][j]} g[i][j]表示当前指针为j,使用了i个物品 g[i][j]=min{f[i][l]+p[j]*i*i) 初值f[1][1],g[1][x] 做到i时给f[1]赋值 于是复杂度就是O(n^2*k) */ #include <iostream> #include <cstdio> #include <cstdlib> #include <memory.h> #include <algorithm> using namespace std; int n,k,p[200],f[2000][200]; void init() { memset(f,0,sizeof(f)); memset(p,0,sizeof(p)); scanf("%d%d",&n,&k); for (int i = 1; i <= k; ++ i) scanf("%d",&p[i]); sort(p+1,p+1+k); } int mmin(int a,int b) { if (a == 0) return b; else return min(a,b); } int dp(int x,int y,int l) { if (x == 1) { f[x][y] = p[y]; return f[x][y]; } if (y == k) { f[x][y] = p[y] * x * x + dp(x,1,x-1); return f[x][y]; } int temp; temp = k - y + 1; if (temp * l < x) return 0xFFFFFFF; if (f[x][y] != 0) return f[x][y]; temp = (x-1) / (temp) + 1; for (int i = temp; i <= l; ++ i) { if (i == 1) f[x][y] = dp(x-1,y+1,x-2) + p[y]; else f[x][y] = mmin( f[x][y] , dp(x-i,y+1,x-i-1) + dp(i,1,i-1) + i * i * p[y] ); } return f[x][y]; } int main() { init(); printf("%d",dp(n,1,n-1)); return 0; }
8ea2b517aa518d24983813000560688648277e93
a3ae44249dc9ac07d03ac1d546024cef920507c3
/SDK/IViewRender.h
7500cac318ac6f17e3718d48f616a010b779a762
[]
no_license
zanzo420/spaghettos.cc
81005fb5ad21faf7345b406bacebf4cddd654df1
9dc8fc1cb6a13e6e3abe443b8f14dc840c748934
refs/heads/master
2021-09-02T08:16:10.866015
2017-12-31T21:16:18
2017-12-31T21:16:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
36
h
IViewRender.h
#pragma once class IViewRender { };
4d905b2dd4a5617c4f18bea6c820c02442c915f8
e8c6fb88dd50c93171f3eca1f37cc438fd2af575
/source/dialog.cpp
2ba882faf7bfcea56d24c5b04c4e6a3af2781376
[]
no_license
QianG0104/Chinese_Chess_Player
3c8340006007b76b57c5d9fc50c82792cceeb100
fade6e8248ebba9c8b0f3de996eb1261cb3893af
refs/heads/master
2022-07-08T16:49:43.247263
2020-05-20T05:34:57
2020-05-20T05:34:57
265,457,847
3
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
dialog.cpp
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::on_buttonBox_accepted() { in[0]=ui->lineEdit_4->text(); in[1]=ui->lineEdit_5->text(); out[0]=ui->lineEdit->text(); out[1]=ui->lineEdit_2->text(); out[2]=ui->lineEdit_3->text(); dialog0.exec(); }
760dd9cc45d19cf3728954797a67042abc0307d3
984d5ce2898360bff1a1c805f026a3de68f9ea7b
/07. Functions/04. function_template.cpp
7b1530b3613b3cfc3db96f1736d4b32fb295793a
[ "MIT" ]
permissive
AnmolTomer/cpp_deep_dive
f7e57a0fe28c6e13d0bf44c0f087baa70052c6d5
8b534ce48cf80e5012caec76bef6ad210ac4594f
refs/heads/master
2021-12-09T16:04:52.933459
2021-10-31T22:54:12
2021-10-31T22:54:12
193,171,362
139
69
MIT
2021-10-31T22:54:13
2019-06-21T23:40:31
C++
UTF-8
C++
false
false
2,293
cpp
04. function_template.cpp
/* author : Anmol Tomer email : anmol3540@gmail.com */ #include <iostream> using namespace std; /* // Doing things overloaded way. int max(int x, int y) { return x > y ? x : y; // If x > y ? return x : else return y } float max(float x, float y) { return x > y ? x : y; } */ // ----------------------------------------------------------------------------------------------- // Function template way of doing things. template <class T> // T Max(T x, T y) T max(T x, T y) { return x > y ? x : y; } int main() { // cout << max<float>(12.6, 56.5) << endl; / /This would give you error. // Check answer by Francois Andrieux on this link to use :: // cout << Max<float>(12.6, 56.5) << endl;// This works too to have capital function name with namespace std. cout << "Output for float gives us : " << ::max(12.6, 56.5) << endl; cout << "Output for int gives us : " << ::max(112, 93) << endl; return 0; } /* FUNCTION TEMPLATE : The functions which are generic are function templates. Generalised in terms of data type. Above we see 2 examples to understand generic functions. 2 functions are just overloaded with different data type that's all. Number of parameters are same as well but datatype of parameters are different. From main if we call int c as above first function is called and float b calls the second function. If we notice the body of the function i.e. code/logic written is exactly same only datatype is different. So question arises... Why to write same function twice when there is only a difference in data type ? Or go into the hassle of function overloading ? Can't we just write a single function combining these 2 functions for any data type ? Yes we can. We do T for template in the above . We define template <class T> Which is a definition of T defined as class of type template. T is a template class and function is template function. Now when in the main function when via int c we call the function max then automatically T will be replaced by int and when we call via float b then T becomes float. Same function can be used with multiple data types as if it is a single function with difference of data types. Function template will not only work just for datatypes but also for objects of your classes. */
e6b53fc800ad18109b8f87edec335bd89957502f
d8b1d2e70c0deacf6029b181891aa329abe78f1e
/Prob 2 &4/bankAccountImp.cpp
a1647bb6c221a07ee8f38ed149c9cee33b28672f
[]
no_license
Mistah-Skipp/Prog-2
954c340f7218325462ca55ce4613a8c49502ad43
668c0379bfb4e4ca9162f371c0663afd1c92f2c3
refs/heads/master
2022-07-30T16:35:05.258342
2020-05-08T20:59:44
2020-05-08T20:59:44
262,416,516
0
0
null
2020-05-08T20:14:41
2020-05-08T19:57:26
C++
UTF-8
C++
false
false
1,401
cpp
bankAccountImp.cpp
//bankAccountImp.cpp #include <string> #include <iostream> #include <iomanip> #include "bankAccount.h" using namespace std; //Name void bankAccount::setActName(std::string firstName, std::string lastName) { actFName = firstName; actLName = lastName; actName = firstName + " " + lastName; } std::string bankAccount::getActName() const { return actName; } //Number void bankAccount::setActNum(int num) { actNum = num; } double bankAccount::getActNum() const { return actNum; } //Balance void bankAccount::setBalance(double bal) { balance = bal; } double bankAccount::getBalance() const { return balance; } //Account Type void bankAccount::setActType(std::string type) { actType = type; } std::string bankAccount::getActType() const { return actType; } //interest rate double bankAccount::getIntRate() const{ return intRate; } void bankAccount::setIntRate(double iRate) { intRate = iRate; } //Print void bankAccount::actPrint() { cout << "Account Name: "<< getActName() << endl <<"Account Type: "<< getActType() << endl <<"Account Number: "<< getActNum() << endl <<"Interest Rate: "<< setprecision(3) << getIntRate(); } //Constructor bankAccount::bankAccount(std::string firstName,std::string lastName, std::string type, double num, double bal, double iRate) { actFName = firstName; actLName = lastName; actType = type; actNum = num; balance = bal; intRate = iRate; }
2b9a553191c16d13c727c5f4800fd62b6ef38811
6997ee24091019043fb4cc54b1b2f7119a40d426
/src/include/xmppclient.h
c63c35c0151764122115778e498fa318703b5093
[ "MIT" ]
permissive
WST/mawar
eff4311bd25232b07f4611b3094b3d13746e558c
8a603f31869d8b31f60b782e5aa0342082874f9e
refs/heads/master
2020-05-17T03:32:53.740927
2013-09-03T22:38:36
2013-09-03T22:38:36
12,523,582
1
0
null
null
null
null
UTF-8
C++
false
false
6,528
h
xmppclient.h
#ifndef MAWAR_XMPPCLIENT_H #define MAWAR_XMPPCLIENT_H #include <xmppstream.h> #include <nanosoft/gsaslserver.h> #include <xml-types.h> #include <stanza.h> #include <presence.h> /** * Класс XMPP-поток (c2s) */ class XMPPClient: public XMPPStream { protected: /** * Виртуальный хост */ class VirtualHost *vhost; /** * Сеанс авторизации SASL */ GSASLSession *sasl; /** * ID пользователя */ int user_id; ClientPresence client_presence; /** * Событие: начало потока */ virtual void onStartStream(const std::string &name, const attributes_t &attributes); /** * Событие: конец потока */ virtual void onEndStream(); /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ virtual void onPeerDown(); /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ virtual void onTerminate(); public: /** * Признак использования ростера * TRUE - пользователь запросил ростер * FALSE - пользователь не запрашивал ростер и хочет с ним работать */ bool use_roster; /** * Флаг компрессии * XEP-0138: Stream Compression * * TRUE - компрессия включена * FALSE - компрессия отключена */ bool compression; /** * Клиент авторизовался * * TRUE - клиент авторизовался * FALSE - клиент не авторизовался */ bool authorized; /** * "connected resource" * * TRUE - client has bound a resource to the stream * FALSE - client hasn't bound a resource to the stream */ bool connected; /** * Маркер online/offline * * TRUE - Initial presense уже отправлен * FLASE - Initial presense ещё не отправлен */ bool available; /** * JID клиента */ JID client_jid; /** * Конструктор потока */ XMPPClient(XMPPServer *srv, int sock); /** * Деструктор потока */ ~XMPPClient(); /** * JID потока */ JID jid() const; /** * Показывает, что клиент уже авторизовался */ bool isAuthorized(); /** * Показывает, что клиент начал сессию и onOnline() уже было вызвано */ bool isActive(); /** * ID пользователя */ int userId() const { return user_id; } /** * Приоритет ресурса */ ClientPresence presence(); /** * Обработчик станзы */ virtual void onStanza(Stanza stanza); /** * Обработчик авторизации */ virtual void onAuthStanza(Stanza stanza); /** * Обработка этапа авторизации SASL */ virtual void onSASLStep(const std::string &input); /** * Обработчик авторизации: ответ клиента */ virtual void onResponseStanza(Stanza stanza); /** * Обработчик запроса компрессии */ void handleCompress(Stanza stanza); /** * Обработчик запроса TLS */ void handleStartTLS(Stanza stanza); /** * Устаревший обработчик iq roster * * TODO необходима ревизия, скорее всего надо перенести в VirtualHost * или в отдельный модуль */ void handleIQRoster(Stanza stanza); /** * Обработчик iq-станзы */ void onIqStanza(Stanza stanza); /** * RFC 3921 (5.1.1) Initial Presence */ void handleInitialPresence(Stanza stanza); /** * RFC 3921 (5.1.2) Presence Broadcast */ void handlePresenceBroadcast(Stanza stanza); /** * RFC 3921 (5.1.3) Presence Probes */ void handlePresenceProbes(); /** * RFC 3921 (5.1.4) Directed Presence */ void handleDirectedPresence(Stanza stanza); /** * RFC 3921 (5.1.5) Unavailable Presence */ void handleUnavailablePresence(Stanza stanza); /** * RFC 3921 (8.2) Presence Subscribe */ void handlePresenceSubscribe(Stanza stanza); /** * RFC 3921 (8.2) Presence Subscribed */ void handlePresenceSubscribed(Stanza stanza); /** * RFC 3921 (8.4) Presence Unsubscribe */ void handlePresenceUnsubscribe(Stanza stanza); /** * RFC 3921 (8.2.1) Presence Unsubscribed */ void handlePresenceUnsubscribed(Stanza stanza); /** * RFC 3921 (5.1.6) Presence Subscriptions */ void handlePresenceSubscriptions(Stanza stanza); /** * Обработчик presence-станзы */ void onPresenceStanza(Stanza stanza); /** * Обработчик message-станзы */ void onMessageStanza(Stanza stanza); /** * Чтение ростера клиентом * * RFC 3921 (7.3) Retrieving One's Roster on Login */ void handleRosterGet(Stanza stanza); /** * Добавить/обновить контакт в ростере * * RFC 3921 (7.4) Adding a Roster Item * RFC 3921 (7.5) Updating a Roster Item */ void handleRosterItemSet(TagHelper item); /** * Удалить контакт из ростера * * RFC 3921 (7.6) Deleting a Roster Item * RFC 3921 (8.6) Removing a Roster Item and Canceling All Subscriptions */ void handleRosterItemRemove(TagHelper item); /** * Проверить корректность запроса RosterSet */ bool checkRosterSet(Stanza stanza); /** * Обновить ростер */ void handleRosterSet(Stanza stanza); /** * Обработка станз jabber:iq:roster * * RFC 3921 (7.) Roster Managment */ void handleRosterIq(Stanza stanza); /** * XEP-0077: In-Band Registration * * c2s-версия: регистрация происходит как правило до полноценной * авторизации клиента, соответственно vhost не может адресовать * такого клиента, поэтому приходиться сделать две отдельные * версии регистрации: одну для c2s, другую для s2s */ void handleIQRegister(Stanza stanza); }; #endif // MAWAR_XMPPCLIENT_H
deef0733a6bee505f2ef79b6373de519010e50f5
4f4c2cd4e711f2197e03c99f0a0d16f28c69a9da
/Classes/GameConfig.cpp
02acc7b2fb653a6ad933223ba3df94bda4ff57b1
[]
no_license
Anti-Magic/EvolandPocket
9e8d26c3ef76b3ee7281f481312f6692f69cc719
045385a0d69a1c062dc26aa39a1a870508240794
refs/heads/master
2021-01-19T00:24:28.228379
2015-03-15T05:03:16
2015-03-15T05:03:16
31,943,418
6
1
null
null
null
null
UTF-8
C++
false
false
1,114
cpp
GameConfig.cpp
#include "GameConfig.h" using std::string; GameConfig GameConfig::_instance; GameConfig::GameConfig() { timePerMove = 0.3f; timePerAttack = 0.3f; _playerMoveName2 = "playerMove"; _playerFacetoName2 = "playerFaceto"; _playerAttackName2 = "playerAttack"; _enemyMoveName2 = "enemyMove"; GID_Box_Open = 318; GID_Box_Close = 317; GID_SaveArea = 73; } GameConfig* GameConfig::getInstance() { return &_instance; } const string& GameConfig::getPlayerMoveName(Tools::Direction dir) { _playerMoveName = Tools::dirToString(dir) + _playerMoveName2; return _playerMoveName; } const string& GameConfig::getPlayerFacetoName(Tools::Direction dir) { _playerFacetoName = Tools::dirToString(dir) + _playerFacetoName2; return _playerFacetoName; } const string& GameConfig::getPlayerAttackName(Tools::Direction dir) { _playerAttackName = Tools::dirToString(dir) + _playerAttackName2; return _playerAttackName; } const string& GameConfig::getEnemyMoveName(Tools::Direction dir) { _enemyMoveName = Tools::dirToString(dir) + _enemyMoveName2; return _enemyMoveName; }
69ae9eeabd70eb1bdd8197b4c4f5d3279b126b44
0509e367ee369133f0c57f2cbd6cb6fd959da1d5
/chapter14/rei14.5_1.cpp
b8eaced1bc73d96dbb945a1fd3afbc9069192555
[]
no_license
Hiroaki-K4/cpp_learn
5a1e6916d504027c18c64a16c353ee72429ed383
69d38f317f9c144b4e092361936d61b62d3bed3b
refs/heads/main
2023-02-25T12:40:56.497944
2021-01-30T13:27:00
2021-01-30T13:27:00
317,693,373
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
rei14.5_1.cpp
#include <iostream> #include <fstream> #include <iomanip> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <strstream> #include <vector> #include <list> #include <map> using namespace std; int main() { map<char, int> m; int i; for (i = 0; i < 10; i++) { m.insert(pair<char, int>('A' + i, i)); } char ch; cout << "キーを入力: "; cin >> ch; map<char, int>::iterator p; p = m.find(ch); if (p != m.end()) cout << p->second << endl; else cout << "キーはマップにない" << endl; return 0; }
10d23f3ac1638f3a51fb249aa3075f314ab013c7
8f37e02e657ea05ed050c26ba7ca7158b1b8f501
/src/Field.cpp
d1a5150f83e25bf05a31099489559813b8c523a1
[]
no_license
Asmageddon/r1
8178a49fd4626c11ed1c694b5a26a98a0e199372
9d0b2b5b3b9dc505e44b82312e3fe93d12fb0a1d
refs/heads/master
2020-05-14T22:48:43.463521
2013-01-21T19:28:37
2013-01-21T19:28:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,384
cpp
Field.cpp
#include "Field.hpp" #include "Level.hpp" #include <SFML/Graphics.hpp> #define _USE_MATH_DEFINES #include <cmath> Field::Field() { radius = 1; width = 3; intensity = new float[3*3]; center = sf::Vector2i(1,1); current_level = NULL; } void Field::SetRadius(const short& radius) { this->radius = radius; this->width = 1 + radius * 2; this->center = sf::Vector2i(radius, radius); delete[] intensity; intensity = new float[width * width]; } const short& Field::GetRadius() const { return this->radius; } void Field::SetFalloff(const FALLOFF& falloff) { this->falloff = falloff; if (current_level != NULL) Recalculate(); } const FALLOFF& Field::GetFalloff() const { return this->falloff; } void Field::Calculate(Level* level, const sf::Vector2i& caster_pos) { /* * Simple raycasting */ current_level = level; origin = caster_pos; for(int x = 0; x < width; x++) for(int y = 0; y < width; y++) { intensity[x + width * y] = 0.0f; } intensity[center.x + width * center.y] = 1.0f; int rays = M_PI * 2 * radius * 1.6; for(int a = 0; a < rays; a++) { //TODO: Precalculate these values for various ray counts and/or angles float ax = sin(a * M_PI * 2 / rays); float ay = cos(a * M_PI * 2 / rays); float x = center.x; float y = center.y; for(int z = 0; z < this->radius; z++) { x += ax; y += ay; sf::Vector2i pos = sf::Vector2i( (int)round(x), (int)round(y) ); if (z == radius - 1) { if (sqrt((pos.x - center.x) * (pos.x - center.x) + (pos.y - center.y) * (pos.y - center.y)) > radius) { break; } } switch(this->falloff) { float dist; case FALLOFF_LINEAR_ROUGH: intensity[pos.x + width * pos.y] = 1.0f - (z * 1.0f / this->radius); break; case FALLOFF_LINEAR_SMOOTH: dist = sqrt((pos.x - center.x) * (pos.x - center.x) + (pos.y - center.y) * (pos.y - center.y)); if (dist > radius) dist = radius; intensity[pos.x + width * pos.y] = 1.0f - (dist / this->radius); break; case FALLOFF_FLAT: intensity[pos.x + width * pos.y] = 1.0f; break; } sf::Vector2i map_pos = pos + caster_pos - center; if (level->BlocksSight(map_pos)) break; } } } void Field::Recalculate() { Calculate(current_level, origin); } float Field::GetIntensityAt(const sf::Vector2i& pos) const { sf::Vector2i _pos = pos - origin + center; if (_pos.x < 0) return 0.0f; if (_pos.x >= width) return 0.0f; if (_pos.y < 0) return 0.0f; if (_pos.y >= width) return 0.0f; const float& i = intensity[_pos.x + width * _pos.y]; return i; } bool Field::InBounds(const sf::Vector2i& pos) const { sf::Vector2i _pos = pos - origin + center; if (_pos.x < 0) return false; if (_pos.x >= width) return false; if (_pos.y < 0) return false; if (_pos.y >= width) return false; return true; } const sf::Vector2i& Field::GetPosition() const { return origin; }
96ab73c42110657363a76b495fd75f20da413e7b
a9921bd48da8870a589fe8f0e2a1a023991b6c12
/makingchange.cpp
5979ab702bbe66a5cef147072e8d609c954924f8
[]
no_license
atyamsriharsha/My-Uva-solutions-
36b89d88c2c62db8431918b5cbcb1819a9b0052c
e36942e48203594ec895502ff2affe9d7d3620e2
refs/heads/master
2021-01-15T16:17:31.091882
2015-07-22T21:05:57
2015-07-22T21:05:57
38,688,856
1
0
null
null
null
null
UTF-8
C++
false
false
1,301
cpp
makingchange.cpp
/************************************************************ Author : atyam ************************************************************/ #include <bits/stdc++.h> using namespace std ; typedef long long ll ; typedef pair<int,int> pii ; typedef vector<pii> vii ; #define inf 100000 int change[]={5,10,20,50,100,200} ; int result[1000]={10000} ; int av[6] ; result[0] = 0 ; void minimumchange(int n,int first) { if(n<-500||n>500) return inf; if(n<=0&&first<0) return result[-n]; else if(first<0) return inf; else if(!av[first]) return minimumChange(n,first-1); else { av[first]--; int a = minimumChange(n-change[first],first); av[first]++; int b = minimumChange(n,first-1); return min(1+a,b); } } int main() { int a,b,c,d,e,f,r,q ; for (int i = 0; i < 6; ++i) { for (int j = change[i]; j < 1000; ++j) { result[j] = min(result[j],1+result[j-change[i]]) ; } } while(1) { cin >> av[0] >> av[1] >> av[2] >> av[3] >> av[4] >> av[5] ; if(av[0]==0 && av[2]==0 && av[3]==0 && av[4] ==0 && av[5] ==0 && av[6] ==0) { break ; } scanf("%d.%d",&r,&q) ; r = r*100 + q ; minimumchange(r,5) ; } return 0 ; }
33a67865ffc10be843f809a5db2ea7f94eeff693
3a1c247285021d7dfb62e650382186bfcd22b0a8
/src/base/timer.hpp
40a02b9bea003ad26e7fba72efb3f55ec6fd483a
[]
no_license
wytjws/iqt
156f87b94417d030751107685375ed4b8a6e409a
fc74992c046dd8d4d126298a936286543fd189b4
refs/heads/master
2022-10-30T04:43:31.394573
2020-06-15T06:05:36
2020-06-15T06:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,210
hpp
timer.hpp
#ifndef _BASE_TIMER_HPP_ #define _BASE_TIMER_HPP_ #include <functional> #include <thread> #include <mutex> #include <atomic> #include <condition_variable> #include <vector> #include <queue> #include <chrono> #include <cassert> #include <iostream> #include "base/macro.hpp" namespace base { class Timer { public: typedef std::function<void(void *)> TimerTask; private: class TimerTaskWrapper { public: TimerTaskWrapper(long delay, long period, TimerTask task, void *param = nullptr, std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now()) : delay(delay), period(period), task(task), param(param), start_time(std::move(start_time)) {} virtual ~TimerTaskWrapper() {} void run() { task(param); } long delay; long period; TimerTask task; void *param; std::chrono::system_clock::time_point start_time; }; class TimerTaskWrapperCompare { public: bool operator()(const TimerTaskWrapper &lhs, const TimerTaskWrapper &rhs) const { return lhs.start_time + std::chrono::milliseconds(lhs.delay) > rhs.start_time + std::chrono::milliseconds(rhs.delay); } }; public: static Timer *default_timer(); Timer() : _stop_flag(false), _looper(std::thread(std::bind(&Timer::run, this))) {} virtual ~Timer() { // join(); } void schedule(long delay, TimerTask task, void *param = nullptr) { assert(delay >= 0); std::unique_lock<std::mutex> lock(_queue_mutex); _queue.emplace(delay, 0, std::move(task), param); if (1 == _queue.size()) { lock.unlock(); _queue_cv.notify_all(); } } void schedule(const std::chrono::system_clock::time_point &start_time, TimerTask task, void *param = nullptr) { auto now = std::chrono::system_clock::now(); long delay = std::chrono::duration_cast<std::chrono::milliseconds>( start_time - now).count(); delay = delay < 0 ? 0 : delay; std::unique_lock<std::mutex> lock(_queue_mutex); _queue.emplace(delay, 0, task, param, now); if (1 == _queue.size()) { lock.unlock(); _queue_cv.notify_all(); } } void schedule(long delay, long period, TimerTask task, void *param = nullptr) { assert(delay >= 0 && period > 0); std::unique_lock<std::mutex> lock(_queue_mutex); _queue.emplace(delay, period, std::move(task), param); if (1 == _queue.size()) { lock.unlock(); _queue_cv.notify_all(); } } void schedule(const std::chrono::system_clock::time_point &start_time, long period, TimerTask task, void *param = nullptr) { auto now = std::chrono::system_clock::now(); long delay = std::chrono::duration_cast<std::chrono::milliseconds>( start_time - now).count(); delay = delay < 0 ? 0 : delay; std::unique_lock<std::mutex> lock(_queue_mutex); _queue.emplace(delay, period, std::move(task), param, now); if (1 == _queue.size()) { lock.unlock(); _queue_cv.notify_all(); } } void stop() { _stop_flag = true; } void join() { if (_looper.joinable()) _looper.join(); } void detach() { _looper.detach(); } DISALLOW_COPY_AND_ASSIGN(Timer); private: void run() { while (!_stop_flag) { std::unique_lock<std::mutex> lock(_queue_mutex); while (_queue.empty()) _queue_cv.wait(lock); auto task = _queue.top(); _queue.pop(); lock.unlock(); std::unique_lock<std::mutex> lock2(_timeout_mutex); auto now = std::chrono::system_clock::now(); task.delay -= std::chrono::duration_cast<std::chrono::milliseconds>( now - task.start_time).count(); task.start_time = now; auto status = _timeout_cv.wait_for(lock2, std::chrono::milliseconds(task.delay)); if (status == std::cv_status::no_timeout) { now = std::chrono::system_clock::now(); task.delay -= std::chrono::duration_cast<std::chrono::milliseconds>( now - task.start_time).count(); task.start_time = now; std::unique_lock<std::mutex> lock(_queue_mutex); _queue.push(std::move(task)); continue; } task.run(); if (task.period > 0) { /* now = std::chrono::system_clock::now(); task.delay = task.period - std::chrono::duration_cast<std::chrono::milliseconds>( now - task.start_time).count(); task.start_time = now;*/ now = std::chrono::system_clock::now(); task.delay = task.delay + task.period - std::chrono::duration_cast<std::chrono::milliseconds>( now - task.start_time).count(); task.start_time = now; std::unique_lock<std::mutex> lock(_queue_mutex); _queue.push(std::move(task)); } } } private: std::atomic_bool _stop_flag; std::thread _looper; std::mutex _queue_mutex; std::mutex _timeout_mutex; std::condition_variable _queue_cv; std::condition_variable _timeout_cv; std::priority_queue<TimerTaskWrapper, std::vector<TimerTaskWrapper>, TimerTaskWrapperCompare> _queue; }; } /* base */ #endif /* end of include guard: _BASE_TIMER1_HPP_ */
6a3a9843befbe575776e9d02d2ece2601903467f
bcb1b8453096699f944e8e3a0dc5b36178d385a3
/include/html/ul.hpp
bbb6efc7a0b2d98dd4e24db2671ab470f03ee8b5
[ "MIT" ]
permissive
nathanmullenax83/rhizome
0d490bafc40251ccf014b47aeb7e21fdb25fec36
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
refs/heads/master
2020-12-15T01:21:24.799354
2020-07-11T14:46:08
2020-07-11T14:46:08
234,942,360
1
0
MIT
2020-07-05T00:46:50
2020-01-19T18:04:15
C++
UTF-8
C++
false
false
1,110
hpp
ul.hpp
#ifndef RHIZOME_HTML_UL #define RHIZOME_HTML_UL #include <vector> #include <iostream> #include "pattern.hpp" #include "element.hpp" #include "li.hpp" using std::ostream; using std::vector; using rhizome::pattern::Pattern; namespace rhizome { namespace html { /// Represents an unordered list. class UL: public Element { private: vector<LI> items; public: UL(); ~UL(); virtual void write_to( ostream &out, size_t indent ) const; virtual void serialize_to( size_t level, ostream &out ) const override; // virtual void deserialize_from( istream &in, IParser *parser ) override; LI & li( string const &contents ); // virtual Pattern * make_pattern() const override; // virtual Pattern * make_concise_pattern() const override; virtual Thing * clone() const override; virtual string rhizome_type() const override; virtual Thing * invoke(Thing *context, string const &method, Thing * arg ) override; }; } } #endif
f5d491ccd7df9d1633177e573d05c6329fbcc214
cd39fc7e02cddb2900959b263e98e6b6618a1f7c
/PokerOdds.cpp
35fb022d39d4fcb9098a3dc016d3e4ead84818d0
[]
no_license
SilkExpress/PokerFun
f32ced82f529114b502e4c9f99722b1f86c61d98
8a811c92ecc6043f789474feb798db287fbf58d5
refs/heads/master
2021-01-10T15:39:42.524565
2020-04-24T01:45:48
2020-04-24T01:45:48
55,113,268
0
0
null
2020-04-24T01:45:50
2016-03-31T02:20:18
C++
UTF-8
C++
false
false
9,575
cpp
PokerOdds.cpp
// PokerOdds.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Deck.h" #include "Hand.h" #include "Odds.h" #include "HandType.h" using std::cout; using std::endl; using std::cin; using std::getline; using std::string; int main() { Deck deck; Hand hand; Card burn; int rank; string suit; int numPlayers; int input; char inChar; cout << "Please entering the number of players: " << endl; cin >> inChar; numPlayers = inChar - '0'; cout << "Number of starting players: " << numPlayers << endl; while (true) { cout << "Please choose from the following options: " << endl; cout << "1. Enter hole cards." << endl << "2. Randomise hole cards." << endl << "3. Print decklist." << endl << "4. Print deck." << endl; cin >> inChar; input = inChar - '0'; switch (input) { case 1: for (int i = 0; i != 2; ++i) { cout << "Enter hole card " << i + 1 << ": "; cin >> rank >> suit; //fix scenario where rank rank suit burn.rank = rank; burn.suit = suit; //cout << "Card " << i << " is: " << rank << " " << suit << endl; bool cardSet = hand.setCard(deck, burn); if (cardSet) continue; else //try again i--; } break; case 2: for (int i = 0; i != 2; ++i) { cout << "Randomizing hole card " << i + 1 << ": "; //randomize function burn.rank = rank; burn.suit = suit; cout << "Card " << i << " is: " << rank << " " << suit << endl; bool cardSet = hand.setCard(deck, burn); if (cardSet) continue; else //try again i--; } break; case 3: deck.printDecklist(); cout << "Decklist contains: " << deck.sizeDecklist() << " cards" << endl; continue; case 4: deck.printDeck(); cout << "Deck contains: " << deck.sizeDeck() << " cards" << endl; continue; default: cout << "Invalid input. Please enter a number representing one of the following options:" << endl; continue; } break; } while (true) { cout << "Please choose from the following options: " << endl; cout << "1. Enter flop cards." << endl << "2. Randomise flop cards." << endl << "3. Print decklist." << endl << "4. Print deck." << endl << "5. Display hole cards. " << endl; cout << "6. Display community cards." << endl << "7. Display all known cards." << endl << "8. Display all available hand options." << endl << "9. Display the best available hand." << endl; cout << "10. Find odds of hand winning now. " << endl << "11. Find odds of hand winning on flop." << endl; cin >> inChar; input = inChar - '0'; switch (input) { case 1: for (int i = 0; i != 3; ++i) { cout << "Enter flop card " << i + 1 << ": "; cin >> rank >> suit; burn.rank = rank; burn.suit = suit; //cout << "Card " << i + 2 << " is: " << rank << " " << suit << endl; bool cardSet = hand.setCard(deck, burn); if (cardSet) continue; else //try again i--; } break; case 2: break; case 3: deck.printDecklist(); cout << "Decklist contains: " << deck.sizeDecklist() << " cards" << endl; continue; case 4: deck.printDeck(); cout << "Deck contains: " << deck.sizeDeck() << " cards" << endl; continue; case 5: cout << "Hole cards: " << endl; hand.printHole(); continue; case 6: cout << "Community cards: " << endl; hand.printCommunity(); continue; case 7: cout << "Available cards: " << endl; hand.printAvailable(); continue; case 8: cout << "Hands available: " << endl; hand.printHands(); continue; case 9: findBestHand(hand); cout << "Best hand: " << endl; hand.printBest(); continue; case 10: //odds now break; case 11: //odds after flop break; default: cout << "Invalid input. Please enter a number representing one of the following options:" << endl; continue; } break; } while (true) { cout << "Please choose from the following options: " << endl; cout << "1. Enter turn card." << endl << "2. Randomise turn card." << endl << "3. Print decklist." << endl << "4. Print deck." << endl << "5. Display hole cards. " << endl; cout << "6. Display community cards." << endl << "7. Display all known cards." << endl << "8. Display all available hand options." << endl << "9. Display the best available hand." << endl; cout << "10. Find odds of hand winning now. " << endl << "11. Find odds of hand winning on flop." << endl; cin >> inChar; input = inChar - '0'; switch (input) { case 1: for (int i = 0; i != 1; ++i) { cout << "Enter turn card 1: "; cin >> rank >> suit; burn.rank = rank; burn.suit = suit; //cout << "Card " << i + 5 << " is: " << rank << " " << suit << endl; bool cardSet = hand.setCard(deck, burn); if (cardSet) continue; else //try again i--; } break; case 2: break; case 3: deck.printDecklist(); cout << "Decklist contains: " << deck.sizeDecklist() << " cards" << endl; continue; case 4: deck.printDeck(); cout << "Deck contains: " << deck.sizeDeck() << " cards" << endl; continue; case 5: cout << "Hole cards: " << endl; hand.printHole(); continue; case 6: cout << "Community cards: " << endl; hand.printCommunity(); continue; case 7: cout << "Available cards: " << endl; hand.printAvailable(); continue; case 8: cout << "Hands available: " << endl; hand.printHands(); continue; case 9: findBestHand(hand); cout << "Best hand: " << endl; hand.printBest(); continue; case 10: //odds now break; case 11: //odds after flop break; default: cout << "Invalid input. Please enter either a number representing one of the following options:" << endl; continue; } break; } while (true) { cout << "Please choose from the following options: " << endl; cout << "1. Enter river card." << endl << "2. Randomise river card." << endl << "3. Print decklist." << endl << "4. Print deck." << endl << "5. Display hole cards. " << endl; cout << "6. Display community cards." << endl << "7. Display all known cards." << endl << "8. Display all available hand options." << endl << "9. Display the best available hand." << endl; cout << "10. Find odds of hand winning now. " << endl << "11. Find odds of hand winning on flop." << endl; cin >> inChar; input = inChar - '0'; switch (input) { case 1: for (int i = 0; i != 1; ++i) { cout << "Enter river card 1: "; cin >> rank >> suit; burn.rank = rank; burn.suit = suit; //cout << "Card " << i + 5 << " is: " << rank << " " << suit << endl; bool cardSet = hand.setCard(deck, burn); if (cardSet) continue; else //try again i--; } break; case 2: break; case 3: deck.printDecklist(); cout << "Decklist contains: " << deck.sizeDecklist() << " cards" << endl; continue; case 4: deck.printDeck(); cout << "Deck contains: " << deck.sizeDeck() << " cards" << endl; continue; case 5: cout << "Hole cards: " << endl; hand.printHole(); continue; case 6: cout << "Community cards: " << endl; hand.printCommunity(); continue; case 7: cout << "Available cards: " << endl; hand.printAvailable(); continue; case 8: cout << "Hands available: " << endl; hand.printHands(); continue; case 9: findBestHand(hand); cout << "Best hand: " << endl; hand.printBest(); continue; case 10: //odds now break; case 11: //odds after flop break; default: cout << "Invalid input. Please enter either '1', '2', '3' or '4'" << endl; continue; } break; } while (true) { cout << "Please choose from the following options: " << endl; cout << "1. Print decklist." << endl << "2. Print deck." << endl << "3. Display hole cards. " << endl; cout << "4. Display community cards." << endl << "5. Display all known cards." << endl << "6. Display all available hand options." << endl << "7. Display the best available hand." << endl; cout << "8. Find odds of hand winning now. " << endl << "9. Find odds of hand winning on flop." << endl << "10. Exit." << endl; cin >> inChar; input = inChar - '0'; switch (input) { case 1: deck.printDecklist(); cout << "Decklist contains: " << deck.sizeDecklist() << " cards" << endl; continue; case 2: deck.printDeck(); cout << "Deck contains: " << deck.sizeDeck() << " cards" << endl; continue; case 3: cout << "Hole cards: " << endl; hand.printHole(); continue; case 4: cout << "Community cards: " << endl; hand.printCommunity(); continue; case 5: cout << "Available cards: " << endl; hand.printAvailable(); continue; case 6: cout << "Hands available: " << endl; hand.printHands(); continue; case 7: findBestHand(hand); cout << "Best hand: " << endl; hand.printBest(); continue; case 8: //odds now break; case 9: //odds after flop break; case 10: break; default: cout << "Invalid input. Please enter either '1', '2', '3' or '4'" << endl; continue; } break; } findBestHand(hand); cout << "Best hand: " << endl; hand.printBest(); findOdds(deck, hand); return 0; }
69222114cf67977795bf3d0bbedd4c8ed67cd08f
eaebaf1f70e29201fcceb9d37ab758abad09e18f
/src/mainWindow.cpp
6bf58f24164c3236d34b300d3d4b15a8b7b03155
[ "MIT" ]
permissive
zloop1982/TizFbExample
fd86f7c80b8e9086fa78f823217cf9617002bfde
a346f2a68fdd2418292fee7a285b71be1f42c6ac
refs/heads/master
2021-01-14T11:11:34.649794
2014-09-02T15:53:17
2014-09-02T15:53:17
33,650,489
0
1
null
2015-04-09T05:37:11
2015-04-09T05:37:11
null
UTF-8
C++
false
false
2,698
cpp
mainWindow.cpp
/* * Copyright (c) 2014 Christian Schabesberger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mainWindow.hpp" #include "ui_mainWindow.h" #include "tizFacebook/tizFacebook.hpp" #include <QStringList> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), tizFacebook(new TizFacebook(this)) { ui->setupUi(this); connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(onLoginButton())); connect(tizFacebook, SIGNAL(loginChanged(bool,bool)), this, SLOT(onLoginStateChanged(bool, bool))); tizFacebook->setFacebookDir(QString("facebook")); tizFacebook->setClientToken("<client-token here>"); // optional for login on pc //tizFacebook->setClientId("<app_id here>"); QStringList readPermissions("public_profile"); QStringList publishPermisssions("publish_actions"); tizFacebook->setReadPermissions(readPermissions); //tizFacebook->setPublishPermissions(publishPermisssions); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onLoginButton() { if(!tizFacebook->isLoggedIn()) tizFacebook->login(); else tizFacebook->logout(); } void MainWindow::onLoginStateChanged(bool logedIn, bool online) { if(logedIn) { ui->loginButton->setText("logout"); //this line adds ofline access to user data tizFacebook->requestMe(false, true); ui->usrImgLbl->setPixmap(tizFacebook->getPicture()); ui->usrTextLbl->setText(tizFacebook->getName()); } else { ui->loginButton->setText("login"); ui->usrImgLbl->setPixmap(QPixmap()); ui->usrTextLbl->setText(""); } }
e0fbb70374a94c2bf7321e979f084f6a5384e53d
6e2f8b62a9977ae6c51c6bcbe41daccc92a87677
/ParabellumEngine/ParabellumEngine/DirectionalLight.h
5e751c5bdd9e35395c32d533a83a34703c986bab
[ "MIT" ]
permissive
Qazwar/ParabellumFramework
8a455ea5e1ac0dab9c466604d2f443317e2a57bd
7b55003bb04e696a68f436b9ec98a05e026526fd
refs/heads/master
2022-01-26T06:28:53.040419
2019-06-29T11:05:34
2019-06-29T11:05:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,731
h
DirectionalLight.h
#ifndef _DIRECTIONALLIGHT_H_ #define _DIRECTIONALLIGHT_H_ #include <string> #include <memory> #include "../ParabellumFramework/GraphicsDevice.h" #include "../ParabellumFramework/ResourceManager.h" #include "../ParabellumFramework/BoundingVolumes.h" #include "../ParabellumFramework/BoundingFrustum.h" #include "../ParabellumFramework/IntersectCodes.h" #include "../ParabellumFramework/MathHelper.h" #include "../ParabellumFramework/Model.h" #include "Component3D.h" #include "BaseLight.h" #include "Camera.h" #include "TerrainVertexFormat.h" namespace ParabellumEngine { namespace Components { using namespace ParabellumFramework; using namespace ParabellumFramework::Resources; using namespace ParabellumFramework::Graphics; // // Directinal Light // class XYZ_API DirectionalLight : public BaseLight { public: DirectionalLight(); ~DirectionalLight(); private: DirectionalLight(const DirectionalLight&) = delete; // // Methods // public: void Initialize(_IN_ Vector3D& lightDirection, _IN_ Vector3D& lightColor, EFLOAT32 lightIntensity); void Update(); void CalculateLight3DData(_IN_ Camera* pCamera); void CreateLightViewProjectionMatrix(_IN_ EUINT32 no); // // Members // public: Vector3D m_lightDirection; Vector3D m_lightColor; EFLOAT32 m_intensity; // // data used in CSM // Vector3D m_position; Vector3D m_target; Vector3D m_up; Vector3D m_positions[9]; Vector3D m_targets[9]; Vector3D m_ups[9]; Matrix4x4 m_view[9]; Matrix4x4 m_viewTemp[9]; Matrix4x4 m_projection[9]; Matrix4x4 m_viewProjection[9]; EFLOAT32 m_zNear[9]; EFLOAT32 m_zFar[9]; EFLOAT32 m_projectionsSizes[9]; // sizes of part of bounding frustum // for example if m_siceSize[0] is 0.1 then the Top Left corner of // the first part is 10% of full frustum corner far from the camera EFLOAT32 m_sliceSize[9]; // AABB array obeys an area of all parts of 'sliced;' camera frustum // used do determine which depth map should be sampled BoundingBox m_CSMBoxes[9]; // bounding frustums for light cameras BoundingFrustum m_frustums[9]; // how many CMS layers are displayed EUINT32 m_CSMCount; // // Gets and Sets // public: Vector3D* GetDirection(); Vector3D* GetColor(); EFLOAT32 GetIntensity(); void SetDirection(Vector3D& val); void SetColor(Vector3D& val); void SetIntensity(EFLOAT32 val); BoundingBox* GetCSMBox(int no) { return &m_CSMBoxes[no]; } BoundingFrustum* GetFrustum(int no) { return &m_frustums[no]; } BoundingFrustum* GetFrustums() { return m_frustums; } }; } } #endif
d82900de81a2873d3a3a87b07c084763e220f259
055844a18dbd26dbea054a003ab12e254c78b891
/aleph/generate_df_tree.H
2e54fa08bbedaf9e388a3306621e39afc3703a7a
[ "BSD-2-Clause" ]
permissive
AlbertDenn/Aleph-AutoInstall
daa045de598b51d6e2b890c1a448344799ac4ae9
011848abd960d0528daaedefba3cfb85e62589df
refs/heads/master
2021-01-13T00:46:32.935788
2015-12-09T20:40:29
2015-12-09T20:40:29
46,997,943
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,071
h
generate_df_tree.H
/* This file is part of Aleph-w system Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Leandro Rabindranath León All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: Copyright (c) 2002-2014 Leandro Rabindranath León. See details of licence. This product includes software developed by the Hewlett-Packard Company, Free Software Foundation and Silicon Graphics Computer Systems, Inc. 4. Neither the name of the ULA 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 Leandro Rabindranath León ''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 <COPYRIGHT HOLDER> 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. Aleph-w is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. I request users of this software to return to Leandro Rabindranath Leon CEMISID Ed La Hechicera 3er piso, ala sur Facultad de Ingenieria Universidad de Los Andes Merida - REPÚBLICA BOLIVARIANA DE VENEZUELA or leandro.r.leon@gmail.com any improvements or extensions that they make and grant me the rights to redistribute these changes. */ # include <tpl_graph_utils.H> # include <tpl_tree_node.H> # include <generate_tree.H> static long global_counter = 0; struct Clave { int key; long count; long low; }; struct Clave_Igual { const bool operator () (const Clave & c1, const Clave & c2) const { return c1.key == c2.key; } }; struct Convertir { void operator () (Grafo::Node * tnode, Tree_Node<Clave> * t) { Grafo::Node * gnode = static_cast<Grafo::Node *>(NODE_COOKIE(tnode)); Clave & clave = t->get_key(); clave.key = tnode->get_info().clave; clave.count = gnode->get_info().df; clave.low = gnode->get_info().low; } }; struct Write_Node { static const size_t Buf_Size = 512; const string operator () (Tree_Node<Clave> * p) { char str[2]; str[0] = p->get_key().key; str[1] = '\0'; return string(str); } }; struct Write_Df { static const size_t Buf_Size = 512; const string operator () (Tree_Node<Clave> * p) { char buf[Buf_Size]; snprintf(buf, Buf_Size, "(%c,%ld)", p->get_key().key, p->get_key().count); return string(buf); } }; struct Write_Low { static const size_t Buf_Size = 512; const string operator () (Tree_Node<Clave> * p) { char buf[Buf_Size]; if (p->get_key().low >= 0) snprintf(buf, Buf_Size, "%d,%ld,%ld", p->get_key().key, p->get_key().count, p->get_key().low); else snprintf(buf, Buf_Size, "%d,%ld,-", p->get_key().key, p->get_key().count); return string(buf); } }; void visitar_df(Grafo &, Grafo::Node * nodo, Grafo::Arc *) { nodo->get_info().df = global_counter++; } void visitar_low(Grafo &, Grafo::Node * nodo, Grafo::Arc *) { nodo->get_info().low = (long) (nodo->cookie); } template <class GT, class Key> void write_df_low_tree(GT & g, typename GT::Node * src, ofstream & f) { // calcular puntos de corte DynDlist<typename GT::Node*> node_list = compute_cut_nodes(g); depth_first_traversal(g, src, &visitar_df); // copiar df depth_first_traversal(g, src, &visitar_low); // copiar low Grafo tree = find_depth_first_spanning_tree(g, src); // calcular arcos no abarcadores DynDlist<No_Tree_Arc> arc_list; generate_non_tree_arcs(g, arc_list); typename GT::Node * td = static_cast<typename GT::Node *>(NODE_COOKIE(src)); Tree_Node<Key> * rd = Graph_To_Tree_Node () <Grafo, Key, Convertir>(tree, td); generate_tree <Tree_Node<Key>, Write_Low> (rd, f); write_non_tree_arcs(arc_list, rd, f); }
9655173dabeaf3ffc3c714842ae2241cc60ddfbb
690c977dd2a8fe222789bc6cdc87b7f87a0ad0ea
/CodeShala/Trees/Assignment questions/LCA BST.cpp
b956e99f50c3f1073bf16f1f211c24fbf11df3cf
[]
no_license
mohityadav7/CP-Code
54bd29ff5f62c868a9c4b50a86f509c9e665d5ef
86fbb4d18600b269a351cc9943a7c8c47c9ea907
refs/heads/master
2021-03-27T19:39:52.692005
2018-11-15T16:33:14
2018-11-15T16:33:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
cpp
LCA BST.cpp
#include <iostream> #include <algorithm> using namespace std; struct node { int data; struct node * left; struct node * right; } * root = NULL; struct node * insertNode(struct node * tNode, int value) { if(tNode == NULL) { struct node * newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = value; newNode->left = NULL; newNode->right = NULL; return newNode; } if(tNode->data > value) tNode->left = insertNode(tNode->left, value); else tNode->right = insertNode(tNode->right, value); return tNode; } void buildTree(int a[], int N) { for(int i = 0; i < N; i++) { if(i) { insertNode(root, a[i]); } else { root = insertNode(NULL, a[i]); } } } struct node * bstLCA(struct node * root, int a, int b) { struct node *ans=root; if(a>b){ int temp=b; b=a; a=temp; } while(true){ if(a > (ans->data) && b >(ans->data)) ans=ans->right; else if(a<(ans->data) && b<(ans->data)) ans=ans->left; else return ans; } } int main() { int N; cin >> N; int arr[N]; for(int i = 0; i < N; i++) { cin >> arr[i]; } int A, B; cin >> A >> B; buildTree(arr, N); struct node * lca = bstLCA(root, A, B); cout << lca->data << endl; }
bbf06db391371207e9483e237ef2a421f4b9491d
495e7343fd2a82c4fc78a9f26ccbc7fb75ebe992
/test/testcommon/TestFilesystem.cpp
1870cf59148f3ef6ea439e6c09f1c9b7646d210f
[]
no_license
matthewcpp/recondite
fd12bd36f25113cad485aea3baf4cd5b60eae49d
2a10964dd6c6f9ae8bc61b90df459bbcd2d4f740
refs/heads/master
2021-04-12T04:29:47.611629
2017-03-07T14:15:11
2017-03-07T14:15:11
5,922,213
2
1
null
null
null
null
UTF-8
C++
false
false
1,519
cpp
TestFilesystem.cpp
#include "TestFilesystem.hpp" rIStream* TestFilesystem::OpenReadFileRef(const rString& path) { rIStringStream* stream = nullptr; if (savedData.count(path)) { stream = new rIStringStream(savedData[path]); } else { stream = new rIStringStream(); } return stream; } void TestFilesystem::CloseReadFileRef(rIStream* stream) { delete stream; } rOStream* TestFilesystem::OpenWriteFileRef(const rString& path) { rOStringStream* stream = new rOStringStream(); openWriteableFiles[stream] = path; return stream; } void TestFilesystem::CloseWriteFileRef(rOStream* stream) { rOStringStream* stringstream = (rOStringStream*)stream; rString str = stringstream->Str(); rString path = openWriteableFiles[stringstream]; savedData[path] = str; openWriteableFiles.erase(stringstream); delete stream; } void TestFilesystem::SetSavedSata(const rString& path, const rString& data) { savedData[path] = data; } void TestFilesystem::Clear() { for (auto& item : openReadableFiles) delete item; for (auto& item : openWriteableFiles) delete item.first; savedData.clear(); } TestFilesystem::~TestFilesystem() { Clear(); } bool TestFilesystem::FileSize(const rString& path, size_t& size) const { auto result = savedData.find(path); if (result == savedData.end()) { return false; } else { size = result->second.size(); return true; } } bool TestFilesystem::Exists(const rString& path) { return savedData.count(path) > 0; }
0a71d576558f20eb0297984e03a94037561b773a
6a59a44410937dd10619c2ac016a3302670b7353
/tusa9/chatserver/user_profile.h
9f0bac58ebdc1cfa9ca5d3eb974e6d923ed4ea70
[ "MIT" ]
permissive
akakist/tusa-chat
0dbf26674eb94deec56021085a9a7bcdb0239d5a
1dfedb4a15ad86727a0133f06b87a567114afe0d
refs/heads/master
2021-07-10T00:37:29.415885
2021-03-30T07:19:47
2021-03-30T07:19:47
235,997,118
0
0
null
null
null
null
UTF-8
C++
false
false
1,329
h
user_profile.h
#ifndef USER_PROFILE___H #define USER_PROFILE___H #include <string> #include <map> using namespace std; class user_profile: public db_row { public: unsigned int id; const char* getclassname()const { return "user_profile"; } int load_from_db(const string & table_name) ; user_profile(); ~user_profile(); string login; int bought_invisibility; unsigned int level; set<string> __privileges; int setting_neye; unsigned int setting_n_color_pack; unsigned int last_nick_id; string last_nick; CH_id last_channel; unsigned int last_status_id; unsigned int contact_options; bool ul_mode_contacts_only; bool ul_mode_hide_male; bool ul_mode_hide_female; unsigned int notes_msg_per_page; bool notes_save_copy; unsigned char notes_sort; bool notes_sort_desc; bool setting_show_eye; bool unreged; time_t birth_date; enum { CONTACT_ADD_IN_PRIV=0x01, CONTACT_ADD_OUT_PRIV=0x02 }; map<unsigned int,user_status> status; private: int gender; public: void set_gender(unsigned char g); unsigned char get_gender() const; void on_id_not_exists(const string &tbname, unsigned int _id); }; extern db_map<unsigned int,user_profile>user$profiles; #define __UP__ user$profiles #endif
97dfbda9b8abfdadc1d65a958a3f86ff8cd92029
7dd516a2d6f29f3b0eefd8a638155d8010cc1dc2
/image.h
254570a964da9a22c7e8d18f9820f910d560086e
[]
no_license
rshest/algomap
8e826a5f46b57d673f1565ab98ee4a3a19716343
7d1660000eff4a8f36162de4a4ed2c2b8d90a3ec
refs/heads/master
2021-05-26T14:29:04.238281
2012-11-12T10:19:03
2012-11-12T10:19:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
image.h
#ifndef __IMAGE_H__ #define __IMAGE_H__ #include <vector> struct Image { std::vector<unsigned int> rgba; // rgba pixel array int width; int height; }; // Loads image from TGA file bool LoadTGA(const char* fileName, Image& image); #endif // __IMAGE_H__
53f367d515496353260ed9f4a989ecd0cf12dc1c
76b40fb08675511e17131664033b3a42451b83c1
/Temp/StagingArea/il2cppOutput/AssemblyU2DCSharp_nn_hid_ControllerSupportArg1887899189.h
fc06a12d309cc366c970af3a9feb1da548bea660
[]
no_license
Jim3878/SwitchTool
7b460214c9b31169a50090dc65cc62f035a59dae
ef2d9f389aeb4e8dc0960a455729d41cd8fa3047
refs/heads/master
2021-09-08T17:49:46.788937
2018-03-11T14:22:01
2018-03-11T14:22:01
109,232,011
0
0
null
null
null
null
UTF-8
C++
false
false
7,234
h
AssemblyU2DCSharp_nn_hid_ControllerSupportArg1887899189.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3507792607.h" #include "AssemblyU2DCSharp_nn_util_Color4u81633930318.h" #include "mscorlib_System_Byte3683104436.h" // nn.util.Color4u8[] struct Color4u8U5BU5D_t2211783355; // System.Byte[] struct ByteU5BU5D_t3397334013; struct Color4u8_t1633930318 ; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // nn.hid.ControllerSupportArg struct ControllerSupportArg_t1887899189 { public: // System.Byte nn.hid.ControllerSupportArg::playerCountMin uint8_t ___playerCountMin_1; // System.Byte nn.hid.ControllerSupportArg::playerCountMax uint8_t ___playerCountMax_2; // System.Boolean nn.hid.ControllerSupportArg::enableTakeOverConnection bool ___enableTakeOverConnection_3; // System.Boolean nn.hid.ControllerSupportArg::enableLeftJustify bool ___enableLeftJustify_4; // System.Boolean nn.hid.ControllerSupportArg::enablePermitJoyDual bool ___enablePermitJoyDual_5; // System.Boolean nn.hid.ControllerSupportArg::enableSingleMode bool ___enableSingleMode_6; // System.Boolean nn.hid.ControllerSupportArg::enableIdentificationColor bool ___enableIdentificationColor_7; // nn.util.Color4u8[] nn.hid.ControllerSupportArg::identificationColor Color4u8U5BU5D_t2211783355* ___identificationColor_8; // System.Boolean nn.hid.ControllerSupportArg::enableExplainText bool ___enableExplainText_9; // System.Byte[] nn.hid.ControllerSupportArg::explainText ByteU5BU5D_t3397334013* ___explainText_10; public: inline static int32_t get_offset_of_playerCountMin_1() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___playerCountMin_1)); } inline uint8_t get_playerCountMin_1() const { return ___playerCountMin_1; } inline uint8_t* get_address_of_playerCountMin_1() { return &___playerCountMin_1; } inline void set_playerCountMin_1(uint8_t value) { ___playerCountMin_1 = value; } inline static int32_t get_offset_of_playerCountMax_2() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___playerCountMax_2)); } inline uint8_t get_playerCountMax_2() const { return ___playerCountMax_2; } inline uint8_t* get_address_of_playerCountMax_2() { return &___playerCountMax_2; } inline void set_playerCountMax_2(uint8_t value) { ___playerCountMax_2 = value; } inline static int32_t get_offset_of_enableTakeOverConnection_3() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enableTakeOverConnection_3)); } inline bool get_enableTakeOverConnection_3() const { return ___enableTakeOverConnection_3; } inline bool* get_address_of_enableTakeOverConnection_3() { return &___enableTakeOverConnection_3; } inline void set_enableTakeOverConnection_3(bool value) { ___enableTakeOverConnection_3 = value; } inline static int32_t get_offset_of_enableLeftJustify_4() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enableLeftJustify_4)); } inline bool get_enableLeftJustify_4() const { return ___enableLeftJustify_4; } inline bool* get_address_of_enableLeftJustify_4() { return &___enableLeftJustify_4; } inline void set_enableLeftJustify_4(bool value) { ___enableLeftJustify_4 = value; } inline static int32_t get_offset_of_enablePermitJoyDual_5() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enablePermitJoyDual_5)); } inline bool get_enablePermitJoyDual_5() const { return ___enablePermitJoyDual_5; } inline bool* get_address_of_enablePermitJoyDual_5() { return &___enablePermitJoyDual_5; } inline void set_enablePermitJoyDual_5(bool value) { ___enablePermitJoyDual_5 = value; } inline static int32_t get_offset_of_enableSingleMode_6() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enableSingleMode_6)); } inline bool get_enableSingleMode_6() const { return ___enableSingleMode_6; } inline bool* get_address_of_enableSingleMode_6() { return &___enableSingleMode_6; } inline void set_enableSingleMode_6(bool value) { ___enableSingleMode_6 = value; } inline static int32_t get_offset_of_enableIdentificationColor_7() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enableIdentificationColor_7)); } inline bool get_enableIdentificationColor_7() const { return ___enableIdentificationColor_7; } inline bool* get_address_of_enableIdentificationColor_7() { return &___enableIdentificationColor_7; } inline void set_enableIdentificationColor_7(bool value) { ___enableIdentificationColor_7 = value; } inline static int32_t get_offset_of_identificationColor_8() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___identificationColor_8)); } inline Color4u8U5BU5D_t2211783355* get_identificationColor_8() const { return ___identificationColor_8; } inline Color4u8U5BU5D_t2211783355** get_address_of_identificationColor_8() { return &___identificationColor_8; } inline void set_identificationColor_8(Color4u8U5BU5D_t2211783355* value) { ___identificationColor_8 = value; Il2CppCodeGenWriteBarrier(&___identificationColor_8, value); } inline static int32_t get_offset_of_enableExplainText_9() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___enableExplainText_9)); } inline bool get_enableExplainText_9() const { return ___enableExplainText_9; } inline bool* get_address_of_enableExplainText_9() { return &___enableExplainText_9; } inline void set_enableExplainText_9(bool value) { ___enableExplainText_9 = value; } inline static int32_t get_offset_of_explainText_10() { return static_cast<int32_t>(offsetof(ControllerSupportArg_t1887899189, ___explainText_10)); } inline ByteU5BU5D_t3397334013* get_explainText_10() const { return ___explainText_10; } inline ByteU5BU5D_t3397334013** get_address_of_explainText_10() { return &___explainText_10; } inline void set_explainText_10(ByteU5BU5D_t3397334013* value) { ___explainText_10 = value; Il2CppCodeGenWriteBarrier(&___explainText_10, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of nn.hid.ControllerSupportArg struct ControllerSupportArg_t1887899189_marshaled_pinvoke { uint8_t ___playerCountMin_1; uint8_t ___playerCountMax_2; uint8_t ___enableTakeOverConnection_3; uint8_t ___enableLeftJustify_4; uint8_t ___enablePermitJoyDual_5; uint8_t ___enableSingleMode_6; uint8_t ___enableIdentificationColor_7; Color4u8_t1633930318 ___identificationColor_8[4]; int8_t ___enableExplainText_9; uint8_t ___explainText_10[516]; }; // Native definition for COM marshalling of nn.hid.ControllerSupportArg struct ControllerSupportArg_t1887899189_marshaled_com { uint8_t ___playerCountMin_1; uint8_t ___playerCountMax_2; uint8_t ___enableTakeOverConnection_3; uint8_t ___enableLeftJustify_4; uint8_t ___enablePermitJoyDual_5; uint8_t ___enableSingleMode_6; uint8_t ___enableIdentificationColor_7; Color4u8_t1633930318 ___identificationColor_8[4]; int8_t ___enableExplainText_9; uint8_t ___explainText_10[516]; };
9f18e005466a6058b81b0beb4f7e23eba18a3bcd
edfd12506922f269d718faa0d60730f1d30b8e52
/misc/fpsmc.cpp
74cbbac911a1ab9a40cc2ed510ee2c79a05cef55
[]
no_license
simomounir/angsd-1
09794c895a7aee725bff7e53ef7186b0c6ae9e07
6cc8b4e56205ae83a1bbeaaded10329b05bdf9f0
refs/heads/master
2021-01-13T10:02:21.884073
2016-12-09T07:40:55
2016-12-09T07:40:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,372
cpp
fpsmc.cpp
#include <vector> #include <cassert> #include <cmath> #include "psmcreader.h" #include "main_psmc.h" using namespace std; struct Site{ double g0, g1; }; struct wins{ int from;//inclusive int to;//inclusive }; class fastPSMC { unsigned maxTime; //number of time intervals double rho; std::vector<double> timePoints;//coalescence times. std::vector<double> P1, P2, P3, P4, P5, P6, P7;//each has length of timePoints.size() std::vector<double> R1, R2; ////each has length of timePoints.size() std::vector<double> epSize; //effective population size // std::vector<double> fbProb; //length = timePoints.size() double **fw;//maxTime x nWindows+1 double **bw;//maxTime x nWindows+1 public: fastPSMC(){ rho = 0.207; maxTime=100; fprintf(stderr,"rho:%f maxTime:%d\n",rho,maxTime); } void init(size_t numWin); double llh(std::vector<Site> &data); //Initialisation void SetTimeIntervals(){ for (unsigned i = 0; i < maxTime+1; i++){ timePoints.push_back( i ); //prob1.push_back( 0 ); } } void SetEPSize(){ epSize.clear(); for (unsigned i = 0; i < maxTime; i++) epSize.push_back( 1 ); } void ComputeFBProbs(std::vector<Site> &data,std::vector<wins> &windows){ //we first set the initial fwprobs to uniform for(int i=0;i<timePoints.size();i++) fw[i][0] = 1.0/timePoints.size(); //we now loop over windows. //v=0 is above and is the initial distribution, we therefore plug in at v+1 for(int v=0;v<windows.size();v++){ ComputeRs(v);//<-prepare, this is based on last window fw[v+1][0] = fw[v][0]*P1[0] + R1[0]*P3[0] + fw[v][0]*P4[0]; for (unsigned i = 1; i < maxTime; i++){ fw[v+1][i] = (fw[v+1][i]*P1[i] + R2[i-1]*P2[i-1] + R1[i]*P3[i] + fw[v+1][i]*P4[i]); } } } private: void ComputeP1(){ for (unsigned i = 0; i < maxTime; i++){ P1[i] = exp( -rho*1*(timePoints[i+1] - timePoints[i]) ); } } void ComputeP2(){ for (unsigned i = 0; i < maxTime; i++) P2[i] = 1 - P5[i]; } void ComputeP3(){ for (unsigned i = 0; i < maxTime; i++) P3[i] = exp(-2*rho*timePoints[i]) - exp(-2*rho*timePoints[i+1]) - P6[i]; } void ComputeP4(){ for (unsigned i = 0; i < maxTime; i++) P4[i] = P3[i]; } void ComputeP5(){ for (unsigned i = 0; i < maxTime; i++) P5[i] = exp( -epSize[i]*(timePoints[i+1] - timePoints[i]) ); } void ComputeP6(){ for (unsigned i = 0; i < maxTime; i++){ double tmp = 0; tmp = exp((epSize[i]-2*rho)*timePoints[i]) - exp((epSize[i]-2*rho)*timePoints[i+1]); tmp = tmp*2*rho*exp(-epSize[i]*timePoints[i+1])/(epSize[i] - 2*rho); P6[i] = tmp; } } void ComputeP7(){ for (unsigned i = 0; i < maxTime; i++) P7[i] = P6[i]; } void ComputeR1(int v){ double tmp = 0; for (unsigned i = maxTime - 1; i > 0 ; i--){ // fprintf(stderr,"i:%u\n",i); fprintf(stderr,"i:%d cap:%lu val:(%d,%d)\n",i,R1.capacity(),i,v); R1[i] = tmp + fw[i][v]; tmp = R1[i]; } } void ComputeR2(int v){ double tmp = 0; for (unsigned i = 0; i < maxTime ; i++){ R2[i] = tmp*P2[i]+fw[v][i]*P6[i]+R1[i]*P7[i]; tmp = R2[i]; } } void ComputeRs(int v){ fprintf(stderr,"v:%d\n",v); ComputeR1(v); ComputeR2(v); } void ComputeGlobalProbabilities(){ ComputeP1(); ComputeP5(); ComputeP6(); ComputeP2(); ComputeP3(); ComputeP4(); ComputeP7(); } }; void fastPSMC::init(size_t numWindows){ SetTimeIntervals(); SetEPSize(); fw = new double *[timePoints.size()]; bw = new double *[timePoints.size()]; for(int i=0;i<timePoints.size();i++){ fw[i] = new double[numWindows+1]; bw[i] = new double[numWindows+1]; } maxTime++; P1.reserve(maxTime); P2.reserve(maxTime); P2.reserve(maxTime); P3.reserve(maxTime); P4.reserve(maxTime); P5.reserve(maxTime); P6.reserve(maxTime); P7.reserve(maxTime); R1.reserve(maxTime); R2.reserve(maxTime); maxTime--; ComputeGlobalProbabilities(); } double addProtect2(double a,double b){ //function does: log(exp(a)+exp(b)) while protecting for underflow double maxVal;// = std::max(a,b)); if(a>b) maxVal=a; else maxVal=b; double sumVal = exp(a-maxVal)+exp(b-maxVal); return log(sumVal) + maxVal; } //function to print the data we need int print_psmc_print_windows(std::vector<Site> &data){ for(size_t i=0;i<data.size();i++) fprintf(stdout,"%lu\t%f\t%f\n",i,data[i].g0,data[i].g1); } //function to print the data we need int main_analysis(std::vector<Site> &data,std::vector<wins> &windows){ fastPSMC obj; obj.init(windows.size()); for(int w=0;0&w<windows.size();w++){ fprintf(stderr,"win[%d]=(%d,%d)\n",w,windows[w].from,windows[w].to); } for(size_t i=0;0&&i<data.size();i++) fprintf(stdout,"%lu\t%f\t%f\n",i,data[i].g0,data[i].g1); obj.ComputeFBProbs(data,windows); } int psmc_wrapper(args *pars){ // fprintf(stderr,"[%s]\n",__FUNCTION__); //loop over chrs; for(myMap::iterator it=pars->perc->mm.begin();it!=pars->perc->mm.end();++it){ //set perchr iterator, if pars->chooseChr, then we have only use a single chr std::vector<Site> data;//really stupid, but lets go with it for now. std::vector<wins> windows; it = pars->chooseChr?iter_init(pars->perc,pars->chooseChr,pars->start,pars->stop):iter_init(pars->perc,it->first,pars->start,pars->stop); //generate window data int beginIndex = pars->perc->first; while(1){ int beginPos=pars->perc->pos[beginIndex]+1;//add one due to positions being offset with one. int endPos = beginPos+pars->winSize; int at=beginIndex; while(at<pars->perc->last&&pars->perc->pos[at]<endPos){ Site d; d.g0 = pars->perc->gls[at]; d.g1 = pars->perc->gls[at+1]; data.push_back(d); at++; } if(at>=pars->perc->last) break; wins w; w.from=beginIndex; w.to=at; windows.push_back(w); beginIndex = at; } main_analysis(data,windows); break; //print_psmc_print_windows(data); /* for(size_t s=pars->perc->first;0&&s<pars->perc->last;s++){ fprintf(stdout,"%s\t%d\t%e\t%e\n",it->first,pars->perc->pos[s]+1,pars->perc->gls[2*s],pars->perc->gls[2*s+1]); } */ if(pars->chooseChr!=NULL) break; } }
c5bade7445819d1e9154755181c3cdd761bc79e0
1aa205cb391b8924568fd7c8159fcad01d492972
/lab_11/lab11part2.cpp
bf51746984a23ff08ac6d179cab921437589c7f5
[ "MIT" ]
permissive
pwestrich/csc_2100
610832d41a5abe3363ad7cfb16d074b3f32ee28d
baa2326ac0015772b19262337886e5f1d7e0b66c
refs/heads/master
2020-07-04T12:11:48.591455
2016-11-17T20:49:57
2016-11-17T20:49:57
74,065,943
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
lab11part2.cpp
//Lab 11 Part 2 //by Philip Westrich //Tuesday, November 20, 2012 #include <iostream> int main(){ int array[10], *arrayPtr = array, input = 0, sum = 0; std::cout << "Please enter 10 integers." << std::endl; for (int i = 0; i < 10; i++){ do{ if (!std::cin){ std::cin.clear(); std::cin.ignore(80, '\n'); std::cout << "Invalid input. Please try again." << std::endl; } std::cout << "Number " << (i + 1) << ": "; std::cin >> input; } while (!std::cin); array[i] = input; } std::cout << "You entered: " << std::endl; for (int i = 0; i < 10; i++){ std::cout << *(arrayPtr + i) << std::endl; sum += *(arrayPtr + i); } std::cout << "And the sum of the above numbers is: " << sum << "." << std::endl; return 0; }
e30d416c48069ce4c3574283b0b459a6a9058b49
01b1f86aa05da3543a2399ffc34a8ba91183e896
/modules/boost/dispatch/include/boost/dispatch/meta/lambda_terminal.hpp
189e1a62bcfbad29bf0784e1fc2dfbad8c3f7766
[ "BSL-1.0" ]
permissive
jtlap/nt2
8070b7b3c4b2f47c73fdc7006b0b0eb8bfc8306a
1b97350249a4e50804c2f33e4422d401d930eccc
refs/heads/master
2020-12-25T00:49:56.954908
2015-05-04T12:09:18
2015-05-04T12:09:18
1,045,122
35
7
null
null
null
null
UTF-8
C++
false
false
1,180
hpp
lambda_terminal.hpp
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_DISPATCH_META_LAMBDA_TERMINAL_HPP_INCLUDED #define BOOST_DISPATCH_META_LAMBDA_TERMINAL_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////// // Defines a terminal fitting a lambda function //////////////////////////////////////////////////////////////////////////////// #include <boost/proto/matches.hpp> #include <boost/proto/transform.hpp> namespace boost { namespace dispatch { template<class Lambda> struct lambda_terminal : boost::proto:: and_< boost::proto::nullary_expr<boost::proto::_,boost::proto::_> , boost::proto::if_< Lambda() > > {}; } } #endif
ef9d48cc344a4cb895e4f0d45e7534ade54bedec
9f19bb2cf94e37f25a7a3c1550cac872e8fda4da
/Tree Pruning.cpp
3f36617bb69c92bcd4954322982cbb969b4db1dc
[]
no_license
cxz66666/PEG-DMOJ-Solutions
bf7987112f2fb7d1b3d7a7ce43caa03e5b981024
8c1beccc7d6e768f903dac827fd47eb7d739069c
refs/heads/master
2021-09-05T02:55:07.873534
2018-01-23T18:55:04
2018-01-23T18:55:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,998
cpp
Tree Pruning.cpp
#include <bits/stdc++.h> #define INF 0x3f3f3f3f #define B 300 using namespace std; int N, D; struct node { int color = 0; int left = -1; int right = -1; int nw = 0; int nb = 0; }nn; node alln[310]; int dp[310][310+B]; void dfs(int u) { if (alln[u].color) alln[u].nw++; else alln[u].nb++; if (~alln[u].left) { dfs(alln[u].left); alln[u].nw += alln[alln[u].left].nw; alln[u].nb += alln[alln[u].left].nb; } if (~alln[u].right) { dfs(alln[u].right); alln[u].nw += alln[alln[u].right].nw; alln[u].nb += alln[alln[u].right].nb; } } int mincut(int u, int rm) { int diff = alln[u].nw - alln[u].nb; if (rm == 0) return 0; if (rm == diff) return 1; if (~dp[u][rm+B]) return dp[u][rm+B]; int& ans = dp[u][rm+B]; ans = INF; if (~alln[u].left && ~alln[u].right) { for (int i = 0; i <= abs(rm); i++) { int ls = mincut(alln[u].left, rm > 0 ? i : -i); int rs = mincut(alln[u].right, rm > 0 ? rm-i : rm+i); if (ls!=INF && rs != INF); ans = min(ans, ls+rs); } } else if (~alln[u].left) { int ls = mincut(alln[u].left, rm); if (ls != INF) ans = min(ans, ls); } else if (~alln[u].right) { int rs = mincut(alln[u].right, rm); if (rs != INF) ans = min(ans, rs); } return ans; } int main() { cin>>N>>D; for (int i = 0; i < N; i++) { int id, c, nc; cin>>id; cin>>alln[id].color>>nc; if (nc==0) continue; else if (nc == 1) cin>>alln[id].left; else cin>>alln[id].left>>alln[id].right; } dfs(0); int curdiff = alln[0].nw - alln[0].nb; //cout<<curdiff; int rm = curdiff - D; memset(dp,-1,sizeof dp); int ans = mincut(0,rm); if (ans == INF) cout<<"-1"; else cout<<ans; }
b41b8f7bb462d28f86517217afde4fe9c74cd260
0ab72b7740337ec0bcfec102aa7c740ce3e60ca3
/include/functional/corelj612/parameter/name.h
253391cbfbdd92e66ea7bc648c47f74ad8d9f470
[]
no_license
junwang-nju/mysimulator
1d1af4ad7ddbe114433ebdadd92de8bb3a45c04f
9c99970173ce87c249d2a2ca6e6df3a29dfc9b86
refs/heads/master
2021-01-10T21:43:01.198526
2012-12-15T23:22:56
2012-12-15T23:22:56
3,367,116
0
0
null
null
null
null
UTF-8
C++
false
false
438
h
name.h
#ifndef _Functional_CoreLJ612_Parameter_Name_H_ #define _Functional_CoreLJ612_Parameter_Name_H_ #include "functional/lj612/parameter/name.h" namespace mysimulator { enum CoreLJ612ParameterName { CoreLJ612Radius=LJ612EqRadius, CoreLJ612EnergyDepth=LJ612EqEnergyDepth, CoreLJ612RadiusSq=LJ612EqRadiusSq, CoreLJ612TwlfEnergyDepth=LJ612TwlfEnergyDepth, CoreLJ612NumberParameter=LJ612NumberParameter }; } #endif
cc7005cb4445d528615e063fe41d79b92cc402d6
2ce251519cc9fda67441e887b1856a3eb6809550
/common/colibri.cpp
cb8c2e6755670f6809926c50888230cd5a3c2d9d
[]
no_license
xbeowolf/colibrichat
c28ec39bb43c0bb6084410a36d4c8fbede2622c1
a72d6cb915bd025bf8d1a2e98c56770a960de3b5
refs/heads/master
2021-04-28T19:38:10.360351
2018-03-03T23:58:44
2018-03-03T23:58:44
121,901,787
0
0
null
null
null
null
UTF-8
C++
false
false
4,953
cpp
colibri.cpp
//----------------------------------------------------------------------------- // // Includes // #pragma region Includes #include "stdafx.h" // Windows API #include <strsafe.h> // Project #include "colibri.h" #pragma endregion using namespace colibrichat; //----------------------------------------------------------------------------- void CALLBACK io::pack(std::ostream& os, const colibrichat::SetId& data) { io::pack(os, data.size()); for each (colibrichat::SetId::value_type const& v in data) io::pack(os, v); } void CALLBACK io::pack(std::ostream& os, const colibrichat::User& data) { io::pack(os, data.name); io::pack(os, data.ftCreation); io::pack(os, data.IP); io::pack(os, data.isOnline); io::pack(os, data.idOnline); io::pack(os, data.nStatus); io::pack(os, data.accessibility); io::pack(os, data.nStatusImg); io::pack(os, data.strStatus); io::pack(os, data.cheat); } void CALLBACK io::pack(std::ostream& os, const colibrichat::Channel& data) { io::pack(os, data.name); io::pack(os, data.password); io::pack(os, data.opened); io::pack(os, data.ftCreation); io::pack(os, data.topic); io::pack(os, data.idTopicWriter); io::pack(os, data.reader); io::pack(os, data.writer); io::pack(os, data.member); io::pack(os, data.moderator); io::pack(os, data.admin); io::pack(os, data.founder); io::pack(os, data.nAutoStatus); io::pack(os, data.nLimit); io::pack(os, data.isHidden); io::pack(os, data.isAnonymous); io::pack(os, data.crBackground); } void CALLBACK io::unpack(io::mem& is, colibrichat::SetId& data) { size_t count; DWORD id; io::unpack(is, count); while (count--) { io::unpack(is, id); data.insert(id); } } void CALLBACK io::unpack(io::mem& is, colibrichat::User& data) { io::unpack(is, data.name); io::unpack(is, data.ftCreation); io::unpack(is, data.IP); io::unpack(is, data.isOnline); io::unpack(is, data.idOnline); io::unpack(is, data.nStatus); io::unpack(is, data.accessibility); io::unpack(is, data.nStatusImg); io::unpack(is, data.strStatus); io::unpack(is, data.cheat); } void CALLBACK io::unpack(io::mem& is, colibrichat::Channel& data) { io::unpack(is, data.name); io::unpack(is, data.password); io::unpack(is, data.opened); io::unpack(is, data.ftCreation); io::unpack(is, data.topic); io::unpack(is, data.idTopicWriter); io::unpack(is, data.reader); io::unpack(is, data.writer); io::unpack(is, data.member); io::unpack(is, data.moderator); io::unpack(is, data.admin); io::unpack(is, data.founder); io::unpack(is, data.nAutoStatus); io::unpack(is, data.nLimit); io::unpack(is, data.isHidden); io::unpack(is, data.isAnonymous); io::unpack(is, data.crBackground); } //----------------------------------------------------------------------------- // Time funstions void CALLBACK FileTimeToLocalTime(const FILETIME &ft, SYSTEMTIME &st) { FILETIME temp; FileTimeToLocalFileTime(&ft, &temp); FileTimeToSystemTime(&temp, &st); } void CALLBACK GetSystemFileTime(FILETIME& ft) { SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); } //----------------------------------------------------------------------------- bool CALLBACK Contact::isOpened(DWORD id) const { return opened.find(id) != opened.end(); } CALLBACK User::User() { GetSystemFileTime(ftCreation); IP.S_un.S_addr = 0; isOnline = eOffline; idOnline = 0; nStatus = eReady; nStatusImg = 0; strStatus = TEXT(""); cheat.isGod = false; cheat.isDevil = false; } EChanStatus CALLBACK Channel::getStatus(DWORD idUser) const { if (founder.find(idUser) != founder.end()) return eFounder; else if (admin.find(idUser) != admin.end()) return eAdmin; else if (moderator.find(idUser) != moderator.end()) return eModerator; else if (member.find(idUser) != member.end()) return eMember; else if (writer.find(idUser) != writer.end()) return eWriter; else if (reader.find(idUser) != reader.end()) return eReader; else return eOutsider; } void CALLBACK Channel::setStatus(DWORD idUser, EChanStatus val) { // Delete previous state if it's not founder if (founder.find(idUser) != founder.end()) founder.erase(idUser); else if (admin.find(idUser) != admin.end()) admin.erase(idUser); else if (moderator.find(idUser) != moderator.end()) moderator.erase(idUser); else if (member.find(idUser) != member.end()) member.erase(idUser); else if (writer.find(idUser) != writer.end()) writer.erase(idUser); else if (reader.find(idUser) != reader.end()) reader.erase(idUser); // Set new state switch (val) { case eFounder: founder.insert(idUser); break; case eAdmin: admin.insert(idUser); break; case eModerator: moderator.insert(idUser); break; case eMember: member.insert(idUser); break; case eWriter: writer.insert(idUser); break; case eReader: reader.insert(idUser); break; case eOutsider: // No actions break; } } //----------------------------------------------------------------------------- // The End.
81bd582f961aa58fd8efc54704544245e8c759da
e8dceb2f4f6dd1149c798be4312a4f480a66859b
/Source.cpp
9fbadc4440be2d9074b7fbc38a2bcf1f56feb5c8
[]
no_license
JoCoKo/OOP_lab_5
866365fee28ca2983818babc32885393a021e35d
352f8c9a7c64ab3fca523b224d724a0fefb1371d
refs/heads/master
2021-08-30T22:52:33.374508
2017-12-19T18:23:47
2017-12-19T18:23:47
114,767,596
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
Source.cpp
#include <iostream> #include <fstream> #include <thread> #include "Number.h" #include "Numbers.h" #include "Windows.h" using namespace std; int main(int argc, char* argv[]) { /* Number* t1 = new Number(12); cout << "RESULT:" << t1->getDecomposition() << "#" << endl; if (argc >= 3) { uint64 curNum; ofstream fout(argv[2]); ifstream fin(argv[1]); while (!fin.eof()) { fin >> curNum; cout << curNum << " "; Number* w1 = new Number(curNum); fout << w1->getDecomposition() << endl; } fout.close(); fin.close(); } else { cout << "Not enough params" << endl; }; */ { Numbers nums; nums.voidMe(); } //Sleep(5000); //cout << std::thread::hardware_concurrency() << endl; system("pause"); return 0; }
561c959ba2e29221f85d9ce1f9c7be776e803a2c
3d8254cdec23ce1bf8fb8ade5527732fa86a477c
/src/srci2src.cpp
cfde2adad41aabffb7d7633704fabf1d9fb04a42
[ "BSD-3-Clause" ]
permissive
zcy618/openVOICE
8cb2cc60e3aa73b40a438beed38282c343688a97
ee7cff99cfd1bd21265138b4407cfd685c1c0ce7
refs/heads/master
2022-08-27T20:26:34.537356
2020-05-29T21:29:13
2020-05-29T21:29:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,669
cpp
srci2src.cpp
//@author Erik Edwards //@date 2019 #include <iostream> #include <fstream> #include <unistd.h> #include <string> #include <cstring> #include <argtable2.h> #include <valarray> #include <vector> #include <unordered_map> #include <cctype> int main(int argc, char *argv[]) { using namespace std; //timespec tic, toc; clock_gettime(CLOCK_REALTIME,&tic); //Declarations int ret = 0; const string errstr = ": \033[1;31merror:\033[0m "; const string warstr = ": \033[1;35mwarning:\033[0m "; const string progstr(__FILE__,string(__FILE__).find_last_of("/")+1,strlen(__FILE__)-string(__FILE__).find_last_of("/")-5); valarray<char> stdi(1); ifstream ifs; string line; size_t pos1, pos2; const vector<string> includes = {"<iostream>","<fstream>","<unistd.h>","<string>","<cstring>","<valarray>","<complex>","<unordered_map>","<argtable2.h>","\"/home/erik/codee/cmli/cmli.hpp\""}; const string ind = " "; size_t i, I, Imin, o, O, Omin, t, T, a, A = 0; int s2i; //const vector<uint32_t> frmts = {0,1,65,101,102,147,148}; const vector<size_t> types = {0,1,2,3,8,9,10,16,17,32,33,64,65,101,102,103}; const unordered_map<size_t,string> zros = {{1,"0.0f"},{2,"0.0"},{3,"0.0L"},{8,"'\0'"},{9,"'\0'"},{10,"false"},{16,"0"},{17,"0u"},{32,"0"},{33,"0u"},{64,"0l"},{65,"0ul"},{101,"0.0f"},{102,"0.0"},{103,"0.0L"}}; const unordered_map<size_t,string> ones = {{1,"1.0f"},{2,"1.0"},{3,"1.0L"},{8,"'\1'"},{9,"'\1'"},{10,"true"},{16,"1"},{17,"1u"},{32,"1"},{33,"1u"},{64,"1l"},{65,"1ul"},{101,"1.0f"},{102,"1.0"},{103,"1.0L"}}; const unordered_map<size_t,string> aftyps = {{1,"f32"},{2,"f64"},{8,"b8"},{9,"u8"},{10,"b8"},{16,"s16"},{17,"u16"},{32,"s32"},{33,"u32"},{64,"s64"},{65,"u64"},{101,"c32"},{102,"c64"}}; unordered_map<size_t,string> fmts = {{0,"0"},{1,"1"},{65,"65"},{101,"101"},{102,"102"},{147,"147"}}; unordered_map<size_t,string> typs = {{0,"txt"},{1,"float"},{2,"double"},{3,"long double"},{8,"int8_t"},{9,"uint8_t"},{10,"bool"},{16,"int16_t"},{17,"uint16_t"},{32,"int32_t"},{33,"uint32_t"},{64,"int64_t"},{65,"uint64_t"},{101,"complex<float>"},{102,"complex<double>"},{103,"complex<long double>"}}; const unordered_map<size_t,string> typs_arma = {{0,"txt"},{1,"float"},{2,"double"},{3,"long double"},{8,"char"},{9,"unsigned char"},{10,"char"},{16,"int16_t"},{17,"uint16_t"},{32,"int32_t"},{33,"uint32_t"},{64,"int64_t"},{65,"uint64_t"},{101,"complex<float>"},{102,"complex<double>"},{103,"complex<long double>"}}; const unordered_map<size_t,string> typs_afire = {{0,"txt"},{1,"float"},{2,"double"},{8,"char"},{9,"unsigned char"},{10,"char"},{16,"int16_t"},{17,"uint16_t"},{32,"int32_t"},{33,"uint32_t"},{64,"intl"},{65,"uintl"},{101,"af::cfloat"},{102,"af::cdouble"}}; vector<size_t> oktypes; vector<string> oktypestrs; string oktypestr; size_t c, prevc; vector<string> inames, onames, anames; string ttstr, tistr, tcstr, zi, zc, oi, oc, ai, ac; FILE *tmpf = tmpfile(), *tmpf8 = tmpfile(), *tmpf101 = tmpfile(); bool do_float = false, do_int = false, do_complex = false; char buff[256*16]; string::size_type n; string fname; //only used for a_fl opt (only for <cmath>) bool tictoc = false; //Description string descr; descr += "Generates a generic CLI (command-line interface) program,\n"; descr += "printing it to stdout (so can make .cpp file to edit). \n"; descr += "This takes an input .cpp file from isrc,\n"; descr += "and adds boilerplate and other code to make the final .cpp.\n"; descr += "\n"; descr += "Examples:\n"; descr += "$ srci2src srci/X.cpp > src/X.cpp \n"; //Argtable int nerrs; struct arg_file *a_fi = arg_filen(nullptr,nullptr,"<file>",0,1,"input file"); struct arg_lit *a_arma = arg_litn("A","Armadillo",0,1,"include if this is for Armadillo"); struct arg_lit *a_eig = arg_litn("E","Eigen",0,1,"include if this is for Eigen"); struct arg_lit *a_fire = arg_litn("F","ArrayFire",0,1,"include if this is for ArrayFire"); struct arg_lit *a_dz = arg_litn("d","dz",0,1,"sub _s->_d and _c->_z for function names (e.g. for blas names)"); struct arg_lit *a_ov = arg_litn("v","voice",0,1,"sub _s->_d and _c->_z for function names (similar to blas names)"); struct arg_lit *a_fl = arg_litn("f","fl",0,1,"add f, l to float, long double function names (e.g. for cmath)"); struct arg_lit *a_FL = arg_litn("L","FL",0,1,"same but also for complex cases (e.g. for fftw)"); struct arg_lit *a_t = arg_litn("t","time",0,1,"include timing code around Process section"); struct arg_lit *a_T = arg_litn("T","TIME",0,1,"include timing code around whole program"); struct arg_lit *a_oh = arg_litn("O","OH",0,1,"include to omit Write output headers so can write at Finish"); struct arg_lit *a_help = arg_litn("h","help",0,1,"display this help and exit"); struct arg_end *a_end = arg_end(5); void *argtable[] = {a_fi, a_arma, a_eig, a_fire, a_dz, a_ov, a_fl, a_FL, a_t, a_T, a_oh, a_help, a_end}; if (arg_nullcheck(argtable)!=0) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating argtable" << endl; return 1; } nerrs = arg_parse(argc, argv, argtable); if (a_help->count>0) { cout << "Usage: " << progstr; arg_print_syntax(stdout, argtable, "\n"); cout << endl; arg_print_glossary(stdout, argtable, " %-25s %s\n"); cout << endl << descr; return 1; } if (nerrs>0) { arg_print_errors(stderr,a_end,(progstr+": "+to_string(__LINE__)+errstr).c_str()); return 1; } //Check stdin stdi[0] = (a_fi->count<=0 || strlen(a_fi->filename[0])==0 || strcmp(a_fi->filename[0],"-")==0); if (isatty(fileno(stdin)) && stdi.sum()>0) { cerr << progstr+": " << __LINE__ << errstr << "no stdin detected" << endl; return 1; } //Open input if (stdi[0]==0) { ifs.open(a_fi->filename[0], ifstream::binary); } else { ifs.copyfmt(cin); ifs.basic_ios<char>::rdbuf(cin.rdbuf()); } if (!ifs) { cerr << progstr+": " << __LINE__ << errstr << "problem opening input isrc file" << endl; return 1; } //Sub TIC and TOC ofstream oftmp; FILE* ttmpf = tmpfile(); oftmp.open(to_string(fileno(ttmpf))); while (getline(ifs,line) && !ifs.eof()) { pos1 = line.find("//TIC"); pos2 = line.find("//TOC"); if (pos1<line.size()) { oftmp << line.substr(0,pos1) << "clock_gettime(CLOCK_REALTIME,&tic); //TIC" << endl; } else if (pos2<line.size()) { oftmp << line.substr(0,pos2) << "clock_gettime(CLOCK_REALTIME,&toc); //TOC" << endl; oftmp << line.substr(0,pos2) << "cerr << \"elapsed time = \" << (toc.tv_sec-tic.tv_sec)*1e3 + (toc.tv_nsec-tic.tv_nsec)/1e6 << \" ms\" << endl;" << endl; if (a_t->count>0) { cerr << progstr+": " << __LINE__ << warstr << "using tic/toc and -t option could conflict" << endl; } if (a_T->count>0) { cerr << progstr+": " << __LINE__ << errstr << "cannot use -T opt with other timing options" << endl; return 1; } tictoc = true; } else { oftmp << line << endl; } } oftmp.close(); ifs.close(); ifs.open(to_string(fileno(ttmpf))); //Prep for arma if (a_arma->count>0) { typs = typs_arma; } if (a_fire->count>0) { typs = typs_afire; } //Get fname if (a_fl->count>0 || a_FL->count>0) { fname = string(a_fi->filename[0]); if (fname.find("fftw")==string::npos) { pos1 = fname.find_last_of("/") + 1; pos2 = fname.find(".cpp"); fname = " "+fname.substr(pos1,pos2-pos1); //cerr << "fname=" << fname << endl; } else { fname = "fftw"; } } //PRINT OUT CODE //Initial comments cout << "//@author Erik Edwards" << endl; cout << "//@date 2019-2020" << endl; getline(ifs,line); while (line.size()>0 && line.compare(0,9,"//Include")!=0) { cout << line << endl; getline(ifs,line); } cout << endl; //Includes while (line.compare(0,9,"//Include")!=0) { getline(ifs,line); } cout << endl; if (tictoc || a_t->count>0 || a_T->count>0) { cout << "#include <ctime>" << endl; } for (i=0; i<includes.size(); i++) { cout << "#include " << includes[i] << endl; } if (a_arma->count>0) { cout << "#include <armadillo>" << endl; } if (a_eig->count>0) { cout << "#include <eigen3/Eigen/Core>" << endl; } if (a_fire->count>0) { cout << "#include <arrayfire.h>" << endl; } getline(ifs,line); while (line.size()>0 && line.compare(0,14,"//Declarations")!=0) { cout << line << endl; getline(ifs,line); } cout << endl; //Undefine I cout << "#ifdef I" << endl << "#undef I" << endl << "#endif" << endl; cout << endl; //Start main cout << endl; cout << "int main(int argc, char *argv[])" << endl; cout << "{" << endl; cout << ind << "using namespace std;" << endl; if (tictoc || a_t->count>0 || a_T->count>0) { cout << ind << "timespec tic, toc;"; if (a_T->count>0) { cout << " clock_gettime(CLOCK_REALTIME,&tic);"; } cout << endl; } cout << endl; //Declarations start while (line.compare(0,14,"//Declarations")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Declarations" << endl; cout << ind << "int ret = 0;" << endl; cout << ind << "const string errstr = \": \\033[1;31merror:\\033[0m \";" << endl; cout << ind << "const string warstr = \": \\033[1;35mwarning:\\033[0m \";" << endl; cout << ind << "const string progstr(__FILE__,string(__FILE__).find_last_of(\"/\")+1,strlen(__FILE__)-string(__FILE__).find_last_of(\"/\")-5);" << endl; //Get okfmts (only sometimes present) getline(ifs,line); //this line must have okfmts if (line.size()>36 && line.compare(0,34,"const valarray<uint8_t> okfmts = {")==0) { cout << ind << line << endl; getline(ifs,line); } //Get oktypes //this line must have oktypes if (line.size()<37 || line.compare(0,35,"const valarray<uint8_t> oktypes = {")!=0) { cerr << progstr+": " << __LINE__ << errstr << "problem with line for oktypes" << endl; return 1; } cout << ind << line << endl; pos1 = line.find_first_of("{",0) + 1; pos2 = line.find_first_of("}",0) - 1; oktypestr = line.substr(pos1,pos2-pos1+1); T = 1; for (c=0; c<oktypestr.size(); c++) { if (oktypestr.substr(c,1)==",") { T++; } } t = prevc = 0; for (c=0; c<oktypestr.size(); c++) { if (oktypestr.substr(c,1)=="," || oktypestr.substr(c,1)==" ") { s2i = stoi(oktypestr.substr(prevc,c-prevc)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } else { oktypes.push_back(size_t(s2i)); } prevc = c + 1; t++; } } s2i = stoi(oktypestr.substr(prevc,c-prevc)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } oktypes.push_back(size_t(s2i)); for (t=0; t<T; t++) { oktypestrs.push_back(typs.at(oktypes[t])); } //Declare maps //cout << ind << "const unordered_map<uint32_t,size_t> szs = {{0,2},{1,4},{2,8},{3,16},{8,1},{9,1},{10,1},{16,2},{17,2},{32,4},{33,4},{64,8},{65,8},{101,8},{102,16},{103,32}};" << endl; //Get I and O getline(ifs,line); //this line must have I and O if (line.size()<8 || line.find("size_t ")==string::npos) { cerr << progstr+": " << __LINE__ << errstr << "problem with line for I and O" << endl; return 1; } pos1 = line.find("=",0) + 2; pos2 = line.find(",",0) - 1; s2i = stoi(line.substr(pos1,pos2-pos1+1)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } I = size_t(s2i); pos1 = line.find("O",0) + 4; pos2 = line.find(";",0) - 1; s2i = stoi(line.substr(pos1,pos2-pos1+1)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } O = size_t(s2i); if (I>0 || O>0) { cout << ind << "const size_t "; } if (I>0) { cout << "I = " << I; } if (O>0) { if (I>0) { cout << ", "; } cout << "O = " << O; } cout << ";" << endl; //Declarations continue if (I==0) { cout << ind << "ofstream ofs1"; for (o=1; o<O; o++) { cout << ", ofs" << o+1; } cout << ";" << endl; cout << ind << "int8_t stdo1"; for (o=1; o<O; o++) { cout << ", stdo" << o+1; } for (o=0; o==0 || o<O; o++) { cout << ", wo" << o+1; } cout << ";"; cout << endl; if (O>0) { cout << ind << "ioinfo o1"; for (o=1; o<O; o++) { cout << ", o" << o+1; } cout << ";" << endl; } } else { cout << ind << "ifstream ifs1"; for (i=1; i<I; i++) { cout << ", ifs" << i+1; } cout << "; "; cout << "ofstream ofs1"; for (o=1; o<O; o++) { cout << ", ofs" << o+1; } cout << ";" << endl; cout << ind << "int8_t stdi1"; for (i=1; i<I; i++) { cout << ", stdi" << i+1; } for (o=0; o==0 || o<O; o++) { cout << ", stdo" << o+1; } for (o=0; o==0 || o<O; o++) { cout << ", wo" << o+1; } cout << ";"; cout << endl; cout << ind << "ioinfo i1"; for (i=1; i<I; i++) { cout << ", i" << i+1; } for (o=0; o<O; o++) { cout << ", o" << o+1; } cout << ";" << endl; } getline(ifs,line); while (line.size()>0 && line.compare(0,13,"//Description")!=0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; //Description while (line.compare(0,13,"//Description")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Description" << endl; getline(ifs,line); while (line.size()>0 && line.compare(0,1," ")!=0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; //Argtable start while (line.compare(0,10,"//Argtable")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Argtable" << endl; cout << ind << "int nerrs;" << endl; //Get 1st argtable line and Imin and inames if (I>0) { getline(ifs,line); cout << ind << line << endl; pos1 = line.find("<file>",0) + 5; while (line.substr(pos1,1)!=",") { pos1++; } pos1++; pos2 = pos1 + 1; while (line.substr(pos2,1)!=",") { pos2++; } if (line.substr(pos1,pos2-pos1)=="I") { Imin = I; } else if (line.substr(pos1,pos2-pos1)=="I-1") { if (I>0) { Imin = I-1; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="I-2") { if (I>1) { Imin = I-2; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="I-3") { if (I>2) { Imin = I-3; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="I-4") { if (I>3) { Imin = I-4; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="I-5") { if (I>4) { Imin = I-5; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="I-6") { if (I>5) { Imin = I-6; } else { cerr << progstr+": " << __LINE__ << errstr << "Imin expression evals to negative" << endl; return 1; } } else { s2i = stoi(line.substr(pos1,pos2-pos1)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } Imin = size_t(s2i); } pos1 = line.find("input file",0) + 10; while (line.substr(pos1,1)!="(") { pos1++; } pos2 = pos1; for (i=0; i<I; i++) { pos1 = pos2 + 1; pos2 = pos1; while (line.substr(pos2,1)!=")" && line.substr(pos2,1)!=",") { pos2++; } inames.push_back(line.substr(pos1,pos2-pos1)); } } else { Imin = 0; } if (Imin>I) { cerr << progstr+": " << __LINE__ << errstr << "Imin cannot be greater than I" << endl; return 1; } //Get additional argtable lines and anames getline(ifs,line); while (line.find("ofile",0)==string::npos) { cout << ind << line << endl; pos1 = line.find("*",0) + 1; pos2 = line.find("=",0) - 1; anames.push_back(line.substr(pos1,pos2-pos1)); A++; getline(ifs,line); } //Get last argtable line and onames //getline(ifs,line); cout << ind << line << endl; pos1 = line.find("<file>",0) + 5; while (line.substr(pos1,1)!=",") { pos1++; } pos1++; pos2 = pos1 + 1; while (line.substr(pos2,1)!=",") { pos2++; } if (line.substr(pos1,pos2-pos1)=="O") { Omin = O; } else if (line.substr(pos1,pos2-pos1)=="O-1") { if (O>0) { Omin = O-1; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="O-2") { if (O>1) { Omin = O-2; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="O-3") { if (O>2) { Omin = O-3; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="O-4") { if (O>3) { Omin = O-4; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="O-5") { if (O>4) { Omin = O-5; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else if (line.substr(pos1,pos2-pos1)=="O-6") { if (O>5) { Omin = O-6; } else { cerr << progstr+": " << __LINE__ << errstr << "Omin expression evals to negative" << endl; return 1; } } else { s2i = stoi(line.substr(pos1,pos2-pos1)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } Omin = size_t(s2i); } pos1 = line.find("output file",0) + 10; while (line.substr(pos1,1)!="(") { pos1++; } pos2 = pos1; for (o=0; o<O; o++) { pos1 = pos2 + 1; pos2 = pos1; while (line.substr(pos2,1)!=")" && line.substr(pos2,1)!=",") { pos2++; } onames.push_back(line.substr(pos1,pos2-pos1)); } if (Omin>O) { cerr << progstr+": " << __LINE__ << errstr << "Omin cannot be greater than O" << endl; return 1; } //Finish argtable cout << ind << "struct arg_lit *a_help = arg_litn(\"h\",\"help\",0,1,\"display this help and exit\");" << endl; cout << ind << "struct arg_end *a_end = arg_end(5);" << endl; cout << ind << "void *argtable[] = {"; if (I>0) { cout << "a_fi, "; } for (a=0; a<A; a++) { cout << anames[a] << ", "; } cout << "a_fo, a_help, a_end};" << endl; cout << ind << "if (arg_nullcheck(argtable)!=0) { cerr << progstr+\": \" << __LINE__ << errstr << \"problem allocating argtable\" << endl; return 1; }" << endl; cout << ind << "nerrs = arg_parse(argc, argv, argtable);" << endl; cout << ind << "if (a_help->count>0)" << endl; cout << ind << "{" << endl; cout << ind+ind << "cout << \"Usage: \" << progstr; arg_print_syntax(stdout, argtable, \"\\n\");" << endl; cout << ind+ind << "cout << endl; arg_print_glossary(stdout, argtable, \" %-25s %s\\n\");" << endl; cout << ind+ind << "cout << endl << descr; return 1;" << endl; cout << ind << "}" << endl; cout << ind << "if (nerrs>0) { arg_print_errors(stderr,a_end,(progstr+\": \"+to_string(__LINE__)+errstr).c_str()); return 1; }" << endl << endl; //Check stdin if (I>0) { cout << endl; cout << ind << "//Check stdin" << endl; cout << ind << "stdi1 = (a_fi->count==0 || strlen(a_fi->filename[0])==0 || strcmp(a_fi->filename[0],\"-\")==0);" << endl; for (i=1; i<Imin+1; i++) { cout << ind << "stdi" << i+1 << " = (a_fi->count<=" << i << " || strlen(a_fi->filename[" << i << "])==0 || strcmp(a_fi->filename[" << i << "],\"-\")==0);" << endl; } for (i=Imin+1; i<I; i++) { cout << ind << "if (a_fi->count>" << i << ") { stdi" << i+1 << " = (strlen(a_fi->filename[" << i << "])==0 || strcmp(a_fi->filename[" << i << "],\"-\")==0); }"; cout << ind << "else { stdi" << i+1 << " = (!isatty(fileno(stdin)) && a_fi->count==" << i << " && stdi1"; for (o=1; o<i; o++) { cout << "+stdi" << o+1; } cout << "==0); }" << endl; } if (I>1) { cout << ind << "if (stdi1"; for (i=1; i<I; i++) { cout << "+stdi" << i+1; } cout << ">1) { cerr << progstr+\": \" << __LINE__ << errstr << \"can only use stdin for one input\" << endl; return 1; }" << endl; } cout << ind << "if (stdi1"; for (i=1; i<I; i++) { cout << "+stdi" << i+1; } cout << ">0 && isatty(fileno(stdin))) { cerr << progstr+\": \" << __LINE__ << errstr << \"no stdin detected\" << endl; return 1; }" << endl << endl; } //Check stdout cout << endl; cout << ind << "//Check stdout" << endl; if (O==0) { cout << ind << "stdo1 = (a_fo->count==0 || strlen(a_fo->filename[0])==0 || strcmp(a_fo->filename[0],\"-\")==0);" << endl; } else { cout << ind << "if (a_fo->count>0) { stdo1 = (strlen(a_fo->filename[0])==0 || strcmp(a_fo->filename[0],\"-\")==0); }" << endl; cout << ind << "else { stdo1 = (!isatty(fileno(stdout))); }" << endl; } for (o=1; o<O; o++) { cout << ind << "if (a_fo->count>" << o << ") { stdo" << o+1 << " = (strlen(a_fo->filename[" << o << "])==0 || strcmp(a_fo->filename[" << o << "],\"-\")==0); }" << endl; cout << ind << "else { stdo" << o+1 << " = (!isatty(fileno(stdout)) && a_fo->count==" << o << " && stdo1"; for (i=1; i<o; i++) { cout << "+stdo" << i+1; } cout << "==0); }" << endl; } if (O>1) { cout << ind << "if (stdo1"; for (o=1; o<O; o++) { cout << "+stdo" << o+1; } cout << ">1) { cerr << progstr+\": \" << __LINE__ << errstr << \"can only use stdout for one output\" << endl; return 1; }" << endl; } cout << ind << "wo1 = (stdo1 || a_fo->count>0);"; for (o=1; o<O; o++) { cout << " wo" << o+1 << " = (stdo" << o+1 << " || a_fo->count>" << o << ");"; } cout << endl; cout << endl; //Open inputs if (I>0) { cout << endl; cout << ind << "//Open input"; if (I>1) { cout << "s"; } cout << endl; for (i=0; i<Imin+1; i++) { cout << ind << "if (stdi" << i+1 << ") { ifs" << i+1 << ".copyfmt(cin); ifs" << i+1 << ".basic_ios<char>::rdbuf(cin.rdbuf()); } else { ifs" << i+1 << ".open(a_fi->filename[" << i << "]); }" << endl; cout << ind << "if (!ifs" << i+1 << ") { cerr << progstr+\": \" << __LINE__ << errstr << \"problem opening input file"; if (I>1) { cout << " " << i+1; } cout << "\" << endl; return 1; }" << endl; } for (i=Imin+1; i<I; i++) { cout << ind << "if (stdi" << i+1 << " || a_fi->count>" << i << ")" << endl; cout << ind << "{" << endl; cout << ind+ind << "if (stdi" << i+1 << ") { ifs" << i+1 << ".copyfmt(cin); ifs" << i+1 << ".basic_ios<char>::rdbuf(cin.rdbuf()); } else { ifs" << i+1 << ".open(a_fi->filename[" << i << "]); }" << endl; cout << ind+ind << "if (stdi" << i+1 << " && ifs" << i+1 << ".peek()==EOF) { stdi" << i+1 << " = 0; }" << endl; cout << ind+ind << "else if (!ifs" << i+1 << ") { cerr << progstr+\": \" << __LINE__ << errstr << \"problem opening input file " << i+1 << "\" << endl; return 1; }" << endl; //cout << ind+ind << "if (!ifs" << i+1 << ") { cerr << progstr+\": \" << __LINE__ << errstr << \"problem opening input file " << i+1 << "\" << endl; return 1; }" << endl; cout << ind << "}" << endl; } cout << endl; } //Read input headers if (I>0) { cout << endl; cout << ind << "//Read input header"; if (I>1) { cout << "s"; } cout << endl; for (i=0; i<Imin+1; i++) { cout << ind << "if (!read_input_header(ifs" << i+1 << ",i" << i+1 << ")) { cerr << progstr+\": \" << __LINE__ << errstr << \"problem reading header for input file"; if (I>1) { cout << " " << i+1; } cout << "\" << endl; return 1; }" << endl; } for (i=Imin+1; i<I; i++) { cout << ind << "if (stdi" << i+1 << " || a_fi->count>" << i << ")" << endl; cout << ind << "{" << endl; cout << ind+ind << "if (!read_input_header(ifs" << i+1 << ",i" << i+1 << ")) { cerr << progstr+\": \" << __LINE__ << errstr << \"problem reading header for input file" << i+1 << "\" << endl; return 1; }" << endl; cout << ind << "}" << endl; cout << ind << "else { i" << i+1 << ".F = i1.F; i" << i+1 << ".T = i1.T; i" << i+1 << ".R = i" << i+1 << ".C = i" << i+1 << ".S = i" << i+1 << ".H = 1u; }" << endl; } cout << ind << "if ((i1.T==oktypes).sum()==0"; for (i=1; i<I; i++) { cout << " || (i" << i+1 << ".T==oktypes).sum()==0"; } cout << ")" << endl; cout << ind << "{" << endl; cout << ind+ind << "cerr << progstr+\": \" << __LINE__ << errstr << \"input data type must be in \" << \"{\";" << endl; cout << ind+ind << "for (auto o : oktypes) { cerr << int(o) << ((o==oktypes[oktypes.size()-1]) ? \"}\" : \",\"); }" << endl; cout << ind+ind << "cerr << endl; return 1;" << endl; cout << ind << "}" << endl; cout << endl; } //Get options while (line.compare(0,9,"//Get opt")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Get options" << endl; cout << endl; getline(ifs,line); while (line.compare(0,8,"//Checks")!=0) { getline(ifs,line); if (line.compare(0,6,"//Get ")==0) { while (line.size()>0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; } } //Checks while (line.compare(0,8,"//Checks")!=0) { getline(ifs,line); } getline(ifs,line); if (line.size()>0) { cout << endl; cout << ind << "//Checks" << endl; while (line.size()>0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; } //Set output headers if (O>0) { while (line.compare(0,14,"//Set output h")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Set output header info"; if (O>1) { cout << "s"; } cout << endl; getline(ifs,line); while (line.size()>0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; } //Open outputs cout << endl; cout << ind << "//Open output"; if (O>1) { cout << "s"; } cout << endl; for (o=0; o==0 || o<O; o++) { cout << ind << "if (wo" << o+1 << ")" << endl; cout << ind << "{" << endl; cout << ind+ind << "if (stdo" << o+1 << ") { ofs" << o+1 << ".copyfmt(cout); ofs" << o+1 << ".basic_ios<char>::rdbuf(cout.rdbuf()); } else { ofs" << o+1 << ".open(a_fo->filename[" << o << "]); }" << endl; cout << ind+ind << "if (!ofs" << o+1 << ") { cerr << progstr+\": \" << __LINE__ << errstr << \"problem opening output file " << o+1 << "\" << endl; return 1; }" << endl; cout << ind << "}" << endl; } cout << endl; //Write output hdrs if (O>0 && a_oh->count==0) { cout << endl; cout << ind << "//Write output header"; if (O>1) { cout << "s"; } cout << endl; for (o=0; o<O; o++) { cout << ind << "if (wo" << o+1 << " && !write_output_header(ofs" << o+1 << ",o" << o+1 << ")) { cerr << progstr+\": \" << __LINE__ << errstr << \"problem writing header for output file " << o+1 << "\" << endl; return 1; }" << endl; } cout << endl; } //Other prep while (line.compare(0,7,"//Other")!=0 && line.compare(0,9,"//Process")!=0) { getline(ifs,line); } if (line.compare(0,7,"//Other")==0) { cout << endl; cout << ind << "//Other prep" << endl; getline(ifs,line); while (line.size()==0) { cout << endl; getline(ifs,line); } while (line.compare(0,9,"//Process")!=0) { cout << ind << line << endl; getline(ifs,line); } } //Process start while (line.compare(0,9,"//Process")!=0) { getline(ifs,line); } cout << endl; cout << ind << "//Process" << endl; if (I>0 || O>0) { getline(ifs,line); cout << ind << line << endl; //Get t, ttstr and zi pos1 = line.find("=",0) + 2; pos2 = line.find(")",0); s2i = stoi(line.substr(pos1,pos2-pos1)); if (s2i<0) { cerr << progstr+": " << __LINE__ << errstr << "stoi returned negative int" << endl; return 1; } t = size_t(s2i); if (t!=oktypes[0]) { cerr << progstr+": " << __LINE__ << errstr << "type not member of oktypes" << endl; return 1; } if (t<4) { do_float = true; } else if (t<100) { do_int = true; } else { do_complex = true; } pos1 = line.find("(",0) + 1; pos2 = line.find("=",0); ttstr = line.substr(pos1,pos2-pos1); zi = zros.at(t); oi = ones.at(t); if (a_fire->count>0) { ai = aftyps.at(t); } //Do float blocks (and direct-sub int and complex blocks) t = 0; if (do_float) { tistr = typs.at(oktypes[t]); //Write tmpfile and first block getline(ifs,line); while (line.size()>0 && line.find("else if ("+ttstr+"==")==string::npos) { fputs((ind+line+"\n").c_str(),tmpf); if ((a_fl->count>0 || a_FL->count>0) && oktypes[0]==1) { n = 0; while ((n=line.find(fname,n))!=string::npos) { if (isupper(fname[1])) { line.replace(n,fname.size(),fname+"F"); } else { line.replace(n,fname.size(),fname+"f"); } n += fname.size() + 1; } } cout << ind << line << endl; getline(ifs,line); } //Check if extra int or complex block included if (line.size()>0) { if (line.find("else if ("+ttstr+"==8)")!=string::npos) { do_int = true; } else if (line.find("else if ("+ttstr+"==101)")!=string::npos) { do_complex = true; } else { cerr << progstr+": " << __LINE__ << errstr << "int case must be for data type 8, complex case must be for data type 101" << endl; return 1; } } else { do_int = do_complex = false; } //Write float blocks t++; while (t<T && (!do_int || int(oktypes[t])<4) && (!do_complex || int(oktypes[t])<100)) { cout << ind << "else if (" << ttstr << "==" << int(oktypes[t]) << ")" << endl; tcstr = typs.at(oktypes[t]); zc = zros.at(oktypes[t]); oc = ones.at(oktypes[t]); if (a_fire->count>0) { ac = aftyps.at(oktypes[t]); } rewind(tmpf); while (fgets(buff,256*16,tmpf)) { line = string(buff); n = 0; while ((n=line.find(tistr,n))!=string::npos) { line.replace(n,tistr.size(),tcstr); n += tcstr.size(); } n = 0; while ((n=line.find(zi,n))!=string::npos) { line.replace(n,zi.size(),zc); n += zc.size(); } n = 0; while ((n=line.find(oi,n))!=string::npos) { line.replace(n,oi.size(),oc); n += oc.size(); } if (a_fire->count>0) { n = 0; while ((n=line.find(ai,n))!=string::npos) { line.replace(n,ai.size(),ac); n += ac.size(); } } if ((a_fl->count>0 || a_FL->count>0) && oktypes[t]==3) { n = 0; while ((n=line.find(fname,n))!=string::npos) { if (isupper(fname[1])) { line.replace(n,fname.size(),fname+"L"); } else { line.replace(n,fname.size(),fname+"l"); } n += fname.size() + 1; } } if (a_dz->count>0 && oktypes[t]==2) { if ((n=line.find("blas_is",0))!=string::npos) { line.replace(n,7,"blas_id"); } else if ((n=line.find("blas_s",0))!=string::npos) { line.replace(n,6,"blas_d"); } else if (a_ov->count>0 && (n=line.find("_s(",0))!=string::npos) { line.replace(n,3,"_d("); } else if (a_ov->count>0 && (n=line.find("_s (",0))!=string::npos) { line.replace(n,4,"_d ("); } else if (a_ov->count>0 && (n=line.find("_s_",0))!=string::npos) { line.replace(n,3,"_d_"); } } if (a_arma->count>0 && oktypes[t]==2) { if ((n=line.find("fdatum",0))!=string::npos) { line.replace(n,6,"datum"); } } cout << line; } t++; } } //Do int blocks if (do_int) { tistr = typs.at(oktypes[t]); if (do_float) { cout << ind << "else if (" << ttstr << "==" << int(oktypes[t]) << ")" << endl; } else { t = 0; } //Write int tmpfile and first block getline(ifs,line); while (line.size()>0 && line.find("else if ("+ttstr+"==")==string::npos) { fputs((ind+line+"\n").c_str(),tmpf8); cout << ind << line << endl; getline(ifs,line); } //Check if extra complex block included if (line.size()>0) { if (line.find("else if ("+ttstr+"==101)")!=string::npos) { do_complex = true; } else { cerr << progstr+": " << __LINE__ << errstr << "complex case must be for data type 101" << endl; return 1; } } else { do_complex = false; } //Write int blocks t++; while (t<T && (!do_complex || int(oktypes[t])<100)) { cout << ind << "else if (" << ttstr << "==" << int(oktypes[t]) << ")" << endl; tcstr = typs.at(oktypes[t]); rewind(tmpf8); while (fgets(buff,256*16,tmpf8)) { line = string(buff); n = 0; while ((n=line.find(tistr,n))!=string::npos) { if (line.find(tistr+"*>",n)>line.size()) { line.replace(n,tistr.size(),tcstr); } n += tcstr.size(); } n = 0; while ((n=line.find(zi,n))!=string::npos) { line.replace(n,zi.size(),zc); n += zc.size(); } n = 0; while ((n=line.find(oi,n))!=string::npos) { line.replace(n,oi.size(),oc); n += oc.size(); } if (a_fire->count>0) { n = 0; while ((n=line.find(ai,n))!=string::npos) { line.replace(n,ai.size(),ac); n += ac.size(); } } cout << line; } t++; } } //Do complex blocks if (do_complex) { tistr = typs.at(oktypes[t]-100); if (do_float || do_int) { cout << ind << "else if (" << ttstr << "==" << int(oktypes[t]) << ")" << endl; } else { t = 0; } //Write complex tmpfile and first block getline(ifs,line); while (line.size()>0) { fputs((ind+line+"\n").c_str(),tmpf101); if (a_FL->count>0 && oktypes[t]==101) { n = 0; while ((n=line.find(fname,n))!=string::npos) { if (isupper(fname[1])) { line.replace(n,fname.size(),fname+"F"); } else { line.replace(n,fname.size(),fname+"f"); } n += fname.size() + 1; } } cout << ind << line << endl; getline(ifs,line); } //Write complex blocks t++; while (t<T) { cout << ind << "else if (" << ttstr << "==" << int(oktypes[t]) << ")" << endl; tcstr = typs.at(oktypes[t]-100); zc = zros.at(oktypes[t]); oc = ones.at(oktypes[t]); if (a_fire->count>0) { ac = aftyps.at(oktypes[t]); } rewind(tmpf101); while (fgets(buff,256*16,tmpf101)) { line = string(buff); n = 0; while ((n=line.find(tistr,n))!=string::npos) { line.replace(n,tistr.size(),tcstr); n += tcstr.size(); } n = 0; while ((n=line.find(zi,n))!=string::npos) { line.replace(n,zi.size(),zc); n += zc.size(); } n = 0; while ((n=line.find(oi,n))!=string::npos) { line.replace(n,oi.size(),oc); n += oc.size(); } if (a_fire->count>0) { n = 0; while ((n=line.find(ai,n))!=string::npos) { line.replace(n,ai.size(),ac); n += ac.size(); } } if (a_FL->count>0 && oktypes[t]==103) { n = 0; while ((n=line.find(fname,n))!=string::npos) { if (isupper(fname[1])) { line.replace(n,fname.size(),fname+"L"); } else { line.replace(n,fname.size(),fname+"l"); } n += fname.size() + 1; } } if (a_dz->count>0 && oktypes[t]==102) { if ((n=line.find("blas_csca",0))!=string::npos) { line.replace(n,9,"blas_zsca"); } else if ((n=line.find("blas_css",0))!=string::npos) { line.replace(n,8,"blas_zds"); } else if ((n=line.find("blas_csy",0))!=string::npos) { line.replace(n,8,"blas_zsy"); } else if ((n=line.find("blas_scc",0))!=string::npos) { line.replace(n,8,"blas_dzc"); } else if ((n=line.find("blas_scs",0))!=string::npos) { line.replace(n,8,"blas_dzs"); } else if ((n=line.find("blas_sc",0))!=string::npos) { line.replace(n,7,"blas_dz"); } else if ((n=line.find("blas_cs",0))!=string::npos) { line.replace(n,7,"blas_zd"); } else if ((n=line.find("blas_ic",0))!=string::npos) { line.replace(n,7,"blas_iz"); } else if ((n=line.find("blas_c",0))!=string::npos) { line.replace(n,6,"blas_z"); } else if (a_ov->count>0 && (n=line.find("_c(",0))!=string::npos) { line.replace(n,3,"_z("); } else if (a_ov->count>0 && (n=line.find("_c (",0))!=string::npos) { line.replace(n,4,"_z ("); } else if (a_ov->count>0 && (n=line.find("_c_",0))!=string::npos) { line.replace(n,3,"_z_"); } } if (a_arma->count>0 && oktypes[t]==102) { if ((n=line.find("fdatum",0))!=string::npos) { line.replace(n,6,"datum"); } } cout << line; } t++; } } //Write else clause cout << ind << "else" << endl; cout << ind << "{" << endl; cout << ind << ind << "cerr << progstr+\": \" << __LINE__ << errstr << \"data type not supported\" << endl; return 1;" << endl; cout << ind << "}" << endl; } if (a_t->count>0) { cout << ind << "clock_gettime(CLOCK_REALTIME,&toc);" << endl; cout << ind << "cerr << \"elapsed time = \" << (toc.tv_sec-tic.tv_sec)*1e3 + (toc.tv_nsec-tic.tv_nsec)/1e6 << \" ms\" << endl;" << endl; } cout << ind << endl; //Finish while (line.compare(0,8,"//Finish")!=0) { getline(ifs,line); } getline(ifs,line); if (line.size()>0) { cout << endl; cout << ind << "//Finish" << endl; while (line.size()>0) { cout << ind << line << endl; getline(ifs,line); } cout << endl; } //Exit cout << endl; cout << ind << "//Exit" << endl; if (a_T->count>0) { cout << ind << "clock_gettime(CLOCK_REALTIME,&toc);" << endl; cout << ind << "cerr << \"elapsed time = \" << (toc.tv_sec-tic.tv_sec)*1e3 + (toc.tv_nsec-tic.tv_nsec)/1e6 << \" ms\" << endl;" << endl; } cout << ind << "return ret;" << endl; cout << "}" << endl; cout << endl; //Return return ret; }
b061f8137dbc212156df5b592ce9b676121f27d2
e4f8c1b113ecf1ccfb8c0218cffe07bc81d79440
/components/inversekinematics/src/bodypart.h
39837a93a6e3e403b6b45aae688889dff8ae3a30
[]
no_license
robocomp/robocomp-shelly
a5e3a9e9ef71401b63749310eb15a5c1dfdbcef4
b23d5e19336521232386fe52a7a9f11d81a9f02e
refs/heads/master
2020-12-11T05:23:50.447797
2020-01-22T16:22:01
2020-01-22T16:22:01
19,778,519
1
3
null
null
null
null
UTF-8
C++
false
false
1,298
h
bodypart.h
/* ------------------------------------------------------------------ * CLASS BODY PART * IT REPRESETS ONE PART OF THE ROBOT. WE DIVIDE THE ROBOT IN THREE * DIFERENT PARTS: * -----> RIGHT ARM: IT'S COMPOSED BY ALL THE MOTORS OF THE RIGHT ARM * -----> LEFT ARM: IT'S COMPOSED BY ALL THE MOTORS OF THE LEFT ARM * -----> HEAD: IT'S COMPOSED BY ALL THE MOTORS OF THE ROBOT'S HEAD * * ONE PART OF THE ROBOT HAS ALWAYS: * - THE NAME OF THE PART. * - THE LIST OF PART'S MOTORS. * - THE NAME OF THE TIP. * - THE LIST OF TARGETS THAT MUST BE EXECUTED * ------------------------------------------------------------------*/ #ifndef BODYPART_H #define BODYPART_H #include <iostream> #include <QString> #include <QStringList> #include "target.h" using namespace std; class BodyPart { public: BodyPart (QString partName_, QString tipName_, QStringList motorList_); BodyPart (); ~BodyPart (); QString getPartName (); QString getTipName (); QStringList getMotorList (); QQueue<Target> &getTargetList (); void removeTarget (); void addTargetToList (Target &target); void reset (); private: QString partName; QString tipName; QStringList motorList; QQueue<Target> targetList; //QQueue<Target> solvedList; int counter; }; #endif // BODYPART_H
caccca9a123f49eebcc90cdaf6625920ad99f7cc
fa8a54ca27416ade31ca121cfe573f58502b6048
/client/client/gui/ContinueOptionsBackButtonBar.h
78b77dba1d08a4ffebe044d786fc8b18736722d2
[]
no_license
DasElias/MauMau
f2c1d244fadaa145b6f7e212fb2829d90f25cadf
b91d0a29978c80d2411f9dfcfab244864b91cfe8
refs/heads/master
2022-05-29T09:42:33.664885
2020-04-26T15:38:18
2020-04-26T15:38:18
234,632,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,506
h
ContinueOptionsBackButtonBar.h
#pragma once #include <egui/model/nodes/HBox.h> #include "ColoredButton.h" namespace card { class ContinueOptionsBackButtonBar : public egui::HBox { // ---------------------------------------------------------------------- // --------------------------------FIELDS-------------------------------- // ---------------------------------------------------------------------- private: std::shared_ptr<ColoredButton> backBtn; std::shared_ptr<ColoredButton> optionsBtn; std::shared_ptr<ColoredButton> continueBtn; // ---------------------------------------------------------------------- // -----------------------------CONSTRUCTORS----------------------------- // ---------------------------------------------------------------------- public: ContinueOptionsBackButtonBar(std::string backText, std::string optionsText, std::string continueText); // ---------------------------------------------------------------------- // -------------------------------METHODS-------------------------------- // ---------------------------------------------------------------------- public: void addBackBtnEventHandler(egui::FunctionWrapper<egui::ActionEvent> handler); void addOptionsBtnEventHandler(egui::FunctionWrapper<egui::ActionEvent> handler); void addContinueBtnEventHandler(egui::FunctionWrapper<egui::ActionEvent> handler); }; }
6d7372bde6cd9ce0cc38ebd634cd63f6e5029d22
c296c81507494483c278e50c8c88dd1b36c5bdc4
/Datas/CEpargne.h
2cd3f1b7b952e3d947a5457fb5cfb759882e6439
[]
no_license
Stroff/Amonsoft
4278839f932032b6b90455ec241444e7cb00768f
5a8e464951aeafb9e04c990845abc4e83ed5d240
refs/heads/master
2021-01-25T04:01:59.383581
2012-03-31T10:06:22
2012-03-31T10:06:22
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,346
h
CEpargne.h
/* * This software is a part to the amonsoft solution * * Copyright Amon & Sesam Micro * Developper contact pascal.bart@sesam-micro.Fr * * $Id: CEpargne.h,v 1.10 2006/04/29 16:29:28 pascal Exp $ * $Log: CEpargne.h,v $ * Revision 1.10 2006/04/29 16:29:28 pascal * Version 0.1 build 13 * - Correction d'un bug avec les listes 'static' qui étaient partagées * - Suppression des boutons "Valider" & "Rester" * - Modification des images des boutons * - Personnes et Entreprises ne sont plus manipulé que par Id * - Correction de bug : suppression de la liste des retraites * - Réactivation de la sauvegarde manuel et correction des bugs qui ont conduit à sa désactivation * * Revision 1.9 2006/04/21 00:08:16 pascal * Version 0.1.12 * * - correction du problème liée au reset des listes dynamique. * - CPersonne ne crée par forcémment un CFamille (à surveiller !) * - nouvelle image pour les prospects * - correction bugs mineurs * * Revision 1.8 2006/03/21 10:42:16 pascal * *** empty log message *** * * Revision 1.7 2006/01/20 13:18:44 pascal * Version 1.0.8b * - Modifications graphiques et moteurs à tout va, afin de correspondre au mieux aux exigences du client * - Le double clique sur les listes permet désormais de modifier le contenus du champs correspondant * - Grosses modifications des fichiers de données * * Revision 1.6 2005/11/12 15:04:55 pascal * Mise à niveau ... * * Revision 1.5 2005/10/14 08:41:11 pascal * - correction d'un bogue lors de la lecture du fichier XML : Un élément vide était ajouté * * Revision 1.4 2005/10/12 16:11:21 pascal * - implementation des fonctions loadFromXerces des classes CPersonnes * * - bug: ajout de CPrevoyance dans CPersonnes * * Revision 1.3 2005/10/11 22:53:57 pascal * - CPersonnes peut lire depuis le XML ses données * - CConseillers aussi * - CEpargnes en cours ! * * Revision 1.2 2005/10/11 08:12:16 pascal * - nouvelle CEntreprise dans les nouveaux fichiers CEntreprise.* * - les classes de données n'héritent plus de CDatas à part CPersonne et CEntreprise * - les fonctions liées à QT sont toutes implémentées * - les fonctions saveToXML sont implémentées pour les particuliers * * Revision 1.1 2005/10/05 17:14:23 pascal * - nouvelle structure de données pour stocker les informations sur l'épargne * - résolution du problème lié à l'épouse : méthodes surchargées avec un bool supplémentaire permettant de savoir à qui l'on a à faire dans CPersonne et dans CRevenus. * - loadInQT implémenté pour toutes les classes * * */ #ifndef _CEPARGNE_H_ # define _CEPARGNE_H_ // QT #include <qdatetime.h> // STL #include <list> #include "defines.h" #include "CDatas.h" #include "Preferences/CPreferences.h" namespace Datas { typedef enum { eLoiMadelin, eArt83, eArt82, ePerp, ePerco, eArt39, eIFC, eAutreRetraite } t_eTypeEpargne; struct SEpargne { t_eTypeEpargne eType_; QDate dEffet_; uint uInvAnnuel_; uint uEpargne_; QDate dEpargne_; QString sContrat_; struct Preferences::SCompagnie *pCompagnie_; }; typedef std::list< struct Datas::SEpargne* > t_listEpargnes; struct SAssuranceVie { QString sContrat_; struct Preferences::SCompagnie *pCompagnie_; QDate dEffet_; uint uInvAnnuel_; QString sTerme_; uint uCapital_; QDate dCapital_; uint uDSK_; uint uPEP_; uint uMS_; uint uFD_; }; typedef std::list< struct Datas::SAssuranceVie* > t_listAssurancesVie; typedef enum { eCodevi, ePEL, eCEL, eSICAV, eObligations, eActions, ePEA, ePEP, eOPCVM } t_eTypeCompte; struct SComptes { t_eTypeCompte eType_; struct Preferences::SCompagnie *pCompagnie_; QDate dEffet_; uint uInvAnnuel_; QString sTerme_; uint uCapital_; QDate dCapital_; ushort usRendement_; QString sNotes_; }; typedef std::list< struct Datas::SComptes* > t_listComptes; struct SRevenus { QString sDesignation_; uint uMontant_; }; typedef std::list< struct Datas::SRevenus* > t_listRevenus; typedef std::list< struct Datas::SRevenus* > t_listCharges; class CEpargnes { enum eTypeMotivations { eFiscalite, eDisponibilite, eSecurite, eRentabilite }; public: // Constructor CEpargnes() { uSensibilite_ = 0; listEpargnes_.empty(); listAssurancesVie_.empty(); listComptes_.empty(); listRevenus_.empty(); listCharges_.empty(); } // Destructor ~CEpargnes() {} public: // CDatas virtual functions int loadFromXML( XERCES_CPP_NAMESPACE::DOMNode *xmlNode ); int saveToXML( XERCES_CPP_NAMESPACE::DOMDocument *xmlNode, XERCES_CPP_NAMESPACE::DOMElement * ) const; // Graphical functions virtual void loadInQT( dlgAmonSoft & ) const; virtual void copyFromQT( const dlgAmonSoft & ); void setSensibilite( uint val ) { uSensibilite_ = val; } public: static QString typeEpargneToString( t_eTypeEpargne type ); static QString typeCompteToString( t_eTypeCompte type ); public: t_listEpargnes listEpargnes_; t_listAssurancesVie listAssurancesVie_; t_listComptes listComptes_; t_listRevenus listRevenus_; t_listCharges listCharges_; private: uint uSensibilite_; enum eTypeMotivations eMotivation1_; enum eTypeMotivations eMotivation2_; enum eTypeMotivations eMotivation3_; enum eTypeMotivations eMotivation4_; private: // XML sub functions void getXMLListRetraites( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); void getXMLListMotivations( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); void getXMLListAssuranceVies( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); void getXMLListComptes( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); void getXMLListRevenus( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); void getXMLListCharges( XERCES_CPP_NAMESPACE::DOMNode *ptNode ); }; } #endif /* _CEPARGNE_H_ */
a13b82682696411f25665e9acf00341ccc39846e
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/python/detail/force_instantiate.hpp
77a69a115ae70e4a8fdb849223d1c4d095a768b2
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
77
hpp
force_instantiate.hpp
#include "thirdparty/boost_1_58_0/boost/python/detail/force_instantiate.hpp"
7990522b0387c257a97cd7d0646fb15179a90030
b0069cfa317b9281f064a7fbd9d1463c33ee1ac4
/Firestore/core/src/local/remote_document_cache.h
bfe84648c9310882f5ed31deb90ef9e46e1c955a
[ "Swift-exception", "MIT", "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
firebase/firebase-ios-sdk
5bb2b5ef2be28c993e993517059452ddb8bee1e6
1dc90cdd619c5e8493df4a01138e2d87e61bc027
refs/heads/master
2023-08-29T23:15:28.905909
2023-08-29T21:49:41
2023-08-29T21:49:41
89,033,556
5,048
1,594
Apache-2.0
2023-09-14T21:11:30
2017-04-22T00:26:50
Objective-C
UTF-8
C++
false
false
5,922
h
remote_document_cache.h
/* * Copyright 2018 Google * * 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 FIRESTORE_CORE_SRC_LOCAL_REMOTE_DOCUMENT_CACHE_H_ #define FIRESTORE_CORE_SRC_LOCAL_REMOTE_DOCUMENT_CACHE_H_ #include <string> #include "Firestore/core/src/model/document_key.h" #include "Firestore/core/src/model/model_fwd.h" #include "Firestore/core/src/model/overlay.h" namespace firebase { namespace firestore { namespace core { class Query; } // namespace core namespace local { class IndexManager; class QueryContext; /** * Represents cached documents received from the remote backend. * * The cache is keyed by DocumentKey and entries in the cache are MaybeDocument * instances, meaning we can cache both Document instances (an actual document * with data) as well as DeletedDocument instances (indicating that the document * is known to not exist). */ class RemoteDocumentCache { public: virtual ~RemoteDocumentCache() = default; /** * Adds or replaces an entry in the cache. * * The cache key is extracted from `document.key`. If there is already a cache * entry for the key, it will be replaced. * * @param document A Document or DeletedDocument to put in the cache. * @param read_time The time at which the document was read or committed. */ virtual void Add(const model::MutableDocument& document, const model::SnapshotVersion& read_time) = 0; /** Removes the cached entry for the given key (no-op if no entry exists). */ virtual void Remove(const model::DocumentKey& key) = 0; /** * Looks up an entry in the cache. * * @param key The key of the entry to look up. * @return The cached Document or DeletedDocument entry, or nullopt if we * have nothing cached. */ virtual model::MutableDocument Get(const model::DocumentKey& key) const = 0; /** * Looks up a set of entries in the cache. * * @param keys The keys of the entries to look up. * @return The cached Document or NoDocument entries indexed by key. If an * entry is not cached, the corresponding key will be mapped to a null value. */ virtual model::MutableDocumentMap GetAll( const model::DocumentKeySet& keys) const = 0; /** * Looks up the next "limit" number of documents for a collection group based * on the provided offset. The ordering is based on the document's read time * and key. * * @param collection_group The collection group to scan. * @param offset The offset to start the scan at. * @param limit The maximum number of results to return. * @return A newly created map with next set of documents. */ virtual model::MutableDocumentMap GetAll(const std::string& collection_group, const model::IndexOffset& offset, size_t limit) const = 0; /** * Executes a query against the cached Document entries * * Implementations may return extra documents if convenient. The results * should be re-filtered by the consumer before presenting them to the user. * * Cached DeletedDocument entries have no bearing on query results. * * @param query The query to match documents against. * @param offset The read time and document key to start scanning at * (exclusive). * @param limit The maximum number of results to return. * If the limit is not defined, returns all matching documents. * @param mutated_docs The documents with local mutations, they are read * regardless if the remote version matches the given query. * @return The set of matching documents. */ virtual model::MutableDocumentMap GetDocumentsMatchingQuery( const core::Query& query, const model::IndexOffset& offset, absl::optional<size_t> limit = absl::nullopt, const model::OverlayByDocumentKeyMap& mutated_docs = {}) const = 0; /** * Executes a query against the cached Document entries * * Implementations may return extra documents if convenient. The results * should be re-filtered by the consumer before presenting them to the user. * * Cached DeletedDocument entries have no bearing on query results. * * @param query The query to match documents against. * @param offset The read time and document key to start scanning at * (exclusive). * @param context A optional tracker to keep a record of important details * during database local query execution. * @param limit The maximum number of results to return. * If the limit is not defined, returns all matching documents. * @param mutated_docs The documents with local mutations, they are read * regardless if the remote version matches the given query. * @return The set of matching documents. */ virtual model::MutableDocumentMap GetDocumentsMatchingQuery( const core::Query& query, const model::IndexOffset& offset, absl::optional<QueryContext>& context, absl::optional<size_t> limit = absl::nullopt, const model::OverlayByDocumentKeyMap& mutated_docs = {}) const = 0; /** * Sets the index manager used by remote document cache. * * @param manager A pointer to an `IndexManager` owned by `Persistence`. */ virtual void SetIndexManager(IndexManager* manager) = 0; }; } // namespace local } // namespace firestore } // namespace firebase #endif // FIRESTORE_CORE_SRC_LOCAL_REMOTE_DOCUMENT_CACHE_H_
f99b27fd99d73da7febc865a674b464e3add34cd
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Trigger/TrigHypothesis/TrigHLTJetHypo/src/TrigJetHypoToolConfig_partgen.h
d814d785adacf868c27913695a190accc8d8d581
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
2,034
h
TrigJetHypoToolConfig_partgen.h
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef TRIGJETHYPOTOOLConfig_PARTGEN_H #define TRIGJETHYPOTOOLConfig_PARTGEN_H /******************************************************************** * * NAME: TrigJetHypoToolConfig_partgen.h * PACKAGE: Trigger/TrigHypothesis/TrigHLTJetHypo * * *********************************************************************/ #include "ITrigJetHypoToolConfig.h" #include "./ConditionsDefsMT.h" #include "TrigCompositeUtils/HLTIdentifier.h" #include "AthenaBaseComps/AthAlgTool.h" #include "TrigCompositeUtils/TrigCompositeUtils.h" #include "AthenaMonitoringKernel/GenericMonitoringTool.h" #include "TrigHLTJetHypo/ITrigJetHypoToolHelperMT.h" #include "./ConditionsDefsMT.h" #include "./ITrigJetConditionConfig.h" #include "TrigHLTJetHypo/TrigHLTJetHypoUtils/ICleaner.h" #include "TrigHLTJetHypo/TrigHLTJetHypoUtils/IJetGrouper.h" class TrigJetHypoToolConfig_partgen: public extends<AthAlgTool, ITrigJetHypoToolConfig> { public: TrigJetHypoToolConfig_partgen(const std::string& type, const std::string& name, const IInterface* parent); virtual ~TrigJetHypoToolConfig_partgen(); virtual StatusCode initialize() override; virtual std::vector<std::shared_ptr<ICleaner>> getCleaners() const override; virtual std::unique_ptr<IJetGrouper> getJetGrouper() const override; virtual std::unique_ptr<IGroupsMatcherMT> getMatcher() const override; virtual std::optional<ConditionsMT> getConditions() const override; virtual std::size_t requiresNJets() const override; private: ToolHandleArray<ITrigJetConditionConfig> m_conditionMakers{ this, "conditionMakers", {}, "conditions makers for a leaf node."}; Gaudi::Property<unsigned int> m_size{this, "groupSize", {}, "Jet group size"}; ToolHandleArray<ITrigJetHypoToolHelperMT> m_children { this, "children", {}, "list of child jet hypo helpers"}; virtual StatusCode checkVals() const override; }; #endif
b1489392727399151bc416c679e8804a001c6bc0
0f4bd413d54f58f1d50479f554a978b06063d4de
/Project1/ItemPlatform.cpp
93bd56f9d1dcc9bedc241c252d58963f56a2f60c
[]
no_license
Mucchan-ko/Sparty-Gnome
4506e70de3ca3692c623032ced4d365c9041a03c
f890cf1d6c47c7a72549dda6b4916d9b76c5e11e
refs/heads/main
2023-06-26T21:39:21.496176
2021-07-06T22:26:50
2021-07-06T22:26:50
383,610,472
0
0
null
2021-07-06T22:26:50
2021-07-06T22:18:29
null
UTF-8
C++
false
false
1,906
cpp
ItemPlatform.cpp
/** * \file ItemPlatform.cpp * * \author Trent Belanger */ #include "pch.h" #include <string> #include "ItemPlatform.h" using namespace Gdiplus; using namespace std; /** Constructor * \param game game this object is a part of * \param declarations vector of wstring image files * \param width width of platform object * \param height height of platform object */ CItemPlatform::CItemPlatform(CGame* game, std::vector<std::wstring> declarations, int width, int height) : CItemObstacle(game, declarations[1], width, height) { for (auto image : declarations) { auto itemImage = unique_ptr<Bitmap>(Bitmap::FromFile(image.c_str())); if (itemImage->GetLastStatus() != Ok) { wstring msg(L"Failed to open "); msg += image; AfxMessageBox(msg.c_str()); } mImages.push_back(move(itemImage)); } } /** * Draw our item * \param graphics The graphics context to draw on */ void CItemPlatform::Draw(Gdiplus::Graphics* graphics) { // calculate position of leftmost x position int x = GetX() - (mWidth / 2); // draw left endcap graphics->DrawImage(mImages[0].get(), float(x), float(GetY() - mImages[0]->GetHeight() / 2), (float)mImages[0]->GetWidth(), (float)mImages[0]->GetHeight()); x += 32; // draw middle platform images until right end while (x < (GetX() - 32) + (mWidth / 2)) { graphics->DrawImage(mImages[1].get(), float(x), float(GetY() - mImages[1]->GetHeight() / 2), (float)mImages[1]->GetWidth(), (float)mImages[1]->GetHeight()); x += 32; } // draw right endcap graphics->DrawImage(mImages[2].get(), float(x), float(GetY() - mImages[2]->GetHeight() / 2), (float)mImages[2]->GetWidth(), (float)mImages[2]->GetHeight()); }
51a455a89e4c067e906e871162e3b0804ff41ce2
ce778fa316bfbdb4ee5ee8b0c4f4a8d885e3213e
/sem2/AsmStart/AsmStart/AsmStart.cpp
2f897c986d3e68f72703ca3b7c734056da9adf7a
[]
no_license
Bakhar17/Artem
1dc6ff5970db41630937712deda184eba0d54d28
121a84ea94fc798c4e68b0f54c8b3a6df3056570
refs/heads/master
2023-02-01T19:27:55.348219
2020-12-22T20:25:53
2020-12-22T20:25:53
203,357,473
2
0
null
null
null
null
UTF-8
C++
false
false
949
cpp
AsmStart.cpp
#include <iostream> int main() { //int a, b,res; //std::cout << "Put a: "; //std::cin >> a; //std::cout << "Put b: "; //std::cin >> b; //__asm { // mov eax, b // neg eax // cdq // idiv a // mov res,eax //} //std::cout << "x= " << res; //int s, x, z,res; //std::cout << "Put s: "; //std::cin >> s; //std::cout << "Put x: "; //std::cin >> x; //std::cout << "Put z: "; //std::cin >> z; //__asm { // mov eax,s // mul z // neg eax // add eax,x // mul s // mov ebx,x // imul ebx,z // add ebx,s // cdq // idiv ebx // mov res,eax //} //std::cout << "Result:" << res; int res;//50=2x+3y __asm { mov ebx, 1 start: mov eax, 50 imul ebx, 3 sub eax, ebx mov ecx, 0 cmp eax, 0 jg greater jl finish je finish greater : test eax, 1 je cont jz stop stop : add ecx, 1 add ebx, 1 jmp start cont : add ebx, 1 jmp start finish : mov res, ecx } std::cout << res; }
394eab045d821939c02576482d6f2a34b9d351fa
f1ee65fbe1ffc43c2aac45e41515f1987eb534a4
/src/net/third_party/quiche/src/quiche/quic/core/quic_flow_controller.cc
4acdd513f3f7ea37a5a4e7f409022abdba59b35e
[ "BSD-3-Clause" ]
permissive
klzgrad/naiveproxy
6e0d206b6f065b9311d1e12b363109f2d35cc058
8ef1cecadfd4e2b5d57e7ea2fa42d05717e51c2e
refs/heads/master
2023-08-20T22:42:12.511091
2023-06-04T03:54:34
2023-08-16T23:30:19
119,178,893
5,710
976
BSD-3-Clause
2023-08-05T10:59:59
2018-01-27T16:02:33
C++
UTF-8
C++
false
false
11,867
cc
quic_flow_controller.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/quic/core/quic_flow_controller.h" #include <cstdint> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") std::string QuicFlowController::LogLabel() { if (is_connection_flow_controller_) { return "connection"; } return absl::StrCat("stream ", id_); } QuicFlowController::QuicFlowController( QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller) : session_(session), connection_(session->connection()), id_(id), is_connection_flow_controller_(is_connection_flow_controller), perspective_(session->perspective()), bytes_sent_(0), send_window_offset_(send_window_offset), bytes_consumed_(0), highest_received_byte_offset_(0), receive_window_offset_(receive_window_offset), receive_window_size_(receive_window_offset), receive_window_size_limit_(receive_window_size_limit), auto_tune_receive_window_(should_auto_tune_receive_window), session_flow_controller_(session_flow_controller), last_blocked_send_window_offset_(0), prev_window_update_time_(QuicTime::Zero()) { QUICHE_DCHECK_LE(receive_window_size_, receive_window_size_limit_); QUICHE_DCHECK_EQ( is_connection_flow_controller_, QuicUtils::GetInvalidStreamId(session_->transport_version()) == id_); QUIC_DVLOG(1) << ENDPOINT << "Created flow controller for " << LogLabel() << ", setting initial receive window offset to: " << receive_window_offset_ << ", max receive window to: " << receive_window_size_ << ", max receive window limit to: " << receive_window_size_limit_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " consumed " << bytes_consumed_ << " bytes."; MaybeSendWindowUpdate(); } bool QuicFlowController::UpdateHighestReceivedOffset( QuicStreamOffset new_offset) { // Only update if offset has increased. if (new_offset <= highest_received_byte_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " highest byte offset increased from " << highest_received_byte_offset_ << " to " << new_offset; highest_received_byte_offset_ = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { QUIC_BUG(quic_bug_10836_1) << ENDPOINT << LogLabel() << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; // This is an error on our side, close the connection as soon as possible. connection_->CloseConnection( QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, absl::StrCat(send_window_offset_ - (bytes_sent_ + bytes_sent), "bytes over send window offset"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } bytes_sent_ += bytes_sent; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " sent " << bytes_sent_ << " bytes."; } bool QuicFlowController::FlowControlViolation() { if (highest_received_byte_offset_ > receive_window_offset_) { QUIC_DLOG(INFO) << ENDPOINT << "Flow control violation on " << LogLabel() << ", receive window offset: " << receive_window_offset_ << ", highest received byte offset: " << highest_received_byte_offset_; return true; } return false; } void QuicFlowController::MaybeIncreaseMaxWindowSize() { // Core of receive window auto tuning. This method should be called before a // WINDOW_UPDATE frame is sent. Ideally, window updates should occur close to // once per RTT. If a window update happens much faster than RTT, it implies // that the flow control window is imposing a bottleneck. To prevent this, // this method will increase the receive window size (subject to a reasonable // upper bound). For simplicity this algorithm is deliberately asymmetric, in // that it may increase window size but never decreases. // Keep track of timing between successive window updates. QuicTime now = connection_->clock()->ApproximateNow(); QuicTime prev = prev_window_update_time_; prev_window_update_time_ = now; if (!prev.IsInitialized()) { QUIC_DVLOG(1) << ENDPOINT << "first window update for " << LogLabel(); return; } if (!auto_tune_receive_window_) { return; } // Get outbound RTT. QuicTime::Delta rtt = connection_->sent_packet_manager().GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { QUIC_DVLOG(1) << ENDPOINT << "rtt zero for " << LogLabel(); return; } // Now we can compare timing of window updates with RTT. QuicTime::Delta since_last = now - prev; QuicTime::Delta two_rtt = 2 * rtt; if (since_last >= two_rtt) { // If interval between window updates is sufficiently large, there // is no need to increase receive_window_size_. return; } QuicByteCount old_window = receive_window_size_; IncreaseWindowSize(); if (receive_window_size_ > old_window) { QUIC_DVLOG(1) << ENDPOINT << "New max window increase for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. max wndw: " << receive_window_size_; if (session_flow_controller_ != nullptr) { session_flow_controller_->EnsureWindowAtLeast( kSessionFlowControlMultiplier * receive_window_size_); } } else { // TODO(ckrasic) - add a varz to track this (?). QUIC_LOG_FIRST_N(INFO, 1) << ENDPOINT << "Max window at limit for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. Limit size: " << receive_window_size_; } } void QuicFlowController::IncreaseWindowSize() { receive_window_size_ *= 2; receive_window_size_ = std::min(receive_window_size_, receive_window_size_limit_); } QuicByteCount QuicFlowController::WindowUpdateThreshold() { return receive_window_size_ / 2; } void QuicFlowController::MaybeSendWindowUpdate() { if (!session_->connection()->connected()) { return; } // Send WindowUpdate to increase receive window if // (receive window offset - consumed bytes) < (max window / 2). // This is behaviour copied from SPDY. QUICHE_DCHECK_LE(bytes_consumed_, receive_window_offset_); QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; QuicByteCount threshold = WindowUpdateThreshold(); if (!prev_window_update_time_.IsInitialized()) { // Treat the initial window as if it is a window update, so if 1/2 the // window is used in less than 2 RTTs, the window is increased. prev_window_update_time_ = connection_->clock()->ApproximateNow(); } if (available_window >= threshold) { QUIC_DVLOG(1) << ENDPOINT << "Not sending WindowUpdate for " << LogLabel() << ", available window: " << available_window << " >= threshold: " << threshold; return; } MaybeIncreaseMaxWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } void QuicFlowController::UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window) { // Update our receive window. receive_window_offset_ += (receive_window_size_ - available_window); QUIC_DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for " << LogLabel() << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << WindowUpdateThreshold() << ", and receive window size: " << receive_window_size_ << ". New receive window offset is: " << receive_window_offset_; SendWindowUpdate(); } void QuicFlowController::MaybeSendBlocked() { if (SendWindowSize() != 0 || last_blocked_send_window_offset_ >= send_window_offset_) { return; } QUIC_DLOG(INFO) << ENDPOINT << LogLabel() << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; // The entire send_window has been consumed, we are now flow control // blocked. // Keep track of when we last sent a BLOCKED frame so that we only send one // at a given send offset. last_blocked_send_window_offset_ = send_window_offset_; session_->SendBlocked(id_, last_blocked_send_window_offset_); } bool QuicFlowController::UpdateSendWindowOffset( QuicStreamOffset new_send_window_offset) { // Only update if send window has increased. if (new_send_window_offset <= send_window_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << "UpdateSendWindowOffset for " << LogLabel() << " with new offset " << new_send_window_offset << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; // The flow is now unblocked but could have also been unblocked // before. Return true iff this update caused a change from blocked // to unblocked. const bool was_previously_blocked = IsBlocked(); send_window_offset_ = new_send_window_offset; return was_previously_blocked; } void QuicFlowController::EnsureWindowAtLeast(QuicByteCount window_size) { if (receive_window_size_limit_ >= window_size) { return; } QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; IncreaseWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64_t QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } void QuicFlowController::UpdateReceiveWindowSize(QuicStreamOffset size) { QUICHE_DCHECK_LE(size, receive_window_size_limit_); QUIC_DVLOG(1) << ENDPOINT << "UpdateReceiveWindowSize for " << LogLabel() << ": " << size; if (receive_window_size_ != receive_window_offset_) { QUIC_BUG(quic_bug_10836_2) << "receive_window_size_:" << receive_window_size_ << " != receive_window_offset:" << receive_window_offset_; return; } receive_window_size_ = size; receive_window_offset_ = size; } void QuicFlowController::SendWindowUpdate() { QuicStreamId id = id_; if (is_connection_flow_controller_) { id = QuicUtils::GetInvalidStreamId(connection_->transport_version()); } session_->SendWindowUpdate(id, receive_window_offset_); } } // namespace quic
fd02d4691c5461871f3ed08a3741be9bae32a432
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.004/p_rgh
476e0305a2b45d79d71eba89b7bc20543b5076eb
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
7,728
p_rgh
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.004"; object p_rgh; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 545 ( -7.52336e+07 -1.39997e+07 -2.01036e+06 -2.60112e+06 -8.20532e+06 5.38877e+07 -2.96323e+06 -2.34818e+06 -2.4976e+06 -6.70784e+06 9.38076e+07 3.22688e+06 -490595 -554680 -7.02882e+06 5.43598e+07 -3.13576e+06 -1.90953e+06 -296234 -6.30134e+06 -8.65329e+07 -2.3782e+06 -584773 3.78687e+06 1.07995e+07 -6.79323e+06 -1.89687e+06 -908273 -267860 -183560 -157705 -181029 -184132 -200450 -196862 -205186 -199003 -202842 -195746 -196571 -189814 -188809 -183223 -181308 -176857 -173803 -169906 -164923 -160642 -152446 -146522 -133802 -126029 -109134 -101063 -81858.3 -74996.3 -55045.7 -49581.8 -31108.2 -28000.6 -14852.9 -15109 -10354.5 -12673.4 -15489.5 -14145.3 -21712.2 -19688 -40967.3 -6.0054e+06 -1.26007e+06 -866754 -386717 -277404 -218281 -201887 -200587 -201498 -204195 -204153 -204591 -202321 -200378 -196689 -193502 -189465 -186139 -182431 -179014 -175306 -171333 -166899 -161402 -155049 -146502 -137014 -124935 -112873 -98887.1 -86162 -72080.5 -59728.8 -46180.6 -35491.5 -24803.2 -18175.3 -13049.8 -12090.5 -12882.7 -14944.6 -16615.4 -16364.7 -16673.7 -3439.82 -7.01343e+06 -713206 -604566 -263698 -251959 -211967 -205886 -199440 -205358 -202765 -206869 -203350 -204423 -199494 -198407 -193112 -190789 -186100 -183319 -179153 -175715 -171716 -166982 -162209 -154829 -147738 -136345 -126498 -111517 -100791 -84268.1 -74428.6 -57632.2 -48570.7 -33354.1 -26954.5 -16595.4 -14523.3 -11468.1 -13410.8 -15752.3 -15690.8 -17334.8 -14583.2 -24933.6 -7.4121e+06 374051 -63996.2 -50946.9 -179528 -194708 -195082 -201557 -201720 -206020 -203922 -205801 -202098 -201385 -196870 -194572 -189852 -187008 -182796 -179403 -175457 -171464 -167230 -161535 -155729 -146561 -137901 -124632 -113571 -98060 -86948.1 -71375.2 -60850.1 -45317.2 -36617.5 -24251.7 -19327.3 -12820.7 -12942.4 -13361.3 -15290.9 -17267.3 -14656.3 -11466 9321.37 -1.87368e+06 2.8648e+06 856186 144860 -137492 -178467 -196608 -199236 -205095 -203551 -205981 -203482 -203791 -199705 -198289 -193626 -190794 -186442 -183312 -178925 -175336 -171349 -166797 -161857 -155041 -147364 -136825 -126018 -111552 -99702.5 -84563.3 -73757.6 -58424.6 -47842.9 -34442.6 -26878.3 -17719.9 -14723.5 -12208.1 -14038.3 -15556.8 -16441.4 -15930.5 -13097.1 -16980.5 -1.30384e+07 4.19e+06 1.55864e+06 269738 -116992 -180232 -192280 -199564 -198011 -202601 -200430 -205315 -201232 -198072 -192748 -191883 -187156 -184228 -181627 -178992 -172382 -168015 -163773 -158274 -150800 -143071 -137186 -124310 -113167 -95007.4 -82276.2 -65992.5 -57354.7 -41963.1 -33444.1 -22509.7 -20203.4 -13422.3 -13678.8 -11732.8 -11155.8 -12663.4 -8728.34 -6491.88 11699.9 -8.65312e+07 -2.37542e+06 -583112 3.78794e+06 1.07987e+07 5.43612e+07 -3.13369e+06 -1.9077e+06 -295822 -6.30172e+06 9.38082e+07 3.22879e+06 -489491 -554092 -7.02953e+06 5.38879e+07 -2.96191e+06 -2.34737e+06 -2.49743e+06 -6.70813e+06 -7.52337e+07 -1.39982e+07 -2.0105e+06 -2.60053e+06 -8.20597e+06 -1.87321e+06 2.86409e+06 856126 144212 -137271 -178712 -196251 -199213 -204588 -203315 -205489 -203281 -203576 -199815 -198451 -193938 -191032 -186611 -183306 -178799 -175157 -171174 -166640 -161704 -154879 -147175 -136634 -125877 -111480 -99682.2 -84551.9 -73757.3 -58475.2 -48015.4 -34777.6 -27437.8 -18456.7 -15542.8 -12869.4 -14429.4 -15655.6 -16618.2 -16600.5 -13843.2 -17096.7 -7.41211e+06 373286 -64601 -51733.1 -179617 -194862 -194701 -201160 -200860 -205263 -203052 -205241 -201762 -201519 -197284 -195204 -190413 -187352 -182804 -179125 -175055 -171062 -166892 -161191 -155361 -146116 -137506 -124318 -113428 -97985.4 -86941.9 -71360.4 -60997.5 -45698.9 -37401.1 -25426.1 -20843 -14462.6 -14307.4 -14248.4 -15538.1 -17716.1 -16080.2 -13363.6 8896.84 -7.01328e+06 -713937 -605319 -264633 -252327 -212160 -205522 -198740 -204194 -201557 -205668 -202474 -203955 -199614 -198990 -193976 -191597 -186590 -183348 -178777 -175142 -171120 -166451 -161655 -154227 -147037 -135724 -126001 -111259 -100633 -84244.1 -74438.2 -57899.4 -49172.3 -34551.6 -28700.9 -18814.7 -16910.3 -13543.7 -14783.3 -16248 -16261.8 -19245.4 -17182.7 -25498 -6.00551e+06 -1.26051e+06 -867594 -387611 -278066 -218589 -201582 -199724 -200160 -202683 -202720 -203486 -201726 -200434 -197322 -194467 -190405 -186723 -182496 -178608 -174644 -170619 -166217 -160681 -154234 -145594 -136167 -124261 -112447 -98633.6 -86081.6 -72147.7 -60088.2 -46961.8 -36945.1 -26984.2 -20944.5 -16041.4 -14771.2 -14729.1 -15776.2 -17257.1 -18297.8 -19434.1 -4418.17 -6.79309e+06 -1.89748e+06 -908876 -268858 -184300 -158169 -180724 -183270 -199051 -195239 -203625 -197782 -202156 -195767 -197167 -190760 -189747 -183828 -181412 -176503 -173164 -169152 -164140 -159789 -151516 -145503 -132824 -125197 -108591 -100728 -81745.4 -75062.3 -55462 -50445 -32723.4 -30387.5 -17874.5 -18435.5 -13446.6 -14898.7 -16642.9 -14756.4 -23324.8 -21858.1 -41495.3 ) ; boundaryField { AirInlet { type fixedFluxPressure; gradient uniform 3.62007e+08; value uniform -1.30347e+07; } WaterInlet { type fixedFluxPressure; gradient nonuniform List<scalar> 10(0 0 -0.0374796 -0.0396571 0 0 -0.0396571 -0.0374796 -0.036069 -0.22094); value nonuniform List<scalar> 10(-7.52336e+07 5.38877e+07 9.38076e+07 5.43598e+07 -8.65329e+07 -8.65312e+07 5.43612e+07 9.38082e+07 5.38879e+07 -7.52337e+07); } ChannelWall { type fixedFluxPressure; gradient uniform 0; value nonuniform List<scalar> 110 ( -8.65329e+07 -2.3782e+06 -584773 3.78687e+06 1.07995e+07 -8.65312e+07 -2.37542e+06 -583112 3.78794e+06 1.07987e+07 -7.52337e+07 -1.39982e+07 -2.0105e+06 -2.60053e+06 -8.20597e+06 -6.79309e+06 -1.89748e+06 -908876 -268858 -184300 -158169 -180724 -183270 -199051 -195239 -203625 -197782 -202156 -195767 -197167 -190760 -189747 -183828 -181412 -176503 -173164 -169152 -164140 -159789 -151516 -145503 -132824 -125197 -108591 -100728 -81745.4 -75062.3 -55462 -50445 -32723.4 -30387.5 -17874.5 -18435.5 -13446.6 -14898.7 -16642.9 -14756.4 -23324.8 -21858.1 -41495.3 -7.52336e+07 -1.39997e+07 -2.01036e+06 -2.60112e+06 -8.20532e+06 -6.79323e+06 -1.89687e+06 -908273 -267860 -183560 -157705 -181029 -184132 -200450 -196862 -205186 -199003 -202842 -195746 -196571 -189814 -188809 -183223 -181308 -176857 -173803 -169906 -164923 -160642 -152446 -146522 -133802 -126029 -109134 -101063 -81858.3 -74996.3 -55045.7 -49581.8 -31108.2 -28000.6 -14852.9 -15109 -10354.5 -12673.4 -15489.5 -14145.3 -21712.2 -19688 -40967.3 ) ; } Outlet { type totalPressure; rho rho; psi none; gamma 1; p0 uniform 0; value uniform 0; } FrontAndBack { type empty; } } // ************************************************************************* //
0f935a43d679c5d195b31b87be64ce1f67e6545d
305b9d7e4bc8ba731164fb10e53fb1e0a8d53775
/libspindle/adt/Map/ScatterMap.cc
dce1c2affcc48aec97bc790c4117eb24a6d22a49
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-mit-old-style" ]
permissive
skn123/Spindle
33b2bed84de866bb87e69bbfb2eca06e780b3dcb
d5f2cab92c86c547efbf09fb30be9d478da04332
refs/heads/master
2021-05-26T12:50:00.410427
2012-11-14T01:23:01
2012-11-14T01:23:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,447
cc
ScatterMap.cc
// // ScatterMap.cc -- an abstraction of a loc2glob | glob2loc mapping. // // $Id: ScatterMap.cc,v 1.2 2000/02/18 01:31:49 kumfert Exp $ // // Gary Kumfert, Old Dominion University // Copyright(c) 1998, Old Dominion University. All rights reserved. // // Permission to use, copy, modify, distribute and sell this software and // its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. Old Dominion University makes no // representations about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. // /////////////////////////////////////////////////////////////////////// // // The ScatterMap class is meant to abstract away the concept of // a scattering of global items into a subset of local ones. // It encapsulates the one-to-one, but not onto relationship // of loc2glob and glob2loc (local to global and global to local) // // A ScatterMap is not in a valid state until validate() is called // to insure that both loc2glob and glob2loc are consistent with each // other. // #include "spindle/ScatterMap.h" #ifndef SPINDLE_ARCHIVE_H_ #include "spindle/SpindleArchive.h" #endif #ifndef SPINDLE_SYSTEM_H_ #include "spindle/SpindleSystem.h" #endif #ifdef HAVE_NAMESPACES using namespace SPINDLE_NAMESPACE; #endif ScatterMap::ScatterMap() { incrementInstanceCount( ScatterMap::MetaData ); currentState = EMPTY; reset(); } // create an empty map of size n ScatterMap::ScatterMap( int n ) { incrementInstanceCount( ScatterMap::MetaData ); currentState = EMPTY; resize(n); } // creates map of globalIndex[ local ] = global ScatterMap::ScatterMap( const int n, int* local2Global ) : loc2glob( local2Global, n ) { incrementInstanceCount( ScatterMap::MetaData ); currentState = UNKNOWN; changedMostRecent = LOC2GLOB; validate(); } ScatterMap::ScatterMap( const int n, const int* local2Global ) : loc2glob( local2Global, n ) { incrementInstanceCount( ScatterMap::MetaData ); currentState = UNKNOWN; changedMostRecent = LOC2GLOB; validate(); } ScatterMap::~ScatterMap() { decrementInstanceCount( ScatterMap::MetaData ); } int ScatterMap::queryMaxGlobal() const { if ( !isValid() ) { return -1; } int max = -1; for( const int* cur = loc2glob.begin(), *stop = loc2glob.end(); cur != stop; ++cur ) { if ( *cur > max ) { max = *cur; } } return max; } int ScatterMap::queryMinGlobal() const { if ( !isValid() ) { return -1; } if ( loc2glob.size() < 1 ) { return -1; } int min = *(loc2glob.begin()); for( const int* cur = loc2glob.begin(), *stop = loc2glob.end(); cur != stop; ++cur ) { if ( *cur < min ) { min = *cur; } } return min; } SharedArray<int>& ScatterMap::getLoc2Glob() { if ( (!isValid() ) && ( changedMostRecent == GLOB2LOC) ) { validate(); if ( !isValid() ) { loc2glob.init(0); } } currentState = UNKNOWN; changedMostRecent = LOC2GLOB; return loc2glob; } SharedPtr<ScatterMap::glob2loc_t>& ScatterMap::getGlob2Loc() { if ( (!isValid() ) && ( changedMostRecent == LOC2GLOB) ) { validate(); if ( !isValid() ) { if ( glob2loc.notNull() ) { glob2loc->erase( glob2loc->begin(), glob2loc->end() ); } } } currentState = UNKNOWN; changedMostRecent = GLOB2LOC; return glob2loc; } bool ScatterMap::reset() { loc2glob.init(-1); if ( glob2loc.notNull() ) { glob2loc->erase( glob2loc->begin(), glob2loc->end() ); } else { glob2loc.take( new glob2loc_t() ); } currentState = EMPTY; changedMostRecent = NEITHER; return true; } void ScatterMap::resize( const int n ) { currentState = EMPTY; changedMostRecent = NEITHER; loc2glob.resize( n ); if ( glob2loc.notNull() ) { glob2loc->erase( glob2loc->begin(), glob2loc->end() ); } } void ScatterMap::validate() { if ( currentState == VALID ) { return ; } if ( changedMostRecent == NEITHER ) { // try to detect if something has // meaningful information in it if ( loc2glob.size() > 0 ) { changedMostRecent = LOC2GLOB; } else { changedMostRecent = GLOB2LOC; } } if ( changedMostRecent == LOC2GLOB ) { // load glob2loc if ( glob2loc.notNull() ) { glob2loc->erase( glob2loc->begin(), glob2loc->end() ); } else { glob2loc.take( new glob2loc_t() ); } glob2loc_t & g2l = (*glob2loc); int i = 0; for( const int* cur = loc2glob.begin(), *stop = loc2glob.end(); cur != stop; ++cur,++i ) { g2l[*cur] = i; } if ( g2l.size() != (size_t) loc2glob.size() ) { // size mismatch, must have double entries currentState = INVALID; } else { currentState = VALID; } return; } else if ( changedMostRecent == GLOB2LOC ) { currentState = VALID; glob2loc_t & g2l = (*glob2loc); int max = g2l.size(); loc2glob.resize( max ); loc2glob.init(-1); for( glob2loc_t::const_iterator cur = g2l.begin(), stop = g2l.end(); cur != stop; ++cur ) { if ( (*cur).second < max ) { loc2glob[ (*cur).second ] = (*cur).first; } } if ( find( loc2glob.begin(), loc2glob.end(), -1 ) != loc2glob.end() ) { // found a -1 in the range currentState = INVALID; } else { currentState = VALID; } return; } // should never get here currentState = INVALID; return ; } void ScatterMap::dump( FILE * stream ) const { if ( isValid() ) { for( int i =0; i<loc2glob.size(); ++i ) { fprintf( stream, " scatter[ %d ] = %d\n", i, loc2glob[i] ); } } } void ScatterMap::storeObject( SpindleArchive& ar ) const { if ( isValid() ) { const int *p = loc2glob.lend(); size_t my_size = loc2glob.size(); pair< const int*, size_t> my_pair( p,my_size ); ar << my_pair; } else { ar << -1; } } void ScatterMap::loadObject( SpindleArchive& ar ) { size_t new_size = ar.peekLength(); if ( (int)new_size == -1 ) { int junk; ar >> junk; currentState = INVALID; } else { resize(new_size); int* p = getLoc2Glob().begin(); pair<int*, size_t> new_pair( p, new_size ); ar >> new_pair; changedMostRecent = LOC2GLOB; validate(); } } SPINDLE_IMPLEMENT_PERSISTANT( ScatterMap, SpindlePersistant )
85aa7a8f61e4c0bb98c9e7473e667bb1c9f59c0f
19e5c3407466691aa0b42b2fc9a6790baafc5343
/fix_print.cpp
0684dc3e0498ca54e59278120be3253a26c9b665
[]
no_license
8cH9azbsFifZ/lammps-CSI
168101d48f4ba2af5d1d8235ac7c969a74b283ff
ac4b39f405463aa6329e2bf0f72532248b028562
refs/heads/master
2021-06-02T23:40:27.967156
2019-11-05T00:46:52
2019-11-05T00:46:52
6,374,089
1
0
null
null
null
null
UTF-8
C++
false
false
2,017
cpp
fix_print.cpp
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "stdlib.h" #include "string.h" #include "fix_print.h" #include "update.h" #include "input.h" #include "variable.h" #include "error.h" using namespace LAMMPS_NS; #define MAXLINE 1024 /* ---------------------------------------------------------------------- */ FixPrint::FixPrint(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg) { if (narg != 5) error->all("Illegal fix print command"); nevery = atoi(arg[3]); if (nevery <= 0) error->all("Illegal fix print command"); MPI_Comm_rank(world,&me); int n = strlen(arg[4]) + 1; line = new char[n]; strcpy(line,arg[4]); copy = new char[MAXLINE]; work = new char[MAXLINE]; } /* ---------------------------------------------------------------------- */ FixPrint::~FixPrint() { delete [] line; delete [] copy; delete [] work; } /* ---------------------------------------------------------------------- */ int FixPrint::setmask() { int mask = 0; mask |= END_OF_STEP; return mask; } /* ---------------------------------------------------------------------- */ void FixPrint::end_of_step() { // make a copy of line to work on // substitute for $ variables (no printing) // append a newline and print final copy strcpy(copy,line); input->substitute(copy,0); strcat(copy,"\n"); if (me == 0) { if (screen) fprintf(screen,copy); if (logfile) fprintf(logfile,copy); } }
9d02fed831e02c12f1c87cd0e913f56492165345
893b5f0c62c33521645cf4c2036791c61c7d3bbe
/main.cpp
05b29705ed0db27a1bc0f50f20fa2a39a027fece
[]
no_license
Nirmaldahal25/AdjancencyList
41382d260331a5826412b241981eaa20e10fa745
c64d2f7c9ff3f104b06fde08dfef83953b838ea0
refs/heads/master
2023-07-02T09:11:16.760403
2021-07-29T07:30:40
2021-07-29T07:30:40
390,629,784
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
main.cpp
// CMAKENEW generated file: Sample main file #include <iostream> #include "graphs.hpp" #include <string> int main(){ Graph<char> graph{'A', 'B'}; std::set<char> se; graph.addVertex('C'); graph.addVertex('D'); graph.addVertex('E'); graph.addEdge('A', 'B'); graph.addEdge('A', 'C'); graph.neighbours('A', se); graph.removeEdge('A','B'); graph.display(); std::cout<<graph.outDegree('A')<<" Outdegree"<<std::endl; std::cout<<graph.inDegree('A')<<" Indegree"<<std::endl; std::cout<<graph.degree('A')<<" total degree\n"; graph.removeVertex('A'); std::cout<<"A Vertex Removed\n"; std::cout<<std::boolalpha<<graph.isDirected()<<" Directed\n"; std::cout<<std::boolalpha<<graph.isNeighbour('A','C')<<" Are neighbours\n"; for(auto i : se) { std::cout<<i<<std::endl; } return 0; }
92ad7ebeb02919f2823c374bba85688d28e52c87
77a88451e9816de8dcafd76b7d70d6110c8a459f
/starbuzz/beverages/house_blend.hpp
27345da25b130cd9b3b21c978d303e3f90eca866
[]
no_license
jsxft/learn-oop
847dad41823cb7254cbcd28e03d6909ba58cbbf6
58b1f79087ead639a812387b8a56be40bf42d07a
refs/heads/main
2023-04-30T03:23:31.604874
2021-05-13T17:41:59
2021-05-13T17:41:59
363,584,863
0
0
null
null
null
null
UTF-8
C++
false
false
125
hpp
house_blend.hpp
#pragma once #include "beverage.hpp" class HouseBlend : public Beverage { public: HouseBlend(); double cost() const; };
d8faff10d2435891f2de13691e14f36bfe5f74a2
2b2da3c294d188fa7c2795364ab26859e29ffb87
/OFSample-Windows/depends/dwinternal/framework2015/dwutility/app/environmentpath.h
aa5df64bfcb4a0a8b14d95c60f7a17ba33ad6d21
[]
no_license
JocloudSDK/OFSample
1de97d416402b91276f9992197bc0c64961fb9bd
fa678d674b3886fa8e6a1c4a0ba6b712124e671a
refs/heads/master
2022-12-28T05:03:05.563734
2020-10-19T07:11:55
2020-10-19T07:11:55
294,078,053
4
2
null
null
null
null
UTF-8
C++
false
false
151
h
environmentpath.h
#pragma once #include <string> #include "dwglobal.h" namespace DwUtility { namespace app { std::wstring DW_DWUTILITY_EXPORT appRootPath(); } }
c3e104192f12608408a3ff61487eca6314370e1e
c2915484a4fe848b9bfee6bfb65f824993dde59b
/Case/case2/500/phi
d166a001b33359501545d5b2d6b5c632e78afc09
[]
no_license
mamitsu2/aircond5_play3
835b937da2d60771b8a7b81e13631a8a1271e8f4
8eee217855014d562013e0dbe0024208a4633db3
refs/heads/master
2020-05-24T21:54:50.022678
2019-05-19T13:31:37
2019-05-19T13:31:37
187,480,539
0
0
null
null
null
null
UTF-8
C++
false
false
13,508
phi
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "500"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 0 -1 0 0 0 0]; internalField nonuniform List<scalar> 852 ( -0.00323224 0.00328679 -0.00457721 0.00134485 -0.00529567 0.000718348 -0.00546734 0.000171569 -0.00501744 -0.00045001 -0.00389668 -0.00112086 -0.00221454 -0.00168224 -0.000259323 -0.00195532 0.00135919 -0.00161866 0.00249981 -0.00114076 0.00317416 -0.000674491 0.00339281 -0.000218794 0.0031279 0.000264772 0.00221602 0.000911736 0.00221746 -0.000966883 0.000968021 -0.00134859 0.000381446 -0.001131 -0.000217869 -0.000517135 -0.000614137 0.000217321 -0.00073473 0.000895384 -0.00067833 0.00134928 -0.00045418 0.00162916 -0.000280177 0.00185125 -0.000222415 0.00202755 -0.000176641 0.00212647 -9.92951e-05 0.00212558 5.03135e-07 0.00201665 0.000108526 0.00179333 0.000222942 0.00144565 0.000347429 0.000974756 0.000470881 0.000458794 0.000516129 0.000126237 0.000332626 0.000127745 -0.00231623 0.00575189 -0.00351909 0.0025476 -0.00425269 0.00145183 -0.00446108 0.000379852 -0.00406608 -0.0008451 -0.00306943 -0.0021176 -0.00168393 -0.00306784 -0.000242971 -0.00339639 0.00103867 -0.00290044 0.00200351 -0.00210576 0.00261927 -0.0012904 0.00291008 -0.000509748 0.00292311 0.000251584 0.00281323 0.00102146 0.00327292 0.00175762 0.00160773 0.00166498 0.00160751 -0.000351631 0.00132351 -0.000220285 0.000249851 0.000234365 -0.00067286 0.000690023 -0.00107007 0.00107758 -0.00112256 0.001381 -0.000982002 0.00146535 -0.000538798 0.00149361 -0.000308723 0.0015317 -0.000260834 0.0015713 -0.000216601 0.00158254 -0.000110906 0.00155466 2.80029e-05 0.00151144 0.000151384 0.00147731 0.000256749 0.00142844 0.000396078 0.00123446 0.000664774 0.000922778 0.000827807 0.000469463 0.000785914 0.000600863 -0.00162853 0.00761016 -0.00262158 0.00354053 -0.00328331 0.00211345 -0.00347917 0.000575606 -0.00308984 -0.00123453 -0.00215839 -0.00304914 -0.00099232 -0.00423398 0.00010435 -0.00449317 0.00106613 -0.00386237 0.00181402 -0.0028538 0.00230691 -0.00178345 0.0025736 -0.000776607 0.00267989 0.000145134 0.00270563 0.000995561 0.00266662 0.00179647 0.00196175 0.0023697 0.0035691 0.000660071 0.000670014 0.00128835 -0.000378812 0.00159194 -0.000976772 0.0017703 -0.00124872 0.00190781 -0.00126031 0.00211343 -0.00118785 0.00157454 0.00126569 0.00100467 0.000787818 0.000676667 0.00070453 0.000855844 0.00111256 0.00150864 0.00138294 0.000790355 0.0011639 0.00104677 0.000738453 0.00121128 0.00134511 -0.00113126 0.0090411 -0.00188312 0.00429226 -0.0023391 0.00256931 -0.00240836 0.000644758 -0.00191243 -0.00173055 -0.00102554 -0.00393608 -0.000104936 -0.00515465 0.000661118 -0.00525934 0.00130641 -0.00450781 0.00179529 -0.00334286 0.0021027 -0.00209106 0.00226474 -0.000938829 0.00234681 6.2893e-05 0.00241508 0.000927116 0.00254647 0.00166492 0.00278925 0.00212675 0.00402554 0.00233265 0.00284151 0.00119227 0.00305605 0.000455204 0.00297453 -0.000297562 0.00281902 -0.000821497 0.0026289 -0.00105881 0.00241865 -0.00105026 0.00207313 -0.000842504 0.00242006 -0.000347253 0.00253585 -0.000116109 0.00255697 -2.14494e-05 0.002518 3.86396e-05 0.00242963 8.80334e-05 0.00229724 0.000132053 0.00211555 0.000181348 0.00185988 0.000255325 0.00146698 0.000392563 0.00142877 0.000828422 0.00124997 0.00122547 0.000890909 0.00157024 0.00224377 -0.000775853 0.010177 -0.00131322 0.0048295 -0.0014225 0.00267847 -0.00113626 0.000358395 -0.000395353 -0.00247154 0.000367954 -0.00469943 0.000954843 -0.00574159 0.00136184 -0.00566644 0.00165302 -0.00479916 0.00181923 -0.00350927 0.00187156 -0.00214359 0.00186483 -0.000932302 0.00186851 5.90183e-05 0.00195733 0.000838111 0.00220446 0.00141761 0.00259783 0.00173321 0.00314379 0.00178651 0.00319449 0.00114141 0.00327539 0.000374115 0.00318312 -0.000205468 0.002945 -0.000583523 0.00263646 -0.000750416 0.00231605 -0.000729984 0.0020335 -0.000560099 0.00195782 -0.000271718 0.00188734 -4.57841e-05 0.00178341 8.23181e-05 0.00166798 0.000153902 0.00155385 0.000201984 0.00144227 0.000243453 0.0013312 0.000292222 0.00121908 0.000367261 0.00111328 0.000498171 0.00115228 0.000789243 0.00124415 0.00113344 0.00135979 0.00145448 0.00205386 0.00154958 0.00128985 0.000763678 0.000558116 0.000731416 0.000598113 -0.000599228 0.0111884 -0.000866395 0.00509654 -0.000314656 0.00212659 0.000571384 -0.000527784 0.00142986 -0.00333009 0.00194042 -0.00521001 0.00215191 -0.00595312 0.00214163 -0.00565626 0.00199155 -0.00464927 0.00175405 -0.00327201 0.00148229 -0.00187208 0.00125376 -0.000703996 0.00114573 0.000166843 0.00121247 0.000771181 0.00145425 0.00117564 0.00181322 0.00137407 0.00226706 0.00133251 0.00254536 0.000862945 0.00259445 0.000324874 0.00247534 -8.65039e-05 0.00223441 -0.000342732 0.00192973 -0.000445871 0.0016136 -0.000413991 0.00133304 -0.000279681 0.00113912 -7.79543e-05 0.000999193 9.39736e-05 0.000886166 0.00019517 0.000791385 0.000248502 0.000713482 0.000279703 0.000654079 0.00030267 0.000618133 0.000327978 0.000616146 0.000369054 0.000666805 0.000447311 0.000839071 0.000616773 0.00114273 0.000829583 0.00156663 0.0010304 0.00204066 0.00107539 0.00202353 0.000780657 0.00155422 0.00120057 0.0021921 -0.000396219 0.0120471 1.84953e-06 0.00469834 0.00157936 0.000548935 0.00283669 -0.00178522 0.00352045 -0.00401388 0.00368481 -0.00537438 0.00340601 -0.00567435 0.00283296 -0.00508334 0.00213381 -0.00395033 0.00141958 -0.00255805 0.000796526 -0.00124931 0.000366593 -0.000274313 0.000204203 0.000329016 0.000283593 0.000691594 0.000533715 0.000925336 0.000881646 0.00102597 0.00126509 0.000948898 0.00149082 0.000637061 0.00151959 0.000295956 0.0013996 3.33228e-05 0.00118081 -0.0001241 0.000908337 -0.000173561 0.000625419 -0.000131243 0.000370114 -2.45548e-05 0.000184624 0.000107347 6.93796e-05 0.000209025 -4.33208e-06 0.000268687 -5.52735e-05 0.000299251 -8.77988e-05 0.000312035 -9.96356e-05 0.000314313 -8.34641e-05 0.000311609 -2.56981e-05 0.000311084 9.43451e-05 0.000327054 0.000319817 0.000391075 0.000660095 0.000489074 0.00112046 0.000569814 0.00167186 0.000523785 0.00201284 0.000439481 0.00173691 0.00147631 0.00396822 0.00321121 0.00935598 0.00429325 0.00361617 0.00504392 -0.000201873 0.00591567 -0.00265705 0.00608535 -0.00418354 0.00551199 -0.00480098 0.00443036 -0.00459277 0.0030861 -0.00373925 0.00175258 -0.00261709 0.000554152 -0.00135995 -0.000291756 -0.000403718 -0.000710281 0.000143951 -0.000792967 0.000411476 -0.000678762 0.000577181 -0.000441846 0.000688227 -0.000141883 0.000725821 0.000144837 0.000662005 0.000294473 0.000487257 0.000292386 0.000297873 0.000175884 0.000149644 -1.41795e-05 6.5765e-05 -0.000238485 5.05333e-05 -0.000455004 8.50536e-05 -0.000626196 0.000146411 -0.000731857 0.000212784 -0.000788587 0.000265535 -0.000818122 0.000298006 -0.000832987 0.000313904 -0.000839359 0.0003182 -0.000841139 0.000315886 -0.00084392 0.00031418 -0.000859476 0.00032642 -0.000909053 0.000376394 -0.00101493 0.000496704 -0.00122474 0.000698632 -0.00160385 0.000948696 -0.00223407 0.0011538 -0.00308583 0.00129105 -0.00305866 0.00144894 0.00109498 0.00993135 0.0135417 0.0118762 0.0014635 0.0103956 -0.00117641 0.00858105 -0.00236891 0.00648626 -0.00270617 0.00429359 -0.00240024 0.00212419 -0.00157011 0.000273322 -0.000766573 -0.00100199 -8.50209e-05 -0.00161433 0.000208321 -0.00179696 0.00032631 -0.00177511 0.000389383 -0.00164272 0.00044456 -0.00144462 0.000489908 -0.00122503 0.000506015 -0.00103872 0.000475497 -0.000948267 0.000396594 -0.000958067 0.000307457 -0.00104373 0.000235074 -0.00117087 0.000192659 -0.00130323 0.000182644 -0.00141484 0.000196394 -0.0014915 0.000222815 -0.00153107 0.000252091 -0.0015427 0.000276913 -0.00153945 0.000294513 -0.00153231 0.000306533 -0.00153127 0.000316926 -0.00154767 0.000332063 -0.00159557 0.00036185 -0.00169092 0.000421537 -0.00184897 0.000534216 -0.00208152 0.000729033 -0.00241209 0.001029 -0.00290293 0.00143934 -0.00365153 0.00190217 -0.00451654 0.00215568 -0.00423228 0.00116409 -0.0029899 0.00544576 0.00288407 0.00388845 0.000381031 0.00298199 -0.00146252 0.00160511 -0.00132953 -4.81168e-05 -0.000747423 -0.00150067 -0.000117937 -0.00241693 0.000149327 -0.0027896 0.000287311 -0.00288382 0.000302238 -0.0028517 0.000293894 -0.00275629 0.000293692 -0.00262142 0.000309418 -0.0024646 0.000332821 -0.00230859 0.000349751 -0.00218163 0.00034827 -0.00211023 0.000324925 -0.00209445 0.000291393 -0.00211871 0.000259048 -0.00216177 0.000235413 -0.00220305 0.00022362 -0.00222908 0.000222116 -0.0022342 0.00022763 -0.00221901 0.000236599 -0.00218832 0.000245926 -0.00214818 0.000254091 -0.0021037 0.00026177 -0.00205889 0.000271848 -0.00201689 0.000289793 -0.00197956 0.000324254 -0.0019463 0.000388021 -0.00191127 0.000498925 -0.00186007 0.0006776 -0.00177112 0.000939824 -0.0016187 0.00128672 -0.00129673 0.00157998 -0.000425777 0.00128444 0.000472511 0.000265306 -0.00248536 0.000322269 0.00263711 0.000148943 0.000554204 -0.00136436 5.05037e-05 -0.00272017 2.59063e-05 -0.0036139 0.000145926 -0.00398064 0.00024842 -0.00409222 0.000260539 -0.00405151 0.000246249 -0.00396071 0.000211084 -0.00384997 0.000182817 -0.00372746 0.000170852 -0.00359332 0.00017495 -0.00344969 0.000188864 -0.0033047 0.000204427 -0.00317117 0.00021441 -0.00306162 0.000215029 -0.00297888 0.000208305 -0.00291792 0.000197733 -0.00286965 0.000186776 -0.0028244 0.000178013 -0.00277514 0.000172486 -0.00271815 0.000170279 -0.0026527 0.000170792 -0.00258013 0.000173008 -0.00250253 0.000176144 -0.00242137 0.000180262 -0.00233639 0.000186536 -0.00224437 0.000197442 -0.00213736 0.000216919 -0.00200036 0.000250711 -0.00180876 0.000307022 -0.00152659 0.000395152 -0.00109846 0.000511425 -0.000402232 0.00059025 0.000604647 0.000572842 0.00161697 0.000271831 0.00219565 -0.000313729 -0.000257016 0.00176485 -0.00932543 -0.00666849 -0.0061177 -0.00608026 -0.00607215 -0.00594722 -0.00572245 -0.00548758 -0.0052684 -0.00508535 -0.00493123 -0.00478956 -0.00464422 -0.00448541 -0.00431157 -0.00412837 -0.00394527 -0.00376967 -0.0036054 -0.00345277 -0.00330949 -0.00317221 -0.0030375 -0.00290256 -0.00276564 -0.0026258 -0.00248205 -0.00233225 -0.00217179 -0.00199213 -0.00177898 -0.00150983 -0.00115285 -0.000679939 -0.000128819 0.000403408 0.000632383 0.000273572 ) ; boundaryField { floor { type calculated; value nonuniform List<scalar> 29 ( 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1.50149e-06 -3.70824e-06 -5.89143e-06 -7.85027e-06 -1.58755e-06 -1.3793e-06 -4.09122e-06 -6.81486e-06 -8.41058e-06 ) ; } ceiling { type calculated; value nonuniform List<scalar> 43 ( 7.07077e-06 -1.59709e-05 -2.03968e-05 2.99335e-06 1.26579e-05 1.73859e-05 2.0584e-05 2.32262e-05 2.52592e-05 2.66618e-05 2.76218e-05 2.82827e-05 2.87722e-05 2.91969e-05 2.96411e-05 3.01627e-05 3.07882e-05 3.15066e-05 3.2271e-05 3.30223e-05 3.37073e-05 3.4291e-05 3.4762e-05 3.51303e-05 3.54193e-05 3.56577e-05 3.58724e-05 3.6086e-05 3.63158e-05 3.6573e-05 3.68606e-05 3.71708e-05 3.74874e-05 3.78025e-05 3.81637e-05 3.87827e-05 4.02619e-05 4.24404e-05 4.45744e-05 4.80902e-05 8.17588e-06 5.75626e-06 -7.53203e-05 ) ; } sWall { type calculated; value uniform -0.000194417; } nWall { type calculated; value nonuniform List<scalar> 6(-4.02683e-05 -3.99112e-05 -3.93646e-05 -3.24014e-05 -3.3057e-05 -3.20984e-05); } sideWalls { type empty; value nonuniform 0(); } glass1 { type calculated; value nonuniform List<scalar> 9(-5.46715e-05 -0.000148985 -0.000229844 -0.000299787 -0.00036015 -0.000412278 -0.000462555 -0.000520236 -0.000583649); } glass2 { type calculated; value nonuniform List<scalar> 2(-0.000185599 -0.000148216); } sun { type calculated; value uniform 0; } heatsource1 { type calculated; value nonuniform List<scalar> 3(2.0228e-07 2.02566e-07 2.02783e-07); } heatsource2 { type calculated; value nonuniform List<scalar> 4(5.08618e-08 5.10681e-08 0 0); } Table_master { type calculated; value nonuniform List<scalar> 9(-1.52248e-07 -1.52433e-07 -1.5247e-07 -1.52452e-07 -1.52394e-07 -1.52319e-07 -1.5221e-07 -1.52093e-07 -1.51946e-07); } Table_slave { type calculated; value nonuniform List<scalar> 9(1.52005e-07 1.5199e-07 1.51947e-07 1.51911e-07 1.5189e-07 1.51886e-07 1.51899e-07 1.51931e-07 1.51989e-07); } inlet { type calculated; value uniform -0.00686616; } outlet { type calculated; value nonuniform List<scalar> 2(-0.00157798 0.0111057); } } // ************************************************************************* //
a45b2ace926da8ec64587ba11496d525fe9f1128
91c56a7aed55baca57909c94ac0b895b624d9184
/Strategy/Strategy.cpp
dcdbed0b13f341d88e2e76a4635234f92c89090c
[]
no_license
EvenQAQ/4chess
d134232a61f8f28acae727d74f0840190d49cb20
4bd90a4c91a30ec8a0f6bf3aac2279bbcd46f1b7
refs/heads/main
2023-02-11T03:33:40.822771
2021-01-02T10:43:09
2021-01-02T10:43:09
326,160,562
0
0
null
null
null
null
UTF-8
C++
false
false
8,715
cpp
Strategy.cpp
#include <iostream> #include <unistd.h> #include <ctime> #include <cmath> #include "Point.h" #include "Judge.h" #include "Strategy.h" using namespace std; class Status{ private: int n, m, noX, noY, lastX, lastY, player; int **board; int *top; int limits; Status **children; Status *parent; int expandTotal; int *expandNum; int visitedNum; double profit; public: Status(int **_board, int *_top, int _n, int _m, int _noX, int _noY, int _lastX, int _lastY, int _player, Status *_father): board(_board), top(_top), n(_n), m(_m), noX(_noX), noY(_noY), lastX(_lastX), lastY(_lastY), player(_player), parent(_father), limits(2), profit(0), expandTotal(0) { children = new Status*[_n]; for (int i = 0; i < _n; i++) { children[i] = NULL; if (_top[i] != 0) { expandNum[expandTotal] = i; expandTotal++; } } if (_lastX-1 == noX && _lastY == noY) top[_lastY]--; } int getX(); int getY(); void debug(); bool canExpand(); Status* expand(); bool isEnd(); Status* bestChild(); void backup(double delta); void setLimits(int time); void put(int **board, int *top, int player, int x, int y); Status* uctSearch(); Status* treePolicy(Status* temp); double defaultPolicy(); ~Status() { for (int i = 0; i < m; i++) delete board[i]; delete []board; delete []top; delete []parent; for (int i = 0; i < n; i++) delete []children; //delete } }; int Status::getX() { return lastX; } int Status::getY() { return lastY; } void Status::debug() { cout << n << "-" << m << "-" << noX << "-" << noY << "-" << lastX << "-" << lastY << endl; } bool Status::canExpand() { if (expandTotal > 0) return true; else return false; } Status* Status::expand() { int index, X, Y; while(1) { index = rand() % expandTotal; Y = expandNum[index]; X = top[Y]; if (X == noX && Y == noY) continue; else break; } int **tempboard = board; int *temptop = top; tempboard[X][Y] = 3-player; temptop[Y]--; if (X == noX && Y == noY) temptop[Y]--; children[Y] = new Status(tempboard, temptop, n, m, noX, noY, X, Y, 3-player, this); return children[Y]; } bool Status::isEnd() { if (machineWin(lastX, lastY, m, n, board) || userWin(lastX, lastY, m, n, board) || isTie(n, top)) return true; else return false; } Status* Status::bestChild() { Status *bestChild; double maxProfit; for (int i = 0; i < n; i ++) { if (children[i] == NULL) continue; double modifiedProfit = (player == 1 ? -1 : 1) * children[i] -> profit; //修正收益值 int childVisitedNum = children[i] -> visitedNum; //子节点访问数 double tempProfit = modifiedProfit / childVisitedNum + sqrtl(2 * logl(visitedNum) / childVisitedNum) * 1; //计算综合收益率 if (tempProfit > maxProfit || (tempProfit == maxProfit && rand() % 2 == 0)) { //选择综合收益率最大的子节点 maxProfit = tempProfit; bestChild = children[i]; } } return bestChild; } void Status::backup(double delta) { Status *temp = this; while (temp) { temp -> visitedNum ++; //访问次数+1 temp -> profit += delta; //收益增加delta temp = temp -> parent; } } void Status::setLimits(int time) { this->limits = time; } Status* Status::uctSearch() { int start = clock(); int t = 0; Status *root = new Status(board, top, n, m, noX, noY, lastX, lastY, player, NULL); while (t < limits) { Status *node = treePolicy(root); double delta = node->defaultPolicy(); node->backup(delta); t = clock() - start; } return root->bestChild(); } Status* Status::treePolicy(Status *temp) { while (temp -> isEnd() != 1) { //节点不是终止节点 if (temp -> canExpand()) //且拥有未被访问的子状态 return temp->expand(); //扩展该节点 else temp = temp->bestChild(); //选择最优子节点 } return temp; } void Status::put(int **board, int *top, int player, int x, int y) { y = rand() % n; //随机选择一列 while (top[y] == 0) //若此列已下满 y = rand() % n; //再随机选择一列 x = top[y]; //确定落子高度 board[x][y] = player; //落子 if (x - 1 == noX && y == noY) //若落子位置正上方紧邻不可落子点 top[y]--; cout << "put--" << x << "--" << y << endl; } double Status::defaultPolicy() { int **tempboard = this -> board, *temptop = this -> top; int tempplayer = this -> player; int x = this -> lastX, y = this -> lastY; double tempprofit = 2; //计算收益 while (tempprofit == 2) { //若当前状态未达终止状态 put(tempboard, temptop, tempplayer, x, y); //随机落子 if (tempplayer == 1 && userWin(x, y, m, n, tempboard)) tempprofit = -1; if (player == 2 && machineWin(x, y, m, n, tempboard)) tempprofit = 1; if (isTie(n, top)) tempprofit = 0; else tempprofit = 2; //计算收益 tempplayer = 3 - tempplayer; //棋权变换 } for (int i = 0; i < m; i ++) delete [] tempboard[i]; delete [] tempboard; delete [] temptop; return tempprofit; } /* 策略函数接口,该函数被对抗平台调用,每次传入当前状态,要求输出你的落子点,该落子点必须是一个符合游戏规则的落子点,不然对抗平台会直接认为你的程序有误 input: 为了防止对对抗平台维护的数据造成更改,所有传入的参数均为const属性 M, N : 棋盘大小 M - 行数 N - 列数 均从0开始计, 左上角为坐标原点,行用x标记,列用y标记 top : 当前棋盘每一列列顶的实际位置. e.g. 第i列为空,则_top[i] == M, 第i列已满,则_top[i] == 0 _board : 棋盘的一维数组表示, 为了方便使用,在该函数刚开始处,我们已经将其转化为了二维数组board 你只需直接使用board即可,左上角为坐标原点,数组从[0][0]开始计(不是[1][1]) board[x][y]表示第x行、第y列的点(从0开始计) board[x][y] == 0/1/2 分别对应(x,y)处 无落子/有用户的子/有程序的子,不可落子点处的值也为0 lastX, lastY : 对方上一次落子的位置, 你可能不需要该参数,也可能需要的不仅仅是对方一步的 落子位置,这时你可以在自己的程序中记录对方连续多步的落子位置,这完全取决于你自己的策略 noX, noY : 棋盘上的不可落子点(注:涫嫡饫锔?龅膖op已经替你处理了不可落子点,也就是说如果某一步 所落的子的上面恰是不可落子点,那么UI工程中的代码就已经将该列的top值又进行了一次减一操作, 所以在你的代码中也可以根本不使用noX和noY这两个参数,完全认为top数组就是当前每列的顶部即可, 当然如果你想使用lastX,lastY参数,有可能就要同时考虑noX和noY了) 以上参数实际上包含了当前状态(M N _top _board)以及历史信息(lastX lastY),你要做的就是在这些信息下给出尽可能明智的落子点 output: 你的落子点Point */ extern "C" Point* getPoint(const int M, const int N, const int* top, const int* _board, const int lastX, const int lastY, const int noX, const int noY){ /* 不要更改这段代码 */ int x = -1, y = -1;//最终将你的落子点存到x,y中 int** board = new int*[M]; for(int i = 0; i < M; i++){ board[i] = new int[N]; for(int j = 0; j < N; j++){ board[i][j] = _board[i * N + j]; } } /* 根据你自己的策略来返回落子点,也就是根据你的策略完成对x,y的赋值 该部分对参数使用没有限制,为了方便实现,你可以定义自己新的类、.h文件、.cpp文件 */ //Add your own code below /* //a naive example for (int i = N-1; i >= 0; i--) { if (top[i] > 0) { x = top[i] - 1; y = i; break; } } */ int temptop[13] = {}; for (int i = 0; i < N; i++) temptop[i] = top[i]; Status *uct = new Status(board, temptop, N, M, noX, noY, lastX, lastY, 2, NULL); uct->setLimits(1); uct = uct->uctSearch(); uct->debug(); x = uct->getX(); y = uct->getY(); /* 不要更改这段代码 */ clearArray(M, N, board); return new Point(x, y); } /* getPoint函数返回的Point指针是在本dll模块中声明的,为避免产生堆错误,应在外部调用本dll中的 函数来释放空间,而不应该在外部直接delete */ extern "C" void clearPoint(Point* p){ delete p; return; } /* 清除top和board数组 */ void clearArray(int M, int N, int** board){ for(int i = 0; i < M; i++){ delete[] board[i]; } delete[] board; } /* 添加你自己的辅助函数,你可以声明自己的类、函数,添加新的.h .cpp文件来辅助实现你的想法 */
50a14dd433f7ddcef0e5247141588a9049bf763c
c6619ae71fe9f14dda24beb0670b3db32e467ddc
/twel2twen.cpp
2e667137824c644b3ca31a1de0436049b9f59bcd
[]
no_license
icarus18/12-to-24-Hour-Format
48ace986ae4fab4fab71a040e3bfb1f0f9a859df
ce33c42fce1354ebb13d91fefe12993e0c3e86fc
refs/heads/main
2023-02-24T19:43:46.528789
2021-01-24T21:21:18
2021-01-24T21:21:18
332,551,375
0
0
null
null
null
null
UTF-8
C++
false
false
3,171
cpp
twel2twen.cpp
#include <iostream> #include <cstdio> #include <vector> #include <string> using namespace std; int main() { printf("Enter a time in 12hr-Format(ex. 02:03:45AM)\n"); printf("-->"); string s;// = "12:46:05AM"; cin >> s; do { //string s; vector <char> doggy; vector <char> kitty; char mike_tyson = ' '; int i = 0; int u = 0; int cnt = 0; do { mike_tyson = s[i]; doggy.push_back(mike_tyson); i++; } while (s[i] != '\0'); for (int i = 0; i < doggy.size(); i += 1) { if (doggy[i] < 58 && doggy[i] > 47) { kitty.push_back(doggy[i]); } if (doggy[i] == 'P' || doggy[i] == 'p') { cnt++; } if (doggy[i] == 'A' || doggy[i] == 'a') { cnt++; cnt++; } } doggy.erase(doggy.begin(), doggy.end()); doggy.resize(0); if (cnt == 1 && kitty[1] != '2') { s = ""; s = s.append(kitty.begin(), kitty.begin() + 2); i = stoi(s, 0, 0); i = i + 12; } else if (cnt == 1 && kitty[0] == '0' && kitty[1] == '2') { s = ""; s = s.append(kitty.begin(), kitty.begin() + 2); i = stoi(s, 0, 0); i = i + 12; } else if (cnt == 1 && kitty[1] == '2') { s = ""; s = s.append(kitty.begin(), kitty.begin() + 2); i = stoi(s, 0, 0); } else if (cnt == 2 && kitty[0] == '1') { s = ""; i = 0; } else if (cnt == 2 && kitty[1] == '2') { s = ""; i = 2; } else { s = ""; s = s.append(kitty.begin() + 1, kitty.begin() + 2); i = stoi(s, 0, 0); } if (cnt == 1) { u = i / 10; mike_tyson = '0' + u; doggy.push_back(mike_tyson); u = i % 10; mike_tyson = '0' + u; doggy.push_back(mike_tyson); } else { u = 0; mike_tyson = '0' + u; doggy.push_back(mike_tyson); u = i / 1; mike_tyson = '0' + u; doggy.push_back(mike_tyson); } doggy.push_back(58); for (int heyhey = 2; heyhey < kitty.size() - 2; heyhey += 1) { doggy.push_back(kitty[heyhey]); } doggy.push_back(58); for (int holahola = 4; holahola < kitty.size(); holahola += 1) { doggy.push_back(kitty[holahola]); } kitty.erase(kitty.begin(), kitty.end()); kitty.resize(0); s = ""; s = s.append(doggy.begin(), doggy.begin() + doggy.size()); doggy.erase(doggy.begin(), doggy.end()); doggy.resize(0); cout << s << endl; printf("-->"); cin >> s; } while (s != "exit"); printf("\n"); system("pause"); return 0; }
5dc73760ffe1bca0b5d9323be2f2e687ed6fab73
74450d2e5c5d737ab8eb3f3f2e8b7d2e8b40bb5e
/github_cpp/13/120.cpp
402dd62bbaf63b744300a279dab1fbf5c7fb7525
[]
no_license
ulinka/tbcnn-attention
10466b0925987263f722fbc53de4868812c50da7
55990524ce3724d5bfbcbc7fd2757abd3a3fd2de
refs/heads/master
2020-08-28T13:59:25.013068
2019-05-10T08:05:37
2019-05-10T08:05:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
120.cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: void bubbleSort(vector<int> &arr) { int n =arr.size(); bool swapped = true; int j = 0; while (swapped) { swapped = false; j++; for (int i = 0; i < n - j; i++) { if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i+1]); swapped = true; } } } } }; int main(){ vector<int> nums={1,4,2,5,3,7,6,9}; Solution ss; ss.bubbleSort(nums); for(auto it : nums){ cout<<it<<" "; } cout<<endl; return 0; }
79fd2a4b86d54e6c6a631f73205ef6f8bba8568e
9b1639af63f7fc82f0e488b452dee0cb7ae22a3b
/Consumer/r12.0.6/src/UI/NavShellExtHelper/IEToolBandHelper.h
5beafacf047733aef595e901f0cb143e702f6a13
[]
no_license
ExpLife/Norton_AntiVirus_SourceCode
af7cd446efb2f3a10bba04db8e7438092c7299c0
b90225233fa7930d2ef7922080ed975b7abfae8c
refs/heads/master
2017-12-19T09:15:25.150463
2016-10-03T02:33:34
2016-10-03T02:33:34
76,859,815
2
4
null
2016-12-19T12:21:02
2016-12-19T12:21:01
null
UTF-8
C++
false
false
1,261
h
IEToolBandHelper.h
// IEToolBandHelper.h : Declaration of the CIEToolBandHelper #pragma once #include "resource.h" // main symbols #include "NavShellExtHelper.h" #include "avresbranding.h" // CIEToolBandHelper class ATL_NO_VTABLE CIEToolBandHelper : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CIEToolBandHelper, &CLSID_IEToolBandHelper>, public IIEToolBandHelper, public CHelper { public: CIEToolBandHelper() { } DECLARE_CLASSFACTORY_SINGLETON(CIEToolBandHelper) DECLARE_REGISTRY_RESOURCEID(IDR_IETOOLBANDHELPER) BEGIN_COM_MAP(CIEToolBandHelper) COM_INTERFACE_ENTRY(IIEToolBandHelper) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { CBrandingRes BrandRes; m_csProductName = BrandRes.ProductName(); return S_OK; } void FinalRelease() { } HRESULT _Error(int iId, const IID& cGuid) { return Error(iId,cGuid); } HRESULT _Error(CString csError, const IID& cGuid) { return Error(csError,cGuid); } public: STDMETHOD(onActivityLog)(void); STDMETHOD(onVirusDef)(void); STDMETHOD(navigate2NMAINPanel)(BSTR bstrPanelName); STDMETHOD(onQuarantine)(void); }; OBJECT_ENTRY_AUTO(__uuidof(IEToolBandHelper), CIEToolBandHelper)
05710df1fbdcbda17fbb9a5d90d30584b67cdf2c
a57d8437088ac1eb627169ed82c4bbc8e8f3447a
/Kernel_Linux/ss/src/core/client_thread_pool.cc
b2cc974257a43c14c41e69ff952ce6d0c7c1dd7c
[]
no_license
linchendev/kernel
7a74ac4ab5fddaede0f7eb94527fd2e60ba147cc
3f5e76dbb15bef9a57dcbd1e924e38ac3bf1a15b
refs/heads/master
2021-05-26T17:27:43.499709
2013-08-21T09:22:54
2013-08-21T09:22:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
815
cc
client_thread_pool.cc
// // core - server core source code. // // $Rev: 6033 $ // $Author: $ // $Date: 2012-03-16 14:43:23 +0800 (周五, 2012-03-16) $ // // Define class ClientThreadPool. // #include "core/client_thread_pool.h" #include "core/tcp_client.h" namespace core { ClientThreadPool::ClientThreadPool() {} ClientThreadPool::~ClientThreadPool() {} bool ClientThreadPool::Initialize() { // Client thread group. if(this->client_threads_.Initialize(CoreConfig::GetThread()->client_number_, "ClientThread") == false) { CoreLog(ERROR, "%s:%d (%s) Failed in initialize client_threads_", __FILE__, __LINE__, __FUNCTION__); return false; } return true; } void ClientThreadPool::Start() { this->client_threads_.Start(); } void ClientThreadPool::Stop() { this->client_threads_.Stop(); } } // namespace core