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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
db132b3fd819bc9194bb38f3eb66728cc43bcc1c | C++ | mariokonrad/asteroid-flight | /Quaternion.cpp | UTF-8 | 2,932 | 3.3125 | 3 | [
"Unlicense"
] | permissive | #include "Quaternion.h"
#include <math.h>
Quaternion::Quaternion(float x0, float x1, float x2, float x3)
{
x[0] = x0; x[1] = x1; x[2] = x2; x[3] = x3;
}
Quaternion::Quaternion(const Quaternion & q)
{
x[0] = q.x[0]; x[1] = q.x[1]; x[2] = q.x[2]; x[3] = q.x[3];
}
Quaternion::Quaternion(float s, const Vector3 & v)
{
x[0] = s;
x[1] = static_cast<Vector3>(v)[0];
x[2] = static_cast<Vector3>(v)[1];
x[3] = static_cast<Vector3>(v)[2];
}
float Quaternion::s()
{
return x[0];
}
Vector3 Quaternion::v()
{
return Vector3(x[1], x[2], x[3]);
}
Quaternion::operator float * ()
{
return x;
}
float & Quaternion::operator [] (int i)
{
return x[i];
}
Quaternion & Quaternion::operator += (const Quaternion & q)
{
x[0] += q.x[0]; x[1] += q.x[1]; x[2] += q.x[2]; x[3] += q.x[3]; return *this;
}
Quaternion & Quaternion::operator -= (const Quaternion & q)
{
x[0] -= q.x[0]; x[1] -= q.x[1]; x[2] -= q.x[2]; x[3] -= q.x[3]; return *this;
}
Quaternion & Quaternion::operator *= (const Quaternion & b)
{
Quaternion a(*this);
x[0] = a.x[0] * b.x[0] - a.x[1] * b.x[1] - a.x[2] * b.x[2] - a.x[3] * b.x[3];
x[1] = a.x[0] * b.x[1] + b.x[0] * a.x[1] + a.x[2] * b.x[3] - a.x[3] * b.x[2];
x[2] = a.x[0] * b.x[2] + b.x[0] * a.x[2] - a.x[1] * b.x[3] + a.x[3] * b.x[1];
x[3] = a.x[0] * b.x[3] + b.x[0] * a.x[3] + a.x[1] * b.x[2] - a.x[2] * b.x[1];
return *this;
}
Quaternion & Quaternion::operator *= (float s)
{
x[0] *= s; x[1] *= s; x[2] *= s; x[3] *= s; return *this;
}
float Quaternion::length()
{
return sqrt(length2());
}
float Quaternion::length2()
{
return x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3];
}
Quaternion & Quaternion::norm(float s)
{
float f = length();
if (f == 0.0) return *this;
s /= f;
x[0] *= s; x[1] *= s; x[2] *= s; x[3] *= s;
return *this;
}
Quaternion Quaternion::inv()
{
return Quaternion(x[0], -x[1], -x[2], -x[3]);
}
Quaternion operator + (const Quaternion & a, const Quaternion & b)
{
Quaternion q(a);
return q += b;
}
Quaternion operator - (const Quaternion & a, const Quaternion & b)
{
Quaternion q(a);
return q -= b;
}
Quaternion operator * (float s, const Quaternion & a)
{
Quaternion q(a);
return q *= s;
}
Quaternion operator * (const Quaternion & a, float s)
{
Quaternion q(a);
return q *= s;
}
Quaternion operator * (const Quaternion & a, const Quaternion & b)
{
return Quaternion(
a.x[0] * b.x[0] - a.x[1] * b.x[1] - a.x[2] * b.x[2] - a.x[3] * b.x[3],
a.x[0] * b.x[1] + b.x[0] * a.x[1] + a.x[2] * b.x[3] - a.x[3] * b.x[2],
a.x[0] * b.x[2] + b.x[0] * a.x[2] - a.x[1] * b.x[3] + a.x[3] * b.x[1],
a.x[0] * b.x[3] + b.x[0] * a.x[3] + a.x[1] * b.x[2] - a.x[2] * b.x[1]
);
}
ostream & operator << (ostream & os, const Quaternion & v)
{
os << "(" << v.x[0] << "," << v.x[1] << "," << v.x[2] << "," << v.x[3] << ")";
return os;
}
| true |
7c46ed0ffe471ed772143b4e5c9c979d912c851a | C++ | intellild/CellularAutomata | /CellularAutomata/CellularAutomataImplement.cpp | WINDOWS-1252 | 3,913 | 2.53125 | 3 | [
"MIT"
] | permissive | #include"CellularAutomataImplement.h"
#include<omp.h>
#include<Windows.h>
#include<locale>
#include<codecvt>
#include<boost/property_tree/ptree.hpp>
#include<boost/property_tree/xml_parser.hpp>
#include<boost/typeof/typeof.hpp>
using namespace CA;
ElementCollect& CA::getElements()
{
static ElementCollect ec;
return ec;
}
Machine& CA::getCA()
{
static Machine ca;
return ca;
}
Machine::Machine() :
data(boost::extents[50 + 2][50 + 2]),
buffer(boost::extents[50 + 2][50 + 2]),
pThread(nullptr)
{
Point pos;
pos.x = 25;
pos.y = 25;
add_element(getElements().get(L""), pos);
}
Machine::~Machine()
{
if (flag_auto_update)
{
stop_auto_update();
}
}
void Machine::update()
{
update_by_step();
}
void Machine::begin_auto_update()
{
if (!flag_auto_update)
{
flag_auto_update = true;
auto auto_update = [&]()
{
while (flag_auto_update)
{
update_by_step();
Sleep(400);
}
return;
};
pThread = std::make_unique<std::thread>(auto_update);
}
else
{
std::abort();
}
}
void Machine::stop_auto_update()
{
if (flag_auto_update)
{
flag_auto_update = false;
pThread->join();
}
else
{
std::abort();
}
}
void Machine::set_burn(int burn)
{
config_mutex.lock();
this->burn = burn;
config_mutex.unlock();
}
void Machine::set_live(int live)
{
config_mutex.lock();
this->live = live;
config_mutex.unlock();
}
int Machine::get_burn()
{
return burn;
}
int Machine::get_live()
{
return live;
}
void CA::Machine::add_element(const Element & ele, const Point& pos)
{
ele.for_each_point([&](Point point)
{
data[point.x + pos.x][point.y + pos.y] = alive;
});
}
void Machine::for_each(std::function<void(const unit, const int, const int)> func)
{
data_mutex.lock();
for (int i = 1;i < 51;++i)
{
for (int j = 1;j < 51;++j)
{
func(data[i][j], i, j);
}
}
data_mutex.unlock();
}
inline void Machine::update_by_step()
{
#pragma omp parallel for
for (int i = 1;i < 51;++i)
{
for (int j = 1;j < 51;++j)
{
int count =
data[i - 1][j - 1] +
data[i - 1][j] +
data[i - 1][j + 1] +
data[i][j - 1] +
data[i][j + 1] +
data[i + 1][j - 1] +
data[i + 1][j] +
data[i + 1][j + 1];
if (count == burn)
{
buffer[i][j] = 1;
}
else if (count == live)
{
buffer[i][j] = data[i][j];
}
else
{
buffer[i][j] = 0;
}
}
}
data_mutex.lock();
boost::swap(data, buffer);
data_mutex.unlock();
}
inline void Machine::set_alive(const int i, const int j)
{
if (i > 0 && i < 51 && j > 0 && j < 51)
{
data[i][j] = alive;
}
}
CA::Element::Element(const std::vector<Point>& data)
{
this->data = data;
}
void Element::revolve()
{
for (auto& i : data)
{
i.y *= -1;
std::swap(i.x, i.y);
}
}
void CA::Element::for_each_point(std::function<void(Point)> func) const
{
std::for_each(data.begin(), data.end(), func);
}
CA::ElementCollect::ElementCollect()
{
load_from_xml("resource.xml");
}
Element CA::ElementCollect::get(std::wstring name)
{
return data[name];
}
void CA::ElementCollect::load_from_xml(std::wstring wpath)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
std::string path = conv.to_bytes(wpath);
load_from_xml(path);
}
void CA::ElementCollect::load_from_xml(std::string path)
{
using namespace boost::property_tree;
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
ptree root;
read_xml(path, root);
auto resource = root.get_child("resource");
std::for_each(resource.begin(), resource.end(), [&](auto i)
{
std::string name = i.second.get<std::string>("name");
std::wstring wname = conv.from_bytes(name);
ptree points = i.second.get_child("points");
std::vector<Point> vecpoint;
std::for_each(points.begin(), points.end(), [&](auto j)
{
CA::Point point;
point.x = j.second.get<int>("x");
point.y = j.second.get<int>("y");
vecpoint.push_back(point);
});
data[wname] = Element(vecpoint);
});
}
| true |
26d0ecfc22a851f79c9bcf8b826564470d167d9a | C++ | FooJiaYin/OJ-problems | /NTHUCS OJ Problems/11417 - String Operation/11417.cpp | UTF-8 | 778 | 3.109375 | 3 | [] | no_license | #include "function.h"
int main() {
int N;
char input[100];
int index=0;
Str *s[100];
cin>>N;
for(int i=0;i<N;i++){
cin>>input;
s[index++]=new Str(input);
}
char op[3];//"si" || "is" || "s" || "i" || "e"
while(1){
cin>>op;
if(op[0]=='e')break;
int idx1,idx2;
cin>>idx1;
cin>>idx2;
Str &s1=*s[idx1];
Str &s2=*s[idx2];
if(op[0]=='s'&&op[1]=='i'){
s1.strSwap(s2).strInsert(s2);
}else if(op[0]=='i'&&op[1]=='s'){
s1.strInsert(s2).strSwap(s2);
}else if(op[0]=='s'){
s1.strSwap(s2);
}else if(op[0]=='i'){
s1.strInsert(s2);
}
}
for(int i=0;i<N;i++){
s[i]->strPrint();
delete s[i];
}
return 0;
}
| true |
ee7da11e2090469d33e3efda5702dd9bd22e9225 | C++ | mdvv85009/Practice-DataStructure | /Stack/stack.cpp | UTF-8 | 626 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
#define MAX_ITEM 10
typedef struct tagStack{
int Item[MAX_ITEM];
int Top = -1;
} Stack;
void stack_push(Stack* stack, int value){
if(stack_isFull(stack))
stack -> Item[++(stack -> Top)] = value;
}
void stack_pop(Stack* stack, int* value){
if(stack_isEmpty(stack))
*value = stack -> Item[(stack -> Top)--];
}
bool stack_isFull(Stack* stack){
if(stack -> Top == (MAX_ITEM - 1))
return true;
else
return false;
}
bool stack_isEmpty(Stack* stack){
if(stack -> Top == -1)
return true;
else
return false;
} | true |
fa77be63bfdd27d67648c3510d01305f777b66a4 | C++ | MiloHX/Parrot | /parrot/src/parrot/tool/Math.cpp | UTF-8 | 2,082 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #include "prpch.h"
#include "parrot/tool/Math.h"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/matrix_decompose.hpp>
namespace parrot {
bool decomposeGlmTransform(const glm::mat4& transform, glm::vec3& out_translation, glm::vec3& out_rotation, glm::vec3& out_scale) {
using namespace glm;
using T = float;
mat4 local_matrix(transform);
// Normalize the matrix
if (epsilonEqual(local_matrix[3][3], static_cast<T>(0), epsilon<T>())) {
return false;
}
// isolate perspective
if (epsilonNotEqual(local_matrix[0][3], static_cast<T>(0), epsilon<T>()) ||
epsilonNotEqual(local_matrix[1][3], static_cast<T>(0), epsilon<T>()) ||
epsilonNotEqual(local_matrix[2][3], static_cast<T>(0), epsilon<T>()))
{
// clear the perspective partition
local_matrix[0][3] = local_matrix[1][3] = local_matrix[2][3] = static_cast<T>(0);
local_matrix[3][3] = static_cast<T>(1);
}
// translation
out_translation = vec3(local_matrix[3]);
local_matrix[3] = vec4(0, 0, 0, local_matrix[3].w);
vec3 row[3];
// get scale
for (length_t i = 0; i < 3; ++i) {
for (length_t j = 0; j < 3; ++j) {
row[i][j] = local_matrix[i][j];
}
}
// compute X scale factor and normalize first row
out_scale.x = length(row[0]);
row[0] = detail::scale(row[0], static_cast<T>(1));
out_scale.y = length(row[1]);
row[1] = detail::scale(row[1], static_cast<T>(1));
out_scale.z = length(row[2]);
row[2] = detail::scale(row[2], static_cast<T>(1));
// rotation
out_rotation.y = asin(-row[0][2]);
if (cos(out_rotation.y) != 0) {
out_rotation.x = atan2(row[1][2], row[2][2]);
out_rotation.z = atan2(row[0][1], row[0][0]);
} else {
out_rotation.x = atan2(-row[2][0], row[1][1]);
out_rotation.z = 0;
}
return true;
}
} | true |
c5f7636ab995924cb127db7f7fdfe6d9ce8582a4 | C++ | DarkHonin/nibbler | /interface/sdl/include/SDL.class.hpp | UTF-8 | 903 | 2.734375 | 3 | [] | no_license | #ifndef SDL_INTERFACE_H
#define SDL_INTERFACE_H
#include "interface.hpp"
#include <SDL2/SDL.h>
class SDL : public Interface{
public:
static key_callback keyHook;
SDL(int blockx, int blocky, int blocksize);
SDL(SDL const & obj);
~SDL();
void drawBlock(int x, int y, Color c);
void drawText(int x, int y, std::string const txt);
void prerender();
void postrender();
void bindKeyCallback(const key_callback);
bool closing();
void close();
void pollEvents();
std::string getName();
private:
SDL_Window *_window;
SDL_Surface *_drawSurface;
int _xBlocks;
int _yBlocks;
int _blockSize;
};
extern "C"{
Interface * Interface_Init(int w, int h, int b){
printf("Creating new sdl instance\n");
return new SDL(w, h, b);
}
}
#endif | true |
1f36e3c04208ddc84600cfbba69b657fc10fda2b | C++ | nishizumi-lab/sample | /arduino/Distance/UltrasonicSensor/SEEED/main.ino | UTF-8 | 1,243 | 3.25 | 3 | [] | no_license | void setup() {
Serial.begin(9600) ; // シリアル通信速度(9600bps)
}
void loop() {
int cm ;
distance = calcDistance(7) ; // 7番ピンからセンサーの値(距離データ)を取得
Serial.print(distance) ; // 距離をシリアルモニタに表示(cm単位)
Serial.println("cm") ;
delay(1000) ; // 1000ms後に繰り返す
}
// 超音波センサーから取得したセンサ値を距離に換算
int calcDistance(int pin)
{
long t ;
int ans ;
// 超音波センサーに5usのパルスを出力
pinMode(pin, OUTPUT) ; // ピンを出力モード
digitalWrite(pin, LOW) ;
delayMicroseconds(2) ;
digitalWrite(pin, HIGH) ;
delayMicroseconds(5) ;
digitalWrite(pin, LOW) ;
// センサーからの反射パルスを受信する
pinMode(pin, INPUT) ; // ピンを入力モード
t = pulseIn(pin, HIGH) ; // パルス幅の時間を測る
if (t < 18000) { // 3m以内から距離計算
ans = (t / 29) / 2 ; // 往復なので2で割る
} else ans = 0 ; // 3m以上なら0を返す
return ans ;
}
| true |
c4c251d6be466bf24f9efd4c894c8b85bf8e145a | C++ | hdgbdn/LearnEffectCpp | /02_Constructors_Destructors_and_Assignment_Operators/05_Silently_writes_calls.cpp | UTF-8 | 3,170 | 3.875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Empty
{
};
template <typename T>
class NamedObject1
{
public:
NamedObject1(const char* name, const T& value);
NamedObject1(const string& name, const T& value);
// NamedObject1(); // if declared any constructor, compiler will not synthesize default constructor
private:
string nameValue;
T objectValue;
};
template <typename T>
class NamedObject2
{
public:
NamedObject2(string& name, const T& value);
// NamedObject1(); // if declared any constructor, compiler will not synthesize any constructor
private:
string& nameValue; // will not synthesize copy assignment operator, because reference assignment is meaningless
const T objectValue; // also meaningless for const data member
};
class A
{
public:
A& operator=(const A&) = delete; // if base class's copy assignment is deleted
};
class B:public A
{
public:
// copy assignment operator will be also deleted in class B
};
int main()
{
// Empty class is not empty because compiler will declare:
// default constructor(if you don't declare any constructor)
// copy constructor
// copy assignment operator
// destructor
// but it only been created when being called
//Empty e1; // compiler create default constructor and destructor
//Empty e2(e1); // compiler create copy constructor
//e2 = e1; // copy assignment operator
//// if you declared any constructor, compiler will not synthesize any constructor
//NamedObject1<int> no1("Smallest Prime Number", 2);
//NamedObject1<int> no2(no1); // synthesized copy constructor
//// the synthesize copy constructor will call string's copy constructor, and int is a build-in type, so copy int bit-wise
//// synthesized copy constructor will be synthesized only the code will be valid and having meaning
//// see NamedObject2, now constructed by a reference-to-non-const string, and data member nameValue is reference to string
//
//string newDog("Persephone");
//string oldDog("Satch");
//NamedObject2<int> p(newDog, 2);
//NamedObject2<int> s(oldDog, 36);
//// p = s; // attempt to use deleted function, so compiler delete the copy assignment operator
//// because c++ don't allow change reference, so the copy is meaningless.
//// also for const member
//// and if base class has a inaccessible copy assignment operator, then compiler will not synthesize derived class's copy assignment operator
//B b1, b2;
// b2 = b1; // copy assignment operator is also deleted in class B
// Summary:
// compiler will synthesize: default constructor(if no other constructor), copy constructor, copy assignment, destructor
// default constructor: if you defined any constructor, compiler will not synthesize the default constructor(the empty parameter one)
// destructor: the synthesized destructor is non virtual, but is virtual if it's base class has a virtual destructor
// copy assignment: if data member have reference or const, then will not synthesize copy assignment. reference can't be copied, const can't be changed
// also if the base's copy assignment is inaccessibly, like deleted or private, then will not synthesize copy assignment
return 0;
} | true |
379b8a303f3fb1ac733f004216fa8bf1c9cb865c | C++ | WNawaz/bff_alg | /src/algorithm/AlgUtils.cpp | UTF-8 | 380 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by ale_j on 11/3/2021.
//
#include "AlgUtils.h"
#include <vector>
using namespace std;
vector<vector<int>> AlgUtils::createAdjList(vector<pair<int, int>> &edges, int n) {
vector<vector<int>> adj(n);
for (auto e: edges) {
int i = e.first;
int j = e.second;
adj[i].push_back(j);
adj[j].push_back(i);
}
return adj;
}
| true |
09993a3834b8e92a8a0068babb52724dde997bf8 | C++ | juansdiazo/my-ppp-stroustrup-exercises | /ch11/drill4-table.cpp | UTF-8 | 901 | 2.859375 | 3 | [] | no_license | #include "../std_lib_facilities.h"
int main(){
cout << "TABLE EXAMPLE\n" << left
<< setw(15) << "LAST NAME" << setw(15) << "FIRST NAME" << setw(20) << "TELEPHONE\t" << setw(30) << "EMAIL" << endl
<< setw(15) << "Diaz" << setw(15) << "Juan" << setw(20) << "+49 176 1234 5678" << setw(30) << "diazjuan@gmail.com" << endl
<< setw(15) << "Leguizamon"<< setw(15) << "Carolina" << setw(20) << "+49 176 1234 5679" << setw(30) << "leguizamoncarolina@hotmail.com" << endl
<< setw(15) << "Muller" << setw(15) << "Maximilian" << setw(20) << "+49 176 1234 5670" << setw(30) << "mullermaximilian@yahoo.com" << endl
<< setw(15) << "Stroustrup"<< setw(15) << "Bjarne" << setw(20) << "+49 176 1234 5671" << setw(30) << "stroustrupbjarne@gmx.com" << endl
<< setw(15) << "Rodriguez" << setw(15) << "James" << setw(20) << "+49 176 1234 5672" << setw(30) << "rodriguezjames@gmail.com" << endl;
return 0;
} | true |
1ba665d268563384489e5d2a0ce8d251ef765119 | C++ | JinbaoWeb/ACM | /C++/201504121330.cpp | UTF-8 | 505 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;
struct minion{
int a,h;
}m[2];
int main(){
int t;
cin>>t;
while (t--){
cin>>m[0].a>>m[0].h>>m[1].a>>m[1].h;
if (m[0].a==0)
cout<<"Invalid"<<endl;
else{
if (m[0].h<=m[1].a)
cout<<"Discard";
else
cout<<m[0].a<<" "<<m[0].h-m[1].a;
cout<<" ";
if (m[1].h<=m[0].a)
cout<<"Discard";
else
cout<<m[1].a<<" "<<m[1].h-m[0].a;
cout<<endl;
}
}
return 0;
}
| true |
770f4e7c3c761eb87d1b6a238a7ca9a91ce9b042 | C++ | power10dan/DanGradResearch | /MIRACL_Work/Client_Imp.cpp | UTF-8 | 1,415 | 2.9375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<fstream>
#include <ctime>
#include"PEKS_Test.h"
Storage Read_File(){
Storage store;
// init variables
store.text_file = new string[BUFFER];
store.keyword = new string[BUFFER];
ifstream my_file ("160_words.txt");
if(my_file.is_open()){
// read file
for(int i =0; i < BUFFER; i++){
my_file >> store.text_file[i];
// place each word in file into keyword array
store.keyword[i] = store.text_file[i];
}
} else {
printf("Your file cannot be opened\n");
exit(0);
}
my_file.close();
return store;
}
Storage Client::Encryption(PFC &pfc, Big r, G1 h, G1 g){
// randomization initialization
time_t seed;
time(&seed);
irand((long)seed);
// read in file
Storage store = Read_File();
GT t;
clock_t t_encrypt;
t_encrypt = clock();
for(int i = 0; i < BUFFER; ++i){
pfc.random(r);
// store each keyword into a c style array
string temp = store.keyword[i];
char temp_a[1024];
strncpy(temp_a, temp.c_str(), sizeof(temp_a));
// perform encryption
pfc.hash_and_map(store.HW[i], temp_a);
// generate pairing token t
t = pfc.pairing(store.HW[i], pfc.mult(h,r));
// store ciphertext pair
store.PA[i] = pfc.mult(g,r);
store.PB[i] = pfc.hash_to_aes_key(t);
}
t_encrypt = clock() - t_encrypt;
printf("Time to encrypt %d words: %f\n", BUFFER, (((float)t_encrypt) / CLOCKS_PER_SEC));
return store;
}
| true |
d52e4cbba9f1221c857708aa646895ca26a936b3 | C++ | umutsoysal/cpptraining | /GoogleTest/sample1_unittest.cpp | UTF-8 | 1,157 | 3.078125 | 3 | [] | no_license |
#include <limits.h>
#include "sample1.h"
#include "gtest/gtest.h"
namespace {
// Tests for Factorial Function
// Tests factorials of negative numbers.
TEST(FactorialTest,Negative){
EXPECT_EQ(1,Factorial(-5));
EXPECT_EQ(1,Factorial(-1));
EXPECT_GT(Factorial(-10),0);
}
// Tests factorial of 0
TEST(FactorialTest,Zero){
EXPECT_EQ(0,Factorial(0));
}
// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
}
// Tests IsPrime()
// Tests negative input.
TEST(IsPrimeTest, Negative) {
// This test belongs to the IsPrimeTest test case.
EXPECT_FALSE(IsPrime(-1));
EXPECT_FALSE(IsPrime(-2));
EXPECT_FALSE(IsPrime(INT_MIN));
}
// Tests some trivial cases.
TEST(IsPrimeTest, Trivial) {
EXPECT_FALSE(IsPrime(0));
EXPECT_FALSE(IsPrime(1));
EXPECT_TRUE(IsPrime(2));
EXPECT_TRUE(IsPrime(3));
}
// Tests positive input.
TEST(IsPrimeTest, Positive) {
EXPECT_FALSE(IsPrime(4));
EXPECT_TRUE(IsPrime(5));
EXPECT_FALSE(IsPrime(6));
EXPECT_TRUE(IsPrime(23));
}
} // namespace
| true |
f07bbd3a1d03721636a8b06f0176b1024d6936fd | C++ | syo16/Atcoder-practice | /practice/abc126/c.cpp | UTF-8 | 373 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
double ans = 0;;
for (int i = 1; i <= n; i++) {
double p = 1 / double(n);
int t = 0;
while(i * pow(2, t) < k) {
p *= 0.5;
t++;
}
ans += p;
}
printf("%.12f\n", ans);
}
| true |
188cc65ef7e4cc49fe1693561b9ee6e14892ccd0 | C++ | underscoreanuj/Codes | /Hackerearth/Algorithms/Searching/Binary Search/Counting Triangles.cpp | UTF-8 | 811 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
class MyHash
{
public:
size_t operator()(const array<ll, 3> &o) const
{
return (hash<ll>()(o[0]) ^ hash<ll>()(o[1]) ^ hash<ll>()(o[2]));
}
};
int main()
{
int n = 0, ct = 0;
array<ll, 3> input;
unordered_map<array<ll, 3>, int, MyHash> MEM;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> input[0] >> input[1] >> input[2];
sort(input.begin(), input.end());
++MEM[input];
}
for (auto e : MEM)
{
if (e.second == 1)
++ct;
}
cout << ct;
return 0;
} | true |
21e666bf33bf95a2ab449ab7c2540f6b54d7c31d | C++ | SaadiqDaniels/semi_uniform_iterator | /algorithm_driver.cpp | UTF-8 | 1,375 | 3.765625 | 4 | [] | no_license | /*!
* @file algorithm_driver.cpp
* @author Saadiq Daniels
* @date 2/12/2019
* @version 2.0
*/
#include <iostream>
#include <deque>
#include <algorithm>
#include <random>
#include "iterator.h"
#include "base.h"
/*!
* Tests the uses of the iterator classes with
* standard template library algorithms
* @return 0
*/
int main() {
std::deque<derived1> vector;
for (int i = 0; i < 100; ++i)
{
// Push to the front of the vector
vector.emplace_front(i);
}
// Scramble the vector
// This needs random access iterators, which are not accessible through Iterator<T> classes
std::shuffle(vector.begin(), vector.end(), std::mt19937(std::random_device()()));
// Make iterators for the front and back
Iterator<base> list_front = MakeIterator<base>(vector.begin());
Iterator<base> list_back = MakeIterator<base>(vector.end());
// Print the list using the iterators
std::for_each(list_front, list_back, [](const base &rhs) {
std::cout << rhs;
});
std::cout << std::endl;
// Find the smallest element
auto min = std::min_element(list_front, list_back);
std::cout << *min << std::endl;
// Print again, starting from the smallest element
std::for_each(min, list_back, [](const base &rhs) {
std::cout << dynamic_cast<const derived1&>(rhs);
});
std::cout << std::endl;
return 0;
} | true |
d9f8c45581c1e3bee74ba03ceadb0fc24d6b5122 | C++ | mrNoactiv/DDL_Procesor-new | /Framework/common/memdatstruct/cQueue.h | UTF-8 | 5,424 | 3.34375 | 3 | [] | no_license | #pragma once
#include "common/memdatstruct/cMemoryManager.h"
#include "common/memdatstruct/cMemoryBlock.h"
namespace common {
namespace memdatstruct {
/**
* Implement a queue ADT. This class allocate blocks from memory manager.
* It is capable to easily allocate new blocks if the queue is full.
* Interface is oriented on a regular classes implementing the cBasicType interface, therefore,
* it has char* as an input of enqueue.
*
* Example:
* cMemoryManager* manager = new cMemoryManager();
* cQueue<cUInt>* queue = new cQueue<cUInt>(manager, NULL);
* unsigned int num = 1;
* queue->Enqueue((const char*)&num);
* memcpy(&num, queue->Dequeue(), sizeof(int));
* delete queue;
*
*
* \author Radim Baca
* \version 0.1
* \date jul 2013
**/
struct sQueueNode
{
cMemoryBlock * this_block;
sQueueNode* next;
unsigned int count;
};
template <class T>
class cQueue
{
private:
cMemoryManager *mMemoryManager;
unsigned int mBlockSize_indicator;
unsigned int mBlockCount;
sQueueNode* mHeadQueueBlock;
char* mHeadMem;
unsigned int mHeadPos;
sQueueNode* mTailQueueBlock;
char* mTailMem;
unsigned int mTailPos;
bool mIsEmpty;
unsigned int mMemSize;
cDTDescriptor* mDesc;
unsigned int mCount;
sQueueNode* NewQueueNode();
public:
cQueue(cMemoryManager * mmanager, cDTDescriptor* desc, unsigned int block_size = cMemoryManager::SMALL_SIZE);
~cQueue(void);
void Enqueue(const char* item);
char* Dequeue();
char* FrontItem();
void Clear();
bool IsEmpty();
unsigned int GetCount() { return mCount; }
};
/**
* \param mmanager Memory manager that will be used by this class
* \param desc Descriptor for the T data type, can be NULL
* \param block_size Size of the block
*/
template<class T>
cQueue<T>::cQueue(cMemoryManager * mmanager, cDTDescriptor* desc, unsigned int block_size)
{
mMemoryManager = mmanager;
mMemoryManager = mmanager;
mDesc = desc;
mBlockSize_indicator = block_size;
sQueueNode* block1 = NewQueueNode();
sQueueNode* block2 = NewQueueNode();
if (mBlockSize_indicator == cMemoryManager::SMALL_SIZE)
{
mMemSize = mMemoryManager->GetSize_SMALL();
} else if (mBlockSize_indicator == cMemoryManager::BIG_SIZE)
{
mMemSize = mMemoryManager->GetSize_BIG();
} else if (mBlockSize_indicator == cMemoryManager::SYSTEM_SIZE)
{
mMemSize = mMemoryManager->GetSize_SYSTEM();
}
block1->next = block2;
block2->next = block1;
mHeadQueueBlock = block1;
mHeadMem = mHeadQueueBlock->this_block->GetMem();
mHeadPos = 0;
mTailQueueBlock = block1;
mTailMem = mTailQueueBlock->this_block->GetMem();
mTailPos = 0;
mIsEmpty = true;
mBlockCount = 2;
mCount = 0;
}
/**
* Destructor which release all blocks allocated from memory manager
*/
template<class T>
cQueue<T>::~cQueue()
{
sQueueNode* qnode = mHeadQueueBlock;
for (unsigned int i = 0; i < mBlockCount; i++)
{
mMemoryManager->ReleaseMem(qnode->this_block);
sQueueNode* nnode = qnode->next;
delete qnode;
qnode = nnode;
}
}
/**
* Read a new block from the memory manager
*/
template<class T>
sQueueNode* cQueue<T>::NewQueueNode()
{
sQueueNode* block = new sQueueNode();
block->count = 0;
if (mBlockSize_indicator == cMemoryManager::SMALL_SIZE)
{
block->this_block = mMemoryManager->GetMemSmall();
} else if (mBlockSize_indicator == cMemoryManager::BIG_SIZE)
{
block->this_block = mMemoryManager->GetMemBig();
} else if (mBlockSize_indicator == cMemoryManager::SYSTEM_SIZE)
{
block->this_block = mMemoryManager->GetMemSystem();
}
return block;
}
template<class T>
void cQueue<T>::Enqueue(const char* item)
{
if (T::GetSize(item, mDesc) > mMemSize - mTailPos)
{
if (mTailQueueBlock->next->count > 0)
{
// we need to allocate new blocks
sQueueNode* block = NewQueueNode();
sQueueNode* next = mTailQueueBlock->next;
mTailQueueBlock->next = block;
block->next = next;
mBlockCount++;
}
// switch tail to a new block
mTailQueueBlock = mTailQueueBlock->next;
mTailMem = mTailQueueBlock->this_block->GetMem();
T::Copy(mTailMem, item, mDesc);
mTailPos = T::GetSize(item, mDesc);
mTailQueueBlock->count = 1;
if (mIsEmpty)
{
mHeadQueueBlock = mTailQueueBlock;
mHeadMem = mHeadQueueBlock->this_block->GetMem();
mHeadPos = 0;
}
mIsEmpty = false;
} else
{
// if there is enough space
T::Copy(mTailMem + mTailPos, item, mDesc);
mTailPos += T::GetSize(item, mDesc);
mTailQueueBlock->count++;
mIsEmpty = false;
}
mCount++;
}
template<class T>
char* cQueue<T>::Dequeue()
{
char* mem = mHeadMem + mHeadPos;
assert(mHeadQueueBlock->count > 0 && !mIsEmpty);
mHeadQueueBlock->count--;
mHeadPos += T::GetSize(mem, mDesc);
if (mHeadQueueBlock->count == 0)
{
if (mHeadQueueBlock == mTailQueueBlock)
{
mIsEmpty = true;
} else
{
// we need to switch to another block
mHeadQueueBlock = mHeadQueueBlock->next;
mHeadMem = mHeadQueueBlock->this_block->GetMem();
mHeadPos = 0;
}
}
mCount--;
return mem;
}
template<class T>
char* cQueue<T>::FrontItem()
{
assert(mHeadQueueBlock->count > 0 && !mIsEmpty);
return mHeadMem + mHeadPos;
}
/**
* \return true if the queue is empty
*/
template<class T>
bool cQueue<T>::IsEmpty()
{
return mIsEmpty;
}
/**
* Set the queue as an empty
*/
template<class T>
void cQueue<T>::Clear()
{
mHeadPos = 0;
mHeadQueueBlock->count = 0;
mTailQueueBlock = mHeadQueueBlock;
mTailMem = mTailQueueBlock->this_block->GetMem();
mTailPos = 0;
mIsEmpty = true;
mCount = 0;
}
}}
| true |
ddcc960045fbc8bf0268055d1c7d3625da9e521a | C++ | prantostic/HackerEarth | /CodeMonk/Basics of Programming/Basics of Input Output/Database.cpp | UTF-8 | 1,951 | 2.890625 | 3 | [] | no_license | #include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
inline bool isInteger(const std::string &s) {
if (s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+')))
return false;
char *p;
strtol(s.c_str(), &p, 10);
return (*p == 0);
}
int main(int argc, char const *argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
size_t test;
size_t attributes, tuples;
cin >> test;
while (test--) {
cin >> attributes >> tuples;
tuples++;
size_t max_size[attributes];
string database[tuples][attributes];
string type[attributes];
for (size_t i = 0; i < attributes; i++)
max_size[i] = numeric_limits<size_t>::min();
for (size_t i = 0; i < tuples; i++) {
for (size_t j = 0; j < attributes; j++) {
cin >> database[i][j];
max_size[j] = max(max_size[j], database[i][j].length());
}
}
for (size_t i = 0; i < attributes; i++) {
if (!database[tuples - 1][i].compare("true") or
!database[tuples - 1][i].compare("false")) {
type[i] = "bool";
} else if (isInteger(database[tuples - 1][i])) {
type[i] = "int";
} else if (database[tuples - 1][i].find('/') != string::npos) {
type[i] = "date";
} else {
type[i] = "string";
}
}
for (size_t i = 0; i < tuples; i++) {
if (i == 0) {
for (size_t j = 0; j < attributes; j++) {
cout << "+" << setw(max_size[j] + 2) << setfill('-') << "";
}
cout << "+\n";
}
for (size_t j = 0; j < attributes; j++) {
if (type[j] == "int" and i != 0) {
cout << "|" << setw(max_size[j] + 1) << setfill(' ')
<< right << database[i][j] << " ";
} else {
cout << "| " << setw(max_size[j] + 1) << setfill(' ')
<< left << database[i][j];
}
}
cout << "|" << endl;
if (i == 0 or i == tuples - 1) {
for (size_t j = 0; j < attributes; j++) {
cout << "+" << setw(max_size[j] + 2) << setfill('-') << "";
}
cout << "+\n";
}
}
}
return 0;
}
| true |
f798d8e93f57d6f4c62f48731f0b46b56ec42675 | C++ | Moon-GD/c-data-structure-self-taught | /SketchBook/04. 스택 실습 (InStack).cpp | UHC | 1,103 | 3.5 | 4 | [] | no_license | #include<stdio.h>
#include "IntStack.h"
int main() {
IntStack stack;
if (Initialize(&stack, 64) == -1) {
printf(" Ͽϴ.");
return 1;
}
while (1) {
int ans, x = 0;
printf(" : %d/%d\n", Size(&stack), Capacity(&stack));
printf("(1) Ǫ (2) (3) ũ (4) (0) : ");
scanf_s("%d", &ans);
if (ans == 0) { break; }
switch (ans) {
case 1 :
printf("Ǫ : ");
scanf_s("%d", &ans);
if (Push(&stack, ans) == -1) {
printf("Ǫÿ Ͽϴ.\n");
}
break;
case 2:
if (Pop(&stack, &x) == -1) {
printf("˿ Ͽϴ.\n");
}
else {
printf(" ʹ %dԴϴ.\n", x);
}
break;
case 3:
if (Peek(&stack, &x) == -1) {
printf("ũ Ͽϴ.\n");
}
else {
printf("ũ ʹ %d Դϴ.\n", x);
}
break;
case 4:
Print(&stack);
break;
default:
printf("ٽ Էּ.\n");
}
}
Terminate(&stack);
return 0;
} | true |
2bb6bb0ca3dc202f813dada5a70328d4dc5c0f0a | C++ | michaelarakel/timus-solutions | /1295.cpp | UTF-8 | 514 | 3.09375 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
using namespace std;
const int base = 100000;
int binpow(int a, int n)
{
int res = 1;
while (n)
{
if (n & 1)
{
res = (res * 1ll * a) % base;
}
a = (a * 1ll * a) % base;
n >>= 1;
}
return res;
}
int main()
{
int n;
cin >> n;
int temp = (1 + binpow(2, n) + binpow(3, n) + binpow(4, n)) % base;
if (temp == 0)
{
cout << 5;
return 0;
}
int counter = 0;
while (temp % 10 == 0)
{
++counter;
temp /= 10;
}
cout << counter;
} | true |
428cc3fc12de543b1081b6d89a8dd87fdc2bd064 | C++ | AkshayMariyanna/solutions | /spoj/pon.cpp | UTF-8 | 1,089 | 3.265625 | 3 | [] | no_license | //! https://www.spoj.com/problems/PON/
/// PON with cp-algo reference
#include <iostream>
using namespace std;
typedef unsigned __int128 uint128;
typedef unsigned long long ll;
ll binpower(ll x, ll n, ll mod) {
ll ans = 1;
x %= mod;
while (n) {
if (n & 1)
ans = ((uint128) ans * x) % mod;
x = ((uint128) x * x) % mod;
n >>= 1;
}
return ans;
}
bool check_composite(ll n, ll a, ll d, ll s) {
ll x = binpower(a, d, n);
if (x == 1 || x == n - 1)
return false;
for (ll r = 1; r < s; r++) {
x = ((uint128)x * x) % n;
if (x == n - 1)
return false;
}
return true;
}
bool isPrime(ll n) {
if (n < 2)
return false;
int r = 0;
ll d = n - 1;
while ((d & 1) == 0) {
d >>= 1;
r++;
}
for(ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
if (n == a)
return true;
if (check_composite(n, a, d, r))
return false;
}
return true;
}
int main() {
int T;
cin >> T;
while (T--) {
ll N;
cin >> N;
if (isPrime(N))
cout << "YES\n";
else
cout << "NO\n";
}
}
| true |
7ae331aa15eb1e3d15ccacfa452aa6caa087411a | C++ | barawn/aspspower-v1 | /uart_base.h | UTF-8 | 5,429 | 2.875 | 3 | [] | no_license | /*
* uart_base.h
*
* This follows the CRTP-type implementation of the PDQ graphics
* library ( https://github.com/XarkLabs/PDQ_GFX_Libs ) and creates a UART base class, for use
* with the lwevent framework.
*
* Peripheral base classes basically follow the same methodology here:
* 1) Templated base class for overall functionality: UART base, I2C master base, I2C slave base, etc.
* 2) Templated implementation class for implementation-specific functions.
* 3) Configuration class which contains linkages (const pointers) to static elements, as well as instantiation-specific
* details.
*
* The reason for the last step is complicated. The C++ compiler is smart enough to recognize that
* when you define a const pointer, it can just go ahead and replace that with the symbol for the
* object it pointed to (since, well, that's what it is anyway). But the assembler's cdecls parser
* is not smart enough to do that: it just skips the const pointer initialization, and then it wonders
* why the linker hasn't created a symbol for that object.
*
* Plus, the cdecls parser is just not that useful for C++. Sure, it creates globals for you, but does it
* with mangled C++ names. So you have to find the mangled names, and then reimport them in. THIS IS NOT USEFUL.
*
* Created on: Jun 26, 2015
* Author: barawn
*/
#ifndef UART_BASE_H_
#define UART_BASE_H_
#include <stdint.h>
#include "lwevent.h"
//% \brief Collection of buffer pointers.
//%
//% Buffers themselves are not here, because their storage size is unknown.
typedef struct uart_base_pointers {
uint8_t rx_rd;
uint8_t rx_wr;
uint8_t tx_rd;
uint8_t tx_wr;
} uart_base_pointers;
template<class T, class CONFIG>
class uart_base {
public:
uart_base() {}
void init() {
*tx_rd_ptr = 0;
*tx_wr_ptr = 0;
*rx_rd_ptr = 0;
*rx_wr_ptr = 0;
T::init_impl();
}
void control(bool enable) {
T::control_impl(enable);
}
// Dump all read bytes.
void dump() {
*rx_rd_ptr = *rx_wr_ptr;
}
// Get number of bytes available to read.
uint8_t rx_available() {
return (*rx_wr_ptr - *rx_rd_ptr) % RX_BUF_SIZE;
}
// Get number of bytes available to transmit.
uint8_t tx_available() {
return (*tx_rd_ptr - *tx_wr_ptr - 1) % TX_BUF_SIZE;
}
//% \brief Receive a character. Don't call unless you know one is available! (via rx_available)
//%
//% The tmpptr bit here is to defeat poor TI optimization: since rx_rd_ptr is declared volatile,
//% it assigns a register to tmpptr (which it had to do *anyway*, which is why the optimization is poor)
//% and then uses that register throughout the whole calculation.
//%
//% With 'volatile' missing and/or tmpptr not used, the C compiler fetches rx_rd_ptr *again*, rather
//% than using the local copy. The volatile declaration prevents that, since it could have changed.
uint8_t rx() {
uint8_t tmp, tmpptr;
tmpptr = *rx_rd_ptr;
tmp = rx_buffer[tmpptr++];
tmpptr = tmpptr % T::RX_BUF_SIZE;
*rx_rd_ptr = tmpptr;
return tmp;
}
//% Transmit a character. Note there is no overflow protection (so use tx_available if this is a worry)
//% The tmp bit here is to defeat poor TI optimization: since tx_wr_ptr is declared volatile,
//% it assigns a register to tmp (which it had to do *anyway*, which is why the optimization is poor)
//% and then uses that register throughout the whole calculation.
//%
//% With 'volatile' missing and/or tmp not used, the C compiler fetches tx_wr_ptr *again*, rather
//% than using the local copy. The volatile declaration prevents that, since it could have changed.
void tx(uint8_t txc) {
uint8_t tmp;
tmp = *tx_wr_ptr;
tx_buffer[tmp++] = txc;
tmp = tmp % TX_BUF_SIZE;
*tx_wr_ptr = tmp;
}
//% Transmit a character, but this is a virtual function. This is for use with the
//% xprintf function (pulled in through the lwprintf class).
virtual void write(uint8_t txc);
//% Sleep check. This is called before sleeping for each module. Modules cannot interact with each other here.
bool sleep_check() {
return T::sleep_check_impl();
}
//% Add a lwevent to post when the TX fifo empties.
void post_when_tx_empty(lwevent *p) {
tx_empty_store->store(p);
}
static volatile uint8_t *const get_tx_rd_ptr() { return tx_rd_ptr; }
static volatile uint8_t *const get_tx_wr_ptr() { return tx_wr_ptr; }
static volatile uint8_t *const get_rx_rd_ptr() { return rx_rd_ptr; }
static volatile uint8_t *const get_rx_wr_ptr() { return rx_wr_ptr; }
static uint8_t *const get_rx_buffer() { return rx_buffer; }
static uint8_t *const get_tx_buffer() { return tx_buffer; }
uint8_t const RX_BUF_SIZE = CONFIG::RX_BUF_SIZE;
uint8_t const TX_BUF_SIZE = CONFIG::TX_BUF_SIZE;
volatile uint8_t *const tx_wr_ptr = CONFIG::tx_wr_ptr;
volatile uint8_t *const tx_rd_ptr = CONFIG::tx_rd_ptr;
volatile uint8_t *const rx_wr_ptr = CONFIG::rx_wr_ptr;
volatile uint8_t *const rx_rd_ptr = CONFIG::rx_rd_ptr;
uint8_t *const rx_buffer = CONFIG::rx_buffer;
uint8_t *const tx_buffer = CONFIG::tx_buffer;
lwevent *const tx_empty_event = CONFIG::tx_empty_event;
lwevent *const rx_data_event = CONFIG::rx_data_event;
lwevent_store_fifo *const tx_empty_store = CONFIG::tx_empty_store;
};
template<class T, class CONFIG>
void uart_base<T,CONFIG>::write(uint8_t txc) {
tx(txc);
}
#endif /* UART_BASE_H_ */
| true |
4541ca1ad2b2d5af11ff00eed7641ec70e69374b | C++ | mingweili/aworldinchaos | /寒假最新成果/frame/Coffin.cpp | GB18030 | 1,627 | 2.671875 | 3 | [] | no_license | #include "Coffin.h"
Coffin :: Coffin(float _x, float _y)
{
x = _x;
y = _y;
height = COFFIN_HEIGHT;
width = COFFIN_WIDTH;
DoohickeyState = INACTIVE;
sprite = ResourceManager :: getSpritePtr("Coffin");
sprite -> SetZ(0.8f);
LastIn = false;
LastTime = 0;
}
void Coffin :: ToMapCal(DoohSpecies* map)
{
for(int i = (int) (x - width / 2); i < (int) (x + width / 2); ++i)
for(int j = (int) (y - height / 2); j < (int) (y + height / 2); ++j)
map[i + MAPPOINTQUANTITY_X * j] = COFFIN;
}
GameState Coffin :: logic(Player* player, DoohSpecies* map)
{
//жСǷڳӵĹΧ֮
float player_x = player->getX();
float player_y = player->getY();
if( player_x >= (this->x - WORM_WIDTH / 2) && player_x <= (this->x + WORM_WIDTH / 2) &&
player_y >= (this->y - WORM_HEIGHT / 2) && player_y <= (this->y + WORM_HEIGHT / 2) &&
DoohickeyState == INACTIVE )
{
//ڳӹΧ֮,ۼʱ
if(LastIn)
++LastTime;
else
LastTime = 0;
LastIn = true;
//ڳӹΧ֮3
if(LastTime >= 3.0)
return DEAD;
}
else
LastIn = false;
//жɱǷЧ
_Pesticide* p = ( _Pesticide* )( Account :: getAccount()->getProperty(_PESTICIDE) );
if( p != NULL && p->KilledWorm())
{
//ʹӵȾϵͳʧЧ
DoohickeyState = ACTIVE;
}
//Ѿ
if(DoohickeyState == ACTIVE && map[(int)(player_x + MAPPOINTQUANTITY_X * player_y)] == COFFIN)
{
//õʲôͨ
return SUCCESS;
}
return GOON;
}
void Coffin :: render()
{
sprite -> Render(x, y += dy);
} | true |
83e7ab63929acdeda0d499f644a2c9396d02ad5e | C++ | rajeshceg3/leetcode_cpp | /Sort List.cpp | UTF-8 | 697 | 3.28125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head) return nullptr;
vector<int> nums;
while(head)
{
nums.emplace_back(head->val);
head = head->next;
}
std::sort(begin(nums),end(nums));
ListNode* first = new ListNode(nums[0]);
ListNode* result = first;
for( int index = 1; index < nums.size();index++)
{
ListNode* tmp = new ListNode(nums[index]);
first->next = tmp;
first = first->next;
}
return result;
}
};
| true |
f84928a3d24f82a01e87e0f3ccaa8e48b4143300 | C++ | zjin-lcf/HeCBench | /sobel-hip/reference.cu | UTF-8 | 2,725 | 3.203125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "sobel.h"
inline uchar clamp (float f) {
if (f < 0.f) return 0;
if (f > 255.f) return 255;
return (uchar)f;
}
// convolution at the anchor point (c) using a 3x3 kernel(k)
// on an image pointed by ptr. The image width is "width"
void conv(float4 &g, const int k[][3], const uchar4 *ptr, const int c, const int width) {
g.x =
k[0][0] * ptr[c-1-width].x + k[0][1] * ptr[c-width].x + k[0][2] * ptr[c+1-width].x +
k[1][0] * ptr[c-1].x + k[1][1] * ptr[c].x + k[1][2] * ptr[c+1].x +
k[2][0] * ptr[c-1+width].x + k[2][1] * ptr[c+width].x + k[2][2] * ptr[c+1+width].x;
g.y =
k[0][0] * ptr[c-1-width].y + k[0][1] * ptr[c-width].y + k[0][2] * ptr[c+1-width].y +
k[1][0] * ptr[c-1].y + k[1][1] * ptr[c].y + k[1][2] * ptr[c+1].y +
k[2][0] * ptr[c-1+width].y + k[2][1] * ptr[c+width].y + k[2][2] * ptr[c+1+width].y;
g.z =
k[0][0] * ptr[c-1-width].z + k[0][1] * ptr[c-width].z + k[0][2] * ptr[c+1-width].z +
k[1][0] * ptr[c-1].z + k[1][1] * ptr[c].z + k[1][2] * ptr[c+1].z +
k[2][0] * ptr[c-1+width].z + k[2][1] * ptr[c+width].z + k[2][2] * ptr[c+1+width].z;
g.w =
k[0][0] * ptr[c-1-width].w + k[0][1] * ptr[c-width].w + k[0][2] * ptr[c+1-width].w +
k[1][0] * ptr[c-1].w + k[1][1] * ptr[c].w + k[1][2] * ptr[c+1].w +
k[2][0] * ptr[c-1+width].w + k[2][1] * ptr[c+width].w + k[2][2] * ptr[c+1+width].w;
}
// gradient magnitude
void magnitude(uchar4 &result, float4 &gx, float4 &gy) {
result.x = clamp(sqrtf(powf(gx.x, 2.f) + powf(gy.x, 2.f)) / 2.f);
result.y = clamp(sqrtf(powf(gx.y, 2.f) + powf(gy.y, 2.f)) / 2.f);
result.z = clamp(sqrtf(powf(gx.z, 2.f) + powf(gy.z, 2.f)) / 2.f);
result.w = clamp(sqrtf(powf(gx.w, 2.f) + powf(gy.w, 2.f)) / 2.f);
}
void reference (uchar4 *verificationOutput,
const uchar4 *inputImageData,
const uint width,
const uint height,
const int pixelSize)
{
// x-axis gradient mask
const int kx[][3] =
{
{ 1, 0, -1},
{ 2, 0, -2},
{ 1, 0, -1}
};
// y-axis gradient mask
const int ky[][3] =
{
{ 1, 2, 1},
{ 0, 0, 0},
{ -1,-2,-1}
};
// apply filter on each pixel (except boundary pixels)
for (uint y = 0; y < height; y++)
for (uint x = 0; x < width; x++) {
if( x >= 1 && x < (width-1) && y >= 1 && y < height - 1) {
int c = x + y * width;
float4 gx, gy;
conv(gx, kx, inputImageData, c, width);
conv(gy, ky, inputImageData, c, width);
uchar4 result;
magnitude(result, gx, gy);
*(verificationOutput + c) = result;
}
}
}
| true |
b61ca863923fef8c06643142a065904fe60efe1c | C++ | DannyDaiSun/OpenGL | /src/IndexBuffer.h | UTF-8 | 261 | 2.6875 | 3 | [] | no_license | #pragma once
#include "GL/glew.h"
class IndexBuffer{
private:
GLuint m_bufferID=0;
GLint m_count;
public:
IndexBuffer(const GLuint *data, GLint count);
~IndexBuffer();
void Bind()const;
void Unbind()const;
GLint Count() const {
return m_count;
}
};
| true |
accb33181ff39c0917c56c3f64c5f93eb1546f62 | C++ | lesenelir/Learning-Algorithm-Notes | /机试指南/08-动态规划/09-最大上升子序列和.cpp | UTF-8 | 783 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
/*
最大上升子序列和(北京大学)P232
备注:
相对于最长不下降子序列的不同点在于:
dp[i]代表的是以A[i]为结尾的
*/
const int maxn = 1010;
int A[maxn];
int dp[maxn];
int main(int argc, char *argv[]) {
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
// 边界
for (int i = 0; i < n; i++) {
dp[i] = A[i];
}
// 状态转移方程
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (A[j] < A[i] && dp[j] + A[i] > dp[i]) {
dp[i] = dp[j] + A[i];
}
}
}
// 找最大值
int k = 0;
for (int i = 1; i < n; i++) {
if (dp[i] > dp[k]) {
k = i;
}
}
printf("%d\n", dp[k]);
}
} | true |
6b20d7bbfb342c317a5ee2e8111ca6bc7eba4c7e | C++ | PaoloPellizzoni/MuonGenerator | /src/geometry.h | UTF-8 | 2,959 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef GEOM_H_
#define GEOM_H_
#include <bits/stdc++.h>
struct Vec3D{
double x, y, z;
Vec3D(){
}
Vec3D(double _x, double _y, double _z){
x = _x;
y = _y;
z = _z;
}
Vec3D operator + (const Vec3D &o){
return Vec3D(x + o.x, y + o.y, z + o.z);
}
Vec3D operator - (const Vec3D &o){
return Vec3D(x - o.x, y - o.y, z - o.z);
}
Vec3D operator * (const double k){
return Vec3D(x * k, y * k, z * k);
}
Vec3D cross(const Vec3D &o){
return Vec3D( y*o.z- z*o.y, z*o.x- x*o.z, x*o.y- y*o.x);
}
double dot(const Vec3D &o){
return x*o.x + y*o.y + z*o.z;
}
double norm2(){
return x*x + y*y + z*z;
}
Vec3D normalize(){
return (*this) * (1/sqrt(this->norm2()));
}
std::string str(){
return "("+std::to_string(x)+" "+std::to_string(y)+" "+std::to_string(z)+")";
}
};
struct Line{
Vec3D point, dir;
Line(){}
Line(Vec3D _p, Vec3D _d){
point = _p;
dir = _d;
}
Line(std::vector<double> theta){
point = Vec3D(theta[0], theta[1], 0);
dir = Vec3D(theta[2], theta[3], 1);
}
Vec3D line_quasi_intersection(Line o){
Vec3D u = dir.normalize();
Vec3D v = o.dir.normalize();
Vec3D w = o.point - point;
double a = u.dot(u);
double b = u.dot(v);
double c = v.dot(v);
double d = u.dot(w);
double e = v.dot(w);
double D = a*c - b*b;
if(D < 1e-20) // parallel lines
return point;
double sc = (b*e - c*d)/D;
double tc = (a*e - b*d)/D;
Vec3D s = point - u * sc;
Vec3D t = o.point - v * tc;
Vec3D mid = (s + t) * 0.5;
//std::cout << s.str() << " " << t.str() << " " <<mid.str() << " " << std::endl;
return mid;
}
std::string str(){
return "["+point.str()+" + k*" + dir.str()+"]";
}
};
struct Plane{
double z, height, width;
Plane(double _z){
z = _z;
height = 0;
width = 0;
}
Plane(double _z, double _h, double _w){
z = _z;
height = _h;
width = _w;
}
Vec3D line_intersection(Line &l){
double d = (z - l.point.z)/(l.dir.z);
double x = l.point.x + l.dir.x*d;
double y = l.point.y + l.dir.y*d;
return Vec3D(x,y,z);
}
};
struct Plane3D{
Vec3D point, normal;
double height, width;
Plane3D(Vec3D _p, Vec3D _n){
point = _p;
normal = _n.normalize();
}
Plane3D(Vec3D _p, Vec3D _n, double _h, double _w){
point = _p;
normal = _n.normalize();
height = _h;
width = _w;
}
Vec3D line_intersection(Line &l){
double d = ((point - l.point).dot(normal))/(l.dir.dot(normal));
double x = l.point.x + l.dir.x*d;
double y = l.point.y + l.dir.y*d;
double z = l.point.z + l.dir.z*d;
return Vec3D(x,y,z);
}
};
#endif
| true |
e4cedb38d3e81288b38742e3ea9881fb9ee51d8e | C++ | cgmi/lindelib | /src/VertexBufferObject.cpp | UTF-8 | 5,132 | 2.546875 | 3 | [] | no_license | #include "../include/linde/VertexBufferObject.h"
namespace linde
{
/*
#################################################################################
#################################################################################
#################################################################################
################### VBO #########################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
*/
VertexBufferObject::VertexBufferObject(GLContext *glContext) :
GLObject(glContext),
m_nrVertices(0),
m_nrDynamicVertices(0),
m_nrIndices(0),
m_nrDynamicIndices(0),
m_sizeBytesVertices(0),
m_sizeBytesIndices(0),
m_bufferId(0),
m_indexBufferId(0),
m_primitiveMode(GL_POINTS),
m_usage(GL_STATIC_DRAW),
m_sizeAsStride(0),
m_useIndexBuffer(GL_FALSE),
m_attribLocations(),
m_dynamicRendering(GL_FALSE)
{
}
GLuint VertexBufferObject::createVBO(GLenum target, GLuint dataSize, const void* data, GLenum usage)
{
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(target, vbo);
glBufferData(target, dataSize, data, usage);
glBindBuffer(target, 0);
return vbo;
}
VertexBufferObject::~VertexBufferObject()
{
if (m_bufferId != GL_INVALID_VALUE)
glDeleteBuffers(1, &m_bufferId);
if (m_indexBufferId != GL_INVALID_VALUE)
glDeleteBuffers(1, &m_indexBufferId);
}
void VertexBufferObject::bindAttribs()
{
GLint size = (GLint)m_attribLocations.size();
glBindBuffer(GL_ARRAY_BUFFER, m_bufferId);
for (int i = 0; i<size; ++i)
{
GLint attribLoc = m_attribLocations[i];
glVertexAttribPointer(attribLoc, 4, GL_FLOAT, GL_FALSE, sizeof(DATA), ((GLchar*)NULL + 4 * sizeof(float)* i));
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBufferObject::render()
{
GLint size = (GLint)m_attribLocations.size();
glBindBuffer(GL_ARRAY_BUFFER, m_bufferId);
for (int i = 0; i<size; ++i)
{
GLint attribLoc = m_attribLocations[i];
glVertexAttribPointer(attribLoc, 4, GL_FLOAT, GL_FALSE, sizeof(DATA), ((GLchar*)NULL + 4 * sizeof(float)* i));
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
for (int i = 0; i<size; ++i)
glEnableVertexAttribArray(m_attribLocations[i]);
if (m_useIndexBuffer)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferId);
if (m_dynamicRendering)
{
glDrawElements(m_primitiveMode, m_nrDynamicIndices, GL_UNSIGNED_INT, 0);
}
else
{
glDrawElements(m_primitiveMode, m_nrIndices, GL_UNSIGNED_INT, 0);
}
}
else
{
if (m_dynamicRendering)
{
glDrawArrays(m_primitiveMode, 0, m_nrDynamicVertices);
}
else
{
glDrawArrays(m_primitiveMode, 0, m_nrVertices);
}
}
for (int i = 0; i<size; ++i)
glDisableVertexAttribArray(m_attribLocations[i]);
}
void VertexBufferObject::setData(const DATA *data, GLenum usage, GLuint nrVertices, GLenum primitiveMode)
{
m_sizeAsStride = sizeof(DATA);
m_sizeBytesVertices = m_sizeAsStride * nrVertices;
m_primitiveMode = primitiveMode;
m_usage = usage;
m_nrVertices = nrVertices;
m_nrDynamicVertices = nrVertices;
m_bufferId = createVBO(GL_ARRAY_BUFFER, m_sizeBytesVertices, data, usage);
}
void VertexBufferObject::updateData(const DATA *data, GLenum usage, GLuint nrVertices, GLenum primitiveMode)
{
m_sizeAsStride = sizeof(DATA);
m_sizeBytesVertices = m_sizeAsStride * nrVertices;
m_primitiveMode = primitiveMode;
m_usage = usage;
m_nrVertices = nrVertices;
m_nrDynamicVertices = nrVertices;
bind();
glBufferData(GL_ARRAY_BUFFER, m_sizeBytesVertices, data, usage);
release();
}
void VertexBufferObject::addAttrib(GLint attribLoc)
{
m_attribLocations.push_back(attribLoc);
}
void VertexBufferObject::setIndexData(const GLvoid *data, GLenum usage, GLint nrIndices)
{
m_nrIndices = nrIndices;
m_useIndexBuffer = GL_TRUE;
m_sizeBytesIndices = sizeof(uint)* nrIndices;
m_indexBufferId = createVBO(GL_ELEMENT_ARRAY_BUFFER, m_sizeBytesIndices, data, usage);
}
void VertexBufferObject::setVerticesToRender(GLuint nrVertices)
{
m_nrDynamicVertices = nrVertices;
}
void VertexBufferObject::bind()
{
glBindBuffer(GL_ARRAY_BUFFER, m_bufferId);
}
void VertexBufferObject::release()
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBufferObject::setDynamicRendering(GLboolean dynamicRendering)
{
m_dynamicRendering = dynamicRendering;
}
GLuint VertexBufferObject::nrVertices() const
{
return m_nrVertices;
}
GLuint VertexBufferObject::nrDynamicVertices() const
{
return m_nrDynamicVertices;
}
} // namespace linde
| true |
96e1cb1e4680082e45c04ded4e5837c34c72416a | C++ | vhawk19/World_Map_Of_CPP_STL_Algos | /rotate.cpp | UTF-8 | 446 | 3.34375 | 3 | [] | no_license |
#include<iostream>
#include <algorithm>
#include <vector>
int main(){
int n,temp,number_to_be_rotated;
bool truth=true;
std::cin>>n;
std::vector<int> a(n);
for(auto& i:a){
std::cin>>temp;
i=temp;
}
std::cout<<"\nYou want to rotate this by?:";
std::cin>>number_to_be_rotated;
std::rotate(a.begin(),a.begin()+number_to_be_rotated,a.end());
for(auto& i:a){
std::cout<<i<<" ";
}
}
| true |
7d85473fa5268fd924f3a3b7fc95ff69d402a371 | C++ | Hamburger666/HKOI | /MP/swap.cpp | UTF-8 | 497 | 3.234375 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int s = 10;
int a[s];
void add() {
for (int i = 0; i < s; i++) {
a[i] = i + 1;
}
}
void swap(int x, int y) {
int t;
t = a[x];
a[x] = a[y];
a[y] = t;
}
void printA() {
for (int i = 0; i < s; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void f(int k) {
int i = 0;
while (i < k / 2) {
swap(i, k - i - 1);
i++;
}
}
int main() {
add();
f(4);
printA();
}
| true |
41c349a2bbc4c77e1c7102072e8aed84406ee7a4 | C++ | SimulationEverywhere-Models/Cell-DEVS-COVID19-SIRS | /var_generators/vargen.cpp | UTF-8 | 2,027 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
string cellIndexString(int x, int y);
int main(){
ofstream outputFile;
int x_dim = 50;
int y_dim = 50;
// define cell values to be written
string initDefaultBorder = " = 10 1 0.6 0.07 22 6 1 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.17 0.17 0.17 0.17 0.17 0.17 0.17 0.17 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01";
string infectedCell = " = 100 1 0.6 0.07 22 6 0.7 0.3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.17 0.17 0.17 0.17 0.17 0.17 0.17 0.17 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01";
outputFile.open ("var_gen_output.var");
// draw a border around the entire cell space with lower mobility and connectivity
for(int k = 0; k < x_dim; k++){
outputFile << cellIndexString(k,0) + initDefaultBorder << endl;
}
for(int k = 1; k < y_dim-1; k++){
outputFile << cellIndexString(x_dim-1,k) + initDefaultBorder << endl;
}
for(int k = 0; k < x_dim; k++){
outputFile << cellIndexString(k,y_dim-1) + initDefaultBorder << endl;
}
for(int k = 1; k < y_dim-1; k++){
outputFile << cellIndexString(0,k) + initDefaultBorder << endl;
}
// draw a border diving the cell space into two
for(int k = 1; k < x_dim-1; k++){
outputFile << cellIndexString(k,24) + initDefaultBorder << endl;
}
for(int k = 1; k < x_dim-1; k++){
outputFile << cellIndexString(k,25) + initDefaultBorder << endl;
}
// insert infected cells where desired
outputFile << cellIndexString(25,26) + infectedCell << endl;
outputFile.close();
return 0;
}
// create a string of a cell's index given its coordinates x y = "(x,y)"
string cellIndexString(int x, int y){
string s = "(";
string sx = to_string(x);
string sy = to_string(y);
s.append(sx);
s.append(",");
s.append(sy);
s.append(")");
return s;
}
| true |
405ad446b1c083ac4d48cebd5035508f1ab3deb5 | C++ | LineageOS/android_bootable_recovery | /applypatch/utils.cpp | UTF-8 | 2,222 | 2.578125 | 3 | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "utils.h"
/** Write a 4-byte value to f in little-endian order. */
void Write4(int value, FILE* f) {
fputc(value & 0xff, f);
fputc((value >> 8) & 0xff, f);
fputc((value >> 16) & 0xff, f);
fputc((value >> 24) & 0xff, f);
}
/** Write an 8-byte value to f in little-endian order. */
void Write8(long long value, FILE* f) {
fputc(value & 0xff, f);
fputc((value >> 8) & 0xff, f);
fputc((value >> 16) & 0xff, f);
fputc((value >> 24) & 0xff, f);
fputc((value >> 32) & 0xff, f);
fputc((value >> 40) & 0xff, f);
fputc((value >> 48) & 0xff, f);
fputc((value >> 56) & 0xff, f);
}
int Read2(void* pv) {
unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[1] << 8) |
(unsigned int)p[0]);
}
int Read4(void* pv) {
unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[3] << 24) |
((unsigned int)p[2] << 16) |
((unsigned int)p[1] << 8) |
(unsigned int)p[0]);
}
long long Read8(void* pv) {
unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (long long)(((unsigned long long)p[7] << 56) |
((unsigned long long)p[6] << 48) |
((unsigned long long)p[5] << 40) |
((unsigned long long)p[4] << 32) |
((unsigned long long)p[3] << 24) |
((unsigned long long)p[2] << 16) |
((unsigned long long)p[1] << 8) |
(unsigned long long)p[0]);
}
| true |
129bc153194b1851704c885ed4e2d5a4928d682c | C++ | Rodrigosilvacarvalho/Arduino | /Libraries/Json_Streaming_Parser_2/examples/HTTPS_StreamParser_Weather/WeatherForecastHandler.h | UTF-8 | 5,227 | 2.859375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "JsonHandler.h"
#include <map>
#include <forward_list>
#include <string>
#include <stdexcept>
#include <TimeLib.h>
char fullPath[200] = "";
char valueBuffer[50] = "";
/*
* This structure is used within the WeatherForecastHandler implementation.
* It stores the values from the JSON we care about. Everything else
* is discarded.
*/
struct Forecast
{
time_t datetime;
int temp;
int humidity;
char summary[16];
};
// Example: LIST - Store a list of all forecasts
std::forward_list<Forecast> myForecasts;
std::forward_list<Forecast>::iterator myForecasts_it;
// Example: MAP - Store a map of stuff we only care about that the parser sees.
std::map<std::string, float>mymap = {
{ "list[0].dt", 0},
{ "list[0].main.temp", 0},
{ "list[0].main.temp_min", 0},
{ "list[0].main.temp_max", 0}
};
std::map<std::string, float>::iterator it;
// Virtual Handler class implementation
class WeatherForecastHandler: public JsonHandler
{
/* Open weather maps returns something like:
*
cod': "200"
message': 0.003200
cnt': 36
list[0].dt': 1487246336
list[0].main.temp': 286.670013
list[0].main.temp_min': 281.556000
list[0].main.temp_max': 286.670013
list[0].main.pressure': 972.729980
list[0].main.sea_level': 1046.459961
list[0].main.grnd_level': 972.729980
list[0].main.humidity': 75
list[0].main.temp_kf': 5.110000
list[0].weather[0].id': 800
list[0].weather[0].main': "Clear"
start Object
Current key is: dt
start Object
Current key is: temp
Current key is: temp_min
Current key is: temp_max
Current key is: pressure
Current key is: sea_level
Current key is: grnd_level
Current key is: humidity
Current key is: temp_kf
end Object
start Object
Current key is: id
Current key is: main
Current key is: description
Current key is: icon
end Object
*/
private:
Forecast forecast = { 0 };
bool in_forecast = false;
public:
/* Process the value provided at a specific JSON path / element
* This forms the core operation of the Handler.
*/
void value(ElementPath path, ElementValue value)
{
memset(fullPath, 0 , sizeof(fullPath));
path.toString(fullPath);
const char* currentKey = path.getKey();
//Serial.print("Current key is: "); Serial.println(currentKey);
/*
// Uncomment this to see the paths.
Serial.print(fullPath); Serial.print("': ");
Serial.println(value.toString(valueBuffer));
*/
// Map Example 1: Based on path string
it = mymap.find((std::string) fullPath);
if (it != mymap.end())
{
Serial.print("-> Found a key we care about: ");
Serial.print(fullPath);
Serial.print(" = ");
Serial.println(value.toString(valueBuffer));
// Store this in the map
it->second = value.getFloat();
}
// Object entry?
if(currentKey[0] != '\0') {
// Tradition State-Machine based parser
if(strcmp(currentKey, "dt") == 0) {
forecast.datetime = (time_t) value.getInt();
}
else if (strcmp(currentKey, "humidity") == 0) {
forecast.humidity = value.getInt();
}
else if (strcmp(currentKey, "temp") == 0) {
forecast.temp = value.getInt();
}
else if (strcmp(currentKey, "main") == 0) {
strncpy(forecast.summary, value.getString(), sizeof(forecast.summary));
}
else if (strcmp(currentKey, "icon") == 0) { // We're at the end from our perspective.
myForecasts.push_front (forecast);
//Serial.println("Inserted forecast...");
} // end state machine logic
}
// Array item.
/*
else {
int currentIndex = path.getIndex();
if(currentIndex == 0) {
//TODO: use the value.
} else if(currentIndex < 5) {
//TODO: use the value.
}
// else ...
}
*/
} // end value
// Reverse the list so it's most recent to most far away forecast
void endDocument() {
myForecasts.reverse();
}
//
// Functions we don't care about.
void startDocument() { }
void startObject(ElementPath path) { // Start of object '{'
// Serial.println("start Object");
}
void endObject(ElementPath path) { // End of a forecast object '}'
// Serial.println("end Object");
}
void startArray(ElementPath path) {}
void endArray(ElementPath path) {}
void whitespace(char c) {}
}; | true |
4decbdfff73c22f48c0fa6b578250ea5d6c2bdc0 | C++ | RobertSpiri/Joc-2D | /joc 2D/Source/Laboratoare/Laborator3/Laborator3.cpp | UTF-8 | 8,004 | 2.5625 | 3 | [] | no_license | #include "Laborator3.h"
#include <vector>
#include <iostream>
#include <Core/Engine.h>
#include "Transform2D.h"
#include "Object2D.h"
#include <math.h>
#include <time.h>
using namespace std;
class Projectile;
class Enemy_ship;
float pozitiaX;
float pozitiaY;
int ok = 0;
bool game_over;
vector<Projectile*> projectiles;
vector<Enemy_ship*> enemy_ships;
Laborator3::Laborator3()
{
}
Laborator3::~Laborator3()
{
}
int my_hp;
void Laborator3::Init()
{
my_hp = 3;
game_over = false;
glm::ivec2 resolution = window->GetResolution();
auto camera = GetSceneCamera();
camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0.01f, 400);
camera->SetPosition(glm::vec3(0, 0, 50));
camera->SetRotation(glm::vec3(0, 0, 0));
camera->Update();
GetCameraInput()->SetActive(false);
pozitiaX = float( resolution.x ) / 2;
pozitiaY = float( resolution.y ) / 2;
glm::vec3 corner = glm::vec3(0, 0, 0);
float squareSide = 75;
// compute coordinates of square center
float cx = corner.x + squareSide / 2;
float cy = corner.y + squareSide / 2;
srand(time(NULL));
// initialize tx and ty (the translation steps)
translateX = 0;
translateY = 0;
// initialize sx and sy (the scale factors)
scaleX = 1;
scaleY = 1;
// initialize angularStep
angularStep = 0;
Mesh* triangle = Object2D::CreateTriangle("triangle", corner, squareSide, glm::vec3(1, 0.7, 0), true);
AddMeshToList(triangle);
Mesh* projectile = Object2D::CreateProjectile("projectile", glm::vec3(0, 0, 0), 25, glm::vec3(0, 1, 1), true);
AddMeshToList(projectile);
}
void Laborator3::FrameStart()
{
// clears the color buffer (using the previously set color) and depth buffer
glClearColor(0, 0, 0, 1); //1001 face ecranul rosu <----------------------------------------------------------------------
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
// sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
}
float scX = 1, scY = 1;
float rotatie = 0;
class Projectile {
public:
float x, x0;
float y, y0;
float a;
float dX, dY;
bool dead;
Projectile(float x0, float y0, float a) {
this->x0 = x0;
this->y0 = y0;
this->x = x0;
this->y = y0;
this->a = a;
this->dX = 800 * cos(a);
this->dY = 800 * sin(a);
this->dead = false;
}
void update(float dt) {
this->x += dX * dt;
this->y += dY * dt;
}
};
class Enemy_ship {
public:
float x, y;
float a;
bool dead;
float scale;
int hp;
float speed;
Mesh* mesh;
bool hit;
void handle_collisions() {
for (Projectile *p : projectiles) {
if (p->dead) continue;
float distance = sqrt(pow(p->x - this->x, 2) + pow(p->y - this->y, 2));
if (distance < 50) {
hp--;
if (hp <= 0)
this->dead = true;
else {
this->mesh = Object2D::CreateTriangle("triangle_enemy", glm::vec3(0, 0, 0), 75, glm::vec3(0, 0.3, 0.5), true);
this->hit = true;
speed *= 2;
}
p->dead = true;
break;
}
}
float distance = sqrt(pow(pozitiaX - this->x, 2) + pow(pozitiaY - this->y, 2));
if (distance < 70) {
my_hp--;
this->dead = true;
if (my_hp == 0)
game_over = true;
}
}
Enemy_ship(float angle, float radius) {
this->x = pozitiaX + radius *cos(angle);
this->y = pozitiaY + radius *sin(angle);
this->a = 0;
this->dead = false;
this->hp = rand() % 2 + 1;
this->scale = 1;
this->speed = 0.7 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1 - 0.7)));
if(this->hp == 1)
this->mesh = Object2D::CreateTriangle("triangle_enemy", glm::vec3(0, 0, 0), 75, glm::vec3(0, 0, 1), true);
else
this->mesh = Object2D::CreateTriangle("triangle_enemy", glm::vec3(0, 0, 0), 75, glm::vec3(1, 0, 1), true);
this->hit = false;
}
void update(float dt) {
this->a = atan2(pozitiaY - this->y, pozitiaX - this->x);
float dX = speed * 150 * cos(a);
float dY = speed * 150 * sin(a);
this->x += dX * dt;
this->y += dY * dt;
float dS = 0;
if (hit && this->scale > 0.5)
dS = -2;
this->scale += dS * dt;
handle_collisions();
}
};
float contor = 0;
float timp = 2;
float redness = 0;
void Laborator3::Update(float deltaTimeSeconds )
{
if (game_over) {
float dR = 0.5;
if(redness < 1)
redness += dR * deltaTimeSeconds;
glClearColor( redness, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
modelMatrix = glm::mat3(1);
modelMatrix *= Transform2D::Translate(pozitiaX, pozitiaY);
modelMatrix *= Transform2D::Scale(scX, scY);
modelMatrix *= Transform2D::Rotate(rotatie);
RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix);
return;
}
// TODO: update steps for translation, rotation, scale, in order to create animations
contor += deltaTimeSeconds;
glm::ivec2 resolution = window->GetResolution();
modelMatrix = glm::mat3(1);
modelMatrix *= Transform2D::Translate(pozitiaX, pozitiaY);
modelMatrix *= Transform2D::Scale(scX, scY);
modelMatrix *= Transform2D::Rotate(rotatie);
RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix);
for (int i = 0; i < my_hp; i++) {
glm::mat3 modelMatrixHp = glm::mat3(1);
modelMatrixHp *= Transform2D::Translate(resolution.x - 50 + i * 10, resolution.y - 70);
modelMatrixHp *= Transform2D::Rotate(3.14/2);
modelMatrixHp *= Transform2D::Scale(2, 1);
RenderMesh2D(meshes["projectile"], shaders["VertexColor"], modelMatrixHp);
}
for (Projectile *p : projectiles) {
if (p->dead) continue;
p->update(deltaTimeSeconds);
glm::mat3 modelMatrixP = glm::mat3(1);
modelMatrixP *= Transform2D::Translate(p->x, p->y);
modelMatrixP *= Transform2D::Rotate(p->a);
RenderMesh2D(meshes["projectile"], shaders["VertexColor"], modelMatrixP);
}
if (contor >= timp)
{
//printf("au trecut 2 sec \n");
contor = 0;
if (timp > 0.5)
timp -= deltaTimeSeconds;
float angle = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (3.14 * 2)));
float radius = float(min(resolution.y, resolution.x) / 2 - 10);
Enemy_ship *newE = new Enemy_ship(angle,radius);
enemy_ships.push_back(newE);
}
for (Enemy_ship *enemy : enemy_ships) {
if (enemy->dead) continue;
enemy->update(deltaTimeSeconds);
glm::mat3 modelMatrixE = glm::mat3(1);
modelMatrixE *= Transform2D::Translate(enemy->x, enemy->y);
modelMatrixE *= Transform2D::Rotate(enemy->a);
modelMatrixE *= Transform2D::Scale(enemy->scale,enemy->scale);
RenderMesh2D(enemy->mesh, shaders["VertexColor"], modelMatrixE);
}
}
void Laborator3::FrameEnd()
{
}
void Laborator3::OnInputUpdate(float deltaTimeSeconds, int mods)
{
if (game_over) return;
if (window->KeyHold(GLFW_KEY_D)) pozitiaX += 400 * deltaTimeSeconds;
if (window->KeyHold(GLFW_KEY_A)) pozitiaX -= 400 * deltaTimeSeconds;
if (window->KeyHold(GLFW_KEY_W)) pozitiaY += 400 * deltaTimeSeconds;
if (window->KeyHold(GLFW_KEY_S)) pozitiaY -= 400 * deltaTimeSeconds;
}
void Laborator3::OnKeyPress(int key, int mods)
{
// add key press event
}
void Laborator3::OnKeyRelease(int key, int mods)
{
// add key release event
}
void Laborator3::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// add mouse move event
glm::ivec2 resolution = window->GetResolution();
if (!game_over)
rotatie = atan2(-(pozitiaY - (resolution.y - mouseY)), mouseX - pozitiaX);
}
void Laborator3::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// add mouse button press event
glm::ivec2 resolution = window->GetResolution();
if (button == 1)
{
float a = atan2(-(pozitiaY - (resolution.y - mouseY)), mouseX - pozitiaX);
Projectile *newP = new Projectile(pozitiaX, pozitiaY, a);
projectiles.push_back(newP);
}
}
void Laborator3::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// add mouse button release event
}
void Laborator3::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
}
void Laborator3::OnWindowResize(int width, int height)
{
}
| true |
9f991af85289a5a332e98a826dad6bf9a40a2161 | C++ | sonmodx/Week-9-Profund | /Week9.1.cpp | UTF-8 | 2,665 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<windows.h>
using namespace std;
void setcolor(int fg,int bg){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, bg*16+fg);
}
struct Quiz{
string question;
string choices1;
string choices2;
string choices3;
};
void askQuestion(Quiz q)
{
cout << q.question << endl;
cout << "1. "<< q.choices1 << endl;
cout << "2. "<< q.choices2 << endl;
cout << "3. "<< q.choices3 << endl;
}
int main()
{
int number[10];
int score = 0;
int checkanswer[10]= {3,2,2,2,3,3,1,3,1,3};
Quiz q[10];
q[0].question="What is the smallest country?";
q[0].choices1="USA";
q[0].choices2="India";
q[0].choices3="Vatican City";
q[1].question="What is the largest country?";
q[1].choices1="USA";
q[1].choices2="Russia";
q[1].choices3="India";
q[2].question="What is the biggest animal in the world?";
q[2].choices1="Elephant";
q[2].choices2="Blue whale";
q[2].choices3="Great white shark";
q[3].question="What is the lightest element?";
q[3].choices1="Helieum";
q[3].choices2="Hydrogen";
q[3].choices3="Oxygen";
q[4].question="What has Micheal Faraday discoverd?";
q[4].choices1="Love";
q[4].choices2="Myself";
q[4].choices3="Dynamo";
q[5].question="What is the capital of Australia?";
q[5].choices1="Vienna";
q[5].choices2="Kabul";
q[5].choices3="Canberra";
q[6].question="What is the capital of Chile?";
q[6].choices1="Santiago";
q[6].choices2="Bogota";
q[6].choices3="Havana";
q[7].question="What is the fastest animal of the world?";
q[7].choices1="Cheetah";
q[7].choices2="Brown Hare";
q[7].choices3="Peregrine Falcon";
q[8].question="Who is the most handsome in this room?";
q[8].choices1="Mod-x";
q[8].choices2="MOD-X";
q[8].choices3="mod-x";
q[9].question="What is the inequalation?";
q[9].choices1="1 = 0.99999..";
q[9].choices2="0! = 1";
q[9].choices3="22/7 = 3.14";
int i=0;
do {
q[i].question;
q[i].choices1;
q[i].choices2;
q[i].choices3;
askQuestion(q[i]);
cout << "Choose 1-3 :";
cin >> number[i];
if (number[i] == checkanswer[i])
{
setcolor(2,0);
cout << "Correct! (-:";
setcolor(7,0);
score++;
}
else {
setcolor(4,0);
cout << "Incorrect! )-:";
setcolor(7,0);
}
cout << endl;
cout << endl;
i++;
} while(i<10);
cout << "Total score : " << score << "/10" << endl;
}
| true |
89ed23b1867d7f36e913c1937609089456cd7952 | C++ | aliara/Demo | /LineDetect/PrintLines.cpp | UTF-8 | 662 | 2.984375 | 3 | [] | no_license | /**
* @brief La función muestra las líneas detectadas sobre la imagen - RGB son los parametros que dan color a la linea.
* @param img Frame a imprimir
* @param lineas Vector con lineas detectadas
* @param R Color Rojo
* @param G Color Verde
* @param B Color Azul
* @return No retorna nada
* @author Santiago F. Maudet - Andrés Demski - Nicolás Linale
* @date 24/07/2014
**/
#include "Header.h"
void PrintLines (IplImage * img, Linea lineas, int R , int G , int B)
{
CvPoint pt1, pt2;
pt1.x = lineas.punto1.x;
pt1.y = lineas.punto1.y;
pt2.x = lineas.punto2.x;
pt2.y = lineas.punto2.y;
cvLine(img, pt1, pt2, CV_RGB(R,G,B), 3, 8, 0);
return;
}
| true |
29b746ccddc0a6324d17f5302c858b30a6cc8ab1 | C++ | khanhvu207/competitiveprogramming | /Olympiad/CST 2019/Thầy Vinh/T3/TIMSO.CPP | UTF-8 | 2,064 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#define maxn 100001
using namespace std;
int n;
short a[maxn];
void nEgAtiVe()
{
for (int i=n-1; i>=0; --i){
if (a[i]+1 <= 9){
++a[i];
printf("-");
for (int j=0; j<n; ++j)
printf("%d",a[j]);
printf("\n");
return;
}
}
printf("%d",-1);
for (int j=0; j<n; ++j)
printf("%d",a[j]);
printf("\n");
return;
}
void pOsItiVe()
{
int hold = 1 + a[n-1];
for (int i=n-2; i>=0; --i){
if (a[i] && hold + 1 <= (n-i-1)*9){
--a[i];
++hold;
for (int j=i+1; j<n; ++j){
a[j] = min(9,hold);
hold -= a[j];
}
bool flag = false;
for (int j=0; j<n; ++j){
if (a[j]!=0) flag = true;
if (a[j] == 0 && !flag)
continue;
printf("%d",a[j]);
}
printf("\n");
return;
}
hold += a[i];
}
if (hold - a[0] <= (n-1)*9){
printf("-%d",a[0]);
for (int j=1; j<n; ++j){
a[j] = min(9,hold);
hold -= a[j];
printf("%d",a[j]);
}
printf("\n");
return;
}
if (a[0] == 9){
printf("%d%d",-1,a[0]);
} else{
printf("%d",-(a[0]+1));
}
for (int j=1; j<n; ++j)
printf("%d",a[j]);
printf("\n");
return;
}
int main()
{
freopen("TIMSO.INP","r",stdin);
freopen("TIMSO.OUT","w",stdout);
int T = 0; scanf("%d\n",&T);
char c;
bool negative;
while (T--){
c = getchar();
negative = false;
if (c == '-'){
negative = true;
c = getchar();
}
n = 0;
a[n++] = c - '0';
while (scanf("%c",&c)==1){
if ('0'>c||'9'<c) break;
a[n++] = c - '0';
}
if (negative){
nEgAtiVe();
} else
pOsItiVe();
}
return 0;
}
| true |
d0efb4f43a5c749bae1002119dac84ded42fa791 | C++ | lgray/LCContent | /src/LCHelpers/ClusterHelper.cc | UTF-8 | 18,733 | 2.625 | 3 | [] | no_license | /**
* @file PandoraSDK/src/LCHelpers/ClusterHelper.cc
*
* @brief Implementation of the cluster helper class.
*
* $Log: $
*/
#include "Pandora/AlgorithmHeaders.h"
#include "LCHelpers/ClusterHelper.h"
using namespace pandora;
namespace lc_content
{
StatusCode ClusterHelper::GetFitResultsClosestApproach(const ClusterFitResult &lhs, const ClusterFitResult &rhs, float &closestApproach)
{
if (!lhs.IsFitSuccessful() || !rhs.IsFitSuccessful())
return STATUS_CODE_INVALID_PARAMETER;
const CartesianVector interceptDifference(lhs.GetIntercept() - rhs.GetIntercept());
try
{
const CartesianVector directionNormal((lhs.GetDirection().GetCrossProduct(rhs.GetDirection())).GetUnitVector());
closestApproach = std::fabs(directionNormal.GetDotProduct(interceptDifference));
}
catch (StatusCodeException &)
{
closestApproach = interceptDifference.GetMagnitude();
}
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
float ClusterHelper::GetDistanceToClosestHit(const ClusterFitResult &clusterFitResult, const Cluster *const pCluster,
const unsigned int startLayer, const unsigned int endLayer)
{
if (startLayer > endLayer)
throw StatusCodeException(STATUS_CODE_INVALID_PARAMETER);
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
for (unsigned int iLayer = startLayer; iLayer <= endLayer; ++iLayer)
{
OrderedCaloHitList::const_iterator iter = orderedCaloHitList.find(iLayer);
if (orderedCaloHitList.end() == iter)
continue;
for (CaloHitList::const_iterator hitIter = iter->second->begin(), hitIterEnd = iter->second->end(); hitIter != hitIterEnd; ++hitIter)
{
const CartesianVector interceptDifference((*hitIter)->GetPositionVector() - clusterFitResult.GetIntercept());
const float distanceSquared(interceptDifference.GetCrossProduct(clusterFitResult.GetDirection()).GetMagnitudeSquared());
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
distanceFound = true;
}
}
}
if (!distanceFound)
return std::numeric_limits<float>::max();
return std::sqrt(minDistanceSquared);
}
//------------------------------------------------------------------------------------------------------------------------------------------
float ClusterHelper::GetDistanceToClosestHit(const Cluster *const pClusterI, const Cluster *const pClusterJ)
{
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitListI(pClusterI->GetOrderedCaloHitList());
const OrderedCaloHitList &orderedCaloHitListJ(pClusterJ->GetOrderedCaloHitList());
// Loop over hits in cluster I
for (OrderedCaloHitList::const_iterator iterI = orderedCaloHitListI.begin(), iterIEnd = orderedCaloHitListI.end(); iterI != iterIEnd; ++iterI)
{
for (CaloHitList::const_iterator hitIterI = iterI->second->begin(), hitIterIEnd = iterI->second->end(); hitIterI != hitIterIEnd; ++hitIterI)
{
const CartesianVector &positionVectorI((*hitIterI)->GetPositionVector());
// For each hit in cluster I, find closest distance to a hit in cluster J
for (OrderedCaloHitList::const_iterator iterJ = orderedCaloHitListJ.begin(), iterJEnd = orderedCaloHitListJ.end(); iterJ != iterJEnd; ++iterJ)
{
for (CaloHitList::const_iterator hitIterJ = iterJ->second->begin(), hitIterJEnd = iterJ->second->end(); hitIterJ != hitIterJEnd; ++hitIterJ)
{
const float distanceSquared((positionVectorI - (*hitIterJ)->GetPositionVector()).GetMagnitudeSquared());
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
distanceFound = true;
}
}
}
}
}
if (!distanceFound)
return std::numeric_limits<float>::max();
return std::sqrt(minDistanceSquared);
}
//------------------------------------------------------------------------------------------------------------------------------------------
float ClusterHelper::GetDistanceToClosestCentroid(const ClusterFitResult &clusterFitResult, const Cluster *const pCluster,
const unsigned int startLayer, const unsigned int endLayer)
{
if (startLayer > endLayer)
throw StatusCodeException(STATUS_CODE_INVALID_PARAMETER);
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
for (unsigned int iLayer = startLayer; iLayer <= endLayer; ++iLayer)
{
OrderedCaloHitList::const_iterator iter = orderedCaloHitList.find(iLayer);
if (orderedCaloHitList.end() == iter)
continue;
const CartesianVector interceptDifference(pCluster->GetCentroid(iLayer) - clusterFitResult.GetIntercept());
const float distanceSquared(interceptDifference.GetCrossProduct(clusterFitResult.GetDirection()).GetMagnitudeSquared());
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
distanceFound = true;
}
}
if (!distanceFound)
return std::numeric_limits<float>::max();
return std::sqrt(minDistanceSquared);
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ClusterHelper::GetDistanceToClosestCentroid(const Cluster *const pClusterI, const Cluster *const pClusterJ, float ¢roidDistance)
{
// Return if clusters do not overlap
if ((pClusterI->GetOuterPseudoLayer() < pClusterJ->GetInnerPseudoLayer()) || (pClusterJ->GetOuterPseudoLayer() < pClusterI->GetInnerPseudoLayer()))
return STATUS_CODE_NOT_FOUND;
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitListI(pClusterI->GetOrderedCaloHitList());
const OrderedCaloHitList &orderedCaloHitListJ(pClusterJ->GetOrderedCaloHitList());
for (OrderedCaloHitList::const_iterator iterI = orderedCaloHitListI.begin(), iterIEnd = orderedCaloHitListI.end(); iterI != iterIEnd; ++iterI)
{
const CartesianVector centroidI(pClusterI->GetCentroid(iterI->first));
for (OrderedCaloHitList::const_iterator iterJ = orderedCaloHitListJ.begin(), iterJEnd = orderedCaloHitListJ.end(); iterJ != iterJEnd; ++iterJ)
{
if (orderedCaloHitListI.end() == orderedCaloHitListI.find(iterJ->first))
continue;
const CartesianVector centroidJ(pClusterJ->GetCentroid(iterJ->first));
const float distanceSquared((centroidI - centroidJ).GetMagnitudeSquared());
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
distanceFound = true;
}
}
}
if (!distanceFound)
return STATUS_CODE_NOT_FOUND;
centroidDistance = std::sqrt(minDistanceSquared);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ClusterHelper::GetClosestIntraLayerDistance(const Cluster *const pClusterI, const Cluster *const pClusterJ, float &intraLayerDistance)
{
// Return if clusters do not overlap
if ((pClusterI->GetOuterPseudoLayer() < pClusterJ->GetInnerPseudoLayer()) || (pClusterJ->GetOuterPseudoLayer() < pClusterI->GetInnerPseudoLayer()))
return STATUS_CODE_NOT_FOUND;
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitListI(pClusterI->GetOrderedCaloHitList());
const OrderedCaloHitList &orderedCaloHitListJ(pClusterJ->GetOrderedCaloHitList());
for (OrderedCaloHitList::const_iterator iterI = orderedCaloHitListI.begin(), iterIEnd = orderedCaloHitListI.end(); iterI != iterIEnd; ++iterI)
{
const unsigned int pseudoLayer(iterI->first);
OrderedCaloHitList::const_iterator iterJ = orderedCaloHitListJ.find(pseudoLayer);
if (orderedCaloHitListJ.end() == iterJ)
continue;
const CartesianVector centroidI(pClusterI->GetCentroid(pseudoLayer));
const CartesianVector centroidJ(pClusterJ->GetCentroid(pseudoLayer));
const float distanceSquared((centroidI - centroidJ).GetMagnitudeSquared());
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
distanceFound = true;
}
}
if (!distanceFound)
return STATUS_CODE_NOT_FOUND;
intraLayerDistance = std::sqrt(minDistanceSquared);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ClusterHelper::GetTrackClusterDistance(const Track *const pTrack, const Cluster *const pCluster, const unsigned int maxSearchLayer,
const float parallelDistanceCut, const float minTrackClusterCosAngle, float &trackClusterDistance)
{
if ((0 == pCluster->GetNCaloHits()) || (pCluster->GetInnerPseudoLayer() > maxSearchLayer))
return STATUS_CODE_NOT_FOUND;
const TrackState &trackState(pTrack->GetTrackStateAtCalorimeter());
const CartesianVector &trackPosition(trackState.GetPosition());
const CartesianVector trackDirection(trackState.GetMomentum().GetUnitVector());
if (trackDirection.GetCosOpeningAngle(pCluster->GetInitialDirection()) < minTrackClusterCosAngle)
return STATUS_CODE_NOT_FOUND;
bool distanceFound(false);
float minDistanceSquared(std::numeric_limits<float>::max());
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
for (OrderedCaloHitList::const_iterator iter = orderedCaloHitList.begin(), iterEnd = orderedCaloHitList.end(); iter != iterEnd; ++iter)
{
if (iter->first > maxSearchLayer)
break;
for (CaloHitList::const_iterator hitIter = iter->second->begin(), hitIterEnd = iter->second->end(); hitIter != hitIterEnd; ++hitIter)
{
const CartesianVector positionDifference((*hitIter)->GetPositionVector() - trackPosition);
if (std::fabs(trackDirection.GetDotProduct(positionDifference)) > parallelDistanceCut)
continue;
const float perpendicularDistanceSquared((trackDirection.GetCrossProduct(positionDifference)).GetMagnitudeSquared());
if (perpendicularDistanceSquared < minDistanceSquared)
{
minDistanceSquared = perpendicularDistanceSquared;
distanceFound = true;
}
}
}
if (!distanceFound)
return STATUS_CODE_NOT_FOUND;
trackClusterDistance = std::sqrt(minDistanceSquared);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::CanMergeCluster(const Pandora &pandora, const Cluster *const pCluster, const float minMipFraction, const float maxAllHitsFitRms)
{
if (0 == pCluster->GetNCaloHits())
return false;
if (!(pCluster->IsPhotonFast(pandora)))
return true;
if (pCluster->GetMipFraction() - minMipFraction > std::numeric_limits<float>::epsilon())
return true;
return (pCluster->GetFitToAllHitsResult().IsFitSuccessful() && (pCluster->GetFitToAllHitsResult().GetRms() < maxAllHitsFitRms));
}
//------------------------------------------------------------------------------------------------------------------------------------------
float ClusterHelper::GetEnergyWeightedMeanTime(const Cluster *const pCluster)
{
if (0 == pCluster->GetNCaloHits())
throw StatusCodeException(STATUS_CODE_NOT_INITIALIZED);
float energySum(0.f);
float energyTimeProductSum(0.f);
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
for (OrderedCaloHitList::const_iterator iter = orderedCaloHitList.begin(), iterEnd = orderedCaloHitList.end(); iter != iterEnd; ++iter)
{
for (CaloHitList::const_iterator hitIter = iter->second->begin(), hitIterEnd = iter->second->end(); hitIter != hitIterEnd; ++hitIter)
{
const float hadronicEnergy((*hitIter)->GetHadronicEnergy());
energySum += hadronicEnergy;
energyTimeProductSum += (hadronicEnergy * (*hitIter)->GetTime());
}
}
if ((energySum < std::numeric_limits<float>::epsilon()) || (energyTimeProductSum < std::numeric_limits<float>::epsilon()))
throw StatusCodeException(STATUS_CODE_FAILURE);
return energyTimeProductSum / energySum;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::DoesClusterCrossGapRegion(const Pandora &pandora, const Cluster *const pCluster, const unsigned int startLayer,
const unsigned int endLayer, const unsigned int nSamplingPoints)
{
const unsigned int fitStartLayer(std::max(startLayer, pCluster->GetInnerPseudoLayer()));
const unsigned int fitEndLayer(std::min(endLayer, pCluster->GetOuterPseudoLayer()));
if (fitStartLayer > fitEndLayer)
throw StatusCodeException(STATUS_CODE_INVALID_PARAMETER);
ClusterFitResult fitResult;
if (STATUS_CODE_SUCCESS != ClusterFitHelper::FitLayers(pCluster, fitStartLayer, fitEndLayer, fitResult))
return false;
const CartesianVector startLayerCentroid(pCluster->GetCentroid(fitStartLayer));
const float propagationDistance((pCluster->GetCentroid(fitEndLayer) - startLayerCentroid).GetDotProduct(fitResult.GetDirection()));
return ClusterHelper::DoesFitCrossGapRegion(pandora, fitResult, startLayerCentroid, propagationDistance, nSamplingPoints);
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::DoesFitCrossGapRegion(const Pandora &pandora, const ClusterFitResult &clusterFitResult, const CartesianVector &startPosition,
const float propagationDistance, const unsigned int nSamplingPoints)
{
const CartesianVector &fitDirection(clusterFitResult.GetDirection());
const CartesianVector &fitIntercept(clusterFitResult.GetIntercept());
const float fitStartDistance((startPosition - fitIntercept).GetDotProduct(fitDirection));
const CartesianVector fitStartPosition(fitIntercept + (fitDirection * fitStartDistance));
const CartesianVector fitPropagation(fitDirection * propagationDistance);
const DetectorGapList &detectorGapList(pandora.GetGeometry()->GetDetectorGapList());
for (unsigned int i = 0; i < nSamplingPoints; ++i)
{
const CartesianVector fitPosition(fitStartPosition + (fitPropagation * (static_cast<float>(i) / static_cast<float>(nSamplingPoints))));
for (DetectorGapList::const_iterator iter = detectorGapList.begin(), iterEnd = detectorGapList.end(); iter != iterEnd; ++iter)
{
if ((*iter)->IsInGap(fitPosition))
return true;
}
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::IsClusterLeavingDetector(const Cluster *const pCluster, const unsigned int nOuterLayersToExamine,
const unsigned int nMipLikeOccupiedLayers, const unsigned int nShowerLikeOccupiedLayers, const float showerLikeEnergyInOuterLayers)
{
if (!ClusterHelper::ContainsHitInOuterSamplingLayer(pCluster))
return false;
if (ClusterHelper::ContainsHitType(pCluster, MUON))
return true;
// Examine occupancy and energy content of outer layers
const unsigned int outerLayer(pCluster->GetOuterPseudoLayer());
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
if (nOuterLayersToExamine > outerLayer)
throw StatusCodeException(STATUS_CODE_INVALID_PARAMETER);
unsigned int nOccupiedOuterLayers(0);
float hadronicEnergyInOuterLayers(0.f);
for (unsigned int iLayer = outerLayer - nOuterLayersToExamine; iLayer <= outerLayer; ++iLayer)
{
OrderedCaloHitList::const_iterator iter = orderedCaloHitList.find(iLayer);
if (orderedCaloHitList.end() != iter)
{
nOccupiedOuterLayers++;
for (CaloHitList::const_iterator hitIter = iter->second->begin(), hitIterEnd = iter->second->end(); hitIter != hitIterEnd; ++hitIter)
{
hadronicEnergyInOuterLayers += (*hitIter)->GetHadronicEnergy();
}
}
}
if ((nOccupiedOuterLayers >= nMipLikeOccupiedLayers) ||
((nOccupiedOuterLayers == nShowerLikeOccupiedLayers) && (hadronicEnergyInOuterLayers > showerLikeEnergyInOuterLayers)))
{
return true;
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::ContainsHitType(const Cluster *const pCluster, const HitType hitType)
{
const OrderedCaloHitList &orderedCaloHitList(pCluster->GetOrderedCaloHitList());
for (OrderedCaloHitList::const_reverse_iterator iter = orderedCaloHitList.rbegin(), iterEnd = orderedCaloHitList.rend(); iter != iterEnd; ++iter)
{
for (CaloHitList::const_iterator hIter = iter->second->begin(), hIterEnd = iter->second->end(); hIter != hIterEnd; ++hIter)
{
const CaloHit *const pCaloHit(*hIter);
if (hitType == pCaloHit->GetHitType())
return true;
}
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ClusterHelper::ContainsHitInOuterSamplingLayer(const Cluster *const pCluster)
{
return (0 != pCluster->GetNHitsInOuterLayer());
}
} // namespace lc_content
| true |
b3696c687f555087d544e18e99835d6181ae8612 | C++ | Deepan20/Cpp | /String based problems/05_word_count.cpp | UTF-8 | 488 | 3.21875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char a[]="this is awesome bro";
int i=0,word=1;
while(a[i]!='\0')
{
if(a[i]==' ' || a[i]=='\t' || a[i]=='\n')
word++;
i++;
}
cout<<"Word count : "<<word;
return 0;
}
/*
Write a program in C to count the total number of words in a string. Go to the editor
Test Data :
Input the string : This is w3resource.com
Expected Output :
Total number of words in the string is : 3
*/ | true |
7d0f0ac97a7acc4ad609e1341b0f36da9f9a8fe8 | C++ | ptaxom/CP-PL | /Laba2/5/laba2_5try2/DataBase.h | UTF-8 | 1,430 | 2.65625 | 3 | [] | no_license | #pragma once
#include "DataStructs.h"
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <fstream>
class DataBase
{
std::vector<Result> results;
std::vector<Lesson> lessons;
std::vector<Student> students;
std::map<int, std::string> disciplines;
std::map<std::string, std::set<std::string>> defaultMisses;
std::map<int, std::set<int>> groupList;
std::map<int, std::map<std::string, std::pair<std::set<std::string>, std::pair<int, int>>>> dataBase;
void fillDataBase();
std::ifstream loadFile(std::string path);
template<class T> std::vector<T> loadVector(std::string path);
void printStudents();
void printDisciplines();
void printGroups();
double missesPercent(int studentID,const std::string &discipline);
double getAvg(int studentID, const std::string &discipline);
void misses(int studentsID);
double groupMisses(int groupID, const std::string &discipline);
bool isCorrectGroup(int groupID);
bool isCorrectDiscipline(const std::string &discipline);
bool isCorrectStudent(int studentID);
public:
DataBase();
DataBase(int argc, char **argv);
void handle();
~DataBase();
};
template<class T>
T read(std::ifstream &file);
template <>
std::string read<std::string>(std::ifstream &file);
template<>
Lesson read<Lesson>(std::ifstream &file);
template<>
Student read<Student>(std::ifstream &file);
template<>
Result read<Result>(std::ifstream &file); | true |
11414756a8d8a866df21cd6209b91713c8404d86 | C++ | ganmacs/playground | /online_judge/atcoder/joi2010yo_d.cpp | UTF-8 | 922 | 2.734375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
int N, C, a[100], b[100];
map<string, int> Map;
void dfs(int l, int r) {
if (r == 0) {
string str = "";
for (int i = 0; i < C; i++) {
char v1 = (a[i] % 10) + '0';
char v2 = (a[i] / 10) + '0';
if (v2 != '0') {
str += v2;
}
str += v1;
}
printf("%s\n", str.c_str());
Map[str]++;
} else {
if (l == N) return;
dfs(l + 1, r);
swap(a[r], a[l]);
dfs(l + 1, r-1);
swap(a[l], a[r]);
}
}
int main(int argc, char *argv[])
{
cin >> N >> C;
for (int i = 0; i < N; i++) {
cin >> a[i];
}
dfs(0, C);
int ans = 0;
for (auto v: Map) {
ans++;
cout << v.first << endl;
}
cout << ans << endl;
return 0;
}
| true |
bcf9aa38df3dce44a42568df151f81c34b916b88 | C++ | lyylyylyylyy/orbslam2_learn | /orb_extractor/src/main.cpp | UTF-8 | 2,688 | 2.578125 | 3 | [] | no_license | #include "orb_extractor.h"
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
using namespace XIAOC;
int main( int argc, char** argv )
{
cout << "Enter the ORBextractor module..." << endl;
// help infomation
if ( argc != 2 )
{
cout << "Please input ./orb_extractor image" << endl;
return -1;
}
// -----grid based orb extractor
int nfeatures = 1000;
int nlevels = 8;
float fscaleFactor = 1.2;
float fIniThFAST = 20;
float fMinThFAST = 7;
// default parameters printf
cout << "Default parameters are : " << endl;
cout << "nfeature : " << nfeatures << ", nlevels : " << nlevels << ", fscaleFactor : " << fscaleFactor << endl;
cout << "fIniThFAST : " << fIniThFAST << ", fMinThFAST : " << fMinThFAST << endl;
// read image
cout << "Read image..." << endl;
Mat image = imread( argv[1], CV_LOAD_IMAGE_UNCHANGED );
Mat grayImg, mask;
cvtColor( image, grayImg, CV_RGB2GRAY );
imshow( "grayImg", grayImg );
waitKey( 0 );
cout << "Read image finish!" << endl;
// orb extractor initialize
cout << "ORBextractor initialize..." << endl;
ORBextractor* pORBextractor;
pORBextractor = new ORBextractor( nfeatures, fscaleFactor, nlevels, fIniThFAST, fMinThFAST );
cout << "ORBextractor initialize finished!" << endl;
// orb extractor
cout << "Extract orb descriptors..." << endl;
Mat desc;
vector<KeyPoint> kps;
(*pORBextractor)( grayImg, mask, kps, desc );
cout << "Extract orb descriptors finished!" << endl;
cout << "The number of keypoints are = " << kps.size() << endl;
// draw keypoints in output image
Mat outImg;
drawKeypoints( grayImg, kps, outImg, cv::Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );
imshow( "GridOrbKpsImg", outImg );
waitKey( 0 );
cout << "Finished! Congratulations!" << endl;
// ----original orb extractor for comparation
// orb initialization
cout << "Using original orb extractor to extract orb descriptors for comparation." << endl;
Ptr<ORB> orb_ = ORB::create( 1000, 1.2f, 8, 19 );
// orb extract
vector<KeyPoint> orb_kps;
Mat orb_desc;
orb_->detectAndCompute( grayImg, mask, orb_kps, orb_desc );
// draw keypoints in output image
Mat orbOutImg;
drawKeypoints( grayImg, orb_kps, orbOutImg, cv::Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );
imshow( "OrbKpsImg", orbOutImg );
waitKey(0);
// destroy all windows when you press any key
//destroyAllWindows();
return 0;
} | true |
a41c657ba72517525ac4be4b1d7264fe096f6931 | C++ | lorek/PRNG_Arcsine_test | /prngs/DyckPathGenerator.hpp | UTF-8 | 1,152 | 2.78125 | 3 | [] | no_license | #ifndef _DYCK_PATH_H_
#define _DYCK_PATH_H_
#include <cstdlib>
#include <bitset>
#include <random>
typedef long long int64;
/***********************************************************************************
* Generator of Dyck Paths based on vector of booleans *
* - an optimized version of the vector container for storing binary sequences *
* (1 bit per each bool) *
***********************************************************************************/
class DyckPathGenerator {
public:
DyckPathGenerator();
DyckPathGenerator(int64 seed);
void set_seed(int64 seed);
std::vector<bool>* generate_bitsequence(int64 path_n);
std::vector<bool>* generate_bitsequence(int64 path_n, int64 seed);
private:
int64 n;
std::vector<bool> bitseq; // Sequence of generated bits
std::mt19937_64 mtGen; // the underlying PRNG - Mersenne Twister MT19937 (64-bit)
void init_bitseq();
void shuffle_bitseq();
int64 first_lowest_lvl();
void swap_subpath(int64 idx);
};
#endif | true |
c63300accd6fc59f7fac1e2a9fa30a4fd4e17e63 | C++ | qqworker/Cplusplus | /win32/day03/Day03/WinTimer/WinTimer.cpp | GB18030 | 2,342 | 2.734375 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
HINSTANCE g_hInstance = 0;
HANDLE g_hOutput = 0;
void OnTimer( HWND hWnd, WPARAM wParam )
{
char szText[256] = {0};
sprintf( szText, " ڴ˶ʱ: %d\n", wParam);
WriteConsole( g_hOutput, szText, strlen( szText ), NULL, NULL );
}
// ʱ
VOID CALLBACK TimerProc( HWND hwnd, UINT uMsg,
UINT_PTR idEvent, DWORD dwTime){
char szText[256] = {0};
sprintf(szText,"ʱ˶ʱ: %d\n", idEvent );
WriteConsole( g_hOutput, szText, strlen(szText), NULL, NULL );
}
// 2. ڴ
LRESULT CALLBACK WndProc(HWND hWnd,UINT msgID,
WPARAM wParam, LPARAM lParam)
{
switch(msgID)
{
case WM_LBUTTONDOWN:
KillTimer( hWnd, 1001 );
KillTimer( hWnd, 1002 );
break;
case WM_TIMER:
OnTimer( hWnd, wParam );
break;
case WM_CREATE:
SetTimer( hWnd, 1001, 1000, NULL );
SetTimer( hWnd, 1002, 2000, TimerProc );
break;
case WM_DESTROY:
PostQuitMessage( 0 ); // GetMessage0 ?
break;
}
return DefWindowProc( hWnd, msgID, wParam, lParam);
}
// 3. עᴰ
void Register( LPSTR lpClassName, WNDPROC wndProc )
{
WNDCLASS wndCls = {0};
wndCls.cbClsExtra = 0;
wndCls.cbWndExtra = 0;
wndCls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wndCls.hCursor = NULL;
wndCls.hIcon = NULL;
wndCls.hInstance = g_hInstance;
wndCls.lpfnWndProc = wndProc;
wndCls.lpszClassName = lpClassName;
wndCls.lpszMenuName = NULL;
wndCls.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndCls);
}
// 4.
HWND CreateMain( LPSTR lpClassName, LPSTR lpWndName){
HWND hWnd = CreateWindowEx( 0, lpClassName, lpWndName,
WS_OVERLAPPEDWINDOW, 100, 100, 700, 500,
NULL, NULL, g_hInstance, NULL );
return hWnd;
}
// 5. ʾ
void Display( HWND hWnd ){
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
}
// 6. Ϣѭ
void Message(){
MSG nMsg = {0};
while( GetMessage( &nMsg, NULL, 0, 0 ) ){
TranslateMessage( &nMsg );
DispatchMessage( &nMsg );
}
}
// 1. WinMain
int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPrevIns,
LPSTR lpCmdLine,int nCmdShow){
AllocConsole();
g_hOutput = GetStdHandle( STD_OUTPUT_HANDLE );
g_hInstance = hInstance;
Register( "Main", WndProc);
HWND hWnd = CreateMain( "Main", "Window" );
Display( hWnd );
Message();
return 0;
} | true |
ca9b7d8dd605c5183210cedff3d13a9f799e1d09 | C++ | dm0lz/CPlusPlus | /exo2tp5/main.cpp | UTF-8 | 542 | 3.359375 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool anneeBissextile (int a)
{
bool bissextile=false;
if ((a%4==0 && a%100!=0) || a%400==0) {
bissextile=true;
}
return bissextile;
}
string anneeBissextileString (int a)
{
string bissextilite="pas bissextile";
if (anneeBissextile(a)==true) {
bissextilite="bissextile";
}
return bissextilite;
}
int main (int argc, char * const argv[])
{
int a;
cout << "veuillez entrer une annee"<<endl;
cin>>a;
cout << "l annee que vous avez entre est "<<anneeBissextileString(a)<<endl;
}
| true |
0bde175d66e5978e7f00774d5d10dbad16ee612b | C++ | neises/SRE | /SRE/Scene.cpp | UTF-8 | 969 | 2.703125 | 3 | [] | no_license | #include "Scene.h"
#include "Utils.h"
#include "SceneObject.h"
#include "Log.h"
namespace SRE
{
using namespace SRE;
Scene::Scene() : m_aSceneObjects(std::vector<SceneObject*>())
{
}
Scene::~Scene()
{
for (SceneObject* pChild : m_aSceneObjects)
{
SAFE_DELETE(pChild);
}
}
void Scene::AddChild(SceneObject* _pSceneObject)
{
if (_pSceneObject)
{
m_aSceneObjects.push_back(_pSceneObject);
}
}
void Scene::RemoveChild(SceneObject* _pSceneObject, bool bShouldDeleteObject)
{
auto it = find(m_aSceneObjects.begin(), m_aSceneObjects.end(), _pSceneObject);
if (it == m_aSceneObjects.end())
{
Logger::GetLoggerInstance()->L_WARNING("Missing SceneObject");
return;
}
if (bShouldDeleteObject)
{
m_aSceneObjects.erase(it);
delete _pSceneObject;
_pSceneObject = nullptr;
}
else
{
m_aSceneObjects.erase(it);
}
}
std::vector<SceneObject*>& Scene::GetSceneObjects()
{
return m_aSceneObjects;
}
} | true |
1447a09f01421415845f3d93ab074ee25a56f8e5 | C++ | lanpham09/OmniFrame | /SerialPort.cpp | UTF-8 | 7,998 | 2.65625 | 3 | [] | no_license | #include "SerialPort.h"
#include <iostream>
#include <string.h>
#include <cmath>
using namespace std;
SerialPort::SerialPort():
fileDesignator(-1),
portOpen(false)
{
fileName = "NONE";
}
SerialPort::SerialPort(const char *device, rate baudRate ):
fileDesignator(-1),
portOpen(false)
{
openPort(device, baudRate);
}
SerialPort::SerialPort(std::string device, rate baudRate ):
fileDesignator(-1),
portOpen(false)
{
openPort(device.c_str(), baudRate);
}
SerialPort::~SerialPort()
{
closePort();
}
bool SerialPort::openPort(const char *device, rate baudRate )
{
if(portOpen)
closePort();
fileName = "NONE";
// open the port
fileDesignator = open(device, O_RDWR | O_NOCTTY);
// set serial configurations
cout << "fileDesignator " << fileDesignator<< endl;
if(fileDesignator == -1) {
cout << "AMCController: failed to open serial device." << endl;
portOpen = false;
}
else {
// verify that opened device is serial device (aka tty)
if(!isatty(fileDesignator))
{
cout << "AMCController: this is not a serial device." << endl;
portOpen = false;
close(fileDesignator);
fileDesignator = -1;
} else {
struct termios newtio;
newtio.c_cflag = CS8 | CLOCAL | CREAD;
switch( baudRate )
{
case B_0:
newtio.c_cflag = newtio.c_cflag | B0;
break;
case B_50:
newtio.c_cflag = newtio.c_cflag | B50;
break;
case B_75:
newtio.c_cflag = newtio.c_cflag | B75;
break;
case B_110:
newtio.c_cflag = newtio.c_cflag | B110;
break;
case B_134:
newtio.c_cflag = newtio.c_cflag | B134;
break;
case B_150:
newtio.c_cflag = newtio.c_cflag | B150;
break;
case B_200:
newtio.c_cflag = newtio.c_cflag | B200;
break;
case B_300:
newtio.c_cflag = newtio.c_cflag | B300;
break;
case B_600:
newtio.c_cflag = newtio.c_cflag | B600;
break;
case B_1200:
newtio.c_cflag = newtio.c_cflag | B1200;
break;
case B_1800:
newtio.c_cflag = newtio.c_cflag | B1800;
break;
case B_2400:
newtio.c_cflag = newtio.c_cflag | B2400;
break;
case B_4800:
newtio.c_cflag = newtio.c_cflag | B4800;
break;
case B_9600:
newtio.c_cflag = newtio.c_cflag | B9600;
break;
case B_19200:
newtio.c_cflag = newtio.c_cflag | B19200;
break;
case B_38400:
newtio.c_cflag = newtio.c_cflag | B38400;
break;
case B_57600:
newtio.c_cflag = newtio.c_cflag | B57600;
break;
case B_115200:
newtio.c_cflag = newtio.c_cflag | B115200;
break;
case B_230400:
newtio.c_cflag = newtio.c_cflag | B230400;
break;
}
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
tcflush(fileDesignator, TCIOFLUSH);
tcsetattr(fileDesignator, TCSAFLUSH, &newtio);
fileName = string(device);
portOpen = true;
}
}
return portOpen;
}
void SerialPort::closePort()
{
if( portOpen )
close( fileDesignator );
fileDesignator = -1;
fileName = "NONE";
portOpen = false;
}
bool SerialPort::isOpen() const
{
return fileDesignator !=-1;
}
/**
* Flushes data buffer for the serial port.
*
*/
bool SerialPort::flushData( ) {
if( portOpen )
{
ioctl(fileDesignator, TCFLSH, TCIOFLUSH );
}
return portOpen; // otherwise
}
/**
* Reads data from the serial port and puts it in buffer.
*
* Function only reads data if data is available within ms_timeout (microsecond resolution)
* milli-seconds of the function call.
*
* If a start deliminator is specified, it will shift the read data untill startDelim
* is found in the input stream and continue reading until the number of specified bytes has
* been read after the start deliminator. If and end deliminator is specified and is not found
* after the specified number of bytes has been read the funciton returns -bytes read;
*
* Function Returs:
* bytes_read if sucessfully completed, should be equal to the number of bytes requested.
*
* 0 if serial file is unset (fileDesignaor = -1)
*
* -bytes_read if the specified number of bytes cound not be read beacuse data was not available in specified timout time,
* or if the end Deliminator was not achieved. If a message length of 15 was requested a return of -1 to -14 means the
* number was not reached and -15 means that the end deliminator was not achieved.
*
*/
int SerialPort::readData( unsigned char *buffer, int bytes, double ms_timeout, const unsigned char startDelim, const unsigned char endDelim)
{
if( fileDesignator == -1 )
return 0; // no input file setup
int bytes_read = 0;
while (bytes_read < bytes && isDataAvailable( ms_timeout ) )
{
int bytes_left = bytes - bytes_read;
int byters = read(fileDesignator, buffer + bytes_read*sizeof(char), bytes_left );
bytes_read += byters;
// see if start deliminator is start of message
if( startDelim )
{
// find index of start deliminator
int startIndex = 0;
for( ; startIndex < bytes_read && buffer[startIndex] != startDelim; startIndex ++ );
// if not start of message
if( startIndex > 0 )
{
// shift message down to start with start index
for( int index = 0; index < (bytes_read-startIndex); index ++ )
buffer[index] = buffer[index+startIndex];
// reduce effective number of bytes read
bytes_read -= startIndex;
}
}
}
if( (bytes_read < bytes) || (endDelim && buffer[bytes-1] != endDelim) )
return -bytes_read; // did not complete task as desired or did not end with end deliminator
return bytes_read;
}
unsigned char SerialPort::readByte(double ms_timout)
{
unsigned char buf[1] = {0};
readData( buf, 1, ms_timout);
return buf[0];
}
std::string SerialPort::getLine( const unsigned char endDelim )
{
std::string returnString = "";
unsigned char buf[512] = {0};
int numRead = -1;
while( numRead <= 0 )
{
numRead = readData(buf, 512, 25, 0, endDelim);
for( int i=0; i< std::abs(numRead); i++ )
{
char value = buf[i];
returnString += std::string(&value);
}
}
return returnString;
}
bool SerialPort::writeData( unsigned char* buffer, int bytes)
{
int bytesWritten = 0;
if( fileDesignator !=-1 )
{
bytesWritten = write(fileDesignator, buffer, bytes);
}
cout << "wrote " << bytesWritten << endl;
return bytesWritten == bytes;
}
bool SerialPort::writeByte( unsigned char byteToWrite )
{
return writeData( &byteToWrite, sizeof(unsigned char));
}
bool SerialPort::isDataAvailable( double ms_timeout )
{
tv.tv_sec = (int)ms_timeout/1000;
tv.tv_usec = (ms_timeout-1000*tv.tv_sec)*1000;
FD_ZERO(&rfds);
FD_SET(fileDesignator,&rfds);
int retval = select(fileDesignator+1, &rfds, NULL, NULL, &tv);
if( retval == -1 )
cout << "Error occured in isDataAvailable Serial Port Call to " << fileName << endl;
return (retval > 0);
}
| true |
e898e907216a17b064faab609bb96c090ac48ab1 | C++ | sammiiT/leetcode | /BFS/1091. Shortest Path in Binary Matrix.cpp | UTF-8 | 3,612 | 3.3125 | 3 | [] | no_license | //===類似題===
1778. Shortest Path in a Hidden Grid
2435. Paths in Matrix Whose Sum Is Divisible by K
//===思路===
(*)BFS
(*)一個node衍伸出node所有的child, 所有同一層的child, 都在同一層level運算
-當計算每層child時, 都會累加一次
- 如果同一層的child的座標發生了 x== (n-1) && y==(n-1) , 則直接回傳累加次數, 此累加次數即為最少路徑
- 每一層用dirs來判斷; vector<int> dirs = {-1,1}; //每一層有兩個元素
-vector<vector<int>> dirs = {{-1,0},{0,1},{1,0},{0,-1}};//每一層有四個元素
每一個element所衍生的所有"子元素", 是父元素的下一層
for(int i=q.size();i>0;--i){//每一個element所衍生的所有"子元素", 是父元素的下一層
vector<vector<int>> dirs = {{-1,0},{-1,1},{0,1},
{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};//每一層元素有8個
//=====
int shortestPathBinaryMatrix(vector<vector<int>>& grid){
if(grid[0][0]==1) return -1;
int res = 0, n = grid.size();
set<vector<int>> visited;
visited.insert({0,0});
queue<vector<int>> q{{0,0}};
vector<vector<int>> dirs{{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
while(!q.empty()){
++res;//原點就也要計算
for(int i=q.size();i>0;i--){
auto t = q.front();q.pop();
if(t[0]==n-1&&t[1]==n-1) return res;//如果初始位置就是終點位置
for(auto dir:dirs){
int x=t[0]+dir[0], y=t[1]+dir[1];
if(x<0||x>=n||y<0||y>=n||grid[x][y]==1||visited.count({x,y})) continue;
visited.insert({x,y});
q.push({x,y});
}
}
}
return -1;
}
//===作法2
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int m=grid.size(),n=grid[0].size();
vector<vector<bool>> visited(m,vector<bool>(n,false));
if(grid[0][0]) return -1;
vector<vector<int>> dirs{{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
queue<vector<int>> q;
q.push({0,0,1});
visited[0][0]=1;
while(!q.empty()){
vector<int> p=q.front();q.pop();
if(p[0]==m-1 && p[1]==n-1) return p[2];
for(auto dir:dirs){
int x=p[0]-dir[0],y=p[1]+dir[1];
int count = p[2];
if(x<0||x>=m||y<0||y>=n||grid[x][y]||visited[x][y]) continue;
visited[x][y]=1;
q.push({x,y,count+1});
}
}
return -1;
}
//===思路2===
(*)DFS算法會造成time limited exceeded
void helper(vector<vector<int>>& grid,
int x,
int y,
vector<vector<bool>>& visited,
int path,
int& minPath){
if(x==grid.size() && y == grid[0].size()) {
minPath = min(minPath, path);
return;
}
if(x<0||x>=grid.size()||y<0||y>=grid[0].size()||visited[x][y]||grid[x][y]==1) return;
// grid[x][y]==0;
path+=1;
visited[x][y]=true;
helper(grid,x+1,y,visited,path,minPath);
helper(grid,x-1,y,visited,path,minPath);
helper(grid,x,y+1,visited,path,minPath);
helper(grid,x,y-1,visited,path,minPath);
helper(grid,x+1,y+1,visited,path,minPath);
helper(grid,x-1,y-1,visited,path,minPath);
helper(grid,x+1,y-1,visited,path,minPath);
helper(grid,x-1,y+1,visited,path,minPath);
visited[x][y]=false;
}
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size(),false));
int minPath = INT_MAX;
helper(grid,0,0,visited,0,minPath);
return (minPath==INT_MAX)?(-1):minPath;
}
| true |
c9192540062929ef6e5dba4cc5b268167c499ef1 | C++ | philx02/TournamentWS | /include/sqlite/Statement.h | UTF-8 | 1,826 | 3.140625 | 3 | [] | no_license | #include "../sqlite/sqlite3.h"
#include <string>
#include <thread>
class Statement
{
public:
Statement(sqlite3 *iSqlite, const char *iStatementString)
: mStatement(nullptr)
{
auto wResult = sqlite3_prepare_v2(iSqlite, iStatementString, -1, &mStatement, nullptr);
if (wResult != SQLITE_OK)
{
throw std::runtime_error(std::string("Cannot prepare statement: ").append(sqlite3_errstr(wResult)).c_str());
}
}
~Statement()
{
sqlite3_finalize(mStatement);
}
int runOnce()
{
int wResult = 0;
while ((wResult = sqlite3_step(mStatement)) == SQLITE_BUSY)
{
std::this_thread::yield();
}
if (wResult == SQLITE_ERROR)
{
throw std::runtime_error(std::string("Statement runtime error: ").append(sqlite3_errstr(wResult)).c_str());
}
return wResult;
}
void clear()
{
sqlite3_reset(mStatement);
sqlite3_clear_bindings(mStatement);
}
template< typename T >
void bind(const T &iValue)
{
bind(1, iValue);
}
template< typename T >
void bind(int iLocation, const T &iValue)
{
static_assert(false, "Statement: cannot bind this type");
}
template< typename Lambda >
void evaluate(const Lambda &iLambda)
{
iLambda(mStatement);
}
private:
sqlite3_stmt *mStatement;
};
template<>
void Statement::bind< int >(int iLocation, const int &iValue)
{
sqlite3_bind_int(mStatement, iLocation, iValue);
}
template<>
void Statement::bind< size_t >(int iLocation, const size_t &iValue)
{
sqlite3_bind_int(mStatement, iLocation, iValue);
}
template<>
void Statement::bind< std::string >(int iLocation, const std::string &iValue)
{
sqlite3_bind_text(mStatement, iLocation, iValue.c_str(), iValue.size(), SQLITE_TRANSIENT);
}
| true |
93ba8f087b7a6f45ccb03bd11ff787424829bb46 | C++ | jzumaeta/Uyariwawa_TxFirmware | /lib/WirelessSender/WirelessSender.cpp | UTF-8 | 1,517 | 2.6875 | 3 | [] | no_license | #include "WirelessSender.h"
#define WIFI_CHANNEL 1
WirelessSender::WirelessSender(/* args */)
{
}
WirelessSender::~WirelessSender()
{
}
void WirelessSender::Init()
{
//Init ESP-NOW protocol
if (esp_now_init() != 0) {
Serial.println("[ERROR] Can't init ESP-Now! Restarting....\n\n");
delay(3000);
ESP.restart(); delay(1);
}
//MAC info
Serial.print("[WS_INFO] Access Point MAC: ");
Serial.println(WiFi.softAPmacAddress());
Serial.print("[WS_INFO] Station MAC: ");
Serial.println(WiFi.macAddress());
//Set remote peer MAC
memcpy(remoteMac, "\x36\x33\x33\x33\x33\x33", 6);
//Setting roles
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, WIFI_CHANNEL, NULL, 0);
//Sender callback
esp_now_register_send_cb([](uint8_t* mac, uint8_t status) {
uint8_t m[6];
memcpy(m, mac, sizeof(m));
Serial.printf("[WS_INFO] Slave MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
m[0], m[1], m[2], m[3], m[4], m[5]);
Serial.print("[STATUS] (0=0K - 1=ERROR): "); Serial.println(status);
});
}
bool WirelessSender::SendToPeer(const char* msg, int len)
{
int count=0, result=0;
do {
if (count>0) delay(5);
result = esp_now_send(remoteMac, (u8*)msg, len);
Serial.println("[WS_INFO] Send message to peer!\n");
}
while(result!=0 && ++count<3);
//print message
Serial.printf("Tx: %s - Status: %d\n", msg, result);
} | true |
73a1b2f0eb9b3c9edc53a117d4003decb752b7ba | C++ | jordanlee008/Code | /USACO/TrainingPages/Chapter 2/Section 1/frac1/frac1.cpp | UTF-8 | 1,368 | 3.25 | 3 | [] | no_license | /*
ID: jorlee
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
vector< vector<int> > frac;
//final output list - needs to be constructed then sorted
//frac[x][0] contains numerator
//frac[x][1] contains denominator
int N; //input number (biggest denominator)
bool comparefrac(const vector<int> &a, const vector<int> &b) {
return a[0] * b[1] < b[0] * a[1];
}
int gcd (int a, int b) {
//USE EUCLIDEAN ALGORITHM TO FIGURE DETERMINE GCD
//a > b
int r;
do {
r = a % b;
a = b;
b = r;
} while (r != 0);
return a;
}
void construct () {
for (int i = 1; i <= N; i++) {
for (int j = 1; j < i; j++) {
vector<int> x(2); //pushed onto frac vector
//cout << "i: " << i << " j: " << j << endl;
if (gcd(i, j) == 1) {
x[0] = j;
x[1] = i;
frac.push_back(x);
}
}
}
}
int main () {
ofstream fout ("frac1.out");
ifstream fin ("frac1.in");
fin >> N;
construct();
/* for (int i = 0; i < frac.size(); i++)
cout << frac[i][0] << " " << frac[i][1] << endl;
for (int i = 0; i < decimal.size(); i++)
cout << decimal[i] << endl; */
sort(frac.begin(), frac.end(), comparefrac);
fout << "0/1\n";
for (int i = 0; i < frac.size(); i++)
fout << frac[i][0] << "/" << frac[i][1] << endl;
fout << "1/1\n";
return 0;
}
| true |
ba7d735cfacf5a558a7983807c5f5b28979bf304 | C++ | freakstreet/FreakyCamper_Arduino | /FreakyCampManager/webasto.cpp | ISO-8859-2 | 15,475 | 2.578125 | 3 | [] | no_license | //#include <max6675.h>
#include "webasto.h"
// Define constants
#define ON 1
#define OFF 0
#define REMOTE_STARTING 2
#define REMOTE_STOPPING 3
#define REMOTE_SHUTDOWN 4
#define SYSTEM_STOPPING 5
#define SYSTEM_SHUTDOWN 6
#define DELAY_60_SEC 60000
#define DELAY_15_SEC 15000
#define DELAY_5_SEC 5000
#define ON_STATE_CHANGE_INTERRUPT true
#define NO_STATE_CHANGE_INTERRUPT false
#define ON_TEMP_CHANGE_INTERRUPT true
#define NO_TEMP_CHANGE_INTERRUPT false
#define WEBASTO_MAX_START_ATTEMPTS 3
#define WEBASTO_MAX_TEMPERATURE 70
#define WEBASTO_TEMPERATURE_THRESHOLD 10
// Define service variables
boolean debug = true;
volatile long lastDebounceTime = 0;
// Define global variables
int onOffSwitch = 2;
int airFan = 3;
int fuelPump = 4;
int waterPump = 5;
int glowPlug = 6;
int cabinHeater = 8;
int remoteControl = 9;
int carBlinkers = 10;
// Thermocouple 0 = CS, 1 = CLK, 2 = DO
int tempSensor[3] = { 11, 12, 13 };
// Setting
volatile int startingAttempts = 0;
double initialTemperature;
double previousTemperature;
// Define system states (ON, OFF, REMOTE_STARTING, REMOTE_STOPPING, REMOTE_SHUTDOWN, SYSTEM_STOPPING, SYSTEM_SHUTDOWN)
volatile int systemState = OFF;
// Define modules states
int airFanState = OFF;
int waterPumpState = OFF;
int glowPlugState = OFF;
int cabinHeaterState = OFF;
int remoteControlState = ON;
// Initialize temperature sensor
//MAX6675 thermocouple(tempSensor[1], tempSensor[0], tempSensor[2]);
// Setup the controller
void initWebasto(){
// Is debug on
if(debug == true){
// Enable serial connection
Serial.begin(9600);
}
// Set modules modes
pinMode(fuelPump, OUTPUT);
pinMode(waterPump, OUTPUT);
pinMode(glowPlug, OUTPUT);
pinMode(airFan, OUTPUT);
pinMode(cabinHeater, OUTPUT);
pinMode(carBlinkers, OUTPUT);
pinMode(remoteControl, OUTPUT);
// Set ON/OFF switch to ON (internal pull-up resistor)
digitalWrite(onOffSwitch, HIGH);
// Attach interrupt
// attachInterrupt(0, turnOnOffSystem, CHANGE);
// Reset all modules
resetAllModules();
}
// Start the controller
void poolWebasto(){
// If system has to be started or is already started
if(systemState == REMOTE_STARTING || systemState == ON){
// Set initial temperature
initialTemperature = measureTemp(3);
// If temperature is above max temperature level or temperature sensor is off
if(!initialTemperature || initialTemperature >= WEBASTO_MAX_TEMPERATURE){
// If heater was running
if(systemState == ON){
// Set system state
systemState = SYSTEM_STOPPING;
}
// If heater is starting
else {
// Set system state
systemState = SYSTEM_SHUTDOWN;
}
// Stop webasto starting cycle
return;
}
// Is debug on
if(debug == true){
// Log
Serial.print("Initial temperature: ");
Serial.print(initialTemperature);
Serial.println();
}
// Start the Webasto heater
startWebasto();
}
// If system has to be shutdown
else if(systemState == REMOTE_SHUTDOWN || systemState == SYSTEM_SHUTDOWN){
// Reset all modules
resetAllModules();
// Set system state
systemState = OFF;
}
}
// Turn ON/OFF system from remote control
void turnOnOffSystem(){
// Get current time
long currentTime = millis();
// Debounce
if ((currentTime - lastDebounceTime) > 100){
// Record last debounce time
lastDebounceTime = currentTime;
// If system is still starting
if(systemState == REMOTE_STARTING){
// Turn system off immediately
systemState = REMOTE_SHUTDOWN;
}
// If system is on
else if(systemState == ON){
// Turn system off
systemState = REMOTE_STOPPING;
}
// If system is off
else if(systemState == OFF){
// Turn system on
systemState = REMOTE_STARTING;
// Clear all previous starting attempts
startingAttempts = 0;
}
}
}
// Start the webasto heater
void startWebasto(){
// If this is first, second or third attempt
if(startingAttempts < WEBASTO_MAX_START_ATTEMPTS){
// Is debug on
if(debug == true){
// Log
Serial.println("Starting the heater");
}
// Increment attempt
startingAttempts++;
// Reset all modules
resetAllModules();
// Start the air fan to clean the carbon
startAirFan();
// Wait and interrupt on system state change and temperature change
if(wait(DELAY_15_SEC, ON_STATE_CHANGE_INTERRUPT, ON_TEMP_CHANGE_INTERRUPT)) return;
// Stop air fan
stopAirFan();
// Start water pump
startWaterPump();
// Wait and interrupt on system state change and temperature change
if(wait(DELAY_15_SEC, ON_STATE_CHANGE_INTERRUPT, ON_TEMP_CHANGE_INTERRUPT)) return;
// Set system state
systemState = ON;
// Start glow plug
startGlowPlug();
// Wait and interrupt on system state change and temperature change
if(wait(DELAY_5_SEC, ON_STATE_CHANGE_INTERRUPT, ON_TEMP_CHANGE_INTERRUPT)) return;
// Start the combustion process
for(int i = 0; i <= 1000; i++){
// Supply fuel to the burner while checking for state change
if(pulseFuelPump(true, true)) return;
// 15th second from start of the burning process
if(i == 15){
// Start the air fan
startAirFan();
}
// 20th second from start of the burning process
else if(i == 20){
// Stop the glow plug
stopGlowPlug();
}
// 60th second and above from start of the burning process
else if(i >= 60){
// Check temperature
double temperature = measureTemp(3);
// If temperature sensor is off
if(!temperature){
// Go to shutdown mode
systemState = SYSTEM_STOPPING;
// Stop the burning process
return;
}
// 60th second
if(i == 60){
// If temperature threshold is not reached
if(initialTemperature + WEBASTO_TEMPERATURE_THRESHOLD > temperature){
// Is debug on
if(debug == true){
// Print error
Serial.print("Initial temperature: ");
Serial.print(initialTemperature);
Serial.print(", Current temperature: ");
Serial.print(temperature);
Serial.println();
Serial.println("Temperature threshold not reached!");
}
// Restart the burning process
return;
}
// Is debug on
if(debug == true){
// Log
Serial.print("Initial temperature: ");
Serial.print(initialTemperature);
Serial.print(", Current temperature: ");
Serial.print(temperature);
Serial.println();
Serial.println("Temperature threshold reached, continuing the burning process");
}
// Log the current temperature
previousTemperature = temperature;
// Start the cabin heater
startCabinHeater();
}
// Above 60th second
else {
// If temperature has increased
if(temperature >= previousTemperature && temperature <= previousTemperature + 2){
// Log the current temperature
previousTemperature = temperature;
}
// If temperature has decreased
else if(temperature <= previousTemperature && temperature >= previousTemperature - 2){
// Is debug on
if(debug == true){
// Print error
Serial.print("Previous temperature: ");
Serial.print(previousTemperature);
Serial.print(", Current temperature: ");
Serial.print(temperature);
Serial.println();
Serial.println("Temperature has decreased, possible flame extinguishing!");
}
// Restart the burning process
return;
}
}
}
// Wait and interrupt on system state change and temperature change
if(wait(700, true, true)) return;
}
// Go to shutdown mode
systemState = SYSTEM_STOPPING;
}
// If we have tried three times starting the Webasto
else {
// Set system state
systemState = SYSTEM_STOPPING;
}
}
// Stop the webasto heater
void stopWebasto(){
// Is debug on
if(debug == true){
// Log
Serial.println("Shutting down");
}
// Stop fuel burning and cabin heater
stopGlowPlug();
stopCabinHeater();
// Start the water pump and air fan
startWaterPump();
startAirFan();
// Wait without checking for system state change and temperature change
wait(DELAY_60_SEC, NO_STATE_CHANGE_INTERRUPT, NO_TEMP_CHANGE_INTERRUPT);
// Set system state
systemState = OFF;
// Reset all modules
resetAllModules();
// Is debug on
if(debug == true){
// Log
Serial.println("Done");
}
}
// Pulse fuel pump
boolean pulseFuelPump(boolean stateChangeInterrupt, boolean tempChangeInterrupt){
// Start fuel pump
digitalWrite(fuelPump, ON);
// Sleep for 100 miliseconds and return true on state or temperature change
if(wait(100, stateChangeInterrupt, tempChangeInterrupt)) return true;
// Stop fuel pump
digitalWrite(fuelPump, OFF);
// Is debug on
if(debug == true){
// Log
Serial.println("Pulse fuel");
}
// Return false
return false;
}
// Start air fan
void startAirFan(){
// Start the air fan
digitalWrite(airFan, ON);
// Set module status
airFanState = ON;
// Is debug on
if(debug == true){
// Log
Serial.println("Air fan on");
}
}
// Stop air fan
void stopAirFan(){
// Start the air fan
digitalWrite(airFan, OFF);
// Set module status
airFanState = OFF;
// Is debug on
if(debug == true){
// Log
Serial.println("Air fan off");
}
}
// Start water pump
void startWaterPump(){
// Start the water pump
digitalWrite(waterPump, ON);
// Set module status
waterPumpState = ON;
// Is debug on
if(debug == true){
// Log
Serial.println("Water pump on");
}
}
// Stop water pump
void stopWaterPump(){
// Start the water pump
digitalWrite(waterPump, OFF);
// Set module status
waterPumpState = OFF;
// Is debug on
if(debug == true){
// Log
Serial.println("Water pump off");
}
}
// Start glow plug
void startGlowPlug(){
// Start the glow plug
digitalWrite(glowPlug, ON);
// Set module status
glowPlugState = ON;
// Is debug on
if(debug == true){
// Log
Serial.println("Glow plug on");
}
}
// Stop glow plug
void stopGlowPlug(){
// Start the glow plug
digitalWrite(glowPlug, OFF);
// Set module status
glowPlugState = OFF;
// Is debug on
if(debug == true){
// Log
Serial.println("Glow plug off");
}
}
// Start cabin heater
void startCabinHeater(){
// Start the cabin heater
digitalWrite(cabinHeater, ON);
// Set module status
cabinHeaterState = ON;
// Is debug on
if(debug == true){
// Log
Serial.println("Cabin heater on");
}
}
// Stop cabin heater
void stopCabinHeater(){
// Start the cabin heater
digitalWrite(cabinHeater, OFF);
// Set module status
cabinHeaterState = OFF;
// Is debug on
if(debug == true){
// Log
Serial.println("Cabin heater off");
}
}
// Measure unit temperature
double measureTemp(int maxRetries){
// Init temperature variable
double temperature = NAN;
// Loop until max retries number is reached
for (int i = 0; i < maxRetries; i++){
// Measure temperature
// TODO : implmenter l'acquisition de temprature
//temperature = thermocouple.readCelsius();
temperature = 0;
// If temperature reading is ok
if (!isnan(temperature)){
// Exit on first good reading
break;
}
}
// If temperature sensor is off
if (isnan(temperature)) {
// Is debug on
if(debug == true){
// Print error
Serial.println("Thermocouple not responding!");
}
// Return false
return false;
}
// If temperature is ok
else {
// Return temperature
return temperature;
}
}
// Reset all modules
void resetAllModules(){
// Turn off all modules
stopWaterPump();
stopGlowPlug();
stopAirFan();
stopCabinHeater();
}
boolean isWebastoOn(){
return false;
}
// Custom delay
boolean wait(unsigned long milliseconds, boolean stateChangeInterrupt, boolean tempChangeInterrupt){
// Record current time
unsigned long currentTime = millis();
// Get current system state
int currentSystemState = systemState;
// Init temperature variable
double temperature;
// Loop until time limit is reached
while (millis() - currentTime <= milliseconds) {
// If temperature change interrupt is on
if(tempChangeInterrupt == true){
// Measure temperature
temperature = measureTemp(3);
// If temperature is off or above max temperature level
if(!temperature || temperature >= WEBASTO_MAX_TEMPERATURE){
// Is debug on
if(debug == true){
// Print error
Serial.print("Current temperature: ");
Serial.print(temperature);
Serial.println();
Serial.println("Max temperature reached!");
}
// If temperature critical level is reached return true
return true;
}
}
// If state change interrupt is on
if(stateChangeInterrupt == true){
// Check if system state has changed
if(systemState != currentSystemState){
// Update the current system state
currentSystemState = systemState;
// If system state has changed return true
return true;
}
}
}
// Return false if system state has not changed
return false;
}
| true |
3f735673c0221dfdf0a7f150dde16e52c4213a90 | C++ | jonah-chen/midi-piano | /datapoints.hpp | UTF-8 | 592 | 2.9375 | 3 | [] | no_license | #pragma once
/* This file will contain all the datapoints required for the webcam */
#include <iostream>
#include <string>
#include <vector>
struct note
{
std::string name;
int webcam, x, y, r;
note(const std::string&, int, int, int = 0, int = 3);
friend std::ostream& operator<<(std::ostream& os, const note& note)
{
os << note.name << " at (" << note.x << "," << note.y << ")\n";
return os;
}
};
class Stream
{
std::vector<note> notes;
int id;
public:
Stream(int);
void operator+=(const note& note) {notes.push_back(note); }
};
| true |
d9e0d4bb9a816fbb14a3c43a226c952f6646af8d | C++ | eugnsp/CUJ | /16.09/tbecker/balance.cpp | UTF-8 | 184 | 2.671875 | 3 | [] | no_license | #include<functional>
class Balance : public std::unary_function<CUSTOMER_INFO, double>{
public:
double operator() (CUSTOMER_INFO& arg) const
{return arg.dbl_balance;}
};
| true |
b4524bc2fd17315cfcfb7f6ef15bac3fb94b72d6 | C++ | JeroenSoeters/shell-cpp | /shell.h | UTF-8 | 2,129 | 3.046875 | 3 | [] | no_license | #ifndef SHELL_H
#define SHELL_H
#include <array>
#include <list>
#include <vector>
#include <unistd.h>
#include <iostream>
namespace shell
{
struct command
{
std::vector< std::string > args;
std::string input_file, output_file;
};
class ShellAction
{
public:
virtual int execute() = 0;
};
class NopAction: public ShellAction
{
public:
NopAction() noexcept;
int execute() noexcept;
};
class ExitAction: public ShellAction
{
public:
ExitAction() noexcept;
int execute() noexcept;
};
class ChangeDirectoryAction: public ShellAction
{
public:
std::string new_directory;
ChangeDirectoryAction( std::string directory ) noexcept;
int execute() noexcept;
};
class RunCommandsAction: public ShellAction
{
private:
char** convert_to_c_args( std::vector< std::string > args ) noexcept;
void free_c_args( char** c_args, int number_of_c_args ) noexcept;
void overlayProcess( std::vector< std::string > args ) noexcept;
void read_from_file( std::string input_file ) noexcept;
void write_to_file( std::string output_file ) noexcept;
void read_from_pipe( std::array< int, 2 > pipe ) noexcept;
void write_to_pipe( std::array< int, 2 > pipe ) noexcept;
void close_pipe( std::array< int, 2 > pipe ) noexcept;
pid_t execute_chained( command* cmd, bool has_prev_pipe, std::array< int, 2 > prev_pipe, bool has_next_pipe, std::array< int, 2 > next_pipe ) noexcept;
int wait_for_process_chain( std::list< pid_t > pids ) noexcept;
bool has_file_input( command * cmd ) noexcept;
bool has_file_output( command * cmd ) noexcept;
public:
int numberOfCommands = 0;
std::list< command* > commands;
bool runInBackground = false;
RunCommandsAction() noexcept;
int execute() noexcept;
command *peek_first_command() noexcept;
command *pop_first_command() noexcept;
};
struct shell_state
{
ShellAction * action = 0;
};
void parse_command( std::string input, shell_state& state );
}
#endif
| true |
09c192aa116fbdca9f878010bfcae9f384117cfa | C++ | heroinetty/ACM | /平时测试/2016年成都东软学院冬季校赛.cpp | UTF-8 | 4,708 | 2.828125 | 3 | [] | no_license | //#include<stdio.h>
//
//using namespace std;
//
//int main()
//{
// int a, b;
// while(scanf("%d%d", &a, &b) != EOF)
// {
// int ans = a;
// while(a >= b)
// {
// ans += a / b;
// a = a / b + a % b;
// //printf("%d\n", a);
// }
// printf("%d\n", ans);
// }
// return 0;
//}
//#include<math.h>
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//
//using namespace std;
//
//int main()
//{
// int T;
// scanf("%d", &T);
// while(T--)
// {
// int n;
// scanf("%d", &n);
// int m = (int )sqrt(n);
// bool flag = true;
// for(int i = 2; i <= m; i ++)
// if(n % i == 0) flag = false;
// if(flag) puts("Yes");
// else puts("No");
// }
// return 0;
//}
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//
//using namespace std;
//
//int main()
//{
// int n;
// while(scanf("%d", &n) != EOF)
// {
// char stone[55];
// scanf("%s", stone);
// int len = strlen(stone);
// int ans = 0;
// for(int i = 0; i < len - 1; i ++)
// if(stone[i] == stone[i + 1])
// ans ++;
// printf("%d\n", ans);
// }
// return 0;
//}
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//
//using namespace std;
//
//int main()
//{
// // freopen("test4.in", "r", stdin);
// // freopen("test4.out", "w", stdout);
// int matrix[205][205];
// int n;
// while(scanf("%d", &n) != EOF)
// {
// memset(matrix, 0, sizeof(matrix));
// matrix[0][n / 2] = 1;
// int x = 0, y = n / 2;
// int xx, yy;
// for(int i = 2; i <= n * n; i ++)
// {
// xx = x - 1;
// yy = y + 1;
// if(xx < 0) xx = n - 1;
// if(yy > n - 1) yy = 0;
// if(matrix[xx][yy])
// {
// xx = x + 1;
// yy = y;
// }
// matrix[xx][yy] = i;
// x = xx, y = yy;
// // printf("SSs %d %d %d\n", xx, yy, i);
// }
// for(int i = 0; i < n; i ++)
// for(int j = 0; j < n; j ++)
// printf("%d%c", matrix[i][j], j == n - 1? '\n' : ' ');
// puts("");
// }
// return 0;
//}
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//
//using namespace std;
//
//int main()
//{
// int a, b;
// while(scanf("%d%d", &a, &b) != EOF)
// {
// if(b == 0)
// {
// puts("-1");
// continue;
// }
// int ans = a / b;
// if(a % b) ans ++;
// printf("%d\n", ans);
// }
// return 0;
//}
#include<queue>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n, k;
char myMap[105][105];
int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
struct node
{
int x, y;
int time;
int num;
};
node s, e;
int BFS()
{
queue<node>q;
bool vis[105][105][(1 << 5) + 5] = {0};
q.push(s);
vis[s.x][s.y][s.num] = true;
while(q.size())
{
node h = q.front();
q.pop();
if(h.num == ((1 << k) - 1)) return h.time;
for(int i = 0; i < 4; i ++)
{
e.x = h.x + dir[i][0];
e.y = h.y + dir[i][1];
e.time = h.time + 1;
e.num = h.num;
if(e.x >= 0 && e.x < n && e.y >= 0 && e.y < n && myMap[e.x][e.y] != '#')
{
if(myMap[e.x][e.y] >= '0' && myMap[e.x][e.y] <= '5')
{
int key = 1 << (myMap[e.x][e.y] - '0');
e.num |= key;
}
if(vis[e.x][e.y][e.num]) continue;
vis[e.x][e.y][e.num] = true;
q.push(e);
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d", &n, &k) != EOF)
{
int cnt = 0;
for(int i = 0; i < n; i ++)
{
scanf("%s", myMap[i]);
for(int j = 0; j < n; j ++)
{
if(myMap[i][j] == '@')
{
s.x = i;
s.y = j;
s.time = 0;
s.num = 0;
}
if(myMap[i][j] == '1')
{
myMap[i][j] = cnt + '0';
cnt ++;
}
}
}
printf("%d\n", BFS());
}
return 0;
}
| true |
778d56b2154131818c69006be51960aef647bb1d | C++ | jeffery-cavallaro-cavcom/cavcom | /graph/libgraphalgo/hopcroft_test.cc | UTF-8 | 4,053 | 2.921875 | 3 | [] | no_license | // Runs the Hopcroft Tarjan component algorithm.
#include <libunittest/all.hpp>
#include "hopcroft.h"
using namespace cavcom::graph;
TEST(null_graph) {
SimpleGraph g(0);
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), 0);
UNITTEST_ASSERT_TRUE(hop.components().empty());
UNITTEST_ASSERT_EQUAL(hop.number(), 0);
}
TEST(trivial_graph) {
SimpleGraph g(1);
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), 1);
UNITTEST_ASSERT_EQUAL(hop.components().size(), 1);
UNITTEST_ASSERT_EQUAL(hop.number(), 1);
VertexNumbersList expected = {{0}};
UNITTEST_ASSERT_EQUAL_CONTAINERS(hop.components(), expected);
}
TEST(empty_graph) {
const VertexNumber ORDER = 10;
SimpleGraph g(ORDER);
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), 1);
UNITTEST_ASSERT_EQUAL(hop.components().size(), ORDER);
UNITTEST_ASSERT_EQUAL(hop.number(), ORDER);
VertexNumbersList expected;
for (VertexNumber iv = 0; iv < ORDER; ++iv) expected.push_back({iv});
UNITTEST_ASSERT_EQUAL_CONTAINERS(hop.components(), expected);
}
TEST(complete_graph) {
const VertexNumber ORDER = 10;
SimpleGraph g(ORDER);
g.make_complete();
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), ORDER);
UNITTEST_ASSERT_EQUAL(hop.components().size(), 1);
UNITTEST_ASSERT_EQUAL(hop.number(), 1);
VertexNumbersList expected;
expected.push_back(VertexNumbers());
for (VertexNumber iv = 0; iv < ORDER; ++iv) expected.back().insert(iv);
UNITTEST_ASSERT_EQUAL_CONTAINERS(hop.components(), expected);
}
static const VertexValuesList VERTICES = {{"a", NOCOLOR, 0, 2},
{"b", NOCOLOR, 2, 2},
{"c", NOCOLOR, 2, 0},
{"d", NOCOLOR, 0, 0},
{"e", NOCOLOR, 4, 2},
{"f", NOCOLOR, 6, 1},
{"g", NOCOLOR, 4, 0},
{"h", NOCOLOR, 8, 1},
{"i", NOCOLOR, 10, 1}};
static const EdgeValuesList EDGES = {{0, 1}, {0, 2}, {0, 3}, {0, 4},
{1, 2}, {1, 3}, {1, 4}, {1, 6},
{2, 3}, {2, 6},
{3, 6},
{4, 5}, {4, 6}, {4, 7},
{5, 6}, {5, 7},
{6, 7},
{7, 8}};
TEST(connected_graph) {
SimpleGraph g(VERTICES, EDGES);
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), g.order());
UNITTEST_ASSERT_EQUAL(hop.components().size(), 1);
UNITTEST_ASSERT_EQUAL(hop.number(), 1);
VertexNumbersList expected;
expected.push_back(VertexNumbers());
for (VertexNumber iv = 0; iv < g.order(); ++iv) expected.back().insert(iv);
UNITTEST_ASSERT_EQUAL_CONTAINERS(hop.components(), expected);
}
static const EdgeValuesList EDGES2 = {{0, 3}, {0, 8}, {3, 8}, {8, 6},
{1, 2}, {2, 7}, {7, 5}, {5, 1}};
static const VertexNumbersList COMPONENTS = {{0, 3, 6, 8}, {1, 2, 5, 7}, {4}};
TEST(disconnected_graph) {
SimpleGraph g(VERTICES, EDGES2);
Hopcroft hop(g);
UNITTEST_ASSERT_TRUE(hop.execute());
UNITTEST_ASSERT_EQUAL(hop.calls(), g.order());
UNITTEST_ASSERT_EQUAL(hop.maxdepth(), 4);
UNITTEST_ASSERT_EQUAL(hop.components().size(), COMPONENTS.size());
UNITTEST_ASSERT_EQUAL(hop.number(), COMPONENTS.size());
UNITTEST_ASSERT_EQUAL_CONTAINERS(hop.components(), COMPONENTS);
}
| true |
ee39225fc32024aa81f1c4d4c3317fce90becc9d | C++ | MyunghunSeong/CPlus | /step4.cpp | UHC | 6,598 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
//Account Class
class Account
{
char* id;
char* name;
double balance;
public:
Account() : id(NULL), name(NULL), balance(0) {};
Account(char* id, char* name, double balance);
virtual ~Account();
char* GetName();
char* GetId();
double GetBalance();
virtual void SetBalance(double balance);
virtual void ShowAllData();
};
Account :: Account(char* id, char* name, double balance=0)
{
this->id = new char[strlen(id) + 1];
strcpy(this->id, id);
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->balance = balance;
}
Account :: ~Account()
{
delete [] name;
delete [] id;
}
void Account :: ShowAllData()
{
cout << name << " " << endl;
cout << " ȣ: " << id << endl;
cout << " : " << balance << endl;
cout << endl;
}
char* Account :: GetName()
{
return name;
}
char* Account :: GetId()
{
return id;
}
double Account :: GetBalance()
{
return balance;
}
void Account :: SetBalance(double balance)
{
this->balance = balance;
} //End of Accout Class Area
//FaithAccount Class
class FaithAccount : public Account
{
public:
FaithAccount() {}
FaithAccount(char* id, char* name, double balance) : Account(id, name, balance) {}
virtual void SetBalance(double balance);
virtual void ShowAllData();
};
void FaithAccount :: SetBalance(double balance)
{
Account::SetBalance(balance += balance*0.01);
}
void FaithAccount :: ShowAllData()
{
Account::ShowAllData();
}//End of FaithAccount Class Area
//ContriAccount Class
class ContriAccount : public Account
{
double contriMoney;
public:
ContriAccount();
ContriAccount(char* id, char* name, double balance) : Account(id, name, balance) {}
virtual void SetBalance(double balance);
virtual void ShowAllData();
};
ContriAccount :: ContriAccount()
{
contriMoney = 0;
}
void ContriAccount :: ShowAllData()
{
Account::ShowAllData();
cout << " Ѿ : " << contriMoney << endl;
}
void ContriAccount :: SetBalance(double balance)
{
contriMoney = balance * 0.01;
Account::SetBalance(balance -= contriMoney);
}//End of ContriAccount Class Area
//AccManager Class
class AccManager
{
Account* acc[100];
static int idx;
int selection;
public:
AccManager() : selection(0) {};
~AccManager();
void inner_select_Account(int& selection);
void init();
void CreateAccount();
void CreateNormalAccount();
void CreateFaithAccount();
void CreateContriAccount();
void DepositAccount();
void WithdrawAccount();
void SearchAccount();
void inner_SelectAccount(int& type);
int GetSelection();
};
int AccManager ::idx = 0;
AccManager :: ~AccManager()
{
for(int i = 0; i < idx; i++)
{
delete [] acc[i];
}
}
void AccManager :: init()
{
cout << "===== =====" << endl;
cout << "1. " << endl;
cout << "2. " << endl;
cout << "3. " << endl;
cout << "4. ü ܾ ȸ" << endl;
cout << "Input : ";
cin >> selection;
cout << endl;
}
void AccManager :: inner_SelectAccount(int& type)
{
cout << "===== =====" << endl;
cout << "1. " << endl;
cout << "2. " << endl;
cout << "3. " << endl;
cin >> type;
cout << endl;
}
void AccManager :: CreateNormalAccount()
{
char name[30];
char id[30];
cout << "==== Ϲ ====" << endl;
cout << "̸ Է: ";
cin >> name;
cout << " Է: ";
cin >> id;
cout << endl;
acc[idx++] = new Account(name, id);
}
void AccManager :: CreateFaithAccount()
{
char name[30];
char id[30];
cout << "==== Ϲ ====" << endl;
cout << "̸ Է: ";
cin >> name;
cout << " Է: ";
cin >> id;
cout << endl;
acc[idx++] = new FaithAccount(name, id, 0);
}
void AccManager :: CreateContriAccount()
{
char name[30];
char id[30];
cout << "==== Ϲ ====" << endl;
cout << "̸ Է: ";
cin >> name;
cout << " Է: ";
cin >> id;
cout << endl;
acc[idx++] = new ContriAccount(name, id, 0);
}
void AccManager :: CreateAccount()
{
int accountType = 0;
inner_SelectAccount(accountType);
switch(accountType)
{
case 1:
CreateNormalAccount();
break;
case 2:
CreateFaithAccount();
break;
case 3:
CreateContriAccount();
break;
default:
cout << "߸ " << endl;
break;
}
}
void AccManager :: inner_select_Account(int& selection)
{
cout << "==== ====" << endl;
for(int i = 0; i < idx; i++)
{
cout << i+1 << ". " << "̸: " << acc[i]->GetName() << ' ' << " ȣ: " << acc[i]->GetId() << endl;
}
cin >> selection;
cout << endl;
}
void AccManager :: DepositAccount()
{
int money = 0;
int selection = 0;
double balance = 0;
inner_select_Account(selection);
cout << "==== ====" << endl;
cout << " ȣ: " << acc[selection - 1]->GetId() << endl;
cout << " : " << acc[selection - 1]->GetBalance() << endl;
cout << "==== Ա ====" << endl;
cout << "Ա ݾ Է: ";
cin >> money;
balance = acc[selection - 1]->GetBalance() + money;
acc[selection - 1]->SetBalance(balance);
cout << "==== Ա ܾ ====" << endl;
cout << " : " << acc[selection - 1]->GetBalance() << endl;
cout << endl;
}
void AccManager :: WithdrawAccount()
{
int money = 0;
int selection = 0;
double balance = 0;
inner_select_Account(selection);
cout << "==== ====" << endl;
cout << " ȣ: " << acc[selection - 1]->GetId() << endl;
cout << " : " << acc[selection - 1]->GetBalance() << endl;
cout << "==== ====" << endl;
cout << " ݾ Է: ";
cin >> money;
balance = acc[selection - 1]->GetBalance() + money;
acc[selection - 1]->SetBalance(balance);
cout << "==== ܾ ====" << endl;
cout << " : " << acc[selection - 1]->GetBalance() << endl;
cout << endl;
}
void AccManager :: SearchAccount()
{
cout << "==== ü ܾ ȸ ====" << endl;
for(int i = 0; i < idx; i++)
{
acc[i]->ShowAllData();
}
cout << endl;
}
int AccManager :: GetSelection()
{
return selection;
}//End of AccManager Class Area
int main()
{
AccManager manager;
while(true)
{
manager.init();
switch(manager.GetSelection())
{
case 1:
manager.CreateAccount();
break;
case 2:
manager.DepositAccount();
break;
case 3:
manager.WithdrawAccount();
break;
case 4:
manager.SearchAccount();
break;
default:
cout << "߸ " << endl;
break;
}
}
return 0;
} | true |
ed7fdfa45f4abc9c674b0413a1f6f5c8bfd7d30a | C++ | professor-4/DSA-Advanced | /01- Array/largestElementIndex.cpp | UTF-8 | 323 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
int lg = 0;
int index = 0;
int indexMax(int *arr){
for (int i=1; i<5; i++){
if (arr[i]>lg){
lg = arr[i];
index = i;
}
}
return index;
}
int main(){
int arr[5]= {1,5,4,6,2};
cout<<"Index of Maximum number is : "<<indexMax(arr);
}
| true |
3e78a04d49d37da853ae8c104b7b398298dbf896 | C++ | oerpli/ComputationalPhysics | /Thermostaten/src/Thermostat.h | UTF-8 | 410 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Polymer.h"
#include <string>
class Thermostat {
protected:
Polymer& m_poly;
double m_dtime;
public:
Thermostat(Polymer &poly, double delta_time);
double dtime() const;
virtual void dtime(double new_dtime);
virtual void update_temp() = 0; // für mögliche Erwärmung
virtual void propagate() = 0;
virtual std::string name() const = 0;
virtual std::string info() const = 0;
};
| true |
bca75181a3e2699449738d03ad81cc00b09b4c2a | C++ | nappij/WingLoft | /WingLoftTester/WingBuilderTest.cpp | UTF-8 | 10,682 | 2.734375 | 3 | [] | no_license | // ***************************
// * Introduction to C++ *
// ***************************
// Author: John Nappi
// Assignment: Final Project
// Date Due: Apr. 5, 2019
#include "FileName.h"
#include "Wing.h"
#include "WingBuilder.h"
#include "TestHarness.h"
// NOTE: The method buildWing() is tested in the MatlabWriterTest and VTKWriterTest files
// Global tolerance value
const static double TOL = 1.0e-5;
// *****************************************************************************
// Wing Builder Tester Class
// *****************************************************************************
// This class is a friend of the WingBuilder class, and exposes its private
// data and methods for testing.
class WingBuilderTester
{
public:
// Constructors
WingBuilderTester() = delete;
WingBuilderTester(const FileName& file) : wingBuilder(std::make_unique<WingBuilder>(file)) {};
// Destructor
virtual ~WingBuilderTester() = default;
// Wing Builder functions
void readPlanformFile() { wingBuilder->readPlanformFile(); }
void buildAirfoilStack() { wingBuilder->buildAirfoilStack(); }
void loftWing() { wingBuilder->loftWing(); }
void buildConnectivity() { wingBuilder->buildConnectivity(); }
// Getter functions
const FileName getFile() const { return wingBuilder->file; }
const int getNChord() { return wingBuilder->nChord; }
const std::vector<WingBuilder::WingStation> getWingStations() const { return wingBuilder->wingStations; }
const std::vector<Vector3> getGrids() const { return wingBuilder->grids; }
const std::vector<std::vector<int>> getConnectivity() const { return wingBuilder->connectivity; }
private:
std::unique_ptr<WingBuilder> wingBuilder;
};
// *****************************************************************************
// Test Wing
// *****************************************************************************
std::unique_ptr<Wing> testWingPtr;
// *****************************************************************************
// Test WingBuilder
// *****************************************************************************
const FileName wingFile(".\\test input\\test_planform.dat");
WingBuilderTester wingBuilderTester(wingFile);
// *****************************************************************************
// WingBuilder Constructor Test
// *****************************************************************************
TEST(constructor, WingBuilder)
{
CHECK_EQUAL(".\\test input\\test_planform.dat", wingBuilderTester.getFile().getFullName());
}
// *****************************************************************************
// WingBuilder Builder Tests
// *****************************************************************************
TEST(readPlanformFile, WingBuilder)
{
wingBuilderTester.readPlanformFile();
// Check nChords
CHECK_EQUAL(4, wingBuilderTester.getNChord());
// Check first planform line
CHECK_EQUAL("testfoil.dat", wingBuilderTester.getWingStations()[0].airfoilName);
CHECK_EQUAL(0.0, wingBuilderTester.getWingStations()[0].leadingEdgePoint.x);
CHECK_EQUAL(0.0, wingBuilderTester.getWingStations()[0].leadingEdgePoint.y);
CHECK_EQUAL(0.0, wingBuilderTester.getWingStations()[0].leadingEdgePoint.z);
CHECK_EQUAL(10.0, wingBuilderTester.getWingStations()[0].chord);
CHECK_EQUAL(-1.0, wingBuilderTester.getWingStations()[0].twist);
CHECK_EQUAL(2, wingBuilderTester.getWingStations()[0].nSpan);
// Check second planform line
CHECK_EQUAL("testfoil.dat", wingBuilderTester.getWingStations()[1].airfoilName);
CHECK_EQUAL(0.0, wingBuilderTester.getWingStations()[1].leadingEdgePoint.x);
CHECK_EQUAL(10.0, wingBuilderTester.getWingStations()[1].leadingEdgePoint.y);
CHECK_EQUAL(5.0, wingBuilderTester.getWingStations()[1].leadingEdgePoint.z);
CHECK_EQUAL(5.0, wingBuilderTester.getWingStations()[1].chord);
CHECK_EQUAL(3.0, wingBuilderTester.getWingStations()[1].twist);
CHECK_EQUAL(-1, wingBuilderTester.getWingStations()[1].nSpan);
}
TEST(buildAirfoilStack, WingBuilder)
{
wingBuilderTester.buildAirfoilStack();
// Check first airfoil
CHECK_DOUBLES_EQUAL(1.0, wingBuilderTester.getWingStations()[0].airfoil[0].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getWingStations()[0].airfoil[0].z, TOL);
CHECK_DOUBLES_EQUAL(0.75, wingBuilderTester.getWingStations()[0].airfoil[1].x, TOL);
CHECK_DOUBLES_EQUAL(-0.06, wingBuilderTester.getWingStations()[0].airfoil[1].z, TOL);
CHECK_DOUBLES_EQUAL(0.25, wingBuilderTester.getWingStations()[0].airfoil[2].x, TOL);
CHECK_DOUBLES_EQUAL(-0.06, wingBuilderTester.getWingStations()[0].airfoil[2].z, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getWingStations()[0].airfoil[3].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getWingStations()[0].airfoil[3].z, TOL);
CHECK_DOUBLES_EQUAL(0.25, wingBuilderTester.getWingStations()[0].airfoil[4].x, TOL);
CHECK_DOUBLES_EQUAL(0.06, wingBuilderTester.getWingStations()[0].airfoil[4].z, TOL);
CHECK_DOUBLES_EQUAL(0.75, wingBuilderTester.getWingStations()[0].airfoil[5].x, TOL);
CHECK_DOUBLES_EQUAL(0.06, wingBuilderTester.getWingStations()[0].airfoil[5].z, TOL);
CHECK_DOUBLES_EQUAL(1.0, wingBuilderTester.getWingStations()[0].airfoil[6].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getWingStations()[0].airfoil[6].z, TOL);
// Check one point of second airfoil since it should be the same.
CHECK_DOUBLES_EQUAL(0.25, wingBuilderTester.getWingStations()[1].airfoil[2].x, TOL);
CHECK_DOUBLES_EQUAL(-0.06, wingBuilderTester.getWingStations()[1].airfoil[2].z, TOL);
}
TEST(loftWing, WingBuilder)
{
wingBuilderTester.loftWing();
// Computing the expected values was done "by hand" in Excel. It was brutal.
// Check the first airfoil
CHECK_DOUBLES_EQUAL(9.99886, wingBuilderTester.getGrids()[0].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[0].y, TOL);
CHECK_DOUBLES_EQUAL(0.130893, wingBuilderTester.getGrids()[0].z, TOL);
CHECK_DOUBLES_EQUAL(7.50971, wingBuilderTester.getGrids()[1].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[1].y, TOL);
CHECK_DOUBLES_EQUAL(-0.512647, wingBuilderTester.getGrids()[1].z, TOL);
CHECK_DOUBLES_EQUAL(2.51047, wingBuilderTester.getGrids()[2].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[2].y, TOL);
CHECK_DOUBLES_EQUAL(-0.599909, wingBuilderTester.getGrids()[2].z, TOL);
CHECK_DOUBLES_EQUAL(0.000380762, wingBuilderTester.getGrids()[3].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[3].y, TOL);
CHECK_DOUBLES_EQUAL(-0.043631, wingBuilderTester.getGrids()[3].z, TOL);
CHECK_DOUBLES_EQUAL(2.48953, wingBuilderTester.getGrids()[4].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[4].y, TOL);
CHECK_DOUBLES_EQUAL(0.599909, wingBuilderTester.getGrids()[4].z, TOL);
CHECK_DOUBLES_EQUAL(7.48877, wingBuilderTester.getGrids()[5].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[5].y, TOL);
CHECK_DOUBLES_EQUAL(0.687171, wingBuilderTester.getGrids()[5].z, TOL);
CHECK_DOUBLES_EQUAL(9.99886, wingBuilderTester.getGrids()[6].x, TOL);
CHECK_DOUBLES_EQUAL(0.0, wingBuilderTester.getGrids()[6].y, TOL);
CHECK_DOUBLES_EQUAL(0.130893, wingBuilderTester.getGrids()[6].z, TOL);
// Check the intermediate airfoil
CHECK_DOUBLES_EQUAL(7.49686, wingBuilderTester.getGrids()[7].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[7].y, TOL);
CHECK_DOUBLES_EQUAL(2.46732, wingBuilderTester.getGrids()[7].z, TOL);
CHECK_DOUBLES_EQUAL(5.62029, wingBuilderTester.getGrids()[8].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[8].y, TOL);
CHECK_DOUBLES_EQUAL(2.02846, wingBuilderTester.getGrids()[8].z, TOL);
CHECK_DOUBLES_EQUAL(1.87239, wingBuilderTester.getGrids()[9].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[9].y, TOL);
CHECK_DOUBLES_EQUAL(2.05025, wingBuilderTester.getGrids()[9].z, TOL);
CHECK_DOUBLES_EQUAL(0.00104692, wingBuilderTester.getGrids()[10].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[10].y, TOL);
CHECK_DOUBLES_EQUAL(2.51089, wingBuilderTester.getGrids()[10].z, TOL);
CHECK_DOUBLES_EQUAL(1.87761, wingBuilderTester.getGrids()[11].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[11].y, TOL);
CHECK_DOUBLES_EQUAL(2.94975, wingBuilderTester.getGrids()[11].z, TOL);
CHECK_DOUBLES_EQUAL(5.62552, wingBuilderTester.getGrids()[12].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[12].y, TOL);
CHECK_DOUBLES_EQUAL(2.92796, wingBuilderTester.getGrids()[12].z, TOL);
CHECK_DOUBLES_EQUAL(7.49686, wingBuilderTester.getGrids()[13].x, TOL);
CHECK_DOUBLES_EQUAL(5.0, wingBuilderTester.getGrids()[13].y, TOL);
CHECK_DOUBLES_EQUAL(2.46732, wingBuilderTester.getGrids()[13].z, TOL);
// Check the last airfoil
CHECK_DOUBLES_EQUAL(4.99486, wingBuilderTester.getGrids()[14].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[14].y, TOL);
CHECK_DOUBLES_EQUAL(4.80374, wingBuilderTester.getGrids()[14].z, TOL);
CHECK_DOUBLES_EQUAL(3.73087, wingBuilderTester.getGrids()[15].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[15].y, TOL);
CHECK_DOUBLES_EQUAL(4.56957, wingBuilderTester.getGrids()[15].z, TOL);
CHECK_DOUBLES_EQUAL(1.2343, wingBuilderTester.getGrids()[16].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[16].y, TOL);
CHECK_DOUBLES_EQUAL(4.70041, wingBuilderTester.getGrids()[16].z, TOL);
CHECK_DOUBLES_EQUAL(0.00171308, wingBuilderTester.getGrids()[17].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[17].y, TOL);
CHECK_DOUBLES_EQUAL(5.06542, wingBuilderTester.getGrids()[17].z, TOL);
CHECK_DOUBLES_EQUAL(1.2657, wingBuilderTester.getGrids()[18].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[18].y, TOL);
CHECK_DOUBLES_EQUAL(5.29959, wingBuilderTester.getGrids()[18].z, TOL);
CHECK_DOUBLES_EQUAL(3.76227, wingBuilderTester.getGrids()[19].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[19].y, TOL);
CHECK_DOUBLES_EQUAL(5.16875, wingBuilderTester.getGrids()[19].z, TOL);
CHECK_DOUBLES_EQUAL(4.99486, wingBuilderTester.getGrids()[20].x, TOL);
CHECK_DOUBLES_EQUAL(10.0, wingBuilderTester.getGrids()[20].y, TOL);
CHECK_DOUBLES_EQUAL(4.80374, wingBuilderTester.getGrids()[20].z, TOL);
}
TEST(buildConnectivity, WingBuilder)
{
wingBuilderTester.buildConnectivity();
// Just check the connectivity table between the first two airfoils
// Computing the expected values was done "by hand" in Excel. It was brutal.
std::string expected("0 1 8 7 1 2 9 8 2 3 10 9 3 4 11 10 4 5 12 11 5 6 13 12 ");
std::stringstream actual;
for (size_t i = 0; i < 6; ++i)
for (size_t j = 0; j < 4; ++j)
actual << wingBuilderTester.getConnectivity()[i][j] << " ";
CHECK_EQUAL(expected, actual.str());
} | true |
64f61dfbefbc398050b17bb24de1a60813a44aee | C++ | zhyule/data-structure | /dsacpp/list/list_radixSort.h | GB18030 | 793 | 2.828125 | 3 | [] | no_license | #pragma once
typedef unsigned int U;
template <typename T>
void List<T>::radixSort(ListNodePosi<T> p,
int n) { // valid(p) && rank(p) + n <= size
ListNodePosi<T> head = p->pred;
ListNodePosi<T> tail = p;
for (int i = 0; i < n; i++) {
tail = tail->succ;
}
for (U radixBit = 0x1; radixBit && (p = head); radixBit <<= 1) {
for (int i = 0; i < n; i++) {
radixBit& U(p->succ->data) ? insert(remove(p->succ), tail) : p = p->succ;
}
}
}
//˼ij˷ּǰûб仯Ƿ漴㷨
//ĽǰҳԪزЧλӶʡõķּ
//ĽΪremove()insertB()ĵЧʣʵList::moveB(t,p)ӿڣڵpƶt֮ǰ
| true |
efb439ac0a5d31289d2770e690aa10444021c166 | C++ | mreinecker/SchoolCalendar | /main.cpp | UTF-8 | 3,582 | 4.09375 | 4 | [] | no_license | #include <iostream>
#include "Calendar.h"
int main() {
Calendar calendar; // instantiate calender object for use below
bool enter = true; // used to enter while loop below
while(enter) {
// display menu
std::cout << "\nHello!"
<< "\nWelcome to the school calendar"
<< "\nPlease login as a (1)student or (2)teacher"
<< "\nEnter a choice (1 or 2) and hit enter:\t"
<< std::endl;
int choice{0};
std::cin >> choice; // get menu choice
switch (choice) {
case 1: {
// student
std::cout << "\nThe current semester date is: "
<< calendar
<< std::endl;
// ask for days to increment into semester, initialized to 1/1/1
std::cout << "\nHow many days would you like to advance the calendar?"
<< "\nEnter a number in days:\t"
<< std::endl;
int day_increment{0};
std::cin >> day_increment;
// call date increment function
calendar.incrementDate(day_increment);
// display new semester date
std::cout << "\nThe new current semester date is: "
<< calendar
<< std::endl;
// warn student if warner enabled and date matches by calling function
// function will not return warning if not enabled through teacher menu
calendar.warnStudent();
// allow to get back into menu or exit
std::cout << "\n(1)Main Menu \n(2)Exit"
<< "\nEnter a choice (1 or 2) and hit enter:\t"
<< std::endl;
int enter_choice{0};
std::cin >> enter_choice;
enter = enter_choice == 1 ? true : false;
break;
}
case 2: {
// teacher
std::cout << "\nThe current semester date is: "
<< calendar
<< std::endl;
// allow teacher to increment semester days
std::cout << "\nHow many days would you like to advance the calendar?"
<< "\nEnter a number in days:\t"
<< std::endl;
int day_increment{0};
std::cin >> day_increment;
calendar.incrementDate(day_increment);
// display new semester date after incrementing
std::cout << "\nThe new current semester date is: "
<< calendar
<< std::endl;
// allow teacher to set warning
std::cout << "\nWould you like to set a warning for students?"
<< "\nThe warning will notify when the last day is to drop a class"
<< "\nEnter (1) to enable warning and \n(2) to proceed without setting a warning:\t"
<< std::endl;
// get menu choice
int w_choice{0};
std::cin >> w_choice;
if (w_choice == 1) {
// set warner
calendar.setWarner(true);
int day{0};
int week{0};
int month{0};
std::cout << "\nPlease enter the semester month, week and day to warn students:\t"
<< std::endl;
std::cout << "\nMonth:\t" << std::endl;
std::cin >> month;
std::cout << "\nWeek:\t" << std::endl;
std::cin >> week;
std::cout << "\nDay:\t" << std::endl;
std::cin >> day;
calendar.setWarnerDate(month, week, day);
std::cout << "\nWarning set successfully!"
<< std::endl;
}
// allow to go back to menu
std::cout << "\n(1)Main Menu \n(2)Exit"
<< "\nEnter a choice (1 or 2) and hit enter:\t"
<< std::endl;
int enter_choice{0};
std::cin >> enter_choice;
enter = enter_choice == 1 ? true : false;
break;
}
default: {
std::cout << "\nInvalid entry, please try again."
<< std::endl;
}
}
}
return 0;
} | true |
6afcb5fd9ed99b1bd9f91a34656a35f2f666f73b | C++ | lawtonsclass/f20-code-from-class | /csci40/lec21/fact.cpp | UTF-8 | 661 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
// returns n!
int fact(int n) {
if (n == 1) {
// base case
// 1! = 1
return 1;
} else {
// recursive case
// n! = n * (n-1)!
return n * fact(n - 1);
// you get to *assume* (without thinking about it!) that fact(n-1)
// correctly computes (n-1)!
// All you have to worry about is building up the bigger answer
// with that!!!
}
}
// iterative version of factorial:
int fact_iterative(int n) {
int res = 1;
for (int i = n; i >= 1; i--) {
res = res * i;
}
return res;
}
int main() {
cout << fact(5) << endl;
cout << fact_iterative(5) << endl;
return 0;
}
| true |
8bf076cc18b468b2495139b3197a07cc9f52ac24 | C++ | jzou2000/codex | /stl/stl-async2.cpp | UTF-8 | 3,092 | 3.53125 | 4 | [] | no_license | /***************************************************************************
This is a simple demonstration of multiple-threading with future/async.
The difference with stl-async.cpp is that a function object is used
to launch a thread.
The function object can be passed by value or by reference. See the
output of the program. It seems that by reference is appreciated in
most cases.
Program output:
-------- AsyncApp.first(1) is created
-------- AsyncApp.second(2) is created
launch two threads
-------- AsyncApp.first(3<=1) is created
-------- AsyncApp.first(4<=3) is created
-------- AsyncApp.first(3<=1) is deleted
AsyncApp.second(2) is called:
AsyncApp.first(4<=3) is called:
CEget final result
CEECEECCCCEECCECEE-------- AsyncApp.first(4<=3) is deleted
result: 6
-------- AsyncApp.second(2) is deleted
-------- AsyncApp.first(1) is deleted
***************************************************************************/
#include <future>
#include <chrono>
#include <random>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <exception>
using namespace std;
class AsyncApp {
public:
// constructor, copy constructor and destructor
// are used to trace object life.
AsyncApp(string name) : name(name) {
id = seed++;
ostringstream os;
os << "AsyncApp." << name << "(" << id << ")";
name_id = os.str();
cout << "-------- " << name_id << " is created" << endl;
}
AsyncApp(const AsyncApp& a) {
id = seed++;
name = a.name;
ostringstream os;
os << "AsyncApp." << a.name << "(" << id << "<=" << a.id << ")";
name_id = os.str();
cout << "-------- " << name_id << " is created" << endl;
}
virtual ~AsyncApp() {
cout << "-------- " << name_id << " is deleted" << endl;
}
// overload operator () to make function object
// this is the actual thread entrance
int operator () () {
cout << name_id << " is called: " << endl;
std::default_random_engine dre(id);
std::uniform_int_distribution<int> d(10, 1000);
for (auto i = 0; i < 10; ++i) {
this_thread::sleep_for(chrono::milliseconds(d(dre)));
cout.put('A' + id).flush();
}
return id;
}
protected:
static int seed;
int id;
string name;
string name_id;
};
int AsyncApp::seed = 1;
int main()
{
AsyncApp a1("first");
AsyncApp a2("second");
try {
cout << "launch two threads" << endl;
// launch by value, so the object is copied twice (by async)
// i.e. two temp objects are created/deleted
std::future<int> result1(std::async(launch::async, a1));
// launch by ref, no temp object is created/deleted
std::future<int> result2(std::async(launch::async, ref(a2)));
this_thread::sleep_for(chrono::milliseconds(100));
cout << "get final result" << endl;
int result = result1.get() + result2.get();
cout << endl << "result: " << result << endl;
}
catch (exception& e) {
cout << endl << "exception: " << e.what() << endl;
}
catch (...) {
cout << endl << "exception caugth" << endl;
}
return 0;
}
| true |
a34c12964fe853fd6220e4a5a7147141bd327a91 | C++ | chungbwc/vart3157 | /Class02g/Class02g.ino | UTF-8 | 599 | 3.28125 | 3 | [] | no_license | //
// Use 5 LED lights at digital pins:
// 8, 9, 10, 11, 12
// and generate a sequential animation pattern.
//
const int COUNT = 5;
int light[COUNT] = {8, 9, 10, 11, 12};
int index;
void setup() {
index = 0;
pinMode(light[0], OUTPUT);
pinMode(light[1], OUTPUT);
pinMode(light[2], OUTPUT);
pinMode(light[3], OUTPUT);
pinMode(light[4], OUTPUT);
}
void loop() {
for (int i = 0; i < COUNT; i++) {
if (i == index) {
digitalWrite(light[i], HIGH);
} else {
digitalWrite(light[i], LOW);
}
}
index = index + 1;
if (index >= COUNT)
index = 0;
delay(100);
}
| true |
f1c7abd0877e8fb77327dc648b5f1b1410ad6e5c | C++ | andersonbrands/Gamedev_Framework | /GamedevFramework/GamedevFramework/src/Framework/Utilities/Timer.h | UTF-8 | 2,573 | 2.703125 | 3 | [] | no_license | /***************************************************************************************
* Title: Timer.h
* Author: Brandao, Anderson
* Date: 2014
*
* Based on original by Bruce Sutherland available at http://www.apress.com/9781430258308 (2014)
*
***************************************************************************************/
#ifndef TIMER_H_
#define TIMER_H_
#include "../Wrapper.h"
#include "../EventManager/EventHandler.h"
#include "../Utilities/Singleton.h"
namespace Framework {
class Timer : public wTimer, public EventHandler, public Singleton<Timer> {
public:
Timer(const unsigned int priority);
virtual ~Timer();
// task interface
virtual bool start();
virtual void onSuspend();
virtual void update();
virtual void onResume();
virtual void stop();
// timer interface
virtual float getTimeFrame() const;
virtual float getTimeSim() const;
virtual void setSimMultiplier(const float simMultiplier);
virtual float getSimMultiplier();
virtual float getFPS() const;
virtual float getGameTime() const;
virtual TimeUnits getUpdateFrame() const;
virtual void handleEvent(Event* pEvent);
const int UPDATES_PER_SECOND;
private:
TimeUnits timeLastFrame_;
int frameDt_;// delta frame in miliseconds
float simulationMultiplier_;
TimeUnits gameTime_;// game time in miliseconds
// used to have a fixed frame rate
long long currentUpdate_;
long long nextUpdate_;
};
inline float Timer::getFPS() const {
return 1000.0f / (float)frameDt_;
}
// get total game time in seconds
inline float Timer::getGameTime() const {
const float MILI_TO_SECONDS_MULTIPLIER = 0.001f;
return gameTime_ * MILI_TO_SECONDS_MULTIPLIER;
}
// get delta frame in seconds
inline float Timer::getTimeFrame() const {
const float MILI_TO_SECONDS_MULTIPLIER = 0.001f;
return frameDt_ * MILI_TO_SECONDS_MULTIPLIER;
}
// get delta simulation time in seconds
inline float Timer::getTimeSim() const {
return getTimeFrame() * simulationMultiplier_;
}
inline void Timer::setSimMultiplier(const float simMultiplier) {
simulationMultiplier_ = simMultiplier;
}
inline float Timer::getSimMultiplier() {
return simulationMultiplier_;
}
}
#endif // TIMER_H_
| true |
f457a369167f667485ccd3835625e71b66ec6d6c | C++ | blueoyw/study_c- | /list.cpp | UTF-8 | 1,427 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <memory>
#include <array>
using namespace std;
class Node {
public:
Node():_next(NULL) {}
Node(int i):_num(i), _next(NULL) {}
int _num;
Node* _next;
};
template<class T>
class List {
public:
List<T>() : _size(0)
{
_head = new T();
}
~List()
{
if( _size > 0 ) {
T* node = _head->_next;
for( int i=0; i<_size; i++ ) {
Node* tmp = node->_next;
delete node;
node = tmp;
}
}
delete _head;
}
int size()
{
return _size;
}
void push_back( T node )
{
T* add = new T();
*add = node;
T* tmp = _head;
for( int i=0; i<_size; i++ ) {
tmp = tmp->_next;
}
add->_next = tmp->_next;
tmp->_next = add;
_size++;
}
T* get(int index)
{
T* tmp = _head->_next;
for( int i=0; i<index; i++ ) {
tmp = tmp->_next;
}
return tmp;
}
void pop_front()
{
cout << "pop" << endl;
if( _size > 0 ) {
T* tmp = _head->_next;
_head->_next = tmp->_next;
delete tmp;
_size--;
}
}
private:
int _size;
T* _head;
};
int main()
{
Node n1(1);
Node n2(2);
List<Node> list;
list.push_back(n1);
cout << "size="<< list.size() << endl;
list.push_back(n2);
cout << "size="<< list.size() << endl;
Node* tmp = list.get(0);
cout << "num="<<tmp->_num << endl;
tmp = list.get(1);
cout << "num="<<tmp->_num << endl;
list.pop_front();
cout << list.size() << endl;
list.pop_front();
cout << list.size() << endl;
return 0;
}
| true |
9c2ebc680286dffb2d26636c75f67ca75e115f85 | C++ | WhereIsLucas/worldSim | /World.cpp | UTF-8 | 2,900 | 3.328125 | 3 | [] | no_license | //
// Created by lucas on 07.05.21.
//
#include <cstdlib>
#include <random>
#include "World.h"
#include "creatures/Prey.h"
#include "creatures/Predator.h"
World::World(double x, double y) : x(x), y(y) {
World::x = x;
World::y = y;
}
void World::addCreature(Creature &creature) {
World::creatures.push_back(&creature);
}
void World::addNewCreature(Creature &creature){
World::newCreatures.push_back(&creature);
}
void World::clearNewCreature(){
World::newCreatures.clear();
}
unsigned long World::getNewCreaturesCount() {
return World::newCreatures.size();
}
void World::appendVec(){
World::creatures.insert(creatures.end(), newCreatures.begin(), newCreatures.end());
}
unsigned long World::getCreaturesCount() {
return World::creatures.size();
}
unsigned long World::getPreysCount() {
unsigned long count = 0;
for (int i = 0; i < this->getCreaturesCount(); ++i) {
auto creature = this->getCreature(i);
if (creature->getType() == "prey") {
count++;
}
}
return count;
}
unsigned long World::getPredatorsCount() {
unsigned long count = 0;
for (int i = 0; i < this->getCreaturesCount(); ++i) {
auto creature = this->getCreature(i);
if (creature->getType() == "predator") {
count++;
}
}
return count;
}
Creature* World::getCreature(int index) {
return World::creatures[index];
}
double World::getX() const {
return x;
}
double World::getY() const {
return y;
}
void World::prepareFood(int foodQuantity) {
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> dis(-.5, .5);
for (int i = 0; i < foodQuantity; ++i) {
auto position = Vector2(this->getX() * dis(gen),
this->getY() * dis(gen));
auto foodItem = new FoodPlant(position);
foodItem->setIndex(i);
World::addFoodItem(*foodItem, i);
}
}
void World::clearFood() {
World::foodItems.clear();
}
std::vector<FoodPlant> &World::getFoodItems() {
return foodItems;
}
void World::removeCreature(int index) {
World::creatures.erase(World::creatures.begin() + index);
}
void World::setCreatureAsEaten(int index){
auto creature = World::getCreature(index);
creature->setEaten(true);
}
void World::removeFoodItem(int index) {
// World::foodItems.erase(World::foodItems.begin() + index);
// for (int i = 0; i < World::getFoodItems().size(); ++i) {
// auto item = World::getFoodItems()[i];
// item.setIndex(i);
// }
}
void World::setX(double newX) {
World::x = newX;
}
void World::setY(double newY) {
World::y = newY;
}
void World::addFoodItem(FoodPlant foodItem, int index) {
World::foodItems.push_back(foodItem);
}
| true |
e3d0be3ec8d3ed5aeb006020fab39480cc44b2f4 | C++ | Enoch09/GameProject | /0306/0306/ex69.cpp | UHC | 681 | 3.609375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Circle {
int radius;
public:
void setRadius(int r);
int getRadius();
double getArea();
};
void Circle::setRadius(int r) {
radius = r;
}
int Circle::getRadius() {
return radius;
}
double Circle::getArea() {
return radius * radius*3.14;
}
int main() {
int n,r, cnt=0;
Circle *p;
cout << "Number of Circle>> ";
cin >> n;
p = new Circle[n]; // n ũ 迭 Ҵ
for (int x = 0; x < n; x++){
cout << "Circle " << x + 1 << " radius";
cin >> r;
p[x].setRadius(r);
}
for (int y = 0; y < n; y++) {
if ( p[y].getArea() > 100) {
cnt++;
}
}
cout << "result: " << cnt << endl;
} | true |
b604a4a4b3f78ffbba8dc95d6273e1f6b24e44e8 | C++ | OmkarRatnaparkhi/Basic_Cpp_Programs | /Problems_on_numbers/Q10_EvenOdd/Main.cpp | UTF-8 | 536 | 3.9375 | 4 | [] | no_license | /*
Problem statement : Accept number from user and check whether number is even or
odd.
*/
using namespace std;
#include<iostream>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
BOOL EvenOdd(int iNo)
{
if((iNo % 2) == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main()
{
int iValue = 0 , iRet = FALSE;
cout<<"Enter the number"<<"\n";
cin>>iValue;
iRet = EvenOdd(iValue);
if(iRet == TRUE)
{
cout<<iValue<<" number is EVEN"<<"\n";
}
else
{
cout<<iValue<<" number is ODD"<<"\n";
}
return 0;
}
| true |
8c78fb42e69d84dc573cdf2ebd716df5895b66d2 | C++ | MaxSimpson/Exploring-Graphics | /Material.h | UTF-8 | 1,826 | 2.765625 | 3 | [] | no_license | #ifndef _MATERIAL_H_
#define _MATERIAL_H_
// Includes
#include "GLInclude.h"
#include <fstream>
#include <sstream>
#include <memory>
#include "Image.h"
////////////////////////////////////////////////////////////////////////////////
/// @class Class for storing materials
////////////////////////////////////////////////////////////////////////////////
class Material{
public:
////////////////////////////////////////////////////////////////////////////
/// @brief Constructor for material
/// @param _name The name of the material
/// @param _kd Diffuse value for materials
/// @param _ka Ambient value for materials
/// @param _ks Specular value for materials
/// @param image_tag Image tag for diffuse map
Material(std::string _name, glm::vec3 _kd, glm::vec3 _ka, glm::vec3 _ks,
std::string image_tag);
////////////////////////////////////////////////////////////////////////////
/// @brief 2nd constructor for material
Material(const Material &_oldMat);
////////////////////////////////////////////////////////////////////////////
/// @brief Initialization
void Initialize();
////////////////////////////////////////////////////////////////////////////
/// @brief Drawing of material
/// @param _program Shader program for rendering
void Draw(GLuint _program);
private:
glm::vec3 ka; //< Ambient factor
glm::vec3 ks; //< Specular factor
glm::vec3 kd; //< Diffuse factor
std::string mat_name; //< Material
std::string image_tag; //< Texture location
std::unique_ptr<Image> image; //< Texture
GLuint texture{0}; //< GL Image storage
////////////////////////////////////////////////////////////////////////////
/// @brief Parse data
void Parse (const std::string& location);
};
#endif
| true |
ac7a1aacbd3a4801f98c1e15e7ab083baa31fbc8 | C++ | utkarsh914/LeetCode | /Stack, queue, pq/1675. minimize-deviation-in-array.cpp | UTF-8 | 452 | 3.265625 | 3 | [] | no_license | // https://leetcode.com/problems/minimize-deviation-in-array/
class Solution {
public:
int minimumDeviation(vector<int>& A) {
set<int> s;
for (int &a : A)
s.insert(a % 2 ? a * 2 : a); // insert max possible val of each element
int res = *s.rbegin() - *s.begin();
while (*s.rbegin() % 2 == 0) {
s.insert(*s.rbegin() / 2);
s.erase(*s.rbegin());
res = min(res, *s.rbegin() - *s.begin());
}
return res;
}
}; | true |
5239ff6d064eae273adbeac525869c919e046915 | C++ | sarthak11yadav/Competitive-Programming | /Leetcode/Array/1053. Previous Permutation With One Swap.cpp | UTF-8 | 559 | 2.65625 | 3 | [] | no_license | class Solution {
public:
vector<int> prevPermOpt1(vector<int>& a) {
for(int n=a.size()-1;n>=1;n--){
if(a[n]<a[n-1]){
int val=-1;int k=0;
for(int j=n;j<=a.size()-1;j++){
if(val<a[j] && a[j]<a[n-1]){
val=a[j];
k=j;
}
}
int m=a[n-1];
a[n-1]=a[k];a[k]=m;
cout<<n-1<<" "<<k<<endl;
break;
}
}
return a;
}
};
| true |
e5c107d4a76a87a74f85f3744c9f6a4f8c2c6b10 | C++ | sercami97/EstacionMeteorologica | /CodigoArduino/PruebaHallSensor/PruebaHallSensor.ino | UTF-8 | 1,296 | 2.609375 | 3 | [] | no_license | /*
KeyPressed on PIN1
by Mischianti Renzo <http://www.mischianti.org>
https://www.mischianti.org/2019/01/02/pcf8574-i2c-digital-i-o-expander-fast-easy-usage/
*/
#include "Arduino.h"
#include "PCF8574.h"
// Set i2c address
PCF8574 pcf8574(0x20);
unsigned long timeElapsed;
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.println("Begin");
pcf8574.pinMode(P0, INPUT_PULLUP);
pcf8574.pinMode(P1, INPUT_PULLUP);
pcf8574.pinMode(P2, INPUT_PULLUP);
pcf8574.pinMode(P3, INPUT_PULLUP);
pcf8574.pinMode(P4, INPUT_PULLUP);
pcf8574.pinMode(P5, INPUT_PULLUP);
pcf8574.pinMode(P6, INPUT_PULLUP);
pcf8574.pinMode(P7, INPUT_PULLUP);
Serial.print("Init pcf8574...");
if (pcf8574.begin()){
Serial.println("OK");
}else{
Serial.println("KO");
}
}
void loop()
{
if(!pcf8574.digitalRead(P0)) Serial.println("KEY 1 PRESSED");
if(!pcf8574.digitalRead(P1)) Serial.println("KEY 2 PRESSED");
if(!pcf8574.digitalRead(P2)) Serial.println("KEY 3 PRESSED");
if(!pcf8574.digitalRead(P3)) Serial.println("KEY 4 PRESSED");
if(!pcf8574.digitalRead(P4)) Serial.println("KEY 5 PRESSED");
if(!pcf8574.digitalRead(P5)) Serial.println("KEY 6 PRESSED");
if(!pcf8574.digitalRead(P6)) Serial.println("KEY 7 PRESSED");
if(!pcf8574.digitalRead(P7)) Serial.println("KEY 8 PRESSED");
}
| true |
9f6c9085009ae66ee966e072a6e907edc287a7a1 | C++ | burkell530/Cpp-Programming-Class | /csci211/shippingRoutes/stree.h | UTF-8 | 2,261 | 3.1875 | 3 | [] | no_license | #ifndef STREE_H
#define STREE_H
#include <vector>
#include <string>
class Stree
{
public:
Stree();
void countChild(int &, int &, int &);
bool insert(std::string p_orgin ,std::string p_dest, int p_dis);
bool insertNode(std::string p_orgin ,std::string p_dest, int p_dis);
bool deleteNode(std::string p_value);
std::vector<std::string> lookup(std::string p_value, std::vector<int>&);
std::vector<std::string> path(std::string p_start, std::string p_end);
bool distNodes(std::string p_one, std::string p_two, int&);
~Stree();
protected:
private:
class Node
{
public:
std::string value;
Node* ptrParent;
Node* ptrLeft;
Node* ptrRight;
int distance;
Node(std::string p_value,int p_distance, Node* p_ptrParent, Node* p_ptrLeft, Node* p_ptrRight)
{
value = p_value;
distance = p_distance;
ptrParent = p_ptrParent;
ptrLeft = p_ptrLeft;
ptrRight = p_ptrRight;
}
~Node()
{
delete ptrLeft;
delete ptrRight;
ptrLeft = NULL;
ptrRight = NULL;
ptrParent = NULL;
}
};
Node* root;
Node* findNode(Node* p_current, std::string p_target)
{
Node* temp = NULL;
if(p_current->value == p_target) temp = p_current;
else
{
if(p_current -> ptrLeft == NULL && p_current -> ptrRight == NULL) temp == NULL;
if(p_current -> ptrLeft != NULL) temp = findNode(p_current->ptrLeft, p_target);
if(temp == NULL && p_current -> ptrRight != NULL) temp = findNode(p_current->ptrRight, p_target);
}
return temp;
};
void countChild(int &, int &, int &, Node*);
void findPath(Node * ,Node *, std::vector<std::string> &);
void findDist(Node * ,Node *, int&);
};
#endif // STREE_H
| true |
18fc0510f6140ac733a4af5f748f087b36c4fb61 | C++ | Icay12/LeetCode | /Cpp/376_WiggleSubsequence.cpp | UTF-8 | 1,238 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() == 0 || nums.size() == 1)
return (int)nums.size();
int result = 1;
int k = 1;
while(k < nums.size() && nums[k] == nums[k-1])
++k;
if(k >= nums.size())
return 1;
vector<int> res;
res.push_back(nums[0]);
res.push_back(nums[k]);
bool issmaller = (nums[k] < nums[0]);
for(k = k+1; k < nums.size(); ++k) {
if(nums[k] > res[result]) {
if(issmaller) {
res.push_back(nums[k]);
result+=1;
issmaller = !issmaller;
}
else {
res[result] = max(res[result], nums[k]);
}
}
if(nums[k] < nums[k-1]) {
if(!issmaller) {
res.push_back(nums[k]);
result+=1;
issmaller = !issmaller;
}
else {
res[result] = min(res[result], nums[k]);
}
}
}
return result+1;
}
}; | true |
3d33a02cef8858245bd2510e80787a75326e848c | C++ | hsishengmei/tds | /test/testSortedList.cpp | UTF-8 | 1,904 | 2.6875 | 3 | [] | no_license | #include "../src/SortedList.h"
#include "../src/Node.h"
#include "omp.h"
#include <vector>
#include <random>
#define RANGE_MIN 1
#define RANGE_MAX 400000
#define PREINSERT_SIZE 40000
bool _debug = false;
std::vector<int> genRandInt(int sz, int mn, int mx) {
std::random_device rd;
std::uniform_int_distribution<int> dist(mn, mx);
std::vector<int> v;
v.reserve(sz);
for (int n = 0; n < sz; ++n) {
v.push_back(dist(rd));
}
return v;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
printf("usage: ./test [nWorkload] [WorkloadType]\n");
printf("WorkloadType: PURE_READ=0 PURE_WRITE=1 MIXED=2\n");
return 0;
}
int nWorkload = atoi(argv[1]);
int WorkloadType = atoi(argv[2]);
SortedList<Node, int> sl;
// pre insert some nodes
printf("pre insert %d nodes\n", PREINSERT_SIZE);
auto v = genRandInt(PREINSERT_SIZE,RANGE_MIN,RANGE_MAX);
for (int i : v) sl.insert(i);
printf("txsl size: %d\n", sl.size);
// _debug = true;
auto v2 = genRandInt(nWorkload,RANGE_MIN,RANGE_MAX);
// test
double start = omp_get_wtime();
int totalAborts = 0;
int abortCount = 0;
for (int i=0; i<nWorkload; ++i) {
abortCount = 0;
switch (WorkloadType)
{
case 0:
sl.find(v2[i]);
break;
case 1:
if (i%2) sl.insert(v2[i]);
else sl.remove(v[i]);
break;
case 2:
if (i%4==1) sl.insert(v2[i]);
else if (i%4==3) sl.remove(v[i]);
else sl.find(v2[i]);
break;
}
totalAborts += abortCount;
}
double elapsedTime = omp_get_wtime() - start;
printf("elapsed time: %lf seconds\n", elapsedTime);
printf("throughput: %lf ops/seconds\n", 1.0*nWorkload/elapsedTime);
printf("txsl size: %d\n", sl.size);
} | true |
92e6a2c16186626e76abbb1a05fcf2fb2d9dd9d2 | C++ | abarankab/competitive-programming | /region_d5_A/region_d5_A/region_d5_A.cpp | UTF-8 | 1,822 | 2.65625 | 3 | [] | no_license | // region_d5_A.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<pair<int, char> > cnt;
vector<int> count(26);
for (int i = 0; i < n; ++i)
{
++count[s[i] - 'a'];
}
for (int i = 0; i < 26; ++i)
{
cnt.push_back({ count[i], 'a' + i });
}
vector<queue<char> > change(26);
for (int asd = 0; asd < k; ++asd)
{
int mxr = -1;
int initial = -1;
for (int i = 0; i < 26; ++i)
{
for (int j = 0; j < 26; ++j)
{
if (cnt[i].first != 0 && cnt[j].first != 0)
{
mxr = max(abs(cnt[i].first - cnt[j].first), mxr);
}
}
}
initial = mxr;
pair<char, char> res_now;
for (char from = 'a'; from <= 'z'; ++from)
{
for (char to = 'a'; to <= 'z'; ++to)
{
if (from != to && cnt[from - 'a'].first != 0)
{
cnt[from - 'a'].first--;
cnt[to - 'a'].first++;
int cur_res = -1;
for (int i = 0; i < 26; ++i)
{
for (int j = 0; j < 26; ++j)
{
if (cnt[i].first != 0 && cnt[j].first != 0)
{
cur_res = max(abs(cnt[i].first - cnt[j].first), cur_res);
}
}
}
if (cur_res < mxr)
{
res_now = { from, to };
mxr = cur_res;
}
cnt[from - 'a'].first++;
cnt[to - 'a'].first--;
}
}
}
if (mxr == initial)
{
break;
}
change[res_now.first - 'a'].push(res_now.second);
cnt[res_now.first - 'a'].first--;
cnt[res_now.second - 'a'].first++;
if (mxr == 0)
{
break;
}
}
for (int i = 0; i < n; ++i)
{
if (!change[s[i] - 'a'].empty())
{
cout << change[s[i] - 'a'].front();
change[s[i] - 'a'].pop();
}
else
{
cout << s[i];
}
}
return 0;
}
| true |
858b85d701d675c6786cef7bbb98486729e563dd | C++ | HarisonP/OOP-exams-and-homeworks | /k1/71577_kontr1.cpp | UTF-8 | 3,424 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<cassert>
#include<cstring>
using namespace std;
//4-te principa na OOP sa: Abstrakcia, Kapsulacia, Naslediavane, Polymorfizam
class Programmer
{
private:
char*name;
int iq;
double salary;
public:
Programmer(char*name = "Ico", int iq = 120, double salary = 2500)
{
this->name=new char[strlen(name)+1];
assert(this->name != NULL);
strcpy(this->name, name);
this->iq=iq;
this->salary=salary;
}
~Programmer()
{
delete []name;
}
Programmer (const Programmer &other)
{
name=new char[strlen(other.name)+1];
assert(name != NULL);
strcpy(name, other.name);
iq=other.iq;
salary=other.salary;
}
Programmer &operator=(const Programmer &other)
{
if(this != &other)
{
delete []name;
name=new char[strlen(other.name)+1];
assert(name != NULL);
strcpy(name, other.name);
iq=other.iq;
salary=other.salary;
}
return *this;
}
int getIq() const
{
return iq;
}
void setIq(int i)
{
iq=i;
}
double getSalary() const
{
return salary;
}
void setSalary(double s)
{
salary=s;
}
char* getName()
{
return name;
}
void setName(char* name)
{
delete [] this->name;
this->name=new char[strlen(name)+1];
assert(this->name!=NULL);
strcpy(this->name, name);
}
void print()
{
cout<<"Name:"<<name<<endl;
cout<<"Level of intelligence:"<<iq<<endl;
cout<<"Salary:"<<salary<<endl;
}
bool operator>(const Programmer &other)
{
return this->iq>other.iq;
}
bool operator<(const Programmer &other)
{
return this->iq<other.iq;
}
bool operator==(const Programmer &other)
{
return this->iq==other.iq;
}
};
class Team
{
private:
int size, MAX_SIZE=100;
Programmer* programmers;
public:
int getSize()
{
return size;
}
void addProgrammer(Programmer newPr)
{
if(size != MAX_SIZE)
{
programmers[size+1]= newPr;
}
}
void removeProgrammer(char* n)
{
Programmer newList[100];
for(int i=0; i<size; i++)
{
// strcmp
// - 0.1
if(programmers[i].getName() != n)
{
newList[i]= programmers[i];
}
}
}
Programmer getProgrammer(char*n)
{
for(int i=0; i<size; i++)
{
if(programmers[i].getName() == n)
{
return programmers[i];
}
}
}
void print()
{
for(int i=0; i<size; i++)
{
cout<<"Name:"<<programmers[i].getName()<<endl;
cout<<"Level of intelligence:"<<programmers[i].getIq()<<endl;
cout<<"Salary:"<<programmers[i].getSalary()<<endl;
}
}
Team ()
{
//wuut??
{
this->programmers=new Programmer[size+1];
assert(this->programmers != NULL);
}
}
~Team()
{
delete []programmers;
}
};
//.... no dynamic memory, missing a lot of other imporant things
// - 1.0
class Company
{
double averageIq()
{
double avg;
};
// - 1.5
// 3.4 | true |
89da07efd9a2884ace50686867b267cf4516ede6 | C++ | RedFog/Iris-Language | /Iris/include/IrisComponents/IrisUnil/IrisStatementResult.h | UTF-8 | 490 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _H_IRISSTATEMENTRESULT_
#define _H_IRISSTATEMENTRESULT_
#include "IrisValue.h"
class IrisStatementResult
{
public:
enum class StatementResultType {
Normal = 0,
Break,
Continue,
Return,
};
IrisValue m_ivValue;
StatementResultType m_eReturnType = StatementResultType::Normal;
IrisStatementResult() = default;
//operator IrisValue() { return m_ivValue; }
IrisStatementResult(const IrisValue& ivValue, StatementResultType eType);
~IrisStatementResult();
};
#endif | true |
06777e01953aee8a0f7a2de873b9fe7a8e9c60e3 | C++ | Hyarius/JDL_Development_kit | /JGL/includes/structure/jgl_camera.h | UTF-8 | 2,745 | 2.84375 | 3 | [] | no_license | #ifndef JGL_CAMERA_H
#define JGL_CAMERA_H
namespace jgl
{
class Camera
{
protected:
Viewport* _viewport;
Matrix4x4 _model;
Matrix4x4 _view;
Matrix4x4 _projection;
Matrix4x4 _MVP;
Matrix4x4 _MVP_pos;
Vector3 _light_pos;
Vector3 _light_dir;
Color _light_color;
Vector3 _pos;
float _yaw;
float _pitch;
Vector3 _direction;
Vector3 _forward;
Vector3 _right;
Vector3 _up;
float _ratio;
float _fov;
float _near;
float _far;
void calc_variable();
void compute_model();
void compute_view();
void compute_projection();
public:
Camera(Vector3 p_pos = Vector3(), float p_fov = 45, float p_ratio = 4.0f / 3.0f, float p_near = 0.1f, float p_far = 50.0f);
Vector3 mouse_direction(const jgl::Viewport* p_viewport = nullptr) const;
void look_at(Vector3 target);
void rotate_around_point(Vector3 target, float angle, Vector3 axis);
void rotate(Vector3 delta);
void move(Vector3 delta);
void place(Vector3 p_pos);
void compute() {compute_model(); compute_view(); compute_projection(); bake(); }
void set_light_position(Vector3 p_light_pos) { _light_pos = p_light_pos; }
void set_light_direction(Vector3 p_light_dir) { _light_dir = p_light_dir.normalize(); }
void set_yaw(float p_yaw) { _yaw = p_yaw; }
void set_pitch(float p_pitch) { _pitch = p_pitch; }
void set_viewport(Viewport* p_viewport) { _viewport = p_viewport; }
void set_fov(float p_fov) { _fov = p_fov; }
void set_vision_range(float p_near, float p_far) { set_near(p_near); set_far(p_far); }
void set_near(float p_near) { _near = p_near; }
void set_far(float p_far) { _far = p_far; }
const Viewport* viewport() const { return (_viewport); }
const float pitch() const { return (_pitch); }
const float yaw() const { return (_yaw); }
float fov() const { return (_fov); }
float ratio() const { return (_ratio); }
float view_near() const { return (_near); }
float view_far() const { return (_far); }
const Matrix4x4& model() const { return (_model); }
const Matrix4x4& view() const { return (_view); }
const Matrix4x4& projection()const { return (_projection); }
const Matrix4x4& MVP() const { return (_MVP); }
const Vector3 light_dir() const { return (_light_dir); }
const Vector3 light_pos() const { return (_light_pos); }
const Color light_color() const { return (_light_color); }
const Vector3 pos() const { return (_pos); }
const Vector3 direction() const { return (_direction); }
const Vector3 forward() const { return (_forward); }
const Vector3 right() const { return (_right); }
const Vector3 up() const { return (_up); }
void bake() { _MVP = _projection * _view * _model; }
};
}
std::ostream& operator<<(std::ostream& os, const jgl::Camera camera);
#endif
| true |
1538d0b53366585cacdf121c8bdb592cf8088a6a | C++ | eXceediDeaL/OI | /Problems/POJ/动态规划/背包DP/3181.cpp | UTF-8 | 1,239 | 3.21875 | 3 | [] | no_license | /*
Dollar Dayz
题意:求将n分解为大于等于1小于等于k的数,有多少种分法。(划分数问题)
分析:可以用完全背包解,枚举体积1..k,opt[j]+=opt[j-i]
另一种容易想到的方法: 用a[i][j]表示考虑到用数j进行拼接时数字i的拼接方法,可以得到状态转移方程如下:
a[i][j]=a[i][j-1]+a[i-j][j-1]+a[i-2j][j-1]+a[i-3j][j-1]…+a[0][j-1]意思很明显,就将j-1状态可以到达a[i][j]的状态的数字相加。由于得到的结果可能相当大,已经超过了long long,所以应该用大数。但是若跑完所有数据,用大数会超过一秒,我们通过大数的程序可以达到,最大的数字为33位,那么,我们可以将两个long long的数字进行拼接,组成一个超过33位的数。
*/
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long LL;
const LL INF=1e18;
LL a[1010],b[1010];
int main(){
int n,k;
scanf("%d%d",&n,&k);
b[0]=1;
for(int i=1;i<=k;i++)
for(int j=i;j<=n;j++){
a[j]=a[j]+a[j-i]+(b[j]+b[j-i])/INF;
b[j]=(b[j]+b[j-i])%INF;
}
if(a[n])printf("%lld%018lld",a[n],b[n]);
else printf("%lld\n",b[n]);
return 0;
}
| true |
995f2d8095beb630aec4eab34df77b46d66ce3eb | C++ | Paketov/ScriptEngine | /Script/ObjectClass.cpp | UTF-8 | 6,948 | 3.03125 | 3 | [] | no_license | #include "ObjectClass.h"
#include "String.h"
#include "Method.h"
// = Object.MemberIndex
inline INSIDE_DATA OBJECT_CLASS::ReadMember(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex)
{
auto Cell = ((LPOBJECT_HEADER)Object)->NodeTable.Search(MemberIndex);
if(Cell != nullptr)
return Cell->Val;
return INSIDE_DATA::Null;
}
//Object.MemberIndex = Source
void OBJECT_CLASS::WriteMember(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex, const LPINSIDE_DATA Source)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
if(!NODE_TABLE_HEADER::ResizeBeforeInsert(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
NodeTable.Insert(MemberIndex)->Val = *Source;
}
//delete Object.MemberIndex
void OBJECT_CLASS::RemoveMember(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
NodeTable.Remove(MemberIndex);
if(!NODE_TABLE_HEADER::ResizeAfterRemove(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
}
// = Object[MemberIndex]
INSIDE_DATA OBJECT_CLASS::OperatorReadByIndex(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex)
{
auto Cell = ((LPOBJECT_HEADER)Object)->NodeTable.Search(MemberIndex);
if(Cell != nullptr)
return Cell->Val;
return INSIDE_DATA::Null;
}
INSIDE_DATA OBJECT_CLASS::OperatorReadByIndex(INSTANCE_CLASS Object, ZELLI_INTEGER MemberIndex)
{
auto Cell = ((LPOBJECT_HEADER)Object)->NodeTable.Search(MemberIndex);
if(Cell != nullptr)
return Cell->Val;
return INSIDE_DATA::Null;
}
//Object[MemberIndex] = Source
void OBJECT_CLASS::OperatorWriteByIndex(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex, const LPINSIDE_DATA Source)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
if(!NODE_TABLE_HEADER::ResizeBeforeInsert(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
NodeTable.Insert(MemberIndex)->Val = *Source;
}
void OBJECT_CLASS::OperatorWriteByIndex(INSTANCE_CLASS Object, ZELLI_INTEGER MemberIndex, const LPINSIDE_DATA Source)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
if(!NODE_TABLE_HEADER::ResizeBeforeInsert(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
NodeTable.Insert(MemberIndex)->Val = *Source;
}
//delete Object[MemberIndex]
void OBJECT_CLASS::OperatorRemoveByIndex(INSTANCE_CLASS Object, const LPINSIDE_DATA MemberIndex)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
NodeTable.Remove(MemberIndex);
if(!NODE_TABLE_HEADER::ResizeAfterRemove(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
}
void OBJECT_CLASS::OperatorRemoveByIndex(INSTANCE_CLASS Object, ZELLI_INTEGER MemberIndex)
{
NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
NodeTable.Remove(MemberIndex);
if(!NODE_TABLE_HEADER::ResizeAfterRemove(NodeTable))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not realloc table.", UNHANDLED_EXCEPTION::NOT_REALLOC);
}
ZELLI_INTEGER OBJECT_CLASS::GetLength(INSTANCE_CLASS Object) { return ((LPOBJECT_HEADER)Object)->NodeTable.CountUsed; }
void OBJECT_CLASS::MarkInstanceAsUsed(INSTANCE_CLASS Object)
{
LPOBJECT_HEADER Obj = ((LPOBJECT_HEADER)Object);
if(Obj->ForCheckUses == CurCheckUses)
return;
Obj->ForCheckUses = CurCheckUses;
LIST_HEADER<OBJECT_HEADER>::MoveToListRight(Obj, &ListObject);
Obj->NodeTable.EnumValues
(
[](HASH_ELEMENT* El)
{
GC_MARK_VAR(El->Key);
GC_MARK_VAR(El->Val);
return true;
}
);
}
void OBJECT_CLASS::MarkClassAsUsed(INSTANCE_CLASS Object)
{
}
void OBJECT_CLASS::FreeAllUnused()
{
SwitchToAddMode();
LPOBJECT_HEADER ListUnusedObject = &this->ListUnusedObject;
for(LPOBJECT_HEADER CurElem = (LPOBJECT_HEADER)ListUnusedObject->Next;ListUnusedObject != CurElem;)
{
NODE_TABLE_HEADER::Free(CurElem->NodeTable);
CurElem = (LPOBJECT_HEADER)CurElem->Next;
AddInQueueHeader(this, CurElem->Previous);
}
LIST_HEADER<OBJECT_HEADER>::Close(ListUnusedObject);
}
LPOBJECT_HEADER __fastcall OBJECT_CLASS::__AllocHeader(LPOBJECT_CLASS This)
{
LPOBJECT_HEADER NewHeader = (LPOBJECT_HEADER)MEM_ALLOC(sizeof(OBJECT_HEADER));
if(NewHeader == NULL)
THROW_UNHANDLED_EXCEPTION("Not alloc memory for new object.", UNHANDLED_EXCEPTION::NOT_ALLOC_MEMORY);
return NewHeader;
}
OBJECT_CLASS::OBJECT_CLASS(LPSTRING_CLASS ListStrings): HEADER_CLASS(this, "Object", ListStrings)
{
CurCheckUses = 0;
LIST_HEADER<OBJECT_HEADER>::Close(&ListObject);
LIST_HEADER<OBJECT_HEADER>::Close(&ListUnusedObject);
HeaderObjQueue = nullptr;
CountHeaderInQueue = 0;
MaxCountHeaderInQueue = 100;
SwitchToAddMode();
}
void OBJECT_CLASS::EnumKey(INSTANCE_CLASS Object, LPINSIDE_DATA CurKey)
{
OBJECT_CLASS::NODE_TABLE_HEADER& NodeTable = ((LPOBJECT_HEADER)Object)->NodeTable;
NODE_TABLE_HEADER::LPCELL Cell;
if(CurKey->IsNotNull)
Cell = NodeTable.GetNextCellByKey(CurKey);
else
Cell = NodeTable.GetStartCell();
if(Cell != nullptr)
{
*CurKey = Cell->Key;
return;
}
CurKey->SetNull();
}
INSIDE_DATA OBJECT_CLASS::CreateInstance(LPEXECUTE_CONTEXT Context,LPARG_FUNC Arg)
{
LPOBJECT_HEADER NewHeader = GetHeaderFromQueue(this);
LIST_HEADER<OBJECT_HEADER>::AddToRight(&ListObject, NewHeader);
NewHeader->ForCheckUses = CurCheckUses;
if(!NODE_TABLE_HEADER::Realloc(NewHeader->NodeTable, 5))
THROW_UNHANDLED_EXCEPTION("OBJECT_CLASS: Not alloc table.", UNHANDLED_EXCEPTION::NOT_ALLOC_MEMORY);
NewHeader->NodeTable.Init(5);
return NewHeader;
}
LPOBJECT_HEADER __fastcall OBJECT_CLASS::__GetFromQueue(LPOBJECT_CLASS This)
{
if(This->HeaderObjQueue)
{
LPOBJECT_HEADER NewHeader = This->HeaderObjQueue;
This->HeaderObjQueue = *((LPOBJECT_HEADER*)NewHeader);
This->CountHeaderInQueue--;
return NewHeader;
}
This->GetHeaderFromQueue = __AllocHeader;
return __AllocHeader(This);
}
void __fastcall OBJECT_CLASS::__AddInQueue(LPOBJECT_CLASS This, LPOBJECT_HEADER Header)
{
if(This->CountHeaderInQueue < This->MaxCountHeaderInQueue)
{
*((LPOBJECT_HEADER*)Header) = This->HeaderObjQueue;
This->HeaderObjQueue = Header;
This->CountHeaderInQueue++;
return;
}
This->AddInQueueHeader = __DeleteObj;
MEM_FREE(Header);
}
void __fastcall OBJECT_CLASS::__DeleteObj(LPOBJECT_CLASS This, LPOBJECT_HEADER Header) { MEM_FREE(Header); }
bool OBJECT_CLASS::OperatorEq(INSTANCE_CLASS ThisObj, LPINSIDE_DATA SecondObj)
{
if(SecondObj->IsObject)
return ThisObj == SecondObj->Object;
return false;
}
HASH_VAL OBJECT_CLASS::GetHash(INSTANCE_CLASS Instance)
{
return (HASH_VAL)Instance;
} | true |
cb061bc9687018b0fc4b9a456a199b37876d38af | C++ | showwaychen/baselib | /webrtc/external/SigSlot.h | UTF-8 | 1,917 | 3.03125 | 3 | [] | no_license | #pragma once
#include <memory>
#include <functional>
#include <list>
#include <utility>
template <class T, class... ARGS>
class CSigSlot
{
using connectortype = std::pair<std::shared_ptr<T>, std::function<void(T *, ARGS...)>>;
std::list<connectortype> m_cConnectors;
public:
void connect(std::shared_ptr<T> sptr, std::function<void(T *, ARGS...)> mfun)
{
m_cConnectors.push_back(std::make_pair(sptr, mfun));
}
void disconnect(std::shared_ptr<T> lsptr)
{
auto ite = m_cConnectors.begin();
while (ite != m_cConnectors.end())
{
auto sptr = ite->first;
if (sptr == lsptr)
{
m_cConnectors.erase(ite);
}
ite++;
}
}
void operator()(ARGS &&... args)
{
auto ite = m_cConnectors.begin();
while (ite != m_cConnectors.end())
{
auto ptr = ite->first;
auto mfun = ite->second;
mfun(ptr.get(), std::forward<ARGS>(args)...);
ite++;
}
}
};
template <class T, class... ARGS>
class CWeakSigSlot
{
using connectortype = std::pair<std::weak_ptr<T>, std::function<void(T *, ARGS...)>>;
std::list<connectortype> m_cConnectors;
public:
void connect(std::shared_ptr<T> sptr, std::function<void(T *, ARGS...)> mfun)
{
m_cConnectors.push_back(std::make_pair(sptr, mfun));
}
void operator()(ARGS &&... args)
{
auto ite = m_cConnectors.begin();
while (ite != m_cConnectors.end())
{
auto wptr = ite->first;
auto mfun = ite->second;
auto sptr = wptr.lock();
if (sptr != nullptr)
{
mfun(sptr.get(), std::forward<ARGS>(args)...);
}
else
{
m_cConnectors.erase(ite);
}
ite++;
}
}
}; | true |
198674cd30a7cf5ee11fc3cc3639e00e9f1b7590 | C++ | TeschRenan/ADC_ESP32 | /ADC.ino | UTF-8 | 1,806 | 2.578125 | 3 | [] | no_license |
#include <driver/adc.h>
#include <esp_adc_cal.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_err.h>
#include <esp_log.h>
esp_adc_cal_characteristics_t adc_cal;//Estrutura que contem as informacoes para calibracao
//Codigo fonte extraido da Espressif IDF para medição do ADC1_CHANNEL_5 = GPIO 33, com atenuação de 0dB, faixa de leitura de 0 a 1.1V
void setup() {
Serial.begin(115200);
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_5,ADC_ATTEN_DB_0);
esp_adc_cal_value_t adc_type = esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_0, ADC_WIDTH_BIT_12, 1100, &adc_cal);//Inicializa a estrutura de calibracao
if (adc_type == ESP_ADC_CAL_VAL_EFUSE_VREF)
{
Serial.println("ADC CALV ref eFuse encontrado: ");
Serial.print(adc_cal.vref);
Serial.print("mV");
}
else if (adc_type == ESP_ADC_CAL_VAL_EFUSE_TP)
{
Serial.println("ADC CAL Two Point eFuse encontrado");
}
else
{
Serial.println("ADC CAL Nada encontrado, utilizando Vref padrao: ");
Serial.print(adc_cal.vref);
Serial.print("mV");
}
}
void loop() {
uint32_t AD = 0;
for (int i = 0; i < 100; i++)
{
AD += adc1_get_raw(ADC1_CHANNEL_5);//Obtem o valor RAW do ADC
ets_delay_us(30);
}
AD /= 100;
Serial.print("Valor do AD: ");
Serial.print(AD);
Serial.println("");
AD = esp_adc_cal_raw_to_voltage(AD, &adc_cal);//Converte e calibra o valor lido (RAW) para mV
Serial.print("Valor do AD em mV: ");
Serial.print(AD);
Serial.println("mV");
Serial.println("");
delay(1000);
}
| true |
1b012175751359e79075d0417a3c37288a15f52a | C++ | tntguy12355/MinecraftPlaysPortal | /src/datadisplay/DataReceiver.cpp | UTF-8 | 2,998 | 2.71875 | 3 | [] | no_license | #include "DataReceiver.hpp"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
DataReceiver* g_dataReceiver = new DataReceiver();
DataReceiver::DataReceiver()
{
active = false;
clientSocket = INVALID_SOCKET;
}
DataReceiver::~DataReceiver()
{
Disable();
}
void DataReceiver::Initialize(std::string serverIP)
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
throw "WSA Startup failed : " + std::to_string(WSAGetLastError());
}
addrinfo hints, * result;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(serverIP.c_str(), "25565", &hints, &result) != 0) {
throw "GetAddrInfo failed : " + std::to_string(WSAGetLastError());
}
while (clientSocket == INVALID_SOCKET) {
if ((clientSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == INVALID_SOCKET) {
throw "Socket creation failed : " + std::to_string(WSAGetLastError());
}
if (connect(clientSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) {
closesocket(clientSocket);
clientSocket = INVALID_SOCKET;
this_thread::sleep_for(1000ms);
continue;
}
}
freeaddrinfo(result);
active = true;
// send handshake packet
MCP::Packet handshake(0x68);
handshake.Send(clientSocket);
}
void DataReceiver::ReceiveData()
{
// send request packet (detailed)
MCP::Packet request(0x69);
request.WriteByte(0x01);
request.Send(clientSocket);
// wait for new data to arrive
int waitResult = recv(clientSocket, nullptr, 0, 0);
// receive the data
char* dataBuffer = new char[1024];
int dataLen = recv(clientSocket, dataBuffer, 1024, 0);
if (dataLen < 0) {
throw "Socket recv failed : " + std::to_string(WSAGetLastError());
}
if (dataLen == 0)return;
// read the data
MCP::Packet pIn(dataBuffer);
data.movementX = pIn.ReadFloat();
data.movementY = pIn.ReadFloat();
data.angleX = pIn.ReadFloat();
data.angleY = pIn.ReadFloat();
for (int i = 0; i < 5; i++) {
data.digitalAnalogs[i] = pIn.ReadFloat();
}
data.playerCount = pIn.ReadInt();
for (int i = 0; i < 9; i++) {
data.inputCounts[i] = pIn.ReadInt();
}
/*cout << "movX:" << data.movementX << ",";
cout << "movY:" << data.movementY << ",";
cout << "angX:" << data.angleX << ",";
cout << "angY:" << data.angleY << ",";
cout << "digital:";
for (int i = 0; i < 5; i++) {
cout << data.digitalAnalogs[i] << ",";
}
cout << endl;*/
delete[] dataBuffer;
}
void DataReceiver::Disable()
{
if (!active) return;
active = false;
closesocket(clientSocket);
clientSocket = INVALID_SOCKET;
WSACleanup();
}
| true |
09abc1e1236e339af3ada96cb245496ada38fb6d | C++ | cjrequena/learning-cpp | /src/helloworld/HelloWorld.cpp | UTF-8 | 908 | 2.953125 | 3 | [] | no_license | //
// Created by Carlos José Requena Jiménez on 2019-07-29.
//
#include <iostream>
#include "HelloWorld.hpp"
using namespace std; // this is a using directive telling the compiler to check the std namespace when resolving identifiers with no prefix
void HelloWorld::helloWorld() {
cout << "\n" << endl;
cout << "================================" << endl;
cout << "helloWorld example" << endl;
cout << "================================" << endl;
std::cout << "Hello, World!" << std::endl;
}
HelloWorld::HelloWorld() {
cout << "\n" << endl;
cout << "================================" << endl;
cout << "HelloWorld Constructor called." << endl;
cout << "================================" << endl;
}
HelloWorld::~HelloWorld() {
cout << "\n" << endl;
cout << "================================" << endl;
cout << "HelloWorld Destructor called." << endl;
cout << "================================" << endl;
} | true |
952bdb13f328a0b6f0e1033c68faed6a55c9828a | C++ | ghauser57/IHM_L3_HAUSER_VANET | /IHM_L3_HAUSER_VANET/IHM_L3_HAUSER_VANET/GElement.cpp | UTF-8 | 248 | 2.640625 | 3 | [] | no_license | #include "GElement.h"
GElement::operator string() const
{
ostringstream flux;
flux << "Graphe : " << clef;
return flux.str();
}
ostream & operator << (ostream & o, const GElement & g)
{
o << g.operator std::string();
return o;
} | true |
88db3fbf3485f788a4d741425169878128fe8675 | C++ | abhishek7553/Codes | /template_overloading.cpp | UTF-8 | 271 | 3.15625 | 3 | [] | no_license | #include<iostream>
using namespace std;
template <class T>
void fun(T x,T y){
cout<<"template :"; cout<<x<<y;
}
void fun(int x,int y){
cout<<"non-template :"; cout<<x<<y;
}
int main(){
fun(1,3);cout<<endl;
fun(2,'a');cout<<endl;
fun('q','w');cout<<endl;
return 0;
}
| true |
a4a7407785dc073c54421406b34826b78e52a626 | C++ | jondeaton/Algorithms | /Machine-Learning/Q-Learning/include/learner.hpp | UTF-8 | 3,402 | 3.328125 | 3 | [] | no_license | /**
* @file learner.hpp
* @brief Q-Learning algorithm
* @details Q-learning is a model-free reinforcement learning algorithm. It does not construct a
* model of the state transition probabilities of the world. It does keep an explicit value function
* and policy function to make decisions.
*/
#ifndef Q_LEARNING_LEARNER_HPP
#define Q_LEARNING_LEARNER_HPP
#include "maze.hpp"
#include <map>
#include <iostream>
template <class Agent, class Environment, class Quality=double>
class learner {
public:
typedef typename Agent::reward_type reward_type;
typedef typename Agent::state_type state_type;
typedef typename Agent::action_type action_type;
typedef Quality quality_type;
learner(const Agent& agent, const Environment& environment)
: _agent(agent), _environment(environment) {}
/**
* @fn learn
* @breif Executes a series of episodes
* @return The maximum reward obtained
*/
reward_type learn(unsigned int num_episodes=30) {
reward_type max_reward = 0;
for (unsigned int episode = 0; episode < num_episodes; episode++) {
std::clog << "Episode: " << episode << std::endl;
reward_type reward = play_episode();
std::clog << "Episode reward: " << reward << std::endl;
if (reward > max_reward) max_reward = reward;
}
return max_reward;
}
/**
* @fn play_episode
* @breif Plays a single episode
* @return The total reward achieved during the episode
*/
reward_type play_episode() {
_environment.reset();
_agent.reset();
std::clog << "Starting state: " << _agent.current_state() << std::endl;
reward_type total_reward = 0;
while (!_agent.is_done()) {
const observation_type& observation = _agent.observe();
const state_type& old_state =
const state_type& old_state = _agent.current_state();
const action_type& optimal_action = _find_optional_action(old_state);
reward_type reward = _agent.take_action(optimal_action);
const state_type& new_state = _agent.current_state();
std::clog << "Action: " << optimal_action
<< ", new state: " << new_state
<< ", reward: " << reward << std::endl;
update_Q(old_state, new_state, optimal_action, reward);
total_reward += reward;
}
return total_reward;
}
private:
Agent _agent;
Environment _environment;
quality_type Q[Agent::num_states][Agent::num_actions];
quality_type learning_rate;
quality_type gamma_discount;
std::map<state_type, int> state_map;
std::map<action_type, int> action_map;
std::vector<std::tuple<state_type, action_type>> history;
const action_type& _find_optional_action(const state_type& state) {
quality_type max = std::min<quality_type>;
int index = 0;
for (int i=0; i < Agent::num_actions; ++i) {
quality_type q = Q[state][i];
if (q > max) {
max = q;
index = i;
}
}
return _agent.action_at(index);
}
quality_type update_Q(const state_type& new_state, const state_type& old_state, const action_type& action, const reward_type& reward) {
int new_s = state_map[new_state];
int a = action_map[action];
int old_s = state_map[old_state];
quality_type q = Q[new_s][a];
Q[old_s][a] = (1 - learning_rate) * Q[old_s][a] + learning_rate * (reward + gamma_discount * q);
return Q[old_s][a];
}
};
#endif //Q_LEARNING_LEARNER_HPP
| true |
2139cf3730f5253a5e9bb46c67fb538c6c0be392 | C++ | CRblog/algorithm | /practice/青岛网赛K题.cpp | UTF-8 | 928 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int mypow[32];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
mypow[0] = 1, mypow[1] = 2;
for(int i = 2; i<32; i++)
mypow[i] = mypow[i-1] * 2;
int T;
cin >> T;
while(T--)
{
map<int, int> F;
int n;
cin >> n;
int Max = -1;
for(int i = 0; i<n; i++)
{
int tmp;
cin >> tmp;
for(int j = 0; j < 32; j++)
{
if(mypow[j] == tmp)
{
F[j]++;
break;
}
else if(mypow[j] > tmp)
{
F[j-1]++;
break;
}
}
}
for(int i = 0; i<32; i++)
{
Max = max(Max, F[i]);
}
cout<<Max<<endl;
}
return 0;
}
| true |
1f170598498586ccb09146be8dcd9bce97e07e86 | C++ | liihongbin/leetcode | /Roman to Integer.cpp | UTF-8 | 484 | 3.09375 | 3 | [] | no_license | class Solution {
public:
int romanToInt(string s) {
map<char, int> d;
d['I'] = 1;
d['V'] = 5;
d['X'] = 10;
d['L'] = 50;
d['C'] = 100;
d['D'] = 500;
d['M'] = 1000;
int res = 0;
for (int i = 0; i<s.size(); i++){
if (i+1<s.size() && d[s[i]] < d[s[i+1]]){
res -= d[s[i]];
}else{
res += d[s[i]];
}
}
return res;
}
};
| true |
0eb35258bb668eac11c11c5a66940899ada95d6d | C++ | hrefnanamfa/Verkleganamskeid | /PizzaProject/src/repositories/ToppingRepository.cpp | UTF-8 | 1,635 | 3.03125 | 3 | [] | no_license | #include "../../include/repositories/ToppingRepository.h"
void ToppingRepository::replaceToppingsInRepo(vector<Topping> toppings){
ofstream fout;
try {
fout.open("topping.dat", ios::binary);
if (fout.is_open()){
for(unsigned int i = 0; i < toppings.size(); i++){
toppings.at(i).write(fout);
}
fout.close();
}
else {
throw InvalidWriteException();
}
}
catch (InvalidWriteException){
cout << "[UNABLE TO WRITE INTO FILE topping.dat]" << endl;
}
}
void ToppingRepository::addTopping(Topping& topping){
ofstream fout;
try {
fout.open("topping.dat", ios::binary|ios::app);
if (fout.is_open()){
topping.write(fout);
fout.close();
}
else {
throw InvalidReadException();
}
}
catch (InvalidWriteException){
cout << "[UNABLE TO WRITE INTO FILE topping.dat]" << endl;
}
}
vector<Topping> ToppingRepository::getToppings(){
ifstream fin;
vector<Topping> toppings;
try {
fin.open("topping.dat", ios::binary);
if (fin.is_open()){
while(!fin.eof()){
Topping topping;
topping.read(fin);
if(fin.eof())
break;
toppings.push_back(topping);
}
fin.close();
}
else {
throw InvalidReadException();
}
}
catch (InvalidReadException){
cout << "[UNABLE TO READ FILE topping.dat]" << endl;
}
return toppings;
}
| true |
d829c280bb3a03429dca7805b707201cd3a06d74 | C++ | lilyfengli/megamol | /vislib/src/math/Float16.cpp | UTF-8 | 9,173 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Float16.cpp 21.08.2006 (mueller)
*
* Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.
*/
#include "vislib/math/Float16.h"
#include <cfloat>
#include "vislib/assert.h"
/** Absolute of bias of half exponent (-15). */
static const VL_INT32 FLT16_BIAS = 15;
/** Bitmask for the exponent bits of half. */
static const UINT16 FLT16_EXPONENT_MASK = 0x7C00;
/** Bitmask for the mantissa bits of half. */
static const UINT16 FLT16_MANTISSA_MASK = 0x03FF;
/** Bitmask for the sign bit of half. */
static const UINT16 FLT16_SIGN_MASK = 0x8000;
/** Size difference between half and float mantissa. */
static const UINT32 FLT1632_MANTISSA_OFFSET
= (FLT_MANT_DIG - vislib::math::Float16::MANT_DIG) - 1;
/** Distance between half and float sign bit. */
static const UINT32 FLT1632_SIGN_OFFSET = (32 - 16);
/** Bias of float exponent. */
static const VL_INT32 FLT32_BIAS = 127;
/** Bitmask for the exponent bits of float. */
static const UINT32 FLT32_EXPONENT_MASK = 0x7F800000;
/** Bitmask for the mantissa bits of half */
static const UINT32 FLT32_MANTISSA_MASK = 0x007FFFFF;
/** Bitmask for the sign bit of float */
static const UINT32 FLT32_SIGN_MASK = 0x80000000;
/*
* vislib::math::Float16::FromFloat32
*/
void vislib::math::Float16::FromFloat32(UINT16 *outHalf, SIZE_T cnt,
const float *flt) {
VL_INT32 exponent = 0; // Value of exponent of 'flt'.
UINT32 input = 0; // Bitwise reinterpretation of 'flt'.
UINT32 mantissa = 0; // Value of mantissa, biased for half.
UINT32 sign = 0; // The sign bit.
for (SIZE_T i = 0; i < cnt; i++) {
/* Bitwise reinterpretation of input */
input = *(reinterpret_cast<const UINT32 *>(flt + i));
/* Just move the sign bit directly to its final position. */
sign = (input & FLT32_SIGN_MASK) >> FLT1632_SIGN_OFFSET;
/* Retrieve value of exponent. */
exponent = static_cast<VL_INT32>((input & FLT32_EXPONENT_MASK)
>> (FLT_MANT_DIG - 1)) - FLT32_BIAS + FLT16_BIAS;
/* Retrieve value of mantissa. */
mantissa = (input & FLT32_MANTISSA_MASK);
if (exponent < -Float16::MANT_DIG) {
/* Underflow, result is zero. */
outHalf[i] = 0;
} else if (exponent <= 0) {
/* Negative exponent. */
/* Normalise the number. */
mantissa = (mantissa | (1 << (FLT_MANT_DIG - 1))) >> (1 - exponent);
outHalf[i] = static_cast<UINT16>(sign
| (mantissa >> FLT1632_MANTISSA_OFFSET));
} else if (exponent == (FLT32_EXPONENT_MASK >> (FLT_MANT_DIG - 1))
- FLT32_BIAS + FLT16_BIAS) {
/*
* If all exponent bits are set, the input float is either infinity
* ('mantissa' == 0) or NaN ('mantissa' != 0). If all mantissa bits
* are set, NaN is quiet, otherwise, it is signaling. Truncating the
* mantissa should preserve this.
*/
if (mantissa != 0) {
/*
* Truncate mantissa, if it contains data (i. e. is NaN), but
* make sure that the mantissa does not become zero by shifting
* out all relevant bits as this would make the NaN infinity.
*/
mantissa >>= FLT1632_MANTISSA_OFFSET;
mantissa |= (mantissa == 0);
}
outHalf[i] = static_cast<UINT16>(sign | FLT16_EXPONENT_MASK
| mantissa);
} else if (exponent > Float16::MAX_EXP + FLT16_BIAS) {
/* Overflow, result becomes infinity. */
outHalf[i] = static_cast<UINT16>(sign | FLT16_EXPONENT_MASK);
} else {
/*
* Normal, valid number, truncate mantissa and move exponent to its
* final position.
*/
outHalf[i] = sign | (exponent << Float16::MANT_DIG)
| (mantissa >> FLT1632_MANTISSA_OFFSET);
} /* end if (exponent <= 0) */
} /* end for (SIZE_T i = 0; i < cnt; i++) */
}
/*
* vislib::math::Float16::ToFloat32
*/
void vislib::math::Float16::ToFloat32(float *outFloat, const SIZE_T cnt,
const UINT16 *half) {
VL_INT32 exponent = 0; // Value of exponent of 'half'.
UINT32 mantissa = 0; // Value of mantissa.
UINT32 result = 0; // The result
UINT32 sign = 0; // The sign bit.
for (SIZE_T i = 0; i < cnt; i++) {
/* Just move the sign bit directly to its final position. */
sign = static_cast<UINT32>(half[i] & FLT16_SIGN_MASK)
<< FLT1632_SIGN_OFFSET;
/* Retrieve value of exponent. */
exponent = static_cast<VL_INT32>((half[i] & FLT16_EXPONENT_MASK)
>> Float16::MANT_DIG);
/* Retrieve value of mantissa. */
mantissa = static_cast<UINT32>(half[i] & FLT16_MANTISSA_MASK);
if (exponent == 0) {
if (mantissa == 0) {
/* Value is zero, preserve sign. */
result = sign;
} else {
/* Denormalised. */
/*
* Shift left until the first 1 occurs left of the mantissa.
* This is the implicit 1 which must be deleted afterwards.
*/
while ((mantissa & (1 << Float16::MANT_DIG)) == 0) {
mantissa <<= 1;
exponent -= 1;
}
exponent += FLT32_BIAS - FLT16_BIAS + 1;
mantissa &= ~(1 << Float16::MANT_DIG);
result = sign | (exponent << (FLT_MANT_DIG - 1))
| (mantissa << FLT1632_MANTISSA_OFFSET);
}
} else if (exponent == (FLT16_EXPONENT_MASK >> Float16::MANT_DIG)) {
/*
* All exponent bits are set, the number is infinity, if the
* mantissa is zero, or NaN otherwise. If all mantissa bits are
* set, the number is a quiet NaN, if only some are set, it is
* a signaling NaN.
*/
if (mantissa == 0) {
/* Infinity. */
result = (sign | FLT32_EXPONENT_MASK);
} else if (mantissa == FLT16_MANTISSA_MASK) {
/* Quiet NaN. */
result = sign | FLT32_EXPONENT_MASK | FLT32_MANTISSA_MASK;
} else {
/* Signaling NaN. */
result = sign | FLT32_EXPONENT_MASK
| (mantissa << FLT1632_MANTISSA_OFFSET);
}
} else {
result = sign
| ((exponent - FLT16_BIAS + FLT32_BIAS) << (FLT_MANT_DIG - 1))
| (mantissa << FLT1632_MANTISSA_OFFSET);
}
/* Bitwise reinterpret the result as float. */
outFloat[i] = *reinterpret_cast<float *>(&result);
} /* end for (SIZE_T i = 0; i < cnt; i++) */
}
/*
* vislib::math::Float16::MANT_DIG
*/
const INT vislib::math::Float16::MANT_DIG = 10;
/*
* vislib::math::Float16::MAX_EXP
*/
const INT vislib::math::Float16::MAX_EXP = (16 - 1);
/*
* vislib::math::Float16::MIN_EXP
*/
const INT vislib::math::Float16::MIN_EXP = -12;
/*
* vislib::math::Float16::RADIX
*/
const INT vislib::math::Float16::RADIX = 2;
/*
* vislib::math::Float16::EPSILON
*/
const float vislib::math::Float16::EPSILON = 4.8875809e-4f;
/*
* vislib::math::Float16::MAX
*/
const double vislib::math::Float16::MAX = 6.550400e+004;
/*
* vislib::math::Float16::MIN
*/
const double vislib::math::Float16::MIN = 6.1035156e-5;
/*
* vislib::math::Float16::~Float16
*/
vislib::math::Float16::~Float16(void) {
}
/*
* vislib::math::Float16::IsInfinity
*/
bool vislib::math::Float16::IsInfinity(void) const {
// All exponents and no mantissa bits set.
return (((this->value & FLT16_EXPONENT_MASK) == FLT16_EXPONENT_MASK)
&& ((this->value & FLT16_MANTISSA_MASK) == 0));
}
/*
* vislib::math::Float16::IsNaN
*/
bool vislib::math::Float16::IsNaN(void) const {
// All exponent and some mantissa bits set.
return (((this->value & FLT16_EXPONENT_MASK) == FLT16_EXPONENT_MASK)
&& ((this->value & FLT16_MANTISSA_MASK) != 0));
}
/*
* vislib::math::Float16::IsQuietNaN
*/
bool vislib::math::Float16::IsQuietNaN(void) const {
// All exponent and all mantissa bits set.
return (((this->value & FLT16_EXPONENT_MASK) == FLT16_EXPONENT_MASK)
&& ((this->value & FLT16_MANTISSA_MASK) == FLT16_MANTISSA_MASK));
}
/*
* vislib::math::Float16::IsSignalingNaN
*/
bool vislib::math::Float16::IsSignalingNaN(void) const {
// All exponent bits set, some, but not all, mantissa bits set.
return (((this->value & FLT16_EXPONENT_MASK) == FLT16_EXPONENT_MASK)
&& ((this->value & FLT16_MANTISSA_MASK) != 0)
&& ((this->value & FLT16_MANTISSA_MASK) != FLT16_MANTISSA_MASK));
}
/*
* vislib::math::Float16::operator =
*/
vislib::math::Float16& vislib::math::Float16::operator =(const Float16& rhs) {
if (this != &rhs) {
this->value = rhs.value;
}
return *this;
}
| true |
91d46e0be9d346cf3898ee656f0fc9379902e44d | C++ | jkim552/OOP345 | /milestones/ms3/ms3/Station.cpp | UTF-8 | 2,038 | 3.09375 | 3 | [] | no_license | // Name: Junhee Kim
// Seneca Student ID: 159777184
// Seneca email: jkim552@myseneca.ca
// Date of completion: Oct 30 2020
//
// I confirm that I am the only author of this file
// and the content was created entirely by me.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <iomanip>
#include "Utilities.h"
#include "Station.h"
using namespace std;
// Static member variable
size_t Station::s_widthField = 0;
int Station::id_generator = 0;
// 1 arg custom constructor
Station::Station(const std::string& str) {
Utilities util;
s_id = ++id_generator;
size_t pos = 0;
bool more = true;
try {
s_name = util.extractToken(str, pos, more);
s_next = stoi(util.extractToken(str, pos, more));
s_current = stoi(util.extractToken(str, pos, more));
s_widthField = util.getFieldWidth() > s_widthField ? util.getFieldWidth() : s_widthField;
s_description = util.extractToken(str, pos, more);
}
catch (string& str) {
cout << str;
}
}
// Returns the name of the current Station object
const std::string& Station::getItemName() const {
return s_name;
}
// Returns the next serial number
unsigned int Station::getNextSerialNumber() {
return s_next++;
}
// Returns the remaining quantity of the current Station object
unsigned int Station::getQuantity() const {
return s_current;
}
// Subtracts 1 from the available quantity; should not go below 0.
void Station::updateQuantity() {
if (s_current != 0) {
s_current--;
}
}
// Inserts the content of the current object into first parameter.
void Station::display(std::ostream& os, bool full) const {
ios init(NULL);
os.copyfmt(cout);
os << "[";
os << right << setw(3) << setfill('0') << s_id;
os << "] ";
os << "Item: " << left << setw(s_widthField) << setfill(' ') << s_name;
os << right << " [";
os << setw(6) << setfill('0') << s_next;
os << "]" << left;
if (full == false) {
os << endl;
}
else {
os << " Quantity: ";
os << setw(s_widthField) << setfill(' ') << s_current;
os << " Description: ";
os << s_description << endl;
}
}
| true |
1df2e54b3fb18c2e9f897214fe9b0922e6e97d13 | C++ | danielfelipe-df/Network_buses | /Code_CPP/station.h | UTF-8 | 1,343 | 3.0625 | 3 | [] | no_license | #ifndef STATION_H_
#define STATION_H_
#include <vector>
#include "agents.h"
#include "bus.h"
class station{
public:
//Me dice cuánta gente hay de cada tipo
std::vector<agents> Ni; //Infectada
std::vector<agents> Ns1; //Susceptible1
std::vector<agents> Ns2; //Susceptible2
std::vector<agents> Ne; //Expuesta
//Me dice de qué bus deja subir y bajar
int location;
//Me dice cuántas personas máximo pueden estar en la estación
int Nmax=1000;
//Funciones
int N(){return Ns1.size() + Ns2.size() + Ni.size() + Ne.size();};
int NS(){return Ns1.size() + Ns2.size();};
void clear();
//Sobrecarga de operadores
station operator=(station b){
this->Ni = b.Ni;
this->Ns1 = b.Ns1;
this->Ns2 = b.Ns2;
this->Ne = b.Ne;
return b;
}
friend class agents;
station operator +(agents b){
if(b.infected){this->Ni.push_back(b);}
else if(b.susceptible1){this->Ns1.push_back(b);}
else if(b.susceptible2){this->Ns2.push_back(b);}
else{this->Ne.push_back(b);}
return *this;
}
friend class bus;
station operator+(const bus b){
this->Ni.insert(this->Ni.end(), b.Ni.begin(), b.Ni.end());
this->Ns1.insert(this->Ns1.end(), b.Ns1.begin(), b.Ns1.end());
this->Ns2.insert(this->Ns2.end(), b.Ns2.begin(), b.Ns2.end());
this->Ne.insert(this->Ne.end(), b.Ne.begin(), b.Ne.end());
return *this;
}
};
#endif
| true |
69ef14af332786c7cb7a2f10484bb45fd0be99a8 | C++ | proydakov/codeforces | /Good_Bye_2016/A/solution.cpp | UTF-8 | 421 | 2.78125 | 3 | [] | no_license | #include <iostream>
int main()
{
std::ios::sync_with_stdio(false);
int n; int k;
std::cin >> n;
std::cin >> k;
int t = 60 * 4 - k;
int time = 0;
int count = 0;
for(int i = 0; i < n; i++) {
time += (i + 1) * 5;
if(time <= t) {
count = i + 1;
}
else {
break;
}
}
std::cout << count << std::endl;
return 0;
}
| true |
17c7c0b8ec71e5212d3f66eeb81406ed35e49ba3 | C++ | DJPeanutButter/Modulation | /Color.cpp | UTF-8 | 439 | 3.28125 | 3 | [] | no_license | #include "Color.h"
Color::Color (){
r = 0.0f;
g = 0.0f;
b = 0.0;
}
Color::Color (float red, float green, float blue){
r = red;
g = green;
b = blue;
}
Color COLOR (float r, float g, float b){
Color retVal;
retVal.r = r;
retVal.g = g;
retVal.b = b;
return retVal;
}
Color INVERT (Color &c){
c.r = 1.0f - c.r;
c.g = 1.0f - c.g;
c.b = 1.0f - c.b;
return c;
}
void SetColor (Color c){
glColor3f (c.r, c.g, c.b);
return;
}
| true |