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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15e4dc2ee5d69cbe5593773172b4a36c73a761f3 | C++ | DemonikOpen/SFNet | /src/VoiPClient.cpp | UTF-8 | 1,185 | 2.59375 | 3 | [] | no_license | #include "VoiPClient.hpp"
voip::Client::Client()
{
audioStream = new voip::AudioStream();
audioRecorder = new voip::AudioRecorder(*this);
}
voip::Client::~Client()
{
if(audioStream != NULL)
{
delete audioStream;
audioStream = NULL;
}
if(audioRecorder != NULL)
{
delete audioRecorder;
audioRecorder = NULL;
}
}
void voip::Client::OnConnection()
{
audioStream->play();
audioRecorder->start(44100);
}
void voip::Client::Disconnect()
{
audioStream->stop();
audioRecorder->stop();
sf::TcpClient::Disconnect();
}
void voip::Client::OnDataReceive(sf::Packet packet)
{
sf::Uint8 id;
packet >> id;
if (id == audioData)
{
const sf::Int16* samples = reinterpret_cast<const sf::Int16*>(static_cast<const char*>(packet.getData()) + 1);
std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(sf::Int16);
audioStream->SetSamples(samples, sampleCount);
}
else if (id == endOfStream)
{
std::cout << "Audio data has been 100% received!" << std::endl;
}
else
{
std::cout << "Invalid packet received..." << std::endl;
}
}
| true |
d9a4bec223eb13effe85270b98a4eab461917e16 | C++ | ProfJust/MCT1 | /Praxisdemo Kap10_Echo und Encoder/MCT1_Kap11_sw01_Fischertechnik Encoder Motor/MCT1_Kap11_sw01_Fischertechnik_Encoder_Motor/MCT1_Kap11_sw01_Fischertechnik_Encoder_Motor.ino | UTF-8 | 1,233 | 2.65625 | 3 | [] | no_license | //==========================================
// Westfälische Hochschule - FB Maschinenbau
// Prof. Dr.-Ing. Olaf Just
// MCT1, Version vom 27.4.2018
//--------------------------------------
// MCT1_Kap11_sw01_Fischertechnik Encoder Motor.ino
//-----E-Blocks ------------------------
// LED - Board an Jx (D8-D15) + Power-Board + Motor
//-------------------------------------------------------------
//--- Die Power-Board Kabel sind an folgende Pins gedrahtet ---
#define MO0 10
#define MO1 11
int OutPins[2] = {MO0, MO1};
enum MotorDirTyp {LEFT, RIGHT, STOP};
//--------------------------------------
void setup() {
// Ports auf Ausgang setzen
for (int i = 0; i < sizeof(OutPins); i++)
pinMode(OutPins[i], OUTPUT);
}
//--------------------------------------
void setMotor( MotorDirTyp dir){
if ( dir == LEFT){
digitalWrite(MO0, LOW);
digitalWrite(MO1, HIGH);
}
else if ( dir == RIGHT){
digitalWrite(MO0, HIGH);
digitalWrite(MO1, LOW);
}
else{
digitalWrite(MO0, LOW);
digitalWrite(MO1, LOW);
}
}
//--------------------------------------
void loop() {
setMotor(LEFT);
delay(2000);
setMotor(STOP);
delay(1000);
setMotor(RIGHT);
delay(3000);
setMotor(STOP);
delay(5000);
}
| true |
72021b601eefb1995ccd7ce1e1a66622006330d7 | C++ | TASMIAHASAD/Assignment2sorted | /SortedType.h | UTF-8 | 640 | 3.125 | 3 | [] | no_license | #ifndef SORTEDTYPE_H_INCLUDED
#define SORTEDTYPE_H_INCLUDED
template <class ItemType>
class SortedType
{
struct NodeType {
ItemType info = ItemType();
NodeType* next = NULL;
};
public:
SortedType();
~SortedType();
bool IsFull();
int GetLength();
void MakeEmpty();
bool IsEmpty();
ItemType GetItem(ItemType item, bool& found);
bool PutItem(ItemType item);
bool DeleteItem(ItemType item);
//Iterator Operations
void ResetList();
bool HasNextItem();
ItemType GetNextItem();
private:
NodeType* listData = NULL;
int length = 0;
NodeType* currentPos = NULL;
};
#endif // SORTEDTYPE_H_INCLUDED
| true |
7d581d7758d542b79a3a9e7d7b925169121085ba | C++ | 1601110116/LePlasma_Visual | /LeFrame/src/Stage.cpp | UTF-8 | 460 | 2.53125 | 3 | [] | no_license | /*
* Stage.cpp
*
* Created on: Apr 24, 2016
* Author: zlstudio
*/
#include <Stage.h>
Stage::Stage(const char* title,int x,int y,int w,int h):
title(title),
stageX(x),stageY(y),
stageWidth(w),stageHeight(h)
{
this->x=0;
this->y=0;
stage=this;
}
Stage::Stage():title(title),
stageX(0),stageY(0),
stageWidth(DEFAULT_STAGE_WIDTH),
stageHeight(DEFAULT_STAGE_HEIGHT)
{
stage=this;
}
Stage::~Stage(){}
void Stage::display(){
redraw(0,0);
}
| true |
029510b0cd701d088bc4670fd6710c4b2b672924 | C++ | Flash1ee/voyager-game | /libs/math/test/tests/utilits_tests.cpp | UTF-8 | 16,043 | 2.84375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <tuple>
#include <math/utilits.hpp>
#include <math/vector2d.hpp>
struct rotate_test {
math::coords_t point;
math::decimal_t angle;
math::coords_t basis;
math::coords_t answer;
};
// для фикса утечек gtest при попытки вывода данной структуры
void PrintTo(const rotate_test& bar, std::ostream* os) {
*os << bar.answer.x << " " << bar.answer.y;
}
class GeometryRotateTest
: public testing::TestWithParam<rotate_test> {
public:
GeometryRotateTest()
: parameters(GetParam()) {}
protected:
rotate_test parameters;
math::GeometryFunction geometry;
};
TEST_P(GeometryRotateTest, FunctionRotate) {
math::coords_t ans = geometry.rotate_point(parameters.point,
parameters.angle,
parameters.basis);
EXPECT_PRED2(math::Utilits::is_equal, ans.x, parameters.answer.x);
EXPECT_PRED2(math::Utilits::is_equal, ans.y, parameters.answer.y);
}
// =============================================================================
// тест проверки функции поворота точки вокруг базиса
// point - точка, которую поворачиваем
// angle - угол поворота (положительный -> ппротив часовой стрелки)
// basis - базис вокруг которого поворачиваем
// answer - значение x при котором заданная функция обращается в ноль
// для более подробного изучения можно почитать тут:
// https://ru.xcv.wiki/wiki/Rotation_matrix
// =============================================================================
INSTANTIATE_TEST_SUITE_P(SelectValues, GeometryRotateTest, testing::Values(
rotate_test{
math::coords_t(10, 0.f), 360., math::coords_t(0, 0),
math::coords_t(10, 0.f)
}, rotate_test{
math::coords_t(10, 0), -360., math::coords_t(0, 0),
math::coords_t(10, 0.f)
}, rotate_test{
math::coords_t(10, 0), 180., math::coords_t(0, 0),
math::coords_t(-10, 0.f)
}, rotate_test{
math::coords_t(10, 0), -180., math::coords_t(0, 0),
math::coords_t(-10, 0.f)
}, rotate_test{
math::coords_t(10, 0), 90., math::coords_t(0, 0),
math::coords_t(0.f, 10)
}, rotate_test{
math::coords_t(10, 0), -90., math::coords_t(0, 0),
math::coords_t(0.f, -10)
}, rotate_test{
math::coords_t(10, 0), 65., math::coords_t(0, 0),
math::coords_t(4.22618, 9.06308)
}, rotate_test{
math::coords_t(10, 0), -65., math::coords_t(0, 0),
math::coords_t(4.22618, -9.06308)
}, rotate_test{
math::coords_t(10, 0), 360., math::coords_t(12, 30),
math::coords_t(10, 0.f)
}, rotate_test{
math::coords_t(10, 0), -360., math::coords_t(12, 30),
math::coords_t(10, 0.f)
}, rotate_test{
math::coords_t(10, 0), 180., math::coords_t(12, 30),
math::coords_t(14, 60)
}, rotate_test{
math::coords_t(10, 0), -180., math::coords_t(12, 30),
math::coords_t(14, 60)
}, rotate_test{
math::coords_t(10, 0), 90., math::coords_t(12, 30),
math::coords_t(42, 28)
}, rotate_test{
math::coords_t(10, 0), -90., math::coords_t(12, 30),
math::coords_t(-18, 32)
}, rotate_test{
math::coords_t(10, 0), 65., math::coords_t(12, 30),
math::coords_t(38.34399, 15.50883)
}, rotate_test{
math::coords_t(10, 0), -65., math::coords_t(12, 30),
math::coords_t(-16.03447, 19.13406)
}));
struct relative_line_test {
math::Vector2d line;
math::coords_t start_line;
math::coords_t point;
math::GeometryFunction::point_relative answer;
};
// для фикса утечек gtest при попытки вывода данной структуры
void PrintTo(const relative_line_test& bar, std::ostream* os) {
*os << bar.point.x << " " << bar.point.y;
}
class GeometryRelativeLineTest
: public testing::TestWithParam<relative_line_test> {
public:
GeometryRelativeLineTest()
: parameters(GetParam()) {}
protected:
relative_line_test parameters;
math::GeometryFunction geometry;
};
TEST_P(GeometryRelativeLineTest, FunctionRelativeLine) {
if (parameters.answer == math::GeometryFunction::point_relative::at_left) {
EXPECT_EQ(geometry.point_relative_line(parameters.line,
parameters.start_line,
parameters.point),
parameters.answer)
<< ">> "
<< "Expected that point will be defined to the "
"left of the line";
} else if (parameters.answer ==
math::GeometryFunction::point_relative::at_right) {
EXPECT_EQ(geometry.point_relative_line(parameters.line,
parameters.start_line,
parameters.point),
parameters.answer)
<< ">> "
<< "Expected that point will defined be to the "
"right of the line";
} else {
EXPECT_EQ(geometry.point_relative_line(parameters.line,
parameters.start_line,
parameters.point),
parameters.answer)
<< ">> "
<< "Expected that point will defined on line";
}
}
// =============================================================================
// тест проверки метода опредления положения точки относительно прямой
// line - вектор соответствующий направлению прямой
// start_line - любоя точка прямой
// point - точка положение которой проверяется
// answer - положоние точки относительно прямой,
// если смотреть на неё по направлению вектора: слева, справа, на прямой
// для более подробного изучения можно почитать тут:
// https://habr.com/ru/post/148325/ (задача №1)
// =============================================================================
INSTANTIATE_TEST_SUITE_P(SelectValues, GeometryRelativeLineTest,
testing::Values(
relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(-1, 1),
math::GeometryFunction::point_relative::at_left
}, relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(1.64, 4.52),
math::GeometryFunction::point_relative::at_right
}, relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(8, -3),
math::GeometryFunction::point_relative::on_line
}, relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(-4, 6),
math::GeometryFunction::point_relative::on_line
}, relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(2, -10),
math::GeometryFunction::point_relative::at_left
}, relative_line_test{
math::Vector2d(math::coords_t(-4, 3)),
math::coords_t(4, 0),
math::coords_t(10, 1),
math::GeometryFunction::point_relative::at_right
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(10, 1),
math::GeometryFunction::point_relative::at_left
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(2, -10),
math::GeometryFunction::point_relative::at_right
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(-4, 6),
math::GeometryFunction::point_relative::on_line
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(1.64, 4.52),
math::GeometryFunction::point_relative::at_left
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(-1, 1),
math::GeometryFunction::point_relative::at_right
}, relative_line_test{
math::Vector2d(math::coords_t(4, -3)),
math::coords_t(0, 3),
math::coords_t(8, -3),
math::GeometryFunction::point_relative::on_line
}));
using return_alg = math::AlgebraicMethods::return_for_solve_equastion;
struct algebra_test {
std::function<return_alg(math::decimal_t)> func;
math::decimal_t start_x;
size_t number_itter;
math::decimal_t answer;
};
// для фикса утечек gtest при попытки вывода данной структуры
void PrintTo(const algebra_test& bar, std::ostream* os) {
*os << bar.answer;
}
class AlgebraTest
: public testing::TestWithParam<algebra_test> {
public:
AlgebraTest()
: parameters(GetParam()) {}
protected:
algebra_test parameters;
math::AlgebraicMethods algebra;
};
TEST_P(AlgebraTest, HalleyFunction) {
EXPECT_PRED2(math::Utilits::is_equal,
algebra.solve_equastion_by_Halley(parameters.func,
parameters.start_x,
parameters.number_itter),
parameters.answer);
}
// =============================================================================
// тест проверки метода Галлилея поиска решения уравнения
// func - функция которая по заданному x, возвращаетя значение искодной функции,
// для которой ищется корень, а также её первая и вторая вроизводная
// start_x - приближённое значение, от которого начинается поиск корня
// number_itter - число иттераций алгоритма
// answer - значение x при котором заданная функция обращается в ноль
// для более подробного изучения можно почитать тут:
// https://ru.xcv.wiki/wiki/Halley%27s_method
// =============================================================================
INSTANTIATE_TEST_SUITE_P(SelectValues, AlgebraTest, testing::Values(
algebra_test{ // уравнение X^4 + x^3 + 2 * x^2 - x = 3
[](auto x) -> return_alg {
return {
// сама функция
std::pow(x, 4) +
std::pow(x, 3) + 2. * x * x - x - 3.,
// её первая производная
4. * std::pow(x, 3)
+ 3. * std::pow(x, 2) + 4 * x - 1,
// её вторая производная
12. * std::pow(x, 2) + 6. * x + 4
};
}, math::decm(0.8), 10, math::decm(1)
},
algebra_test{ // уравнение X^4 + x^3 + 2 * x^2 - x = 3
[](auto x) -> return_alg {
return {
// сама функция
std::pow(x, 4) + std::pow(x, 3)
+ 2. * x * x - x - 3.,
// её первая производная
4. * std::pow(x, 3)
+ 3. * std::pow(x, 2) + 4 * x - 1,
// её вторая производная
12. * std::pow(x, 2) + 6. * x + 4
};
}, math::decm(-0.8), 5, math::decm(-1)
},
algebra_test{ // уравнение sqrt(2 * x + 1) = 3
[](auto x) -> return_alg {
return {
// сама функция
sqrt(2 * x + 1) - 3,
// её первая производная
1 / sqrt(2 * x + 1),
// её вторая производная
-1 / ((2 * x + 1) * sqrt(2 * x + 1))};
}, math::decm(0.1), 30, math::decm(4)
},
algebra_test{ // уравнение lg(x-3) + lg(x-2) = 1 + lg(5)
[](auto x) -> return_alg {
return {
// сама функция
std::log10(x - 3) + std::log10(x - 2)
- 1 + std::log10(5),
// её первая производная
1 / ((x - 3) * std::log(10))
+ 1 / ((x - 2) * std::log(10)),
// её вторая производная
(1 / ((x - 3) * (x - 3)) +
1 / ((x - 2) * (x - 2))) / std::log(10)
};
}, math::decm(4.5), 25, math::decm(4)
},
algebra_test{ // уравнение sin(x) = 0
[](auto x) -> return_alg {
return {
// сама функция
sin(x),
// её первая производная
cos(x),
// её вторая производная
-sin(x)
};
}, math::decm(0.8), 3, math::decm(0)
})
);
| true |
162c2d0b227ab57cecf9d3f7fb17e66d09d0079a | C++ | raju2592/problem-solving | /topcoder/PowerOfThree.cpp | UTF-8 | 7,077 | 2.875 | 3 | [] | no_license | /**
* SRM: 604
* Div: 1
* Point: 250
*/
#include<cstdio>
#include<ctime>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<utility>
#define ll long long
#define ull unsigned ll
#define pb push_back
#define mp make_pair
#define ii pair<ll,ll>
#define vi vector<ll>
#define vvi vector<vector<ll> >
#define vvii vector<vector< ii > >
using namespace std;
ll Min(ll i,ll j){return i<j?i:j;}
ll Max(ll i,ll j){return i>j?i:j;}
int MOD(int a,int b){return (a%b+b)%b;}
vector<int> conv(int x)
{
vector<int> ret;
if(x==0)
{
ret.pb(0);
return ret;
}
while(x)
{
if(MOD(x,3)<2)
{
//cout<<MOD(x,3)<<" ";
ret.pb(MOD(x,3));
x=(x-MOD(x,3))/3;
}
else
{
ret.pb(-1);
x=(x+1)/3;
//cout<<-1<<" ";
}
//cout<<x<<endl;
}
return ret;
}
class PowerOfThree {
public:
string ableToGet(int x, int y) {
if(x==0 && y==0) return "Possible";
vector<int> xx=conv(x),yy=conv(y);
int i,j,k,p,q;
/*for(i=0;i<xx.size();i++) if(xx[i]>1) return "Impossible";
for(i=0;i<yy.size();i++) if(yy[i]>1) return "Impossible";*/
p=xx.size();
q=yy.size();
//for(i=0;i<p;i++) cout<<xx[i]<<" ";
//cout<<endl;
//for(i=0;i<q;i++) cout<<yy[i]<<" ";
//cout<<endl;
for(i=0;i<min(p,q);i++)
{
if(xx[i]!=0 && yy[i]!=0) return "Impossible";
else if(xx[i]==0 && yy[i]==0) return "Impossible";
}
if(p<=q)
{
for(j=p;j<q;j++) if(yy[j]==0) return "Impossible";
return "Possible";
}
else
{
for(j=q;j<p;j++) if(xx[j]==0) return "Impossible";
return "Possible";
}
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case(int casenum, const string &expected, const string &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: \"" << expected << "\"" << endl;
cerr << " Received: \"" << received << "\"" << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
/*case 0: {
int x = 1;
int y = 3;
string expected__ = "Possible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
int x = 0;
int y = 2;
string expected__ = "Possible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
int x = 1;
int y = 9;
string expected__ = "Impossible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
int x = 3;
int y = 0;
string expected__ = "Impossible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 4: {
int x = 1;
int y = 1;
string expected__ = "Impossible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 5: {
int x = -6890;
int y = 18252;
string expected__ = "Possible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 6: {
int x = 1000000000;
int y = -1000000000;
string expected__ = "Impossible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 7: {
int x = 0;
int y = 0;
string expected__ = "Possible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
// custom cases
case 8: {
int x = 39;
int y = 1;
string expected__ = "Possible";
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}
/* case 9: {
int x = ;
int y = ;
string expected__ = ;
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 10: {
int x = ;
int y = ;
string expected__ = ;
clock_t start__ = clock();
string received__ = PowerOfThree().ableToGet(x, y);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| true |
1f8928f834597668ec6e412c3eec4ae4cf0a8d45 | C++ | jdisset/gaga | /tests/sqlite_tests.hpp | UTF-8 | 4,805 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "../dna/arraydna.hpp"
#include "../extra/sqlitesave/sqlitesave.hpp"
#include "../gaga.hpp"
#include "../novelty.hpp"
#include "catch/catch.hpp"
#include "dna.hpp"
TEST_CASE("SQL") {
// types that will be used in this test
using dna_t = GAGA::ArrayDNA<int, 256>; // our DNA: 256 integers.
using Ind_t = GAGA::Individual<dna_t>; // Individual type is the default gaga one
using GA_t = GAGA::GA<dna_t, Ind_t>; // and finally the GA type (needs dna_t + ind_t)
// SQL saver setup
SQLiteSaver<GA_t> sql(":memory:"); //:memory: is a keyword that triggers in memory DB
sql.newRun(); // ready to start saving a new evo run
std::string query =
"SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';";
std::vector<std::string> tables;
sql.exec(query, [&](int argc, char** argv, char**) {
for (int i = 0; i < argc; i++) tables.push_back(argv[i]);
});
REQUIRE(tables.size() == 6);
// gaga setup
GA_t ga;
const int POPSIZE = 30;
ga.setPopSize(POPSIZE);
ga.setVerbosity(0);
ga.initPopulation([&]() { return dna_t::random(); });
int evaluationNumber = 0;
ga.setEvaluator([&](auto& i, int) {
// here we use only one fitness: = maximize the sum of all integers in the dna
i.fitnesses["sum"] = std::accumulate(i.dna.values.begin(), i.dna.values.end(), 0);
i.infos = std::to_string(evaluationNumber++);
});
// go!
for (size_t i = 0; i < 10; ++i) {
ga.step();
sql.newGen(ga); // saving the generation to sql
sql.exec("SELECT count(*) FROM individual;", [&](int, char** argv, char**) {
REQUIRE(std::atoi(argv[0]) == POPSIZE * (i + 1));
});
size_t ind_id = 0;
auto& prevPop = ga.previousGenerations.back();
query = "SELECT id,dna,infos FROM individual WHERE id_generation = " +
std::to_string(i + 1) + " ORDER BY id ASC;";
sql.exec(query, [&](int, char** argv, char** col) {
REQUIRE(prevPop[ind_id].dna.serialize() == std::string(argv[1]));
REQUIRE(prevPop[ind_id].infos == std::string(argv[2]));
++ind_id;
});
}
}
TEST_CASE("SQL + Novelty") {
// types that will be used in this test
using dna_t = GAGA::ArrayDNA<int, 256>; // our DNA: 256 integers.
using sig_t = decltype(dna_t::values); // signature type is same as dna.values
using Ind_t = GAGA::NoveltyIndividual<dna_t, sig_t>; // Individual type
using GA_t = GAGA::GA<dna_t, Ind_t>; // and finally the GA type (needs dna_t + ind_t)
// gaga setup
GA_t ga;
// novelty extension
GAGA::NoveltyExtension<GA_t> nov;
ga.useExtension(nov);
// SQL saver setup
SQLiteSaver<GA_t> sql(":memory:"); //:memory: keyword that triggers in-memory DB
sql.useExtension(nov);
sql.newRun(); // ready to start saving a new evo run
const int POPSIZE = 30;
ga.setPopSize(POPSIZE);
ga.setVerbosity(0);
ga.initPopulation([&]() { return dna_t::random(); });
int evaluationNumber = 0;
ga.setEvaluator([&](auto& i, int) {
// here we use only one fitness: = maximize the sum of all integers in the dna
i.fitnesses["sum"] = std::accumulate(i.dna.values.begin(), i.dna.values.end(), 0);
i.signature = i.dna.values;
i.infos = std::to_string(evaluationNumber++);
});
nov.setComputeSignatureDistanceFunction([](const auto& fpA, const auto& fpB) {
double sum = 0;
for (size_t i = 0; i < fpA.size(); ++i) sum += std::pow(fpA[i] - fpB[i], 2);
return sqrt(sum);
});
// go!
for (size_t i = 0; i < 10; ++i) {
ga.step();
sql.newGen(ga); // saving the generation to sql
sql.exec("SELECT count(*) FROM individual;", [&](int, char** argv, char**) {
REQUIRE(std::atoi(argv[0]) == POPSIZE * (i + 1));
});
size_t ind_id = 0;
auto& prevPop = ga.previousGenerations.back();
std::string query =
"SELECT id,dna,infos,signature,original_id FROM individual WHERE id_generation "
"= " +
std::to_string(i + 1) + " ORDER BY id ASC;";
sql.exec(query, [&](int, char** argv, char**) {
REQUIRE(prevPop[ind_id].dna.serialize() == std::string(argv[1]));
REQUIRE(prevPop[ind_id].infos == std::string(argv[2]));
nlohmann::json jsSig = prevPop[ind_id].signature;
REQUIRE(jsSig.dump() == std::string(argv[3]));
REQUIRE(jsSig == nlohmann::json(prevPop[ind_id].dna.values));
REQUIRE(ind_id == std::atoi(argv[4]));
++ind_id;
});
////// archive tests
{
query =
"SELECT id_individual, individual.id_generation, individual.original_id FROM "
"archive_content, "
"individual WHERE "
"id_individual = individual.id AND archive_content.id_generation = " +
std::to_string(i + 1) + ";";
int c = 0;
sql.exec(query, [&](int, char** argv, char**) {
REQUIRE(nov.isArchived(std::pair<size_t, size_t>(
std::atoi(argv[1]) - 1, (size_t)std::atoi(argv[2]))) == true);
c++;
});
REQUIRE(c == nov.archive.size());
}
}
}
| true |
9bc47d8114bea526428ef9d732bf0b57d8ad58bf | C++ | MaSteve/UVA-problems | /UVA10288.cpp | UTF-8 | 1,376 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> ii;
ll gcd(ll n, ll m) {
ll auxi;
if (m > n) {
auxi = n;
n = m, m = auxi;
}
while (m != 0) {
auxi = n;
n = m, m = auxi%m;
}
return n;
}
ii sum (ii & a, ii & b) {
ll n = a.first*b.second + b.first*a.second;
ll d = a.second*b.second;
ll g = gcd(n, d);
return ii(n / g, d / g);
}
ii proc(int n) {
ii res = ii(0, 1), auxi = ii(1, 1);
for (int i = 1; i <= n; i++) {
auxi.second = i;
res = sum (res, auxi);
}
res.first *= n;
ll g = gcd(res.first, res.second);
res.first /= g, res.second /= g;
return res;
}
int main() {
int n;
while (cin >> n) {
ii res = proc(n);
if (res.second == 1) printf("%lld\n", res.first);
else {
ll n = res.first / res.second, m = res.first % res.second, d = res.second;
int ln = floor(log10(n)), lm = floor(log10(m)), ld = floor(log10(d));
for (int i = 0; i <= ln + 1; i++) printf(" ");
printf("%lld\n", m);
printf("%lld ", n);
for (int i = 0; i <= max(lm, ld); i++) printf("-");
printf("\n");
for (int i = 0; i <= ln + 1; i++) printf(" ");
printf("%lld\n", d);
}
}
return 0;
}
| true |
c51359f888fc7ed8661bfdaf008ba217c02919c2 | C++ | habi-a/codingame | /singlePlayer/medium/stock-exchange-losses.cpp | UTF-8 | 898 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
vector<int> valuesDiff;
vector<int> maxLosses;
vector<unsigned int> values;
cin >> n; cin.ignore();
for (int i = 0; i < n; i++)
{
int v;
cin >> v; cin.ignore();
values.push_back(v);
}
for (unsigned int i = 0; i < values.size() - 1; i++)
valuesDiff.push_back(values[i + 1] - values[i]);
maxLosses.push_back(valuesDiff[0]);
for (unsigned int i = 1; i < valuesDiff.size(); i++)
maxLosses.push_back(min(valuesDiff[i], (maxLosses[i - 1] + valuesDiff[i])));
auto pMax = *std::min_element(maxLosses.begin(), maxLosses.end());
if (pMax > 0)
pMax = 0;
cout << pMax << endl;
return 0;
}
| true |
cd89743b92ca267b1483c19290ea9b0b65830fbf | C++ | whosxavierwu/LeetCodeSolution | /leetcode_5069/leetcode_5069.cpp | UTF-8 | 3,202 | 3.125 | 3 | [] | no_license | // leetcode_5069.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
/*
Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: "leetcode"
Output: "tcode"
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
// v1: todo how does it work? it takes 590+ms! this is the solution of the winner
class Solution {
public:
string lastSubstring(string s) {
int n = s.size();
string _s = s + '$'; // why?
vector<int> idxSorted(n + 1); // containing the index
// sort indices in lexicographical order
for (int i = 0; i <= n; ++i) idxSorted[i] = i;
sort(idxSorted.begin(), idxSorted.end(),
[&](int a, int b) {
if (_s[a] == _s[b]) return a > b;
return _s[a] < _s[b];
});
vector<int> c(n + 1, 0), r(n + 1), cnt(n + 1);
for (int i = 0; i <= n; i++) r[i] = _s[i]; // char to int ?
for (int len = 1; len <= n; len *= 2) { // ?
for (int i = 0; i <= n; i++) {
c[idxSorted[i]] = i;
// ?
if (i > 0
&& r[idxSorted[i - 1]] == r[idxSorted[i]]
&& idxSorted[i - 1] + len <= n
&& r[idxSorted[i - 1] + len / 2] == r[idxSorted[i] + len / 2])
c[idxSorted[i]] = c[idxSorted[i - 1]];
}
for (int i = 0; i <= n; ++i) {
cnt[i] = i;
r[i] = idxSorted[i];
}
for (int i = 0; i <= n; ++i) {
int s1 = r[i] - len;
if (s1 >= 0) {
idxSorted[cnt[c[s1]]] = s1;
cnt[c[s1]]++;
}
}
c.swap(r);
}
return s.substr(idxSorted[s.size()]);
}
};
//v2: brute-force 32ms faster than 25.00%
class Solution {
public:
string lastSubstring(string s) {
int i = 0;
for (int j = 1; j < s.size(); ++j) {
int sz = 0;
for (; j + sz < s.size(); ++sz) {
if (s[i + sz] == s[j + sz]) continue;
if (s[j + sz] > s[i + sz]) i = j;
break;
}
if (j + sz == s.size()) break;
}
return s.substr(i);
}
};
//v3: 32ms
class Solution {
public:
string lastSubstring(string s) {
int n = s.size();
vector<int> pre(n, 0);
int start = 0;
int to_match = 0;
for (int i = 1; i < s.size(); ++i) {
if (s[i] > s[start]) {
start = i;
to_match = start;
}
else if (s[to_match] == s[i]) {
if (i - start <= 2 * (to_match - start)) {
pre[to_match] = to_match - start;
start = to_match;
to_match = start + 1;
}
else {
to_match++;
}
}
else if (s[to_match] > s[i]) {
to_match = start;
}
else if (s[to_match] < s[i]) {
start = i - (to_match - start);
to_match = start;
}
}
int tot = 0;
int pos = start;
while (pos > 0) {
tot += pre[pos];
pos -= pre[pos];
if (pre[pos] == 0) break;
}
return s.substr(start - tot);
}
};
int main()
{
Solution sol;
string s;
s = "abab";
cout << sol.lastSubstring(s) << endl;
s = "leetcode";
cout << sol.lastSubstring(s) << endl;
s = "xbylisvborylklftlkcioajuxwdhahdgezvyjbgaznzayfwsaumeccpfwamfzmkinezzwobllyxktqeibfoupcpptncggrdqbkji";
cout << sol.lastSubstring(s) << endl;
}
| true |
1afa495d56c009ededb058710a8e1d5df2878442 | C++ | redhatlonghairdontcare/fastcat | /src/manager.h | UTF-8 | 6,094 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef FASTCAT_MANAGER_H_
#define FASTCAT_MANAGER_H_
// Include related header (for cc files)
// Include c then c++ libraries
#include <memory>
#include <queue>
#include <unordered_map>
#include <vector>
// Include external then project includes
#include <yaml-cpp/yaml.h>
#include "fastcat/device_base.h"
#include "jsd/jsd_print.h"
namespace fastcat
{
typedef std::pair<std::string, std::shared_ptr<DeviceBase>> DevicePair;
typedef std::pair<std::string, jsd_t*> JSDPair;
/** @brief Fastcat::Manager is the main application interface to manage all fastcat devices
*/
class Manager
{
public:
Manager();
~Manager();
/** @brief Shutdown the bus and joins all threads.
*
* Also Writes Actuator positions to file if applicable.
* @return void
*/
void Shutdown();
/** @brief Method that accepts a fastcat topology yaml and intializes bus
*
* @return true on successful initialization. If false, application should quit.
*/
bool ConfigFromYaml(YAML::Node node);
/** @brief Updates synchronous PDO and background async SDO requests.
*
* Process() proceeds by
* 1. Triggers PDO Read on EtherCAT bus
* 2. Reads all JSD devices into the manager
* 3. Reads all Fastcat devices (including observed device state propagation)
* 4. Calls DeviceBase::Process() on Fastcat Devices, checking for faults and SDO requests
* 5. Writes Device Commands (Includes User commands and Fastcat Device Commands)
* 6. Calls Process() on JSD devices, checking for faults
* 7. Triggers PDO Write on EtherCAT bus
*
* Note: For best performance, the application should call the Manager::Process() function
* at the same frequency as the input YAML field `target_loop_rate_hz`. This parameter is
* needed by certain devices for profiling and filtering.
*
* @return Return true if bus is not faulted, otherwise a bus fault is active.
*/
bool Process();
/** @brief Interface to command devices on the bus
*
* Commands each have a name field and that name is used to dispatch the command to
* the right device. If the provided name is not found on the loaded bus topology, a
* warning message is printed to stdout but no faults are triggered.
*
* @return void
*/
void QueueCommand(DeviceCmd& cmd);
/** @brief Returns list of device states
*
* @return device states
*/
std::vector<DeviceState> GetDeviceStates();
/** @brief Returns list of device state pointers
*
* Provided for potential optimization. GetDeviceStates() generally performs better.
* @return device states
*/
std::vector<std::shared_ptr<const DeviceState>> GetDeviceStatePointers();
/** @brief Public getter to the YAML `target_loop_rate_hz` parameter
* @return loop rate in hz
*/
double GetTargetLoopRate();
/** @brief Public getter retrieve fault status
* @return true if bus is faulted
*/
bool IsFaulted();
/** @brief Attempts to recover a faulty JSD bus by name
*
* A bus fault example is spurious Working Counter (WKC) error, or perhaps an intended
* power cycle of a configured EtherCAT slave.
*
* @param ifname the name of the JSD bus configured in the input topology YAML
* @return true if bus ifname exists, does not indicate the error is fixed.
*/
bool RecoverBus(std::string ifname);
/** @brief Triggers a single device to reset
*
* @param device_name the name of the device to reset, calls its Reset() method
* @return true if the device exists, false if device_name is invalid.
*/
bool ExecuteDeviceReset(std::string device_name);
/** @brief Triggers a single device to fault
*
* @param device_name the name of the device to fault, calls its Fault() method
* @return true if the device exists, false if device_name is invalid.
*/
bool ExecuteDeviceFault(std::string device_name);
/** @brief Triggers all devices to Reset
*
* This function loops over all devices in the topology and calls their DeviceBase::Reset()
* Method.
*
* @return void
*/
void ExecuteAllDeviceResets();
/** @brief Triggers all devices to Fault
*
* This function loops over all devices in the topology and calls their DeviceBase::Fault()
* Method. An example usage is a soft-stop GUI button that can be used to arrest motion.
*
* @return void
*/
void ExecuteAllDeviceFaults();
private:
bool ConfigJSDBusFromYaml(YAML::Node node);
bool ConfigFastcatBusFromYaml(YAML::Node node);
bool ConfigOfflineBusFromYaml(YAML::Node node);
bool WriteCommands();
bool ConfigSignals();
bool SortFastcatDevice(
std::shared_ptr<DeviceBase> device,
std::vector<std::shared_ptr<DeviceBase>>& sorted_devices,
std::vector<std::string> parents);
bool LoadActuatorPosFile();
bool ValidateActuatorPosFile();
bool SetActuatorPositions();
void GetActuatorPositions();
void SaveActuatorPosFile();
bool CheckDeviceNameIsUnique(std::string name);
double target_loop_rate_hz_;
bool zero_latency_required_ = true;
bool faulted_ = false;
bool actuator_fault_on_missing_pos_file_ = true;
std::string actuator_position_directory_;
std::map<std::string, jsd_t*> jsd_map_;
std::map<std::string, std::shared_ptr<DeviceBase>> device_map_;
std::vector<std::shared_ptr<DeviceBase>> fastcat_device_list_;
std::vector<std::shared_ptr<DeviceBase>> jsd_device_list_;
std::shared_ptr<std::queue<DeviceCmd>> cmd_queue_;
std::vector<DeviceState> states_;
std::map<std::string, ActuatorPosData> actuator_pos_map_;
std::unordered_map<std::string, bool> unique_device_map_;
};
} // namespace fastcat
#endif
| true |
c84cdf112a74a6b6344dd61ff0c00f68357e2a0a | C++ | Strider-7/code | /BST/pair-with-given-sum.cpp | UTF-8 | 2,029 | 3.578125 | 4 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int x)
{
data = x;
left = nullptr;
right = nullptr;
}
};
Node *insert(Node *root, int data) {
if (!root)
return new Node(data);
if (data==root->data)
return nullptr;
else if (data<root->data)
root->left=insert(root->left, data);
else
root->right=insert(root->right, data);
return root;
}
void inOrder(Node *root, unordered_set <int> &s) {
if (root)
{
inOrder(root->left, s);
s.insert(root->data);
inOrder(root->right, s);
}
}
bool findPair(vector <int> arr, int k)
{
int low = 0, high = arr.size()- 1;
while (low < high)
{
if (k == arr[low] + arr[high])
return true;
if (arr[low] + arr[high] > k)
high--;
else
low++;
}
return false;
}
bool pairExists(Node *root, int sum) {
if (!root)
return false;
unordered_set <int> s;
inOrder(root, s);
for (auto &&i : s)
{
auto itr=s.find(sum-i);
if (itr!=s.end() && *itr!=i)
return true;
}
return false;
}
bool pairWithSum(Node *root, int sum, unordered_set <int> &s) {
if (!root)
return false;
if (pairWithSum(root->left, sum, s))
return true;
if (s.find(sum-root->data)!=s.end())
return true;
else
s.insert(root->data);
return pairWithSum(root->right, sum, s);
}
int main() {
Node *root=nullptr;
root=insert(root, 40);
root=insert(root, 30);
root=insert(root, 60);
root=insert(root, 50);
root=insert(root, 70);
root=insert(root, 20);
root=insert(root, 10);
cout<<pairExists(root, 20)<<endl;
unordered_set <int> s;
cout<<pairWithSum(root, 20, s);
return 0;
} | true |
42eba828b8cd6fa441303bd6e7ec40e8057da02f | C++ | Adarsh76/C-plus-plus-programs | /C_BY_REF.CPP | UTF-8 | 368 | 3.625 | 4 | [] | no_license | //WAP to swap two nos using call by references parameter(by alias)
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
void swap ( int &,int &);
clrscr();
cout<<"\n Enter X and Y ";
cin>>x>>y;
swap(x,y);
cout<<"\n After swapping "<<x<<" "<<y;
getch();
}
void swap(int &a, int &b)
{
int c;
c=a;
a=b;
b=c;
} | true |
63949d2c666f83c35d275da60e51af2b9d54e7a3 | C++ | JoshuaHolloway/Parallel_Programming | /Windows/Threading_Advisor_Exercise_Files/01_01/Advisor Demo App/Advisor Demo App/src/TaskHandler.h | UTF-8 | 1,831 | 3.484375 | 3 | [] | no_license | #ifndef TASK_HANDLER_H
#define TASK_HANDLER_H
#include <thread>
#include <chrono>
using namespace std;
// The TaskHandler object is a thread which handles asynchronous execution of a given task.
// It takes in a task to be repeatedly executed on a separate thread.
class TaskHandler
{
public:
static const long s_Infinite = -1L;
// constructors
TaskHandler();
// overloaded constructors to allow easier thread initialization
TaskHandler(const function<void(void)> &f);
TaskHandler(const function<void(void)> &f, const unsigned long &i, const long repeat = TaskHandler::s_Infinite);
// starts the timer thread
void Start(bool Async = true);
// stops the timer thread via join
void Stop();
// check thread alive status flag
bool IsAlive() const;
// setter for number of repeats
void SetTaskRepeatCount(const long r);
// set thread function
void SetTask(const function<void(void)> &f);
// returns number of task calls left
long GetTaskCallsLeft() const;
// returns number of repeats
long GetTaskRepeatCount() const;
// set time for thread to sleep for
void SetThreadSleepTime(const unsigned long &i);
// get thread sleep time
unsigned long GetThreadSleepTime() const;
// get thread function
const function<void(void)>& GetTask() const;
private:
thread m_thread; // thread for asynchronous execution
bool m_alive = false; // is the process alive (running)?
long m_taskCallNumber = -1L; // how many times to call a function
long m_taskCallCount = -1L; // how many times a function has been called
chrono::milliseconds m_sleepTime = chrono::milliseconds(0); // time between function calls
// a pointer to a function (initialized as null)
function<void(void)> m_task = nullptr;
// thread functions
void SleepAndRun();
void ThreadTask();
};
#endif // TaskHandler_H | true |
d31d3f300ee0999b696405dfeca0f42ef050641c | C++ | wangxing0608/CtCI | /Linked_Lists/Partition.cpp | UTF-8 | 2,825 | 4.125 | 4 | [] | no_license | //
// Created by wangxing on 19-7-12.
//
// 2.3 使用x分隔链表中的节点,使得节点中数值小于x的出现在x节点之前,大于x的出现在x之后
// 如果x出现在链表中,只需要出现在比它小的节点之后
#include <iostream>
#include <random>
struct Node {
int data;
Node *next;
Node (int d): data{ d }, next {nullptr} {}
};
void insert(Node * &head, int data)
{
Node *newNode = new Node(data);
if (head == nullptr) {
head = newNode;
} else {
Node *curr = head;
// 链表的头插法
while (curr->next)
{
curr = curr -> next;
}
curr -> next = newNode;
}
}
void printList(Node *head)
{
while (head)
{
std::cout << head->data << "-->";
head = head -> next;
}
std::cout << "nullptr" << std::endl;
}
// 将链表中元素值大于x的插入到x之后,小于x的插入到头结点之后
Node *partition(Node *listhead, int x)
{
Node *head = nullptr; // head 链表中的指针
Node *headInitial = nullptr; // head 链表的头结点
Node *tail = nullptr;
Node *tailInitial = nullptr; // tail 链表中的指针
Node *curr = listhead; // tail链表的头结点
// 遍历链表
while (curr != nullptr)
{
Node *nextNode = curr -> next;
// 当前节点元素小于x,在head链表中添加节点
if (curr -> data < x) {
// 如果tail链表为空,使用第一个小于x的元素初始化head链表
if (head == nullptr) {
head = curr;
headInitial = head;
}
// head链表非空, head指针指向的节点链接在head链表后
head -> next = curr;
head = curr;
}
// 当前元素大于等于x,在tail链表中添加节点
else {
// 如果tail链表为空,使用第一个小于x的元素初始化head链表
if (tail == nullptr) {
tail = curr;
tailInitial = tail;
}
// tail链表非空, tail指针指向的节点链接在head链表后
tail -> next = curr;
tail = curr;
}
curr = nextNode;
}
// 原始链表遍历完后,将两个链表链接在一起
head -> next = tailInitial;
tail -> next = nullptr; // tail指针指向新的链表的最后一个节点,它的尾节点为nullptr
return headInitial; // 返回新的链表
}
int main()
{
Node *head = nullptr;
for (int i = 0; i < 10; i++)
{
insert(head, rand() % 9);
}
std::cout << "List before partition around 5:\n";
printList(head);
std::cout << "List after partition around 5:\n";
printList(partition(head, 5));
return 0;
}
| true |
0afe3760d9d9dc3447ec2f4699f03919b076f394 | C++ | sakibakon/template- | /lower_bound.cpp | UTF-8 | 1,984 | 4.28125 | 4 | [] | no_license | // C++ code to demonstrate the working of lower_bound()
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i=0;
vector<int> arr1(6);// = {10, 15, 20, 25, 30, 35};
arr1[i++]=10; arr1[i++]=15;arr1[i++]=20;arr1[i++]=25;arr1[i++]=30;arr1[i++]=35;
cout << "The position of 20 using lower_bound "
" (in single occurrence case) : ";
int j= (int)(lower_bound(arr1.begin(), arr1.end(), 20) - arr1.begin());
cout << arr1[j--]<<" ";
cout << arr1[j--]<<" ";
cout << arr1[j]<<" ";
cout << endl;
// initializing vector of integers
// for multiple occurrences
i=0;
arr1[i++]=10; arr1[i++]=15;arr1[i++]=20;arr1[i++]=20;arr1[i++]=25;arr1[i++]=30;
cout << "The position of 20 using lower_bound "
"(in multiple occurrence case) : ";
j= (int)(lower_bound(arr1.begin(), arr1.end(), 20) - arr1.begin());
cout << arr1[j--]<<" ";
cout << arr1[j--]<<" ";
cout << arr1[j]<<" ";
cout << endl;
// initializing vector of integers
// for no occurrence
i=0;
arr1[i++]=10; arr1[i++]=15;arr1[i++]=25;arr1[i++]=30;arr1[i++]=35;
cout << "The position of 20 using lower_bound "
"(in no occurrence case) : ";
j= (int)(lower_bound(arr1.begin(), arr1.end(), 20) - arr1.begin());
cout << arr1[j--]<<" ";
cout << arr1[j--]<<" ";
cout << arr1[j]<<" ";
cout << endl;
// using lower_bound() to check if 20 exists
// single occurrence
// prints 2
// using lower_bound() to check if 20 exists
// multiple occurrence
// prints 2
// using lower_bound() to check if 20 exists
// no occurrence
// prints 2 ( index of next higher)
}
//Output:
//The position of 20 using lower_bound (in single occurrence case) : 2
//The position of 20 using lower_bound (in multiple occurrence case) : 2
//The position of 20 using lower_bound (in no occurrence case) : 2
| true |
5db187f6885642fe7bc4fc3161704ef8ceaa9a37 | C++ | Riflio/Cameron | /Plugins/usingleton.h | UTF-8 | 887 | 3.078125 | 3 | [] | no_license | #ifndef USINGLETON_H
#define USINGLETON_H
#include <QtGlobal>
//#pragma warning(disable : 4355)
template <class T>
class uSingleton {
public:
uSingleton(T& rObject) {
Q_ASSERT_X(!s_pInstance, "constructor", "Only one instance of this class is permitted.");
s_pInstance = &rObject;
}
~uSingleton() {
Q_ASSERT_X(s_pInstance, "destructor", "The singleton instance is invalid.");
s_pInstance = 0;
}
static T& instance() {
if(!s_pInstance) {
s_pInstance = new T();
}
//Q_ASSERT_X(s_pInstance, "instancing", "The singleton has not yet been created.");
return (*s_pInstance);
}
private:
static T* s_pInstance;
uSingleton(const uSingleton& Src);
uSingleton& operator=(const uSingleton& Src);
};
template <class T> T* uSingleton<T>::s_pInstance = 0;
#endif // USINGLETON_H
| true |
c1cd8e892dc8ed9d5c8722f0cfc9e5f6a766a5dd | C++ | Lisaflyz/TextDetection | /swt/Line.cpp | UTF-8 | 2,705 | 3.25 | 3 | [] | no_license | #include <math.h>
#include <opencv2/core/core.hpp>
#include "Line.hpp"
/**
* Line drawing based on Breseham's algorithm
*
* @author naoki
*
*/
Line::Line() {
}
/**
* Line drawing using the Simplification code in Wiki.
*
* point.x: vertical direction (row) point.y: horizontal direction (column)
*
* @param image
* @param p0
* @param y0
*/
void Line::draw(cv::Mat image, cv::Point p0, cv::Point p1, cv::Scalar value) {
int dx = (int) abs(p1.x - p0.x);
int dy = (int) abs(p1.y - p0.y);
int sx, sy;
int err = dx - dy;
unsigned int data[3];// = new byte[3];
if(image.channels() == 3){
for(int i = 0;i < 3;i++){
data[i] = (unsigned int) value.val[i];
}
}
if (p0.x < p1.x) {
sx = 1;
} else {
sx = -1;
}
if (p0.y < p1.y) {
sy = 1;
} else {
sy = -1;
}
int max_step;
if (dx > dy) {
max_step = dx;
} else {
max_step = dy;
}
int count = 0;
int x = (int) p0.x;
int y = (int) p0.y;
while (count <= max_step) {
for(int i = 0;i < 3;i++){
image.at<uchar>(y,x,i) = data[i];
}
if (x == p1.x && y == p1.y) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x += sx;
}
if (x == p1.x && y == p1.y) {
for(int i = 0;i < 3;i++){
image.at<uchar>(y,x,i) = data[i];
}
break;
}
if (e2 < dx) {
err += dx;
y += sy;
}
count++;
}
}
/**
* draw a line
* @param image
* @param p0
* @param dx
* @param dy
* @param value
*/
void Line::draw(cv::Mat image, cv::Point p0, double n_dx, double n_dy, cv::Scalar value) {
int dx = (int) (n_dx * 100.0);
int dy = (int) (n_dy * 100.0);
int sx, sy;
int err = dx - dy;
cv::Point p1 = cv::Point(p0.x + dx, p0.y + dy);
unsigned int data[3]; // = new byte[3];
if(image.channels() == 3){
for(int i = 0;i < 3;i++){
data[i] = (unsigned int) value.val[i];
}
}
if (p0.x < p1.x) {
sx = 1;
} else {
sx = -1;
}
if (p0.y < p1.y) {
sy = 1;
} else {
sy = -1;
}
int max_step;
if (dx > dy) {
max_step = dx;
} else {
max_step = dy;
}
int count = 0;
int x = (int) p0.x;
int y = (int) p0.y;
while (count <= max_step) {
for(int i = 0;i < 3;i++){
image.at<uchar>(y,x,i) = data[i];
}
if (x == p1.x && y == p1.y) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x += sx;
}
if (x == p1.x && y == p1.y) {
for(int i = 0;i < 3;i++){
image.at<uchar>(y,x,i) = data[i];
}
break;
}
if (e2 < dx) {
err += dx;
y += sy;
}
count++;
}
}
| true |
e033e5fcbf9c8d754a36dcdff4d5df6181af9c1b | C++ | famez/J1939-Framework | /Tests/SPNStatus_test.cpp | UTF-8 | 2,866 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <gtest/gtest.h>
#include <J1939Common.h>
#include <SPN/SPNStatus.h>
using namespace J1939;
TEST(SPNStatus_test, constructor) {
//Test constructor
SPNStatusSpec::DescMap valueToDesc {
{0, "Desc 0"},
{1, "Desc 1"},
{2, "Desc 2"},
{3, "Desc 3"},
};
SPNStatus status(100, "test_status", 4, 2, 2, valueToDesc);
ASSERT_EQ(status.getSpnNumber(), 100);
ASSERT_EQ(status.getName(), "test_status");
ASSERT_EQ(status.getOffset(), 4);
ASSERT_EQ(status.getBitOffset(), 2);
ASSERT_EQ(status.getBitSize(), 2);
ASSERT_EQ(status.getType(), SPN::SPN_STATUS);
ASSERT_EQ(status.getValueDescription(0), "Desc 0");
ASSERT_EQ(status.getValueDescription(1), "Desc 1");
ASSERT_EQ(status.getValueDescription(2), "Desc 2");
ASSERT_EQ(status.getValueDescription(3), "Desc 3");
}
TEST(SPNStatus_test, copy_constructor) {
SPNStatusSpec::DescMap valueToDesc {
{0, "Desc 0"},
{1, "Desc 1"},
{2, "Desc 2"},
{3, "Desc 3"},
};
SPNStatus status(100, "test_status", 4, 2, 2, valueToDesc);
ASSERT_EQ(status.getBitSize(), 2);
status.setValue(3);
//Test copy constructor
SPNStatus status2(status);
ASSERT_EQ(status2.getSpnNumber(), 100);
ASSERT_EQ(status2.getName(), "test_status");
ASSERT_EQ(status2.getOffset(), 4);
ASSERT_EQ(status2.getBitOffset(), 2);
ASSERT_EQ(status2.getBitSize(), 2);
ASSERT_EQ(status2.getType(), SPN::SPN_STATUS);
ASSERT_EQ(status2.getValueDescription(0), "Desc 0");
ASSERT_EQ(status2.getValueDescription(1), "Desc 1");
ASSERT_EQ(status2.getValueDescription(2), "Desc 2");
ASSERT_EQ(status2.getValueDescription(3), "Desc 3");
ASSERT_EQ(status2.getValue(), 3);
}
TEST(SPNStatus_test, encode) {
try {
{
SPNStatus status1(1, "test_status1", 4, 0, 2);
SPNStatus status2(2, "test_status2", 4, 2, 2);
SPNStatus status3(3, "test_status3", 4, 4, 2);
SPNStatus status4(4, "test_status4", 4, 6, 2);
u8 val;
//Test encoding
status1.setValue(0);
status2.setValue(1);
status3.setValue(2);
status4.setValue(3);
status1.encode(&val, 1);
status2.encode(&val, 1);
status3.encode(&val, 1);
status4.encode(&val, 1);
ASSERT_EQ(val, 0xE4);
}
{
SPNStatus status1(10, "test_status1", 1, 0, 2);
SPNStatus status2(20, "test_status2", 1, 2, 2);
SPNStatus status3(30, "test_status3", 1, 4, 4);
u8 val;
//Test encoding
status1.setValue(2);
status2.setValue(1);
status3.setValue(7);
status1.encode(&val, 1);
status2.encode(&val, 1);
status3.encode(&val, 1);
ASSERT_EQ(val, 0x76);
}
{
SPNStatus status1(10, "test_status1", 1, 0, 5);
SPNStatus status2(20, "test_status2", 1, 5, 3);
u8 val;
//Test encoding
status1.setValue(30);
status2.setValue(6);
status1.encode(&val, 1);
status2.encode(&val, 1);
ASSERT_EQ(val, 0xDE);
}
SUCCEED();
} catch(J1939EncodeException&) {
FAIL();
}
}
| true |
253dc93221067bd04d6b3a61202d124e2eea9442 | C++ | OHDSI/Cyclops | /standalone/codebase/CCD/imputation/ImputationPolicy.cpp | UTF-8 | 4,896 | 2.546875 | 3 | [
"Zlib",
"Apache-2.0"
] | permissive | /*
* ImputationHelper.cpp
*
* Created on: Jul 28, 2012
* Author: Sushil Mittal
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <time.h>
#include "ImputationPolicy.h"
#define MAX_ENTRIES 1000000000
#define FORMAT_MATCH_1 "CONDITION_CONCEPT_ID"
#define MATCH_LENGTH_1 20
#define FORMAT_MATCH_2 "PID"
#define MATCH_LENGTH_2 3
#define MISSING_STRING "NA"
#define MISSING_LENGTH -1
#define DELIMITER ","
namespace bsccs {
using namespace std;
ImputationHelper::ImputationHelper(){
nMissingY = 0;
nCols_Orig = 0;
}
ImputationHelper::~ImputationHelper() { }
/**
* Reads in a dense CSV data file with format:
* Stratum,Outcome,X1 ...
*
**/
template <class InputIterator1, class InputIterator2>
int set_intersection(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2)
{
int result = 0;
while (first1!=last1 && first2!=last2)
{
if(*first1 < *first2)
++first1;
else if(*first2 < *first1)
++first2;
else{
result++;
first1++;
first2++;
}
}
return result;
}
template <class InputIterator>
int set_difference(int* columns, int length, InputIterator first2, InputIterator last2)
{
int result = length;
int i = 0;
while(i < length && first2 != last2)
{
if(columns[i] < *first2)
i++;
else if(*first2 < columns[i])
++first2;
else{
result--;
i++;
first2++;
}
}
return result;
}
void ImputationHelper::sortColumns(){
colIndices.clear();
srand(time(NULL));
vector<int> rands;
for(int i = 0; i < nCols_Orig; i++){
colIndices.push_back(i);
rands.push_back(rand());
}
sort(colIndices.begin(),colIndices.end(),Compare(nMissingPerColumn,rands));
reverseColIndices.resize(nCols_Orig,0);
for(int i = 0; i < nCols_Orig; i++)
reverseColIndices[colIndices[i]] = i;
reindexVector(nMissingPerColumn,colIndices);
vector<int_vector*> missingEntries_ = missingEntries;
for(int i = 0; i < nCols_Orig; i++){
missingEntries[i] = missingEntries_[colIndices[i]];
}
}
void ImputationHelper::resortColumns(){
reindexVector(nMissingPerColumn,reverseColIndices);
vector<int_vector*> missingEntries_ = missingEntries;
for(int i = 0; i < nCols_Orig; i++){
missingEntries[i] = missingEntries_[reverseColIndices[i]];
}
colIndices.clear();
for(int i = 0; i < nCols_Orig; i++)
colIndices.push_back(i);
reverseColIndices = colIndices;
}
void ImputationHelper::push_back(int_vector* vecMissing, int nMissing){
missingEntries.push_back(vecMissing);
nMissingPerColumn.push_back(nMissing);
nCols_Orig++;
}
void ImputationHelper::push_back(int col, int indMissing){
missingEntries[col]->push_back(indMissing);
nMissingPerColumn[col]++;
}
void ImputationHelper::push_backY(int indMissing){
missingEntriesY.push_back(indMissing);
nMissingY++;
}
void ImputationHelper::includeYVector(){
push_back(&missingEntriesY,missingEntriesY.size());
}
void ImputationHelper::pop_back(){
missingEntries.pop_back();
nMissingPerColumn.pop_back();
nCols_Orig--;
}
const vector<int>& ImputationHelper::getnMissingPerColumn() const{
return nMissingPerColumn;
}
const vector<int>& ImputationHelper::getSortedColIndices() const{
return colIndices;
}
const vector<int>& ImputationHelper::getReverseColIndices() const{
return reverseColIndices;
}
void ImputationHelper::setWeightsForImputation(int col, vector<real>& weights, int nRows){
weights.clear();
weights.resize(nRows,1.0);
for(int i = 0; i < (int)missingEntries[col]->size(); i++)
weights[(missingEntries[col])->at(i)] = 0.0;
}
int ImputationHelper::getOrigNumberOfColumns(){
return nCols_Orig;
}
vector<real> ImputationHelper::getOrigYVector(){
return y_Orig;
}
void ImputationHelper::saveOrigYVector(real* y, int nRows){
y_Orig.resize(nRows,0.0);
for(int i = 0; i < nRows; i++)
y_Orig[i] = y[i];
}
void ImputationHelper::saveOrigNumberOfColumns(int nCols){
nCols_Orig = nCols;
}
void ImputationHelper::getMissingEntries(int col, vector<int>& missing){
missing = *missingEntries[col];
}
void ImputationHelper::getSampleMeanVariance(int col, real& Xmean, real& Xvar, real* dataVec, int* columnVec, FormatType formatType, int nRows, int nEntries){
real sumx2 = 0.0;
real sumx = 0.0;
int n = nRows - (int)missingEntries[col]->size();
if(formatType == DENSE) {
int ind = 0;
for(int i = 0; i < nRows; i++){
if(ind < (int)missingEntries[col]->size()){
if(i == missingEntries[col]->at(ind)){
ind++;
}
else{
real xi = dataVec[i];
sumx2 += xi * xi;
sumx += xi;
}
}
else{
real xi = dataVec[i];
sumx2 += xi * xi;
sumx += xi;
}
}
}
else{
sumx = set_difference(columnVec,nEntries, missingEntries[col]->begin(), missingEntries[col]->end());
sumx2 = sumx;
}
Xmean = sumx/n;
Xvar = (sumx2 - Xmean*Xmean*n)/(n-1);
}
} // namespace
| true |
5145c1a7844b1a23373777a717d1e9bd21e7e3fe | C++ | michelwandermaas/p_hamiltonian_heuristic | /BinaryHeap.h | UTF-8 | 456 | 2.75 | 3 | [] | no_license | #ifndef BINARY_HEAP_H
#define BINARY_HEAP_H
#include <math.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MINUS_INFINITY -10000000000.0
class BHNode
{
public:
double key;
int p;
int position;
};
class BinaryHeap
{
public:
BinaryHeap(int n);
~BinaryHeap();
void Insert(BHNode *node);
BHNode* DeleteMin();
void DecreaseKey(BHNode *node);
void Clear();
BHNode *sentinel;
BHNode **elements;
int size;
};
#endif
| true |
f06b28b4173d69927c4a617139a1a37c3920bdf9 | C++ | PawelZydek/university-db | /src/Pesel.cpp | UTF-8 | 3,989 | 3.078125 | 3 | [] | no_license | #include "Pesel.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
static constexpr int peselLen{11};
Pesel::Pesel(const std::array<uint8_t, 11>& numbers) : pesel_(numbers) {}
int Pesel::get_day() const {
return pesel_.at(4) * 10 + pesel_.at(5);
}
int Pesel::get_month() const {
int monthNum{pesel_.at(2) * 10 + pesel_.at(3)};
switch (pesel_.at(2)) {
case 8:
case 9:
return monthNum - 80;
case 0:
case 1:
return monthNum;
case 2:
case 3:
return monthNum - 20;
case 4:
case 5:
return monthNum - 40;
case 6:
case 7:
return monthNum - 60;
default:
return -1;
}
}
int Pesel::get_year() const {
int lastTwoDigits{pesel_.at(0) * 10 + pesel_.at(1)};
switch (pesel_.at(2)) {
case 8:
case 9:
return 1800 + lastTwoDigits;
case 0:
case 1:
return 1900 + lastTwoDigits;
case 2:
case 3:
return 2000 + lastTwoDigits;
case 4:
case 5:
return 2100 + lastTwoDigits;
case 6:
case 7:
return 2200 + lastTwoDigits;
default:
return -1;
}
}
bool isLeap(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
return true;
}
return false;
}
int getDayCount(int monthNumber, int year) {
switch (monthNumber) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return isLeap(year) ? 29 : 28;
default:
return 0;
}
}
bool Pesel::validation_date() const {
int day = get_day();
int month = get_month();
int year = get_year();
if (month < 1 || month > 12 || day < 1 || day > getDayCount(month, year)) {
return false;
}
return true;
}
bool Pesel::validation_check_digit() const {
static constexpr std::array<uint8_t, 10> weights{1, 3, 7, 9, 1,
3, 7, 9, 1, 3};
int sum{0};
for (size_t i{0}; i < weights.size(); ++i) {
sum += pesel_.at(i) * weights[i];
}
auto modulo = sum % 10;
return (modulo == 0 && pesel_.at(10) == 0) || 10 - modulo == pesel_.at(10);
}
bool Pesel::validation_numbers() const {
return std::none_of(pesel_.cbegin(), pesel_.cend(),
[](const auto num) { return num >= 10; });
}
std::string Pesel::get_string() const {
std::string str{};
str.reserve(11);
for (auto num : pesel_) {
str.push_back(static_cast<char>(num + '0'));
}
return str;
}
bool Pesel::is_valid() const {
if (validation_check_digit() && validation_date() && validation_numbers()) {
// Both function return true on success
return true;
}
return false;
}
std::istream& operator>>(std::istream& in, Pesel& pesel) {
char ch{};
for (size_t i = 0; i < peselLen; ++i) {
in >> ch;
if (!isdigit(ch)) {
in.putback(ch);
in.clear(std::ios_base::failbit);
return in;
}
pesel.pesel_[i] = ch - '0';
}
return in;
}
std::ostream& operator<<(std::ostream& out, const Pesel& pesel) {
return out << pesel.get_string();
}
bool operator<(const Pesel& pesel1, const Pesel& pesel2) {
for (size_t i{0}; i < peselLen; ++i) {
if (pesel1.pesel_.at(i) > pesel2.pesel_.at(i)) {
return false;
} else if (pesel1.pesel_.at(i) < pesel2.pesel_.at(i)) {
return true;
}
}
return false;
}
bool operator==(const Pesel& pesel1, const Pesel& pesel2) {
return std::equal(pesel1.pesel_.cbegin(), pesel1.pesel_.cend(),
pesel2.pesel_.cbegin());
}
| true |
d1666b807108a70803031aef42976d17e49e4801 | C++ | jdileo4/JohnMarianoKevin | /Parse.cpp | UTF-8 | 13,332 | 3.21875 | 3 | [] | no_license | #include "Token.h"
#include "Engine.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
//TODO:
#define TYPE_ERROR -1
#define CANT_FIND_TABLE -21
Engine engine;
bool isInteger(const string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;
char * p ;
strtol(s.c_str(), &p, 10) ;
return (*p == 0) ;
}
int createTable(vector<string> operations){
string tableName;
vector<string> data;
vector<string> keys;
//Take the name out of the vector
tableName = operations[2];
//Insert parameters in data vector
for(int i = 3; i < operations.size(); i++ ){
if( (i%2 == 0) && ( (operations[i] != "STRING") && (operations[i] != "INTERGER") ) ){
return TYPE_ERROR;
}
//If we find primary, the first key should be positioned at i+2
else if( operations[i] == "PRIMARY" ){
//Get keys from i+2 until end of vector
for(int j = i+2; j < operations.size(); j++){
keys.push_back(operations[j]);
}
//No more things, break;
break;
}
else{
data.push_back(operations[i]);
}
}
//Engine.
return 0;
}
int insertInto(vector<string> operations){
string tableName = operations[2];
vector<Datum> data;
for(int i = 5; i < operations.size(); i++){
if( isInteger(operations[i]) == true ){
int number = atoi(operations[i].c_str());
data.push_back(Datum(number));
}
else{
data.push_back(Datum(operations[i]));
}
}
engine.insertInto(tableName,data);
return 0;
}
int openTable(vector<string> operations){
char symbol = NULL;
string input;
string type;
//When symbolcount == 0, save first line in keys; when symbolcount == 1, add columns to table;
//When symbolcount > 1 save in data;
int symbolcount = 0;
string tableName = operations[1];
//We will store values here
vector<Datum> data;
vector<string> keys;
ifstream dbFile;
string filename = tableName + ".db";
//Open the file
dbFile.open(filename);
//First one gets the table name
dbFile >> tableName;
while(!dbFile.eof()){
dbFile >> input;
//Check for consecutive semicolons
if( symbol == input[0] ){
//end of file, do nothing
}
else if( input == ";" ){
symbol = ';';
//We are reusing the vector data, insert to table depending on symbolcount
//and clear its content once we reach end of row
if( symbolcount == 0 ){
engine.createEntityTable(tableName,keys);
}
if( symbolcount > 1 ){
engine.insertInto(tableName,data);
data.clear();
}
symbolcount = symbolcount + 1;
}
else{
//No consecutive ';', clear the symbol
symbol = NULL;
if( symbolcount == 0 ){
keys.push_back(input);
}
else if( symbolcount == 1){
dbFile >> type;
engine.addAttribute(tableName,input,type);
}
else{
data.push_back(Datum(input));
}
}
}
return 0;
}
int createFile(vector<string> operations){
ofstream dbFile;
string filename = operations[1]+ ".db";
cout << filename << endl;
dbFile.open(filename);
dbFile.close();
return 0;
}
int saveToTable(vector<string> operations){
int tIndex;
string tableName = operations[1];
ofstream dbFile;
string filename = tableName + ".db";
dbFile.open(filename);
//Look for the table in the engine
tIndex = engine.FindTable(tableName);
if( tIndex == -21 ){
return CANT_FIND_TABLE;
}
//Declare variables for clarification, reuse tableName
tableName = engine.entityTables[tIndex].getName();
int nOfColumns = engine.entityTables[tIndex].getColumns().size();
int nOfRows = engine.entityTables[tIndex].getColumns()[0].getData().size();
int nOfPrimaryKeys = engine.entityTables[tIndex].getKeys().size();
dbFile << tableName;
dbFile << " ";
//Get the primary keys of the table
for( int i = 0; i < nOfPrimaryKeys; i++ ){
dbFile << engine.entityTables[tIndex].getKeys()[i] << " ";
}
dbFile << ";\n";
//Now the Column Names;
for( int i = 0; i < nOfColumns; i++ ){
dbFile << engine.entityTables[tIndex].getIColumn(i).getName() << " ";
dbFile << engine.entityTables[tIndex].getIColumn(i).getType() << " ";
}
//Dont forget, End the line with ; and \n
dbFile << ";\n";
//Now save the data in rows to file
for( int i = 0; i < nOfRows; i++){
for( int j = 0; j < nOfColumns; j++ ){
dbFile << engine.entityTables[tIndex].getIColumn(j).getIData(i).getName() << " ";
}
dbFile << ";\n";
}
dbFile << ";\n";
dbFile << ";";
dbFile.close();
return 0;
}
//UPDATE Random SET (Color = 20) WHERE (Color < 5)
int updateTable(vector<string> operations){
string tableName = operations[1];
string attributeName = operations[3];
string condition = operations[8];
if( isInteger(operations[4]) ){
int newValue = atoi(operations[5].c_str());
if( isInteger(operations[9]) ){
int condValue = atoi(operations[9].c_str());
}
}
else{
string newValue = operations[5];
string condValue = operations[9];
}
//engine.updateEntity(tableName,attributeName,newValue,condition,condValue);
return 0;
}
//DELETE FROM relation-Name Where (Color < 5)
int deleteFrom(vector<string> operations){
string tableName = operations[2];
string attributeName = operations[4];
string condition = operations[5];
if( isInteger(operations[6]) ){
int condValue = atoi(operations[6].c_str());
}
else{
string condValue = operations[6];
}
//engine.deleteFrom(tableName,attributeName,condition,condValue);
return 0;
}
string queryType(int index,vector<string> operations){
string tableName = operations[0];
string instruction = operations[index];
string attribute;
string attributeName;
string operation;
string othertablename;
// select (kind == "dog") select (kind == "food ) animals;
// dogs + (select (kind == "cat") animals);
// common_names <- project (name) (select (aname == name && akind != kind) (a * animals));
//Check if instruction is an operation or an attributeName
if( instruction == "select" ){
attribute = operations[index+1];
operation = operations[index+2];
attributeName = operations[index+3];
othertablename = queryType(index+4,operations);
int tIndex = engine.FindTable(othertablename);
engine.entityTables.push_back(engine.selection(engine.entityTables[tIndex],tableName,attribute,operation,0));
return tableName;
}
// <- project (attributename) | atomic-exp
else if( instruction == "project" ){
attributeName = operations[index+1];
othertablename = queryType(index+2,operations);
int tIndex = engine.FindTable(othertablename);
engine.entityTables.push_back(engine.projection(engine.entityTables[tIndex],tableName,attributeName));
return tableName;
}
else if( instruction == "rename" ){
vector<string> data;
attributeName = operations[index+1];
othertablename = queryType(index+2,operations);
int tIndex = engine.FindTable(othertablename);
engine.entityTables.push_back(engine.rename(engine.entityTables[tIndex],tableName,data));
return tableName;
}
//Check if its an operation like +, *
else if( index+2 < operations.size() ){
//Atomic expression + Atomic expression
if( operations[index+1] == "+" ){
int t1Index = engine.FindTable(instruction);
if( t1Index == -21 ){
return "Error";
}
othertablename = queryType(index+1,operations);
int t2Index = engine.FindTable(othertablename);
if( t2Index == -21) {
return "Error";
}
//engine.setUnion(tableName,engine.entityTables[t1Index],engine.entityTables[t2Index]);
return tableName;
}
else if( instruction == "-"){
int t1Index = engine.FindTable(instruction);
if( t1Index == -21 ){
return "Error";
}
othertablename = queryType(index+1,operations);
int t2Index = engine.FindTable(othertablename);
if( t2Index == -21) {
return "Error";
}
//engine.setDifference(tableName,engine.entityTables[t1Index],engine.entityTables[t2Index]);
return tableName;
}
else if( instruction == "*"){
int t1Index = engine.FindTable(instruction);
if( t1Index == -21 ){
return "Error";
}
othertablename = queryType(index+1,operations);
int t2Index = engine.FindTable(othertablename);
if( t2Index == -21) {
return "Error";
}
//engine.crossProduct(tableName,engine.entityTables[t1Index],engine.entityTables[t2Index]);
return tableName;
}
else if( instruction == "JOIN"){
int t1Index = engine.FindTable(instruction);
if( t1Index == -21 ){
return "Error";
}
othertablename = queryType(index+1,operations);
int t2Index = engine.FindTable(othertablename);
if( t2Index == -21) {
return "Error";
}
//engine.naturalJoin(tableName,engine.entityTables[t1Index],engine.entityTables[t2Index]);
return tableName;
}
}
//else its an attribute name
else{
return instruction;
}
}
//compare stuff
Table comparisons(vector<string> operations, int index){
vector<string> key;
string identifier = operations[index];
if( index + 1 == operations.size() ){
return Table("Table1",key);
}
string operation = operations[index+1];
if( operation == ">" ){
}
else if( operation == "<" ){
}
else if( operation == "!=" ){
}
else if( operation == ">=" ){
}
else if( operation == "<=" ){
}
else if( operation == "==" ){
}
else{
}
return Table("TABLE1",key);
}
string getString(vector<string> operations, int index){
if( index == operations.size() - 1 ){
return operations[index];
}
}
int showTable(vector<string> operations){
//Find the table using second index in operation since
//SHOW tableName, tableName always second string
int tIndex = engine.FindTable(operations[1]);
if ( tIndex == -21 ){
return CANT_FIND_TABLE;
}
cout << engine.entityTables[tIndex].getName() << " ";
for( int i = 0; i < engine.entityTables[tIndex].getKeys().size(); i++){
cout << engine.entityTables[tIndex].getKeys()[i] << " ";
}
cout << endl;
for(int i = 0; i < engine.entityTables[tIndex].getColumns().size(); i++ ){
cout << engine.entityTables[tIndex].getIColumn(i).getName() << " ";
cout << engine.entityTables[tIndex].getIColumn(i).getType() << " ";
}
cout << endl;
for(int i = 0; i < engine.entityTables[tIndex].getIColumn(0).getData().size(); i++){
for( int j = 0; j < engine.entityTables[tIndex].getColumns().size(); j++ ){
cout << engine.entityTables[tIndex].getIColumn(j).getIData(i).getName() << " ";
}
cout << endl;
}
return 0;
}
int Operations(vector<string> operations){
if( operations[0] == "CREATE" ) {
if( createTable(operations) == TYPE_ERROR ){
return TYPE_ERROR;
}
}
else if( operations[0] == "INSERT"){
insertInto(operations);
}
else if( operations[0] == "OPEN" ){
openTable(operations);
}
else if( operations[0] == "WRITE" ){
createFile(operations);
}
else if( operations[0] == "CLOSE" ){
saveToTable(operations);
}
else if( operations[0] == "SHOW"){
showTable(operations);
}
else if( operations[0] == "UPDATE"){
updateTable(operations);
}
else if( operations[0] == "EXIT"){
return 1;
}
else if( operations[1] == "<-" ){
//Three is how this function should start for query
queryType(2,operations);
}
return 0;
}
int Parse(string message, vector<string>& command){
string b;
size_t found;
int size = 0;
bool exit = false;
stringstream input;
input << message;
while(!exit){
//take strings out of the stream
input >> b;
//check the string doesnt start with a (, if it does, erase it
if( (b[0] == '(' || b[0] == '"') ) { b.erase(b.begin()); }
//Check if there string is in this format: (name,kind)
//Locate comma...
found = b.find(',');
//if you find the comma and its not at the end i.e. STRING, ... then
if( found != string::npos && b[found] != b[b.size()-1] ){
//Separate the strings and copy the string to the left of comma into a char
char* s1 = new char[found];
b.copy(s1,found,0);
//copy doesnt null terminate the copy, so we have to manually do it
s1[found] = '\0';
//copy the buffer into a string
string c(s1);
//Erase it from the original string
b.erase(b.begin(),b.begin()+found+1);
//and push back the remaining string.
command.push_back(s1);
}
//Remove special characters, if ;, exit
if( b[b.size()-1] == ';') { b.pop_back(); exit = true;}
if( b[b.size()-1] == ',') { b.pop_back();}
if( b[b.size()-1] == '"') { b.pop_back();}
if( b[b.size()-1] == ')') { b.pop_back();}
if( b[b.size()-1] == ')') { b.pop_back();}
command.push_back(b);
}
return 0;
}
int main(){
int b;
string message = "OPEN Random2;";
vector<string> data;
//Parse takes the message, parses it and stores the
//individual strings in a vector passed as reference
Parse(message,data);
//This function processes the data in vector and does an
//action based on the operation, i.e. OPEN, SHOW
Operations(data);
message = "OPEN Random;";
//Parse takes the message, parses it and stores the
//individual strings in a vector passed as reference
data.clear();
Parse(message,data);
//This function processes the data in vector and does an
//action based on the operation, i.e. OPEN, SHOW
Operations(data);
message = "dogs <- Random + Random2;";
data.clear();
Parse(message,data);
Operations(data);
cin >> b;
}
| true |
267025fb97de541c045a0fe178c8851f97e4ed71 | C++ | gwqw/LeetCodeCpp | /Algorithms/medium/863_all_nodes_distk_BT.cpp | UTF-8 | 2,808 | 4 | 4 | [] | no_license | /**
863. All Nodes Distance K in Binary Tree
We are given a binary tree (with root node root), a target node, and an integer value k.
Return a list of the values of all nodes that have a distance k from the target node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.
Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
Note:
The given tree is non-empty.
Each node in the tree has unique values 0 <= node.val <= 500.
The target node is a node in the tree.
0 <= k <= 1000.
Algo: dfs
- search target:
if node == target:
visit(node->left, 0)
visit(node->right, 0)
return true
else:
res = search(node->left)
if res:
visit(node->right, d)
return true
res = search(node->right)
if res:
visit(node->left, d)
return true
return false
*/
/**
* 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:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
int d = 0;
vector<int> res;
search(root, target, d, res, k);
return res;
}
private:
bool search(TreeNode* node, TreeNode* target, int& d, vector<int>& res, int k) {
if (!node) return false;
if (node == target) {
d = 0;
if (k == d) {
res.push_back(node->val);
return true;
}
visit(node->left, d, res, k);
visit(node->right, d, res, k);
return true;
}
bool ok = search(node->left, target, d, res, k);
if (ok) {
++d;
if (d == k) {
res.push_back(node->val);
}
visit(node->right, d, res, k);
return true;
}
ok = search(node->right, target, d, res, k);
if (ok) {
++d;
if (d == k) {
res.push_back(node->val);
}
visit(node->left, d, res, k);
return true;
}
return false;
}
void visit(TreeNode* node, int d, vector<int>& res, int k) {
if (!node) return;
d++;
if (d == k) {
res.push_back(node->val);
return;
}
if (d > k) return;
visit(node->left, d, res, k);
visit(node->right, d, res, k);
}
};
| true |
0dbe2acca894b62b258d8c7943a50076d792b23f | C++ | pellarolojuani/datos2c2014seventyfivezerosix | /tpDatosPredictor/BIS/NGramas.cpp | UTF-8 | 8,237 | 2.78125 | 3 | [] | no_license | /*
* NGramas.cpp
*
* Created on: 30/10/2014
* Author: juanignacio
*/
#include "NGramas.h"
NGramas::NGramas() {
this->lexico = new abb::ArbolB<Registro, 60>;
this->cantGrama = 0;
separadorNgrama = " ";
listaTerminos = vector<string>();
this->registros = tr1::unordered_map<string, size_t>();
this->oracion = "";
//this->contextos = tr1::unordered_map<string, tr1::unordered_map<string, size_t> >();
}
NGramas::NGramas(int cantGrama, string separadorNgrama){
this->lexico = new abb::ArbolB<Registro, 60>;
this->cantGrama = cantGrama;
this->separadorNgrama = separadorNgrama;
this->listaTerminos = vector<string>();
this->registros = tr1::unordered_map<string, size_t>();
this->oracion = "";
//this->contextos = tr1::unordered_map<string, tr1::unordered_map<string, size_t> >();
}
NGramas::NGramas(int cantGrama, string separadorNgrama,string oracion){
this->lexico = new abb::ArbolB<Registro, 60>;
this->cantGrama = cantGrama;
this->separadorNgrama = separadorNgrama;
this->listaTerminos = vector<string>();
this->registros = tr1::unordered_map<string, size_t>();
this->oracion = oracion;
//this->contextos = tr1::unordered_map<string, tr1::unordered_map<string, size_t> >();
}
NGramas::~NGramas() {
// TODO Auto-generated destructor stub
}
abb::ArbolB<Registro,60>* NGramas::getLexico(){
return this->lexico;
}
tr1::unordered_map<string, tr1::unordered_map<string, size_t> > NGramas::getContextos(){
return this->contextos;
}
//--------------------------------------------------------//
//---------Comienzo de funciones auxiliares --------------//
string getSiguienteTermino(FILE* fp){
string termino = "";
char c = fgetc(fp);
if (c == EOF) return "";
if (c == ' ') c = fgetc(fp);
while (c > 32 && c != ' '){ //a partir del ascii 33 comienzan los caracteres que necesitamos
termino += c;
c = fgetc(fp);
}
if (termino == " ") return "";
return termino;
}
string sacarPrimerTermino(string texto){
//saca la primera palabra de una frase y devuelve la frase nueva
int espacio = texto.find_first_of(" ");
string nuevoTexto = texto.substr(espacio+1);
return nuevoTexto;
}
void NGramas::agregarRegistroEnArbol(Registro unRegistro){
if (!this->lexico->buscar(unRegistro)){
this->lexico->insertar(unRegistro);
}else{
this->lexico->aumentarFrecuencia(unRegistro, 1);
}
}
//--------------------------------------------------------//
//--------------Fin de funciones auxiliares --------------//
void NGramas::streamANgrama(FILE* fp){
char *c = new char[2884354560]; //reservamos mas de 2.5gb de memoria!
fpos_t position;
FILE* fp_flag;
size_t offset = 0;
delete[] c; //libero la memoria reservada
while (!feof(fp) && offset < GIGA){ //Faltaria corregir la creacion de ngramas pero no es tan urgente..
offset = ftell(fp);
cout<<offset<<endl;
string ngrama = "";
ngrama += getSiguienteTermino(fp);
//if (ngrama == "") break;
size_t nuevoOffset = ftell(fp);
Registro unRegistro = Registro();
unRegistro.stringARegistro(ngrama);
if (unRegistro.getTermino() != "" && unRegistro.getTermino() != " ")
this->agregarRegistroEnArbol(unRegistro);
for (int k = 0; k < cantGrama-1; k++){
ngrama += " ";
ngrama += getSiguienteTermino(fp);
unRegistro.stringARegistro(ngrama);
this->agregarRegistroEnArbol(unRegistro);
}
fseek(fp, nuevoOffset, SEEK_SET);
}
}
void NGramas::levantarNgramas(){
cout << "Por favor ingrese la cantidad de archivos de NGramas que desea procesar: ";
int cantidadDeArchivos = 0;
cin >> cantidadDeArchivos;
ManejoArchivo manejoArchivo = ManejoArchivo();
manejoArchivo.abrirArchivo("file1.txt", "r");
Registro unRegistro = Registro();
this->contextos.rehash(10000000);
cout<<"Procesando archivo 1..."<<endl;
while(feof(manejoArchivo.getArchivo()) == 0){
unRegistro = manejoArchivo.getSiguienteRegistro();
//if (unRegistro.getFrecuencia() != 1){
this->contextos[unRegistro.getContexto()][unRegistro.getTermino()] += unRegistro.getFrecuencia();
//en cada contexto tenemos la suma total de frecuencias para poder dividir y calcular probabilidades
this->contextos[unRegistro.getContexto()][TOTAL_FRECUENCIAS] += unRegistro.getFrecuencia();
//}
}
manejoArchivo.cerrarArchivo();
// SE PROCESAN ARCHIVOS FILTRADOS
for(int i=2; i<cantidadDeArchivos+1; i++){
cout<<"Procesando archivo "<< i <<"..."<<endl;
manejoArchivo.abrirArchivo("file2.txt", "r");
while(feof(manejoArchivo.getArchivo()) == 0){
unRegistro = manejoArchivo.getSiguienteRegistro();
if (unRegistro.getFrecuencia() != 1){
this->contextos[unRegistro.getContexto()][unRegistro.getTermino()] += unRegistro.getFrecuencia();
//en cada contexto tenemos la suma total de frecuencias para poder dividir y calcular probabilidades
this->contextos[unRegistro.getContexto()][TOTAL_FRECUENCIAS] += unRegistro.getFrecuencia();
}
}
manejoArchivo.cerrarArchivo();
}
cout<<"Final del procesamiento del archivo."<<endl;
}
/*void NGramas::levantarNgramas(){
ManejoArchivo manejoArchivo = ManejoArchivo();
manejoArchivo.abrirArchivo("file1.txt", "r");
Registro unRegistro = Registro();
this->registros.rehash(90000000);
cout<<"Procesando primer archivo.."<<endl;
size_t cantRegistros = 0;
while(feof(manejoArchivo.getArchivo()) == 0){
//cout<<ftell(manejoArchivo.getArchivo())<<endl;
unRegistro = manejoArchivo.getSiguienteRegistro();
cantRegistros ++;
this->registros[unRegistro.registroAStringSinFrecuencia()] += unRegistro.getFrecuencia();
}
manejoArchivo.cerrarArchivo();
cout<<"Cantidad Registros leidos: "<<cantRegistros<<endl;
cout<<"the: "<<this->registros["the"]<<endl;
cout<<"The: "<<this->registros["The"]<<endl;
//---------PARA RECORRER UN MAP--------
size_t maxFrec = 0;
string maxElemento = "";
for (tr1::unordered_map<string, size_t>::iterator it = this->registros.begin(); it != this->registros.end(); it++){
if ((*it).second > maxFrec) {
maxFrec = (*it).second;
maxElemento = (*it).first;
}
}
cout<<"Elemento con mayor frecuencia: "<<maxElemento<<endl;
//------------------------------------
cout<<"Final del procesamiento del archivo."<<endl;
} */
void NGramas::stringANGramaHashTable(char* buffer){
istringstream iss(buffer);
strcpy(buffer,"");
this->registros.rehash(40000000);
unsigned long int posicionPuntero = 0;
do
{
string sub = "";
string subAux = "";
for(std::size_t i=0; i<3; i++) {
iss >> sub;
if(i==0){
posicionPuntero = iss.tellg();
}
if(sub.compare("")){
subAux = subAux + sub;
//aca guardamos en los hash.
this->registros[subAux] += 1;
//cout << subAux << endl;
subAux += " ";
}
}
iss.seekg(posicionPuntero);
subAux.clear();
}while(iss);
iss.str(std::string());
}
void NGramas:: guardarNgramasAAchivo(string nombreArchivo){
tr1::unordered_map<string, size_t>::iterator itr;
ofstream fichero(nombreArchivo.c_str());
for(itr = this->registros.begin(); itr != registros.end(); ++itr){
string ngrama = (*itr).first.c_str();
ngrama = ngrama + " ";
stringstream ss;
ss << (*itr).second;
ngrama = ngrama + ss.str();
fichero << ngrama << endl;
}
fichero.close();
}
void NGramas::fusionarArchivosNgramas(string unArchivoNgrama,string otroArchivoNgrama){
ManejoArchivo manejoArchivo = ManejoArchivo();
ManejoArchivo otroArchivo = ManejoArchivo();
manejoArchivo.abrirArchivo(unArchivoNgrama, "r");
otroArchivo.abrirArchivo(otroArchivoNgrama, "r");
Registro unRegistro = Registro();
this->registros.rehash(200000000);
//this->terminos_x_contexto.rehash(25000000);
cout<<"Procesando 1er archivo.."<<endl;
while(feof(manejoArchivo.getArchivo()) == 0){
unRegistro = manejoArchivo.getSiguienteRegistro();
this->registros[unRegistro.registroAString()] += unRegistro.getFrecuencia();
}
manejoArchivo.cerrarArchivo();
cout<<"Termino Procesar 1er archivo.."<<endl;
cout<<"Procesando 2do archivo.."<<endl;
while(feof(otroArchivo.getArchivo()) == 0){
unRegistro = otroArchivo.getSiguienteRegistro();
this->registros[unRegistro.registroAString()] += unRegistro.getFrecuencia();
}
cout<<"Termino Procesar 2do archivo.."<<endl;
otroArchivo.cerrarArchivo();
unRegistro.~Registro();
}
| true |
09fcfd043bb1882da01d9abaa214b1c9ab337f1f | C++ | arfaouiGit/OOP2 | /code/misc/mem.cpp | UTF-8 | 4,487 | 3.75 | 4 | [] | no_license |
/*
* Experiments with memory, illustrating the use of
* memory operators and `sizeof()`.
* */
#include <cstddef>
#include <iostream>
#include <iomanip>
using namespace std;
/*
* f() exists to help us further explore the stack!
* */
int f(int n, byte* end) {
int j = n;
int k = n % 23;
cout << "Address of j = " << &j << endl;
cout << "Address of k = " << &k << endl;
// do a hex dump of the stack between f() and main()
int i = 0;
for (byte* bptr = (byte *) &j;
bptr < end;
bptr++, i++) {
cout << hex << setfill('0') << setw(2)
<< (int)*bptr << " ";
if (i % 8 == 7) cout << endl;
}
return j - k * 7;
}
int main() {
/*
* Let's look at the size of some data types:
* */
bool b = true;
cout << "Size of a bool = " << sizeof(b) << endl;
char c = 'a';
cout << "Size of a char = " << sizeof(c) << endl;
int i = 28;
cout << "Size of an integer = " << sizeof(i) << endl;
double d = 2.71828;
cout << "Size of a double = " << sizeof(d) << endl;
/*
* Now let's deal with addresses and pointers:
* */
cout << "Address of b = " << &b << endl;
bool* bptr = &b;
cout << "Value of bptr = " << bptr << endl;
// funkiness coming: `char *`s are C-style strings!
cout << "Address of c = " << &c << endl;
// actually get the address:
cout << "Address of c as void ptr = " << (void *) &c << endl;
// better C++ way to do this:
cout << "Address of c as static cast void ptr = "
<< static_cast<const void *> (&c) << endl;
cout << "Address of i = " << &i << endl;
int* iptr = &i;
cout << "Value of iptr = " << iptr << endl;
cout << "Address of d= " << &d << endl;
double* dptr = &d;
cout << "Value of dptr = " << dptr << endl;
/*
* Hmm, what is the size of a pointer?
* Is it different for different pointers?
* */
cout << "Size of a bool ptr = " << sizeof(bptr) << endl;
cout << "Size of an integer ptr = " << sizeof(iptr) << endl;
cout << "Size of a double ptr = " << sizeof(dptr) << endl;
/*
* Seems like all pointers are the same size! Since C++
* references are "really" a sort of pointer, this explains
* why, for large objects, it is much more efficient, for
* objects we don't want changed in a function,
* (if we want to change the object in a function
* it's clear we *can't* pass a copy!) to pass a
* constant reference than to pass a copy: the reference
* will be essentially an 8-byte address, while the copy
* might be a multi-gigabyte video segment.
*
* So, if we have pointer to some value, how do we get
* the value? We *dereference* the pointer.
* */
cout << "Value pointed to by bptr = " << *bptr << endl;
cout << "Value pointed to by iptr = " << *iptr << endl;
cout << "Value pointed to by dptr = " << *dptr << endl;
/*
* All of what we have done so far has happened on
* the *stack*: all the memory allocation has happened automatically
* for us, performed by the compiler and C++ run-time system.
* But C++ allows as to also allocate memory ourselves,
* on the *heap*.
* */
int* iptr2 = new int(7);
cout << "Value pointed to by iptr2 = " << *iptr2 << endl;
/*
* But note the address of this value, compared to the
* pointers set above:
* */
cout << "The memory location held by iptr2 = " << iptr2 << endl;
/*
* This is because `new` allocates memory on the *heap*, not
* on the stack. Stack memory is automatically allocated by the
* run-time system, but with heap memory, *you*, the programmer,
* are in charge. For instance, with heap memory, you can control
* when it is freed, by calling `delete`:
* */
delete iptr2;
/*
* You can (because the C++ approach is "if the programmer wants to try
* this, let them") de-reference that memory, but the result is
* undefined.
* */
cout << "After delete, the value pointed to by iptr2 = "
<< *iptr2 << endl;
int* iptr3 = new int(14);
cout << "After new alloc, the value pointed to by iptr2 = "
<< *iptr2 << endl;
cout << "Value pointed to by iptr3 = " << *iptr3 << endl;
/*
* Finally, there is a special pointer value: nullptr.
* */
int* iptr4 = nullptr;
if (!iptr4) cout << "iptr4 is null\n";
f(7, (byte *) &iptr4);
}
| true |
29502124651c9147c83949b31bba5fd82b587d3a | C++ | sebCarabali/Problem-Solving-and-Programming-II | /Lecture/08 Friends and Operator Overloading/Sample Code/Friend Function/main.cpp | UTF-8 | 354 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "Button.h"
int main()
{
Button buttons[5];
buttons[0].Setup( "New", 15, 5 );
buttons[1].Setup( "Save", 15, 3 );
buttons[2].Setup( "Save", 15, 3 );
buttons[3].Setup( "Undo", 10, 5 );
buttons[4].Setup( "Exit", 12, 3 );
for ( int i = 0; i < 5; i++ )
{
Draw( buttons[i] );
}
return 0;
}
| true |
94274028027748edb641060b78bac559eae16be8 | C++ | KarinaKlevzhits/labs | /Lab8/fill.h | UTF-8 | 251 | 3.125 | 3 | [] | no_license | #pragma once
template <class Dynamic>
void feelA(Dynamic a, int m)
{
for (int i = 0; i < m; ++i)
{
a[i] = i;
std::cout << a[i] << " ";
}
}
template <class Dynamic>
void feelB(Dynamic b, int n)
{
for (int i = 0; i < n; ++i)
{
b[i] = i;
}
}
| true |
557c7fcac8e36173dfed8417c2a34d7453f5a4f1 | C++ | L4v/os_school | /v11/prioritet/rasporedjivac.h | UTF-8 | 2,505 | 2.890625 | 3 | [] | no_license | #ifndef RASPOREDJIVAC_H_INCLUDED
#define RASPOREDJIVAC_H_INCLUDED
#include <mutex>
#include <vector>
#include "dijagnostika.h"
#include "cv_hrono.h"
#include "red.h"
using namespace std;
using namespace chrono;
class Rasporedjivac {
private:
Dijagnostika& dijagnostika;
vector<Red> prioriteti;
mutex m;
int cpu_id;
public:
Rasporedjivac(Dijagnostika& d, int broj_nivoa_prioriteta) : dijagnostika(d) {
for(int i = 0; i < broj_nivoa_prioriteta; i++)
prioriteti.push_back(Red(i));
cpu_id = -1;
}
Dijagnostika& getDijagnostika() {
return dijagnostika;
}
// Metoda koju poziva nit koja simulira izvršenje procesa, kako bi se proces izvršio
//
// id_procesa - ID procesa
// broj_naredbi - ukupan broj naredbi koje proces treba da izvrši
// prioritet - prioritet procesa
//
// Ukoliko je procesor već zauzet i ne mogu se izvršavati naredbe procesa, potrebno je pozvati metodu dijagnostika.proces_ceka a nakon toga proces treba da pređe u stanje čekanja.
// Nakon što je proces izvršio naredbu, potrebno je pozvati dijagnostika.izvrsio_naredbu.
void izvrsi(int id_procesa, int broj_naredbi, int prioritet) {
for(int i = 0; i < broj_naredbi; i++){
unique_lock<mutex> lock(m);
cpu_id = cpu_id == -1 ? id_procesa : cpu_id;
while(cpu_id != id_procesa){
dijagnostika.proces_ceka(id_procesa);
prioriteti[prioritet].dodaj_u_red(id_procesa, lock);
}
lock.unlock();
this_thread::sleep_for(milliseconds(300));
lock.lock();
int notif_red = -1;
for(auto it = prioriteti.begin(); it != prioriteti.end(); it++){
if(!it->prazan()){
notif_red = it->getPrioritet();
break;
}
}
if(notif_red != -1){
int sledeci;
if(notif_red > prioritet && i < broj_naredbi - 1){
sledeci = id_procesa; // Ako jos nije zavrsio i najveci je prioritet trenutni proces
}else{
sledeci = prioriteti[notif_red].izbaci();
}
cpu_id = sledeci; // Uzima sledeci proces
}else{
cpu_id = -1; // Inace nema aktivnog procesa
}
dijagnostika.izvrsio_naredbu(id_procesa, i);
}
}
};
#endif // RASPOREDJIVAC_H_INCLUDED
| true |
10e815b93b9d67f79c76fa337860f623019dc814 | C++ | byte98/A2B37CPP | /MatrixCalculator/Main.cpp | UTF-8 | 1,385 | 3.375 | 3 | [] | no_license | #include "Matrix.h"
#include <iostream>
#define EXIT_ERR_INPUT -1;
#define EXIT_ERR_OPERATOR -2;
/* Main program */
int main(int argc, char *argv[])
{
Matrix NULL_MX = NULL_MATRIX;
int reti = EXIT_SUCCESS;
//Load first matrix
Matrix M1 = NULL_MATRIX;
M1.loadFromInput();
if (M1 == NULL_MX)
{
reti = EXIT_ERR_INPUT;
}
else
{
std::cout << "Loaded matrix:" << std::endl;
M1.write();
//Load operator
bool correct = false;
char matrix_operator;
while (!correct)
{
std::cin >> matrix_operator;
if (!std::cin.good())
{
std::cout << "Wrong operator! Allowed operators: '+', '-', '*'." << std::endl;
}
else
{
switch (matrix_operator)
{
case '+':
correct = true;
break;
case '-':
correct = true;
break;
case '*':
correct = true;
break;
default:
std::cout << "Wrong operator! Allowed operators: '+', '-', '*'." << std::endl;
break;
}
}
}
//Load second matrix
Matrix M2 = NULL_MATRIX;
M2.loadFromInput(M1, matrix_operator);
std::cout << "Loaded matrix:" << std::endl;
M2.write();
if (M2 == NULL_MX)
{
reti = EXIT_ERR_INPUT;
}
else
{
//Perform computing
Matrix result = NULL_MATRIX;
switch (matrix_operator)
{
case '+':
break;
case '-':
break;
case '*':
break;
default:
break;
}
}
}
return reti;
} | true |
b05802216c0c361317d3a0f5ffba2c7638c3982d | C++ | dongfusong/CmdStringMatching | /src/CmdStringPath.cpp | UTF-8 | 1,123 | 2.6875 | 3 | [] | no_license | #include "CmdStringPath.h"
#include "PartitionSymbolDef.h"
#include <iostream>
#include <assert.h>
using namespace std;
CmdStringPath::CmdStringPath(const std::string& str):_currentIndex(0),_str(str){
}
int CmdStringPath::parse() {
int beginPos = 0, endPos = 0;
while (beginPos < _str.size()) {
if (isSymbol (_str[beginPos])) {
_parts.push_back(string(1, _str[beginPos]));
beginPos++;
} else {
endPos = findSymbol(_str, beginPos);
_parts.push_back(_str.substr(beginPos, endPos - beginPos));
beginPos = endPos;
}
}
return SUCCESS;
}
std::string CmdStringPath::getCurrentPart()const{
assert(not isDone());
return _parts[_currentIndex];
}
void CmdStringPath::first() {
_currentIndex = 0;
}
void CmdStringPath::next() {
_currentIndex++;
}
bool CmdStringPath::isDone() const{
return _currentIndex == _parts.size();
}
bool CmdStringPath::isSymbol(char c) const {
return SYMBOL_TABLE(Partition).isSymbol(c);
}
int CmdStringPath::findSymbol(const std::string& str, int beginPos)const{
int i = beginPos;
for (; i < str.size(); i++) {
if (isSymbol(str[i])) {
break;
}
}
return i;
}
| true |
9e088b7079e2a82fbc6ecf53f4ae0fdd754c79f3 | C++ | klinki/MI-RUN | /Tests/Utf8StringTest.cpp | UTF-8 | 677 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../JVM/utils/HashMap.h"
#include "../JVM/utils/Utf8String.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Tests
{
TEST_CLASS(Utf8StringTest)
{
public:
TEST_METHOD(testHash)
{
Utf8String a("This should get converted to UTF8 string");
Utf8String b = "This should get converted to UTF8 string";
Assert::IsTrue(a == b);
}
TEST_METHOD(testCreateFromStringLiteral)
{
char charArr[] = "This should get converted to UTF8 string";
Utf8String string = charArr;
Assert::AreEqual(strlen(charArr), string.length());
Assert::IsTrue(string.equals(charArr));
}
};
}
| true |
b12e080f0391cebf1dcf4a7262b055e5267c58ea | C++ | AlexChiang0208/C_plusplus_beginner | /資料結構/vector練習.cpp | BIG5 | 481 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
char choice;
vector<int>myVec;
while(1){
cout << "O_nsW(Y/N)";
cin >> choice;
if(choice == 'Y'){
int temp;
cin >> temp;
myVec.push_back(temp);
}
if(choice == 'N'){
break;
}
}
sort(myVec.begin(), myVec.end());
cout << "myVec Ƨǫ" << endl;
for(int i = 0; i < myVec.size(); i++){
cout << myVec[i] << " ";
}
}
| true |
cc08a970c3062eb3433745d86e948cc89fbedf33 | C++ | smallwolf1991/xlib | /hex_str.cc | UTF-8 | 13,213 | 2.640625 | 3 | [] | no_license | #include "hex_str.h"
#include <string.h>
#include "xmsg.h"
#include "ws_s.h"
#include "ws_utf8.h"
using std::string;
//! 十六进制转换,小写索引
static const char* const gk_NumFmt_Low = "0123456789abcdef";
//! 十六进制转换,大写索引
static const char* const gk_NumFmt_Up = "0123456789ABCDEF";
string hex2str(const void* hexs, const size_t size, bool isup)
{
string asc;
if(hexs == nullptr || size == 0) return asc;
const auto fmt = isup ? gk_NumFmt_Up : gk_NumFmt_Low;
for(size_t i = 0; i < size; ++i)
{
const HEX_VALUE_STRUCT* hexchar = (const HEX_VALUE_STRUCT*)((size_t)hexs + i);
asc.push_back(fmt[hexchar->high]);
asc.push_back(fmt[hexchar->low]);
}
return asc;
}
size_t str2hex(const void* strs,
const size_t size,
size_t* lpreadlen,
size_t wantlen,
const bool errexit,
const bool errbreak)
{
size_t values = 0;
size_t readlen = 0;
if(lpreadlen == nullptr) lpreadlen = &readlen;
*lpreadlen = 0;
if(strs == nullptr || size == 0) return 0;
#if !defined(_WIN64) && !defined(__amd64)
const auto wl = gk_str2dword_len;
#else
const auto wl = gk_str2qword_len;
#endif
if((wantlen == 0) || (wantlen > wl)) wantlen = wl;
const char* lp = (const char*)strs;
for(size_t i = 0; i < size; ++i)
{
const char ch = lp[i];
char tmpC = ch & 0xF;
switch(ch)
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f':
{
tmpC += 9; //注意这里没有break
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
--wantlen;
values = values << 0x4;
values += tmpC;
if(wantlen == 0)
{
++(*lpreadlen);
return values;
}
break;
}
default:
if(errexit)
{
*lpreadlen = 0;
return 0;
}
if(errbreak) return values;
break;
}
++(*lpreadlen);
}
return values;
}
string str2hexs(const void* strs,
const size_t size,
size_t* lpreadlen,
const bool errexit,
const bool errbreak)
{
string rets;
size_t readlen = 0;
if(lpreadlen == nullptr) lpreadlen = &readlen;
*lpreadlen = 0;
if(strs == nullptr || size == 0) return 0;
bool pick_high = true; //指示当前提取的是高位还是低位
unsigned char readch = 0; //存放临时的提取值
size_t realreadlen = 0; //存放实际读取数
const char* lp = (const char*)strs;
for(size_t i = 0; i < size; ++i)
{
const char ch = lp[i];
char tmpC = ch & 0xF;
switch(ch)
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f':
{
tmpC += 9; //注意这里没有break
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
if(pick_high)
{
readch = tmpC << 0x4;
}
else
{
readch = (readch & 0xF0) + tmpC;
rets.push_back(readch);
realreadlen = *(lpreadlen) + 1;
}
pick_high = !pick_high;
break;
}
default:
if(errexit)
{
*lpreadlen = 0;
rets.clear();
return rets;
}
if(errbreak)
{
//读取不完整
if(!pick_high)
{
*(lpreadlen) = realreadlen;
}
return rets;
}
break;
}
++(*lpreadlen);
}
return rets;
}
string escape(const void* strs, const size_t size)
{
const char* lp = (const char*)strs;
string msg;
for(size_t i = 0; i < size; ++i)
{
if(lp[i] != '\\')
{
msg.push_back(lp[i]);
continue;
}
switch(lp[++i])
{
case '0': msg.push_back('\0'); break;
case 'a': msg.push_back('\a'); break;
case 'b': msg.push_back('\b'); break;
case 'f': msg.push_back('\f'); break;
case 'n': msg.push_back('\n'); break;
case 'r': msg.push_back('\r'); break;
case 't': msg.push_back('\t'); break;
case 'v': msg.push_back('\v'); break;
case '\\': msg.push_back('\\'); break;
case '\'': msg.push_back('\''); break;
case '\"': msg.push_back('\"'); break;
case '\?': msg.push_back('\?'); break;
case '\0': msg.push_back('\\'); --i; break;
case 'x' :
{
++i;
size_t readlen = 0;
size_t tmpI = str2hex((void*)&lp[i], 1, &readlen, 0, false, true);
switch(readlen)
{
case 0:msg.push_back('x');break;
case 1:
case 2:msg.append((const char*)&tmpI, sizeof(uint8));break;
case 3:
case 4:msg.append((const char*)&tmpI, sizeof(uint16)); break;
#if !defined(_WIN64) && !defined(__amd64)
default:msg.append((const char*)&tmpI, sizeof(uint32));break;
#else
case 5: case 6: case 7: case 8:
msg.append((const char*)&tmpI, sizeof(uint32));break;
default:
msg.append((const char*)&tmpI, sizeof(uint64)); break;
#endif
}
i += (readlen - 1);
}
break;
default:
msg.push_back('\\');
msg.push_back(lp[i]);
}
}
return msg;
}
//! 每行显示数据个数
static const intptr_t gk_max_line_byte = 0x10;
//! 输出hex2show的前缀格式化数据,注意会修改传入的size
static void hex2show_prefix(xmsg& msg,
const unsigned char* data,
intptr_t& size,
const char* fmt,
const size_t prews)
{
msg.append(prews, ' '); //空格前缀
msg << (void*)data; //地址前缀
msg.append("┃"); //地址与16进制数据分隔符
for(intptr_t i = 0; i < gk_max_line_byte; --size)
{
if(size > 0) // HEX格式化输出
{
msg.push_back(fmt[(data[i] >> 4) & 0xF]);
msg.push_back(fmt[(data[i] >> 0) & 0xF]);
}
else // 无数据补齐
{
msg.append(" ");
}
switch(++i)
{
case 4: case 8: case 0xC:
msg.push_back('|'); break;
case 0x10:
msg.append("┃"); break;
default:
msg.push_back(' ');
}
}
}
//! 使unicode字符输出可视化,返回true表示接受字符,否则不接受,一律输出'.'
static bool hex2show_unicode_visualization(xmsg& msg, const charucs2_t wc)
{
//控制字符一律输出'.'
if(wc < L' ' || (wc >= 0x7F && wc <= 0xA0))
{
msg.push_back('.');
return true;
}
//对于'?'做特殊预处理以应对转换无法识别字符
if(wc == L'?')
{
msg.push_back('?');
return true;
}
//尝试转换ASCII,失败则输出'.'
const auto ch(ws2s(ucs2string(1, wc)));
if(ch.empty())
{
msg.push_back('.');
return false;
}
//转换成功,但无法显示,也输出'.'
if(*ch.begin() == '?')
{
msg.push_back('.');
return false;
}
//正常输出
msg << ch;
return true;
}
//! 注意会修改传入的usechar
static void hex2show_unicode(xmsg& msg,
const unsigned char* data,
const intptr_t fix_len,
const bool last,
size_t& usechar)
{
intptr_t lp = 0;
while(lp < fix_len)
{
//在数据最后一行的最后一个byte,无法进行向后匹配完整字符,一律输出'.'
if(last && (lp + 1) >= fix_len)
{
msg.push_back('.');
lp += sizeof(char);
break;
}
const charucs2_t wc = *(charucs2_t*)&data[lp + usechar];
if(hex2show_unicode_visualization(msg, wc))
{
lp += sizeof(charucs2_t);
}
else
{
lp += sizeof(char);
}
}
usechar = 0;
if(lp > fix_len) usechar = lp - fix_len;
}
//! 注意会修改传入的usechar
static void hex2show_utf8(xmsg& msg,
const unsigned char* data,
const intptr_t fix_len,
const bool last,
size_t& usechar)
{
intptr_t lp = 0;
while(lp < fix_len)
{
//尝试转换unicode
unsigned long unicode;
const intptr_t k = utf8_byte2unicode_byte(&unicode, (const p_utf8)&data[lp + usechar]);
//转换失败一律输出'.'
if(k <= 0)
{
msg.push_back('.');
lp += sizeof(char);
continue;
}
//在数据最后一行,无法进行向后匹配完整字符,一律输出'.'
if(last && (lp + k > fix_len))
{
msg.append(fix_len - lp, '.');
lp = fix_len;
break;
}
//转换超出正常unicode范围,一律输出'.'
if(unicode > 0xFFFF)
{
msg.push_back('.');
lp += sizeof(char);
continue;
}
const charucs2_t wc = (charucs2_t)unicode;
if(hex2show_unicode_visualization(msg, wc))
{
lp += k;
}
else
{
lp += sizeof(char);
}
}
usechar = 0;
if(lp > fix_len) usechar = lp - fix_len;
}
static void hex2show_ascii(xmsg& msg,
const unsigned char* data,
const intptr_t fix_len,
const bool last,
size_t& usechar)
{
intptr_t lp = 0;
while(lp < fix_len)
{
const unsigned char ch = *(unsigned char*)&data[lp + usechar];
//控制字符一律输出'.'
if(ch < ' ' || ch == 0x7F)
{
msg.push_back('.');
lp += sizeof(char);
continue;
}
//可显示字符输出
if(ch < 0x7F)
{
msg.push_back(ch);
lp += sizeof(char);
continue;
}
//在数据最后一行的最后一个byte,无法进行向后匹配完整字符,一律输出'.'
if(last && (lp + 1) >= fix_len)
{
msg.push_back('.');
lp += sizeof(char);
break;
}
//尝试转换unicode,转换失败一律输出'.'
const auto unicode(s2ws(string((const char*)&data[lp + usechar], sizeof(charucs2_t))));
if(unicode.empty())
{
msg.push_back('.');
lp += sizeof(char);
continue;
}
if(hex2show_unicode_visualization(msg, *unicode.begin()))
{
lp += sizeof(charucs2_t);
}
else
{
lp += sizeof(char);
}
}
usechar = 0;
if(lp > fix_len) usechar = lp - fix_len;
}
string hex2show(const void* data,
const size_t len,
const Hex2showCode code,
const bool isup,
const size_t prews)
{
xmsg msg;
const char* fmt = isup ? gk_NumFmt_Up : gk_NumFmt_Low;
size_t usechar = 0;
const unsigned char* lpdata = (const unsigned char*)data;
intptr_t size = len;
do
{
hex2show_prefix(msg, lpdata, size, fmt, prews);
//默认情况下输出字符gk_max_line_byte大小,但需要去除之前预支的字符
intptr_t fix_len = gk_max_line_byte - usechar;
//在数据最后一行,输出大小需要控制
const bool last = size < 0;
if(last)
{
fix_len += size;
}
//严格错误判定
if(fix_len >= 0)
{
switch(code)
{
case HC_UNICODE:
hex2show_unicode(msg, lpdata, fix_len, last, usechar);
break;
case HC_UTF8:
hex2show_utf8(msg, lpdata, fix_len, last, usechar);
break;
case HC_ASCII:
default:
hex2show_ascii(msg, lpdata, fix_len, last, usechar);
}
}
lpdata += gk_max_line_byte;
msg.push_back('\r');
msg.push_back('\n');
}while(size > 0);
return msg;
}
#ifdef _XLIB_TEST_
ADD_XLIB_TEST(HEX_STR)
{
SHOW_TEST_INIT;
bool done = false;
const char* const buf = "12345678";
const char* const hex = "3132333435363738";
string rets;
SHOW_TEST_HEAD("hex2str");
done = (hex2str(string(buf)) == hex);
SHOW_TEST_RESULT(done);
SHOW_TEST_HEAD("str2hex");
done = (0x12345678 == str2hex(string(buf)));
SHOW_TEST_RESULT(done);
SHOW_TEST_HEAD("hex2show");
rets = hex2show(string("0123456789ABCDEF"));
rets.erase(rets.begin(), rets.begin() + sizeof(void*) * gk_str2byte_len);
done = (rets == "┃30 31 32 33|34 35 36 37|38 39 41 42|43 44 45 46┃0123456789ABCDEF\r\n");
SHOW_TEST_RESULT(done);
}
#endif // _XLIB_TEST_ | true |
8259fad728aa164e3a798c3a1c8f0c8088c1043f | C++ | njumathdy/code-practice | /Leetcode/543_Diameter of Binary Tree/c++/solution.cpp | UTF-8 | 1,812 | 3.640625 | 4 | [] | no_license | /*******************
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
*******************/
#include <cstdlib>
#include <cstdio>
#include <exception>
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution1 {
public:
int diameterOfBinaryTree(TreeNode* root) {
if(root == nullptr)
return 0;
int res = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
TreeNode* p = q.front();
q.pop();
res = max(res, height(p->left)+height(p->right));
if(p -> left != nullptr)
q.push(p -> left);
if(p -> right != nullptr)
q.push(p -> right);
}
return res;
}
int height(TreeNode* root) {
if(root == nullptr)
return 0;
return 1 + max(height(root->left), height(root->right));
}
};
class Solution2 {
public:
int diameterOfBinaryTree(TreeNode* root) {
if(root == nullptr)
return 0;
int res = 1;
height(root, res);
return res - 1;
}
int height(TreeNode* root, int& ans) {
if(root == nullptr)
return 0;
int l = height(root -> left, ans);
int r = height(root -> right, ans);
ans = max(ans, l+r+1);
return max(l, r) + 1;
}
};
int main() {
return 0;
} | true |
921510ba7b7d03bbc0cd465029595df2c8dc1e17 | C++ | kvolden/Pmatch | /sub_rule.h | UTF-8 | 2,215 | 3.203125 | 3 | [] | no_license | #ifndef Sub_rule_h
#define Sub_rule_h
#include <vector>
#include <string>
#include "pcast.h"
class Sub_rule { // Sub rule for testing one single input
private:
bool invert; // Whether to invert final answer (not-transition)
bool wildcard;
std::vector<std::string> single_values;
std::vector<std::string> ranges;
public:
Sub_rule(bool _invert, std::vector<std::string> _single_values, std::vector<std::string> _ranges){
wildcard = false;
invert = _invert;
single_values = _single_values;
ranges = _ranges;
}
Sub_rule(){ // Constructor without arguments means wildcard
wildcard = true;
invert = false;
}
template <typename Input>
bool match(Input input){
bool match = wildcard; // Ends up returning "true" (short circuits) if wildcard, depends on input if not
for(int i = 0; i < single_values.size(); i++){ // Match any single value
match = match || (input == pcast::cast<Input>(single_values.at(i)));
}
for(int i = 0; i < ranges.size(); i += 2){ // Match any range
match = match || (input >= pcast::cast<Input>(ranges.at(i)) && input <= pcast::cast<Input>(ranges.at(i+1)));
}
return (invert ? !match : match); // Return and invert if appropriate
}
#ifdef PMATCH_DEBUG
std::string debug_escape_characters(std::string chars){
for(int i = 0; i < chars.length(); ++i){
switch(chars.at(i)){
case '-':
case ',':
case '\\':
case '^':
chars.insert(i, "\\");
++i;
break;
}
}
return chars;
}
void debug_output_structure(){
if(wildcard){
std::cout << ".";
}
else{
std::cout << "[" << (invert ? "^" : "" );
for(int i = 0; i < single_values.size(); ++i){
std::cout << debug_escape_characters(single_values.at(i));
if(i != single_values.size()-1){
std::cout << ",";
}
}
if(single_values.size() && ranges.size()){
std::cout << ",";
}
for(int i = 0; i < ranges.size(); i += 2){
std::cout << debug_escape_characters(ranges.at(i)) << "-" << debug_escape_characters(ranges.at(i+1));
if(i != ranges.size()-2){
std::cout << ",";
}
}
std::cout << "]";
}
}
#endif
};
#endif
| true |
fed1ca6a035e7bab640643ef6602de799f9dd05e | C++ | ignacioreyes/opengl_experiments | /experiments/src/tests/Test3D.cpp | UTF-8 | 3,282 | 2.5625 | 3 | [] | no_license | #include "Test3D.h"
#include <GL/glew.h>
#include "imgui/imgui.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
namespace test {
Test3D::Test3D()
: m_ViewFrom {0.0f, 0.0f, 1000.0f},
m_ModelCenter {0.0f, 0.0f, 0.0f},
m_ModelAngle(0.0f)
{
UpdateMVP();
float positions[28] = {
-200.0f, -200.0f, -200.0f, 0.7f, 0.3f, 0.1f, 1.0f,
200.0f, -200.0f, -200.0f, 0.1f, 0.6f, 0.3f, 1.0f,
0.0f, 200.0f, -200.0f, 0.1f, 0.1f, 0.5f, 1.0f,
0.0f, 0.0f, 200.0f, 0.9f, 0.9f, 0.9f, 1.0f
};
unsigned int indices[12] = {
0, 2, 1,
0, 1, 3,
0, 2, 3,
3, 1, 2
};
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
m_Shader = std::make_unique<Shader>("res/shaders/Shader3D.shader");
m_VertexArray = std::make_unique<VertexArray>();
m_VertexBuffer = std::make_unique<VertexBuffer>(positions, sizeof(positions));
VertexBufferLayout layout;
layout.Push(3); // 3D vectors
layout.Push(4); // RGBA colors
m_VertexArray->AddBuffer(*m_VertexBuffer, layout);
m_IndexBuffer = std::make_unique<IndexBuffer>(indices, sizeof(indices) / sizeof(float));
m_Shader->Bind();
}
Test3D::~Test3D(){
glDisable(GL_DEPTH_TEST);
}
void Test3D::UpdateMVP(){
// m_Proj = glm::ortho(0.0f, 1200.0f, 0.0f, 800.0f, -2000.0f, 2000.0f);
m_Proj = glm::perspective(
glm::radians(60.0f),
1200.0f / 800.0f,
1.0f,
5000.0f);
m_View = glm::lookAt(
glm::vec3(m_ViewFrom[0], m_ViewFrom[1], m_ViewFrom[2]), // camera position
glm::vec3(0.0f, 0.0f, 0.0f), // where is looking to
glm::vec3(0, 1, 0));
m_Model = glm::rotate(
glm::mat4(1.0f),
m_ModelAngle,
glm::vec3(0.0f, 1.0f, 0.0f));
m_Model = glm::translate(
glm::mat4(1.0f),
glm::vec3(m_ModelCenter[0], m_ModelCenter[1], m_ModelCenter[2])) * m_Model;
m_MVP = m_Proj * m_View * m_Model;
}
void Test3D::OnUpdate(float deltaTime){
m_ModelAngle += deltaTime * glm::pi<float>();
if (m_ModelAngle > 2 * glm::pi<float>()) {
m_ModelAngle -= 2 * glm::pi<float>();
}
UpdateMVP();
}
void Test3D::OnRender(){
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Renderer renderer;
m_Shader->Bind();
m_Shader->SetUniformMat4f("u_MVP", m_MVP);
renderer.Draw(*m_VertexArray, *m_IndexBuffer, *m_Shader);
}
void Test3D::OnImGuiRender(){
// ImGui::SliderFloat("View: angle", &m_Angle, 0.0f, 6.28f);
ImGui::SliderFloat3("Viewing from", m_ViewFrom, -2000.0f, 2000.0f);
ImGui::SliderFloat3("Model center", m_ModelCenter, -1000.0f, 1000.0f);
ImGui::Text(
"Application average %.3f ms/frame (%.1f FPS)",
1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
} | true |
aa56b9c96a853778a1e961c89a8d34868ae445e5 | C++ | AliZ786/CPP-Codes | /Vectors/main.cpp | UTF-8 | 2,091 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vector1;
vector<int> vector2;
int score_1 {0};
int score_2 {0};
cout<<"Enter the first number that you want to add in vector1: ";
cin >> score_1;
vector1.push_back(score_1);
cout <<"\nEnter the second number that you want to add in vector1: ";
cin >> score_2;
vector1.push_back(score_2);
cout <<"\nThe contents of vector1 are as follows"<<endl;
cout <<"---------------------------------------"<<endl;
cout <<vector1.at(0)<<endl;
cout <<vector1.at(1)<<endl;
cout << "\nThe size of vector1 currently is " << vector1.size() << endl;
int score_3 = 100;
int score_4 =200;
vector2.push_back(score_3);
vector2.push_back(score_4);
cout <<"\nThe contents of vector2 are as follows" <<endl;
cout <<"----------------------------------------"<<endl;
cout <<vector2.at(0)<<endl;
cout << vector2.at(1)<<endl;
cout <<"\nThe size of vector2 currently is " << vector2.size()<<endl;
vector <vector<int>> vector_2d;
vector_2d.push_back(vector1);
vector_2d.push_back(vector2);
cout <<"\nThe 2-D vector prints out something like this:"<<endl;
cout <<"----------------------------------------------"<<endl;
cout << vector_2d.at(0).at(0) <<endl;
cout << vector_2d.at(0).at(1) <<endl;
cout << vector_2d.at(1).at(0)<<endl;
cout << vector_2d.at(1).at(1)<<endl;
vector1.at(0) =1000;
cout <<"\nThe updated 2-D vector prints out something like this:"<<endl;
cout <<"----------------------------------------------"<<endl;
cout << vector_2d.at(0).at(0) <<endl;
cout << vector_2d.at(0).at(1) <<endl;
cout << vector_2d.at(1).at(0)<<endl;
cout << vector_2d.at(1).at(1)<<endl;
cout <<"\nThe contents of vector1 are currently as follows"<<endl;
cout <<"---------------------------------------"<<endl;
cout <<vector1.at(0)<<endl;
cout <<vector1.at(1)<<endl;
return 0;
}
| true |
12c7bcd676bac68c0e3976e4cf64ab38f82a0b3c | C++ | A-Samad1206/cpp | /Prev/c++ code/daily practice/NUMBERS/03 abundant no. DEFIECIENCY.cpp | WINDOWS-1252 | 708 | 3.9375 | 4 | [] | no_license | //consider the number 21. Its proper divisors are 1, 3 and 7, and their sum is 11.
//Because 11 is less than 21, the number 21 is deficient.
//Its deficiency is 2 21 - 32 = 10.
//ABUNDANT NO. whose sum of prime factors is greater than the number itself.
#include<iostream>
using namespace std;
int dis_prime(int);
main()
{
int ch,value,d;
cout<<"Enter the value"<<endl; cin>>value;
ch=dis_prime(value);
if(ch>value)
{
cout<<"Value is abundant";
}
else if(ch<value)
{
cout<<"Value is DEFICIENT";
d=(2*value)-(ch+value);
cout<<endl<<"Deficiency is "<<d<<endl;
}
}
int dis_prime(int num)
{
int sum=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
sum=sum+i;
}
}
return sum;
}
| true |
17aa484fe7e7759c6a17b4387648f0228cc65754 | C++ | cjhgo/learn_and_use | /cpp/mystl/ringbuffer.cpp | UTF-8 | 2,665 | 3.546875 | 4 | [] | no_license | #include <stdlib.h>
#include <iostream>
class RingBuffer2
{
public:
RingBuffer2(int capacity_):
capacity(capacity_),size(0),head(0),tail(0)
{
data = (int*)malloc(capacity*sizeof(int));
}
void show() const
{
for(int i = 0; i < size; i++)
{
int index = (head+i)%capacity;
std::cout<<data[index]<<"\t";
}
std::cout<<std::endl;
}
bool push(int val)
{
if( (tail+1)%capacity == head)
{
std::cout<<head<<"\t"<<tail<<"\tbuffer full\n";
return false;
}else
{
data[tail]=val;
size++;
tail=(tail+1)%capacity;
return true;
}
}
bool pop(int& val)
{
if( head == tail)
{
std::cout<<head<<"\t"<<tail<<"\tbuffer empty\n";
return false;
}else
{
val = data[head];
size--;
head = (head+1)%capacity;
return true;
}
}
private:
int capacity,size,head,tail;
int* data;
};
class RingBuffer
{
public:
RingBuffer(int capacity_):
capacity(capacity_),size(0),head(0),tail(0)
{
data = (int*)malloc(capacity*sizeof(int));
}
void show() const
{
for(int i = 0; i < size; i++)
{
int index = (head+i)%capacity;
std::cout<<data[index]<<"\t";
}
std::cout<<std::endl;
}
bool push(int val)
{
if(size == capacity)
{
std::cout<<head<<"\t"<<tail<<"\tbuffer full\n";
return false;
}
else
{
data[tail]=val;
size++;
tail = (tail+1)%capacity;
}
}
bool pop(int& val)
{
if( size == 0)
{
std::cout<<head<<"\t"<<tail<<"\tbuffer empty\n";
return false;
}
else
{
val = data[head];
size--;
head = (head+1)%capacity;
return true;
}
}
private:
int capacity,size,head,tail;
int* data;
};
int main(int argc, char const *argv[])
{
RingBuffer2 rb(8);
int temp;
rb.pop(temp);
rb.show();
rb.push(1);
rb.show();
rb.push(2);
rb.show();
rb.push(3);
rb.show();
rb.push(4);
rb.show();
rb.push(5);
rb.show();
rb.push(6);
rb.show();
rb.push(7);
rb.show();
rb.push(8);
rb.show();
rb.push(9);
rb.show();
rb.push(10);
rb.show();
rb.push(11);
rb.show();
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.show();
rb.push(9);
rb.show();
rb.push(10);
rb.show();
rb.push(11);
rb.show();
rb.push(11);
rb.show();
rb.push(11);
rb.show();
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.pop(temp);
rb.show();
return 0;
} | true |
0322bdb10c9723513a98f922a7dc3ac954bf9708 | C++ | ssprusakov/far-git-autocomplete | /src/RefsDialog.cpp | UTF-8 | 5,266 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "RefsDialog.h"
#include <algorithm>
#include <cassert>
#include "GitAutocomplete.hpp"
#include "Guid.hpp"
#include "GitAutocompleteLng.hpp"
#include "Utils.hpp"
using namespace std;
static size_t MaxLength(const vector<string> &list) {
return (*max_element(list.begin(), list.end(), [](string x, string y) -> bool {
return x.length() < y.length();
})).length();
}
static SMALL_RECT GetFarRect() {
SMALL_RECT farRect;
Info.AdvControl(&MainGuid, ACTL_GETFARRECT, 0, &farRect);
*logFile << "Far rect (l, t, r, b) = (" << farRect.Left << ", " << farRect.Top << ", " << farRect.Right << ", " << farRect.Bottom << ")" << endl;
return farRect;
}
static FarListItem * InitializeListItems(const vector<string> &list, const string &initiallySelectedItem) {
size_t size = list.size();
FarListItem *listItems = new FarListItem[size];
size_t initiallySelected = 0;
for (size_t i = 0; i < size; ++i) {
wstring wstr = mb2w(list[i]);
listItems[i].Text = (const wchar_t *)wcsdup(wstr.c_str());
listItems[i].Flags = LIF_NONE;
if (list[i] == initiallySelectedItem) {
initiallySelected = i;
}
}
listItems[initiallySelected].Flags |= LIF_SELECTED;
return listItems;
}
static void FreeListItems(FarListItem *listItems, size_t size) {
for (size_t i = 0; i < size; ++i) {
free((wchar_t*)listItems[i].Text);
}
delete[] listItems;
}
typedef struct tGeometry {
int left;
int top;
size_t width;
size_t height;
} Geometry;
static pair<Geometry, Geometry> CalculateListBoxAndDialogGeometry(size_t maxLineLength, size_t linesCount) {
// Example of list geometry:
// (left padding is added inside of ListBox automatically)
//
// +-- Title --+
// |..bar ..|
// |..feature..|
// +-----------+
size_t listBoxWidth = maxLineLength + 6;
size_t listBoxHeight = linesCount + 2;
// Example of dialog geometry:
//
// ..........
// ..+----+..
// ..| |..
// ..+----+..
// ..........
size_t dialogWidth = listBoxWidth + 4;
size_t dialogHeight = listBoxHeight + 2;
// Some pretty double padding for the maximum dialog:
SMALL_RECT farRect = GetFarRect();
size_t dialogMaxWidth = (farRect.Right - farRect.Left + 1) - 8;
size_t dialogMaxHeight = (farRect.Bottom - farRect.Top + 1) - 4;
if (dialogWidth > dialogMaxWidth) {
size_t delta = dialogWidth - dialogMaxWidth;
dialogWidth -= delta;
listBoxWidth -= delta;
}
if (dialogHeight > dialogMaxHeight) {
size_t delta = dialogHeight - dialogMaxHeight;
dialogHeight -= delta;
listBoxHeight -= delta;
}
Geometry list = {2, 1, listBoxWidth, listBoxHeight};
Geometry dialog = {-1, -1, dialogWidth, dialogHeight}; // auto centering
return pair<Geometry, Geometry>(list, dialog);
}
static int ShowListAndGetSelected(const vector<string> &list, const string &initiallySelectedItem) {
FarList listDesc;
listDesc.StructSize = sizeof(listDesc);
listDesc.Items = InitializeListItems(list, initiallySelectedItem);
listDesc.ItemsNumber = list.size();
FarDialogItem listBox;
memset(&listBox, 0, sizeof(listBox));
listBox.Type = DI_LISTBOX;
listBox.Data = GetMsg(MTitle);
listBox.Flags = DIF_NONE;
listBox.ListItems = &listDesc;
auto listAndDialogGeometry = CalculateListBoxAndDialogGeometry(MaxLength(list), list.size());
Geometry listGeometry = listAndDialogGeometry.first;
Geometry dialogGeometry = listAndDialogGeometry.second;
listBox.X1 = listGeometry.left;
listBox.Y1 = listGeometry.top;
listBox.X2 = listGeometry.left + listGeometry.width - 1;
listBox.Y2 = listGeometry.top + listGeometry.height - 1;
FarDialogItem *items = &listBox;
size_t itemsCount = 1;
int listBoxID = 0;
assert(dialogGeometry.left == -1 && dialogGeometry.top == -1); // auto centering
HANDLE dialog = Info.DialogInit(&MainGuid, &RefsDialogGuid, -1, -1, dialogGeometry.width, dialogGeometry.height, L"Contents", items, itemsCount, 0, FDLG_KEEPCONSOLETITLE, nullptr, nullptr);
int runResult = (int)Info.DialogRun(dialog);
int selected;
if (runResult != -1) {
selected = (int)Info.SendDlgMessage(dialog, DM_LISTGETCURPOS, listBoxID, nullptr);
assert(0 <= selected && selected < (int)listBox.ListItems->ItemsNumber);
} else {
selected = -1;
}
Info.DialogFree(dialog);
FreeListItems(listDesc.Items, listDesc.ItemsNumber);
return selected;
}
string ShowRefsDialog(const vector<string> &suitableRefs, const string &initiallySelectedRef) {
assert(!suitableRefs.empty());
int selected = ShowListAndGetSelected(suitableRefs, initiallySelectedRef);
if (selected >= 0) {
*logFile << "Dialog succeeded. Selected = " << selected << endl;
assert(0 <= selected && selected < (int)suitableRefs.size());
return suitableRefs[selected];
} else {
*logFile << "Dialog failed." << endl;
return string("");
}
}
| true |
da3cf779c29b0ed306edc55c2e22a9c7c9685c29 | C++ | hejh6408/cal-2020 | /arithmetic/arithmetic.h | UTF-8 | 848 | 2.671875 | 3 | [] | no_license | #pragma once
#ifndef ARITHMETIC_H
#define ARITHMETIC_H
#include "definition/definition.h"
#include <memory>
#include <cstdbool>
class arithmetic;
typedef std::shared_ptr<arithmetic> pArithmetic;
class arithmetic
{
public:
arithmetic(const size_t size);
virtual ~arithmetic();
void intializeResult(const data result);
virtual void op(data& result, const data input) = 0;
void setDataArraySize(const size_t size);
size_t getDataArraySize() const;
void setDataByIndex(const data& _data, const size_t index);
void setDataValidityByIndex(const size_t index, bool validity);
virtual void calculate();
void resetData();
data getResult() const;
private:
dataArray m_dataArray;
std::vector<bool> m_isIndexDataValid;
bool m_arithmethValidity;
data m_result;
};
#endif // ARITHMETIC_H
| true |
72bbd3543c89eed607c9af47a6a94863232987f0 | C++ | PeterYHChen/idea-of-acm-problem-solutions | /problems-base/hdu/hdu-general/hdu-findTheMostComfortableRoad/solution.cpp | UTF-8 | 1,770 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string.h>
#include <queue>
#include <vector>
using namespace std;
int n, m;
int start, end, speed;
bool mark[201][201][201];
struct Node{
int val, speed;
};
vector<Node> adjacent[201];
struct Transfer{
int s, m, e;
int min, max;
};
class comp{
public:
bool operator()(Transfer &a, Transfer &b)
{
return (a.max - a.min) > (b.max - b.min);
}
};
int BFS()
{
priority_queue<Transfer, vector<Transfer>, comp> qtrans;
Transfer curr, temp;
for(int i = 0; i < adjacent[start].size(); i++)
{
curr.s = start;
curr.m = curr.s;
curr.e = adjacent[start][i].val;
curr.min = curr.max = adjacent[start][i].speed;
qtrans.push(curr);
}
while(!qtrans.empty())
{
curr = qtrans.top();
qtrans.pop();
if(curr.e == end)
return curr.max - curr.min;
for(int i = 0; i < adjacent[curr.e].size(); i++)
{
temp.s = curr.m;
temp.m = curr.e;
temp.e = adjacent[curr.e][i].val;
if(temp.e == temp.s)
continue;
if(mark[temp.s][temp.m][temp.e])
continue;
mark[temp.s][temp.m][temp.e] = true;
temp.max = adjacent[curr.e][i].speed > curr.max? adjacent[curr.e][i].speed : curr.max;
temp.min = adjacent[curr.e][i].speed < curr.min? adjacent[curr.e][i].speed : curr.min;
qtrans.push(temp);
}
}
return -1;
}
int main()
{
while(cin >> n >> m && n && m)
{
for(int i = 0; i <= n; i++)
adjacent[i].clear();
Node temp;
for(int i = 1; i <= m; i++)
{
cin >> start >> end >> speed;
temp.speed = speed;
temp.val = end;
adjacent[start].push_back(temp);
temp.val = start;
adjacent[end].push_back(temp);
}
int q;
cin >> q;
while(q--)
{
memset(mark, 0, sizeof(mark));
cin >> start >> end;
cout << BFS() << endl;
}
}
return 0;
}
| true |
b6328e5d6be89c37edf7d974df273ec6d9384838 | C++ | lwzswufe/CppCode | /Chapter04/prec.cpp | UTF-8 | 657 | 4.03125 | 4 | [] | no_license | // 运算符优先级
#include <iostream>
using std::cout; using std::endl;
int main()
{
cout << 6 + 3 * 4 / 2 + 2 << endl;
// parentheses in this expression match default precedence and associativity
cout << ((6 + ((3 * 4) / 2)) + 2) << endl; // prints 14
int temp = 3 * 4; // 12
int temp2 = temp / 2; // 6
int temp3 = temp2 + 6; // 12
int result = temp3 + 2; // 14
cout << result << endl;
// parentheses result in alternative groupings
cout << (6 + 3) * (4 / 2 + 2) << endl; // prints 36
cout << ((6 + 3) * 4) / 2 + 2 << endl; // prints 20
cout << 6 + 3 * 4 / (2 + 2) << endl; // prints 9
return 0;
}
| true |
9c4b3d081182a539b11fd2abe44ecc07ce1e2652 | C++ | hschoi1104/stupid-week-2021 | /2021/05/30/jh20s/contest#238/1837.cpp | UTF-8 | 461 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Solution {
public:
int longestBeautifulSubstring(string word) {
int cnt = 0;
int ans = 0;
int now = 0;
vector<char> v = { 'a','e','i','o','u','k' };
int i = 0;
while (i<word.size()) {
if ((word[i] == v[now]) || (cnt!=0 && word[i] == v[now + 1])) {
cnt++;
if (word[i] == v[now + 1])
now++;
if (now == 4) {
ans = max(ans, cnt);
}
}
else {
if (word[i] == 'a') i--;
cnt = 0;
now = 0;
}
i++;
}
return ans;
}
}; | true |
4a2c4d52d7b0ebc6f9ebde60a466d0bbd63a3f8a | C++ | lamer0k/stm32Labs | /Lab7Empty/main.cpp | UTF-8 | 1,787 | 2.953125 | 3 | [] | no_license | #include "adc1registers.hpp" //for ADC1
#include "adccommonregisters.hpp" //for ADCCommon
#include "gpioaregisters.hpp" //for Gpioa
#include "gpiocregisters.hpp" //for Gpioc
#include "rccregisters.hpp" //for RCC
#include "tim2registers.hpp" //for TIM2
#include <iostream>
extern "C"
{
int __low_level_init(void)
{
//Switch on external 8 MHz oscillator
//Switch system clock on external oscillator
//Switch on clock on PortA a
// ************** Setup TIM2 ***********
// Set Devider PSC to count every 1 ms
// Set ARR to 5 seconds overflow
// Clear Overdlow event flag
// Reset counter
// Enable TIM2 to count
//********* ADC1 setup
//Switch on clock on ADC1
//Switch On internal tempearture sensor
//Set single conversion mode
// Set 84 cycles sample rate for channel 18
// Set laentgh of conversion sequence to 1
// Connect first conversion on Channel 18
return 1;
}
}
constexpr float B1 = // see datacheet (page 226) and calculate B coeficient here ;
constexpr float K1 = // see datcheet ((page 226)) and calculate K coeficient here ;
int main()
{
std::uint32_t data = 0U ;
float temperature = 0.0F ;
for(;;)
{
//**************ADC*****************
// Enable ADC1
//Start conversion
// wait until Conversion is not complete
//Get data from ADC
data = //Get data from ADC;
temperature = data * K1 + B1 ; //Convert ADC counts to temperature
std::cout << "Count: " << data << " Temperature: " << temperature << std::endl ;
//Next conversion after 5 sec, wait untel timer is not overflow
while(TIM2::SR::UIF::NoUpdate::IsSet())
{
}
TIM2::SR::UIF::NoUpdate::Set();
}
}
| true |
06f790b5971b78cd2146c2f696f171b95d697a2e | C++ | odiraitis/VEKTORIUS | /vekt_class/vektorius.h | UTF-8 | 15,971 | 3.09375 | 3 | [] | no_license | #define pragma once
#include <initializer_list>
#include <algorithm>
#include <iterator>
#include <exception>
#include <memory>
#include <cstddef>
#include <utility>
template<class T,class Alloc = std::allocator<T>> class Vector {
private:
size_t sz{};
size_t max{};
T *elem;
friend Vector<T> operator+(const Vector<T>& a, const Vector<T>& b) {
if (a.size() != b.size())
throw std::runtime_error("Vektorių dydžio neatitikimas!");
auto size = a.size();
Vector c(size);
for (auto i = 0; i != a.size(); ++i) c[i] = a[i] + b[i];
return c;
}
public:
typedef T value_type;
typedef Alloc allocator_type;
typedef size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef value_type&reference;
typedef const value_type& const_reference;
typedef typename std::allocator_traits<allocator_type>::pointer pointer;
typedef typename std::allocator_traits<allocator_type>::const_pointer const_pointer;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
// konstruktoriai
explicit Vector(const allocator_type& alloc = allocator_type()) :
allocator_(alloc),
capacity_(0),
size_(0),
array_(nullptr)
{
rearrange_pointers();
// std::cout << "c-tor 1" << std::endl;
};
Vector(size_type n, value_type val, const allocator_type& alloc = allocator_type()) :
allocator_(alloc),
capacity_(n),
size_(n),
array_(allocator_.allocate(n))
{
rearrange_pointers();
construct_elements(array_, n, val);
// std::cout << "c-tor 2" << std::endl;
};
explicit Vector(size_type n) :
allocator_(),
capacity_(n),
size_(n),
array_(allocator_.allocate(n))
{
rearrange_pointers();
// std::cout << "c-tor 3" << std::endl;
};
Vector(pointer first, pointer last, const allocator_type& alloc = allocator_type()) :
allocator_(alloc),
capacity_(static_cast<size_type>(last - first)),
size_(static_cast<size_type>(last - first)),
array_(allocator_.allocate(static_cast<size_type>(last - first)))
{
rearrange_pointers();
construct_elements(first, last, array_start_);
// std::cout << "c-tor 4" << std::endl;
};
Vector(const Vector& x) :
allocator_(),
capacity_(x.capacity()),
size_(x.size()),
array_(allocator_.allocate(x.capacity()))
{
rearrange_pointers();
construct_elements(x.begin(), x.end(), array_start_);
//std::cout << "c-tor 5.0" << std::endl;
};
Vector(const Vector& x, const allocator_type& alloc) :
allocator_(alloc),
capacity_(x.capacity()),
size_(x.size()),
array_(allocator_.allocate(x.capacity()))
{
rearrange_pointers();
construct_elements(x.begin(), x.end(), array_start_);
//std::cout << "c-tor 6" << std::endl;
};
Vector(Vector&& x) :
allocator_(),
capacity_(x.capacity_),
size_(x.size_),
array_(x.array_)
{
rearrange_pointers();
x.array_ = nullptr;
x.size_ = 0;
x.capacity_ = 0;
x.rearrange_pointers();
};
Vector(Vector&& x, const allocator_type& alloc) :
allocator_(alloc),
capacity_(x.capacity_),
size_(x.size_),
array_(x.array_)
{
rearrange_pointers();
x.array_ = nullptr;
x.size_ = 0;
x.capacity_ = 0;
x.rearrange_pointers();
};
Vector(std::initializer_list<value_type> il, const allocator_type& alloc = allocator_type()) :
allocator_(alloc),
capacity_(il.size()),
size_(il.size()),
array_(allocator_.allocate(il.size()))
{
rearrange_pointers();
construct_elements(il.begin(), il.end(), array_start_);
std::cout << "c-tor 8" << std::endl;
};
//desructor
~Vector() {
naikink(array_, size_);
allocator_.deallocate(array_, capacity_);
array_start_ = nullptr;
array_end_ = nullptr;
array_range_end_ = nullptr;
//std::cout << "d - tor" << std::endl;
}
// = operatorius
Vector& operator=(const Vector& temp)
{
if (capacity_ >= temp.size_) {
size_ = temp.size();
}
else {
naikink(array_, size_);
allocator_.deallocate(array_, capacity_);
capacity_ = temp.size();
size_ = temp.size();
array_ = allocator_.allocate(temp.size());
}
rearrange_pointers();
construct_elements(temp.begin(), temp.end(), array_start_);
std::cout << "copy" << std::endl;
return *this;
}
Vector& operator=(Vector&& temp)
{
//atlaisvinu atminti priskiriu tempinius kintamuosius pakeiciu rodykles ir nunuliniu tempinius
naikink(array_, capacity_);
allocator_.deallocate(array_, capacity_);
size_ = temp.size_;
capacity_ = temp.capacity_;
array_ = temp.array_;
rearrange_pointers();
temp.size_ = 0;
temp.capacity_ = 0;
temp.array_ = nullptr;
temp.rearrange_pointers();
std::cout<<"move"<<std::endl;
return *this;
}
// assign
void assign(size_type n, const_reference val) {
if (n > capacity_) { increase_array(n); }
construct_elements(array_, n, val);
size_ = n;
rearrange_pointers();
}
void assign(pointer first, pointer last) {
if (last - first > capacity_) { increase_array(last - first); }
construct_elements(first, last, array_start_);
size_ = last - first;
rearrange_pointers();
}
void assign(std::initializer_list<value_type> il) {
if (il.size() <= capacity_) {
}
else {
increase_array(il.size());
}
construct_elements(il.begin(), il.end(), begin());
size_ = il.size();
rearrange_pointers();
}
// get_allocator
inline allocator_type get_allocator() { return allocator_; }
// ELEMENT ACCESS
// at
reference at(size_type n)
{
if (n >= 0 && n < capacity_){ return *(array_start_ + n); }
else throw std::out_of_range("out of vector range.");
}
const_reference at(size_type n) const
{
if (n >= 0 && n < capacity_){ return *(array_start_ + n); }
else throw std::out_of_range("out of vector range.");
}
// operator []
reference operator[](size_type n) { return *(array_start_ + n); }
const_reference operator[](size_type n) const { return *(array_start_ + n); }
// front
inline reference front() { return *(array_start_); }
inline const_reference front() const { return *(array_start_); }
// back
inline reference back() { return *(array_end_); }
inline const_reference back() const { return *(array_end_); }
// data
inline pointer data() const { return array_; }
// begin end iteratoriai
inline iterator begin() { return iterator(array_start_); }
inline const_iterator begin() const { return const_iterator(array_start_); }
inline const_iterator cbegin() const { return const_iterator(array_start_); }
inline iterator end() { return iterator(array_end_); }
inline const_iterator end() const { return const_iterator(array_end_); }
inline const_iterator cend() const { return const_iterator(array_end_); }
inline reverse_iterator rbegin() { return reverse_iterator(end()); }
inline const_reverse_iterator rbegin() const { return reverse_iterator(cend()); }
inline const_reverse_iterator crbegin() const { return reverse_iterator(cend()); }
inline reverse_iterator rend() { return reverse_iterator(begin()); }
inline const_reverse_iterator rend() const { return reverse_iterator(cbegin()); }
inline const_reverse_iterator crend() const { return reverse_iterator(cbegin()); }
//vektoriaus dydis
inline bool empty() const { return size_ == 0; }
inline size_type size() const { return size_; }
inline size_type max_size() const { return size_type(-1); }
void reserve(size_type n)
{
if (n > capacity_){ increase_array(n); }
}
inline size_type capacity() const { return capacity_; }
void shrink_to_fit() { increase_array(size_); }
// vektoriaus valymas
void clear()
{
naikink(array_, size_);
size_ = 0;
rearrange_pointers();
}
// insert
iterator insert(const_iterator position, const value_type& val)
{
const difference_type distance = position - cbegin();
if (array_end_ == array_range_end_)
{
increase_array(std::max(1, static_cast<int>(capacity_ * 2)));
}
size_++;
iterator it = begin() + distance;
construct_elements_backward(it, end(), array_start_ + distance + 1);
allocator_.construct(array_start_ + distance, val);
rearrange_pointers();
return it;
}
iterator insert(const_iterator position, value_type&& val)
{
const difference_type distance = position - cbegin();
if (array_end_ == array_range_end_)
{
increase_array(std::max(1, static_cast<int>(capacity_ * 2)));
}
size_++;
iterator it = begin() + distance;
construct_elements_backward(it, end(), array_start_ + distance + 1);
allocator_.construct(array_start_ + distance, val);
rearrange_pointers();
return it;
}
iterator insert(const_iterator position, size_type count, const value_type& val)
{
const difference_type distance = position - cbegin();
if (size_ + count > capacity_)
{
increase_array(std::max(static_cast<int>(capacity_ * 2), static_cast<int>(size_ + count)));
}
size_ += count;
iterator it = begin() + distance;
construct_elements_backward(it, end(), array_start_ + distance + count);
construct_elements(it, count, val);
rearrange_pointers();
return it;
}
iterator insert(const_iterator position, const_iterator first, const_iterator last)
{
const difference_type distance = position - cbegin();
const difference_type count = last - first;
if (size_ + count > capacity_)
{
increase_array(std::max(static_cast<int>(capacity_ * 2), static_cast<int>(size_ + count)));
}
size_ += count;
iterator it = begin() + distance;
construct_elements_backward(it, end(), array_start_ + distance + count);
construct_elements(first, last, array_start_ + distance);
rearrange_pointers();
return it;
}
iterator insert(const_iterator position, std::initializer_list<value_type> il)
{
const difference_type distance = position - cbegin();
const difference_type count = il.end() - il.begin();
if (size_ + count > capacity_)
{
increase_array(std::max(static_cast<int>(capacity_ * 2), static_cast<int>(size_ + count)));
}
size_ += count;
iterator it = begin() + distance;
construct_elements_backward(it, end(), array_start_ + distance + count);
construct_elements(il.begin(), il.end(), array_start_ + distance);
rearrange_pointers();
return it;
}
// emplace
template <class... Args>
iterator emplace(const_iterator position, Args&&... args)
{
difference_type distance = position - cbegin();
if (array_end_ == array_range_end_)
{
increase_array(std::max(1, static_cast<int>(capacity_ * 2)));
}
construct_elements_backward(begin() + distance, end(), array_start_ + distance + 1);
allocator_.construct(array_start_ + distance, std::forward<Args>(args)...);
size_++;
rearrange_pointers();
return begin() + distance;
}
// erase reikalingas atrinkimui su remove if
iterator erase(const_iterator first, const_iterator last)
{
const difference_type distance = first - cbegin();
const difference_type distance_first_last = last - cbegin();
iterator it_first = begin() + distance;
iterator it_last = begin() + distance_first_last;
construct_elements(it_last, end(), array_start_ + distance);
size_ -= last - first;
rearrange_pointers();
return it_first;
}
// push_back
void push_back(const value_type& val)
{
if (array_end_ == array_range_end_)
{
increase_array(std::max(1, static_cast<int>(capacity_ * 2)));
}
allocator_.construct(array_end_, val);
size_++;
rearrange_pointers();
}
// pop_back
void pop_back()
{
allocator_.destroy(array_end_);
size_--;
rearrange_pointers();
}
// resizinimas
void resize(size_type n)
{
if (n <= size_)
{
naikink(array_start_ + n, size_ - n);
}
else increase_array(std::max(n, 2 * capacity_));
size_ = n;
}
void resize(size_type n, const value_type& val)
{
if (n <= size_)
{
naikink(array_start_ + n, size_ - n);
}
else
{
increase_array(std::max(n, 2 * capacity_));
construct_elements(end(), array_range_end_ - array_end_, val);
rearrange_pointers();
}
size_ = n;
}
//swapas
void swap(Vector& temp)
{
std::swap(capacity_, temp.capacity_);
std::swap(size_, temp.size_);
std::swap(array_, temp.array_);
rearrange_pointers();
temp.rearrange_pointers();
}
private:
allocator_type allocator_;
size_type capacity_;
size_type size_;
pointer array_;
pointer array_start_;
pointer array_end_;
pointer array_range_end_;
void rearrange_pointers()
{
array_start_ = array_;
array_end_ = array_ + size_;
array_range_end_ = array_ + capacity_;
}
void increase_array(size_type new_size)
{
pointer new_array = allocator_.allocate(new_size);
construct_elements(begin(), std::min(end(), begin() + new_size), new_array);
naikink(array_, size_);
allocator_.deallocate(array_, capacity_);
array_ = new_array;
capacity_ = new_size;
rearrange_pointers();
}
void construct_elements(const_iterator begin, const_iterator end, const_iterator destination)
{
const difference_type distance = end - begin;
for (difference_type i = 0; i < distance; ++i)
{
allocator_.construct(destination +i, *(begin));
begin++;
}
}
void construct_elements_backward(const_iterator begin, const_iterator end, const_iterator destination)
{
const difference_type distance = end - begin;
for (difference_type i = distance - 1; i >= 0; --i)
{
allocator_.construct(destination + i, *(end - 1));
end--;
}
}
void construct_elements(pointer destination, size_type count, value_type value)
{
for (size_type i = 0; i < count; ++i)
{
allocator_.construct(destination + i, value);
}
}
void naikink(pointer start, size_type n)
{
for (size_type i = 0; i < n; ++i)
{
allocator_.destroy(start + i);
}
}
};
| true |
fcb17e5bf12c0e2fa84f69749152eb9f1ad9959f | C++ | FariaLucas/Hots | /Hots/src/Torre.h | UTF-8 | 623 | 2.5625 | 3 | [] | no_license | #pragma once
#include "ofMain.h"
#include "Meteoro.h"
class Torre {
private:
ofVec2f m_posicao;
ofImage m_imagem;
Meteoro* meteoro[20];
int m_numeroMeteoro, m_tempo;
bool m_ataque, m_status;
public:
Torre(int x, int y);
ofVec2f GetPosicao();
int GetMeteoroNumero();
bool Radar(ofVec2f posicao);
bool GetAtaque();
bool GetStatus();
bool TempoDeAtaque();
void Atacar(ofVec2f Pos);
void Update(ofVec2f Pos);
void SetPosicao(ofVec2f Pos);
void SetImagem(string nomedoarquivo);
void Draw(ofVec2f Camera);
void SetMeteoroNumero(int numero);
void SetStatus(bool status);
void SetAtaque(bool ataque);
}; | true |
273be12fb1d6f26b0b7407c3f07ae8eb822bf1c0 | C++ | fvandepitte/dailyprogrammer | /_ideas/Rumikub/source.cpp | UTF-8 | 729 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <algorithm>
struct letter
{
char c;
int v;
};
inline bool operator<(const Letter& lhs, const Letter& rhs)
{
return lhs.c == rhs.c : lhs.v < rhs.v ? lhs.c < rhs.c;
}
bool isVallidGroup(const std::set<letter>& letters){
if (letters.size() < 3)
return false;
char firstColor = letters.begin()->c;
return std::all_off(letters.begin() + 1, letters.end(), [firstColor](const letter& l){ return l.c == firstColor }) || std::all_off(letters.begin() + 1, letters.end(), [firstColor](const letter& l){ return l.c != firstColor });
}
int main()
{
auto lambda = [](auto x){ return x; };
std::cout << lambda("Hello generic lambda!\n");
return 0;
} | true |
968c82d8383411573989da33bb7f685d26bfc4f0 | C++ | Parean/Homeworks | /1/Hw6/Task6.1/tree.cpp | UTF-8 | 4,118 | 3.625 | 4 | [] | no_license | #include "tree.h"
#include <stdio.h>
TreeNode *removeElement(TreeNode *treeNode, TreeNode *&temp);
TreeNode **findNode(TreeNode *&treeNode, int value);
TreeNode *addInTree(Tree *tree, TreeNode *treeNode, int value);
void deleteNode(TreeNode *&treeNode);
void printInDescendingOrder(TreeNode *treeNode);
void printInAscendingOrder(TreeNode *treeNode);
void debugOutput(TreeNode *treeNode);
void deleteTree(TreeNode *&treeNode);
TreeNode *createTreeNode(Tree *&tree, int value)
{
TreeNode *newTreeNode = new TreeNode;
newTreeNode->value = value;
newTreeNode->left = newTreeNode->right = nullptr;
if (tree->root == nullptr)
tree->root = newTreeNode;
return newTreeNode;
};
Tree *createTree()
{
Tree *newTree = new Tree;
newTree->root = nullptr;
return newTree;
}
TreeNode **findNode(Tree *tree, int value)
{
return findNode(tree->root, value);
}
TreeNode **findNode(TreeNode *&treeNode, int value)
{
if (!treeNode)
return nullptr;
if (treeNode->value == value)
return &treeNode;
if (treeNode->value > value)
return findNode(treeNode->left, value);
else
return findNode(treeNode->right, value);
}
void addInTree(Tree *tree, int value)
{
addInTree(tree, tree->root, value);
}
TreeNode *addInTree(Tree *tree, TreeNode *treeNode, int value)
{
if (!treeNode)
return createTreeNode(tree, value);
if (treeNode->value > value)
treeNode->left = addInTree(tree, treeNode->left, value);
else
treeNode->right = addInTree(tree, treeNode->right, value);
return treeNode;
}
void deleteNode(Tree *tree, int value)
{
if (tree->root)
{
TreeNode **treeNode = findNode(tree->root, value);
if (treeNode)
deleteNode(*treeNode);
}
}
void deleteNode(TreeNode *&treeNode)
{
if (treeNode->left == nullptr && treeNode->right == nullptr)
{
delete treeNode;
treeNode = nullptr;
}
else if (treeNode->left == nullptr && treeNode->right != nullptr ||
treeNode->left != nullptr && treeNode->right == nullptr)
{
if (treeNode->left)
{
TreeNode *temp = treeNode->left;
delete treeNode;
treeNode = temp;
}
if (treeNode->right)
{
TreeNode *temp = treeNode->right;
delete treeNode;
treeNode = temp;
}
}
else if (treeNode->left != nullptr && treeNode->right != nullptr)
{
TreeNode *temp = nullptr;
treeNode->right = removeElement(treeNode->right, temp);
TreeNode *left = treeNode->left;
TreeNode *right = treeNode->right;
delete treeNode;
treeNode = temp;
treeNode->left = left;
treeNode->right = right;
}
}
TreeNode *removeElement(TreeNode *treeNode, TreeNode *&temp)
{
if (treeNode->left != nullptr)
{
treeNode->left = removeElement(treeNode->left, temp);
}
else
{
temp = treeNode;
return treeNode->right;
}
return treeNode;
}
void printInDescendingOrder(Tree *tree)
{
if (tree->root)
printInDescendingOrder(tree->root);
}
void printInDescendingOrder(TreeNode *treeNode)
{
if (treeNode->right != nullptr)
printInDescendingOrder(treeNode->right);
printf("%d ", treeNode->value);
if (treeNode->left != nullptr)
printInDescendingOrder(treeNode->left);
}
void printInAscendingOrder(Tree *tree)
{
if (tree->root)
printInAscendingOrder(tree->root);
}
void printInAscendingOrder(TreeNode *treeNode)
{
if (treeNode->left != nullptr)
printInAscendingOrder(treeNode->left);
printf("%d ", treeNode->value);
if (treeNode->right != nullptr)
printInAscendingOrder(treeNode->right);
}
void debugOutput(Tree *tree)
{
if (tree->root)
debugOutput(tree->root);
}
void debugOutput(TreeNode *treeNode)
{
printf("(");
printf("%d ", treeNode->value);
if (treeNode->left != nullptr)
{
debugOutput(treeNode->left);
}
else
printf("null ");
if (treeNode->right != nullptr)
{
debugOutput(treeNode->right);
}
else
printf("null");
printf(")");
}
void deleteTree(Tree *tree)
{
deleteTree(tree->root);
}
void deleteTree(TreeNode *&treeNode)
{
if (treeNode)
{
if (treeNode->left != nullptr)
deleteTree(treeNode->left);
if (treeNode->right != nullptr)
deleteTree(treeNode->right);
if (treeNode->left == nullptr && treeNode->right == nullptr)
{
delete treeNode;
treeNode = nullptr;
}
}
} | true |
f217b5062cbc853eb2d2fa4e207d054091f6c3e8 | C++ | KoTLiK/network | /src/server.cpp | UTF-8 | 2,013 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <csignal>
#include "Network.h"
Net::Server server(Net::Datagram::TCP);
void signalHandler(int) {
server.stop();
std::cout << "\nShutting down...\n";
exit(0);
}
int main() {
std::string input;
signal(SIGINT, signalHandler);
std::string delimiter = ".";
Net::Protocol protocol(delimiter);
try {
server.start(8080);
if (server.getDatagram() == Net::Datagram::TCP) {
server.setListen(2);
while (true) {
server.openConnection();
std::cout << "Client connected.\n";
while (true) {
try {
if (!server.receiveMessage(protocol))
break;
protocol.front();
protocol.pop();
std::cout << "RECV: " << protocol.getCurrentMessage() << std::endl; // Serve
server.sendMessage(protocol.getCurrentMessage());
} catch (Net::NetworkException& e) {
std::cerr << e.what() << std::endl;
break;
}
}
server.closeConnection();
std::cout << "Connection closed.\n";
}
} else { // Net::Datagram::UDP
while (true) {
try {
if (!server.receiveMessage(protocol))
break;
protocol.front();
protocol.pop();
std::cout << "RECV: " << protocol.getCurrentMessage() << std::endl; // Serve
server.sendMessage(protocol.getCurrentMessage());
} catch (Net::NetworkException& e) {
std::cerr << e.what() << std::endl;
break;
}
}
}
} catch (Net::NetworkException& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| true |
ca450d080707f85f9118a4c1442fde9aabd0e33d | C++ | shashank0107/CP-Solutions | /UVA 757.cpp | UTF-8 | 4,198 | 2.625 | 3 | [] | no_license | /*
Note that John will plan his travel linearly, i.e., after going to 2 from 1 he won't come back to 1
Now we'll just find the value of dp[i][ti] : fishes caught in pos i till time ti ( 1 ti = 5 min ),
this value only depends on the previous state and the time of transition from the previous lake to the current
*/
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/*** Template Begins ***/
typedef long long ll;
typedef pair<ll,ll> PII;
typedef pair<ll, pair<int, int> > PIII;
typedef vector<int> vi;
#define endl '\n'
#define pb push_back
#define INF INT_MAX/10
#define F first
#define S second
#define mp make_pair
#define ios ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define hell 1000000007
#define all(a) (a).begin(),(a).end()
ll power(ll x, ll y, ll p){ ll res = 1;x = x % p;while (y > 0){ if (y & 1) res = (res*x) % p;y = y>>1;x = (x*x) % p;} return res; }
// Debug //
#define trace(x) cerr << #x << ": " << x << endl;
#define trace1(x) cerr << #x << ": " << x << endl;
#define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl;
// Constants //
const int N = 200;
const int xinc[] = {0, 0, 1, -1};
const int yinc[] = {1, -1, 0, 0};
const long double PI = acos(-1.0);
const double EPS = 1e-9;
/*** Template Ends ***/
int n, h, t[N], f[N], d[N], dp[N][N], rem[N][N], limit[N];
int prv[N][N], spent[N];
bool valid(int pos, int time){
return (time >= 0 && dp[pos][time] != -1);
}
int val(int pos, int ti){
if (ti <= limit[pos])
return ti*f[pos] - (d[pos]*ti*(ti-1))/2;
else{
ti = limit[pos];
return ti*f[pos] - (d[pos]*ti*(ti-1))/2 + f[pos]%d[pos];
}
}
void tracedp(int pos, int ti){
spent[pos] = ti - prv[pos][ti];
if (pos != 0)
tracedp(pos-1, prv[pos][ti]-t[pos]);
}
void solve(){
while(cin >> n){
if (n == 0) break;
memset(dp, -1, sizeof dp);
memset(spent, 0, sizeof spent);
cin >> h; h*=12;
for(int i = 0; i < n; i++) cin >> f[i];
for(int i = 0; i < n; i++) cin >> d[i];
for(int i = 1; i < n; i++) cin >> t[i];
for(int i = 0; i < n; i++) limit[i] = d[i] != 0 ? f[i]/d[i] : INT_MAX;
for(int ti = 0; ti <= h; ti++)
dp[0][ti] = val(0, ti);
for(int i = 1; i < n; i++)
for(int ti = 0; ti <= h; ti++)
{
// need to calculate dp[i][ti]
// we have many choices about the time at which john came to this lake
// let that be t_lake
dp[i][ti] = -1;
for(int t_lake = ti; t_lake >= 0; t_lake--)
if (valid(i-1, t_lake-t[i])){
if ( dp[i-1][t_lake-t[i]] + val(i, ti-t_lake) > dp[i][ti] )
dp[i][ti] = dp[i-1][t_lake-t[i]] + val(i, ti-t_lake),
prv[i][ti] = t_lake;
}
//trace3(i, ti, dp[i][ti]);
}
int ans = -1, lp = -1;
for(int i = 0; i < n; i++)
if (dp[i][h] > ans) ans = dp[i][h], lp = i;
tracedp(lp, h);
for(int i = 0; i < n-1; i++) cout << spent[i]*5 << ", ";
cout << spent[n-1]*5 << endl;
cout << "Number of fish expected: " << ans << endl;
cout << endl;
}
}
int main(){
ios;
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int t;
//cin >> t;
t = 1;
while(t--)
solve();
return 0;
}
| true |
5592da1facd5c6599619d5e162f0a4f5d0875edf | C++ | acastellanos95/AppCompPhys | /CH18/NITROGEN/N2.cpp | UTF-8 | 10,422 | 2.90625 | 3 | [
"MIT"
] | permissive | /*
N2.cpp Ryckaert method for dumbbell N2
this time with standard Verlet
molecule index m:0->N_mol-1)
atom index a:(0,1)
particle index i:(0->2N_mol-1)
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <vector>
using namespace std;
typedef mt19937_64 MersenneTwister;
double d; // N2 diameter
double mass; // atomic mass (equal mas case)
double eps; // potential strength in units of Ar LJ potl
int Nmol; // number of molecules
int Nmol3; // Nmol^1/3 for indexing in cube
int Np; // 2 Nmol
double L;
class ThreeVect {
public:
double x;
double y;
double z;
ThreeVect () {
x=0.0; y=0.0; z=0.0;
};
ThreeVect (double x0, double y0, double z0) {
x=x0; y=y0; z=z0;
};
void setV(double x0, double y0, double z0) {
x=x0; y=y0; z=z0;
}
void setV(ThreeVect v) {
x=v.x; y=v.y; z=v.z;
}
double magSq() {
return x*x + y*y + z*z;
}
double operator*(const ThreeVect & other);
ThreeVect operator+(const ThreeVect & other);
ThreeVect operator-(const ThreeVect & other);
ThreeVect operator^(const ThreeVect & other);
friend std::ostream &operator<<(std::ostream &out, ThreeVect v0) {
out << v0.x << " " << v0.y << " " << v0.z;
return out;
}
}; // end of class ThreeVect
ThreeVect ThreeVect::operator-(const ThreeVect & other) {
return ThreeVect(x-other.x,y-other.y,z-other.z);
}
ThreeVect ThreeVect::operator+(const ThreeVect & other) {
return ThreeVect(x+other.x,y+other.y,z+other.z);
}
ThreeVect ThreeVect::operator^(const ThreeVect & other) {
// cross product
double x0 = y*other.z - z*other.y;
double y0 = z*other.x - x*other.z;
double z0 = x*other.y - y*other.x;
return ThreeVect(x0,y0,z0);
}
double ThreeVect::operator*(const ThreeVect & other) {
// dot product
return x*other.x + y*other.y + z*other.z;
}
ThreeVect operator*(const double & lhs, const ThreeVect & rhs) {
ThreeVect v0 = ThreeVect(lhs*rhs.x,lhs*rhs.y,lhs*rhs.z);
return v0;
}
ThreeVect operator*(const ThreeVect & lhs, const double & rhs) {
ThreeVect v0 = ThreeVect(rhs*lhs.x,rhs*lhs.y,rhs*lhs.z);
return v0;
}
ThreeVect operator/(const ThreeVect & lhs, const double & rhs) {
ThreeVect v0 = ThreeVect(lhs.x/rhs,lhs.y/rhs,lhs.z/rhs);
return v0;
}
// --------------------------------------------------------------------
ThreeVect *rold = NULL;
ThreeVect *r = NULL;
ThreeVect *rnew = NULL;
ThreeVect *rCM = NULL;
ThreeVect *v = NULL;
ThreeVect *f = NULL;
int IM(int m, int a) {
// indexing for m=molecule (0,N^3) and a=atom (0,1)
return 2*m + a;
}
int IJ(int i, int j) {
// indexing for (0:Np)^2
return i*Np+j;
}
int I(int m1, int m2, int m3) {
// indexing for 3d lattice (0:Nmol3-1)^3
return (m1*Nmol3+m2)*Nmol3 + m3;
}
double rsqMin(int i, int j) {
ThreeVect r1,r2;
r1 = r[i];
r2 = r[j];
if (abs(r1.x-r2.x) > L/2.0) r2.x += copysign(L,r1.x-r2.x);
if (abs(r1.y-r2.y) > L/2.0) r2.y += copysign(L,r1.y-r2.y);
if (abs(r1.z-r2.z) > L/2.0) r2.z += copysign(L,r1.z-r2.z);
return (r1-r2).magSq();
}
ThreeVect rhatMin(int i, int j) {
// really \vec{r} not \hat{r}
ThreeVect r1,r2;
r1 = r[i];
r2 = r[j];
if (abs(r1.x-r2.x) > L/2.0) r2.x += copysign(L,r1.x-r2.x);
if (abs(r1.y-r2.y) > L/2.0) r2.y += copysign(L,r1.y-r2.y);
if (abs(r1.z-r2.z) > L/2.0) r2.z += copysign(L,r1.z-r2.z);
ThreeVect rh = r1-r2;
return rh;
}
void getF() {
// obtain F
for (int m=0;m<Nmol;m++) {
for (int a=0;a<2;a++) {
int i1 = IM(m,a);
f[IJ(i1,i1)].setV(0.0,0.0,0.0);
for (int n=m+1;n<Nmol;n++) {
for (int b=0;b<2;b++) {
int i2 = IM(n,b);
f[IJ(i1,i2)].setV(0.0,0.0,0.0);
f[IJ(i2,i2)].setV(0.0,0.0,0.0);
double rsq = rsqMin(i1,i2);
double r6 = rsq*rsq*rsq;
ThreeVect rhat = rhatMin(i1,i2);
double ft = eps*24.0*(2.0/(r6*r6) - 1.0/r6)/rsq;
f[IJ(i1,i2)] = ft*rhat;
f[IJ(i2,i1)] = (-1.0)*f[IJ(i1,i2)];
}}
}}
return;
}
ThreeVect getA(int i) {
// obtain acceleration for particle i
ThreeVect a;
for (int j=0;j<Np;j++) {
a = a + f[IJ(i,j)];
}
return a/mass;
}
void getBC() {
// it doesn't matter how one defines wrapping, as long as the volume is L^3
// we'll use the CM coords
for (int m=0;m<Nmol;m++) {
if (rCM[m].x > L) {
rnew[IM(m,0)].x -= L;
rnew[IM(m,1)].x -= L;
r[IM(m,0)].x -= L;
r[IM(m,1)].x -= L;
}
if (rCM[m].x < 0) {
rnew[IM(m,0)].x += L;
rnew[IM(m,1)].x += L;
r[IM(m,0)].x += L;
r[IM(m,1)].x += L;
}
if (rCM[m].y > L) {
rnew[IM(m,0)].y -= L;
rnew[IM(m,1)].y -= L;
r[IM(m,0)].y -= L;
r[IM(m,1)].y -= L;
}
if (rCM[m].y < 0) {
rnew[IM(m,0)].y += L;
rnew[IM(m,1)].y += L;
r[IM(m,0)].y += L;
r[IM(m,1)].y += L;
}
if (rCM[m].z > L) {
rnew[IM(m,0)].z -= L;
rnew[IM(m,1)].z -= L;
r[IM(m,0)].z -= L;
r[IM(m,1)].z -= L;
}
if (rCM[m].z < 0) {
rnew[IM(m,0)].z += L;
rnew[IM(m,1)].z += L;
r[IM(m,0)].z += L;
r[IM(m,1)].z += L;
}
} // end of molecule loop
}
double temp() {
// equipartition theorem: per molecule we have
// sum_{a=0,1} 1/2 m v^2 = 5/2 kT -->
// sum_{m,a} 1/2 m_m v_{m,a}^2 = 5/2 Nmol kT
double kin=0.0;
for (int i=0;i<Np;i++) {
kin += v[i].magSq();
}
return mass*kin/(5.0*Nmol);
}
double LJ(double rsq) {
// unitless Lenard-Jones potential as a function of r^2
// scale by eps (in units of Ar epsilon)
// m=1 eps=1 sigma=1 t=1.8 ps
// normally V = 4 eps ( (sig/r)^12 - (sig/r)^6) eps/k = 119.8K sig= 2.405 A
double r6 = rsq*rsq*rsq;
return eps*4.0*(1.0/(r6*r6) - 1.0/r6);
}
double U() {
double u = 0.0;
for (int m=0;m<Nmol;m++) {
for (int a=0;a<2;a++) {
int i1 = IM(m,a);
for (int n=m+1;n<Nmol;n++) {
for (int b=0;b<2;b++) {
int i2 = IM(n,b);
u += LJ(rsqMin(i1,i2));
}}
}}
return u/Np;
}
double energy() {
double e = 0.0;
for (int i=0;i<Np;i++) {
e += v[i].magSq();
}
e = mass*e/2.0;
for (int m=0;m<Nmol;m++) {
for (int a=0;a<2;a++) {
int i1 = IM(m,a);
for (int n=m+1;n<Nmol;n++) {
for (int b=0;b<2;b++) {
int i2 = IM(n,b);
e += LJ(rsqMin(i1,i2));
}}
}}
return e/Np;
}
int main(void) {
uniform_real_distribution<double> Dist(-1.0,1.0);
uniform_real_distribution<double> thDist(0.0,M_PI);
uniform_real_distribution<double> phDist(0.0,2.0*M_PI);
double mu,v0,dt,temp0,tol;
int Ttherm,Tlambda;
ofstream ofs,ofs2,ofs3;
ofs.open("N2.dat");
ofs2.open("N2b.dat");
ofs3.open("N2c.dat");
ofs << "# N2.cpp " << endl;
cout << " input N (number of molecules = N^3), box size, molecule diameter, atomic mass " << endl;
cin >> Nmol3 >> L >> d >> mass;
mu = mass/2.0;
Nmol = Nmol3*Nmol3*Nmol3;
Np = 2*Nmol;
cout << " enter temp, dt, Ttherm, Tlambda, eps " << endl;
cin >> temp0 >> dt >> Ttherm >> Tlambda >> eps;
cout << " enter tolerance for Ryckaert iteration " << endl;
cin >> tol;
v0 = sqrt(5.0*temp0/(2.0*mass));
double r0 = L/Nmol3;
cout << " enter seed " << endl;
int seed;
cin >> seed;
MersenneTwister mt(seed);
rold = new ThreeVect[Np];
r = new ThreeVect[Np];
rnew = new ThreeVect[Np];
rCM = new ThreeVect[Nmol];
v = new ThreeVect[Np];
f = new ThreeVect[Np*Np];
for (int i=0;i<Nmol3;i++) {
for (int j=0;j<Nmol3;j++) {
for (int k=0;k<Nmol3;k++) {
// initial molecular CM
ThreeVect RCM(r0*(i + 0.5 + Dist(mt)/10.0),
r0*(j + 0.5 + Dist(mt)/10.0),
r0*(k + 0.5 + Dist(mt)/10.0));
// initial d
double th = thDist(mt);
double ph = phDist(mt);
ThreeVect dd(d*sin(th)*cos(ph),d*sin(th)*sin(ph),d*cos(th));
// set atoms
int m = I(i,j,k);
r[IM(m,0)].setV(RCM+dd/2.0);
r[IM(m,1)].setV(RCM-dd/2.0);
ofs << "0 " << r[IM(m,0)] << " " << r[IM(m,1)] << endl;
}}}
// try something simple for now
for (int i=0;i<Np;i++) {
rold[i] = r[i];
v[i].setV(0.0,0.0,0.0);
}
cout << " initial temp: " << 0.4*mass*v0*v0 << " " << temp() << endl;
cout << " density: " << pow(Nmol3/L,3) << endl;
int tLam=1;
for (int t=0;t<Ttherm;t++) {
getF();
// standard Verlet
for (int i=0;i<Np;i++) {
ThreeVect a = getA(i);
if (dt*dt*sqrt(a.magSq()) > r0) cout << " trouble " << endl;
rnew[i] = 2.0*r[i] - rold[i] + dt*dt*a;
}
// temperature rescaling.
tLam++;
if (tLam == Tlambda) {
double lambda = sqrt(temp0/temp());
cout << temp0 << " " << temp() << endl;
for (int i=0;i<Np;i++) rnew[i] = lambda*rnew[i] - (lambda-1.0)*rold[i];
tLam = 1;
}
// impose Lagrangian constraints
for (int m=0;m<Nmol;m++) {
ThreeVect Dr;
Dr.setV(r[IM(m,0)]-r[IM(m,1)]);
ThreeVect r0 = rnew[IM(m,0)];
ThreeVect r1 = rnew[IM(m,1)];
ThreeVect Drold=r0-r1; // rold(m,0)-rold(m,1); starting value is rnew from Verlet
double lambda = 1000.0;
int it=0;
while (abs(lambda) > tol) {
double den = Drold*Dr;
den = den*dt*dt*4.0/mu;
lambda = (Drold.magSq() - d*d)/den;
ThreeVect rn0 = r0 - 2.0*dt*dt*lambda/mass*Dr;
ThreeVect rn1 = r1 + 2.0*dt*dt*lambda/mass*Dr;
r0 = rn0;
r1 = rn1;
Drold = r0-r1;
it++;
if (it > 100) {
cout << " iteration trouble " << lambda << " " << m << " " << t << endl;
abort();
}
}
rnew[IM(m,0)] = r0;
rnew[IM(m,1)] = r1;
}
// BCs
for (int m=0;m<Nmol;m++) {
rCM[m] = 0.5*(rnew[IM(m,0)]+rnew[IM(m,1)]);
}
getBC();
// and update
for (int i=0;i<Np;i++) {
v[i] = (rnew[i] - rold[i])/(2.0*dt);
rold[i] = r[i];
r[i] = rnew[i];
}
ofs2 << t << " " << r[IM(1,0)] << " " << r[IM(1,1)] << " " << (r[IM(1,0)]-r[IM(1,1)]).magSq() << endl;
for (int m=0;m<Nmol;m++) {
ofs << t << " " << r[IM(m,0)] << " " << r[IM(m,1)] << endl;
}
ofs3 << t << " " << temp() << " " << U() << " " << energy() << endl;
} // end of thermalization loop
cout << " t, r(1), r(2) in N2.dat " << endl;
cout << " t, r(1), r(2) for a molecule 1 in N2b.dat " << endl;
cout << " t, T, U, E in N2c.dat " << endl;
delete [] rold;
delete [] r;
delete [] rnew;
delete [] rCM;
delete [] v;
delete [] f;
ofs.close();
ofs2.close();
ofs3.close();
return 0;
}
| true |
dbb5a3febcedf9e98f8f625b6d808b47e485a6e2 | C++ | Dogbone0714/C-_Database | /A56.cpp | UTF-8 | 248 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(void){
for(;;){
int a,sum=0;
double b=0.1;
cin>>a;
while(a/2>=1){
b*=10;
sum=sum+(a%2)*b;
a/=2;
}
cout<<b*10+sum<<endl;
}
}
| true |
81b84968bedfd2cc620e61897d349fa29e7c5a88 | C++ | ramonjunquera/GlobalEnvironment | /RPi/Geany/02 cpp/08 Lists/01 ForwardList/ForwardList.cpp | UTF-8 | 4,324 | 3.640625 | 4 | [] | no_license | /*
* Autor: Ramón Junquera
* Tema: Programación en C++
* Objetivo: Lista simple
* Material: Raspberry Pi
* Descripción:
* Las listas son una de las estructuras más utilizadas en programación.
*
* En el ejemplo actual aprenderemos a utilizar una lista simple.
* Son aquellas que un elemento guarda un valor y un puntero al
* siguiente elemento de la lista. Sólo se pueden recorrer en una
* dirección: de principio a fin.
*
* Ya existe una clase librería llamada forward_list que permite
* automatizar su uso.
* El problema es que esta librería pertenece al estándar C++11 que no
* siempre está disponible en el compilador.
* Por suerte en la versión actual de Raspbian el compilador (gcc) es
* capaz de soportarla aunque sea en modo beta.
* Para ello tendremos que hacer alguna modificación en los parámetros
* del compilador.
* Seleccionamos Build/Set Build Commands y en la sección "C++ commands"
* Encontraremos los siguientes parámetros:
* Compile: g++ -Wall -c "%f"
* Build: g++ -Wall -o "%e" "%f"
* Que los sustituiremos por:
* Compile: g++ -Wall -std=c++11 -c "%f"
* Build: g++ -Wall -std=c++11 -o "%e" "%f"
*
* Comenzamos incluyendo la librería forward_list
*
* En la función main creamos una lista sencilla de números enteros.
* Realmente podemos poner cualquier tipo de variable. Clases incluidas.
*
* A continuación añadimos varios elementos a la lista.
* A este tipo de listas sólo se le pueden añadir elementos por el
* principio.
* Realmente se crea un nuevo nodo y se le hace apuntar al nodo que
* antes era el primero.
*
* Para finalizar, llamamos a una función que se encarga de mostrar la
* lista en pantalla.
*
* La función PrintList tiene como parámetro el puntero de la lista.
* Lo que hacemos es utilizar un iterator para recorrer todos los
* elementos de la lista.
* Un iterator se comporta como un puntero. Apunta a un nodo de la
* lista. La gran ventaja es que admite su incremento (++).
* Esto no pasa a la siguiente posición de memoria, sino al siguiente
* nodo. Esto facilita las cosas a la hora de moverse por los nodos de
* la lista.
* Comenzamos por el nodo inicial (list.begin()).
* Recorremos los nodos hasta llegar al final (list.end()).
* El nodo final no es el último, sino que es el puntero del último de
* los nodos (que habitualmente es NULL).
* En cada ciclo iremos aumentando el iterator.
* Otra de las ventajas es que el contenido del iterator es el valor del
* nodo. Así no tenemos que buscarlo.
*
* En esta primera función se declara completamente el iterator.
*
* Existe una segunda función para imprimir la lista llamada PrintList2.
* La única diferencia es que aquí no se declara el iterator.
* Nos aprovechamos de que una variable puede ser declarada como auto y
* su tipo será definido cuando se le asigne valor.
* Esta sintaxis es más cómoda, rápida y evita errores de declaración.
*/
#include <iostream>
#include <forward_list>
using namespace std;
void PrintList(forward_list<int> list)
{
//Muestra la lista en pantalla
//Recorre todos los elementos de la lista, comenzando por el primero
//de uno en uno, mientras no se llegue al último
for(forward_list<int>::iterator itr=list.begin();itr!=list.end();itr++)
{
//Muestra el valor del elemento de la lista seguido de un espacio
cout << *itr << " ";
}
//Hemos terminado de escribir todos los elementos de la lista
//Escribimos un retorno de carro
cout << endl;
}
void PrintList2(forward_list<int> list)
{
//Muestra la lista en pantalla
//Recorre todos los elementos de la lista, comenzando por el primero
//de uno en uno, mientras no se llegue al último
for(auto itr=list.begin();itr!=list.end();itr++)
{
//Muestra el valor del elemento de la lista seguido de un espacio
cout << *itr << " ";
}
//Hemos terminado de escribir todos los elementos de la lista
//Escribimos un retorno de carro
cout << endl;
}
int main(int argc, char **argv)
{
//Creamos una lista sencilla de números enteros
forward_list<int> list;
//Añadimos varios valores a la lista por el inicio
list.push_front(3);
list.push_front(7);
list.push_front(8);
//Mostramos el contenido de la lista
PrintList(list);
//Mostramos el contenido de la lista
PrintList2(list);
//Todo ok
return 0;
}
| true |
4157e1a35a01d907200c9d263f335055f875fb08 | C++ | AlexDz27/cpp-fiddles | /projects/template-functions/main.cpp | UTF-8 | 240 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
template<typename T>
T sum(T a, T b) {
return a + b;
}
int main() {
double a = 2.4;
double b = 3.5;
double result = sum<double>(a, b);
cout << result;
return 0;
}
| true |
be72d0bfcf410899c6eb09b3477275fa4d5f9eb1 | C++ | gr001/PeaksProcessing2 | /Bridge/section.cpp | UTF-8 | 1,930 | 2.625 | 3 | [] | no_license | // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "Stdafx.h"
#include "./stfio.h"
#include "./section.h"
// Definitions------------------------------------------------------------
// Default constructor definition
// For reasons why to use member initializer lists instead of assignments
// within the constructor, see [1]248 and [2]28
Section::Section(void)
: section_description(), x_scale(1.0), data(0)
{}
Section::Section( const Vector_double& valA, const std::string& label )
: section_description(label), x_scale(1.0), data(valA)
{}
Section::Section(std::size_t size, const std::string& label)
: section_description(label), x_scale(1.0), data(size)
{}
Section::~Section(void) {
}
double Section::at(std::size_t at_) const {
if (at_>=data.size()) {
std::out_of_range e("subscript out of range in class Section");
throw (e);
}
return data[at_];
}
double& Section::at(std::size_t at_) {
if (at_>=data.size()) {
std::out_of_range e("subscript out of range in class Section");
throw (e);
}
return data[at_];
}
void Section::SetXScale( double value ) {
if ( x_scale >= 0 )
x_scale=value;
else
throw std::runtime_error( "Attempt to set x-scale <= 0" );
}
| true |
0c11a750a5f91fc45ced1697373c7693e36df5dc | C++ | IvanovskyOrtega/Udemy-Curso-Cpp | /S2-Operaciones-Basicas/promedioNotas.cpp | UTF-8 | 494 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main(){
/** EJERCICIO 3 **/
/**
Escriba un programa que lea 3 notas y escriba el promedio final.
**/
float nota1, nota2, nota3, promedio;
cout << "Ingresa la primer nota: ";
cin >> nota1;
cout << "Ingresa la segunda nota: ";
cin >> nota2;
cout << "Ingresa la tercer nota: ";
cin >> nota3;
promedio = (nota1 + nota2 + nota3)/3;
cout << "El promedio es: " << promedio << endl;
return 0;
}
| true |
fd17c0436c8a2d982f23ceab1e474e0bbaded4b3 | C++ | 15831944/nfpvr | /nfpvrlib/Bitfield.h | UTF-8 | 1,008 | 2.765625 | 3 | [] | no_license | #ifndef __bitfield_h__
#define __bitfield_h__
#include "NfpvrTypes.h"
namespace nfpvr
{
class Bitfield
{
public:
Bitfield(uint8* buffer, int length);
void attach(uint8* buffer, int length);
template <typename T>
static T decode(const uint8* buffer);
template <typename T>
static void encode(const T data, uint8* buffer);
virtual void skip(int bits)=0;
virtual void reset()=0;
protected:
uint8* _buffer;
int _length;
int _bitIndex;
int _byteIndex;
};
class BitfieldWriter: public Bitfield
{
public:
BitfieldWriter(uint8* data, int length);
template <typename T>
void write(T& data, int bits);
void write(const uint8, int bits);
void skip(int bits);
void reset();
};
class BitfieldReader: public Bitfield
{
public:
BitfieldReader(const uint8* data, int length);
template <typename T>
void read(T& data, int bits);
uint8 read(int bits);
void skip(int bits);
void reset();
};
}
#endif
| true |
b574b42c46ef22585b2733ce575fe786b2c91e78 | C++ | wonderly321/CodeExercise | /LCS&LIS/d.cpp | UTF-8 | 1,891 | 2.609375 | 3 | [] | no_license | /*
* Author : Wonderly321
* Create Time : 2018-12-08 21:26:09
* File Name : d.cpp
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <vector>
#include <map>
#include <stack>
#include <ctime>
#include <sstream>
using namespace std;
#define inf 0x3f3f3f3f
#define eps 1e-10
#define sqr(x) ((x)*(x))
#define clr(x) memset(x,0,sizeof(x))
typedef long long ll;
template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}
int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}
int m, n;
char s[110], t[110];
int dp[110][110];
int score(char a,char b){
if(a == b)
return 5;
if((a == 'C' && b == 'G')||(a == 'G' && b == 'C')||(a == 'A' && b == '-')||(a == '-' && b == 'A'))
return -3;
if((a == 'G' && b == 'A')||(a == 'A' && b == 'G')||(a == 'C' && b =='T')||(a == 'T' && b == 'C')||(a == '-' && b == 'G')||(a == 'G' && b == '-')||(a == 'T' && b =='G')||(a == 'G' && b == 'T'))
return -2;
if((a == 'A' && b == 'T')||(a == 'T' && b == 'A')||(a == 'A' && b == 'C')||(a == 'C' && b == 'A')||(a == 'T' && b == '-')||(a == '-' && b == 'T'))
return -1;
if((a == 'C' && b == '-')||(a == '-' && b == 'C'))
return -4;
return 0;
}
int main(){
int T;
cin>>T;
while(T--){
scanf("%d %s", &m, s+1);
scanf("%d %s", &n, t+1);
for(int i = 1; i <= m; i++) dp[i][0] = dp[i-1][0] + score(s[i],'-');
for(int j = 1; j <= n; j++) dp[0][j] = dp[0][j-1] + score(t[j],'-');
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = max(dp[i-1][j-1] + score(s[i],t[j]) , max(dp[i][j-1] + score('-',t[j]) , dp[i-1][j]+score(s[i],'-')));
}
}
cout<<dp[m][n]<<endl;
}
return 0;
}
| true |
2575abc1a4aa5e92318e4834c99b4fdc9acf6e29 | C++ | nathreya/karma | /lex.cpp | UTF-8 | 15,893 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "lex.h"
#include "lex_utils.h"
namespace __karma {
namespace __lex {
string remove_line_continuations(string source) {
vector<string> tpsplt;
int index = 0;
string ret;
for(int i = 0; i < source.length(); i++) {
if(source.substr(i,_new_line.length()) == _new_line) {
string ins = source.substr(index,i - index);
tpsplt.push_back(ins);
index = i + 1;
}
}
tpsplt.push_back(source.substr(index,source.length()));
int counter = 0;
for(int i = 0; i < tpsplt.size(); i++) {
string tos = tpsplt[i];
trim(tos);
string ending("\\");
if(ends_with(tos,ending)) {
int c = 0;
while(ends_with(tos,ending)) {
tos = tpsplt[i];
if(ends_with(tos,ending)) {
ret.insert(ret.length(),tos.substr(0,tos.length() - 1));
}
else {
ret.insert(ret.length(),tos);
c++;
}
i++;
counter++;
}
for(int i = 0; i < counter; i++)
ret += _new_line;
counter = 0;
i -= c;
}
else if(!ends_with(tos,ending)) {
ret.insert(ret.length(),tos + _new_line);
}
}
return ret;
}
vector <token> lex(string source) {
vector<string> ret;
for(int i = 0; i < source.length(); i++) {
switch(source[i]) {
case '?':
ret.push_back("?");
break;
case ':':
ret.push_back(":");
break;
case '~':
ret.push_back("~");
break;
case '(':
ret.push_back("(");
break;
case ')':
ret.push_back(")");
break;
case '[':
ret.push_back("[");
break;
case ']':
ret.push_back("]");
break;
case '{':
ret.push_back("{");
break;
case '}':
ret.push_back("}");
break;
case ',':
ret.push_back(",");
break;
case ';':
ret.push_back(";");
break;
case '\n':
ret.push_back("\n");
break;
case '`':
ret.push_back("`");
break;
case '@':
ret.push_back("@");
break;
case '$':
ret.push_back("$");
break;
case '\\':
ret.push_back("\\");
break;
case '\'':
if(source[i] == '\'') {
i++;
string ident = "'";
while(source[i] != '\'' && source[i] != '\n' && i < source.length()) {
if(source[i] == '\\' && source[i + 1] == '\\') {
ident += string(1, source[i]);
i++;
}
else if(source[i] == '\\' && source[i + 1] == '\'') {
ident += string(1,source[i]);
i++;
}
ident += string(1,source[i]);
i++;
}
if(source[i] == '\'')
ident += "\'";
ret.push_back(ident);
}
break;
case '\"':
if(source[i] == '\"') {
i++;
string ident = "\"";
while(source[i] != '\"' && source[i] != '\n' && i < source.length()) {
if(source[i] == '\\' && source[i + 1] == '\\') {
ident += string(1, source[i]);
i++;
}
else if(source[i] == '\\' && source[i + 1] == '\"') {
ident += string(1,source[i]);
i++;
}
ident += string(1,source[i]);
i++;
}
if(source[i] == '\"')
ident += "\"";
ret.push_back(ident);
}
break;
case '+':
if(source[i + 1] == '=') {
ret.push_back("+=");
i++;
}
else if(source[i + 1] == '+') {
ret.push_back("++");
i++;
}
else
ret.push_back("+");
break;
case '-':
if(source[i + 1] == '=') {
ret.push_back("-=");
i++;
}
else if(source[i + 1] == '-') {
ret.push_back("--");
i++;
}
else if(source[i + 1] == '>') {
ret.push_back("->");
i++;
}
else
ret.push_back("-");
break;
case '*':
if(source[i + 1] == '=') {
ret.push_back("*=");
i++;
}
else
ret.push_back("*");
break;
case '/':
if(source[i + 1] == '/') {
while(source[i] != '\n' && i != source.length())
i++;
i--;
}
else if(source[i + 1] == '*') {
i += 2;
int ncounter = 0;
while(source.substr(i,2) != "*/" && i != source.length()) {
if(source[i] == '\n')
ncounter++;
i++;
}
for(int i = 0; i < ncounter; i++)
ret.push_back("\n");
i++;
}
else if(source[i + 1] == '=') {
ret.push_back("/=");
i++;
}
else
ret.push_back("/");
break;
case '%':
if(source[i + 1] == '=') {
ret.push_back("%=");
i++;
}
else
ret.push_back("%");
break;
case '^':
if(source[i + 1] == '=') {
ret.push_back("^=");
i++;
}
else
ret.push_back("^");
break;
case '|':
if(source[i + 1] == '=') {
ret.push_back("|=");
i++;
}
else if(source[i + 1] == '|') {
ret.push_back("||");
i++;
}
else
ret.push_back("|");
break;
case '&':
if(source[i + 1] == '=') {
ret.push_back("&=");
i++;
}
else if(source[i + 1] == '&') {
ret.push_back("&&");
i++;
}
else
ret.push_back("&");
break;
case '=':
if(source[i + 1] == '=') {
ret.push_back("==");
i++;
}
else
ret.push_back("=");
break;
case '!':
if(source[i + 1] == '=') {
ret.push_back("!=");
i++;
}
else
ret.push_back("!");
break;
case '>':
if(source[i + 1] == '>') {
if(source[i + 2] == '=') {
ret.push_back(">>=");
i += 2;
}
else {
ret.push_back(">>");
i++;
}
}
else if(source[i + 1] == '=') {
ret.push_back(">=");
i++;
}
else
ret.push_back(">");
break;
case '<':
if(source[i + 1] == '<') {
if(source[i + 1] == '<') {
if(source[i + 2] == '=') {
ret.push_back("<<=");
i += 2;
}
else {
ret.push_back("<<");
break;
}
}
}
else if(source[i + 1] == '=') {
ret.push_back("<=");
i++;
}
else if(i != 0 && ret[ret.size() - 1] == _hinclude) {
ret.push_back("<");
i++;
string ident;
while(source[i] != '>' && source[i] != '\n') {
ident.insert(ident.length(),string(1,source[i]));
i++;
}
ret.push_back(ident);
i--;
}
else
ret.push_back("<");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
//hexadecimal number
if(source[i] == '0' &&(source[i + 1] == 'x' || source[i + 1] == 'X')) {
string ident;
i += 2;
string atf = "abcdefABCDEF";
while(isdigit(source[i]) ||(int) atf.find(source[i]) > 0) {
ident.insert(ident.length(),string(1,source[i]));
i++;
}
std::stringstream ss;
ss << std::hex << ident;
int r;
ss >> r;
ret.push_back(itos(r));
i--;
}
else {
string ident;
bool encountered = false;
while(source[i] == '.' || source[i] == 'p' || source[i] == 'P' || source[i] == 'e' || source[i] == 'E' || isdigit(source[i]) || source.substr(i, 3) == "ull"
|| source.substr(i, 2) == "LL" || source.substr(i, 2) == "ll" ||(int) _suffixes.find(source[i]) >= 0) {
if(source.substr(i, 3) == "ull" || source.substr(i, 2) == "ll" || source.substr(i, 3) == "LL" ||(int) _suffixes.find(source[i]) >= 0) {
if(source.substr(i, 3) == "ull") {
ident.insert(ident.length(), " ull");
i += 3;
}
else if(source.substr(i, 2) == "LL" || source.substr(i, 2) == "ll") {
ident.insert(ident.length(), " " + source.substr(i, 2));
i += 2;
}
else {
ident.insert(ident.length(), " " + source.substr(i, 1));
i++;
}
break;
}
else if(string(1,source[i]) == _p || string(1,source[i]) == _P || string(1,source[i]) == _e || string(1,source[i]) == _E) {
if(!encountered) encountered = true;
else break;
if(string(1,source[i + 1]) == _plus || string(1,source[i + 1]) == _minus) {
ident.insert(ident.length(),string(1,source[i]) + string(1,source[i + 1]));
i++;
}
else
ident.insert(ident.length(),string(1,source[i]));
}
else
ident.insert(ident.length(),string(1,source[i]));
i++;
}
ret.push_back(ident);
i--;
}
break;
case '.':
if(source[i + 1] == '.' && source[i + 2] == '.') {
ret.push_back("...");
i += 2;
}
else if(isdigit(source[i + 1])) {
i++;
string ident;
bool encountered = false;
while(source[i] == 'p' || source[i] == 'P' || source[i] == 'e' || source[i] == 'E' || isdigit(source[i]) || source.substr(i, 3) == "ull"
|| source.substr(i, 2) == "LL" || source.substr(i, 2) == "ll" ||(int) _suffixes.find(source[i]) >= 0) {
if(source.substr(i, 3) == "ull" || source.substr(i, 2) == "ll" || source.substr(i, 3) == "LL" ||(int) _suffixes.find(source[i]) >= 0) {
if(source.substr(i, 3) == "ull") {
ident.insert(ident.length(), " ull");
i += 3;
}
else if(source.substr(i, 2) == "LL" || source.substr(i, 2) == "ll") {
ident.insert(ident.length(), " " + source.substr(i, 2));
i += 2;
}
else {
ident.insert(ident.length(), " " + source.substr(i, 1));
i++;
}
break;
}
else if(string(1, source[i]) == _p || string(1, source[i]) == _P || string(1, source[i]) == _e || string(1, source[i]) == _E) {
if(!encountered) encountered = true;
else break;
if(string(1, source[i + 1]) == _plus || string(1, source[i + 1]) == _minus) {
ident.insert(ident.length(), string(1, source[i]) + string(1, source[i + 1]));
i++;
}
else
ident.insert(ident.length(), string(1, source[i]));
}
else
ident.insert(ident.length(), string(1, source[i]));
i++;
}
ret.push_back(itos(0) + _dot + ident);
i--;
}
else
ret.push_back(".");
break;
case '#':
if(source[i + 1] == '#') {
ret.push_back("##");
i++;
}
else {
if(source.substr(i,_hdefine.length()) == _hdefine &&(source[i + _hdefine.length()] != '_' && !isalnum(source[i + _hdefine.length()]))) {
ret.push_back(_hdefine);
i += _hdefine.length() - 1;
}
else if(source.substr(i, _hwarning.length()) == _hwarning &&(source[i + _hwarning.length()] != '_' && !isalnum(source[i + _hwarning.length()]))) {
ret.push_back(_hwarning);
i += _hwarning.length() - 1;
}
else if(source.substr(i,_hif.length()) == _hif &&(source[i + _hif.length()] != '_' && !isalnum(source[i + _hif.length()]))) {
ret.push_back(_hif);
i += _hif.length() - 1;
}
else if(source.substr(i,_helif.length()) == _helif &&(source[i + _helif.length()] != '_' && !isalnum(source[i + _helif.length()]))) {
ret.push_back(_helif);
i += _helif.length() - 1;
}
else if(source.substr(i,_hifdef.length()) == _hifdef &&(source[i + _hifdef.length()] != '_' && !isalnum(source[i + _hifdef.length()]))) {
ret.push_back(_hifdef);
i += _hifdef.length() - 1;
}
else if(source.substr(i,_hifndef.length()) == _hifndef &&(source[i + _hifndef.length()] != '_' && !isalnum(source[i + _hifndef.length()]))) {
ret.push_back(_hifndef);
i += _hifndef.length() - 1;
}
else if(source.substr(i,_helse.length()) == _helse &&(source[i + _helse.length()] != '_' && !isalnum(source[i + _helse.length()]))) {
ret.push_back(_helse);
i += _helse.length() - 1;
}
else if(source.substr(i,_hendif.length()) == _hendif &&(source[i + _hendif.length()] != '_' && !isalnum(source[i + _hendif.length()]))) {
ret.push_back(_hendif);
i += _hendif.length() - 1;
}
else if(source.substr(i,_hpragma.length()) == _hpragma &&(source[i + _hpragma.length()] != '_' && !isalnum(source[i + _hpragma.length()]))) {
ret.push_back(_hpragma);
i += _hpragma.length() - 1;
}
else if(source.substr(i,_hline.length()) == _hline &&(source[i + _hline.length()] != '_' && !isalnum(source[i + _hline.length()]))) {
ret.push_back(_hline);
i += _hline.length() - 1;
}
else if(source.substr(i,_hinclude.length()) == _hinclude &&(source[i + _hinclude.length()] != '_' && !isalnum(source[i + _hinclude.length()]))) {
ret.push_back(_hinclude);
i += _hinclude.length() - 1;
}
//else if(source.substr(i,_himport.length()) == _himport &&(source[i + _himport.length()] != '_' && !isalnum(source[i + _himport.length()]))) {
//ret.push_back(_himport);
//i += _himport.length() - 1;
//}
//else if(source.substr(i,_husing.length()) == _husing &&(source[i + _husing.length()] != '_' && !isalnum(source[i + _husing.length()]))) {
//ret.push_back(_husing);
//i += _husing.length() - 1;
//}
else if(source.substr(i,_herror.length()) == _herror &&(source[i + _herror.length()] != '_' && !isalnum(source[i + _herror.length()]))) {
ret.push_back(_herror);
i += _herror.length() - 1;
}
else if(source.substr(i,_hundef.length()) == _hundef &&(source[i + _hundef.length()] != '_' && !isalnum(source[i + _hundef.length()]))) {
ret.push_back(_hundef);
i += _hundef.length() - 1;
}
else {
ret.push_back(_hash);
i += _hash.length() - 1;
}
}
break;
case ' ':
break;
case '\t':
break;
default:
//for wide characters
if(source[i] == 'L' && source[i + 1] == '\'') {
i += 2;
string ident = "\'";
while(source[i] != '\'' && source[i] != '\n' && i != source.length()) {
if(source[i] == '\\' && source[i + 1] == '\\') {
ident += string(1, source[i]);
i++;
}
else if(source[i] == '\\' && source[i + 1] == '\'') {
ident += string(1,source[i]);
i++;
}
ident += string(1,source[i]);
i++;
}
if(source[i] == '\'')
ident += "\'";
ret.push_back("@wchar_t " + ident);
}
else if(source[i] == 'L' && source[i + 1] == '\"') {
i += 2;
string ident = "\"";
while(source[i] != '\"' && source[i] != '\n' && i != source.length()) {
if(source[i] == '\\' && source[i + 1] == '\\') {
ident += string(1, source[i]);
i++;
}
else if(source[i] == '\\' && source[i + 1] == '\"') {
ident += string(1,source[i]);
i++;
}
ident += string(1,source[i]);
i++;
}
if(source[i] == '\"')
ident += "\"";
ret.push_back("@wchar_t*"+ ident);
}
string ident;
while((source[i] == '_' || isalnum(source[i])) && i != source.length()) {
ident.insert(ident.length(),string(1,source[i]));
i++;
}
trim(ident);
if(ident.length() != 0) {
ret.push_back(ident);
i--;
}
else {}
break;
}
}
vector<token> tret;
for(int i = 0; i < ret.size(); i++) {
tret.push_back(token(ret[i]));
}
return tret;
}
}
}
| true |
d9f48651d2a200428a89fda8a2bcfc77aaf9171f | C++ | Bulkas456/BOTS | /BOTS/BotsEngine.Tests/DamageManipulatorTests.cpp | UTF-8 | 4,488 | 3 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
#include "../BotsEngine.Damage/DamageManipulator.h"
#include "../BotsEngine.Damage/DamageManipulatorMethods.h"
#include "../BotsEngine.Damage/DamageType.h"
#include "../BotsEngine.Damage/DamageData.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace BotsEngine::Damage;
using namespace BotsEngine::Damage::DamageType;
using namespace BotsEngine::Damage::Manipulator;
using namespace BotsEngine::Tests;
namespace BotsEngineTests
{
TEST_CLASS(DamageManipulatorTests)
{
public:
TEST_METHOD(WhenManipulateWithIntManipulatorWithPositiveValue_ShouldManipulateProperly)
{
// Arrange
IntValueDamageManipulator valueManipulator(ConstantValueDamageManipulatorMethod, 5);
DamageManipulator manipulator([](const IDamageType&) -> bool { return true; }, valueManipulator);
Damage min(10);
Damage max(12);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator.Manipulate(actual);
// Assert
Assert::AreEqual(15u, actual.Min.GetValue());
Assert::AreEqual(17u, actual.Max.GetValue());
}
TEST_METHOD(WhenManipulateWithIntManipulatorWithNegativeValue_ShouldManipulateProperly)
{
// Arrange
IntValueDamageManipulator valueManipulator(ConstantValueDamageManipulatorMethod, -5);
DamageManipulator manipulator([](const IDamageType&) -> bool { return true; }, valueManipulator);
Damage min(10);
Damage max(12);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator.Manipulate(actual);
// Assert
Assert::AreEqual(5u, actual.Min.GetValue());
Assert::AreEqual(7u, actual.Max.GetValue());
}
TEST_METHOD(WhenManipulateWithIntPercentManipulatorWithPositiveValue_ShouldManipulateProperly)
{
// Arrange
IntValueDamageManipulator valueManipulator(PercentValueDamageManipulatorMethod, 50);
DamageManipulator manipulator([](const IDamageType&) -> bool { return true; }, valueManipulator);
Damage min(10);
Damage max(20);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator.Manipulate(actual);
// Assert
Assert::AreEqual(15u, actual.Min.GetValue());
Assert::AreEqual(30u, actual.Max.GetValue());
}
TEST_METHOD(WhenManipulateWithIntPercentManipulatorWithPositiveValue_ShouldManipulateProperly2)
{
// Arrange
IntValueDamageManipulator valueManipulator(PercentValueDamageManipulatorMethod, 22);
DamageManipulator manipulator([](const IDamageType&) -> bool { return true; }, valueManipulator);
Damage min(15);
Damage max(22);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator.Manipulate(actual);
// Assert
Assert::AreEqual(18u, actual.Min.GetValue());
Assert::AreEqual(27u, actual.Max.GetValue());
}
TEST_METHOD(WhenManipulateWithIntPercentManipulatorWithNegativeValue_ShouldManipulateProperly2)
{
// Arrange
IntValueDamageManipulator valueManipulator(PercentValueDamageManipulatorMethod, -23);
DamageManipulator manipulator([](const IDamageType&) -> bool { return true; }, valueManipulator);
Damage min(17);
Damage max(22);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator.Manipulate(actual);
// Assert
Assert::AreEqual(13u, actual.Min.GetValue());
Assert::AreEqual(17u, actual.Max.GetValue());
}
TEST_METHOD(WhenManipulateMoreThanOnce_ShouldManipulateProperly)
{
// Arrange
IntValueDamageManipulator valueManipulator1(PercentValueDamageManipulatorMethod, -23);
DamageManipulator manipulator1([](const IDamageType&) -> bool { return true; }, valueManipulator1);
IntValueDamageManipulator valueManipulator2(ConstantValueDamageManipulatorMethod, 5);
DamageManipulator manipulator2([](const IDamageType&) -> bool { return true; }, valueManipulator2);
Damage min(170);
Damage max(220);
BotsEngine::Damage::DamageType::DamageType damageType("type");
DamageData actual{ min, max, damageType };
// Act
manipulator1.Manipulate(actual);
manipulator2.Manipulate(actual);
// Assert
Assert::AreEqual(136u, actual.Min.GetValue());
Assert::AreEqual(174u, actual.Max.GetValue());
}
};
} | true |
5323e0570d6863cd957365b35abf6d8ef72219cc | C++ | BilalAli181999/OOP-IN-C_Plus_Plus | /oop Mid term last question/oop Mid term last question/Header1.h | UTF-8 | 455 | 2.875 | 3 | [] | no_license | #ifndef HEADER1_H
#define HEADER1_H
#include<iostream>
#include"header.h"
using namespace std;
class A
{
int a;
public:
A(int i=0)
{
cout << "\n para cons of A";
}
A(A & ref)
{
cout << "A::A(A& ref)";
}
void operator=(A& ref)
{
cout << "A::operator =(A& ref)";
}
A(B & ref)
{
cout << "A::A(B& ref)";
}
void operator=(B& ref)
{
cout << "A::operator =(B& ref)";
}
/*operator B()
{
cout << "operator A::B()";
}*/
};
#endif | true |
141155b1e37151cce1a73fce4e045f790073c82a | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/46/2270.c | UTF-8 | 881 | 2.875 | 3 | [] | no_license | void main()
{
int a[105][105];
int flag=1,loci=0,locj=0,row,col,upwall=0,downwall,rightwall,leftwall=-1,i,j;
scanf("%d %d",&row,&col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
rightwall=col;
downwall=row;
for(i=1;i<row*col;){
if(locj+1<rightwall&&flag==1){printf("%d\n",a[loci][locj++]);i++;}
else if(locj-1>leftwall&&flag==2){printf("%d\n",a[loci][locj--]);i++;}
else if(loci+1<downwall&&flag==3){printf("%d\n",a[loci++][locj]);i++;}
else if(loci-1>upwall&&flag==4){printf("%d\n",a[loci--][locj]);i++;}
else if(locj+1==rightwall&&flag==1){
rightwall--;
flag=3;
}
else if(locj-1==leftwall&&flag==2){
leftwall++;
flag=4;
}
else if(loci+1==downwall&&flag==3){
downwall--;
flag=2;
}
else if(loci-1==upwall&&flag==4){
upwall++;
flag=1;
}
}
printf("%d\n",a[loci][locj]);
} | true |
735785f35c030a6c99d5b5af3e7bd25f8e0f5f17 | C++ | taylor0000/Client-Database-System-PP3 | /Client.cpp | UTF-8 | 907 | 2.65625 | 3 | [] | no_license | /************************************************************************
Programming Project #3 -- Team Project for C++ Client Database System Exp
ArbitraryForClientsAndRepsansion
// Client Database Project.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
//TODO: Saving to text file functions will be implimented last
*********************************************************************************/
#include "Client.h"
Client::Client() {
}
Client::Client(string fullName, string address) {
this->name = fullName;
this->address = address;
}
Client::Client(string fullName, string address, int totalSales) {
this->name = fullName;
this->address = address;
this->totalSales = totalSales;
}
void Client::PrintInfo() {
cout << "Name: " << name << endl;
cout << "Address: " << address << endl;
cout << "Total Sales: " << totalSales << endl << endl;
}
| true |
cbe79b8c1633ffcacccefcad0f796e088658796c | C++ | zackliscio/topicmapping | /Sources/TopicMapping/optimize_alpha.cpp | UTF-8 | 950 | 2.65625 | 3 | [] | no_license |
# include "../standard_package/standard_include.cpp"
#include "lda_util.cpp"
#include "alpha_optimization.cpp"
int main(int argc, char * argv[]) {
if(argc<2) {
cout<<argv[0]<<" [gamma_file]"<<endl;
cout<<"computes alphas and writes to file:: ";
cout<<"alphas.txt"<<endl;
return -1;
}
string gins;
ifstream gin(argv[1]);
general_assert(gin.is_open(), "gamma_file not found!");
deque<DD> gammas;
int size=-1;
while(getline(gin, gins)) {
DD vs;
cast_string_to_doubles(gins, vs);
general_assert(size==-1 or int(vs.size())==size, \
"ERROR: gammas should all have same length");
size=vs.size();
gammas.push_back(vs);
}
gin.close();
DD alphas;
optimize_alpha(gammas, alphas);
ofstream pout("alphas.txt");
prints(alphas, pout);
pout.close();
return 0;
} | true |
422968a213213a509ad39ac21e88795c0bc60188 | C++ | MathisLeclair/piscine-cpp | /d04/ex00/Peon.hpp | UTF-8 | 367 | 2.59375 | 3 | [] | no_license | #ifndef PEON_HPP
# define PEON_HPP
# include <string>
# include <iostream>
# include "Victim.hpp"
class Peon: public Victim{
public:
Peon(std::string name);
Peon(Peon & src);
~Peon();
Peon & operator=(Peon & src);
virtual void getPolymorphed() const;
private:
Peon();
};
std::ostream & operator<<(std::ostream & o , Peon & s);
#endif
| true |
f7123d39e8f1693c37fcc6e402c1ef13049dfa5f | C++ | mathieuwang/myproject | /myproject/leetcode_11_maxarea/leetcode_11_maxarea/maxarea.cpp | UTF-8 | 828 | 3.078125 | 3 | [] | no_license | //
// maxarea.cpp
// leetcode_11_maxarea
//
// Created by mathieuwang on 15/9/2.
// Copyright (c) 2015年 mathieuwang. All rights reserved.
//
#include <stdio.h>
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int hsize = (int) height.size();
int ret = 0;
int i = 0;
int j = hsize - 1;
while (i < j) {
bool hjisbigger = false;
if (height[i] < height[j]) hjisbigger = true;
int area = (hjisbigger ? height[i] : height[j]) * (j - i);
if (area > ret) {
ret = area;
}
if (hjisbigger) {
++ i;
}
else {
-- j;
}
}
return ret;
}
}; | true |
1aca1c9243dc193408e3925c060c0ea65952541a | C++ | zproksi/lanczos | /CommandQueue.h | UTF-8 | 1,801 | 2.953125 | 3 | [] | no_license | #pragma once
namespace DialogsSync
{
class Command
{
public:
enum cmdtype : uint32_t
{
cmdNothing = 0,
cmdClose = 1,
cmdScrollTo = 2,
cmdTotal = 3
};
Command(const cmdtype acmdtype) : _type(acmdtype) {}
cmdtype type()const noexcept { return _type; }
public:
Gdiplus::PointF _imageOrigin = { 0., 0. };// we are drawing the image from this point. So for image 10 on 10 we can draw 1 pixel from 9:9
private:
cmdtype _type = cmdNothing;
};
extern Command commands[Command::cmdTotal];
class CommandQueue
{
public:
Command* next() noexcept; ///@brief get next command to execute
void release() noexcept; ///@brief release command from queue
void add(Command* acmd); ///@brief add comand to execute
protected:
std::mutex _guard;
std::queue<Command*> _commands;
};
template <typename T>
class CommandSequence
{
CommandSequence& operator=(const CommandSequence&) = delete;
CommandSequence&& operator=(CommandSequence&&) = delete;
CommandSequence(const CommandSequence&) = delete;
CommandSequence(CommandSequence&&) = delete;
public:
typedef std::shared_ptr<T> TCommand;
CommandSequence() {}
bool next(TCommand& ret) noexcept ///@brief get next command to execute
{
std::lock_guard<std::mutex> guard(_guard);
if (!_commands.empty())
{
std::swap(ret, _commands.front());
_commands.pop();
return true;
}
ret.reset();
return false;
}
void add(TCommand&& acmd) ///@brief add comand to execute
{
std::lock_guard<std::mutex> guard(_guard);
_commands.emplace(acmd);
}
protected:
std::mutex _guard;
std::queue<TCommand> _commands;
};
} // namespace DialogsSync
| true |
7100d3868ba633d8e980a1b0b0d6d0800b1d09fd | C++ | rodolfomartinezc/fibonacci_iterativo1 | /Iterativo/fibonacciIterativo.cpp | UTF-8 | 1,418 | 3.90625 | 4 | [] | no_license | #include<iostream> //libreria de entradas y salidas
using namespace std;
unsigned int fibonacci(int n) { // funcion fibonacci nos regresa un valor no signado
if (n < 2) { // condicion de paro
return n;
}
unsigned int a = 1, b = 1, c; // se hace el metodo iterativo con variables locales
for (int i = 0; i < n - 2; ++i) { // cambiando su valor en cada iteracion
c = a + b; // avanazando progresivamente como auxiliares
b = a;
a = c;
}
return a; // regresamos a al termino de la iteracion
}
int main()
{
cout<<"\n -Fibonacci Iterativo- \n"; // Metodo a Evaluar
cout<<" Rodolfo Martinez y Brenda Ortega \n\n"; // Miembros de Equipo
unsigned int i, num ; // variables de apoyo, para limites de iteracion
do
{
cout<<"Ingrese un numero: "; // Se ingresa un valor
cin>>num; // Se registra en la variable num
} while(num < 0);
cout<<"\n Serie de Fibonacci: \n\t";
for(i=0; i<num; i++) // Se ejecuta la funcion
{
if(fibonacci(i) != 0) // si es diferente de cero se pone una coma para acomodar los datos
cout<< ", ";
cout<< fibonacci(i); // se imprime el valor que regresa la funcion
}
cout<<"\n";
return 0; // Fin del Programa
}
| true |
4e8a4081f2744e5d9f0a2d24785947a48f9d3780 | C++ | moevm/oop | /8383/averina/labs/Interface/Commands/SaveCommands/GameSaveRequest.cpp | UTF-8 | 695 | 2.796875 | 3 | [] | no_license | #include "GameSaveRequest.h"
void GameSaveRequest::Command()
{
std::cout << "------- GAME SAVE ------" << std::endl;
std::cout << "/save" << std::endl;
std::cout << "/load" << std::endl;
std::cout << "------------------------" << std::endl;
std::string input;
std::cout << "<command> : " ;
std::cin >> input;
if (input == "/save")
{
Snapshot* snapshot = field->createSnapshot("save");
snapshot->saveGame();
}
else if (input == "/load")
{
Snapshot* snapshot = field->createSnapshot("load");
field = snapshot->loadGame();
}
else
{
std::cout << "ERROR: wrong command of save" << std::endl;
}
} | true |
671846950aa6b9a565de62fe349f3677ae2e82cc | C++ | GoodGuySteve/SchoolProjects | /CS24/virtual_directory.cpp | UTF-8 | 4,940 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "bst.h"
#include "directory.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
/* Change `cwd` to point to either its parent (..) or one of its
subdirectories.
If `name` is `..` change into the parent directory. Attempting to change to
the parent directory of the root should produce the "Invalid directory:
<NAME>" error message.
Otherwise `cwd` should only be updated if `cwd` has a subdirectory with the
name `name`. Otherwise the message "Invalid directory: <NAME>" sh`ould be
output where `<NAME>` is replaced by the `name` variable.
Note: `cwd` is a reference to a pointer so that when you reassign `cwd` that
change occurs for the cwd of the caller (main in this case).
*/
void change_directory(Directory *&cwd, string name) {
using namespace std;
if (name == ".."){
if (cwd->get_parent()== NULL){
cout << "Invalid directory: " << name << '\n';
return;
}
cwd = cwd->get_parent();
return;
}
Directory* foundit;
if ((foundit = cwd->get_subdirectory(name)) == NULL){
cout << "Invalid directory: " << name << endl;
return;
}
cwd = foundit;
// DOESN'T WORK BECAUSE SUBDIRS IS PRIVATE
// Directory* dir = new Directory(name);
//
// PtrWrapper<Directory*> foundit;
// PtrWrapper<Directory*> *pointy = new PtrWrapper<Directory*>(dir);
// try{
// foundit = cwd->subdirs.contains(*pointy);
// }
// catch(int e){
// if (e == 1){
// cout << "Invalid directory: " << name;
// delete pointy;
// delete dir;
// return;
// }
// }
// delete pointy;
// delete dir;
//
// cwd = foundit.ptr;
//
return;
// TODO: Implement this function
}
/* Attempt to create a directory with name `name` under the cwd.
The directory name `..` is reserved to mean the parent directory. If `name`
matches `..` output: "../ is a reserved directory name\n"
On failure (the directory already exists) output: "Directory already exists:
<NAME>" where `<NAME>` is replaced by the `name` variable.
*/
void make_directory(Directory *cwd, string name) {
if (name == ".."){
std::cout << ".. is a reserved directory name\n";
return;
}
if (!cwd->add_subdirectory(name)){
std::cout << "Directory already exists: "<< name << std::endl;
return;
}
return;
// TODO: Implement this function
}
/* Output the complete path to the present working directory.
From the root the output should only be "/\n".
From a directory foo with parent bar whose parent is the root the output
should be "/bar/foo\n".
Hint: You might want to use one of the data structures to help produce the
output in the correct order.
*/
void output_pwd(Directory *cwd) {
using namespace std;
Directory * dir = cwd;
Stack<Directory *> silver;
silver.push(cwd);
while ((dir->get_parent()) != NULL){
silver.push(dir->get_parent());
dir = dir->get_parent();
}
while (!(silver.is_empty())){
dir = silver.pop();
cout << '/' << dir->get_name();
}
cout << endl;
// TODO: Implement this function
}
/* Attempt to remove a subdirectory of `cwd` matching `name`.
If the directory does not exist output: "Invalid directory: <NAME>\n"
*/
void remove_directory(Directory *cwd, string name) {
using namespace std;
// PtrWrapper<Directory *> to_delete; remove subdir returns bool. don't need this atm
// try {
// to_delete = cwd->get_subdirectory(name);
// }
// catch(int e){
// cout << "Invalid directory: " << name << endl;
// return;
// }
//
// make sure to replace get_subdirectory
if(!cwd->remove_subdirectory(name)){
cout << "Invalid directory: " << name << endl;
return;
}
//delete to_delete.ptr;
// TODO: Implement this function
}
/* The main program simply prompts the user for commands until the input stream
is closed (ctrl+d or EOF).
You need not change anything in main. However, you are more than welcome to
add additional commands for fun and possibly extra credit.
*/
int main() {
Directory root("");
Directory *cwd = &root;
string command;
while (cin) {
cout << cwd->get_name() << "> ";
getline(cin, command);
if (command == "help") {
cout << "Commands: cd NAME, mkdir NAME, ls, pwd, rmdir NAME\n";
}
else if (command.substr(0, 3) == "cd ") {
change_directory(cwd, command.substr(3, command.size()));
}
else if (command == "ls") {
cwd->list_directory();
}
else if (command.substr(0, 6) == "mkdir ") {
make_directory(cwd, command.substr(6, command.size()));
}
else if (command == "pwd") {
output_pwd(cwd);
}
else if (command.substr(0, 6) == "rmdir ") {
remove_directory(cwd, command.substr(6, command.size()));
}
else if (command == "");
else {
cout << "Invalid command. Type help for the list of commands.\n";
}
}
return 0;
}
| true |
2d8ad1161b0e42320d04741c68b7eef5b340aad4 | C++ | parvezaalam786/Placement-Preparation | /Strings/Z Algorithm.cpp | UTF-8 | 790 | 2.84375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
/*
Z Algorithm: It is string matching algorithm
Time Complexity = O(string.length() + pattern.length())
string = ababaa , pattern = aba
step1: string tot = pattern + "$" + string
=> tot = aba$ababaa
step2: 0 1 2 3 4 5 6 7 8 9
tot = a b a $ a b a b a a
i j tot[i] = tot[j] i++,j++
i j tot[i] = tot[j] i++,j++
i j tot[i] = tot[j] i++,j++
i j tot[i] != tot[j] i++,j++ after encountering $
Z[] = 0 0 1 0 3 0 3 0 1 1
0 1 2 3 4 5 6 7 8 9
Indicies at which pattern is found
4-3-1 = 0
6-3-1 = 2 we find that a match has occured
*/
void solve()
{
}
signed main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
solve();
return 0;
}
| true |
4887c61513448c378b5496a7df38a37f0b69cefc | C++ | jeffsetter/Halide_CoreIR | /apps/coreir_examples/camera_pipe/pipeline.cpp | UTF-8 | 24,362 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "Halide.h"
#include <stdint.h>
using namespace Halide;
Var x("x"), y("y"), tx("tx"), ty("ty"), c("c"), xi("xi"), yi("yi"), z("z");
Var xo("xo"), yo("yo");
Var x_grid("x_grid"), y_grid("y_grid"), x_in("x_in"), y_in("y_in");
// Average two positive values rounding up
Expr avg(Expr a, Expr b) {
Type wider = a.type().with_bits(a.type().bits() * 2);
return cast(a.type(), (cast(wider, a) + b + 1)/2);
}
Func hot_pixel_suppression(Func input) {
Expr a = max(max(input(x-2, y), input(x+2, y)),
max(input(x, y-2), input(x, y+2)));
Expr b = min(min(input(x-2, y), input(x+2, y)),
min(input(x, y-2), input(x, y+2)));
Func denoised("denoised");
denoised(x, y) = clamp(input(x, y), b, a);
return denoised;
}
class MyPipeline {
int schedule;
ImageParam input;
std::vector<Argument> args;
Func shifted;
Func processed;
Func denoised;
Func deinterleaved;
Func demosaiced;
Func corrected;
Func hw_output;
Func curve;
Func interleave_x(Func a, Func b) {
Func out;
out(x, y) = select((x%2)==0, a(x/2, y), b(x/2, y));
return out;
}
Func interleave_y(Func a, Func b) {
Func out;
out(x, y) = select((y%2)==0, a(x, y/2), b(x, y/2));
return out;
}
Func deinterleave(Func raw) {
// Deinterleave the color channels
Func deinterleaved("deinterleaved");
deinterleaved(x, y, c) = select(c == 0, raw(2*x, 2*y),
select(c == 1, raw(2*x+1, 2*y),
select(c == 2, raw(2*x, 2*y+1),
raw(2*x+1, 2*y+1))));
return deinterleaved;
}
Func demosaic(Func deinterleaved) {
// These are the values we already know from the input
// x_y = the value of channel x at a site in the input of channel y
// gb refers to green sites in the blue rows
// gr refers to green sites in the red rows
// Give more convenient names to the four channels we know
Func r_r, g_gr, g_gb, b_b;
g_gr(x, y) = deinterleaved(x, y, 0);
r_r(x, y) = deinterleaved(x, y, 1);
b_b(x, y) = deinterleaved(x, y, 2);
g_gb(x, y) = deinterleaved(x, y, 3);
// These are the ones we need to interpolate
Func b_r, g_r, b_gr, r_gr, b_gb, r_gb, r_b, g_b;
// First calculate green at the red and blue sites
// Try interpolating vertically and horizontally. Also compute
// differences vertically and horizontally. Use interpolation in
// whichever direction had the smallest difference.
Expr gv_r = avg(g_gb(x, y-1), g_gb(x, y));
Expr gvd_r = absd(g_gb(x, y-1), g_gb(x, y));
Expr gh_r = avg(g_gr(x+1, y), g_gr(x, y));
Expr ghd_r = absd(g_gr(x+1, y), g_gr(x, y));
g_r(x, y) = select(ghd_r < gvd_r, gh_r, gv_r);
Expr gv_b = avg(g_gr(x, y+1), g_gr(x, y));
Expr gvd_b = absd(g_gr(x, y+1), g_gr(x, y));
Expr gh_b = avg(g_gb(x-1, y), g_gb(x, y));
Expr ghd_b = absd(g_gb(x-1, y), g_gb(x, y));
g_b(x, y) = select(ghd_b < gvd_b, gh_b, gv_b);
// Next interpolate red at gr by first interpolating, then
// correcting using the error green would have had if we had
// interpolated it in the same way (i.e. add the second derivative
// of the green channel at the same place).
Expr correction;
correction = g_gr(x, y) - avg(g_r(x, y), g_r(x-1, y));
r_gr(x, y) = correction + avg(r_r(x-1, y), r_r(x, y));
// Do the same for other reds and blues at green sites
correction = g_gr(x, y) - avg(g_b(x, y), g_b(x, y-1));
b_gr(x, y) = correction + avg(b_b(x, y), b_b(x, y-1));
correction = g_gb(x, y) - avg(g_r(x, y), g_r(x, y+1));
r_gb(x, y) = correction + avg(r_r(x, y), r_r(x, y+1));
correction = g_gb(x, y) - avg(g_b(x, y), g_b(x+1, y));
b_gb(x, y) = correction + avg(b_b(x, y), b_b(x+1, y));
// Now interpolate diagonally to get red at blue and blue at
// red. Hold onto your hats; this gets really fancy. We do the
// same thing as for interpolating green where we try both
// directions (in this case the positive and negative diagonals),
// and use the one with the lowest absolute difference. But we
// also use the same trick as interpolating red and blue at green
// sites - we correct our interpolations using the second
// derivative of green at the same sites.
correction = g_b(x, y) - avg(g_r(x, y), g_r(x-1, y+1));
Expr rp_b = correction + avg(r_r(x, y), r_r(x-1, y+1));
Expr rpd_b = absd(r_r(x, y), r_r(x-1, y+1));
correction = g_b(x, y) - avg(g_r(x-1, y), g_r(x, y+1));
Expr rn_b = correction + avg(r_r(x-1, y), r_r(x, y+1));
Expr rnd_b = absd(r_r(x-1, y), r_r(x, y+1));
r_b(x, y) = select(rpd_b < rnd_b, rp_b, rn_b);
// Same thing for blue at red
correction = g_r(x, y) - avg(g_b(x, y), g_b(x+1, y-1));
Expr bp_r = correction + avg(b_b(x, y), b_b(x+1, y-1));
Expr bpd_r = absd(b_b(x, y), b_b(x+1, y-1));
correction = g_r(x, y) - avg(g_b(x+1, y), g_b(x, y-1));
Expr bn_r = correction + avg(b_b(x+1, y), b_b(x, y-1));
Expr bnd_r = absd(b_b(x+1, y), b_b(x, y-1));
b_r(x, y) = select(bpd_r < bnd_r, bp_r, bn_r);
// Interleave the resulting channels
Func r = interleave_y(interleave_x(r_gr, r_r),
interleave_x(r_b, r_gb));
Func g = interleave_y(interleave_x(g_gr, g_r),
interleave_x(g_b, g_gb));
Func b = interleave_y(interleave_x(b_gr, b_r),
interleave_x(b_b, b_gb));
Func output("demosaiced");
output(x, y, c) = select(c == 0, r(x, y),
c == 1, g(x, y),
b(x, y));
/* THE SCHEDULE */
if (schedule == 1) {
// optimized for ARM
// Compute these in chunks over tiles, vectorized by 8
g_r.compute_at(processed, tx).vectorize(x, 8);
g_b.compute_at(processed, tx).vectorize(x, 8);
r_gr.compute_at(processed, tx).vectorize(x, 8);
b_gr.compute_at(processed, tx).vectorize(x, 8);
r_gb.compute_at(processed, tx).vectorize(x, 8);
b_gb.compute_at(processed, tx).vectorize(x, 8);
r_b.compute_at(processed, tx).vectorize(x, 8);
b_r.compute_at(processed, tx).vectorize(x, 8);
// These interleave in y, so unrolling them in y helps
output.compute_at(processed, tx)
.vectorize(x, 8)
.unroll(y, 2)
.reorder(c, x, y).bound(c, 0, 3).unroll(c);
} else if (schedule == 3) {
// CUDA
output.compute_root().unroll(y, 2).unroll(x, 2)
.reorder(c, x, y).bound(c, 0, 3).unroll(c)
.gpu_tile(x, y, 32, 16);;
} else {
// optimized for X86
// Don't vectorize, because sse is bad at 16-bit interleaving
g_r.compute_at(processed, tx);
g_b.compute_at(processed, tx);
r_gr.compute_at(processed, tx);
b_gr.compute_at(processed, tx);
r_gb.compute_at(processed, tx);
b_gb.compute_at(processed, tx);
r_b.compute_at(processed, tx);
b_r.compute_at(processed, tx);
// These interleave in x and y, so unrolling them helps
output.compute_at(processed, tx).unroll(x, 2).unroll(y, 2)
.reorder(c, x, y).bound(c, 0, 3).unroll(c);
}
return output;
}
Func color_correct(Func input, int32_t matrix[3][4]) {
Expr ir = cast<int32_t>(input(x, y, 0));
Expr ig = cast<int32_t>(input(x, y, 1));
Expr ib = cast<int32_t>(input(x, y, 2));
Expr r = matrix[0][3] + matrix[0][0] * ir + matrix[0][1] * ig + matrix[0][2] * ib;
Expr g = matrix[1][3] + matrix[1][0] * ir + matrix[1][1] * ig + matrix[1][2] * ib;
Expr b = matrix[2][3] + matrix[2][0] * ir + matrix[2][1] * ig + matrix[2][2] * ib;
r = cast<int16_t>(r/256);
g = cast<int16_t>(g/256);
b = cast<int16_t>(b/256);
corrected(x, y, c) = select(c == 0, r,
select(c == 1, g, b));
return corrected;
}
Func apply_curve(Func input, Type result_type, float gamma, float contrast) {
// copied from FCam
//Func curve("curve");
Expr xf = clamp(cast<float>(x)/1024.0f, 0.0f, 1.0f);
Expr g = pow(xf, 1.0f/gamma);
Expr b = 2.0f - (float) pow(2.0f, contrast/100.0f);
Expr a = 2.0f - 2.0f*b;
Expr z = select(g > 0.5f,
1.0f - (a*(1.0f-g)*(1.0f-g) + b*(1.0f-g)),
a*g*g + b*g);
Expr val = cast(result_type, clamp(z*256.0f, 0.0f, 255.0f));
curve(x) = val;
curve.compute_root(); // It's a LUT, compute it once ahead of time.
if (schedule == 3) {
// GPU schedule
curve.gpu_tile(x, 256);
}
Func hw_output("hw_output");
hw_output(x, y, c) = curve(input(x, y, c));
return hw_output;
}
public:
MyPipeline(int _schedule, int32_t matrix[3][4], float gamma, float contrast)
: schedule(_schedule), input(UInt(16), 2), curve("curve")
{
// Parameterized output type, because LLVM PTX (GPU) backend does not
// currently allow 8-bit computations
int bit_width = 8; //atoi(argv[1]);
Type result_type = UInt(bit_width);
// The camera pipe is specialized on the 2592x1968 images that
// come in, so we'll just use an image instead of a uniform image.
// shift things inwards to give us enough padding on the
// boundaries so that we don't need to check bounds. We're going
// to make a 2560x1920 output image, just like the FCam pipe, so
// shift by 16, 12
shifted(x, y) = input(x+16, y+12);
denoised = hot_pixel_suppression(shifted);
deinterleaved = deinterleave(denoised);
demosaiced = demosaic(deinterleaved);
corrected = color_correct(demosaiced, matrix);
hw_output = apply_curve(corrected, result_type, gamma, contrast);
processed(tx, ty, c) = hw_output(tx, ty, c);
// Schedule
// We can generate slightly better code if we know the output is a whole number of tiles.
Expr out_width = processed.output_buffer().width();
Expr out_height = processed.output_buffer().height();
processed
.bound(tx, 0, (out_width/128)*128)
.bound(ty, 0, (out_height/128)*128)
.bound(c, 0, 3); // bound color loop 0-3, properly
args = {input};
}
void compile_cpu() {
assert(schedule == 1);
std::cout << "\ncompiling cpu code..." << std::endl;
// Compute in chunks over tiles, vectorized by 8
denoised.compute_at(processed, tx).vectorize(x, 8);
deinterleaved.compute_at(processed, tx).vectorize(x, 8).reorder(c, x, y).unroll(c);
corrected.compute_at(processed, tx).vectorize(x, 4).reorder(c, x, y).unroll(c);
processed.tile(tx, ty, xi, yi, 32, 32).reorder(xi, yi, c, tx, ty);
processed.parallel(ty);
//processed.print_loop_nest();
processed.compile_to_lowered_stmt("pipeline_native.ir.html", args, HTML);
processed.compile_to_file("pipeline_native", args);
}
void compile_gpu() {
assert(schedule == 3);
std::cout << "\ncompiling gpu code..." << std::endl;
processed.gpu_tile(tx, ty, c, 32, 16, 1);
denoised.compute_root().gpu_tile(x, y, 32, 16);
/*
deinterleaved.compute_root()
.reorder(c, x, y).unroll(c)
.gpu_tile(x, y, 32, 16);
*/
//processed.print_loop_nest();
Target target = get_target_from_environment();
target.set_feature(Target::CUDA);
processed.compile_to_lowered_stmt("pipeline_cuda.ir.html", args, HTML, target);
processed.compile_to_header("pipeline_cuda.h", args, "pipeline_cuda", target);
processed.compile_to_object("pipeline_cuda.o", args, "pipeline_cuda", target);
}
};
class MyPipelineOpt {
int schedule;
ImageParam input;
std::vector<Argument> args;
Func shifted;
Func processed;
Func denoised;
Func deinterleaved;
Func demosaiced;
Func corrected;
Func hw_output;
Func curve;
Func interleave_x(Func a, Func b) {
Func out;
out(x, y) = select((x%2)==0, a(x, y), b(x-1, y));
return out;
}
Func interleave_y(Func a, Func b) {
Func out;
out(x, y) = select((y%2)==0, a(x, y), b(x, y-1));
return out;
}
// The demosaic algorithm is optimized for HLS schedule
// such that the bound analysis can derive a constant window
// and shift step without needed to unroll 'demosaic' into
// a 2x2 grid.
//
// The chances made from the original is that there is no
// explict downsample and upsample in 'deinterleave' and
// 'interleave', respectively.
// All the intermediate functions are the same size as the
// raw image although only pixels at even coordinates are used.
Func demosaic(Func raw) {
Func r_r, g_gr, g_gb, b_b;
g_gr(x, y) = raw(x, y);//deinterleaved(x, y, 0);
r_r(x, y) = raw(x+1, y);//deinterleaved(x, y, 1);
b_b(x, y) = raw(x, y+1);//deinterleaved(x, y, 2);
g_gb(x, y) = raw(x+1, y+1);//deinterleaved(x, y, 3);
// These are the ones we need to interpolate
Func b_r, g_r, b_gr, r_gr, b_gb, r_gb, r_b, g_b;
Expr gv_r = avg(g_gb(x, y-2), g_gb(x, y));
Expr gvd_r = absd(g_gb(x, y-2), g_gb(x, y));
Expr gh_r = avg(g_gr(x+2, y), g_gr(x, y));
Expr ghd_r = absd(g_gr(x+2, y), g_gr(x, y));
g_r(x, y) = select(ghd_r < gvd_r, gh_r, gv_r);
Expr gv_b = avg(g_gr(x, y+2), g_gr(x, y));
Expr gvd_b = absd(g_gr(x, y+2), g_gr(x, y));
Expr gh_b = avg(g_gb(x-2, y), g_gb(x, y));
Expr ghd_b = absd(g_gb(x-2, y), g_gb(x, y));
g_b(x, y) = select(ghd_b < gvd_b, gh_b, gv_b);
Expr correction;
correction = g_gr(x, y) - avg(g_r(x, y), g_r(x-2, y));
r_gr(x, y) = correction + avg(r_r(x-2, y), r_r(x, y));
// Do the same for other reds and blues at green sites
correction = g_gr(x, y) - avg(g_b(x, y), g_b(x, y-2));
b_gr(x, y) = correction + avg(b_b(x, y), b_b(x, y-2));
correction = g_gb(x, y) - avg(g_r(x, y), g_r(x, y+2));
r_gb(x, y) = correction + avg(r_r(x, y), r_r(x, y+2));
correction = g_gb(x, y) - avg(g_b(x, y), g_b(x+2, y));
b_gb(x, y) = correction + avg(b_b(x, y), b_b(x+2, y));
correction = g_b(x, y) - avg(g_r(x, y), g_r(x-2, y+2));
Expr rp_b = correction + avg(r_r(x, y), r_r(x-2, y+2));
Expr rpd_b = absd(r_r(x, y), r_r(x-2, y+2));
correction = g_b(x, y) - avg(g_r(x-2, y), g_r(x, y+2));
Expr rn_b = correction + avg(r_r(x-2, y), r_r(x, y+2));
Expr rnd_b = absd(r_r(x-2, y), r_r(x, y+2));
r_b(x, y) = select(rpd_b < rnd_b, rp_b, rn_b);
// Same thing for blue at red
correction = g_r(x, y) - avg(g_b(x, y), g_b(x+2, y-2));
Expr bp_r = correction + avg(b_b(x, y), b_b(x+2, y-2));
Expr bpd_r = absd(b_b(x, y), b_b(x+2, y-2));
correction = g_r(x, y) - avg(g_b(x+2, y), g_b(x, y-2));
Expr bn_r = correction + avg(b_b(x+2, y), b_b(x, y-2));
Expr bnd_r = absd(b_b(x+2, y), b_b(x, y-2));
b_r(x, y) = select(bpd_r < bnd_r, bp_r, bn_r);
// Interleave the resulting channels
Func r = interleave_y(interleave_x(r_gr, r_r),
interleave_x(r_b, r_gb));
Func g = interleave_y(interleave_x(g_gr, g_r),
interleave_x(g_b, g_gb));
Func b = interleave_y(interleave_x(b_gr, b_r),
interleave_x(b_b, b_gb));
Func output("demosaiced");
output(x, y, c) = select(c == 0, r(x, y),
c == 1, g(x, y),
b(x, y));
return output;
}
Func color_correct(Func input, int32_t matrix[3][4]) {
Expr ir = cast<int32_t>(input(x, y, 0));
Expr ig = cast<int32_t>(input(x, y, 1));
Expr ib = cast<int32_t>(input(x, y, 2));
Expr r = matrix[0][3] + matrix[0][0] * ir + matrix[0][1] * ig + matrix[0][2] * ib;
Expr g = matrix[1][3] + matrix[1][0] * ir + matrix[1][1] * ig + matrix[1][2] * ib;
Expr b = matrix[2][3] + matrix[2][0] * ir + matrix[2][1] * ig + matrix[2][2] * ib;
r = cast<int16_t>(r/256);
g = cast<int16_t>(g/256);
b = cast<int16_t>(b/256);
corrected(x, y, c) = select(c == 0, r,
select(c == 1, g, b));
return corrected;
}
Func apply_curve(Func input, float gamma, float contrast) {
// copied from FCam
//Expr xf = clamp(cast<float>(x)/1024.0f, 0.0f, 1.0f);
Expr xf = x/1024.0f;
Expr g = pow(xf, 1.0f/gamma);
Expr b = 2.0f - (float) pow(2.0f, contrast/100.0f);
Expr a = 2.0f - 2.0f*b;
Expr val = select(g > 0.5f,
1.0f - (a*(1.0f-g)*(1.0f-g) + b*(1.0f-g)),
a*g*g + b*g);
curve(x) = cast<uint8_t>(clamp(val*256.0f, 0.0f, 255.0f));
Func hw_output("hw_output");
Expr in_val = clamp(input(x, y, c), 0, 1023);
hw_output(c, x, y) = select(input(x, y, c) < 0, 0,
select(input(x, y, c) >= 1024, 255,
curve(in_val)));
return hw_output;
}
public:
MyPipelineOpt(int _schedule, int32_t matrix[3][4], float gamma, float contrast)
: schedule(_schedule), input(UInt(16), 2), curve("curve")
{
// The camera pipe is specialized on the 2592x1968 images that
// come in, so we'll just use an image instead of a uniform image.
// shift things inwards to give us enough padding on the
// boundaries so that we don't need to check bounds. We're going
// to make a 2560x1920 output image, just like the FCam pipe, so
// shift by 16, 12
shifted(x, y) = input(x+16, y+12);
denoised = hot_pixel_suppression(shifted);
//deinterleaved = deinterleave(denoised);
demosaiced = demosaic(denoised);
corrected = color_correct(demosaiced, matrix);
hw_output = apply_curve(corrected, gamma, contrast);
processed(x, y, c) = hw_output(c, x, y);
// Schedule
// We can generate slightly better code if we know the output is a whole number of tiles.
Expr out_width = processed.output_buffer().width();
Expr out_height = processed.output_buffer().height();
processed
.bound(x, 0, (out_width/640)*640)
.bound(y, 0, (out_height/480)*480)
.bound(c, 0, 3); // bound color loop 0-3, properly
args = {input};
}
void compile_hls() {
assert(schedule == 2);
std::cout << "\ncompiling HLS code..." << std::endl;
// Block in chunks over tiles
processed.tile(x, y, xo, yo, xi, yi, 640, 480)
.reorder(c, xi, yi, xo, yo);
shifted.compute_at(processed, xo);
hw_output.compute_at(processed, xo);
hw_output.tile(x, y, xo, yo, xi, yi, 640, 480)
.reorder(c, xi, yi, xo, yo);
hw_output.unroll(c).unroll(xi, 2); // 2 pix/cyc throughput
hw_output.accelerate({shifted}, xi, xo);
denoised.linebuffer()
.unroll(x).unroll(y);
demosaiced.linebuffer()
.unroll(c).unroll(x).unroll(y);
curve.compute_at(hw_output, xo).unroll(x); // synthesize curve to a ROM
//processed.print_loop_nest();
Target hls_target = get_target_from_environment();
hls_target.set_feature(Target::CPlusPlusMangling);
processed.compile_to_lowered_stmt("pipeline_hls.ir.html", args, HTML, hls_target);
processed.compile_to_hls("pipeline_hls.cpp", args, "pipeline_hls", hls_target);
processed.compile_to_header("pipeline_hls.h", args, "pipeline_hls", hls_target);
std::vector<Target::Feature> features({Target::Zynq});
Target target(Target::Linux, Target::ARM, 32, features);
processed.compile_to_zynq_c("pipeline_zynq.c", args, "pipeline_zynq", target);
processed.compile_to_header("pipeline_zynq.h", args, "pipeline_zynq", target);
shifted.vectorize(x, 8);
processed
.vectorize(xi, 16).unroll(c);
processed.fuse(xo, yo, xo).parallel(xo);
//shifted.set_stride(0, 3).set_stride(2, 1).set_bounds(2, 0, 3);
processed.compile_to_object("pipeline_zynq.o", args, "pipeline_zynq", target);
processed.compile_to_lowered_stmt("pipeline_zynq.ir.html", args, HTML, target);
processed.compile_to_assembly("pipeline_zynq.s", args, "pipeline_zynq", target);
}
void compile_coreir() {
assert(schedule == 4);
std::cout << "\ncompiling COREIR code..." << std::endl;
// Block in chunks over tiles
processed.tile(x, y, xo, yo, xi, yi, 640, 480)
.reorder(c, xi, yi, xo, yo);
shifted.compute_at(processed, xo);
hw_output.compute_at(processed, xo);
hw_output.tile(x, y, xo, yo, xi, yi, 640, 480)
.reorder(c, xi, yi, xo, yo);
hw_output.unroll(c).unroll(xi, 2); // 2 pix/cyc throughput
hw_output.accelerate({shifted}, xi, xo);
denoised.linebuffer()
.unroll(x).unroll(y);
demosaiced.linebuffer()
.unroll(c).unroll(x).unroll(y);
curve.compute_at(hw_output, xo).unroll(x); // synthesize curve to a ROM
//processed.print_loop_nest();
Target coreir_target = get_target_from_environment();
coreir_target.set_feature(Target::CPlusPlusMangling);
processed.compile_to_lowered_stmt("pipeline_coreir.ir.html", args, HTML, coreir_target);
processed.compile_to_coreir("pipeline_coreir.cpp", args, "pipeline_coreir", coreir_target);
processed.compile_to_header("pipeline_coreir.h", args, "pipeline_coreir", coreir_target);
}
};
int main(int argc, char **argv) {
if (argc < 4) {
printf("Usage: ./pipeline color_temp gamma contrast\n"
"e.g. ./pieline 3200 2 50");
return 0;
}
float color_temp = atof(argv[1]);
float gamma = atof(argv[2]);
float contrast = atof(argv[3]);
// These color matrices are for the sensor in the Nokia N900 and are
// taken from the FCam source.
float matrix_3200[][4] = {{ 1.6697f, -0.2693f, -0.4004f, -42.4346f},
{-0.3576f, 1.0615f, 1.5949f, -37.1158f},
{-0.2175f, -1.8751f, 6.9640f, -26.6970f}};
float matrix_7000[][4] = {{ 2.2997f, -0.4478f, 0.1706f, -39.0923f},
{-0.3826f, 1.5906f, -0.2080f, -25.4311f},
{-0.0888f, -0.7344f, 2.2832f, -20.0826f}};
// Get a color matrix by linearly interpolating between two
// calibrated matrices using inverse kelvin.
int32_t matrix[3][4];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 4; x++) {
float alpha = (1.0f/color_temp - 1.0f/3200) / (1.0f/7000 - 1.0f/3200);
float val = matrix_3200[y][x] * alpha + matrix_7000[y][x] * (1 - alpha);
matrix[y][x] = (int32_t)(val * 256.0f); // Q8.8 fixed point
}
}
MyPipeline p1(1, matrix, gamma, contrast);
p1.compile_cpu();
MyPipelineOpt p2(2, matrix, gamma, contrast);
p2.compile_hls();
MyPipelineOpt p3(4, matrix, gamma, contrast);
p3.compile_coreir();
return 0;
}
| true |
04983d9b887837f255abcb9718c04060f8dccdd3 | C++ | CodersCove/opengl | /c++ opengl/OB/Player.cpp | UTF-8 | 2,074 | 2.765625 | 3 | [] | no_license |
#include "Player.h"
#include "Game.h"
Player::Player(Game* game)
{
this->game = game;
}
void Player::HandleInput()
{
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_D ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->Right();
}
else
{
this->game->MoveLeft();
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_A ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->Left();
}
else
{
this->game->MoveRight();
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_W ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->Up();
}
else
{
this->game->MoveDown();
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_S ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->Down();
}
else
{
this->game->MoveUp();
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_E ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->SizeUp();
//selected->color = Color(selected->color.GetR()-10, selected->color.GetG()+10, selected->color.GetB());
}
else
{
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_Q ) == GLFW_PRESS)
{
if(buildmode && selected != nullptr)
{
selected->SizeDown();
//selected->color = Color(selected->color.GetR()+10, selected->color.GetG()-10, selected->color.GetB());
}
else
{
}
}
if(glfwGetKey(this->game->GetWindow(), GLFW_KEY_R ) == GLFW_PRESS)
{
if(this->buildmode)
this->buildmode = false;
else
this->buildmode = true;
}
int newState = glfwGetKey(this->game->GetWindow(), GLFW_KEY_SPACE);
if (newState == GLFW_PRESS && this->oldState == GLFW_RELEASE)
{
//std::vector<Ball*> balls = this->game->GetBalls();
this->game->AddBall(new Ball());
this->selected = this->game->GetBall(this->game->GetBallCount() - 1);
std::cout << "spawned" << "\n";
}
this->oldState = newState;
}
| true |
ebe86c0124935c9cff29d6f93eb06df42b554cae | C++ | yitati/LCProject | /Leetcode/GameOfLife.cpp | UTF-8 | 3,196 | 3.71875 | 4 | [] | no_license | /******************************************************************************/
/*
* Question: #289 Game Of Life
* According to the Wikipedia's article: "The Game of Life, also known simply as Life,
* is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
* Given a board with m by n cells, each cell has an initial state live (1) or dead (0).
* Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
* Any live cell with fewer than two live neighbors dies, as if caused by under-population.
* Any live cell with two or three live neighbors lives on to the next generation.
* Any live cell with more than three live neighbors dies, as if by over-population..
* Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
* Write a function to compute the next state (after one update) of the board given its current state.
* Follow up:
* Could you solve it in-place? Remember that the board needs to be updated at the same time:
* You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array.
* In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array.
* How would you address these problems?
*/
/*****************************************************************************/
#include <vector>
using namespace std;
// state: 0 current state is 0 and next state is 0
// state: 1 current state is 1 and next state is 1
// state: -1 current state is 1 and next state is 0
// state: 2 current state is 0 and next state is 2
int getStat(vector<vector<int>> & board, int r, int c)
{
int count = 0;
// up
if (r > 0 && (board[r - 1][c] == 1 || board[r - 1][c] == -1)) count++;
// up left
if (r > 0 && c > 0 && (board[r - 1][c - 1] == 1 || board[r - 1][c - 1] == -1)) count++;
// up right
if (r > 0 && c < board[0].size() - 1 && (board[r - 1][c + 1] == 1 || board[r - 1][c + 1] == -1)) count++;
// left
if (c > 0 && (board[r][c - 1] == 1 || board[r][c - 1] == -1)) count++;
// right
if (c < board[0].size() - 1 && (board[r][c + 1] == 1 || board[r][c + 1] == -1)) count++;
// left bottom
if (c > 0 && r < board.size() - 1 && (board[r + 1][c - 1] == 1 || board[r + 1][c - 1] == -1)) count++;
// bottom
if (r < board.size() - 1 && (board[r + 1][c] == 1 || board[r + 1][c] == -1)) count++;
// right bottom
if (c < board[0].size()-1 && r < board.size() - 1 && (board[r + 1][c + 1] == 1 || board[r + 1][c + 1] == -1)) count++;
return count;
}
void gameOfLife(vector<vector<int>>& board)
{
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
int count = getStat(board, i, j);
if (board[i][j] == 1)
{
if (count < 2 || count > 3) board[i][j] = -1;
}
if (board[i][j] == 0)
{
if (count == 3) board[i][j] = 2;
}
}
}
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
if (board[i][j] == 2) board[i][j] = 1;
if (board[i][j] == -1) board[i][j] = 0;
}
}
} | true |
ae95d36b557c70f29ab9cc96ef988ba29114a3a7 | C++ | sundsx/RevBayes | /src/revlanguage/datatypes/evolution/RlTaxon.cpp | UTF-8 | 4,718 | 2.625 | 3 | [] | no_license | #include "ConstantNode.h"
#include "ModelVector.h"
#include "RlTaxon.h"
#include "TimeAndDate.h"
#include "RbUtil.h"
#include "RlString.h"
#include "TypeSpec.h"
#include <sstream>
using namespace RevLanguage;
/** Default constructor */
Taxon::Taxon(void) : ModelObject<RevBayesCore::Taxon>() {
}
/** Construct from core Taxon */
Taxon::Taxon(RevBayesCore::Taxon *c) : ModelObject<RevBayesCore::Taxon>( c ) {
}
/** Construct from core Taxon */
Taxon::Taxon(const RevBayesCore::Taxon &t) : ModelObject<RevBayesCore::Taxon>( new RevBayesCore::Taxon( t ) ) {
}
/** Construct from DAG node */
Taxon::Taxon(RevBayesCore::TypedDagNode<RevBayesCore::Taxon> *n) : ModelObject<RevBayesCore::Taxon>( n ) {
}
/** Construct */
Taxon::Taxon(const Taxon &t) : ModelObject<RevBayesCore::Taxon>( t ) {
}
/** Clone object */
Taxon* Taxon::clone(void) const {
return new Taxon(*this);
}
void Taxon::constructInternalObject( void )
{
// we free the memory first
if ( dagNode != NULL )
{
if ( dagNode->decrementReferenceCount() == 0 )
{
delete dagNode;
}
}
// now allocate a new Taxon
std::string taxonName = static_cast<const RlString &>( (taxon)->getRevObject() ).getValue() ;
std::string taxonSpecies = static_cast<const RlString &>( (species)->getRevObject() ).getValue() ;
// std::string taxonDate = static_cast<const RlDate &>( (date)->getRevObject() ).getValue() ;
// RevBayesCore::TimeAndDate d = RevBayesCore::TimeAndDate();
dagNode = new RevBayesCore::ConstantNode<RevBayesCore::Taxon>("", new RevBayesCore::Taxon( taxonName, taxonSpecies ) );
dagNode->incrementReferenceCount();
}
/* Map calls to member methods */
RevLanguage::RevPtr<RevLanguage::Variable> Taxon::executeMethod(std::string const &name, const std::vector<Argument> &args) {
// if (name == "nnodes") {
// size_t n = this->value->getValue().getNumberOfNodes();
// return new Natural( n );
// }
// else if (name == "names") {
// const std::vector<std::string>& n = this->value->getValue().getNames();
// return new ModelVector<RlString>( n );
// }
return ModelObject<RevBayesCore::Taxon>::executeMethod( name, args );
}
/** Return member rules (no members) */
const MemberRules& Taxon::getMemberRules(void) const {
static MemberRules modelMemberRules;
static bool rulesSet = false;
if ( !rulesSet ) {
modelMemberRules.push_back( new ArgumentRule("taxonName", true, RlString::getClassTypeSpec() ) );
modelMemberRules.push_back( new ArgumentRule("speciesName", true, RlString::getClassTypeSpec() ) );
// modelMemberRules.push_back( new ArgumentRule("date", true, RlDate::getClassTypeSpec() ) );
rulesSet = true;
}
return modelMemberRules;
}
/** Get Rev type of object */
const std::string& Taxon::getClassType(void) {
static std::string revType = "Taxon";
return revType;
}
/** Get class type spec describing type of object */
const TypeSpec& Taxon::getClassTypeSpec(void) {
static TypeSpec revTypeSpec = TypeSpec( getClassType(), new TypeSpec( RevObject::getClassTypeSpec() ) );
return revTypeSpec;
}
/* Get method specifications */
const RevLanguage::MethodTable& Taxon::getMethods(void) const {
static MethodTable methods = MethodTable();
static bool methodsSet = false;
if ( methodsSet == false ) {
// ArgumentRules* nnodesArgRules = new ArgumentRules();
// methods.addFunction("nnodes", new MemberProcedure(Natural::getClassTypeSpec(), nnodesArgRules ) );
//
// ArgumentRules* namesArgRules = new ArgumentRules();
// methods.addFunction("names", new MemberProcedure(ModelVector<RlString>::getClassTypeSpec(), namesArgRules ) );
// necessary call for proper inheritance
methods.setParentTable( &RevObject::getMethods() );
methodsSet = true;
}
return methods;
}
/** Get type spec */
const TypeSpec& Taxon::getTypeSpec( void ) const {
static TypeSpec typeSpec = getClassTypeSpec();
return typeSpec;
}
/** Set a member variable */
void Taxon::setConstMemberVariable(const std::string& name, const RevPtr<const Variable> &var) {
if ( name == "taxonName")
{
taxon = var ;
}
else if ( name == "speciesName")
{
species = var ;
}
else if ( name == "date")
{
date = var ;
}
else {
RevObject::setConstMemberVariable(name, var);
}
}
| true |
a3b4a455bc28c38bf7ffcca2e60a5603392fb23d | C++ | Bohdan-Belik/wppt-archive | /Semestr2/KP/projects/lab2/figury c++/main.cpp | UTF-8 | 7,284 | 3 | 3 | [] | no_license | /**LAB 3_ZAD.2
*@author Max_Telepchuk
*/
#include <iostream>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <sstream>
#define PI 3.14159265
using namespace std;
class Figura
{
public:
virtual float ObliczObwod(){};
virtual float ObliczPole(){};
};
class Czworokat: public Figura
{
protected:
float bok1;
float bok2;
float bok3;
float bok4;
float kat;
public:
virtual float ObliczObwod(){};
virtual float ObliczPole(){};
};
class Okrag: public Figura
{
private:
float promien;
public:
float ObliczObwod()
{
return 2.0f *PI* promien;
}
float ObliczPole()
{
return PI * promien * promien;
}
Okrag (float promien1)
{
promien = promien1;
}
};
class Pieciokat: public Figura
{
private:
float bok;
public:
Pieciokat (float bok1)
{
bok = bok1;
}
float ObliczObwod()
{
return (float)(bok*5.0);
}
float ObliczPole()
{
return (float)(bok*bok*1.72);
}
};
class Szesciokat: public Figura
{
private:
float bok;
public:
float ObliczObwod()
{
return 6.0f * bok;
}
float ObliczPole()
{
return bok * bok * 2.59f;
}
Szesciokat (float n)
{
bok = n;
}
};
class Kwadrat: public Czworokat
{
public:
float ObliczObwod()
{
return 4.0f * bok1;
}
float ObliczPole()
{
return bok1 * bok1;
}
Kwadrat (float n)
{
bok1 = n;
}
};
class Romb: public Czworokat
{
public:
float ObliczObwod()
{
return 4.0f * bok1;
}
float ObliczPole()
{
return bok1 * bok1 * sin(kat);
}
Romb (float n1, float n2)
{
bok1 = n1;
kat = n2;
}
};
class Prostokat: public Czworokat
{
public:
float ObliczObwod()
{
return 2.0f * bok1 + 2.0f * bok2;
}
float ObliczPole()
{
return bok1 * bok2;
}
Prostokat (float n, float m)
{
bok1 = n;
bok2 = m;
}
};
int Tablica (char tab[], int *j, vector<Figura*> *dane, char* argv[], int argc, int wskliczby, int k, int liczby[])
{
int a=1;
switch(tab[*j]){
case 'o':{ //j - wskaźnik na pierwszy argument
if (wskliczby<argc-2) // wskliczby - indeks parametrów
{
if (liczby[wskliczby]>=0)
{
dane->push_back(new Okrag(liczby[wskliczby]));
}
else
{
cout <<"NIEPOPRAWNE DANE"<< endl;
a=-1;
}
}
else
{
a=-1;
cout <<"NIEPOPRAWNE DANE" << endl;
}
break;
}
case 'c':{
if(wskliczby+4<argc-2)
{
int* i=&liczby[wskliczby];
if ((*i>=0) && (*(i+1)>=0) && (*(i+2)>=0) && (*(i+3)>=0) && (*(i+4)>=0))
{
if ((*i==*(i+1)) && (*i==*(i+2)) && (*i==*(i+3)))
{
if(*(i+4)==90)
dane->push_back(new Kwadrat(*i));
else if (*i<=180 && *i>0)
dane->push_back(new Romb(*i, *(i+4)));
else
cout <<"NIEPOPRAWNE DANE"<< endl;
}
else if ((((*i==*(i+1))&&(*(i+2)==*(i+3)))||((*i==*(i+2))&&(*(i+1)==*(i+3)))||((*i==*(i+4))&&(*(i+1)==*(i+2))))&&(*(i+4)==90))
dane->push_back(new Prostokat((min(*i,*(i+1)),min(*(i+2),*(i+3))),(max(*i,*(i+1)),max(*(i+2),*(i+3)))));
else
{
cout <<"NIEPOPRAWNE DANE" << endl;
a=-1;
}
}
else
{
cout <<"NIEPOPRAWNE DANE"<< endl;
a=-1;
}
}
else
{
a=-1;
cout <<"NIEPOPRAWNE DANE"<< endl;
}
break;
}
case 'p':{
if (wskliczby<argc-2)
{
if (liczby[wskliczby]>=0)
{
dane->push_back(new Pieciokat(liczby[wskliczby]));
}
else
{
cout <<"NIEPOPRAWNE DANE"<< endl;
a=-1;
}
}
else
{
a=-1;
cout <<"NIEPOPRAWNE DANE"<< endl;
}
break;
}
case 's':{
if (wskliczby<argc-2)
{
if (liczby[wskliczby]>=0)
{
dane->push_back(new Szesciokat(liczby[wskliczby]));
}
else
{
cout <<"NIEPOPRAWNE DANE"<< endl;
a=-1;
}
}
else
{
a=-1;
cout <<"NIEPOPRAWNE DANE"<< endl;
}
break;
}
}
return a;
}
int TestTablica (char tab[], int *j, vector <Figura*> *dane, char* argv[], int argc, int wskliczby, int k, int liczby[]) throw (string)
{
if ((tab[*j]!='o') && (tab[*j]!='c') && (tab[*j]!='p') && (tab[*j]!='s'))
throw (string) "NIEPOPRAWNE DANE";
return Tablica (tab, j, dane, argv, argc, wskliczby, k, liczby);
}
int main(int argc, char* argv[])
{
if (argc>1)
{
char *tab = argv[1];
int j=0, k=0, wskliczby=0;
vector <Figura*> dane;
int length = strlen(tab);
int *liczby=new int [argc-2];
for (int j=2; j<argc; j++)
{
stringstream s;
s << argv[j];
s >> liczby[j-2];
if (s.fail())
{
cout <<"NIEPOPRAWNE DANE"<< endl;
return 0;
}
}
int a;
for (j=0; j<length; j++)
{
try
{
a = TestTablica(tab, &j, &dane, argv, argc, wskliczby, k, liczby);
if (a==1)
{
k++;
}
if (tab[j]=='c')
wskliczby=wskliczby+5;
else
wskliczby++;
}
catch (string w)
{
cout << tab[j] << " - " << w << endl;
}
}
for (int i=0; i<k; i++)
{
cout << "Pole figury "<<i+1<<" = "<< dane[i]->ObliczPole() << endl;
cout << "Obwod figury "<<i+1<<" = "<< dane[i]->ObliczObwod() << endl;
cout<<""<<endl;
}
}
return 0;
}
| true |
306ec61afb0fb724640a9b3c327a2ca7ea74ca3b | C++ | 7starsea/Prioritized-Experience-Replay | /util_cpp/inc/cnarray.hpp | UTF-8 | 4,718 | 2.671875 | 3 | [
"MIT"
] | permissive | #ifndef KLEIN_CPP_INC_CNARRAY_HPP
#define KLEIN_CPP_INC_CNARRAY_HPP
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
#include "cnarray_c.hpp"
/*
/// @brief construct np.1darray from a raw data pointer
/// user should make sure the data pointer is valid
/// during the lifetime of the constructed np.1darray
template<typename T>
py::array to_ndarray(T * data, int n){
return np::from_data(data,
np::dtype::get_builtin<T>(),
boost::python::make_tuple(n),
boost::python::make_tuple(sizeof(T)),
boost::python::object()
);
}
*/
/// @brief internally used for destroy the pointer malloced in the method cndarray::init
template<typename T>
inline void internal_destroy_cndarray_object(PyObject* obj) {
T * b = reinterpret_cast<T*>( PyCapsule_GetPointer(obj, NULL) );
if(b){
///boost::alignment::aligned_free(b);
std::free(b);
}
}
/**
* @class template<> cndarray
* @brief provide a convenient way of transferring between c++ data array and numpy.ndarray
*
* @tparam T: data type (e.g. double, int, ...)
* @tparam N: array dimension (e.g. 1, 2, 3, ...)
*/
template<typename T, int N>
class cndarray : public cndarray_c<T, N>{
public:
cndarray()
:cndarray_c<T, N>() {}
cndarray(T* data, bool is_raw=false)
:cndarray_c<T, N>(data ,is_raw) {}
/// @brief from np::ndarray
cndarray(const py::array & x)
:cndarray_c<T, N>(){
from_ndarray(x);
}
/// @brief init data with np::ndarray
void from_ndarray( const py::array_t<T> & x ){
assert((NULL == this->data_ && "You cannot reinitialize cndarray!"));
this->data_ = reinterpret_cast<T*>((void*) x.data());
for(int i = 0; i < N; ++i ){
this->shape_[i] = x.shape(i);
this->strides_[i] = x.strides(i) / sizeof(T);
}
}
//// @brief to np::ndarray
py::array to_ndarray() const {
ssize_t v[N];
for(int i = 0; i < N; ++i) v[i] = this->strides_[i] * sizeof(T);
const auto info = py::buffer_info(
this->data_, /* data as contiguous array */
sizeof(T), /* size of one scalar */
py::format_descriptor<T>::format(), /* data type */
N, /* number of dimensions */
this->shape_, /* shape of the matrix */
v /* strides for each axis */
);
/*
if(this->is_raw_){
py::handle h(::PyCapsule_New((void *)info.ptr, NULL, (PyCapsule_Destructor)&internal_destroy_cndarray_object<int>));
return py::array(pybind11::dtype(info), info.shape, info.strides, info.ptr, py::object(h, false));
}
*/
const bool is_borrowed = !this->is_raw_;
py::handle h(::PyCapsule_New((void *)info.ptr, NULL, is_borrowed ? (PyCapsule_Destructor)&internal_destroy_cndarray_object<int> : NULL));
return py::array(pybind11::dtype(info), info.shape, info.strides, info.ptr, py::object(h, is_borrowed));
}
/// @brief return sub-cndarray with axis index is j
/// return_type is cndarray<T, N-1> if N > 1
/// return_type is T if N = 1
typename if_< is_greater< std::integral_constant<int, N>, std::integral_constant<int, 1> >, cndarray<T, N-1>, T >::type
view(int j, int axis=0){
typedef typename is_greater< std::integral_constant<int, N>, std::integral_constant<int, 1> >::type mpl_bool_type;
return _view(j, axis, mpl_bool_type());
}
/// @brief return sub-cndarray with axis index is j
/// return_type is cndarray<T, N-1> if N > 1
/// return_type is T if N = 1
typename if_< is_greater< std::integral_constant<int, N>, std::integral_constant<int, 1> >, cndarray<T, N-1>, T >::type const
view(int j, int axis=0)const{
typedef typename is_greater< std::integral_constant<int, N>, std::integral_constant<int, 1> >::type mpl_bool_type;
return _view(j, axis, mpl_bool_type());
}
protected:
cndarray<T, N-1> _view(int j, int axis, const std::true_type &)const{
/// always make sure N > 1
cndarray<T, N-1> sub_cndarr (this->data_ + j * this->strides_[axis]);
int k = 0;
for(int i = 0; i < N; ++i){
if(i == axis) continue;
sub_cndarr.shape(k) = this->shape_[i];
sub_cndarr.strides(k) = this->strides_[i];
++k;
}
return sub_cndarr;
}
T _view(int i, int axis, const std::false_type &)const{
/// always make sure N == 1
return this->ix(i);
}
};
#endif // GAUSS_PY_INC_CNARRAY_HPP
| true |
d37804a5cb2daed66856e4da9b33313aca7efaa0 | C++ | david-grs/c-excercises | /course6/toyapp-adam/displaylib/mesh.cc | UTF-8 | 634 | 2.875 | 3 | [] | no_license | #include "mesh.h"
namespace Display {
void Mesh::NormalizeScale()
{
auto maxDimension = 0.0f;
for (auto& triangle : triangles)
{
for (unsigned vector = 0; vector < 3; ++vector)
{
for (unsigned vertex = 0; vertex < 3; ++vertex)
{
auto dimension = std::fabs(triangle[vector][vertex]);
if (dimension > maxDimension)
maxDimension = dimension;
}
}
}
if (maxDimension == 0.0f)
return;
auto scale = 1.0f / maxDimension;
for (auto& triangle : triangles)
for (unsigned vector = 0; vector < 3; ++vector)
for (unsigned vertex = 0; vertex < 3; ++vertex)
triangle[vector][vertex] *= scale;
}
}
| true |
2dd8d947a38e2cbc56581f106f104e560e9a0f5a | C++ | DancingOnAir/LeetCode | /Leetcode/Array/035_SearchInsertPosition.cpp | UTF-8 | 576 | 3.25 | 3 | [] | no_license | //#include <iostream>
//#include <stdlib.h>
//#include <vector>
//
//using namespace std;
//int searchInsert(vector<int>& nums, int target)
//{
// int i = 0;
// int j = nums.size() - 1;
//
// while (i < j)
// {
// int mid = (i + j) / 2;
// if (nums[mid] < target)
// i = mid + 1;
// else
// j = mid;
// }
//
// if (nums[i] >= target)
// return i;
// else
// return i + 1;
//}
//
//int main(void)
//{
// int a[] = { 1, 3, 5, 6 };
// int target = 0;
// vector<int> vec(a, a + 4);
//
// cout << searchInsert(vec, target) << endl;
//
// system("pause");
// return 0;
//} | true |
6ac30cd6f70e35cca77ebbbac407a9066b7355cd | C++ | sam830917/TenNenDemon | /Engine/Code/Engine/Math/OBB3.hpp | UTF-8 | 582 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Vec2.hpp"
#include "Vec3.hpp"
struct OBB3
{
Vec3 m_center;
Vec3 m_halfDimensions;
Vec3 m_iBasisNormal = Vec3( 1.f, 0.f, 0.f );
Vec3 m_jBasisNormal = Vec3( 0.f, 1.f, 0.f );
Vec3 m_kBasisNormal = Vec3( 0.f, 0.f, 1.f );
OBB3() = default;
~OBB3() = default;
explicit OBB3( const Vec3& center, const Vec3& fullDimensions );
Vec3 GetIBasisNormal() const { return m_iBasisNormal; }
Vec3 GetJBasisNormal() const { return m_jBasisNormal; }
Vec3 GetKBasisNormal() const { return m_kBasisNormal; }
void GetCornerPosition( Vec3* out_fourPoints ) const;
}; | true |
c7c7ae0dc0bd2a656e59c2ef6549e7db1d441ba2 | C++ | jchallenger/ShaderTestEngine | /ShaderTester/WindowInfo.cpp | UTF-8 | 1,551 | 3.078125 | 3 | [] | no_license | #include "WindowInfo.h"
WindowInfo::WindowInfo(){
fullScreen = false;
mouseHide = false;
}
WindowInfo::~WindowInfo()
{
}
void WindowInfo::setWindow(sf::RenderWindow * _window){
window = _window;
setSize( _window->getSize() );
}
sf::RenderWindow * WindowInfo::getWindow(){
return window;
}
void WindowInfo::draw(){
window->display();
}
void WindowInfo::close(){
window->close();
}
void WindowInfo::setWidth(float x){
window->setSize(sf::Vector2u(x,window->getSize().y));
centerWidth = x/2;
}
void WindowInfo::setHeight(float y){
window->setSize(sf::Vector2u(window->getSize().x,y));
centerHeight = y/2;
}
void WindowInfo::setSize(unsigned int x, unsigned int y){
setSize(sf::Vector2u(x,y));
}
void WindowInfo::setSize(sf::Vector2u _size){
window->setSize(_size);
centerHeight = _size.y/2;
centerWidth = _size.x/2;
}
void WindowInfo::toggleFullScreen(){
fullScreen = !fullScreen;
}
void WindowInfo::hideMouse(){
mouseHide = true;
window->setMouseCursorVisible(false);
}
void WindowInfo::showMouse(){
mouseHide = false;
window->setMouseCursorVisible(true);
}
bool WindowInfo::isFullScreen(){ return fullScreen; }
bool WindowInfo::isMouseHidden(){ return mouseHide; }
float WindowInfo::getWidth(){ return window->getSize().x; }
float WindowInfo::getHeight(){ return window->getSize().y; }
float WindowInfo::getCenterX(){ return centerWidth; }
float WindowInfo::getCenterY(){ return centerHeight; } | true |
34ad893ab94c5a32e9ca015f0e7439666e888777 | C++ | gnole/lab-01-parser | /sources/print_any.cpp | UTF-8 | 1,895 | 3.453125 | 3 | [
"MIT"
] | permissive | // Copyright 2020 gnole
#include <print_any.hpp>
#include <iomanip>
#include <vector>
std::stringstream ssany(const std::any& object)
{
std::stringstream out_str;
if (object.type() == typeid(std::string))
{
out_str << std::any_cast<std::string>(object);
} else if (object.type() == typeid(int)) {
out_str << std::to_string(std::any_cast<int>(object));
} else if (object.type() == typeid(double)) {
out_str << std::setprecision(3)
<< std::any_cast<double>(object);
} else if (object.type() == typeid(std::vector<std::string>)) {
std::vector<std::string> str_vec
= std::any_cast<std::vector<std::string>>(object);
int size = str_vec.size();
if (size > 1)
{
out_str << std::to_string(size) << " items";
} else if (size == 1) {
out_str << str_vec[0];
}
} else if (object.type() == typeid(bool)) {
out_str << "null";
} else {
std::bad_cast ex;
throw ex;
}
return out_str;
}
std::ostream& operator << (std::ostream &out, const std::any& object)
{
std::stringstream out_str;
if (object.type() == typeid(std::string))
{
out_str << std::any_cast<std::string>(object);
} else if (object.type() == typeid(int)) {
out_str << std::to_string(std::any_cast<int>(object));
} else if (object.type() == typeid(double)) {
out_str << std::setprecision(3)
<< std::any_cast<double>(object);
} else if (object.type() == typeid(std::vector<std::string>)) {
std::vector<std::string> str_vec
= std::any_cast<std::vector<std::string>>(object);
int size = str_vec.size();
if (size > 1)
{
out_str << std::to_string(size) << " items";
} else if (size == 1) {
out_str << str_vec[0];
}
} else if (object.type() == typeid(bool)) {
out_str << "null";
} else {
std::bad_cast ex;
throw ex;
}
out << out_str.str();
return out;
}
| true |
f0a3db72e062bef1caef2fd5e77d32ed610e2e07 | C++ | northWindPA/cpp_modules | /Module_04/ex03/Character.cpp | UTF-8 | 1,152 | 3.0625 | 3 | [] | no_license | #include "Character.hpp"
void Character::equip(AMateria *m)
{
for (int i = 0; i < 4; ++i)
{
if (_materia_pack[i] == nullptr)
{
_materia_pack[i] = m;
break;
}
}
}
void Character::unequip(int idx)
{
if (idx >= 0 && idx < 4)
if (_materia_pack[idx])
_materia_pack[idx] = nullptr;
}
void Character::use(int idx, ICharacter &target)
{
if (idx >= 0 && idx < 4)
if (_materia_pack[idx])
_materia_pack[idx]->use(target);
}
const std::string &Character::get_name() const
{
return _name;
}
Character::Character()
{}
Character::Character(const std::string &name)
: _name(name)
{
for (int i = 0; i < 4; ++i)
{
_materia_pack[i] = nullptr;
}
}
Character::~Character()
{
for (int i = 0; i < 4; ++i)
{
if (_materia_pack[i])
delete _materia_pack[i];
}
}
Character &Character::operator=(const Character &other)
{
if (this == &other)
return *this;
for (int i = 0; i < 4; ++i)
{
if (_materia_pack[i])
delete _materia_pack[i];
}
_name = other._name;
for (int i = 0; i < 4; ++i)
{
_materia_pack[i] = other._materia_pack[i];
}
return *this;
}
Character::Character(const Character &other)
{
*this = other;
}
| true |
fb32d9433d11273165f7b11801097aa102e3d998 | C++ | MGPDGLC/CSDN | /53.cpp | UTF-8 | 627 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
void fun(int x, int y, int z);
int main()
{
int x, y, z;
cin >> x >> y >> z;
fun(x, y, z);
return 0;
}
void fun(int x, int y, int z)
{
int i, j, k=1;
int n = 0;
for (i = 2000; i <= x; i++)
{
for (j = 1; j <= 12; j++)
{
if (i == x && j == y)
{
n += z;
break;
}
else
{
if (j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12)
n += 31;
else if (j == 4 || j == 6 || j == 9 || j == 11)
n += 30;
else
{
n += 28;
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
n += 1;
}
}
}
}
cout << n;
} | true |
521255940e82303d4438a0745a955853293860c6 | C++ | Jeremycw-tec/MasterMind | /Proyecto c++/MasterMind/mainwindow.cpp | UTF-8 | 17,359 | 2.6875 | 3 | [] | no_license | //Librerias
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QColor"
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <cstdlib>
using namespace std;
//Algunas varibles iniciales
//verificadores para el boton de hacer jugada
int verif1=0;
int verif2=0;
int verif3=0;
int verif4=0;
int cal[4];//Organizacion de la calificacion
int cal2[4];
int cal3[4];
int cal4[4];
int cal5[4];
int cal6[4];
int cal7[4];
int cal8[4];
int comb[4];//combinacion aleatoria
char colores[6][10]={"rojo","azul","amarillo","naranja","verde","morado"};//colores
char letras [6][2]={"A","B","C","D","F","G"};//letras
char numeros[6][2]={"1","2","3","4","5","6"};//numeros
//Contadores para los botones
int filas=0;//contador para las filas ocultas
int contc1=0; //Boton 1
int contc2=0; //Boton 2
int contc3=0; //Boton 3
int contc4=0; //Boton 4
int resty=50; //Movimiento en las coordenadas
//-------------------------------------------------------------------------------
//Funciones
void datoaleatorio(int com[4]){
srand(time(NULL));
for (int i = 0; i < 4; i++) {
com[i] = rand() % 6;
}
return;
}//Funciona correctamente
int verif(int n,int com[4]) { //Verifica si un numero se encuenta en el arreglo
for (int i=0; i < 4; i++) {
if (n == com[i]) {
return 1;
}
}
return 0;
}
void calif(int com[4]) //Crea la organizacion aleatoria de la calificacion
{
int i = 0;
while (i < 4) {
srand(time(NULL));
int alea = 1+ rand() % 4;
if(verif(alea,com)==0){
com[i] = alea;
i++;
}
continue;
}
return;
}
//---------------------------------------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
calif(cal);
calif(cal2);
calif(cal3);
calif(cal4);
calif(cal5);
calif(cal6);
calif(cal7);
calif(cal8);
//Objetos ocultos
//fila 1
ui->boton1_1->setVisible(false);
ui->boton2_1->setVisible(false);
ui->boton3_1->setVisible(false);
ui->boton4_1->setVisible(false);
ui->ver1_1->setVisible(false);
ui->ver2_1->setVisible(false);
ui->ver3_1->setVisible(false);
ui->ver4_1->setVisible(false);
//fila 2
ui->boton1_2->setVisible(false);
ui->boton2_2->setVisible(false);
ui->boton3_2->setVisible(false);
ui->boton4_2->setVisible(false);
ui->ver1_2->setVisible(false);
ui->ver2_2->setVisible(false);
ui->ver3_2->setVisible(false);
ui->ver4_2->setVisible(false);
//fila 3
ui->boton1_3->setVisible(false);
ui->boton2_3->setVisible(false);
ui->boton3_3->setVisible(false);
ui->boton4_3->setVisible(false);
ui->ver1_3->setVisible(false);
ui->ver2_3->setVisible(false);
ui->ver3_3->setVisible(false);
ui->ver4_3->setVisible(false);
//fila 4
ui->boton1_4->setVisible(false);
ui->boton2_4->setVisible(false);
ui->boton3_4->setVisible(false);
ui->boton4_4->setVisible(false);
ui->ver1_4->setVisible(false);
ui->ver2_4->setVisible(false);
ui->ver3_4->setVisible(false);
ui->ver4_4->setVisible(false);
//fila 5
ui->boton1_5->setVisible(false);
ui->boton2_5->setVisible(false);
ui->boton3_5->setVisible(false);
ui->boton4_5->setVisible(false);
ui->ver1_5->setVisible(false);
ui->ver2_5->setVisible(false);
ui->ver3_5->setVisible(false);
ui->ver4_5->setVisible(false);
//fila 6
ui->boton1_6->setVisible(false);
ui->boton2_6->setVisible(false);
ui->boton3_6->setVisible(false);
ui->boton4_6->setVisible(false);
ui->ver1_6->setVisible(false);
ui->ver2_6->setVisible(false);
ui->ver3_6->setVisible(false);
ui->ver4_6->setVisible(false);
//fila 7
ui->boton1_7->setVisible(false);
ui->boton2_7->setVisible(false);
ui->boton3_7->setVisible(false);
ui->boton4_7->setVisible(false);
ui->ver1_7->setVisible(false);
ui->ver2_7->setVisible(false);
ui->ver3_7->setVisible(false);
ui->ver4_7->setVisible(false);
//fila 8
ui->boton1_8->setVisible(false);
ui->boton2_8->setVisible(false);
ui->boton3_8->setVisible(false);
ui->boton4_8->setVisible(false);
ui->ver1_8->setVisible(false);
ui->ver2_8->setVisible(false);
ui->ver3_8->setVisible(false);
ui->ver4_8->setVisible(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_boton1_clicked()
{
verif1=1;
if(contc1==6){
contc1=0;
}
if (contc1==0){
ui->boton1->setIcon(QIcon(":/rojo.jpg"));
}
if (contc1==1){
ui->boton1->setIcon(QIcon(":/azul.png"));
}
if (contc1==2){
ui->boton1->setIcon(QIcon(":/amarillo.png"));
}
if (contc1==3){
ui->boton1->setIcon(QIcon(":/naranja.jpg"));
}
if (contc1==4){
ui->boton1->setIcon(QIcon(":/verde.png"));
}
if (contc1==5){
ui->boton1->setIcon(QIcon(":/morado.png"));
}
contc1++;
if(verif1==1 && verif2==1 && verif3==1 && verif4==1){
ui->jugada->setEnabled(true);
}
}
void MainWindow::on_boton2_clicked()
{
verif2=1;
if(contc2==6){
contc2=0;
}
if (contc2==0){
ui->boton2->setIcon(QIcon(":/rojo.jpg"));
}
if (contc2==1){
ui->boton2->setIcon(QIcon(":/azul.png"));
}
if (contc2==2){
ui->boton2->setIcon(QIcon(":/amarillo.png"));
}
if (contc2==3){
ui->boton2->setIcon(QIcon(":/naranja.jpg"));
}
if (contc2==4){
ui->boton2->setIcon(QIcon(":/verde.png"));
}
if (contc2==5){
ui->boton2->setIcon(QIcon(":/morado.png"));
}
contc2++;
if(verif1==1 && verif2==1 && verif3==1 && verif4==1){
ui->jugada->setEnabled(true);
}
}
void MainWindow::on_boton3_clicked()
{
verif3=1;
if(contc3==6){
contc3=0;
}
if (contc3==0){
ui->boton3->setIcon(QIcon(":/rojo.jpg"));
}
if (contc3==1){
ui->boton3->setIcon(QIcon(":/azul.png"));
}
if (contc3==2){
ui->boton3->setIcon(QIcon(":/amarillo.png"));
}
if (contc3==3){
ui->boton3->setIcon(QIcon(":/naranja.jpg"));
}
if (contc3==4){
ui->boton3->setIcon(QIcon(":/verde.png"));
}
if (contc3==5){
ui->boton3->setIcon(QIcon(":/morado.png"));
}
contc3++;
if(verif1==1 && verif2==1 && verif3==1 && verif4==1){
ui->jugada->setEnabled(true);
}
}
void MainWindow::on_boton4_clicked()
{
verif4=1;
if(contc4==6){
contc4=0;
}
if (contc4==0){
ui->boton4->setIcon(QIcon(":/rojo.jpg"));
}
if (contc4==1){
ui->boton4->setIcon(QIcon(":/azul.png"));
}
if (contc4==2){
ui->boton4->setIcon(QIcon(":/amarillo.png"));
}
if (contc4==3){
ui->boton4->setIcon(QIcon(":/naranja.jpg"));
}
if (contc4==4){
ui->boton4->setIcon(QIcon(":/verde.png"));
}
if (contc4==5){
ui->boton4->setIcon(QIcon(":/morado.png"));
}
contc4++;
if(verif1==1 && verif2==1 && verif3==1 && verif4==1){
ui->jugada->setEnabled(true);
}
}
void MainWindow::on_iniciar_clicked()
{
datoaleatorio(comb);//creacion de la combinacion
ui->iniciar->setEnabled(false);
ui->boton1->setEnabled(true);
ui->boton2->setEnabled(true);
ui->boton3->setEnabled(true);
ui->boton4->setEnabled(true);
//ui->jugada->setEnabled(true);
}
void MainWindow::on_jugada_clicked()
{
int combinacion[4]={contc1-1,contc2-1,contc3-1,contc4-1};
if(filas==0){//Cambia los datos de los elementos de la primera fila
ui->boton1_1->setVisible(true);
ui->boton2_1->setVisible(true);
ui->boton3_1->setVisible(true);
ui->boton4_1->setVisible(true);
ui->ver1_1->setVisible(true);
ui->ver2_1->setVisible(true);
ui->ver3_1->setVisible(true);
ui->ver4_1->setVisible(true);
if (contc1-1==0){
ui->boton1_1->setIcon(QIcon(":/rojo.jpg"));
}
if (contc1-1==1){
ui->boton1_1->setIcon(QIcon(":/azul.png"));
}
if (contc1-1==2){
ui->boton1_1->setIcon(QIcon(":/amarillo.png"));
}
if (contc1-1==3){
ui->boton1_1->setIcon(QIcon(":/naranja.jpg"));
}
if (contc1-1==4){
ui->boton1_1->setIcon(QIcon(":/verde.png"));
}
if (contc1-1==5){
ui->boton1_1->setIcon(QIcon(":/morado.png"));
}
//-------------------------------------------------------------
if (contc2-1==0){
ui->boton2_1->setIcon(QIcon(":/rojo.jpg"));
}
if (contc2-1==1){
ui->boton2_1->setIcon(QIcon(":/azul.png"));
}
if (contc2-1==2){
ui->boton2_1->setIcon(QIcon(":/amarillo.png"));
}
if (contc2-1==3){
ui->boton2_1->setIcon(QIcon(":/naranja.jpg"));
}
if (contc2-1==4){
ui->boton2_1->setIcon(QIcon(":/verde.png"));
}
if (contc2-1==5){
ui->boton2_1->setIcon(QIcon(":/morado.png"));
}
//----------------------------------------------------------------
if (contc3-1==0){
ui->boton3_1->setIcon(QIcon(":/rojo.jpg"));
}
if (contc3-1==1){
ui->boton3_1->setIcon(QIcon(":/azul.png"));
}
if (contc3-1==2){
ui->boton3_1->setIcon(QIcon(":/amarillo.png"));
}
if (contc3-1==3){
ui->boton3_1->setIcon(QIcon(":/naranja.jpg"));
}
if (contc3-1==4){
ui->boton3_1->setIcon(QIcon(":/verde.png"));
}
if (contc3-1==5){
ui->boton3_1->setIcon(QIcon(":/morado.png"));
}
//------------------------------------------------------------------
if (contc4-1==0){
ui->boton4_1->setIcon(QIcon(":/rojo.jpg"));
}
if (contc4-1==1){
ui->boton4_1->setIcon(QIcon(":/azul.png"));
}
if (contc4-1==2){
ui->boton4_1->setIcon(QIcon(":/amarillo.png"));
}
if (contc4-1==3){
ui->boton4_1->setIcon(QIcon(":/naranja.jpg"));
}
if (contc4-1==4){
ui->boton4_1->setIcon(QIcon(":/verde.png"));
}
if (contc4-1==5){
ui->boton4_1->setIcon(QIcon(":/morado.png"));
}
//----------------------------------------------------------------------
for (int i=0;i<4;i++){
if (combinacion[i]==comb[i]){
if(cal[i]==0){
ui->ver1_1->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal[i]==1){
ui->ver2_1->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal[i]==3){
ui->ver3_1->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal[i]==4){
ui->ver4_1->setIcon(QIcon(":/negro.png"));
continue;
}
}
if (verif(combinacion[i],comb)==true){
if(cal[i]==0){
ui->ver1_1->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal[i]==1){
ui->ver2_1->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal[i]==3){
ui->ver3_1->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal[i]==4){
ui->ver4_1->setIcon(QIcon(":/blanco.png"));
continue;
}
}
}
}
if(filas==1){//segunda fila
ui->boton1_2->setVisible(true);
ui->boton2_2->setVisible(true);
ui->boton3_2->setVisible(true);
ui->boton4_2->setVisible(true);
ui->ver1_2->setVisible(true);
ui->ver2_2->setVisible(true);
ui->ver3_2->setVisible(true);
ui->ver4_2->setVisible(true);
if (contc1-1==0){
ui->boton1_2->setIcon(QIcon(":/rojo.jpg"));
}
if (contc1-1==1){
ui->boton1_2->setIcon(QIcon(":/azul.png"));
}
if (contc1-1==2){
ui->boton1_2->setIcon(QIcon(":/amarillo.png"));
}
if (contc1-1==3){
ui->boton1_2->setIcon(QIcon(":/naranja.jpg"));
}
if (contc1-1==4){
ui->boton1_2->setIcon(QIcon(":/verde.png"));
}
if (contc1-1==5){
ui->boton1_2->setIcon(QIcon(":/morado.png"));
}
//-------------------------------------------------------------
if (contc2-1==0){
ui->boton2_2->setIcon(QIcon(":/rojo.jpg"));
}
if (contc2-1==1){
ui->boton2_2->setIcon(QIcon(":/azul.png"));
}
if (contc2-1==2){
ui->boton2_2->setIcon(QIcon(":/amarillo.png"));
}
if (contc2-1==3){
ui->boton2_2->setIcon(QIcon(":/naranja.jpg"));
}
if (contc2-1==4){
ui->boton2_2->setIcon(QIcon(":/verde.png"));
}
if (contc2-1==5){
ui->boton2_2->setIcon(QIcon(":/morado.png"));
}
//----------------------------------------------------------------
if (contc3-1==0){
ui->boton3_2->setIcon(QIcon(":/rojo.jpg"));
}
if (contc3-1==1){
ui->boton3_2->setIcon(QIcon(":/azul.png"));
}
if (contc3-1==2){
ui->boton3_2->setIcon(QIcon(":/amarillo.png"));
}
if (contc3-1==3){
ui->boton3_2->setIcon(QIcon(":/naranja.jpg"));
}
if (contc3-1==4){
ui->boton3_2->setIcon(QIcon(":/verde.png"));
}
if (contc3-1==5){
ui->boton3_2->setIcon(QIcon(":/morado.png"));
}
//------------------------------------------------------------------
if (contc4-1==0){
ui->boton4_2->setIcon(QIcon(":/rojo.jpg"));
}
if (contc4-1==1){
ui->boton4_2->setIcon(QIcon(":/azul.png"));
}
if (contc4-1==2){
ui->boton4_2->setIcon(QIcon(":/amarillo.png"));
}
if (contc4-1==3){
ui->boton4_2->setIcon(QIcon(":/naranja.jpg"));
}
if (contc4-1==4){
ui->boton4_2->setIcon(QIcon(":/verde.png"));
}
if (contc4-1==5){
ui->boton4_2->setIcon(QIcon(":/morado.png"));
}
//----------------------------------------------------------------------
for (int i=0;i<4;i++){
if (combinacion[i]==comb[i]){
if(cal2[i]==0){
ui->ver1_2->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal2[i]==1){
ui->ver2_2->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal2[i]==3){
ui->ver3_2->setIcon(QIcon(":/negro.png"));
continue;
}
if(cal2[i]==4){
ui->ver4_2->setIcon(QIcon(":/negro.png"));
continue;
}
}
if (verif(combinacion[i],comb)==true){
if(cal2[i]==0){
ui->ver1_2->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal2[i]==1){
ui->ver2_2->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal2[i]==3){
ui->ver3_2->setIcon(QIcon(":/blanco.png"));
continue;
}
if(cal2[i]==4){
ui->ver4_2->setIcon(QIcon(":/blanco.png"));
continue;
}
}
}
}
ui->boton1->setIcon(QIcon(":/gris.jpg"));
ui->boton2->setIcon(QIcon(":/gris.jpg"));
ui->boton3->setIcon(QIcon(":/gris.jpg"));
ui->boton4->setIcon(QIcon(":/gris.jpg"));
ui->ver1->setIcon(QIcon(":/gris.jpg"));
ui->ver2->setIcon(QIcon(":/gris.jpg"));
ui->ver3->setIcon(QIcon(":/gris.jpg"));
ui->ver4->setIcon(QIcon(":/gris.jpg"));
ui->boton1->setGeometry(110,510-resty,40,40);
ui->boton2->setGeometry(180,510-resty,40,40);
ui->boton3->setGeometry(250,510-resty,40,40);
ui->boton4->setGeometry(320,510-resty,40,40);
ui->ver1->setGeometry(380,510-resty,16,16);
ui->ver2->setGeometry(380,530-resty,16,16);
ui->ver3->setGeometry(400,510-resty,16,16);
ui->ver4->setGeometry(400,530-resty,16,16);
ui->jugada->setEnabled(false);
contc1=0;
contc2=0;
contc3=0;
contc4=0;
verif1=0;
verif2=0;
verif3=0;
verif4=0;
resty+=50;
filas++;
}
| true |
ebc29d0b260b5502d2a19e1e9157f739c421e9ca | C++ | lav0/MathLib | /rcbCubeState.cpp | UTF-8 | 3,931 | 2.78125 | 3 | [] | no_license | #include "stdafx.h"
#include "rcbCubeState.h"
//==============================================================================
bool operator==(eTurnAxis a_e_axis, eCubeSide a_e_side)
{
switch (a_e_axis) {
case TA_X: return a_e_side == CS_FRONT || a_e_side == CS_BACK;
case TA_Y: return a_e_side == CS_RIGHT || a_e_side == CS_LEFT;
case TA_Z: return a_e_side == CS_DOWN || a_e_side == CS_UP;
};
assert(0);
return false;
}
//==============================================================================
eCubeSide opposite(eCubeSide a_e_side)
{
switch (a_e_side) {
case CS_DOWN : return CS_UP;
case CS_UP : return CS_DOWN;
case CS_BACK : return CS_FRONT;
case CS_FRONT: return CS_BACK;
case CS_RIGHT: return CS_LEFT;
case CS_LEFT : return CS_RIGHT;
};
assert(0);
return CS_UP;
}
//==============================================================================
eCubeSide turn_rules(eCubeSide a_side, eTurnAxis a_axis, eAngle a_angle)
{
if (a_axis == a_side)
return a_side;
if (a_angle == A_180)
return opposite(a_side);
else if (a_angle == A_270)
return opposite(turn_rules(a_side, a_axis, A_90));
switch (a_side) {
case CS_UP:
if (a_axis == TA_X) return CS_LEFT;
else if (a_axis == TA_Y) return CS_FRONT;
else assert(0);
case CS_DOWN:
if (a_axis == TA_X) return CS_RIGHT;
else if (a_axis == TA_Y) return CS_BACK;
else assert(0);
case CS_FRONT:
if (a_axis == TA_Y) return CS_DOWN;
else if (a_axis == TA_Z) return CS_RIGHT;
else assert(0);
case CS_BACK:
if (a_axis == TA_Y) return CS_UP;
else if (a_axis == TA_Z) return CS_LEFT;
else assert(0);
case CS_RIGHT:
if (a_axis == TA_X) return CS_UP;
else if (a_axis == TA_Z) return CS_BACK;
else assert(0);
case CS_LEFT:
if (a_axis == TA_X) return CS_DOWN;
else if (a_axis == TA_Z) return CS_FRONT;
else assert(0);
};
assert(0);
return CS_DOWN;
}
//==============================================================================
rcbCubeState::rcbCubeState()
: m_z_side(CS_UP), m_x_side(CS_FRONT) {}
//==============================================================================
rcbCubeState::rcbCubeState(eCubeSide a_z, eCubeSide a_x)
: m_z_side(a_z), m_x_side(a_x) {}
//==============================================================================
void rcbCubeState::turn(eTurnAxis a_e_axis, eAngle a_e_angle)
{
m_z_side = turn_rules(m_z_side, a_e_axis, a_e_angle);
m_x_side = turn_rules(m_x_side, a_e_axis, a_e_angle);
}
//==============================================================================
//==============================================================================
// rcbCubePosition further
//==============================================================================
rcbCubePosition::rcbCubePosition(Dimention size, Dimention x, Dimention y, Dimention z)
: m_size(size)
, m_pos_x(x)
, m_pos_y(y)
, m_pos_z(z)
{
}
//==============================================================================
void rcbCubePosition::turn(eTurnAxis a_e_axis, eAngle a_e_angle)
{
if (a_e_angle == A_180)
{
turn(a_e_axis, A_90);
turn(a_e_axis, A_90);
return;
} else if (a_e_angle == A_270)
{
turn(a_e_axis, A_180);
turn(a_e_axis, A_90);
return;
}
assert(a_e_angle == A_90);
if (a_e_axis == TA_X)
{
Dimention tmp = m_pos_z;
m_pos_z = m_pos_y;
m_pos_y = m_size - tmp;
}
else if (a_e_axis == TA_Y)
{
Dimention tmp = m_pos_x;
m_pos_x = m_pos_z;
m_pos_z = m_size - tmp;
}
else if (a_e_axis == TA_Z)
{
Dimention tmp = m_pos_y;
m_pos_y = m_pos_x;
m_pos_x = m_size - tmp;
}
}
//============================================================================== | true |
55c488679e9c51a84638cb3d5deac08d07aa97ed | C++ | mehulthakral/logic_detector | /backend/CDataset/myPow/myPow_18.cpp | UTF-8 | 252 | 2.90625 | 3 | [] | no_license | class Solution {
public:
double myPow(double x, int n) {
long n2 = (long)n;
if (n2 < 0) {n2 = -n2; x = 1/x;}
if (n2 == 0)
return 1;
return (n2 % 2 == 0) ? myPow(x*x, n2/2) : myPow(x*x, n2/2)*x;
}
};
| true |
91c925e626b867ba93e22441d43d5acb7af46046 | C++ | Urevel/Project | /кучи/Heap.h | WINDOWS-1251 | 4,495 | 3.671875 | 4 | [] | no_license | #pragma once
struct AAA
{
int x;
void Print();
int GetPriority();
};
namespace heap //
{
enum CMP { LESS = -1, EQUAL = 0, GREAT = 1 }; // ( )
struct Heap
{
int Size;
int MaxSize;
void** Storage;
CMP(*Compare)(void*, void*); //
Heap(int maxsize, CMP(*f)(void*, void*)) //
{
Size = 0;
Storage = new void* [MaxSize = maxsize];
Compare = f;
};
Heap(int maxsize, CMP(*f)(void*, void*), void* x[]) //
{
Size = 0;
Storage = x;
MaxSize = maxsize;
Compare = f;
};
int Left(int ix); // , ( ) ix
int Right(int ix); // , ( ) ix
int Parent(int ix); // , ( ) ix
bool isFull() //
{
return (Size >= MaxSize); //
};
bool isEmpty() //
{
return (Size <= 0); //
};
bool isLess(void* x1, void* x2) // 1 2
{
return Compare(x1, x2) == LESS; // 1 2 LESS
};
bool isGreat(void* x1, void* x2) // 1 2
{
return Compare(x1, x2) == GREAT;// 1 2 GREAT
};
bool isEqual(void* x1, void* x2) // 1 2
{
return Compare(x1, x2) == EQUAL;// 1 2 EQUAL
};
void Swap(int i, int j); // i j
void Heapify(int ix); //
void Insert(void* x); //
void* ExtractMax(); // , ..
void DeleteHeap(); //
void Scan(int i); //
void* ExtractMin(); //
void* ExtractI(int i); // i-
void Union(Heap&); // (Heap& - )
};
Heap Create(int maxsize, CMP(*f)(void*, void*)); // (void* - )
};
| true |
1c716e6ff921f10b5767df2aa461a2fb73526c8d | C++ | RMoraffah/hippo-postgresql | /src/include/izenelib/include/am/db_trie/traits.h | UTF-8 | 1,722 | 2.5625 | 3 | [
"Apache-2.0",
"PostgreSQL"
] | permissive | #ifndef _DB_TRIE_TRAITS_H_
#define _DB_TRIE_TRAITS_H_
#include <limits.h>
NS_IZENELIB_AM_BEGIN
/**
* Traits for NodeID
*/
template<typename NIDType> class NodeIDTraits;
template <>
class NodeIDTraits<int32_t>
{
public:
enum{RootValue = 1, EmptyValue = 2, MinValue = 3, MaxValue = INT_MAX};
};
template <>
class NodeIDTraits<uint32_t>
{
public:
enum{RootValue = 1, EmptyValue = 2, MinValue = 3, MaxValue = UINT_MAX};
};
template <>
class NodeIDTraits<int64_t>
{
public:
enum{RootValue = 1, EmptyValue = 2, MinValue = 3, MaxValue = LONG_MAX};
};
template <>
class NodeIDTraits<uint64_t>
{
public:
enum{RootValue = 1, EmptyValue = 2, MinValue = 3, MaxValue = ULONG_MAX};
};
/**
* Traits for CharType
*/
template<typename NumberType> class NumericTraits;
template <>
class NumericTraits<char>
{
public:
enum{MinValue = SCHAR_MIN, MaxValue = SCHAR_MAX};
};
template <>
class NumericTraits<int8_t>
{
public:
enum{MinValue = SCHAR_MIN, MaxValue = SCHAR_MAX};
};
template <>
class NumericTraits<uint8_t>
{
public:
enum{MinValue = 0, MaxValue = UCHAR_MAX};
};
template <>
class NumericTraits<int16_t>
{
public:
enum{MinValue = SHRT_MIN, MaxValue = SHRT_MAX};
};
template <>
class NumericTraits<uint16_t>
{
public:
enum{MinValue = 0, MaxValue = USHRT_MAX};
};
template <>
class NumericTraits<int32_t>
{
public:
enum{MinValue = INT_MIN, MaxValue = INT_MAX};
};
template <>
class NumericTraits<uint32_t>
{
public:
enum{MinValue = 0, MaxValue = UINT_MAX};
};
template <>
class NumericTraits<int64_t>
{
public:
enum{MinValue = LONG_MIN, MaxValue = LONG_MAX};
};
template <>
class NumericTraits<uint64_t>
{
public:
enum{MinValue = 0, MaxValue = ULONG_MAX};
};
NS_IZENELIB_AM_END
#endif
| true |
38708cfeaea4d74d5c8a945fb4d0bc420398bbcf | C++ | ranjeevnayak/book-my-show | /mainClass.cpp | UTF-8 | 15,623 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
int count=0;
class Movies{
int ch;
char sig[1];
public:
Movies(int in)
{
if(in==-1)
{
int z;
cout<<"-----------------------------------------------------------------"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"WELCOME TO BOOKMYSHOW"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"------------------------------------------------------------------"<<"\n";
cout<<"\n";
cout<<"\n";
cout<<"1.ADMIN"<<"\n";
cout<<"2.VISITOR"<<"\n";
cout<<"ENTER YOUR ChOICE"<<"\n";
cin>>z;
if(z==1)
{
cout<<"NO CONTENT FOR ADMIN NOW ..!!";
cout<<"\n";
}
else if(z==2)
{
Movies ob(0);
}
}
else if(in==0)
{
int choice;
do{
cout<<"-----------------------------------------------------------------"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"WELCOME TO BOOKMYSHOW"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"|"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"|"<<"\n";
cout<<"------------------------------------------------------------------"<<"\n";
cout<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\n";
cout<<"BOOK TICKETS FOR MOVIES,EVENTS,PLAYS AND SPORTS"<<"\n";
cout<<"1.MOVIES"<<"\n";
cout<<"2.EVENTS/PLAYS"<<"\n";
cout<<"3.SPORTS"<<"\n";
cout<<"4.EXIT"<<"\n";
cout<<"Press Your Choice Please !"<<"\n";
cin>>choice;
if(choice==4)
{
exit(0);
}
else
{
Movies ob(choice);
}
}while(true);
}
else if(in==1)
{
do{
cout<<"\n";
cout<<"CHOOSE YOUR LANGUAGE:"<<"\n";
cout<<"1.HINDI"<<"\n";
cout<<"2.ENGLISH"<<"\n";
cout<<"3.PUNJABI"<<"\n";
cout<<"4.EXIT"<<"\n";
cout<<"Enter your choice:";
cin>>ch;
if(ch==4)
{
Movies ob(0);
}
movies(ch);
cout<<"\n";
cout<<"Do you want to continue:(Y/N)";
cin>>sig;
}while(strcmp(sig,"Y")==0 ||strcmp(sig,"y")==0);
Movies ob(0);
}
else if(in==2)
{
do{
events();
cout<<"Do you want to continue:(Y/N)";
cin>>sig;
}while(strcmp(sig,"Y")==0 ||strcmp(sig,"y")==0);
Movies ob(0);
}
else if(in==3)
{
int as;
cout<<"SORRY THE PAGE IS UNDER CONSTRUCTION..! "<<"\n";
cout<<"\n";
cout<<"\n";
cout<<"PRESS 1 TO GO BACK TO MAIN PAGE OR 0 TO EXIT"<<"\n";
cin>>as;
if(as==1)
{
Movies ob(0);
}
else if(as==0)
{
exit(0);
}
}
}
void movies(int c);
void events();
void payment(int ch,int c);
};
void Movies::movies(int c)
{
char str[30];
char str1[10];
char str2[20];
int ch;
ifstream fin;
ifstream fin1;
ifstream fin2;
if(c==1)
{
fin.open("hindi.txt");
}
else if(c==2)
{
fin.open("english.txt");
}
else if(c==3)
{
fin.open("punjabi.txt");
}
int i=1;
fin1.open("cinemas.txt");
fin2.open("time.txt");
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<setw(5)<<"|"<<"S.NO"<<"|"<<setw(15)<<"|"<<"MOVIE NAME"<<"|"<<setw(15)<<"|"<<"TIME"<<"|"<<setw(15)<<"|"<<"THEATER"<<"|"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
while(!fin.eof())
{
fin.getline(str,99);
fin1.getline(str1,29);
fin2.getline(str2,9);
cout<<setw(5)<<i<<"."<<"\t"<<setw(15)<<str<<setw(35)<<str2<<setw(25)<<"\t"<<str1<<"\n";
cout<<"\n";
i++;
}
fin.seekg(0,ios::beg);
fin1.seekg(0,ios::beg);
fin2.seekg(0,ios::beg);
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\n";
int input;
int found=0;
cout<<"CHOOSE THE OPTIONS:"<<"\n";
cout<<"1.GO FOR PAYMENT"<<"\n";
cout<<"2.MORE OPTIONS"<<"\n";
cin>>input;
if(input==1)
{
int a;
cout<<"PLEASE ENTER YOUR ChOICE :"<<"\n";
cin>>a;
payment(a,c);
}
else if(input==2)
{
cout<<"1.SEARCH MOVIE BY TIME"<<"\n";
cout<<"2.SEARCH MOVIE BY CINEMA"<<"\n";
cout<<"3.SEARCH MOVIE BY NAME"<<"\n";
cout<<"PLEASE ENTER YOUR ChOICE :"<<"\n";
cin>>ch;
if(ch==1)
{
i=1;
cout<<"Enter Your Time:";
string ti1;
cin>>ti1;
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<setw(5)<<"|"<<"S.NO"<<"|"<<setw(15)<<"|"<<"MOVIE NAME"<<"|"<<setw(15)<<"|"<<"TIME"<<"|"<<setw(15)<<"|"<<"THEATER"<<"|"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
while(!fin.eof())
{
fin.getline(str,99);
fin1.getline(str1,29);
fin2.getline(str2,9);
string ti=(string)str2;
if(strncmp(ti.c_str(),ti1.c_str(),1)==0)
{
cout<<setw(5)<<i<<"."<<"\t"<<setw(15)<<str<<setw(35)<<str2<<setw(25)<<"\t"<<str1<<"\n";
cout<<"\n";
found=1;
}
i++;
}
if(found==0)
{
cout<<"\n";
cout<<"NO RESULT FOUND FOR THE GIVEN TIME"<<"\n";
cout<<"\n";
}
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
}
else if(ch==2)
{
i=1;
cout<<"Enter Your Cinema Name:";
string ti1;
cin>>ti1;
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<setw(5)<<"|"<<"S.NO"<<"|"<<setw(15)<<"|"<<"MOVIE NAME"<<"|"<<setw(15)<<"|"<<"TIME"<<"|"<<setw(15)<<"|"<<"THEATER"<<"|"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
while(!fin.eof())
{
fin.getline(str,99);
fin1.getline(str1,29);
fin2.getline(str2,9);
string ti=(string)str1;
if(strncmp(ti.c_str(),ti1.c_str(),1)==0)
{
cout<<setw(5)<<i<<"."<<"\t"<<setw(15)<<str<<setw(35)<<str2<<setw(25)<<"\t"<<str1<<"\n";
cout<<"\n";
found=1;
}
i++;
}
if(found==0)
{
cout<<"\n";
cout<<"NO RESULT FOUND FOR THE GIVEN NAME"<<"\n";
cout<<"\n";
}
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
}
else if(ch==3)
{
i=1;
cout<<"Enter Your Movie Name:";
string ti1;
cin>>ti1;
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<setw(5)<<"|"<<"S.NO"<<"|"<<setw(15)<<"|"<<"MOVIE NAME"<<"|"<<setw(15)<<"|"<<"TIME"<<"|"<<setw(15)<<"|"<<"THEATER"<<"|"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
while(!fin.eof())
{
fin.getline(str,99);
fin1.getline(str1,29);
fin2.getline(str2,9);
string ti=(string)str;
if(strncmp(ti.c_str(),ti1.c_str(),1)==0)
{
cout<<setw(5)<<i<<"."<<"\t"<<setw(15)<<str<<setw(35)<<str2<<setw(25)<<"\t"<<str1<<"\n";
cout<<"\n";
found=1;
}
i++;
}
if(found==0)
{
cout<<"\n";
cout<<"NO RESULT FOUND FOR THE GIVEN NAME"<<"\n";
cout<<"\n";
}
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"-------------------------------------------------------------------------------------------------------------"<<"\n";
}
}
if(input==2 && found!=0)
{
int b;
cout<<"1.GO FOR PAYMENT"<<"\n";
cout<<"2.TO GO BACK TO MAIN PAGE"<<"\n";
cout<<"3.TO EXIT"<<"\n";
cin>>b;
if(b==2)
{
Movies ob(0);
}
else if(b==3)
{
exit(0);
}
else if(b==1)
{ int q;
cout<<"ENTER YOUR ChOICE:";
cin>>q;
payment(q,c);
}
}
fin.close();
fin2.close();
fin1.close();
}
void Movies::events()
{
int ch;
char str1[200];
char str2[200];
char str3[10];
char str4[10];
int i=1;
ifstream fin4,fin1,fin2,fin3;
fin1.open("event.txt");
fin2.open("Venue.txt");
fin3.open("price.txt");
fin4.open("time.txt");
fin1.seekg(0,ios::beg);
fin2.seekg(0,ios::beg);
fin3.seekg(0,ios::beg);
fin4.seekg(0,ios::beg);
cout<<"\n";
cout<<"----------------------------------------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<setw(5)<<"|"<<"S.NO"<<"|"<<setw(15)<<"|"<<"EVENT NAME"<<"|"<<setw(35)<<"|"<<"TIME"<<"|"<<setw(25)<<"|"<<"VENUE"<<"|"<<setw(25)<<"|"<<"PRICE"<<"|"<<"\n";
cout<<"----------------------------------------------------------------------------------------------------------------------------------------------"<<"\n";
while(!fin1.eof())
{
fin1.getline(str1,199);
fin2.getline(str2,199);
fin3.getline(str3,9);
fin4.getline(str4,9);
cout<<setw(5)<<i<<"."<<"\t"<<setw(15)<<str1<<setw(25)<<str4<<setw(15)<<"\t"<<str2<<setw(25)<<str3<<"\n";
cout<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"\n";
i++;
}
cout<<"----------------------------------------------------------------------------------------------------------------------------------------------"<<"\n";
cout<<"-----------------------------------------------------------------------------------------------------------------------------------------------"<<"\n";
fin4.close();
fin1.close();
fin2.close();
fin3.close();
cout<<"PRESS 1 TO GO BACK TO MAIN PAGE OR 0 TO EXIT"<<"\n";
cout<<"PLEASE ENTER YOUR ChOICE :"<<"\n";
cin>>ch;
if(ch==0)
{
exit(0);
}
else if(ch==1)
{
Movies ob(0);
}
else{
payment(ch,4);
}
}
void Movies::payment(int ch,int c)
{
char name[20];
char Id[30];
long long num;
int tickets;
count++;
int event_price;
ofstream fout;
fout.open("database.txt",ios_base::app);
fout<<"\n";
char str[100];
char str1[10];
char str2[10];
char str3[200];
ifstream fin;
ifstream fin1;
ifstream fin2,fin3;
int i=1;
if(c==1)
{
fin.open("hindi.txt");
fin1.open("cinemas.txt");
fin2.open("time.txt");
}
else if(c==2)
{
fin.open("english.txt");
fin1.open("cinemas.txt");
fin2.open("time.txt");
}
else if(c==3)
{
fin.open("punjabi.txt");
fin1.open("cinemas.txt");
fin2.open("time.txt");
}
else if(c==4)
{
fin.open("event.txt");
fin1.open("Venue.txt");
fin2.open("price.txt");
fin3.open("time.txt");
}
if(c!=4)
{
while(!fin.eof() && i<=ch)
{
fin.getline(str,99);
fin1.getline(str1,9);
fin2.getline(str2,9);
if(i==ch)
{
fout<<"CUSTOMER ID :"<<count<<"\n";
fout<<"MOVIE NAME:"<<str<<"\n";
fout<<"TIME:"<<str2<<"\n";
fout<<"THEATER :"<<str1<<"\n";
}
i++;
}
fin.close();
fin1.close();
fin2.close();
}
else if(c==4)
{
while(!fin.eof() && i<=ch)
{
fin.getline(str,199); // event name
fin1.getline(str3,199); // venue
fin2.getline(str1,9); // price
fin3.getline(str2,9); // time
if(i==ch)
{
fout<<"CUSTOMER ID :"<<count<<"\n";
fout<<"EVENT NAME :"<<str<<"\n";
fout<<"EVENT VENUE :"<<str3<<"\n";
fout<<"TIME:"<<str2<<"\n";
fout<<"PRICE :"<<str1<<"\n";
event_price=atoi(str1);
}
i++;
}
fin.close();
fin1.close();
fin2.close();
fin3.close();
}
cout<<"------ MAKE PAYMENT --------"<<"\n";
cout<<"Enter Your Name:";
cin>>name;
fout<<"CUSTOMER NAME:"<<name<<"\n";
cout<<"Your Mobile Number:";
cin>>num;
fout<<"MOBILE NUMBER:"<<num<<"\n";
cout<<"Enter Your E-mail Id:";
cin>>Id;
fout<<"E-MAIL :"<<Id<<"\n";
cout<<"Number of TICKETS:";
cin>>tickets;
fout<<"TICKETS:"<<tickets<<"\n";
if(c!=4)
{
cout<<"Amount to be paid(150 per Ticket):"<<150*tickets<<"\n";
fout<<"AMOUNT COLLECTED:"<<150*tickets<<"\n";
}
else if(c==4)
{
cout<<"Amount paid:"<<event_price*tickets<<"\n";
fout<<"AMOUNT COLLECTED:"<<event_price*tickets<<"\n";
}
cout<<"**** THANK YOU !! ****"<<"\n";
cout<<"**** DATABASE UPDATED !! *****"<<"\n";
fout<<"\n";
fout.close();
}
int main(){
Movies n(-1);
return 0;
}
| true |
7b1da689be3e9e41a9c1706792351d181fdf86c9 | C++ | FTWinston/Chessmaker | /ChessmakerCore/TurnOrder.cpp | UTF-8 | 2,249 | 3.125 | 3 | [] | no_license | #include "TurnOrder.h"
#include "Player.h"
TurnRepeat::TurnRepeat(int count)
{
maxRepeats = count;
currentIteration = 0;
state = AtStart;
}
TurnRepeat::~TurnRepeat()
{
while (!steps.empty())
delete steps.front(), steps.pop_front();
}
TurnStep* TurnRepeat::GetNext(bool forwards)
{
if (state == AtStart)
{
if (!forwards)
return 0;
it = steps.begin();
}
else if (state == AtEnd)
{
if (forwards)
return 0;
it = steps.end();
it--;
}
if (state != AtEnd && !(*it)->IsStep())
{
TurnRepeat *repeat = (TurnRepeat*)*it;
TurnStep *step = repeat->GetNext(forwards);
if (step != 0)
{
state = InMiddle;
return step;
}
}
if (state != InMiddle) // on the first use, don't increment this iterator
state = InMiddle;
else if (forwards)
{
it++;
if (it == steps.end())
{
if (maxRepeats != 0 && currentIteration >= maxRepeats - 1)
{
state = AtEnd;
return 0; // gone past the end on last iteration
}
currentIteration++;
it = steps.begin();
}
}
else
{
if (it == steps.begin())
{
if (maxRepeats != 0 && currentIteration <= 0)
{
state = AtStart;
return 0; // gone past the beginning on first iteration
}
currentIteration--;
it = steps.end();
it--;
}
else
it--;
}
if ((*it)->IsStep())
{
TurnStep *step = (TurnStep*)*it;
return step;
}
// arriving into a repeat for the first time, so reset it
TurnRepeat *repeat = (TurnRepeat*)*it;
if (forwards)
{
repeat->currentIteration = 0;
repeat->state = AtStart;
}
else
{
repeat->currentIteration = repeat->maxRepeats - 1;
repeat->state = AtEnd;
}
return repeat->GetNext(forwards);
}
TurnOrder::TurnOrder() : TurnRepeat(1)
{
}
TurnOrder::~TurnOrder()
{
}
TurnOrder *TurnOrder::CreateDefault(std::list<Player*> players)
{
TurnOrder *order = new TurnOrder();
TurnRepeat *repeat = new TurnRepeat(0);
order->steps.push_back(repeat);
for (auto it = players.begin(); it != players.end(); it++)
repeat->steps.push_back(new TurnStep(*it));
return order;
}
Player *TurnOrder::GetNextPlayer()
{
currentStep = GetNext(true);
if (currentStep == 0)
return 0;
return currentStep->GetPlayer();
}
void TurnOrder::StepBackward()
{
currentStep = GetNext(false);
}
| true |
5075ad5496a720715d995fbbaefe5eaaac95fbd6 | C++ | SayanBan/Hacktoberfest-Codes | /C program/p3.cpp | UTF-8 | 267 | 2.875 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
int main()
{
char i,j,s=1,k;
for(i='G';i>='A';i--)
{
for(j='A';j<=i;j++)
{
printf("%c",j);
}
for(k=s;k>1;k--)
{
printf("\n");
}
for(j=i;j>=1;j--)
{
printf("%c",j);
}
printf("\n");
s++;
}
}
| true |
585724fcc6327086a2ff313e2aaa2bfc000fddf9 | C++ | Wbrta/ACM | /BZOJ/1001.[BeiJing2006]狼抓兔子.cpp | UTF-8 | 2,941 | 2.609375 | 3 | [] | no_license | #include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef struct node {
int v, cap, nxt;
node(int a = 0, int b = 0, int c = 0) {
v = a; cap = b; nxt = c;
}
}Edge;
const int maxn = 2100005;
const int maxm = 6100005;
const int inf = 0x3f3f3f3f;
Edge edge[maxm];
int tot, head[maxn];
int vis[maxn], dis[maxn];
void add(int u, int v, int cap) {
edge[tot] = Edge(v, cap, head[u]);
head[u] = tot++;
edge[tot] = Edge(u, cap, head[v]);
head[v] = tot++;
}
int spfa(int s, int t) {
int x;
Edge e;
queue<int> q;
while (!q.empty()) q.pop();
memset(vis, 0, sizeof(vis));
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0; vis[s] = 1; q.push(s);
while (!q.empty()) {
x = q.front(); q.pop(); vis[x] = 0;
for (int i = head[x]; ~i; i = edge[i].nxt) {
e = edge[i];
if (dis[x] + e.cap < dis[e.v]) {
dis[e.v] = dis[x] + e.cap;
if (!vis[e.v]) {
vis[e.v] = 1;
q.push(e.v);
}
}
}
}
return dis[t];
}
int main() {
int n, m, u, v, cap;
while (~scanf("%d%d", &n, &m)) {
if (n == 1 || m == 1) {
if (n > m) swap(n, m);
int ans = inf;
for (int i = 1, a; i < m; ++i) {
scanf("%d", &a);
ans = min(ans, a);
}
printf("%d\n", ans == inf ? 0 : ans);
continue;
}
int s = 0, t = (m - 1) * 2 * (n - 1) + 1;
tot = 0;
memset(head, -1, sizeof(head));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m - 1; ++j) {
scanf("%d", &cap);
if (i == 1) { u = s; v = 2 * j; }
else if (i == n) { u = (m - 1) * (n - 2) * 2 + 2 * j - 1; v = t; }
else { v = (m - 1) * 2 * (i - 2) + 2 * j - 1; u = (m - 1) * 2 * (i - 1) + 2 * j; }
add(u, v, cap);
//printf("u = %d, v = %d, cap = %d\n", u, v, cap);
}
}
for (int i = 1; i < n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &cap);
if (j == 1) { v = t; u = (m - 1)*(i - 1) * 2 + 1; }
else if (j == m) { u = s; v = (m - 1) * i * 2; }
else { u = (m - 1) * (i - 1) * 2 + 2 * (j - 1); v = u + 1; }
add(u, v, cap);
//printf("u = %d, v = %d, cap = %d\n", u, v, cap);
}
}
for (int i = 1; i < n; ++i) {
for (int j = 1; j < m; ++j) {
scanf("%d", &cap);
u = (m - 1) * 2 * (i - 1) + 2 * j - 1;
v = u + 1;
add(u, v, cap);
//printf("u = %d, v = %d, cap = %d\n", u, v, cap);
}
}
printf("%d\n", spfa(s, t));
}
return 0;
} | true |
b9541fb4b0ff239c24acc8959ee6fd14978229d2 | C++ | suyuan945/LeetCode | /139_WordBreak/139_WordBreak.cpp | UTF-8 | 648 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
const int n = s.size();
vector<bool> dp(n+1, false);
dp[0] = true;
for (int i = 1; i <= n; ++i){
for (int j = i - 1; j >= 0; --j){
if (dp[j] && (find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end())){
dp[i] = true;
break;
}
}
}
return dp[n];
}
};
int main(int argc, char *argv[]){
Solution s;
cout << s.wordBreak("leetcode", vector<string>{"leet" , "code"}) << endl;
system("pause");
return 0;
} | true |
d1aef424040e456a1822fc5886c4ad06e1c3a895 | C++ | thecodingwizard/competitive-programming | /Infoarena/engineer.cpp | UTF-8 | 3,877 | 2.703125 | 3 | [] | no_license | /*
* Parallel binary search + BIT
*
* The time limit is ridiculously tight, so you basically can't use maps at all.
* Instead of using 2D BIT, you have to use 1D bit and just brute force loop through
* one dimension (no idea why this works but a 2D bit doesn't)
*/
#include <bits/stdc++.h>
using namespace std;
namespace FastIO {
const int BSZ = 1<<15; ////// INPUT
char ibuf[BSZ]; int ipos, ilen;
char nc() { // next char
if (ipos == ilen) {
ipos = 0; ilen = fread(ibuf,1,BSZ,stdin);
if (!ilen) return EOF;
}
return ibuf[ipos++];
}
void rs(string& x) { // read str
char ch; while (isspace(ch = nc()));
do { x += ch; } while (!isspace(ch = nc()) && ch != EOF);
}
template<class T> void ri(T& x) { // read int or ll
char ch; int sgn = 1;
while (!isdigit(ch = nc())) if (ch == '-') sgn *= -1;
x = ch-'0'; while (isdigit(ch = nc())) x = x*10+(ch-'0');
x *= sgn;
}
template<class T, class... Ts> void ri(T& t, Ts&... ts) {
ri(t); ri(ts...); } // read ints
////// OUTPUT (call initO() at start)
char obuf[BSZ], numBuf[100]; int opos;
void flushOut() { fwrite(obuf,1,opos,stdout); opos = 0; }
void wc(char c) { // write char
if (opos == BSZ) flushOut();
obuf[opos++] = c; }
void ws(string s) { for (auto &c : s) wc(c); } // write str
template<class T> void wi(T x, char after = '\0') { /// write int
if (x < 0) wc('-'), x *= -1;
int len = 0; for (;x>=10;x/=10) numBuf[len++] = '0'+(x%10);
wc('0'+x); for (int i = len-1; i; i--) wc(numBuf[i]);
if (after) wc(after);
}
void initO() { assert(atexit(flushOut) == 0); } /// auto-flush output
}
using namespace FastIO;
#define ii pair<int, int>
#define f first
#define s second
#define mp make_pair
#define pb push_back
struct query {
int x, y, a, b, k;
};
int n, m, q;
int A[1100][1100];
int L[1000], R[1000];
vector<query> queries;
int ft[1101][1101];
void reset() {
memset(ft, 0, sizeof(ft));
}
int qry(int x, int y) {
int s = 0;
while (y) {
s += ft[x][y];
y -= y&-y;
}
return s;
}
void upd(int x, int y, int v) {
while (y <= m) {
ft[x][y] += v;
y += y&-y;
}
}
// find number of ones in the rectangle defined by query i
int qryQuery(int i) {
query q = queries[i];
int s = 0;
for (int i = q.x; i <= q.a; i++) {
s += qry(i, q.b) - qry(i, q.y-1);
}
return s;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
freopen("engineer.in", "r", stdin);
freopen("engineer.out", "w", stdout);
ri(n, m);
vector<pair<int, ii>> things;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ri(A[i][j]);
things.pb(mp(A[i][j], mp(i, j)));
}
}
sort(things.begin(), things.end());
ri(q);
for (int i = 0; i < q; i++) {
int x, y, a, b, k; ri(x, y, a, b, k);
queries.pb(query{x,y,a,b,k});
L[i] = 0, R[i] = things.size();
}
vector<int> check[things.size()];
while (true) {
bool done = true;
reset();
for (int i = 0; i < q; i++) {
if (L[i] != R[i]) {
done = false;
check[(L[i]+R[i])/2].pb(i);
}
}
if (done) break;
for (int i = 0; i < things.size(); i++) {
auto thing = things[i].s;
upd(thing.f+1, thing.s+1, 1);
if (check[i].empty()) continue;
for (int qryIdx : check[i]) {
int num = qryQuery(qryIdx);
//cout << num << " " << qryIdx << " " << i << endl;
if (num >= queries[qryIdx].k) {
R[qryIdx] = i;
} else {
L[qryIdx] = i+1;
}
}
check[i].clear();
}
}
for (int i = 0; i < q; i++) {
cout << things[L[i]].f << "\n";
}
return 0;
}
| true |
217372d6ab539b1c14d6285123cad4f8d4fad4df | C++ | andy-c-huang/Hitchin | /discreteheatflowiterator.cpp | UTF-8 | 3,435 | 2.515625 | 3 | [] | no_license | #include "discreteheatflowiterator.h"
#include "liftedgraph.h"
template <typename Point, typename Map>
DiscreteHeatFlowIterator<Point, Map>::DiscreteHeatFlowIterator(const LiftedGraphFunction<Point, Map> *initialFunction) :
nbBoundaryPoints(initialFunction->nbBoundaryPoints), nbPoints(initialFunction->nbPoints),
neighborsIndices(initialFunction->neighborsIndices), neighborsWeights(initialFunction->neighborsWeights),
boundaryPointsNeighborsPairingsValues(initialFunction->boundaryPointsNeighborsPairingsValues), initialValues(initialFunction->getValues()),
outputFunction(initialFunction->cloneCopyConstruct())
{
reset();
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::reset()
{
newValues = initialValues;
errors.resize(nbPoints);
newNeighborsValuesKicked.resize(nbPoints);
uint i=0, j;
while(i != nbBoundaryPoints)
{
j=0;
for (auto neighborIndex : neighborsIndices[i])
{
newNeighborsValuesKicked[i].push_back(boundaryPointsNeighborsPairingsValues[i][j]*newValues[neighborIndex]);
++j;
}
++i;
}
while (i != nbPoints)
{
for (auto neighborIndex : neighborsIndices[i])
{
newNeighborsValuesKicked[i].push_back(newValues[neighborIndex]);
}
++i;
}
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::getOutputFunction(LiftedGraphFunction<Point, Map> *outputFunction)
{
refreshOutput();
outputFunction->cloneCopyAssign(this->outputFunction.get());
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::refreshOutput()
{
outputFunction->resetValues(newValues);
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::refreshNeighborsValuesKicked()
{
oldNeighborsValuesKicked = newNeighborsValuesKicked;
uint i=0, j;
while(i != nbBoundaryPoints)
{
j=0;
for (auto neighborIndex : neighborsIndices[i])
{
newNeighborsValuesKicked[i][j] = boundaryPointsNeighborsPairingsValues[i][j]*newValues[neighborIndex];
++j;
}
++i;
}
while (i != nbPoints)
{
j=0;
for (auto neighborIndex : neighborsIndices[i])
{
newNeighborsValuesKicked[i][j] = newValues[neighborIndex];
++j;
}
++i;
}
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::updateValues()
{
oldValues = newValues;
for (uint i=0; i!=nbPoints; ++i)
{
newValues[i] = H2Point::centroid(newNeighborsValuesKicked[i], neighborsWeights[i]);
}
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::iterate()
{
refreshNeighborsValuesKicked();
updateValues();
}
template <typename Point, typename Map>
void DiscreteHeatFlowIterator<Point, Map>::iterate(uint nbIterations)
{
for (uint i=0; i!=nbIterations; ++i)
{
iterate();
}
}
template <typename Point, typename Map>
double DiscreteHeatFlowIterator<Point, Map>::updateSupDelta()
{
for (uint i=0; i!=nbPoints; ++i)
{
errors[i] = Point::distance(oldValues[i], newValues[i]);
}
supDelta = *std::max_element(errors.begin(), errors.end());
return supDelta;
}
template class DiscreteHeatFlowIterator<H2Point, H2Isometry>;
| true |
6072fb14afe2688127d97d6e15779bb8df515d08 | C++ | renr3/HIGROTERM | /Source Code/A000_SourceCode_HIGROTERM_EnPtVersion_v0_4_DUE_Version/A40_drawConfigurationScreen.ino | UTF-8 | 1,235 | 3.328125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /* This function draws the Configuration Screen.
* When it finishes, it outputs the value of exit_flag, a byte variable.
* This variable indicates where to proceed next:
* - A output of 1 indicates the main code will proceed to Loading Screen;
* - A output of 2 indicates the main code will proceed to Monitoring Table Screen.
*/
byte drawConfigurationScreen () {
resetTouch();//Reset touch screen
currentPage = 3; // Indicates that we are at Configuration Screen
byte exit_flag = 0; /*While 0, sketch stays in Configuration Screen.
When not 0, sketch leaves Configuration Screen:
-When 1, it performs Loading Screen right after.
-When 2, it goes to Monitoring Table Screen.*/
int sliderY_min = 65;
int sliderY_max = sliderY_min + 15;
drawEntireConfigurationScreen(sliderY_min,sliderY_max);//Draws all graphical elements from this screen
while (exit_flag == 0) {
if (myTouch.dataAvailable()) {
myTouch.read();
exit_flag = getUserInput_ConfigurationScreen(sliderY_min,sliderY_max);
//Check the inputs the user may perform in the system while the Configuration Screen is displayed
}
}
return exit_flag;
}
| true |
aad60c05dd63ecfc8f9a0dbe4c8a3c4e8bc9c25e | C++ | vladopp/distributed-decipher | /common/vigenerecipher.h | UTF-8 | 661 | 2.515625 | 3 | [] | no_license | #ifndef VIGENERECIPHER_H
#define VIGENERECIPHER_H
#include <QString>
class VigenereCipher
{
public:
static QString encrypt(const QString& text, const QString& key);
static QString decrypt(const QString& text, const QString& key);
static int getProbableKeyLength(const QString& text);
private:
static double calculateIndexOfCoincidenceEveryNthLetter(const QString& text, const int n);
static QString getEveryNthLetter(const QString& text, const int n, const int startIdx);
static double calculateIndexOfCoincidence(const QString& text);
static int chooseMostProbableKeyLength(double probabilities[]);
};
#endif // VIGENERECIPHER_H
| true |