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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
51df85aaffd6e34c05f59ae0e6275e3cfaa7a4fd | C++ | wrongway88/RemoteMouse | /src/framework/MainLoop.cpp | UTF-8 | 320 | 2.640625 | 3 | [] | no_license | #include "MainLoop.h"
MainLoop::MainLoop(BaseApplication* baseApplication):
m_application(baseApplication)
{}
MainLoop::~MainLoop()
{}
void MainLoop::run()
{
bool run = true;
m_application.setup();
while(run)
{
m_application.update();
run = m_application.getKeepRunning();
}
m_application.shutdown();
} | true |
4ce224ccc4099e5f6fd8da5a8fbff25b2354c0c4 | C++ | King00s/OJ100 | /快速排序.cpp | GB18030 | 956 | 3.296875 | 3 | [] | no_license | #include<bits/stdc++.h>
void swap(int& a, int& b) {
int t = b;
b = a;
a = t;
}
void quicksort(int a[], int start, int end){
if(end>start){
// ѡһΪ
int part=rand()%(end-start)+start;
int divide=a[part];
//
swap(a[start], a[part]);
int i = start;
int j = i+1;
while(j<end) {
while(a[j]>divide&&j<end)
j++;
if(j<end){
i++;
swap(a[i],a[j]);
j++;
}
}
swap(a[i],a[start]);
quicksort(a,start,i);
quicksort(a,i+1,end);
}
}
int main()
{
int n;
// Ԫظ
scanf("%d\n",&n);
int array[n];
int i,j;
for(i=0;i<n;i++)
{
// Ԫ
scanf("%d",&array[i]);
}
printf("\n");
quicksort(array,0,n);
for(j=0;j<n;j++)
{
printf("%d ",array[j]);
}
return 0;
}
| true |
568af684d423ceaeb5cf0a94d3eaf85d396982d7 | C++ | Ilgrim/PandaSDL | /src/ai/behaviour_tree/nodes/combiners.h | UTF-8 | 1,057 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef __pandasdl_behaviourtree_combiners_h__
#define __pandasdl_behaviourtree_combiners_h__
#include "base.h"
namespace PandaSDL::BehaviourTree
{
/*
Run all children, waiting on each to complete, regardless of their success
*/
class Combiner : public BehaviourTreeNode
{
public:
Combiner();
~Combiner();
virtual eNodeStatus Run() override;
protected:
unsigned int _nodeIndex;
std::vector<std::shared_ptr<BehaviourTreeNode>> _children;
};
/*
Run all children, waiting on each to complete, until they all finish or one returns failure
*/
class CombinerUntilFailure : public BehaviourTreeNode
{
public:
CombinerUntilFailure();
~CombinerUntilFailure();
virtual eNodeStatus Run() override;
protected:
unsigned int _nodeIndex;
std::vector<std::shared_ptr<BehaviourTreeNode>> _children;
};
}
#endif | true |
4013dd23138f2f517a207adbf0a9d376d552cd23 | C++ | ixan29/MathSolver | /Utils.cpp | UTF-8 | 8,775 | 3.125 | 3 | [] | no_license | #include "Utils.h"
#include "ConstFunction.h"
#include "VarFunction.h"
#include "SumFunction.h"
#include "MulFunction.h"
#include "DivFunction.h"
#include "PowFunction.h"
#include "LogFunction.h"
#include "SinFunction.h"
#include "CosFunction.h"
#include "TanFunction.h"
#include "MatrixFunction.h"
#include <cstring>
#include <stdexcept>
bool needsParentheses(const Function& function)
{
return function.getType() == typeid(SumFunction).hash_code();
}
std::shared_ptr<Function> createSerie(const std::shared_ptr<Function> function, const std::string& variable, const double value, const unsigned degree)
{
std::map<std::string, std::shared_ptr<Function>> var {
{variable, ConstFunction::create(value)}
};
std::vector<std::shared_ptr<Function>> terms;
terms.reserve(degree+1);
double factorial = 1;
terms.push_back (
function->solve(var)
);
std::shared_ptr<Function> der = function;
for(unsigned i=1 ; i<=degree; i++)
{
der = der->derivative(variable);
factorial *= i;
terms.push_back(
MulFunction::create({
DivFunction::create (
der->solve(var),
ConstFunction::create(factorial)
),
PowFunction::create (
SumFunction::create ({
VarFunction::create(variable),
ConstFunction::create(-value)
}),
ConstFunction::create(i)
)
})
);
}
return SumFunction::create(terms);
}
std::vector<std::string> splitCommas(const std::string& str)
{
std::vector<std::string> split {""};
int countPar=0;
for(char c : str)
switch(c)
{
case '{':
case '(': countPar++; break;
case '}':
case ')': countPar--; break;
case ',':
if(countPar==0)
split.push_back("");
break;
default: split.back() += c; break;
}
return split;
}
std::vector<std::string> splitSums(const std::string& str)
{
std::vector<std::string> split {""};
int countPar=0;
for(char c : str)
switch(c)
{
case '(': countPar++; break;
case ')': countPar--; break;
case '+':
if(countPar==0)
split.push_back("");
break;
case '-':
if(countPar==0)
{
if(split.back()=="")
split.back() += '-';
else
split.push_back("-");
}
break;
default: split.back() += c; break;
}
return split;
}
std::vector<std::string> splitMuls(const std::string& str)
{
std::vector<std::string> split {""};
int countPar=0;
for(char c : str)
switch(c)
{
case '(': countPar++; break;
case ')': countPar--; break;
case '*':
if(countPar==0)
split.push_back("");
break;
default: split.back() += c; break;
}
return split;
}
std::vector<std::string> splitDivs(const std::string& str)
{
std::vector<std::string> split {""};
int countPar=0;
for(char c : str)
switch(c)
{
case '(': countPar++; break;
case ')': countPar--; break;
case '/':
if(countPar==0)
split.push_back("");
break;
default: split.back() += c; break;
}
return split;
}
std::vector<std::string> splitPow(const std::string& str)
{
std::vector<std::string> split {""};
int countPar=0;
for(char c : str)
switch(c)
{
case '(': countPar++; break;
case ')': countPar--; break;
case '^':
if(countPar==0)
split.push_back("");
break;
default: split.back() += c; break;
}
return split;
}
bool isNumber(const std::string& str)
{
for(char c : str)
if(!isdigit(c)
&& c != '.'
&& c != '-'
)
return false;
return true;
}
std::shared_ptr<Function> parse(const std::string& expr, std::map<std::string, std::shared_ptr<Function>>& map)
{
std::string str = expr;
auto sums = splitSums(str);
if(sums.size() > 1)
{
std::vector<std::shared_ptr<Function>> s;
s.reserve(sums.size());
for(auto& sum : sums)
s.push_back(parse(sum, map));
return SumFunction::create(s);
}
auto muls = splitMuls(str);
if(muls.size() > 1)
{
std::vector<std::shared_ptr<Function>> m;
m.reserve(muls.size());
for(auto& mul : muls)
m.push_back(parse(mul, map));
return MulFunction::create(m);
}
auto divs = splitDivs(str);
if(divs.size() > 1)
{
std::vector<std::shared_ptr<Function>> d;
d.reserve(divs.size());
for(auto& div : divs)
d.push_back(parse(div, map));
return
DivFunction::create(
d[0],
MulFunction::create(
std::vector<std::shared_ptr<Function>>(d.begin()+1, d.end())
)
);
}
auto pows = splitPow(str);
if(pows.size() > 2)
throw std::runtime_error("powers are anbiguous here: "+str+". Use parentheses plz");
if(pows.size() == 2)
return
PowFunction::create (
parse(pows[0], map),
parse(pows[1], map)
);
if(str[0]=='(')
if(str.back()==')')
return parse(str.substr(1, str.length()-2), map);
else
throw std::runtime_error("missing closing bracket after "+str);
if(str.find("log")==0)
return LogFunction::create(parse(str.substr(3), map));
if(str.find("sin")==0)
return SinFunction::create(parse(str.substr(3), map));
if(str.find("cos")==0)
return CosFunction::create(parse(str.substr(3), map));
if(str.find("tan")==0)
return TanFunction::create(parse(str.substr(3), map));
if(str.find("matrix")==0)
{
auto numsStr = splitCommas(str.substr(7, str.length()-8));
return MatrixFunction::create(
std::stoi(numsStr[0]),
std::stoi(numsStr[1])
);
}
if(str.find("identity")==0)
{
auto numStr = str.substr(9, str.length()-10);
return MatrixFunction::identity(std::stoi(numStr));
}
if(str.find("transpose")==0)
{
auto func = parse(str.substr(10, str.length()-11), map);
if(func->getType() == typeid(MatrixFunction).hash_code())
return std::static_pointer_cast<MatrixFunction>(func)->transpose();
throw std::runtime_error("Getting a transpose from a non-matrix function is impossible");
}
if(str.find("det")==0)
{
auto func = parse(str.substr(4, str.length()-5), map);
if(func->getType() == typeid(MatrixFunction).hash_code())
return std::static_pointer_cast<MatrixFunction>(func)->determinant();
throw std::runtime_error("Getting the determinant from a non-matrix function is impossible");
}
if(str.find("derivative{")==0)
{
if(str.back() != '}')
throw std::runtime_error("missing closing bracket a the end of "+str);
str = str.substr(strlen("derivative{"));
str = str.substr(0, str.length()-1);
return
parse(str.substr(str.find(',')+1), map)
->derivative(str.substr(0, str.find(",")));
}
if(str.find('(') < str.length())
{
if(str.back() != ')')
throw std::runtime_error("missing parenthese at the end of "+str);
std::string variable = str.substr(0, str.find('('));
str = str.substr(str.find('(')+1);
str = str.substr(0, str.length()-1);
std::map<std::string, std::shared_ptr<Function>> localFunctions;
for(auto arg : splitCommas(str))
{
if(arg.find('=') >= arg.length())
throw std::runtime_error("missing = symbol at argument: "+arg);
localFunctions[arg.substr(0, arg.find('='))] =
parse(arg.substr(arg.find('=')+1), map);
}
return map[variable]->solve(localFunctions);
}
if(isNumber(str))
return ConstFunction::create(std::stod(str));
else
if(map.count(str))
return map[str];
else
return VarFunction::create(str);
} | true |
e0250e03d524b13b43a4c4259b6206e0dde881bb | C++ | ovieira/pavement | /projects/pavement/src/Canvas.cpp | UTF-8 | 4,356 | 2.765625 | 3 | [] | no_license | #include "Canvas.h"
Canvas::Canvas() {
_camera = new Camera(glm::vec3(0.0 , 5.0, 5.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0), new Camera::Perspective(30.0f, 1.0f, 2.0f, 20.0f));
_linesNr = 40;
_interval = 0.25f;
generateGrid();
}
Canvas::~Canvas() {
}
void Canvas::generateGrid() {
glm::vec4 startVerticalPoint(0.0, 0.0, -5.0, 1.0);
glm::vec4 endVerticalPoint(0.0, 0.0, 5.0, 1.0);
glm::vec4 startHorizontalPoint(-5.0, 0.0, 0.0, 1.0);
glm::vec4 endHorizontalPoint(5.0, 0.0, 0.0, 1.0);
// Z axis
_lines.push_back(startVerticalPoint);
_lines.push_back(endVerticalPoint);
// X axis
_lines.push_back(startHorizontalPoint);
_lines.push_back(endHorizontalPoint);
for (int i = 1; i < _linesNr / 2; i++) {
//Vertical right
_lines.push_back(glm::vec4(startVerticalPoint.x + _interval * i, startVerticalPoint.y, startVerticalPoint.z, startVerticalPoint.w));
_lines.push_back(glm::vec4(endVerticalPoint.x + _interval * i, endVerticalPoint.y, endVerticalPoint.z, endVerticalPoint.w));
//vertical left
_lines.push_back(glm::vec4(startVerticalPoint.x - _interval * i, startVerticalPoint.y, startVerticalPoint.z, startVerticalPoint.w));
_lines.push_back(glm::vec4(endVerticalPoint.x - _interval * i, endVerticalPoint.y, endVerticalPoint.z, endVerticalPoint.w));
//Horizontal front
_lines.push_back(glm::vec4(startHorizontalPoint.x, startHorizontalPoint.y, startHorizontalPoint.z + _interval * i, startHorizontalPoint.w));
_lines.push_back(glm::vec4(endHorizontalPoint.x, endHorizontalPoint.y, endHorizontalPoint.z + _interval * i, endHorizontalPoint.w));
//Horizontal back
_lines.push_back(glm::vec4(startHorizontalPoint.x, startHorizontalPoint.y, startHorizontalPoint.z - _interval * i, startHorizontalPoint.w));
_lines.push_back(glm::vec4(endHorizontalPoint.x, endHorizontalPoint.y, endHorizontalPoint.z - _interval * i, endHorizontalPoint.w));
}
for (int i = 0; i < (int)_lines.size() ; i++) {
_lineColors.push_back(glm::vec4(0.5, 0.5, 0.5, 1.0));
}
}
void Canvas::highlightGrid(int n) {
switch(n){
case 0:
_lineColors[0] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[1] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[2] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[3] = glm::vec4(0.5, 0.5, 0.5, 1.0);
break;
case 1:
_lineColors[0] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[1] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[2] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[3] = glm::vec4(0.5, 0.5, 0.5, 1.0);
break;
case 2:
_lineColors[0] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[1] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[2] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[3] = glm::vec4(0.7, 0.7, 0.1, 1.0);
break;
case 3:
_lineColors[0] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[1] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[2] = glm::vec4(0.5, 0.5, 0.5, 1.0);
_lineColors[3] = glm::vec4(0.5, 0.5, 0.5, 1.0);
break;
case 4:
_lineColors[0] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[1] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[2] = glm::vec4(0.7, 0.7, 0.1, 1.0);
_lineColors[3] = glm::vec4(0.7, 0.7, 0.1, 1.0);
break;
}
createBufferObjects();
}
void Canvas::createBufferObjects() {
glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);
glGenBuffers(4, VboId);
glBindBuffer(GL_ARRAY_BUFFER, VboId[0]);
glBufferData(GL_ARRAY_BUFFER, _lines.size() * sizeof(glm::vec4), &_lines[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(VERTICES);
glVertexAttribPointer(VERTICES, 4, GL_FLOAT, GL_FALSE, sizeof( glm::vec4 ), 0);
glBindBuffer(GL_ARRAY_BUFFER, VboId[1]);
glBufferData(GL_ARRAY_BUFFER, _lineColors.size()*sizeof(glm::vec4), &_lineColors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(COLORS);
glVertexAttribPointer(COLORS, 4, GL_FLOAT, GL_FALSE, sizeof( glm::vec4 ), 0);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(COLORS);
glDisableVertexAttribArray(VERTICES);
//checkOpenGLError("ERROR: Could not create VAOs and VBOs.");
}
void Canvas::draw() {
_camera->lookAt();
_camera->project();
glBindVertexArray(VaoId);
glDrawArrays(GL_LINES, 0, _lines.size());
glBindVertexArray(0);
_scene.draw();
}
void Canvas::addNode(SceneNode* n) {
_scene.addNode(n);
}
SceneGraph* Canvas::getScene() {
return &_scene;
}
Camera* Canvas::getCamera() {
return _camera;
}
| true |
5416547f2fcddb3862b1d98d344e55648e2b0d5f | C++ | midorae/LastSubString | /main.cpp | UTF-8 | 998 | 3.390625 | 3 | [] | no_license | //
// main.cpp
// LastSubstring
//
// Created by 이창기 on 2016. 11. 21..
// Copyright © 2016년 이창기. All rights reserved.
//
#include <iostream>
using namespace std;
string lastSubstring(string s);
int main(int argc, const char * argv[])
{
string str;
string lastSubstr;
cout << "Input Your String :";
cin >> str;
lastSubstr = lastSubstring(str);
cout << "lastSubString : " << lastSubstr << endl;
return 0;
}
string lastSubstring(string s)
{
char lastStr[101];
int i = 0;
int max_Index = 0;
char max = s[max_Index];
int count = 0;
while(s[i] != 0)
{
if(max < s[i])
{
max_Index = i;
max = s[i];
}
i++;
}
lastStr[0] = max;
count++;
for(i=max_Index+1; i<s.length(); i++)
{
lastStr[i-max_Index] = s[i];
count++;
}
lastStr[count] = 0;
return lastStr;
}
| true |
f2b625b0945b4e5c5e88ff0fb67c0a389bd07b72 | C++ | VillaJuan/VillalpandoJuan_40107 | /Hmwk/Assignment 2/Gaddis_8thEd_Ch3_Prob1_MPG/main.cpp | UTF-8 | 1,393 | 3.390625 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Juan Villalpando
* Created on January 12, 2016, 1:02 PM
* Purpose: Write a program that calculates a car’s gas mileage. The program should ask the user
to enter the number of gallons of gas the car can hold and the number of miles it can
be driven on a full tank. It should then display the number of miles that may be driven
per gallon of gas.
*/
//System Libraries Here
#include <iostream>
using namespace std;
//User Libraries Here
//Global Constants Only, No Global Variables
//Like PI, e, Gravity, or conversions
//Function Prototypes Here
//Program Execution Begins Here
int main(int argc, char** argv) {
//Declare all Variables Here
unsigned short numGall;
unsigned short numMile;
unsigned short mpg;
//Input or initialize values Here
cout<<"This Program determines the amount of miles"<<endl;
cout<<"that a vehicle can travel per gallon based on"<<endl;
cout<<"how many gallons of gas the vehicle can hold."<<endl<<endl;
cout<<"Please enter the number of gallons the vehicle can hold"<<endl;
cin>>numGall;
cout<<"Now enter the number of miles the vehicle can be driven on a full tank"<<endl;
cin>>numMile;
//Process/Calculations Here
mpg= numMile/numGall;
//Output Located Here
cout<<"This vehicle can drive at "<<mpg<<" Miles Per Gallon"<<endl;
//Exit
return 0;
}
| true |
44d3f05790b0ac1d69aeb428a652a45970a2e7f0 | C++ | kaustubh-pandey/Competitive-Programming | /CodeChef/SSEC-2/prime.cpp | UTF-8 | 1,656 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
#define xll __int128
#define fo(i,n) for(int i=0;i<n;i++)
#define rfo(i,n) for(int i=n-1;i>=0;i--)
#define Fo(i,q,n) for(int i=q;i<n;i++)
#define rFo(i,q,n) for(int i=n-1;i>=q;i--)
#define fO(i,n,k) for(int i=0;i<n;i+=k)
#define FO(i,q,n,k) for(int i=q;i<n;i+=k)
#define zero(a,n) memset(a,0,sizeof(a[0])*n)
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define endl "\n"
#define Endl "\n"
#define trace(x) cerr<<#x<<": "<<x<<" "<<endl;
using namespace std;
const int MOD=1000000007;
void print(){cout <<endl;}
template <typename T, typename... Types>
void print(T var1, Types... var2){cout << var1 << " " ;print(var2...) ;}
//ceil of a/b
template <typename T>
T fceil(T a,T b){return (T)(a+b-1)/b;}
template <typename T>
void printvec(vector<T> v){ for(int i=0;i<(int)v.size();i++){ cout<<v[i]<<" ";} cout<<endl;}
template <typename T>
void printarr(T a[],int n){ for(int i=0;i<n;i++){ cout<<a[i]<<" ";} cout<<endl;}
//const int N=2e5;
//int arr[N+1];
bool isPrime(int n){
if(n==0 || n==1){return false;}
if(n==2){return true;}
if(n%2==0){return false;}
for(int j=3;j*j<=n;j+=2){
if(n%j==0){return false;}
}
return true;
}
int main(){
int a,b;
cin>>a>>b;
int low = (a/2 * b/2);
int high = a*b;
vector<int> primes;
for(int i=a;i<=b;i++){
if(isPrime(i)){
primes.pb(i);
}
}
for(int i=0;i<(int)primes.size();i++){
for(int j=i+1;j<(int)primes.size();j++){
int val = primes[i]*primes[j];
if(val>=low && val<=high){
cout<<primes[i]<<","<<primes[j]<<endl;
}
}
}
return 0;
}
/*NOTE: Take MOD after sorting and not before sorting!*/
| true |
73defa2f1073ee276254c9800a37d32b67f286dc | C++ | thejesusbr/GPU-Color2Gray | /image_io.cpp | UTF-8 | 4,435 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <map>
#include "images.h"
//return variables for fscanf and fread to keep the compiler happy
static int ret = 0;
static size_t bytesRead = 0;
sven::rgb *readPPM(const char *filename, int *cols, int *rows, int * colors)
{
using sven::rgb;
char tag[40];
rgb *image;
FILE *fp;
int read, num[3], curchar;
if (filename != NULL && strlen(filename))
fp = fopen(filename, "rb");
else
fp = stdin;
if (fp)
{
ret = fscanf(fp, "%s\n", tag);
bool binary;
// Read the "magic number" at the beginning of the ppm
if (strncmp(tag, "P6", 40) == 0)
binary = true;
else if (strncmp(tag, "P3", 40) == 0)
binary = false;
else
throw std::runtime_error("not a ppm!");
// Read the rows, columns, and color depth output by cqcam
// need to read in three numbers and skip any lines that start with a #
read = 0;
while (read < 3)
{
curchar = fgetc(fp);
if ((char) curchar == '#')
{ // skip this line
while (fgetc(fp) != '\n')
/* do nothing */;
}
else
{
ungetc(curchar, fp);
ret = fscanf(fp, "%d", &(num[read]));
read++;
}
}
while (fgetc(fp) != '\n')
/* pass the last newline character */;
*cols = num[0];
*rows = num[1];
*colors = num[2];
if (*cols > 0 && *rows > 0)
{
image = new rgb[(*rows) * (*cols)];
if (image)
{
// Read the data
if (binary)
bytesRead = fread(image, sizeof(rgb), (*rows) * (*cols), fp);
else
{
for (int x = 0; x < *rows; x++)
for (int y = 0; y < *cols; y++)
{
int r, g, b;
ret = fscanf(fp, "%d %d %d", &r, &g, &b);
image[x + *rows * y] = rgb(r, g, b);
}
}
fclose(fp);
return image;
}
}
}
return (NULL);
} // end read_ppm
void ColorImage::load(const char * fname)
{
using sven::rgb;
if (data || dataYCrCb)
{
delete[] data;
// delete[] dataYCrCb;
}
int c;
rgb * colors = readPPM(fname, &w, &h, &c);
N = w * h;
printf("image loaded, w: %d, y: %d, c: %d.\n", w, h, c);
data = new amy_lab[N];
dataYCrCb = new amy_yCrCb[N];
int i;
for (i = 0; i < N; i++)
{
data[i] = amy_lab(colors[i]);
dataYCrCb[i] = amy_yCrCb(colors[i]);
}
delete[] colors;
}
void GrayImage::save(const char *fname) const
{
using sven::rgb;
rgb * rval = new rgb[N];
for (int i = 0; i < N; i++)
{
rval[i] = amy_lab(data[i], 0, 0).to_rgb();
}
//write out the grayscale image.
FILE *fp;
fp = fopen(fname, "wb");
if (fp)
{
fprintf(fp, "P6\n");
fprintf(fp, "%d %d\n%d\n", w, h, 255);
fwrite(rval, sizeof(rgb), N, fp);
}
fclose(fp);
delete[] rval;
}
void ColorImage::load_quant_data(const char *fname)
{
using sven::rgb;
int c;
int i;
rgb * colors = readPPM(fname, &w, &h, &c);
N = w * h;
printf("quantized image loaded, w: %d, y: %d, c: %d.\n", w, h, c);
qdata.clear();
using namespace std;
map<rgb, int> q;
map<rgb, int>::iterator r;
for (i = 0; i < N; i++)
{
r = q.find(colors[i]);
if (r == q.end())
q[colors[i]] = 1;
else
r->second++;
}
printf("quantized image appears to use %d colors.\n", (int)q.size());
qdata.resize(q.size());
for (i = 0, r = q.begin(); r != q.end(); r++, i++)
{
qdata[i] = amy_lab_int(amy_lab(r->first), r->second);
}
// data = new amy_lab[N];
// int i;
// for( i=0;i<N;i++) data[i]=amy_lab(colors[i]);
delete[] colors;
}
void ColorImage::save(const char* fname, bool type) const
{
using sven::rgb;
rgb * rval = new rgb[N];
if (!type)
{
for (int i = 0; i < N; i++)
{
rval[i] = amy_yCrCb(dataYCrCb[i].y, 0, 0).to_rgb();
}
}
else
{
for (int i = 0; i < N; i++)
{
rval[i] = amy_yCrCb(dataYCrCb[i].y, dataYCrCb[i].Cr, dataYCrCb[i].Cr).to_rgb();
}
}
//write out the grayscale image.
FILE *fp;
fp = fopen(fname, "wb");
if (fp)
{
fprintf(fp, "P6\n");
fprintf(fp, "%d %d\n%d\n", w, h, 255);
fwrite(rval, sizeof(rgb), N, fp);
}
fclose(fp);
delete[] rval;
}
void GrayImage::saveColor(const char *fname, const ColorImage &source) const
{
using sven::rgb;
rgb * rval = new rgb[N];
printf("Saving Color2Gray + Chrominance\n");
for (int i = 0; i < N; i++)
{
rval[i]
= amy_lab(data[i], ((source.data)[i]).a, ((source.data)[i]).b).to_rgb();
}
//write out the grayscale image.
FILE *fp;
fp = fopen(fname, "wb");
if (fp)
{
fprintf(fp, "P6\n");
fprintf(fp, "%d %d\n%d\n", w, h, 255);
fwrite(rval, sizeof(rgb), N, fp);
}
fclose(fp);
delete[] rval;
}
| true |
9b80356106019ba5bdc6cc4b4e1eb8b8406d5532 | C++ | natalielisha1/Reversi-c- | /Reversi/src/server/src/JoinCommand.cpp | UTF-8 | 1,188 | 2.828125 | 3 | [] | no_license | /***************************************
* Student Name: Ofek Segal and Natalie Elisha
* Student ID: 315638288, 209475458
* Exercise Name: Ex7
**************************************/
#include "JoinCommand.h"
using namespace std;
/***************************************
* Function Name: joinCommand (Constructor)
* The Input: a reference of a game set
* The Output: joinCommand instance
* The Function Operation: currently nothing
**************************************/
JoinCommand::JoinCommand(){
games = GameSet::getInstance();
}
/***************************************
* Function Name: ~joinCommand (Destructor)
* The Input: no input
* The Output: no ouput
* The Function Operation: currently nothing
**************************************/
JoinCommand::~JoinCommand() {
//Nothing right now
}
/***************************************
* Function Name: execute
* The Input: id socket of the sender and a vector
* of arguments
* The Output: no ouput
* The Function Operation: adding the sender (a client)
* to a match
**************************************/
CommandResult JoinCommand::execute(int sender, vector<string> args) {
return games->joinMatch(sender, args);
}
| true |
442b42b1ea295ad6f9dceb00cc3e4fdfdebbed19 | C++ | flowerfx/ColorLockPuzzle | /cocos2D/Lib/XFlatformCorePackage/WCP/src/WindowsCorePackage.Shared/SecureStorageManager/ISingleton.h | UTF-8 | 677 | 2.96875 | 3 | [] | no_license | #pragma once
namespace WCPToolkit
{
template<typename T>
class ISingleton
{
protected:
inline explicit ISingleton<T>(){}
inline ISingleton(const ISingleton&){}
inline ISingleton& operator=(const ISingleton&){}
virtual ~ISingleton(){}
public:
static void CreateInstance()
{
if (ms_pInstance == nullptr)
{
ms_pInstance = new T;
}
}
static T* GetInstance()
{
CreateInstance();
return ms_pInstance;
}
static void DestroyInstance()
{
if (ms_pInstance)
{
delete ms_pInstance;
ms_pInstance = nullptr;
}
}
protected:
static T* ms_pInstance;
};
template<typename T>
T* ISingleton<T>::ms_pInstance = nullptr;
}; | true |
d51ea578911adc375cf439cc1624927cd30f6805 | C++ | QuteSaltyFish/singleLinkList | /singleLinkList/main.cpp | UTF-8 | 4,773 | 3.65625 | 4 | [] | no_license | //
// main.cpp
// singleLinkList
//
// Created by Mingke Wang on 2018/9/30.
// Copyright © 2018年 Mingke Wang. All rights reserved.
//
#include <iostream>
#include <list>
using namespace std;
template <class elemType>
class sLinkList:public list<elemType>
{
template <class T> friend sLinkList<T> operator+(const sLinkList<T> &a, const sLinkList<T> &b); //把a和b相连成为c
private:
struct node
{
elemType data;
node *next;
node(const elemType &x, node *n=NULL)
{
data=x;next=n;;
}
node():next(NULL){}
~node(){};
};
node *head; //头指针
int currentLength; //表长
node *move(int i) const;//返回第i个节点的地址
public:
sLinkList<elemType>& operator=(const sLinkList<elemType> &obj);
sLinkList();
sLinkList(sLinkList<elemType>& obj);
~sLinkList()
{
clear();
delete head;
}
void clear();
int length() const {return currentLength;}
void insert(int i, const elemType &x);
void remove(int i);
int search(const elemType &x) const;
elemType visit(int i) const;
void traverse() const;
void erase(int x, int y);
void reverse();
};
template <class elemType>
sLinkList<elemType>& sLinkList<elemType>::operator=(const sLinkList<elemType> &obj)
{
if (this==&obj) return *this; //防止自己复制自己
this->clear();
for (int i=0; i<obj.currentLength; ++i)
{
this->insert(i, obj.visit(i));
}
return *this;
}
template <class T>
sLinkList<T> operator+(const sLinkList<T> &a, const sLinkList<T> &b)
{
sLinkList<T> c;
for (int i=0; i<a.currentLength; ++i)
c.insert(i, a.visit(i));
for (int i=0; i<b.currentLength; ++i)
c.insert(i + a.currentLength, b.visit(i));
return c;
}
template <class elemType>
sLinkList<elemType>::sLinkList(sLinkList<elemType> &obj)
{
head = new node;
currentLength = 0;
for (int i=0; i<obj.currentLength; ++i)
{
insert(i, obj.visit(i));
}
}
//单链表私有函数move的实现
template <class elemType>
typename sLinkList<elemType>::node *sLinkList<elemType>::move(int i) const
{
node *p = head;
while (i-->=0) p = p->next;
return p;
}
//单链表的构造函数
template <class elemType>
sLinkList<elemType>::sLinkList()
{
head = new node;
currentLength = 0;
}
//单链表类清空函数的实现
template <class elemType>
void sLinkList<elemType>::clear()
{
node *p = head->next, *q;
head->next=NULL;
while (p!=NULL)
{
q = p->next;
delete p;
p = q;
}
currentLength = 0;
}
//节点插入与删除函数的实现
template <class elemType>
void sLinkList<elemType>::insert(int i, const elemType &x) //首地址不存放data,所以后面的输出是从第二位开始输出
{
node *pos;
pos = move(i-1);
pos->next = new node(x, pos->next);
++currentLength;
}
template <class elemType>
void sLinkList<elemType>::remove(int i)
{
node *pos, *delp;
pos = move(i-1);
delp = pos->next;
pos->next = delp->next;
delete delp;
--currentLength;
}
//单链表中search, visit和traverse的实现
template <class elemType>
int sLinkList<elemType>::search(const elemType &x) const
{
node *p = head->next;
int i = 0;
while (p!=NULL && p->data != x)
{
p = p->next;
++i;
}
if (p==NULL) return -1; //不存在该元素
else return i;
}
template <class elemType>
elemType sLinkList<elemType>::visit(int i) const
{
return move(i)->data;
}
template <class elemType>
void sLinkList<elemType>::traverse() const
{
node *p = head->next;
cout<<endl;
while (p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
template <class elemType>
void sLinkList<elemType>::erase(int x, int y)
{
node *p=head->next;
int i=0;
while (p!=NULL)
{
if (p->data>=x && p->data<=y)
remove(i);
else i++;
p = p->next;
}
}
template <class elemType>
void sLinkList<elemType>::reverse()
{
elemType *storage = new elemType[currentLength];
for (int i=0 ; i<currentLength; ++i)
{
storage[i] = visit(i);
}
for (int i=0; i<currentLength; ++i)
{
move(i)->data = storage[currentLength-i-1];
}
delete[] storage;
}
int main() {
std::cout << "Hello, World!" << std::endl;
sLinkList<int> list;
for (int i=0; i<10; ++i)
list.insert(i, i+1);
list.traverse();
list.erase(2, 5);
list.traverse();
list.reverse();
list.traverse();
sLinkList<int> b(list);
b.traverse();
b= list + list;
b.traverse();
return 0;
}
| true |
21fe5f68102b22a9b2972448a58d0f32b28a88d1 | C++ | Susuo/rtilabs | /files/asobiba/filer/SolvablePathWeb.cpp | SHIFT_JIS | 2,083 | 3.0625 | 3 | [] | no_license | // SolvablePathWeb.cpp: SolvablePathWeb NX̃Cve[V
//
//////////////////////////////////////////////////////////////////////
#include "comm.h"
#include "SolvablePathWeb.h"
#include "SolvablePathSpecialFolder.h"
#include "MultiString.h"
//////////////////////////////////////////////////////////////////////
// \z/
//////////////////////////////////////////////////////////////////////
//̃pXĂ݂
bool SolvablePathWeb::DoSolvable(string inPath)
{
//擪 http:// ł邱
if ( inPath.substr(0,7) != "http://" && inPath.substr(0,7) != "https://" )
{
//hCۂOłΕ⊮....
if (inPath.size() <= 3) return false; //ȒẐ͂Ȃ. a.to Ẑ?
if (inPath[1] == ':') return false; //hCu^[?
if (inPath.find("://") != -1) return false; // :// ĂƂ͂Ȃʂ̃vgR?
if (inPath.substr(0,2) == "\\\\") return false; //ꂾ狤L.
if (inPath.find(".") == -1) return false; // . ȂhCȂĂȂł傤.
//܂ł炱hCƂĔF.
inPath = string("http://") + inPath;
}
this->setPath(inPath);
//OK
return true;
}
//fBNgオ
string SolvablePathWeb::UpDirectory() const
{
const string path = getPath() ;
int protcolSkip = path.find("://"); //http:// XLbv.
if (protcolSkip == -1 ) protcolSkip = 0; //oO?
else protcolSkip += sizeof("://");
const int lastpos = MultiString::getLastDirectoryPos( path.substr( protcolSkip ), '/');
if (lastpos == 0)
{ //gbv炵̂ŁAfXNgbvɖ߂.
return SolvablePathSpecialFolder::getSpecialFolder(CSIDL_DESKTOP);
}
return path.substr( 0 , protcolSkip + lastpos + 1) ;
}
void SolvablePathWeb::Test()
{
SolvablePathWeb sp;
//pX邩.
ASSERT( sp.DoSolvable("http://www.yahoo.co.jp") );
ASSERT( sp.getPath() == "http://www.yahoo.co.jp" );
}
| true |
987867f38160e06e2dd8067cc864a5d9fecc04fc | C++ | LuckyDmitry/devtools-course-practice | /modules/polygon_area/test/test_polygon.cpp | UTF-8 | 3,152 | 3.15625 | 3 | [
"CC-BY-4.0"
] | permissive | // Copyright 2020 Loogin Mikhail
#include <gtest/gtest.h>
#include <utility>
#include <vector>
#include "include/polygon_engine.h"
using Point = polygon_engine::Point;
using Polygon = polygon_engine::Polygon;
/*
1. throw_in_isConnectedness_when_tops_count_less_3
2. throw_in_getPerimeter_when_tops_count_less_3
3. throw_in_getArea_when_tops_count_less_3
4. check_isConnectedness_when_is_intersect
5. throw_when_is_intersect
6. check_isConnectedness_when_is_not_intersect
7. check_perimeter_for_from_3_to_100_tops_polygon
8. check_area_for_from_3_to_100_tops_polygon
*/
TEST(polygon, throw_in_isConnectedness_when_tops_count_less_3) {
// Arrange
std::vector<Point> points = {{0, 0}, {1, 0}, {0, 1}};
// Assert & Act
while (points.size() > 0) {
points.pop_back();
auto p = Polygon(points);
ASSERT_ANY_THROW(p.isConnectedness());
}
}
TEST(polygon, throw_in_getPerimeter_when_tops_count_less_3) {
// Arrange
std::vector<Point> points = { {0, 0}, {1, 0}, {0, 1} };
// Assert & Act
while (points.size() > 0) {
points.pop_back();
auto p = Polygon(points);
ASSERT_ANY_THROW(p.getPerimeter());
}
}
TEST(polygon, throw_in_getArea_when_tops_count_less_3) {
// Arrange
std::vector<Point> points = { {0, 0}, {1, 0}, {0, 1} };
// Assert & Act
while (points.size() > 0) {
points.pop_back();
auto p = Polygon(points);
ASSERT_ANY_THROW(p.getArea());
}
}
TEST(polygon, check_connectedness_when_is_intersect) {
// Arrange
std::vector<Point> points = { {0, 0}, {1, 1}, {1, 0}, {0, 1} };
auto p = Polygon(points);
// Assert & Act
EXPECT_FALSE(p.isConnectedness());
}
TEST(polygon, throw_when_is_intersect) {
// Arrange
std::vector<Point> points = { {0, 0}, {1, 1}, {1, 0}, {0, 1} };
auto p = Polygon(points);
// Assert & Act
ASSERT_ANY_THROW(p.getPerimeter());
ASSERT_ANY_THROW(p.getArea());
}
TEST(polygon, check_isConnectedness_when_is_not_intersect) {
// Arrange
std::vector<Point> points = { {0, 0}, {1, 0}, {1, 1}, {0, 1} };
auto p = Polygon(points);
// Assert & Act
EXPECT_TRUE(p.isConnectedness());
}
TEST(polygon, check_perimeter_for_from_3_to_100_tops_polygon) {
// Arrange
std::vector<Point> points = { {0, 0}, {0, 1}, {1, 1} };
// Assert & Act
for (auto h = 1.; points.size() < 100; h++) {
points.push_back({h, 0});
auto p = Polygon(points);
EXPECT_EQ(4 * h, p.getPerimeter());
points.pop_back();
points.push_back({h, points[points.size() - 1].y + 1});
points.push_back({ h + 1, points[points.size() - 1].y});
}
}
TEST(polygon, check_area_for_from_3_to_100_tops_polygon) {
// Arrange
std::vector<Point> points = { {0, 0}, {0, 1}, {1, 2} };
// Assert & Act
for (auto h = 1.; points.size() < 100; h++) {
points.push_back({ h, 0 });
auto p = Polygon(points);
EXPECT_EQ(1.5 * h, p.getArea());
points.pop_back();
points.push_back({ h + 1, points[points.size() - 1].y == 1.
? 2. : 1.});
}
}
| true |
25aa08d5e96c124e5a8f5af6aff24bd6a58e95f6 | C++ | karlnapf/shogun | /src/shogun/lib/SGStringList.h | UTF-8 | 2,105 | 2.84375 | 3 | [
"BSD-3-Clause",
"DOC",
"GPL-3.0-only"
] | permissive | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Soeren Sonnenburg, Sergey Lisitsyn, Thoralf Klein, Yuyu Zhang,
* Bjoern Esser
*/
#ifndef __SGSTRINGLIST_H__
#define __SGSTRINGLIST_H__
#include <shogun/lib/config.h>
#include <shogun/lib/common.h>
#include <shogun/lib/SGReferencedData.h>
#include <shogun/lib/SGString.h>
namespace shogun
{
class CFile;
template <class T> class SGString;
/** @brief template class SGStringList */
template <class T> class SGStringList : public SGReferencedData
{
public:
/** default constructor */
SGStringList();
/** constructor for setting params */
SGStringList(SGString<T>* s, index_t num_s, index_t max_length,
bool ref_counting=true);
/** constructor to create new string list in memory */
SGStringList(index_t num_s, index_t max_length, bool ref_counting=true);
/** copy constructor */
SGStringList(const SGStringList &orig);
/** destructor */
virtual ~SGStringList();
/**
* get the string list (no copying is done here)
*
* @return the refcount increased string list
*/
inline SGStringList<T> get()
{
return *this;
}
/** load strings from file
*
* @param loader File object via which to load data
*/
void load(CFile* loader);
/** save strings to file
*
* @param saver File object via which to save data
*/
void save(CFile* saver);
/** clone string list
*
* @return a deep copy of current string list
*/
SGStringList<T> clone() const;
/** Equals method
* @param other SGStringList to compare with
* @return false iff the number of strings, the maximum string length or
* any of the string items are different, true otherwise
*/
bool equals(const SGStringList<T>& other) const;
protected:
/** copy data */
virtual void copy_data(const SGReferencedData &orig);
/** init data */
virtual void init_data();
/** free data */
void free_data();
public:
/** number of strings */
index_t num_strings;
/** length of longest string */
index_t max_string_length;
/** this contains the array of features */
SGString<T>* strings;
};
}
#endif // __SGSTRINGLIST_H__
| true |
460fc42b8ee1cfcab2c893aadfb591794db853d4 | C++ | danielmevi/DMV_References | /scheduler_one_thread_experiment/Experiment_PImpl.cpp | UTF-8 | 856 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <functional>
bool foo1(int, double){
std::cout << __PRETTY_FUNCTION__ << '\n';
return true;
}
bool foo2(int, int){
std::cout << __PRETTY_FUNCTION__ << '\n';
return false;
}
template <class T>
struct Event {
Event(T callback) : callback_{reinterpret_cast<void*>(callback)} {}
bool operator() () {
using callback_t = bool(*)(int, double);
callback_t callback = callback_t(callback_);
callback(1,1.2);
auto result = reinterpret_cast<T*>(callback_)(2,2.2);
//auto callback2 = getCallback();
return true;
}
void* callback_;
};
template <class T>
inline Event<T> CreateEvent(T& callback) {
return Event<T>{callback};
}
int main() {
auto event{CreateEvent(foo1)};
event();
auto event2{CreateEvent(foo2)};
event2();
} | true |
af0718013e04fd1547aadbb46322f03118157328 | C++ | SOPT-ALPPO/ALPPO-4z7l | /Implementation/BOJ 3190.cpp | UTF-8 | 1,134 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, k, L;
int board[101][101] = { 0, };
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
struct pos{
int x, y;
};
int main()
{
cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
cin >> n >> k;
int a, b;
for (int i = 0; i < k; i++) {
cin >> a >> b;
board[a][b] = 2;
}
cin >> L;
char ch;
vector<pair<int, char>> movements;
for (int i = 0; i < L; i++) {
cin >> a >> ch;
movements.push_back({ a,ch });
}
int time = 0;
int nx = 1, ny = 1, dir = 0;;
deque<pos> dQ;
dQ.push_front({ nx,ny });
board[nx][ny] = 1;
int m_ind = 0;
while (true) {
time++;
nx = dQ.front().x + dx[dir];
ny = dQ.front().y + dy[dir];
if (nx<1 || nx>n || ny<1 || ny>n || board[nx][ny] == 1) break;
if (board[nx][ny] == 0) {
board[dQ.back().x][dQ.back().y] = 0;
dQ.pop_back();
}
dQ.push_front({ nx,ny });
board[nx][ny] = 1;
if (m_ind<L && movements[m_ind].first == time) {
if (movements[m_ind].second == 'L') dir = (dir + 3) % 4;
else dir = (dir + 1) % 4;
m_ind++;
}
}
cout << time;
return 0;
}
| true |
9e41be90b13158feb49d9fd76b65b299ecd5f77e | C++ | ya-ming/boost-asio | /tutorial/13-daytime-async-TCP-UDP-server.cpp | UTF-8 | 7,386 | 3.0625 | 3 | [] | no_license | #include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>
using boost::asio::ip::tcp;
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std;
time_t now = time(0);
return ctime(&now);
}
/*** tcp server ***/
/* We will use shared_ptr and enable_shared_from_this because we want to
keep the tcp_connection object alive as long as there is an operation that refers to it. */
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_context &io_context)
{
return pointer(new tcp_connection(io_context));
}
tcp::socket &socket()
{
return socket_;
}
/* In the function start(), we call boost::asio::async_write() to serve the data to the client.
Note that we are using boost::asio::async_write(), rather than ip::tcp::socket::async_write_some(),
to ensure that the entire block of data is sent. */
void start()
{
/* The data to be sent is stored in the class member message_ as we need to keep the data valid until the asynchronous operation is complete. */
message_ = make_daytime_string();
/* When initiating the asynchronous operation, and if using boost::bind(),
you must specify only the arguments that match the handler's parameter list.
In this program, both of the argument placeholders (boost::asio::placeholders::error and boost::asio::placeholders::bytes_transferred)
could potentially have been removed, since they are not being used in handle_write(). */
boost::asio::async_write(
socket_,
boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
tcp_connection(boost::asio::io_context &io_context)
: socket_(io_context)
{
}
/* Any further actions for this client connection are now the responsibility of handle_write(). */
void handle_write(const boost::system::error_code & /*error*/,
size_t /*bytes_transferred*/)
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
/* The constructor initialises an acceptor to listen on TCP port 13. */
tcp_server(boost::asio::io_context &io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
/* The function start_accept() creates a socket and initiates an asynchronous accept operation to wait for a new connection. */
void start_accept()
{
tcp_connection::pointer new_connection = tcp_connection::create(io_context_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(
&tcp_server::handle_accept,
this,
new_connection,
boost::asio::placeholders::error));
}
/* The function handle_accept() is called when the asynchronous accept operation initiated by start_accept() finishes.
It services the client request, and then calls start_accept() to initiate the next accept operation. */
void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code &error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
boost::asio::io_context &io_context_;
tcp::acceptor acceptor_;
};
/*** end of tcp server ***/
/*** udp server ***/
class udp_server
{
public:
/* The constructor initialises a socket to listen on UDP port 13. */
udp_server(boost::asio::io_context &io_context)
: socket_(io_context, udp::endpoint(udp::v4(), 13))
{
start_service();
}
private:
void start_service()
{
/* The function ip::udp::socket::async_receive_from() will cause the application to listen in the background for a new request.
When such a request is received, the io_context object will invoke the handle_receive() function with two arguments:
a value of type boost::system::error_code indicating whether the operation succeeded or failed,
and a size_t value bytes_transferred specifying the number of bytes received. */
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/* The function handle_receive() will service the client request. */
void handle_receive(const boost::system::error_code &error, std::size_t /*bytes_transferred*/)
{
/* The error parameter contains the result of the asynchronous operation.
Since we only provide the 1-byte recv_buffer_ to contain the client's request,
the io_context object would return an error if the client sent anything larger.
We can ignore such an error if it comes up. */
if (!error)
{
/* Determine what we are going to send. */
boost::shared_ptr<std::string> message(new std::string(make_daytime_string()));
/* We now call ip::udp::socket::async_send_to() to serve the data to the client. */
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
/* When initiating the asynchronous operation, and if using boost::bind(),
you must specify only the arguments that match the handler's parameter list.
In this program, both of the argument placeholders
(boost::asio::placeholders::error and boost::asio::placeholders::bytes_transferred)
could potentially have been removed. */
boost::bind(&udp_server::handle_send, this, message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
/* Start listening for the next client request. */
start_service();
/* Any further actions for this client request are now the responsibility of handle_send(). */
}
}
/* The function handle_send() is invoked after the service request has been completed. */
void handle_send(boost::shared_ptr<std::string> /*message*/,
const boost::system::error_code & /*error*/,
std::size_t /*bytes_transferred*/
)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
/*** end of udp server ***/
int main()
{
try
{
/* Create a server object to accept incoming client requests, and run the io_context object. */
boost::asio::io_context io_context;
tcp_server server1(io_context);
udp_server server2(io_context);
io_context.run();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
} | true |
c61b3564a736c9ffcb02872cb2cbf8b983c98ec4 | C++ | SoMa-Project/vision | /thirdparty/GeometricTools/WildMagic5/LibCore/DataTypes/Wm5Tuple.h | UTF-8 | 1,601 | 2.59375 | 3 | [
"BSD-2-Clause-Views"
] | permissive | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.3 (2012/03/09)
#ifndef WM5TUPLE_H
#define WM5TUPLE_H
#include "Wm5CoreLIB.h"
// The class TYPE is either native data or is class data that has the
// following member functions:
// TYPE::TYPE ()
// TYPE::TYPE (const TYPE&);
// TYPE& TYPE::operator= (const TYPE&)
namespace Wm5
{
template <int DIMENSION, typename TYPE>
class Tuple
{
public:
// Construction and destruction. The default constructor does not
// initialize the tuple elements for native elements. The tuple elements
// are initialized for class data whenever TYPE initializes during its
// default construction.
Tuple ();
Tuple (const Tuple& tuple);
~Tuple ();
// Coordinate access.
inline operator const TYPE* () const;
inline operator TYPE* ();
inline const TYPE& operator[] (int i) const;
inline TYPE& operator[] (int i);
// Assignment.
Tuple& operator= (const Tuple& tuple);
// Comparison.
bool operator== (const Tuple& tuple) const;
bool operator!= (const Tuple& tuple) const;
bool operator< (const Tuple& tuple) const;
bool operator<= (const Tuple& tuple) const;
bool operator> (const Tuple& tuple) const;
bool operator>= (const Tuple& tuple) const;
protected:
TYPE mTuple[DIMENSION];
};
#include "Wm5Tuple.inl"
}
#endif
| true |
8b0cad4b70f42f01e03a76809af965b7487abf10 | C++ | simply-software/Aquanaut | /Aqua/observation.h | UTF-8 | 1,437 | 3.03125 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <string>
#include "convert_from_string.h"
#include "datetime.h"
#include "parse_csv_record.h"
namespace aqua {
struct observation final {
using temperature_t = double;
observation() = default;
observation(const observation&) = default;
observation(observation&&) = default;
observation& operator=(observation rhs) noexcept {
this->swap(rhs);
return *this;
}
observation& operator=(observation&& rhs) = default;
void swap(observation& that) noexcept {
using std::swap;
swap(m_weather_station, that.m_weather_station);
swap(m_time_of_observation, that.m_time_of_observation);
swap(m_air_temperature, that.m_air_temperature);
}
void populate_from(parse_csv_record& csv) {
convert_from_string(m_weather_station, csv(0));
convert_from_string(m_time_of_observation, csv(1));
convert_from_string(m_air_temperature, csv(2));
}
public:
std::string m_weather_station;
datetime_t m_time_of_observation;
temperature_t m_air_temperature;
}; // struct observation
inline void swap(observation& first, observation& second) noexcept {
first.swap(second);
}
} // namespace aqua
| true |
dbd1a5e9d9d833479eae57278b649f0a85b0c2d3 | C++ | lighingyang/OS | /进程管理.cpp | UTF-8 | 6,597 | 2.921875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
/*
描述:可允许进程最大数量
*/
const int maxn = 10010;
/*
描述:实际到来进程数量
*/
int n;
/*
描述:进程的声明
*/
struct process;
/*
描述:进程PCB的声明
*/
struct PCB;
/*
功能:就绪队列
*/
queue<int> q1;
/*
功能:阻塞队列
*/
queue<int> q2;
/*
功能:进程PCB
*/
struct PCB{
int id;//进程id
int cls;//进程等级
int come;//进程到来时间
int alltime;//进程所需时间
int cputime; //已用cpu时间
int startblock;//一个时间片的时间
int starttime;//从阻塞状态转为就绪状态的时间
int blocktime;//已阻塞的时间
char state;//进程状态
struct precess *Next;
};
/*
功能:进程
*/
struct process{
int waittime;
int runtime;
PCB pcb;
process(){
runtime = 0;
}
setdata(int i,int cl,int cm,int ati,int sb,int st){
pcb.id = i;
pcb.cls = cl;
pcb.come = cm;
pcb.alltime = ati;
pcb.cputime = 0;
pcb.startblock = sb;
pcb.starttime = st;
pcb.blocktime = 0;
pcb.state = 'W';
runtime = 0;
waittime = 0;
}
};
process p[maxn];
/*
功能:查看此刻阻塞队列中的进程
*/
void find_block(){
printf("阻塞队列中的进程为:");
for(int i=0;i<n;i++){
if(p[i].pcb.state == 'B') printf(" 进程%d",p[i].pcb.id);
}
printf("\n");
}
/*
功能:查看此刻就绪队列中的进程
*/
void find_ready(){
printf("就绪队列中的进程为:");
for(int i=0;i<n;i++){
if(p[i].pcb.state == 'R') printf(" 进程%d",p[i].pcb.id);
}
printf("\n");
}
/*
功能:检查当前时刻有没有到来的进程
*/
void solve_ready(int now_time){
for(int i=0;i<n;i++){
if(now_time == p[i].pcb.come){
q1.push(i);
p[i].pcb.state = 'R';
printf("进程%d来到就绪队列\n",p[i].pcb.id);
}
}
return ;
}
/*
功能:阻塞队列更新
*/
void updata_block(){
/*
名称:q3
功能:阻塞临时队列
*/
queue<int> q3;
while(!q2.empty()){
int now = q2.front();
q2.pop();
p[now].pcb.blocktime ++;
if(p[now].pcb.blocktime == p[now].pcb.starttime){
q1.push(now);
p[now].pcb.state = 'R';
p[now].pcb.blocktime = 0;
printf("进程%d从阻塞队列进入就绪队列\n",p[now].pcb.id);
}
else{
q3.push(now);
}
}
while(!q3.empty()){
int now = q3.front();
q3.pop();
q2.push(now);
}
return ;
}
/*
功能:寻找优先队列中优先级最大的进程
*/
int find_maxcls(){
int mmmax = 0;
int idx = -1;
for(int i=0;i<n;i++){
if(p[i].pcb.state == 'R'&&p[i].pcb.cls>mmmax){
mmmax = p[i].pcb.cls;
idx = i;
}
}
return idx;
}
/*
功能:就绪队列更新
*/
void updata_ready(int pid){
/*
名称:q4
功能:就绪临时队列
*/
queue<int> q4;
while(!q1.empty()){
int now = q1.front();
q1.pop();
if(p[now].pcb.id == pid){
continue;
}
else{
q4.push(now);
}
}
while(!q4.empty()){
int now = q4.front();
q4.pop();
q1.push(now);
}
return ;
}
/*
功能:手动输入进程
描述: cl: cls
cm: come
ati: alltime
sb: startblock
st: starttime
*/
void input(){
scanf("%d",&n);
int i=0;
int cl;
int cm,ati,sb,st;
scanf("%d %d %d %d %d",&cl,&cm,&ati,&sb,&st);
//printf("%d %.2lf %.2lf %.2lf %.2lf\n",cl,cm,at,sb,st);
p[0].setdata(0+1,cl,cm,ati,sb,st);
for(++i;i<n;++i){
scanf("%d %d %d %d %d",&cl,&cm,&ati,&sb,&st);
//printf("%d %.2lf %.2lf %.2lf %.2lf\n",cl,cm,at,sb,st);
p[i].setdata(i+1,cl,cm,ati,sb,st);
}
return ;
}
/*
功能:更新就绪队列中的进程的cls
*/
void updata_rdycls(int pid){
for(int i=0;i<n;i++){
if(p[i].pcb.state == 'R'){
p[i].waittime++;
if(p[i].waittime%p[i].pcb.startblock==0){
p[i].pcb.cls++;
}
}
}
return ;
}
/*
功能: sort排序方法
描述:先按照时间到来的顺序进行升序排序,再按照进程的优先级升序排序
*/
bool cmp(process a,process b){
if(a.pcb.come!=b.pcb.come) return a.pcb.come<b.pcb.come;
return a.pcb.cls>b.pcb.cls;
}
/*
功能:实际情况处理进程
*/
void solve(){
int num = 0;
int now_time = 0;
while(num<n){
printf("当前时刻:%d\n",now_time);
solve_ready(now_time);
find_ready();
find_block();
/*
当时如果没有进程在就绪队列中就跳过
*/
//cout<<"q1 :"<<q1.size()<<endl;
//printf("11111 %d\n",q1.front());
if(q1.empty()){
now_time++;
updata_block();
continue;
}
int now = find_maxcls();
if(now == -1) {
now_time++;
updata_block();
continue;
}
p[now].pcb.state = 'N';//运行
printf("进程%d开始运行\n",p[now].pcb.id);
int ttime = min(p[now].pcb.alltime - p[now].pcb.cputime,p[now].pcb.startblock);
int ttt = ttime;
while(ttime){
p[now].runtime++;
p[now].pcb.cputime++;
ttime--;
now_time++;
printf("当前时刻:%d\n",now_time);
updata_block();
solve_ready(now_time);
updata_rdycls(p[now].pcb.id);
printf("当前时刻:%d,进程%d正在运行\n",now_time,p[now].pcb.id);
find_ready();
find_block();
}
printf("进程%d运行了%d时间,进程结束\n",p[now].pcb.id,ttt);
if(p[now].pcb.cputime == p[now].pcb.alltime){
num++;
p[now].pcb.state = 'F';
printf("进程%d在%d时刻完成\n",p[now].pcb.id,now_time);
updata_ready(p[now].pcb.id);
continue;
}
if(p[now].runtime == p[now].pcb.startblock){
q1.pop();
q2.push(now);
p[now].pcb.state = 'B';
p[now].pcb.cls -= 3;
printf("进程%d进入阻塞队列\n",p[now].pcb.id);
updata_ready(p[now].pcb.id);
p[now].runtime = 0;
continue;
}
}
printf("运行总时间为:%d\n",now_time);
printf("已完成进程%d\n",num);
return ;
}
/*
名称:主函数
*/
int main(){
freopen("1.txt","r",stdin);
input();
sort(p,p+n,cmp);
for(int i=0;i<n;i++){
printf("%d %d %d %d %d %d\n",p[i].pcb.id,p[i].pcb.cls,p[i].pcb.come,p[i].pcb.alltime,p[i].pcb.startblock,p[i].pcb.starttime);
}
solve();
return 0;
}
| true |
821dfcd18e6f915084b2090d58de0c78f0c355b0 | C++ | SeanCST/Algorithm_Problems | /LeetCode/069_x的平方根.cpp | UTF-8 | 850 | 3.40625 | 3 | [] | no_license |
class Solution {
public:
int mySqrt(int x) {
if(x <= 1) {
return x;
}
int min = 0, max = x;
while(max > min + 1) {
int m = (max + min) / 2;
if(x / m < m) {
max = m;
} else {
min = m;
}
}
return min;
}
};
class Solution {
public:
int mySqrt(int x) {
if(x <= 1) {
return x;
}
int64_t r = x;
while(r > x / r) {
r = (r + x / r) / 2;
}
return r;
}
};
class Solution {
public:
int mySqrt(int x) {
int i = 1;
while(i < x){
if ((i * i <= x) && ((i + 1) * (i + 1) > x)) {
return i;
}
i++;
}
return i;
}
}; | true |
43ae528a4a938f54ab17754024225423a0974fab | C++ | Tonyvitamin/Algorithm_HW3 | /algo_hw3.hpp | UTF-8 | 1,795 | 3.25 | 3 | [] | no_license | // change this to your id
static const char* student_id = "0416001";
// do not edit prototype
void LCS(int *, int*, int*);
// X,Y are input strings, C is answer string
//
// data structure :
// length of array X is m+1, length of array Y is n+1, length of array C is m+n
// X[0] = m+1, Y[0] = n+1,
// all element of C are "-1"
// other datas are in [0,255] means the symble in ASCII or ANSI table
// you only allow declare a table with size (m+1)*(n+1)
//
// do your homework here
//
void print_lcs_improved(int ** c, int * ans, int * x, int * y, int i, int j, int length)
{
if (i == 0 || j == 0)
return;
else if (x[i] == y[j])
{
ans[length] = x[i];
print_lcs_improved(c, ans, x, y, i - 1, j - 1, length - 1);
return;
}
else if (c[i][j - 1] > c[i - 1][j])
{
print_lcs_improved(c, ans, x, y, i, j - 1, length);
return;
}
else
{
print_lcs_improved(c, ans, x, y, i - 1, j, length);
}
return;
}
void LCS(int* X, int* Y, int* C)
{
int x_size = X[0];
int y_size = Y[0];
//initiate table value to 0
int **c_table = new int *[x_size];
for (int i = 0; i < (x_size); i++)
c_table[i] = new int[y_size];
for (int i = 0; i < x_size; i++)
c_table[i][0] = 0;
for (int j = 1; j < y_size; j++)
c_table[0][j] = 0;
//In O(m*n) way
for (int i = 1; i < x_size; i++)
for (int j = 1; j < y_size; j++)
{
if (X[i] == Y[j])
{
c_table[i][j] = c_table[i - 1][j - 1] + 1;
}
else if (c_table[i][j - 1] > c_table[i - 1][j])
{
c_table[i][j] = c_table[i][j - 1];
}
else
{
c_table[i][j] = c_table[i - 1][j];
}
}
int k_length = c_table[x_size - 1][y_size - 1];
print_lcs_improved(c_table, C, X, Y, x_size - 1, y_size - 1, k_length - 1);
delete c_table;
} | true |
925f678eb31c07be8cfc56970b49016a54b5c3dd | C++ | orestescm76/IGVProyecto20 | /src/igvFuenteLuz.cpp | ISO-8859-3 | 3,651 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "igvFuenteLuz.h"
// Metodos constructores
igvFuenteLuz::igvFuenteLuz()
{
}
igvFuenteLuz::igvFuenteLuz(const unsigned int _idLuz,
const igvPunto3D & _posicion,
const igvColor & cAmb, const igvColor & cDif, const igvColor & cEsp,
const double a0, const double a1, const double a2)
{
idLuz = _idLuz;
posicion = _posicion;
colorAmbiente = cAmb;
colorDifuso = cDif;
colorEspecular = cEsp;
aten_a0 = a0;
aten_a1 = a1;
aten_a2 = a2;
// valores por defecto cuando la luz no es un foco
direccion_foco = igvPunto3D(0,0,0);
angulo_foco = 180; // de esta manera la luz se convierte en puntual
exponente_foco = 0;
encendida = true;
}
igvFuenteLuz::igvFuenteLuz(const unsigned int _idLuz,
const igvPunto3D & _posicion,
const igvColor& cAmb, const igvColor& cDif, const igvColor& cEsp,
const double a0, const double a1, const double a2,
const igvPunto3D& dir_foco, const double ang_foco, const double exp_foco)
{
idLuz = _idLuz;
posicion = _posicion;
colorAmbiente = cAmb;
colorDifuso = cDif;
colorEspecular = cEsp;
aten_a0 = a0;
aten_a1 = a1;
aten_a2 = a2;
direccion_foco = dir_foco;
angulo_foco = ang_foco;
exponente_foco = exp_foco;
encendida = true;
}
// Metodos publicos ----------------------------------------
igvPunto3D& igvFuenteLuz::getPosicion(void)
{
return posicion;
}
void igvFuenteLuz::setPosicion(igvPunto3D pos)
{
posicion = pos;
}
void igvFuenteLuz::set(const igvColor & cAmb, const igvColor & cDif, const igvColor & cEsp)
{
colorAmbiente = cAmb;
colorDifuso = cDif;
colorEspecular = cEsp;
}
void igvFuenteLuz::setAmbiental(const igvColor & cAmb)
{
colorAmbiente = cAmb;
}
void igvFuenteLuz::setDifuso(const igvColor & cDif)
{
colorDifuso = cDif;
}
void igvFuenteLuz::setEspecular(const igvColor & cEsp)
{
colorEspecular = cEsp;
}
igvColor & igvFuenteLuz::getAmbiental(void)
{
return colorAmbiente;
}
igvColor & igvFuenteLuz::getDifuso(void) {
return colorDifuso;
}
igvColor & igvFuenteLuz::getEspecular(void) {
return colorEspecular;
}
void igvFuenteLuz::setAtenuacion(double a0, double a1, double a2) {
aten_a0 = a0;
aten_a1 = a1;
aten_a2 = a2;
}
void igvFuenteLuz::getAtenuacion(double & a0, double & a1, double & a2) {
a0 = aten_a0;
a1 = aten_a1;
a2 = aten_a2;
}
void igvFuenteLuz::encender(void) {
encendida = true;
}
void igvFuenteLuz::apagar(void) {
encendida = false;
}
unsigned int igvFuenteLuz::esta_encendida(void) {
return encendida;
}
void igvFuenteLuz::aplicar(void) {
// APARTADO A
// si la luz est encendida
if (encendida)
{
// activar la luz
glEnable(idLuz);
// establecer la posicin de la luz
glLightfv(idLuz, GL_POSITION, posicion.cloneToFloatArray());
// establecer los colores ambiental, difuso y especular
glLightfv(idLuz, GL_AMBIENT, colorAmbiente.cloneToFloatArray());
glLightfv(idLuz, GL_DIFFUSE, colorDifuso.cloneToFloatArray());
glLightfv(idLuz, GL_SPECULAR, colorEspecular.cloneToFloatArray());
// establecer la atenuacin radial
glLightf(idLuz, GL_CONSTANT_ATTENUATION, aten_a0);
glLightf(idLuz, GL_LINEAR_ATTENUATION, aten_a1);
glLightf(idLuz, GL_QUADRATIC_ATTENUATION, aten_a2);
// establecer la atenuacin angular y la direccin del foco
glLightfv(idLuz, GL_SPOT_DIRECTION, direccion_foco.cloneToFloatArray());
glLightf(idLuz, GL_SPOT_EXPONENT, exponente_foco);
glLightf(idLuz, GL_SPOT_CUTOFF, angulo_foco);
}
// si la luz est apagada
// desactivar la luz
else
glDisable(idLuz);
}
| true |
5635ff7e955258254fd3eb026a5c3797dec63afd | C++ | trustee-wallet/djinni-react-native | /support-lib/cpp/JavascriptObjectImpl.hpp | UTF-8 | 1,155 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | #include "JavascriptObject.hpp"
#include "JavascriptType.hpp"
class JavascriptObjectImpl : public JavascriptObject {
public:
JavascriptObjectImpl(const JavascriptObjectImpl& other);
JavascriptObjectImpl(std::nullptr_t);
JavascriptObjectImpl(bool value);
JavascriptObjectImpl(double value);
JavascriptObjectImpl(int32_t value);
JavascriptObjectImpl(const std::string& value);
JavascriptObjectImpl(const std::shared_ptr<JavascriptArray>& value);
JavascriptObjectImpl(const std::shared_ptr<JavascriptMap>& value);
~JavascriptObjectImpl();
JavascriptType getType() override;
bool isNull() override;
bool asBoolean() override;
double asDouble() override;
int32_t asInt() override;
std::string asString() override;
std::shared_ptr<JavascriptArray> asArray() override;
std::shared_ptr<JavascriptMap> asMap() override;
private:
union U {
U() {}
~U() {}
bool mBool;
double mDouble;
std::string mString;
std::shared_ptr<JavascriptArray> mArray;
std::shared_ptr<JavascriptMap> mMap;
} mUnion;
JavascriptType mType;
};
| true |
61e008a5c4cace42dfce49ad200cf3d71d6b865d | C++ | alvas/ms_interview_100 | /leetcode/UglyNumber.cpp | UTF-8 | 847 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Solution {
public:
bool isUgly(int num) {
if (num <= 0)
{
return false;
}
else if (num == 1 || num == 2 || num == 3 || num == 5)
{
return true;
}
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
}
else if (num % 3 == 0)
{
num /= 3;
}
else if (num % 5 == 0)
{
num /= 5;
}
else
{
return false;
}
}
return true;
}
};
int main()
{
Solution sln;
int num = 0;
std::cout << "Please enter num: ";
cin >> num;
std::cout << sln.isUgly(num) << endl;
return 0;
}
| true |
f456221efd9578e5ccbe456cb4fe5776390c96e7 | C++ | ruslashev/vxr | /pixeldrawer.hpp | UTF-8 | 401 | 2.796875 | 3 | [] | no_license | #ifndef PIXELDRAWER_HPP
#define PIXELDRAWER_HPP
#include <SDL2/SDL.h>
#include <memory>
const int WindowWidth = 800, WindowHeight = 600;
class PixelDrawer
{
private:
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *texture;
Uint32 pixelData[WindowWidth*WindowHeight];
public:
PixelDrawer();
~PixelDrawer();
void Update();
void WritePixel(int x, int y, Uint32 color);
};
#endif
| true |
e6b2d9d0fb00f570601ff259f755895a9ef54639 | C++ | jaswantcoder/CodingNotes | /MasteringCompetitiveProgrammingQuestions/DIVSUBS.cpp | UTF-8 | 1,030 | 2.609375 | 3 | [] | no_license | //Divisible Subset - Page 45
//https://www.codechef.com/status/DIVSUBS
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000000
typedef long long ll;
typedef unsigned long long ull;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) cin >> a[i];
ll b[n + 1];
b[0] = 0;
vector<ll> temp[n];
temp[b[0] % n].push_back(0);
for(int i=1; i<=n; ++i)
{
b[i] = b[i - 1] + a[i - 1];
temp[b[i] % n].push_back(i);
}
ll start, end;
for(int i=0; i<n; ++i)
{
if(temp[i].size() >=2 )
{
start = temp[i][0];
end = temp[i][1];
}
}
cout << (end - start) << endl;
for(int i = start + 1; i <= end; ++i)
cout << i << " ";
cout << endl;
}
return 0;
} | true |
54b09f9c8b382c607f84b6e7ad5b03a52a653023 | C++ | histat/dc-nx | /sdlshim/common/tcpstuff.cpp | UTF-8 | 5,246 | 2.53125 | 3 | [] | no_license |
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
#include <fcntl.h>
#include "tcpstuff.h"
#include "tcpstuff.fdh"
#define uchar uint8_t
struct sockaddr_in sain;
int senddata(uint32_t sock, const uint8_t *packet, int len)
{
return send(sock, packet, len, 0);
}
int sendstr(uint32_t sock, const char *str)
{
return senddata(sock, (const uint8_t *)str, strlen(str));
}
int sendnow(uint32_t sock, const uint8_t *packet, int len)
{
int ok;
net_nodelay(sock, true);
ok = senddata(sock, packet, len);
net_nodelay(sock, false);
return ok;
}
void net_flush(uint32_t sock)
{
net_nodelay(sock, true);
net_nodelay(sock, false);
}
/*
void c------------------------------() {}
*/
int chkread(uint32_t sock)
{
fd_set readfds;
struct timeval poll;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
memset((char *)&poll, 0, sizeof(poll));
return select(sock+1, &readfds, (fd_set *)0, (fd_set *)0, &poll);
}
int chkwrite(uint32_t sock)
{
fd_set writefds;
struct timeval poll;
FD_ZERO(&writefds);
FD_SET(sock, &writefds);
memset((char *)&poll, 0, sizeof(poll));
return select(sock+1, (fd_set *)0, &writefds, (fd_set *)0, &poll);
}
/*
void c------------------------------() {}
*/
bool net_setnonblock(uint32_t sock, bool enable)
{
long fvalue;
// Set non-blocking
if ((fvalue = fcntl(sock, F_GETFL, NULL)) < 0)
{
staterr("net_setnonblock: Error fcntl(..., F_GETFL) (%s)", strerror(errno));
return 1;
}
if (enable)
fvalue |= O_NONBLOCK;
else
fvalue &= ~O_NONBLOCK;
if (fcntl(sock, F_SETFL, fvalue) < 0)
{
staterr("net_setnonblock: Error fcntl(..., F_SETFL) (%s)", strerror(errno));
return 1;
}
return 0;
}
bool net_nodelay(uint32_t sock, int flag)
{
return setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
}
/*
void c------------------------------() {}
*/
char *decimalip(uint32_t ip)
{
static char buffer[80];
sprintf(buffer, "%d.%d.%d.%d",
(ip>>24)&255, (ip>>16)&255, (ip>>8)&255, ip&255);
return buffer;
}
uint32_t net_dnslookup(const char *host)
{
struct hostent *hosten;
uint32_t ip;
// attempt to resolve the hostname via DNS
hosten = gethostbyname(host);
if (hosten == NULL)
{
staterr("dnslookup: failed to resolve host: '%s'.", host);
return 0;
}
else
{
memcpy((char*)&ip, hosten->h_addr_list[0], 4);
return ntohl(ip);
}
}
/*
void c------------------------------() {}
*/
// attempts to connect to ip:port, and returns the new socket number if successful,
// else returns 0.
uint32_t net_connect(uint32_t ip, uint16_t port, int timeout_ms)
{
int conn_socket, result;
bool connected;
bool use_timeout;
if (!(conn_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)))
{
staterr("connect_tcp: Failed to create socket.");
return 1;
}
net_setnonblock(conn_socket, true);
sain.sin_addr.s_addr = htonl(ip);
sain.sin_port = htons(port);
sain.sin_family = AF_INET;
#define TICK_BASE 10
use_timeout = (timeout_ms != 0);
connected = false;
for(;;)
{
result = connect(conn_socket, (struct sockaddr *)&sain, sizeof(struct sockaddr_in));
if (errno == EISCONN || result != -1)
{
connected = true;
break;
}
if (errno == EINTR) break;
if (use_timeout)
{
if (timeout_ms >= 0)
{
usleep(TICK_BASE * 1000);
timeout_ms -= TICK_BASE;
}
else break;
}
}
net_setnonblock(conn_socket, false);
if (connected)
return conn_socket;
close(conn_socket);
return 0;
}
/*
void c------------------------------() {}
*/
// create a socket and have it listen on all available interfaces.
uint32_t net_open_and_listen(uint16_t port, bool reuse_addr)
{
int sock;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!sock)
{
staterr("net_open_and_listen: failed to create socket!");
return 0;
}
if (reuse_addr)
{
// prevent port from getting blocked if server is shut down unexpectandly
int on = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
}
if (net_listen_socket(sock, INADDR_ANY, port))
{
close(sock);
return 0;
}
return sock;
}
// set a socket to listen on the given IP and port
char net_listen_socket(uint32_t sock, uint32_t listen_ip, uint16_t listen_port)
{
sockaddr_in thesock;
thesock.sin_addr.s_addr = htonl(listen_ip);
thesock.sin_port = htons(listen_port);
thesock.sin_family = AF_INET;
if (bind(sock, (struct sockaddr *)&thesock, sizeof(sockaddr_in)))
{
staterr("bind failed to %s:%d!", decimalip(listen_ip), listen_port);
return 1;
}
if (listen(sock, 50))
{
staterr("listen failed!");
return 1;
}
stat("bind success to %s:%d", decimalip(listen_ip), listen_port);
return 0;
}
// accepts an incoming connection on a socket and returns the new socket.
// if remote_ip is non-NULL, it is written with the IP of the connecting host.
uint32_t net_accept(uint32_t s, uint32_t *connected_ip)
{
uint32_t newsocket;
struct sockaddr_in sockinfo;
socklen_t sz = sizeof(sockinfo);
newsocket = accept(s, (struct sockaddr *)&sockinfo, &sz);
if (connected_ip)
{
if (newsocket)
{
*connected_ip = ntohl(sockinfo.sin_addr.s_addr);
}
else
{
*connected_ip = 0;
}
}
return newsocket;
}
/*
void c------------------------------() {}
*/
| true |
e44906d6c2f188abdfc87041885f757e5cde1ae8 | C++ | spacechase0/AndroidPartyGame | /gameserver/src/net/prelogin/LoginPacket.cpp | UTF-8 | 707 | 2.578125 | 3 | [] | no_license | #include "net/prelogin/LoginPacket.hpp"
#include "net/Buffer.hpp"
#include "net/PacketId.hpp"
namespace net
{
namespace prelogin
{
LoginPacket::LoginPacket()
: LoginPacket( "", "" )
{
}
LoginPacket::LoginPacket( const std::string& user, const std::string& pass )
: Packet( PacketId::Login ),
username( user ),
password( pass )
{
}
void LoginPacket::read( Buffer& buffer )
{
buffer >> username >> password;
}
void LoginPacket::write( Buffer& buffer ) const
{
buffer << username << password;
}
}
}
| true |
ab730c82780c1b98cbb56cf73aa79f8de28a6e2a | C++ | kn33hit/Coursework | /GL_backup/341/proj/proj4/LinearProbing.cpp | UTF-8 | 4,173 | 3.4375 | 3 | [] | no_license | /**************************************************************
* File: LinearProbing.cpp
* Project: CMSC 341 - Project 4
* Author : Neh Patel
* Date : 16-November-2014
* Section: Lecture-02
* E-mail: npatel10@umbc.edu
*
* Implementation of the Linear Probing class.
*
*************************************************************/
#include "LinearProbing.h"
#include <fstream>
/************************************************************
CONSTRUCTOR
creates the object and sets everything to zero. Takes a
vector and places 0 as empty buckets. and takes in the size
**********************************************************/
LinearProbing::LinearProbing(int m){
// need size here to make the table
size = m;
HashTable.resize(m);
successData = 0;
unsuccessData = 0;
lambda = 0;
probes = 0;
maxProbes = 0;
// since table is currently empty. treats data as 0
}
/************************************************************
INSERT just made to make sense when someone wantst to insert
something. Calls Handle Collisions which actually
does all the work
**********************************************************/
void LinearProbing::insert(const int number){
HandleCollision( number);
}
/************************************************************
HANDLE COLLISION
takes in the key. uses the linear function and accounts
for the output results. And inserts values into the
hash table
**********************************************************/
void LinearProbing::HandleCollision( const int number){
// LINEAR:H(K,I) = (H(K) + I) MOD M
int i = 1;
// H(K): size (constant)
int index = number % size;
// another h(k) but is change throghout
int newIndex = index;
maxProbes= 0;
while(1){
// cout << index << " = " << number << " % " << size << endl;
// first case: if the spot is open, break out, and insert value
if(HashTable[newIndex] == 0){
HashTable[newIndex] = number;
successData++;
maxProbes++;
break;
}else{
// if spot not open. check the spot under it using this function
newIndex = (index + i) % size;
probes++;
maxProbes++;
i++;
}
// once you go through the whole table exit. this case helps us do that
if(isFull() == true){
unsuccessData++;
break;
}
}
}
/************************************************************
IS FULL
checks if the table is full or not and returns true
if it is
************************************************************/
bool LinearProbing::isFull(){
int count = 0;
for(int i = 0 ; i < (signed)HashTable.size();i++){
if(HashTable[i] != 0){
count++;}
}
if(count == (signed)HashTable.size()){
return true;
}
return false;
}
/************************************************************
OUTPUT RESULTS
writes the actual table to the outputTable.txt
file
**********************************************************/
void LinearProbing::OutputResults(){
// outputting the actula table to a file
ofstream outfile;
outfile.open("outputTable.txt");
outfile << "Linear Probing actual table" << endl;
// hashtable is the parameter that holds all the values as a hash table
for(int i = 0; i < size; i++){
if(HashTable[i] != 0){
outfile << i << ": " << HashTable[i] << endl;
}else{
outfile << i << ":" << endl;
}
}
outfile << endl;
outfile.close();
}
| true |
72835d491f1ad943810e0a5591971fca59c853e6 | C++ | Tigrouzen/UnrealEngine-4 | /Engine/Source/Runtime/Renderer/Private/CustomDepthRendering.h | UTF-8 | 1,224 | 2.640625 | 3 | [] | no_license | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
CustomDepthRendering.h: CustomDepth rendering implementation.
=============================================================================*/
#pragma once
/**
* Set of distortion scene prims
*/
class FCustomDepthPrimSet
{
public:
/**
* Iterate over the prims and draw them
* @param ViewInfo - current view used to draw items
* @return true if anything was drawn
*/
bool DrawPrims(const class FViewInfo* ViewInfo,bool bInitializeOffsets);
/**
* Add a new primitive to the list of prims
* @param PrimitiveSceneProxy - primitive info to add.
* @param ViewInfo - used to transform bounds to view space
*/
void AddScenePrimitive(FPrimitiveSceneProxy* PrimitiveSceneProxy,const FViewInfo& ViewInfo)
{
Prims.Add(PrimitiveSceneProxy);
}
/**
* @return number of prims to render
*/
int32 NumPrims() const
{
return Prims.Num();
}
/**
* @return a prim currently set to render
*/
/*
const FPrimitiveSceneProxy* GetPrim(int32 i)const
{
return Prims[i];
}*/
private:
/** list of prims added from the scene */
TArray<FPrimitiveSceneProxy*> Prims;
};
| true |
b218365043997056a8882762a5e64e90bedd1be2 | C++ | jochenklein/tempest | /lib/mtl/mtl/fromtorange.h | UTF-8 | 1,364 | 3.421875 | 3 | [
"Apache-2.0"
] | permissive | #include <iterator>
#include <memory>
namespace mtl
{
template <typename range_type>
class range : public std::iterator<std::bidirectional_iterator_tag, range_type>
{
public:
range(range_type f, range_type l) : first_(f), last_(l), curr_(f)
{
}
range begin()
{
return{ first_, last_, first_ };
}
range end()
{
return{ first_, last_, last_ };
}
bool operator==(const range& rhs) const
{
return (rhs.first_ == first_) && (rhs.last_ == last_) && (rhs.curr_ == curr_);
}
bool operator!=(const range& rhs) const
{
return !(*this == rhs);
}
range_type operator*() const
{
return curr_;
}
range& operator++()
{
++curr_;
return *this;
}
range operator++(int)
{
range tmp(*this);
operator++();
return tmp;
}
range& operator--()
{
--curr_;
return *this;
}
range operator--(int)
{
range tmp(*this);
operator--();
return tmp;
}
private:
range(range_type f, range_type l, range_type c) : curr_(c), first_(f), last_(l)
{
}
range_type first_;
range_type last_;
range_type curr_;
};
template<typename range_type, typename IV>
range<range_type> range_from_to(IV first, range_type last)
{
return{ first + (0u*last), last };
}
template <typename range_type>
range<range_type> count_until(range_type last)
{
return{ 0u, last };
}
} | true |
62bcacb071327c615af87aca6a96134b85cbbd0e | C++ | neophytos-sk/phigita-star | /lib/ttext/ttext_v1/src/cluster/common.cpp | UTF-8 | 2,972 | 2.90625 | 3 | [
"TCL"
] | permissive | #include "common.h"
bool getLines(string filename,vector<string>* lines)
{
lines->clear();
FILE * f = fopen(filename.c_str(),"r");
if (f)
{
while (!feof(f))
{
string line("");
char ch = 'a';
while (ch != '\n')
{
char ch = (char) fgetc(f);
if (ch != EOF)
{
if (ch == '\n' || ch == '\0')
break;
line += ch;
}
else
{
fclose(f);
return true;
}
}
lines->push_back(line);
}
}
return false;
}
bool getText(string filename, string* text)
{
*text = "";
FILE * f = fopen(filename.c_str(),"r");
if (f)
{
while (!feof(f))
{
string line("");
char ch = 'a';
while (ch != '\n')
{
char ch = (char) fgetc(f);
if (ch != EOF)
{
if (ch == '\n' || ch == '\0')
break;
line += ch;
}
else
{
fclose(f);
return true;
}
}
*text += " " + line;
}
}
return false;
}
string toLower(string str)
{
char * d = (char*) str.c_str();
Tcl_UtfToLower(d);
str.assign(d);
return str;
}
/*string toLower(string str)
{
char * s = (char *) str.c_str();
unsigned int length = Tcl_NumUtfChars(s,-1);
string empty("");
string result("");
for (unsigned int i = 0; i < length; i++)
{
Tcl_UniChar cht = Tcl_UniCharAtIndex(s,i);
char * ch = (char *) empty.c_str();
cht = Tcl_UniCharToLower(cht);
Tcl_UniCharToUtf(cht,ch);
result += ch;
}
return result;
}*/
string replaceAll(string str)
{
for (unsigned int i = 0; i < str.length(); i++)
if (!Tcl_UniCharIsAlnum((int) str[i]))
str[i] = ' ';
return str;
}
string clearString(string str)
{
string s("");
for (unsigned int i = 0; i < str.length(); i++) {
if (Tcl_UniCharIsPrint((int) str[i]))
s += str[i];
}
return s;
}
string trim(string line)
{
while (Tcl_UniCharIsSpace(line[0]))
line.erase(0,1);
while (Tcl_UniCharIsSpace(line[line.length()-1]))
line.erase(line.length()-1,1);
return line;
}
string getFilePath(string filename)
{
int slashpos = filename.rfind("/");
if (slashpos >= 0)
return filename.substr(0,slashpos+1);
else
return "";
}
vector<string> getTokens(string str)
{
vector<string> tokens;
string token("");
char * s = (char *) str.c_str();
unsigned int length = Tcl_NumUtfChars(s,-1);
string empty("");
for (unsigned int i = 0; i < length; i++)
{
Tcl_UniChar cht = Tcl_UniCharAtIndex(s,i);
char * ch = (char *) empty.c_str();
Tcl_UniCharToUtf(cht,ch);
if (Tcl_UniCharIsAlnum(cht))
token += ch;
else
{
if (token.length() > 0)
{
tokens.push_back(token);
token = "";
}
}
}
if (token.length() > 0)
tokens.push_back(token);
return tokens;
}
int compareStrings(string s1, string s2)
{
return Tcl_UtfNcasecmp(
(char*) s1.c_str(),
(char*) s2.c_str(),
min( Tcl_NumUtfChars((char*) s1.c_str(),-1),Tcl_NumUtfChars((char*) s2.c_str(),-1) )
);
}
| true |
55b1fd0ae74b3507bc036e00bfcd595e8a2f9753 | C++ | lobcsysinfi/Design-Pattern-Project | /586ProjectNew/state.cpp | UTF-8 | 1,699 | 2.625 | 3 | [] | no_license | //state.cpp
//implement methods in state.h
#include "state.h"
#include "MDA_EFSM.h"
#include <iostream>
void idle::card(){ //card() method
attempts=0;
operations->store_pin1();
operations->store_balance1();
operations->prompt_for_PIN1();
}
void check_pin::IncorrectPin(int max){ //IncorrectPin method
if (attempts < max){
operations->incorrect_pin_msg1();
attempts=attempts + 1;
}
else{
operations->incorrect_pin_msg1();
operations->too_many_attempts_msg1();
operations->eject_card1();
}
}
void check_pin::CorrectPinBelowMin(){
operations->display_menu1(); //invoke display_munu method
}
void check_pin::CorrectPinAboveMin(){
operations->display_menu1();
}
void ready::WithdrawAboveMin(){
operations->MakeWithdraw1(); //invoke makewithdraw method
}
void ready::DepositAboveMin(){
operations->MakeDeposit1(); //invoke makedeposit method
}
void ready::balance(){
operations->DisplayBalance1();
}
void ready::lock(){
}
void ready::exit(){
operations->eject_card1();
}
void ready::WithdrawBelowMin(){
operations->MakeWithdraw1();
operations->Penalty1(); //invoke op::penalty()
}
void locked::unlockAboveMin(){
}
void locked::unlockBelowMin(){
}
void overdrawn::DepositBelowMin(){
operations->MakeDeposit1();
operations->Penalty1();
}
void overdrawn::balance(){ //invoke displayBalance in op
operations->DisplayBalance1();
}
void overdrawn::lock(){
}
void overdrawn::DepositAboveMin(){
operations->MakeDeposit1(); //invoke displayBalance in op
}
void overdrawn::exit(){
operations->eject_card1();
} | true |
e27651d3e691fd32399f45882daaf75ee56d6d4b | C++ | ThewyRogue99/OS-Dev | /src/kernel/io/io.cpp | UTF-8 | 1,054 | 3.171875 | 3 | [] | no_license | #include "io.h"
namespace IO
{
unsigned char port_byte_in(unsigned short port)
{
// A handy C wrapper function that reads a byte from the specified port
// "=a" ( result ) means : put AL register in variable RESULT when finished
// "d" ( port ) means : load EDX with port
unsigned char result ;
__asm__ ("in %%dx , %% al" : "=a" ( result ) : "d" ( port ));
return result ;
}
void port_byte_out(unsigned short port , unsigned char data)
{
// "a" ( data ) means : load EAX with data
// "d" ( port ) means : load EDX with port
__asm__ (" out %%al , %% dx" : :"a" ( data ), "d" ( port ));
}
unsigned short port_word_in(unsigned short port)
{
unsigned short result ;
__asm__ ("in %%dx , %% ax" : "=a" ( result ) : "d" ( port ));
return result ;
}
void port_word_out(unsigned short port , unsigned short data)
{
__asm__ (" out %%ax , %% dx" : :"a" ( data ), "d" ( port ));
}
} | true |
15a915358249db4586c7a9db6c3f1cfef42bc7dc | C++ | cosmicray001/Online_judge_Solutions | /uri/1097.cpp | UTF-8 | 230 | 2.640625 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
int main()
{
int i, j, x, c;
for(i = 1, j = 7; i <= 9; i += 2, j += 2)
{
for(x = j, c = 0; c < 3; x--, c++)
{
printf("I=%d J=%d\n", i, x);
}
}
return 0;
}
| true |
a32995662e0e146ef1bed8ef3f847b398624047f | C++ | DEYASHINI/Contact_Book_Simulation | /demo.cpp | UTF-8 | 4,426 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include<ctime>
#include "demo.h"
using namespace std;
void printMessage()
{
cout<<"//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<"//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<endl<<endl<<endl<<endl;
cout<<" WELCOME TO THE CONTACT BOOK APPLICATION.....HOPE YOU ENJOY IT"<<endl;
cout<<endl<<endl<<endl<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<endl<<endl<<endl<<endl;
time_t timetoday;
time(&timetoday);
cout <<" Date and time as per todays is : "<< asctime(localtime(&timetoday));
cout<<endl<<endl<<endl<<endl;
cout<<"//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<"//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl;
cout <<" Chose an action to continue "<< asctime(localtime(&timetoday));
cout<<endl<<endl<<endl<<endl;
}
void printMenu()
{
cout<<" 1. Sign Up"<<endl;
cout<<" 2. Login"<<endl;
cout<<" 3. Exit"<<endl;
cout<<endl<<endl<<" Enter your choice:"<<endl;
cout<<endl<<endl;
}
void printChoice()
{
cout<<endl<<endl<<endl;
cout<<" *********************************************************************************"<<endl;
cout<<" *********************************************************************************"<<endl<<endl;
cout<<" 1.Create and Insert new Contact Details"<<endl;
cout<<" 2.Enter initials to find Suggestions for a Contact by Name"<<endl;
cout<<" 3.Chose contact to retrieve details and call by name"<<endl;
cout<<" 4.Retrieve recent atmost 5 contacts"<<endl;
cout<<" 5.Search by Number to retrieve details and call"<<endl;//hashmap
cout<<" 6.Sort and Display details by name"<<endl;
cout<<" 7.Delete record by Name"<<endl;
cout<<" 8.Modify Details"<<endl;
cout<<" 9.Retrieve the phone number of person at a particular location if exists"<<endl;
cout<<" 10.Find phone numbers of all nearest neighbors to a location"<<endl;
cout<<" 11.Delete account"<<endl;
cout<<" 12.Exit application"<<endl<<endl;
cout<<" *********************************************************************************"<<endl;
cout<<" *********************************************************************************"<<endl<<endl;
cout<<" Enter your choice"<<endl<<endl;
}
void printExitMessage()
{
cout<<" EXIT FROM CONTACT BOOK SIMULATION"<<endl<<endl;
cout<<" BACKED UP DATA SUCCESSFULLY"<<endl<<endl<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl<<endl;
cout<<" GOODBYE..... SEE YOU SOON"<<endl<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl;
cout<<"///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"<<endl<<endl;
}
| true |
53fe43af9e092fa92a1ece7b84cd2ffa76997856 | C++ | Romamart/system-programming | /Task_9/src/project/Task_4/Matrix.hpp | UTF-8 | 3,448 | 3.390625 | 3 | [] | no_license | //
// Created by roman on 15.11.2019.
//
#pragma once
#include <iostream>
#include <vector>
#include "Matrix.h"
#include <math.h>
template <class T> Matrix<T>::Matrix() {Mat = {};}
template<class T> Matrix<T>::Matrix(std::vector<T> vector) {
Mat = vector;
}
template <class T> void Matrix<T>::set(std::vector<T>& vector) {
this->Mat.clear();
Mat = vector;
}
template <class T> void Matrix<T>::push_back(T element) {
Mat.push_back(element);
}
//template<class T> Matrix<T>& Matrix<T>::operator=(const std::vector<T>& other){
// Mat.clear();
// rows = 1;
// cols = other.size();
// Mat = other.data();
// return *this;
//}
template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& other) {
if (this != &other) {
Mat.clear();
for (auto& element : other.data)
{
Mat.push_back(element);
}
}
return *this;
}
template <class T> Matrix<bool> operator<(Matrix<T>& a, Matrix<T>& b){
Matrix<bool> res{};
std::vector<T> data1 = a.get();
std::vector<T> data2 = b.get();
for (int i = 0; i < std::max(data1.size(),data2.size()); ++i){
if (i < data1.size() && i > data2.size())
res.push_back(true);
else
if (i > data1.size() && i < data2.size())
res.push_back(false);
else
res.push_back(data1.at(i) < data2.at(i));
}
return res;
}
template <class T> Matrix<T> operator<(Matrix<T> matrix, double eps) {
Matrix<T> res;
for (int i = 0; i < matrix.get().size(); ++i) {
res.push_back((T)(matrix.get().at(i) < eps));
}
return res;
}
template <class T> Matrix<T> where(Matrix<bool> matbool, Matrix<T>& mat1, Matrix<T>& mat2){
Matrix<T> res{};
std::vector<T> data1 = mat1.get();
std::vector<T> data2 = mat2.get();
std::vector<bool> booldata = matbool.get();
for (int i = 0; i < matbool.get().size(); ++i){
if (booldata[i] == true)
res.push_back(data1.at(i));
else
res.push_back(data2.at(i));
}
return res;
}
template <class T> std::vector<T>& Matrix<T>::get() { return Mat; }
template<class T> void Matrix<T>::GetConsol(int k, int l){
// reshape(k,l);
std::cout << k << " " << l << std::endl;
for (int i = 0; i < k; ++i){
for (int j = 0; j < l; ++j){
std::cout << Mat[i*k + j] << " ";
}
std::cout << std::endl;
}
}
template <class T> Matrix<T> operator-(Matrix<T> first, Matrix<T> second) {
Matrix<T> res{};
for (int i = 0; i < first.get().size(); ++i) {
res.push_back(first.get().at(i) - second.get().at(i));
}
return res;
}
template <class T> Matrix<T> abs(Matrix<T> matrix) {
for (auto& element : matrix.get()) {
element = std::abs(element);
}
return matrix;
}
template <class T> Matrix<T> Matrix<T>::transposed() {
Matrix<T> res{};
int l = sqrt(Mat.size());
int k = sqrt(Mat.size());
for (size_t i = 0; i < l; ++i) {
for (size_t j = 0; j < k; ++j)
res.push_back(Mat[j*(l) + i]);
}
return res;
}
template <class T> bool all(Matrix<T> matrix) {
for (int i = 0; i < matrix.get().size(); ++i) {
if (matrix.get().at(i) == 0){
return 0;
}
}
return 1;
}
template <class T> bool Matrix<T>::is_symmetric(double eps) {
return all(abs(*this - this->transposed()) < eps);
} | true |
4b4627e6f726cf137221b5876a3c057c93d6b26e | C++ | Sockke/MyData | /Linux/TCPIP/socket/udpsocket.h | UTF-8 | 1,354 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
using namespace std;
class UdpSocket {
public:
UdpSocket()
: _sockfd(-1)
{}
bool u_socket() {
_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (_sockfd < 0) {
return false;
}
return true;
}
bool u_bind(const string& ip, unsigned short port) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip.c_str()) ;
addr.sin_port = htons(port);
int len = sizeof(struct sockaddr_in);
int ret = bind(_sockfd, (struct sockaddr*)&addr, len);
if (ret < 0) {
return false;
}
return true;
}
bool u_read(string& data, struct sockaddr_in& addr) {
char buf[1024] = {0};
socklen_t len = sizeof(addr);
int ret = recvfrom(_sockfd, buf, 1024, 0, (struct sockaddr*)&addr, &len);
if (ret < 0) {
return false;
}
data.assign(buf, ret);
return true;
}
bool u_send(const string& data, struct sockaddr_in& addr) {
socklen_t len = sizeof(addr);
int ret = sendto(_sockfd, &data[0], data.size(), 0, (struct sockaddr*)&addr, len);
if (ret < 0) {
return false;
}
return true;
}
private:
int _sockfd;
};
| true |
9d5ff069fb02c2dbac550e54c2820436df0e0ec2 | C++ | mockk/mockk | /modules/mockk-agent-android/external/slicer/export/slicer/arrayview.h | UTF-8 | 1,342 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "common.h"
#include <stdlib.h>
namespace slicer {
// A shallow array view
template <class T>
class ArrayView {
public:
ArrayView() = default;
ArrayView(const ArrayView&) = default;
ArrayView& operator=(const ArrayView&) = default;
ArrayView(T* ptr, size_t count) : begin_(ptr), end_(ptr + count) {}
T* begin() const { return begin_; }
T* end() const { return end_; }
T* data() const { return begin_; }
T& operator[](size_t i) const {
SLICER_CHECK(i < size());
return *(begin_ + i);
}
size_t size() const { return end_ - begin_; }
bool empty() const { return begin_ == end_; }
private:
T* begin_ = nullptr;
T* end_ = nullptr;
};
} // namespace slicer
| true |
1a68f46ed23662498b6da0a2882c5cb8ac0dc698 | C++ | dokgo/Melnikova | /src/fourth/fourthLab.cpp | UTF-8 | 506 | 2.984375 | 3 | [] | no_license | //
// Created by dokgo on 26.04.17.
//
#include <vector>
#include "Animals.h"
#include "SeaAnimals.h"
using std::vector;
int main() {
/*vector<Animals *> vector1 = {new SeaAnimals("fish", "joe", 2), new Animals(), new SeaAnimals("star", "patric", 5)};
for (Animals *a : vector1) {
a->say();
}*/
vector<Animals> vec = {SeaAnimals("fish", "joe", 2), Animals(), SeaAnimals("star", "patric", 5)};
for (Animals a : vec) {
a.say();
a.move();
}
return 0;
} | true |
72356880a0920146b730ccc9223d05d6daa2e04c | C++ | sharatsachin/Competitive-Programming-Solutions | /Leetcode/MaxIncreasetoKeepCitySkyline.cpp | UTF-8 | 537 | 2.515625 | 3 | [] | no_license | class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
int n = grid.size();
vector<int> mxr(n,0), mxc(n,0);
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++){
mxr[i] = max(mxr[i],grid[i][j]);
mxc[j] = max(mxc[j],grid[i][j]);
}
}
int sum=0;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++){
sum += (min(mxr[i],mxc[j])-grid[i][j]);
}
}
return sum;
}
};
| true |
82775fa3d4094e8a05b10ee919ac0f34c2016d97 | C++ | STRyu-Liu/homework | /list5-11/list5-11/list511.cpp | UTF-8 | 566 | 2.71875 | 3 | [] | no_license | // list511.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
#define NUMBER 5
#include<stdio.h>
int main(void) {
int i;
int tensu[NUMBER];
int max, min;
printf("输入%d人的分数\n",NUMBER);
for (i = 0; i < NUMBER;i++) {
printf("NO.%d:",i+1);
scanf("%d",&tensu[i]);
}
min = max = tensu[0];
for (i = 0; i < NUMBER; i++) {
if (tensu[i] > max) max = tensu[i];
if (tensu[i] < min) min = tensu[i];
}
printf("max:%d\n",max);
printf("min:%d\n",min);
return 0;
}
| true |
7f8f22f83497fca9403ca5550eb2701df354cab4 | C++ | velazqua/competitive-programming | /online-judges/Project-Euler/PE96/PE96.cpp | UTF-8 | 4,673 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <fstream>
#define DEBUG 0
using namespace std;
struct Cell {
int n;
set<int> p;
Cell (int n_, set<int> p_) : n(n_), p(p_) {}
};
typedef vector< vector<Cell> > State;
vector<pair<int,int> > rowDeleter(State &cells, int i, int val) {
vector< pair<int,int> > result;
for(int y = 0; y < 9; y++) {
set<int>::iterator f = cells[i][y].p.find(val);
if (f != cells[i][y].p.end()) {
result.push_back(make_pair(i, y));
cells[i][y].p.erase(f);
}
}
return result;
}
vector<pair<int,int> > colDeleter(State &cells, int j, int val) {
vector< pair<int,int> > result;
for(int y = 0; y < 9; y++) {
set<int>::iterator f = cells[y][j].p.find(val);
if (f != cells[y][j].p.end()) {
result.push_back(make_pair(y, j));
cells[y][j].p.erase(f);
}
}
return result;
}
vector<pair<int,int> > boxDeleter(State &cells, int i, int j, int val) {
if (i < 3) i = 0;
else if (i < 6) i = 3;
else i = 6;
if (j < 3) j = 0;
else if (j < 6) j = 3;
else j = 6;
vector< pair<int,int> > result;
for(int x = i; x < i+3; x++) {
for(int y = j; y < j+3; y++) {
set<int>::iterator f = cells[x][y].p.find(val);
if (f != cells[x][y].p.end()) {
result.push_back(make_pair(x, y));
cells[x][y].p.erase(f);
}
}
}
return result;
}
void doDeductions (State& cells) {
while (true) {
bool deduction = false;
for(int i = 0; i < 9; i++) {
if (deduction) break;
for(int j = 0; j < 9; j++) {
if (cells[i][j].n == 0 && cells[i][j].p.size() == 1) {
int val = *cells[i][j].p.begin();
cells[i][j].n = val;
rowDeleter(cells, i, val);
colDeleter(cells, j, val);
boxDeleter(cells, i, j, val);
deduction = true;
break;
}
}
}
if (!deduction) break;
}
}
bool contradiction (State const& cells) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if (cells[i][j].n == 0 && cells[i][j].p.size() == 0)
return true;
}
}
return false;
}
void printSudoku(State& cells) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
cout << cells[i][j].n;
}
cout << endl;
}
cout << endl;
}
void updateCells (State& cells, int i, int j, int val) {
rowDeleter(cells, i, val);
colDeleter(cells, j, val);
boxDeleter(cells, i, j, val);
}
int main ()
{
// Sudoku Solver
ifstream fin("sudoku.txt");
int ans = 0;
for(int t = 0; t < 50; t++) {
string line;
getline(fin, line);
if (line == "") getline(fin, line);
vector<string> board(9);
for(int j = 0; j < 9; j++)
fin >> board[j];
set<int> temp;
for(int j = 1; j <= 9; j++)
temp.insert(j);
State cells;
for(int i = 0; i < 9; i++) {
vector<Cell> tempRow;
for(int j = 0; j < 9; j++) {
tempRow.push_back(Cell(board[i][j]-'0', temp));
}
cells.push_back(tempRow);
}
// Update all cells
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if (cells[i][j].n != 0) {
updateCells(cells, i, j, cells[i][j].n);
}
}
}
doDeductions(cells);
vector<State> Q;
Q.push_back(cells);
int numZeros = 0;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if (cells[i][j].n == 0)
numZeros++;
}
}
State ansGrid;
if (numZeros == 0)
ansGrid = cells;
for(int k = 0; k < numZeros; k++) {
int size = Q.size();
bool done = false;
for(int i = 0; i < size; i++) {
// find first 0 entry
bool found = false;
for(int x = 0; x < 9; x++) {
if (found) break;
for(int y = 0; y < 9; y++) {
if (found) break;
if (Q[i][x][y].n == 0) {
found = true;
for(auto& val : Q[i][x][y].p) {
State temp(Q[i].begin(), Q[i].end());
temp[x][y].n = val;
updateCells(temp, x, y, val);
doDeductions(temp);
if (!contradiction(temp)) {
Q.push_back(temp);
}
}
break;
}
}
}
if (!found) {
ansGrid = Q[i];
done = true;
break;
}
}
if (done) break;
Q.erase(Q.begin(), Q.begin()+size);
}
cout << "Grid #" << t+1 << endl;
printSudoku(ansGrid);
ans += ansGrid[0][0].n * 100 + ansGrid[0][1].n * 10 + ansGrid[0][2].n;
cout << endl;
}
cout << "Answer: " << ans << endl;
fin.close();
}
| true |
fc42ac52742128b3243fe9749f013370370fe7ab | C++ | noshluk2/ITeachStuff-CPP-for-Beginners-to-Beyond | /Section_2_OOP_ Code Organizing/2_classes_constructors.cpp | UTF-8 | 956 | 3.6875 | 4 | [
"MIT"
] | permissive | /*
- Purpose :
Exploring Classes with Constructors
- Understand :
Constructors
Multi-Constructor
Written by Muhammad Luqman
MIT License
*/
//Explaination :
//The Result class has multiple constructors
// by input we differentiate them
#include <cstdio>
struct Result {
//conditions -> class name and constructor should be same
Result() {
printf("no input given\n");
}
Result(int x) {
printf("Your Marks are %d\n", x);
}
Result(char x) {
printf("Your Grade is %c\n", x);
}
Result(float x) {
printf("Your Marks are %f\n", x);
}
};
int main() {
printf("\f");
Result student_1;// here no argument constructor is called by making a object
Result student_2{};
Result student_3('f');
Result student_4{'c'};// character constructor gets called
Result student_5={'l'};
Result student_6{99}; // integer constructor
Result student_7{85.56f}; // float constructor
} | true |
0d455ad2ac013e2300ea17d6ffc25d771deac127 | C++ | crazysnail/XServer | /source/include/connector.h | GB18030 | 1,607 | 2.578125 | 3 | [] | no_license | // ,from muduo
#ifndef _zxero_network_connector_h_
#define _zxero_network_connector_h_
#include "types.h"
#include "inet_address.h"
#include "date_time.h"
#include "tcp_socket.h"
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
namespace zxero
{
namespace network
{
class connector : boost::noncopyable, public boost::enable_shared_from_this<connector>
{
public:
typedef boost::function<void(std::unique_ptr<tcp_socket>&)> new_connection_callback_t;
connector(event_loop*, const inet_address&);
~connector();
public:
void new_connection_callback(const new_connection_callback_t&);
void start();
void stop();
// loop̲߳ܵ
void restart();
const inet_address& server_address() const;
private:
enum StateE {
kDisconnected,
kConnecting,
kConnected,
};
static const time_duration kMaxRetryDelayMs/* = seconds(30)*/;
static const time_duration kInitRetryDelayMs/* = milliseconds(500)*/;
void state(StateE s);
void start_in_loop();
void stop_in_loop();
void connect();
void connecting();
void handle_write();
void handle_error();
void retry();
void remove_and_reset_channel();
void reset_channel();
private:
event_loop* loop_;
inet_address server_address_;
bool connect_;
StateE state_;
boost::scoped_ptr<channel> channel_;
std::unique_ptr<tcp_socket> socket_;
new_connection_callback_t new_connection_callback_;
time_duration retry_delay_;
};
}
}
#endif // #ifndef _zxero_network_connector_h_
| true |
c519f8d265383304a6d85d4ab8c20b758481a4e3 | C++ | starsep/jnp1-zadanie2 | /maptel.cc | UTF-8 | 2,964 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unordered_map>
#include <map>
#include <set>
#include <cctype>
#include "cmaptel"
#ifdef __cplusplus
namespace jnp1 {
#endif
typedef unsigned long ul;
static ul lastId = 0;
static std::map<ul, std::unordered_map<std::string, std::string> > maptel;
static void debug(const std::string &message) {
#if DEBUG
std::cerr << message << std::endl;
#endif
}
unsigned long maptel_create() {
lastId++;
maptel[lastId] = std::unordered_map<std::string, std::string>();
return lastId;
}
void maptel_delete(unsigned long id) {
if (maptel.find(id) != maptel.end()) {
maptel.erase(id);
}
else {
std::cerr << "Nie istnieje maptel o takim numerze."; //TODO zmienić komunikat
}
}
static bool validNumber(const std::string &number) {
if(number.empty() || number.size() > TEL_NUM_MAX_LEN) {
debug("Numer ma niepoprawną długość."); //TODO zmienić komunikat
return false;
}
for(size_t i = 0; i < number.size(); i++) {
if(!isdigit(number[i])) {
debug("Numer ma niepoprawny znak."); //TODO zmienić komunikat
return false;
}
}
return true;
}
static bool maptel_exists(ul id) {
if(maptel.find(id) == maptel.end()) {
debug("Nie istnieje maptel o takim numerze."); //TODO zmienić komunikat
return false;
}
return true;
}
void maptel_insert(unsigned long id, char const *tel_src, char const *tel_dst) {
if(!maptel_exists(id)) {
return;
}
std::string src(tel_src);
std::string dst(tel_dst);
if(!validNumber(src) || !validNumber(dst)) {
return;
}
maptel[id][src] = dst;
}
static bool maptel_key_exists(ul id, const std::string &key) {
if(maptel[id].find(key) == maptel[id].end()) {
debug("Nie istnieje taki klucz w mapie o numerze " + std::to_string(id)); //TODO zmienić komunikat
return false;
}
return true;
}
static bool correctArguments(ul id, char const *tel_src, std::string &result) {
if(!maptel_exists(id)) {
return false;
}
std::string src(tel_src);
if(!validNumber(src)) {
return false;
}
if(!maptel_key_exists(id, src)) {
return false;
}
result = src;
return true;
}
void maptel_erase(unsigned long id, char const *tel_src) {
std::string src;
if(!correctArguments(id, tel_src, src)) {
return;
}
maptel[id].erase(src);
}
void maptel_transform(unsigned long id, char const *tel_src, char *tel_dst, size_t len) {
std::string src;
if(!correctArguments(id, tel_src, src)) {
return;
}
std::string current = src;
std::set<std::string> occurencies;
occurencies.insert(current);
while(occurencies.find(current) == occurencies.end()) {
current = maptel[id][current];
if(!maptel_key_exists(id, current)) {
break;
}
}
if(current.size() >= len) {
debug("Bufor wynikowy jest za mały."); //TODO zmienić komunikat
return;
}
for(size_t i = 0; i < current.size(); i++) {
tel_dst[i] = current[i];
}
tel_dst[current.size()] = '\0';
}
size_t TEL_NUM_MAX_LEN = 22;
#ifdef __cplusplus
}
#endif
| true |
681225726007d18f2153c82e511d540577526a75 | C++ | cyhbrilliant/hdu_oj.rc | /2043.cpp | UTF-8 | 1,188 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int M;
while (cin >> M) {
getchar();
for (int i = 0; i < M; i++) {
char S[51];
cin.getline(S, 50);
bool is = true;
int num = 0;
for (int j = 0; S[j] != '\0'; j++){
num++;
}
if (num < 8 || num > 16){
is =false;
}
// cout << num << endl;
int Sclass[4] = {0, 0, 0, 0};
for (int j = 0; S[j] != '\0'; j++){
if (S[j] >= 'A' && S[j] <= 'Z') {
if (Sclass[0] == 0) {
Sclass[0] = 1;
}
}else if (S[j] >= 'a' && S[j] <= 'z') {
if (Sclass[1] == 0) {
Sclass[1] = 1;
}
}else if (S[j] >= '0' && S[j] <= '9') {
if (Sclass[2] == 0) {
Sclass[2] = 1;
}
}else if (S[j] == '~' || S[j] == '!' || S[j] == '@' || S[j] == '^' ||
S[j] == '#' || S[j] == '$' || S[j] == '%') {
if (Sclass[3] == 0) {
Sclass[3] = 1;
}
}else {
is =false;
}
}
// cout << Sclass[0]<< Sclass[1] << Sclass[2] << Sclass[3] << endl;
if (Sclass[0]+Sclass[1]+Sclass[2]+Sclass[3] < 3) {
is =false;
}
if (is) {
cout << "YES" << endl;
}else {
cout << "NO" << endl;
}
}
}
return 0;
} | true |
35c5eaa5ca3cbf735f5a6214a845d53ed49112ce | C++ | divyaagarwal24/coderspree | /Android/AnjumanHasan_AnjumanHasan_2024cse1157_2/Patterns/Pattern20.cpp | UTF-8 | 420 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n,i,j;
cin >> n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(j==n-1||j==0)
{
cout << "*\t";
}
else if(i==j&&i>=(n-1)/2)
{
cout << "*\t";
}
else if(i+j==(n-1)&&i>=(n-1)/2)
{
cout << "*\t";
}
else
cout << "\t";
}
cout << endl;
}
}
| true |
86b7e7e35ee48cba0854868ba9fe3b6d49e0310e | C++ | Nikhilbhateja22/Love-Babbar-450 | /06_binary_trees/29_maximum_sum_of_nodes_in_BT_such_that_no_2_are_adjacent.cpp | UTF-8 | 4,115 | 3.828125 | 4 | [] | no_license | /*
link: https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/
*/
// ----------------------------------------------------------------------------------------------------------------------- //
/*
using map
TC: O(N^2)
*/
// C++ program to find maximum sum from a subset of
// nodes of binary tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node structure */
struct node
{
int data;
struct node* left, * right;
};
/* Utility function to create a new Binary Tree node */
struct node* newNode(int data)
{
struct node* temp = new struct node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Declaration of methods
int sumOfGrandChildren(node* node);
int getMaxSum(node* node);
int getMaxSumUtil(node* node, map<struct node*, int>& mp);
// method returns maximum sum possible from subtrees rooted
// at grandChildrens of node 'node'
int sumOfGrandChildren(node* node, map<struct node*, int>& mp)
{
int sum = 0;
// call for children of left child only if it is not NULL
if (node->left)
sum += getMaxSumUtil(node->left->left, mp) +
getMaxSumUtil(node->left->right, mp);
// call for children of right child only if it is not NULL
if (node->right)
sum += getMaxSumUtil(node->right->left, mp) +
getMaxSumUtil(node->right->right, mp);
return sum;
}
// Utility method to return maximum sum rooted at node 'node'
int getMaxSumUtil(node* node, map<struct node*, int>& mp)
{
if (node == NULL)
return 0;
// If node is already processed then return calculated
// value from map
if (mp.find(node) != mp.end())
return mp[node];
// take current node value and call for all grand children
int incl = node->data + sumOfGrandChildren(node, mp);
// don't take current node value and call for all children
int excl = getMaxSumUtil(node->left, mp) +
getMaxSumUtil(node->right, mp);
// choose maximum from both above calls and store that in map
mp[node] = max(incl, excl);
return mp[node];
}
// Returns maximum sum from subset of nodes
// of binary tree under given constraints
int getMaxSum(node* node)
{
if (node == NULL)
return 0;
map<struct node*, int> mp;
return getMaxSumUtil(node, mp);
}
// Driver code to test above methods
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->right->right = newNode(5);
root->left->left = newNode(1);
cout << getMaxSum(root) << endl;
return 0;
}
// ----------------------------------------------------------------------------------------------------------------------- //
/*
using pair
TC: O(N)
*/
// C++ program to find maximum sum in Binary Tree
// such that no two nodes are adjacent.
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node* left, * right;
Node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
pair<int, int> maxSumHelper(Node* root)
{
if (root == NULL)
{
pair<int, int> sum(0, 0);
return sum;
}
pair<int, int> sum1 = maxSumHelper(root->left);
pair<int, int> sum2 = maxSumHelper(root->right);
pair<int, int> sum;
// This node is included (Left and right children
// are not included)
sum.first = sum1.second + sum2.second + root->data;
// This node is excluded (Either left or right
// child is included)
sum.second = max(sum1.first, sum1.second) +
max(sum2.first, sum2.second);
return sum;
}
int maxSum(Node* root)
{
pair<int, int> res = maxSumHelper(root);
return max(res.first, res.second);
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(1);
root->left->left = new Node(2);
root->left->left->left = new Node(1);
root->left->right = new Node(3);
root->left->right->left = new Node(4);
root->left->right->right = new Node(5);
cout << maxSum(root);
return 0;
}
| true |
a51dca73f902fb8907dabbfbd9f19075c96cd56c | C++ | jackgoddard/hepObjects | /MCBlock.cc | UTF-8 | 2,120 | 2.609375 | 3 | [] | no_license | #define MCBLOCK_CXX
#include "MCBlock.h"
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
MCBlock::MCBlock(){
m_n = -1;
m_pt = 0.0;
m_m = 0.0;
m_eta= 0.0;
m_phi= 0.0;
m_charge = 0;
m_status =0;
m_barcode = 0;
m_pdgid = 0;
}
MCBlock::~MCBlock(){}
int MCBlock::N() const { return m_n; }
float MCBlock::Pt() const { return m_pt; }
float MCBlock::M() const { return m_m; }
float MCBlock::Eta() const { return m_eta; }
float MCBlock::Phi() const { return m_phi; }
float MCBlock::Charge() const { return m_charge; }
int MCBlock::Status() const { return m_status; }
int MCBlock::BarCode() const { return m_barcode; }
int MCBlock::PDGID() const { return m_pdgid; }
std::vector<int> MCBlock::ParentIndex() const { return m_parent_index; }
std::vector<int> MCBlock::ChildIndex() const { return m_child_index; }
std::vector<int> MCBlock::Parents() const { return m_parents; }
std::vector<int> MCBlock::Children() const { return m_children; }
TLorentzVector MCBlock::LorentzVector() const {return m_lorentz_vector;}
//-- Setter Functions
void MCBlock::SetN( const int n ){ m_n = n; }
void MCBlock::SetPt( const float pt ) { m_pt = pt; }
void MCBlock::SetM( const float m ){ m_m = m; }
void MCBlock::SetEta( const float eta ){ m_eta = eta;}
void MCBlock::SetPhi( const float phi ){ m_phi = phi; }
void MCBlock::SetCharge( const float charge ){ m_charge = charge; }
void MCBlock::SetStatus( const int status ){ m_status = status; }
void MCBlock::SetBarCode( const int barcode ){ m_barcode = barcode; }
void MCBlock::SetPDGID( const int pdgid ){ m_pdgid = pdgid; }
void MCBlock::SetParents( const std::vector<int> parents ){ m_parents = parents; }
void MCBlock::SetParentIndex( const std::vector<int> index ){ m_parent_index = index;}
void MCBlock::SetChildren( const std::vector<int> children){ m_children = children; }
void MCBlock::SetChildIndex( const std::vector<int> index){ m_child_index = index; }
void MCBlock::SetLorentzVector( const TLorentzVector vector ){ m_lorentz_vector = vector;}
| true |
0a3f1003a66319edf8686bcbb6de8b183f7e8bd0 | C++ | xdinos/Cocoa | /CocoaEngine/cpp/cocoa/renderer/Camera.cpp | UTF-8 | 2,740 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "cocoa/renderer/Camera.h"
#include "cocoa/core/Application.h"
#include "cocoa/events/Input.h"
namespace Cocoa {
Camera::Camera(glm::vec3& position) {
this->m_Transform = Transform(position, glm::vec3(1.0f), glm::vec3(0.0f));
this->m_CameraForward = glm::vec3();
this->m_CameraUp = glm::vec3();
this->m_CameraRight = glm::vec3();
this->m_InverseProjection = glm::mat4();
this->m_OrthoInverseProjection = glm::mat4();
this->m_OrthoView = glm::mat4();
this->m_OrthoInverseView = glm::mat4();
this->AdjustPerspective();
}
void Camera::AdjustPerspective() {
this->CalculateAspect();
this->m_ProjectionMatrix = glm::perspective(m_Fov, m_Aspect, 0.5f, 10000.0f);
this->m_OrthoProjection = glm::ortho(-1920.0f * m_Zoom / 2.0f, 1920.0f * m_Zoom / 2.0f, -1080.0f * m_Zoom / 2.0f, 1080.0f * m_Zoom / 2.0f, 0.5f, 100.0f);
this->m_InverseProjection = glm::inverse(m_ProjectionMatrix);
this->m_OrthoInverseProjection = glm::inverse(m_OrthoProjection);
}
glm::mat4& Camera::GetViewMatrix() {
this->m_CameraForward.x = glm::cos(glm::radians(m_Transform.m_EulerRotation.y)) * glm::cos(glm::radians(m_Transform.m_EulerRotation.x));
this->m_CameraForward.y = glm::sin(glm::radians(m_Transform.m_EulerRotation.x));
this->m_CameraForward.z = glm::sin(glm::radians(m_Transform.m_EulerRotation.y)) * glm::cos(glm::radians(m_Transform.m_EulerRotation.x));
this->m_CameraForward = glm::normalize(m_CameraForward);
this->m_CameraRight = glm::cross(m_CameraUp, glm::vec3(0, 1, 0));
this->m_CameraUp = glm::cross(m_CameraRight, m_CameraForward);
glm::vec3 front = glm::vec3(m_Transform.m_Position.x, m_Transform.m_Position.y, m_Transform.m_Position.z) + m_CameraForward;
m_ViewMatrix = glm::lookAt(m_Transform.m_Position, front, m_CameraUp);
return m_ViewMatrix;
}
glm::mat4& Camera::GetOrthoView() {
glm::vec3 cameraFront = glm::vec3(0, 0, -1) + glm::vec3(m_Transform.m_Position.x, m_Transform.m_Position.y, 0.0f);
glm::vec3 cameraUp = glm::vec3(0, 1.0f, 0);
glm::normalize(cameraUp);
this->m_OrthoView = glm::lookAt(glm::vec3(m_Transform.m_Position.x, m_Transform.m_Position.y, 20), cameraFront, cameraUp);
this->m_OrthoInverseView = glm::inverse(m_OrthoView);
return this->m_OrthoView;
}
void Camera::CalculateAspect() {
// TODO: actually make this calculate window's current aspect
this->m_Aspect = Application::Get()->GetWindow()->GetTargetAspectRatio();
}
glm::vec2 Camera::ScreenToOrtho()
{
return Input::ScreenToOrtho(this);
}
} | true |
9be37b2b25368d4ba3b18aefd4801fac80f4f49e | C++ | SokoloiD/made-cpp-2020-hw | /chuck_allocator/MemChunk.h | UTF-8 | 471 | 2.578125 | 3 | [] | no_license | //
// Created by asokolov on 17.10.2020.
//
#ifndef MEM_ALLOCATOR_MEMCHUNK_H
#define MEM_ALLOCATOR_MEMCHUNK_H
#include <cstddef>
#include <cstdint>
class MemChunk {
public:
MemChunk(const size_t size, MemChunk *prev);
~MemChunk();
MemChunk *getPrev();
size_t getFreeMem();
uint8_t *allocMem(size_t size);
private:
size_t chunkSize_;
size_t allocated_;
uint8_t *buffer_;
MemChunk *prevChunk_;
};
#endif//MEM_ALLOCATOR_MEMCHUNK_H
| true |
47a3e7093220af4b2795c2541c30537f59b27756 | C++ | yimingli718/CSE335_CanadaExperience | /CanadianExperience/Knife.h | UTF-8 | 1,033 | 2.671875 | 3 | [] | no_license | /**
* \file Knife.h
*
* \author Yiming Li
*
* \brief Implement a knife for sparty
*/
#pragma once
#include "ImageDrawable.h"
#include "AnimChannelPoint.h"
/**
* \brief Implemnet the knife for sparty
*/
class CKnife :
public CImageDrawable
{
public:
CKnife(const std::wstring &name, const std::wstring &filename);
/** \brief Default constructor disabled */
CKnife() = delete;
/** \brief Copy constructor disabled */
CKnife(const CKnife &) = delete;
/** \brief Assignment operator disabled */
void operator=(const CKnife &) = delete;
~CKnife();
/// \brief Is this drawable moveable?
/// \returns true
virtual bool IsMovable() { return true; }
void Draw(Gdiplus::Graphics *graphics);
virtual void SetActor(CActor *actor) override;
virtual void SetTimeline(CTimeline *timeline) override;
virtual void SetKeyframe() override;
virtual void GetKeyframe() override;
private:
/// Channel for the head position
CAnimChannelPoint mPositionChannel;
CRotatedBitmap mKnife; ///< Bitmap for the left eye
};
| true |
0a618b648c6ad9a93bd0ef35d1e39406413dbaa4 | C++ | tobiasschulz/call-qt | /src/model-abstract.h | UTF-8 | 1,610 | 2.578125 | 3 | [] | no_license | #ifndef MODEL_ABSTRACT_H
#define MODEL_ABSTRACT_H
#include <QObject>
#include <QPointer>
#include <QAbstractItemModel>
#include "contact.h"
namespace Model
{
class Abstract: public QAbstractItemModel, public ID
{
Q_OBJECT
public:
explicit Abstract(Abstract* parentmodel, QObject* parent = 0);
virtual QString id() const = 0;
virtual int internalSize() const = 0;
virtual int offset(Abstract* submodel) const;
virtual Contact getContact(const QModelIndex& index) const = 0;
virtual User getUser(const QModelIndex& index) const = 0;
int size() const;
int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex& parent = QModelIndex()) const;
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex& child) const;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::DisplayRole);
bool visible() const;
public slots:
void beginSetItems(int oldcount, int newcount);
void endSetItems();
void onStateChanged(int i);
void refresh();
void setConnectionsVisible(bool state);
void setVisible(bool state);
private:
void beginInsertItems(int start, int end);
void endInsertItems();
void beginRemoveItems(int start, int end);
void endRemoveItems();
void changeItems(int start, int end);
protected:
QPointer<Abstract> m_parentmodel;
bool m_showConnections;
bool m_visible;
private:
enum RowOperationState
{
REMOVING, INSERTING, NONE
};
RowOperationState m_rowOperationState;
};
}
#endif // MODEL_ABSTRACT_H
| true |
7300f75a3bf2c6739207e8d94a307334bbf64602 | C++ | coconutpie/COP1334 | /projects/2d-arrays/main.cpp | UTF-8 | 1,089 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>
#include <string>
using namespace std;
const int STUDENTS = 3;
const int ASSIGNMENTS = 4;
const int LOW = 70, HIGH = 100;
int cop1334[STUDENTS][ASSIGNMENTS], total = 0;
void
seed_database() {
for (int i = 0; i < STUDENTS; i++)
{
for (int j = 0; j < ASSIGNMENTS; j++)
cout << (cop1334[i][j] = rand() % (HIGH - LOW + 1) + LOW) << " ";
cout << endl;
}
}
void
list_averages() {
for (int i = 0; i < STUDENTS; i++)
{
for (int j = 0; j < ASSIGNMENTS; j++)
total += cop1334[i][j];
cout << "Average for Student " << i << " = "
<< static_cast<double> (total) / ASSIGNMENTS << endl;
total = 0;
}
}
void
last_bit() {
for (int j = 0; j < ASSIGNMENTS; j++)
{
for (int i = 0; i < STUDENTS; i++)
total += cop1334[i][j];
cout << "Average for Assignment " << j << " = "
<< static_cast<double> (total) / STUDENTS << endl;
total = 0;
}
}
int main()
{
srand(time(0));
seed_database();
cout << endl << endl;
list_averages();
cout << endl << endl;
last_bit();
while(true) {}
}
| true |
13f614994ac5a9cfacb2c82562d6f064d94fcde1 | C++ | lirui233/C-Primer_vs2017 | /C++Primer_vs2017/10.36.cpp | UTF-8 | 271 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
using namespace std;
int main(void)
{
list<int> lst{ 1,2,3,0,5,4,1,0,1 };
auto iter = find(lst.crbegin(), lst.crend(), 0);
cout << *iter << endl;
//cout <<
system("pause");
return 0;
} | true |
425457bd8c74d989c889465af0c5f8af8bad3a86 | C++ | SRomero85/Globant-Bootcamp-TP3 | /TP3/TP3/max_min.cpp | UTF-8 | 1,360 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <limits>
int mainmaxmin() {
int val = 0;
std::cout << "\nEl valor Maximo de un 'int' es: " << std::numeric_limits<int>::max() << std::endl;
std::cout << "El valor Minimo de un 'int' es: " << std::numeric_limits<int>::min() << std::endl;
std::cout << "El valor Maximo de un 'short int' es: " << std::numeric_limits<short int>::max() << std::endl;
std::cout << "El valor Minimo de un 'short int' es: " << std::numeric_limits<short int>::min() << std::endl;
std::cout << "El valor Maximo de un 'char' es: " << std::numeric_limits<char>::max() << std::endl;
std::cout << "El valor Minimo de un 'char' es: " << std::numeric_limits<char>::min() << std::endl;
std::cout << "El valor Maximo de un 'long' es: " << std::numeric_limits<long>::max() << std::endl;
std::cout << "El valor Minimo de un 'long' es: " << std::numeric_limits<long>::min() << std::endl;
std::cout << "El valor Maximo de un 'long long' es: " << std::numeric_limits<long long>::max() << std::endl;
std::cout << "El valor Minimo de un 'long long' es: " << std::numeric_limits<long long>::min() << std::endl;
std::cout << "El valor Maximo de un 'size_t' es: " << std::numeric_limits<size_t>::max() << std::endl;
std::cout << "El valor Minimo de un 'size_t' es: " << std::numeric_limits<size_t>::min() << std::endl;
return 0;
} | true |
86aed1ca2b4f0c6365e0e21a3dccbc5dc29e84cd | C++ | 94rain/openFlights | /algorithm/BFS.h | UTF-8 | 724 | 3.0625 | 3 | [] | no_license | #pragma once
#include <queue>
#include <unordered_map>
#include "../OpenFlight.h"
using std::queue;
using std::vector;
class BFS{
public:
/**
* get the path of all visited airports during BFS
* @param graph the OpenFlight graph for BFS traversal
* @return {vector<Airport>}
*/
vector<Airport> getPath(OpenFlight graph);
/**
* get the number of visited airports during BFS
* @return {int}
*/
int getCount();
/**
* get the ending airport during BFS
* @return {Airport}
*/
Airport getEnd();
private:
vector<Airport> path;
int count;
Airport end;
};
| true |
d9c9d9c9efb0b4fdc52e00d81665fb34e4be9c7c | C++ | zaliasc/hust-lab | /c++/lab/3.cpp | UTF-8 | 11,373 | 3.515625 | 4 | [
"MIT"
] | permissive | //D:/learn/c++/c++_experiment/U201714480_3
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
class STACK
{
int *const elems; //申请内存用于存放栈的元素
const int max; //栈能存放的最大元素个数
int pos; //栈实际已有元素个数,栈空时pos=0;
public:
STACK() : elems(nullptr), max(0), pos(0){}; //默认构造函数
STACK(int m); //初始化栈:最多存m个元素
STACK(const STACK &s); //用栈s拷贝初始化栈
STACK(STACK &&s); //移动构造
virtual int size() const; //返回栈的最大元素个数max
virtual operator int() const; //返回栈的实际元素个数pos
virtual int operator[](int x) const; //取下标x处的栈元素,第1个元素x=0
virtual STACK &operator<<(int e); //将e入栈,并返回栈
virtual STACK &operator>>(int &e); //出栈到e,并返回栈
virtual STACK &operator=(const STACK &s); //赋s给栈,并返回被赋值栈
virtual STACK &operator=(STACK &&s); //移动赋值
virtual void print() const; //打印栈
virtual ~STACK(); //销毁栈
};
// STACK(int m); //初始化栈:最多存m个元素
STACK::STACK(int m) : elems(new int[m]), max(m), pos(0)
{
}
// STACK(const STACK &s); //用栈s拷贝初始化栈
STACK::STACK(const STACK &s) : elems(new int[s.max]), max(s.max), pos(s.pos)
{
for (int i = 0; i < this->pos; i++)
{
this->elems[i] = s.elems[i];
}
}
// STACK(STACK &&s); //移动构造
STACK::STACK(STACK &&s) : elems(s.elems), max(s.max), pos(s.pos)
{
int **p = (int **)&(s.elems);
*p = nullptr;
}
// virtual int size() const; //返回栈的最大元素个数max
int STACK::size() const
{
return this->max;
}
// virtual operator int() const; //返回栈的实际元素个数pos
STACK::operator int() const
{
return this->pos;
}
// virtual int operator[](int x) const; //取下标x处的栈元素,第1个元素x=0
int STACK::operator[](int x) const
{
return this->elems[x];
}
// virtual STACK &operator<<(int e); //将e入栈,并返回栈
STACK &STACK::operator<<(int e)
{
if (this->pos == this->max)
cout << "push failed!" << endl;
else
{
this->elems[pos] = e;
this->pos++;
}
return *this;
}
// virtual STACK &operator>>(int &e); //出栈到e,并返回栈
STACK &STACK::operator>>(int &e)
{
if (this->pos == 0)
cout << "pop failed!" << endl;
else
{
this->pos--;
e = this->elems[pos];
}
return *this;
}
// virtual STACK &operator=(const STACK &s); //赋s给栈,并返回被赋值栈
STACK &STACK::operator=(const STACK &s)
{
if (s.max != this->max)
{
if (this->elems)
delete this->elems;
int **p = (int **)&(this->elems);
*p = new int[s.max];
int *q = (int *)&(this->max);
*q = s.max;
}
this->pos = s.pos;
for (int i = 0; i < this->pos; i++)
{
this->elems[i] = s.elems[i];
}
return *this;
}
//virtual STACK &operator=(STACK &&s); //移动赋值
STACK &STACK::operator=(STACK &&s)
{
this->pos = s.pos;
int **p = (int **)(&(this->elems));
int **q = (int **)(&(s.elems));
int *r = (int *)(&(this->max));
*p = s.elems;
*q = nullptr;
*r = s.max;
return *this;
}
//virtual void print() const; //打印栈
void STACK::print() const
{
for (int i = 0; i < this->pos; i++)
printf("%d ", this->elems[i]);
}
//virtual ~STACK(); //销毁栈
STACK::~STACK()
{
delete[] this->elems;
this->pos = 0;
int **p = (int **)(&(this->elems));
int **q = (int **)(&(this->max));
*p = nullptr;
*q = 0;
}
class QUEUE
{
STACK s1, s2;
public:
QUEUE(int m); //每个栈最多m个元素,要求实现的队列最多能入2m个元素
QUEUE(const QUEUE &q); //用队列q拷贝初始化队列
QUEUE(QUEUE &&q); //移动构造
virtual operator int() const; //返回队列的实际元素个数
virtual int full() const; //返回队列是否已满,满返回1,否则返回0
virtual int operator[](int x) const; //取下标为x的元素,第1个元素下标为0
virtual QUEUE &operator<<(int e); //将e入队列,并返回队列
virtual QUEUE &operator>>(int &e); //出队列到e,并返回队列
virtual QUEUE &operator=(const QUEUE &q); //赋q给队列,并返回被赋值的队列
virtual QUEUE &operator=(QUEUE &&q); //移动赋值
virtual void print() const; //打印队列
virtual ~QUEUE(); //销毁队列
void debug(){
cout<<"s1.size: "<<s1.size()<<" s1.pos: "<<int(s1)<<" ---";
s1.print();
cout << endl;
cout << "s2.size: " << s2.size() << " s2.pos: " << int(s2)<<" ---";
s2.print();
cout<<endl;
}
};
// QUEUE(int m); //每个栈最多m个元素,要求实现的队列最多能入2m个元素
QUEUE::QUEUE(int m) : s1(STACK(m)), s2(STACK(m))
{
//s1 = STACK(m);
//s2 = STACK(m);
}
// QUEUE(const QUEUE &q); //用队列q拷贝初始化队列
QUEUE::QUEUE(const QUEUE &q):s1(q.s1),s2(q.s2){
// s1 = q.s1;
// s2 = q.s2;
}
// QUEUE(QUEUE &&q); //移动构造
QUEUE::QUEUE(QUEUE &&q) : s1(move(q.s1)), s2(move(q.s2))
{
//s1 = move(q.s1);
//s2 = move(q.s2);
}
// virtual operator int() const; //返回队列的实际元素个数
QUEUE::operator int() const{
return int(s1)+int(s2);
}
// virtual int full() const; //返回队列是否已满,满返回1,否则返回0
int QUEUE::full()const{
if(s1.size()==int(s1)&&int(s2)>0)
return 1;
else
return 0;
}
// virtual int operator[](int x) const; //取下标为x的元素,第1个元素下标为0
int QUEUE::operator[](int x) const{
if(x<int(s2))
return s2[int(s2)-x-1];
else if(x<int(s2)+int(s1))
return s1[x-int(s2)];
else return -1;
}
// virtual QUEUE &operator<<(int e); //将e入队列,并返回队列
QUEUE& QUEUE::operator<<(int e){
// debug();
if(int(s1)<s1.size())
{
s1<<e;
return *this;
}
else if(int(s2)==0)
{
for(int i =0;i< s1.size();i++){
int temp = 0;
s1 >> temp;
s2 << temp;
}
s1<<e;
return *this;
}
else
{
cout << "push faled!";
return *this;
}
}
// virtual QUEUE &operator>>(int &e); //出队列到e,并返回队列
QUEUE &QUEUE::operator>>(int &e)
{
//debug();
if (int(s2) > 0)
{
s2 >> e;
return *this;
}
else if(int(s1)>0)
{
for (int i = 0,length = int(s1); i < length; i++)
{
//debug();
int temp = 0;
s1 >> temp;
s2 << temp;
}
s2 >> e;
return *this;
}
else
{
cout<<"pop failed";
return *this;
}
}
// virtual QUEUE &operator=(const QUEUE &q); //赋q给队列,并返回被赋值的队列
QUEUE & QUEUE::operator=(const QUEUE &q){
s1 = q.s1;
s2 = q.s2;
return *this;
}
// virtual QUEUE &operator=(QUEUE &&q); //移动赋值
QUEUE &QUEUE::operator=(QUEUE &&q)
{
s1 = move(q.s1);
s2 = move(q.s2);
return *this;
}
// virtual void print() const; //打印队列
void QUEUE::print() const{
for (int i = int(s2)-1; i >=0; i--)
printf("%d ", s2[i]);
for (int i = 0; i < int(s1); i++)
printf("%d ", s1[i]);
}
// virtual ~QUEUE(); //销毁队列
QUEUE::~QUEUE(){
}
void print_file(const QUEUE &s, ofstream &outfile)
{
for(int i =0;i<int(s);i++)
outfile << s[i] << " ";
}
int main(const int argc, const char **argv)
{
string filename = argv[0];
int temp = filename.find(".exe");
if (temp != filename.npos)
{
string s = filename.substr(0, temp);
filename = s;
}
filename += ".txt";
ofstream outfile(filename);
QUEUE *s = nullptr;
outfile << "S " << atoi(argv[2]) << " ";
QUEUE s1(atoi(argv[2]));
print_file(s1, outfile);
// s1.debug();
s = &s1;
for (int i = 3; i < argc; i++)
{
if (argv[i][0] == '-')
{
switch (argv[i][1])
{
case 'I':
{
bool isoverflow = false;
outfile << "I ";
for (int j = i + 1; j < argc && argv[j][0] != '-'; j++, i++)
{
if (argv[j][0] != '-')
{
//(*s).debug();
if((*s).full())
isoverflow = true;
else
*s << atoi(argv[j]);
}
}
if (isoverflow == true)
{
outfile << 'E' << " ";
i = argc - 1;
break;
}
print_file(*s, outfile);
break;
}
case 'O':
{
bool isoverflow = false;
outfile << "O ";
int e;
for (int j = 0; j < atoi(argv[i + 1]); j++)
{
if (int(*s) > 0)
*s >> e;
else
isoverflow = true;
}
i++;
if (isoverflow == true)
{
outfile << 'E' << " ";
i = argc - 1;
break;
}
print_file(*s, outfile);
break;
}
case 'C':
{
outfile << "C ";
QUEUE s_temp(*s);
s1 = move(s_temp);
s=&s1;
// cout<<"ccccc:::\n";
// (*s).debug();
print_file(*s, outfile);
break;
}
case 'A':
{
outfile << "A ";
i++;
QUEUE s_temp(atoi(argv[i + 1]));
s_temp = *s;
s1 = move(s_temp);
s=&s1;
print_file(*s, outfile);
break;
}
case 'N':
{
outfile << "N " << int(*s) << " ";
break;
}
case 'G':
{
outfile << "G ";
if (atoi(argv[i + 1]) < int(*s) && atoi(argv[i + 1]) >= 0)
outfile << (*s)[atoi(argv[i + 1])] << " ";
else
{
outfile << 'E' << " ";
i = argc - 1;
}
break;
}
}
}
}
outfile.close();
return 0;
} | true |
ec9bad745626a92f98f8abff704130ea94063f21 | C++ | AK2001/Video-management-application | /Management Application/vectordata.cpp | UTF-8 | 1,434 | 3.25 | 3 | [] | no_license | //vectordata.cpp
#include <iomanip>
#include "vectordata.h"
void VectorVideoData::populate(string filename){
ifstream infile;
VideoData anItemdata;
infile.open(filename.c_str());
while(infile){
infile >> anItemdata;
data.push_back(anItemdata);
}
}
bool VectorVideoData::exists (string title){
for(int i=0;i<data.size();i++)
if(data[i].getTitle() == title)
return true;
return false;
}
VideoData& VectorVideoData::findByTitle(string title){
for(int i=0;i<data.size();i++)
if(data[i].getTitle() == title)
return data[i];
}
void VectorVideoData::save(string filename){
ofstream fileOut;
fileOut.open(filename.c_str());
int spacing = 34;//NOTE: if u want the user to be able to enter a title of more than 25 character add +1 for every character
fileOut << left <<setw(spacing)<<setfill(' ')<<"Videos\nTitle"; //Header of the .txt file using the ionmanip library
fileOut << left << setw(spacing-20) << setfill(' ') << "Minutes";
fileOut << left << setw(spacing-22) << setfill(' ') << "Size (mb)";
fileOut << left << "Date (dd/mm/yy)";
fileOut<<endl;
for(int i=0;i<data.size();i++) //Data
fileOut<<data[i]<<endl;
fileOut.close();
}
ostream& operator << (ostream &out, VectorVideoData &vector){
for(int i=0;i<vector.data.size();i++)
out<<vector.data[i]<<endl;
return out;
}
| true |
04cff9aaa96fb9c741b6e013f1e09f1dd09e4ac9 | C++ | ravitejamajeti/Artificial-Intelligence | /Assignment_2/shc.cpp | UTF-8 | 3,604 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
void GeneratePosition(int n, int *ran) {
int i = 0, flag = 0;
while (i < n) {
ran[i] = rand() % n;
/*for (int j = 0; j < i; j++) {
if(ran[i] == ran[j]) {
flag = 1;
}
}
if(flag == 1) {
flag = 0;
continue;
}
*/
cout<<"ran is : "<<ran[i]<<"\n";
i++;
}
}
int fitness(int *ran, int n) {
int fitness = 0, present, present_x, present_y, next, next_x, next_y, count;
for(int i = 0; i < n; i++) {
count = 1;
for(int j = i+1; j < n; j++) {
present = ran[i];
present_x = ran[i];
present_y = i;
next = ran[j];
next_x = ran[j];
next_y = j;
if(present_x + count == next_x && present_y + count == next_y)
fitness++;
else if(present_x + present_y == next_x + next_y)
fitness++;
else if(present_x == next_x)
fitness++;
count++;
}
}
return fitness;
}
int main() {
srand (time(NULL));
int n, i = 0, fit_orig, AR_Flag = 0, initial_position, i_zero, zero_flag = 0, i_min, min_flag = 0, j = 0, opt = 0, turn = 0, count = 0;
cout<<"Enter n for number of queens : \n";
cin>>n;
int all_fit[n], all_fit_min = n * n, global_fit = n * n;
int *positions = new int[n];
while(turn < 100) {
GeneratePosition(n, positions);
j = 0;
count = 0;
while(j < n)
{
initial_position = positions[j];
if(count == 0) {
fit_orig = fitness(positions, n);
cout<<"Starting Fitness is : "<<fit_orig<<"\n";
all_fit_min = fit_orig;
}
for(int i = 0; i < n; i++)
{
positions[j] = i;
all_fit[i] = fitness(positions, n);
cout<<"j is : "<<j<<" i is : "<<i<<" fitness is : "<<all_fit[i]<<"\n";
if(all_fit[i] == 0){
i_zero = i;
zero_flag = 1;
break;
}
if(all_fit[i] < all_fit_min) {
i_min = i;
all_fit_min = all_fit[i];
min_flag = 1;
}
}
cout<<j<<"th column min fitness is : "<<all_fit_min<<"\n";
if(zero_flag == 1) {
cout<<"Zero Fitness Caught \n";
opt++;
all_fit_min = 0;
zero_flag = 0;
positions[j] = i_zero;
break;
}
if(min_flag == 1)
{
cout<<"Inter min caught in "<<j<<"\n";
min_flag = 0;
positions[j] = i_min;
if(j != 0)
AR_Flag = 1;
}
else
positions[j] = initial_position;
if(j == n - 1 && AR_Flag == 1) {
cout<<"Flagged \n";
j = -1;
AR_Flag = 0;
}
count++;
j++;
}
if(global_fit > all_fit_min)
global_fit = all_fit_min;
turn++;
}
cout<<"Min fitness is : "<<global_fit<<"\n";
cout<<"Number of optimizations are : "<<opt<<"\n";
} | true |
4bf907e789bd6154868ae5b91d51ac31e4decd0e | C++ | RuiGuedes/PROG1617_T2 | /Trabalho 2/src/Company.h | UTF-8 | 1,027 | 2.921875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "Line.h"
#include "Driver.h"
#include "Bus.h"
using namespace std;
class Company{
friend void info_bus(Company &SR);
friend void BusWithoutDriver(Company &SR);
friend void atribuir_trabalho(Company &SR);
private:
string name;
string fichDrivers;
string fichLines;
vector<Driver> drivers;
vector<Line> lines;
multimap<unsigned int, vector<Bus>> LineBusData; //Multimap com o ID da linha e um vector com os respetivos autocarros para essa linha
public:
Company(string name, string fichDrivers, string fichLines);
// Get methods
string getName() const;
string getFichDrivers() const;
string getFichLines() const;
vector<Driver> getVecDriver() const;
vector<Line> getVecLines() const;
// Set methods
void setName(string name);
void setDrivers(vector<Driver> drivers);
void setLines(vector<Line> lines);
// Other methods
void addLineBusData(unsigned int LineID, vector<Bus> busData);
};
| true |
94b112a60a69b2e18e2ca50a10b8f6db475244f2 | C++ | stilda/Audio-Visualizer | /Sequence/Converters/ConverterBreakOn3bitsNumbers.cpp | UTF-8 | 957 | 2.59375 | 3 | [] | no_license | #include "ConverterBreakOn3bitsNumbers.h"
#include <vector>
#include "..\StorageCursor.h"
#include "..\Storage.h"
#include <cassert>
float conv_to_bit( const float v )
{
return v < 0.0f ? 0.0f : 1.0f;
}
void ConverterBreakOn3bitsNumbers::process()
{
auto ostor = out_stor<Storage<float>*>(0);
auto istor = in_stor<Storage<float>*>(0);
std::vector<float> & ibuf = istor->tmp_buf();
std::vector<float> & obuf = ostor->tmp_buf();
auto icur = in_cursor(0);
icur->set_sync( 3 );
icur->snapshort( istor );
long lag = icur->lag();
if( lag == 0 )
return;
istor->read( icur->position(), lag, ibuf );
obuf.clear();
if( (int)obuf.capacity() < lag / 3 )
obuf.reserve( lag / 3 );
for( int i = 0; i < (int)ibuf.size(); i += 3 )
{
float v = 1 * conv_to_bit( ibuf[i] ) + 2 * conv_to_bit( ibuf[i+1] ) + 4 * conv_to_bit( ibuf[i+2] );
obuf.push_back( v );
}
ostor->append( obuf );
icur->move_on( lag );
} | true |
e3a984d1e0ce558d306e7bcf22e4e8b82667b192 | C++ | Matheuss26/traffic-light-search-heuristic | /tests/test_graph.cpp | UTF-8 | 3,357 | 2.984375 | 3 | [] | no_license | #include "assert.h"
#include "traffic_graph.h"
#define NUMBER_OF_VERTICES 8
#define EDGE1 {7, 5}
#define EDGE1_WEIGHT 6
#define EDGE2 {5, 2}
#define EDGE2_WEIGHT 10
#define EDGE3 {5, 4}
#define EDGE3_WEIGHT 4
#define CYCLE 20
#define TIMING_7 16
#define TIMING_5 8
#define TIMING_2 4
#define TIMING_4 7
using namespace traffic;
using namespace std;
Graph::Edge edge1 = EDGE1,
edge2 = EDGE2,
edge3 = EDGE3;
class MockGraphImplementation : public Graph {
private:
unordered_map<Vertex, Weight> neighborsOf5;
unordered_map<Vertex, Weight> emptyMap;
public:
MockGraphImplementation() : Graph(NUMBER_OF_VERTICES, CYCLE) {
this->neighborsOf5[edge1.vertex1] = EDGE1_WEIGHT;
this->neighborsOf5[edge2.vertex2] = EDGE2_WEIGHT;
this->neighborsOf5[edge3.vertex2] = EDGE3_WEIGHT;
}
virtual Weight weight(const Graph::Edge& edge) const {
if (edge == edge1) {
return EDGE1_WEIGHT;
} else if (edge == edge2) {
return EDGE2_WEIGHT;
} else if (edge == edge3) {
return EDGE3_WEIGHT;
} else {
return -1;
}
}
virtual const unordered_map<Vertex, Weight>& neighborsOf (Vertex vertex) const {
if (vertex == 5) {
return this->neighborsOf5;
} else {
return this->emptyMap;
}
}
};
int main (void) {
Graph* graph;
Graph::Edge edge1 = EDGE1,
edge2 = EDGE2,
edge3 = EDGE3;
test_case("constructor raises no error") {
graph = new MockGraphImplementation();
assert_true(graph != NULL);
} end_test_case;
test_case("has correct number of vertices") {
assert_equal(graph->getNumberOfVertices(), NUMBER_OF_VERTICES);
} end_test_case;
test_case("has correct cycle") {
assert_equal(graph->getCycle(), CYCLE);
} end_test_case;
test_case("set vertices timings") {
graph->setTiming(7, TIMING_7);
graph->setTiming(5, TIMING_5);
graph->setTiming(2, TIMING_2);
graph->setTiming(4, TIMING_4);
assert_equal(graph->getTiming(edge1.vertex1), TIMING_7);
assert_equal(graph->getTiming(edge1.vertex2), TIMING_5);
} end_test_case;
test_case("penalty between two vertices with edge between them") {
TimeUnit penalty_uv = graph->penalty(edge1.vertex1, edge1.vertex2);
TimeUnit penalty_vu = graph->penalty(edge1.vertex2, edge1.vertex1);
assert_equal(penalty_uv, 6);
assert_equal(penalty_vu, 2);
} end_test_case;
test_case ("penalty between two vertices with no edge between them is 0") {
TimeUnit penalty;
Graph::Edge edge;
for (size_t i = 0; i < NUMBER_OF_VERTICES; i++) {
for (size_t j = 0; j < NUMBER_OF_VERTICES; j++) {
edge = {i, j};
if (edge == edge1 || edge == edge2 || edge == edge3) {
continue;
}
penalty = graph->penalty(i, j);
assert_equal(penalty, 0);
}
}
} end_test_case;
test_case ("total penalty for a vertex") {
TimeUnit penalty;
TimeUnit expectedPenalty = 2+6+5 + 6+6+3;
penalty = graph->vertexPenalty(5);
assert_equal(penalty, expectedPenalty);
} end_test_case;
test_case ("total penalty for a vertex ignoring neighbors penalties") {
TimeUnit penalty;
TimeUnit expectedPenalty = 2+6+5;
penalty = graph->vertexPenaltyOnewayOnly(5);
assert_equal(penalty, expectedPenalty);
} end_test_case;
test_case ("total penalty") {
TimeUnit penalty;
TimeUnit expectedPenalty = 2+6+5;
penalty = graph->totalPenalty();
assert_equal(penalty, expectedPenalty);
} end_test_case;
delete graph;
}
| true |
da56177b3d304acd11cbfd1e9537119c21543e39 | C++ | lnarolski/mearm-stm32f429i | /Middlewares/ST/touchgfx/framework/include/touchgfx/containers/Container.hpp | UTF-8 | 6,415 | 2.921875 | 3 | [
"MIT"
] | permissive | /**
******************************************************************************
* This file is part of the TouchGFX 4.15.0 distribution.
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/**
* @file touchgfx/containers/Container.hpp
*
* Declares the touchgfx::Container class.
*/
#ifndef CONTAINER_HPP
#define CONTAINER_HPP
#include <touchgfx/Callback.hpp>
#include <touchgfx/Drawable.hpp>
namespace touchgfx
{
/**
* A Container is a Drawable that can have child nodes. The z-order of children is determined by
* the order in which Drawables are added to the container - the Drawable added last
* will be front-most on the screen.
*
* This class overrides a few functions in Drawable in order to traverse child nodes.
*
* Note that containers act as view ports - that is, only the parts of children that
* intersect with the geometry of the container will be visible (e.g. setting a
* container's width to 0 will render all children invisible).
*
* @see Drawable
*/
class Container : public Drawable
{
public:
Container()
: Drawable(),
firstChild(0)
{
}
/**
* Adds a Drawable instance as child to this Container. The Drawable added will be
* placed as the element to be drawn last, and thus appear on top of all previously
* added drawables in the Container.
*
* @param [in] d The Drawable to add.
*
* @note Never add a drawable more than once!
*/
virtual void add(Drawable& d);
/**
* Removes a Drawable from the container by removing it from the linked list of
* children. If the Drawable is not in the list of children, nothing happens. It is
* possible to remove an element from whichever Container it is a member of using:
* @code
* if (d.getParent()) d.getParent()->remove(d);
* @endcode
* The Drawable will have the parent and next sibling cleared, but is otherwise left
* unaltered.
*
* @param [in] d The Drawable to remove.
*
* @note This is safe to call even if d is not a child of this Container (in which case nothing happens).
*/
virtual void remove(Drawable& d);
/**
* Removes all children in the Container by resetting their parent and sibling pointers.
* Please note that this is not done recursively, so any child which is itself a
* Container is not emptied.
*/
virtual void removeAll();
/**
* Removes all children by unlinking the first child. The parent and sibling pointers of
* the children are not reset.
*
* @see getFirstChild
*/
virtual void unlink();
/**
* Query if a given Drawable has been added directly to this Container. The search is
* not done recursively.
*
* @param d The Drawable to look for.
*
* @return True if the specified Drawable instance is direct child of this container,
* false otherwise.
*/
virtual bool contains(const Drawable& d);
/**
* Inserts a Drawable after a specific child node. If previous child node is 0, the
* drawable will be inserted as the first element in the list. The first element in the
* list of children is the element drawn first, so this makes it possible to insert a
* Drawable \a behind all previously added children.
*
* @param [in] previous The Drawable to insert after. If null, insert as header.
* @param [in] d The Drawable to insert.
*
* @note As with add, do not add the same drawable twice.
*/
virtual void insert(Drawable* previous, Drawable& d);
/**
* Gets the last child in the list of children in this Container. If this Container is
* touchable (isTouchable()), it will be passed back as the result. Otherwise all \a
* visible children are traversed recursively to find the Drawable that intersects with
* the given coordinate.
*
* @param x The x coordinate of the intersection.
* @param y The y coordinate of the intersection.
* @param [out] last out parameter in which the result is placed.
*
* @see isVisible, isTouchable
*/
virtual void getLastChild(int16_t x, int16_t y, Drawable** last);
virtual void draw(const Rect& invalidatedArea) const;
virtual Rect getSolidRect() const;
/**
* Executes the specified callback function for each child in the Container. The
* callback to execute must have the following prototype: void T::func(Drawable&)
*
* @param [in] function The function to be executed for each child.
*/
virtual void forEachChild(GenericCallback<Drawable&>* function);
/**
* Obtain a pointer to the first child of this container. The first child is the
* Drawable drawn first, and therefore the Drawable \a behind all other children of this
* Container. Useful if you want to manually iterate the children added to this
* container.
*
* @return Pointer to the first drawable added to this container. If nothing has been
* added return zero.
*
* @see getNextSibling
*/
Drawable* getFirstChild()
{
return firstChild;
}
protected:
/**
* Gets a rectangle describing the total area covered by the children of this container.
*
* @return Rectangle covering all children.
*/
virtual Rect getContainedArea() const;
/**
* Calls moveRelative on all children.
*
* @param deltaX Horizontal displacement.
* @param deltaY Vertical displacement.
*/
virtual void moveChildrenRelative(int16_t deltaX, int16_t deltaY);
Drawable* firstChild; ///< Pointer to the first child of this container. Subsequent children can be found through firstChild's nextSibling.
friend class Screen;
/// @cond
virtual void setupDrawChain(const Rect& invalidatedArea, Drawable** nextPreviousElement);
/// @endcond
};
} // namespace touchgfx
#endif // CONTAINER_HPP
| true |
45281bb48fa6fae6f50be16151777d805d34e46d | C++ | amarsgithub/Sorting-Algorithms | /SimpleTimer.cpp | UTF-8 | 460 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include "SimpleTimer.h"
using namespace std;
SimpleTimer::SimpleTimer()
{
// Get the current time
start = highResClock::now();
}
SimpleTimer::SimpleTimer(string name)
{
// Get the current time
this->name = name;
start = highResClock::now();
}
SimpleTimer::~SimpleTimer()
{
end = highResClock::now();
elapsed = end - start;
cout << "Elapsed time for " << name << ": "<< elapsed.count() << " seconds\n";
}
| true |
692409b3892b9a9f8cd1f2a24277d0d78128ed4f | C++ | xxsytriskxx/Pokemon-SwSh-Seed-Generator | /SeedGenerator/Source/Fields/Gender.cpp | UTF-8 | 1,730 | 3.1875 | 3 | [] | no_license |
#include <map>
#include "Gender.h"
namespace SeedGenerator{
std::string to_string(GenderRatio ratio){
switch (ratio){
case GenderRatio::MALE:
return "100% Male";
case GenderRatio::MALE_88:
return "88% Male";
case GenderRatio::MALE_75:
return "75% Male";
case GenderRatio::EVEN:
return "50% male/female";
case GenderRatio::FEMALE_75:
return "75% female";
case GenderRatio::FEMALE_88:
return "88% female";
case GenderRatio::FEMALE:
return "100% female";
case GenderRatio::GENDERLESS:
return "genderless";
default:
throw "Invalid Gender";
}
}
const std::map<std::string, GenderRatio> GENDER_RATIO_TOKENS{
{"MALE", GenderRatio::MALE},
{"MALE_88", GenderRatio::MALE_88},
{"MALE_75", GenderRatio::MALE_75},
{"EVEN", GenderRatio::EVEN},
{"FEMALE_75", GenderRatio::FEMALE_75},
{"FEMALE_88", GenderRatio::FEMALE_88},
{"FEMALE", GenderRatio::FEMALE},
{"GENDERLESS", GenderRatio::GENDERLESS},
};
GenderRatio read_genderratio(const std::string& token){
auto iter = GENDER_RATIO_TOKENS.find(token);
if (iter == GENDER_RATIO_TOKENS.end()){
throw "Invalid GenderRatio: " + token;
}
return iter->second;
}
const std::map<std::string, GenderFilter> GENDER_FILTER_TOKENS{
{"Unspecified", GenderFilter::UNSPECIFIED},
{"Male", GenderFilter::MALE},
{"Female", GenderFilter::FEMALE},
};
GenderFilter read_gender(const std::string& token){
auto iter = GENDER_FILTER_TOKENS.find(token);
if (iter == GENDER_FILTER_TOKENS.end()){
throw "Invalid GenderFilter: " + token;
}
return iter->second;
}
}
| true |
0631ad9c2d8cda840876df5a8b60205ca73d32ad | C++ | classygroup/sems | /core/sip/ssl_settings.h | UTF-8 | 2,794 | 2.578125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <map>
#include <string>
using std::vector;
using std::map;
using std::string;
struct settings
{
std::string certificate;
std::string certificate_key;
std::vector<std::string> ca_list;
virtual ~settings();
bool checkCertificateAndKey(const char *interface_name,
const char* interface_type,
const char *role_name);
virtual const char *getProtocolName() = 0;
};
class tls_settings : public settings
{
public:
virtual ~tls_settings(){}
enum Protocol {
TLSv1,
TLSv1_1,
TLSv1_2
};
static Protocol protocolFromStr(const std::string& proto) {
if(proto == "TLSv1") {
return TLSv1;
} else if(proto == "TLSv1.1") {
return TLSv1_1;
}
return TLSv1_2;
}
static std::string protocolToStr(Protocol proto) {
if(proto == TLSv1) {
return "TLSv1";
} else if(proto == TLSv1_1) {
return "TLSv1.1";
}
return "TLSv1.2";
}
virtual const char *getProtocolName();
std::vector<Protocol> protocols;
};
class dtls_settings : public settings
{
public:
virtual ~dtls_settings(){}
enum Protocol {
DTLSv1,
DTLSv1_2
};
static Protocol protocolFromStr(const std::string& proto) {
if(proto == "DTLSv1") {
return DTLSv1;
} else {
return DTLSv1_2;
}
}
static std::string protocolToStr(Protocol proto) {
if(proto == DTLSv1) {
return "DTLSv1";
} else {
return "DTLSv1.2";
}
}
virtual const char *getProtocolName();
std::vector<Protocol> protocols;
std::vector<uint16_t> srtp_profiles;
};
template<class SettingsType>
class ssl_client_settings : public SettingsType
{
public:
ssl_client_settings()
: verify_certificate_chain(false),
verify_certificate_cn(false)
{}
~ssl_client_settings(){}
bool verify_certificate_chain;
bool verify_certificate_cn;
};
typedef ssl_client_settings<tls_settings> tls_client_settings;
typedef ssl_client_settings<dtls_settings> dtls_client_settings;
template<class SettingsType>
class ssl_server_settings : public SettingsType
{
public:
ssl_server_settings()
: require_client_certificate(false),
verify_client_certificate(false)
{}
~ssl_server_settings(){}
bool require_client_certificate;
bool verify_client_certificate;
std::vector<std::string> cipher_list;
std::vector<std::string> macs_list;
std::string dhparam;
};
typedef ssl_server_settings<tls_settings> tls_server_settings;
typedef ssl_server_settings<dtls_settings> dtls_server_settings;
| true |
99490d47b2eece27d654eb2030bfd481de8b2d69 | C++ | masumr/problem_solve | /code/392.cpp | UTF-8 | 1,206 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
vector<ll>convert(string a)
{
stringstream ss(a);
vector<ll>v;
ll num;
while(ss>>num)v.push_back(num);
return v;
}
int main()
{
string a;
int i;
while(1)
{
getline(cin,a);
vector<ll>v=convert(a);
int count=0;
int y=v.size()-1;
for(int i=0; i<v.size(); i++)
{
if(v[i]==0)
{
count++;
}
else break;
}
if(count==v.size()){cout<<0;}
else
{
ll x=v[count];
if(x!=1 && x!=-1){
if(x<0) x=-x;
cout<<x;
}
int y=v.size()-count;
cout<<"x^"<<y;
count++;
y--;
for(i=count;i<v.size()-1;i++){
if(v[i]!=0){
x=v[i];
cout<<" + ";
if(x!=-1 && x!=1)
cout<<x;
cout<<"x^"<<y;
}
y--;
}
if(v[i]!=0) cout<<" + "<<v[i];
}
cout<<endl;
v.clear();
}
}
| true |
2fc247a38d0755d39f796f256f92ec79f739db6f | C++ | TadashiHiramatsu/nkGame_11 | /nkEngine/nkEngine/_Graphics/3DObject/Model/ModelData/nkMeshNode.h | SHIFT_JIS | 2,018 | 3.0625 | 3 | [] | no_license | /**
* bVm[hNX̒`.
*/
#pragma once
#include"nkNode.h"
namespace nkEngine
{
class Material;
/**
* bVm[hNX.
*/
class MeshNode : public INode
{
public:
/**
* _obt@\.
*/
struct VertexBufferS
{
Vector4 Pos = Vector4(0.0f, 0.0f, 0.0f, 1.0f); //!< _W.
Vector2 Tex = Vector2::Zero; //!< UVW.
Vector3 Normal = Vector3::Zero; //!< @xNg.
Vector3 Tangent = Vector3::Zero; //!< ڃxNg
};
public:
/**
* RXgN^.
*/
MeshNode()
{
}
/**
* fXgN^.
*/
~MeshNode()
{
}
/**
* 쐬.
*
* @param fbxNode FBXSDK̃m[hNX.
* @param parent ẽ|C^.
* @param modelData ff[^.
*/
void Create(FbxNode* fbxNode,Transform* parent, ModelData* modelData)override;
/**
* `.
*/
void Render()override;
/**
* [hs擾.
*/
const Matrix& GetWorldMatrix()
{
return Transform_.WorldMatrix_;
}
/**
* Ή}eAԍ擾.
*/
int GetMaterialNum() const
{
return MaterialNum_;
}
/**
* _WXg擾.
*/
vector<Vector3>& GetVertexPosList()
{
return VertexPosList_;
}
private:
/**
* _obt@̍쐬.
*/
void CreateVertexBuffer(FbxMesh* fbxMesh);
/**
* ڃxNg쐬.
*
* @param vertexList _Xg.
*/
void CreateTanget(vector<VertexBufferS>& vertexList);
/**
* }eA̍쐬.
*
* @param fbxNode FBXSDK̃m[hNX.
*/
void CreateMaterial(FbxNode* fbxNode,ModelData* modelData);
private:
/** _WXg. */
vector<Vector3> VertexPosList_;
/** _obt@. */
VertexBuffer VertexBuffer_;
/** _. */
UINT VertexCount_ = 0;
/** Ή}eAԍ. */
int MaterialNum_ = -1;
/** UVZbg. */
vector<string> UVSetNameList_;
};
} | true |
5f593c6df95de6d602a85acfc0f96328c211ccf3 | C++ | mandome/TVS-Device-SDK | /Linux SDK/samples/sample_recv/testrecv.cpp | UTF-8 | 3,897 | 2.71875 | 3 | [] | no_license | /**
* @file
* @author kangrong
* @date 2017/8/28
* @brief 示例代码:设备接收手机指令进行配网
* @version 0.1.0
* @note
*/
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <cstdlib>
#include <sstream>
#include "aisdk_common_api.h"
#include "aisdk_account_online.h"
#include "aisdk_recv.h"
using namespace std;
void * myGetApThread(void *args){
string apList;
/**
* getAPList(apList);获取ap列表需要实现
*
*/
aisdkRecvSendApListByJson(apList.c_str(),apList.size());
return NULL;
}
void * myConnectApThread(void *args){
//连接ap,需要实现
//连接成功就发送成功给SDK。
aisdkRecvSendConnectState(AISDKConnectState::OK);
//aisdkRecvSendConnectState(AISDKConnectState::FAIL);
return NULL;
}
void callback(int cmd, char* data, int dataLen, void* userData, int userDataLen, void *extra, int extraLen)
{
// 任何情况下,不要阻塞回调线程。
string result(data, dataLen);
cout << "callback cmd: " << cmd << " result:"<<result<<endl;
switch(cmd) {
case AISDK_CMD_RECV_GET_INFO:{
cout<<"CMD: AISDK_CMD_RECV_GET_INFO"<<endl;
aisdkRecvSendDeviceInfo("deviceSerialNum", "productId", "AP_NAME", "wlan0", NULL);
break;
}
case AISDK_CMD_RECV_ON_BIND_SUCCESS:{
//账号登录
cout<<"CMD: AISDK_CMD_BIND_ON_BIND_SUCCESS"<<endl;
/**
* 可以通过以下代码获得clientId
char* clientId=NULL;
int ret=aisdkGetAccountClientId(&clientId);
*/
break;
}
case AISDK_CMD_RECV_CONNECT_AP:{
cout<<"CMD: AISDK_CMD_BIND_CONNECT_AP"<<endl;
/**
* 解析json数据,连接ap。并将连接状态发送给SDK。
*
*
*/
pthread_t connectApThread;
pthread_create(&connectApThread, NULL, myConnectApThread, NULL);
break;
}
case AISDK_CMD_RECV_GET_AP_LIST:{
//完成
cout<<"CMD: AISDK_CMD_BIND_GET_AP_LIST"<<endl;
pthread_t getApThread;
pthread_create(&getApThread,NULL,myGetApThread,NULL);
break;
}
case AISDK_CMD_RECV_LOGOUT:{
// 账号登出
cout<<"CMD: AISDK_CMD_BIND_LOGOUT"<<endl;
break;
}
case AISDK_CMD_RECV_RESTORE:{
// 恢复出厂设置。
cout<<"CMD: AISDK_CMD_BIND_RESTORE"<<endl;
break;
}
case AISDK_CMD_RECV_CONNECT_AP_STATUS:{
// 上层可以忽略
cout<<"CMD: AISDK_CMD_BIND_CONNECT_AP_STATUS"<<endl;
break;
}
default:
cout<<"CMD: OTHER"<<endl;
break;
}
}
/**
* 程序后面跟一个参数,指定读取的录音文件。
* @param argc
* @param argv
* @return
*/
int main(int argc, char *argv[])
{
//先设置回调函数
aisdkSetCallback(callback);
//初始化SDK
int res = aisdkInit(".", "1234", "asdf");
if(res != 0) {
std::cerr << "init iva fail, err:" << res << std::endl;
return -2;
}
std::string cmd;
while(true) {
std::cout << "cmd>>> 1:退出" << std::endl;
std::cin >> cmd;
int ran_num = rand() % 4;
std::cout << "cmd:" << cmd << std::endl;
if (cmd == "1") {
std::cout << "退出测试程序" << std::endl;
break;
} else {
std::cerr << "cmd:" << cmd << ", not match 1/2/3/4/5" << std::endl;
}
sleep(5); // 由于异步操作,主线程等待5s
}
return 0;
} | true |
2c329b597a65df8a42864436ad2f8495714023d9 | C++ | grandmaster789/scimitar | /scimitar/util/typemap.inl | UTF-8 | 1,433 | 3.265625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "typemap.h"
#include "algorithm.h"
namespace scimitar::util {
template <typename T>
void TypeMap::insert(T* ptr) {
std::type_index key(typeid(T));
if (!contains(m_Keys, key)) {
m_Keys .push_back(key);
m_Values.push_back(ptr);
}
else
throw std::runtime_error("Cannot store multiple pointers of the same type");
}
template <typename T>
void TypeMap::remove(T* ptr) {
std::type_index key(typeid(T));
auto it = find(m_Keys, key);
if (it != m_Keys.end()) {
size_t position = std::distance(std::begin(m_Keys), it);
m_Keys.erase(it);
m_Values.erase(std::begin(m_Values) + position);
}
else
throw std::runtime_error("Type could not be found in this container");
}
template <typename T>
const T* TypeMap::get() const {
std::type_index key(typeid(T));
auto it = find(m_Keys, key);
if (it == std::cend(m_Keys))
return nullptr;
else {
size_t position = std::distance(std::cbegin(m_Keys), it);
return static_cast<const T*>(*(std::cbegin(m_Values) + position));
}
}
template <typename T>
T* TypeMap::get() {
std::type_index key(typeid(T));
auto it = std::find(
std::begin(m_Keys),
std::end(m_Keys),
key
);
if (it == std::end(m_Keys))
return nullptr;
else {
size_t position = std::distance(std::begin(m_Keys), it);
// convert from void* to T*
return static_cast<T*>(*(std::begin(m_Values) + position));
}
}
} | true |
d4fcdfbe810307fd08ea2cffc384ba2339c58942 | C++ | chaudhariyash10/Algorithms | /Dyanamic Programming/Knapsack/Coin Change count Minimum number of coins Required.cpp | UTF-8 | 835 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int minimumNumberOfCoinsRequired(int coins[], int n, int sum)
{
int dp[n + 1][sum + 1];
for (int i = 0; i < sum + 1; i++)
dp[0][i] = INT_MAX - 1;
for (int i = 1; i < n + 1; i++)
dp[i][0] = 0;
for (int i = 0; i < sum + 1; i++)
if (i % coins[0] == 0)
dp[1][i] = i / coins[0];
else
dp[1][i] = INT_MAX - 1;
for (int i = 2; i < n + 1; i++)
for (int j = 1; j < sum + 1; j++)
{
if (coins[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = min(dp[i][j - coins[i - 1]] + 1, dp[i - 1][j]);
}
return dp[n][sum];
}
int main()
{
int coins[] = {1, 2, 3};
int sum = 7;
cout << minimumNumberOfCoinsRequired(coins, 3, sum);
} | true |
b7b2225332013cd465eb082caa7b537378f80e3c | C++ | taceroc/Herr | /Estudio/1.cpp | UTF-8 | 1,123 | 3.5625 | 4 | [] | no_license | #include <cstdio>
#include <math.h>
double f(double x, double a, double b, double c);
int main(void)
{
double a = 1e-17;
double b = -1e17;
double c = 1e17;
double x;
double x1; double x2; double x11; double x22;
if(a!=0)
{
x11 = b+(sqrt(pow(b,2)-4*a*c));
x1 = (-2*c)/x11;
x22 = b-(sqrt(pow(b,2)-4*a*c));
x2 = (-2*c)/x22;
std::printf("La raiz positiva es = %.16f\n", x1);
std::printf("La raiz negativa es = %.16f\n", x2);
std::printf("f(%.16f) = %f\n",x1,f(x1,a,b,c));
std::printf("f(%.16f) = %f\n",x2,f(x2,a,b,c));
}
else
{
if(b!=0)
{
x1 = -c/b;
std::printf("La raiz es = %f\n", x1);
std::printf("f(%f) = %f\n",x1,f(x1,a,b,c));
}
else
{
if(c==0)
{
std:: printf("x puede ser cualquier numero ya que f(x) = %f\n", f(x,a,b,c));
}
else
{
std:: printf("La ecuacion no tiene solucion ya que f(x) = %f\n", f(x,a,b,c));
}
}
}
return 0;
}
double f(double x, double a, double b,double c)
{
double f;
f = a * (pow(x,2)) + b * x + c;
return f;
}
| true |
71be19bbbb5bf2527403157773d07b3b044620aa | C++ | heowoohyuk/OOP | /termproject/block.cpp | UHC | 1,767 | 3.1875 | 3 | [] | no_license | #include "block.h"
//
block::block(int color) {
this->color = color;
this->set_location(2, 0);
}
//
block::~block() {
this->color = 0;
}
//
int block::get_color() {
return this->color;
}
// xǥ
int block::get_x() {
return this->x;
}
// yǥ
int block::get_y() {
return this->y;
}
// 츸
void block::set_group(color_block *group) {
this->group = group;
}
//
color_block* block::get_group() {
return this->group;
}
// ġ ϱ
void block::set_location(int x, int y) {
this->x = x;
this->y = y;
}
// ̵ ?
bool block::can_left() {
return false;
}
// ̵?
bool block::can_right() {
return false;
}
// Ʒ ?
bool block::can_down() {
return false;
}
// ̵
void block::right() {
array_2d::delete_block(this->get_x(), this->get_y());
this->set_location(this->get_x() + 1, this->get_y());
}
// ̵
void block::left() {
array_2d::delete_block(this->get_x(), this->get_y());
this->set_location(this->get_x() - 1, this->get_y());
}
// Ʒ
void block::down() {
array_2d::delete_block(this->get_x(), this->get_y());
this->set_location(this->get_x(), this->get_y() + 1);
}
// ѹ濡 Ʒ
void block::down_all() {
int x = 0;
array_2d::delete_block(this->get_x(), this->get_y());
while (array_2d::block_array[this->get_y() + x][this->get_x()] != 0) {
array_2d::delete_block(this->get_x(), this->get_y() + x);
this->set_location(this->get_x(), this->get_y() + x);
x++;
}
}
// ġⰡ?
// ߰?
// ġ
// ĥѰ ã
| true |
487718b6dc5bf878872ccb3fc4a0c9411fd16f75 | C++ | roddehugo/utprofiler | /dao/CursusDAO.cpp | UTF-8 | 11,876 | 2.796875 | 3 | [] | no_license | #include "dao/CursusDAO.h"
#include "dao/CategorieDAO.h"
#include <QDebug>
QMap<int, Cursus *> CursusDAO::findAll(){
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
if (!query.exec("SELECT * FROM cursus;")){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
while (query.next()){
QSqlRecord rec = query.record();
const int id = rec.value("id").toInt();
const QString c = rec.value("code").toString();
const QString t = rec.value("titre").toString();
const int maxSem = rec.value("maxsemestres").toInt();
const int ects = rec.value("ects").toInt();
const int p = rec.value("parent").toInt();
const int prevSem = rec.value("previsionsemestres").toInt();
if (!Map.contains(id)) {
QMap<QString,int> ectsmap = getEctsMap(id);
LogWriter::writeln("Cursus.cpp","Lecture du cursus : " + c);
Cursus* cursus;
if(p != 0){
Cursus* par = find(p);
cursus=new Cursus(id,c,t,ects,maxSem,prevSem,par,ectsmap);
}else{
cursus=new Cursus(id,c,t,ects,maxSem,prevSem,NULL,ectsmap);
}
Map.insert(id,cursus);
}
}
return Map;
}catch(UTProfilerException e){
LogWriter::writeln("Cursus::findAll()",e.getMessage());
}
}
Cursus* CursusDAO::find(const int& id){
try{
if (Map.contains(id)) {
LogWriter::writeln("Cursus.cpp","Lecture du cursus depuis la map : " + Map.value(id)->getCode());
return Map.value(id);
}
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("SELECT * FROM cursus WHERE id = :id;");
query.bindValue(":id",id);
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
if(query.first()){
QSqlRecord rec = query.record();
const int id = rec.value("id").toInt();
const QString c = rec.value("code").toString();
const QString t = rec.value("titre").toString();
const int cects = rec.value("ects").toInt();
const int maxSem = rec.value("maxsemestres").toInt();
const int prevSem = rec.value("previsionsemestres").toInt();
const int p = rec.value("parent").toInt();
LogWriter::writeln("Cursus.cpp","Lecture du cursus : " + c);
QMap<QString,int> ectsmap = getEctsMap(id);
Cursus* cursus;
if(p != 0){
Cursus* par = find(p);
cursus=new Cursus(id,c,t,cects,maxSem,prevSem,par,ectsmap);
}else{
cursus=new Cursus(id,c,t,cects,maxSem,prevSem,NULL,ectsmap);
}
Map.insert(id,cursus);
return cursus;
}else{
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
}catch(UTProfilerException e){
LogWriter::writeln("Cursus::find()",e.getMessage());
}
}
Cursus *CursusDAO::findByCode(const QString &str)
{
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("SELECT * FROM cursus WHERE code = :code;");
query.bindValue(":code",str);
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
if(query.first()){
QSqlRecord rec = query.record();
const int id = rec.value("id").toInt();
const QString c = rec.value("code").toString();
const QString t = rec.value("titre").toString();
const int ects = rec.value("ects").toInt();
const int maxSem = rec.value("maxsemestres").toInt();
const int prevSem = rec.value("previsionsemestres").toInt();
const int p = rec.value("parent").toInt();
if (Map.contains(id)) {
LogWriter::writeln("Cursus.cpp","Lecture du cursus depuis la map : " + str);
return Map.value(id);
}
LogWriter::writeln("Cursus.cpp","Lecture du cursus : " + c);
QMap<QString,int> ectsmap = getEctsMap(id);
Cursus* cursus;
if(p != 0){
Cursus* par = find(p);
cursus=new Cursus(id,c,t,ects,maxSem,prevSem,par,ectsmap);
}else{
cursus=new Cursus(id,c,t,ects,maxSem,prevSem,NULL,ectsmap);
}
Map.insert(id,cursus);
return cursus;
}else{
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
}catch(UTProfilerException e){
LogWriter::writeln("CursusDAO::findByCode()",e.getMessage());
}
}
bool CursusDAO::update(Cursus* obj){
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("UPDATE cursus SET (code=:code, titre=:titre, ects=:ects, maxsemestres=:maxsemestres, previsionsemestres=:previsionsemestres, parent=:parent) WHERE id = :id ;");
query.bindValue(":id", obj->ID());
query.bindValue(":code", obj->getCode() );
query.bindValue(":titre", obj->getTitre() );
query.bindValue(":maxsemestres", obj->getMaxSemestres() );
query.bindValue(":previsionsemestres", obj->getPrevisionSemestres() );
query.bindValue(":ects", obj->getEcts() );
if(obj->getParent()){
query.bindValue(":parrent", obj->getParent()->ID() );
}else{
query.bindValue(":parrent", 0 );
}
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
return false;
}else{
LogWriter::writeln("CursusDAO.cpp","Modification du cursus : " + obj->getCode());
return true;
}
}catch(UTProfilerException e){
LogWriter::writeln("CursusDAO::update()",e.getMessage());
return false;
}
}
bool CursusDAO::remove(Cursus* obj){
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("DELETE FROM cursus WHERE id = :id ;");
query.bindValue(":id", obj->ID());
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
return false;
}else{
LogWriter::writeln("CursusDAO.cpp","Suprression du cursus : " + obj->getCode());
query.prepare("DELETE FROM categorie_cursus_decorator WHERE idcursus = :id ;");
query.bindValue(":id", obj->ID());
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
Map.erase(Map.find(obj->ID()));
return true;
}
}catch(UTProfilerException e){
LogWriter::writeln("CursusDAO::remove()",e.getMessage());
return false;
}
}
bool CursusDAO::create(Cursus *obj){
QSqlQuery query(Connexion::getInstance()->getDataBase());
try{
query.prepare("INSERT INTO cursus (code, titre, ects, maxsemestres, previsionsemestres, parent) VALUES (:code, :titre, :ects, :maxsemestres, :previsionsemestres, :parent);");
query.bindValue(":code", obj->getCode() );
query.bindValue(":titre", obj->getTitre() );
query.bindValue(":ects", obj->getEcts() );
query.bindValue(":maxsemestres", obj->getMaxSemestres() );
query.bindValue(":previsionsemestres", obj->getPrevisionSemestres() );
if(obj->getParent()){
query.bindValue(":parrent", obj->getParent()->ID() );
}else{
query.bindValue(":parrent", 0 );
}
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
return false;
}else{
int id = query.lastInsertId().toInt();
obj->setID(id);
Map.insert(id,obj);
LogWriter::writeln("CursusDAO.cpp","Création du cursus : " + obj->getCode());
QMap<QString, int> cat = obj->getCredits();
query.prepare("INSERT INTO categorie_cursus_decorator (idcursus, idcategorie, ects) VALUES (:idcursus, :idcategorie, :ects);");
for (QMap<QString, int>::const_iterator i = cat.begin(); i != cat.end(); ++i) {
int idcat = CategorieDAO::getInstance()->findByStr(i.key());
query.bindValue(":idcursus", obj->ID() );
query.bindValue(":idcategorie", idcat );
query.bindValue(":ects", i.value() );
if (!query.exec()){
throw UTProfilerException("La requète a échoué : " + query.lastQuery());
}
LogWriter::writeln("CursusDAO.cpp","Ajout de la reference categorie : " + QString::number(idcat));
}
return true;
}
}catch(UTProfilerException e){
LogWriter::writeln("CursusDAO::create()",e.getMessage());
}
}
QStringList CursusDAO::getStringList(const QString colonne)
{
QStringList liste;
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("SELECT "+colonne+" FROM cursus;");
if (!query.exec()){
throw UTProfilerException("La requête a échoué : " + query.lastQuery());
}
while (query.next()){
QSqlRecord rec = query.record();
liste<<(rec.value(colonne).toString());
}
}catch(UTProfilerException e){
LogWriter::writeln("Categorie::getColonne()",e.getMessage());}
return liste;
}
QMap<QString, int> CursusDAO::getEctsMap(const unsigned int id)
{
QMap<QString,int> ectsmap;
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("SELECT c.id ,cat.titre, ccd.ects FROM cursus c JOIN categorie_cursus_decorator ccd ON ccd.idcursus = c.id JOIN categories cat ON cat.id = ccd.idcategorie WHERE c.id = :id;");
query.bindValue(":id",id);
if (!query.exec()){
throw UTProfilerException("La requête a échoué : " + query.lastQuery());
}
while (query.next()){
QSqlRecord rec = query.record();
ectsmap.insert(rec.value("titre").toString(),rec.value("ects").toInt());
}
return ectsmap;
}catch(UTProfilerException e){
LogWriter::writeln("CursusDAO::getEctsMap()",e.getMessage());}
}
QMap<QString, int > CursusDAO::computePercent(unsigned int id)
{
QMap<QString,int > ectsmap;
try{
QSqlQuery query(Connexion::getInstance()->getDataBase());
query.prepare("SELECT categories.titre, SUM(cud.ects) as somme "
"FROM cursus LEFT JOIN uvs_cursus ON cursus.id = uvs_cursus.idcursus "
"LEFT JOIN inscriptions ON inscriptions.uv = uvs_cursus.iduv "
"LEFT JOIN categorie_uv_decorator cud ON cud.iduv = uvs_cursus.iduv "
"LEFT JOIN categories ON categories.id = cud.idcategorie "
"WHERE inscriptions.resultat IN ('A','B','C','D','E') "
"AND cursus.id = :id GROUP BY categories.titre;");
query.bindValue(":id",id);
if (!query.exec()){
throw UTProfilerException("La requête a échoué : " + query.lastQuery());
}
while (query.next()){
QSqlRecord rec = query.record();
ectsmap.insert(rec.value("titre").toString(), rec.value("somme").toInt());
}
return ectsmap;
}catch(UTProfilerException e){
LogWriter::writeln("CusrsusDAO::computePercent()",e.getMessage());}
}
| true |
ac2abf2af9dccf924dbf339d442a20181fd51c2e | C++ | PhantomFS/Alexis-Coding-Ellis-2019 | /cpp/T1A03-Loop-Alexis.cpp | UTF-8 | 883 | 3.046875 | 3 | [
"MIT"
] | permissive | #define NAME "Player"
#include <stdio.h>
int * triangle(int num){
int * temp;
int * triangle1 [num];
for (int i = 0; i < num; i++) {
triangle1[i] = &(triangle1[i][i+1]);
for (int j = 0; j < i+1; j++) {
if (j == 0 || j == i) {
triangle1[i][j] = (1);
} else {
triangle1[i][j] = (triangle1[i-1][j-1]) + (triangle1[i-1][j]);
temp = &triangle1[i][j];
}
}
}
return temp;
}
int main(){
int a, c, d;
printf("Please enter a number");
scanf("%i",&a);
int * myAr[a];
myAr[a] = triangle (a);
for(int x = 0; x < a; x++ ){
myAr[x] = &(myAr[x][x+1]);
for(int * y = 0; y < myAr[x]; y++ ){
printf("%s, ",&myAr[x][y]);
}
printf("\n");
}
} | true |
1431968817a2c1bae0f7cfdb62512a7a9e7e85f1 | C++ | myunpe/fireattack | /Classes/GameEffect.h | UTF-8 | 1,241 | 2.609375 | 3 | [
"MIT"
] | permissive | //
// GameEffect.h
// Tetris
//
// Created by Yoshida Mitsunobu on 2014/07/20.
//
//
#ifndef __Tetris__GameEffect__
#define __Tetris__GameEffect__
#include "cocos2d.h"
/**
* ゲームのいろいろなエフェクトを管理する
* このクラスで行われるエフェクトが再生されている間は操作不可になる
*/
USING_NS_CC;
class GameEffect : public Sprite {
public:
GameEffect(void);
virtual ~GameEffect(void);
virtual void onEnter() override;
virtual void onExit() override;
bool onTouchBegan(Touch* touch, Event* event);
void onTouchMoved(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
Rect getRect();
void move(float delta);
void setDispatchTouch(bool isEnable);
//Playerを生成するようのメソッド
static GameEffect* create(const std::string &filename);
//失敗した時のエフェクト
void failEffect(std::function<void()> callback);
//クリアした時のエフェクト
void clearEffect(std::function<void()> callback);
private:
void endEffect();
private:
Vec2 beginTouch;
float power;
bool isDispatch;
};
#endif /* defined(__Tetris__GameEffect__) */
| true |
ac3cd8118b85e7ae0bc06463ccde65f408dd3ffe | C++ | xhw994/LeetCode | /LeetCode/LeetCode201_250/203_Remove_Linked_List_Elements.cpp | UTF-8 | 476 | 2.640625 | 3 | [] | no_license | #include "../..//LeetCodeCpp/LeetCode201_250.h"
#include "../..//LeetCodeCpp/Common.h"
using namespace std;
using namespace LeetCode;
ListNode* LeetCode::LeetCode201_250::removeElements(ListNode* head, int val) {
if (!head) return nullptr;
ListNode* p = nullptr, *c = head;
while (c) {
if (c->val == val) {
if (!p) head = c->next;
else p->next = c->next;
}
else p = c;
c = c->next;
}
return head;
} | true |
e541ca5b5adca2d76bf7ab36b7f52c1e78b5490e | C++ | MarkHCole/CSC-228 | /Q3 Linked.cpp | UTF-8 | 2,909 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std;
// implementing the dynamic List ADT using Linked List
class Node {
private:
int data;
Node* nextNodePtr;
public:
Node() {}
void setData(int d) {
data = d;
}
int getData() {
return data;
}
void setNextNodePtr(Node* nodePtr) {
nextNodePtr = nodePtr;
}
Node* getNextNodePtr() {
return nextNodePtr;
}
};
class SortedList {
private:
Node* headPtr;
public:
SortedList() {
headPtr = new Node();
headPtr->setNextNodePtr(0);
}
Node* getHeadPtr() {
return headPtr;
}
bool isEmpty() {
if (headPtr->getNextNodePtr() == 0)
return true;
return false;
}
void insertAtIndex(int insertIndex, int data) {
Node* currentNodePtr = headPtr->getNextNodePtr();
Node* prevNodePtr = headPtr;
int index = 0;
while (currentNodePtr != 0) {
if (index == insertIndex)
break;
prevNodePtr = currentNodePtr;
currentNodePtr = currentNodePtr->getNextNodePtr();
index++;
}
Node* newNodePtr = new Node();
newNodePtr->setData(data);
newNodePtr->setNextNodePtr(currentNodePtr);
prevNodePtr->setNextNodePtr(newNodePtr);
}
void insertSortedOrder(int data) {
Node* currentNodePtr = headPtr->getNextNodePtr();
Node* prevNodePtr = headPtr;
while (currentNodePtr != 0) {
if (data < currentNodePtr->getData()) {
Node* newNodePtr = new Node();
newNodePtr->setData(data);
newNodePtr->setNextNodePtr(currentNodePtr);
prevNodePtr->setNextNodePtr(newNodePtr);
return;
}
currentNodePtr = currentNodePtr->getNextNodePtr();
prevNodePtr = prevNodePtr->getNextNodePtr();
}
Node* newNodePtr = new Node();
newNodePtr->setData(data);
newNodePtr->setNextNodePtr(NULL);
prevNodePtr->setNextNodePtr(newNodePtr);
return;
}
void IterativePrint() {
Node* currentNodePtr = headPtr->getNextNodePtr();
while (currentNodePtr != 0) {
cout << currentNodePtr->getData() << " ";
currentNodePtr = currentNodePtr->getNextNodePtr();
}
cout << endl;
}
};
int main() {
using namespace std::chrono;
int listSize;
cout << "Enter the number of elements you want to insert: ";
cin >> listSize;
int maxValue;
cout << "Enter the maximum value for an element in the list: ";
cin >> maxValue;
srand(time(NULL));
SortedList integerList; // Create an empty list
high_resolution_clock::time_point t1 = high_resolution_clock::now();
for (int i = 0; i < listSize; i++) {
int value = 1 + rand() % maxValue;
integerList.insertSortedOrder(value);
}
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double, std::nano> insertionTime_nano = t2 - t1;
//integerList.IterativePrint();//troubleshooting
cout << "Avg insertion time per element " << (insertionTime_nano.count() / listSize) << endl;
system("pause");
return 0;
} | true |
89970479ea6a3a36d69c601b4700c71d193aa00b | C++ | TeamTurtleF14/CS113TurtleGame | /include/LayoutGen.hpp | UTF-8 | 2,346 | 3.421875 | 3 | [] | no_license | /*
* LayoutGen.hpp
* Header file for the Layout Generator
* Creates room objects, attaches rooms properly when directed.
*/
#ifndef _LAYOUTGEN_HPP_
#define _LAYOUTGEN_HPP_
#include "Room.hpp"
#include <vector>
#include <utility> // std::pair, std::make_pair
class LayoutGen {
public:
int NumRooms; // # of rooms for entire level
int CriticalPathRooms; // # of rooms from from start to end, including entrance/exit
int AdditionalRooms; // # of rooms outside of Crit Path
int SidePathRooms; // # of rooms are on the sides, leads to dead ends
int CircularPathRooms; // # of rooms that are part of a circle, leads back to self
std::vector< std::pair<int, int> > RoomCoords; // coordinates for layout generation
Room* HeadRoom;
std::vector<Room*> RoomContainer; // Used to hold references to all Room* for deletion
LayoutGen(); // Creates total rooms, will add to NumRooms here
~LayoutGen(); // Destructor
// Creates the critical path, in a set of coords
std::vector<std::pair<int, int> > CriticalPathGen();
std::vector<std::pair<int,int> > CriticalPathGen(unsigned int CriticalPathRooms);
// Checks to see if there are 'forward' rooms ahead, without reaching end
bool roomForwardCheck(Room* start, Room* next, int forward);
// Helper function, translates directions where previous room was in relation to current
// EX: go North into a new room, you came into new room from South
char incomingDirection(Room* prev, Room* current);
// // returns true, if a room is within the critical path
// bool isinCriticalPath(Room* current);
// helper function, checks to see if a pair is already in the Coordinate list
bool isinCoords(std::pair<int, int>);
// This versions takes in integer inputs
bool isinCoords(int x, int y);
// creates the CriticalPath()
void generateCriticalPath();
// adds on the SidePaths
void generateSidePaths();
// adds on more rooms that will become a circular path
void generateCircularPaths();
// Helper function to help simplify getting directions from string
char OppositeDirection(char direction);
// Functions below are for outside calls
Room* getHeadRoom(); // Returns room pointer to starting room
std::vector<Room*> getRoomList(); //Returns room list, makes for easy deletion
// void getRoomList(std::vector<Room*> RoomList);
};
#endif /* _LAYOUTGEN_HPP_ */
| true |
de7def603a190a715e4d3c476c097c85e5c7b5a4 | C++ | bryan-pakulski/emulators | /chip8/src/cpu/cpu.cpp | UTF-8 | 2,017 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "cpu.hpp"
#include <vector>
#include <fstream>
cpu::cpu(memoryc8* m, display* g) {
mem = m;
gfx = g;
op_lookup = new opcodes();
drawFlag = true;
clearScreen = true;
I = 0;
PC = 0x200;
op = 0;
sp = 0;
}
cpu::~cpu() {
delete op_lookup;
}
/**
* Resets the keypad array to 0
*/
void cpu::clearKeyPad() {
memset(keypad, 0, 0xF * sizeof(*keypad));
}
/**
* Sets a key at index to be pressed
*/
void cpu::setKey(int index, unsigned char value) {
keypad[index] = value;
}
/**
* Checks if a key at index is pressed
*/
bool cpu::keyPressed(int index) {
return (keypad[index] == 0x1);
}
/**
* Getter and setter functions for member variables
*/
unsigned short cpu::getI() {
return I;
}
void cpu::setI( unsigned short value ) {
I = value;
}
unsigned short cpu::getPC() {
return PC;
}
void cpu::stepPC( int value ) {
PC += ( 2 * value );
}
void cpu::setPC( unsigned short value) {
PC = value;
}
unsigned short cpu::getOP() {
return op;
}
void cpu::setOP( unsigned short value ) {
op = value;
}
unsigned short cpu::getV(int index) {
return V[index];
}
void cpu::setV(int index, unsigned short value) {
V[index] = value;
}
/**
* Pops from stack
*/
unsigned short cpu::popStack() {
--sp;
unsigned short val = stack[sp];
stack[sp] = 0;
return val;
}
/**
* Pushes to stack and increments stack pointer to stop data overwriting
*
* @param value The value to push
*/
void cpu::pushStack(unsigned short value) {
stack[sp] = value;
++sp;
}
/**
* Fetch next opcode
*
* @return Returns combined opcodes to form a single instruction
*/
unsigned short cpu::fetchNextOpcode() {
return mem->get(PC) << 8 | (mem->get(PC+1) & 0x00FF);
}
/**
* Call function mapping from opcode and update other logic i.e. timers
*/
void cpu::cycle(cpu* proc) {
// Fetch opcode
proc->setOP(proc->fetchNextOpcode());
// Increment PC before execution
proc->stepPC(1);
// Decode opcode and execute
func_p opCallFunction = proc->op_lookup->get(proc->getOP());
opCallFunction(proc);
} | true |
0dc1822cd0919854d72878813616bc03ac54dde5 | C++ | ggonnella/gfaviz | /src/gfa/alignment.cpp | UTF-8 | 2,175 | 3.09375 | 3 | [
"ISC",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "gfa/alignment.h"
GfaAlignment::GfaAlignment() {
is_set = false;
lengths[0] = 0;
lengths[1] = 0;
}
GfaAlignment::~GfaAlignment() {
//if (cigar)
//free(cigar);
}
void GfaAlignment::createFromCigarString(char *str, unsigned long len) {
unsigned long idx;
bool char_found = false;
bool digit_found = false;
bool last_start = 0;
if (len == 1 && str[0] == '*') { /* 1st alternative: '*' */
is_set = false;
return;
}
else {/* Just allowing MIDP as of GFA2 */
for (idx = 0; idx < len; idx++) {
if ((str[idx] == 'M' || str[idx] == 'I' || str[idx] == 'D' || str[idx] == 'P') && digit_found == true) { /* MIDP*/
unsigned long numops = atol(str+last_start);
if (str[idx] == 'M') {
lengths[0]+=numops;
lengths[1]+=numops;
} else if (str[idx] == 'I') {
lengths[1]+=numops;
} else if (str[idx] == 'D') {
lengths[0]+=numops;
} else if (str[idx] == 'P') {
//TODO: ???
} else if (str[idx] == 'X') {
//TODO: ???
} else if (str[idx] == '=') {
//TODO: ???
} else if (str[idx] == 'S') {
//TODO: ???
} else if (str[idx] == 'H') {
//TODO: ???
}
GfaCigarOp op;
op.type = (GfaCigarOpType)str[idx];
op.count = numops;
ops.push_back(op);
char_found = true;
digit_found = false;
last_start = idx+1;
} else if (isdigit(str[idx])) {
digit_found = true;
char_found = false;
} else {
//throw fatal_error() << "Invalid Cigar string '" << str << "'.";
}
}
}
if (!char_found) {
//throw fatal_error() << "Invalid Cigar string '" << str << "'.";
}
is_set = true;
}
ostream& operator<< (ostream &out, const GfaAlignment &a) {
a.print(out);
return out;
}
void GfaAlignment::print(ostream &out) const {
if (is_set) {
for (GfaCigarOp op : ops) {
out << op.count << (char)op.type;
}
} else {
out << '*';
}
}
unsigned long GfaAlignment::getLength(int idx) const {
return lengths[idx];
}
bool GfaAlignment::isSet() const {
return is_set;
}
| true |
f4da52caca6adf9c027c596d0a821400d084d78d | C++ | TenFifteen/SummerCamp | /lbc_lintcode/445-cosine-similarity.cc | UTF-8 | 777 | 3.578125 | 4 | [] | no_license | /*
题目:28 % Cosine Similarity new 容易
题目大意:
给定两个向量,求其cos角度
解题思路:
根据公式直接算
遇到的问题:
没有问题。
*/
class Solution {
public:
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: Cosine similarity.
*/
double cosineSimilarity(vector<int> A, vector<int> B) {
// write your code here
if (A.size() == 0 || A.size() != B.size()) return 2.0;
double mulA = 0, mulB = 0, mulAB = 0;
for (int i = 0; i < A.size(); ++i) {
mulA += A[i]*A[i];
mulB += B[i]*B[i];
mulAB += A[i]*B[i];
}
if (mulA == 0 || mulB == 0) return 2.0;
return mulAB/sqrt(mulA)/sqrt(mulB);
}
};
| true |
e8620a602a54dd97f73c20e2aeefa2d7cf03d569 | C++ | sycinf/ArchSyn | /archsyn_regression/spmv/test_spmv.cpp | UTF-8 | 1,455 | 3.078125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#define DIM 50
#define SPARSITY 2
float spmv( float* y, int* ptr, float* valArray, int* indArray, float* xvec, int dim);
float spmv_sw(float* y, int* ptr, float* valArray, int* indArray, float* xvec, int dim)
{
int kbegin = 0;
float rtVal = 0.0;
for(int s=0; s<dim; s++)
{
int kend = ptr[s];
float curY = 0.0;
for(int k=kbegin; k<kend; k++)
{
curY=curY+valArray[k]*xvec[indArray[k]];
}
y[s] = curY;
kbegin = kend;
rtVal = curY;
}
return rtVal;
}
int main()
{
int* ptr = (int*)malloc(DIM*sizeof(int));
int totalNum = 0;
int i;
for(i=0; i<DIM; i++)
{
int numEle = rand()%(DIM/SPARSITY);
totalNum+=numEle;
ptr[i] = totalNum;
}
float* xvec = (float*)malloc(DIM*sizeof(float));
for(i=0; i<DIM; i++)
{
xvec[i] = (float)(i);
}
int* indArray;
float* valArray;
valArray=(float*) malloc(totalNum*sizeof(float));
int j;
for(j=0; j<totalNum; j++)
{
valArray[j] = (float)(rand()%DIM);
}
indArray=(int*)malloc(totalNum*sizeof(int));
int k;
for(k=0; k<totalNum; k++)
indArray[k]=rand()%DIM;
float* y = (float*)malloc(DIM*sizeof(float));
for(k=0; k<DIM; k++)
{
y[k] = 0.0;
}
float* y2 = (float*)malloc(DIM*sizeof(float));
for(k=0; k<DIM; k++)
{
y2[k] = 0.0;
}
spmv(y,ptr,valArray,indArray,xvec,DIM);
spmv_sw(y2,ptr,valArray,indArray,xvec,DIM);
for(k=0; k<DIM; k++)
printf("%f ",y[k]);
printf("\n");
for(k=0; k<DIM; k++)
printf("%f ",y2[k]);
}
| true |
b588de67aff03c968a92aff6117ecb702597d458 | C++ | JohanJacobs/Sorting-Algorithms | /src/demo.cpp | UTF-8 | 2,163 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include "Helpers/Timer.h"
//sorting algorithms
#include "Sort/BubbleSort.h"
#include "Sort/SelectionSort.h"
#include "Sort/InsertionSort.h"
#include "Sort/ShellSort.h"
//data files from https://www.coursera.org/learn/algorithms-part1
std::vector<std::string> FileNames ={
"Data/1Kints.txt",
"Data/2Kints.txt",
"Data/4Kints.txt",
"Data/8Kints.txt",
"Data/16Kints.txt",
"Data/32Kints.txt"
};
std::vector<int> GetData(const std::string& filename)
{
std::fstream file;
file.open(filename, std::ios::in);
if (!file.is_open())
{
std::cout << filename << " not found!\n";
exit(EXIT_FAILURE);
}
std::vector<int> data;
std::string line;
while (std::getline(file, line))
{
data.push_back(std::stoi(line));
}
file.close();
return data;
}
/// <summary>
/// Template function that takes a sorting function to run data over
/// </summary>
/// <param name="func">Sortingfunction that accepts an std::vector<int></param>
/// <param name="label">Label name for the sorting function</param>
template<typename TF>
void SimulateSort(TF&& func, const std::string& label)
{
std::cout << "Running " << label << "\n";
std::vector < std::pair<std::string, long long>> m_Results;
for (size_t FileID = 0; FileID < FileNames.size(); FileID++)
{
// load relevant data set
auto data = GetData(FileNames[FileID]);
JTime::Stopwatch stopwatch(FileNames[FileID], false);
// run the sorting function provided
func(data);
// save the results
m_Results.push_back(std::make_pair(FileNames[FileID], stopwatch.Elapsed()));
}
// print results
for (auto v : m_Results)
{
std::cout << " " << v.first << ": " << v.second << " microseconds (" << v.second / 1000 << " ms).\n";
}
std::cout << "\n";
}
int main()
{
std::cout << "Running sorting algorithms.\n\n";
//other sorting
SimulateSort(ShellSort::ShellSort, "ShellSort");
SimulateSort(InsertionSort::InsertionSort, "InsertionSort");
SimulateSort(SelectionSort::SelectionSort,"SelectionSort");
SimulateSort(BubbleSort::BubbleSort, "BubbleSort");
return EXIT_SUCCESS;
} | true |
3487f5a5d8c857613a8fbf9b61eb614585fcd328 | C++ | vesoft-inc/nebula | /src/common/base/test/EitherOrTest.cpp | UTF-8 | 9,811 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include <gtest/gtest.h>
#include "common/base/Base.h"
#include "common/base/EitherOr.h"
namespace nebula {
TEST(EitherOr, ConstructFromDefault) {
{
EitherOr<bool, std::string> result;
ASSERT_TRUE(result.isVoid());
}
{
EitherOr<int16_t, uint16_t> result;
ASSERT_TRUE(result.isVoid());
}
{
EitherOr<char*, std::string> result;
ASSERT_TRUE(result.isVoid());
}
}
TEST(EitherOr, ConstructFromValue) {
{
EitherOr<bool, std::string> result(true);
ASSERT_FALSE(result.isVoid());
ASSERT_TRUE(result.isLeftType());
EXPECT_TRUE(result.left());
}
{
EitherOr<int, std::string> result("Hello World");
ASSERT_FALSE(result.isVoid());
ASSERT_FALSE(result.isLeftType());
EXPECT_EQ("Hello World", result.right());
}
{
static char str[] = "Hello World";
EitherOr<char*, std::string> result(str);
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ(str, result.left());
}
{
EitherOr<char*, std::string> result(6, 'a');
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("aaaaaa", result.right());
}
}
TEST(EitherOr, ConstructFromTaggedValue) {
{
// This will cause compile failure
// EitherOr<int16_t, uint16_t> result(1);
EitherOr<int16_t, uint16_t> result(kConstructLeft, 1);
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ(1, result.left());
}
{
EitherOr<int16_t, uint16_t> result(kConstructRight, 65535);
ASSERT_TRUE(result.isRightType());
EXPECT_EQ(65535U, result.right());
}
}
TEST(EitherOr, ReturnFromFunctionCall) {
{
auto foo = []() -> EitherOr<float, std::string> { return "Hello World"; };
auto result = foo();
ASSERT_FALSE(result.isVoid());
ASSERT_FALSE(result.isLeftType());
EXPECT_EQ("Hello World", result.right());
}
{
auto foo = []() -> EitherOr<int, std::string> { return 101; };
auto result = foo();
ASSERT_FALSE(result.isVoid());
ASSERT_FALSE(result.isRightType());
EXPECT_EQ(101, result.left());
}
{
auto foo = []() -> EitherOr<int16_t, int32_t> { return static_cast<int16_t>(101); };
auto result = foo();
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ(101, result.left());
}
}
TEST(EitherOr, ReturnFromMoveOnlyValue) {
// return move only from anonymous value
{
auto foo = []() -> EitherOr<int, std::unique_ptr<std::string>> {
return std::make_unique<std::string>("SomeValue");
};
auto result = foo();
ASSERT_FALSE(result.isVoid());
ASSERT_FALSE(result.isLeftType());
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("SomeValue", *result.right());
}
// return move only from named value
{
auto foo = []() -> EitherOr<int, std::unique_ptr<std::string>> {
auto ptr = std::make_unique<std::string>("SomeValue");
return ptr;
};
auto result = foo();
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("SomeValue", *result.right());
}
}
TEST(EitherOr, CopyConstructFromDefault) {
EitherOr<int, std::string> result1;
auto result2 = result1;
ASSERT_TRUE(result2.isVoid());
}
TEST(EitherOr, CopyConstructFromValue) {
{
EitherOr<int, std::string> result1(101);
auto result2 = result1;
ASSERT_FALSE(result1.isVoid());
ASSERT_FALSE(result2.isVoid());
ASSERT_EQ(101, result1.left());
ASSERT_EQ(101, result2.left());
}
{
EitherOr<int, std::string> result1("Something");
auto result2 = result1;
ASSERT_FALSE(result1.isVoid());
ASSERT_FALSE(result2.isVoid());
ASSERT_EQ("Something", result1.right());
ASSERT_EQ("Something", result2.right());
}
{
EitherOr<int16_t, std::string> r1("Hello World");
EitherOr<int32_t, std::string> r2 = r1;
ASSERT_TRUE(r1.isRightType());
ASSERT_TRUE(r2.isRightType());
EXPECT_EQ(r1.right(), r2.right());
}
{
EitherOr<int16_t, std::string> r1(256);
EitherOr<int32_t, std::string> r2 = r1;
ASSERT_TRUE(r1.isLeftType());
ASSERT_TRUE(r2.isLeftType());
EXPECT_EQ(r1.left(), r2.left());
}
}
TEST(EitherOr, CopyAssignFromDefault) {
EitherOr<int, std::string> result1;
decltype(result1) result2;
result2 = result1;
ASSERT_TRUE(result1.isVoid());
ASSERT_TRUE(result2.isVoid());
}
TEST(EitherOr, CopyAssignFromValue) {
{
EitherOr<int, std::string> result1(101);
decltype(result1) result2;
result2 = result1;
ASSERT_FALSE(result1.isVoid());
ASSERT_FALSE(result2.isVoid());
ASSERT_TRUE(result1.isLeftType());
ASSERT_TRUE(result2.isLeftType());
EXPECT_EQ(101, result1.left());
EXPECT_EQ(101, result2.left());
}
{
EitherOr<int, std::string> result1("SomeValue");
decltype(result1) result2;
result2 = result1;
ASSERT_TRUE(result1.isRightType());
ASSERT_TRUE(result2.isRightType());
ASSERT_EQ("SomeValue", result1.right());
ASSERT_EQ("SomeValue", result2.right());
}
{
EitherOr<int16_t, std::string> r1("Hello World");
EitherOr<int32_t, std::string> r2;
r2 = r1;
ASSERT_TRUE(r1.isRightType());
ASSERT_TRUE(r2.isRightType());
EXPECT_EQ(r1.right(), r2.right());
r1 = 256;
r2 = r1;
ASSERT_TRUE(r1.isLeftType());
ASSERT_TRUE(r2.isLeftType());
EXPECT_EQ(r1.left(), r2.left());
}
}
TEST(EitherOr, MoveConstructFromDefault) {
EitherOr<int, std::string> result1;
auto result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_TRUE(result2.isVoid());
}
TEST(EitherOr, MoveConstructFromValue) {
{
EitherOr<int, std::string> result1(101);
auto result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_FALSE(result2.isVoid());
ASSERT_TRUE(result2.isLeftType());
EXPECT_EQ(101, result2.left());
}
{
EitherOr<int, std::string> result1("SomeValue");
auto result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_TRUE(result2.isRightType());
EXPECT_EQ("SomeValue", result2.right());
}
{
EitherOr<int16_t, std::string> r1("Hello World");
EitherOr<int32_t, std::string> r2 = std::move(r1);
ASSERT_TRUE(r1.isVoid());
ASSERT_TRUE(r2.isRightType());
EXPECT_EQ("Hello World", r2.right());
}
{
EitherOr<int16_t, std::string> r1(256);
EitherOr<int32_t, std::string> r2 = std::move(r1);
ASSERT_TRUE(r1.isVoid());
ASSERT_TRUE(r2.isLeftType());
EXPECT_EQ(256, r2.left());
}
}
TEST(EitherOr, MoveAssignFromDefault) {
EitherOr<int, std::string> result1;
decltype(result1) result2;
result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_TRUE(result2.isVoid());
}
TEST(EitherOr, MoveAssignFromValue) {
{
EitherOr<int, std::string> result1(101);
decltype(result1) result2;
result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_FALSE(result2.isVoid());
ASSERT_TRUE(result2.isLeftType());
EXPECT_EQ(101, result2.left());
}
{
EitherOr<int, std::string> result1("SomeValue");
decltype(result1) result2;
result2 = std::move(result1);
ASSERT_TRUE(result1.isVoid());
ASSERT_TRUE(result2.isRightType());
EXPECT_EQ("SomeValue", result2.right());
}
{
EitherOr<int16_t, std::string> r1("Hello World");
EitherOr<int32_t, std::string> r2;
r2 = std::move(r1);
ASSERT_TRUE(r1.isVoid());
ASSERT_TRUE(r2.isRightType());
EXPECT_EQ("Hello World", r2.right());
r1 = 256;
r2 = std::move(r1);
ASSERT_TRUE(r1.isVoid());
ASSERT_TRUE(r2.isLeftType());
EXPECT_EQ(256, r2.left());
}
}
TEST(EitherOr, AssignFromValue) {
{
EitherOr<int, std::string> result;
result = 101;
ASSERT_FALSE(result.isVoid());
EXPECT_EQ(101, result.left());
result = "SomeValue";
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("SomeValue", result.right());
}
{
EitherOr<int, std::string> result;
result = "SomeValue";
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("SomeValue", result.right());
result = 101;
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ(101, result.left());
}
{
EitherOr<std::unique_ptr<std::string>, std::string> result;
auto val = std::make_unique<std::string>("Hello World");
result = std::move(val);
ASSERT_TRUE(!val);
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ("Hello World", *result.left());
auto str = std::string("SomeValue");
result = std::move(str);
ASSERT_TRUE(str.empty());
ASSERT_TRUE(result.isRightType());
EXPECT_EQ("SomeValue", result.right());
}
{
EitherOr<int16_t, int32_t> result;
result = static_cast<int16_t>(101);
ASSERT_TRUE(result.isLeftType());
EXPECT_EQ(101, result.left());
result = static_cast<int32_t>(202);
ASSERT_TRUE(result.isRightType());
EXPECT_EQ(202, result.right());
}
}
TEST(EitherOr, MoveOutValue) {
EitherOr<int, std::string> result("SomeValue");
ASSERT_FALSE(result.isVoid());
EXPECT_EQ("SomeValue", result.right());
auto str = std::move(result).right();
ASSERT_TRUE(result.isVoid());
EXPECT_EQ("SomeValue", str);
}
TEST(EitherOr, SelfAssignment) {
{
EitherOr<int, std::string> r("SomeValue");
r = r;
ASSERT_TRUE(r.isRightType());
EXPECT_EQ("SomeValue", r.right());
}
{
EitherOr<int, std::string> r("SomeValue");
r = std::move(r);
ASSERT_TRUE(r.isRightType());
EXPECT_EQ("SomeValue", r.right());
}
}
TEST(EitherOr, Destruct) {
auto ptr = std::make_shared<std::string>("SomeValue");
ASSERT_EQ(1UL, ptr.use_count());
{
EitherOr<int, std::shared_ptr<std::string>> result;
result = ptr;
ASSERT_TRUE(result.isRightType());
EXPECT_EQ(2UL, ptr.use_count());
auto ptr2 = result.right();
ASSERT_EQ(3UL, ptr.use_count());
}
ASSERT_EQ(1UL, ptr.use_count());
}
} // namespace nebula
| true |
e81e3a89b646b47c1a7b4d7762640524795a0c4a | C++ | PathwayAnalysisPlatform/ProteoformNetworks | /src/Cpp/base/bits.h | UTF-8 | 10,919 | 3 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #ifndef BASE_BITS_H
#define BASE_BITS_H
#include "functional.h"
#include "intrinsic.h"
#include <cstddef>
#include <type_traits>
namespace base {
/*template<typename T>
struct word_type;
template<typename T>
using word_type_t = typename word_type<T>::type;
template<typename T> requires std::is_integral_v<T>
struct word_type<T> {
using type = T;
};*/
template<typename T>
struct word_type {
using type = T;
};
template<typename T>
using word_type_t = typename word_type<T>::type;
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t word_granularity( ) noexcept {
return bit_size<T>( );
}
template<typename T> //requires std::is_integral_v<T>
constexpr T bitmask(std::size_t i, std::size_t n) noexcept {
return ((T(n != bit_size<T>( )) << n) - 1) << i;
}
template<typename T> //requires std::is_integral_v<T>
constexpr T bitmask(const T& v, std::size_t i, std::size_t n) noexcept {
return v & bitmask<T>(i, n);
}
template<typename T> //requires std::is_integral_v<T>
constexpr T bitmask_from(const T& v, std::size_t i) noexcept {
return v & bitmask<T>(i, bit_size(v) - i);
}
template<typename T> //requires std::is_integral_v<T>
constexpr T bitmask_until(const T& v, std::size_t i) noexcept {
return v & bitmask<T>(0, i);
}
template<typename T> //requires std::is_integral_v<T>
constexpr T get_n_bits(const T& v, std::size_t i, std::size_t n) noexcept {
return bitmask_until(v >> i, n);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void and_n_bits(T& v, std::size_t i, std::size_t n, const identity_t<T>& s) noexcept {
v &= ~(bitmask_until(~s, n) << i);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void or_n_bits(T& v, std::size_t i, std::size_t n, const identity_t<T>& s) noexcept {
v |= bitmask_until(s, n) << i;
}
template<typename T> //requires std::is_integral_v<T>
constexpr void xor_n_bits(T& v, std::size_t i, std::size_t n, const identity_t<T>& s) noexcept {
v ^= bitmask_until(s, n) << i;
}
template<typename T> //requires std::is_integral_v<T>
constexpr void reset_n_bits(T& v, std::size_t i, std::size_t n) noexcept {
and_n_bits(v, i, n, T(0));
}
template<typename T> //requires std::is_integral_v<T>
constexpr void set_n_bits(T& v, std::size_t i, std::size_t n) noexcept {
or_n_bits(v, i, n, ~T(0));
}
template<typename T> //requires std::is_integral_v<T>
constexpr void flip_n_bits(T& v, std::size_t i, std::size_t n) noexcept {
xor_n_bits(v, i, n, ~T(0));
}
template<typename T> //requires std::is_integral_v<T>
constexpr void write_n_bits(T& v, std::size_t i, std::size_t n, const identity_t<T>& s) noexcept {
reset_n_bits(v, i, n);
or_n_bits(v, i, n, s);
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool get_bit(const T& v, std::size_t i) noexcept {
return get_n_bits(v, i, 1);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void and_bit(T& v, std::size_t i, bool b) noexcept {
and_n_bits(v, i, 1, b);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void or_bit(T& v, std::size_t i, bool b) noexcept {
or_n_bits(v, i, 1, b);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void xor_bit(T& v, std::size_t i, bool b) noexcept {
xor_n_bits(v, i, 1, b);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void reset_bit(T& v, std::size_t i) noexcept {
and_bit(v, i, false);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void set_bit(T& v, std::size_t i) noexcept {
or_bit(v, i, true);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void flip_bit(T& v, std::size_t i) noexcept {
xor_bit(v, i, true);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void write_bit(T& v, std::size_t i, bool b) noexcept {
reset_bit(v, i);
or_bit(v, i, b);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void and_bits(T& v, const identity_t<T>& s) noexcept {
and_n_bits(v, 0, bit_size(v), s);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void or_bits(T& v, const identity_t<T>& s) noexcept {
or_n_bits(v, 0, bit_size(v), s);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void xor_bits(T& v, const identity_t<T>& s) noexcept {
xor_n_bits(v, 0, bit_size(v), s);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void write_bits(T& v, const identity_t<T>& s) noexcept {
write_n_bits(v, 0, bit_size(v), s);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void reset_bits(T& v) noexcept {
reset_n_bits(v, 0, bit_size(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr void set_bits(T& v) noexcept {
set_n_bits(v, 0, bit_size(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr void flip_bits(T& v) noexcept {
flip_n_bits(v, 0, bit_size(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool none_bits(const T& v) noexcept {
return v == T(0);
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool all_bits(const T& v) noexcept {
return v == ~T(0);
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool any_bits(const T& v) noexcept {
return !none_bits(v);
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool none_n_bits(const T& v, std::size_t i, std::size_t n) noexcept {
return none_bits(bitmask(v, i, n));
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool all_n_bits(const T& v, std::size_t i, std::size_t n) noexcept {
return all_bits(v | ~bitmask<T>(i, n));
}
template<typename T> //requires std::is_integral_v<T>
constexpr bool any_n_bits(const T& v, std::size_t i, std::size_t n) noexcept {
return !none_n_bits(v, i, n);
}
constexpr std::size_t popcount(unsigned char v) noexcept {
return __builtin_popcount(v);
}
constexpr std::size_t popcount(unsigned short v) noexcept {
return __builtin_popcount(v);
}
constexpr std::size_t popcount(unsigned int v) noexcept {
return __builtin_popcount(v);
}
constexpr std::size_t popcount(unsigned long v) noexcept {
return __builtin_popcountl(v);
}
constexpr std::size_t popcount(unsigned long long v) noexcept {
return __builtin_popcountll(v);
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t popcount(const T& v) noexcept {
return popcount(std::make_unsigned_t<T>(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t popcount_n(const T& v, std::size_t i, std::size_t n) noexcept {
return popcount(bitmask(v, i, n));
}
constexpr void byte_swap(std::uint8_t& v) noexcept {
return;
}
constexpr void byte_swap(std::uint16_t& v) noexcept {
// v = __builtin_bswap16(v);
}
constexpr void byte_swap(std::uint32_t& v) noexcept {
// v = __builtin_bswap32(v);
}
constexpr void byte_swap(std::uint64_t& v) noexcept {
// v = __builtin_bswap64(v);
}
template<typename T> //requires std::is_integral_v<T>
constexpr void byte_swap(T& v) noexcept {
byte_swap(reinterpret_cast<std::make_unsigned_t<T>&>(v));
}
constexpr std::size_t find_first_set_bit(unsigned char v) noexcept {
return (v != 0 ? __builtin_ctz(v) : bit_size(v));
}
constexpr std::size_t find_first_set_bit(unsigned short v) noexcept {
return (v != 0 ? __builtin_ctz(v) : bit_size(v));
}
constexpr std::size_t find_first_set_bit(unsigned int v) noexcept {
return (v != 0 ? __builtin_ctz(v) : bit_size(v));
}
constexpr std::size_t find_first_set_bit(unsigned long v) noexcept {
return (v != 0 ? __builtin_ctzl(v) : bit_size(v));
}
constexpr std::size_t find_first_set_bit(unsigned long long v) noexcept {
return (v != 0 ? __builtin_ctzll(v) : bit_size(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t find_first_set_bit(const T& v) noexcept {
return find_first_set_bit(std::make_unsigned_t<T>(v));
}
constexpr std::size_t find_last_set_bit(unsigned char v) noexcept {
return (v != 0 ? bit_size(v) - __builtin_clz(v) - 1 : bit_size(v));
}
constexpr std::size_t find_last_set_bit(unsigned short v) noexcept {
return (v != 0 ? bit_size(v) - __builtin_clz(v) - 1 : bit_size(v));
}
constexpr std::size_t find_last_set_bit(unsigned int v) noexcept {
return (v != 0 ? bit_size(v) - __builtin_clz(v) - 1 : bit_size(v));
}
constexpr std::size_t find_last_set_bit(unsigned long v) noexcept {
return (v != 0 ? bit_size(v) - __builtin_clzl(v) - 1 : bit_size(v));
}
constexpr std::size_t find_last_set_bit(unsigned long long v) noexcept {
return (v != 0 ? bit_size(v) - __builtin_clzll(v) - 1 : bit_size(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t find_last_set_bit(const T& v) noexcept {
return find_last_set_bit(std::make_unsigned_t<T>(v));
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t find_next_set_bit(T v, std::size_t i) noexcept {
reset_n_bits(v, 0, i + 1);
return find_first_set_bit(v);
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t find_previous_set_bit(T v, std::size_t i) noexcept {
reset_n_bits(v, i, bit_size(v) - i);
return find_last_set_bit(v);
}
template<typename T> //requires std::is_integral_v<T>
constexpr std::size_t find_ith_set_bit(T v, std::size_t i) noexcept {
std::size_t res = 0;
for (auto bits = bit_size(v); bits > 1; bits /= 2) {
auto cuantos = popcount(bitmask_until(v, bits / 2));
if (cuantos <= i) {
i -= cuantos;
v >>= bits / 2;
res += bits / 2;
}
}
return (i == 0 && get_bit(v, 0) ? res : bit_size(v));
}
template<typename T, typename F> //requires std::is_integral_v<T>
constexpr void visit_set_bits(T v, F&& f) noexcept {
while (v != 0) {
auto bit = find_first_set_bit(v);
reset_bit(v, bit);
f(bit);
}
}
template<typename T, typename F> //requires std::is_integral_v<T>
constexpr void visit_set_n_bits(T v, std::size_t i, std::size_t n, F&& f) noexcept {
visit_set_bits(bitmask(v, i, n), f);
}
}
#endif
| true |
00525edde742b2d79b3a79cbc43b1cbda051ef5b | C++ | Vahan92/balanced_binare_search_tree | /src/tree.cpp | UTF-8 | 7,523 | 3.59375 | 4 | [] | no_license | #include "node.hpp"
#include "tree.hpp"
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
Tree::Tree() : root(NULL), parent(NULL) {}
Node* Tree::newNode(int data)
{
Node* temp = new Node;
temp -> value = data;
temp -> left = NULL;
temp -> right = NULL;
temp -> height = 0;
return temp;
}
Node* Tree::insert(Node* parent, int data)
{
if ( parent == NULL ) {
parent = newNode (data);
} else if ( data < parent -> value ) {
parent -> left = insert(parent -> left, data);
if(get_height(parent->left) - get_height(parent->right) == 2) {
if(data < parent->left->value)
parent = single_right_rotate(parent);
else
parent = left_right_rotate(parent);
}
} else {
parent -> right = insert(parent -> right, data);
if(get_height(parent->right) - get_height(parent->left) == 2) {
if(data > parent->right->value) {
parent = single_left_rotate(parent);
} else {
parent = right_left_rotate(parent);
}
}
}
parent->height = max(get_height(parent->left), get_height(parent->right))+1;
root = parent;
return parent;
}
void Tree::insert_data(int data)
{
if ( root == NULL ) {
root = newNode(data);
} else {
insert (root, data);
}
}
int Tree::left_count(Node* parent, int count)
{
if (parent != NULL ) {
if ( parent->left != NULL) {
left_count(parent->left, ++count);
}
}
return count;
}
void Tree::postorder(Node* parent, int indent = 4)
{
//char c = '\';
if (parent != NULL) {
std::cout << " " << parent->value << std::endl;
if (parent->left != NULL) {
std::cout << "/" << " \\" <<std::endl;
postorder(parent->left,indent+4);
} else {
std::cout << "NULL ";
}
if (parent->right != NULL) {
postorder(parent->right,indent +4);
} else {
std::cout << "\\" << std::endl;
std::cout << "NULL";
}
/*if (parent->left != NULL) {
std::cout << parent->left->value << " ";
}
if (parent->right != NULL) {
std::cout << parent->right->value;
}
if(p->left) postorder(p->left, indent+4);
if(p->right) postorder(p->right, indent+4);
if (indent) {
std::cout << std::setw(indent) << ' ';
}*/
std::cout << std::endl;
}
}
int Tree::get_height( Node* parent)
{
if (parent == NULL)
return 0;
return parent->height;
}
Node* Tree::single_right_rotate(Node* parent)
{
Node* temp = parent->left;
parent->left = temp->right;
temp->right = parent;
parent->height = max(get_height(parent->left), get_height(parent->right))+1;
temp->height = max(get_height(temp->left), parent->height)+1;
return temp;
}
Node* Tree::single_left_rotate(Node* parent)
{
Node* temp = parent->right;
parent->right = temp->left;
temp->left = parent;
parent->height = std::max(get_height(parent->left), get_height(parent->right))+1;
temp->height = max(get_height(parent->right), parent->height)+1 ;
return temp;
}
Node* Tree::right_left_rotate(Node* parent)
{
parent->right = single_right_rotate(parent->right);
return single_left_rotate(parent);
}
Node* Tree::left_right_rotate(Node* parent)
{
parent->left = single_left_rotate(parent->left);
return single_right_rotate(parent);
}
void Tree::print_2d(Node* parent, int indent)
{
if (parent != nullptr)
{
print_2d(parent->right, indent + 4);
if (indent > 0) {
std::cout << std::setw(indent) << " ";
}
std::cout << parent->value << std::endl;
print_2d(parent->left, indent + 4);
}
}
void Tree::print_postorder()
{
postorder(root);
}
Node* Tree::min_node(Node* parent)
{
if(parent == NULL)
return NULL;
else if(parent->left == NULL)
return parent;
else
return min_node(parent->left);
}
bool Tree::search(Node* parent, int data)
{
if ( parent == NULL ) {
std::cout << "Not found" << std::endl;
return false;
}
if ( data == parent -> value ) {
std::cout << "Found!!!" << std::endl;
return true;
} else if ( data < parent -> value ) {
search(parent -> left, data);
} else {
search(parent -> right, data);
}
}
void Tree::find(int data)
{
search(root, data);
}
Node* Tree::remove_node(Node* parent, int data)
{
Node* temp;
if (parent == NULL) {
return parent;
} else if ( data < parent -> value) {
parent -> left = remove_node ( parent -> left, data );
} else if ( data > parent ->value) {
parent -> right = remove_node ( parent -> right, data );
} else {
std::cout << " p-r" << parent->right->value << std::endl;
if ( (parent -> left == NULL) && (parent -> right == NULL)) {
delete parent;
parent = NULL;
return parent;
} else if (parent -> left == NULL) {
parent = parent -> left;
return parent;
} else if (parent -> right == NULL) {
parent =parent -> right;
return parent;
} else {
temp = min_node(parent->right);
parent->value = temp->value;
parent->right = remove_node(parent->right, temp->value);
}
}
if(parent == NULL)
return parent;
parent->height = max(get_height(parent->left), get_height(parent->right))+1;
if(get_height(parent->left) - get_height(parent->right) == 2)
{
if(get_height(parent->left->left) - get_height(parent->left->right) == 1)
return single_left_rotate(parent);
else
return right_left_rotate(parent);
}
else if(get_height(parent->right) - get_height(parent->left) == 2)
{
if(get_height(parent->right->right) - get_height(parent->right->left) == 1)
return single_right_rotate(parent);
else
return left_right_rotate(parent);
}
return parent;
}
void Tree::remove(int data)
{
remove_node(root, data);
}
| true |
19776ff691bf13807cf88531d2db9fef2e9ec5d4 | C++ | stephmackenz/avalon | /common/sgx_workload/workload/workload_processor.h | UTF-8 | 3,873 | 2.5625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | permissive | /* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Defines base class WorkloadProcessor and other definitions to
* create an Avalon workload processor.
* To use, #include "workload_processor.h"
*/
#pragma once
#include <map>
#include <string>
#include "work_order_data.h"
/** Class to register, create, and process a workload. */
class WorkloadProcessor {
public:
WorkloadProcessor(void);
virtual ~WorkloadProcessor(void);
/** Clone a WorkloadProcessor */
virtual WorkloadProcessor* Clone() const = 0;
/**
* Create a WorkloadProcessor
*
* @param workload_id Workload identifier
* @returns Pointer to WorkloadProcessor
*/
static WorkloadProcessor* CreateWorkloadProcessor(std::string workload_id);
/**
* Register a WorkloadProcessor.
* Used by the workloads to register themselves
*
* @param workload_id Workload identifier
* @returns Pointer to WorkloadProcessor
*/
static WorkloadProcessor* RegisterWorkloadProcessor(std::string workload_id,
WorkloadProcessor* processor);
/** Mapping between workload id and WorkloadProcessor. */
static std::map<std::string, WorkloadProcessor*> workload_processor_table;
/**
* Process the workload.
*
* @param workload_id Workload identifier string
* @param requester_id Requester ID to identify who submitted
* work order
* @param worker_id Worker ID, a unique string identifying
* this type of work order processor
* @param work_order_id Unique work order ID for this type of
* work order processor
* @param in_work_order_data Work order data input submitted to the
* work order processor
* @param out_work_order_data Work order data returned by the
* work order processor
*/
virtual void ProcessWorkOrder(
std::string workload_id,
const ByteArray& requester_id,
const ByteArray& worker_id,
const ByteArray& work_order_id,
const std::vector<tcf::WorkOrderData>& in_work_order_data,
std::vector<tcf::WorkOrderData>& out_work_order_data) = 0;
};
/**
* This macro clones an instance of class WorkloadProcessor
* for an Avalon worker.
* Example usage in a .h header file:
* IMPL_WORKLOAD_PROCESSOR_CLONE(Workload)
*
* @param TYPE Name of the Workload class
*/
#define IMPL_WORKLOAD_PROCESSOR_CLONE(TYPE) \
WorkloadProcessor* Clone() const { return new TYPE(*this); }
/**
* This macro registers a workload processor for a specific application.
* It associates a string with a workload.
* This is the same string that is passed in the work order request
* JSON payload.
* Example usage in a .cpp source file:
* REGISTER_WORKLOAD_PROCESSOR(workload_id_string, Workload)
*
* @param WORKLOADID_STR A string literal or variable identifying the workload
* type
* @param TYPE Name of the Workload class
*/
#define REGISTER_WORKLOAD_PROCESSOR(WORKLOADID_STR,TYPE) \
WorkloadProcessor* TYPE##_myProcessor = \
WorkloadProcessor::RegisterWorkloadProcessor(WORKLOADID_STR, new TYPE());
| true |
c75499cb971c8b05e93ef7e0bd42897ba1b423d9 | C++ | code-11/Pandora-Effect | /source.h | UTF-8 | 1,835 | 3.015625 | 3 | [] | no_license | #include <unordered_map>
using namespace std;
const int sizex=48;
const int sizey=24;
typedef unordered_map<char,int> Point;
Point matrix[sizex][sizey];
Point chrome;
class Source
{
public:
Source(int X, int Y, char Type, int Decay_rate, int str);//nondefault constructor
Source();
int eval();
//int eval();
int distance(int x0,int y0,int x1,int y1);
char type;
private:
int decay_rate;
int x;
int y;
int str;
};
Source::Source(){}
Source::Source(int X,int Y,char Type, int Decay_rate,int Str)
{
x=X;
y=Y;
type=Type;
decay_rate=Decay_rate;
str=Str;
}
int Source::distance(int x0,int y0,int x1,int y1)
{
int dx=(x1-x0);
int dy=(y1-y0);
double temp=sqrt((dx*dx)+(dy*dy));
return round(temp);
}
//int Source::eval()
int Source::eval() //inserts pairs into points in our matrix
{
int src_size=str/decay_rate;
int startx=x-src_size;
int starty=y-src_size;
int endx=x+src_size;
int endy=y+src_size;
if (startx<0){startx=0;}
if (starty<0){starty=0;}
if (endx>sizex-1){endx=sizex-1;}
if (endy>sizey-1){endy=sizey-1;}
int evalx=startx;
int evaly;
int dis;
pair <char,int> to_insert;
while(evalx<=endx){
evaly=starty;
while(evaly<=endy){
dis=distance(evalx,evaly,x,y);
//dis=abs(evalx-x)+abs(evaly-y)
if (dis<src_size)
{
to_insert=make_pair(type,((src_size-dis)*decay_rate));
//if the biome already exists at that point, average the two
if ((matrix[evalx][evaly]).count(type)>0){
matrix[evalx][evaly][type]+=to_insert.second;
matrix[evalx][evaly][type]/=2;
//otherwise, just add it
}else{
matrix[evalx][evaly].insert(to_insert);
}
//if water is there get rid of it
if (matrix[evalx][evaly].count('~')>0){
matrix[evalx][evaly].erase('~');
}
}
evaly+=1;
}
evalx+=1;
}
return 1;
}
| true |
6fb14cf49232f9c7b803b2b73055586f6b944cf7 | C++ | LiZhenhuan1019/lzhlib | /include/lzhlib/utility/optional.hpp | UTF-8 | 798 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef LZHLIB_UTILITY_OPTIONAL_HPP
#define LZHLIB_UTILITY_OPTIONAL_HPP
#include <exception>
#include "lzhlib/lzhlib_conf.hpp"
#include "lzhlib/utility/utility_conf.hpp"
namespace lzhlib
{
struct nullopt_t
{
enum class construct
{
token
};
explicit constexpr nullopt_t(construct)
{}
};
inline constexpr nullopt_t nullopt{nullopt_t::construct::token};
struct bad_optional_access : public std::exception
{
char const *what() const noexcept override
{ return "bad optional access."; }
~bad_optional_access() override = default;
};
[[noreturn]] inline void throw_bad_optional_access()
{
lzhlib_throw_or_abort(bad_optional_access());
}
}
#endif //LZHLIB_UTILITY_OPTIONAL_HPP
| true |
2a2d079a012233ec3d571ae89351afb186caab9b | C++ | alexandraback/datacollection | /solutions_5640146288377856_0/C++/pr0gramm3r/a.cpp | UTF-8 | 515 | 2.578125 | 3 | [] | no_license | //in the name of god!
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <fstream>
using namespace std;
#define pb push_back
#define x first
#define y second
#define mk make_pair
ifstream fin("1.in");
ofstream fout("1.out");
int T,r,c,w;
int main(){
fin>>T;
for(int t=0;t<T;t++){
fin>>r>>c>>w;
int ans = (r-1)*(c/w) + ((c+w-1)/w + w - 1);
fout<<"Case #"<<t+1<<": "<<ans<<endl;
}
return 0;
}
| true |
29e3e2d32e4b0a66a502a189f9a6778c7f1ca39d | C++ | BizaoDeBizancio/POO2017.2Monael | /poo11048216/Pratica/pratica4/Complexos/Complexos.cpp | UTF-8 | 3,244 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
class Complexo{
private:
int real;
int imaginario;
public:
Complexo();
Complexo(int, int);
void setReal(int);
int getReal();
void setImaginario(int);
int getImaginario();
Complexo operator + (Complexo);
Complexo operator - (Complexo);
Complexo operator * (Complexo);
Complexo operator / (Complexo);
};
Complexo::Complexo(){
}
Complexo::Complexo(int r, int i){
this->setReal(r);
this->setImaginario(i);
}
void Complexo::setReal(int r){
this->real = r;
}
int Complexo::getReal(){
return this->real;
}
void Complexo::setImaginario(int i){
this->imaginario = i;
}
int Complexo::getImaginario(){
return this->imaginario;
}
Complexo Complexo::operator + (Complexo c){
Complexo res;
res.setReal(this->getReal() + c.getReal());
res.setImaginario(this->getImaginario() + c.getImaginario());
return res;
}
Complexo Complexo::operator - (Complexo c){
Complexo res;
res.setReal(this->getReal() - c.getReal());
res.setImaginario(this->getImaginario() - c.getImaginario());
return res;
}
Complexo Complexo::operator * (Complexo c){
Complexo res;
res.setReal((this->getReal()*c.getReal()) - (this->getImaginario()*c.getImaginario()));
res.setImaginario((this->getImaginario()*c.getReal()) + (this->getReal()*c.getImaginario()));
return res;
}
Complexo Complexo::operator / (Complexo c){
Complexo res;
int quad = ((pow(c.getReal(),2)) + (pow(c.getImaginario(),2)));
c.setImaginario(c.getImaginario()*(-1));
res = (*this)*c;
res.setReal(res.getReal()/quad);
res.setImaginario(res.getImaginario()/quad);
return res;
}
int main(){
std::string i1, i2;
int r1, r2, imi1, imi2;
char op;
while(std::cin >> r1 >> i1 >> op >> r2 >> i2){
i1.erase(i1.end()-1);
i2.erase(i2.end()-1);
if(!i1.empty()){
if(i1.length()==1 && *(i1.begin())=='-'){
imi1 = -1;
}else{
imi1 = atoi(i1.c_str());
}
}else{
imi1 = 1;
}
if(!i2.empty()){
if(i2.length()==1 && *(i2.begin())=='-'){
imi2 = -1;
}else{
imi2 = atoi(i2.c_str());
}
}else{
imi2 = 1;
}
Complexo c1(r1,imi1), c2(r2,imi2), c;
switch(op){
case '+':
c = c1 + c2;
break;
case '-':
c = c1 - c2;
break;
case '*':
c = c1 * c2;
break;
case '/':
c = c1/c2;
break;
default:
break;
}
if(c.getImaginario()>0){
std::cout << c.getReal() << " +" << c.getImaginario() << "i" << std::endl;
}else{
std::cout << c.getReal() << " " << c.getImaginario() << "i" << std::endl;
}
}
return 0;
} | true |
eec7200946ef0ece94384b93cacf8c2d081adfb8 | C++ | AirChen/autodiff | /autodiff/tests/MatrixTest.cpp | UTF-8 | 2,217 | 3.484375 | 3 | [
"MIT"
] | permissive | //
// MatrixTest.cpp
// tests
//
// Created by AirChen on 2021/3/22.
//
#include "MatrixTest.hpp"
#include "gtest/gtest.h"
#include <eigen3/Eigen/Dense>
// The fixture for testing class Foo.
class MatrixTest : public ::testing::Test {
protected:
MatrixTest() {
// You can do set-up work for each test here.
}
~MatrixTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
};
using namespace Eigen;
TEST_F(MatrixTest, BasicTest) {
MatrixXd m(2,2);
m(0,0) = 3;
m(1,0) = 2.5;
m(0,1) = -1;
m(1,1) = m(1,0) + m(0,1);
std::cout << m << std::endl;
m = MatrixXd::Random(3,3);
m = (m + MatrixXd::Constant(3,3,1.2)) * 50;
std::cout << "m =" << std::endl << m << std::endl;
VectorXd v(3);
v << 1, 2, 3;
std::cout << "m * v =" << std::endl << m * v << std::endl;
m = Matrix3d::Random();
m = (m + Matrix3d::Constant(1.2)) * 50;
std::cout << "m =" << std::endl << m << std::endl;
Vector3d v1(1,2,3);
std::cout << "m * v =" << std::endl << m * v1 << std::endl;
}
TEST_F(MatrixTest, Resizing) {
MatrixXd m(2,5);
m.resize(4,3);
std::cout << "The matrix m is of size "
<< m.rows() << "x" << m.cols() << std::endl;
std::cout << "It has " << m.size() << " coefficients" << std::endl;
VectorXd v(2);
v.resize(5);
std::cout << "The vector v is of size " << v.size() << std::endl;
std::cout << "As a matrix, v is of size "
<< v.rows() << "x" << v.cols() << std::endl;
}
TEST_F(MatrixTest, Resizing_1) {
MatrixXf a(2,2);
std::cout << "a is of size " << a.rows() << "x" << a.cols() << std::endl;
MatrixXf b(3,3);
a = b;
std::cout << "a is now of size " << a.rows() << "x" << a.cols() << std::endl;
}
| true |
6ab297e008cf80af1bc42f9db9600d39d02627f7 | C++ | chth2116/web-dev-index-page | /scss/class/SLL.cpp | UTF-8 | 1,014 | 3.859375 | 4 | [
"MIT"
] | permissive | //implement whats defined in header
#include <iostream>
#include "SLL.h"
using namespace std;
//default constructor
SLL::SLL(){
}
//constructor that takes an int
SLL::SLL(int nodeID){
//create head of list
head = new Node;
head -> next = NULL;
head ->id = nodeID;
}
SLL::~SLL(){
//free the memory from the linked list
if(head!=nullptr){
cout << "deleting head id " << head->id << endl;
delete head;
}
}
bool SLL::insertNodeAtEnd(int nodeID){
Node *newNode = new Node;
newNode->next = nullptr;
newNode->id = nodeID;
//check if head is null, if so, create a head node
if (head == nullptr){
head = newNode;
}
//if head is not null, add a new node at the end of the list
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current -> next = newNode;
}
return true;
}
void SLL::printList(){
Node *tmp;
tmp = head;
while (tmp != nullptr){
cout << tmp->id << endl;
tmp = tmp->next;
}
}
| true |
f0b52aa1727fa40454176ca4a41e62a6432d3558 | C++ | zhongxuanS/- | /Piece.cpp | UTF-8 | 2,399 | 3.234375 | 3 | [] | no_license | #include "Piece.h"
#include <algorithm>
Piece::Piece(int pieceId, int pieceRotaion, COLORREF pieceColor, const POINT* apt, int numPoints)
:color_(pieceColor), id_(pieceId), rotaion_(pieceRotaion),
numPoints_(numPoints),width_(0),height_(0), body_(NULL)
{
//因为旋转后的图形左下角并不在坐标原点,所以要做平移操作
POINT leftBottom = apt[0];
for(int i = 1; i < numPoints_; ++i)
{
leftBottom.x = std::min<long>(leftBottom.x, apt[i].x);
leftBottom.y = std::min<long>(leftBottom.y, apt[i].y);
}
// 将apt中的点进行平移操作,使其左下角在坐标原点
body_ = new POINT[numPoints_];
for(int i = 0; i < numPoints_; ++i)
{
body_[i].x = apt[i].x - leftBottom.x;
body_[i].y = apt[i].y - leftBottom.y;
width_ = std::max<int>(static_cast<int>(body_[i].x + 1), width_);
height_ = std::max<int>(static_cast<int>(body_[i].y + 1), height_);
}
}
Piece::~Piece(void)
{
delete[] body_;
}
void Piece::getBody(POINT* apt) const
{
for(int i = 0; i < numPoints_; ++i)
{
apt[i] = body_[i];
}
}
//获得左边缘点
int Piece::getLeftSide(POINT* apt) const
{
int count = 0;
//通过遍历的方式来获取
for(int y = 0; y < height_; ++y)
{
for(int x = 0; x < width_; ++x)
{
if(isPointExists(x, y))
{
apt[count].x = x;
apt[count].y = y;
++count;
break;
}
}
}
return count;
}
int Piece::getRightSide(POINT* apt) const
{
int count = 0;
for(int y = 0; y < height_; ++y)
{
for(int x = width_ - 1; x >= 0; --x)
{
if(isPointExists(x, y))
{
apt[count].x = x;
apt[count].y = y;
++count;
break;
}
}
}
return count;
}
int Piece::getSkirt(POINT* apt) const
{
int count = 0;
for(int x = 0; x < width_; ++x)
{
for(int y = 0; y < height_; ++y)
{
if(isPointExists(x, y))
{
apt[count].x = x;
apt[count].y = y;
++count;
break;
}
}
}
return count;
}
void Piece::print() const
{
printf("width:%d, height:%d, numOfPoints:%d, color:%x\n", width_, height_, numPoints_, color_);
for(int y = height_ - 1; y >= 0; --y)
{
for(int x = 0; x < width_; ++x)
{
if(isPointExists(x, y))
{
printf("#");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
bool Piece::isPointExists(int x, int y) const
{
for(int i = 0; i < numPoints_; ++i)
{
if(body_[i].x == x && body_[i].y == y)
{
return true;
}
}
return false;
}
| true |
131d401d2c777414889abaa67388ad2c42c1a6a7 | C++ | OsipovDmitry/Trash | /core/src/textnode.cpp | UTF-8 | 1,725 | 2.75 | 3 | [] | no_license | #include <core/textnode.h>
#include "textnodeprivate.h"
namespace trash
{
namespace core
{
TextNode::TextNode(const std::string& text_, TextNodeAlignment alignX, TextNodeAlignment alignY, const glm::vec4& color_, float lineSpacing_)
: DrawableNode(new TextNodePrivate(*this))
{
auto& tnPrivate = m();
tnPrivate.text = text_;
tnPrivate.alignX = alignX;
tnPrivate.alignY = alignY;
tnPrivate.color = color_;
tnPrivate.lineSpacing = lineSpacing_;
tnPrivate.dirtyDrawable();
tnPrivate.updateDrawable(); // for calculating bounding box
}
const std::string &TextNode::text() const
{
return m().text;
}
void TextNode::setText(const std::string& value)
{
auto& tnPrivate = m();
if (tnPrivate.text != value)
{
tnPrivate.text = value;
tnPrivate.dirtyDrawable();
}
}
const glm::vec4 &TextNode::color() const
{
return m().color;
}
void TextNode::setColor(const glm::vec4& value)
{
auto& tnPrivate = m();
tnPrivate.color = value;
tnPrivate.dirtyDrawable();
}
float TextNode::lineSpacing() const
{
return m().lineSpacing;
}
void TextNode::setLineSpaceng(float value)
{
auto& tnPrivate = m();
tnPrivate.lineSpacing = value;
tnPrivate.dirtyDrawable();
}
TextNodeAlignment TextNode::alignmentX() const
{
return m().alignX;
}
TextNodeAlignment TextNode::alignmentY() const
{
return m().alignY;
}
void TextNode::setAlignmentX(TextNodeAlignment value)
{
auto& tnPrivate = m();
tnPrivate.alignX = value;
tnPrivate.dirtyDrawable();
}
void TextNode::setAlignmentY(TextNodeAlignment value)
{
auto& tnPrivate = m();
tnPrivate.alignY = value;
tnPrivate.dirtyDrawable();
}
} // namespace
} // namespace
| true |