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
b0455f80545e18c4039f4ae3e8d7922f7af034f6
c049b73ff2a62a5d8427743f1c77cb4da8e7b70f
/FZYZOJ/1198/p1198.cpp
8fa83bb346795c03d5f42bd8a7535e5ab3849003
[]
no_license
ztl8702/OICode
933c6abbfd59596dd35cad2f07278e62f505611a
a7374be244543e2416289ee40daa750369d4b547
refs/heads/master
2021-01-22T07:11:10.124494
2018-05-29T07:11:08
2018-05-29T07:11:08
12,105,677
0
0
null
null
null
null
UTF-8
C++
false
false
2,605
cpp
#include <cstdio> #include <algorithm> #include <cstring> #include <cstdlib> #include <vector> const double INFPRC=1e+20; double D1,C,D2,P0; int n; struct TStation { double d,p; } sta[1005]; struct TOil { int sta; double price,used,pos; } oil[1005]; int ocount; inline bool cmpOil(const TOil &a, const TOil &b) { return a.price<b.price; } inline bool cmpStation(const TStation &a, const TStation &b) { return a.d<b.d; } inline void input() { scanf("%lf%lf%lf%lf%d",&D1,&C,&D2,&P0,&n); for (int i=1; i<=n; ++i) scanf("%lf%lf",&sta[i].p,&sta[i].d); ++n; sta[n].d=0; sta[n].p=P0; std::sort(sta+1,sta+1+n,cmpStation); ++n; sta[n].d=D1; sta[n].p=0; for (int i=1; i<=n; ++i) printf("#%d:pos=%.2lf pri=%.2lf\n",i,sta[i].d,sta[i].p); } inline void addOilType(const int staid) { ++ocount; oil[ocount].price=sta[staid].p; oil[ocount].used=0; oil[ocount].pos=sta[staid].d; oil[ocount].sta=staid; std::sort(oil+1,oil+ocount+1,cmpOil); } inline double useOil(const double need,const double pos) { int i,disabled=0; double require=need,fee=0; std::sort(oil+1,oil+ocount+1,cmpOil); i=1; while (require>0 && i<=ocount) { if (oil[i].used<C && pos-oil[i].pos<=C*D2) { if (C-oil[i].used>=require) { oil[i].used+=require; fee+=oil[i].price*require; printf(" use #%d*%.2lfL;",oil[i].sta,require); require=0; } else { fee+=oil[i].price*(C-oil[i].used); printf(" use #%d*%.2lfL;",oil[i].sta,(C-oil[i].used)); require-=C-oil[i].used; oil[i].used=C; } if (oil[i].used>=C) { ++disabled; oil[i].price=INFPRC; } } else { ++disabled; oil[i].price=INFPRC; } ++i; } std::sort(oil+1,oil+ocount+1,cmpOil); ocount-=disabled; return (require>0)?-1:fee; } inline void work() { int i,j; double ans=0,tmp; addOilType(1); for (i=2; i<=n; ++i) { printf("Station %d->%d: ",i-1,i); tmp=useOil((sta[i].d-sta[i-1].d)/D2,sta[i].d); if (tmp<0) { printf("No Solution\n"); return; } else ans+=tmp; addOilType(i); printf("\n"); } printf("%lf\n",ans); } int main() { input(); work(); system("pause"); return 0; }
[ "ztl8702@server.fake" ]
ztl8702@server.fake
27742459f27fccce4ff33f409c97702999baa81d
185f4c4e492cc328f1946f120b4eefbe38e314bf
/src/tests/chiralEnsemble.cc
8c8d6b06baf0069b483207aa06edd8288d39cdcd
[]
no_license
protCAD/protcad
072b8830a574f03edcdf875aa7f5abffaad4f9f2
ebd265e022664f4c7219b4aacf43abd134cbcd03
refs/heads/master
2023-01-27T19:08:50.374495
2023-01-20T18:37:39
2023-01-20T18:37:39
20,460,150
14
21
null
2022-11-15T20:33:02
2014-06-03T21:20:22
C++
UTF-8
C++
false
false
13,599
cc
#include "typedef.h" #include "ensemble.h" #include "PDBInterface.h" #include "ran.h" #include <sstream> UInt countHbonds(protein* _prot); double getEnergy(protein* _prot); UInt countCAOclashes(protein* _prot); string intToString(int _num); void saveState(protein* _prot, string _prefix, UInt _fileNum, UInt _step, double _beta, double _score); bool isFixed(UIntVec _fixedPositions, UInt _res); bool flipChirality(protein* _prot, UInt _res); double getProb(double _oldScore, double _score, double _beta); int main (int argc, char* argv[]) { enum aminoAcid {A, R, N, D, C, Q, E, G, H, I, L, K, M, F, P, S, T, W, Y, V}; //read command line if (argc < 2) { cout << "primalSoup inputfile" << endl; exit(1); } //read inputfile string inputFile = argv[1]; ifstream inFile; inFile.open(inputFile.c_str()); if (!inFile) { cout << "Unable to find or open file" << endl; exit(1); } string currentLine; vector <string> parsedStrings; parsedStrings.resize(0); getline(inFile, currentLine, '\n'); parsedStrings = Parse::parse(currentLine); string inputFileName = parsedStrings[0]; // read in prot structure PDBInterface* thePDB = new PDBInterface(inputFileName); ensemble* theEnsemble = thePDB->getEnsemblePointer(); molecule* theMol = theEnsemble->getMoleculePointer(0); protein* prot = static_cast<protein*>(theMol); residue::setCutoffDistance(6.5); pmf::setScaleFactor(0.0); rotamer::setScaleFactor(0.0); microEnvironment::setScaleFactor(0.0); amberVDW::setScaleFactor(1.0); amberVDW::setRadiusScaleFactor(0.9); amberVDW::setLinearRepulsionDampeningOff(); amberElec::setScaleFactor(0.0); solvation::setItsScaleFactor(0.0); ran ranNumber; UInt randomSeed; if (argc == 3) { getline(inFile, currentLine, '\n'); // read in but skip sscanf(argv[2], "%u", &randomSeed); // use second command line arg instead ranNumber.setSeed(randomSeed); } else { getline(inFile, currentLine, '\n'); parsedStrings = Parse::parse(currentLine); sscanf(parsedStrings[0].c_str(), "%u", &randomSeed); ranNumber.setSeed(randomSeed); } UInt iterations, history; getline(inFile, currentLine, '\n'); parsedStrings = Parse::parse(currentLine); sscanf(parsedStrings[0].c_str(), "%u", &iterations); sscanf(parsedStrings[1].c_str(), "%u", &history); double startBeta, endBeta; getline(inFile, currentLine, '\n'); parsedStrings = Parse::parse(currentLine); sscanf(parsedStrings[0].c_str(), "%lf", &startBeta); sscanf(parsedStrings[1].c_str(), "%lf", &endBeta); double probLAla; // enantiomeric excess of L-Ala getline(inFile, currentLine, '\n'); parsedStrings = Parse::parse(currentLine); sscanf(parsedStrings[0].c_str(), "%lf", &probLAla); UInt size = prot->getNumResidues(0); for (UInt i = 0; i < size; i ++) { prot->activateForRepacking(0,i); prot->setPhi(0,i,180); prot->setPsi(0,i,180); if (ranNumber.getNext() > 0.5) // randomize initial sequence prot->mutate(0, i, 20); else prot->mutate(0, i, 0); } UIntVec fixedPositions; while (getline(inFile, currentLine, '\n')) { parsedStrings=Parse::parse(currentLine); UInt tempRes, tempID; sscanf(parsedStrings[0].c_str(), "%u", &tempRes); sscanf(parsedStrings[1].c_str(), "%u", &tempID); fixedPositions.push_back(tempRes); prot->mutate(0, tempRes, tempID); } // center dimer on origin dblVec center = prot->getBackBoneCentroid(0); prot->translate(0, -1.0* center); center = prot->getBackBoneCentroid(1); prot->translate(1, -1.0* center); // move mobile monomer away double xtrans, ytrans, ztrans, irot1, irot2, irot3; xtrans = 3 + 6 * ranNumber.getNext(); ytrans = 3 + 6 * ranNumber.getNext(); ztrans = 3 + 6 * ranNumber.getNext(); irot1 = -180 + 360*ranNumber.getNext(); irot2 = -180 + 360*ranNumber.getNext(); irot3 = -180 + 360*ranNumber.getNext(); prot->eulerRotate(0, irot1, irot2, irot3); prot->translate(0, xtrans, ytrans, ztrans); //doMove(prot, 0, radius, rot1, rot2, rot3); pdbWriter(prot, "start.pdb"); prot->silenceMessages(); double lowestScore = 1000; double oldScore = lowestScore; UInt lowCounter = 1; UInt counter = 0; for (UInt i = 0; i < iterations; i ++) { counter ++; // counter for storing history files double beta = startBeta + i * (endBeta - startBeta) / iterations; // linear cooling if ( 0.80 > ranNumber.getNext()) // then deal with intrachain optimization { UInt res = UInt(ranNumber.getNext()*(size+1)); if (res >= size) res = size - 1; UInt choice = 0; // 0 is change dihedral (default) , 1 is change id, 2 is change both if (isFixed(fixedPositions,res)) { choice = 0; } else { double tempProb = ranNumber.getNext(); if (tempProb < probLAla && prot->getTypeFromResNum(0,res) == 20) // currently D, then flip to L { if (ranNumber.getNext() < 0.5) choice = 1; else choice = 2; } else if (tempProb >= probLAla && prot->getTypeFromResNum(0,res) == 0) // currently L, then flip to D { if(ranNumber.getNext() < 0.5) choice = 1; else choice = 2; } } // CHOICE 0 - change dihedral only if (choice == 0) { double oldPhi = prot->getPhi(0,res); double oldPsi = prot->getPsi(0,res); double newPhi = 180 - 360*ranNumber.getNext(); double newPsi = 180 - 360*ranNumber.getNext(); prot->setPhi(0,res,newPhi); prot->setPsi(0,res,newPsi); double score = getEnergy(prot); if (score < oldScore) { oldScore = score; if (score < lowestScore) { lowestScore = score; lowCounter ++; saveState(prot, "low", lowCounter, i, beta, score); pdbWriter(prot, "final.pdb"); } } else { double metropolis = getProb(oldScore, score, beta); if ( metropolis > ranNumber.getNext() ) { oldScore = score; } else { prot->setPhi(0, res, oldPhi); prot->setPsi(0, res, oldPsi); } } } // CHOICE 1 - flip chirality if (choice == 1) { flipChirality(prot,res); double score = getEnergy(prot); if (score < oldScore) { oldScore = score; if (score < lowestScore) { lowestScore = score; lowCounter ++; saveState(prot, "low", lowCounter, i, beta, score); pdbWriter(prot, "final.pdb"); } } else { double metropolis = getProb(oldScore, score, beta); if ( metropolis > ranNumber.getNext() ) { oldScore = score; } else { flipChirality(prot, res); // if rejected, flip back } } } // CHOICE 2 - change both simultaneously if (choice == 2) { flipChirality(prot, res); double oldPhi = prot->getPhi(0,res); double oldPsi = prot->getPsi(0,res); double newPhi = 180 - 360*ranNumber.getNext(); double newPsi = 180 - 360*ranNumber.getNext(); prot->setPhi(0,res,newPhi); prot->setPsi(0,res,newPsi); double score = getEnergy(prot); if (score < oldScore) { oldScore = score; if (score < lowestScore) { lowestScore = score; lowCounter ++; saveState(prot, "low", lowCounter, i, beta, score); pdbWriter(prot, "final.pdb"); } } else { double metropolis = getProb(oldScore, score, beta); if ( metropolis > ranNumber.getNext() ) { oldScore = score; } else { flipChirality(prot, res); prot->setPhi(0, res, oldPhi); prot->setPsi(0, res, oldPsi); } } } } else // translate/rotate { dblVec centroid = prot->getBackBoneCentroid(0); dblVec newPos(3); newPos[0] = centroid[0] - 1 + 2.0 * ranNumber.getNext(); newPos[1] = centroid[1] - 1 + 2.0 * ranNumber.getNext(); newPos[2] = centroid[2] - 1 + 2.0 * ranNumber.getNext(); double radius = sqrt(CMath::dotProduct(newPos,newPos)); if (radius > 12.0) { newPos = newPos * 12.0/radius; } if (radius < 3.0) { newPos = newPos * 3.0/radius; } double rot1 = - 15 + 30.0 * ranNumber.getNext(); double rot2 = - 15 + 30.0 * ranNumber.getNext(); double rot3 = - 15 + 30.0 * ranNumber.getNext(); prot->translate(0, -1.0*centroid); prot->eulerRotate(0, rot1, rot2, rot3); prot->translate(0, newPos); double score = getEnergy(prot); if (score < oldScore) { oldScore = score; if (score < lowestScore) { lowestScore = score; lowCounter ++; saveState(prot, "low", lowCounter, i, beta, score); pdbWriter(prot, "final.pdb"); } } else { double metropolis = getProb(oldScore, score, beta); if ( metropolis > ranNumber.getNext() ) { oldScore = score; } else { prot->translate(0, -1.0* newPos); prot->undoEulerRotate(0, rot1, rot2, rot3); prot->translate(0, centroid); } } } cout << "Score " << i << " " << oldScore << " temp " << beta << " lowest " << lowestScore << endl; if (counter == history) { counter = 0; saveState(prot, "out", i, i, beta, oldScore); } } pdbWriter(prot,"end.pdb"); return 0; } double getProb(double _oldScore, double _score, double _beta) { double dScore = _oldScore - _score; double prob = pow(2.718, dScore * _beta); return prob; } double getEnergy(protein* _prot) { UInt nhbs = countHbonds(_prot); UInt nclashes = countCAOclashes(_prot); double vdwE = _prot->intraEnergy(); dblVec centroid = _prot->getBackBoneCentroid(0); double radius = sqrt(CMath::dotProduct(centroid, centroid)); double force = -1 * (3 - radius); double score = force + vdwE + 5.0*(float)nclashes - 5.0*(float)nhbs; return score; } UInt countCAOclashes(protein* _prot) { UInt size = _prot->getNumResidues(0); UInt clashes = 0; vector < dblVec > CBcoords; vector < dblVec > Ocoords; for (UInt i = 0; i < size-1; i ++) // do not count clashes on last residue as we cannot change its PSI anyways { dblVec tempcoord; UInt type = _prot->getTypeFromResNum(0,i); if (type == 0 || type == 20) { tempcoord =_prot->getCoords(0, i, 4); CBcoords.push_back(tempcoord); } tempcoord =_prot->getCoords(0, i, 3); Ocoords.push_back(tempcoord); } for (UInt i = 0; i < CBcoords.size(); i ++) { for (UInt j = 0; j < Ocoords.size(); j ++) { dblVec temp = CBcoords[i] - Ocoords[j]; double distance = sqrt(CMath::dotProduct(temp,temp)); int resSpace = (i - j); if (distance < 3.0 && abs(resSpace) < 2 ) { clashes ++; } } } return clashes; } UInt countHbonds(protein* _prot) { UInt size = _prot->getNumResidues(0); UInt numHbonds = 0; vector < dblVec > Ncoords; vector < dblVec > Ocoords; vector < dblVec > Ccoords; vector < dblVec > CAcoords; for (UInt i = 0; i < size; i ++) { dblVec tempcoord =_prot->getCoords(0, i, 0); Ncoords.push_back(tempcoord); tempcoord =_prot->getCoords(0, i, 3); Ocoords.push_back(tempcoord); tempcoord =_prot->getCoords(0, i, 1); CAcoords.push_back(tempcoord); tempcoord = _prot->getCoords(0, i, 2); Ccoords.push_back(tempcoord); } // for first residue = no angular constraint for (UInt j = 0; j < Ocoords.size(); j ++) { dblVec temp = Ncoords[0] - Ocoords[j]; double distance = sqrt(CMath::dotProduct(temp,temp)); int resSpace = (0 - j); if (distance < 3.2 && abs(resSpace) > 2 ) { numHbonds ++; } } for (UInt i = 1; i < Ncoords.size(); i ++) { for (UInt j = 0; j < Ocoords.size(); j ++) { int resSpace = (i - j); if ( abs(resSpace) > 2) { dblVec NO = Ncoords[i] - Ocoords[j]; double distance = sqrt(CMath::dotProduct(NO,NO)); dblVec pseudoAtom = (Ccoords[i-1] + CAcoords[i])/2.0; dblVec NH = Ncoords[i] - pseudoAtom; double magNH = sqrt(CMath::dotProduct(NH,NH)); double angle = acos( CMath::dotProduct(NO,NH) / (magNH * distance) ); angle = angle * 180 / 3.14159; if (distance < 3.2 && angle > 90.0) { numHbonds ++; } } } } return numHbonds; } string intToString(int _num) { ostringstream myStream; myStream << _num << flush; return (myStream.str()); } void saveState(protein* _prot, string _prefix, UInt _fileNum, UInt _step, double _beta, double _score) { string pad = ""; if (_fileNum < 10) pad = "000000"; else if(_fileNum < 100) pad = "00000"; else if(_fileNum < 1000) pad = "0000"; else if(_fileNum < 10000) pad = "000"; else if(_fileNum < 100000) pad = "00"; else if(_fileNum < 1000000) pad = "0"; string filename = _prefix + pad + intToString(_fileNum) + ".pdb"; pdbWriter(_prot, filename); string logfile = _prefix + ".log"; ofstream fout (logfile.c_str() ,ios::app); fout << "step " << _step << " beta " << _beta << " score " << _score << " nhbs " << countHbonds(_prot)<< " clashes " << countCAOclashes(_prot) << " sequence "; UInt size = _prot->getNumResidues(0); for (UInt n = 0; n < size; n ++) { if (_prot->getTypeFromResNum(0,n) == 0) { fout << "L "; } else if (_prot->getTypeFromResNum(0, n) == 20) { fout << "D "; } else { fout << _prot->getTypeStringFromResNum(0,n) << " "; } } for (UInt n = 0; n < size; n ++) { fout << _prot->getPhi(0,n) << " "; fout << _prot->getPsi(0,n) << " ; "; } fout << endl; fout.close(); return; } bool flipChirality(protein* _prot, UInt _res) { if (_prot->getTypeFromResNum(0,_res) == 0) { _prot->mutate(0, _res, 20); return true; } else if (_prot->getTypeFromResNum(0, _res) == 20) { _prot->mutate(0, _res, 0); return true; } return false; } bool isFixed(UIntVec _fixedPositions, UInt _res) { bool flag = false; for (UInt i = 0; i < _fixedPositions.size(); i ++) { if (_res == _fixedPositions[i]) { flag = true; } } return flag; }
[ "doughp1@me.com" ]
doughp1@me.com
1e8b01cedaf8f47dddc198d47560c3c0280df835
5c29011a56c0c10c085674643cfc4798b47c1490
/SPA/Node.cpp
cf2d8549b5bbc7f2b3d9ae75698771e3acba4338
[]
no_license
mlaniewski/SPA_2
3f6c3dce5c6816988b8c2404390a44fe5e2b0d13
eba2b24ef878361ffe446ab078b5821b8755b45f
refs/heads/master
2023-04-09T12:36:00.236530
2021-04-12T13:20:36
2021-04-12T13:20:36
357,239,769
0
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
#include "Node.h" using namespace std; unsigned int Node::nextId = 0; map<unsigned int, NODE> Node::nodes = map<unsigned int, NODE>(); Node::Node(NODETYPE nodeType) : nodeType(nodeType), id(nextId++) { } Node::~Node() { } void Node::setParam(NODEPARAMTYPE type, string val) { params[type] = val; } string Node::getParam(NODEPARAMTYPE type) { return params[type]; } NODE Node::getTreeIterator() { return nodeIter; } void Node::setTreeIterator(NODE node) { nodeIter = node; nodes[id] = node; } NODE Node::getNodeById(int id) { return nodes[id]; }
[ "mateuszlaniewski98@gmail.com" ]
mateuszlaniewski98@gmail.com
192df9577d44599f3308a393ebf5e1714961822d
7f86f33a60adf52f5e8519ade0df1e4bb9af7de5
/ProjTP/Projet11/PileCartes.h
61bdec0a63d24b35a8071ef762155f002a46640f
[]
no_license
AsProgramming/C-
1f1294338b1b7e20a8163fc90b82641ab272fa72
091573b328130181f36bc4aec766eb6adec6a5a2
refs/heads/master
2020-03-29T18:17:30.419863
2018-09-25T03:48:04
2018-09-25T03:48:04
150,203,515
0
0
null
null
null
null
UTF-8
C++
false
false
422
h
#ifndef PILECARTES_H #define PILECARTES_H #include "NoeudCarte.h" using namespace std; class PileCartes { public: PileCartes(); ~PileCartes(); const PileCartes& operator=(const PileCartes& pile); Carte retirerSommet(); const Carte& getSommet() const; void ajouterCarte(const Carte& carte); int getTaille() const; void ajouterPile(const PileCartes& cartes); private: NoeudCarte *tete; int taille; }; #endif
[ "eddi3.as@gmail.com" ]
eddi3.as@gmail.com
6434d733c7889d74090860173c779df9149998a1
0f3a7221e1284a01db8d7156fba174df0a70d0cb
/DayOfYear.hpp
4083d1459f7c4389fa43f102a9ad0cc75e82062f
[]
no_license
dctownsend/inClassAssignment2
61d4609777f2560a12ab468ba2a26bcafeb6537b
fdc9b374653babcfd81ad634c52120c5fe2d1481
refs/heads/master
2020-03-15T09:08:29.851278
2018-05-04T01:20:30
2018-05-04T01:20:30
132,067,953
0
0
null
null
null
null
UTF-8
C++
false
false
522
hpp
// // DayOfYear.hpp // homework // // Created by dakota townsend on 5/1/18. // Copyright © 2018 dakota townsend. All rights reserved. // #ifndef DayOfYear_hpp #define DayOfYear_hpp #include <stdio.h> #include<string> using namespace std; class DayOfYear { private: int days; string months[12]; int endOfMonths[13]; static string dayMonth; static int restDays; public: DayOfYear(int day); void print(); void setEndOfMonths(); void setMonth(); }; #endif /* DayOfYear_hpp */
[ "noreply@github.com" ]
noreply@github.com
3cc1124f67d8e07412ad822d8ae8cabb3f48fa94
d24757a662f21392191d4880bbe418209f97fd08
/src/qt/editaddressdialog.cpp
59d3cdac46ed638fce928ec794759f789c5ef494
[ "MIT" ]
permissive
raipat/rain
13d3faadccd3a39920874905c270ba265a21da01
6424cea265e2a36db23e8861717088bb35606853
refs/heads/master
2022-06-01T17:39:14.751839
2022-03-05T13:03:49
2022-03-05T13:03:49
126,747,650
1
5
null
2018-03-25T22:59:05
2018-03-25T22:59:05
null
UTF-8
C++
false
false
4,286
cpp
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(false); ui->stealthCB->setEnabled(true); ui->stealthCB->setVisible(true); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); ui->stealthCB->setVisible(false); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(true); ui->stealthCB->setEnabled(false); ui->stealthCB->setVisible(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); ui->stealthCB->setVisible(false); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); mapper->addMapping(ui->stealthCB, AddressTableModel::Type); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: { int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal; address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text(), typeInd); } break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid rain address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
[ "bitc0der2245@gmail.com" ]
bitc0der2245@gmail.com
ed5d1560280997a46619fcad61dc7d103ed6d103
745c621eca689d8512e98fe2aad6b8a1a45012b8
/Queue.cpp
97d0b8cfaf9d76dac08ea799ad7206ec6ad5797f
[ "MIT" ]
permissive
DeepTalekar/HacktoberFestContribute
55eab93a76c2a189e2d0cc4c76482fa29d45485b
151c1c355c771c45ab3dfa5c6c7a4ece57592de9
refs/heads/master
2020-08-29T02:03:14.963924
2019-10-27T17:14:44
2019-10-27T17:14:44
217,888,709
0
0
MIT
2019-10-27T17:14:45
2019-10-27T17:11:17
null
UTF-8
C++
false
false
2,612
cpp
#include "stdafx.h" #include <iostream> #include <stdio.h> #include <conio.h> using namespace std; using namespace System; void enqueue(int v); int dequeue(); void print(); ConsoleKey menu(); void handleEnqueue(); void handleDequeue(); void handlePrint(); bool isValidKey(ConsoleKey k); int q[10]; int last=-1; void main() { ConsoleKey k; while((k = menu()) != ConsoleKey::D4) { switch(k) { case ConsoleKey::D1 : handleEnqueue();break; case ConsoleKey::D2 : handleDequeue();break; case ConsoleKey::D3 : handlePrint();break; default : cout << "Error Aborting Program"<<endl; exit(-1); break; } } } void handleEnqueue() { int v; Console::Clear(); cout << "Enter the value to Enqueue"<< endl; cin >> v; enqueue(v); cout << "Please Enter to Continue..." <<endl; Console::ReadLine(); } void handleDequeue() { int v; Console::Clear(); v = dequeue(); if(v==-1) { cout << "Sorry nothing in queue to dequeue"<<endl; } else { cout <<"The value dequeued is "<<v<<endl; } cout << "Please Enter to Continue..." <<endl; Console::ReadLine(); } void handlePrint() { Console::Clear(); cout << "Printing Queue"<<endl; print(); cout << "Please Enter to Continue..." <<endl; Console::ReadLine(); } ConsoleKey menu() { Console::Clear(); cout << " Welcome to Queue"<< endl; cout << " Press 1 to Enqueue value"<<endl; cout << " Press 2 to Dequeue-value"<<endl; cout << " Press 3 to Print Queue"<<endl; cout << " Press 4 to Quit"<<endl; ConsoleKey k = Console::ReadKey(true).Key; while(!isValidKey(k)) { cout << "Please Enter Valid Key"<<endl; k = Console::ReadKey(true).Key; } return k; } bool isValidKey(ConsoleKey k) { switch(k) { case ConsoleKey::D1 : return true; case ConsoleKey::D2 : return true; case ConsoleKey::D3 : return true; case ConsoleKey::D4 : return true; default :return false; } } void enqueue(int v) { if(last == 9) { cout << "Queue Full" << endl; } else { last = last + 1; q[last] = v; } } int dequeue() { if(last == -1){ cout << "Queue Empty" << endl; return - 1; } int temp = q[0]; for( int i = 0 ; i < last ; i++) { q[i] = q[i+1]; } last = last - 1; return temp; } void print() { cout << "Printing Queue"<<endl; for(int i=0 ; i<=last ; i++) { cout << q[i] << endl; } }
[ "noreply@github.com" ]
noreply@github.com
2df254f019839e5297f4f5e75ffd411820f28918
a1cc8e0976f296192b1002e279d66a6a3dada28f
/visual_utility/include/visual_utility/VisualUtilityEstimatorXMLParameters.h
2f6b52b9b2e3a8524a400c8c3dfb2c0acd717f13
[ "MIT" ]
permissive
MRSD2018/reefbot-1
40ef435ac4e1664858f225fde1d9ee995d55f235
a595ca718d0cda277726894a3105815cef000475
refs/heads/master
2021-04-09T10:26:25.455651
2018-04-01T19:13:43
2018-04-01T19:13:43
125,381,499
0
0
MIT
2018-04-01T15:24:29
2018-03-15T14:41:59
C++
UTF-8
C++
false
false
1,179
h
// A set of structures to read xml definitions of visual utility // estimators and create the corresponding objects. // // The xml file is in the format: // <estimators> // <estimator> // <class>LABMotionVUEstimator</class> // ... parameters ... // </extimator> // ... more estimators ... // </estimators> // // Author: Mark Desnoyer (mdesnoyer@gmail.com) // Date: April 2012 #ifndef __VISUAL_UTILITY_ESTIMATOR_XML_PARAMETERS_H__ #define __VISUAL_UTILITY_ESTIMATOR_XML_PARAMETERS_H__ #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include "VisualUtilityEstimator.h" namespace visual_utility { typedef std::vector<boost::shared_ptr<VisualUtilityEstimator> > VUEstimatorContainer; // Function that parses an xml file and return a set of // VisualUtilityEstimators. // // Inputs: // filename - Filename for the XML file to parse // out - Container to return the set of VisualUtilityEstimators // // Return value: // true if the parsing was sucessfull bool ParseVUEstimatorsXMLFile(const std::string& filename, VUEstimatorContainer* out); } // namespace #endif // __VISUAL_UTILITY_ESTIMATOR_XML_PARAMETERS_H__
[ "mdesnoyer@gmail.com" ]
mdesnoyer@gmail.com
f4dbeba61ef6b8aea091d400a53548dce63502ac
fd9a83767035abcc5de5945d11401b66574ea258
/Station/Station/PM_LTE_Case_PM.h
880437f711be95dc5efc31de846b98528bd837a2
[]
no_license
bradxiang/lte_station
cd5e21735c332640e7db084d06c920f1ae51d087
f0ac97a6d8e6c95e0ab85a8aeb63d4643bbf6e6e
refs/heads/master
2021-08-19T07:08:26.607269
2017-11-25T04:08:26
2017-11-25T04:08:26
111,864,506
1
0
null
null
null
null
GB18030
C++
false
false
3,077
h
#pragma once #include "afxcmn.h" #include "afxwin.h" #include "MyMutiTreeCtrl.h" // CPM_LTE_Case_PM 窗体视图 class CPM_LTE_Case_PM : public CFormView { DECLARE_DYNCREATE(CPM_LTE_Case_PM) protected: CPM_LTE_Case_PM(); // 动态创建所使用的受保护的构造函数 virtual ~CPM_LTE_Case_PM(); public: enum { IDD = IDD_PM_LTE_CASE_PM }; #ifdef _DEBUG virtual void AssertValid() const; #ifndef _WIN32_WCE virtual void Dump(CDumpContext& dc) const; #endif #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: //------------------------------------------------------------------------------------------------------ // 函数定义 //------------------------------------------------------------------------------------------------------ virtual void OnInitialUpdate(); //初始化 virtual BOOL PreTranslateMessage(MSG* pMsg); //消息预处理 afx_msg void OnDestroy(); // afx_msg void OnSize(UINT nType, int cx, int cy); // afx_msg void OnTvnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult); //树Item变化相应 afx_msg void OnBnClickedExcel2(); afx_msg void OnLvnColumnclickList3(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnNMClickList3(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedQuary2(); afx_msg void OnNMRClickList3(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnPmLteCaseDel(); afx_msg void OnPmLteCaseWDel(); afx_msg void OnBnClickedExcel3(); afx_msg void OnNMRClickList5(NMHDR *pNMHDR, LRESULT *pResult); //自定义 bool My_ExecuteSQL(CString v_sSql); //执行SQL命令 void My_LoadData_Per(); //装载信息 void My_LoadData_Case(); //装载信息 void My_Input_PER(); //数据导入 //线程:导入 CWinThread* v_pThread_Input; //线程指针 static UINT My_Thread_Inoput(LPVOID lparam); //线程:导入 void My_Input_Main(); //导入_主程序 //分窗 CSSplitter m_SplitterPane_Main; //垂直线 CSSplitter m_SplitterPane_Bottom; //垂直线 //------------------------------------------------------------------------------------------------------ // 变量定义 //------------------------------------------------------------------------------------------------------ CMyListCtrl m_cList; //信息 CMyListCtrl m_cList_Case; //信息 CEdit m_cSum; //网元数量 CButton m_cQuery; CButton m_cExcel; CEdit m_cCase; //自定义 CString v_sFrame_Name; //窗体名称 mFrame_Window::iterator v_pIterator_Frame; //窗体:迭代器 int v_iWorking; //工作代号: int v_iList_Item; //选中的列表Item CString v_sName_Account,v_sName_Case; //选中的列表Item的模板名称 }; //------------------------------------------------------------------------------------------------------ // End //------------------------------------------------------------------------------------------------------
[ "xiangxyyu@126.com" ]
xiangxyyu@126.com
e81c87f7631e705c03d0c5e85c0623d4833632db
203d7b7e3792acb8e7ccf0ca6feda8dc5b70ce60
/src/Scenario/SplitEx.cpp
312a4ceb0c930ed4d61333720b09599e20a9e325
[ "MIT" ]
permissive
Kalamatee/RayStorm
44e40882b5aff6fbefa3209bf6706cd402868dc3
1adb8f50478f795973aa51dcceb02682d671b41d
refs/heads/master
2020-12-11T03:38:15.490729
2019-06-21T15:32:22
2019-06-21T15:32:22
37,782,719
4
0
null
2015-06-20T19:22:47
2015-06-20T19:22:47
null
UTF-8
C++
false
false
5,618
cpp
///////////////////////////////////////////////////////////////////////////// // Copyright: // Uwe Kotyczka <kotyczka@mipool.uni-jena.de> // created: July 1998 // // based on a sample of // Oleg G. Galkin // ///////////////////////////////////////////////////////////////////////////// // SplitterWndAdvanced.cpp: Implementierungsdatei // #include "Typedefs.h" #include "SplitEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSplitterWndEx IMPLEMENT_DYNAMIC(CSplitterWndEx, CSplitterWnd) BEGIN_MESSAGE_MAP(CSplitterWndEx, CSplitterWnd) //{{AFX_MSG_MAP(CSplitterWndEx) ON_WM_LBUTTONDOWN() ON_WM_SETCURSOR() ON_WM_MOUSEMOVE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSplitterWndEx Konstruktion/Destruction CSplitterWndEx::CSplitterWndEx() { m_nHiddenCol = -1; m_nHiddenRow = -1; m_bEnableResizing = TRUE; } CSplitterWndEx::~CSplitterWndEx() { } ///////////////////////////////////////////////////////////////////////////// // CSplitterWndEx Kommandos void CSplitterWndEx::ShowColumn() { ASSERT_VALID(this); ASSERT(m_nCols < m_nMaxCols); ASSERT(m_nHiddenCol != -1); int colNew = m_nHiddenCol; m_nHiddenCol = -1; int cxNew = m_pColInfo[m_nCols].nCurSize; m_nCols++; // add a column ASSERT(m_nCols == m_nMaxCols); // fill the hidden column int col; for (int row = 0; row < m_nRows; row++) { CWnd* pPaneShow = GetDlgItem(AFX_IDW_PANE_FIRST + row * 16 + m_nCols); ASSERT(pPaneShow != NULL); pPaneShow->ShowWindow(SW_SHOWNA); for (col = m_nCols - 2; col >= colNew; col--) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row, col + 1)); } pPaneShow->SetDlgCtrlID(IdFromRowCol(row, colNew)); } // new panes have been created -- recalculate layout for (col = colNew + 1; col < m_nCols; col++) m_pColInfo[col].nIdealSize = m_pColInfo[col - 1].nCurSize; m_pColInfo[colNew].nIdealSize = cxNew; RecalcLayout(); } void CSplitterWndEx::ShowRow() { ASSERT_VALID(this); ASSERT(m_nRows < m_nMaxRows); ASSERT(m_nHiddenRow != -1); int rowNew = m_nHiddenRow; m_nHiddenRow = -1; int cyNew = m_pRowInfo[m_nRows].nCurSize; m_nRows++; // add a row ASSERT(m_nCols == m_nMaxCols); // fill the hidden row int row; for (int col = 0; col < m_nCols; col++) { CWnd* pPaneShow = GetDlgItem(AFX_IDW_PANE_FIRST + m_nRows * 16 + col); ASSERT(pPaneShow != NULL); pPaneShow->ShowWindow(SW_SHOWNA); for (row = m_nRows - 2; row >= rowNew; row--) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row + 1, col)); } pPaneShow->SetDlgCtrlID(IdFromRowCol(rowNew, col)); } // new panes have been created -- recalculate layout for (row = rowNew + 1; row < m_nRows; row++) m_pRowInfo[row].nIdealSize = m_pRowInfo[row - 1].nCurSize; m_pRowInfo[rowNew].nIdealSize = cyNew; RecalcLayout(); } void CSplitterWndEx::HideColumn(int colHide) { ASSERT_VALID(this); ASSERT(m_nCols > 1); ASSERT(colHide < m_nCols); ASSERT(m_nHiddenCol == -1); m_nHiddenCol = colHide; // if the column has an active window -- change it int rowActive, colActive; if (GetActivePane(&rowActive, &colActive) != NULL && colActive == colHide) { if (++colActive >= m_nCols) colActive = 0; SetActivePane(rowActive, colActive); } // hide all column panes for (int row = 0; row < m_nRows; row++) { CWnd* pPaneHide = GetPane(row, colHide); ASSERT(pPaneHide != NULL); pPaneHide->ShowWindow(SW_HIDE); pPaneHide->SetDlgCtrlID(AFX_IDW_PANE_FIRST + row * 16 + m_nCols); for (int col = colHide + 1; col < m_nCols; col++) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row, col - 1)); } } m_nCols--; m_pColInfo[m_nCols].nCurSize = m_pColInfo[colHide].nCurSize; RecalcLayout(); } void CSplitterWndEx::HideRow(int rowHide) { ASSERT_VALID(this); ASSERT(m_nRows > 1); ASSERT(rowHide < m_nRows); ASSERT(m_nHiddenRow == -1); m_nHiddenRow = rowHide; // if the row has an active window -- change it int rowActive, colActive; if (GetActivePane(&rowActive, &colActive) != NULL && rowActive == rowHide) { if (++rowActive >= m_nRows) rowActive = 0; SetActivePane(rowActive, colActive); } // hide all row panes for (int col = 0; col < m_nCols; col++) { CWnd* pPaneHide = GetPane(rowHide, col); ASSERT(pPaneHide != NULL); pPaneHide->ShowWindow(SW_HIDE); pPaneHide->SetDlgCtrlID(AFX_IDW_PANE_FIRST + m_nRows * 16 + col); for (int row = rowHide + 1; row < m_nRows; row++) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row - 1, col)); } } m_nRows--; m_pRowInfo[m_nRows].nCurSize = m_pRowInfo[rowHide].nCurSize; RecalcLayout(); } int CSplitterWndEx::GetHiddenColumn() { return m_nHiddenCol; } int CSplitterWndEx::GetHiddenRow() { return m_nHiddenRow; } void CSplitterWndEx::OnLButtonDown(UINT nFlags, CPoint point) { if (m_bEnableResizing == FALSE) return; CSplitterWnd::OnLButtonDown(nFlags, point); } BOOL CSplitterWndEx::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (m_bEnableResizing == FALSE) return TRUE; else return CSplitterWnd::OnSetCursor(pWnd, nHitTest, message); } void CSplitterWndEx::OnMouseMove(UINT nFlags, CPoint point) { if (m_bEnableResizing == FALSE) CWnd::OnMouseMove(nFlags, point); else CSplitterWnd::OnMouseMove(nFlags, point); }
[ "andreasheu@gmail.com" ]
andreasheu@gmail.com
111328a9e42046463bf1b068556f2b4a018182ba
70bf6ade0770b89bdd6e729faff483443fde2fe0
/src/bic_denoise.cpp
415ab75d107680f08f11b92f18643fffc287622a
[]
no_license
trevor-harris/fmci
f177b1e876ed8d3a0c295c7f43c519e4410ab66f
5b2dfa7791de9d87a2a1090ff2fd2bcfa65be328
refs/heads/master
2022-11-24T14:23:22.065670
2020-08-02T16:02:57
2020-08-02T16:02:57
283,853,791
0
0
null
null
null
null
UTF-8
C++
false
false
6,846
cpp
#include<RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::plugins("cpp11")]] //' @export //[[Rcpp::export]] IntegerVector which0 (NumericVector& x) { IntegerVector ind = seq(0, x.size()-1); return(ind[x != 0]); } //' @export //[[Rcpp::export]] NumericVector sharpenC (IntegerVector& cp_ind, NumericVector& w, double cval = 0.1, int reach = 10) { int ncp = cp_ind.size(); NumericVector cp_out(ncp); int i = 0; while(i < ncp) { // link all cp within reach to form the group int k = 0; for(int j = i+1; j < ncp; j++) { if((cp_ind(j) - cp_ind(j-1)) < reach) { k += 1; } else { break; } } // if group has a collectively large enough jump then denote the largest one as the cp if(std::abs(sum(w[Range(i, i+k)])) > cval) { cp_out(i) = cp_ind(which_max(Rcpp::abs(w[Range(i, i+k)])) + i) + 1; } i += k + 1; } return(cp_out[which0(cp_out)]); } //' @export //[[Rcpp::export]] List mergeC (IntegerVector& cp_ind, NumericVector& w, int reach = 10) { int ncp = cp_ind.size(); NumericVector cp_out(ncp); NumericVector w_out(ncp); int i = 0; int ind; while(i < ncp) { // link all cp within reach to form the group int k = 0; for(int j = i+1; j < ncp; j++) { if((cp_ind(j) - cp_ind(j-1)) < reach) { k += 1; } else { break; } } ind = which_max(abs(w[Range(i, i+k)])) + i; cp_out(i) = cp_ind(ind); w_out(i) = sum(w[Range(i, i+k)]); i += k + 1; } return(List::create(cp_out[which0(cp_out)], w_out[which0(w_out)])); // return(cp_out[which0(cp_out)]); } // //' @export // //[[Rcpp::export]] // double vmult (const arma::vec& lhs, // const arma::vec& rhs) { // arma::mat prod = lhs.t() * rhs; // return prod(0,0); // } // // //' @export // //[[Rcpp::export]] // arma::vec mergeM (const arma::vec& cp, const arma::vec& w, int reach = 10) { // // int ncp = cp.n_elem; // arma::vec cp_out(ncp); // arma::vec cg(ncp); // arma::vec wg(ncp); // // // int i = 0; // int k = 0; // while(i < ncp) { // // link all cp within reach to form the group // k = 0; // cg(k) = cp(i); // wg(k) = w(i); // // for(int j = i+1; j < ncp; j++) { // if((cp(j) - cp(j-1)) < reach) { // k += 1; // cg(k) = cp(j); // wg(k) = w(j); // // } else { // break; // } // } // cp_out(i) = vmult(cg, wg) / sum(wg); // // i += k + 1; // } // // arma::uvec ids = find(cp_out > 1e-10); // Find indices // return(cp_out.elem(ids)); // // return(cp_out[which0(cp_out)]); // } //' @export //[[Rcpp::export]] NumericVector poolC (IntegerVector& cp_ind, int reach = 10) { int ncp = cp_ind.size(); NumericVector cp_out(ncp); int i = 0; // int ind; while(i < ncp) { // link all cp within reach to form the group int k = 0; for(int j = i+1; j < ncp; j++) { if((cp_ind(j) - cp_ind(j-1)) < reach) { k += 1; } else { break; } } // ind = mean(cp_ind[Range(i, i+k)]) + i; cp_out(i) = mean(cp_ind[Range(i, i+k)]); i += k + 1; } return(cp_out[which0(cp_out)]); // return(cp_out[which0(cp_out)]); } // //' @export // //[[Rcpp::export]] // NumericVector l1fit (NumericVector& m, NumericVector& cp) { // int n = m.size(); // int cpn = cp.size(); // double mhat; // NumericVector fit(n); // // // if no cp then set fit to the mean of the m // if (cpn == 0) { // mhat = mean(m); // for(int j = 0; j < n; j++) { // fit(j) = mhat; // } // return(fit); // } // // // else set fit to the segment means // // fill out regime boundaries // NumericVector regb(cpn+2); // regb(0) = 0; // regb[Range(1, cpn)] = cp; // regb(cpn+1) = n; // // // fit based on change points // NumericVector mi; // // for (int i = 1; i < (cpn+2); i++) { // mi = m[Range(regb(i-1), (regb(i)-1))]; // mhat = mean(mi); // // for(int j = regb[i-1]; j < regb[i]; j++) { // fit(j) = mhat; // } // } // return(fit); // } // //' @export // //[[Rcpp::export]] // double l1bic (NumericVector& m, NumericVector& cp) { // int n = m.size(); // NumericVector fit(n); // double out; // // fit = l1fit(m, cp); // out = n*log(var(m - fit)) + sum(diff(fit) != 0)*log(n); // return(out); // } // //' @export // //[[Rcpp::export]] // NumericVector bic_denoise (NumericVector& m, NumericVector& tv, const int r_init) { // // // get cp locatioons and weights // NumericVector dtv = diff(tv); // IntegerVector cp_ind = which0(dtv); // NumericVector w = dtv[cp_ind]; // // // kseq are all change point jump sizes in the initial fit // // basically just backwards eliminate small change points using the sharpening strat // NumericVector adtv = Rcpp::abs(dtv); // NumericVector kseq = unique(adtv.sort()); // int kl = kseq.size(); // // IntegerVector rseq = seq(r_init, r_init + kl); // NumericVector bics(kl); // // for(int k = 0; k < kl; k++) { // NumericVector cp = sharpenC(cp_ind, w, kseq(k), r_init); // bics(k) = l1bic(m, cp); // } // double k = kseq[which_min(bics)]; // // for(int r = 0; r < kl; r++) { // NumericVector cp = sharpenC(cp_ind, w, k, rseq(r)); // bics(r) = l1bic(m, cp); // } // int r = rseq[which_min(bics)]; // // NumericVector tvfit = sharpenC(cp_ind, w, k, r); // return(l1fit(m, tvfit)); // } // // // //' @export // //[[Rcpp::export]] // NumericVector bic_cp (NumericVector& m, NumericVector& tv, const int r_init) { // // // get cp locatioons and weights // NumericVector dtv = diff(tv); // IntegerVector cp_ind = which0(dtv); // NumericVector w = dtv[cp_ind]; // // // kseq are all change point jump sizes in the initial fit // // basically just backwards eliminate small change points using the sharpening strat // NumericVector adtv = unique(Rcpp::abs(dtv)); // NumericVector kseq = adtv.sort(true); // int kl = kseq.size(); // // IntegerVector rseq = seq(r_init, r_init + kl); // NumericVector bics(kl); // // double k = 0; // for(int i = 1; i < kl; i++) { // NumericVector cp = sharpenC(cp_ind, w, kseq(i), r_init); // bics(i) = l1bic(m, cp); // // if(i > 1 && bics(i) > bics(i-1)) { // k = kseq(i-1); // break; // } // } // // NumericVector bic_sub = bics[which0(bics)]; // // double k = kseq[which_min(bic_sub)]; // // // for(int r = 0; r < kl; r++) { // // NumericVector cp = sharpenC(cp_ind, w, k, rseq(r)); // // bics(r) = l1bic(m, cp); // // } // // int r = rseq[which_min(bics)]; // // // NumericVector cp = sharpenC(cp_ind, w, k, r_init); // // NumericVector weight = diff(l1fit(m, cp)); // // // // return(List::create(cp, weight[cp])); // // return(sharpenC(cp_ind, w, k, r_init)); // }
[ "trevorh2@illinois.edu" ]
trevorh2@illinois.edu
70b076e3ca31dc35a7fdefdff55dab542c74ffac
fae551eb54ab3a907ba13cf38aba1db288708d92
/chrome/updater/test/integration_test_commands_factory_system.cc
085e41240b44de862bda126d580aca9a2904ddd1
[ "BSD-3-Clause" ]
permissive
xtblock/chromium
d4506722fc6e4c9bc04b54921a4382165d875f9a
5fe0705b86e692c65684cdb067d9b452cc5f063f
refs/heads/main
2023-04-26T18:34:42.207215
2021-05-27T04:45:24
2021-05-27T04:45:24
371,258,442
2
1
BSD-3-Clause
2021-05-27T05:36:28
2021-05-27T05:36:28
null
UTF-8
C++
false
false
472
cc
// Copyright 2021 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 "base/memory/scoped_refptr.h" #include "chrome/updater/test/integration_test_commands.h" namespace updater { namespace test { scoped_refptr<IntegrationTestCommands> CreateIntegrationTestCommands() { return CreateIntegrationTestCommandsSystem(); } } // namespace test } // namespace updater
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
d60e6b65145c55a67f0362faeae3a0037b921c2d
ad16b253ec7f3d9f2f72f68b05d785adf6bb8a68
/classes/ParametersBuilder.h
d51f4306b5abf770b71e4d0d85b9cc242bb59e4d
[]
no_license
gladki24/flowerpot_arguments
0cd9d30da43c0252220aaf66b21340ccc8ce7c6f
aa7c91669991b7e172a7a8cb177f117137a2489c
refs/heads/master
2022-12-28T14:48:15.740928
2020-10-12T20:42:52
2020-10-12T20:42:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
752
h
// // Created by Seweryn on 11.10.2020. // #ifndef FLOWERPOTARGUMENTS_PARAMETERSBUILDER_H #include <list> #include <string> #include <map> #include "Parameters.h" #define FLOWERPOTARGUMENTS_PARAMETERSBUILDER_H namespace Flowerpot { class ParametersBuilder { public: ParametersBuilder() = default; ~ParametersBuilder() = default; void AddValue(std::string value); void AddFlag(std::string flag); void AddKeyValue(std::pair<std::string, std::string> keyValue); Parameters Build() const; private: std::list<std::string> _values; std::list<std::string> _flags; std::map<std::string, std::string> _keyValues; }; } #endif //FLOWERPOTARGUMENTS_PARAMETERSBUILDER_H
[ "seweryngla@hotmail.com" ]
seweryngla@hotmail.com
266bd2b8b4f1ad5a95110d8d7298b80ad1fe501c
ff087f48d12684a84de77b25eb6b2c18462e876c
/project7/task2_cpp/headers/utilityFunctions.h
f16b94e58072aea36fd8e41c1322eadd492d3a1e
[]
no_license
vladimir-vakhter/system-level-design-and-modeling
bdf88065b1eb96cb59d38dda1c1b1289946893e5
c40866887bc4cb7ce47d058d2dd8c50963213492
refs/heads/main
2023-02-01T12:19:42.635233
2020-12-12T15:02:43
2020-12-12T15:02:43
320,045,437
0
0
null
null
null
null
UTF-8
C++
false
false
264
h
#include <iostream> #include <string> char And(char a, char b); char Or(char a, char b); char Not(char a); char Tri(char a, char c); char Resolve(char a, char c); char Xor(char a, char b); void FullAdder(char a, char b, char ci, char& co, char& sum);
[ "noreply@github.com" ]
noreply@github.com
eb1eac556e88229fc852f5e6cb7d1446992bd0cc
3a0e06c5ff680fe2bb316551204684b3478c1015
/Engine/Renderer/Pipeline/RenderBuffer.cpp
d62344ec1b4a322da0122bf2c8cb134fb1290a01
[]
no_license
itsdrell/Strawberry
3fdb37a0300506780ca94959dae68010d5d6f122
e852a67a161e5b026b039e0794209d517d7a84bc
refs/heads/master
2022-05-10T18:51:56.767445
2022-05-08T04:21:27
2022-05-08T04:21:27
168,198,048
0
0
null
null
null
null
UTF-8
C++
false
false
1,624
cpp
#include "RenderBuffer.hpp" #include "Engine/Internal/EmscriptenCommon.hpp" //=============================================================================================== RenderBuffer::RenderBuffer() { m_handle = 0; m_bufferSize = 0; } RenderBuffer::~RenderBuffer() { if (m_handle != NULL) { glDeleteBuffers( 1, &m_handle ); GL_CHECK_ERROR(); m_handle = NULL; } } bool RenderBuffer::CopyToGPU(size_t const byteCount, void const * data) { GL_CHECK_ERROR(); // handle is a GLuint member - used by OpenGL to identify this buffer // if we don't have one, make one when we first need it [lazy instantiation] if (m_handle == NULL) { glGenBuffers( 1, &m_handle ); GL_CHECK_ERROR(); } // Bind the buffer to a slot, and copy memory // GL_DYNAMIC_DRAW means the memory is likely going to change a lot (we'll get // during the second project) glBindBuffer( GL_ARRAY_BUFFER, m_handle ); GL_CHECK_ERROR(); glBufferData( GL_ARRAY_BUFFER, byteCount, data, GL_DYNAMIC_DRAW ); GL_CHECK_ERROR(); // buffer_size is a size_t member variable I keep around for // convenience m_bufferSize = byteCount; return true; } //=============================================================================================== IndexBuffer::IndexBuffer(uint indexCount, uint indexStride) { m_indexCount = indexCount; m_indexStride = indexStride; } //=============================================================================================== VertexBuffer::VertexBuffer(uint vertexCount, uint vertexStride) { m_vertexCount = vertexCount; m_vertexStride = vertexStride; }
[ "ztbracken@gmail.com" ]
ztbracken@gmail.com
cdc231f6fd66899da35a493ffcaca39914382391
de80b91a12b10bd962b59a89b2badbb83a0193da
/ClientProject/Mof/MofLibrary/Include/Sound/XAudio/XAudioSound.h
365aedf48431bff63ed7aba3bd512483071bd109
[ "MIT" ]
permissive
OIC-Shinchaemin/RatchetNclank-PrivateCopy
8845eea799b3346646c8c93435c0149e842dede8
e2e646e89ef3c29d474a503f5ca80405c4c676c9
refs/heads/main
2023-08-15T06:36:05.244293
2021-10-08T00:34:48
2021-10-08T00:34:48
350,923,064
0
0
MIT
2021-10-06T11:05:03
2021-03-24T02:35:36
C++
SHIFT_JIS
C++
false
false
2,958
h
/*************************************************************************//*! @file XAudioSound.h @brief XAudio2での各種サウンドの処理を行うクラス。 @author CDW @date 2014.05.14 *//**************************************************************************/ //ONCE #ifndef __XAUDIOSOUND__H__ #define __XAUDIOSOUND__H__ //INCLUDE #include "../Sound.h" namespace Mof { /*******************************//*! @brief サウンド基底インターフェイス サウンドの基底となるインターフェイス。 @author CDW *//********************************/ class MOFLIBRARY_API CXAudioSound : public ISound { protected: /*******************//*! XAudio2オブジェクト *//********************/ IXAudio2* m_pSound; /*******************//*! マスター *//********************/ IXAudio2MasteringVoice* m_pMastering; public: /*************************************************************************//*! @brief コンストラクタ @param None @return None *//**************************************************************************/ CXAudioSound(); /*************************************************************************//*! @brief デストラクタ @param None @return None *//**************************************************************************/ virtual ~CXAudioSound(); /*************************************************************************//*! @brief サウンドオブジェクトの生成 @param[in] pInfo サウンドの生成情報 @return TRUE 成功<br> それ以外 失敗、エラーコードが戻り値となる *//**************************************************************************/ virtual MofBool Create(LPSOUNDCREATEINFO pInfo); /*************************************************************************//*! @brief 解放 @param[in] pData 解放追加データ @return TRUE 正常終了<br> それ以外 解放エラー、エラーコードを返す。 *//**************************************************************************/ virtual MofBool Release(LPMofVoid pData = NULL); //---------------------------------------------------------------------------- ////Get //---------------------------------------------------------------------------- /*************************************************************************//*! @brief サウンドデバイス取得<br> 使用しない環境で呼び出した場合NULLを返す。 @param None @return サウンドデバイス *//**************************************************************************/ virtual MofSoundDevice GetDevice(void); //クラス基本定義 MOF_LIBRARYCLASS_NOTCOPY(CXAudioSound,MOF_XAUDIOSOUNDCLASS_ID); }; #include "XAudioSound.inl" } #endif //[EOF]
[ "shin@oic.jp" ]
shin@oic.jp
bd62a23243b59bb991f2fae53e8865341ef28e10
2c8c76c3ad0d39e901cb7264d5738102de44047e
/co-op/UI/ExportImportHistoryDlg.cpp
b72b82fee058f507142c34e2fe44b2967bebfa43
[ "MIT" ]
permissive
jjzhang166/CodeCoop
87d4404f2dab5676915f0a72fc82869199b306c9
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
refs/heads/master
2023-07-11T07:01:22.342089
2018-03-01T15:24:01
2018-03-01T15:24:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
//------------------------------------ // (c) Reliable Software, 2007 - 2008 //------------------------------------ #include "precompiled.h" #include "ExportImportHistoryDlg.h" #include <File/File.h> History::ExportRequest::ExportRequest (std::string const & projectName) : SaveFileRequest ("Export Code Co-op Project History", "Exported history file name: ", "Store the project history on: ", "Recent History Export", "History Export FTP Site", "History Export Path") { _fileName = projectName; _fileName += ".his"; File::LegalizeName (_fileName); _fileDescription = "project history"; _userNote = "Note: The history you are exporting can only be imported in enlistments that have already joined this project." " Future joins will not be able to accept this history."; } History::OpenRequest::OpenRequest () : OpenFileRequest ("Open Code Co-op Project History File", "The project history is present on: ", "Select History File To Open", "Recent History Import", "History Import FTP Site", "History Import Path") {}
[ "bartosz@relisoft.com" ]
bartosz@relisoft.com
0ec84aa8942c3fb4d916b5b96ba8916473e98485
c05a19257d337df35fdd3f91c3d5037bf0f3b05c
/src/ofApp.cpp
f46d526e730e7a7125c483ceef2eb193bb21138f
[]
no_license
frikkfossdal/improved-garbanzo
a2d8bd1cc5d9a425359887b30cc7d43dbbcee375
1a0196abc6d7128895a5cc7d03141b83a09b9a7a
refs/heads/master
2021-04-15T14:06:06.741642
2019-02-05T07:21:57
2019-02-05T07:21:57
126,347,919
0
0
null
null
null
null
UTF-8
C++
false
false
2,367
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ node1.createShape(); node1.startNode(); node2.createShape(); node2.startNode(); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(55); cam.begin(); node1.show(); node2.show(); cam.end(); ofSetColor(255, 55); <<<<<<< HEAD ofDrawBitmapString(node1.timeIndex2, 50, 50); ofDrawBitmapString(node2.timeIndex2, 50, 80); ======= ofDrawBitmapString(node1.pos, 50, 50); ofDrawBitmapString(node2.pos, 50, 70); ofDrawBitmapString(node1.timeIndex, 50, 100); ofDrawBitmapString(node2.timeIndex, 50, 120); >>>>>>> fec6f1599aef9cace230d64c667a36a22f6d9672 } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ <<<<<<< HEAD //node1.createShape(); node1.stopNode(); node2.stopNode(); ======= >>>>>>> fec6f1599aef9cace230d64c667a36a22f6d9672 } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ node1.stopNode(); } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ node1.startNode(); <<<<<<< HEAD node2.startNode(); ======= >>>>>>> fec6f1599aef9cace230d64c667a36a22f6d9672 } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "frikkfossdal@gmail.com" ]
frikkfossdal@gmail.com
9eb98561d41ba7f74daccb63a829053f23e5f950
24665ce459a8f67ce90337d6897aa05343d5199f
/Source/Mode.h
1eb471f04db8efb1c3051390818b2fc34ffbce0f
[]
no_license
vsicurella/Tune-Up-MIDI
ef5a9edb01a770c67420cea02ffb60cbe1153547
8d492b9b0fc911aa9850d7378717ced1e4c90716
refs/heads/master
2023-06-10T12:09:39.104247
2021-06-12T17:28:05
2021-06-12T17:28:05
276,292,142
4
0
null
null
null
null
UTF-8
C++
false
false
6,413
h
/* ============================================================================== ModeLayout.h Created: 31 Mar 2019 2:16:09pm Author: Vincenzo ============================================================================== */ #pragma once #include "CommonFunctions.h" /* A class for representing the layout of a virtualKeyboard based on a given mode. The mode can be applied to different scales. */ class Mode { String name; int scaleSize; int modeSize; String family; String info; StringArray tags; int rootNote = 60; int offset; String stepsString; Array<int> steps; Array<int> ordersDefault; Array<int> mosClass; Array<int> orders; Array<int> scaleDegrees; Array<float> modeDegrees; // Keyboard Convenience Array<int> stepsOfOrders; // each index is the step which the note is associated with Array<int> keyboardOrdersSizes; // amount of keys in each key order groupings public: ValueTree modeNode; Mode(); Mode(String stepsIn, String familyIn="undefined", int rootNoteIn=60, String nameIn="", String infoIn=""); Mode(Array<int> stepsIn, String familyIn="undefined", int rootNoteIn=60, String nameIn="", String infoIn=""); Mode(ValueTree modeNodeIn, bool copyNode=false); ~Mode(); void updateNode(bool initializeNode=false); void restoreNode(ValueTree nodeIn, bool useNodeRoot=true); static bool isValidMode(ValueTree nodeIn); static ValueTree createNode(String stepsIn, String familyIn = "undefined", String nameIn = "", String infoIn="", int rootNoteIn=60, bool factoryPreset = false); static ValueTree createNode(Array<int> stepsIn, String familyIn = "undefined", String nameIn = "", String infoIn="", int rootNoteIn=60, bool factoryPreset = false); /* Sets temperament family name. */ void setFamily(String familyIn); /* Sets custom name of the mode. */ void setName(String nameIn); /* Sets info regarding the mode. */ void setInfo(String infoIn); /* Recalculates mode properties based on parameter change */ void updateProperties(); /* Sets the offset of the mode and updates parameters so that the offset replaces the current visualization of the mode */ void setRootNote(int rootNoteIn); /* Rotates the mode to the amount of given steps */ void rotate(int rotateAmt); void addTag(String tagIn); int removeTag(String tagIn); int getRootNote() const; int getOffset() const; int getScaleSize() const; int getModeSize() const; Array<int> getIntervalSizeCount() const; String getFamily() const; String getName() const; String getInfo() const; StringArray getTags() const; Array<int>* getKeyboardOrdersSizes(); int getKeyboardOrdersSize(int ordersIn) const; Array<int> getStepsOfOrders() const; int getNoteStep(int noteNumberIn) const; Array<int> getSteps(int rotationIn=0) const; String getStepsString(int rotationIn=0) const; Array<int> getOrdersDefault() const; Array<int> getOrders() const; int getOrder(int noteNumberIn) const; Array<float> getModalDegrees() const; Array<int> getScaleDegrees() const; int getScaleDegree(int midiNoteIn) const; float getModeDegree(int midiNoteIn) const; int getMidiNote(int scaleDegreeIn) const; int getMidiNote(int periodIn, int scaleDegreeIn) const; int getMaxStep() const; Array<int> getMOSClass() const; String getDescription() const; String getScaleDescription() const; String getModeDescription() const; Array<int> getNotesOfOrder(int order = 0) const; int indexOfTag(String tagNameIn); /* Returns -1 if modes are different, otherwise returns the number of rotations needed to make the modes equivalent. */ int isSimilarTo(Mode* modeToCompare) const; /* Returns a table of note numbers (with current root) organized by key order. */ Array<Array<int>> getNotesOrders(); /* Returns a table of note numbers (with current root) organized by scale degree. */ Array<Array<int>> getNotesInScaleDegrees(); /* Returns a table of note numbers (with current root) organized by modal degree. */ Array<Array<int>> getNotesInModalDegrees(); /* Simply parses a string reprsenting step sizes and returns a vector */ static Array<int> parseIntStringToArray(String stepsIn); /* Takes in step vector like {2, 2 , 1 , 2 , 2 , 2 , 1} Returns a string like "2 2 1 2 2 2 1" */ static String intArrayToString(Array<int> stepsIn); /* Takes in a vector like {2, 2, 1, 2, 2, 2, 1} and a mask like {0, 0, 2, 0, 0, 0, 2} Returns a vector of each index repeated by the mask {2, 2, 1, 1, 2, 2, 2, 1, 1} If no mask supplied, then it uses it's own magnitudes. */ static Array<int> repeatIndicies(Array<int> arrayToRepeat, Array<int> repeatMask=Array<int>()); /* Takes in step vector like {2, 2, 1, 2, 2, 2, 1} Returns a vector of key orders {0, 1, 0, 1, 0, 0, 1,...} */ static Array<int> unfoldStepsToOrders(Array<int> stepsIn); /* Takes in array of a scale layout of note orders (1:1) {0, 1, 0, 1 , 0, 0, 1,...} and returns scale step size layout "2, 2, 1, 2,..." */ static Array<int> foldOrdersToSteps(Array<int> layoutIn); /* Takes in a period-size vector, a new vector size, and an offset Returns a vector at new size using original vector's period for repetition with the given offset */ // needs revision to allow for notes to start in the middle of a step static Array<int> repeatArray(Array<int> ordersIn, int sizeIn, int offsetIn=0); /* Takes in array of a scale layout of note orders (1:1) {0, 1, 0, 1 , 0, 0, 1,...} and returns scale step size layout "0, 0.5, 1, 1.5,..." */ static Array<float> ordersToModalDegrees(Array<int> ordersIn); /* Simply creates an array of scale degrees based off of scale size and offset */ static Array<int> generateScaleDegrees(int scaleSize, int offset = 0); /* Takes in a vector like {2, 2, 1, 2, 2, 2, 1} Returns a vector of sizes large->small like {5, 2} */ static Array<int> intervalAmounts(Array<int> stepsIn); /* Takes in a vector like {2, 2, 1, 2, 2, 2, 1} And returns a sum of the previous indicies at each index like {0, 2, 4, 5, 7, 9, 11} */ static Array<int> sumArray(Array<int> stepsIn, int offsetIn = 0, bool includePeriod = false); };
[ "sicurella12@gmail.com" ]
sicurella12@gmail.com
def47041ed2c1d6712060f1864e23309982e1d29
4e38faaa2dc1d03375010fd90ad1d24322ed60a7
/src/Dump/Reflection.cpp
1c4563644a39195789bb0e92d5c7b58a7f0867cf
[ "MIT" ]
permissive
WopsS/RED4ext.SDK
0a1caef8a4f957417ce8fb2fdbd821d24b3b9255
3a41c61f6d6f050545ab62681fb72f1efd276536
refs/heads/master
2023-08-31T08:21:07.310498
2023-08-18T20:51:18
2023-08-18T20:51:18
324,193,986
68
25
MIT
2023-08-18T20:51:20
2020-12-24T16:17:20
C++
UTF-8
C++
false
false
142
cpp
#ifndef RED4EXT_STATIC_LIB #error Please define 'RED4EXT_STATIC_LIB' to compile this file. #endif #include <RED4ext/Dump/Reflection-inl.hpp>
[ "expired6978@gmail.com" ]
expired6978@gmail.com
868b3a978c25d0be21e996b32ca3aef19ec207dd
a1dabfd418d0b1dc4c2d3d63084506c1a23bb6f1
/src/utils/Array.cpp
6253f71ef8a5421a5ed8e0becdfac7235864663f
[ "Apache-2.0" ]
permissive
brinkqiang2cpp/metacpp-1
b57b10c34f69c8b78c48230e17e411ffec29f0f8
e8e728cf936adb1ec44814675d01aad5421e121f
refs/heads/master
2020-06-01T19:17:21.417166
2016-04-29T11:21:04
2016-04-29T11:21:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
cpp
/**************************************************************************** * Copyright 2014-2015 Trefilov Dmitrij * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ****************************************************************************/ #include "Array.h"
[ "the-alien@live.ru" ]
the-alien@live.ru
20359e572e1381690a03757003d6ae19aebc86f0
88de295bd35bc504104815e1afd897266802875b
/legacy/tau/tau+/b1/tau+/tau_core/tau_structures.hpp
b72cbea4a8465ac4ff5866caa0bdc5c52107b9c9
[]
no_license
mfonken/combine
4a26545c8e742dfcbc21d16236f6c5a346bfcb16
aac79987ebfd4af0c8e1d441826bc1bfd78e39da
refs/heads/master
2022-11-30T21:40:19.574096
2022-11-18T04:08:04
2022-11-18T04:08:04
94,054,420
0
1
null
null
null
null
UTF-8
C++
false
false
3,586
hpp
// // tau_structures.hpp // tau+ // // Created by Matthew Fonken on 2/8/18. // Copyright © 2018 Marbl. All rights reserved. // #ifndef tau_structures_hpp #define tau_structures_hpp #include <stdio.h> #include <stdint.h> #include <sys/time.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "test_setup.h" #include "kalman.hpp" #define ABSINV(X) ((X<1)?1-X:X-1) #define ABS(X) ((X>=0)?X:-X) #define GTTHR(X,Y,T) X>=(Y+T) #define INRANGE(X,Y,T) (X>(Y-T)&&X<(Y+T)) #define MAX_PERSISTENCE ( 1 << 7 ) - 1 // MAX OF SIGNED BYTE static inline double timeDiff( struct timeval a, struct timeval b ) { return ((b.tv_sec - a.tv_sec) + (b.tv_usec - a.tv_usec)/1000000.0) + 0.0005; } typedef int image_dimension_base_t; typedef unsigned char pixel_base_t; typedef struct { int width, height; pixel_base_t * pixels; }cimage_t; static double pixelDist(cv::Vec3b p) { return p[2]>100?255:0; /*sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);*/ } // static double thresh(cv::Vec3b p) { return pixelDist(p); } static void cimageInit( cimage_t * img, int width, int height ) { img->width = width; img->height = height; img->pixels = (pixel_base_t *)malloc(sizeof(pixel_base_t)*width*height); } static void cimageFromMat( cv::Mat mat, cimage_t * img ) { int w = mat.cols, h = mat.rows, p = 0; for(int y = 0; y < h; y++ ) { for(int x = 0; x < w; x++) { img->pixels[p++] = (pixel_base_t)pixelDist(mat.at<cv::Vec3b>(y,x)); } } } static void cimageToMat( cimage_t * img, cv::Mat mat ) { int w = img->width, h = img->height, p = 0; unsigned char d = 0; mat.cols = w; mat.rows = h; for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { p = x + y*h; d = (img->pixels[p]>0)*255; cv::Vec3b c = {d,d,d}; mat.at<cv::Vec3b>(y,x) = c; } } } typedef enum { UNWEIGHTED = 0, WEIGHTED = 1 } sorting_settings; /* Tau filter types specifically for kalman matrix structure */ typedef enum { NO_FILTER = 0, SOFT_FILTER, HARSH_FILTER, CHAOS_FILTER } filter_t; /* Stability tracking for selec tions */ class Stability { public: double primary; double secondary; double alternate; double overall; }; #define PREDICTION_LIFESPAN 1.0 #define PREDICTION_VALUE_UNCERTAINTY 0.5 #define PREDICTION_BIAS_UNCERTAINTY 0.01 #define PREDICTION_SENSOR_UNCERTAINTY 0.001 typedef struct { double primary, secondary, alternate; } prediction_probabilities_t; class Prediction { public: KalmanFilter primary, secondary; double primary_new, secondary_new; prediction_probabilities_t probabilities; Prediction(); }; typedef enum { SIMILAR = 0, OPPOSITE } selection_pair_t; class PredictionPair { public: Prediction x; Prediction y; selection_pair_t selection_pair; }; /* RHO */ class DensityMap { public: int * map; int * fil; int length; int max; double variance; KalmanFilter kalman; }; class DensityMapPair { public: DensityMap x; DensityMap y; DensityMapPair( int, int ); }; class PeakList { public: int length; int* map; int* den; int* max; }; class PeakListPair { public: PeakList x; PeakList y; PeakListPair(); }; /* SIGMA */ #endif /* tau_structures_hpp */
[ "mgfonken@gmail.com" ]
mgfonken@gmail.com
64a21ea0c442c984292c5661ef77b040ca4863ad
bc0b701fc41f2218af511c4ecbd675c8bf365f1c
/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
480342c1a342ff39c21fb7cb0b4fd7be7d5868e0
[ "NCSA" ]
permissive
lygstate/safecode-mirror
768810a51816e6abc6f190a0b72ea27d1fc7df09
27e48405e9cd268a53429226c51bdffe9fb8fb6a
refs/heads/master
2021-01-18T06:46:23.842583
2011-09-19T15:24:28
2011-09-19T15:24:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,868
cpp
//===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines PthreadLockChecker, a simple lock -> unlock checker. // Also handles XNU locks, which behave similarly enough to share code. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/ImmutableList.h" using namespace clang; using namespace ento; namespace { class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > { mutable llvm::OwningPtr<BugType> BT_doublelock; mutable llvm::OwningPtr<BugType> BT_lor; enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics }; public: void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const; void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const; }; } // end anonymous namespace // GDM Entry for tracking lock state. namespace { class LockSet {}; } namespace clang { namespace ento { template <> struct ProgramStateTrait<LockSet> : public ProgramStatePartialTrait<llvm::ImmutableList<const MemRegion*> > { static void *GDMIndex() { static int x = 0; return &x; } }; } // end GR namespace } // end clang namespace void PthreadLockChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { const ProgramState *state = C.getState(); const Expr *Callee = CE->getCallee(); const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl(); if (!FD) return; // Get the name of the callee. IdentifierInfo *II = FD->getIdentifier(); if (!II) // if no identifier, not a simple C function return; StringRef FName = II->getName(); if (CE->getNumArgs() != 1) return; if (FName == "pthread_mutex_lock" || FName == "pthread_rwlock_rdlock" || FName == "pthread_rwlock_wrlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0)), false, PthreadSemantics); else if (FName == "lck_mtx_lock" || FName == "lck_rw_lock_exclusive" || FName == "lck_rw_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0)), false, XNUSemantics); else if (FName == "pthread_mutex_trylock" || FName == "pthread_rwlock_tryrdlock" || FName == "pthread_rwlock_tryrwlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0)), true, PthreadSemantics); else if (FName == "lck_mtx_try_lock" || FName == "lck_rw_try_lock_exclusive" || FName == "lck_rw_try_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0)), true, XNUSemantics); else if (FName == "pthread_mutex_unlock" || FName == "pthread_rwlock_unlock" || FName == "lck_mtx_unlock" || FName == "lck_rw_done") ReleaseLock(C, CE, state->getSVal(CE->getArg(0))); } void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; const ProgramState *state = C.getState(); SVal X = state->getSVal(CE); if (X.isUnknownOrUndef()) return; DefinedSVal retVal = cast<DefinedSVal>(X); if (state->contains<LockSet>(lockR)) { if (!BT_doublelock) BT_doublelock.reset(new BugType("Double locking", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_doublelock, "This lock has already " "been acquired", N); report->addRange(CE->getArg(0)->getSourceRange()); C.EmitReport(report); return; } const ProgramState *lockSucc = state; if (isTryLock) { // Bifurcate the state, and allow a mode where the lock acquisition fails. const ProgramState *lockFail; switch (semantics) { case PthreadSemantics: llvm::tie(lockFail, lockSucc) = state->assume(retVal); break; case XNUSemantics: llvm::tie(lockSucc, lockFail) = state->assume(retVal); break; default: llvm_unreachable("Unknown tryLock locking semantics"); break; } assert(lockFail && lockSucc); C.addTransition(lockFail); } else if (semantics == PthreadSemantics) { // Assume that the return value was 0. lockSucc = state->assume(retVal, false); assert(lockSucc); } else { // XNU locking semantics return void on non-try locks assert((semantics == XNUSemantics) && "Unknown locking semantics"); lockSucc = state; } // Record that the lock was acquired. lockSucc = lockSucc->add<LockSet>(lockR); C.addTransition(lockSucc); } void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; const ProgramState *state = C.getState(); llvm::ImmutableList<const MemRegion*> LS = state->get<LockSet>(); // FIXME: Better analysis requires IPA for wrappers. // FIXME: check for double unlocks if (LS.isEmpty()) return; const MemRegion *firstLockR = LS.getHead(); if (firstLockR != lockR) { if (!BT_lor) BT_lor.reset(new BugType("Lock order reversal", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_lor, "This was not the most " "recently acquired lock. " "Possible lock order " "reversal", N); report->addRange(CE->getArg(0)->getSourceRange()); C.EmitReport(report); return; } // Record that the lock was released. state = state->set<LockSet>(LS.getTail()); C.addTransition(state); } void ento::registerPthreadLockChecker(CheckerManager &mgr) { mgr.registerChecker<PthreadLockChecker>(); }
[ "criswell@91177308-0d34-0410-b5e6-96231b3b80d8" ]
criswell@91177308-0d34-0410-b5e6-96231b3b80d8
397bdb7eaeb6d2b9831af8c08dd8fb178f723730
bd6812a3da4ad51328e85676c1b443cee2a4f0da
/tests/grid_stokeslets/main_slip.cpp
610d9c8b56832519cce67f1da2323b2067622996
[]
no_license
calinacopos/Parallelized-CUDA-Method-of-Regularized-Stokeslets
f608f8a6fc865d95395fbfa0c8afed6bbe57d374
9faa8c9b29403873e19a728ca8a4f16e1d040fb0
refs/heads/master
2022-04-18T23:20:30.898241
2020-04-17T15:07:46
2020-04-17T15:07:46
256,535,560
0
0
null
null
null
null
UTF-8
C++
false
false
18,903
cpp
/* main_slip.cpp * GPU Benchmark Immersed Boundary Structured Grid * Based on "The Method of Regularized Stokelets" by R.Cortez` * C.Copos 11/12/2012 */ #include <GL/glut.h> #include <iostream> #include <fstream> #include <stdlib.h> #include <math.h> #include <time.h> #include <cstdio> #include <cstdlib> #include <stdio.h> using namespace std; const double PI = 3.14159265358979323846264338f; const int N = 32; // # side square partitions const float visc = 1.0f; const float flow = 1.0f; const float drag = 0.0001f; // time const float TMAX = 0.08f; const float tstep = 0.001f; static double stop = TMAX/tstep; // curve constants const float r0 = 1.0f; const float ri = 1.2f; const double ds = ri/(N-1); const double e = 1.2f*ds; // e: parameter determining width of blobs or cutoffs // vector structure struct vector{ double x; // x-component double y; // y-component }; // spring constants const double kl = 1.0f*ds/*0.1f*ds*/; const double ks = 0.5f*kl; // from victor camacho's elasticity paper // OpenGL Initialization void init(); // OpenGL Callback functions void display(void); void keyboard(unsigned char key); // OpenGL Support Functions void drawObject(); // Define the window position on screen int window_x; int window_y; // Variable representing the window size and title int window_width = 400; int window_height = 400; // Set OpenGL program initial state void init(void) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glPointSize(5.0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); } // Compute time difference in seconds double diffclock(clock_t s, clock_t e) { double diffticks = s-e; double diffms = (diffticks)/CLOCKS_PER_SEC; return diffms; } // Compute average elastic force at point ij due to its nearest neighboring points vector eforce(int i, int j, double x[N][N], double y[N][N]) { vector f; // final force double rl = r0/(N-1); // rest length for longitudinal springs double rd = sqrtf(2.0f)*rl; // rest length for diagonal springs int i_0, i_1, i_2, j_0, j_1, j_2; i_0 = i-1; i_1 = i; i_2 = i+1; j_0 = j-1; j_1 = j; j_2 = j+1; double dlk_00, dlk_01, dlk_02, dlk_10, dlk_12, dlk_20, dlk_21, dlk_22; vector f_00, f_01, f_02, f_10, f_12, f_20, f_21, f_22; // distance between point (i,j) = (i_1,j_1) and points ... // top left corner if (i_1==0 && j_1==0) { dlk_00 = 0.0f; dlk_10 = 0.0f; dlk_20 = 0.0f; dlk_01 = 0.0f; dlk_02 = 0.0f; dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); dlk_22 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_2],2) + powf(y[i_1][j_1]-y[i_2][j_2],2)); } // top right corner else if (i_1==(N-1) && j_1==0) { dlk_00 = 0.0f; dlk_10 = 0.0f; dlk_20 = 0.0f; dlk_21 = 0.0f; dlk_22 = 0.0f; dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); dlk_02 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_2],2) + powf(y[i_1][j_1]-y[i_0][j_2],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); } // bottom left corner else if (i_1==0 && j_1==(N-1)) { dlk_00 = 0.0f; dlk_01 = 0.0f; dlk_02 = 0.0f; dlk_12 = 0.0f; dlk_22 = 0.0f; dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_20 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_0],2) + powf(y[i_1][j_1]-y[i_2][j_0],2)); dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); } // bottom right corner else if (i_1==(N-1) && j_1==(N-1)) { dlk_20 = 0.0f; dlk_21 = 0.0f; dlk_22 = 0.0f; dlk_12 = 0.0f; dlk_02 = 0.0f; dlk_00 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_0],2) + powf(y[i_1][j_1]-y[i_0][j_0],2)); dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); } // top edge else if (j_1==0) { dlk_00 = 0.0f; dlk_10 = 0.0f; dlk_20 = 0.0f; dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); dlk_02 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_2],2) + powf(y[i_1][j_1]-y[i_0][j_2],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); dlk_22 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_2],2) + powf(y[i_1][j_1]-y[i_2][j_2],2)); } // right edge else if (i_1==(N-1)) { dlk_20 = 0.0f; dlk_21 = 0.0f; dlk_22 = 0.0f; dlk_00 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_0],2) + powf(y[i_1][j_1]-y[i_0][j_0],2)); dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); dlk_02 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_2],2) + powf(y[i_1][j_1]-y[i_0][j_2],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); } // bottom edge else if (j_1==(N-1)) { dlk_02 = 0.0f; dlk_12 = 0.0f; dlk_22 = 0.0f; dlk_00 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_0],2) + powf(y[i_1][j_1]-y[i_0][j_0],2)); dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_20 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_0],2) + powf(y[i_1][j_1]-y[i_2][j_0],2)); dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); } // left edge else if (i_1==0) { dlk_00 = 0.0f; dlk_01 = 0.0f; dlk_02 = 0.0f; dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_20 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_0],2) + powf(y[i_1][j_1]-y[i_2][j_0],2)); dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); dlk_22 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_2],2) + powf(y[i_1][j_1]-y[i_2][j_2],2)); } // interior else { dlk_00 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_0],2) + powf(y[i_1][j_1]-y[i_0][j_0],2)); dlk_10 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_0],2) + powf(y[i_1][j_1]-y[i_1][j_0],2)); dlk_20 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_0],2) + powf(y[i_1][j_1]-y[i_2][j_0],2)); dlk_01 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_1],2) + powf(y[i_1][j_1]-y[i_0][j_1],2)); dlk_21 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_1],2) + powf(y[i_1][j_1]-y[i_2][j_1],2)); dlk_02 = sqrtf(powf(x[i_1][j_1]-x[i_0][j_2],2) + powf(y[i_1][j_1]-y[i_0][j_2],2)); dlk_12 = sqrtf(powf(x[i_1][j_1]-x[i_1][j_2],2) + powf(y[i_1][j_1]-y[i_1][j_2],2)); dlk_22 = sqrtf(powf(x[i_1][j_1]-x[i_2][j_2],2) + powf(y[i_1][j_1]-y[i_2][j_2],2)); } // finally, compute forces if (dlk_00 == 0.0f) { f_00.x = 0.0f; f_00.y = 0.0f; } else { f_00.x = -1.0f*ks*(dlk_00-rd)*((x[i_1][j_1] - x[i_0][j_0])/dlk_00); f_00.y = -1.0f*ks*(dlk_00-rd)*((y[i_1][j_1] - y[i_0][j_0])/dlk_00); } if (dlk_10 == 0.0f) { f_10.x = 0.0f; f_10.y = 0.0f; } else { f_10.x = -1.0f*kl*(dlk_10-rl)*((x[i_1][j_1] - x[i_1][j_0])/dlk_10); f_10.y = 1.0f*kl*(dlk_10-rl)*((-y[i_1][j_1] + y[i_1][j_0])/dlk_10); } if (dlk_20 == 0.0f) { f_20.x = 0.0f; f_20.y = 0.0f; } else { f_20.x = -1.0f*ks*(dlk_20-rd)*((x[i_1][j_1] - x[i_2][j_0])/dlk_20); f_20.y = -1.0f*ks*(dlk_20-rd)*((y[i_1][j_1] - y[i_2][j_0])/dlk_20); } if (dlk_01 == 0.0f) { f_01.x = 0.0f; f_01.y = 0.0f; } else { f_01.x = -1.0f*kl*(dlk_01-rl)*((x[i_1][j_1] - x[i_0][j_1])/dlk_01); f_01.y = 1.0f*kl*(dlk_01-rl)*((-y[i_1][j_1] + y[i_0][j_1])/dlk_01); } if (dlk_21 == 0.0f) { f_21.x = 0.0f; f_21.y = 0.0f; } else { f_21.x = -1.0f*kl*(dlk_21-rl)*((x[i_1][j_1] - x[i_2][j_1])/dlk_21); f_21.y = 1.0f*kl*(dlk_21-rl)*((-y[i_1][j_1] + y[i_2][j_1])/dlk_21); } if (dlk_02 == 0.0f) { f_02.x = 0.0f; f_02.y = 0.0f; } else { f_02.x = -1.0f*ks*(dlk_02-rd)*((x[i_1][j_1] - x[i_0][j_2])/dlk_02); f_02.y = -1.0f*ks*(dlk_02-rd)*((y[i_1][j_1] - y[i_0][j_2])/dlk_02); } if (dlk_12 == 0.0f) { f_12.x = 0.0f; f_12.y = 0.0f; } else { f_12.x = -1.0f*kl*(dlk_12-rl)*((x[i_1][j_1] - x[i_1][j_2])/dlk_12); f_12.y = 1.0f*kl*(dlk_12-rl)*((-y[i_1][j_1] + y[i_1][j_2])/dlk_12); } if (dlk_22 == 0.0f) { f_22.x = 0.0f; f_22.y = 0.0f; } else { f_22.x = -1.0f*ks*(dlk_22-rd)*((x[i_1][j_1] - x[i_2][j_2])/dlk_22); f_22.y = -1.0f*ks*(dlk_22-rd)*((y[i_1][j_1] - y[i_2][j_2])/dlk_22); } // evaluate final force components f.x = (double)(f_00.x + f_10.x + f_20.x + f_01.x + f_21.x + f_02.x + f_12.x + f_22.x); f.y = (double)(f_00.y + f_10.y + f_20.y + f_01.y + f_21.y + f_02.y + f_12.y + f_22.y); // what's going on with the forces? //printf("%f %f %f %f\n", x[i][j], y[i][j], f.x, f.y); ///* //printf("Force @ position: (%f,%f) is: (%f,%f)\n", x[i][j], y[i][j], f.x, f.y); //printf("Force due to (0,0) neighbor is: (%f,%f)\n", f_00.x, f_00.y); //printf("Force due to (1,0) neighbor is: (%f,%f)\n", f_10.x, f_10.y); //printf("Force due to (2,0) neighbor is: (%f,%f)\n", f_20.x, f_20.y); //printf("Force due to (0,1) neighbor is: (%f,%f)\n", f_01.x, f_01.y); //printf("Force due to (2,1) neighbor is: (%f,%f)\n", f_21.x, f_21.y); //printf("Force due to (0,2) neighbor is: (%f,%f)\n", f_02.x, f_02.y); //printf("Force due to (1,2) neighbor is: (%f,%f)\n", f_12.x, f_12.y); //printf("Force due to (2,2) neighbor is: (%f,%f)\n", f_22.x, f_22.y); //*/ return f; } // Compute pressure at point ij due to all other points in the structured grid double pressure(int i, int j, double x[N][N], double y[N][N]) { double p; vector f; double pp = 0.0f; // partial pressure double rk = 0.0f; double sq = 0.0f; for (int jj=0; jj<N; jj++) { // loop over all nodes in the grid for (int ii=0; ii<N; ii++) { f.x = eforce(ii, jj, x, y).x; f.y = eforce(ii, jj, x, y).y; double r = sqrtf(powf(x[i][j],2) + powf(y[i][j],2)); double pk = sqrtf(powf(x[ii][jj],2)+powf(y[ii][jj],2)); double theta = atan2f(y[i][j], x[i][j]); double thetaj = atan2f(y[ii][jj], x[ii][jj]); double dtheta; if (theta>PI) { dtheta = thetaj + 2*PI - theta; } else { dtheta = theta - thetaj; } // dealing with rounding off errors if (dtheta > -0.000001 && dtheta < 0.000001) { rk = 0.0f; } else { rk = sqrtf(powf(r,2) + powf(pk,2) - 2*r*pk*cosf(dtheta)); } // rk^2 = |x-xk|^2 = r^2 + pk^2 - 2*r*pk*cos(theta-thetak) where r=|x|, pk=|xk| sq = sqrtf(powf(rk,2)+powf(e,2)); double h = (1.0f)/(2.0f*PI) * (powf(rk,2)+2.0f*powf(e,2)+e*sq)/((sq+e)*powf(sq,1.5f)); pp = (f.x*(x[i][j]-x[ii][jj]) + f.y*(y[i][j]-y[ii][jj])) * h; p += pp; } } return p; } // Compute velocity at point ij due to all other points in the structured grid vector velocity(int i, int j, double x[N][N], double y[N][N]) { vector v; vector f; v.x = 0.0f ; v.y = 0.0f; f.x = 0.0f; f.y = 0.0f; double pvx = 0.0f; double pvy = 0.0f; // partial component velocities double rk = 0.0f; double sq = 0.0f; for (int jj=0; jj<N; jj++) { for (int ii=0; ii<N; ii++) { // loop over all nodes in the grid f.x = eforce(ii, jj, x, y).x; f.y = eforce(ii, jj, x, y).y; double r = sqrt(powf(x[i][j],2) + powf(y[i][j],2)); double pk = sqrt(powf(x[ii][jj],2) + powf(y[ii][jj],2)); double theta = atan2f(y[i][j], x[i][j]); double thetaj = atan2(y[ii][jj], x[ii][jj]); double dtheta; if (theta>PI) { dtheta = thetaj + 2*PI - theta; } else { dtheta = theta - thetaj; } // dealing with rounding off errors if (dtheta > -0.000001 && dtheta < 0.000001) { rk = 0.0f; } else { rk = sqrtf(powf(r,2) + powf(pk,2) - 2*r*pk*cosf(dtheta)); } // rk^2 = |x-xk|^2 = r^2 + pk^2 - 2*r*pk*cos(theta-thetak) where r=|x|, pk=|xk| sq = sqrtf(powf(rk,2)+powf(e,2)); pvx = 0.0f; pvy = 0.0f; double p1 = (1.0f/(4.0f*visc*PI)) * (logf(sq+e)-(e*(sq+2*e))/(sq*(sq+e))); double p2 = (1.0f/(4.0f*visc*PI)) * (sq+2*e)/(sq*powf(sq+e,2)); pvx = -1.0f*p1*f.x + p2*(powf(x[i][j]-x[ii][jj],2)*f.x + (x[i][j]-x[ii][jj])*(y[i][j]-y[ii][jj])*f.y); pvy = -1.0f*p1*f.y + p2*((x[i][j]-x[ii][jj])*(y[i][j]-y[ii][jj])*f.x + powf(y[i][j]-y[ii][jj],2)*f.y); v.x += pvx; v.y += pvy; } } return v; } // Compute polygonal area double area(double x[N][N], double y[N][N]) { double A = 0.0f; int k1; int k2; // k1 = k; k2 = k+1 double x_ext[4*N-4]; double y_ext[4*N-4]; // exterior points /* Check for shear that we obtain a perfectly rotate uniformly discretized grid // check horizontal sides for(int j=0; j<N; j++) { for(int i=0; i<N-1; i++) { double x_current = x[i][j]; double x_next = x[i+1][j]; double y_current = y[i][j]; double y_next = y[i+1][j]; double horiz_side = sqrtf(powf(x_current-x_next,2) + powf(y_current-y_next,2)); printf("h(%d, %d) = %f\n", i, j, horiz_side); } } // check vertical sides for(int i=0; i<N; i++) { for(int j=0; j<N-1; j++) { double x_current = x[i][j]; double x_next = x[i][j+1]; double y_current = y[i][j]; double y_next = y[i][j+1]; double vert_side = fabs(y_next - y_current); printf("v(%d, %d) = %f\n", i, j, vert_side); } } */ // rearrange points in vector that contain exterior points for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { if(j==0) { x_ext[i] = x[i][j]; y_ext[i] = y[i][j]; } // bottom else if((i==(N-1)) && (j!=0)) { x_ext[j+i] = x[i][j]; y_ext[j+i] = y[i][j]; } // right else if((j==(N-1)) && (i!=(N-1))) { x_ext[3*j-i] = x[i][j]; y_ext[3*j-i] = y[i][j]; } // bottom else if((i==0) && (j!=0) && (j!=(N-1))) { x_ext[4*(N-1)-j] = x[i][j]; y_ext[4*(N-1)-j] = y[i][j]; } // left } } for(int k=0; k<(4*N-4); k++) { k1 = k; if(k1 == (4*N-5)) { k2 = 0; } else k2 = k+1; A += 0.5f * (x_ext[k1]*y_ext[k2]-x_ext[k2]*y_ext[k1]); } return A; } // Progression void progress(double x[N][N], double y[N][N]) { double x_i[N][N]; double y_i[N][N]; double u[N][N]; double v[N][N]; vector vel; vector ef; double p; double vmax = 0.0f, fmax = 0.0f, vmin = 0.0f, fmin = 0.0f, vmean = 0.0f, fmean = 0.0f; double vtime = 0.0f, ftime = 0.0f; for(int t=0; t<stop; t++) { for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { p = pressure(i, j, x, y); //if (t == stop-1) { printf("%.6f %.6f %.6f\n", x[i][j], y[i][j], p); } clock_t vbegin = clock(); vel = velocity(i, j, x, y); clock_t vend = clock(); clock_t fbegin = clock(); ef = eforce(i, j, x, y); clock_t fend = clock(); u[i][j] = vel.x + ef.x/drag; v[i][j] = vel.y + ef.y/drag; // timings double partv = diffclock(vend, vbegin); double partf = diffclock(fend, fbegin); if (vmax < partv) { vmax = partv; }; if (vmin > partv) { vmin = partv; }; if (fmax < partf) { fmax = partf; }; if (fmin < partv) { fmin = partf; }; vtime = vtime + partv; ftime = ftime + partf; vmean = vmean + (partv/(stop*N*N)); fmean = fmean + (partf/(stop*N*N)); } } for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { x_i[i][j] = x[i][j]; y_i[i][j] = y[i][j]; // saving initial configuration for initial area calculation x[i][j] = x[i][j] + tstep*u[i][j]; y[i][j] = y[i][j] + tstep*v[i][j]; } } // display final stage only /* glColor3f(0.0f, 0.0f, 1.0f); // blue glBegin(GL_POINTS); for (int j=0; j<N; j++) { for (int i=0; i<N; i++) { glVertex2f(x[i][j], y[i][j]); } } glEnd(); glFlush(); //printf("Done with first time step"); */ } // print out times printf("Per element forcing computation time (s): max = %.10f, min = %.10f, mean = %.10f\n", fmax, fmin, fmean); printf("Per element velocity computation time (s): max = %.10f, min = %.10f, mean = %.10f\n", vmax, vmin, vmean); printf("Total focing computation time (s): %.10f\n", ftime); printf("Total velocity computation time (s): %.10f\n", vtime); // display final stage only ///* glColor3f(0.0f, 0.0f, 1.0f); // blue glBegin(GL_POINTS); for (int j=0; j<N; j++) { for (int i=0; i<N; i++) { glVertex2f(x[i][j], y[i][j]); } } glEnd(); glFlush(); //*/ // compute final area printf("Starting area: %.16f, Final area: %.16f\n", fabs(area(x_i,y_i)), fabs(area(x,y)) ); } // Draw starting configuration void startCurve() { double xf[N][N]; double yf[N][N]; glColor3f(1.0f, 1.0f, 1.0f); // white glBegin(GL_POINTS); ///* // stretch uniformly in each direction for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { double dx = ri/(N-1); double dy = ri/(N-1); xf[i][j] = -ri/2 + dx*i; yf[i][j] = ri/2 - dy*j; glVertex2f(xf[i][j], yf[i][j]); } } //*/ /* // stretch in y-direction only for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { double dx = r0/(N-1); double dy = ri/(N-1); xf[i][j] = -r0/2 + dx*i; yf[i][j] = ri/2 - dy*j; glVertex2f(xf[i][j], yf[i][j]); } } */ /* // shear in both directions double lambda = 0.5f; // shear element for(int j=0; j<N; j++) { for(int i=0; i<N; i++) { double dx = r0/(N-1); double dy = r0/(N-1); yf[i][j] = r0/2 - dy*j; xf[i][j] = -r0/2 + dx*i + lambda*yf[i][j]; glVertex2f(xf[i][j], yf[i][j]); } } */ glEnd(); glFlush(); progress(xf, yf); } // Draw contour void markers() { glColor3f(1.0f, 1.0f, 1.0f); // white glBegin(GL_LINES); glVertex2f(-0.8f, -0.8f); glVertex2f(-0.8f, 0.8f); glVertex2f(-0.8f, 0.8f); glVertex2f(0.8f, 0.8f); glVertex2f(0.8f, 0.8f); glVertex2f(0.8f, -0.8f); glVertex2f(0.8f, -0.8f); glVertex2f(-0.8f, -0.8f); glEnd(); glFlush(); } // This function is passed to the glutKeyboardFunc and is called whenever the user hits a key. void keyboard(unsigned char key, int x, int y) { if (key == 27) { // ESC (exit) exit(1); } glutPostRedisplay(); } // This function is passed to glutDisplayFunc in order to display OpenGL contents on the window void display(void) { clock_t begin = clock(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); markers(); startCurve(); clock_t end = clock(); printf("Total computation time (s): %.10f\n", double(diffclock(end,begin)) ); glutSwapBuffers(); } // Main int main(int argc, char **argv) { // GLUT Initialiation glutInit(&argc, argv); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(window_x, window_y); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutCreateWindow("Immersed Structured Grid using Stokeslets"); init(); // Callback functions glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; }
[ "anamaria1@Calinas-MacBook-Pro.local" ]
anamaria1@Calinas-MacBook-Pro.local
d39dcf464942df42f001b81e030a9c3cfb95bb90
edf429b7d74a8fa2ea112fe4a9ac8a0e17559acb
/main.cpp
b60dbb963110ff89e6eaadfabe7c46272ce77b04
[]
no_license
buevichd/otus5
9629015b6a4769c9d21b509eab19e1188efd8d3c
e2d5e31d75cb3ee8b47ff5e2f3cc56dcb9b0f60c
refs/heads/main
2023-06-07T01:24:14.067768
2021-07-05T20:36:26
2021-07-05T20:36:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
cpp
#include <iostream> #include "matrix.h" #include <cassert> template <class T, T DefaultValue> void PrintMatrixFragment( const Matrix<T, DefaultValue>& matrix, size_t i_begin, size_t i_end, size_t j_begin, size_t j_end) { assert(i_begin < i_end && j_begin < j_end); for (size_t i = i_begin; i < i_end; ++i) { for (size_t j = j_begin; j < j_end; ++j) { std::cout << ((j != j_begin) ? " " : "") << matrix[i][j]; } std::cout << '\n'; } } template <class T, T DefaultValue> void PrintAllFilledCells(const Matrix<T, DefaultValue>& matrix) { for (const auto& [i, j, value] : matrix) { std::cout << '(' << i << ',' << j << "): " << value << '\n'; } } int main() { Matrix<int, 0> matrix; for (size_t i = 0; i < 10; ++i) { matrix[i][i] = i; matrix[i][9 - i] = 9 - i; } std::cout << "Matrix fragment:\n"; PrintMatrixFragment(matrix, 1, 9, 1, 9); std::cout << "\nMatrix size: " << matrix.size() << '\n'; std::cout << "All filled cells:\n"; PrintAllFilledCells(matrix); return 0; }
[ "buevichd@yandex-team.ru" ]
buevichd@yandex-team.ru
5b69b9234e4421dbcbef949dfb992e5614972aaa
a89b7910eca8b6553821d5040702b88538371803
/CSAR_Feb2017/rocpack-0.1.5/src/polyhedron.h
16a8ca2cd1aa3c7dac463e1a828f07ba7c51d2aa
[]
no_license
btbojko/PropSurfCoupling
0b303900c50b9f0ab461b9f2c4bab014e0070cf6
79efc5af4266baa9a3ee852c593dcb831f9611df
refs/heads/master
2021-01-22T02:14:40.825856
2017-05-24T23:47:58
2017-05-24T23:47:58
92,344,770
0
0
null
null
null
null
UTF-8
C++
false
false
1,358
h
#ifndef _POLYHEDRON_H #define _POLYHEDRON_H #include <vector> #include <algorithm> #include <cstdio> #include <cstring> #include "point.h" #include "matrix.h" #include "convex.h" class Polyhedron : public Convex { public: Polyhedron(const char *name, std::vector<Point> vertices, std::vector<std::vector<int> > faces) : vertex(vertices), face(faces) { m_name = strdup(name); compute_mass_properties(); } ~Polyhedron() { free(m_name); vertex.clear(); face.clear(); } ShapeType type() const { return CONVEX; } const char* name() const { return m_name; } float bounding_radius() const { return radius; } Point support(const Vector& v) const { int c = 0; float h = v * vertex[0]; for (unsigned int i = 1; i < vertex.size(); i++) { float d = v * vertex[i]; if (d > h) { h = d; c = i; } } return vertex[c]; } Matrix inertia() const { return m_inertia; } Matrix inverse_inertia() const { return m_inv_inertia; } float volume() const { return m_volume; } void write_povray_object(FILE* output) const; #ifdef HAVE_OPENGL void draw() const; #endif private: float radius; float m_volume; std::vector<Point> vertex; std::vector<Vector> normal; std::vector<std::vector<int> > face; Matrix m_inertia, m_inv_inertia; char *m_name; void compute_mass_properties(); }; #endif
[ "bbojko@first-rule.wd.navair-rdte.navy.mil" ]
bbojko@first-rule.wd.navair-rdte.navy.mil
01ddbecd55d4cbd65ffe22eb8df71b139522d791
dae2b1d2b2e0f30e5fa5551bc6ca73333fbde8e4
/cobotsys_tutorials/examples/Qt.Test/tool/testTreeView/QDataItemTree.cpp
24c8631fd6cdd20c9de5ed4e1e846092ad9cc9c0
[]
no_license
COBOTOS/CobotSys
360301fa644e238191ecfe43e74b93d1a3595559
22b2d9a0783a3605a28bc7bda420a7cb3170789f
refs/heads/master
2020-09-23T11:29:37.648116
2019-12-19T08:58:01
2019-12-19T08:58:01
225,490,747
6
1
null
null
null
null
UTF-8
C++
false
false
4,103
cpp
#include "QDataItemTree.h" #include <QStringList> QDataItemTree::QDataItemTree(const QString &data, QObject *parent): QAbstractItemModel(parent) { QList<QVariant> rootData; rootData << data; rootItem = new QDataItem(rootData); } QDataItemTree::~QDataItemTree() { delete rootItem; } QVariant QDataItemTree::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); QDataItem *item = static_cast<QDataItem*>(index.internalPointer()); return item->data(index.column()); } Qt::ItemFlags QDataItemTree::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; return QAbstractItemModel::flags(index); } QVariant QDataItemTree::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return rootItem->data(section); return QVariant(); } QModelIndex QDataItemTree::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); QDataItem *parentItem; if (!parent.isValid()) parentItem = rootItem; else parentItem = static_cast<QDataItem*>(parent.internalPointer()); QDataItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QModelIndex QDataItemTree::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); QDataItem *childItem = static_cast<QDataItem*>(index.internalPointer()); QDataItem *parentItem = childItem->parentItem(); if (parentItem == rootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem); } int QDataItemTree::rowCount(const QModelIndex &parent) const { QDataItem *parentItem; if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = rootItem; else parentItem = static_cast<QDataItem*>(parent.internalPointer()); return parentItem->childCount(); } int QDataItemTree::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return static_cast<QDataItem*>(parent.internalPointer())->columnCount(); else return rootItem->columnCount(); } QDataItem* QDataItemTree::addBatch(int number) { QString name = "Batch_"+QString::number(number); QList<QVariant> d; d<<name; QDataItem* batch = new QDataItem(d,rootItem); beginInsertRows(indexFromItem(rootItem), rootItem->childCount(), rootItem->childCount()); rootItem->appendChild(batch); endInsertRows(); return batch; } QDataItem* QDataItemTree::addBatchElement(int number, QDataItem* parent) { QString name = "Element_"+QString::number(number); QList<QVariant> d; d<<name; QDataItem* element = new QDataItem(d,parent); beginInsertRows(indexFromItem(parent), parent->childCount(), parent->childCount()); parent->appendChild(element); endInsertRows(); return element; } QDataItem* QDataItemTree::addBatchElementChild(int number, QDataItem* parent) { QString name = "Child_"+QString::number(number); QList<QVariant> d; d<<name; QDataItem* element_child = new QDataItem(d,parent); beginInsertRows(indexFromItem(parent), parent->childCount(), parent->childCount()); parent->appendChild(element_child); endInsertRows(); return element_child; } QModelIndex QDataItemTree::indexFromItem(QDataItem *item){ if(item == rootItem || item == NULL) return QModelIndex(); QDataItem *parent = item->parentItem(); QList<QDataItem *> parents; while (parent && parent!=rootItem) { parents<<parent; parent = parent->parentItem(); } QModelIndex ix; parent = rootItem; for(int i=0; i < parents.count(); i++){ ix = index(parents[i]->row(), 0, ix); } ix = index(ix.row(), 0, ix); return ix; }
[ "1246054700@qq.com" ]
1246054700@qq.com
c3b49932361cdad2bedef4d9b8527d840af13d88
99fc190b97baf08bbcdf6541708b331e70b0f8b7
/utilities.cpp
3ba4f3764179079b0e2d55f0b1ead6d5d0a3c18e
[]
no_license
ntavendale/ssfi
8d4ad8927504d234ecb473cce77f3d1e3545f488
dfcb637c1613b837dae6d0df1cb55df18d72775f
refs/heads/master
2020-06-28T18:20:12.753043
2019-08-05T00:00:04
2019-08-05T00:00:04
200,305,891
0
0
null
null
null
null
UTF-8
C++
false
false
1,830
cpp
#include "utilities.h" bool Utilities::directoryExists(char* directroyPath) { DIR* dir = opendir(directroyPath); if (dir) { /* Directory exists. */ closedir(dir); return true; } else if (ENOENT == errno) { return false; } //got some other error other than the NOWENT Error. //This means dir is there but there is some issue with it (probably permissions). return true; } bool Utilities::directoryAccessible(char* directroyPath) { DIR* dir = opendir(directroyPath); if (dir) { /* Directory exists. */ closedir(dir); return true; } //If it's not there, it's not accessable. return false; } std::vector<std::string> Utilities::readDirectory(char* directroyPath) { std::vector<std::string> fileList; if (!(directroyPath)) { return fileList; } std::string dir(directroyPath); if ( (!filesys::exists(dir)) || (!filesys::is_directory(dir)) ) { return fileList; } // Create a Recursive Directory Iterator object and points to the starting of directory filesys::recursive_directory_iterator iter(dir); // Create a Recursive Directory Iterator object pointing to end. filesys::recursive_directory_iterator end; while (iter != end) { if ((!filesys::is_directory(iter->path())) && (".txt" == iter->path().extension().string() )) { // it's not a directory and has .txt extension fileList.push_back(iter->path().string()); } boost::system::error_code ec; // Increment the iterator to point to next entry in recursive iteration iter.increment(ec); if (ec) { std::cout << "Error While Accessing " << iter->path().string() << ": "<< ec.message(); } } return fileList; }
[ "nigel.tavendale@allthingssyslog.com" ]
nigel.tavendale@allthingssyslog.com
f06bbb0c7eec4a1a2d8c266d7b17d890bc49795b
f043ac0aa15a28e9c9af1ab9f0b9a0dec02057a8
/test/utest/checker/checker_test.cpp
c51e89966f472269eeb1032110cd24d48cbfdc0d
[ "Apache-2.0" ]
permissive
dendisuhubdy/HugeCTR
9fe1f1bedd13df6f64115c45a3282549c5c824c6
849be3fde24f91d2f0b389830a0d427617fd40b4
refs/heads/master
2022-12-29T08:44:09.244236
2020-10-05T12:10:38
2020-10-05T12:10:38
301,602,662
0
0
Apache-2.0
2020-10-06T03:24:53
2020-10-06T03:23:14
null
UTF-8
C++
false
false
2,166
cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "HugeCTR/include/data_readers/check_sum.hpp" #include "HugeCTR/include/common.hpp" #include "HugeCTR/include/data_readers/file_source.hpp" #include "gtest/gtest.h" using namespace HugeCTR; TEST(checker, CheckSum) { auto func = [](std::string file, std::string str) { int count = str.length(); char sum = 0; std::ofstream out_stream(file, std::ofstream::binary); for (int i = 0; i < count; i++) { sum += str[i]; } out_stream.write(reinterpret_cast<char*>(&count), sizeof(int)); out_stream.write(str.c_str(), count); out_stream.write(reinterpret_cast<char*>(&sum), sizeof(char)); out_stream.write(reinterpret_cast<char*>(&count), sizeof(int)); out_stream.write(str.c_str(), count); out_stream.write(reinterpret_cast<char*>(&sum), sizeof(char)); out_stream.close(); out_stream.open("file_list.txt", std::ofstream::out); out_stream << "1\n" << file; out_stream.close(); }; const int NUM_CHAR = 7; const char str[] = {"abcdefg"}; func("file1.txt", str); FileSource file_source(0, 1, "file_list.txt"); CheckSum check_sum(file_source); char tmp1[NUM_CHAR], tmp2[NUM_CHAR]; check_sum.next_source(); EXPECT_EQ(check_sum.read(tmp1, NUM_CHAR), Error_t::Success); // for(int i=0; i< NUM_CHAR; i++){ // std::cout << tmp1[i]; // } EXPECT_EQ(strncmp(tmp1, str, NUM_CHAR), 0); EXPECT_EQ(check_sum.read(tmp2, NUM_CHAR), Error_t::Success); // for(int i=0; i< NUM_CHAR; i++){ // std::cout << tmp2[i]; // } EXPECT_EQ(strncmp(tmp1, str, NUM_CHAR), 0); }
[ "zehuanw@nvidia.com" ]
zehuanw@nvidia.com
5272ba2942450c526b09eed37c62f29b6e1461b5
d01dc974582ea930c76a4b12bbcde0af6ab28b63
/client/tripplanner_client_tripplanner.h
d4601559433ffc676b4e3001c82dc318753f472d
[]
no_license
LuoWDK/TripPlanner
69da87d2aae1409eb2ec5a608093a3b638e6930a
87f0771f3f71675f803d460939a401b9b9f57467
refs/heads/master
2020-03-07T03:48:45.931537
2018-03-29T06:39:08
2018-03-29T06:39:08
127,247,350
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
h
#ifndef TRIPPLANNER_CLIENT_TRIPPLANNER_H #define TRIPPLANNER_CLIENT_TRIPPLANNER_H #include <QDialog> #include <QDialogButtonBox> #include <QGroupBox> #include <QRadioButton> #include <QDateEdit> #include <QLabel> #include <QRadioButton> #include <QLabel> #include <QComboBox> #include <QTimeEdit> #include <QTableWidget> #include <QProgressBar> #include <QPushButton> #include <QButtonGroup> #include <QTcpSocket> #include <QAbstractButton> namespace Ui { class TripPlanner; } class TripPlanner : public QDialog { Q_OBJECT public: explicit TripPlanner(QWidget *parent = 0); ~TripPlanner(); private: void CloseConnection(); Ui::TripPlanner *ui; QDialogButtonBox *button_box_; QPushButton *search_button_; QPushButton *stop_button_; QPushButton *quit_button_; QButtonGroup *group_; QTcpSocket tcp_socket_; quint16 next_block_size_; private slots: void ConnectToServer(); void SendRequest(); void UpdateTableWidget(); void StopSearch(); void ConnectClosedByServer(); void Error(); }; #endif // TRIPPLANNER_CLIENT_TRIPPLANNER_H
[ "Maggieluo0120@gmail.com" ]
Maggieluo0120@gmail.com
e9e8b7a4f3da13169b32d4f826f8cfde4142e970
a7643e386a5f3675b8ea5a2dbd7c64401511ff17
/EndUserUpgradeTool/CIniFile.h
8f2617d52f2a42d85dc9d48dbce8246bee3996cf
[]
no_license
virqin/brew_code
fa2a7ab1a31a45fba7396b6d24e6c37940ca984b
c34e08e98d51f3e58cf6b20d70acab9c4322e4ca
refs/heads/master
2021-01-10T01:26:14.489462
2016-03-30T10:45:17
2016-03-30T10:45:17
43,925,742
1
0
null
null
null
null
GB18030
C++
false
false
1,924
h
/*================================================================== = 文件名:CIniFile类定义文件 = = 主要功能:可以读取.修改变量数值,可以设置新的组,新的变量 = = 修改日期:2002-12-28 = = 作者:阿皮 = = E_Mail:peijikui@sd365.com QQ:122281932 = = ====================================================================*/ #ifndef _CINIFILE_H_ #define _CINIFILE_H_ //用户接口说明:在成员函数SetVarStr和SetVarInt函数中,当iType等于零,则如果用户制定的参数在ini文件中不存在, //则就写入新的变量.当iType不等于零,则如果用户制定的参数在ini文件中不存在,就不写入新的变量,而是直接返回FALSE; #include <afxtempl.h> class CIniFile { public: CIniFile(); virtual ~CIniFile(); private: CIniFile(const CIniFile &); CIniFile & operator = (const CIniFile &); public: //创建函数 BOOL Create(const CString &strFileName); //得到变量整数型数值 BOOL GetVarInt(const CString &,const CString & ,int &); //得到变量字符串型数值 BOOL GetVarStr(const CString &,const CString & ,CString & ); //重新设置变量整数型数值 BOOL SetVarInt(const CString &,const CString & ,const int &,const int iType = 1); //重新设置变量字符串型数值 BOOL SetVarStr(const CString &,const CString &, const CString &,const int iType = 1); private: BOOL GetVar(const CString &,const CString &,CString &); BOOL SetVar(const CString &,const CString &,const CString &,const int iType = 1); int SearchLine(const CString &,const CString &); private: // vector <CString> FileContainer; CArray <CString,CString> FileContainer; BOOL bFileExsit; CStdioFile stfFile; CString strInIFileName; }; #endif
[ "yaohongtao@shanlitech.com" ]
yaohongtao@shanlitech.com
1e163a1b4ee99882755ca5fce12e0bf592d5fa72
bb47dd255fcb8e504b6277b99d2809314be7292d
/Programming Windows, 6th Edition/CPlusPlus/Chapter01/StrippedDownHello/StrippedDownHello/App.h
4dd8b636ab5017f14668f5a78fcfe1b8f4b859ae
[]
no_license
harshalbetsol/book-examples
154869b228220803bf50cad00fca3024a84195af
4eff9c402a6e2f0ab17dc4a0d345b45cf9c6d25f
refs/heads/master
2021-09-08T02:35:16.590826
2018-03-05T04:59:51
2018-03-06T05:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
268
h
#pragma once #include "pch.h" namespace StrippedDownHello { ref class App sealed : public Windows::UI::Xaml::Application { public: virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override; }; }
[ "sungmann.cho@gmail.com" ]
sungmann.cho@gmail.com
83d8159634deb38c711bf6567955d518fc0b88f6
a3a31574f023b263e999af40501791027032d7ac
/src/server/rmlui/source/Core/StyleSheetNodeSelectorNthOfType.cpp
cf6577f87221e784f1384434d694317ddb993157
[ "BSD-3-Clause" ]
permissive
ScaredyCat/NymphCast
08131679f557153782c411fb90f2f3ee830ecdac
0df2e91fbf37ec1a852789c05da5fe9e169a8ade
refs/heads/master
2023-05-14T00:11:39.490071
2021-06-08T17:24:22
2021-06-08T17:24:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,402
cpp
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "StyleSheetNodeSelectorNthOfType.h" #include "../../include/RmlUi/Core/ElementText.h" namespace Rml { StyleSheetNodeSelectorNthOfType::StyleSheetNodeSelectorNthOfType() { } StyleSheetNodeSelectorNthOfType::~StyleSheetNodeSelectorNthOfType() { } // Returns true if the element index is (n * a) + b for a given integer value of n. bool StyleSheetNodeSelectorNthOfType::IsApplicable(const Element* element, int a, int b) { Element* parent = element->GetParentNode(); if (parent == nullptr) return false; // Start counting elements until we find this one. int element_index = 1; for (int i = 0; i < parent->GetNumChildren(); ++i) { Element* child = parent->GetChild(i); // If we've found our element, then break; the current index is our element's index. if (child == element) break; // Skip nodes that don't share our tag. if (child->GetTagName() != element->GetTagName() || child->GetDisplay() == Style::Display::None) continue; element_index++; } return IsNth(a, b, element_index); } } // namespace Rml
[ "maya@nyanko.ws" ]
maya@nyanko.ws
d361b5ff251cf35d63a652025c958135049a487c
39adfee7b03a59c40f0b2cca7a3b5d2381936207
/codeforces/100761/C.cpp
939bf208b10bd95b10c284c504a70d0561f6a28f
[]
no_license
ngthanhtrung23/CompetitiveProgramming
c4dee269c320c972482d5f56d3808a43356821ca
642346c18569df76024bfb0678142e513d48d514
refs/heads/master
2023-07-06T05:46:25.038205
2023-06-24T14:18:48
2023-06-24T14:18:48
179,512,787
78
22
null
null
null
null
UTF-8
C++
false
false
12,532
cpp
#include <bits/stdc++.h> using namespace std; const int base = 1000000000; const int base_digits = 9; struct BigInt { vector<int> a; int sign; BigInt() : sign(1) { } BigInt(long long v) { *this = v; } BigInt(const string &s) { read(s); } void operator=(const BigInt &v) { sign = v.sign; a = v.a; } void operator=(long long v) { sign = 1; if (v < 0) sign = -1, v = -v; a.clear(); for (; v > 0; v = v / base) a.push_back(v % base); } BigInt operator+(const BigInt &v) const { if (sign == v.sign) { BigInt res = v; for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) { if (i == (int) res.a.size()) res.a.push_back(0); res.a[i] += carry + (i < (int) a.size() ? a[i] : 0); carry = res.a[i] >= base; if (carry) res.a[i] -= base; } return res; } return *this - (-v); } BigInt operator-(const BigInt &v) const { if (sign == v.sign) { if (abs() >= v.abs()) { BigInt res = *this; for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) { res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0); carry = res.a[i] < 0; if (carry) res.a[i] += base; } res.trim(); return res; } return -(v - *this); } return *this + (-v); } void operator*=(int v) { if (v < 0) sign = -sign, v = -v; for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) { if (i == (int) a.size()) a.push_back(0); long long cur = a[i] * (long long) v + carry; carry = (int) (cur / base); a[i] = (int) (cur % base); //asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base)); } trim(); } BigInt operator*(int v) const { BigInt res = *this; res *= v; return res; } BigInt pow(int y) { if (!y) return BigInt(1); BigInt res = pow(y / 2); res = res * res; if (y % 2) res = res * (*this); return res; } friend pair<BigInt, BigInt> divmod(const BigInt &a1, const BigInt &b1) { int norm = base / (b1.a.back() + 1); BigInt a = a1.abs() * norm; BigInt b = b1.abs() * norm; BigInt q, r; q.a.resize(a.a.size()); for (int i = a.a.size() - 1; i >= 0; i--) { r *= base; r += a.a[i]; int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()]; int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1]; int d = ((long long) base * s1 + s2) / b.a.back(); r -= b * d; while (r < 0) r += b, --d; q.a[i] = d; } q.sign = a1.sign * b1.sign; r.sign = a1.sign; q.trim(); r.trim(); return make_pair(q, r / norm); } friend BigInt sqrt(const BigInt &a1) { BigInt a = a1; while (a.a.empty() || a.a.size() % 2 == 1) a.a.push_back(0); int n = a.a.size(); int firstDigit = (int) sqrt((double) a.a[n - 1] * base + a.a[n - 2]); int norm = base / (firstDigit + 1); a *= norm; a *= norm; while (a.a.empty() || a.a.size() % 2 == 1) a.a.push_back(0); BigInt r = (long long) a.a[n - 1] * base + a.a[n - 2]; firstDigit = (int) sqrt((double) a.a[n - 1] * base + a.a[n - 2]); int q = firstDigit; BigInt res; for(int j = n / 2 - 1; j >= 0; j--) { for(; ; --q) { BigInt r1 = (r - (res * 2 * base + q) * q) * base * base + (j > 0 ? (long long) a.a[2 * j - 1] * base + a.a[2 * j - 2] : 0); if (r1 >= 0) { r = r1; break; } } res *= base; res += q; if (j > 0) { int d1 = res.a.size() + 2 < r.a.size() ? r.a[res.a.size() + 2] : 0; int d2 = res.a.size() + 1 < r.a.size() ? r.a[res.a.size() + 1] : 0; int d3 = res.a.size() < r.a.size() ? r.a[res.a.size()] : 0; q = ((long long) d1 * base * base + (long long) d2 * base + d3) / (firstDigit * 2); } } res.trim(); return res / norm; } BigInt operator/(const BigInt &v) const { return divmod(*this, v).first; } BigInt operator%(const BigInt &v) const { return divmod(*this, v).second; } void operator/=(int v) { if (v < 0) sign = -sign, v = -v; for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) { long long cur = a[i] + rem * (long long) base; a[i] = (int) (cur / v); rem = (int) (cur % v); } trim(); } BigInt operator/(int v) const { BigInt res = *this; res /= v; return res; } int operator%(int v) const { if (v < 0) v = -v; int m = 0; for (int i = a.size() - 1; i >= 0; --i) m = (a[i] + m * (long long) base) % v; return m * sign; } void operator+=(const BigInt &v) { *this = *this + v; } void operator-=(const BigInt &v) { *this = *this - v; } void operator*=(const BigInt &v) { *this = *this * v; } void operator/=(const BigInt &v) { *this = *this / v; } bool operator<(const BigInt &v) const { if (sign != v.sign) return sign < v.sign; if (a.size() != v.a.size()) return a.size() * sign < v.a.size() * v.sign; for (int i = a.size() - 1; i >= 0; i--) if (a[i] != v.a[i]) return a[i] * sign < v.a[i] * sign; return false; } bool operator>(const BigInt &v) const { return v < *this; } bool operator<=(const BigInt &v) const { return !(v < *this); } bool operator>=(const BigInt &v) const { return !(*this < v); } bool operator==(const BigInt &v) const { return !(*this < v) && !(v < *this); } bool operator!=(const BigInt &v) const { return *this < v || v < *this; } void trim() { while (!a.empty() && !a.back()) a.pop_back(); if (a.empty()) sign = 1; } bool isZero() const { return a.empty() || (a.size() == 1 && !a[0]); } BigInt operator-() const { BigInt res = *this; res.sign = -sign; return res; } BigInt abs() const { BigInt res = *this; res.sign *= res.sign; return res; } long long longValue() const { long long res = 0; for (int i = a.size() - 1; i >= 0; i--) res = res * base + a[i]; return res * sign; } friend BigInt gcd(const BigInt &a, const BigInt &b) { return b.isZero() ? a : gcd(b, a % b); } friend BigInt lcm(const BigInt &a, const BigInt &b) { return a / gcd(a, b) * b; } void read(const string &s) { sign = 1; a.clear(); int pos = 0; while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { if (s[pos] == '-') sign = -sign; ++pos; } for (int i = s.size() - 1; i >= pos; i -= base_digits) { int x = 0; for (int j = max(pos, i - base_digits + 1); j <= i; j++) x = x * 10 + s[j] - '0'; a.push_back(x); } trim(); } friend istream& operator>>(istream &stream, BigInt &v) { string s; stream >> s; v.read(s); return stream; } friend ostream& operator<<(ostream &stream, const BigInt &v) { if (v.sign == -1 && !v.isZero()) stream << '-'; stream << (v.a.empty() ? 0 : v.a.back()); for (int i = (int) v.a.size() - 2; i >= 0; --i) stream << setw(base_digits) << setfill('0') << v.a[i]; return stream; } static vector<int> convert_base(const vector<int> &a, int old_digits, int new_digits) { vector<long long> p(max(old_digits, new_digits) + 1); p[0] = 1; for (int i = 1; i < (int) p.size(); i++) p[i] = p[i - 1] * 10; vector<int> res; long long cur = 0; int cur_digits = 0; for (int i = 0; i < (int) a.size(); i++) { cur += a[i] * p[cur_digits]; cur_digits += old_digits; while (cur_digits >= new_digits) { res.push_back(int(cur % p[new_digits])); cur /= p[new_digits]; cur_digits -= new_digits; } } res.push_back((int) cur); while (!res.empty() && !res.back()) res.pop_back(); return res; } typedef vector<long long> vll; static vll karatsubaMultiply(const vll &a, const vll &b) { int n = a.size(); vll res(n + n); if (n <= 32) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) res[i + j] += a[i] * b[j]; return res; } int k = n >> 1; vll a1(a.begin(), a.begin() + k); vll a2(a.begin() + k, a.end()); vll b1(b.begin(), b.begin() + k); vll b2(b.begin() + k, b.end()); vll a1b1 = karatsubaMultiply(a1, b1); vll a2b2 = karatsubaMultiply(a2, b2); for (int i = 0; i < k; i++) a2[i] += a1[i]; for (int i = 0; i < k; i++) b2[i] += b1[i]; vll r = karatsubaMultiply(a2, b2); for (int i = 0; i < (int) a1b1.size(); i++) r[i] -= a1b1[i]; for (int i = 0; i < (int) a2b2.size(); i++) r[i] -= a2b2[i]; for (int i = 0; i < (int) r.size(); i++) res[i + k] += r[i]; for (int i = 0; i < (int) a1b1.size(); i++) res[i] += a1b1[i]; for (int i = 0; i < (int) a2b2.size(); i++) res[i + n] += a2b2[i]; return res; } BigInt operator*(const BigInt &v) const { vector<int> a6 = convert_base(this->a, base_digits, 6); vector<int> b6 = convert_base(v.a, base_digits, 6); vll a(a6.begin(), a6.end()); vll b(b6.begin(), b6.end()); while (a.size() < b.size()) a.push_back(0); while (b.size() < a.size()) b.push_back(0); while (a.size() & (a.size() - 1)) a.push_back(0), b.push_back(0); vll c = karatsubaMultiply(a, b); BigInt res; res.sign = sign * v.sign; for (int i = 0, carry = 0; i < (int) c.size(); i++) { long long cur = c[i] + carry; res.a.push_back((int) (cur % 1000000)); carry = (int) (cur / 1000000); } res.a = convert_base(res.a, 6, base_digits); res.trim(); return res; } }; BigInt ways[1111]; int n, k, flag[3333], bad[22][3], cnt[1111]; int main() { int n, k; cin >> n >> k; for (int i = 0; i < k; i++) for (int j = 0; j < 3; j++) cin >> bad[i][j]; for (int mask = 0; mask < 1 << k; mask++) { int ok = 1, bit = __builtin_popcount(mask); for (int i = 0; i < k; i++) if (mask >> i & 1) for (int j = 0; j < 3; j++) if (flag[bad[i][j]] == mask) ok = 0; else flag[bad[i][j]] = mask; if (ok) { if (bit % 2) cnt[n - bit]--; else cnt[n - bit]++; } } BigInt ans(0), ways(1); for (int i = 0; i <= n; i++) { ways *= (i * 3 - 1) * (i * 3 - 2) / 2; if (cnt[i]) ans += ways * cnt[i]; } cout << ans << endl; }
[ "ngthanhtrung23@gmail.com" ]
ngthanhtrung23@gmail.com
be97a25450536e56e08e2ed266f4aa58f7f965b9
31b9b808715f764a509769bc3b0a5c535c101353
/april-04-02.cpp
8078ed6ccd4f6a1e7171334d7776b93264ce8b94
[]
no_license
Reazul137/113th-prblm
e6bfaa420f11bcf4bb4412c398f0ffb3e45a8347
6488dea1b4c645f5a94e39f458b68fe8ef7b2421
refs/heads/master
2020-03-08T09:12:30.650074
2018-04-04T09:41:08
2018-04-04T09:41:08
128,041,273
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
#include <iostream> using namespace std; int main() { int num = 57; cout << "\n\n Display the operation of pre and post increment and decrement :\n"; cout << "--------------------------------------------------------------------\n"; cout <<" The number is : " << num << endl; num++; // increase by 1 (post-increment) cout <<" After post increment by 1 the number is : " << num << endl; ++num; // increase by 1 (pre-increment) cout <<" After pre increment by 1 the number is : " << num << endl; num = num + 1; // num is now increased by 1. cout <<" After increasing by 1 the number is : " << num << endl; // 79 num--; // decrease by 1 (post-decrement) cout <<" After post decrement by 1 the number is : " << num << endl; --num; // decrease by 1 (pre-decrement) cout <<" After pre decrement by 1 the number is : " << num << endl; num = num - 1; // num is now decreased by 1. cout <<" After decreasing by 1 the number is : " << num << endl; cout << endl; return 0; }
[ "reazulislam137@gmail.com" ]
reazulislam137@gmail.com
1fc547eef4ddc5b043bc4172db9429c0d5f5f311
cbbd486d6bbc1b7c2ace1249412f5240db6efbe0
/1149.cpp
00041eb6c21d8784fc8d2b53f91403a5db586dc1
[]
no_license
Cafemug/baekjoon-cpp
f383708e17affbaf3be3ed797c8dac14771e1cc8
cb5452f8d08d071b2f3535009b545555c6a92190
refs/heads/master
2021-10-21T02:18:44.017457
2021-10-18T12:10:50
2021-10-18T12:10:50
116,027,319
3
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
#include <iostream> using namespace std; const int MAX=100002; long long red[MAX]; long long green[MAX]; long long blue[MAX]; long long d[MAX][3]; int main(){ long long n; cin>>n; for(int i=1;i<=n;i++){ cin>>red[i]; cin>>green[i]; cin>>blue[i]; } d[1][0]=red[1]; d[1][1]=green[1]; d[1][2]=blue[1]; for(int i=2;i<=n;i++){ d[i][0]=min((red[i]+d[i-1][1]),(red[i]+d[i-1][2])); d[i][1]=min((green[i]+d[i-1][0]),(green[i]+d[i-1][2])); d[i][2]=min((blue[i]+d[i-1][1]),(blue[i]+d[i-1][0])); } long long res=min(d[n][0],min(d[n][1],d[n][2])); cout<<res; }
[ "hyanghope@naver.com" ]
hyanghope@naver.com
4a3778f1f9832c6d19db8bc4c38a8db4c22f415f
162b0ac013e65d9bc73417571f88a6a861ebc8e6
/lins/include/parameters.h
755cb08f29f4bf4e67bbc0aabd2bae71a5f20b11
[]
no_license
zackLiuzz/my_LINS
8b5ffb569577d650e949acf7fd2f7825c857277c
5cdabb24c72d175d5cc3181e44851dc6468f945d
refs/heads/master
2023-08-26T02:48:04.838256
2021-10-14T10:06:03
2021-10-14T10:06:03
417,079,070
0
0
null
null
null
null
UTF-8
C++
false
false
5,176
h
// This file is part of LINS. // // Copyright (C) 2020 Chao Qin <cscharlesqin@gmail.com>, // Robotics and Multiperception Lab (RAM-LAB <https://ram-lab.com>), // The Hong Kong University of Science and Technology // // 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 the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. #ifndef INCLUDE_PARAMETERS_H_ #define INCLUDE_PARAMETERS_H_ #include <math.h> #include <nav_msgs/Odometry.h> #include <pcl/common/common.h> #include <pcl/filters/filter.h> #include <pcl/filters/voxel_grid.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/range_image/range_image.h> #include <pcl/registration/icp.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <ros/ros.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/NavSatFix.h> #include <sensor_msgs/PointCloud2.h> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> #include <tic_toc.h> #include <eigen3/Eigen/Dense> #include <fstream> #include <iostream> #include <mutex> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <queue> #include <thread> #include "cloud_msgs/cloud_info.h" typedef pcl::PointXYZI PointType; typedef Eigen::Vector3d V3D; typedef Eigen::Matrix3d M3D; typedef Eigen::VectorXd VXD; typedef Eigen::MatrixXd MXD; typedef Eigen::Quaterniond Q4D; namespace parameter { /*!@EARTH COEFFICIENTS */ const double G0 = 9.81; // gravity const double deg = M_PI / 180.0; // degree const double rad = 180.0 / M_PI; // radian const double dph = deg / 3600.0; // degree per hour const double dpsh = deg / sqrt(3600.0); // degree per square-root hour const double mg = G0 / 1000.0; // mili-gravity force const double ug = mg / 1000.0; // micro-gravity force const double mgpsHz = mg / sqrt(1.0); // mili-gravity force per second const double ugpsHz = ug / sqrt(1.0); // micro-gravity force per second const double Re = 6378137.0; ///< WGS84 Equatorial radius in meters const double Rp = 6356752.31425; const double Ef = 1.0 / 298.257223563; const double Wie = 7.2921151467e-5; const double Ee = 0.0818191908425; const double EeEe = Ee * Ee; /*!@SLAM COEFFICIENTS */ const bool loopClosureEnableFlag = true; const double mappingProcessInterval = 0.3; const float ang_res_x = 0.2; const float ang_res_y = 2.0; const float ang_bottom = 15.0 + 0.1; const int groundScanInd = 5; const int systemDelay = 0; const float sensorMountAngle = 0.0; const float segmentTheta = 1.0472; const int segmentValidPointNum = 5; const int segmentValidLineNum = 3; const float segmentAlphaX = ang_res_x / 180.0 * M_PI; const float segmentAlphaY = ang_res_y / 180.0 * M_PI; const int edgeFeatureNum = 2; const int surfFeatureNum = 4; const int sectionsTotal = 6; const float surroundingKeyframeSearchRadius = 50.0; const int surroundingKeyframeSearchNum = 50; const float historyKeyframeSearchRadius = 5.0; const int historyKeyframeSearchNum = 25; const float historyKeyframeFitnessScore = 0.3; const float globalMapVisualizationSearchRadius = 500.0; // !@ENABLE_CALIBRATION extern int CALIBARTE_IMU; extern int SHOW_CONFIGURATION; extern int AVERAGE_NUMS; // !@INITIAL_PARAMETERS extern double IMU_LIDAR_EXTRINSIC_ANGLE; extern double IMU_MISALIGN_ANGLE; // !@LIDAR_PARAMETERS extern int LINE_NUM; extern int SCAN_NUM; extern double SCAN_PERIOD; extern double EDGE_THRESHOLD; extern double SURF_THRESHOLD; extern double NEAREST_FEATURE_SEARCH_SQ_DIST; // !@TESTING extern int VERBOSE; extern int ICP_FREQ; extern int MAX_LIDAR_NUMS; extern int NUM_ITER; extern double LIDAR_SCALE; extern double LIDAR_STD; // !@SUB_TOPIC_NAME extern std::string IMU_TOPIC; extern std::string LIDAR_TOPIC; // !@PUB_TOPIC_NAME extern std::string LIDAR_ODOMETRY_TOPIC; extern std::string LIDAR_MAPPING_TOPIC; // !@KALMAN_FILTER extern double ACC_N; extern double ACC_W; extern double GYR_N; extern double GYR_W; extern V3D INIT_POS_STD; extern V3D INIT_VEL_STD; extern V3D INIT_ATT_STD; extern V3D INIT_ACC_STD; extern V3D INIT_GYR_STD; // !@INITIAL IMU BIASES extern V3D INIT_BA; extern V3D INIT_BW; // !@EXTRINSIC_PARAMETERS extern V3D INIT_TBL; extern Q4D INIT_RBL; void readParameters(ros::NodeHandle& n); void readV3D(cv::FileStorage* file, const std::string& name, V3D& vec_eigen); void readQ4D(cv::FileStorage* file, const std::string& name, Q4D& quat_eigen); enum StateOrder { O_R = 0, O_P = 3, }; } // namespace parameter #endif // INCLUDE_PARAMETERS_H_
[ "qinchaom4a1@163.com" ]
qinchaom4a1@163.com
fb842471c4b3361fbd59fc9233e8afaf2fbcf679
92a9f837503a591161330d39d061ce290c996f0e
/SiNDY-u/CountMapShp/other_src/Smp_db_obj_attr.cpp
10616e285c2cfe602659bd6088733cf1d7507cf5
[]
no_license
AntLJ/TestUploadFolder
53a7dae537071d2b1e3bab55e925c8782f3daa0f
31f9837abbd6968fc3a0be7610560370c4431217
refs/heads/master
2020-12-15T21:56:47.756829
2020-01-23T07:33:23
2020-01-23T07:33:23
235,260,509
1
1
null
null
null
null
SHIFT_JIS
C++
false
false
11,721
cpp
/* * Copyright (C) INCREMENT P CORP. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY INCREMENT P CORP., 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ #include "stdafx.h" #include "Smp_db_obj_attr.h" /** 構造体にSdeRowからデータをセットする @return bool */ bool Smp_db_obj_attr:: Attr_Set_AOBJ ( IFeaturePtr c_Feature ) ///< フェッチしてきたフィーチャ[IN] { LONG a_Col_Size = 0; IFieldsPtr a_Col_Defs; // カラムの定義 c_Feature->get_Fields ( &a_Col_Defs ); a_Col_Defs->get_FieldCount ( &a_Col_Size ); LONG i = 0; CComBSTR a_Col_Name; for( i = 0 ; i < a_Col_Size ; i++ ) { IFieldPtr a_Col_Def; CComVariant a_Value; a_Col_Defs->get_Field ( i, &a_Col_Def ); a_Col_Name.Empty(); esriFieldType a_Col_Type; // フィールドタイプ a_Col_Def->get_Type ( &a_Col_Type ); // カラムタイプ a_Col_Def->get_Name ( &a_Col_Name ); // カラム名称 c_Feature->get_Value( i, &a_Value ); // 属性値の取得 if(a_Col_Name == O_ID) { // オブジェクトID e_Obj_ID = a_Value.intVal; }else if( (a_Col_Name == DSC1_F) || (a_Col_Name == SC1DT_C) ){ // 表示スケール1(ベース、ミドル、トップ)背景・注記 e_Sc1_Disp_Type_C= a_Value.intVal; }else if( (a_Col_Name == DSC2_F) || (a_Col_Name == SC2DT_C) ){ // 表示スケール2 e_Sc2_Disp_Type_C= a_Value.intVal; }else if( (a_Col_Name == DSC3_F) || (a_Col_Name == SC3DT_C) || (a_Col_Name == DST_C) ){ // 表示スケール3(都市地図注記も対応) e_Sc3_Disp_Type_C= a_Value.intVal; }else if( (a_Col_Name == DSC4_F) || (a_Col_Name == SC4DT_C) ){ // 表示スケール4 e_Sc4_Disp_Type_C= a_Value.intVal; }else if( a_Col_Name == SC1BGC_C ){ // 表示種別コード・スケール1(ベース、ミドル、トップ)背景 e_Sc1_Disp_Code_C = a_Value.intVal; e_Cur_Attr_Cls = BG_C; }else if( a_Col_Name == SC2BGC_C ){ // 表示種別コード・表示スケール2 e_Sc2_Disp_Code_C = a_Value.intVal; e_Cur_Attr_Cls = BG_C; }else if( a_Col_Name == SC3BGC_C ){ // 表示種別コード・表示スケール3 e_Sc3_Disp_Code_C = a_Value.intVal; e_Cur_Attr_Cls = BG_C; }else if( a_Col_Name == SC4BGC_C ){ // 表示種別コード・表示スケール4 e_Sc4_Disp_Code_C = a_Value.intVal; e_Cur_Attr_Cls = BG_C; }else if(a_Col_Name == UNDER_F){ // 地上・地下フラグ(鉄道関係) e_Under_Ground_F= a_Value.intVal; }else if(a_Col_Name == CNT_C){ // 段彩種別 e_Class_C = a_Value.intVal; ///< 段彩 e_Cur_Attr_Cls = CNT_C; }else if(a_Col_Name == CLR_CODE) { ///< 街区色番号 e_Color_Code = a_Value.intVal; }else if(a_Col_Name == BG_C){ ///< 背景種別(都市、ベース、ミドル、トップ) e_Class_C = a_Value.intVal; ///< 都市地図、中縮尺種別 e_Cur_Attr_Cls = BG_C; }else if(a_Col_Name == RAIL_C){ // 鉄道路線種別 e_Class_C = a_Value.intVal; ///< 鉄道路線 e_Cur_Attr_Cls = RAIL_C; }else if(a_Col_Name == STAT_C){ // 鉄道駅舎種別 e_Class_C = a_Value.intVal; ///< 駅舎 e_Cur_Attr_Cls = STAT_C; }else if(a_Col_Name == BLD_C){ // 建物種別 e_Class_C = a_Value.intVal; ///< 建物ポリゴン e_Cur_Attr_Cls = BLD_C; }else if(a_Col_Name == ROAD_C){ // 道路表示種別 e_Class_C = a_Value.intVal; ///< 道路 e_Cur_Attr_Cls = ROAD_C; }else if(a_Col_Name == C_CODE){ // 市区町村コード // 行政界のみ string a_City_Code_Str; a_City_Code_Str = Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); e_City_Code = a_City_Code_Str; }else if(a_Col_Name == A_CODE){ // 町丁目コード string a_Addr_Code_Str; a_Addr_Code_Str = Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); e_Addr_Code = a_Addr_Code_Str; }else if(a_Col_Name == N_STR_1){ // 名称文字列1 e_Str_1 = Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); }else if(a_Col_Name == N_STR_2){ // 名称文字列2 e_Str_2 = Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); }else if(a_Col_Name == N_STR_3){ // 名称文字列3 e_Str_3 = Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); }else if(a_Col_Name == S_NUM_1){ // 名称文字数1 e_Str_Num_1 = a_Value.intVal; }else if(a_Col_Name == S_NUM_2){ // 名称文字数2 e_Str_Num_2 = a_Value.intVal; }else if(a_Col_Name == S_NUM_3){ // 名称文字数3 e_Str_Num_3 = a_Value.intVal; }else if(a_Col_Name == AN_CLS_C){ // 注記種別 e_Anno_Class_C = a_Value.intVal; e_Cur_Attr_Cls = AN_CLS_C; }else if(a_Col_Name == TMP_AN_CLS){ // テンポラリ種別 e_Tmp_Anno_Class= Str_to_SJIS ((CComBSTR *)(&a_Value.bstrVal)); }else if(a_Col_Name == M_TYPE){ // 図形IDにあたる // e_Mark_Type = a_Value.intVal; }else if(a_Col_Name == CHINUM) { // 地番番号 e_Chiban_No = a_Value.intVal; }else if(a_Col_Name == A_F) { // 地番注記フラグ e_Anno_F = a_Value.intVal; }else if(a_Col_Name == F_SIZE) { // フォントサイズ e_FontSize = a_Value.intVal; }else if(a_Col_Name == A_ID) { // ラインに対応するID e_Note_ID = a_Value.intVal; }else if(a_Col_Name == TARGET_S) { // 表示文字列がどれか e_Target_Str_Num= a_Value.intVal; }else if(a_Col_Name == MESH_C) { // メッシュコード矩形用 e_MeshCode = a_Value.intVal; }else if(a_Col_Name == SPEC_F) { e_Spec_F = a_Value.intVal; // 段差情報 }else if(a_Col_Name == SHP){ // シェイプデータ // if( a_Col_Type == SE_SHAPE_TYPE ){ // IGeometryPtr a_Tmp_Shp; // c_Feature->get_ShapeCopy ( &a_Tmp_Shp ); // e_Geometry_Ptr = a_Tmp_Shp; // c_Feature->get_Shape ( &c_Shape ); // シェイプを取得 // } } } // End for return ( true ); } /** Unicodeの文字列からSJISにする */ string Smp_db_obj_attr:: Str_to_SJIS ( CComBSTR* c_CStr ) // 文字列(Unicode) { string ret_str; #ifdef _ARC_9_1_ USES_CONVERSION; if (*c_CStr != 0) { ret_str = OLE2T(*c_CStr); } #else USES_CONVERSION; #ifndef _SINDY_A_ long length = c_CStr->Length() * 2; char* tmp_moji = new char[length+1]; memset (tmp_moji, '\0', length+1); _bstr_t a_bTmp ( *c_CStr, false ); // wchar_t* tmp_wide = OLE2W(*c_CStr); wchar_t* tmp_wide = (wchar_t *)a_bTmp; if(tmp_wide == NULL) { ret_str = ""; }else { if(wcstombs( tmp_moji, tmp_wide, length+1 ) == -1){ ret_str = ""; }else { ret_str = tmp_moji; } } delete [] tmp_moji; #else if (*c_CStr != 0) { ret_str = OLE2T(*c_CStr); } #endif #endif // end of _ARC_9_1_ return (ret_str); } /** ジオメトリを内部点列に変換 @return bool */ bool Smp_db_obj_attr:: Inport_Geo ( IGeometryPtr c_ipGeo ) ///< ジオメトリ { // HRESULT hr; esriGeometryType a_eGeoType; if( c_ipGeo == NULL ) { fprintf ( stderr, "ジオメトリがNULLです\n"); return ( false ); } if( FAILED( c_ipGeo->get_GeometryType( &a_eGeoType )) ) { fprintf ( stderr, "[Inport_Geo] ジオメトリタイプがとれません\n" ); return ( false ); } // ジオメトリのタイプを取得する if( a_eGeoType == esriGeometryPolygon ) { e_Pts_Type = PTS_POLY; }else if( a_eGeoType == esriGeometryPolyline ) { e_Pts_Type = PTS_LINE; }else if( a_eGeoType == esriGeometryPoint ) { e_Pts_Type = PTS_POINT; }else { fprintf ( stderr, "未対応のジオメトリタイプです<msi_get_parts_info>\n" ); return ( false ); } // ジオメトリコレクションにしてパート、サブパート毎にばらばらの点列にする IGeometryCollectionPtr a_ipGeoColl ( c_ipGeo ); long a_lGeo_Count = 0; // ジオメトリの個数 a_ipGeoColl->get_GeometryCount ( &a_lGeo_Count ); int i = 0; for ( i = 0; i < a_lGeo_Count; i++ ) { IGeometryPtr a_ipCurGeo; // ジオメトリを取り出す a_ipGeoColl->get_Geometry ( i, &a_ipCurGeo ); IPointCollectionPtr a_ipTmpPts; // 補間点列 if( a_eGeoType == esriGeometryPolygon ) { // ポリゴン a_ipTmpPts = (IRingPtr)a_ipCurGeo; }else if( a_eGeoType == esriGeometryPolyline ) { // ポリライン a_ipTmpPts = (IPathPtr)a_ipCurGeo; }else { // ポイント a_ipTmpPts = (IPointPtr)a_ipCurGeo; } long a_lPtCount = 0; // 補間点数 a_ipTmpPts->get_PointCount ( &a_lPtCount ); // 内部点列の領域を確保しておく v_Dpos a_TmpPts; // 1ジオメトリの点列 int i = 0; for ( i = 0; i < a_lPtCount; i++ ) { IPointPtr a_ipPt; Dpos a_dPos; a_ipTmpPts->get_Point ( i, &a_ipPt ); a_ipPt->get_X ( &a_dPos.xpos ); a_ipPt->get_Y ( &a_dPos.ypos ); a_TmpPts.push_back ( a_dPos ); // パートごとの点列に追加 } e_vDPtsArray.push_back ( a_TmpPts ); // 点列をベクタに追加 } return ( true ); } /** 内部点列をジオメトリに変換 @return IGeometryPtr 成功 @return NULL 失敗 */ IGeometryPtr Smp_db_obj_attr:: Export_Geo ( void ) { IGeometryPtr a_ipRetGeo = NULL; IGeometryCollectionPtr a_ipTmpColl; IPolygonPtr a_ipPoly ( CLSID_Polygon ); IPolylinePtr a_ipLine ( CLSID_Polyline ); IPointPtr a_ipPoint( CLSID_Point ); if( e_Pts_Type == PTS_POLY ) { a_ipTmpColl = a_ipPoly; }else if( e_Pts_Type == PTS_LINE ) { a_ipTmpColl = a_ipLine; }else { a_ipTmpColl = a_ipPoint; } iv_v_Dpos a_ivIndx; // 点列パートのインデックス for( a_ivIndx = e_vDPtsArray.begin(); a_ivIndx != e_vDPtsArray.end(); a_ivIndx++ ) { v_Dpos a_vCurPts = *a_ivIndx; IGeometryPtr a_ipTmpGeo; IRingPtr a_ipRing ( CLSID_Ring ); IPathPtr a_ipPath ( CLSID_Path ); IPointCollectionPtr a_ipPts; // if( e_Pts_Type == PTS_POLY ) { // ポリゴンの場合 a_ipTmpGeo = a_ipPoly; a_ipPts = a_ipPoly; }else if( e_Pts_Type == PTS_LINE ) { // ポリラインの場合 a_ipTmpGeo = a_ipLine; a_ipPts = a_ipLine; }else { // ポイントの場合 a_ipTmpGeo = a_ipPoint; a_ipPts = a_ipPoint; } // 点列を追加していく iv_Dpos a_ivIndx2; for ( a_ivIndx2 = a_vCurPts.begin(); a_ivIndx2 != a_vCurPts.end(); a_ivIndx2++ ) { Dpos a_TmpPt = *a_ivIndx2; IPointPtr a_ipPt ( CLSID_Point ); a_ipPt->put_X ( a_TmpPt.xpos ); a_ipPt->put_Y ( a_TmpPt.ypos ); a_ipPts->AddPoint ( a_ipPt ); } // コレクションに追加する a_ipTmpColl->AddGeometry ( a_ipTmpGeo ); } // コレクションに追加したデータについてシンプリファイかける if( e_Pts_Type == PTS_POLY ) { if( FAILED ( a_ipPoly->SimplifyPreserveFromTo () ) ) { fprintf ( stderr, "Simplifyに失敗\n" ); return ( NULL ); } a_ipRetGeo = a_ipPoly; }else if( e_Pts_Type == PTS_LINE ) { if( FAILED ( a_ipLine->SimplifyNetwork () ) ) { fprintf ( stderr, "Simplifyに失敗\n" ); return ( NULL ); } a_ipRetGeo = a_ipLine; }else { a_ipRetGeo = a_ipPoint; } return ( a_ipRetGeo ); }
[ "noreply@github.com" ]
noreply@github.com
3ea603a7dc4401b7bc2f7f77c780faf513c9ff00
306c60c674af877691e42c28d5249faf27acbef3
/GLL/src/minecraft/MapGenerator/TemperateForestBiome.cpp
5d8ff3d40e3f63fabb6f09c2b17dfb0d49a900d8
[]
no_license
waynezxcv/playMC
f028dd9c89a6fa56d55a1b800437c071522d260c
0cb0723500e7b467c1c3c6c8b7d3e79da14e26fa
refs/heads/master
2020-07-10T17:16:56.989680
2019-09-07T17:35:18
2019-09-07T17:35:18
204,319,687
0
0
null
null
null
null
UTF-8
C++
false
false
1,000
cpp
#include "TemperateForestBiome.hpp" #include "TreeGenerator.hpp" using namespace GLL; TemperateForestBiome::TemperateForestBiome(int seed) : Biome(getNoiseParameters(), 55, 75, seed) { } BlockId TemperateForestBiome::getTopBlock(Rand& rand) const { return rand.intInRange(0, 10) < 8 ? BlockId_Grass : BlockId_Dirt; } BlockId TemperateForestBiome::getUnderWaterBlock(Rand& rand) const { return rand.intInRange(0, 10) > 8 ? BlockId_Dirt: BlockId_Sand; } void TemperateForestBiome::makeTree(Rand& rand, std::shared_ptr<Chunk> chunk, int x, int y, int z) const { makeOakTree(chunk, rand, x, y, z); } NoiseParameters TemperateForestBiome::getNoiseParameters() { NoiseParameters heightParams; heightParams.octaves = 5; heightParams.amplitude = 100; heightParams.smoothness = 195; heightParams.heightOffset = -30; heightParams.roughness = 0.52; return heightParams; } BlockId TemperateForestBiome::getPlant(Rand& rand) const { return BlockId_TallGrass; }
[ "liuweiself@126.com" ]
liuweiself@126.com
3a87abf0c225d20b6db4118187faaa29ed32f298
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Plugins/Runtime/GameplayAbilities/Source/GameplayAbilities/Private/Abilities/Tasks/AbilityTask_ApplyRootMotionConstantForce.cpp
bb62528c907e3bd45a45cea009d856489959c1e0
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
4,628
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Abilities/Tasks/AbilityTask_ApplyRootMotionConstantForce.h" #include "GameFramework/RootMotionSource.h" #include "GameFramework/CharacterMovementComponent.h" #include "AbilitySystemComponent.h" #include "AbilitySystemGlobals.h" #include "Net/UnrealNetwork.h" UAbilityTask_ApplyRootMotionConstantForce::UAbilityTask_ApplyRootMotionConstantForce(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { StrengthOverTime = nullptr; } UAbilityTask_ApplyRootMotionConstantForce* UAbilityTask_ApplyRootMotionConstantForce::ApplyRootMotionConstantForce ( UGameplayAbility* OwningAbility, FName TaskInstanceName, FVector WorldDirection, float Strength, float Duration, bool bIsAdditive, UCurveFloat* StrengthOverTime, ERootMotionFinishVelocityMode VelocityOnFinishMode, FVector SetVelocityOnFinish, float ClampVelocityOnFinish ) { UAbilitySystemGlobals::NonShipping_ApplyGlobalAbilityScaler_Duration(Duration); UAbilityTask_ApplyRootMotionConstantForce* MyTask = NewAbilityTask<UAbilityTask_ApplyRootMotionConstantForce>(OwningAbility, TaskInstanceName); MyTask->ForceName = TaskInstanceName; MyTask->WorldDirection = WorldDirection.GetSafeNormal(); MyTask->Strength = Strength; MyTask->Duration = Duration; MyTask->bIsAdditive = bIsAdditive; MyTask->StrengthOverTime = StrengthOverTime; MyTask->FinishVelocityMode = VelocityOnFinishMode; MyTask->FinishSetVelocity = SetVelocityOnFinish; MyTask->FinishClampVelocity = ClampVelocityOnFinish; MyTask->SharedInitAndApply(); return MyTask; } void UAbilityTask_ApplyRootMotionConstantForce::SharedInitAndApply() { if (AbilitySystemComponent->AbilityActorInfo->MovementComponent.IsValid()) { MovementComponent = Cast<UCharacterMovementComponent>(AbilitySystemComponent->AbilityActorInfo->MovementComponent.Get()); StartTime = GetWorld()->GetTimeSeconds(); EndTime = StartTime + Duration; if (MovementComponent) { ForceName = ForceName.IsNone() ? FName("AbilityTaskApplyRootMotionConstantForce"): ForceName; FRootMotionSource_ConstantForce* ConstantForce = new FRootMotionSource_ConstantForce(); ConstantForce->InstanceName = ForceName; ConstantForce->AccumulateMode = bIsAdditive ? ERootMotionAccumulateMode::Additive : ERootMotionAccumulateMode::Override; ConstantForce->Priority = 5; ConstantForce->Force = WorldDirection * Strength; ConstantForce->Duration = Duration; ConstantForce->StrengthOverTime = StrengthOverTime; ConstantForce->FinishVelocityParams.Mode = FinishVelocityMode; ConstantForce->FinishVelocityParams.SetVelocity = FinishSetVelocity; ConstantForce->FinishVelocityParams.ClampVelocity = FinishClampVelocity; RootMotionSourceID = MovementComponent->ApplyRootMotionSource(ConstantForce); if (Ability) { Ability->SetMovementSyncPoint(ForceName); } } } else { ABILITY_LOG(Warning, TEXT("UAbilityTask_ApplyRootMotionConstantForce called in Ability %s with null MovementComponent; Task Instance Name %s."), Ability ? *Ability->GetName() : TEXT("NULL"), *InstanceName.ToString()); } } void UAbilityTask_ApplyRootMotionConstantForce::TickTask(float DeltaTime) { if (bIsFinished) { return; } Super::TickTask(DeltaTime); AActor* MyActor = GetAvatarActor(); if (MyActor) { const bool bTimedOut = HasTimedOut(); const bool bIsInfiniteDuration = Duration < 0.f; if (!bIsInfiniteDuration && bTimedOut) { // Task has finished bIsFinished = true; if (!bIsSimulating) { MyActor->ForceNetUpdate(); if (ShouldBroadcastAbilityTaskDelegates()) { OnFinish.Broadcast(); } EndTask(); } } } else { bIsFinished = true; EndTask(); } } void UAbilityTask_ApplyRootMotionConstantForce::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(UAbilityTask_ApplyRootMotionConstantForce, WorldDirection); DOREPLIFETIME(UAbilityTask_ApplyRootMotionConstantForce, Strength); DOREPLIFETIME(UAbilityTask_ApplyRootMotionConstantForce, Duration); DOREPLIFETIME(UAbilityTask_ApplyRootMotionConstantForce, bIsAdditive); DOREPLIFETIME(UAbilityTask_ApplyRootMotionConstantForce, StrengthOverTime); } void UAbilityTask_ApplyRootMotionConstantForce::PreDestroyFromReplication() { bIsFinished = true; EndTask(); } void UAbilityTask_ApplyRootMotionConstantForce::OnDestroy(bool AbilityIsEnding) { if (MovementComponent) { MovementComponent->RemoveRootMotionSourceByID(RootMotionSourceID); } Super::OnDestroy(AbilityIsEnding); }
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
cd7ec8d4dcb0f5e463fa2efc4c812767e5af4401
ee32d46014c1f2fc5ec7bb833233c24237270933
/1400C/main.cpp
668ce9ff81b01e6702de104956acff6b8408eaa1
[]
no_license
boxnos/codeforces
42b48367d222cc58c2bc0f408469fc6a2732cec7
fbc358fe7ddf48d48bda29e75ef3264f9ed19852
refs/heads/master
2023-08-27T21:18:44.163264
2023-08-26T18:06:59
2023-08-26T18:06:59
192,764,064
0
0
null
null
null
null
UTF-8
C++
false
false
7,011
cpp
#if !defined __clang__ #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #define _USE_MATH_DEFINES #endif #include <cstdio> #include <cstring> #include <utility> #include <functional> #include <array> #include <limits> #include <string> // #include <unordered_set> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; // #define MINUS_ #define IO_ //#define PCK_ #define I_ inline #define T_ template #define TN_ typename #define TT_ T_ <TN_ T> #define HT_ T_ <TN_ H,TN_... T> #define OP_(t) I_ operator t() #define ly(x) __builtin_expect(x, 1) #define un(x) __builtin_expect(x, 0) #ifdef IO_ namespace io { const size_t s=1<<18;char in[s],*i {},*e {},out[s],*o=out,*f=o+s-1; I_ char get(){return i==e?e=(i=in)+fread(in,1,s,stdin),i==e?EOF:*i++:*i++;} I_ void flush(){fwrite(out,1,o-out,stdout);o=out;} I_ void put(char c){*o++=c;if(o==f)flush();} I_ void put_string(char *b, char *e) { static char *g {f + 1}; if (size_t l = e - b, r = g - o; ly(l < r)) memcpy(o, b, l), o+=l; else { memcpy(o, b, r), o+=r; flush(); if (l > r) put_string(b + r, e); } }; #ifdef _GLIBCXX_STRING #define S_ I_ void put_string(string &str) { static char *g {f + 1}; if (un(str.size() >= size_t(g - o))) put_string(&str[0], &str[str.size()]); else memcpy(o, &str[0], str.size()), o+=str.size(); }; I_ void get_string(string &str) { if (str.size() > size_t(e - i)) { for(char &i:str)i=get(); get(); } else memcpy(&str[0], i, str.size()), i+=str.size(), get(); }; I_ string get_string() { for (char *j = i; j != e; ++j) if (*j == ' ' || *j == '\n') return string(exchange(i, j + 1), j); string s;for(char c;c=get(),c!=' '&&c!='\n';)s+=c;return s; } #endif struct flush_{~flush_(){flush();}} flush__;} #define gcu io::get #define pcu io::put #else #ifdef __linux #define _U(s) s##_unlocked #else #define _U(s) _##s##_nolock #define _CRT_DISABLE_PERFCRIT_LOCKS #endif #define gcu _U(getchar) #define pcu _U(putchar) #endif struct in_ { I_ operator void *(){char c;do{c=gcu();}while(c!=' '&&c!='\n');return NULL;} #ifdef S_ OP_(string){ #ifdef IO_ return io::get_string();} #else string s;for(char c;c=get(),c!=' '&&c!='\n';)s+=c;return s;} #endif //OP_(string){string s;char c;while(isspace(c = gcu()));do{s+=c;}while(c=gcu(),c!=' '&&c!='\n'&&c!=EOF);return s;} I_ string read(int n,char c) { string v(n,c); #ifdef IO_ io::get_string(v); #else for(char &i:v)i=gcu();gcu(); #endif return v; } #endif OP_(char){char c=gcu();gcu();return c;} #ifndef IO_ OP_(double){double d; scanf("%lf",&d); gcu();return d;} #endif TT_ I_ T RI_(char c){T n{};do{n=10*n+(c-'0'),c=gcu();}while(c>='0'/* &&c<='9' */);return n;} TT_ OP_(T){ char c=gcu(); #ifdef PCK_ for(;isspace(c);c=gcu()); #endif #ifdef MINUS_ return c=='-'?~(RI_<T>(gcu())-1):RI_<T>(c); #else return RI_<T>(c); #endif } #ifdef _GLIBCXX_VECTOR #define TI_ T_<TN_ T=vector<int>, TN_ I=TN_ T::value_type> TI_ I_ T read(int n) {T v(n);for(I &i:v)i=*this;return v;} TI_ I_ T read(int n,function<int(TN_ T::value_type)>f){T v(n);for(I &i:v)i=f(*this);return v;} TI_ I_ T read(int n,function<void(TN_ T::value_type&,TN_ T::value_type)>f){T v(n);for(I &i:v)f(i,*this);return v;} #endif T_ <int N, TN_ T=int> array<T, N> read(){array<T, N>a;for(T &i:a)i=*this;return a;} } in; T_ <TN_ T=int> struct ist { int n; ist(int _n) : n(_n) {}; struct it { int p; it(int _p) : p(_p) {}; I_ T operator *() const {return T(in);}; I_ bool operator !=(const it& v) {return p != v.p;}; I_ it & operator ++() {++p; return *this;}; }; I_ it begin() {return {0};}; I_ it end() {return {n};}; }; #define DEF_(r, n, ...) I_ r n(__VA_ARGS__) #define OUT_(...) DEF_(void,out,__VA_ARGS__) #define OUTL_(...) DEF_(void,outl,__VA_ARGS__) OUT_(bool b){pcu('0'+b);} OUT_(const char *s){while(*s)pcu(*s++);} OUT_(char c){pcu(c);} #ifdef S_ OUT_(string &s){ #ifdef IO_ io::put_string(s); #else for(char c:s)pcu(c); #endif } //OUT_(string s){for(char c:s)pcu(c);} #endif //TT_ DEF_(void,OUTX_,T n){if(n<10)pcu(n+'0');else OUTX_(n/10),pcu(n%10+'0');} TT_ OUT_(T n){ #ifdef MINUS_ if(n<0)pcu('-'),n=-n; #endif static char b[20], *a=b+20; char *p=a; if(n)while(n)*--p=n%10+'0',n/=10;else*--p='0'; #ifdef IO_ io::put_string(p, a); #else while(p!=a)pcu(*p++); #endif //OUTX_(n); } TT_ OUT_(initializer_list<T> v){for(auto i{begin(v)};i!=end(v);++i)out(i==begin(v)?"":" "),out(*i);} #ifdef _GLIBCXX_VECTOR TT_ OUT_(vector<T> &v){if(auto i{begin(v)},e{end(v)};i!=e){out(*i++);for(;i!=e;++i)out(' '),out(*i);}} #endif HT_ OUT_(H &&h,T... t){out(h);out(t...);} OUTL_(){out('\n');} T_ <TN_... T> OUTL_(T... t){out(t...);outl();} T_ <TN_ I,TN_... T> OUTL_(initializer_list<I> v,T... t){for(auto i{begin(v)};i!=end(v);++i)out(i==begin(v)?"":" "),out(*i);outl(t...);} T_ <TN_ T=int> struct range{ T e,b=0,s=1;range(T b,T e,T s):e(e),b(b),s(s){} range(T b,T e): e(e), b(b){} range(T e):e(e){} struct it{T v,s; it(T v,T s):v(v),s(s){} operator T()const{return v;} I_ operator T&(){return v;}T operator*()const{return v;} I_ it& operator++(){v+=s;return *this;}}; it begin(){return {b,s};} it end(){return {e,s};}}; #define Range(b,...)for([[maybe_unused]] auto b:range<int>((int) __VA_ARGS__)) #define Test Range(testcase__, in) #define dbg(...)fprintf(stderr,__VA_ARGS__) using LL=long long; #define tee(s,v)({dbg(s,v);v;}) #define TAPP(t,s)t tapp(t v){return tee(s, v);} TAPP(char,"%c") TAPP(int,"%d") TAPP(LL,"%lld") TAPP(const char *, "%s") TAPP(bool, "%d") #ifdef S_ string tapp(string s) {return tee("%s",s.c_str());} #endif TT_ T tapp(T v){for (auto i: v){tapp(i);dbg(" ");}return v;} TT_ T tapl(T v){tapp(v);dbg("\n");return v;} #ifdef _GLIBCXX_IOSTREAM void fast_io() {ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);} #endif #ifdef _FUNCTIONAL_HASH_H #include <chrono> struct custom_hash{size_t operator()(size_t x)const{static const size_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); x += 0x9e3779b97f4a7c15 + FIXED_RANDOM; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } }; #endif TT_ constexpr T inf {numeric_limits<T>::max()}; TT_ T sign(T a) {return (a > 0) - (a < 0);} I_ int bsign(bool b){return b - !b;} TT_ T eucdiv(T a, T b) {T t = a / b; return a % b < 0 ? t - 1: t;} TT_ T eucmod(T a, T b) {T t = a % b; return t < 0 ? t + abs(b) : t;} TT_ I_ T ceil(T a, T b) {return (a + b - 1) / b;} T_ <TN_ P, TN_ O> I_ constexpr int len(P &p, O o) {return distance(begin(p), o);} TT_ I_ constexpr int len(T p) {return size(p);} int main() { Test { string s = in, o(size(s), '1'); int x {in}, n = size(s); outl([&] () -> string { Range (i, n) if (s[i] == '0') { if (i + x < n) o[i + x] = '0'; if (i >= x) o[i - x] = '0'; } Range (i, n) if (s[i] == '1' && (i + x >= n || o[i + x] != '1') && (i < x || o[i - x] != '1')) return "-1"; return o; }()); } } /* vim: set ts=4 noet: */
[ "boxnos@yahoo.com" ]
boxnos@yahoo.com
b5a716ef0046c7ec77f862c27d4f645d8dc34a99
d0d8c07fabb26d80201ae78e29819b2b41c04e4e
/HelloWorld.cpp
d83e7dd5d062e995ab12f04cb1a2c82c13feede5
[]
no_license
sbw111/learner
b012be80c497d3aabfeb847d8713d86e243632be
39bdbead38fb09ddc8863cf272f07978c41ae4f6
refs/heads/master
2020-05-25T10:21:57.248575
2013-11-29T07:33:11
2013-11-29T07:33:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
122
cpp
#include<iostream> using std::cin; using std::cout; using std::endl; void main(){ cout<<"Hello World!I'm elroy!"<<endl; }
[ "782172672@qq.com" ]
782172672@qq.com
74013ce4d0f200419528a0d2c2a0cc3e066b49d6
d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9
/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_listen_socket_execlp_82_bad.cpp
8ffdf05d859a90e7ddeeb2d732987f24defe2a45
[]
no_license
arichardson/juliet-test-suite-c
cb71a729716c6aa8f4b987752272b66b1916fdaa
e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9
refs/heads/master
2022-12-10T12:05:51.179384
2022-11-17T15:41:30
2022-12-01T15:25:16
179,281,349
34
34
null
2022-12-01T15:25:18
2019-04-03T12:03:21
null
UTF-8
C++
false
false
1,308
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_listen_socket_execlp_82_bad.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-82_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Fixed string * Sinks: execlp * BadSink : execute command with execlp * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE78_OS_Command_Injection__char_listen_socket_execlp_82.h" #ifdef _WIN32 #include <process.h> #define EXECLP _execlp #else /* NOT _WIN32 */ #define EXECLP execlp #endif namespace CWE78_OS_Command_Injection__char_listen_socket_execlp_82 { void CWE78_OS_Command_Injection__char_listen_socket_execlp_82_bad::action(char * data) { /* execlp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); } } #endif /* OMITBAD */
[ "Alexander.Richardson@cl.cam.ac.uk" ]
Alexander.Richardson@cl.cam.ac.uk
07327af6bf5d2511108531de6f09e2c78a99b7a3
605f46e451203be926c82a8cbcc94b71a4d2cce8
/StackUsingqueue(2).cpp
ec4cf083f9917450108c9994f367997cc1ae7b99
[]
no_license
jayantbansal21/C-OnceAgain
46b0005432d2fedaca1529f76da6ae6a58f963b1
154abed0b8dfe63122319ef250e96259eb942e42
refs/heads/main
2023-04-23T16:22:40.941822
2021-05-15T13:05:35
2021-05-15T13:05:35
363,094,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,112
cpp
#include <bits/stdc++.h> using namespace std; //Output method is costly class Stack { queue<int> q1; queue<int> q2; int n; public: Stack() { n = 0; } void push(int val) { q1.push(val); n++; } void pop() { if (q1.empty()) { return; } while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } q1.pop(); n--; queue<int> temp = q1; q1 = q2; q2 = temp; } int top() { if (q1.empty()) { return -1; } while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } int ans = q1.front(); q2.push(ans); queue<int> temp = q1; q1 = q2; q2 = temp; return ans; } int size() { return n; } }; int main() { Stack st; st.push(1); st.push(2); st.push(3); st.push(4); cout << st.top() << endl; st.pop(); cout << st.top() << endl; return 0; }
[ "bansal.jayant8737@gmail.com" ]
bansal.jayant8737@gmail.com
d60e953ffc729eae9e8a6eb051fd507934d5fc44
cd5ca42c7ed09d7dc59e02c92c0b0a78b4049055
/HPLC-MS/DataFitting.h
0b2df8e7f3f9e8c46645f5af9804444c8759ced9
[]
no_license
tangxulab/QitVenture-6
8397421f1149953f94ce715db4c1ee6fa7308bb2
91be42bd38d49c958090b19a031cf7f4cf897b2a
refs/heads/main
2023-08-03T20:39:07.294912
2021-09-15T06:29:47
2021-09-15T06:29:47
406,621,931
0
0
null
null
null
null
UTF-8
C++
false
false
778
h
#ifndef DATAFITTING_H #define DATAFITTING_H #include <QVector> #include <QtMath> #include "SQLList.h" class DataFitting { public: DataFitting(); //最小二乘拟合相关函数定义 double sum(QVector<double> Vnum, int n); double MutilSum(QVector<double> Vx, QVector<double> Vy, int n); double RelatePow(QVector<double> Vx, int n, int ex); double RelateMutiXY(QVector<double> Vx, QVector<double> Vy, int n, int ex); void EMatrix(QVector<double> Vx, QVector<double> Vy, int n, int ex, double coefficient[]); void CalEquation(int exp, double coefficient[]); double F(double c[], int l, int m); double Em[6][4]; void LineFitLeastSquares(double* data_x, double* data_y, int data_n, double& a, double& b); }; #endif // DATAFITTING_H
[ "m17855827529@163.com" ]
m17855827529@163.com
4c829be287d8853672ac83dd4c31504392c8d45d
2ee36ad41dbb204cbcadb835899c91ffbdf4756f
/Queue.cpp
966b5d904c08b1475d5b4f240aa9aa0f2d221a03
[]
no_license
HarshNandwani/DataStructures-C-Implementation
1c70f66bf0f46c7d93844c4ad50bef51ffb84878
b43bb6cab8ba39b5650e8d83119e2a16f2ebcbc3
refs/heads/master
2020-06-01T17:22:29.446354
2019-06-08T08:30:08
2019-06-08T08:30:08
190,863,925
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
#include<iostream> using namespace std; class Queue{ int front; int rear; int list[100]; public: void EnQueue(); void deQueue(); bool QueueIsEmpty(); Queue(){ front=-1; rear=-1; } }; /*Inserting from rear & deletion from front.*/ void Queue::EnQueue(){ int x; cout<<"Enter elememt: "; cin>>x; if(QueueIsEmpty()){ front++; rear++; list[rear]=x; } else{ rear++; list[rear]=x; } } void Queue::deQueue(){ if(QueueIsEmpty()){ cout<<"Queue is already Empty."; } else{ int temp=list[front]; front++; cout<<"The element "<<temp<<"is deleted from Queue"<<endl; } } bool Queue::QueueIsEmpty(){ if(front==-1&&rear==-1) return true; else return false; } void menu(){ cout<<"\t\t MENU"<<endl; cout<<"1.Add element to queue"<<endl; cout<<"2.Delete from queue"<<endl; cout<<"3.Display Queue"<<endl; } int main(){ Queue A; char Continue='Y'; int option; while(Continue=='Y'||Continue=='y'){ menu(); cout<<"Enter Option from menu: "; cin>>option; switch(option){ case 1: A.EnQueue(); break; case 2: A.deQueue(); break; } } }
[ "noreply@github.com" ]
noreply@github.com
bd70881049c3d271c4f8470636fcf834cca8928f
88f3fe8a0fd64a36f4bba69aa8fd8e41a6feea64
/src/util/unittest/StringHashMapTest.cpp
de923a66f4d82fa912dc18a162103fb409dd65c9
[]
no_license
AltropInc/alt
0fa30bd2e5194d0b0e4832f8dce89177c4c00b62
831fc4e19d74364da03ba02cf9ac643afc0adaa3
refs/heads/master
2023-09-04T18:52:38.873358
2023-09-03T13:17:33
2023-09-03T13:17:33
249,748,618
0
0
null
null
null
null
UTF-8
C++
false
false
2,376
cpp
#include <util/storage/StringHashMap.h> #include <catch2/catch.hpp> #include <iostream> #include <assert.h> #include <vector> TEST_CASE( "StringHashMapTest", "[StringHashMapTest]" ) { //std::cout << "testhash start" << std::endl; alt::StringHashMap<std::pair<int64_t, double>> testhash; //std::cout << "testhash.emplace(\"one\")" << std::endl; auto res = testhash.emplace("one", std::make_pair(1,1.1)); //std::cout << "testhash.emplace(\"two\")" << std::endl; auto res2 = testhash.emplace("two", std::make_pair(2,1.2)); //std::cout << "testhash.emplace(\"three\")" << std::endl; auto res3 = testhash.emplace("three", std::make_pair(3,1.3)); //std::cout << "testhash.find(\"one\")" << std::endl; auto fres1 = testhash.find("one"); //std::cout << "testhash.find(\"two\")" << std::endl; auto fres2 = testhash.find("two"); //std::cout << "testhash.find(\"three\")" << std::endl; auto fres3 = testhash.find("three"); REQUIRE(fres1->second.first==1); REQUIRE(fres2->second.first==2); REQUIRE(fres3->second.first==3); //std::cout << "testhash.erase(\"three\")" << std::endl; testhash.erase("three"); //std::cout << "testhash.find(\"three\")" << std::endl; fres3 = testhash.find("three"); REQUIRE(fres3==testhash.end()); REQUIRE(2==testhash.size()); //std::cout << "testhash end" << std::endl; } /* ALLOCATE n=1 hint=0 Tsz=24 rebind_size=0 FixedMemPool::newSlab: malloc size=28800 entry_size=32 New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 New rebindAllocator Tsz=8 Usz=24 ALLOCATE n=3 hint=0 Tsz=8 rebind_size=8 FixedMemPool::newSlab: malloc size=17600 entry_size=16 DELETE ALLOCATOR Tsz=8 ALLOCATE n=1 hint=0 Tsz=24 rebind_size=0 New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 ALLOCATE n=1 hint=0 Tsz=24 rebind_size=0 New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 New rebindAllocator Tsz=8 Usz=24 ALLOCATE n=7 hint=0 Tsz=8 rebind_size=8 DELETE ALLOCATOR Tsz=8 New rebindAllocator Tsz=8 Usz=24 DELETE ALLOCATOR Tsz=8 testhash find 1 by one testhash find 2 by two testhash find 3 by three New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 New rebindAllocator Tsz=16 Usz=24 DELETE ALLOCATOR Tsz=16 New rebindAllocator Tsz=8 Usz=24 DELETE ALLOCATOR Tsz=8 DELETE ALLOCATOR Tsz=24 */
[ "lujunshang@gmail.com" ]
lujunshang@gmail.com
3e5902684c29dd8787b3c6ca55d16380441dbb14
54a9780a07814578cc321ea4e753ea6d6f428e18
/src/ArgParse.cpp
5982f7a1042d53f51a5df0b480fe786f69fbc5a3
[]
no_license
JosephFoster118/J118
7293ae2a5fa9ba797a14bb845789d7fc54afe1bd
381b80d8e1f36cc56800f89dc1db53a6e5092c84
refs/heads/master
2020-06-16T22:43:32.069244
2020-02-14T20:51:55
2020-02-14T20:51:55
75,064,844
0
0
null
2020-02-14T04:57:49
2016-11-29T09:25:39
C++
UTF-8
C++
false
false
1,471
cpp
#include "J118/ArgParse.h" namespace J118 { namespace Utilities { ArgParse::ArgParse() { } void ArgParse::parseArgs(int argc, const char** argv) { for(int i = 0; i < argc; i++) { if(argv[i][0] == '-') { if(argv[i][1] == '-') { } else { if(checkIfHasStaticArgument(argv[i][1])) { for(uint8_t j = 0; j < static_arguments.size(); j++) { if(static_arguments[j].single == argv[i][1]) { printf("Setting...\n"); static_arguments[j].value = !static_arguments[j].value; } } } } } } } void ArgParse::addStatic(char single, const char* long_name, const char* description, bool defualt_value) { if(checkIfHasStaticArgument(single)) { return; } StaticArgument to_add; to_add.single = single; to_add.long_name = long_name; to_add.description = description; to_add.value = defualt_value; static_arguments.push_back(to_add); } bool ArgParse::checkIfHasStaticArgument(char single) { for(uint8_t i = 0; i < static_arguments.size(); i++) { if(static_arguments[i].single == single) { return true; } } return false; } bool ArgParse::getStatic(char single) { if(checkIfHasStaticArgument(single)) { for(uint8_t i = 0; i < static_arguments.size(); i++) { if(static_arguments[i].single == single) { return static_arguments[i].value; } } } return false; } } }
[ "joseph.foster118@gmail.com" ]
joseph.foster118@gmail.com
8aaa1b332e9b3d2f2ccf73f01775f9adb173e48f
0565fb5e3f12ca1aa9631e9e4fa7b7de32fd8a57
/src/solver.cpp
cfa62c34bf23d498c3ee768f974480b79397c1e2
[ "MIT" ]
permissive
naruto2/solver
28dd8487c006a1abb5736b1e898d05adda19a82a
fee58df0c24f60999e356d0346197bd53001c3dc
refs/heads/master
2022-09-23T01:10:40.427496
2020-05-29T15:51:41
2020-05-29T15:51:41
266,781,397
3
0
null
null
null
null
UTF-8
C++
false
false
2,079
cpp
#include <cuda_runtime.h> #include <cusolverDn.h> #include <cassert> #include <vector> #include <map> #include "matrix.hpp" using namespace std; template<typename T> inline size_t bytesof(unsigned int s) { return s * sizeof(T); } template<typename T> T* allocate(unsigned int size) { T* result = nullptr; cudaError_t status = cudaMalloc(&result, bytesof<T>(size)); assert( status == cudaSuccess ); return result; } static void Host2Device(double *h, double *d, unsigned int n) { cudaMemcpy(h, d, bytesof<double>(n), cudaMemcpyHostToDevice); } static void Device2Host(double *h, double *d, unsigned int n) { cudaMemcpy(h, d, bytesof<double>(n), cudaMemcpyDeviceToHost); } int solver(matrix<double>&A, vector<double>&x, const vector<double> &b) { static cusolverDnHandle_t handle; static cusolverStatus_t status; static double *a, *dA, *dB, *workspace; static int n, nrhs, lda, worksize, *pivot, *devInfo, init=1; if (init) { status = cusolverDnCreate(&handle); init =0; } n = A.size(); nrhs = 1; lda = n; dA = allocate<double>(n*n); dB = allocate<double>(n*nrhs); pivot = allocate<int>(n); devInfo = allocate<int>(1); a = (double*)calloc(n*n,sizeof(double)); if ( a == NULL ) { fprintf(stderr,"can't malloc\n"); abort(); } for (int i=0; i<n; i++ ) { auto Ai = A[i]; auto j = Ai.begin(); for ( ; j != Ai.end(); j++ ) a[i*n+j->first] = A[i][j->first]; } Host2Device(dA,a,n*n); status = cusolverDnDgetrf_bufferSize( handle, n, n, dA, lda, &worksize); workspace = allocate<double>(worksize); status = cusolverDnDgetrf( handle, n, n, dA, lda, workspace, pivot, devInfo); Host2Device(dB, (double*)&b[0], n*nrhs); status = cusolverDnDgetrs( handle, CUBLAS_OP_T, n, nrhs, dA, lda, pivot, dB, n, devInfo); x.resize(n); Device2Host((double*)&x[0], dB, n*nrhs); cudaFree(dA); cudaFree(dB); cudaFree(devInfo); cudaFree(pivot); cudaFree(workspace); //cudaDeviceReset(); free(a); return 0; }
[ "tsukuda.yoshio@gmail.com" ]
tsukuda.yoshio@gmail.com
2079bec15a3245eedce0c3c4f88e74a62ad26bc1
20843378ddcf65af0033371052885267ff637b0c
/1A/NOWCODER/technique/RotateMatrix.cpp
4d6ffef2d5f81d75dd89cd198a7e02cb57bc89dd
[]
no_license
axhiao/myleet
40a35794f56016565d2005c61fa457264b984eaf
02979f51476aae702c77358b0e308c42ffd6b7a0
refs/heads/master
2021-01-22T09:10:31.918330
2015-09-02T09:06:34
2015-09-02T09:06:34
32,560,409
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
#include <iostream> #include <vector> using namespace std; void printMatrix(vector<vector<int> > &matrix) { for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[i].size(); j++) { cout << matrix[i][j] << " "; } cout << endl; } } void rotateEdgeOfMatrix(vector<vector<int> > &matrix, int tR, int tC, int dR, int dC) { int times = dC - tC; for (int i = 0; i < times; i++) { int tmp = matrix[tR][tC+i]; matrix[tR][tC+i] = matrix[dR-i][tC]; matrix[dR-i][tC] = matrix[dR][dC-i]; matrix[dR][dC-i] = matrix[tR+i][dC]; matrix[tR+i][dC] = tmp; } } void rotateMatrix(vector<vector<int> > &matrix) { int tR = 0; int tC = 0; int dR = matrix.size()-1; int dC = matrix[0].size()-1; while (tR < dR) { rotateEdgeOfMatrix(matrix,tR++, tC++, dR--, dC--); } } int main() { int row = 4; int col = 4; vector<vector<int> > matrix(row); int t1[] = {1, 2, 3, 4}; int t2[] = {5, 6, 7, 8}; int t3[] = {9, 10, 11, 12}; int t4[] = {13, 14, 15, 16}; matrix[0].assign(t1, t1+col); matrix[1].assign(t2, t2+col); matrix[2].assign(t3, t3+col); matrix[3].assign(t4, t4+col); printMatrix(matrix); rotateMatrix(matrix); cout << "==============" << endl; printMatrix(matrix); return 0; }
[ "axhiao@gmail.com" ]
axhiao@gmail.com
945869403bef1d086c0d9f0ae4457a80190243c4
6d54a7b26d0eb82152a549a6a9dfde656687752c
/src/lib/support/ZclString.cpp
3482cd430323bf384ac7ce21a5a7a647d39b917c
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
project-chip/connectedhomeip
81a123d675cf527773f70047d1ed1c43be5ffe6d
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
refs/heads/master
2023-09-01T11:43:37.546040
2023-09-01T08:01:32
2023-09-01T08:01:32
244,694,174
6,409
1,789
Apache-2.0
2023-09-14T20:56:31
2020-03-03T17:05:10
C++
UTF-8
C++
false
false
1,559
cpp
/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ZclString.h" namespace chip { // ZCL strings are stored as pascal-strings (first byte contains the length of // the data), and a length of 255 means "invalid string" so the maximum actually // allowed string length is 254. constexpr size_t kBufferMaximumSize = 254; CHIP_ERROR MakeZclCharString(MutableByteSpan & buffer, const char * cString) { CHIP_ERROR err = CHIP_NO_ERROR; if (buffer.size() == 0) { // We can't even put a 0 length in there. return CHIP_ERROR_INBOUND_MESSAGE_TOO_BIG; } size_t len = strlen(cString); size_t availableStorage = min(buffer.size() - 1, kBufferMaximumSize); if (len > availableStorage) { buffer.data()[0] = 0; return CHIP_ERROR_INBOUND_MESSAGE_TOO_BIG; } buffer.data()[0] = static_cast<uint8_t>(len); memcpy(&buffer.data()[1], cString, len); return err; } } // namespace chip
[ "noreply@github.com" ]
noreply@github.com
1f9263af0be8147b3d109f74a2756c25e4499086
27b2055835499bb13022f64cb4c893b4988ecda7
/keyvi/tests/keyvi/util/active_object_test.cpp
4b97bd9c9628a7ee65b7fc1c382213ca5e0d4d38
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
subu-cliqz/keyvi-1
cf45a555692a547a61467b0d63161d77f57b5635
ee34ed3d2ccb60b88bd3ddcd7b2c2f96509d6931
refs/heads/master
2020-12-20T08:04:52.529276
2020-01-24T14:19:31
2020-01-24T14:19:31
236,009,437
0
0
Apache-2.0
2020-01-24T13:39:43
2020-01-24T13:39:43
null
UTF-8
C++
false
false
2,612
cpp
// // keyvi - A key value store. // // Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com> // // 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. // /* * active_object_test.cpp * * Created on: Dec 21, 2017 * Author: hendrik */ #include <chrono> //NOLINT #include <sstream> #include <thread> //NOLINT #include <boost/test/unit_test.hpp> #include "keyvi/util/active_object.h" namespace keyvi { namespace util { BOOST_AUTO_TEST_SUITE(ActiveObjectTests) void ScheduledTask(size_t* calls) { ++*calls; } BOOST_AUTO_TEST_CASE(scheduledtasktimingemptyqueue) { std::ostringstream string_stream; std::chrono::system_clock::time_point last_call; size_t calls = 0; { ActiveObject<std::ostringstream> wrapped_stream(&string_stream, std::bind(ScheduledTask, &calls), std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } BOOST_CHECK(calls > 7); BOOST_CHECK(calls < 11 + 1); } BOOST_AUTO_TEST_CASE(scheduledtasktimingfullqueue) { std::ostringstream string_stream; std::chrono::system_clock::time_point last_call; size_t calls = 0; auto start_time = std::chrono::high_resolution_clock::now(); { ActiveObject<std::ostringstream> wrapped_stream(&string_stream, std::bind(ScheduledTask, &calls), std::chrono::milliseconds(8)); for (size_t i = 0; i < 15000; ++i) { wrapped_stream([i](std::ostream& o) { o << "Hello world" << i << std::endl; }); if (i % 50 == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } auto end_time = std::chrono::high_resolution_clock::now(); size_t duration = std::chrono::duration<double, std::milli>(end_time - start_time).count(); size_t expected_min_calls = (duration / 8) > 5 ? ((duration - duration / 10) / 8) - 5 : 0; BOOST_CHECK(expected_min_calls > 0); BOOST_CHECK(calls > expected_min_calls); BOOST_CHECK(calls < (duration / 8) + 1 + 1); } BOOST_AUTO_TEST_SUITE_END() } /* namespace util */ } /* namespace keyvi */
[ "noreply@github.com" ]
noreply@github.com
33b18af73d114fdff365711fbee99820c6e5b54e
05dc072c08c26439dd687e9a5fcdb27562107678
/JetsonNano/MJPEGWriter.cpp
d0081cc1bf341d3e3f4d23a64586daa3514464cb
[]
no_license
4mbilal/AI_NEOM_RemoteReality
b4dc6647d5cac9f55ddfac583f2022d5638d6cc5
eb6a6c99daae24ed34b290346f83c36c29344a8d
refs/heads/master
2022-12-11T16:14:11.654872
2020-09-07T18:09:28
2020-09-07T18:09:28
293,587,252
0
0
null
null
null
null
UTF-8
C++
false
false
4,637
cpp
#include "MJPEGWriter.h" #include <fstream> void MJPEGWriter::Listener() { // send http header std::string header; header += "HTTP/1.0 200 OK\r\n"; header += "Cache-Control: no-cache\r\n"; header += "Pragma: no-cache\r\n"; header += "Connection: close\r\n"; header += "Content-Type: multipart/x-mixed-replace; boundary=mjpegstream\r\n\r\n"; const int header_size = header.size(); char* header_data = (char*)header.data(); fd_set rread; SOCKET maxfd; this->open(); pthread_mutex_unlock(&mutex_writer); while (true) { rread = master; struct timeval to = { 0, timeout }; maxfd = sock + 1; if (sock == INVALID_SOCKET){ return; } int sel = select(maxfd, &rread, NULL, NULL, &to); if (sel > 0) { for (int s = 0; s < maxfd; s++) { if (FD_ISSET(s, &rread) && s == sock) { int addrlen = sizeof(SOCKADDR); SOCKADDR_IN address = { 0 }; SOCKET client = accept(sock, (SOCKADDR*)&address, (socklen_t*)&addrlen); if (client == SOCKET_ERROR) { cerr << "error : couldn't accept connection on sock " << sock << " !" << endl; return; } maxfd = (maxfd>client ? maxfd : client); pthread_mutex_lock(&mutex_cout); cout << "new client " << client << endl; char headers[4096] = "\0"; int readBytes = _read(client, headers); cout << headers; pthread_mutex_unlock(&mutex_cout); pthread_mutex_lock(&mutex_client); _write(client, header_data, header_size); clients.push_back(client); pthread_mutex_unlock(&mutex_client); } } } usleep(1000); } } void MJPEGWriter::Writer() { pthread_mutex_lock(&mutex_writer); pthread_mutex_unlock(&mutex_writer); const int milis2wait = 100000;//16666; while (this->isOpened()) { pthread_mutex_lock(&mutex_client); int num_connected_clients = clients.size(); pthread_mutex_unlock(&mutex_client); if (!num_connected_clients) { usleep(milis2wait); continue; } pthread_t threads[NUM_CONNECTIONS]; int count = 0; std::vector<uchar> outbuf; std::vector<int> params; params.push_back(cv::IMWRITE_JPEG_QUALITY); params.push_back(quality); //Wait for the fresh frame to be captured while(!frame_updated); frame_updated = false; pthread_mutex_lock(&mutex_writer); imencode(".jpg", lastFrame, outbuf, params); pthread_mutex_unlock(&mutex_writer); int outlen = outbuf.size(); pthread_mutex_lock(&mutex_client); std::vector<int>::iterator begin = clients.begin(); std::vector<int>::iterator end = clients.end(); pthread_mutex_unlock(&mutex_client); std::vector<clientPayload*> payloads; for (std::vector<int>::iterator it = begin; it != end; ++it, ++count) { if (count > NUM_CONNECTIONS) break; struct clientPayload *cp = new clientPayload({ (MJPEGWriter*)this, { outbuf.data(), outlen, *it } }); payloads.push_back(cp); pthread_create(&threads[count], NULL, &MJPEGWriter::clientWrite_Helper, cp); } for (; count > 0; count--) { pthread_join(threads[count-1], NULL); delete payloads.at(count-1); } usleep(milis2wait); } } void MJPEGWriter::ClientWrite(clientFrame & cf) { stringstream head; head << "--mjpegstream\r\nContent-Type: image/jpeg\r\nContent-Length: " << cf.outlen << "\r\n\r\n"; string string_head = head.str(); pthread_mutex_lock(&mutex_client); _write(cf.client, (char*) string_head.c_str(), string_head.size()); int n = _write(cf.client, (char*)(cf.outbuf), cf.outlen); if (n < cf.outlen) { std::vector<int>::iterator it; it = find (clients.begin(), clients.end(), cf.client); if (it != clients.end()) { cerr << "kill client " << cf.client << endl; clients.erase(std::remove(clients.begin(), clients.end(), cf.client)); ::shutdown(cf.client, 2); } } pthread_mutex_unlock(&mutex_client); pthread_exit(NULL); }
[ "4mbilal@gmail.com" ]
4mbilal@gmail.com
2adcbd4b102c7587135f100ca848030f5f87d4b4
54d75581d3a76d9251ceca98aa9a4c6d6f958ceb
/20160274_Practice_5_1/20160274_Practice_5_1/20160274_Practice_5_1View.h
d5b286532cf7e0dbb1ba3768d6313c7cdb95d037
[]
no_license
blackbeaver37/2019_MFC-WindowProgramming
d7b79ba9734c0a6975a0641a487a7bc29324fb83
47adfbd064fd92dc223cf5bc98fe87f75d1e1794
refs/heads/master
2023-04-16T12:40:23.491161
2021-04-28T09:14:48
2021-04-28T09:14:48
274,039,420
0
0
null
null
null
null
UHC
C++
false
false
2,870
h
// 20160274_Practice_5_1View.h : CMy20160274_Practice_5_1View 클래스의 인터페이스 // #include "atltypes.h" enum DRAW_MODE { LINE_MODE, ELLIPSE_MODE, POLYGON_MODE }; #pragma once class CMy20160274_Practice_5_1View : public CView { protected: // serialization에서만 만들어집니다. CMy20160274_Practice_5_1View(); DECLARE_DYNCREATE(CMy20160274_Practice_5_1View) // 특성입니다. public: CMy20160274_Practice_5_1Doc* GetDocument() const; // 작업입니다. public: // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현입니다. public: virtual ~CMy20160274_Practice_5_1View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() public: afx_msg void OnLine(); afx_msg void OnEllipse(); afx_msg void OnPolygon(); afx_msg void OnLineColor(); afx_msg void OnFaceColor(); afx_msg void OnBdiagonal(); afx_msg void OnCross(); afx_msg void OnVertical(); int m_nDrawMode; int m_nHatchStyle; afx_msg void OnUpdateLine(CCmdUI *pCmdUI); afx_msg void OnUpdateEllipse(CCmdUI *pCmdUI); afx_msg void OnUpdatePolygon(CCmdUI *pCmdUI); afx_msg void OnMouseMove(UINT nFlags, CPoint point); CPoint m_ptStart; // 시작점을 저장하는 변수 CPoint m_ptPrev; // 이전 점을 저장하는 변수 bool m_bFirst; // 처음 그리는 것인지 체크하는 변수 bool m_bLButtonDown; // 왼쪽 버튼이 눌렸는지 체크하는 변수 bool m_bContextMenu; // 컨텍스트 메뉴의 활성화를 체크하는 변수 bool m_bHatch; // 해치 브러시를 사용하느지를 체크하는 변수 CPoint m_ptData[50]; // 다각형의 점을 저장할 배열 int m_nCount; // m_ptData 배열의 카운트를 저장하는 변수 COLORREF m_colorPen; // 펜 색상을 설정하는 변수 COLORREF m_colorBrush; // 브러시 색상을 설정하는 변수 afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); }; #ifndef _DEBUG // 20160274_Practice_5_1View.cpp의 디버그 버전 inline CMy20160274_Practice_5_1Doc* CMy20160274_Practice_5_1View::GetDocument() const { return reinterpret_cast<CMy20160274_Practice_5_1Doc*>(m_pDocument); } #endif
[ "noreply@github.com" ]
noreply@github.com
5868948b0269859e117673aad0c1f11c91c32584
8cc3669da4acab5f59044c975c79825e5264abe4
/TGNetwork/TGEndSignatureParser.cpp
13ed92c4c3781700b138a91e5e0a61b1a0e64473
[]
no_license
zhandb/tegrenys
f9af6def3e2b57c46d1dddf2986e4a9e5df51503
d4393ff296728b105e35a8a6e90dd244c7d7c19a
refs/heads/master
2021-01-10T01:46:22.878155
2013-01-24T19:08:40
2013-01-24T19:08:40
47,877,683
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
5,322
cpp
//--------------------------------------------------------------------- #include "TGEndSignatureParser.h" #include "..\TGSystem\TGBufferPool.h" //--------------------------------------------------------------------- TGEndSignatureParser::TGEndSignatureParser(PTGModule receiver, QByteArray signature) : TGBaseDataParser(receiver) { SignatureCounter = 0; SetSignature(signature); } //--------------------------------------------------------------------- TGEndSignatureParser::~TGEndSignatureParser() { } //--------------------------------------------------------------------- void TGEndSignatureParser::OnDataReceived(TGDataFragmentList& data_fragments) { TGDataFragmentList::iterator data = data_fragments.begin(); while (data != data_fragments.end()) { int signature_bytes_count = SearchForSignature(*data); //TODO: Что если сигнатура встречается несколько раз? //TODO: Что если данных много, а сигнатуры нет? //Если сигнатура в данном фрагменте не завершена или отсутствует if (signature_bytes_count == -1) { //Сохраним весь фрагмент ParserDataList.push_back(*data); data_fragments.pop_front(); data = data_fragments.begin(); } else { //иначе сохраним часть фрагмента, завершающуюся сигнатурой ParserDataList.push_back(TGDataFragment(data->StartOffset, data->Data, signature_bytes_count)); //Уберем сигнатуру из дальнейшей обработки RemoveSignature(); //Отработаем данные и избавимся от них ProcessRequest(); ParserDataList.clear(); //Передадим рекурсивно остаток фрагмента на дальнейшую обработку int bytes_left = data->Size - signature_bytes_count; if (bytes_left > 0) { const char* c = data->Data->GetConstData() + data->StartOffset + signature_bytes_count; data->StartOffset += signature_bytes_count; data->Size = bytes_left; ReceiveData(data_fragments); } if (!data_fragments.empty()) data_fragments.pop_front(); data = data_fragments.begin(); } } } //--------------------------------------------------------------------- //void TGEndSignatureParser::ParseRequest(PTGBuffer buffer) //{ // char* data_ptr = (char*)buffer->GetConstData(); // uint32_t data_size = buffer->GetDataSize(); // // PTGTextLineRequest request = new TGTextLineRequest(); // request->RequestBuffer = buffer; // // TGTextRequestLine first_line; // first_line.TagName = data_ptr; // first_line.TagValue = NULL; // // request->RequestLines.push_back(first_line); // // for (uint32_t i = 0; i < data_size - 1; ++i) // { // if (data_ptr[i] == ':' && data_ptr[i + 1] == ' ') // { // data_ptr[i] = 0; // request->RequestLines.back().TagValue = data_ptr + (i + 2); // } // else // { // if (data_ptr[i] == '\r' && data_ptr[i + 1] == '\n') // { // data_ptr[i] = 0; // if (i < data_size - 2) // { // TGTextRequestLine line; // line.TagName = data_ptr + (i + 2); // line.TagValue = NULL; // request->RequestLines.push_back(line); // } // } // } // } // ProcessRequest(request); //} ////--------------------------------------------------------------------- void TGEndSignatureParser::ProcessRequest() { } //--------------------------------------------------------------------- void TGEndSignatureParser::SetSignature(QByteArray signature) { Signature = signature; } //--------------------------------------------------------------------- int TGEndSignatureParser::SearchForSignature(TGDataFragment data_fragment) { int res = -1; const char* data_ptr = data_fragment.Data->GetConstData() + data_fragment.StartOffset; for (uint32_t i = 0; i < data_fragment.Size; ++i) { //Если вся сигнатура собрана if (data_ptr[i] == Signature[SignatureCounter]) { SignatureCounter++; if (SignatureCounter == Signature.length()) { SignatureCounter = 0; res = i + 1; //Количество байт, включая сигнатуру } } else { SignatureCounter = 0; } } return res; } //--------------------------------------------------------------------- void TGEndSignatureParser::RemoveSignature() { uint32_t sign_counter = Signature.length(); //Удаляем с конца фрагменты данных, полностью состоящие из частей сигнатуры //Это возможно при малых размерах фрагментов или большой длине сигнатуры while (!ParserDataList.empty() && ParserDataList.back().Size <= sign_counter) { sign_counter -= ParserDataList.back().Size; ParserDataList.pop_back(); } //Уменьшаем размер последнего фрагмента данных на размер остатка сигнатуры if (!ParserDataList.empty()) ParserDataList.back().Size -= sign_counter; } //---------------------------------------------------------------------
[ "np2001@list.ru" ]
np2001@list.ru
c22d90cde1a55335abf6db8758b485d45e27c52f
4cd7f9447801592739d8b05c4f41f9f210fdb784
/src/components/html_viewer/html_document_application_delegate.cc
8638640167463b9cce2f6cacbe8d720b6d9a74d0
[ "BSD-3-Clause" ]
permissive
crash0verrid3/Firework-Browser
15fbcdcdf521f1b1a1f609310fba9a5ab520b92a
9f2e99135fa4230581bde1806ca51e484372be50
refs/heads/master
2021-01-10T13:18:41.267236
2015-10-18T23:04:10
2015-10-18T23:04:10
44,147,842
2
1
null
null
null
null
UTF-8
C++
false
false
7,067
cc
// Copyright 2015 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 "components/html_viewer/html_document_application_delegate.h" #include "base/bind.h" #include "base/command_line.h" #include "components/html_viewer/global_state.h" #include "components/html_viewer/html_document_oopif.h" #include "components/html_viewer/html_viewer_switches.h" #include "mojo/application/public/cpp/application_connection.h" #include "mojo/application/public/cpp/application_delegate.h" #include "mojo/application/public/cpp/connect.h" namespace html_viewer { namespace { bool EnableOOPIFs() { return base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kOOPIF); } HTMLDocument* CreateHTMLDocument(HTMLDocument::CreateParams* params) { return new HTMLDocument(params); } } // namespace // ServiceConnectorQueue records all incoming service requests and processes // them once PushRequestsTo() is called. This is useful if you need to delay // processing incoming service requests. class HTMLDocumentApplicationDelegate::ServiceConnectorQueue : public mojo::ServiceConnector { public: ServiceConnectorQueue() {} ~ServiceConnectorQueue() override {} void PushRequestsTo(mojo::ApplicationConnection* connection) { ScopedVector<Request> requests; requests_.swap(requests); for (Request* request : requests) { connection->GetLocalServiceProvider()->ConnectToService( request->interface_name, request->handle.Pass()); } } private: struct Request { std::string interface_name; mojo::ScopedMessagePipeHandle handle; }; // mojo::ServiceConnector: void ConnectToService(mojo::ApplicationConnection* application_connection, const std::string& interface_name, mojo::ScopedMessagePipeHandle handle) override { scoped_ptr<Request> request(new Request); request->interface_name = interface_name; request->handle = handle.Pass(); requests_.push_back(request.Pass()); } ScopedVector<Request> requests_; DISALLOW_COPY_AND_ASSIGN(ServiceConnectorQueue); }; HTMLDocumentApplicationDelegate::HTMLDocumentApplicationDelegate( mojo::InterfaceRequest<mojo::Application> request, mojo::URLResponsePtr response, GlobalState* global_state, scoped_ptr<mojo::AppRefCount> parent_app_refcount) : app_(this, request.Pass(), base::Bind(&HTMLDocumentApplicationDelegate::OnTerminate, base::Unretained(this))), parent_app_refcount_(parent_app_refcount.Pass()), url_(response->url), initial_response_(response.Pass()), global_state_(global_state), html_document_creation_callback_(base::Bind(CreateHTMLDocument)) { } HTMLDocumentApplicationDelegate::~HTMLDocumentApplicationDelegate() { // Deleting the documents is going to trigger a callback to // OnHTMLDocumentDeleted() and remove from |documents_|. Copy the set so we // don't have to worry about the set being modified out from under us. std::set<HTMLDocument*> documents(documents_); for (HTMLDocument* doc : documents) doc->Destroy(); DCHECK(documents_.empty()); std::set<HTMLDocumentOOPIF*> documents2(documents2_); for (HTMLDocumentOOPIF* doc : documents2) doc->Destroy(); DCHECK(documents2_.empty()); } void HTMLDocumentApplicationDelegate::SetHTMLDocumentCreationCallback( const HTMLDocumentCreationCallback& callback) { html_document_creation_callback_ = callback; } // Callback from the quit closure. We key off this rather than // ApplicationDelegate::Quit() as we don't want to shut down the messageloop // when we quit (the messageloop is shared among multiple // HTMLDocumentApplicationDelegates). void HTMLDocumentApplicationDelegate::OnTerminate() { delete this; } // ApplicationDelegate; void HTMLDocumentApplicationDelegate::Initialize(mojo::ApplicationImpl* app) { mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = mojo::String::From("mojo:network_service"); mojo::ApplicationConnection* connection = app_.ConnectToApplication(request.Pass()); connection->ConnectToService(&network_service_); connection->ConnectToService(&url_loader_factory_); } bool HTMLDocumentApplicationDelegate::ConfigureIncomingConnection( mojo::ApplicationConnection* connection) { if (initial_response_) { OnResponseReceived(mojo::URLLoaderPtr(), connection, nullptr, initial_response_.Pass()); } else { // HTMLDocument provides services, but is created asynchronously. Queue up // requests until the HTMLDocument is created. scoped_ptr<ServiceConnectorQueue> service_connector_queue( new ServiceConnectorQueue); connection->SetServiceConnector(service_connector_queue.get()); mojo::URLLoaderPtr loader; url_loader_factory_->CreateURLLoader(GetProxy(&loader)); mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = url_; request->auto_follow_redirects = true; // |loader| will be passed to the OnResponseReceived method through a // callback. Because order of evaluation is undefined, a reference to the // raw pointer is needed. mojo::URLLoader* raw_loader = loader.get(); raw_loader->Start( request.Pass(), base::Bind(&HTMLDocumentApplicationDelegate::OnResponseReceived, base::Unretained(this), base::Passed(&loader), connection, base::Passed(&service_connector_queue))); } return true; } void HTMLDocumentApplicationDelegate::OnHTMLDocumentDeleted( HTMLDocument* document) { DCHECK(documents_.count(document) > 0); documents_.erase(document); } void HTMLDocumentApplicationDelegate::OnHTMLDocumentDeleted2( HTMLDocumentOOPIF* document) { DCHECK(documents2_.count(document) > 0); documents2_.erase(document); } void HTMLDocumentApplicationDelegate::OnResponseReceived( mojo::URLLoaderPtr loader, mojo::ApplicationConnection* connection, scoped_ptr<ServiceConnectorQueue> connector_queue, mojo::URLResponsePtr response) { // HTMLDocument is destroyed when the hosting view is destroyed, or // explicitly from our destructor. if (EnableOOPIFs()) { HTMLDocumentOOPIF* document = new HTMLDocumentOOPIF( &app_, connection, response.Pass(), global_state_, base::Bind(&HTMLDocumentApplicationDelegate::OnHTMLDocumentDeleted2, base::Unretained(this))); documents2_.insert(document); } else { HTMLDocument::CreateParams params( &app_, connection, response.Pass(), global_state_, base::Bind(&HTMLDocumentApplicationDelegate::OnHTMLDocumentDeleted, base::Unretained(this))); HTMLDocument* document = html_document_creation_callback_.Run(&params); documents_.insert(document); } if (connector_queue) { connector_queue->PushRequestsTo(connection); connection->SetServiceConnector(nullptr); } } } // namespace html_viewer
[ "sasha@sasha-kaidalov" ]
sasha@sasha-kaidalov
3e7642e7b4fd2b455b3059b9224782d389b62811
a44380d820109813649f95651eea8590e8fd2f26
/OSX/exemples/UartPrbsTest/UartPrbsTest/main.cpp
aaccbcefb536ca4a0c5e008654d0cbd65427007f
[ "BSD-3-Clause" ]
permissive
I-SYST/EHAL
1e8bce9083085bba75aae2314f80310a4925d815
b1459e8dba9eeebed13f19a4b3d376603f325495
refs/heads/master
2022-05-14T12:59:44.041952
2022-03-06T04:48:21
2022-03-06T04:48:21
19,235,514
98
25
BSD-3-Clause
2019-01-30T10:52:08
2014-04-28T10:48:51
C
UTF-8
C++
false
false
4,698
cpp
/*-------------------------------------------------------------------------- File : main.cpp Author : Hoang Nguyen Hoan Aug. 31, 2016 Desc : UART PRBS test Demo code using EHAL library to do PRBS transmit test using UART Copyright (c) 2016, I-SYST inc., all rights reserved Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies, and none of the names : I-SYST or its contributors may be used to endorse or promote products derived from this software without specific prior written permission. For info or contributing contact : hnhoan at i-syst dot com THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- Modified by Date Description ----------------------------------------------------------------------------*/ #include <stdio.h> #include <stdint.h> #include <string.h> #include <chrono> #include <time.h> #include "coredev/uart.h" #include "prbs.h" char s_DevPath[] = {"/dev/cu.usbmodem00304160000942"}; // UART configuration data const UARTCFG g_UartCfg = { .DevNo = 0, .pIoMap = s_DevPath, .IoMapLen = static_cast<int>(strlen(s_DevPath)), .Rate = 1000000, // Rate .DataBits = 8, .Parity = UART_PARITY_NONE, .StopBits = 1, // Stop bit .FlowControl = UART_FLWCTRL_NONE, .bIntMode = true, .IntPrio = 1, // use APP_IRQ_PRIORITY_LOW with Softdevice .EvtCallback = nullptr, .bFifoBlocking = true, // fifo blocking mode .RxMemSize = 0, .pRxMem = NULL, .TxMemSize = 0,//FIFOSIZE, .pTxMem = NULL,//g_TxBuff, .bDMAMode = true, }; #define DEMO_C #ifdef DEMO_C // For C UARTDEV g_UartDev; #else // For C++ // UART object instance UART g_Uart; #endif // // Print a greeting message on standard output and exit. // // On embedded platforms this might require semi-hosting or similar.g // // For example, for toolchains derived from GNU Tools for Embedded, // to enable semi-hosting, the following was added to the linker: // // --specs=rdimon.specs -Wl,--start-group -lgcc -lc -lc -lm -lrdimon -Wl,--end-group // // Adjust it for other toolchains. // int main() { bool res; #ifdef DEMO_C res = UARTInit(&g_UartDev, &g_UartCfg); #else res = g_Uart.Init(g_UartCfg); #endif uint8_t d = 0xff; uint8_t val = 0; uint32_t errcnt = 0; uint32_t cnt = 0; auto t_start = std::chrono::high_resolution_clock::now(); auto t_end = std::chrono::high_resolution_clock::now(); std::chrono::duration<float> elapse = std::chrono::duration<float>(0); t_start = std::chrono::high_resolution_clock::now(); time_t t; double e = 0.0; bool isOK = false; // do { #ifdef DEMO_C while (UARTRx(&g_UartDev, &d, 1) <= 0); #else while (g_Uart.Rx(&d, 1) <= 0); #endif if (val == d) isOK = true; val = Prbs8(d); // } while (!isOK); while(1) { // t_start = std::chrono::high_resolution_clock::now(); t = time(NULL); #ifdef DEMO_C while (UARTRx(&g_UartDev, &d, 1) <= 0); #else while (g_Uart.Rx(&d, 1) <= 0); #endif { e += difftime(time(NULL), t); // t_end = std::chrono::high_resolution_clock::now(); //elapse += std::chrono::duration<float>(t_end-t_start); cnt++; // If success send next code // printf("%x ", d); if (val != d) { errcnt++; // printf("PRBS %u errors %x %x\n", errcnt, val, d); } else if ((cnt & 0x7fff) == 0) { printf("PRBS rate %.3f B/s, err : %u\n", cnt / e, errcnt); // printf("PRBS rate %.3f B/s, err : %u\n", cnt / elapse.count(), errcnt); } val = Prbs8(d); } } return 0; }
[ "hnhoan@i-syst.com" ]
hnhoan@i-syst.com
abdd2442e1c19aed20cb233500d96551d738510d
579f6399b3f8238eee552b8a70b5940db894a3eb
/neizhko.vladimir/common/circle.hpp
26ff5b9421b8ce2604a5b6f1174ead7330e5fa4c
[]
no_license
a-kashirin-official/spbspu-labs-2018
9ac7b7abaa626d07497104f20f7ed7feb6359ecf
aac2bb38fe61c12114975f034b498a116e7075c3
refs/heads/master
2020-03-19T04:18:15.774227
2018-12-02T22:21:38
2018-12-02T22:21:38
135,814,536
0
0
null
null
null
null
UTF-8
C++
false
false
604
hpp
#ifndef CIRCLE_HPP #define CIRCLE_HPP #include "shape.hpp" #include "base-types.hpp" namespace neizhko { class Circle : public Shape { public: // Radius, Cords of center (x, y) Circle(double r, double x, double y); double getArea() const override; rectangle_t getFrameRect() const override; void move(point_t c) override; void move(double dx, double dy) override; void printInfo() const override; void scale(double ratio) override; double getRad() const; private: double rad_; point_t center_; }; } #endif
[ "a.kashirin.official@gmail.com" ]
a.kashirin.official@gmail.com
ca990167ce6e20af889522c9ed49a91aba3ffd64
77e5785439b395b15d8941d7cf02f9b241ea8592
/gui/geometryengine.h
ad945c62dbad819e30454891a976ac3eb0511f0a
[]
no_license
zhouhuanxiang/Demo
55fc1c0440a507ef2126efdfa658e02eb38ea238
9c49a656bb18ac1c4d0ef2091e8ce9dd2db633b7
refs/heads/master
2020-03-19T14:29:49.483354
2018-06-11T12:28:56
2018-06-11T12:28:56
136,625,669
0
1
null
null
null
null
UTF-8
C++
false
false
2,698
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef GEOMETRYENGINE_H #define GEOMETRYENGINE_H #include <QOpenGLFunctions> #include <QOpenGLShaderProgram> #include <QOpenGLBuffer> #include <QGLFormat> #include <string> #include <Eigen/Eigen> class GeometryEngine : protected QOpenGLFunctions { public: GeometryEngine(); virtual ~GeometryEngine(); void drawFaceGeometry(QOpenGLShaderProgram *program); void updateFaceGeometry(Eigen::MatrixXd &pos); void setNormal(QOpenGLShaderProgram *program); void setConstant(QOpenGLShaderProgram *program); private: QOpenGLBuffer arrayBuf; QOpenGLBuffer positionBuf; QOpenGLBuffer normalBuf; QOpenGLBuffer indexBuf; bool rendered; Eigen::VectorXf local_pos_; Eigen::VectorXf local_nor_; }; #endif // GEOMETRYENGINE_H
[ "zhouhx.cn@gmail.com" ]
zhouhx.cn@gmail.com
ef6305dd45907a83ffba6d35ff705f904438e580
a6899d323e465c8829b755cb9a7c65ed3c20e999
/test/unit/tests/actor/flow_control.cc
b62c43d6327421fdd36e23c143a419b15906b08f
[ "BSD-3-Clause" ]
permissive
superyarick/vast
71f36201deb44564208f4a2d53c447b7ac8e156f
fbf1d78356c387e5b724ae1b17996cefd183b66e
refs/heads/master
2020-07-11T10:20:08.317917
2015-10-30T18:25:19
2015-10-30T18:30:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,031
cc
#include "vast/actor/controller.h" #define SUITE actors #include "test.h" using namespace vast; namespace { behavior worker(event_based_actor* self, actor controller, actor supervisor) { auto overloads = std::make_shared<int>(0); auto underloads = std::make_shared<int>(0); return { [=](overload_atom, actor const&) { self->send(supervisor, ++*overloads); }, [=](underload_atom, actor const&) { self->send(supervisor, ++*underloads); }, [=](enable_atom, overload_atom) { self->send(message_priority::high, controller, overload_atom::value); }, [=](enable_atom, underload_atom) { self->send(message_priority::high, controller, underload_atom::value); } }; } } // namespace <anonymous> TEST(single-path flow-control) { scoped_actor self; MESSAGE("constructing data flow path A -> B -> C -> D"); auto fc = self->spawn(controller::actor); auto a = self->spawn<priority_aware>(worker, fc, self); auto b = self->spawn<priority_aware>(worker, fc, self); auto c = self->spawn<priority_aware>(worker, fc, self); auto d = self->spawn<priority_aware>(worker, fc, self); MESSAGE("registering edges with flow controller"); self->send(fc, add_atom::value, a, b); self->send(fc, add_atom::value, b, c); self->send(fc, add_atom::value, c, d); MESSAGE("overloading C"); self->send(c, enable_atom::value, overload_atom::value); self->send(c, enable_atom::value, overload_atom::value); MESSAGE("checking overload count on A"); auto i = 1; self->receive_for(i, 3)( [&](int overloads) { CHECK(self->current_sender() == a); CHECK(overloads == i); } ); MESSAGE("underloading D"); self->send(d, enable_atom::value, underload_atom::value); MESSAGE("checking underload count on A"); self->receive( [&](int underloads) { CHECK(self->current_sender() == a); CHECK(underloads == 1); } ); self->send_exit(a, exit::done); self->send_exit(b, exit::done); self->send_exit(c, exit::done); self->send_exit(d, exit::done); self->send_exit(fc, exit::done); self->await_all_other_actors_done(); } TEST(multi-path flow-control with deflectors) { scoped_actor self; MESSAGE("constructing data flow path A -> B -> C -> D"); MESSAGE("constructing data flow path E -> F -> C"); auto fc = self->spawn(controller::actor); auto a = self->spawn<priority_aware>(worker, fc, self); auto b = self->spawn<priority_aware>(worker, fc, self); auto c = self->spawn<priority_aware>(worker, fc, self); auto d = self->spawn<priority_aware>(worker, fc, self); auto e = self->spawn<priority_aware>(worker, fc, self); auto f = self->spawn<priority_aware>(worker, fc, self); MESSAGE("registering edges with flow controller"); self->send(fc, add_atom::value, a, b); self->send(fc, add_atom::value, b, c); self->send(fc, add_atom::value, c, d); self->send(fc, add_atom::value, e, f); self->send(fc, add_atom::value, f, c); MESSAGE("overloading D"); self->send(d, enable_atom::value, overload_atom::value); MESSAGE("checking overload count on A & E"); auto i = 0; self->receive_for(i, 2)( [&](int overloads) { CHECK((self->current_sender() == a || self->current_sender() == e)); CHECK(overloads == 1); } ); MESSAGE("adding deflector F"); self->send(fc, add_atom::value, deflector_atom::value, f); MESSAGE("overloading D"); self->send(d, enable_atom::value, overload_atom::value); MESSAGE("checking overload count on A & F"); self->receive( [&](int overloads) { CHECK(self->current_sender() == f); CHECK(overloads == 1); } ); self->receive( [&](int overloads) { CHECK(self->current_sender() == a); CHECK(overloads == 2); } ); self->send_exit(a, exit::done); self->send_exit(b, exit::done); self->send_exit(c, exit::done); self->send_exit(d, exit::done); self->send_exit(e, exit::done); self->send_exit(f, exit::done); self->send_exit(fc, exit::done); self->await_all_other_actors_done(); }
[ "vallentin@icir.org" ]
vallentin@icir.org
dd7363a54b71d2b947c77d3ceda4a8fad4176b3b
c9e1e726f2be799ba77d4b57b038a9534d24b951
/LCD_Ultrasonic.ino
c6f61700d76a245b73ccffe4fb2e8fcb650e9431
[]
no_license
planer-pro/Ultrasonic-range-meter
3358467e0f2cc2de4d080dec53206e5c6008dc3f
af054e96a61ebc2561676b9a4d1f013871f79258
refs/heads/master
2021-01-17T09:45:42.767702
2017-03-05T18:27:13
2017-03-05T18:27:13
83,992,290
0
0
null
null
null
null
UTF-8
C++
false
false
1,482
ino
#include <Wire.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x20 for a 16 chars and 2 line display #define trigPin 10 #define echoPin 11 #define noCounts 4 unsigned int distance, distanceOut, distanceOutOld; unsigned long startAfter100ms; unsigned long startAfter400ms; void setup() { lcd.init(); lcd.backlight(); lcd.print("RangeFinder v.1.0"); delay(2000); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { if (millis() >= startAfter100ms) { int distance = GetDistance(); startAfter100ms = millis() + 100; } if (millis() >= startAfter400ms) { if (distanceOut >= 4 && distanceOut <= 400) { if (distanceOut != distanceOutOld) { lcd.clear(); lcd.print("Distance is:"); lcd.setCursor(8, 2); lcd.print(distanceOut); lcd.print(" cm"); distanceOutOld = distanceOut; startAfter400ms = millis() + 400; } } else { lcd.clear(); lcd.print("Distance is:"); lcd.setCursor(2, 2); lcd.print("Out of Range!!!"); distanceOutOld = distanceOut; startAfter400ms = millis() + 400; } } } int GetDistance() { for (int i = 0; i < noCounts; i++) { digitalWrite(trigPin, HIGH); delayMicroseconds(1000); digitalWrite(trigPin, LOW); int duration = pulseIn(echoPin, HIGH); distance = duration/58; //distance = (duration/2) / 29.1; delayMicroseconds(1000); distanceOut += distance; } distanceOut /= noCounts; return distanceOut; }
[ "planer.reg@gmail.com" ]
planer.reg@gmail.com
5403efc433f5a7de31579ee0d783815adedcc933
98a112e0577d63a48fd826d14d00420e58479a03
/ejercicios/sensor_bme280/sensor_bme280.ino
4667bf28c712b65b5fecc9d587095eedfad86401
[]
no_license
mundostr/itec_arduino2019_c1
d22b823d30f75ba9577a0707c51cde087761ba65
8bd0812b6a37f9acf090603c9955634a2f1e7e63
refs/heads/master
2020-05-19T03:24:49.802004
2020-02-17T12:25:21
2020-02-17T12:25:21
184,799,627
0
0
null
null
null
null
UTF-8
C++
false
false
639
ino
#include <Wire.h> #include <BME280I2C.h> BME280I2C bme; void sensarBME280() { float temp(NAN), hum(NAN), pres(NAN); BME280::TempUnit tempUnit(BME280::TempUnit_Celsius); BME280::PresUnit presUnit(BME280::PresUnit_hPa); bme.read(pres, temp, hum, tempUnit, presUnit); Serial.println("T: " + String(temp)); Serial.println("P: " + String(pres)); Serial.println("H: " + String(hum)); } void setup() { Serial.begin(38400); Wire.begin(); while (!bme.begin()) { Serial.println("No se detecta el sensor BME280"); delay(1000); } } void loop() { sensarBME280(); delay(1000); }
[ "idux.net@gmail.com" ]
idux.net@gmail.com
9d856f21f827b746a3a2ccaf3d42785ba1623175
438fdcf2cbc55ceb7383b5b09b99ab24be1cce49
/3rdparty/qtcreator/utils/styledbar.h
426e6e08407e3eb56d927150b43184bf15deaf24
[]
no_license
Squirtle/lazy-newb-pack-qt
1e900bab8a3c39e273fe8a49073e04c325563e09
cddbf5bacaaf05b7f8b9dcc4290c0d481b3bddd4
refs/heads/master
2020-05-19T13:19:13.535807
2012-08-26T22:48:25
2012-08-26T22:48:25
3,108,045
3
1
null
null
null
null
UTF-8
C++
false
false
1,860
h
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #ifndef STYLEDBAR_H #define STYLEDBAR_H #include <QtGui/QWidget> namespace Utils { class StyledBar : public QWidget { Q_OBJECT public: StyledBar(QWidget *parent = 0); void setSingleRow(bool singleRow); bool isSingleRow() const; void setLightColored(bool lightColored); bool isLightColored() const; protected: void paintEvent(QPaintEvent *event); }; class StyledSeparator : public QWidget { Q_OBJECT public: StyledSeparator(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; } // Utils #endif // STYLEDBAR_H
[ "unnamedrambler@gmail.com" ]
unnamedrambler@gmail.com
6e035058551a32f8bd6c5fb9228733e576dc9937
20ae4729e04db70c879b2dba631dc5ceb0703147
/dtimelimiter.h
d9a5a386327a92e848332fff4281154901f102ba
[]
no_license
damir00/burningskids
dbaa4dff37780b01deb4846cf1e9ef2c8acc5d7b
fb9b98dcc004634b9d54b2e045ca7a154716b481
refs/heads/master
2020-06-06T07:14:51.269458
2014-10-20T09:28:39
2014-10-20T09:28:39
25,458,862
0
0
null
null
null
null
UTF-8
C++
false
false
391
h
#ifndef _DTIMELIMITER_H_ #define _DTIMELIMITER_H_ #include <sys/time.h> #include <time.h> #include <unistd.h> class DTimeLimiter { struct timeval mtime; long prev_tick; long current_tick; long delta; long getTime(); public: long min_delta; DTimeLimiter(); DTimeLimiter(long min_delta); void firstMark(); void mark(); void wait(); long getDelta(); //nanoseconds }; #endif
[ "damir.srpcic@gmail.com" ]
damir.srpcic@gmail.com
312d869edbc38517ab9822b4707f5c881dd89b7f
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/multiprecision/cpp_int.hpp
e55313a9dba49995e9924c7751b4d315c6636b02
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
102,330
hpp
//////////////////3///////////////////////////////////////////// // Copyright 2012 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_MP_CPP_INT_HPP #define BOOST_MP_CPP_INT_HPP #include <iostream> #include <iomanip> #include <type_traits> #include <cstdint> #include <boost/multiprecision/detail/endian.hpp> #include <boost/multiprecision/number.hpp> #include <boost/multiprecision/detail/integer_ops.hpp> #include <boost/multiprecision/detail/rebind.hpp> #include <boost/core/empty_value.hpp> #include <boost/multiprecision/cpp_int/cpp_int_config.hpp> #include <boost/multiprecision/rational_adaptor.hpp> #include <boost/multiprecision/traits/is_byte_container.hpp> #include <boost/integer/static_min_max.hpp> #include <boost/multiprecision/cpp_int/checked.hpp> #include <boost/multiprecision/detail/constexpr.hpp> #include <boost/multiprecision/cpp_int/value_pack.hpp> namespace boost { namespace multiprecision { namespace backends { #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable : 4307) // integral constant overflow (oveflow is in a branch not taken when it would overflow) #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4702) // Unreachable code (reachability depends on template params) #endif template <unsigned MinBits = 0, unsigned MaxBits = 0, boost::multiprecision::cpp_integer_type SignType = signed_magnitude, cpp_int_check_type Checked = unchecked, class Allocator = typename std::conditional<MinBits && (MinBits == MaxBits), void, std::allocator<limb_type> >::type> struct cpp_int_backend; } // namespace backends namespace detail { template <unsigned MinBits, unsigned MaxBits, boost::multiprecision::cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct is_byte_container<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > : public std::false_type {}; } // namespace detail namespace backends { template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator, bool trivial = false> struct cpp_int_base; // // Traits class determines the maximum and minimum precision values: // template <class T> struct max_precision; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct max_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > { static constexpr const unsigned value = std::is_void<Allocator>::value ? static_unsigned_max<MinBits, MaxBits>::value : (((MaxBits >= MinBits) && MaxBits) ? MaxBits : UINT_MAX); }; template <class T> struct min_precision; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct min_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > { static constexpr const unsigned value = (std::is_void<Allocator>::value ? static_unsigned_max<MinBits, MaxBits>::value : MinBits); }; // // Traits class determines whether the number of bits precision requested could fit in a native type, // we call this a "trivial" cpp_int: // template <class T> struct is_trivial_cpp_int { static constexpr const bool value = false; }; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > { using self = cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>; static constexpr const bool value = std::is_void<Allocator>::value && (max_precision<self>::value <= (sizeof(double_limb_type) * CHAR_BIT) - (SignType == signed_packed ? 1 : 0)); }; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct is_trivial_cpp_int<cpp_int_base<MinBits, MaxBits, SignType, Checked, Allocator, true> > { static constexpr const bool value = true; }; } // namespace backends // // Traits class to determine whether a cpp_int_backend is signed or not: // template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct is_unsigned_number<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > : public std::integral_constant<bool, (SignType == unsigned_magnitude) || (SignType == unsigned_packed)> {}; namespace backends { // // Traits class determines whether T should be implicitly convertible to U, or // whether the constructor should be made explicit. The latter happens if we // are losing the sign, or have fewer digits precision in the target type: // template <class T, class U> struct is_implicit_cpp_int_conversion; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> struct is_implicit_cpp_int_conversion<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>, cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> > { using t1 = cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> ; using t2 = cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>; static constexpr const bool value = (is_signed_number<t2>::value || !is_signed_number<t1>::value) && (max_precision<t1>::value <= max_precision<t2>::value); }; // // Traits class to determine whether operations on a cpp_int may throw: // template <class T> struct is_non_throwing_cpp_int : public std::integral_constant<bool, false> {}; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType> struct is_non_throwing_cpp_int<cpp_int_backend<MinBits, MaxBits, SignType, unchecked, void> > : public std::integral_constant<bool, true> {}; // // Traits class, determines whether the cpp_int is fixed precision or not: // template <class T> struct is_fixed_precision; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct is_fixed_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > : public std::integral_constant<bool, max_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value != UINT_MAX> {}; namespace detail { inline BOOST_MP_CXX14_CONSTEXPR void verify_new_size(unsigned new_size, unsigned min_size, const std::integral_constant<int, checked>&) { if (new_size < min_size) BOOST_THROW_EXCEPTION(std::overflow_error("Unable to allocate sufficient storage for the value of the result: value overflows the maximum allowable magnitude.")); } inline BOOST_MP_CXX14_CONSTEXPR void verify_new_size(unsigned /*new_size*/, unsigned /*min_size*/, const std::integral_constant<int, unchecked>&) {} template <class U> inline BOOST_MP_CXX14_CONSTEXPR void verify_limb_mask(bool b, U limb, U mask, const std::integral_constant<int, checked>&) { // When we mask out "limb" with "mask", do we loose bits? If so it's an overflow error: if (b && (limb & ~mask)) BOOST_THROW_EXCEPTION(std::overflow_error("Overflow in cpp_int arithmetic: there is insufficient precision in the target type to hold all of the bits of the result.")); } template <class U> inline BOOST_MP_CXX14_CONSTEXPR void verify_limb_mask(bool /*b*/, U /*limb*/, U /*mask*/, const std::integral_constant<int, unchecked>&) {} } // namespace detail // // Now define the various data layouts that are possible as partial specializations of the base class, // starting with the default arbitrary precision signed integer type: // template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> struct cpp_int_base<MinBits, MaxBits, signed_magnitude, Checked, Allocator, false> : private boost::empty_value<typename detail::rebind<limb_type, Allocator>::type> { template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, bool trivial2> friend struct cpp_int_base; using allocator_type = typename detail::rebind<limb_type, Allocator>::type; using limb_pointer = typename std::allocator_traits<allocator_type>::pointer ; using const_limb_pointer = typename std::allocator_traits<allocator_type>::const_pointer; using checked_type = std::integral_constant<int, Checked>; // // Interface invariants: // static_assert(!std::is_void<Allocator>::value, "Allocator must not be void here"); using base_type = boost::empty_value<allocator_type>; private: struct limb_data { unsigned capacity; limb_pointer data; }; public: static constexpr unsigned limb_bits = sizeof(limb_type) * CHAR_BIT; static constexpr limb_type max_limb_value = ~static_cast<limb_type>(0u); static constexpr limb_type sign_bit_mask = static_cast<limb_type>(1u) << (limb_bits - 1); static constexpr unsigned internal_limb_count = MinBits ? (MinBits / limb_bits + ((MinBits % limb_bits) ? 1 : 0)) : (sizeof(limb_data) / sizeof(limb_type)) > 1 ? (sizeof(limb_data) / sizeof(limb_type)) : 2; private: union data_type { limb_data ld; limb_type la[internal_limb_count]; limb_type first; double_limb_type double_first; constexpr data_type() noexcept : first(0) {} constexpr data_type(limb_type i) noexcept : first(i) {} constexpr data_type(signed_limb_type i) noexcept : first(i < 0 ? static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(i)) : i) {} #if BOOST_MP_ENDIAN_LITTLE_BYTE constexpr data_type(double_limb_type i) noexcept : double_first(i) {} constexpr data_type(signed_double_limb_type i) noexcept : double_first(i < 0 ? static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) : i) {} #endif #if !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX) && !(defined(BOOST_MSVC) && (BOOST_MSVC < 1900)) constexpr data_type(limb_type* limbs, unsigned len) noexcept : ld{ len, limbs } {} #else constexpr data_type(limb_type* limbs, unsigned len) noexcept { ld.capacity = len; ld.data = limbs; } #endif }; data_type m_data; unsigned m_limbs; bool m_sign, m_internal, m_alias; public: // // Direct construction: // BOOST_MP_FORCEINLINE constexpr cpp_int_base(limb_type i) noexcept : m_data(i), m_limbs(1), m_sign(false), m_internal(true), m_alias(false) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(signed_limb_type i) noexcept : m_data(i), m_limbs(1), m_sign(i < 0), m_internal(true), m_alias(false) {} #if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE) BOOST_MP_FORCEINLINE constexpr cpp_int_base(double_limb_type i) noexcept : m_data(i), m_limbs(i > max_limb_value ? 2 : 1), m_sign(false), m_internal(true), m_alias(false) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(signed_double_limb_type i) noexcept : m_data(i), m_limbs(i < 0 ? (static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) > static_cast<double_limb_type>(max_limb_value) ? 2 : 1) : (i > max_limb_value ? 2 : 1)), m_sign(i < 0), m_internal(true), m_alias(false) {} #endif // // Aliasing constructor aliases data: // struct scoped_shared_storage : private boost::empty_value<allocator_type> { private: limb_type* data; unsigned capacity; unsigned allocated; bool is_alias; allocator_type& allocator() noexcept { return boost::empty_value<allocator_type>::get(); } public: scoped_shared_storage(const allocator_type& a, unsigned len) : boost::empty_value<allocator_type>(boost::empty_init_t(), a), capacity(len), allocated(0), is_alias(false) { data = allocator().allocate(len); } scoped_shared_storage(const cpp_int_base& i, unsigned len) : boost::empty_value<allocator_type>(boost::empty_init_t(), i.allocator()), capacity(len), allocated(0), is_alias(false) { data = allocator().allocate(len); } scoped_shared_storage(limb_type* limbs, unsigned n) : data(limbs), capacity(n), allocated(0), is_alias(true) {} ~scoped_shared_storage() { if(!is_alias) allocator().deallocate(data, capacity); } limb_type* allocate(unsigned n) noexcept { limb_type* result = data + allocated; allocated += n; BOOST_ASSERT(allocated <= capacity); return result; } void deallocate(unsigned n) { BOOST_ASSERT(n <= allocated); allocated -= n; } }; explicit constexpr cpp_int_base(limb_type* data, unsigned offset, unsigned len) noexcept : m_data(data + offset, len), m_limbs(len), m_sign(false), m_internal(false), m_alias(true) {} // This next constructor is for constructing const objects from const limb_type*'s only. // Unfortunately we appear to have no way to assert that within the language, and the const_cast // is a side effect of that :( explicit constexpr cpp_int_base(const limb_type* data, unsigned offset, unsigned len) noexcept : m_data(const_cast<limb_type*>(data) + offset, len), m_limbs(len), m_sign(false), m_internal(false), m_alias(true) {} explicit cpp_int_base(scoped_shared_storage& data, unsigned len) noexcept : m_data(data.allocate(len), len), m_limbs(len), m_sign(false), m_internal(false), m_alias(true) {} // // Helper functions for getting at our internal data, and manipulating storage: // BOOST_MP_FORCEINLINE allocator_type& allocator() noexcept { return base_type::get(); } BOOST_MP_FORCEINLINE const allocator_type& allocator() const noexcept { return base_type::get(); } BOOST_MP_FORCEINLINE unsigned size() const noexcept { return m_limbs; } BOOST_MP_FORCEINLINE limb_pointer limbs() noexcept { return m_internal ? m_data.la : m_data.ld.data; } BOOST_MP_FORCEINLINE const_limb_pointer limbs() const noexcept { return m_internal ? m_data.la : m_data.ld.data; } BOOST_MP_FORCEINLINE unsigned capacity() const noexcept { return m_internal ? internal_limb_count : m_data.ld.capacity; } BOOST_MP_FORCEINLINE bool sign() const noexcept { return m_sign; } void sign(bool b) noexcept { m_sign = b; // Check for zero value: if (m_sign && (m_limbs == 1)) { if (limbs()[0] == 0) m_sign = false; } } void resize(unsigned new_size, unsigned min_size) { constexpr const unsigned max_limbs = MaxBits / (CHAR_BIT * sizeof(limb_type)) + ((MaxBits % (CHAR_BIT * sizeof(limb_type))) ? 1 : 0); // We never resize beyond MaxSize: if (new_size > max_limbs) new_size = max_limbs; detail::verify_new_size(new_size, min_size, checked_type()); // See if we have enough capacity already: unsigned cap = capacity(); if (new_size > cap) { // We must not be an alias, memory allocation here defeats the whole point of aliasing: BOOST_ASSERT(!m_alias); // Allocate a new buffer and copy everything over: cap = (std::min)((std::max)(cap * 4, new_size), max_limbs); limb_pointer pl = allocator().allocate(cap); std::memcpy(pl, limbs(), size() * sizeof(limbs()[0])); if (!m_internal && !m_alias) allocator().deallocate(limbs(), capacity()); else m_internal = false; m_limbs = new_size; m_data.ld.capacity = cap; m_data.ld.data = pl; } else { m_limbs = new_size; } } BOOST_MP_FORCEINLINE void normalize() noexcept { limb_pointer p = limbs(); while ((m_limbs - 1) && !p[m_limbs - 1]) --m_limbs; } BOOST_MP_FORCEINLINE constexpr cpp_int_base() noexcept : m_data(), m_limbs(1), m_sign(false), m_internal(true), m_alias(false){} BOOST_MP_FORCEINLINE cpp_int_base(const cpp_int_base& o) : base_type(o), m_limbs(o.m_alias ? o.m_limbs : 0), m_sign(o.m_sign), m_internal(o.m_alias ? false : true), m_alias(o.m_alias) { if (m_alias) { m_data.ld = o.m_data.ld; } else { resize(o.size(), o.size()); std::memcpy(limbs(), o.limbs(), o.size() * sizeof(limbs()[0])); } } // rvalue copy: cpp_int_base(cpp_int_base&& o) : base_type(static_cast<base_type&&>(o)), m_limbs(o.m_limbs), m_sign(o.m_sign), m_internal(o.m_internal), m_alias(o.m_alias) { if (m_internal) { std::memcpy(limbs(), o.limbs(), o.size() * sizeof(limbs()[0])); } else { m_data.ld = o.m_data.ld; o.m_limbs = 0; o.m_internal = true; } } cpp_int_base& operator=(cpp_int_base&& o) noexcept { if (!m_internal && !m_alias) allocator().deallocate(m_data.ld.data, m_data.ld.capacity); *static_cast<base_type*>(this) = static_cast<base_type&&>(o); m_limbs = o.m_limbs; m_sign = o.m_sign; m_internal = o.m_internal; m_alias = o.m_alias; if (m_internal) { std::memcpy(limbs(), o.limbs(), o.size() * sizeof(limbs()[0])); } else { m_data.ld = o.m_data.ld; o.m_limbs = 0; o.m_internal = true; } return *this; } template <unsigned MinBits2, unsigned MaxBits2, cpp_int_check_type Checked2> cpp_int_base& operator=(cpp_int_base<MinBits2, MaxBits2, signed_magnitude, Checked2, Allocator>&& o) noexcept { if(o.m_internal) { m_sign = o.m_sign; this->resize(o.size(), o.size()); std::memcpy(this->limbs(), o.limbs(), o.size() * sizeof(*(o.limbs()))); return *this; } if (!m_internal && !m_alias) allocator().deallocate(m_data.ld.data, m_data.ld.capacity); *static_cast<base_type*>(this) = static_cast<typename cpp_int_base<MinBits2, MaxBits2, signed_magnitude, Checked2, Allocator>::base_type&&>(o); m_limbs = o.m_limbs; m_sign = o.m_sign; m_internal = o.m_internal; m_alias = o.m_alias; m_data.ld.capacity = o.m_data.ld.capacity; m_data.ld.data = o.limbs(); o.m_limbs = 0; o.m_internal = true; return *this; } BOOST_MP_FORCEINLINE ~cpp_int_base() noexcept { if (!m_internal && !m_alias) allocator().deallocate(limbs(), capacity()); } void assign(const cpp_int_base& o) { if (this != &o) { static_cast<base_type&>(*this) = static_cast<const base_type&>(o); m_limbs = 0; resize(o.size(), o.size()); std::memcpy(limbs(), o.limbs(), o.size() * sizeof(limbs()[0])); m_sign = o.m_sign; } } BOOST_MP_FORCEINLINE void negate() noexcept { m_sign = !m_sign; // Check for zero value: if (m_sign && (m_limbs == 1)) { if (limbs()[0] == 0) m_sign = false; } } BOOST_MP_FORCEINLINE bool isneg() const noexcept { return m_sign; } BOOST_MP_FORCEINLINE void do_swap(cpp_int_base& o) noexcept { std::swap(m_data, o.m_data); std::swap(m_sign, o.m_sign); std::swap(m_internal, o.m_internal); std::swap(m_limbs, o.m_limbs); std::swap(m_alias, o.m_alias); } protected: template <class A> void check_in_range(const A&) noexcept {} }; template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> const unsigned cpp_int_base<MinBits, MaxBits, signed_magnitude, Checked, Allocator, false>::limb_bits; template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> const limb_type cpp_int_base<MinBits, MaxBits, signed_magnitude, Checked, Allocator, false>::max_limb_value; template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> const limb_type cpp_int_base<MinBits, MaxBits, signed_magnitude, Checked, Allocator, false>::sign_bit_mask; template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> const unsigned cpp_int_base<MinBits, MaxBits, signed_magnitude, Checked, Allocator, false>::internal_limb_count; template <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked, class Allocator> struct cpp_int_base<MinBits, MaxBits, unsigned_magnitude, Checked, Allocator, false> : private boost::empty_value<typename detail::rebind<limb_type, Allocator>::type> { // // There is currently no support for unsigned arbitrary precision arithmetic, largely // because it's not clear what subtraction should do: // static_assert(((sizeof(Allocator) == 0) && !std::is_void<Allocator>::value), "There is curently no support for unsigned arbitrary precision integers."); }; // // Fixed precision (i.e. no allocator), signed-magnitude type with limb-usage count: // template <unsigned MinBits, cpp_int_check_type Checked> struct cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, false> { using limb_pointer = limb_type* ; using const_limb_pointer = const limb_type* ; using checked_type = std::integral_constant<int, Checked>; struct scoped_shared_storage { BOOST_MP_CXX14_CONSTEXPR scoped_shared_storage(const cpp_int_base&, unsigned) {} BOOST_MP_CXX14_CONSTEXPR void deallocate(unsigned) {} }; // // Interface invariants: // static_assert(MinBits > sizeof(double_limb_type) * CHAR_BIT, "Template parameter MinBits is inconsistent with the parameter trivial - did you mistakingly try to override the trivial parameter?"); public: static constexpr unsigned limb_bits = sizeof(limb_type) * CHAR_BIT; static constexpr limb_type max_limb_value = ~static_cast<limb_type>(0u); static constexpr limb_type sign_bit_mask = static_cast<limb_type>(1u) << (limb_bits - 1); static constexpr unsigned internal_limb_count = MinBits / limb_bits + ((MinBits % limb_bits) ? 1 : 0); static constexpr limb_type upper_limb_mask = (MinBits % limb_bits) ? (limb_type(1) << (MinBits % limb_bits)) - 1 : (~limb_type(0)); static_assert(internal_limb_count >= 2, "A fixed precision integer type must have at least 2 limbs"); private: union data_type { limb_type m_data[internal_limb_count]; limb_type m_first_limb; double_limb_type m_double_first_limb; constexpr data_type() : m_data{0} {} constexpr data_type(limb_type i) : m_data{i} {} #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION constexpr data_type(limb_type i, limb_type j) : m_data{i, j} {} #endif constexpr data_type(double_limb_type i) : m_double_first_limb(i) { #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION if (BOOST_MP_IS_CONST_EVALUATED(m_double_first_limb)) { data_type t(static_cast<limb_type>(i & max_limb_value), static_cast<limb_type>(i >> limb_bits)); *this = t; } #endif } template <limb_type... VALUES> constexpr data_type(literals::detail::value_pack<VALUES...>) : m_data{VALUES...} {} } m_wrapper; std::uint16_t m_limbs; bool m_sign; public: // // Direct construction: // BOOST_MP_FORCEINLINE constexpr cpp_int_base(limb_type i) noexcept : m_wrapper(i), m_limbs(1), m_sign(false) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(signed_limb_type i) noexcept : m_wrapper(limb_type(i < 0 ? static_cast<limb_type>(-static_cast<signed_double_limb_type>(i)) : i)), m_limbs(1), m_sign(i < 0) {} #if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE) BOOST_MP_FORCEINLINE constexpr cpp_int_base(double_limb_type i) noexcept : m_wrapper(i), m_limbs(i > max_limb_value ? 2 : 1), m_sign(false) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(signed_double_limb_type i) noexcept : m_wrapper(double_limb_type(i < 0 ? static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) : i)), m_limbs(i < 0 ? (static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) > max_limb_value ? 2 : 1) : (i > max_limb_value ? 2 : 1)), m_sign(i < 0) {} #endif template <limb_type... VALUES> constexpr cpp_int_base(literals::detail::value_pack<VALUES...> i) : m_wrapper(i), m_limbs(sizeof...(VALUES)), m_sign(false) {} constexpr cpp_int_base(literals::detail::value_pack<> i) : m_wrapper(i), m_limbs(1), m_sign(false) {} constexpr cpp_int_base(const cpp_int_base& a, const literals::detail::negate_tag&) : m_wrapper(a.m_wrapper), m_limbs(a.m_limbs), m_sign((a.m_limbs == 1) && (*a.limbs() == 0) ? false : !a.m_sign) {} explicit constexpr cpp_int_base(scoped_shared_storage&, unsigned) noexcept : m_wrapper(), m_limbs(0), m_sign(false) {} // // These are deprecated in C++20 unless we make them explicit: // BOOST_MP_CXX14_CONSTEXPR cpp_int_base& operator=(const cpp_int_base&) = default; // // Helper functions for getting at our internal data, and manipulating storage: // BOOST_MP_FORCEINLINE constexpr unsigned size() const noexcept { return m_limbs; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR limb_pointer limbs() noexcept { return m_wrapper.m_data; } BOOST_MP_FORCEINLINE constexpr const_limb_pointer limbs() const noexcept { return m_wrapper.m_data; } BOOST_MP_FORCEINLINE constexpr bool sign() const noexcept { return m_sign; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void sign(bool b) noexcept { m_sign = b; // Check for zero value: if (m_sign && (m_limbs == 1)) { if (limbs()[0] == 0) m_sign = false; } } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void resize(unsigned new_size, unsigned min_size) noexcept((Checked == unchecked)) { m_limbs = static_cast<std::uint16_t>((std::min)(new_size, internal_limb_count)); detail::verify_new_size(m_limbs, min_size, checked_type()); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void normalize() noexcept((Checked == unchecked)) { limb_pointer p = limbs(); detail::verify_limb_mask(m_limbs == internal_limb_count, p[m_limbs - 1], upper_limb_mask, checked_type()); p[internal_limb_count - 1] &= upper_limb_mask; while ((m_limbs - 1) && !p[m_limbs - 1]) --m_limbs; if ((m_limbs == 1) && (!*p)) m_sign = false; // zero is always unsigned } BOOST_MP_FORCEINLINE constexpr cpp_int_base() noexcept : m_wrapper(limb_type(0u)), m_limbs(1), m_sign(false) {} // Not defaulted, it breaks constexpr support in the Intel compiler for some reason: BOOST_MP_FORCEINLINE constexpr cpp_int_base(const cpp_int_base& o) noexcept : m_wrapper(o.m_wrapper), m_limbs(o.m_limbs), m_sign(o.m_sign) {} // Defaulted functions: //~cpp_int_base() noexcept {} void BOOST_MP_CXX14_CONSTEXPR assign(const cpp_int_base& o) noexcept { if (this != &o) { m_limbs = o.m_limbs; #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION if (BOOST_MP_IS_CONST_EVALUATED(m_limbs)) { for (unsigned i = 0; i < m_limbs; ++i) limbs()[i] = o.limbs()[i]; } else #endif std::memcpy(limbs(), o.limbs(), o.size() * sizeof(o.limbs()[0])); m_sign = o.m_sign; } } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void negate() noexcept { m_sign = !m_sign; // Check for zero value: if (m_sign && (m_limbs == 1)) { if (limbs()[0] == 0) m_sign = false; } } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR bool isneg() const noexcept { return m_sign; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_swap(cpp_int_base& o) noexcept { for (unsigned i = 0; i < (std::max)(size(), o.size()); ++i) std_constexpr::swap(m_wrapper.m_data[i], o.m_wrapper.m_data[i]); std_constexpr::swap(m_sign, o.m_sign); std_constexpr::swap(m_limbs, o.m_limbs); } protected: template <class A> BOOST_MP_CXX14_CONSTEXPR void check_in_range(const A&) noexcept {} }; template <unsigned MinBits, cpp_int_check_type Checked> const unsigned cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, false>::limb_bits; template <unsigned MinBits, cpp_int_check_type Checked> const limb_type cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, false>::max_limb_value; template <unsigned MinBits, cpp_int_check_type Checked> const limb_type cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, false>::sign_bit_mask; template <unsigned MinBits, cpp_int_check_type Checked> const unsigned cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, false>::internal_limb_count; // // Fixed precision (i.e. no allocator), unsigned type with limb-usage count: // template <unsigned MinBits, cpp_int_check_type Checked> struct cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, false> { using limb_pointer = limb_type* ; using const_limb_pointer = const limb_type* ; using checked_type = std::integral_constant<int, Checked>; struct scoped_shared_storage { BOOST_MP_CXX14_CONSTEXPR scoped_shared_storage(const cpp_int_base&, unsigned) {} BOOST_MP_CXX14_CONSTEXPR void deallocate(unsigned) {} }; // // Interface invariants: // static_assert(MinBits > sizeof(double_limb_type) * CHAR_BIT, "Template parameter MinBits is inconsistent with the parameter trivial - did you mistakingly try to override the trivial parameter?"); public: static constexpr unsigned limb_bits = sizeof(limb_type) * CHAR_BIT; static constexpr limb_type max_limb_value = ~static_cast<limb_type>(0u); static constexpr limb_type sign_bit_mask = static_cast<limb_type>(1u) << (limb_bits - 1); static constexpr unsigned internal_limb_count = MinBits / limb_bits + ((MinBits % limb_bits) ? 1 : 0); static constexpr limb_type upper_limb_mask = (MinBits % limb_bits) ? (limb_type(1) << (MinBits % limb_bits)) - 1 : (~limb_type(0)); static_assert(internal_limb_count >= 2, "A fixed precision integer type must have at least 2 limbs"); private: union data_type { limb_type m_data[internal_limb_count]; limb_type m_first_limb; double_limb_type m_double_first_limb; constexpr data_type() : m_data{0} {} constexpr data_type(limb_type i) : m_data{i} {} #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION constexpr data_type(limb_type i, limb_type j) : m_data{i, j} {} #endif constexpr data_type(double_limb_type i) : m_double_first_limb(i) { #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION if (BOOST_MP_IS_CONST_EVALUATED(m_double_first_limb)) { data_type t(static_cast<limb_type>(i & max_limb_value), static_cast<limb_type>(i >> limb_bits)); *this = t; } #endif } template <limb_type... VALUES> constexpr data_type(literals::detail::value_pack<VALUES...>) : m_data{VALUES...} {} } m_wrapper; limb_type m_limbs; public: // // Direct construction: // BOOST_MP_FORCEINLINE constexpr cpp_int_base(limb_type i) noexcept : m_wrapper(i), m_limbs(1) {} BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(signed_limb_type i) noexcept((Checked == unchecked)) : m_wrapper(limb_type(i < 0 ? static_cast<limb_type>(-static_cast<signed_double_limb_type>(i)) : i)), m_limbs(1) { if (i < 0) negate(); } #if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE) BOOST_MP_FORCEINLINE constexpr cpp_int_base(double_limb_type i) noexcept : m_wrapper(i), m_limbs(i > max_limb_value ? 2 : 1) {} BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(signed_double_limb_type i) noexcept((Checked == unchecked)) : m_wrapper(double_limb_type(i < 0 ? static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) : i)), m_limbs(i < 0 ? (static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)) > max_limb_value ? 2 : 1) : (i > max_limb_value ? 2 : 1)) { if (i < 0) negate(); } #endif template <limb_type... VALUES> constexpr cpp_int_base(literals::detail::value_pack<VALUES...> i) : m_wrapper(i), m_limbs(sizeof...(VALUES)) {} constexpr cpp_int_base(literals::detail::value_pack<>) : m_wrapper(static_cast<limb_type>(0u)), m_limbs(1) {} explicit constexpr cpp_int_base(scoped_shared_storage&, unsigned) noexcept : m_wrapper(), m_limbs(1) {} // // Helper functions for getting at our internal data, and manipulating storage: // BOOST_MP_FORCEINLINE constexpr unsigned size() const noexcept { return m_limbs; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR limb_pointer limbs() noexcept { return m_wrapper.m_data; } BOOST_MP_FORCEINLINE constexpr const_limb_pointer limbs() const noexcept { return m_wrapper.m_data; } BOOST_MP_FORCEINLINE constexpr bool sign() const noexcept { return false; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void sign(bool b) noexcept((Checked == unchecked)) { if (b) negate(); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void resize(unsigned new_size, unsigned min_size) noexcept((Checked == unchecked)) { m_limbs = (std::min)(new_size, internal_limb_count); detail::verify_new_size(m_limbs, min_size, checked_type()); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void normalize() noexcept((Checked == unchecked)) { limb_pointer p = limbs(); detail::verify_limb_mask(m_limbs == internal_limb_count, p[internal_limb_count - 1], upper_limb_mask, checked_type()); p[internal_limb_count - 1] &= upper_limb_mask; while ((m_limbs - 1) && !p[m_limbs - 1]) --m_limbs; } BOOST_MP_FORCEINLINE constexpr cpp_int_base() noexcept : m_wrapper(limb_type(0u)), m_limbs(1) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(const cpp_int_base& o) noexcept : m_wrapper(o.m_wrapper), m_limbs(o.m_limbs) {} // Defaulted functions: //~cpp_int_base() noexcept {} // // These are deprecated in C++20 unless we make them explicit: // BOOST_MP_CXX14_CONSTEXPR cpp_int_base& operator=(const cpp_int_base&) = default; BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void assign(const cpp_int_base& o) noexcept { if (this != &o) { m_limbs = o.m_limbs; #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION if (BOOST_MP_IS_CONST_EVALUATED(m_limbs)) { for (unsigned i = 0; i < m_limbs; ++i) limbs()[i] = o.limbs()[i]; } else #endif std::memcpy(limbs(), o.limbs(), o.size() * sizeof(limbs()[0])); } } private: void check_negate(const std::integral_constant<int, checked>&) { BOOST_THROW_EXCEPTION(std::range_error("Attempt to negate an unsigned number.")); } BOOST_MP_CXX14_CONSTEXPR void check_negate(const std::integral_constant<int, unchecked>&) {} public: BOOST_MP_CXX14_CONSTEXPR void negate() noexcept((Checked == unchecked)) { // Not so much a negate as a complement - this gets called when subtraction // would result in a "negative" number: if ((m_limbs == 1) && (m_wrapper.m_data[0] == 0)) return; // negating zero is always zero, and always OK. check_negate(checked_type()); unsigned i = m_limbs; for (; i < internal_limb_count; ++i) m_wrapper.m_data[i] = 0; m_limbs = internal_limb_count; for (i = 0; i < internal_limb_count; ++i) m_wrapper.m_data[i] = ~m_wrapper.m_data[i]; normalize(); eval_increment(static_cast<cpp_int_backend<MinBits, MinBits, unsigned_magnitude, Checked, void>&>(*this)); } BOOST_MP_FORCEINLINE constexpr bool isneg() const noexcept { return false; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_swap(cpp_int_base& o) noexcept { for (unsigned i = 0; i < (std::max)(size(), o.size()); ++i) std_constexpr::swap(m_wrapper.m_data[i], o.m_wrapper.m_data[i]); std_constexpr::swap(m_limbs, o.m_limbs); } protected: template <class A> BOOST_MP_CXX14_CONSTEXPR void check_in_range(const A&) noexcept {} }; template <unsigned MinBits, cpp_int_check_type Checked> const unsigned cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, false>::limb_bits; template <unsigned MinBits, cpp_int_check_type Checked> const limb_type cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, false>::max_limb_value; template <unsigned MinBits, cpp_int_check_type Checked> const limb_type cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, false>::sign_bit_mask; template <unsigned MinBits, cpp_int_check_type Checked> const unsigned cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, false>::internal_limb_count; // // Traits classes to figure out a native type with N bits, these vary from boost::uint_t<N> only // because some platforms have native integer types longer than boost::long_long_type, "really boost::long_long_type" anyone?? // template <unsigned N, bool s> struct trivial_limb_type_imp { using type = double_limb_type; }; template <unsigned N> struct trivial_limb_type_imp<N, true> { using type = typename boost::uint_t<N>::least; }; template <unsigned N> struct trivial_limb_type : public trivial_limb_type_imp<N, N <= sizeof(boost::long_long_type) * CHAR_BIT> {}; // // Backend for fixed precision signed-magnitude type which will fit entirely inside a "double_limb_type": // template <unsigned MinBits, cpp_int_check_type Checked> struct cpp_int_base<MinBits, MinBits, signed_magnitude, Checked, void, true> { using local_limb_type = typename trivial_limb_type<MinBits>::type; using limb_pointer = local_limb_type* ; using const_limb_pointer = const local_limb_type* ; using checked_type = std::integral_constant<int, Checked> ; struct scoped_shared_storage { BOOST_MP_CXX14_CONSTEXPR scoped_shared_storage(const cpp_int_base&, unsigned) {} BOOST_MP_CXX14_CONSTEXPR void deallocate(unsigned) {} }; protected: static constexpr unsigned limb_bits = sizeof(local_limb_type) * CHAR_BIT; static constexpr local_limb_type limb_mask = (MinBits < limb_bits) ? local_limb_type((local_limb_type(~local_limb_type(0))) >> (limb_bits - MinBits)) : local_limb_type(~local_limb_type(0)); private: local_limb_type m_data; bool m_sign; // // Interface invariants: // static_assert(MinBits <= sizeof(double_limb_type) * CHAR_BIT, "Template parameter MinBits is inconsistent with the parameter trivial - did you mistakingly try to override the trivial parameter?"); protected: template <class T> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!(!boost::multiprecision::detail::is_integral<T>::value || (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::digits <= (int)MinBits)))>::type check_in_range(T val, const std::integral_constant<int, checked>&) { using common_type = typename std::common_type<typename boost::multiprecision::detail::make_unsigned<T>::type, local_limb_type>::type; if (static_cast<common_type>(boost::multiprecision::detail::unsigned_abs(val)) > static_cast<common_type>(limb_mask)) BOOST_THROW_EXCEPTION(std::range_error("The argument to a cpp_int constructor exceeded the largest value it can represent.")); } template <class T> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!(boost::multiprecision::detail::is_integral<T>::value || (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::digits <= (int)MinBits)))>::type check_in_range(T val, const std::integral_constant<int, checked>&) { using std::abs; using common_type = typename std::common_type<T, local_limb_type>::type; if (static_cast<common_type>(abs(val)) > static_cast<common_type>(limb_mask)) BOOST_THROW_EXCEPTION(std::range_error("The argument to a cpp_int constructor exceeded the largest value it can represent.")); } template <class T, int C> BOOST_MP_CXX14_CONSTEXPR void check_in_range(T, const std::integral_constant<int, C>&) noexcept {} template <class T> BOOST_MP_CXX14_CONSTEXPR void check_in_range(T val) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<T>(), checked_type()))) { check_in_range(val, checked_type()); } public: // // Direct construction: // template <class SI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == unchecked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<SI>()))) : m_data(i < 0 ? static_cast<local_limb_type>(static_cast<typename boost::multiprecision::detail::make_unsigned<SI>::type>(boost::multiprecision::detail::unsigned_abs(i)) & limb_mask) : static_cast<local_limb_type>(i & limb_mask)), m_sign(i < 0) {} template <class SI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<SI>()))) : m_data(i < 0 ? (static_cast<local_limb_type>(static_cast<typename boost::multiprecision::detail::make_unsigned<SI>::type>(boost::multiprecision::detail::unsigned_abs(i)) & limb_mask)) : static_cast<local_limb_type>(i & limb_mask)), m_sign(i < 0) { check_in_range(i); } template <class UI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(static_cast<local_limb_type>(i) & limb_mask), m_sign(false) {} template <class UI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<UI>()))) : m_data(static_cast<local_limb_type>(i) & limb_mask), m_sign(false) { check_in_range(i); } #if !(defined(__clang__) && defined(__MINGW32__)) template <class F> BOOST_MP_FORCEINLINE constexpr cpp_int_base(F i, typename std::enable_if<std::is_floating_point<F>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(static_cast<local_limb_type>(std::fabs(i)) & limb_mask), m_sign(i < 0) {} template <class F> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(F i, typename std::enable_if<std::is_floating_point<F>::value && (Checked == checked)>::type const* = 0) : m_data(static_cast<local_limb_type>(std::fabs(i)) & limb_mask), m_sign(i < 0) { check_in_range(i); } #else // // conversion from float to __int128 is broken on clang/mingw, // see: https://bugs.llvm.org/show_bug.cgi?id=48940 // Since no floating point type has more than 64 bits of // precision, we can simply cast to an intermediate type to // solve the issue: // template <class F> BOOST_MP_FORCEINLINE constexpr cpp_int_base(F i, typename std::enable_if<std::is_floating_point<F>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(static_cast<local_limb_type>(static_cast<std::uint64_t>(std::fabs(i))) & limb_mask), m_sign(i < 0) {} template <class F> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(F i, typename std::enable_if<std::is_floating_point<F>::value && (Checked == checked)>::type const* = 0) : m_data(static_cast<local_limb_type>(static_cast<std::uint64_t>(std::fabs(i))) & limb_mask), m_sign(i < 0) { check_in_range(i); } #endif constexpr cpp_int_base(literals::detail::value_pack<>) noexcept : m_data(static_cast<local_limb_type>(0u)), m_sign(false) {} template <limb_type a> constexpr cpp_int_base(literals::detail::value_pack<a>) noexcept : m_data(static_cast<local_limb_type>(a)), m_sign(false) {} template <limb_type a, limb_type b> constexpr cpp_int_base(literals::detail::value_pack<a, b>) noexcept : m_data(static_cast<local_limb_type>(a) | (static_cast<local_limb_type>(b) << bits_per_limb)), m_sign(false) {} constexpr cpp_int_base(const cpp_int_base& a, const literals::detail::negate_tag&) noexcept : m_data(a.m_data), m_sign(a.m_data ? !a.m_sign : false) {} // // These are deprecated in C++20 unless we make them explicit: // BOOST_MP_CXX14_CONSTEXPR cpp_int_base& operator=(const cpp_int_base&) = default; explicit constexpr cpp_int_base(scoped_shared_storage&, unsigned) noexcept : m_data(0), m_sign(false) {} // // Helper functions for getting at our internal data, and manipulating storage: // BOOST_MP_FORCEINLINE constexpr unsigned size() const noexcept { return 1; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR limb_pointer limbs() noexcept { return &m_data; } BOOST_MP_FORCEINLINE constexpr const_limb_pointer limbs() const noexcept { return &m_data; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR bool sign() const noexcept { return m_sign; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void sign(bool b) noexcept { m_sign = b; // Check for zero value: if (m_sign && !m_data) { m_sign = false; } } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void resize(unsigned /* new_size */, unsigned min_size) { detail::verify_new_size(2, min_size, checked_type()); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void normalize() noexcept((Checked == unchecked)) { if (!m_data) m_sign = false; // zero is always unsigned detail::verify_limb_mask(true, m_data, limb_mask, checked_type()); m_data &= limb_mask; } BOOST_MP_FORCEINLINE constexpr cpp_int_base() noexcept : m_data(0), m_sign(false) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(const cpp_int_base& o) noexcept : m_data(o.m_data), m_sign(o.m_sign) {} //~cpp_int_base() noexcept {} BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void assign(const cpp_int_base& o) noexcept { m_data = o.m_data; m_sign = o.m_sign; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void negate() noexcept { m_sign = !m_sign; // Check for zero value: if (m_data == 0) { m_sign = false; } } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR bool isneg() const noexcept { return m_sign; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_swap(cpp_int_base& o) noexcept { std_constexpr::swap(m_sign, o.m_sign); std_constexpr::swap(m_data, o.m_data); } }; // // Backend for unsigned fixed precision (i.e. no allocator) type which will fit entirely inside a "double_limb_type": // template <unsigned MinBits, cpp_int_check_type Checked> struct cpp_int_base<MinBits, MinBits, unsigned_magnitude, Checked, void, true> { using local_limb_type = typename trivial_limb_type<MinBits>::type; using limb_pointer = local_limb_type* ; using const_limb_pointer = const local_limb_type* ; struct scoped_shared_storage { BOOST_MP_CXX14_CONSTEXPR scoped_shared_storage(const cpp_int_base&, unsigned) {} BOOST_MP_CXX14_CONSTEXPR void deallocate(unsigned) {} }; private: static constexpr unsigned limb_bits = sizeof(local_limb_type) * CHAR_BIT; static constexpr local_limb_type limb_mask = limb_bits != MinBits ? static_cast<local_limb_type>(static_cast<local_limb_type>(~local_limb_type(0)) >> (limb_bits - MinBits)) : static_cast<local_limb_type>(~local_limb_type(0)); local_limb_type m_data; using checked_type = std::integral_constant<int, Checked>; // // Interface invariants: // static_assert(MinBits <= sizeof(double_limb_type) * CHAR_BIT, "Template parameter MinBits is inconsistent with the parameter trivial - did you mistakingly try to override the trivial parameter?"); protected: template <class T> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if< !(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::digits <= (int)MinBits))>::type check_in_range(T val, const std::integral_constant<int, checked>&, const std::integral_constant<bool, false>&) { using common_type = typename std::common_type<T, local_limb_type>::type; if (static_cast<common_type>(val) > limb_mask) BOOST_THROW_EXCEPTION(std::range_error("The argument to a cpp_int constructor exceeded the largest value it can represent.")); } template <class T> BOOST_MP_CXX14_CONSTEXPR void check_in_range(T val, const std::integral_constant<int, checked>&, const std::integral_constant<bool, true>&) { using common_type = typename std::common_type<T, local_limb_type>::type; if (static_cast<common_type>(val) > static_cast<common_type>(limb_mask)) BOOST_THROW_EXCEPTION(std::range_error("The argument to a cpp_int constructor exceeded the largest value it can represent.")); if (val < 0) BOOST_THROW_EXCEPTION(std::range_error("The argument to an unsigned cpp_int constructor was negative.")); } template <class T, int C, bool B> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void check_in_range(T, const std::integral_constant<int, C>&, const std::integral_constant<bool, B>&) noexcept {} template <class T> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void check_in_range(T val) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<T>(), checked_type(), boost::multiprecision::detail::is_signed<T>()))) { check_in_range(val, checked_type(), boost::multiprecision::detail::is_signed<T>()); } public: // // Direct construction: // #ifdef __MSVC_RUNTIME_CHECKS template <class SI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(i < 0 ? (1 + ~static_cast<local_limb_type>(-i & limb_mask)) & limb_mask : static_cast<local_limb_type>(i & limb_mask)) {} template <class SI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<SI>()))) : m_data(i < 0 ? 1 + ~static_cast<local_limb_type>(-i & limb_mask) : static_cast<local_limb_type>(i & limb_mask)) { check_in_range(i); } template <class UI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(static_cast<local_limb_type>(i& limb_mask)) {} template <class UI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<UI>()))) : m_data(static_cast<local_limb_type>(i & limb_mask)) { check_in_range(i); } #else template <class SI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(i < 0 ? (1 + ~static_cast<local_limb_type>(-i)) & limb_mask : static_cast<local_limb_type>(i) & limb_mask) {} template <class SI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(SI i, typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<SI>()))) : m_data(i < 0 ? 1 + ~static_cast<local_limb_type>(-i) : static_cast<local_limb_type>(i)) { check_in_range(i); } template <class UI> BOOST_MP_FORCEINLINE constexpr cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == unchecked)>::type const* = 0) noexcept : m_data(static_cast<local_limb_type>(i) & limb_mask) {} template <class UI> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(UI i, typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (Checked == checked)>::type const* = 0) noexcept(noexcept(std::declval<cpp_int_base>().check_in_range(std::declval<UI>()))) : m_data(static_cast<local_limb_type>(i)) { check_in_range(i); } #endif template <class F> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_base(F i, typename std::enable_if<std::is_floating_point<F>::value >::type const* = 0) noexcept((Checked == unchecked)) : m_data(static_cast<local_limb_type>(std::fabs(i)) & limb_mask) { check_in_range(i); if (i < 0) negate(); } constexpr cpp_int_base(literals::detail::value_pack<>) noexcept : m_data(static_cast<local_limb_type>(0u)) {} template <limb_type a> constexpr cpp_int_base(literals::detail::value_pack<a>) noexcept : m_data(static_cast<local_limb_type>(a)) {} template <limb_type a, limb_type b> constexpr cpp_int_base(literals::detail::value_pack<a, b>) noexcept : m_data(static_cast<local_limb_type>(a) | (static_cast<local_limb_type>(b) << bits_per_limb)) {} // // These are deprecated in C++20 unless we make them explicit: // BOOST_MP_CXX14_CONSTEXPR cpp_int_base& operator=(const cpp_int_base&) = default; explicit constexpr cpp_int_base(scoped_shared_storage&, unsigned) noexcept : m_data(0) {} // // Helper functions for getting at our internal data, and manipulating storage: // BOOST_MP_FORCEINLINE constexpr unsigned size() const noexcept { return 1; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR limb_pointer limbs() noexcept { return &m_data; } BOOST_MP_FORCEINLINE constexpr const_limb_pointer limbs() const noexcept { return &m_data; } BOOST_MP_FORCEINLINE constexpr bool sign() const noexcept { return false; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void sign(bool b) noexcept((Checked == unchecked)) { if (b) negate(); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void resize(unsigned, unsigned min_size) { detail::verify_new_size(2, min_size, checked_type()); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void normalize() noexcept((Checked == unchecked)) { detail::verify_limb_mask(true, m_data, limb_mask, checked_type()); m_data &= limb_mask; } BOOST_MP_FORCEINLINE constexpr cpp_int_base() noexcept : m_data(0) {} BOOST_MP_FORCEINLINE constexpr cpp_int_base(const cpp_int_base& o) noexcept : m_data(o.m_data) {} //~cpp_int_base() noexcept {} BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void assign(const cpp_int_base& o) noexcept { m_data = o.m_data; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void negate() noexcept((Checked == unchecked)) { BOOST_IF_CONSTEXPR(Checked == checked) { BOOST_THROW_EXCEPTION(std::range_error("Attempt to negate an unsigned type.")); } m_data = ~m_data; ++m_data; } BOOST_MP_FORCEINLINE constexpr bool isneg() const noexcept { return false; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_swap(cpp_int_base& o) noexcept { std_constexpr::swap(m_data, o.m_data); } }; // // Traits class, lets us know whether type T can be directly converted to the base type, // used to enable/disable constructors etc: // template <class Arg, class Base> struct is_allowed_cpp_int_base_conversion : public std::conditional< std::is_same<Arg, limb_type>::value || std::is_same<Arg, signed_limb_type>::value #if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE) || std::is_same<Arg, double_limb_type>::value || std::is_same<Arg, signed_double_limb_type>::value #endif || literals::detail::is_value_pack<Arg>::value || (is_trivial_cpp_int<Base>::value && boost::multiprecision::detail::is_arithmetic<Arg>::value), std::integral_constant<bool, true>, std::integral_constant<bool, false>>::type {}; // // Now the actual backend, normalising parameters passed to the base class: // template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct cpp_int_backend : public cpp_int_base< min_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value, max_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value, SignType, Checked, Allocator, is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value> { using self_type = cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>; using base_type = cpp_int_base< min_precision<self_type>::value, max_precision<self_type>::value, SignType, Checked, Allocator, is_trivial_cpp_int<self_type>::value>; using trivial_tag = std::integral_constant<bool, is_trivial_cpp_int<self_type>::value>; public: using signed_types = typename std::conditional< is_trivial_cpp_int<self_type>::value, std::tuple< signed char, short, int, long, boost::long_long_type, signed_double_limb_type>, std::tuple<signed_limb_type, signed_double_limb_type> >::type; using unsigned_types = typename std::conditional< is_trivial_cpp_int<self_type>::value, std::tuple<unsigned char, unsigned short, unsigned, unsigned long, boost::ulong_long_type, double_limb_type>, std::tuple<limb_type, double_limb_type> >::type; using float_types = typename std::conditional< is_trivial_cpp_int<self_type>::value, std::tuple<float, double, long double>, std::tuple<long double> >::type; using checked_type = std::integral_constant<int, Checked> ; BOOST_MP_FORCEINLINE constexpr cpp_int_backend() noexcept {} BOOST_MP_FORCEINLINE constexpr cpp_int_backend(const cpp_int_backend& o) noexcept(std::is_void<Allocator>::value) : base_type(o) {} // rvalue copy: BOOST_MP_FORCEINLINE constexpr cpp_int_backend(cpp_int_backend&& o) noexcept : base_type(static_cast<base_type&&>(o)) {} template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2> BOOST_MP_FORCEINLINE BOOST_CXX14_CONSTEXPR cpp_int_backend(cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2>&& o, typename std::enable_if<is_implicit_cpp_int_conversion<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2>, self_type>::value>::type* = 0) noexcept { *this = static_cast<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2>&&>(o); } // // Direct construction from arithmetic type: // template <class Arg> BOOST_MP_FORCEINLINE constexpr cpp_int_backend(Arg i, typename std::enable_if<is_allowed_cpp_int_base_conversion<Arg, base_type>::value>::type const* = 0) noexcept(noexcept(base_type(std::declval<Arg>()))) : base_type(i) {} // // Aliasing constructor: the result will alias the memory referenced, unless // we have fixed precision and storage, in which case we copy the memory: // explicit constexpr cpp_int_backend(limb_type* data, unsigned offset, unsigned len) noexcept : base_type(data, offset, len) {} explicit cpp_int_backend(const limb_type* data, unsigned offset, unsigned len) noexcept : base_type(data, offset, len) { this->normalize(); } explicit constexpr cpp_int_backend(typename base_type::scoped_shared_storage& data, unsigned len) noexcept : base_type(data, len) {} private: template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR void do_assign(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, std::integral_constant<bool, true> const&, std::integral_constant<bool, true> const&) { // Assigning trivial type to trivial type: this->check_in_range(*other.limbs()); *this->limbs() = static_cast<typename self_type::local_limb_type>(*other.limbs()); this->sign(other.sign()); this->normalize(); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR void do_assign(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, std::integral_constant<bool, true> const&, std::integral_constant<bool, false> const&) { // non-trivial to trivial narrowing conversion: double_limb_type v = *other.limbs(); if (other.size() > 1) { v |= static_cast<double_limb_type>(other.limbs()[1]) << bits_per_limb; BOOST_IF_CONSTEXPR(Checked == checked) { if (other.size() > 2) { BOOST_THROW_EXCEPTION(std::range_error("Assignment of a cpp_int that is out of range for the target type.")); } } } *this = v; this->sign(other.sign()); this->normalize(); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR void do_assign(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, std::integral_constant<bool, false> const&, std::integral_constant<bool, true> const&) { // trivial to non-trivial, treat the trivial argument as if it were an unsigned arithmetic type, then set the sign afterwards: *this = static_cast< typename boost::multiprecision::detail::canonical< typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::local_limb_type, cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::type>(*other.limbs()); this->sign(other.sign()); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR void do_assign(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, std::integral_constant<bool, false> const&, std::integral_constant<bool, false> const&) { // regular non-trivial to non-trivial assign: this->resize(other.size(), other.size()); #if !defined(BOOST_MP_HAS_IS_CONSTANT_EVALUATED) && !defined(BOOST_MP_HAS_BUILTIN_IS_CONSTANT_EVALUATED) && !defined(BOOST_NO_CXX14_CONSTEXPR) unsigned count = (std::min)(other.size(), this->size()); for (unsigned i = 0; i < count; ++i) this->limbs()[i] = other.limbs()[i]; #else #ifndef BOOST_MP_NO_CONSTEXPR_DETECTION if (BOOST_MP_IS_CONST_EVALUATED(other.size())) { unsigned count = (std::min)(other.size(), this->size()); for (unsigned i = 0; i < count; ++i) this->limbs()[i] = other.limbs()[i]; } else #endif std::memcpy(this->limbs(), other.limbs(), (std::min)(other.size(), this->size()) * sizeof(this->limbs()[0])); #endif this->sign(other.sign()); this->normalize(); } public: template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR cpp_int_backend( const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, typename std::enable_if<is_implicit_cpp_int_conversion<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>, self_type>::value>::type* = 0) : base_type() { do_assign( other, std::integral_constant<bool, is_trivial_cpp_int<self_type>::value>(), std::integral_constant<bool, is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>()); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> explicit BOOST_MP_CXX14_CONSTEXPR cpp_int_backend( const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other, typename std::enable_if< !(is_implicit_cpp_int_conversion<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>, self_type>::value)>::type* = 0) : base_type() { do_assign( other, std::integral_constant<bool, is_trivial_cpp_int<self_type>::value>(), std::integral_constant<bool, is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>()); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR cpp_int_backend& operator=( const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& other) { do_assign( other, std::integral_constant<bool, is_trivial_cpp_int<self_type>::value>(), std::integral_constant<bool, is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>()); return *this; } constexpr cpp_int_backend(const cpp_int_backend& a, const literals::detail::negate_tag& tag) : base_type(static_cast<const base_type&>(a), tag) {} BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_backend& operator=(const cpp_int_backend& o) noexcept(noexcept(std::declval<cpp_int_backend>().assign(std::declval<const cpp_int_backend&>()))) { this->assign(o); return *this; } // rvalue copy: BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR cpp_int_backend& operator=(cpp_int_backend&& o) noexcept(noexcept(std::declval<base_type&>() = std::declval<base_type>())) { *static_cast<base_type*>(this) = static_cast<base_type&&>(o); return *this; } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<((MaxBits2 <= MaxBits) || (MaxBits == 0)) && !std::is_void<Allocator>::value, cpp_int_backend&>::type operator=(cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator>&& o) noexcept { *static_cast<base_type*>(this) = static_cast<typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2>::base_type&&>(o); return *this; } private: template <class A> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_unsigned<A>::value>::type do_assign_arithmetic(A val, const std::integral_constant<bool, true>&) noexcept(noexcept(std::declval<cpp_int_backend>().check_in_range(std::declval<A>()))) { this->check_in_range(val); *this->limbs() = static_cast<typename self_type::local_limb_type>(val); this->sign(false); this->normalize(); } template <class A> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!(boost::multiprecision::detail::is_unsigned<A>::value || !boost::multiprecision::detail::is_integral<A>::value)>::type do_assign_arithmetic(A val, const std::integral_constant<bool, true>&) noexcept(noexcept(std::declval<cpp_int_backend>().check_in_range(std::declval<A>())) && noexcept(std::declval<cpp_int_backend>().sign(true))) { this->check_in_range(val); *this->limbs() = (val < 0) ? static_cast<typename self_type::local_limb_type>(boost::multiprecision::detail::unsigned_abs(val)) : static_cast<typename self_type::local_limb_type>(val); this->sign(val < 0); this->normalize(); } template <class A> BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!boost::multiprecision::detail::is_integral<A>::value>::type do_assign_arithmetic(A val, const std::integral_constant<bool, true>&) { this->check_in_range(val); *this->limbs() = (val < 0) ? static_cast<typename self_type::local_limb_type>(boost::multiprecision::detail::abs(val)) : static_cast<typename self_type::local_limb_type>(val); this->sign(val < 0); this->normalize(); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_assign_arithmetic(limb_type i, const std::integral_constant<bool, false>&) noexcept { this->resize(1, 1); *this->limbs() = i; this->sign(false); } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void do_assign_arithmetic(signed_limb_type i, const std::integral_constant<bool, false>&) noexcept(noexcept(std::declval<cpp_int_backend>().sign(true))) { this->resize(1, 1); *this->limbs() = static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(i)); this->sign(i < 0); } BOOST_MP_CXX14_CONSTEXPR void do_assign_arithmetic(double_limb_type i, const std::integral_constant<bool, false>&) noexcept { static_assert(sizeof(i) == 2 * sizeof(limb_type), "Failed integer size check"); static_assert(base_type::internal_limb_count >= 2, "Failed internal limb count"); typename base_type::limb_pointer p = this->limbs(); #ifdef __MSVC_RUNTIME_CHECKS *p = static_cast<limb_type>(i & ~static_cast<limb_type>(0)); #else *p = static_cast<limb_type>(i); #endif p[1] = static_cast<limb_type>(i >> base_type::limb_bits); this->resize(p[1] ? 2 : 1, p[1] ? 2 : 1); this->sign(false); } BOOST_MP_CXX14_CONSTEXPR void do_assign_arithmetic(signed_double_limb_type i, const std::integral_constant<bool, false>&) noexcept(noexcept(std::declval<cpp_int_backend>().sign(true))) { static_assert(sizeof(i) == 2 * sizeof(limb_type), "double limb type size check failed"); static_assert(base_type::internal_limb_count >= 2, "Failed internal limb count check"); bool s = false; if (i < 0) s = true; double_limb_type ui = static_cast<double_limb_type>(boost::multiprecision::detail::unsigned_abs(i)); typename base_type::limb_pointer p = this->limbs(); #ifdef __MSVC_RUNTIME_CHECKS *p = static_cast<limb_type>(ui & ~static_cast<limb_type>(0)); #else *p = static_cast<limb_type>(ui); #endif p[1] = static_cast<limb_type>(ui >> base_type::limb_bits); this->resize(p[1] ? 2 : 1, p[1] ? 2 : 1); this->sign(s); } BOOST_MP_CXX14_CONSTEXPR void do_assign_arithmetic(long double a, const std::integral_constant<bool, false>&) { using default_ops::eval_add; using default_ops::eval_subtract; using std::floor; using std::frexp; using std::ldexp; if (a < 0) { do_assign_arithmetic(-a, std::integral_constant<bool, false>()); this->sign(true); return; } if (a == 0) { *this = static_cast<limb_type>(0u); } if (a == 1) { *this = static_cast<limb_type>(1u); } if ((boost::math::isinf)(a) || (boost::math::isnan)(a)) { BOOST_THROW_EXCEPTION(std::runtime_error("Cannot convert a non-finite number to an integer.")); } int e = 0; long double f(0), term(0); *this = static_cast<limb_type>(0u); f = frexp(a, &e); #if !(defined(__clang__) && (__clang_major__ <= 7)) constexpr limb_type shift = std::numeric_limits<limb_type>::digits; #else // clang 7 has an issue converting long double to unsigned long long in // release mode (bits get dropped, conversion appears to go via float) // Never extract more than double bits at a time: constexpr limb_type shift = std::numeric_limits<limb_type>::digits > std::numeric_limits<double>::digits ? std::numeric_limits<double>::digits : std::numeric_limits<limb_type>::digits; #endif while (f) { // extract int sized bits from f: f = ldexp(f, shift); term = floor(f); e -= shift; eval_left_shift(*this, shift); #if !(defined(__clang__) && (__clang_major__ <= 7)) if (term > 0) eval_add(*this, static_cast<limb_type>(term)); else eval_subtract(*this, static_cast<limb_type>(-term)); #else // clang 7 requires extra cast to double to avoid buggy code generation: if (term > 0) eval_add(*this, static_cast<limb_type>(static_cast<double>(term))); else eval_subtract(*this, static_cast<limb_type>(static_cast<double>(-term))); #endif f -= term; } if (e > 0) eval_left_shift(*this, e); else if (e < 0) eval_right_shift(*this, -e); } public: template <class Arithmetic> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!boost::multiprecision::detail::is_byte_container<Arithmetic>::value, cpp_int_backend&>::type operator=(Arithmetic val) noexcept(noexcept(std::declval<cpp_int_backend>().do_assign_arithmetic(std::declval<Arithmetic>(), trivial_tag()))) { do_assign_arithmetic(val, trivial_tag()); return *this; } private: void do_assign_string(const char* s, const std::integral_constant<bool, true>&) { std::size_t n = s ? std::strlen(s) : 0; *this = 0; unsigned radix = 10; bool isneg = false; if (n && (*s == '-')) { --n; ++s; isneg = true; } if (n && (*s == '0')) { if ((n > 1) && ((s[1] == 'x') || (s[1] == 'X'))) { radix = 16; s += 2; n -= 2; } else { radix = 8; n -= 1; } } if (n) { unsigned val; while (*s) { if (*s >= '0' && *s <= '9') val = *s - '0'; else if (*s >= 'a' && *s <= 'f') val = 10 + *s - 'a'; else if (*s >= 'A' && *s <= 'F') val = 10 + *s - 'A'; else val = radix + 1; if (val >= radix) { BOOST_THROW_EXCEPTION(std::runtime_error("Unexpected content found while parsing character string.")); } *this->limbs() = detail::checked_multiply(*this->limbs(), static_cast<typename base_type::local_limb_type>(radix), checked_type()); *this->limbs() = detail::checked_add(*this->limbs(), static_cast<typename base_type::local_limb_type>(val), checked_type()); ++s; } } if (isneg) this->negate(); } void do_assign_string(const char* s, const std::integral_constant<bool, false>&) { using default_ops::eval_add; using default_ops::eval_multiply; std::size_t n = s ? std::strlen(s) : 0; *this = static_cast<limb_type>(0u); unsigned radix = 10; bool isneg = false; if (n && (*s == '-')) { --n; ++s; isneg = true; } if (n && (*s == '0')) { if ((n > 1) && ((s[1] == 'x') || (s[1] == 'X'))) { radix = 16; s += 2; n -= 2; } else { radix = 8; n -= 1; } } // // Exception guarantee: create the result in stack variable "result" // then do a swap at the end. In the event of a throw, *this will // be left unchanged. // cpp_int_backend result; if (n) { if (radix == 16) { while (*s == '0') ++s; std::size_t bitcount = 4 * std::strlen(s); limb_type val; std::size_t limb, shift; if (bitcount > 4) bitcount -= 4; else bitcount = 0; std::size_t newsize = bitcount / (sizeof(limb_type) * CHAR_BIT) + 1; result.resize(static_cast<unsigned>(newsize), static_cast<unsigned>(newsize)); // will throw if this is a checked integer that cannot be resized std::memset(result.limbs(), 0, result.size() * sizeof(limb_type)); while (*s) { if (*s >= '0' && *s <= '9') val = *s - '0'; else if (*s >= 'a' && *s <= 'f') val = 10 + *s - 'a'; else if (*s >= 'A' && *s <= 'F') val = 10 + *s - 'A'; else { BOOST_THROW_EXCEPTION(std::runtime_error("Unexpected content found while parsing character string.")); } limb = bitcount / (sizeof(limb_type) * CHAR_BIT); shift = bitcount % (sizeof(limb_type) * CHAR_BIT); val <<= shift; if (result.size() > limb) { result.limbs()[limb] |= val; } ++s; bitcount -= 4; } result.normalize(); } else if (radix == 8) { while (*s == '0') ++s; std::size_t bitcount = 3 * std::strlen(s); limb_type val; std::size_t limb, shift; if (bitcount > 3) bitcount -= 3; else bitcount = 0; std::size_t newsize = bitcount / (sizeof(limb_type) * CHAR_BIT) + 1; result.resize(static_cast<unsigned>(newsize), static_cast<unsigned>(newsize)); // will throw if this is a checked integer that cannot be resized std::memset(result.limbs(), 0, result.size() * sizeof(limb_type)); while (*s) { if (*s >= '0' && *s <= '7') val = *s - '0'; else { BOOST_THROW_EXCEPTION(std::runtime_error("Unexpected content found while parsing character string.")); } limb = bitcount / (sizeof(limb_type) * CHAR_BIT); shift = bitcount % (sizeof(limb_type) * CHAR_BIT); if (result.size() > limb) { result.limbs()[limb] |= (val << shift); if (shift > sizeof(limb_type) * CHAR_BIT - 3) { // Deal with the bits in val that overflow into the next limb: val >>= (sizeof(limb_type) * CHAR_BIT - shift); if (val) { // If this is the most-significant-limb, we may need to allocate an extra one for the overflow: if (limb + 1 == newsize) result.resize(static_cast<unsigned>(newsize + 1), static_cast<unsigned>(newsize + 1)); if (result.size() > limb + 1) { result.limbs()[limb + 1] |= val; } } } } ++s; bitcount -= 3; } result.normalize(); } else { // Base 10, we extract blocks of size 10^9 at a time, that way // the number of multiplications is kept to a minimum: limb_type block_mult = max_block_10; while (*s) { limb_type block = 0; for (unsigned i = 0; i < digits_per_block_10; ++i) { limb_type val; if (*s >= '0' && *s <= '9') val = *s - '0'; else BOOST_THROW_EXCEPTION(std::runtime_error("Unexpected character encountered in input.")); block *= 10; block += val; if (!*++s) { block_mult = block_multiplier(i); break; } } eval_multiply(result, block_mult); eval_add(result, block); } } } if (isneg) result.negate(); result.swap(*this); } public: cpp_int_backend& operator=(const char* s) { do_assign_string(s, trivial_tag()); return *this; } BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR void swap(cpp_int_backend& o) noexcept { this->do_swap(o); } private: std::string do_get_trivial_string(std::ios_base::fmtflags f, const std::integral_constant<bool, false>&) const { using io_type = typename std::conditional<sizeof(typename base_type::local_limb_type) == 1, unsigned, typename base_type::local_limb_type>::type; if (this->sign() && (((f & std::ios_base::hex) == std::ios_base::hex) || ((f & std::ios_base::oct) == std::ios_base::oct))) BOOST_THROW_EXCEPTION(std::runtime_error("Base 8 or 16 printing of negative numbers is not supported.")); std::stringstream ss; ss.flags(f & ~std::ios_base::showpos); ss << static_cast<io_type>(*this->limbs()); std::string result; if (this->sign()) result += '-'; else if (f & std::ios_base::showpos) result += '+'; result += ss.str(); return result; } std::string do_get_trivial_string(std::ios_base::fmtflags f, const std::integral_constant<bool, true>&) const { // Even though we have only one limb, we can't do IO on it :-( int base = 10; if ((f & std::ios_base::oct) == std::ios_base::oct) base = 8; else if ((f & std::ios_base::hex) == std::ios_base::hex) base = 16; std::string result; unsigned Bits = sizeof(typename base_type::local_limb_type) * CHAR_BIT; if (base == 8 || base == 16) { if (this->sign()) BOOST_THROW_EXCEPTION(std::runtime_error("Base 8 or 16 printing of negative numbers is not supported.")); limb_type shift = base == 8 ? 3 : 4; limb_type mask = static_cast<limb_type>((1u << shift) - 1); typename base_type::local_limb_type v = *this->limbs(); result.assign(Bits / shift + (Bits % shift ? 1 : 0), '0'); std::string::difference_type pos = result.size() - 1; char letter_a = f & std::ios_base::uppercase ? 'A' : 'a'; for (unsigned i = 0; i < Bits / shift; ++i) { char c = '0' + static_cast<char>(v & mask); if (c > '9') c += letter_a - '9' - 1; result[pos--] = c; v >>= shift; } if (Bits % shift) { mask = static_cast<limb_type>((1u << (Bits % shift)) - 1); char c = '0' + static_cast<char>(v & mask); if (c > '9') c += letter_a - '9'; result[pos] = c; } // // Get rid of leading zeros: // std::string::size_type n = result.find_first_not_of('0'); if (!result.empty() && (n == std::string::npos)) n = result.size() - 1; result.erase(0, n); if (f & std::ios_base::showbase) { const char* pp = base == 8 ? "0" : (f & std::ios_base::uppercase) ? "0X" : "0x"; result.insert(static_cast<std::string::size_type>(0), pp); } } else { result.assign(Bits / 3 + 1, '0'); std::string::difference_type pos = result.size() - 1; typename base_type::local_limb_type v(*this->limbs()); bool neg = false; if (this->sign()) { neg = true; } while (v) { result[pos] = (v % 10) + '0'; --pos; v /= 10; } std::string::size_type n = result.find_first_not_of('0'); result.erase(0, n); if (result.empty()) result = "0"; if (neg) result.insert(static_cast<std::string::size_type>(0), 1, '-'); else if (f & std::ios_base::showpos) result.insert(static_cast<std::string::size_type>(0), 1, '+'); } return result; } std::string do_get_string(std::ios_base::fmtflags f, const std::integral_constant<bool, true>&) const { #ifdef BOOST_MP_NO_DOUBLE_LIMB_TYPE_IO return do_get_trivial_string(f, std::integral_constant<bool, std::is_same<typename base_type::local_limb_type, double_limb_type>::value>()); #else return do_get_trivial_string(f, std::integral_constant<bool, false>()); #endif } std::string do_get_string(std::ios_base::fmtflags f, const std::integral_constant<bool, false>&) const { using default_ops::eval_get_sign; int base = 10; if ((f & std::ios_base::oct) == std::ios_base::oct) base = 8; else if ((f & std::ios_base::hex) == std::ios_base::hex) base = 16; std::string result; unsigned Bits = this->size() * base_type::limb_bits; if (base == 8 || base == 16) { if (this->sign()) BOOST_THROW_EXCEPTION(std::runtime_error("Base 8 or 16 printing of negative numbers is not supported.")); limb_type shift = base == 8 ? 3 : 4; limb_type mask = static_cast<limb_type>((1u << shift) - 1); cpp_int_backend t(*this); result.assign(Bits / shift + ((Bits % shift) ? 1 : 0), '0'); std::string::difference_type pos = result.size() - 1; char letter_a = f & std::ios_base::uppercase ? 'A' : 'a'; for (unsigned i = 0; i < Bits / shift; ++i) { char c = '0' + static_cast<char>(t.limbs()[0] & mask); if (c > '9') c += letter_a - '9' - 1; result[pos--] = c; eval_right_shift(t, shift); } if (Bits % shift) { mask = static_cast<limb_type>((1u << (Bits % shift)) - 1); char c = '0' + static_cast<char>(t.limbs()[0] & mask); if (c > '9') c += letter_a - '9'; result[pos] = c; } // // Get rid of leading zeros: // std::string::size_type n = result.find_first_not_of('0'); if (!result.empty() && (n == std::string::npos)) n = result.size() - 1; result.erase(0, n); if (f & std::ios_base::showbase) { const char* pp = base == 8 ? "0" : (f & std::ios_base::uppercase) ? "0X" : "0x"; result.insert(static_cast<std::string::size_type>(0), pp); } } else { result.assign(Bits / 3 + 1, '0'); std::string::difference_type pos = result.size() - 1; cpp_int_backend t(*this); cpp_int_backend r; bool neg = false; if (t.sign()) { t.negate(); neg = true; } if (this->size() == 1) { result = boost::lexical_cast<std::string>(t.limbs()[0]); } else { cpp_int_backend block10; block10 = max_block_10; while (eval_get_sign(t) != 0) { cpp_int_backend t2; divide_unsigned_helper(&t2, t, block10, r); t = t2; limb_type v = r.limbs()[0]; for (unsigned i = 0; i < digits_per_block_10; ++i) { char c = '0' + v % 10; v /= 10; result[pos] = c; if (pos-- == 0) break; } } } std::string::size_type n = result.find_first_not_of('0'); result.erase(0, n); if (result.empty()) result = "0"; if (neg) result.insert(static_cast<std::string::size_type>(0), 1, '-'); else if (f & std::ios_base::showpos) result.insert(static_cast<std::string::size_type>(0), 1, '+'); } return result; } public: std::string str(std::streamsize /*digits*/, std::ios_base::fmtflags f) const { return do_get_string(f, trivial_tag()); } private: template <class Container> void construct_from_container(const Container& c, const std::integral_constant<bool, false>&) { // // We assume that c is a sequence of (unsigned) bytes with the most significant byte first: // unsigned newsize = static_cast<unsigned>(c.size() / sizeof(limb_type)); if (c.size() % sizeof(limb_type)) { ++newsize; } if (newsize) { this->resize(newsize, newsize); // May throw std::memset(this->limbs(), 0, this->size()); typename Container::const_iterator i(c.begin()), j(c.end()); unsigned byte_location = static_cast<unsigned>(c.size() - 1); while (i != j) { unsigned limb = byte_location / sizeof(limb_type); unsigned shift = (byte_location % sizeof(limb_type)) * CHAR_BIT; if (this->size() > limb) this->limbs()[limb] |= static_cast<limb_type>(static_cast<unsigned char>(*i)) << shift; ++i; --byte_location; } } } template <class Container> BOOST_MP_CXX14_CONSTEXPR void construct_from_container(const Container& c, const std::integral_constant<bool, true>&) { // // We assume that c is a sequence of (unsigned) bytes with the most significant byte first: // using local_limb_type = typename base_type::local_limb_type; *this->limbs() = 0; if (c.size()) { typename Container::const_iterator i(c.begin()), j(c.end()); unsigned byte_location = static_cast<unsigned>(c.size() - 1); while (i != j) { unsigned limb = byte_location / sizeof(local_limb_type); unsigned shift = (byte_location % sizeof(local_limb_type)) * CHAR_BIT; if (limb == 0) this->limbs()[0] |= static_cast<limb_type>(static_cast<unsigned char>(*i)) << shift; ++i; --byte_location; } } } public: template <class Container> BOOST_MP_CXX14_CONSTEXPR cpp_int_backend(const Container& c, typename std::enable_if<boost::multiprecision::detail::is_byte_container<Container>::value>::type const* = 0) { // // We assume that c is a sequence of (unsigned) bytes with the most significant byte first: // construct_from_container(c, trivial_tag()); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare_imp(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o, const std::integral_constant<bool, false>&, const std::integral_constant<bool, false>&) const noexcept { if (this->sign() != o.sign()) return this->sign() ? -1 : 1; // Only do the compare if the same sign: int result = compare_unsigned(o); if (this->sign()) result = -result; return result; } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare_imp(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o, const std::integral_constant<bool, true>&, const std::integral_constant<bool, false>&) const { cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> t(*this); return t.compare(o); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare_imp(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o, const std::integral_constant<bool, false>&, const std::integral_constant<bool, true>&) const { cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> t(o); return compare(t); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare_imp(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o, const std::integral_constant<bool, true>&, const std::integral_constant<bool, true>&) const noexcept { if (this->sign()) { if (o.sign()) { return *this->limbs() < *o.limbs() ? 1 : (*this->limbs() > *o.limbs() ? -1 : 0); } else return -1; } else { if (o.sign()) return 1; return *this->limbs() < *o.limbs() ? -1 : (*this->limbs() > *o.limbs() ? 1 : 0); } } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o) const noexcept { using t1 = std::integral_constant<bool, is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value> ; using t2 = std::integral_constant<bool, is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>; return compare_imp(o, t1(), t2()); } template <unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> BOOST_MP_CXX14_CONSTEXPR int compare_unsigned(const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& o) const noexcept { if (this->size() != o.size()) { return this->size() > o.size() ? 1 : -1; } typename base_type::const_limb_pointer pa = this->limbs(); typename base_type::const_limb_pointer pb = o.limbs(); for (int i = this->size() - 1; i >= 0; --i) { if (pa[i] != pb[i]) return pa[i] > pb[i] ? 1 : -1; } return 0; } template <class Arithmetic> BOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<Arithmetic>::value, int>::type compare(Arithmetic i) const { // braindead version: cpp_int_backend t; t = i; return compare(t); } }; } // namespace backends namespace default_ops { template <class Backend> struct double_precision_type; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct double_precision_type<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > { using type = typename std::conditional< backends::is_fixed_precision<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value, backends::cpp_int_backend< (std::is_void<Allocator>::value ? 2 * backends::max_precision<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value : MinBits), 2 * backends::max_precision<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value, SignType, Checked, Allocator>, backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::type; }; } // namespace default_ops template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2> struct is_equivalent_number_type<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>, backends::cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> > : public std::integral_constant<bool, std::numeric_limits<number<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>, et_on> >::digits == std::numeric_limits<number<backends::cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>, et_on> >::digits>{}; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked> struct expression_template_default<backends::cpp_int_backend<MinBits, MaxBits, SignType, Checked, void> > { static constexpr const expression_template_option value = et_off; }; using boost::multiprecision::backends::cpp_int_backend; template <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator> struct number_category<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> > : public std::integral_constant<int, number_kind_integer> {}; using cpp_int = number<cpp_int_backend<> > ; using cpp_rational_backend = rational_adaptor<cpp_int_backend<> >; using cpp_rational = number<cpp_rational_backend> ; // Fixed precision unsigned types: using uint128_t = number<cpp_int_backend<128, 128, unsigned_magnitude, unchecked, void> > ; using uint256_t = number<cpp_int_backend<256, 256, unsigned_magnitude, unchecked, void> > ; using uint512_t = number<cpp_int_backend<512, 512, unsigned_magnitude, unchecked, void> > ; using uint1024_t = number<cpp_int_backend<1024, 1024, unsigned_magnitude, unchecked, void> >; // Fixed precision signed types: using int128_t = number<cpp_int_backend<128, 128, signed_magnitude, unchecked, void> > ; using int256_t = number<cpp_int_backend<256, 256, signed_magnitude, unchecked, void> > ; using int512_t = number<cpp_int_backend<512, 512, signed_magnitude, unchecked, void> > ; using int1024_t = number<cpp_int_backend<1024, 1024, signed_magnitude, unchecked, void> >; // Over again, but with checking enabled this time: using checked_cpp_int = number<cpp_int_backend<0, 0, signed_magnitude, checked> > ; using checked_cpp_rational_backend = rational_adaptor<cpp_int_backend<0, 0, signed_magnitude, checked> >; using checked_cpp_rational = number<checked_cpp_rational_backend> ; // Fixed precision unsigned types: using checked_uint128_t = number<cpp_int_backend<128, 128, unsigned_magnitude, checked, void> > ; using checked_uint256_t = number<cpp_int_backend<256, 256, unsigned_magnitude, checked, void> > ; using checked_uint512_t = number<cpp_int_backend<512, 512, unsigned_magnitude, checked, void> > ; using checked_uint1024_t = number<cpp_int_backend<1024, 1024, unsigned_magnitude, checked, void> >; // Fixed precision signed types: using checked_int128_t = number<cpp_int_backend<128, 128, signed_magnitude, checked, void> > ; using checked_int256_t = number<cpp_int_backend<256, 256, signed_magnitude, checked, void> > ; using checked_int512_t = number<cpp_int_backend<512, 512, signed_magnitude, checked, void> > ; using checked_int1024_t = number<cpp_int_backend<1024, 1024, signed_magnitude, checked, void> >; #ifdef _MSC_VER #pragma warning(pop) #endif }} // namespace boost::multiprecision // // Last of all we include the implementations of all the eval_* non member functions: // #include <boost/multiprecision/cpp_int/limits.hpp> #include <boost/multiprecision/cpp_int/comparison.hpp> #include <boost/multiprecision/cpp_int/add.hpp> #include <boost/multiprecision/cpp_int/multiply.hpp> #include <boost/multiprecision/cpp_int/divide.hpp> #include <boost/multiprecision/cpp_int/bitwise.hpp> #include <boost/multiprecision/cpp_int/misc.hpp> #include <boost/multiprecision/cpp_int/literals.hpp> #include <boost/multiprecision/cpp_int/serialize.hpp> #include <boost/multiprecision/cpp_int/import_export.hpp> #endif
[ "noreply@github.com" ]
noreply@github.com
edcc2d50dc63c57962a47bcfebb65dca81e277d1
6b85398bd278e55532a9eb14a63f073c585da02e
/lab2/func.cpp
da28cadcc260ca0917c90f579b05b19dbabe6fcc
[]
no_license
castlesofplacebo/programming-Cpp
80c99f35e3eecaee5da01e3ae0215ce33417e63a
89a04a18a8614098de25f6c2ebfa367297437b74
refs/heads/master
2023-04-06T13:25:55.648685
2021-04-11T20:55:29
2021-04-11T20:55:29
356,977,185
0
0
null
null
null
null
UTF-8
C++
false
false
2,595
cpp
#include "head.h" #include <iostream> using namespace std; //Конструкторы : По умолчанию squarePolynomial::squarePolynomial() : a_(0), b_(0), c_(0) { } //Конструкторы :Копирования три вещественных числа squarePolynomial::squarePolynomial(double a, double b, double c) : a_(a), b_(b), c_(c) { } squarePolynomial &squarePolynomial::operator=(const squarePolynomial &current) { if (this != &current) { this->a_ = current.a_; this->b_ = current.b_; this->c_ = current.c_; } return *this; } //Деструктор squarePolynomial::~squarePolynomial() = default; //Функциональность : Вычисления значения в заданной точке double squarePolynomial::inPoint(double x) { return (a_ * x * x) + (b_ * x) + c_; } //Функциональность : Нахождения количества корней unsigned squarePolynomial::countOfRoots() { if (((b_ * b_) - (4 * a_ * c_)) > 0) return 2; else if (((b_ * b_) - (4 * a_ * c_)) == 0) return 1; else return 0; } //Функциональность : Нахождение корней void squarePolynomial::rootsInPolynomial() { double d = ((b_ * b_) - (4 * a_ * c_)); if (d >= 0) { if (d == 0) cout << -b_ / (2 * a_) << endl; else { cout << (-b_ + d) / (2 * a_) << '\t'; cout << (-b_ - d) / (2 * a_) << endl; } } else cout << "NO REAL ROOTS" << endl; } //Функциональность : Нахождение максимума/минимума void squarePolynomial::maxOrMin() { if (a_ == 0) cout << "NO MAX OR MIN" << endl; else { double x = (-b_) / (2 * a_); cout << (a_ * x * x + b_ * x + c_) << endl; } } //Функциональность : Вывод на экран void squarePolynomial::onScreen() { cout << a_ << " * x^2 + " << b_ << " * x + " << c_ << endl; } //Конструкторы : Присваивания квадратного многочлена squarePolynomial::squarePolynomial(const squarePolynomial &s) { a_ = s.a_; b_ = s.b_; c_ = s.c_; } void start() { cout << "CHOOSE ONE ACTION WITH SQUARE POLYNOMIAL: \n " << "1 - CALCULATE A VALUE AT THE POINT \n" << "2 - FINDING THE NUMBER OF ROOTS \n" << "3 - FINDING THE ROOOTS \n" << "4 - FINDING THE EXTREMUMS \n" << "5 - OUTPUT POLYNOMIAL ON THE SCREEN \n" << "0 - EXIT \n"; }
[ "castlesofplacebo@gmail.com" ]
castlesofplacebo@gmail.com
48898a4d91e48d2b51d00df50eba02c1292240a5
cd7cc68283bf1044e3f9d98420ba83f7dcd279b5
/src/Skeleton.h
9123a7f414c4345f74c4649b520b66c264822a2a
[ "MIT" ]
permissive
atomul/Arduino-Skeletron
d7d85af00472e4a882c286e582e8098bc60540b6
59582aa23ab507e54de0f9893cc2ff4b09014e23
refs/heads/master
2022-01-12T17:25:55.244622
2022-01-01T12:32:57
2022-01-01T12:32:57
137,406,696
0
0
null
null
null
null
UTF-8
C++
false
false
991
h
#pragma once #include "Core/Components/Buttons/Button.h" #include "Core/Components/Buttons/SwitchButton.h" class LED; class Skeleton : public IButtonObserver , public ISwitchButtonObserver { public: Skeleton(); ~Skeleton(); void SetupEyes(); void SetupMouth(); void SetupButtons(); void TurnOnRedEyes(); void TurnOnGreenEyes(); void TurnOffRedEyes(); void TurnOffGreenEyes(); void Update(); private: void OnButtonClick(uint32_t buttonId) override final; void OnButtonDown(uint32_t buttonId) override final; void OnButtonHold(uint32_t buttonId) override final; void OnButtonUp(uint32_t buttonId) override final; void OnSwitchOn(uint32_t buttonId) override final; void OnSwitchOff(uint32_t buttonId) override final; private: uint8_t m_delay; bool m_isEnabled; LED* m_LEDLeftEye_red; LED* m_LEDLeftEye_green; LED* m_LEDRightEye_red; LED* m_LEDRightEye_green; Button* m_buttonIncreaseSpeed; Button* m_buttonDecreaseSpeed; SwitchButton* m_buttonStartStop; };
[ "petredaniel.puiu@yahoo.ro" ]
petredaniel.puiu@yahoo.ro
78d0a1388501b18a9a8622266415d84739d552e8
79c4bbdf1695896f0bfd1ad3a36c605c0449442f
/cf/467C.cpp
e808150bb8b945c6ef0adca2d0675bb6ad50ec3d
[]
no_license
jlgm/Algo
935c130c7f21d1a8d1a5ab29c9b7a1f73dcb9303
19e9b4ef0ae5b0f58bc68bb9dae21354c77829e5
refs/heads/master
2022-09-24T15:58:59.522665
2022-09-15T17:05:42
2022-09-15T17:05:42
77,110,537
6
0
null
null
null
null
UTF-8
C++
false
false
914
cpp
#pragma comment(linker, "/STACK:16777216") #include <bits/stdc++.h> using namespace std; #define ms(ar,a) memset(ar, a, sizeof(ar)) #define fr(i,j,k) for (int (i) = (j); (i) < (k); (i)++) #define db(x) cout << (#x) << " = " << x << endl; #define pb push_back #define mp make_pair #define X first #define Y second typedef long long ll; typedef pair<int, int> pii; template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); } ll n, m, k, a[5005], s[5005], dp[5005][5005]; ll solve(ll K, ll N) { ll &ret = dp[K][N]; if (ret != -1) return ret; if (K >= k) return 0; if (N >= n) return 0; return ret = max(s[N] + solve(K+1, N+m), solve(K,N+1)); } int main() { scanf("%lld%lld%lld", &n, &m, &k); fr(i,0,n) scanf("%lld", &a[i]); fr(i,0,n-m+1) fr(j,0,m) s[i] += a[i+j]; ms(dp,-1); printf("%lld\n", solve(0,0)); return 0; }
[ "jlgm@cin.ufpe.br" ]
jlgm@cin.ufpe.br
1ff805bc6312272f5efb5f9ebf1f2012f6aa9ca7
75bf41a5ebef61fd0a508b13790da2c5d47b0032
/Source/GoblinDisk.h
4096367cabee6721638e530eeb83dd46928c6ad5
[]
no_license
neodyme60/Goblin
30120277dba9c41895e3ddd0ec8de4b1e09671c3
fd1bdd4b9da6e0bfd1ef7d05718231b8df7cc925
refs/heads/master
2021-01-22T21:49:14.011590
2017-02-23T07:12:26
2017-02-23T07:12:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,656
h
#ifndef GOBLIN_DISK_H #define GOBLIN_DISK_H #include "GoblinGeometry.h" #include "GoblinFactory.h" namespace Goblin { class Disk : public Geometry { public: Disk(float r, size_t numSlices = 30); ~Disk() {}; void init(); bool intersect(const Ray& ray) const; bool intersect(const Ray& ray, float* epsilon, Fragment* fragment) const; Vector3 sample(float u1, float u2, Vector3* normal) const; float area() const; BBox getObjectBound() const; size_t getVertexNum() const; size_t getFaceNum() const; const Vertex* getVertexPtr(size_t index) const; const TriangleIndex* getFacePtr(size_t index) const; private: void buildSlices(); private: float mRadius; size_t mNumSlices; VertexList mVertices; TriangleList mTriangles; }; inline float Disk::area() const { return PI * mRadius * mRadius; } inline size_t Disk::getVertexNum() const { return mVertices.size(); } inline size_t Disk::getFaceNum() const { return mTriangles.size(); } inline const Vertex* Disk::getVertexPtr(size_t index) const { return &mVertices[index]; } inline const TriangleIndex* Disk::getFacePtr(size_t index) const { return &mTriangles[index]; } class ParamSet; class SceneCache; class DiskGeometryCreator : public Creator<Geometry, const ParamSet&, const SceneCache&> { public: Geometry* create(const ParamSet& params, const SceneCache&sceneCache) const; }; } #endif //GOBLIN_DISK_H
[ "bachi95tw@gmail.com" ]
bachi95tw@gmail.com
13c7e317a226b23b31dc2811772c45458ea6c724
d6097b678c734dcb2efb858dc9b142c121c5b533
/system/os_platform/mac_sdl/source/sdlhal.h
892fa71e2602aaab959a818d5d4dc7a3d0728795
[]
no_license
mizbit/LA104
4e3e88ed2b383052d62ab3b7c7e987557461129a
8e696f91f064595545d3017b7949b44292515971
refs/heads/master
2021-01-15T07:26:40.764397
2020-02-13T22:49:17
2020-02-13T22:49:17
242,914,079
1
0
null
2020-02-25T05:01:02
2020-02-25T05:01:01
null
UTF-8
C++
false
false
6,111
h
#include "../../common/source/bios/Bios.h" void setPixel(int x, int y, int c); int getPixel(int x, int y); bool sdl_running(); int sdl_lastKey(); void sdl_loop(); class CSdlHal : public CHal { int fd; virtual void SetPixel(int x, int y, uint16_t c) override { setPixel(x, y, c); } virtual uint16_t GetPixel(int x, int y) override { return getPixel(x, y); } virtual bool IsRunning() override { sdl_loop(); return sdl_running(); } virtual char GetKey() override { switch (sdl_lastKey()) { case SDL_SCANCODE_LEFT: return '-'; break; case SDL_SCANCODE_RIGHT: return '+'; break; case SDL_SCANCODE_UP: return '<'; break; case SDL_SCANCODE_DOWN: return '>'; break; case SDL_SCANCODE_RETURN: return '1'; break; case SDL_SCANCODE_BACKSPACE: return '2'; break; //case SDL_SCANCODE_BACKSPACE: return '3'; break; } return 0; } #ifdef LA104 virtual void UartSetup(int baudrate, BIOS::GPIO::UART::EConfig config) override { #ifdef USEUART // Open port fd = open("/dev/tty.usbmodemLA104CDC", O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1){ printf("Device cannot be opened.\n"); exit(-1); // If the device is not open, return -1 } struct termios options; fcntl(fd, F_SETFL, FNDELAY); // Open the device in nonblocking mode // Set parameters tcgetattr(fd, &options); // Get the current options of the port bzero(&options, sizeof(options)); // Clear all the options speed_t Speed; switch (baudrate) // Set the speed (baudRate) { case 110 : Speed=B110; break; case 300 : Speed=B300; break; case 600 : Speed=B600; break; case 1200 : Speed=B1200; break; case 2400 : Speed=B2400; break; case 4800 : Speed=B4800; break; case 9600 : Speed=B9600; break; case 19200 : Speed=B19200; break; case 38400 : Speed=B38400; break; case 57600 : Speed=B57600; break; case 115200 : Speed=B115200; break; default : exit(-4); } cfsetispeed(&options, Speed); // Set the baud rate at 115200 bauds cfsetospeed(&options, Speed); options.c_cflag |= ( CLOCAL | CREAD | CS8); // Configure the device : 8 bits, no parity, no control options.c_iflag |= ( IGNPAR | IGNBRK ); options.c_cc[VTIME]=0; // Timer unused options.c_cc[VMIN]=0; // At least on character before satisfy reading tcsetattr(fd, TCSANOW, &options); // Activate the settings #endif } virtual void UartClose() override { #ifdef USEUART close(fd); fd = 0; #endif } virtual bool UartAvailable() override { #ifdef USEUART int count; ioctl(fd, FIONREAD, &count); return count>0; #else return false; #endif } virtual uint8_t UartRead() override { #ifdef USEUART uint8_t data; _ASSERT(read(fd, &data, 1) == 1); return data; #else return 0; #endif } virtual void UartWrite(uint8_t data) override { #ifdef USEUART _ASSERT(write(fd, &data, 1) == 1); #endif } #endif // SYS virtual void Delay(int intervalMs) override { SDL_Delay(intervalMs); } virtual uint32_t GetTick() override { return SDL_GetTicks(); } #if 0 // FAT virtual bool FatInit() override { return true; } virtual bool FatOpen(const char* strName, ui8 nIoMode) override { if (nIoMode == BIOS::FAT::IoRead) { f = fopen(strName, "rb"); return !!f; } if (nIoMode == BIOS::FAT::IoWrite) { f = fopen(strName, "wb"); return !!f; } return false; } virtual bool FatRead(uint8_t* pSectorData, int length) override { fread(pSectorData, length, 1, f); return true; } virtual bool FatWrite(uint8_t* pSectorData, int length) override { fwrite(pSectorData, length, 1, f); return true; } virtual bool FatClose() override { fclose(f); return true; } virtual bool FatOpenDir(char* strPath) override { char fullPath[512]; #ifdef __APPLE__ static char* rootPath = (char*)"/Users/gabrielvalky/Documents/git/LA104/system/release/"; if (strPath[0] == '/') strcpy(fullPath, strPath); else { strcpy(fullPath, rootPath); for (int i=0; i<strlen(strPath); i++) strPath[i] = tolower(strPath[i]); strcat(fullPath, strPath); } #else strcpy(fullPath, strPath); #endif dirp = opendir(fullPath); return !!dirp; } virtual bool FatFindNext(BIOS::FAT::TFindFile* pFile) override { struct dirent * dp; dp = readdir(dirp); if (!dp) { closedir(dirp); return false; } pFile->nAtrib = dp->d_type & DT_DIR ? BIOS::FAT::EAttribute::EDirectory : BIOS::FAT::EAttribute::EArchive; pFile->nFileLength = 0; strcpy(pFile->strName, dp->d_name); return true; } virtual uint32_t FatGetFileSize() override { int prev = ftell(f); fseek(f, 0, SEEK_END); int len = ftell(f); fseek(f, prev, SEEK_SET); return len; } virtual bool FatSeek(uint32_t offset) override { fseek(f, offset, SEEK_SET); return true; } #endif virtual void FlashRead(uint8_t* buff, int offset, int length) {} virtual void FlashWrite(const uint8_t* buff, int offset, int length) {} };
[ "gvalky@sygic.com" ]
gvalky@sygic.com
51f95b94a312705a4bd9bf39a90f0f9c6ced8014
4fd5aae8fd9e8c0f2bcd41661eeeb8e4d1d2eacf
/src/providers/nordvpn/nvpnserver.cpp
72882c587285a2d9b53af631070c3496bbbd0f50
[ "MIT" ]
permissive
eliasrm87/VpnManager
cde5c026e6d268086f5b1f2968363dd35e964ffd
21d6a6e8f1e463c3e85f5e6a1ae131a0f9ce6d10
refs/heads/master
2021-11-04T11:01:46.672213
2019-04-27T21:01:11
2019-04-27T21:02:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
376
cpp
#include "nvpnserver.h" NvpnServer::NvpnServer(const QJsonObject &data, QObject *parent) : AbstractServer(data, parent) { } QString NvpnServer::hostName() { return properties_.value("domain").toString(); } QString NvpnServer::city() { return properties_.value("name").toString(); } int NvpnServer::capacity() { return properties_.value("load").toInt(); }
[ "elias@eliasrm.es" ]
elias@eliasrm.es
3d6001b7d54f2a553fa4128fdd908d4c5cb2f4b7
01dbe06e8ad0d7da2635604650edbbd8f1dd5cf8
/cpp/src/external/lisp/sexpr/value.cpp
b647d702cf7eafcadf033a720dd75f606a9c7bd5
[ "BSL-1.0", "LicenseRef-scancode-proprietary-license" ]
permissive
scignscape/SubjectiveSpeechQualityMeasurement
ccfe93d4569d45d711eb6a92c842cac9ae4a5404
ab68b91108f3f1d7086ea1ac9a8801c063dc9bff
refs/heads/master
2020-04-04T11:24:26.062577
2018-12-02T04:44:44
2018-12-02T04:44:44
155,889,835
0
1
BSL-1.0
2018-11-13T17:09:00
2018-11-02T16:02:47
C++
UTF-8
C++
false
false
1,289
cpp
// SExp - A S-Expression Parser for C++ // Copyright (C) 2006 Matthias Braun <matze@braunis.de> // 2015 Ingo Ruhnke <grumbel@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "sexp/value.hpp" #include <sstream> #include "sexp/io.hpp" namespace sexp { std::string Value::str_with_indent(int indent) const { std::ostringstream os; #ifdef SEXP_USE_LOCALE os.imbue(std::locale::classic()); #endif write_with_indent(os, *this, indent); return os.str(); } std::string Value::str() const { std::ostringstream os; #ifdef SEXP_USE_LOCALE os.imbue(std::locale::classic()); #endif os << *this; return os.str(); } } // namespace sexp /* EOF */
[ "osrworkshops@gmail.com" ]
osrworkshops@gmail.com
b2393b0821e10956e2de9f77f2019158fcf210c4
1de331d068456cedbd2a5b4d4a6b16145646f97d
/src/libv/ui/core_component.hpp
0a6fd1a5b5b74f14007c99d1fa1f161149204515
[ "Zlib" ]
permissive
sheerluck/libv
ed37015aeeb49ea8504d7b3aa48a69bde754708f
293e382f459f0acbc540de8ef6283782b38d2e63
refs/heads/master
2023-05-26T01:18:50.817268
2021-04-18T01:06:51
2021-04-27T03:20:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,895
hpp
// Project: libv.ui, File: src/libv/ui/core_component.hpp, Author: Császár Mátyás [Vader] #pragma once // libv #include <libv/math/vec.hpp> #include <libv/utility/function_ref.hpp> #include <libv/utility/intrusive_ptr.hpp> #include <libv/utility/observer_ptr.hpp> #include <libv/utility/observer_ref.hpp> // std #include <string> #include <string_view> #include <typeindex> // pro #include <libv/ui/flag.hpp> #include <libv/ui/generate_name.hpp> #include <libv/ui/property.hpp> // TODO P1: Remove property.hpp from here (the variant is killing me) #include <libv/ui/property/anchor.hpp> #include <libv/ui/property/margin.hpp> #include <libv/ui/property/padding.hpp> #include <libv/ui/property/size.hpp> #include <libv/ui/style_fwd.hpp> namespace libv { namespace ui { // ------------------------------------------------------------------------------------------------- //class ContextRender; class Component; class ContextFocusTraverse; class ContextLayout1; class ContextLayout2; class ContextStyle; class ContextUI; class EventChar; class EventFocus; class EventKey; class EventMouseButton; class EventMouseMovement; class EventMouseScroll; class Renderer; // ------------------------------------------------------------------------------------------------- using ChildID = int32_t; static constexpr ChildID ChildIDSelf = -2; static constexpr ChildID ChildIDNone = -1; class CoreComponent { friend struct AccessConnect; friend struct AccessEvent; friend struct AccessLayout; friend struct AccessParent; friend struct AccessProperty; friend struct AccessRoot; friend class Component; private: Flag_t flags = Flag::mask_init; ChildID childID = 0; uint32_t ref_count = 0; libv::vec3f layout_position_; /// Component position relative to parent in pixels libv::vec3f layout_size_; /// Component size in pixels private: Size size_; Anchor anchor_; libv::vec4f margin_; /// x: left, y: down, z: right, w: top libv::vec4f padding_; /// x: left, y: down, z: right, w: top // libv::vec4f margin_{10, 10, 10, 10}; // Theme::default_margin // libv::vec4f padding_{5, 5, 5, 5}; // Theme::default_padding private: /// Never null, points to self if its a (temporal) root element otherwise points to parent libv::observer_ref<CoreComponent> parent_ = libv::make_observer_ref(this); /// Never null, points to the associated context libv::observer_ref<ContextUI> context_; /// Null if no style is assigned to the component libv::intrusive_ptr<Style> style_; public: std::string name; public: explicit CoreComponent(std::string name); explicit CoreComponent(GenerateName_t, const std::string_view type, size_t index); CoreComponent(const CoreComponent&) = delete; CoreComponent(CoreComponent&&) = delete; CoreComponent& operator=(const CoreComponent&) = delete; CoreComponent& operator=(CoreComponent&&) = delete; virtual ~CoreComponent(); public: [[nodiscard]] inline libv::observer_ref<CoreComponent> parent() const noexcept { return parent_; } [[nodiscard]] std::string path() const; [[nodiscard]] inline ContextUI& context() const noexcept { return *context_; } [[nodiscard]] inline bool isAttached() const noexcept { return parent_ != this; } [[nodiscard]] inline bool isRendered() const noexcept { return flags.match_any(Flag::render); } [[nodiscard]] inline bool isLayouted() const noexcept { return flags.match_any(Flag::layout); } [[nodiscard]] inline bool isFocused() const noexcept { return flags.match_any(Flag::focused); } [[nodiscard]] inline libv::vec3f layout_position() const noexcept { return layout_position_; } [[nodiscard]] inline libv::vec2f layout_position2() const noexcept { return libv::vec2f{layout_position_.x, layout_position_.y}; } [[nodiscard]] inline libv::vec3f layout_size() const noexcept { return layout_size_; } [[nodiscard]] inline libv::vec2f layout_size2() const noexcept { return libv::vec2f{layout_size_.x, layout_size_.y}; } public: [[nodiscard]] inline const Size& size() const noexcept { return size_; } void size(Size value) noexcept; [[nodiscard]] inline Anchor anchor() const noexcept { return anchor_; } inline void anchor(Anchor value) noexcept { anchor_ = value; flagAuto(Flag::pendingLayout | Flag::pendingRender); } inline void margin(Margin value) noexcept { margin_ = value; flagAuto(Flag::pendingLayout | Flag::pendingRender); } inline void margin(float left_down_right_top) noexcept { margin({left_down_right_top, left_down_right_top, left_down_right_top, left_down_right_top}); } inline void margin(float left_right, float down_top) noexcept { margin({left_right, down_top, left_right, down_top}); } inline void margin(float left, float down, float right, float top) noexcept { margin({left, down, right, top}); } /// x: left, y: down, z: right, w: top [[nodiscard]] inline Margin margin() const noexcept { return margin_; } /// x: left, y: down [[nodiscard]] inline libv::vec2f margin_LB() const noexcept { return xy(margin_); } /// x: left, y: down, z: 0 [[nodiscard]] inline libv::vec3f margin_LB3() const noexcept { return {margin_LB(), 0.0f}; } /// x: right, y: top [[nodiscard]] inline libv::vec2f margin_RT() const noexcept { return zw(margin_); } /// x: right, y: top, z: 0 [[nodiscard]] inline libv::vec3f margin_RT3() const noexcept { return {margin_RT(), 0.0f}; } /// x: left + right, y: down + top [[nodiscard]] inline libv::vec2f margin_size() const noexcept { return margin_LB() + margin_RT(); } /// x: left + right, y: down + top, z: 0 [[nodiscard]] inline libv::vec3f margin_size3() const noexcept { return {margin_size(), 0.0f}; } inline void padding(Padding value) noexcept { padding_ = value; flagAuto(Flag::pendingLayout | Flag::pendingRender); } inline void padding(float left_down_right_top) noexcept { padding({left_down_right_top, left_down_right_top, left_down_right_top, left_down_right_top}); } inline void padding(float left_right, float down_top) noexcept { padding({left_right, down_top, left_right, down_top}); } inline void padding(float left, float down, float right, float top) noexcept { padding({left, down, right, top}); } /// x: left, y: down, z: right, w: top [[nodiscard]] inline Padding padding() const noexcept { return padding_; } /// x: left, y: down [[nodiscard]] inline libv::vec2f padding_LB() const noexcept { return xy(padding_); } /// x: left, y: down, z: 0 [[nodiscard]] inline libv::vec3f padding_LB3() const noexcept { return {padding_LB(), 0.0f}; } /// x: right, y: top [[nodiscard]] inline libv::vec2f padding_RT() const noexcept { return zw(padding_); } /// x: right, y: top, z: 0 [[nodiscard]] inline libv::vec3f padding_RT3() const noexcept { return {padding_RT(), 0.0f}; } /// x: left + right, y: down + top [[nodiscard]] inline libv::vec2f padding_size() const noexcept { return padding_LB() + padding_RT(); } /// x: left + right, y: down + top, z: 0 [[nodiscard]] inline libv::vec3f padding_size3() const noexcept { return {padding_size(), 0.0f}; } public: template <typename T> void access_properties(T& ctx); protected: void flagDirect(Flag_t flags_) noexcept; void flagAncestors(Flag_t flags_) noexcept; public: void flagAuto(Flag_t flags_) noexcept; void flagForce(Flag_t flags_) noexcept; private: void flagPurge(Flag_t flags_) noexcept; protected: void watchChar(bool value) noexcept; void watchKey(bool value) noexcept; void watchFocus(bool value) noexcept; void watchMouse(bool value) noexcept; void floatRegion(bool value) noexcept; [[nodiscard]] bool isWatchChar() const noexcept; [[nodiscard]] bool isWatchKey() const noexcept; [[nodiscard]] bool isWatchFocus() const noexcept; [[nodiscard]] bool isWatchMouse() const noexcept; public: [[nodiscard]] bool isFloatRegion() const noexcept; public: void focus() noexcept; void markRemove() noexcept; void style(libv::intrusive_ptr<Style> style) noexcept; public: template <typename Property> inline void set(Property& property, typename Property::value_type value); template <typename Property> inline void reset(Property& property); private: void _fire(std::type_index type, const void* event_ptr); public: template <typename Event> inline void fire(const Event& event); private: static void connect(CoreComponent& signal, CoreComponent& slot, std::type_index type, std::function<void(void*, const void*)>&& callback); private: ContextStyle makeStyleContext() noexcept; private: bool isFocusableComponent() const noexcept; private: static void eventChar(CoreComponent& component, const EventChar& event); static void eventKey(CoreComponent& component, const EventKey& event); static void focusGain(CoreComponent& component); static void focusLoss(CoreComponent& component); private: virtual void onChar(const EventChar& event); virtual void onKey(const EventKey& event); virtual void onFocus(const EventFocus& event); virtual void onMouseButton(const EventMouseButton& event); virtual void onMouseMovement(const EventMouseMovement& event); virtual void onMouseScroll(const EventMouseScroll& event); private: void attach(CoreComponent& parent); void detach(CoreComponent& parent); void style(); void styleScan(); libv::observer_ptr<CoreComponent> focusTraverse(const ContextFocusTraverse& context); libv::vec3f layout1(const ContextLayout1& environment); void layout2(const ContextLayout2& environment); void render(Renderer& r); private: virtual void doAttach(); virtual void doDetach(); virtual void doDetachChildren(libv::function_ref<bool(Component&)> callback); virtual void doStyle(ContextStyle& context); virtual void doStyle(ContextStyle& context, ChildID childID); virtual libv::observer_ptr<CoreComponent> doFocusTraverse(const ContextFocusTraverse& context, ChildID current); virtual libv::vec3f doLayout1(const ContextLayout1& environment); virtual void doLayout2(const ContextLayout2& environment); virtual void doCreate(Renderer& r); virtual void doRender(Renderer& r); virtual void doDestroy(Renderer& r); virtual void doForeachChildren(libv::function_ref<bool(Component&)> callback); virtual void doForeachChildren(libv::function_ref<void(Component&)> callback); }; // ------------------------------------------------------------------------------------------------- // TODO P2: libv.ui: Remove set/reset from here (?) template <typename Property> inline void CoreComponent::set(Property& property, typename Property::value_type value) { AccessProperty::driver(property, PropertyDriver::manual); if (value != property()) AccessProperty::value(*this, property, std::move(value)); } template <typename Property> inline void CoreComponent::reset(Property& property) { AccessProperty::driver(property, PropertyDriver::style); flagAuto(Flag::pendingStyle); } // ------------------------------------------------------------------------------------------------- template <typename EventT> inline void CoreComponent::fire(const EventT& event) { _fire(std::type_index(typeid(EventT)), &event); } // ------------------------------------------------------------------------------------------------- template <typename T> void CoreComponent::access_properties(T& ctx) { ctx.synthetize( [](auto& c, auto v) { c.size(v); }, [](const auto& c) { return c.size(); }, pgr::layout, pnm::size, "Component size in pixel, percent, ratio and dynamic units" ); ctx.synthetize( [](auto& c, auto v) { c.anchor(v); }, [](const auto& c) { return c.anchor(); }, pgr::layout, pnm::anchor, "Component's anchor point" ); ctx.synthetize( [](auto& c, auto v) { c.margin(v); }, [](const auto& c) { return c.margin(); }, pgr::layout, pnm::margin, "Component's margin" ); ctx.synthetize( [](auto& c, auto v) { c.padding(v); }, [](const auto& c) { return c.padding(); }, pgr::layout, pnm::padding, "Component's padding" ); } // ------------------------------------------------------------------------------------------------- struct AccessEvent { static inline decltype(auto) onMouseButton(CoreComponent& component, const EventMouseButton& event) { return component.onMouseButton(event); } static inline decltype(auto) onMouseMovement(CoreComponent& component, const EventMouseMovement& event) { return component.onMouseMovement(event); } static inline decltype(auto) onMouseScroll(CoreComponent& component, const EventMouseScroll& event) { return component.onMouseScroll(event); } }; struct AccessParent { [[nodiscard]] static inline auto& childID(CoreComponent& component) noexcept { return component.childID; } [[nodiscard]] static inline const auto& childID(const CoreComponent& component) noexcept { return component.childID; } static inline decltype(auto) isFocusableComponent(const CoreComponent& component) { return component.isFocusableComponent(); } static inline decltype(auto) isFocusableChild(const CoreComponent& component) { return component.flags.match_any(Flag::focusableChild); } static inline decltype(auto) doFocusTraverse(CoreComponent& component, const ContextFocusTraverse& context, ChildID current) { return component.doFocusTraverse(context, current); } static inline decltype(auto) render(CoreComponent& component, Renderer& r) { return component.render(r); } }; struct AccessConnect { static inline void connect(CoreComponent& signal, CoreComponent& slot, std::type_index type, std::function<void(void*, const void*)>&& callback) { CoreComponent::connect(signal, slot, type, std::move(callback)); } }; struct AccessLayout { static inline decltype(auto) layout1(CoreComponent& component, const ContextLayout1& environment) { return component.layout1(environment); } static inline decltype(auto) layout2(CoreComponent& component, const ContextLayout2& environment) { return component.layout2(environment); } }; struct AccessRoot : AccessEvent, AccessLayout, AccessParent { [[nodiscard]] static inline auto& layout_position(CoreComponent& component) noexcept { return component.layout_position_; } [[nodiscard]] static inline const auto& layout_position(const CoreComponent& component) noexcept { return component.layout_position_; } [[nodiscard]] static inline auto& layout_size(CoreComponent& component) noexcept { return component.layout_size_; } [[nodiscard]] static inline const auto& layout_size(const CoreComponent& component) noexcept { return component.layout_size_; } static inline decltype(auto) flagAuto(CoreComponent& component, Flag_t flags_) noexcept { return component.flagAuto(flags_); } static inline decltype(auto) eventChar(CoreComponent& component, const EventChar& event) { return CoreComponent::eventChar(component, event); } static inline decltype(auto) eventKey(CoreComponent& component, const EventKey& event) { return CoreComponent::eventKey(component, event); } static inline decltype(auto) attach(CoreComponent& component, CoreComponent& parent) { return component.attach(parent); } static inline decltype(auto) detach(CoreComponent& component, CoreComponent& parent) { return component.detach(parent); } static inline decltype(auto) style(CoreComponent& component) { return component.style(); } static inline decltype(auto) styleScan(CoreComponent& component) { return component.styleScan(); } static inline decltype(auto) focusGain(CoreComponent& component) { return CoreComponent::focusGain(component); } static inline decltype(auto) focusLoss(CoreComponent& component) { return CoreComponent::focusLoss(component); } static inline decltype(auto) focusTraverse(CoreComponent& component, const ContextFocusTraverse& context) { return component.focusTraverse(context); } }; // ------------------------------------------------------------------------------------------------- } // namespace ui } // namespace libv
[ "vaderhun@gmail.com" ]
vaderhun@gmail.com
c4c00860d887fcb84589825e83f6ee723832ec0b
cb4b79040dd3f66979691f251f05fcf718b8700d
/Classes/Model/Model.cpp
fc68646bfacc7283a700cb130984055a9423ac0e
[]
no_license
Cz865342/object
19b536d5cecc1625f5c9e6c7b4aa040c94fbbe68
6a8232ad0b0d2b7b4c65a66a5bd0e3265e4edf5a
refs/heads/master
2020-06-02T10:16:44.514162
2019-06-09T03:35:45
2019-06-09T03:35:45
191,125,004
0
0
null
2019-06-10T08:09:54
2019-06-10T08:09:53
null
UTF-8
C++
false
false
698
cpp
#include"Model.h" Model::Model() { } Model::~Model() { } bool Model::init() { return false; } const std::string & Model::getName() { return _name; } void Model::setName(const std::string _string) { _name = _string; } bool Model::isDie() { return this->getCurrentHp() <= 0; } void Model::attacked(float delta) { this->setCurrentHp(this->getCurrentHp() - delta); } void Model::setDirction_image() { std::string dir[8] = { "Up","Down","Left","Right","Left-Up","Left-Down","Right-Up","Right-Down" }; for (int i = 0; i < 8; i++) { dirction_image[dir[i]] = cocos2d::StringUtils::format("%s/%s/Walk/%s/0000.PNG", this->getName().c_str(), this->getName().c_str(), dir[i].c_str()); } }
[ "46839828+yelangpi@users.noreply.github.com" ]
46839828+yelangpi@users.noreply.github.com
6b9257c931bb4eec1b0269c9754d8c3b7db85ac6
bbc197df80337a0908e420b4cf5ac0f1e1911c19
/src/Semaforos/Semaforo.h
729d9e8466e0b8f7d0d547a559d7170f8affd45e
[]
no_license
nicodiaz55/ConcuCalesita
043ab73703180ae174bec5bd7abd92ee34931a60
34eec3326cf2d3f84a46b21039439b920041d42c
refs/heads/master
2020-06-02T10:54:19.567963
2014-10-16T16:09:18
2014-10-16T16:09:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
663
h
#ifndef SEMAFORO_H_ #define SEMAFORO_H_ #include <sys/ipc.h> #include <sys/sem.h> #include <sys/types.h> #include <string> #include "../Constantes.h" class Semaforo { private: std::string arch; int clave; int valorInicial; // valor inical al ser creado o -1 si se crea ya inicializado int nombre; int inicializar () const; public: Semaforo ( const std::string& nombre,int clave,const int valorInicial ); Semaforo ( const std::string& nombre,int clave); ~Semaforo(); int crear(); int p (int cant) const; // decrementa int v (int cant) const; // incrementa int zero () const; //espera a cero int eliminar () const; }; #endif /* SEMAFORO_H_ */
[ "juanfedericofuld@hotmail.com" ]
juanfedericofuld@hotmail.com
5b25203f531b423a8083f4183a12d995c9730176
b1e34350be8b7259d4053931cd474e1e583ff55d
/node_modules/react-native/ReactAndroid/src/main/jni/first-party/jni/fbjni/References-inl.h
2176d1e022ea9c7c310654a0aeed8b9fa8f52eb7
[ "BSD-3-Clause", "CC-BY-SA-4.0", "CC-BY-4.0", "CC-BY-NC-SA-4.0", "LicenseRef-scancode-unknown", "MIT" ]
permissive
ttalhouk/Game_On
7d3a695b51785d44a142b20407e49708e23f5bbf
3c2d0c0d0309afe010d5e0c4b92715893d782541
refs/heads/master
2021-01-20T19:39:29.478197
2016-06-22T21:01:50
2016-06-22T21:01:50
60,302,910
5
5
MIT
2018-01-25T22:19:26
2016-06-02T23:00:41
Makefile
UTF-8
C++
false
false
14,298
h
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #pragma once #include <new> #include "CoreClasses.h" namespace facebook { namespace jni { template<typename T> inline enable_if_t<IsPlainJniReference<T>(), T> getPlainJniReference(T ref) { return ref; } template<typename T> inline JniType<T> getPlainJniReference(alias_ref<T> ref) { return ref.get(); } template<typename T, typename A> inline JniType<T> getPlainJniReference(const base_owned_ref<T, A>& ref) { return ref.get(); } namespace detail { template <typename Repr> struct ReprAccess { using javaobject = JniType<Repr>; static void set(Repr& repr, javaobject obj) noexcept { repr.JObjectBase::set(obj); } static javaobject get(const Repr& repr) { return static_cast<javaobject>(repr.JObject::get()); } }; namespace { template <typename Repr> void StaticAssertValidRepr() noexcept { static_assert(std::is_base_of<JObject, Repr>::value, "A smart ref representation must be derived from JObject."); static_assert(IsPlainJniReference<JniType<Repr>>(), "T must be a JNI reference"); static_assert(sizeof(Repr) == sizeof(JObjectBase), ""); static_assert(alignof(Repr) == alignof(JObjectBase), ""); } } template <typename Repr> ReprStorage<Repr>::ReprStorage(JniType<Repr> obj) noexcept { StaticAssertValidRepr<Repr>(); set(obj); } template <typename Repr> void ReprStorage<Repr>::set(JniType<Repr> obj) noexcept { new (&storage_) Repr; ReprAccess<Repr>::set(get(), obj); } template <typename Repr> Repr& ReprStorage<Repr>::get() noexcept { return *reinterpret_cast<Repr*>(&storage_); } template <typename Repr> const Repr& ReprStorage<Repr>::get() const noexcept { return *reinterpret_cast<const Repr*>(&storage_); } template <typename Repr> JniType<Repr> ReprStorage<Repr>::jobj() const noexcept { ReprAccess<Repr>::get(get()); return ReprAccess<Repr>::get(get()); } template <typename Repr> void ReprStorage<Repr>::swap(ReprStorage& other) noexcept { StaticAssertValidRepr<Repr>(); using std::swap; swap(get(), other.get()); } inline void JObjectBase::set(jobject reference) noexcept { this_ = reference; } inline jobject JObjectBase::get() const noexcept { return this_; } template<typename T, typename Alloc> enable_if_t<IsNonWeakReference<T>(), plain_jni_reference_t<T>> make_ref(const T& reference) { auto old_reference = getPlainJniReference(reference); if (!old_reference) { return nullptr; } auto ref = Alloc{}.newReference(old_reference); if (!ref) { // Note that we end up here if we pass a weak ref that refers to a collected object. // Thus, it's hard to come up with a reason why this function should be used with // weak references. throw std::bad_alloc{}; } return static_cast<plain_jni_reference_t<T>>(ref); } } // namespace detail template<typename T> inline local_ref<T> adopt_local(T ref) noexcept { static_assert(IsPlainJniReference<T>(), "T must be a plain jni reference"); return local_ref<T>{ref}; } template<typename T> inline global_ref<T> adopt_global(T ref) noexcept { static_assert(IsPlainJniReference<T>(), "T must be a plain jni reference"); return global_ref<T>{ref}; } template<typename T> inline weak_ref<T> adopt_weak_global(T ref) noexcept { static_assert(IsPlainJniReference<T>(), "T must be a plain jni reference"); return weak_ref<T>{ref}; } template<typename T> inline enable_if_t<IsPlainJniReference<T>(), alias_ref<T>> wrap_alias(T ref) noexcept { return alias_ref<T>(ref); } template<typename T> enable_if_t<IsPlainJniReference<T>(), alias_ref<T>> wrap_alias(T ref) noexcept; template<typename T> enable_if_t<IsNonWeakReference<T>(), local_ref<plain_jni_reference_t<T>>> make_local(const T& ref) { return adopt_local(detail::make_ref<T, LocalReferenceAllocator>(ref)); } template<typename T> enable_if_t<IsNonWeakReference<T>(), global_ref<plain_jni_reference_t<T>>> make_global(const T& ref) { return adopt_global(detail::make_ref<T, GlobalReferenceAllocator>(ref)); } template<typename T> enable_if_t<IsNonWeakReference<T>(), weak_ref<plain_jni_reference_t<T>>> make_weak(const T& ref) { return adopt_weak_global(detail::make_ref<T, WeakGlobalReferenceAllocator>(ref)); } template<typename T1, typename T2> inline enable_if_t<IsNonWeakReference<T1>() && IsNonWeakReference<T2>(), bool> operator==(const T1& a, const T2& b) { return isSameObject(getPlainJniReference(a), getPlainJniReference(b)); } template<typename T1, typename T2> inline enable_if_t<IsNonWeakReference<T1>() && IsNonWeakReference<T2>(), bool> operator!=(const T1& a, const T2& b) { return !(a == b); } // base_owned_ref /////////////////////////////////////////////////////////////////////// template<typename T, typename Alloc> inline base_owned_ref<T, Alloc>::base_owned_ref() noexcept : base_owned_ref(nullptr) {} template<typename T, typename Alloc> inline base_owned_ref<T, Alloc>::base_owned_ref(std::nullptr_t t) noexcept : base_owned_ref(static_cast<javaobject>(nullptr)) {} template<typename T, typename Alloc> inline base_owned_ref<T, Alloc>::base_owned_ref(const base_owned_ref& other) : storage_{static_cast<javaobject>(Alloc{}.newReference(other.get()))} {} template<typename T, typename Alloc> template<typename U> inline base_owned_ref<T, Alloc>::base_owned_ref(const base_owned_ref<U, Alloc>& other) : storage_{static_cast<javaobject>(Alloc{}.newReference(other.get()))} {} template<typename T, typename Alloc> inline facebook::jni::base_owned_ref<T, Alloc>::base_owned_ref( javaobject reference) noexcept : storage_(reference) { assert(Alloc{}.verifyReference(reference)); internal::dbglog("New wrapped ref=%p this=%p", get(), this); } template<typename T, typename Alloc> inline base_owned_ref<T, Alloc>::base_owned_ref( base_owned_ref<T, Alloc>&& other) noexcept : storage_(other.get()) { internal::dbglog("New move from ref=%p other=%p", other.get(), &other); internal::dbglog("New move to ref=%p this=%p", get(), this); // JObject is a simple type and does not support move semantics so we explicitly // clear other other.set(nullptr); } template<typename T, typename Alloc> template<typename U> base_owned_ref<T, Alloc>::base_owned_ref(base_owned_ref<U, Alloc>&& other) noexcept : storage_(other.get()) { internal::dbglog("New move from ref=%p other=%p", other.get(), &other); internal::dbglog("New move to ref=%p this=%p", get(), this); // JObject is a simple type and does not support move semantics so we explicitly // clear other other.set(nullptr); } template<typename T, typename Alloc> inline base_owned_ref<T, Alloc>::~base_owned_ref() noexcept { reset(); internal::dbglog("Ref destruct ref=%p this=%p", get(), this); } template<typename T, typename Alloc> inline auto base_owned_ref<T, Alloc>::release() noexcept -> javaobject { auto value = get(); internal::dbglog("Ref release ref=%p this=%p", value, this); set(nullptr); return value; } template<typename T, typename Alloc> inline void base_owned_ref<T,Alloc>::reset() noexcept { reset(nullptr); } template<typename T, typename Alloc> inline void base_owned_ref<T,Alloc>::reset(javaobject reference) noexcept { if (get()) { assert(Alloc{}.verifyReference(reference)); Alloc{}.deleteReference(get()); } set(reference); } template<typename T, typename Alloc> inline auto base_owned_ref<T, Alloc>::get() const noexcept -> javaobject { return storage_.jobj(); } template<typename T, typename Alloc> inline void base_owned_ref<T, Alloc>::set(javaobject ref) noexcept { storage_.set(ref); } // weak_ref /////////////////////////////////////////////////////////////////////// template<typename T> inline weak_ref<T>& weak_ref<T>::operator=( const weak_ref& other) { auto otherCopy = other; swap(*this, otherCopy); return *this; } template<typename T> inline weak_ref<T>& weak_ref<T>::operator=( weak_ref<T>&& other) noexcept { internal::dbglog("Op= move ref=%p this=%p oref=%p other=%p", get(), this, other.get(), &other); reset(other.release()); return *this; } template<typename T> local_ref<T> weak_ref<T>::lockLocal() const { return adopt_local( static_cast<javaobject>(LocalReferenceAllocator{}.newReference(get()))); } template<typename T> global_ref<T> weak_ref<T>::lockGlobal() const { return adopt_global( static_cast<javaobject>(GlobalReferenceAllocator{}.newReference(get()))); } template<typename T> inline void swap( weak_ref<T>& a, weak_ref<T>& b) noexcept { internal::dbglog("Ref swap a.ref=%p a=%p b.ref=%p b=%p", a.get(), &a, b.get(), &b); a.storage_.swap(b.storage_); } // basic_strong_ref //////////////////////////////////////////////////////////////////////////// template<typename T, typename Alloc> inline basic_strong_ref<T, Alloc>& basic_strong_ref<T, Alloc>::operator=( const basic_strong_ref& other) { auto otherCopy = other; swap(*this, otherCopy); return *this; } template<typename T, typename Alloc> inline basic_strong_ref<T, Alloc>& basic_strong_ref<T, Alloc>::operator=( basic_strong_ref<T, Alloc>&& other) noexcept { internal::dbglog("Op= move ref=%p this=%p oref=%p other=%p", get(), this, other.get(), &other); reset(other.release()); return *this; } template<typename T, typename Alloc> inline alias_ref<T> basic_strong_ref<T, Alloc>::releaseAlias() noexcept { return wrap_alias(release()); } template<typename T, typename Alloc> inline basic_strong_ref<T, Alloc>::operator bool() const noexcept { return get() != nullptr; } template<typename T, typename Alloc> inline auto basic_strong_ref<T, Alloc>::operator->() noexcept -> Repr* { return &storage_.get(); } template<typename T, typename Alloc> inline auto basic_strong_ref<T, Alloc>::operator->() const noexcept -> const Repr* { return &storage_.get(); } template<typename T, typename Alloc> inline auto basic_strong_ref<T, Alloc>::operator*() noexcept -> Repr& { return storage_.get(); } template<typename T, typename Alloc> inline auto basic_strong_ref<T, Alloc>::operator*() const noexcept -> const Repr& { return storage_.get(); } template<typename T, typename Alloc> inline void swap( basic_strong_ref<T, Alloc>& a, basic_strong_ref<T, Alloc>& b) noexcept { internal::dbglog("Ref swap a.ref=%p a=%p b.ref=%p b=%p", a.get(), &a, b.get(), &b); using std::swap; a.storage_.swap(b.storage_); } // alias_ref ////////////////////////////////////////////////////////////////////////////// template<typename T> inline alias_ref<T>::alias_ref() noexcept : storage_{nullptr} {} template<typename T> inline alias_ref<T>::alias_ref(std::nullptr_t) noexcept : storage_{nullptr} {} template<typename T> inline alias_ref<T>::alias_ref(const alias_ref& other) noexcept : storage_{other.get()} {} template<typename T> inline alias_ref<T>::alias_ref(javaobject ref) noexcept : storage_(ref) { assert( LocalReferenceAllocator{}.verifyReference(ref) || GlobalReferenceAllocator{}.verifyReference(ref)); } template<typename T> template<typename TOther, typename /* for SFINAE */> inline alias_ref<T>::alias_ref(alias_ref<TOther> other) noexcept : storage_{other.get()} {} template<typename T> template<typename TOther, typename AOther, typename /* for SFINAE */> inline alias_ref<T>::alias_ref(const basic_strong_ref<TOther, AOther>& other) noexcept : storage_{other.get()} {} template<typename T> inline alias_ref<T>& alias_ref<T>::operator=(alias_ref other) noexcept { swap(*this, other); return *this; } template<typename T> inline alias_ref<T>::operator bool() const noexcept { return get() != nullptr; } template<typename T> inline auto facebook::jni::alias_ref<T>::get() const noexcept -> javaobject { return storage_.jobj(); } template<typename T> inline auto alias_ref<T>::operator->() noexcept -> Repr* { return &(**this); } template<typename T> inline auto alias_ref<T>::operator->() const noexcept -> const Repr* { return &(**this); } template<typename T> inline auto alias_ref<T>::operator*() noexcept -> Repr& { return storage_.get(); } template<typename T> inline auto alias_ref<T>::operator*() const noexcept -> const Repr& { return storage_.get(); } template<typename T> inline void alias_ref<T>::set(javaobject ref) noexcept { storage_.set(ref); } template<typename T> inline void swap(alias_ref<T>& a, alias_ref<T>& b) noexcept { a.storage_.swap(b.storage_); } // Could reduce code duplication by using a pointer-to-function // template argument. I'm not sure whether that would make the code // more maintainable (DRY), or less (too clever/confusing.). template<typename T, typename U> enable_if_t<IsPlainJniReference<T>(), local_ref<T>> static_ref_cast(const local_ref<U>& ref) noexcept { T p = static_cast<T>(ref.get()); return make_local(p); } template<typename T, typename U> enable_if_t<IsPlainJniReference<T>(), global_ref<T>> static_ref_cast(const global_ref<U>& ref) noexcept { T p = static_cast<T>(ref.get()); return make_global(p); } template<typename T, typename U> enable_if_t<IsPlainJniReference<T>(), alias_ref<T>> static_ref_cast(const alias_ref<U>& ref) noexcept { T p = static_cast<T>(ref.get()); return wrap_alias(p); } template<typename T, typename RefType> auto dynamic_ref_cast(const RefType& ref) -> enable_if_t<IsPlainJniReference<T>(), decltype(static_ref_cast<T>(ref))> { if (! ref) { return decltype(static_ref_cast<T>(ref))(); } std::string target_class_name{jtype_traits<T>::base_name()}; // If not found, will throw an exception. alias_ref<jclass> target_class = findClassStatic(target_class_name.c_str()); local_ref<jclass> source_class = ref->getClass(); if ( ! source_class->isAssignableFrom(target_class)) { throwNewJavaException("java/lang/ClassCastException", "Tried to cast from %s to %s.", source_class->toString().c_str(), target_class_name.c_str()); } return static_ref_cast<T>(ref); } }}
[ "pair+shaun-sweet.ttalhouk@devbootcamp.com" ]
pair+shaun-sweet.ttalhouk@devbootcamp.com
dd06ad52b405015e0e0a74a558f7ed0b6429de02
4435a0a6110b77060478876a464f6187d635f3a3
/MGEOP_gen/Snap-2.3/snap-exp/dblp.cpp
1c29b8717dc071bc20c1637fbb50912fac88e001
[]
no_license
vshesh/fractal-graphs
014469f650fd42eb9a3334699a73ef9dbfafca1c
5d294f903458148470216d0bca4723d5c8e3644d
refs/heads/main
2021-06-07T07:55:49.462792
2021-04-03T00:51:51
2021-04-03T00:51:51
75,800,804
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:30d794866a80a99a1f33c5e3e3d3c39b76146ec854a4d49a0c8f1cfedfee1b86 size 1972
[ "cayman.simpson@gmail.com" ]
cayman.simpson@gmail.com
af69bbdadd3c978750833f5ec6ca426a77c59cfd
43b27eac03fdda72502f5042c4b278e78acf1e13
/3_parcial/bidimencionales/67_calificaciones_alumnos.cpp
2e43dd89b07f1c1f02be5f91168b279e1c583075
[]
no_license
sensito/Cosas-C
d54ca3c59db849315b15e85b0bffb9afef9f52b2
8c7923a46788a7d6bf991f86d3d027eed5845554
refs/heads/master
2020-05-20T10:58:54.603233
2019-05-08T06:35:01
2019-05-08T06:35:01
185,536,379
0
0
null
null
null
null
UTF-8
C++
false
false
1,738
cpp
#include <stdio.h> #include <stdlib.h> #include<conio.h> bool validacion(float); void calificacion_final (float, float, float, int&); main() { float a,b,c, prom = 0, extraordinario=0; char opc = 'n',extra = 'n'; int CF = 0, alumnos = 0; do { do { system("cls"); printf("ingresa la primer calificacion\n"); scanf("%f",&a ); system("cls"); } while(validacion(a) == false); do { printf("ingresa la segunda calificacion\n"); scanf("%f",&b ); system("cls"); } while(validacion(b) == false); do { printf("ingresa la terser calificacion\n"); scanf("%f",&c ); system("cls"); } while(validacion(c) == false); calificacion_final(a,b,c,CF); printf("realisaste extraordinario?\n"); scanf("%c",&extra); extra = getche(); system("cls"); if (extra =='s') { printf("ingresa la calificacion del extra\n"); scanf("%d", &extraordinario); system("cls"); } if (extraordinario > CF) { printf("tu calificacion es %d\n", extraordinario); prom = prom + extraordinario; } else{ printf("tu calificaion es %d\n",CF); prom = prom + CF; } alumnos = alumnos + 1; printf("tienes mas alumnos\n"); scanf("%c",&opc); } while(opc == 's'); printf("el promedio del grupo es:%f\n", prom/alumnos); } bool validacion(float x){ if (x < 0 && x >10) { return false;} else{ return true; } } void calificacion_final (float a, float b, float c, int& CF){ float cali; cali = (a+b+c)/3; if (cali > 6) { cali = cali + .5; } CF = cali; }
[ "danielivanhola@gmail.com" ]
danielivanhola@gmail.com
8cbaf3bf1fd691e9e026b274a945762b0aa59fc4
513ffc29658412023932d7245f552a127fd6cb1c
/src/engine/real_time_pbr/mesh/model.cpp
475312c24cdd5198a67058dbac7162ebd5d68c80
[ "BSD-2-Clause" ]
permissive
huyu1314/physical-based-renderer
f8f8a91b7b847739a819de754c05f300b3075265
32567e91d8b1aa3c163618fd649e104274549736
refs/heads/master
2020-03-17T03:39:56.197212
2018-05-07T08:47:50
2018-05-07T08:47:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,801
cpp
#pragma once #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <vector> #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "stb_image.h" #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "model.h" #include "mesh.h" namespace PBR { Model::Model() { } Model::~Model() { } void Model::loadModel(std::string path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } this->directory = path.substr(0, path.find_last_of('/')); this->processNode(scene->mRootNode, scene); } void Model::Draw() { for (GLuint i = 0; i < this->meshes.size(); i++) this->meshes[i].Draw(); } void Model::processNode(aiNode* node, const aiScene* scene) { for (GLuint i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; this->meshes.push_back(this->processMesh(mesh, scene)); } for (GLuint i = 0; i < node->mNumChildren; i++) { this->processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<Vertex> vertices; std::vector<GLuint> indices; for (GLuint i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; glm::vec3 vector; vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.Position = vector; vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.Normal = vector; if (mesh->mTextureCoords[0]) { glm::vec2 vec; vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.TexCoords = vec; } else vertex.TexCoords = glm::vec2(0.0f, 0.0f); vertices.push_back(vertex); } for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (GLuint j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } return Mesh(vertices, indices); } }
[ "yoyo.sincerely@gmail.com" ]
yoyo.sincerely@gmail.com
5013fd9c89862428da7215ddffc703d752480a89
6392530e7a657b1a5e1214038fc40b162cb36ec3
/longest-common-substring.cpp
e54a8f5e0437257fe036ace23271800407a3111e
[]
no_license
vishalpandya1990/LeetCodeProblems
94f2133784000237cd64413a5009c2fda47839cb
5facac363c8966c0d97cfb2e3f4a452cba4838e3
refs/heads/master
2021-01-19T13:57:04.435849
2018-05-09T09:27:34
2018-05-09T09:27:34
100,866,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
/* Dynamic Programming solution to find length of the longest common substring */ #include<iostream> #include<string.h> using namespace std; int LCSubStr(char *X, char *Y, int m, int n) { if(m == 0 || n == 0) return 0; int dp[m][n]; dp[0][0] = X[0] == Y[0] ? 1 : 0; for(int col = 1; col < n; col++) { dp[0][col] = 0; if(X[0] == Y[col]) dp[0][col] = 1; } for(int row = 1; row < m; row++) { dp[row][0] = 0; if(X[row] == Y[0]) dp[row][0] = 1; } int ans = 0; for(int row = 1; row < m; row++) { for(int col = 1; col < n; col++) { if(X[row] == Y[col]) dp[row][col] = 1 + dp[row-1][col-1]; else dp[row][col] = 0; ans = max(ans, dp[row][col]); } } return ans; } /* Driver program to test above function */ int main() { char X[] = "OldSite:GeeksforGeeks.org"; char Y[] = "NewSite:GeeksQuiz.com"; int m = strlen(X); int n = strlen(Y); cout << "Length of Longest Common Substring is " << LCSubStr(X, Y, m, n); return 0; }
[ "vishalpandya1990@gmail.com" ]
vishalpandya1990@gmail.com
9cfb329674b1ca9ebd38e5b70532277d9ddb4400
a6e9ad468d7dc7404a20de86ade8c3d09f9ad925
/Source/thirdparty/Ogre/RenderSystems/GLES2/src/EGL/Android/OgreAndroidEGLWindow.cpp
a56af8dab22035e93b2f3c8fdf6705821f99f190
[ "MIT" ]
permissive
SiwenZhang/OgrePort
b9a997cb2a2f10076b88d7f644456be36e9d26f0
65aab5b80a44255c3212ebb02fb6fac92d9f2237
refs/heads/master
2021-01-12T03:51:03.131199
2016-12-27T12:10:36
2016-12-27T12:10:36
78,274,406
1
1
null
2017-01-07T11:11:33
2017-01-07T11:11:33
null
UTF-8
C++
false
false
11,480
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreWindowEventUtilities.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreAndroidEGLSupport.h" #include "OgreAndroidEGLWindow.h" #include "OgreAndroidEGLContext.h" #include "OgreAndroidResourceManager.h" #include <iostream> #include <algorithm> #include <climits> namespace Ogre { AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport) : EGLWindow(glsupport), mMaxBufferSize(32), mMinBufferSize(16), mMaxDepthSize(16), mMaxStencilSize(0), mMSAA(0), mCSAA(0) { } AndroidEGLWindow::~AndroidEGLWindow() { } EGLContext* AndroidEGLWindow::createEGLContext() const { return new AndroidEGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface); } void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height ) { // We don't have a native window.... but I think all android windows are origined left = top = 0; } void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) { } void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) { } void AndroidEGLWindow::reposition( int left, int top ) { } void AndroidEGLWindow::resize(uint width, uint height) { } void AndroidEGLWindow::windowMovedOrResized() { if(mActive) { // When using GPU rendering for Android UI the os creates a context in the main thread // Now we have 2 choices create OGRE in its own thread or set our context current before doing // anything else. I put this code here because this function called before any rendering is done. // Because the events for screen rotation / resizing did not worked on all devices it is the best way // to query the correct dimensions. mContext->setCurrent(); eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth); eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight); // Notify viewports of resize ViewportList::iterator it = mViewportList.begin(); while( it != mViewportList.end() ) (*it++).second->_updateDimensions(); } } void AndroidEGLWindow::switchFullScreen(bool fullscreen) { } void AndroidEGLWindow::create(const String& name, uint width, uint height, bool fullScreen, const NameValuePairList *miscParams) { mName = name; mWidth = width; mHeight = height; mLeft = 0; mTop = 0; mIsFullScreen = fullScreen; void* eglContext = NULL; AConfiguration* config = NULL; if (miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); if ((opt = miscParams->find("currentGLContext")) != end && StringConverter::parseBool(opt->second)) { eglContext = eglGetCurrentContext(); if (eglContext) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "EGLWindow::create"); } eglContext = eglGetCurrentContext(); mEglSurface = eglGetCurrentSurface(EGL_DRAW); } if((opt = miscParams->find("externalWindowHandle")) != end) { mWindow = (ANativeWindow*)(Ogre::StringConverter::parseInt(opt->second)); } if((opt = miscParams->find("androidConfig")) != end) { config = (AConfiguration*)(Ogre::StringConverter::parseInt(opt->second)); } int ctxHandle = -1; if((miscParams->find("externalGLContext")) != end) { mIsExternalGLControl = true; ctxHandle = Ogre::StringConverter::parseInt(opt->second); } if((opt = miscParams->find("maxColourBufferSize")) != end) { mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second); } if((opt = miscParams->find("maxDepthBufferSize")) != end) { mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second); } if((opt = miscParams->find("maxStencilBufferSize")) != end) { mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second); } if((opt = miscParams->find("minColourBufferSize")) != end) { mMinBufferSize = Ogre::StringConverter::parseInt(opt->second); if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize; } if((opt = miscParams->find("MSAA")) != end) { mMSAA = Ogre::StringConverter::parseInt(opt->second); } if((opt = miscParams->find("CSAA")) != end) { mCSAA = Ogre::StringConverter::parseInt(opt->second); } } initNativeCreatedWindow(miscParams); if (mEglSurface) { mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height); } if (!mEglConfig && eglContext) { mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); if (!mEglConfig) { // This should never happen. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a EGLFBConfig", "EGLWindow::create"); } } mIsExternal = (mEglSurface != 0); if (!mEglConfig) { _createInternalResources(mWindow, config); mHwGamma = false; } mContext = createEGLContext(); mContext->setCurrent(); eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth); eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight); EGL_CHECK_ERROR mActive = true; mVisible = true; mClosed = false; } void AndroidEGLWindow::_destroyInternalResources() { mContext->setCurrent(); GLES2RenderSystem::getResourceManager()->notifyOnContextLost(); mContext->_destroyInternalResources(); eglDestroySurface(mEglDisplay, mEglSurface); EGL_CHECK_ERROR eglTerminate(mEglDisplay); EGL_CHECK_ERROR mEglDisplay = 0; mEglSurface = 0; mActive = false; mVisible = false; mClosed = true; } void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config) { mWindow = window; int minAttribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BUFFER_SIZE, mMinBufferSize, EGL_DEPTH_SIZE, 16, EGL_NONE }; int maxAttribs[] = { EGL_BUFFER_SIZE, mMaxBufferSize, EGL_DEPTH_SIZE, mMaxDepthSize, EGL_STENCIL_SIZE, mMaxStencilSize, EGL_NONE }; bool bAASuccess = false; if (mCSAA) { try { int CSAAminAttribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BUFFER_SIZE, mMinBufferSize, EGL_DEPTH_SIZE, 16, EGL_COVERAGE_BUFFERS_NV, 1, EGL_COVERAGE_SAMPLES_NV, mCSAA, EGL_NONE }; int CSAAmaxAttribs[] = { EGL_BUFFER_SIZE, mMaxBufferSize, EGL_DEPTH_SIZE, mMaxDepthSize, EGL_STENCIL_SIZE, mMaxStencilSize, EGL_COVERAGE_BUFFERS_NV, 1, EGL_COVERAGE_SAMPLES_NV, mCSAA, EGL_NONE }; mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs); bAASuccess = true; } catch (Exception& e) { LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed"); } } if (mMSAA && !bAASuccess) { try { int MSAAminAttribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BUFFER_SIZE, mMinBufferSize, EGL_DEPTH_SIZE, 16, EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, mMSAA, EGL_NONE }; int MSAAmaxAttribs[] = { EGL_BUFFER_SIZE, mMaxBufferSize, EGL_DEPTH_SIZE, mMaxDepthSize, EGL_STENCIL_SIZE, mMaxStencilSize, EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, mMSAA, EGL_NONE }; mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs); bAASuccess = true; } catch (Exception& e) { LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed"); } } mEglDisplay = mGLSupport->getGLDisplay(); if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); EGLint format; eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format); EGL_CHECK_ERROR ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format); mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); if(config) { bool isLandscape = (int)AConfiguration_getOrientation(config) == 2; mGLSupport->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait"); } if(mContext) { mActive = true; mVisible = true; mClosed = false; mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL); static_cast<GLES2RenderSystem*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this); } } }
[ "liuenbao@lius-MacBook-Pro.local" ]
liuenbao@lius-MacBook-Pro.local
e58002b6118385f80c7a5c6c3f031ca72e1d0209
b8b1cf5cef7dcd9cdf83c0fddd2c7bc6a9141016
/dp/sg/io/IL/Saver/ILTexSaver.cpp
1a9d8affbfee1f91d1f6ba5b256072831774c7c0
[ "BSD-3-Clause" ]
permissive
LightPixel/pipeline
87d4ab9ef8bbbf2e3d081316ed402eecfa38be7a
7337d51aa06a61ada8a7c9fa62f17c2f5c38971a
refs/heads/master
2021-01-18T20:10:55.248245
2015-01-08T13:27:08
2015-01-12T07:26:08
29,166,089
0
1
null
2015-01-13T01:19:41
2015-01-13T01:19:40
null
UTF-8
C++
false
false
12,182
cpp
// Copyright NVIDIA Corporation 2002-2015 // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ILTexSaver.cpp : Defines the entry point for the DLL application. // #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers # include <windows.h> #endif #include <typeinfo> #include <dp/sg/io/PlugInterfaceID.h> #include <dp/sg/core/TextureHost.h> #include <dp/util/DPAssert.h> #include <dp/util/File.h> #include <dp/util/Tools.h> #include "ILTexSaver.h" #include "il.h" using namespace dp::sg::core; using namespace dp::util; using std::vector; using std::string; // a pointer to our single instance of the Loader ILTexSaverSharedPtr ILTexSaver::m_instance; // supported Plug Interface ID const UPITID PITID_TEXTURE_SAVER(UPITID_TEXTURE_SAVER, UPITID_VERSION); // plug-in type #define NUM_SUPPORTED_EXTENSIONS 22 static string SUPPORTED_EXTENSIONS[] = { ".TGA", ".JPG", ".JPEG", ".DDS", ".PNG", ".BMP", ".PCX", ".PBM", ".PGM", ".PPM", ".PSD", ".SGI", ".BW", ".RGB", ".RGBA", ".TIF", ".TIFF", ".JP2", ".PAL", ".VTF", ".RAW", ".HDR" }; // convenient macro #ifndef INVOKE_CALLBACK #define INVOKE_CALLBACK(cb) if ( callback() ) callback()->cb #endif #if defined(_WIN32) BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } #endif bool getPlugInterface(const UPIID& piid, dp::util::PlugInSharedPtr & pi) { for( unsigned int i=0; i<NUM_SUPPORTED_EXTENSIONS; ++i) { UPIID tempPiid(SUPPORTED_EXTENSIONS[i].c_str(), PITID_TEXTURE_SAVER); if( piid==tempPiid ) { if ( !ILTexSaver::m_instance ) { ILTexSaver::m_instance = ILTexSaver::create(); } pi = ILTexSaver::m_instance; return( !!pi ); } } return false; } void queryPlugInterfacePIIDs( std::vector<dp::util::UPIID> & piids ) { piids.clear(); for( unsigned int i=0; i<NUM_SUPPORTED_EXTENSIONS; ++i) { // generate piids for all supported extensions dynamically UPIID tempPiid(SUPPORTED_EXTENSIONS[i].c_str(), PITID_TEXTURE_SAVER); piids.push_back(tempPiid); } } static int determineImage( int i, bool isDDS, bool isCube ) { int image = i; if ( isDDS ) { if ( isCube ) { if ( 4 == image ) { image = 5; } else if ( 5 == image ) { image = 4; } } } return( image ); } static ILenum determineILFormat(Image::PixelFormat format) { ILenum ilFormat = 0; switch( format ) { case Image::IMG_COLOR_INDEX : ilFormat = IL_COLOR_INDEX; break; case Image::IMG_RGB : case Image::IMG_INTEGER_RGB : ilFormat = IL_RGB; break; case Image::IMG_RGBA : case Image::IMG_INTEGER_RGBA : ilFormat = IL_RGBA; break; case Image::IMG_BGR : case Image::IMG_INTEGER_BGR : ilFormat = IL_BGR; break; case Image::IMG_BGRA : case Image::IMG_INTEGER_BGRA : ilFormat = IL_BGRA; break; case Image::IMG_LUMINANCE : case Image::IMG_ALPHA : case Image::IMG_DEPTH_COMPONENT : case Image::IMG_INTEGER_ALPHA : case Image::IMG_INTEGER_LUMINANCE : ilFormat = IL_LUMINANCE; break; case Image::IMG_LUMINANCE_ALPHA : case Image::IMG_INTEGER_LUMINANCE_ALPHA : ilFormat = IL_LUMINANCE_ALPHA; break; default : ilFormat = 0; DP_ASSERT( !"Unknown pixel format" ); break; } return ilFormat; } static ILenum determineILType(Image::PixelDataType type) { ILenum ilType = 0; switch( type ) { case Image::IMG_BYTE : ilType = IL_BYTE; break; case Image::IMG_UNSIGNED_BYTE : ilType = IL_UNSIGNED_BYTE; break; case Image::IMG_SHORT : ilType = IL_SHORT; break; case Image::IMG_UNSIGNED_SHORT : ilType = IL_UNSIGNED_SHORT; break; case Image::IMG_INT : ilType = IL_INT; break; case Image::IMG_UNSIGNED_INT : ilType = IL_UNSIGNED_INT; break; case Image::IMG_FLOAT : ilType = IL_FLOAT; break; case Image::IMG_UNKNOWN_TYPE: default: ilType = 0; DP_ASSERT( !"Unknown pixel type" ); break; } return ilType; } static void faceTwiddling(int face, TextureHostSharedPtr const& texImage) { if ( face == 0 || face == 1 || face == 4 || face == 5 ) // px, nx, pz, nz { texImage->mirrorY(face); } else { texImage->mirrorX(face); } } ILTexSaverSharedPtr ILTexSaver::create() { return( std::shared_ptr<ILTexSaver>( new ILTexSaver() ) ); } ILTexSaver::ILTexSaver() { ilInit(); } ILTexSaver::~ILTexSaver() { ilShutDown(); ILTexSaver::m_instance = ILTexSaverSharedPtr::null; } bool ILTexSaver::save( const TextureHostSharedPtr & image, const string & fileName ) { DP_ASSERT(image); // set locale temporarily to standard "C" locale dp::util::TempLocale tl("C"); bool isCube; unsigned int imageID; ilGenImages( 1, (ILuint *) &imageID ); ilBindImage( imageID ); string ext = dp::util::getFileExtension( fileName ); bool isDDS = !_stricmp(".DDS", ext.c_str()); // .dds needs special handling if ( isDDS ) { // DirectDraw Surfaces have their origin at upper left ilEnable( IL_ORIGIN_SET ); ilOriginFunc( IL_ORIGIN_UPPER_LEFT ); } else { ilDisable( IL_ORIGIN_SET ); } // DevIL does not know how to handle .jps and .pns. Since those formats are just renamed .jpgs and .pngs // pass over filename.(jps|pns).(jpg|png) and rename the file after saving it. // FIXME Sent bug report to DevIL. Remove this once jps/pns is added to DevIL. bool isStereoFormat = false; std::string devilFilename = fileName; if (!_stricmp(".JPS", ext.c_str())) { isStereoFormat = true; devilFilename += ".JPG"; } else if (!_stricmp(".PNS", ext.c_str())) { isStereoFormat = true; devilFilename += ".PNG"; } unsigned int numImages = image->getNumberOfImages(); isCube = image->isCubeMap(); unsigned char * pixels = NULL; // we only handle these cases properly DP_ASSERT(isCube == (numImages==6)); DP_ASSERT(!isCube == (numImages==1)); for ( unsigned int i = 0; i < numImages; ++i ) { // for DDS cube maps we need to juggle with the faces // to get them into the right order for DDS formats int face = determineImage( i, isDDS, isCube ); ilBindImage(imageID); ilActiveImage(0); ilActiveFace(face); DP_ASSERT(IL_NO_ERROR == ilGetError()); // TODO: Do not know how to handle paletted! This information is already destroyed // // pixel format // unsigned int format = ilGetInteger(IL_IMAGE_FORMAT); // if ( IL_COLOR_INDEX == format ) // { // // convert color index to whatever the base type of the palette is // if ( !ilConvertImage(ilGetInteger(IL_PALETTE_BASE_TYPE), IL_UNSIGNED_BYTE) ) // { // DP_TRACE_OUT("ERROR: conversion from color index format failed!\n"); // INVOKE_CALLBACK(onInvalidFile(fileName, "DevIL Loadable Color-Indexed Image")); // goto ERROREXIT; // } // // now query format of the converted image // format = ilGetInteger(IL_IMAGE_FORMAT); // } // // Determine the Pixel Format and type ILenum ilFormat = determineILFormat(image->getFormat()); ILenum ilType = determineILType(image->getType()); // Retrieve the image dimensions unsigned int width = image->getWidth(i); unsigned int height = image->getHeight(i); unsigned int depth = image->getDepth(i); // If assertion fires, something is wrong DP_ASSERT( (width > 0) && (height > 0) && (depth > 0) ); // again some twiddling for DDS format necessary prior to // specify the IL image if ( isDDS && isCube ) { faceTwiddling( face, image ); } // temporary cache to retrieve SceniX' TextureHost pixels pixels = new unsigned char[image->getNumberOfBytes()]; // specify the IL image image->getSubImagePixels(i, 0, 0, 0, 0, width, height, depth, pixels); ilTexImage( width, height, depth, image->getBytesPerPixel(), ilFormat, ilType, NULL ); void* destpixels = ilGetData(); memcpy(destpixels, pixels, image->getNumberOfBytes()); // done with the temporary pixel cache delete[] pixels; DP_ASSERT(IL_NO_ERROR == ilGetError()); // undo the face twiddling from before if ( isDDS && isCube ) { faceTwiddling( face, image ); } } // By default, always overwrite ilEnable(IL_FILE_OVERWRITE); if ( ilSaveImage( (const ILstring)devilFilename.c_str() ) ) { // For stereo formats rename the file to the original filename if (isStereoFormat) { // Windows will not rename a file if the destination filename already does exist. remove( fileName.c_str() ); rename( devilFilename.c_str(), fileName.c_str() ); } ilDeleteImages(1, &imageID); DP_ASSERT(IL_NO_ERROR == ilGetError()); return true; } else { #if 0 DP_TRACE_OUT("ERROR: save image failed!\n"); #endif // clean up errors while( ilGetError() != IL_NO_ERROR ) {} // report that an error has occured INVOKE_CALLBACK( onInvalidFile( fileName, "saving image file failed!") ); } // free all resources associated with the DevIL image ilDeleteImages(1, &imageID); return false; }
[ "matavenrath@nvidia.com" ]
matavenrath@nvidia.com
76896af9c2a3e329adf42d64973e7aaca9b87192
2cbcfb9b9046ac131dc01a6fd048b6920d29cd42
/CPlusPlus/LeetCode/剑指offer/剑指 Offer 56 - II. 数组中数字出现的次数 II/main.cpp
6eec180ada68f93b1b7f4e112b8ea14db334825c
[]
no_license
pulinghao/LeetCode_Python
6b530a0e491ea302b1160fa73582e838338da3d1
82ece6ed353235dcd36face80f5d87df12d56a2c
refs/heads/master
2022-08-12T21:19:43.510729
2022-08-08T03:04:52
2022-08-08T03:04:52
252,371,954
2
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
// // main.cpp // 剑指 Offer 56 - II. 数组中数字出现的次数 II // // Created by pulinghao on 2022/6/27. // #include <iostream> #include "common.h" class Solution { public: int singleNumber(vector<int>& nums) { vector<int> k(32); for (int i = 0; i < nums.size(); ++i) { int num = nums[i]; int j = 31; while(num){ k[j] += num % 2; num = num >> 1; j--; } } vector<int> res(32); for (int i = 0; i < 32; ++i) { if (k[i] % 3 == 1) { res[i] = 1; } } int resV = 0; for (int i = 31; i >= 0; i--) { if (res[i]) { resV += pow(2,31 - i); } } return resV; } }; int main(int argc, const char * argv[]) { // insert code here... vector<int> input = {3,4,3,3}; std::cout << Solution().singleNumber(input); return 0; }
[ "536400571@qq.com" ]
536400571@qq.com
914b157977c9b621c4f8b1cd59ea36c693de7a29
bc6c37cf0469c6b2778707b76227558b3a040718
/Leetcode/1428. Leftmost Column with at Least a One-2.cpp
1345b99b910a7d9a1cc5203e553824d3976bcdcf
[]
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
688
cpp
/** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation * class BinaryMatrix { * public: * int get(int row, int col); * vector<int> dimensions(); * }; */ class Solution { public: int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { vector<int> dim = binaryMatrix.dimensions(); int rows=dim[0]; int cols=dim[1]; int r=0, c=cols-1; for(;r<rows;++r) { for(;c>=0;--c) { if(binaryMatrix.get(r, c)==0) { break; } } } return c+1==cols?-1:c+1; } };
[ "noreply@github.com" ]
noreply@github.com
06ab685a6efdf94489b5201611cceb14abd38984
11b87ee1cc9fcafc901d5f98e51b1045d117ffae
/src/time_series.h
b815f3dae7f4112deefae8f9ca2411e7dbc80df2
[]
no_license
gnyiri/sys-ins
25c20e75ee16e69c859238328c497136fdbb2659
2b3f4816b27cea570e549c9a555ce24b22fc0045
refs/heads/master
2021-01-10T10:47:34.576935
2016-03-16T17:42:33
2016-03-16T17:42:33
53,420,430
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
h
#ifndef TIME_SERIES_H #define TIME_SERIES_H #include <vector> /*! * \brief The time_series class */ class time_series { public: /*! * \brief time_series */ time_series(); /*! * \brief time_series */ time_series(const unsigned int p_size); /*! * \brief ~time_series */ ~time_series(); /*! * \brief add new element * \param p_time_data */ void add(const unsigned int p_time_data); /*! * \brief get * \param p_index * \return */ unsigned int get(const unsigned int p_index) const; /*! * \brief get size * \return size */ unsigned int get_size() const; /*! * \brief get_min * \return max */ unsigned int get_min() const; /*! * \brief get_max * \return max */ unsigned int get_max() const; /*! * \brief get_avg * \return */ unsigned int get_avg() const; /*! * \brief get_buff * \return */ void* get_buff(); private: /*! * \brief m_size */ unsigned int m_size; /*! * \brief m_position */ unsigned int m_position; /*! * \brief m_max */ unsigned int m_min; /*! * \brief m_min */ unsigned int m_max; /*! * \brief m_sum */ unsigned long m_sum; /*! * \brief m_data */ std::vector<unsigned int> m_data; }; #endif // TIME_SERIES_H
[ "gergely.nyiri@gmail.com" ]
gergely.nyiri@gmail.com
2de088a8fd6c36c9d6925d781a70cfbcf13bb16d
7487c08a56546157df3f3681b03a7ec5d3bb9c44
/pgn/piecepathview.h
75aba5f9a6de8da0c5e79121160c8714b12766f8
[]
no_license
ifanatic/chessgameviewer2
431dbdf41474e7d1a2876ba85b431f8827602091
90966a7f36f9358666a4a5300f59989389e19d9e
refs/heads/master
2021-01-22T20:25:49.698309
2012-09-13T02:54:30
2012-09-13T02:54:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
684
h
#ifndef PIECEPATHVIEW_H #define PIECEPATHVIEW_H #include <QWidget> #include <vector> #include <algorithm> #include "chessboard.h" using namespace std; class PiecePathView : public QWidget { Q_OBJECT private: vector<ChessPosition> _positions; ChessBoardPiece _piece; protected: void paintEvent(QPaintEvent *event); public: explicit PiecePathView( QWidget *parent = 0); void setPositions(const vector<ChessPosition>& positions) { _positions = positions; } void setPiece(const ChessBoardPiece& piece) { _piece = piece; } signals: public slots: }; #endif // PIECEPATHVIEW_H
[ "nikolay@3divi.com" ]
nikolay@3divi.com
2f8ef63b19079a568e8558fb519f7c5d4ffc8b8b
e0089e71e523e4dd46bc1040498ee51c713f31f7
/simulation/g4simulation/g4tpc/PHG4TpcDefs.h
ca3e2fa75d59a76d66f688c40383c2719f6e8f7a
[]
no_license
johnlajoie/coresoftware
d66ba3c4c6af6380061dff630e84b6a75bc28d02
57a393eade7a5edad8fb6a602d730845ae2143d4
refs/heads/master
2022-01-03T04:11:51.631461
2021-12-19T12:29:43
2021-12-19T12:29:43
38,701,802
0
0
null
2015-07-07T16:52:39
2015-07-07T16:52:38
null
UTF-8
C++
false
false
255
h
#ifndef G4TPC_PHG4TPCDEFS_H #define G4TPC_PHG4TPCDEFS_H namespace PHG4TpcDefs { enum { North = 1, South = 2 }; // passive materials id's (copy numbers) enum { Window = 100, WindowCore }; }; // namespace PHG4TpcDefs #endif
[ "pinkenburg@bnl.gov" ]
pinkenburg@bnl.gov
d3f39621b5976f3427f1f358416482db6c861c18
40e60e01ede0b99f14d5e01603e0cd15009b98dc
/EduRound2_51/R2_51C.cpp
584ace7cf474900ea640136c216b3299b6809c58
[]
no_license
mylvoh0714/Codeforces
d01de00928a7f075fc5e0fc7c656b028a646b1c0
7339a1b8de4d0d95d38f293822628c37b202c65c
refs/heads/master
2020-03-25T15:34:11.883461
2018-11-16T10:43:06
2018-11-16T10:43:06
143,882,211
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#include <iostream> #include <map> using namespace std; map<int, int> mp; int a[104]; char ans[104]; bool odd_possible; int main() { cin.tie(NULL); ios_base::sync_with_stdio(false); int n; cin >> n; for ( int i = 1; i <= n; i++ ) ans[i] = 'A'; for ( int i = 1; i <= n; i++ ) { cin >> a[i]; mp[a[i]] += 1; } int nice_cnt = 0; for ( int i = 1; i <= n; i++ ) { if ( mp[a[i]] == 1 ) { nice_cnt++; } else if ( mp[a[i]] >= 3 ) { odd_possible = true; } } if ( ( ( nice_cnt & 1 ) && odd_possible == false) ) { cout << "NO\n"; return 0; } else if ( ( nice_cnt & 1 ) && odd_possible == true ) { cout << "YES\n"; nice_cnt /= 2; for ( int i = 1; i <= n; i++ ) { if ( nice_cnt == 0 && odd_possible == false) break; if ( mp[a[i]] == 1 && nice_cnt > 0) { ans[i] = 'B'; nice_cnt--; } if ( mp[a[i]] >= 3 && odd_possible == true) { ans[i] = 'B'; odd_possible = false; } } } else { cout << "YES\n"; nice_cnt /= 2; for ( int i = 1; i <= n; i++ ) { if ( nice_cnt == 0 ) break; if ( mp[a[i]] == 1 ) { ans[i] = 'B'; nice_cnt--; } } } for ( int i = 1; i <= n; i++ ) cout << ans[i]; }
[ "mylvoh0714@gmail.com" ]
mylvoh0714@gmail.com
a52b265e0942314879f27682a6942239460e0a91
53ac92caa5928662fc507c7a05d730263e60dfd6
/lab6c-Racca.cpp
2af5e1a3d98ef341b10d1412d524c999b79c16f9
[]
no_license
racca3141/Max-and-Min-in-an-Array
c01fa51345f1370a199d02868926f30d2de7bc6e
2785970e8ee4bd023d14944b42bbdcc7fd9a419f
refs/heads/master
2023-08-14T07:08:58.934050
2021-10-06T05:37:43
2021-10-06T05:37:43
414,082,122
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
cpp
// Emerson Racca // 10/4/2021 // Lab 6c - Max and Min in an Array /* Create a 20-element integer array named randomNumbers. const int size = 20; int randomNumbers[size]; 1. Populate the array with random integers from 1 - 1000. 2. Write a function that returns the maximum integer in the array. int maxInteger( int a[], int size ); 3. Write a function that returns the minimum integer in an array. int minInteger( int a[], int size ); 4. Display the results in the main. That is, display all 20 random integers, the max and the min. 5. Ask the user if they would like to play again. */ #include<iostream> #include<cstdlib> // srand(), rand() #include<ctime> // time(0) using namespace std; int maxInteger(int a[], int size); int minInteger(int a[], int size); int main(void) { srand((unsigned int)time(0)); //rids unsigned int error. const int size = 20; int randomNumbers[size]; char runAgain; cout << "Max and Min in an Array\n"; cout << "This program finds the maximum and minimum element in an array.\n\n"; do { for (int i = 0; i < size; i++) { randomNumbers[i] = 1 + rand() % 1000; cout << "Element\t" << i << "\t=\t" << randomNumbers[i] << endl; //I know this could have been displayed using another for loop. } cout << endl; cout << "The maximum integer in the array is:\t" << maxInteger(randomNumbers, size) << endl; cout << "The minimum integer in the array is:\t" << minInteger(randomNumbers, size) << endl; cout << "\nDo you want to run it again (y or n)? "; cin >> runAgain; cout << endl << endl; } while (runAgain == 'y'); return 0; } int maxInteger(int a[], int size) { int maxInt = 1; for (int i = 0; i < size; i++) { if (a[i] > maxInt) maxInt = a[i]; } return maxInt; } int minInteger(int a[], int size) { int minInt = 1000; for (int i = 0; i < size; i++) { if (a[i] < minInt) minInt = a[i]; } return minInt; }
[ "epracca@hotmail.com" ]
epracca@hotmail.com
052efb4a5c6ae003ba3666b2fa3fdc5bf48dd12a
f7a5d6c8aaf1cd37fb0abb416254c95b638279fd
/fibonacci.cpp
f37f3d1d5acd37b6aba9a22b3ffef63d9bc9c5c6
[ "MIT" ]
permissive
GautamSachdeva/fibonacci_small
8904d5a7285ba4a8e42d85d99a11662edd200447
f935f603875685581a39dee8746ccdb5dff335ae
refs/heads/master
2020-06-17T17:39:36.345369
2019-07-09T11:32:01
2019-07-09T11:32:01
195,995,658
0
0
null
null
null
null
UTF-8
C++
false
false
1,682
cpp
#include <iostream> #include <cassert> using namespace std; // The following code calls a naive algorithm for computing a Fibonacci number. // // What to do: // 1. Compile the following code and run it on an input "40" to check that it is slow. // You may also want to submit it to the grader to ensure that it gets the "time limit exceeded" message. // 2. Implement the fibonacci_fast procedure. // 3. Remove the line that prints the result of the naive algorithm, comment the lines reading the input, // uncomment the line with a call to test_solution, compile the program, and run it. // This will ensure that your efficient algorithm returns the same as the naive one for small values of n. // 4. If test_solution() reveals a bug in your implementation, debug it, fix it, and repeat step 3. // 5. Remove the call to test_solution, uncomment the line with a call to fibonacci_fast (and the lines reading the input), // and submit it to the grader. int fibonacci_naive(int n) { if (n <= 1) return n; return fibonacci_naive(n - 1) + fibonacci_naive(n - 2); } int fibonacci_fast(int n) { int* array = new int[n+1]; array[0] = 0; array[1] = 1; for(int i = 2 ; i < n+1 ; i++){ array[i] = array[i-1] + array[i-2]; } int answer = array[n]; delete[] array; return answer; } void test_solution() { assert(fibonacci_fast(3) == 2); assert(fibonacci_fast(10) == 55); for (int n = 0; n < 20; ++n) assert(fibonacci_fast(n) == fibonacci_naive(n)); } int main() { int n = 0; std::cin >> n; // std::cout << fibonacci_fast(n) << '\n'; //test_solution(); std::cout << fibonacci_fast(n) << '\n'; return 0; }
[ "noreply@github.com" ]
noreply@github.com
8b1dbf6987037bddddcb34f6bcc16a6871f6f944
3745a2d6049ae93dbe298ea6ab8ec675c4112da0
/libs/cml/mathlib/matrix/rotation.h
4a56f993f24b331d63ce307ff7b38bbd28f0486a
[]
no_license
albertomila/mini-game-engine-and-editor
17aa60c1376b672446950fa4869892880fe57de1
46919411c43b5f046e740a657b0e9f42f4c155ba
refs/heads/master
2020-06-17T08:39:02.331449
2019-07-08T18:18:26
2019-07-08T18:18:26
195,864,185
0
0
null
null
null
null
UTF-8
C++
false
false
10,207
h
/* -*- C++ -*- ------------------------------------------------------------ @@COPYRIGHT@@ *-----------------------------------------------------------------------*/ /** @file */ #pragma once #ifndef cml_mathlib_matrix_rotation_h #define cml_mathlib_matrix_rotation_h #include <tuple> #include <cml/scalar/traits.h> #include <cml/storage/compiled_selector.h> #include <cml/vector/vector.h> #include <cml/vector/type_util.h> #include <cml/matrix/type_util.h> #include <cml/quaternion/fwd.h> #include <cml/mathlib/euler_order.h> #include <cml/mathlib/axis_order.h> /** @defgroup mathlib_matrix_rotation Matrix Rotation Functions */ namespace cml { /** @addtogroup mathlib_matrix_rotation */ /*@{*/ /** @defgroup mathlib_matrix_rotation_builders_2D 2D Rotation Matrix Builders */ /*@{*/ /** Compute a 2D rotation matrix give @c angle. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 2x2. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class E> void matrix_rotation_2D(writable_matrix<Sub>& m, E angle); /*@}*/ /** @defgroup mathlib_matrix_rotation_builders_3D 3D Rotation Matrix Builders */ /*@{*/ /** Compute a matrix representing a 3D rotation @c angle about world axis * @c axis. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. * * @throws std::invalid_argument if @c axis < 0 or @c axis > 2. */ template<class Sub, class E> void matrix_rotation_world_axis(writable_matrix<Sub>& m, int axis, const E& angle); /** Compute a matrix representing a 3D rotation @c angle about the world * x-axis. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class E> void matrix_rotation_world_x(writable_matrix<Sub>& m, const E& angle); /** Compute a matrix representing a 3D rotation @c angle about the world * y-axis. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class E> void matrix_rotation_world_y(writable_matrix<Sub>& m, const E& angle); /** Compute a matrix representing a 3D rotation @c angle about the world * z-axis. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class E> void matrix_rotation_world_z(writable_matrix<Sub>& m, const E& angle); /** Compute a rotation matrix from an axis and angle. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. * * @throws vector_size_error at run-time if @c v is dynamically-sized, and * is not 3D. If @c v is fixed-size, the size is checked at compile-time. */ template<class Sub, class QSub, class E> void matrix_rotation_axis_angle( writable_matrix<Sub>& m, const readable_vector<QSub>& axis, const E& angle); /** Compute a rotation matrix given three Euler angles and the required * order. * * The rotations are applied about the cardinal axes in the order specified * by the 'order' argument, where 'order' is one of the following * enumerants: * * euler_order_xyz * euler_order_xzy * euler_order_xyx * euler_order_xzx * euler_order_yzx * euler_order_yxz * euler_order_yzy * euler_order_yxy * euler_order_zxy * euler_order_zyx * euler_order_zxz * euler_order_zyz * * e.g. euler_order_xyz means compute the column-basis rotation matrix * equivalent to R_x * R_y * R_z, where R_i is the rotation matrix above * axis i (the row-basis matrix would be R_z * R_y * R_x). * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class E0, class E1, class E2> void matrix_rotation_euler(writable_matrix<Sub>& m, E0 angle_0, E1 angle_1, E2 angle_2, euler_order order); /** Compute a rotation matrix given a vector containing the Euler angles. * * @throws vector_size_error at run-time if @c euler is dynamically-sized, * and is not 3D. If fixed-size, the sizs is checked at compile-time. */ template<class Sub, class ESub> void matrix_rotation_euler(writable_matrix<Sub>& m, const readable_vector<ESub>& euler, euler_order order); /** Build a matrix of derivatives of Euler angles about the specified axis. * * The rotation derivatives are applied about the cardinal axes in the * order specified by the 'order' argument, where 'order' is one of the * following enumerants: * * euler_order_xyz * euler_order_xzy * euler_order_yzx * euler_order_yxz * euler_order_zxy * euler_order_zyx * * e.g. euler_order_xyz means compute the column-basis rotation matrix * equivalent to R_x * R_y * R_z, where R_i is the rotation matrix above * axis i (the row-basis matrix would be R_z * R_y * R_x). * * The derivative is taken with respect to the specified 'axis', which is * the position of the axis in the triple; e.g. if order = euler_order_xyz, * then axis = 0 would mean take the derivative with respect to x. Note * that repeated axes are not currently supported. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. * * @throws std::invalid_argument if @c axis is not 0, 1, or 2, or if @c * order has a repeated axis. */ template<class Sub, class E0, class E1, class E2> void matrix_rotation_euler_derivatives(writable_matrix<Sub>& m, int axis, E0 angle_0, E1 angle_1, E2 angle_2, euler_order order); /** Build a matrix of derivatives of Euler angles about the specified axis, * given the angles as a vector. * * @throws vector_size_error at run-time if @c euler is dynamically-sized, * and is not 3D. If fixed-size, the sizs is checked at compile-time. */ template<class Sub, class ESub> void matrix_rotation_euler_derivatives(writable_matrix<Sub>& m, int axis, const readable_vector<ESub>& euler, euler_order order); /** Compute a rotation matrix from a quaternion. * * @throws minimum_matrix_size_error at run-time if @c m is * dynamically-sized, and is not at least 3x3. If @c m is fixed-size, the * size is checked at compile-time. */ template<class Sub, class QSub> void matrix_rotation_quaternion( writable_matrix<Sub>& m, const readable_quaternion<QSub>& q); /*@}*/ /** @defgroup mathlib_matrix_rotation_alignment 3D Rotation Alignment */ /*@{*/ /** Compute a rotation matrix that aligns vector @c align to @c reference, * using rotations in axis order @c order. */ template<class Sub, class ASub, class RSub> void matrix_rotation_align(writable_matrix<Sub>& m, const readable_vector<ASub>& align, const readable_vector<RSub>& reference, bool normalize = true, axis_order order = axis_order_zyx); /** Compute a rotation matrix to align the vector from @c pos to @c target * with @c reference. */ template<class Sub, class PSub, class TSub, class RSub> void matrix_rotation_aim_at(writable_matrix<Sub>& m, const readable_vector<PSub>& pos, const readable_vector<TSub>& target, const readable_vector<RSub>& reference, axis_order order = axis_order_zyx); /*@}*/ /** @defgroup mathlib_matrix_rotation_conversion Rotation Matrix Conversion */ /*@{*/ /** Convert a 3D rotation matrix @c m to an axis-angle pair. * * @note @c tolerance is used to detect a near-zero axis length. */ template<class Sub, class ASub, class E, class Tol = value_type_trait_of_t<ASub>> void matrix_to_axis_angle( const readable_matrix<Sub>& m, writable_vector<ASub>& axis, E& angle, Tol tolerance = cml::epsilon<Tol>()); /** Convert a 3D rotation matrix @c m to an axis-angle pair returned as a * std::tuple. * * @note @c tolerance is used to detect a near-zero axis length. */ template<class Sub, class Tol = value_type_trait_of_t<Sub>> std::tuple< vector<value_type_trait_of_t<Sub>, compiled<3>>, value_type_trait_of_t<Sub> > matrix_to_axis_angle( const readable_matrix<Sub>& m, Tol tolerance = cml::epsilon<Tol>()); /** Convert a 3D rotation matrix @c m to an Euler-angle triple. * * @note @c tolerance is used to detect degeneracies. */ template<class Sub, class E0, class E1, class E2, class Tol = value_type_trait_of_t<Sub>> void matrix_to_euler( const readable_matrix<Sub>& m, E0& angle_0, E1& angle_1, E2& angle_2, euler_order order, Tol tolerance = cml::epsilon<Tol>(), enable_if_matrix_t<Sub>* = nullptr); /** Convert a 3D rotation matrix @c m to an Euler-angle triple, and return * the result as a fixed-size 3D vector. * * @note @c tolerance is used to detect degeneracies. */ template<class Sub, class Tol = value_type_trait_of_t<Sub>> vector<value_type_trait_of_t<Sub>, compiled<3>> matrix_to_euler(const readable_matrix<Sub>& m, euler_order order, Tol tolerance = cml::epsilon<Tol>(), enable_if_matrix_t<Sub>* = nullptr); /** Convert a 3D rotation matrix @c m to an Euler-angle triple, and return * the result as a user-specified vector type. * * @note @c tolerance is used to detect degeneracies. * * @note @c VectorT can be any vector type with 3 elements, having internal * storage (e.g. compiled<3> or allocated<>). The default is vector<T, * compiled<3>>, where T is the value_type of the matrix. */ template<class VectorT, class Sub, class Tol = value_type_trait_of_t<Sub>> VectorT matrix_to_euler(const readable_matrix<Sub>& m, euler_order order, Tol tolerance = cml::epsilon<Tol>(), enable_if_vector_t<VectorT>* = nullptr, enable_if_matrix_t<Sub>* = nullptr); /*@}*/ /*@}*/ } // namespace cml #define __CML_MATHLIB_MATRIX_ROTATION_TPP #include <cml/mathlib/matrix/rotation.tpp> #undef __CML_MATHLIB_MATRIX_ROTATION_TPP #endif // ------------------------------------------------------------------------- // vim:ft=cpp:sw=2
[ "alberto.miladiaz@gmail.com" ]
alberto.miladiaz@gmail.com
4c2d83cb3d5d43fc50f24e6576692c576fbc04b4
0149a18329517d09305285f16ab41a251835269f
/Contest Volumes/Volume 100 (10000-10099)/UVa_10048_Audiophobia.cpp
546a2f73b7b403174e21347805bdbb7bb3883a63
[]
no_license
keisuke-kanao/my-UVa-solutions
138d4bf70323a50defb3a659f11992490f280887
f5d31d4760406378fdd206dcafd0f984f4f80889
refs/heads/master
2021-05-14T13:35:56.317618
2019-04-16T10:13:45
2019-04-16T10:13:45
116,445,001
3
1
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
/* UVa 10048 - Audiophobia To build using Visual Studio 2008: cl -EHsc -O2 UVa_10048_Audiophobia.cpp */ #include <iostream> #include <vector> #include <algorithm> #include <limits> using namespace std; void floyd(int n, vector< vector<int> >& matrix) // the minmax Floyd-Warshall algorithm { for (int k = 0; k < n; k++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) matrix[i][j] = min(matrix[i][j], max(matrix[i][k], matrix[k][j])); } int main(int /* argc */, char** /* argv */) { for (int t = 1; ; t++) { int n /* number of crossings */, s /* number of streets */, q /* number of queries */; cin >> n >> s >> q; if (!n && !s && !q) break; vector< vector<int> > matrix(n, vector<int>(n, numeric_limits<int>::max())); for (int i = 0; i < n; i++) matrix[i][i] = 0; for (int i = 0; i < s; i++) { int c1, c2, d; cin >> c1 >> c2 >> d; c1--; c2--; matrix[c1][c2] = matrix[c2][c1] = d; } floyd(n, matrix); // the minmax Floyd-Warshall algorithm if (t > 1) cout << endl; cout << "Case #" << t << endl; for (int i = 0; i < q; i++) { int c1, c2; cin >> c1 >> c2; c1--; c2--; if (matrix[c1][c2] == numeric_limits<int>::max()) cout << "no path\n"; else cout << matrix[c1][c2] << endl; } } return 0; }
[ "keisuke.kanao.154@gmail.com" ]
keisuke.kanao.154@gmail.com
e82a0bafd0f5664e6bc29733da884193a4d3ab71
e3f4187a68800ca58b77840f724b167160bea4bc
/coroutline.cpp
535aa7e5a1c5d1ae95c288c00841f29a996f9af2
[]
no_license
xiaoshuangyoyo/RabbitLine
d942fd6ec93d80359dab3ec3954fc53b5a037f86
6b2ed77378f24d2ade5dcc2de5666230be440601
refs/heads/master
2021-09-24T21:40:33.947161
2018-10-15T03:26:56
2018-10-15T03:26:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,492
cpp
// // Created by NorSnow_ZJ on 2018/7/5. // #include <cstring> #include <cassert> #include <iostream> #include "coroutline.h" using namespace RabbitLine; __thread Scheduler * localScheduler = NULL; Scheduler * RabbitLine::getLocalScheduler() { if (!localScheduler) { localScheduler = new Scheduler(); } return localScheduler; } Scheduler::Scheduler() : runningWorker_(-1), run_(false), switchInited_(false), seq_(0), activeWorkerNum_(0) { stack_ = new char[kMaxStackSize]; switchStack_ = new char[1024]; poller_ = getLocalPoller(); } Scheduler::~Scheduler() { for (auto & w : workers_) { delete w.second; } delete [] switchStack_; delete [] stack_; } void Scheduler::initSwitchCtx() { getcontext(&switchCtx_); switchCtx_.uc_stack.ss_sp = switchStack_; switchCtx_.uc_stack.ss_size = 1024; switchCtx_.uc_sigmask = {0}; /*这个上下文在中途就会跳转,绝不会执行完*/ switchCtx_.uc_link = NULL; makecontext(&switchCtx_, reinterpret_cast<void (*)()>(&Scheduler::jumpToRunningCo), 1, this); switchInited_ = true; } int64_t Scheduler::create(Func func) { if (activeWorkerNum_ >= kMaxCoroutlineNum) { return -1; } int64_t id = seq_++; activeWorkerNum_++; if (!switchInited_) { initSwitchCtx(); } coroutline_t * co = new coroutline_t(); co->func = func; co->state = RUNABLE; workers_.insert(WorkersMap::value_type(id, co)); return id; } void Scheduler::resume(int64_t id) { //std::cout << "resume worker " << id << "state: " << workers_[id].state << std::endl; if (workers_.end() == workers_.find(id)) { return; } coroutline_t * co = workers_[id]; /*获取当前上下文,如果处于协程调用链的底层,则该resum是mainLoop调用的,上下文保存在loopCtx_中*/ ucontext_t * curCtx = NULL; if (!callPath_.empty()) { int64_t curId = callPath_.top(); /*如果上级调用者不是mainLoop,则需要保存栈信息*/ assert(runningWorker_ == curId); saveCoStack(curId); curCtx = &workers_[curId]->ctx; } else { curCtx = &loopCtx_; } callPath_.push(id); switch (co->state) { case RUNABLE: getcontext(&co->ctx); co->ctx.uc_stack.ss_sp = stack_; co->ctx.uc_stack.ss_size = kMaxStackSize; co->ctx.uc_sigmask = {0}; runningWorker_ = id; co->state = RUNNING; makecontext(&co->ctx, reinterpret_cast<void (*)()>(&Scheduler::workerRoutline), 1, this); swapcontext(curCtx, &co->ctx); break; case SUSPEND: /* * 处于SUSPEND状态的协程需要拷贝栈信息, * 通过运行在独立栈中的jumpToCo来拷贝,当上级调用者是mainLoop时其实可以不用 * */ co->state = RUNNING; swapcontext(curCtx, &switchCtx_); break; default: assert(0); break; } } State Scheduler::getStatus(int64_t id) { if (workers_.end() == workers_.find(id)) { return UNKNOWN; } else { return workers_[id]->state; } } int64_t Scheduler::getRunningWoker() { return runningWorker_; } void Scheduler::saveCoStack(int64_t id) { coroutline_t * co = workers_[id]; char dummy = 0; /* * 计算当协程已经使用的程栈大小 * 由于栈由高地址向低地址增长,stack_ + kMaxStackSize表示栈底 * dummy的地址代表栈顶 * */ uint64_t size = stack_ + kMaxStackSize - &dummy; assert(size <= kMaxStackSize); /*自动增长栈大小*/ if (size > co->stackSize) { delete [] co->stack; co->stack = new char[size]; } co->stackSize = size; co->stackCapacity = size; memcpy(co->stack, &dummy, size); } /* * 由于使用共享栈,非对称协程之间的调用要拷贝栈, * 必须用一个运行于单独的栈空间的特殊函数来拷贝 * */ void Scheduler::jumpToRunningCo() { if (runningWorker_ != -1) { coroutline_t * curCo = workers_[runningWorker_]; if (curCo->state == FREE) { workers_.erase(runningWorker_); delete curCo; } } /*除返回主循环mainLoop之外都要拷贝栈*/ if (!callPath_.empty()) { runningWorker_ = callPath_.top(); coroutline_t * co = workers_[runningWorker_]; memcpy(stack_+kMaxStackSize - co->stackSize, co->stack, co->stackSize); setcontext(&co->ctx); } else { runningWorker_ = -1; setcontext(&loopCtx_); } } void Scheduler::yield() { if (runningWorker_ == -1) { return; } coroutline_t * co = workers_[runningWorker_]; assert(runningWorker_ == callPath_.top()); callPath_.pop(); co->state = SUSPEND; saveCoStack(runningWorker_); swapcontext(&co->ctx, &switchCtx_); } void Scheduler::mainLoop() { run_ = true; while (run_) { poller_->runPoll(); } } void Scheduler::stopLoop() { run_ = false; } void Scheduler::workerRoutline() { coroutline_t * co = workers_[runningWorker_]; co->func(); co->state = FREE; assert(runningWorker_ == callPath_.top()); activeWorkerNum_--; callPath_.pop(); //std::cout << runningWorker_ << "has ended!" << std::endl; setcontext(&switchCtx_); }
[ "623239185@qq.com" ]
623239185@qq.com
abd2605d25dcaf801778fd9d71097ff8a2473855
ed7f4f3fce64cc6803abd82b65fbaafcc106fefa
/data-processor/string-distance/String Distance/String Distance/wide_string.cpp
bf8dd81e1f64060f6008c1b7d70c8c68cceabfe3
[]
no_license
BobbyL2k/unsuper-nlp
6bdcc2356e821d72268a6607caf02d47697f049f
34e4b61bffbbc789aa3a1cbefd8172d637a53a8d
refs/heads/master
2021-01-21T13:29:20.334696
2018-04-17T13:14:12
2018-04-17T13:14:12
102,127,199
0
2
null
2017-10-18T11:41:02
2017-09-01T15:31:19
JavaScript
UTF-8
C++
false
false
4,135
cpp
#include "wide_string.hpp" #include <cassert> #include <clocale> bool utf8_locale_check(const char locale[]) { const char match[] = "UTF-8"; int c; for (c = 0; locale[c] && match[c]; c++) { if (locale[c] != match[c]) { return false; } } return locale[c] == match[c]; } void setup_locale() { setlocale(LC_ALL, ""); // assert(utf8_locale_check(setlocale(LC_CTYPE, NULL))); } wide_string utf8_to_widestring(const std::string str) { wide_string result; wide_char wch = 0; int left = 0; for (int c = 0; c < str.size(); c++) { unsigned char ch = str[c]; if (ch & 0x80) { if (left > 0) { assert((ch & 0xC0) == 0x80); wch = (wch << 8) | ch; left--; if (left) continue; } else { if ((ch & 0xE0) == 0xC0) { left = 1; } else if ((ch & 0xF0) == 0xE0) { left = 2; } else if ((ch & 0xF8) == 0xF0) { left = 3; } else { assert(false); } wch = (wch << 8) | ch; continue; } } else { assert(left == 0); wch = ch; } result.push_back(wch); wch = 0; } return result; } void display(std::ostream &out, const wide_char ch) { for (int c = 3; c >= 0; c--) { out << (char)(255 & (ch >> (8 * c))); } } std::vector<range> find_substring(const wide_string large_str, const wide_string small_str, int accept_error) { struct finder { int distance; int end_at; }; struct full_finder { finder set[2]; }; const auto large_size = large_str.size(); std::vector<full_finder> v_find(large_size + 1); for (int c = 0; c < large_size + 1; c++) { v_find[c].set[small_str.size() & 1].end_at = c; } for (signed long cs = small_str.size() - 1; cs >= 0; cs--) { int now = cs & 1; int last = now ^ 1; for (signed long cl = large_str.size() - 1; cl >= 0; cl--) { if (large_str[cl] == small_str[cs]) { v_find[cl].set[now].distance = v_find[cl + 1].set[last].distance; v_find[cl].set[now].end_at = v_find[cl + 1].set[last].end_at; } else { if (v_find[cl].set[last].distance < v_find[cl + 1].set[now].distance) { v_find[cl].set[now].distance = 1 + v_find[cl].set[last].distance; v_find[cl].set[now].end_at = v_find[cl].set[last].end_at; } else { v_find[cl].set[now].distance = 1 + v_find[cl + 1].set[now].distance; v_find[cl].set[now].end_at = v_find[cl + 1].set[now].end_at; } } } v_find[large_size].set[now].distance = (int)(small_str.size() - cs); v_find[large_size].set[now].end_at = (int)large_size; } std::vector<range> result; for (int start_at = 0; start_at < v_find.size(); start_at++) { const int now = 0; const finder &find = v_find[start_at].set[now]; bool valid = true; if (find.distance > accept_error) { valid = false; } if (start_at + 1 < v_find.size()) { if (v_find[start_at].set[now].distance == v_find[start_at + 1].set[now].distance + 1) { valid = false; } } if (start_at > 0) { if (v_find[start_at].set[now].distance == v_find[start_at - 1].set[now].distance + 1) { valid = false; } } if (valid) { result.push_back((range){.from = start_at, .distance = find.distance, .to = find.end_at}); } } return result; }
[ "bobby_nh@hotmail.com" ]
bobby_nh@hotmail.com
1be14d8d3b7d18bd4eee4e108f847412be5414e3
43a54d76227b48d851a11cc30bbe4212f59e1154
/tcb/src/v20180608/model/DescribeCloudBaseProjectVersionListResponse.cpp
6b19b5a9599780ec7b1e948279066ba8deffb381
[ "Apache-2.0" ]
permissive
make1122/tencentcloud-sdk-cpp
175ce4d143c90d7ea06f2034dabdb348697a6c1c
2af6954b2ee6c9c9f61489472b800c8ce00fb949
refs/heads/master
2023-06-04T03:18:47.169750
2021-06-18T03:00:01
2021-06-18T03:00:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,229
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tcb/v20180608/model/DescribeCloudBaseProjectVersionListResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tcb::V20180608::Model; using namespace std; DescribeCloudBaseProjectVersionListResponse::DescribeCloudBaseProjectVersionListResponse() : m_projectVersionsHasBeenSet(false), m_totalCountHasBeenSet(false) { } CoreInternalOutcome DescribeCloudBaseProjectVersionListResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("ProjectVersions") && !rsp["ProjectVersions"].IsNull()) { if (!rsp["ProjectVersions"].IsArray()) return CoreInternalOutcome(Error("response `ProjectVersions` is not array type")); const rapidjson::Value &tmpValue = rsp["ProjectVersions"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { CloudBaseProjectVersion item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_projectVersions.push_back(item); } m_projectVersionsHasBeenSet = true; } if (rsp.HasMember("TotalCount") && !rsp["TotalCount"].IsNull()) { if (!rsp["TotalCount"].IsUint64()) { return CoreInternalOutcome(Error("response `TotalCount` IsUint64=false incorrectly").SetRequestId(requestId)); } m_totalCount = rsp["TotalCount"].GetUint64(); m_totalCountHasBeenSet = true; } return CoreInternalOutcome(true); } vector<CloudBaseProjectVersion> DescribeCloudBaseProjectVersionListResponse::GetProjectVersions() const { return m_projectVersions; } bool DescribeCloudBaseProjectVersionListResponse::ProjectVersionsHasBeenSet() const { return m_projectVersionsHasBeenSet; } uint64_t DescribeCloudBaseProjectVersionListResponse::GetTotalCount() const { return m_totalCount; } bool DescribeCloudBaseProjectVersionListResponse::TotalCountHasBeenSet() const { return m_totalCountHasBeenSet; }
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
8d6e828ea399b5a1bec03544f4aa1cd41a1a2ea1
8444a31a821f1b7266c5e31dc6aafa65f45664cf
/Galaga/src/infra/Hud.cpp
7e2fe6110d83a902b66c54071c81bbed0f1b2338
[]
no_license
powergraphics/CppGalaga
a5ffcc1b8ca8804d8ffa1d590f5d650530bc7f6a
b1232a6725da0a60431208f5f396edc146701d69
refs/heads/master
2022-01-06T10:57:29.159500
2019-06-03T23:57:55
2019-06-03T23:57:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,575
cpp
#include <cmath> #include "infra/Util.hpp" #include "infra/Resources.hpp" #include "infra/AudioPlayer.hpp" #include "infra/Display.hpp" #include "infra/Hud.hpp" ol::HudInfo ol::hudInfo { 0, 0, 0, 30000, 30000 }; // struct HudInfo std::string ol::HudInfo::getStageStr() { std::string stageStr = "000" + std::to_string(stage); stageStr = stageStr.substr(stageStr.length() - 3, 3); return stageStr; } std::string ol::HudInfo::getLivesStr() { std::string livesStr = "00" + std::to_string(lives); livesStr = livesStr.substr(livesStr.length() - 2, 2); return livesStr; } std::string ol::HudInfo::getScoreStr() { std::string scoreStr = "000000" + std::to_string(score); scoreStr = scoreStr.substr(scoreStr.length() - 6, 6); return scoreStr; } std::string ol::HudInfo::getHiscoreStr() { std::string hiscoreStr = "000000" + std::to_string(hiscore); hiscoreStr = hiscoreStr.substr(hiscoreStr.length() - 6, 6); return hiscoreStr; } void ol::HudInfo::addScore(int point) { score += point; if (score > nextExtraLifeScore) { lives++; nextExtraLifeScore += 70000; playSound(Sound::EXTRA_LIFE); } } void ol::HudInfo::updateHiscore() { if (score > hiscore) { hiscore = score; } } // class Hud ol::Hud::Hud() { //ctor isLivesVisible_ = true; is1UpBlinkink_ = false; stageSymbols_.setStage(0); scale_ = 1.2f; targetScale_ = 1.2f; } ol::Hud::~Hud() { //dtor } void ol::Hud::setStage(int stage) { stageSymbols_.setStage(stage); } bool ol::Hud::isStageSymbolsFinished() { return stageSymbols_.isFinished(); } bool ol::Hud::isLivesVisible() { return isLivesVisible_; } bool ol::Hud::set1UpBlinking(bool is1UpBlinkink) { is1UpBlinkink_ = is1UpBlinkink; } void ol::Hud::setLivesVisible(bool isLivesVisible) { isLivesVisible_ = isLivesVisible; } void ol::Hud::update() { float dif = targetScale_ - scale_; if (fabs(dif) < 0.01f) { scale_ = targetScale_; } else { scale_ += dif > 0 ? 0.005f : -0.005f; } //1.0f + 0.2f * sin(getGameElapsedTime()); stageSymbols_.update(); } void ol::Hud::draw(Renderer& renderer) { // score renderer.drawText1(" HI-SCORE", getScaledPosition(Vec2(1.0f, 1.0f)), Color::RED); if (!is1UpBlinkink_ || (is1UpBlinkink_ && blink())) { renderer.drawText1("1UP", getScaledPosition(Vec2(1.0f, 1.0f)), Color::RED); } renderer.drawText1(hudInfo.getScoreStr(), getScaledPosition(Vec2(1.0f, 9.0f)), Color::WHITE); renderer.drawText1(hudInfo.getHiscoreStr(), getScaledPosition(Vec2(89.0f, 9.0f)), Color::WHITE); // lives if (isLivesVisible_) { renderer.drawSprite(Sprite::FIGHTER, getScaledPosition(Vec2(0.0f, Display::SCREEN_HEIGHT - 17.0f)), Vec2(96.0f, 0.0f), Vec2(16.0f, 16.0f)); renderer.drawText1("x" + hudInfo.getLivesStr(), getScaledPosition(Vec2(17.0f, 278.0f)), Color::WHITE); } stageSymbols_.draw(renderer); } ol::Vec2 ol::Hud::getScaledPosition(Vec2 position) { if (scale_ != 1.0f) { position = position - Vec2(112.0f, 144.0f); position = scale_ * position; position = position + Vec2(112.0f, 144.0f); } return position; } void ol::Hud::show() { targetScale_ = 1.0f; } void ol::Hud::hide() { targetScale_ = 1.2f; stageSymbols_.setStage(0); }
[ "ono.leo@gmail.com" ]
ono.leo@gmail.com
3b85dd78d874198b0b462dfc267e72f68cf2a215
5848f2680f835da100f40bacffe967e2ec20f077
/lab7/d.cpp
703292b2c80d23a8ad5320d18f97026bce8b9b34
[]
no_license
sashapff/algorithms-and-data-structures
3881aef4843811e96c66cc6c8ca60b27f04acbdf
a4bb6d8599a5231c782bdb3d44263aa92c9e0ae8
refs/heads/main
2023-01-04T06:33:02.546186
2020-10-21T11:09:13
2020-10-21T11:09:13
305,996,743
1
0
null
null
null
null
UTF-8
C++
false
false
1,584
cpp
#include <iostream> #include <vector> using namespace std; vector<int> d; vector<int> a; int n, sz; int log(int a) { int cnt = 0; while (a != 0) { cnt++; a = a >> 1; } return cnt; } void build(int i, int l, int r) { if (r - l == 0) { return; } if (r - l == 1) { d[i] = a[l]; return; } build(i * 2 + 1, l, (r + l) / 2); build(i * 2 + 2, (r + l) / 2, r); d[i] = min(d[i * 2 + 1], d[i * 2 + 2]); } int get(int l, int r, int i, int L, int R) { if (r <= L || R <= l) { return INT32_MAX; } if (l <= L && r >= R) { return d[i]; } return min(get(l, r, i * 2 + 1, L, (L + R) / 2), get(l, r, i * 2 + 2, (L + R) / 2, R)); } void set(int i, int ind, int l, int r) { if (r - l == 0) { return; } if (r - l == 1) { d[ind] = a[l]; return; } if (i < (r + l) / 2) { set(i, ind * 2 + 1, l, (r + l) / 2); } else { set(i, ind * 2 + 2, (r + l) / 2, r); } d[ind] = min(d[ind * 2 + 1], d[ind * 2 + 2]); } int main() { cin >> n; sz = 1 << log(n); a.resize(sz); d.resize(4 * sz); for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = n; i < sz; i++) { a[i] = INT32_MAX; } build(0, 0, sz); string s; while (cin >> s) { int l, r; cin >> l >> r; if (s == "min") { cout << get(l - 1, r, 0, 0, sz) << endl; } else { a[l - 1] = r; set(l - 1, 0, 0, sz); } } return 0; }
[ "a.ivanova@niuitmo.ru" ]
a.ivanova@niuitmo.ru
c8e63b552b6f795288b48ec6485f28638a9811ca
cdedf21e95f8071fba0d4c013875a6b035da116c
/PhD_Code/Arduino/conditional_if_from_analog_input_v3/conditional_if_from_analog_input_v3.ino
bd94dc6d9fd1926820758df6d6f1e5a6dd38068e
[ "MIT" ]
permissive
hphilamore/merge_test
e95da65d5cc9905e78f0e682fabc7c8f5793d28e
289eeb4392852f7a298f183fb48d128af64e560e
refs/heads/master
2021-05-15T19:12:25.134770
2017-10-10T14:37:52
2017-10-10T14:37:52
106,429,096
0
0
null
null
null
null
UTF-8
C++
false
false
1,425
ino
// the setup routine runs once when you press reset: int relay_vdd = 2; // pin that the LED is attached to int relay_vss = 3; // an arbitrary threshold level that's in the range of the analog input int switch_maxon_open = 8; int switch_maxon_close = 9; void setup() { pinMode(relay_vdd, OUTPUT); pinMode(relay_vss, OUTPUT); // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0); digitalWrite(relay_vdd, HIGH); // sets the LED on digitalWrite(relay_vss, LOW); // sets the LED on if (voltage > 3.1 && voltage < 4){ digitalWrite(switch_maxon_close, LOW); // sets the LED on digitalWrite(switch_maxon_open, HIGH); // sets the LED on } else if (voltage > 2.1 && voltage < 3){ digitalWrite(switch_maxon_open, LOW); // sets the LED on digitalWrite(switch_maxon_close, HIGH); // sets the LED on } else { digitalWrite(switch_maxon_open, LOW); // sets the LED on digitalWrite(switch_maxon_close, LOW); // sets the LED on } // print out the value you read: Serial.println(voltage); }
[ "hemmaphilamore@gmail.com" ]
hemmaphilamore@gmail.com
4954ee79b56a7286011f14524daf500b9693a71b
f7fe751653e994ec7c3a6958e3d6c9b37b7f4e84
/MrRobot/Background.cpp
a983e6ce291cb1037a18ca91238a8adfd610d00a
[]
no_license
erick-henri/Jogos_Game2
ea96a00c74df3fd76f14d52a34f8dad9820d96f6
8a9757bfb427d7fa5c97acf4b30d1d690a4758f4
refs/heads/main
2023-08-14T09:41:52.600930
2021-10-21T03:12:10
2021-10-21T03:12:10
419,025,674
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,566
cpp
#include "Background.h" #include "Platform.h" // --------------------------------------------------------------------------------- Background::Background(uint type) { velx = 200; // Velocidade das telas de fundo se movendo xF = x; Xn = x; // Vai verificar qual o nivel da fase para colocar o sprite correspondente switch (type) { case NIVEL1: level = new Sprite("Resources/Nivel1.png"); type = NIVEL1; break; case NIVEL11: level = new Sprite("Resources/Nivel11.png"); type = NIVEL11; break; case NIVEL2: level = new Sprite("Resources/Nivel2.png"); type = NIVEL2; break; case NIVEL22: level = new Sprite("Resources/Nivel22.png"); type = NIVEL22; break; } // carrega imagens gameFont = new Font("Resources/Font2.png"); gameFont->Spacing(13); img = new Image("Resources/Vida.png"); life = new Sprite(img); img = new Image("Resources/Background.png"); back1 = new Sprite(img); back2 = new Sprite(img); // Carrega animações tileset = new TileSet("Resources/lava.png", 800, 64, 1, 5); anim = new Animation(tileset, 0.120f, true); } // --------------------------------------------------------------------------------- Background::~Background() { delete gameFont; delete img; delete back1; delete back2; delete tileset; delete anim; delete life; delete level; } // ------------------------------------------------------------------------------- void Background::Update() { // Se houver colisão a velocidade do background vai paralisar if (Platform::colileft == true) { velx = 0; } // move sprites com velocidades diferentes xF -= velx * gameTime; Xn -= 100 * gameTime; anim->NextFrame(); } // ------------------------------------------------------------------------------- void Background::Draw() { // Carrega as posições dos sprites de background level->Draw(Xn+600, 400,Layer::FRONT); gameFont->Draw(Xn+200, 150, "Pressione espaço para pular para chegar ao fim do nivel e avançar"); life->Draw(64, 64, Layer::UPPER); anim->Draw(window->CenterX(), window->CenterY() + 280, Layer::FRONT); back1->Draw(xF, window->Height() / 2.0f, Layer::MIDDLE, 1.0f, 0.0f); back2->Draw(xF + img->Width(), window->Height() / 2.0f, Layer::MIDDLE, 1.0f, 0.0f); // traz pano de fundo de volta para dentro da tela if (xF + img->Width() / 2.0f < 0) xF += img->Width(); } // -------------------------------------------------------------------------------
[ "erick.h.a@hotmail.com" ]
erick.h.a@hotmail.com
645b53eb1a6648603cc958ff20e7f18c1a3cb30a
7cffa9b29f855c68ec5efcf049f596dc7be6bff6
/src/color/rgb/make/violet.hpp
e999a4e255b21491e92442421e129c8f218f88c1
[ "Apache-2.0" ]
permissive
lzs4073/color
c4e12e26cfe96022e0a5e6736a7abaadf9912c14
290c2c1550c499465f814ba89a214cbec19a72df
refs/heads/master
2020-04-03T07:16:33.120894
2016-02-02T16:18:25
2016-02-02T16:18:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
hpp
#ifndef color_rgb_make_violet #define color_rgb_make_violet // ::color::make::violet( c ) namespace color { namespace make { //RGB equivalents: std::array<double,3>( { 0.933333, 0.509804, 0.933333 } ) - rgb(238,130,238) - #ee82ee inline void violet( ::color::_internal::model< ::color::category::rgb_uint8 > & color_parameter ) { color_parameter.container() = std::array< std::uint8_t, 3 >( { 0xee, 0x82, 0xee } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_uint16 > & color_parameter ) { color_parameter.container() = std::array< std::uint16_t, 3 >( { 0xeeee, 0x8282, 0xeeee } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_uint32 > & color_parameter ) { color_parameter.container() = std::array< std::uint32_t, 3 >( { 0xeeeeeeee, 0x82828282, 0xeeeeeeee } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_uint64 > & color_parameter ) { color_parameter.container() = std::array< std::uint64_t, 3>( { 0, 0, 0 } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_float > & color_parameter ) { color_parameter.container() = std::array<float,3>( { 238/255.0, 130/255.0, 238/255.0 } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_double> & color_parameter ) { color_parameter.container() = std::array<double,3>( { 238/255.0, 130/255.0, 238/255.0 } ); } inline void violet( ::color::_internal::model< ::color::category::rgb_ldouble> & color_parameter ) { color_parameter.container() = std::array<long double,3>( { 238/255.0, 130/255.0, 238/255.0 } ); } } } #endif
[ "dmilos@gmail.com" ]
dmilos@gmail.com