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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
673d26d409abd2186325457b61f346df8180ed20 | C++ | Mingrui-Yu/slambook2 | /my_implementation_2/ch6/ceresCurveFitting/ceresCurveFitting.cpp | UTF-8 | 2,395 | 2.65625 | 3 | [] | permissive | #include <iostream>
#include <chrono>
#include <Eigen/Core> // Eigen 核心部分
#include <Eigen/Dense> // 稠密矩阵的代数运算(逆,特征值等)
#include <Eigen/Geometry> // Eigen/Geometry 模块提供了各种旋转和平移的表示
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <ceres/ceres.h>
struct CURVE_FITTING_COST{
CURVE_FITTING_COST(double t, double y): _t(t), _y(y) {}
template<typename T>
bool operator() (const T *const x, T *residual) const {
residual[0] = T(_y) - ceres::exp(x[0]*T(_t)*T(_t) + x[1]*T(_t) + x[2]);
return true;
}
const double _t, _y;
};
int main(int argc, char **argv){
double a_e = 2.0, b_e = -1.0, c_e = 5.0; // 待拟合参数 及估计初值
double a = 1.0, b = 2.0, c = 1.0; // 待拟合参数 实际值
cv::RNG rng; // OpenCV 随机数产生器
double w_sigma = 1.0;
double inv_sigma = 1.0 / w_sigma;
// 生成数据
int num_data = 100;
std::vector<double> t_data, y_data;
for(int i = 0; i < num_data; i++){
double t = i / 100.0;
double y = exp(a*t*t + b*t + c) + rng.gaussian(w_sigma * w_sigma);
t_data.push_back(t);
y_data.push_back(y);
}
double x[3] = {a_e, b_e, c_e};
// 构建最小二乘问题
ceres::Problem problem;
for(int i = 0; i < num_data; i++){
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<CURVE_FITTING_COST, 1, 3>(new
CURVE_FITTING_COST(t_data[i], y_data[i])),
nullptr,
x
);
}
// 配置求解器
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;
options.minimizer_progress_to_stdout = true;
ceres::Solver::Summary summary;
std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
ceres::Solve(options, &problem, &summary);
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
std::chrono::duration<double> time_used = std::chrono::duration_cast <std::chrono::duration<double>> (t2 - t1);
std::cout << "time_cost = " << time_used.count() << "second" << std::endl;
std::cout << summary.BriefReport() << std::endl;
std::cout << "estimated_parameters = " << x[0] << " " << x[1] << " " << x[2] << std::endl;
return 0;
}
| true |
8f546bbd14120c2d55f49ca54a53e2a68e0b3dad | C++ | benreid24/BLIB | /include/BLIB/Events/SubscribeHelpers.hpp | UTF-8 | 1,324 | 2.625 | 3 | [] | no_license | #ifndef BLIB_EVENTS_SUBSCRIBEHELPERS_HPP
#define BLIB_EVENTS_SUBSCRIBEHELPERS_HPP
#include <BLIB/Events/SingleDispatcher.hpp>
namespace bl
{
namespace event
{
namespace priv
{
template<typename T>
struct SubscriberBase {
SubscriberBase(SingleDispatcher<T>& bus, ListenerBase<T>* l, bool defer) {
bus.addListener(l, defer);
}
};
template<typename... Ts>
struct SubscriberHelper : public SubscriberBase<Ts>... {
SubscriberHelper(std::vector<SingleDispatcherBase*>& dlist, std::mutex& dlock,
Listener<Ts...>* l, bool defer)
: SubscriberBase<Ts>(SingleDispatcher<Ts>::get(dlist, dlock), static_cast<ListenerBase<Ts>*>(l),
defer)... {}
};
template<typename T>
struct UnSubscriberBase {
UnSubscriberBase(SingleDispatcher<T>& bus, ListenerBase<T>* l, bool defer) {
bus.removeListener(l, defer);
}
};
template<typename... Ts>
struct UnSubscriberHelper : public UnSubscriberBase<Ts>... {
UnSubscriberHelper(std::vector<SingleDispatcherBase*>& dlist, std::mutex& dlock,
Listener<Ts...>* l, bool defer)
: UnSubscriberBase<Ts>(SingleDispatcher<Ts>::get(dlist, dlock),
static_cast<ListenerBase<Ts>*>(l), defer)... {}
};
} // namespace priv
} // namespace event
} // namespace bl
#endif
| true |
c12cdd35fd8e0beade5a0b18f75f5b8a6da44f3d | C++ | jiadaizhao/LeetCode | /1101-1200/1180-Count Substrings with Only One Distinct Letter/1180-Count Substrings with Only One Distinct Letter.cpp | UTF-8 | 342 | 3.109375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int countLetters(string S) {
int total = 0, start = 0;
for (int i = 0; i <= S.size(); ++i) {
if (i == S.size() || S[i] != S[start]) {
total += (i - start) * (i - start + 1) / 2;
start = i;
}
}
return total;
}
};
| true |
092004983ca595e609d78ec7da4ffe80beb082a1 | C++ | shultays/ingenue | /lexer_cpp/Tools.cpp | UTF-8 | 2,948 | 2.6875 | 3 | [] | no_license | #include "Tools.h"
#include<assert.h>
const char* operatorStrings[] = {
"err",
"+",
"-",
"*",
"/",
"%",
"==",
"!=",
">",
">=",
"<",
"<=",
"++",
"--",
"-",
"+",
"!",
};
const char* tokenNames[Tt_count];
const char* defaultFuncNames[Df_count];
void buildTools() {
assert(sizeof(float) == 4);
defaultFuncNames[Df_print] = "print";
defaultFuncNames[Df_scan] = "scan";
defaultFuncNames[Df_assert] = "assert";
defaultFuncNames[Df_exit] = "exit";
tokenNames[Tt_whitespace] = "whitespace";
tokenNames[Tt_comment_single] = "comment_single";
tokenNames[Tt_comment_multi] = "comment_multi";
tokenNames[Tt_ws] = "ws";
tokenNames[Tt_empty] = "empty";
tokenNames[Tt_integer] = "integer";
tokenNames[Tt_float] = "float";
tokenNames[Tt_operator] = "operator";
tokenNames[Tt_semicolon] = "semicolon";
tokenNames[Tt_if] = "if";
tokenNames[Tt_p_left] = "p_left";
tokenNames[Tt_p_right] = "p_right";
tokenNames[Tt_cp_left] = "cp_left";
tokenNames[Tt_cp_right] = "cp_right";
tokenNames[Tt_for] = "for";
tokenNames[Tt_while] = "while";
tokenNames[Tt_do] = "do";
tokenNames[Tt_string] = "string";
tokenNames[Tt_variable] = "variable";
tokenNames[Tt_singleoperator] = "singleoperator";
tokenNames[Tt_variable_withpost] = "variable_withpost";
tokenNames[Tt_variable_withpre] = "variable_withpre";
tokenNames[Tt_unary] = "unary";
tokenNames[Tt_value] = "value";
tokenNames[Tt_value_one] = "value_one";
tokenNames[Tt_assignment] = "assignment";
tokenNames[Tt_func_call] = "func_call";
tokenNames[Tt_statement] = "statement";
tokenNames[Tt_multiple_statement] = "multiple_statement";
tokenNames[Tt_return] = "return";
tokenNames[Tt_break] = "break";
tokenNames[Tt_ifcond] = "ifcond";
tokenNames[Tt_forloop] = "forloop";
tokenNames[Tt_whileloop] = "whileloop";
tokenNames[Tt_dowhileloop] = "dowhileloop";
tokenNames[Tt_func_def] = "func_def";
tokenNames[Tt_else] = "else";
tokenNames[Tt_program] = "program";
tokenNames[Tt_assign] = "assign";
tokenNames[Tt_variable_def] = "variable_def";
//tokenNames[Tt_value_with_unary] = "value_with_unary";
tokenNames[Tt_invalid] = "invalid";
}
const char* getTokenName(TokenType type) {
return tokenNames[type];
}
const char* getDefaultFunctionName(int f) {
return defaultFuncNames[f];
}
int getDefaultFunctionEnum(const char* name) {
for (int i = 0; i < Df_count; i++) {
if (strncmp(defaultFuncNames[i], name, strlen(defaultFuncNames[i])) == 0) {
return (DefaltFunction)i;
}
}
return Df_invalid;
}
const char* getOperatorString(int type) {
return operatorStrings[type];
}
bool isOperatorUnion(OperatorType op) {
return op >= Op_inc;
}
int floatToStr(float num, char* str, int max) {
#ifdef _WIN32
return sprintf_s(str, max, "%f", num);
#else
return snprintf(str, max, "%f", num);
#endif
}
int intToStr(int num, char* str, int max) {
#ifdef _WIN32
return sprintf_s(str, max, "%d", num);
#else
return snprintf(str, max, "%d", num);
#endif
}
| true |
57be17bf3bd74da65a3c33f09343ce3329f7c1de | C++ | svineet/competitive_programming | /codeforces/alyoni_copybooks.cpp | UTF-8 | 471 | 2.796875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, a, b, c;
cin >> n >> a >> b >> c;
if (n%4 == 0) {
cout << 0 << endl;
return 0;
}
long long left = ((n - n%4)/4 + 1)*4 - n;
if (left == 3) {
cout << min({c, 3*a, a+b}) << endl;
} else if (left == 2) {
cout << min({b, 2*b, 2*a, 2*c}) << endl;
} else if (left == 1) {
cout << min({a, b+c, 3*c}) << endl;
}
return 0;
}
| true |
0cfa4fab6cb4f7efa5aad2f9ff7cdac9fbc3e228 | C++ | rkwagner/dp176easyCPP | /pivot.cpp | UTF-8 | 1,299 | 3.46875 | 3 | [] | no_license | //-------------------------------------------------------------
//Author: Ryan Wagner
//Date: August 22, 2014
//Description:Pivot Table (Dailyprogrammer Challenge #176 Easy)
//Input: Text file windfarm.dat
//Output: Pivot utilizing the three input fields.
//-------------------------------------------------------------
#include<iostream>
#include<fstream>
#include<string>
struct results{
int terminal[10];
std::string day[7];
int kWh[10][7];
};
results buildResults(int i){
results res={{1000,1001,1002,1003,1004,1005,1006,1007,1008,1009},
{"Mon","Tue","Wed","Thu","Fri","Sat","Sun"},0};
int terminal,kWh;
std::string day;
std::ifstream infile("windfarm.dat");
while(infile>>terminal>>day>>kWh){
for(i=0;day.compare(res.day[i]);i++);
res.kWh[terminal-1000][i]+=kWh;
}
infile.close();
return res;
}
void printChart(results res,int i, int j){
for(i=0;i<7;i++){
std::cout<<"\t"<<res.day[i];
}
std::cout<<'\n';
for(i=0;i<sizeof(res.terminal)/sizeof(res.terminal[0]);i++){
std::cout<<res.terminal[i]<<"\t";
for(j=0;j<sizeof(res.day)/sizeof(res.day[0]);j++){
std::cout<<res.kWh[i][j]<<"kWh\t";
}
std::cout<<'\n';
}
}
int main(void){
int i,j;
results res = buildResults(i);
printChart(res, i, j);
return 0;
}
| true |
d53990b4450ea97af1eec7b6b31a5a90d6404226 | C++ | sepidehsaran/appfs | /Sanny/ex8/src/c/ex8.cpp | UTF-8 | 4,800 | 3.125 | 3 | [
"MIT"
] | permissive | /**
* Exercise 8 : Read in a gph-file, interpretes it as a Steiner-problem and solves it.
*
* @author FirstSanny
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <utility>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "Steiner.h"
#include "GraphChecker.h"
// Constants
namespace {
const char* FILEEND = ".gph";
}
// declaring print
using std::cout;
using std::endl;
using std::flush;
using std::cerr;
using std::string;
// declaring types
namespace po = boost::program_options;
/** Parsing the arguments given via command line */
po::variables_map parseCommandLine(po::options_description desc, int argn,
char* argv[]) {
desc.add_options()//
("help,h", "produce help message")//
("start_node,sn", po::value<std::vector<int >>(),"node, where to start")//
("input-file", po::value<string>(), "input file");
po::positional_options_description p;
p.add("input-file", 1);
p.add("start_node", -1);
po::variables_map vm;
po::store(
po::command_line_parser(argn, argv).options(desc).positional(p).run(),
vm);
po::notify(vm);
return vm;
}
/** Reading in a Graphfile, computes the Steiner */
int main(int argn, char *argv[]) {
boost::timer::auto_cpu_timer t;
if (argn <= 1) {
cerr << "ERROR : There was no filename" << endl;
return 1;
}
po::options_description desc("Allowed options");
po::variables_map vm = parseCommandLine(desc, argn, argv);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
std::ifstream fileStream;
if(vm.count("input-file") == 0){
cerr << "No input-file was given!" << endl;
return 1;
}
std::vector<int > startnodes;
if(vm.count("start_node") == 0){
cout << "using default startnode 2" << endl;
startnodes = std::vector<int >();
startnodes.push_back(2);
} else {
startnodes = vm["start_node"].as<std::vector<int >>();
}
string filename = vm["input-file"].as<string >();
if(filename.find(FILEEND) == std::string::npos){
filename += FILEEND;
}
cout << "Going to parse the file " << filename << endl;
fileStream.open(filename.c_str(), std::ios::in);
if ( (fileStream.rdstate()) != 0 ){
std::perror("ERROR : Encoutered Problem opening file");
return 1;
}
string line;
unsigned int edgeCount;
unsigned int vertexCount;
if(std::getline(fileStream, line)){
sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount);
cout << "Vertexcount: " << vertexCount << endl;
cout << "Edgecount: " << edgeCount << endl;
line.clear();
vertexCount++;
} else {
cerr << "ERROR : File was empty" << endl;
return 1;
}
Edges* edges = new Edges(edgeCount);
Weights* weights = new Weights(edgeCount);
cout << "Reading edges..." << flush;
int i = 0;
while (getline(fileStream, line)) {
int start;
int end;
double weight;
int count = sscanf(line.c_str(), "%d %d %lf", &start, &end, &weight);
if (count != 3) {
line.clear();
continue;
}
edges->at(i) = std::make_pair(start, end);
weights->at(i) = weight;
i++;
line.clear();
}
cout << "done" << endl << endl;
Steiner** steiners = new Steiner*[startnodes.size()];
cout << "Solves Steiner problem for startnodes ";
for(unsigned int i = 0; i < startnodes.size(); i++){
cout << startnodes[i];
if(i != startnodes.size() - 1){
cout << ", ";
} else {
cout << endl;
}
}
#pragma omp parallel for
for(unsigned int i = 0; i < startnodes.size(); i++){
steiners[i] = new Steiner();
steiners[i]->steiner(vertexCount, edges, *weights, startnodes[i]);
cout << "Objective value of Steiner-tree for startnode " << startnodes[i] << ": " << steiners[i]->getWeight() << endl;
}
Steiner* s = steiners[0];
int node = startnodes[0];
int weight = s->getWeight();
cout << "Searching the one with least weight..." << flush;
for(unsigned int i = 0; i < startnodes.size(); i++){
if(weight > steiners[i]->getWeight()){
s = steiners[i];
node = startnodes[i];
weight = steiners[i]->getWeight();
}
}
cout << "done" << endl;
cout << "It's the one with startnode " << node << endl << endl;
cout << "Checking for cycle..." << flush;
Edges steinerEdges = s->getEdges();
GraphChecker* checker = new GraphChecker(steinerEdges, s->getNodes());
if(checker->hasCycle()){
cout << "failed" << endl;
return 1;
}
cout << "passed" << endl;
cout << "Checking if graph is connected..." << flush;
if(!checker->isConnected()){
cout << "failed" << endl;
return 1;
}
cout << "passed" << endl << endl;
cout << "Edges:" << endl;
for(unsigned int i = 0; i < steinerEdges.size(); i++){
Edge edge = steinerEdges[i];
cout << edge.first << " " << edge.second << endl;
}
delete edges;
delete weights;
delete checker;
for(unsigned int i = 0; i < startnodes.size(); i++){
delete steiners[i];
}
delete [] steiners;
return 0;
}
| true |
b01609951382707054653763a6198b81cfed110e | C++ | jaya6400/Coding | /RangeSumQuerySolution.cpp | UTF-8 | 590 | 3.328125 | 3 | [] | no_license | class NumArray {
public:
vector<int> vec;
NumArray(vector<int>& nums) {
vec = nums;
// if(nums.size() > 0){
// vec[0] = nums[0];
// for(int i = 1; i < nums.size(); i++){
// vec[i] = vec[i-1] + vec[i];
// }
// }
}
int sumRange(int left, int right) {
int sum = 0;
//if(left == 0)
// return vec[right];
// return vec[right] - vec[left-1];
for(int i = left; i <= right; i++){
sum+=vec[i];
}
return sum;
}
};
| true |
aad36f89b5505773e52b0117709b0761101eeadf | C++ | grvx24/KsiazkaKucharskaDemo | /KsiazkaKucharskaDemo/main.cpp | WINDOWS-1250 | 10,126 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <list>
#include <conio.h>
#include <windows.h>
#include <fstream>
using namespace std;
enum class Typ_potrawy { owoc, warzywo, mieso, nabial, zbozowe, inne };
class Produkt
{
private:
string nazwa, ilosc;
Typ_potrawy typ;
void napis_jako_typ()
{
int wybor;
cout << "Podaj odpowiedni nr: 1.owoc 2.warzywo 3.mieso 4.nabial 5.zbozowe 6.inne" << endl;
cin >> wybor;
switch (wybor)
{
case 1:
{
typ = Typ_potrawy::owoc;
}break;
case 2:
{
typ = Typ_potrawy::warzywo;
}break;
case 3:
{
typ = Typ_potrawy::mieso;
}break;
case 4:
{
typ = Typ_potrawy::nabial;
}break;
case 5:
{
typ = Typ_potrawy::zbozowe;
}break;
case 6:
{
typ = Typ_potrawy::inne;
}break;
default:
break;
}
}
public:
Produkt() :nazwa("domyslne"), ilosc("domyslne"), typ(Typ_potrawy::inne) {}
Produkt(string nazwa, string ilosc, Typ_potrawy typ) :nazwa(nazwa), ilosc(ilosc), typ(typ)
{
}
~Produkt()
{
}
string typ_jako_napis()
{
switch (typ)
{
case Typ_potrawy::owoc:
{
return "owoc";
}
break;
case Typ_potrawy::warzywo:
{
return "warzywo";
}
break;
case Typ_potrawy::mieso:
{
return "mieso";
}
break;
case Typ_potrawy::nabial:
{
return "nabial";
}
break;
case Typ_potrawy::zbozowe:
{
return "zbozowe";
}
case Typ_potrawy::inne:
{
return "inne";
}
break;
default:
{
return "nieznany";
}
break;
}
}
void ustaw_nazwe()
{
cout << "Podaj nazw skadnika" << endl;
cin >> nazwa;
}
void ustaw_typ()
{
napis_jako_typ();
}
void ustaw_ilosc()
{
cout << "Podaj ilosc" << endl;
cin >> ilosc;
}
string get_nazwa() { return this->nazwa; }
string get_ilosc() { return this->ilosc; }
friend ostream& operator<<(ostream &out, Produkt &produkt);
};
ostream& operator<<(ostream &out, Produkt &produkt)
{
return out << produkt.nazwa << " " << produkt.ilosc << endl;
}
class Posilek
{
protected:
string nazwa, przepis;
vector<Produkt> produkty;
public:
Posilek(string nazwa, string ilosc, string przepis) :nazwa(nazwa), przepis(przepis) {}
virtual void dodaj_skladnik()
{
int liczba = 1;
while (liczba == 1)
{
Produkt produkt;
produkt.ustaw_nazwe();
produkt.ustaw_ilosc();
produkt.ustaw_typ();
produkty.push_back(produkt);
cout << "Czy dodac kolejny skladnik? 1. Tak 2.Nie" << endl;
cin >> liczba;
if (liczba != 1)
{
cout << "Podaj przepis: ";
cin.ignore();
getline(cin, przepis);
}
}
}
virtual void wypisz_posilek()
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
cout << "Nazwa potrawy: " << this->nazwa << endl;
cout << "===============================" << endl;
cout << "Skladniki" << endl;
cout << endl;
for (auto it = produkty.begin(); it != produkty.end(); it++)
{
cout << *it << endl;
}
cout << "Przepis" << endl;
cout << this->przepis << endl;
}
virtual string get_nazwa() { return this->nazwa; }
virtual string get_przepis() { return this->przepis; }
virtual vector<Produkt> get_produkty() { return this->produkty; }
};
class Sniadanie : public Posilek
{
private:
public:
Sniadanie(string nazwa, string ilosc, string przepis) :Posilek((nazwa), (ilosc), (przepis)) {}
};
class Obiad : public Posilek
{
private:
public:
Obiad(string nazwa, string ilosc, string przepis) :Posilek((nazwa), (ilosc), (przepis)) {}
};
class Kolacja : public Posilek
{
private:
public:
Kolacja(string nazwa, string ilosc, string przepis) :Posilek((nazwa), (ilosc), (przepis)) {}
};
class Deser : public Posilek
{
private:
public:
Deser(string nazwa, string ilosc, string przepis) :Posilek((nazwa), (ilosc), (przepis)) {}
};
class Interfejs
{
int wybor;
public:
void menu()
{
list<Sniadanie> lista_sniadan;
list<Obiad> lista_obiadow;
list<Kolacja> lista_kolacji;
list<Deser> lista_deserow;
for (;;)
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_BLUE);
cout << endl;
cout << "1: Dodaj sniadanie" << endl;
cout << "2: Wyswietl sniadania" << endl;
cout << "3: Usun sniadanie" << endl;
cout << "4: Dodaj obiad" << endl;
cout << "5: Wyswietl obiady" << endl;
cout << "6: Usun obiad" << endl;
cout << "7: Dodaj kolacje" << endl;
cout << "8: Wyswietl kolacje" << endl;
cout << "9: Usun kolacje" << endl;
cout << "10: Dodaj deser" << endl;
cout << "11: Wyswietl desery" << endl;
cout << "12: Usun deser" << endl;
cout << "13 Wyjscie z programu " << endl;
cin >> wybor;
switch (wybor)
{
case 1:
{
string nazwa, ilosc, przepis;
cout << "Podaj nazwe posilku" << endl;
getline(cin, nazwa);
getline(cin, nazwa);
Sniadanie sniadanie(nazwa, ilosc, przepis);
sniadanie.dodaj_skladnik();
lista_sniadan.push_back(sniadanie);
system("cls");
}break;
case 2:
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
int licznik1 = 0;
for (auto it = lista_sniadan.begin(); it != lista_sniadan.end(); it++)
{
++licznik1;
cout << licznik1 << " ";
(*it).wypisz_posilek();
cout << endl;
}
}break;
case 3:
{
int licznik2 = 0;
for (auto it = lista_sniadan.begin(); it != lista_sniadan.end(); it++)
{
++licznik2;
cout << licznik2 << " ";
(*it).wypisz_posilek();
cout << endl;
}
int licznik3 = 0;
int pozycja;
cin >> pozycja;
for (auto it = lista_sniadan.begin(); it != lista_sniadan.end();)
{
licznik3++;
if (licznik3 == pozycja)
it = lista_sniadan.erase(it);
else
++it;
}
}break;
case 4:
{
string nazwa, ilosc, przepis;
cout << "Podaj nazwe posilku" << endl;
getline(cin, nazwa);
getline(cin, nazwa);
Obiad obiad(nazwa, ilosc, przepis);
obiad.dodaj_skladnik();
lista_obiadow.push_back(obiad);
system("cls");
}break;
case 5:
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
int licznik4 = 0;
for (auto it = lista_obiadow.begin(); it != lista_obiadow.end(); it++)
{
++licznik4;
cout << licznik4 << " ";
(*it).wypisz_posilek();
cout << endl;
}
}break;
case 6:
{
int licznik5 = 0;
for (auto it = lista_obiadow.begin(); it != lista_obiadow.end(); it++)
{
++licznik5;
cout << licznik5 << " ";
(*it).wypisz_posilek();
cout << endl;
}
int licznik6 = 0;
int pozycja;
cin >> pozycja;
for (auto it = lista_obiadow.begin(); it != lista_obiadow.end();)
{
licznik6++;
if (licznik6 == pozycja)
it = lista_obiadow.erase(it);
else
++it;
}
}break;
case 7:
{
string nazwa, ilosc, przepis;
cout << "Podaj nazwe posilku" << endl;
getline(cin, nazwa);
getline(cin, nazwa);
Kolacja kolacja(nazwa, ilosc, przepis);
kolacja.dodaj_skladnik();
lista_kolacji.push_back(kolacja);
system("cls");
}break;
case 8:
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
int licznik7 = 0;
for (auto it = lista_kolacji.begin(); it != lista_kolacji.end(); it++)
{
++licznik7;
cout << licznik7 << " ";
(*it).wypisz_posilek();
cout << endl;
}
}break;
case 9:
{
int licznik8 = 0;
for (auto it = lista_kolacji.begin(); it != lista_kolacji.end(); it++)
{
++licznik8;
cout << licznik8 << " ";
(*it).wypisz_posilek();
cout << endl;
}
int licznik9 = 0;
int pozycja;
cin >> pozycja;
for (auto it = lista_kolacji.begin(); it != lista_kolacji.end();)
{
licznik9++;
if (licznik9 == pozycja)
it = lista_kolacji.erase(it);
else
++it;
}
}break;
case 10:
{
string nazwa, ilosc, przepis;
cout << "Podaj nazwe posilku" << endl;
getline(cin, nazwa);
getline(cin, nazwa);
Deser deser(nazwa, ilosc, przepis);
deser.dodaj_skladnik();
lista_deserow.push_back(deser);
system("cls");
}break;
case 11:
{
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
int licznik10 = 0;
for (auto it = lista_deserow.begin(); it != lista_deserow.end(); it++)
{
++licznik10;
cout << licznik10 << " ";
(*it).wypisz_posilek();
cout << endl;
}
}break;
case 12:
{
int licznik11 = 0;
for (auto it = lista_deserow.begin(); it != lista_deserow.end(); it++)
{
++licznik11;
cout << licznik11 << " ";
(*it).wypisz_posilek();
cout << endl;
}
int licznik = 0;
int pozycja;
cin >> pozycja;
for (auto it = lista_deserow.begin(); it != lista_deserow.end();)
{
licznik++;
if (licznik == pozycja)
it = lista_deserow.erase(it);
else
++it;
}
}break;
case 13:
{
exit(0);
}
case 14:
{
fstream plik;
plik.open("sniadania.txt", ios::out);
for (auto it = lista_sniadan.begin(); it != lista_sniadan.end(); it++)
{
string nazwa_potrawy = (*it).get_nazwa();
plik << nazwa_potrawy;
plik << endl;
std::vector<Produkt> produkty = (*it).get_produkty();
for (int i = 0; i < produkty.size(); i++)
{
string nazwa_produktu = produkty[i].get_nazwa();
string ilosc = produkty[i].get_ilosc();
string typ = produkty[i].typ_jako_napis();
plik << nazwa_produktu << " " << ilosc << " " << typ << endl;
}
string przepis = (*it).get_przepis();
plik << "Przepis" << endl;
plik << przepis << endl;
}
cout << "Zapisano w pliku" << endl;
plik.close();
}break;
default:
break;
}
}
}
void zapis();
void odczyt();
};
int main()
{
Interfejs program;
program.menu();
int x;
cin >> x;
return 0;
} | true |
82a50e5f9b97515cab19f61fabbf5b1707533444 | C++ | xiangruipuzhao/c_plus_primer_3 | /c_primer_plus_3/class_21.3/main.cpp | GB18030 | 1,271 | 3.890625 | 4 | [] | no_license | #include<iostream>
#include<set>
#include<string>
#include<algorithm>
using namespace std;
class CCompareStringNoCase
{
public://ԪνݲַַСдʽȻбȽ
bool operator()(const string& str1, const string& str2) const
{
string str1LowerCase;
str1LowerCase.resize(str1.size());
transform(str1.begin(), str1.end(), str1LowerCase.begin(), towlower);
string str2LowerCase;
str2LowerCase.resize(str2.size());
transform(str2.begin(), str2.end(), str2LowerCase.begin(), tolower);
return (str1LowerCase < str2LowerCase);
//classĺһںķʽش֮
}
};
int main()
{
//setһʱݵͣڶһԪνʣͨclassԪν
set<string, CCompareStringNoCase> names;
names.insert("Tina");
names.insert("jim");
names.insert("jack");
names.insert("Sam");
names.insert("hello");
set<string, CCompareStringNoCase>::iterator iNameFound = names.find("Jim");
if (iNameFound != names.end())
{
cout << "ҵˣ" << *iNameFound << endl;
}
else
{
cout << "ûҵ" << endl;
}
return 0;
} | true |
18bbf698435a4264d9171580e46c10c0bcee2376 | C++ | soulsystem00/bj_2798 | /bj_2798/bj_11723.cpp | UTF-8 | 1,053 | 2.5625 | 3 | [] | no_license | //#include <iostream>
//#include <set>
//#include <string>
//using namespace std;
//
//int arr[21];
//
//int main()
//{
// cin.tie(NULL);
// ios_base::sync_with_stdio(false);
// int n;
// cin >> n;
// cin.ignore();
// for (int t = 0; t < n; t++)
// {
//
// string str;
// getline(cin, str);
//
// if (str.substr(0, 3) == "add")
// {
// int tmp = stoi(str.substr(4, str.length()));
// arr[tmp] = 1;
// }
// else if (str.substr(0, 6) == "remove")
// {
// int tmp = stoi(str.substr(7, str.length()));
// arr[tmp] = 0;
// }
// else if (str.substr(0, 5) == "check")
// {
// int tmp = stoi(str.substr(6, str.length()));
// cout << arr[tmp] << '\n';
// }
// else if (str.substr(0, 6) == "toggle")
// {
// int tmp = stoi(str.substr(7, str.length()));
// arr[tmp] = !arr[tmp];
// }
// else if (str.substr(0, 3) == "all")
// {
// for (int i = 1; i <= 20; i++)
// {
// arr[i] = 1;
// }
// }
// else if (str.substr(0, 5) == "empty")
// {
// for (int i = 1; i <= 20; i++)
// {
// arr[i] = 0;
// }
// }
// }
//} | true |
da2fb59936cd9a121d82428d0855b98ba8ec742c | C++ | kyduke/Coding | /AlgoSpot/WITHDRAWAL.cpp | UTF-8 | 1,100 | 2.984375 | 3 | [] | no_license | // https://algospot.com/judge/problem/read/WITHDRAWAL
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
const int SIZE = 1000;
int ranks[SIZE];
int classes[SIZE];
int n, k;
bool decision(double rank) {
vector<double> arr;
int i;
double v;
for (i = 0; i < n; i++) {
v = rank * classes[i] - ranks[i];
arr.push_back(v);
}
sort(arr.begin(), arr.end());
v = 0;
for (i = n - 1; i >= n - k; i--) {
v += arr[i];
}
return (v >= 0.0);
}
double solve() {
double low, hi, mid;
int i;
low = 0.0;
hi = 1.0;
i = 100;
while (i) {
mid = (low + hi) / 2.0;
if (decision(mid) == true) {
hi = mid;
} else {
low = mid;
}
i--;
}
return hi;
}
int main(int argc, char* argv[]) {
int T, i;
cin >> T;
while (T--) {
cin >> n >> k;
i = 0;
while (i < n) {
cin >> ranks[i] >> classes[i];
i++;
}
printf("%.10f\n", solve());
}
return 0;
}
/*
3
3 2
1 4 6 10 10 17
4 2
4 8 9 12 3 10 2 5
10 5
70 180 192 192 1 20 10 200 6 102 60 1000 4 9 1 12 8 127 100 700
=====
0.5000000000
0.3333333333
0.0563991323
*/
| true |
e58540faf91eeed20712f36030e96bc3c9c33c72 | C++ | sogapalag/problems | /atcoder/dwango6d.cpp | UTF-8 | 3,290 | 2.625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
void __solve() {
int n; cin >> n;
vector<int> a(n), indeg(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
a[i]--;
indeg[a[i]]++;
}
if (n == 2) {
cout << -1; return;
}
set<int> bucket;
set<pair<int,int>> lookup;
for (int i = 0; i < n; i++) {
bucket.insert(i);
lookup.insert({indeg[i], i});
}
vector<int> p(n);
vector<bool> trk(n);
const int L = 3;
for (int i = 0; i < n-L; i++) {
auto it = --lookup.end();
int cnt,z;
tie(cnt,z) = *it;
for (int x: bucket) {
if (i == 0 || a[p[i-1]] != x) {
// if erase x, no invalid
if (z == x || cnt - (i && a[p[i-1]]==z) < n-i-1) {
p[i] = x;
break;
}
}
}
if (i > 0) {
int x = a[p[i-1]];
if (!trk[x]) {
lookup.erase({indeg[x],x});
lookup.insert({--indeg[x], x});
}
}
trk[p[i]] = true;
bucket.erase(p[i]);
lookup.erase({indeg[p[i]], p[i]});
}
for (int i = max(0, n-L); i < n; i++) {
p[i] = *bucket.begin();
bucket.erase(p[i]);
}
do {
bool yes = true;
for (int i = max(1, n-L); i < n; i++) {
if (a[p[i-1]] == p[i]) yes = false;
}
if (yes) {
for (int x: p) cout << x+1 << ' ';
return;
}
} while (next_permutation(p.begin(), p.end()));
}
// the key is whenever we ensure no (max indeg)node that cannot put anywhere. i.e. deg = n-i-1. full
// then we're fine till the end, except n=3, no u->v, v->u. case. we can ignore that. use next_perm. 3! at most.
void solve() {
int n; cin >> n;
vector<int> a(n), indeg(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
a[i]--;
indeg[a[i]]++;
}
if (n == 2) {
cout << -1; return;
}
set<int> bucket;
for (int i = 0; i < n; i++) {
bucket.insert(i);
}
vector<int> p(n);
vector<bool> trk(n);
const int L = 3;
for (int i = 0; i < n-L; i++) {
// cost is might need to find max-deg in the back.
// don't happen much, since total deg <= n
for (int x: bucket) {
if (i == 0 || a[p[i-1]] != x) {
// if erase x, no invalid
if (trk[a[x]] || indeg[a[x]] - (i && a[p[i-1]]==a[x]) < n-i-1) {
p[i] = x;
break;
}
}
}
if (i > 0) {
int x = a[p[i-1]];
if (!trk[x]) indeg[x]--;
}
trk[p[i]] = true;
bucket.erase(p[i]);
}
for (int i = max(0, n-L); i < n; i++) {
p[i] = *bucket.begin();
bucket.erase(p[i]);
}
do {
bool yes = true;
for (int i = max(1, n-L); i < n; i++) {
if (a[p[i-1]] == p[i]) yes = false;
}
if (yes) {
for (int x: p) cout << x+1 << ' ';
return;
}
} while (next_permutation(p.begin(), p.end()));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| true |
06a724bad2c8872fafc175222d5b2db0cc081974 | C++ | apolukhin/Boost-Cookbook | /Chapter06/01_tasks_processor_base/main.cpp | UTF-8 | 1,314 | 2.890625 | 3 | [
"BSL-1.0"
] | permissive | // Amost all the code for this example is in this header
#include "tasks_processor_base.hpp"
using namespace tp_base;
int func_test() {
static int counter = 0;
++ counter;
boost::this_thread::interruption_point();
switch (counter) {
case 3:
throw std::logic_error("Just checking");
case 10:
// Emulation of thread interruption.
// Caught inside task_wrapped and does not stop execution.
throw boost::thread_interrupted();
case 30:
// Throwing exception not derived from std::exception.
throw 1;
case 90:
// Stopping the tasks_processor.
tasks_processor::stop();
}
return counter;
}
int main () {
for (std::size_t i = 0; i < 100; ++i) {
tasks_processor::push_task(&func_test);
}
// Processing was not started.
assert(func_test() == 1);
// We can also use lambda as a task.
#ifndef BOOST_NO_CXX11_LAMBDAS
// Counting 2 + 2 asynchronously.
int sum = 0;
tasks_processor::push_task(
[&sum]() { sum = 2 + 2; }
);
// Processing was not started.
assert(sum == 0);
#endif
// Does not throw, but blocks till
// one of the tasks it is owning
// calls tasks_processor::stop().
tasks_processor::start();
assert(func_test() >= 91);
}
| true |
a1fe43fad24468472d5b535a4a87613f6ea20d05 | C++ | MFA8CL/OOP-Text-based-adventure-game-in-c-for-PHYS30672 | /Characters/NPCs/alchemist.cpp | UTF-8 | 3,923 | 3.28125 | 3 | [] | no_license | #include "alchemist.h"
alchemist::alchemist() {
type = "alchemist";
health = 100;
}
int alchemist::converse(player& p) {
bool still_talking(true);
cout << "\n" << "Alchemist: 'Alright? I'm the alchemist, got an assortment of funky fresh potions here'\n" << endl;
cout << '1' << " = " << "Purchase a health potion (50 gold)" << endl;
cout << '2' << " = " << "Purchase a shield potion (100 gold)" << endl;
cout << '3' << " = " << "Purchase a damage potion (50 gold)" << endl;
cout << '4' << " = " << "View potion descriptions" << endl;
cout << '0' << " = " << "End conversation" << endl;
do {
int answer;
while ((cin >> answer).fail() || cin.peek() != '\n' || answer > 4 || answer < 0)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter one of the given options" << endl;
}
switch (answer) {
case 0:
still_talking = false;
case 1:
if (p.get_gold() < 50) {
cout << "Insufficient funds!" << endl;
}
else {
cout << "here u go" << endl;
gift_item(p, "health potion", 50);
cout << '1' << " = " << "Purchase a health potion (50 gold)" << endl;
cout << '2' << " = " << "Purchase a shield potion (100 gold)" << endl;
cout << '3' << " = " << "Purchase a damage potion (50 gold)" << endl;
cout << '4' << " = " << "View potion descriptions" << endl;
cout << '0' << " = " << "End conversation" << endl;
}
break;
case 2:
if (p.get_gold() < 100) {
cout << "Insufficient funds!" << endl;
}
else {
gift_item(p, "shield potion", 100);
cout << '1' << " = " << "Purchase a health potion (50 gold)" << endl;
cout << '2' << " = " << "Purchase a shield potion (100 gold)" << endl;
cout << '3' << " = " << "Purchase a damage potion (50 gold)" << endl;
cout << '4' << " = " << "View potion descriptions" << endl;
cout << '0' << " = " << "End conversation" << endl;
}
break;
case 3:
if (p.get_gold() < 50) {
cout << "Insufficient funds!" << endl;
}
else {
gift_item(p, "damage potion", 50);
cout << '1' << " = " << "Purchase a health potion (50 gold)" << endl;
cout << '2' << " = " << "Purchase a shield potion (100 gold)" << endl;
cout << '3' << " = " << "Purchase a damage potion (50 gold)" << endl;
cout << '4' << " = " << "View potion descriptions" << endl;
cout << '0' << " = " << "End conversation" << endl;
}
break;
case 4:
cout << "\nHealth potion: Restores health to 100 but no higher\n";
cout<< "Shield potion: Adds 50 health onto any health value with no upper limit\n";
cout << "Damage potion: Adds 50 damage to any strike against an enemy on a one time basis\n";
cout << "Disclaimer: All potions have temporary effects and thus can only be used in the heat of battle, so choose wisely\n";
break;
default:
cout << "Please choose one of the numbered options" << endl;
}
} while (still_talking);
return 0;
}
alchemist::~alchemist() {};
string alchemist::get_type() const { return type; };
void alchemist::gift_item(player& p, string type, int cost) {
if (type =="shield potion"){
shared_ptr<potion> newshield = { make_shared<potion>("shield potion", 0 , 50) };
p.add_to_inventory(newshield);
p.add_gold(-cost);
p.view_inventory();
cout << "PLAYER GOLD = " << p.get_gold() << endl;
}else if (type == "health potion") {
shared_ptr<potion> newhealth = { make_shared<potion>("health potion", 0 , 100) };
p.add_to_inventory(newhealth);
p.add_gold(-cost);
p.view_inventory();
cout << "PLAYER GOLD = " << p.get_gold() << endl;
}else if (type == "damage potion") {
shared_ptr<potion> newdmg = { make_shared<potion>("damage potion", 50 , 0) };
p.add_to_inventory(newdmg);
p.add_gold(-cost);
p.view_inventory();
cout << "PLAYER GOLD = " << p.get_gold() << endl;
}
}
| true |
ccc52e5f2aeeaa5fd997639ce8cf92c99670e84c | C++ | einkat/Micromouse_fin | /micromouse/czujnik.h | UTF-8 | 1,328 | 3.15625 | 3 | [] | no_license | #ifndef CZUJNIK_H
#define CZUJNIK_H
#include <mwalls.h>
/// \brief Klasa czujnika wykrywającego ściany
class Czujnik
{
public:
/**
* @brief Czujnik Czujnik ścian
* @param x Położenie robota w osi X
* @param y Położenie robota w osi Y
* @param direction Kierunek wykrywania
* @param range Zasięg wykrywania
*/
Czujnik(int x, int y, int direction,int range);
/**
* @brief ChangeCords Zmienia położenie czujnika adekwatnie do położenia robota
* @param x Położenie robota w osi X
* @param y Położenie robota w osi Y
*/
void ChangeCords(double x, double y);
/**
* @brief GetType Sprawdza rodzaj ściany
*/
int GetType();
/**
* @brief Detect Sprawdza czy czujnik widzi ściane
* @param _walls Labirynt
* @param rodzaj Określa czy szukać ścian pionowych czy poziomych
* @return 1 jeżeli ściana zostanie wykryta, 0 jeżeli ściana nie zostanie wykryta
*/
bool Detect(MWalls * _walls,int rodzaj);
private:
/// Położenie w osi X
double cord_x,
/// Położenie w osi Y
cord_y,
/// Zasięg w osi X
range_x,
/// Zasięg w osi Y
range_y;
/// Parametr wykrytej ściany
int type = 0;
};
#endif // CZUJNIK_H
| true |
214561d3bd877dc9edb0d831420eb82d73b8c51f | C++ | StephaneBranly/LO21-RPN-Calculator | /src/engine/expression/operator/operatorsdefinition.h | UTF-8 | 2,528 | 2.703125 | 3 | [] | no_license | #ifndef OPERATORSDEFINITION_H
#define OPERATORSDEFINITION_H
#include "operator.h"
namespace Engine {
// Definition des differents operateurs affectant la pile, atoms, ...
class OperatorCLEAR : public Operator {
public:
OperatorCLEAR(): Operator("OperatorCLEAR",0){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "CLEAR"; }
Expression* getCopy() const override { return new OperatorCLEAR; }
};
class OperatorSWAP : public Operator {
public:
OperatorSWAP(): Operator("OperatorSWAP",2){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "SWAP"; }
Expression* getCopy() const override { return new OperatorSWAP; }
};
class OperatorDROP : public Operator {
public:
OperatorDROP(): Operator("OperatorDROP",1){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "DROP"; }
Expression* getCopy() const override { return new OperatorDROP; }
};
class OperatorDUP : public Operator {
public:
OperatorDUP(): Operator("OperatorDUP",1){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "DUP"; }
Expression* getCopy() const override { return new OperatorDUP; }
};
class OperatorEVAL : public Operator {
public:
OperatorEVAL(): Operator("OperatorEVAL",1){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "EVAL"; }
Expression* getCopy() const override { return new OperatorEVAL; }
};
class OperatorSTO : public Operator {
public:
OperatorSTO(): Operator("OperatorSTO",2){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "STO"; }
Expression* getCopy() const override { return new OperatorSTO; }
};
class OperatorFORGET : public Operator {
public:
OperatorFORGET(): Operator("OperatorFORGET",1){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "FORGET"; }
Expression* getCopy() const override { return new OperatorFORGET; }
};
class OperatorTYPE : public Operator {
public:
OperatorTYPE(): Operator("OperatorTYPE",1){}
void executeOpe(vector<Expression*> e) override;
const std::string toString() const override{ return "TYPE"; }
Expression* getCopy() const override { return new OperatorTYPE; }
};
}
#endif // OPERATORSDEFINITION_H
| true |
bd2f04cdbb6a3d38b9311bb8210dc478c1c43971 | C++ | rushioda/PIXELVALID_athena | /athena/MuonSpectrometer/MuonReconstruction/MuonSegmentMakers/MuonSegmentMakerUtils/MuonSegmentMakerUtils/MuonSegmentKey.h | UTF-8 | 1,829 | 2.84375 | 3 | [] | no_license | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef MUON_MUONSEGMENTKEY_H
#define MUON_MUONSEGMENTKEY_H
#include <set>
#include <vector>
namespace Trk {
class MeasurementBase;
}
namespace Muon{
class MuonSegment;
/**
Class to cache the identifiers on a segment in sets that can later be used to perform an
overlap removel between two segments.
@author Ed Moyse, Niels van Eldik
*/
class MuonSegmentKey {
public:
/** The first int is the Identifier, whilst the second is the sign of the 1st measurement (i.e. drift radius)*/
typedef std::set< std::pair<unsigned int, int> > MeasurementKeys;
/** default constructor */
MuonSegmentKey();
/** constructor taking a MuonSegment */
MuonSegmentKey( const MuonSegment& segment);
/** constructor taking a vector of measurements */
MuonSegmentKey( const std::vector< const Trk::MeasurementBase* >& measurements );
/** function to calculate keys from a vector of measurements, the signCor is can be
use to flip the signs of the MDT hits if the two segments that are compared have opposite directions */
void calculateKeys( const std::vector< const Trk::MeasurementBase* >& measurements, int signCor = 1 );
virtual ~MuonSegmentKey();
/** access to precision hit keys */
const MeasurementKeys& keys() const;
/** access to trigger hit keys */
const MeasurementKeys& keysTrigger() const;
private:
MeasurementKeys m_measKeys;
MeasurementKeys m_measKeysTrigger;
};
}
inline const Muon::MuonSegmentKey::MeasurementKeys& Muon::MuonSegmentKey::keysTrigger() const
{
return m_measKeysTrigger;
}
inline const Muon::MuonSegmentKey::MeasurementKeys& Muon::MuonSegmentKey::keys() const
{
return m_measKeys;
}
#endif
| true |
6a8ec2006d91b92098d3eaeeff4382656635e6ca | C++ | a1h2med/Arduino | /Push_Button/sketch_feb08a.ino | UTF-8 | 137 | 2.609375 | 3 | [] | no_license | int val ;
void setup()
{
pinMode(13,OUTPUT);
pinMode(7,INPUT);
}
void loop()
{
val=digitalRead(7);
digitalWrite(13,val);
}
| true |
66e56bd404eda10f829bd63d669e9837ba6a7a93 | C++ | nicknick1945/melonoma | /semion/SLib/Features/steacher.cpp | UTF-8 | 4,708 | 3.171875 | 3 | [] | no_license | #include "steacher.h"
/*!
* \brief Конструктор по умолчанию.
* \details Задает правило интерпретации цветов:
* - красный (255,0,0) - код 1
* - зеленый (0,255,0 )- код 2
* - синий (0,0,255) - код 3
* - желтый (255,255,0) - код 4
* - голубой (0,255,255) - код 5
* - пурпурный (255,0,255) - код 6
* Иначе - код 0
* По умолчанию порог необходимости = 0.1
* \warning Т.к интерпретируются не яркости, а коды пикселей, используте план прямой передачи S::Lasy().
*/
STeacher::STeacher()
{
marks = {{0xFFFF0000,1}, //red
{0xFFFFFF00,2}, //yellow
{0xFF00FF00,3}, //green
{0xFF00FFFF,4}, //cyan
{0xFF0000FF,5}, //blue
{0xFFFF00FF,6}}; //magenta
}
/*!
* \brief Конструктор по правилу интерпретации.
* \details Позволяет задать собственное правило интерпретации цветов в виде словаря и доли пикселей.
* Ключ словаря - цвет, значение - код класса. Например:
* \code
* marks = {{0xFFFF0000,1}, //red
{0xFFFFFF00,2}, //yellow
{0xFF00FF00,3}, //green
{0xFF00FFFF,4}, //cyan
{0xFF0000FF,5}, //blue
{0xFFFF00FF,6}}; //magenta
* \endcode
* \param marks - ссылка на словарь
* \param necessity_threshold - порог необходимости
* \throw std::invalid_argument - при пороге <0 или >1
*/
STeacher::STeacher(const std::map<int, int> &marks, double necessity_threshold)
:marks(marks),necessity_thrs(necessity_threshold)
{
if (necessity_threshold>1 || necessity_threshold<0)
throw std::invalid_argument("STeacher: necessity_threshold must be within [0,1]");
}
/*!
* \brief Перестройка класса.
* \details По сути дает изображению метку класса. Игнорирование фона при этом не играет существенной роли.
* \param img - полутоновое изображение
* \param ignore_zero - игнорирование фона
* \remark Лучше всего используте план прямой передачи S::Lasy().
* \warning В случае конфликта разметок изображение относится к классу с наибольшим ключем в словаре.
*/
void STeacher::rebuild(const SMatrix &img, bool ignore_zero)
{
using namespace std;
map<int,int> counters;
for (int y=0;y<img.height();++y)
for (int x=0;x<img.width();++x)
{
int pix = img(x,y);
if (!ignore_zero || pix != 0)
++counters[pix];
}
segment_class=0;
if (counters.size()!=0)
{
for (pair<int,int> c:counters)
if (marks.find(c.first)!=marks.end())
{
double ratio = double(c.second)/
double(img.width()*img.height());
if (ratio>necessity_thrs)
{
if (segment_class!=0)
{
qDebug("STeacher: the markup used permits duality");
qDebug(" help: try to improve threshold of necessity");
}
segment_class = marks[c.first];
}
}
}
}
/*!
* \brief Создание листа с названием признака.
* \details К названиям признаков можно добавлять некоторую приставку.
* Итоговое название признака будет складываться из приставки и оригинального названия = "Y".
* Признак всего один - идентификатор класса.
* \param prefix - приставка
* \return лист с одним названием
*/
std::list<std::__cxx11::string> STeacher::getHeader(const std::__cxx11::string &prefix)
{return {prefix+"Y"};}
/*!
* \brief Создание листа со значением идентификатора класса.
* \details Возвращает лист с единственным признаком - идентификатором класса.
* \return лист с одним признаком
*/
std::list<double> STeacher::getFeatures()
{
return {double(segment_class)};
}
| true |
a142f83288c5a6c99c26ff368707e1c8463c91f4 | C++ | jingaz/LeeCode | /罗马数字转整数.cpp | UTF-8 | 1,745 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int romanToInt(string s) {
int ret = 0;
while (!s.empty()) {
char ch = s.back();
s.pop_back();
switch (ch) {
case 'I':
ret += 1;
break;
case 'V':
if (!s.empty() && s.back() == 'I') {
ret += 4;
s.pop_back();
} else {
ret += 5;
}
break;
case 'X':
if (!s.empty() && s.back() == 'I') {
ret += 9;
s.pop_back();
} else {
ret += 10;
}
break;
case 'L':
if (!s.empty() && s.back() == 'X') {
ret += 40;
s.pop_back();
} else {
ret += 50;
}
break;
case 'C':
if (!s.empty() && s.back() == 'X') {
ret += 90;
s.pop_back();
} else {
ret += 100;
}
break;
case 'D':
if (!s.empty() && s.back() == 'C') {
ret += 400;
s.pop_back();
} else {
ret += 500;
}
break;
case 'M':
if (!s.empty() && s.back() == 'C') {
ret += 900;
s.pop_back();
} else {
ret += 1000;
}
break;
default:
break;
}
}
return ret;
}
int main() {
vector<string> testdata = {"III", "IV", "IX", "LVIII", "MCMXCIV"};
for (string it : testdata) {
cout << it << ": " << romanToInt(it) << endl;
}
} | true |
9b6a00890fdf7f35bbb17644803b0eaeb2bab100 | C++ | LeverImmy/Codes | /比赛/学校/2019-9-13测试/熊泽恩/noon/std.cpp | UTF-8 | 2,058 | 2.65625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <cstring>
#define rgi register int
#define il inline
#define ll long long
using namespace std;
const int oo = 0x3f3f3f3f;
const int N = 1e5 + 10;
const int M = 1e5 + 10;
int n, m;
int gcd(int a, int b){return !b ? a : gcd(b, a % b);}
struct Fraction
{
int up, down;
Fraction(){down = 1;}
void init(){int g = gcd(up, down); up /= g, down /= g;}
};
bool operator < (struct Fraction a, struct Fraction b)
{
int cur_l = a.down < 0 ? -1 : 1;
int cur_r = b.down < 0 ? -1 : 1;
return (ll)a.up * b.down * cur_l < (ll)a.down * b.up * cur_r;
}
struct Seg_Tree
{
int lc, rc, len;
struct Fraction val;
} t[N << 2];
il int read()
{
rgi x = 0, f = 0, ch;
while(!isdigit(ch = getchar())) f |= ch == '-';
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
int calc(struct Fraction cur_val, int p)
{
if(t[p].lc == t[p].rc)
return cur_val < t[p].val;
if(!(cur_val < t[p << 1].val))
return calc(cur_val, p << 1 | 1);
return t[p].len - t[p << 1].len + calc(cur_val, p << 1);
}
void Pushup(int p)
{
t[p].val = max(t[p << 1].val, t[p << 1 | 1].val);
t[p].len = t[p << 1].len + calc(t[p << 1].val, p << 1 | 1);
}
void Build(int p, int l, int r)
{
t[p].lc = l, t[p].rc = r;
if(l == r)
{
t[p].len = 0;
return;
}
int mid = l + r >> 1;
Build(p << 1, l, mid);
Build(p << 1 | 1, mid + 1, r);
// Pushup(p);
}
void Add(int p, int x, struct Fraction val)
{
if(t[p].lc == t[p].rc)
{
t[p].len = 1;
t[p].val = val;
return;
}
int mid = t[p].lc + t[p].rc >> 1;
if(x <= mid)
Add(p << 1, x, val);
else
Add(p << 1 | 1, x, val);
Pushup(p);
}
signed main()
{
// freopen("noon.in", "r", stdin);
// freopen("noon.out", "w", stdout);
n = read(), m = read();
Build(1, 1, n);
for(rgi i = 1; i <= m; ++i)
{
int x = read(), h = read();
struct Fraction a; a.up = h, a.down = x;
a.init();
Add(1, x, a);
printf("%d\n", t[1].len);
}
return 0;
}
/*
3 4
2 4
3 6
1 1000000
1 1
5 5
1 2
2 5
3 4
4 8
5 20
*/
| true |
e6383055dcec1f4278e15d032de441f4995a5e33 | C++ | joedanpar/Academic-Projects | /CSCI 241/assign0.cc | UTF-8 | 498 | 2.921875 | 3 | [
"MIT"
] | permissive | /************************************************************
* CSCI 241 Autumn, 2008
* Name: Joe Daniel Parker
* Assignment 0
* Due Date: 09/02/2008
* Purpose: This is a basic practice program.
*
************************************************************/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char Name[50];
cout << "What is your first name? ";
cin >> Name;
cout << "Hello, " << Name << endl;
return 0;
}
| true |
d56743b4ec14f687206d6d86723bdaab3a5667cd | C++ | traherom/hasher | /hashdatabase.h | UTF-8 | 1,198 | 2.734375 | 3 | [] | no_license | #ifndef HASHDATABASE_H
#define HASHDATABASE_H
#include <string>
#include <list>
using std::string;
#include <sqlite3.h>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using boost::shared_ptr;
#include "scan.h"
#include "scanfile.h"
class HashDatabase : public boost::enable_shared_from_this<HashDatabase>
{
public:
HashDatabase(string dbPath);
~HashDatabase();
static shared_ptr<HashDatabase> createNew(string dbPath);
static shared_ptr<HashDatabase> open(string dbPath);
// Misc
const string &getDatabasePath() const { return mDbPath; }
const string getSetting(const string &key);
const string setSetting(const string &key, const string &value);
const string getBasePath();
void setBasePath(const string &path);
// NSRL
bool hasNSRLData() const { return false; }
// Manage scans
shared_ptr<Scan> addScan(string name);
shared_ptr<Scan> getNewestScan();
std::list<shared_ptr<Scan>> getAllScans() { return Scan::getAllScans(shared_from_this()); }
inline sqlite3 *getDatabase() { return mDb; }
private:
HashDatabase();
string mDbPath;
sqlite3 *mDb;
};
#endif // HASHDATABASE_H
| true |
0e56a297768fa633a370ed91be49b5183c36d074 | C++ | DoRightt/Lippman-CPP-Primier-exercises | /Chapter_13/exercise13.14/main.cpp | UTF-8 | 363 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
class numbered {
public:
numbered() : mysn(++n) { };
int mysn;
private:
static int n;
};
int numbered::n = 0;
void f(numbered n) {
cout << n.mysn << endl;
}
int main() {
numbered a, b = a, c = b;
f(a); f(b); f(c); // 1; 1; 1;
return 0;
} | true |
ab222f1fcbec5089f0233688f8f4242808c99122 | C++ | caster99yzw/Y3DGameEngine | /common/Math/Y3DMathFunc.h | UTF-8 | 4,260 | 3.3125 | 3 | [] | no_license | #pragma once
#include "Y3DPI.h"
#include <cmath>
#include <limits>
// Provide the interface to cover the type of data
// Function of c-math can not be non-constexpr
namespace Y3D
{
//////////////////////////////////////////////////////////////////////////
//
// Basic Function
//
//////////////////////////////////////////////////////////////////////////
template <class T>
static T Abs(T const& rhs) { return static_cast<T>(std::fabs(rhs)); }
template <class T>
static T Sqrt(T const& lhs) { return static_cast<T>(std::sqrt(lhs)); }
template <class T>
static T RecipSqrt(T const& lhs) { return T(1) / static_cast<T>(std::sqrt(lhs)); }
template <class T>
static T Mod(T const& lhs, T const& rhs) { return static_cast<T>(std::fmod(lhs, rhs)); }
//////////////////////////////////////////////////////////////////////////
//
// Basic self-definite function
//
//////////////////////////////////////////////////////////////////////////
template <class T>
constexpr static T Sign(T const& rhs) { return rhs >= T(0) ? T(1) : T(-1); }
template <class T>
constexpr static T Max(T const& lhs, T const& rhs) { return lhs < rhs ? rhs : lhs; }
template <class T>
constexpr static T Min(T const& lhs, T const& rhs) { return lhs > rhs ? rhs : lhs; }
template <class T>
constexpr static T Clamp(T const& rhs, T const& low, T const& hi)
{
return (rhs > hi) ? hi : ((rhs < low) ? low : rhs);
}
template <class T>
constexpr static T Square(T const& rhs) { return rhs * rhs; }
template <class T>
constexpr static T Cube(T const& rhs) { return rhs * rhs * rhs; }
//////////////////////////////////////////////////////////////////////////
//
// Equi Function
//
//////////////////////////////////////////////////////////////////////////
template <class T>
constexpr static bool Equi(T const& lhs, T const& rhs) { return lhs == rhs; }
template <>
static bool Equi<float32>(float32 const& lhs, float32 const& rhs)
{
return std::abs(lhs - rhs) <= std::numeric_limits<float32>::epsilon();
}
template <>
static bool Equi<float64>(float64 const& lhs, float64 const& rhs)
{
return std::abs(lhs - rhs) <= std::numeric_limits<float64>::epsilon();
}
template <class T>
static bool Equi(Radian<T> const& lhs, Radian<T> const& rhs)
{
return std::abs(lhs.radValue - rhs.radValue) <= std::numeric_limits<T>::epsilon();
}
template <class T>
static bool Equi(Degree<T> const& lhs, Degree<T> const& rhs)
{
return std::abs(lhs.degVaule - rhs.degVaule) <= std::numeric_limits<T>::epsilon();
}
//////////////////////////////////////////////////////////////////////////
//
// Trigonometric Function
//
//////////////////////////////////////////////////////////////////////////
template <class T>
static T Sin(Radian<T> const& rhs) { return static_cast<T>(std::sin(rhs.radValue)); }
template <class T>
static T Cos(Radian<T> const& rhs) { return static_cast<T>(std::cos(rhs.radValue)); }
template <class T>
static T Tan(Radian<T> const& rhs) { return static_cast<T>(std::tan(rhs.radValue)); }
template <class T>
static Radian<T> ASin(T const& rhs)
{
return Radian<T>(
static_cast<T>(std::asin(rhs))
);
}
template <class T>
static Radian<T> ACos(T const& rhs)
{
return Radian<T>(
static_cast<T>(std::acos(rhs))
);
}
template <class T>
static Radian<T> ATan(T const& rhs)
{
return Radian<T>(
static_cast<T>(std::atan(rhs))
);
}
template <class T>
static Radian<T> ATan2(T const& rhs0, T const& rhs1)
{
return Radian<T>(
static_cast<T>(std::atan2(rhs0, rhs1))
);
}
//////////////////////////////////////////////////////////////////////////
//
// Logarithmic and Exponential Function
//
//////////////////////////////////////////////////////////////////////////
template <class T>
static T LogE(T const& rhs) { return static_cast<T>(std::log(rhs)); }
template <class T>
static T Log2(T const& rhs) { return static_cast<T>(std::log2(rhs)); }
template <class T>
static T Log10(T const& rhs) { return static_cast<T>(std::log10(rhs)); }
template <class T>
static T Pow(T const& rhs, T const& ex) { return static_cast<T>(std::pow(rhs, ex)); }
template <class T>
static T Exp(T const& ex) { return static_cast<T>(std::exp(ex)); }
} | true |
75b960fe2bcc99adcc3c01f326a4f2d124ab322a | C++ | devloop0/dharma-vm | /src/builtins.cpp | UTF-8 | 34,985 | 2.8125 | 3 | [] | no_license | #include "includes/runtime.hpp"
namespace dharma_vm {
shared_ptr<runtime_variable> runtime::print(shared_ptr<runtime_variable> rvar) {
if (rvar == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (rvar->get_runtime_type_information() == runtime_type_information_list::_boolean) {
cout << (rvar->get_boolean() ? "true" : "false");
}
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_decimal)
cout << rvar->get_decimal();
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_dict) {
if (rvar->get_dict().first.size() != rvar->get_dict().second.size())
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, rvar);
cout << "{{{ ";
for (int i = 0; i < rvar->get_dict().first.size(); i++) {
print(rvar->get_dict().first[i]);
cout << ": ";
print(rvar->get_dict().second[i]);
if (i != rvar->get_dict().first.size() - 1)
cout << ", ";
}
cout << " }}}";
}
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_list || rvar->get_runtime_type_information() == runtime_type_information_list::_tuple) {
if (rvar->get_runtime_type_information() == runtime_type_information_list::_list)
cout << "[[[ ";
else
cout << "<<< ";
for (int i = 0; i < rvar->get_list_tuple().size(); i++) {
print(rvar->get_list_tuple()[i]);
if (i != rvar->get_list_tuple().size() - 1)
cout << ", ";
}
if (rvar->get_runtime_type_information() == runtime_type_information_list::_list)
cout << " ]]]";
else
cout << " >>>";
}
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_int)
cout << rvar->get_integer();
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_nil)
cout << "Nil";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_func)
cout << "Function: " << rvar->get_string();
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_boolean)
cout << "[Boolean]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_decimal)
cout << "[Decimal]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_dict)
cout << "[Dict]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_func)
cout << "[Function: " << rvar->get_string() << "]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_int)
cout << "[Integer]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_list)
cout << "[List]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_nil)
cout << "[Nil]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_string)
cout << "[String]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_pure_tuple)
cout << "[Tuple]";
else if (rvar->get_runtime_type_information() == runtime_type_information_list::_string)
cout << rvar->get_string();
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_YES)
cout << "[Struct: " << rvar->get_string() << "]";
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_YES)
cout << "[Enum: " << rvar->get_string() << "]";
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_YES)
cout << "[Enum Child: " << rvar->get_string() << "]";
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_YES)
cout << "[Module: " << rvar->get_string() << "]";
else {
vector<pair<shared_ptr<runtime_variable>, shared_ptr<runtime>>> results = find_special_function(instruction_list, nullptr, builtins::builtin__print__);
bool success = false;
if (results.size() > 0) {
for (int j = 0; j < results.size(); j++) {
pair<shared_ptr<runtime_variable>, shared_ptr<runtime>> res = results[j];
for (int i = 0; i < res.first->get_function().size(); i++) {
shared_ptr<runtime_variable> temp = run_function({ res.first->get_function()[i] }, res.first, { rvar }, res.second);
if (temp->get_runtime_type_information() == runtime_type_information_list::_nil);
else {
print(temp);
success = true;
break;
}
}
if (success)
break;
}
}
if (!success) {
if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO)
cout << "Struct: " << rvar->get_string();
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO)
cout << "Module: " << rvar->get_string();
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO)
cout << "Enum: " << rvar->get_string();
else if (rvar->get_runtime_type_information().get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD && rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO)
cout << "Enum Child: " << rvar->get_string();
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, rvar);
}
}
shared_ptr<runtime_variable> ret = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", true,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), runtime_type_information_list::_boolean,
vector<shared_ptr<function>>());
return checked_insertion(ret);
}
shared_ptr<runtime_variable> runtime::exit(shared_ptr<runtime_variable> exit_code, shared_ptr<runtime_variable> message) {
if (exit_code == nullptr || message == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (exit_code->get_runtime_type_information() != runtime_type_information_list::_int)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, exit_code);
if (message->get_runtime_type_information() != runtime_type_information_list::_string)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, message);
print(message);
std::exit(exit_code->get_integer());
shared_ptr<runtime_variable> created_bool = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", true,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), runtime_type_information_list::_boolean,
vector<shared_ptr<function>>());
runtime_temporary_count++;
return checked_insertion(created_bool);
}
shared_ptr<runtime_variable> runtime::add(shared_ptr<runtime_variable> dict, shared_ptr<runtime_variable> key, shared_ptr<runtime_variable> value) {
if (dict == nullptr || key == nullptr || value == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (dict->get_runtime_type_information() == runtime_type_information_list::_dict);
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, dict);
if (dict->get_unmodifiable())
report_error_and_terminate_program(runtime_diagnostic_messages::unmodifiable_value, dict);
shared_ptr<runtime_variable> created_dict = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), runtime_type_information_list::_dict,
vector<shared_ptr<function>>());
created_dict->set_dict(dict->get_dict());
runtime_temporary_count++;
vector<shared_ptr<runtime_variable>> key_list = created_dict->get_dict().first;
vector<shared_ptr<runtime_variable>> value_list = created_dict->get_dict().second;
if (dict->get_dict().first.size() != dict->get_dict().second.size())
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, dict);
if (dict->get_dict().first.size() == 0) {
key_list.push_back(key);
value_list.push_back(value);
}
else {
runtime_type_information key_t_inf = created_dict->get_dict().first[0]->get_runtime_type_information();
if (key_t_inf == key->get_runtime_type_information()) {
if (key_t_inf.get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO) {
if (key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM || key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE ||
key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM || key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD) {
if (dict->get_dict().first[0]->get_unique_id() == key->get_unique_id());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key);
}
}
}
else if ((key_t_inf == runtime_type_information_list::_int && key->get_runtime_type_information() == runtime_type_information_list::_decimal) ||
(key_t_inf == runtime_type_information_list::_decimal && key->get_runtime_type_information() == runtime_type_information_list::_int)) {
if (key_t_inf == runtime_type_information_list::_int) {
key->set_integer(key->get_decimal());
key->set_runtime_type_information(runtime_type_information_list::_int);
}
else {
key->set_decimal(key->get_integer());
key->set_runtime_type_information(runtime_type_information_list::_decimal);
}
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key);
for (int i = 0; i < created_dict->get_dict().first.size(); i++) {
shared_ptr<runtime_variable> k_temp = make_shared<runtime_variable>(key->get_storage_field(), key->get_integer(), key->get_decimal(), key->get_string(), key->get_boolean(),
key->get_list_tuple(), key->get_dict(), key->get_struct_enum_member_list(), key->get_module_runtime(), key->get_runtime_type_information(), key->get_function());
k_temp->set_unmodifiable(key->get_unmodifiable());
k_temp->set_unique_id(key->get_unique_id());
if ((k_temp == created_dict->get_dict().first[i])->get_boolean())
report_error_and_terminate_program(runtime_diagnostic_messages::key_already_exists, key);
}
key_list.push_back(key);
runtime_type_information value_t_inf = created_dict->get_dict().second[0]->get_runtime_type_information();
if (value_t_inf == value->get_runtime_type_information()) {
if (value_t_inf.get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO) {
if (value_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM || value_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE ||
value_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM || value_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD) {
if (created_dict->get_dict().second[0]->get_unique_id() == value->get_unique_id());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, value);
}
}
}
else if ((value_t_inf == runtime_type_information_list::_int && value->get_runtime_type_information() == runtime_type_information_list::_decimal) ||
(value_t_inf == runtime_type_information_list::_decimal && value->get_runtime_type_information() == runtime_type_information_list::_int)) {
if (value_t_inf == runtime_type_information_list::_int) {
value->set_integer(value->get_decimal());
value->set_runtime_type_information(runtime_type_information_list::_int);
}
else {
value->set_decimal(value->get_integer());
value->set_runtime_type_information(runtime_type_information_list::_decimal);
}
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, value);
value_list.push_back(value);
}
created_dict->set_dict(make_pair(key_list, value_list));
return created_dict;
}
shared_ptr<runtime_variable> runtime::add(shared_ptr<runtime_variable> list_string, shared_ptr<runtime_variable> element) {
if (list_string == nullptr || element == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (list_string->get_unmodifiable())
report_error_and_terminate_program(runtime_diagnostic_messages::unmodifiable_value, list_string);
shared_ptr<runtime_variable> created_list_string = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), list_string->get_runtime_type_information(),
vector<shared_ptr<function>>());
created_list_string->set_list_tuple(list_string->get_list_tuple());
created_list_string->set_string(list_string->get_string());
runtime_temporary_count++;
if (list_string->get_runtime_type_information() == runtime_type_information_list::_list) {
vector<shared_ptr<runtime_variable>> list = created_list_string->get_list_tuple();
if (list_string->get_list_tuple().size() == 0)
list.push_back(element);
else {
runtime_type_information t_inf = created_list_string->get_list_tuple()[0]->get_runtime_type_information();
if (t_inf == element->get_runtime_type_information()) {
if (t_inf.get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO) {
if (t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM || t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE ||
t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM || t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD) {
if (list_string->get_list_tuple()[0]->get_unique_id() == element->get_unique_id());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
}
}
}
else if ((t_inf == runtime_type_information_list::_int && element->get_runtime_type_information() == runtime_type_information_list::_decimal) ||
(t_inf == runtime_type_information_list::_decimal && element->get_runtime_type_information() == runtime_type_information_list::_int)) {
if (t_inf == runtime_type_information_list::_int) {
element->set_integer(element->get_decimal());
element->set_runtime_type_information(runtime_type_information_list::_int);
}
else {
element->set_decimal(element->get_integer());
element->set_runtime_type_information(runtime_type_information_list::_decimal);
}
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
list.push_back(element);
}
created_list_string->set_list_tuple(list);
}
else if (list_string->get_runtime_type_information() == runtime_type_information_list::_string) {
if (element->get_runtime_type_information() == runtime_type_information_list::_string)
created_list_string->set_string(created_list_string->get_string() + element->get_string());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, list_string);
return created_list_string;
}
shared_ptr<runtime_variable> runtime::insert(shared_ptr<runtime_variable> list_string, shared_ptr<runtime_variable> pos, shared_ptr<runtime_variable> element) {
if (list_string == nullptr || pos == nullptr || element == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
shared_ptr<runtime_variable> created_list_string = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), list_string->get_runtime_type_information(),
vector<shared_ptr<function>>());
created_list_string->set_list_tuple(list_string->get_list_tuple());
created_list_string->set_string(list_string->get_string());
runtime_temporary_count++;
if (pos->get_runtime_type_information() != runtime_type_information_list::_int)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, pos);
if (list_string->get_unmodifiable())
report_error_and_terminate_program(runtime_diagnostic_messages::unmodifiable_value, list_string);
if (list_string->get_runtime_type_information() == runtime_type_information_list::_list) {
vector<shared_ptr<runtime_variable>> list = created_list_string->get_list_tuple();
if (list.size() == 0)
report_error_and_terminate_program(runtime_diagnostic_messages::use_the_add_function_to_add_an_element_to_an_empty_list, list_string);
if (pos->get_integer() < 0 || pos->get_integer() > list.size())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, pos);
runtime_type_information t_inf = created_list_string->get_list_tuple()[0]->get_runtime_type_information();
if (t_inf == element->get_runtime_type_information()) {
if (t_inf.get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO) {
if (t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM || t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE ||
t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM || t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD) {
if (list_string->get_list_tuple()[0]->get_unique_id() == element->get_unique_id());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
}
}
}
else if ((t_inf == runtime_type_information_list::_int && element->get_runtime_type_information() == runtime_type_information_list::_decimal) ||
(t_inf == runtime_type_information_list::_decimal && element->get_runtime_type_information() == runtime_type_information_list::_int)) {
if (t_inf == runtime_type_information_list::_int) {
element->set_integer(element->get_decimal());
element->set_runtime_type_information(runtime_type_information_list::_int);
}
else {
element->set_decimal(element->get_integer());
element->set_runtime_type_information(runtime_type_information_list::_decimal);
}
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
list.insert(list.begin() + pos->get_integer(), element);
created_list_string->set_list_tuple(list);
}
else if (list_string->get_runtime_type_information() == runtime_type_information_list::_string) {
string str = created_list_string->get_string();
if (element->get_runtime_type_information() != runtime_type_information_list::_string)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, element);
if (pos->get_integer() < 0 || pos->get_integer() > str.length())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, pos);
str.insert(pos->get_integer(), element->get_string());
created_list_string->set_string(str);
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, list_string);
return created_list_string;
}
shared_ptr<runtime_variable> runtime::remove(shared_ptr<runtime_variable> list_string_dict, shared_ptr<runtime_variable> key_index) {
if (list_string_dict == nullptr || key_index == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
shared_ptr<runtime_variable> created_list_string_dict = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), list_string_dict->get_runtime_type_information(),
vector<shared_ptr<function>>());
created_list_string_dict->set_list_tuple(list_string_dict->get_list_tuple());
created_list_string_dict->set_string(list_string_dict->get_string());
created_list_string_dict->set_dict(list_string_dict->get_dict());
runtime_temporary_count++;
if (list_string_dict->get_unmodifiable())
report_error_and_terminate_program(runtime_diagnostic_messages::unmodifiable_value, list_string_dict);
if (list_string_dict->get_runtime_type_information() == runtime_type_information_list::_dict) {
pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>> dict = created_list_string_dict->get_dict();
if (dict.first.size() != dict.second.size())
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, list_string_dict);
if (dict.first.size() == 0)
report_error_and_terminate_program(runtime_diagnostic_messages::cannot_remove_from_an_empty_dictionary, list_string_dict);
runtime_type_information key_t_inf = dict.first[0]->get_runtime_type_information();
if (key_t_inf == key_index->get_runtime_type_information()) {
if (key_t_inf.get_type_pure_kind() == type_pure_kind::TYPE_PURE_NO) {
if (key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_CUSTOM || key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_MODULE ||
key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM || key_t_inf.get_runtime_type_kind() == runtime_type_kind::TYPE_ENUM_CHILD) {
if (dict.first[0]->get_unique_id() == key_index->get_unique_id());
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key_index);
}
}
}
else if ((key_t_inf == runtime_type_information_list::_int && key_index->get_runtime_type_information() == runtime_type_information_list::_decimal) ||
(key_t_inf == runtime_type_information_list::_decimal && key_index->get_runtime_type_information() == runtime_type_information_list::_int)) {
if (key_t_inf == runtime_type_information_list::_int) {
key_index->set_integer(key_index->get_decimal());
key_index->set_runtime_type_information(runtime_type_information_list::_int);
}
else {
key_index->set_decimal(key_index->get_integer());
key_index->set_runtime_type_information(runtime_type_information_list::_decimal);
}
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key_index);
int store = -1;
for (int i = 0; i < dict.first.size(); i++) {
shared_ptr<runtime_variable> k_temp = make_shared<runtime_variable>(key_index->get_storage_field(), key_index->get_integer(), key_index->get_decimal(), key_index->get_string(), key_index->get_boolean(),
key_index->get_list_tuple(), key_index->get_dict(), key_index->get_struct_enum_member_list(), key_index->get_module_runtime(), key_index->get_runtime_type_information(), key_index->get_function());
k_temp->set_unmodifiable(key_index->get_unmodifiable());
k_temp->set_unique_id(key_index->get_unique_id());
if ((k_temp == dict.first[i])->get_boolean()) {
store = i;
break;
}
}
if (store == -1);
else {
dict.first.erase(dict.first.begin() + store, dict.first.begin() + store + 1);
dict.second.erase(dict.second.begin() + store, dict.second.begin() + store + 1);
}
created_list_string_dict->set_dict(dict);
}
else if (list_string_dict->get_runtime_type_information() == runtime_type_information_list::_list) {
vector<shared_ptr<runtime_variable>> list = created_list_string_dict->get_list_tuple();
if (key_index->get_runtime_type_information() != runtime_type_information_list::_int)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key_index);
if (key_index->get_integer() < 0 || key_index->get_integer() > list.size())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, key_index);
list.erase(list.begin() + key_index->get_integer(), list.begin() + key_index->get_integer() + 1);
created_list_string_dict->set_list_tuple(list);
}
else if (list_string_dict->get_runtime_type_information() == runtime_type_information_list::_string) {
string str = created_list_string_dict->get_string();
if (key_index->get_runtime_type_information() != runtime_type_information_list::_int)
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, key_index);
if (key_index->get_integer() < 0 || key_index->get_integer() > str.length())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, key_index);
str.erase(key_index->get_integer(), 1);
created_list_string_dict->set_string(str);
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, list_string_dict);
return created_list_string_dict;
}
shared_ptr<runtime_variable> runtime::remove(shared_ptr<runtime_variable> list_string, shared_ptr<runtime_variable> start, shared_ptr<runtime_variable> end) {
shared_ptr<runtime_variable> created_list_string = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), list_string->get_runtime_type_information(),
vector<shared_ptr<function>>());
created_list_string->set_list_tuple(list_string->get_list_tuple());
created_list_string->set_string(list_string->get_string());
runtime_temporary_count++;
if (list_string->get_unmodifiable())
report_error_and_terminate_program(runtime_diagnostic_messages::unmodifiable_value, list_string);
if (start->get_runtime_type_information() == runtime_type_information_list::_int);
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, start);
if (end->get_runtime_type_information() == runtime_type_information_list::_int);
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, end);
if (list_string->get_runtime_type_information() == runtime_type_information_list::_list) {
vector<shared_ptr<runtime_variable>> list = created_list_string->get_list_tuple();
if (start->get_integer() < 0 || start->get_integer() > list.size())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, start);
if (end->get_integer() < 0 || end->get_integer() > list.size())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, end);
if (start->get_integer() > end->get_integer())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, end);
list.erase(list.begin() + start->get_integer(), list.begin() + end->get_integer());
created_list_string->set_list_tuple(list);
}
else if (list_string->get_runtime_type_information() == runtime_type_information_list::_string) {
string str = created_list_string->get_string();
if (start->get_integer() < 0 || start->get_integer() > str.length())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, start);
if (end->get_integer() < 0 || end->get_integer() > str.length())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, end);
if (start->get_integer() > end->get_integer())
report_error_and_terminate_program(runtime_diagnostic_messages::subscript_out_of_range, end);
str.erase(start->get_integer(), end->get_integer() - start->get_integer());
}
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, list_string);
return created_list_string;
}
shared_ptr<runtime_variable> runtime::load_library(shared_ptr<runtime_variable> dll_name) {
if (dll_name == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (dll_name->get_runtime_type_information() == runtime_type_information_list::_string);
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, dll_name);
shared_ptr<runtime_variable> created_dll = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, dll_name->get_string(), false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(), make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector <vector<shared_ptr<runtime_variable>>>(),
vector<vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>()), runtime_type_information(runtime_type_kind::TYPE_MODULE, type_pure_kind::TYPE_PURE_NO, type_class_kind::TYPE_CLASS_YES, builtins::builtin_runtime_dll_module_prefix + dll_name->get_string()), vector<shared_ptr<function>>());
runtime_temporary_count++;
return created_dll;
}
shared_ptr<runtime_variable> runtime::input(shared_ptr<runtime_variable> prompt) {
if (prompt == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
if (prompt->get_runtime_type_information() == runtime_type_information_list::_string);
else
report_error_and_terminate_program(runtime_diagnostic_messages::incompatible_types, prompt);
cout << prompt->get_string();
string str;
cin >> str;
shared_ptr<runtime_variable> ret = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, str, false,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(),
make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(),
vector<shared_ptr<runtime_variable>>()), runtime_type_information_list::_string, vector<shared_ptr<function>>());
return ret;
}
shared_ptr<runtime_variable> runtime::is_pure(shared_ptr<runtime_variable> rvar) {
if (rvar == nullptr)
report_error_and_terminate_program(runtime_diagnostic_messages::fatal_error, nullptr);
bool pure = false;
if (rvar->get_runtime_type_information().get_type_pure_kind() == type_pure_kind::TYPE_PURE_YES)
pure = true;
shared_ptr<runtime_variable> ret = make_shared<runtime_variable>(storage_field(-1, runtime_temporary_prefix + to_string(runtime_temporary_count), storage_field_kind::STORAGE_FIELD_IDENTIFIER), -1, -1, "", pure,
vector<shared_ptr<runtime_variable>>(), pair<vector<shared_ptr<runtime_variable>>, vector<shared_ptr<runtime_variable>>>(), vector<shared_ptr<runtime_variable>>(),
make_shared<runtime>(vector<string>(), vector<shared_ptr<runtime_variable>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(), vector<vector<shared_ptr<runtime_variable>>>(),
vector<shared_ptr<runtime_variable>>()), runtime_type_information_list::_boolean, vector<shared_ptr<function>>());
return ret;
}
} | true |
2f9e2e7c1b857bacc1dcc097f7c30b59aafafc35 | C++ | NorinStark/OOP_Labs | /Lab 2/StatisticMultiset.cpp | UTF-8 | 2,180 | 3.265625 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <set>
#include <vector>
#include <list>
#include <fstream>
#include <string>
#include "StatisticMultiset.h"
template <class T> StatisticMultiset<T>::StatisticMultiset() : sum(0) {}
template <class T> void StatisticMultiset<T>::AddNum(T const &num) {
data.insert(num);
sum += num;
}
template <class T> void StatisticMultiset<T>::AddNum(std::multiset<T> const &numbers) {
for (auto &i : numbers) {
data.insert(i);
sum += i;
}
}
template <class T> void StatisticMultiset<T>::AddNum(std::vector<T> const &numbers) {
for (auto &i : numbers) {
data.insert(i);
sum += i;
}
}
template <class T> void StatisticMultiset<T>::AddNum(std::list<T> const &numbers) {
for (auto &i : numbers) {
data.insert(i);
sum += i;
}
}
template <class T> void StatisticMultiset<T>::AddNum(StatisticMultiset<T> const &a_stat_set) {
if (this != &a_stat_set) {
AddNum(a_stat_set.data);
}
else {
for (auto i = a_stat_set.data.begin(); i != a_stat_set.data.end(); i++) {
data.insert(*i);
sum += *i;
i++;
}
}
}
template <class T> void StatisticMultiset<T>::AddNumsFromFile(char const * filename) {
std::ifstream in(filename);
if (!in.good())
std::cerr << "File can not be opened!\n";
T Mset;
while (in >> Mset) {
AddNum(Mset);
sum += Mset;
}
}
template <class T> T StatisticMultiset<T>::GetMin() const {
return *data.begin();
}
template <class T> T StatisticMultiset<T>::GetMax() const {
return *data.rbegin();
}
template <class T> float StatisticMultiset<T>::GetAvg() const {
float ans = 0;
if (data.size() == 0)
std::cerr << "StatisticMultiset is empty! \n";
else
ans = (sum / data.size());
return ans;
}
template <class T> int StatisticMultiset<T>::GetCountUnder(float const &threshold) const {
int ans = 0;
for (auto i = data.begin(); i != data.end() && *i < threshold; i++)
++ans;
return ans;
}
template <class T> int StatisticMultiset<T>::GetCountAbove(float const &threshold) const {
int ans = 0;
for (auto i = data.rbegin(); i != data.rend() && *i > threshold; i++)
++ans;
return ans;
} | true |
4a07acae5fa733a8cb6b4256c6d4fe436f3533e8 | C++ | CDK6182CHR/PlantVsZombie | /plants/Plant.cpp | GB18030 | 843 | 2.796875 | 3 | [] | no_license | #include "Plant.h"
#include "../Block.h"
#include "../System.h"
#include "../Position.h"
#include <string>
using namespace std;
Plant::Plant(System& sys):Placeable(sys),hp(0)
{
}
/*
precondition: positionʾλûֲ
*/
void Plant::place()
{
Block* pBlock = position.target();
if (pBlock->currentPlant() == nullptr) {
pBlock->setPlant(this);
}
system.addItem(this);
}
void Plant::remove()
{
Block* pBlock = position.target();
if (pBlock->currentPlant() == this)
pBlock->removePlant();
system.removeItem(this);
}
void Plant::eaten(int dh)
{
hp -= dh;
if (hp <= 0)
remove();
}
void Plant::setBlock(int row, int col)
{
position.setBlock(row, col);
}
inline std::string Plant::getStatus() const
{
char buffer[100];
sprintf_s(buffer, 100, "(%d%%)", (int)((double)hp * 100 / initHp()));
return string(buffer);
}
| true |
d1ae67cc733fc816849c9933e4dbc0d4a89fd215 | C++ | BankZKuma/Project11 | /Project13/Source.cpp | UTF-8 | 847 | 3.15625 | 3 | [] | no_license | #include<stdio.h>
float usd(float);
float jpy(float);
float convert(float baht, float (*p)(float));
int main() {
int count = 0;
float collecTusd[10],collecTjpy[10];
float baht;
for (int i = 0; i < 5; i++) {
printf("Enter baht : ");
scanf_s("%f", &baht);
collecTusd[i] = convert(baht, usd);
collecTjpy[i] = convert(baht, jpy);
if (count == 2 || count == 4) {
printf("USD = %f\nYEN = %f\n", convert(baht, usd)*
0.95, convert(baht, jpy)*0.90);
}
else {
printf("USD = %f\nYEN = %f\n", convert(baht, usd), convert(baht, jpy));
}
count++;
}
return 0;
}
float usd(float baht) {
float getdollar = baht / 35;
return getdollar;
}
float jpy(float baht) {
float yen = baht / 0.3;
return yen;
}
float convert(float baht, float (*p)(float)) {
float total = (*p)(baht);
return total;
}
| true |
8dc3ab38eb4fd883934b191f42c42a48c6146d1d | C++ | ksajan/Pancake_topological_sorting | /main.cpp | UTF-8 | 2,605 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int src, dest;
};
class Graph{
public:
vector<vector<int> > adjacentList;
Graph(vector<Edge> const &edgeList, int N){
adjacentList.resize(N);
for (auto &edge: edgeList) {
adjacentList[edge.src].push_back(edge.dest);
}
}
};
void DFS(Graph const &graph, int v, vector<bool> &visited, vector<int> &start, vector<int> &finish, int &time){
start[v] = ++time; // Setting the starting time of vertex v
visited[v] = true; //Marked node v as visited
for (int i: graph.adjacentList[v]){
if (!visited[i]){
DFS(graph, i, visited, start, finish, time);
}
}
finish[v] = ++time; // set vertex v finish time
}
bool sortByFinishTime(const vector<int> &v1, const vector<int> &v2){
return v1[2] > v2[2];
}
void topologicalSort(vector<vector<int> > &finishOrder, int rows, int cols){
sort(finishOrder.begin(), finishOrder.end(), sortByFinishTime);
cout << "Result after Topological Sort on Pancake Graph based on finish time" << endl;
cout << endl;
cout << " Vertex " << " Arrival " << " Finish " << endl;
for (int i=0; i<rows; i++)
{
cout << " " << finishOrder[i][0] << " " << finishOrder[i][1] << " " << finishOrder[i][2] << endl;
}
}
int main(){
vector<Edge> edgeList = {
{0, 3}, {1, 3}, {2, 3}, {3, 4}, {3, 5}, {4, 8}, {5, 7} , {6, 5}, {7, 8}
};
int N = 9;
Graph graph(edgeList, N);
vector<int> start(N);
vector<int> finish(N);
vector<bool> visited(N);
int time = 0;
// Performing DFS traversal to calculate finish time of all unvisited nodes.
for (int i = 0; i < N; i++){
if (!visited[i]){
DFS(graph, i, visited, start, finish, time);
}
}
vector<vector<int> > finishOrder(N);
cout << endl;
cout << "List of Vertex in pancake Graph with their arrival and finish time ( Arrival, Finish )" << endl;
cout << endl;
cout << " Vertex " << " Arrival " << " Finish " << endl;
for (int i = 0; i < N; i++)
{
cout << " "<< i << " " << start[i] << " " << finish[i] << endl;
finishOrder[i] = vector<int>(3);
finishOrder[i][0] = i;
finishOrder[i][1] = start[i];
finishOrder[i][2] = finish[i];
}
cout << endl;
cout << "================================*******************************================================" << endl;
cout << endl;
topologicalSort(finishOrder, N, 3);
return 0;
} | true |
dbf202ac869c6998bd3c1072b01fdd4e27a4e1e9 | C++ | Oepeling/Introduction-to-Robotics | /Lab Work/Lab 8/motorWithoutDriver/motorWithoutDriver.ino | UTF-8 | 382 | 2.796875 | 3 | [] | no_license | const int motorPin = 3;
int givenSpeed = 0;
void setup() {
// put your setup code here, to run once:
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
// if (Serial.available() > 0){
// givenSpeed = Serial.read();
// analogWrite(motorPin, givenSpeed);
// }
analogWrite(motorPin, 255);
// delay(1);
}
| true |
2a0fd19295902e3a6c123d6608c218d117271357 | C++ | duri26/cc26 | /20181102/singleton/autorelesesingleton3.cc | UTF-8 | 916 | 2.84375 | 3 | [] | no_license | ///
/// @file autorelesesingleton.cc
/// @author duri(1197010670@qq.com)
/// @date 2018-11-04 22:26:40
///
#include <stdlib.h>
#include <iostream>
using std::cout;
using std::endl;
class Singleton
{
public:
static Singleton * getInstance()
{
pthread_once(&_once,init);
return _pInstance;
}
static void init()
{
atexit(destroy);
_pInstance =new Singleton;
}
static void destroy()
{
if(_pInstance)
{
delete _pInstance;
cout<<"delete _pInstance3"<<endl;
}
}
private:
Singleton()
{
cout<<"Singleton()"<<endl;
}
~Singleton()
{
cout<<"~Singleton()"<<endl;
}
private :
static pthread_once_t _once;
static Singleton * _pInstance;
};
pthread_once_t Singleton::_once=PTHREAD_ONCE_INIT;
Singleton * Singleton ::_pInstance =getInstance();
int main(void)
{
Singleton *p1=Singleton ::getInstance();
Singleton *p2=Singleton ::getInstance();
cout<<"p1="<<p1<<endl;
cout << "p2="<<p2<<endl;
return 0;
}
| true |
9f75d4b085167997fce409859424aa6cf8c7697e | C++ | Hoshoyo/PhysicsEngine | /HoEngine/src/WindowApi/Primitive.cpp | UTF-8 | 3,128 | 2.78125 | 3 | [] | no_license | #include "Primitive.h"
#include <hmath.h>
Primitive::Primitive()
{
}
Primitive::~Primitive()
{
}
using namespace hm;
Quad::Quad(vec3 center, float sizeX, float sizeY) : Quad(center, sizeX, sizeY, 1, 0){}
Quad::Quad(vec3 center, float sizeX, float sizeY, int textureNumRows, int textureIndex)
{
model = new IndexedModel();
this->index = (float)textureIndex;
this->numRows = (float)textureNumRows;
calcAtlas();
vec3 topL = vec3(center.x - sizeX, center.y + sizeY, 0); // 0
vec3 topR = vec3(center.x + sizeX, center.y + sizeY, 0); // 1
vec3 botL = vec3(center.x - sizeX, center.y - sizeY, 0); // 2
vec3 botR = vec3(center.x + sizeX, center.y - sizeY, 0); // 3
model->getPositions()->push_back(topL);
model->getPositions()->push_back(topR);
model->getPositions()->push_back(botL);
model->getPositions()->push_back(botR);
vec4 normal_v4 = mat4::rotate(vec3(1, 0, 0), -ANGLE) * vec4(0, 0, 1, 1);
vec3 normal = vec3(normal_v4.x, normal_v4.y, normal_v4.z);
model->getNormals()->push_back(normal);
model->getNormals()->push_back(normal);
model->getNormals()->push_back(normal);
model->getNormals()->push_back(normal);
model->getTexCoords()->push_back(vec2(0, 1));
model->getTexCoords()->push_back(vec2(1, 1));
model->getTexCoords()->push_back(vec2(0, 0));
model->getTexCoords()->push_back(vec2(1, 0));
model->getIndices()->push_back(0);
model->getIndices()->push_back(3);
model->getIndices()->push_back(1);
model->getIndices()->push_back(0);
model->getIndices()->push_back(2);
model->getIndices()->push_back(3);
}
Quad::Quad(vec3& topLeftCorner, vec3& bottomRightCorner)
{
model = new IndexedModel();
this->index = 0.0f;
this->numRows = 1.0f;
vec3 bottomLeft = vec3(topLeftCorner.x, bottomRightCorner.y, topLeftCorner.z);
vec3 topRight = vec3(bottomRightCorner.x, topLeftCorner.y, bottomRightCorner.z);
model->positions.push_back(topLeftCorner);
model->positions.push_back(topRight);
model->positions.push_back(bottomLeft);
model->positions.push_back(bottomRightCorner);
vec3 normal = vec3(0, 1, 0);
model->normals.push_back(normal);
model->normals.push_back(normal);
model->normals.push_back(normal);
model->normals.push_back(normal);
model->texCoords.push_back(vec2(0, 0)); // 0
model->texCoords.push_back(vec2(1, 0)); // 1
model->texCoords.push_back(vec2(0, 1)); // 2
model->texCoords.push_back(vec2(1, 1)); // 3
model->indices.push_back(0);
model->indices.push_back(3);
model->indices.push_back(1);
model->indices.push_back(0);
model->indices.push_back(2);
model->indices.push_back(3);
}
void Quad::calcAtlas()
{
int column = (int)index % (int)numRows;
offset.x = (float)column / (float)numRows;
int row = (int)index / (int)numRows;
offset.y = (float)row / (float)numRows;
}
Quad::~Quad()
{
if (model)
delete model;
}
float Quad::getTextureIndex()
{
return index;
}
float Quad::getTextureNumRows()
{
return numRows;
}
vec2& Quad::getTextureOffset()
{
return offset;
}
void Quad::setIndex(int i)
{
this->index = (float)i;
calcAtlas();
}
float Quad::getIndex()
{
return this->index;
}
IndexedModel* Quad::getIndexedModel()
{
return model;
} | true |
2a3090ddd2687d63e990052c76e5c8ab9fd3fa75 | C++ | Petapetilon/Foxygine | /Foxygine/src/Graphics/Lights/Lighting.h | UTF-8 | 908 | 2.578125 | 3 | [] | no_license | #pragma once
#include <list>
#include <vector>
#include "../../Math/Color.h"
#include "../../Math/Vector3.h"
class Light;
class Lighting
{
private:
static const int maxLights = 128;
public:
enum class LightType {
Directional = 0,
Ambient = 1,
Point = 2,
};
struct LightPass {
public:
LightType type;
Vector3 pos;
Vector3 dir;
Color color;
float intensity;
glm::mat4 LSM;
};
private:
static std::list<Light*> lights;
static std::vector<float> positions;
static std::vector<float> directions;
static std::vector<float> colors;
static std::vector<float> intensities;
static std::vector<int> types;
public:
static void RegisterLight(Light* l);
static void UnregisterLight(Light* l);
static void LightDataChanged(Light* l);
static void GL_SetLightUniforms();
static void GL_RenderShadows();
static void GL_BakeEnvironmentLight();
static void GL_BakeLightMaps();
};
| true |
cadeb83809022b72dcdae7791dae4b7aa028b0ef | C++ | VanishRan/leetcode | /RanLeetCode/RanLeetCode/回溯算法/经典/37解数独.cpp | UTF-8 | 2,048 | 3.46875 | 3 | [] | no_license | //
// 37解数独.cpp
// RanLeetCode
//
// Created by mahuanran on 2020/7/12.
// Copyright © 2020 mahuanran. All rights reserved.
//
#include "common.h"
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
backTrack(board, 0, 0);
}
bool backTrack(vector<vector<char>>& board, int row, int col) {
if (col == 9) {
return backTrack(board, row+1, 0);
}
if (row == 9) {
return true;
}
if (board[row][col] != '.') {
return backTrack(board, row, col+1);
}
for (int i=0; i<9; i++) {
char ch = '1' + i;
if (!isValid(board, row, col, ch)) {
continue;
}
board[row][col] = ch;
if(backTrack(board, row, col+1))
return true;
board[row][col] = '.';
}
return false;
}
bool isValid(vector<vector<char>>& board, int row, int col, char ch) {
for (int i=0; i<9; i++) {
//检查行
if (board[i][col] == ch)
return false;
//检查列
if (board[row][i] == ch)
return false;
//检查9*9小正方形
int x = (row/3)*3 + i/3;
int y = (col/3)*3 + i%3;
if (board[x][y] == ch)
return false;
}
return true;
}
};
/*
编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
Note:
给定的数独序列只包含数字 1-9 和字符 '.' 。
你可以假设给定的数独只有唯一解。
给定数独永远是 9x9 形式的。
*/
| true |
1d133fde523cc3c72fa0d8f56517d337062ce920 | C++ | RS-codes/CppQuickRef | /LEVEL_1_NOVICE/21_Default_Function_Parameters.cpp | UTF-8 | 480 | 3.46875 | 3 | [] | no_license | //#21. C++ Default Function Parameters :
#include<iostream>
using namespace std;
void display(int x,int y ,int z=10){ //start initializing frm RIGHTMOST variable
//void display(int x=10,int y,int z){ //generates ERROR,since u initialized the LEFTMOST var
cout<<x<<endl;
cout<<y<<endl;
cout<<z<<endl;
}
int main()
{
display(30,20);//calling ftn with only 2 parameters
//display(30,20,40) // can be used,overwrites the default ftn parameter
return 0;
}
| true |
9a37ef4543972ce236869df70d6683569bcebd4d | C++ | jamesmagnus/light_of_paladin | /Light_of_Paladin/ClassContenaire.h | UTF-8 | 2,187 | 2.875 | 3 | [] | no_license | #pragma once
#include "ClassInventaire.h"
#include "Affichable.h"
/* Classe finale, non héritable */
/* Permet de créer des objets affichable avec un inventaire tel des coffres, ... */
/* Sémantique d'entité */
class Contenaire: public Inventaire, Affichable
{
private:
std::string mProprietaire, mNom;
/* Surcharge de la fonction héritée de Inventaire pour empécher qu'elle soit appelée par erreur */
void afficheDebugInv(std::ostream& rOst) const;
public:
/* Constructeur */
/* pNode, adresse du noeud de scène lié à l'objet */
/* shapeType, enum Shape qui détermine quel forme est utilisée pour représenter l'objet */
/* IsVisible, true si l'objet doit être rendu, true par défaut */
/* max, la taille de l'inventaire du contenaire */
Contenaire(Ogre::SceneNode *pNode, EShape shapeType, bool IsVisible=true, int max=10);
/* Constructeur */
/* pNode, adresse du noeud de scène lié à l'objet */
/* IsVisible, true si l'objet doit être rendu, true par défaut */
/* inv, l'inventaire à partir duquel construire le contenaire, vide cet inventaire */
Contenaire(Ogre::SceneNode *pNode, Inventaire& inv, bool IsVisible=true);
/* Destructeur */
virtual ~Contenaire();
/* clone un contenaire, devant être libéré */
/* Renvoie un pointeur */
/* clone les objets de l'inventaire du contenaire original */
virtual Contenaire* clone() const override;
#ifdef _DEBUG
/* Affiche des informations sur l'objet dans la console, DEBUG */
virtual void afficheDebug(std::ostream& rOst) const override;
#endif
/* Défini le propriètaire du contenaire */
/* nom, le nom du propriètaire, par défaut "all", signifiant aucun propriètaire */
void setProprietaire(std::string const& nom);
/* Renvoie le nom du propriètaire */
/* "all" pour aucun propriètaire */
std::string getProprietaire() const;
/* Défini le nom du contenaire */
/* nom, le nom du contenaire, par défaut "Coffre" */
void setNom(std::string const& nom);
/* Renvoie le nom du contenaire */
std::string getNom() const;
};
/* Surcharge des opérateurs externes */
#ifdef _DEBUG
/* << */
std::ostream& operator<<(std::ostream& rOst, Contenaire const& obj);
#endif | true |
4ae54440a2ef57bc409cbd30821cb7c68a59d4f4 | C++ | harshitagarwal2/CS122 | /NEW/L2/L8-L10 Classes and Objects Contd/Chapter02/L2P24.cpp | WINDOWS-1250 | 795 | 3.875 | 4 | [] | no_license | /*Beginning of friendClass.cpp*/
class B; //forward declaration necessary because
//definition of class B is after the statement
//that declares class B a friend of class A.
class A
{
int x;
public:
void setx(const int=0);
int getx()const;
friend class B; //declaring B as a friend of A
};
class B
{
A * APtr; //pointer to an object of class A
public:
void Map(A * const);
void test_friend(const int);
};
void B::Map(A * const p)
{
APtr = p;
}
void B::test_friend(const int i)
{
APtr->x=i; //accessing the private data member
}
/*End of friendClass.cpp*/
int main()
{
B b;//object of B
A a;//object of A
b.map(&a); //call of member function of B passing address of an object of A
b.test_friend(10); //initalizes private data member of object a
cout<<a.getx();
} | true |
169cf59189f2419af7382e15c6c9ce5914b33acc | C++ | fud200/Algorithm | /p2875.cpp | UTF-8 | 311 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int min(int a, int b) {
return a < b ? a : b;
}
int main(void) {
int N,M, K;
int res=0;
cin >> N >> M >> K;
for (int i = 0; i <= K; i++) {
res = max(res, min((N - i) / 2, (M - K + i)));
}
cout << res << endl;
} | true |
3aade6db02a8af9cbc88c599414f2f3db6bda18d | C++ | eariunerdene/C-course | /Day#3/RGB7012-2.cpp | UTF-8 | 156 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
int a,b,c,d;
cin>>a;
b=a/3600;
c=a%3600/60;
d=a%3600%60;
cout<<b<<" "<<c<<" "<<d;
}
| true |
f7e712401b402a6e9ab6919211398f42610a98cc | C++ | SourangshuGhosh/v3 | /languages/cpp/exercises/concept/strings/.meta/example.cpp | UTF-8 | 403 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "strings.h"
namespace log_line {
std::string message(const std::string& line) {
return line.substr(line.find(':') + 2);
}
std::string log_level(const std::string& line) {
return line.substr(1, line.find(']') - 1);
}
std::string reformat(const std::string& line) {
return message(line) + " (" + log_level(line) + ')';
}
} // namespace log_line
| true |
ec6227730e74ca1b1d04279a915bd81f5282af5f | C++ | przemyslawgesieniec/MetodyNumeryczne | /Zadanie4/newtoncotes.cpp | UTF-8 | 628 | 2.546875 | 3 | [] | no_license | #include "newtoncotes.h"
#include <iostream>
#include <math.h>
using namespace std;
NewtonCotes::NewtonCotes() : Calkowanie()
{
}
double NewtonCotes::calkuj(vector<double> x,double h,Funkcja * wsk,bool waga)
{
double Y=0;
vector<double>y;
for(int i=0;i<x.size();i++)
{
y.push_back(wsk->oblicz(x.at(i),waga));
}
double tmpYnp=0;
double tmpYp=0;
int n =(y.size()-1)/2;
for(int i=1;i<n;i++)
{
tmpYnp+=y.at(2*i-1);
}
for(int i=1;i<n-1;i++)
{
tmpYp+=y.at(2*i);
}
Y = (h/3.0) * (y.at(0) + 4* tmpYnp + 2* tmpYp + y.at(y.size()-1));
return Y;
}
| true |
659f02e698aac562103cb3c8017a4a6355ac2f7c | C++ | sylph01/cea21 | /0411/stream_iterator.cpp | UTF-8 | 533 | 2.953125 | 3 | [] | no_license | #include <vector>
#include <algorithm>
#include <iostream>
#include <fstream> // has ifstream and ofstream
#include <iterator> // has istream_iterator and ostream_iterator
using namespace std;
int main(){
string from, to;
cin >> from >> to;
ifstream is {from};
istream_iterator<string> ii {is};
istream_iterator<string> eos {};
ofstream os {to};
ostream_iterator<string> oo {os, "\n"};
vector<string> b {ii, eos};
sort(b.begin(), b.end());
unique_copy(b.begin(), b.end(), oo);
return !is.eof() || !os;
}
| true |
f493e6f45af1184dcd9c9d929c95688a4fb72e7e | C++ | HeRaNO/OI-ICPC-Codes | /NOI[OpenJudge]/1.13/1.13.34.cpp | UTF-8 | 780 | 3.109375 | 3 | [
"MIT"
] | permissive | //Code By HeRaNO
#include <stdio.h>
char p[32], q[32], r[32];
int MinRadix()
{
int i, minRadix;
minRadix = 1;
for (i = 0; p[i]; i++)
if (minRadix < p[i] - '0') minRadix = p[i] - '0';
for (i = 0; q[i]; i++)
if (minRadix < q[i] - '0') minRadix = q[i] - '0';
for (i = 0; r[i]; i++)
if (minRadix < r[i] - '0') minRadix = r[i] - '0';
return minRadix + 1;
}
bool Radix(int radix)
{
int i, P, Q, R;
for (P = i = 0; p[i]; ++i)
P = P * radix + p[i] - '0';
for (Q = i = 0; q[i]; ++i)
Q = Q * radix + q[i] - '0';
for (R = i = 0; r[i]; ++i)
R = R * radix + r[i] - '0';
if (P * Q == R) return 1;
else return 0;
}
int main()
{
int i;
scanf("%s%s%s", p, q, r);
for (i = MinRadix(); i < 17; i++)
if (Radix(i)) break;
printf("%d\n", i == 17 ? 0 : i);
return 0;
}
| true |
85342324aa6b2840989ad904c45bf6c58d806dd1 | C++ | seth1002/antivirus-1 | /klava/kernel/klavsyslib/os_vm.cpp | UTF-8 | 2,043 | 2.65625 | 3 | [] | no_license | // os_vm.cpp
//
#include <klava/klavsys_os.h>
#include <klava/kl_sys_vmem.h>
////////////////////////////////////////////////////////////////
// Generic virtual memory wrapper
class KLAVSYS_Virtual_Memory : public KLAV_IFACE_IMPL(KLAV_Virtual_Memory)
{
public:
KLAVSYS_Virtual_Memory ();
virtual ~KLAVSYS_Virtual_Memory ();
virtual uint32_t KLAV_CALL vm_pagesize ();
virtual KLAV_ERR KLAV_CALL vm_alloc (void **pptr, uint32_t size, uint32_t prot, void * pref_addr);
virtual KLAV_ERR KLAV_CALL vm_free (void *ptr, uint32_t size);
virtual KLAV_ERR KLAV_CALL vm_protect (void *ptr, uint32_t size, uint32_t newprot);
private:
KLAVSYS_Virtual_Memory (const KLAVSYS_Virtual_Memory&);
KLAVSYS_Virtual_Memory& operator= (const KLAVSYS_Virtual_Memory&);
};
////////////////////////////////////////////////////////////////
static unsigned int map_prot (unsigned int prot)
{
unsigned int n = 0;
if (prot & KLAV_MEM_PROT_READ) n |= KL_VIRTMEM_READ;
if (prot & KLAV_MEM_PROT_WRITE) n |= KL_VIRTMEM_WRITE;
if (prot & KLAV_MEM_PROT_EXEC) n |= KL_VIRTMEM_EXECUTE;
return n;
}
KLAVSYS_Virtual_Memory::KLAVSYS_Virtual_Memory ()
{
}
KLAVSYS_Virtual_Memory::~KLAVSYS_Virtual_Memory ()
{
}
uint32_t KLAVSYS_Virtual_Memory::vm_pagesize ()
{
return KLSysNS::vm_pagesize ();
}
KLAV_ERR KLAVSYS_Virtual_Memory::vm_alloc (void **pptr, uint32_t size, uint32_t prot, void * pref_addr)
{
*pptr = KLSysNS::vm_allocate (size, map_prot (prot), pref_addr);
if (*pptr == 0) return KLAV_EUNKNOWN;
return KLAV_OK;
}
KLAV_ERR KLAVSYS_Virtual_Memory::vm_free (void *ptr, uint32_t size)
{
KLSysNS::vm_deallocate (ptr, size);
return KLAV_OK;
}
KLAV_ERR KLAVSYS_Virtual_Memory::vm_protect (void *ptr, uint32_t size, uint32_t newprot)
{
bool ok = KLSysNS::vm_protect (ptr, size, map_prot (newprot));
if (! ok) return KLAV_EUNKNOWN;
return KLAV_OK;
}
KLAV_Virtual_Memory * KLAV_CALL KLAVSYS_Get_Virtual_Memory ()
{
static KLAVSYS_Virtual_Memory g_vmem;
return & g_vmem;
}
| true |
22acb6ee566ab2a40aab9d9a3f014c6e9c7abb4e | C++ | donmayun/Algorithm-learning-through-Problems | /cpp/The Stable Marriage Problem/TheStableMarriageProblem.cpp | UTF-8 | 2,856 | 2.984375 | 3 | [
"MIT"
] | permissive | //
// TheStableMarriageProblem.cpp
// laboratory
//
// Created by 徐子珊 on 14/12/31.
// Copyright (c) 2014年 xu_zishan. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <set>
#include <hash_map>
#include <iterator>
using namespace std;
struct Male{
string pref;
size_t current;
Male(string p=""):pref(p), current(0){}
};
struct Female{
string pref;
bool engaged;
Female(string p=""): pref(p), engaged(false){}
};
struct Couple{
char female, male;
Couple(char f=' ', char m=' '):female(f), male(m){}
};
bool operator==(const Couple& a, const Couple& b){
return a.female==b.female;
}
bool operator<(const Couple& a, const Couple& b){
return a.male<b.male;
}
ostream& operator<<(ostream& out, const Couple& a){
out<<a.male<<" "<<a.female;
return out;
}
set<Couple, less<Couple> > stableMarriage(hash_map<char, Male>& M, hash_map<char, Female>& F){
set<Couple, less<Couple> > A;
queue<char> Q;
hash_map<char, Male>::iterator a;
for (a=M.begin(); a!=M.end(); a++)
Q.push(a->first);
while (!Q.empty()) {
char m=Q.front();
char f=M[m].pref[M[m].current++];
if (!F[f].engaged) {
A.insert(Couple(f, m));
F[f].engaged=true;
Q.pop();
}else{
set<Couple, less<Couple> >::iterator couple=find(A.begin(), A.end(), Couple(f));
char m1=couple->male;
if ((F[f].pref).find(m)<(F[f].pref).find(m1)) {
A.erase(Couple(f, m1));
A.insert(Couple(f, m));
Q.pop();
Q.push(m1);
}
}
}
return A;
}
int main(){
ifstream inputdata("The Stable Marriage Problem/inputdata.txt");
ofstream outputdata("The Stable Marriage Problem/outputdata.txt");
int t;
inputdata>>t;
for (int i=0; i<t; i++) {
int n;
string aline;
inputdata>>n;
hash_map<char, Male> M;
hash_map<char, Female> F;
getline(inputdata, aline, '\n');
getline(inputdata, aline, '\n');
for(int j=0; j<n; j++){
getline(inputdata, aline, '\n');
char name=aline[0];
string preference=aline.substr(2,n);
M[name]=Male(preference);
}
for(int j=0; j<n; j++){
getline(inputdata, aline, '\n');
char name=aline[0];
string preference=aline.substr(2,n);
F[name]=Female(preference);
}
set<Couple, less<Couple> > A=stableMarriage(M, F);
copy(A.begin(),A.end(),ostream_iterator<Couple>(outputdata, "\n"));
outputdata<<endl;
copy(A.begin(),A.end(),ostream_iterator<Couple>(cout, "\n"));
cout<<endl;
}
inputdata.close();
outputdata.close();
return 0;
} | true |
2aae238b389cbe6921767bdfa2b1ceb63c9128aa | C++ | mitmehta/myCcode | /Reorder_index.cpp | UTF-8 | 781 | 4.3125 | 4 | [] | no_license | /* Arrange Array according to given indexex */
#include<iostream>
using namespace std;
void Reorder_Array(int arr[], int index[], int n)
{
int oldI, newI;
for(int i = 0; i < n; i++) {
while(index[i] != i) {
oldI = index[index[i]];
newI = arr[index[i]];
arr[index[i]] = arr[i];
index[index[i]] = index[i];
index[i] = oldI;
arr[i] = newI;
}
}
}
void PrintArray(int arr[], int n)
{
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {50, 40, 10, 30, 20};
int index[] = {4, 3, 0, 2, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Print Array before Rearranging" << endl;
PrintArray(arr, n);
Reorder_Array(arr, index, n);
cout << "Print Array After Rearranging" << endl;
PrintArray(arr, n);
}
| true |
fe424025cf52784de57f567249932cdf727142b2 | C++ | angieshu/Space_Shooter | /src/Star.class.cpp | UTF-8 | 387 | 2.59375 | 3 | [] | no_license | /**
* @Author: Anhelina Shulha <angieshu>
* @Date: Jul-25-2017
* @Email: anhelina.shulha@gmail.com
* @Filename: Star.class.cpp
* @Last modified by: angieshu
* @Last modified time: Jul-25-2017
*/
#include "Star.class.hpp"
Star::Star(int x) {
setWidth(STAR_WIDTH);
setHeight(STAR_HEIGHT);
setX(x);
setY(-STAR_HEIGHT - 1);
}
Star::~Star(void) {
}
void Star::moveDown(void) {
setY(getY() + 1);
}
| true |
ad13f9d3d0769c777ef7d28305631a7ddae56db1 | C++ | TadeuszNorek/lab2 | /main.cpp | UTF-8 | 986 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
int gcd (int a, int b);
struct fraction
{
int nominator;
int denominator;
bool is_correct()
{
return((abs(denominator)>abs(nominator)) && (denominator!=0)?true:false);
};
void shorten()
{
int a = gcd(abs(nominator), abs(denominator));
nominator = nominator/a;
denominator = denominator/a;
};
};
int main(int argc, char **argv)
{
int n = atoi(argv[1]);
srand(time(NULL));
fraction *fractions = new fraction[n];
for (int i=0; i<n; i++)
{
do
{
fractions[i].nominator = (rand() % 19) - 9;
fractions[i].denominator = (rand() % 19) - 9;
}
while (fractions[i].is_correct() != true);
fractions[i].shorten();
}
for (int i = 0; i < n; assert(fractions[i++].is_correct()))
printf("[%i] %2i / %2i\n", i, fractions[i].nominator, fractions[i].denominator);
}
int gcd(int a, int b)
{
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return a;
}
| true |
acd12c6d8325c5715df5a8cd31e5fbb4a6a590de | C++ | YorkeWei/DataStuctureHomework | /heap.hpp | UTF-8 | 3,235 | 3.125 | 3 | [] | no_license | #define Parent(i) ((i - 1) >> 1) //i的父亲
#define LChild(i) (1 + (( i ) << 1))//i的左儿子
#define RChild(i) ((1 + ( i )) << 1)//i的右儿子
#define InHeap(n, i) (((-1) < ( i )) && (( i ) < ( n )))
#define LChildValid(n, i) InHeap(n, LChild( i ))
#define RChildValid(n, i) InHeap(n, RChild( i ))
#define Smaller(HC, i, j) (cmp(HC[i] , HC[j]) ? i : j)
#define ProperParent(HC, n, i)\
(RChildValid(n, i) ? Smaller(HC, Smaller(HC, i, LChild(i)), RChild(i)) : \
(LChildValid(n, i) ? Smaller(HC, i, LChild(i)) : i)\
)
#define DEFAULT_CAPACITY 100
#include <iostream>
#include <vector>
template <typename T>
class heap
{
protected:
T* heapChain;
int _size;
int _capacity;
bool(*cmp)(T, T);
public:
heap()
{
_capacity = DEFAULT_CAPACITY;
heapChain = new T[_capacity];
_size = 0;
}
heap(T* e, int lo, int hi, void(*cmp)(T, T))
{
_capacity = DEFAULT_CAPACITY;
heapChain = new T[_capacity];
_size = 0;
this->cmp = cmp;
for (int i = lo; i < hi; i++)
insert(e[i]);
}
heap(std::vector<T> e, bool(*cmp)(T, T))
{
_capacity = DEFAULT_CAPACITY;
heapChain = new T[_capacity];
_size = 0;
this->cmp = cmp;
int len = e.size();
for (int i = 0; i < len; i++)
insert(e[i]);
}
void insert(T e)
{
expand();
int i = _size;
heapChain[_size++] = e;
while ((i > 0) && !cmp(heapChain[Parent(i)], heapChain[i]))
{
std::swap(heapChain[Parent(i)], heapChain[i]);
i = Parent(i);
}
}
void expand()
{
//空间不足时,将容量扩为原来的2倍
if (_size < _capacity)
return;
T* oldHeapChain = heapChain;
heapChain = new T[_capacity << 1];
for (int i = 0; i < _size; i++)
heapChain[i] = oldHeapChain[i];
delete[] oldHeapChain;
}
T delMin()//删除堆顶元素
{
if (_size <= 0)
return NULL;
T e = heapChain[0];
heapChain[0] = heapChain[--_size];
int n = _size;
int i = 0, j;
while (i != (j = ProperParent(heapChain, n, i)))
{
std::swap(heapChain[i], heapChain[j]);
i = j;
}
shrink();
return e;
}
T del(int rank)
{
if (rank < 0 || rank >= _size)
return NULL;
T e = heapChain[rank];
heapChain[rank] = heapChain[--_size];
int n = _size;
int i = rank, j;
if (i == ProperParent(heapChain, n, i))
{
while ((i > 0) && !cmp(heapChain[Parent(i)] , heapChain[i]))
{
std::swap(heapChain[Parent(i)], heapChain[i]);
i = Parent(i);
}
}
else {
while (i != (j = ProperParent(heapChain, n, i)))
{
std::swap(heapChain[i], heapChain[j]);
i = j;
}
}
shrink();
return e;
}
void shrink()
{
//有效空间不足25%时,将容量缩小为原来的50%
if (_size << 2 >= _capacity)
return;
T* oldHeapChain = heapChain;
heapChain = new T[_capacity >> 1];
for (int i = 0; i < _size; i++)
heapChain[i] = oldHeapChain[i];
delete[] oldHeapChain;
}
T getMin()
{
if (_size <= 0)
return NULL;
return heapChain[0];
}
friend void HuffmanTree(double* f, char* ch, int _size);
};
template <typename T>
void heapSort(T* _elem, int lo, int hi)
{
heap<T> h(_elem, lo, hi);
for (int i = lo; i < hi; i++)
_elem[i] = h.delMin();
}
| true |
98d2e2c054baa7165b7424f1a50dc20cfabd1959 | C++ | mviseu/Cpp_primer | /Chapter9/9_16_alternative.cc | UTF-8 | 547 | 3.5 | 4 | [] | no_license | #include <vector>
#include <iostream>
#include <list>
using std::vector;
using std::cout;
using std::endl;
using std::list;
int main() {
vector<int> v1 = {0, 1, 2, 3};
list<int> l1 = {0, 1, 2};
if(v1.size() != l1.size()) {
cout << "The vectors are not equal" << endl;
return 0;
}
auto iterV2 = l1.cbegin();
for(auto iterV1 = v1.cbegin(); iterV1 != v1.cend(); ++iterV1, ++iterV2) {
if(*iterV1 != *iterV2) {
cout << "The vectors are not equal" << endl;
return 0;
}
}
cout << "The vectors are equal" << endl;
return 0;
} | true |
e70edbab0e06e69ff97ce8c6f9a2aebaf02ac466 | C++ | qixianbd/partition_wqm | /node.h | UTF-8 | 1,358 | 2.828125 | 3 | [] | no_license | /*
* node.h
*
* Created on: 2011-12-28
* Author: harry
*/
#ifndef NODE_H_
#define NODE_H_
#include <vector>
#include "common.h"
namespace util {
class node {
public:
enum node_group_status{
INIT,
BIG,
SMALL,
MIDDLE
};
enum node_kind{ LOOP, NODE_GROUP};
enum { EDGE_INF = 0x00FFFFFF};
private:
std::vector<int> node_group;
double edge_evalue;
node_group_status status;
node_kind kind;
/**
* spawn_pos;是由外部由set方法传入,由get传出,外部负责内存回收
*/
tnle *spawn_pos;
public:
//static const int EDGE_INF;
public:
node();
node(const std::vector<int> node_vec);
virtual ~node();
double getEdge_evalue() const;
std::vector<int> getNode_group() const;
tnle *getSpawn_pos() const;
node_group_status getStatus() const;
void setEdge_evalue(double edge_evalue);
void setNode_group(std::vector<int> node_group);
void setSpawn_pos(tnle *spawn_pos);
void setStatus(node_group_status status);
node_kind getKind() const;
void setKind(node_kind kind);
bool is_loop()const{return kind == LOOP;}
bool is_node_group()const{return kind == NODE_GROUP;}
/**
* format:[1, 2, 3, 4]
*/
void print(FILE *fp);
};
//const int EDGE_INF = 0x00FFFFFF;
DECLARE_LIST_CLASS(node_list, node *);
}
#endif /* NODE_H_ */
| true |
966a9bdbbed213e497ce71b3f9ce51afbafba4ae | C++ | Mioriarty/RhinoGameEngine | /rhino-core/src/modules/rendering/data/Texture.cpp | UTF-8 | 1,622 | 2.625 | 3 | [] | no_license | #include "Texture.h"
#define STB_IMAGE_IMPLEMENTATION
#define ABSOLUTE_PATH "C:/Users/Moritz/Desktop/Programmieren/C++/RhinoEngine/rhino-core/"
#include <stb_image.h>
#include <iostream>
namespace rhino {
const TextureSettings TextureSettings::DEFAULT = {TextureSettings::FilterMode::LINEAR, TextureSettings::WrapMode::CLAMP, TextureSettings::WrapMode::CLAMP, true, false};
Texture::Texture(const std::string& file, const TextureSettings& settings)
:settings(settings) {
stbi_set_flip_vertically_on_load(1);
buffer = stbi_load((ABSOLUTE_PATH + file).c_str(), &width, &height, &bpp, 4);
if (buffer == nullptr) {
std::cout << "stb_image couldn't read the image (" << file << ")" << std::endl;
return;
}
glGenTextures(1, &glId);
glBindTexture(GL_TEXTURE_2D, glId);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)settings.filterMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)settings.filterMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (int)settings.wrapHorizontal);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (int)settings.wrapVertical);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (void*)buffer);
glBindTexture(GL_TEXTURE_2D, 0);
if (!settings.storeData)
stbi_image_free(buffer);
}
Texture::~Texture() {
glDeleteTextures(1, &glId);
}
void Texture::bind(unsigned int slot) const {
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, glId);
}
void Texture::unbind() const {
glBindTexture(GL_TEXTURE_2D, 0);
}
} | true |
7653442736747b11a193268bc14a3c1b0fb44823 | C++ | jaladhivyas/CPP-Basic-Programming | /CPP_Programming/memory_management_set_2.h | UTF-8 | 2,631 | 4.15625 | 4 | [] | no_license | #ifndef MEMORY_MANAGEMENT_SET_2_H
#define MEMORY_MANAGEMENT_SET_2_H
#include "iostream"
namespace std
{
namespace memSet2
{
// new and delete operator
/*
To allocate space dynamically, use the unary operator new, followed by the type being allocated.
new int; // dynamically allocates an int
new double; // dynamically allocates a double
to create an array dynamically, use the same form, but put brackets with a size after the type:
new int[40]; // dynamically allocates an array of 40 ints
new double[size]; // dynamically allocates an array of size doubles
the new operator returns the starting address of the allocated space, and this address can be stored in a pointer:
int * p; // declare a pointer p
p = new int; // dynamically allocate an int and load address into p
double * d; // declare a pointer d
d = new double; // dynamically allocate a double and load address into d
// similarly
int x = 40;
int * list = new int[x];
float * numbers = new float[x+10];
*/
// delete
/*
To deallocate memory that was created with new, we use the unary operator delete. The one operand should be a pointer that stores the address of the space to be deallocated:
int * ptr = new int; // dynamically created int
// ...
delete ptr; // deletes the space that ptr points to
the pointer ptr still exists in this example.
That's a named variable subject to scope and extent determined at compile time. It can be reused:
ptr = new int[10]; // point p to a brand new array
To deallocate a dynamic array, use this form:
delete [] name_of_pointer;
Example:
int * list = new int[40]; // dynamic array
delete [] list; // deallocates the array
list = 0; // reset list to null pointer
After deallocating space, it's always a good idea to reset the pointer to null
unless you are pointing it at another valid target right away.
*/
/*
Note:
int *x = new int[size]; // It throws exception bad_alloc if allocation fails.
using keyword nothrow it can be avoided and it returns nullptr
E.g.
x = new (nothrow) int[size];
*/
// new vs malloc
// 1. new is an operator whereas malloc() is a library function.
// 2. new allocates memory and calls constructor for object initialization.
// But malloc() allocates memory and does not call constructor.
// 3. Return type of new is exact data type while malloc() returns void*.
// 4. new is faster than malloc() because an operator is always faster than a function.
}
}
#endif // MEMORY_MANAGEMENT_SET_2_H
| true |
d0600b50146b5d24c09416a1b9dd0743134668f3 | C++ | TanavShah/SPOJ | /cpp_codes/fctrl.cpp | UTF-8 | 388 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int fun(int p)
{
int ans = 0;
for(int i=1;;i++)
{
ans += (p/(pow(5,i)));
if((p/(pow(5,i))) == 0)
{
break;
}
}
return ans;
}
int main()
{
int t;
cin >> t;
for(int aa = 0; aa < t ; aa++)
{
int n;
cin >> n;
int sum;
sum = fun(n);
cout << sum << endl;
}
return 0;
}
| true |
fcdd9976de8093a60dac1aec2e387685a2112abf | C++ | YangKian/MyPractice | /cpp/basic/new/main.cpp | UTF-8 | 1,054 | 3.6875 | 4 | [] | no_license | #include <iostream>
using string = std::string;
class Entity {
private:
string m_Name;
public:
// 构造函数的另一种写法:Constructor Initializer List
// 可以在 {} 中添加其他初始化逻辑
Entity() : m_Name("Unknown") {}
Entity(const string& name) : m_Name(name) {}
const string& GetName() const { return m_Name; }
};
int main() {
// 调用默认构造器
Entity e;
Entity e_1 = Entity();
// 使用参数进行初始化
Entity e2("Tome");
Entity e2_1 = Entity("Tome");
// new 关键字:在堆上分配内存,并返回一个指针,同时还会调用对应的构造器
auto* e3 = new Entity();
auto* e4 = new Entity[50];
// malloc 分配内存是 C 中的用法,与 new 的区别在于,malloc 只分配内存,不会调用构造器
auto* e5 = (Entity*)malloc(sizeof(Entity));
// malloc 分配的内存要使用 free 来释放
free(e5);
// 使用 new 关键字分配的空间要使用 delete 进行回收
delete e3;
delete[] e4;
}
| true |
11106166218b148a689fbd7ef556aa92bf3fee33 | C++ | BAntDit/enttx | /src/systemManager.h | UTF-8 | 7,217 | 2.609375 | 3 | [] | no_license | //
// Created by bantdit on 12/31/18.
//
#ifndef ENTTX_SYSTEMMANAGER_H
#define ENTTX_SYSTEMMANAGER_H
#include "config.h"
#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>
namespace enttx {
template<typename Config>
class SystemManager;
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
class SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>
{
public:
using config_t = SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>;
using system_list_t = typename config_t::system_list_t;
template<typename... Components>
using system_list_for_components_t =
typename easy_mp::flatten<easy_mp::type_list<std::conditional_t<Systems::template is_in_use_v<Components...>,
easy_mp::type_list<Systems&>,
easy_mp::type_list<>>...>>::type;
template<typename... Components>
using const_system_list_for_components_t =
typename easy_mp::flatten<easy_mp::type_list<std::conditional_t<Systems::template is_in_use_v<Components...>,
easy_mp::type_list<Systems const&>,
easy_mp::type_list<>>...>>::type;
template<typename S, typename R = void>
using enable_if_system = std::enable_if_t<system_list_t ::template has_type<S>::value, R>;
SystemManager();
template<typename System>
auto get() const -> enable_if_system<System, System const&>;
template<typename System>
auto get() -> enable_if_system<System, System&>;
template<typename... Components>
auto getSystemsForComponents() ->
typename system_list_for_components_t<Components...>::template specialization_t<std::tuple>;
template<typename... Components>
auto getSystemsForComponents() const ->
typename const_system_list_for_components_t<Components...>::template specialization_t<std::tuple>;
template<typename EntityManager, typename... Args>
void update(EntityManager&& entityManager, Args&&... args);
template<typename... Components>
static constexpr bool has_system_for_components_v = (Systems::template is_in_use_v<Components...> | ...);
private:
template<size_t STAGE, typename System, typename EntityManager, typename... Args>
void _update(EntityManager&& entityManager, Args&&... args);
template<size_t STAGE, typename EntityManager, typename... Args>
void _updateStage(EntityManager&& entityManager, Args&&... args);
template<size_t... STAGES, typename EntityManager, typename... Args>
void _updateStages(std::index_sequence<STAGES...>, EntityManager&& entityManager, Args&&... args);
template<typename... Ss>
auto _getSystemTuple(easy_mp::type_list<Ss...>) const -> std::tuple<Ss...>;
template<typename... Ss>
auto _getSystemTuple(easy_mp::type_list<Ss...>) -> std::tuple<Ss...>;
private:
std::tuple<Systems...> systems_;
};
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::SystemManager()
: systems_{ Systems()... }
{}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename EntityManager, typename... Args>
void SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::update(
EntityManager&& entityManager,
Args&&... args)
{
_updateStages(std::make_index_sequence<UPDATE_STAGE_COUNT>{},
std::forward<EntityManager>(entityManager),
std::forward<Args>(args)...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<size_t... STAGES, typename EntityManager, typename... Args>
void SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::_updateStages(
std::index_sequence<STAGES...>,
EntityManager&& entityManager,
Args&&... args)
{
(_updateStage<STAGES>(std::forward<EntityManager>(entityManager), std::forward<Args>(args)...), ...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<size_t STAGE, typename EntityManager, typename... Args>
void SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::_updateStage(
EntityManager&& entityManager,
Args&&... args)
{
(_update<STAGE, Systems>(std::forward<EntityManager>(entityManager), std::forward<Args>(args)...), ...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<size_t STAGE, typename System, typename EntityManager, typename... Args>
void SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::_update(
EntityManager&& entityManager,
Args&&... args)
{
std::get<system_list_t::template get_type_index<System>::value>(systems_)
.template update<std::decay_t<decltype(*this)>, EntityManager, STAGE>(
*this, std::forward<EntityManager>(entityManager), std::forward<Args>(args)...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename System>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::get() const
-> enable_if_system<System, System const&>
{
return std::get<system_list_t::template get_type_index<System>::value>(systems_);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename System>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::get()
-> enable_if_system<System, System&>
{
return std::get<system_list_t::template get_type_index<System>::value>(systems_);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename... Ss>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::_getSystemTuple(
easy_mp::type_list<Ss...>) const -> std::tuple<Ss...>
{
return std::tuple<Ss const&...>(std::get<std::decay_t<Ss>>(systems_)...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename... Ss>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::_getSystemTuple(
easy_mp::type_list<Ss...>) -> std::tuple<Ss...>
{
return std::tuple<Ss&...>(std::get<std::decay_t<Ss>>(systems_)...);
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename... Components>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::getSystemsForComponents()
-> typename system_list_for_components_t<Components...>::template specialization_t<std::tuple>
{
return _getSystemTuple(system_list_for_components_t<Components...>{});
}
template<size_t UPDATE_STAGE_COUNT, typename... Systems>
template<typename... Components>
auto SystemManager<SystemManagerConfig<UPDATE_STAGE_COUNT, easy_mp::type_list<Systems...>>>::getSystemsForComponents()
const -> typename const_system_list_for_components_t<Components...>::template specialization_t<std::tuple>
{
return _getSystemTuple(const_system_list_for_components_t<Components...>{});
}
}
#endif // ENTTX_SYSTEMMANAGER_H
| true |
8e3ea84c9565c97160aa8dff355349cb8adf6140 | C++ | ZetaTwo/sa104x-kexjobb | /Verifier/KeyVerifier.cpp | UTF-8 | 3,663 | 2.984375 | 3 | [] | no_license | #include <vector>
#include <fstream>
#include <ios>
#include "KeyVerifier.h"
#include "Node.h"
#include "IntLeaf.h"
#include "FileNames.h"
bool keyVerifier(proofStruct &pfStr)
{
Node pk;
// Step 1 - Read public key from file and reject if not successful
try {
pk = Node(pfStr.directory + "/" + FULL_PUBLIC_KEY_FILE);
}
catch(...)
{
// Something wrong with file/nonexisting file
return false;
}
// Check if public key is OK
if(!isPublicKey(pfStr.Gq, pk))
{
// Did not read a key from file, reject proof
return false;
}
// Step 2 - Read partial public keys and check consistency with public key
Node pub_keys;
IntLeaf pub_key;
for(unsigned int i = 1; i <= pfStr.lambda; i++)
{
// Read correct file for partial public key nr i
char ppk_filename[FILENAME_BUFFER_SIZE];
sprintf(ppk_filename, PARTIAL_PUBLIC_KEY_FILE_TMPL.c_str(), i);
try
{
std::ifstream key_file((pfStr.directory + "/proofs/" + ppk_filename).c_str(), std::ios_base::binary | std::ios_base::in);
pub_key = IntLeaf(key_file);
}
catch(...)
{
// Not possible to read file
return false;
}
// Check to see if partial public key is OK
if(!isPartialPublicKey(pfStr.Gq, pub_key))
{
// Did not read a key from file, reject proof
return false;
}
// Save partial public key in partial public key array
pub_keys.addChild(pub_key);
}
// Save public key pk = (g,y) and max size of ints p for convenience
const IntLeaf &g = pk.getIntLeafChild(0);
const IntLeaf &y = pk.getIntLeafChild(1);
const IntLeaf &p = pfStr.Gq.getIntLeafChild(0);
// multiply ppk:s and check that the product is consistent with pk
IntLeaf prod = pub_keys.prodMod(p);
if(pub_keys.prodMod(p) != y)
{
// Public keys do not match, reject proof
return false;
}
// Step 3 - read partial secret keys
Node sec_keys;
IntLeaf sec_key;
for(unsigned int i = 1; i <= pfStr.lambda; i++)
{
// Create correct filename
char psk_filename[FILENAME_BUFFER_SIZE];
sprintf(psk_filename, PARTIAL_SECRET_KEY_FILE_TMPL.c_str(), i);
std::ifstream fstr((pfStr.directory + "/" + psk_filename).c_str(), std::fstream::in);
// If file exists
if(fstr)
{
sec_key = IntLeaf(fstr);
// Check to see if sec_key is really a secret key
if(!isPartialSecretKey(pfStr.Gq, sec_key))
{
// Did not read a valid key from file, reject proof
return false;
}
// Check consistency with ppk:s, (children indices starts with 0)
if(pub_keys.getIntLeafChild(i-1) != g.expMod(sec_key, p))
{
// Secret key does not match public key, reject proof
return false;
}
}
// If file does not exist
else
{
// Set invalid value to mark this
sec_key = BOTTOM;
}
// Add psk to psk array
sec_keys.addChild(sec_key);
}
// Step 4
// Save keys to proofStruct instead of returning array
pfStr.pk = pk;
pfStr.y = pub_keys;
pfStr.x = sec_keys;
return true;
}
bool isPublicKey(const Node &G, const Node &pk)
{
// A public key pk = (g,y) where g and y are elements of Gq
if(isElemOfGq(G, pk.getIntLeafChild(0)) &&
isElemOfGq(G, pk.getIntLeafChild(1)))
{
return true;
}
return false;
}
bool isPartialPublicKey(const Node &G, const IntLeaf &ppk)
{
// A partial public key ppk is an element of Gq
return isElemOfGq(G, ppk);
}
bool isPartialSecretKey(const Node &G, const IntLeaf &psk)
{
// A partial secret key pskk is an element of Zq, where q is the same as in Gq
return isElemOfZn(G.getIntLeafChild(1), psk);
}
| true |
94c70a1e59420d03a64cf1d7c741f770fa8ba12f | C++ | studiefredfredrik/thermominer | /ArduinoTemperatureSensor/I2C_functions.ino | UTF-8 | 747 | 3.328125 | 3 | [
"MIT"
] | permissive | // Read 16 bit int from I2C address addr and register reg
uint16_t read16(uint8_t addr, uint8_t reg) {
uint16_t data;
Wire.beginTransmission(addr);
Wire.write(reg); // send register address to read from
Wire.endTransmission();
Wire.beginTransmission(addr);
Wire.requestFrom((uint8_t)addr, (uint8_t)2); // request 2 bytes of data
data = Wire.read(); // receive data
data <<= 8;
data |= Wire.read();
Wire.endTransmission();
return data;
}
// Write data to I2C address addr, register reg
void write16(uint8_t addr, uint8_t reg, uint16_t data) {
Wire.beginTransmission(addr);
Wire.write(reg); // sends register address to write to
Wire.write(data>>8); // write data
Wire.write(data);
Wire.endTransmission();
}
| true |
aa11ef39dce909601c9d132e1fc943acdecfa53a | C++ | dante72/sudoku | /sources/actions.cpp | UTF-8 | 3,284 | 2.84375 | 3 | [
"MIT"
] | permissive | #define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include "header.h"
char **correct_sudoku(Sudoku item, const int nn, int point, bool game)
{
int i = point / nn;
int j = point % nn;
int x;
bool enter = false;
char** m1 = nullptr, **m = item.task;
if (game)
{
item.result = new_copy(m, nn);
m1 = item.result;
}
do {
system("cls");
print_sudoku(item, nn, point);
if (m1 && n_space(m, nn) == -1)
{
printf("\tYOU WIN!!\n\tPress ENTER...");
ft_free(m);
m = m1;
getchar();
enter = true;
}
else
printf("\tUse Space, Up, Dowp, Left, Right\n\tPress ESC to exit...");
x = _getch();
if (x >= Button0 && x <= Button9)
{
char ch = x - Button0 + '0';
if (ch == '0')
m[i][j] = '.';
else
if (check_sq(m, i, j, ch))
m[i][j] = ch;
}
switch (x)
{
case Down:
if (i + 1 < nn)
i++;
break;
case Right:
if (j + 1 < nn)
j++;
break;
case Up:
if (i - 1 >= 0)
i--;
break;
case Left:
if (j - 1 >= 0)
j--;
break;
case (Space):
if(!game || m1[i][j] == '.')
do {
if (m[i][j] == '9')
m[i][j] = '.';
else
if (m[i][j] == '.')
m[i][j] = '1';
else
m[i][j]++;
if (m[i][j] == '.')
break;
} while (!check_sq(m, i, j, m[i][j]));
break;
case ESC:
if (game)
{
ft_free(m);
m = m1;
}
enter = true;
break;
}
point = nn * i + j;
} while (!enter);
return m;
}
Sudoku* load(Sudoku* list, int& index)
{
char buff[100];
FILE* f;
int n = 9;
if ((f = fopen("example.txt", "r")) != NULL)
{
while (!feof(f))
{
fgets(buff, sizeof(buff), f);
if (check_str(buff, n))
{
list = (Sudoku*)realloc(list, sizeof(Sudoku) * (index + 1));
list[index].task = create_squard(n);
list[index].result = nullptr;
list[index].n_result = -1;
list[index].task = str_to_squard(list[index].task, n, buff);
list[index].index = index;
index++;
}
}
fclose(f);
}
return list;
}
void free_list(Sudoku* list, int index)
{
for (int i = 0; i < index; i++)
{
ft_free(list[i].task);
ft_free(list[i].result);
}
free(list);
}
void save(Sudoku* list, int index)
{
FILE* f;
int i = 0;
if ((f = fopen("example.txt", "w")) != NULL)
{
while (i < index)
{
int j = 0;
while (list[i].task[j])
{
fprintf(f, "%s ", list[i].task[j]);
j++;
}
fprintf(f, "\n");
i++;
}
fprintf(f, "\n");
fclose(f);
}
}
Sudoku* new_item(Sudoku* list, int& index)
{
int n = 9;
list = (Sudoku*)realloc(list, sizeof(Sudoku) * (index + 1));
list[index].task = create_squard(n);
list[index].task = empty_squard(list[index].task, n);
list[index].result = nullptr;
list[index].n_result = -1;
list[index].index = index;
index++;
return list;
}
Sudoku* del_item(Sudoku* list, int& index, int k)
{
int n = 9, i = 0, j = 0;
Sudoku* temp_list;
if (index == 1)
temp_list = nullptr;
else
temp_list = (Sudoku*)malloc(sizeof(Sudoku) * index);
while (i < index)
{
if (i != k)
{
temp_list[j].task = new_copy(list[i].task, n);
temp_list[j].result = new_copy(list[i].result, n);
temp_list[j].n_result = list[i].n_result;
temp_list[j].index = j;
j++;
}
i++;
}
free_list(list, index);
index--;
list = temp_list;
return list;
} | true |
02721d96b6d5e003fd7cd171890f253fee2a2d54 | C++ | nguyenvandai61/DiscreteMath | /ChinhHopLapSinh.cpp | UTF-8 | 716 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void init(int *a, int &n, int &k) {
cout << "Nhap n: ";
cin >> n;
cout << "Nhap k: ";
cin >> k;
for (int i = 1; i <= k; i++)
a[i] = 1;
}
void out(int *a, int k)
{
for (int i = 1; i <= k; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
bool isLast(int *a, int n, int k)
{
for(int i = k; i>=1; i--)
if (a[i] != n) return false;
return true;
}
void Gen(int *a, int n, int k)
{
int p = k;
while (a[p] == n) p--;
a[p]++;
for (int i = p+1; i <= k; i++)
a[i] = 1;
out(a, k);
}
void Method(int *a, int &n, int &k)
{
init(a, n, k);
out(a, k);
while(!isLast(a, n, k))
{
Gen(a, n, k);
}
}
int main()
{
int n, k;
int a[100];
Method(a, n, k);
}
| true |
5b09c0e4b987b8c8ab9eaeb6feb252ad1df906b3 | C++ | catejaeger86/school | /computer_vision/assignment3/4_em/em.hpp | UTF-8 | 1,214 | 2.734375 | 3 | [] | no_license | #ifndef _EM_HPP
#define _EM_HPP
#include <cv.h>
#include <matrix_raii.hpp>
#include <vector>
// performs em algorithm
void em( CvMat * data, int nClusters, int nTries, IplImage * image );
// performs expectation step of the em algorithm
MatrixRAII expectation( CvMat * data, int nClusters, std::vector<CvMat *> &means, std::vector<CvMat *> &variances, std::vector<double> &weights );
// creates a point given the red / green values
MatrixRAII create_point( double red, double green );
// calculates the normal distribution
double normal_distribution( double z, CvMat * x, CvMat * mean, CvMat * variance );
// performs maximization step of the em algorithm
void maximization( CvMat * r, CvMat * data, std::vector<CvMat *> &means, std::vector<CvMat *> &variances, std::vector<double> &weights );
// converts an image to a matrix of size [2 x # of pixels]
MatrixRAII convert_data( IplImage * image );
// generates a random point within the bounds of the image_size
CvPoint random_point( CvSize image_size );
// given the [2 x # of pixels] matrix, generate a graph
void display_data( CvMat * data, std::vector<CvMat *> means, std::vector<CvMat *> variances, std::vector<double> weights, CvSize image_size );
#endif
| true |
654d53fdced5ef1f39b85ebe1b20d45558d243a5 | C++ | PrabhuSammandam/JaSmartObject | /code/stack/common/inc/InteractionStore.h | UTF-8 | 3,556 | 2.609375 | 3 | [] | no_license | #pragma once
#include <common/inc/BaseInteraction.h>
#include <Exchange.h>
#include <vector>
namespace ja_iot {
namespace stack {
class ServerInteraction;
class ClientInteraction;
class MulticastClientInteraction;
typedef std::vector<Exchange *> ExchangeList;
typedef std::vector<BaseInteraction *> InteractionList;
typedef std::vector<MulticastClientInteraction *> MulticastInteractionList;
/**
* Class to store all the interactions and exchanges. This is the singleton class and maintains all the interactions with in the
* system. This class is common for both server and client.
*/
class InteractionStore
{
public:
static InteractionStore& inst();
/*{{{{{{{{{{{{{{{{{{{{ SERVER {{{{{{{{{{{{{{{{*/
bool add_server_exchange( Exchange *server_exchange );
bool delete_server_exchange( Exchange *server_exchange );
Exchange* find_server_exchange( ja_iot::network::CoapMsg &rcz_coap_msg );
void check_remove_expired_server_exchanges();
ExchangeList& get_server_exchange_list() { return ( _server_exchanges ); }
ServerInteraction* create_server_interaction( ja_iot::network::CoapMsg *coap_msg );
ServerInteraction* find_server_interaction( ja_iot::network::CoapMsg *coap_msg, bool create_if_null = false );
bool delete_server_interaction( ServerInteraction *server_interaction );
void remove_expired_server_interaction();
InteractionList& get_server_interaction_list() { return ( _server_interactions ); }
/*}}}}}}}}}}}}}}}}} SERVER }}}}}}}}}}}}}}}}}}}*/
/*{{{{{{{{{{{{{{{{{{{{ CLIENT {{{{{{{{{{{{{{{{*/
bool add_client_exchange( Exchange *client_exchange );
bool delete_client_exchange( Exchange *client_exchange );
Exchange* find_client_exchange( ja_iot::network::CoapMsg &rcz_coap_msg );
ExchangeList& get_client_exchange_list() { return ( _client_exchanges ); }
ClientInteraction* create_client_interaction( ja_iot::network::CoapMsg *coap_msg );
ClientInteraction* find_client_interaction( ja_iot::network::CoapMsg *coap_msg );
InteractionList& get_client_interaction_list() { return ( _client_interactions ); }
MulticastClientInteraction* create_multicast_client_interaction(ja_iot::network::CoapMsg *coap_msg);
MulticastClientInteraction* find_multicast_client_interaction( ja_iot::network::CoapMsg *coap_msg );
MulticastInteractionList& get_mcast_interaction_list() { return ( _mcast_client_interactions ); }
/*}}}}}}}}}}}}}}}}} CLIENT }}}}}}}}}}}}}}}}}}}*/
void print_server_exchanges();
void print_server_interactions();
void print_client_exchanges();
void print_client_interactions();
private:
InteractionStore ();
~InteractionStore ();
static InteractionStore * _pcz_instance;
InteractionStore( const InteractionStore &other ) = delete;
InteractionStore( InteractionStore &&other ) noexcept = delete;
InteractionStore & operator = ( const InteractionStore &other ) = delete;
InteractionStore & operator = ( InteractionStore &&other ) noexcept = delete;
ExchangeList _server_exchanges;
InteractionList _server_interactions;
ExchangeList _client_exchanges;
InteractionList _client_interactions;
std::vector<MulticastClientInteraction *> _mcast_client_interactions;
};
}
}
| true |
1e7613b563f42862f8f886ec4c07e712677fba8b | C++ | LGHigh/Algorithm | /UVa437(The Tower of Babylon).cpp | UTF-8 | 1,169 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int tr[40][3];
int dp[40][3];
int G[100][100];
int n;
bool Less(int i, int j, int m, int n) {
int a = (j + 1) % 3, b = (j + 2) % 3;
int x = (n + 1) % 3, y = (n + 2) % 3;
if (tr[i][a] < tr[m][x] && tr[i][b] < tr[m][y])return true;
if (tr[i][a] < tr[m][y] && tr[i][b] < tr[m][x])return true;
return false;
}
int d(int i) {
int& ans = dp[i/3][i%3];
if (ans > 0)return ans;
ans = tr[i / 3][i % 3];
for (int k = 0; k < 3 * n; k++) {
if (G[i][k])ans = max(ans, d(k) + tr[i / 3][i % 3]);
}
return ans;
}
int main() {
int kase = 0;
while (cin >> n && n) {
int res = 0;
memset(dp, 0, sizeof(dp));
memset(tr, 0, sizeof(tr));
memset(G, 0, sizeof(G));
for (int i = 0; i < n; i++) {
cin >> tr[i][0] >> tr[i][1] >> tr[i][2];
}
for (int i = 0; i < 3 * n; i++) {
int x = i / 3, y = i % 3;
for (int j = 0; j < 3 * n; j++) {
if (Less(x, y, j / 3, j % 3))G[i][j] = 1;
}
}
for (int i = 0; i < 3 * n; i++)
d(i);
for (int i = 0; i < 3 * n; i++)res = max(res,dp[i / 3][i % 3]);
cout << "Case " << ++kase << ": maximum height = " << res << endl;
}
} | true |
e4c534beebc72e1c5f52bbe80d2bba22026b5aaa | C++ | edadasko/aisd_bsuir_2019 | /avl_tree/avl_tree.hpp | UTF-8 | 1,934 | 3.25 | 3 | [] | no_license | //
// avl_tree.hpp
// avl_tree
//
// Created by Eduard Adasko on 5/6/19.
// Copyright © 2019 Eduard Adasko. All rights reserved.
//
#ifndef avl_tree_hpp
#define avl_tree_hpp
#include <stdio.h>
#include <vector>
template <typename T>
struct avl_node {
T key;
unsigned char height;
avl_node<T>* parent;
avl_node<T>* left;
avl_node<T>* right;
avl_node<T>(T k) {
key = k;
parent = left = right = nullptr;
height = 1;
}
};
template <typename T>
class AVL_tree{
private:
void insertRec(avl_node<T>* node, T key);
void removeRec(avl_node<T>* node, T key);
void removeLeaf(avl_node<T>*& node);
void removeNodeWithOneLeaf(avl_node<T>*& node);
bool findRec(avl_node<T>* node, T key);
long long sizeRec(avl_node<T>* node);
T minRec(avl_node<T>* node);
T maxRec(avl_node<T>* node);
void inOrderRec(avl_node<T>* node);
void printRec(avl_node<T>* node, int level);
avl_node<T>* minNodeRec(avl_node<T>* node);
avl_node<T>* maxNodeRec(avl_node<T>* node);
avl_node<T>* makeBalanced(avl_node<T>* node);
avl_node<T>* rotateL(avl_node<T>* node);
avl_node<T>* rotateR(avl_node<T>* node);
unsigned char height (avl_node<T>* node);
int balanceFactor (avl_node<T>* node);
void setHeight (avl_node<T>* node);
bool isBalanced (avl_node<T>* node);
void changeNodeToBalanced(avl_node<T>* node);
public:
avl_node<T>* root;
AVL_tree<T>();
AVL_tree<T>(std::vector<T> keys);
void insert(T key);
void insert(std::vector<T> keys);
void remove(T key);
bool find(T key);
T min();
T max();
T rootElement();
void inOrder();
long long size();
void Print();
avl_node<T>* minNode();
avl_node<T>* maxNode();
avl_node<T>* successor(avl_node<T>* node);
avl_node<T>* predecessor(avl_node<T>* node);
int getHeight();
};
#endif /* avl_tree_hpp */
| true |
0bdb555872b7e49bf7ebcdd8339bbecc1df7b826 | C++ | PaulPio/urbeproyectos | /programacion1/corte 2/Burbuja.cpp | UTF-8 | 1,137 | 3.5 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int num, aux;
int comparaciones = 0;
int intercambios = 0;
cout << "Cuantos numeros seran: ";
cin >> num;
int arreglo[num];
cout << endl << "***CAPTURA DE NUMEROS***" << endl;
for(int x = 0; x < num; x++) {
cout << "Ingresa el numero " << x << " de la serie: ";
cin >> arreglo[x];
cout << endl;
}
cout << "***MUESTRA DE NUMEROS***" << endl;
for(int y = 0; y < num; y++) {
cout << "Numero " << y << ".- " << arreglo[y] << endl;
}
for(int z = 1; z < num; ++z) {
for(int v = 0; v < (num - z); v++) {
comparaciones++;
if(arreglo[v] > arreglo[v+1]){
aux = arreglo[v];
arreglo[v] = arreglo[v + 1];
arreglo[v + 1] = aux;
intercambios++;
}
}
}
cout << "***NUMEROS ARREGLADOS***" << endl;
for(int w = 0; w < num; w++) {
cout << "Numero " << w << ".- " << arreglo[w] << endl;
}
cout << "Numero de comparaciones: " << comparaciones << endl;
cout << "Numero de intercambios: " << intercambios << endl;
}
| true |
1dfe6eed54470e4edd57eee4d4fb3b470d8374fc | C++ | bksaiki/MathSolver | /lib/expr/expr.h | UTF-8 | 2,188 | 3.25 | 3 | [] | no_license | #ifndef _MATHSOLVER_EXPRESSION_H_
#define _MATHSOLVER_EXPRESSION_H_
#include "../common/base.h"
#include "../expr/node.h"
namespace MathSolver
{
//
// Expression operations
//
// Returns true if every node in the expression satisfies the given predicate.
template <typename Pred>
bool containsAll(ExprNode* expr, Pred pred)
{
for (auto e : expr->children())
if (!containsAll(e, pred)) return false;
return pred(expr);
}
// Returns true if the expression contains at least one node satisfying the given predicate.
template <typename Pred>
bool containsOnce(ExprNode* expr, Pred pred)
{
for (auto e : expr->children())
if (containsOnce(e, pred)) return true;
return pred(expr);
}
// Returns true if the expression contains at least one instance of a certain type
inline bool containsType(ExprNode* expr, ExprNode::Type type) { return containsOnce(expr, [&](ExprNode* node) { return node->type() == type; }); }
// Returns a copy of the given expression tree.
ExprNode* copyOf(ExprNode* expr);
// Returns true if the value of two nodes is the same.
bool eqvExpr(ExprNode* a, ExprNode* b);
// Returns a list of variable names in an expression
std::list<std::string> extractVariables(ExprNode* expr);
// Takes an expression node and recursively simplifes certain operators with interior nodes of the
// same operator into a single operator with many operands. e.g. (+ (+ a (+ b c)) d) ==> (+ a b c d)
void flattenExpr(ExprNode* expr);
// Deletes an expression tree.
void freeExpression(ExprNode* expr);
// Returns true if the expression only contains numerical operands (Non-symbolic expression).
inline bool isNumerical(ExprNode* expr)
{
return containsAll(expr, [](ExprNode* node) { return node->isNumber() || node->isOperator() || node->type() == ExprNode::FUNCTION; });
}
// Returns the number of nodes in the expression tree.
size_t nodeCount(ExprNode* expr);
// Returns an expression tree as a string in infix notation. Assumes the tree is valid.
std::string toInfixString(ExprNode* expr);
// Returns an expression tree as a string in prefix notation. Assumes the tree is valid.
std::string toPrefixString(ExprNode* expr);
}
#endif
| true |
e3a850c969eb2939d363c1d5733b8fadaa6f220f | C++ | Chandanjk/Pick_Place_Arm | /main_structure/main_structure.ino | UTF-8 | 329 | 2.578125 | 3 | [] | no_license | #include<Servo.h>
Servo s;
void setup()
{
s.attach(6);
Serial.begin(57600);
for(int i=90;i<=180;i+=1)
{
s.write(i);
delay(20);
}
}
void loop()
{
for(int i=180;i>=0;i-=1)
{
s.write(i);
delay(20);
}
for(int i=0;i<=180;i+=1)
{
s.write(i);
delay(20);
}
}
| true |
7befd3a48d5def1dfe1aad45e37819f993636a23 | C++ | SergueiFedorov/SF_Sqlite | /SF_Sqlite_Helper.cpp | UTF-8 | 6,096 | 3.078125 | 3 | [] | no_license | #include "SF_Sqlite_Helper.h"
void sf_sqlite_buildColumnType(std::string& output, const std::string& column, const std::string& type)
{
output += column + " " + type;
}
void sf_sqlite_buildColumnDataPairStrings(std::string& nameOutput, std::string& columnOutput, const std::vector<SF_Sqlite_Column_Data_Pair>& values)
{
std::vector<SF_Sqlite_Column_Data_Pair>::const_iterator iterator;
for (iterator = values.begin(); iterator != values.end(); ++iterator)
{
nameOutput += (*iterator).columnName;
nameOutput += ",";
columnOutput += (*iterator).columnData;
columnOutput += ",";
}
nameOutput.resize(nameOutput.size() - 1);
columnOutput.resize(columnOutput.size() - 1);
}
void sf_sqlite_buildCommaList(std::string& output, const std::vector<std::string> values)
{
std::vector<std::string>::const_iterator iterator;
for (iterator = values.begin(); iterator != values.end(); ++iterator)
{
output += (*iterator);
output += ",";
}
output.resize(output.size() - 1);
}
void sf_sqlite_buildEqualsCommaList (std::string& output, const std::vector<SF_Sqlite_Column_Data_Pair>& pairs)
{
std::vector<SF_Sqlite_Column_Data_Pair>::const_iterator iterator;
for (iterator = pairs.begin(); iterator != pairs.end(); ++iterator)
{
sf_sqlite_buildEquals(output, (*iterator).columnName, (*iterator).columnData);
output += ",";
}
output.resize(output.size() - 1);
}
void sf_sqlite_buildEquals(std::string& output, const std::string& left, const std::string& right)
{
output += left + " = " + right;
}
void sf_sqlite_buildFinalSelectNoWhereQuery(std::string& output, const std::string& table, const std::string& selectColumns)
{
output += SF_SQLITE_QUERY_STRINGS::SELECT + selectColumns + SF_SQLITE_QUERY_STRINGS::FROM + table;
}
void sf_sqlite_buildFinalSelectNoWhereNoColumnsQuery(std::string& output,
const std::string& table)
{
output += SF_SQLITE_QUERY_STRINGS::SELECT + " * " + SF_SQLITE_QUERY_STRINGS::FROM + table;
}
void sf_sqlite_buildFinalSelectAllQuery(std::string& output,
const std::string& table,
const std::string& selectColumns,
const std::string& whereValues)
{
output += SF_SQLITE_QUERY_STRINGS::SELECT + selectColumns + " FROM " + table + whereValues;
}
void sf_sqlite_buildFinalUpdateQuery(std::string& output,
const std::string& table,
const std::string& where,
const std::string& set)
{
output += SF_SQLITE_QUERY_STRINGS::UPDATE + table + set + where;
}
void sf_sqlite_buildWhereColumnList(std::string& output, const std::vector<SF_Sqlite_Column_Data_Pair>& whereValues)
{
if (whereValues.size() > 0)
{
output += SF_SQLITE_QUERY_STRINGS::WHERE;
sf_sqlite_buildEqualsCommaList(output, whereValues);
}
}
void sf_sqlite_buildSelectColumnList(std::string& output)
{
output += " * ";
}
void sf_sqlite_buildSelectColumnList(std::string& output, const std::vector<std::string>& columns)
{
if (columns.size() > 0)
{
sf_sqlite_buildCommaList(output, columns);
}
else
{
output = " * ";
}
}
void sf_sqlite_buildFinalDropTable(std::string& output, const std::string& table)
{
output += SF_SQLITE_QUERY_STRINGS::DROP_TABLE;
output += table;
}
void sf_sqlite_buildCreateTableColumns(std::string& output, std::vector<SF_Sqlite_Column_Type_Pair> pairs)
{
output += "(";
std::vector<SF_Sqlite_Column_Type_Pair>::const_iterator iterator;
for (iterator = pairs.begin(); iterator != pairs.end(); ++iterator)
{
sf_sqlite_buildColumnType(output, (*iterator).columnName, (*iterator).columnType);
if (((*iterator).columnFlags & SF_COLUMN_FLAGS::PRIMARY_KEY) > 0)
{
output += SF_SQLITE_QUERY_STRINGS::PRIMARY_KEY;
}
if (((*iterator).columnFlags & SF_COLUMN_FLAGS::AUTOINCREMENT) > 0)
{
output += SF_SQLITE_QUERY_STRINGS::AUTOINCREMENT;
}
if (((*iterator).columnFlags & SF_COLUMN_FLAGS::UNIQUE) > 0)
{
output += SF_SQLITE_QUERY_STRINGS::UNIQUE;
}
output += std::string(",");
}
output.resize(output.size() - 1);
output += ")";
}
void sf_sqlite_buildCreateTable(std::string& output, const std::string& table)
{
output += SF_SQLITE_QUERY_STRINGS::CREATE_TABLE + " IF NOT EXISTS ";
output += table;
}
void sf_sqlite_buildInsertIntoTableHeader(std::string& output, const std::string& table)
{
output += SF_SQLITE_QUERY_STRINGS::INSERT_INTO;
output += table;
}
void sf_sqlite_buildInsertValues(std::string& output, const std::vector<std::string>& values)
{
output += SF_SQLITE_QUERY_STRINGS::VALUES + "(";
sf_sqlite_buildCommaList(output, values);
output += ")";
}
void sf_sqlite_buildInsertValues(std::string& ouput, const std::vector<SF_Sqlite_Column_Data_Pair>& values)
{
std::string nameString = "(";
std::string columnString = SF_SQLITE_QUERY_STRINGS::VALUES + "(";
sf_sqlite_buildColumnDataPairStrings(nameString, columnString, values);
nameString += ")";
columnString += ")";
ouput += nameString;
ouput += columnString;
}
void sf_sqlite_buildSetValues(std::string& output, const std::vector<SF_Sqlite_Column_Data_Pair>& values)
{
output += " SET ";
sf_sqlite_buildEqualsCommaList(output, values);
}
void sf_sqlite_buildParamedQuery(std::string& output, const std::string& paramedString, const std::vector<SF_Sqlite_Parameter>& params)
{
output = paramedString;
std::vector<SF_Sqlite_Parameter>::const_iterator iterator;
for (iterator = params.begin(); iterator != params.end(); ++iterator)
{
int paramterID = (*iterator).paramNum;
std::string parameterIDStringed;
parameterIDStringed += "{";
parameterIDStringed += std::to_string(paramterID);
parameterIDStringed += "}";
size_t paramPosition = output.find(parameterIDStringed);
if (paramPosition != -1)
{
output.replace(paramPosition, parameterIDStringed.size(), (*iterator).data);
}
}
}
| true |
897c06d6a46a4bbf0fc3114a10423a9725ffc132 | C++ | a-ignatieva/sars-cov-2-recombination | /Code/Rcpp_funs.cpp | UTF-8 | 1,051 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
int sim_null_realisation(int m, vec P) {
int M = P.size();
int ind = m;
vec S = regspace(1, M);
vec R(M, fill::zeros);
R.subvec(0, m-1) = Rcpp::RcppArmadillo::sample(S, m, true, P);
vec Q = unique(R); // unique elements drawn (plus 0)
int qsize = Q.size() - 1; // number of unique elements drawn
while(qsize < m) {
R.subvec(ind, ind + m - qsize - 1) = Rcpp::RcppArmadillo::sample(S, m - qsize, true, P);
Q = unique(R);
ind = ind + m - qsize;
qsize = Q.size() - 1;
}
return ind - m;
}
int mod(int a, int n)
{
return a - floor(a/n)*n;
}
// [[Rcpp::export]]
vec sim_null_dist(int m, int n, vec P) {
vec S(n);
for(int i = 0; i<n; i++) {
S[i] = sim_null_realisation(m, P);
if(mod(i, 1000) == 0) {
if(mod(i,100000)==0) {
Rcout << "#\n";
}
else{
Rcout << "#";
}
}
}
return S;
}
| true |
221d266d5b63c2720f251da631babcd4f8994671 | C++ | plaguera/Modbus | /ModbusTCP.cpp | UTF-8 | 11,745 | 2.84375 | 3 | [] | no_license | /*
* ModbusTCP.cpp
*
* Created on: Apr 12, 2019
* Author: Pedro Lagüera Cabrera | alu0100891485
*/
#include "ModbusTCP.hpp"
namespace modbus {
// Inicializar el servidor
ModbusTCP::ModbusTCP(std::vector<int> ids) : devices(std::vector<ModbusServer*>()), sockfd(-1) {
for (int i = 0; i < ids.size(); i++)
AddDevice(ids[i]);
}
// Destruir todos los dispositivos existentes
ModbusTCP::~ModbusTCP() {
for (int i = 0; i < devices.size(); i++)
delete devices[i];
}
// Inicializa y arranca los hilos de ejecución y los sockets
void ModbusTCP::Start() {
sockfd = socket(AF_INET, SOCK_STREAM, 0); // Crear un nuevo socket, guardar el file descriptor
if (sockfd < 0) {
Util::Exception(UNABLE_TO_OPEN_SOCKET);
return;
}
int reusePort = 1; // Disables default "wait time" after port is no longer in use before it is unbound
setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &reusePort, sizeof(reusePort));
bzero((char *) &serv_addr, sizeof(serv_addr)); // Inicializar serv_addr con ceros
serv_addr.sin_family = AF_INET; // Address family
serv_addr.sin_port = htons(portno); // Convierte el número de puerto de host byte order a network byte order
serv_addr.sin_addr.s_addr = INADDR_ANY; // Guarda la IP de la máquina donde se ejecute el servidor
// Asignar los parámetros de dirección al socket abierto
if (bind(sockfd, (sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
Util::Error(UNABLE_TO_BIND);
return;
}
unsigned int backlogSize = 5; // Número de conexiones que pueden estar en espera a que finalice otra
listen(sockfd, backlogSize);
std::cout << Util::Color(MAGENTA, "C++ Server Opened on Port " + std::to_string(portno)) << std::endl;
threads_stop = false;
t_server = std::thread(&ModbusTCP::Listen, this); // Lanzar la escucha de nuevos clientes en un hilo independiente
t_server.detach();
CommandPrompt(); // Ejecutar línea de comandos en el hilo principal de ejecución
}
// Permite input de comandos y los procesa
void ModbusTCP::CommandPrompt() {
std::string input;
while (!threads_stop) {
//std::cout << "> $ ";
std::getline(std::cin, input);
ProcessCommand(input);
}
}
// Parsea el texto introducido por línea de comandos y ejecuta las acciones correspondientes
void ModbusTCP::ProcessCommand(std::string input) {
if (input.length() == 0 || std::all_of(input.begin(),input.end(),isspace)) return; // Texto vacío o espacios se descarta
selected_device->Update(); // Actualizar el dispositivo seleccionado
std::transform(input.begin(), input.end(), input.begin(), ::tolower); // Transformar texto a minúsculas
Command cmd = Util::TokenizeCommand(input); // Parsear texto y obtener un comando
switch (cmd.command)
{
case DEVICES:
if(!regex_match(input, std::regex("(devices)"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
for (int i = 0; i < devices.size(); i++) {
if (devices[i] == selected_device)
std::cout << i+1 << ".- " << BOLD << *devices[i] << "*" << RESET << std::endl;
else
std::cout << i+1 << ".- " << *devices[i] << std::endl;
}
break;
case CONNECTIONS:
if(!regex_match(input, std::regex("(connections)"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
for (int i = 0; i < clients.size(); i++)
std::cout << Util::FormatSockAddr(clients[i].address) << std::endl;
break;
case STOP:
if(!regex_match(input, std::regex("(stop)"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
Stop();
break;
case GET:
{
if(!regex_match(input, std::regex("(get)\\s*(((analog)|(digital)|(input)|(output))\\s*)*"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
bool analog = std::find(cmd.args.begin(), cmd.args.end(), "analog") != cmd.args.end();
bool digital = std::find(cmd.args.begin(), cmd.args.end(), "digital") != cmd.args.end();
bool input = std::find(cmd.args.begin(), cmd.args.end(), "input") != cmd.args.end();
bool output = std::find(cmd.args.begin(), cmd.args.end(), "output") != cmd.args.end();
int mode = analog * 8 + digital * 4 + input * 2 + output * 1;
selected_device->Print(mode);
}
break;
case SET:
{
if(!regex_match(input, std::regex("(set)\\s+((analog)|(digital))\\s+[0-9]{1,2})"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
bool analog = cmd.args[0] == "analog";
int position = stoi(cmd.args[1]), value;
if (position < 15 || position > 19) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
std::cout << "Device " << *selected_device << " << " << (analog ? "Analog" : "Digital") << "[" << position << "] >> = ";
std::cin >> value;
if (!analog && value != 0 && value != 1) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
if (analog) selected_device->SetAnalogInput(position, value);
else selected_device->SetDigitalInput(position, value);
}
break;
case SELECT:
{
if(!regex_match(input, std::regex("(select)\\s*((?:0[xX])?[0-9a-fA-F]+)?"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
if (cmd.args.empty()) {
std::cout << *selected_device << std::endl;
break;
}
ModbusServer* device = Device(std::stoi(cmd.args[0]));
if (device != NULL) selected_device = device;
}
break;
case HELP:
if(!regex_match(input, std::regex("(help)"))) {
Util::Error(BAD_COMMAND_SYNTAX);
break;
}
std::cout << "Commands:" << std::endl;
std::cout << "\tCONNECTIONS" << std::endl;
std::cout << "\tDEVICES" << std::endl;
std::cout << "\tGET [Analog | Digital | Input | Output]*" << std::endl;
std::cout << "\tHELP" << std::endl;
std::cout << "\tSELECT [Device ID]?" << std::endl;
std::cout << "\tSET [Analog | Digital] [position]" << std::endl;
std::cout << "\tSTOP" << std::endl;
break;
case UNKNOWN:
default: Util::Error(COMMAND_NOT_FOUND); break;
}
}
// Escuchar por nuevos clientes y crear hilos nuevos para manejarlos en el caso de que se conecten
void ModbusTCP::Listen() {
while (!threads_stop) {
int newsockfd; // Nuevo socket file descriptor
sockaddr_in cli_addr; // Dirección cliente
unsigned int cli_len = sizeof(sockaddr_in); // Tamaño dirección cliente
newsockfd = accept(sockfd, (sockaddr *) &cli_addr, &cli_len); // Bloquear hasta que se conecte un cliente
if (newsockfd < 0) {
Util::Error(UNABLE_TO_ACCEPT);
Stop();
}
std::string aux(inet_ntoa(cli_addr.sin_addr) + std::string(" : ") + std::to_string(ntohs(cli_addr.sin_port)));
std::cout << Util::FormatSockAddr(&cli_addr) << " - " << Util::Color(BOLD, Util::Color(GREEN, "Connected")) << std::endl;
// Crear hilo que ejecute 'HandleRequest' para el nuevo cliente y almacenarlo en la lista
clients.push_back(Client(newsockfd, &cli_addr));
clients.back().thread = std::thread(&ModbusTCP::HandleRequest, this, newsockfd, &cli_addr);
clients.back().thread.detach();
}
}
// Escucha por mensajes del cliente correspondiente y cuando los recibe, se procesan y devuelve una respuesta
void ModbusTCP::HandleRequest(int sockfd, sockaddr_in* cli_addr) {
char buffer[1024];
ssize_t bytes_received = 0, bytes_sent;
do {
bytes_received = recv(sockfd, buffer, 1024, 0); // Bloquear hasta que se recibe un mensaje
if (bytes_received <= 0) break; // El cliente se ha desconectado
byte* array = (byte*) buffer; // Convertir el mensaje de char* a byte*
std::vector<byte> input(array, array + sizeof(array)/sizeof(byte)); // Convertir el byte* a vector<byte>
std::cout << Util::FormatSockAddr(cli_addr) + " - {Input}" << Util::ToString(input) << std::endl;
std::vector<byte> output = ProcessPetition(input); // Procesar petición y guardar respuesta
if (!output.empty())
std::cout << " --> {Response}: " + Util::ToString(output) << std::endl;
else
std::cout << " --> {Response}: [(0) ]" << std::endl;
const char* foo = reinterpret_cast<const char*>(output.data()); // Convertir respuesta de vector<byte> a char*
bytes_sent = send(sockfd, foo, output.size(), 0); // Enviar respuesta
if (bytes_sent < 0) break;
} while (bytes_received > 0);
if (bytes_received == 0) std::cout << Util::FormatSockAddr(cli_addr) << " - " << Util::Color(BOLD, Util::Color(RED, "Disconnected")) << std::endl;
if (bytes_received == -1) Util::Error(RECEIVE_ERROR);
for (int i = 0; i < clients.size(); i++)
if (clients[i].sockfd == sockfd)
clients.erase(clients.begin() + i); // Eliminar cliente de la lista
close(sockfd); // Cerrar socket
}
// Buscar dispositivo correspondiente a la petición y que la procese
std::vector<byte> ModbusTCP::ProcessPetition(std::vector<byte> input) {
ModbusServer* device = Device(input[0]);
if (device != NULL)
return device->Petition(input);
return std::vector<byte>();
}
// Para todos los hilos de ejecución y cierre el socket principal
void ModbusTCP::Stop() {
threads_stop = true;
sockfd = -1;
std::cout << Util::Color(RED, "Stopping server...") << std::endl;
close(sockfd);
}
// Añadir un nuevo dispositivo con el identificador especificado
void ModbusTCP::AddDevice(byte id) {
devices.push_back(new ModbusServer(id));
if (devices.size() == 1) selected_device = devices.back();
}
// Devuelve el dispositivo con el identificador especificado
ModbusServer* ModbusTCP::Device(byte id) {
for (int i = 0; i < devices.size(); i++)
if (devices[i]->GetID() == id)
return devices[i];
Util::Error(INVALID_DEVICE_ID);
return NULL;
}
} | true |
ed2670eb1984ae9456298125d52d35303deee043 | C++ | ArpitSingla/LeetCode | /30 Day Leet Code Challenge/First Bad Version.cpp | UTF-8 | 533 | 3.21875 | 3 | [] | no_license | // The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int low=1;
int high=n;
while(low<=high){
int mid=low+(high-low)/2;
if(!(isBadVersion(mid))){
low=mid+1;
}
else if(isBadVersion(mid)){
if(!(isBadVersion(mid-1))){
return mid;
}
high=mid-1;
}
}
return -1;
}
}; | true |
3370447d083b287019334a243c7ab4f82cafb307 | C++ | theboi/competitive-programming | /solutions/HackerRank/C++/1-Introduction/5-forLoop.cpp | UTF-8 | 382 | 3.1875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int main() {
int low, high;
cin >> low >> high;
string nums[] = {"", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
for (int i = low; i <= high; i++) {
cout << (i >= 1 && i <= 9 ? nums[i] : (i % 2 == 0 ? "even" : "odd"))
<< endl;
}
return 0;
}
| true |
326c0f6a5d1449a0759f5965e5a09e55330ca0d3 | C++ | tonyellis69/3DTest2 | /src/windows/nearWin.cpp | UTF-8 | 1,533 | 2.515625 | 3 | [] | no_license | #include "nearWin.h"
#include <glm/glm.hpp>
#include "../gameState.h"
#include "../gameGui.h"
void CNearWin::update(float dT)
{
return;
//scraping so scrap
if (gameWorld.player == nullptr)
return;
float nearDist = 1.0f;
bool nearItemsChanged = false;
glm::vec3 playerPos = gameWorld.player->getPos();
//check if any items are no longer near
for (auto& item = nearItems.begin(); item != nearItems.end();) {
if (glm::distance(playerPos, (*item)->getPos()) > nearDist ) {
item = nearItems.erase(item);
nearItemsChanged = true;
}
else
item++;
}
//add any newly near items
//TO DO: if we're looping through all entities/items every tick, may as well
//clear and rebuild list every time.
for (auto& entity : gameWorld.entities) {
if (entity->isItem && ((CItem*)entity.get())->parent == nullptr
&& glm::distance(playerPos, entity->getPos()) < nearDist) {
if (std::find(nearItems.begin(), nearItems.end(), (CItem*)entity.get()) == nearItems.end()) {
nearItems.push_back((CItem*)entity.get());
nearItemsChanged = true;
}
}
}
if (nearItemsChanged)
refresh();
}
void CNearWin::removeItem(int itemNo) {
for (auto& item = nearItems.begin(); item != nearItems.end(); item++) {
if ((*item)->id == itemNo) {
nearItems.erase(item);
refresh();
return;
}
}
}
void CNearWin::refresh() {
gWin::pNear->clearText();
for (auto& item : nearItems) {
gWin::pNear->addText(item->getShortDesc() + "\n");
}
}
| true |
926774d0a18b587bd75ee3546e5224a9795899a6 | C++ | aajjbb/contest-files | /Codeforces/Combination.cpp | UTF-8 | 991 | 3.359375 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct Card {
int a, b;
Card() {}
Card(int _a, int _b) {
a = _a;
b = _b;
}
bool operator<(const Card& c) const {
if(a > c.a && b > c.b) {
return true;
} else {
if(b == c.b) {
if(a > c.a) {
return true;
}
}
if(b > c.b) return true;
}
return false;
}
};
vector<Card> v;
int main(void) {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int ta, tb;
cin >> ta >> tb;
v.push_back(Card(ta, tb));
}
sort(v.begin(), v.end());
int c = 1, pivot = 0, points = 0;
while(c > 0 && pivot < n) {
c -= 1;
points += v[pivot].a;
c += v[pivot].b;
pivot++;
}
cout << points << endl;
return 0;
}
| true |
9bec97c96d4faa7368f54e9f816f03f282c0fc2b | C++ | Stupeflix/freetype-gl | /src/ft/Glyph.cpp | UTF-8 | 1,169 | 2.84375 | 3 | [] | no_license |
#include <iostream>
#include "utils/convert.hpp"
#include "ft/Glyph.hpp"
namespace ft {
Glyph::Glyph() :
width(0), height(0),
offset_x(0), offset_y(0),
advance_x(0), advance_y(0),
s0(0), t0(0), s1(0), t1(0) {
}
Glyph::~Glyph() {}
float Glyph::getKerning(const wchar_t charcode) const {
for (auto &k : kerning) {
if (k.charcode == charcode)
return k.kerning;
}
return 0;
}
std::string Glyph::toJson() const {
std::string json;
json += "\"" + convert<std::string>(charcode) + "\":{";
json += "\"offset_x\": " + convert<std::string>(offset_x) + ",";
json += "\"offset_y\": " + convert<std::string>(offset_y) + ",";
json += "\"advance_x\": " + convert<std::string>(advance_x) + ",";
json += "\"advance_y\": " + convert<std::string>(advance_y) + ",";
json += "\"width\": " + convert<std::string>(width) + ",";
json += "\"height\": " + convert<std::string>(height) + ",";
json += "\"s0\": " + convert<std::string>(s0) + ",";
json += "\"t0\": " + convert<std::string>(t0) + ",";
json += "\"s1\": " + convert<std::string>(s1) + ",";
json += "\"t1\": " + convert<std::string>(t1) + "}";
return json;
}
} // namespace ft
| true |
99ec3f6cc3de0c7ecb31e6e9fa7b7afeacc498d6 | C++ | Bit-W/Search_Engines | /sercher/searcher.cc | UTF-8 | 3,556 | 3.09375 | 3 | [] | no_license | #include"searcher.h"
#include<iostream>
#include"../common/util.hpp"
namespace sercher{
//查正排
DocInfo* Index::GetDocInfo(uint64_t doc_id){
if(doc_id >= forward_index.size()) //找到返回,没找到返回空
return NULL;
return &forward_index[doc_id];
}
//查倒排
std::vector<Weight>* Index:: GetInvertedList(std::string key){
//直接在underod_map中查找
auto pos = inverted_index.find(key);
if(pos == inverted_index.end())
{
std::cout<<"not found key"<<std::endl;
return NULL;
}
return &pos->second;
}
//构建索引
bool Index::Build(std::string input_path){
std::cout<<"build index is start"<<std::endl;
//1.按行读取文件内容,每一行就是一个html
//打开一个文件,并且按行读取,但是并不包括结尾的\n
std::ifstream file(input_path.c_str());
if(!file.is_open())
{
std::cout<<"open the input_path false input_path = "<<input_path<<std::endl;
return false;
}
std::string line;
while(std::getline(file,line)){
//2.构造DocInfo对象,更新正排索引
DocInfo* info = BuildForward(line);
//3.更新倒排索引数据
BuildInverted(*info);
if(info->doc_id % 500 == 0){
std::cout<<"already build: "<<(info->doc_id)<<std::endl;
}
}
file.close();
std::cout<<"index build finish!"<<std::endl;
return true;
}
//更新正排索引
DocInfo* Index::BuildForward(std::string& line){
//对读取的一行进行切分,区分出url.正文,标题
std::vector<std::string> tokens; //存放切分结果
StringUtil::Split(line,&tokens,"\3");
if(tokens.size() != 3)
{
std::cout<<"tokens is false"<<std::endl;
return NULL;
}
//构造为一个DocInfo对象
DocInfo info;
info.doc_id = forward_index.size();
info.title = tokens[0];
info.url = tokens[1];
info.content = tokens[2];
//把这个对象插入正排索引中
forward_index.push_back(info);
return &forward_index.back();
}
//更新倒排索引
void Index::BuildInverted(DocInfo& info){
//1.先进行分词,标题正文都要分
std::vector<std::string> title_tokens;//存放标题的分词结果
CutWord(info.title,&title_tokens);
std::vector<std::string> content_tokens;//存放正文的分词结果
CutWord(info.content,&content_tokens);
struct WordCut{ //定义一个结构体来统计正文和标题的词频
int title_cnt;
int content_cnt;
};
//2.在进行词频统计(用一个哈希表去统计)
std::unordered_map<std::string,WordCut> word_cnt;
for(auto& word : title_tokens){
boost::to_lower(word); //全部变换为小写
++(word_cnt[word].title_cnt);
}
for(auto& word : content_tokens){
boost::to_lower(word); //忽略大小写
++(word_cnt[word].content_cnt);
}
//3.遍历分词结果,在倒排中查找
for(auto& word_pair : word_cnt){
Weight weight;
weight.doc_id = info.doc_id;
weight.weight = 20 * word_pair.second.title_cnt + word_pair.second.content_cnt;
weight.key = word_pair.first;
//4.不存在就插入
//5.存在的话就进行,找到对应的值,构建weight
std:: vector<Weight>& inverted_list = inverted_index[word_pair.first];
inverted_list.push_back(weight);
}
}
}//end of namespace
| true |
808bb898538f29bbdee690ce52473878ff7b6c8e | C++ | Robert-Lu/QtGLDemo | /QtGLDemo/OpenGLCamera.cpp | UTF-8 | 4,006 | 3.015625 | 3 | [] | no_license | #include "stdafx.h"
#include "OpenGLCamera.h"
#define PI 3.14159f
OpenGLCamera::~OpenGLCamera()
{
}
OpenGLCamera::OpenGLCamera(const OpenGLCamera& rhs)
{
position_ = rhs.position_;
target_ = rhs.target_;
direction_ = rhs.direction_;
right_ = rhs.right_;
up_ = rhs.up_;
}
void OpenGLCamera::update()
{
direction_ = (position_ - target_).normalized();
QVector3D up{ 0.0f, 0.0f, 1.0f };
right_ = QVector3D::crossProduct(up, direction_);
right_.normalize();
up_ = QVector3D::crossProduct(direction_, right_);
up_.normalize();
}
void OpenGLCamera::move_right(float dis)
{
position_ += dis * right_;
update();
}
void OpenGLCamera::move_up(float dis)
{
position_ += dis * up_;
update();
}
void OpenGLCamera::move_back(float dis)
{
float radius = (position_ - target_).length();
if (radius < -dis)
return;
position_ += dis * direction_;
update();
}
void OpenGLCamera::move_right_target(float dis)
{
target_ += dis * right_;
update();
}
void OpenGLCamera::move_up_target(float dis)
{
target_ += dis * up_;
update();
}
void OpenGLCamera::move_back_target(float dis)
{
target_ += dis * direction_;
update();
}
void OpenGLCamera::move_around_right(float angle)
{
float radius = (position_ - target_).length();
float cos_theta = abs(QVector3D::dotProduct(direction_, { 0.0f, 0.0f, 1.0f })); // theta: up(absolute) and direction
float sin_theta = sqrtf(1 - cos_theta * cos_theta);
float dis = 2 * sin_theta * radius * sinf(angle * PI / 180.0f / 2.0f); // d = 2 r cos(theta) sin(alpha * PI / 2)
position_ += dis * cosf(angle * PI / 180.0f / 2.0f) * right_; // x += d cos(alpha * PI / 2)
position_ -= dis * sinf(angle * PI / 180.0f / 2.0f) * direction_ * sin_theta; // z -= d sin(alpha * PI / 2) sin(theta)
position_ += dis * sinf(angle * PI / 180.0f / 2.0f) * up_ * cos_theta; // y += d sin(alpha * PI / 2) cos(theta)
update();
}
void OpenGLCamera::move_around_up(float angle)
{
float radius = (position_ - target_).length();
float cos_theta = abs(QVector3D::dotProduct(direction_, { 0.0f, 0.0f, 1.0f }));
float cos_angle = cosf(angle * PI / 180.0f);
if (cos_theta > cos_angle - 0.00001f && direction_.z() * angle > 0)
return;
float dis = 2 * radius * sinf(angle * PI / 180.0f / 2.0f); // d = 2 r sin(alpha * PI / 2)
position_ += dis * cosf(angle * PI / 180.0f / 2.0f) * up_; // y += d cos(alpha * PI / 2)
position_ -= dis * sinf(angle * PI / 180.0f / 2.0f) * direction_; // z -= d sin(alpha * PI / 2)
update();
}
void OpenGLCamera::move_around_right_target(float angle)
{
float radius = (position_ - target_).length();
float cos_theta = abs(QVector3D::dotProduct(direction_, { 0.0f, 0.0f, 1.0f })); // theta: up(absolute) and direction
float sin_theta = sqrtf(1 - cos_theta * cos_theta);
float dis = 2 * sin_theta * radius * sinf(angle * PI / 180.0f / 2.0f); // d = 2 r cos(theta) sin(alpha * PI / 2)
target_ += dis * cosf(angle * PI / 180.0f / 2.0f) * right_; // x += d cos(alpha * PI / 2)
target_ -= dis * sinf(angle * PI / 180.0f / 2.0f) * direction_ * sin_theta; // z -= d sin(alpha * PI / 2) sin(theta)
target_ += dis * sinf(angle * PI / 180.0f / 2.0f) * up_ * cos_theta; // y += d sin(alpha * PI / 2) cos(theta)
update();
}
void OpenGLCamera::move_around_up_target(float angle)
{
float radius = (position_ - target_).length();
float dis = 2 * radius * sinf(angle * PI / 180.0f / 2.0f); // d = 2 r sin(alpha * PI / 2)
target_ += dis * cosf(angle * PI / 180.0f / 2.0f) * up_; // y += d cos(alpha * PI / 2)
target_ += dis * sinf(angle * PI / 180.0f / 2.0f) * direction_; // z += d sin(alpha * PI / 2)
update();
}
QMatrix4x4 OpenGLCamera::view_mat() const
{
QMatrix4x4 view;
view.lookAt(position_, target_, up_);
return view;
} | true |
5ee2fc75a3a14538f6f5d0632144fe368985646d | C++ | sn0wyQ/MMMX | /GameObject/RigidBody/intersect_checker.cpp | UTF-8 | 4,403 | 3.078125 | 3 | [] | no_license | #include "intersect_checker.h"
std::vector<QPointF> IntersectChecker::GetIntersectPointsBodies(
const std::shared_ptr<RigidBody>& first,
const std::shared_ptr<RigidBody>& second,
QVector2D offset, float rotation) {
if (second->GetType() == RigidBodyType::kRectangle) {
return GetIntersectPoints(
std::dynamic_pointer_cast<RigidBodyCircle>(first),
std::dynamic_pointer_cast<RigidBodyRectangle>(second),
offset, rotation);
} else {
return GetIntersectPoints(
std::dynamic_pointer_cast<RigidBodyCircle>(first),
std::dynamic_pointer_cast<RigidBodyCircle>(second),
offset, rotation);
}
}
std::vector<QPointF> IntersectChecker::GetIntersectPoints(
const std::shared_ptr<RigidBodyCircle>& circle1,
const std::shared_ptr<RigidBodyCircle>& circle2,
QVector2D offset, float) {
// Формула нахождения точек пересечения двух кругов:
// http://e-maxx.ru/algo/circles_intersection
float r1 = circle1->GetRadius();
float r2 = circle2->GetRadius();
float a = -2 * offset.x();
float b = -2 * offset.y();
float c = offset.x() * offset.x() + offset.y() * offset.y()
+ r1 * r1 - r2 * r2;
return GetLineWithCircleIntersectPoints(a, b, c, r1);
}
std::vector<QPointF> IntersectChecker::GetIntersectPoints(
const std::shared_ptr<RigidBodyCircle>& circle,
const std::shared_ptr<RigidBodyRectangle>& rectangle,
QVector2D offset, float rotation) {
// Нахождение всех точек пересечения круга с прямоугольником -
// это нахождение точек пересечения с каждой стороной круга
float r = circle->GetRadius();
std::vector<QPointF> points = Math::GetRectanglePoints(
offset.toPointF(), rotation, rectangle);
std::vector<QPointF> result;
for (int i = 0; i < 4; i++) {
QPointF first = points[i];
QPointF second = points[(i + 1) % 4];
auto a = static_cast<float>(second.y() - first.y());
auto b = static_cast<float>(first.x() - second.x());
auto c
= static_cast<float>(first.y() * second.x() - first.x() * second.y());
std::vector<QPointF> points_on_line
= GetLineWithCircleIntersectPoints(a, b, c, r);
for (const auto& point : points_on_line) {
if (Math::IsPointOnSegment(first, second, point)) {
result.push_back(point);
}
}
}
return result;
}
std::vector<QPointF> IntersectChecker::GetLineWithCircleIntersectPoints(
float a, float b, float c, float r) {
// Формула нахождения точек пересечения линии с кругом:
// http://e-maxx.ru/algo/circle_line_intersection
std::vector<QPointF> result;
float x0 = -a * c / (a * a + b * b);
float y0 = -b * c / (a * a + b * b);
float formula = c * c - r * r * (a * a + b * b);
if (std::abs(formula) < kEps) {
result.emplace_back(x0, y0);
} else if (formula < -kEps) {
float d = r * r - c * c / (a * a + b * b);
float mult = std::sqrt(d / (a * a + b * b));
QPointF first_intersect(x0 + b * mult, y0 - a * mult);
result.push_back(first_intersect);
QPointF second_intersect(x0 - b * mult, y0 + a * mult);
result.push_back(second_intersect);
}
return result;
}
bool IntersectChecker::IsSimilarVectors(QVector2D first, QVector2D second) {
float cos_between_vectors = QVector2D::dotProduct(first, second)
/ first.length() / second.length();
return cos_between_vectors >= 1 - kCosEps;
}
QVector2D IntersectChecker::CalculateDistanceToObjectNotToIntersectBodies(
const std::shared_ptr<RigidBody>& first,
const std::shared_ptr<RigidBody>& second,
QVector2D offset, float rotation, QVector2D delta_intersect) {
// Поиск максимального расстояния без пересечений
// от первого объекта до второго
// Гарантируется, что при r = 1 пересечение есть
// При l = 0 может как быть, так и не быть пересечения
float l = 0;
float r = 1;
while (r - l > kEps) {
float m = (l + r) / 2;
if (!GetIntersectPointsBodies(first, second,
offset - delta_intersect * m, rotation).empty()) {
r = m - kEps;
} else {
l = m;
}
}
return delta_intersect * l;
}
| true |
dcb40b759e12341cc59219f3bc8df3f7f8f6441a | C++ | rahul-nambiar/SPA4321-2016 | /Ex1.4/main.cpp | UTF-8 | 264 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main() {
float x;
cin >> x;
float y;
cin >> y;
float r = sqrt(pow(x,2)+pow(y,2));
cout << r << endl;
float theta = atan(y/x);
cout << theta << endl;
return 0;
} | true |
55d715cf23a22905a79b66d70c210a419492b7a2 | C++ | JoeKhoa/Source_I_must_learn | /Datat Structure/codeC/Matrix_/main.cpp | UTF-8 | 640 | 3.25 | 3 | [] | no_license | //http://www.cplusplus.com/doc/tutorial/arrays/
#include <iostream>
using namespace std;
int define_matrix();
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
define_matrix();
return 0;
}
int define_matrix(){
const size_t n = 5;
int a[n][n];
a[0][0] = 1;
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
a[i][j+1] = a[i][j]+1;
}
}
for (int i=0; i < n; i++){
cout << endl;
for(int j=0; j < n; j++){
if (a[i][j] < 10 ){
cout << a[i][j] << " ";
}else
cout << a[i][j] << " ";
}
}
}
| true |
5c2874f946e46e8bfc2ff0e76cbd4fe187e64b1a | C++ | Volverman/procon-archive | /atcoder.jp/abc103/abc103_b/Main.cpp | UTF-8 | 584 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define INF 2e9
#define ALL(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
string ROTATE(string S){
char b = S.at(S.size()-1);
S.pop_back();
S = b + S;
return S;
}
int main()
{
string S, T;
cin >> S >> T;
int flag = 0;
REP(i,S.size()){
if(S == T){
flag = 1;
}
S = ROTATE(S);
}
if(flag == 1){
cout << "Yes" << endl;
}else{
cout << "No" << endl;
}
} | true |
a9b31a47e507558b51477364c73f77e50802da82 | C++ | Enhex/GUI | /src/gui/double_clickable.cpp | UTF-8 | 753 | 3.046875 | 3 | [
"LLVM-exception",
"Apache-2.0"
] | permissive | #include "double_clickable.h"
double_clickable::double_clickable()
{
// initialize with a time point furthest away from now()
// as a way to tell if a time press was stored yet or not.
press_time[0] = press_time[1] = time_point_t(std::chrono::steady_clock::now() - time_point_t::max());
}
void double_clickable::on_mouse_press()
{
press_time_index = !press_time_index;
press_time[press_time_index] = std::chrono::steady_clock::now();
}
bool double_clickable::on_mouse_release()
{
using namespace std::chrono;
auto const time_passed = duration_cast<milliseconds>(steady_clock::now() - press_time[!press_time_index]).count();
auto const double_click_ready = (time_passed < double_click_time) & (time_passed >= 0);
return double_click_ready;
}
| true |
b855acb7ecaf4bebdef978410d5e825fc638b799 | C++ | Enrique720/KDTree | /main.cpp | UTF-8 | 2,871 | 2.75 | 3 | [] | no_license | #include <CGAL/Epick_d.h>
#include <CGAL/point_generators_d.h>
#include <CGAL/Manhattan_distance_iso_box_point.h>
#include <CGAL/K_neighbor_search.h>
#include <CGAL/Search_traits_d.h>
#include <CGAL/Search_traits.h>
#include <CGAL/Orthogonal_k_neighbor_search.h>
#include <bits/stdc++.h>
#include "CImg.h"
using namespace std;
typedef CGAL::Epick_d<CGAL::Dimension_tag<100>> Kernel;
typedef Kernel::Point_d Point_d;
typedef Kernel::Iso_box_d Iso_box_d;
typedef Kernel TreeTraits;
typedef CGAL::Manhattan_distance_iso_box_point<TreeTraits> Distance;
typedef CGAL::Orthogonal_k_neighbor_search<TreeTraits, Distance> K_neighbor_search;
typedef K_neighbor_search::Tree Tree;
vector<double> Vectorizar(string filename, int width, int height, int cuts=4)
{
vector<double> R;
CImg<double> img(filename.c_str());
img.resize(width, height);
CImg<double> img2 = img.haar(false, cuts);
CImg<double> img3 = img2.crop(0, 0, 16, 16);
cimg_forXY(img3, x, y)
{
R.push_back((img(x, y, 0) + img(x, y, 1) + img(x, y, 2)) / 3);
}
return R;
}
int main() {
const int N = 1000;
const unsigned int K = 10;
Tree tree;
ifstream infile;
infile.open("data.txt");
string line, name, emocion;
map<Point_d*, pair<string,string>> ptrs;
while (getline(infile, line)) {
vector<double> coor;
stringstream ss(line);
if(getline(ss, line, ' ')){
name = line;
}
if(getline(ss, line, ' ')){
emocion = line;
}
while(getline(ss, line, ' ')){
coor.push_back(stod(line));
}
Point_d* pp = new Point_d(coor.begin(),coor.end());
ptrs[pp] = {name,emocion};
tree.insert(*pp);
}
ifstream testfile;
testfile.open("input.txt");
while (getline(infile, line)) {
vector<double> coor;
stringstream ss(line);
if(getline(ss, line, ' ')){
name = line;
}
if(getline(ss, line, ' ')){
emocion = line;
}
while(getline(ss, line, ' ')){
coor.push_back(stod(line));
}
Point_d qq(coor.begin(),coor.end());
K_neighbor_search search(tree, qq, 5);
for(K_neighbor_search::iterator it = search.begin(); it != search.end(); ++it){
cout << it->first << '\n';
}
}
/*Point_d pp(0.1,0.1,0.1,0.1);
Distance tr_dist;
Neighbor_search N1(tree, pp, n); // eps=10.0, nearest=false
std::cout << "For query rectangle = [0.1, 0.2]^4 " << std::endl
<< "the " << K << " approximate furthest neighbors are: " << std::endl;
for (Neighbor_search::iterator it = N1.begin();it != N1.end();it++) {
std::cout << " Point " << it->first << " at distance " << tr_dist.inverse_of_transformed_distance(it->second) << std::endl;
}*/
return 0;
} | true |
ce578d74244fe43d87e85f3e528bc46df53b494b | C++ | 45deg/NiniroMosaic | /source/image_manager.cpp | UTF-8 | 3,638 | 2.75 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #include "image_manager.hpp"
#include <iostream>
#include <memory>
#include <dirent.h>
#include <sys/types.h>
#include "opencv2/opencv.hpp"
#include <vector>
#include <climits>
#include <mutex>
Tile::Tile(std::string filename, int tileSize, int presicion){
image = cv::imread(filename, 1);
cv::resize(image, image, cv::Size(tileSize, tileSize));
colorInfo = cv::Mat(presicion, presicion, CV_8UC3);
int cropWidth = image.cols / presicion;
int cropHeight = image.rows / presicion;
for(int i = 0; i < presicion; ++i){
for(int j = 0; j < presicion; ++j){
double r = 0, g = 0, b = 0;
for(int y = cropHeight * i; y < cropHeight * (i+1); ++y){
for(int x = cropWidth * j; x < cropWidth * (j+1); ++x){
int offset = y * image.step + x * image.elemSize();
b += image.data[offset+0];
g += image.data[offset+1];
r += image.data[offset+2];
}
}
b /= cropHeight * cropWidth;
g /= cropHeight * cropWidth;
r /= cropHeight * cropWidth;
colorInfo.at<cv::Vec3b>(i,j) = cv::Vec3b(b, g, r);
}
}
}
ImageCollections::ImageCollections(std::string dirName, int tileSize, int presicion){
std::vector<std::string> files = getListOfFiles(dirName);
for (auto&& file : files) {
auto tile = std::make_shared<Tile>(file, tileSize, presicion);
if(tile->image.data != NULL) {
images.push_back(tile);
}
std::cout << "\033[0G" << images.size() << " images loaded" << std::flush;
}
std::cout << std::endl;
std::cout << "Making feature..." << std::endl;
featureMat = cv::Mat(images.size(), presicion*presicion*3, CV_32FC1);
for(int i = 0; i < images.size(); ++i){
cv::Mat lab;
images[i]->colorInfo.convertTo(lab, CV_32FC3, 1./256);
cv::cvtColor(lab, lab, CV_BGR2Lab);
lab.reshape(1,1).copyTo(featureMat.row(i));
}
std::cout << "Making index..." << std::endl;
kdtree = std::make_shared<cv::flann::Index>(featureMat, cv::flann::KDTreeIndexParams(4));
}
void ImageCollections::makeMosaicArt(cv::Mat& masterImage, cv::Mat& outputImage,
int widthTile, int heightTile, int tileSize){
const int dw = masterImage.size().width / widthTile;
const int dh = masterImage.size().height / heightTile;
for(int i = 0; i < heightTile; ++i){
for(int j = 0; j < widthTile; ++j){
cv::Mat cropped = masterImage(cv::Rect(j*dw, i*dh, dw, dh)).clone();
cv::Mat nearestChip = findNearest(cropped);
nearestChip.copyTo(outputImage(cv::Rect(j*tileSize, i*tileSize, tileSize, tileSize)));
}
}
}
cv::Mat ImageCollections::findNearest(cv::Mat& color) {
cv::Mat query = color.reshape(1, 1);
cv::Mat index;
cv::Mat dist;
static auto&& searchParams = cv::flann::SearchParams(32);
kdtree->knnSearch(query, index, dist, 1, searchParams);
return images[index.at<int>(0,0)]->image;
}
std::vector<std::string> ImageCollections::getListOfFiles(std::string dirName){
std::vector<std::string> files;
DIR* dp = opendir(dirName.c_str());
std::string prefix = dirName + "/";
if (dp != NULL)
{
struct dirent* dent;
while((dent = readdir(dp)) != NULL){
// skip hidden file
if(dent->d_name[0] == '.')
continue;
files.push_back(prefix + std::string(dent->d_name));
}
closedir(dp);
}
return files;
}
| true |
74461b7b81be7540937bf50c86372644b10094f1 | C++ | mitiguy/drake | /common/proto/test/call_python_test.cc | UTF-8 | 3,680 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "drake/common/proto/call_python.h"
#include <cmath>
#include <gtest/gtest.h>
// TODO(eric.cousineau): Instrument client to verify output (and make this a
// unittest).
namespace drake {
namespace common {
GTEST_TEST(TestCallPython, DispStr) {
CallPython("print", "Hello");
CallPython("disp", "World");
}
GTEST_TEST(TestCallPython, CheckKwargs) {
// Ensure that we can create dict with Kwargs (MATLAB-style of arguments).
auto out = CallPython("dict", ToPythonKwargs("a", 2, "b", "hello"));
CallPython("print", out);
}
GTEST_TEST(TestCallPython, SetVar) {
CallPython("setvar", "example_var", "Howdy");
// Execute code printing the value.
CallPython("eval", "print(example_var)");
// Print a letter.
CallPython("print", CallPython("eval", "example_var")[2]);
// Print all variables avaiable.
CallPython("print", CallPython("locals").attr("keys")());
}
GTEST_TEST(TestCallPython, DispEigenMatrix) {
Eigen::Matrix2d m;
m << 1, 2, 3, 4;
CallPython("print", m);
Eigen::Matrix<bool, 2, 2> b;
b << true, false, true, false;
CallPython("print", b);
}
GTEST_TEST(TestCallPython, RemoteVarTest) {
auto magic = CallPython("magic", 3);
// N.B. `var.slice(x, y, ...)` and `var[x][y]...` should be interchangeable if
// you are dealing with NumPy matrices; however, `slice(...)` will allow
// strings to be specified for slices (e.g. ":", ":-2", "::-1").
CallPython("print", magic);
CallPython("print", "element(0,0) is ");
CallPython("print", magic[0][0]);
CallPython("print", "element(2,1) is ");
// Show using both `operator[]` and `.slice`.
CallPython("print", magic[2][1]);
CallPython("print", magic.slice(2, 1));
CallPython("print", "elements ([0, 2]) are");
CallPython("print", magic.slice(Eigen::Vector2i(0, 2)));
CallPython("print", "row 2 is ");
CallPython("print", magic.slice(2, ":"));
CallPython("print", "rows [0, 1] are");
CallPython("print", magic[Eigen::VectorXi::LinSpaced(2, 0, 1)]);
CallPython("print", "row 1 (accessed via logicals) is");
CallPython("print", magic.slice(Vector3<bool>(false, true, false), ":"));
CallPython("print", "Third column should now be [1, 2, 3]: ");
magic.slice(":", 2) = Eigen::Vector3d(1, 2, 3);
CallPython("print", magic);
}
GTEST_TEST(TestCallPython, Plot2d) {
const int N = 100;
Eigen::VectorXd time(N), val(N);
for (int i = 0; i < N; i++) {
time[i] = 0.01 * i;
val[i] = sin(2 * M_PI * time[i]);
}
CallPython("print", "Plotting a sine wave.");
CallPython("figure", 1);
CallPython("plot", time, val);
// Send variables in different ways.
CallPython("locals")["val"] = val;
CallPython("locals").attr("update")(ToPythonKwargs("time", time));
// Check usage.
CallPython("eval", "print(len(val) + len(time))");
}
GTEST_TEST(TestCallPython, Plot3d) {
const int N = 25, M = 35;
Eigen::VectorXd x(N), y(M);
Eigen::MatrixXd Z(M, N);
for (int i = 0; i < N; i++) {
x(i) = -3.0 + 6.0 * i / (N - 1);
}
for (int i = 0; i < M; i++) {
y(i) = -3.0 + 6.0 * i / (M - 1);
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
Z(j, i) = 3 * pow(1 - x(i), 2) * exp(-pow(x(i), 2) - pow(y(j) + 1, 2)) -
10 * (x(i) / 5 - pow(x(i), 3) - pow(y(j), 5)) *
exp(-pow(x(i), 2) - pow(y(j), 2)) -
1.0 / 3.0 * exp(-pow(x(i) + 1, 2) - pow(y(j), 2));
}
}
CallPython("print", "Plotting a simple 3D surface");
CallPython("figure", 2);
CallPython("surf", x, y, Z);
// Send variables.
CallPython("setvars", "x", x, "y", y, "Z", Z);
CallPython("eval", "print(len(x) + len(y) + len(Z))");
}
} // namespace common
} // namespace drake
| true |
79c3f16c3ef472fdfeb75f0f740b3e03d4889090 | C++ | nyhu/PCPP | /D04/ex01/main.cpp | UTF-8 | 987 | 2.921875 | 3 | [] | no_license | #include "PlasmaRifle.hpp"
#include "PowerFist.hpp"
#include "SuperMutant.hpp"
#include "RadScorpion.hpp"
#include "Character.hpp"
int main()
{
std::cout << "42 tests" << std::endl;
Character *zaz = new Character("zaz");
std::cout << *zaz;
Enemy *b = new RadScorpion();
AWeapon *pr = new PlasmaRifle();
AWeapon *pf = new PowerFist();
zaz->equip(pr);
std::cout << *zaz;
zaz->equip(pf);
zaz->attack(b);
std::cout << *zaz;
zaz->equip(pr);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
std::cout << std::endl << "personnal tests" << std::endl;
b = new SuperMutant();
zaz->equip(pf);
zaz->attack(b);
std::cout << *zaz;
*pr = *pr;
zaz->equip(pr);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
zaz->attack(b);
std::cout << *zaz;
/* cannot bear undeleted stuff */
delete pr;
delete pf;
delete zaz;
delete b;
return 0;
}
| true |
53e753f49f7b81d193f5304dd98f2cfb4c3486d4 | C++ | SuperUserNameMan/Larduino_HSP | /hardware/LGT/avr/libraries/Larduino_HSPExamples/examples/lgt8fx8p_pwm_d5d6_solo/lgt8fx8p_pwm_d5d6_solo.ino | UTF-8 | 484 | 2.546875 | 3 | [
"MIT"
] | permissive |
uint16_t dutyMax = 0xff;
uint8_t deadBand = 0x8;
void setup() {
// put your setup code here, to run once:
// usage: pwmMode(pin, pwm_mode, freq_mode)
pwmMode(D5, PWM_MODE_SOLO, PWM_FREQ_FAST|PWM_FREQ_BOOST);
// usage: pwmFrequency(pin, freq_in_hz)
// 250KHz PWM frequency
dutyMax = pwmFrequency(D5, 250000);
// usage: pwmWrite(pin, duty)
pwmWrite(D5, dutyMax >> 2);
pwmWrite(D6, dutyMax >> 2);
}
void loop() {
// put your main code here, to run repeatedly:
}
| true |
46f6fea1bcaaf04a0fefbf0911752dfdbfa91e41 | C++ | taxagawa/MATES-for-EV-simulation | /ARouter.h | UTF-8 | 3,533 | 2.828125 | 3 | [] | no_license | /* **************************************************
* Copyright (C) 2014 ADVENTURE Project
* All Rights Reserved
**************************************************** */
#ifndef __AROUTER_H__
#define __AROUTER_H__
#include <string>
#include <vector>
class RoadMap;
class Intersection;
class Route;
class Section;
class OD;
class Vehicle;
/// 大域的経路探索を行うクラスの抽象基底クラス
/**
* @sa Route
* @ingroup Routing
*/
class ARouter
{
public:
ARouter(Intersection*, Intersection*, RoadMap*) {};
virtual ~ARouter(){};
/// 担当する車両を設定する
virtual void setVehicle(Vehicle* vehicle) = 0;
/// 始点と終点および経由地を設定する
virtual void setTrip(OD* od, RoadMap* roadMap) = 0;
/// 選好を設定する
/**
* 重み付けに用いられるため,要素間の相対値が意味を持つ
* それぞれの数値の意味はサブクラスを参照
*/
virtual void setParam(const std::vector<double>&) = 0;
/// 探索を行い,見つかった経路を@p result_routeに格納する
/**
* @param start 探索を開始する交差点
* @param step 処理を打ち切る上限のステップ数
* @param[out] result_route 得られた経路を格納する
*
* @note 探索失敗すると@p result_routeにはNULLが与えられる
* @warning 非NULLの@p result_routeは呼び出し側でdeleteすること
*/
virtual bool search(const Intersection* start,
int step,
Route*& result_route) = 0;
/// searchの@p section指定版
// by uchida 2016/5/10
// EV用に充電フラグを追加
virtual bool search(const Section* section,
const Intersection* start,
int step,
Route*& result_route) = 0;
virtual bool CSsearch(const Section* section,
const Intersection* start,
int step,
Route*& result_route,
std::string stopCS) = 0;
// by uchida 2016/5/27
/// 経路のGvalueを返す
virtual double searchSegmentGV(const Intersection *start,
const Intersection *goal,
const Intersection *past,
int step,
std::string stopCS) = 0;
//
// by uchida 2017/2/26
/// 経路のGvalueを返す(SubNode用)
virtual double searchSegmentGV(const Intersection *start,
const Intersection *goal,
const Intersection *past,
int step) = 0;
/// 最後に通過した経由地を指定する
/**
* 指定された交差点が経由地リストになければ何もしない
*/
virtual void setLastPassedStopPoint(const std::string passedInter) = 0;
/// 経路探索の現在のステップ数を返す
virtual int counter() const = 0;
/// このクラスに設定された情報を返す
virtual void printParam() const = 0;
/// 始点を返す
virtual const Intersection* start() const = 0;
/// 終点を返す
virtual const Intersection* goal() const = 0;
/// 経路探索パラメータを返す
virtual const std::vector<double> param() const = 0;
/// ODデータを返す
virtual OD* od() = 0;
};
#endif
| true |
8cc17218f34ca2bb9279bece8fc0ece839796921 | C++ | crazyanimals/unlimited_racer | /GraphicObjects/Light.cpp | UTF-8 | 8,440 | 2.671875 | 3 | [] | no_license | #include "stdafx.h"
#include "Light.h"
using namespace graphic;
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all colors at once
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetColor( D3DXVECTOR4 *col )
{
Diffuse.r = col->x;
Diffuse.g = col->y;
Diffuse.b = col->z;
Diffuse.a = col->w;
Specular.r = col->x;
Specular.g = col->y;
Specular.b = col->z;
Specular.a = col->w;
Ambient.r = col->x;
Ambient.g = col->y;
Ambient.b = col->z;
Ambient.a = col->w;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all colors at once
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetColor( D3DCOLORVALUE *col )
{
Diffuse.r = col->r;
Diffuse.g = col->g;
Diffuse.b = col->b;
Diffuse.a = col->a;
Specular.r = col->r;
Specular.g = col->g;
Specular.b = col->b;
Specular.a = col->a;
Ambient.r = col->r;
Ambient.g = col->g;
Ambient.b = col->b;
Ambient.a = col->a;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all colors at once
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetColor( D3DCOLOR col )
{
Diffuse.r = (float) ( ( col & 0x00ff0000 ) >> 16 ) / 255.0f;
Diffuse.g = (float) ( ( col & 0x0000ff00 ) >> 8 ) / 255.0f;
Diffuse.b = (float) ( ( col & 0x000000ff ) ) / 255.0f;
Diffuse.a = (float) ( ( col & 0xff000000 ) >> 24 ) / 255.0f;
Specular = Ambient = Diffuse;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all colors at once
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetColor( FLOAT r, FLOAT g, FLOAT b, FLOAT a )
{
Diffuse.r = r;
Diffuse.g = g;
Diffuse.b = b;
Diffuse.a = a;
Specular.r = r;
Specular.g = g;
Specular.b = b;
Specular.a = a;
Ambient.r = 0;
Ambient.g = 0;
Ambient.b = 0;
Ambient.a = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all light's colors with own values
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetColor( D3DCOLOR ambient, D3DCOLOR diffuse, D3DCOLOR specular )
{
Ambient.r = (float) ( ( ambient & 0x00ff0000 ) >> 16 ) / 255.0f;
Ambient.g = (float) ( ( ambient & 0x0000ff00 ) >> 8 ) / 255.0f;
Ambient.b = (float) ( ( ambient & 0x000000ff ) ) / 255.0f;
Ambient.a = (float) ( ( ambient & 0xff000000 ) >> 24 ) / 255.0f;
Diffuse.r = (float) ( ( diffuse & 0x00ff0000 ) >> 16 ) / 255.0f;
Diffuse.g = (float) ( ( diffuse & 0x0000ff00 ) >> 8 ) / 255.0f;
Diffuse.b = (float) ( ( diffuse & 0x000000ff ) ) / 255.0f;
Diffuse.a = (float) ( ( diffuse & 0xff000000 ) >> 24 ) / 255.0f;
Specular.r = (float) ( ( specular & 0x00ff0000 ) >> 16 ) / 255.0f;
Specular.g = (float) ( ( specular & 0x0000ff00 ) >> 8 ) / 255.0f;
Specular.b = (float) ( ( specular & 0x000000ff ) ) / 255.0f;
Specular.a = (float) ( ( specular & 0xff000000 ) >> 24 ) / 255.0f;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// use this if you want to set Theta in degrees
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetTheta( FLOAT angle )
{
Theta = (angle / 180.0f) * D3DX_PI;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// use this if you want to set Phi in degrees
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetPhi( FLOAT angle )
{
Phi = (angle / 180.0f) * D3DX_PI;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets all three relative parameters at once
// use NULL for parameters that shouldn't change
// after settings these parameters, PrecomputePosition() method is called that computes
// position and direction vectors on the base of relative params
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetRelativeSystem( D3DXMATRIX * mat, D3DXVECTOR3 * pos, D3DXVECTOR3 * dir )
{
if ( mat ) RelPointWorldMatrix = *mat;
if ( pos ) RelativePosition = *pos;
if ( dir ) RelativeDirection = *dir;
PrecomputePosition();
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// computes position and direction vectors on the base of relative params
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::PrecomputePosition()
{
D3DXVECTOR3 vec;
D3DXVec3TransformCoord( &Position, &RelativePosition, &RelPointWorldMatrix );
vec = RelativeDirection + RelativePosition;
D3DXVec3TransformCoord( &Direction, &vec, &RelPointWorldMatrix );
Direction -= Position;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// sets standard light settings, type is specifying the light type
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetStandardLight( UINT type )
{
ZeroMemory( this, sizeof( CLight ) );
Enabled = TRUE;
SetColor( 1.5f, 1.5f, 1.5f, 1.0f );
Attenuation1 = 0.002f;
Falloff = 1.0f;
Theta = D3DX_PI / 6;
Phi = D3DX_PI / 2.75f;
Type = type;
switch ( type )
{
case LT_DIRECTIONAL:
case LT_FOGLAMP:
case LT_AMBIENT:
Range = 2000000.0f; // unranged
break;
case LT_LAMP:
case LT_POINT:
Range = 1200.0f;
break;
case LT_CARREFLECTOR:
Range = 2000.0f;
break;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// fills the standard D3DLIGHT9 structure with values appropriate to this light object
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::GetD3DLight( D3DLIGHT9 *D3DLight )
{
D3DLight->Ambient = this->Ambient;
D3DLight->Attenuation0 = this->Attenuation0;
D3DLight->Attenuation1 = this->Attenuation1;
D3DLight->Attenuation2 = this->Attenuation2;
D3DLight->Diffuse = this->Diffuse;
D3DLight->Direction = this->Direction;
D3DLight->Falloff = this->Falloff;
D3DLight->Phi = this->Phi;
D3DLight->Position = this->Position;
D3DLight->Range = this->Range;
D3DLight->Specular = this->Specular;
D3DLight->Theta = this->Theta;
switch ( this->Type )
{
case LT_DIRECTIONAL:
D3DLight->Type = D3DLIGHT_DIRECTIONAL;
break;
case LT_CARREFLECTOR:
case LT_LAMP:
D3DLight->Type = D3DLIGHT_SPOT;
break;
case LT_POINT:
D3DLight->Type = D3DLIGHT_POINT;
break;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// computes the map-position coordinates from the light's real world position
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::SetMapPositionAsWorldPosition()
{
MapPosition.PosX = (int) ( Position.x / TERRAIN_PLATE_WIDTH );
MapPosition.PosZ = (int) ( Position.z / TERRAIN_PLATE_WIDTH );
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// returns all four color components computed from UINT input color
//
//////////////////////////////////////////////////////////////////////////////////////////////
void CLight::ComputeD3DColorValue( D3DCOLORVALUE * newColorValue, D3DCOLOR col )
{
newColorValue->r = (float) ( ( col & 0x00ff0000 ) >> 16 ) / 255.0f;
newColorValue->g = (float) ( ( col & 0x0000ff00 ) >> 8 ) / 255.0f;
newColorValue->b = (float) ( ( col & 0x000000ff ) ) / 255.0f;
newColorValue->a = (float) ( ( col & 0xff000000 ) >> 24 ) / 255.0f;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
| true |
e82fda2ab555e52da4cbf59648bb45ce905ee93e | C++ | SamuelPavlik/MyGameEngine | /MyGameEngine/Quadtree.hpp | UTF-8 | 1,287 | 2.859375 | 3 | [] | no_license | #ifndef Quadtree_hpp
#define Quadtree_hpp
#include <SFML/Graphics.hpp>
#include <memory>
#include <vector>
#include <array>
class C_BoxCollider;
class Quadtree {
public:
Quadtree();
Quadtree(int maxObjects, int maxLevels, int level,
sf::FloatRect bounds, Quadtree* parent);
void Insert(std::shared_ptr<C_BoxCollider>& object);
void Remove(std::shared_ptr<C_BoxCollider>& object);
void Clear();
std::vector<std::shared_ptr<C_BoxCollider>>
Search(const sf::FloatRect& area);
const sf::FloatRect& GetBounds() const;
const bool ContainsNull() const;
void DrawDebug() const;
private:
void SearchInArea(const sf::FloatRect& area,
std::vector<std::shared_ptr<C_BoxCollider>>& overlappingObjects) const;
int GetChildIndexForObject(const sf::FloatRect& objectBounds) const;
void Split();
static const int thisTree = -1;
static const int childNE = 0;
static const int childNW = 1;
static const int childSW = 2;
static const int childSE = 3;
int maxObjects;
int maxLevels;
Quadtree* parent;
std::array<std::shared_ptr<Quadtree>, 4> children;
int level;
sf::FloatRect bounds;
public:
std::vector<std::shared_ptr<C_BoxCollider>> objects;
};
#endif /* Quadtree_hpp */ | true |
568ed73aeac75f285cbc90115a95f7db980779cd | C++ | M3rs/ogle | /src/ogle/camera.cpp | UTF-8 | 2,262 | 2.703125 | 3 | [] | no_license | #include "ogle/camera.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include <SDL2/SDL.h>
namespace ogle {
Camera::Camera(int width, int height)
: m_pos(glm::vec3(0.0f, 0.0f, 8.0f)), m_front(glm::vec3(0.0f, 0.0f, -1.0f)),
m_up(glm::vec3(0.0f, 1.0f, 0.0f)), m_yaw(-90.0f), m_pitch(0.0f),
m_width(width), m_height(height), debug(false) {}
void Camera::update(float dt) {
// mouse / front update
// TODO: refactor to fix mouse look
// BUG - when the movement is *super* fast, the "hidden cursor" shows up big.
// TODO: input handling outside of this
/*
int mx, my;
SDL_GetMouseState(&mx, &my);
float xoff = mx - (m_width / 2);
float yoff = (m_height / 2) - my;
*/
float xoff, yoff;
get_offsets(&xoff, &yoff);
float sensativity = 0.07; // 0.05
xoff *= sensativity;
yoff *= sensativity;
m_yaw += xoff;
m_pitch += yoff;
if (m_pitch > 89.0f)
m_pitch = 89.0f;
if (m_pitch < -89.0f)
m_pitch = -89.0f;
glm::vec3 front;
front.x = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
front.y = sin(glm::radians(m_pitch));
front.z = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
m_front = glm::normalize(front);
// keyboard update
float speed = 3.00f; // px/s old: 2.00
float dist = speed * dt;
const Uint8 *keystate = SDL_GetKeyboardState(NULL);
if (keystate[SDL_SCANCODE_W])
m_pos += dist * m_front;
if (keystate[SDL_SCANCODE_S])
m_pos -= dist * m_front;
if (keystate[SDL_SCANCODE_A])
m_pos -= glm::normalize(glm::cross(m_front, m_up)) * dist;
if (keystate[SDL_SCANCODE_D])
m_pos += glm::normalize(glm::cross(m_front, m_up)) * dist;
m_pos.y = 1.0f;
}
glm::mat4 Camera::get_view() const {
return glm::lookAt(m_pos, m_pos + m_front, m_up);
}
glm::vec3 Camera::get_pos() const { return m_pos; }
glm::vec3 Camera::get_dir() const { return m_front; }
void Camera::set_debug(bool debug) { this->debug = debug; }
glm::vec3 Camera::get_front() const { return m_front; }
glm::vec3 Camera::get_up() const { return m_up; }
void Camera::get_offsets(float *xoff, float *yoff) {
if (debug) {
*xoff = 0;
*yoff = 0;
return;
}
int mx, my;
SDL_GetMouseState(&mx, &my);
*xoff = mx - (m_width / 2);
*yoff = (m_height / 2) - my;
}
}
| true |
08f8ec77bc72d88805edb306ddb137d2ce558a47 | C++ | jancura/modular-server | /DLL/ping/spracuj_net_addr.cpp | UTF-8 | 4,422 | 2.71875 | 3 | [
"MIT"
] | permissive | //definuje funkcie pre spracovanie IP adries, konverziu integera na string
//a obratenie DWORDU
/*Pali Jancura - to jest ja :)
* 08.05.2005
* chng: inicializujGenerovanie() - osetrenie pre masku 0.0.0.0
* 07.05.2005
* rem: my_ping() - presunuty do ping.cpp
* checksum() - presunuty do ping.cpp
* 06.05.2005 - a ideme na samotny ping
* add: my_ping() - nedokoncene
* checksum() - ma nejaku chybu pri pointri => pozmeneby original
* 29.04.2005 - zaciatok komentovania, dufam, ze konecne rozumna verzia generovania IP adries
* add: globalne premenne lastIP; pocetIP; subnetCh[33];
* getLocalIP()
* networkAddress()
* spracujSubnet()
* generujIP()
* inicializujGenerovanie()
* obratDWORD()
* dectostr()
*/
#include "stdafx.h"
#include "spracuj_net_addr.h"
#include <stdexcept>
#include <winsock.h>
#include <iostream>
#include "ip_icmp.h"
#include "iphdr.h"
//maximalna dlzka pre name loclahostu a velkosti bufferu
#define maxlen 255
//definovanie globalnych premennych
static struct in_addr lastIP;
static int pocetIP;
static unsigned char subnetCh[32]; //32 pretoze nebudem inicializovat pre
//masku 0.0.0.0
/******************************************************************************
* getLocalIP() - v l-e byteorder
*****************************************************************************/
int getLocalIP(struct in_addr *in)
{
char hostname[maxlen];
try{
if(gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR)
throw std::domain_error("chyba v getLocalIP () pri gethostname()");
hostent *H = gethostbyname(hostname);
if(H == NULL)
throw std::domain_error("chyba v getLocalIP() gethostBYname()");
if(H->h_addr_list[0] == NULL)
throw std::domain_error("chyba v getLocalIP() - H->h_addr_list je prazdny");
*in = *(in_addr *)H->h_addr_list[0];
return 0;
}catch (std::domain_error e) {
std::cerr << e.what() << std::endl;
return -1;
}
} //getLocalIP() */
/******************************************************************************
* networkAddres - ku danej ip adrese priradi na zaklade subnet masky adresu
* siete
*****************************************************************************/
struct in_addr networkAddress(struct in_addr addr, struct in_addr subnet)
{
struct in_addr naddr;
naddr.s_addr = addr.s_addr & subnet.s_addr;
return naddr;
} //networkAddres */
/******************************************************************************
* spracujSubnet - vrati pocet nul v subnet maske a naplni pole s poziciami
* tychto nul (znak 32 je ukoncovaci znak)
*****************************************************************************/
int spracujSubnet(struct in_addr subnet)
{
int S_addr = (subnet.s_addr);
int pocet = 0;
for(int i = 31; i >= 0; --i){
if (S_addr >> i) S_addr -= 1 << i;
else subnetCh[pocet++] = i;
}
subnetCh[pocet] = 32;
if(pocet == 0) return -1;
return pocet;
}//spracujSubnet() */
/******************************************************************************
* vygeneruje IP adresu na zaklade predchadzajucej IP ulozenej v globalne
* premennej lastIP
*****************************************************************************/
int generujIP(struct in_addr* in)
{
int i = 0, pom = 255 << 24;
if(pocetIP == 0) return -1;
//generuje novu IP podla lastIP pomocou binarnej operacie xor a uklada ju hned do lastIP
while(subnetCh[i] != 32){
lastIP.s_addr = lastIP.s_addr^(1 << subnetCh[i]);
if (lastIP.s_addr & (1<<subnetCh[i++])) break;
}
pocetIP--;
//overi, ci neide o niektoru z specialnych IP vyhradenych pre siet
if( ((lastIP.s_addr & pom) == 0) || ((lastIP.s_addr & pom) == pom) ){
if (generujIP(in)) return -1;
}else *in = lastIP; //ak nie priradi vysledok, teda novu IP
return 0;
} //generujIP() */
/******************************************************************************
* inicializuje hodnoty pre funkciu generujIP()
*****************************************************************************/
int inicializujGenerovanie(struct in_addr localIP, struct in_addr subnet)
{
int i;
if(!(subnet.s_addr == 0)){
lastIP = networkAddress(localIP, subnet);
if((i = spracujSubnet(subnet)) == -1) return -1;
pocetIP = (1 << i);
return 0;
}//je sprosta maska,pre 1<<32 nestaci typ int, preto to nebudem podporovat :)
return -1;
}//inicializujGenerovanie() */
| true |
3b544a5b71e35ca22d5ecd0b23bf5e18b45a2410 | C++ | iulianR/snippets | /bmp/bmp.cpp | UTF-8 | 1,917 | 3.109375 | 3 | [] | no_license | #include "bmp.h"
#include <cstring>
#include <fstream>
#include <iterator>
#include <iostream>
using namespace std;
namespace bmp {
Image::~Image()
{
::memset(&m_bfh, 0x00, sizeof m_bfh);
::memset(&m_bih, 0x00, sizeof m_bih);
::memset(&m_data, 0x00, sizeof m_data);
}
void Image::load()
{
ifstream stream(m_filename, ios::binary);
if (!stream.is_open())
return;
::memset(&m_bfh, 0x00, sizeof m_bfh);
::memset(&m_bih, 0x00, sizeof m_bih);
stream.read(reinterpret_cast<char*>(&m_bfh), sizeof m_bfh);
stream.read(reinterpret_cast<char*>(&m_bih), sizeof m_bih);
m_width = m_bih.width;
m_height = m_bih.height;
m_bpp = m_bih.color_depth >> 3;
m_row_inc = m_width * m_bpp;
m_data.resize(m_height * m_row_inc);
int padding = (4 - ((m_bpp * m_width) % 4)) % 4;
char padding_data[4] = {0,0,0,0};
for (unsigned int i; i < m_height; ++i) {
int row_index = m_height - i - 1;
unsigned char* data = const_cast<unsigned char*>(&m_data[m_row_inc * row_index]);
stream.read(reinterpret_cast<char*>(data), sizeof(char) * m_bpp * m_width);
stream.read(padding_data, padding);
}
stream.close();
}
void Image::save(const std::string& filename)
{
ofstream stream(filename, ios::binary);
if (!stream.is_open())
return;
stream.write(reinterpret_cast<char*>(&m_bfh), sizeof m_bfh);
stream.write(reinterpret_cast<char*>(&m_bih), sizeof m_bih);
int padding = (4 - ((m_bpp * m_width) % 4)) % 4;
char padding_data[4] = {0x00,0x00,0x00,0x00};
for (unsigned int i = 0; i < m_height; i++) {
int row_index = m_height - i - 1;
const unsigned char* data = &m_data[m_row_inc * row_index];
stream.write(reinterpret_cast<const char*>(data), sizeof(unsigned char) * m_bpp * m_width);
stream.write(padding_data, padding);
}
stream.close();
}
}
| true |
a34737f01ce93de0f71eba85df23bb57c20cbcc0 | C++ | talsahar/HangmanOnline | /Game/src/Guest.cpp | UTF-8 | 2,091 | 2.78125 | 3 | [] | no_license | /*
* Guest.cpp
*
* Created on: Aug 15, 2017
* Author: user
*/
#include "Guest.h"
namespace npl {
Guest::Guest( string peerIP) :
Player(GUEST_PORT) {
this->peerIP = peerIP;
this->peerPort = HOST_PORT;
}
Guest::~Guest(){
}
int Guest::startGame() {
if(!sendCommand(GUEST_SAY_HELLO, NULL))
{
onError("couldnt connect: host is not available");
return 0;
}
cout<<"waiting for hosts secret.."<<endl;
readWhile();
close();
return score;
}
void Guest::analyzeMessage(char* msg) {
bool booli;
char tmpchar[100];
char* c;
switch (atoi(msg)) {
case TOPIC_AND_WORD:
printTopic(readMessage(tmpchar));
c=getValidGuess();
if(c[0]=='0')
sendCommand(GUEST_SAY_BYE, NULL);
else
sendCommand(GUESS, c);
break;
case CORRECT_GUESS:
cout<<"correct guess :)"<<endl;;
break;
case BAD_GUESS:
cout<<"incorrect guess :("<<endl;
printHangedMan(readMessage(tmpchar));
break;
case WIN:
score++;
booli = onGameOver(1,readMessage(tmpchar));
if (booli == true)
sendCommand(GUEST_SAY_HELLO, NULL);
else {
playing = false;
sendCommand(GUEST_SAY_BYE, NULL);
}
break;
case LOSE:
booli =onGameOver(0,readMessage(tmpchar));
if (booli == true)
sendCommand(GUEST_SAY_HELLO, NULL);
else {
playing = false;
sendCommand(GUEST_SAY_BYE, NULL);
}
break;
}
}
char* Guest::getValidGuess() {
char tmpchar;
do {
cout << "enter guess: ";
cin >> tmpchar;
} while ((tmpchar<'a'||tmpchar>'z')&&tmpchar!='0');
char* arr=new char[1];
arr[0]=tmpchar;
return arr;
}
int Guest::send(string msg) {
return socket->write(msg, peerIP, peerPort);
}
void Guest::printTopic(char* str) {
char* topic = strtok(str, ",");
char* word = strtok(NULL, ",");
cout << "-------" << endl;
cout << "topic: " << topic << endl;
cout << "secret: ";
for(int i=0;i<strlen(word);i++)
cout<<word[i]<<" ";
cout<<endl<<"-------"<<endl;
}
bool Guest::onGameOver(bool won,string message) {
if(won)
manPrinter.hangedwinner();
else
manPrinter.hanged0();
cout <<"The word was: "<< message << endl;
return retryQ();
}
} /* namespace npl */
| true |
cab206f0466d9928ae5c4d3c8c37f91fffcbb62f | C++ | TereSolano15/lab02-oop-lions | /University.cpp | UTF-8 | 1,796 | 3.21875 | 3 | [] | no_license | //
// Created by Maikol Guzman on 8/2/20.
//
#include <sstream>
#include "University.h"
University::University(const string &name, Professor *professor, Administrative *administrative,
const vector<Professor> &professorList, const vector<Administrative> &administrativeList)
:name(name), professor(professor), administrative(administrative), professorList(professorList), administrativeList(
administrativeList) {}
University::University(const string &name) : name(name) {}
University::University() {}
University::~University() {
}
const string &University::getName() const {
return name;
}
void University::setName(const string &name) {
University::name = name;
}
Professor *University::getProfessor() const {
return professor;
}
void University::setProfessor(Professor *professor) {
University::professor = professor;
}
Administrative *University::getAdministrative() const {
return administrative;
}
void University::setAdministrative(Administrative *administrative) {
University::administrative = administrative;
}
const vector<Professor> University::getListProfessor() {
vector<Professor> professorListReturn;
for (int cont = 0; cont < professorList.size(); cont++) {
professorListReturn.push_back(professorList[cont]);
}
return professorList;
}
void University::addProfessor(Professor pro){
professorList.push_back(pro);
}
const vector<Administrative> University::getListAdministrative() {
vector<Administrative> administrativeListReturn;
for (int cont = 0; cont < administrativeList.size(); cont++) {
administrativeListReturn.push_back(administrativeList[cont]);
}
return administrativeList;
}
void University::addAdministrative(Administrative admin) {
administrativeList.push_back(admin);
}
| true |
691c8f768d1b60c1992204202da50da8729be0c5 | C++ | irbisPro10/laba3 | /labaTPMlist/labaTPMlist/labaTPMlist.cpp | WINDOWS-1251 | 4,169 | 3.1875 | 3 | [] | no_license | // labaTPMlist.cpp: .
//
#include "stdafx.h"
class list{
list *l = 0x00, *first = 0x00;//
int i;//
public:
list *lN, *lP;
int inf;
list(){
lN = lP = 0x00;
}
list(list *prev, list *next){
lP = prev;
lN = next;
}
int addUp(int inf){//
l = first;
i = 0;
while (l != 0x00 && l->lN != 0x00){
i++;
l = l->lN;
}
if (l != 0x00){
l->lN = new list();
l->lN->lP = l;
l->lN->inf = inf;
}
else{
first = l = new list();
l->inf = inf;
}
return 0;
}
int addIn(int n, int inf){//
l = first;
i = 0;
while (l != 0x00 && l->lN != 0x00 && i<n){
i++;
l = l->lN;
}
if (i < n) addUp(inf);
else{
if (l != 0x00){
l = new list(l->lP, l);
if (l->lP != 0x00){
l->lP->lN = l;
}
else first = l;
if (l->lN != 0x00) l->lN->lP = l;
l->inf = inf;
}
else{
first = l = new list();
l->inf = inf;
}
}
return 0;
}
int addDown(int inf){//
l = first;
if (l != 0x00){
first = l->lP = new list();
first->lN = l;
first->inf = inf;
}
else{
first = l = new list();
l->inf = inf;
}
return 0;
}
int delUp(){//
l = first;
i = 0;
while (l != 0x00 && l->lN != 0x00){
i++;
l = l->lN;
}
if (l != 0x00){
if (l->lP == 0x00) first = 0x00;
else l->lP->lN = 0x00;
delete(l);
}
else{
return 2;
}
return 0;
}
int delIn(int n){//
l = first;
i = 0;
while (l != 0x00 && l->lN != 0x00 && i<n){
i++;
l = l->lN;
}
if (l != 0x00){
if (l->lP == 0x00 && l->lN == 0x00) first = 0x00;
if (l->lP != 0x00 && l->lN != 0x00){ l->lP->lN = l->lN; l->lN->lP = l->lP; }
if (l->lP != 0x00 && l->lN == 0x00){ l->lP->lN = l->lN; }
if (l->lP == 0x00 && l->lN != 0x00){ l->lN->lP = l->lP; }
delete(l);
}
else{
return 2;
}
return 0;
}
int delDown(){//
l = first;
if (l != 0x00){
if (l->lN == 0x00) first = 0x00;
else{
first = l->lN;
l->lN->lP = 0x00;
}
delete(l);
}
else{
return 2;
}
return 0;
}
void print(){
l = first;
i = 0;
if (l != 0x00){
while (l != 0x00){
cout << l->inf << endl;
i++;
l = l->lN;
}
}
else{
cout << "> !\n";
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int inf, n;
char c;
setlocale(LC_ALL,"Rus");
list l;
cout << endl<<"+ - "<<endl<<"* - "<<endl<<"- - "<<endl<<"/ - "<<endl<<"= - "<<endl<<"_ - "<<endl<<"p - "<<endl<<"0 - "<<endl;
while (1){
cout << ">> ";
cin >> c;
if (c == 'p'){
l.print();
}
if (c == '0') break;
if (c == '+'){
cout << "> ";
cin >> inf;
if (l.addUp(inf) == 0) cout << ""<<endl;
else cout << "" << endl;
}
if (c == '*'){
cout << "> ";
cin >> inf;
if (l.addDown(inf) == 0) cout << ""<<endl;
else cout << ""<<endl;
}
if (c == '='){
cout << "> >";
cin >> n;
cout << "> ";
cin >> inf;
if (l.addIn(n, inf) == 0) cout << ""<<endl;
else cout << "" << endl;
}
if (c == '-'){
if (l.delUp() == 0) cout << ""<<endl;
else cout << "" << endl;
}
if (c == '/'){
if (l.delDown() == 0) cout << ""<<endl;
else cout << "" << endl;
}
if (c == '_'){
cout << " ";
cin >> n;
if (l.delIn(n) == 0) cout << "";
else cout << " "<<endl;
}
}
return 0;
}
| true |
ee1807791fa0c1bd2864b6352bd7eb991c337163 | C++ | charlyzt/tarea-1 | /trabajos domingo/temporizador.cpp | UTF-8 | 541 | 2.921875 | 3 | [] | no_license | #include <iostream>
//temporizador
using namespace std;
int main(int argc, char *argv[])
{
int temporizador = 1;
int segundos=0;
int minutos;
while (true)
int s=1;
cout << temporizador << endl;
if (temporizador == segundos) cout << "***fin del tiempo ***" << endl;
if (temporizador > segundos)
segundos=(1000); //1 segundo
temporizador++;
cout << "Segundos para que suene la alarma: ";
cin>>segundos;
segundos(cin, segundos);
if ((s) >> segundos) alarma(segundos);
return 0;
}
| true |
35eb3fd3700c519984b2d143af20fae339ad455e | C++ | GerdHirsch/Cpp-Basics | /BadCode/src/TrafficLight.cpp | UTF-8 | 2,196 | 2.875 | 3 | [] | no_license | ///////////////////////////////////////////////////////////
// Ampel.cpp
// Implementation of the Class Ampel
// Created on: 30-Sep-2008 14:54:02
///////////////////////////////////////////////////////////
#include <exception>
#include <iostream>
using namespace std;
#include "TrafficLight.h"
#include "LightBulb.h"
#include "ProtocolViolationException.h"
void TrafficLight::off(){
if (state != OFF && state != TWINKLING)
throw ProtocolViolationException("Ampel.aus() in falschem State");
cout << "Ampel::aus() in State: Blinkend" << endl;
state = OFF;
red->off();
yellow->off();
green->off();
}
void TrafficLight::switchOver(){
switch(state){
case RED:
cout << "TrafficLight::switchOver() in State: RED" << endl;
state = REDYELLOW;
//entry Action
red->on();
yellow->on();
green->off();
break;
case REDYELLOW:
state = GREEN;
cout << "TrafficLight::switchOver() in State: REDYELLOW" << endl;
//entry Action
red->off();
yellow->off();
green->on();
break;
case GREEN:
cout << "TrafficLight::switchOver() in State: GREEN" << endl;
//entry Action
state = YELLOW;
red->off();
yellow->on();
green->off();
break;
case YELLOW:
cout << "TrafficLight::switchOver() in State: YELLOW" << endl;
//entry Action
state = RED;
red->on();
yellow->off();
green->off();
break;
case TWINKLING:
cout << "TrafficLight::switchOver() in State: TWINKLING" << endl;
//TODO exit Action: stop TWINKLINGThread
state = YELLOW;
//Entry Action
red->off();
yellow->on();
green->off();
break;
case OFF:
default:
throw ProtocolViolationException("TrafficLight::switchOver() in State OFF");
};
}
TrafficLight::TrafficLight(LightBulb* rot, LightBulb* gelb, LightBulb* gruen)
:red(rot), yellow(gelb), green(gruen), state(OFF)
{}
void TrafficLight::warn(){
/*
Alles Ausschalten und blinken Thread starten
*/
cout << "Ampel::warne()" << endl;
state = TWINKLING;
red->off();
yellow->on(); // symbolisch f�r blinkend
green->off();
}
| true |