blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
839de9caff10bc68bde5266a4243073d9fd0814d
beb0314dd976050bc41ff670537a73b24a3df6c2
/DataStructureComp/sources/type-manipulators/fibheaptypemanipulator.cpp
9afc1eca5b8163226abc892982f9f44a8cf4c480
[]
no_license
danielScLima/dsPerformanceComp
68840f8eb9bdb2e3894dc859e1fb83648efb2447
e5d5a2393b3c4cdcbec041d61a0ce52d1a3400ab
refs/heads/master
2023-02-17T10:07:16.581038
2021-01-17T20:23:46
2021-01-17T20:23:46
329,736,368
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include "headers/type-manipulators/fibHtypemanipulator.h" void FibonacciHeapTypeManipulator::initialize() { } void FibonacciHeapTypeManipulator::insert(int key) { fh.insertBeforeStart(key); } void FibonacciHeapTypeManipulator::remove(int key) { FibonacciHeapNode* node = fh.deleteMinInterface(); if (node != nullptr) delete node; } void FibonacciHeapTypeManipulator::search(int key) { fh.search(key); } void FibonacciHeapTypeManipulator::destroy() { }
2920fc86a0617af3abeb246b7f16c83950637953
31321c469832a8d3695d106f73afef611fe66e41
/BasesAreLoaded/BasesAreLoaded/Source.cpp
3073b1d241b75870ff79274a3b92a38613f5f978
[]
no_license
Travisrowe/4883_Programming_Techniques
7fc0efe67b828e3e52de63f5b1c80f50caf8c0ec
c334ba0163206f33bce89fdb5fb7879d2de10937
refs/heads/master
2020-03-28T08:31:37.222070
2018-12-10T19:38:17
2018-12-10T19:38:17
147,971,250
0
0
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
//BasesAreLoaded : UVa 355 : Travis Rowe : Thiefone18 : 10/23/18 #include <iostream> #include <string> #include <sstream> #include <algorithm> //includes reverse method using namespace std; int charVal(char c) { if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10; } string convertToBaseB(long long baseTenNum, int b) { string Nnum = ""; while (baseTenNum != 0) { int digit = baseTenNum % b; if (digit < 10) Nnum += digit + '0'; else Nnum += digit - 10 + 'A'; baseTenNum /= b; } //Num is backwards, reverse it reverse(Nnum.begin(), Nnum.end()); return Nnum; } long long convertToBaseTen(string num, int base) { long long deciNum = 0; int len = num.length(); long long power = 1; for (int i = 1; i <= len; i++) { int val = charVal(num[len - i]); if (val >= base) { cout << num << " is an illegal base " << base << " number\n"; return -1; } deciNum += val * power; power = power * base; } return deciNum; } void PrintOutput(int Obase, int Nbase, string Onum, string Nnum) { cout << Onum << " base " << Obase << " = " << Nnum << " base " << Nbase << '\n'; //printf("%s base %d = %s base %d", Onum, Obase, Nnum, Nbase); } int main() { int Obase, Nbase; string line; string Onum, Nnum; while (getline(cin, line)) { stringstream(line) >> Obase >> Nbase >> Onum; //convert our Onum to an integer in base ten long long baseTenNum = convertToBaseTen(Onum, Obase); if (baseTenNum != -1 && Nbase == 10) PrintOutput(Obase, Nbase, Onum, std::to_string(baseTenNum)); else if(baseTenNum != -1) //-1 if illegal number { Nnum = convertToBaseB(baseTenNum, Nbase); PrintOutput(Obase, Nbase, Onum, Nnum); } } }
ace66035324f9fc7b51f1224fbf28f56abb28121
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_winapi_security.hpp
eeb4633f457489aa0cee585e953d9dacc18e1580
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
37
hpp
#include <boost/winapi/security.hpp>
5c6444385e1d3c386cce5a3e3151bb76a074ad5d
434692931b1b973f22f29104930ed197cac34152
/CommonUtilities/CommonUtilities/Math/Matrix3x3.h
85c49694d96d3dfe8ad908a3080c48df93236982
[]
no_license
mrsGoransson/someStuff
67ce9fdaef9fdf41e2fa7175667bfeb6d60596b5
68271d5c01c35f0bf43a3010e10a7c101e2770f0
refs/heads/main
2023-07-03T19:57:01.096574
2021-08-08T11:45:54
2021-08-08T11:45:54
324,770,537
1
0
null
null
null
null
UTF-8
C++
false
false
8,716
h
#pragma once #include "Matrix4x4.h" #include "Vector3.h" #include <assert.h> #include <math.h> namespace CU { template<class T> class Matrix3x3 { public: Matrix3x3<T>(); Matrix3x3<T>(const Matrix3x3<T>& aMatrix); Matrix3x3<T>(const Matrix4x4<T>& aMatrix); T& operator()(const int row, const int column); const T& operator()(const int row, const int column) const; Matrix3x3<T> operator+=(Matrix3x3<T> aMatrix3x3); Matrix3x3<T> operator-=(Matrix3x3<T> aMatrix3x3); Matrix3x3<T> operator*=(Matrix3x3<T> aMatrix3x3); void operator=(Matrix3x3<T> aMatrix3x3); bool operator==(Matrix3x3<T> aMatrix3x3); static Matrix3x3<T> CreateRotationAroundX(T aAngleInRadians); static Matrix3x3<T> CreateRotationAroundY(T aAngleInRadians); static Matrix3x3<T> CreateRotationAroundZ(T aAngleInRadians); static Matrix3x3<T> Transpose(const Matrix3x3<T>& aMatrixToTranspose); private: T myMatrix[3][3]; }; template<class T> inline Matrix3x3<T>::Matrix3x3() { myMatrix[0][0] = 1; myMatrix[0][1] = 0; myMatrix[0][2] = 0; myMatrix[1][0] = 0; myMatrix[1][1] = 1; myMatrix[1][2] = 0; myMatrix[2][0] = 0; myMatrix[2][1] = 0; myMatrix[2][2] = 1; } template<class T> inline Matrix3x3<T>::Matrix3x3(const Matrix3x3<T>& aMatrix) { for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { myMatrix[column][row] = aMatrix(column + 1, row + 1); } } } template<class T> inline Matrix3x3<T>::Matrix3x3(const Matrix4x4<T>& aMatrix) { for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { myMatrix[column][row] = aMatrix(column + 1, row + 1); } } } template<class T> inline T& Matrix3x3<T>::operator()(const int row, const int column) { assert(row > 0 && column > 0 && row <= 3 && column <= 3 && "index out of range!"); return myMatrix[row - 1][column - 1]; } template<class T> inline const T& Matrix3x3<T>::operator()(const int row, const int column) const { assert(row > 0 && column > 0 && row <= 3 && column <= 3 && "index out of range!"); return myMatrix[row - 1][column - 1]; } template<class T> inline Matrix3x3<T> operator+(Matrix3x3<T> aMatrix0, Matrix3x3<T> aMatrix1) { Matrix3x3<T> tempMatrix; for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { tempMatrix(column + 1, row + 1) = aMatrix0(column + 1, row + 1) + aMatrix1(column + 1, row + 1); } } return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::operator+=(Matrix3x3<T> aMatrix3x3) { for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { myMatrix[column][row] += aMatrix3x3(column + 1, row + 1); } } return *this; } template<class T> inline Matrix3x3<T> operator-(Matrix3x3<T> aMatrix0, Matrix3x3<T> aMatrix1) { Matrix3x3<T> tempMatrix; for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { tempMatrix(column + 1, row + 1) = aMatrix0(column + 1, row + 1) - aMatrix1(column + 1, row + 1); } } return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::operator-=(Matrix3x3<T> aMatrix3x3) { for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { myMatrix[column][row] -= aMatrix3x3(column + 1, row + 1); } } return *this; } template<class T> inline Matrix3x3<T> operator*(Matrix3x3<T> aMatrix0, Matrix3x3<T> aMatrix1) { Matrix3x3<T> tempMatrix; tempMatrix(1, 1) = aMatrix0(1, 1) * aMatrix1(1, 1) + aMatrix0(1, 2) * aMatrix1(2, 1) + aMatrix0(1, 3) * aMatrix1(3, 1); tempMatrix(1, 2) = aMatrix0(1, 1) * aMatrix1(1, 2) + aMatrix0(1, 2) * aMatrix1(2, 2) + aMatrix0(1, 3) * aMatrix1(3, 2); tempMatrix(1, 3) = aMatrix0(1, 1) * aMatrix1(1, 3) + aMatrix0(1, 2) * aMatrix1(2, 3) + aMatrix0(1, 3) * aMatrix1(3, 3); tempMatrix(2, 1) = aMatrix0(2, 1) * aMatrix1(1, 1) + aMatrix0(2, 2) * aMatrix1(2, 1) + aMatrix0(2, 3) * aMatrix1(3, 1); tempMatrix(2, 2) = aMatrix0(2, 1) * aMatrix1(1, 2) + aMatrix0(2, 2) * aMatrix1(2, 2) + aMatrix0(2, 3) * aMatrix1(3, 2); tempMatrix(2, 3) = aMatrix0(2, 1) * aMatrix1(1, 3) + aMatrix0(2, 2) * aMatrix1(2, 3) + aMatrix0(2, 3) * aMatrix1(3, 3); tempMatrix(3, 1) = aMatrix0(3, 1) * aMatrix1(1, 1) + aMatrix0(3, 2) * aMatrix1(2, 1) + aMatrix0(3, 3) * aMatrix1(3, 1); tempMatrix(3, 2) = aMatrix0(3, 1) * aMatrix1(1, 2) + aMatrix0(3, 2) * aMatrix1(2, 2) + aMatrix0(3, 3) * aMatrix1(3, 2); tempMatrix(3, 3) = aMatrix0(3, 1) * aMatrix1(1, 3) + aMatrix0(3, 2) * aMatrix1(2, 3) + aMatrix0(3, 3) * aMatrix1(3, 3); return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::operator*=(Matrix3x3<T> aMatrix3x3) { Matrix3x3<T> tempMatrix = *this; myMatrix[0][0] = tempMatrix(1, 1) * aMatrix3x3(1, 1) + tempMatrix(1, 2) * aMatrix3x3(2, 1) + tempMatrix(1, 3) * aMatrix3x3(3, 1); myMatrix[0][1] = tempMatrix(1, 1) * aMatrix3x3(1, 2) + tempMatrix(1, 2) * aMatrix3x3(2, 2) + tempMatrix(1, 3) * aMatrix3x3(3, 2); myMatrix[0][2] = tempMatrix(1, 1) * aMatrix3x3(1, 3) + tempMatrix(1, 2) * aMatrix3x3(2, 3) + tempMatrix(1, 3) * aMatrix3x3(3, 3); myMatrix[1][0] = tempMatrix(2, 1) * aMatrix3x3(1, 1) + tempMatrix(2, 2) * aMatrix3x3(2, 1) + tempMatrix(2, 3) * aMatrix3x3(3, 1); myMatrix[1][1] = tempMatrix(2, 1) * aMatrix3x3(1, 2) + tempMatrix(2, 2) * aMatrix3x3(2, 2) + tempMatrix(2, 3) * aMatrix3x3(3, 2); myMatrix[1][2] = tempMatrix(2, 1) * aMatrix3x3(1, 3) + tempMatrix(2, 2) * aMatrix3x3(2, 3) + tempMatrix(2, 3) * aMatrix3x3(3, 3); myMatrix[2][0] = tempMatrix(3, 1) * aMatrix3x3(1, 1) + tempMatrix(3, 2) * aMatrix3x3(2, 1) + tempMatrix(3, 3) * aMatrix3x3(3, 1); myMatrix[2][1] = tempMatrix(3, 1) * aMatrix3x3(1, 2) + tempMatrix(3, 2) * aMatrix3x3(2, 2) + tempMatrix(3, 3) * aMatrix3x3(3, 2); myMatrix[2][2] = tempMatrix(3, 1) * aMatrix3x3(1, 3) + tempMatrix(3, 2) * aMatrix3x3(2, 3) + tempMatrix(3, 3) * aMatrix3x3(3, 3); return *this; } template<class T> inline void Matrix3x3<T>::operator=(Matrix3x3<T> aMatrix3x3) { for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { myMatrix[column][row] = aMatrix3x3(column + 1, row + 1); } } } template<class T> inline bool Matrix3x3<T>::operator==(Matrix3x3<T> aMatrix3x3) { bool isEqual; for (int column = 0; column < 3; ++column) { for (int row = 0; row < 3; ++row) { isEqual = myMatrix[column][row] == aMatrix3x3(column + 1, row + 1); if (!isEqual) { return false; } } } return isEqual; } template<class T> CU::Vector3<T> operator*(const Vector3<T> aVector3, const Matrix3x3<T> aMatrix3x3) { Vector3<T> tempVector; tempVector.x = aVector3.x * aMatrix3x3(1, 1) + aVector3.y * aMatrix3x3(2, 1) + aVector3.z * aMatrix3x3(3, 1); tempVector.y = aVector3.x * aMatrix3x3(1, 2) + aVector3.y * aMatrix3x3(2, 2) + aVector3.z * aMatrix3x3(3, 2); tempVector.z = aVector3.x * aMatrix3x3(1, 3) + aVector3.y * aMatrix3x3(2, 3) + aVector3.z * aMatrix3x3(3, 3); return tempVector; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::CreateRotationAroundX(T aAngleInRadians) { Matrix3x3<T> tempMatrix; tempMatrix(1, 1) = 1; tempMatrix(1, 2) = 0; tempMatrix(1, 3) = 0; tempMatrix(2, 1) = 0; tempMatrix(2, 2) = cos(aAngleInRadians); tempMatrix(2, 3) = sin(aAngleInRadians); tempMatrix(3, 1) = 0; tempMatrix(3, 2) = -sin(aAngleInRadians); tempMatrix(3, 3) = cos(aAngleInRadians); return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::CreateRotationAroundY(T aAngleInRadians) { Matrix3x3<T> tempMatrix; tempMatrix(1, 1) = cos(aAngleInRadians); tempMatrix(1, 2) = 0; tempMatrix(1, 3) = -sin(aAngleInRadians); tempMatrix(2, 1) = 0; tempMatrix(2, 2) = 1; tempMatrix(2, 3) = 0; tempMatrix(3, 1) = sin(aAngleInRadians); tempMatrix(3, 2) = 0; tempMatrix(3, 3) = cos(aAngleInRadians); return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::CreateRotationAroundZ(T aAngleInRadians) { Matrix3x3<T> tempMatrix; tempMatrix(1, 1) = cos(aAngleInRadians); tempMatrix(1, 2) = sin(aAngleInRadians); tempMatrix(1, 3) = 0; tempMatrix(2, 1) = -sin(aAngleInRadians); tempMatrix(2, 2) = cos(aAngleInRadians); tempMatrix(2, 3) = 0; tempMatrix(3, 1) = 0; tempMatrix(3, 2) = 0; tempMatrix(3, 3) = 1; return tempMatrix; } template<class T> inline Matrix3x3<T> Matrix3x3<T>::Transpose(const Matrix3x3<T>& aMatrixToTranspose) { Matrix3x3<T> tempMatrix; for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) { tempMatrix(j, i) = aMatrixToTranspose(i, j); } } return tempMatrix; } }
95c279e8cb1f1cef85f0ce9b29cf443ad8252c49
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_3610_squid-3.1.23.cpp
d15dcbae2e20f52959ccaf0cb03ce32b4783fff6
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
void UrnState::setUriResFromRequest(HttpRequest *r) { if (RequestNeedsMenu(r)) { updateRequestURL(r, r->urlpath.rawBuf() + 5, r->urlpath.size() - 5 ); flags.force_menu = 1; } createUriResRequest (r->urlpath); if (urlres_r == NULL) { debugs(52, 3, "urnStart: Bad uri-res URL " << urlres); ErrorState *err = errorCon(ERR_URN_RESOLVE, HTTP_NOT_FOUND, r); err->url = urlres; urlres = NULL; errorAppendEntry(entry, err); return; } HTTPMSGLOCK(urlres_r); urlres_r->header.putStr(HDR_ACCEPT, "text/plain"); }
2ed7e0772e84a10402c35743480487c32df6de47
dfee46dd7053daf7eb52459a3ac9c81d70dbf3a1
/Player.cpp
5c5939277b8321ee90059538bd78b465308087e1
[]
no_license
Ishay1997/pandemic-a
5b456552f6d091c7ae0926c3f1d0431daa757dd2
883b5c1be6a18421ea56478b2e394a0c015ddb91
refs/heads/master
2023-04-20T16:46:55.656722
2021-05-05T15:51:57
2021-05-05T15:51:57
364,617,529
0
0
null
null
null
null
UTF-8
C++
false
false
621
cpp
#include "Player.hpp" using namespace std; namespace pandemic { Player::Player(Board &board, City city) {} Player::Player(Board &board, City city, int x) {} Player Player::drive(const City &c) { return *this; } Player Player::fly_direct(const City &c) { return *this; } Player Player::fly_charter(const City &c) { return *this; } Player Player::fly_shuttle(const City &c) { return *this; } Player Player::build() { return *this; } Player Player::discover_cure(const Color &c) { return *this; } Player Player::treat(const City &c) { return *this; } Player Player::take_card(const City &c) { return *this; } }
c4b4ac9b2f7971c65d0ee59ab9beea2712297c8f
0e693b0f2ef8eb7fa7fdc33aa225a8849a80ad14
/src/dsmanage/StatusWin.h
3c60311a5f956416d6f0e17484b1ba9f7adc14db
[]
no_license
ncareol/zebra
b40bed1845bc5741cabf50cad7244d61156895e3
1f9f2e7cf99db82cab840536245e90a9ac95bdff
refs/heads/master
2022-05-07T02:36:45.619871
2022-03-24T21:35:56
2022-03-24T21:35:56
124,604,310
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
h
// // Status window for loading data. // /* Copyright (C) 1987,88,89,90,91,92 by UCAR * University Corporation for Atmospheric Research * All rights reserved * * No part of this work covered by the copyrights herein may be reproduced * or used in any form or by any means -- graphic, electronic, or mechanical, * including photocopying, recording, taping, or information storage and * retrieval systems -- without permission of the copyright owner. * * This software and any accompanying written materials are provided "as is" * without warranty of any kind. UCAR expressly disclaims all warranties of * any kind, either express or implied, including but not limited to the * implied warranties of merchantibility and fitness for a particular purpose. * UCAR does not indemnify any infringement of copyright, patent, or trademark * through use or modification of this software. UCAR does not provide * maintenance or updates for its software. */ class StatusWindow : public dsPopupWindow { Widget sw_textline; Widget sw_scroll; int sw_nf, sw_bytes; int sw_abort; public: StatusWindow (const char *, int nf, int bytes); ~StatusWindow (); void popdown () { delete this; }; int status (int nf, int bytes); void setAbort (int value) { sw_abort = value; } };
debacd312f553cfc11ca404ddd1fb54dba63055f
1963d07b4520a6d4379e988241b8f2fb1a75b8ca
/ASP2019/ASP2019/PZ3/Z1/main.cpp
5deb4100d4a5929b25c63e270ca2e7b6cb3ccd21
[]
no_license
bsuljic1/Data-Structure-And-Algorithms
f776decfac0648f426dcab2eb0a294eccdfe86ed
0cf9f89a40e3d1f1a1b466015f5be31db2439c81
refs/heads/master
2023-02-28T21:42:31.038958
2021-01-31T15:16:56
2021-01-31T15:16:56
334,270,003
0
0
null
null
null
null
UTF-8
C++
false
false
2,485
cpp
#include <iostream> template<typename Tip> class Cvor { public: Tip element; Cvor *sljedeci; Cvor() { sljedeci = nullptr; } Cvor(const Cvor &c) { element = c.element; sljedeci = c.sljedeci; } Cvor(const Tip &el, Cvor *sl) : element(el), sljedeci(sl) {}; }; template<typename Tip> class Stek { Cvor<Tip> *Vrh = nullptr; int velicina = 0; public: Stek() {}; ~Stek() { brisi(); delete Vrh; } Stek(const Stek &s) { velicina = s.velicina; Cvor<Tip> *q; Cvor<Tip> *p = s.Vrh; Vrh = 0; while(p != 0) { Cvor<Tip> *n = new Cvor<Tip>(p->element, 0); if(Vrh == 0 ) Vrh = n; else q->sljedeci = n; q = n; p = p->sljedeci; } } Stek &operator =(const Stek &s) { velicina = s.velicina; if(&s == this) return *this; brisi(); Cvor<Tip> *q; Cvor<Tip> *p = s.Vrh; Vrh = 0; while(p != 0) { Cvor<Tip> *n = new Cvor<Tip>(p->element, 0); if(Vrh == 0) Vrh = n; else q->sljedeci = n; q = n; p = p->sljedeci; } return *this; } void brisi() { while(Vrh != 0) skini(); } void stavi(const Tip& el) { Cvor<Tip> *p = new Cvor<Tip>(el, Vrh); Vrh = p; //Vrh = new Cvor(el,Vrh); velicina++; } Tip skini() { if(Vrh == nullptr) throw("Stek je prazan"); Tip el = Vrh->element; Cvor<Tip> *p = Vrh->sljedeci; delete Vrh; Vrh = p; velicina--; return el; } Tip& vrh() const { if(Vrh == 0) throw("Stek je prazan"); return Vrh->element; } int brojElemenata() { return velicina; } }; void testFunkcija(){ Stek<int> s; for(int i = 1; i <= 10; i++) s.stavi(i); std::cout << s.skini() << std::endl; std::cout << s.brojElemenata() << std::endl; std::cout << s.vrh() << std::endl; Stek<int> s2; for(int i = 1; i <= 5; i++) s2.stavi(i); s = s2; std::cout << s.skini() << std::endl; std::cout << s.vrh() << std::endl; s.brisi(); s2.brisi(); } int main() { std::cout << "Pripremna Zadaca Za Vjezbu 3, Zadatak 1" << std::endl; testFunkcija(); return 0; }
c60617cb8bb922af61381dc93b6ce123bba8eebd
e5423140f1894992af36c8b5ea2f42855d8c4701
/gyroclient.ino
92e7cdc307646c578e42407a37ca6d75da68abec
[]
no_license
TimtimSMART/Future-Da-Codes
aaa2fcf8b2c52c9b53b41e5bda2d66cf6117d3ba
9675cd34aa36561ffbd08e85b04bca02c980692e
refs/heads/master
2022-12-04T05:38:22.549475
2020-08-19T11:21:10
2020-08-19T11:21:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
ino
#include <ESP8266WiFi.h> #include <Wire.h> #include <ITG3205.h> #include <math.h> #include <Ticker.h> ITG3205 itg3205; Ticker Time; float deltaGz; float gz_prev=0; float degz = 0; float anglez = 0; int serverport = 88; IPAddress server(192,168,4,1); WiFiClient client2; void interrupt() { itg3205.itg3205ReadGyro(); float gz=itg3205.itg3205GyroZ(); // deltaGz = gz + gz_prev; // anglez = (deltaGz/2)*0.01; // if((fabs(gz-gz_prev)/0.01)>1) // { // degz = degz + anglez; // } // //X=(fabs(gz-gz_prev))/0.01; // gz_prev = gz; // //Serial.print(X); // Serial.println(degz); anglez=gz*0.01; degz = degz + anglez; gz_prev = gz; Serial.println(degz); client2.println(degz); client2.flush(); } void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(115200); pinMode(2, OUTPUT); if(WiFi.status() == WL_CONNECTED) { WiFi.disconnect(); WiFi.mode(WIFI_OFF); delay(50); } WiFi.mode(WIFI_STA); WiFi.begin("ARADA","123456789"); //check connectivity while(WiFi.status() != WL_CONNECTED) { for(int i=0; i < 10; i++) { digitalWrite(2, !HIGH); delay(250); digitalWrite(2, !LOW); delay(250); Serial.print("."); } Serial.println(""); } digitalWrite(2, !HIGH); //Stop Blinking To Indicate Connected Serial.println("!-- Client Device Connected --!"); Serial.print ("Server IP Address : "); Serial.println(server); Serial.print ("Server Port Num : "); Serial.println(serverport); client2.stop(); // If Sucessfully Connected Send Connection Message if(client2.connect(server, serverport)) { Serial.println ("CONNECTED"); client2.println ("CONNECTED"); } delay(100); itg3205.itg3205initGyro(); delay(100); itg3205.itg3205CalGyro(); delay(100); Time.attach(0.01,interrupt); } void loop() { // put your main code here, to run repeatedly: }
b33e2efb410307ae0dc1cfab6402a6916e4ccdbc
3b1fb2557b629738a1909a89e4b0364f94c3de31
/utils/mutex_wrapper.h
0702440021582eb779aace90d3fed2d6bd129d38
[]
no_license
wangscript007/common_library
78816267e4542270277c7cb5c3551fba8b3b5b78
7e591a83282e67b83a1d149ccccc1fbd674c7d68
refs/heads/master
2023-01-22T09:12:06.928323
2020-11-23T06:54:27
2020-11-23T06:54:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
650
h
#ifndef COMMON_LIBRARY_MUTEX_WRAPPER_H #define COMMON_LIBRARY_MUTEX_WRAPPER_H #include <mutex> #define LOCK_GUARD(mux) std::lock_guard<decltype(mux)> lock(mux) namespace common_library { template <typename Mux = std::recursive_mutex> class MutexWrapper { public: MutexWrapper(bool enable) { enable_ = enable; } ~MutexWrapper() {} public: inline void lock() { if (enable_) { mux_.lock(); } } inline void unlock() { if (enable_) { mux_.unlock(); } } private: bool enable_; Mux mux_; }; } // namespace common_library #endif
4673b4d29bd7000e9b169d5b9d19c308fb8f5c98
bc6c37cf0469c6b2778707b76227558b3a040718
/Other/2018kickstart/RoundD/c.cpp
b4342377b55f7804c450ba8d25e2b4e08d8e5e47
[]
no_license
zeroplusone/AlgorithmPractice
241530a5c989f6321543f7bd07a393c405cdf2e6
7fe9182d943bc2066f7fd31cc05096be79dc12cb
refs/heads/master
2022-01-28T21:57:04.393943
2022-01-26T13:46:43
2022-01-26T13:46:43
84,074,414
2
1
null
null
null
null
UTF-8
C++
false
false
731
cpp
#include <bits/stdc++.h> using namespace std; #define ForN(i,n) for (i=0; i<n; i++) #define For1N(i,n) for (i=1; i<=n; i++) #define ForAB(i,a,b) for (i=a; i<=b; i++) #define ForNR(i,n) for (i=(n)-1; i>=0; i--) #define For1NR(i,n) for (i=n; i>0; i--) #define ForABR(i,a,b) for (i=b; i>=a; i--) #define ForBE(i,s) for (i=s.begin(); i!=s.end(); i++) #define Fill(s,v) memset(s,v,sizeof(s)) #define Debug(x) cout << #x" = " << x <<endl; #define LL long long #define LD long double #define PR pair<int,int> #define pb push_back #define mp make_pair #define x first #define y second int main() { int T; scanf("%d", &T); for(int tt = 1; tt <= T; tt++){ printf("Case #%d: ", tt); printf("Answer\n"); } }
f969043198938c00a87fc34123bc57896eeb464b
b3a158034526daacee4427fa2eae0b797f904924
/ServiceProject/Deamon/DeamonClassFactory.h
67a058dd5559ac88cead0b616cd2a7d5e449e938
[]
no_license
15831944/Corpse
e1785c12d620f7defd16ab0b0abb0705907815c9
51ca96ada1db58272fff3bdbdff165200be96191
refs/heads/master
2023-06-29T08:36:07.487065
2021-05-22T01:31:41
2021-05-22T01:31:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
441
h
#pragma once class CDeamonClassFactory : public IClassFactory { public: CDeamonClassFactory(); ~CDeamonClassFactory(); public: // IUnknown STDMETHOD_(ULONG, AddRef)(); STDMETHOD_(ULONG, Release)(); STDMETHOD(QueryInterface)(REFIID riid, void** ppv); // IClassFactory STDMETHOD(CreateInstance)(IUnknown* pUnkOuter, REFIID riid, void** ppv); STDMETHOD(LockServer)(BOOL fLock); protected: ULONG m_uRefCount; };
[ "Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7" ]
Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7
b80f719f774906b9d672c4f516d4debccef9bd30
1306171f2763287c287785858c31c6681cefc6fc
/File1(stc c++)/unorderset.c++
47f7a1198977a9c9da1a6541c3edafe17bbfad09
[]
no_license
pratap0007/C-Data-Structure-and-Algorithm
8e6ea4ec4c9517721f489e37f9fdf6d665f3a0a8
0dbb857ae805a7bed3ca5756c9c9d233263c0d34
refs/heads/master
2020-04-30T07:14:13.470096
2019-05-16T03:22:07
2019-05-16T03:22:07
176,678,240
0
0
null
null
null
null
UTF-8
C++
false
false
194
#include<bits/stdc++.h> using namespace std; #include<unordered_set> int main() { unordered_set <int> ux; ux.insert(1); ux.insert(2); ux.insert(3); ux.insert(1); cout<<ux.find(1); return 0; }
5bdff1852d9232f11b680e9b10e84d85a60d31ce
b05ad8baaad75df38405c6ca594d55600c77d64b
/NetWork/download.h
91fdc70cd2a12da474bebf680c7558b87d6ffa24
[ "Apache-2.0" ]
permissive
jjsz/KLive
d8e71b6d5c88b329c1e4da81dd62fb026ae646fe
490fc56e3c32f30fce5a2e956355cd2d53777bda
refs/heads/master
2021-10-11T00:02:41.612410
2019-01-19T14:24:01
2019-01-19T14:24:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
692
h
#ifndef DOWNLOAD_H #define DOWNLOAD_H #include <QObject> #include <QFile> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkAccessManager> class Download : public QObject { Q_OBJECT public: explicit Download(QObject *parent = nullptr); ~Download(); private: QNetworkAccessManager *NetManager = NULL; QNetworkReply *Reply = NULL; QFile *File = NULL; signals: void sig_DownLoadFinish(QString filename); void sig_downloadProgress(double all,double current); public slots: bool startDown(QUrl url); void readyRead(); void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void finished(); }; #endif // DOWNLOAD_H
4cc334434608d1ae5aa57e2a7870b7c6e57a38ea
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/VCSamples/VC2010Samples/MFC/Visual C++ 2008 Feature Pack/PaletteDemo/MainFrm.h
f6397760566aef1a4d2a2d891f097fd807e0f807
[ "MIT" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
1,646
h
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #pragma once #include "ToolsPalette.h" class CMainFrame : public CFrameWndEx { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CMFCMenuBar m_wndMenuBar; CMFCStatusBar m_wndStatusBar; CMFCToolBar m_wndToolBar; CToolsPalette m_wndPalette; protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnViewToolsPalette(); afx_msg void OnUpdateViewToolsPalette(CCmdUI* pCmdUI); afx_msg void OnTwoColumns(); afx_msg void OnUpdateTwoColumns(CCmdUI* pCmdUI); afx_msg void OnThreeColumns(); afx_msg void OnUpdateThreeColumns(CCmdUI* pCmdUI); afx_msg void OnFourColumns(); afx_msg void OnUpdateFourColumns(CCmdUI* pCmdUI); afx_msg LRESULT OnToolbarContextMenu(WPARAM,LPARAM); afx_msg void OnViewCustomize(); DECLARE_MESSAGE_MAP() virtual BOOL OnShowPopupMenu (CMFCPopupMenu* pMenuPopup); };
bdea066dc25504211db4e840de1ab794c128cede
de7d7418c1542d04a35522e2d3d6b92359b5d717
/Edge.cpp
754798c28efed2478b20ad8bb70720b021409390
[]
no_license
Wanderinglc/FCM_3D
89a60fdb1736e85c10415d22606cab1d3a1c9ca9
99abc22f390c0a6219b49a5690a5a9100235d5d3
refs/heads/master
2020-07-27T01:09:02.214713
2019-10-07T02:26:01
2019-10-07T02:26:01
208,818,680
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
/*======================================================================= Edge Define the attributes of Edge for finite element method. =======================================================================*/ //#include "Edge.h" // // // //Edge::Edge() {} // //Edge::Edge(const int polynomialDegree, const int dofDimension) //{ // numberOfDofsPerFieldComponent = polynomialDegree - 1; // dofs.resize(numberOfDofsPerFieldComponent*dofDimension); //} // //Edge::~Edge() //{ // // nothing for now //}
e8b8791f5f7a13ebcd834f3dc29fd3566908783f
d956ffdbe73474a2f2e463623e0ff9fac563f8fe
/Tham lam/GRECUTSEG.cpp
67c1df959d31772bccf6ed734adfb6ee33d46579
[]
no_license
NghiaST/VinhDinhCoder
a5c5babe71e1dc742eae42a5940d699947e8aa70
7c7f9f428ecb4d4e66ceed617c576f5d0061cd73
refs/heads/main
2023-08-19T20:17:41.669372
2021-10-26T07:51:07
2021-10-26T07:51:07
361,578,717
5
2
null
null
null
null
UTF-8
C++
false
false
1,033
cpp
#include <iostream> #include <algorithm> using namespace std; int t, n, nxt[100005]; pair<int,int> a[100005]; void ReadInt(int &x) { char c = getchar(); while (!isdigit(c)) c = getchar(); x = 0; while (isdigit(c)) x = (x<<3) + (x<<1) + c - '0', c = getchar(); } int main() { ReadInt(t); while (t--) { ReadInt(n); for(int i=1; i<=n; i++) ReadInt(a[i].first), a[i].second = i; sort(a+1, a+n+1); a[n+1].first = -1; for(int i=1; i<=n; i++) if (a[i].first == a[i+1].first) nxt[a[i].second] = a[i+1].second; else nxt[a[i].second] = n+1; int _left=0, _right=0; for(int i=1, lft=1, rgt=n+1; i<=n; i++) { if (rgt>nxt[i]) rgt=nxt[i]; if (rgt==i) { if (_left) cout << _left << ' ' << _right << '\n'; _left = lft; _right = rgt; lft=i+1; rgt=n+1; } } if (!_left) cout << "-1\n"; else cout << _left << ' ' << n << '\n'; } }
0aa4f244730ef1b891c9ebff8d0ee2bcb4642594
a1faa9455a5e9e39db0d6448f7ba244d77eb51cc
/sources/draw.cpp
2ea6fbf96a65aa56330a26dab3156b1f67116f11
[ "MIT" ]
permissive
indjev99/Pong
1e0e068b8a03c9cbc476e0f0957afb448bbb536c
bb5eb346c025172f21bf537ba47501ad55fe3f3f
refs/heads/master
2021-01-13T02:56:32.312949
2019-09-27T11:00:10
2019-09-27T11:00:10
77,081,303
0
0
null
null
null
null
UTF-8
C++
false
false
2,062
cpp
#include "../headers/draw.h" #include "../headers/window_size.h" #include "../headers/window_functions.h" #include "../headers/colours.h" #include "../headers/dimensions.h" #include<math.h> const double DEG2RAD=3.14159/180.0; void drawPartEllipse(float x, float y, float radiusX, float radiusY, double alpha, double beta) { alpha=round(alpha*2); beta=round(beta*2); glBegin(GL_TRIANGLES); for(int i=alpha;i<beta;++i) { float rad=i*0.5*DEG2RAD; float rad2=(i+1)*0.5; while (rad2>=360) rad2-=360; rad2*=DEG2RAD; glVertex2f(cos(rad)*radiusX+x,sin(rad)*radiusY+y); glVertex2f(cos(rad2)*radiusX+x,sin(rad2)*radiusY+y); glVertex2f(x,y); } glEnd(); } void drawWindow(GLFWwindow* w, std::vector<Ball>& balls, double p1H, double p2H) { glfwSetWindowShouldClose(w,0); pressed=-1; float ratio; int width, height; glfwMakeContextCurrent(w); glfwGetFramebufferSize(w,&width,&height); ratio=width/(float)height; glViewport(0,0,width,height); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-ratio,ratio,-1.f,1.f,1.f,-1.f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(BACKGROUND_COLOUR_R,BACKGROUND_COLOUR_G,BACKGROUND_COLOUR_B); glBegin(GL_QUADS); glVertex2f(-1.0,-1.0); glVertex2f(1.0,-1.0); glVertex2f(1.0,1.0); glVertex2f(-1.0,1.0); glEnd(); glColor3f(FOREGROUND_COLOUR_R,FOREGROUND_COLOUR_G,FOREGROUND_COLOUR_B); for (int i=0;i<balls.size();++i) { drawPartEllipse(balls[i].x,balls[i].y,thickness,thickness,0,360); } glBegin(GL_QUADS); glVertex2f(-1.0+thickness,p1H-length); glVertex2f(-1.0,p1H-length); glVertex2f(-1.0,p1H+length); glVertex2f(-1.0+thickness,p1H+length); glEnd(); glBegin(GL_QUADS); glVertex2f(1.0-thickness,p2H-length); glVertex2f(1.0,p2H-length); glVertex2f(1.0,p2H+length); glVertex2f(1.0-thickness,p2H+length); glEnd(); glfwSwapBuffers(w); }
d2ea32e80f465678ec6f80d220c5422bf7eb742b
15b322d609ed38de5392b67fc578fbbd22a4b7d0
/TextArt/BADA/FSclPhoneNumber.h
e9c8277f9a759ffb79bbfaf711e903f022c05b19
[]
no_license
Vizantiec/Bada
7725bb06cecb72267218220bec05a99879fc2087
51a3f544c8e0193dbf374d3a8042d867dbca9818
refs/heads/master
2016-09-11T02:18:26.326902
2013-12-23T10:22:35
2013-12-23T10:22:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,177
h
/* $Change: 1142016 $ */ // // Copyright (c) 2011 Samsung Electronics Co., Ltd. // All rights reserved. // This software contains confidential and proprietary information // of Samsung Electronics Co., Ltd. // The user of this software agrees not to disclose, disseminate or copy such // Confidential Information and shall use the software only in accordance with // the terms of the license agreement the user entered into with Samsung. // /** * @file FSclPhoneNumber.h * @brief This is the header file for the %PhoneNumber class. * * This header file contains the declarations of the %PhoneNumber class. */ #ifndef _FSCL_PHONE_NUMBER_H_ #define _FSCL_PHONE_NUMBER_H_ // Includes #include "FBaseResult.h" #include "FBaseString.h" #include "FSclConfig.h" namespace Osp { namespace Social { // Enums and Constants /** * Defines the types of phone number. * * @since 1.0 */ enum PhoneNumberType { PHONENUMBER_TYPE_HOME, /**< The phone number type is home telephone*/ PHONENUMBER_TYPE_WORK, /**< The phone number type is work telephone*/ PHONENUMBER_TYPE_MOBILE, /**< The phone number type is mobile */ PHONENUMBER_TYPE_HOME_FAX, /**< The phone number type is home fax */ PHONENUMBER_TYPE_WORK_FAX, /**< The phone number type is work fax */ PHONENUMBER_TYPE_PAGER, /**< The phone number type is pager */ PHONENUMBER_TYPE_OTHER /**< The phone number type is other */ }; /** The maximum length of the phone number property. * * @since 1.0 */ static const int MAX_PHONE_NUMBER_LENGTH = 50; /** * @class PhoneNumber * @brief This class stores the information of a phone number. * @since 1.0 * * The %PhoneNumber class consists of the phone number and phone number type. * * The following example demonstrates how to use the %PhoneNumber class. * * @code using namespace Osp::Base; using namespace Osp::Social::Services; void MyClass::SomeMethod(void) { result r = E_SUCCESS; // Creates an instance of PhoneNumber. PhoneNumber phoneNumber = PhoneNumber(); // Sets the number. r = phoneNumber.SetPhoneNumber(L"010-111-2222"); if (IsFailed(r)) { return r; } // Sets the type. phoneNumber.SetType(PHONENUMBER_TYPE_MOBILE); return E_SUCCESS; } * @endcode */ class _EXPORT_SOCIAL_ PhoneNumber: public Osp::Base::Object { // Construct Operation public: /** * This is the default constructor for this class. * * @since 1.0 */ PhoneNumber(void); /** * Initializes this instance of %PhoneNumber with the specified type and phone number. * * @since 1.0 * @param[in] type The type of the phone number * @param[in] number The phone number */ PhoneNumber(PhoneNumberType type, const Osp::Base::String& number); /** * This is the copy constructor for the %PhoneNumber class. * * @since 1.0 * @param[in] value An instance of %PhoneNumber */ PhoneNumber(const PhoneNumber& value); /** * This is the destructor for this class. * * @since 1.0 */ virtual ~PhoneNumber(void); public: /** * Copies the data contained in the specified instance of %PhoneNumber to the current instance. * * @since 1.0 * @param[in] value An instance of %PhoneNumber */ PhoneNumber& operator =(const PhoneNumber& value); /** * Checks whether the data in the specified instance of %PhoneNumber is equal to the data in the current instance. * * @since 1.0 * @return @c true if the data in the specified instance equals the data in the current instance, @n * else @c false * @param[in] rhs An instance of %PhoneNumber */ bool operator ==(const PhoneNumber& rhs) const; /** * Checks whether the data in the specified instance of %PhoneNumber is not equal to the data in the current instance. * * @since 1.0 * @return @c true if the data in the specified instance is not equal to the data in the current instance, @n * else @c false * @param[in] rhs An instance of %PhoneNumber */ bool operator !=(const PhoneNumber& rhs) const; // Operations public: /** * Gets the type of the phone number. * * @since 1.0 * @return The type of the phone number */ PhoneNumberType GetType(void) const; /** * Gets the phone number. * * @since 1.0 * @return The phone number */ Osp::Base::String GetPhoneNumber(void) const; /** * Sets the type of the phone number. * * @since 1.0 * @param[in] type The type of the phone number */ void SetType(PhoneNumberType type); /** * Sets the phone number for the current instance of %PhoneNumber. @n * Only alphabets (a~z, A~Z), numbers, plus (+), asterisk (*), pound (#), and comma (,) are allowed for the phone number * and all the other characters will be removed. * * @since 1.0 * @return An error code * @param[in] number The phone number * @exception E_SUCCESS The method is successful. * @exception E_INVALID_ARG The specified number is an empty string, or @n * the length of the specified number exceeds #MAX_PHONE_NUMBER_LENGTH. */ result SetPhoneNumber(const Osp::Base::String& number); private: PhoneNumberType __type; Osp::Base::String __phoneNumber; friend class PhoneNumberEx; class PhoneNumberEx* __pPhoneNumberEx; }; // PhoneNumber };};// Osp::Social #endif//_FSCL_PHONE_NUMBER_H_
36f5b0ae3a35bb6332083befaa66a7e1e8aa43e3
36c99aa5e74ce00e699c20577baa8298e62b9582
/codechif_DSA/1.11.cpp
e3e055234017d5cf486e161977110e8f340ab6e0
[]
no_license
Tiwari12abha/c-competitive-programming-
bed3749b51eb81d1f437f0085fc84e749f96d3b5
5527441db8e958270156d5e98f5319b3acf560a5
refs/heads/main
2023-07-03T07:01:09.246912
2021-08-12T14:12:44
2021-08-12T14:12:44
395,340,043
0
0
null
null
null
null
UTF-8
C++
false
false
149
cpp
//Add natrual numbers #include<iostream> using namespace std; int main(){ long long n; cin>>n; cout<<(n*(n+1))/2; return 0; }
869bdafffa69c8c928603c00dbc857388522cebb
9a33566bdd5fd8a1a7f40b27f69ad8d1118f8f18
/epoch/ayla/include/ayla/api.hpp
0767fb4017ead9fdc054f1aa1b493985c713275e
[ "MIT" ]
permissive
nwalablessing/vize
d0968f6208d608d9b158f0b21b0d063a12a45c81
042c16f96d8790303563be6787200558e1ec00b2
refs/heads/master
2023-05-31T15:39:02.877681
2019-12-22T14:09:02
2019-12-22T14:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
320
hpp
#ifndef AYLA_API_HPP #define AYLA_API_HPP #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) #if defined(AYLA_LIB) #define AYLA_API __declspec(dllexport) #else #define AYLA_API __declspec(dllimport) #endif #endif #ifndef AYLA_API #define AYLA_API #endif #endif // AYLA_API_HPP
29a66dbd6eb62e0d946b5eaa9af9b2281fe2a4fe
750b12e612ed4689a103715332a43c5f32abec38
/lab8-Stack/Stack/BaseConverting.cpp
58e0efab9444a96623521242a3c4e62057e82aa1
[]
no_license
lang22/-
d4c8e88ad001c86f1c800f1ef9a8b54cddc33d4e
b0551a0ce9ebf79c87ac49c9be0514fd2faf1092
refs/heads/master
2020-04-01T23:00:38.255650
2018-10-19T06:54:46
2018-10-19T06:54:46
153,736,913
0
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
#include"BaseConverting.h" #include<iostream> using namespace std; void convert() { Stack<int> num; cout << "please enter a postive number!" << endl; long long int m; cin >> m; while (cin.fail()) { cin.clear(); cin.sync(); cin.ignore(); cout << "you bad! Invalid input! Resume!" << endl; cin >> m; } cout << "please enter the base(2~16)!" << endl; int b; cin >> b; while (cin.fail()||b<2||b>16) { cin.clear(); cin.sync(); cin.ignore(); cout << "you bad! Invalid input! Resume!" << endl; cin >> b; } cout << "Successfully convert!" << endl; while (m != 0) { num.push(m%b); m /= b; } while (!num.empty()) { char c = num.top() - 10 + 'A'; // cout <<( num.top() > 9 ?c:num.top()); if (num.top() > 9) cout << c; else cout << num.top(); num.pop(); } cout << endl; return; }
f879abeba2de5b280fa82d4f81c609330268fb6e
b389f1f3075092f7cb25f45ee9bf910c55250735
/WorkInProgress/Codeforces - Grakn Forces 2020/A. Circle Coloring/sol.cpp
552567958a444d22113eb9e29ec011c97d3e0656
[]
no_license
leostd/Competitive-Programming
7b3c4c671e799216c79aeefd2ca7d68c5d463fa6
4db01b81314f82c4ebb750310e5afb4894b582bd
refs/heads/master
2023-05-13T07:04:40.512100
2023-05-06T10:58:28
2023-05-06T10:58:28
87,685,033
0
1
null
null
null
null
UTF-8
C++
false
false
3,992
cpp
/* think first, always - c,g,a, alg - r,s,iag?,iabs? */ #pragma GCC diagnostic ignored "-Wunused-const-variable" #include <iostream> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <bitset> #include <random> #include <chrono> #include <complex> #include <algorithm> #include <utility> #include <functional> #include <cmath> #include <cstring> #include <cassert> #include <cstdio> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; #define mp make_pair #define pb push_back #define forn(i, n) for(int i = 0; i < (int)(n); ++i) #define for1(i, n) for(int i = 1; i < (int)(n); ++i) #define nfor(i, n) for(int i = int(n) - 1; i >= 0; --i) #define fore(i, l, r) for(int i = int(l); i < int(r); ++i) #define correct(x, y, n, m) (0 <= x && x < n && 0 <= y && y < m) #define all(x) (x).begin(), (x).end() #define fst first #define snd second #define endl "\n" typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, int> pli; typedef pair<ll, ll> pll; typedef long double ld; typedef tuple<int,int,int> iii; template<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); } template<typename T> inline T sqr(T a){ return a * a; } template<class T> T gcd(T a, T b) { return a ? gcd (b % a, a) : b; } template<class T> T lcm(T a, T b) { return a / gcd (a, b) * b; } template<class T> T sign(T a) { return a > 0 ? 1 : (a < 0 ? -1 : 0); } string to_string(string s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } void dbg() { cout << endl; } template <typename Head, typename... Tail> void dbg(Head H, Tail... T) { cout << " " << to_string(H); dbg(T...); } #ifdef DEBUG #define dbg(...) cout << "(" << #__VA_ARGS__ << "):", dbg(__VA_ARGS__) #else #define dbg(...) #endif void fastIO() { cin.sync_with_stdio(false); cin.tie(0); } template<typename T> vector<T> make_unique(vector<T> v) { sort(all(v)); return v.resize(unique(all(v)) - v.begin()); } int nxt() { int x; cin >> x; return x; } const int dx[4] = {0, 0, 1, -1}; const int dy[4] = {1, -1, 0, 0}; const int dxKn[8] = {-2, -1, 1, 2, 2, 1, -1, -2}; const int dyKn[8] = { 1, 2, 2, 1, -1, -2, -2, -1}; const int dxK[8] = {0, 0, 1, -1, 1, 1, -1, -1}; const int dyK[8] = {1, -1, 0, 0, 1, -1, 1, -1}; const int MOD = int(1e9) + 7; const int INF = int(1e9) + 100; const ll INF64 = 2e18; const ld PI = ld(3.1415926535897932384626433832795); const ld e = ld(2.7182818284590452353602874713527); const ld EPS = 1e-9; //############################# const int MAXN = 1000005; void solve() { int n = nxt(); vector<int> a(n, 0), b,c, ans; b = c = a; generate(all(a), nxt); generate(all(b), nxt); generate(all(c), nxt); ans.pb(a[0]); for1(i, n-1){ int aux; if (a[i] != ans.back()) aux = a[i]; else if (b[i] != ans.back()) aux = b[i]; else aux = c[i]; ans.pb(aux); } int i = n-1; int aux = -1; dbg(ans); dbg(a[i], b[i], c[i], ans.back()); if (a[i] != ans.back() && a[i] != ans[0]) aux = a[i]; else if (b[i] != ans.back() && b[i] != ans[0]) aux = b[i]; else aux = c[i]; ans.pb(aux); for(auto x : ans){ cout << x << " "; } cout << endl; } int main() { fastIO(); int t = nxt(); while(t--) { solve(); } return 0; }
6d591dcf8f5c040bcb092fa86d6a9508f234bdfc
8928e745a14ea907a3fb488d63d8d6437e84457b
/Loops/factorial/factorial.cpp
58169e3d158b134956fcc9c560dd3ef8be524a6d
[]
no_license
subhodynamics/codeclass
8b653b53fc2fecb1e0520f924e29d1aa2753568c
8fb30525f7f4290c50d256881132dc5b31a26f1b
refs/heads/classwork
2023-07-20T22:01:08.786744
2021-09-10T13:23:20
2021-09-10T13:25:45
338,342,379
0
1
null
2021-07-14T07:32:57
2021-02-12T14:31:14
C
UTF-8
C++
false
false
241
cpp
#include<iostream> using namespace std; int main() { int fact,n; fact=1; cout<<"enter a no"<<"\t"; cin>>n; cout<<"\n"; for(int i=1;i<=n;i++) { fact*=i; } cout<<n<<" != "<<fact; return 0; }
a92f8db48525db02875992e67ff06ba1d57756d9
94a78cedf3d9fadf3c15385406ff43848e96e72d
/src/test/scheduler_tests.cpp
b044568fd43d698d2bd78c6a786dfbfe5d50fd1e
[ "MIT" ]
permissive
BitCoinONE1/BTCONE-Blockchain
02bfbfb4f096232299e01f85d5f6e28111805791
bccc7e28878b2572f8cafa6c0e4e896745b33a27
refs/heads/master
2020-04-13T23:57:55.114465
2019-01-16T19:26:32
2019-01-16T19:26:32
163,520,721
4
4
MIT
2019-01-16T13:06:36
2018-12-29T15:20:56
C++
UTF-8
C++
false
false
4,969
cpp
// Copyright (c) 2012-2013 The Bitcoin Core developers // Copyright (c) 2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "scheduler.h" #if defined(HAVE_CONFIG_H) #include "config/bitcoinone-config.h" #else #define HAVE_WORKING_BOOST_SLEEP_FOR #endif #include <boost/bind.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/thread.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(scheduler_tests) static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime) { { boost::unique_lock<boost::mutex> lock(mutex); counter += delta; } boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min(); if (rescheduleTime != noTime) { CScheduler::Function f = boost::bind(&microTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime); s.schedule(f, rescheduleTime); } } static void MicroSleep(uint64_t n) { #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::microseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::microseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } BOOST_AUTO_TEST_CASE(manythreads) { seed_insecure_rand(false); // Stress test: hundreds of microsecond-scheduled tasks, // serviced by 10 threads. // // So... ten shared counters, which if all the tasks execute // properly will sum to the number of tasks done. // Each task adds or subtracts from one of the counters a // random amount, and then schedules another task 0-1000 // microseconds in the future to subtract or add from // the counter -random_amount+1, so in the end the shared // counters should sum to the number of initial tasks performed. CScheduler microTasks; boost::mutex counterMutex[10]; int counter[10] = { 0 }; boost::random::mt19937 rng(insecure_rand()); boost::random::uniform_int_distribution<> zeroToNine(0, 9); boost::random::uniform_int_distribution<> randomMsec(-11, 1000); boost::random::uniform_int_distribution<> randomDelta(-1000, 1000); boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); boost::chrono::system_clock::time_point now = start; boost::chrono::system_clock::time_point first, last; size_t nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 0); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 100); BOOST_CHECK(first < last); BOOST_CHECK(last > now); // As soon as these are created they will start running and servicing the queue boost::thread_group microThreads; for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); MicroSleep(600); now = boost::chrono::system_clock::now(); // More threads and more tasks: for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } // Drain the task queue then exit threads microTasks.stop(true); microThreads.join_all(); // ... wait until all the threads are done int counterSum = 0; for (int i = 0; i < 10; i++) { BOOST_CHECK(counter[i] != 0); counterSum += counter[i]; } BOOST_CHECK_EQUAL(counterSum, 200); } BOOST_AUTO_TEST_SUITE_END()
98b95624a17f025b8b0ab6f6214e394678bddca8
59b8ea5e919fe9761fe5799e9f591850d71383c0
/codechef/long/may_2020/nanobots.cpp
e8b8f610d343f2c5567ddae1362be21eeaab345c
[]
no_license
utsavkuchhal/Competitive-Programming
a25db05aaf16009910497c1b1127815fece332aa
fd16601f223dbd168c4a3efda7d78af799ac4602
refs/heads/master
2023-04-18T00:33:31.738464
2021-04-24T03:07:50
2021-04-24T03:07:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,863
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define f(i,n) for(int i=0;i<n;i++) #define fs(i,s,n) for(int i=s;i<n;i++) #define ff first #define ss second #define int long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define mii map<int,int> #define pqb priority_queue<int> #define pqs priority_queue<int,vi,greater<int> > #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define MOD 998244353; #define inf 1e18 #define ps(x,y) fixed<<setprecision(y)<<x #define mk(arr,n,type) type *arr=new type[n]; #define w(x) int x; cin>>x; while(x--) #define PI 3.1415926535897932384626 mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; int inv(int a) { int r = 1, t = a, k = MOD - 2; while (k) { if (k & 1) r = (long long) r * t % MOD; t = (long long) t * t % MOD; k >>= 1; } return r; } int mpow(int base, int exp) { base %= mod; int result = 1; while (exp > 0) { if (exp & 1) result = (result * base) % mod; base = (base * base) % mod; exp >>= 1; } return result; } void sm25official() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int32_t main(){ sm25official(); int n, f; cin>>n>>f; int a[n][n]; f(i, n){ f(j, n){ cin>>a[i][j]; } } int k; cin>>k; vector<pair<char, int>> horhits; int hcelldes=0; f(i, n){ int sum1=0; int celdes1=0; f(j, n){ sum1+=a[i][j]; if(sum1==f){ celdes1+=j+1; break; } else if(sum1>f){ sum1-=a[i][j]; celdes1+=j; break; } } int sum2=0; int celdes2=0; for(int j=n-1;j>=0;j--){ sum2+=a[i][j]; if(sum2==f){ celdes2+=n-j; break; } else if(sum2>f){ sum2-=a[i][j]; celdes2= n-j-1; break; } } if(celdes1>celdes2){ hcelldes+=celdes1; horhits.pb(mp('L',i+1)); } else if(celdes1<celdes2){ hcelldes+=celdes2; horhits.pb(mp('R',i+1)); } else{ if(sum1>=sum2){ hcelldes+=celdes1; horhits.pb(mp('L',i+1)); } else{ hcelldes+=celdes2; horhits.pb(mp('R',i+1)); } } } vector<pair<char, int>> verhits; int vcelldes=0; f(j, n){ int sum1=0; int celdes1=0; f(i, n){ sum1+=a[i][j]; if(sum1==f){ celdes1=i+1; break; } else if(sum1>f){ sum1-=a[i][j]; celdes1=i; break; } } int sum2=0; int celdes2=0; for(int i=n-1;i>=0;i--){ sum2+=a[i][j]; if(sum2==f){ celdes2=n-i; break; } else if(sum2>f){ sum2-=a[i][j]; celdes2=n-i-1; break; } } if(celdes1>celdes2){ vcelldes+=celdes1; verhits.pb(mp('U',j+1)); } else if(celdes1<celdes2){ vcelldes+=celdes2; verhits.pb(mp('D',j+1)); } else{ if(sum1>sum2){ vcelldes+=celdes1; verhits.pb(mp('U',j+1)); } else{ vcelldes+=celdes2; verhits.pb(mp('D',j+1)); } } } if(vcelldes>=hcelldes){ for(auto k: verhits){ if(k.ff=='U'){ int po=f; f(i, n){ int j=k.ss-1; if(po>=a[i][j]){ po-=a[i][j]; a[i][j]=0; if(po<=0){ break; } } else{ break; } } } else{ int po=f; for(int i=n-1;i>=0;i--){ int j=k.ss-1; if(po>=a[i][j]){ po-=a[i][j]; a[i][j]=0; if(po<=0){ break; } } else{ break; } } } } f(i, n){ int po=f; f(j, n){ if(a[i][j]==0 && po==f) continue; if(po>=a[i][j]){ po-=a[i][j]; if(po<=0 || j==n-1){ verhits.pb(mp('L', i+1)); po=f; } } else{ verhits.pb(mp('L', i+1)); po=f; po-=a[i][j]; if(j==n-1){ verhits.pb(mp('L', i+1)); } } } } cout<<verhits.size()<<endl; for(auto i:verhits){ cout<<i.ff<<" "<<i.ss<<endl; } } else{ for(auto k: horhits){ if(k.ff=='L'){ int po=f; f(i, n){ int j=k.ss-1; if(po>=a[j][i]){ po-=a[j][i]; a[j][i]=0; if(po<=0){ break; } } else{ break; } } } else{ int po=f; for(int i=n-1;i>=0;i--){ int j=k.ss-1; if(po>=a[j][i]){ po-=a[j][i]; a[j][i]=0; if(po<=0){ break; } } else{ break; } } } } // f(i,n){ // f(j, n){ // cout<<a[i][j]<<" "; // } // cout<<endl; // } f(j, n){ int po=f; f(i, n){ if(a[i][j]==0 && po==f) continue; if(po>=a[i][j]){ po-=a[i][j]; if(po<=0 || i==n-1){ horhits.pb(mp('U', j+1)); po=f; } } else{ horhits.pb(mp('U', j+1)); po=f; po-=a[i][j]; if(j==n-1){ horhits.pb(mp('U', j+1)); } } } } cout<<horhits.size()<<endl; for(auto i:horhits){ cout<<i.ff<<" "<<i.ss<<endl; } } return 0; }
e10359e960f3b83844477ef962e38d90c0f291fb
bbf83fa8c6b540f8c057a370b4d683f1c0b023bf
/CarambolaChat/Model/DCCChat/dcc_chat_connection.h
deba79f519635a6438e4e75b1a34581107f1ab6c
[]
no_license
dpjudas/CarambolaChat
af5b8c171f3b61b645db4aab0a8824401a2878a1
87f38a9fff9e64258149168bfef706c6753c4440
refs/heads/master
2020-04-06T06:58:50.554238
2016-06-23T08:03:28
2016-06-23T08:03:28
39,250,669
0
1
null
2015-11-26T09:22:14
2015-07-17T11:21:56
C++
UTF-8
C++
false
false
1,458
h
#pragma once #include "../IRCSession/irc_text.h" class DCCChatConnection { public: DCCChatConnection(const std::string &local_nick, const std::string &remote_nick, const uicore::SocketName &socket_name); ~DCCChatConnection(); void connect(); void offer(); void send_line(const IRCText &text); void disconnect(); std::string local_nick; std::string remote_nick; uicore::Signal<void(const std::string &)> sig_system_text; uicore::Signal<void(const std::string &)> sig_disconnected; uicore::Signal<void(const IRCText &)> sig_text_line; private: void process(); void worker_main(); bool read_connection_data(uicore::TCPConnection &connection, IRCRawString &read_line); bool write_connection_data(IRCRawString &write_line, IRCRawString::size_type &write_pos, uicore::TCPConnection &connection); void queue_system(const IRCRawString &text); void queue_disconnected(const IRCRawString &reason); void queue_line(const IRCRawString &line); struct Message { enum Type { type_system, type_text, type_disconnect }; Message(Type type, IRCRawString text) : type(type), text(text) { } Type type; IRCRawString text; }; uicore::SocketName socket_name; std::thread thread; std::mutex mutex; std::condition_variable started_event; uicore::NetworkConditionVariable change_event; bool stop_flag = false; bool started_flag = false; bool is_server; std::vector<Message> send_queue; std::vector<Message> receive_queue; };
16f30f1924a366dbac7965a326e1936808e59be7
9eb7064a8d890f97419d07ac434ab0c27899cfac
/m02/target14-3.cpp
e920a6c9f2f2809ff64799b195b9a9830fd5e268
[ "MIT" ]
permissive
campbellcole/CS200
9e656a8ea483bbb84954affa254cd5b4a233d2de
333df210e70757da7cec481314b1a1e734fd03ed
refs/heads/master
2022-04-26T04:11:47.801541
2020-05-02T20:55:47
2020-05-02T20:55:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
cpp
// This program demonstrates a static member function. #include <iostream> #include <iomanip> using namespace std; class Budget { static double corpBudget; // Static member variable double divisionBudget; // Instance member variable public: Budget() { divisionBudget = 0; } void addBudget(double b) { divisionBudget += b; corpBudget += b; } double getDivisionBudget() const { return divisionBudget; } double getCorpBudget() const { return corpBudget; } static void mainOffice(double); // Static member function }; double Budget::corpBudget = 0; void Budget::mainOffice(double moffice) { corpBudget += moffice; } int main() { int count; // Loop counter const int NUM_DIVISIONS = 4;// Number of divisions double mainOfficeRequest; // Main office budget request // Get the main office's budget request. // Note that no instances of the Budget class have been defined. double mainOfficeRequest; // Main office budget request cout << "Enter the main office's budget request: "; cin >> mainOfficeRequest; Budget::mainOffice(mainOfficeRequest); Budget divisions[NUM_DIVISIONS]; // An array of Budget objects. // Get the budget requests for each division. for (count = 0; count < NUM_DIVISIONS; count++) { double budgetAmount; cout << "Enter the budget request for division "; cout << (count + 1) << ": "; cin >> budgetAmount; divisions[count].addBudget(budgetAmount); } // Display the budget requests and the corporate budget. cout << fixed << showpoint << setprecision(2) << "\nHere are the division budget requests:\n"; for (count = 0; count < NUM_DIVISIONS; count++) { cout << "\tDivision " << (count + 1) << "\t$ " << divisions[count].getDivisionBudget() << endl; } cout << "\tTotal Budget Requests:\t$ " << divisions[0].getCorpBudget() << endl; }
e72a1fcdd8f50c4dd9015cbdd8619228b1f61298
4ca18c4cdd5a26f29f53d0044eb3054c2d5916ca
/mlp/mlp.h
ede0d79716480123039c4b497796500ed5d11379
[]
no_license
samfu1994/4j_project
6fd2d08340a82d9dd68818ef58da7fce2b6a7292
e194e9de30270c5d4fe3c178b9b8411ba0b92a66
refs/heads/master
2021-01-06T20:41:49.665480
2015-05-10T13:02:29
2015-05-10T13:02:29
33,973,834
1
0
null
null
null
null
UTF-8
C++
false
false
1,742
h
/********************************************************************* * File : mlp.h * Author: Sylvain BARTHELEMY * mailto:[email protected] * http://www.sylbarth.com * Date : 2000-08 *********************************************************************/ #ifndef _MLP_H_ #define _MLP_H_ #include <vector> #include "../liblinear/linear.h" using namespace std; struct Neuron { double x; /* sortie */ double e; /* erreur */ double* w; /* poids */ double* dw; /* dernier poids pour les momentum */ double* wsave; /* poids sauvegard� */ }; struct Layer { int nNumNeurons; Neuron* pNeurons; }; class MultiLayerPerceptron { int nNumLayers; Layer* pLayers; double dMSE; double dMAE; void RandomWeights(); void SetInputSignal (double* input); void GetOutputSignal(double* output); void SaveWeights(); void RestoreWeights(); void PropagateSignal(); void ComputeOutputError(double* target); void BackPropagateError(); void AdjustWeights(); void Simulate(double* input, double* output, double* target, bool training); void ConvertFeatureNode(const struct feature_node *x, double *t); public: double dEta; double dAlpha; double dGain; double dAvgTestError; MultiLayerPerceptron(int nl, int npl[]); ~MultiLayerPerceptron(); int Train(const char* fnames); int Train(const struct problem *prob,const struct parameter *param); int Test (const char* fname); int Test (const struct problem *prob,const struct parameter *param); double predict(const struct feature_node *x); void Run(const char* fname, const int maxiter); void Run(const struct problem *prob,const struct parameter *param, int maxiter); }; #endif
c75fef3019c3ef7602cc77b519e0e0bae865a585
840fcc8e5dbca3a0de6a608b4f2a59a02d779b6a
/src/mainmenustate.cpp
74d234cedbb35a2cd4a4fb5b9137efb8688aad49
[]
no_license
marcoswicket/algorithm-analysis
39404c2c56eb741449bbc98e89c89e8c2243bdf5
fecf8d3d8af1843694e079e8b9e05138fc603e7e
refs/heads/master
2021-08-19T08:48:37.185890
2017-11-25T15:50:36
2017-11-25T15:50:36
108,470,028
0
0
null
null
null
null
UTF-8
C++
false
false
1,887
cpp
#include <iostream> #include <assert.h> #include "mainmenustate.h" const std::string MainMenuState::menuID = "MENU"; // Button callbacks void MainMenuState::menuToPlay() { // TODO: Need to properly create a new state; //Window::getAppStateMachine()->changeState(); std::cout << "I'm working bro relax" << std::endl; Window::getAppStateMachine()->changeState(new ConvexHullState()); } void MainMenuState::exitFromMenu() { Window::quitApplication(); } void MainMenuState::update() { // TODO: Properly make colision with the buttons for(int i = 0 ; i < (int) menuButtons.size() ; i++) { menuButtons[i]->update(); } } void MainMenuState::render() { // TODO: Render all objects related to this thing for(int i = 0 ; i < (int) menuButtons.size() ; i++) { menuButtons[i]->render(); } SDL_SetRenderDrawColor(Window::getRenderer(), bgColor[0], bgColor[1], bgColor[2], bgColor[3]); } bool MainMenuState::onEnter() { // TODO: Alloc all things bgColor[0] = 149; bgColor[1] = 225; bgColor[2] = 211; bgColor[3] = 255; // Thats a long line, just adding the buttons to our button vector menuButtons.push_back(new MenuButton(&menuToPlay, Window::getWindowWidth() * 0.105, Window::getWindowHeight() * 0.87 - 50, 243, 129, 129, 255)); menuButtons.push_back(new MenuButton(&exitFromMenu, Window::getWindowWidth() * 0.58, Window::getWindowHeight() * 0.87 - 50, 243, 129, 129, 255)); menuButtons[0]->loadTexture("assets/start.png"); menuButtons[1]->loadTexture("assets/quit.png"); return true; } bool MainMenuState::onExit() { // TODO: Free all things for(int i = 0 ; i < (int) menuButtons.size() ; i++) { menuButtons.back()->clean(); menuButtons.pop_back(); } menuButtons.clear(); std::cout << "Exiting MenuState" << std::endl; return true; } //void MainMenuState::setCallbacks(const std::vector<Callback>& callbacks) { // TODO: Set callbacks for buttons //}
fc9c9fb3b7680dd47419b61604ccff64ad9b65f5
07460e0f8517bfe062ed74de1d932bdb8a664a41
/include/tuplehandlerdustcart.h
49fd7ab62101734b6c6ce5e252c2195fb1c331d6
[]
no_license
benadler/peis_ros
6814588ecd5cca07d7c6dd166402cab864d4f471
db38dfa48571d64e65ccf76136185becfd5933f1
refs/heads/master
2016-09-05T22:59:26.888526
2013-01-31T18:37:54
2013-01-31T18:37:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
h
#include <ros/ros.h> #include <tf/tf.h> #include <std_msgs/String.h> #include <tuplehandler.h> #include <peis.h> class TupleHandlerDustCart : public TupleHandler { public: TupleHandlerDustCart(const std::string& robotName, Peis* peis); virtual ~TupleHandlerDustCart(void); // reimplemented form TupleHandler bool processTuple(PeisTuple* t); const std::string getPattern(); protected: ros::Subscriber mRosSubDustCartStatus; void onRosDustCartStatusChange(const std_msgs::String::ConstPtr& msg); struct LastCommand { // the COMMAND-Tuple came from owner 123, so we should send the STATE -> COMPLETE packet back to this owner in callbackDone. int tupleOwner; // the COMMAND-Tuple's key was Dustcart1.MoveTo.14.*, so we should send the STATE -> COMPLETE packet back using this prefix in callbackDone. std::string tuplePrefix; std::string action; LastCommand() { tupleOwner = 0; } }; LastCommand mLastCommand; std::string mRobotName; Peis* mPeis; ros::NodeHandle mRosNodeHandle; ros::Publisher mRosPublisher; };
e82343a30720a89c584beffef46cd15bd852b383
a77cae61867e4fb947f88acb4e11603d9cd0f6d1
/LeetCode/Leetcode68面_二叉树最近公共祖先.cpp
0ed84561ab93a1bf5763ba3d579a7b3d4f98c96e
[]
no_license
CHOcho-quan/OJ-Journey
cbad32f7ab52e59218ce4741097d6fa0ac9b462f
a9618891b5e14790ba65914783e26f8a7aa03497
refs/heads/master
2023-06-09T15:35:27.418405
2023-06-01T00:57:11
2023-06-01T00:57:11
166,665,271
1
0
null
null
null
null
UTF-8
C++
false
false
1,294
cpp
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *result; int findTreeNode(TreeNode *root, int p, int q) { if (root == NULL) return 0; if (root->val == p) { int left = findTreeNode(root->left, p, q), right = findTreeNode(root->right, p, q); if (left == 2 || right == 2) { result = root; return -1000; } return 1; } if (root->val == q) { int left = findTreeNode(root->left, p, q), right = findTreeNode(root->right, p, q); if (left == 1 || right == 1) { result = root; return -1000; } return 2; } int left = findTreeNode(root->left, p, q), right = findTreeNode(root->right, p, q); if (left + right == 3) { result = root; return -1000; } return left + right; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { findTreeNode(root, p->val, q->val); return result; } int main() { string s = "abc", t = "cda"; cout << CheckPermutation(s, t); }
72146df0d5f36b549358d4a7a4fb3fe01e25eb1a
1d7e5e8269d7ef7a3cd951d41bbb14d6b942bad3
/2ndLab/include/stack.h
3aee3cb699696a786f4b96f6540536fe95535fa2
[]
no_license
sudhansu15/lab-assignments
6a1d29fea9e87f2a418a15d7506a13294ed32020
53254cac4a36e12a5c2d96cb651e29571f579bdf
refs/heads/master
2023-07-12T11:48:57.906622
2021-08-21T13:55:02
2021-08-21T13:55:02
377,398,305
0
1
null
null
null
null
UTF-8
C++
false
false
342
h
#pragma once #include <iostream> template <class T> class stack { public: virtual ~stack() {} virtual bool isEmpty() const = 0; virtual bool isFull() const = 0; virtual bool push(const T &element) = 0; virtual bool pop(T &element) = 0; virtual bool top(T &element) const = 0; /* virtual void print() = 0; */ };
c9c41e3238c3bb5ac0b15a57e1ff7047901638c8
d0a70993a4b6f73af29f161f988b64985e9b6e80
/GlutApp.h
a1351f3ea37659beb16e551bc507869405ae4b12
[]
no_license
EtcetFelix/Pong-toss-game
23271b5f29ea4d370903462ede445b0a1c79a460
12158a564a12eb439174f5c708c6779967b60b45
refs/heads/main
2023-07-03T17:20:58.077045
2021-08-05T20:57:44
2021-08-05T20:57:44
393,167,621
0
0
null
null
null
null
UTF-8
C++
false
false
1,709
h
#ifndef GlutApp_h #define GlutApp_h #if defined WIN32 #include <freeglut.h> #elif defined __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif class GlutApp { int width; int height; const char* title; bool fullscreen; // Prevent derived classes from defining these constructors GlutApp(){} GlutApp(const GlutApp&){} static void glutDisplayCB(); static void glutKeyDownCB(unsigned char, int, int); static void glutKeyUpCB(unsigned char, int, int); static void glutSpecialKeyDownCB(int, int, int); static void glutSpecialKeyUpCB(int, int, int); static void glutMouseCB(int, int, int, int); static void glutMotionCB(int, int); static void glutPassiveMotionCB(int x, int y); static void glutResizeCB(int, int); static void glutIdleCB(); friend void windowToScene(float&, float&); protected: GlutApp(int, char**, int = 600, int = 600, const char* title = "GLUT Application"); public: void run(); void redraw(); void toggleFullScreen(); virtual void draw() const = 0; virtual void keyDown(unsigned char, float, float){} virtual void keyUp(unsigned char, float, float){} virtual void specialKeyDown(int, float, float){} virtual void specialKeyUp(int, float, float){} virtual void leftMouseDown(float, float){} virtual void rightMouseDown(float, float){} virtual void leftMouseUp(float, float){} virtual void rightMouseUp(float, float){} virtual void drag(float, float){} virtual void moveMouse(float, float){} virtual void idle(){} virtual ~GlutApp(){} }; #endif
57cd930f1d082411f6981967c3c8b30b33f7b0bd
c069df36af6ae8cfc51b19b442ad48b80dbd875f
/src/pomolite/pomoresult.h
d23c5852dee812e1ede1bfa7f9e4652c172dfb29
[]
no_license
hkmix/pomoqt
ba259ee28ed22ba4be607c124a62e13362f9fc26
07f70ab71b52ccdb0ab4baff6df2e3a356880f4c
refs/heads/master
2021-01-12T09:33:09.618715
2016-12-11T19:05:50
2016-12-11T19:05:50
76,193,657
0
0
null
null
null
null
UTF-8
C++
false
false
1,851
h
#ifndef POMORESULT_H #define POMORESULT_H #include <exception> #include <string> enum class PomoResultCode { SUCCESS, FAIL, }; // Exception class PomoResultException : public std::exception { public: PomoResultException(const std::string& msg); PomoResultException(const char* msg); virtual const char* what() const noexcept; private: const char* msg_; }; PomoResultException::PomoResultException(const std::string& msg) : msg_(msg.c_str()) { } PomoResultException::PomoResultException(const char* msg) : msg_(msg) { } const char* PomoResultException::what() const noexcept { return msg_; } // PomoResult class template<typename T> class PomoResult { public: PomoResult(); PomoResult(PomoResultCode code, T value); PomoResult(PomoResultCode code, T&& value); bool successful() const; PomoResultCode code() const; const T& value() const; private: const PomoResultCode code_; T value_; }; template<typename T> PomoResult<T>::PomoResult() : code_(PomoResultCode::FAIL) { } template<typename T> PomoResult<T>::PomoResult(PomoResultCode code, T value) : code_(code) , value_(value) { } template<typename T> PomoResult<T>::PomoResult(PomoResultCode code, T&& value) : code_(code) , value_(value) { } /** * @brief Simple code check * @return Whether result is SUCCESS */ template<typename T> bool PomoResult<T>::successful() const { return code_ == PomoResultCode::SUCCESS; } /** * @brief Retrieve result code * @return PomoResultCode result */ template<typename T> PomoResultCode PomoResult<T>::code() const { return code_; } /** * @brief Retrieve value * @return Result value */ template <typename T> const T& PomoResult<T>::value() const { if (!successful()) { throw PomoResultException("Cannot access value of failed query."); } return value_; } #endif // POMORESULT_H
f0fd7f64f07439d43c300bb897f512950574b04d
6ca64ae363fe6ad5b0d630e28a8c55dd4aed5c05
/Software/Linux_App_Driver/ui.cpp
3b7f1a8dfe82dca900353def668d9897c772c836
[ "MIT" ]
permissive
iscalab/PCIe_FPGA_Accel
d7d9fba2849273050ef7b68167ed2ebd03b84f55
bd601ac5b212583fd6329721ff21a857ae45a0d6
refs/heads/master
2020-03-22T09:23:16.963328
2018-07-05T10:50:27
2018-07-05T10:50:27
139,833,637
7
1
null
null
null
null
UTF-8
C++
false
false
143,958
cpp
/******************************************************************************* * Filename: ui.cpp * Author: Dimitrios Bakoyiannis <[email protected]> * License: * * MIT License * * Copyright (c) [2018] [Dimitrios Bakoyiannis] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ********************************************************************************/ /* * -------------- * Public Headers * ----------------> */ #include <sys/ioctl.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <stdint.h> #include <pthread.h> #include <sys/syscall.h> #include <sys/file.h> /* * ------------- * Local Headers * ---------------> */ #include "xilinx_pci_driver.h" /* * ---------------- * Global Variables * ------------------> */ /* * Flags (access_status_x) Used to Indicate the Completion of an Acceleration Group. * Their Values Change by the Corresponding Signal Handler Below Depending on the Received Signal. * The Application Remains in Polling Mode Reading One/Some of the Following Flags * until it Changes to Non-Zero Value Indicating the Completion of the Acceleration. */ int access_status_0 = 0; int access_status_1 = 0; int access_status_2 = 0; int access_status_3 = 0; int access_status_4 = 0; int access_status_5 = 0; int access_status_6 = 0; int access_status_7 = 0; /* * total_reserved_size is the Total Number of Bytes that an Image Requires which is (Width * Height * 4). * The Images are in .bmp Format which Requires 3 Bytes for each Pixel. * In order to Have Aligned Image Trasfers the Acceleration System Requires 4 Bytes per Pixel. * As a Result Each Pixel Uses an Extra Byte (Dummy) as Padding to Fill the 4 Bytes Requirement. */ int total_reserved_size; /* * The uint_shared_kernel_address is Used to Map the PCIe BAR1 of the PCIe Bridge to the Userspace Virtual Address Space. * PCIe BAR1 Represents a BRAM Memory Inside the FPGA which is Used to Store Metrics Information, SG Lists and Synchronization Flags. * By Mapping the PCIe BAR1 the Userspace Application ic Able to Have Direct Access to the BRAM Memory of the FPGA. * The shared_kernel_address Pointer, also, Points to the BRAM Memory as the uint_shared_kernel_address Pointer but it Makes it Possible * to Access the Memory According to the Fields of the struct shared_repository */ unsigned int *uint_shared_kernel_address = NULL; struct shared_repository *shared_kernel_address = NULL; /* * The uint_32_pcie_bar_kernel_address is Used to Map the PCIe BAR0 of the PCIe Bridge to the Userspace Virtual Address Space. * PCIe BAR0 Represents the AXI Address Space of the FPGA where All the FPGA Peripherals are Mapped. * By Mapping the PCIe BAR0 the Userspace Application is Able to Have Direct Access to the Peripherals of the FPGA. * The uint_64_pcie_bar_kernel_address Pointer, also, Points to the FPGA Peripherals as the uint_32_pcie_bar_kernel_address Pointer but * it Makes it Possible to Make 64 Bit Data Reads/Writes. */ unsigned int *uint_32_pcie_bar_kernel_address = NULL; uint64_t *uint_64_pcie_bar_kernel_address = NULL; /* * The sigaction Structures are Used to Setup the Signal Handlers for each Signal Received by the Driver * There are 8 Signals Specified each for the 7 Acceleration Groups (Two Signals for the Scatter/Gather) */ struct sigaction interrupt_signal_action_0; struct sigaction interrupt_signal_action_1; struct sigaction interrupt_signal_action_2; struct sigaction interrupt_signal_action_3; struct sigaction interrupt_signal_action_4; struct sigaction interrupt_signal_action_5; struct sigaction interrupt_signal_action_6; struct sigaction interrupt_signal_action_sg; /* * pcie_bar_0_mmap_file and pcie_bar_1_mmap_file are Used to Map the PCIe BAR0 and PCIe BAR1 to the Userspace. * This Way the Userspace Application Can Have Direct Access to the FPGA Peripherals And Memories. */ int pcie_bar_0_mmap_file; int pcie_bar_1_mmap_file; /* * Structures that are Used to Store Info from the Header of the Image File * * bmpfile_magic_t magic_number --> The Structure that Stores the Magic Number of the Bitmap Image * bmpfile_header_t bitmap_file_header --> The File Header of the Bitmap Image * bitmap_info_header_t bitmap_info_header --> The Info Header of the Bitmap Image */ bmpfile_magic_t magic_number; bmpfile_header_t bitmap_file_header; bitmap_info_header_t bitmap_info_header; /* * Used to Store the Process ID (PID) */ unsigned int pid; /* * common_load (Pointer) Points to an Allocated Memory where the Image is Initially Loaded from the Storage Device. * This Allocated Memory is Shareable among the Threads of the Application. * Each Thread Copies the Image Data from this Shareable Memory to Its Exclusive Memory Allocation before Requesting Acceleration * This Technique is Used to Avoid Loading the Image Multiple Times for each Iteration of each Thread which Has Serious Latency Impact */ uint8_t *common_load; /* * global_iterations Indicates the Number of Times that each Thread Should Run to Request Acceleration * The Value of this Variable is Given as an Argument when this Application is Called */ int global_iterations = 0; /* * save_request Indicates whether the Thread is going to Save the Accelerated Image. * Saving an Image Has Serious Latency Impact thus it Should be Optional in Some Cases * The Value of this Variable is Given as an Argument when this Application is Called * There are 3 Different Values that this Variable Can be Given: * * 0 --> Do Not Save the Image * 1 --> Save the Image in EACH Iteration * 2 --> Save the Image ONLY in the Last Iteration */ int save_request = 0; /* * load_path_name is Used to Store the Path and Filename of the Image File that the Application is going to Load * The Value of this Array is Given as an Argument when this Application is Called */ char load_path_name[100]; /* * Structure pthread_barrier_t is Used to Force all the Threads of the Application to Start Simultaneously * A Barrier is a Point where the Thread is Going to Wait for other Threads and Will Proceed Further only when * the Predefined Number of Threads Reach the Same Barrier. */ pthread_barrier_t threads_barrier; /* * renamer_value is Used when Saving the Multiple .xml Files that Keep Metrics Info. * The Application will Run a Number of Tests which is Given as an Argument. * Each Test Raises a Number of Threads which is, also, Given as an Argument * and each Thread Makes a Number of Acceleration Requests According to the global_iterations Described Above. * For Each Test the Application Saves a new .xml File. * In order to Dynamically Name each .xml File we use the renamer_value Variable. * The Application Reads an Arithmetic Value from a Specific .txt File and Stores it in the renamer_value. * The new .xml File is Named According to the renamer_value. * The Arithmetic Value of the .txt File is then Incremented for the Next .xml File. */ int renamer_value = 0; /* * --------------------- * Functions Declaration * -----------------------> */ void signal_handler_0(int, siginfo_t *, void *); void signal_handler_1(int, siginfo_t *, void *); void signal_handler_2(int, siginfo_t *, void *); void signal_handler_3(int, siginfo_t *, void *); void signal_handler_4(int, siginfo_t *, void *); void signal_handler_5(int, siginfo_t *, void *); void signal_handler_6(int, siginfo_t *, void *); void signal_handler_sg(int, siginfo_t *, void *); int setup_signal_handling(); void clear_screen(); int load_bmp(uint8_t *); int save_bmp(uint8_t *, char *); uint64_t convert_cycles_2_ns(uint64_t); int file_size(FILE *); int print_save_metrics(struct shared_repository_process *, int, unsigned int, int); int set_save_accelerator(char *, int, int, int); int pcie_bar_mmap(); struct shared_repository_process * shared_repo_mmap(struct per_thread_info *); uint8_t * pre_process_mmap(struct per_thread_info *); uint8_t * post_process_mmap(struct per_thread_info *); void* start_thread(void *); int multi_threaded_acceleration(int); int acceleration_thread(); /* * --------------------- * Functions Description * -----------------------> */ /* OK * signal_handler_x() * * The Driver Can Send Signals to the Application to Indicate the Completion of an Acceleration. * There is One Signal Dedicated for each Acceleration Group. * When the Application Requests Acceleration it Remains in Polling Mode Reading a Specific Flag * that Indicates the Status of the Acceleration. * The Signal Handler is Called to Change the Corresponding Flag Depending on the Acceleration Group on Completion of the Acceleration. * The Signal Method is not Currently Used but is Kept for Future Implementations that Might Require Signal Handling */ void signal_handler_0(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_0 = DEFAULT_SIGNAL_0;//ACCELERATOR_DIRECT_0_OCCUPIED; } void signal_handler_1(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_1 = DEFAULT_SIGNAL_1;//ACCELERATOR_DIRECT_1_OCCUPIED; } void signal_handler_2(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_2 = DEFAULT_SIGNAL_2;//ACCELERATOR_INDIRECT_0_OCCUPIED; } void signal_handler_3(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_3 = DEFAULT_SIGNAL_3;//ACCELERATOR_INDIRECT_1_OCCUPIED; } void signal_handler_4(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_4 = DEFAULT_SIGNAL_4;//ACCELERATOR_INDIRECT_2_OCCUPIED; } void signal_handler_5(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_5 = DEFAULT_SIGNAL_5;//ACCELERATOR_INDIRECT_3_OCCUPIED; } void signal_handler_6(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_6 = DEFAULT_SIGNAL_6;//ACCELERATOR_SG_OCCUPIED; } void signal_handler_sg(int sig, siginfo_t *siginfo, void *c) { #ifdef DEBUG_MESSAGES_UI printf("Received Signal %d from Kernel Module\n", sig); #endif access_status_7 = DEFAULT_SIGNAL_SG;//ACCELERATOR_SG_TO_OCCUPY; } /* OK * setup_signal_handling() * * Sets Up each Signal Handler with a Dedicated Signal */ int setup_signal_handling() { unsigned int pid; /* * Set the struct interrupt_signal_action_0 with the Signal Handler (signal_handler_0) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_0 */ interrupt_signal_action_0.sa_sigaction = &signal_handler_0; /* * Set the Flags for the struct interrupt_signal_action_0 */ interrupt_signal_action_0.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_0 Signal According to the struct interrupt_signal_action_0. */ if (sigaction(DEFAULT_SIGNAL_0, &interrupt_signal_action_0, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 0 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_1 with the Signal Handler (signal_handler_1) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_1 */ interrupt_signal_action_1.sa_sigaction = &signal_handler_1; /* * Set the Flags for the struct interrupt_signal_action_1 */ interrupt_signal_action_1.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_1 Signal According to the struct interrupt_signal_action_1. */ if (sigaction(DEFAULT_SIGNAL_1, &interrupt_signal_action_1, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 1 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_2 with the Signal Handler (signal_handler_2) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_2 */ interrupt_signal_action_2.sa_sigaction = &signal_handler_2; /* * Set the Flags for the struct interrupt_signal_action_2 */ interrupt_signal_action_2.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_2 Signal According to the struct interrupt_signal_action_2. */ if (sigaction(DEFAULT_SIGNAL_2, &interrupt_signal_action_2, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 2 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_3 with the Signal Handler (signal_handler_3) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_3 */ interrupt_signal_action_3.sa_sigaction = &signal_handler_3; /* * Set the Flags for the struct interrupt_signal_action_3 */ interrupt_signal_action_3.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_3 Signal According to the struct interrupt_signal_action_3. */ if (sigaction(DEFAULT_SIGNAL_3, &interrupt_signal_action_3, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 3 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_4 with the Signal Handler (signal_handler_4) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_4 */ interrupt_signal_action_4.sa_sigaction = &signal_handler_4; /* * Set the Flags for the struct interrupt_signal_action_4 */ interrupt_signal_action_4.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_4 Signal According to the struct interrupt_signal_action_4. */ if (sigaction(DEFAULT_SIGNAL_4, &interrupt_signal_action_4, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 4 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_5 with the Signal Handler (signal_handler_5) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_5 */ interrupt_signal_action_5.sa_sigaction = &signal_handler_5; /* * Set the Flags for the struct interrupt_signal_action_5 */ interrupt_signal_action_5.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_5 Signal According to the struct interrupt_signal_action_5. */ if (sigaction(DEFAULT_SIGNAL_5, &interrupt_signal_action_5, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 5 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_6 with the Signal Handler (signal_handler_6) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_6 */ interrupt_signal_action_6.sa_sigaction = &signal_handler_6; /* * Set the Flags for the struct interrupt_signal_action_6 */ interrupt_signal_action_6.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_6 Signal According to the struct interrupt_signal_action_6. */ if (sigaction(DEFAULT_SIGNAL_6, &interrupt_signal_action_6, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action 6 for Kernel Signals\n"); #endif return -1; } /* * Set the struct interrupt_signal_action_sg with the Signal Handler (signal_handler_sg) that will be Used when the Driver Triggers the DEFAULT_SIGNAL_SG */ interrupt_signal_action_sg.sa_sigaction = &signal_handler_sg; /* * Set the Flags for the struct interrupt_signal_action_sg */ interrupt_signal_action_sg.sa_flags = SA_SIGINFO; /* * Call sigaction() Function which Specifies the Action to be Associated with the DEFAULT_SIGNAL_SG Signal According to the struct interrupt_signal_action_sg. */ if (sigaction(DEFAULT_SIGNAL_SG, &interrupt_signal_action_sg, NULL) < 0) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Could not Setup Action Scatter/Gather for Kernel Signals\n"); #endif return -1; } pid = getpid(); #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Process ID is: %d\n", pid); #endif return 1; } /* OK * clear_screen() * * Prints a Specified String to The Terminal that Forces the Terminal to Clear Its Screen */ void clear_screen() { /* * Clear Screen and Move to Top-Left Corner */ printf("\033[2J\033[1;1H"); } /* OK * load_bmp() * * Used to Load the Image from the Storage Device to a Given Memory * According to the u8_pre_process_kernel_address Pointer. * According to the Current Implementation the u8_pre_process_kernel_address Points Directly to an Allocated Memory in Kernel Space */ int load_bmp(uint8_t *u8_pre_process_kernel_address) { size_t total_read_bytes; FILE *bmp_file; int status; int repeat; size_t pad; uint8_t current_byte; int count = 0; int i,j; #ifdef DEBUG_MESSAGES_UI printf("The Path is: %s\n", load_path_name); printf("Loading the Image File\n"); #endif /* * Open the Image File According to the File Name Given by the the User */ bmp_file = fopen(load_path_name, "r"); if(bmp_file != NULL) { #ifdef DEBUG_MESSAGES_UI printf("Image File Opened\n"); #endif } else { if(bmp_file == NULL) { printf("Image Failed to Open [NULL Pointer]\n"); } usleep(2000000); return(FAILURE); } #ifdef DEBUG_MESSAGES_UI printf("Checking the Magic Number to Validate that this is a Bitmap File\n"); #endif /* * Read the Magic Number from the Header of the Bitmap File. */ fread(&magic_number, sizeof(bmpfile_magic_t), 1, bmp_file); /* * Check the Magic Number to Validate that this is a Bitmap File. * The Magic Number for .bmp Files is: 0x4D42. */ if (*((uint16_t *)magic_number.magic) == 0x4D42) { #ifdef DEBUG_MESSAGES_UI printf("Bitmap File Valid [MAGIC NUMBER 0x%X]\n", *((uint16_t *)magic_number.magic)); #endif } else { #ifdef DEBUG_MESSAGES_UI printf("No Bitmap File Was Found/Aborting\n"); #endif fclose(bmp_file); return FAILURE; } #ifdef DEBUG_MESSAGES_UI printf("Reading the Bitmap File Header\n"); #endif /* * Read the Bitmap File Header */ fread(&bitmap_file_header, sizeof(bmpfile_header_t), 1, bmp_file); #ifdef DEBUG_MESSAGES_UI printf("Reading the Bitmap Info Header\n"); #endif /* * Read the Bitmap Info Header */ fread(&bitmap_info_header, sizeof(bitmap_info_header_t), 1, bmp_file); #ifdef DEBUG_MESSAGES_UI printf("Checking Compression\n"); #endif /* * Check the Info Header Structure to See if Compression is Supported */ if (bitmap_info_header.compress_type == 0) { #ifdef DEBUG_MESSAGES_UI printf("Compression is Supported\n"); #endif } else { #ifdef DEBUG_MESSAGES_UI printf("Warning, Compression is not Supported\n"); #endif } /* * Print Information About the Image */ #ifdef DEBUG_MESSAGES_UI printf("\n* Image Width: %d Pixels\n", bitmap_info_header.width); printf("* Image Height: %d Pixels\n", bitmap_info_header.height); printf("* Image Size: %d Bytes\n", bitmap_info_header.bmp_bytesz); printf("* Image Header Size: %d Bytes\n", bitmap_info_header.header_sz); printf("* Bits Per Pixel: %d \n\n", bitmap_info_header.bitspp); #endif /* * Read the Info Header to Make Sure that the Image Resolution is up to 1920x1080 which is the Maximum Supported */ if((bitmap_info_header.width > 1920) || (bitmap_info_header.height >1080)) { printf("The Image Cannot be Processed due to Sobel Accelerator's Restricted Resolution at Maximum of 3840x2160/Aborting\n"); fclose(bmp_file); usleep(5000000); return FAILURE; } /* * Move the File Pointer at the Beginning of the Bitmap File */ fseek(bmp_file, bitmap_file_header.bmp_offset, SEEK_SET); #ifdef DEBUG_MESSAGES_UI printf("Moved File Pointer at the Beginning of Bitmap Data\n"); #endif /* * Get the Total Size Required for the Image Data. * See Details at the Global Variables Section at the Comments for the total_reserved_size Variable.s */ total_reserved_size = (bitmap_info_header.width * bitmap_info_header.height) * 4; #ifdef DEBUG_MESSAGES_UI printf("The Total Reserved Size Should Be: %d\n", total_reserved_size); #endif /* * Calculate the Possible Padding that Might be Found at the end of an Image Row. */ pad = (4 - (((bitmap_info_header.bitspp / 8)*bitmap_info_header.width) % 4)) % 4; #ifdef DEBUG_MESSAGES_UI printf("The Padding is: %d\n", pad); #endif /* * Loop for the Number of Image Rows */ for(i=0; i<bitmap_info_header.height; i++) { /* * Loop for the Number of Image Columns (The Pixels of each Row) */ for(j=0; j<(bitmap_info_header.width); j++) { /* * Read and Store the First Byte of the Current Pixel */ fread(&current_byte, sizeof(uint8_t), 1, bmp_file); u8_pre_process_kernel_address[count++] = current_byte; /* * Read and Store the Second Byte of the Current Pixel */ fread(&current_byte, sizeof(uint8_t), 1, bmp_file); u8_pre_process_kernel_address[count++] = current_byte; /* * Read and Store the Third Byte of the Current Pixel */ fread(&current_byte, sizeof(uint8_t), 1, bmp_file); u8_pre_process_kernel_address[count++] = current_byte; /* * Store a Padding Byte in Order to Have 4 Bytes Alignment per Pixel. */ u8_pre_process_kernel_address[count++] = 0x0; } /* * Move the Position Indicator of the File According to the pad Variable so that we Get to the Beginning of the Next Image Row. * The fseek() Herein is Required because there might be a Chance that in each Row there is a Number of Padding Bytes after the End of the Valid Image Data of each Row. * As a Result Using fseek() is the Way to Move to the Valid Image Data of the Next Row. */ fseek(bmp_file, pad, SEEK_CUR); } #ifdef DEBUG_MESSAGES_UI printf("The Image Data is Loaded\n"); #endif /* * Close the Bitmap File. */ fclose(bmp_file); return SUCCESS; } /* OK * save_bmp() * * Used to Save the Processed Image from a Memory Given by the u8_post_process_kernel_address Pointer * to the Storage Device at the Directory and Filename Given by the save_path_name Pointer. * According to the Current Implementation the u8_post_process_kernel_address Points Directly to an Allocated Memory in Kernel Space */ int save_bmp(uint8_t *u8_post_process_kernel_address, char *save_path_name) { size_t total_written_bytes; FILE *bmp_file; bmpfile_magic_t save_magic_number; bmpfile_header_t save_bitmap_file_header; size_t i; size_t j; size_t k; size_t pad; uint8_t current_byte; #ifdef DEBUG_MESSAGES_UI printf("Saving the Image File\n"); #endif /* * Open the Image File According to the File Name Given by the the User */ bmp_file = fopen(save_path_name, "wb"); if(bmp_file != NULL) { #ifdef DEBUG_MESSAGES_UI printf("New Image File Opened\n"); #endif } else { if(bmp_file == NULL) { printf("New Image File Failed to Open [NULL Pointer]\n"); } usleep(2000000); return(FAILURE); } #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] Writing the Magic Number at the New Image File\n"); #endif /* * Set the Magic Number Structure with the .bmp Image Magic Number. */ save_magic_number.magic[0] = 0x42; save_magic_number.magic[1] = 0x4d; /* * Write the Magic Number Inside the File */ if (fwrite(&save_magic_number, sizeof(bmpfile_magic_t), 1, bmp_file) != 1) { printf("[SAVE PROCESS] Failed to Write the Magic Number\n"); fclose(bmp_file); return FAILURE; } else { #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] The Magic Number is Written\n"); #endif } /* * Calculate the Offset where the Clear Image Data (After the File Header) Starts. */ const uint32_t offset = sizeof(bmpfile_magic_t) + sizeof(bmpfile_header_t) + bitmap_info_header.header_sz; /* * Set the File Header with the File Size, Creator 1, Creator 2 and the Offset of the Bitmap Data. */ save_bitmap_file_header.filesz = offset + bitmap_info_header.bmp_bytesz; save_bitmap_file_header.creator1 = 0; save_bitmap_file_header.creator2 = 0; save_bitmap_file_header.bmp_offset = offset; #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] Writing the File Header of the Image File\n"); #endif /* * Write the File Header inside the File. */ if (fwrite(&save_bitmap_file_header, sizeof(bmpfile_header_t), 1, bmp_file) != 1) { printf("[SAVE PROCESS] Failed to Write the File Header\n"); fclose(bmp_file); return FAILURE; } else { #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] The File Header is Written\n"); #endif } #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] Writing the Info Header of the Image File\n"); #endif /* * Write the Info Header inside the File. */ if (fwrite(&bitmap_info_header, sizeof(bitmap_info_header_t), 1, bmp_file) != 1) { printf("[SAVE PROCESS] Failed to Write the Info Header\n"); fclose(bmp_file); return FAILURE; } else { #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] The Info Header is Written\n"); #endif } #ifdef DEBUG_MESSAGES_UI printf("[SAVE PROCESS] Moving the File Pointer at the Beginning of the Bitmap Data\n"); #endif /* * Move the File Pointer at the Beginning of the Bitmap Data; */ if (fseek(bmp_file, offset, SEEK_SET)) { printf("[SAVE PROCESS] Failed to Move the File Pointer at the Beginning of the Bitmap Data\n"); fclose(bmp_file); return FAILURE; } /* * Calculate the Possible Padding that Might be Found at the end of an Image Row. */ pad = (4 - (((bitmap_info_header.bitspp / 8) * bitmap_info_header.width) % 4)) % 4; #ifdef DEBUG_MESSAGES_UI printf("Writing the Bitmap Data\n"); #endif /* * Loop for the Number of Image Rows */ for(i=0; i < bitmap_info_header.height; i++) { /* * Loop for the Number of Image Columns (The Pixels of each Row) */ for(j=0; j < bitmap_info_header.width; j++) { /* * Loop 3 Times for each Pixel (3 Bytes Per Pixel / bitspp = 24) */ for(k=0; k<(bitmap_info_header.bitspp / 8); k++) { /* * Get the Current Byte (1 of 3) of the Current Pixel which is Stored in the (j * 4) + k + (bitmap_info_header.width * i * 4) Offset * of the Kernel Memory (u8_post_process_kernel_address). */ current_byte = (uint8_t) u8_post_process_kernel_address[(j * 4) + k + (bitmap_info_header.width * i * 4)]; /* * Write the Current Byte Inside the Bitmap Data Offset of the File. */ if (fwrite(&current_byte, sizeof(uint8_t), 1, bmp_file) != 1) { printf("Failed to Write the Bitmap Data\n"); fclose(bmp_file); return true; } } } /* * If Any Padding is Necessary then Add it to the End of the Row. */ current_byte = 0; /* * Loop for the Number of Padding Bytes and */ for(j=0; j < pad; j++) if (fwrite(&current_byte, sizeof(uint8_t), 1, bmp_file) != 1) { fclose(bmp_file); return true; } } /* * Close the Save Bitmap File. */ fclose(bmp_file); #ifdef DEBUG_MESSAGES_UI printf("Image is Saved\n"); #endif return SUCCESS; } /* OK * convert_cycles_2_ns() * * Used to Convert Cycles to Nano Seconds. * The Global Clock Counter of the AXI Performance Monitors of the FPGA Use two 32 Bit Registers (Lower and Upper) to Store the * Clock Counting in Order to Support Long Cycle Counts. * The convert_cycles_2_ns() Combines Lower and Upper Register Values to Convert the Total Cycles to Nano Seconds. * * The Userspace Application or the Driver Make One 64 Bit Read from the AXI Performance Monitor Unit to Get the Values of the Upper and Lower 32 Bit Register with a Single Transaction. * The First Register Holds the Upper Part of the Cycle Counting while the Second Register Holds the Lower Part of the Cycle Counting. * As a Result when we Make a 64 Bit Read we Get the Two Registers at Once which Means that the 32 LSBs of the Read Value Hold the Upper Cycle Counting and the 32 MSBs Hold the Lower Cycle Counting. * The convert_cycles_2_ns() Function Shifts the Upper Cycle Counting from the LSBs to Become the MSBs and the Lower Cycle Counting from the MSBs to Become the LSBs. * Then the Cycles are Converted to Nano Seconds. */ uint64_t convert_cycles_2_ns(uint64_t cycles) { uint64_t gcc_u; uint64_t gcc_l; uint64_t nano_seconds; /* * Assign the gcc_u Variable with the 32 LSBs */ gcc_u = cycles & 0x00000000FFFFFFFF; /* * Assign the gcc_l Variable with the 32 MSBs */ gcc_l = cycles & 0xFFFFFFFF00000000; /* * Shift Right the gcc_l Variable so that the MSBs Become LSBs */ gcc_l = gcc_l >> 32; /* * Shift Left the gcc_l Variable so that the LSBs Become MSBs */ gcc_u = gcc_u << 32; /* * Add the gcc_l with the gcc_u to Get the Correct Total Number of Cycles. * Then Multiply the Add Value by 8 to Get the Nanoseconds where 8 is the Number of Nanoseconds for each Cycle at 125MHz. */ nano_seconds = (gcc_l + gcc_u) * 8; return nano_seconds; } /* OK * file_size() * * Used to Get the Size of a File. * It is Useful when We Need to Know if a File is Empty or Not. */ int file_size(FILE *file) { int previous_size; int new_size; /* * Use ftell() which Returns the Current Value of the Position Indicator which Should Be at the Beginning of the File. * Store the Return Value to the previous_size Variable so that it Can Later be Used to Return the Position Indicator at the Beginning of the File. */ previous_size = ftell(file); /* * Use fseek() to Move the Position Indicator at the End (SEEK_END) of the File. */ fseek(file, 0L, SEEK_END); /* * Use ftell() which Returns the Current Value of the Position Indicator which Should Be Now at the End of the File. * Store the Return Value to the new_size Variable so that it Can Later be Used to Know the Size of the File. */ new_size = ftell(file); /* * Use fseek() to Move the Position Indicator at the Beginning of the File According to the previous_size Variable. */ fseek(file, previous_size, SEEK_SET); /* * Return the new_size Variable which Indicates the Size of the File. */ return new_size; } /* OK * print_save_metrics() * * Used to Save the Metrics of each Iteration of each Test. * The Metrics from the Hardware Schedulers, the Driver and the User Application are Collected in the * Shared Kernel Memory which is Accessed by the shared_repo_kernel_address Pointer. * The shared_repo_kernel_address Pointer Provides Access to the Collected Metrics which are Stored as Structure Fields of Type struct shared_repository_process. * The Metrics are Organized and Written as Element Nodes of a .xml File. * * ---------------------------------------------- * The Structure of the .xml Nodes is as Follows: * * <Process> * <Iteration> ### </Iteration> * <Image_Segments> ### </Image_Segments> * <Preparation_Time_Start> ### </Preparation_Time_Start> * <Preparation_Time_End> ### </Preparation_Time_End> * <Load_Time_Start> ### </Load_Time_Start> * <Load_Time_End> ### </Load_Time_End> * <Total_Time_Start> ### </Total_Time_Start> * <Sleep_Time_Start> ### </Sleep_Time_Start> * <Sleep_Time_End> ### </Sleep_Time_End> * <Save_Time_Start> ### </Save_Time_Start> * <Save_Time_End> ### </Save_Time_End> * <Total_Time_End> ### </Total_Time_End> * <Segment> * <Segment_Number> ### </Segment_Number> * <Initiator> ### </Initiator> * <Read_Transactions> ### </Read_Transactions> * <Read_Bytes> ### </Read_Bytes> * <Write_Transactions> ### </Write_Transactions> * <Write_Bytes> ### </Write_Bytes> * <Stream_Packets> ### </Stream_Packets> * <Stream_Bytes> ### </Stream_Bytes> * <Process_Cycles> ### </Process_Cycles> * <Set_Pages_Overhead_Time_Start> ### </Set_Pages_Overhead_Time_Start> * <Set_Pages_Overhead_Time_End> ### </Set_Pages_Overhead_Time_End>\ * <Unmap_Pages_Overhead_Time_Start> ### </Unmap_Pages_Overhead_Time_Start> * <Unmap_Pages_Overhead_Time_End> ### </Unmap_Pages_Overhead_Time_End> * <CDMA_Fetch_Time_Start> ### </CDMA_Fetch_Time_Start> * <CDMA_Fetch_Time_End> ### </CDMA_Fetch_Time_End> * <Process_Time_Start> ### </Process_Time_Start> * <Process_Time_End> ### </Process_Time_End> * <CDMA_Send_Time_Start> ### </CDMA_Send_Time_Start> * <CDMA_Send_Time_End> ### </CDMA_Send_Time_End> * </Segment> * </Process> * * ------------------------- * Element Node Explanation: * * Process --> The Process ID of the Process that those Metrics Refer to * Iteration --> The Current Iteration of the Current Thread * Image_Segments --> The Number of Segments that the Image was Splitted for Parallel Acceleration * Preparation_Time_Start --> The Starting Point for the Preparation Needed before the Acceleration Procedure * Preparation_Time_End --> The Ending Point for the Preparation Needed before the Acceleration Procedure * Load_Time_Start --> The Starting Point of the Duration for Loading the Image from the Storage Device * Load_Time_End --> The Ending Point of the Duration for Loading the Image from the Storage Device * Total_Time_Start --> The Starting Point of the Total Time Required for the Acceleration Procedure * Sleep_Time_Start --> The Starting Point of the Duration that the Thread Possibly Stayed in Sleep State * Sleep_Time_End --> The Ending Point of the Duration that the Thread Possibly Stayed in Sleep State * Save_Time_Start --> The Starting Point of the Duration for Saving the Image to the Storage Device * Save_Time_End --> The Ending Point of the Duration for Saving the Image to the Storage Device * Total_Time_End --> The Ending Point of the Total Time Required for the Acceleration Procedure * Segment --> The Segment Element Node Carries Metrics Regarding the Current Segment that Was Accelerated.There Can be as many as 6 Segment Nodes * Segment_Number --> The Current Segment Number Among the Rest that the Image Might was Splitted * Initiator --> The Acceleration Group that Accelerated the Current Image Segment * Read_Transactions --> The Number of Read Transactions that Took Place while the DMA was Reading the Current Image Segment from the Kernel Memory * Read_Bytes --> The Number of Read Bytes that were Transferred while the DMA was Reading the Current Image Segment from the Kernel Memory * Write_Transactions --> The Number of Write Transactions that Took Place while the DMA was Writing the Current Processed Image Segment to the Kernel Memory * Write_Bytes --> The Number of Write Bytes that were Transferred while the DMA was Writing the Current Processed Image Segment to the Kernel Memory * Stream_Packets --> The Number of Stream Packets that where Transferred through the Sobel Accelerator's Stream Interface * Stream_Bytes --> The Number of Stream Bytes that where Transferred through the Sobel Accelerator's Stream Interface * Process_Cycles --> The Number of Clock Cycles that were Required to Complete the Acceleration (DMA Read -> Sobel Acceleration -> DMA Write) * Set_Pages_Overhead_Time_Start --> The Starting Point of the Duration that the Driver Required to Create the Scatter/Gather List if the Acceleration Group SG was Requested * Set_Pages_Overhead_Time_End --> The Ending Point of the Duration that the Driver Required to Create the Scatter/Gather List if the Acceleration Group SG was Requested * Unmap_Pages_Overhead_Time_Start --> The Starting Point of the Duration that the Driver Required to Unmap the Pages that were Previously Mapped when Creating the Scatter/Gather List * Unmap_Pages_Overhead_Time_End --> The Ending Point of the Duration that the Driver Required to Unmap the Pages that were Previously Mapped when Creating the Scatter/Gather List * CDMA_Fetch_Time_Start --> The Starting Point of the Duration that the CDMA Fetch Peripheral Required to Fetch Image Data to the FPGA DDR3 Memory (Applicable for the Initiators: AGI0, AGI1, AGI2, AGI3) * CDMA_Fetch_Time_End --> The Ending Point of the Duration that the CDMA Fetch Peripheral Required to Fetch Image Data to the FPGA DDR3 Memory (Applicable for the Initiators: AGI0, AGI1, AGI2, AGI3) * Process_Time_Start --> The Starting Point of the Duration that the Image Segment Acceleration Required to Complete * Process_Time_End --> The Ending Point of the Duration that the Image Segment Acceleration Required to Complete * CDMA_Send_Time_Start --> The Starting Point of the Duration that the CDMA Send Peripheral Required to Send Processed Image Data from the FPGA DDR3 Memory (Applicable for the Initiators: AGI0, AGI1, AGI2, AGI3) * CDMA_Send_Time_End --> The Ending Point of the Duration that the CDMA Send Peripheral Required to Send Processed Image Data from the FPGA DDR3 Memory (Applicable for the Initiators: AGI0, AGI1, AGI2, AGI3) * */ int print_save_metrics(struct shared_repository_process *shared_repo_kernel_address, int used_accelerator, unsigned int tid, int global_repeat) { char file_name[100]; FILE *metrics_summary_file; uint64_t gcc_u; uint64_t gcc_l; uint64_t time_counted; struct stat file_statistics; int segments = 0; int segment_count = 0; int repeat; /* * Depending on the Acceleration Policy an Image Can be Processed by Several Acceleration Groups, that is, an Image * Can be Splitted in Several Segments. * The Following if Statements Check which Acceleration Groups Took Part in Accelerating the Current Image which is Equal to * the Number of Segments that the Image was Splitted. */ if((used_accelerator & ACCELERATOR_DIRECT_0_OCCUPIED) == ACCELERATOR_DIRECT_0_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_DIRECT_1_OCCUPIED) == ACCELERATOR_DIRECT_1_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_INDIRECT_0_OCCUPIED) == ACCELERATOR_INDIRECT_0_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_INDIRECT_1_OCCUPIED) == ACCELERATOR_INDIRECT_1_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_INDIRECT_2_OCCUPIED) == ACCELERATOR_INDIRECT_2_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_INDIRECT_3_OCCUPIED) == ACCELERATOR_INDIRECT_3_OCCUPIED) { segments++; } if((used_accelerator & ACCELERATOR_SG_OCCUPIED) == ACCELERATOR_SG_OCCUPIED) { segments++; } /* * Use sprintf() to Create a String that Represents the Path and Name of the Metrics .xml File. * The Arithmetic Value of the renamer_value Variable is Included in the File Name to Ensure that each Test Iteration * Creates a New .xml File which is Unique Among the Rest .xml Files. */ sprintf(file_name,"Results/Metrics_Summary_%d.xml", renamer_value); /* * Open Again the .xml File to Write the Collected Metrics. */ metrics_summary_file = fopen(file_name, "a"); /* * The .xml File is Possibly Accessed by Many Threads. * flock() is Used to Ensure that Only One Thread Write at this .xml File at the Moment. */ flock(fileno(metrics_summary_file), LOCK_EX); /* * If the Metrics .xml File was Found or Created then Start Writing the Metrics Data. */ if (metrics_summary_file != NULL) { #ifdef DEBUG_MESSAGES_UI printf("File %s Opened\n", file_name); #endif /* * Write the Open Tag of the Process Element. * The Process Element, also, Includes the "ID" Attribute which is the Process ID of the Current Thread. */ fprintf(metrics_summary_file," <Process ID=\"%d\">\n", tid); /* * The Following Element Nodes Refer to Metrics of the Acceleration Procedure for the whole Image */ /* * Write the Iteration Element Node. * The global_repeat is the Function Argument Given as the Current Iteration of the Acceleration that the Thread Requested */ fprintf(metrics_summary_file," <Iteration>%d</Iteration>\n", global_repeat); /* * Write the Image_Segments Element Node. * The segments was Calculated Previously by Incrementing the Number of Acceleration Groups that Took Part in Accelerating the Current Image */ fprintf(metrics_summary_file," <Image_Segments>%d</Image_Segments>\n", segments); /* * Write the Preparation_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the preparation_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Preparation_Time_Start>%lld</Preparation_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.preparation_time_start)); /* * Write the Preparation_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the preparation_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Preparation_Time_End>%lld</Preparation_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.preparation_time_end)); /* * Write the Load_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the load_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Load_Time_Start>%lld</Load_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.load_time_start)); /* * Write the Load_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the load_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Load_Time_End>%lld</Load_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.load_time_end)); /* * Write the Total_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the total_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Total_Time_Start>%lld</Total_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.total_time_start)); /* * Write the Sleep_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the sleep_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Sleep_Time_Start>%lld</Sleep_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.sleep_time_start)); /* * Write the Sleep_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the sleep_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Sleep_Time_End>%lld</Sleep_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.sleep_time_end)); /* * Write the Save_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the save_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Save_Time_Start>%lld</Save_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.save_time_start)); /* * Write the Save_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the save_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Save_Time_End>%lld</Save_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.save_time_end)); /* * Write the Total_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the total_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Total_Time_End>%lld</Total_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.total_time_end)); /* * The Following Element Nodes Refer to Metrics of the Acceleration Procedure for each Image Segment that was Accelerated. * There are 7 if Statements for each of the 7 Acceleration Groups. * For each Acceleration Group that Took Part in the Acceleration Procedure a new Segment Element Node is Added to the Process Parent Node. * * Comments will be Provided Only for Creating the Segment of the Acceleration Group Direct 0. * The Procedure is Exactly the Same for the Rest of the Acceleration Groups. */ /* * Acceleration Group Direct 0 Segment */ if((used_accelerator & ACCELERATOR_DIRECT_0_OCCUPIED) == ACCELERATOR_DIRECT_0_OCCUPIED) { /* * Write the Open Tag of the Segment Element. */ fprintf(metrics_summary_file," <Segment>\n"); /* * Write the Segment_Number Element Node. * The Segment_Number Value is Given by the segment_count Variable which Holds a Value that Increments for each New Segment that is Added to the Process Parent Node */ fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); /* * Write the Initiator Element Node which is Acceleration Group Direct 0. */ fprintf(metrics_summary_file," <Initiator>Acceleration Group Direct 0</Initiator>\n"); /* * Write the Read_Transactions Element Node Along with its Value. * The Node Value was Found in the apm_read_transactions Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agd0.apm_read_transactions); /* * Write the Read_Bytes Element Node Along with its Value. * The Node Value was Found in the apm_read_bytes Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agd0.apm_read_bytes); /* * Write the Write_Transactions Element Node Along with its Value. * The Node Value was Found in the apm_write_transactions Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agd0.apm_write_transactions); /* * Write the Write_Bytes Element Node Along with its Value. * The Node Value was Found in the apm_write_bytes Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agd0.apm_write_bytes); /* * Write the Stream_Packets Element Node Along with its Value. * The Node Value was Found in the apm_packets Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agd0.apm_packets); /* * Write the Stream_Bytes Element Node Along with its Value. * The Node Value was Found in the apm_bytes Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agd0.apm_bytes); /* * Write the Process_Cycles Element Node Along with its Value. * The Node Value was Found in the apm_gcc_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agd0.apm_gcc_l); /* * Write the Set_Pages_Overhead_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the set_pages_overhead_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); /* * Write the Set_Pages_Overhead_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the set_pages_overhead_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); /* * Write the Unmap_Pages_Overhead_Time_Start Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the unmap_pages_overhead_time_start Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); /* * Write the Unmap_Pages_Overhead_Time_End Element Node Along with its Value (nanoseconds). * The Node Value was Calculated by Converting the Cycles Value Found in the unmap_pages_overhead_time_end Field of the shared_repo_kernel_address->process_metrics Structure of the Shared Kernel Memory */ fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); /* * Get the cdma_fetch_time_start_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_fetch_time_start_l Field is Partially the CDMA Fetch Time Start Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_fetch_time_start_l; /* * Get the cdma_fetch_time_start_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_fetch_time_start_u Field is Partially the CDMA Fetch Time Start Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_fetch_time_start_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct CDMA Fetch Time Start Value from Cycles to Nanoseconds and Write it to the CDMA_Fetch_Time_Start Element Node. */ fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); /* * Get the cdma_fetch_time_end_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_fetch_time_end_l Field is Partially the CDMA Fetch Time End Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_fetch_time_end_l; /* * Get the cdma_fetch_time_end_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_fetch_time_end_u Field is Partially the CDMA Fetch Time End Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_fetch_time_end_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct CDMA Fetch Time End Value from Cycles to Nanoseconds and Write it to the CDMA_Fetch_Time_End Element Node. */ fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); /* * Get the dma_accel_time_start_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The dma_accel_time_start_l Field is Partially the Acceleration Time Start Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.dma_accel_time_start_l; /* * Get the dma_accel_time_start_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The dma_accel_time_start_u Field is Partially the Acceleration Time Start Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.dma_accel_time_start_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct Acceleration Time Start Value from Cycles to Nanoseconds and Write it to the Process_Time_Start Element Node. */ fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); /* * Get the dma_accel_time_end_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The dma_accel_time_end_l Field is Partially the Acceleration Time End Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.dma_accel_time_end_l; /* * Get the dma_accel_time_end_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The dma_accel_time_end_u Field is Partially the Acceleration Time End Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.dma_accel_time_end_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct Acceleration Time End Value from Cycles to Nanoseconds and Write it to the Process_Time_End Element Node. */ fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); /* * Get the cdma_send_time_start_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_send_time_start_l Field is Partially the CDMA Send Time Start Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_send_time_start_l; /* * Get the cdma_send_time_start_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_send_time_start_u Field is Partially the CDMA Send Time Start Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_send_time_start_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct CDMA Send Time Start Value from Cycles to Nanoseconds and Write it to the CDMA_Send_Time_Start Element Node. */ fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); /* * Get the cdma_send_time_end_l Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_send_time_end_l Field is Partially the CDMA Send Time End Value which was Found at the APM Lower Global Clock Counter Register. */ gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_send_time_end_l; /* * Get the cdma_send_time_end_u Field of the shared_repo_kernel_address->process_metrics.agd0 Structure of the Shared Kernel Memory. * The cdma_send_time_end_u Field is Partially the CDMA Send Time End Value which was Found at the APM Upper Global Clock Counter Register. */ gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd0.cdma_send_time_end_u; /* * Shift Left by 32 the gcc_u Value. */ gcc_u = gcc_u << 32; /* * Calculate the Correct CDMA Send Time End Value from Cycles to Nanoseconds and Write it to the CDMA_Send_Time_End Element Node. */ fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); /* * Write the Close Tag of the Segment Element Node. */ fprintf(metrics_summary_file," </Segment>\n\n\n"); /* * Increment the segment_count Variable for the Next Segment that Might be Present. */ segment_count++; } /* * Acceleration Group Direct 1 Segment */ if((used_accelerator & ACCELERATOR_DIRECT_1_OCCUPIED) == ACCELERATOR_DIRECT_1_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group Direct 1</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agd1.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agd1.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agd1.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agd1.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agd1.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agd1.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agd1.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agd1.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Acceleration Group Indirect 0 Segment */ if((used_accelerator & ACCELERATOR_INDIRECT_0_OCCUPIED) == ACCELERATOR_INDIRECT_0_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group Indirect 0</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agi0.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agi0.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agi0.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agi0.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agi0.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agi0.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agi0.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi0.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Acceleration Group Indirect 1 Segment */ if((used_accelerator & ACCELERATOR_INDIRECT_1_OCCUPIED) == ACCELERATOR_INDIRECT_1_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group Indirect 1</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agi1.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agi1.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agi1.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agi1.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agi1.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agi1.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agi1.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi1.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Acceleration Group Indirect 2 Segment */ if((used_accelerator & ACCELERATOR_INDIRECT_2_OCCUPIED) == ACCELERATOR_INDIRECT_2_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group Indirect 2</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agi2.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agi2.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agi2.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agi2.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agi2.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agi2.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agi2.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi2.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Acceleration Group Indirect 3 Segment */ if((used_accelerator & ACCELERATOR_INDIRECT_3_OCCUPIED) == ACCELERATOR_INDIRECT_3_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group Indirect 3</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agi3.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agi3.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agi3.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agi3.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agi3.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agi3.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agi3.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agi3.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Acceleration Group Scatter/Gather Segment */ if((used_accelerator & ACCELERATOR_SG_OCCUPIED) == ACCELERATOR_SG_OCCUPIED) { fprintf(metrics_summary_file," <Segment>\n"); fprintf(metrics_summary_file," <Segment_Number>%d</Segment_Number>\n", segment_count); fprintf(metrics_summary_file," <Initiator>Acceleration Group SG</Initiator>\n"); fprintf(metrics_summary_file," <Read_Transactions>%d</Read_Transactions>\n", shared_repo_kernel_address->process_metrics.agsg.apm_read_transactions); fprintf(metrics_summary_file," <Read_Bytes>%d</Read_Bytes>\n", shared_repo_kernel_address->process_metrics.agsg.apm_read_bytes); fprintf(metrics_summary_file," <Write_Transactions>%d</Write_Transactions>\n", shared_repo_kernel_address->process_metrics.agsg.apm_write_transactions); fprintf(metrics_summary_file," <Write_Bytes>%d</Write_Bytes>\n", shared_repo_kernel_address->process_metrics.agsg.apm_write_bytes); fprintf(metrics_summary_file," <Stream_Packets>%d</Stream_Packets>\n", shared_repo_kernel_address->process_metrics.agsg.apm_packets); fprintf(metrics_summary_file," <Stream_Bytes>%d</Stream_Bytes>\n", shared_repo_kernel_address->process_metrics.agsg.apm_bytes); fprintf(metrics_summary_file," <Process_Cycles>%d</Process_Cycles>\n", shared_repo_kernel_address->process_metrics.agsg.apm_gcc_l); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_Start>%lld</Set_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start)); fprintf(metrics_summary_file," <Set_Pages_Overhead_Time_End>%lld</Set_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_Start>%lld</Unmap_Pages_Overhead_Time_Start>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start)); fprintf(metrics_summary_file," <Unmap_Pages_Overhead_Time_End>%lld</Unmap_Pages_Overhead_Time_End>\n", convert_cycles_2_ns(shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end)); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_fetch_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_fetch_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_Start>%lld</CDMA_Fetch_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_fetch_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_fetch_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Fetch_Time_End>%lld</CDMA_Fetch_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.dma_accel_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.dma_accel_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_Start>%lld</Process_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.dma_accel_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.dma_accel_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <Process_Time_End>%lld</Process_Time_End>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_send_time_start_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_send_time_start_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_Start>%lld</CDMA_Send_Time_Start>\n", (gcc_l + gcc_u) * 8); gcc_l = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_send_time_end_l; gcc_u = (uint64_t)shared_repo_kernel_address->process_metrics.agsg.cdma_send_time_end_u; gcc_u = gcc_u << 32; fprintf(metrics_summary_file," <CDMA_Send_Time_End>%lld</CDMA_Send_Time_End>\n", (gcc_l + gcc_u) * 8); fprintf(metrics_summary_file," </Segment>\n\n\n"); segment_count++; } /* * Write to the Metrics .xml the Close Tag of the Process Element. */ fprintf(metrics_summary_file," </Process>\n\n\n"); /* * Close the Metrics .xml File. */ fclose(metrics_summary_file); /* * Unlock the Metrics .xml File so that the Rest of the Threads Can Use It. */ flock(fileno(metrics_summary_file), LOCK_UN); metrics_summary_file = NULL; } else { printf("Could not Open the File %s\n", file_name); } } /* OK * set_save_accelerator() * * Used to Create a String that Represents the Path and Name of the .bmp File where the Accelerated Image is Going to be Stored. * The Name of the new .bmp File Carries the Following Information Regarding the Processed Image: * -> pid Followed by the Process ID Number. * -> iter Followed by the Current Iteration Number. * -> d0 Followed by Value Zero or One Depending on whether the Accelereration Group Direct 0 Was Used or Not for Accelerating the Current Image * -> d1 Followed by Value Zero or One Depending on whether the Accelereration Group Direct 1 Was Used or Not for Accelerating the Current Image * -> i0 Followed by Value Zero or One Depending on whether the Accelereration Group Indirect 0 Was Used or Not for Accelerating the Current Image * -> i1 Followed by Value Zero or One Depending on whether the Accelereration Group Indirect 1 Was Used or Not for Accelerating the Current Image * -> i2 Followed by Value Zero or One Depending on whether the Accelereration Group Indirect 2 Was Used or Not for Accelerating the Current Image * -> i3 Followed by Value Zero or One Depending on whether the Accelereration Group Indirect 3 Was Used or Not for Accelerating the Current Image * -> sg Followed by Value Zero or One Depending on whether the Accelereration Group Scatter/Gather Was Used or Not for Accelerating the Current Image */ int set_save_accelerator(char *save_path_name, int used_accelerator, int tid, int iteration) { int accel_occupied[7]; int repeat; /* * Shift Right the used_accelerator Variable to Get the 7 LSB Bits * that Represent the Status (Used or Not) of each Acceleration Group Respectively */ for(repeat = 0; repeat < 7; repeat++) { accel_occupied[repeat] = (used_accelerator >> repeat) & 1; } /* * Create a New String that Carries the Path, Name and Image Info that will be Used to Later Save the Current Processed Image */ sprintf(save_path_name, "Results/pid_%d_iter_%d_d0%d_d1%d_i0%d_i1%d_i2%d_i3%d_sg%d.bmp", tid, iteration, accel_occupied[0], accel_occupied[1], accel_occupied[2], accel_occupied[3], accel_occupied[4], accel_occupied[5], accel_occupied[6]); return SUCCESS; } /* OK * pcie_bar_mmap() * * Used to Map the PCIe BAR0 and PCIe BAR1 of the PCIe Bridge as Part of the Virtual Address Space of the Userspace Application. * PCIe BARs Represent Memories or Address Mappings of a PCIe Endpoint Device. * The Host System Can Get Direct Access to the the Peripherals and Memories of the Endpoint Device through the PCIe BARs. * * Herein: * PCIe BAR0 Represents the AXI Address Space where all the FPGA Peripherals are Mapped. * PCIe BAR1 Represents the BRAM Memory of the FPGA which is Used to Store Metrics Information, SG Lists and Synchronization Flags. * * At Boot Time the Host System, among others, Enumerates the PCIe BAR0 and PCIe BAR 1 of the PCIe Endpoint Device and Creates * the resource0 and resource2 Files at the "/sys/bus/pci/devices/0000:01:00.0/" Path. * Those two Files are Used to Map the PCIe BARs Respectively. */ int pcie_bar_mmap() { printf("Memory Mapping PCIe BAR Address Space\n"); /* * Open the resource0 File that Represents the PCIe BAR0 of the PCIe Bridge. */ pcie_bar_0_mmap_file = open("/sys/bus/pci/devices/0000:01:00.0/resource0", O_RDWR); /* * If the pcie_bar_0_mmap_file Value is Less than Zero then the System Failed to Open the File or the File Does not Exist */ if ( pcie_bar_0_mmap_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening PCIe BAR 0 MMAP File\n"); #endif return FAILURE; } /* * Use the mmap() Function to Map the PCIe BAR0 to the Virtual Address Space of the Userspace. * The mmap() Function Returns a 32 Bit Pointer(uint_32_pcie_bar_kernel_address) which Can be Used to Get Direct Access to the AXI Address Space (Peripherals) of the FPGA. */ uint_32_pcie_bar_kernel_address = (unsigned int *)mmap(0, MMAP_ALLOCATION_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, pcie_bar_0_mmap_file, 0); /* * Cast the uint_32_pcie_bar_kernel_address Pointer to the 64 Bit uint_64_pcie_bar_kernel_address Pointer. * The uint_64_pcie_bar_kernel_address Can be Used to Make 64 Bit Read/Write Transactions. */ uint_64_pcie_bar_kernel_address = (uint64_t *)uint_32_pcie_bar_kernel_address; /* * If the Value of the uint_32_pcie_bar_kernel_address Pointer is Equal with the MAP_FAILED Value it Means that We Failed to Map the PCIe BAR0 */ if (uint_32_pcie_bar_kernel_address == MAP_FAILED) { printf("Kernel Memory MMAP [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(2000000); #endif return FAILURE; } else { printf("PCIe BAR 0 Kernel Memory MMAP [SUCCESS]\n"); printf("PCIe BAR 0 Kernel Virtual Address is 0x%016lX\n", (unsigned long)uint_64_pcie_bar_kernel_address); } /* * Open the resource2 File that Represents the PCIe BAR1 of the PCIe Bridge. */ pcie_bar_1_mmap_file = open("/sys/bus/pci/devices/0000:01:00.0/resource2", O_RDWR); /* * If the pcie_bar_1_mmap_file Value is Less than Zero then the System Failed to Open the File or the File Does not Exist */ if ( pcie_bar_1_mmap_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening PCIe BAR 1 MMAP File\n"); #endif return FAILURE; } /* * Use the mmap() Function to Map the PCIe BAR1 to the Virtual Address Space of the Userspace. * The mmap() Function Returns a n Unsigned Int Pointer(uint_shared_kernel_address) which Can be Used to Get Direct Access to the FPGA BRAM. */ uint_shared_kernel_address = (unsigned int *)mmap(0, 128 * KBYTE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, pcie_bar_1_mmap_file, 0); /* * Cast the uint_shared_kernel_address Pointer to the struct shared_repository shared_kernel_address Pointer. * The shared_kernel_address Pointer Can be Used to Make Read/Write Transactions in a Manner of Accessing the Fields of the struct shared_repository. */ shared_kernel_address = (struct shared_repository *)uint_shared_kernel_address; /* * If the Value of the uint_shared_kernel_address Pointer is Equal with the MAP_FAILED Value it Means that We Failed to Map the PCIe BAR1 */ if (uint_shared_kernel_address == MAP_FAILED) { printf("Kernel Memory MMAP [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(2000000); #endif return FAILURE; } else { printf("PCIe BAR 1 Kernel Memory MMAP [SUCCESS]\n"); printf("PCIe BAR 1 Kernel Virtual Address is 0x%016lX\n", (unsigned long)shared_kernel_address); } return SUCCESS; } /* OK * shared_repo_mmap() * * This Function is Used to Map a Memory Allocation of the Kernel Space so that it Can Be Directly Accessed by the User Application. * This Memory Allocation is Shared Between the Kernel Driver and the User Application and is Used to Store Metrics Gathered During the Whole Acceleration Procedure. */ struct shared_repository_process * shared_repo_mmap(struct per_thread_info *per_thread_info) { unsigned int *uint_shared_repo_kernel_address; struct shared_repository_process *shared_repo_kernel_address; //clear_screen(); printf("Memory Mapping Shared Repo Kernel Allocation Buffer\n"); /* * Open the shared_repo_mmap_value File. * This File is Used to Make File Operations(Open, Read, Write, Mmap, Release, etc) Targetting Specific Code Execution Parts of the Kernel Driver. * The shared_repo_mmap_value File Located inside the "/sys/kernel/debug/" Path is a Debugfs File which is Created by the Kernel Driver. * The shared_repo_mmap_value File is Set with the Open, Mmap and Release File Operations that on Being Called Execute Specific Code Routines inside the Kernel Driver. * The Debugfs File is Integrated to Provide Additional Operations between the User Application and the Kernel Driver. */ per_thread_info->shared_repo_mmap_file = open("/sys/kernel/debug/shared_repo_mmap_value", O_RDWR); /* * If the per_thread_info->shared_repo_mmap_file Value is Less than Zero then the System Failed to Open the File or the File Does not Exist */ if ( per_thread_info->shared_repo_mmap_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening Shared Repo MMAP File\n"); #endif } /* * When Calling the mmap() Function the Driver Makes a MMap File Operation which Allocates Memory in Kernel Space and Maps it to the Userspace Application. * The mmap() Function Returns an unsigned int Pointer(uint_shared_repo_kernel_address) which Can be Used so that the * Userspace Application Can Read/Write Directly to the Kernel Memory Allocation. */ uint_shared_repo_kernel_address = (unsigned int *)mmap(0, MMAP_ALLOCATION_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, per_thread_info->shared_repo_mmap_file, 0); /* * Cast the uint_shared_repo_kernel_address Pointer to the struct shared_repository_process shared_repo_kernel_address Pointer. * The shared_repo_kernel_address Pointer Can be Used to Read/Write the Kernel Memory Allocation in a Manner of Accessing the Fields of the struct shared_repository_process. * This Memory Allocation is Used to Store Metrics. * Being Shareable it Means that Both the Userspace Application and the Kernel Driver Can Store Metrics in this Kernel Space Memory Allocation. */ shared_repo_kernel_address = (struct shared_repository_process *)uint_shared_repo_kernel_address; /* * If the Value of the uint_shared_repo_kernel_address Pointer is Equal with the MAP_FAILED Value it Means that We Failed to Map the Kernel Space Memory Allocation */ if (uint_shared_repo_kernel_address == MAP_FAILED) { printf("Kernel Memory MMAP [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(2000000); #endif } else { printf("Kernel Memory MMAP [SUCCESS]\n"); printf("Kernel Virtual Address is 0x%016lX\n", (unsigned long)shared_repo_kernel_address); } return shared_repo_kernel_address; } /* OK * pre_process_mmap() * * This Function is Used to Map a Memory Allocation of the Kernel Space so that it Can Be Directly Accessed by the User Application. * This Memory Allocation is Shared Between the Kernel Driver and the User Application and is Used to Load the Image Data Directly from the Storage Device to the Kernel Space Memory. * Without Using the MMap Technique Application the Userspace would Have to Load the Image Data in a Userspace Memory Allocation and then Copy the Image Data to a Kernel Memory Allocation. * By Using the MMap Technique we Avoid Additional Memory Allocations and Data Copies. */ uint8_t * pre_process_mmap(struct per_thread_info *per_thread_info) { unsigned int *pre_process_kernel_address; uint8_t *u8_pre_process_kernel_address; //clear_screen(); printf("Memory Mapping Pre-Process Kernel Allocation Buffer\n"); /* * Open the pre_process_mmap_value File. * This File is Used to Make File Operations(Open, Read, Write, Mmap, Release, etc) Targetting Specific Code Execution Parts of the Kernel Driver. * The pre_process_mmap_value File Located inside the "/sys/kernel/debug/" Path is a Debugfs File which is Created by the Kernel Driver. * The pre_process_mmap_value File is Set with the Open, Mmap and Release File Operations that on Being Called Execute Specific Code Routines inside the Kernel Driver. * The Debugfs File is Integrated to Provide Additional Operations between the User Application and the Kernel Driver. */ per_thread_info->pre_process_mmap_file = open("/sys/kernel/debug/pre_process_mmap_value", O_RDWR); /* * If the per_thread_info->pre_process_mmap_file Value is Less than Zero then the System Failed to Open the File or the File Does not Exist */ if ( per_thread_info->pre_process_mmap_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening Pre-Process MMAP File\n"); #endif } /* * When Calling the mmap() Function the Driver Makes a MMap File Operation which Allocates Memory in Kernel Space and Maps it to the Userspace Application. * The mmap() Function Returns an unsigned int Pointer(pre_process_kernel_address) which Can be Used so that the * Userspace Application Can Read/Write Directly to the Kernel Memory Allocation. */ pre_process_kernel_address = (unsigned int *)mmap(0, MMAP_ALLOCATION_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, per_thread_info->pre_process_mmap_file, 0); /* * Cast the pre_process_kernel_address Pointer to the 8 Bit u8_pre_process_kernel_address Pointer. * The u8_pre_process_kernel_address Pointer Can be Used to Make Byte Reads/Writes from/to the Kernel Memory Allocation. * This Memory Allocation is Used to Store the Image Data that we Load from the Storage Device. */ u8_pre_process_kernel_address = (uint8_t *)pre_process_kernel_address; /* * If the Value of the pre_process_kernel_address Pointer is Equal with the MAP_FAILED Value it Means that We Failed to Map the Kernel Space Memory Allocation */ if (pre_process_kernel_address == MAP_FAILED) { printf("Kernel Memory MMAP [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(2000000); #endif } else { printf("Kernel Memory MMAP [SUCCESS]\n"); printf("Kernel Virtual Address is 0x%016lX\n", (unsigned long)pre_process_kernel_address); } return u8_pre_process_kernel_address; } /* OK * post_process_mmap() * * This Function is Used to Map a Memory Allocation of the Kernel Space so that it Can Be Directly Accessed by the User Application. * This Memory Allocation is Shared Between the Kernel Driver and the User Application and is Used to Save the Processed Image Data Directly from the Kernel Space Memory to the Storage Device. * Without Using the MMap Technique the Userspace Application would Have to Copy the Image Data From the Kernel Space Memory Allocation to the Userspace Memory Allocation * and then Save the Image Data to the Storage Device. * By Using the MMap Technique we Avoid Additional Memory Allocations and Data Copies. */ uint8_t * post_process_mmap(struct per_thread_info *per_thread_info) { unsigned int *post_process_kernel_address; uint8_t *u8_post_process_kernel_address; //clear_screen(); printf("Memory Mapping Post-Process Kernel Allocation Buffer\n"); /* * Open the post_process_mmap_value File. * This File is Used to Make File Operations(Open, Read, Write, Mmap, Release, etc) Targetting Specific Code Execution Parts of the Kernel Driver. * The post_process_mmap_value File Located inside the "/sys/kernel/debug/" Path is a Debugfs File which is Created by the Kernel Driver. * The post_process_mmap_value File is Set with the Open, Mmap and Release File Operations that on Being Called Execute Specific Code Routines inside the Kernel Driver. * The Debugfs File is Integrated to Provide Additional Operations between the User Application and the Kernel Driver. */ per_thread_info->post_process_mmap_file = open("/sys/kernel/debug/post_process_mmap_value", O_RDWR); /* * If the per_thread_info->post_process_mmap_file Value is Less than Zero then the System Failed to Open the File or the File Does not Exist */ if ( per_thread_info->post_process_mmap_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening Post-Process MMAP File\n"); #endif } /* * When Calling the mmap() Function the Driver Makes a MMap File Operation which Allocates Memory in Kernel Space and Maps it to the Userspace Application. * The mmap() Function Returns an unsigned int Pointer(post_process_kernel_address) which Can be Used so that the * Userspace Application Can Read/Write Directly to the Kernel Memory Allocation. */ post_process_kernel_address = (unsigned int *)mmap(0, MMAP_ALLOCATION_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, per_thread_info->post_process_mmap_file, 0); /* * Cast the post_process_kernel_address Pointer to the 8 Bit u8_post_process_kernel_address Pointer. * The u8_post_process_kernel_address Pointer Can be Used to Make Byte Reads/Writes from/to the Kernel Memory Allocation. * This Memory Allocation is Used to Store the Processed Image Data that are Later Saved to the Storage Device. */ u8_post_process_kernel_address = (uint8_t *)post_process_kernel_address; /* * If the Value of the post_process_kernel_address Pointer is Equal with the MAP_FAILED Value it Means that We Failed to Map the Kernel Space Memory Allocation */ if (post_process_kernel_address == MAP_FAILED) { printf("Kernel Memory MMAP [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(2000000); #endif } else { printf("Kernel Memory MMAP [SUCCESS]\n"); printf("Kernel Virtual Address is 0x%016lX\n", (unsigned long)post_process_kernel_address); } return u8_post_process_kernel_address; } /* OK * start_thread() * * This is the Function that each new Thread is Actually Going to Execute. */ void* start_thread(void *arg) { /* * Make a System Call to Get the Process ID of the Current Thread (Thread ID). */ pid_t x = syscall(__NR_gettid); /* * When a Thread Calls pthread_barrier_wait(), it Blocks Until the Number of Threads Specified Initially in the pthread_barrier_init() Function * Have Called pthread_barrier_wait() (and Blocked Also). * When the Correct Number of Threads Have Called pthread_barrier_wait(), all those Threads Will Unblock at the Same Time. */ pthread_barrier_wait(&threads_barrier); printf("[Thread ID: %d]\n", x); /* * At this Point each Thread Has Unblocked from pthread_barrier_wait(). * At this Point each Thread calls Its Own acceleration_thread() Function * which Actually Starts and Manages the Acceleration Procedure. */ acceleration_thread(); return NULL; } /* OK * multi_threaded_acceleration() * * Called to Generate a Number of Threads According to the threads_number Function Argument. */ int multi_threaded_acceleration(int threads_number) { int status; int repeat; /* * Create a pthread_t Type Array According to the threads_number. */ pthread_t thread_id[threads_number]; /* * Initialize the Threads Barrier. * A Barrier is a Point where the Thread is Going to Wait for other Threads and Will Proceed Further only when * the Predefined Number of Threads (threads_number) Reach the Same Barrier. */ pthread_barrier_init(&threads_barrier, NULL, threads_number + 1); clear_screen(); printf("Performing the Multi-Threading Test\n"); /* * Loop for as many Times as Defined by the threads_number in order to Create the Required Number of Threads. */ for(repeat = 0; repeat < threads_number; repeat++) { /* * Create a New Thread of the start_thread() Function */ status = pthread_create(&thread_id[repeat], NULL, &start_thread, NULL); if (status != 0) { printf("\nCannot Create a Thread :[%s]", strerror(status)); } else { printf("\nThread Created Successfully\n"); } } /* * When a Thread Calls pthread_barrier_wait(), it Blocks Until the Number of Threads Specified Initially in the pthread_barrier_init() Function * Have Called pthread_barrier_wait() (and Blocked Also). * When the Correct Number of Threads Have Called pthread_barrier_wait(), all those Threads Will Unblock at the Same Time. */ pthread_barrier_wait(&threads_barrier); /* * The pthread_join() function Waits for the Thread to Terminate. * We Loop for as many Times as Defined by the threads_number to Make Sure that All Threads are Terminated. */ for (repeat = 0;repeat < threads_number; repeat++) { /* * The pthread_join() function Waits for the Thread to Terminate. */ pthread_join(thread_id[repeat], NULL); } /* * Call the pthread_barrier_destroy() Function which Destroys the Barrier and Releases any Resources Used by the Barrier. */ pthread_barrier_destroy(&threads_barrier); return SUCCESS; } /* OK * acceleration_thread() * * Called to Start a New Acceleration Request and Manage the Acceleration Procedure. * There are as many acceleration_thread() Functions as the Number of Threads that the Application Initiated. */ int acceleration_thread() { /* * The pre_process_kernel_address Points to the Kernel Memory Created by the pre_process_mmap() Function. * This Kernel Memory is Used to Load the Initial Image Data */ unsigned int *pre_process_kernel_address = NULL; /* * The u8_pre_process_kernel_address, also, Points to the Kernel Memory Created by the pre_process_mmap() Function * It is Used for 8 Bit Reads/Writes. */ uint8_t *u8_pre_process_kernel_address = NULL; /* * The post_process_kernel_address Points to the Kernel Memory Created by the post_process_mmap() Function. * This Kernel Memory is Used to Keep and Later Save the Processed Image Data */ unsigned int *post_process_kernel_address = NULL; /* * The u8_post_process_kernel_address, also, Points to the Kernel Memory Created by the post_process_mmap() Function * It is Used for 8 Bit Reads/Writes. */ uint8_t *u8_post_process_kernel_address = NULL; /* * The uint_shared_repo_kernel_address Points to the Kernel Memory Created by the shared_repo_mmap() Function. * This Kernel Memory is Used to Collect the Metrics Information. */ unsigned int *uint_shared_repo_kernel_address = NULL; /* * The shared_repo_kernel_address, also, Points to the Kernel Memory Created by the shared_repo_mmap() Function * It is Used to Access the Metrics Data as Fields of a struct shared_repository_process Structure Type. */ struct shared_repository_process *shared_repo_kernel_address = NULL; /* * The Name of the PCIe Device Driver. */ char device_driver_name[] = "/dev/xilinx_pci_driver"; int device_file = -1; /* * This Variable Increments for Each New Completed Acceleration. */ int completed = 0; /* * The save_path_name Char Array is Used to Store the String with the Path and Name of the Save Image File. */ char save_path_name[100]; pid_t tid = syscall(__NR_gettid); int repeat; int global_repeat = 0; int status = 0; int page_size; /* * This Structure Pointer is Used to Store the Pre Process, Post Process and Metrics Kernel Memory Pointers as well as the File Descriptors * which are used by the pre_process_mmap(), post_process_mmap() and shared_repo_mmap() Functions for Mapping the Kernel's Allocated Memories for the Current Thread. */ struct per_thread_info *mm_per_thread_info; /* * Used to Keep the Last Time Value Captured by the FPGA's Shared Timer. */ uint64_t time_stamp; /* * Used to Point to Pre Process Userspace Memory for the Source Data of the Acceleration Group SG. */ uint8_t *u8_sg_pre_process_kernel_address = NULL; /* * Used to Point to Post Process Userspace Memory for the Destination Data of the Acceleration Group SG. */ uint8_t *u8_sg_post_process_kernel_address = NULL; /* * This Structure Pointer is Used to Store the Pre Process and Post Process Userspace Memory Pointers. */ struct sg_list_addresses *sg_list_src_dst_addresses = NULL; char* device_file_name = device_driver_name; /* * Open the PCIe Device Driver. */ device_file = open(device_file_name, O_RDWR); if ( device_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening Device File\n"); #endif return 0; } /* * Call the clear_screen() Function to Clear the Terminal Screen */ clear_screen(); #ifdef DEBUG_MESSAGES_UI printf("Performing .bmp Image Acceleration\n"); #endif /* * Allocate a "per_thread_info" Structure */ mm_per_thread_info = (struct per_thread_info *)malloc(sizeof(struct per_thread_info)); pid = getpid(); /* * Read the Time Spot where the Required Preparation before Acceleration Started. * * The uint_64_pcie_bar_kernel_address Pointer Points to the PCIe BAR0 which Gives Access to the Peripherlas of the FPGA. * The BAR0_OFFSET_TIMER is the Offset where the Shared Timer Peripheral is Mapped in the FPGA AXI Address Space. * Reading from that Offset of the uint_64_pcie_bar_kernel_address Pointer is Actually Reading the Lower and Upper Registers of the Global Clock Counter of the Shared Timer (Shared APM). */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; /* * MMap Kernel Memory Allocation (4M) that is Common Between the Kernel Space and the Userspace * This Memory is Used to Store Time and Transfer Metrics */ shared_repo_kernel_address = shared_repo_mmap(mm_per_thread_info); /* * Store the Height, Width and Size of the Image that will be Accelerated. * This Information will be Given by the Driver to the Appropriate Acceleration Group. */ shared_repo_kernel_address->shared_image_info.rows = bitmap_info_header.height; shared_repo_kernel_address->shared_image_info.columns = bitmap_info_header.width; shared_repo_kernel_address->shared_image_info.size = total_reserved_size; /* * Store the Time Spot where the Required Preparation before Acceleration Started */ shared_repo_kernel_address->process_metrics.preparation_time_start = time_stamp; /* * MMap a Kernel Memory Allocation (4M Size) so that it Can be Common Between the Kernel Space and the Userspace. * This Memory is Used by the Userspace Application to Load the Image Directly to the Kernel Space (Pre-Process Data) * This Memory is where the Accelerator Reads the Data from. */ u8_pre_process_kernel_address = pre_process_mmap(mm_per_thread_info); /* * MMap a Kernel Memory Allocation (4M Size) so that it can be Common Between the Kernel Space and the Userspace. * This Memory is where the Accelerator Writes the Processed Data to (Post-Process Data). * This Memory is Directly Accessed by the Userspace Application to Save the Processed Data to an Image File. */ u8_post_process_kernel_address = post_process_mmap(mm_per_thread_info); /* * The Post Process Kernel Memory Allocated and Mapped in the Previous Step (post_process_mmap()) is not Used in this Implementation. * Due to Limitation of Available AXI BARs we Use one Kernel Memory Allocation for the Image Data which is the Pre Process Kernel Memory. * The DMA Gets Access to that Memory through one AXI BAR, It Reads the Initial Image Data which are Processed and then Returned to the Same Memory and Same Offset. * As a Result, the Post Process Kernel Memory is Not Required but it is Created in Case the Developer Decides to Make a Different Implementation * Regarding where the DMA Reads from or Writes to and how Many BARs are Used for a Single Acceleration. * * Taking the Above into Consideration, the u8_post_process_kernel_address Pointer is Set to Point at the Pre Process Kernel Memory as the u8_pre_process_kernel_address Pointer. * The Application will Use the u8_pre_process_kernel_address Pointer to Load the Image and the u8_post_process_kernel_address Pointer to Save the Processed Image. */ u8_post_process_kernel_address = (uint8_t * )u8_pre_process_kernel_address; /* * Read the Time Spot where the Required Preparation before Acceleration Ended */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; /* * Store the Time Spot where the Required Preparation before Acceleration Ended */ shared_repo_kernel_address->process_metrics.preparation_time_end = time_stamp; /* * This Loop Contains the Main Steps of the Acceleration Procedure from Requesting Acceleration to Completing the Acceleration. * Each New Iteration of the for Loop is A New Acceleration Request. */ for(global_repeat = 0; global_repeat < global_iterations; global_repeat++) { /* * Read and Store the Time Spot where we Start to Capture the Total Time of a Single Iteration of the Acceleration Procedure */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.total_time_start = time_stamp; /* * Read and Store the Time Spot where Loading the Image to the Kernel Memory Started */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.load_time_start = time_stamp; /* * Copy the Image Data from the Common Memory where they were Initially Loaded to the Pre Process Kernel Memory (u8_pre_process_kernel_address). * An Old but Slower Approach was to Load the Image Data to the Pre Process Kernel Memory instead of Using the Copy Method. */ memcpy((void *)u8_pre_process_kernel_address, (void *)common_load, shared_repo_kernel_address->shared_image_info.size); /* * Read and Store the Time Spot where Loading the Image to the Kernel Memory Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.load_time_end = time_stamp; #ifdef DEBUG_MESSAGES_UI printf("Sending Access Request to the Driver\n"); #endif /* * Read and Store the Time Spot Right Before the Thread is Possibly Set to Sleep State (If no Acceleration Groups were Found Available). * This is where the Sleep State Possibly Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.sleep_time_start = time_stamp; /* * IOCtl Request Access to Hardware Accelerator From Driver. * This System Call Makes the Driver to Execute a Specific Code Routine that will Try to Occupy Acceleration Group(s) */ status = ioctl(device_file, COMMAND_REQUEST_ACCELERATOR_ACCESS, (unsigned long)0); if(status == FAILURE) { printf("IOCtl Failed\n"); usleep(1500000); return FAILURE; } /* * This if Statement Checks if the Acceleration Group SG is Occupied which Requires Additional Handling for Creating Scatter/Gather Lists. * The Reason for Scatter/Gather Lists is that the AGSG Uses Userspace Memory for Loading the Image Data which is Chunked in Pages. */ if(shared_repo_kernel_address->accel_occupied == ACCELERATOR_SG_OCCUPIED) { #ifdef DEBUG_MESSAGES_UI printf("The Only Available Accelerator is SG\nGoing to Allocate Userspace Memory in order to Occupy the Acceleration Group SG\n"); #endif if(u8_sg_pre_process_kernel_address == NULL && u8_sg_post_process_kernel_address == NULL) { /* * Get the Page Size which is Set by the Linux System. */ page_size = getpagesize(); /* * Allocate a "sg_list_addresses" Structure. * This Structure Holds the Pointers for the Pre Process (Source) and the Post Process (Destination) Userspace Memories. */ sg_list_src_dst_addresses = (struct sg_list_addresses *)malloc(sizeof(struct sg_list_addresses)); /* * Allocate 4M of Memory Aligned in Pages of PAGE_SIZE (4K) for the Pre Process Userspace Memory */ status = posix_memalign((void **)&sg_list_src_dst_addresses->sg_list_source_address, page_size, POSIX_ALLOCATED_SIZE); /* * Set the u8_sg_pre_process_kernel_address Pointer to Point at the Pre Process Userspace Memory as the sg_list_src_dst_addresses->sg_list_source_address Pointer. */ u8_sg_pre_process_kernel_address = (uint8_t *)sg_list_src_dst_addresses->sg_list_source_address; if(status == 0) { printf("Succesfully Allocated Memory for Source Buffer\nThe Virtual Address for Source Buffer is: 0x%016X\n", (unsigned long)sg_list_src_dst_addresses->sg_list_source_address); } else { printf("Failed to Allocate Memory for Source Buffer [ERROR %d]", status); } /* * Pin the Allocated Memory to Avoid Swapping. */ mlock(sg_list_src_dst_addresses->sg_list_source_address, POSIX_ALLOCATED_SIZE); /* * Allocate 4M of Memory Aligned in Pages of PAGE_SIZE (4K) for the Post Process Userspace Memory */ status = posix_memalign((void **)&sg_list_src_dst_addresses->sg_list_destination_address, page_size, POSIX_ALLOCATED_SIZE); /* * Set the u8_sg_post_process_kernel_address Pointer to Point at the Post Process Userspace Memory as the sg_list_src_dst_addresses->sg_list_destination_address Pointer. */ u8_sg_post_process_kernel_address = (uint8_t *)sg_list_src_dst_addresses->sg_list_destination_address; if(status == 0) { printf("Succesfully Allocated Memory for Destination Buffer\nThe Virtual Address for Destination Buffer is: 0x%016X\n", (unsigned long)sg_list_src_dst_addresses->sg_list_destination_address); } else { printf("Failed to Allocate Memory for Destination Buffer [ERROR %d]", status); } /* * Pin the Allocated Memory to Avoid Swapping. */ mlock(sg_list_src_dst_addresses->sg_list_destination_address, POSIX_ALLOCATED_SIZE); } /* * The Thread Originally Copied the Image Data to the Pre Process Kernel Memory (u8_pre_process_kernel_address). * Since there was no Available Acceleration Group (Except for the AGSG) that Uses the Kernel Memory the Data Must be Copied to the * Pre Process Userspace Memory so that they Can be Processed by the Acceleration Group SG (AGSG). */ memcpy(u8_sg_pre_process_kernel_address, u8_pre_process_kernel_address, total_reserved_size); sg_list_src_dst_addresses->current_pid = tid; /* * Read and Store the Time Spot where Setting the Scatter/Gather Lists Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start = time_stamp; /* * IOCtl Request to Create the Scatter/Gather List. * This System Call Provides the Driver with the Pre Process and Post Process Memory Pointers so that the Driver Can Create * two Scatter/Gather Lists for the Source and Destination of the Image Data. */ ioctl(device_file, COMMAND_SET_PAGES, (unsigned long)sg_list_src_dst_addresses); /* * Read and Store the Time Spot where Setting the Scatter/Gather Lists Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end = time_stamp; /* * Read and Store the Time Spot Right Before the Thread is Possibly Set to Sleep State (If no Acceleration Groups were Found Available). * This is where the Sleep State Possibly Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.sleep_time_start = time_stamp; /* * IOCtl Request Access to Hardware Accelerator From Driver. * This System Call Makes the Driver to Execute a Specific Code Routine that will Try to Occupy Acceleration Group(s). * This Time Since there were no other Acceleration Groups Available (Except for the AGSG) the Application Requests to Occupy the Acceleration Group SG. */ ioctl(device_file, COMMAND_REQUEST_ACCELERATOR_SG_ACCESS, (unsigned long)0); } /* * The shared_repo_kernel_address->accel_occupied is a Flag whose 7 LSBs Indicate which Acceleration Groups where Occupied for the Current Thread Depending on the Acceleration Policy. * The shared_repo_kernel_address->accel_completed is a Flag whose 7 LSBs Indicate which Acceleration Groups Have Completed their Procedure. * When the Driver Occupies a Number of Acceleration Groups for the Thread we Expect that the Total Acceleration is Completed when all the Occupied Acceleration Groups Have Completed. * As a Result the while Loop is Active until all the Acceleration Groups that where Occupied are Completed. */ while(shared_repo_kernel_address->accel_completed != shared_repo_kernel_address->accel_occupied) { } printf("Occupied: %d Completed: %d [PID: %d]\n", shared_repo_kernel_address->accel_occupied, shared_repo_kernel_address->accel_completed, tid); #ifdef DEBUG_MESSAGES_UI printf("Accereration Completed\n"); #endif /* * Call the set_save_accelerator() Function to Create the Path and Name for the Image File. */ set_save_accelerator(save_path_name, shared_repo_kernel_address->accel_occupied, tid, global_repeat); /* * The if-else Statement Below Nests the Procedure for Saving the Processed Image. * Check the accel_occupied Flag to Know if the Acceleration Group SG was Used Because Saving the Image in such Case Requires Special Handling. */ if(shared_repo_kernel_address->accel_occupied == ACCELERATOR_SG_OCCUPIED) { /* * Read and Store the Time Spot where Unmapping the Pages Started. * Those Pages were Previously Mapped when Creating the Scatter/Gather Lists. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start = time_stamp; /* * IOCtl Request to Unmap the Pages. * This System Call Makes the Driver to Execute a Specific Code Routine that will Try to Unmap the Pages * that were Previoulsy Mapped when Creating the Scatter/Gather Lists. * The Scatter/Gather Mapped Pages Must be Released before the Application Tries to Read and Store * the Processed Image Data from the Pre Process Userspace Memory. * * The Unmap Procedure is Only Required if the Acceleration Group SG was Occupied. */ ioctl(device_file, COMMAND_UNMAP_PAGES, (unsigned long)0); /* * Read and Store the Time Spot where Unmapping the Pages Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end = time_stamp; /* * If the save_request Value is Set to 1 then Save the Image in EACH Iteration. */ if(save_request == 1) { /* * Read and Store the Time Spot where Saving the Processed Image Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_start = time_stamp; /* * Call the save_bmp() Function to Save the Image from the Post Process Usespace Memory (u8_sg_post_process_kernel_address) to the Storage Device (save_path_name). */ status = save_bmp(u8_sg_post_process_kernel_address, save_path_name); /* * Read and Store the Time Spot where Saving the Processed Image Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_end = time_stamp; } /* * If the save_request Value is Set to 2 then Save the Image Only in the Last Iteration. */ if(save_request == 2) { /* * If the Current Iteration is Equal with the Number of global_iterations then it is the Last Iteration so Save the Processed Image. */ if(global_repeat == (global_iterations - 1)) { /* * Read and Store the Time Spot where Saving the Processed Image Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_start = time_stamp; /* * Call the save_bmp() Function to Save the Image from the Post Process Usespace Memory (u8_sg_post_process_kernel_address) to the Storage Device (save_path_name). */ status = save_bmp(u8_sg_post_process_kernel_address, save_path_name); /* * Read and Store the Time Spot where Saving the Processed Image Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_end = time_stamp; } } } else { if(save_request == 1) { /* * Read and Store the Time Spot where Saving the Processed Image Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_start = time_stamp; /* * Call the save_bmp() Function to Save the Image from the Pre Process Kernel Memory (u8_post_process_kernel_address Points to u8_pre_process_kernel_address) * to the Storage Device (save_path_name). */ status = save_bmp(u8_post_process_kernel_address, save_path_name); /* * Read and Store the Time Spot where Saving the Processed Image Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_end = time_stamp; } if(save_request == 2) { /* * If the Current Iteration is Equal with the Number of global_iterations then it is the Last Iteration so Save the Processed Image. */ if(global_repeat == (global_iterations - 1)) { /* * Read and Store the Time Spot where Saving the Processed Image Started. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_start = time_stamp; /* * Call the save_bmp() Function to Save the Image from the Pre Process Kernel Memory (u8_post_process_kernel_address Points to u8_pre_process_kernel_address) * to the Storage Device (save_path_name). */ status = save_bmp(u8_post_process_kernel_address, save_path_name); /* * Read and Store the Time Spot where Saving the Processed Image Ended. */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.save_time_end = time_stamp; } } } /* * Read and Store the Time Spot where we End to Capture the Total Time of a Single Iteration of the Acceleration Procedure */ time_stamp = uint_64_pcie_bar_kernel_address[BAR0_OFFSET_TIMER / 8]; shared_repo_kernel_address->process_metrics.total_time_end = time_stamp; /* * Call the print_save_metrics() Function to Collect and Save the Metrics of the Current Iteration in the Metrics .xml File. */ print_save_metrics(shared_repo_kernel_address, shared_repo_kernel_address->accel_occupied, tid, global_repeat); /* * Reset to Zero the Following 6 Fields of the Metrics and Flags Kernel Memory. */ shared_repo_kernel_address->process_metrics.set_pages_overhead_time_start = 0; shared_repo_kernel_address->process_metrics.set_pages_overhead_time_end = 0; shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_start = 0; shared_repo_kernel_address->process_metrics.unmap_pages_overhead_time_end = 0; shared_repo_kernel_address->accel_completed = 0; shared_repo_kernel_address->accel_occupied = 0; if(status == SUCCESS) { #ifdef DEBUG_MESSAGES_UI printf("Saving Bitmap [SUCCESS]\n"); #endif } else { printf("Multi-Application Access Test Failed / Save Image Error\n"); usleep(1500000); return FAILURE; } completed++; printf("Completed Jobs: %d [PID: %d]\n", completed, tid); } /* * If the sg_list_src_dst_addresses Pointer is not Null then Release All the Memories Related with the Acceleration Group SG. */ if(sg_list_src_dst_addresses != NULL) { printf("Freed SG Lists [PID: %d]\n", tid); /* * If the Pre Process (Source) Userspace Memory (sg_list_src_dst_addresses->sg_list_source_address) was Used (not Null) then Release it. */ if(sg_list_src_dst_addresses->sg_list_source_address != NULL) { free(sg_list_src_dst_addresses->sg_list_source_address); #ifdef DEBUG_MESSAGES_UI printf("SG LIST SOURCE FREED %d\n", tid); #endif } /* * If the Post Process (Destination) Userspace Memory (sg_list_src_dst_addresses->sg_list_destination_address) was Used (not Null) then Release it. */ if(sg_list_src_dst_addresses->sg_list_destination_address != NULL) { free(sg_list_src_dst_addresses->sg_list_destination_address); #ifdef DEBUG_MESSAGES_UI printf("SG LIST DESTINATION FREED %d\n", tid); #endif } /* * Free the Memory Allocation of the sg_list_src_dst_addresses Pointer. */ free(sg_list_src_dst_addresses); } /* * Call munmap() to Release the Pre Process Kernel Memory that was Mapped when Calling the pre_process_mmap() Function. */ munmap(mm_per_thread_info->u8_pre_process_kernel_address, MMAP_ALLOCATION_SIZE); /* * Call munmap() to Release the Post Process Kernel Memory that was Mapped when Calling the post_process_mmap() Function. */ munmap(mm_per_thread_info->u8_post_process_kernel_address, MMAP_ALLOCATION_SIZE); /* * Call munmap() to Release the Metrics Kernel Memory that was Mapped when Calling the shared_repo_mmap() Function. */ munmap(mm_per_thread_info->shared_repo_kernel_address, MMAP_ALLOCATION_SIZE); /* * Close the pre_process_mmap_file File that was Opened when Calling the pre_process_mmap() Function. */ close(mm_per_thread_info->pre_process_mmap_file); /* * Close the post_process_mmap_file File that was Opened when Calling the post_process_mmap() Function. */ close(mm_per_thread_info->post_process_mmap_file); /* * Close the shared_repo_mmap_file File that was Opened when Calling the shared_repo_mmap() Function. */ close(mm_per_thread_info->shared_repo_mmap_file); /* * Close the PCIe Device Driver. */ close(device_file); /* * Free the Memory Allocation of the mm_per_thread_info Pointer. */ free(mm_per_thread_info); completed = 0; return SUCCESS; } /* OK * The Starting Point for the Application */ int main(int argc, char *argv[]) { /* * The Device Driver to Open */ char device_driver_name[] = "/dev/xilinx_pci_driver"; int device_file = -1; /* * Used to Store the Arithmetic Value Read from the renamer.txt File */ char value[4]; /* * Used for File Operations on the Image File */ FILE *bmp_file; /* * Used for File Operations on the Metrics .xml File */ FILE *metrics_summary_file; /* * Used for File Operations on the renamer.txt File */ FILE *renamer_file; /* * Used to Store the Path and Name of the Metrics .xml File */ char file_name[100]; int repeat; int global_repeat = 0; int test_iterations = 0; int test_repeat = 0; int status; /* * Used to Store the Number of Threads that the Application is Going to Start. */ int threads_number = 0; /* * Get the First Argument of the Application Call. * The First Argument Represents the Path and Name of the Image File to Accelerate. */ strcpy(load_path_name, argv[1]); /* * Get the Second Argument of the Application Call. * The Second Argument Represents the Number of Iterations (Acceleration Requests) that each Thread Should Perform. */ global_iterations = atoi(argv[2]); /* * Get the Third Argument of the Application Call. * The Third Argument Represents the Number of Threads that the Application is Going to Start. */ threads_number = atoi(argv[3]); /* * Get the Fourth Argument of the Application Call. * The Fourth Argument Represents the Save Flag which Refers to Saving or Not the Accelerated Image. * See the Comments of the save_request at the Global Variables Section for more Details. */ save_request = atoi(argv[4]); /* * Get the Fifth Argument of the Application Call. * The Fifth Argument Represents the Number of Tests to Run. * In every Test the Application Starts a Number of Threads according to the threads_number Variable * and each Thread Runs for a Number of Iterations (Acceleration Requests) According to the global_iterations Variable */ test_iterations = atoi(argv[5]); clear_screen(); /* * The for Loop Below Represents the Tests Execution * It Loops for as Many Times as Defined by the test_iterations Variable */ for(test_repeat = 0; test_repeat < test_iterations; test_repeat++) { /* * Call pcie_bar_mmap() to Map the PCIe BAR0 and PCIe BAR1 of the PCIe Bridge to the Virtual Address Space of the Userspace * See Details Inside the pcie_bar_mmap() Function Description */ status = pcie_bar_mmap(); if(status == SUCCESS) { #ifdef DEBUG_MESSAGES_UI printf("Memory Mapping PCIe BAR Address Space [SUCCESS]\n"); #endif } else { printf("Memory Mapping PCIe BAR Address Space [FAILURE]\n"); #ifdef DEBUG_MESSAGES_UI usleep(1500000); #endif return FAILURE; } /* * Call setup_signal_handling() Function to Setup the Handler for Signals Triggered by the Kernel Module */ setup_signal_handling(); /* * Call getpid() to Get the Parent Process ID */ pid = getpid(); printf("Process ID is: %d\n", pid); /* * Open the Image File According to the File Name Given by the the User. * In this Point We Open the Image File to Extract Information from Its Header. * This Information (Image Width/Heigth etc) Will be Shared by All the Threads */ bmp_file = fopen(load_path_name, "r"); if(bmp_file != NULL) { #ifdef DEBUG_MESSAGES_UI printf("Image File Opened\n"); #endif } else { if(bmp_file == NULL) { printf("Image Failed to Open [NULL Pointer]\n"); } usleep(2000000); return(FAILURE); } #ifdef DEBUG_MESSAGES_UI printf("Checking the Magic Number to Validate that this is a Bitmap File\n"); #endif /* * Read the Magic Number from the Header of the Bitmap File. */ fread(&magic_number, sizeof(bmpfile_magic_t), 1, bmp_file); /* * Check the Magic Number to Validate that this is a Bitmap File. * The Magic Number for .bmp Files is: 0x4D42. */ if (*((uint16_t *)magic_number.magic) == 0x4D42) { #ifdef DEBUG_MESSAGES_UI printf("Bitmap File Valid [MAGIC NUMBER 0x%X]\n", *((uint16_t *)magic_number.magic)); #endif } else { #ifdef DEBUG_MESSAGES_UI printf("No Bitmap File Was Found/Aborting\n"); #endif fclose(bmp_file); return FAILURE; } #ifdef DEBUG_MESSAGES_UI printf("Reading the Bitmap File Header\n"); #endif /* * Read the Bitmap File Header */ fread(&bitmap_file_header, sizeof(bmpfile_header_t), 1, bmp_file); #ifdef DEBUG_MESSAGES_UI printf("Reading the Bitmap Info Header\n"); #endif /* * Read the Bitmap Info Header */ fread(&bitmap_info_header, sizeof(bitmap_info_header_t), 1, bmp_file); #ifdef DEBUG_MESSAGES_UI printf("Checking Compression\n"); #endif /* * Read the Info Header Structure to Check if Compression is Supported */ if (bitmap_info_header.compress_type == 0) { #ifdef DEBUG_MESSAGES_UI printf("Compression is Supported\n"); #endif } else { #ifdef DEBUG_MESSAGES_UI printf("Warning, Compression is not Supported\n"); #endif } /* * Print Information About the Image */ #ifdef DEBUG_MESSAGES_UI printf("\n* Image Width: %d Pixels\n", bitmap_info_header.width); printf("* Image Height: %d Pixels\n", bitmap_info_header.height); printf("* Image Size: %d Bytes\n", bitmap_info_header.bmp_bytesz); printf("* Image Header Size: %d Bytes\n", bitmap_info_header.header_sz); printf("* Bits Per Pixel: %d \n\n", bitmap_info_header.bitspp); #endif /* * Close the Image File Since We Extracted the Necessary Information from the Headers */ fclose(bmp_file); /* * Allocate a Common Memory Area Equal to the Size of the Clear Image Data (No Headers) Along with the Required Padding. * common_load is the Pointer where All Threads will Copy the Image from. */ common_load = (uint8_t *)malloc(bitmap_info_header.width * bitmap_info_header.height * 4); /* * Call the load_bmp() Function to Load the Image to a Common Memory */ status = load_bmp(common_load); /* * Open the renamer.txt File */ renamer_file = fopen("Results/renamer.txt", "r"); /* * Read the Arithmetic Value Stored as a String in the renamer.txt File */ fscanf(renamer_file, "%s", value); /* * Close the renamer.txt File */ fclose(renamer_file); /* * Convert the Previous Arithmetic Value from String to Integer and Write it to the renamer_value * This Integer Value Will Be Used to Name and Save the Metrics .xml File when the Current Test Completes */ renamer_value = atoi(value); /* * Use sprintf() to Create a String that Represents the Path and Name of the Metrics .xml File. * The Arithmetic Value of the renamer_value Variable is Included in the File Name to Ensure that each Test Iteration * Creates a New .xml File which is Unique Among the Rest .xml Files. */ sprintf(file_name,"Results/Metrics_Summary_%d.xml", renamer_value); /* * Open the Current Metrics .xml File */ metrics_summary_file = fopen(file_name, "a"); /* * Since this is the First Time we Open the File it is Required to Write the XML Header. */ fprintf(metrics_summary_file,"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\n\n"); /* * It is, also, Required to Write the Open Tag of the Root Node */ fprintf(metrics_summary_file,"<Process_Plot>\n\n"); /* * Close for now the Current Metrics .xml File */ fclose(metrics_summary_file); /* * Write a Value to the Data Register of the GPIO PCIe Interrupt Peripheral of the FPGA through the PCIe BAR0. * The Written Value is a Command to Start the FPGA Shared Timer (Shared APM). * On Receiving the new Value the GPIO PCIe Interrupt Peripheral Triggers an Interrupt. * This Interrupt is Handled by the Microblaze that Reads the Command (Written Value) from the Data Register of the GPIO PCIe Interrupt Peripheral. * See Details for this Pointer at the Global Variables Section */ uint_64_pcie_bar_kernel_address[BAR0_OFFSET_GPIO_PCIE_INTERRUPT / 8] = (uint32_t)OPERATION_START_TIMER; usleep(150000); //Do Not Remove. Microblaze Requires Some Time to Restart the Shared Timer Before we Use it to Get Correct Time Stamps /* * Call multi_threaded_acceleration() Function to Start new Threads According to the Value of the threads_number Variable. * When this Function Returns All Threads Have Completed and we are Ready to Move to the Next Test Iteration. */ multi_threaded_acceleration(threads_number); /* * At this Point All Threads Have Completed and any Metrics Info is Already Written to the Current Metrics .xml File. * We Have to Re-open the Current Metrics .xml File to Write the Close Tag of the Root Element. */ metrics_summary_file = fopen(file_name, "a"); /* * Write the Close Tag of the Root Element. */ fprintf(metrics_summary_file,"</Process_Plot>\n\n"); /* * Close the Current Metrics .xml File. */ fclose(metrics_summary_file); /* * Increment the Arithmetic Value of the renamer_value Variable. * This Value will be Used in the Next Test Iteration to Save a New Metrics .xml File. */ renamer_value++; /* * Open the renamer.txt File and Update it with the Incremented Arithmetic Value of the renamer_value Variable. */ renamer_file = fopen("Results/renamer.txt", "w"); fprintf(renamer_file,"%d", renamer_value); fclose(renamer_file); /* * Unmap the PCIe BAR0 from the Virtual Address Space. * It is Important that the Unmap Operation Should Happen before Closing the Corresponding pcie_bar_0_mmap_file. */ munmap(uint_64_pcie_bar_kernel_address, MMAP_ALLOCATION_SIZE); /* * Unmap the PCIe BAR1 from the Virtual Address Space * It is Important that the Unmap Operation Should Happen before Closing the Corresponding pcie_bar_1_mmap_file. */ munmap(shared_kernel_address, 128 * KBYTE); /* * Free the Allocated Common Memory */ free(common_load); /* * Close the pcie_bar_0_mmap_file and pcie_bar_1_mmap_file Files that where Opened when we Previously Called pcie_bar_mmap(). * These to Files are Actually Debugfs Files that are Associated with the Xilinx PCIe Device Driver. * See Details in the pcie_bar_mmap() Function Description. */ close(pcie_bar_0_mmap_file); close(pcie_bar_1_mmap_file); /* * Open the Xilinx PCIe Device Driver. */ char* device_file_name = device_driver_name; device_file = open(device_file_name, O_RDWR); if ( device_file < 0 ) { #ifdef DEBUG_MESSAGES_UI printf("[DEBUG MESSAGE] Error Opening Device File\n"); #endif return 0; } /* * Make a IOCtl System Call to Request Reseting the Driver's Variables. * The Driver will Actually Set to Zero the Synchronization Flags tha are Loacated in the FPGA BRAM. */ status = ioctl(device_file, COMMAND_RESET_VARIABLES, (unsigned long)0); /* * Close the Xilinx PCIe Device Driver. */ close(device_file); } return SUCCESS; }
0def4085d65967c43c47335e709ed377c769d228
7b83ba2cdfb21b2d99a2482f8f9969232844e339
/0295_Find_Median_from_Data_Stream/MQQM.cpp
2fbd1e57da63f424ee828de323c75fd6504ce7bb
[]
no_license
MQQM/LeetCode
515b1bab62f174753c5a50dee5e3bd63500a78dc
ad3ce34c4b8a1a2cb5be59a64a1633747a1d55e4
refs/heads/master
2020-04-01T23:37:37.421439
2020-01-23T05:07:58
2020-01-23T05:07:58
152,594,081
1
0
null
2018-10-11T13:12:12
2018-10-11T13:12:12
null
UTF-8
C++
false
false
965
cpp
/* 题目: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 参考: https://blog.csdn.net/lv1224/article/details/82222719 */ class Solution { private: vector<int> nums; public: void Insert(int num){ auto it=upper_bound(nums.begin(),nums.end(),num); // 在一个区间中找到,返回大于val的第一个元素位置 nums.insert(it,num); } double GetMedian() { int len = nums.size(); if(len%2==0){ return ( nums[len/2 -1] + nums[len/2] ) / 2.0; } else{ return nums[len/2]; } } };
32aea8150f3176b857c2c9340443edad0cca41e4
2cd103b2972f4f1f32e860cd5d5b5010a536ee88
/dig/Code/Scanner.h
ddc317c4e1f0cdb27588d2b6f5fe8ba2afe80e71
[]
no_license
MasterCna/digger
f946aad2c0eac29c2888612942c26c5e876b2fab
813f818072d2a0a40af08d64d235033214bcad53
refs/heads/master
2021-04-27T05:48:43.596618
2018-02-23T09:48:39
2018-02-23T09:48:39
122,601,816
1
0
null
2018-02-23T09:51:47
2018-02-23T09:39:56
C++
WINDOWS-1252
C++
false
false
562
h
/****************************************************************************\ * Created: 1/9/2018 by Ali Sepehri-Amin * Version: 0.9.0000 * Copyright © Tehranbytes Team. * History: - * Description: - \****************************************************************************/ #ifndef __SCANNER_H__ #define __SCANNER_H__ #include <Windows.h> #include <iostream> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #include <queue> class CScanner { public: int ScanFile(const std::wstring& p_path, std::string &status); }; #endif // __SCANNER_H__
ca0f8221aa0734ebea3d22c4393300dc286a9717
665813341b9d0911aaab3658c38b495ff1dae30a
/AtCoder/ABC/160/B-GoldenCoins.cpp
5ed0cf5feca93b440c7324a4356d5f0c96248138
[]
no_license
THEToilet/program
1fd54802d8e90ae648a50685d2ff8ee1838ebeb9
30b13449e114849981f832a6360dd0ab702682d1
refs/heads/master
2021-12-22T07:14:47.025845
2021-12-19T17:10:29
2021-12-19T17:10:29
243,990,671
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
#include <bits/stdc++.h> using namespace std; int main() { long int X; cin >> X; long int fivehund; long int five; fivehund = X/500; //cout << fivehund << endl; five = (X-fivehund*500)/5; // cout << five << endl; cout << fivehund*1000 + five*5 << endl; }
f29a4c2435f359d4a8ad38c89963f5434d776ecd
f8b1dfccaef5a8f75567b527fc7c2f0a34e3877b
/swjtu/e20150122/p2.cpp
5575c5fe715b261983ffeb72451e6cdc7e92832c
[]
no_license
bamboohiko/problemSolve
e7e2a2c6e46a4d10ccfa54cffff3c9895b3ddb1b
cd3e9e5986325f5def4efe01975a950f6eaa6015
refs/heads/master
2021-01-17T06:39:42.502176
2017-09-13T14:30:08
2017-09-13T14:30:08
47,928,189
0
0
null
null
null
null
UTF-8
C++
false
false
886
cpp
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int f[100000 + 10]; set<int> use; int add(int x) { if (!use.count(x)) { use.insert(x); return 1; } return 0; } int main() { int x,y,t = 0; while (scanf("%d%d",&x,&y) != EOF && x >= 0 && y >= 0) { printf("Case %d is ",++t); if (!x || !y) { printf("not a tree.\n"); continue; } use.clear(); int cou = 1,n = add(x) + add(y),ans = 1; memset(f,0,sizeof(f)); if (x == y) ans = 0; while (scanf("%d%d",&x,&y) != EOF && x && y) { cou++; n += add(x) + add(y); f[y]++; if (f[y] > 1) ans = 0; } if (cou != n-1) ans = 0; if (!ans) printf("not "); printf("a tree.\n"); } return 0; }
9a11bc9fabca9a4fc4a271683bd328cb80ec1c7b
e47888a89a89c3ba5010efac9f52ceb44cc35b48
/opengl/src/test.cpp
851ac914f84243fdc60961b7dc502e6287bc1024
[ "MIT" ]
permissive
workflowmate/shoveler
9c3c36784004026d47c22bf033db067740517282
3846427cd43ff3bdec291fc3dffd306d02fff1d0
refs/heads/master
2022-10-12T15:11:43.861882
2020-06-12T10:43:38
2020-06-12T10:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <gtest/gtest.h> extern "C" { #include "shoveler/log.h" } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); shovelerLogInit("shoveler/", SHOVELER_LOG_LEVEL_ALL, stdout); int result = RUN_ALL_TESTS(); shovelerLogTerminate(); return result; }
0c557e1997292da9927c852c4f37b81957a6415b
53ffff4bf1b977e52da7b925cfa428f9c291e937
/State/workState/AfternoonState.h
27e8dc2a567f63d35fa319c5282a0a8bb757e17c
[]
no_license
willtuna/DesignPatternExercise
4260c1b2b7096e353b4b0eea67ee028a9c9992ca
8d1b43c5a739f2fa8705ce5a96fa8c50f1c47b36
refs/heads/master
2020-04-14T17:13:07.968621
2014-09-03T10:25:21
2014-09-03T10:25:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
154
h
#ifndef AFTERNOONSTATE_H #define AFTERNOONSTATE_H #include "state.h" class AfternoonState : public State { public: void WriteProgram(Work& w); }; #endif
0533b3f338751418b98814b9fdea9017e9ea96c3
511d7cd374cf8ecdc6a9d72223bed16a32d83c78
/msdk/mscom/download/downloadmgr/HttpSyncRequest.cpp
63f4467080bd2e48256da2abda128c73b7af1de3
[]
no_license
mynick777/msdk
1818c718a181de772b9a3e2dd6d7b9a66296dc86
4ee669c60148ad72e1d8af9bea05e05019af79e6
refs/heads/master
2020-05-18T00:56:37.308774
2019-05-01T16:19:13
2019-05-01T16:19:13
184,075,465
0
0
null
2019-04-29T13:22:32
2019-04-29T13:22:32
null
WINDOWS-1256
C++
false
false
8,148
cpp
#include "StdAfx.h" #include "HttpSyncRequest.h" #include <vector> CHttpSyncRequest::CHttpSyncRequest(void) { } CHttpSyncRequest::~CHttpSyncRequest(void) { } STDMETHODIMP CHttpSyncRequest::HttpRequest(LPCWSTR lpszUrl, /*IMsBuffer*/IMSBase** ppBuffer) { RASSERT(lpszUrl && _tcslen(lpszUrl), E_INVALIDARG); UTIL::com_ptr<IMsBuffer> pBuffer; DllQuickCreateInstance(CLSID_MsBuffer, re_uuidof(IMsBuffer), pBuffer,NULL); RASSERT(pBuffer, E_FAIL); fsURL url; fsInternetResult fsRet = url.Crack(lpszUrl); if (fsRet != IR_SUCCESS) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsURL::Crack(%s)"), lpszUrl); return E_FAIL; } fsInternetSession Session; fsHttpConnection HttpConnection; fsHttpFile HttpFile; fsRet = Session.Create(_T("HttpSyncRequest"), IAT_NOPROXY, _T("")); fsRet = HttpConnection.Initialize(&Session); fsRet = HttpFile.Initialize(&HttpConnection); BOOL bRedirInner; LPTSTR pszNewUrl = NULL; fsRet = HttpOpenUrl(lpszUrl, url.GetUserName(), url.GetPassword(), &HttpConnection, &HttpFile, &pszNewUrl, &bRedirInner, 0); BYTE pBuf[1024] = {0}; DWORD dwRead = 0; do { dwRead = 0; fsRet = HttpFile.Read(pBuf, sizeof(pBuf), &dwRead); if (fsRet == IR_SUCCESS) { if (dwRead) { pBuffer->AddTail(pBuf, dwRead); } else //½لتّ { break; } } else { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsHttpFile::Read(%s)"), lpszUrl); break; } } while (TRUE); if (fsRet == IR_SUCCESS) { pBuffer->QueryInterface(re_uuidof(IMsBuffer), (void**)ppBuffer); return S_OK; } GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest(%s)"), lpszUrl); return E_FAIL; } fsInternetResult CHttpSyncRequest::HttpOpenPath(LPCTSTR pszPath, fsHttpConnection *pServer, fsHttpFile *pFile, LPTSTR *ppRedirectedUrl, BOOL *pbRedirInner, UINT64 uPos /*=0*/) { fsInternetResult ir; pFile->Initialize (pServer); *ppRedirectedUrl = NULL; ir = pFile->Open (pszPath, uPos); //m_strCookes = pFile->GetCookies(); if (ir != IR_SUCCESS) { if (ir == IR_NEEDREDIRECT) { CString strUrl = pFile->GetLastError (); fsURL u; BOOL bRelUrl = FALSE; //strUrl+=pszPath; if (u.Crack (strUrl) != IR_SUCCESS) bRelUrl = TRUE; *pbRedirInner = TRUE; if (bRelUrl) { if (*pFile->GetLastError () != '/' && *pFile->GetLastError () != '\\') { strUrl = pszPath; int len = strUrl.GetLength(); while (strUrl [len - 1] != '/' && strUrl [len - 1] != '\\') len--; strUrl.SetAt(len, '\0') ; strUrl += pFile->GetLastError (); } else { strUrl = pFile->GetLastError (); } ir = HttpOpenPath (strUrl, pServer, pFile, ppRedirectedUrl, pbRedirInner, uPos); } else { strUrl = pFile->GetLastError (); ir = HttpOpenUrl (strUrl, NULL, NULL, pServer, pFile, ppRedirectedUrl, pbRedirInner, uPos); } if (*ppRedirectedUrl == NULL) { *ppRedirectedUrl = new TCHAR[strUrl.GetLength() + 1]; lstrcpy (*ppRedirectedUrl, strUrl); } *pbRedirInner = *pbRedirInner && bRelUrl; } return ir; } return IR_SUCCESS; } fsInternetResult CHttpSyncRequest::HttpOpenUrl(LPCTSTR pszUrl, LPCTSTR pszUser, LPCTSTR pszPassword, fsHttpConnection *pServer, fsHttpFile *pFile, LPTSTR *ppRedirectedUrl, BOOL *pbRedirInner , UINT64 uPos /*=0*/) { fsURL url; fsInternetResult ir; ir = url.Crack (pszUrl); if (ir != IR_SUCCESS) return ir; ir = pServer->Connect (url.GetHostName (), pszUser ? pszUser : url.GetUserName (), pszPassword ? pszPassword : url.GetPassword (), url.GetPort ()); if (ir != IR_SUCCESS) return ir; pFile->UseSecure (url.GetInternetScheme () == INTERNET_SCHEME_HTTPS); pFile->UseCookie(TRUE); //pFile->SetCookies(m_strCookes); return HttpOpenPath (url.GetPath (), pServer, pFile, ppRedirectedUrl, pbRedirInner, uPos); } STDMETHODIMP CHttpSyncRequest::HttpDownload(LPCWSTR lpszUrl, LPCWSTR lpszSafeFile) { RASSERT(lpszUrl && _tcslen(lpszUrl) && lpszSafeFile && _tcslen(lpszSafeFile), E_INVALIDARG); mspath::CPath::CreateDirectoryEx(lpszSafeFile); fsURL url; fsInternetResult fsRet = url.Crack(lpszUrl); if (fsRet != IR_SUCCESS) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsURL::Crack(%s)"), lpszUrl); return E_FAIL; } fsInternetSession Session; fsHttpConnection HttpConnection; fsHttpFile HttpFile; fsRet = Session.Create(_T("HttpDownload"), IAT_NOPROXY, _T("")); fsRet = HttpConnection.Initialize(&Session); fsRet = HttpFile.Initialize(&HttpConnection); BOOL bRedirInner; LPTSTR pszNewUrl = NULL; CString strSaveTempFile = lpszSafeFile; strSaveTempFile += ".download"; ::DeleteFile(strSaveTempFile); UTIL::sentry<HANDLE, UTIL::handle_sentry> hSaveFile = CreateFile(strSaveTempFile, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hSaveFile == INVALID_HANDLE_VALUE) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpDownload::CreateFile(%s)"), strSaveTempFile.GetBuffer()); return E_FAIL; } fsRet = HttpOpenUrl(lpszUrl, url.GetUserName(), url.GetPassword(), &HttpConnection, &HttpFile, &pszNewUrl, &bRedirInner, 0); BYTE pBuf[1024] = {0}; DWORD dwRead = 0; do { dwRead = 0; fsRet = HttpFile.Read(pBuf, sizeof(pBuf), &dwRead); if (fsRet == IR_SUCCESS) { if (dwRead) { DWORD dwWrite = 0; WriteFile(hSaveFile, pBuf, dwRead, &dwWrite, NULL); FlushFileBuffers(hSaveFile); } else //½لتّ { break; } } else { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsHttpFile::Read(%s)"), lpszUrl); break; } } while (TRUE); hSaveFile = NULL; if (fsRet == IR_SUCCESS) { DeleteFile(lpszSafeFile); if (MoveFile(strSaveTempFile, lpszSafeFile)) { return S_OK; } } GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest(%s)"), lpszUrl); return E_FAIL; } STDMETHODIMP CHttpSyncRequest::HttpPost(LPCWSTR lpszUrl, LPCWSTR lpszPath, LPCWSTR lpszParam,/*IMsBuffer*/IMSBase** ppBuffer) { RASSERT(lpszUrl && _tcslen(lpszUrl), E_INVALIDARG); UTIL::com_ptr<IMsBuffer> pBuffer; DllQuickCreateInstance(CLSID_MsBuffer, re_uuidof(IMsBuffer), pBuffer,NULL); RASSERT(pBuffer, E_FAIL); fsURL url; fsInternetResult fsRet = url.Crack(lpszUrl); if (fsRet != IR_SUCCESS) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsURL::Crack(%s)"), lpszUrl); return E_FAIL; } UTIL::sentry<fsInternetSession* ,UTIL::default_sentry> Session = new fsInternetSession(); UTIL::sentry<fsHttpConnection* ,UTIL::default_sentry> HttpConnection = new fsHttpConnection(); UTIL::sentry<fsHttpFile* ,UTIL::default_sentry> HttpFile = new fsHttpFile(); //fsInternetSession Session; //fsHttpConnection HttpConnection; //fsHttpFile HttpFile; fsRet = Session->Create(_T("HttpSyncRequest"), IAT_NOPROXY, _T("")); fsRet = HttpConnection->Initialize(Session); HttpFile->Initialize(HttpConnection); HttpFile->SetPostData(lpszParam); fsRet = HttpConnection->Connect(url.GetHostName (), url.GetUserName (),url.GetPassword (), url.GetPort ()); if (fsRet != IR_SUCCESS) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpConnection::Connect(%s)"), lpszUrl); return E_FAIL; } //fsRet = HttpFile.Initialize(&HttpConnection); fsRet = HttpFile->Open(lpszPath, 0); if (fsRet != IR_SUCCESS) { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpFile::Open(%s)"), lpszUrl); return E_FAIL; } BYTE pBuf[1024] = {0}; DWORD dwRead = 0; do { dwRead = 0; fsRet = HttpFile->Read(pBuf, sizeof(pBuf), &dwRead); if (fsRet == IR_SUCCESS) { if (dwRead) { pBuffer->AddTail(pBuf, dwRead); } else //½لتّ { break; } } else { GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest::fsHttpFile::Read(%s)"), lpszUrl); break; } } while (TRUE); if (fsRet == IR_SUCCESS) { pBuffer->QueryInterface(re_uuidof(IMsBuffer), (void**)ppBuffer); return S_OK; } GrpError(GroupName, MsgLevel_Error, _T("CHttpSyncRequest::HttpRequest(%s)"), lpszUrl); return E_FAIL; }
3309e129321652340f6c2ec2360482a8b9a9a071
8dc84558f0058d90dfc4955e905dab1b22d12c08
/ui/aura/test/test_screen.cc
6d107d8b4e3227cf0301deb5c07a10631c03f5ea
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
6,473
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/aura/test/test_screen.h" #include <stdint.h> #include "base/logging.h" #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_host_mus.h" #include "ui/aura/test/mus/window_tree_client_private.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/input_method.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/native_widget_types.h" namespace aura { namespace { bool IsRotationPortrait(display::Display::Rotation rotation) { return rotation == display::Display::ROTATE_90 || rotation == display::Display::ROTATE_270; } } // namespace // static TestScreen* TestScreen::Create(const gfx::Size& size, WindowTreeClient* window_tree_client) { const gfx::Size kDefaultSize(800, 600); // Use (0,0) because the desktop aura tests are executed in // native environment where the display's origin is (0,0). return new TestScreen(gfx::Rect(size.IsEmpty() ? kDefaultSize : size), window_tree_client); } TestScreen::~TestScreen() { delete host_; } WindowTreeHost* TestScreen::CreateHostForPrimaryDisplay() { DCHECK(!host_); if (window_tree_client_) { host_ = WindowTreeClientPrivate(window_tree_client_) .CallWmNewDisplayAdded(GetPrimaryDisplay()); } else { host_ = WindowTreeHost::Create(gfx::Rect(GetPrimaryDisplay().GetSizeInPixel())); } // Some tests don't correctly manage window focus/activation states. // Makes sure InputMethod is default focused so that IME basics can work. host_->GetInputMethod()->OnFocus(); host_->window()->AddObserver(this); // Other test code may have already initialized the compositor. if (!host_->compositor()->root_layer()) host_->InitHost(); host_->window()->Show(); return host_; } void TestScreen::SetDeviceScaleFactor(float device_scale_factor) { display::Display display(GetPrimaryDisplay()); gfx::Rect bounds_in_pixel(display.GetSizeInPixel()); display.SetScaleAndBounds(device_scale_factor, bounds_in_pixel); display_list().UpdateDisplay(display); host_->OnHostResizedInPixels(bounds_in_pixel.size()); } void TestScreen::SetColorSpace(const gfx::ColorSpace& color_space) { display::Display display(GetPrimaryDisplay()); display.set_color_space(color_space); display_list().UpdateDisplay(display); } void TestScreen::SetDisplayRotation(display::Display::Rotation rotation) { display::Display display(GetPrimaryDisplay()); gfx::Rect bounds_in_pixel(display.GetSizeInPixel()); gfx::Rect new_bounds(bounds_in_pixel); if (IsRotationPortrait(rotation) != IsRotationPortrait(display.rotation())) { new_bounds.set_width(bounds_in_pixel.height()); new_bounds.set_height(bounds_in_pixel.width()); } display.set_rotation(rotation); display.SetScaleAndBounds(display.device_scale_factor(), new_bounds); display_list().UpdateDisplay(display); host_->SetRootTransform(GetRotationTransform() * GetUIScaleTransform()); } void TestScreen::SetUIScale(float ui_scale) { ui_scale_ = ui_scale; display::Display display(GetPrimaryDisplay()); gfx::Rect bounds_in_pixel(display.GetSizeInPixel()); gfx::Rect new_bounds = gfx::ToNearestRect( gfx::ScaleRect(gfx::RectF(bounds_in_pixel), 1.0f / ui_scale)); display.SetScaleAndBounds(display.device_scale_factor(), new_bounds); display_list().UpdateDisplay(display); host_->SetRootTransform(GetRotationTransform() * GetUIScaleTransform()); } void TestScreen::SetWorkAreaInsets(const gfx::Insets& insets) { display::Display display(GetPrimaryDisplay()); display.UpdateWorkAreaFromInsets(insets); display_list().UpdateDisplay(display); } gfx::Transform TestScreen::GetRotationTransform() const { gfx::Transform rotate; display::Display display(GetPrimaryDisplay()); switch (display.rotation()) { case display::Display::ROTATE_0: break; case display::Display::ROTATE_90: rotate.Translate(display.bounds().height(), 0); rotate.Rotate(90); break; case display::Display::ROTATE_270: rotate.Translate(0, display.bounds().width()); rotate.Rotate(270); break; case display::Display::ROTATE_180: rotate.Translate(display.bounds().width(), display.bounds().height()); rotate.Rotate(180); break; } return rotate; } gfx::Transform TestScreen::GetUIScaleTransform() const { gfx::Transform ui_scale; ui_scale.Scale(1.0f / ui_scale_, 1.0f / ui_scale_); return ui_scale; } void TestScreen::OnWindowBoundsChanged(Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) { DCHECK_EQ(host_->window(), window); display::Display display(GetPrimaryDisplay()); display.SetSize(gfx::ScaleToFlooredSize(new_bounds.size(), display.device_scale_factor())); display_list().UpdateDisplay(display); } void TestScreen::OnWindowDestroying(Window* window) { if (host_->window() == window) { host_->window()->RemoveObserver(this); host_ = NULL; } } gfx::Point TestScreen::GetCursorScreenPoint() { return Env::GetInstance()->last_mouse_location(); } bool TestScreen::IsWindowUnderCursor(gfx::NativeWindow window) { return GetWindowAtScreenPoint(GetCursorScreenPoint()) == window; } gfx::NativeWindow TestScreen::GetWindowAtScreenPoint(const gfx::Point& point) { if (!host_ || !host_->window()) return nullptr; return host_->window()->GetEventHandlerForPoint(point); } display::Display TestScreen::GetDisplayNearestWindow( gfx::NativeWindow window) const { return GetPrimaryDisplay(); } TestScreen::TestScreen(const gfx::Rect& screen_bounds, WindowTreeClient* window_tree_client) : host_(nullptr), ui_scale_(1.0f), window_tree_client_(window_tree_client) { static int64_t synthesized_display_id = 2000; display::Display display(synthesized_display_id++); display.SetScaleAndBounds(1.0f, screen_bounds); ProcessDisplayChanged(display, true /* is_primary */); } } // namespace aura
67a5292df3ad8d288619d5398a176c597cd57f2d
f9759b3118826bb4787fe8ace58307523763cdfb
/DAY3 J/main.cpp
398330979ef51bc09f773dc49a021ff340837b39
[]
no_license
Abraham-WH/2017ACMtraining
72eb3ec2d6d6760da22b671c05764db6bb57ed27
048ab6ae3b94b45b771208d2fbcbf16b47ec5c6d
refs/heads/master
2020-04-10T21:11:56.368966
2018-12-11T07:00:28
2018-12-11T07:00:28
161,290,523
0
0
null
null
null
null
GB18030
C++
false
false
1,173
cpp
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int n,k; int a[10000000]; int ans; void find(int kk,int l,int r);//kk,要求的第k大数 int read(); int read()//读写优化函数 { int tmp = 0; char x; while(1) { x = getchar(); if(x >= '0' && x<= '9') tmp = tmp * 10 + x - '0'; else break; } return tmp; } void find(int kk,int l,int r) { int mid = (l + r) / 2;//快排轴值 int key ; swap(a[mid],a[r]);//轴值放队尾 int i = l; int j = r - 1; while(i <= j)//开始两边处理,与轴值比较 { while(a[i] < a[r]) i++; while(a[j] > a[r]) j--; if(i <= j) swap(a[i++],a[j--]); } key = i; swap(a[i],a[r]);//换回轴值 if(key == n-kk) { ans = a[key]; return ;//找到 } if(l < j)find(kk,l,j);//递归,分治 if(r > i)find(kk,i+1,r); } int main() { int left,right; ans = 0; cin>>n>>k; left = 0; right = n - 1; for(int i = 0; i < n; i++) a[i] = read();//读入的优化 find(k,left,right); cout <<ans<< endl; return 0; }
0e1ae7bf34963412d42a8cec9b06278e18e6984d
2d9af107b5f83b1333feb094e71d3cde1387329e
/cpp/Robot/RobotCommonTest/RobotCommonTestCommon.h
cab5ac39da037eee06e9b69855eafbf26becd1ec
[]
no_license
VijayEluri/src
c068d84a011b129fb832c2a057cf71c7b0edcee7
9abd682df413091c99614867cd416d6c0fa1d072
refs/heads/master
2020-05-20T10:58:59.373647
2019-03-19T10:30:17
2019-03-19T10:30:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
810
h
#pragma once #include "stdafx.h" #include "CppUnitTest.h" #include "..\RobotCommon\Direction.h" #include "..\RobotCommon\Vector.h" #include <string> using std::wstring; using RobotCommon::Vector; using RobotCommon::Direction; using RobotCommon::DirectionUtils; namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { template<> static wstring ToString<Vector>(const Vector& v) { return v.ToString(); } } } } namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { template<> static wstring ToString<Direction>(const Direction& d) { return DirectionUtils::ToString(d); } } } }
ea35128c9453d1931bd9e52f9dbe2c4a500e134a
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp
c50a7d1d5c7b7b16241ffd23ab88f2b295a559a8
[ "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-only", "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
cool2528/miniblink49
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
7f646289d8074f098cf1244adc87b95e34ab87a8
refs/heads/master
2020-06-05T03:18:43.211372
2019-06-01T08:57:37
2019-06-01T08:59:56
192,294,645
2
0
Apache-2.0
2019-06-17T07:16:28
2019-06-17T07:16:27
null
UTF-8
C++
false
false
7,075
cpp
/* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek <[email protected]> * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h" #include "core/inspector/InjectedScriptManager.h" #include "bindings/core/v8/ScriptValue.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptHost.h" #include "core/inspector/InjectedScriptNative.h" #include "core/inspector/JSONParser.h" #include "platform/JSONValues.h" #include "public/platform/Platform.h" #include "public/platform/WebData.h" #include "wtf/PassOwnPtr.h" namespace blink { PassOwnPtrWillBeRawPtr<InjectedScriptManager> InjectedScriptManager::createForPage() { return adoptPtrWillBeNoop(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWindow)); } PassOwnPtrWillBeRawPtr<InjectedScriptManager> InjectedScriptManager::createForWorker() { return adoptPtrWillBeNoop(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWorkerGlobalScope)); } InjectedScriptManager::InjectedScriptManager(InspectedStateAccessCheck accessCheck) : m_nextInjectedScriptId(1) , m_injectedScriptHost(InjectedScriptHost::create()) , m_inspectedStateAccessCheck(accessCheck) , m_customObjectFormatterEnabled(false) { } InjectedScriptManager::~InjectedScriptManager() { } DEFINE_TRACE(InjectedScriptManager) { visitor->trace(m_injectedScriptHost); } void InjectedScriptManager::disconnect() { m_injectedScriptHost->disconnect(); m_injectedScriptHost.clear(); } InjectedScriptHost* InjectedScriptManager::injectedScriptHost() { return m_injectedScriptHost.get(); } InjectedScript InjectedScriptManager::injectedScriptForId(int id) { IdToInjectedScriptMap::iterator it = m_idToInjectedScript.find(id); if (it != m_idToInjectedScript.end()) return it->value; for (auto& state : m_scriptStateToId) { if (state.value == id) return injectedScriptFor(state.key.get()); } return InjectedScript(); } int InjectedScriptManager::injectedScriptIdFor(ScriptState* scriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(scriptState); if (it != m_scriptStateToId.end()) return it->value; int id = m_nextInjectedScriptId++; m_scriptStateToId.set(scriptState, id); return id; } InjectedScript InjectedScriptManager::injectedScriptForObjectId(const String& objectId) { RefPtr<JSONValue> parsedObjectId = parseJSON(objectId); if (parsedObjectId && parsedObjectId->type() == JSONValue::TypeObject) { long injectedScriptId = 0; bool success = parsedObjectId->asObject()->getNumber("injectedScriptId", &injectedScriptId); if (success) return m_idToInjectedScript.get(injectedScriptId); } return InjectedScript(); } void InjectedScriptManager::discardInjectedScripts() { m_idToInjectedScript.clear(); m_scriptStateToId.clear(); } void InjectedScriptManager::discardInjectedScriptFor(ScriptState* scriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(scriptState); if (it == m_scriptStateToId.end()) return; m_idToInjectedScript.remove(it->value); m_scriptStateToId.remove(it); } bool InjectedScriptManager::canAccessInspectedWorkerGlobalScope(ScriptState*) { return true; } void InjectedScriptManager::releaseObjectGroup(const String& objectGroup) { Vector<int> keys; keys.appendRange(m_idToInjectedScript.keys().begin(), m_idToInjectedScript.keys().end()); for (auto& key : keys) { IdToInjectedScriptMap::iterator s = m_idToInjectedScript.find(key); if (s != m_idToInjectedScript.end()) s->value.releaseObjectGroup(objectGroup); // m_idToInjectedScript may change here. } } void InjectedScriptManager::setCustomObjectFormatterEnabled(bool enabled) { m_customObjectFormatterEnabled = enabled; IdToInjectedScriptMap::iterator end = m_idToInjectedScript.end(); for (IdToInjectedScriptMap::iterator it = m_idToInjectedScript.begin(); it != end; ++it) { if (!it->value.isEmpty()) it->value.setCustomObjectFormatterEnabled(enabled); } } String InjectedScriptManager::injectedScriptSource() { const WebData& injectedScriptSourceResource = Platform::current()->loadResource("InjectedScriptSource.js"); return String(injectedScriptSourceResource.data(), injectedScriptSourceResource.size()); } InjectedScript InjectedScriptManager::injectedScriptFor(ScriptState* inspectedScriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(inspectedScriptState); if (it != m_scriptStateToId.end()) { IdToInjectedScriptMap::iterator it1 = m_idToInjectedScript.find(it->value); if (it1 != m_idToInjectedScript.end()) return it1->value; } if (!m_inspectedStateAccessCheck(inspectedScriptState)) return InjectedScript(); int id = injectedScriptIdFor(inspectedScriptState); RefPtr<InjectedScriptNative> injectedScriptNative = adoptRef(new InjectedScriptNative(inspectedScriptState->isolate())); ScriptValue injectedScriptValue = createInjectedScript(injectedScriptSource(), inspectedScriptState, id, injectedScriptNative.get()); InjectedScript result(injectedScriptValue, m_inspectedStateAccessCheck, injectedScriptNative.release()); if (m_customObjectFormatterEnabled) result.setCustomObjectFormatterEnabled(m_customObjectFormatterEnabled); m_idToInjectedScript.set(id, result); return result; } } // namespace blink
976858f831485da1095bc390973975c6564c221b
6fa3d87c4df47a15186a7141a80f4aa90c908fc9
/src/optimizer.cpp
18b9ee351cb3290cca707709f3a037e92b1f6e70
[ "MIT" ]
permissive
lorenzosquadrani/plasticity
4dc539c3a9513ea8cb3fa341349c2ee10f4f2df8
6ae648fe537ebbff8432ec04beb58e4acac5871e
refs/heads/main
2023-07-03T12:37:53.274114
2021-08-07T12:06:28
2021-08-07T12:06:28
367,437,263
0
1
NOASSERTION
2021-05-14T17:37:25
2021-05-14T17:37:25
null
UTF-8
C++
false
false
5,434
cpp
#include <optimizer.h> float update_args :: epsil = 1e-6f; update_args :: update_args () : m (), v (), type (-1), learning_rate (0.f), momentum (0.f), decay (0.f), B1 (0.f), B2 (0.f), rho (0.f) { } update_args :: update_args (const int & type, float learning_rate, float momentum, float decay, float B1, float B2, float rho) : m (), v (), type (type), learning_rate (learning_rate), momentum (momentum), decay (decay), B1 (B1), B2 (B2), rho (rho) { #ifdef DEBUG assert (type >= optimizer_t :: adam && type <= optimizer_t :: sgd); #endif } void update_args :: init_arrays (const int & rows, const int & cols) { this->m = Eigen :: MatrixXf :: Zero(rows, cols); this->v = Eigen :: MatrixXf :: Zero(rows, cols); } update_args & update_args :: operator = (const update_args & args) { this->type = args.type; this->learning_rate = args.learning_rate; this->momentum = args.momentum; this->decay = args.decay; this->B1 = args.B1; this->B2 = args.B2; this->rho = args.rho; this->m = args.m; return *this; } update_args :: update_args (const update_args & args) : type (args.type), learning_rate (args.learning_rate), momentum (args.momentum), decay (args.decay), B1 (args.B1), B2 (args.B2), rho (args.rho) { this->m = args.m; this->v = args.v; } void update_args :: update ( const int & iteration, Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update ) { if ( this->m.size() != weights.size() ) throw std :: runtime_error("Invalid number of weights found. Given " + std :: to_string(weights.size()) + ". Aspected " + std :: to_string(this->m.size())); switch ( this->type ) { case optimizer_t :: adam: adam_update(iteration, weights, weights_update); break; case optimizer_t :: momentum: momentum_update(weights, weights_update); break; case optimizer_t :: nesterov_momentum: nesterov_momentum_update(weights, weights_update); break; case optimizer_t :: adagrad: adagrad_update(weights, weights_update); break; case optimizer_t :: rmsprop: rmsprop_update(weights, weights_update); break; case optimizer_t :: adadelta: adadelta_update(weights, weights_update); break; case optimizer_t :: adamax: adamax_update(iteration, weights, weights_update); break; case optimizer_t :: sgd: sgd_update(weights, weights_update); break; } this->learning_rate *= 1.f / (this->decay * iteration + 1.f); this->learning_rate = this->learning_rate < 0.f ? 0.f : this->learning_rate; } void update_args :: adam_update (const int & iteration, Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { const float a_t = this->learning_rate * math :: sqrt(1.f - math :: pow(this->B2, iteration)) / (1.f - math :: pow(this->B1, iteration)); this->m = this->m * this->B1 + (1.f - this->B1) * weights_update; this->v = this->v * this->B2 + (1.f - this->B2) * weights_update.cwiseProduct(weights_update); weights = weights.array() - a_t * this->m.array() / (this->v.cwiseSqrt().array() + update_args :: epsil); } void update_args :: sgd_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { weights = weights - this->learning_rate * weights_update; } void update_args :: momentum_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { this->v = this->momentum * this->v - this->learning_rate * weights_update; weights = weights + this->v; } void update_args :: nesterov_momentum_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { this->v = this->momentum * this->v - this->learning_rate * weights_update; weights = weights + this->momentum * this->v - this->learning_rate * weights_update; } void update_args :: adagrad_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { this->v = weights_update.cwiseProduct(weights_update); weights = weights.array() - this->learning_rate * weights_update.array() / (this->v.cwiseSqrt().array() + update_args :: epsil); } void update_args :: rmsprop_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { this->v = this->rho * this->v + (1.f - this->rho) * weights_update.cwiseProduct(weights_update); weights = weights.array() - this->learning_rate * weights_update.array() / (this->v.cwiseSqrt().array() + update_args :: epsil); } void update_args :: adadelta_update (Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { this->v = this->rho * this->v + (1.f - this->rho) * weights_update.cwiseProduct(weights_update); Eigen :: MatrixXf update = weights_update.array() * ( this->m.cwiseSqrt().array() + update_args :: epsil) / (this->v.cwiseSqrt().array() + update_args :: epsil); weights = weights - this->learning_rate * update; this->m = this->rho * this->m + (1.f - this->rho) * update.cwiseProduct(update); } void update_args :: adamax_update (const int & iteration, Eigen :: MatrixXf & weights, const Eigen :: MatrixXf & weights_update) { const float a_t = this->learning_rate / (1.f - math :: pow(this->B1, iteration)); this->m = this->m * this->B1 + (1.f - this->B1) * weights_update; this->v = weights_update.cwiseAbs().cwiseMax(this->B2 * this->v); weights = weights.array() - a_t * this->m.array() / (this->v.array() + update_args :: epsil); }
ae4d02ba5691d85a325c7ebe1ac981959bdcf894
e1ecf96f19ffd3bda81bf1f614a9ebc9c91a454d
/p2KineticSculptureMotionCode.ino
94a9549bf1380dbcaa47145686eb47cf900469c8
[]
no_license
amsilldn/P2-Kinetic-Sculpture
9c31157f80eb3f4610a7a796ed6fcf5fbf990bfc
a2b3043c1f91ea14ac9e828c21362857835b093b
refs/heads/master
2020-04-04T20:39:33.998487
2018-11-05T19:37:42
2018-11-05T19:37:42
156,255,169
0
0
null
null
null
null
UTF-8
C++
false
false
7,789
ino
#include <Stepper.h> //number of steps the motor will take with one call const int num_steps = 200; // initialize the stepper library on pins 4-7 n 8-11 Stepper myStepper1(num_steps,4,5,6,7); Stepper myStepper2(num_steps,8,9,10,11); //distance sensor one const int trigPin1 = 2; const int echoPin1 = 3; //distance snesor 2 const int trigPin2 = 1; const int echoPin2 = 12; //stores the distance captured by each sensor //sensor 1 float distance1, duration1, distance2, duration2; void setup() { myStepper1.setSpeed(60); //left myStepper2.setSpeed(60); //right //sensor 1 - trig is output & echo is input pinMode(trigPin1, OUTPUT); pinMode(echoPin1, INPUT); //sensor 2 - trig is output & echo is input pinMode(trigPin2, OUTPUT); pinMode(echoPin2, INPUT); Serial.begin(9600); //begin serial communication } void loop() { //clear trig pin 1 digitalWrite(trigPin1, LOW); delayMicroseconds(2); //set trig pin 1 to high for 20 microseconds digitalWrite(trigPin1, HIGH); delayMicroseconds(20); digitalWrite(trigPin1, LOW); //read the echo pin 1, return sound wave travel time in microseconds duration1 = pulseIn(echoPin1, HIGH); //calculate distance //Math for finding distance comes from //https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/ distance1 = (duration1*0.0343)/2; //print distance to serial monitor Serial.print("Distance 1: "); Serial.println(distance1); //if distance sensor 1 returns any distance under 1 meter //have the gears go through their full rotation //didn't feel like doing the math to have it rotate to a certain degree/angle //fuck math if (1.00 < distance1 && distance1 < 100.00) { //open gear one to reveal first image myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal second image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal third image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal fourth image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two to reset myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); delay(500); } //clear trig pin 2 digitalWrite(trigPin2, LOW); delayMicroseconds(2); //set trig pin 2 to high for 20 microseconds digitalWrite(trigPin2, HIGH); delayMicroseconds(20); digitalWrite(trigPin2, LOW); //read the echo pin 2, return sound wave travel time in microseconds duration2 = pulseIn(echoPin2, HIGH); //calculate distance //Math for finding distance comes from //https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/ distance2 = (duration2*0.0343)/2; //print distance to serial monitor Serial.print("Distance 2: "); Serial.println(distance2); //if distance sensor 1 returns any distance under 1 meter //have the gears go through their full rotation //didn't feel like doing the math to have it rotate to a certain degree/angle //fuck math if (1.00 < distance2 && distance2 < 100.00) { //open gear one to reveal first image myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal second image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal third image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two and open gear one to reveal fourth image myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); myStepper1.step(num_steps); delay(5000); //close gear two to reset myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); myStepper2.step(num_steps); delay(500); } delay(500); }
6cb09dc049464c5167c8cde7da3ede6e1542ec9b
2124d0b0d00c3038924f5d2ad3fe14b35a1b8644
/source/GamosCore/GamosData/Data/src/GmDataInitialGammaEquivalentDose.cc
fbb2db46418df22c92223f5317f9809a4aca4ca6
[]
no_license
arceciemat/GAMOS
2f3059e8b0992e217aaf98b8591ef725ad654763
7db8bd6d1846733387b6cc946945f0821567662b
refs/heads/master
2023-07-08T13:31:01.021905
2023-06-26T10:57:43
2023-06-26T10:57:43
21,818,258
1
0
null
null
null
null
UTF-8
C++
false
false
927
cc
#include "GmDataInitialGammaEquivalentDose.hh" #include "GamosCore/GamosUtils/include/GmGenUtils.hh" #include "G4Step.hh" #include "G4Track.hh" #include "G4Event.hh" //---------------------------------------------------------------- GmDataInitialGammaEquivalentDose::GmDataInitialGammaEquivalentDose() { bInitial = true; theExcludedTypes.insert(DTTrack); theExcludedTypes.insert(DTSeco); theExcludedTypes.insert(DTEvent); theFlux2Dose = ReadEnergyBinsForGammas(); SetEquivDoseType("GmDataInitialGammaEquivalentDose"); } //---------------------------------------------------------------- GmDataInitialGammaEquivalentDose::~GmDataInitialGammaEquivalentDose() { } //---------------------------------------------------------------- G4double GmDataInitialGammaEquivalentDose::GetValueFromStep( const G4Step* aStep, G4int ) { return DoseFromEnergy( aStep->GetPreStepPoint()->GetKineticEnergy(), aStep ); }
a3c9f9539cba4e7bdaf70c17f4c06ce47ecfc0e5
02fec111191ecede92d844422125ac8482171bde
/Contests/77edu/d.cpp
90203b0441ae9d2296e060c0f0e89a4de50cb2c6
[]
no_license
Lucas3H/Maratona
475825b249659e376a1f63a6b3b6a1e15c0d4287
97a2e2a91fb60243124fc2ffb4193e1b72924c3c
refs/heads/master
2020-11-24T18:35:24.456960
2020-11-06T14:00:56
2020-11-06T14:00:56
228,292,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,892
cpp
#include<bits/stdc++.h> using namespace std; #define fr(i, n) for(ll i = 0; i < n; i++) #define frr(i, n) for(ll i = 1; i <= n; i++) #define frm(i, n) for(ll i = n-1; i >= 0; i--) #define pb push_back #define f first #define s second typedef long long ll; typedef pair<ll,ll> pii; typedef pair<ll, ll> ponto; typedef vector<vector<ll>> matrix; #define mem(v, k) memset(v, k, sizeof(v)); #define db cout << "Debug" << endl; #define mp make_pair #define pq priority_queue #define mx(a, b) a = max(a, b); #define mod(a, b) a = a%b; #define MAXN 200010 #define MOD 1000000007 ll n, m, k, t; ll a[MAXN]; ll pos_disarm[MAXN]; ll pos_trap[MAXN]; ll danger[MAXN]; set<ll> disarm[MAXN]; set<ll> trap[MAXN]; bool is_possible(ll last_soldier){ ll min_power = a[last_soldier]; ll tempo = n+1; ll maior_dist = 0; ll last_pos = 0; frr(i, n){ for(auto x: trap[i]){ if(danger[x] > min_power && maior_dist < pos_disarm[x] ){ maior_dist = max(maior_dist, pos_disarm[x]); //cout << x << endl; } } //cout << i << " " << maior_dist << endl; if(maior_dist == i) { tempo+=2*(maior_dist - last_pos); last_pos = i; } if(maior_dist < i) last_pos = i; } //cout << maior_dist << endl; //cout << last_soldier << " " << tempo << " "; if(tempo > t) return 0; else return 1; } int main(){ ios::sync_with_stdio(false); cin >> m >> n >> k >> t; frr(i, m) cin >> a[i]; sort(a+1, a+m+1); frr(i, k){ ll l, r, d; cin >> l >> r >> d; trap[l].insert(i); disarm[r].insert(i); pos_trap[i] = l; pos_disarm[i] = r; danger[i] = d; } ll l = 1, r = m, mid; while(l < r-1){ mid = (l+r)/2; if(!is_possible(mid)) l = mid; else r = mid; } //cout << is_possible(3) << endl; //frr(i, m) cout << is_possible(i) << endl; if(is_possible(l)) cout << m - l + 1 << endl; else if(!is_possible(r)) cout << 0 << endl; else cout << m - r + 1 << endl; }
9f9b33764a32acd729ff941b1f1285edadc4eab4
5f67dac5b41e90a96df5156ff40ab0073431d48a
/My Procedure/c++/36 指针数组.cpp
42637f2b578a41a8d2c65351b5e96d85c5979845
[]
no_license
HGD-CodeMe/c_or_cpp
9e98db76a3be9e18943fcdbc7a8c4ff8e9c3518f
84fb1fd1f0dfb5cc70ff97046d2ed130e4ac03a6
refs/heads/master
2021-01-21T17:06:29.646363
2017-11-16T14:01:51
2017-11-16T14:01:51
91,930,692
0
0
null
null
null
null
GB18030
C++
false
false
522
cpp
#include<iostream>//此题是指针数组的应用 这个定义字符数组的方式十分有用 有几个应该注意的地方 如下 using namespace std; main() { int i; char *p[]=//此处注意中括号中不可以带参数值 而且还要带等号 { "January", "Fbruary", "March", "April", "June", "May", "July", "August", "September", "October", "November", "December" }; //return (i<1||i>7)?p[0]:p[i]; 此处主要是为了将这个当做调用函数 cin>>i; cout<<p[i-1]<<endl; }
d8dc7b156da11cf259de21b2f7589bd735c22842
322586fd62facf9563df4e2ba99d2cc10ee74c6b
/73/src_1_22.cpp
1c7f87d05c3f3acd91c804a56da728cef8a49249
[]
no_license
WavesUR/leetcode-study
82fe60ccb65b243a82731951257ad36186bd5784
0564b36237dbb50087bc7dd51932df1f5eb37e83
refs/heads/master
2021-01-13T12:19:03.696019
2018-12-03T05:19:12
2018-12-03T05:19:12
77,957,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,955
cpp
#include <iostream> #include <cstring> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <cmath> #include <cctype> #include <climits> using namespace std; class Solution { public: void setZeroes(vector<vector<int> >& matrix) { bool first_row_zero = false; bool first_col_zero = false; for(int i = 0; i < matrix.size(); i++){ if(matrix[i][0] == 0){ first_col_zero = true; break; } } for(int i = 0; i < matrix[0].size(); i++){ if(matrix[0][i] == 0){ first_row_zero = true; break; } } for(int i = 0; i < matrix.size();i++){ for(int j = 0; j < matrix[0].size();j++){ if(matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; break; } } } for(int i = 1; i < matrix.size(); i++){ if(matrix[i][0] == 0){ for(int j = 1; j < matrix[0].size();j++){ matrix[i][j] = 0; } } } for(int i = 1; i < matrix[0].size(); i++){ if(matrix[0][i] == 0){ for(int j = 1; j < matrix.size();j++){ matrix[j][i] = 0; } } } if(first_row_zero){ for(int j = 0; j < matrix[0].size();j++){ matrix[0][j] = 0; } } if(first_col_zero){ for(int j = 0; j < matrix.size();j++){ matrix[j][0] = 0; } } } }; int main(){ vector<vector<int> > matrix; matrix = {{1,0,2},{3,4,6},{2,3,4}}; Solution solution; solution.setZeroes(matrix); for(int i = 0; i < matrix.size();i++){ for(int j = 0; j < matrix[0].size();j++){ cout << matrix[i][j] << " "; } cout << endl; } return 0; }
2bb076154163cc755690fb0d8a138732ba8d629a
3dd33e0cced471c94cd1ab7e6f30890a16cd6d15
/PKO ProxyServer/Client/PacketHandler/EndPlayHandler.h
f1b5dc2784dd308f03f9b209cdd18cf628b6c210
[]
no_license
lanochan/ProxyServer
4cee76cb2dc4b7bd2b219a0db620f0a074b258ea
47cef011cf17deb5688a724b2ef7b1480f4d763b
refs/heads/main
2023-04-24T15:58:27.331716
2021-05-19T20:49:56
2021-05-19T20:49:56
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
959
h
#pragma once #include "../../Main/IPacketHandler.h" namespace PKO { // Обработчик пакета выхода на выбор персонажа // C -> S class CEndPlayHandler : public IPacketHandler { public: // Конструктор CEndPlayHandler(); // Деструктор ~CEndPlayHandler(); // Получить ID пакета virtual unsigned short int getId() const; // Прочитать пакет virtual void read(CBinaryReader& Reader, CPlayer& Player); // Обработать пакет virtual bool handle(CPlayer& Player); // Действие после отправки пакета virtual void after_send(CPlayer& Player); // Сбросить обработчик virtual void reset(); private: // Запрещаем копирование CEndPlayHandler(const CEndPlayHandler&) = delete; CEndPlayHandler& operator=(const CEndPlayHandler&) = delete; }; }
93575ff384dfa86c81d9fd72d5fd864f986f2ce7
b85d1556bdee32ca69bb54dfa688538a309b5ad9
/FrameworkLib/ScriptInterpreter.h
8b417f5d420bb8494b3a827538aa0518f6249b5d
[ "Zlib" ]
permissive
DashW/Ingenuity
e32c62e90005d43d304e3f5459c076ae167c039b
f7944a9e8063beaa3dda31e8372d18b4147782e2
refs/heads/master
2021-05-04T11:53:42.817688
2017-01-29T20:40:52
2017-01-29T20:40:52
20,335,794
0
0
null
null
null
null
UTF-8
C++
false
false
4,908
h
#pragma once #include <stdarg.h> #include "ScriptLogger.h" #include "ScriptParam.h" #include <vector> namespace Ingenuity { class ScriptInterpreter; struct ScriptCallbackMeta { const char * name; //void(*call)(ScriptInterpreter*); const char * help; ScriptCallbackMeta(const char * name, const char * help = "") : name(name), help(help) {} }; //struct ScriptModule //{ // const char * name; // const char * help; // // ScriptModule(const char * name, const char * help) // : name(name), help(help) {} //}; class RealtimeApp; class ScriptInterpreter { static const int MAX_PARAMS = 20; int dependencies; int numParams; ScriptParam params[MAX_PARAMS]; ScriptLogger logger; bool inError; bool initialised; protected: RealtimeApp * app; ScriptInterpreter(RealtimeApp * app) : dependencies(0), numParams(0), inError(false), initialised(false), app(app) {} virtual void FunctionCalled(const char * functionName) = 0; inline void SetParam(int index, ScriptParam param) { if(index > -1 && index < numParams) { params[index] = param; } } inline ScriptParam GetParam(int index) { if(index > -1 && index < numParams) return params[index]; return ScriptParam(); } inline void SetNumParams(int numParams) { if(numParams > MAX_PARAMS) { ThrowError("Function cannot accept more than 20 parameters!"); } else if(numParams > -1) { this->numParams = numParams; } } void SetError(bool inError) { this->inError = inError; } void SetInitialised() { initialised = true; } public: typedef void(*ScriptCallback)(ScriptInterpreter*); std::vector<ScriptCallbackMeta> callbackMeta; //std::vector<ScriptModule> modules; // I'm not quite sure where I'm going with this... virtual ~ScriptInterpreter() {} enum Operator { Call, Add, Sub, Mul, Div, Pow, Neg, Equals, ToString, IndexGet, IndexSet, Length }; enum SpecialPtrType { TypeVector4, TypeMatrix4, TypeFloatArray }; virtual bool LoadScript(const char * data, unsigned dataSize, const char * filename, const char * moduleName = 0) = 0; virtual void ThrowError(const char * error) = 0; virtual void RunCommand(const char * command) = 0; // This and LoadScript now do the same thing, should be merged? //virtual void ReloadScript(const wchar_t * filename) = 0; // Suggestion: The ScriptInterpreter shouldn't care about its 'error state', // and certainly shouldn't force the caller to reload the script to recover. // Perhaps this could be removed from the interface and handled in Ingenuity Main? bool IsInError() { return inError; } void ResetError() { inError = false; } bool IsInitialised() { return initialised && dependencies == 0; } inline void PushParam(ScriptParam param) { if(numParams < MAX_PARAMS) { params[numParams] = param; ++numParams; } } inline ScriptParam PopParam() { if(numParams > 0) { --numParams; ScriptParam result = params[numParams]; params[numParams] = ScriptParam(); return result; } return ScriptParam(); } inline int NumParams() { return numParams; } inline void ClearParams() { while(numParams > 0) params[--numParams] = ScriptParam(); } virtual bool HasFunction(const char * functionName) = 0; //virtual ScriptParam GetGlobal(const char * globalName) = 0; void CallFunction(const char* functionName /*, ...*/) { if(!inError) { FunctionCalled(functionName); } } virtual void CallFunction(ScriptParam function) = 0; inline ScriptLogger & GetLogger() { return logger; } inline RealtimeApp * GetApp() { return app; } virtual unsigned RegisterPointerType(unsigned structSize = 0) = 0; virtual void RegisterCallback(const char * name, ScriptCallback callback) = 0; virtual void RegisterCallback(const char * name, ScriptCallback callback, const char * help) { for(unsigned i = 0; i < callbackMeta.size(); ++i) { if(strcmp(name, callbackMeta[i].name) == 0) { std::string error = "Module function registered twice: "; error += name; ThrowError(error.c_str()); break; } } callbackMeta.push_back(ScriptCallbackMeta(name, help)); RegisterCallback(name, callback); } //virtual void RegisterModule(ScriptModule & module) = 0; virtual void RegisterMathObjects() = 0; virtual void RegisterMethod(unsigned ptrType, const char * name, ScriptCallback callback) = 0; virtual void RegisterOperator(unsigned ptrType, Operator op, ScriptCallback callback) = 0; virtual ScriptParam CreateMap() = 0; virtual void SetMapNext(ScriptParam mapref, ScriptParam & key, ScriptParam & value) = 0; virtual bool GetMapNext(ScriptParam mapref, ScriptParam & key, ScriptParam & value) = 0; virtual unsigned GetMapLength(ScriptParam mapref) = 0; virtual unsigned GetSpecialPtrType(SpecialPtrType type) = 0; void incDependencies() { dependencies++; } void decDependencies() { dependencies--; } }; } // namespace Ingenuity
dd66f65a5aa92224a615700306e94a53d51c18f6
b8bbb54a43d0eb883716eed4f8daecf34d983ae8
/TableModel.h
08f589a8659fda8cdda50a256e81bf855db36fcf
[]
no_license
IulyN1/ShopAppGUI
8a6452e648f733490ac30c3c3e88e38b7bfe7ded
4913706fb6c19ce47e45f6cc593187142236aff1
refs/heads/master
2023-05-09T10:17:36.378205
2021-06-04T15:25:39
2021-06-04T15:25:39
373,884,080
1
0
null
null
null
null
UTF-8
C++
false
false
2,668
h
#pragma once #include "Cos.h" #include <QtWidgets/qtableview.h> #include "Observer.h" #include "ProdusServ.h" class MyTableModel : public QAbstractTableModel, public Observer { private: Cos& cos; public: // Constructorul modelului de tabel pentru cos // cos - referinta la obiect Cos MyTableModel(Cos& cos) :cos{ cos } { cos.addObserver(this); } // Functie suprascrisa de update void update() override { emit layoutChanged(); } // Functie suprascrisa care returneaza numarul de randuri // parent - QModelIndex int rowCount(const QModelIndex& parent = QModelIndex()) const override { return cos.get_all().size(); } // Functie suprascrisa care returneaza numarul de coloane // parent - QModelIndex int columnCount(const QModelIndex& parent = QModelIndex()) const override { return 4; } // Functie suprascrisa care prelucreaza datele tabelului in functie de rol // index - QModelIndex // role - intreg QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; // Functie care schimba header-ul tabelului // section - intreg // orientation - QOrientation // role - intreg QVariant headerData(int section, Qt::Orientation orientation, int role) const; }; class MyAdvancedTableModel : public QAbstractTableModel{ private: vector<Produs> produse; vector<int> rows; public: // Constructorul modelului de tabel pentru produse // produse - vector de obiecte Produs MyAdvancedTableModel(vector<Produs> produse) :produse{ produse } { } // Functie suprascrisa care returneaza numarul de randuri // parent - QModelIndex int rowCount(const QModelIndex& parent = QModelIndex()) const override { return produse.size(); } // Functie suprascrisa care returneaza numarul de coloane // parent - QModelIndex int columnCount(const QModelIndex& parent = QModelIndex()) const override { return 4; } // Functie care adauga un rand care urmeaza sa fie colorat la cautare intr-o lista // row - intreg void addRow(int row) { rows.push_back(row); } // Functie care goleste lista de randuri colorate void reset_rows() { rows.clear(); } // Functie suprascrisa care prelucreaza datele tabelului in functie de rol // index - QModelIndex // role - intreg QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; // Functie care schimba header-ul tabelului // section - intreg // orientation - QOrientation // role - intreg QVariant headerData(int section, Qt::Orientation orientation, int role) const; // Functie care seteaza produsele in model cand acesta s-a modificat // produse - vector de obiecte Produs void setProducts(const vector<Produs>& produse); };
4b81767038329affa72e029ec670fed61db85e66
7bb34b9837b6304ceac6ab45ce482b570526ed3c
/external/webkit/Source/WebCore/platform/gtk/GeolocationServiceGtk.h
46249ed8fdb1d96db56f77ee1735ff4d174034de
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
ghsecuritylab/android_platform_sony_nicki
7533bca5c13d32a8d2a42696344cc10249bd2fd8
526381be7808e5202d7865aa10303cb5d249388a
refs/heads/master
2021-02-28T20:27:31.390188
2013-10-15T07:57:51
2013-10-15T07:57:51
245,730,217
0
0
Apache-2.0
2020-03-08T00:59:27
2020-03-08T00:59:26
null
UTF-8
C++
false
false
2,498
h
/* * Copyright (C) 2008 Holger Hans Peter Freyther * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef GeolocationServiceGtk_h #define GeolocationServiceGtk_h #if ENABLE(GEOLOCATION) #include "GeolocationService.h" #include "Geoposition.h" #include "PositionError.h" #include "RefPtr.h" #include <geoclue/geoclue-master.h> #include <geoclue/geoclue-position.h> namespace WebCore { class GeolocationServiceGtk : public GeolocationService { public: static GeolocationService* create(GeolocationServiceClient*); ~GeolocationServiceGtk(); virtual bool startUpdating(PositionOptions*); virtual void stopUpdating(); virtual void suspend(); virtual void resume(); Geoposition* lastPosition() const; PositionError* lastError() const; private: GeolocationServiceGtk(GeolocationServiceClient*); void setError(PositionError::ErrorCode, const char* message); void updatePosition(); static void position_changed(GeocluePosition*, GeocluePositionFields, int, double, double, double, GeoclueAccuracy*, GeolocationServiceGtk*); static void getPositionCallback(GeocluePosition*, GeocluePositionFields, int, double, double, double, GeoclueAccuracy*, GError*, GeolocationServiceGtk*); private: RefPtr<Geoposition> m_lastPosition; RefPtr<PositionError> m_lastError; // state objects GeoclueMasterClient* m_geoclueClient; GeocluePosition* m_geocluePosition; // Error and Position state double m_latitude; double m_longitude; double m_altitude; double m_accuracy; double m_altitudeAccuracy; int m_timestamp; }; } #endif // ENABLE(GEOLOCATION) #endif
c9d65348a89e8889e88d3773b6b3d2b37abfa911
8638a2efe2168eaa536bd89ca5f6b87927d17118
/practice/dp/knapsacksimple.cpp
c7dbe2637f5a9120f80934242ab04914f356c8ee
[]
no_license
Simply-divine/Competitive
5c5e6418ddaceb8fae3c643a2e120b23a256b67c
0a7e720322a57fd95cff0d796640ac69a6f45cdc
refs/heads/master
2022-12-26T21:32:04.483818
2020-04-18T15:52:40
2020-04-18T15:52:40
256,789,554
1
1
null
2020-10-01T06:37:57
2020-04-18T15:37:30
C++
UTF-8
C++
false
false
611
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #define F first #define S second #define PB push_back #define MP make_pair #define REP(i,a,b) for(int i=a;i<=b;i++) #define SQ(a) (a)*(a) #define DEBUG printf("hello\n") #define nl "\n" #define INF std::numeric_limits<int>::max() using namespace std; using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; ll mod=1000000009; int main() { ios_base::sync_with_stdio(false); cin.tie(0); return 0; }
3042a693758e970b8b54bcc86e1757744418dac8
50acc31c58b4711f5acfaaeb3278473a77a8e94f
/gis/GIS/GisImageLoader.cpp
dd8d41fcb80bb9a99275a24cdcecf1350399a1e3
[]
no_license
MAPSWorks/opengl-1
c3ca7b1c0169f7c29a05cbca76c40b5989c4fe06
c137ce7d49542d0872698cd8283d0a12c52424e8
refs/heads/master
2020-07-10T17:51:25.309201
2019-01-03T14:49:46
2019-01-03T14:49:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include "GisImageLoader.h" namespace GIS { GisImage* GisImageLoader::load(const char* fileName) { GisImage* pImage = 0; return pImage; } bool GisImageLoader::loadImage(const char* fileName, GIS::GisImage& image) { return true; } RgbBuffer* GisImageLoader::loadRgb_256X256(const char* fileName) { RgbBuffer* pBufer = 0; return pBufer; } RgbaBuffer* GisImageLoader::loadRgba_256X256(const char* fileName) { RgbaBuffer* pBufer = 0; return pBufer; } bool GisImageLoader::loadImageToRgb(const char* fileName, GisImage& image) { int width = 0; int height = 0; int channel = 0; return true; } }
e41045e677a64a39c854725b67588af9c38634f8
4d49450b3c7a0daf35022012ec7906ca556dd9e8
/lfa/ckyAlgorithm.cpp
e7f0ee89d70b389062c52ff26fec8e8cc87adfcd
[]
no_license
rebecadiaconu/fmi
3d3c7d977b8f61ee02a52b81c0cdc7ae0ccd31ae
1ccee33441f6a1843bfe599eec6219b37c533c95
refs/heads/master
2023-04-14T08:39:11.996296
2021-04-22T08:49:55
2021-04-22T08:49:55
238,420,720
1
0
null
null
null
null
UTF-8
C++
false
false
3,186
cpp
#include<iostream> #include<cstring> #include<string> #include <fstream> #include<iomanip> using namespace std; #define dim 200 typedef struct{ string T; string s[dim]; int nrCuv; }cyk; cyk v[dim]; string concat( string a, string b) { int i; string aux=a; for(i=0; i<b.length(); i++) if(aux.find(b[i]) > aux.length()) aux+=b[i]; return (aux); } void gram(string tranz, int n) { int i, nr = 0, poz; poz=tranz.find("->"); v[n].T = tranz[0]; tranz = tranz.substr(poz+2, tranz.length()); while(tranz.length()) { i=tranz.find("|"); if(i>tranz.length()) { v[n].s[nr++] = tranz; tranz=""; } else { v[n].s[nr++] = tranz.substr(0,i); tranz=tranz.substr(i+1,tranz.length()); } } v[n].nrCuv = nr; } string prod(string prod, int nrtranz) { int i,k; string aux=""; for(i=0; i<nrtranz; i++) { k=0; while(v[i].s[k] != "" && k<v[i].nrCuv) { if(prod==v[i].s[k]) { aux=concat(aux, v[i].T); } k++; } } return (aux); } string combina(string a, string b, int nrtranz) // BA * AB = {BA, BB, AA, BB} { int i,j; string sir, rez=""; for(i=0; i<a.length(); i++) for(j=0; j<b.length(); j++) { sir=""; sir=sir+a[i]+b[j]; rez=rez+ prod(sir, nrtranz); } return (rez); } int main() { int i, j, l, k, nrtranz; string tranz, cuv, s, start, aux; ifstream f("cyk1.txt"); ofstream g("lfa1.txt"); f>>start; f>>nrtranz; for(i=0; i<nrtranz; i++) { f>>tranz; gram(tranz, i); } f>>cuv; string mat[dim][dim]; f >> cuv; for(i=0;i<cuv.length();i++) //Assigns values to principal diagonal of matrix { s=""; aux = ""; aux += cuv[i]; for(j=0; j<nrtranz; j++) { k=0; while(k < v[j].nrCuv){ if(v[j].s[k] == aux) { s = concat(s, v[j].T); } k++; } } mat[i][i] = s; } for(k=1; k<cuv.length(); k++) //Assigns values to upper half of the matrix { for(j=k;j<cuv.length(); j++) { s=""; for(l=j-k;l<j;l++) { aux = combina(mat[j-k][l], mat[l+1][j], nrtranz); s = concat(s, aux); } mat[j-k][j] = s; } } for(i=0; i<cuv.length(); i++) { k=0; l = cuv.length()-i-1; for(j=l; j<cuv.length(); j++) { g<<setw(5)<<mat[k++][j]<<" "; } g<<endl; } for(i=0; i<start.length(); i++) if(mat[0][cuv.length()-1].find(start[i]) <= mat[0][cuv.length()-1].length()) //Checks if last element of first row contains a Start variable { g<<"Cuvantul poate fi generat. \n"; return 0; } else g<<"Cuvantul nu poate fi generat. \n"; return 0; }
4dfb27aaa15ea7e139f2e5b4fe3417b0cc07a5c3
1cc570030a86cd38ef3455bbf9243014f72776bd
/planning/semi_trailer_truck_collision_checker.h
b865f5892f5dae6c8e7e2c699e0299381c7a4d7a
[]
no_license
tradye/CIDItrucksim
005d3d37bb41c12f5a9eb44b3ae8c3ca8be8fcbd
7047c178c618f7f4eced2f3379556fc70ef53591
refs/heads/master
2020-03-09T23:24:51.295437
2018-05-14T14:51:41
2018-05-14T14:51:41
129,057,538
1
0
null
2018-05-14T14:51:42
2018-04-11T08:04:28
Matlab
UTF-8
C++
false
false
2,307
h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * Copyright 2018 CiDi **/ /** * @file **/ #ifndef MODULES_PLANNING_CONSTRAINT_CHECKER_SEMI_TRAILER_TRUCK_COLLISION_CHECKER_H_ #define MODULES_PLANNING_CONSTRAINT_CHECKER_SEMI_TRAILER_TRUCK_COLLISION_CHECKER_H_ #include <array> #include <vector> #include "modules/common/math/box2d.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" namespace apollo { namespace planning { class SemiTrailerTruckCollisionChecker { public: explicit SemiTrailerTruckCollisionChecker( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<common::PathPoint>& discretized_reference_line), ; bool InCollision(const DiscretizedTrajectory& discretized_trajectory); private: void BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<common::PathPoint>& discretized_reference_line); bool IsEgoVehicleInLane(const double ego_vehicle_d); bool ShouldIgnore( const Obstacle* obstacle, const double ego_vehicle_s, const std::vector<apollo::common::PathPoint>& discretized_reference_line); std::vector<std::vector<common::math::Box2d>> predicted_bounding_rectangles_; }; } // namespace planning } // namespace apollo #endif // MODULES_PLANNING_CONSTRAINT_CHECKER_COLLISION_CHECKER_H_
5f653229eb95c1ecb7386f267f1e7c212757993c
a309d6ea67b7caf7177bf34ccc064f46bfaad7b5
/ServiceManager/ServiceProcessConfig.cpp
7ea92df1b295e0572bdd80273bf2fa9aea7ee4cf
[ "MIT" ]
permissive
fengjixuchui/JAV-AV-Engine
a968ecd18ad4954e3668030f92e5680d93cd0969
c258c1bb283d2cccc358dab5d3a7bacd4fc35790
refs/heads/master
2020-04-30T16:08:46.699929
2018-08-25T09:28:44
2018-08-25T09:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,484
cpp
#include "ServiceProcessConfig.h" #include "BaseObject.h" ServiceProcessConfig::ServiceProcessConfig( __in_opt TCHAR * _strMachineName, __in_opt TCHAR * _strDatabaseName, __in DWORD _dwDesiredAccessSCM, __in TCHAR * _strServiceName, __in_opt TCHAR * _strDisplayName, __in DWORD _dwDesiredAccessService, __in DWORD _dwServiceType, __in DWORD _dwStartType, __in DWORD _dwErrorControl, __in_opt TCHAR * _strBinaryPathName, __in_opt TCHAR * _strLoadOrderGroup, __in_opt TCHAR * _strDependencies, __in_opt TCHAR * _strServiceStartName, __in_opt TCHAR * _strPassword) { strMachineName = _strMachineName; strDatabaseName =_strDatabaseName; dwDesiredAccessSCM=_dwDesiredAccessSCM; strServiceName = _strServiceName; strDisplayName = _strDisplayName; dwDesiredAccessService =_dwDesiredAccessService; dwServiceType=_dwServiceType; dwStartType=_dwStartType; dwErrorControl=_dwErrorControl; strBinaryPathName=_strBinaryPathName; strLoadOrderGroup=_strLoadOrderGroup; strDependencies=_strDependencies; strServiceStartName=_strServiceStartName; strPassword=_strPassword; } ServiceProcessConfig::~ServiceProcessConfig() { if ( strPassword != NULL ) delete strPassword; if ( strServiceStartName != NULL ) delete strServiceStartName; if ( strDependencies != NULL ) delete strDependencies ; if ( strLoadOrderGroup != NULL) delete strLoadOrderGroup ; if ( strBinaryPathName != NULL ) delete strBinaryPathName ; if ( strDisplayName != NULL) delete strDisplayName ; if ( strServiceName != NULL) delete strServiceName ; if ( strDatabaseName != NULL) delete strDatabaseName ; if ( strMachineName != NULL) delete strMachineName ; } string ServiceProcessConfig::LpwstrToString(LPWSTR lpwstr) { char str[256]; wcstombs(str,lpwstr,256); char* p_char=(char*)(lpwstr); string resultStr=(string)(str); return resultStr; } void ServiceProcessConfig::StringToLpwstr(string str, LPWSTR &dest) { mbstowcs(dest,str.c_str(),str.size()); dest[str.size()] = L'\0'; if(*dest==0) dest=NULL; //dest=NULL; return; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// const TCHAR * ServiceProcessConfig::getMachineName() { return strMachineName; } void ServiceProcessConfig::SetMachineName(const TCHAR * strArg) { if (strArg == NULL) { if (strMachineName == NULL) return ; else { delete strMachineName ; strMachineName = NULL ; } }else { if ( strMachineName != NULL ) { delete strMachineName ; } UINT uSize = lstrlen(strArg) +1 ; strMachineName = new TCHAR [uSize]; memcpy (strMachineName ,strArg ,uSize *sizeof(TCHAR)); } } const TCHAR * ServiceProcessConfig::getDatabaseName() { return strDatabaseName; } void ServiceProcessConfig::SetDatabaseName(const TCHAR *strArg) { if (strArg == NULL) { if (strDatabaseName == NULL) return ; else { delete strDatabaseName ; strDatabaseName = NULL ; } }else { if ( strDatabaseName != NULL ) { delete strDatabaseName ; } UINT uSize = lstrlen(strArg) +1 ; strDatabaseName = new TCHAR [uSize]; memcpy (strDatabaseName ,strArg ,uSize *sizeof(TCHAR)); } } DWORD ServiceProcessConfig::getDesiredAccessSCM() { return dwDesiredAccessSCM ; } void ServiceProcessConfig::SetDesiredAccessSCM(DWORD dwArg) { dwDesiredAccessSCM = dwArg ; } const TCHAR * ServiceProcessConfig::getServiceName() { return strServiceName; } void ServiceProcessConfig::SetServiceName(const TCHAR *strArg) { if (strArg == NULL) { if (strServiceName == NULL) return ; else { delete strServiceName ; strServiceName = NULL ; } }else { if ( strServiceName != NULL ) { delete strServiceName ; } UINT uSize = lstrlen(strArg) +1 ; strServiceName = new TCHAR [uSize]; memcpy (strServiceName ,strArg ,uSize *sizeof(TCHAR)); } } const TCHAR * ServiceProcessConfig::getDisplayName() { return strDisplayName; } void ServiceProcessConfig::SetDisplayName(const TCHAR * strArg) { if (strArg == NULL) { if (strDisplayName == NULL) return ; else { delete strDisplayName ; strDisplayName = NULL ; } }else { if ( strDisplayName != NULL ) { delete strDisplayName ; } UINT uSize = lstrlen(strArg) +1 ; strDisplayName = new TCHAR [uSize]; memcpy (strDisplayName ,strArg ,uSize *sizeof(TCHAR)); } } DWORD ServiceProcessConfig::getDesiredAccessService() { return dwDesiredAccessService ; } void ServiceProcessConfig::SetDesiredAccessService(DWORD dwArg) { dwDesiredAccessService = dwArg ; } DWORD ServiceProcessConfig::getServiceType() { return dwServiceType ; } void ServiceProcessConfig::SetServiceType(DWORD dwArg) { dwServiceType = dwArg ; } DWORD ServiceProcessConfig::getStartType() { return dwStartType ; } void ServiceProcessConfig::SetStartType(DWORD dwArg) { dwStartType = dwArg ; } DWORD ServiceProcessConfig::getErrorControl() { return dwErrorControl ; } void ServiceProcessConfig::SetErrorControl(DWORD dwArg) { dwErrorControl = dwArg ; } const TCHAR * ServiceProcessConfig::getBinaryPathName() { return strBinaryPathName; } void ServiceProcessConfig::SetBinaryPathName(const TCHAR * strArg) { if (strArg == NULL) { if (strBinaryPathName == NULL) return ; else { delete strBinaryPathName ; strBinaryPathName = NULL ; } }else { if ( strBinaryPathName != NULL ) { delete strBinaryPathName ; } UINT uSize = lstrlen(strArg) +1 ; strBinaryPathName = new TCHAR [uSize]; memcpy (strBinaryPathName ,strArg ,uSize *sizeof(TCHAR)); } } const TCHAR * ServiceProcessConfig::getLoadOrderGroup() { return strLoadOrderGroup ; } void ServiceProcessConfig::SetLoadOrderGroup(const TCHAR *strArg) { if (strArg == NULL) { if (strLoadOrderGroup == NULL) return ; else { delete strLoadOrderGroup ; strLoadOrderGroup = NULL ; } }else { if ( strLoadOrderGroup != NULL ) { delete strLoadOrderGroup ; } UINT uSize = lstrlen(strArg) +1 ; strLoadOrderGroup = new TCHAR [uSize]; memcpy (strLoadOrderGroup ,strArg ,uSize *sizeof(TCHAR)); } } void ServiceProcessConfig::SetTagId(DWORD i_dwTagId) { dwTagId = i_dwTagId ; } DWORD ServiceProcessConfig::getTagId() { return dwTagId ; } const TCHAR * ServiceProcessConfig::getDependencies() { return strDependencies; } void ServiceProcessConfig::SetDependencies(const TCHAR * strArg) { if (strArg == NULL) { if (strLoadOrderGroup == NULL) return ; else { delete strLoadOrderGroup ; strLoadOrderGroup = NULL ; } }else { if ( strLoadOrderGroup != NULL ) { delete strLoadOrderGroup ; } UINT uSize = 0; if ( sizeof (TCHAR) == 2 ) { int index = 0; unsigned char * byteTmp =(unsigned char *) strArg ; while ((*(unsigned int *)(byteTmp+index)) != 0) { uSize ++ ; index += sizeof (TCHAR); } uSize += 2*sizeof (TCHAR) ; }else if (sizeof (TCHAR) == 1) { int index = 0; unsigned char * byteTmp =(unsigned char *) strArg ; while ((*(unsigned short int *)(byteTmp+index)) != 0) { uSize ++ ; index ++ ; } uSize +=2 ; } strLoadOrderGroup = new TCHAR [uSize]; memcpy (strLoadOrderGroup ,strArg ,uSize * sizeof(TCHAR)); } } const TCHAR * ServiceProcessConfig::getServiceStartName() { return strServiceStartName; } void ServiceProcessConfig::SetServiceStartName(const TCHAR * strArg) { if (strArg == NULL) { if (strServiceStartName == NULL) return ; else { delete strServiceStartName ; strServiceStartName = NULL ; } }else { if ( strServiceStartName != NULL ) { delete strServiceStartName ; } UINT uSize = lstrlen(strArg) +1 ; strServiceStartName = new TCHAR [uSize]; memcpy (strServiceStartName ,strArg ,uSize *sizeof(TCHAR)); } } const TCHAR * ServiceProcessConfig::getPassword() { return strPassword; } void ServiceProcessConfig::SetPassword(const TCHAR * strArg) { if (strArg == NULL) { if (strPassword == NULL) return ; else { delete strPassword ; strPassword = NULL ; } }else { if ( strPassword != NULL ) { delete strPassword ; } UINT uSize = lstrlen(strArg) +1 ; strPassword = new TCHAR [uSize]; memcpy (strPassword ,strArg ,uSize *sizeof(TCHAR)); } }
a718a16be2343f5b4d5aa50d37b41f579b9ea0f2
bbac388eb6b53daec63190e2f271a18fe9bfb163
/abc129/CTypicalStairs.cpp
977fb85746604ed9df081c092c92f90e67eb93ae
[]
no_license
tatsumack/atcoder
8d94cf29160b6553b0c089cb795c54efd3fb0f7b
fbe1e1eab80c4c0680ec046acdc6214426b19650
refs/heads/master
2023-06-17T23:09:54.056132
2021-07-04T13:03:59
2021-07-04T13:03:59
124,963,709
0
0
null
null
null
null
UTF-8
C++
false
false
2,889
cpp
#include <iostream> #include <limits.h> #include <algorithm> #include <bitset> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> #include <queue> #include <unordered_map> #include <unordered_set> #define int long long #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define REPS(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i) #define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i) #define REV(i, a, b) for (int i = (a); i >= (b); --i) #define CLR(a, b) memset((a), (b), sizeof(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define INF 1001001001001001001ll #define fcout cout << fixed << setprecision(12) using namespace std; typedef pair<int, int> P; int mod = 1e9+7; struct mint { unsigned x; mint() : x(0) { } mint(signed sig) { x = sig < 0 ? sig % mod + mod : sig % mod; } mint(signed long long sig) { x = sig < 0 ? sig % mod + mod : sig % mod; } int get() const { return (int)x; } mint &operator+=(mint that) { if ((x += that.x) >= mod) x -= mod; return *this; } mint &operator-=(mint that) { if ((x += mod - that.x) >= mod) x -= mod; return *this; } mint &operator*=(mint that) { x = (unsigned long long)x * that.x % mod; return *this; } mint &operator/=(mint that) { return *this *= that.inverse(); } mint operator+(mint that) const { return mint(*this) += that; } mint operator-(mint that) const { return mint(*this) -= that; } mint operator*(mint that) const { return mint(*this) *= that; } mint operator/(mint that) const { return mint(*this) /= that; } mint inverse() const { long long a = x, b = mod, u = 1, v = 0; while (b) { long long t = a / b; a -= t * b; std::swap(a, b); u -= t * v; std::swap(u, v); } return mint(u); } bool operator==(mint that) const { return x == that.x; } bool operator!=(mint that) const { return x != that.x; } mint operator-() const { mint t; t.x = x == 0 ? 0 : mod - x; return t; } }; mint dp[100005]; class CTypicalStairs { public: static constexpr int kStressIterations = 0; static void generateTest(std::ostream& test) { } void solve(std::istream& cin, std::ostream& cout) { int N, M; cin >> N >> M; unordered_set<int> hole; REP(i, M) { int a; cin >> a; hole.insert(a); } REP(i, N+1) dp[i] = 0; dp[0] = 1; REP(i, N) { if (hole.count(i)) continue; dp[i+1] += dp[i]; dp[i+2] += dp[i]; } cout << dp[N].get() << endl; } };
aee3aaf3bf5baffa9b481e0fd7fab05d5f8837fa
9bcedb0048c0c7a3908d27c6bdf3def3acb27849
/Day16~27/DXEngine/DXEngine08_FBXLoader/Engine/DXUtil.h
ea84d2b5455e81b775c76b202689749224aa9e35
[]
no_license
youga114/AlgorithmAndDX
653b2e60fa605584353120468febcedf938c59f8
ea94a3bc94aae80e5c188e2596e61a01b39bc290
refs/heads/master
2020-06-02T21:36:21.462739
2019-07-23T09:52:54
2019-07-23T09:52:54
null
0
0
null
null
null
null
UHC
C++
false
false
647
h
#pragma once #include <d3d11.h> #include <d3dcompiler.h> #include <DirectXMath.h> #pragma comment(lib, "d3d11.lib") //프로젝트 설정에서 링커->입력->종속성에 추가한것과 같음 #pragma comment(lib, "d3dcompiler.lib") namespace Memory { template <class T> void SafeRelease(T& t) { if (t) { t->Release(); t = NULL; } } template <class T> void SafeDelete(T& t) { if (t) { delete t; t = NULL; } } // 배열 메모리 해제용. template <class T> void SafeDeleteArray(T& t) { if (t) { delete[] t; t = NULL; } } } // 오류 확인용 함수. bool IsError(HRESULT hr, LPCTSTR msg);
030feff9a56be68f47035ab3e4d84e87d5d2a9e7
2c36841c1c3bef06fe4a82bd87cacc64425d08c7
/Source/rclUE/Public/Msgs/ROS2GenericMsg.h
78b81a579d10b3a0961c39528c5cdd03af0b424a
[]
no_license
saratrajput/rclUE
29edba1a9b5b218264880b60844e9da2a1474602
4521c29ac66caba6eb5aa91483e75751652f91bf
refs/heads/master
2023-08-12T07:28:01.881375
2021-10-04T22:06:57
2021-10-04T22:06:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
// Copyright 2020-2021 Rapyuta Robotics Co., Ltd. #pragma once #include <CoreMinimal.h> #include "rclcUtilities.h" #include "ROS2GenericMsg.generated.h" DECLARE_LOG_CATEGORY_EXTERN(LogROS2Msg, Log, All); /** * This should be refactored with other generic ROS2 types (Msgs, Sensors, Actions) * Need to have a common class * Get/Print/ToString methods should be merged into a single of each with a parameter to switch versions (these are not bottlenecks and control flow inside them should be fine) */ UCLASS(Blueprintable) class RCLUE_API UROS2GenericMsg : public UObject { GENERATED_BODY() // Add interface functions to this class. This is the class that will be inherited to implement this interface. public: UFUNCTION(BlueprintCallable) virtual void Init(); UFUNCTION(BlueprintCallable) virtual void Fini(); virtual void* Get(); virtual const rosidl_message_type_support_t* GetTypeSupport() const; UFUNCTION(BlueprintCallable) virtual FString MsgToString() const; };
c41f05983604566dc1211d53df68a68d7d9bc9d1
c8ae40e956c93e44c86bad95a89e5b752a1c9cad
/src/caffe/net.cpp
c753f190bdce683908faea0413b5767dcc0419e1
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
lpx1233/caffe-yolov2
25739bed1661f54480b26027a21132b4e0341b95
c113a15fb734fb36da941f0550a44199d4fb454b
refs/heads/master
2020-05-16T09:07:42.454463
2019-04-23T05:35:57
2019-04-23T05:35:57
182,938,539
0
0
NOASSERTION
2019-04-23T05:20:18
2019-04-23T05:20:14
null
UTF-8
C++
false
false
41,529
cpp
#include <algorithm> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "hdf5.h" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/net.hpp" #include "caffe/parallel.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/hdf5.hpp" #include "caffe/util/insert_splits.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/upgrade_proto.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template <typename Dtype> Net<Dtype>::Net(const NetParameter& param, const Net* root_net) : root_net_(root_net) { Init(param); } template <typename Dtype> Net<Dtype>::Net(const string& param_file, Phase phase, const Net* root_net) : root_net_(root_net) { NetParameter param; ReadNetParamsFromTextFileOrDie(param_file, &param); param.mutable_state()->set_phase(phase); Init(param); } template <typename Dtype> void Net<Dtype>::Init(const NetParameter& in_param) { CHECK(Caffe::root_solver() || root_net_) << "root_net_ needs to be set for all non-root solvers"; // Set phase from the state. phase_ = in_param.state().phase(); // Filter layers based on their include/exclude rules and // the current NetState. NetParameter filtered_param; FilterNet(in_param, &filtered_param); LOG_IF(INFO, Caffe::root_solver()) << "Initializing net from parameters: " << std::endl << filtered_param.DebugString(); // Create a copy of filtered_param with splits added where necessary. NetParameter param; InsertSplits(filtered_param, &param); // Basically, build all the layers and set up their connections. name_ = param.name(); map<string, int> blob_name_to_idx; set<string> available_blobs; memory_used_ = 0; // For each layer, set up its input and output bottom_vecs_.resize(param.layer_size()); top_vecs_.resize(param.layer_size()); bottom_id_vecs_.resize(param.layer_size()); param_id_vecs_.resize(param.layer_size()); top_id_vecs_.resize(param.layer_size()); bottom_need_backward_.resize(param.layer_size()); for (int layer_id = 0; layer_id < param.layer_size(); ++layer_id) { // For non-root solvers, whether this layer is shared from root_net_. bool share_from_root = !Caffe::root_solver() && root_net_->layers_[layer_id]->ShareInParallel(); // Inherit phase from net if unset. if (!param.layer(layer_id).has_phase()) { param.mutable_layer(layer_id)->set_phase(phase_); } // Setup layer. const LayerParameter& layer_param = param.layer(layer_id); if (layer_param.propagate_down_size() > 0) { CHECK_EQ(layer_param.propagate_down_size(), layer_param.bottom_size()) << "propagate_down param must be specified " << "either 0 or bottom_size times "; } if (share_from_root) { LOG(INFO) << "Sharing layer " << layer_param.name() << " from root net"; layers_.push_back(root_net_->layers_[layer_id]); layers_[layer_id]->SetShared(true); } else { layers_.push_back(LayerRegistry<Dtype>::CreateLayer(layer_param)); } layer_names_.push_back(layer_param.name()); LOG_IF(INFO, Caffe::root_solver()) << "Creating Layer " << layer_param.name(); bool need_backward = false; // Figure out this layer's input and output for (int bottom_id = 0; bottom_id < layer_param.bottom_size(); ++bottom_id) { const int blob_id = AppendBottom(param, layer_id, bottom_id, &available_blobs, &blob_name_to_idx); // If a blob needs backward, this layer should provide it. need_backward |= blob_need_backward_[blob_id]; } int num_top = layer_param.top_size(); for (int top_id = 0; top_id < num_top; ++top_id) { AppendTop(param, layer_id, top_id, &available_blobs, &blob_name_to_idx); // Collect Input layer tops as Net inputs. if (layer_param.type() == "Input") { const int blob_id = blobs_.size() - 1; net_input_blob_indices_.push_back(blob_id); net_input_blobs_.push_back(blobs_[blob_id].get()); } } // If the layer specifies that AutoTopBlobs() -> true and the LayerParameter // specified fewer than the required number (as specified by // ExactNumTopBlobs() or MinTopBlobs()), allocate them here. Layer<Dtype>* layer = layers_[layer_id].get(); if (layer->AutoTopBlobs()) { const int needed_num_top = std::max(layer->MinTopBlobs(), layer->ExactNumTopBlobs()); for (; num_top < needed_num_top; ++num_top) { // Add "anonymous" top blobs -- do not modify available_blobs or // blob_name_to_idx as we don't want these blobs to be usable as input // to other layers. AppendTop(param, layer_id, num_top, NULL, NULL); } } // After this layer is connected, set it up. if (share_from_root) { // Set up size of top blobs using root_net_ const vector<Blob<Dtype>*>& base_top = root_net_->top_vecs_[layer_id]; const vector<Blob<Dtype>*>& this_top = this->top_vecs_[layer_id]; for (int top_id = 0; top_id < base_top.size(); ++top_id) { this_top[top_id]->ReshapeLike(*base_top[top_id]); LOG(INFO) << "Created top blob " << top_id << " (shape: " << this_top[top_id]->shape_string() << ") for shared layer " << layer_param.name(); } } else { layers_[layer_id]->SetUp(bottom_vecs_[layer_id], top_vecs_[layer_id]); } LOG_IF(INFO, Caffe::root_solver()) << "Setting up " << layer_names_[layer_id]; for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) { if (blob_loss_weights_.size() <= top_id_vecs_[layer_id][top_id]) { blob_loss_weights_.resize(top_id_vecs_[layer_id][top_id] + 1, Dtype(0)); } blob_loss_weights_[top_id_vecs_[layer_id][top_id]] = layer->loss(top_id); LOG_IF(INFO, Caffe::root_solver()) << "Top shape: " << top_vecs_[layer_id][top_id]->shape_string(); if (layer->loss(top_id)) { LOG_IF(INFO, Caffe::root_solver()) << " with loss weight " << layer->loss(top_id); } memory_used_ += top_vecs_[layer_id][top_id]->count(); } LOG_IF(INFO, Caffe::root_solver()) << "Memory required for data: " << memory_used_ * sizeof(Dtype); const int param_size = layer_param.param_size(); const int num_param_blobs = layers_[layer_id]->blobs().size(); CHECK_LE(param_size, num_param_blobs) << "Too many params specified for layer " << layer_param.name(); ParamSpec default_param_spec; for (int param_id = 0; param_id < num_param_blobs; ++param_id) { const ParamSpec* param_spec = (param_id < param_size) ? &layer_param.param(param_id) : &default_param_spec; const bool param_need_backward = param_spec->lr_mult() != 0; need_backward |= param_need_backward; layers_[layer_id]->set_param_propagate_down(param_id, param_need_backward); } for (int param_id = 0; param_id < num_param_blobs; ++param_id) { AppendParam(param, layer_id, param_id); } // Finally, set the backward flag layer_need_backward_.push_back(need_backward); if (need_backward) { for (int top_id = 0; top_id < top_id_vecs_[layer_id].size(); ++top_id) { blob_need_backward_[top_id_vecs_[layer_id][top_id]] = true; } } } // Go through the net backwards to determine which blobs contribute to the // loss. We can skip backward computation for blobs that don't contribute // to the loss. // Also checks if all bottom blobs don't need backward computation (possible // because the skip_propagate_down param) and so we can skip bacward // computation for the entire layer set<string> blobs_under_loss; set<string> blobs_skip_backp; for (int layer_id = layers_.size() - 1; layer_id >= 0; --layer_id) { bool layer_contributes_loss = false; bool layer_skip_propagate_down = true; for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) { const string& blob_name = blob_names_[top_id_vecs_[layer_id][top_id]]; if (layers_[layer_id]->loss(top_id) || (blobs_under_loss.find(blob_name) != blobs_under_loss.end())) { layer_contributes_loss = true; } if (blobs_skip_backp.find(blob_name) == blobs_skip_backp.end()) { layer_skip_propagate_down = false; } if (layer_contributes_loss && !layer_skip_propagate_down) break; } // If this layer can skip backward computation, also all his bottom blobs // don't need backpropagation if (layer_need_backward_[layer_id] && layer_skip_propagate_down) { layer_need_backward_[layer_id] = false; for (int bottom_id = 0; bottom_id < bottom_vecs_[layer_id].size(); ++bottom_id) { bottom_need_backward_[layer_id][bottom_id] = false; } } if (!layer_contributes_loss) { layer_need_backward_[layer_id] = false; } if (Caffe::root_solver()) { if (layer_need_backward_[layer_id]) { LOG(INFO) << layer_names_[layer_id] << " needs backward computation."; } else { LOG(INFO) << layer_names_[layer_id] << " does not need backward computation."; } } for (int bottom_id = 0; bottom_id < bottom_vecs_[layer_id].size(); ++bottom_id) { if (layer_contributes_loss) { const string& blob_name = blob_names_[bottom_id_vecs_[layer_id][bottom_id]]; blobs_under_loss.insert(blob_name); } else { bottom_need_backward_[layer_id][bottom_id] = false; } if (!bottom_need_backward_[layer_id][bottom_id]) { const string& blob_name = blob_names_[bottom_id_vecs_[layer_id][bottom_id]]; blobs_skip_backp.insert(blob_name); } } } // Handle force_backward if needed. if (param.force_backward()) { for (int layer_id = 0; layer_id < layers_.size(); ++layer_id) { layer_need_backward_[layer_id] = true; for (int bottom_id = 0; bottom_id < bottom_need_backward_[layer_id].size(); ++bottom_id) { bottom_need_backward_[layer_id][bottom_id] = bottom_need_backward_[layer_id][bottom_id] || layers_[layer_id]->AllowForceBackward(bottom_id); blob_need_backward_[bottom_id_vecs_[layer_id][bottom_id]] = blob_need_backward_[bottom_id_vecs_[layer_id][bottom_id]] || bottom_need_backward_[layer_id][bottom_id]; } for (int param_id = 0; param_id < layers_[layer_id]->blobs().size(); ++param_id) { layers_[layer_id]->set_param_propagate_down(param_id, true); } } } // In the end, all remaining blobs are considered output blobs. for (set<string>::iterator it = available_blobs.begin(); it != available_blobs.end(); ++it) { LOG_IF(INFO, Caffe::root_solver()) << "This network produces output " << *it; net_output_blobs_.push_back(blobs_[blob_name_to_idx[*it]].get()); net_output_blob_indices_.push_back(blob_name_to_idx[*it]); } for (size_t blob_id = 0; blob_id < blob_names_.size(); ++blob_id) { blob_names_index_[blob_names_[blob_id]] = blob_id; } for (size_t layer_id = 0; layer_id < layer_names_.size(); ++layer_id) { layer_names_index_[layer_names_[layer_id]] = layer_id; } ShareWeights(); debug_info_ = param.debug_info(); LOG_IF(INFO, Caffe::root_solver()) << "Network initialization done."; } template <typename Dtype> void Net<Dtype>::FilterNet(const NetParameter& param, NetParameter* param_filtered) { NetState net_state(param.state()); param_filtered->CopyFrom(param); param_filtered->clear_layer(); for (int i = 0; i < param.layer_size(); ++i) { const LayerParameter& layer_param = param.layer(i); const string& layer_name = layer_param.name(); CHECK(layer_param.include_size() == 0 || layer_param.exclude_size() == 0) << "Specify either include rules or exclude rules; not both."; // If no include rules are specified, the layer is included by default and // only excluded if it meets one of the exclude rules. bool layer_included = (layer_param.include_size() == 0); for (int j = 0; layer_included && j < layer_param.exclude_size(); ++j) { if (StateMeetsRule(net_state, layer_param.exclude(j), layer_name)) { layer_included = false; } } for (int j = 0; !layer_included && j < layer_param.include_size(); ++j) { if (StateMeetsRule(net_state, layer_param.include(j), layer_name)) { layer_included = true; } } if (layer_included) { param_filtered->add_layer()->CopyFrom(layer_param); } } } template <typename Dtype> bool Net<Dtype>::StateMeetsRule(const NetState& state, const NetStateRule& rule, const string& layer_name) { // Check whether the rule is broken due to phase. if (rule.has_phase()) { if (rule.phase() != state.phase()) { LOG_IF(INFO, Caffe::root_solver()) << "The NetState phase (" << state.phase() << ") differed from the phase (" << rule.phase() << ") specified by a rule in layer " << layer_name; return false; } } // Check whether the rule is broken due to min level. if (rule.has_min_level()) { if (state.level() < rule.min_level()) { LOG_IF(INFO, Caffe::root_solver()) << "The NetState level (" << state.level() << ") is above the min_level (" << rule.min_level() << ") specified by a rule in layer " << layer_name; return false; } } // Check whether the rule is broken due to max level. if (rule.has_max_level()) { if (state.level() > rule.max_level()) { LOG_IF(INFO, Caffe::root_solver()) << "The NetState level (" << state.level() << ") is above the max_level (" << rule.max_level() << ") specified by a rule in layer " << layer_name; return false; } } // Check whether the rule is broken due to stage. The NetState must // contain ALL of the rule's stages to meet it. for (int i = 0; i < rule.stage_size(); ++i) { // Check that the NetState contains the rule's ith stage. bool has_stage = false; for (int j = 0; !has_stage && j < state.stage_size(); ++j) { if (rule.stage(i) == state.stage(j)) { has_stage = true; } } if (!has_stage) { LOG_IF(INFO, Caffe::root_solver()) << "The NetState did not contain stage '" << rule.stage(i) << "' specified by a rule in layer " << layer_name; return false; } } // Check whether the rule is broken due to not_stage. The NetState must // contain NONE of the rule's not_stages to meet it. for (int i = 0; i < rule.not_stage_size(); ++i) { // Check that the NetState contains the rule's ith not_stage. bool has_stage = false; for (int j = 0; !has_stage && j < state.stage_size(); ++j) { if (rule.not_stage(i) == state.stage(j)) { has_stage = true; } } if (has_stage) { LOG_IF(INFO, Caffe::root_solver()) << "The NetState contained a not_stage '" << rule.not_stage(i) << "' specified by a rule in layer " << layer_name; return false; } } return true; } template <typename Dtype> Dtype Net<Dtype>::findMax(Blob<Dtype>* blob) { const Dtype* data = blob->cpu_data(); int cnt = blob->count(); Dtype max_val = (Dtype)-10; for (int i = 0; i < cnt; ++i) { max_val = std::max(max_val, (Dtype)fabs(data[i])); } return max_val; } template <typename Dtype> void Net<Dtype>::RangeInLayers(vector<string>* layer_name, vector<Dtype>* max_in, vector<Dtype>* max_out, vector<Dtype>* max_param) { // Initialize vector elements, if needed. if(layer_name->size()==0) { for (int layer_id = 0; layer_id < layers_.size(); ++layer_id) { if (strcmp(layers_[layer_id]->type(), "Convolution") == 0 || strcmp(layers_[layer_id]->type(), "InnerProduct") == 0) { layer_name->push_back(this->layer_names()[layer_id]); max_in->push_back(0); max_out->push_back(0); max_param->push_back(0); } } } // Find maximal values. int index = 0; Dtype max_val; for (int layer_id = 0; layer_id < layers_.size(); ++layer_id) { if (strcmp(layers_[layer_id]->type(), "Convolution") == 0 || strcmp(layers_[layer_id]->type(), "InnerProduct") == 0) { max_val = findMax(bottom_vecs_[layer_id][0]); max_in->at(index) = std::max(max_in->at(index), max_val); max_val = findMax(top_vecs_[layer_id][0]); max_out->at(index) = std::max(max_out->at(index), max_val); // Consider the weights only, ignore the bias max_val = findMax(&(*layers_[layer_id]->blobs()[0])); max_param->at(index) = std::max(max_param->at(index), max_val); index++; } } } // Helper for Net::Init: add a new top blob to the net. template <typename Dtype> void Net<Dtype>::AppendTop(const NetParameter& param, const int layer_id, const int top_id, set<string>* available_blobs, map<string, int>* blob_name_to_idx) { shared_ptr<LayerParameter> layer_param( new LayerParameter(param.layer(layer_id))); const string& blob_name = (layer_param->top_size() > top_id) ? layer_param->top(top_id) : "(automatic)"; // Check if we are doing in-place computation if (blob_name_to_idx && layer_param->bottom_size() > top_id && blob_name == layer_param->bottom(top_id)) { // In-place computation LOG_IF(INFO, Caffe::root_solver()) << layer_param->name() << " -> " << blob_name << " (in-place)"; top_vecs_[layer_id].push_back(blobs_[(*blob_name_to_idx)[blob_name]].get()); top_id_vecs_[layer_id].push_back((*blob_name_to_idx)[blob_name]); } else if (blob_name_to_idx && blob_name_to_idx->find(blob_name) != blob_name_to_idx->end()) { // If we are not doing in-place computation but have duplicated blobs, // raise an error. LOG(FATAL) << "Top blob '" << blob_name << "' produced by multiple sources."; } else { // Normal output. if (Caffe::root_solver()) { LOG(INFO) << layer_param->name() << " -> " << blob_name; } shared_ptr<Blob<Dtype> > blob_pointer(new Blob<Dtype>()); const int blob_id = blobs_.size(); blobs_.push_back(blob_pointer); blob_names_.push_back(blob_name); blob_need_backward_.push_back(false); if (blob_name_to_idx) { (*blob_name_to_idx)[blob_name] = blob_id; } top_id_vecs_[layer_id].push_back(blob_id); top_vecs_[layer_id].push_back(blob_pointer.get()); } if (available_blobs) { available_blobs->insert(blob_name); } } // Helper for Net::Init: add a new bottom blob to the net. template <typename Dtype> int Net<Dtype>::AppendBottom(const NetParameter& param, const int layer_id, const int bottom_id, set<string>* available_blobs, map<string, int>* blob_name_to_idx) { const LayerParameter& layer_param = param.layer(layer_id); const string& blob_name = layer_param.bottom(bottom_id); if (available_blobs->find(blob_name) == available_blobs->end()) { LOG(FATAL) << "Unknown bottom blob '" << blob_name << "' (layer '" << layer_param.name() << "', bottom index " << bottom_id << ")"; } const int blob_id = (*blob_name_to_idx)[blob_name]; LOG_IF(INFO, Caffe::root_solver()) << layer_names_[layer_id] << " <- " << blob_name; bottom_vecs_[layer_id].push_back(blobs_[blob_id].get()); bottom_id_vecs_[layer_id].push_back(blob_id); available_blobs->erase(blob_name); bool need_backward = blob_need_backward_[blob_id]; // Check if the backpropagation on bottom_id should be skipped if (layer_param.propagate_down_size() > 0) { need_backward = layer_param.propagate_down(bottom_id); } bottom_need_backward_[layer_id].push_back(need_backward); return blob_id; } template <typename Dtype> void Net<Dtype>::AppendParam(const NetParameter& param, const int layer_id, const int param_id) { const LayerParameter& layer_param = layers_[layer_id]->layer_param(); const int param_size = layer_param.param_size(); string param_name = (param_size > param_id) ? layer_param.param(param_id).name() : ""; if (param_name.size()) { param_display_names_.push_back(param_name); } else { ostringstream param_display_name; param_display_name << param_id; param_display_names_.push_back(param_display_name.str()); } const int net_param_id = params_.size(); params_.push_back(layers_[layer_id]->blobs()[param_id]); param_id_vecs_[layer_id].push_back(net_param_id); param_layer_indices_.push_back(make_pair(layer_id, param_id)); ParamSpec default_param_spec; const ParamSpec* param_spec = (layer_param.param_size() > param_id) ? &layer_param.param(param_id) : &default_param_spec; if (!param_size || !param_name.size() || (param_name.size() && param_names_index_.find(param_name) == param_names_index_.end())) { // This layer "owns" this parameter blob -- it is either anonymous // (i.e., not given a param_name) or explicitly given a name that we // haven't already seen. param_owners_.push_back(-1); if (param_name.size()) { param_names_index_[param_name] = net_param_id; } const int learnable_param_id = learnable_params_.size(); learnable_params_.push_back(params_[net_param_id].get()); learnable_param_ids_.push_back(learnable_param_id); has_params_lr_.push_back(param_spec->has_lr_mult()); has_params_decay_.push_back(param_spec->has_decay_mult()); params_lr_.push_back(param_spec->lr_mult()); params_weight_decay_.push_back(param_spec->decay_mult()); } else { // Named param blob with name we've seen before: share params const int owner_net_param_id = param_names_index_[param_name]; param_owners_.push_back(owner_net_param_id); const pair<int, int>& owner_index = param_layer_indices_[owner_net_param_id]; const int owner_layer_id = owner_index.first; const int owner_param_id = owner_index.second; LOG_IF(INFO, Caffe::root_solver()) << "Sharing parameters '" << param_name << "' owned by " << "layer '" << layer_names_[owner_layer_id] << "', param " << "index " << owner_param_id; Blob<Dtype>* this_blob = layers_[layer_id]->blobs()[param_id].get(); Blob<Dtype>* owner_blob = layers_[owner_layer_id]->blobs()[owner_param_id].get(); const int param_size = layer_param.param_size(); if (param_size > param_id && (layer_param.param(param_id).share_mode() == ParamSpec_DimCheckMode_PERMISSIVE)) { // Permissive dimension checking -- only check counts are the same. CHECK_EQ(this_blob->count(), owner_blob->count()) << "Cannot share param '" << param_name << "' owned by layer '" << layer_names_[owner_layer_id] << "' with layer '" << layer_names_[layer_id] << "'; count mismatch. Owner layer param " << "shape is " << owner_blob->shape_string() << "; sharing layer " << "shape is " << this_blob->shape_string(); } else { // Strict dimension checking -- all dims must be the same. CHECK(this_blob->shape() == owner_blob->shape()) << "Cannot share param '" << param_name << "' owned by layer '" << layer_names_[owner_layer_id] << "' with layer '" << layer_names_[layer_id] << "'; shape mismatch. Owner layer param " << "shape is " << owner_blob->shape_string() << "; sharing layer " << "expects shape " << this_blob->shape_string(); } const int learnable_param_id = learnable_param_ids_[owner_net_param_id]; learnable_param_ids_.push_back(learnable_param_id); if (param_spec->has_lr_mult()) { if (has_params_lr_[learnable_param_id]) { CHECK_EQ(param_spec->lr_mult(), params_lr_[learnable_param_id]) << "Shared param '" << param_name << "' has mismatched lr_mult."; } else { has_params_lr_[learnable_param_id] = true; params_lr_[learnable_param_id] = param_spec->lr_mult(); } } if (param_spec->has_decay_mult()) { if (has_params_decay_[learnable_param_id]) { CHECK_EQ(param_spec->decay_mult(), params_weight_decay_[learnable_param_id]) << "Shared param '" << param_name << "' has mismatched decay_mult."; } else { has_params_decay_[learnable_param_id] = true; params_weight_decay_[learnable_param_id] = param_spec->decay_mult(); } } } } template <typename Dtype> Dtype Net<Dtype>::ForwardFromTo(int start, int end) { CHECK_GE(start, 0); CHECK_LT(end, layers_.size()); Dtype loss = 0; for (int i = start; i <= end; ++i) { // LOG(ERROR) << "Forwarding " << layer_names_[i]; Dtype layer_loss = layers_[i]->Forward(bottom_vecs_[i], top_vecs_[i]); loss += layer_loss; if (debug_info_) { ForwardDebugInfo(i); } } return loss; } template <typename Dtype> Dtype Net<Dtype>::ForwardFrom(int start) { return ForwardFromTo(start, layers_.size() - 1); } template <typename Dtype> Dtype Net<Dtype>::ForwardTo(int end) { return ForwardFromTo(0, end); } template <typename Dtype> const vector<Blob<Dtype>*>& Net<Dtype>::Forward(Dtype* loss) { if (loss != NULL) { *loss = ForwardFromTo(0, layers_.size() - 1); } else { ForwardFromTo(0, layers_.size() - 1); } return net_output_blobs_; } template <typename Dtype> const vector<Blob<Dtype>*>& Net<Dtype>::Forward( const vector<Blob<Dtype>*> & bottom, Dtype* loss) { LOG_EVERY_N(WARNING, 1000) << "DEPRECATED: Forward(bottom, loss) " << "will be removed in a future version. Use Forward(loss)."; // Copy bottom to net bottoms for (int i = 0; i < bottom.size(); ++i) { net_input_blobs_[i]->CopyFrom(*bottom[i]); } return Forward(loss); } template <typename Dtype> void Net<Dtype>::BackwardFromTo(int start, int end) { CHECK_GE(end, 0); CHECK_LT(start, layers_.size()); for (int i = start; i >= end; --i) { if (layer_need_backward_[i]) { layers_[i]->Backward( top_vecs_[i], bottom_need_backward_[i], bottom_vecs_[i]); if (debug_info_) { BackwardDebugInfo(i); } } } } template <typename Dtype> void Net<Dtype>::ForwardDebugInfo(const int layer_id) { for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) { const Blob<Dtype>& blob = *top_vecs_[layer_id][top_id]; const string& blob_name = blob_names_[top_id_vecs_[layer_id][top_id]]; const Dtype data_abs_val_mean = blob.asum_data() / blob.count(); LOG_IF(INFO, Caffe::root_solver()) << " [Forward] " << "Layer " << layer_names_[layer_id] << ", top blob " << blob_name << " data: " << data_abs_val_mean; } for (int param_id = 0; param_id < layers_[layer_id]->blobs().size(); ++param_id) { const Blob<Dtype>& blob = *layers_[layer_id]->blobs()[param_id]; const int net_param_id = param_id_vecs_[layer_id][param_id]; const string& blob_name = param_display_names_[net_param_id]; const Dtype data_abs_val_mean = blob.asum_data() / blob.count(); LOG_IF(INFO, Caffe::root_solver()) << " [Forward] " << "Layer " << layer_names_[layer_id] << ", param blob " << blob_name << " data: " << data_abs_val_mean; } } template <typename Dtype> void Net<Dtype>::BackwardDebugInfo(const int layer_id) { const vector<Blob<Dtype>*>& bottom_vec = bottom_vecs_[layer_id]; for (int bottom_id = 0; bottom_id < bottom_vec.size(); ++bottom_id) { if (!bottom_need_backward_[layer_id][bottom_id]) { continue; } const Blob<Dtype>& blob = *bottom_vec[bottom_id]; const string& blob_name = blob_names_[bottom_id_vecs_[layer_id][bottom_id]]; const Dtype diff_abs_val_mean = blob.asum_diff() / blob.count(); LOG_IF(INFO, Caffe::root_solver()) << " [Backward] " << "Layer " << layer_names_[layer_id] << ", bottom blob " << blob_name << " diff: " << diff_abs_val_mean; } for (int param_id = 0; param_id < layers_[layer_id]->blobs().size(); ++param_id) { if (!layers_[layer_id]->param_propagate_down(param_id)) { continue; } const Blob<Dtype>& blob = *layers_[layer_id]->blobs()[param_id]; const Dtype diff_abs_val_mean = blob.asum_diff() / blob.count(); LOG_IF(INFO, Caffe::root_solver()) << " [Backward] " << "Layer " << layer_names_[layer_id] << ", param blob " << param_id << " diff: " << diff_abs_val_mean; } } template <typename Dtype> void Net<Dtype>::UpdateDebugInfo(const int param_id) { const Blob<Dtype>& blob = *params_[param_id]; const int param_owner = param_owners_[param_id]; const string& layer_name = layer_names_[param_layer_indices_[param_id].first]; const string& param_display_name = param_display_names_[param_id]; const Dtype diff_abs_val_mean = blob.asum_diff() / blob.count(); if (param_owner < 0) { const Dtype data_abs_val_mean = blob.asum_data() / blob.count(); LOG_IF(INFO, Caffe::root_solver()) << " [Update] Layer " << layer_name << ", param " << param_display_name << " data: " << data_abs_val_mean << "; diff: " << diff_abs_val_mean; } else { const string& owner_layer_name = layer_names_[param_layer_indices_[param_owner].first]; LOG_IF(INFO, Caffe::root_solver()) << " [Update] Layer " << layer_name << ", param blob " << param_display_name << " (owned by layer " << owner_layer_name << ", " << "param " << param_display_names_[param_owners_[param_id]] << ")" << " diff: " << diff_abs_val_mean; } } template <typename Dtype> void Net<Dtype>::ShareTrainedLayersWith(const Net* other) { int num_source_layers = other->layers().size(); for (int i = 0; i < num_source_layers; ++i) { Layer<Dtype>* source_layer = other->layers()[i].get(); const string& source_layer_name = other->layer_names()[i]; int target_layer_id = 0; while (target_layer_id != layer_names_.size() && layer_names_[target_layer_id] != source_layer_name) { ++target_layer_id; } if (target_layer_id == layer_names_.size()) { LOG(INFO) << "Ignoring source layer " << source_layer_name; continue; } DLOG(INFO) << "Copying source layer " << source_layer_name; vector<shared_ptr<Blob<Dtype> > >& target_blobs = layers_[target_layer_id]->blobs(); CHECK_EQ(target_blobs.size(), source_layer->blobs().size()) << "Incompatible number of blobs for layer " << source_layer_name; for (int j = 0; j < target_blobs.size(); ++j) { Blob<Dtype>* source_blob = source_layer->blobs()[j].get(); CHECK(target_blobs[j]->shape() == source_blob->shape()) << "Cannot share param " << j << " weights from layer '" << source_layer_name << "'; shape mismatch. Source param shape is " << source_blob->shape_string() << "; target param shape is " << target_blobs[j]->shape_string(); target_blobs[j]->ShareData(*source_blob); } } } template <typename Dtype> void Net<Dtype>::BackwardFrom(int start) { BackwardFromTo(start, 0); } template <typename Dtype> void Net<Dtype>::BackwardTo(int end) { BackwardFromTo(layers_.size() - 1, end); } template <typename Dtype> void Net<Dtype>::Backward() { BackwardFromTo(layers_.size() - 1, 0); if (debug_info_) { Dtype asum_data = 0, asum_diff = 0, sumsq_data = 0, sumsq_diff = 0; for (int i = 0; i < learnable_params_.size(); ++i) { asum_data += learnable_params_[i]->asum_data(); asum_diff += learnable_params_[i]->asum_diff(); sumsq_data += learnable_params_[i]->sumsq_data(); sumsq_diff += learnable_params_[i]->sumsq_diff(); } const Dtype l2norm_data = std::sqrt(sumsq_data); const Dtype l2norm_diff = std::sqrt(sumsq_diff); LOG(ERROR) << " [Backward] All net params (data, diff): " << "L1 norm = (" << asum_data << ", " << asum_diff << "); " << "L2 norm = (" << l2norm_data << ", " << l2norm_diff << ")"; } } template <typename Dtype> void Net<Dtype>::Reshape() { for (int i = 0; i < layers_.size(); ++i) { layers_[i]->Reshape(bottom_vecs_[i], top_vecs_[i]); } } template <typename Dtype> void Net<Dtype>::CopyTrainedLayersFrom(const NetParameter& param) { int num_source_layers = param.layer_size(); for (int i = 0; i < num_source_layers; ++i) { const LayerParameter& source_layer = param.layer(i); const string& source_layer_name = source_layer.name(); int target_layer_id = 0; while (target_layer_id != layer_names_.size() && layer_names_[target_layer_id] != source_layer_name) { ++target_layer_id; } if (target_layer_id == layer_names_.size()) { LOG(INFO) << "Ignoring source layer " << source_layer_name; continue; } DLOG(INFO) << "Copying source layer " << source_layer_name; vector<shared_ptr<Blob<Dtype> > >& target_blobs = layers_[target_layer_id]->blobs(); CHECK_EQ(target_blobs.size(), source_layer.blobs_size()) << "Incompatible number of blobs for layer " << source_layer_name; for (int j = 0; j < target_blobs.size(); ++j) { if (!target_blobs[j]->ShapeEquals(source_layer.blobs(j))) { Blob<Dtype> source_blob; const bool kReshape = true; source_blob.FromProto(source_layer.blobs(j), kReshape); LOG(FATAL) << "Cannot copy param " << j << " weights from layer '" << source_layer_name << "'; shape mismatch. Source param shape is " << source_blob.shape_string() << "; target param shape is " << target_blobs[j]->shape_string() << ". " << "To learn this layer's parameters from scratch rather than " << "copying from a saved net, rename the layer."; } const bool kReshape = false; target_blobs[j]->FromProto(source_layer.blobs(j), kReshape); } } } template <typename Dtype> void Net<Dtype>::CopyTrainedLayersFrom(const string trained_filename) { if (trained_filename.size() >= 3 && trained_filename.compare(trained_filename.size() - 3, 3, ".h5") == 0) { CopyTrainedLayersFromHDF5(trained_filename); } else { CopyTrainedLayersFromBinaryProto(trained_filename); } } template <typename Dtype> void Net<Dtype>::CopyTrainedLayersFromBinaryProto( const string trained_filename) { NetParameter param; ReadNetParamsFromBinaryFileOrDie(trained_filename, &param); CopyTrainedLayersFrom(param); } template <typename Dtype> void Net<Dtype>::CopyTrainedLayersFromHDF5(const string trained_filename) { hid_t file_hid = H5Fopen(trained_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); CHECK_GE(file_hid, 0) << "Couldn't open " << trained_filename; hid_t data_hid = H5Gopen2(file_hid, "data", H5P_DEFAULT); CHECK_GE(data_hid, 0) << "Error reading weights from " << trained_filename; int num_layers = hdf5_get_num_links(data_hid); for (int i = 0; i < num_layers; ++i) { string source_layer_name = hdf5_get_name_by_idx(data_hid, i); if (!layer_names_index_.count(source_layer_name)) { LOG(INFO) << "Ignoring source layer " << source_layer_name; continue; } int target_layer_id = layer_names_index_[source_layer_name]; DLOG(INFO) << "Copying source layer " << source_layer_name; vector<shared_ptr<Blob<Dtype> > >& target_blobs = layers_[target_layer_id]->blobs(); hid_t layer_hid = H5Gopen2(data_hid, source_layer_name.c_str(), H5P_DEFAULT); CHECK_GE(layer_hid, 0) << "Error reading weights from " << trained_filename; // Check that source layer doesn't have more params than target layer int num_source_params = hdf5_get_num_links(layer_hid); CHECK_LE(num_source_params, target_blobs.size()) << "Incompatible number of blobs for layer " << source_layer_name; for (int j = 0; j < target_blobs.size(); ++j) { ostringstream oss; oss << j; string dataset_name = oss.str(); int target_net_param_id = param_id_vecs_[target_layer_id][j]; if (!H5Lexists(layer_hid, dataset_name.c_str(), H5P_DEFAULT)) { // Target param doesn't exist in source weights... if (param_owners_[target_net_param_id] != -1) { // ...but it's weight-shared in target, so that's fine. continue; } else { LOG(FATAL) << "Incompatible number of blobs for layer " << source_layer_name; } } hdf5_load_nd_dataset(layer_hid, dataset_name.c_str(), 0, kMaxBlobAxes, target_blobs[j].get()); } H5Gclose(layer_hid); } H5Gclose(data_hid); H5Fclose(file_hid); } template <typename Dtype> void Net<Dtype>::ToProto(NetParameter* param, bool write_diff) const { param->Clear(); param->set_name(name_); // Add bottom and top DLOG(INFO) << "Serializing " << layers_.size() << " layers"; for (int i = 0; i < layers_.size(); ++i) { LayerParameter* layer_param = param->add_layer(); layers_[i]->ToProto(layer_param, write_diff); } } template <typename Dtype> void Net<Dtype>::ToHDF5(const string& filename, bool write_diff) const { hid_t file_hid = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(file_hid, 0) << "Couldn't open " << filename << " to save weights."; hid_t data_hid = H5Gcreate2(file_hid, "data", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(data_hid, 0) << "Error saving weights to " << filename << "."; hid_t diff_hid = -1; if (write_diff) { diff_hid = H5Gcreate2(file_hid, "diff", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(diff_hid, 0) << "Error saving weights to " << filename << "."; } for (int layer_id = 0; layer_id < layers_.size(); ++layer_id) { const LayerParameter& layer_param = layers_[layer_id]->layer_param(); string layer_name = layer_param.name(); hid_t layer_data_hid = H5Gcreate2(data_hid, layer_name.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(layer_data_hid, 0) << "Error saving weights to " << filename << "."; hid_t layer_diff_hid = -1; if (write_diff) { layer_diff_hid = H5Gcreate2(diff_hid, layer_name.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(layer_diff_hid, 0) << "Error saving weights to " << filename << "."; } int num_params = layers_[layer_id]->blobs().size(); for (int param_id = 0; param_id < num_params; ++param_id) { ostringstream dataset_name; dataset_name << param_id; const int net_param_id = param_id_vecs_[layer_id][param_id]; if (param_owners_[net_param_id] == -1) { // Only save params that own themselves hdf5_save_nd_dataset<Dtype>(layer_data_hid, dataset_name.str(), *params_[net_param_id]); } if (write_diff) { // Write diffs regardless of weight-sharing hdf5_save_nd_dataset<Dtype>(layer_diff_hid, dataset_name.str(), *params_[net_param_id], true); } } H5Gclose(layer_data_hid); if (write_diff) { H5Gclose(layer_diff_hid); } } H5Gclose(data_hid); if (write_diff) { H5Gclose(diff_hid); } H5Fclose(file_hid); } template <typename Dtype> void Net<Dtype>::Update() { for (int i = 0; i < learnable_params_.size(); ++i) { learnable_params_[i]->Update(); } } template <typename Dtype> void Net<Dtype>::ClearParamDiffs() { for (int i = 0; i < learnable_params_.size(); ++i) { Blob<Dtype>* blob = learnable_params_[i]; switch (Caffe::mode()) { case Caffe::CPU: caffe_set(blob->count(), static_cast<Dtype>(0), blob->mutable_cpu_diff()); break; case Caffe::GPU: #ifndef CPU_ONLY caffe_gpu_set(blob->count(), static_cast<Dtype>(0), blob->mutable_gpu_diff()); #else NO_GPU; #endif break; } } } template <typename Dtype> void Net<Dtype>::ShareWeights() { for (int i = 0; i < params_.size(); ++i) { if (param_owners_[i] < 0) { continue; } params_[i]->ShareData(*params_[param_owners_[i]]); params_[i]->ShareDiff(*params_[param_owners_[i]]); } } template <typename Dtype> bool Net<Dtype>::has_blob(const string& blob_name) const { return blob_names_index_.find(blob_name) != blob_names_index_.end(); } template <typename Dtype> const shared_ptr<Blob<Dtype> > Net<Dtype>::blob_by_name( const string& blob_name) const { shared_ptr<Blob<Dtype> > blob_ptr; if (has_blob(blob_name)) { blob_ptr = blobs_[blob_names_index_.find(blob_name)->second]; } else { blob_ptr.reset((Blob<Dtype>*)(NULL)); LOG(WARNING) << "Unknown blob name " << blob_name; } return blob_ptr; } template <typename Dtype> bool Net<Dtype>::has_layer(const string& layer_name) const { return layer_names_index_.find(layer_name) != layer_names_index_.end(); } template <typename Dtype> const shared_ptr<Layer<Dtype> > Net<Dtype>::layer_by_name( const string& layer_name) const { shared_ptr<Layer<Dtype> > layer_ptr; if (has_layer(layer_name)) { layer_ptr = layers_[layer_names_index_.find(layer_name)->second]; } else { layer_ptr.reset((Layer<Dtype>*)(NULL)); LOG(WARNING) << "Unknown layer name " << layer_name; } return layer_ptr; } INSTANTIATE_CLASS(Net); } // namespace caffe
474e07e55682843c5d30a6064cf2eb207d0fddff
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_Task_Scout_Strafe_structs.hpp
4d3d7a30680f98cfdc84d4aca70c67973b080686
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
413
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Basic.hpp" #include "ARKSurvivalEvolved_AIModule_classes.hpp" #include "ARKSurvivalEvolved_Engine_classes.hpp" #include "ARKSurvivalEvolved_CoreUObject_classes.hpp" #include "ARKSurvivalEvolved_ScoutStrafeState_classes.hpp" namespace sdk { } #ifdef _MSC_VER #pragma pack(pop) #endif
f95b32443ea7ff04130330a9e75ecbcd243d640c
36642102620faa102478e824124e347ed243dc23
/112A.cpp
fceae5e18f8b7ab7d3193866ae55333360c6bfc0
[]
no_license
Ajit021/Codeforces
483b769e53c05e2548353b9365eccb330bbf39e7
a3b08c39c862a9e4fc459a8d853c345b1109b958
refs/heads/master
2022-11-18T09:45:51.137985
2020-07-24T05:10:40
2020-07-24T05:10:40
282,121,912
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include<bits/stdc++.h> using namespace std; main() { string s; string s1; cin>>s>>s1; transform(s.begin(), s.end(), s.begin(), ::tolower); transform(s1.begin(), s1.end(), s1.begin(), ::tolower); if(s==s1) cout<<"0"; else if(s<s1) cout<<"-1"; else cout<<"1"; }
ff57ca89185995bc4e9a6cdef52bc70a5d736e94
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/libraries/fc/include/fc/crypto/sha1.hpp
1fd1cea8a330d66cbfa1b979db88e18bc3b2d184
[ "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
2,023
hpp
#pragma once #include <fc/fwd.hpp> #include <fc/string.hpp> namespace fc{ class sha1 { public: sha1(); explicit sha1( const string& hex_str ); string str()const; operator string()const; char* data()const; size_t data_size()const { return 20; } static sha1 hash( const char* d, uint32_t dlen ); static sha1 hash( const string& ); template<typename T> static sha1 hash( const T& t ) { sha1::encoder e; e << t; return e.result(); } class encoder { public: encoder(); ~encoder(); void write( const char* d, uint32_t dlen ); void put( char c ) { write( &c, 1 ); } void reset(); sha1 result(); private: struct impl; fc::fwd<impl,96> my; }; template<typename T> inline friend T& operator<<( T& ds, const sha1& ep ) { ds.write( ep.data(), sizeof(ep) ); return ds; } template<typename T> inline friend T& operator>>( T& ds, sha1& ep ) { ds.read( ep.data(), sizeof(ep) ); return ds; } friend sha1 operator << ( const sha1& h1, uint32_t i ); friend bool operator == ( const sha1& h1, const sha1& h2 ); friend bool operator != ( const sha1& h1, const sha1& h2 ); friend sha1 operator ^ ( const sha1& h1, const sha1& h2 ); friend bool operator >= ( const sha1& h1, const sha1& h2 ); friend bool operator > ( const sha1& h1, const sha1& h2 ); friend bool operator < ( const sha1& h1, const sha1& h2 ); uint32_t _hash[5]; }; class variant; void to_variant( const sha1& bi, variant& v ); void from_variant( const variant& v, sha1& bi ); } // namespace fc namespace std { template<> struct hash<fc::sha1> { size_t operator()( const fc::sha1& s )const { return *((size_t*)&s); } }; }
0bc1b51d509b6fe1d9adf215544e4163e4a5b245
f0e677fe5293bc60315fb70506d03ede72bba0f0
/Bond/Bond.h
15dd49e959b2e3e25d1bab697756e567ca049986
[]
no_license
evteevaa/bpoptim
886344dfe3e02b581cb1a562d93fd062b9b125e3
1194e5d3eaedd19d5a40ada882111f01041ea661
refs/heads/master
2020-08-03T17:20:31.686614
2019-09-30T09:56:18
2019-09-30T09:56:18
211,825,479
1
2
null
null
null
null
UTF-8
C++
false
false
1,073
h
/* * File: Bond.h * Author: melichron * * Created on 10 марта 2019 г., 21:53 */ #ifndef BOND_H #define BOND_H class Bond { public: Bond(); Bond(std::string bn, float cp, float cr, float ye, float NKD, float dur, int cpy=2, float nom=1000, float ys=0); Bond(const Bond& orig); Bond& operator=(const Bond& other); virtual ~Bond(); //variables std::string bondname; int coupons_per_year; // number of coupons at year float nominal; // nominal price float current_price; // price (part of nominal) float ytm_simple; // simple ytm (вообще, это простая доходность, но названа ytm; она не применяется в этой программе, но создана для возможного будущего развития класса) float coupon_rate; // rate of coupon float ytm_eff; // effective ytm float NKD; // nakoplennaya dohodnost' :) float duration; }; #endif /* BOND_H */
a0a9d01f37d162e884d3f1ee6dc9613e1cfdaa9b
c543e7e3c562ed6758fb82ff26e99f316bfbe098
/pacman/src/rendering/post_processing.h
d0a9458210963e61ebc2f677a7fe75392c078ce3
[]
no_license
Tikaszar/wacman
7b1ff88db86ae41d719f4aebd3a1862588cd6a75
cdab50e1a3bc97fa8a3d7ded0a1f453e25f02c33
refs/heads/master
2020-06-20T23:51:02.519935
2019-06-07T18:32:03
2019-06-07T18:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
h
#pragma once #include "shader_program.h" namespace pac { class PostProcessor { public: /*! * \brief The Filter enum describes the various filters that can be applied in post proccessing */ enum class Filter { BlackAndWhite, VerticalLines, SphericalDistort, ChromaticAbberation }; private: /*! * \brief The FrameBuffer struct represents all GL objects required to have a PP framebuffer */ struct FrameBuffer { unsigned renderbuffer = 0u; unsigned framebuffer = 0u; unsigned texture = 0u; }; /* Post processing framebuffer */ FrameBuffer m_framebuffer = {}; /* The post processing shader */ ShaderProgram m_shader; public: PostProcessor(); ~PostProcessor(); /*! * \brief capture begins capturing image information from any draw calls that are drawn. Call this before you draw anything * that you want to apply processing to */ void capture(); /*! * \brief process stops capturing and does the post processing work on all previously captured draw calls. Call this after you * have drawn what you want to apply effects to */ void process(); }; } // namespace pac
e915df1b0da23160b3c52c1f52c7c294b13dc451
ed6ce53c235e0bc64c0b86052829c488e123cabf
/hashing/0-sum-subarr.cpp
57d1cc018ce225e956c4c898e15d11d960328060
[ "MIT" ]
permissive
Strider-7/code
6a2cf94407c0d004fb6fbcdcb3679779e40b1eb0
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
refs/heads/master
2022-12-14T20:12:52.568623
2020-09-04T13:27:16
2020-09-04T13:27:16
292,848,664
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
#include <bits/stdc++.h> using namespace std; bool zeroSumSubarr(int arr[], int n) { unordered_set<int> s; int prefixSum = 0; for (int i = 0; i < n; i++) { prefixSum += arr[i]; if (s.find(prefixSum) != s.end()) { return true; } if (prefixSum == 0) return true; s.insert(prefixSum); } return false; } int main() { int arr[] = {1, 5, 3, -6, 4, -1}; int n = sizeof(arr) / sizeof(arr[0]); cout << zeroSumSubarr(arr, n); return 0; }
f6457b21befc7718d15ce2f76e8c0acc28d31a13
c48bee236ea2b2ae01d0aeda3cf6876ed7469275
/eng/eng/Engine/Core/OctSpacialPartisioning.h
d57fd835902429cbd3d11143b968388206b780a4
[]
no_license
blackmoondrago/Game-Engine-proto
eff6505e79fa8736313b291ccf88b8d62221c334
6664f39cda0351aabfa7a25d1337595db69e5abb
refs/heads/master
2020-12-01T23:35:25.074969
2019-12-29T23:47:44
2019-12-29T23:47:44
230,812,527
0
0
null
null
null
null
UTF-8
C++
false
false
1,159
h
#pragma once #include "..//Rendering/3D/GameObject.h" #include "..//Math/Ray.h" class OctNode { public: enum OctChildren { OCT_TLF, OCT_BLF, OCT_BRF, OCT_TRF, OCT_TLR, OCT_BLR, OCT_BRR, OCT_TRR }; OctNode(glm::vec3 position_, float size_, OctNode* parent_); ~OctNode(); void OnDestroy(); void Octify(int depth_); OctNode* GetParent(); OctNode* GetChild(OctChildren childPos_); void AddCollisons(GameObject* gameObject_); int GetObjectCount(); bool IsLeaf() const; BoundingBox* GetBoundingBox() const; int GetChildCount() const; private: friend class OctSpacialPartisioning; BoundingBox* octBounds; OctNode* parent; OctNode* children[8]; std::vector<GameObject*> objectList; float size; static int childNum; }; class OctSpacialPartisioning { public: GameObject* obj; OctSpacialPartisioning(float worldSize_); ~OctSpacialPartisioning(); void OnDestroy(); void AddObject(GameObject* obj_); GameObject* GetCollision(Ray ray_); private: OctNode* root; std::vector<OctNode*> rayIntersectionList; void AddObjectToCell(OctNode* cell_, GameObject* obj_); void PrepareCollisonQuery(OctNode* cell_, Ray ray_); };
cd9dd156c56a98ebc89fa49e8c8e6a3be27ece30
94dabf1490cc12e8c45a9fde6215351e43c743d7
/acmp/0384.cpp
1a19b4e265f355993b29b4c1aab168d0bd0001e3
[]
no_license
dmironov1993/acmp
a4d820ed3f39180dde282cc8fc666e9ff625b19e
63f3f30e9ce97b796b3a842428b156e3ad4f7fd0
refs/heads/master
2020-09-15T21:21:40.734882
2020-01-07T20:01:35
2020-01-07T20:01:35
223,558,981
1
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
//https://acmp.ru/index.asp?main=task&id_task=384 #include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { while (b) { a %= b; swap(a,b); } return a; } int main() { int i,j, f0 = 0, f1 = 1; cin >> i >> j; for (i = gcd(i,j); i > 0; i--) { int f = (f0 + f1) % 1000000000; f0 = f1; f1 = f; } cout << f0 << endl; }
7e431837ece567d5189b4f9f14de733a55f5ab40
24372fd346e16e7b7f173746f804cbe235f56d64
/share/log/logger.cpp
314dab8fd0b2d87c45ac746fb0b6bb70d4950b43
[]
no_license
jsonwu/zenus
ea1bb6e27bcc24aa98bace81177f7c5155fea7f4
d3c959c4a6674a6b7d321cd2dc29e2247001b138
refs/heads/master
2021-06-05T09:47:34.330019
2017-12-15T07:57:54
2017-12-15T07:57:54
22,098,160
1
1
null
null
null
null
UTF-8
C++
false
false
2,064
cpp
#include <stdarg.h> #include <stdio.h> #include <iostream> #include "logger.h" #include "thread_mutex_guard.h" #define MAX_LOG_BUFF_SIZE 4096 #define MAX_LOG_FILENAME_SIZE 512 logger::logger(string filename_pattern) :filename_pattern_(filename_pattern) { } logger::~logger() { if (this->writer_ != NULL) { delete this->writer_; this->writer_ = NULL; } if (this->filter_ != NULL) { delete this->filter_; this->filter_ = NULL; } if (this->layout_ != NULL) { delete this->layout_; this->layout_ = NULL; } } void logger::close() { this->writer_->close(); } int logger::open() { string file_name; this->logfile_name(file_name); thread_mutex_guard<thread_mutex_lock> lock(this->mutex_lock_); return this->writer_->open(file_name); } int logger::log(char *formate, ...) { if (this->writer_ == NULL) return -1; va_list args; va_start(args, formate); char buff[MAX_LOG_BUFF_SIZE] = {0}; vsnprintf(buff, MAX_LOG_BUFF_SIZE-1, formate, args); va_end(args); thread_mutex_guard<thread_mutex_lock> lock(this->mutex_lock_); int result = this->writer_->write(buff); return result; } int logger::log(logitem &item) { if (this->filter_ != NULL) { if (!this->filter_->pass(item)) return -1; } string write_msg; if (this->layout_ != NULL) { this->layout_->render(item, write_msg); }else { write_msg = item.msg(); } thread_mutex_guard<thread_mutex_lock> lock(this->mutex_lock_); this->writer_->write(write_msg); return 0; } void logger::set_layout(layout *l) { if (this->layout_ != NULL) delete this->layout_; this->layout_ = l; } void logger::set_filter(filter *f) { if (this->filter_ != NULL) delete this->filter_; this->filter_ = f; } void logger::set_writer(writer *w) { if (this->writer_ != NULL) delete this->writer_; this->writer_ = w; } void logger::logfile_name(string &file_name) { char buff[MAX_LOG_FILENAME_SIZE] = {0}; time_t now = time(NULL); struct tm *t = localtime(&now); strftime(buff, MAX_LOG_FILENAME_SIZE-1, this->filename_pattern_.c_str(), t); file_name = buff; }
fc96ed0281fb49a7cc4c75ac9c7cfb460a0db570
c608f260c7d836630762584b35c901688798c565
/exercise/src/coreUtil/Mesh.cpp
1b91f247b597ab1f43c2337a3c5f2314bfd2b3ed
[ "MIT" ]
permissive
softwarekid/crayon
3c87625c670c6690ffacd475e6dc2a577aabecbd
72fe08eab4b4282ad729ee2719e75df2f02f1def
refs/heads/master
2021-07-03T22:41:11.668328
2021-05-18T07:35:14
2021-05-18T07:35:14
46,350,637
0
0
null
null
null
null
UTF-8
C++
false
false
101
cpp
#include "Mesh.h" #include <GL/glut.h> void Mesh::Render() { glutSolidSphere(2.0, 10, 10); }
d0864bba8cebade59f893d72b2e90314483ae264
4e4083a4e6acea1fd3d87439ebd95b1ff4542eaa
/12. Tree Data Structure/HotelReviews.cpp
f3a1a3be69353133aff957caffbd4b86762c98ef
[]
no_license
niravnb/InterviewBit
c1ce460203b7cafad9e5fbcd1ee41c48f5a8f3d3
baa9b71c0a32207913324f0165f7bcd8c6294799
refs/heads/master
2020-08-22T09:09:11.843426
2019-12-15T06:35:21
2019-12-15T06:35:21
216,362,556
0
0
null
null
null
null
UTF-8
C++
false
false
3,917
cpp
/* Given a set of reviews provided by the customers for different hotels and a string containing “Good Words”, you need to sort the reviews in descending order according to their “Goodness Value” (Higher goodness value first). We define the “Goodness Value” of a string as the number of “Good Words” in that string. Note: Sorting should be stable. If review i and review j have the same “Goodness Value” then their original order would be preserved. You are expected to use Trie in an Interview for such problems Constraints: 1. 1 <= No.of reviews <= 200 2. 1 <= No. of words in a review <= 1000 3. 1 <= Length of an individual review <= 10,000 4. 1 <= Number of Good Words <= 10,000 5. 1 <= Length of an individual Good Word <= 4 6. All the alphabets are lower case (a - z) Input: S : A string S containing "Good Words" separated by "_" character. (See example below) R : A vector of strings containing Hotel Reviews. Review strings are also separated by "_" character. Output: A vector V of integer which contain the original indexes of the reviews in the sorted order of reviews. V[i] = k means the review R[k] comes at i-th position in the sorted order. (See example below) In simple words, V[i]=Original index of the review which comes at i-th position in the sorted order. (Indexing is 0 based) Example: Input: S = "cool_ice_wifi" R = ["water_is_cool", "cold_ice_drink", "cool_wifi_speed"] Output: ans = [2, 0, 1] Here, sorted reviews are ["cool_wifi_speed", "water_is_cool", "cold_ice_drink"] LINK: https://www.interviewbit.com/problems/hotel-reviews/ */ ///////////////////////////////////////////////////////////// // Using Trie ///////////////////////////////////////////////////////////// #define MAX 26 bool sortbysec(const pair<int,int> &a, const pair<int,int> &b) { if(a.first == b.first) return a.second < b.second; return (a.first > b.first); } struct trie{ bool end; struct trie* child[MAX]; }; struct trie* newNode(){ struct trie* tmp = new trie; tmp->end = false; for(int i = 0; i<MAX;i++) tmp->child[i] = NULL; return tmp; } void insert(struct trie* r, string s){ int l = s.length(); for(int i =0; i<l;i++){ int ind = s[i]-'a'; if(!r->child[ind]) r->child[ind] = newNode(); r = r->child[ind]; } r->end = true; } bool search(struct trie* r, string s){ int l = s.length(); for(int i =0; i<l;i++){ int ind = s[i]-'a'; if(!r->child[ind]) return false; r = r->child[ind]; } return r->end; } vector<int> Solution::solve(string A, vector<string> &B) { struct trie* t = newNode(); t->end = false; for(int i = 0, j = 0; i<A.length();i++){ if(A[i]=='_' || i==A.length()-1){ string test; if (A[i]=='_') test = A.substr(j,i-j); else test = A.substr(j,i-j+1); insert(t,test); j = i+1; } } vector<pair<int,int>> res; for(int k = 0; k<B.size();k++){ string A = B[k]; int count = 0; for(int i = 0, j = 0; i<A.length();i++){ if(A[i]=='_' || i==A.length()-1){ string test; if (A[i]=='_') test = A.substr(j,i-j); else test = A.substr(j,i-j+1); bool found = search(t,test); j = i+1; if(found) count++; // cout << test << " " << found << endl; } } res.push_back(make_pair(count,k)); } sort(res.begin(),res.end(),sortbysec); vector<int> ret; for(int i =0; i<res.size();i++){ // cout << res[i].first << " " << res[i].second << endl; ret.push_back(res[i].second); } return ret; }
6484c2449f456932b1a0db0fa696e814871a3fbf
14248aaedfa5f77c7fc5dd8c3741604fb987de5c
/luogu/P2167.cpp
87024f2dd63b21f16dc57e914c718c15c568419b
[]
no_license
atubo/online-judge
fc51012465a1bd07561b921f5c7d064e336a4cd2
8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b
refs/heads/master
2021-11-22T19:48:14.279016
2021-08-29T23:16:16
2021-08-29T23:16:16
13,290,232
2
0
null
null
null
null
UTF-8
C++
false
false
3,429
cpp
// https://www.luogu.org/problemnew/show/P2167 // [SDOI2009]Bill的挑战 #include <bits/stdc++.h> using namespace std; const int MOD = 1000003; int T, N, K; int dp_prev[1<<15], dp_curr[1<<15]; int f1[1<<15], f2[1<<15], f3[1<<15]; int ALL, LEN; char str[16][52]; int sub(int64_t a, int64_t b) { return (a + MOD - b) % MOD; } int mul(int64_t a, int64_t b) { return (a * b) % MOD; } void fmt1(int *f, int bits) { for (int i = 0; i < bits; i++) { for (int j = 0; j < (1<<bits); j++) { if (j>>i&1) { f[j] += f[j&(~(1U<<i))]; if (f[j] >= MOD) f[j] -= MOD; } } } } void fmt2(int *f, int bits) { for (int i = 0; i < bits; i++) { for (int j = 0; j < (1<<bits); j++) { if (j>>i&1) { f[j] -= f[j&(~(1U<<i))]; if (f[j] < 0) f[j] += MOD; } } } } void mobius(int *dp1, int *dp2) { for (int s = 0; s <= ALL; s++) { f1[s] = dp1[s^ALL]; f2[s] = dp2[s^ALL]; } fmt1(f1, N); fmt1(f2, N); for (int s = 0; s <= ALL; s++) { f3[s] = (1LL *f1[s] * f2[s]) % MOD; } fmt2(f3, N); for (int s = 0; s <= ALL; s++) { dp1[s] = f3[s^ALL]; } } void getMasks(int pos, int mask, int &in, int &out) { in = out = 0; for (int i = 0; i < N; i++) { char c = str[i][pos]; if ((mask>>i) & 1) { if (c == '?') in |= 1; else in |= 1<<(c-'a'+1); } else { if (c == '?') out |= 1; else out |= 1<<(c-'a'+1); } } } int getCount(int in, int out) { if (out&1) return 0; if (__builtin_popcount(in & (~1U)) > 1) return 0; if (__builtin_popcount(in & out) > 0) return 0; if ((in&(~1U)) == 0) return 26 - __builtin_popcount(out); else return 1; } void build(int pos, int *f) { for (int s = 1; s <= ALL; s++) { int in = 0, out = 0; for (int i = 0; i < N; i++) { char c = str[i][pos]; if ((s>>i) & 1) { if (c == '?') in |= 1; else in |= 1<<(c-'a'+1); } else { if (c == '?') out |= 1; else out |= 1<<(c-'a'+1); } } int ret = 0; if (out&1) ret = 0; else if (__builtin_popcount(in & (~1U)) > 1) ret = 0; else if (__builtin_popcount(in & out) > 0) ret = 0; else if ((in&(~1U)) == 0) ret = 26 - __builtin_popcount(out); else ret = 1; f[s] = ret; } } int solve() { scanf("%d%d", &N, &K); ALL = (1<<N)-1; for (int i = 0; i < N; i++) { scanf("%s", str[i]); } LEN = strlen(str[0]); if (K > N || K < 0) return 0; memset(dp_prev, 0, sizeof(dp_prev)); dp_prev[ALL] = 1; for (int i = 0; i < LEN; i++) { build(i, dp_curr); mobius(dp_prev, dp_curr); } if (K > 0) { int ans = 0; for (int s = 1; s <= ALL; s++) { if (__builtin_popcount(s) == K) (ans += dp_prev[s]) %= MOD; } return ans; } else { int ans = 1; for (int i = 0; i < LEN; i++) ans = mul(ans, 26); for (int s = 1; s <= ALL; s++) { ans = sub(ans, dp_prev[s]); } return ans; } } int main() { scanf("%d", &T); while (T--) { int ans = solve(); printf("%d\n", ans); } return 0; }
1dfef6ae0327f27e1476c7a6d61d4beff725b1bf
0f84b56717a0dc95466f0042d29e80e58d2bdb69
/SDD_ex/CircularList2/CircularList2/CircularList2.cpp
ffce89e256e06d42d7ba5196f02ef3e119f0288b
[]
no_license
cnicolae94/student_work
ea3e26d8b81081d59428c7bb0f1cc2b38878b916
2ffcd404bf5b1a1e4641ee8ff0644d97a7cb0998
refs/heads/main
2023-05-12T09:01:36.018985
2021-05-31T13:35:10
2021-05-31T13:35:10
355,815,060
0
0
null
null
null
null
UTF-8
C++
false
false
2,860
cpp
#include <iostream> using namespace std; struct produs { int cod; char* nume; }; struct nodls { produs inf; nodls* next, * prev; }; nodls* inserare(nodls* cap, nodls** coada, produs p) { nodls* nou = new nodls; nou->inf.cod = p.cod; nou->inf.nume = new char[strlen(p.nume) + 1]; strcpy_s(nou->inf.nume, strlen(p.nume) + 1, p.nume); nou->prev = NULL; nou->next = NULL; if (cap == NULL) { cap = nou; nou->prev = nou; nou->next = nou; *coada = nou; } else { nodls* temp = cap; while (temp->next != cap) { temp = temp->next; } temp->next = nou; nou->prev = temp; *coada = nou; (*coada)->next = cap; cap->prev = *coada; } return cap; } void traversare(nodls* cap) { nodls* temp = cap; while (temp->next != cap) { cout << "Cod: " << temp->inf.cod << "Nume: " << temp->inf.nume << endl; temp = temp->next; } cout << "Cod: " << temp->inf.cod << "Nume: " << temp->inf.nume << endl; } void traversareInversa(nodls* coada) { nodls* temp = coada; while (temp->prev != coada) { cout << "Cod: " << temp->inf.cod << "Nume: " << temp->inf.nume << endl; temp = temp->prev; } cout << "Cod: " << temp->inf.cod << "Nusme: " << temp->inf.nume << endl; } void dezalocare(nodls* cap) { nodls* temp = cap; while (temp->next != cap) { nodls* temp2 = temp->next; delete[] temp->inf.nume; delete[] temp; temp = temp2; } delete[] temp->inf.nume; delete[] temp; } int main() { int n; produs p; nodls* cap = NULL; nodls* coada = NULL; cout << "Nr produse" << endl; cin >> n; char buffer[20]; for (int i = 0; i < n; i++) { cout << "Introdu cod" << endl; cin >> p.cod; cout << "Introdu nume" << endl; cin >> buffer; p.nume = new char[strlen(buffer) + 1]; strcpy_s(p.nume, strlen(buffer) + 1, buffer); cap = inserare(cap, &coada, p); } traversare(cap); traversareInversa(coada); dezalocare(cap); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
eeb0a1efd846ecb4f19fe81214ff2b679fad819a
11b6f11e1aba9a1021c4a0eeb79e086e4fdd41a2
/opp.lab1/lab1.cpp
0386822ffb10c7b25d0ab67912ff29b7a34df584
[]
no_license
gundone2001/oop.2020
1af271ba8ef3f79382163eae4e57b9823df3da54
54fd711d550bb2a66e6aa140803a3c4ca58ee890
refs/heads/master
2023-01-11T07:45:03.376490
2020-11-07T17:53:58
2020-11-07T17:53:58
297,077,902
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include <iostream> #include "Prog1.h" using namespace Prog1; //основная функция int main() { Matrix SparseMatrix = { 0,0,nullptr }; Matrix ResMarix = { 0,0,nullptr }; print_menu(); variant(SparseMatrix); if (!(SparseMatrix.header)) { std::cout << "incorrect data" << std::endl; return 1; } copymatrix(SparseMatrix, ResMarix);// Создание второго массива sortmatrix(ResMarix);//сортировка по условию output("Sourced matrix",SparseMatrix);// Вывод матрицы output("Sorted matrix",ResMarix);// Вывод матрицы erase(SparseMatrix);// Освобождение памяти erase(ResMarix);// Освобождение памяти return 0; }
11abd4c73d389c07c8325250e9c30b62f9b44ef1
0b8515326d4cb6a2e72318d256ed929aa04dff20
/content/browser/media/capture/image_capture_impl.h
8ca23dae59b31de51a450dab104a3010809e8bff
[ "BSD-3-Clause" ]
permissive
wuhengzhi/chromium-crosswalk
0c6aaec514a3952123616679399f84769019a9de
b5d9bfd4f53d132beab079ed59c6e1ae5d14fe98
refs/heads/master
2022-11-11T08:03:41.115014
2016-08-25T07:37:50
2016-08-25T07:37:50
25,424,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,290
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_MEDIA_CAPTURE_IMAGE_CAPTURE_IMPL_H_ #define CONTENT_BROWSER_MEDIA_CAPTURE_IMAGE_CAPTURE_IMPL_H_ #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/string.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "third_party/WebKit/public/platform/modules/imagecapture/image_capture.mojom.h" namespace content { class ImageCaptureImpl : public blink::mojom::ImageCapture { public: static void Create( mojo::InterfaceRequest<blink::mojom::ImageCapture> request); ~ImageCaptureImpl() override; void GetCapabilities(const mojo::String& source_id, const GetCapabilitiesCallback& callback) override; void TakePhoto(const mojo::String& source_id, const TakePhotoCallback& callback) override; private: explicit ImageCaptureImpl( mojo::InterfaceRequest<blink::mojom::ImageCapture> request); mojo::StrongBinding<blink::mojom::ImageCapture> binding_; DISALLOW_COPY_AND_ASSIGN(ImageCaptureImpl); }; } // namespace content #endif // CONTENT_BROWSER_MEDIA_CAPTURE_IMAGE_CAPTURE_IMPL_H_
c0f2e6fe65bd43b672d4c2491a5c6abf63ef5182
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/RangesOfConfiguration/UNIX_RangesOfConfiguration.h
d824b7248e2fb6522e1705e9bc45c83bfac2fb69
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
2,676
h
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifndef __UNIX_RANGESOFCONFIGURATION_H #define __UNIX_RANGESOFCONFIGURATION_H #include "CIM_Dependency.h" #include "UNIX_RangesOfConfigurationDeps.h" #define PROPERTY_ENABLE_ADVERTISE "EnableAdvertise" class UNIX_RangesOfConfiguration : public CIM_Dependency { public: UNIX_RangesOfConfiguration(); ~UNIX_RangesOfConfiguration(); virtual Boolean initialize(); virtual Boolean load(int&); virtual Boolean finalize(); virtual Boolean find(Array<CIMKeyBinding>&); virtual Boolean validateKey(CIMKeyBinding&) const; virtual void setScope(CIMName); virtual Boolean getAntecedent(CIMProperty&) const; virtual CIMInstance getAntecedent() const; virtual Boolean getDependent(CIMProperty&) const; virtual CIMInstance getDependent() const; virtual Boolean getEnableAdvertise(CIMProperty&) const; virtual Boolean getEnableAdvertise() const; private: CIMName currentScope; # include "UNIX_RangesOfConfigurationPrivate.h" }; #endif /* UNIX_RANGESOFCONFIGURATION */
70df201d0d65ac63a34cea16dc3ed77d0eee600c
1434a7db58d831dd6a64fa564861b30fc1ce2dc5
/cpp/equation-solver/src/Coefficient.cpp
3649a4ae6036218479347c8b380501b654ce912c
[ "Apache-2.0" ]
permissive
reverse-gad/lookwhaticando
67e507df3c5b2559de5c4b9ed21a78dc7ffec6eb
46dae592ad1664e9439c71dee285340a3e55ed5f
refs/heads/master
2020-11-27T14:35:57.550514
2017-02-28T14:57:24
2017-02-28T14:57:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,684
cpp
#include "Coefficient.hpp" Coefficient::Coefficient(double newXExp, std::initializer_list<Variable> newFactors) : xExp(newXExp) { factors.insert(factors.begin(), newFactors.begin(), newFactors.end()); } void Coefficient::derive() { factors.push_back(Variable(xExp)); xExp -= 1.0; } void Coefficient::insert(double x) { double temp = pow(x, xExp); xExp = 0.0; factors.push_back(Variable(temp)); } bool Coefficient::hasVariable(unsigned int id) { for(Variable& v : factors) if(v.getId() && v.getId().value() == id) return true; return false; } double Coefficient::getNumericalFactor() { double ret = 0.0; for(Variable& v : factors) if(v.getValue()) ret = v.getValue().value(); return ret; } bool Coefficient::clean() //returns true if this coefficient can be removed (one of its factors is 0 so it becomes 0) { double temp = 1.0; auto it = factors.begin(); while(it != factors.end()) { it->clean(); if(it->getValue()) { temp *= it->getValue().value(); it = factors.erase(it); continue; } ++it; } if(temp == 0.0) return true; factors.insert(factors.begin(), Variable(temp)); return false; } std::string Coefficient::asString() { std::ostringstream stm; unsigned int i = 0; for(Variable& v : factors) { if(v.getValue()) stm << v.getValue().value(); else stm << static_cast<char>('a' + v.getId().value()); if(i != factors.size()-1) stm << "*"; i++; } if(xExp != 0.0) { if(factors.size() != 0) stm << "*"; stm << "x"; if(xExp != 1.0) stm << "^" << xExp; } return stm.str(); }
2e9088abd3928a064d93f27b5a1c6494de22027a
48b23a49c093e8303b90ed6335e61d64362e40af
/shazhko-artem/src/shazhko05/Wheel.cpp
c785d82f85470bb854934288cf7115c90c268f7e
[ "MIT" ]
permissive
zeienko-vitalii/se-cpp
e5b7d1d8800e2a5c777e76cc9cfd30d898400282
54a5dfb2e98af099fbfaef129a7fe03a7b815d6f
refs/heads/master
2021-08-15T15:22:30.559011
2017-11-17T22:37:45
2017-11-17T22:37:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,225
cpp
/** * @file Wheel.cpp * @brief Содержит реализацию класса Wheel * @author Shazhko Artem * @version 0 * @date 03.10.17 */ #include "Wheel.h" #define _USE_MATH_DEFINES // for C++ #include "SimpleStreamHelperFactory.h" #include <sstream> Wheel::Wheel() : diameter(0), width(0), units(EUNITS_CENTIMETERS) { } Wheel::Wheel(double _diameter, double _width, EUnits _units) : diameter(_diameter), width(_width), units(_units) {} Wheel::Wheel(const Wheel *_wheel) { if (_wheel == NULL) { this->diameter = 0; this->units = EUNITS_CENTIMETERS; this->width = 0; return; } this->diameter = _wheel->diameter; this->units = _wheel->units; this->width = _wheel->width; } bool Wheel::operator==(Wheel const &arg) { if (this->diameter != arg.diameter)return false; if (this->units != arg.units)return false; if (this->width != arg.width)return false; return true; } void Wheel::OnStore(std::ostream & aStream) { StreamHelperFactory *streamHelperFactory = new SimpleStreamHelperFactory(); OutputStreamHelper *oStream = streamHelperFactory->CreateOutputStreamHelper(aStream); StreamHelperArg *data = new StreamHelperArg(); std::stringstream ss; data->nameVulue = "diameter"; ss << this->diameter; ss >> data->value; ss.clear(); oStream->Write(data); data->nameVulue = "units"; ss << this->units; ss >> data->value; ss.clear(); oStream->Write(data); data->nameVulue = "width"; ss << this->width; ss >> data->value; ss.clear(); oStream->Write(data); delete streamHelperFactory; delete oStream; delete data; } void Wheel::OnLoad(std::istream & aStream) { StreamHelperFactory *streamHelperFactory=new SimpleStreamHelperFactory(); InputStreamHelper *iStream = streamHelperFactory->CreateInputStreamHelper(aStream); StreamHelperArg *data=NULL; std::stringstream ss; int loadCount=3; while (!iStream->isEnd() && loadCount!=0) { data = iStream->Read(); if (!data)continue; if (std::string("diameter") == data->nameVulue) { ss << data->value.c_str(); ss >> this->diameter; ss.str(""); ss.clear(); loadCount--; } else if (std::string("width") == data->nameVulue) { ss << data->value.c_str(); ss >> this->width; ss.str(""); ss.clear(); loadCount--; } else if (std::string("units") == data->nameVulue) { ss << data->value.c_str(); int iValue = 0; ss >> iValue; this->units=(EUnits)iValue; ss.str(""); ss.clear(); loadCount--; } if(data) delete data; } delete streamHelperFactory; delete iStream; } Wheel::~Wheel() { } double Wheel::Volume() const { if (diameter == 0) return 0; return 3.14159*pow(diameter / 2, 2)*width; // V=πR^2/h пускай колесо это цилиндр =) } void Wheel::SetDiameter(const double _diameter) { this->diameter = _diameter; } void Wheel::SetWidth(const double _width) { this->width = _width; } void Wheel::SetUnits(const EUnits _units) { this->units = _units; } EUnits Wheel::GetUnits() const { return this->units; } double Wheel::GetDiameter() const { return diameter; } double Wheel::GetWidth() const { return this->width; }
a0f20998a403f0405b12c09bd6b8e2cb90d51cf1
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/ui/uiparent.cpp
cadfd6e4fae50a8d92ab668bb49efa2ffd66a397
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
/* * uiparent.cpp * * Created on: 2.8.2011 * Author: akin */ #include "uiparent.h" namespace ice { UIParent::UIParent() { } UIParent::~UIParent() { } } /* namespace ice */
[ "akin@lich" ]
akin@lich
2d4a6e79536c4defb78283242232499237a71a4b
109c56c286dc91c12d7a9bd8cd98431c45e56696
/Array/ArrayRotation.cpp
209ffa367d8bc9371c9a3cc2a438cdda2807ebca
[]
no_license
zehao-ba/Data-Structure-Exercise
b965cc9e71f8650e8da1894b56a995b1992075b8
a97cb34cf6df419132317d5ea2a25f5046117c07
refs/heads/master
2018-10-26T23:48:51.380656
2018-08-22T01:53:48
2018-08-22T01:53:48
118,995,100
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
#include<iostream> using namespace std; void RotateByone(int arry[], int n){ int temp, i; temp = arry[0]; for(i = 0; i<n-1; i++ ) arry[i] = arry[i+1]; arry[i] = temp; } void RotateLeft(int arry[], int n, int d){ int i; for (i = 0; i<d; i++) RotateByone(arry,n); } void print(int arry[], int size){ int i; for (i = 0; i<size; i++) cout<<arry[i]; } int main(){ int arry[] = {1,2,3,4,5,6,7}; RotateLeft(arry,7,2); print(arry, 7); }
c23326445ca9fc22fbe630a555f65eca64e0b593
2e58ccc2455f302cb6c97847553c804567444ad2
/CLion/HashMap/HashMap.h
04eaedd81a29a286e69453bbaf95610548cb8caf
[]
no_license
octaviodimarco/Entrega
c7991d615e85ecdd7057d229a0a95b2c72d9a11e
ea559f166093ed4cf82710be40d9dca4fe53d349
refs/heads/master
2020-04-05T18:25:23.666915
2018-11-14T05:52:52
2018-11-14T05:52:52
157,101,325
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
#ifndef HASHMAP_H #define HASHMAP_H template<class K, class T> class HashMap { private: unsigned int hashFunc(K clave); static unsigned int hashFuncDefault(K clave) { return 0; }; unsigned int (*hashFuncP)(K clave); T **datos; //puntero a puntero unsigned int tam; public: HashMap(unsigned int k); HashMap(unsigned int k, unsigned int (*hashFuncP)(K clave)); T get(K clave); void put(K clave, T valor); void remove(K clave); ~HashMap(); bool esVacio(); }; template<class K, class T> HashMap<K, T>::HashMap(unsigned int k) { datos = new T *[k]; tam = k; hashFuncP = this->hashFuncDefault; for (int i = 0; i < k; ++i) datos[i] = nullptr; } template<class K, class T> HashMap<K, T>::HashMap(unsigned int k, unsigned int (*fp)(K)) { datos = new T *[k]; tam = k; hashFuncP = fp; //Puntero de funcion, basicamente le da otro nombre a una funcion for (int i = 0; i < k; ++i) datos[i] = nullptr; } template<class K, class T> HashMap<K, T>::~HashMap() { for (int i = 0; i < tam; ++i) if (datos[i] != nullptr) delete datos[i]; } template<class K, class T> T HashMap<K, T>::get(K clave) { unsigned int idx = hashFunc(clave); if (datos[idx] == nullptr) throw 404; return *datos[idx]; //Devuelvo el contenido } template<class K, class T> void HashMap<K, T>::put(K clave, T valor) { unsigned int idx = hashFunc(clave); if (datos[idx] != nullptr) //Este es el caso en que haya colision throw 1; datos[idx] = new T; *datos[idx] = valor; // El contenido del array es lo que tengo que guardar } template<class K, class T> void HashMap<K, T>::remove(K clave) { unsigned int idx = hashFunc(clave); if (datos[idx] == nullptr) throw 404; delete datos[idx]; } template<class K, class T> bool HashMap<K, T>::esVacio() { return false; } template<class K, class T> unsigned int HashMap<K, T>::hashFunc(K clave) { return hashFuncP(clave) % tam; //Esta funcion asegura que no mme pase del tamaño } #endif //HASHMAP_H
dc82d4428675834272a13e8a00018365d7fc2550
be5b2a65fa71e1d91f255d83acd4662105fa04db
/HW_3/part1/csce310hw03pt01.cpp
dd81db60a9280bae983daac99142bc5a45e6d632
[]
no_license
CaseyNolte22/CSCE310
fa0b25531956e324cf2b40d92fff32dc5d46869e
7c5f235ef8c245e2300783a6a45d471195b29610
refs/heads/main
2023-04-13T11:13:25.307208
2021-04-27T19:01:48
2021-04-27T19:01:48
339,200,746
0
0
null
null
null
null
UTF-8
C++
false
false
2,775
cpp
#include <iostream> #include <cstdio> #include <list> #include <vector> #include "csce310hw03pt01.h" using namespace std; class undirected { int vertexes; list<int> *connected; bool LoopTest(int vertex, bool visited[], int root); public: undirected(int vertexes); void addEdge(int vertex1, int vertex2); bool Loop(); }; void undirected::addEdge(int vertex1, int vertex2) { connected[vertex1].push_back(vertex2); connected[vertex2].push_back(vertex1); } undirected::undirected(int vertexes) { this->vertexes = vertexes; connected = new list<int>[vertexes]; } bool undirected::LoopTest(int vertex, bool visited[], int root) { list<int>::iterator i; visited[vertex] = 1; for (i = connected[vertex].begin(); i != connected[vertex].end(); ++i) { if (!visited[*i]) { if (LoopTest(*i, visited, vertex)) { return 1; } } else if (*i != root) { return 1; } } return 0; } bool undirected::Loop() { bool *visited = new bool[vertexes]; for (int i = 0; i < vertexes; i++) { visited[i] = false; } for (int j = 0; j < vertexes; j++) { if (!visited[j]) { if (LoopTest(j, visited, -1)) { return 1; } } } return 0; } double maximumST(vector<vector<double>> adjacencyMatrix) { cerr << endl; int maximumSpanning = 0; int n = adjacencyMatrix[0].size(); bool nodeVisited[n]; int maxWeight = 0; int edgei, edgej = 0; for (int i = 0; i < n; i++) { nodeVisited[i] = false; for (int j = 0; j < n; j++) { int value = adjacencyMatrix[i][j]; fprintf(stderr, "% 3d ", value); } cerr << endl; } vector<int> edgeWeights; vector<vector<int>> pointSet; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (adjacencyMatrix[i][j] != 0) { edgeWeights.push_back(adjacencyMatrix[i][j]); vector<int> points = {i, j}; pointSet.push_back(points); } } } for (int i = 0; i < edgeWeights.size() - 1; i++) { for (int j = 0; j < edgeWeights.size() - i - 1; j++) { if (edgeWeights[j] < edgeWeights[j + 1]) { swap(edgeWeights[j], edgeWeights[j + 1]); swap(pointSet[j], pointSet[j + 1]); } } } for (int i = 0; i < pointSet.size(); i++) { undirected tester(pointSet.size()); for (int j = 0; j <= i; j++) { int pog1 = pointSet[j][0]; int pog2 = pointSet[j][1]; if (pog1 == -1) { continue; } tester.addEdge(pog1, pog2); } int flag = tester.Loop(); if (!flag) { maximumSpanning += edgeWeights[i]; } else { pointSet[i][0] = -1; pointSet[i][1] = -1; } } return maximumSpanning; }
d3dcd32e32c272b9e4a869dc1ce865d4ea68fea9
8d20bdbb889a8a784561ec741ec464d18851ef8a
/Function.cpp
7373ef6c97a3cff0ed02f34c1343065853c3de37
[]
no_license
DENISH220/C-Program
406b01cab6dcf29a0efb399499308371a37faa5c
175fc396fc59c9736a48c72312c796f13d6a1e88
refs/heads/master
2022-12-11T16:44:25.624079
2020-09-06T03:38:21
2020-09-06T03:38:21
293,191,036
1
0
null
null
null
null
UTF-8
C++
false
false
701
cpp
//Function area () is overloading three time #include <iostream> using namespace std; //Declaration of funtion prototypes int area(int); int area(int, int); float areas(float); int main() { cout<<"calling the area () funtion for computing the area of square(side=5):"<<area(5)<<"\n"; cout<<"calling the area () funtion for computing the area of rectangle(length=5,breadth=10):"<<area(5,10)<<"\n"; cout<<"calling the area () funtion for computing the area of circle (radius=5.5):"<<areas(5.5); return 0; } int area (int side) { return(side*side); } int area (int length,int breadth) { return(length*breadth); } float areas (float radius) { return(3.14*radius*radius); }
435d557cf7b3502bf4b1bc6aa3e7f271dff350cd
66e6360325b781ed0791868765f1fd8a6303726f
/LQSearch/BTaggingAndMRScaling/6743/MakePlots.cpp
1aea0aea1fe9d071cbaf29e16c2bf12f4bd6103a
[]
no_license
alintulu/FHead2011PhysicsProject
c969639b212d569198d8fce2f424ce866dcfa881
2568633d349810574354ad61b0abab24a40e510e
refs/heads/master
2022-04-28T14:19:30.534282
2020-04-23T17:17:32
2020-04-23T17:17:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,101
cpp
#include <string> #include <vector> using namespace std; #include "TROOT.h" #include "TStyle.h" #include "TGraphErrors.h" #include "DataHelper.h" #include "PlotHelper2.h" int main() { gROOT->SetStyle("Plain"); DataHelper DHFile("CollectResult.dh"); PsFileHelper PsFile("ParameterDependenceOnBTag.ps"); PsFile.AddTextPage("Parameter dependence on b-tagging"); TGraphErrors GB, GMROffset, GR2Offset; GB.SetNameTitle("ParameterB", "Parameter B"); GMROffset.SetNameTitle("ParameterMROffset", "Parameter MROffset"); GR2Offset.SetNameTitle("ParameterR2Offset", "Parameter R2Offset"); const vector<string> States = DHFile.GetListOfKeys(); for(int i = 0; i < (int)States.size(); i++) { double Jet1TCHELimit = DHFile[States[i]]["Jet1TCHELimit"].GetDouble(); double B = DHFile[States[i]]["B"].GetDouble(); double BError = DHFile[States[i]]["BError"].GetDouble(); double MROffset = DHFile[States[i]]["MROffset"].GetDouble(); double MROffsetError = DHFile[States[i]]["MROffsetError"].GetDouble(); double R2Offset = DHFile[States[i]]["R2Offset"].GetDouble(); double R2OffsetError = DHFile[States[i]]["R2OffsetError"].GetDouble(); if(Jet1TCHELimit < -500) Jet1TCHELimit = -1; GB.SetPoint(i, Jet1TCHELimit, B); GB.SetPointError(i, 0, BError); GMROffset.SetPoint(i, Jet1TCHELimit, MROffset); GMROffset.SetPointError(i, 0, MROffsetError); GR2Offset.SetPoint(i, Jet1TCHELimit, R2Offset); GR2Offset.SetPointError(i, 0, R2OffsetError); } TCanvas CB; GB.Draw("ape"); GB.GetHistogram()->GetXaxis()->SetTitle("Cut position (TCHE) on leading jet"); PsFile.AddCanvas(CB); TCanvas CMROffset; GMROffset.Draw("ape"); GMROffset.GetHistogram()->GetXaxis()->SetTitle("Cut position (TCHE) on leading jet"); PsFile.AddCanvas(CMROffset); TCanvas CR2Offset; GR2Offset.Draw("ape"); GR2Offset.GetHistogram()->GetXaxis()->SetTitle("Cut position (TCHE) on leading jet"); PsFile.AddCanvas(CR2Offset); PsFile.AddTimeStampPage(); PsFile.Close(); }
d74d08a9743f4e81719078ede6c2b3a45d309686
368bc40b7004951f227f6b931aeafaea44426420
/mainwindowbis.h
0d6fd9b8b62f0b3bee1abc845ee9e2b6d79976ea
[]
no_license
LilyOfTheWest/OntologyTool
2f2bc13a3f92f86ff54751f50dcdf6aef1059fe8
e8ef03a67cb0a424bb86c54ac864052337ff5063
refs/heads/master
2021-04-15T14:30:16.400182
2016-06-06T12:26:11
2016-06-06T12:26:11
60,525,217
0
0
null
null
null
null
UTF-8
C++
false
false
315
h
#ifndef MAINWINDOWBIS_H #define MAINWINDOWBIS_H #include <QMainWindow> namespace Ui { class MainWindowBIS; } class MainWindowBIS : public QMainWindow { Q_OBJECT public: explicit MainWindowBIS(QWidget *parent = 0); ~MainWindowBIS(); private: Ui::MainWindowBIS *ui; }; #endif // MAINWINDOWBIS_H
3edf47b13451a077945804ead7293087b1d5c3a4
ff3ce61334d6d1a65ee1076dd92053111f403ce6
/PAT/1010.cpp
7b7f1472e0a10473127ce1360b4b9b30133363ee
[]
no_license
JuntaoLiu01/LeetCode
0c6053cb3eacb02ed6daa91fd11feaff967c8a2c
28bdee75301d4edd34f8b9edbdb307f925e02a06
refs/heads/master
2020-03-23T14:37:21.557481
2020-01-16T07:52:21
2020-01-16T07:52:21
141,688,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
#include <iostream> #include <cctype> #include <math.h> #include <algorithm> using namespace std; long long convert(string num,long long radix){ long long sum = 0; int index = 0,temp = 0; for(int i = num.size()-1;i >=0;i--){ temp = isdigit(num[i])?num[i]-'0':num[i]-'a'+10; sum += temp*pow(radix,index++); } return sum; } long long find(string num,long long target){ char ch = *max_element(num.begin(),num.end()); long long low = (isdigit(ch)?ch-'0':ch-'a'+10)+1; long long high = max(target,low); while(low <= high){ long long mid = (low+high)/2; long long t = convert(num,mid); if(t==target) return mid; else if(t < 0 || t > target) high = mid-1; else low = mid+1; } return -1; } int main(){ string n1,n2; long long tag,radix; cin>>n1>>n2>>tag>>radix; long long num,res; if(tag==1){ num = convert(n1,radix); res = find(n2,num); } else{ num = convert(n2,radix); res = find(n1,num); } if(res==-1) cout<<"Impossible"; else cout<<res; return 0; }
16ed466726fb0b73c6eb5350f31b2a129b24abba
452ba5f01bbea2a7827bbadfa7761c1505d973c8
/ui/editor/roadbuilder.cc
9cb4df473a3880cba1db6b78225d75512948f7e0
[ "MIT" ]
permissive
torokati44/LIMoSim
08dc2b7da426f8222572cb15d22e9e13616cd1d8
e831434d5d40e4fb5287d3e0aea15099d3eac75b
refs/heads/master
2021-06-29T14:23:46.771940
2017-09-13T09:05:12
2017-09-13T09:14:08
103,378,010
0
0
null
2017-09-13T09:05:20
2017-09-13T09:05:20
null
UTF-8
C++
false
false
7,492
cc
#include "roadbuilder.h" #include "ui/uimanager.h" #include "ui/map/mapui.h" #include "ui/map/pathlayer.h" #include "ui/map/nodeui.h" #include <QGuiApplication> #include "LIMoSim/sim/simulation.h" #include "ui/editor/selectionhandler.h" #include "ui/qteventscheduler.h" #include "ui/map/mapui.h" namespace LIMoSim { RoadBuilder *roadBuilderInstance = 0; RoadBuilder::RoadBuilder(QObject *_parent) : QObject(_parent), p_map(Map::getInstance()), p_uiManager(UiManager::getInstance()), p_pathLayer(0), p_selectedNode(0), p_selectedSegment(0), p_currentWay(0) { roadBuilderInstance = this; } RoadBuilder* RoadBuilder::getInstance() { if(!roadBuilderInstance) roadBuilderInstance = new RoadBuilder(); return roadBuilderInstance; } /************************************* * PUBLIC METHODS * ************************************/ void RoadBuilder::clear() { p_selectedNode = 0; p_selectedSegment = 0; p_currentWay = 0; } void RoadBuilder::handleKey(int _key) { QtEventScheduler *scheduler = dynamic_cast<QtEventScheduler*>(Simulation::getInstance()->getEventScheduler()); if(_key==Qt::Key_Delete) { if(p_selectedNode) deleteNode(p_selectedNode); else if(p_selectedSegment) deleteSegment(p_selectedSegment); } else if(_key==Qt::Key_Right) scheduler->step(); else if(_key==Qt::Key_Up) scheduler->start(); else if(_key==Qt::Key_Down) scheduler->stop(); else if(_key>=48 && _key<=57 ) // numeric { int value = _key - 48; bool ctrlPressed = (QGuiApplication::keyboardModifiers()==Qt::ControlModifier); SelectionHandler *selectionHandler = SelectionHandler::getInstance(); } else if(_key==Qt::Key_A) { Car *car = Map::getInstance()->getCar("0"); car->switchToLeftLane(); } else if(_key==Qt::Key_D) { Car *car = Map::getInstance()->getCar("0"); car->switchToRightLane(); } else if(_key==Qt::Key_Space) MapUi::getInstance()->centerInViewPort(); else if(_key==Qt::Key_Plus) { MapUi::getInstance()->zoomIn(); } else if(_key==Qt::Key_Minus) { MapUi::getInstance()->zoomOut(); } else qDebug() << "RoadBuilder::handleKey" << _key; } void RoadBuilder::registerNode(NodeUi *_node) { connect(_node, SIGNAL(leftClicked()), this, SLOT(onNodeLeftClicked())); connect(_node, SIGNAL(rightClicked()), this, SLOT(onNodeRightClicked())); } void RoadBuilder::selectNode(NodeUi *_node) { // deselect the previous node if(p_selectedNode) p_selectedNode->setSelection(SELECTION::NO_SELECTION); if(p_selectedSegment) { p_selectedSegment->setSelection(SELECTION::NO_SELECTION); p_selectedSegment = 0; } // select the new node p_selectedNode = _node; p_selectedNode->setSelection(SELECTION::HARD_SELECTION); } void RoadBuilder::deleteNode(NodeUi *_node) { // unhighlight all highlighted destinates QList<NodeUi*> destinations = p_selectedNode->updateDestinations(); for(int i=0; i<destinations.size(); i++) destinations.at(i)->softDeselection(); // delete the ui part p_uiManager->removeNode(_node); p_selectedNode = 0; } void RoadBuilder::registerSegment(SegmentMarker *_segment) { connect(_segment, SIGNAL(leftClicked()), this, SLOT(onSegmentLeftClicked())); } void RoadBuilder::selectSegment(SegmentMarker *_segment) { // deselect the previous node if(p_selectedSegment) p_selectedSegment->setSelection(SELECTION::NO_SELECTION); if(p_selectedNode) { p_selectedNode->setSelection(SELECTION::NO_SELECTION); p_selectedNode = 0; } // select the new node p_selectedSegment = _segment; p_selectedSegment->setSelection(SELECTION::HARD_SELECTION); } void RoadBuilder::deleteSegment(SegmentMarker *_segment) { // TODO: Segment *segment = _segment->getSegment(); segment->getWay()->removeSegment(segment); // delete the ui part p_uiManager->removeSegment(_segment); p_pathLayer->update(); p_selectedSegment = 0; } void RoadBuilder::deselectAll() { if(p_selectedNode) { p_selectedNode->setSelection(SELECTION::NO_SELECTION); p_selectedNode = 0; } if(p_selectedSegment) { p_selectedSegment->setSelection(SELECTION::NO_SELECTION); p_selectedSegment = 0; } p_currentWay = 0; } void RoadBuilder::registerPathLayer(PathLayer *_pathLayer) { p_pathLayer = _pathLayer; connect(p_pathLayer, SIGNAL(mapPositionClicked(Position)), this, SLOT(onMapPositionClicked(Position))); } NodeUi* RoadBuilder::createNode(const Position &_position, bool _link) { // create a new node Node *node = p_map->createNode(_position); node->setPosition(_position); NodeUi *ui = p_uiManager->addNode(node); // if there is no way yet, create a new one if(_link && p_selectedNode && !p_currentWay) createWayWithNode(); // select the new node selectNode(ui); return ui; } void RoadBuilder::createSegmentUi(Segment *_segment) { // create a new segment marker and update the path layer to display the way if(_segment) { _segment->linkLanes(); p_uiManager->addSegment(_segment); p_uiManager->getNodeUi(_segment->getStartGate()->node)->handleMovement(); p_uiManager->getNodeUi(_segment->getEndGate()->node)->handleMovement(); p_pathLayer->update(); } } void RoadBuilder::createWayWithNode() { p_currentWay = p_map->createWay(); p_currentWay->setType(WAY_TYPE::PRIMARY_HIGHWAY); //p_currentWay->setIsOneway(true); //p_currentWay->setLanes(1, 1, 0, 0); p_currentWay->addNode(p_selectedNode->getNode()); } /************************************* * PRIVATE SLOTS * ************************************/ void RoadBuilder::onMapPositionClicked(const Position &_position) { if(QGuiApplication::keyboardModifiers()==Qt::ShiftModifier) { NodeUi *node = createNode(_position, true); // link the node if(p_currentWay) { Segment *segment = p_currentWay->addNode(node->getNode()); createSegmentUi(segment); } } else { deselectAll(); SelectionHandler::getInstance()->clearSelection(); } } void RoadBuilder::onNodeLeftClicked() { NodeUi *nodeUi = qobject_cast<NodeUi*>(QObject::sender()); if(nodeUi) { // select the node selectNode(nodeUi); p_currentWay = 0; } } void RoadBuilder::onNodeRightClicked() { bool modifier = QGuiApplication::keyboardModifiers()==Qt::ShiftModifier; NodeUi *nodeUi = qobject_cast<NodeUi*>(QObject::sender()); if(modifier && nodeUi && nodeUi!=p_selectedNode) // ensure that start and destination are different { if(!p_currentWay && p_selectedNode) createWayWithNode(); // if(p_currentWay) { Segment *segment = p_currentWay->addNode(nodeUi->getNode()); createSegmentUi(segment); // select the destination node selectNode(nodeUi); } } } void RoadBuilder::onSegmentLeftClicked() { SegmentMarker *segment = qobject_cast<SegmentMarker*>(QObject::sender()); if(segment) { selectSegment(segment); } } }
8523d64519391b7aa3a831c7b44e842cf6df4b68
dda21f4378e37cf448d17b720da4a1c9eb2b24d7
/SDK/SB_BP_Effect_Player_BurningDOT_functions.cpp
038e84cbc922bd20366b5a57891fb699305bd291
[]
no_license
zH4x/SpellBreak-FULL-SDK
ef45d77b63494c8771554a5d0e017cc297d8dbca
cca46d4a13f0e8a56ab8ae0fae778dd389d3b404
refs/heads/master
2020-09-12T17:25:58.697408
2018-12-09T22:49:03
2018-12-09T22:49:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
// SpellBreak By Respecter (0.15.340) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SB_BP_Effect_Player_BurningDOT_parameters.hpp" namespace SpellSDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
b34f321ba097662fa02715697f605b1b83e2d794
c0cbcddb4d2e92d08caa634f61a8ab3bd66526df
/projects/biogears/include/biogears/cdm/utils/unitconversion/QuantityConversionKey.h
2bea025b45616c2ace665c0c16effdedebbbe91d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
timhoer/core
2c50ba7ae42a128768396ac2ce4573237445a258
f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11
refs/heads/master
2020-03-22T09:59:09.621767
2018-07-10T15:12:25
2018-07-10T15:12:25
139,873,468
0
0
Apache-2.0
2018-07-06T18:45:56
2018-07-05T16:12:45
C++
UTF-8
C++
false
false
3,396
h
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************************/ //---------------------------------------------------------------------------- /// @file QuantityConversionKey.h /// @author Chris Volpe /// /// This class contains a representation of a key that can be used in a hash table /// for looking up Quantity Conversion Descriptors. //---------------------------------------------------------------------------- #pragma once #include <biogears/exports.h> #include <biogears/cdm/CommonDataModel.h> class CUnitDimension; class CQuantityConversionKey; class CQuantityConversionKey { public: // Construct from two Quantity Type IDs // This is called by the code that parses the initialization file and // creates the hash map entry CQuantityConversionKey(int fromId, int toID); // Construct from two UnitDimension pointers CQuantityConversionKey(const CUnitDimension* fromDim, const CUnitDimension* toDim) : m_CUDfromDim(fromDim) , m_CUDtoDim(toDim) { // Do nothing } // override less-than operator to facilitate default hash comparison function bool operator<(const CQuantityConversionKey& rhs) const; // For the sake of completeness only, implement the other relational operators bool operator>(const CQuantityConversionKey& rhs) const { return rhs < *this; } bool operator<=(const CQuantityConversionKey& rhs) const { return !(*this > rhs); } bool operator>=(const CQuantityConversionKey& rhs) const { return !(*this < rhs); } bool operator==(const CQuantityConversionKey& rhs) const; bool operator!=(const CQuantityConversionKey& rhs) const { return !(*this == rhs); } // Compute a hash value from an array of the two hash values of the From and // To Dimension objects size_t hash_value() const; private: // Regardless of how we're constructed, these two CUnitDimension pointers // are "owned" by other objects. In the case of the one physically stored in // the hash table, the pointers are owned by the QuantityTypeDescriptor objects // referenced by name in the initializaiton file. In the case of one constructed // in the course of hash table lookup, it's owned by the compound unit objects // involved in the type conversion. const CUnitDimension* m_CUDfromDim; const CUnitDimension* m_CUDtoDim; }; // Overload non_member hash_value on CQuantityConversionKey so that the // templated hash_compare used by hash_map can call it. inline size_t hash_value(const CQuantityConversionKey& ref) { return ref.hash_value(); } namespace std { template <> struct hash<CQuantityConversionKey> { size_t operator()(const CQuantityConversionKey& ref) const { return ref.hash_value(); } }; }
d3e9972f2f8aa0ead76c101f34b472b98b5d5d6d
050b0e3e5d37bf1cd1f79733788b2ed2c361b730
/employee.h
ee98f0eaf2822420654e118cdc64565d53237754
[ "MIT" ]
permissive
cgraves1/WorkerPayApp
a721cd0928e1cd9bda07a6eb62911153dfaef788
9284bbda28199b22333fa5e2c5bd879d397c1bb1
refs/heads/master
2020-03-27T03:54:56.531135
2019-06-27T19:16:06
2019-06-27T19:16:06
145,896,355
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
h
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include <QString> class employee { public: //constructor employee(); employee(QString,QString, double, double);//first, last, wage, com //f, l, wage, com, selected, paiddate, paidamt employee(QString, QString, double, double, bool, QString, double); bool getSelected(); void setSelected(bool); QString getfName(); void setfName(QString); QString getlName(); void setlName(QString); double getAmtOwed(); void setAmtOwed(double); double getWage(); void setWage(double); double getComm(); void setComm(double); QString getLastPaid(); void setLastPaid(QString); double getLastPaidAmt(); void setLastPaidAmt(double); bool operator==(employee); void toggleHidden(); bool isHidden(); private: bool isSelected; // to pay //user set QString fName; QString lName; double wage; double commission; bool hidden; //calculated QString paidDate; double amtOwed; double amtLastPaid; }; #endif // EMPLOYEES_H
bfb6d66861a57abd019406b14d856bfbbab735cf
37a84006b0fe76073ed541cdd8cfb6f446992e3b
/sys/eventqueue.cpp
7d564be84e72382f1ce141f876ebaa5331f529e5
[]
no_license
idx0/GetToTheInn
635161cc21ecf12aa59c0a2a4dd79da9efd8e266
509279ecab0b1639777aed2560300c293a607216
refs/heads/master
2021-01-01T16:06:31.152068
2020-06-03T15:46:19
2020-06-03T15:47:25
26,274,934
0
0
null
null
null
null
UTF-8
C++
false
false
2,975
cpp
#include "eventqueue.h" #include "enumstr.h" #include "logger.h" #include <stdlib.h> #include <string.h> namespace sys { eventqueue *eventqueue::m_instance = static_cast<eventqueue*>(0); bool eventqueue::createEventQueue() { bool ret = false; if (m_instance == static_cast<eventqueue*>(0)) { m_instance = new eventqueue(); ret = true; } return ret; } void eventqueue::destroyEventQueue() { if (m_instance != static_cast<eventqueue*>(0)) { delete m_instance; } } eventqueue::eventqueue(void) { int i; mutex_init(&m_mutex); for (i = 0; i < MAX_LISTENERS; i++) { m_listener[i].l = NULL; m_listener[i].id.setObjectId(TOKEN_LISTENER, INVALID_LISTENER_ID); m_listener[i].type = EVENT_NONE; } } eventqueue::~eventqueue(void) { mutex_destroy(&m_mutex); } void eventqueue::push(const event& e) { // printf("pushed event %d\n", e.getType()); // dont push null events if (e.getType() != EVENT_NONE) { m_instance->lock(); m_instance->m_queue.push(e); // move outside lock? m_instance->notifyListeners(e); m_instance->unlock(); } } event eventqueue::pop() { event e; m_instance->lock(); if (!m_instance->m_queue.empty()) { e = m_instance->m_queue.front(); m_instance->m_queue.pop(); // printf("popped event %d\n", e.getType()); } m_instance->unlock(); return e; } void eventqueue::lock() { mutex_lock(&m_mutex); } void eventqueue::unlock() { mutex_unlock(&m_mutex); } bool eventqueue::empty() { return m_queue.empty(); } int eventqueue::getFreeTicket() { int i; for (i = 0; i < MAX_LISTENERS; i++) { if ((!isValidObject(m_listener[i].id)) && (m_listener[i].l == NULL)) { break; } } return i; } token eventqueue::registerListener(const event_type& type, listener *l) { token id; int idx; lock(); idx = getFreeTicket(); if (idx != MAX_LISTENERS) { m_listener[idx].id.setIndex(idx); m_listener[idx].l = l; m_listener[idx].type = type; id = m_listener[idx].id; logger::log("registered listener %p for type %s at 0x%08x", l, enumstr::stringify(type).c_str(), m_listener[idx].id.getObjectId()); } unlock(); return id; } void eventqueue::unregisterListener(const token& id) { unsigned int idx; lock(); if (isValidObject(id)) { idx = id.getIndex(); if (idx < MAX_LISTENERS) { m_listener[idx].id.setIndex(INVALID_LISTENER_ID); m_listener[idx].l = static_cast<listener *>(0); m_listener[idx].type = EVENT_NONE; } } unlock(); } void eventqueue::notifyListeners(const event& e) { int i; for (i = 0; i < MAX_LISTENERS; i++) { if ((isValidObject(m_listener[i].id)) && (m_listener[i].l != NULL) && (m_listener[i].type == e.getType())) { // logger::log("notifying listener %p for type %s", // m_listener[i].l, enumstr::stringify(e.getType()).c_str()); m_listener[i].l->notify(e); } } } bool eventqueue::isValidObject(const token& obj) { return ((obj.getIndex() != INVALID_LISTENER_ID) && (obj.getType() == TOKEN_LISTENER)); } }
99c80beb7abcc21708de701ef0219c3ce7d7e22e
64cfe764a3e19b85eef6b33a7d280319b89e51ac
/2539/Peresadin/tests.cpp
9dd3f380d1f58cc0fa1b95090348a0e3584317ae
[]
no_license
itmoasm2015/Homework1
78c4db386f10419b04b2b9da2d3a2fdfce13dacf
34f9e92cac985e9f09344e59b4d446f34c3e0992
refs/heads/master
2021-01-10T19:15:47.782958
2015-06-27T10:27:10
2015-06-27T10:27:10
31,006,119
0
2
null
null
null
null
UTF-8
C++
false
false
2,458
cpp
#include <bits/stdc++.h> #include "hw1.h" #define format1 "%0+10u | %0-+10u" std::string gen_flag(int len) { std::string format = "%"; for (int i = 0; i < 7; ++i) { int t = rand() % 4; if (t == 0) format += '+'; if (t == 1) format += ' '; if (t == 2) format += '-'; if (t == 3) format += '0'; } int num = rand() % 100; do { format += num % 10 + '0'; num /= 10; } while (num > 0); format += "d"; //format += '\n'; return format; } void let_first_stage_test() { int n = 1; int arg[n]; char my_out[10000]; char true_out[10000]; memset(my_out, 0, 10000); memset(true_out, 0, 10000); std::string format = ""; for (int i = 0; i < n; ++i) format += gen_flag(rand() % 7); for (int i = 0; i < n; ++i) arg[i] = rand() % 12345; hw_sprintf(my_out, format.c_str(), arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]); sprintf(true_out, format.c_str(), arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]); if (memcmp(true_out, my_out, 1000) != 0) { std::cerr << (("Fail on "+ format).c_str()) << "\n"; std::cerr << "True string: " << "|" << true_out << "|" << "\n"; std::cerr << "My string: " << "|" << my_out << "|" << "\n"; std::cerr << "Args: "; for (int i = 0; i < n; ++i) std::cerr << arg[i] << " "; std::cerr << "\n"; assert(0); } else { //std::cerr << "Ok: " + format + "\n"; } } int main() { srand(time(NULL)); char out[10000]; char true_out[10000]; memset(out, 0, 10000); memset(true_out, 0, 10000); int num = 1; hw_sprintf(out, "50%%"); printf("%s\n", out); //std::string fm = "% +0-01d% -+0-6d%+ - 06d#"; //std::string fm = "% +0-01d% -+0-6d%+ - 064d%00++-7d%-0 ++6d%0- ++66d%0--006d%-0- -83d%+-0- 7d% +04d"; //std::string fm1 = " %-0 0 5d%-+0 069d%0 00 7d%- +- 9d% 0 +3d% -+- 7d%+0-0+5d%+0-007d% 08d% +---9d"; //hw_sprintf( out, fm.c_str(), num, num, num, num, num, num, num, num); //hw_sprintf(true_out, fm.c_str(), num, num, num, num, num, num, num, num); //printf("%s\n=======\n%s\n", out, true_out); //std::cerr << strcmp(out, true_out) << "\n"; for (int i = 0; i < 10000; ++i) { let_first_stage_test();} //hw_sprintf(out, format1, -12345, 12345); //std::cerr << out << "\n"; //sprintf(true_out, format1, -12345, 12345); //std::cerr << true_out << "\n"; //std::cout << strcmp(out, true_out) << std::endl; //std::cerr << "OK. All test passed" << "\n"; return 0; }
0e019bbdbc95751dfe787349470e33805b462cb9
fbbb4a1d84187ce82c5671e22ad3bfc744a36edf
/GeeksForGeeks/C Arrays/Find subarray with given sum.cpp
ef702f06a8ce7f2e16f0c02346237bce9137e98e
[]
no_license
richa18b/Competitive_Coding
49d56dbb6b00a21e07c7b069602fd00fe9cf81e7
74acc7dcc2b83e79f8673ec3bc843242c7563e97
refs/heads/master
2020-07-23T20:42:42.121404
2017-05-29T13:09:48
2017-05-29T13:09:48
73,801,040
1
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
/* Find subarray with given sum [Google Interview Question] [May 13, 2012] */ #include<bits/stdc++.h> using namespace std; bool subarraySum(int a[],int n,int sum) { int curr_sum=a[0],start=0; for(int i=1;i<n;++i) { while(curr_sum>sum&&start<i-1) { curr_sum-=a[start]; start++; } if(curr_sum==sum) { cout<<"Required Subarray: "<<a[start]<<" to "<<a[i-1]<<"\n"; return true; } else curr_sum+=a[i]; } return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t,n,x; cin>>t; while(t--) { cin>>n; cin>>x; int a[n]; for(int i=0;i<n;++i) cin>>a[i]; if(!subarraySum(a,n,x)) cout<<"No such subarray\n"; } return 0; }
7a9045777cc6bd601d1c6e7173592c140d3d981e
a73505cf2ecc7b0cc54770ee3c8d03aaf23e12c9
/Proyecto/menuperiodo.h
774bdff448c8cb2317d67afe933c339f77f8d4bf
[]
no_license
alexVillasenor/SEDDII
97a6623d419c890a57ae4646f1f0506051ac425c
b531638eb8b292c654e130162fc4e04f711fce6f
refs/heads/master
2020-04-07T18:57:01.495658
2018-12-07T03:00:10
2018-12-07T03:00:10
158,630,552
0
0
null
2018-12-07T03:00:11
2018-11-22T02:15:57
C++
UTF-8
C++
false
false
855
h
#ifndef MENUPERIODO_H #define MENUPERIODO_H #include <QWidget> #include <QWidget> #include "profesor.h" #include "login.h" #include "menuuser.h" #include <fstream> #include <QDebug> #include <QMessageBox> #include <QLineEdit> #include <QIntValidator> #include <QRegExpValidator> #include <regex> #include "periodo.h" namespace Ui { class MenuPeriodo; } class MenuPeriodo : public QWidget { Q_OBJECT public: explicit MenuPeriodo(QWidget *parent = 0); ~MenuPeriodo(); private slots: void on_pushButton_7_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_pushButton_6_clicked(); void on_pushButton_clicked(); void on_pushButton_8_clicked(); private: Ui::MenuPeriodo *ui; }; #endif // MENUPERIODO_H