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 |
---|---|---|---|---|---|---|---|---|---|---|---|
033508cad01acc5e52c1e9ca92e214ff56242dc0
|
C++
|
murmal/Softwareprojekt
|
/aufgabe4/test.cpp
|
UTF-8
| 1,054 | 3.59375 | 4 |
[] |
no_license
|
#include "String.h"
ostream& operator<< (ostream &out, String &s) {
for (int i = 0; i<s.size; i++) {
out << s.str[i];
}
return out;
}
int main() {
String s;
String si('a');
String sii('s');
String s3("wie gehts?");
String s33("mir gehts gut danke");
String s4(s3);
String s5("hallo ");
String s44(s33);
s5 += s3;
s4 += s33;
String s2 = s5;
s = sii;
cout << "Strings mit einzelnen Charactern:" << endl;
cout << si << endl;
cout << sii << endl;
cout << "\nStrings mit Zeichenkette:"<< endl;
cout << s3 << endl; //wie gehts
cout << s33 << endl;
cout << "\nStrings aus Strings:" << endl;
cout << s4 << endl; //wie gehts
cout << s44 << endl; //wie gehts
cout << "\nStrings mit '+=':" << endl;
cout << s5 << endl; //hallo wie gehts?
cout << s4 << endl;
cout << "\nStrings mit '=':" << endl;
cout << s2 << endl; //hallo
cout << s << endl; //hallo
cout << "\nStrings mit '[]':" << endl;
cout << s5[3] << endl;
cout << s4[4] << endl;
cout << "ende" << endl;
}
| true |
83d75a851cb08738e5d7b8dbede9be13599fb7f6
|
C++
|
kedvall/coursework
|
/ECE470/src/lab4pkg/src/lab4func.cpp
|
UTF-8
| 2,526 | 2.796875 | 3 |
[] |
no_license
|
#include "lab4pkg/lab4.h"
float get_theta6(float theta1, float yaw_WgripRad);
float get_theta1(float xcen, float ycen);
/**
* function that calculates an elbow up Inverse Kinematic solution for the UR3
*/
std::vector<double> lab_invk(float xWgrip, float yWgrip, float zWgrip, float yaw_WgripDegree)
{
double xcen,ycen,zcen,theta6,theta5,theta4,theta3,theta2,theta1,x3end,y3end,z3end;
double xgrip,ygrip,zgrip;
double a1,a2,a3,a4,a5,a6;
double d1,d2,d3,d4,d5,d6;
double c1,beta1,beta2,beta3,l4,l5;
a1 = 0;
d1 = 0.152;
a2 = 0.244;
d2 = 0.120;
a3 = 0.213;
d3 = -0.093;
a4 = 0;
d4 = 0.083;
a5 = 0;
d5 = 0.083;
a6 = 0.0535;
d6 = (0.082+0.056);
c1 = (d2+d3+d4);
xgrip = xWgrip + 0.149;
ygrip = yWgrip - 0.149;
zgrip = zWgrip - 0.0193;
xcen = xgrip - a6*cos(yaw_WgripDegree*(PI/180.0));
ycen = ygrip - a6*sin(yaw_WgripDegree*(PI/180.0));
zcen = zgrip;
theta1 = atan2(ycen,xcen) - asin(c1/sqrt( xcen*xcen + ycen*ycen ));
theta6 = PI/2.0 + theta1 - yaw_WgripDegree*(PI/180.0);
x3end = xcen + c1*sin(theta1) - d5*cos(theta1);
y3end = ycen - d5*sin(theta1) - c1*cos(theta1);
z3end = zcen + d6;
l5 = sqrt(x3end*x3end + y3end*y3end);
l4 = sqrt(l5*l5 + (z3end-d1)*(z3end-d1));
beta1 = asin((z3end-d1)/l4);
// --------- PROBLEM HERE ----------PROBLEM HERE---------------//
beta2 = acos((a2*a2 + l4*l4 - a3*a3) / (2.0*a2*l4));
// --------- PROBLEM HERE ----------PROBLEM HERE---------------//
beta3 = acos((a2*a2 + a3*a3 - l4*l4) / (2.0*a2*a3));
theta2= -(beta1 + beta2);
theta3= PI - beta3;
theta4= beta1 + beta2 + beta3 - 3.0*PI/2.0;
theta5=-PI/2.0;
// View values
//use cout
cout<<"quat: "<< (a2*a2 + l4*l4 - a3*a3) / (2*a2*l4)<<endl;
cout<<"theta1: "<< theta1<<endl;
cout<<"l4: "<< l4<<endl;
cout<<"l5: "<< l5<<endl;
cout<<"beta1: "<< beta1<<endl;
cout<<"beta2: "<< beta2<<endl;
cout<<"theta2: "<< theta2<<endl;
cout<<"theta3: "<< theta3<<endl;
cout<<"theta4: "<< theta4<<endl;
cout<<"theta5: "<< theta5<<endl;
cout<<"theta6: "<< theta6<<endl;
// check that your values are good BEFORE sending commands to UR3
//lab_fk calculates the forward kinematics and convert it to std::vector<double>
return lab_fk((float)theta1,(float)theta2,(float)theta3,(float)theta4,(float)theta5,(float)theta6);
}
| true |
436acff35449c2aedd9abaaf19f32b242f160b20
|
C++
|
cswangle/QbS
|
/pathPPL.cpp
|
UTF-8
| 8,613 | 2.671875 | 3 |
[] |
no_license
|
// Method: pruned path labelling, (2-hop path cover, a baseline).
// SIGMOD21' Query-by-Sketch: Scaling Shortest Path Graph Queries on Very Large Graphs
// originFile is the file generated by preprocess.
// first, run main function to execute test.labelConstruction() which will generate a labelling file (outputFile).
// second, run main function again to execute test.input() to load the labelling file (inputFile), and excute test.QueryTest(int numberOfTests) to test the query time.
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<math.h>
#include<string>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<stdint.h>
#include <bits/stdc++.h>
#include<sys/time.h>
#define INF 99
#define originFile "skitter_pro.txt"
#define outputFile "skitter_pll.txt"
#define inputFile "skitter_pll.txt"
using namespace std;
struct label{
int l;
uint8_t d;
label(int x,int y){
l = x;
d = y;
}
};
struct edge{
int a,b;
edge(int x,int y)
{
a = min(x,y);
b = x+y-a;
}
};
class pathPLL
{
private:
int countVertex;
vector<vector<label> > labelList;
long labelSize;
public:
pathPLL()
{
//
}
void labelConstruction()
{
ifstream graphFile(originFile);
stringstream ss;
string lineC;
getline(graphFile,lineC);
ss << lineC;
ss >> countVertex;
ss.clear();
ss.str("");
vector<vector<int> > adjList;
vector<label> labelTemp;
int u,v,d;
//read the graph
while(getline(graphFile,lineC))
{
ss << lineC;
ss >> v; //vertex id
ss >> d; //degree
vector<int> tempD(d,0);
for(int i=0;i<d;i++){
ss >> tempD[i];
}
adjList.push_back(tempD);
labelList.push_back(labelTemp);
ss.clear();
ss.str("");
}
graphFile.close();
uint8_t* dist = new uint8_t[countVertex];
uint8_t* prune= new uint8_t[countVertex];
timeval st,ed;
gettimeofday(&st,NULL);
for(int i=0;i<countVertex;i++) // a pruned BFS
{
queue<int> qLabel;
queue<int> qPrune;
memset(dist,INF,countVertex);
memset(prune,0,countVertex);
qLabel.push(i);
dist[i] = 0;
qLabel.push(-1);
label temp(i,INF);
while(qLabel.front()!=-1)
{
while(true)
{
u = qLabel.front();
qLabel.pop();
if(u==-1)
{
qLabel.push(-1);
qPrune.push(-1);
break;
}
temp.d = dist[u];
labelList[u].push_back(temp);
if(prune[u] || u<i)
{
qPrune.push(u);
}
else{
for(int j=0;j<adjList[u].size();j++)
{
v = adjList[u][j];
if(dist[v]==INF)
{
dist[v] = dist[u] + 1;
qLabel.push(v);
}
}
}
}
while(true)
{
u = qPrune.front();
qPrune.pop();
if(u==-1) break;
for(int j=0;j<adjList[u].size();j++)
{
v = adjList[u][j];
if(dist[v]==INF)
{
dist[v] = dist[u] + 1;
qPrune.push(v);
}
else if(dist[v]==dist[u]+1 && prune[v]==0)
{
prune[v] = 1;
}
}
}
}
}
gettimeofday(&ed,NULL);
long sumTime = (ed.tv_sec-st.tv_sec)*1000000 + (ed.tv_usec-st.tv_usec);
cout << "average query time:" << sumTime << endl;
//output label information to a file
labelSize = 0;
ofstream result(outputFile);
for(int i=0;i<countVertex;i++)
{
result << i << " " << labelList[i].size();
labelSize += labelList[i].size();
for(int j=0;j<labelList[i].size();j++)
{
//if(labelList[i][j].l==i) continue; // remove the label from itself
result << " " << labelList[i][j].l << " " << int(labelList[i][j].d);
}
result << endl;
}
result.close();
cout << "Label Size:" << labelSize << endl;
}
void input() //get label information from a file
{
ifstream labelFile(inputFile);
int u, c, a, b;
string line;
stringstream ss;
while(getline(labelFile, line))
{
ss << line;
ss >> u;
ss >> c;
vector<label> labels;
for(int i=0;i<c;i++) {
ss >> a;
ss >> b;
label temp(a,b);
labels.push_back(temp);
}
labelList.push_back(labels);
ss.clear();
ss.str("");
}
countVertex = labelList.size();
cout << "|V|: " << countVertex << endl;
labelFile.close();
}
int QueryDistance(int s,int t)
{
int mind = INF;
int i=0;
int j=0;
while(i<labelList[s].size() && j<labelList[t].size())
{
if(labelList[s][i].l==labelList[t][j].l)
{
mind = min(mind, labelList[s][i].d+labelList[t][j].d);
i++;
j++;
}
else if(labelList[s][i].l<labelList[t][j].l)
i++;
else
j++;
}
return mind;
}
void QueryPath(int s,int t)
{
int mind = INF;
int dtemp;
vector<int> midpoints;
int i=0;
int j=0;
while(i<labelList[s].size() && j<labelList[t].size())
{
if(labelList[s][i].l==labelList[t][j].l)
{
dtemp = labelList[s][i].d+labelList[t][j].d;
if(mind==dtemp)
midpoints.push_back(labelList[s][i].l);
else if(mind>dtemp){
mind = dtemp;
vector<int> tempv;
midpoints.swap(tempv);
midpoints.push_back(labelList[s][i].l);
}
i++;
j++;
}
else if(labelList[s][i].l<labelList[t][j].l){
i++;
}
else{
j++;
}
}
if(mind==1)
{
//cout << s << " " << t << endl;
return;
}
else if(mind==INF) return;
else{
for(int i=0;i<midpoints.size();i++)
{
if(midpoints[i]==s || midpoints[i]==t) continue;
QueryPath(s,midpoints[i]);
QueryPath(t,midpoints[i]);
}
}
return;
}
unsigned int rand_32()
{
return (rand()&0x3)<<30 | rand()<<15 | rand();
}
void QueryTest(int testTime)
{
timeval st,ed;
gettimeofday(&st,NULL);
int s, t;
for(int i=0;i<testTime;i++)
{
s = rand_32()%countVertex;
t = rand_32()%countVertex;
QueryPath(s,t);
}
gettimeofday(&ed,NULL);
long sumTime = (ed.tv_sec-st.tv_sec)*1000000 + (ed.tv_usec-st.tv_usec);
cout << "average query time:" << sumTime*1.0/testTime << endl;
float sumd = 0;
int dt;
for(int i=0;i<testTime;i++)
{
s = rand_32()%countVertex;
t = rand_32()%countVertex;
dt = QueryDistance(s,t);
if(dt!=INF) sumd += dt;
}
cout << "average distance:" << sumd/testTime << endl;
}
};
int main()
{
srand(1);
pathPLL test = pathPLL();
// first time:
test.labelConstruction();
// second time:
// test.input();
// test.QueryTest(10000);
return 0;
}
| true |
e6cb1425ed7b4aac2b1eb4e4e38e8f8bbf6aac4f
|
C++
|
drlongle/leetcode
|
/algorithms/problem_0908/other1.cpp
|
UTF-8
| 1,350 | 3.46875 | 3 |
[] |
no_license
|
class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
// get max and min value in array
int maxv = *max_element(A.begin(),A.end());
int minv = *min_element(A.begin(),A.end());
// possible smallest max value => maxv - K
// possible largest min value => minv + K
// possible smallest diff between max and min = possible smallest max - possible largest min
// value = maxv -K - (minv + K) = maxv-K-minv-K
// This equation holds true if maxv-K > minv+K, otherwise maxv-K won't be max and minv+K won't be min and
// we will get a negative difference
// EX: A = [1,3,6], K = 3 => maxv-K =6-3=3 < minv+K = 1+3 = 4 =>(maxv-K) - (minv+K) = 3-4 = -1 => negative
// result
// Corner Case: If maxv-K < minv+K then maxv-K is not a max value any more and minv+K is not a min value
// any more which gives negative result
// even their absolute difference can give a positive result which is not minimum difference
// In this case, we can think that A array is updated in a way that all values of B are equal as minv+K > maxv-K
// and the smallest possible difference will be 0
// So we comapre the result (maxv-K-minv-K) with 0 and return the max between them
return max(0,maxv-K-minv-K);
}
};
| true |
e82fd5b254d50f34b25d63a9f319f4ab1b3913f5
|
C++
|
nwnlp/fasttree
|
/src/rf.h
|
UTF-8
| 3,452 | 2.640625 | 3 |
[] |
no_license
|
//
// Created by johnny on 2019/7/1.
//
#ifndef DECISIONTREE_RF_H
#define DECISIONTREE_RF_H
#include <vector>
#include "tree.h"
#include "attribute_list.h"
#include <ctime>
#include <omp.h>
#include <unistd.h>
#include "tree_histogram.h"
class RandomForest{
public:
RandomForest(int num_trees, int max_depth, float colsample, float rowsample){
this->num_trees = num_trees;
this->max_depth = max_depth;
this->colsample = colsample;
this->rowsample = rowsample;
}
~RandomForest(){
for (int i = 0; i < forest.size(); ++i) {
delete forest[i];
}
bin.clean_up();
}
int get_tree_nums(){
return forest.size();
}
void fit(Problem& prob){
bin.build(prob);
cout<<"build bin done..."<<endl;
//attribute_list.build(bin, prob);
num_classes = prob.num_classes;
int data_size = prob.data_cnt;
int feature_size = prob.feature_size;
forest.resize(num_trees);
//omp_set_num_threads(8);
#pragma omp parallel for schedule(dynamic)
for (int tree_id = 0; tree_id <num_trees; ++tree_id) {
/*Tree* tree = new Tree(tree_id,max_depth,data_size, feature_size,num_classes, colsample,rowsample);
tree->fit(&attribute_list, &(prob.y));
int node_cnt = tree->get_node_cnt();
int leaf_node_cnt = tree->get_leaf_node_cnt();
cout<<"tree id:"<<tree_id<<" node count:"<<node_cnt<<" leaf node count:"<<leaf_node_cnt<<endl;
*/
TreeLeafWiseLearner* tree = new TreeLeafWiseLearner(tree_id,max_depth,data_size, feature_size,num_classes, colsample,rowsample);
tree->fit(bin,prob);
int node_cnt = tree->get_nodes_cnt();
int leaf_node_cnt = tree->get_leaf_nodes_cnt();
int depth = tree->get_tree_depth();
cout<<"tree id:"<<tree_id<<" node count:"<<node_cnt<<" leaf node count:"<<leaf_node_cnt<<" depth:"<<depth<<endl;
forest[tree_id] = tree;
}
//attribute_list.clean_up();
}
vector<int> predict(Problem& prob){
vector<vector<int>> data = bin.discrete_data(prob.X);
vector<int> y_pred;
y_pred.resize(data.size());
#pragma omp parallel for schedule(dynamic)
for (int data_index = 0; data_index < data.size(); ++data_index) {
vector<float> avg_probs;
avg_probs.resize(num_classes);
int label = -1;
float max_prob= -numeric_limits<float>::infinity();
for (int tree_id = 0; tree_id <num_trees; ++tree_id) {
TreeLeafWiseLearner* tree = forest[tree_id];
vector<float> probs = tree->predict_one(data[data_index]);
for (int i = 0; i < num_classes; ++i) {
avg_probs[i] += probs[i];
}
}
for (int j = 0; j < num_classes; ++j) {
avg_probs[j]/=num_trees;
if(avg_probs[j] > max_prob){
max_prob = avg_probs[j];
label = j;
}
}
y_pred[data_index]=label;
}
return y_pred;
}
private:
vector<TreeLeafWiseLearner*> forest;
int max_depth;
float colsample;
float rowsample;
int num_classes;
int num_trees;
Bin bin;
//AttributeList attribute_list;
};
#endif //DECISIONTREE_RF_H
| true |
9fecf1fc723040f000797d075a15e51244e2132e
|
C++
|
rraallvv/Algorithmic-Composer
|
/MarkovArray/setNote.cpp
|
UTF-8
| 988 | 2.828125 | 3 |
[] |
no_license
|
//
// setNote.cpp
// MarkovArray
//
// Created by Jonas Schüle on 11.12.14.
// Copyright (c) 2014 hw. All rights reserved.
//
#include "Note.h"
void note::setNumber(int number)
{
if(number >= 0 && number < 128)
{
note::noteData[0] = number;
}
else
{
printf("ERROR: Notenumber out of Range");
}
}
void note::setOnTime(int onTime)
{
note::noteData[1] = onTime;
}
void note::setVelocity(int velocity)
{
if(velocity >= 0 && velocity < 128)
{
note::noteData[2] = velocity;
}
else
{
printf("ERROR: Velocity out of Range");
}
}
void note::setOffTime(int offTime)
{
note::noteData[3] = offTime;
}
void note::setDuration()
{
note::noteData[4] = noteData.at(3)-noteData.at(1);
}
void note::setRest(int on)
{
note::noteData[5] = on;
}
void note::setNote(int number, int duration, int velocity)
{
note::noteData[0] = number;
note::noteData[1] = duration;
note::noteData[2] = velocity;
}
| true |
a2fe20e7240842afdb667aec70ce222882a1c9a0
|
C++
|
skzr001/Leetcode
|
/150. Evaluate Reverse Polish Notation/lc150.cpp
|
UTF-8
| 405 | 2.78125 | 3 |
[] |
no_license
|
class Solution {
public:
int evalRPN(vector<string>& tokens) {
string s=tokens.back();
tokens.pop_back();
if(s!="+"&&s!="-"&&s!="*"&&s!="/") return stoi(s);
int b=evalRPN(tokens),a=evalRPN(tokens);
// Does every operation valid?
if(s=="+") return a+b;
if(s=="-") return a-b;
if(s=="*") return a*b;
if(s=="/") return a/b;
}
};
| true |
ed488345c055cf2efa6483926cb7073767b4e346
|
C++
|
jpvanoosten/LearningCUDA
|
/Tutorial2/main.cpp
|
UTF-8
| 3,347 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
#include "cuda_runtime.h"
#include <algorithm>
#include <chrono>
#include <iostream>
cudaError_t addWithCuda_1(int n, float* x, float* y);
cudaError_t addWithCuda_256(int n, float* x, float* y);
cudaError_t addWithCuda_256xN(int n, float* x, float* y);
using namespace std::chrono;
void add(int n, float* x, float* y)
{
for (int i = 0; i < n; ++i)
{
y[i] = x[i] + y[i];
}
}
int main()
{
const int N = 1e6; // 1M elements.
float* x = new float[N];
float* y = new float[N];
duration<double, std::micro> deltaTime;
cudaError_t cudaStatus;
for (int i = 0; i < N; ++i)
{
x[i] = 1.0f;
y[i] = 2.0f;
}
// Add vectors on CPU.
auto t0 = high_resolution_clock::now();
add(N, x, y );
auto t1 = high_resolution_clock::now();
deltaTime = t1 - t0;
std::cout << "CPU Add: " << N << " numbers: " << deltaTime.count() << " us" << std::endl;
// Check for errors.
float maxError = 0.0f;
for (int i = 0; i < N; ++i)
{
maxError = std::max(maxError, std::abs(y[i] - 3.0f) );
}
std::cout << "Maximum Error: " << maxError << std::endl;
t0 = high_resolution_clock::now();
// Add vectors in a single CUDA thread.
cudaStatus = addWithCuda_1(N, x, y);
t1 = high_resolution_clock::now();
deltaTime = t1 - t0;
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
std::cout << "CUDA 1-thread Add: " << N << " numbers: " << deltaTime.count() << " us" << std::endl;
// Check for errors.
maxError = 0.0f;
for (int i = 0; i < N; ++i)
{
maxError = std::max(maxError, std::abs(y[i] - 4.0f));
}
std::cout << "Maximum Error: " << maxError << std::endl;
t0 = high_resolution_clock::now();
// Add vectors in a single CUDA thread.
cudaStatus = addWithCuda_256(N, x, y);
t1 = high_resolution_clock::now();
deltaTime = t1 - t0;
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
std::cout << "CUDA 256-thread Add: " << N << " numbers: " << deltaTime.count() << " us" << std::endl;
// Check for errors.
maxError = 0.0f;
for (int i = 0; i < N; ++i)
{
maxError = std::max(maxError, std::abs(y[i] - 5.0f));
}
std::cout << "Maximum Error: " << maxError << std::endl;
t0 = high_resolution_clock::now();
// Add vectors in a single CUDA thread.
cudaStatus = addWithCuda_256xN(N, x, y);
t1 = high_resolution_clock::now();
deltaTime = t1 - t0;
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
std::cout << "CUDA Thread Block Add: " << N << " numbers: " << deltaTime.count() << " us" << std::endl;
// Check for errors.
maxError = 0.0f;
for (int i = 0; i < N; ++i)
{
maxError = std::max(maxError, std::abs(y[i] - 6.0f));
}
std::cout << "Maximum Error: " << maxError << std::endl;
// cudaDeviceReset must be called before exiting in order for profiling and
// tracing tools such as Nsight and Visual Profiler to show complete traces.
cudaStatus = cudaDeviceReset();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceReset failed!");
return 1;
}
return 0;
}
| true |
54b30f4dfb937ed42cbc527bf68fcc1f417ab573
|
C++
|
mururaj/Algorithms
|
/BitOps/testEndianess.cpp
|
UTF-8
| 359 | 2.796875 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
union s
{
unsigned int i;
unsigned char ch[4];
};
union s obj;
obj.i=1u;
printf("%d %d %d %d %d\n",obj.i,obj.ch[0],obj.ch[1],obj.ch[2],obj.ch[3]);
unsigned int num = 0x01020304;
unsigned char *myChar = (unsigned char *)#
printf("num = %x mychar = %x\n",num,*myChar);
return 1;
}
| true |
872df62ecf54f0a6b6d48913a47a2041f4a06037
|
C++
|
RuslonPy/C-Example
|
/dfs_matritsa.cpp
|
UTF-8
| 941 | 2.84375 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
char a[1000][1000];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n , m;
bool used[1000][1000];
void dfs(int x, int y){
used[x][y] = true;
for(int i = 0; i < 4; i ++){
int tx = x + dx[i], ty = y + dy[i];
if(tx >= 0 and tx < n and ty >= 0 and ty < m and a[tx][ty] != '#' and !used[tx][ty]){
dfs(tx,ty);
}
}
}
main()
{
int x, y, c, b;
cin >> n >> m;
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j++){
cin >> a[i][j];
if(a[i][j] == 's')
x = i,
y = j;
if(a[i][j] == 'f' )
c = i,
b = j;
}
}
dfs(x, y);
if(used[c][b])
cout << "yes";
else cout <<"no";
}
| true |
c73414ee8f44b960e64738689531597cdf9a9bd7
|
C++
|
przempore/Deadstorm
|
/lib/gem/Bounce.cpp
|
UTF-8
| 2,030 | 2.828125 | 3 |
[] |
no_license
|
#include "gem/Bounce.hpp"
namespace Gem
{
void Bounce::Reset()
{
FiniteAction::Reset();
m_action->Reset();
m_reverseAction->Reset();
m_bounceCounter = 0;
m_reverseActionActive = false;
}
void Bounce::Update(float aTimeDelta)
{
if (m_bounceCount > 0)
{
if (!Finished())
{
if (!m_reverseActionActive)
{
m_action->Update(aTimeDelta);
if (m_action->Finished())
{
m_action->Reset();
m_reverseActionActive = true;
}
}
else
{
m_reverseAction->Update(aTimeDelta);
if (m_reverseAction->Finished())
{
if (++m_bounceCounter < m_bounceCount)
{
m_reverseAction->Reset();
m_reverseActionActive = false;
}
else
Finish();
}
}
}
}
else
{
if (!Finished())
Finish();
}
}
ActionPtr Bounce::Reversed() const
{
ActionPtr reversed(
new Bounce(std::dynamic_pointer_cast<FiniteAction>(m_action->Reversed()),m_bounceCount));
GEM_ASSERT(reversed);
return reversed;
}
float Bounce::Duration() const
{
return m_bounceCount * m_action->Duration() + m_bounceCount * m_reverseAction->Duration();
}
float Bounce::TimeElapsed() const
{
return m_bounceCount
* m_action->Duration()
+ m_bounceCount
* m_reverseAction->Duration()
+ (m_reverseActionActive
? m_action->Duration()
+ m_reverseAction->TimeElapsed()
: m_action->TimeElapsed());
}
}
| true |
0732afdf5ea23ed736d91abaa98213228a736ef4
|
C++
|
finch185277/leetcode
|
/051-075/056.cpp
|
UTF-8
| 932 | 3.4375 | 3 |
[] |
no_license
|
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
private:
inline static bool sort_intervals(const Interval &lhs, const Interval &rhs) {
return lhs.start < rhs.start;
}
public: // by @lchen77
vector<Interval> merge(vector<Interval> &intervals) {
std::vector<Interval> ret;
if (intervals.empty())
return ret;
std::sort(intervals.begin(), intervals.end(), sort_intervals);
ret.push_back(intervals.at(0));
for (int i = 1; i < intervals.size(); i++) {
if (ret.back().end < intervals.at(i).start) // they are diff intervals
ret.push_back(intervals.at(i));
else // enlarge the interval size to cover the overlapping area
ret.back().end = std::max(ret.back().end, intervals.at(i).end);
}
return ret;
}
};
| true |
04703672cdf8d2c77bc29cc10d7c1a6082dced59
|
C++
|
jordsti/stigame
|
/StiGame/primitives/Primitive.h
|
UTF-8
| 1,789 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#ifndef PRIMITIVE_H
#define PRIMITIVE_H
#include "SDL.h"
#include "Color.h"
namespace StiGame
{
/* Note(s)
* Need to examine some alternative
* Maybe do a wrapper of SDL_gfx...
*
*/
class Surface;
/// \class SPrimitive
/// \brief Interface to draw or fill a polygon
class Primitive
{
public:
/// \brief Empty constructor
Primitive(void);
/// \brief Destructor
~Primitive(void);
void draw(Surface *surface, Color *color);
void fill(Surface *surface, Color *color);
/// \brief Virtual method to override
/// Draw the primitive, border only
/// \param surface SDL_Surface to draw on
/// \param color SColor pointer
/// \deprecated Using surface gonna be deprecated, but still used in Item rendering...
virtual void draw(SDL_Surface *surface, Color *color) = 0;
/// \brief Virtual method to override
/// Fill the primitive
/// \param surface SDL_Surface to draw on
/// \param color SColor pointer
/// \deprecated Using surface gonna be deprecated, but still used in Item rendering...
virtual void fill(SDL_Surface *surface, Color *color) = 0;
/// \brief Virtual method to override, draw to the screen a Primitive
/// \param renderer SDL_Renderer
/// \param color Primitive Color
virtual void draw(SDL_Renderer *renderer, Color *color) = 0;
/// \brief Virtual method to override, fill to the screen a Primitive
/// \param renderer SDL_Renderer
/// \param color Primitive Color
virtual void fill(SDL_Renderer *renderer, Color *color) = 0;
protected:
/// \brief Set the pixel color
/// \param surface SDL_Surface to modify
/// \param p_x pixel x
/// \param p_y pixel y
/// \param color Uint32 SDL mapped color
/// \depcrecated Surface Pixel modification need to be avoid !
void setPixel(SDL_Surface *surface,int p_x,int p_y,Uint32 color);
};
}
#endif
| true |
a4807911e19714cc2b019cb659d045d22d96bff5
|
C++
|
Samantha-Jo/Final-Project-2.0
|
/user.cpp
|
UTF-8
| 677 | 2.84375 | 3 |
[] |
no_license
|
//
// user.cpp
// CS2Final
//
// Created by Samantha-Jo Cunningham on 5/7/18.
// Copyright © 2018 Samantha-Jo Cunningham. All rights reserved.
//
#include <stdio.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#include "user.h"
User::User(){}
string User::userName(string nameofUser) {
try {
cout << "Username: ";
cin.get();
getline(cin, nameofUser);
cout << endl;
if(nameofUser == "") {
throw runtime_error("Invalid Username");
}
}
catch (runtime_error& excpt){
cout << excpt.what() << endl;
cout << "Please enter a valid username" << endl;
}
return nameofUser;
}
User::~User(){}
| true |
3f6bf57bdf2dda260c0d358a7af68ff8298e5832
|
C++
|
metrosxxmin/OOP_201502090
|
/week03/assignment1.cpp
|
UTF-8
| 433 | 2.78125 | 3 |
[] |
no_license
|
#include <iostream>
void code() {}
static const int rodata = 0;
int data = 1;
int bss;
int main() {
int* heap = new int[1];
int stack = 1;
std::cout << "Code\t : " << (void *) code << '\n';
std::cout << "Rodata\t : " << &rodata << '\n';
std::cout << "Data\t : " << &data << '\n';
std::cout << "Bss\t : " << &bss << '\n';
std::cout << "Heap\t : " << heap << '\n';
std::cout << "Stack\t : " << &stack << '\n';
return 0;
}
| true |
2ea0e5d1feb4bf0dac47b50b987988cb562fd3ba
|
C++
|
Javed69/Cpp_Masterclass
|
/Competitive_Programming/array/max_till_i.cpp
|
UTF-8
| 456 | 3.40625 | 3 |
[] |
no_license
|
/*
Approach
1.Keep a variable max which stores the maximum tiil the ith element
2.Iterate over the array and update max = max(max, a[i])
*/
#include<iostream>
using namespace std;
int main()
{
int mx = -19999999;
int n;
cin>>n;
int array[n];
for (int i = 0; i < n; i++)
{
cin>>array[i];
}
for (int i = 0; i < n; i++)
{
mx = max(mx, array[i]);
cout<<mx<<endl;
}
return 0;
}
| true |
c4217a897ea6a0e39704cab73c2d40b1380bdd1f
|
C++
|
Nimish-Jain/DSA-Practice
|
/Binary Trees/207. LCA.cpp
|
UTF-8
| 699 | 2.875 | 3 |
[] |
no_license
|
//Code :: Nimish Jain
#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
class node {
public:
int data;
node* left;
node* right;
node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
Node* lca(Node* root, int a, int b) {
if (!root) return NULL;
if (root->data == a or root->data == b) {
return root;
}
//search in left & right sub-trees
Node* leftAns = lca(root->left, a, b);
Node* rightAns = lca(root->right, a, b);
if (leftAns != NULL and rightAns != NULL)
return root;
if (leftAns != NULL) return leftAns;
return rightAns;
}
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
return 0;
}
| true |
f6e48a1303ca23e5180ebe7408478b5c5a4f71f5
|
C++
|
Kerorohu/PAT_Code
|
/1041.cpp
|
UTF-8
| 634 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct Data {
string number;
int ksn;
}data;
int main() {
int num;
cin >> num;
int sjn;
map<int, Data> m;
for (int i = 0; i < num; i++) {
cin >> data.number >> sjn >> data.ksn;
m.insert(pair<int, Data>(sjn, data));
}
int q;
cin >> q;
int* a = new int[q];
int temp;
for (int i = 0; i < q; i++) {
cin >> temp;
a[i] = temp;
}
for (int i = 0; i < q; i++) {
cout << m[a[i]].number << " " << m[a[i]].ksn;
if (i < q - 1)
cout << endl;
}
}
| true |
6e196e676a746ded301d52e505312406caae16e8
|
C++
|
glennismade/NeuralNetwork
|
/mlplayer.cpp
|
UTF-8
| 12,752 | 3.15625 | 3 |
[] |
no_license
|
// Library Module Implementing Layers of Perceptrons for CY2D7 .. SE2NN11
// Dr Richard Mitchell 15/12/06 ... 18/09/13
// Adapted by
#include "mlplayer.h"
#include <math.h>
#include <iomanip>
#include <valarray>
// functions students write which return vectors need to be safe
// before student writes the code ... so by default they call this function
vector<double> dummyVector (int num) {
vector<double> dummy(num, 0);
return dummy;
}; // dummy vector :
double myrand (void) {
// return a random number in the range -1..1
// do so calling the rand function in math library
return -1.0 + (2.0 * rand() / RAND_MAX);
}
// Implementation of LinearLayerNetwork *****************************
LinearLayerNetwork::LinearLayerNetwork (int numIns, int numOuts) {
// constructor for Layer of linearly activated neurons
// it is passed the numbers of inputs and of outputs
// there are numOuts neurons in the layer
// each neuron has an output, a delta and an error -
// so have an array of outputs, deltas and errors
// each neuron has numIns+1 weights (first being the bias weight)
// so have large array of weights, and of weight changes
int ct;
numInputs = numIns; // store number inputs
numNeurons = numOuts; // and of outputs in object
numWeights = (numInputs + 1) * numNeurons; // for convenience calculate number of weights
// each neuron has bias + weight for each input
outputs.resize(numNeurons); // get space for array for outputs
deltas.resize(numNeurons); // and deltas
weights.resize(numWeights); // get space for weights
changeInWeights.resize(numWeights); // and change in weights
for (ct=0; ct<numWeights; ct++) {
weights[ct] = myrand(); // initialise weights randomly
changeInWeights[ct] = 0; // initialise changeInWeights to 0
}
for (ct=0; ct < numNeurons; ct++) { // initialise outputs and deltas to 0
outputs[ct] = 0;
deltas[ct] = 0;
}
}
LinearLayerNetwork::~LinearLayerNetwork() {
// destructor ... returns all 'new' memory to heap ... do nowt as all are vectors
}
void LinearLayerNetwork::CalcOutputs(vector<double> ins) {
// calculate the sum of each input in (ins) * associated weight, for each neuron in the layer
// store the results in the array of outputs
// as weights are stored in array, and accessed in order, use a counter auto indexed through array
int wtindex = 0; // counter/index set to refer to first weight of first neuron
for (int neuronct=0; neuronct < numNeurons; neuronct++) { // process each neuron in the layer, in order
outputs[neuronct] = weights[wtindex++]; // output = bias weight (move index to next weight)
for (int inputct=0; inputct < numInputs; inputct++) // for each input
outputs[neuronct] += ins[inputct] * weights[wtindex++]; // add input * next weight
}
}
void LinearLayerNetwork::ComputeNetwork (dataset &data) {
// pass each item in dataset to network and calculate the outputs
for (int ct=0; ct<data.numData(); ct++) { // for each item in data set
CalcOutputs (data.GetNthInputs(ct)); // calculate the weighted sum of inputs
StoreOutputs(ct, data); // copy outputs back into data set
}
}
void LinearLayerNetwork::StoreOutputs (int n, dataset &data) {
// copy calculated network outputs into n'th outputs in data
data.SetNthOutputs(n, outputs);
// Pass the outputs from the layer back to the data set, data
}
void LinearLayerNetwork::FindDeltas (vector<double> errors) {
// find the deltas of each neuron in layer, from the errors which are in the array passed here
deltas = errors; //the deltas for a linear neuron are the same as the errors, this simply applys this rule by assiging the erros variable to the deltas variable
}
void LinearLayerNetwork::ChangeAllWeights (vector<double> ins, double learnRate, double momentum) {
// Change all weights in layer - using inputs ins and [learning rate, momentum]
double numIns;
int nnwud = 0;
for (int countNeurons = 0; countNeurons < numNeurons; countNeurons++)
{
for (int wct = 0; wct < numInputs + 1; wct++) {
if (wct == 0) numIns = 1.0; else numIns = ins[wct - 1];
changeInWeights[nnwud] = numIns * deltas[countNeurons] * learnRate + changeInWeights[nnwud] * momentum;
weights[nnwud] += changeInWeights[nnwud];
nnwud++;
//takes the value of numIns and loops over the wct variable telling it to +1 to numInputs and then uses the function changeInWeights[wct] = numIns * deltas[wct] * learnRate + changeInWeights[wct] * momentum; to take the previouse weight(changeInWeights) and multiply by the deltas, momentum and learn rate and then pass it back to the changeInWeights[wct] variable before assiging these values to weights
}
}
}
void LinearLayerNetwork::AdaptNetwork (dataset &data, double learnRate, double momentum) {
// pass whole dataset to network : for each item
// calculate outputs, copying them back to data
// adjust weights using the delta rule : targets are in data
// where learnparas[0] is learning rate; learnparas[1] is momentum
for (int ct=0; ct<data.numData(); ct++) {
// for each item in data set
CalcOutputs(data.GetNthInputs(ct));
// get inputs from data and pass to network to calculate the outputs
StoreOutputs (ct, data);
// return calculated outputs from network back to dataset
FindDeltas(data.GetNthErrors(ct));
// get errors from data and so get neuron to calculate the deltas
ChangeAllWeights(data.GetNthInputs(ct), learnRate, momentum);
// and then change all the weights, passing inputs and learning constants
}
}
void LinearLayerNetwork::SetTheWeights (vector<double> initWt) {
// set the weights of the layer to the values in initWt
// do so by copying from initWt into object's weights
weights = initWt;
// copy all weights (numweights says how many) from array initWt to layer's array Weights
}
int LinearLayerNetwork::HowManyWeights (void) {
// return the number of weights in layer
return numWeights;
}
vector<double> LinearLayerNetwork::ReturnTheWeights () {
// return in theWts the current value of all the weights in the layer
return weights; //this function is asking the compiler to return a value of double (weights) and the return weights; function tells the system to return the vector double weights to the system
}
vector<double> LinearLayerNetwork::PrevLayersErrors () {
// find weighted sum of deltas in this layer, being errors for prev layer : return result
vector<double> errorcount(numInputs, 0); //temp vector for storing outputs
for (int ctr = 0; ctr < numInputs; ctr++) // loops through the below function
{
for (int ctr2 = 0; ctr2 < numNeurons; ctr2++)
{
errorcount[ctr] += deltas[ctr2] * weights[ctr2*(numInputs +1) + ctr + 1]; //tells the network take errorcount vectore at possistion of the counter and initilise it to the deltas at possistion 0 and * by the weights at possistion of counter plus 1
}
}
return errorcount; // returns my vector of errorcount thats storing the output of the prev layer errors
}
// Implementation of SigmoidalLayerNetwork *****************************
SigmoidalLayerNetwork::SigmoidalLayerNetwork (int numIns, int numOuts)
:LinearLayerNetwork (numIns, numOuts) {
// just use inherited constructor - no extra variables to initialise
}
SigmoidalLayerNetwork::~SigmoidalLayerNetwork() {
// destructor - does not need to do anything other than call inherited destructor
}
void SigmoidalLayerNetwork::CalcOutputs(vector<double> ins) {
// Calculate outputs being Sigmoid (WeightedSum of ins)
LinearLayerNetwork::CalcOutputs(ins); // takes the function of LinearLayerNetwork calcoutputs and uses inheritance to take the member variables.
for (int i = 0; i < outputs.size(); i++) //loops through the function for each output of the vector rather than the entire vector at once
{
outputs[i] = 1.0 / (1.0 + exp(-outputs[i])); // states that outputs is equal to 1/1 + the expinential function(-outputs)
}
}
void SigmoidalLayerNetwork::FindDeltas (vector<double> errors) {
// Calculate the Deltas for the layer -
// For this class these are Outputs * (1 - Outputs) * Errors
for (int i = 0; i < deltas.size(); i++) //used to loop through the vector for the below function
{
deltas[i] = outputs[i] * (1.0 - outputs[i]) *errors[i]; //calculates the deltas by taking the outputs and multiplying the the (1-outputs) and multiplying by errors (sets a value of 1 -outputs *errors *outputs as delta)
}
}
// Implementation of MultiLayerNetwork *****************************
MultiLayerNetwork::MultiLayerNetwork (int numIns, int numOuts, LinearLayerNetwork *tonextlayer)
:SigmoidalLayerNetwork (numIns, numOuts) {
// construct a hidden layer with numIns inputs and numOuts outputs
// where (a pointer to) its next layer is in tonextlayer
// use inherited constructor for hidden layer
// and attach the pointer to the next layer that is passed
nextlayer = tonextlayer;
}
MultiLayerNetwork::~MultiLayerNetwork() {
delete nextlayer; // remove output layer, then auto-call inherited destructor
}
void MultiLayerNetwork::CalcOutputs(vector<double> ins) {
// calculate the outputs of network given the inputs ins
SigmoidalLayerNetwork::CalcOutputs(ins); //calls the inherited function of calcOutputs from the sigmoidlayer
nextlayer->CalcOutputs(outputs); // tells the network to point to the next layer and tells it that (this) uses calcOutputs with the outputs veriable as a condidition
}
void MultiLayerNetwork::StoreOutputs(int n, dataset &data) {
nextlayer->StoreOutputs(n, data);// calls the StoreOutputs function from the previous layer and points (this) to the nextlayer and returns the nth dataset
}
void MultiLayerNetwork::FindDeltas (vector<double> errors) {
// find all deltas in the network
nextlayer->FindDeltas(errors); //points to the next layer finddeltas method passing errors as a peramiter
SigmoidalLayerNetwork::FindDeltas(nextlayer->PrevLayersErrors()); //calls the finddeltas function from the sigmoid layer and points it tothr next layer and tells it (this) is calculated using prev layer errors
}
void MultiLayerNetwork::ChangeAllWeights(vector<double> ins, double learnRate, double momentum) {
// Change all weights in network
SigmoidalLayerNetwork::ChangeAllWeights(ins, learnRate, momentum); // calls the sigmoid layer change all weights and pases them the peramiters of the method
nextlayer->ChangeAllWeights(outputs, learnRate, momentum); // this tells the network take the change in weights and move it to the next layer and by taking outputs from previous layer and passing it as a peramiter
}
void MultiLayerNetwork::SetTheWeights(vector<double> initWt) {
// load all weights in network using values in initWt
// initWt has the weights for this layer, followed by those for next layer
// first numWeights weights are for this layer
// set vector wthis so has weights from start of initWt til one before numWeights
vector<double> wthis(initWt.begin(), initWt.begin() + numWeights);
// set these into this layer
SigmoidalLayerNetwork::SetTheWeights(wthis);
// next copy rest of weights from initWt[numWeights..] to vector wrest
vector<double> wrest(initWt.begin() + numWeights, initWt.end());
// and then send them to the next layer
nextlayer->SetTheWeights(wrest);
}
int MultiLayerNetwork::HowManyWeights (void) {
// return the number of weights in network
return nextlayer->HowManyWeights() + numWeights; // takes a pointer to the nextlayer and tells the network nextlayer(this) = howmanyweights then add the number of weights (this layer) and return them both
}
vector<double> MultiLayerNetwork::ReturnTheWeights () {
// return the weights of the network into theWts
// the weights in this layer are put at the start, followed by those of next layer
vector<double> tmpWts = weights; //stores the weights on this layer into a tempry vector to prevent overwrighting of data
vector<double> strWts = nextlayer->ReturnTheWeights(); //takes a tempry vector and assigns it to a pointer of nextlayer(this) + return the weights inherited from sigmoid in the next layer
tmpWts.insert(tmpWts.end(), strWts.begin(), strWts.end()); // tells the network, take my vector of tmpWts and add on to the end of tmpWts the vector from nextlayer the start of strWts until the end of strWts
return tmpWts; //returns the tmpWts vector with the weights of this and the next layer
}
| true |
28832687f40eddad2893ff42ecaa16242c8ba876
|
C++
|
nagyistoce/millipede
|
/dev/s_golodetz/New Partition Forest Testbed 2/RegionProperties.h
|
UTF-8
| 1,373 | 2.640625 | 3 |
[] |
no_license
|
/***
* millipede: RegionProperties.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_MILLIPEDE_REGIONPROPERTIES
#define H_MILLIPEDE_REGIONPROPERTIES
#include <vector>
#include "VoxelProperties.h"
namespace mp {
struct RegionProperties
{
int area;
double meanGreyValue;
RegionProperties() : area(0), meanGreyValue(0) {}
explicit RegionProperties(int area_, double meanGreyValue_) : area(area_), meanGreyValue(meanGreyValue_) {}
static RegionProperties combine(const std::vector<RegionProperties>& childProperties)
{
// Sample implementation
if(childProperties.empty()) /* NYI */ throw 23;
int areaSum = 0;
double greyValueSum = 0;
for(size_t i=0, size=childProperties.size(); i<size; ++i)
{
areaSum += childProperties[i].area;
greyValueSum += childProperties[i].area * childProperties[i].meanGreyValue;
}
return RegionProperties(areaSum, greyValueSum / areaSum);
}
static RegionProperties combine(const std::vector<VoxelProperties>& childProperties)
{
// Sample implementation
if(childProperties.empty()) /* NYI */ throw 23;
double sum = 0;
for(size_t i=0, size=childProperties.size(); i<size; ++i)
{
sum += childProperties[i].greyValue;
}
return RegionProperties((int)childProperties.size(), sum / childProperties.size());
}
};
}
#endif
| true |
1307acadecf4f55f98ac0f82ed2bffaef7e8acfb
|
C++
|
hmc-cs-jamelang/hmc-tessellate
|
/src/utilities.hpp
|
UTF-8
| 648 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <iostream>
#include <sstream>
#include <random>
namespace hmc { namespace utilities {
std::default_random_engine random_generator;
void set_random_state_true_random()
{
random_generator.seed(std::random_device{}());
}
std::string get_random_state()
{
std::ostringstream s;
s << random_generator;
return s.str();
}
void set_random_state(std::string state)
{
std::istringstream {state} >> random_generator;
}
double uniform(double a, double b)
{
return std::uniform_real_distribution<double>(a, b)(random_generator);
}
}}
| true |
d9d683c142891233db0e867952a330c2e465bbf5
|
C++
|
yami/DBricks
|
/src/util/string.hxx
|
UTF-8
| 351 | 2.703125 | 3 |
[] |
no_license
|
#ifndef STRING_HXX
#define STRING_HXX
#include <cstring>
namespace util {
inline bool string_equal(const char* s1, const char* s2)
{
using namespace std;
return !strcmp(s1, s2);
}
inline bool string_iequal(const char* s1, const char* s2)
{
using namespace std;
return !strcasecmp(s1, s2);
}
} // namespace
#endif // STRING_HXX
| true |
d3d43bac054bba82dac5b9d177d5e3de69f2bfc9
|
C++
|
JerryTheUser/Leetcode
|
/Letter_Combinations_of_a_Phone_Number.cpp
|
UTF-8
| 1,180 | 3.3125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.size() == 0)
return vector<string>();
unordered_map<char, std::string> table {{'2',"abc"}, {'3',"def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
int product = 1, iter = 1, idx = 0;
for(auto& digit : digits)
product *= table[digit].size();
vector<string> ret(product, "");
for(auto& digit : digits){
idx = 0;
product /= table[digit].size();
for(int i=0 ; i<iter ; ++i){
for(int j=0 ; j<table[digit].size() ; ++j){
for(int k=0 ; k<product ; ++k){
ret[idx++] += table[digit][j];
}
}
}
iter *= table[digit].size();
}
return ret;
}
};
int main(){
Solution sol;
vector<string> result = sol.letterCombinations("234");
for(auto& str : result)
cout << str << ' ';
cout << '\n';
return 0;
}
| true |
65eac87dccbe9205704353fbfb504c38ccc86614
|
C++
|
kgrojas/MI_Proyecto
|
/main.cpp
|
UTF-8
| 4,932 | 3.1875 | 3 |
[] |
no_license
|
/* Un ciclista desea obtener una aplicacion que le permita obtener datos estadísticos sobre sus*/
// entrenamientos con el fin de mejorar en su actividad.
// El ciclista nos cuenta que registra una cantidad aleatoria de vueltas, que elige también de forma
// aleatoria, de las 20 vueltas que realiza en cada entrenamiento.
// De cada vuelta siempre se conoce:
// ● Su posición (primera vuelta, segunda vuelta, etc)
// ● Su duración, expresada como un número entero en el formato MMSS
// (minutos,segundos)
// También se conoce la extensión de la vuelta expresada en Km, para todas las vueltas es la
// misma ya que el ciclista realiza los entrenamientos en un circuito cerrado.
#include<stdio.h>
#include<iostream>
using namespace std;
#define VUELTAS (20)
#define KMdeVUELTA (5)//Kilometros
void leer(string mensaje, int &valor) {
cout << mensaje;
cin >> valor;
return;
}
void leer(string mensaje, float &valor) {
cout << mensaje;
cin >> valor;
return;
}
void entradaErronea (int &entradasErroneas){
system("cls");
cout <<endl<< "INGRESE UN VALOR CORRECTO!!: \n" << "Entradas erroneas: " << ++entradasErroneas <<endl<<endl;
}
void calcularTiempo (int &valor1, char &mitadSuperior, char &mitadInferior, int divisor,int vueltaACargar)
{
int dividendo=1;
for (int i = 0; i < divisor; i++) {
dividendo *= 10;
}
cout << "ingrese el tiempo de vuelta "<< vueltaACargar << " en MMSS: ";
cin >> valor1;
mitadSuperior=valor1/dividendo;
mitadInferior=valor1%dividendo;
}
int calcTiempoReduc(int tMax, int tMin){
int minTMax, segTMax, minTMin, segTMin, segTMaxTotal, segTMinTotal;
float tiempoReduc;
minTMax = tMax / 100;
segTMax = tMax % 100;
minTMin = tMin / 100;
segTMin = tMin % 100;
segTMaxTotal = (minTMax * 60) + segTMax;
segTMinTotal = (minTMin * 60) + segTMin;
tiempoReduc = segTMaxTotal - segTMinTotal;
return (tiempoReduc / segTMaxTotal) * 100;
}
int cargarDatos (int &vueltaACargar,int tiempoDeVuelta)
{
int entradasErroneas = 0;
char minutos = 0;
char segundos = 0;
int divisor = 2;
while (vueltaACargar < 0 || vueltaACargar > VUELTAS) {
entradaErronea(entradasErroneas);
leer(" Ingrese la vuelta a cargar (solo se aceptan valores del 1 al 20) \n Ingre 0 para SALIR: ",
vueltaACargar);
}
if (vueltaACargar == 0) {
return 1;
}
calcularTiempo (tiempoDeVuelta,minutos,segundos,divisor,vueltaACargar);
while (minutos > 59 || segundos > 59 || tiempoDeVuelta <= 0) {
entradaErronea(entradasErroneas);
calcularTiempo (tiempoDeVuelta,minutos,segundos,divisor,vueltaACargar);
}
return tiempoDeVuelta;
}
int vueltaRapida(int entrenamiento[],int vueltas){
int rapida = 6060;
for (int i = 1; i < vueltas; i++)
{
if(entrenamiento[i]!=0 && entrenamiento[i] < rapida) {
rapida = entrenamiento[i];
}
}
return rapida;
}
int vueltaLenta(int entrenamiento[],int vueltas){
int lenta = 0;
for (int i = 1; i < vueltas; i++){
if(entrenamiento[i] > lenta) {
lenta = entrenamiento[i];
}
}
return lenta;
}
void imprimirValores(float porcentaje, int rapida, int lenta, int entrenamiento[],int vueltas ){
cout << "Vuelta mas rapida: " << endl;
for (int i = 1; i < vueltas; i++){
if(entrenamiento[i] == rapida){
cout <<"Vuelta: "<< i<<" "<< entrenamiento[i]<<" MMSS"<< endl;
}
}
cout << "Vuelta mas lenta: " << endl;
for (int i = 1; i < vueltas; i++){
if(entrenamiento[i] == lenta){
cout <<"Vuelta: "<< i<<" "<< entrenamiento[i]<<" MMSS"<< endl;
}
}
cout << "El porcentaje de reduccion de tiempo es : " << porcentaje << endl;
}
int main() {
int entrenamiento [VUELTAS+1]= {0};
int vueltaACargar = 1;
int tiempoDeVuelta = 0;
int largoVuelta = 0;
leer("Ingrese la distancia de la Vuelta Completa: ",largoVuelta);
system("cls");
while ( vueltaACargar != 0 ) {
leer(" Ingrese la vuelta a cargar (solo se aceptan valores del 1 al 20) \n Ingrese 0 para SALIR: ", vueltaACargar);
tiempoDeVuelta= cargarDatos(vueltaACargar, tiempoDeVuelta);
entrenamiento [vueltaACargar] = tiempoDeVuelta;
if (vueltaACargar != 0){
} else{
system("cls");
for (int i = 1; i <= VUELTAS; i++)
{
if (entrenamiento[i] != 0) {
cout <<"Vuelta "<<i<< " : " << entrenamiento[i] << endl;
}
}
}
}
int rapida = vueltaRapida(entrenamiento,VUELTAS);
int lenta = vueltaLenta(entrenamiento, VUELTAS);
float porcentajeReduc = calcTiempoReduc(lenta, rapida);
imprimirValores(porcentajeReduc,rapida, lenta, entrenamiento,VUELTAS);
system ("pause");
return 0;
}
| true |
26eb913dc21e432e7cccde39e335f8ea662b9673
|
C++
|
Pothulapati/competitive-practice
|
/SMARTINTERVIEWS/missing.cpp
|
UTF-8
| 360 | 2.59375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
int i,n,sum;
cin >> n;
sum = ((n+1)*(n+2))/2;
int a;
int ssum = 0;
for(i=0;i<n;i++)
{
cin >> a;
ssum += a;
}
cout << sum - ssum << endl;
}
return 0;
}
| true |
23cd6c2a4460aca4e3663c620300aaed194972e9
|
C++
|
caiopngoncalves/uri
|
/1911.cpp
|
UTF-8
| 578 | 2.65625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
map<string ,string > m;
int diff(string &a, string &b)
{
int dif = 0;
for (int i = 0 ; i < min(a.size(), b.size()); ++i)
{
if (a[i] != b[i]) ++dif;
}
return dif + abs(a.size() - b.size());
}
int main()
{
int n, m1;
string s1, s2;
int roubou;
while (cin >> n, n)
{
roubou = 0;
for (int i = 0 ; i < n; ++i)
{
cin >> s1 >> s2;
m[s1] = s2;
}
cin >> m1;
for (int i = 0 ; i < m1; ++i)
{
cin >> s1 >> s2;
if (diff(s2, m[s1]) > 1) ++roubou;
}
cout << roubou << '\n';
}
}
| true |
d05668492a90f84dcda05e61b80a99fcb1f15723
|
C++
|
JpHu2017/gof_pattern
|
/apps/abstract_factory/include/laptop.h
|
UTF-8
| 486 | 2.5625 | 3 |
[] |
no_license
|
#ifndef GOF_PATTERN_LAPTOP_H
#define GOF_PATTERN_LAPTOP_H
#include <memory>
#include <string>
#include "cz_def.h"
namespace gof {
class CZ_EXPORTS Laptop {
public:
typedef std::shared_ptr<Laptop> Ptr;
Laptop();
//use keyword 'virtual' to make that subclass of Computer could be destructed
virtual ~Laptop();
virtual const std::string brand() const = 0;
virtual const std::string type() const = 0;
private:
};
}
#endif //GOF_PATTERN_LAPTOP_H
| true |
0f7a5ea27785f9b414852ae2b7c8c5926c72d859
|
C++
|
ManuelSch/LastMechStanding
|
/LastMechStanding/LastMechStanding/Util/Shader.cpp
|
UTF-8
| 1,851 | 3.0625 | 3 |
[] |
no_license
|
#include "Shader.h"
Shader::Shader(const string & vertexShaderFilePath, const string & fragmentShaderFilePath) {
// create shader program:
shaderProgram = glCreateProgram();
// load shader source code:
loadShader(vertexShaderFilePath, GL_VERTEX_SHADER, vertexShader);
loadShader(fragmentShaderFilePath, GL_FRAGMENT_SHADER, fragmentShader);
}
Shader::~Shader() {
glDeleteProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void Shader::useShader() {
glUseProgram(shaderProgram);
}
GLint Shader::getUniformLocation(const string & uniformName) {
return glGetUniformLocation(shaderProgram, uniformName.c_str());;
}
void Shader::loadShader(const string & filePath, GLenum type, GLuint & shader) {
ifstream shaderFile(filePath);
if (shaderFile.good()) {
// read source code from shader file:
string code = string(istreambuf_iterator<char>(shaderFile), istreambuf_iterator<char>());
shaderFile.close();
// create shader object:
shader = glCreateShader(type);
// attach source code to the shader object and compile:
auto codePtr = code.c_str();
glShaderSource(shader, 1, &codePtr, NULL);
glCompileShader(shader);
// check if shader compilation was successful:
GLint success;
GLchar infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shader, 512, NULL, infoLog);
cout << "ERROR: Shader compilation failed:\n" << infoLog << endl;
}
// attach shader to program object and link it:
glAttachShader(shaderProgram, shader);
glLinkProgram(shaderProgram);
// check if program linking was successful:
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
cout << "ERROR: Shader linking failed:\n" << infoLog << endl;
}
}
}
| true |
5d72786bfd3aaa8c760a0b9fa3f5ef19c092bd90
|
C++
|
DVDemon/mai_oop
|
/Example75_SimpleAllocator/TAllocationBlock.h
|
UTF-8
| 567 | 2.546875 | 3 |
[] |
no_license
|
/*
* File: TAllocationBlock.h
* Author: dvdemon
*
* Created on July 28, 2015, 9:17 AM
*/
#ifndef TALLOCATIONBLOCK_H
#define TALLOCATIONBLOCK_H
#include <cstdlib>
class TAllocationBlock {
public:
TAllocationBlock(uint64_t size,uint64_t count);
void *allocate();
void deallocate(void *pointer);
bool has_free_blocks();
virtual ~TAllocationBlock();
private:
uint64_t _size;
uint64_t _count;
char *_used_blocks;
void **_free_blocks;
uint64_t _free_count;
};
#endif /* TALLOCATIONBLOCK_H */
| true |
142ad8f42f49862413971fdd022aaaa1e286abb4
|
C++
|
Vild/testbench
|
/gl_testbench/Vulkan/VertexBufferVK.cpp
|
UTF-8
| 3,020 | 2.796875 | 3 |
[] |
no_license
|
#include "VertexBufferVK.h"
#include "VulkanRenderer.h"
#include "../IA.h"
#include "MeshVK.h"
VertexBufferVK::VertexBufferVK(VulkanRenderer* renderer, size_t size) : _renderer(renderer), _device(renderer->_device), _size(size) {}
VertexBufferVK::~VertexBufferVK() {
_device.destroyBuffer(_buffer);
_device.freeMemory(_bufferMemory);
}
void VertexBufferVK::setData(const void* data, size_t size, size_t offset) {
static vk::PhysicalDeviceProperties pdp = _renderer->_physicalDevice.getProperties();
static auto minSBOA = pdp.limits.minStorageBufferOffsetAlignment;
EXPECT_ASSERT((minSBOA & (minSBOA - 1)) == 0, "minSBOA is not power-of-2");
// TODO: Make a staging buffer and a final buffer
if (!_buffer) {
// _size = sizeof(elementtype) * COUNT
size_t count = _size / size;
size_t elementSize = (size + minSBOA - 1) & ~(minSBOA - 1);
vk::DeviceSize bufferSize = elementSize * count;
_renderer->createBuffer(bufferSize, vk::BufferUsageFlagBits::eStorageBuffer,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, _buffer, _bufferMemory);
}
EXPECT_ASSERT(offset % size == 0, "offset % size must be 0");
size_t idx = offset / size;
size = (size + minSBOA - 1) & ~(minSBOA - 1);
offset = idx * size;
void* ptr = _device.mapMemory(_bufferMemory, offset, size);
memcpy(ptr, data, size);
_device.unmapMemory(_bufferMemory);
}
void VertexBufferVK::bind(MeshVK* mesh, size_t offset, size_t size, uint32_t location) {
static vk::PhysicalDeviceProperties pdp = _renderer->_physicalDevice.getProperties();
static auto minSBOA = pdp.limits.minStorageBufferOffsetAlignment;
EXPECT_ASSERT((minSBOA & (minSBOA - 1)) == 0, "minSBOA is not power-of-2");
// This is very ugly, temporary until I can think of any other way.
if (location == POSITION)
_descriptorWrite.dstSet = mesh->getDescriptorSet(DescriptorType::position);
else if (location == INDEX)
_descriptorWrite.dstSet = mesh->getDescriptorSet(DescriptorType::index);
else if (location == MODEL)
_descriptorWrite.dstSet = mesh->getDescriptorSet(DescriptorType::model);
EXPECT_ASSERT(offset % size == 0, "offset % size must be 0");
size_t idx = offset / size;
size = (size + minSBOA - 1) & ~(minSBOA - 1);
offset = idx * size;
_bufferInfo.buffer = _buffer;
_bufferInfo.offset = offset;
_bufferInfo.range = size;
_descriptorWrite.dstBinding = location;
_descriptorWrite.dstArrayElement = 0;
_descriptorWrite.descriptorType = vk::DescriptorType::eStorageBuffer;
_descriptorWrite.descriptorCount = 1;
_descriptorWrite.pBufferInfo = &_bufferInfo;
_descriptorWrite.pImageInfo = nullptr;
_descriptorWrite.pTexelBufferView = nullptr;
// Applies the final info needed to update descriptor sets.
_device.updateDescriptorSets(_descriptorWrite, nullptr);
// printf("%s(offset: 0x%zX, size: 0x%zX, location: %u);\n", __PRETTY_FUNCTION__, offset, size, location);
}
void VertexBufferVK::unbind() {
STUB();
}
size_t VertexBufferVK::getSize() {
STUB();
return _size;
}
| true |
d34cd2219fe328a80ad17939a446434e4dffbeca
|
C++
|
ayang55/Lab-3
|
/prog5.cc
|
UTF-8
| 668 | 3.703125 | 4 |
[] |
no_license
|
/*
* @file: prof5.cc
* @author: Andrew Yang
* @date: 9/8/2020
* @brief This is our 3rd lab, and for this program you compare the size of two intergers.
*/
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
double ctof; // equivalent Celsius temperature
double ftoc; // equivalent Fahrenheit temperature.
int fah = 56; //declare and initialize at the same time - page 48
int cel = 20;
ctof = 9.0/5 * cel + 32;
ftoc = 5.0/9 * (fah -32);
cout << cel << " degrees Celsius in Fahrenheit is " << ctof << endl;
cout << fah << " degrees Fahrenheit in Celsius is " << (int)(ftoc*10)/10.0<< endl;
return (EXIT_SUCCESS);
}
| true |
681dd7c5cbf2e17039fbc702496554fd3ccdab90
|
C++
|
ElementAyush/Code
|
/OnlineJudges/codeshef/New folder/SPELLBOB.cpp
|
UTF-8
| 1,249 | 2.84375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std ;
int main()
{
int test_case ;
cin >> test_case ;
for(int i = 0 ; i < test_case ; i++)
{
string s1 , s2 ;
cin >> s1 >> s2 ;
if(s1 == "bob" || s2 == "bob")
{
cout << "yes" << "\n" ;
continue ;
}
int countb = 0 , counto = 0 , counta = 0;
for(int j = 0 ; j < 3 ; j++)
{
if((s1[j] == 'b' && s2[j] == 'o') || (s1[j] == 'o' && s2[j] == 'b'))
counta++ ;
else if(s1[j] == 'o' && s2[j] != 'b' || s1[j] != 'b' && s2[j] == 'o')
counto++ ;
else if(s1[j] == 'b' && s2[j] != 'o' || s1[j] != 'o' && s2[j] == 'b')
countb++ ;
}
if(counta > 2)
{
cout << "yes" << "\n" ;
continue ;
}
if(countb == 2 && counto == 0)
{
if(counta > 0)
{
cout << "yes" << "\n" ;
continue ;
}
}
if(countb == 1 && counto == 0)
{
if(counta > 1)
{
cout << "yes" << "n" ;
continue ;
}
}
if(countb == 0 && counto == 1)
{
if(counta > 1)
{
cout << "yes" << "\n" ;
continue ;
}
}
if(countb == 1 && counto == 1)
{
if(counta > 0)
{
cout << "yes" << "\n" ;
continue ;
}
}
if(countb == 2 && counto == 1)
{
cout << "yes" << "\n" ;
continue ;
}
cout << "no" << "\n" ;
}
}
| true |
7f9798aab9ddcc21f5add89d991ee136abd820df
|
C++
|
andrei828/CPP_Projects
|
/OOP_Project_Company/Director.hpp
|
UTF-8
| 704 | 2.96875 | 3 |
[] |
no_license
|
#ifndef _INCL_DIRECTOR
#define _INCL_DIRECTOR
#include "Dependencies.hpp"
#include "Personnel.hpp"
class Director: virtual public Personnel {
protected:
double Bonus;
public:
virtual double get_salary(Movie *);
/* constructors */
Director(uint Id, std::string Name, double Salary,
std::vector< std::pair< std::string, Movie * > >& Movies, double Bonus):
Personnel(Id, Name, Salary, Movies), Bonus(Bonus) {}
};
double Director::get_salary(Movie *) {
double sum = 0;
std::vector< std::pair< std::string, Movie * > >::iterator it;
for (it = MovieDevelopmentList.begin(); it != MovieDevelopmentList.end(); ++it)
sum += (it->second->get_profit() * Salary + Bonus);
return sum;
}
#endif
| true |
aefe4061de2eefe3580c8d14e2f83d795959848e
|
C++
|
whztt07/acm
|
/uva/489/Sov_03_22_2012.cpp
|
UTF-8
| 777 | 3.234375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
void clean(string &s)
{
for (int i = 0; i < s.size(); i ++)
{
if (s.find(s[i]) != i)
{
s.erase(s.begin()+i);
i --;
}
}
}
int main()
{
int n;
while (cin>>n && n!=-1)
{
string hang,cho;
cin >> hang >> cho;
clean(hang);
clean(cho);
int cnt = 0;
for (int i = 0; i < cho.size(); i ++)
{
if (hang.size() == 0 || cnt == 7)
break;
int found = hang.find(cho[i]);
if (found != -1)
hang.erase(hang.begin()+found);
else
cnt ++;
}
cout << "Round " << n << endl;
//cout << hang.size() << " " << cnt << endl;
if (hang.size() == 0)
cout << "You win." << endl;
else if (cnt < 7)
cout << "You chickened out." << endl;
else
cout << "You lose." << endl;
}
}
| true |
36ca7c9856fd880c03077787f2c19182dc250daa
|
C++
|
TuringJuniors/Fortran
|
/SmartHome/smartLamp/µC(Arduino)/Smart_lamp_arduino/Smart_lamp_arduino.ino
|
UTF-8
| 1,464 | 2.84375 | 3 |
[] |
no_license
|
#include <Wire.h>
using namespace std;
#define ON 0
#define OFF 1
#define BLINK 2
#define LED 7
class controlHub{
};
class smartLamp
{
public:
smartLamp(controlHub* newController);
int state=1;
void blink();
void on();
void off();
private:
controlHub* controller;
};
controlHub mainController;
smartLamp lamp1(&mainController);
void smartLamp :: blink(){
double starttime=millis();
while((millis()-starttime)<=50000){
on();
delay(1000);
off();
delay(1000);
}
}
void smartLamp :: on(){
digitalWrite(LED,HIGH);
}
void smartLamp :: off(){
digitalWrite(LED,LOW);
}
void InputHub(int a)
{
int input;
if(Wire.available())
{
input=Wire.read();
}
int buff=Wire.read();
if (input == 0)
{
}
else if (input == 1)
{
lamp1.state = 0;
}
else if (input == 2)
{
lamp1.state = 1;
}
else if (input == 3)
{
lamp1.state = 2;
}
}
smartLamp :: smartLamp(controlHub* newController){
controller = newController;
}
void setup() {
Wire.begin(1);
Wire.onReceive(InputHub);
pinMode(LED,OUTPUT);
Serial.begin(9600);
}
void loop() {
switch (lamp1.state){
case ON:
lamp1.on();
break;
case OFF:
lamp1.off();
break;
case BLINK:
lamp1.blink();
break;
}
}
| true |
1da5443e3f74f4aaa59e933f208021dde8c3d084
|
C++
|
nur-alam/CrackingTheCodingInterview
|
/Array Problems/Maximum Subarray/StartEndIndexesOfMaxSubArr.cpp
|
UTF-8
| 773 | 3.25 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int* maxSubArray(vector<int>& nums) {
int size = nums.size();
int curmax = 0;
int maxsum = INT_MIN, i = -1;
int startIndex = 0, endIndex = 0, tempIndex = 0;
while(++i < size) {
curmax = max(nums[i], curmax + nums[i]);
if(nums[i] >= curmax)
tempIndex = i;
if(curmax > maxsum) {
maxsum = curmax;
startIndex = tempIndex;
endIndex = i;
}
}
int *indexes = (int *)malloc(2*sizeof(int)); // new int[2];
indexes[0] = startIndex;
indexes[1] = endIndex;
return indexes;
}
int main() {
vector<int> vec{-2,1,-3,4,-1,2,1,-5,4};
int *indexes = maxSubArray(vec);
cout << indexes[0] << " " << indexes[1] << endl;
}
| true |
a4734d832f543d27d7d5b342e8cee9c6f122fae2
|
C++
|
RazrFalcon/ttf-explorer
|
/src/tables/kern.cpp
|
UTF-8
| 16,959 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#include <bitset>
#include "src/algo.h"
#include "tables.h"
struct OpenTypeCoverage
{
static const int Size = 1;
static const QString Type;
static OpenTypeCoverage parse(const quint8 *data)
{ return { data[0] }; }
static QString toString(const OpenTypeCoverage &value)
{
std::bitset<8> bits(value.d);
auto flagsStr = QString::fromUtf8(bits.to_string().c_str()) + '\n';
if (bits[0]) { flagsStr += "Bit 0: Horizontal\n"; }
if (bits[1]) { flagsStr += "Bit 1: Has minimum values\n"; }
if (bits[2]) { flagsStr += "Bit 2: Cross-stream\n"; }
if (bits[3]) { flagsStr += "Bit 3: Override\n"; }
// 4-7 - reserved
flagsStr.chop(1); // trim trailing newline
return flagsStr;
}
quint8 d;
};
const QString OpenTypeCoverage::Type = Parser::BitflagsType;
struct AppleCoverage
{
static const int Size = 1;
static const QString Type;
static AppleCoverage parse(const quint8 *data)
{ return { data[0] }; }
static QString toString(const AppleCoverage &value)
{
std::bitset<8> bits(value.d);
auto flagsStr = QString::fromUtf8(bits.to_string().c_str()) + '\n';
// 0-4 - reserved
if (bits[5]) { flagsStr += "Bit 5: Has variation\n"; }
if (bits[6]) { flagsStr += "Bit 6: Cross-stream\n"; }
if (bits[7]) { flagsStr += "Bit 7: Vertical\n"; }
flagsStr.chop(1); // trim trailing newline
return flagsStr;
}
quint8 d;
};
const QString AppleCoverage::Type = Parser::BitflagsType;
static void parseFormat0(Parser &parser)
{
const auto count = parser.read<UInt16>("Number of kerning pairs");
parser.read<UInt16>("Search range");
parser.read<UInt16>("Entry selector");
parser.read<UInt16>("Range shift");
parser.readArray("Values", count, [&](const auto index){
parser.beginGroup(index);
parser.read<GlyphId>("Left");
parser.read<GlyphId>("Right");
parser.read<Int16>("Value");
parser.endGroup();
});
}
namespace Format1 {
struct EntryFlags
{
static const int Size = 2;
static const QString Type;
static EntryFlags parse(const quint8 *data)
{ return { UInt16::parse(data) }; }
static QString toString(const EntryFlags &value)
{
std::bitset<16> bits(value.d);
auto flagsStr = "Offset " + numberToString(value.d & 0x3FFF) + '\n';
flagsStr += QString::fromUtf8(bits.to_string().c_str()) + '\n';
if (bits[15]) { flagsStr += "Bit 15: Push onto the kerning stack\n"; }
flagsStr.chop(1); // trim trailing newline
return flagsStr;
}
quint16 d;
};
const QString EntryFlags::Type = Parser::BitflagsType;
struct Action
{
static const int Size = 2;
static const QString Type;
static Action parse(const quint8 *data)
{ return { UInt16::parse(data) }; }
static QString toString(const Action &value)
{
static const QString value1 = QLatin1String("Kerning 0. End of List.");
static const QString value2 = QLatin1String("Reset cross-stream. End of List.");
if (value.d == 0x0001) {
return value1;
} else if (value.d == 0x8001) {
return value1;
} else {
return QString("Kerning %1").arg(qint16(value.d));
}
}
quint16 d;
};
const QString Action::Type = QLatin1String("Action");
struct Entry {
quint16 newState;
quint16 flags;
};
// Based on: https://github.com/harfbuzz/harfbuzz/blob/5b91c52083aee1653c0cf1e778923de00c08fa5d/src/hb-aat-layout-common.hh#L524
static quint32 detectNumberOfEntries(
const qint32 numberOfClasses,
const quint16 stateArrayOffset,
const QByteArray states,
const QVector<Entry> &entries
) {
qint32 minState = 0;
qint32 maxState = 0;
quint32 numEntries = 0;
qint32 statePos = 0;
qint32 stateNeg = 0;
quint32 entry = 0;
qint32 maxOps = 0x3FFFFFFF;
while (minState < stateNeg || statePos <= maxState) {
if (minState < stateNeg) {
// Negative states.
maxOps -= stateNeg - minState;
if (maxOps <= 0) {
throw QString("invalid state machine");
}
// Sweep new states.
const qint32 end = minState * numberOfClasses;
if (end > 0) {
for (qint32 i = end-1; i >= 0; i--) {
if (i - 1 < states.size()) {
numEntries = qMax(numEntries, quint32(states[i - 1]) + 1);
} else {
throw QString("invalid index");
}
}
}
stateNeg = minState;
}
if (statePos <= maxState) {
// Positive states.
maxOps -= maxState - statePos + 1;
if (maxOps <= 0) {
throw QString("invalid state machine");
}
// Sweep new states.
const auto start = statePos * numberOfClasses;
const auto end = (maxState + 1) * numberOfClasses;
for (int i = start; i < end; i++) {
if (i < states.size()) {
numEntries = qMax(numEntries, quint32(states[i]) + 1);
} else {
throw QString("invalid index");
}
}
statePos = maxState + 1;
}
maxOps -= int(numEntries - entry);
if (maxOps <= 0) {
throw QString("invalid state machine");
}
// Sweep new entries.
for (quint32 i = entry; i < numEntries; i++) {
if (i >= quint32(entries.size())) {
throw QString("invalid index");
}
const auto newState = (int(entries[i].newState) - int(stateArrayOffset))
/ int(numberOfClasses);
minState = qMin(minState, newState);
maxState = qMax(maxState, newState);
}
entry = numEntries;
}
return numEntries;
}
static void parse(const quint32 subtableSize, Parser &parser)
{
// Sadly, the *State Table for Contextual Kerning* format isn't really documented.
// The AAT kern documentation has only a rough outline and a single example,
// which is clearly not enough to understand how it actually stored.
// And the only FOSS application I know that supports it is HarfBuzz,
// so we are borrowing its implementation.
// No idea how long it took them to figure it out.
//
// Also, there is an obsolete tool called `ftxanalyzer`,
// from the *Apple Font Tool Suite* that can dump an AAT kern table as an XML.
// But the result is still pretty abstract and it's hard to understand
// how it was produced.
// It's not trivial to install it on a modern Mac, so here is a useful
// instruction (not mine):
// https://gist.github.com/thetrevorharmon/9afdeb41a74f8f32b9561eeb83b10eff
//
// And here are some Apple fonts that actually use this format
// (at least in macOS 10.14):
// - Diwan Thuluth.ttf
// - Farisi.ttf
// - GeezaPro.ttc
// - Mishafi.ttf
// - Waseem.ttc
const auto start = parser.offset();
const auto shadow = parser.shadow();
const quint16 numberOfClasses = parser.read<UInt16>("Number of classes");
// Note that offsets are not from the subtable start,
// but from subtable start + header.
const auto classTableOffset = parser.read<Offset16>("Offset to class subtable");
const auto stateArrayOffset = parser.read<Offset16>("Offset to state array");
const auto entryTableOffset = parser.read<Offset16>("Offset to entry table");
const auto valuesOffset = parser.read<Offset16>("Offset to values");
// Check that offsets are properly ordered.
// We do not support random order.
Q_ASSERT(classTableOffset < stateArrayOffset);
Q_ASSERT(stateArrayOffset < entryTableOffset);
Q_ASSERT(entryTableOffset < valuesOffset);
auto numberOfEntries = 0;
{
// Collect states.
auto s1 = shadow;
s1.advanceTo(stateArrayOffset);
// We don't know the length of the states yet,
// so use all the data from offset to the end of the subtable.
const auto states = s1.readBytes(subtableSize - stateArrayOffset);
// Collect entries.
auto s2 = shadow;
s2.advanceTo(entryTableOffset);
// We don't know the length of the states yet,
// so use all the data from offset to the end of the subtable.
const auto entriesCount = (subtableSize - entryTableOffset) / 4;
QVector<Entry> entries;
for (quint32 i = 0; i < entriesCount; i++) {
entries.append({
s2.read<UInt16>(),
s2.read<UInt16>(),
});
}
numberOfEntries = detectNumberOfEntries(numberOfClasses, stateArrayOffset, states, entries);
}
parser.padTo(start + classTableOffset);
parser.beginGroup("Class Subtable");
parser.read<GlyphId>("First glyph");
const auto numberOfGlyphs = parser.read<UInt16>("Number of glyphs");
parser.readBasicArray<UInt8>("Classes", numberOfGlyphs);
parser.endGroup();
parser.padTo(start + stateArrayOffset);
// We only assume that an *entry table* is right after *state array*.
const auto arraysCount = (entryTableOffset - stateArrayOffset) / numberOfClasses;
parser.readArray("State Array", arraysCount, [&](const auto /*index*/){
parser.readBytes("Data", numberOfClasses);
});
parser.padTo(start + entryTableOffset);
parser.readArray("Entries", numberOfEntries, [&](const auto index){
parser.beginGroup(index);
parser.read<Offset16>("State offset");
parser.read<EntryFlags>("Flags");
parser.endGroup();
});
parser.padTo(start + valuesOffset);
const auto numberOfActions = ((subtableSize - 8) - (parser.offset() - start)) / 2;
parser.readBasicArray<Action>("Actions", numberOfActions);
}
}
static quint32 format2DetectNumberOfClasses(const quint32 offset, ShadowParser shadow) {
shadow.advanceTo(offset);
shadow.read<GlyphId>();
const auto count = shadow.read<UInt16>();
QSet<quint16> classes;
for (quint32 i = 0; i < count; i++) {
classes.insert(shadow.read<UInt16>());
}
return classes.size();
}
static void parseFormat2(const quint32 subtableStart, Parser &parser)
{
// Apple fonts that are using this table: Apple Chancery.ttf
const auto shadow = parser.shadow();
const auto headerSize = parser.offset() - subtableStart;
parser.read<UInt16>("Row width in bytes");
const auto leftHandTableOffset = parser.read<Offset16>("Offset to left-hand class table");
const auto rightHandTableOffset = parser.read<Offset16>("Offset to right-hand class table");
const auto arrayOffset = parser.read<Offset16>("Offset to kerning array");
const auto rows = format2DetectNumberOfClasses(leftHandTableOffset - headerSize, shadow);
const auto columns = format2DetectNumberOfClasses(rightHandTableOffset - headerSize, shadow);
enum class OffsetType {
LeftHandTable,
RightHandTable,
Array,
};
struct Offset {
OffsetType type;
quint32 offset;
};
std::array<Offset, 3> offsets = {{
{ OffsetType::LeftHandTable, (quint32)leftHandTableOffset },
{ OffsetType::RightHandTable, (quint32)rightHandTableOffset },
{ OffsetType::Array, (quint32)arrayOffset },
}};
algo::sort_all_by_key(offsets, &Offset::offset);
for (const auto offset : offsets) {
if (offset.offset == 0) {
continue;
}
parser.advanceTo(subtableStart + offset.offset);
switch (offset.type) {
case OffsetType::LeftHandTable: {
parser.beginGroup("Left-hand Class Table");
parser.read<GlyphId>("First glyph");
const quint16 count = parser.read<UInt16>("Number of glyphs");
parser.readBasicArray<UInt16>("Classes", count);
parser.endGroup();
break;
}
case OffsetType::RightHandTable: {
parser.beginGroup("Right-hand Class Table");
parser.read<GlyphId>("First glyph");
const quint16 count = parser.read<UInt16>("Number of glyphs");
parser.readBasicArray<UInt16>("Classes", count);
parser.endGroup();
break;
}
case OffsetType::Array: {
parser.readBasicArray<Int16>("Kerning Values", rows * columns);
break;
}
}
}
}
static void parseFormat3(const quint32 subtableStart, const quint32 subtableSize, Parser &parser)
{
// Apple fonts that are using this table: Skia.ttf
const auto glyphCount = parser.read<UInt16>("Number of glyphs");
const auto kernValues = parser.read<UInt8>("Number of kerning values");
const auto leftHandClasses = parser.read<UInt8>("Number of left-hand classes");
const auto rightHandClasses = parser.read<UInt8>("Number of right-hand classes");
parser.read<UInt8>("Reserved");
parser.readBasicArray<Int16>("Kerning Values", kernValues);
parser.readBasicArray<UInt8>("Left-hand Classes", glyphCount);
parser.readBasicArray<UInt8>("Right-hand Classes", glyphCount);
parser.readBasicArray<UInt8>("Indices", int(leftHandClasses) * int(rightHandClasses));
const auto left = int(subtableSize) - int(parser.offset() - subtableStart);
parser.readPadding(left);
}
// https://docs.microsoft.com/en-us/typography/opentype/spec/kern
static void parseKernOpenType(Parser &parser)
{
parser.read<UInt16>("Version");
const auto numberOfTables = parser.read<UInt16>("Number of tables");
parser.readArray("Subtables", numberOfTables, [&](const auto index){
const auto subtableStart = parser.offset();
parser.beginGroup(index);
parser.read<UInt16>("Version");
parser.read<UInt16>("Length");
const auto format = parser.read<UInt8>("Format");
parser.read<OpenTypeCoverage>("Coverage");
switch (format) {
case 0: parseFormat0(parser); break;
case 2: parseFormat2(subtableStart, parser); break;
default: throw QString("%1 is not a valid format").arg(format);
}
parser.endGroup("", QString("Format %1").arg(format));
});
}
// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html
static void parseKernApple(Parser &parser)
{
parser.read<F16DOT16>("Version");
const auto numberOfTables = parser.read<UInt32>("Number of tables");
parser.readArray("Subtables", numberOfTables, [&](const auto index){
const auto subtableStart = parser.offset();
parser.beginGroup(index);
const auto length = parser.read<UInt32>("Length");
// Yes, the coverage and format order is inverted in AAT.
parser.read<AppleCoverage>("Coverage");
const auto format = parser.read<UInt8>("Format");
parser.read<UInt16>("Tuple index");
switch (format) {
case 0: parseFormat0(parser); break;
case 1: Format1::parse(length, parser); break;
case 2: parseFormat2(subtableStart, parser); break;
case 3: parseFormat3(subtableStart, length, parser); break;
default: throw QString("%1 is not a valid format").arg(format);
}
parser.endGroup("", QString("Format %1").arg(format));
});
}
void parseKern(Parser &parser)
{
// The `kern` table has two variants: OpenType one and Apple one.
// And they both have different headers.
// There are no robust way to distinguish them, so we have to guess.
//
// The OpenType one has the first two bytes (UInt16) as a version set to 0.
// While Apple one has the first four bytes (Fixed) set to 1.0
// So the first two bytes in case of an OpenType format will be 0x0000
// and 0x0001 in case of an Apple format.
const auto version = parser.peek<UInt16>();
if (version == 0) {
parseKernOpenType(parser);
} else {
parseKernApple(parser);
}
}
| true |
10f1efb2a42667e002ca36b360a568b092261f96
|
C++
|
nzombiegaming/Learning-C-Luca-to-Pro
|
/L5switch.cpp
|
UTF-8
| 1,608 | 4.3125 | 4 |
[] |
no_license
|
/*
Today we are going to be talking about switch statements. Switch statements are important to clean programming.
Switch statements allow you to use the versitility of if statements but without all of the nested if's.
Switch statements look better and are easy to modify if you need to change something later on (you will need to).
Each case in a switch statement (case 1, 16, 18...) is what you will compare your age too. You could use character,
integers, strings and others with switch statements. If statements do not allow you to us <= >= < > in c++. Switch
statements are good for when you need a lot of options and you have a list of options for the user.
*/
#include <iostream>
using namespace std;
int main(){
int age; //This line declares an integer named age
cout<<"Enter your age\n";
cin>> age;
switch(age){ // Switch statements are basically more compact if statement
//they are commonly used when there is a large amount of options or nested if statments
case 1: //This is a colon not a semicolon REMEMBER THAT!
cout<< "You are too young to do anything. Your age is " <<age <<endl;
break;//Break exits out of the switch statement.
case 16:
cout<< "You are old enough to drive. Your age is " <<age <<endl;
break;
case 18:
cout<<"You can drink alcohol in Canada, Europe and other places. Your age is " <<age <<endl;
break;
case 21:
cout<<"You can drink alcohol in United States. Your age is " <<age <<endl;
break;
default:
cout<<"Your age is not special enough. Your age is " <<age <<endl;
break;
}
return 0;
}
| true |
428ba57ca5aebc8531bd050e01b5729e0f5aaa65
|
C++
|
qgpmztmf/LeetCode
|
/112.cpp
|
UTF-8
| 1,306 | 3.453125 | 3 |
[] |
no_license
|
// 112. Path Sum
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root){
return false;
}
else{
return _hasPathSum(root,sum);
}
}
bool _hasPathSum(TreeNode* root, int sum) {
if(!root) {
if(sum == 0){
return true;
}
else{
return false;
}
}
else{
bool leftValue = _hasPathSum(root -> left, sum - root -> val);
bool rightValue = _hasPathSum(root -> right, sum - root -> val);
if(root -> left == NULL && root -> right == NULL){
return leftValue || rightValue;
}
else if(root -> left != NULL && root -> right == NULL){
return leftValue;
}
else if(root -> left == NULL && root -> right != NULL){
return rightValue;
}
else{
return leftValue || rightValue;
}
}
}
};
| true |
6dff15ae47793604a490b1679f28085fe3dd7279
|
C++
|
andreifreddmironov/TcpServer
|
/tcpthread.cpp
|
UTF-8
| 2,468 | 2.625 | 3 |
[] |
no_license
|
#include "tcpthread.h"
TcpThread::TcpThread(QObject *parent, int socketDescriptor) : QObject(parent),
m_socketDescriptor(socketDescriptor)
{
}
TcpThread::~TcpThread()
{
qDebug() << "TcpThread exit";
if(m_tcpSocket->isOpen())
{
m_tcpSocket->close();
}
delete m_tcpSocket;
m_tcpSocket = NULL;
}
void TcpThread::start()
{
qDebug() << "TcpThread run";
m_tcpSocket = new QTcpSocket();
if (!m_tcpSocket->setSocketDescriptor(m_socketDescriptor))
{
qDebug() << "Error while setSocketDescriptor";
return;
}
//m_tcpSocket->write("Hello, World!!! rrr am echo server!\r\n");
connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(ServerRead()));
connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(ClientDisconnected()));
}
void TcpThread::ServerRead()
{
//qDebug() << "ServerRead";
if(m_tcpSocket->bytesAvailable() > 0)
{
m_buffer += m_tcpSocket->readAll();
parseData();
}
}
void TcpThread::parseData()
{
if((m_buffer.at(0) == START_PREFIX) &&
(m_buffer.at(1) == START_PREFIX) &&
(m_buffer.at(2) == START_PREFIX) &&
(m_buffer.at(3) == START_PREFIX))
{
QByteArray lenArr = m_buffer.mid(4,4);
const quint32 *inLen = reinterpret_cast<const quint32*>(lenArr.data());
//qDebug() << "Len: " << *inLen;
QByteArray number = m_buffer.remove(0,8);
const double *dNumber = reinterpret_cast<const double*>(number.data());
//double d = *dNumber;
QVector<double> data;
for(int i = 0; i < 1000000; ++i)
{
data.append(*dNumber+i);
}
QByteArray bytes;
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream.setFloatingPointPrecision(QDataStream::DoublePrecision);
stream.setVersion(QDataStream::Qt_5_4);
stream << data;
QByteArray packBegin;
packBegin.append(START_PREFIX);
packBegin.append(START_PREFIX);
packBegin.append(START_PREFIX);
packBegin.append(START_PREFIX);
quint32 dataLen = bytes.length();
packBegin.append(QByteArray(reinterpret_cast<const char*>(&dataLen), sizeof(dataLen)));
m_tcpSocket->write(packBegin);
m_tcpSocket->write(bytes);
}//else if ( m_buffer.at(0) != 0x0A)
//{
//m_buffer.remove(0,1);
//}
}
void TcpThread::ClientDisconnected()
{
m_tcpSocket->close();
emit finished();
}
| true |
2774ab552d5c0b8df47ff340c70e9c3592c7c001
|
C++
|
cerkiewny/exercises
|
/codechef/august2015/transform.cpp
|
UTF-8
| 732 | 3.265625 | 3 |
[] |
no_license
|
#include<vector>
#include<iostream>
using namespace std;
int main(){
int ncases;
cin >> ncases;
for (int i =0 ; i < ncases; i++){
string curs;
cin >> curs;
vector<char> ops;
for(int i = 0; i < curs.size(); i++){
char cur = curs[i];
if(cur == '('){
ops.push_back(cur);
} else if (cur == ')'){
while(ops.back() != '(' && ops.size() > 0){
cout << ops.back();
ops.pop_back();
}
ops.pop_back();
} else if ( cur >= 'a' && cur <= 'z'){
cout << cur;
if(ops.back() != '('){
cout << ops.back();
ops.pop_back();
}
} else {
ops.push_back(cur);
}
}
cout << endl;
}
}
| true |
2d54d3e3e87dd7b7fc21057c452df0e1dfc35e82
|
C++
|
Valtis/Lang
|
/AsmVM/src/MemoryManager.cpp
|
UTF-8
| 2,692 | 3.3125 | 3 |
[] |
no_license
|
#include "MemoryManager.h"
#include <cstdlib>
#include "VM.h"
#define GC_MIN_THRESHOLD 20
MemoryManager::MemoryManager() : m_gcThreshold(20), m_allocatedMemorySizeInBytes(0)
{
}
MemoryManager::~MemoryManager()
{
for (auto &ptr : m_allocatedPointers)
{
free(ptr.ptr);
}
}
VMObject MemoryManager::Allocate(VM *vm, ObjectType t, int cnt)
{
VMObject o;
Ptr managedPtr;
int size;
switch (t)
{
case ObjectType::INTEGER_PTR:
size = sizeof(int);
break;
case ObjectType::CHAR_PTR:
size = sizeof(char);
break;
case ObjectType::DOUBLE_PTR:
size = sizeof(double);
break;
default:
throw std::runtime_error("Internal VM error - attempting to allocate non pointer type");
}
managedPtr.m_marked = false;
managedPtr.size = cnt*size;
m_allocatedMemorySizeInBytes += managedPtr.size;
managedPtr.ptr = malloc(size*cnt);
if (managedPtr.ptr == nullptr)
{
RunGC(vm);
managedPtr.ptr = malloc(size*cnt);
if (managedPtr.ptr == nullptr)
{
throw std::runtime_error("Memory allocation failed - out of memory?");
}
}
o.type = t;
m_allocatedPointers.push_back(managedPtr);
o.values.ptr = &m_allocatedPointers.back();
return o;
}
void MemoryManager::RunGC(VM *vm)
{
//printf("Running garbage collector: Memory allocated now: %d bytes\n", m_allocatedMemory);
MarkRegisters(vm);
MarkStack(vm);
SweepPointers();
//printf("After garbage collection: Memory allocated now: %d bytes\n", m_allocatedMemory);
m_gcThreshold = m_allocatedPointers.size() * 2;
m_gcThreshold = m_gcThreshold < GC_MIN_THRESHOLD ? GC_MIN_THRESHOLD : m_gcThreshold;
//printf("Adjusting collection threshold to %d\n", m_gcThreshold);
}
void MemoryManager::MarkRegisters(VM * vm)
{
for (auto &r : vm->m_registers)
{
if (IsPointer(r))
{
r.values.ptr->m_marked = true;
}
}
}
void MemoryManager::MarkStack(VM * vm)
{
for (int i = 0; i < vm->m_stack_ptr; ++i)
{
if (IsPointer(vm->m_stack[i]))
{
vm->m_stack[i].values.ptr->m_marked = true;
}
}
}
void MemoryManager::SweepPointers()
{
auto it = m_allocatedPointers.begin();
while (it != m_allocatedPointers.end())
{
if (!it->m_marked)
{
m_allocatedMemorySizeInBytes -= it->size;
free(it->ptr);
it = m_allocatedPointers.erase(it);
continue;
}
else
{
it->m_marked = false;
}
it++;
}
}
void MemoryManager::DebugHeapPrint()
{
printf("Current allocated memory in bytes: %d\ncurrent allocated object count:%d\nCurrent gc threshold: %d\n",
m_allocatedMemorySizeInBytes, m_allocatedPointers.size(), m_gcThreshold);
}
bool IsPointer(const VMObject &o)
{
return o.type == ObjectType::CHAR_PTR || o.type == ObjectType::DOUBLE_PTR || o.type == ObjectType::INTEGER_PTR;
}
| true |
3ab2530f658e197b8ecf2f2435d504aaf90ac5bf
|
C++
|
goodcheney/Arduino-Profile-Examples
|
/libraries/Dragino/examples/IoTServer/Emoncms/emoncms_download/emoncms_download.ino
|
UTF-8
| 3,148 | 2.765625 | 3 |
[] |
no_license
|
/*
Downlink Example for Emoncms Server
Arduino Requirements:
* Dragino LG01
* Arduino 1.5.4 IDE or newer
Network Requirements:
* Router with Wi-Fi
* DHCP enabled on Router
Created: December 20, 2016 by Dragino (http://wiki.dragino.com)
by Dragino Technology(hhtp://www.dragino.com)
*/
#include <Bridge.h>
#include <Console.h>
#include <Process.h>
//If you use Dragino IoT Mesh Firmware, uncomment below lines.
//For product: LG01.
#define BAUDRATE 115200
char data[3] = "1";
char Dat[1] = {0} ;
// Emoncms Settings
char feedID[] = "148847"; //Emoncms feed ID
// Other Settings
const unsigned long GETFrequency = 30000UL; // GET frequency in milliseconds (20000 = 20 seconds). Change this to change your GET frequency.
char response[3] = {0}; //Initialize buffer to nulls;
unsigned long lastGETTime = 0; //Don't change. Used to determine if need to GET
void setup()
{
Bridge.begin(BAUDRATE);
// Open Serial monitor and start here.
Console.begin();
while(!Console);
//Wait for the connection to finish stopping
delay(2500);
// initialize digital pin as an output.
pinMode(A2, OUTPUT);
digitalWrite(A2, HIGH); // turn the A2 on (HIGH is the voltage level)
}
void GETCompStreamsLastSamples()
{
Console.println("GET Components Streams Last Samples ...");
//Assemble the url that is used to get streams from gs
lastGETTime = millis();
//You may need to increase the size of urlBuf if any other char array sizes have increased
char urlBuf[180];
sprintf(urlBuf, "https://www.emoncms.org/feed/value.json?id=%s",feedID);
Process process;
process.begin("curl");
process.addParameter("-k");
// process.addParameter("-X");
//process.addParameter("GET");
//Headers
// process.addParameter("-H");
// process.addParameter(xHeadBuf);
// process.addParameter("-H");
//process.addParameter("Connection:close");
// process.addParameter("-H");
//process.addParameter("Content-Type:application/json");
//URL
process.addParameter(urlBuf);
//Make the request
unsigned int result = process.run();
int i = 0;
//Display whatever is returned (usually an error message if one occurred)
while (process.available()>0) {
char c = process.read();
if (i < 3 )
{
response[i++] = c;
}
else if (i == 3)
{
Console.println("response string buffer too small!");
}
//Console.print(c);
}
int a = 0 ;
for( a = 0 ; a < sizeof(response) ; a++)
{
// Console.print( response[a]);
if( response[a] == 48 || response[a] == 49)
{
Dat[0] = response[a]-48 ;
}
}
// Console.flush();
if (Dat[0] == 1)
{
Console.print("turn on led");
digitalWrite(A2, HIGH);
}
else if (Dat[0] == 0)
{
Console.print("turn off led ");
digitalWrite(A2, LOW);
}
//Console.println(Dat[0]);
//Console.println(response[1],DEC);
Console.print("Feed GET Result: ");
Console.println(result);
}
void loop() {
// Update sensor data
if(millis() - lastGETTime > GETFrequency)
{
GETCompStreamsLastSamples();
}
}
| true |
2d0f7155a388c3ec1d6c20417930c166e69d161f
|
C++
|
Salmanius/CS253
|
/Assignments/PA9/Image.h
|
UTF-8
| 746 | 2.796875 | 3 |
[] |
no_license
|
#ifndef IMAGE_INCLUDED
#define IMAGE_INCLUDED
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
using std::stoi;
#include <fstream>
using std::ifstream;
#include <vector>
using std::vector;
#include <math.h>
using std::floor;
class Image
{
public:
Image(string s);
int read();
void histogramPrint(int i);
double normAt(int i) const;
int rawAt(int i) const;
string getFileName() const;
void setClassName();
int getClassName() const;
void singleNormalize();
private:
string fileName;
int className;
vector<int> rawVals;
vector<int> histogram;
vector<float> normalized;
int totalInts;
int x;
int y;
};
#endif
| true |
11e91a7fe288da38803542e4b541936188ca5ff3
|
C++
|
seansio1995/MISC
|
/prioority_queue.cpp
|
UTF-8
| 262 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
#include <queue>
using namespace std;
int main(){
priority_queue<int> myque;
mypq.push(30);
mypq.push(100);
mypq.push(25);
mypq.push(40);
while(!myque.top()){
cout<<myque.top()<<endl;
myque.pop();
}
return 0;
}
| true |
e2bd9bc63899026f0cc518aee224ca6760bfc806
|
C++
|
B0TJerry/Projects
|
/c++/tests/test.cpp
|
UTF-8
| 947 | 2.71875 | 3 |
[] |
no_license
|
#include "test.hpp"
int main() {
long double a,b;
char mode;
char op;
long double ans;
cin >> mode;
while(cin >> a >> op >> b) {
switch(op) {
case '+':
ans = add(a,b);
cout << a << " + " << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
case '-':
ans = sub(a,b);
cout << a << " - " << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
case '*':
ans = mlt(a,b);
cout << a << " * " << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
case '/':
ans = div(a,b);
cout << a << " / " << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
case '^':
ans = pwr(a,b);
cout << a << " ^ " << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
case 'r':
ans = sqr(b);
cout << "√" << b << " = " << ans << '\n';
hist(a,op,b,ans);
break;
default:
cout << INVFNC;
a = 0;
b = 0;
op = ' ';
break;
}
}
}
| true |
38bf3e7f5a4b0618a769cff31355462043b627bd
|
C++
|
matinjun/mtjrandom
|
/main.cpp
|
UTF-8
| 268 | 2.75 | 3 |
[] |
no_license
|
#include "random_method.hpp"
#include <iostream>
using namespace std;
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
mtjrandom::randmize_array(a, 10);
for (int i = 0; i < 10; i++) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
return 0;
}
| true |
054f04dd94c83751ccf7d8275ba29ed6dd012f30
|
C++
|
Didgy74/DEngine
|
/any/include/DEngine/Gui/Grid.hpp
|
UTF-8
| 1,946 | 2.671875 | 3 |
[] |
no_license
|
#pragma once
#include <DEngine/Gui/Widget.hpp>
#include <DEngine/Std/Containers/Box.hpp>
#include <vector>
namespace DEngine::Gui
{
class Grid : public Widget
{
public:
u32 spacing = 10;
void SetDimensions(int width, int height);
void SetWidth(int newWidth);
[[nodiscard]] int GetWidth() const noexcept;
void SetHeight(int newHeight);
[[nodiscard]] int GetHeight() const noexcept;
int PushBackColumn();
int PushBackRow();
void SetChild(int x, int y, Std::Box<Widget>&& in);
Widget* GetChild(int x, int y);
Widget const* GetChild(int x, int y) const;
virtual SizeHint GetSizeHint2(
GetSizeHint2_Params const& params) const override;
virtual void BuildChildRects(
BuildChildRects_Params const& params,
Rect const& widgetRect,
Rect const& visibleRect) const override;
virtual void Render2(
Render_Params const& params,
Rect const& widgetRect,
Rect const& visibleRect) const override;
virtual bool CursorMove(
CursorMoveParams const& params,
Rect const& widgetRect,
Rect const& visibleRect,
bool occluded) override;
virtual bool CursorPress2(
CursorPressParams const& params,
Rect const& widgetRect,
Rect const& visibleRect,
bool consumed) override;
virtual bool TouchMove2(
TouchMoveParams const& params,
Rect const& widgetRect,
Rect const& visibleRect,
bool occluded) override;
virtual bool TouchPress2(
TouchPressParams const& params,
Rect const& widgetRect,
Rect const& visibleRect,
bool consumed) override;
virtual void TextInput(
Context& ctx,
AllocRef const& transientAlloc,
TextInputEvent const& event) override;
virtual void EndTextInputSession(
Context& ctx,
AllocRef const& transientAlloc,
EndTextInputSessionEvent const& event) override;
protected:
// Elements are stored row-major.
std::vector<Std::Box<Widget>> children;
int width = 0;
int height = 0;
struct Impl;
friend Impl;
};
}
| true |
d7ca9f9e922170e9b2da093b4344845edc0c2b73
|
C++
|
Aayushshah196/DataStructure-Algorithms
|
/spanningtree/Edge.h
|
UTF-8
| 428 | 2.765625 | 3 |
[] |
no_license
|
#pragma once
#include "Node.h"
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
class Edge
{
private:
Node* node1;
Node* node2;
sf::RectangleShape rect;
float weight;
public:
Edge();
Edge(Node* node1, Node* node2);
void draw(sf::RenderWindow& window);
void setNodes(Node* node1, Node* node2);
float getWeight();
void setColor(int type = -1);
void setWeight(float x);
Node* getNode1();
Node* getNode2();
};
| true |
80ee69d4c6f3b65c23f98bbe097f96fd9fb172f0
|
C++
|
HarshitGuptaa/DS-Algo
|
/lecture_001/loops/odd_even.cpp
|
UTF-8
| 313 | 2.984375 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main(int args, char **argv){
cout<<"Even :";
for(int i=1;i<=10;i++){
if(i%2==0){
cout<<" "<<i;
}
}
cout<<"\nOdd :";
for(int i=1;i<=10;i++){
if(i%2!=0) {
cout<<" "<<i;
}
}
}
| true |
42a07711d37162ac5a46c5f1ca8863b5d495f6f1
|
C++
|
ercecan/BLG335E
|
/project4/submit.cpp
|
UTF-8
| 11,812 | 3.375 | 3 |
[] |
no_license
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct Keys
{
int x;
int y;
char z;
Keys(){};
Keys(int x_, int y_, char z_)
{
x = x_;
y = y_;
z = z_;
}
void printKeys() { printf("(%d,%d,%c)", x, y, z); }
};
struct node
{
/*int *x; //array of xs
int *y; //array of ys
char *z; //array of zs*/
char key; //holds the key type either 'x', 'y' or 'z'
Keys *keys; // array of x,y,z
int t; //degree
node **children; //array of child pointers
bool leaf; //if it is a leaf set it to true
int n; //current number of keys
int findKeynode(Keys &keynode, char key) //returns the index of the key
{
int i = 0;
if (key == 'x')
while (i < n && keys[i].x < keynode.x)
++i;
if (key == 'y')
while (i < n && keys[i].y < keynode.y)
++i;
if (key == 'z')
while (i < n && keys[i].z < keynode.z)
++i;
return i;
}
void deleteOp(Keys &keynode, char key)
{
int i = findKeynode(keynode, key);
if (i < n and (keys[i].x == keynode.x) and (keys[i].y == keynode.y) and (keys[i].z == keynode.z))
{
if (!leaf)
rmvFromNonL(i);
else
{
for (int j = i + 1; j < n; ++j)
keys[j - 1] = keys[j];
n--;
}
}
else
{
if (leaf)
{
cout << "the key (" << keynode.x << ", " << keynode.y << ", " << keynode.z << ") does not exist" << endl;
return;
}
int k = 0; // flag checking if the key to be removed is at the last child or not
if (i != n)
k = 0;
else
k = 1;
if (children[i]->n < t)
{
fill(i);
}
if (k and i > n)
{
children[i - 1]->deleteOp(keynode, key);
}
else
{
children[i]->deleteOp(keynode, key);
}
}
return;
}
void rmvFromNonL(int i)
{
Keys key = keys[i];
if (this->children[i]->n >= t)
{
node *tmp = children[i];
while (!tmp->leaf)
tmp = tmp->children[tmp->n];
Keys pred = tmp->keys[tmp->n - 1];
keys[i] = pred;
children[i]->deleteOp(pred, this->key);
}
else if (children[i + 1]->n >= t)
{
node *tmp = children[i + 1];
while (!tmp->leaf)
tmp = tmp->children[0];
Keys succ = tmp->keys[0];
keys[i] = succ;
children[i + 1]->deleteOp(succ, this->key);
}
else
{
merge(i);
children[i]->deleteOp(key, this->key);
}
}
void fill(int i)
{
if (i != n and children[i + 1]->n >= t)
takeNext(i);
else if (i and (children[i - 1]->n >= t))
takePrev(i);
else
{
if (i == n)
{
merge(i - 1);
}
else
{
merge(i);
}
}
}
void takePrev(int i)
{
node *s = children[i - 1]; //sibling node
node *c = children[i]; //child node
for (int j = c->n; j >= 0; --j)
{
c->keys[j + 1] = c->keys[j];
}
if (!c->leaf)
{
for (int j = c->n; j >= 0; --j)
c->children[j + 1] = c->children[j];
}
c->keys[0] = keys[i - 1];
if (!c->leaf)
{
c->children[0] = s->children[s->n];
}
keys[i - 1] = s->keys[s->n - 1];
c->n += 1;
s->n -= 1;
}
void takeNext(int i)
{
node *s = children[i + 1]; //sibling node
node *c = children[i]; //child node
c->keys[(c->n)] = keys[i];
if (!(c->leaf))
c->children[(c->n) + 1] = s->children[0];
keys[i] = s->keys[0];
for (int j = 1; j < s->n; ++j)
s->keys[j - 1] = s->keys[j];
if (!s->leaf)
{
for (int j = 1; j <= s->n; ++j)
s->children[j - 1] = s->children[j];
}
c->n += 1;
s->n -= 1;
}
void merge(int i)
{
node *s = children[i + 1]; //sibling node
node *c = children[i]; //child node
c->keys[t - 1] = keys[i];
for (int j = 0; j < s->n; ++j)
{
c->keys[t + j] = s->keys[j];
}
if (!c->leaf)
{
for (int j = 0; j <= s->n; ++j)
c->children[j + t] = s->children[j];
}
for (int j = i + 1; j < n; ++j)
{
keys[j - 1] = keys[j];
}
for (int j = i + 2; j <= n; ++j)
{
children[j - 1] = children[j];
}
c->n += s->n + 1;
n--;
delete (s);
return;
}
void print_node()
{
for (int i = 0; i < n; i++)
keys[i].printKeys();
cout << endl;
if (!this->leaf)
for (int i = 0; i < n + 1; i++)
{
children[i]->print_node();
}
}
void childSplit(int x, node *splitNode)
{
node *newnode = new node(splitNode->t, splitNode->leaf, this->key);
newnode->n = t - 1;
for (int i = 0; i < t - 1; i++)
newnode->keys[i] = splitNode->keys[i + t];
if (!splitNode->leaf)
for (int i = 0; i < t - 1; i++) //t-1 or t//////////////////////////
newnode->children[i] = splitNode->children[i + t];
splitNode->n = t - 1;
for (int j = n; j >= x + 1; j--)
children[j + 1] = children[j];
children[x + 1] = newnode;
for (int j = n - 1; j >= x; j--) /////////n-1 or n
keys[j + 1] = keys[j];
keys[x] = splitNode->keys[t - 1];
n++;
}
void insertNotFull(Keys &newnode, char key)
{
int tmp = n - 1;
if (this->leaf)
{
if (key == 'x')
while (tmp >= 0 and keys[tmp].x > newnode.x)
keys[tmp + 1] = keys[tmp], tmp--;
else if (key == 'y')
while (tmp >= 0 and keys[tmp].y > newnode.y)
keys[tmp + 1] = keys[tmp], tmp--;
else if (key == 'z')
while (tmp >= 0 and keys[tmp].z > newnode.z)
keys[tmp + 1] = keys[tmp], tmp--;
keys[tmp + 1] = newnode;
this->n++;
}
else
{
if (key == 'x')
{
while (tmp >= 0 and keys[tmp].x > newnode.x)
tmp--;
}
else if (key == 'y')
{
while (tmp >= 0 and keys[tmp].y > newnode.y)
tmp--;
}
else if (key == 'z')
{
while (tmp >= 0 and keys[tmp].z > newnode.z)
tmp--;
}
if (children[tmp + 1]->n == 2 * t - 1) //if after insertion the node is full, split again
{
childSplit(tmp + 1, children[tmp + 1]);
if (key == 'x')
if (keys[tmp + 1].x < newnode.x)
tmp++;
if (key == 'y')
if (keys[tmp + 1].y < newnode.y)
tmp++;
if (key == 'z')
if (keys[tmp + 1].z < newnode.z)
tmp++;
}
children[tmp + 1]->insertNotFull(newnode, key);
}
}
node() {}
node(int t, bool is_leaf, char key)
{
this->t = t;
this->leaf = is_leaf;
this->key = key;
keys = new Keys[2 * t - 1];
children = new node *[2 * t];
n = 0;
}
Keys searchX(int x) //keys* or just keys
{
int i = 0;
while (i < n and x > keys[i].x)
i++;
if (keys[i].x == x)
return this->keys[i];
if (leaf)
return this->keys[i]; //bugggg fixx normalde NULL returnlemesi lazim
// Go to the appropriate child
return children[i]->searchX(x);
}
Keys searchY(int y) //keys* or just keys
{
int i = 0;
while (i < n and y > keys[i].y)
i++;
if (keys[i].y == y)
return this->keys[i];
if (leaf)
return this->keys[i]; //buggggggg
return children[i]->searchY(y);
}
Keys searchZ(char z) //keys* or just keys
{
int i = 0;
while (i < n and z > keys[i].z)
i++;
if (keys[i].z == z)
return this->keys[i];
if (leaf)
return this->keys[i]; //buggggggg
return children[i]->searchZ(z);
}
};
class BTree
{
public:
void insert(Keys &keynode);
void del(Keys &keynode);
node *root;
int t;
char key;
BTree(int degree, char key);
void printTree();
};
void BTree::del(Keys &keynode)
{
if (!root)
{
cout << "tree is empty!" << endl;
return;
}
root->deleteOp(keynode, this->key);
if (root->n == 0)
{
node *tmp = root;
if (root->leaf)
{
root = NULL;
}
else
{
root = root->children[0];
}
delete tmp;
}
return;
}
void BTree::printTree()
{
if (root != NULL)
{
root->print_node();
}
}
BTree::BTree(int degree, char key)
{
this->root = NULL;
this->t = degree;
this->key = key;
}
void BTree::insert(Keys &keynode)
{
if (root == NULL)
{
root = new node(t, true, key);
root->keys[0] = keynode;
root->n = 1;
}
else
{
if (root->n == 2 * t - 1)
{
node *newnode = new node(t, false, key);
newnode->children[0] = root;
newnode->childSplit(0, root);
int i = 0;
if (this->key == 'x')
{
if (newnode->keys[i].x < keynode.x)
i++;
}
else if (this->key == 'y')
{
if (newnode->keys[i].y < keynode.y)
i++;
}
else
{
if (newnode->keys[i].z < keynode.z)
i++;
}
newnode->children[i]->insertNotFull(keynode, this->key);
root = newnode;
}
else //if the number of keys is lower than 2*t-1
{
root->insertNotFull(keynode, this->key);
}
}
}
int main()
{
int n, degree;
char key;
cin >> n >> degree >> key;
int x, y;
char z;
Keys *newnode;
BTree btree(degree, key);
for (int i = 0; i < n; i++)
{
cin >> x >> y >> z;
newnode = new Keys(x, y, z);
btree.insert(*newnode);
}
if (key == 'x')
{
int x1 = 0;
cin >> x1;
Keys newkey;
newkey = btree.root->searchX(x1);
btree.del(newkey);
}
else if (key == 'y')
{
int y1 = 0;
cin >> y1;
Keys newkey;
newkey = btree.root->searchY(y1);
btree.del(newkey);
}
else
{
char z1 = 0;
cin >> z1;
Keys newkey;
newkey = btree.root->searchZ(z1);
btree.del(newkey);
}
btree.printTree();
return 0;
}
| true |
c791da5a69b3096cec56af3c088968bb8b647667
|
C++
|
DreamBlack/pat
|
/first/Median.cpp
|
GB18030
| 1,092 | 3.234375 | 3 |
[] |
no_license
|
#include<stdio.h>
long num1[1000000];
long num2[1000000];
int main(){
/*
Ŀ⣺Укϲм
˼·
1ÿʼö̬滮ķ˵ʵDz̫ᡣʱҪԾͨ˫ָķ
2˫ָʱһ鴦µһԵ
3һҪעǣ1000000Ϊȫֱᱨ
*/
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%ld",&(num1[i]));
}
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%ld",&(num2[i]));
}
int i=0,j=0,cnt=0;
int target=(m+n-1)/2;
int temp=0;
while(cnt<=target&&i<n&&j<m){
if(num1[i]<num2[j]){
temp=num1[i++];
}else{
temp=num2[j++];
}
cnt++;
}
if(cnt<=target){
if(i==n){
while(cnt<=target){
temp=num2[j++];
cnt++;
}
}else{
while(cnt<=target){
temp=num1[i++];
cnt++;
}
}
}
printf("%ld",temp);
return 0;
}
| true |
52343ce958170244c926fb027b67fe63d46076ec
|
C++
|
thubk/idps
|
/Masters.cpp
|
UTF-8
| 922 | 2.765625 | 3 |
[] |
no_license
|
#include "Masters.h"
void Masters::updatePriorCounter(double num) {
this->prior_counter = num;
}
void Masters::setV(double v) {
this->v = v;
}
void Masters::setVDelta(double v_delta){
this->v_delta = v_delta;
}
void Masters::setVBackup(double v_backup) {
this->v_backup = v_backup;
}
void Masters::setExV(double ex_v){
this->ex_v = ex_v;
}
void Masters::setExVDelta(double ex_v_delta){
this->ex_v_delta = ex_v_delta;
}
void Masters::setOwner(double key){
owner = key;
}
void Masters::setFlag(bool flag) {
this->flag = flag;
}
double Masters::getOwner() {
return owner;
}
double Masters::getV() {
return v;
}
double Masters::getVDelta(){
return v_delta;
}
double Masters::getVBackup(){
return v_backup;
}
double Masters::getExV(){
return ex_v;
}
double Masters::getExVDelta(){
return ex_v_delta;
}
bool Masters::getFlag(){
return flag;
}
double Masters::getPriorCounter() {
return this->prior_counter;
}
| true |
7139a180e330d3859a0db39351ac183e84b61f32
|
C++
|
devonrball/Assignment4
|
/DLinkedList.h
|
UTF-8
| 4,132 | 3.859375 | 4 |
[] |
no_license
|
#include <string>
#include "Node.h"
using namespace std;
template <typename T>
class DLinkedList
{
private:
Node<T> *front;
Node<T> *back;
unsigned int size;
public:
DLinkedList();
//DlinkedList(Node<T> *someNode);
DLinkedList(T data);
~DLinkedList();
void insertFront(T data);
void insertBack(T data);
Node<T>* removeFront();
Node<T>* removeBack();
Node<T>* peekFront();
Node<T>* peekBack();
bool isEmpty();
int getSize();
//void printList();
//Node<T>* find(int val);
//unsigned int getSize();
//int deletePosition(int pos);
//Node<T>* remove(int key); //returns entire node
//read book as to why this would occur
void clear();
};
template <typename T>
DLinkedList<T>::DLinkedList()
{
/*this->size = 0;
this->front = NULL;
this->back = NULL;*/
front = NULL;
back = NULL;
size = 0;
}
/*template <typename T>
DLinkedList<T>::DLinkedList(Node<T>* someNode)
{
this->size = 1;
this->front = someNode;
this->back = someNode;
//this->next = back; // these might be weird
//this->prev = front; //
}*/
template <typename T>
DLinkedList<T>::DLinkedList(T data) // probably okay
{
Node<T> *newNode = new Node<T>(data);
size = 1;
front = newNode;
back = newNode;
}
template <typename T>
DLinkedList<T>::~DLinkedList() //DOesn't something need to be virtual?
{
/*while(!Empty()){
T* temp;
temp = front;
front = front->next;
delete temp;
}
back = NULL;
size = 0;*/ //doesn't depend on clear()
clear();
//front = NULL;
back = NULL;
}
template <typename T>
void DLinkedList<T>::insertFront(T data) //probably okay
{
Node<T> *newNode = new Node<T>(data);
if(isEmpty()) // front==NULL || size==0
{
back = newNode;
}
else{
front->prev = newNode;
newNode->next = front;
}
front = newNode;
++size;
return;
}
template <typename T>
void DLinkedList<T>::insertBack(T data)
{
Node<T> newNode = new Node<T>(data);
if(isEmpty()) // front==NULL || size==0
{
front = newNode;
}
else{
back->next = newNode;
newNode->prev = back;
}
back = newNode;
++size;
return;
}
template <typename T>
Node<T>* DLinkedList<T>::removeFront() // no clude if this is okay
{
//check if empty
if(isEmpty())
{
cout << "Can't remove elements from an empty list!\n";
exit(EXIT_FAILURE);
//if made bool, could return false
}
Node<T> *temp = this->front;
if(front->next == NULL){
this->back = NULL;
}
else{
front->next->prev = NULL;
}
this->front = this->front->next; //might need to switch sides of =
temp->next = NULL;
--size;
return temp;
}
template <typename T>
Node<T>* DLinkedList<T>::removeBack()
{
if(isEmpty())
{
cout << "Can't remove elements from an empty list!\n";
exit(EXIT_FAILURE);
}
T* temp = this->back;
if(back->prev == NULL){
this->front == NULL;
}
else{
back->prev->next = NULL;
}
this->back = this->back->prev;
temp->prev = NULL;
--size;
return temp;
}
template <typename T>
Node<T>* DLinkedList<T>::peekFront()
{
return this->front;
}
template <typename T>
Node<T>* DLinkedList<T>::peekBack()
{
return this->back;
}
template <typename T>
bool DLinkedList<T>::isEmpty()
{
return (size == 0);
}
/*template <typename T>
void DLinkedList<T>::printList()
{}
template <typename T>
T* DLinkedList<T>::find(int val)
{}
template <typename T>
unsigned in DLinkedList<T>::getSize()
{}
template <typename T>
int DLinkedList<T>::deletePosition(int pos)
{}*/
//template <typename T>
//T* DLinkedList<T>::(int key){}
template <typename T>
int DLinkedList<T>::getSize()
{
return this->size;
}
template <typename T>
void DLinkedList<T>::clear()
{
while(!isEmpty()){
Node<T> *temp = new Node<T>();
temp = front;
front = front->next;
delete temp;
--size;
}
back = NULL;
size = 0;
}
| true |
44a12a105987fd0cd28afd4b4a639b5a66093be2
|
C++
|
wbrbr/raytracer
|
/src/triangle.cpp
|
UTF-8
| 1,681 | 3.015625 | 3 |
[] |
no_license
|
#include "shape.hpp"
#include "mesh.hpp"
std::optional<float> Triangle::intersects(Ray ray) const
{
glm::vec3 v0 = vertex(0).position;
glm::vec3 v1 = vertex(1).position;
glm::vec3 v2 = vertex(2).position;
float a,f,u,v;
glm::vec3 edge1 = v1 - v0;
glm::vec3 edge2 = v2 - v0;
glm::vec3 h = glm::cross(ray.orientation, edge2);
a = glm::dot(edge1, h);
if (a == 0.f) { // use epsilon
return {};
}
f = 1.f / a;
glm::vec3 s = ray.origin - v0;
u = f * glm::dot(s, h);
if (u < 0.f || u > 1.f) {
return {};
}
glm::vec3 q = glm::cross(s, edge1);
v = f * glm::dot(ray.orientation, q);
if (v < 0.f || u + v > 1.f) {
return {};
}
// there is an intersection
float t = f * glm::dot(edge2, q);
if (t <= 0.f) {
return {};
}
return t;
}
glm::vec3 Triangle::normal(glm::vec3 point) const
{
glm::vec3 edge01 = vertex(1).position - vertex(0).position;
glm::vec3 edge02 = vertex(2).position - vertex(0).position;
return glm::normalize(glm::cross(edge01, edge02));
}
Box Triangle::boundingBox() const
{
glm::vec3 minPoint = vertex(0).position;
glm::vec3 maxPoint = vertex(0).position;
for (unsigned int i = 1; i < 3; i++)
{
minPoint = minp(minPoint, vertex(i).position);
maxPoint = maxp(maxPoint, vertex(i).position);
}
Box box;
box.minPoint = minPoint;
box.maxPoint = maxPoint;
return box;
}
glm::vec3 Triangle::centroid() const
{
return (vertex(0).position + vertex(1).position + vertex(2).position) / 3.f;
}
Vertex Triangle::vertex(unsigned int n) const
{
return mesh->vertices[indices[n]];
}
| true |
c6e8442293dcad4d8227a3d4fced8f508b1dc84f
|
C++
|
mojoe12/UVa
|
/synchingsignals.cpp
|
UTF-8
| 882 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[]) {
string s;
getline(cin, s);
for (int c = 1; s != ""; c++) {
int size = (s.length() + 1) / 3;
vector<int> cycles (size);
for (int i = 0; i < size; i++) {
cycles[i] = 10 * (s[3*i] - '0') + s[3*i+1] - '0';
}
int time = *min_element(cycles.begin(), cycles.end()) - 5;
for (; time <= 3600; time++) {
bool ifgreen = true;
for (int i = 0; ifgreen && i < size; i++) {
int x = time % (2 * cycles[i]);
ifgreen = ifgreen && x < cycles[i] - 5;
}
if (ifgreen) break;
}
if (time > 3600) cout << "Set " << c << " is unable to synch after one hour.\n";
else {
cout << "Set " << c << " synchs again at " << time / 60;
cout << " minute(s) and " << time % 60 << " second(s) after all turning green.\n";
}
getline(cin, s);
}
}
| true |
97c7baf1346c7d3598914e6d82e65d6a7690e662
|
C++
|
CESARIUX2596/Computer-Vision-Extended
|
/Tests/OpenCVTest/Source.cpp
|
UTF-8
| 1,844 | 3.125 | 3 |
[] |
no_license
|
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
//Show Image
Mat img = imread("lena.jpg");
if (img.empty())
{
cout << "Could not open or find the image" << endl;
cin.get(); //wait for any key press
return -1;
}
namedWindow("image", WINDOW_NORMAL);
imshow("image", img);
waitKey(0);
destroyWindow("image");
//Create frame with color;
Mat image(600, 800, CV_8UC3, Scalar(100, 250, 30));
String windowName = "Window with Blank Image";
namedWindow(windowName);
imshow(windowName, image);
waitKey(0);
destroyWindow(windowName);
//Play Video
//cap(0) passes as parameter the integrated webcam of a computer in this case my laptop!
VideoCapture cap(0);
if (cap.isOpened() == false)
{
cout << "Cannot open the video file" << endl;
cin.get(); //wait for any key press
return -1;
}
double dWidth = cap.get(CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
double dHeight = cap.get(CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
cout << "Resolution of the video : " << dWidth << " x " << dHeight << endl;
double fps = cap.get(CAP_PROP_FPS);
cout << "Frames per second " << fps << endl;
String window_name = "Video";
namedWindow(window_name, WINDOW_NORMAL);
while (true)
{
Mat frame;
bool bSucces = cap.read(frame);
if (bSucces == false)
{
cout << "Video camera is disconnected" << endl;
cin.get();
break;
}
imshow(window_name, frame);
/*
* wait for1- ms until key is pressed
* If Esc is pressed breaks the while loop
* If the any other key is pressed, continue the loop
* If any key is not pressed withing 10 ms, continue the loop
*/
if (waitKey(10) == 27)
{
cout << "Esc key is pressed by user. Stoppig the video" << endl;
break;
}
}
return 0;
}
| true |
0014cade09e955527877e758b88feb67a2cb5dbf
|
C++
|
obryanlouis/cs_143_group_project
|
/Routing/RoutingTable.h
|
UTF-8
| 1,299 | 2.984375 | 3 |
[] |
no_license
|
// RoutingTable.h
#ifndef ROUTING_TABLE_H
#define ROUTING_TABLE_H
#include "Link.h"
#include <map>
#include <cstddef>
#include <utility>
class Link;
class Node;
class RoutingTable
{
private:
std::map<Node*, std::pair<double, Link*> > mapping;
// The map containing the routing table information. Maps from
// a destination node to a pair, containing the distance to this
// node as well as the next link to follow
public:
friend void outputRoutingTables(void *args);
friend class Router;
RoutingTable();
// Create an empty RoutingTable
RoutingTable(RoutingTable *old);
// Copy an object of class RoutingTable
~RoutingTable();
// Delete this instance of RoutingTable
std::pair<double, Link*> & operator[] (Node *r) { return mapping[r]; }
// operator[] to access elements of the routing table
Link* nextLink(Node *r);
// Returns the next link a packet should follow based on its
// destination node
Node* nextNode(Node *r);
// Returns the next node a packet should go to based on its
// destination node
bool containsEntry(Node *node);
// Determines whether or not the routing table has an entry
// for this node.
// DEBUG
void print();
};
#endif
| true |
f852e973200d0a936936f44ff97c8e7caa7dad11
|
C++
|
neharathig/All_Cpp
|
/82FibbonicciRecursive.cpp
|
UTF-8
| 227 | 3.140625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int Fibb(int n)
{
if (n==0 || n==1)
{
return n;
}
return Fibb(n-1)+Fibb(n-2);
}
int main()
{
int n;
cin>>n;
cout<<Fibb(n)<<endl;
return 0;
}
| true |
0d0b46ca90c272d0cffa6692ec79e4a74efb7e7b
|
C++
|
sandral/numeeriset_menetelmat
|
/ratkaisut1/h1t4.cpp
|
UTF-8
| 692 | 3.21875 | 3 |
[] |
no_license
|
//Tehtävä4
#include <iostream>
#include <math.h>
using namespace std;
double coeff(double x[], double y[], int n)
{
double a;
double b;
double t1;
double t2;
double t3;
double t5;
for (int i=0; i<n; i++)
{
t1 += x[i]*y[i];
t2 += x[i];
t3 += y[i];
}
double t4 = t2/n;
for (int i=0; i<n; i++)
{
t5 += pow((x[i]-t4),2);
}
a = (t1 - (t2*t3)/n)/t5;
b = (t3 - a*t2)/n;
std::cout<< "a: "<< a << " b: "<< b;
return 0;
}
int main()
{
double time[] = {0, 1, 2, 3, 4, 5};
double value[] = {0.8969, 0.9005, 0.8961, 0.8919, 0.8793, 0.8818};
coeff(time, value, 6);
return 0;
}
| true |
80f4f4e40f7dd5dae8fa4f62c5e9275f5b34c880
|
C++
|
simonusher/genetic-programming-challenge
|
/Win32Project1/Node.h
|
UTF-8
| 1,378 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
#include <string>
#include <cstdlib>
#include <vector>
#include <cmath>
#include "constants.h"
const enum NodeType {
OperationSum,
OperationSub,
OperationMult,
OperationDiv,
OperationSin,
OperationCos,
Constant,
Variable
};
const int NUMBER_OF_OPERATIONS = 6;
const int NUMBER_OF_TYPES = 8;
const std::string OPERATION_SUM = "+";
const std::string OPERATION_SUB = "-";
const std::string OPERATION_MULT = "*";
const std::string OPERATION_DIV = "/";
const std::string OPERATION_SIN = "sin";
const std::string OPERATION_COS = "cos";
const int STOPPING_PROBABILITY = 60;
const int DISTRIB_OPERATION = 40;
const int DISTRIB_CONSTANT = 70;
const int DISTRIB_VARIABLE = MAX_PROBABILITY;
const std::vector<std::string> VAR_NAMES = { "x", "y" };
class Node {
public:
friend class Tree;
friend class CPGAlg;
Node();
Node(Node &otherNode);
~Node();
static Node* randomizeNode();
std::string getONPFormula();
void cutDown(int currentDepth, int depth);
double computeValue(double &xValue, double &yValue, bool &evaluationSuccess);
private:
Node** getRandomNodeFromTree(Node **lastPtr);
void changeStructure(Node **pointerToChange);
static int randomType();
static int randomOperation();
static int randomConstant();
static std::string randomVariable();
int nodeType;
std::vector<Node*> children;
std::string variableName;
int constantValue;
};
| true |
c1c63b96531ecfef6fb3f2c62f3b71d21ae3ed53
|
C++
|
LeeGyeongHwan/Algorithm_Student
|
/acm_9286.cpp
|
UTF-8
| 593 | 2.6875 | 3 |
[] |
no_license
|
/*
ACMICPC
문제 번호 : 9286
문제 제목 : Gradabase
풀이 날짜 : 2020-07-27
Solved By Reamer
*/
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int testCase, student, tmp;
cin >> testCase;
for (int i = 0; i < testCase; i++)
{
cin >> student;
cout << "Case " << i + 1 << ":\n";
for (int j = 0; j < student; j++)
{
cin >> tmp;
if (tmp + 1 <= 6)
cout << tmp + 1 << "\n";
}
}
return 0;
}
| true |
b9cc0ab203596f391b45bdfa646c833da0a9b559
|
C++
|
Singhm35/INFO450GUESS
|
/Guess Project/guess.cpp
|
UTF-8
| 2,681 | 3.40625 | 3 |
[] |
no_license
|
#include <iostream>
#include <time.h>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
{
cout << " ***************************************\n";
cout << " ** Find MORE Gold! **\n";
cout << " ** **\n";
cout << " ** You have 5 guesses **\n";
cout << " ** 5 pieces of gold **\n";
cout << " ** and 1 bomb **\n";
cout << " ** **\n";
cout << " ** Good Luck **\n";
cout << " ***************************************\n\n";
cout << "Do you want to play? (Y)";
//string toPlay;
//cin >> toPlay;
string play;
cin >> play;
bool toPlay;
if (play == "Y") {
toPlay = true;
}
else {
exit(EXIT_FAILURE);
}
while (toPlay == true);
{
int response1;
int response2;
int count = 4;
bool redo = true;
int arr[8][8];
int re1 = rand() * int(10);
cout << (re1);
int re2 = rand() * int(10);
int re3 = rand() * int(10);
int re4 = rand() * int(10);
int re5 = rand() * int(10);
int re6 = rand() * int(10);
int re7 = rand() * int(10);
int re8 = rand() * int(10);
int re9 = rand() * int(10);
int re10 = rand() * int(10);
int bombx = rand() * int(10);
int bomby = rand() * int(10);
while (count >= 0)
{
cout << "Enter X Coordinate";
cin >> response1;
cout << ("Enter Y Coordinate");
cin >> response2;
cout << ("You have " + count);
count--;
if (response1 == re1 && response2 == re2)
{
arr[re1][re2] = 1;
cout << ("GOLD!");
redo = true;
}
else if (response1 == re3 && response2 == re4) {
arr[re3][re4] = 1;
cout << ("GOLD");
redo = true;
}
else if (response1 == re5 && response2 == re6) {
arr[re5][re6] = 2;
cout << ("GOLD");
redo = true;
}
else if (response1 == re7 && response2 == re8) {
arr[re7][re8] = 2;
cout << ("GOLD");
redo = true;
}
else if (response1 == re9 && response2 == re10) {
arr[re9][re10] = 2;
cout << ("GOLD");
redo = true;
}
else if (response1 == bombx && response2 == bomby) {
arr[bombx][bomby] = 2;
cout << ("BOMB. You Died");
break;
}
}
for (int i = 0; i < sizeof(arr); i++) {
for (int j = 0; j < sizeof(arr); j++) {
cout << (arr[i][j] + " ");
}
cout << ("");
}
cout << (re1 + " " + re2);
cout << (re3 + " " + re4);
cout << (re5 + " " + re6);
cout << (re7 + " " + re8);
cout << (re9 + " " + re10);
}
}
cout << "Do you want to play? (Y)";
string toPlay;
cin >> toPlay;
}
| true |
fb8e996e3dfb447a6997a742798cbbda26cac2e7
|
C++
|
Abrantedr/Practicas-Informatica-Industrial-4-GIEIA
|
/Practica 2/clienteTCP_noError.cpp
|
UTF-8
| 1,285 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
//Ejemplo cliente eco UDP. Sin control de errores.
//Autor: Alberto Hamilton Castro
// 2019-10-23
#include <iostream> // std::cout, std::endl
#include <arpa/inet.h> // htons(), htonl(), etc.
#include <sys/socket.h> // socket(), bind(), etc.
#include <unistd.h> // close()
#define SERVER "127.0.0.1"
#define BUFLEN 256 // Longitud del buffer
#define PORT 8888 // Puerto al que enviar datos
// SIN control de errores
int main(void) {
//creamos socket TCP
int sfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in si_otro;
unsigned slen = sizeof(struct sockaddr_in);
si_otro.sin_family = AF_INET;
si_otro.sin_port = htons(PORT);
inet_aton(SERVER , &si_otro.sin_addr);
//Conectamos al servidor
connect(sfd, (struct sockaddr *) &si_otro, slen);
std::cout << "Conexión establecida" << std::endl;
while(1) {
std::string mensaje;
std::cout << "\nIntroduce mensaje : ";
std::getline(std::cin, mensaje);
// enviamos mensaje
send(sfd, mensaje.c_str(), mensaje.size()+1 , 0);
// recibimos respuesta
char buf[BUFLEN];
int recv_len = recv(sfd, buf, BUFLEN, 0);
std::cout << "-> Recibido respuesta de "
<< recv_len << " bytes" << std::endl;
std::cout << "-> Datos: " << buf << std::endl;
}
close(sfd);
return 0;
}
| true |
3fbd4c19386b5f4f5bb4cd7961ef74effc9f5a8d
|
C++
|
sangwe11/ray-tracing-in-one-weekend-cpp
|
/src/main.cpp
|
UTF-8
| 4,643 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <fstream>
#include "common.h"
#include "camera.h"
#include "color.h"
#include "hittable_list.h"
#include "sphere.h"
#include "material.h"
double hit_sphere(const point3& center, double radius, const ray& r)
{
vec3 oc = r.origin() - center;
auto a = r.direction().length_squared();
auto half_b = dot(oc, r.direction());
auto c = oc.length_squared() - (radius * radius);
auto descriminant = (half_b * half_b) - (a * c);
if (descriminant < 0)
{
return -1.0;
}
else
{
return (-half_b - sqrt(descriminant)) / a;
}
}
color ray_color(const ray& r, const hittable_list& scene, const int depth)
{
hit_record rec;
if (depth <= 0)
return color(0, 0, 0);
if (scene.hit(r, 0.001, inf, rec))
{
ray scattered;
color attenuation;
if (rec.material->scatter(r, rec, attenuation, scattered))
return attenuation * ray_color(scattered, scene, depth - 1);
return color(0, 0, 0);
}
vec3 unit_direction = r.direction().unit();
auto t = 0.5 * (unit_direction.y() + 1.0);
return (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0);
}
hittable_list random_scene()
{
hittable_list scene;
std::shared_ptr<lambertian> ground_material = std::make_shared<lambertian>(color(0.5, 0.5, 0.5));
scene.add(std::make_shared<sphere>(point3(0, -1000, 0), 1000, ground_material));
for (int a = -11; a < 11; a++)
{
for (int b = -11; b < 11; b++)
{
double choose_material = random_double();
point3 center(a + 0.9 * random_double(), 0.2, b + 0.9 * random_double());
if((center - point3(4, 0.2, 0)).length() > 0.9)
{
std::shared_ptr<material> sphere_material;
if (choose_material < 0.8)
{
vec3 albedo = color::random() * color::random();
sphere_material = std::make_shared<lambertian>(albedo);
scene.add(std::make_shared<sphere>(center, 0.2, sphere_material));
}
else if (choose_material < 0.95)
{
vec3 albedo = color::random(0.5, 1);
double fuzz = random_double(0, 0.5);
sphere_material = std::make_shared<metal>(albedo, fuzz);
scene.add(std::make_shared<sphere>(center, 0.2, sphere_material));
}
else
{
sphere_material = std::make_shared<dielectric>(1.5);
scene.add(std::make_shared<sphere>(center, 0.2, sphere_material));
}
}
}
}
std::shared_ptr<material> material1 = std::make_shared<dielectric>(1.5);
scene.add(std::make_shared<sphere>(point3(0, 1, 0), 1.0, material1));
std::shared_ptr<material> material2 = std::make_shared<lambertian>(color(0.4, 0.2, 0.1));
scene.add(std::make_shared<sphere>(point3(-4, 1, 0), 1.0, material2));
std::shared_ptr<material> material3 = std::make_shared<metal>(color(0.7, 0.6, 0.5), 0.0);
scene.add(std::make_shared<sphere>(point3(4, 1, 0), 1.0, material3));
return scene;
}
int main()
{
// Output file
std::ofstream output_file;
output_file.open("output.ppm");
// Image
const auto aspect_ratio = 16.0 / 9.0;
const int image_width = 400;
const int image_height = static_cast<int>(image_width / aspect_ratio);
const int samples_per_pixel = 100;
const int max_depth = 50;
// Scene
hittable_list scene = random_scene();
// Camera
double focus_distance = 10;
double aperture = 0.1;
camera cam(point3(13, 2, 3), vec3(-13, -2, -3), vec3(0, 1,0), 20, aspect_ratio, aperture, focus_distance);
// Render
output_file << "P3\n" << image_width << ' ' << image_height << "\n255\n";
for (int j = image_height - 1; j >= 0; --j)
{
std::cout << "\rScanlines remaining: " << j << ' ' << std::flush;
for (int i = 0; i < image_width; ++i)
{
color pixel_color(0, 0, 0);
for (int s = 0; s < samples_per_pixel; ++s)
{
auto u = (i + random_double()) / (double)(image_width - 1);
auto v = (j + random_double()) / (double)(image_height - 1);
ray r = cam.get_ray(u, v);
pixel_color += ray_color(r, scene, max_depth);
}
write_color(output_file, pixel_color, samples_per_pixel);
}
}
output_file.close();
std::cout << "\nDone.\n";
return 0;
}
| true |
e190c8a40b3e1cce7aae2ba44a5b8feb1182f088
|
C++
|
soyaoki/CarND-Kidnapped-Vehicle-Project
|
/src/particle_filter.cpp
|
UTF-8
| 11,163 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
/**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*
* Improved on Mar 17, 2019
* Author: Soya AOKI
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 20; // TODO: Set the number of particles
Particle p;
// generate random
std::default_random_engine generator;
std::normal_distribution<double> dist_x(0.0, std[0]);
std::normal_distribution<double> dist_y(0.0, std[1]);
std::normal_distribution<double> dist_theta(0.0, std[2]);
// initialize with noise
for (int i = 0; i < num_particles; i++){
particles.push_back(p);
particles[i].id = i;
particles[i].x = x + dist_x(generator);
particles[i].y = y + dist_y(generator);
particles[i].theta = theta + dist_theta(generator);
particles[i].weight = 1.0;
weights.push_back(particles[i].weight);
}
std::cout << "Initialized!" << std::endl;
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
// generate random
std::default_random_engine generator;
std::normal_distribution<double> dist_x(0.0, std_pos[0]);
std::normal_distribution<double> dist_y(0.0, std_pos[1]);
std::normal_distribution<double> dist_theta(0.0, std_pos[2]);
for (int i = 0; i < num_particles; i++){
// predict x, y and theta after delta_t
if (fabs(yaw_rate) < 0.00001) {
particles[i].x += velocity * delta_t * cos(particles[i].theta) + dist_x(generator);
particles[i].y += velocity * delta_t * sin(particles[i].theta) + dist_y(generator);
} else {
particles[i].x += (velocity / yaw_rate) * (sin(particles[i].theta + yaw_rate * delta_t) - sin(particles[i].theta)) + dist_x(generator);
particles[i].y += (velocity / yaw_rate) * (-cos(particles[i].theta + yaw_rate * delta_t) + cos(particles[i].theta)) + dist_y(generator);
particles[i].theta += (yaw_rate * delta_t) + dist_theta(generator);
}
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
// each measured x, y (landmarks in global map)
for (int ii = 0; ii < observations.size(); ii++){
double distance_error_min = 100000;
LandmarkObs obs;
// each predicted x, y (landmarks in global map)
for (int jj = 0; jj < predicted.size(); jj++){
// calcurate distance between observed and predicted
double d = dist(observations[ii].x, observations[ii].y, predicted[jj].x, predicted[jj].y);
// if minimum
if (d <= distance_error_min){
// record ID
observations[ii].id = predicted[jj].id;
distance_error_min = d;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
double weight_normalizer = 0.0;
// for each Paticles
for (int i = 0; i < num_particles; i++){
// pick up landmarks in range
vector<LandmarkObs> predicted;
for (int j = 0; j < map_landmarks.landmark_list.size(); j++){
// if landmark is in range
//if (dist(particles[i].x, particles[i].y, map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f) <= sensor_range){
if ( (fabs(particles[i].x - map_landmarks.landmark_list[j].x_f) <= sensor_range ) && ( fabs(particles[i].y - map_landmarks.landmark_list[j].y_f) <= sensor_range ) ){
LandmarkObs pred;
pred.id = map_landmarks.landmark_list[j].id_i;
pred.x = map_landmarks.landmark_list[j].x_f;
pred.y = map_landmarks.landmark_list[j].y_f;
predicted.push_back(pred);
}
}
// transform observed (measured) x, y from vehicle coordinate (map) to global coordinate (map)
vector<LandmarkObs> observed;
for (int k = 0; k < observations.size(); k++){
LandmarkObs obs;
// transform
obs.x = particles[i].x + ( cos(particles[i].theta) * observations[k].x ) - ( sin(particles[i].theta) * observations[k].y );
obs.y = particles[i].y + ( sin(particles[i].theta) * observations[k].x ) + ( cos(particles[i].theta) * observations[k].y );
obs.id = k;
observed.push_back(obs);
}
// find closest landmark for each observed x, y
dataAssociation(predicted, observed);
// show predicted and observed X,Y (Landmark in the global map)
//for (int n = 0; n < predicted.size(); n++){
//std::cout << "predicted : " << predicted[n].x << "," << predicted[n].y << ", " << predicted[n].id << std::endl;
//std::cout << "observed : " << observed[n].x << "," << observed[n].y << ", " << observed[n].id << std::endl;
//}
particles[i].weight = 1.0;
// wight update
// for each observed x, y (they have been transformed to global map)
for (int l = 0; l < observed.size(); l++){
// for each predicted x,y
for (int m = 0; m < predicted.size(); m++){
// use the result of dataAssociation (closest observed and predicted has same id)
if ( predicted[m].id == observed[l].id){
// update weight
particles[i].weight = particles[i].weight * multiv_prob(std_landmark[0], std_landmark[1], observed[l].x, observed[l].y, predicted[m].x, predicted[m].y);
//std::cout << "weight : " << multiv_prob(std_landmark[0], std_landmark[1], observed[l].x, observed[l].y, predicted[m].x, predicted[m].y) << std::endl;
}
}
}
//std::cout << "No." << i << " final weight : " << particles[i].weight << std::endl;
weight_normalizer += particles[i].weight;
}
//std::cout << "weight normalizer : " << weight_normalizer << std::endl;
// contain weights
for (int i = 0; i < particles.size(); i++) {
//particles[i].weight = particles[i].weight / weight_normalizer;
weights[i] = particles[i].weight;
}
}
double ParticleFilter::multiv_prob(double sig_x, double sig_y, double x_obs, double y_obs, double mu_x, double mu_y) {
// calculate normalization term
double gauss_norm;
gauss_norm = 1 / (2 * M_PI * sig_x * sig_y);
// calculate exponent
double exponent;
exponent = (pow(x_obs - mu_x, 2) / (2 * pow(sig_x, 2)))
+ (pow(y_obs - mu_y, 2) / (2 * pow(sig_y, 2)));
// calculate weight using normalization terms and exponent
double weight;
weight = gauss_norm * exp(-exponent);
return weight;
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
vector<Particle> new_p;
std::default_random_engine generator;
std::uniform_int_distribution<int> particle_index(0, num_particles - 1);
int index = particle_index(generator);
double beta = 0.0;
double mw = -1.0;
for (int i = 0; i < num_particles; i++){
if (weights[i] > mw){
mw = weights[i];
}
}
for (int j = 0; j < num_particles; j++){
std::uniform_real_distribution<double> random_weight(0.0, 2*mw);
beta += random_weight(generator);
while ( beta > weights[index] ){
beta -= weights[index];
index = (index + 1) % num_particles;
}
new_p.push_back(particles[index]);
}
particles = new_p;
//std::cout << "Resampled! ( N = " << particles.size() << ")" << std::endl;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
| true |
b6fd96f91ea11d3ddc7d8e064ba08050a9fab013
|
C++
|
jeonyeohun/PS-With-CPP
|
/BOJ/P2110_InstallRouter.cpp
|
UTF-8
| 1,026 | 3.171875 | 3 |
[] |
no_license
|
#include <cstdio>
#include <set>
using namespace std;
set<int> houses;
int N, C;
int installRouter(int interval)
{
int count = 1;
int point = *(houses.begin()) + interval;
while (true)
{
auto iter = houses.lower_bound(point);
if (iter != houses.end())
{
count++;
}
else if (iter == houses.end())
break;
point = *iter + interval;
}
return count;
}
int binarySearch()
{
int head = 1;
int tail = *(houses.rbegin());
int answer = 0;
while (head <= tail)
{
int mid = (tail + head) / 2;
int result = installRouter(mid);
if (result >= C)
{
head = mid + 1;
answer = mid;
}
else
tail = mid - 1;
}
return answer;
}
int main()
{
scanf("%d %d", &N, &C);
for (int i = 0; i < N; i++)
{
int house;
scanf("%d", &house);
houses.insert(house);
}
printf("%d", binarySearch());
}
| true |
85894fa89d180a885b1f15bee8af7d3bc8cfed81
|
C++
|
danthinnee/matrix-multi-practice
|
/Sequential/Programs/matrix_timer.cpp
|
UTF-8
| 2,082 | 3.15625 | 3 |
[] |
no_license
|
#include<fstream>
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<sstream>
using namespace std;
const int default_dim = 10000;
int numthreads = 1;
int rows1 = 10000;
int cols1 = 10000;
int rows2 = 10000;
int cols2 = 1;
int matrix1[default_dim][default_dim];
int matrix2[default_dim][1];
int product[default_dim][default_dim];
void populate_matrices(int rows, int cols, int& rows1, int& rows2, int& cols1, int& cols2){
rows1 = rows;
rows2 = rows;
cols1 = cols;
cols2 = 1;
// populate with random values
for(int r=0; r< rows; r++){
for(int c=0; c<cols; c++)
matrix1[r][c] = rand() % 100;
}
for(int r=0; r< rows; r++){
for(int c=0; c<1; c++)
matrix2[r][c] = rand() % 100; }
}
int multiply_time (int iterations){
int x = 0;
// pre time
// will need to be factored out of final time
time_t t = time(0);
// execute multiplication given number of times
//double iterations = 50000;
while(x < iterations){
// multiply matrices together
for(int i=0; i < rows1; i++){
for(int j=0; j < cols2; j++){
for(int k=0; k < cols1; k++){
product[i][j] = product[i][j] + (matrix1[i][k] * matrix2[k][j]);
}
}
}
x++;
}
// post time
// will need to be factored out of final time
time_t t2 = time(0);
cout << t2-t << endl;
return t2-t;
}
string NumberToString ( int Number )
{
stringstream ss;
ss << Number;
return ss.str();
}
int main () {
int iteration_limit = 10000;
int rows=1024, cols=1024;
string filetitle = "SequentialTimes_" + NumberToString(rows) + "x";
populate_matrices(rows, cols, rows1, rows2, cols1, cols2);
ofstream outputFile;
outputFile.open(filetitle.c_str(), ios_base::app);
for(int i=0; i < iteration_limit; i=i+500){
int iterations = i;
int time = multiply_time(iterations);
outputFile << iterations << "," << time << endl;
}
outputFile.close();
}
| true |
4ca946609a92702a1164f2ef29b131e789da5efa
|
C++
|
thaoc/guessinggame
|
/guessgame.cpp
|
UTF-8
| 597 | 3.28125 | 3 |
[] |
no_license
|
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
// nelsoncs02's comment!
int main(){
srand(time(NULL));
int number = rand()%100+1;
int guess;
bool correct = false;
int tries = 0;
cout << "Thinking of a number (1-100). Guess?";
while(!correct){
cin >> guess;
tries++;
if (number == guess){
cout << "You got it in " << tries << " tries." << endl;
correct = true;
} else if (number < guess){
cout << "Your guess is high. try again:" << endl;
} else {
cout << "Your guess is low. try again:" << endl;
}
}
}
| true |
13299b39b7633fc3e54cce109f67867c40d785fb
|
C++
|
kkevn/ACER_Benchmark
|
/benchmarks/saxpy/saxpy_c.cpp
|
UTF-8
| 2,844 | 3.859375 | 4 |
[] |
no_license
|
/* Single-Precision AX+Y in C/C++
*******************************************************************
* Description:
* Populate two vectors each of size N. In the first vector,
* multiply each element by some constant scalar and then sum
* this product with with the elment at same index in other
* vector. This result gets stored in the second vector.
*******************************************************************
* Source:
* https://devblogs.nvidia.com/even-easier-introduction-cuda/
*******************************************************************
*/
#include <ctime>
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
/* saxpy function */
void saxpy(int n, float a, float *x, float *y) {
// iterate through all N elements
for (int i = 0; i < n; i++)
// do AX+Y
y[i] = a * x[i] + y[i];
}
/* program's main() */
int main(int argc, char* argv[]) {
// initialize default vector size and run count
int N = 1000000;
int R = 1000;
// assign new values to N (and R) if arguments provided
if (argc > 2) {
// iterate over arguments
for (int i = 0; i < argc; i++) {
// get current argument
string arg = argv[i];
// if size specified
if (arg.compare("-n") == 0) {
N = stoi(argv[i + 1]);
}
// if run count specified
else if (arg.compare("-r") == 0) {
R = stoi(argv[i + 1]);
}
}
}
// print info
cout << "========================================" << endl;
cout << "|\tSingle-Precision AX+Y" << endl;
cout << "========================================" << endl;
cout << "|\tUsing C++11" << endl;
cout << "|\tN = " << N << endl;
cout << "|\tRuns = " << R << endl;
cout << "|" << endl;
cout << "|\trunning..." << endl;
// initialize the float vectors
float *x, *y;
// allocate memory
x = new float[N];
y = new float[N];
// populate vectors
for (int i = 0; i < N; i++) {
y[i] = 1.0f;
x[i] = 2.0f;
}
// initialize clock
clock_t start = clock();
// perform algorithm R times
for (int i = 0; i < R; i++) {
// perform saxpy on CPU
saxpy(N, 2.0f, x, y);
}
// stop clock
clock_t stop = clock();
// counter for errors (should be 5.0f = 2.0 x 2.0 + 1.0)
int errors = 0;
// iterate vector to check for errors
for (int i = 0; i < N; i++) {
// increment error counter when unexpected value in index
if (fabs(y[i] - (4 * R + 1.0f)) > 0.0f)
errors++;
}
// print end status
cout << "|\t done!" << endl;
cout << "|" << endl;
cout << "|\tCalculation Errors = " << errors << endl;
cout << "|\tTime = " << (stop - start) / (double) CLOCKS_PER_SEC << " seconds" << endl;
cout << "========================================" << endl;
// free allocated memory
delete[] x;
delete[] y;
return 0;
}
| true |
678efb2014d990f47ae83289d957651ea8a3f682
|
C++
|
namhong2001/Algo
|
/aoj/fortress.cpp
|
UTF-8
| 2,505 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <functional>
using namespace std;
struct Circle {
int x;
int y;
int r;
int height = 0;
Circle* parent;
vector<Circle*> children;
int getHeight() {
if (height > 0) return height;
if (children.empty()) return 0;
for (int i=0; i<children.size(); ++i) {
height = max(height, children[i]->getHeight()+1);
}
return height;
}
};
bool isIn(const Circle* a, const Circle* b) {
int dist = pow(abs(a->x - b->x), 2) + pow(abs(a->y - b->y), 2);
return pow(a->r, 2) > dist;
}
Circle* makeTree(Circle* root, const vector<Circle*> &circles) {
vector<Circle*> children;
vector<vector<Circle*>> descendants;
for (int i=0; i<circles.size(); ++i) {
Circle* target = circles[i];
bool inserted = false;
for (int j=0; j<children.size(); ++j) {
if (isIn(children[j], target)) {
descendants[j].push_back(target);
inserted = true;
break;
}
}
if (!inserted) {
target->parent = root;
children.push_back(target);
descendants.push_back({}); // check necessary
}
}
root->children = children;
for (int i=0; i<children.size(); ++i) {
makeTree(children[i], descendants[i]);
}
return root;
}
int solve(Circle* root) {
vector<Circle*> &children = root->children;
int ans = 0;
vector<int> heights;
for (int i=0; i<children.size(); ++i) {
ans = max(ans, solve(children[i]));
heights.push_back(children[i]->getHeight());
}
sort(heights.begin(), heights.end(), greater<int>());
if (heights.size() >= 2) {
ans = max(ans, heights[0] + heights[1] + 2);
} else if (heights.size() == 1) {
ans = max(ans, heights[0]+1);
}
return ans;
}
int main() {
int c;
cin >> c;
while (c--) {
int n;
cin >> n;
vector<Circle*> circles;
for (int i=0; i<n; ++i) {
Circle* circle = new Circle();
cin >> circle->x >> circle->y >> circle->r;
circles.push_back(circle);
}
sort(circles.begin(), circles.end(), [](const Circle* A, const Circle* B){return A->r > B->r;});
Circle* root = makeTree(circles.front(), vector<Circle*>(circles.begin()+1, circles.end()));
cout << solve(root) << endl;
}
}
| true |
89a69001e02cf960c3922dffe17e2b0586a0e512
|
C++
|
THavart/Computer-Engineering-Technology
|
/C++/Graphics_Vectors + Shapes/VectorGraphic.h
|
UTF-8
| 358 | 2.609375 | 3 |
[] |
no_license
|
// VectorGraphic.h
#ifndef VECTORGRAPHIC_H
#define VECTORGRAPHIC_H
#include <vector>
using namespace std;
#include "GraphicElement.h"
class VectorGraphic : public vector<GraphicElement>
{
public:
VectorGraphic();
~VectorGraphic();
void AddGraphicElement();
void DeleteGraphicElement();
friend ostream& operator<<(ostream&, VectorGraphic&);
};
#endif
| true |
1e4a3f6c06b24c9d0a61ad761a8acfc0156eefc1
|
C++
|
mcmiloy/cpp_primer
|
/c3/vector2.cpp
|
UTF-8
| 418 | 3.078125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
int main(){
vector<unsigned> scores(11, 0);
unsigned grade;
while(std::cin >> grade){
if (grade <= 100)
++scores[grade/10];
// same as
// auto ind = grade/10;
// scores[ind] = scores[ind] + 1;
// the subscript operator vector[index] does not add elements to vector!!
}
}
| true |
5ad8c30434c087ff0b14fe6d612f65ed3315d7b2
|
C++
|
byn52602/RAII-Net
|
/src/Ability.h
|
UTF-8
| 488 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef ABILITY_H
#define ABILITY_H
#include <string>
enum Abilities {LinkBoost = 'L', Firewall = 'F', Download = 'D', Polarize = 'P', Scan = 'S', Sand = 'N', Portal = 'O', Strengthen = 'R'} ;
class Ability{
private:
int ID;
Abilities name;
bool isUsed;
public:
Ability(char code, int id);
~Ability();
int getAbilityID();
std::string getAbilityName();
bool getIsUsed();
void useAbility();
};
#endif
| true |
b9cc70d4a3c1a6d7cb85b602dd5d17764b9bb176
|
C++
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
/Engine/Source/ThirdParty/PhysX/APEX_1.4/shared/general/meshimport/include/utils/MiInparser.h
|
UTF-8
| 6,473 | 2.703125 | 3 |
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
/*
* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#ifndef INPARSER_H
#define INPARSER_H
#include <assert.h>
#define MAXARGS 512
/** @file inparser.h
* @brief Parse ASCII text, in place, very quickly.
*
* This class provides for high speed in-place (destructive) parsing of an ASCII text file.
* This class will either load an ASCII text file from disk, or can be constructed with a pointer to
* a piece of ASCII text in memory. It can only be called once, and the contents are destroyed.
* To speed the process of parsing, it simply builds pointers to the original ascii data and replaces the
* seperators with a zero byte to indicate end of string. It performs callbacks to parse each line, in argc/argv format,
* offering the option to cancel the parsing process at any time.
*
*
* By default the only valid seperator is whitespace. It will not treat commas or any other symbol as a separator.
* You can specify any character to be a 'hard' seperator, such as an '=' for example and that will come back as a
* distinct argument string.
*
* To use the parser simply inherit the pure virtual base class 'InPlaceParserInterface'. Define the method 'ParseLine'.
* When you invoke the Parse method on the InPlaceParser class, you will get an ARGC - ARGV style callback for each line
* in the source file. If you return 'false' at any time, it will abort parsing. The entire thing is stack based, so you
* can recursively call multiple parser instances.
*
* It is important to note. Since this parser is 'in place' it writes 'zero bytes' (EOS marker) on top of the whitespace.
* While it can handle text in quotes, it does not handle escape sequences. This is a limitation which could be resolved.
* There is a hard coded maximum limit of 512 arguments per line.
*
* Here is the full example usage:
*
* InPlaceParser ipp("parse_me.txt");
*
* ipp.Parse(this);
*
* That's it, and you will receive an ARGC - ARGV callback for every line in the file.
*
* If you want to parse some text in memory of your own. (It *MUST* be terminated by a zero byte, and lines seperated by carriage return
* or line-feed. You will receive an assertion if it does not. If you specify the source data than *you* are responsible for that memory
* and must de-allocate it yourself. If the data was loaded from a file on disk, then it is automatically de-allocated by the InPlaceParser.
*
* You can also construct the InPlaceParser without passing any data, so you can simply pass it a line of data at a time yourself. The
* line of data should be zero-byte terminated.
*/
#include "MiPlatformConfig.h"
namespace mimp
{
class InPlaceParserInterface
{
public:
virtual MiI32 ParseLine(MiI32 lineno,MiI32 argc,const char **argv) =0; // return TRUE to continue parsing, return FALSE to abort parsing process
virtual bool preParseLine(MiI32 /* lineno */,const char * /* line */) { return false; }; // optional chance to pre-parse the line as raw data. If you return 'true' the line will be skipped assuming you snarfed it.
};
enum SeparatorType
{
ST_DATA, // is data
ST_HARD, // is a hard separator
ST_SOFT, // is a soft separator
ST_EOS, // is a comment symbol, and everything past this character should be ignored
ST_LINE_FEED
};
class InPlaceParser
{
public:
InPlaceParser(void)
{
Init();
}
InPlaceParser(char *data,MiI32 len)
{
Init();
SetSourceData(data,len);
}
InPlaceParser(const char *fname)
{
Init();
SetFile(fname);
}
~InPlaceParser(void);
void Init(void)
{
mQuoteChar = 34;
mData = 0;
mLen = 0;
mMyAlloc = false;
for (MiI32 i=0; i<256; i++)
{
mHard[i] = ST_DATA;
mHardString[i*2] = (char)i;
mHardString[i*2+1] = 0;
}
mHard[0] = ST_EOS;
mHard[32] = ST_SOFT;
mHard[9] = ST_SOFT;
mHard[13] = ST_LINE_FEED;
mHard[10] = ST_LINE_FEED;
}
void SetFile(const char *fname);
void SetSourceData(char *data,MiI32 len)
{
mData = data;
mLen = len;
mMyAlloc = false;
};
MiI32 Parse(const char *str,InPlaceParserInterface *callback); // returns true if entire file was parsed, false if it aborted for some reason
MiI32 Parse(InPlaceParserInterface *callback); // returns true if entire file was parsed, false if it aborted for some reason
MiI32 ProcessLine(MiI32 lineno,char *line,InPlaceParserInterface *callback);
const char ** GetArglist(char *source,MiI32 &count); // convert source string into an arg list, this is a destructive parse.
void SetHardSeparator(char c) // add a hard separator
{
mHard[(unsigned char)c] = ST_HARD;
}
void SetHard(char c) // add a hard separator
{
mHard[(unsigned char)c] = ST_HARD;
}
void SetSoft(char c) // add a hard separator
{
mHard[(unsigned char)c] = ST_SOFT;
}
void SetCommentSymbol(char c) // comment character, treated as 'end of string'
{
mHard[(unsigned char)c] = ST_EOS;
}
void ClearHardSeparator(char c)
{
mHard[(unsigned char)c] = ST_DATA;
}
void DefaultSymbols(void); // set up default symbols for hard seperator and comment symbol of the '#' character.
bool EOS(char c)
{
if ( mHard[(unsigned char)c] == ST_EOS )
{
return true;
}
return false;
}
void SetQuoteChar(char c)
{
mQuoteChar = c;
}
bool HasData( void ) const
{
return ( mData != 0 );
}
void setLineFeed(char c)
{
mHard[(unsigned char)c] = ST_LINE_FEED;
}
bool isLineFeed(char c)
{
if ( mHard[(unsigned char)c] == ST_LINE_FEED ) return true;
return false;
}
private:
inline char * AddHard(MiI32 &argc,const char **argv,char *foo);
inline bool IsHard(char c);
inline char * SkipSpaces(char *foo);
inline bool IsWhiteSpace(char c);
inline bool IsNonSeparator(char c); // non seperator,neither hard nor soft
bool mMyAlloc; // whether or not *I* allocated the buffer and am responsible for deleting it.
char *mData; // ascii data to parse.
MiI32 mLen; // length of data
SeparatorType mHard[256];
char mHardString[256*2];
char mQuoteChar;
const char *argv[MAXARGS];
};
};
#endif
| true |
f98a66f826ca48acc6de7673465af3a1deeaa6b5
|
C++
|
chingpaq/CorbaTask
|
/P5_CorbaTestTask/Common/src/MathFactory.cpp
|
UTF-8
| 164 | 2.703125 | 3 |
[] |
no_license
|
float Plus (int a, int b){return a+b;}
float Minus (int a, int b){return a-b;}
float Multiply (int a, int b){return a*b;}
float Divide (int a, int b){return a/b;}
| true |
2438c1f68e0083a6aabbe43001f2bf54f022961a
|
C++
|
dotnet/runtime
|
/src/coreclr/pal/tests/palsuite/c_runtime/errno/test2/test2.cpp
|
UTF-8
| 1,871 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test2.c
**
** Purpose: Test that errno is 'per-thread' as noted in the documentation.
**
**
**==========================================================================*/
#include <palsuite.h>
/*
This thread function just checks that errno is initially 0 and then sets
it to a new value before returning.
*/
DWORD PALAPI ThreadFunc_errno_test2( LPVOID lpParam )
{
if(errno != 0)
{
*((DWORD*)lpParam) = 1;
}
errno = 20;
return 0;
}
PALTEST(c_runtime_errno_test2_paltest_errno_test2, "c_runtime/errno/test2/paltest_errno_test2")
{
DWORD dwThreadId, dwThrdParam = 0;
HANDLE hThread;
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
/* Set errno to a value within this thread */
errno = 50;
hThread = CreateThread(NULL, 0, ThreadFunc_errno_test2, &dwThrdParam, 0, &dwThreadId);
if (hThread == NULL)
{
Fail("ERROR: CreateThread failed to create a thread. "
"GetLastError() returned %d.\n",GetLastError());
}
WaitForSingleObject(hThread, INFINITE);
/* This checks the result of calling the thread */
if(dwThrdParam)
{
Fail("ERROR: errno was not set to 0 in the new thread. Each "
"thread should have its own value for errno.\n");
}
/* Check to make sure errno is still set to 50 */
if(errno != 50)
{
Fail("ERROR: errno should be 50 in the main thread, even though "
"it was set to 20 in another thread. Currently it is %d.\n",
errno);
}
PAL_Terminate();
return PASS;
}
| true |
1ad837f95ff06fb0c4a5d0bd9dcf8a3a47dee862
|
C++
|
sienaiwun/MAGE
|
/MAGE/MAGE/src/system/system_time.hpp
|
UTF-8
| 2,657 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
//-----------------------------------------------------------------------------
// Engine Includes
//-----------------------------------------------------------------------------
#pragma region
#include "platform\windows.hpp"
#pragma endregion
//-----------------------------------------------------------------------------
// System Includes
//-----------------------------------------------------------------------------
#pragma region
#include <stdint.h>
#pragma endregion
//-----------------------------------------------------------------------------
// Engine Declarations and Definitions
//-----------------------------------------------------------------------------
namespace mage {
/**
Returns the current system timestamp (in 100 ns).
@return The current system timestamp (in 100 ns).
*/
uint64_t GetCurrentSystemTimestamp() noexcept;
/**
Returns the current core timestamp (in 100 ns).
@pre @a handle_process is not equal to @c nullptr.
@pre @a kernel_mode_timestamp is not equal to @c nullptr.
@pre @a user_mode_timestamp is not equal to @c nullptr.
@pre @a handle_process must have the @c PROCESS_QUERY_INFORMATION
or @c PROCESS_QUERY_LIMITED_INFORMATION access right.
@param[in] handle_process
A handle to the process whose timing information is sought.
@param[out] kernel_mode_timestamp
A pointer to the current kernel mode timestamp
of the given process.
@param[out] user_mode_timestamp
A pointer to the current user mode timestamp
of the given process.
@note If the retrieval fails, both @a kernel_mode_timestamp
and @a user_mode_timestamp point to zero.
To get extended error information, call GetLastError.
*/
void GetCurrentCoreTimestamp(HANDLE handle_process,
uint64_t *kernel_mode_timestamp, uint64_t *user_mode_timestamp) noexcept;
/**
Returns the current core timestamp (in 100 ns).
@pre @a kernel_mode_timestamp is not equal to @c nullptr.
@pre @a user_mode_timestamp is not equal to @c nullptr.
@param[out] kernel_mode_timestamp
A pointer to the current kernel mode timestamp
of the calling process.
@param[out] user_mode_timestamp
A pointer to the current user mode timestamp
of the calling process.
@note If the retrieval fails, both @a kernel_mode_timestamp
and @a user_mode_timestamp point to zero.
To get extended error information, call GetLastError.
*/
inline void GetCurrentCoreTimestamp(uint64_t *kernel_mode_timestamp, uint64_t *user_mode_timestamp) noexcept {
GetCurrentCoreTimestamp(GetCurrentProcess(), kernel_mode_timestamp, user_mode_timestamp);
}
}
| true |
ec7ce23cc7e152f83ae6ebf93df6107a1dcebaeb
|
C++
|
brunolaporais/blprecsys
|
/recsys_methods/colaborative_filtring/ItemBased.cpp
|
UTF-8
| 2,206 | 2.578125 | 3 |
[] |
no_license
|
/*
* ItemBased.cpp
*
* Created on: Sep 24, 2015
* Author: brunolaporais
*/
#include "ItemBased.h"
ItemBased::ItemBased(Dataset &d):data(d) {
// TODO Auto-generated constructor stub
}
ItemBased::~ItemBased() {
// TODO Auto-generated destructor stub
}
void ItemBased::predictTarget(int nbNumbers, int minItems, int minUsers){
Similarity calcSim(data);
double rating, numerator = 0.0, denominator = 0.0;
int iterNum = 0;
unordered_map<int,unordered_map<int,double> >::iterator itTargUsr = data.targetData.begin();
for(;itTargUsr != data.targetData.end(); ++itTargUsr){
unordered_map<int,double>::iterator itTargItem = data.targetData[itTargUsr->first].begin();
for(;itTargItem != data.targetData[itTargUsr->first].end(); ++itTargItem){
if(data.ratingsByUser[itTargUsr->first].size() <= minItems &&
data.ratingsByItem[itTargItem->first].size() <= minUsers){
rating = data.itemAvg;
} else if(data.ratingsByUser[itTargUsr->first].size() <= minItems){
rating = data.avgByItem[itTargItem->first];
} else if(data.ratingsByItem[itTargItem->first].size() <= minUsers){
rating = data.avgByUser[itTargUsr->first];
} else {
calcSim.cosineByItem(itTargItem->first);
rating = 0;
numerator = 0.0;
denominator = 0.0;
iterNum = 0;
unordered_map<int,double>::iterator itSim = data.itemSimilarity[itTargItem->first].begin();
for(;itSim != data.itemSimilarity[itTargItem->first].end(); ++itSim){
if(data.ratingsByUser[itTargUsr->first].find(itSim->first) != data.ratingsByUser[itTargUsr->first].end()){
numerator += itSim->second * data.ratingsByItem[itSim->first][itTargUsr->first];
/*cout << itSim->second << "*("
<< data.ratingsByUser[itSim->first][itTargItem->first]
<< "-" << data.avgByUser[itTargUsr->first]
<< ")=" << numerator << "\n";*/
denominator += abs(itSim->second);
++iterNum;
}
if(iterNum >= nbNumbers && nbNumbers > 0) break;
}
if(numerator != 0) {
rating = numerator / denominator;
}
}
if(rating > 10) rating = 10;
if(rating < 1) rating = 1;
rating = rating;
data.targetData[itTargUsr->first][itTargItem->first] = rating;
}
}
}
| true |
78d321306d7df503b5944ee685929f67a1f87972
|
C++
|
xusiwei/leetcode
|
/Algorithms/BinaryTreeZigzagLevelOrderTraversal/binaryTreeZigzagLevelOrderTraversal.cc
|
UTF-8
| 2,722 | 4.03125 | 4 |
[] |
no_license
|
/*
copyright xu(xusiwei1236@163.com), all right reserved.
Binary Tree Zigzag Level Order Traversal
=========================================
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*/
#include <deque>
#include <vector>
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode* lst, TreeNode* rst) : val(x), left(lst), right(rst) {}
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
if(root == NULL) return result;
int level = 0;
deque<TreeNode*> queue;
TreeNode *last = root;
queue.push_back(root);
result.push_back(vector<int>());
while(!queue.empty()) {
TreeNode *p = queue.front();
queue.pop_front();
result[level].insert(level & 1 ? result[level].begin() : result[level].end(), p->val);
if(p->left) queue.push_back(p->left);
if(p->right) queue.push_back(p->right);
if(p == last) {
level++;
last = queue.back();
result.push_back(vector<int>());
}
}
result.pop_back();
return result;
}
};
int main(int argc, char* argv[])
{
TreeNode *root = new TreeNode(3,
new TreeNode(9),
new TreeNode(20,
new TreeNode(15),
new TreeNode(7)));
vector<vector<int> > vv = Solution().zigzagLevelOrder(root);
for(int i = 0; i < vv.size(); i++) {
for(int j = 0; j < vv[i].size(); j++) {
cout << vv[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
3b8728e0c2123b41fb3f03bf4678fce0afe4ea0a
|
C++
|
lukedan/DoodleEngine
|
/Engine/BinarySearchTree.h
|
UTF-8
| 19,044 | 2.703125 | 3 |
[] |
no_license
|
#pragma once
#include <tchar.h>
#include <functional>
#include "Common.h"
#include "Math.h"
#include "ObjectAllocator.h"
#include "List.h"
namespace DE {
namespace Core {
namespace Collections {
template <typename KeyType, typename ValueType> struct KeyValuePair;
template <typename KeyType, typename ValueType, class Comparer = DefaultComparer<KeyType>> class KeyValuePairComparer {
public:
static int Compare(const KeyValuePair<KeyType, ValueType> &lhs, const KeyValuePair<KeyType, ValueType> &rhs) {
return Comparer::Compare(lhs.Key(), rhs.Key());
}
};
template <typename KeyType, typename ValueType> struct KeyValuePair {
public:
KeyValuePair() = default;
explicit KeyValuePair(const KeyType &key) : _key(key) {
}
KeyValuePair(const KeyType &key, const ValueType &value) : _key(key), _value(value) {
}
KeyType &Key() {
return _key;
}
const KeyType &Key() const {
return _key;
}
ValueType &Value() {
return _value;
}
const ValueType &Value() const {
return _value;
}
private:
KeyType _key;
ValueType _value;
};
template <typename T, class Comparer> class BST;
template <typename T, class Comparer = DefaultComparer<T>> class BSTNode {
friend class BST<T, Comparer>;
public:
BSTNode(const BSTNode&) = delete;
BSTNode &operator =(const BSTNode&) = delete;
const T &Value() const {
return _val;
}
T &Value() {
return _val;
}
BSTNode<T, Comparer> *Next() {
if (_tree == nullptr) {
throw InvalidOperationException(_TEXT("this node is not in a tree"));
}
return _tree->Next(this);
}
BSTNode<T, Comparer> *Previous() {
if (_tree == nullptr) {
throw InvalidOperationException(_TEXT("this node is not in a tree"));
}
return _tree->Previous(this);
}
const BSTNode<T, Comparer> *Next() const {
if (_tree == nullptr) {
throw InvalidOperationException(_TEXT("this node is not in a tree"));
}
return _tree->Next(this);
}
const BSTNode<T, Comparer> *Previous() const {
if (_tree == nullptr) {
throw InvalidOperationException(_TEXT("this node is not in a tree"));
}
return _tree->Previous(this);
}
private:
explicit BSTNode(BST<T, Comparer> *t) : _tree(t) {
}
BSTNode(BST<T, Comparer> *t, const T &val) : _val(val), _tree(t) {
}
T _val;
BSTNode<T, Comparer> *_left = nullptr, *_right = nullptr, *_father = nullptr;
size_t _treeSize = 1;
BST<T, Comparer> *const _tree;
/*
* X LeftRotate Y
* / \ <------------ / \
* Y 3 ------------> 1 X
* / \ RightRotate / \
* 1 2 2 3
*/
void LeftRotate() {
if (!_right) {
return;
}
_right->_father = _father;
if (_father) {
(this == _father->_left ? _father->_left : _father->_right) = _right;
}
_father = _right;
_right = _right->_left;
_father->_left = this;
if (_right) {
_right->_father = this;
}
_father->_treeSize = _treeSize;
_treeSize -= 1 + (_father->_right ? _father->_right->_treeSize : 0);
}
void RightRotate() {
if (!_left) {
return;
}
_left->_father = _father;
if (_father) {
(this == _father->_left ? _father->_left : _father->_right) = _left;
}
_father = _left;
_left = _left->_right;
_father->_right = this;
if (_left) {
_left->_father = this;
}
_father->_treeSize = _treeSize;
_treeSize -= 1 + (_father->_left ? _father->_left->_treeSize : 0);
}
static void DisposeTree(BSTNode<T, Comparer> *node) {
if (node) {
List<BSTNode<T, Comparer>*> stk;
stk.PushBack(node);
while (stk.Count() > 0) {
node = stk.PopBack();
if (node->_left) {
stk.PushBack(node->_left);
}
if (node->_right) {
stk.PushBack(node->_right);
}
node->~BSTNode<T, Comparer>();
GlobalAllocator::Free(node);
}
}
}
static void Dispose(BSTNode<T, Comparer> *node) {
node->~BSTNode<T, Comparer>();
GlobalAllocator::Free(node);
}
static BSTNode<T, Comparer> *Copy(BST<T, Comparer> *tree, const BSTNode<T, Comparer> *node, BSTNode<T, Comparer> *father = nullptr) {
if (!node) {
return nullptr;
}
BSTNode<T, Comparer> *result =
new (GlobalAllocator::Allocate(sizeof(BSTNode<T, Comparer>))) BSTNode<T, Comparer>(tree, node->_val);
result->_left = Copy(tree, node->_left, result);
result->_right = Copy(tree, node->_right, result);
result->_treeSize = node->_treeSize;
result->_father = father;
return result;
}
};
template <typename T, class Comparer = DefaultComparer<T>> class BST { // actually splay tree
public:
typedef BSTNode<T, Comparer> Node;
BST() = default;
BST(const BST &src) : _root(Node::Copy(this, src._root)) {
}
BST &operator =(const BST &src) {
if (this == &src) {
return *this;
}
if (_root) {
Node::DisposeTree(_root);
}
_root = Node::Copy(this, src._root);
return *this;
}
virtual ~BST() {
Node::DisposeTree(_root);
}
Node *Maximum() {
Node *n = Maximum(_root);
Splay(n);
return n;
}
const Node *Maximum() const {
return Maximum(_root);
}
Node *Minimum() {
Node *n = Minimum(_root);
Splay(n);
return n;
}
const Node *Minimum() const {
return Minimum(_root);
}
const Node *Next(const Node *n) const {
if (n == nullptr) {
throw InvalidArgumentException(_TEXT("the node is null"));
}
if (n->_right) {
for (n = n->_right; n->_left; n = n->_left) {
}
return n;
}
Node *last = n->_father;
for (; last && n == last->_right; n = last, last = last->_father) {
}
return last;
}
Node *Next(Node *n) {
if (n == nullptr) {
throw InvalidArgumentException(_TEXT("the node is null"));
}
if (n->_right) {
for (n = n->_right; n->_left; n = n->_left) {
}
Splay(n);
return n;
}
Node *last = n->_father;
for (; last && n == last->_right; n = last, last = last->_father) {
}
Splay(last);
return last;
}
const Node *Previous(const Node *n) const {
if (n == nullptr) {
throw InvalidArgumentException(_TEXT("the node is null"));
}
if (n->_left) {
for (n = n->_left; n->_right; n = n->_right) {
}
return n;
}
Node *last = n->_father;
for (; last && n == last->_left; n = last, last = last->_father) {
}
return last;
}
Node *Previous(Node *n) {
if (n == nullptr) {
throw InvalidArgumentException(_TEXT("the node is null"));
}
if (n->_left) {
for (n = n->_left; n->_right; n = n->_right) {
}
Splay(n);
return n;
}
Node *last = n->_father;
for (; last && n == last->_left; n = last, last = last->_father) {
}
Splay(last);
return last;
}
Node *InsertRight(const T &value) {
Node *n = new (GlobalAllocator::Allocate(sizeof(Node))) Node(this, value);
if (_root == nullptr) {
_root = n;
return n;
}
Node **t = nullptr;
for (Node *cur = _root; cur; cur = *t) {
n->_father = cur;
++(cur->_treeSize);
t = (Comparer::Compare(n->_val, cur->_val) < 0 ? &(cur->_left) : &(cur->_right));
}
(*t) = n;
Splay(n);
return n;
}
Node *InsertLeft(const T &value) {
Node *n = new (GlobalAllocator::Allocate(sizeof(Node))) Node(this, value);
if (_root == nullptr) {
_root = n;
return n;
}
Node **t = nullptr;
for (Node *cur = _root; cur; cur = *t) {
n->_father = cur;
++(cur->_treeSize);
t = (Comparer::Compare(n->_val, cur->_val) <= 0 ? &(cur->_left) : &(cur->_right));
}
(*t) = n;
Splay(n);
return n;
}
void Delete(Node *n) {
if (n == nullptr) {
throw InvalidOperationException(_TEXT("the node to delete is null"));
}
Splay(n);
if (n->_left) {
Node *lMax = Maximum(n->_left);
Splay(lMax, n);
lMax->_right = n->_right;
if (lMax->_right) {
lMax->_treeSize += lMax->_right->_treeSize;
lMax->_right->_father = lMax;
}
_root = lMax;
lMax->_father = nullptr;
} else {
_root = n->_right;
if (_root) {
_root->_father = nullptr;
}
}
Node::Dispose(n);
}
Node *Find(const T &targetVal) {
for (Node *n = _root; n; n = (Comparer::Compare(n->_val, targetVal) > 0 ? n->_left : n->_right)) {
if (Comparer::Compare(n->_val, targetVal) == 0) {
Splay(n);
return n;
}
}
return nullptr;
}
const Node *Find(const T &targetVal) const {
int lval;
for (const Node *n = _root; n; n = (lval > 0 ? n->_left : n->_right)) {
lval = Comparer::Compare(n->_val, targetVal);
if (lval == 0) {
return n;
}
}
return nullptr;
}
template <class Predicate> Node *Find(const T &targetVal) {
int lval;
for (Node *n = _root; n; n = (lval > 0 ? n->_left : n->_right)) {
lval = Comparer::Compare(n->_val, targetVal);
if (lval == 0) {
for (; n->_left && Comparer::Compare(n->_left->_val, targetVal) == 0; n = n->_left) {
}
for (Node *cur = n; cur && Comparer::Compare(cur->_val, targetVal) == 0; cur = Next(cur)) {
if (Predicate::Examine(targetVal, cur->_val)) {
return cur;
}
}
return nullptr;
}
}
return nullptr;
}
template <class Predicate> const Node *Find(const T &targetVal) const {
int lval;
for (const Node *n = _root; n; n = (lval > 0 ? n->_left : n->_right)) {
lval = Comparer::Compare(n->_val, targetVal);
if (lval == 0) {
for (; n->_left && Comparer::Compare(n->_left->_val, targetVal) == 0; n = n->_left) {
}
for (Node *cur = n; cur && Comparer::Compare(cur->_val, targetVal) == 0; cur = Next(cur)) {
if (Predicate::Examine(targetVal, cur->_val)) {
return cur;
}
}
return nullptr;
}
}
return nullptr;
}
protected:
struct IterationStackRecord {
IterationStackRecord() = default;
explicit IterationStackRecord(Node *n) : CurrentNode(n) {
}
Node *CurrentNode = nullptr;
bool Visited = false, LVisited = false, RVisited = false;
};
public:
void ForEach(const std::function<bool(Node*)> &func) { // TODO: repeated code
List<IterationStackRecord> stack;
if (_root == nullptr) {
return;
}
stack.PushBack(IterationStackRecord(_root));
while (stack.Count() > 0) {
IterationStackRecord ¤t = stack.Last(), *up = (stack.Count() > 1 ? &stack[stack.Count() - 2] : nullptr);
if (current.Visited) {
if (current.CurrentNode->_right == nullptr || current.RVisited) {
stack.PopBack();
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
} else {
if (current.CurrentNode->_left == nullptr || current.LVisited) {
if (!func(current.CurrentNode)) {
break;
}
current.Visited = true;
if (up) {
(current.CurrentNode == up->CurrentNode->_right ? up->RVisited : up->LVisited) = true;
}
if (current.CurrentNode->_right) {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
}
}
}
void ForEach(const std::function<bool(const Node*)> &func) const {
List<IterationStackRecord> stack;
if (_root == nullptr) {
return;
}
stack.PushBack(IterationStackRecord(_root));
while (stack.Count() > 0) {
IterationStackRecord ¤t = stack.Last(), *up = (stack.Count() > 1 ? &stack[stack.Count() - 2] : nullptr);
if (current.Visited) {
if (current.CurrentNode->_right == nullptr || current.RVisited) {
stack.PopBack();
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
} else {
if (current.CurrentNode->_left == nullptr || current.LVisited) {
if (!func(current.CurrentNode)) {
break;
}
current.Visited = true;
if (up) {
(current.CurrentNode == up->CurrentNode->_right ? up->RVisited : up->LVisited) = true;
}
if (current.CurrentNode->_right) {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
}
}
}
void ForEachReversed(const std::function<bool(Node*)> &func) {
List<IterationStackRecord> stack;
if (_root == nullptr) {
return;
}
stack.PushBack(IterationStackRecord(_root));
while (stack.Count() > 0) {
IterationStackRecord ¤t = stack.Last(), *up = (stack.Count() > 1 ? &stack[stack.Count() - 2] : nullptr);
if (current.Visited) {
if (current.CurrentNode->_left == nullptr || current.LVisited) {
stack.PopBack();
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
} else {
if (current.CurrentNode->_right == nullptr || current.RVisited) {
if (!func(current.CurrentNode)) {
break;
}
current.Visited = true;
if (up) {
(current.CurrentNode == up->CurrentNode->_right ? up->RVisited : up->LVisited) = true;
}
if (current.CurrentNode->_left) {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
}
}
}
void ForEachReversed(const std::function<bool(const Node*)> &func) const {
List<IterationStackRecord> stack;
if (_root == nullptr) {
return;
}
stack.PushBack(IterationStackRecord(_root));
while (stack.Count() > 0) {
IterationStackRecord ¤t = stack.Last(), *up = (stack.Count() > 1 ? &stack[stack.Count() - 2] : nullptr);
if (current.Visited) {
if (current.CurrentNode->_left == nullptr || current.LVisited) {
stack.PopBack();
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
} else {
if (current.CurrentNode->_right == nullptr || current.RVisited) {
if (!func(current.CurrentNode)) {
break;
}
current.Visited = true;
if (up) {
(current.CurrentNode == up->CurrentNode->_right ? up->RVisited : up->LVisited) = true;
}
if (current.CurrentNode->_left) {
stack.PushBack(IterationStackRecord(current.CurrentNode->_left));
}
} else {
stack.PushBack(IterationStackRecord(current.CurrentNode->_right));
}
}
}
}
Node *At(size_t index) {
for (Node *cur = _root; cur; ) {
size_t lsz = (cur->_left ? cur->_left->_treeSize : 0);
if (index == lsz) {
Splay(cur);
return cur;
}
cur = (index > lsz ? cur->_right : cur->_left);
if (index > lsz) {
index -= lsz + 1;
}
}
return nullptr;
}
const Node *At(size_t index) const {
for (const Node *cur = _root; cur; ) {
size_t lsz = (cur->_left ? cur->_left->_treeSize : 0);
if (index == lsz) {
return cur;
}
cur = (index > lsz ? cur->_right : cur->_left);
if (index > lsz) {
index -= lsz + 1;
}
}
return nullptr;
}
size_t GetIndex(Node *n) {
Splay(n);
return (n->_left ? n->_left->_treeSize : 0);
}
size_t GetIndex(const Node *n) const {
if (n == nullptr) {
throw InvalidArgumentException(_TEXT("the node is null"));
}
size_t res = (n->_left ? n->_left->_treeSize : 0);
for (const Node *cur = n->_father, *lst = n; cur; lst = cur, cur = cur->_father) {
if (lst == cur->_right) {
res += 1 + (cur->_left ? cur->_left->_treeSize : 0);
}
}
return res;
}
void Clear() {
Node::DisposeTree(_root);
_root = nullptr;
}
size_t Count() const {
return (_root ? _root->_treeSize : 0);
}
private:
Node *_root = nullptr;
void Splay(Node *target, Node *targetFather = nullptr) {
if (!target) {
return;
}
while (target->_father && target->_father != targetFather) {
bool fl = (target == target->_father->_left);
if (target->_father->_father) {
bool ffl = (target->_father == target->_father->_father->_left);
if (fl == ffl) {
if (fl) {
target->_father->_father->RightRotate();
target->_father->RightRotate();
} else {
target->_father->_father->LeftRotate();
target->_father->LeftRotate();
}
} else {
if (fl) {
target->_father->RightRotate();
target->_father->LeftRotate();
} else {
target->_father->LeftRotate();
target->_father->RightRotate();
}
}
} else {
if (fl) {
target->_father->RightRotate();
} else {
target->_father->LeftRotate();
}
}
}
_root = target;
}
const Node *Maximum(const Node *targetRoot) const {
for (; targetRoot && targetRoot->_right; targetRoot = targetRoot->_right) {
}
return targetRoot;
}
Node *Maximum(Node *targetRoot) {
for (; targetRoot && targetRoot->_right; targetRoot = targetRoot->_right) {
}
return targetRoot;
}
const Node *Minimum(const Node *targetRoot) const {
for (; targetRoot && targetRoot->_left; targetRoot = targetRoot->_left) {
}
return targetRoot;
}
Node *Minimum(Node *targetRoot) {
for (; targetRoot && targetRoot->_left; targetRoot = targetRoot->_left) {
}
return targetRoot;
}
};
}
}
}
| true |
0f4b0a6248281769746d5e9dc8d88a0bdc870903
|
C++
|
dmlicht/Swell-Synth
|
/rand_table.cpp
|
UTF-8
| 382 | 2.671875 | 3 |
[] |
no_license
|
#include "rand_table.h"
#include "wavetable.h"
#include <cmath>
#include <iostream>
rand_table::rand_table(): wavetable::wavetable(){
fill_table();
}
rand_table::rand_table(int size): wavetable::wavetable(size){
fill_table();
}
void rand_table::fill_table(){
srand(time(NULL));
for (int i = 0; i < length; ++i){
table[i] = (double) (rand() % 10000) / 5000 - 1;
}
}
| true |
2e7f10b4d3c996f614c9e4fda5c02baaa6473da7
|
C++
|
Phaeon/QtWarriors
|
/QtWarriors/Models/Pawns/super_attack_decorator.h
|
UTF-8
| 476 | 2.53125 | 3 |
[] |
no_license
|
#ifndef SUPER_ATTACK_DECORATOR_H
#define SUPER_ATTACK_DECORATOR_H
#include "powerdecorator.h"
/**
* @brief The Super_Attack_Decorator class
*/
class Super_Attack_Decorator : public Power_Decorator
{
public:
Super_Attack_Decorator();
Super_Attack_Decorator(std::shared_ptr<Pawn>);
Super_Attack_Decorator(const Super_Attack_Decorator &);
~Super_Attack_Decorator();
void super_attack(std::shared_ptr<Pawn> target);
};
#endif // SUPER_ATTACK_DECORATOR_H
| true |
16e5cd5106a687c1a35f4cdd2e5099dd17453b91
|
C++
|
nexus6-haiku/dontworry
|
/Extra/Exemples/Modifications.cpp
|
UTF-8
| 5,034 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
/*
* Test primitif des classes CS
*
*
*/
#include <DataIO.h>
#include <Entry.h>
#include <Directory.h>
#include <Roster.h>
#include <Path.h>
#include <String.h>
#include <stdio.h>
#include "Modifications.h"
#include "CSLibrary.h"
#include "CSClass.h"
#include "CSMethod.h"
#include "CSVariable.h"
int main()
{
(new ModificationsApp)->Run();
}
ModificationsApp::ModificationsApp()
: BApplication("application/x-vnd.STertois-CS_Modifications")
{
}
void ModificationsApp::ReadyToRun()
{
printf("Début du test.\n");
// détermination du répertoire de l'application
app_info l_MyAppInfo;
GetAppInfo(&l_MyAppInfo);
BEntry l_Application(&l_MyAppInfo.ref);
BDirectory l_AppDir;
l_Application.GetParent(&l_AppDir);
printf("Création du bloc mémoire...");
BMallocIO *l_MyFile = new BMallocIO;
printf("OK\n");
printf("Création de la librarie...");
CSLibrary *l_MyLibrary = new CSLibrary(l_MyFile);
if (l_MyLibrary->InitCheck() == B_OK)
printf("OK\n");
else
{
printf("Erreur!\n");
return;
}
printf("Début du parsing.\n");
BPath l_MyPath(&l_AppDir,"Modifications.h");
status_t l_Error;
while(true)
{
l_Error = l_MyLibrary->Parse(l_MyPath.Path(),false,0,true);
switch(l_Error)
{
case B_OK:
printf("OK!\n");
break;
case CSP_NOT_MODIFIED:
printf("Fichier non modifié\n");
break;
default:
printf("Erreur!\n");
break;
}
// restitution
printf("Restitution.\n");
DumpClass(l_MyLibrary,"ModificationsApp");
printf("Appuyez sur une touche pour recommencer\n");
getchar();
}
// destruction des objets
printf("Desctruction...");
delete l_MyLibrary;
delete l_MyFile;
printf("Fini!\n");
Quit();
}
void ModificationsApp::DumpClass(CSLibrary *lib, const char *className)
{
// on cherche si une description de la classe existe dans la blibliothèque
CSClass *l_Class = lib->GetClass(className);
if (l_Class == NULL)
printf("\n\nClasse %s non trouvée.\n",className);
else
{
DumpClass(lib,l_Class);
delete l_Class;
}
}
void ModificationsApp::DumpClass(CSLibrary *lib, CSClass *theClass)
{
// première ligne avec le nom de la classe
const char *l_HeaderPath = theClass->GetHeaderFile();
if (l_HeaderPath == NULL)
printf("\nclass %s\n{\n",theClass->GetName());
else
printf("\nclass %s\t(%s)\n{\n",theClass->GetName(),l_HeaderPath);
// on va parcourir les méthodes
CSMethod *l_Method = theClass->GetFirstMethod(CSMT_PUBLIC|CSMT_PROTECTED|CSMT_PRIVATE);
while (l_Method != NULL)
{
DumpMethod(l_Method);
delete l_Method;
l_Method = theClass->GetNextMethod();
}
// on va parcourir les variables membre
printf("\n");
CSVariable *l_Variable = theClass->GetFirstMember(CSMT_PROTECTED);
while (l_Variable != NULL)
{
DumpMemberVariable(l_Variable);
// on passe à la suivante
delete l_Variable;
l_Variable = theClass->GetNextMember();
}
// fin de la classe
printf("}\n\n");
// recherche de classes pères
CSClass *l_Father = theClass->GetFirstFather();
while (l_Father != NULL)
{
printf("%s hérite de %s:\n",theClass->GetName(),l_Father->GetName());
DumpClass(lib,l_Father);
delete l_Father;
l_Father = theClass->GetNextFather();
}
}
void ModificationsApp::DumpMemberVariable(CSVariable *variable)
{
// zone
printf("\t");
WriteZone(variable->GetZone());
// type de variable
printf(" %s ",variable->GetTypeName());
// les '*'
unsigned int l_PointerLevel = variable->GetPointerLevel();
for (unsigned int i=0; i<l_PointerLevel; i++)
printf("*");
// le nom de la variable
printf("%s;\n",variable->GetName());
}
void ModificationsApp::DumpMethod(CSMethod *method)
{
// zone
printf("\t");
WriteZone(method->GetZone());
// type de retour
printf(" %s ",method->GetReturnTypeName());
// les '*'
unsigned int l_PointerLevel = method->GetReturnPointerLevel();
for (unsigned int i=0; i<l_PointerLevel; i++)
printf("*");
// le nom de la méthode
printf("%s(",method->GetName());
// les arguments
bool l_FirstArg = true;
CSVariable *l_Argument = method->GetFirstArgument();
while (l_Argument != NULL)
{
// le type de l'argument
printf(l_FirstArg?" %s ":", %s ",l_Argument->GetTypeName());
// les '*'
l_PointerLevel = l_Argument->GetPointerLevel();
for (unsigned int i=0; i<l_PointerLevel; i++)
printf("*");
// le nom de l'argument, s'il est là
const char *l_Text = l_Argument->GetName();
if (l_Text != NULL)
printf(l_Text);
// la valeur par défault, si elle est là
l_Text = l_Argument->GetDefaultValue();
if (l_Text != NULL)
printf(" = %s",l_Text);
delete l_Argument;
l_Argument = method->GetNextArgument();
l_FirstArg = false;
}
// fin de la méthode
printf(");\n");
}
void ModificationsApp::WriteZone(unsigned int zone)
{
switch(zone)
{
case CSMT_PUBLIC:
printf("public");
break;
case CSMT_PROTECTED:
printf("protected");
break;
case CSMT_PRIVATE:
printf("private");
break;
default:
printf("unknown");
break;
}
}
| true |
8196210596553af4249a4cf52b38dd13308b08b2
|
C++
|
pavellebedev7/stc
|
/1/main.cpp
|
UTF-8
| 3,156 | 3.8125 | 4 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int CurrentYear = 2021;
const int n = 5;
struct Citizen{
string LastName;
string Residence;
int DateOfBirth;
};
void PrintFile(Citizen *citizens){
for(int i = 0; i < n; i++){
cout << citizens[i].LastName << " " << citizens[i].Residence << " " << citizens[i].DateOfBirth << endl;
}
}
void EditFile(Citizen *citizens){
int editline;
cout << "Enter the line to be changed" << endl;
cin >> editline;
if(editline >= 1 && editline <= n){
editline--;
cout << "Enter new LastName" << endl;
cin >> citizens[editline].LastName;
cout << "Enter new Residence" << endl;
cin >> citizens[editline].Residence;
cout << "Enter new DateOfBirth" << endl;
cin >> citizens[editline].DateOfBirth;
cout << "Line " << editline+1 << " has been changed" << endl;
}
else{
cout << "This line doesn't exist" << endl;
}
}
void GetAverageAge(Citizen *citizens){
int tmp = 0;
for(int i = 0; i < n; i++){
tmp += CurrentYear - citizens[i].DateOfBirth;
}
float avg = (float)tmp/n;
cout << "Average age: " << avg << endl;
}
void SaveFile(Citizen *citizens){
string filename;
cout << "Enter filename to save to" << endl;
cin >> filename;
ofstream fout;
fout.open(filename.c_str());
if(fout){
for(int i = 0; i < n; i++){
fout << citizens[i].LastName << " " << citizens[i].Residence << " " << citizens[i].DateOfBirth << endl;
}
fout.close();
cout << "Saved to " << filename << endl;
}
else{
cout << "Error" << endl;
}
}
int main()
{
// 20 var
// Memory allocation
Citizen* citizens = new Citizen[n];
// File I/O
ifstream fin;
fin.open("input.txt");
// Read file
if(fin){
for(int i = 0; i < n; i++){
fin >> citizens[i].LastName >> citizens[i].Residence >> citizens[i].DateOfBirth;
}
fin.close();
}
else{
cout << "Error" << endl;
}
// Menu
int command, exitflag = 0;
while(true && !exitflag){
cout << "Enter 1 - Print, 2 - Edit, 3 - Get average age, 4 - Save, 5 - Exit" << endl;
cin >> command;
switch(command){
case(1):
// Print file
PrintFile(citizens);
break;
case(2):
// Edit file
EditFile(citizens);
break;
case(3):
// Get average age
GetAverageAge(citizens);
break;
case(4):
// Save file
SaveFile(citizens);
break;
case(5):
// Exit
cout << "Exit" << endl;
exitflag = 1;
break;
default:
break;
}
}
// Memory deallocation
delete[] citizens;
}
| true |
2092752f4ea6f8985dfcef695d46dc13300ae8d7
|
C++
|
Tudor67/Competitive-Programming
|
/LeetCode/Problems/Algorithms/#1719_NumberOfWaysToReconstructATree_sol1_dfs_and_greedy_and_sort_O(N^2+ElogE)_time_O(N+E)_extra_space_1056ms_123MB.cpp
|
UTF-8
| 2,745 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
private:
using Graph = vector<vector<int>>;
bool contains(const vector<int>& A, const vector<int>& B){
// return true if vector A (with unique elements)
// contains all elements of vector B (with unique elements)
if(A.size() < B.size()){
return false;
}
int indexB = 0;
for(int indexA = 0; indexA < (int)A.size() && indexB < (int)B.size(); ++indexA){
if(A[indexA] == B[indexB]){
indexB += 1;
}
}
return (indexB == (int)B.size());
}
void dfs(int node, unordered_set<int>& vis, Graph& G, bool& isValid, bool& containsDuplicateConfig){
vis.insert(node);
for(int nextNode: G[node]){
if(vis.count(nextNode)){
continue;
}
if(isValid && contains(G[node], G[nextNode])){
containsDuplicateConfig = containsDuplicateConfig || (G[node].size() == G[nextNode].size());
dfs(nextNode, vis, G, isValid, containsDuplicateConfig);
}else{
isValid = false;
break;
}
}
}
public:
int checkWays(vector<vector<int>>& pairs) {
int maxNode = 1;
for(const vector<int>& P: pairs){
int x = P[0];
int y = P[1];
maxNode = max(maxNode, max(x, y));
}
Graph G(maxNode + 1);
int uniqueNodes = 0;
for(const vector<int>& P: pairs){
int x = P[0];
int y = P[1];
G[x].push_back(y);
G[y].push_back(x);
uniqueNodes += (int)((int)G[x].size() == 1);
uniqueNodes += (int)((int)G[y].size() == 1);
}
int root = -1;
for(int node = 1; node <= maxNode; ++node){
G[node].push_back(node);
if((int)G[node].size() == uniqueNodes){
root = node;
}
}
if(root == -1){
return 0;
}
for(int node = 1; node <= maxNode; ++node){
sort(G[node].begin(), G[node].end(),
[&](int lhs, int rhs){
return pair<int, int>{G[lhs].size(), lhs} >
pair<int, int>{G[rhs].size(), rhs};
});
}
unordered_set<int> vis;
bool isValid = true;
bool containsDuplicateConfig = false;
dfs(root, vis, G, isValid, containsDuplicateConfig);
if(!isValid){
return 0;
}
if(!containsDuplicateConfig){
return 1;
}
return 2;
}
};
| true |
1df84c4f91330b1a912b38473191cfca19333724
|
C++
|
Fredrik-G/oru-freguh131
|
/DoA/Forward_List/main.cpp
|
ISO-8859-1
| 1,548 | 3.15625 | 3 |
[] |
no_license
|
#include <iostream>
#include <clocale>
#include <string>
#include "forward_list.h"
using namespace std;
int main()
{
//***********************************************
//COPY CONSTRUCTOR
forward_list<int> fl1,fl2,fl3;
for (int i = 1; i < 15; i++)
fl1.push_front(i);
forward_list<int> fl4(fl1);
cout << "List1\tList4\n";
for (int i = 14; i > 0; i--)
{
cout << fl1.front() << "\t" << fl4.front() << endl;
fl1.pop_front();
fl4.pop_front();
}
//COPY ASSIGNMENT
fl2.push_front(1);
fl2.push_front(2);
fl3.push_front(3);
fl3.push_front(4);
fl3 = fl2;
cout << "\n\n";
for (int i = 2; i > 0; i--)
{
cout << fl2.front() << "\t" << fl3.front() << endl;
fl2.pop_front();
fl3.pop_front();
}
system("pause");
system("cls");
//***********************************************
fl1.push_front(10);
fl1.push_front(20);
fl1.push_front(30);
cout << "Tom? " << fl1.empty() << endl;
cout << fl1.ListAll();
fl1.pop_front();
cout << "\n\n" << fl1.ListAll();
fl1.clear();
cout << "\nTom nu?\n" << fl1.ListAll();
fl1.push_front(10);
fl1.push_front(20);
fl1.push_front(30);
cout << "\n\n\n";
for (auto it = fl1.begin(); it != fl1.end(); it++)
{
cout << it->value << endl;
}
for (auto &n : fl1)
{
cout << n.value << endl;
}
fl2.push_front(30);
fl2.push_front(40);
string asd = fl2.ListAll();
cout << "\nlngd: " << asd.length() << "\nsize: " << asd.size();
cout << "Sista elementet: ";
system("pause");
}
| true |
a1d23a8a68ef1cba2243e11e68bb38fa716878f2
|
C++
|
hophacker/algorithm_coding
|
/POJ/1503/6974649_AC_0MS_200K.cpp
|
UTF-8
| 589 | 2.59375 | 3 |
[] |
no_license
|
#include<iostream>
#include<string.h>
#include<fstream>
#include<memory.h>
using namespace std;
int main()
{
//freopen("in.txt", "r", stdin);
int a[110];
memset(a, 0, sizeof(a));
char s[110];
while (scanf("%s", s) && strcmp(s, "0"))
{
int len = strlen(s);
for (int i = 1; i <= len; i++)
a[i] += (s[len-i] - '0');
}
int jin = 0, t;
for (int i = 1; i <= 109; i++)
{
t = jin + a[i];
a[i] = t % 10;
jin = t /= 10;
}
t = 109;
while (a[t] == 0 && t >= 1) t--;
if (t == 0) cout << 0 << endl;
else
{
for (int i = t; i >= 1; i--) cout << a[i];
cout << endl;
}
}
| true |
8ed1e7aeff84ebf0b6ae8290c7b3eb4cdf85dfe9
|
C++
|
Fairbrook/Panteon
|
/Proyecto_Panteon/include/Propiedades.h
|
UTF-8
| 1,169 | 2.59375 | 3 |
[] |
no_license
|
#ifndef PROPIEDADES_H
#define PROPIEDADES_H
#include <iostream>
#include <string.h>
#include <Propietarios.h>
class Propiedades
{
public:
Propiedades();
virtual ~Propiedades();
void setTamano(float);
void setLimite_personas(short int);
void setTipo(const char*);
void setPredial(float);
void setN_propiedad(int);
void setPropietario(char *);
void setPropietario(Propietarios);
float getTamano();
short int getLimite_personas();
char* getTipo();
float getPredial();
int getN_propiedad();
Propietarios getPropietario();
void _read(char*);
char* _write();
bool isNull();
friend std::ostream& operator<< (std::ostream& os, const Propiedades& p);
friend std::istream& operator>> (std::istream& is, Propiedades& p);
Propiedades operator= (Propiedades);
bool operator== (Propiedades);
private:
float Tamano;
short int Limite_personas;
char Tipo[6];
float Predial;
int N_propiedad;
Propietarios propietario;
};
#endif // PROPIEDADES_H
| true |
00968bfda856785619a54459e32a2f5a2c379fab
|
C++
|
Sambor33/StudyMake
|
/TablMarshCIpher/description.cpp
|
UTF-8
| 2,362 | 2.96875 | 3 |
[] |
no_license
|
#include "MyClass.h"
#include "Exception.h"
MarshCipher::MarshCipher (const wstring &wkey)
{
MyException::CheckKey(wkey);
key=stoi(wkey);
}
int MarshCipher::StrNum (const wstring &text)
{
double dkey=key,dsize=text.size(),dstr;
dstr=ceil(dsize/dkey);
int str = dstr;
return str;
}
int MarshCipher::SpaceNum(const wstring&text)
{
int ost = text.size()%key;
int spacenum = key-ost;
if (spacenum == key) {
spacenum = 0;
}
return spacenum;
}
wstring MarshCipher::Encryct(const wstring&text)
{
MyException::CheckText(text,key);
wstring newtext = text;
int str = StrNum(text);
wchar_t **arr= new wchar_t*[str];
for (int k=0; k<str; k++) {
arr[k]=new wchar_t[key];
}
int t=0;
int size = text.size();
for (int i=0; i<str; i++) {
for (int k=0; k<key; k++,t++) {
if (i*key+k<size+1) {
arr[i][k] = text [t];
} else {
arr[i][k] = '\0';
}
}
}
int l=0;
for (int k=key-1; k>-1; k--) {
for (int i=0; i<str; i++,l++) {
if (arr[i][k]!='\0') {
newtext[l]=arr[i][k];
} else {
break;
}
}
}
for (int k=0; k<str; k++) {
delete [] arr[k];
}
delete [] arr;
return newtext;
}
wstring MarshCipher::Decryct(const wstring&text)
{
MyException::CheckText(text,key);
wstring newtext = text;
int str=StrNum(text);
SpaceNum(text);
int spacenum = SpaceNum(text);
wchar_t **arr= new wchar_t*[str];
for (int k =0; k<str; k++) {
arr[k]=new wchar_t[key];
}
int l=0;
for (int k=key-1; k>-1; k--) {
if (spacenum == 0) {
for (int i=0; i<str; i++,l++) {
arr[i][k]=text[l];
}
} else {
for (int i=0; i<str-1; i++,l++) {
arr[i][k]=text[l];
arr[str-1][k] = '\0';
}
spacenum--;
}
}
int t=0;
for (int i=0; i<str; i++) {
for (int k=0; k<key; k++,t++) {
if (arr[i][k]!='\0') {
newtext[t] = arr[i][k];
} else {
break;
}
}
}
for (int k=0; k<str; k++) {
delete [] arr[k];
}
delete [] arr;
return newtext;
}
| true |
e9e15d98677f90009c3e869c7d3c35cb36a9a361
|
C++
|
habara-k/ICPCLibrary
|
/test/geometry/2D_template/common_tangent.test.cpp
|
UTF-8
| 632 | 2.75 | 3 |
[] |
no_license
|
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/7/CGL_7_G"
#define ERROR "1e-5"
#include "../../../lib/geometry/2D_template.cpp"
int main()
{
cout << fixed << setprecision(10);
double x1, y1, r1, x2, y2, r2;
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;
vector<Line> lines = common_tangent(
Circle(Point(x1, y1), r1),
Circle(Point(x2, y2), r2));
vector<Point> points;
for (Line& l : lines) points.push_back(l.a);
sort(points.begin(), points.end());
for (Point& p : points) {
cout << p.real() << " " << p.imag() << endl;
}
return 0;
}
| true |
b4ba28cb2744c334c51b0b752c0bc91c070f9a3e
|
C++
|
i22bomui/IMC
|
/P1/practica1/practica1.cpp
|
UTF-8
| 2,459 | 2.953125 | 3 |
[] |
no_license
|
//============================================================================
// Introducción a los Modelos Computacionales
// Name : practica1.cpp
// Author : Pedro A. Gutiérrez
// Version :
// Copyright : Universidad de Córdoba
//============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <ctime> // Para cojer la hora time()
#include <cstdlib> // Para establecer la semilla srand() y generar números aleatorios rand()
#include <string.h>
#include <math.h>
#include <vector>
#include "imc/PerceptronMulticapa.h"
using namespace imc;
using namespace std;
int main(int argc, char **argv) {
// Procesar los argumentos de la línea de comandos
// Objeto perceptrón multicapa
PerceptronMulticapa mlp;
// Parámetros del mlp. Por ejemplo, mlp.dEta = valorQueSea;
// Lectura de datos de entrenamiento y test: llamar a mlp.leerDatos(...)
string fichero;
mlp.leerDatos(fichero);
// Inicializar vector topología
//int *topologia = new int[capas+2];
//topologia[0] = pDatosTrain->nNumEntradas;
//for(int i=1; i<(capas+2-1); i++)
// topologia[i] = neuronas;
//topologia[capas+2-1] = pDatosTrain->nNumSalidas;
// Inicializar red con vector de topología
//mlp.inicializar(capas+2,topologia);
// Semilla de los números aleatorios
/*
int semillas[] = {10,20,30,40,50};
double *erroresTest = new double[5];
double *erroresTrain = new double[5];
for(int i=0; i<5; i++){
cout << "**********" << endl;
cout << "SEMILLA " << semillas[i] << endl;
cout << "**********" << endl;
srand(semillas[i]);
mlp.ejecutarAlgoritmoOnline(pDatosTrain,pDatosTest,iteraciones,&(erroresTrain[i]),&(erroresTest[i]));
cout << "Finalizamos => Error de test final: " << erroresTest[i] << endl;
}
cout << "HEMOS TERMINADO TODAS LAS SEMILLAS" << endl;
double mediaErrorTest = 0, desviacionTipicaErrorTest = 0;
double mediaErrorTrain = 0, desviacionTipicaErrorTrain = 0;
// Calcular medias y desviaciones típicas de entrenamiento y test
cout << "INFORME FINAL" << endl;
cout << "*************" << endl;
cout << "Error de entrenamiento (Media +- DT): " << mediaErrorTrain << " +- " << desviacionTipicaErrorTrain << endl;
cout << "Error de test (Media +- DT): " << mediaErrorTest << " +- " << desviacionTipicaErrorTest << endl;
*/
return EXIT_SUCCESS;
}
| true |
bf64ad80a417c2467c75fc8a7885f2d26269438d
|
C++
|
drufino/minTLS
|
/tests/test_helpers.hpp
|
UTF-8
| 3,228 | 2.796875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
#ifndef test_helpers_hpp
#define test_helpers_hpp
#include <iostream>
#include <iomanip>
#include <cstring>
#ifndef _MSC_VER
#include <cxxabi.h>
#endif
#include <gtest/gtest.h>
#include <fstream>
#include <algorithm>
#include <stdint.h>
bool is_hex(char p);
std::ostream& operator<<(std::ostream & os, std::vector<uint8_t> const& x);
std::vector<uint8_t> convert_from_hex(char const *in);
#ifndef tf_tls_primitives_hpp
template<typename T>
std::vector<T> operator+(std::vector<T> const& lhs, std::vector<T> const& rhs)
{
std::vector<T> ret = lhs;
ret.reserve(ret.size() + rhs.size());
std::copy(rhs.begin(),rhs.end(),std::back_inserter(ret));
return ret;
}
template<typename T>
std::vector<T>& operator+=(std::vector<T> & lhs, std::vector<T> const& rhs)
{
lhs.insert(lhs.end(),rhs.begin(),rhs.end());
return lhs;
}
#endif
template<typename Visitor, typename T>
std::vector<T> load_cases(std::string const& fn, int max)
{
Visitor visitor;
std::ifstream in_file(fn.c_str());
char buf[1024];
for (;;)
{
buf[0] = buf[sizeof(buf)-1] = '\0';
if (!in_file.getline(buf, sizeof(buf) - 1, '\n'))
break;
if (strlen(buf) == 0) continue;
if (buf[0] == '#' || buf[0] == '\r' || buf[0] == '\n')
continue;
if (buf[0] == '[')
{
std::string mode(buf+1);
if (mode[mode.length()-1] == '\r' || mode[mode.length()-1] == '\n')
{
mode.resize(mode.length()-1);
}
if (mode[mode.length()-1] == ']')
{
mode.resize(mode.length()-1);
}
visitor.visit_mode(mode);
continue;
}
char *c_equals = strchr(buf,'=');
if (c_equals > buf)
{
*(c_equals - 1) = '\0';
std::string lhs(buf);
std::string rhs(c_equals+2);
if (rhs[rhs.length()-1] == '\r' || rhs[rhs.length() -1] == '\n')
{
rhs.resize(rhs.length()-1);
}
visitor.visit(lhs,rhs);
}
}
std::vector<T> cases = visitor.get_cases();
size_t cnt = max < cases.size() ? max : cases.size();
return std::vector<T>(cases.begin(),cases.begin()+cnt);
}
class MinimalistPrinter : public ::testing::EmptyTestEventListener
{
// Called before a test starts.
virtual void OnTestStart(const ::testing::TestInfo& test_info);
// Called after a failed assertion or a SUCCEED() invocation.
virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result);
// Called after a test ends.
virtual void OnTestEnd(const ::testing::TestInfo& test_info);
};
template<typename T, size_t size>
::testing::AssertionResult ArraysMatch(const T (&expected)[size],
const T (&actual)[size]){
for (size_t i(0); i < size; ++i){
if (expected[i] != actual[i]){
return ::testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
#endif
| true |
aba7930cb8e4d044733bce8534eeeb85d3185b03
|
C++
|
sys-bio/Libstructural
|
/dependencies/libsbml-vs2017-release-32/include/sbml/Compartment.h
|
UTF-8
| 94,920 | 2.640625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
/**
* @file Compartment.h
* @brief Definitions of Compartment and ListOfCompartments
* @author Ben Bornstein
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2017 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*
* @class Compartment
* @sbmlbrief{core} An SBML compartment, where species are located.
*
* A compartment in SBML represents a bounded space in which species are
* located. Compartments do not necessarily have to correspond to actual
* structures inside or outside of a biological cell.
*
* It is important to note that although compartments are optional in the
* overall definition of Model, every species in an SBML model must be
* located in a compartment. This in turn means that if a model defines
* any species, the model must also define at least one compartment. The
* reason is simply that species represent physical things, and therefore
* must exist @em somewhere. Compartments represent the @em somewhere.
*
* Compartment has one required attribute, "id", to give the compartment a
* unique identifier by which other parts of an SBML model definition can
* refer to it. A compartment can also have an optional "name" attribute
* of type @c string. Identifiers and names must be used according to the
* guidelines described in the SBML specifications.
*
* Compartment also has an optional attribute "spatialDimensions" that is
* used to indicate the number of spatial dimensions possessed by the
* compartment. Most modeling scenarios involve compartments with integer
* values of "spatialDimensions" of @c 3 (i.e., a three-dimensional
* compartment, which is to say, a volume), or 2 (a two-dimensional
* compartment, a surface), or @c 1 (a one-dimensional compartment, a
* line). In SBML Level 3, the type of this attribute is @c double,
* there are no restrictions on the permitted values of the
* "spatialDimensions" attribute, and there are no default values. In SBML
* Level 2, the value must be a positive @c integer, and the default
* value is @c 3; the permissible values in SBML Level 2 are @c 3, @c
* 2, @c 1, and @c 0 (for a point).
*
* Another optional attribute on Compartment is "size", representing the @em
* initial total size of that compartment in the model. The "size" attribute
* must be a floating-point value and may represent a volume (if the
* compartment is a three-dimensional one), or an area (if the compartment is
* two-dimensional), or a length (if the compartment is one-dimensional).
* There is no default value of compartment size in SBML Level 2 or
* Level 3. In particular, a missing "size" value <em>does not imply
* that the compartment size is 1</em>. (This is unlike the definition of
* compartment "volume" in SBML Level 1.) When the compartment's
* "spatialDimensions" attribute does not have a value of @c 0, a missing
* value of "size" for a given compartment signifies that the value either is
* unknown, or to be obtained from an external source, or determined by an
* InitialAssignment, AssignmentRule, AlgebraicRule or RateRule
* @if conly structure @else object@endif@~ elsewhere in the model. In SBML
* Level 2, there are additional special requirements on the values of
* "size"; we discuss them in a <a href="#comp-l2">separate section
* below</a>.
*
* The units associated with a compartment's "size" attribute value may be
* set using the optional attribute "units". The rules for setting and
* using compartment size units differ between SBML Level 2 and
* Level 3, and are discussed separately below.
*
* Finally, the Compartment attribute named "constant" is used to
* indicate whether the compartment's size stays constant after simulation
* begins. A value of @c true indicates the compartment's "size" cannot be
* changed by any other construct except InitialAssignment; a value of @c
* false indicates the compartment's "size" can be changed by other
* constructs in SBML. In SBML Level 2, there is an additional
* explicit restriction that if "spatialDimensions"=@c "0", the value
* cannot be changed by InitialAssignment either. Further, in
* Level 2, "constant" is optional, and has a default value of @c true. In SBML
* Level 3, there is no default value for the "constant" attribute,
* and it is required.
*
*
* @section comp-l2 Additional considerations in SBML Level 2
*
* In SBML Level 2, the default units of compartment size, and the kinds
* of units allowed as values of the attribute "units", interact with the
* number of spatial dimensions of the compartment. The value of the "units"
* attribute of a Compartment @if conly structure @else object@endif@~ must
* be one of the base units (see Unit), or the predefined unit identifiers @c
* volume, @c area, @c length or @c dimensionless, or a new unit defined by a
* UnitDefinition @if conly structure @else object@endif@~ in the enclosing
* Model, subject to the restrictions detailed in the following table:
*
* <table border="0" class="centered text-table width80 normal-font alt-row-colors"
* style="padding-bottom: 0.5em">
* <caption class="top-caption">Restrictions on values permitted for
* compartment <code>size</code> and <code>units</code> attributes.</caption>
* <tr>
* <th align="left" valign="bottom">
* Value of<br><code>spatialDimensions</code>
* </th>
* <th align="left" valign="bottom">
* <code>size</code><br>allowed?
* </th>
* <th align="left" valign="bottom">
* <code>units</code><br>allowed?
* </th>
* <th align="left" valign="bottom">
* Allowable kinds of units
* </th>
* <th align="left" valign="bottom">
* Default value of attribute <code>units</code>
* </th>
* </tr>
* <tr>
* <td><code>3</code></td>
* <td>yes</td>
* <td>yes</td>
* <td>units of volume, or <code>dimensionless</code></td>
* <td><code>volume</code></td>
* </tr>
* <tr>
* <td><code>2</code></td>
* <td>yes</td>
* <td>yes</td>
* <td>units of area, or <code>dimensionless</code></td>
* <td><code>area</code></td>
* </tr>
* <tr>
* <td><code>1</code></td>
* <td>yes</td>
* <td>yes</td>
* <td>units of length, or <code>dimensionless</code></td>
* <td><code>length</code></td>
* </tr>
* <tr>
* <td><code>0</code></td>
* <td>no</td>
* <td>no</td>
* <td>(no units allowed)</td>
* <td></td>
* </tr>
* </tr>
* </table>
*
* In SBML Level 2, the units of the compartment size, as defined by the
* "units" attribute or (if "units" is not set) the default value listed in
* the table above, are used in the following ways when the compartment has
* a "spatialDimensions" value greater than @c 0:
* <ul>
* <li> The value of the "units" attribute is used as the units of the
* compartment identifier when the identifier appears as a numerical
* quantity in a mathematical formula expressed in MathML.
*
* <li> The @c math element of an AssignmentRule or InitialAssignment
* referring to this compartment @em must (in Level 2 Versions 1-3)
* or @em should (in Level 2 Version 4) have identical units.
*
* <li> In RateRule objects that set the rate of change of the compartment's
* size, the units of the rule's @c math element @em must (in Level 2
* Versions 1–3) or @em should (in Level 2 Version 4) be identical to the
* compartment's units (whether defined by the "units" attribute or by taking the
* default value from the Model) divided by the default @em time units.
* (In other words, the units for the rate of change of compartment size
* are <em>compartment size</em>/<em>time</em> units.
*
* <li> When a Species is to be treated in terms of concentrations or
* density, the units of the spatial size portion of the concentration
* value (i.e., the denominator in the units formula @em substance/@em
* size) are those indicated by the value of the "units" attribute on the
* compartment in which the species is located.
* </ul>
*
* Compartments with "spatialDimensions"=@c 0 require special treatment in
* this framework. As implied above, the "size" attribute must not have a
* value on an SBML Level 2 Compartment
* @if conly structure @else object@endif@~ if the "spatialDimensions"
* attribute has a value of @c 0. An additional related restriction is that
* the "constant" attribute must default to or be set to @c true if the value
* of the "spatialDimensions" attribute is @c 0, because a zero-dimensional
* compartment cannot ever have a size.
*
* If a compartment has no size or dimensional units, how should such a
* compartment's identifier be interpreted when it appears in mathematical
* formulas? The answer is that such a compartment's identifier should not
* appear in mathematical formulas in the first place---it has no
* value, and its value cannot change. Note also that a zero-dimensional
* compartment is a point, and species located at points can only be
* described in terms of amounts, not spatially-dependent measures such as
* concentration. Since SBML KineticLaw formulas are already in terms of
* @em substance/@em time and not (say) @em concentration/@em time, volume
* or other factors in principle are not needed for species located in
* zero-dimensional compartments.
*
* Finally, in SBML Level 2 Versions 2–4, each compartment in a
* model may optionally be designated as belonging to a particular
* compartment @em type. The optional attribute "compartmentType" is used
* identify the compartment type represented by the Compartment structure.
* The "compartmentType" attribute's value must be the identifier of a
* CompartmentType instance defined in the model. If the "compartmentType"
* attribute is not present on a particular compartment definition, a
* unique virtual compartment type is assumed for that compartment, and no
* other compartment can belong to that compartment type. The values of
* "compartmentType" attributes on compartments have no effect on the
* numerical interpretation of a model. Simulators and other numerical
* analysis software may ignore "compartmentType" attributes. The
* "compartmentType" attribute and the CompartmentType
* @if conly structures @else class of objects@endif@~ are
* not present in SBML Level 3 Core nor in SBML Level 1.
*
*
* @section comp-l3 Additional considerations in SBML Level 3
*
* One difference between SBML Level 3 and lower Levels of SBML is
* that there are no restrictions on the permissible values of the
* "spatialDimensions" attribute, and there is no default value defined for
* the attribute. The value of "spatialDimensions" does not have to be an
* integer, either; this is to allow for the possibility of representing
* structures with fractal dimensions.
*
* The number of spatial dimensions possessed by a compartment cannot enter
* into mathematical formulas, and therefore cannot directly alter the
* numerical interpretation of a model. However, the value of
* "spatialDimensions" @em does affect the interpretation of the units
* associated with a compartment's size. Specifically, the value of
* "spatialDimensions" is used to select among the Model attributes
* "volumeUnits", "areaUnits" and "lengthUnits" when a Compartment
* @if conly object @else structure@endif@~ does not define a value for its
* "units" attribute.
*
* The "units" attribute may be left unspecified for a given compartment in a
* model; in that case, the compartment inherits the unit of measurement
* specified by one of the attributes on the enclosing Model
* @if conly structure @else object@endif@~ instance. The applicable
* attribute on Model depends on the value of the compartment's
* "spatialDimensions" attribute; the relationship is shown in the table
* below. If the Model @if conly structure @else object@endif@~ does not
* define the relevant attribute ("volumeUnits", "areaUnits" or
* "lengthUnits") for a given "spatialDimensions" value, the unit associated
* with that Compartment @if conly structure @else object@endif's size is
* undefined. If a given Compartment's "units" are left unset and
* the "spatialDimensions" either has a value other than @c 1, @c 2, or
* @c 3 or is left unset itself (as it has no default value),
* then no unit can be chosen from among the Model's "volumeUnits",
* "areaUnits" or "lengthUnits" attributes (even if the Model instance
* provides values for those attributes), because there is no basis to select
* between them.
* Leaving the units of compartments' sizes undefined in an SBML model does
* not render the model invalid; however, as a matter of best practice, we
* strongly recommend that all models specify the units of measurement for
* all compartment sizes.
*
* <table border="0" class="centered text-table width80 normal-font alt-row-colors"
* style="padding-bottom: 0.5em">
* <caption class="top-caption">Interpretation of the Compartment "units" attribute.</caption>
* <tr>
* <th align="left" valign="bottom">
* Value of attribute<br>"spatialDimensions"
* </th>
* <th align="left" valign="bottom">
* Attribute of Model used<br>for inheriting the unit
* </th>
* <th align="left" valign="bottom">
* Recommended candidate units
* </th>
* </tr>
* <tr>
* <td><code>3</code></td>
* <td>"volumeUnits"</td>
* <td>units of volume, or <code>dimensionless</code></td>
* </tr>
* <tr>
* <td><code>2</code></td>
* <td>"areaUnits"</td>
* <td>units of area, or <code>dimensionless</code></td>
* </tr>
* <tr>
* <td><code>1</code></td>
* <td>"lengthUnits"</td>
* <td>units of length, or <code>dimensionless</code></td>
* </tr>
* <tr>
* <td><em>other</em></td>
* <td><em>no units inherited</em></td>
* <td><em>no specific recommendations</em></td>
* </tr>
* </tr>
* </table>
*
* The unit of measurement associated with a compartment's size, as defined
* by the "units" attribute or (if "units" is not set) the inherited value
* from Model according to the table above, is used in the following ways:
*
* <ul>
*
* <li> When the identifier of the compartment appears as a numerical
* quantity in a mathematical formula expressed in MathML, it represents
* the size of the compartment, and the unit associated with the size is
* the value of the "units" attribute.
*
* <li> When a Species is to be treated in terms of concentrations or
* density, the unit associated with the spatial size portion of the
* concentration value (i.e., the denominator in the formula
* <em>amount</em>/<em>size</em>) is specified by the value of the "units"
* attribute on the compartment in which the species is located.
*
* <li> The "math" elements of AssignmentRule, InitialAssignment and
* EventAssignment @if conly structures @else objects@endif@~ setting the
* value of the compartment size should all have the same units as the unit
* associated with the compartment's size.
*
* <li> In a RateRule @if conly structure @else object@endif@~ that defines a
* rate of change for a compartment's size, the unit of the rule's "math"
* element should be identical to the compartment's "units" attribute divided
* by the model-wide unit of <em>time</em>. (In other words, {<em>unit of
* compartment size</em>}/{<em>unit of time</em>}.)
*
* </ul>
*
*
* @section comp-other Other aspects of Compartment
*
* In SBML Level 1 and Level 2, Compartment has an optional
* attribute named "outside", whose value can be the identifier of another
* Compartment @if conly structure @else object@endif@~ defined in the
* enclosing Model @if conly structure @else object@endif@~. Doing so means
* that the other compartment contains it or is outside of it. This enables
* the representation of simple topological relationships between
* compartments, for those simulation systems that can make use of the
* information (e.g., for drawing simple diagrams of compartments). It is
* worth noting that in SBML, there is no relationship between compartment
* sizes when compartment positioning is expressed using the "outside"
* attribute. The size of a given compartment does not in any sense include
* the sizes of other compartments having it as the value of their "outside"
* attributes. In other words, if a compartment @em B has the identifier of
* compartment @em A as its "outside" attribute value, the size of @em A does
* not include the size of @em B. The compartment sizes are separate.
*
* In Level 2, there are two restrictions on the "outside" attribute.
* First, because a compartment with "spatialDimensions" of @c 0 has no
* size, such a compartment cannot act as the container of any other
* compartment @em except compartments that @em also have
* "spatialDimensions" values of @c 0. Second, the directed graph formed
* by representing Compartment structures as vertexes and the "outside"
* attribute values as edges must be acyclic. The latter condition is
* imposed to prevent a compartment from being contained inside itself. In
* the absence of a value for "outside", compartment definitions in SBML
* Level 2 do not have any implied spatial relationships between each
* other.
*
*
* <!-- ------------------------------------------------------------------- -->
* @class ListOfCompartments
* @sbmlbrief{core} A list of Compartment objects.
*
* @copydetails doc_what_is_listof
*/
/**
* <!-- ~ ~ ~ ~ ~ Start of common documentation strings ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
* The following text is used as common documentation blocks copied multiple
* times elsewhere in this file. The use of @class is a hack needed because
* Doxygen's @copydetails command has limited functionality. Symbols
* beginning with "doc_" are marked as ignored in our Doxygen configuration.
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ -->
*
* @class doc_compartment_units
*
* @par
* Compartments in SBML have an attribute ("units") for declaring the
* units of measurement intended for the value of the compartment's size. In
* the absence of a value given for this attribute, the units are inherited
* from values either defined on the enclosing Model (in SBML Level 3)
* or in defaults (in SBML Level 2). This method returns a
* @if conly UnitDefinition_t structure @else UnitDefinition object@endif@~
* based on how this compartment's units are interpreted according to the
* relevant SBML guidelines, or it returns @c NULL if no units have been
* declared and no defaults are defined by the relevant SBML specification.
*
* Note that unit declarations for
* @if conly Compartment_t structures @else Compartment objects @endif@~
* are specified in terms of the @em identifier of a unit,
* but @em this method returns @if conly a structure @else an object @endif,
* not a unit identifier. It does this by constructing an appropriate
* @if conly UnitDefinition_t structure @else UnitDefinition object@endif. For
* SBML Level 2 models, it will do this even when the value of the
* "units" attribute is one of the special SBML Level 2 unit identifiers
* @c "substance", @c "volume", @c "area", @c "length" or @c "time". Callers
* may find this useful in conjunction with the helper methods provided by
* the @if conly UnitDefinition_t structure @else UnitDefinition
* class@endif@~ for comparing different UnitDefinition objects.
*
* <!-- ------------------------------------------------------------------- -->
* @class doc_compartment_both_size_and_volume
*
* @par
* In SBML Level 1, compartments are always three-dimensional
* constructs and only have volumes, whereas in SBML Level 2 and higher,
* compartments may be other than three-dimensional, and therefore the
* "volume" attribute is named "size" in Level 2 and above. LibSBML
* provides both @if conly Compartment_getSize() and Compartment_getVolume()
* @else getSize() and getVolume()@endif@~
* for easier support of different SBML Levels.
*
* <!-- ------------------------------------------------------------------- -->
* @class doc_note_compartment_volume
*
* @note The attribute "volume" only exists by that name in SBML
* Level 1. In Level 2 and above, the equivalent attribute is
* named "size". In SBML Level 1, a compartment's volume has a default
* value (@c 1.0) and therefore methods such as
* @if conly Compartment_isSetVolume() @else isSetVolume()@endif@~
* will always return @c true for a Level 1 model. In Level 2, a
* compartment's size (the equivalent of SBML Level 1's "volume") is
* optional and has no default value, and therefore may or may not be set.
*
* <!-- ------------------------------------------------------------------- -->
* @class doc_note_spatial_dimensions_as_double
*
* @note In SBML Level 3, the data type of the "spatialDimensions"
* attribute is @c double, whereas in Level 2, it is @c integer. To
* avoid backward compatibility issues, libSBML provides two separate methods
* for obtaining the value as either an integer or a type @c double, for
* models where it is relevant.
*
* <!-- ------------------------------------------------------------------- -->
* @class doc_note_unit_analysis_depends_on_model
*
* @note The libSBML system for unit analysis depends on the model as a
* whole. In cases where the
* @if conly Compartment_t structure @else Compartment object@endif@~ has not
* yet been added to a model, or the model itself is incomplete, unit
* analysis is not possible, and consequently this method will return @c
* NULL.
*/
#ifndef Compartment_h
#define Compartment_h
#include <sbml/common/extern.h>
#include <sbml/common/sbmlfwd.h>
#ifndef LIBSBML_USE_STRICT_INCLUDES
#include <sbml/annotation/RDFAnnotation.h>
#endif
#include <sbml/common/operationReturnValues.h>
#ifdef __cplusplus
#include <string>
#include <sbml/SBase.h>
#include <sbml/ListOf.h>
LIBSBML_CPP_NAMESPACE_BEGIN
class SBMLVisitor;
class LIBSBML_EXTERN Compartment : public SBase
{
public:
/**
* Creates a new Compartment object using the given SBML @p level and @p
* version values.
*
* @param level an unsigned int, the SBML Level to assign to this Compartment.
*
* @param version an unsigned int, the SBML Version to assign to this
* Compartment.
*
* @copydetails doc_throw_exception_lv
*
* @copydetails doc_note_setting_lv
*/
Compartment (unsigned int level, unsigned int version);
/**
* Creates a new Compartment object using the given SBMLNamespaces object
* @p sbmlns.
*
* @copydetails doc_what_are_sbmlnamespaces
*
* It is worth emphasizing that although this constructor does not take an
* identifier argument, in SBML Level 2 and beyond, the "id"
* (identifier) attribute of a Compartment object is required to have a
* value. Thus, callers are cautioned to assign a value after calling this
* constructor. Setting the identifier can be accomplished using the
* method @if java Compartment::setId(String id)@else setId()@endif.
*
* @param sbmlns an SBMLNamespaces object.
*
* @copydetails doc_throw_exception_namespace
*
* @copydetails doc_note_setting_lv
*/
Compartment (SBMLNamespaces* sbmlns);
/**
* Destroys this Compartment object.
*/
virtual ~Compartment ();
/**
* Copy constructor.
*
* This creates a copy of a Compartment object.
*
* @param orig the Compartment instance to copy.
*/
Compartment(const Compartment& orig);
/**
* Assignment operator for Compartment.
*
* @param rhs the object whose values are used as the basis of the
* assignment.
*/
Compartment& operator=(const Compartment& rhs);
/** @cond doxygenLibsbmlInternal */
/**
* Accepts the given SBMLVisitor for this instance of Compartment.
*
* @param v the SBMLVisitor instance to be used.
*
* @return the result of calling <code>v.visit()</code>, which indicates
* whether the Visitor would like to visit the next Compartment object in the
* list of compartments within which this Compartment object is embedded (i.e.,
* the ListOfCompartments in the parent Model).
*/
virtual bool accept (SBMLVisitor& v) const;
/** @endcond */
/**
* Creates and returns a deep copy of this Compartment object.
*
* @return the (deep) copy of this Compartment object.
*/
virtual Compartment* clone () const;
/**
* Initializes the fields of this Compartment object to "typical" default
* values.
*
* The SBML Compartment component has slightly different aspects and
* default attribute values in different SBML Levels and Versions.
* This method sets the values to certain common defaults, based
* mostly on what they are in SBML Level 2. Specifically:
*
* @li Sets attribute "spatialDimensions" to @c 3
* @li Sets attribute "constant" to @c true
* @li (Applies to Level 1 models only) Sets attribute "volume" to @c 1.0
* @li (Applies to Level 3 models only) Sets attribute "units" to @c litre
*/
void initDefaults ();
/**
* Returns the value of the "id" attribute of this Compartment.
*
* @note Because of the inconsistent behavior of this function with
* respect to assignments and rules, it is now recommended to
* use the getIdAttribute() function instead.
*
* @copydetails doc_id_attribute
*
* @return the id of this Compartment.
*
* @see getIdAttribute()
* @see setIdAttribute(const std::string& sid)
* @see isSetIdAttribute()
* @see unsetIdAttribute()
*/
virtual const std::string& getId () const;
/**
* Returns the value of the "name" attribute of this Compartment object.
*
* @copydetails doc_get_name
*/
virtual const std::string& getName () const;
/**
* Get the value of the "compartmentType" attribute of this Compartment
* object.
*
* @return the value of the "compartmentType" attribute of this
* Compartment object as a string.
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @see isSetCompartmentType()
* @see setCompartmentType(@if java String@endif)
* @see unsetCompartmentType()
*/
const std::string& getCompartmentType () const;
/**
* Get the number of spatial dimensions of this Compartment object.
*
* @return the value of the "spatialDimensions" attribute of this
* Compartment object as an unsigned integer.
*
* @copydetails doc_note_spatial_dimensions_as_double
*
* @see getSpatialDimensionsAsDouble()
* @see setSpatialDimensions(@if java unsigned int@endif)
* @see isSetSpatialDimensions()
* @see unsetSpatialDimensions()
*/
unsigned int getSpatialDimensions () const;
/**
* Get the number of spatial dimensions of this Compartment object,
* as a double.
*
* @return the value of the "spatialDimensions" attribute of this
* Compartment object as a double, or @c NaN if this model is not in SBML
* Level 3 format.
*
* @copydetails doc_note_spatial_dimensions_as_double
*
* @see getSpatialDimensions()
* @see setSpatialDimensions(@if java unsigned int@endif)
* @see isSetSpatialDimensions()
* @see unsetSpatialDimensions()
*/
double getSpatialDimensionsAsDouble () const;
/**
* Get the size of this Compartment object.
*
* @copydetails doc_compartment_both_size_and_volume
*
* @return the value of the "size" attribute ("volume" in Level 1) of
* this Compartment object as a floating-point number.
*
* @note This method is identical to
* @if java Compartment::getVolume()@else getVolume()@endif.
*
* @see getVolume()
* @see isSetSize()
* @see setSize(@if java double@endif)
* @see unsetSize()
*/
double getSize () const;
/**
* Get the volume of this Compartment object.
*
* @copydetails doc_compartment_both_size_and_volume
*
* @return the value of the "volume" attribute ("size" in Level 2) of
* this Compartment object, as a floating-point number.
*
* @copydetails doc_note_compartment_volume
*
* @note This method is identical to
* @if java Compartment::getSize()@else getSize()@endif.
*
* @see getSize()
* @see isSetVolume()
* @see setVolume(@if java double@endif)
* @see unsetVolume()
*/
double getVolume () const;
/**
* Get the units of this Compartment object's size.
*
* The value of an SBML compartment's "units" attribute establishes the
* unit of measurement associated with the compartment's size.
*
* @return the value of the "units" attribute of this Compartment object,
* as a string. An empty string indicates that no units have been assigned
* to the value of the size.
*
* @copydetails doc_note_unassigned_unit_are_not_a_default
*
* @see isSetUnits()
* @see setUnits(@if java String@endif)
* @see unsetUnits()
*/
const std::string& getUnits () const;
/**
* Get the identifier, if any, of the Compartment object that is designated
* as being outside of @em this one.
*
* @return the value of the "outside" attribute of this Compartment object.
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @see isSetOutside()
* @see setOutside(@if java String@endif)
* @see unsetOutside()
*/
const std::string& getOutside () const;
/**
* Get the value of the "constant" attribute of this Compartment object.
*
* @return @c true if this Compartment object's size is flagged as being
* constant, @c false otherwise.
*
* @see isSetConstant()
* @see setConstant(@if java bool@endif)
*/
bool getConstant () const;
/**
* Predicate returning @c true if this Compartment object's "id" attribute
* is set.
*
* @copydetails doc_isset_id
*/
virtual bool isSetId () const;
/**
* Predicate returning @c true if this Compartment object's "name"
* attribute is set.
*
* @copydetails doc_isset_name
*/
virtual bool isSetName () const;
/**
* Predicate returning @c true if this Compartment object's
* "compartmentType" attribute is set.
*
* @return @c true if the "compartmentType" attribute of this Compartment
* is set, @c false otherwise.
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @see setCompartmentType(@if java String@endif)
* @see getCompartmentType()
* @see unsetCompartmentType()
*/
bool isSetCompartmentType () const;
/**
* Predicate returning @c true if this Compartment object's "size"
* attribute is set.
*
* This method is similar but not identical to
* @if java Compartment::isSetVolume()@else isSetVolume()@endif. The latter
* should be used in the context of SBML Level 1 models instead of
* @if java Compartment::isSetSize()@else isSetSize()@endif@~
* because @if java Compartment::isSetVolume()@else isSetVolume()@endif@~
* performs extra processing to take into account the difference in
* default values between SBML Levels 1 and 2.
*
* @return @c true if the "size" attribute ("volume" in Level 2) of
* this Compartment object is set, @c false otherwise.
*
* @see isSetVolume()
* @see setSize(@if java double@endif)
* @see getSize()
* @see unsetSize()
*/
bool isSetSize () const;
/**
* Predicate returning @c true if this Compartment object's "volume"
* attribute is set.
*
* This method is similar but not identical to
* @if java Compartment::isSetSize()@else isSetSize()@endif. The latter
* should not be used in the context of SBML Level 1 models because the
* present method performs extra processing to take into account
* the difference in default values between SBML Levels 1 and 2.
*
* @return @c true if the "volume" attribute ("size" in Level 2 and
* above) of this Compartment object is set, @c false otherwise.
*
* @copydetails doc_note_compartment_volume
*
* @see isSetSize()
* @see getVolume()
* @see setVolume(@if java double@endif)
* @see unsetVolume()
*/
bool isSetVolume () const;
/**
* Predicate returning @c true if this Compartment object's "units"
* attribute is set.
*
* @return @c true if the "units" attribute of this Compartment object is
* set, @c false otherwise.
*
* @copydetails doc_note_unassigned_unit_are_not_a_default
*
* @see setUnits(@if java String@endif)
* @see getUnits()
* @see unsetUnits()
*/
bool isSetUnits () const;
/**
* Predicate returning @c true if this Compartment object's "outside"
* attribute is set.
*
* @return @c true if the "outside" attribute of this Compartment object is
* set, @c false otherwise.
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @see getOutside()
* @see setOutside(@if java String@endif)
* @see unsetOutside()
*/
bool isSetOutside () const;
/**
* Predicate returning @c true if this Compartment object's
* "spatialDimensions" attribute is set.
*
* @return @c true if the "spatialDimensions" attribute of this
* Compartment object is set, @c false otherwise.
*
* @see getSpatialDimensions()
* @see setSpatialDimensions(@if java unsigned int@endif)
* @see unsetSpatialDimensions()
*/
bool isSetSpatialDimensions () const;
/**
* Predicate returning @c true if this Compartment object's "constant"
* attribute is set.
*
* @return @c true if the "constant" attribute of this Compartment object is
* set, @c false otherwise.
*
* @see getConstant()
* @see setConstant(@if java bool@endif)
*/
bool isSetConstant () const;
/**
* Sets the value of the "id" attribute of this Compartment object.
*
* The string @p sid is copied.
*
* @copydetails doc_id_attribute
*
* @param sid the string to use as the identifier of this Compartment object. If
* the string is @c NULL, this method will return
* @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
*
* @see getId()
* @see unsetId()
* @see isSetId()
*/
virtual int setId(const std::string& sid);
/**
* Sets the value of the "name" attribute of this Compartment object.
*
* @copydetails doc_set_name
*/
virtual int setName (const std::string& name);
/**
* Sets the "compartmentType" attribute of this Compartment object.
*
* @param sid the identifier of a CompartmentType object defined elsewhere
* in this Model. If the string is @c NULL, this method will return
* @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @see isSetCompartmentType()
* @see getCompartmentType()
* @see unsetCompartmentType()
*/
int setCompartmentType (const std::string& sid);
/**
* Sets the "spatialDimensions" attribute of this Compartment object.
*
* @param value an unsigned integer indicating the number of dimensions
* of this compartment.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @see getSpatialDimensions()
* @see isSetSpatialDimensions()
* @see unsetSpatialDimensions()
*/
int setSpatialDimensions (unsigned int value);
/**
* Sets the "spatialDimensions" attribute of this Compartment object as a double.
*
* @param value a double indicating the number of dimensions
* of this compartment.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @see getSpatialDimensions()
* @see isSetSpatialDimensions()
* @see unsetSpatialDimensions()
*/
int setSpatialDimensions (double value);
/**
* Sets the "size" attribute (or "volume" in SBML Level 1) of this
* Compartment object.
*
* @param value a @c double representing the size of this compartment
* instance in whatever units are in effect for the compartment.
*
* @copydetails doc_returns_one_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
*
* @note This method is identical to
* @if java Compartment::setVolume(double value)@else setVolume()@endif.
*
* @see setVolume(@if java double@endif)
* @see getSize()
* @see isSetSize()
* @see unsetSize()
*/
int setSize (double value);
/**
* Sets the "volume" attribute (or "size" in SBML Level 2) of this
* Compartment object.
*
* This method is identical to
* @if java Compartment::setSize(double value)@else setSize()@endif@~
* and is provided for compatibility between SBML Level 1 and
* higher Levels of SBML.
*
* @param value a @c double representing the volume of this compartment
* instance in whatever units are in effect for the compartment.
*
* @copydetails doc_returns_one_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
*
* @copydetails doc_note_compartment_volume
*
* @see setSize(@if java double@endif)
* @see getVolume()
* @see isSetVolume()
* @see unsetVolume()
*/
int setVolume (double value);
/**
* Sets the "units" attribute of this Compartment object.
*
* @param sid the identifier of the defined units to use. If @p sid is @c
* NULL, then this method will return
* @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
*
* @see isSetUnits()
* @see getUnits()
* @see unsetUnits()
*/
int setUnits (const std::string& sid);
/**
* Sets the "outside" attribute of this Compartment object.
*
* @param sid the identifier of a compartment that encloses this one. If @p
* sid is @c NULL, then this method will return
* @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @see isSetOutside()
* @see getOutside()
* @see unsetOutside()
*/
int setOutside (const std::string& sid);
/**
* Sets the value of the "constant" attribute of this Compartment object.
*
* @param value a boolean indicating whether the size/volume of this
* compartment should be considered constant (@c true) or variable
* (@c false).
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @see isSetConstant()
* @see getConstant()
*/
int setConstant (bool value);
/**
* @copydoc doc_renamesidref_common
*/
virtual void renameSIdRefs(const std::string& oldid, const std::string& newid);
/**
* @copydoc doc_renameunitsidref_common
*/
virtual void renameUnitSIdRefs(const std::string& oldid, const std::string& newid);
/**
* Unsets the value of the "name" attribute of this Compartment object.
*
* @copydetails doc_unset_name
*/
virtual int unsetName ();
/**
* Unsets the value of the "compartmentType" attribute of this Compartment object.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @see setCompartmentType(@if java String@endif)
* @see isSetCompartmentType()
* @see getCompartmentType()
*/
int unsetCompartmentType ();
/**
* Unsets the value of the "constant" attribute of this Compartment object.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*
* @see isSetConstant()
* @see setConstant(@if java bool@endif)
* @see getConstant()
*/
int unsetConstant ();
/**
* Unsets the value of the "size" attribute of this Compartment object.
*
* In SBML Level 1, a compartment's volume has a default value (@c
* 1.0) and therefore <em>should always be set</em>. Calling this method
* on a Level 1 model resets the value to @c 1.0 rather than actually
* unsetting it. In Level 2, a compartment's "size" is optional with
* no default value, and unsetting it will result in the compartment having
* no defined size.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*
* @note This method is identical to
* @if java Compartment::unsetVolume()@else unsetVolume()@endif.
*
* @see unsetVolume()
* @see getSize()
* @see isSetSize()
* @see setSize(@if java double@endif)
*/
int unsetSize ();
/**
* Unsets the value of the "volume" attribute of this Compartment object.
*
* This method is identical to
* @if java Compartment::unsetSize()@else unsetSize()@endif. Please refer
* to that method's documentation for more information about its behavior.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*
* @copydetails doc_note_compartment_volume
*
* @see unsetSize()
* @see getVolume()
* @see setVolume(@if java double@endif)
* @see isSetVolume()
*/
int unsetVolume ();
/**
* Unsets the value of the "units" attribute of this Compartment object.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*
* @see isSetUnits()
* @see setUnits(@if java String@endif)
* @see getUnits()
*/
int unsetUnits ();
/**
* Unsets the value of the "outside" attribute of this Compartment object.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @see isSetOutside()
* @see getOutside()
* @see setOutside(@if java String@endif)
*/
int unsetOutside ();
/**
* Unsets the value of the "spatialDimensions" attribute of this
* Compartment object.
*
* In SBML Levels prior to Level 3, compartments must always have a
* value for the number of dimensions. Consequently, calling this method
* on a model of SBML Level 1–2 will result in a return value of
* @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @note This function is only valid for SBML Level 3.
*
* @see getSpatialDimensions()
* @see isSetSpatialDimensions()
* @see setSpatialDimensions(@if java unsigned int@endif)
*/
int unsetSpatialDimensions ();
/**
* Constructs and returns a UnitDefinition that corresponds to the units
* of this Compartment object's designated size.
*
* @copydetails doc_compartment_units
*
* @return a UnitDefinition that expresses the units of this
* Compartment object, or @c NULL if one cannot be constructed.
*
* @copydetails doc_note_unit_analysis_depends_on_model
*
* @see isSetUnits()
* @see getUnits()
*/
UnitDefinition * getDerivedUnitDefinition();
/**
* Constructs and returns a UnitDefinition that corresponds to the units
* of this Compartment object's designated size.
*
* @copydetails doc_compartment_units
*
* @return a UnitDefinition that expresses the units of this
* Compartment object, or @c NULL if one cannot be constructed.
*
* @copydetails doc_note_unit_analysis_depends_on_model
*
* @see isSetUnits()
* @see getUnits()
*/
const UnitDefinition * getDerivedUnitDefinition() const;
/**
* Returns the libSBML type code for this SBML object.
*
* @copydetails doc_what_are_typecodes
*
* @return the SBML type code for this object:
* @sbmlconstant{SBML_COMPARTMENT, SBMLTypeCode_t} (default).
*
* @copydetails doc_warning_typecodes_not_unique
*
* @see getElementName()
* @see getPackageName()
*/
virtual int getTypeCode () const;
/**
* Returns the XML element name of this object
*
* For Compartment, the XML element name is always @c "compartment".
*
* @return the name of this element.
*/
virtual const std::string& getElementName () const;
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to write out their contained
* SBML objects as XML elements. Be sure to call your parent's
* implementation of this method as well.
*/
virtual void writeElements (XMLOutputStream& stream) const;
/** @endcond */
/**
* Predicate returning @c true if all the required attributes for this
* Compartment object have been set.
*
* The required attributes for a Compartment object are:
* @li "id" (or "name" in SBML Level 1)
* @li "constant" (in SBML Level 3 only)
*
* @return @c true if the required attributes have been set, @c false
* otherwise.
*/
virtual bool hasRequiredAttributes() const;
#ifndef SWIG
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName, bool& value)
const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName, int& value) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName,
double& value) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName,
unsigned int& value) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName,
std::string& value) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Gets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to retrieve.
*
* @param value, the address of the value to record.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int getAttribute(const std::string& attributeName,
const char* value) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Predicate returning @c true if this Compartment's attribute
* "attributeName" is set.
*
* @param attributeName, the name of the attribute to query.
*
* @return @c true if this Compartment's attribute "attributeName" has been
* set, otherwise @c false is returned.
*/
virtual bool isSetAttribute(const std::string& attributeName) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName, bool value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName, int value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName, double value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName,
unsigned int value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName,
const std::string& value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to set.
*
* @param value, the value of the attribute to set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int setAttribute(const std::string& attributeName, const char*
value);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Unsets the value of the "attributeName" attribute of this Compartment.
*
* @param attributeName, the name of the attribute to query.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
*/
virtual int unsetAttribute(const std::string& attributeName);
/** @endcond */
#endif /* !SWIG */
protected:
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to get the list of
* expected attributes.
* This function is invoked from corresponding readAttributes()
* function.
*/
virtual void addExpectedAttributes(ExpectedAttributes& attributes);
/**
* Subclasses should override this method to read values from the given
* XMLAttributes set into their specific fields. Be sure to call your
* parent's implementation of this method as well.
*/
virtual void readAttributes (const XMLAttributes& attributes,
const ExpectedAttributes& expectedAttributes);
void readL1Attributes (const XMLAttributes& attributes);
void readL2Attributes (const XMLAttributes& attributes);
void readL3Attributes (const XMLAttributes& attributes);
/**
* Subclasses should override this method to write their XML attributes
* to the XMLOutputStream. Be sure to call your parent's implementation
* of this method as well.
*/
virtual void writeAttributes (XMLOutputStream& stream) const;
bool isExplicitlySetSpatialDimensions() const {
return mExplicitlySetSpatialDimensions; };
bool isExplicitlySetConstant() const { return mExplicitlySetConstant; } ;
//std::string mId;
//std::string mName;
std::string mCompartmentType;
unsigned int mSpatialDimensions;
double mSpatialDimensionsDouble;
double mSize;
std::string mUnits;
std::string mOutside;
bool mConstant;
bool mIsSetSize;
bool mIsSetSpatialDimensions;
bool mIsSetConstant;
bool mExplicitlySetSpatialDimensions;
bool mExplicitlySetConstant;
/* the validator classes need to be friends to access the
* protected constructor that takes no arguments
*/
friend class Validator;
friend class ConsistencyValidator;
friend class IdentifierConsistencyValidator;
friend class InternalConsistencyValidator;
friend class L1CompatibilityValidator;
friend class L2v1CompatibilityValidator;
friend class L2v2CompatibilityValidator;
friend class L2v3CompatibilityValidator;
friend class L2v4CompatibilityValidator;
friend class L3v1CompatibilityValidator;
friend class MathMLConsistencyValidator;
friend class ModelingPracticeValidator;
friend class OverdeterminedValidator;
friend class SBOConsistencyValidator;
friend class UnitConsistencyValidator;
/** @endcond */
};
class LIBSBML_EXTERN ListOfCompartments : public ListOf
{
public:
/**
* Creates a new ListOfCompartments object.
*
* The object is constructed such that it is valid for the given SBML
* Level and Version combination.
*
* @param level the SBML Level.
*
* @param version the Version within the SBML Level.
*
* @copydetails doc_throw_exception_lv
*
* @copydetails doc_note_setting_lv
*/
ListOfCompartments (unsigned int level, unsigned int version);
/**
* Creates a new ListOfCompartments object.
*
* The object is constructed such that it is valid for the SBML Level and
* Version combination determined by the SBMLNamespaces object in @p
* sbmlns.
*
* @param sbmlns an SBMLNamespaces object that is used to determine the
* characteristics of the ListOfCompartments object to be created.
*
* @copydetails doc_throw_exception_namespace
*
* @copydetails doc_note_setting_lv
*/
ListOfCompartments (SBMLNamespaces* sbmlns);
/**
* Creates and returns a deep copy of this ListOfCompartments object.
*
* @return the (deep) copy of this ListOfCompartments object.
*/
virtual ListOfCompartments* clone () const;
/**
* Returns the libSBML type code for the objects contained in this ListOf
* (i.e., Compartment objects, if the list is non-empty).
*
* @copydetails doc_what_are_typecodes
*
* @return the SBML type code for the objects contained in this ListOf
* instance: @sbmlconstant{SBML_COMPARTMENT, SBMLTypeCode_t} (default).
*
* @see getElementName()
* @see getPackageName()
*/
virtual int getItemTypeCode () const;
/**
* Returns the XML element name of this object.
*
* For ListOfCompartments, the XML element name is always
* @c "listOfCompartments".
*
* @return the name of this element.
*/
virtual const std::string& getElementName () const;
/**
* Get a Compartment object from the ListOfCompartments.
*
* @param n the index number of the Compartment object to get.
*
* @return the nth Compartment object in this ListOfCompartments.
*
* @see size()
*/
virtual Compartment * get(unsigned int n);
/**
* Get a Compartment object from the ListOfCompartments.
*
* @param n the index number of the Compartment object to get.
*
* @return the nth Compartment object in this ListOfCompartments.
*
* @see size()
*/
virtual const Compartment * get(unsigned int n) const;
/**
* Get a Compartment object from the ListOfCompartments
* based on its identifier.
*
* @param sid a string representing the identifier
* of the Compartment object to get.
*
* @return Compartment object in this ListOfCompartments
* with the given @p sid or @c NULL if no such
* Compartment object exists.
*
* @see get(unsigned int n)
* @see size()
*/
virtual Compartment* get (const std::string& sid);
/**
* Get a Compartment object from the ListOfCompartments
* based on its identifier.
*
* @param sid a string representing the identifier
* of the Compartment object to get.
*
* @return Compartment object in this ListOfCompartments
* with the given @p sid or @c NULL if no such
* Compartment object exists.
*
* @see get(unsigned int n)
* @see size()
*/
virtual const Compartment* get (const std::string& sid) const;
/**
* Removes the nth item from this ListOfCompartments items and returns a pointer to
* it.
*
* The caller owns the returned item and is responsible for deleting it.
*
* @param n the index of the item to remove.
*
* @see size()
*/
virtual Compartment* remove (unsigned int n);
/**
* Removes item in this ListOfCompartments items with the given identifier.
*
* The caller owns the returned item and is responsible for deleting it.
* If none of the items in this list have the identifier @p sid, then
* @c NULL is returned.
*
* @param sid the identifier of the item to remove.
*
* @return the item removed. As mentioned above, the caller owns the
* returned item.
*/
virtual Compartment* remove (const std::string& sid);
/** @cond doxygenLibsbmlInternal */
/**
* Get the ordinal position of this element in the containing object
* (which in this case is the Model object).
*
* The ordering of elements in the XML form of SBML is generally fixed
* for most components in SBML. So, for example, the ListOfCompartments
* in a model is (in SBML Level 2 Version 4) the fifth
* ListOf___. (However, it differs for different Levels and Versions of
* SBML.)
*
* @return the ordinal position of the element with respect to its
* siblings, or @c -1 (default) to indicate the position is not significant.
*/
virtual int getElementPosition () const;
/** @endcond */
protected:
/** @cond doxygenLibsbmlInternal */
/**
* Create and return an SBML object of this class, if present.
*
* @return the SBML object corresponding to next XMLToken in the
* XMLInputStream or @c NULL if the token was not recognized.
*/
virtual SBase* createObject (XMLInputStream& stream);
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#ifndef SWIG
LIBSBML_CPP_NAMESPACE_BEGIN
BEGIN_C_DECLS
/* ----------------------------------------------------------------------------
* See the .cpp file for the documentation of the following functions.
* --------------------------------------------------------------------------*/
/*
LIBSBML_EXTERN
Compartment_t *
Compartment_createWithLevelVersionAndNamespaces (unsigned int level,
unsigned int version, XMLNamespaces_t *xmlns);
*/
/**
* Creates a new Compartment_t structure using the given SBML @p level and @p
* version values.
*
* @param level an unsigned int, the SBML Level to assign to this
* Compartment_t structure.
*
* @param version an unsigned int, the SBML Version to assign to this
* Compartment_t structure.
*
* @returns the newly-created Compartment_t structure, or a null pointer if
* an error occurred during constructions.
*
* @copydetails doc_note_setting_lv
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
Compartment_t *
Compartment_create (unsigned int level, unsigned int version);
/**
* Creates a new Compartment_t structure using the given SBMLNamespaces_t
* structure, @p sbmlns.
*
* @copydetails doc_what_are_sbmlnamespaces
*
* It is worth emphasizing that although this constructor does not take an
* identifier argument, in SBML Level 2 and beyond, the "id"
* (identifier) attribute of a Compartment_t instance is required to have a
* value. Thus, callers are cautioned to assign a value after calling this
* constructor. Setting the identifier can be accomplished using the method
* Compartment_setId().
*
* @param sbmlns an SBMLNamespaces_t structure.
*
* @returns the newly-created Compartment_t structure, or a null pointer if
* an error occurred during constructions
*
* @copydetails doc_note_setting_lv
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
Compartment_t *
Compartment_createWithNS (SBMLNamespaces_t *sbmlns);
/**
* Frees the given Compartment_t structure.
*
* @param c the Compartment_t structure to be freed.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
void
Compartment_free (Compartment_t *c);
/**
* Creates a deep copy of the given Compartment_t structure.
*
* @param c the Compartment_t structure to be copied.
*
* @return a (deep) copy of the given Compartment_t structure, or a null
* pointer if a failure occurred.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
Compartment_t *
Compartment_clone (const Compartment_t* c);
/**
* Initializes the fields of the given Compartment_t structure to "typical"
* default values.
*
* The SBML Compartment component has slightly different aspects and
* default attribute values in different SBML Levels and Versions.
* This method sets the values to certain common defaults, based
* mostly on what they are in SBML Level 2. Specifically:
*
* @li Sets attribute "spatialDimensions" to @c 3
* @li Sets attribute "constant" to @c 1
* @li (Applies to Level 1 models only) Sets attribute "volume" to @c 1.0
* @li (Applies to Level 3 models only) Sets attribute "units" to @c litre
*
* @param c the Compartment_t structure.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
void
Compartment_initDefaults (Compartment_t *c);
/**
* Returns a list of XMLNamespaces_t structures associated with the given
* Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @return pointer to the XMLNamespaces_t structure associated with this SBML
* structure
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const XMLNamespaces_t *
Compartment_getNamespaces(Compartment_t *c);
/**
* Returns the value of the "id" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @return the id of this structure.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const char *
Compartment_getId (const Compartment_t *c);
/**
* Returns the value of the "name" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @return the name of the Compartment_t structure @p c, as a pointer to a
* string.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const char *
Compartment_getName (const Compartment_t *c);
/**
* Get the value of the "compartmentType" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @return the value of the "compartmentType" attribute of the
* Compartment_t structure @p c as a string.
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const char *
Compartment_getCompartmentType (const Compartment_t *c);
/**
* Get the number of spatial dimensions of the given Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @return the value of the "spatialDimensions" attribute of the
* Compartment_t structure @p c as an unsigned integer
*
* @copydetails doc_note_spatial_dimensions_as_double
*
* @see Compartment_getSpatialDimensionsAsDouble()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
unsigned int
Compartment_getSpatialDimensions (const Compartment_t *c);
/**
* Get the number of spatial dimensions of the given Compartment_t structure,
* as a double.
*
* @param c the Compartment_t structure.
*
* @return the value of the "spatialDimensions" attribute of the
* Compartment_t structure @p c as a double.
*
* @copydetails doc_note_spatial_dimensions_as_double
*
* @see Compartment_getSpatialDimensions()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
double
Compartment_getSpatialDimensionsAsDouble (const Compartment_t *c);
/**
* Get the size of the given Compartment_t structure.
*
* @copydetails doc_compartment_both_size_and_volume
*
* @param c the Compartment_t structure.
*
* @return the value of the "size" attribute ("volume" in Level 1) of
* the Compartment_t structure @p c as a float-point number.
*
* @note This method is identical to Compartment_getVolume().
*
* @see Compartment_isSetSize()
* @see Compartment_getVolume()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
double
Compartment_getSize (const Compartment_t *c);
/**
* Get the volume of the given Compartment_t structure.
*
* @copydetails doc_compartment_both_size_and_volume
*
* @param c the Compartment_t structure.
*
* @return the value of the "volume" attribute ("size" in Level 2) of
* @p c, as a floating-point number.
*
* @copydetails doc_note_compartment_volume
*
* @note This method is identical to Compartment_getSize().
*
* @see Compartment_isSetVolume()
* @see Compartment_getSize()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
double
Compartment_getVolume (const Compartment_t *c);
/**
* Get the units of the given Compartment_t structure's size.
*
* The value of an SBML compartment's "units" attribute establishes the
* unit of measurement associated with the compartment's size.
*
* @param c the Compartment_t structure.
*
* @return the value of the "units" attribute of the Compartment_t structure,
* as a string. An empty string indicates that no units have been assigned
* to the value of the size.
*
* @copydetails doc_note_unassigned_unit_are_not_a_default
*
* @see Compartment_isSetUnits()
* @see Compartment_setUnits()
* @see Compartment_getSize()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const char *
Compartment_getUnits (const Compartment_t *c);
/**
* Get the identifier, if any, of the compartment that is designated
* as being outside of the given Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @return the value of the "outside" attribute of this Compartment_t
* structure.
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
const char *
Compartment_getOutside (const Compartment_t *c);
/**
* Get the value of the "constant" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if this compartment's size is flagged as being
* constant, @c 0 otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_getConstant (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "id"
* attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "id" attribute of this Compartment_t structure is
* set, @c 0 otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetId (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "name"
* attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "name" attribute of this Compartment_t structure is
* set, @c 0 otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetName (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's
* "compartmentType" attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "compartmentType" attribute of this Compartment_t
* structure is set, @c 0 otherwise.
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetCompartmentType (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "size"
* attribute is set.
*
* This method is similar but not identical to Compartment_isSetVolume().
* The latter should be used in the context of SBML Level 1 models
* instead of Compartment_isSetSize() because Compartment_isSetVolume()
* performs extra processing to take into account the difference in default
* values between SBML Levels 1 and 2.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "size" attribute ("volume" in Level 2) of
* this Compartment_t structure is set, @c 0 otherwise.
*
* @see Compartment_isSetVolume()
* @see Compartment_setSize()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetSize (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structures's "volume"
* attribute is set.
*
* This method is similar but not identical to Compartment_isSetSize(). The
* latter should not be used in the context of SBML Level 1 models
* because the present method performs extra processing to take into account
* the difference in default values between SBML Levels 1 and 2.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "volume" attribute ("size" in Level 2 and
* above) of this Compartment_t structure is set, @c 0 otherwise.
*
* @copydetails doc_note_compartment_volume
*
* @see Compartment_isSetSize()
* @see Compartment_setVolume()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetVolume (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "units"
* attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "units" attribute of this Compartment_t structure
* is set, @c 0 otherwise.
*
* @copydetails doc_note_unassigned_unit_are_not_a_default
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetUnits (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "outside"
* attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "outside" attribute of this Compartment_t structure
* is set, @c 0 otherwise.
*
* @note The "outside" attribute is defined in SBML Level 1 and
* Level 2, but does not exist in SBML Level 3.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetOutside (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's
* "spatialDimensions" attribute is set.
*
* @param c the Compartment_t structure.
*
* @return @c 1 if the "spatialDimensions" attribute of this Compartment_t
* structure is set, @c 0 otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetSpatialDimensions (const Compartment_t *c);
/**
* Predicate returning @c 1 if the given Compartment_t structure's "constant"
* attribute is set.
*
* @return @c 1 if the "constant" attribute of this Compartment_t
* structure is set, @c 0 otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_isSetConstant (const Compartment_t *c);
/**
* Sets the value of the "id" attribute of the given Compartment_t structure.
*
* The string @p sid is copied.
*
* @copydetails doc_id_attribute
*
* @param c the Compartment_t structure.
*
* @param sid the identifier to which the structures "id" attribute should
* be set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @note Using this function with a null pointer for @p sid is equivalent to
* unsetting the "id" attribute.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setId (Compartment_t *c, const char *sid);
/**
* Sets the "name" attribute of the given Compartment_t structure.
*
* This function copies the string given in @p string. If the string is
* a null pointer, this function performs Compartment_unsetName() instead.
*
* @param c the Compartment_t structure.
*
* @param name the string to which the structures "name" attribute should be
* set.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @note Using this function with a null pointer for @p name is equivalent to
* unsetting the value of the "name" attribute.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setName (Compartment_t *c, const char *name);
/**
* Sets the "compartmentType" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
* @param sid the identifier of a CompartmentType_t structure defined
* elsewhere in the enclosing Model_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @note Using this function with a null pointer for @p sid is equivalent to
* unsetting the value of the "compartmentType" attribute.
*
* @note The "compartmentType" attribute is only available in SBML
* Level 2 Versions 2–4.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setCompartmentType (Compartment_t *c, const char *sid);
/**
* Sets the "spatialDimensions" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
* @param value an unsigned integer indicating the number of dimensions
* of the given compartment.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setSpatialDimensions (Compartment_t *c, unsigned int value);
/**
* Sets the "spatialDimensions" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
* @param value a double indicating the number of dimensions
* of the given compartment.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setSpatialDimensionsAsDouble (Compartment_t *c, double value);
/**
* Sets the "size" attribute (or "volume" in SBML Level 1) of the given
* Compartment_t structure.
*
* @param c the Compartment_t structure.
* @param value a @c double representing the size of the given
* Compartment_t structure in whatever units are in effect.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @see Compartment_isSetSize()
* @see Compartment_setVolume()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setSize (Compartment_t *c, double value);
/**
* Sets the "volume" attribute (or "size" in SBML Level 2) of the given
* Compartment_t structure.
*
* This method is identical to Compartment_setSize() and is provided for
* compatibility between SBML Level 1 and higher Levels of SBML.
*
* @param c the Compartment_t structure.
*
* @param value a @c double representing the volume of the given
* Compartment_t structure in whatever units are in effect.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @copydetails doc_note_compartment_volume
*
* @see Compartment_isSetVolume()
* @see Compartment_setSize()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setVolume (Compartment_t *c, double value);
/**
* Sets the "units" attribute of the given Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @param sid the identifier of the defined units to use. The string will
* be copied.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @note Using this function with a null pointer for @p sid is equivalent to
* unsetting the value of the "units" attribute.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setUnits (Compartment_t *c, const char *sid);
/**
* Sets the "outside" attribute of the given Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @param sid the identifier of a compartment that encloses this one. The
* string will be copied.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @note Using this function with a null pointer for @p sid is equivalent to
* unsetting the value of the "outside" attribute.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setOutside (Compartment_t *c, const char *sid);
/**
* Sets the value of the "constant" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @param value an integer indicating whether the size/volume of the
* compartment @p c should be considered constant (indicated by a nonzero @p
* value) or variable (@p value is zero).
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_setConstant (Compartment_t *c, int value);
/**
* Unsets the "name" attribute of the given Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetName (Compartment_t *c);
/**
* Unsets the value of the "compartmentType" attribute of the given
* Compartment_t structure.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetCompartmentType (Compartment_t *c);
/**
* Unsets the value of the "constant" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetConstant (Compartment_t *c);
/**
* Unsets the value of the "size" attribute of the given Compartment_t
* structure.
*
* In SBML Level 1, a compartment's volume has a default value (@c
* 1.0) and therefore <em>should always be set</em>. Calling this method
* on a Level 1 model resets the value to @c 1.0 rather than actually
* unsetting it. In Level 2, a compartment's "size" is optional with
* no default value, and unsetting it will result in the compartment having
* no defined size.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetSize (Compartment_t *c);
/**
* (For SBML Level 1) Unsets the value of the "volume" attribute of the
* given Compartment_t structure.
*
* This method is identical to Compartment_unsetSize(). Please refer to that
* method's documentation for more information about its behavior.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @copydetails doc_note_compartment_volume
*
* @see Compartment_unsetSize()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetVolume (Compartment_t *c);
/**
* Unsets the value of the "units" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetUnits (Compartment_t *c);
/**
* Unsets the value of the "outside" attribute of the given Compartment_t
* structure.
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetOutside (Compartment_t *c);
/**
* Unsets the value of the "spatialDimensions" attribute of the given
* Compartment_t structure.
*
* In SBML Levels prior to Level 3, compartments must always have a
* value for the number of dimensions. Consequently, calling this method
* on a model of SBML Level 1–2 will result in a return value of
* @sbmlconstant{LIBSBML_UNEXPECTED_ATTRIBUTE, OperationReturnValues_t}
*
* @param c the Compartment_t structure.
*
* @copydetails doc_returns_success_code
* @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t}
* @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t}
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_unsetSpatialDimensions (Compartment_t *c);
/**
* Constructs and returns a UnitDefinition that corresponds to the units
* of the given Compartment_t structure's designated size.
*
* @copydetails doc_compartment_units
*
* @param c the Compartment_t structure whose units are to be returned.
*
* @return a UnitDefinition_t structure that expresses the units
* of the given Compartment_t structure.
*
* @copydetails doc_note_unit_analysis_depends_on_model
*
* @see Compartment_isSetUnits()
* @see Compartment_getUnits()
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
UnitDefinition_t *
Compartment_getDerivedUnitDefinition(Compartment_t *c);
/**
* Predicate returning @c 1 or @c 0 depending on whether all the required
* attributes for the given Compartment_t structure have been set.
*
* The required attributes for a Compartment_t structure are:
* @li id (name in SBML Level 1 only)
* @li constant (in SBML Level 3 only)
*
* @param c the Compartment_t structure to check.
*
* @return @c true (nonzero) if all the required attributes for this
* structure have been defined, @c false (zero) otherwise.
*
* @memberof Compartment_t
*/
LIBSBML_EXTERN
int
Compartment_hasRequiredAttributes (Compartment_t *c);
/**
* Returns the Compartment_t structure having a given identifier.
*
* @param lo the list of Compartments_t structures to search.
* @param sid the "id" attribute value being sought.
*
* @return item in the @p lo ListOfCompartments with the given @p sid or a
* null pointer if no such item exists.
*
* @see ListOf_t
*
* @memberof ListOfCompartments_t
*/
LIBSBML_EXTERN
Compartment_t *
ListOfCompartments_getById (ListOf_t *lo, const char *sid);
/**
* Removes a Compartment_t structure based on its identifier.
*
* The caller owns the returned item and is responsible for deleting it.
*
* @param lo the list of Compartment_t structures to search.
* @param sid the "id" attribute value of the structure to remove.
*
* @return The Compartment_t structure removed, or a null pointer if no such
* item exists in @p lo.
*
* @see ListOf_t
*
* @memberof ListOfCompartments_t
*/
LIBSBML_EXTERN
Compartment_t *
ListOfCompartments_removeById (ListOf_t *lo, const char *sid);
END_C_DECLS
LIBSBML_CPP_NAMESPACE_END
#endif /* !SWIG */
#endif /* Compartment_h */
| true |
028228fa3421e3235d6e9a7171775500c2eed7da
|
C++
|
baocl18ctt2/Book_OOP
|
/Oop/Admin.cpp
|
UTF-8
| 1,501 | 2.9375 | 3 |
[] |
no_license
|
#include "Admin.h"
#include <iomanip>
Admin::Admin()
{
}
Admin::Admin(string kind, string account, string password, string name,float age)
{
mkind = kind;
mAccount = account;
mPassword = password;
mName = name;
mAge = age;
}
Admin::~Admin()
{
}
void Admin::read_1_information(ifstream& FileIn)
{
getline(FileIn, mkind, ',');
if (mkind == "\nAuthor" || mkind == "\nPublisher" || mkind == "\nUser")
{
mkind.erase(mkind.begin(), mkind.begin() + 1);
}
FileIn.seekg(1, 1);
getline(FileIn, mAccount, ',');
FileIn.seekg(1, 1);
getline(FileIn, mPassword, ',');
FileIn.seekg(1, 1);
getline(FileIn, mName, ',');
FileIn.seekg(1, 1);
FileIn >> mAge;
/*string temp;
getline(cin, temp);*/
}
void Admin::display_1_information()
{
cout << left << setw(20) << mkind << setw(20) << mAccount << setw(20) << mPassword << setw(20) << mName << setw(30) << mAge << endl;
}
void Admin::set_kind(string kind)
{
mkind = kind;
}
string Admin::get_kind()
{
return mkind;
}
void Admin::set_account(string account)
{
mAccount = account;
}
string Admin::get_account()
{
return mAccount;
}
void Admin::set_password(string password)
{
mPassword = password;
}
string Admin::get_password()
{
return mPassword;
}
void Admin::set_name(string name)
{
mName = name;
}
string Admin::get_name()
{
return mName;
}
void Admin::set_age(float age)
{
mAge = age;
}
float Admin::get_age()
{
return mAge;
}
| true |
1bf5438613ffd433dc51ea5845703485a81161b5
|
C++
|
rodetas/vsss-rodetas-2017
|
/src/utils/Manipulation.h
|
UTF-8
| 2,779 | 3.09375 | 3 |
[] |
no_license
|
#ifndef MANIPULATION
#define MANIPULATION
#include "../Header.h"
#include "Commons.h"
#include <fstream>
#include <ctime>
#include <iomanip>
using namespace rodetas;
class Manipulation{
private:
//variaveis de calibragem
vector<Hsv> colorsHSV;
vector<Rgb> colorsRGB;
Point point_cut_field_1;
Point point_cut_field_2;
Point goal;
int angle_image_rotation;
bool cameraOn;
string filename;
const string instance_path = "../files/instances/fileCalibration.txt";
const string standart_instance = "../files/instances/standartInstance.txt";
public:
/**
* Default Constructor - automatically loads the instance file
*/
Manipulation();
/**
* Saves the calibration
* \param hsv: receives a hsv vector containing the robot colors references
* \param rgb: receives a rgb vector containing the robot colors references
* \param p1: receives the point cut field 1
* \param p2: receibes the point cut field 2
* \param p3: receives the goal point
* \param angle: receives the rotation angle
* \param cam: receives true if camera is on
*/
void saveCalibration(vector<Hsv>& hsv, vector<Rgb>& rgb, Point p1, Point p2, Point p3, int angle, bool cam);
/**
* Saves the camera parameters
* \param cam_config: receives the struct containing the data
*/
void saveCameraConfig(CameraConfiguration cam_config);
/**
* Saves the coordinates captured during the gama
* \param objects: receive the vector containing all the positions captured during the game
*/
void saveCoordinates(vector<rodetas::Object>&);
/**
* Loads the calibration file
* \return a pair containing a hsv vector and rgb vector
*/
pair<vector<Hsv>, vector<Rgb>> loadCalibration();
/**
* Loads the camera configuration file
* \return the struct CameraConfiguration which contains all the informations
*/
CameraConfiguration loadCameraConfig();
/**
* Print on the screen the calibration loaded so far
*/
void printCalibration();
/**
* \return The vector containing the HSV colors
*/
vector<Hsv> getColorsHsv();
/**
* \return The vector containing the RGB colors
*/
vector<Rgb> getColorsRgb();
/**
*
*/
vector<Rgb> getColorsRgbCairo();
/**
* \return The first point which delimitates the board
*/
Point getPointField1();
/**
* \return The second point which delimitates the board
*/
Point getPointField2();
/**
* \return The image angle rotation
*/
int getAngleImage();
/**
* \return true if should use the camera
*/
bool getCameraOn();
/**
* \return The point which delimitates the goal
*/
Point getGoal();
/**
* \return The point containing the board size
*/
Point getImageSize();
/**
* Sets the file name for saving all the game coordinates
*/
void setFileName(string);
};
#endif
| true |
b0e0640e6581382c912943b8ce3a18adb0f9b076
|
C++
|
Tifloz/Tek2
|
/Piscine_CPP/cpp_d17_2018/ex02/main.cpp
|
UTF-8
| 1,531 | 2.9375 | 3 |
[] |
no_license
|
/*
** EPITECH PROJECT, 2022
** cpp_d17_2018
** File description:
** Created by Florian Louvet,
*/
#include "Cesar.hpp"
#include "OneTime.hpp"
#include <string>
#include <iostream>
static void encryptString(IEncryptionMethod &encryptionMethod,
std::string const &toEncrypt
)
{
size_t len = toEncrypt.size();
encryptionMethod.reset();
for (size_t i = 0; i < len; ++i) {
encryptionMethod.encryptChar(toEncrypt[i]);
}
std::cout << std::endl;
}
static void decryptString(IEncryptionMethod &encryptionMethod,
std::string const &toDecrypt
)
{
size_t len = toDecrypt.size();
encryptionMethod.reset();
for (size_t i = 0; i < len; ++i) {
encryptionMethod.decryptChar(toDecrypt[i]);
}
std::cout << std::endl;
}
int main()
{
Cesar c;
OneTime o("DedeATraversLesBrumes");
OneTime t("TheCakeIsALie");
encryptString(c, "Je clair Luc , ne pas ? Ze woudrai un kekos !");
decryptString(c, "Mi isirb Xhq , ew jvo ? Zf zszjyir fz ytafk !");
encryptString(c, "KIKOO");
encryptString(c, "LULZ XD");
decryptString(c, "Ziqivun ea Ndcsg.Wji !");
encryptString(t, "Prend garde Lion , ne te trompes pas de voie !");
encryptString(o, "De la musique et du bruit !");
encryptString(t, "Kion li faras? Li studas kaj programas!");
decryptString(t, "Iyipd kijdp Pbvr , xi le bvhttgs tik om ovmg !");
decryptString(o, "Gi pa dunmhmp wu xg tuylx !");
decryptString(t, "Dpsp vm xaciw? Pk cxcvad otq rrykzsmla!");
return 0;
}
| true |
f9a8825301c0d29efdfb384a41097ec96519764f
|
C++
|
tuananh100502/BT-code--week5
|
/BT So nguyen to.cpp
|
UTF-8
| 331 | 3.09375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cmath>
using namespace std;
int check (int n){
int count =0,i;
if(n<2) return 0;
if(n>=2){
for(i=2;i<=sqrt(n);i++){
if(n%i==0)
count+=1;
}
if(count==0) return 1;
else return 0;
}
}
int main(){
int n;
cin >> n;
int 1 = check (n);
cout << 1 << endl;
return 0;
}
| true |
fd051a3d7455c658829ce0f72e334846fd8d2cad
|
C++
|
amritsingh1097/OpenGL-Project
|
/Circle.h
|
UTF-8
| 1,505 | 2.640625 | 3 |
[] |
no_license
|
#ifndef CIRCLE_H
#define CIRCLE_H
#include "object.h"
#include <bits/stdc++.h>
#include <conio.h>
#include <gl/glut.h>
using namespace std;
class MidPoint_Circle : public Object
{
int shapeID;
public:
int centerX, centerY, clickedRadiusX, clickedRadiusY, radius;
// bool isFilled;
list< pair<int, int> > filledCoords;
MidPoint_Circle(unsigned char* color, int thickness, string pattern);
void printCoords();
int getShapeID();
void draw(int XCoord1, int YCoord1, int XCoord2, int YCoord2);
void swapPoints(int centerX, int centerY, int quad1_X, int quad1_Y);
bool selectObject(pair<int, int> clickedCoords);
void translate(int dx, int dy);
void rotate(int rotAngle, pair<int, int> pivot);
void scale(float scaleFactor, pair<int, int> pivot);
void setPattern(string pattern);
void setThickness(int thickness);
void setColor(unsigned char* color);
void setFillColor(unsigned char* fillColor);
void erasePreviousObject();
void redrawSelectedObject(unsigned char* color, int thickness);
// void fillBoundary(pair<int, int> seed, unsigned char* fillColor, unsigned char* selectedObjectColor);
void fourFillBoundary(int x, int y, unsigned char* fillColor, unsigned char* selectedObjectColor);
void eightFillBoundary(int x, int y, unsigned char* fillColor, unsigned char* selectedObjectColor);
void fourFloodFill(int x, int y, unsigned char* fillColor);
void eightFloodFill(int x, int y, unsigned char* fillColor);
};
#endif
| true |
34a0f1a4c52c1c4447633712e8dbebfc89e7a2ec
|
C++
|
pro1710/leetcode
|
/562_longest_line_of_consecutive_one_in_matrix.cpp
|
UTF-8
| 956 | 2.640625 | 3 |
[] |
no_license
|
class Solution {
public:
int longestLine(vector<vector<int>>& mat) {
struct Cell {
int hor;
int vert;
int diag;
int adiag;
};
vector<vector<Cell>> dp(mat.size()+2, vector<Cell>(mat[0].size()+2));;
int ans = 0;
for (int i = 0; i < mat.size(); ++i) {
for (int j = 0; j < mat[0].size(); ++j) {
if (mat[i][j]) {
dp[i+1][j+1].hor = dp[i+1][j].hor + 1;
dp[i+1][j+1].vert = dp[i][j+1].vert + 1;
dp[i+1][j+1].diag = dp[i][j].diag + 1;
dp[i+1][j+1].adiag = dp[i][j+2].adiag + 1;
}
ans = max(ans, dp[i+1][j+1].hor);
ans = max(ans, dp[i+1][j+1].vert);
ans = max(ans, dp[i+1][j+1].diag);
ans = max(ans, dp[i+1][j+1].adiag);
}
}
return ans;
}
};
| true |