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
a4ee482da6ef86d07eed41725ee12614160cf888
9dab778aa8e22fc2095888e32b05375ac524c057
/FillArena.cpp
74f0f155bc10d16474f87b9d26665aa839e89c8c
[]
no_license
mukromka/sudoku
48caa493e22ccacfdf54e48a558489913bd5da4e
25717d3a08049c58f1734386f2432094729bf155
refs/heads/master
2023-06-13T06:21:03.671701
2021-07-04T18:40:40
2021-07-04T18:40:40
355,690,513
0
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
FillArena.cpp
#include "fillArena.h" FillArena::FillArena(Board& board, int x, int y, int input) { this->b = &board; this->x = x; this->y = y; this->input = input; }
1c8c9850426cf8ae8cbb4b699dc1652551a7bdc7
243699dc1fb966f69f983dd9cbc04d91fdd9f53b
/tests/ObjectFeatures/main.cpp
8f69827b10ed49c8ab63ad988f6297916343cb32
[]
no_license
jeandet/libCDFpp
3e9d709e708d6a2401c8f0a7bfadc444769fe1bd
d3b919ab56d59140cecb252825fc8b12eec072b2
refs/heads/master
2021-01-20T04:43:08.924474
2017-09-07T21:07:37
2017-09-07T21:07:37
89,721,837
0
0
null
null
null
null
UTF-8
C++
false
false
1,159
cpp
main.cpp
#include "gtest/gtest.h" #include "libCDF.h" namespace { class CdfTestObjectFeatures : public ::testing::Test { protected: CdfTestObjectFeatures() { // You can do set-up work for each test here. } virtual ~CdfTestObjectFeatures() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } }; }; TEST_F(CdfTestObjectFeatures, IsCopyable) { EXPECT_EQ(true, std::is_copy_constructible<Cdf>::value); EXPECT_EQ(true, std::is_copy_assignable<Cdf>::value); } TEST_F(CdfTestObjectFeatures, IsMoveable) { EXPECT_EQ(true, std::is_move_constructible<Cdf>::value); EXPECT_EQ(true, std::is_move_assignable<Cdf>::value); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
3ad418add8b1728140434887db282c010282559c
24c92888bb882378a91e6ef6e8f6ac797762c861
/Additional Problems/FloodFill.cpp
673f86e841e1a681c13a79a1a950543be4c26588
[]
no_license
karthikm15/USACO-Silver-Problems
b54cae9366397bb014607580ec163268e18ba1ec
fdc7928fce80050bd6c5bbc18ac8f223315a21e9
refs/heads/master
2020-12-04T14:41:59.388090
2020-09-13T14:12:24
2020-09-13T14:12:24
231,803,881
1
0
null
null
null
null
UTF-8
C++
false
false
3,788
cpp
FloodFill.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int N = 7; int M = 5; int arr[7][5] = {{0, 0, 1, 0, 1}, {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 1, 0}, {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}}; int arr2[7][5]; int arr_gs[7][5]; int arr_id[7][5]; int floodFill(int x, int y){ if (x < 0 || x >= N || y < 0 || y >= N){ return 0; } if (arr[x][y] != 0){ return 0; } arr[x][y] = 2; int res = 1; res += floodFill(x+1, y); res += floodFill(x-1, y); res += floodFill(x, y+1); res += floodFill(x, y-1); return res; } void h (int x, int y, int gs){ if (x < 0 || x >= N || y < 0 || y >= N){ return; } if (arr[x][y] != 2 || arr_gs[x][y] == gs){ return; } arr_gs[x][y] = gs; h(x+1, y, gs); h(x-1, y, gs); h(x, y+1, gs); h(x, y-1, gs); } void h_id (int x, int y, int gs){ if (x < 0 || x >= N || y < 0 || y >= N){ return; } if (arr[x][y] != 2 || arr_id[x][y] == gs){ return; } arr_id[x][y] = gs; h_id(x+1, y, gs); h_id(x-1, y, gs); h_id(x, y+1, gs); h_id(x, y-1, gs); } /* void a (int x, int y){ if (x<0 || x >=7 || y<0 || y>=7){ return; } if (arr[x][y] != 0 ){ return; } a(x, y+1); a(x, y-1); a(x+1, y); a(x-1,y); } */ int returnSum(int x, int y){ int sumF = 0; int id1, id2, id3, id4 = 0; if (!(x < 1) && (arr_gs[x-1][y] != 1)){ sumF += arr_gs[x-1][y]; id1 = arr_id[x-1][y]; } if (!(x>(N-1)) && (arr_id[x+1][y] != id1) && (arr_gs[x+1][y] != 1)){ sumF += arr_gs[x+1][y]; id2 = arr_id[x+1][y]; } if (!(y < 1) && (arr_id[x][y-1] != id1) && (arr_id[x][y-1] != id2) && (arr_gs[x][y-1] != 1)){ sumF += arr_gs[x][y-1]; id3 = arr_id[x][y-1]; } if (!(y>(N-1)) && (arr_id[x][y+1] != id1) && (arr_id[x][y+1] != id2) && (arr_id[x][y+1] != id3) && (arr_gs[x][y+1] != 1)){ sumF += arr_gs[x][y+1]; id4 = arr_id[x][y+1]; } return sumF; } void arrayH(){ arr_id[1][0] = 2; arr_id[1][1] = 2; arr_id[2][0] = 2; arr_id[3][0] = 2; } int main(){ for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ arr2[i][j] = arr[i][j]; arr_gs[i][j] = arr[i][j]; arr_id[i][j] = arr[i][j]; } } int id = 1; int gs, count, x; for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ if (arr[i][j] == 0){ gs = floodFill(i, j); h(i, j, gs); id++; h_id(i, j, id); } } } arrayH(); vector<int> sums; int count1 = 0; for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ int sum = 0; if (arr_id[i][j] == 1){ sum = returnSum(i, j); sums.push_back(sum); //cout << sum << " " << i << " " << j << endl; count1 += 1; } } } sort(sums.begin(), sums.end()); int max = sums.at(count1-1); /*for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ cout << arr_gs[i][j] << " "; } cout << endl; } cout << endl; for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ cout << arr_id[i][j] << " "; } cout << endl; } cout << endl;*/ cout << max; }
a30107167b6106c6bb1ac0182221fd6f68fe59ab
bb767bfc9db2b0ab7f24d3561b168a829c4eb0bc
/1st_Year/2nd_Semestre/PROG/Visual Studio/Programação orientada por classes/Exercicio_2/Exercicio_2/class.h
cb97f9638a90f88076eb973fc61ea1323dcaa811
[]
no_license
Hugomguima/FEUP
7e6e0faf5408d698a34c3b5aed977b20aa76c067
f26887e2b8e92e41ae5050515cd0b3cdf94d6476
refs/heads/master
2023-06-09T05:21:38.897094
2021-06-29T17:00:01
2021-06-29T17:00:01
272,567,282
0
0
null
null
null
null
UTF-8
C++
false
false
483
h
class.h
#ifndef STUDENT_H #define STUDENT_H #include<string> using namespace std; class Student { public: Student(); Student(const string &code, const string &name); void setGrades(double shortExam, double project, double exam); string GetCode() const; string GetName() const; int GetFinalGrade() const; bool isApproved(); static int weightShortExam, weightProject, weightExam; private: string code; string name; double shortExam, project, exam; int finalGrade; }; #endif
bc026c5c1de56b0bea9043b0fc524ca2cde755c5
f3793bdd88707f984568fbc64f82e18118703382
/LiGridUI/main.cpp
884a6d72fda3b44b27a61147f1178ec32ac263cf
[]
no_license
mastmees/ligrid
b82f3ab56eb8d24e1a8d34a46a02b39e1ce61e07
e8d629c146e552189c1f1717716de1f24fa6323c
refs/heads/master
2021-01-11T02:39:54.559302
2016-10-14T13:45:39
2016-10-14T13:45:39
70,913,649
0
0
null
null
null
null
UTF-8
C++
false
false
4,862
cpp
main.cpp
/* Proof of concept UI for LiGrid Copyright (c) 2009, Madis Kaal <mast@nomad.ee> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the involved organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../juce/juce.h" #include "MainComponent.h" #include "ConnectionThread.h" ConnectionThread Dataconnection; class HelloWorldWindow : public DocumentWindow { public: //============================================================================== HelloWorldWindow() : DocumentWindow (T("LightningDetector"), Colours::lightgrey, DocumentWindow::allButtons, true) { MainComponent* const contentComponent = new MainComponent(); setContentComponent (contentComponent, true, true); centreWithSize (getWidth(), getHeight()); setVisible (true); } ~HelloWorldWindow() { } //============================================================================== void closeButtonPressed() { JUCEApplication::quit(); } }; class JUCEHelloWorldApplication : public JUCEApplication { /* Important! NEVER embed objects directly inside your JUCEApplication class! Use ONLY pointers to objects, which you should create during the initialise() method (NOT in the constructor!) and delete in the shutdown() method (NOT in the destructor!) This is because the application object gets created before Juce has been properly initialised, so any embedded objects would also get constructed too soon. */ HelloWorldWindow* helloWorldWindow; public: //============================================================================== JUCEHelloWorldApplication() : helloWorldWindow (0) { // NEVER do anything in here that could involve any Juce function being called // - leave all your startup tasks until the initialise() method. } ~JUCEHelloWorldApplication() { // Your shutdown() method should already have done all the things necessary to // clean up this app object, so you should never need to put anything in // the destructor. // Making any Juce calls in here could be very dangerous... } //============================================================================== void initialise (const String& commandLine) { helloWorldWindow = new HelloWorldWindow(); /* ..and now return, which will fall into to the main event dispatch loop, and this will run until something calls JUCEAppliction::quit(). In this case, JUCEAppliction::quit() will be called by the hello world window being clicked. */ } void shutdown() { Dataconnection.Stop(); if (helloWorldWindow != 0) delete helloWorldWindow; } //============================================================================== const String getApplicationName() { return T("LightningDetector"); } const String getApplicationVersion() { return T("1.0"); } bool moreThanOneInstanceAllowed() { return false; } void anotherInstanceStarted (const String& commandLine) { } }; //============================================================================== // This macro creates the application's main() function.. START_JUCE_APPLICATION (JUCEHelloWorldApplication)
29f0eb99388a97b338bd3a7974ec54a6f1f8bf5f
39ddf42492e5387a22a8f7516fd0a9ae8998957a
/Primeri/Iklk/Iklk/Main.cpp
ec2d740cb30b363d748cf2c271bd762f343454f2
[]
no_license
nikolabojovic97/RacunarskaGrafika
2784ab3425164546c1bae3fe33344c170f22a9a1
3c74bfd9c884670be9cf2ccb88aed59eff6cf377
refs/heads/master
2023-04-19T09:03:15.419147
2021-05-03T12:00:52
2021-05-03T12:00:52
239,176,267
0
0
null
null
null
null
UTF-8
C++
false
false
5,640
cpp
Main.cpp
#include "GL/freeglut.h" #include "Vector4D.h" #include "Matrix4x4.h" #include <vector> using namespace std; #define PI 3.14159265359 #define MOVING_CONST 0.1; #define ROTATION_CONST PI / 180.0 int WINDOW_HEIGHT = 800; double ASP_RAT = 16.0 / 9.0; int FPS = 60; Vector4D cameraPosition(5.0, 5.0, 5.0, 1.0); Vector4D lookAt(0.0, 0.0, 0.0, 1.0); Vector4D lookUp(0.0, 1.0, 0.0, 1.0); Vector4D center(0.0, 0.0, 0.0, 1.0); Vector4D x(1.0, 0.0, 0.0, 0.0); Vector4D y(0.0, 1.0, 0.0, 0.0); Vector4D z(0.0, 0.0, 1.0, 0.0); vector<Vector4D> meta1; vector<Vector4D> meta2; vector<Vector4D> kupa1; vector<Vector4D> valjak1; vector<Vector4D> valjak2; int nPoints = 30; double rMete = 4.0; double hMete = 1.0; double d1 = 1.0; double d2 = 2.0; double d3 = 0.75; double d4 = 10.0; double d5 = 8.0; double d6 = 7.0; double d7 = 11.0; double r1 = 0.1; double r2 = 1; double r3 = 0.6; double alpha = 2.0 * PI / (nPoints * 1.0); double scale(double min, double max, double a, double b, double x) { return (b - a) * (x - min) / (max - min) + a; } void Transform(vector<Vector4D>& a, Matrix4x4& MT) { for (int i = 0; i < a.size(); i++) a[i] = MT.transformed(a[i]); } void Transform(vector<vector<Vector4D>>& a, Matrix4x4& MT) { for (int i = 0; i < a.size(); i++) Transform(a[i], MT); } void Draw(vector<Vector4D>& poly, int mode) { glBegin(mode); for (int i = 0; i < poly.size(); i++) glVertex3f(poly[i].x(), poly[i].y(), poly[i].z()); glEnd(); } void drawAxis() { //X glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(10.0, 0.0, 0.0); glEnd(); //Y glColor3f(0.0, 1.0, 0.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 10.0, 0.0); glEnd(); //Z glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 10.0); glEnd(); } void setCamera() { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(cameraPosition.x(), cameraPosition.y(), cameraPosition.z(), lookAt.x(), lookAt.y(), lookAt.z(), lookUp.x(), lookUp.y(), lookUp.z()); } void CreateMeta() { meta1.resize(nPoints + 2); meta2.resize(nPoints + 2); meta1[0] = Vector4D(0.0, 0.0, 0.0, 1.0); for (int i = 0; i <= nPoints; i++) meta1[i + 1] = Vector4D(cos(i * alpha) * rMete, 0.0, sin(i * alpha) * rMete, 1.0); meta2 = meta1; Matrix4x4 MT; MT.loadTranslate(0.0, hMete, 0.0); Transform(meta2, MT); } void DrawMeta() { glColor3f(1.0, 0.0, 0.0); Draw(meta1, GL_POLYGON); Draw(meta2, GL_POLYGON); vector<Vector4D> poly; poly.resize(4); glColor3f(0.9, 0.1, 0.1); for (int i = 1; i <= nPoints; i++) { poly[0] = meta1[i]; poly[1] = meta2[i]; poly[2] = meta2[i+1]; poly[3] = meta1[i+1]; Draw(poly, GL_POLYGON); } } void CreateKupa() { kupa1.resize(nPoints + 2); kupa1[0] = Vector4D(0.0, 0.0, 0.0, 1.0); for(int i = 0; i <= nPoints; i++) kupa1[i + 1] = Vector4D(cos(i * alpha) * r1, d1, sin(i * alpha) * r1, 1.0); } void DrawKupa(vector<Vector4D> kupa1) { vector<Vector4D> poly; poly.resize(3); glColor3f(0.9, 0.1, 0.1); for (int i = 1; i <= nPoints; i++) { poly[0] = kupa1[i]; poly[1] = kupa1[0]; poly[2] = kupa1[i + 1]; Draw(poly, GL_POLYGON); } } void CreateValjak() { valjak1.resize(nPoints + 2); valjak2.resize(nPoints + 2); valjak1[0] = Vector4D(0.0, 0.0, 0.0, 1.0); for (int i = 0; i <= nPoints; i++) valjak1[i + 1] = Vector4D(cos(i * alpha) * r1, 0.0, sin(i * alpha) * r1, 1.0); valjak2 = valjak1; Matrix4x4 MT; MT.loadTranslate(0.0, d1, 0.0); Transform(valjak1, MT); MT.loadTranslate(0.0, d1 + d2, 0.0); Transform(valjak2, MT); } void DrawValjak(vector<Vector4D> valjak1, vector<Vector4D> valjak2) { vector<Vector4D> poly; poly.resize(4); glColor3f(0.9, 0.1, 0.1); for (int i = 1; i <= nPoints; i++) { poly[0] = valjak1[i]; poly[1] = valjak2[i]; poly[2] = valjak2[i + 1]; poly[3] = valjak1[i + 1]; Draw(poly, GL_POLYGON); } } void DrawKupa2() { } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_VIEWPORT); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(80.0f, 1.0, 0.1f, 50.0f); setCamera(); drawAxis(); //DrawMeta(); DrawKupa(kupa1); DrawValjak(valjak1, valjak2); glutSwapBuffers(); } void reshape(int w, int h) { if (w < h) WINDOW_HEIGHT = w / ASP_RAT; else WINDOW_HEIGHT = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40.0, ASP_RAT, 0.1, 50.0); setCamera(); } void mouseClicked(int button, int state, int x, int y) { } void keyPressed(unsigned char key, int x, int y) { switch (key) { case 'w': break; case 's': break; case 'a': break; case 'd': break; case '4': break; case '6': break; case '8': break; case '5': break; } glutPostRedisplay(); } void timer(int v) { } void init() { glClearColor(0.0, 0.0, 0.0, 1.0); glShadeModel(GL_FLAT); glEnable(GL_DEPTH_TEST); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(WINDOW_HEIGHT * ASP_RAT, WINDOW_HEIGHT); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutCreateWindow("Kolokvijum"); init(); CreateMeta(); CreateKupa(); CreateValjak(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouseClicked); glutKeyboardFunc(keyPressed); glutTimerFunc(1000 / FPS, timer, 0); glutMainLoop(); return 0; }
76a28a3a4bbbb985ca5db5a65a0de8b97ebd1c8c
314609125e587610353ad0fe67f58bdf45b0c6e1
/Game/Player/Enemy.cpp
535860c785bebb15e8722c67e936e293f2052b94
[]
no_license
Epidilius/ZeldaStyleAdventureGame
1e1b71cf2914c1ca5ea1ff803bf10d172e74b562
bd2bbc89f5acf07c8c89f6301aef326fdeead238
refs/heads/master
2021-01-10T17:15:54.039969
2015-09-27T22:31:38
2015-09-27T22:31:38
43,267,623
0
0
null
null
null
null
UTF-8
C++
false
false
14,775
cpp
Enemy.cpp
// // Enemy.cpp // GameDev2D // // Created by Bradley Flood on 2014-10-20. // Copyright (c) 2014 Algonquin College. All rights reserved. // #include "Enemy.h" #include "Hero.h" #include "../World.h" #include "../SubSection.h" #include "../Tiles/Tile.h" #include "../PathFinding/PathFinder.h" #include "../Pickups/HeartPickup.h" #include "../Pickups/GreenRupeePickup.h" #include "../Pickups/BlueRupeePickup.h" #include "../Pickups/BombPickup.h" #include "../../Source/UI/UI.h" #include "../../Source/Animation/Random.h" #include "../../Source/Audio/Audio.h" namespace GameDev2D { Enemy::Enemy(World* aWorld, Tile* aSpawnTile, string aEnemyType) : Player(aEnemyType, aWorld), m_PathFinder(nullptr), m_EnemyState(EnemyUnknown), m_Random(nullptr), m_PathIndex(0), m_InvincibilityTimer(nullptr), m_EnemyHitAudio(nullptr), m_EnemyDeathAudio(nullptr) { //Set the local position of the hero, based on the center of the spawn tile SetLocalPosition(aSpawnTile->GetCenter(true)); //Create the path finder object SubSection* subSection = m_World->GetSubSectionForPlayer(this); m_PathFinder = new PathFinder(subSection); //Cycle through and create the walking and attacking sprites for all 4 directions if(aEnemyType != "EnemyBlue") { for(unsigned int i = 0; i < PLAYER_DIRECTION_COUNT; i++) { //Create the walking sprite for the current direction m_WalkingSprite[i] = new Sprite("MainAtlas", ENEMY_WALKING_ATLAS_KEY_1[i]); m_WalkingSprite[i]->AddFrame("MainAtlas", ENEMY_WALKING_ATLAS_KEY_2[i]); m_WalkingSprite[i]->SetAnchorPoint(0.5f, 0.5f); m_WalkingSprite[i]->SetDoesLoop(true); m_WalkingSprite[i]->SetIsEnabled(false); AddChild(m_WalkingSprite[i], false); SetHealthCapacity(ENEMY_HEALTH_CAPACITY); SetHealth(ENEMY_HEALTH_CAPACITY); } } else { for(unsigned int i = 0; i < PLAYER_DIRECTION_COUNT; i++) { //Create the walking sprite for the current direction m_WalkingSprite[i] = new Sprite("MainAtlas", ENEMY_BLUE_WALKING_ATLAS_KEY_1[i]); m_WalkingSprite[i]->AddFrame("MainAtlas", ENEMY_BLUE_WALKING_ATLAS_KEY_2[i]); m_WalkingSprite[i]->SetAnchorPoint(0.5f, 0.5f); m_WalkingSprite[i]->SetDoesLoop(true); m_WalkingSprite[i]->SetIsEnabled(false); AddChild(m_WalkingSprite[i], false); SetHealthCapacity(ENEMY_BLUE_HEALTH_CAPACITY); SetHealth(ENEMY_BLUE_HEALTH_CAPACITY); } } //Create the random number generator object m_Random = new Random(); m_Random->RandomizeSeed(); //Set the enemy's state to idle SetState(EnemyIdle); //Create the invincibility timer m_InvincibilityTimer = new Timer(ENEMY_INVINCIBILITY_DURATION); // Set Audio m_EnemyDeathAudio = new Audio("EnemyDeath", "wav", false, false); m_EnemyHitAudio = new Audio("EnemyHit", "wav", false, false); } Enemy::~Enemy() { //Delete the path finder object SafeDelete(m_PathFinder); //Delete the random number generator object SafeDelete(m_Random); //Cycle through and delete the enemy Sprites for(unsigned int i = 0; i < PLAYER_DIRECTION_COUNT; i++) { SafeDelete(m_WalkingSprite[i]); } SafeDelete(m_InvincibilityTimer); SafeDelete(m_EnemyDeathAudio); SafeDelete(m_EnemyHitAudio); } void Enemy::Update(double aDelta) { if(IsEnabled() == true) { m_InvincibilityTimer->Update(aDelta); //Get the hero and the tile the hero is on Hero* hero = m_World->GetHero(); Tile* heroTile = hero->GetTile(); //If the hero tile is the same tile the enemy is on, apply some damage if(heroTile == GetTile()) { hero->ApplyDamage(GetAttackDamage()); } //Cache the tile before we update the player's position Tile* previousTile = GetTile(); //Update the base class Player::Update(aDelta); //Check to see if the player has changed tiles since the start of the update method Tile* currentTile = GetTile(); if(currentTile != previousTile) { HasChangedTiles(currentTile, previousTile); } } } void Enemy::DebugDraw() { #if DEBUG m_PathFinder->DebugDraw(); #endif } void Enemy::Reset() { //Reset the enemy state SetState(EnemyIdle); //Reset Health Capacity SetHealth(ENEMY_HEALTH_CAPACITY); //Reset the base class Player::Reset(); } void Enemy::SetState(unsigned int aState) { //Set the enemy state m_EnemyState = (EnemyState)aState; // Log the enemy State TODO:Delete Log("Enemy set state: %u", m_EnemyState); //Refresh the active sprite RefreshActiveSprite(); //Handle the hero state switch switch (aState) { case EnemyIdle: { if(IsEnabled() == false) { //Ensure the active sprite is enabled m_ActiveSprite->SetIsEnabled(true); //Ensure the enemy object is enabled SetIsEnabled(true); } //Delay call the change state method DelayGameObjectMethod(&Enemy::ChangeState, 1.0f); } break; case EnemySearching: { //Get the enemy's current subsection and the hero's SubSection* subSection = GetSubSection(); SubSection* heroSubSection = m_World->GetHero()->GetSubSection(); //Ensure the hero is on the subsection as our enemy if(subSection == heroSubSection) { //Find the path Tile* destination = m_World->GetHero()->GetTile(); bool pathFound = m_PathFinder->FindPath(GetTile(), destination); //Was a path found if(pathFound == true) { StartWalking(); } else { SetState(StateIdle); } } else { SetState(StateIdle); } } break; case EnemyAttacking: { DelayGameObjectMethod(&Enemy::FireProjectile, ENEMY_PROJECTILE_DELAY); } break; case EnemyWalking: { //Get the current subsection SubSection* subSection = GetSubSection(); m_Random->RandomizeSeed(); //Find the path Tile* destination = nullptr; do { int randomTileIndex = m_Random->RandomInt(subSection->GetNumberOfTiles()); destination = subSection->GetTileForIndex(randomTileIndex); } while (!destination->IsWalkable()); bool pathFound = m_PathFinder->FindPath(GetTile(), destination); //Was a path found if (pathFound == true) { StartWalking(); } else { SetState(StateIdle); } } break; case EnemyDead: { //Disable the active sprite m_ActiveSprite->SetIsEnabled(false); //Disable the enemy object SetIsEnabled(false); } break; default: break; } } bool Enemy::IsInvincible() { return m_InvincibilityTimer->IsRunning(); } void Enemy::ApplyDamage(unsigned int aAttackDamage) { Player::ApplyDamage(aAttackDamage); m_EnemyHitAudio->Play(); //If there is still health left, reset the invincibility timer if (GetHealth() > 0) { m_InvincibilityTimer->Reset(true); } } void Enemy::HasDied() { //Set the enemy state to dead SetState(EnemyDead); // Play death sound m_EnemyDeathAudio->Play(); //Drop an random item pickup m_Random->RandomizeSeed(); unsigned int value = m_Random->RandomRange(0, 100); // if 1 heart (so 2) 50 drop heart, 50 drop nothing // if full health, 50 nothing, 20 green ruppe, 20 bomb, 10 blue rupee // else 15 heart, 15 green rupee, 15 bomb, 5 blue rupee Hero* hero = m_World->GetHero(); if (hero->GetHealth() <= 2) { if (value < 50) { GetTile()->AddPickup(new HeartPickup()); } } else if (hero->GetHealth() == hero->GetHealthCapacity()) { if (value < 20) { GetTile()->AddPickup(new GreenRupeePickup()); } else if (value < 40) { GetTile()->AddPickup(new BombPickup()); } else if (value < 50) { GetTile()->AddPickup(new BlueRupeePickup()); } } else { if (value < 15) { GetTile()->AddPickup(new HeartPickup()); } else if (value < 30) { GetTile()->AddPickup(new GreenRupeePickup()); } else if (value < 45) { GetTile()->AddPickup(new BombPickup()); } else if (value < 50) { GetTile()->AddPickup(new BlueRupeePickup()); } } } void Enemy::StartWalking() { //Refresh the A* debug drawing if the flags are set if((GetSubSection()->GetDebugDrawFlags() & DebugDrawPathFindingScores) > 0) { GetSubSection()->RefreshDebugDraw(); } //Reset the path index m_PathIndex = 0; //Call the walk method, this will be called on a recursive delay until the end of the path is reached Walk(); } void Enemy::Walk() { if(m_EnemyState == EnemySearching || m_EnemyState == EnemyWalking) { if(m_PathFinder->GetPathSize() > 0) { PathNode* pathNode = m_PathFinder->GetPathNodeAtIndex(m_PathIndex); Tile* tile = pathNode->GetTile(); //Get the current position and the destination position and calculate the direction vec2 currentPosition = GetWorldPosition(); vec2 destinationPosition = tile->GetCenter(true); vec2 direction = destinationPosition - currentPosition; //Normalize the direction vector direction = normalize(direction); //Set the enemy's new direction and refresh the active sprite SetDirection(direction); RefreshActiveSprite(); //Calculate the distance and duration float distance = sqrtf((destinationPosition.x - currentPosition.x) * (destinationPosition.x - currentPosition.x) + (destinationPosition.y - currentPosition.y) * (destinationPosition.y - currentPosition.y)); double duration = distance / ENEMY_WALKING_SPEED; //Animate the enemy to the center of the tile SetLocalPosition(tile->GetCenter(true), duration); //Increment the path index m_PathIndex++; //If the path index has reached the end point, set the state to idle if(m_PathIndex == m_PathFinder->GetPathSize()) { //Once the enemy has stopped walking, set the enemy state to idle SetState(EnemyIdle); } else { //Recursively call the walk function with a delay DelayGameObjectMethod(&Enemy::Walk, duration); } } else { SetState(EnemyIdle); } } } void Enemy::FireProjectile() { //Ensure the enemy still has some health if(IsEnabled()) { GetSubSection()->FireProjectile(GetWorldPosition(), GetDirection(), ENEMY_PROJECTILE_SPEED, ENEMY_PROJECTILE_ATTACK_DAMAGE); //Then set the enemy state back to the idle SetState(EnemyIdle); } } void Enemy::ChangeState() { unsigned int state = m_EnemyState; m_Random->RandomizeSeed(); while (state == m_EnemyState) { state = m_Random->RandomRange(0, EnemyStateCount); } // Set the new state SetState(state); } void Enemy::RefreshActiveSprite() { //Disable the active Sprite if(m_ActiveSprite != nullptr) { m_ActiveSprite->SetIsEnabled(false); } //Set the active Sprite based on the direction m_ActiveSprite = m_WalkingSprite[m_DirectionIndex]; //Set the frame speed m_ActiveSprite->SetFrameSpeed(ENEMY_WALKING_ANIMATION_FRAME_SPEED); //Reset the frame index to zero and enable it m_ActiveSprite->SetFrameIndex(0); m_ActiveSprite->SetIsEnabled(true); } }
1c956b238e4da6475a9c3e8734d7f0bd78fa2919
8eee0535579b2e1c82285a6f4341a3e6de3cda65
/LList.cpp
7eb7c082ceedf8df5886411e58ae5274b1445deb
[]
no_license
violet009200/NewCollectionClass
3ca2f35577dfe3979687993e2d45f13735109a67
be1721c512a95b91fed7c1388d02066d6a7acfca
refs/heads/master
2021-01-09T21:54:12.862001
2015-12-02T01:30:13
2015-12-02T01:30:13
46,678,511
0
0
null
null
null
null
UTF-8
C++
false
false
3,382
cpp
LList.cpp
#include "LList.h" LList::LList(){ head = (node*)NULL; } LList::~LList(){ cout<<" ~LList()"<<endl; this->deleteAll(); } //member function Collection* LList::add(int elem, int position){ cout<<" LList add() is called"<<endl; node* newNode = new node(); newNode->value = elem; size_++; if(position == 0){ //index = 0; if(this->head == NULL){ head = newNode; } else{ newNode->next = head; head = newNode; } return this; } else{ node* curNode = new node(); int count = 1; curNode = head; while(count!=position){ curNode = curNode->next; count++; } newNode->next = curNode->next; curNode->next = newNode; } return this; } Collection* LList::remove(int elem){ cout<<" LList remove() is called"<<endl; node* prev = NULL; node* cur = this->head; if(cur == NULL) return 0; else{ //find node while(cur->value != elem){ if(cur->next != NULL){ prev = cur; cur = cur->next; } else //cannot find node { cout<<"Cannot find node"<<endl; return this; } } if(cur->next == NULL){ prev->next = NULL; delete cur; size_--; return this; } else if(cur->next != NULL){ if(prev!=NULL) prev->next = cur->next; delete cur; size_--; return this; } }//else } //take index return the element at the index int& LList::operator[](int index){ cout<< " LList operator[] is called"<<endl; cout<<" finding "<<index<<"th elem"<<endl; //exception throw if(index < 0 || index > size_ ){ throw invalid_argument( "Index is out of bound!" ); } if(this->head == NULL){ cerr<<"list is empty"<<endl; exit(0); } int i=0; node* cur = this->head; while(i<index){ if(cur == NULL) { cerr<<"cur node is empty"<<endl; exit(0); } cur = cur->next; i++; } return cur->value; } //deepcopy void LList::operator=(Collection* llist){ cout<< " LList operator=(Collection*) is called"<<endl; if(llist == NULL){ cerr<<"LList is Empty"<<endl; return; } //delete current LList this->deleteAll(); //LList* newList = new LList(); node* inputNode = ((LList*)llist)->head; node* newNode = new node(); //set head newNode->value = inputNode->value; this->head = newNode; inputNode = inputNode->next; //set size_ this->setsize(llist->getsize()); newNode = this->head; while(inputNode != NULL){ newNode = newNode->next = new node(); //copy all node until inputNode is NULL newNode->value = inputNode->value; //newNode = newNode->next; inputNode = inputNode->next; } //set last node of new newNode->next = NULL; } LList* LList::copy(){ /*cout<<" LList copy() is called"<<endl; LList* newList = (*this).copy(); return newList;*/ return this; } void LList::deleteAll(){ //cout<<" LList: delete All node"<<endl; if(this->head != NULL){ node* curNode = this->head; node* nextNode = NULL; while(curNode->next != NULL){ nextNode = curNode -> next; delete curNode; curNode = nextNode; } delete curNode; } this->size_ = 0; } void LList::display(){ node* cur = this->head; while(cur != NULL){ cout<<cur->value<<" "; cur = cur->next; } cout<<"[size of LList: "<<size_<<" ]"<<endl; cout<<endl; } int LList::getSize(){ return size_; }
8156975b8a06528e9af55e4530fed02b37794174
8adf44127fb9a58a548b8162490010ec6ceef2f0
/Alpha/Source/Player.cpp
0a515ce3391f6ba7da6780703c36c2f0498b7763
[]
no_license
Chongjx/NYP-framework
365839572742f09d02e3c8e09b599e31498e4d53
df1b0379e41b6f93b3a2ed8c859c117408aeccaa
refs/heads/master
2022-12-29T09:06:24.489678
2020-10-22T05:46:29
2020-10-22T05:46:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,709
cpp
Player.cpp
#include "Player.h" CPlayer* CPlayer::instance = 0; CPlayer* CPlayer::GetInstance() { if (instance == 0) instance = new CPlayer(); return instance; } CPlayer::CPlayer() { } CPlayer::~CPlayer() { } void CPlayer::Init(Vector3 currentPos, Vector3 currentDir, Mesh* playerMesh) { playerNode = new SceneNode(); GO3D_Player = new GameObject3D(); playerNode->SetGameObject(GO3D_Player); playerNode->setActive(true); playerNode->GetGameObject()->setPosition(currentPos); playerNode->GetGameObject()->setMesh(playerMesh); playerNode->GetGameObject()->setName("Player"); playerNode->GetGameObject()->setUpdate(true); playerNode->GetGameObject()->setRender(true); playerNode->GetGameObject()->setCollidable(true); } //Dir void CPlayer::SetDirection(Vector3 newDirection) { this->direction = newDirection; } void CPlayer::SetDirection_X(float newDir_X) { this->direction.x = newDir_X; } void CPlayer::SetDirection_Y(float newDir_Y) { this->direction.y = newDir_Y; } void CPlayer::SetDirection_Z(float newDir_Z) { this->direction.z = newDir_Z; } Vector3 CPlayer::GetDirection(void) { return direction; } //Angle float CPlayer::GetAngle(void) { return angle; } void CPlayer::SetAngle(float newAngle) { this->angle = newAngle; } //Physics void CPlayer::SetGravity(float newGravity) { this->gravity = newGravity; } float CPlayer::GetGravity(void) { return gravity; } void CPlayer::SetJumpSpeed(float newJSpeed) { this->jumpSpeed = newJSpeed; } float CPlayer::GetJumpSpeed(void) { return jumpSpeed; } void CPlayer::SetMoveSpeed(float newMSpeed) { this->moveSpeed = newMSpeed; } float CPlayer::GetMoveSpeed(void) { return moveSpeed; } void CPlayer::SetMoveSpeedMult(float newMSpeedMult) { this->moveSpeed_Mult = newMSpeedMult; } float CPlayer::GetMoveSpeedMult(void) { return moveSpeed_Mult; } bool CPlayer::GetInAir(void) { return inAir; } SceneNode* CPlayer::GetNode(void) { return playerNode; } //Update void CPlayer::Update(double dt, float CamAngle) { UpdateMovement(dt); } void CPlayer::UpdateMovement(double dt) { force.x = moveSpeed * moveSpeed_Mult; force.z = moveSpeed * moveSpeed_Mult; orientation = Math::DegreeToRadian(angle); direction.x = sinf(orientation); direction.z = cosf(orientation); Vector3 acceleration = force * (1.f / mass); velocity.x = sinf(orientation) * acceleration.x; velocity.z = cosf(orientation) * acceleration.z; playerNode->GetGameObject()->addPosition(velocity * (float)dt); } //Game related void CPlayer::SetHealth(int newHealth) { this->health = newHealth; } void CPlayer::SetLives(int newLives) { this->lives = newLives; } int CPlayer::GetHealth(void) { return health; } int CPlayer::GetLives(void) { return lives; }
ff84ea9d4522d9414ac347d56d6ec5a68021d0d7
7d80c642c8fbdafb8ed7ee3642167e1b0e98ef37
/data/tplcache/0f498ca7fc1bc9fa662208dd84d374f7.inc
473e94147f16ffae335ad95358cfcfc2a8c9d410
[]
no_license
WishQAQ/templated-cms52
ecd16eab26e6b7335a49ea82ae8278d17df381ce
05f108d57a35719e5d4559a51c8e14bcb127fe48
refs/heads/master
2021-08-30T05:40:56.526949
2017-12-16T08:22:31
2017-12-16T08:22:31
114,445,365
0
0
null
null
null
null
UTF-8
C++
false
false
968
inc
0f498ca7fc1bc9fa662208dd84d374f7.inc
{dede:pagestyle maxwidth='800' pagepicnum='12' ddmaxwidth='200' row='3' col='4' value='2'/} {dede:img ddimg='/uploads/allimg/151004/1-1510041K224.jpg' text='' width='739' height='581'} /uploads/allimg/151004/1-1510041K224.jpg {/dede:img} {dede:img ddimg='/uploads/allimg/151004/1-1510041K227.jpg' text='' width='738' height='596'} /uploads/allimg/151004/1-1510041K227.jpg {/dede:img} {dede:img ddimg='/uploads/allimg/151004/1-1510041K229.jpg' text='' width='761' height='557'} /uploads/allimg/151004/1-1510041K229.jpg {/dede:img} {dede:img ddimg='/uploads/allimg/151004/1-1510041K233.jpg' text='' width='730' height='485'} /uploads/allimg/151004/1-1510041K233.jpg {/dede:img} {dede:img ddimg='/uploads/allimg/151004/1-1510041K236.jpg' text='' width='709' height='597'} /uploads/allimg/151004/1-1510041K236.jpg {/dede:img} {dede:img ddimg='/uploads/allimg/151004/1-1510041K239.jpg' text='' width='599' height='512'} /uploads/allimg/151004/1-1510041K239.jpg {/dede:img}
5066f6bbc8981417fbb42d3cc77dae688bab62b0
188fb8ded33ad7a2f52f69975006bb38917437ef
/Fluid/processor3/0.63/meshPhi
a3f105b53da6f1cc3a541c91c4243d4f4c1e7b74
[]
no_license
abarcaortega/Tuto_2
34a4721f14725c20471ff2dc8d22b52638b8a2b3
4a84c22efbb9cd2eaeda92883343b6910e0941e2
refs/heads/master
2020-08-05T16:11:57.674940
2019-10-04T09:56:09
2019-10-04T09:56:09
212,573,883
0
0
null
null
null
null
UTF-8
C++
false
false
13,290
meshPhi
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "0.63"; object meshPhi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 881 ( -9.37104e-07 1.46214e-06 -1.94177e-06 4.08326e-06 -2.98727e-06 6.12253e-06 -4.03622e-06 7.55443e-06 -5.00575e-06 8.43514e-06 -5.80262e-06 8.84576e-06 -6.35128e-06 8.876e-06 -6.60796e-06 8.61199e-06 -6.56328e-06 8.12898e-06 -6.23788e-06 7.48844e-06 -5.67507e-06 6.73896e-06 -4.93338e-06 5.91944e-06 -4.08002e-06 5.06307e-06 -3.18502e-06 4.20114e-06 -2.31539e-06 3.365e-06 -1.52936e-06 2.58576e-06 -8.71006e-07 1.89175e-06 -3.66132e-07 1.30491e-06 -2.06212e-08 8.37373e-07 1.78029e-07 4.8966e-07 2.57274e-07 -9.14119e-07 2.93416e-06 -1.89683e-06 8.19479e-06 -2.92919e-06 1.22887e-05 -3.97227e-06 1.51644e-05 -4.94044e-06 1.6935e-05 -5.73766e-06 1.77639e-05 -6.28633e-06 1.78314e-05 -6.54154e-06 1.73099e-05 -6.49333e-06 1.63499e-05 -6.16221e-06 1.50733e-05 -5.59155e-06 1.35765e-05 -4.84012e-06 1.19362e-05 -3.97596e-06 1.02181e-05 -3.07058e-06 8.48461e-06 -2.19301e-06 6.79906e-06 -1.40359e-06 5.22513e-06 -7.4796e-07 3.82139e-06 -2.52327e-07 2.63362e-06 7.85482e-08 1.68755e-06 2.59807e-07 9.85004e-07 5.16942e-07 -8.56074e-07 4.42225e-06 -1.78948e-06 1.23522e-05 -2.78343e-06 1.85265e-05 -3.79759e-06 2.28681e-05 -4.744e-06 2.55485e-05 -5.52402e-06 2.68148e-05 -6.05808e-06 2.69378e-05 -6.29997e-06 2.6176e-05 -6.23885e-06 2.47534e-05 -5.89471e-06 2.28511e-05 -5.31064e-06 2.06111e-05 -4.54558e-06 1.8147e-05 -3.66901e-06 1.55561e-05 -2.7552e-06 1.29324e-05 -1.87666e-06 1.03727e-05 -1.09701e-06 7.97597e-06 -4.63668e-07 5.8342e-06 -2.05544e-09 4.02011e-06 2.86663e-07 2.57531e-06 4.23479e-07 1.50396e-06 7.92861e-07 -7.67781e-07 5.93214e-06 -1.62251e-06 1.65722e-05 -2.55018e-06 2.48634e-05 -3.50957e-06 3.07036e-05 -4.41123e-06 3.43251e-05 -5.15419e-06 3.60596e-05 -5.65698e-06 3.62683e-05 -5.87208e-06 3.5294e-05 -5.78722e-06 3.34325e-05 -5.42159e-06 3.09207e-05 -4.81778e-06 2.79442e-05 -4.03474e-06 2.46523e-05 -3.14422e-06 2.11733e-05 -2.22486e-06 1.7633e-05 -1.35444e-06 1.41645e-05 -6.01106e-07 1.09056e-05 -1.4168e-08 7.98578e-06 3.8335e-07 5.5081e-06 5.97e-07 3.53407e-06 6.57875e-07 2.07254e-06 1.10667e-06 -6.50225e-07 7.47055e-06 -1.39962e-06 2.08744e-05 -2.2375e-06 3.13303e-05 -3.12185e-06 3.87125e-05 -3.96177e-06 4.33167e-05 -4.65311e-06 4.55605e-05 -5.1119e-06 4.58951e-05 -5.28904e-06 4.47458e-05 -5.17006e-06 4.24779e-05 -4.7735e-06 3.9382e-05 -4.14167e-06 3.5681e-05 -3.33329e-06 3.15537e-05 -2.42376e-06 2.71617e-05 -1.4985e-06 2.26669e-05 -6.42918e-07 1.8242e-05 6.84703e-08 1.40693e-05 5.84238e-07 1.0321e-05 8.85412e-07 7.1363e-06 9.88445e-07 4.5995e-06 9.40392e-07 2.72424e-06 1.489e-06 -5.04121e-07 9.04406e-06 -1.12253e-06 2.52775e-05 -1.84794e-06 3.79571e-05 -2.6374e-06 4.69381e-05 -3.39934e-06 5.25818e-05 -4.02509e-06 5.5385e-05 -4.42722e-06 5.58878e-05 -4.55511e-06 5.46012e-05 -4.39202e-06 5.19574e-05 -3.95405e-06 4.82985e-05 -3.2832e-06 4.38803e-05 -2.44108e-06 3.89066e-05 -1.50845e-06 3.35721e-05 -5.79425e-07 2.80789e-05 2.50387e-07 2.26454e-05 8.98508e-07 1.75044e-05 1.31188e-06 1.28782e-05 1.47887e-06 8.94732e-06 1.43297e-06 5.81925e-06 1.24387e-06 3.50939e-06 1.98707e-06 -3.30637e-07 1.06613e-05 -7.93485e-07 2.98051e-05 -1.3866e-06 4.47772e-05 -2.06387e-06 5.54177e-05 -2.72997e-06 6.21547e-05 -3.27442e-06 6.55622e-05 -3.60736e-06 6.62716e-05 -3.67509e-06 6.48805e-05 -3.45847e-06 6.18857e-05 -2.96966e-06 5.7676e-05 -2.25047e-06 5.2542e-05 -1.36799e-06 4.6716e-05 -4.10493e-07 4.04217e-05 5.16909e-07 3.39001e-05 1.30591e-06 2.74199e-05 1.865e-06 2.12704e-05 2.14107e-06 1.57294e-05 2.13516e-06 1.10211e-05 1.90524e-06 7.27604e-06 1.55075e-06 4.50858e-06 2.67119e-06 -1.31806e-07 1.23259e-05 -4.15263e-07 3.44655e-05 -8.57179e-07 5.17967e-05 -1.40657e-06 6.41421e-05 -1.96147e-06 7.20037e-05 -2.41087e-06 7.60497e-05 -2.66337e-06 7.70055e-05 -2.66106e-06 7.55488e-05 -2.38172e-06 7.22377e-05 -1.83494e-06 6.75041e-05 -1.06225e-06 6.16721e-05 -1.35019e-07 5.50024e-05 8.483e-07 4.77463e-05 1.76796e-06 4.01834e-05 2.50043e-06 3.26361e-05 2.94455e-06 2.54546e-05 3.05e-06 1.89759e-05 2.83723e-06 1.34686e-05 2.39765e-06 9.08393e-06 1.86912e-06 5.83027e-06 3.63149e-06 9.00234e-08 1.40331e-05 7.67859e-09 3.92393e-05 -2.64549e-07 5.89725e-05 -6.71473e-07 7.30493e-05 -1.10555e-06 8.20609e-05 -1.45157e-06 8.67757e-05 -1.61492e-06 8.80161e-05 -1.53438e-06 8.65372e-05 -1.18497e-06 8.29537e-05 -5.73724e-07 7.77374e-05 2.5841e-07 7.12421e-05 1.2348e-06 6.37521e-05 2.24429e-06 5.55462e-05 3.14977e-06 4.69454e-05 3.81039e-06 3.8329e-05 4.11577e-06 3.01128e-05 4.02282e-06 2.26949e-05 3.58008e-06 1.63863e-05 2.92378e-06 1.13519e-05 2.23974e-06 7.58389e-06 4.9599e-06 3.34292e-07 1.57731e-05 4.72982e-07 4.40957e-05 3.83726e-07 6.62646e-05 1.28009e-07 8.21066e-05 -1.76958e-07 9.23005e-05 -4.12633e-07 9.77142e-05 -4.81305e-07 9.92676e-05 -3.17125e-07 9.77943e-05 1.07785e-07 9.39761e-05 7.88908e-07 8.83224e-05 1.68523e-06 8.12058e-05 2.71341e-06 7.29302e-05 3.74802e-06 6.38012e-05 4.63249e-06 5.41828e-05 5.20754e-06 4.45149e-05 5.35534e-06 3.52829e-05 5.04642e-06 2.69471e-05 4.36842e-06 1.98555e-05 3.51529e-06 1.41737e-05 2.72973e-06 9.85971e-06 6.71979e-06 5.99544e-07 1.75447e-05 9.73234e-07 4.90399e-05 1.07584e-06 7.36943e-05 9.80075e-07 9.13349e-05 8.12596e-07 0.000102727 6.95044e-07 0.000108862 7.26235e-07 0.000110758 9.74696e-07 0.000109327 1.47633e-06 0.00010532 2.23041e-06 9.9282e-05 3.19376e-06 9.15974e-05 4.27523e-06 8.25842e-05 5.33385e-06 7.25726e-05 6.19221e-06 6.19707e-05 6.67238e-06 5.12823e-05 6.65196e-06 4.10663e-05 6.12297e-06 3.1846e-05 5.22465e-06 2.40002e-05 4.22178e-06 1.76772e-05 3.41918e-06 1.27726e-05 8.98452e-06 8.83534e-07 1.93553e-05 1.50311e-06 5.40897e-05 1.80793e-06 8.12621e-05 1.88166e-06 0.000100701 1.85415e-06 0.000113296 1.85595e-06 0.000120172 1.99003e-06 0.000122458 2.32575e-06 0.000121136 2.90671e-06 0.00011701 3.73614e-06 0.000110654 4.76862e-06 0.000102468 5.90488e-06 9.27803e-05 6.98792e-06 8.1942e-05 7.81894e-06 7.04049e-05 8.20168e-06 5.87399e-05 8.0127e-06 4.75834e-05 7.27383e-06 3.75248e-05 6.1885e-06 2.89698e-05 5.10368e-06 2.20304e-05 4.38476e-06 1.65009e-05 1.19148e-05 1.18685e-06 2.12045e-05 2.0647e-06 5.9231e-05 2.57761e-06 8.89272e-05 2.82223e-06 0.000110158 2.9354e-06 0.000123973 3.05652e-06 0.000131627 3.29459e-06 0.000134349 3.72282e-06 0.000133203 4.38731e-06 0.000129033 5.29384e-06 0.000122436 6.39695e-06 0.000113828 7.58985e-06 0.000103542 8.69997e-06 9.19473e-05 9.50751e-06 7.95362e-05 9.79845e-06 6.6949e-05 9.45109e-06 5.49051e-05 8.52452e-06 4.40672e-05 7.2975e-06 3.48731e-05 6.20909e-06 2.73883e-05 5.67949e-06 2.12634e-05 1.57723e-05 1.50966e-06 2.30923e-05 2.65467e-06 6.4463e-05 3.37362e-06 9.66882e-05 3.78747e-06 0.000119707 4.04603e-06 0.000134757 4.29281e-06 0.000143215 4.63832e-06 0.000146417 5.15973e-06 0.000145504 5.90767e-06 0.000141359 6.89165e-06 0.000134605 8.066e-06 0.000125663 9.31748e-06 0.000114868 1.04596e-05 0.000102599 1.12532e-05 8.93819e-05 1.14661e-05 7.59292e-05 1.09789e-05 6.30471e-05 9.89244e-06 5.14838e-05 8.56929e-06 4.17341e-05 7.55266e-06 3.38285e-05 7.32264e-06 2.72428e-05 2.08334e-05 1.83607e-06 3.26398e-06 4.1997e-06 0.000104524 4.78396e-06 0.00012942 5.19069e-06 0.000145705 5.56759e-06 0.000154994 6.02402e-06 0.00015872 6.63858e-06 0.000158099 7.46933e-06 0.000154054 8.53047e-06 0.000147228 9.77621e-06 0.000138046 1.10887e-05 0.000126835 1.22703e-05 0.000113972 1.30661e-05 0.000100008 1.32242e-05 8.57083e-05 1.26196e-05 7.19629e-05 1.13927e-05 5.96436e-05 9.99416e-06 4.93496e-05 9.0871e-06 4.11001e-05 9.24425e-06 3.41758e-05 2.68194e-05 5.23894e-06 6.03431e-06 0.000139308 6.61199e-06 0.000156988 7.14432e-06 0.000167121 7.74009e-06 0.000171417 8.47536e-06 0.000171149 9.42071e-06 0.000167272 1.05989e-05 0.000160446 1.19613e-05 0.000151098 1.33829e-05 0.000139539 1.46507e-05 0.000126128 1.54866e-05 0.000111415 1.5611e-05 9.61934e-05 1.48799e-05 8.14568e-05 1.34587e-05 6.82426e-05 1.18881e-05 5.72877e-05 1.09821e-05 4.86419e-05 1.14792e-05 4.14102e-05 3.3071e-05 7.31829e-06 8.08021e-06 0.000168443 8.76782e-06 0.000179604 9.50383e-06 0.000184464 1.0364e-05 0.000184584 1.14195e-05 0.00018093 1.26992e-05 0.000174162 1.41573e-05 0.000164704 1.56672e-05 0.000152844 1.7007e-05 0.000138904 1.78795e-05 0.000123407 1.79823e-05 0.000107168 1.71491e-05 9.1291e-05 1.55299e-05 7.69796e-05 1.36933e-05 6.51577e-05 1.25555e-05 5.60223e-05 1.30386e-05 4.86421e-05 3.97965e-05 9.66172e-06 1.05105e-05 0.000192116 1.1385e-05 0.000197716 1.23713e-05 0.000198211 1.35361e-05 0.000194835 1.49099e-05 0.000188195 1.64528e-05 0.000178702 1.80417e-05 0.000166624 1.94538e-05 0.000152222 2.03805e-05 0.000135965 2.0498e-05 0.000118666 1.96047e-05 0.000101495 1.77938e-05 8.58155e-05 1.55772e-05 7.28163e-05 1.38581e-05 6.30343e-05 1.3637e-05 5.58661e-05 4.81207e-05 1.23776e-05 1.33908e-05 0.000210851 1.44919e-05 0.000211954 1.57521e-05 0.000208912 1.7208e-05 0.000202486 1.88206e-05 0.000193064 2.04768e-05 0.000180909 2.19636e-05 0.000166186 2.29746e-05 0.000149274 2.31727e-05 0.00013093 2.23125e-05 0.000112337 2.03982e-05 9.49868e-05 1.78104e-05 8.0367e-05 1.52974e-05 6.95262e-05 1.37135e-05 6.26788e-05 5.79329e-05 1.55294e-05 1.67287e-05 0.000225552 1.8071e-05 0.000223178 1.95966e-05 0.000217036 2.12593e-05 0.000207806 2.29649e-05 0.000195772 2.45225e-05 0.000180944 2.56426e-05 0.000163572 2.5991e-05 0.000144308 2.5289e-05 0.000124281 2.34493e-05 0.000105043 2.06906e-05 8.83235e-05 1.75382e-05 7.56672e-05 1.46074e-05 6.80938e-05 6.51017e-05 1.91296e-05 2.05193e-05 2.20864e-05 0.000231706 2.37763e-05 0.000222986 2.55045e-05 0.00021131 2.71167e-05 0.000196671 2.83521e-05 0.000179141 2.89007e-05 0.000159231 2.84736e-05 0.000137953 2.69153e-05 0.000116848 2.43031e-05 9.7756e-05 2.09637e-05 8.25561e-05 1.73593e-05 7.27559e-05 6.91015e-05 2.47223e-05 2.63899e-05 0.000238415 2.81067e-05 0.000227654 2.97435e-05 0.000213542 3.10717e-05 0.000196259 3.18291e-05 0.000176126 3.17392e-05 0.000153999 3.06127e-05 0.000131368 2.84269e-05 0.000110034 2.53569e-05 9.20046e-05 2.17402e-05 7.9086e-05 7.34042e-05 2.91895e-05 3.08249e-05 3.24234e-05 0.000231481 3.37962e-05 0.000215208 3.47221e-05 0.000195304 3.49549e-05 0.000172867 3.43045e-05 0.000149367 3.26918e-05 0.000126345 3.0184e-05 0.000105739 2.69853e-05 8.94332e-05 8.02986e-05 3.52683e-05 3.65879e-05 3.75848e-05 0.000216592 3.80583e-05 0.000194743 3.7823e-05 0.000171166 3.6785e-05 0.000147343 3.49488e-05 0.000124921 3.24228e-05 0.000105741 9.2746e-05 4.05265e-05 4.10989e-05 0.000218878 4.11444e-05 0.000196647 4.05648e-05 0.000172939 3.93424e-05 0.000149732 3.75279e-05 0.00012874 0.000112405 4.42738e-05 4.4417e-05 4.40997e-05 0.000202 4.33175e-05 0.00017948 4.20778e-05 0.000157707 0.000139054 4.7663e-05 4.70934e-05 4.61893e-05 0.000190429 0.000170932 5.02453e-05 ) ; boundaryField { inlet { type calculated; value uniform 0; } outlet { type calculated; value nonuniform 0(); } flap { type calculated; value nonuniform 0(); } upperWall { type calculated; value nonuniform 0(); } lowerWall { type calculated; value uniform 0; } frontAndBack { type empty; value nonuniform 0(); } procBoundary3to0 { type processor; value nonuniform List<scalar> 34 ( 2.48832e-05 6.95878e-05 -4.01166e-06 0.000112126 -6.27262e-06 0.000148817 -8.68163e-06 0.0001793 -1.1351e-05 0.000203826 -1.43848e-05 0.000223065 -1.78578e-05 0.000237908 0.000236943 -2.31838e-05 0.000245683 -2.76255e-05 0.000252737 0.000243951 -3.38076e-05 0.000248431 0.000234784 -3.96046e-05 0.000237811 -4.376e-05 0.000241418 0.000223209 -4.79041e-05 0.000229284 0.000210467 -5.10271e-05 0.000220617 0.000202854 ) ; } procBoundary3to1 { type processor; value nonuniform List<scalar> 9(1.35008e-05 1.4921e-05 1.83914e-05 2.32496e-05 2.89139e-05 3.46201e-05 3.98781e-05 4.45876e-05 4.90169e-05); } procBoundary3to4 { type processor; value nonuniform List<scalar> 19 ( 2.56562e-07 3.17831e-07 4.35987e-07 5.99982e-07 7.91902e-07 9.94173e-07 1.20496e-06 1.45269e-06 1.80231e-06 2.34042e-06 3.14462e-06 4.26898e-06 5.751e-06 7.62886e-06 9.87087e-06 1.25878e-05 1.47123e-05 1.53355e-05 1.42799e-05 ) ; } } // ************************************************************************* //
0615c412b4b762fdce46cda2486d113a67f6a67c
f35830a10b5e4fa5a4f1712d14cbba192dc878fc
/graphics/yafray/dragonfly/patch-src_yafraycore_buffer.h
6a24d0046e11046a37e3a0b88978a21302081955
[]
no_license
jrmarino/DPorts-Raven
10177adf4c17efe028137fbcec1ccbf3b0bddf27
9126990d971ed3a60d54a9c6c3b1ea095d1df498
refs/heads/master
2021-08-05T23:07:39.995408
2017-04-09T23:31:58
2017-04-09T23:31:58
82,212,572
1
0
null
null
null
null
UTF-8
C++
false
false
958
h
patch-src_yafraycore_buffer.h
--- src/yafraycore/buffer.h.orig 2016-12-17 13:01:39.000000000 +0200 +++ src/yafraycore/buffer.h @@ -28,6 +28,7 @@ #endif #include <cstdio> +#include <cstdlib> #include <iostream> #include "color.h" @@ -43,7 +44,7 @@ class YAFRAYCORE_EXPORT gBuf_t if (data==NULL) { std::cerr << "Error allocating memory in cBuffer\n"; - exit(1); + std::exit(1); } mx = x; my = y; @@ -59,7 +60,7 @@ class YAFRAYCORE_EXPORT gBuf_t if(data==NULL) { std::cerr << "Error allocating memory in cBuffer\n"; - exit(1); + std::exit(1); } mx = x; my = y; @@ -153,7 +154,7 @@ Buffer_t<T>::Buffer_t(int x, int y) if(data==NULL) { std::cout<<"Error allocating memory in cBuffer\n"; - exit(1); + std::exit(1); } mx=x; my=y; @@ -175,7 +176,7 @@ void Buffer_t<T>::set(int x, int y) if(data==NULL) { std::cout<<"Error allocating memory in cBuffer\n"; - exit(1); + std::exit(1); } mx=x; my=y;
3c6d131c565d5b9428fee53b81a4131d20651e2e
9d1b0b62ebe69ab0c3e5ffee87657d1d94a14631
/ToolKit/src/FileKit.cpp
b7f6bf50f15a154b83312a8c4d0531f97634017f
[]
no_license
Devin879176/ToolKit
0cfc9308fa43b1235f25748971ec0372f06c5771
ad99746daf1d0a01c2148f5b8aa0d5af7b9db0cd
refs/heads/master
2022-11-28T01:16:03.046642
2020-08-04T08:59:31
2020-08-04T08:59:31
284,903,611
0
0
null
null
null
null
GB18030
C++
false
false
2,157
cpp
FileKit.cpp
#include "FileKit.h" int FileKit::getFiles(std::string path, std::vector<std::string>& files, int category) { //文件句柄 intptr_t hFile = 0; //文件信息 struct _finddata_t fileinfo; std::string p; if (category == 0){ if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1){ do { //如果是目录,迭代 //如果不是,加入列表 if ((fileinfo.attrib & _A_SUBDIR)) { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) getFiles(p.assign(path).append("\\").append(fileinfo.name), files, category); } else { if (strstr(fileinfo.name, "png") != NULL || strstr(fileinfo.name, "bmp") != NULL || \ strstr(fileinfo.name, "jpg") != NULL || strstr(fileinfo.name, "tif") != NULL \ ) files.push_back(p.assign(path).append("\\").append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } return 0; } else if (category == 1){ if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { //如果是目录,迭代之 //如果不是,加入列表 if ((fileinfo.attrib & _A_SUBDIR)) { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) getFiles(p.assign(path).append("\\").append(fileinfo.name), files, category); } else { if ( strstr(fileinfo.name, "avi") != NULL || strstr(fileinfo.name, "mp4") != NULL || \ strstr(fileinfo.name, "dav") != NULL) files.push_back(p.assign(path).append("\\").append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } return 0; } else{ std::cout << "input category param failed!" << std::endl; return -1; } } std::string FileKit::splitStr(const std::string& s, std::vector<std::string>& v, const std::string& c) { std::string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while (std::string::npos != pos2) { v.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) v.push_back(s.substr(pos1)); return *v.rbegin(); }
99ee333cb97bd332941390c7734e37f2106f5c1a
2c43732795f8008c970d0ba180dc28354103fd61
/CppND_System_Monitor/src/process.cpp
3417b9776ca1e423321fbf900e0fe74456038fec
[ "MIT" ]
permissive
Jabalov/CppND-Udacity
ce8f86074e5a0c8834b28ea08b53eaa5a7508533
d46caca36d0cfd35469f4ed7bce2d67d04712f58
refs/heads/master
2022-12-05T21:57:05.894262
2020-08-25T13:40:09
2020-08-25T13:40:09
256,797,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
process.cpp
#include "process.h" #include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "linux_parser.h" using std::stol; using std::string; using std::to_string; using std::vector; // Done: Return this process's ID int Process::Pid() { return pid_; } // Done: Return this process's CPU utilization float Process::CpuUtilization() { return cpu_; } // Done: Return the command that generated this process string Process::Command() { return LinuxParser::Command(pid_); } // Done: Return this process's memory utilization string Process::Ram() { return ram_; } // Done: Return the user (name) that generated this process string Process::User() { return LinuxParser::User(pid_); } // Done: Return the age of this process (in seconds) long int Process::UpTime() { return LinuxParser::UpTime(pid_); } // Done: Overload the "less than" comparison operator for Process objects bool Process::operator<(Process const &a) const { return stoi(a.ram_) < stoi(this->ram_); }
96b01c38b7f71693f258369e3f2cb8560d23ec4b
363ddb2dbe6313fcc302e68b3697cfdd7ee2237b
/include/h/toobgddata.h
fe77869c7ffc1c8e950ce2ce1a975a736f430dc3
[]
no_license
alexocher/ukp
d8dd01e7b6eddb258543fff445f6360349f10979
d7ab7a5087a7e20a6f358cbf79556359cbf8de03
refs/heads/master
2020-04-05T13:31:28.652232
2017-08-02T16:22:27
2017-08-02T16:22:27
83,279,153
0
0
null
null
null
null
UTF-8
C++
false
false
686
h
toobgddata.h
#ifndef TOOBGDDATA_H #define TOOBGDDATA_H #include <TAbstractAttachment> #include <defUkpCommon> class UKPCOMMONSHARED_EXPORT TOobgdData : public TAbstractAttachment { private: public: TOobgdData(TAttachmentType t, int id=0, int n=0, QString nm="", TAbstractObject *parent=NULL); TOobgdData(const TOobgdData &att); ~TOobgdData(); TOobgdData &operator=(const TOobgdData &att); public: // TAbstractObject interface void reset(bool thisonly); QString toStr(); QString toHtml(bool fullinfo=true); bool toDB(QString param); bool fromDB(QString param); }; typedef UKPCOMMONSHARED_EXPORT QPtrList<TOobgdData*> TOobgdDataList; #endif // TOOBGDDATA_H
2955c6de3bc5fc578cf4c228723195c284743823
c920079b644668fcea120937ec7bec392d2029bd
/B4---C++-Programming/cpp_nibbler/includes/PieceSnake.hh
67df43d17a87d4b5712cbff96cfa7b1943533cfd
[]
no_license
Ankirama/Epitech
d23fc8912d19ef657b925496ce0ffcc58dc51d3b
3690ab3ec0c8325edee1802b6b0ce6952e3ae182
refs/heads/master
2021-01-19T08:11:27.374033
2018-01-03T10:06:20
2018-01-03T10:06:20
105,794,978
0
5
null
null
null
null
UTF-8
C++
false
false
669
hh
PieceSnake.hh
// // PieceSnake.h // cpp_nibbler // // Created by Fabien Martinez on 24/03/15. // Copyright (c) 2015 Fabien Martinez. All rights reserved. // #ifndef __cpp_nibbler__PieceSnake__ #define __cpp_nibbler__PieceSnake__ #include "IPiece.hh" class PieceSnake : public IPiece { public: explicit PieceSnake(typePiece type, int x, int y); virtual ~PieceSnake() {} virtual int getX() const; virtual int getY() const; virtual typePiece getType() const; virtual void setX(int x); virtual void setY(int y); virtual void setType(typePiece type); private: int m_x; int m_y; typePiece m_type; }; #endif /* defined(__cpp_nibbler__PieceSnake__) */
47ac6f763ff4e7b362e510c2e9e18db3dc71c725
d152d1ee842b30aec3aafee31bd77b3dda5f2a7e
/src/125.验证回文串.cpp
989f27d574ee80a0babbb909c95d7697680059ab
[]
no_license
seymourtang/LeetCodeNotebook
04f080672e75f1e7874f77fa3fb8d8edd43ad141
351b8172f6f8a43710e827f7c13f014001def2bb
refs/heads/master
2020-05-25T14:30:04.220869
2019-05-22T15:19:55
2019-05-22T15:19:55
187,845,819
0
0
null
null
null
null
UTF-8
C++
false
false
1,727
cpp
125.验证回文串.cpp
/* * @lc app=leetcode.cn id=125 lang=cpp * * [125] 验证回文串 * * https://leetcode-cn.com/problems/valid-palindrome/description/ * * algorithms * Easy (39.58%) * Likes: 87 * Dislikes: 0 * Total Accepted: 36.3K * Total Submissions: 91.5K * Testcase Example: '"A man, a plan, a canal: Panama"' * * 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 * * 说明:本题中,我们将空字符串定义为有效的回文串。 * * 示例 1: * * 输入: "A man, a plan, a canal: Panama" * 输出: true * * * 示例 2: * * 输入: "race a car" * 输出: false * * */ class Solution { public: bool isPalindrome(string s) { if (s == "") { return true; } int size = s.size(); int begin = 0; int end = size - 1; while (begin < end) { while ((begin < size - 1) && !isValid(s[begin])) { ++begin; } if (begin == size - 1) { return true; } while (!isValid(s[end])) { --end; } if (s[begin] != s[end]) { return false; } ++begin; --end; } return true; } bool isValid(char &c) { if (c >= '0' && c <= '9') { return true; } if (c >= 'A' && c <= 'Z') { return true; } if (c >= 'a' && c <= 'z') { c = c - 'a' + 'A'; return true; } return false; } };
e78d1a5cac50407cd1375a5aa4e0e0d7dee3627f
30a7f84922ee4bccbc446d35184e749d78479b07
/src/CWBEMObject.h
b7fc4b1ff2d700967d9621b633f35c8ddbbb3d38
[]
no_license
JonAxtell/WMIApp-AsyncQuery
03668ca41128cd993e5b183f2db4b8e9102cf89c
e654071bb0e7ab3da4fe05e460eb958e668750dd
refs/heads/master
2020-04-28T06:08:26.967032
2019-11-22T09:32:52
2019-11-22T09:32:52
175,045,384
0
0
null
null
null
null
UTF-8
C++
false
false
3,598
h
CWBEMObject.h
#pragma once #include "pch.h" #include "CVariant.h" #include "CWBEMProperty.h" #define _WIN32_DCOM #include <iostream> using namespace std; #include <comdef.h> #include <Wbemidl.h> #ifndef __MINGW_GCC_VERSION #pragma comment(lib, "wbemuuid.lib") #endif #include <vector> #include <memory> //################################################################################################################################# // // Class that encapsulates the process of retrieving a data set from the WBEM sub system in Windows and storing it // in a vector of variants. // // A WBEM object is something like the Operating System or a Printer or a Process. Each object can have many properties from // common ones like a description to properties tied to the object such as stepping model for a processor. A system can // have either single objects (a single OS) or multiple ones (multiple printers). // class CWBEMObject { public: typedef std::pair<int, const CWBEMProperty*> index_property_t; // Default constructor CWBEMObject() {} // Copy constructor (does a deep copy of the whole vector) CWBEMObject(const CWBEMObject& other) { for (auto p : other._properties) { _properties.push_back(p); } } // Move constructor (just transfers the vector) CWBEMObject(CWBEMObject&& other) { this->swap(other); } // Destructor, deletes all objects in the vector virtual ~CWBEMObject() { for (std::vector<CWBEMProperty*>::iterator p = _properties.begin(); p != _properties.end(); ++p) { delete (*p); (*p) = nullptr; } _properties.clear(); } // Copy assignment (does a deep copy of the whole vector) CWBEMObject& operator=(const CWBEMObject& other) { for (auto p : other._properties) { _properties.push_back(p); } return *this; } // Move assignment (just transfers the vector) CWBEMObject& operator=(CWBEMObject&& other) { this->swap(other); return *this; } // Public swap function for use in move operations friend void swap(CWBEMObject& first, CWBEMObject& second) { first.swap(second); } void swap(CWBEMObject &other) { using std::swap; swap(_properties, other._properties); swap(_propertyCount, other._propertyCount); } // Method that gets the properties from the service and places them in the _properties array virtual void Populate(const char** propertyNames, IWbemClassObject __RPC_FAR * pwbemObj); // Methods to access the properties const std::vector<CWBEMProperty* >& Properties() const { return _properties; } std::vector<index_property_t> Properties(enum VARENUM type) const; const CWBEMProperty Property(int prop) const { return (*Properties().at(prop)); } // Methdos to access details about the properties virtual const char* PropertyName(int prop) = 0; unsigned int PropertyCount() { if (_propertyCount == 0) { // If count is zero, assume that the list of property names in the derived class hasn't been scanned yet. // This is done here rather because you can't call a method in a derived class from a virtual base class's constructor. while (PropertyName(_propertyCount++)) { } --_propertyCount; } return _propertyCount; } private: unsigned int _propertyCount{ 0 }; std::vector<CWBEMProperty* > _properties; };
53a29e2fd404635effc048e44b27f4a56f6ff40e
ca11d8df0127efbaa6c3f92ed1138cf3a32b3f90
/hard/154. Find Minimum in Rotated Sorted Array II.cpp
1176de809f88b2ad8ddcaae40527bc2469338f28
[]
no_license
KanaSukita/LeetCode
79ecf465b9486fa0fa910e7748251de8734388b2
7ff9f58c2cd58dd750aecbd3778c706c71b5c57f
refs/heads/master
2021-04-30T10:07:09.672956
2018-07-23T09:42:17
2018-07-23T09:42:17
119,618,148
0
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
154. Find Minimum in Rotated Sorted Array II.cpp
// Follow up for "Find Minimum in Rotated Sorted Array": // What if duplicates are allowed? // // Would this affect the run-time complexity? How and why? // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // // Find the minimum element. // // The array may contain duplicates. // Idea: // use binary search, what's different is when nums[m] == nums[r], make l++ and r-- class Solution { public: int findMin(vector<int>& nums) { if(nums.empty()) return 0; int l = 0, r = nums.size()-1; while(l < r){ if(nums[l] < nums[r]) break; int m = (l+r) / 2; if(nums[m] == nums[r]){ l++; r--; } else if(nums[m] > nums[r]) l = m + 1; else r = m; } return nums[l]; } };
1b15147b568308d3c8aacf4abe622f1f8f9b4b71
421e8f4ea8a66c2227f35c342495e8a78dc50ee8
/Enemy.cpp
b48415c4f5595a6d329f655376303e329f4550e8
[]
no_license
fukasawayuuta/DirectX_Project
6b049aa4091ff7020a2c762cd54948275907c36e
e92819b90d3290cb08e1c0412d84d9a67d4e736b
refs/heads/master
2021-01-23T07:37:53.126948
2017-01-31T11:16:43
2017-01-31T11:16:43
80,512,166
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,890
cpp
Enemy.cpp
/****************************************************************************** タイトル名 : Enemyクラス ファイル名 : Enemy.cpp 作成者 : AT-13C-284 36 深澤佑太 作成日 : 2016/12/17 更新日 : ******************************************************************************/ /****************************************************************************** インクルードファイル ******************************************************************************/ #include "main.h" #include "renderer.h" #include "manager.h" #include "scene.h" #include "texture.h" #include "scene3D.h" #include "sceneX.h" #include "billboard.h" #include "bullet.h" #include "model.h" #include "motionManager.h" #include "dynamicModel.h" #include "Enemy.h" #include "collision.h" #include "capsule.h" #include "sphere.h" #include "collisionDetection.h" #include "collisionList.h" #include "Explosion.h" /****************************************************************************** 関数名 : CEnemy::CEnemy(int Priority, OBJ_TYPE objType, SCENE_TYPE sceneType) : CDynamicModel(Priority, objType, sceneType) 説明 : コンストラクタ ******************************************************************************/ CEnemy::CEnemy(int Priority, OBJ_TYPE objType, SCENE_TYPE sceneType) : CDynamicModel(Priority, objType, sceneType) { m_Hp = 0; m_pCollision = NULL; m_Radius = 0.0f; } /****************************************************************************** 関数名 : CEnemy::~CEnemy() 説明 : デストラクタ ******************************************************************************/ CEnemy::~CEnemy() { } /****************************************************************************** 関数名 : void CEnemy::Init(D3DXVECTOR3 pos, D3DXVECTOR3 rot, DYNAMICMODEL_TYPE modelType) 引数 : pos, rot, modelType 戻り値 : なし 説明 : 座標、角度の初期化。 ******************************************************************************/ void CEnemy::Init(D3DXVECTOR3 pos, D3DXVECTOR3 rot, DYNAMICMODEL_TYPE modelType) { // モーション設定。 m_MotionManager = CMotionManager::Create(modelType, &m_mtxWorld); m_MotionManager->SetMotion(0); m_Pos = pos; m_Rot = rot; m_Hp = 3; // あたり判定生成。 m_pCollision = CSphere::Create(D3DXVECTOR3(0.0f, 50.0f, 0.0f), 50.0f, this); //m_pCollision = CCapsule::Create(D3DXVECTOR3(0.0f, 0.0f, 0.0f), 50.0f, D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 50.0f, 0.0f), this); } /****************************************************************************** 関数名 : void CEnemy::Uninit(void) 引数 : void 戻り値 : なし 説明 : 解放処理。 ******************************************************************************/ void CEnemy::Uninit(void) { m_MotionManager->Uninit(); SAFE_DELETE(m_MotionManager); if (m_pCollision != NULL) { m_pCollision->SetDelete(true); m_pCollision->GetCollisionList()->Uninit(); m_pCollision = NULL; } } /****************************************************************************** 関数名 : void CEnemy::Update(void) 引数 : void 戻り値 : なし 説明 : 解放処理。 ******************************************************************************/ void CEnemy::Update(void) { m_MotionManager->Update(); if (m_Hp < 0) { m_Delete = true; CExplosion::Create(m_Pos, 125.0f, 125.0f, CTexture::G_EXPLOSION); } // 自分になにか当たったら。 if (m_pCollision->GetHit()) { CCollisionList *collicionList = m_pCollision->GetCollisionList(); std::list<CCollision *> *collList = collicionList->GetCollision(); for (auto i = collList->begin(); i != collList->end();) { CCollision *object = (*i); if (object != NULL) { if (object->GetScene()->GetObjectType() == OBJ_TYPE_BULLET) { CBullet *bullet = (CBullet *)object->GetScene(); // 撃った対象がPlayerだったら。 if (bullet->GetTypeUsingSelf() == OBJ_TYPE_PLAYER) { // HPが減少。 --m_Hp; CExplosion::Create(object->GetScene()->GetPos(), 125.0f, 125.0f, CTexture::G_EXPLOSION); object->GetScene()->SetDelete(true); } } // リストのなかみ削除。 i = collList->erase(i); } } } } /****************************************************************************** 関数名 : void CEnemy::Draw(void) 引数 : void 戻り値 : なし 説明 : 描画関数。 ******************************************************************************/ void CEnemy::Draw(void) { CManager *pManager = GetManager(); CRenderer *pRenderer = pManager->GetRenderer(); LPDIRECT3DDEVICE9 pDevice = pRenderer->GetDevice(); // 行列式に使う作業用変数 D3DXMATRIX mtxScl, mtxRot, mtxTrans; // ワールドマトリクスの初期化 D3DXMatrixIdentity(&m_mtxWorld); // スケールを反映 D3DXMatrixScaling(&mtxScl, m_Scl.x, m_Scl.y, m_Scl.z); D3DXMatrixMultiply(&m_mtxWorld, &m_mtxWorld, &mtxScl); // 回転を反映 D3DXMatrixRotationYawPitchRoll(&mtxRot, m_Rot.y, m_Rot.x, m_Rot.z); D3DXMatrixMultiply(&m_mtxWorld, &m_mtxWorld, &mtxRot); // 移動を反映 D3DXMatrixTranslation(&mtxTrans, m_Pos.x, m_Pos.y, m_Pos.z); D3DXMatrixMultiply(&m_mtxWorld, &m_mtxWorld, &mtxTrans); //ワールドマトリクスの設定 pDevice->SetTransform(D3DTS_WORLD, &m_mtxWorld); m_MotionManager->Draw(); } /****************************************************************************** 関数名 : CEnemy * CEnemy::Create(D3DXVECTOR3 pos, D3DXVECTOR3 rot, DYNAMICMODEL_TYPE modelType) 引数 : pos, rot, modelType 戻り値 : obj 説明 : 生成関数。 ******************************************************************************/ CEnemy * CEnemy::Create(D3DXVECTOR3 pos, D3DXVECTOR3 rot, DYNAMICMODEL_TYPE modelType) { CEnemy *obj = new CEnemy; obj->Init(pos, rot, modelType); return obj; }
ebc4060ed1b8e14598a64d5885a3ca76a3a4b2bd
c0f8e5155a1498fbb8cbbe7d5ac45c71b939a63c
/Signature/TestSignature/TestMain.cpp
09c227d972b766f99bdb7dca37fe8ab75df584ab
[]
no_license
ProjetGroupeE/PPC
7fcda003155cd992a619da08d5f666a7f2d384a2
9a0c338b5a0a8ab95eea27b1d80b29b1d64a8fcd
refs/heads/master
2021-01-23T22:24:16.496156
2017-05-15T22:31:58
2017-05-15T22:31:58
83,128,055
0
0
null
null
null
null
ISO-8859-2
C++
false
false
593
cpp
TestMain.cpp
#include <iostream> #include "../Signature/Signature.h" using namespace std; int main(void) { Signature ace; string data = "je suis gallou et je vais dévenir ' % # @ */-51 madame " "sapo equilibre avec un equilibriste de renomer haha ";; string privkey1; string pubkey1; string privkey2; string pubkey2; cout << ace.generate(privkey1, pubkey1) << endl; cout << ace.generate(privkey2, pubkey2) << endl; string signature = ace.sign(data, privkey1); cout << ace.verify(data, signature, pubkey1) << endl; cout << ace.verify(data, signature, pubkey2) << endl; return 0; }
20374eb52f11e1d2ba1bc7204ab8b35a9c7f85ba
fdac512289536816ddb123519566d8210967a95b
/PPR/przydatne.cpp
e1200a25e340932bb7ddc51ce599f4ca5095aeae
[]
no_license
Goggiafk/AMU
1424fbae9926a589c84ba90ed6f02784c10ffd23
6df3317979fe39ccd347282aebfc02ce2425048d
refs/heads/master
2021-05-28T12:51:00.201991
2015-02-28T23:50:32
2015-02-28T23:50:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,490
cpp
przydatne.cpp
/* Funkcja isSubst zwraca true jezeli string child zawiera sie w stringu parent. W przeciwnym wypadku zwraca false. */ bool isSubstr(std::string child, std::string parent) { return parent.find(child) != std::string::npos; } /* Funkcja isPalindrome zwraca true jezeli string s jest palindromem. */ bool isPalindrome(std::string s) { std::string rev = std::string(s.rbegin(), s.rend()); return s == rev; } /* Funkcja NWD zwraca najwiekszy wspolny dzielnik dwoch liczb lub calej tablicy liczb. */ int NWD(int a, int b) { int c; while(b != 0) { c = a % b; a = b; b = c; } return a; } int NWD(int array[], int length) { int result = array[0]; for(int i = 1; i < length; i++) { result = NWD(result, array[i]); } return result; } /* Funkcja average zwraca srednia arytmetyczna wartosci liczb calkowitych znajdujacych sie w tablicy array o dlugosci length. */ float average(int array[], int length) { int s = 0; for(int i = 0; i < length; i++) { s += array[i]; } return (float)s / length; } /* Funkcja sumSubarray zwraca sume wszystkich elementow tablicy array znajdujacych sie w indeksach od x do y (wlacznie). */ int sumSubarray(int array[], int x, int y) { int result = 0; for(int i = x - 1; i < y; i++) { result += array[i]; } return result; } /* Funkcja swap przypisuje zmiennej x wartosc zmiennej y, a zmiennej y wartosc zmiennej x. */ void swap(int& x, int& y) { int temp = x; x = y; y = temp; }
9c726b5ce1b0cf96b6e70ee0d583abac7c448c8d
ff9854ccafd47c9a33db587903493faea6ae3263
/Kakao/캐시.cpp
7f7838829e02e677337f582784d9eb7a000c436f
[]
no_license
peter4549/problems
779cffe0bac283bef0e8a2fd62f715effb251dce
788fc8831f17f931b644ed9fc381c225d018469a
refs/heads/master
2023-03-22T19:22:25.416031
2021-03-06T15:47:31
2021-03-06T15:47:31
299,646,883
0
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
캐시.cpp
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int cache[31]; int main() { int cacheSize, runTime(0); vector<string> lru; scanf("%d", &cacheSize); cin.ignore(256, '\n'); while (true) { string city; getline(cin, city); if (city == "\0") break; transform(city.begin(), city.end(), city.begin(), ::tolower); auto it = find(lru.begin(), lru.end(), city); if (it != lru.end()) { runTime += 1; lru.erase(it); } else { runTime += 5; if (cacheSize == lru.size() && !cacheSize) lru.erase(lru.end()); } if (!cacheSize) lru.insert(lru.begin(), city); } printf("%d", runTime); return 0; }
a251ea5a71ce2d7ccbc1d66e617b93a1febdc33a
926b9211a8e4c7928956d8b5f73bde737bf9c7d3
/Src/Manipulator/TouchballManipulator.h
3af2898bebdacd458ea36a4454f9dfea8366ab8e
[ "MIT" ]
permissive
blackball/Vis2
d7a1eaf9be912c4c3dbf2f445a40ca5daa42a5bd
3febe53bd37091722f88d5bc7c129f209326d768
refs/heads/master
2023-07-20T16:12:56.423270
2021-09-01T13:56:49
2021-09-01T13:56:49
402,078,299
0
0
null
null
null
null
UTF-8
C++
false
false
1,050
h
TouchballManipulator.h
#include <osgGA/MultiTouchTrackballManipulator> class TouchballManipulator : public osgGA::MultiTouchTrackballManipulator { public: TouchballManipulator(int* gizmod = nullptr, bool* view_manipulation = nullptr) : m_gizmod(gizmod), m_view_manipulation(view_manipulation) { setMinimumDistance(-0.5f, true); } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa); protected: virtual void handleMultiTouchPan(const osgGA::GUIEventAdapter* now, const osgGA::GUIEventAdapter* last, const double eventTimeDelta); virtual void handleMultiTouchZoom(const osgGA::GUIEventAdapter* now, const osgGA::GUIEventAdapter* last, const double eventTimeDelta); private: int* m_gizmod; bool* m_view_manipulation; double m_4time = 0.0f; double m_3time = 0.0f; double m_2time = 0.0f; double m_1time = 0.0f; double m_ztime = 0.0f; };
bb6fd2776ed267c87e712d92d32b972bc17d08dc
2728b551ea11cf5de3e793099e02d43d76e72e7b
/ackCore/include/EventReseau.h
21b471cc8b989d741f3f11d4dd350a55c2dc3e9d
[]
no_license
Robien/acharn
0d38317bd1eb40b61f18089288ad6a029105732d
e4b9c657a52edbd08962fe0df890c98c27d8b383
refs/heads/master
2021-01-10T18:42:38.169223
2020-04-08T05:48:19
2020-04-08T05:48:19
39,433,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
h
EventReseau.h
/* * EventReseau.h * * Created on: 31 juil. 2010 * Author: romain */ #ifndef EVENTRESEAU_H_ #define EVENTRESEAU_H_ #include "Callback.h" #include "../include/MainPerso.h" #include "Appli.h" #include "../include/Referenced.h" #include <asio.hpp> class EventReseau: public Callback, public Referenced { public: EventReseau(ackCore::Appli* app); virtual ~EventReseau(); void recevoirMessage(vector<std::string> &message, int source); void connexionReussie(int init, string info); void connexionRefusee(string msgerror); void connexionNewJoueur(int id, int init, string info); void connexionCompetence(vector<std::string> &l_comp); void connexionObjetSac(vector<std::string> &l_objsac); void connexionObjetEquipement(int id, vector<std::string> &l_equip); void connexionTexture(int id, vector<std::string>* l_texture); void verificationInfo(int id); void verificationObjetEquipement(int id); void isEtat(string nom, int etat); void setTexture(int id, vector<std::string>* l_texture); void deconnexionJoueur(int id); void setJoueur(MainPerso* joueur); private: PointeurIntelligent<MainPerso> _joueur; PointeurIntelligent<ackCore::Appli> _app; }; #endif /* EVENTRESEAU_H_ */
a1c0761728880c1e0341fb61932ec247e5f79916
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc044/A/4417655.cpp
c1ac2f0ebf6424ed81cdfa0d2e1776b9234847db
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
253
cpp
4417655.cpp
#include <iostream> int main(){ int n, k, x, y; std::cin >> n >> k >> x >> y; int fee = 0; if(n > k){ fee += k*x; fee += (n - k)*y; }else{ fee += n*x; } std::cout << fee << std::endl; }
b8fc26d809b8578c0abb2671bf1f35de8d9a41da
99d8eca9eae667f3929c3a207b49bcc21225b737
/parser/rba_parser.h
a0dc62c3ec4bc775b544ee78b80da094c7886f90
[]
no_license
martin34/expense-tracker
b4fdcc84849a2204e68fb08e2b6730b9ec943359
cf9e63f9d9d620322e231860ec1626e8865fff24
refs/heads/master
2022-04-20T06:13:00.342818
2020-04-19T15:27:09
2020-04-19T15:41:30
257,034,771
0
0
null
null
null
null
UTF-8
C++
false
false
551
h
rba_parser.h
#pragma once #include "core/transaction.h" #include <string> #include <vector> namespace finance { Transaction ParseFromTransactionString(const std::string &txt_transaction, const std::int32_t year); std::vector<Transaction> ParseTransactionsFromFile(const std::string &file_path); std::string LoadFile(const std::string &file_path); std::vector<Transaction> ParseTransactionsFrom(const std::string &content); std::vector<Transaction> ParseTransactionsFromRbaTxt(std::istream &stream); } // namespace finance
124713131ec12141c9bd74464b0e0c2aee5a3b0a
8757a559b4ffe66c179688b4b063ab1b72ddda37
/Libs/ExtendLibs/ImGui/ImApp.cpp
792d62605e4f0b5700335940a10ffa62b588b814
[]
no_license
AT410/WizBCLateProject
01614d1b5523ca4861f79ce9ca493808f8b38236
5f273910a323ddab6d6b200d075e8e8656682221
refs/heads/master
2023-06-24T09:38:59.908795
2020-09-03T07:15:02
2020-09-03T07:15:02
279,212,628
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,325
cpp
ImApp.cpp
#include "stdafx.h" #ifdef _BSImGui namespace basecross { unique_ptr<ImApp,ImApp::ImAppDeleter> ImApp::m_Instance; ImApp::ImApp(HWND hWnd,int MaxImCount) { // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Control // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings ImGui_ImplWin32_Init(hWnd); auto DeviceRes = App::GetApp()->GetDeviceResources(); auto D3DDevice = DeviceRes->GetD3DDevice(); auto D3DDeviceContext = DeviceRes->GetD3DDeviceContext(); ImGui_ImplDX11_Init(D3DDevice, D3DDeviceContext); ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\meiryo.ttc", 24.0f, &config, io.Fonts->GetGlyphRangesJapanese()); m_maxImCount = MaxImCount > 0 ? MaxImCount : 1; m_guiObjects.clear(); } void ImApp::CreateApp(HWND hWnd,const int MaxImCount) { if (m_Instance.get() == 0) { m_Instance.reset(new ImApp(hWnd,MaxImCount)); // -- 初期生成時の処理はここへ -- } } bool ImApp::ChackApp() { if (m_Instance.get() != 0) { return true; } return false; } unique_ptr<ImApp, ImApp::ImAppDeleter>& ImApp::GetApp() { if (m_Instance.get() != 0) { return m_Instance; } else { throw(BaseException( L"IMGUIアプリケーションがまだ作成されてません", L"if (m_instance.get() == 0)", L"ImApp::GetApp()" )); } } void ImApp::DeleteApp() { if (m_Instance.get() != 0) { m_Instance->OnShutdown(); m_Instance.reset(); } } // -- 更新処理 -- void ImApp::OnUpdate() { // Start the Dear ImGui frame ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); for (auto uObj : m_guiObjects) { // -- 描画処理 -- uObj->OnGUI(); } // Rendering ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); } void ImApp::OnShutdown() { // Cleanup ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); } } #endif // !_BSImGui
5791dcc69f4320a37e53a6b2948ced6d25b81ebd
c2484df95f009d516bf042dca93857b43a292333
/google/2016/qualification_round/a/main.cpp
3a4141e0694a9b181ebc624321512af9282e406e
[ "Apache-2.0" ]
permissive
seirion/code
545a78c1167ca92776070d61cd86c1c536cd109a
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
refs/heads/master
2022-12-09T19:48:50.444088
2022-12-06T05:25:38
2022-12-06T05:25:38
17,619,607
14
4
null
null
null
null
UTF-8
C++
false
false
720
cpp
main.cpp
// https://code.google.com/codejam/contest/6254486/dashboard#s=p0 // A. Counting Sheep #include <cstdio> #include <iostream> #include <string> #include <set> #include <algorithm> using namespace std; bool put(set<char> &s, int num) { while (num) { s.insert(num % 10); num /= 10; } return s.size() == 10; } void solve() { int in; cin >> in; if (in == 0) { cout << "INSOMNIA\n"; return; } int now = in; set<char> s; while (true) { if (put(s, now)) break; now += in; } cout << now << endl; } int main() { int t; cin >> t; for (int i = 1; i <= t; i++) { printf("Case #%d: ", i); solve(); } }
70cde72fde1e590911bd46006982728d72a70c16
a402e9d62844845d993b2ed243f77efa2842188c
/Ink.h
81bf42649c919427c405873b18d7204a8900b978
[]
no_license
matthargett/BlotChooser
d20ef2cc87aeb1f05ae917fa047ca676e66ed942
eaf4400065f06898b3db706b8738b2b0c519d8b2
refs/heads/master
2021-01-10T07:19:52.386406
2015-10-20T19:01:36
2015-10-20T19:01:36
44,446,739
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
Ink.h
// // Created by Matt Hargett on 10/11/15. // #ifndef WHICH_INKS_INK_H #define WHICH_INKS_INK_H #include <string> #include <cstdlib> #include "Color.h" class Ink { public: Ink(const std::string& color_, double cost_): color(color_), cost(cost_) {} Ink(const Ink& other) : color(other.color), cost(other.cost) {} Ink(): color("FFFFFF") {} Color color; double cost; }; #endif //WHICH_INKS_INK_H
83ba6db6fed0deaf8c5cce649f33741eb10f2f5f
63318ff878c3eb0d939548a47a9b47aea7931ce2
/record.h
06cd97194399d24adf61432d54e8a8439fbcd5b4
[]
no_license
JiaAnTW/NCKU_1stGrade_3_CSProgramDesign2_Project3
1ea1d48d098801d34d8b55917773d59a45e9eb4c
cee91cc49e1c419ec7fc5fe868d40eb399611472
refs/heads/master
2020-03-21T08:52:38.081372
2019-03-09T07:27:26
2019-03-09T07:27:26
138,370,768
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
record.h
#ifndef RECORD_H #define RECORD_H #include <QTextStream> #include <QFile> #include <QString> #include <QDebug> #include <QVector> class record { public: record(); void recieveData(int level,int HP,int ult,int score); void saveData(); QVector<int> sendData(); private: QString data; QVector<int> save; }; #endif // RECORD_H
3c5232a1319750bef64795deb8a0e62c8fb33792
a078104804ae056eeb88e5833b2ca67493fe82dc
/robot/main/slave_emil.cc
03e970a16bf884592c4c67b152a3f4a74dda58db
[]
no_license
lintangsutawika/trui-bot-prj
6994e786dba0904aadd72ce94a23c7e04accdb09
1fa5aaa63ef7f10c886111e1cbd919cdd05fa8dd
refs/heads/master
2021-01-20T15:59:35.626717
2015-05-07T18:52:41
2015-05-07T18:52:41
24,822,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,044
cc
slave_emil.cc
#include <arduino/Arduino.h> #include <comm/arduino_mavlink_packet_handler.hpp> #include <comm/custom.h> #include <actuator/motor.h> int timer1_counter; const size_t pwm_pin = 11; const size_t dir_pin = 12; const float outmax = 100.0; const float outmin = -100.0; const int encoder_out_a_pin = 2; const int encoder_out_b_pin = 3; const int encoder_resolution = 360; //Only needed for Initialization, not used unless .rot() is called uint32_t received_speed; float speed; trui::Motor motor(pwm_pin, dir_pin, encoder_out_a_pin, encoder_out_b_pin, encoder_resolution, outmax, outmin); void setup() { // initialize timer1 noInterrupts(); // disable all interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B // set compare match register to desired timer count: OCR1A = 780; // turn on CTC mode: TCCR1B |= (1 << WGM12); // Set CS10 and CS12 bits for 1024 prescaler: TCCR1B |= (1 << CS10); TCCR1B |= (1 << CS12); // enable timer compare interrupt: TIMSK1 |= (1 << OCIE1A); interrupts(); // enable all interrupts } ISR(TIMER1_COMPA_vect) // interrupt service routine { //interrupts(); motor.set_speed(speed); } void receive_data() { } int main() { init();// this needs to be called before setup() or some functions won't work there setup(); motor.setup(); Serial.begin(9600); speed = 0; long timeNow = 0, timeOld = 0; int incoming_byte = 0; uint8_t buffer[9]; while (true) { //1. Wait msg from master //while(true){ if(Serial.available() >= 9) { buffer[0]= Serial.read(); } if (buffer[0] == 206){ for (int i=1; i<9; i++) { buffer[i]= Serial.read(); } //break; } //} //received_speed = (buffer[4] << 24); //received_speed |= (buffer[3] << 16); //received_speed |= (buffer[2] << 8); //received_speed |= (buffer[1]); //if(buffer[5] == 0x00) speed= buffer[1];//received_speed; //speed = 50;//(float) received_speed; delay(1); // //2. Identify msg // //2A. If msgid = manual_setpoint, set speed control to cmd_speed // if ( (rx_msg.msgid==set_speed_msgid) ) { // mavlink_manual_setpoint_t msg; // mavlink_msg_manual_setpoint_decode(&rx_msg, &msg); // speed= msg.roll; // } // //2B. If msgid = asking for actual speed, send back actual speed to master // else if ( (rx_msg.msgid==actual_speed_query_msgid) ) { // float actual_speed; // mavlink_message_t msg_to_master; // uint8_t system_id= MAV_TYPE_RBMT; // uint8_t component_id= MAV_COMP_ID_ARDUINO_SLAVE1; // uint32_t time_boot_ms= millis(); // mavlink_msg_manual_setpoint_pack(system_id, component_id, &msg_to_master, time_boot_ms, actual_speed, 0., 0., 0., 0, 0); // uint8_t buf[MAVLINK_MAX_PACKET_LEN]; // uint16_t len = mavlink_msg_to_send_buffer(buf, &msg_to_master); // Serial.write(buf, len); // } } return 0; }
5c2f35597cf18ccf7c7d2ed14e7bc824d2065d65
7b5469a9828a8caa764d138ad7e224001330a821
/Source/OhMummyMobile/Parts/Sarcophagus.h
8483545b5c3056053c730f08fec05c71defe1a3e
[]
no_license
pjsillescas/ahmummymobile
f11225aaab1a615f86cabb6e606bf9229e9359d5
da334bb7c6e6314c48e34b725a65488dec50857e
refs/heads/master
2022-07-07T15:44:09.219624
2022-06-27T21:19:59
2022-06-27T21:19:59
183,679,680
0
0
null
null
null
null
UTF-8
C++
false
false
2,110
h
Sarcophagus.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Sarcophagus.generated.h" UENUM(BlueprintType) enum class EVertices : uint8 { EV_None UMETA(DisplayName = "None"), EV_Northwest UMETA(DisplayName = "NorthWest"), EV_Northeast UMETA(DisplayName = "NorthEast"), EV_Southwest UMETA(DisplayName = "SouthWest"), EV_SouthEast UMETA(DisplayName = "SouthEast"), }; UCLASS() class OHMUMMYMOBILE_API ASarcophagus : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASarcophagus(); protected: UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Setup") class AJunction* NWVertex; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Setup") class AJunction* NEVertex; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Setup") class AJunction* SWVertex; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Setup") class AJunction* SEVertex; // Called when the game starts or when spawned virtual void BeginPlay() override; UFUNCTION(BlueprintCallable, Category = "Init") bool GetVertices(class UStaticMeshComponent* Mesh); public: // Called every frame virtual void Tick(float DeltaTime) override; UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Vertices") EVertices GetVertexPosition(class AJunction* Vertex); UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Vertices") bool IsNorthEdge(const EVertices Vertex1, const EVertices Vertex2); UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Vertices") bool IsSouthEdge(const EVertices Vertex1, const EVertices Vertex2); UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Vertices") bool IsEastEdge(const EVertices Vertex1, const EVertices Vertex2); UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Vertices") bool IsWestEdge(const EVertices Vertex1, const EVertices Vertex2); private: bool CompareVertices(const EVertices Vertex1, const EVertices Vertex2, const EVertices Value1, const EVertices Value2); };
f3e700a6cb8ff13a4bf6e447ee7310903d198745
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
/modules/spellchecker/src/dictionarymanagement.cpp
dc4683ae068cea9bbb27171d722d2ec2ad5fc66a
[]
no_license
prestocore/browser
4a28dc7521137475a1be72a6fbb19bbe15ca9763
8c5977d18f4ed8aea10547829127d52bc612a725
refs/heads/master
2016-08-09T12:55:21.058966
1995-06-22T00:00:00
1995-06-22T00:00:00
51,481,663
98
66
null
null
null
null
UTF-8
C++
false
false
8,894
cpp
dictionarymanagement.cpp
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef INTERNAL_SPELLCHECK_SUPPORT #include "modules/spellchecker/opspellcheckerapi.h" #include "modules/spellchecker/src/opspellchecker.h" OP_STATUS OwnFileFromDicPath(const uni_char * dictionary_path, OpFile& own_file) { if (!dictionary_path) return SPC_ERROR(OpStatus::ERR); const uni_char * str = uni_strrchr(dictionary_path, PATHSEPCHAR); if (str == NULL) return SPC_ERROR(OpStatus::ERR); str++; OpString own_path; OP_STATUS status = OpStatus::OK; status = own_path.Set(str); if (OpStatus::IsError(status)) return SPC_ERROR(status); int len = own_path.Length(); if (len < 5) return SPC_ERROR(OpStatus::ERR); uni_strcpy(own_path.CStr()+len-3, UNI_L("oow")); status = own_file.Construct(own_path.CStr(), OPFILE_DICTIONARY_FOLDER); if (OpStatus::IsError(status)) return SPC_ERROR(status); return OpStatus::OK; } OP_STATUS OpSpellChecker::RemoveStringsFromOwnFile(const uni_char *str, BOOL in_added_words, BOOL &removed) { if (!m_own_path || *m_own_path == '\0') return OpStatus::OK; OpFile own_file; int file_len = 0; RETURN_IF_ERROR(SCOpenFile(m_own_path, own_file, file_len, OPFILE_UPDATE)); UINT8 *file_data = OP_NEWA(UINT8, file_len); if (!file_data) { own_file.Close(); return SPC_ERROR(OpStatus::ERR_NO_MEMORY); } OpFileLength bytes_read = 0; OP_STATUS status = own_file.Read(file_data, (OpFileLength)file_len, &bytes_read); if (OpStatus::IsError(status) || bytes_read != (OpFileLength)file_len) { own_file.Close(); OP_DELETEA(file_data); return SPC_ERROR(OpStatus::IsError(status) ? status : OpStatus::ERR); } UINT8 *str_buf = TempBuffer(); to_utf8((char*) str_buf, str, SPC_TEMP_BUFFER_BYTES); int ofs; UINT8 *end; for (ofs = 0; ofs < file_len && file_data[ofs]; ofs++); if (in_added_words) { end = file_data + ofs; ofs = 0; } else { end = file_data + file_len; ofs++; } UINT8 *start = file_data + ofs; removed = FALSE; while (start < end) { UINT8 *ptr = start; while (ptr != end && !is_ascii_new_line(*ptr)) ptr++; BOOL removed_new_line = FALSE; if (ptr != end) { ptr++; removed_new_line = TRUE; } int len = (int)(ptr-start); if (len && str_equal(start, str_buf, len - (removed_new_line ? 1 : 0))) { int i; int to_copy = file_len - (int)(ptr-file_data); for (i=0;i<to_copy;i++) start[i] = start[i+len]; removed = TRUE; end -= len; file_len -= len; } else start = ptr; while (start < end && is_ascii_new_line(*start)) start++; } ReleaseTempBuffer(); own_file.Close(); status = OpStatus::OK; if (removed) { // Write down the changed file int dummy = 0; status = SCOpenFile(m_own_path, own_file, dummy, OPFILE_WRITE); if (OpStatus::IsSuccess(status)) { status = own_file.SetFileLength(0); if (OpStatus::IsSuccess(status)) status = own_file.Write(file_data, (OpFileLength)file_len); else { OP_ASSERT(!"We just destroyed the own word database. Doh. Should be using OpSafeFile or something"); } own_file.Close(); } } OP_DELETEA(file_data); return status; } OP_STATUS OpSpellChecker::CreateOwnFileIfNotExists() { if (m_own_path && *m_own_path) return OpStatus::OK; OP_STATUS status = OpStatus::OK; OpFile own_file; status = OwnFileFromDicPath(m_dictionary_path, own_file); if (OpStatus::IsError(status)) return SPC_ERROR(status); status = own_file.Open(OPFILE_OVERWRITE); if (OpStatus::IsError(status)) return SPC_ERROR(status); status = own_file.Write("\0",1); if (OpStatus::IsError(status)) return SPC_ERROR(status); OpString own_path; status = own_path.Set(own_file.GetFullPath()); if (OpStatus::IsError(status)) return SPC_ERROR(status); status = m_language->SetOwnFilePath(own_path.CStr()); if (OpStatus::IsError(status)) return SPC_ERROR(status); return SPC_ERROR(UniSetStr(m_own_path, own_path.CStr())); } BOOL OpSpellChecker::CanRepresentInDictionaryEncoding(const uni_char *str) { int i; if (!m_8bit_enc || !str || !*str) return TRUE; UINT8 *buffer = (UINT8*)TempBuffer(); int was_read = 0; int to_write = uni_strlen(str)+1; int to_read = to_write*sizeof(uni_char); int was_written = m_output_converter->Convert(str, to_read, buffer, SPC_TEMP_BUFFER_BYTES, &was_read); if (was_written != to_write || was_read != to_read) { ReleaseTempBuffer(); return FALSE; } int qm = 0; for (i=0;i<to_write-1;i++) qm += str[i] == '\?' ? 1 : 0; for (i=0;i<to_write-1;i++) qm -= buffer[i] == '\?' ? 1 : 0; ReleaseTempBuffer(); return !qm; } #ifndef SPC_USE_HUNSPELL_ENGINE OP_STATUS OpSpellChecker::RemoveWordList(UINT8 *data, int len) { if (!data || !len || !*data) return OpStatus::OK; BOOL finished = FALSE; uni_char *buf = (uni_char*)TempBuffer(); UINT8 *str; while (!finished) { str = data; while (!is_ascii_new_line(*data) && *data) // data is '\0' terminated data++; if (!*data) finished = TRUE; *data = '\0'; if (data != str) { RETURN_IF_ERROR(ConvertStringToUTF16(str, buf, SPC_TEMP_BUFFER_BYTES)); RETURN_IF_ERROR(m_removed_words.AddString(buf,FALSE)); } while (!finished && is_ascii_new_line(*(++data))); } ReleaseTempBuffer(); RETURN_IF_ERROR(m_removed_words.Sort()); return OpStatus::OK; } OP_STATUS OpSpellChecker::AddWord(const uni_char *word, BOOL permanently) { OP_STATUS status; if (!CanAddWord(word) || m_added_words.HasString(word)) return OpStatus::OK; if (m_removed_words.HasString(word)) { BOOL dummy = FALSE; m_removed_words.RemoveString(word); if (permanently) RETURN_IF_ERROR(RemoveStringsFromOwnFile(word,FALSE,dummy)); BOOL has_word = FALSE; RETURN_IF_ERROR(IsWordInDictionary(word, has_word)); if (has_word && !m_added_from_file_and_later_removed.HasString(word)) return OpStatus::OK; } else RETURN_IF_ERROR(m_added_words.AddString(word)); if (!permanently) return OpStatus::OK; RETURN_IF_ERROR(CreateOwnFileIfNotExists()); OpFile own_file; int file_len = 0; RETURN_IF_ERROR(SCOpenFile(m_own_path, own_file, file_len, OPFILE_READ)); UINT8 *buf = TempBuffer(); status = ConvertStringFromUTF16(word, buf, SPC_TEMP_BUFFER_BYTES); int word_bytes = op_strlen((const char*)buf) + 1; UINT8 *new_data = OP_NEWA(UINT8, file_len+word_bytes); if (OpStatus::IsError(status) || !new_data) { own_file.Close(); ReleaseTempBuffer(); OP_DELETEA(new_data); return SPC_ERROR(OpStatus::IsError(status) ? status : OpStatus::ERR_NO_MEMORY); } op_strcpy((char*)new_data, (const char*)buf); new_data[word_bytes-1] = '\n'; OpFileLength bytes_read = 0; status = own_file.Read(new_data+word_bytes, (OpFileLength)file_len, &bytes_read); if (OpStatus::IsSuccess(status)) { own_file.Close(); int dummy = 0; status = SCOpenFile(m_own_path, own_file, dummy, OPFILE_WRITE); if (OpStatus::IsSuccess(status)) status = own_file.SetFileLength(0); if (OpStatus::IsSuccess(status)) status = own_file.SetFilePos(0); // not so necessary I guess... if (OpStatus::IsSuccess(status)) status = own_file.Write(new_data, (OpFileLength)(file_len+word_bytes)); } own_file.Close(); ReleaseTempBuffer(); OP_DELETEA(new_data); return OpStatus::IsError(status) ? SPC_ERROR(status) : OpStatus::OK; } OP_STATUS OpSpellChecker::RemoveWord(const uni_char *word, BOOL permanently) { OP_STATUS status; const uni_char* word_end = word + uni_strlen(word); if (!CanSpellCheck(word, word_end) || m_removed_words.HasString(word)) return OpStatus::OK; BOOL removed_from_file = FALSE; if (permanently) RETURN_IF_ERROR(RemoveStringsFromOwnFile(word,TRUE,removed_from_file)); if (m_added_words.HasString(word)) { m_added_words.RemoveString(word); BOOL has_word = FALSE; RETURN_IF_ERROR(IsWordInDictionary(word, has_word)); if (!has_word) return OpStatus::OK; } else if (removed_from_file && !m_added_from_file_and_later_removed.HasString(word)) RETURN_IF_ERROR(m_added_from_file_and_later_removed.AddString(word)); RETURN_IF_ERROR(m_removed_words.AddString(word)); if (!permanently || removed_from_file) return OpStatus::OK; RETURN_IF_ERROR(CreateOwnFileIfNotExists()); OpFile own_file; int file_len = 0; RETURN_IF_ERROR(SCOpenFile(m_own_path, own_file, file_len, OPFILE_APPEND)); UINT8 *buf = TempBuffer(); status = ConvertStringFromUTF16(word, buf, SPC_TEMP_BUFFER_BYTES); int word_bytes = op_strlen((const char*)buf); if (OpStatus::IsSuccess(status)) status = own_file.Write(buf,(OpFileLength)word_bytes); if (OpStatus::IsSuccess(status)) status = own_file.Write("\n",1); own_file.Close(); ReleaseTempBuffer(); return OpStatus::IsError(status) ? SPC_ERROR(status) : OpStatus::OK; } #endif // !SPC_USE_HUNSPELL_ENGINE #endif // INTERNAL_SPELLCHECK_SUPPORT
f29565293acf518a19cca2873b9b92a3eef4a105
999bbd6b2ffdbd511924f18b9f1aae234ce226f6
/include/btwxt/regular-grid-interpolator.h
2c2dca626d7b3ab871c51be9b4b871df7efd72ca
[ "BSD-2-Clause" ]
permissive
bigladder/btwxt
c89930861dfe5cadeb56dcdb733931b972f5ea29
2a5926e96b594bafbcaa7640a9cabd40b5ae043d
refs/heads/main
2023-09-06T02:23:54.925497
2023-08-28T17:11:31
2023-08-28T17:11:31
133,846,917
11
9
BSD-3-Clause
2023-08-28T17:11:33
2018-05-17T17:27:26
C++
UTF-8
C++
false
false
4,987
h
regular-grid-interpolator.h
/* Copyright (c) 2018 Big Ladder Software LLC. All rights reserved. * See the LICENSE file for additional terms and conditions. */ #pragma once // Standard #include <functional> #include <memory> #include <vector> #include <courierr/courierr.h> // btwxt #include "grid-axis.h" #include "grid-point-data.h" #include "logging.h" namespace Btwxt { class RegularGridInterpolatorImplementation; enum class TargetBoundsStatus { below_lower_extrapolation_limit, extrapolate_low, interpolate, extrapolate_high, above_upper_extrapolation_limit }; // this will be the public-facing class. class RegularGridInterpolator { public: RegularGridInterpolator(); explicit RegularGridInterpolator( const std::vector<std::vector<double>>& grid_axis_vectors, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); RegularGridInterpolator( const std::vector<std::vector<double>>& grid_axis_vectors, const std::vector<std::vector<double>>& grid_point_data_vectors, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); explicit RegularGridInterpolator( const std::vector<GridAxis>& grid_axes, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); RegularGridInterpolator( const std::vector<GridAxis>& grid_axes, const std::vector<std::vector<double>>& grid_point_data_vectors, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); RegularGridInterpolator( const std::vector<std::vector<double>>& grid_axis_vectors, const std::vector<GridPointDataSet>& grid_point_data_sets, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); RegularGridInterpolator( const std::vector<GridAxis>& grid_axes, const std::vector<GridPointDataSet>& grid_point_data_sets, const std::shared_ptr<Courierr::Courierr>& logger = std::make_shared<BtwxtLogger>()); ~RegularGridInterpolator(); RegularGridInterpolator(const RegularGridInterpolator& source); RegularGridInterpolator(const RegularGridInterpolator& source, const std::shared_ptr<Courierr::Courierr>& logger); RegularGridInterpolator& operator=(const RegularGridInterpolator& source); std::size_t add_grid_point_data_set(const std::vector<double>& grid_point_data_vector, const std::string& name = ""); std::size_t add_grid_point_data_set(const GridPointDataSet& grid_point_data_set); void set_axis_extrapolation_method(std::size_t axis_index, ExtrapolationMethod method); void set_axis_interpolation_method(std::size_t axis_index, InterpolationMethod method); void set_axis_extrapolation_limits(std::size_t axis_index, const std::pair<double, double>& extrapolation_limits); std::size_t get_number_of_dimensions(); // Public normalization methods double normalize_grid_point_data_set_at_target(std::size_t data_set_index, double scalar = 1.0); double normalize_grid_point_data_set_at_target(std::size_t data_set_index, const std::vector<double>& target, double scalar = 1.0); void normalize_grid_point_data_sets_at_target(double scalar = 1.0); void normalize_grid_point_data_sets_at_target(const std::vector<double>& target, double scalar = 1.0); std::string write_data(); // Get results void set_target(const std::vector<double>& target); double get_value_at_target(const std::vector<double>& target, std::size_t data_set_index); double operator()(const std::vector<double>& target, const std::size_t data_set_index) { return get_value_at_target(target, data_set_index); } double get_value_at_target(std::size_t data_set_index); double operator()(const std::size_t data_set_index) { return get_value_at_target(data_set_index); } std::vector<double> get_values_at_target(const std::vector<double>& target); std::vector<double> operator()(const std::vector<double>& target) { return get_values_at_target(target); } std::vector<double> get_values_at_target(); std::vector<double> operator()() { return get_values_at_target(); } const std::vector<double>& get_target(); [[nodiscard]] const std::vector<TargetBoundsStatus>& get_target_bounds_status() const; void clear_target(); void set_logger(const std::shared_ptr<Courierr::Courierr>& logger, bool set_grid_axes_loggers = false); std::shared_ptr<Courierr::Courierr> get_logger(); private: std::unique_ptr<RegularGridInterpolatorImplementation> implementation; }; } // namespace Btwxt
65f297f8af35a214e06416a4c952840fcbb8e1f4
d9c9095e837a6f22377a89bd8b88e1ba8ac79ca6
/luogu/P1328 生活大爆炸版石头剪刀布.cpp
224289e968005d83d3b1fa148a0a4123d36052f1
[]
no_license
alexcui03/luogu-test
3ade46adb43adf50a8f2b40dfde83d399116f0fa
7614ce64adcf5399181b113bcc571cdc84092f0f
refs/heads/master
2021-06-28T02:08:33.365736
2020-12-02T14:47:01
2020-12-02T14:47:01
177,288,367
2
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
P1328 生活大爆炸版石头剪刀布.cpp
#include <iostream> using namespace std; constexpr bool result[5][5] = { { 0, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0 }, { 0, 1, 0, 0, 1 }, { 0, 0, 1, 0, 1 }, { 1, 1, 0, 0, 0 } }; int main() { short n, na, nb; cin >> n >> na >> nb; short *ra = new short[na], *rb = new short[nb]; for (int i = 0; i < na; ++i) cin >> ra[i]; for (int i = 0; i < nb; ++i) cin >> rb[i]; short sa = 0, sb = 0; while (n--) { sa += result[ra[n % na]][rb[n % nb]]; sb += result[rb[n % nb]][ra[n % na]]; } cout << sa << ' ' << sb << endl; return 0; }
5ed12005318f10a8b2da6da6e41b2eda11b0b9ef
c16b72f3553c67429357df3ee8d22a35245a6b48
/Tree.h
9b69836a198d264699f0624ee43b130e39fc4485
[]
no_license
Butanosuke/Kikori
848b3669ddc7e277123079fbb98d43377d67dfe9
091f2d88521856bedd8a74d77496fcdf205af7d0
refs/heads/master
2021-01-23T11:50:22.617548
2015-07-23T10:48:35
2015-07-23T10:48:35
38,837,887
1
0
null
null
null
null
UTF-8
C++
false
false
90
h
Tree.h
#pragma once class Tree { public: Tree(void); ~Tree(void); void Draw(); };
25c281fb91960e03fe04a53b0afe2265befab38e
be76d466ea7fe3692eab3af51e0b7afb9a96e23e
/OnlineReversi/OnlineReversi/Reversi.cpp
155b8d999c2baa0b8deebb48422a9463f6a11883
[]
no_license
yuki-takamura/OnlineReversi
3ac7f33dd068ac022bba414f25227f90dfcf67da
59dde9301962edf662539eea41ad4f279b0768c9
refs/heads/master
2021-01-02T15:35:11.459305
2017-08-06T19:44:55
2017-08-06T19:44:55
99,303,733
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,981
cpp
Reversi.cpp
#include "NetworkManager.h" #include <iostream> #include <time.h> #include <random> #include "DrawObject.h" #include "Reversi.h" using namespace std; Reversi::Reversi(bool isVersion7) { this->isVersion7 = isVersion7; srand((unsigned)time(NULL)); player[0].myColor = Color::WHITE; player[1].myColor = Color::BLACK; } void Reversi::run() { int sqN = 0; string inputBuffer; string message; char buffer[256]; char receiveBuffer[256]; string host; unsigned short port = 0; SOCKET soc; int rcv; bool isConnecting = false; //設定 while (cpu == Other) { cout << "1:server 2:client\n"; getline(cin, inputBuffer); switch (atoi(inputBuffer.c_str())) { case 1: cpu = Server; break; case 2: cpu = Client; break; default: cout << "1 or 2 を入力せよ\n"; } } //接続 while (!isConnecting) { switch (cpu) { case Server: networkManager.inputPort(&port); if (networkManager.serverStart(port, &soc)) { cout << "ソケット通信機能が正常に使用できなかったので通信は行いません\n"; } else { message = networkManager.encode(sqN); cout << message << "送信\n";//実際にどのような文字を送るのか確認 int sendBytes = send(soc, message.c_str(), message.length(), 0); cout << sendBytes << "bytes 送信完了\n"; isConnecting = true; } break; case Client: networkManager.inputHost(&host); networkManager.inputPort(&port); if (networkManager.clientStart(host, port, &soc)) { cout << "ソケット通信機能が正常に使用できなかったので通信は行いません\n"; } else { cout << "受信待ち\n"; rcv = recv(soc, receiveBuffer, sizeof(receiveBuffer) - 1, 0); if (rcv == SOCKET_ERROR) { cout << "受信出来ませんでした\n"; } else { receiveBuffer[rcv] = '\0'; cout << "受信\n"; //実際にどのような文字を受信したか確認 cout << rcv << "bytes 受信完了\n"; sqN = networkManager.decode(receiveBuffer); isConnecting = true; } } break; default: break; } } Reversi::initialize(); Reversi::draw(); //実行 while (true) { switch (cpu) { case Server: cout << "相手(黒)の番です"; rcv = recv(soc, buffer, sizeof(buffer) - 1, 0); if (rcv == SOCKET_ERROR) { cout << "error"; break; } buffer[rcv] = '\0'; if (player[1].checkEnd(stone)) { canNotPut[1] = false; player[1].update(stone, buffer); } else canNotPut[1] = true; Reversi::update(); Reversi::draw(); if (strcmp(buffer, "c_end") == 0) { cout << "クライアントが切断\n"; break; } cout << "受信 : " << buffer << "に置かれました\n"; cout << "あなた(白)の番です : "; cin >> buffer; if (strcmp(buffer, "s_end") == 0) { send(soc, buffer, int(strlen(buffer)), 0); break; } //置けるかどうかの判定処理 if (player[0].checkEnd(stone)) { canNotPut[0] = false; player[0].update(stone, buffer); } else canNotPut[0] = true; send(soc, buffer, int(strlen(buffer)), 0); Reversi::update(); Reversi::draw(); break; case Client: cout << "あなた(黒)の番です : "; cin >> buffer; if (strcmp(buffer, "c_end") == 0) { send(soc, buffer, (int)strlen(buffer), 0); break; } //置けるかどうかの判定 if (player[1].checkEnd(stone)) { canNotPut[1] = false; player[1].update(stone, buffer); } else canNotPut[1] = true; send(soc, buffer, (int)strlen(buffer), 0); Reversi::update(); Reversi::draw(); cout << "相手(白)の番です\n"; rcv = recv(soc, buffer, sizeof(buffer) - 1, 0); if (rcv == SOCKET_ERROR) { cout << "error\n"; break; } buffer[rcv] = '\0'; if (player[0].checkEnd(stone)) { canNotPut[0] = false; player[0].update(stone, buffer); } else canNotPut[0] = true; Reversi::update(); Reversi::draw(); if (strcmp(buffer, "s_end") == 0) { cout << "サーバーが切断\n"; break; } cout << "受信 : " << buffer << "に置かれました\n"; break; default: break; } if (canNotPut[0] && canNotPut[1]) { cout << "終了します" << endl; break; } } networkManager.socketEnd(&soc); } void Reversi::initialize() { board.initialize(); const int GREEN = 0; const int BLACK = 1; const int WHITE = 2; for (int i = 0; i < VERTICAL; i++) { for (int j = 0; j < HORIZONTAL; j++) { //中央の左上 if ((j + 1) * 2 == HORIZONTAL && (i + 1) * 2 == VERTICAL) { stone[i][j].initialize(BLACK); continue; } //中央の右上 if (j * 2 == HORIZONTAL && (i + 1) * 2 == VERTICAL) { stone[i][j].initialize(WHITE); continue; } //中央の左下 if ((j + 1) * 2 == HORIZONTAL && i * 2 == VERTICAL) { stone[i][j].initialize(WHITE); continue; } //中央の右下 if (j * 2 == HORIZONTAL && i * 2 == VERTICAL) { stone[i][j].initialize(BLACK); continue; } stone[i][j].initialize(GREEN); } } } void Reversi::update() { //描画更新 system("cls"); if (canNotPut[0] && canNotPut[1]) { for (int i = 0; i < VERTICAL; i++) { for (int j = 0; j < HORIZONTAL;j++) { if (stone[i][j].myColor == Color::BLACK) stoneCounter[0]++; else if (stone[i][j].myColor == Color::WHITE) stoneCounter[1]++; } } if (stoneCounter[0] > stoneCounter[1]) { cout << "あなたの勝ちです" << endl; } else if (stoneCounter[0] < stoneCounter[1]) { cout << "相手の勝ちです" << endl; } else { cout << "ひきわけ" << endl; } cout << "くろ : " << stoneCounter[0] << "個" << endl; cout << "しろ : " << stoneCounter[1] << "個" << endl; } } void Reversi::draw() { cout << endl; guide.drawHorizontal(isVersion7); board.draw(stone, guide); }
28eebb2ebd74c41c801538262fcba5c3cc6208f1
8d4a8691a1a095b0b271b27fde97d886c4a24c8f
/mapCell.cpp
6ac819675f498f63a8ecaf14ac473a693b386c61
[]
no_license
felixwangchao/Tankwar
4887e303bd40407de234323157c0e900171f0b57
ba3c3820fb8f654a3965a1364246bcd678fb1830
refs/heads/master
2021-04-19T00:58:08.791073
2017-06-17T01:53:50
2017-06-17T01:53:50
94,594,038
0
0
null
null
null
null
GB18030
C++
false
false
4,905
cpp
mapCell.cpp
#include "mapCell.h" #include "Data.h" #include "Draw.h" // 无参构造函数 mapCell::mapCell(){ this->mapCellType = 0; this->color = 0; this->showLevel = 0; this->mis_pass = 0; this->mis_destory = 0; this->tank_pass = 0; } //有参构造函数 mapCell::mapCell(int mapCellType){ switch (mapCellType){ /* 类型 颜色 显示级别 子弹能否通过, 子弹能否摧毁, 坦克能否通过 */ case WALL_NULL: /*空 空道*/ setMapCellInfo(WALL_NULL, F_WHITE, SHOWLEVEL_0,true,false,true); break; case WALL_A1: /*▓ 土墙*/ setMapCellInfo(WALL_A1, F_RED, SHOWLEVEL_1,false,true,false); break; case WALL_A2: /*卍 土墙*/ setMapCellInfo(WALL_A2, F_RED, SHOWLEVEL_1,false,true,false); break; case WALL_B: /*〓 铁墙*/ setMapCellInfo(WALL_B, F_CYAN, SHOWLEVEL_1,false,false,false); break; case WALL_C: /*≈ 河流*/ setMapCellInfo(WALL_C, F_H_BLUE, SHOWLEVEL_0,true,false,false); break; case WALL_D: /*■ 路障*/ setMapCellInfo(WALL_D, F_WHITE, SHOWLEVEL_1,false,false,false); break; case WALL_E: /*≡ 丛林*/ setMapCellInfo(WALL_E, F_H_GREEN, SHOWLEVEL_2,true,false,true); break; case WALL_F: /*※ 高速路*/ setMapCellInfo(WALL_F, F_YELLOW, SHOWLEVEL_0,true,false,true); break; case WALL_G: /*☆ 箱子*/ setMapCellInfo(WALL_G, B_H_YELLOW, SHOWLEVEL_3,true,false,true); break; case CELLSTART_P1: /*玩家1出生点*/ setMapCellInfo(CELLSTART_P1, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_P2: /*玩家2出生点*/ setMapCellInfo(CELLSTART_P2, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_P3: /*玩家3出生点*/ setMapCellInfo(CELLSTART_P3, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N1: /*NPC1出生点 */ setMapCellInfo(CELLSTART_N1, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N2: /*NPC2出生点 */ setMapCellInfo(CELLSTART_N2, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N3: /*NPC3出生点 */ setMapCellInfo(CELLSTART_N3, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N4: /*NPC4出生点 */ setMapCellInfo(CELLSTART_N4, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N5: /*NPC5出生点 */ setMapCellInfo(CELLSTART_N5, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_N6: /*NPC6出生点 */ setMapCellInfo(CELLSTART_N6, F_WHITE, SHOWLEVEL_0,true,false,true); break; case CELLSTART_H1: /*阵营1基地 */ setMapCellInfo(CELLSTART_H1, F_GREEN, SHOWLEVEL_3,false,true,false); break; case CELLSTART_H2: /*阵营2基地 */ setMapCellInfo(CELLSTART_H2, F_H_PURPLE, SHOWLEVEL_3,false,true,false); break; case CELLSTART_H3: /*阵营3基地 */ setMapCellInfo(CELLSTART_H3, F_H_RED, SHOWLEVEL_3,false,true,false); break; case CELLSTART_H4: /*阵营NPC基地*/ setMapCellInfo(CELLSTART_H4, F_H_BLUE, SHOWLEVEL_3,false,true,false); break; } } // 设置信息函数 void mapCell::setMapCellInfo(int mapCellType, int color,int showLevel,bool mis_pass, bool mis_destory, bool tank_pass) { this->mapCellType = mapCellType; this->color = color; this->showLevel = showLevel; this->mis_pass = mis_pass; this->mis_destory = mis_destory; this->tank_pass = tank_pass; } // 绘制地图点函数 void mapCell::drawMapCell(int row, int col,int tmp_color) { int wallType = mapCellType; int color_print = (tmp_color > 0) ? tmp_color : color; if (wallType == WALL_NULL) { writeChar(row, col, " ", color_print); } if (wallType == WALL_A1) { writeChar(row, col, WALL_A1_PC, color_print); } if (wallType == WALL_A2) { writeChar(row, col, WALL_A2_PC, color_print); } if (wallType == WALL_B) { writeChar(row, col, WALL_B_PC, color_print); } if (wallType == WALL_C) { writeChar(row, col, WALL_C_PC, color_print); } if (wallType == WALL_D) { writeChar(row, col, WALL_D_PC, color_print); } if (wallType == WALL_E) { writeChar(row, col, WALL_E_PC, color_print); } if (wallType == WALL_F) { writeChar(row, col, WALL_F_PC, color_print); } if (wallType == WALL_G) { writeChar(row, col, WALL_G_PC, color_print); } if (wallType == CELLSTART_H1) { writeChar(row, col, WALL_G_PC, color_print); } } void mapCell::Destory(){ // 地形被摧毁时调用 setMapCellInfo(WALL_NULL, F_WHITE, SHOWLEVEL_0, true, false, true); }; // Map无参构造函数 Map::Map(){ } // 初始化地图信息,注意读取时X轴Y轴交换 void Map::InitMap(int load_map[][40]){ for (int row = 0; row < MAP_HIGH; row++) { for (int col = 0; col < MAP_WIDTH; col++) { MapData[row][col] = mapCell(load_map[col][row]); LMapData[row][col] = 0; } } } // 绘制地图 void Map::drawMap() { for (int row = 0; row < MAP_HIGH; row++) { for (int col = 0; col < MAP_WIDTH; col++) { MapData[row][col].drawMapCell(row,col); if (MapData[row][col].MapCellType() == WALL_G) box_flag = 1; } } } // 正在使用的地图 Map CurrentMap;
2e9462e096122f843e8b3f1e7931af6c3fbd5e79
48520d818ecbaaeca8772c8fd29b613b594811df
/Prototype/src/Vaango_UILayout.h
f948fff16c0b086ad0e4f188fbbd5b9c14c3a45a
[]
no_license
bbanerjee/VaangoUI
f902cd5182aa8c46bc72f10ae732a948d6f50ef7
677c976b01ee4e43c4502076a8d36a631a0690ed
refs/heads/master
2022-12-22T09:56:12.832778
2022-12-15T05:56:05
2022-12-15T05:56:05
95,497,463
0
2
null
2017-07-10T22:55:52
2017-06-26T23:17:25
JavaScript
UTF-8
C++
false
false
1,396
h
Vaango_UILayout.h
#ifndef __Vaango_UI_DRAW_H__ #define __Vaango_UI_DRAW_H__ #include <Vaango_UIBase.h> #include <imgui.h> #include <memory> #include <glad/glad.h> #include <GLFW/glfw3.h> namespace VaangoUI { class Vaango_UIPanelBase; class Vaango_UILayout : public Vaango_UIBase { public: Vaango_UILayout(GLFWwindow* mainWindow, const std::string& settingsFile); virtual ~Vaango_UILayout(); protected: virtual bool isViewVisible() override { //return !ImGui::IsPopupOpen(); return true; } virtual void addMessageToConsole(const char* message) override {}; virtual void draw(AIS_InteractiveContext* context, V3d_View* view, const bool hasFocus) override; private: void init(AIS_InteractiveContext* context, V3d_View* view); Vaango_UIPanelBase* getPanel(const std::string& id_string) { auto panel_iter = d_panels.find(id_string.c_str()); if (panel_iter == d_panels.end()) { throw std::runtime_error("Could not find VaangoUI panel " + id_string); } return panel_iter->second.get(); } private: GLFWwindow* d_mainWindow; std::map<std::string, std::unique_ptr<Vaango_UIPanelBase>> d_panels; bool d_isInitialized; bool d_autoscaleUIfromDPI = true; bool d_isViewVisible = true; std::string d_settingsFileName; }; } // namespace VaangoUI #endif //__Vaango_UI_DRAW_H__
031695ff2c77eddc95ce7146b1fc1891e16b86d5
cb4e16f41bfedb9a96f21f6394d3efe9ac3557d5
/Sorting/sorting1.cpp
187de98d0913d085b69166cc74ea25acbfcce2e1
[]
no_license
Trung1234/AlgorithmExcercise
958fc6618b14e0e03365499b2252c32d18405a08
57d6245811d470ce5ee9443f4335f6b63aa43d78
refs/heads/master
2022-04-24T23:11:00.201827
2020-04-15T03:39:41
2020-04-15T03:39:41
111,266,001
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
sorting1.cpp
#include <iostream> #include <fstream> #include <math.h> #include <string.h> #include <stdio.h> #include <algorithm> using namespace std; int n; int a[1111]; void input(){ scanf("%d",&n); for (int i=0;i<n;i++) scanf("%d",&a[i]); } // ham so sanh giua 2 phan tu // s1 dung truoc , s2 dung sau // xac dinh cach sap xep giua 2 phan tu bool cmp(int s1,int s2){ if ( s1 > s2 ) return false; return true; } void solve(){ // cach 1 : sort tu be den lon // bien the 1 //sort(a,a+n); // dao thu tu array //reverse(a,a+n); // cach 2 : sort voi ham compare tham so sort(a,a+n,cmp); } void output(){ for (int i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); } int main(int argc, const char * argv[]) { freopen("input.txt","r",stdin); int ntest; scanf("%d",&ntest); for (int itest=0;itest<ntest;itest++){ input(); solve(); output(); } }
587dfcabdaf25d1273a9d600e7606236b51cc299
ce6ade9b0e03d69118f538392be2573792297ecf
/lidardata_pub/Ls01aDriver.h
4888e3c21867708d0a7a47f7099617181675bde4
[]
no_license
zdevt/cls
f1042c20e707c62bce08bd7d527e4090bed28a53
7518fdb60192817e7aac30a3462b2fb184964a4f
refs/heads/master
2020-03-19T02:43:24.557383
2018-06-01T01:55:36
2018-06-01T01:55:36
135,654,669
0
0
null
null
null
null
UTF-8
C++
false
false
1,545
h
Ls01aDriver.h
/* * ========================================================================= * * FileName: Ls01aDriver.h * * Description: * * Version: 1.0 * Created: 2018-03-06 15:57:54 * Last Modified: 2018-04-20 14:00:31 * Revision: none * Compiler: gcc * * Author: zt () * Organization: * * ========================================================================= */ #ifndef LS01ADRIVER_INC #define LS01ADRIVER_INC #include <string> #include <memory> #include <thread> #include <mutex> #include <vector> #include "SerialPort.h" #include "LidarData.h" #include "../common/EvClient.h" #include "../common/Common.h" class Ls01aDriver { private: explicit Ls01aDriver ( std::string devname ); virtual ~Ls01aDriver(); void ReadLidarData ( ); void SendLidarData ( ); private: int SendCmd ( uint8_t* pcmd, int cmdlen ); int StartScan(); int SingleScan ( LidarData& single_scan_data ); int Scan(); int StopScan(); public: static Ls01aDriver* GetInstance ( std::string devname ); int Start(); int Stop(); void InitialEvClient ( std::string ip = "127.0.0.1", uint16_t port = 18888 ); private: bool m_runFlag; bool m_scanFlag; std::thread m_threadReadLidarData; std::thread m_threadSendLidarData; std::mutex m_mutex; std::vector<uint8_t> m_vecBuffer; std::shared_ptr<EvClient> m_sp_EvClient; SerialPort m_serialport; LidarData m_single_scan_data; }; #endif /* LS01ADRIVER_INC */
e7deded9ab66cff7f2b0489bcbd928e63867afc7
de7ee4345f6706673e4b4ece6aa3dd66fa24561f
/header/Connector.hpp
89af705ee09cb1cb533cbad81ee8eaa74e2c01a7
[ "MIT" ]
permissive
mohamedrayyan/Rshell
e011db5eb93186bac4941428832f0f1b9d83cbf7
37c0dd264799d199e6c0dc1f13ae1e25f9368620
refs/heads/master
2022-03-22T16:54:27.020109
2019-12-19T19:33:29
2019-12-19T19:33:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
413
hpp
Connector.hpp
#ifndef CONNECTOR #define CONNECTOR #include "Executable.hpp" #include "Cmnd.hpp" class Connector : public Executable { protected: Executable* left; Executable* right; public: virtual bool run_command() =0; virtual char** get_command() {} virtual void set_left(Executable*) =0; virtual void set_right(Executable*) =0; virtual Executable* get_left() =0; virtual Executable* get_right() =0; }; #endif
ba9e36cc7b28808506477cb4271a849eb86272e6
c45ed46065d8b78dac0dd7df1c95b944f34d1033
/TC-SRM-564-div1-250/ywq.cpp
551d83e5b04f9fd84a1dd950e2464374d9134eaa
[]
no_license
yzq986/cntt2016-hw1
ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e
12e799467888a0b3c99ae117cce84e8842d92337
refs/heads/master
2021-01-17T11:27:32.270012
2017-01-26T03:23:22
2017-01-26T03:23:22
84,036,200
0
0
null
2017-03-06T06:04:12
2017-03-06T06:04:12
null
UTF-8
C++
false
false
518
cpp
ywq.cpp
#include <map> #include <cmath> #include <cstdio> #include <string> #include <vector> #include <cstring> #include <algorithm> using namespace std; #define pb push_back #define mp make_pair #define x first #define y second typedef long long ll; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<pii> vpii; struct KnightCircuit2 { int maxSize(int w, int h) { if (w>h) swap(w,h); if (w==1) return 1; if (w==2) return (h+1)/2; if (h==3) return 8; return w*h; } };
50de6e94909271277405362ad65706d5120e8c07
76aae6cab924b1d9ddd66cb2862db6ba2c65960a
/Rin_and_unknow_flower.cpp
a89feb9a2f5e18deedccf670fcb046e8174bf729
[]
no_license
eng-arvind/Codeforces_problem
3308edc588754947796a4c244bf893b027ca4414
4717f374e2fda556bd2fb80b1424ca7743f8654f
refs/heads/master
2020-11-27T02:30:24.188027
2020-08-25T16:03:59
2020-08-25T16:03:59
229,273,210
1
0
null
null
null
null
UTF-8
C++
false
false
9,909
cpp
Rin_and_unknow_flower.cpp
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int n; cin >> n; string s(n, '?'); auto Ask = [&](string t) { cout << "? " << t << endl; int foo; cin >> foo; for (int i = 0; i < foo; i++) { int bar; cin >> bar; --bar; for (int j = 0; j < (int) t.size(); j++) { s[bar + j] = t[j]; } } }; if (n <= 7) { Ask("CH"); Ask("CO"); if (s == string(n, '?')) { if (n == 4) { Ask("HO"); if (s == string(n, '?')) { Ask("OH"); if (s == string(n, '?')) { Ask("CCC"); if (s == string(n, '?')) { Ask("OOO"); if (s[0] == 'O') { if (s[n - 1] == '?') s[n - 1] = 'C'; } else { Ask("HHH"); if (s[0] == 'H') { if (s[n - 1] == '?') s[n - 1] = 'C'; } else { Ask("OOCC"); if (s == string(n, '?')) s = "HHCC"; } } } else { Ask("HCCC"); Ask("OCCC"); } } else { for (int i = 0; i < n; i++) { if (s[i] == '?') { s[i] = 'O'; } else { break; } } goto haha; } } else { goto haha; } } else { Ask("CC"); if (s[1] != '?' && s[0] == '?') { string q = s; q[0] = 'H'; Ask(q); if (s[0] == '?') { s[0] = 'O'; } } else { Ask("OH"); Ask("HO"); if (s == string(n, '?')) { Ask(string(n, 'H')); Ask(string(n, 'O')); if (s == string(n, '?')) { string q(n, 'H'); q[n - 1] = 'C'; Ask(q); if (s == string(n, '?')) { s = string(n, 'O'); s[n - 1] = 'C'; } } } else { if (s[n - 1] == 'C' && s.find("H") == string::npos && s.find("O") == string::npos) { string q = s; for (int i = 0; i < n; i++) { if (q[i] == '?') { q[i] = 'H'; } } Ask(q); if (s[0] == '?') { for (int i = 0; i < n; i++) { if (s[i] == '?') { s[i] = 'O'; } } } } else { int beg = 0; while (beg < n) { if (s[beg] != '?') { ++beg; continue; } int end = beg; while (end + 1 < n && s[end + 1] == '?') { ++end; } if (beg == 0) { for (int i = beg; i <= end; i++) { s[i] = s[end + 1]; } } else { for (int i = beg; i <= end; i++) { s[i] = s[beg - 1]; } } beg = end + 1; } string q = s; q[n - 1] = 'C'; Ask(q); } } } } } else { haha: while (true) { bool any = false; for (int i = 0; i < n; i++) { if (s[i] == '?') { any = true; break; } } if (!any) { break; } bool found = false; for (int i = 0; i + 4 < n; i++) { if (s[i] == '?' && s[i + 1] != '?' && s[i + 2] != '?' && s[i + 3] != '?' && s[i + 4] != '?') { string q = "C"; q += s[i + 1]; q += s[i + 2]; q += s[i + 3]; q += s[i + 4]; Ask(q); if (s[i] == '?') { q[0] = 'O'; Ask(q); if (s[i] == '?') { s[i] = 'H'; } } found = true; break; } } if (found) continue; for (int i = 0; i + 4 < n; i++) { if (s[i] != '?' && s[i + 1] != '?' && s[i + 2] != '?' && s[i + 3] != '?' && s[i + 4] == '?') { string q = ""; q += s[i]; q += s[i + 1]; q += s[i + 2]; q += s[i + 3]; q += "C"; Ask(q); if (s[i + 4] == '?') { q[4] = 'O'; Ask(q); if (s[i + 4] == '?') { s[i + 4] = 'H'; } } found = true; break; } } if (found) continue; for (int i = 0; i + 3 < n; i++) { if (s[i] == '?' && s[i + 1] != '?' && s[i + 2] != '?' && s[i + 3] != '?') { string q = "C"; q += s[i + 1]; q += s[i + 2]; q += s[i + 3]; Ask(q); if (s[i] == '?') { q[0] = 'O'; Ask(q); if (s[i] == '?') { s[i] = 'H'; } } found = true; break; } } if (found) continue; for (int i = 0; i + 3 < n; i++) { if (s[i] != '?' && s[i + 1] != '?' && s[i + 2] != '?' && s[i + 3] == '?') { string q = ""; q += s[i]; q += s[i + 1]; q += s[i + 2]; q += "C"; Ask(q); if (s[i + 3] == '?') { q[3] = 'O'; Ask(q); if (s[i + 3] == '?') { s[i + 3] = 'H'; } } found = true; break; } } if (found) continue; for (int i = 0; i + 2 < n; i++) { if (s[i] == '?' && s[i + 1] != '?' && s[i + 2] != '?') { string q = "C"; q += s[i + 1]; q += s[i + 2]; Ask(q); if (s[i] == '?') { q[0] = 'O'; Ask(q); if (s[i] == '?') { s[i] = 'H'; } } found = true; break; } } if (found) continue; for (int i = 0; i + 2 < n; i++) { if (s[i] != '?' && s[i + 1] != '?' && s[i + 2] == '?') { string q = ""; q += s[i]; q += s[i + 1]; q += "C"; Ask(q); if (s[i + 2] == '?') { q[2] = 'O'; Ask(q); if (s[i + 2] == '?') { s[i + 2] = 'H'; } } found = true; break; } } assert(found); } } } else { Ask("CH"); Ask("CO"); Ask("HC"); Ask("HO"); Ask("OC"); if (s == string(n, '?')) { Ask(string(n, 'C')); if (s == string(n, '?')) { Ask("OHH"); if (s == string(n, '?')) { Ask(string(n - 1, 'O')); if (s == string(n, '?')) { s = string(n, 'H'); } else { if (s[n - 1] == '?') { s[n - 1] = 'H'; } } } else { for (int i = 0; i < n; i++) { if (s[i] == '?') { s[i] = 'O'; } else { break; } } for (int i = n - 1; i >= 0; i--) { if (s[i] == '?') { s[i] = 'H'; } else { break; } } } } } else { Ask("OHH"); int pref = 0, suf = 0; int beg = 0; while (beg < n) { if (s[beg] != '?') { ++beg; continue; } int end = beg; while (end + 1 < n && s[end + 1] == '?') { ++end; } if (beg == 0) { if (s[end + 1] != 'H') { for (int i = beg; i <= end; i++) { s[i] = s[end + 1]; } } else { pref = end + 1; } } else { if (end == n - 1) { if (s[beg - 1] != 'O') { for (int i = beg; i <= end; i++) { s[i] = s[beg - 1]; } } else { for (int i = beg; i <= end - 1; i++) { s[i] = 'O'; } suf = 1; } } else { if (s[beg - 1] == 'O' && s[end + 1] == 'H') { for (int i = beg; i <= end; i++) { s[i] = 'O'; } } else { assert(s[beg - 1] == s[end + 1]); for (int i = beg; i <= end; i++) { s[i] = s[beg - 1]; } } } } beg = end + 1; } if (pref > 0) { string q = s; if (suf > 0) { q.pop_back(); } for (int i = 0; i < pref; i++) { q[i] = 'O'; } Ask(q); if (s[0] == '?') { for (int i = 0; i < pref; i++) { s[i] = 'H'; } } } if (suf > 0) { string q = s; q[n - 1] = 'O'; Ask(q); if (s[n - 1] == '?') { s[n - 1] = 'H'; } } } } cout << "! " << s << endl; int foo; cin >> foo; if (foo == 0) break; } return 0; }
96dba3ba75a85fec185a0bebd063e03f23ee3321
f81dd7de276236638e073c0ff00ac18cb2eb64b2
/task3.cpp
9f2a648becd4ecf7a161720e149bb8a74d29ae3c
[]
no_license
sef-computin/engineerium
56adc5344fb5eb7e31a2a96e95bf2f5afec7160c
5aa8f3fa374c0799114f4f18a0db63474a69031a
refs/heads/main
2023-05-15T10:00:17.300004
2021-06-13T12:53:09
2021-06-13T12:53:09
376,388,520
0
0
null
null
null
null
UTF-8
C++
false
false
4,210
cpp
task3.cpp
#include <iostream> static int results = 0; static int Field[11][11]; static int M,N,P; struct Cell{ public: int x; int y; Cell(int i, int j){ x = i; y = j; } }; struct Figure{ public: int width; int height; int placeholder[3][3]; }; Figure COLLECTION[6]={ // ## // # {2, 2, {{1,1,0},{1,0,0},{0,0,0}}}, // ## // # {2, 2, {{2,2,0},{0,2,0},{0,0,0}}}, // # // ## {2, 2, {{3,0,0},{3,3,0},{0,0,0}}}, // # // ## {2, 2, {{0,4,0},{4,4,0},{0,0,0}}}, // ### // {3, 1, {{5,5,5},{0,0,0},{0,0,0}}}, // # // # // # {1, 3, {{6,0,0},{6,0,0},{6,0,0}}} }; static Cell searchEmptyFull(int Field[11][11], Cell st, Cell end, int d){ for (; st.y < end.y; st.y++) { for (; st.x < end.x; st.x++) { if (Field[st.y][st.x] == d) { return st; } } st.x = 0; } return st; } static Cell searchEmpty3x3(int Field[3][3], Cell st, Cell end, int d){ for (; st.y < end.y; st.y++) { for (; st.x < end.x; st.x++) { if (Field[st.y][st.x] == d) { return st; } } st.x = 0; } return st; } static int countEmpty(int y, int x, int count){ if ((y<0)||(x<0)) return count-1; if (Field[y][x]==0){ if (count == 2) return 3; Field[y][x] = 99; count = countEmpty(y, x+1, count+1); if (count<3){ count = countEmpty(y+1, x, count+1); if(count<3){ count = countEmpty(y, x-1, count+1); if (count<3){ count = countEmpty(y-1, x, count+1); } } } Field[y][x] = 0; } else return count-1; return count; } static void findSolutions(int i){ Cell pt(0,0); while(true){ pt = searchEmptyFull(Field, pt, Cell(N,M),0); if (pt.y == M) break; Cell f = searchEmpty3x3(COLLECTION[i].placeholder, Cell(0,0), Cell(3,3), i+1); if((pt.x -f.x >=0) && (pt.x - f.x + COLLECTION[i].width<=N) && (COLLECTION[i].height<=M)){ bool s = true; int d = f.x; for(int y = 0; y<COLLECTION[i].height;y++){ for (int x = 0; x<COLLECTION[i].width; x++){ if(COLLECTION[i].placeholder[y][x] == i+1){ if (Field[pt.y+y][pt.x+x]!=0){ s = false; x = COLLECTION[i].width; y = COLLECTION[i].height; } } } } if (s){ for (int y = 0; y<COLLECTION[i].height; y++){ for(int x = 0; x<COLLECTION[i].width;x++){ Field[pt.y+y][pt.x-f.x+x]+=COLLECTION[i].placeholder[y][x]; } } int y1 = pt.y-1; int x1 = pt.x - f.x-1; if(y1<0) y1 = 0; if(x1<0) x1 = 0; for (int y=y1; y<y1+COLLECTION[i].height+2; y++){ for (int x = x1; x<x1+COLLECTION[i].width+2;x++){ if (Field[y][x] == 0){ if (countEmpty(y,x,0)<3){ s = false; x = N; y = M; } } } } if (s){ if (i<5){ findSolutions(i+1); for (int y =0; y<COLLECTION[i].height;y++){ for (int x = 0; x<COLLECTION[i].width; x++){ Field[pt.y+y][pt.x-f.x+x]-=COLLECTION[i].placeholder[y][x]; } } } else{ Cell pr = pt; pt = searchEmptyFull(Field, Cell(0,0), Cell(N,M), 0); if (pt.x ==0 && pt.y ==M){ results++; printf("Решение: %d\n", results); for (int i = 1; i<4;i++){ for (int j = 1;j<10;j++) { printf("%d ", Field[i][j]); } printf("\n"); } pt = pr; for (int y = 0; y<COLLECTION[i].height;y++){ for (int x = 0; x<COLLECTION[i].width;x++){ Field[pt.y+y][pt.x - f.x + x] -= COLLECTION[i].placeholder[y][x]; } } } } } else{ for (int y = 0; y<COLLECTION[i].height;y++){ for (int x = 0; x<COLLECTION[i].width; x++){ Field[pt.y+y][pt.x - f.x + x] -= COLLECTION[i].placeholder[y][x]; } } } } } pt.x++; if(pt.x == N){ pt.x =0; pt.y++; if(pt.y>=M){ break; } } } } int main(){ N = 10; M = 4; for (int i = 0; i<11;i++){ for (int j = 0; j<11;j++){ Field[i][j] = -1; } } for (int i = 1; i<4;i++){ for (int j = 1;j<10;j++) { Field[i][j] = 0; printf("%d ", Field[i][j]); } printf("\n"); } findSolutions(0); return 0; }
2e5150339fae1029176cd08abf08e3cda1825a03
0c51500f87101f13c471f0c310e9451a87adc714
/irs/src/CRescType.cpp
3549b6d8e3fecb3ab0c6ed9281d9bd550319c116
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
firelab/wfips
a5e589fde41579e87008a7900a87692ec985e529
6b3bd4934d281ebb31164bd242a57079a82053b0
refs/heads/master
2020-05-01T06:03:41.792664
2017-01-27T19:31:55
2017-01-27T19:31:55
14,540,320
2
1
null
null
null
null
UTF-8
C++
false
false
2,940
cpp
CRescType.cpp
// CRescType.cpp // Member functions for class CRescType holding resource type information // created 10/11 for IRS #include <iostream> //contains input and output functions using namespace std; #include <string> //contains functions for operations with strings using std::string; // Include Resouce Type class definitions from CRescType.h #include "CRescType.h" // CRescType default constructor CRescType::CRescType() { m_Type = ""; m_AvgSpeed = 0; m_DispatchDelay = 0; m_ResponseDelay = 0; m_SetupDelay = 0; } // CRescType destructor CRescType::~CRescType() {} // CRescType constructor CRescType::CRescType( string Type, int Avg_Speed, int Disp_Delay, int Resp_Delay, int Setup_Delay) { m_Type = Type; m_AvgSpeed = Avg_Speed;; m_DispatchDelay = Disp_Delay; m_ResponseDelay = Resp_Delay; m_SetupDelay = Setup_Delay; } /** * \brief Copy constructor * \author Kyle Shannon <kyle@pobox.com> * \date 2012-09-11 * \param rhs object to copy */ CRescType::CRescType( const CRescType &rhs ) { m_Type = rhs.m_Type; m_AvgSpeed = rhs.m_AvgSpeed; m_DispatchDelay = rhs.m_DispatchDelay; m_ResponseDelay = rhs.m_ResponseDelay; m_SetupDelay = rhs.m_SetupDelay; } // Set the resource type void CRescType::SetRescType( string resctype ) { m_Type = resctype; } // Get the resource type string CRescType::GetRescType() { return m_Type; } // Set the average speed for the resource type void CRescType::SetAvgSpeed( int speed ) { m_AvgSpeed = speed; } // Get the average speed for the resource type int CRescType::GetAvgSpeed() { return m_AvgSpeed; } // Set the dispatch delay for the resource type void CRescType::SetDispatchDelay( int delay ) { m_DispatchDelay = delay; } // Get the dispatch delay for the resource type int CRescType::GetDispatchDelay() { return m_DispatchDelay; } // Set the response delay for the resource type void CRescType::SetResponseDelay( int delay ) { m_ResponseDelay = delay; } // Get the response delay for the resource type int CRescType::GetResponseDelay() { return m_ResponseDelay; } // Set the setup delay for the resource type void CRescType::SetSetupDelay( int delay ) { m_SetupDelay = delay; } // Get the setup delay for the resource type int CRescType::GetSetupDelay() { return m_SetupDelay; } // Calculate protion of arrival delay due to dispatch, response, and set-up delays int CRescType::PreConstructDelay() { return m_DispatchDelay + m_ResponseDelay + m_SetupDelay; } // Print information about the resource type void CRescType::PrintRescType() { cout << "Resource Type: " << m_Type << "\n"; cout << " Average Speed: " << m_AvgSpeed << "\n"; cout << " Dispatch Delay: " << m_DispatchDelay << "\n"; cout << " Resource Response Delay: " << m_ResponseDelay << "\n"; cout << " Set-up Delay: " << m_SetupDelay << "\n"; return; }
400b1404b3dfe234ff6ae1670a53f7dbee6ccf13
f8fda1f917fde99a8c1ebcb88765cc3136df5c0e
/StrangeAttractor/src/StrangeAttractorApp.cpp
051c78bc568ba6241309f4e9cc6d8023bafa9358
[]
no_license
smandyam/avseoul.github.io
41ffa67993c43310dec33aba6226cbf274c81d93
08846d35b4abe87a58c4340e0b1157ee69eb26de
refs/heads/master
2020-03-12T01:57:16.927387
2018-04-12T07:04:23
2018-04-12T07:04:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,972
cpp
StrangeAttractorApp.cpp
#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/BSpline.h" #include "cinder/Path2d.h" #include "cinder/MayaCamUI.h" #include "cinder/Rand.h" #include "Mover.h" #include "SubMover_01.h" #include "SubMover_02.h" #include <math.h> #include <vector> #include "cinder/gl/TileRender.h" #include "cinder/Utilities.h" using namespace ci; using namespace ci::app; using namespace std; class StrangeAttractorApp : public AppNative { public: void prepareSettings( Settings *settings); void setup(); void update(); void draw(); void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event ); float rotateY; float translateZ; int count; /* camera */ CameraPersp mSceneCam; MayaCamUI mMayaCam; /* strange attractor objects */ vector<Mover*> mMovers; vector<SubMover*> mSubMovers; vector<SubMover02*> mSubMover02s; float sinCountForMover; float sinCountForSubMover; float sinCountForSubMover02; int GLLineIndex; //save frames int mCurrentFrame; }; void StrangeAttractorApp::prepareSettings( Settings *settings) { settings->setWindowSize(1920, 1080); settings->setFullScreen( true ); settings->setTitle( "CINDER" ); settings->setFrameRate(60); } void StrangeAttractorApp::setup() { /* setting for Cemera Matrix */ mSceneCam.setPerspective(45.0f, getWindowAspectRatio(), 0.1, 10000); Vec3f mEye = Vec3f( 0, 0, 3000 ); Vec3f mCenter = Vec3f(Vec3f(0, 0, 0)); Vec3f mUp = Vec3f::yAxis(); mSceneCam.lookAt( mEye, mCenter, mUp ); mSceneCam.setCenterOfInterestPoint(Vec3f(0, 0, 0)); mMayaCam.setCurrentCam(mSceneCam); /* initialize variables */ sinCountForSubMover = 0; sinCountForMover = 0; sinCountForSubMover02 = 0; count = 1; GLLineIndex = 0; /* add one object for each of my strange attractor class */ mMovers.push_back(new Mover(GLLineIndex)); mSubMovers.push_back(new SubMover(GLLineIndex)); mSubMover02s.push_back(new SubMover02(GLLineIndex)); } void StrangeAttractorApp::mouseDown( MouseEvent event ) { mMayaCam.mouseDown( event.getPos()); } void StrangeAttractorApp::mouseDrag( MouseEvent event ) { mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); } void StrangeAttractorApp::update() { int mArraySize = mMovers.size(); int randNum = randInt(2, 5); /* add more objects (the maximum number is 120) */ if(count%randNum == 0){ if(mArraySize < 120){ GLLineIndex++; mMovers.push_back(new Mover(GLLineIndex)); mSubMovers.push_back(new SubMover(GLLineIndex)); mSubMover02s.push_back(new SubMover02(GLLineIndex)); } } /* update my objects */ for(int i = 0; i < mArraySize; i++){ mMovers[i]->calUpdateLocs(sinCountForMover); mSubMovers[i]->calUpdateLocs(sinCountForSubMover); mSubMover02s[i]->calUpdateLocs(sinCountForSubMover); } sinCountForSubMover += 0.005; sinCountForSubMover02 += 0.01; sinCountForMover += 0.025; count++; } void StrangeAttractorApp::draw() { /* set my camera viewport */ gl::setMatrices(mMayaCam.getCamera()); // gl::clear( Color( 0.0f, 0.0f, 0.0f ) ); gl::clear( Color( 0.9f, 0.9f, 0.9f ) ); /* draw my objects and make camera animation */ gl::pushMatrices(); { gl::translate(0, 0, translateZ); gl::pushMatrices(); { gl::rotate(Vec3f(0, rotateY, 0)); ci::Vec3f mRight, mUp; mMayaCam.getCamera().getBillboardVectors(&mRight, &mUp); int mArraySize = mMovers.size(); for(int i = 0; i < mArraySize; i++){ mMovers[i]->drawGLLine(); mMovers[i]->drawMover(); mMovers[i]->drawRandomPoint(mRight, mUp); mSubMovers[i]->drawGLLine(); mSubMovers[i]->drawMover(); mSubMovers[i]->drawRandomPoint(mRight, mUp); mSubMover02s[i]->drawGLLine(); mSubMover02s[i]->drawMover(); mSubMover02s[i]->drawRandomPoint(mRight, mUp); } } gl::popMatrices(); } gl::popMatrices(); rotateY -= 0.6; translateZ -= 1.2; // writeImage( getHomeDirectory() / "CinderScreengrabs" / ( "StrangeAttractor_" + toString( mCurrentFrame ) + ".png" ), copyWindowSurface() ); // mCurrentFrame++; } CINDER_APP_NATIVE( StrangeAttractorApp, RendererGl )
915bde29c757fc5fc64fdb23b210d2f3bc77e7a9
9e3a2a980c4c0f50dab735a2f17488b9e3e5d245
/MSCL/source/mscl/MicroStrain/Wireless/WirelessParser.cpp
47354a54948cb1cd97ff350850257ccb6227e90c
[ "OpenSSL", "MIT", "BSL-1.0" ]
permissive
LORD-MicroStrain/MSCL
6c11a0c50889fae852bf04cdce9b4fe7230cecf1
aef74d5a85c2573cee224f53dad1e22c32d4a128
refs/heads/master
2023-08-31T06:51:24.246179
2023-08-23T00:03:50
2023-08-23T00:03:50
41,445,502
73
61
MIT
2023-07-04T00:07:55
2015-08-26T19:27:43
C++
UTF-8
C++
false
false
36,744
cpp
WirelessParser.cpp
/***************************************************************************************** ** Copyright(c) 2015-2022 Parker Hannifin Corp. All rights reserved. ** ** ** ** MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License. ** *****************************************************************************************/ #include "stdafx.h" #include "WirelessParser.h" #include "Packets/AsyncDigitalAnalogPacket.h" #include "Packets/AsyncDigitalPacket.h" #include "Packets/BufferedLdcPacket.h" #include "Packets/BufferedLdcPacket_v2.h" #include "Packets/DiagnosticPacket.h" #include "Packets/HclSmartBearing_RawPacket.h" #include "Packets/HclSmartBearing_CalPacket.h" #include "Packets/LdcPacket.h" #include "Packets/LdcMathPacket.h" #include "Packets/LdcMathPacket_aspp3.h" #include "Packets/LdcPacket_v2.h" #include "Packets/LdcPacket_v2_aspp3.h" #include "Packets/RawAngleStrainPacket.h" #include "Packets/RollerPacket.h" #include "Packets/SyncSamplingPacket.h" #include "Packets/SyncSamplingPacket_v2.h" #include "Packets/SyncSamplingPacket_v2_aspp3.h" #include "Packets/SyncSamplingMathPacket.h" #include "Packets/SyncSamplingMathPacket_aspp3.h" #include "Packets/WirelessPacket.h" #include "Packets/WirelessPacketCollector.h" #include "Packets/WirelessPacketUtils.h" #include "mscl/MicroStrain/ResponseCollector.h" #include "mscl/MicroStrain/ChecksumBuilder.h" namespace mscl { WirelessParser::WirelessParser(WirelessPacketCollector& packetCollector, std::weak_ptr<ResponseCollector> responseCollector, RawBytePacketCollector& rawBytePacketCollector): m_packetCollector(packetCollector), m_responseCollector(responseCollector), m_rawBytePacketCollector(rawBytePacketCollector) {} bool WirelessParser::processPacket(const WirelessPacket& packet, std::size_t lastReadPos) { //if this is a data packet if(WirelessPacket::isDataPacket(packet.type())) { //store the data packet with the packet collector m_packetCollector.addDataPacket(packet); return true; } else if(packet.isDiscoveryPacket()) { //store the node discovery packet with the packet collector m_packetCollector.addNodeDiscoveryPacket(packet); return true; } //if this is not a data packet else { //this could be a valid ASPP command response return findMatchingResponse(packet, lastReadPos); } } bool WirelessParser::findMatchingResponse(DataBuffer& data) { //attempt to get the pointer from the weak_ptr std::shared_ptr<ResponseCollector> collector(m_responseCollector.lock()); //if we got the shared_ptr if(collector) { //if the response collector is waiting for any responses if(collector->waitingForResponse()) { //if the bytes match an expected response in the response collector if(collector->matchExpected(data)) { return true; } } } //we didn't match any expected responses return false; } bool WirelessParser::findMatchingResponse(const WirelessPacket& packet, std::size_t lastReadPos) { //attempt to get the pointer from the weak_ptr std::shared_ptr<ResponseCollector> collector(m_responseCollector.lock()); //if we got the shared_ptr if(collector) { //if the response collector is waiting for any responses if(collector->waitingForResponse()) { //if the bytes match an expected response in the response collector if(collector->matchExpected(packet, lastReadPos)) { return true; } } } //we didn't match any expected responses return false; } void WirelessParser::parse(DataBuffer& data, WirelessTypes::Frequency freq) { mscl::Bytes rawBytes; RawBytePacket rawBytePacket; ParsePacketResult parseResult; //holds the result of verifying whether it was a valid ASPP packet or not WirelessPacket packet; size_t bytesRemaining; //holds how many bytes we have remaining, helps determine if the buffer has been moved by an external function //make a save point so we can revert if need be ReadBufferSavePoint savepoint(&data); std::size_t lastReadPosition; //while there is more data to be read in the DataBuffer while(data.moreToRead()) { lastReadPosition = data.readPosition(); //read the next byte (doesn't move data's read position) uint8 currentByte = data.peekByte(); //skipByte is set to false when we don't want to skip to the next byte after we are done looking at the current byte bool moveToNextByte = true; //notEnoughData is true when the bytes could be a valid packet, but there isn't enough bytes to be sure bool notEnoughData = false; //if this is any ASPP Start of Packet byte if(currentByte == WirelessPacket::ASPP_V1_SOP || currentByte == WirelessPacket::ASPP_V2_SOP || currentByte == WirelessPacket::ASPP_V3_SOP) { //check if the packet is a valid ASPP packet, starting at this byte parseResult = parseAsPacket(data, packet, freq); size_t position = data.readPosition(); uint8 nextByte; //check the result of the parseAsPacket command switch(parseResult) { //good packet, process it and then look for the next case parsePacketResult_completePacket: if (rawBytes.size() > 0) { addRawBytePacket(rawBytes, false, false, WirelessPacket::PacketType::packetType_NotFound); } position = data.readPosition(); savepoint.revert(); //Read out the "in packet" bytes into the rawBytes buffer... nextByte = data.peekByte(); while (data.readPosition() < position) { rawBytes.push_back(data.read_uint8()); } //savepoint.revert(); //Push the "in packet" raw bytes into the debugPacket buffer as a ConnectionDebugData processPacket(packet, lastReadPosition); addRawBytePacket(rawBytes, true, true, packet.type()); savepoint.commit(); continue; //packet has been processed, move to the next byte after the packet case parsePacketResult_duplicate: savepoint.commit(); continue; //packet is a duplicate, but byte position has been moved. Move to the next byte after the packet //somethings incorrect in the packet, move passed the AA and start looking for the next packet case parsePacketResult_invalidPacket: case parsePacketResult_badChecksum: if (rawBytes.size() > 0) { addRawBytePacket(rawBytes, false, true, WirelessPacket::PacketType::packetType_NotFound); } savepoint.commit(); break; //ran out of data, return and wait for more case parsePacketResult_notEnoughData: moveToNextByte = false; notEnoughData = true; break; default: assert(false); //unhandled verifyResult, need to add a case for it } } //data is not a packet at this point bytesRemaining = data.bytesRemaining(); //check if the bytes we currently have match an expected response // This isn't perfect (could possibly use part of a partial ASPP packet as a cmd response), // but unfortunately its the best we can do with single byte responses being part of our protocol if(findMatchingResponse(data)) { //the bytes have already moved, don't move to the next byte in the next iteration savepoint.commit(); moveToNextByte = false; } else { //failed to match //if we didn't have enough data for a full packet, and it didn't match any expected responses if(notEnoughData) { //look for packets after the current byte. // Even though this looks like it could be the start of an ASPP packet, // if we find any full ASPP packets inside of the these bytes, we need // to pick them up and move on. WirelessPacket::PacketType type = findPacketInBytes(data, freq); if (type == WirelessPacket::PacketType::packetType_NotFound) { //if the read position in the bytes has been moved external to this function if(data.bytesRemaining() != bytesRemaining) { //read position has moved somewhere else, so bytes have been committed. Commit in our local savepoint as well. savepoint.commit(); } //we didn't find a packet within this, so return from this function as we need to wait for more data return; } else { size_t position = data.readPosition(); if (rawBytes.size() > 0) { addRawBytePacket(rawBytes, false, false, WirelessPacket::PacketType::packetType_NotFound); } position = data.readPosition(); savepoint.revert(); //Read out the "in packet" bytes into the debugPacket buffer... while (data.readPosition() < position) { rawBytes.push_back(data.read_uint8()); } savepoint.commit(); addRawBytePacket(rawBytes, true, true, type); } } } //if we need to move to the next byte if (moveToNextByte) { //if the read position in the bytes has been moved external to this function if(data.bytesRemaining() != bytesRemaining) { //read position has moved somewhere else, so bytes have been committed. Commit in our local savepoint as well. savepoint.commit(); } else { //move to the next byte rawBytes.push_back(data.read_uint8()); } } } } WirelessPacket::PacketType WirelessParser::findPacketInBytes(DataBuffer& data, WirelessTypes::Frequency freq) { //create a read save point for the DataBuffer ReadBufferSavePoint savePoint(&data); std::size_t lastReadPosition; //while there are enough bytes remaining to make an ASPP response packet while(data.bytesRemaining() > WirelessPacket::ASPP_MIN_RESPONSE_PACKET_SIZE) { //move to the next byte data.read_uint8(); lastReadPosition = data.readPosition(); ReadBufferSavePoint packetParseSavePoint(&data); WirelessPacket packet; //if we found a packet within the bytes if(parseAsPacket(data, packet, freq) == parsePacketResult_completePacket) { if(processPacket(packet, lastReadPosition)) { //was a data packet, or a response packet we were expecting packetParseSavePoint.commit(); savePoint.commit(); return packet.type(); } else { //found what looks like a packet within the bytes, but wasn't a data packet, nor a response packet we were expecting //revert back to before we parsed this packet that we aren't interested in packetParseSavePoint.revert(); } } } //we didn't find any packet in the bytes buffer return WirelessPacket::PacketType::packetType_NotFound; } WirelessParser::ParsePacketResult WirelessParser::parseAsPacket_ASPP_v1(DataBuffer& data, WirelessPacket& packet, WirelessTypes::Frequency freq) { //Assume we are at the start of the packet, read the packet header //byte 1 - Start Of Packet //byte 2 - Delivery Stop Flag //byte 3 - App Data Type //byte 4 - 5 - Node Address (uint16) //byte 6 - Payload Length //byte 7 to N-4 - Payload //byte N-3 - Node RSSI //byte N-2 - Base RSSI //byte N-1 - Simple Checksum (MSB) //byte N - Simple Checksum (LSB) //create a save point for the DataBuffer ReadBufferSavePoint savePoint(&data); std::size_t totalBytesAvailable = data.bytesRemaining(); //we need at least 10 bytes for any ASPP v1 packet if(totalBytesAvailable < 10) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //read byte 1 uint8 startOfPacket = data.read_uint8(); //Start Of Packet //verify that the first byte is the Start Of Packet if(startOfPacket != WirelessPacket::ASPP_V1_SOP) { //Invalid Packet return parsePacketResult_invalidPacket; } //read byte 2 uint8 deliveryStopFlag = data.read_uint8(); //Delivery Stop Flag //read byte 3 uint8 appDataType = data.read_uint8(); //App Data Type //read bytes 4 and 5 uint16 nodeAddress = data.read_uint16(); //Node Address //read byte 6 uint8 payloadLength = data.read_uint8(); //Payload Length (max of 255) //determine the full packet length uint32 packetLength = payloadLength + WirelessPacket::ASPP_V1_NUM_BYTES_BEFORE_PAYLOAD + WirelessPacket::ASPP_V1_NUM_BYTES_AFTER_PAYLOAD; //the DataBuffer must be large enough to hold the rest of the packet if(totalBytesAvailable < packetLength) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //create the Bytes vector to hold the payload bytes Bytes payload; payload.reserve(payloadLength); //loop through the payload for(uint8 payloadItr = 0; payloadItr < payloadLength; payloadItr++) { //store the payload bytes payload.push_back(data.read_uint8()); //Payload Bytes } //read the node RSSI int16 nodeRSSI = data.read_int8(); //Node RSSI //read the base station rssi int16 baseRSSI = data.read_int8(); //Base RSSI //get the checksum sent in the packet uint16 checksum = data.read_uint16(); //Checksum //build the checksum to calculate from all the bytes ChecksumBuilder calcChecksum; calcChecksum.append_uint8(deliveryStopFlag); calcChecksum.append_uint8(appDataType); calcChecksum.append_uint16(nodeAddress); calcChecksum.append_uint8(payloadLength); calcChecksum.appendBytes(payload); //verify that the returned checksum is the same as the one we calculated if(checksum != calcChecksum.simpleChecksum()) { //Bad Checksum return parsePacketResult_badChecksum; } DeliveryStopFlags flags = DeliveryStopFlags::fromInvertedByte(deliveryStopFlag); //add all the info about the packet to the WirelessPacket reference passed in packet.asppVersion(WirelessPacket::aspp_v1); packet.deliveryStopFlags(flags); packet.type(static_cast<WirelessPacket::PacketType>(appDataType)); packet.nodeAddress(static_cast<uint32>(nodeAddress)); packet.payload(payload); packet.nodeRSSI(nodeRSSI); packet.baseRSSI(baseRSSI); packet.frequency(freq); //Correct the packet type if it is incorrect WirelessPacketUtils::correctPacketType(packet); //make sure the packet is valid based on its specific type if(!WirelessPacketUtils::packetIntegrityCheck(packet)) { //not a valid packet, failed integrity check return parsePacketResult_invalidPacket; } //check if the packet is a duplicate if(isDuplicate(packet)) { //even though it is a duplicate, we still have a complete packet so commit the bytes to skip over them savePoint.commit(); //duplicate packet return parsePacketResult_duplicate; } //we have a complete packet, commit the bytes that we just read (move the read pointer) savePoint.commit(); return parsePacketResult_completePacket; } WirelessParser::ParsePacketResult WirelessParser::parseAsPacket_ASPP_v2(DataBuffer& data, WirelessPacket& packet, WirelessTypes::Frequency freq) { //Assume we are at the start of the packet, read the packet header //byte 1 - Start Of Packet //byte 2 - Delivery Stop Flag //byte 3 - App Data Type //byte 4 - 7 - Node Address (uint32) //byte 8 - 9 - Payload Length //byte 10 to N-4 - Payload //byte N-3 - Node RSSI //byte N-2 - Base RSSI //byte N-1 - Fletcher Checksum (MSB) //byte N - Fletcher Checksum (LSB) //create a save point for the DataBuffer ReadBufferSavePoint savePoint(&data); std::size_t totalBytesAvailable = data.bytesRemaining(); //we need at least 13 bytes for any ASPP v2 packet (if empty payload) if(totalBytesAvailable < 13) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //read byte 1 uint8 startOfPacket = data.read_uint8(); //Start Of Packet //verify that the first byte is the Start Of Packet if(startOfPacket != WirelessPacket::ASPP_V2_SOP) { //Invalid Packet return parsePacketResult_invalidPacket; } //read byte 2 uint8 deliveryStopFlag = data.read_uint8(); //Delivery Stop Flag //read byte 3 uint8 appDataType = data.read_uint8(); //App Data Type //read bytes 4 - 7 uint32 nodeAddress = data.read_uint32(); //Node Address //read bytes 8 and 9 uint16 payloadLength = data.read_uint16(); //Payload Length //determine the full packet length size_t packetLength = payloadLength + WirelessPacket::ASPP_V2_NUM_BYTES_BEFORE_PAYLOAD + WirelessPacket::ASPP_V2_NUM_BYTES_AFTER_PAYLOAD; //the DataBuffer must be large enough to hold the rest of the packet if(totalBytesAvailable < packetLength) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //create the Bytes vector to hold the payload bytes Bytes payload; payload.reserve(payloadLength); //loop through the payload for(uint16 payloadItr = 0; payloadItr < payloadLength; payloadItr++) { //store the payload bytes payload.push_back(data.read_uint8()); //Payload Bytes } //read the node RSSI uint8 nodeRSSI = data.read_uint8(); //Node RSSI //read the base station rssi uint8 baseRSSI = data.read_uint8(); //Base RSSI //get the checksum sent in the packet uint16 checksum = data.read_uint16(); //Checksum //build the checksum to calculate from all the bytes ChecksumBuilder calcChecksum; calcChecksum.append_uint8(startOfPacket); calcChecksum.append_uint8(deliveryStopFlag); calcChecksum.append_uint8(appDataType); calcChecksum.append_uint32(nodeAddress); calcChecksum.append_uint16(payloadLength); calcChecksum.appendBytes(payload); calcChecksum.append_uint8(nodeRSSI); calcChecksum.append_uint8(baseRSSI); //verify that the returned checksum is the same as the one we calculated if(checksum != calcChecksum.fletcherChecksum()) { //Bad Checksum return parsePacketResult_badChecksum; } DeliveryStopFlags flags = DeliveryStopFlags::fromByte(deliveryStopFlag); //add all the info about the packet to the WirelessPacket reference passed in packet.asppVersion(WirelessPacket::aspp_v2); packet.deliveryStopFlags(flags); packet.type(static_cast<WirelessPacket::PacketType>(appDataType)); packet.nodeAddress(nodeAddress); packet.payload(payload); packet.nodeRSSI(static_cast<int16>(nodeRSSI) - 205); packet.baseRSSI(static_cast<int16>(baseRSSI) - 205); packet.frequency(freq); //Correct the packet type if it is incorrect WirelessPacketUtils::correctPacketType(packet); //make sure the packet is valid based on its specific type if(!WirelessPacketUtils::packetIntegrityCheck(packet)) { //not a valid packet, failed integrity check return parsePacketResult_invalidPacket; } //check if the packet is a duplicate if(isDuplicate(packet)) { //even though it is a duplicate, we still have a complete packet so commit the bytes to skip over them savePoint.commit(); //duplicate packet return parsePacketResult_duplicate; } //we have a complete packet, commit the bytes that we just read (move the read pointer) savePoint.commit(); return parsePacketResult_completePacket; } WirelessParser::ParsePacketResult WirelessParser::parseAsPacket_ASPP_v3(DataBuffer& data, WirelessPacket& packet, WirelessTypes::Frequency freq) { //Assume we are at the start of the packet, read the packet header //byte 1 - Start Of Packet //byte 2 - Delivery Stop Flag //byte 3 - App Data Type //byte 4 - 7 - Node Address (uint32) //byte 8 - 9 - Payload Length //byte 10 to N-6 - Payload //byte N-5 - Node RSSI //byte N-4 - Base RSSI //byte N-3 to N - CRC Checksum (uint32) //create a save point for the DataBuffer ReadBufferSavePoint savePoint(&data); std::size_t totalBytesAvailable = data.bytesRemaining(); //we need at least 15 bytes for any ASPP v3 packet (if empty payload) if(totalBytesAvailable < 15) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //read byte 1 uint8 startOfPacket = data.read_uint8(); //Start Of Packet //verify that the first byte is the Start Of Packet if(startOfPacket != WirelessPacket::ASPP_V3_SOP) { //Invalid Packet return parsePacketResult_invalidPacket; } //read byte 2 uint8 deliveryStopFlag = data.read_uint8(); //Delivery Stop Flag //read byte 3 uint8 appDataType = data.read_uint8(); //App Data Type //read bytes 4 - 7 uint32 nodeAddress = data.read_uint32(); //Node Address //read bytes 8 and 9 uint16 payloadLength = data.read_uint16(); //Payload Length //determine the full packet length size_t packetLength = payloadLength + WirelessPacket::ASPP_V3_NUM_BYTES_BEFORE_PAYLOAD + WirelessPacket::ASPP_V3_NUM_BYTES_AFTER_PAYLOAD; //the DataBuffer must be large enough to hold the rest of the packet if(totalBytesAvailable < packetLength) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //create the Bytes vector to hold the payload bytes Bytes payload; payload.reserve(payloadLength); //loop through the payload for(uint16 payloadItr = 0; payloadItr < payloadLength; payloadItr++) { //store the payload bytes payload.push_back(data.read_uint8()); //Payload Bytes } //read the node RSSI uint8 nodeRSSI = data.read_uint8(); //Node RSSI //read the base station rssi uint8 baseRSSI = data.read_uint8(); //Base RSSI //get the checksum sent in the packet uint32 checksum = data.read_uint32(); //Checksum //build the checksum to calculate from all the bytes ChecksumBuilder calcChecksum; calcChecksum.append_uint8(startOfPacket); calcChecksum.append_uint8(deliveryStopFlag); calcChecksum.append_uint8(appDataType); calcChecksum.append_uint32(nodeAddress); calcChecksum.append_uint16(payloadLength); calcChecksum.appendBytes(payload); calcChecksum.append_uint8(nodeRSSI); calcChecksum.append_uint8(baseRSSI); //verify that the returned checksum is the same as the one we calculated if(checksum != calcChecksum.crcChecksum()) { //Bad Checksum return parsePacketResult_badChecksum; } DeliveryStopFlags flags = DeliveryStopFlags::fromByte(deliveryStopFlag); //add all the info about the packet to the WirelessPacket reference passed in packet.asppVersion(WirelessPacket::aspp_v3); packet.deliveryStopFlags(flags); packet.type(static_cast<WirelessPacket::PacketType>(appDataType)); packet.nodeAddress(nodeAddress); packet.payload(payload); packet.nodeRSSI(static_cast<int16>(nodeRSSI) - 205); packet.baseRSSI(static_cast<int16>(baseRSSI) - 205); packet.frequency(freq); //Correct the packet type if it is incorrect //WirelessPacketUtils::correctPacketType(packet); //make sure the packet is valid based on its specific type if(!WirelessPacketUtils::packetIntegrityCheck(packet)) { //not a valid packet, failed integrity check return parsePacketResult_invalidPacket; } //check if the packet is a duplicate if(isDuplicate(packet)) { //even though it is a duplicate, we still have a complete packet so commit the bytes to skip over them savePoint.commit(); //duplicate packet return parsePacketResult_duplicate; } //we have a complete packet, commit the bytes that we just read (move the read pointer) savePoint.commit(); return parsePacketResult_completePacket; } WirelessParser::ParsePacketResult WirelessParser::parseAsPacket(DataBuffer& data, WirelessPacket& packet, WirelessTypes::Frequency freq) { if(data.bytesRemaining() == 0) { //Not Enough Data to tell if valid packet return parsePacketResult_notEnoughData; } //choose the correct ASPP version parser switch(data.peekByte()) { case WirelessPacket::ASPP_V1_SOP: return parseAsPacket_ASPP_v1(data, packet, freq); case WirelessPacket::ASPP_V2_SOP: return parseAsPacket_ASPP_v2(data, packet, freq); case WirelessPacket::ASPP_V3_SOP: return parseAsPacket_ASPP_v3(data, packet, freq); default: return parsePacketResult_invalidPacket; } } bool WirelessParser::isDuplicate(const WirelessPacket& packet) { //packets that we don't check for duplicates for switch(packet.type()) { //isn't a valid data packet that has a unique id, so we can't check for duplicates case WirelessPacket::packetType_nodeCommand: case WirelessPacket::packetType_nodeErrorReply: case WirelessPacket::packetType_nodeDiscovery: case WirelessPacket::packetType_TCLinkLDC: case WirelessPacket::packetType_beaconEcho: case WirelessPacket::packetType_nodeDiscovery_v2: case WirelessPacket::packetType_nodeDiscovery_v3: case WirelessPacket::packetType_nodeDiscovery_v4: case WirelessPacket::packetType_nodeDiscovery_v5: case WirelessPacket::packetType_nodeReceived: case WirelessPacket::packetType_nodeSuccessReply: case WirelessPacket::packetType_baseCommand: case WirelessPacket::packetType_baseReceived: case WirelessPacket::packetType_baseSuccessReply: case WirelessPacket::packetType_baseErrorReply: case WirelessPacket::packetType_rfScanSweep: case WirelessPacket::packetType_SHM: return false; default: break; } uint16 uniqueId; if(packet.asppVersion() == WirelessPacket::aspp_v3) { //ASPP v3 Packets //check the packet type switch(packet.type()) { case WirelessPacket::packetType_LDC_16ch: uniqueId = LdcPacket_v2_aspp3::getUniqueId(packet); break; case WirelessPacket::packetType_LDC_math: uniqueId = LdcMathPacket_aspp3::getUniqueId(packet); break; case WirelessPacket::packetType_SyncSampling_16ch: uniqueId = SyncSamplingPacket_v2_aspp3::getUniqueId(packet); break; case WirelessPacket::packetType_SyncSampling_math: uniqueId = SyncSamplingMathPacket_aspp3::getUniqueId(packet); break; case WirelessPacket::packetType_rawAngleStrain: uniqueId = RawAngleStrainPacket::getUniqueId(packet); break; //same payload, no new parser case WirelessPacket::packetType_diagnostic: uniqueId = DiagnosticPacket::getUniqueId(packet); break; //same payload, no new parser default: assert(false); //unhandled packet type, need to add a case for it return false; } } else { //ASPP v1 and v2 Packets //check the packet type switch(packet.type()) { //get the unique id depending on the type of packet case WirelessPacket::packetType_LDC: uniqueId = LdcPacket::getUniqueId(packet); break; case WirelessPacket::packetType_SyncSampling: uniqueId = SyncSamplingPacket::getUniqueId(packet); break; case WirelessPacket::packetType_BufferedLDC: uniqueId = BufferedLdcPacket::getUniqueId(packet); break; case WirelessPacket::packetType_AsyncDigital: uniqueId = AsyncDigitalPacket::getUniqueId(packet); break; case WirelessPacket::packetType_AsyncDigitalAnalog: uniqueId = AsyncDigitalAnalogPacket::getUniqueId(packet); break; case WirelessPacket::packetType_diagnostic: uniqueId = DiagnosticPacket::getUniqueId(packet); break; case WirelessPacket::packetType_LDC_16ch: uniqueId = LdcPacket_v2::getUniqueId(packet); break; case WirelessPacket::packetType_LDC_math: uniqueId = LdcMathPacket::getUniqueId(packet); break; case WirelessPacket::packetType_SyncSampling_16ch: uniqueId = SyncSamplingPacket_v2::getUniqueId(packet); break; case WirelessPacket::packetType_SyncSampling_math: uniqueId = SyncSamplingMathPacket::getUniqueId(packet); break; case WirelessPacket::packetType_BufferedLDC_16ch: uniqueId = BufferedLdcPacket_v2::getUniqueId(packet); break; case WirelessPacket::packetType_HclSmartBearing_Calibrated: uniqueId = HclSmartBearing_CalPacket::getUniqueId(packet); break; case WirelessPacket::packetType_HclSmartBearing_Raw: uniqueId = HclSmartBearing_RawPacket::getUniqueId(packet); break; case WirelessPacket::packetType_rawAngleStrain: uniqueId = RawAngleStrainPacket::getUniqueId(packet); break; case WirelessPacket::packetType_roller: uniqueId = RollerPacket::getUniqueId(packet); break; default: assert(false); //unhandled packet type, need to add a case for it return false; } } DuplicateCheckKey key(packet.nodeAddress(), packet.type()); //if we found the packet's node address in the lastPacketMap if(m_lastPacketMap.find(key) != m_lastPacketMap.end()) { //if the unique id in the lastPacketMap matches the uniqueId from this packet if(m_lastPacketMap[key] == uniqueId) { //it is a duplicate packet return true; } } //update or set m_lastPacketMap's uniqueId for this node m_lastPacketMap[key] = uniqueId; //it is not a duplicate packet return false; } void WirelessParser::addRawBytePacket(Bytes& rawBytePacket, bool valid = true, bool packetFound = true, WirelessPacket::PacketType wirelessType = WirelessPacket::PacketType::packetType_NotFound) { RawBytePacket packet; packet.payload(rawBytePacket); if (valid) { packet.type(WirelessPacket::isDataPacket(wirelessType) ? RawBytePacket::DATA_PACKET : RawBytePacket::COMMAND_PACKET); } else { packet.type(packetFound ? RawBytePacket::INVALID_PACKET : RawBytePacket::NO_PACKET_FOUND); } m_rawBytePacketCollector.addRawBytePacket(packet); rawBytePacket.clear(); } const bool operator < (const WirelessParser::DuplicateCheckKey& key1, const WirelessParser::DuplicateCheckKey& key2) { if(key1.nodeAddress < key2.nodeAddress) { return true; } if(key1.nodeAddress > key2.nodeAddress) { return false; } if(key1.packetType < key2.packetType) { return true; } return false; } }
8f64ca8a600c3d3db64286cdd48de6aabe6b9610
feccd0f7d92cece361cc2342132d93f240520cc0
/cpp/5.lab_5/Q5.cpp
54001dda10126f82ea8acd8a81195a552af5156e
[]
no_license
REGATTE/SEM_6
e4756dcecd1f8c8d53b0f48588e03381728b464c
2a678eb6b6048de2789b19c70b06658097cf159b
refs/heads/master
2023-03-31T23:43:59.675405
2021-04-08T19:22:30
2021-04-08T19:22:30
329,066,941
2
1
null
null
null
null
UTF-8
C++
false
false
995
cpp
Q5.cpp
/* J ashok kumar E18CSE029 EB03 */ #include<iostream> #include<string> using namespace std; void print1DArray(int *, int); int *sortArr(int *, int); int main() { int n; cout<<"Enter the number of elements: "; cin>>n; int arr[n]; for(int i=0; i<n; i++) { cin>>arr[i]; } cout<<"\nOriginal Array: "; print1DArray((int *)arr, n); int *finalArr = sortArr((int *)arr, n); cout<<"\nSorted Array: "; print1DArray(finalArr, n); return 0; } void print1DArray(int *arr, int n) { for(int i=0; i<n; i++) { cout<<arr[i]<<" "; } cout<<"\n"; } int *sortArr(int *arr, int n) { int temp; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(arr[j]>arr[i]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; }
edff0c5696b53835016f1e2c9721ae1b98dba9a4
96c763148f58d3810689f673e5a7e3241e2089fb
/STL container graph(хуевая не работающая версия)/main.cpp
9f4a4a0a96833a63c539b4690bdab1595c083a32
[]
no_license
IvanYakimtsov/Sem2
500c3c3bf5287ab8ba5a7b469416314e87e8a0f8
ad421de52a2274921915afd848db92dce4eff7a3
refs/heads/master
2020-12-31T06:09:09.061900
2017-02-25T17:02:24
2017-02-25T17:02:24
59,771,554
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
9,714
cpp
main.cpp
#include <iostream> #include <map> #include<vector> using namespace std; template <typename T> class Graph { private: struct Vertex { T value; vector <T> vert_list; }; vector <Vertex> graph; Vertex return_vertex(int i) { return graph[i]; } int get_number(T v) { for(int i=0; i<graph.size(); i++) { if(graph[i].value==v) return i; } return -1; } public: Graph() { } Graph(const Graph<T> &obj) { graph=obj.graph; } void add_vertex(T vert) { bool check=true; for(int i=0; i<graph.size(); i++) { if(vert == graph[i].value) check=false; } if(check) { vector<int> tmp; tmp.clear(); Vertex temp; temp.value = vert; temp.vert_list = tmp; graph.push_back(temp); } } bool add_arc(T v1,T v2) { if(!contain(v1)) return false; if(!contain(v2)) return false; int n1,n2; n1=get_number(v1); n2=get_number(v2); graph[n1].vert_list.push_back(v2); graph[n2].vert_list.push_back(v1); return true; } int size() { return graph.size(); } int vert_pow(T v) { int index=get_number(v); return graph[index].vert_list.size(); } bool is_empty() { if(graph.size()) return true; else return false; } T at(int tmp) { return graph[tmp].value; } void change_elem(T v1,T v2) { int n1; n1=get_number(v1); graph[n1].value=v2; } bool contain(T temp) { for(int i=0; i<graph.size(); i++) { if(temp == graph[i].value) return true; } return false; } bool check_connection(T v1,T v2) { if(!contain(v1)) return false; if(!contain(v2)) return false; int n1,n2; n1=get_number(v1); n2=get_number(v2); for(int i=0; i<graph[n1].vert_list.size(); i++) { if(v2 == graph[n1].vert_list[i]) return true; } return false; } void del_node(T vdel) { int del; if(contain(vdel)) { del=get_number(vdel); for(int i=0; i<graph.size(); i++) for(int j=0; j<graph[i].vert_list.size(); j++) { if(graph[i].vert_list[j]==vdel) graph[i].vert_list.erase(graph[i].vert_list.begin()+j); } graph.erase(graph.begin()+del); } } void clear_graph() { graph.clear(); } void del_arc(T v1, T v2) { if(contain(v1) && contain(v2) && check_connection(v1,v2)) { int vert1,vert2; vert1=get_number(v1); vert2=get_number(v2); for(int i=0; i<graph[vert1].vert_list.size(); i++) { if(graph[vert1].vert_list[i]==v2) graph[vert1].vert_list.erase(graph[vert1].vert_list.begin()+i); } for(int i=0; i<graph[vert2].vert_list.size(); i++) { if(graph[vert2].vert_list[i]==v1) graph[vert2].vert_list.erase(graph[vert2].vert_list.begin()+i); } } } /* void show_graph() { cout<<"graph: "<<endl; for(int i=0;i<graph.size();i++) { for(int j=0;j<graph[i].vert_list.size();j++) { cout<<graph[i].vert_list[j]<<" "; } cout<<endl; } cout<<"//----------------------------------------- "<<endl; }*/ public: class Node_Iterator { private: Graph<T> *gr; int index; public: Node_Iterator( Graph<T> &graph) { gr = &graph; index = 0; } bool next() { if (gr->graph.size() <= index+1)return false; index++; return true; } T get() { return gr->graph[index].value; } bool delNode() { gr->del_node(get()); } bool prev() { if (index==0) return false; index--; return true; } }; class Node_Adjacent_Iterator { private: Graph<T> *gr; int index; int number=0; T priv_vert; T val; T node_val; public: Node_Adjacent_Iterator( Graph<T> &graph, T v) { gr = &graph; node_val=v; } Node_Adjacent_Iterator( Graph<T> &graph) { gr = &graph; index = 0; if(gr->graph[index].vert_list.size()) { val=gr->graph[index].vert_list[0]; } if(!gr->graph[index].vert_list.size()) { val=gr->graph[index].value; } node_val=gr->graph[index].value; } T next_elem() { if(gr->graph[index].vert_list.size()) { number++; if(number>=gr->graph[index].vert_list.size()) number=0; val=gr->graph[index].vert_list[number]; return val; } return gr->graph[index].value; } bool next() { for(int i=0; i<gr->graph.size(); i++) { if(gr->graph[i].value==node_val) index = i; } if(gr->graph[index].vert_list.size() && gr->contain(val)) { priv_vert=get(); for(int i=0; i<gr->graph.size(); i++) { if(gr->graph[i].value==val) index = i; } node_val=gr->graph[index].value; return true; } return false; } T get() { for(int i=0; i<gr->graph.size(); i++) { if(gr->graph[i].value==node_val) index = i; } return gr->graph[index].value; } bool delNode() { gr->del_node(get()); node_val=priv_vert; } }; ~Graph() { } Graph& operator = (const Graph<T> &obj) { graph=obj.graph; return *this; } }; ///TODO: Show Graph int main() { setlocale(LC_ALL,"rus"); Graph<int> gr; gr.add_vertex(111); gr.add_vertex(222); gr.add_vertex(333); gr.add_vertex(444); gr.add_arc(111,222); gr.add_arc(111,333); gr.add_arc(333,444); ///-------------------------------------------------------------------------------- cout<<"конструктор копирования и оператор присваивания тест"<<endl; cout<<gr.at(1)<<endl; ///конструктор копирования и оператор присваивания тест cout<<gr.at(0)<<endl; cout<<gr.check_connection(111,222)<<endl; cout<<gr.check_connection(111,444)<<endl; cout<<gr.size()<<endl<<endl; Graph<int> gr1; gr1 = gr; cout<<gr1.at(1)<<endl; cout<<gr1.at(0)<<endl; cout<<gr1.check_connection(111,222)<<endl; cout<<gr1.check_connection(111,444)<<endl; cout<<gr1.size()<<endl<<endl; Graph<int> gr2(gr1); cout<<gr2.at(1)<<endl; cout<<gr2.at(0)<<endl; cout<<gr2.check_connection(111,222)<<endl; cout<<gr2.check_connection(111,444)<<endl; cout<<gr2.size()<<endl<<endl; ///-------------------------------------------------------------------------------- cout<<"///--------------------------------------------------------------------------------" <<endl; cout<<"тест удаления"<<endl; cout<<gr.contain(222)<<endl; cout<<gr.check_connection(111,222)<<endl; cout<<gr.check_connection(222,111)<<endl; cout<<gr.check_connection(333,444)<<endl; gr.del_node(222); ///тест удаления cout<<endl; cout<<gr.contain(222)<<endl; cout<<gr.check_connection(111,222)<<endl; cout<<gr.check_connection(222,111)<<endl; cout<<gr.check_connection(333,444)<<endl; cout<<endl; gr.del_arc(333,444); cout<<gr.check_connection(333,444)<<endl; cout<<endl; gr.clear_graph(); cout<<"size "<<gr.size()<<endl; cout<<endl; cout<<"///--------------------------------------------------------------------------------" <<endl; cout<<"тест итератора по вершинам"<<endl; Graph<int>::Node_Iterator it(gr1); ///тест итератора по вершинам it.next(); it.next(); cout<<it.get()<<endl; it.delNode(); cout<<it.get()<<endl; it.prev(); cout<<it.get()<<endl; cout<<"///--------------------------------------------------------------------------------" <<endl; cout<<"тест итератора по смежным вершинам"<<endl; Graph<int>::Node_Adjacent_Iterator it1(gr2,111); cout<<it1.get()<<endl; cout<<"test next elem"<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; cout<<"test next"<<endl; it1.next(); cout<<it1.get()<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; it1.next(); cout<<it1.next_elem()<<endl; it1.next(); cout<<it1.get()<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; cout<<"delete test"<<endl; cout<<it1.get()<<endl; it1.delNode(); cout<<it1.get()<<endl; cout<<it1.next_elem()<<endl; cout<<it1.next_elem()<<endl; return 0; }
cbcd50baa906e4b5ae5a674a8fd345179af31d10
d9e96244515264268d6078650fa707f34d94ee7a
/Utility/ArithmeticUtils.h
5160744c794b0af50fe4cece5b11618daec2fb5b
[ "MIT" ]
permissive
xlgames-inc/XLE
45c89537c10561e216367a2e3bcd7d1c92b1b039
69cc4f2aa4faf12ed15bb4291c6992c83597899c
refs/heads/master
2022-06-29T17:16:11.491925
2022-05-04T00:29:28
2022-05-04T00:29:28
29,281,799
396
102
null
2016-01-04T13:35:59
2015-01-15T05:07:55
C++
UTF-8
C++
false
false
16,531
h
ArithmeticUtils.h
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #pragma once #include "../Core/Prefix.h" #include "../Core/Types.h" #include "Detail/API.h" #include <vector> #include <assert.h> namespace Utility { // clz := count leading zeros // ctl := count trailing zeros // bsf := bit scan forward // bsr := bit scan reverse // [caveats] in intel architecture, bsr & bsf are coressponds to // machine instruction. so the following implementations are inefficient! uint32 xl_clz1(uint8 x); uint32 xl_ctz1(uint8 x); uint32 xl_clz2(uint16 x); uint32 xl_ctz2(uint16 x); uint32 xl_ctz4(const uint32& x); uint32 xl_clz4(const uint32& x); uint32 xl_ctz8(const uint64& x); uint32 xl_clz8(const uint64& x); uint32 xl_bsr1(const uint16& x); uint32 xl_bsr2(const uint16& x); uint32 xl_bsr4(const uint32& x); uint32 xl_bsr8(const uint64& x); uint32 xl_lg(const size_t& x); XL_UTILITY_API void printbits(const void* blob, int len); XL_UTILITY_API void printhex32(const void* blob, int len); XL_UTILITY_API void printbytes(const void* blob, int len); XL_UTILITY_API void printbytes2(const void* blob, int len); uint32 popcount(uint32 v); uint32 parity(uint32 v); int countbits(uint32 v); int countbits(std::vector<uint32>& v); int countbits(const void* blob, int len); void invert(std::vector<uint32>& v); uint32 getbit(const void* block, int len, uint32 bit); uint32 getbit_wrap(const void* block, int len, uint32 bit); template < typename T > inline uint32 getbit(T& blob, uint32 bit); void xl_setbit(void* block, int len, uint32 bit); void xl_setbit(void* block, int len, uint32 bit, uint32 val); template < typename T > inline void xl_setbit(T& blob, uint32 bit); void xl_clearbit(void* block, int len, uint32 bit); void flipbit(void* block, int len, uint32 bit); template < typename T > inline void flipbit(T& blob, uint32 bit); //----------------------------------------------------------------------------- // Left and right shift of blobs. The shift(N) versions work on chunks of N // bits at a time (faster) XL_UTILITY_API void lshift1(void* blob, int len, int c); XL_UTILITY_API void lshift8(void* blob, int len, int c); XL_UTILITY_API void lshift32(void* blob, int len, int c); void lshift(void* blob, int len, int c); template < typename T > inline void lshift(T& blob, int c); XL_UTILITY_API void rshift1(void* blob, int len, int c); XL_UTILITY_API void rshift8(void* blob, int len, int c); XL_UTILITY_API void rshift32(void* blob, int len, int c); void rshift(void* blob, int len, int c); template < typename T > inline void rshift(T& blob, int c); //----------------------------------------------------------------------------- // Left and right rotate of blobs. The rot(N) versions work on chunks of N // bits at a time (faster) XL_UTILITY_API void lrot1(void* blob, int len, int c); XL_UTILITY_API void lrot8(void* blob, int len, int c); XL_UTILITY_API void lrot32(void* blob, int len, int c); void lrot(void* blob, int len, int c); template < typename T > inline void lrot(T& blob, int c); XL_UTILITY_API void rrot1(void* blob, int len, int c); XL_UTILITY_API void rrot8(void* blob, int len, int c); XL_UTILITY_API void rrot32(void* blob, int len, int c); void rrot(void* blob, int len, int c); template < typename T > inline void rrot(T& blob, int c); //----------------------------------------------------------------------------- // Bit-windowing functions - select some N-bit subset of the input blob XL_UTILITY_API uint32 window1(void* blob, int len, int start, int count); XL_UTILITY_API uint32 window8(void* blob, int len, int start, int count); XL_UTILITY_API uint32 window32(void* blob, int len, int start, int count); uint32 window(void* blob, int len, int start, int count); template < typename T > inline uint32 window(T& blob, int start, int count); // bit-scan #if COMPILER_ACTIVE == COMPILER_TYPE_MSVC #pragma intrinsic(_BitScanForward, _BitScanReverse) inline uint32 xl_ctz4(const uint32& x) { unsigned long i = 0; if (!_BitScanForward(&i, (unsigned long)x)) { return 32; } return (uint32)i; } inline uint32 xl_clz4(const uint32& x) { unsigned long i = 0; if (!_BitScanReverse(&i, (unsigned long)x)) { return 32; } return (uint32)(31 - i); } #if SIZEOF_PTR == 8 #pragma intrinsic(_BitScanForward64, _BitScanReverse64) inline uint32 xl_ctz8(const uint64& x) { unsigned long i = 0; if (!_BitScanForward64(&i, x)) { return 64; } return (uint32)i; } inline uint32 xl_clz8(const uint64& x) { unsigned long i = 0; if (!_BitScanReverse64(&i, x)) { return 64; } return (uint32)(63 - i); } #else namespace Internal { union Int64U { struct Comp { uint32 LowPart; uint32 HighPart; } comp; uint64 QuadPart; }; } inline uint32 xl_ctz8(const uint64& x) { Internal::Int64U li; li.QuadPart = (uint64)x; uint32 i = xl_ctz4((uint32)li.comp.LowPart); if (i < 32) { return i; } return xl_ctz4((uint32)li.comp.HighPart) + 32; } inline uint32 xl_clz8(const uint64& x) { Internal::Int64U li; li.QuadPart = (uint64)x; uint32 i = xl_clz4((uint32)li.comp.HighPart); if (i < 32) { return i; } return xl_clz4((uint32)li.comp.LowPart) + 32; } #endif #elif COMPILER_ACTIVE == COMPILER_GCC inline uint32 xl_ctz4(const uint32& x) { __builtin_ctz(x); } inline uint32 xl_clz4(const uint32& x) { __builtin_clz(x); } inline uint32 xl_ctz8(const uint64& x) { __builtin_ctzll(x); } inline uint32 xl_clz8(const uint64& x) { __builtin_clzll(x); } #else #error 'Unsupported Compiler!' #endif inline uint32 xl_clz2(uint16 x) { uint32 i = xl_clz4(x); if (i == 32) { return 16; } //assert (i >= 16); return (i - 16); } inline uint32 xl_ctz2(uint16 x) { uint32 i = xl_ctz4(x); if (i == 32) { return 16; } //assert(i < 16); return i; } inline uint32 xl_clz1(uint8 x) { uint32 i = xl_clz4(x); if (i == 32) { return 8; } //assert (i >= 24); return (i - 24); } inline uint32 xl_ctz1(uint8 x) { uint32 i = xl_ctz4(x); if (i == 32) { return 8; } //assert(i < 8); return i; } #define xl_bsf1 xl_ctz1 #define xl_bsf2 xl_ctz2 #define xl_bsf4 xl_ctz4 #define xl_bsf8 xl_ctz8 inline uint32 xl_bsr1(const uint16& x) { uint32 i = (uint32)xl_clz2(x); if (i == 8) { return 8; } return 7 - i; } inline uint32 xl_bsr2(const uint16& x) { uint32 i = xl_clz2(x); if (i == 16) { return 16; } return 15 - i; } inline uint32 xl_bsr4(const uint32& x) { uint32 i = xl_clz4(x); if (i == 32) { return 32; } return 31 - i; } inline uint32 xl_bsr8(const uint64& x) { uint32 i = xl_clz8(x); if (i == 64) { return 64; } return 63 - i; } inline uint32 xl_lg(const size_t& x) { #if SIZEOF_PTR == 8 return xl_bsr8(x); #else return xl_bsr4(x); #endif } //----------------------------------------------------------------------------- // Bit-level manipulation // These two are from the "Bit Twiddling Hacks" webpage inline uint32 popcount(uint32 v) { v = v - ((v >> 1) & 0x55555555); // reuse input as temporary v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp uint32 c = ((v + ((v >> 4) & 0xF0F0F0F)) * 0x1010101) >> 24; // count return c; } inline uint32 parity(uint32 v) { v ^= v >> 1; v ^= v >> 2; v = (v & 0x11111111U) * 0x11111111U; return (v >> 28) & 1; } inline uint32 getbit(const void* block, int len, uint32 bit) { uint8* b = (uint8*)block; int byte = bit >> 3; bit = bit & 0x7; if (byte < len) {return (b[byte] >> bit) & 1;} return 0; } inline uint32 getbit_wrap(const void* block, int len, uint32 bit) { uint8* b = (uint8*)block; int byte = bit >> 3; bit = bit & 0x7; byte %= len; return (b[byte] >> bit) & 1; } inline void xl_setbit(void* block, int len, uint32 bit) { unsigned char* b = (unsigned char*)block; int byte = bit >> 3; bit = bit & 0x7; if (byte < len) {b[byte] |= (1 << bit);} } inline void xl_clearbit(void* block, int len, uint32 bit) { uint8* b = (uint8*)block; int byte = bit >> 3; bit = bit & 0x7; if (byte < len) {b[byte] &= ~(1 << bit);} } inline void xl_setbit(void* block, int len, uint32 bit, uint32 val) { val ? xl_setbit(block, len, bit) : xl_clearbit(block, len, bit); } inline void flipbit(void* block, int len, uint32 bit) { uint8* b = (uint8*)block; int byte = bit >> 3; bit = bit & 0x7; if (byte < len) {b[byte] ^= (1 << bit);} } inline int countbits(uint32 v) { v = v - ((v >> 1) & 0x55555555); // reuse input as temporary v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp int c = ((v + ((v >> 4) & 0xF0F0F0F)) * 0x1010101) >> 24; // count return c; } //---------- template < typename T > inline uint32 getbit(T& blob, uint32 bit) { return getbit(&blob, sizeof(blob), bit); } template <> inline uint32 getbit(uint32& blob, uint32 bit) { return (blob >> (bit & 31)) & 1; } template <> inline uint32 getbit(uint64& blob, uint32 bit) { return (blob >> (bit & 63)) & 1; } //---------- template < typename T > inline void xl_setbit(T& blob, uint32 bit) { return xl_setbit(&blob, sizeof(blob), bit); } template <> inline void xl_setbit(uint32& blob, uint32 bit) { blob |= uint32(1) << (bit & 31); } template <> inline void xl_setbit(uint64& blob, uint32 bit) { blob |= uint64(1) << (bit & 63); } //---------- template < typename T > inline void flipbit(T& blob, uint32 bit) { flipbit(&blob, sizeof(blob), bit); } template <> inline void flipbit(uint32& blob, uint32 bit) { bit &= 31; blob ^= (uint32(1) << bit); } template <> inline void flipbit(uint64& blob, uint32 bit) { bit &= 63; blob ^= (uint64(1) << bit); } // shift left and right inline void lshift(void* blob, int len, int c) { if ((len & 3) == 0) { lshift32(blob, len, c); } else { lshift8(blob, len, c); } } inline void rshift(void* blob, int len, int c) { if ((len & 3) == 0) { rshift32(blob, len, c); } else { rshift8(blob, len, c); } } template < typename T > inline void lshift(T& blob, int c) { if ((sizeof(T) & 3) == 0) { lshift32(&blob, sizeof(T), c); } else { lshift8(&blob, sizeof(T), c); } } template < typename T > inline void rshift(T& blob, int c) { if ((sizeof(T) & 3) == 0) { lshift32(&blob, sizeof(T), c); } else { lshift8(&blob, sizeof(T), c); } } template <> inline void lshift(uint32& blob, int c) { blob <<= c; } template <> inline void lshift(uint64& blob, int c) { blob <<= c; } template <> inline void rshift(uint32& blob, int c) { blob >>= c; } template <> inline void rshift(uint64& blob, int c) { blob >>= c; } // Left and right rotate of blobs inline void lrot(void* blob, int len, int c) { if ((len & 3) == 0) { return lrot32(blob, len, c); } else { return lrot8(blob, len, c); } } inline void rrot(void* blob, int len, int c) { if ((len & 3) == 0) { return rrot32(blob, len, c); } else { return rrot8(blob, len, c); } } template < typename T > inline void lrot(T& blob, int c) { if ((sizeof(T) & 3) == 0) { return lrot32(&blob, sizeof(T), c); } else { return lrot8(&blob, sizeof(T), c); } } template < typename T > inline void rrot(T& blob, int c) { if ((sizeof(T) & 3) == 0) { return rrot32(&blob, sizeof(T), c); } else { return rrot8(&blob, sizeof(T), c); } } #if COMPILER_ACTIVE == COMPILER_TYPE_MSVC #define ROTL32(x, y) _rotl(x, y) #define ROTL64(x, y) _rotl64(x, y) #define ROTR32(x, y) _rotr(x, y) #define ROTR64(x, y) _rotr64(x, y) #define BIG_CONSTANT(x) (x) #else inline uint32 rotl32(uint32 x, int8_t r) { return (x << r) | (x >> (32 - r)); } inline uint64 rotl64(uint64 x, int8_t r) { return (x << r) | (x >> (64 - r)); } inline uint32 rotr32(uint32 x, int8_t r) { return (x >> r) | (x << (32 - r)); } inline uint64 rotr64(uint64 x, int8_t r) { return (x >> r) | (x << (64 - r)); } #define ROTL32(x, y) rotl32(x, y) #define ROTL64(x, y) rotl64(x, y) #define ROTR32(x, y) rotr32(x, y) #define ROTR64(x, y) rotr64(x, y) #define BIG_CONSTANT(x) (x ## LLU) #endif template <> inline void lrot(uint32& blob, int c) { blob = ROTL32(blob, c); } template <> inline void lrot(uint64& blob, int c) { blob = ROTL64(blob, c); } template <> inline void rrot(uint32& blob, int c) { blob = ROTR32(blob, c); } template <> inline void rrot(uint64& blob, int c) { blob = ROTR64(blob, c); } //----------------------------------------------------------------------------- // Bit-windowing functions - select some N-bit subset of the input blob inline uint32 window(void* blob, int len, int start, int count) { if (len & 3) { return window8(blob, len, start, count); } else { return window32(blob, len, start, count); } } template < typename T > inline uint32 window(T& blob, int start, int count) { if ((sizeof(T) & 3) == 0) { return window32(&blob, sizeof(T), start, count); } else { return window8(&blob, sizeof(T), start, count); } } template <> inline uint32 window(uint32& blob, int start, int count) { return ROTR32(blob, start) & ((1 << count) - 1); } template <> inline uint32 window(uint64& blob, int start, int count) { return (uint32)ROTR64(blob, start) & ((1 << count) - 1); } } using namespace Utility;
d23598e98fa2c7fc312a065790f53787a505c1b6
601ed8fbe671633b3413ed9107021a2f6e5a1bf7
/src/Driver.hpp
450f9298d633a4bf6593dc365845ac6523a44b89
[]
no_license
OpenLEAD/drivers-ptu_kongsberg_oe10
c73b02b5617dde7aeed3cbeb0a5a76c057ce39a6
ddc76d0f8856420b62527ccf7dcdcd3b856ac719
refs/heads/master
2021-01-19T18:56:31.194602
2015-01-22T14:09:57
2015-01-22T14:09:57
23,894,003
1
1
null
2016-02-24T12:52:27
2014-09-10T21:59:59
C++
UTF-8
C++
false
false
2,075
hpp
Driver.hpp
#ifndef PTU_KONGSBERG_OE10_DRIVER_HPP #define PTU_KONGSBERG_OE10_DRIVER_HPP #include <ptu_kongsberg_oe10/Packet.hpp> #include <iodrivers_base/Driver.hpp> #include <ptu_kongsberg_oe10/Status.hpp> #include <ptu_kongsberg_oe10/PanTiltStatus.hpp> namespace ptu_kongsberg_oe10 { class Driver : public iodrivers_base::Driver { public: Driver(); Status getStatus(int device_id); void requestPanTiltStatus(int device_id); PanTiltStatus readPanTiltStatus(int device_id); PanTiltStatus getPanTiltStatus(int device_id); void useEndStops(int device_id, bool enable); void setPanPositiveEndStop(int device_id); void setPanNegativeEndStop(int device_id); void setTiltPositiveEndStop(int device_id); void setTiltNegativeEndStop(int device_id); void setPanPosition(int device_id, float pan); void setTiltPosition(int device_id, float tilt); void setPanSpeed(int device_id, float speed); void setTiltSpeed(int device_id, float speed); double tiltUp(int device_id); double tiltDown(int device_id); double tiltStop(int device_id); protected: /** Read the response of a command and validates it * * The protocol specifies that the data field of ACKs starts with the * command that is being ACKed. This method removes the prefix (after * having validated it), so the returned packet's data array starts with * the actual data. */ Packet readResponse(Packet const& cmd, int expectedSize); void setPosition(int device_id, char axis, float angle); void setSpeed(int device_id, char cmd0, char cmd1, float speed); double simpleMovement(int device_id, char cmd0, char cmd1); void setEndStop(int device_id, char cmd0, char cmd1); void writePacket(Packet const& packet); Packet readPacket(); std::vector<boost::uint8_t> writeBuffer; int extractPacket(boost::uint8_t const* buffer, size_t size) const; }; } #endif
6d2a4a4ec8add419fe15e0b9d8bb812f5d3d008c
e984aa610affc6e333ca021325088c79f126bcac
/list.cpp
7dd4c0edb98e159be6868bfe6744a3cdf657366d
[]
no_license
gahyeonkim45/goldrone_qt
334346ccb735ecca18f8820aabad6432f40a5c1d
c7fd695fc910e586da703ae8cff4283c9a290452
refs/heads/master
2021-01-21T17:13:34.929511
2017-05-21T07:57:53
2017-05-21T07:57:53
91,941,462
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
list.cpp
#include "list.h" #include "managewindow.h" #include <QJsonArray> #include <QJsonObject> #include <QJsonValue> #include <QVariantMap> #include <QString> #include <QJsonDocument> #include <qDebug> #include <QVariantList> #include <QMap> List::List(QObject *parent) : QObject(parent) { m_win = (ManageWindow *)parent; } void List::AddWid(QString str){ QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8()); // qDebug() << "QJsonDocument" << doc; QVariantMap result; QList<QVariant> temp; if(!doc.isNull()) { if(doc.isObject()) { result = doc.toVariant().toMap(); } else { qDebug() << "Document is not an object" << endl; } } else { qDebug() << "Invalid JSON...\n" << str << endl; } temp = result["data"].toList(); //qDebug() << "QVariantMap" << result["data"].toList().type(); //qDebug() << "QVariantMap" << temp.at(0).toMap().find("address").value(); m_win->setText(temp); }
8d0eef50774d38ed651b1e06ea7cdb42bdb6df55
40525c30da6c26a1cbbc46c7cd64977bb1e25233
/desktop/src/gui/inspectors/channel/exportPage/pageExportChannel.cpp
3c505e7108024a2ae5f852e576e67e7d9c66edb7
[]
no_license
seung-lab/omni.play
e17f5c977c9458a71062c1383d63baedf8ef6458
a4f1220e9df499f05457aaaee5bc68c2b66d4d54
refs/heads/master
2021-03-24T12:36:23.997379
2016-08-11T15:09:01
2016-08-11T15:09:01
3,678,095
1
0
null
null
null
null
UTF-8
C++
false
false
845
cpp
pageExportChannel.cpp
#include "gui/inspectors/channel/exportPage/buttons/exportButtonChannel.hpp" #include "gui/inspectors/channel/exportPage/buttons/channelInspectorButtons.hpp" #include "gui/inspectors/channel/exportPage/pageExportChannel.h" #include "utility/omStringHelpers.h" om::channelInspector::PageExport::PageExport(QWidget* parent, const ChannelDataWrapper& cdw) : QWidget(parent), cdw_(cdw) { QVBoxLayout* overallContainer = new QVBoxLayout(this); overallContainer->addWidget(makeExportBox()); } QGroupBox* om::channelInspector::PageExport::makeExportBox() { QGroupBox* actionsBox = new QGroupBox("Actions"); QGridLayout* gridAction = new QGridLayout(actionsBox); ExportButton* exportButton = new ExportButton(this); gridAction->addWidget(exportButton, 2, 0, 1, 1); return actionsBox; }
61693ad31d6cf7f034443b116ea796526763e95a
0d2d3bad66b920d0fd35f9a4aa44d5bc119eaf59
/count/count.cpp
b98110f9217b2360673590874d040aac5885869d
[ "MIT" ]
permissive
DINoMe-Project/cryptominisat
3f58806e1729b854004c49542ce810b16d65e4c8
ad7a4ab7ffdffa1d24041da288486d02cec1e212
refs/heads/master
2023-07-02T04:28:05.212402
2021-08-13T01:55:44
2021-08-13T01:55:44
286,884,637
0
0
null
null
null
null
UTF-8
C++
false
false
61,879
cpp
count.cpp
#include "count.h" #include "src/dimacsparser.h" #include <boost/lexical_cast.hpp> #include <ctime> #include <iostream> #include <sys/types.h> #include <unistd.h> #include <unordered_map> using boost::lexical_cast; using std::cout; using std::exit; using std::map; using std::ofstream; using std::unordered_map; using std::unordered_set; string Count::GenerateRandomBits_prob(unsigned size, double prob) { string randomBits = ""; unsigned base = 10000; std::uniform_int_distribution<uint32_t> dist{0, base}; for (int i = 0; i < size; ++i) { randomBits += (dist(randomEngine) < (base * prob)) ? "1" : "0"; } return randomBits; } string Count::GenerateRandomBits(unsigned size) { return GenerateRandomBits_prob(size, 0.5); } string bit2string(vector<bool> &secret_rhs) { string ret = ""; for (int i = 0; i < secret_rhs.size(); ++i) { ret += secret_rhs[i] ? "1" : "0"; } return ret; } bool Count::shuffle(vector<bool> &secret_rhs) { if (secret_rhs.size() == 0) return false; string randomBits_rhs_old = bit2string(secret_rhs); vector<bool> old_secret_rhs = secret_rhs; bool success = false; while (!success) { string randomBits_rhs = GenerateRandomBits(secret_rhs.size()); if (randomBits_rhs != randomBits_rhs_old) { success = true; } for (int i = 0; i < secret_rhs.size(); ++i) { secret_rhs[i] = randomBits_rhs[i] == '1'; } } return true; } void Count::readInAFileToCache(SATSolver *solver2, const string &filename) { vector<vector<Lit>> trans_clauses; vector<std::pair<vector<unsigned>, bool>> trans_xor_clauses; trans_xor_clauses.clear(); trans_clauses.clear(); if (conf.verbosity) { cout << "c Reading file '" << filename << "'" << endl; } #ifndef USE_ZLIB FILE *in = fopen(filename.c_str(), "rb"); DimacsParser<StreamBuffer<FILE *, FN>, SATSolver> parser( solver2, &debugLib, conf.verbosity, &trans_clauses, &trans_xor_clauses); #else gzFile in = gzopen(filename.c_str(), "rb"); DimacsParser<StreamBuffer<gzFile, GZ>, SATSolver> parser( solver2, &debugLib, conf.verbosity, &trans_clauses, &trans_xor_clauses); #endif if (in == NULL) { std::cerr << "ERROR! Could not open file '" << filename << "' for reading: " << strerror(errno) << endl; std::exit(1); } bool strict_header = conf.preprocess; if (!parser.parse_DIMACS(in, strict_header)) { exit(-1); } if (!sampling_vars_str.empty() && !parser.sampling_vars.empty()) { std::cerr << "ERROR! Independent vars set in console but also in CNF." << endl; exit(-1); } if (!sampling_vars_str.empty()) { assert(sampling_vars.empty()); std::stringstream ss(sampling_vars_str); uint32_t i; while (ss >> i) { const uint32_t var = i - 1; sampling_vars.push_back(var); if (ss.peek() == ',' || ss.peek() == ' ') ss.ignore(); } } else { sampling_vars.insert(sampling_vars.end(), parser.sampling_vars.begin(), parser.sampling_vars.end()); } symbol_vars.insert(parser.symbol_vars.begin(), parser.symbol_vars.end()); if (conf.keep_symbol) { for (auto one_symbol_vars : symbol_vars) { for (auto lit : one_symbol_vars.second) sampling_vars.push_back(lit.var()); } } if (sampling_vars.empty()) { if (only_sampling_solution) { std::cout << "ERROR: only independent vars are requested in the " "solution, but no independent vars have been set!" << endl; exit(-1); } } else { solver2->set_sampling_vars(&sampling_vars); } solver2->set_symbol_vars(&symbol_vars); call_after_parse(); #ifndef USE_ZLIB fclose(in); #else gzclose(in); #endif cout << "parse finish and close\n"; cout << "parse trans_clauses" << trans_clauses.size() << std::endl; for (auto cl : trans_clauses) { for (auto lit : cl) { used_vars.insert(lit.var()); } } for (auto cl : trans_xor_clauses) { for (auto var : cl.first) { used_vars.insert(var); } } } vector<string> Count::getCIISSModel(SATSolver *solver) { string ret = ""; std::stringstream ret2; vector<string> labels = {CONTROLLED_, OTHER_ + "_0", OTHER_ + "_1", SECRET_ + "_0", SECRET_ + "_1"}; vector<string> complete_labels = { CONTROLLED_, OTHER_ + "_0", OTHER_ + "_1", SECRET_ + "_0", SECRET_ + "_1", OBSERVABLE_ + "_0", OBSERVABLE_ + "_1"}; auto &model = solver->get_model(); for (auto label : complete_labels) { if (symbol_vars.count(label) == 0) continue; for (auto l : symbol_vars[label]) { ret2 << Lit(l.var(), model[l.var()] == l_False) << ", "; } ret2 << ", "; } for (auto label : labels) { if (symbol_vars.count(label) == 0) { ret += ", "; continue; } ret += ""; for (auto l : symbol_vars[label]) { if (model[l.var()] == l_Undef) ret += "x"; if (model[l.var()] == l_True) ret += l.sign() ? "0" : "1"; if (model[l.var()] == l_False) ret += l.sign() ? "1" : "0"; ret += ", "; } ret += ", "; } return {ret2.str(), ret}; } vector<unsigned> Lits2Vars(vector<Lit> &lits) { vector<unsigned> vars; for (auto l : lits) { vars.push_back(l.var()); } return vars; } void replace_vars(vector<vector<unsigned>> &added_count_lits, vector<unsigned> &old_count_vars, vector<unsigned> &new_count_vars) { unordered_map<unsigned, unsigned> old_to_new; for (int i = 0; i < old_count_vars.size(); ++i) { old_to_new[old_count_vars[i]] = new_count_vars[i]; } int i = 0; for (auto &vars : added_count_lits) { for (auto &var : vars) { var = old_to_new[var]; } i++; } } void Count::AddVariableDiff(SATSolver *solver, map<string, vector<Lit>> all_vars) { int len = -1; vector<Lit> watches; assert(all_vars.size() > 0); int nvar = 0; for (auto id_lits : all_vars) { auto id = id_lits.first; auto lits = id_lits.second; if (len > 0) { assert(len == lits.size()); } len = lits.size(); nvar++; if (nvar > 2) { break; } } static int outtimes = 0; outtimes++; string diff_file = out_dir_ + "//" + out_file_ + ".addVarDiffhash" + std::to_string(outtimes); std::ofstream finalout(diff_file); auto newWatch = solver->nVars() - 1; solver->new_vars(len); for (int i = 0; i < len; ++i) { vector<unsigned> clause; newWatch++; clause.push_back(newWatch); watches.push_back(Lit(newWatch, true)); bool xor_bool = true; nvar = 0; for (auto id_vars : all_vars) { auto id = id_vars.first; auto &lits = id_vars.second; clause.push_back(lits[i].var()); if (lits[i].sign()) xor_bool = !xor_bool; nvar++; if (nvar > 2) { break; } } solver->add_xor_clause(clause, xor_bool); finalout << "x" << (xor_bool ? "" : "-"); for (auto v : clause) finalout << v + 1 << " "; finalout << std::endl; } cout << "add watches" << watches; solver->add_clause(watches); finalout << watches << " 0\n"; finalout.close(); } void Count::setSecretVars() { if (secret_vars.size()) return; for (auto name_lits : symbol_vars) { int name_len = SECRET_.length(); if (!name_lits.first.compare(0, SECRET_.length(), SECRET_)) { auto id = name_lits.first.substr(name_len); for (auto lit : name_lits.second) { secret_vars.push_back(lit.var()); all_secret_lits[id].push_back(lit); } } name_len = DECLASS_.length(); if (!name_lits.first.compare(0, DECLASS_.length(), DECLASS_)) { auto id = name_lits.first.substr(name_len); for (auto lit : name_lits.second) { all_declass_lits[id].push_back(lit); } } } } void Count::setCountVars() { if (count_vars.size()) return; cout << "setCountVars\n"; all_observe_lits.clear(); control_lits.clear(); all_other_lits.clear(); all_count_vars.clear(); vector<unsigned> other_control_vars; for (auto name_lits : symbol_vars) { if (!name_lits.first.compare(0, CONTROLLED_.length(), CONTROLLED_)) { for (auto lit : name_lits.second) { control_lits.push_back(lit); } } else if (!name_lits.first.compare(0, OBSERVABLE_.length(), OBSERVABLE_)) { auto id = name_lits.first.substr(OBSERVABLE_.length()); for (auto lit : name_lits.second) { // count_vars.push_back(lit.var()); all_observe_lits[id].push_back(lit); } } else if (!name_lits.first.compare(0, OTHER_.length(), OTHER_)) { auto id = name_lits.first.substr(OTHER_.length()); for (auto lit : name_lits.second) { all_other_lits[id].push_back(lit); } } } cout << "control_lits size=" << control_lits.size() << std::endl; for (auto id_lits : all_observe_lits) { auto id = id_lits.first; for (auto lit : control_lits) { all_count_vars[id_lits.first].push_back(lit.var()); } if (count_direction_ == "in") { for (auto lit : all_secret_lits[id]) { all_count_vars[id_lits.first].push_back(lit.var()); } } else { for (auto lit : all_observe_lits[id]) { all_count_vars[id_lits.first].push_back(lit.var()); } } for (auto lit : all_other_lits[id]) { all_count_vars[id_lits.first].push_back(lit.var()); } if (declassification_mode_ == 1 && (all_declass_lits.size() > 0)) { for (auto lit : all_declass_lits[id]) { all_count_vars[id_lits.first].push_back(lit.var()); } } cout << "all_count_vars[id_lits] size=" << all_count_vars[id_lits.first].size() << std::endl; } } void Count::AddVariableSame(SATSolver *solver, map<string, vector<Lit>> all_vars) { int len = -1; vector<Lit> watches; if (all_vars.size() == 0) { return; } assert(all_vars.size() > 0); int nvar = 0; for (auto id_lits : all_vars) { auto id = id_lits.first; auto lits = id_lits.second; if (len > 0) { assert(len == lits.size()); } len = lits.size(); nvar++; if (nvar == 2) { break; } } string diff_file = out_dir_ + "//" + out_file_ + ".testsamehash"; std::ofstream finalout(diff_file); for (int i = 0; i < len; ++i) { vector<unsigned> clause; bool xor_bool = false; cout << "add same "; nvar = 0; for (auto id_vars : all_vars) { auto id = id_vars.first; auto &lits = id_vars.second; clause.push_back(lits[i].var()); if (lits[i].sign()) { cout << "reverse" << xor_bool << " to "; xor_bool = !xor_bool; cout << xor_bool << " "; } cout << lits[i] << " " << lits[i].sign() << " " << xor_bool << "\t"; nvar++; if (nvar == 2) { break; } } cout << "\n"; solver->add_xor_clause(clause, xor_bool); finalout << "x" << (xor_bool ? "" : "-"); cout << "x" << (xor_bool ? "" : "-"); for (auto v : clause) { cout << v << "\t"; finalout << (v + 1) << " "; } cout << "0\n"; finalout << "0\n"; } finalout.close(); } string Count::trimVar(SATSolver *solver2, vector<unsigned> &vars) { string ret = ""; std::unordered_map<unsigned, string> fixed_var_set; set<unsigned> new_vars; for (auto lit : solver2->get_zero_assigned_lits()) { fixed_var_set[lit.var()] = lit.sign() ? "0" : "1"; } for (auto var : vars) { if (used_vars.count(var) == 0) { if (find(secret_vars.begin(), secret_vars.end(), var) == secret_vars.end()) { std::cout << "unused vars" << var << std::endl; ret += "u"; continue; } } if (unused_sampling_vars.count(var)) { if (find(secret_vars.begin(), secret_vars.end(), var) == secret_vars.end()) { std::cout << "unused_sampling_vars vars" << var << std::endl; ret += "u"; continue; } } if (fixed_var_set.count(var) > 0) { ret += fixed_var_set[var]; std::cout << "fixed_var_set vars" << var << " =" << fixed_var_set[var] << std::endl; continue; } new_vars.insert(var); ret += "x"; } cout << "new trimed vars size=" << new_vars.size(); vars.clear(); vars.insert(vars.begin(), new_vars.begin(), new_vars.end()); // std::swap(new_secret_vars, secret_vars); return ret; } template <class T> void print_map(std::map<std::string, vector<T>> &map) { for (auto var : map) { cout << var.first << " "; for (auto i : var.second) cout << i << " "; cout << std::endl; } } static string getSSignature(vector<vector<unsigned>> &added_secret_vars) { string sxor = ""; for (auto x : added_secret_vars) { sxor += "xor("; for (auto l : x) { if (sxor[sxor.length() - 1] != ',' && sxor[sxor.length() - 1] != '(') sxor += ","; sxor += std::to_string(l); } sxor += ");"; } return sxor; } void Count::RecordCount(map<int, int> &sols, int hash_count, string rnd) { std::ofstream count_f(out_dir_ + "/" + out_file_ + ".count", std::ofstream::out | std::ofstream::app); count_f << sols[hash_count] << "\t" << hash_count + unrelated_number_countvars << "\t%" << rnd << std::endl; count_f.close(); } void Count::RecordCountInter(map<int, int> &sols, int hash_count, vector<map<int, int>> b_sols, vector<int> b_hash_counts, string rnd, int totaltime) { std::ofstream count_f(out_dir_ + "/" + out_file_ + ".inter.count", std::ofstream::out | std::ofstream::app); count_f << abs(sols[hash_count]) << "\t" << hash_count + unrelated_number_countvars << "\t"; int norm_sum_sols = 0; string timeoutmark = ""; timeoutmark += (sols[hash_count] < 0) ? "t" : ""; for (int id = 0; id < b_sols.size(); ++id) { int hash = b_hash_counts[id]; timeoutmark += (b_sols[id][hash] < 0) ? "t" : ""; count_f << abs(b_sols[id][hash]) << "\t" << hash + unrelated_number_countvars << "\t"; norm_sum_sols += abs(b_sols[id][hash]) * pow(2, hash - hash_count); } double j = 1 - 1.0 * abs(sols[hash_count]) / norm_sum_sols; std::cout << "Jaccard =" << j << std::endl; count_f << std::setprecision(3) << j << "\t%" << timeoutmark << ",used=" << totaltime << "," << rnd << std::endl; count_f.close(); } void Count::calculateDiffSolution(vector<vector<Lit>> &sol1, vector<vector<Lit>> &sol2, vector<string> &sol_str1, vector<string> &sol_str2, string rnd) { if (conf.verbosity == 0) { return; } set<string> str1; //(sol_str1.begin(), sol_str1.end()), set<string> str2; map<string, int> strmap; //(sol_str2.begin(), sol_str2.end()); std::ofstream solution_f(out_dir_ + "//" + out_file_ + ".sol.diff", std::ofstream::out | std::ofstream::app); for (auto lit : sol1) { std::stringstream ss(""); ss << lit; cout << ss.str() << std::endl; str1.insert(ss.str()); } int i = 0; for (auto lit : sol2) { std::stringstream ss(""); ss << lit; strmap[ss.str()] = i; ++i; str2.insert(ss.str()); } for (auto s : str1) { cout << s << std::endl; } for (auto s : str2) { cout << s << std::endl; } cout << "====calculateDiffSolution\n"; cout << str1.size() << "\t" << str2.size() << std::endl; for (auto s : str2) { if (!str1.count(s)) { cout << s << std::endl << strmap[s] << std::endl; solution_f << s << " %" << rnd << std::endl; } } cout << "====calculateSameSolution\n"; for (auto s : str2) { if (str1.count(s)) { cout << s << std::endl; } } solution_f.close(); } void Count::RecordSolution(string rnd, string subfix = "") { if (!record_solution_) return; std::cout << "start record solution\n"; std::ofstream solution_f(out_dir_ + "//" + out_file_ + ".sol" + subfix, std::ofstream::out | std::ofstream::app); for (int i = 0; i < solution_lits.size(); ++i) solution_f << solution_lits[i] << "; " << solution_strs[i] << " % " << rnd << std::endl; solution_f.close(); } void Count::add_count_options() { countOptions_.add_options()("cycles", po::value(&cycles_)->default_value(1), "Number of composition cycles."); countOptions_.add_options()( "victim", po::value(&victim_model_config_)->default_value(""), "Victim model config: secret sym_name offset size\n observe: " "(sym_name,offset,size)\n control: (sym_name,offset,size) "); countOptions_.add_options()("debug", po::value(&debug)->default_value(false), "Debug"); countOptions_.add_options()( "declassification_mode", po::value(&declassification_mode_)->default_value(1), "declassification_mode: 0: additional leakage, 1: additional leakage " "when declassified is known"); countOptions_.add_options()( "caching_solution", po::value(&caching_solution_)->default_value(true), "Caching solution when counting "); countOptions_.add_options()("symmap", po::value(&symmap_file_)->default_value(""), "Initilization constraint file."); countOptions_.add_options()("initfile", po::value(&init_file_)->default_value(""), "Initilization constraint file."); countOptions_.add_options()("count_out", po::value(&out_file_)->default_value("out"), "Countd filename."); countOptions_.add_options()("out", po::value(&out_dir_)->default_value("tmp")); countOptions_.add_options()("xor_ratio", po::value(&xor_ratio_)->default_value(0.5)); countOptions_.add_options()("num_xor_cls", po::value(&num_xor_cls_)->default_value(0)); countOptions_.add_options()("max_sol", po::value(&max_sol_)->default_value(64)); countOptions_.add_options()("max_count_times", po::value(&max_count_times_)->default_value(10)); countOptions_.add_options()("nsample", po::value(&nsample)->default_value(5)); countOptions_.add_options()("min_log_size", po::value(&min_log_size_)->default_value(-1)); countOptions_.add_options()( "total_call_timeout", po::value(&total_call_timeout_)->default_value(700)); countOptions_.add_options()( "one_call_timeout", po::value(&one_call_timeout_)->default_value(200)); countOptions_.add_options()("max_log_size", po::value(&max_log_size_)->default_value(-1)); countOptions_.add_options()("max_xor_per_var", po::value(&max_xor_per_var_)->default_value(32)); countOptions_.add_options()("xor_decay", po::value(&xor_decay_)->default_value(1.0)); countOptions_.add_options()("count_mode", po::value(&mode_)->default_value("block"), "mode: nonblock-> backtrack, block -> block"); countOptions_.add_options()( "count_direction", po::value(&count_direction_)->default_value("inout"), "inout: C,I,O, in: C,I,S"); countOptions_.add_options()( "use_overlap_coefficient", po::value(&use_overlap_coefficient_)->default_value(true), "Valid when inter_mode=2, False: use Y1 V Y2 as denominator, True: use " "Y1 as denominator"); countOptions_.add_options()("use_simplify", po::value(&use_simplify_)->default_value(true), "use simplify"); countOptions_.add_options()( "inter_mode", po::value(&inter_mode_)->default_value(2), "1-> secret_1 and secret_2, observe_1 and observe_2, 0: single, 2: " "JaccardHat with diff set if use_overlap_coefficient=false, " "JaccardHat with symmetric diff set if use_overlap_coefficient=true, " "3: " "JaccardHat with Same Other"); countOptions_.add_options()( "record_solution", po::value(&record_solution_)->default_value(true), "True: write solutions; false: do not write solutions"); help_options_simple.add(countOptions_); help_options_complicated.add(countOptions_); } void Count::add_supported_options() { Main::add_supported_options(); add_count_options(); } bool Count::readVictimModel(SATSolver *&solver) { std::ifstream vconfig_f; if (victim_model_config_.length() == 0) return false; vconfig_f.open(victim_model_config_); map<string, vector<Lit>> new_symbol_vars; string line; while (std::getline(vconfig_f, line)) { std::stringstream ss(line); std::string token; vector<std::string> tokens; while (std::getline(ss, token, ' ')) { tokens.push_back(token); } if (tokens.size() != 4) { cout << "error victim model: " << line; exit(1); } string name = tokens[1]; int offset = std::stoi(tokens[2]); int size = std::stoi(tokens[3]); if (symbol_vars.count(name) == 0) { cout << "not found symbol: " << name; exit(1); } if (!IsValidVictimLabel(tokens[0])) { cout << "Error Victim Label " << tokens[0]; exit(1); } if (symbol_vars[name].size() < size) { cout << "Error symbol " << name << " " << symbol_vars[name].size() << " " << size << std::endl; exit(1); } for (int i = offset; i < offset + size; ++i) { victim_model_[tokens[0]].push_back(symbol_vars[name][i].var()); new_symbol_vars[tokens[0]].push_back(symbol_vars[name][i]); } } solver->set_symbol_vars(&new_symbol_vars); string symbol_tmpfile = out_dir_ + "//" + out_file_ + ".symbol"; std::ofstream symbol_tmpf(symbol_tmpfile); /* for (auto &vars : new_symbol_vars) { string values = trimVar(solver, vars.second); symbol_tmpf << vars.first << "\t" << values << std::endl; }*/ symbol_tmpf.close(); sampling_vars.clear(); for (auto lits : new_symbol_vars) for (auto lit : lits.second) sampling_vars.push_back(lit.var()); solver->set_sampling_vars(&sampling_vars); // simplify(solver); string victim_cnf_file = out_dir_ + "//" + out_file_ + ".simp"; std::ofstream finalout(victim_cnf_file); solver->dump_irred_clauses_ind_only(&finalout); finalout.close(); // delete solver; auto newconf = conf; SATSolver s(&newconf); solver = newCounterSolver(&s, (void *)&newconf); symbol_vars.clear(); sampling_vars.clear(); readInAFile(solver, victim_cnf_file); return true; /* vector<unsigned> secret_vars(victim_model_[SECRET_].begin(), victim_model_[SECRET_].end()); count_vars.insert(count_vars.end(), victim_model_[CONTROLLED_].begin(), victim_model_[CONTROLLED_].end()); count_vars.insert(count_vars.end(), victim_model_[OBSERVABLE_].begin(), victim_model_[OBSERVABLE_].end()); count_vars.insert(count_vars.end(), victim_model_[OTHER_].begin(), victim_model_[OTHER_].end());*/ } string Count::SampleSmallXor(SATSolver *solver2, std::vector<unsigned> vars, int num_xor_cls, vector<Lit> &watch, vector<vector<unsigned>> &alllits, vector<bool> &rhs, Lit addInner, bool is_restarted) { num_xor_cls = num_xor_cls * amplifier_factor_; vector<Lit> addInners; addInners.push_back(addInner); set<vector<bool>> rhs_sets; string ret = ""; for (int i = 0; i < amplifier_factor_; ++i) { auto sub_addInner = new_watch(solver2); watch.clear(); ret = Sample(solver2, vars, num_xor_cls, watch, alllits, rhs, sub_addInner, is_restarted); addInners.push_back(sub_addInner); rhs_sets.insert(rhs); while (rhs_sets.count(rhs)) { shuffle(rhs); } } solver2->add_clause(addInners); return ret; } string Count::Sample(SATSolver *solver2, std::vector<unsigned> vars, int num_xor_cls, vector<Lit> &watch, vector<vector<unsigned>> &alllits, vector<bool> &rhs, Lit addInner, bool is_restarted) { /*if (num_xor_cls < 2) { return SampleSmallXor(solver2, vars, num_xor_cls, watch, alllits, rhs, addInner, is_restarted); }*/ double ratio = xor_ratio_; double xor_decay = xor_decay_; // srand(unsigned(time(NULL))); if (num_xor_cls * ratio > max_xor_per_var_) { ratio = max_xor_per_var_ * 1.0 / num_xor_cls; cout << "too many xor... we hope to use at most" << max_xor_per_var_ << " xor per var, thus change ratio to" << ratio << std::endl; } string randomBits = ""; std::set<string> randomBitsSet; if (num_xor_cls == vars.size()) { // only pick one value ratio = 1.0 / num_xor_cls; xor_decay = 1.0; vector<int> tmp(num_xor_cls); for (int i = 0; i < num_xor_cls; ++i) { tmp[i] = i; } // std::shuffle(tmp.begin(), tmp.end(), randomEngine); randomBits = string(vars.size() * num_xor_cls, '0'); for (int i = 0; i < num_xor_cls; ++i) { randomBits[tmp[i] + i * vars.size()] = '1'; } } else { for (int i = 0; i < num_xor_cls; ++i) { int max_xor_per_var = ratio * vars.size(); string tmp(max_xor_per_var, '1'); tmp = tmp + string(vars.size() - max_xor_per_var, '0'); if (num_xor_cls > 100) { ratio = ratio * xor_decay; xor_decay = 1.0 / xor_decay; } while (true) { if (num_xor_cls < 100) tmp = GenerateRandomBits_prob(vars.size(), ratio); else std::shuffle(tmp.begin(), tmp.end(), randomEngine); if (tmp.find("1") == std::string::npos) { // no var is chosen in the hash continue; } if (randomBitsSet.count(tmp) == 0) break; } randomBitsSet.insert(tmp); randomBits += tmp; } } string randomBits_rhs = GenerateRandomBits(num_xor_cls); vector<unsigned> lits; // assert watch=0;? if (watch.size() < num_xor_cls) { int diff = num_xor_cls - watch.size(); int base = watch.size(); watch.resize(num_xor_cls); for (int i = 0; i < diff; ++i) { watch[base + i] = Lit(solver2->nVars() + i, false); } solver2->new_vars(diff); } for (int i = 0; i < num_xor_cls; ++i) { lits.clear(); if (alllits.size() > i) { // reuse generated xor lits; // lits = alllits[i]; if (is_restarted) { lits = alllits[i]; } } else { while (lits.size() < 1) { for (unsigned j = 0; j < vars.size(); j++) { if (randomBits[i * vars.size() + j] == '1') lits.push_back(vars[j]); if (hashf) *hashf << vars[j] + 1 << " "; } assert(lits.size() >= 1); } /*cout << "add hash " << randomBits.substr(i * vars.size(), vars.size()) << std::endl;*/ alllits.push_back(lits); rhs.push_back(randomBits_rhs[i] == '1'); } // 0 xor 1 = 1, 0 xor 0= 0, thus,we add watch=0 => xor(1,2,4) = r if (watch[i].var() >= solver2->nVars()) { solver2->new_vars(watch[i].var() - solver2->nVars() + 1); } lits.push_back(watch[i].var()); if (addInner != lit_Undef) { solver2->add_clause({addInner, watch[i]}); /* debugging*/ cout << "secret hash xor:\n"; cout << "watch:" << addInner << watch[i]; for (auto l : lits) { cout << l + 1 << "\t"; } cout << rhs[i] << std::endl; } // e.g., xor watch 1 2 4 .. solver2->add_xor_clause(lits, rhs[i]); } return randomBits; } int Count::bounded_sol_count_cached(SATSolver *solver, const vector<unsigned> &count_vars, unsigned maxSolutions, const vector<Lit> &assumps, Lit act_lit) { int nsol = 0; vector<Lit> blocked_lits; for (auto solution : cached_inter_solution) { auto begin = cpuTimeTotal(); solution.insert(solution.end(), assumps.begin(), assumps.end()); auto ret = solver->solve(&solution, true); if (ret == l_True) { nsol++; blocked_lits.clear(); blocked_lits.push_back(act_lit); for (auto l : solution) { blocked_lits.push_back(~l); } solver->add_clause(blocked_lits); } std::cout << "check cached sol once" << cpuTimeTotal() - begin << "nsol=" << nsol << std::endl; if (nsol >= maxSolutions) { break; } } cout << "cached solution =" << nsol; return nsol; } int Count::bounded_sol_count(SATSolver *solver, const vector<unsigned> &target_count_vars, unsigned maxSolutions, const vector<Lit> &assumps, bool only_ind) { int solutions = 0; vector<Lit> solution; lbool ret; // solver->load_state(conf.saved_state_file); // setCountVars(); auto s_vars = target_count_vars; solver->set_sampling_vars(&s_vars); if (mode_ == "nonblock") { ret = solver->solve(&assumps, only_ind); for (auto sol_str : solver->get_solutions()) { std::stringstream ss(sol_str); string token; solution.clear(); while (ss >> token) { int int_lit = std::stoi(token); unsigned var = abs(int_lit) - 1; solution.push_back(Lit(var, int_lit < 0)); } solution_strs.push_back(getCIISSModel(solver)[0]); solution_lits.push_back(solution); } // delete solver; return solver->n_seareched_solutions(); } // Set up things for adding clauses that can later be removed vector<lbool> model; vector<Lit> new_assumps(assumps); solver->new_var(); unsigned act_var = solver->nVars() - 1; new_assumps.push_back(Lit(act_var, true)); long begin = cpuTimeTotal(); if (new_assumps.size() > 1) simplify(solver, &new_assumps); if (debug) { std::ofstream finalout("debug.cnf"); for (auto l : new_assumps) { solver->add_clause({l}); symbol_vars["assump"].push_back(l); } solver->dump_irred_clauses_ind_only(&finalout); finalout.close(); exit(0); } std::cout << "after simp, time=" << cpuTimeTotal() - begin << std::endl; solutions = bounded_sol_count_cached(solver, target_count_vars, maxSolutions, new_assumps, Lit(act_var, false)); used_time_ = 0; while (solutions < maxSolutions) { begin = cpuTimeTotal(); solver->set_max_time( std::max(one_call_timeout_, total_call_timeout_ - used_time_)); ret = solver->solve(&new_assumps, only_ind); used_time_ = cpuTimeTotal() - begin; std::cout << "sol=" << solutions << "/" << maxSolutions << ",solve once" << cpuTimeTotal() - begin << std::endl; solver->set_max_time(100000 * one_call_timeout_); // assert(ret == l_False || ret == l_True); if (conf.verbosity >= 2) { cout << "[appmc] bounded_sol_count ret: " << std::setw(7) << ret; if (ret == l_True) { cout << " sol no. " << std::setw(3) << solutions; } else { cout << " No more. " << std::setw(3) << ""; } } if (ret != l_True) { break; } solutions++; model = solver->get_model(); if (solutions < maxSolutions) { vector<Lit> lits; lits.push_back(Lit(act_var, false)); solution.clear(); for (const unsigned var : target_count_vars) { solution.push_back(Lit(var, model[var] == l_False)); if (model[var] != l_Undef) { lits.push_back(Lit(var, model[var] == l_True)); } else { assert(false); } } assert(solution.size() == target_count_vars.size()); if (conf.verbosity > 1) { cout << "====result===" << std::endl; cout << std::setbase(16); for (int k = 0; k < 8; ++k) { long long val = 0, base = 1; for (int i = 0; i < 100; ++i) { if (i % 32 == 0) { val = 0; } val = (val << 1) + (lits[1 + i + k * 100].sign() ? 1 : 0); if (i % 32 == 31) { cout << val << " "; } } cout << std::setbase(16); cout << val << " "; cout << std::endl; } cout << std::setbase(10); cout << std::setbase(10); cout << "[appmc] Adding banning clause: " << lits << endl; } solver->add_clause(lits); if (record_solution_ || caching_solution_) { solution_lits.push_back(solution); solution_strs.push_back(getCIISSModel(solver)[0]); } } } // Remove clauses added vector<Lit> cl_that_removes; cl_that_removes.push_back(Lit(act_var, false)); solver->add_clause(cl_that_removes); if (ret == l_Undef) { return -solutions; } return solutions; } map<int, int> Count::count_once(SATSolver *solver, vector<unsigned> &target_count_vars, const vector<Lit> &secret_watch, int &left, int &right, int &hash_count, bool reserve_xor) { right = std::min(int(target_count_vars.size()), right); if (left > right) { left = right / 2; } long total_start = cpuTimeTotal(); int nsol = 0, nice_hash_count = target_count_vars.size() * 2, timeout_nice_hash_count = target_count_vars.size() * 2; std::set<int> nice_hash_counts, timeout_nice_hash_counts; if (!reserve_xor) { added_count_lits.clear(); count_rhs.clear(); count_watch.clear(); } else { count_watch.clear(); Sample(solver, target_count_vars, added_count_lits.size(), count_watch, added_count_lits, count_rhs, lit_Undef, true); } map<int, int> solution_counts; map<int, vector<vector<Lit>>> hash_solutions; map<int, vector<string>> hash_solution_strs; vector<Lit> assump; solution_lits.clear(); solution_strs.clear(); cout << "target count size" << target_count_vars.size() << std::endl; if (left < 1 && hash_count == 0) { nsol = bounded_sol_count(solver, target_count_vars, max_sol_, assump, true); hash_solutions[0] = solution_lits; hash_solution_strs[0] = solution_strs; if (nsol < max_sol_) { left = right = hash_count = 0; solution_counts[0] = nsol; nice_hash_count = 0; cout << "found solution" << nsol << "no need xor\n"; } } hash_count = hash_count > 0 ? hash_count : (right + left) / 2; int timeouts = 0; while (left < right && (nsol < max_sol_ * 0.6 || nsol >= max_sol_)) { solution_lits.clear(); solution_strs.clear(); cout << "starting... hash_count=" << hash_count << ",left=" << left << ", right=" << right << std::endl << std::flush; long start = cpuTimeTotal(); Sample(solver, target_count_vars, hash_count, count_watch, added_count_lits, count_rhs, lit_Undef, true); cout << "sample time cost=" << cpuTimeTotal() - start << std::endl; assump.clear(); // assump = secret_watch; assump.insert(assump.end(), count_watch.begin(), count_watch.begin() + hash_count); if (!solution_counts.count(hash_count)) { solution_counts[hash_count] = bounded_sol_count(solver, target_count_vars, max_sol_, assump, true); hash_solutions[hash_count] = solution_lits; hash_solution_strs[hash_count] = solution_strs; cached_inter_solution.insert(cached_inter_solution.end(), solution_lits.begin(), solution_lits.end()); } else { break; } nsol = solution_counts[hash_count]; cout << "hash_count=" << hash_count << ", nsol=" << solution_counts[hash_count] << std::endl; solution_counts[hash_count] = abs(nsol); if (nsol >= max_sol_) { left = hash_count + 1; } else if (nsol < max_sol_ * 0.6) { if (nsol > 0 && timeout_nice_hash_counts.count(hash_count) == 0) nice_hash_counts.insert(hash_count); else if (nsol < 0) { timeouts++; timeout_nice_hash_counts.insert(hash_count); } if (nsol > 0) { right = hash_count; auto new_hash_count = std::max( left, hash_count - int(floor(log2(max_sol_ * 1.0 / nsol)))); if (nice_hash_counts.size() == 1 || solution_counts.begin()->second < max_sol_) { left = std::min(left, new_hash_count - int(floor(log2(max_sol_ * 1.0 / nsol))) - 1); } if (new_hash_count == hash_count) { hash_count = std::max(left, hash_count - 1); } else { hash_count = new_hash_count; } left = std::max(left, hash_count - int(floor(log2(max_sol_ * 1.0 / nsol))) - 1); cout << "hash_count=" << hash_count << ", nsol=" << nsol << "left=" << left << "right=" << right << std::endl; continue; } else if (nsol < 0) { if (timeouts < 3 && (hash_count - left > 1)) { hash_count--; cout << "timeout..... Let's check smaller hashcount to see some " "luck"; } else { left = hash_count; hash_count++; cout << "timeouts > 2..... Let's check larger hashcount to see some " "luck"; } continue; } else if (nsol == 0) { right = hash_count; if (solution_counts.begin()->second==0) { left = std::max( 0, std::min(left, right - int(floor(log2(max_sol_))) * 2 - 2)); } } } else { if (timeout_nice_hash_counts.count(nice_hash_count) == 0) nice_hash_counts.insert(hash_count); right = hash_count; left = hash_count; break; } if (right <= left && solution_counts[hash_count] >= max_sol_) { if (solution_counts.rbegin()->second >= max_sol_) { right = int(target_count_vars.size()); } } if (right <= left && solution_counts[hash_count] == 0) { if (solution_counts.begin()->second == 0) { left = 0; } } hash_count = left + (right - left) / 2; } bool use_timeout_result = (nice_hash_counts.size() == 0); if ((nice_hash_counts.size() > 0) || (timeout_nice_hash_counts.size() > 0)) hash_count = (nice_hash_counts.size() > 0) ? *nice_hash_counts.begin() : *timeout_nice_hash_counts.begin(); bool retry = false; int retry_max_sol = max_sol_; if (!solution_counts.count(hash_count) && hash_count >= 0) { retry = true; } if (solution_counts[hash_count] > max_sol_) { retry = true; retry_max_sol = max_sol_ * 4; } if (solution_counts[hash_count] == 0) { if (solution_counts.count(hash_count - 1) && solution_counts[hash_count - 1] > 0) { retry = true; hash_count = hash_count - 1; retry_max_sol = max_sol_ * 4; } } if (retry) { // std::cerr << "error !solution_counts.count(hash_count) && hash_count >= // 0"; assert(false); long start = cpuTimeTotal(); Sample(solver, target_count_vars, hash_count, count_watch, added_count_lits, count_rhs, lit_Undef, true); cout << "retry sample time cost=" << cpuTimeTotal() - start << std::endl; solution_lits.clear(); solution_strs.clear(); assump.clear(); // assump = secret_watch; assump.insert(assump.end(), count_watch.begin(), count_watch.begin() + hash_count); solution_counts[hash_count] = bounded_sol_count( solver, target_count_vars, retry_max_sol, assump, true); hash_solutions[hash_count] = solution_lits; hash_solution_strs[hash_count] = solution_strs; cout << "retry hashcount=" << hash_count << ", nsols=" << solution_counts[hash_count]; } left = std::max(0, hash_count - std::min(5, (hash_count + 1) / 2)); right = std::min(int(target_count_vars.size()), hash_count + std::min(5, (hash_count + 1) / 2)); cout << "found solution" << solution_counts[hash_count] << "* 2^" << hash_count << std::endl; solution_lits = hash_solutions[hash_count]; solution_strs = hash_solution_strs[hash_count]; cout << "Total time=" << cpuTimeTotal() - total_start << std::endl; if (use_timeout_result) { solution_counts[hash_count] = -solution_counts[hash_count]; } return solution_counts; } vector<unsigned> Count::getCISAlt() { vector<unsigned> ret; string id0 = "_0", id1 = "_1"; for (auto l : control_lits) { ret.push_back(l.var()); } for (auto l : all_other_lits[id1]) { ret.push_back(l.var()); } for (auto l : all_secret_lits[id1]) { ret.push_back(l.var()); } return ret; } void compose_distinct_secretset( SATSolver *solver, const map<string, vector<Lit>> &solver_secret_rhs_watches, bool useCup) { auto choice1 = Lit(solver->nVars(), true); auto choice2 = Lit(choice1.var() + 1, true); solver->new_vars(2); for (auto id_watches_pair : solver_secret_rhs_watches) { auto id_watches = id_watches_pair.second; if (id_watches.size() != 2) { std::cerr << "id_watches.size()=" << id_watches.size() << std::endl; } solver->add_clause({~id_watches[0], choice1}); solver->add_clause({~id_watches[1], choice2}); cout << "====compose_distinct_secretset===\n"; cout << ~id_watches[0] << "," << choice1 << std::endl; cout << ~id_watches[1] << "," << choice2 << std::endl; } if (useCup) { // ( h(S1)=r1 && h(S2)=r2 ) or (h(S1)=r2 && h(S2)=r1) solver->add_xor_clause({choice2.var(), choice1.var()}, true); } else { // ( h(S1)=r1 && h(S2)=r2 ) solver->add_clause({~choice1}); // solver->add_clause({choice2}); } } bool Count::count(SATSolver *solver, vector<unsigned> &secret_vars) { vector<vector<unsigned>> added_secret_vars; map<string, vector<vector<unsigned>>> all_added_secret_vars; map<string, vector<bool>> all_added_secret_rhs; vector<Lit> secret_watch; vector<bool> secret_rhs; string secret_rnd = ""; // trimVar(solver, secret_vars); cout << "count\n" << solver << ", secret size=" << secret_vars.size(); cout << "Sample\n" << std::flush; if (secret_vars.size() < num_xor_cls_) { cout << "add more xor " << num_xor_cls_ << " than secret var size\n" << std::flush; num_xor_cls_ = secret_vars.size(); } map<string, vector<Lit>> solver_secret_rhs_watches; if (inter_mode_ == 0) { auto rhs_watch = new_watch(solver); solver->add_clause({~rhs_watch}); secret_rnd = Sample(solver, secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, rhs_watch); } else { map<unsigned, int> prev_secret_var_to_index; int number_S = 0; vector<string> ids = getIDs(); for (size_t i = 0; i < ids.size(); ++i) { // for (auto id_lits : all_secret_lits) { string id = ids[i]; cout << id; auto current_secret_vars = Lits2Vars(all_secret_lits[id]); // when one secret set is selcted, we should generate another set using // same hash but with different rhs to ensure disjoint sets. if (i > 1 || shuffle(secret_rhs)) { for (auto &added_vars : added_secret_vars) { // replace var from secret_1 to secret_2 for (auto &var : added_vars) { var = current_secret_vars[prev_secret_var_to_index[var]]; } } } for (int offset = 0; offset < current_secret_vars.size(); ++offset) { prev_secret_var_to_index[current_secret_vars[offset]] = offset; } if (i < 2) { auto rhs_watch = new_watch(solver); // assert h(Si)=ri; secret_watch.clear(); secret_rnd += Sample(solver, current_secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, rhs_watch, true); secret_rnd += bit2string(secret_rhs); solver_secret_rhs_watches[id].push_back(rhs_watch); } else { auto rhs_watch = solver_secret_rhs_watches[ids[i - 1]].back(); secret_watch.clear(); secret_rnd += Sample(solver, current_secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, rhs_watch, true); } // solver->add_clause({~rhs_watch}); all_added_secret_vars[id] = added_secret_vars; all_added_secret_rhs[id] = secret_rhs; } for (size_t i = 0; i < 2; ++i) { std::cout << "sample opposite sets: H(S1)=r2, H(S2)=r1" << std::endl; string id = ids[i]; string add_id = ids[1 - i]; auto current_secret_vars = Lits2Vars(all_secret_lits[id]); auto added_secret_vars = all_added_secret_vars[id]; auto secret_rhs = all_added_secret_rhs[add_id]; // add H(S1)=r2 xor solver_secret_rhs_watches[2] // add H(S2)=r1 xor solver_secret_rhs_watches[3] auto secret_rhs_watch = new_watch(solver); secret_watch.clear(); solver_secret_rhs_watches[id].push_back(secret_rhs_watch); Sample(solver, current_secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, secret_rhs_watch, true); } for (size_t i = 2; i < ids.size(); ++i) { secret_watch.clear(); auto secret_rhs = all_added_secret_rhs[ids[1]]; auto added_secret_vars = all_added_secret_vars[ids[i]]; Sample(solver, Lits2Vars(all_secret_lits[ids[i]]), num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, solver_secret_rhs_watches[ids[1]].back(), true); } compose_distinct_secretset(solver, solver_secret_rhs_watches, use_overlap_coefficient_); std::ofstream ff(out_dir_ + "/" + std::to_string(num_xor_cls_) + ".inter.cnf", std::ofstream::out); solver->dump_irred_clauses_ind_only(&ff); ff.close(); // exit(1); for (int k = 0; k < backup_solvers.size(); ++k) { cout << "sample for solver id" << k << std::endl; map<string, vector<Lit>> backup_secret_rhs_watches; backup_secret_rhs_watches.clear(); for (size_t i = 0; i < 2; ++i) { // for (auto id_lits : all_secret_lits) { string id = ids[i]; // for (auto id_added_secret_vars : all_added_secret_vars) { // auto id = id_added_secret_vars.first; backup_secret_rhs_watches[id].resize(2); for (size_t j = 0; j < 2; ++j) { string jid = ids[j]; auto secret_rhs = all_added_secret_rhs[jid]; auto added_secret_vars = all_added_secret_vars[id]; auto current_secret_vars = Lits2Vars(all_secret_lits[id]); auto rhs_watch = new_watch(backup_solvers[k]); if (id == jid) backup_secret_rhs_watches[id][0] = rhs_watch; else backup_secret_rhs_watches[id][1] = rhs_watch; secret_watch.clear(); Sample(backup_solvers[k], current_secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, rhs_watch, true); } } // ( h(S1)=r1 && h(S2)=r2 ) or (h(S1)=r2 && h(S2)=r1) compose_distinct_secretset(backup_solvers[k], backup_secret_rhs_watches, use_overlap_coefficient_); std::ofstream fff(out_dir_ + "/" + std::to_string(num_xor_cls_) + ".back.cnf" + std::to_string(k), std::ofstream::out); backup_solvers[k]->dump_irred_clauses_ind_only(&fff); fff.close(); } } cout << "secret_rnd=" << secret_rnd << std::endl; return after_secret_sample_count(solver, secret_rnd); } bool Count::after_secret_sample_count(SATSolver *solver, string secret_rnd) { // exit(0); vector<map<int, int>> backup_solution_counts(backup_solvers.size()); map<int, int> solution_counts; int max_hash_count = 0; vector<int> backup_max_hash_count(backup_right_.size(), 0); int hash_count = 0; int left, right; vector<int> backup_left(backup_solvers.size()), backup_right(backup_solvers.size()), backup_hash_count(backup_solvers.size()); cout << "Sample end\n" << std::flush; cout << "used_vars.size=" << used_vars.size() << std::endl; /*solver->set_sampling_vars(nullptr); for(int i=0;i<backup_solvers.size();++i) backup_solvers[i]->set_sampling_vars(nullptr);*/ // solver->add_clause(secret_watch); auto start = cpuTimeTotal(); auto checkunion = backup_solvers[0]->solve(); auto time1 = (cpuTimeTotal() - start); std::cout << "checking time=" << time1 << std::endl; if (checkunion == l_False) { std::cerr << "solve is false" << std::endl; return false; } cout << "count size=" << count_vars.size(); string trim = trimVar(backup_solvers[0], count_vars); unrelated_number_countvars = std::count(trim.begin(), trim.end(), 'u'); cout << "secret size=" << secret_vars.size() << std::endl; cout << "count size=" << count_vars.size() << ",unrelated vars=" << unrelated_number_countvars << trim << std::endl; std::cout << "solve is ok" << std::endl; cout << "trimed count vars:"; for (auto v : count_vars) { cout << v << "\t"; } cout << std::endl; start = cpuTimeTotal(); auto checkinter = solver->solve(); if (checkinter == l_False) { solution_counts[0] = 0; hash_count = 0; for (size_t i = 0; i < backup_solution_counts.size(); ++i) { backup_hash_count[i] = (backup_left[i] + backup_right[i]) / 2; backup_solution_counts[i][backup_hash_count[i]] = max_sol_; } RecordCountInter(solution_counts, hash_count, backup_solution_counts, backup_hash_count, secret_rnd, 0); return true; } auto time2 = (cpuTimeTotal() - start) - time1; std::cout << "checking time=" << time2 << std::endl; bool count_inter_first = false; simplify(solver); simplify(backup_solvers[0]); if (time2 > 1 && time2 < time1 / 4) { count_inter_first = true; } left = (left_ > -1) ? left_ : ((min_log_size_ == -1) ? 0 : min_log_size_); right = (right_ > -1) ? right_ : ((max_log_size_ == -1) ? count_vars.size() : max_log_size_); for (size_t i = 0; i < backup_solvers.size(); ++i) { backup_left[i] = backup_left_[i] ? backup_left_[i] : left; backup_right[i] = backup_right_[i] ? backup_right_[i] : right; backup_hash_count[i] = 0; } for (int count_times = 0; count_times < max_count_times_; ++count_times) { auto start_time = cpuTimeTotal(); if (warm_up) { max_sol_ = max_sol_ / 2; } solution_lits.clear(); solution_strs.clear(); solution_counts.clear(); cached_inter_solution.clear(); int idx = 0; if (count_inter_first) { // count intersection before unions cout << count_times << "=========count for target " << "left=" << left << ",right= " << right << "\n\n"; solution_counts = count_once(solver, count_vars, {}, left, right, hash_count); if (warm_up) { for (size_t i = 0; i < backup_solvers.size(); ++i) { backup_right[i] = hash_count + std::min(hash_count, 5); backup_left[i] = hash_count - std::min(hash_count, 5); } } } auto inter_solution_lits = solution_lits; auto inter_solution_strs = solution_strs; for (size_t i = 0; i < backup_solvers.size(); ++i) { cout << "======count for id=" << i << "left=" << backup_left[i] << ",right= " << backup_right[i] << "\n\n"; // auto &current_count_vars = all_count_vars.begin()->second; // replace_vars(added_count_lits, *prev_count_vars, current_count_vars); backup_solution_counts[i] = count_once(backup_solvers[i], count_vars, {}, backup_left[i], backup_right[i], backup_hash_count[i], count_inter_first); RecordSolution(secret_rnd, "." + std::to_string(i)); backup_max_hash_count[i] = std::max(backup_max_hash_count[i], backup_hash_count[i]); // prev_count_vars = &current_count_vars; } auto union_solution_lits = solution_lits; auto union_solution_strs = solution_strs; if (!count_inter_first) { // count unions before intersection; if (warm_up) { right = backup_hash_count[0] + std::min(backup_hash_count[0], 5); left = backup_hash_count[0] - std::min(backup_hash_count[0], 5); } else { if (abs((right + left) / 2 - backup_hash_count[0]) < 3) { right = backup_hash_count[0] + 2; left = backup_hash_count[0] - 2; } } cout << count_times << "=========count for target " << "left=" << left << ",right= " << right << "\n\n"; solution_lits.clear(); solution_strs.clear(); solution_counts = count_once(solver, count_vars, {}, left, right, hash_count, true); inter_solution_lits = solution_lits; inter_solution_strs = solution_strs; } RecordSolution(secret_rnd); calculateDiffSolution(inter_solution_lits, union_solution_lits, inter_solution_strs, union_solution_strs, secret_rnd); if (inter_mode_ == 0) RecordCount(solution_counts, hash_count, secret_rnd); else { auto total_time = cpuTimeTotal() - start_time; RecordCountInter(solution_counts, hash_count, backup_solution_counts, backup_hash_count, secret_rnd, total_time); } max_hash_count = std::max(max_hash_count, hash_count); if (warm_up) { max_sol_ = original_max_sol; int diff = floor(log2(original_max_sol / 16)); max_hash_count -= diff; left -= diff; right -= diff; for (int i = 0; i < backup_solvers.size(); ++i) { backup_max_hash_count[i] -= diff; backup_right[i] -= diff; backup_left[i] -= diff; } } warm_up = false; } left_ = std::max(0, max_hash_count - 5); right_ = std::min(int(count_vars.size()), max_hash_count + 5); for (size_t i = 0; i < backup_right_.size(); ++i) { backup_left_[i] = std::max(0, backup_max_hash_count[i] - 5); backup_right_[i] = std::min(int(count_vars.size()), backup_max_hash_count[i] + 5); } return true; } static void RecordHash(string filename, const vector<vector<unsigned>> &added_secret_vars, const vector<bool> &count_rhs) { std::ofstream f(filename, std::ofstream::out | std::ofstream::app); int i = 0; f << "p cnf 1000 " << added_secret_vars.size() << std::endl; for (auto xor_lits : added_secret_vars) { f << "x" << (count_rhs[i] ? "-" : ""); for (auto v : xor_lits) { f << v + 1 << " "; } f << " 0\n"; i++; } f.close(); } void Count::simulate_count(SATSolver *solver, vector<unsigned> &secret_vars) { solver->set_sampling_vars(&count_vars); vector<vector<unsigned>> added_secret_vars; vector<Lit> secret_watch; vector<bool> secret_rhs; // trimVar(solver, secret_vars); cout << "count\n" << solver << ", secret size=" << secret_vars.size(); cout << "Sample\n"; if (secret_vars.size() < num_xor_cls_) { cout << "add more xor " << num_xor_cls_ << " than secret var size\n"; num_xor_cls_ = secret_vars.size(); } auto rhs_watch = new_watch(solver); solver->add_clause({~rhs_watch}); Sample(solver, secret_vars, num_xor_cls_, secret_watch, added_secret_vars, secret_rhs, rhs_watch); RecordHash("secret_hash.cnf", added_secret_vars, secret_rhs); cout << "Sample end\n"; // solver->add_clause(secret_watch); // trimVar(solver, count_vars); vector<Lit> count_watch; // solver->add_clause(secret_watch); int hash_count = 0; hash_count = max_log_size_; vector<vector<unsigned>> added_count_lits; vector<bool> count_rhs; int pid = -1; string secret_cnf = "final_secret_hash.cnf"; std::ofstream f(secret_cnf, std::ofstream::out); solver->dump_irred_clauses_ind_only(&f); f.close(); for (int count_times = 0; count_times < max_count_times_; ++count_times) { if (pid == 0) { continue; } pid = 0; pid = fork(); if (pid != 0) { continue; } SATSolver newsolver(&conf); readInAFile(&newsolver, secret_cnf); cout << count_times << std::endl; added_count_lits.clear(); count_watch.clear(); count_rhs.clear(); Sample(solver, count_vars, hash_count, count_watch, added_count_lits, count_rhs, lit_Undef); RecordHash("count_hash" + std::to_string(count_times) + ".cnf", added_count_lits, count_rhs); solver->set_preprocess(1); solver->solve(); solver->set_preprocess(0); } } void Count::setBackupSolvers(vector<SATSolver *> &bs) { auto ids = getIDs(); backup_solvers = bs; backup_unused_sampling_vars.clear(); backup_unused_sampling_vars.resize(2); if (inter_mode_) { for (int i = 0; i < 2; ++i) { symbol_vars.clear(); sampling_vars.clear(); readInAFile(backup_solvers[i], filesToRead[0]); if (((declassification_mode_ == 0 && i == 1) || (declassification_mode_ == 1 && i == 0)) && all_declass_lits.size()) { if (all_declass_lits.count("_2")) { cout << "add all_declass_lits[_0], all_declass_lits[_1];" << std::endl; map<string, vector<Lit>> diff_declass_lits; diff_declass_lits["_0"] = all_declass_lits["_0"]; diff_declass_lits["_1"] = all_declass_lits["_1"]; AddVariableSame(backup_solvers[i], diff_declass_lits); } else AddVariableSame(backup_solvers[i], all_declass_lits); } } if (all_declass_lits.size() == 0 || declassification_mode_ == 1) { backup_solvers.resize(1); } } backup_left_.resize(backup_solvers.size()); backup_right_.resize(backup_solvers.size()); backup_unused_sampling_vars.resize(backup_solvers.size()); } void Count::run() { string target_file = filesToRead[0]; if (mode_ == "nonblock") conf.max_sol_ = max_sol_; else { conf.max_sol_ = 1; } original_max_sol = max_sol_; SATSolver s1(&conf); solver = newCounterSolver(&s1, (void *)&conf); inputfile = filesToRead[0]; readInAFileToCache(solver, inputfile); if (init_file_.length() > 0) readInAFile(solver, init_file_); if (symmap_file_.length() > 0) { symbol_vars.clear(); sampling_vars.clear(); readInAFile(solver, symmap_file_); } cout << "read model\n"; if (readVictimModel(solver)) { return; } cout << "end model\n"; // this will set keep_symbol=0, which means it will keep sampling_var but // eliminate symbol setSecretVars(); setCountVars(); target_file = inputfile; /* target_file = out_dir_ + "//" + out_file_ + ".tmp"; std::ofstream finalout(target_file); solver->dump_irred_clauses_ind_only(&finalout); finalout.close();*/ if (mode_ == "simulate") { if (inter_mode_ == 2) { AddVariableSame(solver, all_observe_lits); auto ids = getIDs(); count_vars = all_count_vars[ids[0]]; /*target_file = out_dir_ + "//" + out_file_ + ".same"; std::ofstream finalout(target_file); solver->dump_irred_clauses_ind_only(&finalout); finalout.close();*/ } simulate_count(solver, secret_vars); } else { clearFlagVars(); for (int t = 0; t < nsample; ++t) { symbol_vars.clear(); sampling_vars.clear(); SATSolver ss(&conf); // delete solver; solver = newCounterSolver(&ss, (void *)&conf); readInAFileToCache(solver, target_file); std::cerr << "I am here"; setSecretVars(); setCountVars(); /* if (inter_mode_ == 1) { auto ids = getIDs(); count_vars = all_count_vars[ids[0]]; AddVariableDiff(solver, all_observe_lits); }*/ if (inter_mode_ == 2) { cout << "AddVariableSame for solver"; all_observe_lits.erase("_2"); AddVariableSame(solver, all_observe_lits); if (all_declass_lits.size()) { if (all_declass_lits.count("_2")) { cout << "add all_declass_lits[_0], all_declass_lits[_2];" << std::endl; map<string, vector<Lit>> diff_declass_lits; diff_declass_lits["_0"] = all_declass_lits["_0"]; diff_declass_lits["_2"] = all_declass_lits["_2"]; AddVariableSame(solver, diff_declass_lits); if (declassification_mode_ == 1) { diff_declass_lits["_1"] = all_declass_lits["_1"]; diff_declass_lits.erase("_2"); AddVariableSame(solver, diff_declass_lits); } } else AddVariableSame(solver, all_declass_lits); } auto ids = getIDs(); count_vars = all_count_vars[ids[0]]; cout << "count vars:"; for (auto v : count_vars) { cout << v << "\t"; } cout << std::endl; } solver->set_up_for_jaccard_count(); SATSolver bs1(&conf); SATSolver bs2(&conf); vector<SATSolver *> bs = {newCounterSolver(&bs1, &conf), newCounterSolver(&bs2, &conf)}; setBackupSolvers(bs); std::ofstream finalout("solver.cnf"); solver->dump_irred_clauses_ind_only(&finalout); finalout.close(); std::cout << "sample once" << std::endl << std::flush; if (count(solver, secret_vars) == false) { t--; } } } /*solver = new SATSolver((void *)&conf); parseInAllFiles(solver, filesToRead[0]);*/ }
3029aa66aa03b0b5d58ff2298a73cd8b5964f695
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Implementation/1931.cpp
90517968f6603195643a1389b358087cf7dcc8e8
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
402
cpp
1931.cpp
#include<bits/stdc++.h> using namespace std; int main(){ long long n,x,y,z,sx,sy,sz; cin>>n; sx = 0; sy = 0; sz = 0; for(int i = 0;i< n;i++){ cin>>x>>y>>z; sx+=x; sy+=y; sz+=z; } if(sx==0 && sy == 0 && sz == 0){ cout<<"YES"<<endl; }else { cout<<"NO"<<endl; } return 0; }
b03cb1c4f0f98ba2dde961030ccf9cba86091687
90e2027d4d477557cf37b5f372ef7817a23be484
/string_125_valid_palindrome.cpp
4d50354c56d925f27628ce80dcedab593e598297
[]
no_license
jackyue/leet_code
b860cb93a2835ad735b62dc6daab3bf46e771334
ee7b89b288a623e72c076791317d5fba97264c83
refs/heads/master
2021-06-08T11:34:38.460911
2020-12-13T16:47:51
2020-12-13T16:47:51
98,762,782
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
string_125_valid_palindrome.cpp
/*************************************************************************************** * * 用isalnum判断字符串中的字符是否是字母或者数字,经过reverse之后,判断是否和原字符串相同。 * 时间复杂度O(n),空间复杂度O(1)。 * ***************************************************************************************/ class Solution { public: bool isPalindrome(string s) { if (s.empty()) { return true; } std::string str; for (int i = 0; i < s.length(); ++i) { if (isalnum(s[i])) { str += toupper(s[i]); } } std::string str_raw = str; std::reverse(str.begin(), str.end()); if (str == str_raw) { return true; } return false; } };
67d95eab6352fe78dd70d4e8fa09fccd3c949ecc
ef0be825d2688f00972087423f897129ab214fee
/Server.cpp
23e14a010133e07f46919cc15e4b6adb9e0a5c18
[]
no_license
MerlinSmiles/afmcontrol
5b86714214c4199256e9221821a38fcffa16ec2b
711c6121729cbd261e506fea9c913b08ff2de17a
refs/heads/master
2021-01-17T09:41:32.523091
2016-05-22T12:14:43
2016-05-22T12:14:43
39,294,437
1
1
null
null
null
null
UTF-8
C++
false
false
8,105
cpp
Server.cpp
// File Example1Server.cpp #include <litho.h> #include <guimfc.h> //#include <winsock2.h> #include <windows.h> #include <process.h> /* _beginthread, _endthread */ #include <direct.h> #include <stdlib.h> #include <stdio.h> #include <tchar.h> #include <time.h> #include <merlin_afm.h> //#include <ctime> #include <iostream> // std::cout #include <fstream> // std::ifstream #include <sstream> #include <string> #include <vector> #include <bitset> #include <iostream> #include <conio.h> #include "my_globals.h" using namespace std; void DeleteContent(LPTSTR); bool CheckAbort(LPTSTR); bool RefreshDirectory(LPTSTR); void RefreshTree(LPTSTR); void WatchDirectory(LPTSTR); void ParseFile(LPTSTR); //Prototypen int initWinsock(void); int startWinsock(void); int closeWinsock(void); int connectWinsock(void); int readWinsock(void); int readAbort(void); unsigned int __stdcall CheckKey( void *dummy ); //int writeWinsock(std::string); template<typename C> void split(string const&, char const*, C&); bool b_shutdown = false; /* Global repeat flag */ bool b_abort = false; volatile bool running = true; long rc; SOCKET ServerSocket; SOCKET connectedSocket; //SOCKADDR_IN addr; /* CheckKey - Thread to wait for a keystroke, then clear repeat flag. */ unsigned int __stdcall CheckKey( void *dummy ) { int ch; do { printf( "Type 'A' to abort or 'X' for shutdown\n" ); ch = _getch(); if (ch == 'A') { b_abort = true; //Scriptabort } } while( (ch != 'X') && running); b_shutdown = true; /* _endthread implied */ return 0; } template<typename C> void split(string const& s, char const* d, C& ret) { C output; bitset<255> delims; while( *d ) { unsigned char code = *d++; delims[code] = true; } typedef string::const_iterator iter; iter beg; bool in_token = false; for( string::const_iterator it = s.begin(), end = s.end(); it != end; ++it ) { if( delims[*it] ) { if( in_token ) { output.push_back(typename C::value_type(beg, it)); in_token = false; } } else if( !in_token ) { beg = it; in_token = true; } } if( in_token ) output.push_back(typename C::value_type(beg, s.end())); output.swap(ret); } // Server function. //void InitStage( extern "C" __declspec(dllexport) int macroMain() { b_shutdown = false; b_abort = false; initKeithley(); //HANDLE hThread = (HANDLE)_beginthread( &CheckKey, 0, 0 ); //HANDLE hThread = (HANDLE)_beginthreadex(0, 0, &CheckKey, 0, 0, 0); LITHO_BEGIN; //std::cout << "1 StageGetPosition X: " << StageGetPosition(0) <<std::endl; //X //std::cout << "1 StageGetPosition Y: " << StageGetPosition(1) <<std::endl; //Y //std::cout << "1 StageGetPosition Z: " << StageGetPosition(2) <<std::endl; //Z //return 0; if (1) { LithoDisplayStatusBox(); bool stat = IsEngaged(); if (stat == 1) { LithoScan(FALSE); } LithoCenterXY(); //LithoPause(0.00000000001); int ret = 0; ret = initWinsock(); std::cout << "INIT: " << ret <<std::endl; if (ret == 0) { //printf("16...\n"); //startWinsock(); ret = connectWinsock(); if (ret == 0) { printf("1...\n"); ret = 0; while (running) { if (b_shutdown == true) { printf("22...\n"); break; } printf("2...\n"); if (ret == 1) { connectWinsock(); printf("3...\n"); //running = false; //break; } printf("4...\n"); ret = readWinsock(); printf("5...\n"); if (ret == 2) { printf("6...\n"); running = false; break; } if (ret == 1) { printf("14...\n"); //running = false; //break; } printf("7...\n"); } } closeWinsock(); } printf("8...\n"); } printf("9...\n"); LITHO_END; //CloseHandle(hThread); printf("10...\n"); std::cout << std::endl << "END" << std::endl<< std::endl; //KeithSetVoltage( float(0.0) ); KeithClose(); return 0; } void ParseScript() { printf("\nParsing Script...\n"); writeWinsock("\nParsing Script...\n"); printf("\n\n"); std::istringstream line(scriptbuf); //make a stream for the line itself std::string str; while (std::getline(line,str)) { if (b_abort == true) { printf("21...\n"); b_abort = false; writeWinsock("ABORT"); break; return; } //std::vector<std::string> cmd = split(str, '\t'); char const* delims = " \t"; vector<std::string> cmd; split(str, delims, cmd); /* std::cout << str <<":"<<std::endl; std::cout << cmd.size() <<":"<<std::endl;*/ //std::string cmd; writeWinsock(str); if (cmd.size() == 0) { continue; } //std::cout << cmd[0] <<":"<<std::endl; // LithoPause(0.00000000001); if (cmd[0] == "xyAbs") { double x, y, r; x = stod(cmd[1]); y = stod(cmd[2]); r = stod(cmd[3]); //line >> x >> y >> rate; //now read the whitespace-separated floats //std::cout << " moving to x: " << x <<" y: " <<y <<std::endl; LithoTranslateAbsolute(x,y,r); //std::cout << cmd << ":" << x << " " << y << " " << rate << std::endl; } else if (cmd[0] == "xy") { double x, y, rate; x = stod(cmd[1]); y = stod(cmd[2]); rate = stod(cmd[3]); //line >> x >> y >> rate; //now read the whitespace-separated floats // std::cout << " moving to x: " << x <<" y: " <<y <<std::endl; LithoTranslate(x,y,rate); // std::cout << cmd << ":" << x << " " << y << " " << rate << std::endl; } //else if (cmd[0] == "vtip_swp") //{ // double vtip; // vtip = stod(cmd[1]); // //line >> vtip; //now read the whitespace-separated floats // KeithSweepVoltage(vtip,30); // //LithoSet(lsAna2, vtip); //} else if (cmd[0] == "vtip") { float vtip; vtip = stof(cmd[1]); //line >> vtip; //now read the whitespace-separated floats //KeithSetVoltage(vtip); KeithSweepVoltage(vtip,30); //LithoSet(lsAna2, vtip); } else if (cmd[0] == "trigger") { std::string chan; chan = cmd[1]; //line >> chan; //now read the whitespace-separated floats std::cout << cmd[0] << ":" << chan << std::endl; } else if (cmd[0] == "pulse") { std::string chan, value, time; chan = cmd[1]; value = cmd[2]; time = cmd[3]; //line >> chan >> value >> time; //now read the whitespace-separated floats std::cout << cmd[0] << ":" << chan << value << time << std::endl; } else if (cmd[0] == "signal") { std::string chan, value; chan = cmd[1]; value = cmd[2]; //line >> chan >> value; //now read the whitespace-separated floats std::cout << cmd[0] << ":" << chan << value << std::endl; } else if (cmd[0] == "setpoint") { double value; value = stod(cmd[1]); //line >> value; //now read the whitespace-separated floats LithoSet(lsSetpoint, value); std::cout << cmd[0] << ":" << "Setpoint " << value << std::endl; } else if (cmd[0] == "udp") { /*std::string send; std::getline(line, send);*/ std::cout << cmd[0] << ":" << str << std::endl; } else if (cmd[0] == "getxy") { double posX = LithoGetXPosUM(); double posY = LithoGetYPosUM(); std::cout << cmd[0] << " x: " << posX << " y: " << posY << std::endl; } else if (cmd[0] == "pause") { float value; value = stof(cmd[1]); //line >> value; std::cout << cmd[0] << " " << value << "s" << std::endl; //Sleep(value); LithoPause(value); } else if (cmd[0] == "wait") { // Here we need to wait for the scan to finish } else if (cmd[0] == "center") { LithoCenterXY(); double posX = LithoGetXPosUM(); double posY = LithoGetYPosUM(); std::cout << cmd[0] << " x: " << posX << " y: " << posY << std::endl; } else if (cmd[0] == "SketchScript") { //continue; } else if (cmd[0] == "#") { if (readAbort() != 0) { writeWinsock("ABORT"); return; } } else { if (str.empty()) { // empty line } else { std::cout << "unknown " << cmd[0] << ":" << str << std::endl; } } } writeWinsock("Ready"); }
2b877638750eb87ca46f4ca03faff01ae5eadb1c
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case30/Case/case2/900/T
53fa4db8a4b032ed0007fcf958f4bd571a750134
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
7,213
T
// -*- C++ -*- // File generated by PyFoam - sorry for the ugliness FoamFile { version 2.0; format ascii; class volScalarField; location "900"; object T; } dimensions [ 0 0 0 1 0 0 0 ]; internalField nonuniform List<scalar> 459 ( 303.564 303.306 303.293 303.289 303.285 303.281 303.277 303.271 303.263 303.252 303.24 303.228 303.22 303.216 303.218 303.308 303.287 303.279 303.281 303.285 303.289 303.293 303.296 303.3 303.304 303.307 303.311 303.315 303.318 303.322 303.326 303.33 303.336 303.354 303.739 303.349 303.325 303.328 303.331 303.332 303.329 303.323 303.308 303.286 303.26 303.236 303.217 303.206 303.201 303.199 303.197 303.308 303.271 303.265 303.268 303.272 303.276 303.278 303.28 303.282 303.283 303.284 303.285 303.287 303.289 303.291 303.295 303.301 303.31 303.339 303.921 303.4 303.361 303.371 303.385 303.395 303.4 303.395 303.373 303.334 303.289 303.249 303.219 303.202 303.197 303.197 303.198 303.251 303.25 303.257 303.266 303.276 303.283 303.283 303.283 303.284 303.284 303.284 303.284 303.285 303.285 303.286 303.289 303.293 303.301 303.332 304.104 303.462 303.397 303.413 303.441 303.467 303.486 303.484 303.45 303.389 303.319 303.26 303.218 303.197 303.192 303.195 303.201 303.212 303.225 303.243 303.262 303.28 303.296 303.308 303.318 303.326 303.334 303.341 303.347 303.352 303.355 303.358 303.359 303.336 303.317 303.308 303.331 304.283 303.541 303.439 303.45 303.488 303.532 303.572 303.571 303.519 303.43 303.336 303.261 303.211 303.188 303.185 303.194 303.208 303.225 303.245 303.269 303.292 303.314 303.332 303.347 303.36 303.371 303.38 303.387 303.392 303.394 303.393 303.39 303.383 303.365 303.34 303.32 303.329 303.4 303.447 303.453 304.444 303.644 303.512 303.501 303.537 303.593 303.644 303.625 303.548 303.439 303.33 303.244 303.192 303.171 303.176 303.196 303.221 303.249 303.278 303.307 303.334 303.357 303.376 303.391 303.403 303.413 303.42 303.426 303.429 303.428 303.423 303.415 303.405 303.387 303.362 303.338 303.332 303.363 303.38 303.414 304.592 303.807 303.675 303.646 303.662 303.709 303.714 303.647 303.528 303.394 303.274 303.191 303.15 303.147 303.17 303.207 303.249 303.289 303.326 303.358 303.385 303.406 303.422 303.434 303.444 303.451 303.456 303.459 303.459 303.456 303.448 303.437 303.424 303.406 303.383 303.36 303.347 303.355 303.365 303.394 304.806 304.219 304.074 303.987 303.945 303.887 303.763 303.59 303.407 303.251 303.144 303.092 303.091 303.125 303.179 303.243 303.301 303.349 303.387 303.415 303.436 303.452 303.464 303.472 303.479 303.483 303.485 303.485 303.483 303.479 303.471 303.459 303.446 303.43 303.413 303.396 303.389 303.401 303.419 303.541 305.113 304.836 304.58 304.345 304.117 303.823 303.494 303.214 303.025 302.933 302.921 302.969 303.053 303.145 303.235 303.322 303.38 303.418 303.445 303.465 303.48 303.49 303.498 303.503 303.506 303.508 303.507 303.506 303.504 303.501 303.499 303.499 303.5 303.506 303.519 303.541 303.572 303.604 303.625 303.677 296.358 298.241 299.445 300.277 300.984 301.586 302.078 302.46 302.75 302.98 303.174 303.288 303.364 303.418 303.453 303.476 303.493 303.505 303.514 303.52 303.524 303.526 303.528 303.529 303.53 303.53 303.53 303.531 303.533 303.534 303.538 303.546 303.559 303.577 303.6 303.622 303.641 303.662 297.01 298.85 300.287 301.251 301.862 302.312 302.656 302.913 303.101 303.235 303.336 303.404 303.449 303.48 303.501 303.515 303.525 303.532 303.536 303.54 303.542 303.544 303.546 303.547 303.548 303.549 303.55 303.551 303.552 303.554 303.557 303.563 303.572 303.584 303.599 303.617 303.615 303.644 299.716 299.638 299.633 301.466 302.278 302.667 302.896 303.065 303.194 303.292 303.365 303.419 303.459 303.486 303.503 303.515 303.523 303.528 303.532 303.535 303.537 303.539 303.541 303.543 303.545 303.547 303.549 303.551 303.553 303.555 303.557 303.559 303.562 303.566 303.571 303.581 303.589 303.595 303.597 303.636 ) ; boundaryField { floor { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 29 ( 303.41 303.666 303.603 303.572 303.575 303.586 303.599 303.616 303.634 303.652 303.67 303.687 303.704 303.719 303.735 303.75 303.765 303.782 303.797 303.837 303.837 303.754 303.712 303.688 303.41 303.666 303.648 303.465 303.378 ) ; } ceiling { type wallHeatTransfer; Tinf uniform 303.2; alphaWall uniform 0.24; value nonuniform List<scalar> 43 ( 299.964 299.88 299.868 301.574 302.337 302.703 302.917 303.074 303.194 303.285 303.351 303.399 303.432 303.453 303.466 303.473 303.478 303.481 303.483 303.484 303.485 303.487 303.488 303.49 303.492 303.495 303.497 303.5 303.503 303.507 303.51 303.514 303.519 303.524 303.53 303.541 303.55 303.554 303.554 303.586 305.024 304.771 297.41 ) ; } sWall { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 0.36; value uniform 301.314; } nWall { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 0.36; value nonuniform List<scalar> 6 ( 304.157 304.105 304.029 304.174 304.152 304.215 ) ; } sideWalls { type empty; } glass1 { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 4.3; value nonuniform List<scalar> 9 ( 311.519 310.889 310.491 310.188 309.936 309.707 309.539 309.611 309.836 ) ; } glass2 { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 4.3; value nonuniform List<scalar> 2 ( 305.818 305.912 ) ; } sun { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 14 ( 303.737 303.493 303.478 303.469 303.459 303.451 303.442 303.433 303.422 303.411 303.4 303.393 303.392 303.397 ) ; } heatsource1 { type fixedGradient; gradient uniform 0; } heatsource2 { type fixedGradient; gradient uniform 0; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type fixedValue; value uniform 293.15; } outlet { type zeroGradient; } } // ************************************************************************* //
14e578f0f823153ae7ee11826b0fa119e427f939
462e7038f4676cad610a191bc3fc3f571897544d
/src/image_recognition/src/image_recognition_node.cpp
bea7bc17e51c9c99317a1685439ebd03a15862ff
[ "Apache-2.0" ]
permissive
ShengruiLYU/ELEC-4010K
2bc44cb187d1c0455de42bd5105c2a31508b738d
ba91a8a43869489f276e593f7d5f0b46b14679e1
refs/heads/master
2021-09-27T23:58:31.196336
2018-11-12T15:06:36
2018-11-12T15:06:36
157,228,098
0
0
null
null
null
null
UTF-8
C++
false
false
7,818
cpp
image_recognition_node.cpp
#include <ros/ros.h> #include <ros/console.h> #include <std_msgs/Bool.h> #include <sensor_msgs/Image.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Pose.h> #include <visualization_msgs/Marker.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <math.h> #include <cmath> using namespace cv; ros::Publisher pub_cmd; char* image_window = "Source Image"; char* result_window = "Result window"; int match_method = CV_TM_SQDIFF ; int max_Trackbar = 5; double th1 = 1.5e08; double th2 = 2.1e08; double th3 = 1e08; double th4 = 1.2e08; double th5 = 2e08; Mat templ1_1st; Mat templ1_2nd; Mat templ1_3rd; Mat templ2_1st; Mat templ2_2nd; Mat templ2_3rd; Mat templ3_1st; Mat templ3_2nd; Mat templ3_3rd; Mat templ4_1st; Mat templ4_2nd; Mat templ4_3rd; Mat templ5_1st; Mat templ5_2nd; Mat templ5_3rd; bool dis = false; Point matchLoc; Mat templ; Mat result; void MatchingMethod(Mat img, Mat templ1, Mat templ2, Mat templ3, int type) { /// Source image to display Mat img_display; img.copyTo( img_display ); /// Create the result matrix int result_cols = img.cols - templ1.cols + 1; int result_rows = img.rows - templ1.rows + 1; Mat result1; result1.create( result_rows, result_cols, CV_32FC1 ); matchTemplate( img, templ1, result1, match_method ); double minVal1=10; double maxVal1=-10; Point minLoc1; Point maxLoc1; minMaxLoc( result1, &minVal1, &maxVal1, &minLoc1, &maxLoc1, Mat() ); Mat result2; result1.create( result_rows, result_cols, CV_32FC1 ); matchTemplate( img, templ2, result2, match_method ); double minVal2=10; double maxVal2=-10; Point minLoc2; Point maxLoc2; minMaxLoc( result2, &minVal2, &maxVal2, &minLoc2, &maxLoc2, Mat() ); Mat result3; result3.create( result_rows, result_cols, CV_32FC1 ); matchTemplate( img, templ3, result3, match_method ); double minVal3=10; double maxVal3=-10; Point minLoc3; Point maxLoc3; minMaxLoc( result3, &minVal3, &maxVal3, &minLoc3, &maxLoc3, Mat() ); double minVal; if (minVal2<minVal1&&minVal2<minVal3){ minVal = minVal2; matchLoc = minLoc2; templ = templ2; result = result2; } else if (minVal3<minVal1&&minVal3<minVal2){ minVal = minVal3; matchLoc = minLoc3; templ = templ3; result = result3; } else{ minVal = minVal1; matchLoc = minLoc1; templ = templ1; result = result1; } std::cout<<"type"<<type<<"Min "<<minVal<<std::endl; dis = false; switch(type){ case 1: dis=minVal < th1; break; case 2: dis=minVal < th2; break; case 3: dis=minVal < th3; break; case 4: dis=minVal < th4; break; case 5: dis=minVal < th5; break; } if(dis){ rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 ); rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 ); double real_edge = 512/(templ.cols); double tan225 = 0.4142135624; double distance = real_edge/(2*tan225); double position = (512/2 - (matchLoc.x+ (templ.cols/2)))/(templ.cols); visualization_msgs::Marker marker; marker.header.frame_id = "camera_link"; marker.header.stamp = ros::Time(); marker.ns = "my_namespace"; marker.id = 0; marker.type = visualization_msgs::Marker::SPHERE; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = -(position); marker.pose.position.y = 0.0; marker.pose.position.z = distance; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.x = 1; marker.scale.y = 0.1; marker.scale.z = 0.1; marker.color.a = 1.0; marker.color.r = 0.0; marker.color.g = 1.0; marker.color.b = 0.0; pub_cmd.publish(marker); } imshow( image_window, img_display ); // imshow( result_window, result ); waitKey(10); return; } void img_callback(const sensor_msgs::ImageConstPtr &img_msg) { cv_bridge::CvImagePtr bridge_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGR8); Mat img = bridge_ptr->image; if(img.empty()) { ROS_INFO("Didn't get the cv_bridge image"); std::cout<<"didn't received cv_bridge image"<<std::endl; } MatchingMethod(img,templ1_1st,templ1_2nd,templ1_3rd,1); cv::waitKey(10); MatchingMethod(img,templ2_1st,templ2_2nd,templ2_3rd,2); cv::waitKey(10); MatchingMethod(img,templ3_1st,templ3_2nd,templ3_3rd,3); cv::waitKey(10); MatchingMethod(img,templ4_1st,templ4_2nd,templ4_3rd,4); cv::waitKey(10); MatchingMethod(img,templ5_1st,templ5_2nd,templ5_3rd,5); cv::waitKey(10); } int main(int argc, char **argv) { ros::init(argc, argv, "image_recognition"); ros::NodeHandle n("~"); pub_cmd = n.advertise<visualization_msgs::Marker>("image_reconition_result",0); // to be modified Mat original_templ1 = imread ("/home/shengrui/catkin_ws/src/picture_sample/pic001.jpg"); Mat original_templ2 = imread ("/home/shengrui/catkin_ws/src/picture_sample/pic002.jpg"); Mat original_templ3 = imread ("/home/shengrui/catkin_ws/src/picture_sample/pic003.jpg"); flip(original_templ3, original_templ3, 1); Mat original_templ4 = imread ("/home/shengrui/catkin_ws/src/picture_sample/pic004.jpg"); Mat original_templ5 = imread ("/home/shengrui/catkin_ws/src/picture_sample/pic005.jpg"); flip(original_templ5, original_templ5, 1); // put templ_2nd as global variable, becuase we cannot pass it to call_back function resize(original_templ1,templ1_1st,Size(250,250),0,0); resize(original_templ1, templ1_2nd, Size(120,120), 0, 0); namedWindow( "templ1_2nd", CV_WINDOW_AUTOSIZE ); imshow("templ1_2nd",templ1_2nd); resize(original_templ1, templ1_3rd, Size(150,150), 0, 0); namedWindow( "templ1_3rd", CV_WINDOW_AUTOSIZE ); imshow("templ1_3rd",templ1_3rd); resize(original_templ2,templ2_1st,Size(250,250),0,0); resize(original_templ2, templ2_2nd, Size(120,120), 0, 0); namedWindow( "templ2_2nd", CV_WINDOW_AUTOSIZE ); imshow("templ2_2nd",templ2_2nd); resize(original_templ2, templ2_3rd, Size(150,150), 0, 0); namedWindow( "templ2_3rd", CV_WINDOW_AUTOSIZE ); imshow("templ2_3rd",templ2_3rd); resize(original_templ3,templ3_1st,Size(250,250),0,0); resize(original_templ3, templ3_2nd, Size(120,120), 0, 0); namedWindow( "templ3_2nd", CV_WINDOW_AUTOSIZE ); imshow("templ3_2nd",templ3_2nd); resize(original_templ3, templ3_3rd, Size(150,150), 0, 0); namedWindow( "templ3_3rd", CV_WINDOW_AUTOSIZE ); imshow("templ3_3rd",templ3_3rd); resize(original_templ4,templ4_1st,Size(250,250),0,0); resize(original_templ4, templ4_2nd, Size(120,120), 0, 0); namedWindow( "templ4_2nd", CV_WINDOW_AUTOSIZE ); imshow("templ4_2nd",templ4_2nd); resize(original_templ4, templ4_3rd, Size(150,150), 0, 0); namedWindow( "templ4_3rd", CV_WINDOW_AUTOSIZE ); imshow("templ4_3rd",templ4_3rd); resize(original_templ5,templ5_1st,Size(250,250),0,0); resize(original_templ5, templ5_2nd, Size(120,120), 0, 0); namedWindow( "templ5_2nd", CV_WINDOW_AUTOSIZE ); imshow("templ5_2nd",templ5_2nd); resize(original_templ5, templ5_3rd, Size(150,150), 0, 0); namedWindow( "templ5_3rd", CV_WINDOW_AUTOSIZE ); imshow("templ5_3rd",templ5_3rd); namedWindow( image_window, CV_WINDOW_AUTOSIZE ); namedWindow( result_window, CV_WINDOW_AUTOSIZE ); ros::Subscriber sub = n.subscribe("/flipped_image", 100, img_callback); ros::spin(); }
e16291300600a79cb471623c9c189f86c234366e
c18011a46125386c53aa8173a26a6dd49bad2cce
/Classe_GUI/logsystem.cpp
d0eb5d1a57553c1e17e39dfa3ddd801b14a024bf
[]
no_license
lfgLO21/projet-LO21
81ab685eb258ff06e47cd634a3ed2f71da8614ca
cce1a9f74c588a1a6fafe7f6cb72175a9a11102b
refs/heads/master
2021-01-19T03:21:52.153513
2012-06-18T13:26:52
2012-06-18T13:26:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
logsystem.cpp
#include "logsystem.h" /*! *\fn void LogSystem::printLog(LogMessage) *\brief Methode de creation d'un nouveau message de LogSystem decrivant une action efectuee par une procedure */ LogMessage::LogMessage(const std::string& s,unsigned int i) { this->_log = QString(s.c_str()); this->_degree = i; this->_time = QDateTime::currentDateTime(); } /*! *\fn void LogSystem::printLog(LogMessage) *\brief Methode d'affichage d'un LogMessage dans un format lisible, comprenant le moment ou est apparu le LogSystem, son intitule et son niveau */ QString LogMessage::getLog()const { std::stringstream ss; ss<<" : ["; ss<<this->_degree; ss<<"]"; return QString(this->_time.toString("dd/MM/yyyy - hh:mm:ss")+ss.str().c_str()+this->_log); } /*! *\fn void LogSystem::printLog(LogMessage) *\brief Methode d'ecriture du LogSystem dans un fichier recapitulatif lisible hors fonctionnement */ void LogSystem::printLog(const LogMessage& l) { cerr<<l.getLog().toStdString()<<endl; QFile file("stderr.pony"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream flux(&file); flux.setCodec("UTF-8"); flux << l.getLog().toStdString().c_str() << endl; }
89414857fb7d874f348099cda1265123b54225df
6d48eecfac0f8983b0ec9b3d130430d1057eccba
/Lab1.cpp
9553a71deb8f385fd6a60e03e6ac65a8af225723
[]
no_license
Hieracon/APD
c4f7fb474b1ddd9f61cca923cca2a4f401c4a84b
39789496f4ee981c75bab8697648015de6f920d6
refs/heads/master
2021-02-18T12:37:04.223293
2020-03-10T15:19:16
2020-03-10T15:19:16
245,195,568
0
0
null
null
null
null
UTF-8
C++
false
false
4,302
cpp
Lab1.cpp
#include <mpi.h> #include <stdio.h> #include <time.h> #include <stdlib.h> // -----------------------------Prime Numbers------------------- /* bool isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } int main(int argc, char** argv) { MPI_Init(NULL, NULL); int size; int rank; int nrElements; int start; int N = 13; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { if (size >= 2) { nrElements = N / (size - 1); } else { printf("no se pueda"); return 0; } for (int it = 1; it < size; ++it) { start = (it - 1) * nrElements; MPI_Send(&start, 1, MPI_INT, it, 1, MPI_COMM_WORLD); MPI_Send(&nrElements, 1, MPI_INT, it, 2, MPI_COMM_WORLD); } } else { MPI_Recv(&start, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&nrElements, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (rank == (size - 1)) { nrElements = N; } else { nrElements = nrElements + start; } for (int it = start + 1; it <= nrElements; ++it) { if (isPrime(it)) { printf("Process %i found the prime number %i.\n", rank, it); } } } MPI_Finalize(); } */ // -----------------------------Prime Numbers------------------- // ------------ARRAY SEARCH-------------------------------------- /* int main(int argc, char** argv) { MPI_Init(NULL, NULL); int size; int rank; int nrElements; int start; int notArray[] = {3,3,4,7,9,0,1,3,22,33,13,3}; int searchedNumber = 3; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { if (size >= 2) { nrElements = (sizeof(notArray) / sizeof(notArray[0]))/ (size - 1); } else { printf("no se pueda"); return 0; } for (int it = 1; it < size; ++it) { start = (it - 1) * nrElements; MPI_Send(&start, 1, MPI_INT, it, 1, MPI_COMM_WORLD); MPI_Send(&nrElements, 1, MPI_INT, it, 2, MPI_COMM_WORLD); } } else { MPI_Recv(&start, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&nrElements, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (rank == (size - 1)) { nrElements = (sizeof(notArray) / sizeof(notArray[0])); } else { nrElements = nrElements + start; } for (int it = start; it < nrElements; ++it) { if ((notArray[it] == searchedNumber)) { printf("Process %i found the number at position %i.\n", rank, it); } } } MPI_Finalize(); } */ // ------------ARRAY SEARCH-------------------------------------- // ------------Random Numbers-------------------------------------- int main(int argc, char** argv) { MPI_Init(NULL, NULL); int size; int rank; int nrElements; int randomNumbers; int randomNr; int sumProc = 0; int sum = 0; time_t start, end; double time_taken; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); srand((unsigned)time(NULL)); if (rank == 0) { //start = clock(); time(&start); for (int it = 1; it < size; ++it) { randomNumbers = rand() % 900 + 100; MPI_Send(&randomNumbers, 1, MPI_INT, it, 1, MPI_COMM_WORLD); MPI_Recv(&sumProc, 1, MPI_INT, it, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); sum = sum + sumProc; } printf("Final sum is : %i.\n", sum); //end = clock(); time(&end); time_taken = double(end - start); printf("Process %i took %f seconds", rank, time_taken); } else { //start = clock(); time(&start); MPI_Recv(&randomNumbers, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for (int it = 0; it < randomNumbers; ++it) { randomNr = rand() % 10 + 1; //printf("Process %i generated the number %i.\n", rank, randomNr); sumProc = sumProc + randomNr; } MPI_Send(&sumProc, 1, MPI_INT, 0, 2, MPI_COMM_WORLD); //end = clock(); time(&end); time_taken = double(end - start); printf("Process %i took %f seconds", rank, time_taken); } MPI_Finalize(); } // ------------Random Numbers--------------------------------------
fc586af827feada6713e50fa4a8844df2fb17f0c
04e11bec5bc79ea397e74780f32aa41dea88f54b
/src/AlleleRecords.h
d12e3adebc2832d6495b62b82cf02e3fb440f1f0
[]
no_license
grenaud/dice
94af0fdc34150dea8a80e948d48d54fd96a110c6
1fe23b343c645a0abe24ac73c654bfee4291a262
refs/heads/master
2021-01-24T22:44:06.145810
2020-12-03T15:34:04
2020-12-03T15:34:04
29,676,122
1
3
null
null
null
null
UTF-8
C++
false
false
1,181
h
AlleleRecords.h
/* * AlleleRecords * Date: Mar-28-2013 * Author : Gabriel Renaud gabriel.reno [at sign here] gmail.com * */ #ifndef AlleleRecords_h #define AlleleRecords_h #include <string> #include <vector> #include "SingleAllele.h" using namespace std; class AlleleRecords{ private: public: AlleleRecords(); AlleleRecords(const AlleleRecords & other); ~AlleleRecords(); AlleleRecords & operator= (const AlleleRecords & other){ chr = other.chr; coordinate = other.coordinate; ref = other.ref; alt = other.alt; vectorAlleles = new vector<SingleAllele> ( *(other.vectorAlleles) ); return *this; } string chr; unsigned int coordinate; char ref; char alt; vector<SingleAllele> * vectorAlleles; bool everyRecordNonNull() const; bool everyNonChimpAncRecordNonNull() const; friend ostream& operator<<(ostream& os, const AlleleRecords & ar){ os<<ar.chr<<"\t"; os<<stringify(ar.coordinate)<<"\t"; os<<ar.ref<<","; os<<ar.alt<<"\t"; os<<vectorToString(*(ar.vectorAlleles),"\t"); return os; } friend bool operator== (const AlleleRecords & first,const AlleleRecords & second); }; #endif
25578ec841a1f062a6e56d35b1e113c99015dddd
7af5412a85f6675e4a378f033978db11fa683f94
/剑指offer/对称的二叉树.cpp
23d6c557d22e809d1377489c0e6ac63251559a93
[]
no_license
Catnip0709/CodeStudy
82ea6e03b3e6ec9b77eca2fadf676cb9c7e3f64c
f259c566c8b8e7b46e8620557b3e7667a8f1ca59
refs/heads/master
2020-12-11T01:13:05.904773
2020-04-02T04:16:27
2020-04-02T04:16:27
233,762,279
1
0
null
null
null
null
UTF-8
C++
false
false
1,031
cpp
对称的二叉树.cpp
/* Author: Catnip Date: 2020/02/18 From: 剑指offer Link: https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb?tpId=13&tqId=11211&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking */ /* Q 请实现一个函数,用来判断一颗二叉树是不是对称的。 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 */ /* A 递归判断 */ #include<iostream> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool symmetrical(TreeNode* left, TreeNode* right) { if (left == NULL && right == NULL) return true; if ((left == NULL && right != NULL) || (left != NULL && right == NULL)) return false; if (left->val != right->val) return false; return symmetrical(left->left, right->right) && symmetrical(left->right, right->left); } bool isSymmetrical(TreeNode* pRoot) { if (pRoot == NULL) return true; return symmetrical(pRoot->left, pRoot->right); }
d26cb92b0f5b7527685ac92242d9c7883c1083a2
f9c4b251e5de9d2b4179ad418c6b826ca2bf56e3
/PAT/PAT-Basic/B-1003.cpp
73eb568628b0c52e42bf67cfdcba19ce8430d038
[]
no_license
MatthewLQM/AlgorithmCode
d82f3b634b7e03ba3a47d1d1e3daae9121db9b81
150438a2ed38193890bb82522bb8d5158d875fd4
refs/heads/master
2020-04-05T13:36:57.897589
2018-01-31T10:35:48
2018-01-31T10:35:48
94,917,818
0
0
null
2017-09-25T03:27:03
2017-06-20T17:30:37
C++
UTF-8
C++
false
false
670
cpp
B-1003.cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> using namespace std; int main(void){ int n, flag; char x; int a[3] = {0}; cin >> n; getchar(); for(int i = 0; i < n; i++){ flag = 0; a[0] = a[1] = a[2] = 0; while((x = getchar())!='\n'){ if(x != 'P' && x != 'A' && x != 'T'){ flag = -1; } else if(x == 'A' && flag != -1){ a[flag]++; } else if(x == 'P' && flag == 0){ flag++; } else if(x == 'T' && flag == 1){ flag++; } else { flag = -1; } } if(flag == 2 && a[0] * a[1] == a[2] && a[1] != 0)cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
40c739211e3c5d24d7b245b274ff322e883d8454
4f0d99949fcb2429e1ead9f07ea16d28878e7add
/include/views/UserView.h
8202b6b956073a9a30d780bf43efdd7ae93ec571
[]
no_license
bmclachlin1/IssueTracker
323fc84996065c73dc4e940f88f69920b515acd3
710d8d5d4dd042b9a3cda4ed67c675685053c3c7
refs/heads/master
2023-01-31T08:36:44.747862
2020-12-10T23:23:56
2020-12-10T23:23:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,450
h
UserView.h
#ifndef USERVIEW_H #define USERVIEW_H #include <string> #include "BaseView.h" enum class UserViewState { CreateUser = 1, SelectUser, GoBack }; enum class ManageUserState { Update = 1, Delete, GoBack }; /** * @class UserView * @brief Handles user input relating to users */ class UserView : public BaseView { public: UserView() {} virtual ~UserView() {} /** * Displays a menu of choices for the user to pick from * @returns the integer representing their choice */ UserViewState MainMenu(); /** * Prompts the user for information to create a new user * @return the user's inputted values */ void CreateUserView(); /** * Prompts the user for information to update a user * @return the user's input */ void UpdateUserView(const User& user); /** * Prompts the user for the information required to delete a User from the * system * @return std::string the user's input */ void DeleteUserView(const User& user); /** * Displays a list of users to select from * @returns the user selected */ User SelectUserView(); /** * Displays a menu for the user to decide to Update or Delete a user */ ManageUserState ManageUserMenu(); inline void RunUserView(UserViewState choice) { bool quit = false; while (!quit) { switch (choice) { case UserViewState::CreateUser: CreateUserView(); break; case UserViewState::SelectUser: { User selectedUser = SelectUserView(); // If they decided to cancel, go back if (selectedUser.id.empty()) break; ManageUserState nextMenu = ManageUserMenu(); switch (nextMenu) { default: break; case ManageUserState::Update: UpdateUserView(selectedUser); break; case ManageUserState::Delete: DeleteUserView(selectedUser); break; } } break; default: quit = true; break; } if (!quit) choice = MainMenu(); } } /** * Displays the user information in a nice format */ static void DisplayUser(const User& user); /** * @param prompt the prompt shown to the user * @param serverUri the uri to the server * @returns the userId based on the provided User's name */ static std::string GetUserIdFromName(const std::string& prompt); }; #endif // USERVIEW_H
3875bb769895e04eca595b7fdb13f3310735ac74
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/game/shared/library/swgSharedNetworkMessages/src/shared/core/SetupSwgSharedNetworkMessages.cpp
fb9785c078a669c48eb08b90c11a895440cd1045
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
29,933
cpp
SetupSwgSharedNetworkMessages.cpp
// ====================================================================== // // SetupSwgSharedNetworkMessages.cpp // copyright 1998 Bootprint Entertainment // copyright 2001 Sony Online Entertainment // // ====================================================================== #include "swgSharedNetworkMessages/FirstSwgSharedNetworkMessages.h" #include "swgSharedNetworkMessages/SetupSwgSharedNetworkMessages.h" #include "StringId.h" #include "localizationArchive/StringIdArchive.h" #include "sharedFoundation/ExitChain.h" #include "sharedFoundation/GameControllerMessage.h" #include "sharedGame/MatchMakingCharacterResult.h" #include "sharedGame/ProsePackage.h" #include "sharedGame/ProsePackageArchive.h" #include "sharedMath/Sphere.h" #include "sharedMathArchive/SphereArchive.h" #include "sharedMathArchive/VectorArchive.h" #include "sharedNetworkMessages/ControllerMessageFactory.h" #include "sharedNetworkMessages/MessageQueueCommandTimer.h" #include "sharedNetworkMessages/MessageQueueGenericValueType.h" #include "sharedUtility/StartingLocationData.h" #include "sharedUtility/StartingLocationDataArchive.h" #include "swgSharedNetworkMessages/MessageQueueCombatAction.h" #include "swgSharedNetworkMessages/MessageQueueCombatDamage.h" #include "swgSharedUtility/Behaviors.def" #include "swgSharedUtility/Locomotions.def" #include "swgSharedUtility/MentalStates.def" // ---------------------------------------------------------------------- namespace SetupSwgSharedNetworkMessagesNamespace { static bool g_installed = false; void packAttributeMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<Attributes::Enumerator, Attributes::Value> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<Attributes::Enumerator, Attributes::Value> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackAttributeMessage(Archive::ReadIterator & source) { std::pair<Attributes::Enumerator, Attributes::Value> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<Attributes::Enumerator, Attributes::Value> > * result = new MessageQueueGenericValueType<std::pair<Attributes::Enumerator, Attributes::Value> >(v); return result; } void packMentalStatesMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, MentalStates::Value> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, MentalStates::Value> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackMentalStatesMessage(Archive::ReadIterator & source) { std::pair<MentalStates::Enumerator, MentalStates::Value> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, MentalStates::Value> > * result = new MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, MentalStates::Value> >(v); return result; } void packMentalStatesTowardsMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, MentalStates::Value> > > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, MentalStates::Value> > > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackMentalStatesTowardsMessage(Archive::ReadIterator & source) { std::pair<NetworkId, std::pair<MentalStates::Enumerator, MentalStates::Value> > v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, MentalStates::Value> > > * result = new MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, MentalStates::Value> > >(v); return result; } void packIntMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<int> * const msg = dynamic_cast<const MessageQueueGenericValueType<int> *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackIntMessage(Archive::ReadIterator & source) { int v; Archive::get(source, v); MessageQueueGenericValueType<int> * result = new MessageQueueGenericValueType<int>(v); return result; } void packUint32PairMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<uint32, uint32> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<uint32, uint32> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackUint32PairMessage(Archive::ReadIterator & source) { std::pair<uint32, uint32> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<uint32, uint32> > * result = new MessageQueueGenericValueType<std::pair<uint32, uint32> >(v); return result; } void packBoolMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<bool> * const msg = dynamic_cast<const MessageQueueGenericValueType<bool> *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackBoolMessage(Archive::ReadIterator & source) { bool v; Archive::get(source, v); MessageQueueGenericValueType<bool> * result = new MessageQueueGenericValueType<bool>(v); return result; } void packMentalStateTowardClampBehaviorMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, std::pair<MentalStates::Value, Behaviors::Enumerator> > > > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, std::pair<MentalStates::Value, Behaviors::Enumerator> > > > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackMentalStateTowardClampBehaviorMessage(Archive::ReadIterator & source) { std::pair<NetworkId, std::pair<MentalStates::Enumerator, std::pair<MentalStates::Value, Behaviors::Enumerator> > > v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, std::pair<MentalStates::Value, Behaviors::Enumerator> > > > * result = new MessageQueueGenericValueType<std::pair<NetworkId, std::pair<MentalStates::Enumerator, std::pair<MentalStates::Value, Behaviors::Enumerator> > > >(v); return result; } void packMentalStateDecayMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, float> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, float> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackMentalStateDecayMessage(Archive::ReadIterator & source) { std::pair<MentalStates::Enumerator, float> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, float> > * result = new MessageQueueGenericValueType<std::pair<MentalStates::Enumerator, float> >(v); return result; } void packLocomotionMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<Locomotions::Enumerator> * const msg = dynamic_cast<const MessageQueueGenericValueType<Locomotions::Enumerator> *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackLocomotionMessage(Archive::ReadIterator & source) { Locomotions::Enumerator v; Archive::get(source, v); MessageQueueGenericValueType<Locomotions::Enumerator> * result = new MessageQueueGenericValueType<Locomotions::Enumerator>(v); return result; } void packAddToPlayerSpawnQueueMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<NetworkId, unsigned long> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<NetworkId, unsigned long> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackAddToPlayerSpawnQueueMessage(Archive::ReadIterator & source) { std::pair<NetworkId, unsigned long> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<NetworkId, unsigned long> > * result = new MessageQueueGenericValueType<std::pair<NetworkId, unsigned long> >(v); return result; } void packNetworkIdMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<NetworkId> * const msg = dynamic_cast<const MessageQueueGenericValueType<NetworkId> *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackNetworkIdMessage(Archive::ReadIterator & source) { NetworkId v; Archive::get(source, v); MessageQueueGenericValueType<NetworkId> * result = new MessageQueueGenericValueType<NetworkId>(v); return result; } void packGenericStringIdMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<StringId> * const msg = safe_cast<const MessageQueueGenericValueType<StringId> *>(data); if (msg) Archive::put (target, msg->getValue ()); } MessageQueue::Data* unpackGenericStringIdMessage(Archive::ReadIterator & source) { StringId v; Archive::get(source, v); MessageQueueGenericValueType<StringId> * const result = new MessageQueueGenericValueType<StringId>(v); return result; } void packGenericStringVectorPairMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<std::string, Vector> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<std::string, Vector> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackGenericStringVectorPairMessage(Archive::ReadIterator & source) { std::pair<std::string, Vector> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<std::string, Vector> > * result = new MessageQueueGenericValueType<std::pair<std::string, Vector> >(v); return result; } void packGenericStringIdProsePackageMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<std::pair<StringId, ProsePackage>, Unicode::String> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) Archive::put (target, msg->getValue ()); } MessageQueue::Data* unpackGenericStringIdProsePackageMessage(Archive::ReadIterator & source) { typedef std::pair<std::pair<StringId, ProsePackage>, Unicode::String> Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; } void packNetworkIdUnicodeStringPairMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::pair<NetworkId, Unicode::String> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::pair<NetworkId, Unicode::String> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackNetworkIdUnicodeStringPairMessage(Archive::ReadIterator & source) { std::pair<NetworkId, Unicode::String> v; Archive::get(source, v); MessageQueueGenericValueType<std::pair<NetworkId, Unicode::String> > * result = new MessageQueueGenericValueType<std::pair<NetworkId, Unicode::String> >(v); return result; } void packGenericVectorOfUnicodeStrings(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::vector<Unicode::String> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::vector<Unicode::String> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackGenericVectorOfUnicodeStrings(Archive::ReadIterator & source) { std::vector<Unicode::String> v; Archive::get(source, v); MessageQueueGenericValueType<std::vector<Unicode::String> > * const result = new MessageQueueGenericValueType<std::vector<Unicode::String> >(v); return result; } //---------------------------------------------------------------------- void packCharacterMatchResultVectorMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<MatchMakingCharacterResult> * const msg = dynamic_cast<const MessageQueueGenericValueType<MatchMakingCharacterResult> *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackCharacterMatchResultVectorMessage(Archive::ReadIterator & source) { MatchMakingCharacterResult v; Archive::get(source, v); MessageQueueGenericValueType<MatchMakingCharacterResult> * result = new MessageQueueGenericValueType<MatchMakingCharacterResult>(v); return result; } //---------------------------------------------------------------------- void packStartingLocationSelectionResult(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<std::string, bool> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) Archive::put (target, msg->getValue ()); // packGenericMessage <Payload>(data, target); } MessageQueue::Data* unpackStartingLocationSelectionResult(Archive::ReadIterator & source) { typedef std::pair<std::string, bool> Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; } //---------------------------------------------------------------------- void packStartingLocations(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<StartingLocationData, bool> PayloadData; typedef std::vector<PayloadData> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) Archive::put (target, msg->getValue ()); } MessageQueue::Data* unpackStartingLocations(Archive::ReadIterator & source) { typedef std::pair<StartingLocationData, bool> PayloadData; typedef std::vector<PayloadData> Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; } //---------------------------------------------------------------------- void packStringNetworkIdPairVector(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<NetworkId, std::string> PayloadData; typedef std::vector<PayloadData> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) Archive::put (target, msg->getValue ()); } MessageQueue::Data* unpackStringNetworkIdPairVector(Archive::ReadIterator & source) { typedef std::pair<NetworkId, std::string> PayloadData; typedef std::vector<PayloadData> Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; } //---------------------------------------------------------------------- void packSphereVectorMessage(const MessageQueue::Data * data, Archive::ByteStream & target) { const MessageQueueGenericValueType<std::vector<Sphere> > * const msg = dynamic_cast<const MessageQueueGenericValueType<std::vector<Sphere> > *>(data); if(msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackSphereVectorMessage(Archive::ReadIterator & source) { std::vector<Sphere> v; Archive::get(source, v); MessageQueueGenericValueType<std::vector<Sphere> > * result = new MessageQueueGenericValueType<std::vector<Sphere> >(v); return result; } //---------------------------------------------------------------------- void packNetworkIdBoolPair(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<NetworkId, bool> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) { Archive::put (target, msg->getValue ()); } } MessageQueue::Data* unpackNetworkIdBoolPair(Archive::ReadIterator & source) { typedef std::pair<NetworkId, bool> Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; } //---------------------------------------------------------------------- void packNetworkIdNetworkIdVector(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::pair<NetworkId, std::vector<NetworkId> > Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) { Archive::put(target, msg->getValue().first); Archive::put(target, msg->getValue().second); } } MessageQueue::Data* unpackNetworkIdNetworkIdVector(Archive::ReadIterator & source) { typedef std::pair<NetworkId, std::vector<NetworkId> > Payload; Payload payload; Archive::get(source, payload.first); Archive::get(source, payload.second); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(payload); return result; } //---------------------------------------------------------------------- void packNetworkIdVector(const MessageQueue::Data * data, Archive::ByteStream & target) { typedef std::vector<NetworkId> Payload; const MessageQueueGenericValueType<Payload> * const msg = safe_cast<const MessageQueueGenericValueType<Payload> *>(data); if (msg) { Archive::put(target, msg->getValue()); } } MessageQueue::Data* unpackNetworkIdVector(Archive::ReadIterator & source) { typedef std::vector<NetworkId> Payload; Payload payload; Archive::get(source, payload); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(payload); return result; } //---------------------------------------------------------------------- void packNothing(const MessageQueue::Data *, Archive::ByteStream &) { } MessageQueue::Data* unpackNothing(Archive::ReadIterator &) { return NULL; } //---------------------------------------------------------------------- void packCommandTimerMessage( const MessageQueue::Data * data, Archive::ByteStream &target ) { /* typedef std::pair< byte, std::vector< float > > Payload; const MessageQueueGenericValueType< Payload > * const msg = safe_cast< const MessageQueueGenericValueType< Payload > * >( data ); if ( msg ) { Archive::put( target, msg->getValue() ); } */ const MessageQueueCommandTimer * msg = safe_cast< const MessageQueueCommandTimer * >( data ); if ( msg ) { uint32 flags = msg->getFlags(); Archive::put( target, (byte)flags ); Archive::put( target, msg->getSequenceId() ); Archive::put( target, msg->getCommandNameCrc() ); if ( flags & MessageQueueCommandTimer::toBitValue( MessageQueueCommandTimer::F_cooldown ) ) { Archive::put( target, msg->getCooldownGroup() ); } if ( flags & MessageQueueCommandTimer::toBitValue( MessageQueueCommandTimer::F_cooldown2 ) ) { Archive::put( target, msg->getCooldownGroup2() ); } for ( int i = 0; i < MessageQueueCommandTimer::F_MAX; ++i ) { MessageQueueCommandTimer::Flags flag = static_cast< MessageQueueCommandTimer::Flags >( i ); if ( flags & MessageQueueCommandTimer::toBitValue( flag ) ) { Archive::put( target, msg->getCurrentTime( flag ) ); Archive::put( target, msg->getMaxTime( flag ) ); } } } } MessageQueue::Data* unpackCommandTimerMessage(Archive::ReadIterator & source) { /* typedef std::pair< byte, std::vector< float > > Payload; Payload v; Archive::get(source, v); MessageQueueGenericValueType<Payload> * const result = new MessageQueueGenericValueType<Payload>(v); return result; */ byte flags; Archive::get( source, flags ); uint32 sequenceId; Archive::get( source, sequenceId ); uint32 commandNameCrc; Archive::get( source, commandNameCrc ); int cooldownGroup = NULL_COOLDOWN_GROUP; if ( flags & MessageQueueCommandTimer::toBitValue( MessageQueueCommandTimer::F_cooldown ) ) { Archive::get( source, cooldownGroup ); } int cooldownGroup2 = NULL_COOLDOWN_GROUP; if ( flags & MessageQueueCommandTimer::toBitValue( MessageQueueCommandTimer::F_cooldown2 ) ) { Archive::get( source, cooldownGroup2 ); } MessageQueueCommandTimer *msg = new MessageQueueCommandTimer( sequenceId, cooldownGroup, cooldownGroup2, commandNameCrc ); for ( int i = 0; i < MessageQueueCommandTimer::F_MAX; ++i ) { MessageQueueCommandTimer::Flags flag = static_cast< MessageQueueCommandTimer::Flags >( i ); if ( flags & MessageQueueCommandTimer::toBitValue( flag ) ) { float value; Archive::get( source, value ); msg->setCurrentTime( flag, value ); Archive::get( source, value ); msg->setMaxTime( flag, value ); } } return msg; } } using namespace SetupSwgSharedNetworkMessagesNamespace; // ---------------------------------------------------------------------- void SetupSwgSharedNetworkMessages::install () { DEBUG_FATAL(g_installed, ("SetupSwgSharedNetworkMessages::install - is already installed")); MessageQueueCombatAction::install(); MessageQueueCombatDamage::install(); ControllerMessageFactory::registerControllerMessageHandler(CM_setAttribute, packAttributeMessage, unpackAttributeMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMaxAttribute, packAttributeMessage, unpackAttributeMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMentalState, packMentalStatesMessage, unpackMentalStatesMessage ); ControllerMessageFactory::registerControllerMessageHandler(CM_setMaxMentalState, packMentalStatesMessage, unpackMentalStatesMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMentalStateToward, packMentalStatesTowardsMessage, unpackMentalStatesTowardsMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setCover, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMaxHitPoints, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setCombatAttitude, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setAutoAttack, packBoolMessage, unpackBoolMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setInvulnerable, packBoolMessage, unpackBoolMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMentalStateTowardClampBehavior, packMentalStateTowardClampBehaviorMessage, unpackMentalStateTowardClampBehaviorMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setMentalStateDecay, packMentalStateDecayMessage, unpackMentalStateDecayMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_setLocomotion, packLocomotionMessage, unpackLocomotionMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_addPlayerToSpawnQueue, packAddToPlayerSpawnQueueMessage, unpackAddToPlayerSpawnQueueMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_removePlayerFromSpawnQueue, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_forwardNpcConversationMessage, packGenericStringIdProsePackageMessage, unpackGenericStringIdProsePackageMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_musicFlourish, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_npcConversationSelect, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_craftingSessionEnded, packBoolMessage, unpackBoolMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_biographyRetrieved, packNetworkIdUnicodeStringPairMessage, unpackNetworkIdUnicodeStringPairMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_characterMatchRetrieved, packCharacterMatchResultVectorMessage, unpackCharacterMatchResultVectorMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_startingLocations, packStartingLocations, unpackStartingLocations); ControllerMessageFactory::registerControllerMessageHandler(CM_startingLocationSelectionResult, packStartingLocationSelectionResult, unpackStartingLocationSelectionResult); ControllerMessageFactory::registerControllerMessageHandler(CM_disconnect, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_emergencyDismountForRider, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_detachRiderForMount, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_formDataForEdit, packNetworkIdUnicodeStringPairMessage, unpackNetworkIdUnicodeStringPairMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_serverAsteroidDebugData, packSphereVectorMessage, unpackSphereVectorMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_commPlayer, packNetworkIdUnicodeStringPairMessage, unpackNetworkIdUnicodeStringPairMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_clientLookAtTargetComponent, packIntMessage, unpackIntMessage, true); ControllerMessageFactory::registerControllerMessageHandler(CM_aboutToHyperspace, packGenericStringVectorPairMessage, unpackGenericStringVectorPairMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_playerTransitioningOut, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_playerTransitioningIn, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_addIgnoreIntersect, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_removeIgnoreIntersect, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_spaceTerminalRequest, packNetworkIdMessage, unpackNetworkIdMessage, true); ControllerMessageFactory::registerControllerMessageHandler(CM_spaceTerminalResponse, packStringNetworkIdPairVector, unpackStringNetworkIdPairVector); ControllerMessageFactory::registerControllerMessageHandler(CM_hyperspaceOrientShipToPointAndLockPlayerInput, packGenericStringVectorPairMessage, unpackGenericStringVectorPairMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_lockPlayerShipInputOnClient, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_unlockPlayerShipInputOnClient, packNothing, unpackNothing); ControllerMessageFactory::registerControllerMessageHandler(CM_inviteOtherGroupMembersToLaunchIntoSpace, packNetworkIdMessage, unpackNetworkIdMessage, true); ControllerMessageFactory::registerControllerMessageHandler(CM_askGroupMemberToLaunchIntoSpace, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_groupMemberInvitationToLaunchIntoSpaceResponse, packNetworkIdBoolPair, unpackNetworkIdBoolPair, true); ControllerMessageFactory::registerControllerMessageHandler(CM_relayGroupMemberInvitationToLaunchAnswer, packNetworkIdBoolPair, unpackNetworkIdBoolPair); ControllerMessageFactory::registerControllerMessageHandler(CM_groupOpenLotteryWindowOnClient, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_groupCloseLotteryWindowOnClient, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_groupLotteryWindowHeartbeat, packNetworkIdMessage, unpackNetworkIdMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_groupLotteryWindowCloseResults, packNetworkIdNetworkIdVector, unpackNetworkIdNetworkIdVector, true); ControllerMessageFactory::registerControllerMessageHandler(CM_commandTimer, packCommandTimerMessage, unpackCommandTimerMessage ); ControllerMessageFactory::registerControllerMessageHandler(CM_requestActivateQuest, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_requestCompleteQuest, packIntMessage, unpackIntMessage); ControllerMessageFactory::registerControllerMessageHandler(CM_staticLootItemData, packGenericVectorOfUnicodeStrings, unpackGenericVectorOfUnicodeStrings); ControllerMessageFactory::registerControllerMessageHandler(CM_showLootBox, packNetworkIdVector, unpackNetworkIdVector); ControllerMessageFactory::registerControllerMessageHandler(CM_forceActivateQuest, packIntMessage, unpackIntMessage); g_installed = true; ExitChain::add (SetupSwgSharedNetworkMessages::remove, "SetupSwgSharedNetworkMessages"); } // ---------------------------------------------------------------------- void SetupSwgSharedNetworkMessages::remove ( void ) { DEBUG_FATAL(!g_installed, ("SetupSwgSharedNetworkMessages::remove - not already installed")); g_installed = false; } // ----------------------------------------------------------------------
ff11eca11eae45216c685e64ba12baec6c3f4a74
f789494db62d68f5664579595cd517109dab5742
/software/lib/sim/src/JadePixDigitizer.cc
23fcc24972921f1b3add8ff58a820d74fa70d101
[]
no_license
rkiuchi/jadepix
0535dd6ca08788fd90dd5774a920b00d1b74fd45
1a6e0abb5341c306211da6eda60efc75a65636b1
refs/heads/master
2021-09-06T23:02:49.394836
2018-02-13T04:33:36
2018-02-13T04:33:36
121,213,883
0
0
null
2018-02-12T07:23:04
2018-02-12T07:23:04
null
UTF-8
C++
false
false
26,654
cc
JadePixDigitizer.cc
#include "JadePixDigitizer.hh" #include "JadePixHit.hh" #include "G4PhysicalConstants.hh" #include "G4SystemOfUnits.hh" #include "G4UnitsTable.hh" #include "G4DigiManager.hh" #include "Randomize.hh" #include "G4ios.hh" #include <math.h> JadePixDigitizer::JadePixDigitizer(G4String modName):G4VDigitizerModule(modName){ JadePixGeo=JadePixGeoParameter::GetGeo(); collectionName.push_back("JadePixDigisCollection"); noiseFlag = 1.; fakeHitFlag = 0; nAdcBit = JadePixGeo->Layer(0).ADCBitNo(); cce = JadePixGeo->Layer(0).CCE(); enc = JadePixGeo->Layer(0).ENC(); pedestal = 0; ehpEnergy = 3.6 *eV; energyThreshold = (pedestal+0*enc)*ehpEnergy; adcEnergyRange = JadePixGeo->Layer(0).ADCRange()*ehpEnergy; } JadePixDigitizer::~JadePixDigitizer(){} void JadePixDigitizer::Digitize(){ digiMap.clear(); G4int NHits; G4double pixEdep; G4DigiManager* DigiMan = G4DigiManager::GetDMpointer(); //hits collection ID G4int THCID=-1; THCID = DigiMan->GetHitsCollectionID("JadePixHitsCollection"); //hits collection JadePixHitsCollection* THC = 0; THC = (JadePixHitsCollection*) (DigiMan->GetHitsCollection(THCID)); if(THC){ digisCollection=new JadePixDigisCollection(moduleName, collectionName[0]); NHits=THC->entries(); //G4cout<<"BesSimDigitizer::Primary Hits No: "<<NHits<<endl; for(G4int i=0;i<NHits;i++){ //HitRealizition((*THC)[i]); //G4cout<<"Total Edep: "<<(*THC)[i]->GetEdep()<<", ehPairs: "<<(*THC)[i]->GetEdep()/ehpEnergy<<G4endl; HitRealizitionEelectrode((*THC)[i]); } G4int nrHit=0; std::vector<JadePixHit*>::iterator itRealHitCol; for(itRealHitCol=realizedHitsCol.begin();itRealHitCol!=realizedHitsCol.end();++itRealHitCol){ JadePixHit* _realHit = *itRealHitCol; pixEdep = _realHit->GetEdep() + noiseFlag*ehpEnergy*G4RandGauss::shoot(pedestal,enc); if(pixEdep>energyThreshold){ JadePixDigi* newDigi = new JadePixDigi(); newDigi->SetTrackID(_realHit->GetTrackID()); newDigi->SetLayerID(_realHit->GetLayerID()); newDigi->SetLadderID(_realHit->GetLadderID()); newDigi->SetChipID(_realHit->GetChipID()); newDigi->SetGlobalChipID(_realHit->GetGlobalChipID()); newDigi->SetRow(_realHit->GetRow()); newDigi->SetCol(_realHit->GetCol()); newDigi->SetEdep(pixEdep); newDigi->SetGlobalT(_realHit->GetGlobalT()); //int adc = GetADC(pixEdep); int adc = GetVolADC(pixEdep); //Change ADC method int tdc = GetTDC(_realHit->GetGlobalT()); newDigi->SetADC(adc); newDigi->SetTDC(tdc); JadePixIdentifier _JadePixDigiId(_realHit->GetLayerID(),_realHit->GetLadderID(),_realHit->GetChipID(),_realHit->GetCol(),_realHit->GetRow()); unsigned int key=_JadePixDigiId.PixelID(); G4int NbDigis = digisCollection->insert(newDigi); digiMap[key]=NbDigis-1; nrHit++; if(verboseLevel>0) { G4cout<<"MyMessage::Processing Digi: "<<" layer: "<<_realHit->GetLayerID()<<" ladder: "<<_realHit->GetLadderID()<<" Chip: "<<_realHit->GetChipID()<<" Row: "<<_realHit->GetRow()<<" Col: "<<_realHit->GetCol()<<" Edep: "<<_realHit->GetEdep()<<", ehPairs: "<<_realHit->GetEdep()/ehpEnergy<<", ADC: "<<adc<<G4endl; } } delete _realHit; } realizedHitsCol.clear(); realizedHitMap.clear(); //G4cout<<"MyMessage::Primary Hit No: "<<NHits<<" Realized Hit No: "<<nrHit<<G4endl; if(fakeHitFlag==1) AddFake(); if (verboseLevel>0) { G4cout << "\n-------->digis Collection: in this event they are " << digisCollection->entries() << " digis in the JadePix: " << G4endl; digisCollection->PrintAllDigi(); } StoreDigiCollection(digisCollection); } } void JadePixDigitizer::HitRealizition(JadePixHit* rawHit){ G4int layerId = rawHit->GetLayerID(); G4int ladderId = rawHit->GetLadderID(); G4int chipId = rawHit->GetChipID(); JadePixIdentifier JadePixId(layerId,ladderId,chipId,-1,-1); G4ThreeVector locInPos = rawHit->GetPrePos(); G4ThreeVector locOutPos = rawHit->GetPostPos(); G4double edep = rawHit->GetEdep(); G4ThreeVector locMidPos = (locInPos+locOutPos)/2; // Change to Possion Distribution G4double preEdep=edep*(0.23+0.2*G4UniformRand()); G4double postEdep=edep*(0.23+0.2*G4UniformRand()); G4double midEdep=edep-preEdep-postEdep; //G4cout<<"MyMessage::Edep: "<<edep<<" PreEdep: "<<preEdep<<" PostEdep: "<<postEdep<<" MidEdep: "<<midEdep<<G4endl; G4int digiMethod = JadePixGeo->Layer(0).DigiMethod(); if(digiMethod == 0){ if (verboseLevel>0){ G4cout<<"Two Gauss is in use!" << G4endl;} DiffuseE(preEdep,locInPos,JadePixId,rawHit); DiffuseE(midEdep,locMidPos,JadePixId,rawHit); DiffuseE(postEdep,locOutPos,JadePixId,rawHit); }else if(digiMethod == 1){ if(verboseLevel>0){G4cout<<"Gauss is in use!" << G4endl;} DiffuseGaussE(preEdep,locInPos,JadePixId,rawHit); DiffuseGaussE(midEdep,locMidPos,JadePixId,rawHit); DiffuseGaussE(postEdep,locOutPos,JadePixId,rawHit); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void JadePixDigitizer::DiffuseE(G4double edep,G4ThreeVector hitPoint,JadePixIdentifier& JadePixId,JadePixHit* rawHit){ //G4cout<<"MyMessage::locHitPosX: "<<hitPoint.x()<<" locHitPosY: "<<hitPoint.y()<<" locHitPosZ: "<<hitPoint.z()<<G4endl; G4double sigmaS = 1*um; G4double sigmaL = 2.5*um; G4double frac=0.8; G4double diffuseSize = 5*sigmaL; G4int nSector=10; G4double secPitch = diffuseSize/(2*nSector+1); G4double secEdep; G4double eT=0; for(G4int iSC=-nSector;iSC<nSector+1;++iSC){ for(G4int iSR=-nSector;iSR<nSector+1;++iSR){ G4double dx=secPitch*iSC; G4double dy=secPitch*iSR; G4double iPosX=hitPoint.x()+dx; G4double iPosY=hitPoint.y()+dy; //gauss pdf G4double pdf1 = exp(-(pow(dx,2)+pow(dy,2))/(2*sigmaS*sigmaS))/(twopi*sigmaS*sigmaS); G4double pdf2 = exp(-(pow(dx,2)+pow(dy,2))/(2*sigmaL*sigmaL))/(twopi*sigmaL*sigmaL); //exp pdf //G4double r=sqrt(pow(iX-hitPoint.x(),2)+pow(iY-hitPoint.y(),2)); //if(r<=sigma/3) r=sigma/3; // G4double pdf = exp(-r/sigma)/(twopi*r*sigma); //G4double xy=fabs(dx)+fabs(dy); //if(xy<secPitch) xy=secPitch*4/7; //G4double pdf2=exp(-xy/sigmaL)/(4*sigmaL*sigmaL); G4double pdf= frac*pdf1 + (1-frac)*pdf2; secEdep = edep*pdf*secPitch*secPitch; //G4cout<<"MyMessage::locCol: "<<iSC<<" locRow: "<<iSR<<" Edep: "<<secEdep<<G4endl; JadePixId.WhichPixel(iPosX,iPosY); PixelIntegration(secEdep,JadePixId,rawHit); eT += secEdep; } } //G4cout<<"MyMessage::Total E Collect: "<<eT<<" Total Percent: "<<100*eT/edep<<"%"<<G4endl; } void JadePixDigitizer::DiffuseGaussE(G4double edep,G4ThreeVector hitPoint,JadePixIdentifier& JadePixId,JadePixHit* rawHit){ //G4cout<<"MyMessage::locHitPosX: "<<hitPoint.x()<<" locHitPosY: "<<hitPoint.y()<<" locHitPosZ: "<<hitPoint.z()<<G4endl; G4double sigma = 9.59*um; G4double frac=0.6807; G4double diffuseSize = 5*sigma; G4double d0=1.406*um; G4double base = 0.2988; G4int nSector=10; G4double secPitch = diffuseSize/(2*nSector+1); G4double secEdep; G4double eT=0; for(G4int iSC=-nSector;iSC<nSector+1;++iSC){ for(G4int iSR=-nSector;iSR<nSector+1;++iSR){ G4double dx=secPitch*iSC; G4double dy=secPitch*iSR; G4double iPosX=hitPoint.x()+dx; G4double iPosY=hitPoint.y()+dy; //gauss pdf G4double pdf = frac*exp(-(pow(dx,2)+pow(dy,2)-d0)/(2*sigma*sigma))+base; secEdep = edep*pdf*secPitch*secPitch; //G4cout<<"MyMessage::locCol: "<<iSC<<" locRow: "<<iSR<<" Edep: "<<secEdep<<G4endl; JadePixId.WhichPixel(iPosX,iPosY); PixelIntegration(secEdep,JadePixId,rawHit); eT += secEdep; } } //G4cout<<"MyMessage::Total E Collect: "<<eT<<" Total Percent: "<<100*eT/edep<<"%"<<G4endl; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void JadePixDigitizer::HitRealizitionEelectrode(JadePixHit* rawHit){ G4int layerId = rawHit->GetLayerID(); G4int ladderId = rawHit->GetLadderID(); G4int chipId = rawHit->GetChipID(); JadePixIdentifier JadePixId(layerId,ladderId,chipId,-1,-1); G4ThreeVector locInPos = rawHit->GetPrePos(); G4ThreeVector locOutPos = rawHit->GetPostPos(); if(verboseLevel>0){ G4cout<<"MyMessage:: locInPos.X: "<<locInPos.x()/cm<<" Y: "<<locInPos.y()/cm<<" Z: "<<locInPos.z()/cm<<G4endl; G4cout<<"MyMessage:: locOutPos.X: "<<locOutPos.x()/cm<<" Y: "<<locOutPos.y()/cm<<" Z: "<<locOutPos.z()/cm<<G4endl; } G4double edep = rawHit->GetEdep(); G4ThreeVector locMidPos = (locInPos+locOutPos)/2; G4int nofCol = JadePixGeo->Layer(0).ColNo(); G4int nofRow = JadePixGeo->Layer(0).RowNo(); G4int digiMethod = JadePixGeo->Layer(0).DigiMethod(); G4ThreeVector locSegPos; G4int nSegments = 10; //Step segment G4double SegEdep=edep/nSegments; //Uniform distribution of energy in step --> Should change to Landau distribution G4double eT; G4double eTotal=0; G4double ratio; G4int nAdjacentPix=1; //Neighbouring pixel hitting std::vector<std::vector <G4double>> ePixArray(2*nAdjacentPix+1,std::vector<G4double>(2*nAdjacentPix+1,0)); for(G4int iSeg=0; iSeg<nSegments; iSeg++){ locSegPos = (locOutPos-locInPos)/nSegments*(iSeg+0.5)+locInPos; //center of segment JadePixId.WhichPixel(locSegPos.x(),locSegPos.y()); G4int localColID = JadePixId.ColID(); G4int localRowID = JadePixId.RowID(); G4double ePix=0; eT=0; // Segment tot edep for(G4int iC=-nAdjacentPix; iC<nAdjacentPix+1; iC++){ for(G4int iR=-nAdjacentPix; iR<nAdjacentPix+1; iR++){ G4int subColID = localColID+iC; G4int subRowID = localRowID+iR; JadePixIdentifier iJadePixId(layerId,ladderId,chipId,subColID,subRowID); if(subColID>-1 && subColID<nofCol && subRowID>-1 && subRowID<nofRow){ // GaussLorentz diffusion collected in electrode if(digiMethod == 0){ if (verboseLevel>0){ G4cout<<"Gauss lorentz is in use!" << G4endl;} ePix = SegEdep*DiffuseGaussLorentzElectrode(iJadePixId,locSegPos); }else if(digiMethod == 1){ if(verboseLevel>0){G4cout<<"Gauss lorentz with four diode is in use!" << G4endl;} ePix = SegEdep*OverMOSDiffuseGaussLorentzElectrode(iJadePixId,locSegPos); }else if (digiMethod == 2){ if(verboseLevel>0){G4cout<<"Gauss with center is in use!" << G4endl;} ePix = SegEdep*DiffuseGaussElectrode(iJadePixId,locSegPos); }else if (digiMethod == 3){ ePix = SegEdep*DiffuseGaussElectrodeDivided(iJadePixId,locSegPos); } if(verboseLevel>0){G4cout<<"SegEdep: "<<SegEdep<<", "<<ePix<<G4endl;} } ePixArray[nAdjacentPix+iC][nAdjacentPix+iR]=ePix; eT += ePix; } } if(verboseLevel>0) { std::cout<<"SegEdep: "<<G4BestUnit(SegEdep,"Energy")<<", eSegCollected: "<<G4BestUnit(eT,"Energy")<<endl; } ratio = cce*SegEdep/eT; G4double eTpost = 0; for(G4int iC=-nAdjacentPix; iC<nAdjacentPix+1; iC++){ for(G4int iR=-nAdjacentPix; iR<nAdjacentPix+1; iR++){ G4int subColID = localColID+iC; G4int subRowID = localRowID+iR; JadePixIdentifier iJadePixId(layerId,ladderId,chipId,subColID,subRowID); ePix = ePixArray[nAdjacentPix+iC][nAdjacentPix+iR]*ratio; //cout<<"ePix: "<<ePix<<endl; PixelIntegration(ePix,iJadePixId,rawHit); eTpost += ePix; } } if(verboseLevel>0) { std::cout<<"SegEdep: "<<G4BestUnit(SegEdep,"Energy")<<", eTpost: "<<G4BestUnit(eTpost,"Energy")<<endl; } eTotal += eTpost; } if(verboseLevel>0) { std::cout<<"edep: "<<G4BestUnit(edep,"Energy")<<", eCollected: "<<G4BestUnit(eTotal,"Energy")<<endl; } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... double JadePixDigitizer::DiffuseGaussLorentzElectrode(JadePixIdentifier& JadePixId, G4ThreeVector hitPoint) { G4double pixPitchX=JadePixGeo->Layer(0).PitchX()*um; G4double pixPitchY=JadePixGeo->Layer(0).PitchY()*um; //segment impact pixel G4double Csigma = 13.2*um; G4double CN0=0.458; G4double CN1=6.45*um; G4double Cd0=-3.98*um; G4double Cd1=1.80*um; G4double CGamma=3.99*um; //Other pixel G4double Osigma = 17.5*um; G4double ON0=0.117; G4double ON1=3.71*um; G4double Od0=-1.07*um; G4double Od1=-4.64*um; G4double OGamma=47.1*um; G4double sigma,N0,N1,d0,d1,Gamma; G4ThreeVector iPixPos = JadePixId.PixelPos(); G4double iX=iPixPos.x(); G4double iY=iPixPos.y(); G4double dxRaw=hitPoint.x()-iX; G4double dyRaw=hitPoint.y()-iY; //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; G4double pixEdgeCut=30*um; //G4double nominalPixPitch=22.5*um; G4double nominalPixPitch=pixEdgeCut-0.05*(pixPitchX-10*um); G4double dx = dxRaw*nominalPixPitch/pixPitchX; G4double dy = dyRaw*nominalPixPitch/pixPitchY; // The distance between the reconstructed position of the cluster and the diode in collection of pixel in the XY sensor G4double d = sqrt(pow(dx,2)+pow(dy,2)); G4double pdf1,pdf2; //if(fabs(dx)<=(pixPitchX/2) && fabs(dy)<=(pixPitchY/2)) if(fabs(dx)<=pixEdgeCut && fabs(dy)<=pixEdgeCut){ sigma = Csigma; N0 = CN0; N1 = CN1; d0 = Cd0; d1 = Cd1; Gamma = CGamma; }else{ sigma = Osigma; N0 = ON0; N1 = ON1; d0 = Od0; d1 = Od1; Gamma = OGamma; } // Reference Loic COUSIN // Charge Collection pdf1=exp(-pow((d-d0),2)/(2*sigma*sigma)); pdf2=Gamma/(Gamma*Gamma+pow((d-d1),2)); G4double pdf=N0*pdf1+N1*pdf2; G4double factor=1./2; return pdf*factor; } double JadePixDigitizer::DiffuseGaussElectrode(JadePixIdentifier& JadePixId, G4ThreeVector hitPoint) { //G4double pixPitchX=JadePixGeo->Layer(0).PitchX()*um; //G4double pixPitchY=JadePixGeo->Layer(0).PitchY()*um; //segment impact pixel G4double sigma = 9.59*um; G4double N0=0.6807; G4double d0=1.406*um; G4double base=0.2988; //G4double sigma = 10.72*um; //G4double N0=0.99; //G4double d0=2.94*um; G4ThreeVector iPixPos = JadePixId.PixelPos(); G4double iX=iPixPos.x(); //Diode in the center G4double iY=iPixPos.y(); G4double dxRaw=hitPoint.x()-iX; G4double dyRaw=hitPoint.y()-iY; //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; //G4double pixEdgeCut=33*um; ////G4double nominalPixPitch=22.5*um; //G4double nominalPixPitch=pixEdgeCut-0.05*(pixPitchX-4*um); //G4double dx = dxRaw*nominalPixPitch/pixPitchX; //G4double dy = dyRaw*nominalPixPitch/pixPitchY; G4double dx = dxRaw; G4double dy = dyRaw; //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; // The distance between the reconstructed position of the cluster and the diode in collection of pixel in the XY sensor G4double d = sqrt(pow(dx,2)+pow(dy,2)); //cout<<"d-d0: "<<d-d0<<endl; // Charge Collection //G4double pdf=N0*exp(-pow((d-d0),2)/(2*sigma*sigma)); G4double pdf=N0*exp(-pow((d-d0),2)/(2*sigma*sigma))+base; //cout<<"pdf: "<<pdf<<endl; G4double factor=1.0; return pdf*factor; } double JadePixDigitizer::DiffuseGaussElectrodeDivided(JadePixIdentifier& JadePixId, G4ThreeVector hitPoint) { G4double pixPitchX=JadePixGeo->Layer(0).PitchX()*um; G4double pixPitchY=JadePixGeo->Layer(0).PitchY()*um; G4double diodesize=JadePixGeo->Layer(0).DiodeSize()*um; //segment impact pixel //G4double sigma = 9.59*um; //G4double N0=0.6807; //G4double d0=1.406*um; //G4double base=0.2988; //G4double mean1 = 1.5*um; G4double mean2 = 1.5*um; G4double mean3 = 4.*um; //G4double sigma1 = 2.*um; G4double sigma2 = 10.*um; G4double sigma3 = 15.*um; G4double N0=0.7; G4double d0=0*um; G4double base=0.3; G4ThreeVector iPixPos = JadePixId.PixelPos(); G4double iX=iPixPos.x(); //Diode in the center G4double iY=iPixPos.y(); G4double dxRaw=hitPoint.x()-iX; G4double dyRaw=hitPoint.y()-iY; const int poly_sides = 8; G4double L1 = diodesize/2; G4double innerangle = 360/poly_sides; G4double alpha = 3.1415926*innerangle/2/180; G4double L2 = L1/tan(alpha); G4double poly_x[poly_sides] = {iX+L1,iX+L2,iX+L2,iX+L1,-(iX+L1),-(iX+L2),-(iX+L2),-(iX+L1)}; G4double poly_y[poly_sides] = {iY+L2,iY+L1,-(iY+L1),-(iY+L2),-(iY+L2),-(iY+L1),iY+L1,iY+L2}; G4double x = hitPoint.x(); G4double y = hitPoint.y(); G4int ret; ret = InOrNot(poly_sides, poly_x, poly_y, x, y); //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; //G4double pixEdgeCut=33*um; //G4double nominalPixPitch=22.5*um; //G4double nominalPixPitch=pixEdgeCut-0.05*(pixPitchX-4*um); //G4double dx = dxRaw*nominalPixPitch/pixPitchX; //G4double dy = dyRaw*nominalPixPitch/pixPitchY; G4double dx = dxRaw; G4double dy = dyRaw; //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; // The distance between the reconstructed position of the cluster and the diode in collection of pixel in the XY sensor G4double d = sqrt(pow(dx,2)+pow(dy,2)); //cout<<"d-d0: "<<d-d0<<endl; // Charge Collection G4double pdf; if(ret == 1){ //pdf=N0*exp(-pow((d-d0),mean1)/(2*sigma1*sigma1))+base; pdf=1; } else if(fabs(dxRaw)<=pixPitchX && fabs(dyRaw)<=pixPitchY){ pdf=N0*exp(-pow((d-d0),mean2)/(2*sigma2*sigma2))+base; }else{ pdf=N0*exp(-pow((d-d0),mean3)/(2*sigma3*sigma3))+base; } //cout<<"d-d0: "<<d-d0<<endl; //cout<<"pdf: "<<pdf<<endl; G4double factor=1.0; return pdf*factor; } double JadePixDigitizer::OverMOSDiffuseGaussLorentzElectrode(JadePixIdentifier& JadePixId, G4ThreeVector hitPoint) { //G4double pixPitchX=JadePixGeo->Layer(0).PitchX()*um; //G4double pixPitchY=JadePixGeo->Layer(0).PitchY()*um; //center pixel G4double Csigma = 42.1*um; G4double CN0=17.5; G4double CN1=211.8*um; G4double Cd0=-230.8*um; G4double Cd1=-170.6*um; G4double CGamma=23.6*um; G4double Osigma = 42.1*um; G4double ON0=17.5; G4double ON1=211.8*um; G4double Od0=-230.8*um; G4double Od1=-170.6*um; G4double OGamma=23.6*um; G4double sigma,N0,N1,d0,d1,Gamma; //G4ThreeVector iPixPos = JadePixId.PixelPos(); std::vector<G4ThreeVector> pixDiode = JadePixId.PixelDiode(); std::vector<G4ThreeVector>::iterator ipixDiode; //G4double iX=iPixPos.x(); //G4double iY=iPixPos.y(); //G4double dxRaw=hitPoint.x()-iX; //G4double dyRaw=hitPoint.y()-iY; G4double dxRaw=0; G4double dyRaw=0; //cout<<"pixPitchX: "<<pixPitchX<<", pixPitchY: "<<pixPitchY<<endl; //cout<<"iX: "<<iX<<", dx: "<<dx<<", iY: "<<iY<<", dy: "<<dy<<endl; for(ipixDiode=pixDiode.begin();ipixDiode!=pixDiode.end();++ipixDiode){ //G4cout<<"Pixel diode vector: "<<*ipixDiode<<G4endl; G4double tmp_dxRaw=hitPoint.x()-ipixDiode->x(); if(tmp_dxRaw<dxRaw){ dxRaw=tmp_dxRaw;} G4double tmp_dyRaw=hitPoint.y()-ipixDiode->y(); if(tmp_dyRaw<dyRaw){ dyRaw=tmp_dyRaw;} } //G4cout<<"dxRaw: "<<dxRaw<<", dyRaw: "<<dyRaw<<G4endl; G4double pixEdgeCut=24*um; //G4double nominalPixPitch=22.5*um; //G4double nominalPixPitch=pixEdgeCut-0.05*(pixPitchX-10*um); //G4double dx = dxRaw*nominalPixPitch/pixPitchX; //G4double dy = dyRaw*nominalPixPitch/pixPitchY; G4double dx = dxRaw; G4double dy = dyRaw; // The distance between the reconstructed position of the cluster and the diode in collection of pixel in the XY sensor G4double d = sqrt(pow(dx,2)+pow(dy,2)); G4double pdf1,pdf2; //if(fabs(dx)<=(pixPitchX/2) && fabs(dy)<=(pixPitchY/2)) if(fabs(dx)<=pixEdgeCut && fabs(dy)<=pixEdgeCut){ sigma = Csigma; N0 = CN0; N1 = CN1; d0 = Cd0; d1 = Cd1; Gamma = CGamma; }else{ sigma = Osigma; N0 = ON0; N1 = ON1; d0 = Od0; d1 = Od1; Gamma = OGamma; } // Reference Loic COUSIN // Charge Collection pdf1=exp(-pow((d-d0),2)/(2*sigma*sigma)); pdf2=Gamma/(Gamma*Gamma+pow((d-d1),2)); G4double pdf=N0*pdf1+N1*pdf2; G4double factor=11.33337; return pdf*factor; } void JadePixDigitizer::PixelIntegration(G4double ePix,JadePixIdentifier& JadePixId, JadePixHit* rawHit){ G4int colId=JadePixId.ColID(); G4int rowId=JadePixId.RowID(); //G4cout<<"MyMessage::colId: "<<colId<<" rowId: "<<rowId<<G4endl; G4double globalT = rawHit->GetGlobalT(); G4int trackId = rawHit->GetTrackID(); G4int nofCol = JadePixGeo->Layer(0).ColNo(); G4int nofRow = JadePixGeo->Layer(0).RowNo(); if(colId>-1 && colId<nofCol && rowId>-1 && rowId<nofRow){ unsigned int key = JadePixId.PixelID(); //cout<<"Row: "<<rowId<<" Col: "<<colId<<" Key: "<<key<<endl; JadePixHit* _hit = new JadePixHit(); _hit->SetLayerID(JadePixId.LayerID()); _hit->SetLadderID(JadePixId.LadderID()); _hit->SetChipID(JadePixId.ChipID()); _hit->SetGlobalChipID(JadePixId.GlobalChipID()); _hit->SetCol(colId); _hit->SetRow(rowId); _hit->SetEdep(ePix); _hit->SetTrackID(trackId); _hit->SetGlobalT(globalT); itRealizedHitMap = realizedHitMap.find(key); if(itRealizedHitMap==realizedHitMap.end()){ realizedHitsCol.push_back(_hit); realizedHitMap[key]=G4int(realizedHitsCol.size())-1; } else{ G4int pointer=(*itRealizedHitMap).second; //cout<<"Key: "<<key<<" pointer: "<<pointer<<endl; (realizedHitsCol[pointer])->SetEdep((realizedHitsCol[pointer])->GetEdep()+_hit->GetEdep()); G4double preGlobalT=(realizedHitsCol[pointer])->GetGlobalT(); if(globalT<preGlobalT){ (realizedHitsCol[pointer])->SetGlobalT(globalT); } delete _hit; } } } void JadePixDigitizer::AddFake(){ //G4double fakeRate = 10e-4; //G4double frPerEvt = fakeRate/600; G4int nRow=JadePixGeo->Layer(0).RowNo(); G4int nCol=JadePixGeo->Layer(0).ColNo(); //G4int nPix=JadePixGeo->Layer(0).PixNo(); // G4int nfakePix = nPix*frPerEvt+G4RandGauss::shoot(0,0.5); G4int nfakePix = G4RandGauss::shoot(0,0.7); if(nfakePix<0) nfakePix = 0; //G4cout<<"MyMessage::nfakePix: "<<nfakePix<<G4endl; for(G4int i=0;i<nfakePix;++i){ G4int rowId=nRow*G4UniformRand(); G4int colId=nCol*G4UniformRand(); G4long key=rowId*nCol+colId; itDigiMap=digiMap.find(key); if(itDigiMap==digiMap.end()){ G4double fakeE=energyThreshold*G4RandGauss::shoot(); if(fakeE<energyThreshold) fakeE += 2*(energyThreshold-fakeE); JadePixDigi* newDigi = new JadePixDigi(); newDigi->SetTrackID(-1); newDigi->SetLayerID(0); newDigi->SetLadderID(0); newDigi->SetChipID(0); newDigi->SetGlobalChipID(0); newDigi->SetRow(rowId); newDigi->SetCol(colId); newDigi->SetEdep(fakeE); newDigi->SetGlobalT(0); digisCollection->insert(newDigi); } } } int JadePixDigitizer::GetADC(double eDep){ int locAdcRange = pow(2,nAdcBit); double dE = (adcEnergyRange-energyThreshold)/locAdcRange; double eDepEff=eDep-energyThreshold; if(eDepEff<0)eDepEff=0; int dAdc = int(eDepEff/dE); if(dAdc >= locAdcRange) dAdc = locAdcRange-1; int adc = int((energyThreshold+dAdc*dE)/ehpEnergy); return adc; } int JadePixDigitizer::GetVolADC(double eDep){ int locAdcRange = pow(2,nAdcBit)-1; //G4double gain = 0.02*1e-3; G4double gain = 0.032*1e-3; //int Vref = 0.5; double dE = (adcEnergyRange-energyThreshold)/locAdcRange; double eDepEff=eDep-energyThreshold; if(eDepEff<0)eDepEff=0; int dAdc = int(eDepEff/dE); if(dAdc >= locAdcRange) dAdc = locAdcRange-1; int adc = int(((energyThreshold+dAdc*dE)/ehpEnergy*gain)*locAdcRange); return adc; } int JadePixDigitizer::GetTDC(double time){ int nofBit = 5; int tdcRange = pow(2,double(nofBit)); double range = 5; double dT = range/tdcRange; int tdc = int(time/dT); if(tdc > tdcRange) tdc = tdcRange; return tdc; } int JadePixDigitizer::InOrNot(int poly_sides, double *poly_x, double *poly_y, double x, double y){ int i, j; j = poly_sides-1; int res = 0; for (i = 0; i<poly_sides; i++) { if( ( (poly_y[i]<y && poly_y[j]>=y) || (poly_y[j]<y && poly_y[i]>=y) ) && (poly_x[i]<=x || poly_x[j]<=x)){ res ^= ((poly_x[i] + (y-poly_y[i])/(poly_y[j]-poly_y[i])*(poly_x[j]-poly_x[i])) < x); } j=i; } return res; }
b64ae91adf7ab395ca07f100a9667137d5e563c0
5cec37261e756a98b632eda290d4869461738403
/testing/unit_testing/src/2_ranks/composite_mesh.cpp
8bfb59b435d27e5f630c1f8b576864fc76a04061
[ "MIT" ]
permissive
maierbn/opendihu
d78630244fbba035f34f98a4f4bd0102abe57f04
e753fb2a277f95879ef107ef4d9ac9a1d1cec16d
refs/heads/develop
2023-09-05T08:54:47.345690
2023-08-30T10:53:10
2023-08-30T10:53:10
98,750,904
28
11
MIT
2023-07-16T22:08:44
2017-07-29T18:13:32
C++
UTF-8
C++
false
false
23,359
cpp
composite_mesh.cpp
#include <Python.h> // this has to be the first included header #include <iostream> #include <cstdlib> #include <fstream> #include <cassert> #include <cmath> #include "gtest/gtest.h" #include "opendihu.h" #include "arg.h" #include "../utility.h" #include "mesh/face_t.h" #include "function_space/function_space.h" TEST(CompositeTest, Case0) { // run serial problem std::string pythonConfig = R"( meshes = { "submesh0": { "nElements": [2, 3], "inputMeshIsGlobal": True, "physicalExtent": [2.0, 3.0], }, "submesh1": { "nElements": [1, 4], "inputMeshIsGlobal": True, "physicalExtent": [2.0, 4.0], "physicalOffset": [2.0, 0.0], }, } config = { "Meshes": meshes, "FiniteElementMethod": { "inputMeshIsGlobal": True, "meshName": ["submesh0", "submesh1"], }, } print(config) )"; DihuContext settings(argc, argv, pythonConfig); typedef SpatialDiscretization::FiniteElementMethod< Mesh::CompositeOfDimension<2>, BasisFunction::LagrangeOfOrder<2>, Quadrature::Gauss<1>, Equation::None > ProblemType; ProblemType problem(settings); problem.initialize(); std::string stringRespresentation = problem.data().functionSpace()->meshPartition()->getString(); std::cout << "stringRespresentation: \n" << stringRespresentation; std::string reference; if (DihuContext::ownRankNoCommWorld() == 0) { reference = "CompositeMesh, nSubMeshes: 2, removedSharedNodes: [, [1,0] -> [0,4] [1,3] -> [0,9] [1,6] -> [0,14] [1,9] -> [0,19] [1,12] -> [0,24] , ], nElementsLocal: 6, nElementsGlobal: 10, elementNoGlobalBegin: 0, nNodesSharedLocal: 4, nGhostNodesSharedLocal: 1, nRemovedNodesNonGhost: [0, 4, ], nNonDuplicateNodesWithoutGhosts: [20, 8, ], nNodesLocalWithoutGhosts: 28, nNodesLocalWithGhosts: 35, nNodesGlobal: 55, nonDuplicateNodeNoGlobalBegin: 0, meshAndNodeNoLocalToNodeNoNonDuplicateGlobal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,28,29,30,31,32,],[-1,20,21,-1,22,23,-1,24,25,-1,26,27,-1,43,44,],], meshAndNodeNoLocalToNodeNoNonDuplicateLocal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,28,29,30,31,32,],[-1,20,21,-1,22,23,-1,24,25,-1,26,27,-1,33,34,],], isDuplicate: [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,],], nodeNoNonDuplicateLocalToMeshAndDuplicateLocal: [<0,0>,<0,1>,<0,2>,<0,3>,<0,4>,<0,5>,<0,6>,<0,7>,<0,8>,<0,9>,<0,10>,<0,11>,<0,12>,<0,13>,<0,14>,<0,15>,<0,16>,<0,17>,<0,18>,<0,19>,<1,1>,<1,2>,<1,4>,<1,5>,<1,7>,<1,8>,<1,10>,<1,11>,<0,20>,<0,21>,<0,22>,<0,23>,<0,24>,<1,13>,<1,14>,], nonDuplicateGhostNodeNosGlobal: [28,29,30,31,32,43,44,], onlyNodalDofLocalNos: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,], ghostDofNosGlobalPetsc: [28,29,30,31,32,43,44,], nElementsLocal(): 6, nElementsGlobal(): 10, nDofsLocalWithGhosts(): 35, nDofsLocalWithoutGhosts(): 28, nDofsGlobal(): 55, nNodesLocalWithGhosts(): 35, nNodesLocalWithoutGhosts(): 28, nNodesGlobal(): 55, beginNodeGlobalPetsc(): 0, dofNosLocal(true): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,], dofNosLocal(false): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,], ghostDofNosGlobalPetsc(): [28,29,30,31,32,43,44,], getElementNoGlobalNatural: 0->0 1->1 2->2 3->3 4->6 5->7 , getNodeNoGlobalPetsc: 0->0 1->1 2->2 3->3 4->4 5->5 6->6 7->7 8->8 9->9 10->10 11->11 12->12 13->13 14->14 15->15 16->16 17->17 18->18 19->19 20->20 21->21 22->22 23->23 24->24 25->25 26->26 27->27 28->28 29->29 30->30 31->31 32->32 33->43 34->44 , getNodeNoGlobalNatural: 0,0->0 0,1->1 0,2->2 0,3->5 0,4->6 0,5->7 0,6->10 0,7->11 0,8->12 1,0->2 1,1->3 1,2->4 1,3->7 1,4->8 1,5->9 1,6->12 1,7->13 1,8->14 2,0->10 2,1->11 2,2->12 2,3->15 2,4->16 2,5->17 2,6->20 2,7->21 2,8->22 3,0->12 3,1->13 3,2->14 3,3->17 3,4->18 3,5->19 3,6->22 3,7->23 3,8->24 4,0->35 4,1->36 4,2->37 4,3->38 4,4->39 4,5->40 4,6->41 4,7->42 4,8->43 5,0->41 5,1->42 5,2->43 5,3->44 5,4->45 5,5->46 5,6->47 5,7->48 5,8->49 , getDofNoGlobalPetsc: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,43,44,], getDofNoGlobalPetsc: 0->0 1->1 2->2 3->3 4->4 5->5 6->6 7->7 8->8 9->9 10->10 11->11 12->12 13->13 14->14 15->15 16->16 17->17 18->18 19->19 20->20 21->21 22->22 23->23 24->24 25->25 26->26 27->27 28->28 29->29 30->30 31->31 32->32 33->43 34->44 , getElementNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->5->1 6->-1->0 7->-1->0 8->-1->0 9->-1->0 , getNodeNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->5->1 6->6->1 7->7->1 8->8->1 9->9->1 10->10->1 11->11->1 12->12->1 13->13->1 14->14->1 15->15->1 16->16->1 17->17->1 18->18->1 19->19->1 20->20->1 21->21->1 22->22->1 23->23->1 24->24->1 25->25->1 26->26->1 27->27->1 28->28->0 29->29->0 30->30->0 31->31->0 32->32->0 33->33->0 34->34->0 35->35->0 36->36->0 37->37->0 38->38->0 39->39->0 40->40->0 41->41->0 42->42->0 43->43->0 44->44->0 45->45->0 46->46->0 47->47->0 48->48->0 49->49->0 50->50->0 51->51->0 52->52->0 53->53->0 54->54->0 , getDofNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->5->1 6->6->1 7->7->1 8->8->1 9->9->1 10->10->1 11->11->1 12->12->1 13->13->1 14->14->1 15->15->1 16->16->1 17->17->1 18->18->1 19->19->1 20->20->1 21->21->1 22->22->1 23->23->1 24->24->1 25->25->1 26->26->1 27->27->1 28->28->0 29->29->0 30->30->0 31->31->0 32->32->0 33->33->0 34->34->0 35->35->0 36->36->0 37->37->0 38->38->0 39->39->0 40->40->0 41->41->0 42->42->0 43->43->0 44->44->0 45->45->0 46->46->0 47->47->0 48->48->0 49->49->0 50->50->0 51->51->0 52->52->0 53->53->0 54->54->0 , extractLocalNodesWithoutGhosts: [0,20,21,3,22,23,6,24,25,9,26,27,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,], extractLocalDofsWithoutGhosts: [0,20,21,3,22,23,6,24,25,9,26,27,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,], getSubMeshNoAndElementNoLocal: 0->0,0 1->0,1 2->0,2 3->0,3 4->1,0 5->1,1 , getSubMeshNoAndNodeNoLocal: 0->0,0 1->0,1 2->0,2 3->0,3 4->0,4 5->0,5 6->0,6 7->0,7 8->0,8 9->0,9 10->0,10 11->0,11 12->0,12 13->0,13 14->0,14 15->0,15 16->0,16 17->0,17 18->0,18 19->0,19 20->1,1 21->1,2 22->1,4 23->1,5 24->1,7 25->1,8 26->1,10 27->1,11 28->0,20 29->0,21 30->0,22 31->0,23 32->0,24 33->1,12 34->1,13 , getSubMeshesWithNodes: 0->[<0,0> ] 1->[<0,1> ] 2->[<0,2> ] 3->[<0,3> ] 4->[<0,4> <1,0> ] 5->[<0,5> ] 6->[<0,6> ] 7->[<0,7> ] 8->[<0,8> ] 9->[<0,9> <1,3> ] 10->[<0,10> ] 11->[<0,11> ] 12->[<0,12> ] 13->[<0,13> ] 14->[<0,14> <1,6> ] 15->[<0,15> ] 16->[<0,16> ] 17->[<0,17> ] 18->[<0,18> ] 19->[<0,19> <1,9> ] 20->[<1,1> ] 21->[<1,2> ] 22->[<1,4> ] 23->[<1,5> ] 24->[<1,7> ] 25->[<1,8> ] 26->[<1,10> ] 27->[<1,11> ] 28->[<0,20> ] 29->[<0,21> ] 30->[<0,22> ] 31->[<0,23> ] 32->[<0,24> <1,12> ] 33->[<1,12> ] 34->[<1,13> ] "; } else { reference = "CompositeMesh, nSubMeshes: 2, removedSharedNodes: [, [1,0] -> [0,4] [1,3] -> [0,9] [1,6] -> [0,14] , ], nElementsLocal: 4, nElementsGlobal: 10, elementNoGlobalBegin: 6, nNodesSharedLocal: 3, nGhostNodesSharedLocal: 0, nRemovedNodesNonGhost: [0, 3, ], nNonDuplicateNodesWithoutGhosts: [15, 12, ], nNodesLocalWithoutGhosts: 27, nNodesLocalWithGhosts: 27, nNodesGlobal: 55, nonDuplicateNodeNoGlobalBegin: 28, meshAndNodeNoLocalToNodeNoNonDuplicateGlobal: [[28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,],[-1,43,44,-1,45,46,-1,47,48,49,50,51,52,53,54,],], meshAndNodeNoLocalToNodeNoNonDuplicateLocal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,],[-1,15,16,-1,17,18,-1,19,20,21,22,23,24,25,26,],], isDuplicate: [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,],], nodeNoNonDuplicateLocalToMeshAndDuplicateLocal: [<0,0>,<0,1>,<0,2>,<0,3>,<0,4>,<0,5>,<0,6>,<0,7>,<0,8>,<0,9>,<0,10>,<0,11>,<0,12>,<0,13>,<0,14>,<1,1>,<1,2>,<1,4>,<1,5>,<1,7>,<1,8>,<1,9>,<1,10>,<1,11>,<1,12>,<1,13>,<1,14>,], nonDuplicateGhostNodeNosGlobal: [], onlyNodalDofLocalNos: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,], ghostDofNosGlobalPetsc: [], nElementsLocal(): 4, nElementsGlobal(): 10, nDofsLocalWithGhosts(): 27, nDofsLocalWithoutGhosts(): 27, nDofsGlobal(): 55, nNodesLocalWithGhosts(): 27, nNodesLocalWithoutGhosts(): 27, nNodesGlobal(): 55, beginNodeGlobalPetsc(): 28, dofNosLocal(true): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,], dofNosLocal(false): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,], ghostDofNosGlobalPetsc(): [], getElementNoGlobalNatural: 0->4 1->5 2->8 3->9 , getNodeNoGlobalPetsc: 0->28 1->29 2->30 3->31 4->32 5->33 6->34 7->35 8->36 9->37 10->38 11->39 12->40 13->41 14->42 15->43 16->44 17->45 18->46 19->47 20->48 21->49 22->50 23->51 24->52 25->53 26->54 , getNodeNoGlobalNatural: 0,0->20 0,1->21 0,2->22 0,3->25 0,4->26 0,5->27 0,6->30 0,7->31 0,8->32 1,0->22 1,1->23 1,2->24 1,3->27 1,4->28 1,5->29 1,6->32 1,7->33 1,8->34 2,0->47 2,1->48 2,2->49 2,3->50 2,4->51 2,5->52 2,6->53 2,7->54 2,8->55 3,0->53 3,1->54 3,2->55 3,3->56 3,4->57 3,5->58 3,6->59 3,7->60 3,8->61 , getDofNoGlobalPetsc: [28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,], getDofNoGlobalPetsc: 0->28 1->29 2->30 3->31 4->32 5->33 6->34 7->35 8->36 9->37 10->38 11->39 12->40 13->41 14->42 15->43 16->44 17->45 18->46 19->47 20->48 21->49 22->50 23->51 24->52 25->53 26->54 , getElementNoLocal: 0->-1->0 1->-1->0 2->-1->0 3->-1->0 4->-1->0 5->-1->0 6->0->1 7->1->1 8->2->1 9->3->1 , getNodeNoLocal: 0->-28->0 1->-27->0 2->-26->0 3->-25->0 4->-24->0 5->-23->0 6->-22->0 7->-21->0 8->-20->0 9->-19->0 10->-18->0 11->-17->0 12->-16->0 13->-15->0 14->-14->0 15->-13->0 16->-12->0 17->-11->0 18->-10->0 19->-9->0 20->-8->0 21->-7->0 22->-6->0 23->-5->0 24->-4->0 25->-3->0 26->-2->0 27->-1->0 28->0->1 29->1->1 30->2->1 31->3->1 32->4->1 33->5->1 34->6->1 35->7->1 36->8->1 37->9->1 38->10->1 39->11->1 40->12->1 41->13->1 42->14->1 43->15->1 44->16->1 45->17->1 46->18->1 47->19->1 48->20->1 49->21->1 50->22->1 51->23->1 52->24->1 53->25->1 54->26->1 , getDofNoLocal: 0->-28->0 1->-27->0 2->-26->0 3->-25->0 4->-24->0 5->-23->0 6->-22->0 7->-21->0 8->-20->0 9->-19->0 10->-18->0 11->-17->0 12->-16->0 13->-15->0 14->-14->0 15->-13->0 16->-12->0 17->-11->0 18->-10->0 19->-9->0 20->-8->0 21->-7->0 22->-6->0 23->-5->0 24->-4->0 25->-3->0 26->-2->0 27->-1->0 28->0->1 29->1->1 30->2->1 31->3->1 32->4->1 33->5->1 34->6->1 35->7->1 36->8->1 37->9->1 38->10->1 39->11->1 40->12->1 41->13->1 42->14->1 43->15->1 44->16->1 45->17->1 46->18->1 47->19->1 48->20->1 49->21->1 50->22->1 51->23->1 52->24->1 53->25->1 54->26->1 , extractLocalNodesWithoutGhosts: [28,43,44,31,45,46,34,47,48,49,50,51,52,53,54,0,0,0,0,0,0,0,0,0,0,0,0,], extractLocalDofsWithoutGhosts: [28,43,44,31,45,46,34,47,48,49,50,51,52,53,54,0,0,0,0,0,0,0,0,0,0,0,0,], getSubMeshNoAndElementNoLocal: 0->0,0 1->0,1 2->1,0 3->1,1 , getSubMeshNoAndNodeNoLocal: 0->0,0 1->0,1 2->0,2 3->0,3 4->0,4 5->0,5 6->0,6 7->0,7 8->0,8 9->0,9 10->0,10 11->0,11 12->0,12 13->0,13 14->0,14 15->1,1 16->1,2 17->1,4 18->1,5 19->1,7 20->1,8 21->1,9 22->1,10 23->1,11 24->1,12 25->1,13 26->1,14 , getSubMeshesWithNodes: 0->[<0,0> ] 1->[<0,1> ] 2->[<0,2> ] 3->[<0,3> ] 4->[<0,4> <1,0> ] 5->[<0,5> ] 6->[<0,6> ] 7->[<0,7> ] 8->[<0,8> ] 9->[<0,9> <1,3> ] 10->[<0,10> ] 11->[<0,11> ] 12->[<0,12> ] 13->[<0,13> ] 14->[<0,14> <1,6> ] 15->[<1,1> ] 16->[<1,2> ] 17->[<1,4> ] 18->[<1,5> ] 19->[<1,7> ] 20->[<1,8> ] 21->[<1,9> ] 22->[<1,10> ] 23->[<1,11> ] 24->[<1,12> ] 25->[<1,13> ] 26->[<1,14> ] "; } ASSERT_EQ(stringRespresentation, reference); } TEST(CompositeTest, Case1) { // run serial problem std::string pythonConfig = R"( import sys own_rank_no = (int)(sys.argv[-2]) n_ranks = (int)(sys.argv[-1]) print("n_ranks: {}".format(n_ranks)) print("own_rank_no: {}".format(own_rank_no)) meshes = {} if own_rank_no == 0: # rank 0 meshes = { "submesh0": { "nRanks": [1,2], "nElements": [3, 1], "inputMeshIsGlobal": False, "physicalExtent": [3.0, 1.0], }, "submesh1": { "nRanks": [1,2], "nElements": [2, 1], "inputMeshIsGlobal": False, "physicalExtent": [2.0, 1.0], "physicalOffset": [3.0, 0.0], }, } else: # rank 1 meshes = { "submesh0": { "nRanks": [1,2], "nElements": [3, 1], "inputMeshIsGlobal": False, "physicalExtent": [3.0, 1.0], }, "submesh1": { "nRanks": [1,2], "nElements": [2, 1], "inputMeshIsGlobal": False, "physicalExtent": [2.0, 1.0], "physicalOffset": [3.0, 0.0], }, } config = { "Meshes": meshes, "FiniteElementMethod": { "inputMeshIsGlobal": False, "meshName": ["submesh0", "submesh1"], }, } print(config) )"; DihuContext settings(argc, argv, pythonConfig); typedef SpatialDiscretization::FiniteElementMethod< Mesh::CompositeOfDimension<2>, BasisFunction::LagrangeOfOrder<2>, Quadrature::Gauss<1>, Equation::None > ProblemType; ProblemType problem(settings); problem.initialize(); std::string stringRespresentation = problem.data().functionSpace()->meshPartition()->getString(); std::cout << "stringRespresentation: \n" << stringRespresentation; std::string reference; if (DihuContext::ownRankNoCommWorld() == 0) { reference = "CompositeMesh, nSubMeshes: 2, removedSharedNodes: [, [1,0] -> [0,6] [1,5] -> [0,13] [1,10] -> [0,20] , ], nElementsLocal: 5, nElementsGlobal: 10, elementNoGlobalBegin: 0, nNodesSharedLocal: 2, nGhostNodesSharedLocal: 1, nRemovedNodesNonGhost: [0, 2, ], nNonDuplicateNodesWithoutGhosts: [14, 8, ], nNodesLocalWithoutGhosts: 22, nNodesLocalWithGhosts: 33, nNodesGlobal: 55, nonDuplicateNodeNoGlobalBegin: 0, meshAndNodeNoLocalToNodeNoNonDuplicateGlobal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,22,23,24,25,26,27,28,],[-1,14,15,16,17,-1,18,19,20,21,-1,43,44,45,46,],], meshAndNodeNoLocalToNodeNoNonDuplicateLocal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,22,23,24,25,26,27,28,],[-1,14,15,16,17,-1,18,19,20,21,-1,29,30,31,32,],], isDuplicate: [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,],], nodeNoNonDuplicateLocalToMeshAndDuplicateLocal: [<0,0>,<0,1>,<0,2>,<0,3>,<0,4>,<0,5>,<0,6>,<0,7>,<0,8>,<0,9>,<0,10>,<0,11>,<0,12>,<0,13>,<1,1>,<1,2>,<1,3>,<1,4>,<1,6>,<1,7>,<1,8>,<1,9>,<0,14>,<0,15>,<0,16>,<0,17>,<0,18>,<0,19>,<0,20>,<1,11>,<1,12>,<1,13>,<1,14>,], nonDuplicateGhostNodeNosGlobal: [22,23,24,25,26,27,28,43,44,45,46,], onlyNodalDofLocalNos: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,], ghostDofNosGlobalPetsc: [22,23,24,25,26,27,28,43,44,45,46,], nElementsLocal(): 5, nElementsGlobal(): 10, nDofsLocalWithGhosts(): 33, nDofsLocalWithoutGhosts(): 22, nDofsGlobal(): 55, nNodesLocalWithGhosts(): 33, nNodesLocalWithoutGhosts(): 22, nNodesGlobal(): 55, beginNodeGlobalPetsc(): 0, dofNosLocal(true): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,], dofNosLocal(false): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,], ghostDofNosGlobalPetsc(): [22,23,24,25,26,27,28,43,44,45,46,], getElementNoGlobalNatural: 0->0 1->1 2->2 3->6 4->7 , getNodeNoGlobalPetsc: 0->0 1->1 2->2 3->3 4->4 5->5 6->6 7->7 8->8 9->9 10->10 11->11 12->12 13->13 14->14 15->15 16->16 17->17 18->18 19->19 20->20 21->21 22->22 23->23 24->24 25->25 26->26 27->27 28->28 29->43 30->44 31->45 32->46 , getNodeNoGlobalNatural: 0,0->0 0,1->1 0,2->2 0,3->7 0,4->8 0,5->9 0,6->14 0,7->15 0,8->16 1,0->2 1,1->3 1,2->4 1,3->9 1,4->10 1,5->11 1,6->16 1,7->17 1,8->18 2,0->4 2,1->5 2,2->6 2,3->11 2,4->12 2,5->13 2,6->18 2,7->19 2,8->20 3,0->35 3,1->36 3,2->37 3,3->40 3,4->41 3,5->42 3,6->45 3,7->46 3,8->47 4,0->37 4,1->38 4,2->39 4,3->42 4,4->43 4,5->44 4,6->47 4,7->48 4,8->49 , getDofNoGlobalPetsc: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,43,44,45,46,], getDofNoGlobalPetsc: 0->0 1->1 2->2 3->3 4->4 5->5 6->6 7->7 8->8 9->9 10->10 11->11 12->12 13->13 14->14 15->15 16->16 17->17 18->18 19->19 20->20 21->21 22->22 23->23 24->24 25->25 26->26 27->27 28->28 29->43 30->44 31->45 32->46 , getElementNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->-1->0 6->-1->0 7->-1->0 8->-1->0 9->-1->0 , getNodeNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->5->1 6->6->1 7->7->1 8->8->1 9->9->1 10->10->1 11->11->1 12->12->1 13->13->1 14->14->1 15->15->1 16->16->1 17->17->1 18->18->1 19->19->1 20->20->1 21->21->1 22->22->0 23->23->0 24->24->0 25->25->0 26->26->0 27->27->0 28->28->0 29->29->0 30->30->0 31->31->0 32->32->0 33->33->0 34->34->0 35->35->0 36->36->0 37->37->0 38->38->0 39->39->0 40->40->0 41->41->0 42->42->0 43->43->0 44->44->0 45->45->0 46->46->0 47->47->0 48->48->0 49->49->0 50->50->0 51->51->0 52->52->0 53->53->0 54->54->0 , getDofNoLocal: 0->0->1 1->1->1 2->2->1 3->3->1 4->4->1 5->5->1 6->6->1 7->7->1 8->8->1 9->9->1 10->10->1 11->11->1 12->12->1 13->13->1 14->14->1 15->15->1 16->16->1 17->17->1 18->18->1 19->19->1 20->20->1 21->21->1 22->22->0 23->23->0 24->24->0 25->25->0 26->26->0 27->27->0 28->28->0 29->29->0 30->30->0 31->31->0 32->32->0 33->33->0 34->34->0 35->35->0 36->36->0 37->37->0 38->38->0 39->39->0 40->40->0 41->41->0 42->42->0 43->43->0 44->44->0 45->45->0 46->46->0 47->47->0 48->48->0 49->49->0 50->50->0 51->51->0 52->52->0 53->53->0 54->54->0 , extractLocalNodesWithoutGhosts: [0,14,15,16,17,5,18,19,20,21,10,11,12,13,0,0,0,0,0,0,0,0,], extractLocalDofsWithoutGhosts: [0,14,15,16,17,5,18,19,20,21,10,11,12,13,0,0,0,0,0,0,0,0,], getSubMeshNoAndElementNoLocal: 0->0,0 1->0,1 2->0,2 3->1,0 4->1,1 , getSubMeshNoAndNodeNoLocal: 0->0,0 1->0,1 2->0,2 3->0,3 4->0,4 5->0,5 6->0,6 7->0,7 8->0,8 9->0,9 10->0,10 11->0,11 12->0,12 13->0,13 14->1,1 15->1,2 16->1,3 17->1,4 18->1,6 19->1,7 20->1,8 21->1,9 22->0,14 23->0,15 24->0,16 25->0,17 26->0,18 27->0,19 28->0,20 29->1,10 30->1,11 31->1,12 32->1,13 , getSubMeshesWithNodes: 0->[<0,0> ] 1->[<0,1> ] 2->[<0,2> ] 3->[<0,3> ] 4->[<0,4> ] 5->[<0,5> ] 6->[<0,6> <1,0> ] 7->[<0,7> ] 8->[<0,8> ] 9->[<0,9> ] 10->[<0,10> ] 11->[<0,11> ] 12->[<0,12> ] 13->[<0,13> <1,5> ] 14->[<1,1> ] 15->[<1,2> ] 16->[<1,3> ] 17->[<1,4> ] 18->[<1,6> ] 19->[<1,7> ] 20->[<1,8> ] 21->[<1,9> ] 22->[<0,14> ] 23->[<0,15> ] 24->[<0,16> ] 25->[<0,17> ] 26->[<0,18> ] 27->[<0,19> ] 28->[<0,20> <1,10> ] 29->[<1,10> ] 30->[<1,11> ] 31->[<1,12> ] 32->[<1,13> ] "; } else { reference = "CompositeMesh, nSubMeshes: 2, removedSharedNodes: [, [1,0] -> [0,6] [1,5] -> [0,13] [1,10] -> [0,20] , ], nElementsLocal: 5, nElementsGlobal: 10, elementNoGlobalBegin: 5, nNodesSharedLocal: 3, nGhostNodesSharedLocal: 0, nRemovedNodesNonGhost: [0, 3, ], nNonDuplicateNodesWithoutGhosts: [21, 12, ], nNodesLocalWithoutGhosts: 33, nNodesLocalWithGhosts: 33, nNodesGlobal: 55, nonDuplicateNodeNoGlobalBegin: 22, meshAndNodeNoLocalToNodeNoNonDuplicateGlobal: [[22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,],[-1,43,44,45,46,-1,47,48,49,50,-1,51,52,53,54,],], meshAndNodeNoLocalToNodeNoNonDuplicateLocal: [[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,],[-1,21,22,23,24,-1,25,26,27,28,-1,29,30,31,32,],], isDuplicate: [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,],], nodeNoNonDuplicateLocalToMeshAndDuplicateLocal: [<0,0>,<0,1>,<0,2>,<0,3>,<0,4>,<0,5>,<0,6>,<0,7>,<0,8>,<0,9>,<0,10>,<0,11>,<0,12>,<0,13>,<0,14>,<0,15>,<0,16>,<0,17>,<0,18>,<0,19>,<0,20>,<1,1>,<1,2>,<1,3>,<1,4>,<1,6>,<1,7>,<1,8>,<1,9>,<1,11>,<1,12>,<1,13>,<1,14>,], nonDuplicateGhostNodeNosGlobal: [], onlyNodalDofLocalNos: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,], ghostDofNosGlobalPetsc: [], nElementsLocal(): 5, nElementsGlobal(): 10, nDofsLocalWithGhosts(): 33, nDofsLocalWithoutGhosts(): 33, nDofsGlobal(): 55, nNodesLocalWithGhosts(): 33, nNodesLocalWithoutGhosts(): 33, nNodesGlobal(): 55, beginNodeGlobalPetsc(): 22, dofNosLocal(true): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,], dofNosLocal(false): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,], ghostDofNosGlobalPetsc(): [], getElementNoGlobalNatural: 0->3 1->4 2->5 3->8 4->9 , getNodeNoGlobalPetsc: 0->22 1->23 2->24 3->25 4->26 5->27 6->28 7->29 8->30 9->31 10->32 11->33 12->34 13->35 14->36 15->37 16->38 17->39 18->40 19->41 20->42 21->43 22->44 23->45 24->46 25->47 26->48 27->49 28->50 29->51 30->52 31->53 32->54 , getNodeNoGlobalNatural: 0,0->14 0,1->15 0,2->16 0,3->21 0,4->22 0,5->23 0,6->28 0,7->29 0,8->30 1,0->16 1,1->17 1,2->18 1,3->23 1,4->24 1,5->25 1,6->30 1,7->31 1,8->32 2,0->18 2,1->19 2,2->20 2,3->25 2,4->26 2,5->27 2,6->32 2,7->33 2,8->34 3,0->45 3,1->46 3,2->47 3,3->50 3,4->51 3,5->52 3,6->55 3,7->56 3,8->57 4,0->47 4,1->48 4,2->49 4,3->52 4,4->53 4,5->54 4,6->57 4,7->58 4,8->59 , getDofNoGlobalPetsc: [22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,], getDofNoGlobalPetsc: 0->22 1->23 2->24 3->25 4->26 5->27 6->28 7->29 8->30 9->31 10->32 11->33 12->34 13->35 14->36 15->37 16->38 17->39 18->40 19->41 20->42 21->43 22->44 23->45 24->46 25->47 26->48 27->49 28->50 29->51 30->52 31->53 32->54 , getElementNoLocal: 0->-1->0 1->-1->0 2->-1->0 3->-1->0 4->-1->0 5->0->1 6->1->1 7->2->1 8->3->1 9->4->1 , getNodeNoLocal: 0->-22->0 1->-21->0 2->-20->0 3->-19->0 4->-18->0 5->-17->0 6->-16->0 7->-15->0 8->-14->0 9->-13->0 10->-12->0 11->-11->0 12->-10->0 13->-9->0 14->-8->0 15->-7->0 16->-6->0 17->-5->0 18->-4->0 19->-3->0 20->-2->0 21->-1->0 22->0->1 23->1->1 24->2->1 25->3->1 26->4->1 27->5->1 28->6->1 29->7->1 30->8->1 31->9->1 32->10->1 33->11->1 34->12->1 35->13->1 36->14->1 37->15->1 38->16->1 39->17->1 40->18->1 41->19->1 42->20->1 43->21->1 44->22->1 45->23->1 46->24->1 47->25->1 48->26->1 49->27->1 50->28->1 51->29->1 52->30->1 53->31->1 54->32->1 , getDofNoLocal: 0->-22->0 1->-21->0 2->-20->0 3->-19->0 4->-18->0 5->-17->0 6->-16->0 7->-15->0 8->-14->0 9->-13->0 10->-12->0 11->-11->0 12->-10->0 13->-9->0 14->-8->0 15->-7->0 16->-6->0 17->-5->0 18->-4->0 19->-3->0 20->-2->0 21->-1->0 22->0->1 23->1->1 24->2->1 25->3->1 26->4->1 27->5->1 28->6->1 29->7->1 30->8->1 31->9->1 32->10->1 33->11->1 34->12->1 35->13->1 36->14->1 37->15->1 38->16->1 39->17->1 40->18->1 41->19->1 42->20->1 43->21->1 44->22->1 45->23->1 46->24->1 47->25->1 48->26->1 49->27->1 50->28->1 51->29->1 52->30->1 53->31->1 54->32->1 , extractLocalNodesWithoutGhosts: [22,43,44,45,46,27,47,48,49,50,32,51,52,53,54,37,38,39,40,41,42,0,0,0,0,0,0,0,0,0,0,0,0,], extractLocalDofsWithoutGhosts: [22,43,44,45,46,27,47,48,49,50,32,51,52,53,54,37,38,39,40,41,42,0,0,0,0,0,0,0,0,0,0,0,0,], getSubMeshNoAndElementNoLocal: 0->0,0 1->0,1 2->0,2 3->1,0 4->1,1 , getSubMeshNoAndNodeNoLocal: 0->0,0 1->0,1 2->0,2 3->0,3 4->0,4 5->0,5 6->0,6 7->0,7 8->0,8 9->0,9 10->0,10 11->0,11 12->0,12 13->0,13 14->0,14 15->0,15 16->0,16 17->0,17 18->0,18 19->0,19 20->0,20 21->1,1 22->1,2 23->1,3 24->1,4 25->1,6 26->1,7 27->1,8 28->1,9 29->1,11 30->1,12 31->1,13 32->1,14 , getSubMeshesWithNodes: 0->[<0,0> ] 1->[<0,1> ] 2->[<0,2> ] 3->[<0,3> ] 4->[<0,4> ] 5->[<0,5> ] 6->[<0,6> <1,0> ] 7->[<0,7> ] 8->[<0,8> ] 9->[<0,9> ] 10->[<0,10> ] 11->[<0,11> ] 12->[<0,12> ] 13->[<0,13> <1,5> ] 14->[<0,14> ] 15->[<0,15> ] 16->[<0,16> ] 17->[<0,17> ] 18->[<0,18> ] 19->[<0,19> ] 20->[<0,20> <1,10> ] 21->[<1,1> ] 22->[<1,2> ] 23->[<1,3> ] 24->[<1,4> ] 25->[<1,6> ] 26->[<1,7> ] 27->[<1,8> ] 28->[<1,9> ] 29->[<1,11> ] 30->[<1,12> ] 31->[<1,13> ] 32->[<1,14> ] "; } ASSERT_EQ(stringRespresentation, reference); }
e51dfa29c927b0870dcff3e5f8adbe45716460c2
d46788ac1bd03854adae8370ccb188b8928f1c21
/fifth/3/源.cpp
14129bccbc9030c1ca30730cca075d26c75c1960
[]
no_license
Wansit99/ZhengLi--
258af73d1f6b2f87296f50c3c49a169c3e8c1762
d32753a9e51db6a211f5e256bf6615d1e487faaa
refs/heads/main
2023-03-07T01:10:27.957373
2021-02-20T13:05:05
2021-02-20T13:05:05
340,651,433
0
0
null
null
null
null
UTF-8
C++
false
false
828
cpp
源.cpp
#include <iostream> using namespace std; class Date { private: int year; int month; int day; public: Date(int x, int y, int z) :year(x), month(y), day(z) {} friend class Time; }; class Time { private: int hour; int minute; int second; public: Time(int hh, int mm, int ss) :hour(hh), minute(mm), second(ss) {} void display(Date &a) { cout << a.year << '/' << a.month << '/' << a.day << endl; cout << hour << ':' << minute << ':' << second; } }; int main() { int year, month, day; cin >> year >> month >> day; Date d1(year, month, day); int hour, minute, second; cin >> hour >> minute >> second; Time t1(hour, minute, second); t1.display(d1); return 0; }
e34cdec73b92eb52232903b4c6e2177fc59c7a49
059f0375acc3b9ae61696eb40fa2b4446b18ea9e
/other_stellarium_python_servers/leon_rosengarten/Deadon/deadon.cpp
94535fad344b32e245f77818d782a6277f63bbb3
[]
no_license
EmmanuelSchaan/DIYGotoMount
206a793eb5358a92a656c3c25647000041e5a8bf
28d7b5876e063d026c61688d1a8ef84ca4516a4b
refs/heads/master
2023-05-30T17:55:08.529767
2021-06-18T00:50:45
2021-06-18T00:50:45
298,691,203
0
0
null
null
null
null
UTF-8
C++
false
false
2,170
cpp
deadon.cpp
#include <Arduino.h> #include "deadon.h" #include <SPI.h> DEADON::DEADON(int ssPin) { csPin = ssPin; } void DEADON::RTC_init() { pinMode(csPin,OUTPUT); // chip select // start the SPI library: SPI.begin(); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE1); // both mode 1 & 3 should work //set control register digitalWrite(csPin, LOW); //Enable oscillator, disable square wave, alarms SPI.transfer(CONTROL_W); SPI.transfer(0x0); digitalWrite(csPin, HIGH); delay(1); //Clear oscilator stop flag, 32kHz pin digitalWrite(csPin, LOW); SPI.transfer(CONTROL_STATUS_W); SPI.transfer(0x0); digitalWrite(csPin, HIGH); delay(1); } void DEADON::RtcSetTimeDate(int d, int mo, int y, int h, int mi, int s) { int TimeDate [7]={ s,mi,h,0,d,mo,y }; for(int i=0; i<=6;i++){ if(i==3) i++; int b= TimeDate[i]/10; int a= TimeDate[i]-b*10; if(i==2){ if (b==2) b=B00000010; else if (b==1) b=B00000001; } TimeDate[i]= a+(b<<4); digitalWrite(csPin, LOW); SPI.transfer(i+0x80); SPI.transfer(TimeDate[i]); digitalWrite(csPin, HIGH); } } void DEADON::RtcReadTimeDate(int &hh, int &mm, int &ss, int &dd, int &mon, int &yy) { int TimeDate [7]; //second,minute,hour,null,day,month,year for(int i=0; i<=6;i++){ if(i==3) i++; digitalWrite(csPin, LOW); SPI.transfer(i+0x00); unsigned int n = SPI.transfer(0x00); digitalWrite(csPin, HIGH); int a=n & B00001111; if(i==2){ int b=(n & B00110000)>>4; //24 hour mode if(b==B00000010) b=20; else if(b==B00000001) b=10; TimeDate[i]=a+b; } else if(i==4){ int b=(n & B00110000)>>4; TimeDate[i]=a+b*10; } else if(i==5){ int b=(n & B00010000)>>4; TimeDate[i]=a+b*10; } else if(i==6){ int b=(n & B11110000)>>4; TimeDate[i]=a+b*10; } else{ int b=(n & B01110000)>>4; TimeDate[i]=a+b*10; } } hh = TimeDate[2]; mm = TimeDate[1]; ss = TimeDate[0]; dd = TimeDate[4]; mon = TimeDate[5]; yy = TimeDate[6]; }
46fcdb17252ec292e0a75043a12474c0f00d6df6
28b4979073dfa53705c3993d1fb2ace26461cb19
/programs/lsim/LsimBdd1.h
91a205f8926c763fdfd48872f05ce8743df290be
[]
no_license
yusuke-matsunaga/ym-apps
51c826e510a91d7c4f6e5c4252a2afb91a5f30ce
185c9aa876a95fcad4772db2ba270ba8fd53e1ac
refs/heads/master
2016-09-16T15:38:13.272565
2015-11-01T04:33:49
2015-11-01T04:33:49
38,557,898
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
h
LsimBdd1.h
#ifndef LSIMBDD1_H #define LSIMBDD1_H /// @file LsimBdd1.h /// @brief LsimBdd1 のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2011 Yusuke Matsunaga /// All rights reserved. #include "Lsim.h" #include "YmLogic/Bdd.h" #include "YmLogic/BddMgr.h" BEGIN_NAMESPACE_YM ////////////////////////////////////////////////////////////////////// /// @class LsimBdd1 LsimBdd1.h "LsimBdd1.h" /// @brief BDD を用いた Lsim の実装 ////////////////////////////////////////////////////////////////////// class LsimBdd1 : public Lsim { public: /// @brief コンストラクタ LsimBdd1(); /// @brief デストラクタ virtual ~LsimBdd1(); public: ////////////////////////////////////////////////////////////////////// // Lsim の仮想関数 ////////////////////////////////////////////////////////////////////// /// @brief ネットワークをセットする. /// @param[in] bdn 対象のネットワーク /// @param[in] order_map 順序マップ virtual void set_network(const BdnMgr& bdn, const unordered_map<string, ymuint>& order_map); /// @brief 論理シミュレーションを行う. /// @param[in] iv 入力ベクタ /// @param[out] ov 出力ベクタ virtual void eval(const vector<ymuint64>& iv, vector<ymuint64>& ov); private: ////////////////////////////////////////////////////////////////////// // 内部で用いられる関数 ////////////////////////////////////////////////////////////////////// ympuint make_node(Bdd bdd, unordered_map<Bdd, ympuint>& node_map); public: ////////////////////////////////////////////////////////////////////// // 内部で用いられるデータ構造 ////////////////////////////////////////////////////////////////////// struct Bdd1Node { Bdd1Node(VarId id, ympuint node0, ympuint node1) { mId = id; mFanins[0] = node0; mFanins[1] = node1; } VarId mId; ympuint mFanins[2]; }; private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // BDD の管理用オブジェクト BddMgr mBddMgr; // ノードの配列 vector<Bdd1Node*> mNodeList; // 出力のノードの配列 vector<ympuint> mOutputList; }; END_NAMESPACE_YM #endif // LSIMBDD1_H
4ef2e6576c319bbf0ecd3fe7d45ee85f735f415c
5cfbbc62f2c94ccb34cdd549490db6d0413bfd24
/MyVideoStabilizer/motionvector.cpp
e7503e1f5147c884666789ba96ab05b760117fcc
[]
no_license
postasze/Video-Stabilization-Algorithm
437ae0e49def822e6a7583325394b3fc3f624a7c
c9c7579fc6e834075a3186aea4cc467ab16d0afe
refs/heads/master
2021-04-07T21:36:05.770370
2020-07-10T13:05:12
2020-07-10T13:05:12
248,710,548
2
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
motionvector.cpp
#include "motionvector.h" MotionVector::MotionVector() { this->x = 0; this->y = 0; this->startPoint = cv::Point2f(0, 0); this->endPoint = cv::Point2f(0, 0); this->magnitude = 0; this->angle = 0; } MotionVector::MotionVector(cv::Point2f startPoint, cv::Point2f endPoint) { this->x = endPoint.x - startPoint.x; this->y = endPoint.y - startPoint.y; this->startPoint = startPoint; this->endPoint = endPoint; this->calculateMagnitude(); this->calculateAngle(); } MotionVector::MotionVector(const MotionVector& motionVector) { this->x = motionVector.x; this->y = motionVector.y; this->startPoint = motionVector.startPoint; this->endPoint = motionVector.endPoint; this->magnitude = motionVector.magnitude; this->angle = motionVector.angle; } double MotionVector::calculateMagnitude(MotionVector motionVector) { return sqrt(pow(motionVector.x, 2) + pow(motionVector.y, 2)); } double MotionVector::calculateAngle(MotionVector motionVector) { return atan2(motionVector.y, motionVector.x); } void MotionVector::calculateMagnitude() { this->magnitude = sqrt(pow(this->x, 2) + pow(this->y, 2)); } void MotionVector::calculateAngle() { this->angle = atan2(this->y, this->x); } bool MotionVector::magnitudesComparer(MotionVector firstMotionVector, MotionVector secondMotionVector) { return (firstMotionVector.magnitude < secondMotionVector.magnitude); } bool MotionVector::anglesComparer(MotionVector firstMotionVector, MotionVector secondMotionVector) { return (firstMotionVector.angle < secondMotionVector.angle); }
5cd21237d4f82885fa41f1ec5e8c756492cbaed2
3ae18db84d0aba32bf473d7902e466cec26e6897
/cpp-primer/type_conversion.cc
4fffa6bb32ece2ab49472edd5a1a160801519251
[ "MIT" ]
permissive
sylsaint/cpp_learning
59f8c18d78699cb3c27ec6d1bb3361edb5515eb3
158bdf6186a38838ef16f9739e436b17518a56ba
refs/heads/master
2021-01-12T08:03:46.036808
2018-09-21T09:58:03
2018-09-21T09:58:03
77,113,208
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cc
type_conversion.cc
#include<iostream> int main() { bool b = 42; // b is true std::cout << b << std::endl; int i = b; // i has value 1 std::cout << i << std::endl; i = 3.14; // i has value 3 std::cout << i << std::endl; double pi = i;  // pi has value 3.0 std::cout << pi << std::endl; unsigned char c = -1;   // assuming 8-bit chars, c has value 255 std::cout << "c: " << c << std::endl; signed char c2 = 256;   // assuming 8-bit chars, the value of c2 is undefined” std::cout << "c2: " << c2 << std::endl; // test implicit type conversion // below is int to unsigned int m = -42; unsigned int n = 24; std::cout << m + m << std::endl; std::cout << m + n << std::endl; // if 32bits-int, it will output 4294967264 // unsigned int arithmatic unsigned int u1 = 40, u2 = 10; std::cout << u1 - u2 << std::endl; // ok, output 30 std::cout << u2 - u1 << std::endl; // ok, but result will be wrapped around // unsigned loop unsigned loop = 10; while (loop > 0) { std::cout << --loop << std::endl; } return 0; }
cb54873dd422de5840c933bb7587e55c2d6af641
e04f52ed50f42ad255c66d7b6f87ba642f41e125
/appseed/aura/net/net_address.h
69aecfa37b82b035c48c3915cc4420c0b33df01a
[]
no_license
ca2/app2018
6b5f3cfecaa56b0e8c8ec92ed26e8ce44f9b44c0
89e713c36cdfb31329e753ba9d7b9ff5b80fe867
refs/heads/main
2023-03-19T08:41:48.729250
2018-11-15T16:27:31
2018-11-15T16:27:31
98,031,531
3
0
null
null
null
null
UTF-8
C++
false
false
3,999
h
net_address.h
#pragma once #if defined(LINUX) #include <netdb.h> #define in_addr6 in6_addr #elif defined(VSNORD) #include <netdb.h> #include <netinet/in.h> #define in_addr6 in6_addr #endif namespace net { class CLASS_DECL_AURA address { public: //#if defined METROWIN && defined(__cplusplus_winrt) // // class CLASS_DECL_AURA os_data // { // public: // // ::Windows::Networking::HostName ^ m_hostname; // ::String ^ m_strService; // // }; // //#else //class os_data; //#endif union address_union { struct address_struct { uint16_t m_family; uint16_t m_port; } s; struct sockaddr_in m_addr; struct sockaddr_in6 m_addr6; struct sockaddr m_sa; } u; int m_iLen; //#ifdef METROWIN // // os_data * m_posdata; // //#endif address(); address(int32_t family,port_t port = 0); address(const string & strAddress,port_t port = 0); address(::aura::application * papp,const string & strAddress,const string & strServiceName); address(const in_addr & a,port_t port = 0); address(const in6_addr & a,port_t port = 0); address(const sockaddr_in & a); address(const sockaddr_in6 & a, int iLen = -1); address(const sockaddr & sa, int iLen = -1); address(const address & address); ~address(); address & operator = (const address & address); bool operator == (const address & address) const; inline void copy(const address & address); string get_display_number() const; inline port_t get_service_number() const; inline void set_service_number(port_t iPort); bool is_in_same_net(const address & addr,const address & addrMask) const; bool is_equal(const address & addr) const; inline bool is_ipv4() const; inline bool is_ipv6() const; inline bool is_valid() const; inline int32_t get_family() const; inline sockaddr * sa(); inline const sockaddr * sa() const; int32_t sa_len() const; void * addr_data(); bool set_address(const string & strAddress); //string reverse() const; inline void SetFlowinfo(uint32_t x); inline uint32_t GetFlowinfo(); #ifndef WINDOWS inline void SetScopeId(uint32_t x); inline uint32_t GetScopeId(); #endif void sync_os_address(); void sync_os_service(); }; inline int32_t address::get_family() const { return u.s.m_family; } inline port_t address::get_service_number() const { return ntohs(u.s.m_port); } inline void address::set_service_number(port_t port) { u.s.m_port = htons(port); } inline bool address::is_ipv4() const { return u.s.m_family == AF_INET; } inline bool address::is_ipv6() const { return u.s.m_family == AF_INET6; } inline bool address::is_valid() const { return is_ipv6() || is_ipv4() //#if defined METROWIN && defined(__cplusplus_winrt) // || (m_posdata != NULL && m_posdata->m_hostname != nullptr) //#endif ; } inline sockaddr * address::sa() { return &u.m_sa; } inline const sockaddr * address::sa() const { return &u.m_sa; } inline void address::SetFlowinfo(uint32_t x) { ASSERT(is_ipv6()); u.m_addr6.sin6_flowinfo = x; } inline uint32_t address::GetFlowinfo() { ASSERT(is_ipv6()); return u.m_addr6.sin6_flowinfo; } #ifndef WINDOWS inline void address::SetScopeId(uint32_t x) { ASSERT(is_ipv6()); u.m_addr6.sin6_scope_id = x; } inline uint32_t address::GetScopeId() { ASSERT(is_ipv6()); return u.m_addr6.sin6_scope_id; } #endif address ipv4(uint32_t ui, port_t port = 0); address ipv6(void * p128bits, port_t port = 0); } // namespace sockets
e1898d94f67001565636234e9cdad6a48cfd36f0
45364deefe009a0df9e745a4dd4b680dcedea42b
/SDK/FSD_ABP_Gatling_parameters.hpp
7c9928ffe6f9f5a54d41fa34c7dc6ab4115395ba
[]
no_license
RussellJerome/DeepRockGalacticSDK
5ae9b59c7324f2a97035f28545f92773526ed99e
f13d9d8879a645c3de89ad7dc6756f4a7a94607e
refs/heads/master
2022-11-26T17:55:08.185666
2020-07-26T21:39:30
2020-07-26T21:39:30
277,796,048
0
0
null
null
null
null
UTF-8
C++
false
false
993
hpp
FSD_ABP_Gatling_parameters.hpp
#pragma once // DeepRockGalactic SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "FSD_ABP_Gatling_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ABP_Gatling.ABP_Gatling_C.EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Gatling_AnimGraphNode_TransitionResult_C43F1AB0406296EBFD76D282EDD7538C struct UABP_Gatling_C_EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Gatling_AnimGraphNode_TransitionResult_C43F1AB0406296EBFD76D282EDD7538C_Params { }; // Function ABP_Gatling.ABP_Gatling_C.ExecuteUbergraph_ABP_Gatling struct UABP_Gatling_C_ExecuteUbergraph_ABP_Gatling_Params { int* EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
01589e66ad989c9904f2ea73f6062252f6305948
844439f89c42872e1db6339f922c7445bdc829d7
/logger/log_file.h
eb892c8eb0e7f30ee7a89f87cae7749cb7253dcc
[]
no_license
csyangbinbin/filelogger
bfb234de9580b14515062a98888a4d14580099a2
5d9150a77b800c7c7411f04ea153c8001fdaf159
refs/heads/master
2021-01-01T18:32:21.582547
2017-07-26T00:56:31
2017-07-26T00:56:31
98,362,787
0
0
null
null
null
null
GB18030
C++
false
false
7,361
h
log_file.h
/******************************************************************** created: 2013/07/17 created: 17:7:2013 8:16 filename: log_file.h file path: logfile file base: log_file file ext: h author: purpose: 异步日志记录(主要算法参考muduo) License: // Muduo - A reactor-based C++ network library for Linux // Copyright (c) 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * The name of the author may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #ifndef __LOG_FILE_INCLUDE__ #define __LOG_FILE_INCLUDE__ #include <stdio.h> #include <string> #include <boost/utility.hpp> #include <boost/scoped_ptr.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/thread.hpp> #include <windows.h> #include "threadctrl/threadctrl.h" #include "threadctrl/threadctrl_ext.h" #include "singleton.h" #define FILE_SIZE_1K (1024) #define FILE_SIZE_1M (1024*FILE_SIZE_1K) #define FILE_SIZE_1G (1024*FILE_SIZE_1M) namespace fst_log_file { class fast_file : boost::noncopyable { public: explicit fast_file(const std::string& filename); ~fast_file(); void append(const char* logline, const size_t len); void flush(); size_t writtenBytes() const { return writtenBytes_; } private: size_t write(const char* logline, size_t len) ; FILE* fp_; size_t writtenBytes_; }; class log_file : boost::noncopyable { public: log_file(const std::string& basename, size_t rollSize = 4*FILE_SIZE_1M, int checkEveryN = 20, bool threadSafe = true , int flushInterval = 2); ~log_file(); void append(const char* logline, int len); void flush(); static std::string getLogFileName(const std::string& basename, time_t* now) ; private: void append_unlocked(const char* logline, int len); bool rollFile() ; const std::string basename_; const int flushInterval_; time_t lastFlush_; time_t startOfPeriod_; time_t lastRoll_; void* mutex_ ; size_t rollSize_ ; int count_ ; int checkEveryN_ ; boost::scoped_ptr<fast_file> file_; const static int kRollPerSeconds_ = 60*60*24; }; const int kSmallBuffer = 4000; const int kLargeBuffer = 4000*1000; template<int SIZE> class FixedBuffer : boost::noncopyable { public: FixedBuffer() : cur_(data_) {} ~FixedBuffer(){} void append(const char* buf, size_t len){ if ((size_t)avail() > len){ memcpy(cur_, buf, len); cur_ += len; } } const char* data() const { return data_; } int length() const { return static_cast<int>(cur_ - data_); } char* current() { return cur_; } int avail() const { return static_cast<int>(end() - cur_); } void add(size_t len) { cur_ += len; } void reset_buffer() { cur_ = data_; } void bzero() { ::memset(data_, 0 , sizeof(data_) ) ; } private: const char* end() const { return data_ + sizeof data_; } char data_[SIZE]; char* cur_; }; //每条日志的最大字节数 #define MAX_LOG_BUFFER_SIZE (512) class async_logging : boost::noncopyable { public: async_logging(const std::string& basename,int flushInterval = 2); ~async_logging(); void append(const char* logline, int len); void start(); void stop(); private: async_logging(const async_logging&); // ptr_container async_logging& operator=(const async_logging&); // ptr_container void threadFunc(); typedef FixedBuffer<kSmallBuffer> Buffer; typedef boost::ptr_vector<Buffer> BufferVector; typedef BufferVector::auto_type BufferPtr; const int flushInterval_; volatile bool running_; std::string basename_; void* mutex_ ; void* cond_ ; BufferPtr currentBuffer_; BufferPtr nextBuffer_; BufferVector buffers_; countdown_latch latch_ ; boost::thread* log_thread ; }; enum LogLevel { DEBUG_LEVEL =0, INFO_LEVEL, WARN_LEVEL, ERR_LEVEL, NULL_LEVEL }; class logger { DECLARE_SINGLETON_CLASS(logger); public: void init(const std::string& log_in_dir ,const std::string&basename ,LogLevel level) ; bool load_config(const std::string& filename); void log(LogLevel level ,const char *logstr, ... ); void stop(); protected: logger() :is_console_log(false) ,is_file_log(false) {} private: logger(const logger&); logger& operator=(const logger&) ; private: void console_output(LogLevel level , const char* buffer , int len ); void logfile_output(LogLevel level , const char* buffer , int len) ; bool config_set_log_level(std::string& cfg , LogLevel& level) ; bool create_log_dir(); void start_logging(); private: std::string basename_ ; LogLevel console_level_ , logfile_level_ ; boost::scoped_ptr<async_logging> logfilePtr_ ; bool is_console_log , is_file_log ; HANDLE hOut; std::string log_dir_; }; typedef pattern::singleton<logger> sln_logger ; #define LOG_LOAD_CONFIG(file) fst_log_file::sln_logger::instance().load_config(file) #if defined(USE_LOG_FILE) //使用logfile日志 #define LOG_DBG(...) fst_log_file::sln_logger::instance().log( fst_log_file::DEBUG_LEVEL, __VA_ARGS__); #define LOG_DEBUG(...) fst_log_file::sln_logger::instance().log( fst_log_file::DEBUG_LEVEL, __VA_ARGS__); #define LOG_INFO(...) fst_log_file::sln_logger::instance().log( fst_log_file::INFO_LEVEL, __VA_ARGS__); #define LOG_WARN(...) fst_log_file::sln_logger::instance().log( fst_log_file::WARN_LEVEL, __VA_ARGS__); #define LOG_ERR(...) fst_log_file::sln_logger::instance().log( fst_log_file::ERR_LEVEL, __VA_ARGS__); #define LOG_ERROR(...) fst_log_file::sln_logger::instance().log( fst_log_file::ERR_LEVEL, __VA_ARGS__); #else //不使用logfile日志,仅仅将日志重定向到标准输出 #define LOG_DBG(...) printf( __VA_ARGS__); #define LOG_DEBUG(...) printf( __VA_ARGS__); #define LOG_INFO(...) printf( __VA_ARGS__); #define LOG_WARN(...) printf( __VA_ARGS__); #define LOG_ERR(...) printf( __VA_ARGS__); #define LOG_ERROR(...) printf( __VA_ARGS__); #endif } #endif
11c5bd6caa5bcab9e190d31da27d249c412192d9
3557afba2127184fba12300f6721e1470aee1d69
/ICPC_Cluc.cpp
435ad3fc0b53503a39ce95d5e547256e6042abaf
[]
no_license
Noiri/icpc_practice2018
7a12907f4386c51478dee0e79a15441add9e243b
d90dbf1a3ede2c8e58156fe936f918aaa7974aba
refs/heads/master
2020-03-19T14:34:25.849084
2018-06-28T08:48:27
2018-06-28T08:48:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
ICPC_Cluc.cpp
#include<bits/stdc++.h> using namespace std; //operand, level vector<pair<string, int> > v; int main(){ int n; cin >> n; int max_level = 0; for(int i = 0; i < n; i++){ string tmp; cin >> tmp; //count level and push int cnt = 0; for(int j = 0; j < (int)tmp.size(); j++){ if(tmp[j] == '.') cnt++; } v.push_back(make_pair(string() + tmp[(int)tmp.size() - 1], cnt)); max_level = max(max_level, cnt); } reverse(v.begin(), v.end()); //for(int i = 0; i < n; i++) cout << v[i].first << " " << v[i].second << endl; while(max_level >= 1){ //get head and tail, make que cout << "max_level = " << max_level << endl; cout << "vec_size = " << v.size() << endl; int del_head = -1; int del_tail; int flag = 0; queue<int> que; string operand; for(int i = 0; i < (int)v.size(); i++){ if(del_head == -1 and v[i].second == max_level){ del_head = i; que.push(stoi(v[i].first)); } else if(v[i].second == max_level){ que.push(stoi(v[i].first)); flag = 1; } else if(v[i].second == max_level - 1 and flag){ operand = v[i].first; del_tail = i; //modified break; } } //NTpmDM02 v.erase(v.begin() + del_head, v.begin() + del_tail); //make place_holder int place_holder; if(operand == "+") place_holder = 0; else if(operand == "*") place_holder = 1; while(que.size()){ cout << "que_size = " << que.size() << endl; int x = que.front(); cout << "x = " << x << endl; que.pop(); if(operand == "+") place_holder += x; else if(operand == "*") place_holder *= x; } v[del_head] = make_pair(to_string(place_holder), max_level - 1); cout << place_holder << endl; max_level--; } cout << v[0].first << endl; return 0; }
d0e1cd0bd24b5321e67761ea2ac47aef9f942cab
69d3a1def95e8c38cfb62d18d0c1e3cac10e7ba5
/Week-1/process_packages.cpp
86ee03ca43773ab8342ac81077f24a5fbccba661
[]
no_license
MalikSaurabh/Data-Structures-Coursera-Solutions
665ec776c79c48b43659694d7a5dad3108c8b021
4a678eb954022e3a22c62a101c9c7b203666dafa
refs/heads/master
2020-09-07T07:30:07.501984
2019-11-09T21:28:04
2019-11-09T21:28:04
220,704,759
0
0
null
null
null
null
UTF-8
C++
false
false
2,067
cpp
process_packages.cpp
#include <iostream> #include <queue> #include <vector> struct Request { Request(int at, int pt): at(at), pt(pt) {} int at; int pt; }; struct Response { Response(bool dropped, int st): dropped(dropped), st(st) {} bool dropped; int st; }; class Buffer { public: Buffer(int size): size_(size), finish_time_() {} Response Process(const Request &request) { while (!finish_time_.empty()) { if (finish_time_.front() <= request.at) finish_time_.pop(); else break; } if (finish_time_.size() == size_) return Response(true, -1); if (finish_time_.empty()) { finish_time_.push(request.at + request.pt); return Response(false, request.at); } int last_element = finish_time_.back(); finish_time_.push(last_element + request.pt); return Response(false, last_element); } private: int size_; std::queue <int> finish_time_; }; std::vector <Request> ReadRequests() { std::vector <Request> requests; int count; std::cin >> count; for (int i = 0; i < count; ++i) { int at, pt; std::cin >> at >> pt; requests.push_back(Request(at, pt)); } return requests; } std::vector <Response> ProcessRequests(const std::vector <Request> &requests, Buffer *buffer) { std::vector <Response> responses; for (int i = 0; i < requests.size(); ++i) responses.push_back(buffer->Process(requests[i])); return responses; } void PrintResponses(const std::vector <Response> &responses) { for (int i = 0; i < responses.size(); ++i) std::cout << (responses[i].dropped ? -1 : responses[i].st) << std::endl; } int main() { int size; std::cin >> size; std::vector <Request> requests = ReadRequests(); Buffer buffer(size); std::vector <Response> responses = ProcessRequests(requests, &buffer); PrintResponses(responses); return 0; }
914d500dd28821a8b2c05866a74b2e9e7da529bd
703cb315cc14a399058b661e2f3ce712a9cae618
/testSDK/CommandView/CustomCombobox.h
f500b3fa384e0e7712d6b8a1dfe293ab5c2e0a4d
[ "BSD-3-Clause" ]
permissive
yongyuwh/HMI_SDK_LIB
d7180078da2e5cbbbe7a72b7f6dbd607a559b1b6
0c97dbd3e7ef1c7704088c40adcde4d99163cd03
refs/heads/master
2021-08-31T11:33:54.812790
2017-12-21T06:59:10
2017-12-21T06:59:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,476
h
CustomCombobox.h
#ifndef CUSTOMCOMBOBOX_H #define CUSTOMCOMBOBOX_H #include <QListWidget> #include "Common/ScrollBar.h" #include "CustomComboboxItem.h" class CustomCombobox : public QListWidget { Q_OBJECT public: explicit CustomCombobox(int iMaxHeight, bool bUp = false, QWidget *parent = NULL); //explicit CustomCombobox(int iStartX,int iStartY,int iWidth,int iMaxHeight,bool bUp = true,QWidget *parent = NULL); ~CustomCombobox(); static QString cssString(); void AddListItem(QString strText, bool bMenu, std::string strImagePath = ""); // 根据朝向设定窗体位置 void SetPos(int iStartX, int iStartY, int iWidth, int iHeight); // 清空所有项 void ClearAllItem(); signals: void ItemClickedSignal(QListWidgetItem *pItem); public slots: void OnTimeOutSlot(); void OnScrollBarValueChange(int iValue); void OnItemClicked(CustomComboboxItem *pItem); private: enum SCROLLBARPOS {TOP = 0, MIDDLE, BOTTOM}; void SetScrollBarStyle(int iMode); // 定时检查鼠标位置,给悬停的选项高亮 QTimer *m_pTimer; void SetScrollParams(int page, int range); QVector<CustomComboboxItem *> m_itemList; int m_iOldHoverItemIndex; ScrollBar m_scrollWidget; // 起始点 int m_iStartX; int m_iStartY; // 宽度 int m_iWidth; // 高度 int m_iHeight; // 最大高度 int m_iMaxHeight; // true表示向上,false表示朝下 bool m_bUp; //void mouseMoveEvent(QMouseEvent *event); }; #endif // CUSTOMCOMBOBOX_H
c030df192ce53b2ae586b9efd17de3a8553fc041
8bdd599364b621da20d2fea67b3499dcfc2b1661
/test(Prime number detection -do while)/test/test/test.cpp
373a2d6d7f7b3946ad804f138b49c9b8c864e3b5
[]
no_license
lin60102/Cpp_programs
fd5e3884f4bf666e704ac2f2aa48924867a4db58
e3709a6648ff23c5aa01843e7e9bc6146408893d
refs/heads/master
2020-04-18T04:50:07.725509
2019-01-27T08:31:16
2019-01-27T08:31:16
null
0
0
null
null
null
null
BIG5
C++
false
false
1,167
cpp
test.cpp
// test.cpp: 主要專案檔。 #include "stdafx.h" #include "iostream" using namespace System; using namespace System::Collections; int main(array<System::String ^> ^args) { ArrayList ^a = gcnew ArrayList(); int num,ans,i=1; do { Console::Write("請輸入一個數字:"); try { num = Convert::ToInt16(Console::ReadLine()); if(num>99||num<2) { throw gcnew ArgumentOutOfRangeException(); } else { do { ans=num%i; i++; if(ans==0) { a->Add(i-1); } }while(i<num+1); Console::Write("因數有: "); for each(Object^ item in a) Console::Write("{0} ",item); Console::WriteLine(); if(a->Count==2) { Console::WriteLine("你輸入的數字 {0} 為質數",num); } else { Console::WriteLine("你輸入的數字 {0} 為非質數",num); } } } catch(ArgumentOutOfRangeException ^error) { Console::WriteLine("輸入之數字必須在2~99之間!錯誤訊息為:"+error->Message); } catch(Exception ^error) { Console::WriteLine("錯誤訊息為:"+error->Message); } }while(num>99||num<2); system("pause"); return 0; }
37c88060587f3a9598bb1623a02c76eee323510c
87b416ca6c742d413ff3e6bc156b611fabecfa72
/networktest/udp_server.cpp
98b864390070750324510b0bd67856dfd21f4aee
[]
no_license
killwing/mytests
895df7b5f4dacf6f8c394111b5048805697e275e
36592fe0a3c33f0ff6eac0ad0617c4f907233861
refs/heads/master
2016-09-06T18:00:20.668274
2013-12-11T09:03:55
2013-12-11T09:03:55
3,735,432
1
0
null
null
null
null
UTF-8
C++
false
false
2,745
cpp
udp_server.cpp
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string> #include <iostream> #include <cstring> #include <stdio.h> using namespace std; #define MAXLINE 100 void setrecvbuff(int fd, socklen_t n = 0) { socklen_t buflen = 0; socklen_t len = sizeof(buflen); getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&buflen, &len); cout<<"before - recvbuf: "<<buflen<<endl; buflen = n; if (n > 0) { setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&buflen, len); } getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&buflen, &len); cout<<"after - recvbuf: "<<buflen<<endl; } void echo(int fd) { char recvline[MAXLINE + 1]; while (1) { sockaddr_in cliaddr; int cliaddrlen = sizeof(cliaddr); int n = recvfrom(fd, recvline, MAXLINE, 0, (sockaddr*)&cliaddr, (socklen_t*)&cliaddrlen); if (n > 0) { recvline[n] = 0; if (sendto(fd, recvline, strlen(recvline), 0, (sockaddr*)&cliaddr, cliaddrlen) < 0) { perror("sendto"); break; } } else if (n < 0) { perror("recvfrom"); break; } else // n == 0 { // seems remote shutdown can not take us here, so.. should set timeout of recvfrom() break; } } } void mute() { sleep(600); } void eat(int fd) { //setrecvbuff(fd, 3200); char recvline[MAXLINE + 1]; int sum = 0; while (1) { sockaddr_in cliaddr; int cliaddrlen = sizeof(cliaddr); int n = recvfrom(fd, recvline, MAXLINE, 0, (sockaddr*)&cliaddr, (socklen_t*)&cliaddrlen); if (n > 0) { recvline[n] = 0; sum += n; cout<<"recvd "<<sum<<": "<<recvline<<endl; } else if (n < 0) { perror("recvfrom"); break; } else // n == 0 { // seems remote shutdown can not take us here, so.. should set timeout of recvfrom() break; } } } int main() { int socketfd = socket(AF_INET, SOCK_DGRAM, 0); if (socketfd < 0) { perror("socket"); return 0; } sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(7777); if (bind(socketfd, (sockaddr*)&servaddr, sizeof(servaddr))< 0) { perror("bind"); return 0; } //echo(socketfd) //mute(); sleep(10); eat(socketfd); close(socketfd); return 0; }
37f45de1f9faec609a1f92f3b636daec04763f98
0421bc55fe0928ce76ab1f45fc3cdfd7f8b6a9b0
/gauntlet/C_Updateable.h
f3bcf55d1e29cb1faffce362e0275e07c00c524f
[]
no_license
GandhiGames/gauntlet
f3ce79cdf85468bc456f0536283a25b516408fe8
17ebe9143e2371de47d8a158971d92b4bfaeac9b
refs/heads/master
2021-01-20T11:39:15.554575
2017-09-25T12:54:30
2017-09-25T12:54:30
101,512,609
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
C_Updateable.h
#pragma once //TODO: rename - remove C_ class C_Updateable { friend class Object; public: C_Updateable(); virtual ~C_Updateable() = 0; virtual void Update(float deltaTime, Object* owner) {} virtual void LateUpdate(float deltaTime, Object* owner) {} };
f10b33c6345e0486ecfd35c02059551cab9828f2
1e97a77a6a86e20b9340247d40dd04ee0317fbfc
/examples/Hardware/adc/adc.ino
1eafa9f8636777d36b4eb577fe2488ec8ec1d370
[ "MIT" ]
permissive
dyc1229/Bluefruit52_Arduino
a9ab1b17efbce0d4cbe02c5bbb4cfa4e28d95c7c
1bffe16d3a296d77c46a082e28d645de9002d850
refs/heads/master
2022-02-28T14:35:07.778875
2019-09-03T07:23:36
2019-09-03T07:23:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
ino
adc.ino
/* ADC get input get adc value from pin and print value. This example code is in the public domain. 2019/01/02 by Afantor */ int adc_pin = A5; int adc_value = 0; float mv_per_lsb = 3600.0F/1024.0F; // 10-bit ADC with 3.6V input range void setup() { Serial.begin(115200); } void loop() { // Get a fresh ADC value adc_value = analogRead(adc_pin); // Print the results Serial.print(adc_value); Serial.print(" ["); Serial.print((float)adc_value * mv_per_lsb); Serial.println(" mV]"); delay(100); }
acda82d6fe980c94577a1520b604a8ff2176e407
ac82758a30d9b440473209e35e40e3ccf364444f
/Übungsaufgaben/A09/Code/6.cpp
ca09bca6d316c81838454bcabdab6ec1c703aeb7
[]
no_license
PaulOxxx1/DSAL-Arbeitsverzeichnis
e2eacb68ec07e6a10f240b67aa595244eff52b77
72442f472f0505571e8fa1c65de27ed95bdf6f8c
refs/heads/master
2021-11-11T05:40:45.426744
2021-10-28T12:33:07
2021-10-28T12:33:07
129,533,636
1
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
6.cpp
bool isBipartit(list adj[n]){ queue q; q.enqueue(1); while(!q.empty()){ u = q.dequeue(); foreach v in adj[u]{ if(!v.color){ if(u.color == red) v.color = black; else v.color = red; q.enqueue(v); } else if (v.color == u.color) return false; } } return true; }
cf39c4cbdd8134b38ab8554a453e3dbb9bde421e
4ed098beb4924a42931227ba13ad6ca3321e5d33
/main.cpp
eac7befbdca7a9896284d0ee08970dace31e56c0
[]
no_license
DanyloOS/Chess_QML
760d46eae845db389c8647fbd78d953ad623037d
f94387f21684aabc7e1b8ef60c1b3529619dbed8
refs/heads/master
2023-05-05T22:44:02.357868
2021-02-20T20:49:18
2021-02-20T20:49:18
340,426,305
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
main.cpp
#include "gameengine.h" #include <QQmlContext> #include <QtCore> #include <QGuiApplication> #include <QQmlApplicationEngine> // TODO: find better place for this #define FEN_START_POS "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); GameEngine gameEngine; gameEngine.setUpStartPos(FEN_START_POS); engine.rootContext()->setContextProperty("chessBoardModel", &(gameEngine.getChessBoardModel())); engine.rootContext()->setContextProperty("chessPieceModel", &(gameEngine.getChessPieceModel())); engine.load(url); return app.exec(); }
d0aa81b7ea58bc59e94031038ea5652f311c4b68
6204fae696932f831d18b77bc1ebcc2cb1bff1df
/project-euler/volume02/77.cc
5b1ebfd4ff66d700839c47e4aa2b4114613b0b8b
[]
no_license
Pentagon03/competitive-programming
3e725bab66ba75f5e8c8489bada41c5ee51fed91
8ca7cec0ff7bb7c096d4b8d7100840cef6ae0c99
refs/heads/master
2022-11-15T15:36:18.595463
2020-07-02T15:27:37
2020-07-02T15:27:37
287,737,119
1
1
null
null
null
null
UTF-8
C++
false
false
545
cc
77.cc
#include <bits/stdc++.h> using namespace std; int sol(int n) { vector<int> vs(n, 1); vs[0] = vs[1] = 0; vector<int> pl; vector<int> dp(n, 0); dp[0] = 1; for (int i = 2; i < n; ++ i) if (vs[i] == 1) { pl.push_back(i); for (int j = i + i; j < n; j += i) vs[j] = 0; } for (int i = 0; i < pl.size(); ++ i) { for (int j = pl[i]; j < n; ++ j) { dp[j] += dp[j - pl[i]]; } } for (int i = 1; i < n; ++ i) { if (dp[i] > 5000) return i; } return -1; } int main() { cout << sol(1000) << endl; return 0; }
0be6dc2f3eb93b4281433fc4eba494c24a66393c
8307623044be8f9ef6310a69e0a957de40f09ab5
/Implementations/04 - Sorting And Searching (2)/4.1 - Interval Cover.cpp
cea65fae1dee44f8208db7d6955bf6bbfceffa5d
[]
no_license
ailyanlu1/USACO-1
488569b16d196180b30cdabdda43f3aa9184ef73
100213ccf2036cc89facee0ebc582048955694f5
refs/heads/master
2020-03-23T07:48:18.848515
2018-07-16T16:06:37
2018-07-16T16:06:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
992
cpp
4.1 - Interval Cover.cpp
/** * Usage: https://open.kattis.com/problems/intervalcover * Description: Example of greedy algorithm */ double A,B,cur; vector<pair<pd,int>> in; int N,nex; vi ans; void solve() { nex = 0; ans.clear(); cin >> N; in.resize(N); F0R(i,N) { cin >> in[i].f.f >> in[i].f.s; in[i].s = i; } sort(all(in)); pair<double,int> mx = {-DBL_MAX,-1}; while (nex < in.size() && in[nex].f.f <= A) { mx = max(mx,{in[nex].f.s,in[nex].s}); nex++; } if (nex == 0) { cout << "impossible\n"; return; } ans.pb(mx.s); while (mx.f < B) { cur = mx.f; while (nex < in.size() && in[nex].f.f <= cur) { mx = max(mx,{in[nex].f.s,in[nex].s}); nex++; } if (mx.f == cur) { cout << "impossible\n"; return; } ans.pb(mx.s); } cout << ans.size() << "\n"; for (int i: ans) cout << i << " "; cout << "\n"; }
d7b0096409547f468068041e45229272396e2671
4584df33ba273610ea91efd3f7ad58a6a01a2f20
/171-excel-sheet-column-title.cpp
9966aa83ce979671a6747825efb022ad1166ed16
[]
no_license
Sudha247/leetcode-solutions
bfb761f04844d87dfd5ca60766be82d071b93a15
b06988c3d84d0b72505b909793b18eb077dd299c
refs/heads/master
2020-03-25T11:49:39.794696
2018-08-16T17:48:07
2018-08-16T17:48:07
143,750,250
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
171-excel-sheet-column-title.cpp
class Solution { public: int titleToNumber(string s) { int l = s.length(); int i = l-1, pos = 0, sum = 0; while(i >= 0){ sum += (int(s[i] - 'A' + 1))*pow(26,pos); pos++; i--; } return sum; } };
5265a6d0f0318ad7aee0ccc77a86b0320f61025e
3dc9e2aaa40037bc099ed478b027892c03e2839c
/src/exp2-2-2.cpp
e30da99b78cf2e4968ceed588d265906429ec6b9
[ "MIT" ]
permissive
ASjet/data-struct
66841462ec6cd97de6bec2b55af2ce6c4a664339
184117e353f919c8d752f5b70c814e9a78254c22
refs/heads/main
2023-08-18T12:09:19.953989
2021-10-15T06:01:59
2021-10-15T06:01:59
352,577,838
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
exp2-2-2.cpp
#include <iostream> #include <string> #include "LinerLink.h" //////////////////////////////////////////////////////////////////////////////// using std::cin; using std::cout; using std::endl; using std::string; //////////////////////////////////////////////////////////////////////////////// int main(void) { LinerLink<int> * LF = new LinerLink<int>; LinerLink<int> * LR = new LinerLink<int>; for(link_size_t i = 0; i != 10; ++i) { LF->insert(0,i); LR->insert(-1,i); } cout << *LF << endl << *LR << endl; delete LF; delete LR; return 0; }
92074ce15b7a8af2033862eb64d6a88423513389
b221a94867fccca77e30d62cb3230639f1ff2374
/code/oned/rhs_contrb_diff_br2_p1.cpp
dba9d8d60c17b417af0a1cca1536fc2bd8d88e98
[]
no_license
karthikncsuiisc/A-Discontinuous-Galerkin-program-for-solving-1D-Nonlinear-Advection-Diffusion-equations
b6bfa3d59d36166be4c95ff3c4030ad70ce85cab
255fbff2d64044e89911c3733719c0e2862dda82
refs/heads/master
2023-02-07T08:47:18.918371
2020-12-26T17:54:44
2020-12-26T17:54:44
324,606,629
1
0
null
null
null
null
UTF-8
C++
false
false
2,444
cpp
rhs_contrb_diff_br2_p1.cpp
//Program contributes diffusive terms to rhspo using BR2 method //------------------------------------------------------------------------------------------------- // Cells discrption //-------------------------------------------------------------------------------------------------- // Ghost domain cells Ghost cells // 0 1 2 3 4 5 6 .................. nelem . nelem+1 nelem+2 // |---|---|____|____|____|_____|_____|_____________________|______|_____|_____|_____|-----|-----| // 0 1 2 3 4 5 6 7 ................. nelem nelem+1 nelem+4 // Points location //-------------------------------------------------------------------------------------------------- #include "functions.h" #include "oned_header.h" void rhs_contrb_diff_br2_p1() { /*if(disc_order!=1) { cout<<"BR2 method is implemented only for P1 method"<<endl; exit(1); }*/ double ui,uj; double fluxleft,fluxright; double M11,M22,ujump,B2,dx; for(int ielem=2;ielem<=nelem+1;ielem++) { M11=coord_1d[ielem+1]-coord_1d[ielem]; M22=(coord_1d[ielem+1]-coord_1d[ielem])/3.0; ui=unkel[ielem][0][0]-unkel[ielem][0][1]; uj=unkel[ielem-1][0][0]+unkel[ielem-1][0][1]; ujump=uj-ui; B2=-1; liftopr[ielem][0][0]=-etabr2*ujump/(2.0*M11); liftopr[ielem][0][1]=-etabr2*ujump*B2/(2.0*M22); ui=unkel[ielem][0][0]+unkel[ielem][0][1]; uj=unkel[ielem+1][0][0]-unkel[ielem+1][0][1]; ujump=uj-ui; B2=1; liftopr[ielem][1][0]=-etabr2*ujump/(2.0*M11); liftopr[ielem][1][1]=-etabr2*ujump*B2/(2.0*M22); } //cout<<"-------------------------"<<endl; for(int ielem=2;ielem<=nelem+1;ielem++) { dx=coord_1d[ielem+1]-coord_1d[ielem]; B2=-1; fluxleft=unkel[ielem][0][1]/dx-(liftopr[ielem][0][0]+B2*liftopr[ielem][0][1]); B2=1; fluxright=unkel[ielem][0][1]/dx-(liftopr[ielem][1][0]+B2*liftopr[ielem][1][1]); rhspo[ielem][0][0]=rhspo[ielem][0][0]+coefc*(fluxright-fluxleft); B2=-1; fluxleft=unkel[ielem][0][1]/dx-(liftopr[ielem][0][0]+B2*liftopr[ielem][0][1]); fluxleft=B2*(fluxleft); B2=1; fluxright=unkel[ielem][0][1]/dx-(liftopr[ielem][1][0]+B2*liftopr[ielem][1][1]); fluxright=B2*fluxright; rhspo[ielem][0][1]=rhspo[ielem][0][1]+coefc*(fluxright-fluxleft); rhspo[ielem][0][1]=rhspo[ielem][0][1] -2.0*coefc*(unkel[ielem][0][1]/dx-liftopr[ielem][0][0]-liftopr[ielem][1][0]); // cout<<ielem<<" "<<rhspo[ielem][0][0]<<" "<<rhspo[ielem][0][1]<<endl; } }
31778266338cbdbdac97b0200038972fd1bd6574
4868c6be7f84a65d8edeaa5cbdc45a677e7e22b3
/src/geometryUtils.cpp
ab0030c2db1545e6a2c76346cfcecbfafd11f828
[ "Apache-2.0" ]
permissive
GoogleCloudPlatform/wsi-to-dicom-converter
cd3e6b7a91760984c7d4dc929b67db720cee9e18
ee532a3ad944c209585bffb534f426c17fa8abba
refs/heads/develop
2023-08-18T02:10:53.695454
2023-05-12T22:24:21
2023-05-12T22:24:21
191,454,643
55
23
Apache-2.0
2023-05-12T22:24:22
2019-06-11T21:45:05
C++
UTF-8
C++
false
false
1,532
cpp
geometryUtils.cpp
// Copyright 2019 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <algorithm> #include "src/geometryUtils.h" namespace wsiToDicomConverter { void dimensionDownsampling( int64_t frameWidth, int64_t frameHeight, int64_t sourceLevelWidth, int64_t sourceLevelHeight, bool retile, double downsampleOfLevel, int64_t *downsampledLevelWidth, int64_t *downsampledLevelHeight, int64_t *downsampledLevelFrameWidth, int64_t *downsampledLevelFrameHeight) { *downsampledLevelWidth = sourceLevelWidth; *downsampledLevelHeight = sourceLevelHeight; if (retile) { *downsampledLevelWidth /= downsampleOfLevel; *downsampledLevelHeight /= downsampleOfLevel; } *downsampledLevelFrameWidth = std::min<int64_t>(frameWidth, *downsampledLevelWidth); *downsampledLevelFrameHeight = std::min<int64_t>(frameHeight, *downsampledLevelHeight); } } // namespace wsiToDicomConverter
1fecfbac79b9078bd307f8db6bf324e34a146431
4cd0b9ce7c2e2a57623cc71b936c6dcda79bdd5c
/xfa/fxfa/cxfa_textpiece.h
f115c41e846e3bfae33b24d2304a922e4d95bce9
[ "BSD-3-Clause" ]
permissive
prepare/pdfium
32b8f9cecc2dd98cd578d2b4e8d882e5c4f0e1ed
92770e8072cd3a38597966116045147c78b5a359
refs/heads/master
2021-01-21T04:43:53.541194
2018-12-23T06:55:27
2018-12-23T06:55:27
27,119,109
7
3
null
2015-08-11T13:40:07
2014-11-25T09:47:59
C++
UTF-8
C++
false
false
975
h
cxfa_textpiece.h
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef XFA_FXFA_CXFA_TEXTPIECE_H_ #define XFA_FXFA_CXFA_TEXTPIECE_H_ #include <vector> #include "core/fxcrt/fx_coordinates.h" #include "core/fxcrt/fx_string.h" #include "core/fxge/fx_dib.h" #include "xfa/fxfa/fxfa_basic.h" class CFGAS_GEFont; class CXFA_LinkUserData; class CXFA_TextPiece { public: CXFA_TextPiece(); ~CXFA_TextPiece(); WideString szText; std::vector<int32_t> Widths; int32_t iChars; int32_t iHorScale; int32_t iVerScale; int32_t iBidiLevel; int32_t iUnderline; XFA_AttributeValue iPeriod; int32_t iLineThrough; FX_ARGB dwColor; float fFontSize; CFX_RectF rtPiece; RetainPtr<CFGAS_GEFont> pFont; RetainPtr<CXFA_LinkUserData> pLinkData; }; #endif // XFA_FXFA_CXFA_TEXTPIECE_H_
92688391aa6af2ab8c6cf5baf5a8ec3e059a4922
ff25687a61d90efa94871a1f21b8f32ea98998c7
/SpellCorrect/server/inc/MyPoolThread.h
bd62a43c6b00a69747830d05858aaa44d4240a8b
[]
no_license
bat-battle/ProjectBattle
f45269eb49c24ef0d89cf653e6e38412f61af7ae
b6550761aec7a80b7c44bad2aba587f2dc9f0c37
refs/heads/master
2021-01-13T06:53:56.430416
2017-10-21T11:28:54
2017-10-21T11:28:54
81,315,015
18
15
null
null
null
null
UTF-8
C++
false
false
536
h
MyPoolThread.h
#ifndef _MYPOOLTHREAD_H #define _MYPOOLTHREAD_H /***************************************/ //1、MyPoolThread继承自Thread,拥有Thread //的所有非私有成员及函数。 // //2、之所以要传入线程池的引用,是因为 //Thread中的run()方法要执行线程池中的 //threadFunc()方法 /***************************************/ #include "Thread.h" class Threadpool; class MyPoolThread : public Thread { public: MyPoolThread(Threadpool &threadpool); void run(); private: Threadpool &threadpool_; }; #endif
48df25e3e173220bb237073e439257b48347ce6b
6c8a158fd3eea6dc37b8497f9eb7ea2e57b91896
/137_QtQml_QQuickPaintedItem/outlinetextitem.cpp
53b33a3358adcec3768bd7cf85097d3dc1ba1ed5
[]
no_license
beduty/QtTrain
07677ec37730c230dbf5ba04c30ef69f39d29a45
5983ef485b5f45ae59ef2ac33bc40c7241ae6db7
refs/heads/master
2023-02-10T11:22:49.400596
2021-01-04T14:59:20
2021-01-04T14:59:20
326,716,000
0
0
null
null
null
null
UTF-8
C++
false
false
3,318
cpp
outlinetextitem.cpp
#include "outlinetextitem.h" #include "outlinetextitemborder.h" #include <QPainter> OutlineTextItem::OutlineTextItem(QQuickItem *parent) : QQuickPaintedItem(parent) { m_border = new OutlineTextItemBorder(this); connect(this, &OutlineTextItem::textChanged, this, &OutlineTextItem::updateItem); connect(this, &OutlineTextItem::colorChanged, this, &OutlineTextItem::updateItem); connect(this, &OutlineTextItem::fontFamilyChanged, this, &OutlineTextItem::updateItem); connect(this, &OutlineTextItem::fontPixelSizeChanged, this, &OutlineTextItem::updateItem); connect(m_border, &OutlineTextItemBorder::widthChanged, this, &OutlineTextItem::updateItem); connect(m_border, &OutlineTextItemBorder::colorChanged, this, &OutlineTextItem::updateItem); connect(m_border, &OutlineTextItemBorder::styleChanged, this, &OutlineTextItem::updateItem); updateItem(); } OutlineTextItemBorder *OutlineTextItem::border() const { return m_border; } void OutlineTextItem::updateItem() { /// 이 함수에서 쓰이는 m_fontFamily, m_fontPixelSize, m_text는 /// 아래와 같이 QML객체 속성에 부여한 값과 동일하다. /// QML 엔진에서 속성을 변경하면 MEMBER m_text등으로 선언된 Q_PROPERTY와 /// connect(..)로 연결된 SIGNAL-SLOT으로 인해 updateItem이 호출되고, /// 변경된 값을 바로 받아서 GUI업데이트를 수행한다! /// /// OutlineTextItem{ /// anchors.centerIn: parent /// text : "This is outliend text" /// fontFamily: "Arial" /// fontPixelSize: 64 /// ... /// } /// QFont font(m_fontFamily, m_fontPixelSize); m_path = QPainterPath(); // QString 텍스트로 Path를 만들 수 있다!! (QPainterPathStroker..) m_path.addText(0,0, font, m_text); m_boundingRect = borderShape(m_path).controlPointRect(); setImplicitWidth(m_boundingRect.width()); setImplicitHeight(m_boundingRect.height()); update(); } void OutlineTextItem::paint(QPainter *painter) { if(m_text.isEmpty()) return; // paint(..)는 updateItem()에서 호출한 update(..)에 의해 콜백된다. // m_border->pen()은 아래의 QML 객체에 설정한 속성값중 border.color 등으로 설정한 // m_color, m_width, m_style에 의해서 QPen OutlineTextItemBorder::pen() 이 리턴될 때 // QPen의 속성으로 설정된다. // OutlineTextItem{ // ... // border.color: "blue" // border.width: 2 // border.style: Qt.DotLine // } // QPen OutlineTextItemBorder::pen() const // { // QPen p; // p.setColor(m_color); // p.setWidth(m_width); // p.setStyle(m_style); // return p; // } painter->setPen(m_border->pen()); painter->setBrush(m_color); painter->setRenderHint(QPainter::Antialiasing, true); painter->translate(-m_boundingRect.topLeft()); painter->drawPath(m_path); } QPainterPath OutlineTextItem::borderShape(const QPainterPath &path) const { QPainterPathStroker pathStroker; pathStroker.setWidth(m_border->width()); QPainterPath p = pathStroker.createStroke(path); p.addPath(path); return p; }
0e64dfea1a1d082d54d559cc54f1ca88a6fc4748
ded918c134d4b3f576658b927602e8e359209197
/drzpprz.cpp
a72cdb5a87a51e88beb1c7988cbc2ec0549cb167
[ "MIT" ]
permissive
wdomitrz/Basic_algorithms
f5c352efad394bccfcb2ff41cf8115410439cff6
f16aa58aecb27329e9d53f7fe62fe4f61680095c
refs/heads/master
2021-05-15T03:51:48.252020
2018-09-25T18:17:04
2018-09-25T18:17:04
106,850,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
cpp
drzpprz.cpp
#include<cstdio> #include<algorithm> using namespace std; const int base = 1 << 20; int drz[2 * base]; bool gwiazdki[2 * base]; void spusc(int x) { gwiazdki[x] = false; drz[x * 2] = drz[x]; gwiazdki[x * 2] = true; drz[x * 2 + 1] = drz[x]; gwiazdki[x * 2 + 1] = true; } void aktualizuj(int x) { drz[x] = max(drz[2 * x], drz[2 * x + 1]); } void zmien(int x, int pocz, int kon, int a, int b, int naco) { // [a, b] = przedzial, [pocz, kon] = to, co widzi wierzcholek x if(a == pocz && b == kon) { drz[x] = naco; gwiazdki[x] = true; return; } if(gwiazdki[x]) spusc(x); int sr = (a + b) / 2; if(b <= sr) { zmien(x * 2, pocz, sr, a, b, naco); aktualizuj(x); return; } if(a > sr) { zmien(x * 2 + 1, sr + 1, kon, a, b, naco); aktualizuj(x); return; } zmien(x * 2, pocz, sr, a, sr, naco); zmien(x * 2 + 1, sr + 1, kon, sr + 1, b, naco); aktualizuj(x); } int czytaj(int x, int pocz, int kon, int a, int b) { if(a == pocz && b == kon) { return drz[x]; } if(gwiazdki[x]) spusc(x); int sr = (a + b) / 2; if(b <= sr) { return czytaj(x * 2, pocz, sr, a, b); } if(a > sr) { return czytaj(x * 2 + 1, sr + 1, kon, a, b); } return max(czytaj(x * 2, pocz, sr, a, sr), czytaj(x * 2 + 1, sr + 1, kon, sr + 1, b)); }
2857e894b4bf2a5132e786bec6c083e68e534303
3a42866c55c2166338756ef036de6bcdbec33c57
/fts.cpp
dab11efc08a85e0302ab0600c8b4ce0a1bf1d386
[]
no_license
dymayday/Fts
7163bdd88901a19999c634255e7b2a2f9454f396
ba092d43fb9006c1f72ad43a46a6ac57f90bbb2f
refs/heads/master
2016-09-05T18:42:15.617515
2012-08-28T15:51:33
2012-08-28T15:51:33
5,514,261
0
0
null
null
null
null
UTF-8
C++
false
false
21,152
cpp
fts.cpp
#include <stdlib.h> #include <iostream> #include <fstream> #include <unistd.h> #include "chronometer.hpp" //#include "./mem/mem.cpp" //#include "./SkelGIS/skelgis.h" using namespace std; #define stackOverFlawLimit 20000 float hugeNumber(10000); const float eps(0.00000001); int depth(0); int nbmodif(0); struct HEADER{ unsigned int width; unsigned int height; float x; float y; float spacing; float nodata; }; #include "neighbour.h" struct HEADER_ASC{ unsigned int ncols; unsigned int nrows; float xllcorner; float yllcorner; float cellsize; float nodata; // ncols 5068 // nrows 2913 // xllcorner 92250 // yllcorner 2235525 // cellsize 75.000000 // NODATA_value -9999 }; struct HEADER_BIN{ float cols; float rows; float west; float south; float north; float east; }; struct HEADER_MAT{ int type; int rows; int cols; int unUsed; int namelength; char name; }; // struct HEADER_ESRI{ // int cols; // int rows; // cellsize 0.050401 // xllcorner -130.128639 // yllcorner 20.166799 // nodata_value 9999.000000 // nbits 32 // pixeltype float // byteorder msbfirst // }; bool withinMatrix(const HEADER head, int i, int j){ if(i >= 0 && i < head.height && j >= 0 && j < head.width) return true; else return false; } int maxDEM(const HEADER head, float *const* Z){ int max(0); for(int i(0); i<head.height; i++) for(int j(0); j<head.width; j++) if(Z[i][j] > max) max = Z[i][j]; return max; } bool isPixelBorder(const HEADER &head, const float *const* tab2D, int i, int j){ if(i == 0 || j == 0){ return true; }else if(i == (head.height-1)){ return true; }else if(j == (head.width-1)){ return true; }else return false; } float lowerNeighbour(const HEADER &head, const float *const* tab2D, int i, int j){ float lowerNb(tab2D[i][j]); if(tab2D[i-1][j] <= lowerNb) lowerNb = tab2D[i-1][j]; if(tab2D[i-1][j+1] <= lowerNb) lowerNb = tab2D[i-1][j+1]; if(tab2D[i][j+1] <= lowerNb) lowerNb = tab2D[i][j+1]; if(tab2D[i+1][j+1] <= lowerNb) lowerNb = tab2D[i+1][j+1]; if(tab2D[i+1][j] <= lowerNb) lowerNb = tab2D[i+1][j]; if(tab2D[i+1][j-1] <= lowerNb) lowerNb = tab2D[i+1][j-1]; if(tab2D[i][j-1] <= lowerNb) lowerNb = tab2D[i][j-1]; if(tab2D[i-1][j-1] <= lowerNb) lowerNb = tab2D[i-1][j-1]; return lowerNb; } bool isSink(const HEADER &head, const float *const* tab2D, int i, int j){ if(tab2D[i][j] <= lowerNeighbour(head, tab2D, i, j)){ return true; }else return false; } float sinksCatchmentArea(const HEADER &head, float ** tab2D){ for(int i(0); i<head.height; i++){ for(int j(0); j<head.width; j++){ } } } bool isCatchmentArea(const HEADER &head, float ** tab2D, int i, int j){ } void printTab2DSinksAndBorders(HEADER &head, float ** tab2D){ for(int i(0); i<head.height; i++){ for(int j(0); j<head.width; j++){ if(isPixelBorder(head, tab2D, i, j)) cout<<tab2D[i][j]<<" "; else if(isSink(head, tab2D, i, j)) cout<<tab2D[i][j]<<" "; else cout<<" "; } cout<<endl; } cout<<endl; } float ** onlySinksDEM(const HEADER head, float ** Z){ float ** W = NULL; W = new float*[head.height]; for(int i(0); i<head.height; i++) W[i] = new float[head.width]; for(int i(0); i<head.height; i++){ for(int j(0); j<head.width; j++){ if(isPixelBorder(head, Z, i, j)) W[i][j] = Z[i][j]; else if(isSink(head, Z, i, j)) W[i][j] = Z[i][j]; else W[i][j] = 10; } } return W; } void printTab2DtestBorder(const HEADER &head, const float *const* tab2D){ for(int i(0); i<head.height; i++){ for(int j(0); j<head.width; j++){ if(isPixelBorder(head, tab2D, i, j)){ cout<<tab2D[i][j]<<" "; }else cout<<" "; } cout<<endl; } cout<<endl; } void printMatrix(const HEADER &head, float ** tab2D){ cout<<endl; if(tab2D != NULL){ for(int i(0); i<head.height; i++){ if(tab2D[i] != NULL) for(int j(0); j<head.width; j++){ cout.width(3); cout<<tab2D[i][j]; } cout<<endl; } } cout<<endl; } void printTab2D(const HEADER &head, float ** tab2D){ cout<<endl<<" "; for(int i(0); i<head.width; i++){ cout.width(3); cout<<i; } cout<<endl<<endl; if(tab2D != NULL){ for(int i(0); i<head.height; i++){ cout<<i<<" "; if(tab2D[i] != NULL) for(int j(0); j<head.width; j++){ cout.width(3); cout<<tab2D[i][j]; } cout<<endl; } } cout<<endl; } void writeMatrixTest(char * file){ HEADER head_perso; head_perso.width = 2; head_perso.height = 2; head_perso.x = 0; head_perso.y = 0; head_perso.spacing = 0; head_perso.nodata = -9999; float tabTest[]={2,2,4,5,6,6,8,6,5, 3,3,5,5,5,5,7,6,4, 5,5,4,5,4,4,7,8,6, 4,4,4,3,3,3,5,7,8, 2,3,3,3,2,3,4,5,6, 4,4,3,2,2,3,4,7,7, 3,4,4,2,2,3,6,8,9, 2,3,4,4,4,4,5,9,7, 2,2,3,4,4,5,6,8,7, 1,2,3,4,5,6,7,8,9}; float tabTestStrahler[]={0,0,0,1,0,1,0,0, 0,0,0,1,0,1,0,0, 0,0,0,0,2,0,0,0, 0,0,0,0,2,1,0,0, 0,0,0,0,2,0,2,0, 0,0,0,0,0,3,0,0, 0,0,0,0,0,3,0,0, 0,0,0,0,0,0,3,3, 0,0,0,0,0,2,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,}; int cpt(0); float ** tab2D = NULL; tab2D = new float*[head_perso.height]; for(int i(0); i<head_perso.height; i++) tab2D[i] = new float[head_perso.width]; for(int i(0); i<head_perso.height; i++){ for(int j(0); j<head_perso.width; j++){ tab2D[i][j] = tabTest[cpt]; cpt++; } } ofstream fout(file, ios::binary | ios::out); fout.write((char*)(&head_perso),sizeof(HEADER)); for(int i(0); i<head_perso.height; i++){ fout.write((char*)(tab2D[i]),sizeof(float)*head_perso.width); } if(tab2D != NULL){ for(int i(0); i<head_perso.height; i++){ if(tab2D[i] != NULL) delete tab2D[i]; else cout<<endl<<"tab2D["<<i<<"] -> NULL"<<endl; } delete [] tab2D; } else cout<<"\ntab2D -> NULL"<<endl; fout.close(); } float ** subDEM(const HEADER head, const float *const* Z){ float ** W = NULL; cout<<endl<<"DEM immersion..."<<endl; W = new float*[head.height]; for(int i(0); i<head.height; i++) W[i] = new float[head.width]; for(int i(0); i<head.height; i++) for(int j(0); j<head.width; j++){ if(isPixelBorder(head, Z, i, j)) W[i][j] = Z[i][j]; else W[i][j] = hugeNumber; } return W; } float ** streamBurning(const HEADER head, const float *const* Z, const float *const* S, int coeff=1){ float ** W = NULL; cout<<endl<<"Stream Burning..."<<endl; W = new float*[head.height]; for(int i(0); i<head.height; i++) W[i] = new float[head.width]; for(int i(0); i<head.height; i++) for(int j(0); j<head.width; j++){ W[i][j] = Z[i][j] - (coeff*S[i][j]); } return W; } float ** streamBurning(const HEADER head, const float *const* Z, const float *const* S, const float * tabCoeff){ float ** W = NULL; cout<<endl<<"Stream Burning..."<<endl; W = new float*[head.height]; for(int i(0); i<head.height; i++) W[i] = new float[head.width]; for(int i(0); i<head.height; i++) for(int j(0); j<head.width; j++){ W[i][j] = Z[i][j] - (tabCoeff[(int)(S[i][j])]); } return W; } void dryCell(const HEADER head, float ** Z, float ** &W, int x, int y){ for(int i(x-1); i<=(x+1); i++){ for(int j(y-1); j<=(y+1); j++){ if(withinMatrix(head, i, j) && (i != x && j != y)){ if(W[i][j] == hugeNumber){ if(Z[i][j] >= (W[x][y] + eps)){//(Z[x][y],W[i][j]))){ W[i][j] = Z[i][j]; nbmodif++; dryCell(head, Z, W, i, j); } } } } } } void fillTheSinks(const HEADER head, float ** Z, float ** &W){ // Time::Chronometer chrono; // chrono.start(); cout<<endl<<"Filling the sinks : "<<endl; cout<<" Border processing..."<<endl; for(int i(0); i<head.height; i++){ dryCell(head, Z, W, i, 0); } depth = 0; cout<<"nbmodif="<<nbmodif<<endl; for(int j(0); j<head.width; j++){ dryCell(head, Z, W, 0, j); } depth = 0; cout<<"nbmodif="<<nbmodif<<endl; for(int i(head.height-1); i>=0; --i){ dryCell(head, Z, W, i, head.width-1); } depth = 0; cout<<"nbmodif="<<nbmodif<<endl; for(int j(head.width-1); j>=0; --j){ dryCell(head, Z, W, head.height-1, j); } cout<<"nbmodif="<<nbmodif<<endl; cout<<" Filling matrix process."<<endl; bool modif(false); cout<<"nbmodif="<<nbmodif<<endl; do{ nbmodif=0; modif = false; for(int x(0); x<head.height; ++x){ for(int y(0); y<head.width; ++y){ if(W[x][y] > Z[x][y]){ for(int i(x-1); i<=(x+1); i++){ for(int j(y-1); j<=(y+1); j++){ if(withinMatrix(head, i, j)){// && (i != x && j != y)){ if(Z[x][y] >= (W[i][j] + eps)){//(Z[x][y],W[i][j]))){ W[x][y] = Z[x][y]; modif = true; nbmodif++; //dryCell(head, Z, W, x, y); }else if(W[x][y] > W[i][j] + eps){//(Z[x][y], W[i][j])){ W[x][y] = W[i][j] + eps;//(Z[x][y], W[i][j]); modif = true; nbmodif++; } } } } } } } cout<<"nbmodif="<<nbmodif<<endl; }while(modif); // chrono.stop(); // do{ // depth = 0; // nbmodif=0; // modif = false; // for(int x(head.height-1); x >=0; --x){ // for(int y(head.width-1); y >=0; --y){ // if(W[x][y] > Z[x][y]){ // for(int i(x-1); i<=(x+1); i++){ // for(int j(y-1); j<=(y+1); j++){ // if(withinMatrix(head, i, j) && (i != x && j != y)){ // if(Z[x][y] >= (W[i][j] + eps(Z[x][y],W[i][j]))){ // W[x][y] = Z[x][y]; // modif = true; // nbmodif++; // //dryCell(head, Z, W, x, y); // }else // if(W[x][y] > W[i][j] + eps(Z[x][y], W[i][j])){ // W[x][y] = W[i][j] + eps(Z[x][y], W[i][j]); // modif = true; // nbmodif++; // } // } // } // } // } // } // } // cout<<"nbmodif="<<nbmodif<<endl; // }while(modif); cout<<"100%"<<endl; //cout<<endl<<"Time : "<<chrono<<endl; } float ** directions(const HEADER head, const float *const* Z){ float ** W = NULL; W = new float*[head.height]; for(int i(0); i<head.height; i++) W[i] = new float[head.width]; for(int i(0); i<head.height; i++) for(int j(0); j<head.width; j++){ neighbour nb(head, Z, i, j); W[i][j] = nb.id_min; nb; } return W; } void deleteTab2D(const HEADER &head, float ** &tab2D){ if(tab2D != NULL){ for(int i(0); i<head.height; i++){ if(tab2D[i] != NULL) delete tab2D[i]; else cout<<endl<<"tab2D["<<i<<"] -> NULL"<<endl; } delete [] tab2D; } else cout<<"\ntab2D -> NULL"<<endl; } float ** readDEM(HEADER &head, const char * file){ float ** tab2D = NULL; ifstream f(file, ios::binary | ios::in); f.read((char*)(&head),sizeof(HEADER)); cout<<endl; cout<<"Width : "<<head.width<<endl; cout<<"Height : "<<head.height<<endl; // cout<<"x position : "<<head.x<<endl; // cout<<"y position : "<<head.y<<endl; printf("x position : %f\n", head.x); printf("y position : %f\n", head.y); cout<<"spacing : "<<head.spacing<<endl; cout<<"nodata : "<<head.nodata<<endl; tab2D = new float*[head.height]; for(int i(0); i<head.height; i++) tab2D[i] = new float[head.width]; cout<<endl<<"Loading DEM..."<<endl; f.seekg(sizeof(HEADER),ios::beg); for(int i(0); i<head.height; i++){ f.read((char*)(tab2D[i]),sizeof(float)*head.width); } return tab2D; } void readHeader(const char * file){ ifstream f(file, ios::binary | ios::in); HEADER head; f.read((char*)(&head),sizeof(HEADER)); cout<<endl; cout<<"Width : "<<head.width<<endl; cout<<"Height : "<<head.height<<endl; // cout<<"x position : "<<head.x<<endl; // cout<<"y position : "<<head.y<<endl; printf("x position : %f\n", head.x); printf("y position : %f\n", head.y); cout<<"spacing : "<<head.spacing<<endl; cout<<"nodata : "<<head.nodata<<endl; } void exportDEM_MAT(const HEADER head_MNT, const float *const* Z, char * file_mat){ HEADER_MAT head_mat; ofstream fout(file_mat, ios::binary | ios::out); head_mat.type = 10; head_mat.rows = head_MNT.height; head_mat.cols = head_MNT.width; head_mat.unUsed = 0; head_mat.namelength = 1; head_mat.name = 0; cout<<endl; cout<<"Exporting results to "<<file_mat<<" in binary format..."<<endl; cout<<"Type : "<<head_mat.type<<endl; cout<<"Rows : "<<head_mat.rows<<endl; cout<<"Cols : "<<head_mat.cols<<endl; cout<<endl; fout.write((char*)(&head_mat),sizeof(HEADER_MAT)); for(int i(0); i<head_MNT.height; i++){ fout.write((char*)(Z[i]),sizeof(float)*head_MNT.width); } } void exportDEM_BIN(const HEADER head, const float *const* Z, char * fileOut){ ofstream fout(fileOut, ios::binary | ios::out); cout<<endl<<"Exporting results to "<<fileOut<<" in binary format..."<<endl; fout.write((char*)(&head),sizeof(HEADER)); for(int i(0); i<head.height; i++){ fout.write((char*)(Z[i]),sizeof(float)*head.width); } fout.close(); } void exportDEM_ASC(const HEADER head, float ** Z, char * file_asc){ ofstream fout(file_asc); HEADER_ASC head_ASC; head_ASC.nrows = head.height; head_ASC.ncols = head.width; head_ASC.xllcorner = head.x; head_ASC.yllcorner = head.y; head_ASC.cellsize = head.spacing; head_ASC.nodata = head.nodata; fout<<"ncols "<<head_ASC.ncols<<endl; fout<<"nrows "<<head_ASC.nrows<<endl; fout<<"xllcorner "<<head_ASC.xllcorner<<endl; fout<<"yllcorner "<<head_ASC.yllcorner<<endl; fout<<"cellsize "<<head_ASC.cellsize<<endl; fout<<"NODATA_value "<<head_ASC.nodata<<endl; cout<<endl; cout<<"Exporting results to "<<file_asc<<" in ASCII format..."<<endl; cout<<"ncols "<<head_ASC.ncols<<endl; cout<<"nrows "<<head_ASC.nrows<<endl; //cout<<"xllcorner "<<head_ASC.xllcorner<<endl; printf("xllcorner %f",head_ASC.xllcorner); cout<<endl; printf("yllcorner %f",head_ASC.yllcorner); cout<<endl; //cout<<"yllcorner "<<head_ASC.yllcorner<<endl; cout<<"cellsize "<<head_ASC.cellsize<<endl; cout<<"NODATA_value "<<head_ASC.nodata<<endl; for(int i(0); i<head_ASC.nrows; i++){ for(int j(0); j<head_ASC.ncols; j++){ fout<<Z[i][j]<<" "; } fout<<endl; } fout.close(); } float * setTabCoeff(){ ifstream fin("./config.txt"); if(fin.is_open()){ int nbLines(0); char buffer[256]; cout<<endl<<"Strahler coeff tab : "<<endl; while(fin.getline(buffer, 256)){ ++nbLines; cout<<buffer<<endl; } fin.close(); fin.open("./config.txt"); float * tabCoeff = new float[nbLines]; for(int i(0); fin.ignore(256, ':'); i++){ fin.getline(buffer, 256); tabCoeff[i] = atof(buffer); } fin.close(); for(int i(0); i< nbLines;++i) cout<<i<<" "<<tabCoeff[i]<<endl; return tabCoeff; }else{ cout<<endl<<"ERROR : impossible to open config.txt file."<<endl<<endl; exit(1); } } void abort(char* prog_name){ cout<<endl<<endl; cout<<prog_name<<" has exit unespectedly !"<<endl<<endl; exit(1); } int main(int argc, char** argv){ char * fileIn = NULL; char * fileSub = NULL; char * fileStrahler = NULL; char * fileOut = NULL; HEADER head; int coeff(1); float ** Z=NULL; float ** W=NULL; float ** S=NULL; int options; bool opt_arg_i(false); //input flag bool opt_arg_a(false); //save results .asc bool opt_arg_b(false); //save results .bin bool opt_arg_c(false); //stream burning coeff bool opt_arg_d(false); //directions flow flag bool opt_arg_l(false); //header reader bool opt_arg_m(false); //export .mat flag (doesn't work for now) bool opt_arg_e(false); //export flag : simply save the input file into ascii format bool opt_arg_u(false); //immersion flag bool opt_arg_s(false); //stream burning flag bool opt_arg_t(false); //write test matrix flag while((options=getopt(argc,argv,"i:a:b:c:d:e:m:u:t:s:l:"))!=-1){ switch(options){ case 'i': opt_arg_i = true; fileIn = optarg; break; case 'a': opt_arg_a = true; fileOut = optarg; break; case 'b': opt_arg_b = true; fileOut = optarg; break; case 'c': opt_arg_c = true; coeff = atoi(optarg); break; case 'd': opt_arg_d = true; fileOut = optarg; break; case 'l': opt_arg_l = true; fileIn = optarg; break; case 'm': opt_arg_m = true; fileOut = optarg; break; case 'e': opt_arg_e = true; fileOut = optarg; break; case 'u': opt_arg_u = true; fileSub = optarg; break; case 's': opt_arg_s = true; fileStrahler = optarg; break; case 't': opt_arg_t = true; fileOut = optarg; break; default: abort(argv[0]); } } if(opt_arg_t) writeMatrixTest(fileOut); else if(opt_arg_l) readHeader(fileIn); else if(opt_arg_i){ Z = readDEM(head, fileIn); if(opt_arg_d){ W = directions(head, Z); exportDEM_ASC(head, W, fileOut); } else{ if(opt_arg_s){ S = readDEM(head, fileStrahler); if(opt_arg_c) W = streamBurning(head, Z, S, coeff); else{ float * tabCoeff = setTabCoeff(); W = streamBurning(head, Z, S, tabCoeff); delete tabCoeff; } } if(opt_arg_e){ // exportDEM_BIN(head, Z, fileOut); exportDEM_ASC(head, W, fileOut); }else{ W = subDEM(head, Z); if(opt_arg_u){ exportDEM_BIN(head, W, fileSub); }else{ fillTheSinks(head, Z, W); if(opt_arg_a){ exportDEM_ASC(head, W, fileOut); }else if(opt_arg_b){ exportDEM_BIN(head, W, fileOut); }else if(opt_arg_m){ exportDEM_MAT(head, W, fileOut); } } } } deleteTab2D(head, Z); if(opt_arg_a || opt_arg_b || opt_arg_m || opt_arg_d) deleteTab2D(head, W); if(opt_arg_s){ deleteTab2D(head, W); deleteTab2D(head, S); } }else abort(argv[0]); //writeMatrixTest(argv[1]); cout<<endl<<"Operation Done."<<endl<<endl; return 0; }
aa8960dba3d5e01e1a36187a59c52de32516dcd3
fc86bce28f67772d5a80d5e9c678b68d4eff8be1
/include/proxsuite/linalg/veg/internal/integer_seq.hpp
ce5dc20696574aabc98476165f0245d1510043b0
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
Simple-Robotics/proxsuite
fb0ef3cfab0f3aacb0fd67df038c4c1034967e24
24e9b4c7b346248cc8d0126545c5a4b724306d80
refs/heads/main
2023-09-03T18:40:57.331153
2023-08-02T18:10:41
2023-08-02T18:10:41
489,039,140
264
33
BSD-2-Clause
2023-09-12T12:39:31
2022-05-05T16:01:55
C++
UTF-8
C++
false
false
6,749
hpp
integer_seq.hpp
#ifndef VEG_INTEGER_SEQ_HPP_JBT0EKAQS #define VEG_INTEGER_SEQ_HPP_JBT0EKAQS #include "proxsuite/linalg/veg/internal/typedefs.hpp" #include "proxsuite/linalg/veg/internal/macros.hpp" #include "proxsuite/linalg/veg/internal/prologue.hpp" namespace proxsuite { namespace linalg { namespace veg { namespace meta { template<typename T, T N> using make_integer_sequence = _detail::_meta::make_integer_sequence<T, N>*; template<usize N> using make_index_sequence = _detail::_meta::make_integer_sequence<usize, N>*; template<typename T, T... Nums> using integer_sequence = _detail::_meta::integer_sequence<T, Nums...>*; template<usize... Nums> using index_sequence = integer_sequence<usize, Nums...>; template<typename... Ts> using type_sequence = _detail::_meta::type_sequence<Ts...>*; template<typename Seq, typename... Bs> struct and_test : false_type {}; template<typename Seq, typename... Bs> struct or_test : true_type {}; template<usize Is, typename T> using indexed = T; template<typename... Ts> struct pack_size { static constexpr usize value = sizeof...(Ts); }; template<usize... Is> struct and_test<index_sequence<Is...>, indexed<Is, true_type>...> : true_type {}; template<usize... Is> struct or_test<index_sequence<Is...>, indexed<Is, false_type>...> : false_type {}; } // namespace meta namespace _detail { namespace _meta { using namespace meta; template<typename ISeq, typename... Ts> struct all_same_impl : false_type {}; template<usize... Is, typename T> struct all_same_impl<meta::index_sequence<Is...>, discard_1st<decltype(Is), T>...> : true_type {}; template<> struct all_same_impl<meta::index_sequence<>> : true_type {}; } // namespace _meta } // namespace _detail namespace concepts { VEG_DEF_CONCEPT( typename... Ts, all_same, _detail::_meta::all_same_impl<meta::make_index_sequence<sizeof...(Ts)>, Ts...>::value); } // namespace concepts namespace _detail { namespace _meta { template<template<typename...> class F, typename Seq> struct apply_type_seq; template<template<typename...> class F, typename... Ts> struct apply_type_seq<F, meta::type_sequence<Ts...>> { using type = F<Ts...>; }; template<typename Valid, template<typename...> class F, typename... Seqs> struct concat_type_seq; template<typename Valid, template<typename...> class F, typename... Seqs> struct zip_type_seq; template<template<typename...> class F, typename... Seqs> struct zip_type_seq2; template<template<typename...> class F> struct zip_type_seq<meta::true_type, F> { using type = F<>; }; template<template<typename...> class F, typename... Ts> struct zip_type_seq<meta::true_type, F, F<Ts...>> { using type = F<F<Ts>...>; }; template<template<typename...> class F, typename... Ts, typename... Zipped> struct zip_type_seq2<F, F<Ts...>, F<Zipped...>> { using type = F<typename concat_type_seq<true_type, F, F<Ts>, Zipped>::type...>; }; template<template<typename...> class F, typename T> struct specializes : meta::false_type {}; template<template<typename...> class F, typename... Ts> struct specializes<F, F<Ts...>> : meta::true_type {}; template<template<typename...> class F, typename T> struct specialize_len : meta::constant<usize, 0> {}; template<template<typename...> class F, typename... Ts> struct specialize_len<F, F<Ts...>> : meta::constant<usize, sizeof...(Ts)> {}; template<template<typename...> class F, typename... Ts, typename Seq, typename... Seqs> struct zip_type_seq<meta::true_type, F, F<Ts...>, Seq, Seqs...> { using type = typename zip_type_seq2< F, F<Ts...>, typename zip_type_seq<meta::true_type, F, Seq, Seqs...>::type>::type; }; template<template<typename...> class F> struct concat_type_seq<true_type, F> { using type = F<>; }; template<template<typename...> class F, typename... Ts> struct concat_type_seq<true_type, F, F<Ts...>> { using type = F<Ts...>; }; template<template<typename...> class F, typename... Ts, typename... Us> struct concat_type_seq<true_type, F, F<Ts...>, F<Us...>> { using type = F<Ts..., Us...>; }; template<template<typename...> class F, typename... Ts, typename... Us, typename... Vs, typename... Seqs> struct concat_type_seq<true_type, F, F<Ts...>, F<Us...>, F<Vs...>, Seqs...> { using type = typename concat_type_seq< true_type, F, F<Ts..., Us..., Vs...>, typename concat_type_seq<true_type, F, Seqs...>::type>::type; }; } // namespace _meta } // namespace _detail namespace meta { template<template<typename... F> class F, typename... Seqs> using type_sequence_cat = typename _detail::_meta::concat_type_seq< bool_constant<VEG_ALL_OF(_detail::_meta::specializes<F, Seqs>::value)>, F, Seqs...>::type; template<template<typename...> class F, typename... Seqs> using type_sequence_zip = typename _detail::_meta::zip_type_seq< meta::bool_constant< VEG_ALL_OF(_detail::_meta::specializes<F, Seqs>::value) && VEG_CONCEPT( all_same< constant<usize, _detail::_meta::specialize_len<F, Seqs>::value>...>)>, F, Seqs...>::type; template<template<typename...> class F, typename Seq> using type_sequence_apply = typename _detail::_meta::apply_type_seq<F, Seq>::type; } // namespace meta namespace _detail { template<usize I, typename T> struct HollowLeaf {}; template<typename ISeq, typename... Ts> struct HollowIndexedTuple; template<usize... Is, typename... Ts> struct HollowIndexedTuple<meta::index_sequence<Is...>, Ts...> : HollowLeaf<Is, Ts>... {}; template<usize I, typename T> auto get_type(HollowLeaf<I, T> const*) VEG_NOEXCEPT->T; template<typename T, usize I> auto get_idx(HollowLeaf<I, T> const*) VEG_NOEXCEPT->meta::constant<usize, I>; template<usize I> struct pack_ith_elem { template<typename... Ts> using Type = decltype(_detail::get_type<I>( static_cast< HollowIndexedTuple<meta::make_index_sequence<sizeof...(Ts)>, Ts...>*>( nullptr))); }; template<typename T> struct pack_idx_elem { template<typename... Ts> using Type = decltype(_detail::get_idx<T>( static_cast< HollowIndexedTuple<meta::make_index_sequence<sizeof...(Ts)>, Ts...>*>( nullptr))); }; } // namespace _detail template<typename T, typename... Ts> using position_of = typename _detail::pack_idx_elem<T>::template Type<Ts...>; #if VEG_HAS_BUILTIN(__type_pack_element) template<usize I, typename... Ts> using ith = __type_pack_element<I, Ts...>; #else template<usize I, typename... Ts> using ith = typename _detail::pack_ith_elem<I>::template Type<Ts...>; #endif } // namespace veg } // namespace linalg } // namespace proxsuite #include "proxsuite/linalg/veg/internal/epilogue.hpp" #endif /* end of include guard VEG_INTEGER_SEQ_HPP_JBT0EKAQS */
dc9eaf732d754abbbb02f79b8463d75ebf472163
363ff47ec32297c25c43840d12dae4497b5f0b32
/src/InternalForces/Muscles/StateDynamics.cpp
234f9a3281a667d98e90b8ad6f4af10a80639da6
[ "MIT" ]
permissive
pyomeca/biorbd
0fd76f36a01bce2e259ddea476d712c60fb79364
70265cb1931c463a24f27013350e363134ce6801
refs/heads/master
2023-06-25T21:07:37.358851
2023-06-22T13:38:47
2023-06-22T13:38:47
124,423,173
63
43
MIT
2023-09-14T14:40:58
2018-03-08T17:08:37
C++
UTF-8
C++
false
false
5,620
cpp
StateDynamics.cpp
#define BIORBD_API_EXPORTS #include "InternalForces/Muscles/StateDynamics.h" #include "Utils/Error.h" #include "Utils/String.h" #include "InternalForces/Muscles/Characteristics.h" #ifdef USE_SMOOTH_IF_ELSE #include "Utils/CasadiExpand.h" #endif using namespace BIORBD_NAMESPACE; internal_forces::muscles::StateDynamics::StateDynamics( const utils::Scalar& excitation, const utils::Scalar& activation) : internal_forces::muscles::State(excitation,activation), m_previousExcitation(std::make_shared<utils::Scalar>(0)), m_previousActivation(std::make_shared<utils::Scalar>(0)), m_activationDot(std::make_shared<utils::Scalar>(0)) { setType(); } internal_forces::muscles::StateDynamics::StateDynamics( const internal_forces::muscles::State &other) : internal_forces::muscles::State(other) { const auto& state = dynamic_cast<const internal_forces::muscles::StateDynamics&>(other); m_previousExcitation = state.m_previousExcitation; m_previousActivation = state.m_previousActivation; m_activationDot = state.m_activationDot; } internal_forces::muscles::StateDynamics::~StateDynamics() { //dtor } internal_forces::muscles::StateDynamics internal_forces::muscles::StateDynamics::DeepCopy() const { internal_forces::muscles::StateDynamics copy; copy.DeepCopy(*this); return copy; } void internal_forces::muscles::StateDynamics::DeepCopy(const internal_forces::muscles::StateDynamics &other) { internal_forces::muscles::State::DeepCopy(other); *m_excitationNorm = *other.m_excitationNorm; *m_previousExcitation = *other.m_previousExcitation; *m_previousActivation = *other.m_previousActivation; *m_activationDot = *other.m_activationDot; } const utils::Scalar& internal_forces::muscles::StateDynamics::timeDerivativeActivation( const internal_forces::muscles::State& emg, const internal_forces::muscles::Characteristics& characteristics, bool alreadyNormalized) { return timeDerivativeActivation(emg.excitation(), emg.activation(), characteristics, alreadyNormalized); } const utils::Scalar& internal_forces::muscles::StateDynamics::timeDerivativeActivation( const utils::Scalar& excitation, const utils::Scalar& activation, const internal_forces::muscles::Characteristics &characteristics, bool alreadyNormalized) { setExcitation(excitation); setActivation(activation); return timeDerivativeActivation(characteristics, alreadyNormalized); } const utils::Scalar& internal_forces::muscles::StateDynamics::timeDerivativeActivation( const internal_forces::muscles::Characteristics &characteristics, bool alreadyNormalized) { // Implémentation de la fonction da/dt = (u-a)/GeneralizedTorque(u,a) // ou GeneralizedTorque(u,a) = t_act(0.5+1.5*a) is u>a et GeneralizedTorque(u,a)=t_deact(0.5+1.5*a) sinon #ifdef BIORBD_USE_CASADI_MATH *m_activation = IF_ELSE_NAMESPACE::if_else( IF_ELSE_NAMESPACE::lt(*m_activation, characteristics.minActivation()), characteristics.minActivation(), *m_activation); *m_excitation = IF_ELSE_NAMESPACE::if_else( IF_ELSE_NAMESPACE::lt(*m_excitation, characteristics.minActivation()), characteristics.minActivation(), *m_excitation); #else if (*m_activation < characteristics.minActivation()) { *m_activation = characteristics.minActivation(); } if (*m_excitation < characteristics.minActivation()) { *m_excitation = characteristics.minActivation(); } #endif // see doi:10.1016/j.humov.2011.08.006 // see doi:10.1016/S0021-9290(03)00010-1 // http://simtk-confluence.stanford.edu:8080/display/OpenSim/First-Order+Activation+Dynamics utils::Scalar num; if (alreadyNormalized) { num = *m_excitation - *m_activation; // numérateur } else { num = normalizeExcitation(characteristics.stateMax())- *m_activation; // numérateur } utils::Scalar denom; // dénominateur #ifdef BIORBD_USE_CASADI_MATH denom = IF_ELSE_NAMESPACE::if_else( IF_ELSE_NAMESPACE::gt(num, 0), characteristics.torqueActivation() * (0.5+1.5* *m_activation), characteristics.torqueDeactivation() / (0.5+1.5* *m_activation)); #else if (num>0) { denom = characteristics.torqueActivation() * (0.5+1.5* *m_activation); } else { denom = characteristics.torqueDeactivation() / (0.5+1.5* *m_activation); } #endif *m_activationDot = num/denom; return *m_activationDot; } const utils::Scalar& internal_forces::muscles::StateDynamics::timeDerivativeActivation() { return *m_activationDot; } void internal_forces::muscles::StateDynamics::setExcitation( const utils::Scalar& val, bool turnOffWarnings) { *m_previousExcitation = *m_excitation; internal_forces::muscles::State::setExcitation(val, turnOffWarnings); } const utils::Scalar& internal_forces::muscles::StateDynamics::previousExcitation() const { return *m_previousExcitation; } void internal_forces::muscles::StateDynamics::setActivation( const utils::Scalar& val, bool turnOffWarnings) { *m_previousActivation = *m_activation; internal_forces::muscles::State::setActivation(val, turnOffWarnings); } const utils::Scalar& internal_forces::muscles::StateDynamics::previousActivation() const { return *m_previousActivation; } void internal_forces::muscles::StateDynamics::setType() { *m_stateType = internal_forces::muscles::STATE_TYPE::DYNAMIC; }