blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
bd6a505bae8acebf74af98fe1732204bc7b3a11f
C++
chrisyees/cs100
/src/headers/vectorContainer.h
UTF-8
1,447
2.90625
3
[ "BSD-3-Clause" ]
permissive
#ifndef _VECTORCONTAINER_H_ #define _VECTORCONTAINER_H_ #include "rshell.h" #include <string> #include <string.h> #include <unistd.h> #include <stdio.h> #include <typeinfo> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include "argument.h" #include "connector.h" #include <sys/wait.h> #include <vector> using namespace std; class vectorContainer { private: string input; //the users input vector<rshell*> argumentList; //holds all parsed commands/arguments vector<rshell*> connectorList; //holds all parsed connectors public: vectorContainer() : input(NULL){}; vectorContainer(string in) : input(in){}; //passes in a string to parse into the vector //void add_element(rshell* element); //used in parse() to add to the vector void print(); //prints all commands in the vector int size(); //returns both vectors' sizes sum void parse(); //breaks string into it's separate commands and places them into the vector container rshell* argAt(int i); //returns the argument at a location rshell* conAt(int i); //return the connector at a location void execute(); //uses all functions above to both create the vector of commands and execute it }; #endif
true
9661e2bfb2e3ce58b54f037d50b32f28d672355e
C++
movie-travel-code/moses
/src/include/IR/IRType.h
UTF-8
6,990
2.71875
3
[]
no_license
//===----------------------------------IRType.h---------------------------===// // // This file contains the declaration of the Type class. // //===---------------------------------------------------------------------===// #pragma once #include "Parser/Type.h" #include <cassert> #include <iostream> #include <memory> #include <sstream> #include <vector> using namespace ast; namespace IR { class Type; class StructType; class FunctionType; class PointerType; class MosesIRContext; using ASTBuiltinTy = ast::BuiltinType; using ASTUDTy = ast::UserDefinedType; using ASTUDTyPtr = std::shared_ptr<ASTUDTy>; using ASTTyKind = ast::TypeKind; using ASTAnonyTy = ast::AnonymousType; using IRTyPtr = std::shared_ptr<Type>; using IRStructTyPtr = std::shared_ptr<StructType>; using IRFuncTyPtr = std::shared_ptr<FunctionType>; using IRPtTyPtr = std::shared_ptr<PointerType>; /// \brief IR Type. class Type { public: //===----------------------------------------------------------===// // Definitions of all of the base types for the type system. Based // on this value, you can cast to a class defined in DerivedTypes.h. enum class TypeID { VoidTy, LabelTy, IntegerTy, BoolTy, FunctionTy, StructTy, PointerTy, AnonyTy }; private: TypeID ID; public: Type(TypeID id) : ID(id) {} virtual ~Type() {} //===-----------------------------------------------------===// // Accessors for working with types. TypeID getTypeID() const { return ID; } bool isVoidType() const { return getTypeID() == TypeID::VoidTy; } bool isLabelTy() const { return getTypeID() == TypeID::LabelTy; } bool isIntegerTy() const { return getTypeID() == TypeID::IntegerTy; } bool isFunctionTy() const { return getTypeID() == TypeID::FunctionTy; } bool isStructTy() const { return getTypeID() == TypeID::StructTy; } bool isAnonyTy() const { return getTypeID() == TypeID::AnonyTy; } bool isBoolTy() const { return getTypeID() == TypeID::BoolTy; } bool isPointerTy() const { return getTypeID() == TypeID::PointerTy; } /// isSingleValueType - Return true if the type is a valid type for a /// register in codegen. bool isSingleValueType() const { return isIntegerTy() || isBoolTy(); } /// isAggregateType - Return true if the type is an aggregate type. bool isAggregateType() const { return getTypeID() == TypeID::StructTy || getTypeID() == TypeID::AnonyTy; } //===------------------------------------------------------------===// // Helper for get types. static IRTyPtr getVoidType(MosesIRContext &Ctx); static IRTyPtr getLabelType(MosesIRContext &Ctx); static IRTyPtr getIntType(MosesIRContext &Ctx); static IRTyPtr getBoolType(MosesIRContext &Ctx); virtual unsigned getSize() const; /// \brief Print the type info. virtual void Print(std::ostringstream &out); }; /// \brief FunctionType - Class to represent function types. class FunctionType : public Type { FunctionType(const FunctionType &) = delete; const FunctionType &operator=(const FunctionType &) = delete; private: std::vector<IRTyPtr> ContainedTys; unsigned NumContainedTys; public: FunctionType(IRTyPtr retty, std::vector<IRTyPtr> parmsty); FunctionType(IRTyPtr retty); /// This static method is the primary way of constructing a FunctionType. static std::shared_ptr<FunctionType> get(IRTyPtr retty, std::vector<IRTyPtr> parmtys); /// Create a FunctionType taking no parameters. static std::shared_ptr<FunctionType> get(IRTyPtr retty); IRTyPtr getReturnType() const { return ContainedTys[0]; } /// param type. /// returntype parm0 parm1 parm2 /// [0] = parm0 /// [2] = parm2 IRTyPtr operator[](unsigned index) const; unsigned getNumParams() const { return NumContainedTys - 1; } std::vector<IRTyPtr> getParams() const { return ContainedTys; } static bool classof(IRTyPtr Ty); /// \brief Print the FunctionType info. void Print(std::ostringstream &out) override; private: std::vector<IRTyPtr> ConvertParmTypeToIRType(MosesIRContext &Ctx, std::vector<std::shared_ptr<ASTType>> ParmTypes); }; /// Class to represent struct types. /// struct type: /// (1) Literal struct types (e.g { i32, i32 }) /// (2) Identifier structs (e.g %foo) class StructType : public Type { StructType(const StructType &) = delete; const StructType &operator=(const StructType &) = delete; private: bool Literal; std::string Name; std::vector<IRTyPtr> ContainedTys; unsigned NumContainedTys; /// For a named struct that actually has a name, this is a pointer to the /// symbol table entry for the struct. This is null if the type is an /// literal struct or if it is a identified type that has an empty name. public: StructType(std::vector<IRTyPtr> members, std::string Name, bool isliteral); /// Create identified struct. /*static IRStructTyPtr Create(std::string Name); static IRStructTyPtr Create(MosesIRContext &Ctx, std::vector<IRTyPtr> Elements, std::string Name);*/ static IRStructTyPtr Create(MosesIRContext &Ctx, std::shared_ptr<ASTType> type); /// Create literal struct type. static IRStructTyPtr get(std::vector<IRTyPtr> Elements); /// Create literal struct type. static IRStructTyPtr get(MosesIRContext &Ctx, std::shared_ptr<ASTType> type); virtual unsigned getSize() const override; bool isLiteral() const { return Literal; } /// Return the name for this struct type if it has an identity. /// This may return an empty string for an unnamed struct type. Do not call /// this on an literal type. std::string getName() const; /// Change the name of this type to the specified name. void setName(std::string Name); bool isLayoutIdentical(IRStructTyPtr Other) const; unsigned getNumElements() const { return NumContainedTys; } std::vector<std::shared_ptr<Type>> getContainedTys() const { return ContainedTys; } IRTyPtr operator[](unsigned index) const { assert(index < NumContainedTys && "Index out of range!"); return ContainedTys[index]; } static bool classof(IRTyPtr T) { return T->getTypeID() == TypeID::StructTy; } /// \brief Print the StructType Info. void Print(std::ostringstream &out) override; void PrintCompleteInfo(std::ostringstream &out); }; /// PointerType - Class to represent pointers class PointerType : public IR::Type { IRTyPtr ElementTy; public: PointerType(IRTyPtr ElementTy); static IRPtTyPtr get(IRTyPtr ElementTy); IRTyPtr getElementTy() const { return ElementTy; }; static bool classof(IRPtTyPtr) { return true; } static bool classof(IRTyPtr Ty) { return Ty->isPointerTy(); } /// \brief Print the PointerType. void Print(std::ostringstream &out) override; }; } // namespace IR
true
23192fb8b6269d006d5c68f42e2f4fc6aa5210d4
C++
piffs1/AnyCPP
/zadachi/mergeIntervals.cpp
UTF-8
1,638
3.6875
4
[]
no_license
/* Merge intervals. * input :[1;3][2;6][8;10][15;18] * output:[1;6][8;10][15;18] * Program can insert intervals and merge intervals */ #include <iostream> #include <map> #include <stack> #include <vector> using namespace std; int main() { vector<pair<int,int>> vr; int lb,rb; //lb = left border. rb = right border int countIntervals; cout << "Input count intervals "; cin >> countIntervals; for(int i = 0; i < countIntervals; i++) { cout << "Input left border "; cin >> lb; cout << "Input right border "; cin >> rb; vr.push_back(make_pair(lb,rb)); } multimap<int,char> mp; for(int i = 0; i < vr.size(); i++) { mp.insert(make_pair(vr[i].first,'b')); // insert left border and char 'b' equals begin mp.insert(make_pair(vr[i].second,'e')); // insert right border and char 'e' equals end } stack<pair<int,char>> s; //stack for check //for(auto it = mp.begin(); it!=mp.end();++it) // debug //cout << it->first << ' ' << it->second << endl; for(auto it = mp.begin(); it!=mp.end(); ++it) { if(s.size()==1 && it->second=='e' && s.top().second=='b') // if stack size is 1. => stack.top().second ='b' { cout << '[' << s.top().first << ';' << it->first << ']'; s.pop(); continue; } if(s.size() > 1 && s.top().second=='b' && it->second=='e') { s.pop(); continue; } s.push(make_pair(it->first,it->second)); // fill stack. //cout << it->first << '-' << it->second << endl; } return 0; }
true
7187a0800d039c576670442a18de58f4705c4069
C++
usini/bottangoTest
/BottangoArduino/src/CircularArray.h
UTF-8
1,583
3.390625
3
[]
no_license
#ifndef BOTTANGO_CIRCULARARRAY_H #define BOTTANGO_CIRCULARARRAY_H #include "Errors.h" #include "Log.h" template <class T> class CircularArray { T **array; byte capacity; byte idx; public: explicit CircularArray(int capacity); void pushBack(T *data); void remove(T *toRemove); T *get(int index); byte size(); void clear(); }; template <class T> CircularArray<T>::CircularArray(int _capacity) { capacity = _capacity; array = new T *[capacity]; idx = 0; for (int i = 0; i < capacity; ++i) { array[i] = NULL; } } template <class T> void CircularArray<T>::pushBack(T *data) { if (idx >= capacity) { Error::reportError_NoSpaceAvailable(); return; } array[idx++] = data; } template <class T> void CircularArray<T>::remove(T *toRemove) { int index = -1; for (int i = 0; i < capacity; i++) { if (array[i] == toRemove) { index = i; break; } } if (index == -1) { return; } for (int i = index; i < capacity; i++) { array[i] = array[i + 1]; } array[idx] = NULL; idx--; } template <class T> T *CircularArray<T>::get(int index) { return array[index]; } template <class T> byte CircularArray<T>::size() { return idx; } template <class T> void CircularArray<T>::clear() { for (int i = 0; i < capacity; ++i) { array[i] = NULL; } } #endif
true
1579795c4c75277b7df19ff76e2d517261571253
C++
tixvage/Console-Game
/Level.cpp
UTF-8
265
2.609375
3
[]
no_license
#include "Level.hpp" Level::Level(Window* window, std::stack<Level*>* levels) { this->window = window; this->levels = levels; this->quit = false; } Level::~Level() { } const bool& Level::getQuit() const { return this->quit; } void Level::checkForQuit() { }
true
912e364fea0df7058ddf0772e100b03a0b513e3a
C++
maxthielen/yml
/test/WorldTests/HistorySizeTest.cpp
UTF-8
1,905
2.578125
3
[ "MIT" ]
permissive
//// //// Created by emiel on 04-02-20. //// // //#include <gtest/gtest.h> //#include <test/helpers/FieldHelper.h> //#include <test/helpers/WorldHelper.h> //#include <include/roboteam_ai/world/World.hpp> // //TEST(worldTest, HistorySizeTest) { // /* Note, this test only works if the history of worlds is still empty. Since its a static, make // * sure that this test is always the first to run for anything that uses or modifies this history! */ // proto::World world; // // // Get the worldInstance // rtt::world::World* worldInstance = rtt::world::World::instance(); // // // There should currently not be a world in the worldInstance // EXPECT_FALSE(worldInstance->getWorld().has_value()); // // The history should be empty // EXPECT_EQ(worldInstance->getHistorySize(), 0); // // // Put a world into worldInstance // worldInstance->updateWorld(world); // // These should now be a world in the worldInstance // EXPECT_TRUE(worldInstance->getWorld().has_value()); // // The history of the world should still be empty // EXPECT_EQ(worldInstance->getHistorySize(), 0); // // // Put another world into worldInstance // worldInstance->updateWorld(world); // // There should still be a world in the worldInstance // EXPECT_TRUE(worldInstance->getWorld().has_value()); // // The history of the world should now contain a single world // EXPECT_EQ(worldInstance->getHistorySize(), 1); // // // Fill up the worldInstance with twice the amount of maximum worlds // for (int i = 0; i < 2 * rtt::world::World::HISTORY_SIZE; i++) worldInstance->updateWorld(world); // // // There should still be a world in the worldInstance // EXPECT_TRUE(worldInstance->getWorld().has_value()); // // The history should contain exactly the amount of maximum worlds // EXPECT_EQ(worldInstance->getHistorySize(), rtt::world::World::HISTORY_SIZE); //}
true
1ee2ae62ec67134d0b0dccf77adf4abd7a8a08e3
C++
36V3mA21Hz/LeetCodePractice
/Codes/BestTimeToBuy.cpp
UTF-8
525
3.015625
3
[]
no_license
class Solution { public: int maxProfit(vector<int> &prices) { if (prices.empty()) return 0; int n = prices.size(); vector<int> diff; diff.push_back(0); for (int i = 1; i < n; i++) { diff.push_back(prices[i] - prices[i-1]); } int max_end = INT_MIN; int max = INT_MIN; for (int i = 0; i < n; i++) { if (max_end > 0) max_end += diff[i]; else max_end = diff[i]; if (max < max_end) max = max_end; } return max; } };
true
9a4700c1702e637afc895ba6643740e11c9ffd05
C++
AlexMalov/Softbox
/SoftBox/effects.ino
UTF-8
1,698
2.859375
3
[]
no_license
// --------------------------------- конфетти ------------------------------------ void sparklesRoutine() { for (byte i = 0; i < scale; i++) { byte x = random(0, WIDTH); byte y = random(0, HEIGHT); if (getPixColorXY(x, y) == 0) leds[getPixelNumber(x, y)] = CHSV(random(0, 255), 255, 255); } fader(70); } // функция плавного угасания цвета для всех пикселей void fader(byte step) { for (byte i = 0; i < WIDTH; i++) for (byte j = 0; j < HEIGHT; j++) fadePixel(i, j, step); } void fadePixel(byte i, byte j, byte step) { // новый фейдер int pixelNum = getPixelNumber(i, j); if (getPixColor(pixelNum) == 0) return; if (leds[pixelNum].r >= 30 || leds[pixelNum].g >= 30 || leds[pixelNum].b >= 30) leds[pixelNum].fadeToBlackBy(step); else leds[pixelNum] = 0; } // ---------------------------------------- радуга ------------------------------------------ byte hue; void rainbowHorizontal() { hue += 2; for (byte i = 0; i < WIDTH; i++) { CHSV thisColor = CHSV((byte)(hue + i * (scale>>3)), 255, 255); for (byte j = 0; j < HEIGHT; j++) drawPixelXY(i, j, thisColor); } } // ---------------------------------------- ЦВЕТА ------------------------------------------ void colorsRoutine() { hue += scale>>3; FastLED.showColor(CHSV(hue, 255, 255)); //for (int i = 0; i < NUM_LEDS; i++) // leds[i] = CHSV(hue, 255, 255); } // --------------------------------- ЦВЕТ ------------------------------------ void colorRoutine() { FastLED.showColor(CHSV(scale, speed, 255)); } void colorRGBRoutine() { FastLED.showColor(CRGB(scale, speed, brightness)); }
true
41c651c93b8d77ce768d8fe3c72929cb2c5b806d
C++
anzhedro/labs
/C++/6. Template_Array_Stack/ArrayStack.h
WINDOWS-1251
1,857
3.140625
3
[]
no_license
struct BAD{}; template <class T> class ArrayStack { int size; int top; T *p; public: ArrayStack(const int& _size); ArrayStack(ArrayStack &s) { size = s.size; p = new T[size]; for(int q = 0; q < size; q++) { p[q] = s.p[q]; } top = s.top; } ~ArrayStack(); void push(const T &x); T pop(); bool isEmpty(); bool isFull(); friend class <T>ArrayStackIterator; }; template <class T> ArrayStack <T>::ArrayStack(const int& _size) // { size = _size; p = new T[size]; top = 0; } template <class T> ArrayStack <T>::~ArrayStack() // { delete []p; } template <class T> void ArrayStack <T> ::push(const T& n) // { if (isFull() == 1) { T *K; K = new T[size + 10]; for(int q = 0; q < size; q ++) K[q] = p[q]; delete []p; p = K; size = size + 10; } p[top++] = n; } template <class T> T ArrayStack <T> ::pop() // { if (isEmpty() == 1) { throw BAD(); } else { top--; return p[top]; } } template <class T> bool ArrayStack <T> ::isEmpty() // ? { if (top == 0) return 1; return 0; } template <class T> bool ArrayStack <T> ::isFull() // ? { if (top == size) return 1; return 0; } template <class T> class ArrayStackIterator: public ArrayStack { ArrayStack <T>&a; int pos; public: ArrayStackIterator( ArrayStack<T>& _a):pos (_a.top), a(_a){} bool InRange() const { if(pos < 0 || pos > a.top) return false; return true;} void Reset() { pos = 0; return;} void operator++() { if(InRange()) {--pos; return;} else return;} void operator++(int) { if(InRange()) {pos--; return;} else return;} T operator *() const { return a.p[pos];} };
true
7d55e35d5affeaa7640f6ff1c94a7c5458d480cb
C++
connerkward/OpenAgent_2D
/src/environments/Tile.cpp
UTF-8
866
3.328125
3
[]
no_license
/** This object represents a location on a Board, and can contain Food, an Agent, or both. */ #include "Tile.h" Tile::Tile(int x, int y) : xPos(x), yPos(y) { entity = nullptr; } void Tile::placeEntity(Entity& newEntity) { entity = &newEntity; } void Tile::removeEntity() { entity = nullptr; } ENTITY_TYPE Tile::getEntityType() { return (*entity).entityType; } std::ostream& operator << (std::ostream& os, const Tile& thisTile) { if (thisTile.entity != nullptr) { os << thisTile.entity->entityChar; return os; } else { os << '-'; return os; } } std::string Tile::tostring() { std::string returnstring; if (this->entity != nullptr) { returnstring += this->entity->entityChar; return returnstring; } else { returnstring += '-'; return returnstring; } }
true
45ca984145f20d293f1f7510b3b32a2cd6a09f5e
C++
goelShweta/C-code
/cons_var_size.cpp
UTF-8
547
3.359375
3
[]
no_license
#include <iostream> using namespace std; int main() { int a=2321; char c[] ="da"; long l=1234334445; short sh=12; float f=12.34; double d=12.345; string s[]="abcdefgh"; cout <<"integer size "<<sizeof(a)<<endl; cout <<"character size "<<sizeof(c)<<endl; cout <<"float size "<<sizeof(f)<<endl; cout <<"double size "<<sizeof(d)<<endl; cout <<"string size "<<sizeof(s)<<endl; cout <<"long size "<<sizeof(l)<<endl; cout <<"short size "<<sizeof(sh)<<endl; return 0; }
true
fe6b26c285ca951efd5ddedf7bce3b2af1a1f50f
C++
Beaterie/programmiersprachen-aufgabenblatt-3
/source/aufgabe5.cpp
UTF-8
584
2.84375
3
[]
no_license
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <cmath> #include <algorithm> #include <vector> bool is_odd(int i){ return (i % 2) != 0; } bool is_even(int i){ return (i % 2) == 0; } TEST_CASE("describe_factorial", "[aufgabe3]"){ // ihre Loesung : std::vector<int> v(100); for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i) { *i = rand()%101; } v.erase( std::remove_if(v.begin(), v.end(), is_odd), v.end() ); REQUIRE(std::all_of(v.begin(), v.end(), is_even) == true); } int main(int argc, char* argv[]){ return Catch::Session().run(argc, argv); }
true
34500911eb1dadb0bafa03f0475b895799007df2
C++
Nantus/Database
/main.cpp
UTF-8
1,240
3.265625
3
[]
no_license
#include <iostream> #include <vector> #include <map> #include <string> #include <algorithm> #include <math.h> #include <iomanip> #include <exception> #include <stdexcept> #include <sstream> using namespace std; int main() { Database db; string command; string c; string event; Date date; while (getline(cin, command)) { stringstream ss; try{ event = ""; c = ""; ss << command; ss >> c; if(c == "Add"){ ss >> date >> event; db.AddEvent(date,event); } else if(c == "Del"){ ss >> date; ss >> event; if(event != ""){ db.DeleteEvent(date,event); cout << "Deleted successfully" << endl; } else cout << "Deleted " << db.DeleteDate(date) << " events" << endl; } else if(c == "Find"){ ss >> date; if(db.Find(date).size() != 0) for(const auto& iter: db.Find(date)) cout << iter << endl; } else if(c == "Print"){ db.Print(); } else if(c != "") cout << "Unknown command: " << c << endl; }catch(const exception& ex){ cout << ex.what() << endl; } } return 0; }
true
40ef05e6cc2ac9c595a16fb4a677683f74ee0572
C++
AtelierNum/projet_dis-information_signals_1819
/Unoui/Code_UNOUi_Farouk-Robin/Code_UNOUi_Farouk-Robin.ino
UTF-8
2,764
3.046875
3
[ "MIT" ]
permissive
const int numReadings = 50; int readings[numReadings]; // the readings from the analog input int readIndex = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average int inputPin = 0; #include <FastLED.h> #define NUM_LEDS 6 // définir le nombre de leds CRGBArray<NUM_LEDS> leds; // définir un tableau de données chaque entrée du tableau représentera une led. float inc = 0; // un variable que l'on va utiliser pour créer une animation. void setup() { FastLED.addLeds<NEOPIXEL, 9>(leds, NUM_LEDS); //Ici on défini le nombre de led Serial.begin(9600); // ouvrir la connexion série pinMode(8, OUTPUT); for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } } void loop() { int value = analogRead(0); // lire la valeur sur la pin A0 et la stocker dans une variable entière int v = abs(constrain(value, 0, 1024)); // subtract the last reading: total = total - readings[readIndex]; // read from the sensor: readings[readIndex] = v; // add the reading to the total: total = total + readings[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: Cela nous permet d'effectur une "moyenne" des valeurs average = total / numReadings; average = constrain(average, 0, 1024); // send it to the computer as ASCII digits Serial.println(average); delay(1); // delay in between reads for stability //analogRead(0)=constrain(value,100,1000); if (average > 150) {// Valeur a partir de laquelle l'enceinte et les lampes s'active tone(8, average * 10); int n=map(average,150,160,2,6); inc += 0.05; // on augmente la valeur de inc // on calcule en fonction de inc un valeur qui va osciller entre 0 et 244. int green = (sin(inc) + 1) * 122; // cette valeur est stocké dans une variable nommée "green" // Pour i allant de 0 à 5, on va éxecuter le code entre accolades, // à chaque fois on augmente la valeur de i de 1 for (int i = 0; i < n; i++) { // on change la valeur de la led 'i' du tableau nommé 'leds" en lui donnant une nouvelle valeur RGB leds[i] = CRGB(255 - green, green, 0); } } else { //Boucle permettant de couper le son et la lumièré noTone(8); for (int i = 0; i < NUM_LEDS; i++) { // on change la valeur de la led 'i' du tableau nommé 'leds" en lui donnant une nouvelle valeur RGB leds[i] = CRGB(0,0,0); } } FastLED.show(); // on actualise le ruban de led }
true
61a538e5d664cc8f4cec02ac541e12211549e0bb
C++
HaseProgram/University
/4sem/OOP/02/02/iterror.h
UTF-8
511
3.03125
3
[]
no_license
#pragma once #include <exception> class ItError : public std::exception { public: virtual const char* out() { return "Iteration error occured"; } }; class Range : public ItError { public: const char* out() { return "Attempt to apply item out of range!"; } }; class Index : public ItError { public: const char* out() { return "Index in [] is out of range!"; } }; class Compare : public ItError { public: const char* out() { return "Cannot compare different copies of Lists!"; } };
true
d3bb2fb2d4518eea4705071b775736ba228e8d14
C++
learningZhang/lodeBalancer
/lodeBalancer/server2.cpp
UTF-8
1,272
2.546875
3
[]
no_license
#include "head.h" #include "mysql.h" #include "server.h" int searchFd(CMysql &db, const char *name) { if (name == NULL || strlen(name)>12) { return -1; } return db.getStates(name);//对离线信息进行存储,之后按照姓名进行查找 } bool findMesgByName(CMysql &db, const char*name, char *str, int length) { return db.findMessageByName(name, str, length); } bool delAllStateInfo(CMysql &db)//删除state表中的所有数据 { return db.deleteElemBySocket(0, 2);//需要通过对象调用 } bool delStateByfd(CMysql &db, int fd) { return db.deleteElemBySocket(1, fd); } bool insertIntoMessage(const char *fromuser, const char *touser, const char* msg, CMysql &db) { return db.insertIntoMessage(fromuser, touser, msg); } bool delSendedMsg(CMysql &db, const char *name) { return db.delInMessage(name); } //1.当客户端请求的是注册时,mysql中增加user,回复的信息中将发来的fd添加 //2.当客户端是登陆的时候,向state表中插入数据,回复信息中增加其发来的fd //3.当客户端是聊天的时候,查询对方是否在线,如果在线就将此包中的fd更换,将消息进行转发, // --如果不在线的话就将消息存储message<message,from, to>,向发送来的fd回复提醒消息
true
9381f802b511839ce6cc9c8edcafe4af8cad6b9a
C++
nadirizr/betterp2p
/core/src/libbp2p/common/BitVector.cc
UTF-8
791
2.859375
3
[]
no_license
#include "BitVector.h" #include <iostream> using namespace std; namespace BT2 { BitVector bitvector_from_string(const std::string& data, size_t bitlen) { if (bitlen == 0) { // if no bitlen given, assume all bits are used bitlen = data.length() * BitVector::bits_per_block; } BitVector b(data.length() * BitVector::bits_per_block); boost::from_block_range( (const unsigned char*)data.c_str(), (const unsigned char*)(data.c_str()+data.length()), b); b.resize(bitlen); return b; } std::string bitvector_to_string(const BitVector& bits) { std::string s(bits.num_blocks(), '\0'); boost::to_block_range( bits, const_cast<unsigned char*>((unsigned char*)s.c_str())); return s; } } // namespace BT2
true
c36c7b7a5a12eecb487e645d22af5c09469f4006
C++
Houssk/Synthese-d-images-avec-OpenGL
/Materials/FittingTexture/C++/Rectangle3.cpp
UTF-8
1,733
2.78125
3
[]
no_license
// Définition de la classe Rectangle3 #include <GL/glew.h> #include <GL/gl.h> #include <math.h> #include <sstream> #include <iostream> #include <utils.h> #include <MeshModuleDrawing.h> #include <Rectangle3.h> /** * Constructeur */ Rectangle3::Rectangle3() { // créer le maillage m_Mesh = new Mesh("Rectangle3"); // sommets MeshVertex* C = m_Mesh->addVertex("C"); C->setCoord(vec3::fromValues(0.0, -1.0, 0.0)); C->setTexCoord(vec2::fromValues(0.75, 0.0)); MeshVertex* D = m_Mesh->addVertex("D"); D->setCoord(vec3::fromValues(+1.0, -1.0, 0.0)); D->setTexCoord(vec2::fromValues(1.0, 0.0)); MeshVertex* E = m_Mesh->addVertex("E"); E->setCoord(vec3::fromValues(+1.0, +1.0, 0.0)); E->setTexCoord(vec2::fromValues(1.0, 1.0)); MeshVertex* F = m_Mesh->addVertex("F"); F->setCoord(vec3::fromValues(0.0, +1.0, 0.0)); F->setTexCoord(vec2::fromValues(0.75, 1.0)); // quadrilatère m_Mesh->addQuad(C, D, E, F); // créer le matériau du rectangle m_Texture = new Texture2D("data/textures/1024px-LandscapeArchPano.jpg", GL_LINEAR, GL_REPEAT); m_Material = new TextureMaterial(m_Texture); // créer les VBO pour afficher ce maillage MeshModuleDrawing renderer(m_Mesh); m_VBOset = renderer.createStripVBOset(m_Material, true); } /** * dessine l'objet sur l'écran * @param mat4Projection : matrice de projection * @param mat4ModelView : matrice de vue */ void Rectangle3::onDraw(mat4& mat4Projection, mat4& mat4ModelView) { m_VBOset->onDraw(mat4Projection, mat4ModelView); } /** * Cette méthode supprime les ressources allouées */ Rectangle3::~Rectangle3() { delete m_Material; delete m_VBOset; delete m_Mesh; }
true
2a18ce0eb222114427feb2e3ce7d9b5b2ddec818
C++
Abhishek-Rout/Competitive-Coding
/HackerRank/30 Days of Code/Day 22 Binary Search Trees/BinarySearchTrees.cpp
UTF-8
328
2.515625
3
[]
no_license
int getHeight(Node* root){ //Write your code here if(!root) { return -1; } int leftDepth = getHeight(root->left); int rightDepth = getHeight(root->right); return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1; }
true
8b5f4c81b2aa0535aee237d9300d869751cded82
C++
Christoph9402/CarND-PID-Controller
/src/PID.cpp
UTF-8
769
3.265625
3
[ "MIT" ]
permissive
#include "PID.h" PID::PID() {} PID::~PID() {} void PID::Init(double Kp, double Ki, double Kd) { this->Kp=Kp; this->Ki=Ki; this->Kd=Kd; //Initializing errors and previous_cte with 0.0 p_error=0; i_error=0; d_error=0; } void PID::UpdateError(double cte) { // D-component: calculated by subtracting p_error (which is 0 in the first step) from the cte d_error = cte - p_error; //P-component:set the p_error to the current cte p_error = cte; // I-component: add the current cte to the previous i_error i_error += cte; } double PID::TotalError() { //Calculate and return the total error using the formula presented in the lesson 12.12 double error_t = -Kp * p_error - Kd * d_error - Ki * i_error; return error_t; }
true
232cbfdf38ed4db7b04d9a8b6f63a9e588dd71c3
C++
ZackSungy/Learn-C-Language
/Subset/main.cpp
UTF-8
304
2.828125
3
[]
no_license
#include<stdio.h> void f(int n, int *A, int cur) { for (int i = 0; i < cur; i++) { printf("%d", A[i]); } printf("\n"); int s = cur ? A[cur - 1] + 1 : 0; for (int i = s; i<n; i++) { A[cur] = i; f(n, A, cur + 1); } } int main() { int n, a[10]; scanf("%d", &n); f(n, a, 0); return 0; }
true
b5cc1f984f7f73a63d4129fd7ea01b8e43c97e3b
C++
andreimit11/TemaPoo3
/TemaPOO3/Cont_de_economii.cpp
UTF-8
3,292
2.734375
3
[]
no_license
#include "Cont_de_economii.h" #include <iostream> Cont_de_economii::Cont_de_economii(const Cont_de_economii&cont) { using namespace std; m_detinator=cont.m_detinator; copy_date(cont.m_data_deschiderii); m_sold=cont.m_sold; m_rata_dobanzii=cont.m_rata_dobanzii; m_tipul_dobanzii=cont.m_tipul_dobanzii; } void Cont_de_economii::depunere(double val) { using namespace std; time_t t=time(nullptr); tm *time_Ptr=localtime(&t); m_sold+=val; Date current_date=make_tuple(time_Ptr->tm_mday, time_Ptr->tm_mon+1, time_Ptr->tm_year+1900); m_istoric_sold.push_back(make_pair(current_date, m_sold)); } int Cont_de_economii::getCurrentYear()const { time_t t=time(nullptr); tm *time_Ptr=localtime(&t); int year=time_Ptr->tm_year+1900; // current year return year; } double Cont_de_economii::getDobanda()const { using namespace std; int n=getCurrentYear()-( get<2>(m_data_deschiderii) ); // durata contului in ani double dobanda_simpla=m_sold*m_rata_dobanzii*n; return dobanda_simpla; } std::istream& Cont_de_economii::read_rata_dobanzii(std::istream&in,double&dobanda) { using namespace std; in.clear(); in.ignore(32767, '\n'); while(1) { cout<<"\nIntrodu rata dobanzii ( nr subunitar ): "; in>>dobanda; if(readFail(in)) { continue; } if(dobanda<0 || dobanda>=1) { continue; } break; } return in; } std::istream& Cont_de_economii::read_tipul_dobanzii(std::istream&in,std::string&tip_dobanda) { using namespace std; in.clear(); in.ignore(32767, '\n'); int op{0}; while(1) { cout<<"\nSelecteaza tipul dobanzii: \n1->pe 3 luni\n2->pe 6 luni\n3->pe 1 an\noptiune: "; in>>op; if(readFail(in)) { continue; } if( (op!=1) && (op!=2) && (op!=3 )) { continue; } if(op==1) { tip_dobanda="3 luni"; } if(op==2) { tip_dobanda="6 luni"; } if(op==3) { tip_dobanda="1 an"; } break; } return in; } std::istream& Cont_de_economii::read_cont(std::istream&in) { std::cout<<"\nTitularul contului:\n"; in>>m_detinator; read_date(in,m_data_deschiderii); read_sold(in,m_sold); read_tipul_dobanzii(in,m_tipul_dobanzii); read_rata_dobanzii(in,m_rata_dobanzii); m_istoric_sold.push_back(make_pair(m_data_deschiderii, m_sold)); return in; } std::ostream& Cont_de_economii::display_cont(std::ostream&out)const { using namespace std; out<<"\nTitularul contului: \n"<<m_detinator<<'\n'<<"Data deschiderii: "<<get<0>(m_data_deschiderii)<<' ' <<get<1>(m_data_deschiderii)<<' '<<get<2>(m_data_deschiderii)<<'\n'; out<<"Sold: "<<m_sold<<'\n'<<"Rata dobanzii: "<<m_rata_dobanzii<<' ' <<"( pe "<<m_tipul_dobanzii<<" )\n"<<"Valoarea curenta a dobanzii: "<<getDobanda()<<'\n'; out<<"\nIstoric actualizare sold \n"; for(const auto&it:m_istoric_sold) { out<<"Actualizare sold: "<<it.second<<" ( in data de "<<get<0>(it.first)<<' '<<get<1>(it.first)<<' '<<get<2>(it.first)<<" )\n"; } return out; }
true
979812117c1e550b490a8d49141761de0f0ae7c9
C++
NathanielRN/uwaterloo-class-resources
/ECE 250/weightedgraph/Weighted_graph.h
UTF-8
16,544
3
3
[]
no_license
/***************************************** * Instructions * - Replace 'uwuserid' with your uWaterloo User ID * - Select the current calendar term and enter the year * - List students with whom you had discussions and who helped you * * uWaterloo User ID: enruizno @uwaterloo.ca * Submitted for ECE 250 * Department of Electrical and Computer Engineering * University of Waterloo * Calender Term of Submission: (Winter) 2018 * * By submitting this file, I affirm that * I am the author of all modifications to * the provided code. * * The following is a list of uWaterloo User IDs of those students * I had discussions with in preparing this project: * gnardyee * cxlei * * The following is a list of uWaterloo User IDs of those students * who helped me with this project (describe their help; e.g., debugging): * - *****************************************/ #ifndef WEIGHTED_GRAPH_H #define WEIGHTED_GRAPH_H #ifndef nullptr #define nullptr 0 #endif #include <iostream> #include <limits> #include <cstring> #include "Exception.h" // include whatever classes you want /**************************************************** * Weighted_graph Class * * Implementation Djikstra's algorithm optimized for the speed2.cpp test * * Public classes, fields and methods * * Constructors * * new(int) constructor Initializes a 2D matrix and min heap for quick distance calculations, * if the passed in value is less than 1, it's default is 1 * * Deconstructors * * delete deconstructor Deletes all arrays used to store information about what the weighted * graph contains * Accessors * * degree(int) Returns the degree of the passed in vertex, throw illegal argument if * an invalid vertex * * edge_count() Returns the number of edges currently in the graph * * adjacent(int, int) Returns the weight between two passed in vertices, throws an illegal * argument exception if either vertex is invalid * * Mutators * * distance(int, int) Returns the distance between the two passed invertices, throws an illegal * argument exception if either vertex is invalid * * insert(int, int) Inserts an edge between the two passed in vertices, throws an illegal * argument exception if either vertex is invalid * * Private classes, fields and methods * * Fields * * numberOfVertices Stores how many vertices there are in the graph * * edges_count Field that keeps track of how many edges are inserted between a new pair * of vertices * * vertex_degrees Array that keeps track of the degrees of each vertex by storing their degree * at their vertex number in the index of this array. * * vertex_links 2D matrix that stores the weights between two vertices, implemented as a * long array and uses offsets to use the vertices as a row and column * * has_link 2D matrix implemented as a long array to store whether a connection exists * between two vertices, as a matrix of booleans this array takes up much less * memory * * lastStartVertex Since speed2.cpp calls for distances from the same start vertex, we * remember the last vertex and if it matches our last vertex, we can continue/ * use our table to find the weight faster * * heapIsValid Since an insert into the graph will change relative possible smallest * distances, this boolean tracks whether our heap is still valid. * * allVerticesInOrder We use an in order vertex array to have a quick way of populating the * vertexVisitHeap and notYetVisitedVerticesLocations Heap * * vertexDistanceHeap A minimum heap that keeps only the vertex which is closest (has the smallest * distance away from us) and adjusts by percolation for insertion of new nodes * * numberOfElementsInTheHeap Value that tracks how many elements are currently in the heap * * vertexLocations An array which tracks where the vertices are in the vertexDistanceHeap * * vertexSmallestWeights An array which tracks the smallest distance to every vertex. The smallest * distance to any given vertex is found by accessing the index corresponding * to the vertex number. * * vertexVisitHeap A regular heap which contains all the vertices that have not yet been * visited. This speeds up our search for connections to other vertices since * we do not check vertices that we have already visited. * * verticesLeft Tracks how many vertices are left to check and is the number of nodes left * in the vertexVisitHeap * * notYetVisitedVerticesLocations An array which tracks where the vertices are in the vertexVisitHeap. * ****************************************************/ class Weighted_graph { private: // your implementation here // you can add both private member variables and private member functions static const double INF; public: Weighted_graph( int = 50 ); ~Weighted_graph(); int const numberOfVertices; int edges_count; int* vertex_degrees; double* vertex_links; bool* has_link; int lastStartVertex; bool heapIsValid; int* allVerticesInOrder; int* vertexDistanceHeap; int numberOfElementsInTheHeap; int* vertexLocations; double* vertexSmallestWeights; int* vertexVisitHeap; int verticesLeft; int* notYetVisitedVerticesLocations; int degree( int ) const; int edge_count() const; double adjacent( int, int ) const; double distance( int, int ); void insert( int, int, double ); // Friends friend std::ostream &operator<<( std::ostream &, Weighted_graph const & ); }; const double Weighted_graph::INF = std::numeric_limits<double>::infinity(); // Your implementation here Weighted_graph::Weighted_graph(int n): numberOfVertices((n < 1) ? 1 : n), edges_count(0), lastStartVertex(-1), heapIsValid(false) { int const linkLength = numberOfVertices*numberOfVertices; vertex_links = new double[linkLength]; has_link = new bool[linkLength]; vertex_degrees = new int[numberOfVertices]; notYetVisitedVerticesLocations = new int[numberOfVertices]; vertexLocations = new int[numberOfVertices]; vertexSmallestWeights = new double[numberOfVertices]; int numberOfVerticesPlusOne = numberOfVertices + 1; allVerticesInOrder = new int[numberOfVerticesPlusOne]; vertexDistanceHeap = new int[numberOfVerticesPlusOne]; vertexVisitHeap = new int[numberOfVerticesPlusOne]; for(int i = 0; i <= numberOfVertices; ++i) { allVerticesInOrder[i] = i; } std::memset(&vertex_links[0], 0, linkLength* sizeof(double)); std::memset(&has_link[0], 0, linkLength* sizeof(bool)); std::memset(&vertex_degrees[0], 0, numberOfVertices * sizeof(int)); std::memset(&vertexDistanceHeap[1], 0, numberOfVertices * sizeof(int)); } Weighted_graph::~Weighted_graph() { delete[] allVerticesInOrder; delete[] vertex_links; delete[] has_link; delete[] vertex_degrees; delete[] vertexDistanceHeap; delete[] notYetVisitedVerticesLocations; delete[] vertexVisitHeap; delete[] vertexLocations; delete[] vertexSmallestWeights; } int Weighted_graph::degree( int i ) const { return vertex_degrees[i]; } int Weighted_graph::edge_count() const { return edges_count; } double Weighted_graph::adjacent( int m, int n ) const { if (m < 0 || n < 0 || m > numberOfVertices - 1 || n > numberOfVertices - 1) { throw illegal_argument(); } else if (m == n) { return 0; } double const weight = vertex_links[size_t(numberOfVertices) * n + m]; /* If there is no record of an edge between the two vertices, return infinity */ if (!weight) { return INF; } return weight; } double Weighted_graph::distance( int m, int n) { if (n < 0 || m < 0 || m > numberOfVertices - 1 || n > numberOfVertices - 1) { throw illegal_argument(); } else if (m == n) { return 0; } int currentNode; // If we have searched from this position before, we can either return an already calculated distance or start of // where we left off if (lastStartVertex == m) { if (!notYetVisitedVerticesLocations[n]) { return vertexSmallestWeights[n]; } } else { // This sequence resets the table that stores the smallest distances. verticesLeft = numberOfVertices; numberOfElementsInTheHeap = 0; std::memcpy(&vertexVisitHeap[1], &allVerticesInOrder[0], numberOfVertices* sizeof(int)); std::memcpy(&notYetVisitedVerticesLocations[0], &allVerticesInOrder[1], numberOfVertices * sizeof(int)); std::memset(&vertexLocations[0], 0, numberOfVertices * sizeof(int)); std::memset(&vertexSmallestWeights[0], 0, numberOfVertices * sizeof(double)); if (!heapIsValid) { heapIsValid = true; } // This will get immediately popped off, it is the only case where we allow a distance of 0 in the heap ++numberOfElementsInTheHeap; vertexSmallestWeights[m] = 0; vertexDistanceHeap[1] = m; lastStartVertex = m; } while(numberOfElementsInTheHeap) { currentNode = vertexDistanceHeap[1]; if (currentNode == n) { return vertexSmallestWeights[n]; } // Pop off the current vertex from the min heap if (numberOfElementsInTheHeap == 1) { numberOfElementsInTheHeap--; } else { int const closestVertexAtTheBack = vertexDistanceHeap[numberOfElementsInTheHeap]; double const pushSize = vertexSmallestWeights[closestVertexAtTheBack]; int currentParentVertex = 1; while (true) { int const first_child = currentParentVertex << 1; // Needs to be at the top here to catch first edge case if (first_child >= numberOfElementsInTheHeap) { break; } int const second_child_index = first_child | 1; int const left_child = vertexDistanceHeap[first_child]; double const left_weight = vertexSmallestWeights[left_child]; int const right_child = vertexDistanceHeap[second_child_index]; double const right_weight = vertexSmallestWeights[right_child]; if (left_weight < right_weight) { if (pushSize > left_weight) { vertexLocations[left_child] = currentParentVertex; vertexDistanceHeap[currentParentVertex] = left_child; currentParentVertex = first_child; } else { break; } } else { if (pushSize > right_weight) { vertexLocations[right_child] = currentParentVertex; vertexDistanceHeap[currentParentVertex] = right_child; currentParentVertex = second_child_index; } else { break; } } } vertexDistanceHeap[currentParentVertex] = closestVertexAtTheBack; vertexLocations[closestVertexAtTheBack] = currentParentVertex; numberOfElementsInTheHeap--; } // Pop of the vertex from the visited heap. int const currentNodeLocation = notYetVisitedVerticesLocations[currentNode]; int const lastVertexAtBack = vertexVisitHeap[verticesLeft]; vertexVisitHeap[currentNodeLocation] = lastVertexAtBack; notYetVisitedVerticesLocations[lastVertexAtBack] = currentNodeLocation; notYetVisitedVerticesLocations[currentNode] = 0; verticesLeft--; // Add the distances between adjacent vertices int const maxLinksToCurrentNode = vertex_degrees[currentNode]; int foundLinks = 0; double const currentDistanceToGetHere = vertexSmallestWeights[currentNode]; for(int i = 1; i <= verticesLeft; ++i) { int const destinationVertex = vertexVisitHeap[i]; size_t const destinationVertexArrayOffset = size_t(numberOfVertices) * currentNode + destinationVertex; if(has_link[destinationVertexArrayOffset]) { ++foundLinks; // Insert into the min heap int currentPlace; double const currentVertexWeight = vertexSmallestWeights[destinationVertex]; double const totalDistance = currentDistanceToGetHere + vertex_links[destinationVertexArrayOffset]; if (!currentVertexWeight) { ++numberOfElementsInTheHeap; currentPlace = numberOfElementsInTheHeap; } else if (totalDistance >= currentVertexWeight) { if (foundLinks == maxLinksToCurrentNode) { break; } continue; } else { currentPlace = vertexLocations[destinationVertex]; } while (currentPlace != 1) { int const parent = currentPlace >> 1; int const parentVertex = vertexDistanceHeap[parent]; // Vertex weights can't be 0 here because we wouldn't put 0 into the heap if (vertexSmallestWeights[parentVertex] < totalDistance) { break; } vertexLocations[parentVertex] = currentPlace; vertexDistanceHeap[currentPlace] = parentVertex; currentPlace = parent; } vertexDistanceHeap[currentPlace] = destinationVertex; vertexSmallestWeights[destinationVertex] = totalDistance; vertexLocations[destinationVertex] = currentPlace; if (foundLinks == maxLinksToCurrentNode) { break; } } } } return INF; } void Weighted_graph::insert( int m, int n, double w ) { if (w <= 0 || m == n || m < 0 || n < 0 || m > numberOfVertices - 1 || n > numberOfVertices - 1) { throw illegal_argument(); } // If the heap is valid, we set it to not be valid anymore because we inserted something. if (heapIsValid) { lastStartVertex = -1; heapIsValid = false; } int const firstLocation = m*numberOfVertices + n; int const secondLocation = n*numberOfVertices + m; // If the vertex is new, we add to the degree and edge count and indicate there is a connection here. if (!vertex_links[firstLocation]) { ++edges_count; ++vertex_degrees[m]; ++vertex_degrees[n]; has_link[firstLocation] = true; has_link[secondLocation] = true; } vertex_links[firstLocation] = w; vertex_links[secondLocation] = w; } // You can modify this function however you want: it will not be tested std::ostream &operator<<( std::ostream &out, Weighted_graph const &graph ) { return out; } // Is an error showing up in ece250.h or elsewhere? // Did you forget a closing '}' ? #endif
true
3378d67ca123b2432768f1982bf0745ccd3224fa
C++
OxOOO1/RawRenderer
/RawRenderer/RawRenderer/src/Scene/DrawableComponent/DebugDraw.h
UTF-8
2,052
3.078125
3
[]
no_license
#pragma once #include "Drawable.h" class RDebugDrawable { public: enum EType { PLANE = 6, CUBE = 36, CONE = 192, CIRCLE = 96, ICOSPHERE = 240, UVSPHERE = 2880, }; struct InstanceDescription { matrix TransformMat; float4 Color; }; RDebugDrawable(EType inType) { Type = inType; InstancesBuffer.Create(L"DebugDrawMatricesBuffer", 1000, sizeof(InstanceDescription)); } EType Type; void UploadInstance(InstanceDescription* instanceDesc, UINT instanceIndex); UINT NumInstances = 0; RStructuredBuffer InstancesBuffer; }; struct RDebugInstanceRef { RDebugDrawable::EType Type; UINT Index; }; class RDebugDrawManagerS { public: static RDebugDrawManagerS& Get() { static RDebugDrawManagerS debugDraw; return debugDraw; } static UINT UploadInstance(const RDebugInstanceRef& instanceRef, RDebugDrawable::InstanceDescription& desc) { RDebugDrawable* drawable = GetDrawableBasedOnType(instanceRef.Type); drawable->UploadInstance(&desc, instanceRef.Index); } static UINT CreateInstance(RDebugDrawable::EType DrawableType) { auto& G = Get(); RDebugDrawable* drawable = GetDrawableBasedOnType(DrawableType); return drawable->NumInstances++; } private: static RDebugDrawable* GetDrawableBasedOnType(RDebugDrawable::EType type) { auto& G = Get(); switch (type) { case RDebugDrawable::PLANE: return &G.Plane; break; case RDebugDrawable::CUBE: return &G.Cube; break; case RDebugDrawable::CONE: return &G.Cone; break; case RDebugDrawable::CIRCLE: return &G.Circle; break; case RDebugDrawable::ICOSPHERE: return &G.Icosphere; break; case RDebugDrawable::UVSPHERE: return &G.Sphere; break; default: return nullptr; break; } } RDebugDrawable Plane{ RDebugDrawable::PLANE }; RDebugDrawable Cube{ RDebugDrawable::CUBE }; RDebugDrawable Circle{ RDebugDrawable::CIRCLE }; RDebugDrawable Cone{ RDebugDrawable::CONE }; RDebugDrawable Sphere{ RDebugDrawable::UVSPHERE }; RDebugDrawable Icosphere{ RDebugDrawable::ICOSPHERE }; };
true
6962e1f309ac249f393bd60ddac277381a7443ba
C++
winwingy/Study
/HomeDoOld/VolumeScreenWebSpeed/Old/WRect.cpp
UTF-8
767
2.71875
3
[]
no_license
#include "StdAfx.h" #include "WRect.h" namespace wingy_ui { WRect::WRect(void) { } WRect::WRect(int l, int t, int r, int b) { left = l; top = t; right = r; bottom = b; } WRect::operator RECT ()const { RECT rect = {left, top, right, bottom}; return rect; } WRect::WRect(const RECT& rect) { left = rect.left; top = rect.top; right = rect.right; bottom = rect.bottom; } int WRect::Width() const { return right - left; } int WRect::Height() const { return bottom - top; } WRect::~WRect(void) { } RECT WRect::GetRECT() const { return (RECT)(*this); } }
true
bbc64f52e00a25d6b9e4d9025cf28fded3ac2bd2
C++
furongw/DS
/ch4/ch4/main5.cpp
UTF-8
268
2.546875
3
[]
no_license
#include <stdio.h> #include "selectionsort.h" int main() { DataType R[7+1]; int data[7] = { 6,15,45,23,9,78,35 }; int i; for (i = 1; i <= 7; i++) { R[i].key = data[i-1]; } Simple_Select_Sort(R, 7); for (i = 1; i <= 7; i++) { printf("%d ", R[i].key); } }
true
745cb73ff3c8e519c2895157e887fef322815cc2
C++
singhdharmveer311/PepCoding
/Level-2/22. HashMap and Heap/Longest Substring Without Repeating Characters.cpp
UTF-8
865
2.921875
3
[ "Apache-2.0" ]
permissive
#include<iostream> #include<vector> #include<string> #include<map> using namespace std; int lengthOfLongestSubstring (string &s) { //Write your code here int i=-1,j=-1; int n=s.length(); int ans =-1; map<char,int> mp; while(i<n-1){ //acquire while(i<n-1){ i++; mp[s[i]]++; if(mp[s[i]]>1){ break; } else{ ans = max(ans,i-j); } } while(j < i){ j++; if(mp[s[j]]==2){ mp[s[j]]--; ans = max(ans,i-j); break; } else{ mp[s[j]]--; } } } return ans; } int main(int argc,char** argv){ string s; cin>>s; cout<<lengthOfLongestSubstring(s)<<endl; }
true
62c6a39258a250597b90a5c0d89a1f19729e7705
C++
lhprojects/QuSim
/src/DeviceTemplate.h
UTF-8
46,975
3.1875
3
[]
no_license
#pragma once #include "Device.h" #include <memory> #include <complex> #include <algorithm> #include <execution> #include <utility> #include <tuple> #include <cstddef> #include <cstring> // for memmove #ifndef QUSIM_HOST_DEVICE #define QUSIM_HOST_DEVICE #endif template<class Integer> struct int_iter { using difference_type = ptrdiff_t; using value_type = Integer; using pointer = Integer*; using reference = const Integer; // uh..., you can't change the value the iterator points to using iterator_category = std::random_access_iterator_tag; Integer fInt; int_iter() : fInt() {} int_iter(Integer i) : fInt(i) {} Integer operator[](size_t n) const { return fInt + n; } int_iter operator+(difference_type i) const { return int_iter(fInt + i); } int_iter& operator+=(difference_type i) { fInt += i; return *this; } int_iter operator-(difference_type i) const { return int_iter(fInt - i); } int_iter& operator-=(difference_type i) { fInt -= i; return *this; } difference_type operator-(int_iter r) const { return difference_type(fInt - r); } int_iter& operator++() { fInt += 1; return *this; } int_iter& operator--() { fInt += 1; return *this; } Integer operator*() const { return fInt; } }; template<class Iter1, class Iter2> struct zip_iter { Iter1 iter1; Iter2 iter2; using value_type1 = typename std::iterator_traits<Iter1>::value_type; using value_type2 = typename std::iterator_traits<Iter2>::value_type; using reference1 = typename std::iterator_traits<Iter1>::reference; using reference2 = typename std::iterator_traits<Iter2>::reference; using zip_value = std::pair<value_type1, value_type2>; using reference = std::pair<reference1, reference2>; using iterator_category = std::random_access_iterator_tag; using difference_type = ptrdiff_t; using value_type = zip_value; using pointer = value_type*; zip_iter() : iter1(), iter2() { } zip_iter(Iter1 iter1, Iter2 iter2) : iter1(iter1), iter2(iter2) { } zip_iter& operator+=(difference_type n) { iter1 += n; iter2 += n; } zip_iter operator+(difference_type n) const { return zip_iter(iter1 + n, iter2 + n); } zip_iter& operator-=(difference_type n) { iter1 -= n; iter2 -= n; } zip_iter operator-(difference_type n) const { return zip_iter(iter1 - n, iter2 - n); } difference_type operator-(zip_iter r) const { return r.iter1 - iter1; } zip_iter& operator++() { iter1 += 1; iter2 += 1; return *this; } zip_iter& operator--() { iter1 -= 1; iter2 -= 1; return *this; } reference operator*() const { return reference(*iter1, *iter2); } reference operator[](size_t n) const { return reference(iter1[n], iter2[n]); } }; template<class Iter1, class Iter2, class Iter3> struct zip_iter3 { Iter1 iter1; Iter2 iter2; Iter3 iter3; using value_type1 = typename std::iterator_traits<Iter1>::value_type; using value_type2 = typename std::iterator_traits<Iter2>::value_type; using value_type3 = typename std::iterator_traits<Iter3>::value_type; using reference1 = typename std::iterator_traits<Iter1>::reference; using reference2 = typename std::iterator_traits<Iter2>::reference; using reference3 = typename std::iterator_traits<Iter3>::reference; using zip_value = std::tuple<value_type1, value_type2, value_type3>; using reference = std::tuple<reference1, reference2, reference3>; using iterator_category = std::random_access_iterator_tag; using difference_type = ptrdiff_t; using value_type = zip_value; using pointer = value_type*; zip_iter3() : iter1(), iter2(), iter3() { } zip_iter3(Iter1 iter1, Iter2 iter2, Iter3 iter3) : iter1(iter1), iter2(iter2), iter3(iter3) { } zip_iter3& operator+=(difference_type n) { iter1 += n; iter2 += n; iter3 += n; } zip_iter3 operator+(difference_type n) const { return zip_iter3(iter1 + n, iter2 + n, iter3 + n); } zip_iter3& operator-=(difference_type n) { iter1 -= n; iter2 -= n; iter3 -= n; } zip_iter3 operator-(difference_type n) const { return zip_iter(iter1 - n, iter2 - n, iter3); } difference_type operator-(zip_iter3 r) const { return r.iter3 - iter3, r.iter2 - iter2, r.iter1 - iter1; } zip_iter3& operator++() { iter1 += 1; iter2 += 1; iter3 += 1; return *this; } zip_iter3& operator--() { iter1 -= 1; iter2 -= 1; iter3 -= 1; return *this; } reference operator*() const { return reference(*iter1, *iter2, *iter3); } reference operator[](size_t n) const { return reference(iter1[n], iter2[n], iter3[n]); } }; template<class E> struct ExecTrait { using Exec = E; static const bool cOnMainMemory = true; template<class T> using IntIter = int_iter<T>; template<class T> using ReverseIter = std::reverse_iterator<T>; template<class T> using DevicePtr = T*; using ComplexType = std::complex<double>; using RealType = double; template<class R> struct ScalarTrait { using DeviceType = R; using ComplexType = std::complex<R>; using RealType = R; static RealType real_max() { return std::numeric_limits<R>::max(); } }; template<class R> struct ScalarTrait<const R> { using DeviceType = const R; using ComplexType = const std::complex<R>; using RealType = const R; static RealType real_max() { return std::numeric_limits<R>::max(); } }; template<class R> struct ScalarTrait<std::complex<R>> { using DeviceType = std::complex<R>; using ComplexType = std::complex<R>; using RealType = R; static RealType real_max() { return std::numeric_limits<R>::max(); } }; template<class R> struct ScalarTrait<const std::complex<R>> { using DeviceType = const std::complex<R>; using ComplexType = const std::complex<R>; using RealType = const R; static RealType real_max() { return std::numeric_limits<R>::max(); } }; static void MemToDevice(Exec& exec, void* out, void const* in, size_t bytes) { std::copy(exec, (std::byte*)in, (std::byte*)in + bytes, (std::byte*)out); } static void MemToHost(Exec& exec, void* out, void const* in, size_t bytes) { std::copy(exec, (std::byte*)in, (std::byte*)in + bytes, (std::byte*)out); } static void MoveToDevice(void* out, void const* in, size_t bytes) { memmove(out, in, bytes); } static void MoveToHost(void* out, void const* in, size_t bytes) { memmove(out, in, bytes); } static void* Alloc(size_t bytes) { void *p = malloc(bytes); if (!p) { throw std::runtime_error("can't alloc " + std::to_string(bytes) + " bytes"); } return p; } static void Free(void* p) { return free(p); } template<class Iter, class T> static void Fill(Exec &exec, Iter b1, Iter e1, T const &v) { std::fill(exec, b1, e1, v); } template<class Iter, class OutIter> static void Copy(Exec& exec, Iter b1, Iter e1, OutIter b2) { std::copy(exec, b1, e1, b2); } template<class Iter, class OutIter, class UnitaryOp> static void Transform(Exec& exec, Iter b1, Iter e1, OutIter outIter, UnitaryOp op) { std::transform(exec, b1, e1, outIter, op); } template<class Iter, class Iter2, class OutIter, class BinaryOp> static void Transform(Exec& exec, Iter b1, Iter e1, Iter2 b2, OutIter outIter, BinaryOp op) { std::transform(exec, b1, e1, b2, outIter, op); } template<class TransOp> struct op_Expand { op_Expand(TransOp op) : transOp(op) { } TransOp transOp; template<class U, class V> auto operator()(U u, V v) { return transOp(u, std::get<0>(v), std::get<1>(v)); } }; template<class TransOp> struct op_Expand3 { TransOp transOp; op_Expand3(TransOp op) : transOp(op) { } template<class U, class V> auto operator()(U u, V v) { return transOp(u, std::get<0>(v), std::get<1>(v), std::get<2>(v)); } }; template<class Iter, class Iter2, class Iter3, class OutIter, class TransOp> static void Transform(Exec& exec, Iter b1, Iter e1, Iter2 b2, Iter3 b3, OutIter outIter, TransOp op) { using ZipIter = zip_iter<Iter2, Iter3>; using OpExpand = op_Expand<TransOp>; std::transform(exec, b1, e1, ZipIter(b2, b3), outIter, OpExpand(op)); } template<class Iter, class ReduceOp, class T, class TransOp> static T TransformReduce(Exec& exec, Iter b1, Iter e1, T init, ReduceOp reduce_op, TransOp transOp) { return std::transform_reduce(exec, b1, e1, init, reduce_op, transOp); } template<class Iter, class Iter2, class T, class ReduceOp, class TransOp> static T TransformReduce(Exec& exec, Iter b1, Iter e1, Iter2 b2, T init, ReduceOp reduceOp, TransOp transOp) { return std::transform_reduce(exec, b1, e1, b2, init, reduceOp, transOp); } template<class Iter, class Iter2, class Iter3, class T, class ReduceOp, class TransOp> static T TransformReduce(Exec& exec, Iter b1, Iter e1, Iter2 b2, Iter3 b3, T init, ReduceOp reduceOp, TransOp transOp) { using ZipIter = zip_iter<Iter2, Iter3>; using OpExpand2 = op_Expand<TransOp>; return std::transform_reduce(exec, b1, e1, ZipIter(b2, b3), init, reduceOp, OpExpand2(transOp)); } template<class Iter, class Iter2, class Iter3, class Iter4, class T, class ReduceOp, class TransOp> static T TransformReduce(Exec& exec, Iter b1, Iter e1, Iter2 b2, Iter3 b3, Iter4 b4, T init, ReduceOp reduceOp, TransOp transOp) { using ZipIter = zip_iter3<Iter2, Iter3, Iter4>; using OpExpand = op_Expand3<TransOp>; return std::transform_reduce(exec, b1, e1, ZipIter(b2, b3, b4), init, reduceOp, OpExpand(transOp)); } static inline QUSIM_HOST_DEVICE double Abs2(double s) { return s * s; } static inline QUSIM_HOST_DEVICE float Abs2(float s) { return s * s; } template<class R> static inline QUSIM_HOST_DEVICE R Abs2(std::complex<R> s) { return s.imag() * s.imag() + s.real() * s.real(); } static inline QUSIM_HOST_DEVICE std::complex<double> IMul(double c) { return std::complex<double>(double(0), c); } static inline QUSIM_HOST_DEVICE std::complex<double> IMul(std::complex<double> c) { return std::complex<double>(-c.imag(), c.real()); } static inline QUSIM_HOST_DEVICE double GetReal(std::complex<double> c) { return c.real(); } static inline QUSIM_HOST_DEVICE double GetImag(std::complex<double> c) { return c.imag(); } }; template<class ExecPar> struct DeviceTemplate : Device { using Trait = ExecTrait<ExecPar>; using ExecType = typename Trait::Exec; template<class T> using IntIter = typename Trait::template IntIter<T>; template<class T> using ReverseIter = typename Trait::template ReverseIter<T>; template<class T> using DevicePtr = typename Trait::template DevicePtr<T>; using ComplexType = typename Trait::ComplexType; using RealType = typename Trait::RealType; template<class T> using ScalarTrait = typename Trait::template ScalarTrait<T>; DevicePtr<RealType> DevicePtrCast(DReal* p) { return DevicePtr<RealType>((RealType*)p); } DevicePtr<const RealType> DevicePtrCast(DReal const * p) { return DevicePtr<const RealType>((RealType*)p); } DevicePtr<ComplexType> DevicePtrCast(DComplex* p) { return DevicePtr<ComplexType>((ComplexType*)p); } DevicePtr<const ComplexType> DevicePtrCast(DComplex const* p) { return DevicePtr<const ComplexType>((ComplexType*)p); } template<class Iter> ReverseIter<Iter> MakeReverseIter(Iter iter) { return ReverseIter<Iter>(iter); } ExecType fExecPar; QUSIM_HOST_DEVICE ExecType& Exec() { return fExecPar; } template<class S> static inline QUSIM_HOST_DEVICE S QuSqr(S s) { return s * s; } template<class R> struct op_LinearUpdate { QUSIM_HOST_DEVICE op_LinearUpdate(R gamma) : gamma(gamma) {} R const gamma; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return u * (1 - gamma) + v * gamma; } }; QUSIM_HOST_DEVICE static inline size_t fold_half(size_t i, size_t N) { return (i > N / 2) ? (N - i) : i; } QUSIM_HOST_DEVICE static inline void cal_index_2d(size_t &ix, size_t &iy, size_t idx, size_t nx, size_t ny) { auto const ix_ = idx / ny; auto const iy_ = idx % ny; ix = ix_; iy = iy_; } QUSIM_HOST_DEVICE static inline void cal_index_3d(size_t &ix, size_t &iy, size_t &iz, size_t idx, size_t nx, size_t ny, size_t nz) { size_t const k = idx % nz; size_t const idx2 = idx / nz; size_t const j = idx2 % ny; size_t const i = idx2 / ny; ix = i; iy = j; iz = k; } template<class P> struct op_ExpI { QUSIM_HOST_DEVICE op_ExpI(P a) : alpha(a) {} P const alpha; template<class U> QUSIM_HOST_DEVICE auto operator()(U o1) const { return exp(Trait::IMul(o1 * alpha)); } }; struct op_Abs2 { template<class U> QUSIM_HOST_DEVICE auto operator()(U o1) const { return Trait::Abs2(o1); } }; template<class P> struct op_MulExpI { P const alpha; QUSIM_HOST_DEVICE op_MulExpI(P a) : alpha(a) {} template<class V, class U> QUSIM_HOST_DEVICE auto operator()(V o1, U o2) const { return o1 * Trait::IMul(alpha*o2); } }; template<class P> struct op_ExpMul { QUSIM_HOST_DEVICE op_ExpMul(P a) : alpha(a) {} P const alpha; template<class U> QUSIM_HOST_DEVICE auto operator()(U o1) const { return exp(alpha * o1); } }; template<class P> struct op_MulExpMul { QUSIM_HOST_DEVICE op_MulExpMul(P a) : alpha(a) {} P const alpha; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U o1, V o2) const { return o1 * exp(alpha * o2); } }; template<class P> struct op_Scale { QUSIM_HOST_DEVICE op_Scale(P a) : alpha(a) {} P const alpha; template<class U> QUSIM_HOST_DEVICE auto operator()(U o1) const { return alpha * o1; } }; struct op_Min { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return u < v ? u : v; } }; struct op_Max { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return u >= v ? u : v; } }; struct op_Abs2Mul { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return Trait::Abs2(u) * v; } }; struct op_GetReal { template<class U> QUSIM_HOST_DEVICE auto operator()(U u) const { return Trait::GetReal(u); } }; struct op_GetImag { template<class U> QUSIM_HOST_DEVICE auto operator()(U u) const { return Trait::GetImag(u); } }; struct op_Add { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return u + v; } }; struct op_Sub { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return u - v; } }; struct op_Mul { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U o1, V o2) const { return o1 * o2; } }; struct op_MulR { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U o1, V o2) const { return o1 * Trait::GetReal(o2); } }; struct op_MulMinusI { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U o1, V o2) const { return o1 * V(0, -Trait::GetImag(o2)); } }; template<class P> struct op_MulMul { QUSIM_HOST_DEVICE op_MulMul(P a) : alpha(a) {} P const alpha; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U o1, V o2) const { return o1 * alpha * o2; } }; template<class R> struct op_Abs2K1D { QUSIM_HOST_DEVICE op_Abs2K1D(size_t sz, R ax) : ax(ax), Nx(sz){} R const ax; size_t const Nx; template<class U> QUSIM_HOST_DEVICE auto operator()(U u, size_t idx) const { size_t i = fold_half(idx, Nx); using RealType = typename ScalarTrait<U>::RealType; return Trait::Abs2(u) * QuSqr(RealType(i)) * ax; } }; template<class R, class S> struct op_MulExpK1D { QUSIM_HOST_DEVICE op_MulExpK1D(size_t sz, S ax) : Nx(sz), ax(ax) {} size_t const Nx; S const ax; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V idx) const { size_t const i = fold_half(idx, Nx); using RealType = typename ScalarTrait<U>::RealType; return u * exp(ax * QuSqr(RealType(i))); } }; template<class R> struct op_Abs2K2D { QUSIM_HOST_DEVICE op_Abs2K2D(size_t nx, size_t ny, R ax, R ay) : Nx(nx), Ny(ny), ax(ax), ay(ay) {} size_t const Nx; size_t const Ny; R const ax; R const ay; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V idx) const { size_t i, j; cal_index_2d(i, j, idx, Nx, Ny); i = fold_half(i, Nx); j = fold_half(j, Ny); using RealType = typename ScalarTrait<U>::RealType; return Trait::Abs2(u) * (QuSqr(RealType(i)) * ax + QuSqr(RealType(j)) * ay); } }; template<class R, class S> struct op_MulExpK2D { QUSIM_HOST_DEVICE op_MulExpK2D(size_t nx, size_t ny, R ax, R ay, S alpha) : Nx(nx), Ny(ny), ax(ax), ay(ay), alpha(alpha) { } size_t const Nx; size_t const Ny; R const ax; R const ay; S const alpha; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V idx) const { size_t i, j; cal_index_2d(i, j, idx, Nx, Ny); i = fold_half(i, Nx); j = fold_half(j, Ny); using RealType = typename ScalarTrait<U>::RealType; return u * exp(alpha * (QuSqr(RealType(i)) * ax + QuSqr(RealType(j)) * ay)); } }; template<class R> struct op_Abs2K3D { QUSIM_HOST_DEVICE op_Abs2K3D(size_t nx, size_t ny, size_t nz, R ax, R ay, R az) : Nx(nx), Ny(ny), Nz(nz), ax(ax), ay(ay), az(az) { } size_t const Nx; size_t const Ny; size_t const Nz; R const ax; R const ay; R const az; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V idx) const { size_t i, j, k; cal_index_3d(i, j, k, idx, Nx, Ny, Nz); i = fold_half(i, Nx); j = fold_half(j, Ny); k = fold_half(k, Nz); using RealType = typename ScalarTrait<U>::RealType; return Trait::Abs2(u) * (QuSqr(RealType(i)) * ax + QuSqr(RealType(j)) * ay + QuSqr(RealType(k)) * az); } }; template<class R, class S> struct op_MulExpK3D { QUSIM_HOST_DEVICE op_MulExpK3D(size_t nx, size_t ny, size_t nz, R ax, R ay, R az, S alpha) : Nx(nx), Ny(ny), Nz(nz), ax(ax), ay(ay), az(az), alpha(alpha) { } size_t const Nx; size_t const Ny; size_t const Nz; R const ax; R const ay; R const az; S const alpha; template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V idx) const { size_t i, j, k; cal_index_3d(i, j, k, idx, Nx, Ny, Nz); i = fold_half(i, Nx); j = fold_half(j, Ny); k = fold_half(k, Nz); using RealType = typename ScalarTrait<U>::RealType; return u * exp(QuSqr(RealType(i)) * ax + QuSqr(RealType(j)) * ay + QuSqr(RealType(k)) * az); } }; template<class R> struct op_G01D { QUSIM_HOST_DEVICE op_G01D(size_t n, R en, R eps, R dk2div2m) : N(n), E(en), Epsilon(eps), Dpx2Div2M(dk2div2m) { } size_t const N; R const E; R const Epsilon; R const Dpx2Div2M; template<class U> QUSIM_HOST_DEVICE auto operator()(U u, size_t v) const { using ComplexType = U; using RealType = RealType; v = fold_half(v, N); RealType t = QuSqr(RealType(v)) * Dpx2Div2M; return u / ComplexType(E - t, Epsilon); } }; template<class R> struct op_G02D { QUSIM_HOST_DEVICE op_G02D(size_t nx, size_t ny, R en, R eps, R Dpx2Div2M, R Dpy2Div2M) : Nx(nx), Ny(ny), E(en), Epsilon(eps), Dpx2Div2M(Dpx2Div2M), Dpy2Div2M(Dpy2Div2M) { } size_t const Nx; size_t const Ny; R const E; R const Epsilon; R const Dpx2Div2M; R const Dpy2Div2M; template<class U> QUSIM_HOST_DEVICE auto operator()(U psi, size_t idx) const { size_t i, j; cal_index_2d(i, j, idx, Nx, Ny); i = fold_half(i, Nx); j = fold_half(j, Ny); RealType t = QuSqr(RealType(i)) * Dpx2Div2M + QuSqr(RealType(j)) * Dpy2Div2M; return psi / ComplexType(E - t, Epsilon); } }; template<class R> struct op_G03D { QUSIM_HOST_DEVICE op_G03D(size_t nx, size_t ny, size_t nz, R en, R eps, R dkx2div2m, R dky2div2m, R dkz2div2m) : Nx(nx), Ny(ny), Nz(nz), E(en), Epsilon(eps), Dkx2HbarDiv2M(dkx2div2m), Dky2HbarDiv2M(dky2div2m), Dkz2HbarDiv2M(dkz2div2m) { } size_t const Nx; size_t const Ny; size_t const Nz; R const E; R const Epsilon; R const Dkx2HbarDiv2M; R const Dky2HbarDiv2M; R const Dkz2HbarDiv2M; template<class C> QUSIM_HOST_DEVICE auto operator()(C psi, size_t idx) const { using ComplexType = C; size_t k = idx % Nz; size_t idx2 = idx / Nz; size_t j = idx2 % Ny; size_t i = idx2 / Ny; i = fold_half(i, Nx); j = fold_half(j, Ny); k = fold_half(k, Nz); RealType t = QuSqr(RealType(i)) * Dkx2HbarDiv2M + QuSqr(RealType(j)) * Dky2HbarDiv2M + QuSqr(RealType(k)) * Dkz2HbarDiv2M; return psi / ComplexType(E - t, Epsilon); } }; template<class P> struct op_MulExpSquare { QUSIM_HOST_DEVICE op_MulExpSquare(P a) : alpha(a) {} P const alpha; template<class U> QUSIM_HOST_DEVICE auto operator()(U u, size_t idx) const { using RealType = typename ScalarTrait<P>::RealType; return u * exp(QuSqr(RealType(idx)) * alpha); } }; struct op_Abs2MulSquare { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { using RealType = typename ScalarTrait<U>::RealType; return Trait::Abs2(u) * QuSqr(RealType(v)); } }; struct op_AddMul { template<class U, class V, class P> QUSIM_HOST_DEVICE auto operator()(U delpsi, V psi0, P v) { return (delpsi + psi0) * v; } }; struct op_Minus { template<class U> QUSIM_HOST_DEVICE U operator()(U u) const { return -u; } }; template<class R> struct op_Vellekoop { QUSIM_HOST_DEVICE op_Vellekoop(R slow, R epsilon) : slow(slow), epsilon(epsilon) { } R const slow; R const epsilon; template<class U, class V, class P> QUSIM_HOST_DEVICE U operator()(U oldpsi, V newpsi, P v_) const { using ComplexType = typename ScalarTrait<R>::ComplexType; ComplexType gamma = 1. - Trait::IMul(v_) / epsilon; gamma *= slow; return (1. - gamma) * oldpsi + gamma * newpsi; } }; template<class R> struct op_Hao1 { QUSIM_HOST_DEVICE op_Hao1(R slow, R epsilon) : slow(slow), epsilon(epsilon) { } R const slow; R const epsilon; template<class U, class V, class P> QUSIM_HOST_DEVICE U operator()(U oldpsi, V newpsi, P v_) const { using ComplexType = typename ScalarTrait<R>::ComplexType; ComplexType gamma = 1. - Trait::IMul(ComplexType(v_.real(), -v_.imag())) / epsilon; gamma *= slow; return (1. - gamma) * oldpsi + gamma * newpsi; } }; template<class R> struct op_Hao2 { QUSIM_HOST_DEVICE op_Hao2(R slow, R epsilon) : slow(slow), epsilon(epsilon) { } R const slow; R const epsilon; template<class U, class V, class P> QUSIM_HOST_DEVICE U operator()(U oldpsi, V newpsi, P v_) const { using ComplexType = typename ScalarTrait<R>::ComplexType; ComplexType gamma = 2. / (1. + Trait::IMul(v_) / epsilon); gamma *= slow; return (1. - gamma) * oldpsi + gamma * newpsi; } }; template<class R> struct op_Add3 { QUSIM_HOST_DEVICE op_Add3(R epsilon) : epsilon(epsilon) {} R const epsilon; template<class U, class V, class P> QUSIM_HOST_DEVICE U operator()(U u, V psi0, P v_) const { using ComplexType = typename ScalarTrait<R>::ComplexType; return ComplexType(v_.real(), v_.imag() + epsilon) * u + v_.real() * psi0; } }; struct op_MinusAbs2 { template<class U, class V> QUSIM_HOST_DEVICE auto operator()(U u, V v) const { return Trait::Abs2(u - v); } }; template<class R> struct op_Xsec3D { R kx, ky, kz; R dx, dy, dz; R x0, y0, z0; size_t nx, ny, nz; op_Xsec3D(R kx, R ky, R kz, R dx, R dy, R dz, R x0, R y0, R z0, size_t nx, size_t ny, size_t nz) : kx(kx), ky(ky), kz(kz), dx(dx), dy(dy), dz(dz), x0(x0), y0(y0), z0(z0), nx(nx), ny(ny), nz(nz) { } template<class U> QUSIM_HOST_DEVICE auto operator()(U psi0, U psi, U v, size_t idx) const { size_t ix, iy, iz; cal_index_3d(ix, iy, iz, idx, nx, ny, nz); auto phase = (x0 + RealType(ix) * dx) * kx + (y0 + RealType(iy) * dy) * ky + (z0 + RealType(iz) * dz) * kz; return (psi0 + psi) * Trait::GetReal(v) * exp(-Trait::IMul(phase)); } }; bool OnMainMem() override { return Trait::cOnMainMemory; } void MemToDevice(void* out, void const* in, size_t bytes) override { Trait::MemToDevice(Exec(), out, in, bytes); } void MemToHost(void* out, void const* in, size_t bytes) override { Trait::MemToHost(Exec(), out, in, bytes); } void* AllocMem(size_t bytes) override { return Trait::Alloc(bytes); } DComplex At(DComplex const* in, size_t idx, size_t n) override { DComplex ans; Trait::MoveToHost(&ans, in + idx, sizeof(DComplex)); return ans; } DReal At(DReal const* in, size_t idx, size_t n) override { DReal ans; Trait::MoveToHost(&ans, in + idx, sizeof(DReal)); return ans; } void Set(DComplex* in, size_t idx, DComplex alpha) override { Trait::MoveToDevice(in + idx, &alpha, sizeof(DComplex)); } void Set(DReal* in, size_t idx, DReal alpha) override { Trait::MoveToDevice(in + idx, &alpha, sizeof(DReal)); } void Free(void* ptr) override { return Trait::Free(ptr); } void SetZero(DComplex* in, size_t n) override { Trait::Fill(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), DComplex(0)); } void SetOne(DComplex* in, size_t n) override { Trait::Fill(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), DComplex(1)); } DReal Abs2Idx(DComplex const* in, size_t n) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2Mul()); } DReal Abs2Idx(DReal const* in, size_t n) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2Mul()); } DReal Norm2(DComplex const* in, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + nx), RealType(0), op_Add(), op_Abs2()); } DReal Min(DComplex const* in, size_t n) override { return sqrt(Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), ScalarTrait<DReal>::real_max(), op_Min(), op_Abs2())); } DReal Max(DComplex const* in, size_t n) override { return sqrt(Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), DReal(0), op_Max(), op_Abs2())); } DReal SumReal(DComplex const* in, size_t n) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), DReal(0), op_Add(), op_GetReal() ); } DReal SumImag(DComplex const* in, size_t n) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + n), DReal(0), op_Add(), op_GetImag() ); } DReal MinusNorm2(DComplex const* in1, DComplex const* in2, size_t n) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in1), DevicePtrCast(in1 + n), DevicePtrCast(in2), RealType(0), op_Add(), op_MinusAbs2()); } DReal Norm2(DReal const* in, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in), DevicePtrCast(in + nx), RealType(0), op_Add(), op_Abs2()); } void Exp(DComplex* to, DReal const* from, DComplex alpha, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_ExpMul<ComplexType>(alpha)); } void ExpI(DComplex* to, DReal const* from, DReal alpha, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_ExpI<RealType>(alpha)); } void Exp(DComplex* to, DComplex const* from, DComplex alpha, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_ExpMul<ComplexType>(alpha)); } void CopyReverseMinu(DComplex* out, DComplex const* in, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(in), DevicePtrCast(in + nx), MakeReverseIter(DevicePtrCast(out + 1)), op_Minus()); } void Copy(DComplex* out, DComplex const* in, size_t nx) override { Trait::Copy(Exec(), DevicePtrCast(in), DevicePtrCast(in + nx), DevicePtrCast(out)); } void Copy(DReal* out, DReal const* in, size_t nx) override { Trait::Copy(Exec(), DevicePtrCast(in), DevicePtrCast(in + nx), DevicePtrCast(out)); } void Scale(DReal* fromto, DReal scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(fromto), op_Scale<RealType>(scale)); } void Scale(DComplex* fromto, DReal scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(fromto), op_Scale<RealType>(scale)); } void Scale(DComplex* fromto, DComplex scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(fromto), op_Scale<ComplexType>(scale)); } void Scale(DReal* to, DReal const* from, DReal scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_Scale<RealType>(scale)); } void Scale(DComplex* to, DComplex const* from, DReal scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_Scale<RealType>(scale)); } void Scale(DComplex* to, std::complex<double> const* from, DComplex scale, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from), DevicePtrCast(from + nx), DevicePtrCast(to), op_Scale<ComplexType>(scale)); } void Sub(DComplex* to, DComplex const* in1, DComplex const* in2, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(in1), DevicePtrCast(in1 + n), DevicePtrCast(in2), DevicePtrCast(to), op_Sub()); } void MulR(DComplex* to, DComplex const* from1, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_MulR()); } void MulMinusI(DComplex* to, DComplex const* from1, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_MulMinusI()); } void Mul(DComplex* to, DComplex const* from1, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_Mul()); } void Mul(DComplex* to, DReal const* from1, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_Mul()); } void Mul(DComplex* to, DReal const* from1, DComplex alpha, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_MulMul<ComplexType>(alpha)); } void Mul(DComplex* to, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from2), DevicePtrCast(from2 + nx), DevicePtrCast(to), DevicePtrCast(to), op_Mul()); } void MulExp(DComplex* to, DComplex const* from1, DComplex alpha, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(from1), DevicePtrCast(from1 + nx), DevicePtrCast(from2), DevicePtrCast(to), op_MulExpMul<ComplexType>(alpha)); } void MulExp(DComplex* fromto, DComplex alpha, DComplex const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(from2), DevicePtrCast(fromto), op_MulExpMul<ComplexType>(alpha)); } void MulExp(DComplex* fromto, DComplex alpha, DReal const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(from2), DevicePtrCast(fromto), op_MulExpMul<ComplexType>(alpha)); } void MulExpI(DComplex* fromto, DReal alpha, DReal const* from2, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(fromto), DevicePtrCast(fromto + nx), DevicePtrCast(from2), DevicePtrCast(fromto), op_MulExpI<RealType>(alpha)); } void MulExpIdx2(DComplex* psi, DComplex alpha, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx), IntIter<size_t>(0), DevicePtrCast(psi), op_MulExpSquare<ComplexType>(alpha)); } DReal Abs2Idx2(DComplex const* psi, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2MulSquare()); } DReal Abs2K1D(DComplex const* psi, DReal ax, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2K1D<RealType>(nx, ax)); } DReal Abs2K2D(DComplex const* psi, DReal ax, size_t nx, DReal ay, size_t ny) override { return Trait::TransformReduce(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx * ny), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2K2D<RealType>(nx, ny, ax, ay)); } DReal Abs2K3D(DComplex const* psi, DReal ax, size_t nx, DReal ay, size_t ny, DReal az, size_t nz) override { return Trait::TransformReduce(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx * ny * nz), IntIter<size_t>(0), RealType(0), op_Add(), op_Abs2K3D<RealType>(nx, ny, nz, ax, ay, az)); } void MulExpK1D(DComplex* psi, DComplex ax, size_t nx) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx), IntIter<size_t>(0), DevicePtrCast(psi), op_MulExpK1D<RealType, ComplexType>(nx, ax)); } void MulExpK2D(DComplex* psi, DComplex alpha, DReal ax, size_t nx, DReal ay, size_t ny) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx * ny), IntIter<size_t>(0), DevicePtrCast(psi), op_MulExpK2D<RealType, ComplexType>(nx, ny, ax, ay, alpha)); } void MulExpK3D(DComplex* psi, DComplex alpha, DReal ax, size_t nx, DReal ay, size_t ny, DReal az, size_t nz) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + nx * ny * nz), IntIter<size_t>(0), DevicePtrCast(psi), op_MulExpK3D<RealType, ComplexType>(nx, ny, nz, ax, ay, az, alpha)); } DComplex Abs2Mul(DComplex const* in1, DComplex const* in2, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in1), DevicePtrCast(in1 + nx), DevicePtrCast(in2), ComplexType(0), op_Add(), op_Abs2Mul()); } DReal Abs2Mul(DComplex const* in1, DReal const* in2, size_t nx) override { return Trait::TransformReduce(Exec(), DevicePtrCast(in1), DevicePtrCast(in1 + nx), DevicePtrCast(in2), RealType(0), op_Add(), op_Abs2Mul()); } void G01D(DComplex* psik, DReal E, DReal epsilon, DReal Dpx2Div2M, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psik), DevicePtrCast(psik + n), IntIter<size_t>(0), DevicePtrCast(psik), op_G01D<RealType>(n, E, epsilon, Dpx2Div2M)); } void G02D(DComplex* psik, DReal E, DReal epsilon, DReal Dkx2HbarDiv2M, DReal Dky2HbarDiv2M, size_t nx, size_t ny) override { Trait::Transform(Exec(), DevicePtrCast(psik), DevicePtrCast(psik + nx * ny), IntIter<size_t>(0), DevicePtrCast(psik), op_G02D<RealType>(nx, ny, E, epsilon, Dkx2HbarDiv2M, Dky2HbarDiv2M)); } void G03D(DComplex* psik, DReal E, DReal epsilon, DReal a1, DReal a2, DReal a3, size_t nx, size_t ny, size_t nz) override { Trait::Transform(Exec(), DevicePtrCast(psik), DevicePtrCast(psik + nx * ny * nz), IntIter<size_t>(0), DevicePtrCast(psik), op_G03D<RealType>(nx, ny, nz, E, epsilon, a1, a2, a3)); } DComplex Xsection3D(DComplex const* psi0, DComplex const* psi, DComplex const* v, DReal kx, DReal ky, DReal kz, DReal x0, DReal y0, DReal z0, DReal dx, DReal dy, DReal dz, size_t nx, size_t ny, size_t nz) override { return Trait::TransformReduce(Exec(), DevicePtrCast(psi0), DevicePtrCast(psi0 + nx * ny * nz), DevicePtrCast(psi), DevicePtrCast(v), IntIter<size_t>(0), ComplexType(0), op_Add(), op_Xsec3D<DReal>(kx, ky, kz, dx, dy, dz, x0, y0, z0, nx, ny, nz) ); } void AddMul(DComplex* psi, DComplex const* psi0, DComplex const* v, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + n), DevicePtrCast(psi0), DevicePtrCast(v), DevicePtrCast(psi), op_AddMul()); } void Add3(DComplex* deltaPsix, DComplex const* psi0x, DComplex const* v, DReal epsilon, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(deltaPsix), DevicePtrCast(deltaPsix + n), DevicePtrCast(psi0x), DevicePtrCast(v), DevicePtrCast(deltaPsix), op_Add3<RealType>(epsilon)); } void Add3(DComplex* add3, DComplex const* deltaPsix, DComplex const* psi0x, DComplex const* v, DReal epsilon, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(deltaPsix), DevicePtrCast(deltaPsix + n), DevicePtrCast(psi0x), DevicePtrCast(v), DevicePtrCast(add3), op_Add3<RealType>(epsilon)); } void LinearUpdate(DComplex* psi, DComplex const* newPsi, DReal gamma, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + n), DevicePtrCast(newPsi), DevicePtrCast(psi), op_LinearUpdate<RealType>(gamma)); } void Vellekoop(DComplex* psi, DComplex const* newPsi, DComplex const* V, DReal slow, DReal epsilon, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + n), DevicePtrCast(newPsi), DevicePtrCast(V), DevicePtrCast(psi), op_Vellekoop<RealType>(slow, epsilon)); } void Hao1(DComplex* psi, DComplex const* newPsi, DComplex const* V, DReal slow, DReal epsilon, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + n), DevicePtrCast(newPsi), DevicePtrCast(V), DevicePtrCast(psi), op_Hao1<RealType>(slow, epsilon)); } void Hao2(DComplex* psi, DComplex const* newPsi, DComplex const* V, DReal slow, DReal epsilon, size_t n) override { Trait::Transform(Exec(), DevicePtrCast(psi), DevicePtrCast(psi + n), DevicePtrCast(newPsi), DevicePtrCast(V), DevicePtrCast(psi), op_Hao2<RealType>(slow, epsilon)); } };
true
a4eb7616b7cee06a374ee4643c4db5ba5cae2ccc
C++
Silvertrousers/C_Compiler_Coursework
/translator/include/c2python_ast.hpp
UTF-8
922
2.640625
3
[]
no_license
#ifndef c2python_ast_hpp #define c2python_ast_hpp #include <vector> #include <string> #include "c2python_symbol_table.hpp" class c2python_ast_node{ public: std::string node_type; std::string value; std::vector<std::string> branch_notes; std::vector<c2python_ast_node*> branches; void print_python(int tab_count, c2python_symbol_table &table); c2python_ast_node(std::string _node_type, std::string _value, std::vector<c2python_ast_node*> _branches, std::vector<std::string> _branch_notes){ node_type = _node_type; value = _value; branches = _branches; branch_notes = _branch_notes; } c2python_ast_node(std::string _node_type, std::string _value){ node_type = _node_type; value = _value; branches = {}; branch_notes = {}; } ~c2python_ast_node(); }; extern c2python_ast_node *parseAST(); #endif
true
16300c7eb71b075f64cee5305364d9db4f915271
C++
omec-project/epctools
/include/epc/ehash.h
UTF-8
17,375
2.625
3
[ "Apache-2.0", "FSFAP" ]
permissive
/* * Copyright (c) 2009-2019 Brian Waters * Copyright (c) 2019 Sprint * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __ehash_h_included #define __ehash_h_included #include <limits> #include <bits/hash_bytes.h> #include "ebase.h" #include "estring.h" #include "eerror.h" /// @file /// @brief Hash calculation functions for strings and byte arrays. /// @brief Calcuates a 32-bit hash value for the specified string or array of characters. class EHash { public: /// @brief Returns the 32-bit hash value for the specified string. /// @param str The string to calculate the hash for. /// @return 32-bit hash value static ULong getHash(EString &str); /// @brief Returns the 32-bit has value for the array of characters. /// @param val The array of characters to calculate the hash for. /// @param len The length of the array of characters. /// @return 32-bit hash value static ULong getHash(cpChar val, ULong len); /// @brief Returns the 32-bit has value for the array of unsigned characters. /// @param val The array of unsigned characters to calculate the hash for. /// @param len The length of the array of unsigned characters. /// @return 32-bit hash value static ULong getHash(cpUChar val, ULong len); private: static ULong m_crcTable[256]; }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // ESipHash24 is adapted from the C reference implementation located at // https://github.com/veorq/SipHash which is licensed to public domain by // the [CC0 1.0 Universal] license. // DECLARE_ERROR(ESipHash24Error_InvalidKeyLength); /// @brief Calculates a 32-bit, 64-bit or 128-bit hash value using the SipHash algorithm. class ESipHash24 { public: /// @brief Represents a key to be used when calculating a hash value. class Key { public: /// @brief Class constructor. Key() : data_{0} {} /// @brief Copy constructor. /// @param k the Key to copy. Key(const Key &k) { assign(k.data_,sizeof(k.data_)); } /// @brief Class constructor. /// @param k a buffer containing the key value. /// @param len the length of the key buffer. Key(cpUChar k, const size_t len) { assign(k,len); } /// @brief The const unsigned char* conversion operator. /// @return The data value of this Key object. operator cpUChar() const { return data_; } /// @brief Data extractor. /// @return The data value of this Key object. cpUChar data() const { return data_; } /// @brief Assigns a new key value. /// @param k the data buffer to copy. /// @param len the length of the data buffer to copy. /// @return A reference to this object. Key& assign(cpUChar k, const size_t len) { size_t i = 0; for (; i<min(len,sizeof(data_)); i++) data_[i] = k[i]; for( ; i < sizeof(data_); i++) data_[i] = 0; return *this; } private: UChar data_[16]; }; /// @brief Assigns a new default key value. /// @param k the new key value. /// @return A reference to the new key value. static Key& setKey(const Key& k) { return key_ = k; } /// @brief Assigns a new default key value. /// @param val the key data for the new key value. /// @param len the length of the key data. /// @return A reference to the new key value. static Key& setKey(cpUChar val, const size_t len) { return key_.assign(val, len); } /// @brief Retrieves the default key. /// @return Reference to the default key. static const Key& key() { return key_; } /// @brief Returns the 32-bit hash associated with the string. /// @param str The string to calculate the hash for. /// @param key The key to be used to calculate the hash. /// @return The 32-bit hash value. static ULong getHash32(EString &str, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(str.c_str()), str.length(), key); } /// @brief Returns the 32-bit hash associated with the character buffer. /// @param val The character buffer to calculate the hash for. /// @param len The length of the character buffer. /// @param key The key to be used to calculate the hash. /// @return The 32-bit hash value. static ULong getHash32(cpChar val, const size_t len, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(val), len, key); } /// @brief Returns the 32-bit hash associated with the unsigned character buffer. /// @param in The unsigned character buffer to calculate the hash for. /// @param inlen The length of the unsigned character buffer. /// @param key The key to be used to calculate the hash. /// @return The 32-bit hash value. static ULong getHash32(cpUChar in, const size_t inlen, const Key &key=key_); /// @brief Calculates the 32-bit hash associated with the unsigned character buffer. /// @param in The unsigned character buffer to calculate the hash for. /// @param inlen The length of the unsigned character buffer. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True static Bool getHash32(cpUChar in, const size_t inlen, pUChar out, const size_t outlen, const Key &key=key_); /// @brief Returns the 32-bit hash associated with the unsigned character buffer. /// @param val The value to calculate the hash for. /// @param key The key to be used to calculate the hash. /// @return The 32-bit hash value. /// @{ static ULong getHash32(cShort val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cUShort val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cLong val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cULong val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cLongLong val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cULongLong val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cFloat val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULong getHash32(cDouble val, const Key &key=key_) { return getHash32(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } /// @} /// @brief Returns the 64-bit hash associated with the string. /// @param str The string to calculate the hash for. /// @param key The key to be used to calculate the hash. /// @return The 64-bit hash value. static ULongLong getHash64(EString &str, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(str.c_str()), str.length(), key); } /// @brief Returns the 64-bit hash associated with the character buffer. /// @param val The character buffer to calculate the hash for. /// @param len The length of the character buffer. /// @param key The key to be used to calculate the hash. /// @return The 64-bit hash value. static ULongLong getHash64(cpChar val, const size_t len, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(val), len, key); } /// @brief Returns the 64-bit hash associated with the unsigned character buffer. /// @param in The unsigned character buffer to calculate the hash for. /// @param inlen The length of the unsigned character buffer. /// @param key The key to be used to calculate the hash. /// @return The 64-bit hash value. static ULongLong getHash64(cpUChar in, const size_t inlen, const Key &key=key_); /// @brief Calculates the 64-bit hash associated with the unsigned character buffer. /// @param in The unsigned character buffer to calculate the hash for. /// @param inlen The length of the unsigned character buffer. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True static Bool getHash64(cpUChar in, size_t inlen, pUChar out, const size_t outlen, const Key &key=key_); /// @brief Returns the 64-bit hash associated with the unsigned character buffer. /// @param val The value to calculate the hash for. /// @param key The key to be used to calculate the hash. /// @return The 64-bit hash value. static ULongLong getHash64(cShort val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cUShort val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cLong val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cULong val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cLongLong val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cULongLong val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cFloat val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } static ULongLong getHash64(cDouble val, const Key &key=key_) { return getHash64(reinterpret_cast<cpUChar>(&val), sizeof(val), key); } /// @} /// @brief Calculates the 128-bit hash associated with the string. /// @param str The string to calculate the hash for. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True static Bool getHash128(EString &str, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(str.c_str()), str.length(), out, outlen, key); } /// @brief Calculates the 128-bit hash associated with the character buffer. /// @param val The character buffer to calculate the hash for. /// @param len The length of the unsigned character buffer. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True static Bool getHash128(cpChar val, size_t len, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(val), len, out, outlen, key); } /// @brief Calculates the 128-bit hash associated with the unsigned character buffer. /// @param in The unsigned character buffer to calculate the hash for. /// @param inlen The length of the unsigned character buffer. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True static Bool getHash128(cpUChar in, size_t inlen, pUChar out, const size_t outlen, const Key &key=key_); /// @brief Calculates the 128-bit hash associated with the unsigned character buffer. /// @param val The value to calculate the hash for. /// @param out The output buffer for the resulting hash. /// @param outlen The length of the output buffer. /// @param key The key to be used to calculate the hash. /// @return True /// @{ static Bool getHash128(cShort val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cUShort val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cLong val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cULong val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cLongLong val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cULongLong val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cFloat val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } static Bool getHash128(cDouble val, pUChar out, const size_t outlen, const Key &key=key_) { return getHash128(reinterpret_cast<cpUChar>(&val), sizeof(val), out, outlen, key); } /// @} private: static Bool getFullHash(cpUChar in, size_t inlen, cpUChar k, pUChar out, const size_t outlen); static Bool getHalfHash(cpUChar in, size_t inlen, cpUChar k, pUChar out, const size_t outlen); static Key key_; }; /// @brief Calcuates a 64-bit murmur hash for the specified value. class EMurmurHash64 { public: /// @brief Calculates a 64-bit murmur hash for the value. /// @param val The value to calculate the hash for. /// @param seed The seed to be used for the hash calculation. /// @return The 64-but murmur hash value. /// @{ static size_t getHash(cChar val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cUChar val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cShort val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cUShort val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cLong val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cULong val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cLongLong val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cULongLong val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cFloat val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(cDouble val, size_t seed=0xc70f6907UL) { return _Hash_bytes(&val,sizeof(val),seed); } static size_t getHash(const EString &val, size_t seed=0xc70f6907UL) { return _Hash_bytes(val.c_str(),val.size(),seed); } /// @} /// @brief Calculates a 64-bit murmur hash for the value. /// @param val The value to calculate the hash for. /// @param len The length of the value in bytes. /// @param seed The seed to be used for the hash calculation. /// @return The 64-bit murmur hash value. /// @{ static size_t getHash(cpChar val, size_t len, size_t seed=0xc70f6907UL) { return _Hash_bytes(val,len,seed); } static size_t getHash(cpUChar val, size_t len, size_t seed=0xc70f6907UL) { return _Hash_bytes(val,len,seed); } /// @} /// @brief Combines 2 64-bit hash values. /// @param h1 The first 64-bit hash value. /// @param h2 The second 64-bit hash value. /// @return The rsulting 64-bit combined hash value. static size_t combine(size_t h1, size_t h2) { return rotateLeft(circularAdd(h1,h2), 19) ^ circularSubtract(h1,h2); } private: static size_t rotateLeft(const size_t val, const size_t bits) { return (size_t)((val << bits) | (val >> (64 - bits))); } static size_t circularAdd(size_t val1, size_t val2) { size_t result = val1 + val2; return result + (result < val1); } static size_t circularSubtract(size_t val1, size_t val2) { size_t result = val1 - val2; return result - (result > val1); } }; #endif // #define __ehash_h_included
true
8cc2490c80125330ab99f9d450e6c298bf66bb6a
C++
awiebe1996/WiebeAndrew_CIS5_Spring2017
/Homework/Homework 4/Gaddis_8thEd_Chap5_Prob7_Pennies/main.cpp
UTF-8
1,320
3.75
4
[]
no_license
/* * File: main.cpp * Author: Andrew Wiebe * Created on April 3, 2017, 01:00 PM * Purpose: Pennies. */ //System Libraries #include <iostream> //Input - Output Library using namespace std; //Name-space under which system libraries exist //User Libraries //Global Constants //Function Prototypes //Execution begins here int main(int argc, char** argv) { //Declare variables float penny=1; //amount of pennies in $ float days; //amount of days this person has worked float day=1; //The minimum days that can be worked float total; //The total amount of money earned in $ //Initialize variables cout<<"How many days have you worked?"<<endl; cin>>days; if(days<=0){ //If the user enters a 0-negative number cout<<"Please enter a integer for the number of days"<<endl; return 0; } cout<<"You have made 1$ on the 1 day."<<endl; while(day<=days-1){ penny = penny*2;//squaring the pennies cout<<"You have made "<<penny/100<<"$ on the "<<day+1<<" day."<<endl; day++; //days increment total+=penny; //calculating the total } cout<<"Your total pay was "<<(total+1)/100<<"$"<<endl; //Output the transformed data //Exit stage right! return 0; }
true
afad44d08716c2671ae05c0b0ba2caa142d2eaa0
C++
RunaticMoon/BOJ
/백준/1157 단어 공부.cpp
UTF-8
729
3.3125
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> #include <functional> using namespace std; int compare(int a, int b) { return a - b; } int main() { string str; int alphabet[26], tempAlphabet[26], max = 0; fill(alphabet, alphabet + 26, 0); cin >> str; for (auto it = str.begin(); it != str.end(); ++it) { if (*it >= 'a') ++alphabet[*it - 'a']; else ++alphabet[*it - 'A']; } for (int i = 0; i < 26; ++i) { tempAlphabet[i] = alphabet[i]; } sort(tempAlphabet, tempAlphabet + 26, greater<int>()); max = tempAlphabet[0]; if (tempAlphabet[0] == tempAlphabet[1]) cout << "?"; else { for (int i = 0; i < 26; ++i) { if (alphabet[i] == max) cout << (char)('A' + i); } } return 0; }
true
9bf00e200ca4fb3bc94848bbd3e615c6338f2f61
C++
JosephMillsAtWork/u2t
/libu2t-private/gsettings-qt/src/util.cpp
UTF-8
1,927
2.578125
3
[]
no_license
/* * Copyright 2013 Canonical Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authors: Lars Uebernickel <lars.uebernickel@canonical.com> * Ryan Lortie <desrt@desrt.ca> */ #include <glib.h> #include <QString> /* convert 'some-key' to 'someKey' or 'SomeKey'. * the second form is needed for appending to 'set' for 'setSomeKey' */ QString qtify_name(const char *name) { bool next_cap = false; QString result; while (*name) { if (*name == '-') { next_cap = true; } else if (next_cap) { result.append(toupper(*name)); next_cap = false; } else { result.append(*name); } name++; } return result; } /* Convert 'someKey' to 'some-key' * * This is the inverse function of qtify_name, iff qtify_name was called with a * valid gsettings key name (no capital letters, no consecutive dashes). * * Returns a newly-allocated string. */ gchar * unqtify_name(const QString &name) { const gchar *p; QByteArray bytes; GString *str; bytes = name.toUtf8(); str = g_string_new (NULL); for (p = bytes.constData(); *p; p++) { if (isupper(*p)) { g_string_append_c (str, '-'); g_string_append_c (str, tolower(*p)); } else { g_string_append_c (str, *p); } } return g_string_free(str, FALSE); }
true
d593567bb46718ab6bcecfd87e57921b951417db
C++
jiye-algorithm/Data-Structure
/吉页c++库/ch2/employee/employee.cpp
GB18030
1,543
3.5
4
[]
no_license
/* 201449 15:04:51 ҳ ܣ ˳ģʱԱϰ500PM °뿪 ʾûϰСʱͷԼᱣϺţ ʹtimeCardȷԱһĹʣ ʹģķ֮ԱԼ £ ûдʱ timeCard ׳rangeError쳣 catch ģԱΪԱ */ #include <iostream> #include "E:\ѧϰ\ݽṹ\ݽṹSTL\ҳc++\include/y_random.h" #include "E:\ѧϰ\ݽṹ\ݽṹSTL\ҳc++\include/y_tcard.h" using namespace std; int main() { // ÿСʱнˮ const double PAYRATE = 12.5; // 5:00PM ° const time24 CHECKOUT(17, 0); // ģԱ°Ǵ < 0.25 ˵Աû° // ɹԱԱ randomNumber rnd; // ԱԱźϰʱ string id; int hour, minute; cout << "Աţ "; cin >> id; cout << endl; cout << "ԱϰСʱͷ "; cin >> hour >> minute; cout << endl; timeCard employee(id, PAYRATE, hour, minute); if (rnd.frandom() > 0.25) employee.PunchOut(CHECKOUT); // Աûд򿨣 Ա try { employee.writeSalaryInfo(); } catch (const rangeError& e) { // Ϣ cerr << e.what() << endl; employee.PunchOut(CHECKOUT); employee.writeSalaryInfo(); } return 0; }
true
b6e86bfb176512d09e24685ae91fa5afaecc0c6a
C++
arnabs542/ikk2
/Sorting/HW1/TopKElementsFromStream/TopKElementsFromStream.cpp
MacCentralEurope
3,697
3.703125
4
[]
no_license
/* Top K Problem Statement: You are given an array of integers arr, of size n, which is analogous to a continuous stream of integers input. Your task is to find K largest elements from a given stream of numbers. By definition, we don't know the size of the input stream. Hence, produce K largest elements seen so far, at any given time. For repeated numbers, return them only once. If there are less than K distinct elements in arr, return all of them. Note: Don't rely on size of input array arr. Feel free to use built-in functions if you need a specific data-structure. Input/Output Format For The Function: Input Format: There is only one argument: Integer array arr. Output Format: Return an integer array res, containing K largest elements. If there are less than K unique elements, return all of them. Order of elements in res does not matter. Input/Output Format For The Custom Input: Input Format: The first line of input should contain an integer n, denoting size of input array arr. In next n lines, ith line should contain an integer arr[i], denoting a value at index i of arr. In the next line, there should be an integer, denoting value of K. If n = 5, arr = [1, 5, 4, 4, 2] and K = 2, then input should be: 5 1 5 4 4 2 2 Output Format: Lets denote size of res as m, where res is the array of integers returned by solution function. Then, there will be m lines of output, where ith line contains an integer res[i], denoting value at index i of res. For input n = 5, arr = [1, 5, 4, 4, 2] and K = 2, output will be: 4 5 Constraints: 1 <= n <= 10^5 1 <= K <= 10^5 arr may contains duplicate numbers. arr may or may not be sorted Sample Test Case: Sample Test Case 1: Sample Input 1: arr = [1, 5, 4, 4, 2]; K = 2 Sample Output 1: [4, 5] Sample Test Case 2: Sample Input 2: arr = [1, 5, 1, 5, 1]; K = 3 Sample Output 2: [5, 1] //Less Execution time vector<int> topK(vector<int> arr, int k) { set<int> topk; for (int v : arr) { if (topk.find(v) == topk.end()) { topk.insert(v); } if (topk.size() > k) { topk.erase(topk.begin()); } } vector<int> result(topk.begin(), topk.end()); return result; } //Less Memory Usage vector <int> topK(vector <int> arr, int k) { vector<int> heap; unordered_set<int> seen; auto comparator = [](int a, int b) { return a>b; }; for (auto a: arr) { if (!seen.count(a)) { heap.push_back(a); push_heap(heap.begin(), heap.end(), comparator); if (heap.size() > k) { pop_heap(heap.begin(), heap.end(), comparator); heap.pop_back(); } // for (auto b: heap) { // cout << b << " "; // } // cout << endl; auto p = seen.insert(a); assert(p.second); } } return heap; // use minHeap // for (auto a: arr) { // heap.push_back(a); // push_heap(h.begin(), h.end(), cmp); // if (heap.size() > k) { // pop_heap(heap.begin(), heap.end(), cmp); // heap.pop_back(); // } // } } */ #include <bits/stdc++.h> using namespace std; /* * Complete the function below. */ vector <int> topK(vector <int> arr, int k) { } int main() { ostream &fout = cout; vector <int> res; int arr_size = 0; cin >> arr_size; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); vector<int> arr; for (int i = 0; i < arr_size; i++) { int arr_item; cin >> arr_item; cin.ignore(numeric_limits<streamsize>::max(), '\n'); arr.push_back(arr_item); } int k; cin >> k; cin.ignore(numeric_limits<streamsize>::max(), '\n'); res = topK(arr, k); for (int res_i = 0; res_i < res.size(); res_i++) { fout << res[res_i] << endl;; } return 0; }
true
21866c3cfedef97447da2c23b787af9806575456
C++
jectivex/ScriptCore
/backend/Lua/LuaLocalReference.cc
UTF-8
12,351
2.796875
3
[]
no_license
#include <ScriptCore/ScriptCore.h> #include "LuaHelper.hpp" namespace script { namespace lua_backend { int copyLocal(int index) { if (index == 0) { return 0; } auto lua = currentLua(); luaEnsureStack(lua, 1); lua_pushvalue(lua, index); return lua_gettop(lua); } void ensureNonnull(int index) { if (index != 0) { if (!lua_isnoneornil(currentLua(), index)) { return; } } throw Exception("NullPointerException"); } } // namespace lua_backend #define REF_IMPL_BASIC_FUNC(ValueType) \ Local<ValueType>::Local(const Local<ValueType>& copy) \ : val_(lua_backend::copyLocal(copy.val_)) {} \ Local<ValueType>::Local(Local<ValueType>&& move) noexcept : val_(move.val_) { move.val_ = 0; } \ Local<ValueType>::~Local() {} \ Local<ValueType>& Local<ValueType>::operator=(const Local& from) { \ Local(from).swap(*this); \ return *this; \ } \ Local<ValueType>& Local<ValueType>::operator=(Local&& move) noexcept { \ Local(std::move(move)).swap(*this); \ return *this; \ } \ void Local<ValueType>::swap(Local& rhs) noexcept { std::swap(val_, rhs.val_); } #define REF_IMPL_BASIC_EQUALS(ValueType) \ bool Local<ValueType>::operator==(const script::Local<script::Value>& other) const { \ return asValue() == other; \ } #define REF_IMPL_BASIC_NOT_VALUE(ValueType) \ Local<ValueType>::Local(InternalLocalRef val) : val_(val) { lua_backend::ensureNonnull(val); } \ Local<String> Local<ValueType>::describe() const { return asValue().describe(); } \ std::string Local<ValueType>::describeUtf8() const { return asValue().describeUtf8(); } #define REF_IMPL_TO_VALUE(ValueType) \ Local<Value> Local<ValueType>::asValue() const { return Local<Value>(val_); } REF_IMPL_BASIC_FUNC(Value) REF_IMPL_BASIC_FUNC(Object) REF_IMPL_BASIC_NOT_VALUE(Object) REF_IMPL_BASIC_EQUALS(Object) REF_IMPL_TO_VALUE(Object) REF_IMPL_BASIC_FUNC(String) REF_IMPL_BASIC_NOT_VALUE(String) REF_IMPL_BASIC_EQUALS(String) REF_IMPL_TO_VALUE(String) REF_IMPL_BASIC_FUNC(Number) REF_IMPL_BASIC_NOT_VALUE(Number) REF_IMPL_BASIC_EQUALS(Number) REF_IMPL_TO_VALUE(Number) REF_IMPL_BASIC_FUNC(Boolean) REF_IMPL_BASIC_NOT_VALUE(Boolean) REF_IMPL_BASIC_EQUALS(Boolean) REF_IMPL_TO_VALUE(Boolean) REF_IMPL_BASIC_FUNC(Function) REF_IMPL_BASIC_NOT_VALUE(Function) REF_IMPL_BASIC_EQUALS(Function) REF_IMPL_TO_VALUE(Function) REF_IMPL_BASIC_FUNC(Array) REF_IMPL_BASIC_NOT_VALUE(Array) REF_IMPL_BASIC_EQUALS(Array) REF_IMPL_TO_VALUE(Array) REF_IMPL_BASIC_FUNC(ByteBuffer) REF_IMPL_BASIC_NOT_VALUE(ByteBuffer) REF_IMPL_BASIC_EQUALS(ByteBuffer) REF_IMPL_TO_VALUE(ByteBuffer) REF_IMPL_BASIC_FUNC(Unsupported) REF_IMPL_BASIC_NOT_VALUE(Unsupported) REF_IMPL_BASIC_EQUALS(Unsupported) REF_IMPL_TO_VALUE(Unsupported) // ==== value ==== Local<Value>::Local() noexcept : val_() {} Local<Value>::Local(InternalLocalRef index) : val_(index) {} void Local<Value>::reset() { if (val_ != 0) { auto lua = lua_backend::currentLua(); lua_backend::luaEnsureStack(lua, 1); lua_pushnil(lua); lua_replace(lua, val_); } val_ = 0; } ValueKind Local<Value>::getKind() const { if (val_ == 0) { return ValueKind::kNull; } auto type = lua_type(lua_backend::currentLua(), val_); if (type <= 0) { return ValueKind::kNull; } else if (type == LUA_TSTRING) { return ValueKind::kString; } else if (type == LUA_TNUMBER) { return ValueKind::kNumber; } else if (type == LUA_TBOOLEAN) { return ValueKind::kBoolean; } else if (type == LUA_TFUNCTION) { return ValueKind::kFunction; } else if (isByteBuffer()) { return ValueKind::kByteBuffer; } else if (type == LUA_TTABLE) { // lua don't have array type, the are all tables return ValueKind::kObject; } else { return ValueKind::kUnsupported; } } bool Local<Value>::isNull() const { return val_ == 0 || lua_isnoneornil(lua_backend::currentLua(), val_); } bool Local<Value>::isString() const { return val_ != 0 && lua_type(lua_backend::currentLua(), val_) == LUA_TSTRING; } bool Local<Value>::isNumber() const { return val_ != 0 && lua_type(lua_backend::currentLua(), val_) == LUA_TNUMBER; } bool Local<Value>::isBoolean() const { return val_ != 0 && lua_type(lua_backend::currentLua(), val_) == LUA_TBOOLEAN; } bool Local<Value>::isFunction() const { return val_ != 0 && lua_type(lua_backend::currentLua(), val_) == LUA_TFUNCTION; } bool Local<Value>::isArray() const { return isObject(); } bool Local<Value>::isByteBuffer() const { auto engine = lua_backend::currentEngine(); return engine->byteBufferDelegate_->isByteBuffer(engine, *this); } bool Local<Value>::isObject() const { return val_ != 0 && lua_type(lua_backend::currentLua(), val_) == LUA_TTABLE; } bool Local<Value>::isUnsupported() const { return getKind() == ValueKind::kUnsupported; } Local<String> Local<Value>::asString() const { if (isString()) return Local<String>{val_}; throw Exception("can't cast value as String"); } Local<Number> Local<Value>::asNumber() const { if (isNumber()) return Local<Number>{val_}; throw Exception("can't cast value as Number"); } Local<Boolean> Local<Value>::asBoolean() const { if (isBoolean()) return Local<Boolean>{val_}; throw Exception("can't cast value as Boolean"); } Local<Function> Local<Value>::asFunction() const { if (isFunction()) return Local<Function>{val_}; throw Exception("can't cast value as Function"); } Local<Array> Local<Value>::asArray() const { if (isArray()) return Local<Array>{val_}; throw Exception("can't cast value as Array"); } Local<ByteBuffer> Local<Value>::asByteBuffer() const { if (isByteBuffer()) return Local<ByteBuffer>{val_}; throw Exception("can't cast value as ByteBuffer"); } Local<Object> Local<Value>::asObject() const { if (isObject()) return Local<Object>{val_}; throw Exception("can't cast value as Object"); } Local<Unsupported> Local<Value>::asUnsupported() const { if (isUnsupported()) return Local<Unsupported>{val_}; throw Exception("can't cast value as Unsupported"); } bool Local<Value>::operator==(const script::Local<script::Value>& other) const { // both null if (val_ == 0 || other.val_ == 0) { return other.val_ == val_; } return lua_compare(lua_backend::currentLua(), val_, other.val_, LUA_OPEQ); } // [+1, 0, 0] Local<String> Local<Value>::describe() const { if (isNull()) return String::newString("nil"); auto lua = lua_backend::currentLua(); lua_backend::luaEnsureStack(lua, 1); luaL_tolstring(lua, val_, nullptr); return Local<String>(lua_gettop(lua)); } Local<Value> Local<Object>::get(const script::Local<script::String>& key) const { auto lua = lua_backend::currentLua(); lua_backend::luaEnsureStack(lua, 1); lua_pushvalue(lua, key.val_); lua_gettable(lua, val_); return Local<Value>{lua_gettop(lua)}; } void Local<Object>::set(const script::Local<script::String>& key, const script::Local<script::Value>& value) const { auto lua = lua_backend::currentLua(); lua_backend::luaStackScope(lua, [this, lua, &key, &value]() { lua_backend::luaEnsureStack(lua, 2); lua_pushvalue(lua, key.val_); lua_backend::pushValue(lua, value); lua_settable(lua, val_); }); } void Local<Object>::remove(const Local<class script::String>& key) const { // lua has no remove, just set nil // http://lua-users.org/wiki/StoringNilsInTables set(key, {}); } bool Local<Object>::has(const Local<class script::String>& key) const { return !get(key).isNull(); } /** * Lua don't have built-in `instanceof` operator, * this functions has equivalent logic to lua code: * * \code * * if ScriptCore.isInstanceOf(self, type) then * return true * end * * local mt = getmetatable(self) * while mt ~= nil do * if mt == type then * return true * end * mt = getmetatable(self) * end * * return false * * \endcode * */ bool Local<Object>::instanceOf(const Local<class script::Value>& type) const { if (type.isNull() || !type.isObject()) return false; auto lua = lua_backend::currentLua(); auto index = type.val_; if (lua_backend::LuaEngine::isInstanceOf(lua, val_, index)) { return true; } lua_backend::luaEnsureStack(lua, 1); lua_pushvalue(lua, val_); auto meta = lua_gettop(lua); // metatable checks while (lua_getmetatable(lua, meta)) { lua_replace(lua, meta); if (lua_rawequal(lua, meta, index)) { // pop meta lua_pop(lua, 1); return true; } } // pop meta lua_pop(lua, 1); return false; } std::vector<Local<String>> Local<Object>::getKeys() const { auto lua = lua_backend::currentLua(); std::vector<Local<String>> ret; auto len = static_cast<int>(luaL_len(lua, val_)); lua_backend::luaEnsureStack(lua, len + 1); lua_pushnil(lua); // first key while (lua_next(lua, val_) != 0) { // pop value, we don't care lua_pop(lua, 1); if (lua_type(lua, -1) == LUA_TSTRING) { // dup key, one for result, one for next iteration lua_pushvalue(lua, -1); ret.emplace_back(Local<String>(lua_absindex(lua, -2))); } else { continue; } } return ret; } float Local<Number>::toFloat() const { return static_cast<float>(toDouble()); } double Local<Number>::toDouble() const { return lua_tonumber(lua_backend::currentLua(), val_); } int32_t Local<Number>::toInt32() const { return static_cast<int32_t>(toDouble()); } int64_t Local<Number>::toInt64() const { return static_cast<int64_t>(toDouble()); } bool Local<Boolean>::value() const { return lua_toboolean(lua_backend::currentLua(), val_); } Local<Value> Local<Function>::callImpl(const Local<Value>& thiz, size_t size, const Local<Value>* args) const { return lua_backend::callFunction(*this, thiz, size, args); } size_t Local<Array>::size() const { return static_cast<int>(luaL_len(lua_backend::currentLua(), val_)); } /** * LUA_NOTE: LUA array index are 1 based, OUR API IS TO 0 BASED. */ Local<Value> Local<Array>::get(size_t index) const { index++; auto lua = lua_backend::currentLua(); lua_backend::luaEnsureStack(lua, 1); lua_rawgeti(lua, val_, index); return Local<Value>{lua_gettop(lua)}; } void Local<Array>::set(size_t index, const script::Local<script::Value>& value) const { index++; auto lua = lua_backend::currentLua(); lua_backend::luaStackScope(lua, [this, lua, index, &value]() { lua_backend::luaEnsureStack(lua, 1); lua_backend::pushValue(lua, value); lua_rawseti(lua, val_, index); }); } void Local<Array>::add(const script::Local<script::Value>& value) const { set(size(), value); } void Local<Array>::clear() const { auto len = size(); for (size_t i = 0; i < len; ++i) { set(i, {}); } } ByteBuffer::Type Local<ByteBuffer>::getType() const { return ByteBuffer::Type::kUnspecified; } size_t Local<ByteBuffer>::byteLength() const { auto engine = lua_backend::currentEngine(); return engine->byteBufferDelegate_->getByteBufferSize(engine, asValue()); } void* Local<ByteBuffer>::getRawBytes() const { return getRawBytesShared().get(); } std::shared_ptr<void> Local<ByteBuffer>::getRawBytesShared() const { auto engine = lua_backend::currentEngine(); return engine->byteBufferDelegate_->getByteBuffer(engine, asValue()); } bool Local<ByteBuffer>::isShared() const { return true; } void Local<ByteBuffer>::commit() const {} void Local<ByteBuffer>::sync() const {} } // namespace script
true
f061487c8825afaf9a29f2c11a1bc70aad9a2e22
C++
m1001200/Linux_Project
/Quellcode/main.cpp
UTF-8
1,189
2.625
3
[ "MIT" ]
permissive
// Arkadij Doronin 24.05.2013 // IRC-Bot #ifndef main_cpp #define main_cpp #include <iostream> #include <string> #include <cstdlib> #include <cstdio> #include <cstring> #include "SQLite.h" using namespace std; int main(){ pid_t PID[15]; int countPID = 0; // sqlite_BD wird geöffnet sql_init(); BotParam botParam[2]; // Hier werden Parameter aus der sqlite_BD für jeden Bot geladen. // Bot_1-Parameter (port,server,channel,nick) botParam[0]= sqlite_getlogdatabase(1); // Bot_2-Parameter (port,server,channel,nick) botParam[1]= sqlite_getlogdatabase(2); // sqlite_BD wird geschlossen sql_close(); while (countPID < 2) { PID[countPID] = fork(); if (PID[countPID] < 0) { exit(1); } else if(PID[countPID] == 0){ // Übergabe an Bots if(execlp ("./Bot", "./Bot", botParam[countPID].port.c_str(), botParam[countPID].server.c_str(), botParam[countPID].channel.c_str(), botParam[countPID].nick.c_str(), NULL)); exit(1); } else { countPID++; } } return 0; } #endif
true
57f1654dbbfa214b7fd0798142b67de0da682a60
C++
ChenChangxi/Basic-Algorithm
/Hash/1092 To Buy or Not to Buy (20分).cpp
UTF-8
2,518
3.671875
4
[]
no_license
//// Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy some beads. There were many colorful strings of beads. However the owner of the shop would only sell the strings in whole pieces. Hence Eva must check whether a string in the shop contains all the beads she needs. She now comes to you for help: if the answer is Yes, please tell her the number of extra beads she has to buy; or if the answer is No, please tell her the number of beads missing from the string. //// //// For the sake of simplicity, let's use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. For example, the 3rd string in Figure 1 is the one that Eva would like to make. Then the 1st string is okay since it contains all the necessary beads with 8 extra ones; yet the 2nd one is not since there is no black bead and one less red bead. //// //// figbuy.jpg //// //// Figure 1 //// //// Input Specification: //// Each input file contains one test case. Each case gives in two lines the strings of no more than 1000 beads which belong to the shop owner and Eva, respectively. //// //// Output Specification: //// For each test case, print your answer in one line. If the answer is Yes, then also output the number of extra beads Eva has to buy; or if the answer is No, then also output the number of beads missing from the string. There must be exactly 1 space between the answer and the number. // //// Sample Input 1: //// ppRYYGrrYBR2258 //// YrR8RrY // //// Sample Output 1: //// Yes 8 // //// Sample Input 2: //// ppRYYGrrYB225 //// YrR8RrY // //// Sample Output 2: //// No 2 // //#include <iostream> //#include <unordered_map> // //using namespace std; // //string beads,own;int letter; // //unordered_map<char,int> counts; // //int main() { // cin>>beads>>own; // for(int i=0;i<beads.length();++i) counts[beads[i]]++; // for(int i=0;i<own.size();++i) if(counts[own[i]]-->0) ++letter; // letter==own.length()?cout<<"Yes "<<beads.length()-letter:cout<<"No "<<own.length()-letter; //} // ////说明:给一个原串和新串,如果原串包含新串(只是字符包含,对位置没有要求),输出原串中剩余字符的个数,否则输出新串中原串不包含的字符个数。 // ////分析:用一个hash数组来统计原串当中每个字符出现的次数,遍历新串并判断原串中的字符的个数是否够用,最后按要求输出即可。
true
b3effd82a163861e293b2b63859e3646f4500f1e
C++
megatrihr/Arduino-Project
/e_mpu6050_set.ino
UTF-8
1,909
2.84375
3
[]
no_license
void MPU6050_set(){ Wire.begin(); //Initiate the Wire library and join the I2C bus as a master /*set clockspeed 400KHz for fast access default is 100 KHz if you want to use default one just comment out line 27 */ Wire.setClock(400000); //wait for some time to get ready MPU6050 delay(500); Serial.begin(115200); // start serial communication high baudrate to avoid delay in serial print and read setup_gyro(); // setup gyro //initialize the values gyro_cal[0] = gyro_cal[1] = gyro_cal[2] = 0; acc[0] = acc[1] = acc[2] = 0; angle[0] = angle[1] = angle[2] = 0; angular_rate[0] = angular_rate[1] = angular_rate[2] = 0; calibrated = false; double acc_temp[3] = {0.0, 0.0, 0.0}; // tempurary variable //calibrating the gyro //dont move the gyro during calibration for (int i = 0; i < 2000; i++) { read_gyro(); //add a particular axis data to its corrosponding variable gyro_cal[0] += gyro[0]; gyro_cal[1] += gyro[1]; gyro_cal[2] += gyro[2]; acc_temp[0] += acc[0]; acc_temp[1] += acc[1]; acc_temp[2] += acc[2]; delayMicroseconds(4000); //wait for some times say 4000 µs } calibrated = true; //devide the total value by 2000 to get the average value gyro_cal[0] /= 2000; gyro_cal[1] /= 2000; gyro_cal[2] /= 2000; //take the average of acc data acc[0] = acc_temp[0] / 2000; acc[1] = acc_temp[0] / 2000; acc[2] = acc_temp[0] / 2000; //get the gravity vector gravity = sqrt(acc[0] * acc[0] + acc[1] * acc[1] + acc[2] * acc[2]); angle[0] = asin(acc[0] / gravity) * 57.295779; //set the initial pitch angle angle[1] = asin(acc[1] / gravity) * 57.295779; //set the initial roll angle angle[2] = 0; //set the initial yaw angle to 0 while (!Serial); //wait for serial port to ready count = 0; //set the variable count to zero which used to print data in serial }
true
c05075f825e8756bafa3cd9827c597688500e536
C++
KazuhitoT/competitive-programming
/lib/rolling_hash.cpp
UTF-8
1,086
2.90625
3
[]
no_license
#include <string> const unsigned long long B = 1000000007; // const unsigned long long B = 10000000000000061ULL; bool contain(std::string a, std::string b) { int al = a.length(), bl = b.length(); if (al > bl) { return false; } unsigned long long t = 1; for (int i = 0; i < al; i++) { t *= B; } unsigned long long ah = 0, bh = 0; for (int i = 0; i < al; i++) { ah = ah * B + a[i]; } for (int i = 0; i < al; i++) { bh = bh * B + b[i]; } for (int i = 0; i + al <= bl; i++) { if (ah == bh) { return true; } if (i + al < bl) { bh = bh * B + b[i + al] - b[i] * t; } } return false; } int overlap(std::string a, std::string b) { int al = a.size(), bl = b.size(); unsigned long long ah = 0, bh = 0, t = 1; int ans = 0; for (int i = 0; i < std::min(al, bl); i++) { ah = ah + a[al - i - 1] * t; bh = bh * B + b[i]; if (ah == bh) { ans = i + 1; } t *= B; } return ans; }
true
8142fcaa33b35911595f127ac8a69aaf3d702344
C++
nguaki/CPP
/hackerrank/variadic/var_parameters.cpp
UTF-8
856
4
4
[]
no_license
// Oct 13, 16 // //Demonstrates variadic ( unknown type and unknown size) // //1, 2, 3, 4 //1, 2, 3, 4, 5 //Hello, World, 2.3, 4.567, C, 1 #include <iostream> using namespace std; //This is a must otherwise there is a compilation error. //This takes care of the last element. template <typename T> ostream &vPrint(ostream &os, const T &t ) { return os << t; } template <typename T, typename... Args> //Expansion pack //The first t is for the first element. //rest represents 0 or more elements. ostream &vPrint(ostream &os, const T &t, const Args&... rest ) { os << t << ", "; return vPrint(os, rest...); //Recursive call. } int main() { vPrint(cout, 1,2,3,4); cout << endl; vPrint(cout, 1,2,3,4,5); cout << endl; vPrint(cout, "Hello", "World", 2.3, 4.567, 'C', true); cout << endl; return 0; }
true
5de04b8dbe8811a0b84adfd4c8d2377089b66d33
C++
godnoTA/acm.bsu.by
/4. Алгоритмы на графах/64. Построить матрицу смежности #3271/[OK]166384.cpp
UTF-8
664
3.03125
3
[ "Unlicense" ]
permissive
#include <iostream> #include <fstream> using namespace std; int main() { ifstream fin("input.txt"); ofstream fout("output.txt"); int n,m; fin >> n; fin >> m; int** matrix=new int*[n]; for (int i = 0; i < n; i++) matrix[i] = new int[n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) matrix[i][j] = 0; int value1, value2;; for (int i = 0; i < m;i++) { fin >> value1; fin >> value2; matrix[value1 - 1][value2 - 1] = matrix[value2-1][value1-1] = 1; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { fout << matrix[i][j] << " "; } fout << endl; } fin.close(); return 0; }
true
740760413cc79dfb396ff51f89e4aee84a7b99ad
C++
ajaysharma12799/Data-Structure-With-CPP
/Array/matrixmultiply.cpp
UTF-8
1,136
3.546875
4
[]
no_license
#include <iostream> using namespace std; int main(int argc, char const * argv[]) { int row, col, sum; cout << "\n Enter Row : "; cin >> row; cout << "\n Enter Column : "; cin >> col; //creating matrix of specific size int arr1[row][col], arr2[row][col], multi[row][col]; //taking input cout<<"\n Enter Element in Matrix 1 : "; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cin >> arr1[i][j]; } } cout<<"\n Enter Element in Matrix 2 : "; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cin >> arr2[i][j]; } } //multiplying matrix for (int i = 0; i < row; i++) { sum = 0; for (int j = 0; j < col; j++) { for(int k = 0; k < col; k++) { sum += arr1[i][k] * arr2[k][j]; } multi[i][j] = sum; } } cout<<"\n Resultant Matrix : \n"; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << multi[i][j]<<" "; } cout << endl; } return 0; }
true
571b806dd48dff2551f3c144ea8d11c879b711aa
C++
thesonofwil/cs220-Intermediate_Programming_Final_Project
/basicgamerules.cpp
UTF-8
5,695
3.328125
3
[]
no_license
//Brhea D'Mello //bdmello2 //Jingyu Huang //jhuan146 //Wilson Tjoeng //wtjoeng1 #include "basicgamerules.h" #include "entity.h" #include "entitycontroller.h" #include "game.h" #include "maze.h" #include "tile.h" BasicGameRules::BasicGameRules() { } BasicGameRules::~BasicGameRules() { } /* Allow Entity to make a move if: 1. it is onto an adjacent unnocupied Tile, and the Tile's checkMoveOnto member function allows the move, or 2. it is onto an adjacent Tile occupied by an entity with the “v” (moveable) property, and the moveable entity is permitted to move onto an unoccupied adjacent Tile in the same direction that the original entity is moving. This case allows the entity to "push" a moveable entity. Moves out of bounds, or moves by more than 1 unit of distance, are not allowed. */ bool BasicGameRules::allowMove(Game *game, Entity *actor, const Position &source, const Position &dest) const { // Return false if inanimate object, move would be > 1 space, or if dest contains a moveable object // that can't move further if (source.distanceFrom(dest) > 1) { return false; } // Check if actor can move to dest tile. return checkObjCanBePushed(game, actor, source, dest); } // Update the positions of the entity and the inanimate object if pushed // Precondition: allowMove() returned true void BasicGameRules::enactMove(Game *game, Entity *actor, const Position &dest) const { EntityController *controller = actor->getController(); // Check if any pushable objects occupy the dest tile. if (controller->isUser()) { std::vector<Entity *> objs = game->getEntitiesWithProperty('v'); for (Entity* obj : objs) { if (obj->getPosition() == dest) { Direction dir = getPushDirection(actor, obj); Position newPos = getPushPosition(game, dir, obj); obj->setPosition(newPos); break; // Only one object at a tile at a time } } } actor->setPosition(dest); } // Return the current game state. // If hero reaches Goal, return GameResult::HERO_WINS. // If minotour reaches hero, return GameResult::HERO_LOSES. // Otherwise return GameResult::UNKNOWN. // GameResult defined in gamerules.h GameResult BasicGameRules::checkGameResult(Game *game) const { Maze *maze = game->getMaze(); std::vector<Entity *> heroes = game->getEntitiesWithProperty('h'); // Get vector of heroes. A game may have multiple heroes std::vector<Entity *> minotaurs = game->getEntitiesWithProperty('m'); // Get vector of minotaurs. // Get list of positions of minotaurs std::vector<Position> minPositions; if (!minotaurs.empty()) { for (Entity* minotaur : minotaurs) { minPositions.push_back(minotaur->getPosition()); } } for (Entity* hero : heroes) { Position pos = hero->getPosition(); const Tile *tile = maze->getTile(pos); if (tile->isGoal()) { return GameResult::HERO_WINS; } // Check if any minotaur is at the same position as hero if (!minPositions.empty()) { for (Position p : minPositions) { if (p == pos) { return GameResult::HERO_LOSES; } } } } return GameResult::UNKNOWN; } // Get the direction of the actor pushing onto an inanimate object. Direction BasicGameRules::getPushDirection(Entity *actor, Entity *obj) const { Position actorPos = actor->getPosition(); // Get position of object Position objPos = obj->getPosition(); // Get position if it were displaced int x = objPos.getX() - actorPos.getX(); int y = objPos.getY() - actorPos.getY(); if (x == 0 && y == 1) { return Direction::DOWN; } else if (x == 0 && y == -1) { return Direction::UP; } else if (x == 1 && y == 0) { return Direction::RIGHT; } else if (x == -1 && y == 0) { return Direction::LEFT; } return Direction::NONE; // Invalid push } // Get the new position of an object when it's pushed Position BasicGameRules::getPushPosition(Game *game, Direction dir, Entity *obj) const { Maze *maze = game->getMaze(); Position newPos = obj->getPosition().displace(dir); // Get new position if object were to be pushed const Tile *destTile = maze->getTile(newPos); // Get tile at destination MoveResult check = destTile->checkMoveOnto(obj, obj->getPosition(), newPos); Entity *block = game->getEntityAt(newPos); // Check if there exists an entity at displaced position // Check if newPos is valid if (!newPos.inBounds(maze->getWidth(), maze->getHeight()) || check == MoveResult::BLOCK || block != nullptr) { return obj->getPosition(); // No change in position } return newPos; } bool BasicGameRules::checkObjCanBePushed(Game *game, Entity *actor, const Position &source, const Position &dest) const { Maze *maze = game->getMaze(); const Tile *tile = maze->getTile(dest); MoveResult result = tile->checkMoveOnto(actor, source, dest); Entity *object = game->getEntityAt(dest); if (object == nullptr && result == MoveResult::ALLOW) { // Empty adjacent tile return true; } else if (object == nullptr && result == MoveResult::BLOCK) { return false; } else if ((actor->hasProperty('m') && object->hasProperty('h')) || (actor->hasProperty('h') && object->hasProperty('m'))) { // Hero and minotaur return true; } else if (object->hasProperty('v')) { // v denotes moveable entity // Check if moveable object can be moved further Direction dir = getPushDirection(actor, object); if (dir == Direction::NONE) { return false; } Position pushPos = getPushPosition(game, dir, object); if (pushPos == object->getPosition()) { // Object cannot be pushed return false; } return true; } return true; // Default: there is no object }
true
1f5c3cf653bbb0e2aad01583a01f1d9ab1d278e4
C++
Wiladams/sr
/lessons/week7/testy/test_vectypes.cpp
UTF-8
195
2.53125
3
[ "MIT" ]
permissive
#include <stdio.h> #include "vec_types.hpp" void main() { vec3 v1 = {10,20,30}; vec3 v2 = {20,30,40}; vec3 v3 = v1 + v2; printf("add: %3.2f %3.2f %3.2f\n", v3.x, v3.y, v3.z); }
true
c98cd170200830440a12b0ddf1daa6f405f2c506
C++
lepecoder/threadpool
/threadpool.cpp
UTF-8
4,039
3.171875
3
[]
no_license
#include "threadpool.hpp" #include <cstring> #include <iostream> #include <string> using namespace std; /********** * 任务队列定义 * **********/ TaskQueue<function<void()>>::TaskQueue() { /* 构造函数 */ } TaskQueue<function<void()>>::~TaskQueue() { /* 析构函数 */ } /* 添加任务 */ void TaskQueue<function<void()>>::addTask(T &t) { mtx.lock(); m_taskQ.emplace(t); mtx.unlock(); } /* 添加任务 */ void TaskQueue<function<void()>>::addTask(callback f, void *arg) { mtx.lock(); m_taskQ.emplace(f, arg); mtx.unlock(); } /* 获取任务 */ Task TaskQueue<function<void()>>::takeTask() { Task task; mtx.lock(); if (!m_taskQ.empty()) { task = m_taskQ.front(); m_taskQ.pop(); } mtx.unlock(); return task; } /***************** * 线程池类的定义 * *****************/ ThreadPool::ThreadPool(int minNum, int maxNum) { taskQ = new TaskQueue; // 实例化一个任务队列 this->minNum = minNum; this->maxNum = maxNum; busyNum = 0; aliveNum = minNum; work_threads = new thread[maxNum]; // 根据最大线程数申请空间 /**************** * 根据最小线程数量创建工作线程 * ****************/ for (int i = 0; i < minNum; i++) { work_threads[i] = thread(worker, this); // 创建工作线程 cout << "创建子线程, ID: " << work_threads[i].get_id() << endl; } /*********** * 创建管理者线程 * ***********/ manager_thread = thread(manager, this); } /* 退出一个线程 */ void ThreadPool::threadExit() { // TODO 本身应该是有一个线程来调用这个函数 // 需要把调用这个函数的线程结束掉 // 这个就有点麻烦了,thread在初始化的时候就和运行的函数绑定,运行完之后就自动销毁, // 所以没有退出一个线程这个说法 } /* 管理者线程的任务函数 */ void *ThreadPool::manager(void *arg) { ThreadPool *pool = static_cast<ThreadPool *>(arg); while (!pool->shutdown) { // 建个3s检查一次 this_thread::sleep_for(3s); } } /************* * 工作线程的任务函数 * *************/ void *ThreadPool::worker(void *arg) { // 有很多个worker,每个worker都是一个线程,执行队列中的任务 // TODO 这里传入的this是实例对象的指针,但我的worker不是静态成员函数, // 所以即使不用传this也可以访问非静态的成员变量 // 写完后试一下不传this指针行不行 ThreadPool *pool = static_cast<ThreadPool *>(arg); while (true) { // 访问任务队列,加锁 unique_lock<mutex> mut(pool->mutPool); mut.lock(); // 判断任务个数,如果是0就阻塞 while (pool->taskQ->taskNum() == 0 && !pool->shutdown) { cout << "thread " << this_thread::get_id() << " waiting..." << endl; notEmpty.wait(mut); // 阻塞线程 // 解除阻塞后,判断是否需要销毁线程 if (pool->exitNum > 0) { pool->exitNum--; if (pool->aliveNum > pool->minNum) { pool->aliveNum--; mut.unlock(); pool->threadExit(); // TODO 退出哪个线程呢 } } } // 判断线程池是否被关闭了 if (pool->shutdown) { mut.unlock(); pool->threadExit(); // 退出工作线程 } // 从任务队列中取出一个任务 Task task = pool->taskQ->takeTask(); pool->busyNum++; // 工作线程+1 mut.unlock(); // 执行取出的任务 cout << "thread " << this_thread::get_id() << " start working..." << endl; task.func(task.arg); delete task.arg; task.arg = nullptr; // 任务执行完毕 cout << "thread " << this_thread::get_id() << " end working..." << endl; mut.lock(); pool->busyNum--; mut.unlock(); } return nullptr; }
true
b0b73f79069fff885a024cb752cc9eeb1b405fb2
C++
CP-Mangue/cp-lib
/codes/math_nt/SegmentedSieve.cpp
UTF-8
926
3.140625
3
[]
no_license
/* Author: Ubiratan Correia Barbosa Neto */ /* Segmented Erathostenes Sieve */ /* Needs primes up to sqrt(N) - Use normal sieve to get them */ namespace NT { const int MAX_N = 1123456; bitset<MAX_N> prime; vector<int> primes; vector<int> seg_primes; void Sieve(int n) { prime.set(); prime[0] = false; prime[1] = false; for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * p; i <= n; i += p) { prime[i] = false; } } } for (int i = 2; i <= n; i++) if (prime[i]) primes.pb(i); } void SegmentedSieve(int l, int r) { prime.set(); seg_primes.clear(); for (int p : primes) { int start = l - l % p - p; while (start < l) start += p; if (p == start) start += p; for (int i = start; i <= r; i += p) { prime[i - l] = false; } } for (int i = 0; i < r - l + 1; i++) { if (prime[i] && l + i > 1) { seg_primes.pb(l + i); } } } } // namespace NT
true
97a11b82181ef909ea0675c9c71d64b7b5cf0944
C++
kostathai/PrisonerDilemma
/table.h
UTF-8
1,326
2.9375
3
[]
no_license
#pragma once #include <fstream> #include <map> #include <vector> typedef std::map<std::vector<char>, std::vector<int>> MATRIX_; static MATRIX_ CreateMatrix(const std::string &filename) { MATRIX_ T; if (filename.empty()) { T[{'D', 'D', 'D'}] = {1, 1, 1}; T[{'D', 'D', 'C'}] = {5, 5, 0}; T[{'D', 'C', 'D'}] = {5, 0, 5}; T[{'C', 'D', 'D'}] = {0, 5, 5}; T[{'D', 'C', 'C'}] = {9, 3, 3}; T[{'C', 'D', 'C'}] = {3, 9, 3}; T[{'C', 'C', 'D'}] = {3, 3, 9}; T[{'C', 'C', 'C'}] = {7, 7, 7}; return T; } std::ifstream in(filename); if (in.is_open()) { int a, b, c; in >> a >> b >> c; T[{'D', 'D', 'D'}] = {a, b, c}; in >> a >> b >> c; T[{'D', 'D', 'C'}] = {a, b, c}; in >> a >> b >> c; T[{'D', 'C', 'D'}] = {a, b, c}; in >> a >> b >> c; T[{'C', 'D', 'D'}] = {a, b, c}; in >> a >> b >> c; T[{'D', 'C', 'C'}] = {a, b, c}; in >> a >> b >> c; T[{'C', 'D', 'C'}] = {a, b, c}; in >> a >> b >> c; T[{'C', 'C', 'D'}] = {a, b, c}; in >> a >> b >> c; T[{'C', 'C', 'C'}] = {a, b, c}; } else throw std::runtime_error("file with matrix not found :("); return T; }
true
2db1dd451375a7d6e2b35ba7ba5e1adbd6e954e9
C++
Ranima/particles
/CheckingBits/CheckingBits/pool.h
UTF-8
2,637
3.34375
3
[]
no_license
#pragma once #include <vector> template <typename T> class obpool { const static size_t Default_Pool_Size = 100; std::vector<T> pool; std::vector<bool> poolValidity; size_t nextEmpty() { for (size_t i = 0; i < poolValidity.size(); ++i) { return i; } size_t newIdx = pool.size(); pool.resize(pool.size() * 1.5); poolValidity.resize(poolValidity.size() * 1.5); return newIdx; } public: obpool() { pool.resize(Default_Pool_Size); poolValidity.resize(Default_Pool_Size); for (size_t i = 0; i < Default_Pool_Size; ++i) { pool.push_back(T()); poolValidity.push_back(false); } } ~obpool() {} class handle { public: handle() : pool(NULL) {} handle(obpool * poolPtr, size_t poolIdx) : pool(poolPtr), index(poolIdx) {} obpool * pool; size_t index; T& value() const { return pool->at(index); } void free() { pool->pop(index); } bool isValid() const { return pool->isValid(index); } size_t getIndex() const { return index; } handle &operator++() { for (size_t i = index + 1; i < pool->poolValidity.size(); ++i) { if (pool->poolValidity[i]) { index = i; return *this; } } index = pool->pool.size(); return *this; } T& operator*() const { return value(); } const T& operator*() const { return value(); } T& operator->() { return value(); } const T& operator->() const { return value(); } bool operator==(const handle& other) const { return other.pool == pool && other.index == index; } bool operator==(const handle& other) const { return other.pool == pool && other.index == index; } bool operator!=(const handle& other) { return !(other == *this); } }; handle push(const T& cpy) { size_t idx = nextEmpty(); assert(idx != -1); pool[idx] = cpy; poolValidity[idx] = true; return handle(this, idx); } void pop(size_t idx) { poolValidity[idx] = false; } bool isValid(size_t idx) const { return poolValidity[idx]; } handle begin() { for (size_t i = 0; i < poolValidity.size(); ++i) { if (poolValidity[i]) { return handle(this, i); } } assert(false && "can not iterate over a pool with no elements!"); } handle get(size_t idx) { assert(idx < pool.size()); return handle(this, idx); } handle end() { return handle(this, pool.size()); } T& at(size_t idx) { assert(isValid(idx)); return pool[idx]; } const T& at(size_t idx) { assert(isValid(idx)); return pool[idx]; } const T& at(size_t idx) const { assert(isValid(idx)); return pool[idx]; } };
true
ad6cd6ad12e515f4eea7bd038c4f0e9f363cbd38
C++
rohitsikka/UVa
/UVa 531.cpp
UTF-8
1,478
2.578125
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> using namespace std; string s1[110],s2[110]; short int C[110][110],S[110][110],n1,n2; bool flag=false; void print(int i,int j) { if(i<=0||j<=0) return ; if(S[i][j]==0) { print(i-1,j-1); if(flag) cout<<" "<<s1[i-1]; else { flag=true; cout<<s1[i-1]; } } else if(S[i][j]==1) print(i-1,j); else print(i,j-1); } void LCS() { for(int i=0;i<=n1;i++) C[i][0]=0; for(int i=0;i<=n2;i++) C[0][i]=0; for(int i=1;i<=n1;i++) { for(int j=1;j<=n2;j++) { if(s1[i-1]==s2[j-1]) { C[i][j]=C[i-1][j-1]+1; S[i][j]=0; } else if(C[i-1][j]>C[i][j-1]) { C[i][j]=C[i-1][j]; S[i][j]=1; } else { C[i][j]=C[i][j-1]; S[i][j]=-1; } } } print(n1,n2); } int main() { freopen("temp.txt","r",stdin); string str; while(cin>>str) { n1=1; n2=0; s1[0]=str; while(cin>>str&&str[0]!='#') { s1[n1]=str; n1++; } while(cin>>str&&str[0]!='#') { s2[n2]=str; n2++; } flag=false; LCS(); cout<<endl; } return 0; }
true
46f3da5c2809c3a448f84ebab9bcebfcbb648075
C++
adityabettadapura/Algorithms-and-Datastructures
/linkedlist/add_linked_lists.cpp
UTF-8
1,855
3.953125
4
[]
no_license
/**************************** Add two lists: the digits of two numbers are represented as nodes of 2 lists. Author: Aditya Bettadapura ****************************/ #include<iostream> #include<stack> #include<cstdlib> using namespace std; struct node{ int data; node* next; }; node* StackToList(stack<int> stk){ stack<int> reverse; int carry = 0; while(!stk.empty()){ reverse.push(stk.top()%10); carry = stk.top()/10; stk.pop(); if(!stk.empty()) stk.top() += carry; } if(carry) reverse.push(carry); node *head = new node(); node *temp = head; while(!reverse.empty()){ temp->data = reverse.top(); reverse.pop(); if(!reverse.empty()){ temp->next = new node(); temp = temp->next; } else { temp->next = NULL; } } return head; } node* AddLists(node* l1, node* l2){ if(l1 == NULL) return l2; if(l2 == NULL) return l1; stack<int> sumstk; node *ptr1 = l1; node *ptr2 = l2; while(ptr1 && ptr2){ sumstk.push(ptr1->data + ptr2->data); ptr1 = ptr1->next; ptr2 = ptr2->next; } while(ptr1){ sumstk.push(ptr1->data); ptr1 = ptr1->next; } while(ptr2){ sumstk.push(ptr2->data); ptr2 = ptr2->next; } node* out = StackToList(sumstk); return out; } void PopulateList(node* head){ node* input = head; int n = 5; int i=0; while(i < n){ input->data = rand()%10; if(i<n-1){ input->next = new node(); } else { input->next = NULL; } input = input->next; ++i; } } void PrintList(node* head){ node* input = head; while(input){ cout << input->data << " "; input = input->next; } cout << endl; } int main(){ srand(time(0)); node *list1 = new node(); node *list2 = new node(); PopulateList(list1); PrintList(list1); PopulateList(list2); PrintList(list2); node *result = AddLists(list1, list2); PrintList(result); free(list1); free(list2); free(result); return 0; }
true
847685e2ec0fb85b77073872ecb33ea07f52bfc4
C++
GLeurquin/shiny-waffle
/Project5/add_markers/src/add_markers.cpp
UTF-8
4,315
2.90625
3
[]
no_license
#include "ros/ros.h" #include <visualization_msgs/Marker.h> #include "add_markers/ModifyMarker.h" class AddMarkersService { public: AddMarkersService() { // Advertise a service to change markers in rviz ROS_INFO("Offering modify marker service on /add_markers/modify_marker"); service_ = n_.advertiseService("/add_markers/modify_marker", &AddMarkersService::handle_modify_marker_callback, this); // We are going to publish messages to the visualization_marker service of // rviz marker_pub_ = n_.advertise<visualization_msgs::Marker>( "visualization_marker", 1); // Wait for marker to be ready while (marker_pub_.getNumSubscribers() < 1) { if (!ros::ok()) { return; } ROS_WARN_ONCE("Please create a subscriber to the marker"); sleep(1); } ROS_INFO("Ready to display markers"); } private: ros::NodeHandle n_; ros::ServiceServer service_; ros::Publisher marker_pub_; /** * Creates a ros marker */ visualization_msgs::Marker get_marker(float x, float y, float z, float scale, ros::Duration duration, uint32_t id, uint32_t action ) { visualization_msgs::Marker marker; // Set the frame ID and timestamp. See the TF tutorials for information on // these. marker.header.frame_id = "/map"; // Use the map as a frame reference marker.header.stamp = ros::Time::now(); // Set the namespace and id for this marker. This serves to create a unique // ID // Any marker sent with the same namespace and id will overwrite the old one marker.ns = "basic_shapes"; marker.id = id; // Set the marker type. This is a CUBE marker.type = visualization_msgs::Marker::CUBE; // Set the marker action. Options are ADD, DELETE, and new in ROS Indigo: 3 // (DELETEALL) marker.action = action; // Set the pose of the marker. This is a full 6DOF pose relative to the // frame/time specified in the header marker.pose.position.x = x; marker.pose.position.y = y; marker.pose.position.z = z; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; // Set the scale of the marker -- 1x1x1 here means 1m on a side marker.scale.x = scale; marker.scale.y = scale; marker.scale.z = scale; // Set the color -- be sure to set alpha to something non-zero! marker.color.r = 0.0f; marker.color.g = 1.0f; marker.color.b = 0.0f; marker.color.a = 1.0; marker.lifetime = duration; return marker; } // This callback function executes whenever a add_markers service is requested bool handle_modify_marker_callback(add_markers::ModifyMarker::Request & req, add_markers::ModifyMarker::Response& res) { ROS_INFO("ModifyMarkerRequest received - j1:%1.2f, j2:%1.2f", (float)req.position.x, (float)req.position.y); // Create the marker object visualization_msgs::Marker the_marker = get_marker( req.position.x, req.position.y, req.position.z, req.scale, ros::Duration(), req.id, req.action ); // Publish it to rviz marker_pub_.publish(the_marker); // Return a response message res.msg_feedback = "Marker " + std::to_string(req.id) + " published."; ROS_INFO_STREAM(res.msg_feedback); return true; } }; // End of class AddMarkersService int main(int argc, char **argv) { // Initiate ROS ros::init(argc, argv, "add_markers"); // Create an object of class AddMarkersService that will take care of // everything AddMarkersService AddMarkersService; ros::spin(); return 0; }
true
69c7b7bc897fe9cbe7af75e368a0990538cb0458
C++
yisonPylkita/opengl-cpp-playground
/triangle/triangle/triangle.cpp
UTF-8
2,945
3.046875
3
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <GL/glew.h> #include <SFML/OpenGL.hpp> #include <SFML/Window.hpp> using namespace std::string_literals; // TODO: replace it with spdlog class Log { public: static void debug(const std::string &msg) { std::cout << "[DEBUG]: " << msg << std::endl; } static void error(const std::string &msg) { std::cout << "[ERROR]: " << msg << std::endl; } }; namespace { // An array of 3 vectors which represents 3 vertices const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; } int main_impl() { sf::ContextSettings opengl_context; opengl_context.majorVersion = 4; opengl_context.minorVersion = 5; opengl_context.depthBits = 24; sf::Window window(sf::VideoMode(800, 600), "Triangle", sf::Style::Default, opengl_context); window.setVerticalSyncEnabled(true); window.setActive(true); glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) throw std::runtime_error("Could not initialize glew - "s + reinterpret_cast<const char *>(glewGetErrorString(err))); // triangle setup // This will identify our vertex buffer GLuint vertexbuffer{}; GLuint VertexArrayID{}; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); bool running = true; while (running) { // handle events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { // end the program running = false; } else if (event.type == sf::Event::Resized) { // adjust the viewport when the window is resized glViewport(0, 0, event.size.width, event.size.height); } } // clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw... glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); // end the current frame (internally swaps the front and back buffers) window.display(); } return EXIT_SUCCESS; } int main() { int ret_code = EXIT_SUCCESS; try { ret_code = main_impl(); } catch (const std::exception &ex) { Log::error("Unhandled std exception -> "s + ex.what()); } catch (...) { Log::error("Unrecognized unhandled exception"); } Log::debug("Application exited with code: " + std::to_string(ret_code)); return ret_code; }
true
30a15e1f97e822273319a29be0ad3a59395a8a6d
C++
tfeldmann/QlockToo
/Firmware/DemoMatrix.ino
UTF-8
858
3.1875
3
[ "MIT" ]
permissive
// // Matrix screen Mode // #include "globals.h" void demo_matrix_setup() { srand(seconds + minutes + hours); display_clear(); corner_clear(); } void demo_matrix_loop() { static int wait_move = 0; static int wait_light = 0; if (++wait_move == 10) { wait_move = 0; // move rows one down for (byte y = ROWS - 1; y > 0; y--) { for (byte x = 0; x < COLS; x++) { matrix[y][x] = matrix[y - 1][x]; } } // darken first line for (byte x = 0; x < COLS; x++) { matrix[0][x] = 0.8 * matrix[0][x]; } } // add a light if (++wait_light == 20) { wait_light = 0; byte col = rand() % COLS; matrix[0][col] = constrain(matrix[0][col] + rand() % 255, 0, 255); } }
true
27b436dbfc83912efe3bbd535bdfe3d13060b24e
C++
art-kosm/homeworks
/term_2/homework_06/arithmetic_tree/operatorDiv.cpp
UTF-8
158
2.734375
3
[]
no_license
#include "operatorDiv.h" OperatorDiv::OperatorDiv() { value = '/'; } int OperatorDiv::calculate(int left, int right) const { return left / right; }
true
335f39087d8968b6f52061b79b8d4ec739646bb7
C++
BITERP/PinkRabbitMQ
/src/amqpcpp/linux_tcp/tcpchannel.h
UTF-8
1,154
3.25
3
[ "BSD-3-Clause", "MIT" ]
permissive
/** * TcpChannel.h * * Extended channel that can be constructed on top of a TCP connection * * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * @copyright 2015 - 2017 Copernica BV */ /** * Include guard */ #pragma once /** * Set up namespace */ namespace AMQP { /** * Class definition */ class TcpChannel : public Channel { public: /** * Constructor * * The passed in connection pointer must remain valid for the * lifetime of the channel. A constructor is thrown if the channel * cannot be connected (because the connection is already closed or * because max number of channels has been reached) * * @param connection * @throws std::runtime_error */ TcpChannel(TcpConnection *connection) : Channel(&connection->_connection) {} /** * Destructor */ virtual ~TcpChannel() {} /** * Copying is not allowed. * @param other */ TcpChannel(const TcpChannel &other) = delete; /** * But movement is allowed * @param other */ TcpChannel(TcpChannel &&other) = default; }; /** * End of namespace */ }
true
b062a05d820ac2df48c82282004f1d73a80d336c
C++
scortier/Snippets
/Amazon/Maxm min path 1.cpp
UTF-8
1,540
3.640625
4
[]
no_license
// Given a matrix with r rows and c columns, find the maximum score of a path starting at [0, 0] and ending at [r - 1, c - 1]. The score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4. #include <iostream> #include <string> #include <vector> #include <limits.h> using namespace std; int maxScore(vector<vector<int> >& grid) { if (grid.empty()) return 0; for (unsigned int i = 1; i < grid[0].size(); i++) { grid[0][i] = min(grid[0][i], grid[0][i - 1]); } for (unsigned int i = 1; i < grid.size(); i++) { grid[i][0] = min(grid[i][0], grid[i - 1][0]); } for (unsigned int i = 1; i < grid.size(); i++) { for (unsigned int j = 1; j < grid[0].size(); j++) { grid[i][j] = max(min(grid[i - 1][j], grid[i][j]), min(grid[i][j - 1], grid[i][j])); } } return grid[grid.size() - 1][grid[0].size() - 1]; } int main() { // Testing vector<vector<int>> grid1 {{5, 1}, {4, 5}}; vector<vector<int> > grid2 {{5, 1, 7}, {4, 8, 5}}; vector<vector<int> > grid3 {{1, 9, 9}, {9, 9, 9}, {9, 9, 9}}; vector<vector<int> > grid4 {{10, 7, 3}, {12, 11, 9}, {1, 2, 8}}; vector<vector<int> > grid5 {{20, 20, 3}, {20, 3, 20}, {3, 20, 20}}; cout << "Max score should be 4: " << maxScore(grid1) << "\n"; cout << "Max score should be 4: " << maxScore(grid2) << "\n"; cout << "Max score should be 1: " << maxScore(grid3) << "\n"; cout << "Max score should be 8: " << maxScore(grid4) << "\n"; cout << "Max score should be 3: " << maxScore(grid5) << "\n"; }
true
9ea7d61e5f77f5e1b5f14f3e5a632cd961d05b02
C++
D34Dspy/warz-client
/External/ChilKat/include/CkHtmlToText.h
UTF-8
1,898
2.515625
3
[]
no_license
// CkHtmlToText.h: interface for the CkHtmlToText class. // ////////////////////////////////////////////////////////////////////// #ifndef _CkHtmlToText_H #define _CkHtmlToText_H class CkByteData; #include "CkString.h" #include "CkMultiByteBase.h" #ifdef WIN32 #pragma warning( disable : 4068 ) #pragma unmanaged #endif /* IMPORTANT: Objects returned by methods as non-const pointers must be deleted by the calling application. */ #ifndef __sun__ #pragma pack (push, 8) #endif // CLASS: CkHtmlToText class CkHtmlToText : public CkMultiByteBase { public: CkHtmlToText(); virtual ~CkHtmlToText(); // May be called when finished with the object to free/dispose of any // internal resources held by the object. void dispose(void); // BEGIN PUBLIC INTERFACE bool UnlockComponent(const char *code); bool IsUnlocked(void) const; const char *readFileToString(const char *path, const char *srcCharset); bool ReadFileToString(const char *path, const char *srcCharset, CkString &outStr); bool WriteStringToFile(const char *str, const char *path, const char *charset); // TOTEXT_BEGIN bool ToText(const char *html, CkString &outStr); const char *toText(const char *html); // TOTEXT_END // RIGHTMARGIN_BEGIN int get_RightMargin(void); void put_RightMargin(int newVal); // RIGHTMARGIN_END // SUPPRESSLINKS_BEGIN bool get_SuppressLinks(void); void put_SuppressLinks(bool newVal); // SUPPRESSLINKS_END // DECODEHTMLENTITIES_BEGIN bool get_DecodeHtmlEntities(void); void put_DecodeHtmlEntities(bool newVal); // DECODEHTMLENTITIES_END // HTMLTOTEXT_INSERT_POINT // END PUBLIC INTERFACE // For internal use only. private: // Don't allow assignment or copying these objects. CkHtmlToText(const CkHtmlToText &) { } CkHtmlToText &operator=(const CkHtmlToText &) { return *this; } }; #ifndef __sun__ #pragma pack (pop) #endif #endif
true
6d18777865204f78bcd08c289008734791c47133
C++
Moreniell/study-projects
/CPlusPlus/Time/Time.cpp
UTF-8
3,131
3.359375
3
[]
no_license
#include "stdafx.h" #include "Time.h" #include "Utils.h" // Конструкторы и деструктор Time::Time(WORD hh = 0, WORD mm = 0, WORD ss = 0) { setTime(hh, mm, ss); cout<<"Конструктор"<<endl; } Time::Time(const Time &time) { setTime(time.hour, time.minute, time.second); cout<<"Копирующий конструктор"<<endl; } Time::~Time() { } // МЕТОДЫ // Арифметические void Time::add(WORD hh, WORD mm, WORD ss) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(hh,mm,ss); Time c = SecToTime(a+b); hour = c.hour; minute = c.minute; second = c.second; } void Time::sub(WORD minutes) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(hh,mm,ss); Time c = abs(SecToTime(a-b)); hour = c.hour; minute = c.minute; second = c.second; } Time Time::diff(Time x) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(x.hour,x.minute,x.second); return a > b ? a-b : b-a; } // Логические bool Time::equal(Time x) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(x.hour,x.minute,x.second); return a == b; } bool Time::greate(Time x) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(x.hour,x.minute,x.second); return a > b; } bool Time::less(Time x) { WORD a = TimeToSec(hour,minute,second); WORD b = TimeToSec(x.hour,x.minute,x.second); return a < b; } // Проверяет время на корректность. bool Time::IsValidTime(WORD hour, WORD minute, WORD second) { return second >= 0 && second <= 60 && minute >= 0 && minute <= 60 && hour >= 0 && hour <= 24; } // Геттеры и Сеттеры WORD Time::getHour() { return hour; } WORD Time::getMinute() { return minute; } WORD Time::getSecond() { return second; } void Time::setHour(WORD hour) { this->hour = hour; } void Time::setMinute(WORD minute) { this->minute = minute; } void Time::setSecond(WORD second) { this->second = second; } void Time::setTime(WORD hour, WORD minute, WORD second) { // setTime - Альтернативное название для Init if (IsValidTime(hour, minute, second)) { setHour(hour); setMinute(minute); setSecond(second); } else { throw string("Not valid time!"); } } void Time::coutTime() { cout << hour << ':' << minute << ':' << second; } // Конвертеры WORD Time::TimeToSec() { return (hour*3600)+(minute*60)+second; } // Функция вычисляет наибольшее простое кратное числа. int Time::NPK(int numb,int mult) { int f; for (int i = 1; i > numb; i++) { if (i % mult == 0) f = i; } return f; } Time Time::SecToTime(WORD secs) { Time t; int m = secs/NPK(secs,60); int s = secs-m; int h = m/NPK(m,60); m = m-h; t.hour = h; t.minute = m; t.second = s; return t; } //Инициализация. void Time::Init() { Init(0, 24); } void Time::Init(a, b) { if (not (IsValidTime(a, 0, 0) || IsValidTime(b, 0, 0))) {throw string("Not valid hour!"); return;} WORD h = Random(a, b); WORD m = Random(0, 60); WORD s = Random(0, 60); hour = h; minute = m; second = s; }
true
81bc7f2af0511a5776883158436d30fbc135f1c7
C++
chengfx/my_leetcode_exercise
/77. Combinations/Combinations.cpp
UTF-8
873
3.40625
3
[]
no_license
#include"Combinations.h" #include<iostream> using namespace std; void Combinations::example() { vector<vector<int>> results = combine(4, 3); for (auto& row : results) { for (auto& column : row) cout << column; cout << endl; } } vector<vector<int>> Combinations::combine(int n, int k) { vector<vector<int>> results; vector<int> digits(n, 0),temp; for (int i = 0; i < n; i++) digits[i] = i + 1; results.push_back(digits); recursive(digits, temp, results, 0, k); return results; } void Combinations::recursive(const vector<int>&digits,vector<int>&temp,vector<vector<int>>& results, int index, int k) { if ((digits.size() - index) < k) return; if (k == 0) { results.push_back(temp); return; } temp.push_back(digits[index]); recursive(digits, temp, results, index + 1, k - 1); temp.pop_back(); recursive(digits, temp, results, index + 1, k); }
true
0cdc6351472a95ab09f492c986aa3530221d74a6
C++
pdschubert/WALi-OpenNWA
/Source/opennwa/RelationOpsPaired.hpp
UTF-8
13,846
2.65625
3
[ "MIT" ]
permissive
#ifndef RELATION_OPS_PAIRED_HPP #define RELATION_OPS_PAIRED_HPP #include <algorithm> #include <iterator> #include <cassert> #include <utility> #include <map> #include <set> #define relations std_set_relations #include "RelationOps.hpp" #undef relations #define relations buddy_relations #include "RelationOpsBuddy.hpp" #undef relations namespace wali { namespace relations { namespace wsr = wali::std_set_relations; namespace wbr = wali::buddy_relations; typedef wsr::RelationTypedefs<unsigned long>::BinaryRelation wsrbr; typedef wbr::RelationTypedefs<unsigned long>::BinaryRelation wbrbr; extern int count; inline void counter(char* vals, int size) { int numDontCares = 0; for (int i=0; i<size; ++i) { if (vals[i] < 0) { ++numDontCares; } } //for (int i=0; i<size; ++i) { // std::cout << (vals[i] < 0 ? 'X' : ('0' + vals[i])); //} //std::cout << "\n"; count += 1 << numDontCares; } inline int bdd_rel_size(::bdd b, int factor) { count = 0; //std::cout << "Call to allsat:\n"; bdd_allsat(b, counter); assert(bdd_satcount(b) == count); return count/factor; } /// Wraps a bdd in a nice friendly package struct BinaryRelation { wsrbr set; wbrbr bdd; BinaryRelation(unsigned int largest) : bdd(largest) {} BinaryRelation() {} bool insert(unsigned int leftVal, unsigned int rightVal) { return insert(std::make_pair(leftVal, rightVal)); } bool insert(std::pair<unsigned int, unsigned int> pair) { assert(check()); bool added1 = set.insert(pair).second; bool added2 = bdd.insert(pair); assert(check()); assert(added1 == added2); return added1; } bool empty() const { assert(set.empty() == bdd.empty()); return set.empty(); } bool operator== (BinaryRelation const & other) const { assert( (set == other.set) == (bdd == other.bdd) ); return bdd == other.bdd; } ::bdd getBdd() const { return bdd.getBdd(); } int bddSize() const { return bdd_rel_size(bdd.getBdd(), 256); } int setSize() const { return set.size(); } bool check() const { return bddSize() == setSize(); } }; struct TernaryRelation { wsr::RelationTypedefs<unsigned long>::TernaryRelation set; wbr::RelationTypedefs<unsigned long>::TernaryRelation bdd; TernaryRelation(unsigned int largest) : bdd(largest) {} TernaryRelation() {} bool insert(unsigned int leftVal, unsigned int middleVal, unsigned int rightVal) { bool added1 = set.insert(Triple<unsigned long,unsigned long,unsigned long>(leftVal, middleVal, rightVal)); bool added2 = bdd.insert(Triple<unsigned,unsigned,unsigned>(leftVal, middleVal, rightVal)); assert(added1 == added2); return added1; } bool insert(Triple<unsigned, unsigned, unsigned> triple) { return insert(triple.first, triple.second, triple.third); } bool insert(Triple<unsigned long, unsigned long, unsigned long> triple) { return insert(triple.first, triple.second, triple.third); } bool check() const { return bdd_rel_size(bdd.getBdd(), 16) == set.size(); } }; /// This can be used in client code to hide the actual relation types template<typename State> struct RelationTypedefs { typedef wali::relations::BinaryRelation BinaryRelation; typedef wali::relations::TernaryRelation TernaryRelation; }; using wbr::buddyInit; // inline // void buddyInit() // { // if (!bdd_isrunning()) { // const int million = 1000000; // int rc = bdd_init( 50*million, 100000 ); // if( rc < 0 ) { // std::cerr << "[ERROR] " << bdd_errstring(rc) << std::endl; // assert( 0 ); // exit(10); // } // // Default is 50,000 (1 Mb),memory is cheap, so use 100,000 // bdd_setmaxincrease(100000); // } // } /// Composes two binary relations /// /// { (x,z) | (x,y) \in r1, (y,z) \in r2} /// /// Parameters: /// out_result: The relational composition of r1 and r2 /// r1: relation 1 /// r2: relation 2 inline void compose(BinaryRelation & out_result, BinaryRelation const & r1, BinaryRelation const & r2) { wsr::compose<unsigned long>(out_result.set, r1.set, r2.set); wbr::compose(out_result.bdd, r1.bdd, r2.bdd); assert(out_result.check()); } /// Projects out the symbol in the internal and call relation /// /// {(source, target) | (source, alpha, target) \in delta} /// /// Parameters: /// out_result: The relation delta restricted to alpha /// delta: Internals or calls relation /// alpha: Alphabet symbol to select and project template<typename OutRelation, typename State, typename Symbol> void project_symbol_3_set(OutRelation & out_result, std::set<Triple<State, Symbol, State> > const & delta, Symbol alpha) { wsr::project_symbol_3<OutRelation, State, Symbol>(out_result, delta, alpha); } template<typename OutRelation, typename State, typename Symbol> void project_symbol_3(OutRelation & out_result, std::set<Triple<State, Symbol, State> > const & delta, Symbol alpha) { wsr::project_symbol_3<wsrbr, State, Symbol>(out_result.set, delta, alpha); wbr::project_symbol_3<wbrbr, State, Symbol>(out_result.bdd, delta, alpha); assert(out_result.check()); } /// Performs the sort of merge required for NWA return edges /// /// {(q, q') | (q,q1) \in r_call, (q1,q2) \in r_exit, (q2,q1,q') \in delta} /// /// Parameters: /// out_result: The relational composition of R1 and R2 /// r_exit: The relation at the exit node /// r_call: The relation at the call node /// delta_r: The return transition relation with the alphabet /// symbol projected out inline void merge(BinaryRelation & out_result, BinaryRelation const & r_exit, BinaryRelation const & r_call, TernaryRelation const & delta_r) { assert(out_result.check()); assert(r_exit.check()); assert(r_call.check()); assert(delta_r.check()); wsr::merge<unsigned long>(out_result.set, r_exit.set, r_call.set, delta_r.set); wbr::merge(out_result.bdd, r_exit.bdd, r_call.bdd, delta_r.bdd); //std::cout << out_result.bdd.getBdd() << "\n"; assert(out_result.check()); } /// Projects out the symbol in the return relation /// /// {(source, pred, target) | (source, pred, alpha, target) \in delta} /// /// Parameters: /// out_result: The ternary relation delta restricted to alpha /// delta: Return relation /// alpha: Alphabet symbol to select and project template<typename State, typename Symbol> void project_symbol_4(TernaryRelation & out_result, std::set<Quad<State, State, Symbol, State> > const & delta, Symbol alpha) { assert(out_result.check()); wsr::project_symbol_4<State, Symbol>(out_result.set, delta, alpha); wbr::project_symbol_4<State, Symbol>(out_result.bdd, delta, alpha); assert(out_result.check()); } template<typename State> State biggest(State s1, State s2, State s3) { return std::max(s1, std::max(s2, s3)); } /// Constructs the transitive closure of an algorithm. /// /// TODO: Right now we break the abstraction and assume State is a /// (reasonably small) integer. /// /// { (p, q) | p R* q} or however you want to denote it /// /// Parameters: /// out_result: The transitive closure of r /// r: The source relation template<typename Relation> void transitive_closure(Relation & out_result, Relation const & r) { typedef typename Relation::const_iterator Iterator; typedef typename Relation::value_type::first_type State; #ifndef NDEBUG const bool domain_and_codomain_are_the_same = boost::is_same<typename Relation::value_type::first_type, typename Relation::value_type::second_type>::value; BOOST_STATIC_ASSERT(domain_and_codomain_are_the_same); #endif // Find the largest state State largest_state = State(); for(Iterator edge = r.begin(); edge != r.end(); ++edge) { largest_state = biggest(largest_state, edge->first, edge->second); } largest_state = largest_state + 1; assert(largest_state < 2000); // reasonable based on my examples // I think // Set up the path matrix std::vector<std::deque<bool> > matrix(largest_state); for(size_t i = 0; i<matrix.size(); ++i) { matrix[i].resize(largest_state); } for(size_t source=0; source<largest_state; ++source) { matrix[source][source] = 1; } for(Iterator edge = r.begin(); edge != r.end(); ++edge) { matrix[edge->first][edge->second] = 1; } // Now perform Floyd-Warshall alg. From Wikipedia: // // /* Assume a function edgeCost(i,j) which returns the cost of // the edge from i to j (infinity if there is none). Also // assume that n is the number of vertices and // edgeCost(i,i) = 0 // */ // // int path[][]; // // /* A 2-dimensional matrix. At each step in the algorithm, // path[i][j] is the shortest path from i to j using // intermediate vertices (1..k-1). Each path[i][j] is // initialized to edgeCost(i,j) or infinity if there is no // edge between i and j. // */ // // procedure FloydWarshall () // for k := 1 to n // for i := 1 to n // for j := 1 to n // path[i][j] = min ( path[i][j], path[i][k]+path[k][j] ); for(size_t k = 0; k < largest_state; ++k) for(size_t i = 0; i < largest_state; ++i) for(size_t j = 0; j < largest_state; ++j) matrix[i][j] = matrix[i][j] || (matrix[i][k] && matrix[k][j]); // Now go through and convert back to the multimap view for(size_t source=0; source<largest_state; ++source) { for(size_t target=0; target<largest_state; ++target) { if(matrix[source][target]) { out_result.insert(std::make_pair(source,target)); } } } // done with } /// Returns the intersection of two binary relations on states /// /// Parameters: /// out_result: The intersection of r1 and r2 /// r1: One binary relation on states /// r2: Another binary relation on states inline void intersect(BinaryRelation & out_result, BinaryRelation const & r1, BinaryRelation const & r2) { wsr::intersect(out_result.set, r1.set, r2.set); wbr::intersect(out_result.bdd, r1.bdd, r2.bdd); assert(out_result.check()); } /// Returns the union of two binary relations on states /// /// Parameters: /// out_result: The union of r1 and r2 /// r1: One binary relation on states /// r2: Another binary relation on states inline void union_(BinaryRelation & out_result, BinaryRelation const & r1, BinaryRelation const & r2) { assert(r1.check()); assert(r2.check()); wsr::union_(out_result.set, r1.set, r2.set); wbr::union_(out_result.bdd, r1.bdd, r2.bdd); assert(out_result.check()); } template<typename T> class VectorSet { typedef std::vector<T> Items; Items items; public: typedef typename Items::iterator iterator; typedef typename Items::const_iterator const_iterator; void insert(T const & item) { if (find(item) == end()) { items.push_back(item); } } iterator find(T const & item) { return std::find(items.begin(), items.end(), item); } const_iterator find(T const & item) const { return std::find(items.begin(), items.end(), item); } bool empty() const { return items.empty(); } iterator begin() { return items.begin(); } const_iterator begin() const { return items.begin(); } iterator end() { return items.end(); } const_iterator end() const { return items.end(); } void erase(iterator i) { items.erase(i); } void erase(const_iterator i) { items.erase(i); } }; } // namespace relations } // namespace wali // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End: #endif
true
81f23423f361baa03beba2f25f3a3b6c845dee76
C++
thb32133451/windows
/第七章 思考题 10/第七章 思考题 10/calculate.cpp
UTF-8
671
3.3125
3
[]
no_license
#include <iostream> using namespace std; double add(double x, double y); double point(double x, double y); double calculate(double x, double y, double(*pf[2])(double, double)); int main() { double x, y; double (*pf[2])(double, double) = { add,point }; if ((cin>>x && cin>>y)) { double z = calculate(x,y,pf); cout << z << endl; } else { cout << "please enter two number next time! now we will exit.\n"; } system("pause"); return 0; } double add(double x, double y) { return x+y; } double calculate(double x,double y, double(*pf[2])(double, double)) { double k =pf[0](x,y)+pf[1](x,y); return k; } double point(double x, double y) { return x / y; }
true
d4afda9857833f555590fe93c84c29600f31ea4f
C++
HongYeseul/DataStructure
/C++_Vacation/1230/Calculator/Adder.cpp
UTF-8
167
2.5625
3
[]
no_license
#include <iostream> using namespace std; #include "Adder.h" Adder :: Adder(int a, int b){ op1 = a; op2 = b; } int Adder :: process(){ return op1+op2; }
true
855a206b9057da1204983393af53dee58f2650c1
C++
antonmax/Anton-s-Space-Invaders
/SFMLProject/GP1/Game/CountdownTimer.h
UTF-8
371
2.625
3
[]
no_license
#pragma once #include "stdafx.h" class CountdownTimer{ public: CountdownTimer(); void SetTime(int hours, int minutes, int seconds); void Update(); void Reset(); void Start(); void Stop(); bool Done(); int Seconds; int Minutes; int Hours; private: sf::Clock clocks; sf::Time time; bool ticking; int defaultSeconds; int defaultMinutes; int defaultHours; };
true
961fb672d0df5da7510fc4d8996a1cd0002f332e
C++
JJJoonngg/Algorithm
/백준/1373_2진수8진수.cpp
UTF-8
703
2.671875
3
[]
no_license
// // Created by 김종신 on 2020/01/27. // #include <bits/stdc++.h> using namespace std; string input, output = ""; int main() { cin.tie(NULL); cout.tie(NULL); std::ios::sync_with_stdio(false); cin >> input; reverse(input.begin(), input.end()); while(input.size()%3 != 0){ input += "0"; } for (int i = 0; i < input.size(); i += 3) { int tmp = 1, res = 0; for (int cnt = 0; cnt < 3; cnt++) { int cur = int(input[i + cnt] - '0'); cur *= tmp; res += cur; tmp *= 2; } output += to_string(res); } reverse(output.begin(),output.end()); cout << output<<"\n"; return 0; }
true
0a642cefb0bad68ff0e8eea1de2e1f66fcbb9e0c
C++
gondur/Magical-Broom-Extreme
/luna_new/luna_new/Project/Lue/Source/LueFile.cpp
SHIFT_JIS
8,453
2.703125
3
[]
no_license
//------------------------------------------------------------------------------------------------ // INCLUDE //------------------------------------------------------------------------------------------------ #include "LueBase.h" #include "LueFile.h" //------------------------------------------------------------------------------------------------ // NameSpace //------------------------------------------------------------------------------------------------ using namespace Selene; //------------------------------------------------------------------------------------------------ // for C compiler //------------------------------------------------------------------------------------------------ extern "C" { //------------------------------------------------------------------------------------------------ // ProtoType //------------------------------------------------------------------------------------------------ extern ICore *Lue_GetCore( void ); extern void MBCStoWCS( const char *pSrc, wchar_t *pDst ); //------------------------------------------------------------------------------------------------ /** @brief t@Cǂݍ @author t` @param pFile [in] ǂݍ݃t@C @param ppData [out] ǂݍ݃f[^i[ @param pSize [out] ǂݍ݃f[^TCYi[ @retval LTRUE ǂݍݐ @retval LFALSE ǂݍݎs t@C̓ǂݍ݂s܂B<BR> ǂݍ݂ƓŃmۂA<BR> ̃AhX ppData Ɋi[At@CTCY pSize Ɋi[܂B<BR> ǂݍ݌AsvɂȂt@Cf[^ File_Release ֐ŃォĂB */ //------------------------------------------------------------------------------------------------ eLueBool LueFile_Load( const char *pFile, void **ppData, unsigned int *pSize ) { wchar_t wTemp[MAX_PATH] = L""; MBCStoWCS( pFile, wTemp ); return Lue_GetCore()->GetFileMgrPointer()->Load( wTemp, ppData, (Uint32*)pSize ) ? LTRUE : LFALSE; } //------------------------------------------------------------------------------------------------ /** @brief t@C @author t` @param pData [in] ǂݍ݃f[^ File_Load ֐œǂݍ񂾃f[^܂B<BR> ̊֐ʼnsȂƃAvP[VIĂ<BR> 폜܂B */ //------------------------------------------------------------------------------------------------ void LueFile_Release( void *pData ) { MemGlobalFree( pData ); } //------------------------------------------------------------------------------------------------ /** @brief t@C̃I[v @author t` @param pFile [in] t@C @retval NULL t@CI[vs @return NULLȊO t@C̃t@C|C^ I[ṽt@C̃N[Y܂B */ //------------------------------------------------------------------------------------------------ LUE_FILEPTR LueFile_FileOpen( const char *pFile ) { wchar_t wTemp[MAX_PATH] = L""; MBCStoWCS( pFile, wTemp ); return (LUE_FILEPTR)Lue_GetCore()->GetFileMgrPointer()->FileOpen( wTemp ); } //------------------------------------------------------------------------------------------------ /** @brief t@C̃N[Y @author t` @param FilePtr [in] t@C|C^ I[ṽt@C̃N[Y܂B */ //------------------------------------------------------------------------------------------------ void LueFile_FileClose( LUE_FILEPTR FilePtr ) { ((IResourceFile*)FilePtr)->Release(); } //------------------------------------------------------------------------------------------------ /** @brief t@C̃TCY擾 @author t` @param FilePtr [in] t@C|C^ I[ṽt@C̃t@CTCY擾܂B */ //------------------------------------------------------------------------------------------------ unsigned int LueFile_FileGetSize( LUE_FILEPTR FilePtr ) { return ((IResourceFile*)FilePtr)->GetFileSize(); } //------------------------------------------------------------------------------------------------ /** @brief t@C|C^̈ʒu擾 @author t` @param FilePtr [in] t@C|C^ I[ṽt@Č݂̃t@C|C^<BR> ʒu擾܂B */ //------------------------------------------------------------------------------------------------ unsigned int LueFile_FileGetPosition( LUE_FILEPTR FilePtr ) { return ((IResourceFile*)FilePtr)->GetFilePosition(); } //------------------------------------------------------------------------------------------------ /** @brief t@C̓ǂݍ @author t` @param FilePtr [in] t@C|C^ @param pData [in/out] f[^i[ @param Size [in] ǂݍ݃TCY ݂̃t@C|C^̈ʒuwf[^TCY<BR> f[^ǂݍ݂܂B */ //------------------------------------------------------------------------------------------------ unsigned int LueFile_FileRead( LUE_FILEPTR FilePtr, void *pData, unsigned int Size ) { return ((IResourceFile*)FilePtr)->Read( pData, Size ); } //------------------------------------------------------------------------------------------------ /** @brief t@C|C^̈ړ @author t` @param FilePtr [in] t@C|C^ @param Offset [in] t@C|C^̈ړ @param Flag [in] t@C|C^ʒu I[ṽt@C̃t@C|C^Cӂ̈ʒuɈړ܂B */ //------------------------------------------------------------------------------------------------ int LueFile_FileSeek( LUE_FILEPTR FilePtr, int Offset, eLueSeek Flag ) { switch ( Flag ) { case LSEEK_FILE_CURRENT: ///< ݈ʒu return ((IResourceFile*)FilePtr)->Seek( Offset ); case LSEEK_FILE_START: ///< 擪ʒu return ((IResourceFile*)FilePtr)->SeekStart( Offset ); case LSEEK_FILE_END: ///< I[ʒu return ((IResourceFile*)FilePtr)->SeekEnd( Offset ); } return 0; } //------------------------------------------------------------------------------------------------ /** @brief t@Cǂݍ݃JgfBNgݒ @author t` @param pCurrentDir [in] JgfBNg t@CۂɎgJgfBNgݒ肵܂<BR> LueFile_SetLoadPath [g̃pXƂāAȉ̃fBNgw肵܂<BR> <BR> jData/Texture/Chara00/Stand.bmp ̓ǂݍ<BR> LueFile_SetLoadPath Data w肵A<BR> LueFile_SetCurrentDirectory Texture/Chara00 w肵܂B<BR> ̌ LueFile_Load Stand.bmp Ǝw肷邱Ƃœǂݍ܂܂B */ //------------------------------------------------------------------------------------------------ void LueFile_SetCurrentDirectory( char *pCurrentDir ) { wchar_t wTemp[MAX_PATH] = L""; MBCStoWCS( pCurrentDir, wTemp ); Lue_GetCore()->GetFileMgrPointer()->SetCurrentDirectory( wTemp ); } //------------------------------------------------------------------------------------------------ /** @brief t@Cǂݍ݃pXݒ @author t` @param Priority [in] ǂݍݗDx @param pRootPath [in] [gfBNg @param pPackFile [in] pbNt@C t@Cǂݍ݂̍ۂɎgpXݒ肵܂<BR> pRootPath pPackFile ͓ɈA<BR> pRootPath ̌s pPackFile ̌s悤ɂȂĂ܂B */ //------------------------------------------------------------------------------------------------ void LueFile_SetLoadPath( unsigned int Priority, const char *pRootPath, const char *pPackFile ) { wchar_t wTemp0[MAX_PATH] = L""; wchar_t wTemp1[MAX_PATH] = L""; MBCStoWCS( pRootPath, wTemp0 ); MBCStoWCS( pPackFile, wTemp1 ); return Lue_GetCore()->GetFileMgrPointer()->SetLoadPath( Priority, wTemp0, wTemp1 ); } } // extern "C"
true
46a596c2abfd47e9922d4fafd76dccc4974f0e97
C++
DeltaHao/sword-to-offer
/34.cpp
UTF-8
758
3.359375
3
[]
no_license
/*第一个只出现一次的字符 在一个字符串,全部由字母组成中找到第一个只出现一次的字符,并返回它的位置,如果没有则返回-1 */ #include<iostream> #include<unordered_map>//无序键值对, 即哈希表 using namespace std; class Solution { public: int FirstNotRepeatingChar(string str){ unordered_map<char, int> char_counts; int the_once=0; for(int i=0;i<str.size();i++){//O(n) char_counts[str[i]]++;//更新哈希表中该字符的出现次数 } while(char_counts[str[the_once]] > 1 && the_once < str.size()){//O(26+26) the_once++; } if(the_once>=str.size()) return -1; else return the_once; } };
true
e95a98af3ab1fdddd6bc9c4597518e4825188957
C++
VardAlex/clientservertcp
/server.cpp
UTF-8
1,090
3.296875
3
[]
no_license
#include <iostream> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <cstring> int main() { // creating an endpoint and descriptor int listening = socket(AF_INET, SOCK_STREAM, 0); // socket description sockaddr_in server; // address family server.sin_family = AF_INET; // IPv4 server.sin_port = htons(5400); // convert between host and network byte order // convert string into a network address (IPv4) and copies it to server.sin_addr inet_pton(AF_INET, "0.0.0.0", &server.sin_addr); // assigning address to the descriptor bind(listening, (sockaddr *) &server, sizeof(server)); // listening for connection on a socket listen(listening, 1); // accept a connection on a socket int clientSocket = accept(listening, NULL, NULL); // close a file descriptor close(listening); char buf[256]; // receive a message from a clientSocket int bytesRecv = recv(clientSocket, buf, 256, 0); std::cout << std::string(buf, 0, bytesRecv) << std::endl; close(clientSocket); return 0; }
true
7936af691573da6bc0c5424cf9c05e51b0afd7e2
C++
ghostumar/DSA
/MATHEMATICS/prime factor of a number.cpp
UTF-8
535
3.46875
3
[ "Apache-2.0" ]
permissive
#include<iostream> using namespace std; bool isprime(int); void primefactor(int n){ for(int i=2;i<n;i++){ if(isprime(i)){ int x=i; while(n%x==0){ cout<<i; x=x*i; } } } } bool isprime(int i){ if(i==1) return false; if(i==2 || i==3) return true; if(i%2==0 || i%3==0) return false; for(int j=5;j*j<=i;j++){ if(i%j==0 ||i%(j+2)==0) return false; } return true; } int main(){ int n; cout<<"Enter the number"<<endl; cin>>n; primefactor(n); }
true
7ce93c22c31a123b37be45e9665965cfe7f5479e
C++
mingsjtu/OJ_exercise
/王道/cloop.cpp
UTF-8
909
2.59375
3
[]
no_license
//http://bailian.openjudge.cn/practice/2115/ #pragma warning(disable:4996) #include<iostream> #include<cstdio> #include<math.h> typedef long long ll; using namespace std; ll a, b, c, d; ll exgcd(ll a, ll b, ll& x, ll& y) { if (!b) { x = 1, y = 0; return a; } ll d, tx, ty; d = exgcd(b, a%b, tx, ty);//bx'+(a%b)y'=1(mod p) x = ty, y = tx - (a / b)*ty;//ay'+b(x'-t*y')=1(mod p) return d; } int main() { while (true) { scanf("%lld %lld %lld %lld", &a, &b, &c, &d); if (!(a||b||c||d))return 0; if (a == b) { cout << 0; continue; } ll rex=0, rey=0, gcd; int d1 = 2; for (int i = 0; i < d; i++) d1 = d1 << 1; cout << "d1" << d1 << endl; gcd = exgcd(c, d1, rex, rey); cout << "rex" << rex << endl; cout << gcd << "gcd" << endl; if ( (a - b)%gcd == 0) { ll each = d / gcd; rex = rex * (b - a) / gcd; while (rex < 0) { rex += each; } } cout << rex << endl; } }
true
af35d21e7cc587138ef24ced441fa98bb2293552
C++
SharifulCSECoU/competitive-programming
/uva-online-judge/accepted-solutions/10484 - Divisibility of Factors.cpp
UTF-8
2,137
2.59375
3
[]
no_license
/*****************/ /* LAM PHAN VIET */ /* UVA 10484 - Divisibility of Factors /* Time limit: 3.000s /********************************/ #include <algorithm> #include <bitset> #include <cctype> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <queue> #include <stack> #include <string> #include <vector> #define FileIn(file) freopen(file".inp", "r", stdin) #define FileOut(file) freopen(file".out", "w", stdout) #define FOR(i, a, b) for (int i=a; i<=b; i++) #define REP(i, n) for (int i=0; i<n; i++) #define Fill(ar, val) memset(ar, val, sizeof(ar)) #define PI 3.1415926535897932385 #define uint64 unsigned long long #define int64 long long #define all(ar) ar.begin(), ar.end() #define pb push_back #define bit(n) (1<<(n)) #define Last(i) ( i & -i ) #define INF 500000000 #define maxN 105 using namespace std; bitset<maxN> isP; vector<int> prime; int number[30], n, m; void sieve() { isP.set(); for (int i = 3; i * i < maxN; i += 2) if (isP[i]) for (int j = i * i; j < maxN; j += i + i) isP.reset(j); prime.pb(2); for (int i = 3; i < maxN; i += 2) if (isP[i]) prime.pb(i); } int cal(int n, int k) { int res = 0, kk = k; while (kk <= n) { res += n / kk; kk *= k; } return res; } int64 solve() { if (n == 0) return (m == 1)? 1: 0; int p = 0; while (prime[p] <= n) { number[p] = cal(n, prime[p]); p++; } int p2 = 0; while (p2 < prime.size() && m != 1) { if (m % prime[p2] == 0) { while (m % prime[p2] == 0) { m /= prime[p2]; number[p2]--; if (number[p2] < 0) return 0; } } p2++; } if (m != 1) return 0; int64 res = 1; REP(i, 25) if (number[i]) res *= (number[i] + 1); return res; } main() { // FileIn("test"); FileOut("test"); sieve(); while (scanf("%d %d", &n, &m) && (n || m)) { REP(i, 25) number[i] = 0; m = abs(m); printf("%lld\n", solve()); } } /* lamphanviet@gmail.com - 2011 */
true
098fe85ea631805b8f2975b70deda9c065a1b71d
C++
Domash/Coursera
/Art of Development in Modern C++ Specialization/Yellow_belt/Week_2/isPalindrom.cpp
UTF-8
2,891
3.34375
3
[]
no_license
// // isPalindrom.cpp // coursera // // Created by Денис Домашевич on 2/2/19. // Copyright © 2018 Денис Домашевич. All rights reserved. // #include <iostream> #include <map> #include <set> #include <sstream> #include <stdexcept> #include <algorithm> #include <string> #include <vector> using namespace std; template <class T> ostream& operator << (ostream& os, const vector<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class T> ostream& operator << (ostream& os, const set<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class K, class V> ostream& operator << (ostream& os, const map<K, V>& m) { os << "{"; bool first = true; for (const auto& kv : m) { if (!first) { os << ", "; } first = false; os << kv.first << ": " << kv.second; } return os << "}"; } template<class T, class U> void AssertEqual(const T& t, const U& u, const string& hint = {}) { if (t != u) { ostringstream os; os << "Assertion failed: " << t << " != " << u; if (!hint.empty()) { os << " hint: " << hint; } throw runtime_error(os.str()); } } void Assert(bool b, const string& hint) { AssertEqual(b, true, hint); } class TestRunner { public: template <class TestFunc> void RunTest(TestFunc func, const string& test_name) { try { func(); cerr << test_name << " OK" << endl; } catch (exception& e) { ++fail_count; cerr << test_name << " fail: " << e.what() << endl; } catch (...) { ++fail_count; cerr << "Unknown exception caught" << endl; } } ~TestRunner() { if (fail_count > 0) { cerr << fail_count << " unit tests failed. Terminate" << endl; exit(1); } } private: int fail_count = 0; }; bool IsPalindrom(const string& str) { int len = str.size(); for(int i = 0; i < len; ++i) { if(str[i] != str[len - i - 1]) return false; } return true; } bool TruePalindrom(const string& str) { int len = str.size(); for(int i = 0; i < len; ++i) { if(str[i] != str[len - i - 1]) return false; } return true; } string Generator(int len) { string res = ""; for(int i = 0; i < len; ++i) { if(rand() % 4 == 0) { res += ' '; } else { res += 'a' + rand() % 3; } } return res; } void TEST() { for(int i = 0; i < 10; ++i) { for(int j = 0; j < i * 4 + 22; ++j) { string curr = Generator(i); sort(curr.begin(), curr.end()); do { AssertEqual(IsPalindrom(curr), TruePalindrom(curr)); } while(next_permutation(curr.begin(), curr.end())); } } } int main() { TestRunner runner; runner.RunTest(TEST, "TEST"); return 0; }
true
1425a81ca18f1079f53f3b215ae482956574f352
C++
NealXu/HeadFirstDesignPattern
/code/06/include/stereo_on_with_cd.h
UTF-8
495
2.59375
3
[]
no_license
#ifndef _STEREO_ON_WITH_CD_H_ #define _STEREO_ON_WITH_CD_H_ #include "command.h" #include "stereo.h" class StereoOnWithCdCommand : public Command { public: StereoOnWithCdCommand(Stereo *pSte) { pStereo = pSte; } ~StereoOnWithCdCommand() {} virtual void Excute() { pStereo->On(); pStereo->SetCd(); } virtual void Undo() { pStereo->Off(); } private: Stereo *pStereo; }; #endif /* end of stereo_on_with_cd.h */
true
4779424ff16432eb2fc788688af8446c7321fe51
C++
qianlishun/toolsClass
/toolsDemo/Framewokes/hough/HoughLineDetector.h
UTF-8
3,345
3.015625
3
[]
no_license
#include <vector> typedef enum _HOUGH_LINE_TYPE_CODE { HOUGH_LINE_STANDARD = 0, //standad hough line HOUGH_LINE_PROBABILISTIC = 1, //probabilistic hough line }HOUGH_LINE_TYPE_CODE; typedef struct { int x; int y; int width; int height; }boundingbox_t; typedef struct { float startx; float starty; float endx; float endy; }line_float_t; /* @function HoughLineDetector @param [in] src: image,single channel @param [in] w: width of image @param [in] h: height of image @param [in] scaleX: downscale factor in X-axis @param [in] scaleY: downscale factor in Y-axis @param [in] CannyLowThresh: lower threshold for the hysteresis procedure in canny operator @param [in] CannyHighThresh: higher threshold for the hysteresis procedure in canny operator @param [in] HoughRho: distance resolution of the accumulator in pixels @param [in] HoughTheta: angle resolution of the accumulator in radians @param [in] MinThetaLinelength: standard: for standard and multi-scale hough transform, minimum angle to check for lines. propabilistic: minimum line length. Line segments shorter than that are rejected @param [in] MaxThetaGap: standard: for standard and multi-scale hough transform, maximum angle to check for lines propabilistic: maximum allowed gap between points on the same line to link them @param [in] HoughThresh: accumulator threshold parameter. only those lines are returned that get enough votes ( >threshold ). @param [in] _type: hough line method: HOUGH_LINE_STANDARD or HOUGH_LINE_PROBABILISTIC @param [in] bbox: boundingbox to detect @param [in/out] lines: result @return: 0:ok; 1:error @brief: _type: HOUGH_LINE_STANDARD: standard hough line algorithm HOUGH_LINE_PROBABILISTIC probabilistic hough line algorithm When HOUGH_LINE_STANDARD runs, the line points might be the position outside the image coordinate standard: try (src,w,h,scalex,scaley,70,150, 1, PI/180, 0, PI, 100, HOUGH_LINE_STANDARD, bbox, line) propabilistic: try (src,w,h,scalex,scaley,70,150, 1, PI/180, 30, 10, 80, HOUGH_LINE_STANDARD, bbox, line) */ const int HoughLineDetector(unsigned char *src, int w, int h, float scaleX, float scaleY, float CannyLowThresh, float CannyHighThresh, float HoughRho, float HoughTheta, float MinThetaLinelength, float MaxThetaGap, int HoughThresh, HOUGH_LINE_TYPE_CODE _type, boundingbox_t bbox, std::vector<line_float_t> &lines); const char* MppsTo(unsigned char *src, int w, int h, float scaleX, float scaleY, float CannyLowThresh, float CannyHighThresh, float HoughRho, float HoughTheta, float MinThetaLinelength, float MaxThetaGap, int HoughThresh, HOUGH_LINE_TYPE_CODE _type, boundingbox_t bbox);
true
746b229a25e7ba68a14d42b18711de2b7e2a622e
C++
fred-mc/FRED-J-PET
/plugin/plugin_orig/Arr3d.h
UTF-8
7,352
2.609375
3
[]
no_license
#ifndef ARR3D_H #define ARR3D_H #include "idx3d.h" #include "types.h" #include <iostream> #include <iomanip> using namespace std; namespace fred { template <class T> class Arr3d { public: T *data; uint64 N; union { //size vector uint32 sizev[3]; struct { uint32 nx,ny,nz;}; }; uint32 stridev[3]; // stride vector //basev[3]; // base vector public: Arr3d(); Arr3d(int n, int m, int k); Arr3d(i3d dims); inline T & operator[](const int i) {return data[i];} // access via voxel index inline const T & operator[](const int i) const {return data[i];} inline T& el(int i,int j,int k){return data[i+j*stridev[1]+k*stridev[2]];} // access via 3d idx ASSUMING COLUMN MAJOR inline T& el(size_t i){return data[i];} inline T& el(i3d idx){return data[idx.x+idx.y*stridev[1]+idx.z*stridev[2]];} // access via 3d idx using idx3d ASSUMING COLUMN MAJOR inline T& el(i3ds idx){return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T& el(ui3ds idx){return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T& operator()(int i,int j,int k){return data[i+j*stridev[1]+k*stridev[2]];} inline T operator()(int i,int j,int k) const {return data[i+j*stridev[1]+k*stridev[2]];} inline T& operator()(i3d idx){return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T operator()(i3d idx)const {return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T& operator()(i3ds idx){return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T operator()(i3ds idx)const {return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T& operator()(ui3ds idx){return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline T operator()(ui3ds idx)const {return data[(int)idx.x+(int)idx.y*stridev[1]+(int)idx.z*stridev[2]];} inline uint32 vxlidx(int i,int j,int k) {return i+j*stridev[1]+k*stridev[2];} inline uint32 vxlidx(i3d idx) {return idx.x+idx.y*stridev[1]+idx.z*stridev[2];} inline i3d vxlcoord(int idx); inline size_t numel(){return N;} inline int dim1() const {return sizev[0];} inline int dim2() const {return sizev[1];} inline int dim3() const {return sizev[2];} i3d dims() const {return i3d(sizev[0],sizev[1],sizev[2]);}; ~Arr3d(); Arr3d<T>& operator=(T v); Arr3d<T>& operator=(Arr3d<T>& B); Arr3d<T>& operator+=(const T v); Arr3d<T>& operator-=(const T v); Arr3d<T>& operator*=(const T v); Arr3d<T>& operator/=(const T v); void resize(i3d nn); void resize(int n, int m, int k); void reshape(int n, int m, int k); void realloc(); void range(T &vmin,T &vmax); T sum(); T max(); T min(); T max(i3d *loc); T min(i3d *loc); void clamp(T vmin, T vmax); void indexes(int dim =-1); void info(ostream &os=std::cout); }; template <class T> Arr3d<T>::Arr3d() {sizev[0]=sizev[1]=sizev[2]=0; data=NULL; N=0;} template <class T> Arr3d<T>::Arr3d(int n, int m, int k) { sizev[0]=sizev[1]=sizev[2]=0; data=NULL; N=0; resize(n,m,k); } template <class T> Arr3d<T>::Arr3d(i3d dims) { sizev[0]=sizev[1]=sizev[2]=0; data=NULL; N=0; resize(dims[0],dims[1],dims[2]); } template <class T> void Arr3d<T>::reshape(int n, int m, int k) { N = 1UL*n*m*k; sizev[0]=n; sizev[1]=m; sizev[2]=k; stridev[0]=1; // column major stridev[1]=n; stridev[2]=n*m; } template <class T> void Arr3d<T>::realloc() { if (data != NULL) { //release memory delete[] (data); } data = new T[N]; } template <class T> void Arr3d<T>::resize(int n, int m, int k) { reshape(n,m,k); realloc(); } template <class T> void Arr3d<T>::resize(i3d nn) { resize(nn[0],nn[1],nn[2]); } template <class T> inline Arr3d<T>& Arr3d<T>::operator=(const T v) { T *p=data; for(size_t i=0; i<N; i++,p++) *p=v; return *this; } template <class T> inline Arr3d<T>& Arr3d<T>::operator+=(const T v) { T *p=data; for(size_t i=0; i<N; i++,p++) *p+=v; return *this; } template <class T> inline Arr3d<T>& Arr3d<T>::operator-=(const T v) { T *p=data; for(size_t i=0; i<N; i++,p++) *p-=v; return *this; } template <class T> inline Arr3d<T>& Arr3d<T>::operator*=(const T v) { T *p=data; for(size_t i=0; i<N; i++,p++) *p*=v; return *this; } template <class T> inline Arr3d<T>& Arr3d<T>::operator/=(const T v) { T *p=data; for(size_t i=0; i<N; i++,p++) *p/=v; return *this; } template <class T> Arr3d<T> & Arr3d<T>::operator=(Arr3d<T> &B) { if (this != &B) { if(dims() != B.dims()) resize(B.dim1(),B.dim2(),B.dim3()); memcpy((void *)data,(void *) B.data,1UL*B.numel()*sizeof(T)); } return *this; } template <class T> Arr3d<T>::~Arr3d() { if (data != 0) { delete[] (data); } } template <class T> void Arr3d<T>::range(T &vmin,T &vmax) { T *p=data; vmin=vmax=p[0]; for(size_t i=1; i<N; i++){ if(p[i]<vmin) vmin=p[i]; if(p[i]>vmax) vmax=p[i]; } } template <class T> T Arr3d<T>::sum() { T *p=data; T s0=0; for(size_t i=0; i<N; i++) s0+=p[i]; return s0; } template <class T> T Arr3d<T>::max() { T *p=data; T v=*p; for(;p<data+N; p++) if(v<*p) v=*p; return v; } template <class T> T Arr3d<T>::min() { T *p=data; T v=*p; for(;p<data+N; p++) if(v>*p) v=*p; return v; } template <class T> T Arr3d<T>::max(i3d *loc) { T *p=data; T v=*p; size_t ivxl=0; for(size_t i=0; i<N; i++,p++) if(v<*p) {v=*p;ivxl=i;} *loc = vxlcoord(ivxl); return v; } template <class T> T Arr3d<T>::min(i3d *loc) { T *p=data; T v=*p; size_t ivxl=0; for(size_t i=0; i<N; i++,p++) if(v>*p) {v=*p;ivxl=i;} *loc = vxlcoord(ivxl); return v; } template <class T> void Arr3d<T>::clamp(T vmin, T vmax) { size_t n=1UL*nx*ny*nz; T *p=data; //#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) for(size_t i=0; i<n; i++) p[i] = (((p[i]) > (vmax)) ? (vmax) : (((p[i]) < (vmin)) ? (vmin) : (p[i]))); } template <class T> i3d Arr3d<T>::vxlcoord(int idx){ i3d p; p[2] = idx/stridev[2]; int rem = idx%stridev[2]; p[1] = rem/stridev[1]; p[0] = rem%stridev[1]; return p; } template <class T> void Arr3d<T>::indexes(int dim){ Arr3d<T> &A=*this; for(int i=0;i<nx;i++) { for(int j=0;j<ny;j++) { for(int k=0;k<nz;k++) { switch(dim){ default: case -1: A(i,j,k)=100*(i+1)+10*(j+1)+k+1; break; case 0: A(i,j,k)=i+1; break; case 1: A(i,j,k)=j+1; break; case 2: A(i,j,k)=k+1; break; } }}} } template <class T> ostream& operator<<(ostream& os,Arr3d<T>& A){ ios_base::fmtflags oldFlags= os.flags(); int prec = 3; long savedPrec = os.precision(); os.precision(prec); os<<"array dims=("<<A.nx<<','<<A.ny<<','<<A.nz<<")"<<endl; for(int k=0;k<A.nz;k++) { for(int i=0;i<A.nx;i++) { for(int j=0;j<A.ny;j++) { os << setw(prec) << A(i,j,k)<<' '; } os<<endl; } os<<endl; } os<<endl; os.precision(savedPrec); os.flags(oldFlags); return os; } template <class T> void Arr3d<T>:: info(ostream &os){ os<<"\tdims: "<<this->dims()<<" => "<<this->N<<" elements"<<endl; os<<"\tdatatype: "<<typeid(T).name()<<endl; os<<"\tmemory occupation: "; size_t B = this->N*sizeof(T); os<<B<<" B "; if (B<1024L*1024L) { os<<" = "<<B/1024<<" KB";} else if (B<1024L*1024L*1024L) { os<<" = "<<B/1024/1024<<" MB";} else { os<<" = "<<B/1024/1024/1024<<" GB";} os<<endl; } } // namespace #endif // ARR3D_H
true
32090627c475f91fb7934148a8d5f73ed5b784c2
C++
zhj149/HereticOS-ObjectSystem
/src/other/TextIoSystem.h
GB18030
7,978
2.5625
3
[ "Apache-2.0" ]
permissive
#pragma once //mylispϵͳ #include "BaseFunctionTool.h" #include "AutoLock.h" #include "stdio.h" #include <stdarg.h> class PrinterProxyInterface { public: PrinterProxyInterface(){}; ~PrinterProxyInterface(){}; virtual void Output(const TCHAR * pMsg){}; virtual void Input(const TCHAR * pMsg){}; virtual const TCHAR * GetInput(tstring & szInput){return NULL;}; virtual const TCHAR * GetOutput(tstring & szOutput){return NULL;}; protected: private: }; class PrinterProxyConsole :public PrinterProxyInterface { public: PrinterProxyConsole(){}; ~PrinterProxyConsole(){}; void Output(const TCHAR * pMsg) { printf_t(pMsg); } const TCHAR * GetInput(tstring & szInput) { TCHAR szMsg[64*1024]; gets_s_t(szMsg,64*1024); szInput=szMsg; return szInput.c_str(); } protected: private: }; class PrinterProxyOutputFile :public PrinterProxyInterface { public: FILE* m_fp; PrinterProxyOutputFile(){ m_fp=NULL; }; ~PrinterProxyOutputFile(){ if(m_fp) { DWORD nEnd={0}; fwrite(&nEnd,4,1,m_fp); fclose(m_fp); m_fp=NULL; } }; void operator()(TCHAR * pszFilePath){ m_fp=fopen_t(pszFilePath,_T("w+b")); if(sizeof(TCHAR)==2) { unsigned short nHead=0xfeff; fwrite(&nHead,2,1,m_fp); } }; void Output(const TCHAR * pMsg) { if(m_fp) { fwrite(pMsg,(strlen_t(pMsg)),sizeof(TCHAR),m_fp); fflush(m_fp); } } const TCHAR * GetInput(tstring & szInput) { TCHAR szMsg[64*1024]; gets_s_t(szMsg,64*1024); szInput=szMsg; return szInput.c_str(); } protected: private: }; #ifndef _LINUX_ class PrinterProxyCom :public PrinterProxyInterface { public: PrinterProxyCom(){}; ~PrinterProxyCom(){}; list<tstring> m_OutputQueue; list<tstring> m_InputQueue; CCriticalSectionStack m_InputLock; CCriticalSectionStack m_OutputLock; void Output(const TCHAR * pMsg) { CAutoStackLock lk(&m_OutputLock,_T("PrinterProxyCom::Output")); m_OutputQueue.push_back(tstring(pMsg)); } void Input(const TCHAR * pMsg){ CAutoStackLock lk(&m_InputLock,_T("PrinterProxyCom::Input")); m_InputQueue.push_back(tstring(pMsg)); } BOOL WaitInputer() { CAutoStackLock lk; for(;;) { lk.Lock(&m_InputLock,NULL); if(m_InputQueue.size()) return TRUE; lk.UnLock(); Sleep(200); } return FALSE; } const TCHAR * GetInput(tstring & szInput){ if(WaitInputer()) { CAutoStackLock lk(&m_InputLock,_T("PrinterProxyCom::GetInput")); szInput=m_InputQueue.front(); m_InputQueue.pop_front(); return szInput.c_str(); } return NULL; } const TCHAR * GetOutput(tstring & szOutput){ CAutoStackLock lk(&m_OutputLock,_T("PrinterProxyCom::GetOutput")); if(m_OutputQueue.size()) { szOutput=m_OutputQueue.front(); m_OutputQueue.pop_front(); return szOutput.c_str(); } return NULL; } protected: private: }; class PrinterProxyOutputDebugString :public PrinterProxyInterface { public: PrinterProxyOutputDebugString() {}; ~PrinterProxyOutputDebugString() {}; void Output(const TCHAR * pMsg) { OutputDebugString(pMsg); } const TCHAR * GetInput(tstring & szInput) { TCHAR szMsg[64 * 1024]; gets_s_t(szMsg, 64 * 1024); szInput = szMsg; return szInput.c_str(); } protected: private: }; #endif class ErrorPrinter { public: PrinterProxyInterface * m_pIo; #define LogBugLen 4096*16 enum ErrorType { ErrorType_Fail=0x1, ErrorType_OK=0x2, ErrorType_Info=0x4, ErrorType_Log1=0x8, ErrorType_Log2=0x10, ErrorType_Log3=0x20, ErrorType_Log4=0x40, ErrorType_Log5=0x80, ErrorType_Log6=0x100, ErrorType_Log7=0x200, ErrorType_Log8=0x400, ErrorType_DebugOut=0x800, }; __int64 m_AllowType; map<tstring,__int64,less<tstring>> m_AllowTypeInfo; ErrorPrinter(){ m_pIo=NULL; m_AllowTypeInfo[tstring(_T("Fail"))]=ErrorType_Fail; m_AllowTypeInfo[tstring(_T("GetValOK"))]=ErrorType_OK; m_AllowTypeInfo[tstring(_T("GetValAll"))]=ErrorType_Fail|ErrorType_OK; m_AllowTypeInfo[tstring(_T("ִд"))]=ErrorType_Fail; m_AllowTypeInfo[tstring(_T("ֵɹ"))]=ErrorType_OK; m_AllowTypeInfo[tstring(_T("ֵ"))]=ErrorType_Fail|ErrorType_OK; m_AllowTypeInfo[tstring(_T("־1"))]=ErrorType_Log1; m_AllowTypeInfo[tstring(_T("־2"))]=ErrorType_Log2; m_AllowTypeInfo[tstring(_T("־3"))]=ErrorType_Log3; m_AllowTypeInfo[tstring(_T("־4"))]=ErrorType_Log4; m_AllowTypeInfo[tstring(_T("־5"))]=ErrorType_Log5; m_AllowTypeInfo[tstring(_T("־6"))]=ErrorType_Log6; m_AllowTypeInfo[tstring(_T("־7"))]=ErrorType_Log7; m_AllowTypeInfo[tstring(_T("־8"))]=ErrorType_Log8; m_AllowType=m_AllowTypeInfo[tstring(_T("ִд"))]|ErrorType_DebugOut; }; ~ErrorPrinter(){}; void SetIo(PrinterProxyInterface * InOutPrinterProxy) { m_pIo=InOutPrinterProxy; } void operator()(ErrorType nType,const TCHAR * line,... ) { if((nType&m_AllowType)&&(m_pIo!=NULL)&&(!IsBadReadPtr(m_pIo,sizeof(PrinterProxyInterface)))) { TCHAR cpBuf[LogBugLen]; memset(cpBuf,0,sizeof(cpBuf)); //sprintf_s(cpBuf,2048,"log:",GetCurrentThreadId()); va_list vl; va_start( vl, line ); size_t len=strlen_t(cpBuf); vsprintf_s_t(cpBuf+len,LogBugLen-len-6, line, vl ); va_end( vl); strcat_s_t(cpBuf, LogBugLen,_T("\r\n")); //printf(cpBuf); m_pIo->Output(cpBuf); return ; } } void operator()(const TCHAR * line,... ) { if((m_pIo!=NULL)&&(!IsBadReadPtr(m_pIo,sizeof(PrinterProxyInterface)))) { TCHAR cpBuf[LogBugLen]; memset(cpBuf,0,sizeof(cpBuf)); //sprintf_s(cpBuf,2048,"log:",GetCurrentThreadId()); va_list vl; va_start( vl, line ); size_t len=strlen_t(cpBuf); vsprintf_s_t(cpBuf+len,LogBugLen-len-6, line, vl ); va_end( vl); strcat_s_t(cpBuf, LogBugLen,_T("\r\n")); //printf(cpBuf); m_pIo->Output(cpBuf); return ; } } void operator()(tstring & szDst) { if ((m_pIo != NULL) && (!IsBadReadPtr(m_pIo, sizeof(PrinterProxyInterface)))) { m_pIo->Output(szDst.c_str()); return; } } template<typename StringT> void operator()(StringT & szDst, const typename StringT::value_type * fmt, ...) { StringT::value_type cpBuf[LogBugLen]; memset(cpBuf, 0, sizeof(cpBuf)); //swprintf_s(cpBuf,2048,L"%s tid=%d log:",szHead,GetCurrentThreadId()); va_list vl; va_start(vl, fmt); size_t len = strlen_t(cpBuf); vsprintf_s_t(cpBuf + len, LogBugLen - len, fmt, vl); va_end(vl); //strcat_t(cpBuf,_T("\r\n")); szDst = cpBuf; return; } //ʽ׷ӵszDst template<typename StringT> void cat(StringT & szDst, const typename StringT::value_type * fmt, ...) { StringT::value_type cpBuf[LogBugLen]; memset(cpBuf, 0, sizeof(cpBuf)); //swprintf_s(cpBuf,2048,L"%s tid=%d log:",szHead,GetCurrentThreadId()); va_list vl; va_start(vl, fmt); size_t len = strlen_t(cpBuf); vsprintf_s_t(cpBuf + len, LogBugLen - len, fmt, vl); va_end(vl); //strcat_t(cpBuf,_T("\r\n")); szDst += cpBuf; return; } bool OpenLog(tstring & szLogName) { map<tstring,__int64,less<tstring>>::iterator itType=m_AllowTypeInfo.find(szLogName); if(itType!=m_AllowTypeInfo.end()) { m_AllowType|=itType->second; return true; } return false; } bool CloseLog(tstring & szLogName) { map<tstring,__int64,less<tstring>>::iterator itType=m_AllowTypeInfo.find(szLogName); if(itType!=m_AllowTypeInfo.end()) { m_AllowType&=(~itType->second); return true; } return false; } }; template<typename IOType> class ErrorPrinterT : public ErrorPrinter { public: IOType m_Io; ErrorPrinterT(){ SetIo(&m_Io); }; template<typename T> ErrorPrinterT(T & Par){ m_Io(Par); SetIo(&m_Io); }; template<typename T> ErrorPrinterT(T Par){ m_Io(Par); SetIo(&m_Io); }; ~ErrorPrinterT(){}; protected: private: }; #ifndef _LINUX_ typedef ErrorPrinterT<PrinterProxyOutputDebugString> ErrorPrinter_OutputDebugString; #endif typedef ErrorPrinterT<PrinterProxyOutputFile> ErrorPrinter_OutputFile; typedef ErrorPrinterT<PrinterProxyConsole> ErrorPrinter_Console;
true
c40526b6dca5b8d7d557c5b04110436494094e77
C++
lucastle6969/comp371
/src/entities/WorldOrigin.cpp
UTF-8
1,105
2.65625
3
[]
no_license
#ifdef __APPLE__ #include <OpenGL/gl3.h> #include <OpenGL/gl3ext.h> #else #include <GL/glew.h> // include GL Extension Wrangler #endif #include <glm/glm.hpp> #include <vector> #include "Entity.hpp" #include "DrawableEntity.hpp" #include "WorldOrigin.hpp" #include "../constants.hpp" WorldOrigin::WorldOrigin( const GLuint& shader_program, const int& x_max, const int& y_max, const int& z_max, Entity* parent ) : DrawableEntity(shader_program, parent) { this->draw_mode = GL_LINES; // x-axis this->vertices.emplace_back(0.0001f, 0.0f, 0.0f); this->vertices.emplace_back(x_max, 0.0f, 0.0f); // y-axis this->vertices.emplace_back(0.0f, 0.0001f, 0.0f); this->vertices.emplace_back(0.0f, y_max, 0.0f); // z-axis this->vertices.emplace_back(0.0f, 0.0f, 0.0001f); this->vertices.emplace_back(0.0f, 0.0f, z_max); this->vao = this->initVertexArray(this->vertices); } const std::vector<glm::vec3>& WorldOrigin::getVertices() const { return this->vertices; } GLuint WorldOrigin::getVAO() { return this->vao; } const int WorldOrigin::getColorType() { return COLOR_COORDINATE_AXES; }
true
fc9976513f9763369c9d63d766a158a05ed4a38f
C++
CenTea/CPP-Practice
/Rational (2).cpp
WINDOWS-1252
4,411
3.828125
4
[]
no_license
// CPSC 121 Programming Concepts // assignment: Assignment #6 Rational Overloading. Rational.cpp // due-date: May 2 // author: Matthew Tea // partners:N/A // brief: Overload a bunch of operators to demonstrate understanding. #include <iostream> // Include using namespace std; // Namespace class Rational // Beginning of class { private: int numerator, denominator; public: friend ostream &operator<<(ostream &output, Rational &obj); // Overload prototypes friend Rational operator+(Rational &obj, Rational &obj2); friend Rational operator-(Rational &obj, Rational &obj2); friend Rational operator*(Rational &obj, Rational &obj2); friend Rational operator/(Rational &obj, Rational &obj2); Rational &operator-() // Unary overload { numerator = -numerator; return *this; } // Constructor builds a rational number n/d Rational(int n, int d):numerator(n), denominator(d) { reduce(); } private: // This member function transforms a rational number into // reduced form where the numerator and denominator have 1 // as greatest common factor void reduce(); }; ostream &operator<<(ostream &output, Rational &obj) // Output overload, Uses a "N/D" format. { output << obj.numerator << '/' << obj.denominator << endl; return output; } //************************************************************ // This member function transforms a rational number into * // reduced form where the numerator and denominator have 1 * // as greatest common factor. * //************************************************************ void Rational::reduce() { bool negative = (numerator < 0) != (denominator < 0); numerator = abs(numerator); denominator = abs(denominator); int factor = 2; while (factor <= min(numerator, denominator)) { if (numerator % factor == 0 && denominator % factor == 0) { numerator = numerator / factor; denominator = denominator / factor; continue; } factor ++; } if (negative) numerator = - numerator; } int main() // Main function { int num, den; // Declarations int num2, den2; Rational result(0,0); char symbol; cout << "Enter Numerator for Fraction 1: "; // Inputs for Data cin >> num; cout << "Enter Denominator for Fraction 1: "; cin >> den; Rational x(num,den); // Construction of the first Fraction cout << "Enter Numerator for Fraction 1: "; // More inputs cin >> num2; cout << "Enter Denominator for Fraction 2: "; cin >> den2; Rational y(num2, den2); // Construction of the 2nd fraction do // Validation input { cout << "Enter the Operation: "; // Input of Operation cin >> symbol; if (symbol == '+') // Checks for symbol and does operation accordingly { result = x+y; cout << result; } else if (symbol == '-') { result = x-y; cout << result; } else if (symbol == '*') { result = x*y; cout << result; } else if (symbol == '/') { result = x/y; cout << result; } else { cout << "Invalid, Enter a Valid operation symbol (+,-,*,/)" << endl; } } while(symbol!='+'&&symbol!='-'&&symbol!='*'&&symbol!='/'); cout << "Unary test: " << -result << endl; // Unary overload system("PAUSE"); return 0; // End of Program } Rational operator+(Rational &obj, Rational &obj2) // Plus overload { Rational x((obj.numerator*obj2.denominator) + (obj2.numerator*obj.denominator),obj.denominator*obj2.denominator); // Creats an object that stores the values and reduces it return x; } Rational operator-(Rational &obj, Rational &obj2) // Minus overload { Rational x((obj.numerator*obj2.denominator) - (obj2.numerator*obj.denominator),obj.denominator*obj2.denominator);// Creats an object that stores the values and reduces it return x; } Rational operator*(Rational &obj, Rational &obj2) // Multiply overload { Rational x(obj.numerator * obj2.numerator,obj.denominator * obj2.denominator);// Creats an object that stores the values and reduces it return x; } Rational operator/(Rational &obj, Rational &obj2) // Divide overload { Rational x(obj.numerator * obj2.denominator,obj.denominator * obj2.numerator);// Creats an object that stores the values and reduces it return x; }
true
e9cab7cf608ca5ab6853b42fd55e5745b6383f33
C++
lijiancheng0614/poj_solutions
/Volume1/1058/1058.cpp
UTF-8
3,785
2.796875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; typedef vector<string> vs; typedef vector<bool> vb; class Node { public: Node(string name) : name(name){} vector<string> files; vector<Node *> dirs; string name; }; class Solution { public: Solution(int n = 16) : n(n) {} bool solve(vector<vs> & lines, vector<vs> & ans) { ans.assign(2, vs(4, "AAAA")); graph.assign(n, vb(n, false)); for (int i = 0; i < lines.size(); ++i) for (int j = 0; j < 4; ++j) add_block(lines[i][j]); for (int i = 1; i < n; ++i) if (!graph[0][i]) { vector<int> points = get_disconnected_points(0, i); if (points.size() != 2) return false; ans[0][0][1] = i + 'A'; ans[0][0][2] = points[0] + 'A'; ans[0][0][3] = points[1] + 'A'; add_block(ans[0][0]); for (int j = 0; j < 4; ++j) { points = get_disconnected_points(ans[0][0][j] - 'A'); if (points.size() != 3) return false; ans[1][j][0] = ans[0][0][j]; for (int k = 0; k < 3; ++k) ans[1][j][1 + k] = points[k] + 'A'; add_block(ans[1][j]); } break; } for (int j = 1; j < 4; ++j) { vector<int> points = get_disconnected_points(ans[1][0][j] - 'A'); if (points.size() != 3) return false; ans[0][j][0] = ans[1][0][j]; for (int k = 0; k < 3; ++k) ans[0][j][1 + k] = points[k] + 'A'; add_block(ans[1][j]); } return true; } private: vector<vb> graph; int n; void add_block(string & block) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { int x = block[i] - 'A'; int y = block[j] - 'A'; graph[x][y] = graph[y][x] = true; } } vector<int> get_disconnected_points(int i, int j) { vector<int> ans; for (int k = 0; k < n; ++k) if (!graph[i][k] && !graph[j][k]) ans.push_back(k); return ans; } vector<int> get_disconnected_points(int i) { vector<int> ans; for (int k = 0; k < n; ++k) if (!graph[i][k]) ans.push_back(k); return ans; } }; int main() { string block; while (cin >> block) { vs line(1, block); for (int i = 0; i < 3; ++i) { cin >> block; line.push_back(block); } vector<vs> lines(1, line); for (int i = 0; i < 2; ++i) { vs line; for (int j = 0; j < 4; ++j) { cin >> block; line.push_back(block); } lines.push_back(line); } vector<vs> ans; bool flag = Solution().solve(lines, ans); if (!flag) cout << "It is not possible to complete this schedule." << endl; else { for (int i = 0; i < lines.size(); ++i) { for (int j = 0; j < lines[i].size(); ++j) cout << lines[i][j] << " "; cout << endl; } for (int i = 0; i < ans.size(); ++i) { for (int j = 0; j < ans[i].size(); ++j) cout << ans[i][j] << " "; cout << endl; } } cout << endl; } return 0; }
true
a68947604b1151fdbf3cb5437bc643d4a613657a
C++
FranciscoDavidMunozArmas/Semester-III
/BR_Tree/Libraries/Screen.cpp
UTF-8
1,602
2.578125
3
[]
no_license
/* * Universidad la Fuerzas Armadas ESPE * * @autor David Munoz & Daniela Orellana * @date Jueves, 28 de mayo de 2020 10:07:14 * @function Implementation of Screen */ #include "Screen.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <time.h> #include <windows.h> #include <ctype.h> #include <mmsystem.h> #pragma once using namespace std; /** * @brief gotoxy * @param x * @param y */ void Screen::gotoxy(int x, int y) { HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE); COORD dwPos; dwPos.X = x; dwPos.Y = y; SetConsoleCursorPosition(hcon, dwPos); } /** * @brief hide_cursor */ void Screen::hide_cursor() { HANDLE Cursor = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO info; info.dwSize = 100; info.bVisible = false; SetConsoleCursorInfo(Cursor, &info); } /** * @brief screen_size * @param width * @param height */ void Screen::screen_size(int width, int height) { _COORD size; _SMALL_RECT rect; size.X = width; size.Y = height; rect.Top = 0; rect.Left = 0; rect.Right = width - 1; rect.Bottom = height - 1; HANDLE _console = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleScreenBufferSize(_console, size); SetConsoleWindowInfo(_console, TRUE, &rect); } /** * @brief color_text * @param color */ void Screen::color_text(int color) { HANDLE ColorText = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(ColorText, color); } //void Screen::color_background() { // //}
true
030996ac6427924425fb7a8e10247147369bdf78
C++
tychen5/NTU_ANTS-lab
/networkTA_project/submission/DemoIII/b05705028_15.h
UTF-8
1,047
3
3
[]
no_license
#ifndef PROTOCOL_HPP #define PROTOCOL_HPP #include <string> using namespace std; namespace JPay { class Protocol { public: Protocol() : _success(false), _message("") {} Protocol(bool success, string message) : _success(success), _message(message) {} const bool success() const { return _success; } const string message() const { return _message; } const string rstrip() const { return _message.substr(0, _message.length() - 1); } void success(const bool success) { _success = success; } void message(const string message) { _message = message; } protected: // whether send success bool _success; string _message; }; class Request : public Protocol { public: Request() : Protocol() {} Request(bool success, string message) : Protocol(success, message) {} }; class Response : public Protocol { public: Response() : Protocol() {} Response(bool success, string message) : Protocol(success, message) {} }; enum ResponseStatus { OK = 100, FAIL = 210, AUTH_FAIL = 220 }; } // namespace JPay #endif
true
96ffd0cb50e0d3e0f8032d6d2ba68b93054b34de
C++
AdarshRaj9/Algorithmic-Toolbox-Coursera
/assignment_week3/q3/example/main.cpp
UTF-8
2,350
3.0625
3
[]
no_license
// // main.cpp // example // // Created by AADARSH RAJ on 26/04/20. // Copyright © 2020 ADARSH RAJ. All rights reserved. // /*#include <iostream> #include<vector> using namespace std; int no_Of_Stop(vector<int>arr,int n ,int l) { int numRefils=0,currRefil=0;//lastRefil=0; while(currRefil<=n) { int lastRefil=currRefil; while(((currRefil<=n) && (arr[currRefil+1]-arr[lastRefil]<=l))) { currRefil++; //if(currRefil == (n)) //break; } if(currRefil==lastRefil) return -1; if(currRefil<=n) numRefils++; } return numRefils; } int main(int argc, const char * argv[]) { int d=0,tank=0,n=0; //cout<<"total length\n"; cin>>d; //cout<<"Enter atmost kms\n"; cin>>tank; vector<int>arr; //cout<<"Enter the size of arr:\n"; cin>>n; //cout<<"Size of arr"<<" "<<n<<"\n"; //cout<<"Enter the arr\n"; for(int i=0;i<n;i++) { int a; cin>>a; arr.push_back(a); } if(tank<d) { int a=no_Of_Stop(arr,n,tank); // insert code here... cout <<a <<"\n"; } else cout<<0<<endl; return 0; }*/ #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; using std::max; int refills(int dist, int tank, vector<int> & arr, int start, int count) { if ((start + tank) >= dist) { return count; } if (arr.size() == 0) { return -1; } int old_start = start; for (int i = 0; i < arr.size(); i++) { if (arr[i] <= (start + tank)) { old_start = arr[i]; } else { if (i != 0) { arr.erase(arr.begin(), arr.begin() + i); } else { arr.erase(arr.begin()); } return refills(dist, tank, arr, old_start, count+1); } } return (old_start + tank) >= dist ? count+1 : -1; } int min_refills(int dist, int tank, vector<int> & stops) { return refills(dist, tank, stops, 0, 0); } int main() { int dist = 0; cin >> dist; int m = 0; cin >> m; int n = 0; cin >> n; vector<int> arr(n); for (size_t i = 0; i < n; ++i) cin >> arr.at(i); cout << min_refills(dist, m, arr) << "\n"; return 0; }
true
1216541b28c2b5d9796b455e03276cdb1e735b6b
C++
manarshawkey/SIM
/OOD new A3/processor.h
UTF-8
1,388
3.171875
3
[]
no_license
#pragma once #include<iostream> #include<string> #include"InstFactory.h" #include<vector> #include"Data_Mem.h" class processor { public: processor(); void execute_program(std::string, std::vector<Data_Mem>::pointer); void operator()(std::string, std::vector<Data_Mem>::pointer); private: InstFactory factory; void parse(std::string, std::vector<Data_Mem>::pointer); std::vector<instruction*> inst_mem; }; void processor::operator()(std::string p, std::vector<Data_Mem>::pointer d){execute_program(p, d);} processor::processor(){} void processor::execute_program(std::string file_path, std::vector<Data_Mem>::pointer data_mem) { try { parse(file_path, data_mem); } catch (std::exception e) { std::cout << e.what(); } bool halt = 0; int res; try { for (int pc = 0; pc < inst_mem.size(); pc++) { try{ res = inst_mem[pc]->execute(); } catch (const std::exception & e){ std::cout << "Error reported while program execution: " << e.what() << std::endl; } if (res == 0) continue; if (res == -1) { halt = 1; break; } else pc = res - 1; } if (!halt) throw std::exception("no halt command to terminate the execution!\n"); } catch (std::exception e) { std::cout << e.what() << std::endl; } } void processor::parse(std::string path, std::vector<Data_Mem>::pointer data_mem) { factory.parse(path, inst_mem, data_mem); }
true
6e58f50f0eebc87213cd27308df27ac6341f2d9d
C++
hadibrais/Alleria
/AlleriaPintool/BufferListManager.h
UTF-8
2,228
3.03125
3
[ "MIT" ]
permissive
#ifndef BUFFERLISTMANAGER_H #define BUFFERLISTMANAGER_H #include "pin.H" #include "AppThreadManager.h" #include <list> #include "PortableApi.h" struct BUFFER_STATE { // Points to the first element in the buffer. VOID *m_bufferStart; // Points to past the last element in the buffer. VOID *m_bufferEnd; // Represents the app thread manager that created the buffer. APP_THREAD_MANAGER *m_appThreadManager; }; // Represents a list of buffers that are either full and yet to be processed or // empty and yet to be filled. class BUFFER_LIST_MANAGER { public: BUFFER_LIST_MANAGER(); static VOID SetBufferSize(UINT32 bufferSize); VOID AddFullBuffer( // The address of the first element in the buffer. VOID *bufferStart, // The address of past the last element in the buffer. VOID *bufferEnd, // The app thread manager that created the buffer. APP_THREAD_MANAGER *atm, // The ID of the thread calling this function. THREADID tid ); VOID AddNewFreeBuffer(THREADID tid); VOID AddFreeBuffer( // The address of the first element in the buffer. VOID *bufferStart, // The ID of the thread calling this function. THREADID tid ); BOOL AcquireFullBuffer( BUFFER_STATE& buffer, // The ID of the thread calling this function. THREADID tid ); BOOL AcquireFreeBuffer( // The address of the first element in the MemRef buffer. VOID **bufferStart, // The ID of the thread calling this function. THREADID tid ); // Returns the number of buffers in the list. // TODO: Use list<BUFFER_STATE>::size_type when it becomes available size_t GetCount(); // Tells all processing threads that the process is terminating. VOID SignalTermination(); private: // The list of buffers. list<BUFFER_STATE> m_bufferList; // A Pin lock used to manage the buffer list in a thread-safe way. PIN_LOCK m_bufferListLock; // A semaphore used to coordinate all processing threads. // Cannot use PIN_SEMAPHORE because that's a binary semaphore and we need a counting sem. PSEMAPHORE m_bufferListSem; // The size of a buffer. static UINT32 s_bufferSize; }; #endif /* BUFFERLISTMANAGER_H */
true
451837ae6df6819ec2697225b8c74f90997e14e5
C++
kranurag01/Institute-Coding-Test-1
/Lazy Sorting.cpp
UTF-8
478
2.796875
3
[]
no_license
#include <iostream> #include <ctime> #include <cstdlib> #include <cmath> #include <iomanip> using namespace std; int fac(int n){ return (n == 1 || n == 0) ? 1 : fac(n - 1) * n; } int main(){ int n; cin >> n; int p[n]; for(int i = 0; i < n; ++i) cin >> p[i]; double time = 0; int t = fac(n); for(int i = 1; i <= 1000000000; ++i){ time = time + 1.0*i*pow(t,-i); } cout << fixed; cout << setprecision(6) << time << endl; return 0; }
true
fcbc6be93da52e4e48d6b53f16c5acfef59dddbb
C++
steven860219/sa
/作業9/prog1.cpp
UTF-8
5,999
3.578125
4
[]
no_license
#include <iostream> #include <cstdlib> #include <iomanip> using namespace std; class GeometricObject { private: string color; bool filled; public: GeometricObject() { color = "BLACK"; filled = false; cout << "Constructor1" << endl; } GeometricObject(string &color,bool filled) { this->color = color; this->filled = filled; cout << "Constructor2" << endl; } string getColor(void) { return color; } void setColor(string color) { this->color = color; } bool isFilled(void) { return filled; } void setFilled(bool filled) { this->filled = filled; } void toString(void) { if(filled == 0) cout << "Color:" << this->color << " Filled:False" << endl; else cout << "Color:" << this->color << " Filled:True" << endl; } }; class Circle : public GeometricObject { private: double radius; public: Circle() { radius = 1; cout << "CConstructor1" << endl; } Circle(double radius) { if(radius < 0) { cout << "CConstructor2" << endl; cout << "Wrong" << endl; this->radius = 0; } else { this->radius = radius; cout << "CConstructor2" << endl; } } Circle(double radius,string &color,bool filled) { if(radius < 0) { cout << "CConstructor3" << endl; cout << "Wrong" << endl; setColor(color); setFilled(filled); this->radius = 0; } else { setColor(color); setFilled(filled); this->radius = radius; cout << "CConstructor3" << endl; } } double getRadius(void) { return this->radius; } void setRadius(double radius) { if(radius < 0) { cout << "Wrong" << endl; this->radius = 0; } else this->radius = radius; } double getArea(void) { return (radius*radius*3.14159); } double getDiameter(void) { return (2*radius); } double getPerimeter(void) { return (2*radius*3.14159); } void toString(void) { cout << "CColor:" << getColor() << " Radius:" << fixed << setprecision(6) << this->radius << endl; std::cout.unsetf(std::ios_base::floatfield); } }; class Rectangle : public GeometricObject { private: double width,height; public: Rectangle() { width = 1; height = 1; cout << "RConstructor1" << endl; } Rectangle(double width,double height) { if(width < 0 || height < 0) { cout << "RConstructor2" << endl; cout << "Wrong" << endl; if(width < 0) { this->width = 0; this->height = height; } if(height < 0) { this->height = 0; this->width = width; } } else { cout << "RConstructor2" << endl; this->width = width; this->height = height; } } Rectangle(double width,double height,string &color,bool filled) { if(width < 0 || height < 0) { cout << "RConstructor2" << endl; cout << "Wrong" << endl; if(width < 0) { this->width = 0; this->height = height; } if(height < 0) { this->height = 0; this->width = width; } setColor(color); setFilled(filled); } else { cout << "RConstructor2" << endl; this->width = width; this->height = height; setColor(color); setFilled(filled); } } double getWidth(void) { return width; } double getHeight(void) { return height; } void setWidth(double width) { if(width >= 0) this->width = width; else cout << "Wrong" << endl; } void setHeight(double height) { if(height >= 0) this->height = height; else cout << "Wrong" << endl; } double getArea(void) { return (width*height); } double getPerimeter(void) { return (2*(width+height)); } void toString(void) { cout << "Rheight:" << fixed << setprecision(6) << this->height << " Rwidth:"<< fixed << setprecision(6) << this->width << endl; std::cout.unsetf(std::ios_base::floatfield); } }; int main(void) { GeometricObject shape; shape.setColor("red"); shape.setFilled(true); shape.toString();cout << "color: " << shape.getColor() << " filled: " << (shape.isFilled() ? "true" : "false") << endl; Circle circle(5); circle.setColor("black"); circle.setFilled(false); circle.toString(); cout << "color: " << circle.getColor() << " filled: " << (circle.isFilled() ? "true" : "false") << " radius: " << circle.getRadius() << " area: " << circle.getArea() << " perimeter: " << circle.getPerimeter() << endl; Circle circle1(-5); circle1.setColor("black"); circle1.setFilled(false); circle1.toString(); cout<< "color: " << circle1.getColor() << " filled: " << (circle1.isFilled() ? "true" : "false") << " radius: " << circle1.getRadius() << " area: " << circle1.getArea() << " perimeter: " << circle1.getPerimeter() << endl; string strc("red"); Circle circle2(2.5, strc, false); circle2.setColor("black"); circle2.setFilled(false); circle2.toString(); cout << "color: " << circle2.getColor() << " filled: " << (circle2.isFilled() ? "true" : "false") << " radius: " << circle2.getRadius() << " area: " << circle2.getArea() << " perimeter: " << circle2.getPerimeter() << endl; Rectangle rectangle(2, 3); rectangle.setColor("orange"); rectangle.setFilled(true); rectangle.toString();cout << "color: " << rectangle.getColor() << " filled: " << (rectangle.isFilled() ? "true" : "false") << " width: " << rectangle.getWidth() << " height: " << rectangle.getHeight() << " area: " << rectangle.getArea() << " perimeter: " << rectangle.getPerimeter() << endl; Rectangle rectangle1(2, 0); rectangle.setColor("orange"); rectangle.setFilled(true); rectangle1.toString();cout << "color: " << rectangle1.getColor() << " filled: " << (rectangle1.isFilled() ? "true" : "false") << " width: " << rectangle1.getWidth() << " height: " << rectangle1.getHeight() << " area: " << rectangle1.getArea() << " perimeter: " << rectangle1.getPerimeter()<<endl; return 0; }
true
778e0cdad4f34784c871d7db838cb7fbee7de9df
C++
toanndpro/Basic-C-Plug-Plug
/Class/EX12/Source.cpp
UTF-8
2,067
3.59375
4
[]
no_license
/* Xây dựng lớp TIME mô tả các thông tin về giờ, phút, giây. Lớp TIME có các thành phần sau: - Các thuộc tính mô tả giờ phút giây - Hàm thiết lập có ba tham số giờ, phút, giây được lấy giá trị ngầm định là 0. - Hàm thành phần Set(int,int,int) để xác lập thời gian - Hàm hiển thị giờ yheo 24 tiếng - Hàm hiển thị giờ theo 12 tiếng ( AM và PM) */ #include<iostream> #include<stdio.h> #include<Windows.h> using namespace std; // Khai bao lop TIME class TIME { // Thuoc tinh gio, phut va giay int hour, minute, second; private: //Tang gio len 1 void incHour() { hour++; // Chuyen ngay if (hour == 24) hour = 0; } // Tang phut len 1 void incMinute() { minute++; //Chuyen gio if (minute == 60) { minute = 0; incHour(); } } public: TIME(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}; //~TIME(); void set(int h, int m = 0, int s = 0) { // Ham xac lap thoi gian vowi phut va giay mac dinh la 0 hour = h; minute = m; second = s; } //Ham thanh phan tick void tick() { //Tang giay len 1 second++; if (second == 60) { second = 0; incMinute(); } } // Cac ham xac lap tung thanh phan void setHour(int h) { hour = h; } void setMinute(int m) { minute = m; } void setSecond(int s) { second = s; } // Cac ham lay gia tri tung thanh phan int getHour() { return hour; } int getMinute() { return minute; } int getSecond() { return second; } // Ham hien thi gio theo 24 tieng void display24() { cout << hour << ":" << minute << ":" << second; } // Ham hien thi gio theo 12 tieng void display12() { if (hour > 12) { cout << hour - 12 << ":" << minute << ":" << second <<" PM"<< endl; } else { cout << hour << ":" << minute << ":" << second<< " AM" << endl; } } }; int main() { TIME time(10,32,45); //time.display12(); while (true) { system("cls"); time.tick(); time.display24(); Sleep(1000); } system("pause"); return 0; }
true
acef954f24ca64887d657391d2277de37108b1bb
C++
RahmanMoshiur00/Code-Library
/Graph/Articulation Bridge.cpp
UTF-8
1,731
2.625
3
[]
no_license
// LightOJ 1026 - Critical Links #include <bits/stdc++.h> using namespace std; #define repit(it, x) for(__typeof__((x).begin()) it = (x).begin(); it != (x).end(); ++it) #define rep(i, begin, end) for (__typeof(end) i = (begin); i < (end); i += 1) #define all(a) a.begin(), a.end() #define mxn 100010 vector<int> adj[mxn]; bool vis[mxn]; int parent[mxn], dis[mxn], low[mxn], tym = 0; vector< pair<int, int> > bridge; void ArticulationBridge(int u) //finds articulation bridges { vis[u] = true; low[u] = dis[u] = ++tym; repit(it, adj[u]) { int v = *it; if(parent[u] == v){ continue; } if(vis[v]){ //back edge low[u] = min(low[u], dis[v]); } if(!vis[v]){ parent[v] = u; ArticulationBridge(v); low[u] = min(low[u], low[v]); if(dis[u]<low[v]){ //u-v is an articulation bridge bridge.push_back({min(u, v), max(u, v)}); } } } } void solve(int tc) { int n, u, v, k; scanf("%d", &n); rep(i, 0, n){ scanf("%d (%d)", &u, &k); rep(j, 0, k){ scanf("%d", &v); adj[u].push_back(v); } } rep(i, 0, mxn) vis[i] = false, parent[i] = -1; tym = 0; rep(i, 0, n){ if(!vis[i]){ ArticulationBridge(i); } } sort(all(bridge)); int sz = bridge.size(); printf("Case %d:\n", tc); printf("%d critical links\n", sz); rep(i, 0, sz) printf("%d - %d\n", bridge[i].first, bridge[i].second); rep(i, 0, n) adj[i].clear(); bridge.clear(); } int32_t main() { int tc; cin>>tc; rep(t, 1, tc+1) solve(t); return 0; }
true
19968b3c2dcccc06b6ef4a5b53ed12442ac65d15
C++
Hallaation/Lootcrates
/LootBoxes/LootBoxes.cpp
UTF-8
4,468
2.65625
3
[]
no_license
// LootBoxes.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Rarity.h" #include <random> #include <time.h> #include <iostream> #include "BaseLootCrate.h" #include "RewardList.h" struct MyLootCrates { BaseLootCrate mCrate; int miAmountOfCrates; }; using namespace std; int main() { std::vector<BaseLootCrateReward> mObtainedRewards; srand(time(NULL)); //Setup a reward list RewardList *mRewardList = new RewardList(); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(COMMON, "Common")); mRewardList->AddReward(BaseLootCrateReward(RARE, "Rare")); mRewardList->AddReward(BaseLootCrateReward(RARE, "Rare")); mRewardList->AddReward(BaseLootCrateReward(RARE, "Rare")); mRewardList->AddReward(BaseLootCrateReward(RARE, "Rare")); mRewardList->AddReward(BaseLootCrateReward(EPIC, "Epic")); mRewardList->AddReward(BaseLootCrateReward(EPIC, "Epic")); mRewardList->AddReward(BaseLootCrateReward(LEGENDARY, "Legendary")); mRewardList->AddReward(BaseLootCrateReward(MYTHICAL, "Mythical")); //Make some lootcrates MyLootCrates mLootCrates[4] { { BaseLootCrate(COMMON, 1.99, 5), 5 }, { BaseLootCrate(RARE, 2.99, 4), 5 }, { BaseLootCrate(EPIC, 3.99, 3), 5 }, { BaseLootCrate(LEGENDARY, 5.99, 2), 5 }, }; for (size_t i = 0; i < 4; i++) { mLootCrates[i].mCrate.SetRewardList(mRewardList); } bool running = true; float creditBalance = 2000; int currentSkew = 10; int OpenedBoxes, AmountForGuaranteeLegendary = 20; char selection; while (running) { std::cout << "Current balance: $" << creditBalance << std::endl; for (auto it : mObtainedRewards) { std::cout << it.GetReward() << " "; } std::cin >> selection; switch (toupper(selection)) { case 'C': { if (mLootCrates[0].miAmountOfCrates > 0) { for (auto it : mLootCrates[0].mCrate.RollRewards(currentSkew, (OpenedBoxes >= AmountForGuaranteeLegendary))) { std::cout << it.GetReward() << std::endl; mObtainedRewards.push_back(it); } mLootCrates[0].miAmountOfCrates--; currentSkew--; OpenedBoxes++; creditBalance -= mLootCrates[0].mCrate.GetPrice(); } else { std::cout << "Not enough money" << std::endl; } break; } case 'R': { if (mLootCrates[1].mCrate.GetPrice() <= creditBalance) { for (auto it : mLootCrates[1].mCrate.RollRewards(currentSkew, (OpenedBoxes >= AmountForGuaranteeLegendary))) { std::cout << it.GetReward() << std::endl; mObtainedRewards.push_back(it); } mLootCrates[1].miAmountOfCrates--; currentSkew--; OpenedBoxes++; creditBalance -= mLootCrates[1].mCrate.GetPrice(); } else { std::wcout << "Not enough money" << std::endl; } break; } case 'E': { if (mLootCrates[2].mCrate.GetPrice() <= creditBalance) { for (auto it : mLootCrates[2].mCrate.RollRewards(currentSkew, (OpenedBoxes >= AmountForGuaranteeLegendary))) { std::cout << it.GetReward() << std::endl; mObtainedRewards.push_back(it); } mLootCrates[2].miAmountOfCrates--; currentSkew--; OpenedBoxes++; creditBalance -= mLootCrates[2].mCrate.GetPrice(); } else { std::cout << "Not enough money" << std::endl; } break; } case 'L': { if (mLootCrates[3].mCrate.GetPrice() <= creditBalance) { for (auto it : mLootCrates[3].mCrate.RollRewards(currentSkew, (OpenedBoxes >= AmountForGuaranteeLegendary))) { std::cout << it.GetReward() << std::endl; mObtainedRewards.push_back(it); } mLootCrates[3].miAmountOfCrates--; currentSkew--; OpenedBoxes++; creditBalance -= mLootCrates[3].mCrate.GetPrice(); } else { std::cout << "Not enough money" << std::endl; } break; } default: break; } if (currentSkew <= 0) { currentSkew = 10; } std::cout << std::endl; system("cls"); //cout << &lootCrate1; } delete mRewardList; mRewardList = nullptr; return 0; }
true
38c6138f1b17987f244707e23b83c52952f6d60b
C++
c0f93f4fcaa31895c50a3e6a3de98c1f/project
/src/sklist/main.cpp
UTF-8
647
2.796875
3
[]
no_license
#include <iostream> #include "sklist.h" using namespace std; //Just for test void *GenData(int len) { void *ptr = new char [len]; return ptr; } int main() { SkList *sklist = new SkList(3); sklist->Insert(1, GenData(3)); sklist->Insert(2, GenData(2)); sklist->Insert(3, GenData(4)); sklist->Insert(4, GenData(5)); sklist->Insert(5, GenData(5)); sklist->Insert(6, GenData(3)); sklist->Insert(7, GenData(2)); sklist->Insert(8, GenData(4)); sklist->Insert(9, GenData(5)); sklist->Insert(10, GenData(5)); sklist->Display(); sklist->Delete(8); sklist->Display(); return 0; }
true
2e45126da4ace1ad6adfd6438c2e20a4d6534950
C++
devdk1/Coding
/zigZag.cpp
UTF-8
512
3.34375
3
[]
no_license
#include <iostream> using namespace std; void zigZag(int a[], int n) { bool flag = true; for(int i = 0; i < n - 1; i++) { if(flag && a[i] > a[i+1]) swap(a[i], a[i+1]); else if(!flag && a[i] < a[i+1]) swap(a[i], a[i+1]); flag = !flag; } for(int i = 0; i < n; i++) cout<<a[i]<<" "; cout<<endl; } int main() { int n; cin>>n; int arr[n]; for( int i = 0; i < n; i++) cin>>arr[i]; zigZag(arr, n); return 0; }
true
d05409e89273ed67be67916bb4ad3886fb58cb57
C++
vmmc2/Competitive-Programming
/UVA 00784 - Maze Exploration.cpp
UTF-8
1,664
2.671875
3
[]
no_license
#include <bits/stdc++.h> #include <string.h> using namespace std; int a; int auxiliar; int xp, yp; int colunas, linhas; int x, y; char grid[300][300]; int visitados[300][300]; int dx[8] = {0 ,-1, 1, 0, -1, -1, 1, 1}; int dy[8] = {-1, 0, 0, 1, -1, 1, 1, -1}; void floodfill(int lin, int col){ int newx, newy; visitados[lin][col] = 1; for(int i = 0; i < 8; i++){ newx = lin + dx[i]; newy = col + dy[i]; if((grid[newx][newy] == ' ') && (newx >= 0) && (newy >= 0) && (visitados[newx][newy] == 0)){ grid[newx][newy] = '#'; //printmatriz(); floodfill(newx, newy); } } } int main(){ int numcasos; char aux[300]; char lixeira[300]; scanf("%d", &numcasos); for(a = 0; a < numcasos; a++){ memset(grid, 'V', sizeof grid); memset(visitados, 0, sizeof visitados); auxiliar = 0; while(true){ scanf(" %[^\n]", aux); if(aux[0] == '_'){ strcpy(lixeira, aux); break; } for(int j = 0; j < (int)strlen(aux); j++){ grid[auxiliar][j] = aux[j]; if(grid[auxiliar][j] == '*'){ grid[auxiliar][j] = '#'; xp = auxiliar; yp = j; } } auxiliar++; } floodfill(xp, yp); cin.ignore(); for(int i = 0; i < auxiliar; i++){ for(int j = 0; grid[i][j] != 'V'; j++){ cout << grid[i][j]; } cout << endl; } printf("%s\n", lixeira); } return 0; }
true
2f7f3179cc0362064cc2f3df831962e138c022eb
C++
rangaeeeee/profession
/predictoutput/cpp0078.cpp
UTF-8
562
3.453125
3
[]
no_license
/** * \file file.cpp * \author Rangarajan R * \date March, 2016 * \brief * Predict the output. * * \details * Detailed description of file. * * \note * The notes for this file. * * \copyright * */ #include<iostream> using namespace std; class A { int i; public: A(int ii = 0) : i(ii) {} void show() { cout << i << endl; } }; class B { int x; public: B(int xx) : x(xx) {} operator A() const { return A(x); } }; void g(A a) { a.show(); } int main() { B b(10); g(b); g(20); return 0; }
true
f4186db8c05b3cbcd061b80fb1fe66512b523b1d
C++
HonestRationalBest/CLionProjects
/prapareToCol/Figura.cpp
UTF-8
751
2.828125
3
[]
no_license
// // Created by pavel on 23.04.2021. // #include "Figura.h" #include <string> #include <math.h> #include <iostream> using namespace std; Operacje::~Operacje() { } void Figura::liczPole() { pole = value*value*3.14; } double Figura::podajPole() { return pole; } Kolo::Kolo(string f, int v):figura(f){ value = v; liczPole(); } Kolo::~Kolo() { std::cout << "Kolo znika" << std::endl; } Figura::Figura(string f, int v):figura(f){ value = v; liczPole(); } Figura::~Figura() { std::cout << "Kolo znika" << std::endl; } double Figura::Dodaj(double p1, double p2){ return p1+p2; } double Figura::Odejmuj(double p1, double p2){ return p1+p2; } double Figura::Zamien(double p1, double p2){ return p1+p2; }
true
57e629cfa0788762f3ba7115a19ad2a7bd05b747
C++
s8lei/Bezier-Roller-Coaster
/cse167proj4/BezierCurve.cpp
UTF-8
4,203
2.65625
3
[]
no_license
// // BezierCurve.cpp // cse167proj4 // // Created by LSQ on 11/11/19. // Copyright © 2019 LSQ. All rights reserved. // #include <stdio.h> #include "BezierCurve.h" #include "Window.h" glm::mat4 BezierCurve::B = glm::mat4(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); std::vector<int> BezierCurve::pindices = {0, 1, 2, 3}; BezierCurve::BezierCurve(int index) { this->index = index; } void BezierCurve::draw(glm::mat4 P) { render(P); Window::setIsCP(true); glBindVertexArray(vao); glDrawElements(GL_LINES, indices.size()*2, GL_UNSIGNED_INT, 0); // Unbind from the VAO. glBindVertexArray(0); Window::setIsCP(true); glBindVertexArray(pvao); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glPointSize(13); glDrawElements(GL_POINTS, pindices.size(), GL_UNSIGNED_INT, 0); // Unbind from the VAO. glBindVertexArray(0); } void BezierCurve::render(glm::mat4 P) { cps.clear(); cps.push_back(glm::vec3(P[0])); cps.push_back(glm::vec3(P[1])); cps.push_back(glm::vec3(P[2])); cps.push_back(glm::vec3(P[3])); this->P = P; points.clear(); for ( int i = 0; i <= 150; i++) { float t = float(i)/150.0f; glm::vec3 x = getPoint(t); points.push_back(x); if ( i != 150) indices.push_back(glm::ivec2(i, i+1)); } length = sqrt(glm::dot(points[1]-points[0], points[1]-points[0])); glGenVertexArrays(1, &vao); glGenBuffers(2, vbos); glGenBuffers(1, &ebo); // Bind to the VAO. glBindVertexArray(vao); // Bind to the first VBO. We will use it to store the points. glBindBuffer(GL_ARRAY_BUFFER, vbos[0]); // Pass in the data. glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * points.size(), points.data(), GL_STATIC_DRAW); // Enable vertex attribute 0. // We will be able to access points through it. glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); // Bind to the EBO. We will use it to store the indices. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); // Pass in the data. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(glm::ivec2) * indices.size(), indices.data(), GL_STATIC_DRAW); // Unbind from the VBO. glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind from the VAO. glBindVertexArray(0); glGenVertexArrays(1, &pvao); glGenBuffers(2, pvbos); glGenBuffers(1, &pebo); // Bind to the VAO. glBindVertexArray(pvao); // Bind to the first VBO. We will use it to store the points. glBindBuffer(GL_ARRAY_BUFFER, pvbos[0]); // Pass in the data. glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * cps.size(), cps.data(), GL_STATIC_DRAW); // Enable vertex attribute 0. // We will be able to access points through it. glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, vbos[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * colors.size(), colors.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); // Bind to the EBO. We will use it to store the indices. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pebo); // Pass in the data. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int) * pindices.size(), pindices.data(), GL_STATIC_DRAW); // Unbind from the VBO. glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind from the VAO. glBindVertexArray(0); } void BezierCurve::update() { } glm::vec3 BezierCurve::getPoint(GLfloat t) { glm::vec4 tvec = glm::vec4(glm::pow(t, 3.0f), glm::pow(t, 2.0f), t, 1.0f); glm::vec3 x = glm::vec3(P * B * tvec); return x; } void BezierCurve::setColor(std::vector<glm::vec3> colors) { this->colors = colors; // if (Window::manipulate) // { // std::cout<<index<<std::endl<<colors.size()<<std::endl; // for (int i = 0; i < 4; i ++) // { // std::cout<<colors[i].x<<colors[i].y<<colors[i].z<<std::endl; // } // } }
true
17e9fbaa948b9cfb5e42a0712ddfab911ed2c436
C++
Ockin/trogdor-pp
/src/core/lua/api/entities/luaentity.cpp
UTF-8
13,287
2.78125
3
[]
no_license
#include "../../../include/entities/entity.h" #include "../../../include/entities/being.h" #include "../../../include/lua/api/entities/luaentity.h" #include "../../../include/lua/api/entities/luabeing.h" using namespace std; namespace core { namespace entity { // Types which are considered valid by checkEntity() static const char *entityTypes[] = { "Entity", "Place", "Room", "Thing", "Item", "Object", "Being", "Player", "Creature", 0 }; // functions that take an Entity as an input (new, get, etc.) // format of call: Entity.new(e), where e is an Entity static const luaL_reg functions[] = { {0, 0} }; // Lua Entity methods that bind to C++ Entity methods // also includes meta methods static const luaL_reg methods[] = { {"input", LuaEntity::in}, {"out", LuaEntity::out}, {"getMeta", LuaEntity::getMeta}, {"setMeta", LuaEntity::setMeta}, {"getMessage", LuaEntity::getMessage}, {"setMessage", LuaEntity::setMessage}, {"isType", LuaEntity::isType}, {"getType", LuaEntity::getType}, {"getName", LuaEntity::getName}, {"getTitle", LuaEntity::getTitle}, {"setTitle", LuaEntity::setTitle}, {"getLongDesc", LuaEntity::getLongDesc}, {"setLongDesc", LuaEntity::setLongDesc}, {"getShortDesc", LuaEntity::getShortDesc}, {"setShortDesc", LuaEntity::setShortDesc}, {"observe", LuaEntity::observe}, {"glance", LuaEntity::glance}, {"observedBy", LuaEntity::observedBy}, {"glancedBy", LuaEntity::glancedBy}, {"__tostring", LuaEntity::getName}, {0, 0} }; /***************************************************************************/ const luaL_reg *LuaEntity::getFunctions() { return functions; } /***************************************************************************/ const luaL_reg *LuaEntity::getMethods() { return methods; } /***************************************************************************/ void LuaEntity::registerLuaType(lua_State *L) { luaL_newmetatable(L, "Entity"); // Entity.__index = Entity lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_register(L, 0, methods); luaL_register(L, "Entity", functions); } /***************************************************************************/ Entity *LuaEntity::checkEntity(lua_State *L, int i) { luaL_checktype(L, i, LUA_TUSERDATA); return *(Entity **)LuaState::luaL_checkudata_ex(L, i, entityTypes); } /***************************************************************************/ int LuaEntity::in(lua_State *L) { string str; int n = lua_gettop(L); if (n != 1) { return luaL_error(L, "takes no arguments"); } Entity *e = checkEntity(L, -n); if (0 == e) { return luaL_error(L, "not an Entity!"); } e->in() >> str; lua_pushstring(L, str.c_str()); return 1; } /***************************************************************************/ int LuaEntity::out(lua_State *L) { const char *message; const char *channel; int n = lua_gettop(L); if (n > 3) { return luaL_error(L, "too many arguments"); } if (n < 2) { message = "\n"; } else { message = luaL_checkstring(L, 1 - n); } if (n < 3) { channel = "notifications"; } else { channel = luaL_checkstring(L, -1); } Entity *e = checkEntity(L, -n); if (0 == e) { return luaL_error(L, "not an Entity!"); } e->out(channel) << message; e->out(channel).flush(); return 1; } /***************************************************************************/ int LuaEntity::getMeta(lua_State *L) { int n = lua_gettop(L); if (2 != n) { return luaL_error(L, "takes one string argument"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getMeta(luaL_checkstring(L, -1)).c_str()); return 1; } /***************************************************************************/ int LuaEntity::setMeta(lua_State *L) { int n = lua_gettop(L); if (3 != n) { return luaL_error(L, "takes two string arguments"); } Entity *e = checkEntity(L, -3); if (0 == e) { return luaL_error(L, "not an Entity!"); } e->setMeta(luaL_checkstring(L, -2), luaL_checkstring(L, -1)); return 1; } /***************************************************************************/ int LuaEntity::getMessage(lua_State *L) { int n = lua_gettop(L); if (2 != n) { return luaL_error(L, "takes one string argument"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getMessage(luaL_checkstring(L, -1)).c_str()); return 1; } /***************************************************************************/ int LuaEntity::setMessage(lua_State *L) { int n = lua_gettop(L); if (3 != n) { return luaL_error(L, "takes two string arguments"); } Entity *e = checkEntity(L, -3); if (0 == e) { return luaL_error(L, "not an Entity!"); } e->setMessage(luaL_checkstring(L, -2), luaL_checkstring(L, -1)); return 1; } /***************************************************************************/ int LuaEntity::isType(lua_State *L) { int n = lua_gettop(L); if (2 != n) { return luaL_error(L, "takes only one input, an entity type"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } enum EntityType type; string typeStr = luaL_checkstring(L, -1); // TODO: move all of this into Entity::strToType() if (0 == typeStr.compare("entity")) { type = ENTITY_ENTITY; } else if (0 == typeStr.compare("place")) { type = ENTITY_PLACE; } else if (0 == typeStr.compare("room")) { type = ENTITY_ROOM; } else if (0 == typeStr.compare("thing")) { type = ENTITY_THING; } else if (0 == typeStr.compare("item")) { type = ENTITY_ITEM; } else if (0 == typeStr.compare("object")) { type = ENTITY_OBJECT; } else if (0 == typeStr.compare("being")) { type = ENTITY_BEING; } else if (0 == typeStr.compare("player")) { type = ENTITY_PLAYER; } else if (0 == typeStr.compare("creature")) { type = ENTITY_CREATURE; } // string doesn't match any type (script writer is stupid) else { lua_pushboolean(L, 0); return 1; } lua_pushboolean(L, e->isType(type)); return 1; } /***************************************************************************/ int LuaEntity::getType(lua_State *L) { int n = lua_gettop(L); if (1 != n) { return luaL_error(L, "getType takes no arguments"); } Entity *e = checkEntity(L, 1); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getTypeName().c_str()); return 1; } /***************************************************************************/ int LuaEntity::getName(lua_State *L) { int n = lua_gettop(L); if (1 != n) { return luaL_error(L, "getName takes no arguments"); } Entity *e = checkEntity(L, 1); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getName().c_str()); return 1; } /***************************************************************************/ int LuaEntity::getTitle(lua_State *L) { int n = lua_gettop(L); if (1 != n) { return luaL_error(L, "getTitle takes no arguments"); } Entity *e = checkEntity(L, 1); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getTitle().c_str()); return 1; } /***************************************************************************/ int LuaEntity::setTitle(lua_State *L) { int n = lua_gettop(L); if (3 != n) { return luaL_error(L, "takes one string argument"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } string title = luaL_checkstring(L, -1); e->setTitle(title); return 1; } /***************************************************************************/ int LuaEntity::getLongDesc(lua_State *L) { int n = lua_gettop(L); if (1 != n) { return luaL_error(L, "getLongDesc takes no arguments"); } Entity *e = checkEntity(L, 1); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getLongDescription().c_str()); return 1; } /***************************************************************************/ int LuaEntity::setLongDesc(lua_State *L) { int n = lua_gettop(L); if (3 != n) { return luaL_error(L, "takes one string argument"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } string desc = luaL_checkstring(L, -1); e->setLongDescription(desc); return 1; } /***************************************************************************/ int LuaEntity::getShortDesc(lua_State *L) { int n = lua_gettop(L); if (1 != n) { return luaL_error(L, "getShortDesc takes no arguments"); } Entity *e = checkEntity(L, 1); if (0 == e) { return luaL_error(L, "not an Entity!"); } lua_pushstring(L, e->getShortDescription().c_str()); return 1; } /***************************************************************************/ int LuaEntity::setShortDesc(lua_State *L) { int n = lua_gettop(L); if (3 != n) { return luaL_error(L, "requires one string argument"); } Entity *e = checkEntity(L, -2); if (0 == e) { return luaL_error(L, "not an Entity!"); } string desc = luaL_checkstring(L, -1); e->setShortDescription(desc); return 1; } /***************************************************************************/ int LuaEntity::observe(lua_State *L) { // default values for optional arguments bool triggerEvents = true; bool displayFull = false; int n = lua_gettop(L); if (n < 2) { return luaL_error(L, "requires one string argument"); } else if (n > 4) { return luaL_error(L, "too many arguments"); } Entity *observed = LuaEntity::checkEntity(L, -n); Being *observer = LuaBeing::checkBeing(L, 1 - n); if (n > 2) { triggerEvents = lua_toboolean(L, 2 - n); } if (n > 3) { displayFull = lua_toboolean(L, 3 - n); } observed->observe(observer, triggerEvents, displayFull); return 1; } /***************************************************************************/ int LuaEntity::glance(lua_State *L) { // default values for optional argument bool triggerEvents = true; int n = lua_gettop(L); if (n < 2) { return luaL_error(L, "requires one string argument"); } else if (n > 3) { return luaL_error(L, "too many arguments"); } Entity *observed = LuaEntity::checkEntity(L, -n); Being *observer = LuaBeing::checkBeing(L, 1 - n); if (n > 2) { triggerEvents = lua_toboolean(L, 2 - n); } observed->glance(observer, triggerEvents); return 1; } /***************************************************************************/ int LuaEntity::observedBy(lua_State *L) { int n = lua_gettop(L); if (n < 2) { return luaL_error(L, "requires one argument"); } else if (n > 2) { return luaL_error(L, "too many arguments"); } Entity *observed = LuaEntity::checkEntity(L, -2); Being *observer = LuaBeing::checkBeing(L, -1); lua_pushboolean(L, observed->observedBy(observer)); return 1; } /***************************************************************************/ int LuaEntity::glancedBy(lua_State *L) { int n = lua_gettop(L); if (n < 2) { return luaL_error(L, "requires one argument"); } else if (n > 2) { return luaL_error(L, "too many arguments"); } Entity *glanced = LuaEntity::checkEntity(L, -2); Being *glancer = LuaBeing::checkBeing(L, -1); lua_pushboolean(L, glanced->glancedBy(glancer)); return 1; } }}
true
9fb6a49677092415644a4bae4cd8d6aab1e6708b
C++
johnsogg/cs1300
/homeworks/hw-7-cpp-basics/cpp/cpp_basics_driver.cpp
UTF-8
3,471
2.984375
3
[]
no_license
/* cpp_basics_driver.cpp Note to students: this is a weirdo file. Unless you are already a C++ pro, this will be baffling, confusing, and (possibly) frightening. Just sayin'. Go ahead and look at the unit test code, but realize that this is built using crazy C mis-features called macros. They're handy but zomg are they confusing. */ #include <cmath> #include "UTFramework.h" #include "cpp_basics.h" #define EPSILON 0.0001 using namespace Thilenius; bool eq(float actual, float expected) { return fabs(actual - expected) < EPSILON; } SUITE_BEGIN("CPP Basics") TEST_BEGIN("GetPower") { float res; res = get_power(2.4, 3); IsTrue("2.4^3", eq(13.824, res), "Wrong :("); res = get_power(2.4, -3); IsTrue("2.4^-3", eq(0, res), "Should be zero"); res = get_power(0, 3); IsTrue("0^-3", eq(0, res), "Should be zero"); res = get_power(0.42, 10); IsTrue("0.42^10", eq(0.00017080, res), "Wrong :("); }TEST_END TEST_BEGIN("GetPercent") { float res; res = get_percent(15, 30); IsTrue("15, 30", eq(50.0, res), "Wrong :("); res = get_percent(30, 30); IsTrue("30, 30", eq(100.0, res), "Wrong :("); res = get_percent(23, 30); IsTrue("23, 30", eq(76.6667, res), "Wrong :("); res = get_percent(-5, 30); IsTrue("-5, 30", eq(0, res), "Wrong :("); res = get_percent(30, 15); IsTrue("30, 15", eq(0, res), "Wrong :("); res = get_percent(43, 50); IsTrue("43, 50", eq(86.0, res), "Wrong :("); }TEST_END TEST_BEGIN("Strangeness") { int res; res = strangeness(100, 43); IsTrue("100, 43", 9 == res, "Wrong :("); res = strangeness(10, 43); IsTrue("10, 43", 33 == res, "Wrong :("); res = strangeness(5354, -4332); IsTrue("5354, -4332", 973 == res, "Wrong :("); res = strangeness(834, 834); IsTrue("834, 834", 0 == res, "Wrong :("); }TEST_END TEST_BEGIN("GetSizeForDoubles") { int res; int exp; exp = sizeof(double) * 12; res = get_size_for_n_doubles(12); IsTrue("12 doubles", exp == res, "Wrong :("); exp = 0; res = get_size_for_n_doubles(0); IsTrue("0 doubles", exp == res, "Wrong :("); res = get_size_for_n_doubles(-10); IsTrue("-10 doubles", exp == res, "Wrong :("); }TEST_END TEST_BEGIN("PeriwinkleVsGamboge") { bool isp; bool isg; int n; n = -401; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("-401", isp && !isg, "Wrong :("); n = 11; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("11", !isp && isg, "Wrong :("); n = 47; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("47", !isp && isg, "Wrong :("); n = 55; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("55", !isp && isg, "Wrong :("); n = 149; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("149", !isp && isg, "Wrong :("); n = 9; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("9", isp && !isg, "Wrong :("); n = 16; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("16", isp && !isg, "Wrong :("); n = 57; isp = is_periwinkle(n); isg = is_gamboge(n); IsTrue("57", isp && !isg, "Wrong :("); bool ok = true; for (int i=-500; i < 500; i++) { isp = is_periwinkle(i); isg = is_gamboge(i); ok = isp ^ isg; if (!ok) { break; } } IsTrue("-500 to 500", ok, "Something inconsistent."); }TEST_END SUITE_END int main (int argc, char* argv[]) { UTFrameworkInit; }
true
8de2d5f6588a87f405e1c6dfc555c4ae035a49df
C++
tomaszewskipablo/Backyard-Game
/BackyardGame/BackyardGame/Player.h
UTF-8
361
2.796875
3
[]
no_license
#pragma once #include "Entity.h" class Player : public Entity { private: double movementSpeed; bool isBlocked = false; public: Player(); ~Player(); // getters/setters bool getIsBlocked() const; //methods void move(const double &dt, const double xDirection, const double yDirection); void update(const double& dt); void block(); void unblock(); };
true
61e06811aef63883a171705f0a10dd7bbe0962af
C++
BRAINSia/BRAINSTools
/BRAINSCommonLib/TestSuite/DWIMetaDataDictionaryValidatorTest.cxx
UTF-8
14,377
2.9375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/** * \author Ali Ghayoor * This test file creates an ITK vector image, * and writes the image to the disk in NRRD format. */ #include <itkMetaDataObject.h> #include <cstdio> #include <itkImage.h> #include <itkImageFileWriter.h> #include <itkImageFileReader.h> #include <itkVectorImage.h> #include <itkImageRegionIteratorWithIndex.h> #include "DWIMetaDataDictionaryValidator.h" // Force printing of key values nicely static std::string ForceConvert(const itk::MetaDataObjectBase * myMetaDataObjectBase) { const auto * myMetaDataObject = dynamic_cast<const itk::MetaDataObject<std::string> *>(myMetaDataObjectBase); if (myMetaDataObject) { // const std::string temp =myMetaDataObject->GetMetaDataObjectTypeName(); const std::string temp("std::string"); return myMetaDataObject->GetMetaDataObjectValue() + " (type): " + temp; // assuming you define print for matrix } else { // double type for thickness field const auto * doubleMetaDataObject = dynamic_cast<const itk::MetaDataObject<double> *>(myMetaDataObjectBase); if (doubleMetaDataObject) { const std::string temp("double"); // convert double value to string std::ostringstream strs; strs << doubleMetaDataObject->GetMetaDataObjectValue(); std::string str = strs.str(); return str + " (type): " + temp; } else { const std::string temp = myMetaDataObjectBase->GetMetaDataObjectTypeName(); return "???_conversion (type): " + temp; } } } static void PrintDictionaryHelper(const itk::MetaDataDictionary & dictPrint) { std::cout << "----------------" << std::endl; auto end = dictPrint.End(); for (auto it = dictPrint.Begin(); it != end; ++it) { if (it->first.find("NRRD_measurement frame") != std::string::npos) { std::cout << ' ' << it->first << ":=" << std::endl; using msrFrameType = std::vector<std::vector<double>>; const auto * msrFrameMetaDataObject = dynamic_cast<const itk::MetaDataObject<msrFrameType> *>(it->second.GetPointer()); const msrFrameType & outMsr = msrFrameMetaDataObject->GetMetaDataObjectValue(); for (const auto & i : outMsr) { std::cout << " "; for (const auto & j : i) { std::cout << j << " "; } std::cout << std::endl; } } else { std::cout << ' ' << it->first << ":=" << ForceConvert(it->second) << std::endl; } } std::cout << "----------------" << std::endl; } // Create a vector image using PixelType = short; using VectorImageType = itk::VectorImage<PixelType, 3>; static VectorImageType::Pointer CreateVolume(const size_t numOfComponents) { constexpr int imageSize = 11; // each image component has size of imageSize^3 VectorImageType::IndexType start; start.Fill(0); VectorImageType::SizeType size; size.Fill(imageSize); VectorImageType::RegionType region(start, size); VectorImageType::Pointer nrrdVolume = VectorImageType::New(); nrrdVolume->SetRegions(region); nrrdVolume->SetVectorLength(numOfComponents); nrrdVolume->Allocate(); itk::VariableLengthVector<PixelType> ZeroPixel(numOfComponents); ZeroPixel.Fill(itk::NumericTraits<PixelType>::Zero); nrrdVolume->FillBuffer(ZeroPixel); itk::VariableLengthVector<PixelType> f(numOfComponents); for (size_t i = 0; i < numOfComponents; ++i) { if (i == 0 || i == 4) { f[i] = 255; // assumed as b0 images } else { f[i] = i * 10; // assumed as 6 gradient components } } // define a sub region start.Fill(3); size.Fill(4); VectorImageType::RegionType subRegion(start, size); using IteratorType = itk::ImageRegionIterator<VectorImageType>; IteratorType it(nrrdVolume, subRegion); it.GoToBegin(); while (!it.IsAtEnd()) { it.Set(f); ++it; } return nrrdVolume; } // TEST PROGRAM int main(int argc, char * argv[]) { if (argc < 4) { std::cout << argv[0] << "outputArtificialTestNrrdImage inputReferenceImage outputReplicatedReferenceImage" << std::endl; return EXIT_FAILURE; } bool allTestPass = true; // TEST #1 /* * FIRST TEST: * - Sets individual fields in the validator to create an output MetaDataDictionary * - Creates a vector image with default values * - Writes the created volume with output MetaDataDictionary */ constexpr size_t numOfComponents = 8; // Create a vector image VectorImageType::Pointer nrrdVolume = CreateVolume(numOfComponents); // Instantiate a validator object DWIMetaDataDictionaryValidator bldValidator; // Set and test validator fields individually try { /* NOTE: "centerings" and "thickness" should be created based on "volume interleaved". If the image is "pixel interleave" (like vectorImage in ITK), the NrrdIO will automatically handle the correct permutation. */ // Centerings testing { std::vector<std::string> tempCenterings(4, std::string("cell")); tempCenterings[3] = "???"; bldValidator.SetCenterings(tempCenterings); const std::vector<std::string> outCenterings = bldValidator.GetCenterings(); if (tempCenterings != outCenterings) { std::cout << "ERROR: outCenterings not preserved" << std::endl; for (const auto & outCentering : outCenterings) { std::cout << "Out outCenterings " << outCentering << std::endl; } allTestPass = false; } } // thickness testing { bool thicknessPass = true; std::vector<double> tempThickness(4, std::numeric_limits<double>::quiet_NaN()); tempThickness[2] = 2.123; bldValidator.SetThicknesses(tempThickness); const std::vector<double> outThicknesses = bldValidator.GetThicknesses(); if (tempThickness.size() != outThicknesses.size()) { thicknessPass = false; } else { for (size_t i = 0; i < outThicknesses.size(); ++i) { if (std::isnan(outThicknesses[i])) { if (!std::isnan(tempThickness[i])) { thicknessPass = false; } } else { if (outThicknesses[i] != tempThickness[i]) { thicknessPass = false; } } } } if (thicknessPass == false) { std::cout << "ERROR: outThicknesses not preserved" << std::endl; for (double outThicknesse : outThicknesses) { std::cout << "Output Thicknesses " << outThicknesse << std::endl; } allTestPass = false; } } // Measurement Frame { DWIMetaDataDictionaryValidator::RotationMatrixType msrFrame; for (unsigned int saxi = 0; saxi < 3; saxi++) { for (unsigned int saxj = 0; saxj < 3; saxj++) { msrFrame(saxi, saxj) = 0.0; } } msrFrame(0, 0) = 1.0; msrFrame(1, 1) = 1.0; msrFrame(2, 2) = 1.0; bldValidator.SetMeasurementFrame(msrFrame); const DWIMetaDataDictionaryValidator::RotationMatrixType outMsr = bldValidator.GetMeasurementFrame(); if (msrFrame != outMsr) { std::cout << "ERROR: outMsr not preserved" << std::endl; for (size_t i = 0; i < outMsr.RowDimensions; ++i) { for (size_t j = 0; j < outMsr.ColumnDimensions; ++j) { std::cout << "Out outMsr " << i << " " << j << " " << outMsr(i, j) << std::endl; } } allTestPass = false; } } // Modality { std::string tempModality("DWMRI"); // The only valid DWI modality bldValidator.SetModality(tempModality); const std::string outModality = bldValidator.GetModality(); if (tempModality != outModality) { std::cout << "ERROR: outModality not preserved" << std::endl; std::cout << "Out outModality " << outModality << std::endl; allTestPass = false; } } // B-Value { const double bValue = 10000.0 / 3; // The only valid DWI modality bldValidator.SetBValue(bValue); const double outBvalue = bldValidator.GetBValue(); if (bValue != outBvalue) { std::cout << "ERROR: outBvalue not preserved" << std::endl; std::cout << "Out outBvalue " << outBvalue << std::endl; allTestPass = false; } } // Gradient-Directions { /* We should apply direction std::cosines to gradient directions if requested by the user */ DWIMetaDataDictionaryValidator::GradientTableType GradientTable(numOfComponents); GradientTable[0][0] = 0; // first b0 image GradientTable[0][1] = 0; GradientTable[0][2] = 0; GradientTable[1][0] = 1; GradientTable[1][1] = 0; GradientTable[1][2] = 0; GradientTable[2][0] = 0; GradientTable[2][1] = 1; GradientTable[2][2] = 0; GradientTable[3][0] = 0; GradientTable[3][1] = 0; GradientTable[3][2] = 1; GradientTable[4][0] = 0; // second b0 image GradientTable[4][1] = 0; GradientTable[4][2] = 0; GradientTable[5][0] = 2; GradientTable[5][1] = 0; GradientTable[5][2] = 0; GradientTable[6][0] = 0; GradientTable[6][1] = 2; GradientTable[6][2] = 0; GradientTable[7][0] = 0; GradientTable[7][1] = 0; GradientTable[7][2] = 2; bldValidator.SetGradientTable(GradientTable); const DWIMetaDataDictionaryValidator::GradientTableType outGT = bldValidator.GetGradientTable(); if (GradientTable != outGT) { std::cout << "ERROR: outGT not preserved! Output outGT:" << std::endl; for (const auto & i : outGT) { for (const auto & j : i) { std::cout << j << " "; } std::cout << std::endl; } allTestPass = false; } } std::cout << "\n****\\begin Artificial Dictionary ****" << std::endl; PrintDictionaryHelper(bldValidator.GetMetaDataDictionary()); std::cout << "****\\end Artificial Dictionary ****" << std::endl; std::cout << "\nWrite the artificial vector image to the disk using the created artificial MetaDataDictionary...\n" << std::endl; // Write DWI Image To Disk { // Add meta data to nrrd volume nrrdVolume->SetMetaDataDictionary(bldValidator.GetMetaDataDictionary()); // Write Nrrd volume to disk using WriterType = itk::ImageFileWriter<VectorImageType>; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseCompressionOn(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput(nrrdVolume); nrrdWriter->SetFileName(argv[1]); nrrdWriter->Update(); } // TEST #2 /* * SECOND TEST: * - Read a reference DWI image as a vector image in ITK * - Set individual fields of a manual validator from the reference image metaDataDictionary * - Writes the itk reference image with the manual MetaDataDictionary * - Compares the input reference image with the replicated reference volume */ std::cout << "\n\n\n>>>Testing IO based copy from reference data:\n" << std::endl; // Test Replicating DWI Image Image From Disk // --Read Reference Image // --Replicate its meta data dictionary using the validator // --Write replicated reference image using the new meta data // --Compare the replicated image with input reference volume { using ReaderType = itk::ImageFileReader<VectorImageType>; ReaderType::Pointer nrrdReader = ReaderType::New(); nrrdReader->SetFileName(argv[2]); nrrdReader->Update(); VectorImageType::Pointer refVolume = nrrdReader->GetOutput(); // Create a reference validator by setting its MetaDataDictionary from the input reference volume DWIMetaDataDictionaryValidator refVolumeValidator; refVolumeValidator.SetMetaDataDictionary(refVolume->GetMetaDataDictionary()); std::cout << "****\\begin Reference Dictionary ****" << std::endl; PrintDictionaryHelper(refVolumeValidator.GetMetaDataDictionary()); std::cout << "****\\end Reference Dictionary ****" << std::endl; // Now copy over the dictionaries element by element to test storage/retrieval DWIMetaDataDictionaryValidator manualVolumeValidator; /* Fields that need to be set: - thickness - centerings - measurement frame - modality - b-value - gradients */ // Centerings testing manualVolumeValidator.SetCenterings(refVolumeValidator.GetCenterings()); // Thicknesses manualVolumeValidator.SetThicknesses(refVolumeValidator.GetThicknesses()); // Measurement Frame manualVolumeValidator.SetMeasurementFrame(refVolumeValidator.GetMeasurementFrame()); // Modality manualVolumeValidator.SetModality(refVolumeValidator.GetModality()); // B-Value manualVolumeValidator.SetBValue(refVolumeValidator.GetBValue()); // Gradient-Directions { DWIMetaDataDictionaryValidator::GradientTableType temp = refVolumeValidator.GetGradientTable(); manualVolumeValidator.SetGradientTable(temp); } std::cout << "\n=============================================================\n" << std::endl; std::cout << "****\\begin Manual Dictionary ****" << std::endl; PrintDictionaryHelper(manualVolumeValidator.GetMetaDataDictionary()); std::cout << "****\\end Manual Dictionary ****" << std::endl; // Now reset MetaDataDictionary from validator refVolume->SetMetaDataDictionary(manualVolumeValidator.GetMetaDataDictionary()); // Write Nrrd volume to disk using WriterType = itk::ImageFileWriter<VectorImageType>; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseCompressionOn(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput(refVolume); nrrdWriter->SetFileName(argv[3]); nrrdWriter->Update(); } } catch (...) { throw; } if (allTestPass) { std::cout << "SUCCESS!" << std::endl; return EXIT_SUCCESS; } std::cout << "FAILURE!" << std::endl; return EXIT_FAILURE; }
true
d92639e48e611f31dcfce232516fd16989e96364
C++
mnmartins/exerciciosC
/Projetos em C/GokuxVegeta.cpp
ISO-8859-1
406
2.921875
3
[]
no_license
#include<stdlib.h> #include<stdio.h> /*> Leia a distancia do Goku para o Vegeta > Diga se ele acerta ou no o Vegeta Alcance de golpe at 5000b Km*/ int main() { float distancia; printf ("Qual a distancia de Goku para Vegeta?\n"); scanf ("%f",&distancia); if (distancia <= 5000) { printf ("Te peguei, trouxa!!!\n"); } else { printf ("Te pego na proxima!\n"); } return 0; }
true