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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
71fe69fffb77ec56b99e30707c35fe756c213372 | C++ | swxie/algorithm | /disjoint.cpp | UTF-8 | 1,700 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <vector>
#include <unordered_map>
using namespace std;
class disjoint
{
private:
vector<int> parent;
vector<int> rank;//秩
public:
disjoint(int size);
~disjoint();
int find(int x){
if (x == parent[x])
return x;
else{
parent[x] = find(parent[x]);
return parent[x];
}
};
int unionSet(int x, int y){
x = find(x);
y = find(y);
if (x == y)
return 0;
if (rank[x] > rank[y]){
parent[y] = x;
}
else{
parent[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
vector<vector<int>> serialize(){
unordered_map<int, vector<int>> buffer;
for (int i = 0; i < parent.size(); i++){
if (buffer.find(parent[i]) == buffer.end())
buffer[parent[i]] = vector<int>();
buffer[parent[i]].push_back(i);
}
vector<vector<int>> ans;
for (auto i = buffer.begin(); i != buffer.end(); i++){
ans.push_back(i->second);
}
return ans;
}
};
disjoint::disjoint(int size)
{
rank = vector<int>(size, 0);
parent = vector<int>(size);
for (int i = 0; i < size; i++){
parent[i] = i;
}
}
disjoint::~disjoint()
{
}
int main(){
disjoint disjoint(10);
disjoint.unionSet(5, 6);
disjoint.unionSet(7, 8);
disjoint.unionSet(1, 8);
vector<vector<int>> ans = disjoint.serialize();
for (int i = 0; i < ans.size(); i++){
copy(ans[i].begin(), ans[i].end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
}
| true |
13a6839772217ebdeae4c674c6416ad0e4a697cd | C++ | paksas/Tamy | /Code/Include/core/Algorithms.inl | UTF-8 | 2,270 | 3.21875 | 3 | [] | no_license | #ifndef _ALGORITHMS_H
#error "This file can only be included from Algorithms.h"
#else
///////////////////////////////////////////////////////////////////////////////
template< typename T >
void Collection::clear( T& collection )
{
for ( T::iterator it = collection.begin(); it != collection.end(); ++it )
{
delete *it;
}
collection.clear();
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
T clamp( T val, T min, T max )
{
return ( min < val ) ? ( ( val < max ) ? val : max ) : min;
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
T roundEx( T value, T precision )
{
T roundedVal = (T)(long)( value / precision ) * precision;
return roundedVal;
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
float mag( T value )
{
if ( value == 0.0 )
{
return 1.0f;
}
else
{
float logVal = (float)log10( value );
int intMag = (int)logVal;
if ( intMag > 0 )
{
return (float)pow( 10.0, intMag );
}
else if ( intMag == 0 )
{
if ( value >= 1.0 )
{
return 1.0f;
}
else
{
return 0.1f;
}
}
else // intMag < 0
{
if ( logVal - intMag < 0 )
{
--intMag;
}
intMag = -intMag;
return (float)( 1.0 / pow( 10.0, intMag ) );
}
}
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
T min2( T val1, T val2 )
{
return val1 < val2 ? val1 : val2;
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
T max2( T val1, T val2 )
{
return val1 > val2 ? val1 : val2;
}
///////////////////////////////////////////////////////////////////////////////
template< typename T >
T sign( T val )
{
if ( val > ( T ) 0 )
{
return ( T ) 1;
}
else if ( val < ( T ) 0 )
{
return ( T )-1;
}
else
{
return ( T ) 0;
}
}
///////////////////////////////////////////////////////////////////////////////
#endif // _ALGORITHMS_H
| true |
0baf6651fdcb71245b49a87fb2d79e80791443d3 | C++ | szr712/PAT-Advanced-Level-Practice | /1052.cpp | UTF-8 | 1,296 | 2.796875 | 3 | [] | no_license | /*
这道题坑点很多
然后有可能给出的结点不是全部都在链表中
最后一个最坑 就是可能给出的起始地址不在给出的结点的中
*/
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<cmath>
#include<stack>
using namespace std;
int n;
map<int, pair<int, int>> link;
map<int, int> ans;
int start;
int main() {
scanf("%d %d", &n, &start);
// if (n == 0) {经过验证,给出零是不可能的
// printf("%d %05d\n", n, start);
// system("pause");
// return 0;
// }
for (int i = 0; i < n; i++) {
int a, next;
int key;
scanf("%d %d %d", &a, &key, &next);
link[a].first = key;
link[a].second = next;
}
if (link.find(start) == link.end()) {//开始结点就没给出
cout << 0 << " " << -1;
system("pause");
return 0;
}
while (start != -1) {
ans[link[start].first] = start;
start = link[start].second;
}
start = ans.begin()->second;
printf("%d %05d\n", ans.size(), start);//要输出size,因为给出的结点不一定都在链表中
auto i = ans.begin();
while (i != ans.end()) {
printf("%05d %d", i->second, i->first);
i++;
if (i != ans.end()) {
printf(" %05d\n", i->second);
}
else {
printf(" -1\n");
}
}
system("PAUSE");
} | true |
37a5e54282f02d241e7c80288e973b7ecd27a798 | C++ | gzumpan/fuzzy-cmeans | /VAT/cmeans/Unicode/UnicodeUtil.cpp | UTF-8 | 3,467 | 2.8125 | 3 | [] | no_license | // UnicodeUtil.cpp: implementation of the UnicodeUtil class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "UnicodeUtil.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
UnicodeUtil::UnicodeUtil()
{
}
UnicodeUtil::~UnicodeUtil()
{
}
BOOL UnicodeUtil::Utf8ToWstring(const std::string utf8string, std::wstring &resultstring)
{
ConversionResult res;
size_t widesize;
widesize = utf8string.length();
if (sizeof(wchar_t) == 2)
{
UTF16 *targetstart, *targetend;
const UTF8* sourcestart = reinterpret_cast<const UTF8*>(utf8string.c_str());
const UTF8* sourceend = sourcestart + widesize;
resultstring.resize(widesize + 1, L'\0');
targetstart = reinterpret_cast<UTF16*>(&resultstring[0]);
targetend = targetstart + widesize;
res = ConvertUTF8toUTF16(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
if (res != conversionOK) {
return (FALSE);
}
*targetstart = 0;
return (TRUE);
}
else if (sizeof(wchar_t) == 4)
{
UTF32 *targetstart, *targetend;
const UTF8* sourcestart = reinterpret_cast<const UTF8*>(utf8string.c_str());
const UTF8* sourceend = sourcestart + widesize;
resultstring.resize(widesize + 1, L'\0');
targetstart = reinterpret_cast<UTF32*>(&resultstring[0]);
targetend = targetstart + widesize;
res = ConvertUTF8toUTF32(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
if (res != conversionOK) {
return (FALSE);
}
*targetstart = 0;
return (TRUE);
}
return (FALSE);
}
BOOL UnicodeUtil::WstringToUtf8(const std::wstring widestring, std::string &resultstring)
{
ConversionResult res;
size_t widesize, utf8size;
size_t endPos;
widesize = widestring.length();
if (sizeof(wchar_t) == 2)
{
UTF8 *targetstart, *targetend;
const UTF16* sourcestart = reinterpret_cast<const UTF16*>(widestring.c_str());
const UTF16* sourceend = sourcestart + widesize;
utf8size = 3 * widesize + 1;
resultstring.resize(utf8size, '\0');
targetstart = reinterpret_cast<UTF8*>(&resultstring[0]);
targetend = targetstart + utf8size;
res = ConvertUTF16toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
if (res != conversionOK) {
return (FALSE);
}
*targetstart = 0;
// Ninh change: erase trailings
endPos = resultstring.find('\0');
resultstring.erase(endPos, utf8size - widesize);
return (TRUE);
}
else if (sizeof(wchar_t) == 4)
{
UTF8 *targetstart, *targetend;
const UTF32* sourcestart = reinterpret_cast<const UTF32*>(widestring.c_str());
const UTF32* sourceend = sourcestart + widesize;
utf8size = 4 * widesize + 1;
resultstring.resize(utf8size, '\0');
targetstart = reinterpret_cast<UTF8*>(&resultstring[0]);
targetend = targetstart + utf8size;
res = ConvertUTF32toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
if (res != conversionOK) {
return (FALSE);
}
*targetstart = 0;
// Ninh change: erase trailings
endPos = resultstring.find('\0');
resultstring.erase(endPos, utf8size - widesize);
return (TRUE);
}
return (FALSE);
}
| true |
6e25321bd68972d8955ad5fbffaed61196ec2295 | C++ | ajosh0504/Cosine-and-Dot-Product-Similarity | /doc_query.cpp | UTF-8 | 7,881 | 2.8125 | 3 | [] | no_license | #include <dirent.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <Eigen/SVD>
#define MAX_STRING 50
#define FOUND -1
#define QUERY_PATH "Documents/Machine Learning/MachineLearning/MachineLearning/queries"
#define DOCS_PATH "Documents/Machine Learning/MachineLearning/MachineLearning/docs"
using namespace std;
using namespace Eigen;
bool my_predicate(char c){
if (c == '\n' || c == '\r' || c == '\0')
return true;
else
return false;
}
std::vector<std::string> getfiles(std::string path = ".") {
std::vector<std::string> files;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (path.c_str())) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
string s = ent->d_name;
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
if( !(s == "." || s == ".." || s == ".DS_Store") )
files.push_back(ent->d_name);
}
closedir (dir);
}
else
{
/* could not open directory */
perror ("");
}
return files;
}
std::vector<std::string> vocab;
void build_vocab_vector (const char * docs){
static char buf[MAX_STRING] = "";
FILE *file;
file = fopen(docs, "r+");
while(fgets(buf, MAX_STRING, file)){
bool flag = false;
for(int i = 0; i < vocab.size(); i++){
string s = buf;
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
flag = false || (vocab[i] == s);
if(flag)
break;
}
if(!flag){
string s = buf;
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
vocab.push_back(s);
}
}
fclose(file);
}
int main(){
std::vector<std::string> docs, queries;
docs = getfiles(DOCS_PATH); // or pass which dir to open
queries = getfiles(QUERY_PATH);
for (int i = 0; i < docs.size(); ++i) {
build_vocab_vector((string(DOCS_PATH) + string("/") + docs[i]).c_str());
}
cout<< "Size of vocab vector: "<<vocab.size()<<endl;
cout<< "Computing the Vocab-Docs Matrix...."<<endl;
short mat_d[2869][500];
for(int i=0; i<vocab.size(); i++) //This loops on the rows.
{
for(int j=0; j<docs.size(); j++) //This loops on the columns
{
mat_d[i][j] = 0;
}
}
char buf[MAX_STRING];
for(int i = 0; i < docs.size(); ++i){
FILE *f = fopen((string(DOCS_PATH) + string("/") + docs[i]).c_str(), "r");
while( fgets(buf, MAX_STRING, f) ){
string s = buf;
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
for(int j = 0; j < vocab.size(); ++j){
if( vocab[j] == s){
++mat_d[j][i];
}
}
}
}
cout<< "Computing the Vocab-Query Matrix...."<<endl;
short mat_q[2869][5];
for(int i=0; i<vocab.size(); i++)
{
for(int j=0; j<queries.size(); j++)
{
mat_q[i][j] = 0;
}
}
for(int i = 0; i < queries.size(); ++i){
FILE *f = fopen((string(QUERY_PATH) + string("/") + queries[i]).c_str(), "r");
while( fgets(buf, MAX_STRING, f) ){
string s = buf;
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
for(int j = 0; j < vocab.size(); ++j){
if( vocab[j] == s){
++mat_q[j][i];
}
}
}
}
// mat_Q is VALID
cout << "Computing the Dot-Scalar Similarity and Cosine-Similarity..."<<endl;
int result_dot[500];
float result_cosine[500];
float sum = 0;
int Di = 0;
int Qi = 0;
for(int i=0; i<5; i++)
{
int top_ten[10];
for(int j=0; j<500; j++)
{
sum = 0;
Di = 0;
Qi = 0;
for(int k = 0; k < vocab.size(); ++k){
sum = sum + mat_q[k][i] * mat_d[k][j];
Di = Di + mat_d[k][j] * mat_d[k][j];
Qi = Qi + mat_q[k][i] * mat_q[k][i];
}
result_dot[j] = sum;
result_cosine[j] = sum/(sqrt(Di) * sqrt(Qi));
}
cout << "For Dot Product Similarity: "<<endl;
for( int k = 0; k < 10; k++){
int index = 0;
int temp = result_dot[0];
for(int j = 1; j<500; ++j){
if(temp <= result_dot[j]){
index = j;
temp = result_dot[j];
}
}
result_dot[index] = FOUND;
top_ten[k] = index;
}
cout << "For Query "<<i+1<<" The top 10 files are: "<<endl;
for(int k: top_ten)
cout << docs[k].c_str() <<endl;
cout << "For Cosine Similarity: "<<endl;
for( int k = 0; k < 10; k++){
int index = 0;
float temp = result_cosine[0];
for(int j = 1; j<500; ++j){
if(temp <= result_cosine[j]){
index = j;
temp = result_cosine[j];
}
}
result_cosine[index] = FOUND;
top_ten[k] = index;
}
cout << "For Query "<<i+1<<" The top 10 files are: "<<endl;
for(int k: top_ten)
cout << docs[k].c_str() <<endl;
}
cout << "Performing LSI...."<<endl;
cout << "Computing the SVD for vocab-doc matrix..."<<endl;
MatrixXf A(2869, 500);
for(int i=0; i<vocab.size(); i++) //This loops on the rows.
{
for(int j=0; j<docs.size(); j++) //This loops on the columns
{
A(i, j) = mat_d[i][j];
}
}
//JacobiSVD<MatrixXf> s(A, ComputeFullU | ComputeFullV);
JacobiSVD<MatrixXf> svd = A.jacobiSvd(ComputeFullU | ComputeFullV);
// Diagonals are ordered by magnitude, therefore top - 5 signular values are top 5 diagnal values.
MatrixXf U = svd.matrixU();
MatrixXf V = svd.matrixV();
MatrixXf d = svd.singularValues();
MatrixXf S(5,5);
for(int i=0; i<5; i++) //This loops on the rows.
{
for(int j=0; j<5; j++) //This loops on the columns
{
S(i, j) = 0;
}
}
for (int i = 0; i < 5; i ++){
S(i, i) = d(i);
}
cout << "Top 5 singular vlaues are: "<<endl;
for(int i=0; i<5; i++) //This loops on the rows.
{
for(int j=0; j<5; j++) //This loops on the columns
{
cout << S(i, j) << " ";
}
cout << "......."<<endl;
}
for(int i=0; i < 5; i++){
int top_ten[10];
for( int k = 0; k < 10; k++){
int index = 0;
float temp = U(0, i);
for(int j = 1; j<2869; ++j){
if(temp <= U(j, i)){
index = j;
temp = U(j, i);
}
}
U(index, i) = FOUND;
top_ten[k] = index;
}
cout << "For Concept "<<i+1<<" The top 10 words are: "<<endl;
for(int k: top_ten)
cout << vocab[k].c_str() <<endl;
for( int k = 0; k < 10; k++){
int index = 0;
float temp = V(0, i);
for(int j = 1; j<500; ++j){
if(temp <= V(j, i)){
index = j;
temp = V(j, i);
}
}
V(index, i) = FOUND;
top_ten[k] = index;
}
cout << "For Concept "<<i+1<<" The top 10 files are: "<<endl;
for(int k: top_ten)
cout << docs[k].c_str() <<endl;
}
return 0;
}
| true |
b7969f4c1dbb408401cb5ca020a77a9bc61a1c69 | C++ | Spark-NF/face-detector | /addpersondialog.cpp | UTF-8 | 948 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #include "addpersondialog.h"
#include "ui_addpersondialog.h"
AddPersonDialog::AddPersonDialog(QList<Person*> *persons, QList<Group *> *groups, QWidget *parent)
: QDialog(parent), ui(new Ui::AddPersonDialog), _groups(groups)
{
setModal(true);
ui->setupUi(this);
for (Group *group : *groups)
ui->comboGroup->addItem(group->name(), group->id());
int maxID = 0;
for (Person *person : *persons)
if (person->id() > maxID)
maxID = person->id();
ui->lineID->setText(QString::number(maxID + 1));
connect(this, &QDialog::accepted, this, &AddPersonDialog::emitPerson);
}
AddPersonDialog::~AddPersonDialog()
{
delete ui;
}
void AddPersonDialog::emitPerson()
{
Group *group = nullptr;
for (Group *gr : *_groups)
if (gr->id() == ui->comboGroup->currentData())
group = gr;
emit addPerson(new Person(ui->lineID->text().toInt(), ui->lineName->text(), group));
}
| true |
8d67b6f2fb2cd21510b487545eeca50b5773eb94 | C++ | trinhvo/OceanRendering | /Terrain.h | UTF-8 | 830 | 2.625 | 3 | [] | no_license | #ifndef _TERRAIN_H
#define _TERRAIN_H
#include "VertexArrayObject.h"
#include <glm/glm.hpp>
#include <vector>
using namespace glm;
class Terrain : public VertexArrayObject {
public:
Terrain(int resolution, int tileNumber, bool generateHeightValues);
Terrain(int resolution, int tileNumber, bool generateHeightValues, float frequency, float amplitude);
~Terrain();
void setHeight(int x, int z, float height);
float getHeightValue(float x, float z) const;
int calcIndex(int x, int z);
void setVAOPositions(bool generateHeight);
private:
void drawSimplePlane();
void generateHeight();
float getHeight(int x, int z) const;
float perlin2D(int x, int z);
float hash(vec2 v);
int mResolution;
int mTileNumber;
std::vector<float> mHeight;
float mFrequency;
float mAmplitude;
};
#endif
| true |
8106a78ba46f587ac99ec091d07f40002913ca0a | C++ | ThereWillBeOneDaypyf/Summer_SolveSet | /codeforces/cf_980_a.cpp | UTF-8 | 418 | 2.78125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
while(cin >> s)
{
int cnt = 0;
for(int i = 0;i < s.size();i ++)
{
char temp = s[i];
if(temp == '-')
cnt ++;
}
int ret = (int)s.size() - cnt;
if(ret == 0)
{
cout << "YES" << endl;
continue;
}
if(cnt % ret == 0)
cout << "YES" << endl;
else cout << "NO" << endl;
}
} | true |
d68a20b9562730ac903c2ea864c179020c4a2a4f | C++ | hect1995/Processing-Radar-Data | /data.hpp | UTF-8 | 1,824 | 2.609375 | 3 | [] | no_license | //
// data.hpp
// ubimet
//
// Created by Héctor Esteban Cabezos on 04/06/2020.
// Copyright © 2020 Héctor Esteban Cabezos. All rights reserved.
//
#ifndef data_hpp
#define data_hpp
#include <stdio.h>
#include <vector>
#include <string>
#include <map>
struct Spherical{
float latitude;
float longitude;
};
class Data{
private:
short int id; // 1 byte
char date[17];
short int Ny; // # rows
short int Nx; // # columns
short int L;
short int distance;
short int N;
std::map<short int, short int> quant_levels;
std::vector<std::vector<short int>> Pixels;
float max_lat;
float min_lat = 180;
float max_lon;
float min_lon = 180;
const char* input_filename;
const char* csv_filename;
static constexpr double v0 = 8.194; //(reference lon)
static constexpr double v1 = 50.437; //(reference lat)
static constexpr double v2 = 0;
static constexpr double v3 = 0;
static constexpr double v4 = 1018.18; // (meter / pixel)
static constexpr double v5 = 1018.18; //(meter / pixel)
public:
Data(const char* in_filename, const char* out_csv="output.csv");
std::vector<Spherical> convertCoordinates();
Spherical pixelToGeographical(int row, int col);
void plotImage(int Nx, int Ny, const std::vector<short int>& image, const std::vector<Spherical> &sph, int counter=0);
void obtainLimitsMap(const std::vector<Spherical> &sph);
static float productPh(int row, int col);
static float productLA(int row, int col);
void maxColumn(const std::vector<Spherical> &sph);
void createCsv(const std::vector<Spherical>& sph, const std::vector<short int>& value);
void obtain_results();
void readFile();
unsigned int writepng(const std::string& filename, int Nx, int Ny, const unsigned char* data);
};
#endif /* data_hpp */
| true |
1b4aed40ed62056101a93ec400b679eab698b703 | C++ | SanchitaMishra170676/STL100 | /VECTOR/vector-5.cpp | UTF-8 | 535 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define pb push_back
#define int long long
using namespace std;
// To print vector
void printvector(vector<ll> &v){
ll n = v.size();
for(int i=0;i<n;i++){
cout<<v[i]<<"\n";
}
}
// sort in reverse
bool rev(const &a, const &b)
{
return (a > b);
}
signed main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
vector<ll> v;
while(t--){
ll x;
cin>>x;
v.pb(x);
}
sort(v.begin(),v.end(),rev);
printvector(v);
}
| true |
d953570a3b0e327e4f526c31aa713e0df2cf2b63 | C++ | d2macster/leetcode-cpp | /src/E/3/E342_PowerFour.cpp | UTF-8 | 241 | 2.65625 | 3 | [] | no_license | //
// Created by Andrii Cherniak on 1/9/18.
//
class Solution {
public:
bool isPowerOfFour(int num) {
unsigned int mask = 0b10101010101010101010101010101010;
return num > 0 && (num & (num - 1)) == 0 && (num & mask) == 0;
}
}; | true |
e88a8b447796227d1bc8f78bc019aaa218cdee20 | C++ | TheOnlyJoey/vlc-vr | /include/label.h | UTF-8 | 3,275 | 2.8125 | 3 | [] | no_license | #ifndef LABEL_H
#define LABEL_H
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <GL/gl.h>
#include <usercontrol.h>
template <class Controller> class Label : public UserControl<Controller>
{
public:
Label(float x, float y, int fontSize,
std::string text, GLuint shaderProgram)
: UserControl<Controller>(x, y, 0, 0, shaderProgram),
text(text),
police(NULL), textSurface(NULL),
mustRenderText(true)
{
police = TTF_OpenFont("../timeless.ttf", fontSize);
glGenTextures(1, texture);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glEnable(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 1.0);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
~Label()
{
SDL_FreeSurface(textSurface);
TTF_CloseFont(police);
}
void draw()
{
if (this->getState() == UNVISIBLE)
return;
UserControl<Controller>::draw();
if (mustRenderText)
{
renderText();
mustRenderText = false;
}
/* Move to the control space. */
glPushMatrix();
glTranslatef(this->x, this->y, 0.f);
/* Draw the control */
// Alpha null to tell the shader to apply the texture.
glColor4f(0.f, 0.f, 0.f, 0.f);
glBindTexture(GL_TEXTURE_2D, texture[0]);
GLfloat vertexCoord[] = {
0.f, 0.f, 0.f,
0.f, this->height, 0.f,
this->width, this->height, 0.f,
this->width, 0.f, 0.f
};
GLfloat textureCoord[] = {
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
};
GLushort indices[] = {
0, 1, 2, 3
};
this->drawMesh(vertexCoord, textureCoord,
sizeof(vertexCoord) / sizeof(GLfloat) / 3,
indices, sizeof(indices) / sizeof(GLushort),
GL_QUADS);
glPopMatrix();
}
void renderText()
{
SDL_Color whiteColor = {255, 255, 255};
textSurface = TTF_RenderUTF8_Blended(police, text.c_str(), whiteColor);
if (textSurface != NULL)
{
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
textSurface->w, textSurface->h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, textSurface->pixels);
#define PIXEL_WORD_RATIO 0.001f
this->width = textSurface->w * PIXEL_WORD_RATIO;
this->height = textSurface->h * PIXEL_WORD_RATIO;
SDL_FreeSurface(textSurface);
}
}
void setText(std::string t)
{
text = t;
mustRenderText = true;
}
private:
GLuint texture[1];
std::string text;
bool mustRenderText;
TTF_Font *police;
SDL_Surface *textSurface;
};
#endif // LABEL_H
| true |
60c5f6f391853566a5a5bfd38937db08dfb5f835 | C++ | oysterkwok/Practice | /UVa OJ/Binary Trees/112.cpp | UTF-8 | 820 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
bool found;
int n;
bool play_tree(int);
bool play_tree(int sum) {
char ch;
cin >> ch;
string num_buf;
bool both_empty = true;
while (ch != ')') {
if (ch == '(') {
if (!play_tree(sum + atoi(num_buf.c_str()))) {
both_empty = false;
}
}
if (ch >= '0' && ch <= '9') {
num_buf += ch;
}
if (ch == '-' || ch == '+') {
num_buf += ch;
}
cin >> ch;
}
if (num_buf.size() == 0) {
return true;
}
else {
if (both_empty && n == (sum + atoi(num_buf.c_str()))) {
found = true;
}
return false;
}
}
int main() {
while (cin >> n) {
char ch;
cin >> ch;
while (ch != '(') {
cin >> ch;
}
found = false;
play_tree(0);
if (found) {
cout << "yes\n";
}
else {
cout << "no\n";
}
}
}
| true |
07d7aed152f9f935cef47072c758ec31a2d8b00a | C++ | Job-Colab/Coding-Preparation | /Day-62/Lavanya.cpp | UTF-8 | 371 | 2.96875 | 3 | [] | no_license | class Solution {
public:
int maximumWealth(vector<vector<int>>& accounts) {
int max=0;
for(int i=0;i<accounts.size();i++){
int amt=0;
for(int j=0;j<accounts[i].size();j++){
amt+=accounts[i][j];
}
if(amt>max){
max=amt;
}
}
return max;
}
};
| true |
951ce51d6c0c70a57367c06348de71879bff87f3 | C++ | imhdx/My-all-code-of-Vjudge-Judge | /POJ/2386/18602413_AC_32ms_1064kB.cpp | UTF-8 | 696 | 2.71875 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
using namespace std;
int dx[]={0,0,1,-1,1,-1,1,-1};
int dy[]={1,-1,0,0,1,-1,-1,1};
char str[102][102];
int n,m;
void dfs(int x,int y)
{
for (int i=0;i<8;i++){
int tx=x+dx[i];
int ty=y+dy[i];
if (tx<0||tx>=n||ty<0||ty>=m) continue;
if (str[tx][ty]=='.') continue;
str[tx][ty]='.';
dfs(tx,ty);
}
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=0;i<n;i++) scanf("%s",str[i]);
int cnt=0;
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (str[i][j]=='W'){
cnt++;
dfs(i,j);
}
}
}
printf("%d\n",cnt);
return 0;
}
| true |
229cc1cb981c0e4b314000022ef32055a4269211 | C++ | PeachOS/zserio | /compiler/extensions/cpp/runtime/src/zserio/VarUInt64Util.cpp | UTF-8 | 689 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | #include <limits>
#include "CppRuntimeException.h"
#include "StringConvertUtil.h"
#include "VarUInt64Util.h"
namespace zserio
{
namespace
{
template <typename T>
T convertVarUInt64(uint64_t value)
{
if (value > static_cast<uint64_t>(std::numeric_limits<T>::max()))
throw CppRuntimeException("VarUInt64 value (" + convertToString(value) +
") is out of bounds for conversion!");
return static_cast<T>(value);
}
}
int convertVarUInt64ToInt(uint64_t value)
{
return convertVarUInt64<int>(value);
}
size_t convertVarUInt64ToArraySize(uint64_t value)
{
return convertVarUInt64<size_t>(value);
}
} // namespace zserio
| true |
bf93ee9fb7277f67e09f3a7d745e45e9acb548a4 | C++ | XintongHu/leetcode | /CPP/IntergerToRoman.cpp | UTF-8 | 765 | 2.953125 | 3 | [] | no_license | class Solution {
public:
string intToRoman(int num) {
string ans = "", tmp;
int r, n = 0, i;
vector<string> roman = {"I", "V", "X", "L", "C", "D", "M"};
while (num != 0) {
tmp = "";
r = num%10;
num/=10;
if (r == 9) tmp += (roman[n] + roman[n + 2]);
else if (r < 9 && r >= 5) {
tmp += roman[n + 1];
for (i = 0; i < r - 5; ++i)
tmp += roman[n];
}
else if (r == 4) tmp += (roman[n] + roman[n + 1]);
else {
for (i = 0; i < r; ++i)
tmp += roman[n];
}
n += 2;
ans = tmp + ans;
}
return ans;
}
}; | true |
51c1494abc9f79fdff8332f8b16f581691219544 | C++ | mariokonrad/marnav | /test/marnav/seatalk/Test_seatalk_message_36.cpp | UTF-8 | 1,192 | 2.734375 | 3 | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | #include <marnav/seatalk/message_36.hpp>
#include <gtest/gtest.h>
namespace
{
using namespace marnav::seatalk;
class test_seatalk_message_36 : public ::testing::Test
{
};
TEST_F(test_seatalk_message_36, construction)
{
message_36 m;
}
TEST_F(test_seatalk_message_36, parse_invalid_data_size)
{
EXPECT_ANY_THROW(message_36::parse({1, 0x00}));
EXPECT_ANY_THROW(message_36::parse({2, 0x00}));
}
TEST_F(test_seatalk_message_36, parse_invalid_length)
{
EXPECT_ANY_THROW(message_36::parse({0x36, 0x01, 0x01}));
EXPECT_ANY_THROW(message_36::parse({0x36, 0x02, 0x01}));
}
TEST_F(test_seatalk_message_36, parse)
{
struct test_case {
raw data;
};
std::vector<test_case> cases{
{{0x36, 0x00, 0x01}},
};
for (auto const & t : cases) {
auto generic_message = message_36::parse(t.data);
EXPECT_TRUE(generic_message != nullptr);
if (!generic_message)
continue;
auto m = message_cast<message_36>(generic_message);
EXPECT_TRUE(m != nullptr);
if (!m)
continue;
EXPECT_EQ(message_id::cancel_mob_condition, m->type());
}
}
TEST_F(test_seatalk_message_36, write_default)
{
const raw expected{0x36, 0x00, 0x01};
message_36 m;
EXPECT_EQ(expected, m.get_data());
}
}
| true |
91a1630c07e09b92bf3fb2bb8acfb9f28e431cd6 | C++ | 8489545/SpaceEngine | /Space/ObjectMgr.cpp | UTF-8 | 1,361 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "ObjectMgr.h"
ObjectMgr::ObjectMgr()
{
}
ObjectMgr::~ObjectMgr()
{
}
void ObjectMgr::Release()
{
for (auto iter = m_Objects.begin(); iter != m_Objects.end(); iter++)
{
(*iter)->SetDestroy(true);
}
}
void ObjectMgr::DeleteCheak()
{
for (auto iter = m_Objects.begin(); iter != m_Objects.end();)
{
if ((*iter)->GetDestroy())
{
GameObject* temp = (*iter);
iter = m_Objects.erase(iter);
SafeDelete(temp);
}
else
{
++iter;
}
}
}
void ObjectMgr::CollisionCheak(GameObject* obj, const std::string tag)
{
for (auto& iter : m_Objects)
{
if (iter->m_Tag == tag)
{
RECT rc;
if (IntersectRect(&rc, &obj->m_Collision, &iter->m_Collision))
{
obj->OnCollision(iter);
iter->OnCollision(obj);
}
}
}
}
void ObjectMgr::DeleteObject(std::string tag)
{
for (auto& iter : m_Objects)
{
if (iter->m_Tag == tag)
{
iter->SetDestroy(true);
}
}
}
void ObjectMgr::Update()
{
DeleteCheak();
for (const auto& iter : m_Objects)
{
(iter)->Update();
}
}
void ObjectMgr::Render()
{
m_Objects.sort(stLISTsort());
for (const auto& iter : m_Objects)
{
(iter)->Render();
}
}
void ObjectMgr::AddObject(GameObject* obj, const std::string tag)
{
m_Objects.push_back(obj);
obj->SetTag(tag);
}
void ObjectMgr::RemoveObject(GameObject* obj)
{
if (obj)
obj->SetDestroy(true);
} | true |
811aee31e421fa2e59766b8d9c0fc10366a22263 | C++ | nitcse2018/daa-jerinjoseph121 | /DAA Assignment/Divide and Conquer Method/DivideandConquer.cpp | UTF-8 | 3,305 | 3.15625 | 3 | [] | no_license | //product multiplication using divide and conquer
//in this method instead of divind the whole polynomials together, we divide into parts
//there is only three polynomial multiplications of small degree taking place
//A=a1x + a0
//B=b1x + b0
//AB=a1b1x^2 + ((a1+a0)(b1+b0) - a1b1 - a0b0)x + a0b0
#include<iostream>
using namespace std;
int* PolyMul(int* a,int* b,int n1)
{
int n = 2*n1;
int k;
int dn=n1/2;
int* d0=new int[dn+1];
int* d1=new int[dn+1];
k=0;
for(int i=0;i<(dn+1);i++)//storing first half of poly 1 in d0
d0[i]=a[k++];
for(int i=0;i<(dn+1);i++)
d1[i]=0;
for(int i=0;k<n1+1;k++)//storing second half of poly 1 in d1
d1[i++]=a[k];
int en=n1/2;
int* e0=new int[en+1];
int* e1=new int[en+1];
k=0;
for(int i=0;i<(en+1);i++)//storing first half of poly 2 in e0
e0[i]=b[k++];
for(int i=0;i<(en+1);i++)
e1[i]=0;
for(int i=0;k<n1+1;k++)//storing second half of poly 2 in e1
e1[i++]=b[k];
int* d1e1=new int[dn+en+1];
for(int i=0;i<(dn+en+1);i++)
d1e1[i]=0;
for(int i=0;i<(dn+1);i++)//getting d1*e1 which is stored in d1e1
for(int j=0;j<(en+1);j++)
d1e1[i+j]+=d1[i]*e1[j];
int* d0e0=new int[dn+en+1];
for(int i=0;i<(dn+en+1);i++)
d0e0[i]=0;
for(int i=0;i<(dn+1);i++)//getting d0*e0 which is stored in d0e0
for(int j=0;j<(en+1);j++)
d0e0[i+j]+=d0[i]*e0[j];
int* d1d0e1e0=new int[dn+en+1];
for(int i=0;i<(dn+en+1);i++)
d1d0e1e0[i]=0;
for(int i=0;i<(dn+1);i++)//getting (d0+d1)*(e0+e1) which is stored in d1d0e1e0
for(int j=0;j<(en+1);j++)
d1d0e1e0[i+j]+=(d1[i]+d0[i])*(e1[j]+e0[j]);
int* c=new int[n+1];
int power;
if((n1+1)%2==0)
power=n1+1;
else
power=n1+2;
for(int i=0;i<(n+1);i++)
c[i]=0;
for(int i=0;i<(dn+en+1);i++)//adds d1e1*x^n in the final polynomial
c[i+power]+=d1e1[i];
for(int i=0;i<(dn+en+1);i++)//adds d1d0e1e0*x^(n/2) in the final polynomial
c[i+(power/2)]+=(d1d0e1e0[i]-d1e1[i]-d0e0[i]);
for(int i=0;i<(dn+en+1);i++)//adds d0e0 in the final polynomial
c[i]+=d0e0[i];
return c;//adding all these three terms gives us the final polnomial array which is returned back to the main function
}
int main()
{
int n1;
cout<<"\nEnter the degree of the two polynomials\n";
cin>>n1;
int* a=new int[n1+1];
cout<<"\nEnter the coefficients of the first polynomial from power 0 to n\n";
for(int i=0;i<n1+1;i++)//entering first polynomial
cin>>a[i];
int* b=new int[n1+1];
cout<<"\nEnter the coefficients of the second polynomial from power 0 to n\n";
for(int i=0;i<n1+1;i++)//entering second polynomial
cin>>b[i];
cout<<"\nPolynomial 1:\n\n";
cout<<a[0];
for(int i=1;i<n1+1;i++)
cout<<" + "<<a[i]<<"x^"<<i;
cout<<"\n\nPolynomial 2:\n\n";
cout<<b[0];
for(int i=1;i<n1+1;i++)
cout<<" + "<<b[i]<<"x^"<<i;
int *result= new int[n1+n1+1];
if(n1!=0)
result=PolyMul(a,b,n1);//the function does the multiplcation and stores in an array called result
else
result[0]=a[0]*b[0];
cout<<"\n\n\nProduct of Polynomial 1 and Polynomial 2:\n\n";
cout<<result[0];
for(int i=1;i<(n1+n1+1);i++)//printing the product of the polynomials
cout<<" + "<<result[i]<<"x^"<<i;
cout<<endl;
return 0;
}
| true |
cc5a6fceeac8175d4c3eb815e4bea86595d8f7ba | C++ | pliamoconnor/Personnal-Projects | /Unlimited/Unlimited/Graphics/Mesh/Mesh.cpp | UTF-8 | 239 | 2.546875 | 3 | [] | no_license | #include "Mesh.h"
Mesh::Mesh(Vector3 position, Vector2 uv, Vector3 normal)
{
m_VertexData = new VertexFormat(position, uv, normal);
}
Mesh::~Mesh()
{
if (m_VertexData != nullptr)
{
delete m_VertexData;
m_VertexData = nullptr;
}
} | true |
7cc382274a8819ff18eb8a35269febea8cc50cab | C++ | shivangigoel1302/leetcode_solutions | /number_of_good_leaf_node_pairs.cpp | UTF-8 | 1,054 | 3.203125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countPairs(TreeNode* root, int distance) {
int res = 0;
dfs(root, distance, res);
return res;
}
vector<int> dfs(TreeNode* root, int d, int& cnt){
if(!root) return {};
if(!root->left && !root->right) return vector<int>{0};
auto v1 = dfs(root->left, d, cnt), v2 = dfs(root->right, d, cnt);
for(auto& x:v1) x++;
for(auto& x:v2) x++;
for(int i=0, j=int(v2.size())-1;i<v1.size() && j>=0;i++){
while(j>=0 && v1[i]+v2[j]>d) j--;
cnt += j+1;
}
v1.insert(v1.end(), v2.begin(), v2.end());
sort(v1.begin(), v1.end());
return v1;
}
};
| true |
bb028facc99ee56b1fc66c50b3ede03ea63d2f63 | C++ | madil90/miro | /src/material.h | UTF-8 | 1,582 | 2.90625 | 3 | [] | no_license | #ifndef __MATERIAL_H__
#define __MATERIAL_H__
#include <list>
#include <string>
#include "miro.h"
#include "Vector.h"
class Material
{
public:
Material();
virtual ~Material();
virtual void PreCalc() {}
virtual Vector3 Shade (const Ray& ray, const HitInfo& hit,
Scene& scene) ;
void SetReflectence(Vector3& v) {mr = v;}
void SetTransmittance(Vector3& v) {mt = v;}
void SetIndex(float ind) {index = ind;}
void SetEmissive(Vector3& v) {me = v;}
float getIndex() const {return index;}
Vector3 getReflectance() const {return mr;}
Vector3 getTransmittance() const {return mt;}
Vector3 getEmissive() const {return me;}
virtual Vector3 getDiffuse() const {return Vector3(0,0,0);}
// material properties for reflectance
// and transmittance
Vector3 mr,mt;
Vector3 me;
float index;
};
class PhongMaterial : public Material
{
public:
PhongMaterial() : Material() {
ma = Vector3(0,0,0);
ms= Vector3(0,0,0);
md = Vector3(0,0,0);
msp = 10;
}
void SetAmbient(Vector3& v) {ma = v;}
void SetDiffuse(Vector3& v) {md = v;}
void SetSpecular(Vector3& v) {ms = v;}
void SetMetalness(float& v) {msp = v;}
virtual Vector3 getDiffuse() const {return md;}
void PreCalc() {}
Vector3 Shade (const Ray& ray, const HitInfo& hit,
Scene& scene) ;
protected:
// Material Properties in the following order
// ma = Ambient
// md = Diffuse
// ms = Specular
// msp = MetalNess
// mr = Reflectence
// mt = Transmittance
Vector3 ma,md,ms;
float msp;
};
#endif
| true |
b1be784044374acc2e391476fff59601da06acdb | C++ | nicolasbrailo/playingwithgtk | /gtk_helper/image.h | UTF-8 | 1,258 | 2.703125 | 3 | [] | no_license | #ifndef INCL_GTK_HELPER_IMAGE_H
#define INCL_GTK_HELPER_IMAGE_H
#include "general.h"
#include <gtk/gtk.h>
#include <string>
namespace Gtk_Helper {
class Image : Gtk_Object
{
GtkWidget *img;
public:
GtkWidget* get_raw_ui_ptr() { return this->img; }
operator GtkWidget* () { return this->img; }
Image(const std::string& path)
: img(gtk_image_new_from_file(path.c_str()))
{}
virtual ~Image()
{
gtk_widget_destroy(GTK_WIDGET(img));
}
protected:
void draw() { gtk_widget_show(img); }
void set_from_png_buff(unsigned len, const void* buf)
{
auto pb_loader = gdk_pixbuf_loader_new_with_type("png", NULL);
bool ok = gdk_pixbuf_loader_write(pb_loader, (const guchar*)buf, len, NULL);
ok = gdk_pixbuf_loader_close(pb_loader, NULL);
ok = ok; // TODO
auto pb = gdk_pixbuf_loader_get_pixbuf(pb_loader);
gtk_image_set_from_pixbuf(GTK_IMAGE(this->img), pb);
}
void set_from_file(const std::string &path)
{
gtk_image_set_from_file(GTK_IMAGE(this->img), path.c_str());
}
};
} /* Gtk_Helper */
#endif /* INCL_GTK_HELPER_IMAGE_H */
| true |
6f21d5166be2b976741055e5b768656f4a6109d1 | C++ | nqtwilford/Misc | /CppShortCode/TextQuery/Test2.cpp | UTF-8 | 542 | 2.59375 | 3 | [] | no_license | #include "Query.h"
#include "TextQuery.h"
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
TextQuery tq;
void print(TextQuery::line_no lno)
{
cout<<lno<<":"<<tq.text_line(lno)<<endl;
}
int main(int argc, char **argv)
{
ifstream in("infile.txt");
tq.read_file(in);
Query qry = ( Query("fiery") & Query("bird") | Query("wind") ) & ~Query("Her");
const set<TextQuery::line_no> &lines = qry.eval(tq);
cout<<qry<<endl;
for_each(lines.begin(), lines.end(), print);
return 0;
}
| true |
59bef909d7819a9e1ba044cc386f7bfd5f78e787 | C++ | Markisino/Pandemic | /view/show_deck.cpp | UTF-8 | 1,684 | 3.21875 | 3 | [] | no_license | #include <iomanip>
#include "show_deck.h"
auto show_deck::name() const -> std::string {
return "show-deck";
}
auto show_deck::description() const -> std::string {
return "Show deck information";
}
auto show_deck::run(context &ctx, args_type const &args, ostream_type &out) const -> void {
if (args.empty()) {
static constexpr auto col1 = 18;
static constexpr auto col2 = 8;
static constexpr auto fill = ' ';
out << std::left << std::setw(col1) << std::setfill(fill) << "DECK";
out << std::left << std::setw(col2) << std::setfill(fill) << "SIZE";
out << std::endl;
for (auto const &deck : ctx.decks) {
auto name = deck.first;
auto card_count = ctx.decks.size(name);
out << std::left << std::setw(col1) << std::setfill(fill) << name;
out << std::left << std::setw(col2) << std::setfill(fill) << card_count;
out << std::endl;
}
return;
}
auto const &deck = args.at(0);
try {
if (ctx.decks.size(deck) == 0) {
out << name() << ": '" << deck << "' is empty" << std::endl;
return;
}
for (auto i = ctx.decks.begin(deck); i != ctx.decks.end(deck); i++) {
out << *i << " ";
}
} catch (std::out_of_range const &) {
out << name() << ": '" << deck << "' does not exist" << std::endl;
}
try {
// Saved event card shows up at the end of line in bracket not counting as card ex. [airlift]
if (ctx.players.get_role(deck) == "contingency_planner"_h) {
for (auto i = ctx.decks.begin("contingency_planner"_h); i != ctx.decks.end("contingency_planner"_h); i++) {
out << "[" << *i << "]";
}
}
} catch (std::out_of_range const &) {
// Do nothing - get_role throws out_of_range if deck is not a player deck
}
out << std::endl;
} | true |
83ab1fdc13c2ac52a41a0fe5febd96e5684a3a2d | C++ | binsearch/code | /topcoder/584/Egalitarianism.cpp | UTF-8 | 4,987 | 2.8125 | 3 | [] | no_license | #line 2 "Egalitarianism.cpp"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <queue>
using namespace std;
class Egalitarianism
{
public:
int n;
std::vector<string> g;
int hit(int index){
std::vector<int> dist;
dist.assign(n,-1);
dist[index] = 0;
queue<int> bfs;
bfs.push(index);
while(!bfs.empty()){
int temp = bfs.front();
// cout << temp << " front" << endl;
bfs.pop();
string frnd = g[temp];
for(int i = 0; i < n; i++){
if(frnd[i] == 'Y'){
if(dist[i] == -1){
dist[i] = dist[temp] + 1;
bfs.push(i);
}
}
}
}
// for(int i = 0; i < n; i++)
// cout << dist[i] << endl;
sort(dist.begin(),dist.end());
// for(int i = 0; i < n; i++)
// cout << dist[i] << endl;
if(dist[0] == -1){
return -1;
}
return dist[n-1];
}
int maxDifference(vector <string> isFriend, int d)
{
n = isFriend.size();
g = isFriend;
int max = 0;
for(int i = 0; i < n; i++){
int len = hit(i);
if(len == -1){
return -1;
}
// cout << len << endl;
if(len > max)
max = len;
}
return max*d;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"NYN",
"YNY",
"NYN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 10; int Arg2 = 20; verify_case(0, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"NN",
"NN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = -1; verify_case(1, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"NNYNNN",
"NNYNNN",
"YYNYNN",
"NNYNYY",
"NNNYNN",
"NNNYNN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1000; int Arg2 = 3000; verify_case(2, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"NNYN",
"NNNY",
"YNNN",
"NYNN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 584; int Arg2 = -1; verify_case(3, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"NYNYYYN",
"YNNYYYN",
"NNNNYNN",
"YYNNYYN",
"YYYYNNN",
"YYNYNNY",
"NNNNNYN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; int Arg2 = 20; verify_case(4, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_5() { string Arr0[] = {"NYYNNNNYYYYNNNN",
"YNNNYNNNNNNYYNN",
"YNNYNYNNNNYNNNN",
"NNYNNYNNNNNNNNN",
"NYNNNNYNNYNNNNN",
"NNYYNNYNNYNNNYN",
"NNNNYYNNYNNNNNN",
"YNNNNNNNNNYNNNN",
"YNNNNNYNNNNNYNN",
"YNNNYYNNNNNNNNY",
"YNYNNNNYNNNNNNN",
"NYNNNNNNNNNNNNY",
"NYNNNNNNYNNNNYN",
"NNNNNYNNNNNNYNN",
"NNNNNNNNNYNYNNN"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 747; int Arg2 = 2988; verify_case(5, Arg2, maxDifference(Arg0, Arg1)); }
void test_case_6() { string Arr0[] = {"NY",
"YN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; int Arg2 = 0; verify_case(6, Arg2, maxDifference(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Egalitarianism ___test;
___test.run_test(-1);
system("pause");
}
// END CUT HERE
| true |
c7bd866f2358d93cece3634f9fe37b3a22d2fdf6 | C++ | YuhuiYin/CPP-Primer-Notes | /ch12/t12-7.cc | UTF-8 | 481 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <memory>
using namespace std;
shared_ptr<vector<int>> my_alloc(void) {
return make_shared<vector<int>>();
}
void fill(shared_ptr<vector<int>> p) {
int elem;
while (cin >> elem)
p->push_back(elem);
}
void print(shared_ptr<vector<int>> p) {
for (auto &e : *p)
cout << e << " ";
cout << endl;
}
int main() {
shared_ptr<vector<int>> p = my_alloc();
fill(p);
print(p);
return 0;
}
| true |
b377ef7bcd1045e63327c613959b82085a0837f1 | C++ | usnistgov/OOF1 | /XPPM2OOF/elector.C | UTF-8 | 3,524 | 2.515625 | 3 | [] | no_license | // -*- C++ -*-
// $RCSfile: elector.C,v $
// $Revision: 1.5 $
// $Author: langer $
// $Date: 2004-10-23 00:48:47 $
// Machinery to take care of homogeneity calculations.
// Elector classes are used to vote to find the most popular kind of
// pixel in a mesh triangle. There is only one of each type of
// Elector, so the constructors are private. These functions return
// the global Electors.
#include "adaptmesh.h"
#include "cell_coordinate.h"
#include "elector.h"
#include "goof.h"
#include "material.h"
void Elector::vote(const Cell_coordinate& pxl, double weight) {
nvotes += weight;
for(int j=0; j<catalog.capacity(); j++) {
if(sameparty(pxl, catalog[j])) {
abundance[j] += weight;
return;
}
}
// found a new category of pixel
catalog.grow(1, pxl);
abundance.grow(1, weight);
}
void Elector::tally() {
// find out who won the election
double max = 0;
int winnerno = -1;
for(int i=0; i<catalog.capacity(); i++) {
if(abundance[i] > max) {
max = abundance[i];
winnerno = i;
}
}
vote_fraction = max/nvotes;
winner_ = catalog[winnerno];
// get ready for next election
catalog.resize(0);
abundance.resize(0);
nvotes = 0;
}
//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//
// Elector functions to decide if two pixels are the same:
// are two lists of groups the same?
static int comparegroups(LinkList<PixelGroup*> &g1, LinkList<PixelGroup*> &g2) {
if(g1.size() != g2.size()) return 0;
for(LinkListIterator<PixelGroup*> i1=g1.begin(), i2=g2.begin();
!i1.end() && !i2.end();
++i1, ++i2)
// if(g1[i1]->query_name() != g2[i2]->query_name())
if(g1[i1] != g2[i2])
return 0;
return 1;
}
int GroupElector::sameparty(const Cell_coordinate &c1,
const Cell_coordinate &c2) const
{
Material *mat1 = current_goof->material[c1];
Material *mat2 = current_goof->material[c2];
if(mattype || mattypeparam) {
// if one material isn't defined, they aren't the same
if((mat1 && !mat2) || (mat2 && !mat1)) return 0;
if(mat1 && mat2) {
// do the pixels have the same material type?
if(mattype && mat1->tag() != mat2->tag()) return 0;
// do the pixels have the same gray value?
if(gray && mat1->query_gray() != mat2->query_gray()) return 0;
// are the materials exactly the same?
if(mattypeparam && !(*mat1 == *mat2)) return 0;
}
}
if(groupmemb) { // are the pixels in the same groups?
if(!comparegroups(current_goof->pixelgrouplist[c1],
current_goof->pixelgrouplist[c2]))
return 0;
}
return 1;
}
int MaterialElector::sameparty(const Cell_coordinate &c1,
const Cell_coordinate &c2) const
{
Material *mat1 = current_goof->material[c1];
Material *mat2 = current_goof->material[c2];
// if one material isn't defined, they aren't the same
if((mat1 && !mat2) || (mat2 && !mat1)) return 0;
if(mat1 && mat2) {
// do the pixels have the same gray value?
if(gray && mat1->query_gray() != mat2->query_gray()) return 0;
// if both are defined, but they're different, they're not the same
if(!(*mat1 == *mat2)) return 0;
}
if(groupmemb) { // are the pixels in the same groups?
if(!comparegroups(current_goof->pixelgrouplist[c1],
current_goof->pixelgrouplist[c2]))
return 0;
}
return 1;
}
//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//
int GroupElector::badrules() {
return !(mattype || mattypeparam || groupmemb);
}
| true |
8ea7c44ca7933329b76fd891a6f3293bc424bdfa | C++ | IzhakLatovski/programming-snippets | /C++/cppMatrix.cpp | UTF-8 | 3,201 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
class Matrix {
private:
int m_rows;
int m_columns;
int m_totalSize;
int* m_ptValues;
public:
Matrix(int rows, int columns);
~Matrix();
Matrix(const Matrix& temp);
Matrix& operator=(const Matrix& temp);
int& operator()(int row, int column);
Matrix operator*(int scalar);
Matrix operator+(const Matrix& temp);
Matrix operator*(const Matrix& temp);
void printMatrix();
};
Matrix::Matrix(int rows, int columns) : m_rows(rows), m_columns(columns) {
m_totalSize = m_rows * m_columns;
m_ptValues = new int[m_totalSize]();
}
Matrix::~Matrix() {
if (m_ptValues) {
delete[] m_ptValues;
}
}
Matrix::Matrix(const Matrix& temp) : m_rows(temp.m_rows), m_columns(temp.m_columns) {
m_totalSize = temp.m_totalSize;
m_ptValues = new int[temp.m_totalSize]();
memcpy(m_ptValues, temp.m_ptValues, temp.m_totalSize * sizeof(int));
}
Matrix& Matrix::operator=(const Matrix& temp) {
if (&temp == this) {
return *this;
}
if (m_totalSize == temp.m_totalSize) {
memcpy(m_ptValues, temp.m_ptValues, temp.m_totalSize * sizeof(int));
} else {
delete[] m_ptValues;
m_ptValues = new int[temp.m_totalSize]();
memcpy(m_ptValues, temp.m_ptValues, temp.m_totalSize * sizeof(int));
}
m_rows = temp.m_rows;
m_columns = temp.m_columns;
m_totalSize = temp.m_totalSize;
return *this;
}
int& Matrix::operator()(int row, int column) {
if (row >= m_rows || row<0 || column >= m_columns || column<0) {
printf("Index out of bounds");
}
return m_ptValues[row * m_columns + column];
}
Matrix Matrix::operator*(int scalar) {
Matrix result(m_rows, m_columns);
for (int i = 0; i < m_totalSize; i++) {
result.m_ptValues[i] = m_ptValues[i] * scalar;
}
return result;
}
Matrix Matrix::operator+(const Matrix& temp) {
if (m_rows != temp.m_rows || m_columns != temp.m_columns) {
cout << "Matrix sizes are not similar" << endl;
}
Matrix result(m_rows, m_columns);
for (int i = 0; i < m_totalSize; i++) {
result.m_ptValues[i] = this->m_ptValues[i] + temp.m_ptValues[i];
}
return result;
}
void Matrix::printMatrix() {
std::string delimiter = "";
for (int i = 0; i < m_rows; i++) {
delimiter = "";
for (int j = 0; j < m_columns; j++) {
cout << delimiter << m_ptValues[i * m_columns + j];
delimiter = ",";
}
cout << endl;
}
cout << endl;
}
Matrix Matrix::operator*(const Matrix& temp) {
if (m_columns != temp.m_rows) {
cout<<"Matrix sizes are not similar"<<endl;
}
Matrix result(m_rows, temp.m_columns);
int sum;
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < temp.m_columns; j++) {
sum = 0;
for (int k = 0; k < m_rows; k++) {
sum += this(i, k) * temp(k,j);
}
result(i,j) = sum;
}
}
return result;
} | true |
49905d823bc589a25bb68232137a369f64c0cea7 | C++ | pennkao/algorithm | /随机算法/001randN.cpp | UTF-8 | 1,002 | 3.921875 | 4 | [] | no_license | /* 题目:已知随机数rand(), 以概率p产生0,以概率1-p产生1,现在要求设计一个新的随机函数RandN(),
* 以等概率产生1-n之间的数。
* 思路:首先这个rand()概率函数是假定存在的,
* TIME:2015-4-28
*/
/* 等概率产生0-1
* 0、1实际上是二进制数,那么使用rand()产生两个0的概率是
*/
int Rand()
{
int i = 2;
//00:p^2
//01:p(1-p)
//10:(1-p)p
//11:(1-p)^2
int n = 2*rand()+rand(); //转换成进制数
if(n == 1) //p(1-p)
return 0;
else if(n == 2) //(1-p)p
return 1;
}
/* 实现2 */
int Rand()
{
int n1 = rand();
int n2 = rand();
if(n1 == 0 && n2 == 1)
return 0;
else if(n1 == 1 && n2 == 0)
return 1;
}
/* 等概率产生1-n之间的数 */
int RandN(int n)
{
int k = log2l(n)+1; //n的二进制位数
int res = 0;
for(int i = 0; i < k; ++)
res = (res << i) + rand();
if(res < n) //丢掉大于n的数, 重新产生数
RandN();
return res + 1;
} | true |
87ef13e24ae81da5f3984f1a6d4d3c246a8e83b1 | C++ | tdyx87/moon-core | /moon/net/ServerSocket.h | UTF-8 | 1,428 | 2.71875 | 3 | [] | no_license | /**
Copyright 2018, Mugui Zhou. All rights reserved.
Use of this source code is governed by a BSD-style license
that can be found in the License file.
Author: Mugui Zhou
*/
#ifndef MOON_NET_SERVERSOCKET_H_
#define MOON_NET_SERVERSOCKET_H_
#include <moon/noncopyable.h>
#include <moon/net/InetAddress.h>
namespace moon
{
namespace net
{
class InetAddress;
/**
* 一个ServerSocket对象代表一个被监听的socket,不同于@Socket
*/
class ServerSocket : noncopyable
{
public:
ServerSocket(uint16_t port, bool nonblock = true, bool reuseAddr = true);
ServerSocket(const InetAddress& localAddress, bool nonblock = true, bool reuseAddr = true);
~ServerSocket();
int getFd()const {return mSocketFd;}
int listen();
/**
@description:
Accept a connection on a socket.
@param: pobjPeerAddr
input and output parameter, which will be changed by accept
@return:
On success, returns a non-negaive integer that is a descriptor for the accepted socket,
which has been set to non-block and close-on-exec, *pobjPeerAddr is assigned.
On error, -1 is returned, and *pobjPeerAddr is untouched.
*/
int accept(InetAddress* peerAddr);
int setReuseAddr(bool on);
private:
int init(bool reuseAddr);
int bind();
private:
int mSocketFd;
InetAddress mLocalAddress;
bool mReuseAddr;
};
} //~ namespace net
} //~ namespace moon
#endif // ~MOON_NET_SERVER_SOCKET_H_ | true |
9e8808a4984dec043a6365847a2f6cdb7f693a7a | C++ | shubhampathak09/codejam | /30 days training for beginners/Problem_Bank_adhoc/ith_bit.cpp | UTF-8 | 228 | 2.609375 | 3 | [] | no_license | // check ith bit set or not
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=5; // 101
//check if 0th bit is set or nit
int i=1;
int ans=n & (1<<i);
if(ans)
cout<<ans;
else
cout<<"ith bit is not set";
}
| true |
3be09d9b3d00cd2613c33b55832fe52a2925490a | C++ | xMijumaru/RamosKevin_CSC5_SPRING2018__ | /Assignments/Assignment_5/Savitch_9thEdition_Chap5_PracProj6_Shootergame/main.cpp | UTF-8 | 2,188 | 3.484375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Kevin Ramos
* Created on April 26th, 2018, 12:10 PM
* Purpose: Shooter Program
*/
//System Libraries
#include <iostream> //I/O Library -> cout,endl
#include <iomanip> //Format Library
#include <cstdlib> //Srand function
#include <ctime> //Time function
#include <cmath> //Power function
using namespace std;//namespace I/O stream library created
//User Libraries
//Global Constants
//Math, Physics, Science, Conversions, 2-D Array Columns
//Function Prototypes
float frand();//Probability from 0 to 1
bool shoot(float);
void shoot(bool, float, bool &,bool &);
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
bool aLive,bLive,cLive;
char remain;
float aPk,bPk,cPk;
int aCnt,bCnt,cCnt,nGames;
//Initial Variables
aCnt=bCnt=cCnt=0;
aPk=1.0f/3.0f;
bPk=1.0f/2.0f;
cPk=1.0f;
nGames=1000;
for(int game=1;game<=nGames;game++){
//Initialize Life
aLive=bLive=cLive=true;
//Map/Process Inputs to Outputs
do{
shoot(aLive,aPk,cLive,bLive);
shoot(bLive,bPk,cLive,aLive);
shoot(cLive,cPk,bLive,aLive);
remain=aLive+bLive+cLive;
}while(remain>1);
aCnt+=aLive;
bCnt+=bLive;
cCnt+=cLive;
}
//Output the results
cout<<"Aaron Pk = "<<aPk<<endl;
cout<<"Bob Pk = "<<bPk<<endl;
cout<<"Charlie Pk = "<<cPk<<endl;
cout<<"Out of "<<nGames<<" games"<<endl;
cout<<"Aaron Lives "<<aCnt<<" times"<<endl;
cout<<"Bob Lives "<<bCnt<<" times"<<endl;
cout<<"Charlie Lives "<<cCnt<<" times"<<endl;
cout<<"Game Check = "<<aCnt+bCnt+cCnt<<" games"<<endl;
//Exit program!
return 0;
}
void shoot(bool aLive, float aPk, bool &cLive,bool &bLive){
if(aLive){
if(cLive) cLive=shoot(aPk);
else if(bLive) bLive=shoot(aPk);
}
}
bool shoot(float pk){
if(frand()>pk)return true;
return false;
}
float frand(){
static float MAXRAND=pow(2,31)-1;
return rand()/MAXRAND;
} | true |
275c7d2123519e87f49ae31f00e3b727ed5aa955 | C++ | UgolnikovAR/FortTE | /main.cpp | WINDOWS-1251 | 4,070 | 2.8125 | 3 | [] | no_license | //#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
#include "Data.cpp"
int main()
{
DataClass data;
/*
data.object[0].field[0] = "CMake\0";
data.object[0].field[0].print('\r');
data.object[0].field[1] = 126;
data.object[0].field[1].print('\r');
data.object[0].field[2] = float(89.7);
data.object[0].field[2].print('\r');
*/
/*
std::vector<int> vec;
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
std::vector<int>::iterator iter;
iter = vec.begin();
vec.insert(iter, 2);
vec.erase(1);
*/
//---------------------------------------open file for restore
std::ofstream fin("save.txt");
fin.close();
//---------------------------------------programm_loop
std::string str;
std::string screen_str;
std::string str_create = "create";
std::string str_delete = "delete";
std::string str_minus_o = "-o";
std::string str_minus_f = "-f";
std::string str_field = "field";
std::string str_done = "done";
bool create_m = false;
bool delete_m = false;
bool minus_o_m = false;
bool minus_f_m = false;
bool command = false;
char key = 0; //bufer for input symbol
while(1)
{
//---------------------------draw window
//std::cout << str << std::endl;
//std::cout << screen_str;
//---------------------------get input command
//general commands
if(str == str_create)
{
std::cout << "\n\tUsed command create" << std::endl;
create_m = true;
//-----
screen_str += ' ';
command = true;
str = "";
}
else if(str == str_delete)
{
std::cout << "\n\tUsed command delete" << std::endl;
delete_m = true;
//-----
screen_str += ' ';
command = true;
str = "";
}
//keys for commands
if(str == str_minus_o)
{
std::cout << "\n\tUsed key minus o" << std::endl;
minus_o_m = true;
//-----
screen_str += ' ';
command = true;
str = "";
}
else if(str == str_minus_f)
{
std::cout << "\n\tUsed key minus f" << std::endl;
minus_f_m = true;
//-----
screen_str += ' ';
command = true;
str = "";
}
//sub commands
if(str == str_field)
{
std::cout << "\n\tUsed sub command field" << std::endl;
//-----
screen_str += ' ';
command = true;
str = "";
}
if(str == str_done)
{
std::cout << "\n\tUsed sub command done" << std::endl;
//-----
screen_str += ' ';
command = true;
str = "";
}
//---------------------------action
/*
* create_m
* delete_m
* minus_o_m
* minus_f_m
*/
// create -o : data.object.push_back(stobject)
// create -f : data.object[curobject()].push_back(stfield)
// delete -o : data.object[curobject()].clear()
// delete -f : data.object[curobject()].field[curfield()].
//---------------------------user input
key = 0;
if(command)
{
while(char ch = getch() != ' ');
command = false;
system("cls");
}
else
{
key = getche();
//virtual window
str += key;
screen_str += key;
//clear virtual window
if(key == '\r')
{
screen_str = "";
str = "";
}
}
//---------------------------
}
system("pause");
return 0;
}
| true |
cdb1b68871301e24dc7673dfbf5dea79b153645b | C++ | JediJeremy/unorthodox-arduino | /Unorthodox/examples/tokenfs-ramdrive.cpp | UTF-8 | 4,522 | 2.515625 | 3 | [] | no_license | #include <unorthodox.h>
unsigned long debug_count = -1;
unsigned long stop_count = -1;
// create a 1024 byte buffer
byte storage[1024];
// wrap it in a virtual page
MemoryPage store(storage);
// create tokenfs storage
TokenFS fs(&store,1024,192);
// remember token state
byte token_state[256];
const int check_tokens = 192;
int block_size = 0;
int block_mask = 7;
void setup() {
// initialize serial port
Serial.begin(9600);
delay(10000);
// leonardo - wait for connection
while(!Serial) { }
memset(token_state,0,256); // clear the token state
// add a selection of records to the store
Serial.print("\n creating blocks...");
for(int i=0; i<check_tokens; i++) {
writeblock(i);
if(!checkblocks(false)) checkblocks(true);
}
// dump the record store in it's initial state
checkblocks(true);
}
bool more = true;
int next = 0;
int dot_count = 0;
int line_count = 200;
unsigned long loop_count = 0;
void loop() {
if(more) {
// add the block again
bool wr = writeblock(next++);
if(next>=check_tokens) next = 0;
more = checkblocks(loop_count >= debug_count);
if(loop_count < debug_count) {
if(dot_count==0) {
if(line_count==0) {
line_count = 200;
checkblocks(true); // debug
}
line_count--;
Serial.print("\n"); Serial.print(loop_count);
dot_count=50;
}
dot_count--;
if(more) {
Serial.print(wr?'.':'/');
if(dot_count==0) {
Serial.print(" used:"); Serial.print(fs.used);
Serial.print(" updates:"); Serial.print(fs.updates);
}
} else {
Serial.print('!');
// debug the broken state
checkblocks(true);
}
}
loop_count++;
if(loop_count>=stop_count) more = false;
}
}
bool writeblock(byte token) {
byte block[16];
// the length will be based on the last three digits.
// int len = (token & 7) + 1;
// the length will be the next in the sequence
// int len = block_size + 1;
// block_size = (block_size+1) & block_mask;
// block size is random
int len = random(6) + 1;
// fill the block with the token byte
memset(block,token,len);
// write it to the filesystem
MemoryPage page(block);
if(loop_count < debug_count) {
// Serial.print('W'); Serial.print(token); // Serial.print(' ');
} else {
Serial.print("\n Writing block "); Serial.print(token); // Serial.print(' ');
}
if( fs.token_write(token, &page, len) ) {
// record if the block is empty or not
token_state[token] = len - 1;
return true;
} else {
// Serial.print("\n Write Failed ");
token_state[token] = 0;
return false;
}
}
bool checkblocks(bool debug) {
bool result = true;
// mark all tokens as not found yet
byte token_count[256]; memset(token_count,0,256);
// for(int i=0; i<256; i++) token_state[i] |= 0x01;
if(debug) Serial.print("\n ============================== ");
// second pass: load all the entires in journal order from the head to tail.
fs.pass_reset();
while(fs.i_more) {
fs.pass_next();
if(fs.i_valid) {
if(debug) {
Serial.print("\n block:"); Serial.print(fs.i_block-1); Serial.print(":"); Serial.print(fs.i_size+5);
Serial.print(" ");
}
for(int i=0; i<fs.i_size; i++) {
byte b = fs.page->read_byte(fs.i_block+i);
if(debug) Serial.print(b);
if(i!=0) {
// mark off this token as found
token_count[b]++;
}
if(debug) Serial.print((i==0)?'.':' ');
}
}
}
// go through the tokens we were tracking
for(int i=0; i<check_tokens; i++) {
if( (token_count[i]==0) && (token_state[i]!=0)) {
if(debug) {
Serial.print("\n missing:"); Serial.print(i);
}
result = false;
} else {
// check that the expected length is still correct
if(token_state[i] != fs.token_size(i)) {
if(debug) {
Serial.print("\n incorrect length:"); Serial.print(i);
Serial.print(" put:"); Serial.print(token_state[i]);
Serial.print(" got:"); Serial.print(fs.token_size(i));
}
result = false;
}
}
}
if(debug) {
Serial.print("\n head:"); Serial.print(fs.head);
Serial.print(" tail:"); Serial.print(fs.tail);
Serial.print(" next:"); Serial.print(fs.next);
Serial.print(" used:"); Serial.print(fs.used);
Serial.print(" updates:"); Serial.print(fs.updates);
}
return result;
}
| true |
b84ac4115239026c338c4b2fc86d7500d2c4ff53 | C++ | Yaman8/Sorting-Visualizer | /Project1/Project1/insertion sort.cpp | UTF-8 | 1,548 | 2.671875 | 3 | [] | no_license | //#include<iostream>
//#include<SFML/Graphics.hpp>
//#include<limits.h>
//#include<Windows.h>
//#define size 800
//using namespace std;
//
//int random = 0, pass = 1, itr = 0, temp = 0, lim = 799;
//
//struct element {
// int hei;
// int pos;
//}num[800];
//
//
//
//int main() {
// sf::RenderWindow window(sf::VideoMode(800, 600), "Insertion Sort");
// sf::Event event;
// sf::Texture f1;
// sf::Sprite s1;
// sf::RectangleShape rect;
// int j;
//
// f1.loadFromFile("t1.png");
// s1.setTexture(f1);
// rect.setPosition(sf::Vector2f(2, 178));
// rect.setFillColor(sf::Color(255, 0, 0));
//
// srand(time(NULL));
// while (window.isOpen()) {
// while (window.pollEvent(event)) {
// if (event.type == sf::Event::Closed) {
// window.close();
// }
// }
//
// if (pass == 1) {
// for (int i = 0; i < 800; i++) {
// random = 1 + rand() % 600;
// num[i].pos = i;
// num[i].hei = random;
// if (i == 799) {
// pass = 2;
// }
// }
// }
//
// if (pass == 2) {
// temp = num[itr].hei;
// j = itr - 1;
// while ((temp < num[j].hei) && (j >= 0)) {
// num[j + 1].hei = num[j].hei;
// j--;
// }
// num[j + 1].hei = temp;
// }
//
// window.clear(sf::Color::Black);
// window.draw(s1);
// for (int i = 0; i < 800; i++) {
// rect.setFillColor(sf::Color(255, 0, 0));
// rect.setPosition(num[i].pos, 600);
// rect.setSize(sf::Vector2f(2, num[i].hei));
// rect.setRotation(180);
// window.draw(rect);
// }
// window.display();
// itr++;
// if (itr >= lim) {
// itr = 0;
// }
// }
// return 0;
//} | true |
47228a1e9b88cf3c790a98a3d3be61ec1d65158f | C++ | johnjacobpeters/cryoET | /Tom_Toolbox/tom_dev/IOfun/FileTool.cpp | UTF-8 | 42,436 | 2.515625 | 3 | [] | no_license | // FileTool.cpp: implementation of the FileTool class.
//
//////////////////////////////////////////////////////////////////////
#include "FileTool.h"
//#include "File.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define SIZEOF_EMVECTOR_IN_FILE 6312
/* TIFF FORMAT NUMBERS */
#define TYPE_BYTE 1
#define TYPE_ASCII 2
#define TYPE_SHORT 3
#define TYPE_LONG 4
#define TYPE_RATIONAL 5
#define TYPE_SBYTE 6
#define TYPE_UNDEFINED 7
#define TYPE_SSHORT 8
#define TYPE_SLONG 9
#define TYPE_SRATIONAL 10
#define TYPE_FLOAT 11
#define TYPE_DOUBLE 12
#define TAG_TEM_DATA 37706 // TVIPS tag 1
#define TAG_OVL_DATA 37707 // TVIPS tag 2
#define ROWS_PER_STRIP 1 // use always 1 row per TIFF strip
// In this macro I use this simple formula because 2000 is also a schaltjahr
#define IS_SCHALTJAHR(j) ( (((j)/4)*4) == (j) )
#define RETURN_WITH_ERROR(txt, err) {printf(txt); return ( err ); }
#define RETURN_WITH_ERRORV(txt) {printf(txt); return; }
CFileTool::CFileTool()
{
}
CFileTool::~CFileTool()
{
}
/*
* CLU:
*
* Read the data from a given TIFF file and fill - if the file contains the data - the
* EM-Vector
*/
void CFileTool::Swapper(char *cp, long lLen)
{
char c;
if( lLen == 2 )
{
c = cp[0];
cp[0] = cp[1];
cp[1] = c;
}
if( lLen == 4 )
{
c = cp[0];
cp[0] = cp[3];
cp[3] = c;
c = cp[1];
cp[1] = cp[2];
cp[2] = c;
}
}
void CFileTool::ConvertV1ToV2( void *p, void *p2 )
{
//
// This function evaluates the version 1 header of the TVIPS TIFF tag and converts it as good as possible
// into the version 2 header.
//
TIFF_DATA *pTIFF_Data;
pTIFF_Data = (TIFF_DATA*)p2;
EMVECTOR *pEMV;
int i;
pEMV = (EMVECTOR *)p;
if( pTIFF_Data!= NULL )
pEMV->ud_v2.lImgDataType = (pTIFF_Data->BitsPerSample==8?1:3); // 8bit->DT_UCHAR, 16bit->DT_SHORT
ApplyUnicodeString( (char*)&pEMV->ud_v2.szImgName[0],""); // image name
ApplyUnicodeString( (char*)&pEMV->ud_v2.szImgFolder[0],""); // path to image
pEMV->ud_v2.lImgSizeX = (long)pEMV->ud_v1.lCCDPixelXY; // images in EMMENU 3.0 are 2dim and square !!!
pEMV->ud_v2.lImgSizeY = (long)pEMV->ud_v1.lCCDPixelXY; // images in EMMENU 3.0 are 2dim and square !!!
pEMV->ud_v2.lImgSizeZ = 0;
pEMV->ud_v2.lImgSizeE = 0;
long lDay, lMonth, lYear;
GetDateInformation( pEMV->ud_v1.lDate, &lDay, &lMonth, &lYear );
pEMV->ud_v2.lImgCreationDate = (65536*lYear + 256*lMonth + lDay);
pEMV->ud_v2.lImgCreationTime = static_cast<long>(pEMV->ud_v1.lTime*.01); // time ( from 1/100 s into s )
ApplyUnicodeString( (char*)&pEMV->ud_v2.szImgComment[0],&pEMV->ud_v1.strComment[0]); // image comment
ApplyUnicodeString( (char*)&pEMV->ud_v2.szImgHistory[0],""); // image history
pEMV->ud_v2.lImgType = 0; // 0=image
pEMV->ud_v2.lImgDisplay = 0; // 0=display as grey value image
// The following formula contains some multiplication and division factors
// by 1000 or 10000, respectively. They come from the different units, the
// individual structure elements use. For better readibility they remain in
// the code:
// ud_v1.lCCDSinglePixelSize * 1000 -> pixelsize in nm
// ud_v1.lElOptMag*1000.f -> real mag
// (ud_v1.lPostMag*0.0001) -> real postmag
pEMV->ud_v2.fImgDistX =
pEMV->ud_v2.fImgDistY = ((pEMV->ud_v1.lCCDSinglePixelSize * 1000)*pEMV->ud_v1.lCCDBinningFactor)/(pEMV->ud_v1.lElOptMag*1000.f*(pEMV->ud_v1.lPostMag*0.0001));
pEMV->ud_v2.fImgDistZ = 0.f;
pEMV->ud_v2.fImgDistE = 0.f;
ApplyUnicodeString( (char*)&pEMV->ud_v2.szTemType[0],""); // TEM name
pEMV->ud_v2.fTemHT = pEMV->ud_v1.lHighTension*1000.f; // HT
pEMV->ud_v2.lTemMode = 0; // bright field
pEMV->ud_v2.fTemMagScr = pEMV->ud_v1.lElOptMag*1000.f; // mag
pEMV->ud_v2.fTemMagCor = 1.f; // new factor in EM4, so set it to 1.0
pEMV->ud_v2.fTemMagPst = pEMV->ud_v1.lPostMag*.0001f; // postmag
pEMV->ud_v2.lTemStgType = 0; // 0 = manual
pEMV->ud_v2.lTemShutter = 0; // 0 = ???
ApplyUnicodeString( (char*)&pEMV->ud_v2.szCamType[0],"EMMENU 3.0 image"); // camera name
pEMV->ud_v2.fCamPixel[0] = pEMV->ud_v1.lCCDSinglePixelSize * 1000;
pEMV->ud_v2.fCamPixel[1] = pEMV->ud_v1.lCCDSinglePixelSize * 1000;
pEMV->ud_v2.lCamOffX = static_cast<long>(pEMV->ud_v1.lCCDOffsetX);
pEMV->ud_v2.lCamOffY = static_cast<long>(pEMV->ud_v1.lCCDOffsetY);
pEMV->ud_v2.lCamBinX = static_cast<long>(pEMV->ud_v1.lCCDBinningFactor);
pEMV->ud_v2.lCamBinY = static_cast<long>(pEMV->ud_v1.lCCDBinningFactor);
pEMV->ud_v2.fCamExpTime = pEMV->ud_v1.lCCDExposureTime;
pEMV->ud_v2.fCamGain = pEMV->ud_v1.lCCDGain;
pEMV->ud_v2.fCamSpeed = pEMV->ud_v1.lCCDReadOutSpeed;
ApplyUnicodeString( (char*)&pEMV->ud_v2.szCamFlat[0],""); // flat image link
pEMV->ud_v2.fCamSense = pEMV->ud_v1.lCCDSensitivity;
pEMV->ud_v2.fCamDose = 0.f;
ApplyUnicodeString( (char*)&pEMV->ud_v2.szAdaTietzSpecInfo[0],""); // tecnai specific data 1
ApplyUnicodeString( (char*)&pEMV->ud_v2.szAdaTietzMicInfo[0],""); // tecnai specific data 2
for( i=0; i<32; i++ )
{
pEMV->ud_v2.fImgMisc[i] = 0;
pEMV->ud_v2.fTemAberr[i] = 0;
pEMV->ud_v2.fTemEnergy[i] = 0;
pEMV->ud_v2.fTemMisc[i] = 0;
pEMV->ud_v2.fCamMisc[i] = 0;
if( i< 16 )
{
pEMV->ud_v2.fImgScaling[i] = 0;
}
if( i < 7 )
{
pEMV->ud_v2.fTemTiling[i] = 0;
}
if( i < 5 )
{
pEMV->ud_v2.fTemStgPos[i] = 0;
}
if( i < 3 )
{
pEMV->ud_v2.fTemIllum[i] = 0;
}
if( i < 2 )
{
pEMV->ud_v2.fTemImgShift[i] = 0;
pEMV->ud_v2.fTemBeamShift[i] = 0;
pEMV->ud_v2.fTemBeamTilt[i] = 0;
}
}
}
void CFileTool::ApplyUnicodeString( char *cpDst, char *cpSrc )
{
while( (*cpSrc) != 0 )
{
*cpDst = *cpSrc;
cpDst++;
*cpDst = 0;
cpDst++;
cpSrc++;
}
*cpDst = 0;
cpDst++;
*cpDst = 0;
cpDst++;
}
void CFileTool::GetDateInformation( long lSince1_1_1970, long *lpDay, long *lpMonth, long *lpYear )
{
long lDay, lMonth, lYear, lDaysLeft;
lYear = 1970;
lMonth = 1;
lDay = 1;
*lpDay = lDay;
*lpMonth = lMonth;
*lpYear = lYear;
lDaysLeft = lSince1_1_1970+1; // 1.1.1970 is day 1
if( lDaysLeft >= 0 )
{
lYear = 1970;
while( lDaysLeft > 0 )
{
if( IS_SCHALTJAHR(lYear-1) && lDaysLeft > 366 )
{
lYear++;
lDaysLeft-= 366;
continue;
}
if( lDaysLeft > 365 )
{
lYear++;
lDaysLeft-= 365;
continue;
}
*lpYear = lYear;
break;
}
if( IS_SCHALTJAHR( lYear) )
{
if( lDaysLeft >= 336 ){ *lpMonth = 12; *lpDay = lDaysLeft-335; return; }
if( lDaysLeft >= 306 ){ *lpMonth = 11; *lpDay = lDaysLeft-305; return; }
if( lDaysLeft >= 275 ){ *lpMonth = 10; *lpDay = lDaysLeft-274; return; }
if( lDaysLeft >= 245 ){ *lpMonth = 9; *lpDay = lDaysLeft-244; return; }
if( lDaysLeft >= 214 ){ *lpMonth = 8; *lpDay = lDaysLeft-213; return; }
if( lDaysLeft >= 183 ){ *lpMonth = 7; *lpDay = lDaysLeft-182; return; }
if( lDaysLeft >= 153 ){ *lpMonth = 6; *lpDay = lDaysLeft-152; return; }
if( lDaysLeft >= 122 ){ *lpMonth = 5; *lpDay = lDaysLeft-121; return; }
if( lDaysLeft >= 92 ){ *lpMonth = 4; *lpDay = lDaysLeft-91; return; }
if( lDaysLeft >= 61 ){ *lpMonth = 3; *lpDay = lDaysLeft-60; return; }
if( lDaysLeft >= 32 ){ *lpMonth = 2; *lpDay = lDaysLeft-32; return; }
if( lDaysLeft >= 1 ){ *lpMonth = 1; *lpDay = lDaysLeft; return; }
}
else
{
if( lDaysLeft >= 335 ){ *lpMonth = 12; *lpDay = lDaysLeft-334; return; }
if( lDaysLeft >= 305 ){ *lpMonth = 11; *lpDay = lDaysLeft-304; return; }
if( lDaysLeft >= 274 ){ *lpMonth = 10; *lpDay = lDaysLeft-273; return; }
if( lDaysLeft >= 244 ){ *lpMonth = 9; *lpDay = lDaysLeft-243; return; }
if( lDaysLeft >= 213 ){ *lpMonth = 8; *lpDay = lDaysLeft-212; return; }
if( lDaysLeft >= 182 ){ *lpMonth = 7; *lpDay = lDaysLeft-181; return; }
if( lDaysLeft >= 152 ){ *lpMonth = 6; *lpDay = lDaysLeft-151; return; }
if( lDaysLeft >= 121 ){ *lpMonth = 5; *lpDay = lDaysLeft-120; return; }
if( lDaysLeft >= 91 ){ *lpMonth = 4; *lpDay = lDaysLeft-90; return; }
if( lDaysLeft >= 60 ){ *lpMonth = 3; *lpDay = lDaysLeft-59; return; }
if( lDaysLeft >= 32 ){ *lpMonth = 2; *lpDay = lDaysLeft-31; return; }
if( lDaysLeft >= 1 ){ *lpMonth = 1; *lpDay = lDaysLeft; return; }
}
}
return;
}
/*
* CLU: reads data (byte stream) from a file into a destination buffer and does little - big
* endian conversion.
*
* Parameters:
* FILE *pFile: pointer to FILE
* BYTE *pcDst: pointer to destination buffer
* size_t size: number of bytes to be copied
* BOOL bEndian: TRUE: reverse byte order
* FALSE: just copy
*
* Note: the calling routine must ensure the destination buffer size is sufficient
*
*/
void CFileTool::ReadFromFile(FILE *pFile, BYTE *pcDst, size_t size, BOOL bEndian) {
BYTE* pcBuf; // CLU: read buffer
if (!(pcBuf = (BYTE *)malloc(size))) {
RETURN_WITH_ERRORV("Out of Memory!");
}
if (fread(pcBuf, sizeof(BYTE), size, pFile) != size) { // CLU: corrupt file
free(pcBuf);
RETURN_WITH_ERRORV("Cannot read from file!");
}
SWITCHENDIAN(pcDst, pcBuf, size, bEndian); // CLU: interpret data
free(pcBuf);
//return(S_OK);
}
// K:B
bool CFileTool::BufferReadTiff(const BYTE *pBuffer, var_list<BYTE> *pDst, var_list<EMVECTOR> *pEmVector, var_list<BYTE> *pThumbNail)
{
UINT nStripOffsetsSize,
nStripBytesSize;
LONG lFilePosition;
DWORD *pdwStripOffsets = NULL,
*pdwBytesPerStrip = NULL;
double dXResolution = 72,
dYResolution = 72;
// HRESULT hr;
ULONG pos = 0L;
TIFF_DATA TIFF_Data;
TIFF_FIELD TIFF_Field;
if (!pDst && !pEmVector && !pThumbNail) {
RETURN_WITH_ERROR("Illegal parameter (pDst and pEmVector and pThumbNail are NULL", 1);
}
try {
/*
* CLU: initiate the TIFF data fields with -1
*/
TIFF_Data.ImageWidth =
TIFF_Data.ImageLength =
TIFF_Data.BitsPerSample =
TIFF_Data.Compression =
TIFF_Data.PhotoInterpret =
TIFF_Data.StripOffsets =
TIFF_Data.StripOffsetsCount =
TIFF_Data.RowsPerStrip =
TIFF_Data.StripByteCounts =
TIFF_Data.XResolutionZ =
TIFF_Data.XResolutionN =
TIFF_Data.YResolutionZ =
TIFF_Data.YResolutionN =
TIFF_Data.ResolutionUnit = -1;
/*
* CLU: check byte order and TIFF signature
*/
BYTE cBuf_4[4]; // CLU: read buffer
ReadFromFile(pBuffer, pos, cBuf_4, 4, FALSE);
if ((*(int *)cBuf_4 != 0x002a4949 && *(int *)cBuf_4 != 0x2a004d4d)) { // CLU: no tiff file
RETURN_WITH_ERROR("No TIFF file detected", 1);
}
BOOL bBigEndian = (*(short *)cBuf_4 == 0x4d4d); // CLU: the byte order
/*
* CLU: get first IFD
*/
ULONG IFD_Offset;
ReadFromFile(pBuffer, pos, (BYTE *)&IFD_Offset, sizeof(ULONG), bBigEndian);
if (IFD_Offset == 0) { // CLU: image contains no data
RETURN_WITH_ERROR("Image contains no data", 1);
}
// now we are checking whether there is special TVIPS thumbnail information in this image
if( IFD_Offset >= 0xc010 ) {
char ca[16];
ReadFromFile(pBuffer, pos, (BYTE *)&ca[0], 8, bBigEndian);
if( strncmp( ca, "THUMB128", 8 ) == 0 ) { // if 0, then we found it
if( pThumbNail != NULL && pThumbNail->vpData != NULL &&
pThumbNail->lDimensions == 2 &&
pThumbNail->lDim[0] == 128 &&
pThumbNail->lDim[1] == 128 &&
pThumbNail->lType == DT_RGB8 ) {
ReadFromFile(pBuffer, pos, (BYTE *)pThumbNail->vpData, 128*128*3, bBigEndian);
}
}
}
/*
* CLU: read all IFD's (Image File Directories)
*/
while (IFD_Offset != 0) {
pos = IFD_Offset;
/*
* CLU: get number of fields
*/
WORD wFields;
WORD wTmp, *wpTmp;
ReadFromFile(pBuffer, pos, (BYTE *)&wFields, sizeof(WORD), bBigEndian); // num(Directory Entries)
/*
* CLU: read all fields
*/
for (int i = 0; i < wFields; i++ ) {
/*
* CLU: get field tag
*/
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Field.tag, sizeof(WORD), bBigEndian);
/*
* CLU: get field type
*/
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Field.type, sizeof(WORD), bBigEndian);
/*
* CLU: get field count
*/
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Field.count, sizeof(DWORD), bBigEndian);
/*
* CLU: get field value
*/
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Field.value, sizeof(DWORD), bBigEndian);
/*
* CLU: decode TIFF fields
*/
switch (TIFF_Field.tag) {
case 256: // CLU: ImageWidth
switch (TIFF_Field.type) {
case TYPE_SHORT:
if (bBigEndian) {
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.ImageWidth = (DWORD)wTmp;
}
else {
wTmp = *( (WORD*)(&TIFF_Field.value) );
TIFF_Data.ImageWidth = (DWORD)wTmp;
}
break;
case TYPE_LONG:
TIFF_Data.ImageWidth = TIFF_Field.value;
break;
default:
RETURN_WITH_ERROR("Cannot decode TIFF data", 1);
}
break;
case 257: // CLU: ImageLength
switch (TIFF_Field.type) {
case TYPE_SHORT:
if (bBigEndian )
{
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.ImageLength = (DWORD)wTmp;
}
else
{
wTmp = *( (WORD*)(&TIFF_Field.value) );
TIFF_Data.ImageLength = (DWORD)wTmp;
}
break;
case TYPE_LONG:
TIFF_Data.ImageLength = TIFF_Field.value;
break;
default:
RETURN_WITH_ERROR("Cannot decode TIFF data", 1);
}
break;
case 258: // CLU: BitsPerSample
if (TIFF_Field.type != TYPE_SHORT) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
if( TRUE == bBigEndian )
{
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.BitsPerSample = (DWORD)wTmp;
}
else
TIFF_Data.BitsPerSample = TIFF_Field.value;
switch (TIFF_Data.BitsPerSample) {
case 8:
case 16:
break;
default:
RETURN_WITH_ERROR("Cannot decode TIFF data", 1);
}
break;
case 259: // CLU: Compression
if (TIFF_Field.type != TYPE_SHORT) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
if( bBigEndian )
{
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.Compression = (DWORD)wTmp;
}
else
TIFF_Data.Compression = TIFF_Field.value;
if (TIFF_Data.Compression != 1) {
RETURN_WITH_ERROR("Cannot decode TIFF data", 1);
}
break;
case 262: // CLU: PhotometricInterpretation
if (TIFF_Field.type != TYPE_SHORT) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
if( TRUE == bBigEndian )
{
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.PhotoInterpret= (DWORD)wTmp;
}
else
TIFF_Data.PhotoInterpret = TIFF_Field.value;
switch (TIFF_Data.PhotoInterpret) {
case 0:
case 1:
break;
default:
RETURN_WITH_ERROR("Cannot decode TIFF data", 1);
}
break;
case 273: // CLU: StripOffsets
switch (TIFF_Field.type) {
case TYPE_SHORT:
case TYPE_LONG:
TIFF_Field.type == TYPE_SHORT ? nStripOffsetsSize = 2 : nStripOffsetsSize = 4;
TIFF_Data.StripOffsetsCount = TIFF_Field.count;
if (!(pdwStripOffsets = (DWORD*)malloc(sizeof(DWORD)*TIFF_Data.StripOffsetsCount))) {
RETURN_WITH_ERROR("No memory", 1);
}
if (TIFF_Data.StripOffsetsCount == 1) *pdwStripOffsets = (DWORD)TIFF_Field.value;
else {
lFilePosition = pos;
pos = TIFF_Field.value;
for (int j = 0; j < (int)TIFF_Data.StripOffsetsCount; j++) {
ReadFromFile(pBuffer, pos, (BYTE *)&pdwStripOffsets[j], nStripOffsetsSize, bBigEndian);
}
pos = lFilePosition;
}
break;
default:
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
break;
case 278: // CLU: RowsPerStrip
switch (TIFF_Field.type) {
case TYPE_SHORT:
if( TRUE == bBigEndian )
{
wpTmp = (WORD*)&TIFF_Field.value;
wTmp = wpTmp[1];
TIFF_Data.RowsPerStrip = (DWORD)wTmp;
}
else
{
wTmp = *( (WORD*)(&TIFF_Field.value) );
TIFF_Data.RowsPerStrip = (DWORD)wTmp;
}
break;
case TYPE_LONG:
TIFF_Data.RowsPerStrip = TIFF_Field.value;
break;
default:
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
break;
case 279: // CLU: StripByteCount
switch (TIFF_Field.type) {
case TYPE_SHORT:
case TYPE_LONG:
TIFF_Field.type == TYPE_SHORT ? nStripBytesSize = 2 : nStripBytesSize = 4;
TIFF_Data.StripByteCounts = TIFF_Field.count;
if (!(pdwBytesPerStrip = (DWORD*)malloc(sizeof(DWORD)*TIFF_Data.StripByteCounts))) {
RETURN_WITH_ERROR("No memory", 1);
}
if (TIFF_Data.StripByteCounts == 1) *pdwBytesPerStrip = TIFF_Field.value;
else {
lFilePosition = pos;
pos = TIFF_Field.value;
for (int j = 0; j < (int)TIFF_Data.StripByteCounts; j++) {
ReadFromFile(pBuffer, pos, (BYTE *)&pdwBytesPerStrip[j], nStripBytesSize, bBigEndian);
}
pos = lFilePosition;
} // else
break;
default:
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
break;
case 282: // CLU: XResolution
if (TIFF_Field.type != TYPE_RATIONAL) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
lFilePosition = pos;
pos = TIFF_Field.value;
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Data.XResolutionZ, sizeof(DWORD), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Data.XResolutionN, sizeof(DWORD), bBigEndian);
dXResolution = (double)TIFF_Data.XResolutionZ/TIFF_Data.XResolutionN;
pos = lFilePosition;
break;
case 283: // CLU: YResolution
if (TIFF_Field.type != TYPE_RATIONAL) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
lFilePosition = pos;
pos = TIFF_Field.value;
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Data.YResolutionZ, sizeof(DWORD), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&TIFF_Data.YResolutionN, sizeof(DWORD), bBigEndian);
dYResolution = (double)TIFF_Data.YResolutionZ/TIFF_Data.YResolutionN;
pos = lFilePosition;
break;
case 296: // CLU: ResolutionUnit
if (TIFF_Field.type != TYPE_SHORT) {
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
TIFF_Data.ResolutionUnit = TIFF_Field.value;
switch (TIFF_Data.ResolutionUnit) {
case 1:
case 2:
case 3: break;
default:
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
break;
case TAG_OVL_DATA: // TVIPS specific Overlay tag
{
int lOverlaySize;
BYTE *cpOverlayData;
lOverlaySize = (int)TIFF_Field.count;
if( lOverlaySize == 0 ) // Oops, ignore this tag silently
break;
cpOverlayData = new BYTE[lOverlaySize];
if( cpOverlayData == NULL ) // Oops, no buffer, then overlay data are ignored
break;
int lOverlayOffset;
lOverlayOffset = TIFF_Field.value;
// store current file position
lFilePosition = pos;
pos = lOverlayOffset;
// seek file position of overlay data
// read overlay data
ReadFromFile(pBuffer, pos, (BYTE *)cpOverlayData, lOverlaySize, FALSE /*binary, no byte reversal*/);
// restore file position
pos = lFilePosition;
//g_DataContainer.WriteOverlayData(lImgHandle, cpOverlayData, lOverlaySize);
delete[] cpOverlayData;
}
break;
case TAG_TEM_DATA: // TVIPS specific TemData tag
if (pEmVector) {
if (TIFF_Field.type != TYPE_LONG) { // CLU: read only if needed
RETURN_WITH_ERROR("Wrong TIFF data type", 1);
}
int EMVectorVersion; // CLU: version of EM vector
lFilePosition = pos;;
pos = TIFF_Field.value;
ReadFromFile(pBuffer, pos, (BYTE *)&EMVectorVersion, sizeof(DWORD), bBigEndian);
if (EMVectorVersion >= 1) {
switch (EMVectorVersion) {
case 1: // CLU: em_vector V == 1 starts here
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v1.strComment, 80, bBigEndian);
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lHighTension = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lSphericalAberration = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lIllumAperture = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lElOptMag = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
//EMVECTOR *pEMV;
//pEMV = (EMVECTOR *)pEmVector->vpData;
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lPostMag = (*(int *)cBuf_4);
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lFocalLength = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDefocus = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lAstigmatismNM = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lAstigmatismMRAD = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lBiprismTension = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lSpecimenTiltAngle = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lSpecimenTiltDirection = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lIllumTiltAngle = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lIllumTiltDirection = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lMode = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lEnergySpread = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lChromaticalAberration = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lShutterType = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDefocusSpread = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDNumber = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDPixelXY = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDOffsetX = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDOffsetY = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDSinglePixelSize = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDBinningFactor = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDGain = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDReadOutSpeed = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDSensitivity = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lCCDExposureTime = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lFlatfieldCorrection = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDeadPixelCorrection = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lMeanValue = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lStandardDeviation = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDisplacementX = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDisplacementY = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
// (*(EMVECTOR *)pEmVector->vpData).ud_v1.lDate = 0.0001f**(float *)cBuf_4;
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lDate = (float)(*(int *)cBuf_4);
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
// (*(EMVECTOR *)pEmVector->vpData).ud_v1.lTime = 0.0001f**(float *)cBuf_4;
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lTime = (float)(*(int *)cBuf_4);
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lMinimum = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lMaximum = (*(int *)cBuf_4)/10000;
ReadFromFile(pBuffer, pos, cBuf_4, sizeof(int), bBigEndian);
(*(EMVECTOR *)pEmVector->vpData).ud_v1.lQualityFactor = (*(int *)cBuf_4)/10000;
ConvertV1ToV2( (void *)pEmVector->vpData, (void*)&TIFF_Data );
break; // case 1:
case 2: // CLU: em_vector V == 2 starts here
pos += 240;
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szImgName,
80*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szImgFolder,
80*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgSizeX,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgSizeY,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgSizeZ,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgSizeE,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgDataType,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgCreationDate,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgCreationTime,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szImgComment,
512*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szImgHistory,
512*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgScaling,
16*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.cmplxImgStat,
16*sizeof(_complex), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgType,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lImgDisplay,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgDistX,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgDistY,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgDistZ,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgDistE,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fImgMisc,
32*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szTemType,
80*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemHT,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemAberr,
32*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemEnergy,
32*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lTemMode,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemMagScr,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemMagCor,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemMagPst,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lTemStgType,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemStgPos,
5*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemImgShift,
2*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemBeamShift,
2*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemBeamTilt,
2*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemTiling,
7*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemIllum,
3*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lTemShutter,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fTemMisc,
32*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szCamType,
80*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamPixel,
2*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lCamOffX,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lCamOffY,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lCamBinX,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.lCamBinY,
sizeof(int), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamExpTime,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamGain,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamSpeed,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szCamFlat,
80*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamSense,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamDose,
sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.fCamMisc,
32*sizeof(float), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szAdaTietzMicInfo,
512*sizeof(USHORT), bBigEndian);
ReadFromFile(pBuffer, pos, (BYTE *)&(*(EMVECTOR *)pEmVector->vpData).ud_v2.szAdaTietzSpecInfo,
512*sizeof(USHORT), bBigEndian);
int lMagic; // PSP: Added magic number $aaaaaaaa at the end of the structure
ReadFromFile(pBuffer, pos, (BYTE *)&lMagic, 4, bBigEndian);
if( lMagic != 0xaaaaaaaa )
{
RETURN_WITH_ERROR("Magic number in EMVector missing", 1);
}
break; // case 2:
/*
case 3: * CLU: add future versions (V == 3) here, and (V > 3) below
case 4: *
case 5: */
default:
RETURN_WITH_ERROR("Unknown EM vector", 1);
} // switch (EMVectorVersion)
} // if (EMVectorVersion >= 1)
pos = lFilePosition;
} // if (pEmVector)
break; // TAG_TEM_DATA
default: // CLU: ignore unknown or not supported tags
break;
} // switch (TIFF_Field.tag)
} // for (int i = 0; i < wFields; i++ )
if (pDst) { // CLU: read data if required
/*
* Check the required elements of the structure TIFF_Data against -1.
* If there are required elements equal to -1 then return FALSE, if all is OK go on.
* Use some assumptions if you can - instead of error message.
*/
if (TIFF_Data.ImageWidth == -1 ||
TIFF_Data.ImageLength == -1 ||
TIFF_Data.BitsPerSample == -1 ||
TIFF_Data.Compression == -1 ||
TIFF_Data.RowsPerStrip == -1) {
free(pdwStripOffsets); // CLU: free memory
free(pdwBytesPerStrip); // CLU: free memory
RETURN_WITH_ERROR("Required entry in TIFF image missing", 1);
}
if (TIFF_Data.PhotoInterpret == -1) TIFF_Data.PhotoInterpret = 1;
lFilePosition = pos;
DWORD nSizeX = TIFF_Data.ImageWidth,
nSizeY = TIFF_Data.ImageLength,
nDataSize = (TIFF_Data.BitsPerSample / 8);
/*
* CLU: adapt the parameters of the destination variable
*/
pDst->lDimensions = 2L;
pDst->lDim[0] = (int)nSizeX;
pDst->lDim[1] = (int)nSizeY;
pDst->lDim[2] =
pDst->lDim[3] = 0L;
pDst->lType = nDataSize == 1 ? DT_UCHAR : DT_SHORT;
if ((pDst->vpData = (BYTE *)realloc(pDst->vpData, nSizeX*nSizeY*nDataSize)) == NULL) {
free(pdwStripOffsets); // CLU: free memory
free(pdwBytesPerStrip); // CLU: free memory
RETURN_WITH_ERROR("No memory", 1);
}
BYTE *pbB = NULL, *pB = (BYTE *)pDst->vpData;
for (int j = 0; j < (int)TIFF_Data.StripOffsetsCount; j++) {
pos = (int)pdwStripOffsets[j];
if ((pbB = (BYTE *)realloc(pbB, pdwBytesPerStrip[j])) == NULL) {
free(pdwStripOffsets); // CLU: free memory
free(pdwBytesPerStrip); // CLU: free memory
RETURN_WITH_ERROR("No memory", 1);
free(pdwStripOffsets); // CLU: free memory
}
ReadFromFile(pBuffer, pos, pbB, pdwBytesPerStrip[j], FALSE);
if (nDataSize == 1)
memcpy(pB, pbB, (int)(pdwBytesPerStrip[j]));
if (nDataSize > 1)
for (int k = 0; k < (int)(pdwBytesPerStrip[j]); k += nDataSize)
SWITCHENDIAN(pB + k, pbB + k, nDataSize, bBigEndian); // CLU: interpret data
pB += pdwBytesPerStrip[j];
} // for int j = 0; j < (int)TIFF_Data.StripOffsetsCount; j++)
free(pbB); // CLU: free memory
} // if (pDst)
free(pdwStripOffsets); // CLU: free memory
free(pdwBytesPerStrip); // CLU: free memory
pos = lFilePosition;
/*
* CLU: check next IFD (if any)
*
* The next offset should equals to 0, since only 1 image per file is
* supported (till 2day (= 21.10.2002))
*/
ReadFromFile(pBuffer, pos, (BYTE *)&IFD_Offset, sizeof(ULONG), bBigEndian);
if (IFD_Offset != 0) { // CLU: file contains more image(s)
IFD_Offset = 0;
}
} // while (IFD_Offset != 0)
}
catch (...) {
return false;
}
return(true);
}
HRESULT CFileTool::DoReadTiff(TCHAR *ptcFilename, struct var_list<BYTE> *pDst, struct var_list<EMVECTOR> *pEmVector, struct var_list<BYTE> *pThumbNail)
{
bool hr;
struct stat FileInfo;
stat(ptcFilename, &FileInfo);
int Fsize;
Fsize = FileInfo.st_size;
void *map = NULL;
int fd;
fd = open(ptcFilename, O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
exit(EXIT_FAILURE);
}
map = mmap(0, Fsize, PROT_READ, MAP_PRIVATE, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
hr = BufferReadTiff((BYTE *)map, pDst, pEmVector, pThumbNail);
if (munmap(map, Fsize ) == -1) {
perror("Error un-mmapping the file");
}
close(fd);
return 0L;
/*
HRESULT hr = S_OK;
WIN32_FILE_ATTRIBUTE_DATA wfad;
if (!GetFileAttributesEx(ptcFilename, GetFileExInfoStandard, &wfad)) {
RETURN_WITH_ERROR("File don't exist");
}
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hMapFile = NULL;
void *lpFileData = NULL;
__try {
hFile = CreateFile(ptcFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
RETURN_WITH_ERROR("Failed to open file");
}
hMapFile = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, wfad.nFileSizeLow, NULL);
if (hMapFile == NULL) {
RETURN_WITH_ERROR("Failed to open file");
}
lpFileData = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
if (lpFileData == NULL) {
RETURN_WITH_ERROR("Failed to open file");
}
hr = BufferReadTiff((BYTE *)lpFileData, pDst, pEmVector, pThumbNail);
}
__finally {
if (lpFileData)
UnmapViewOfFile(lpFileData);
if (hMapFile)
CloseHandle(hMapFile);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
}
return hr;
*/
}
| true |
39f5fa58cf0d02ef3e76140926361e4312634466 | C++ | lstefani006/teensy | /LibStm/LeoStm/ring.cpp | UTF-8 | 939 | 3.25 | 3 | [] | no_license | #include <ring.hpp>
Ring::Ring()
: _data(nullptr), _size(0), _begin(0), _end(0)
{
}
Ring::Ring(uint8_t *buf, int32_t size)
: _data(buf), _size(size), _begin(0), _end(0)
{
}
void Ring::begin(uint8_t *buf, int32_t size)
{
_data = buf;
_size = size;
_begin = 0;
_end = 0;
}
int32_t Ring::WriteCh(uint8_t ch)
{
if (this->Full())
return -1;
this->_data[this->_end] = ch;
this->_end = (this->_end + 1) % this->_size;
return ch;
}
int32_t Ring::Write(const uint8_t *data, int32_t size)
{
int32_t i;
for (i = 0; i < size; i++)
if (WriteCh(data[i]) < 0)
return -i;
return i;
}
int32_t Ring::ReadCh(uint8_t *ch)
{
if (this->Empty()) return -1;
uint8_t ret = this->_data[this->_begin];
this->_begin = (this->_begin + 1) % this->_size;
if (ch) *ch = ret;
return ret;
}
int32_t Ring::Read(uint8_t *data, int32_t size)
{
int32_t i;
for (i = 0; i < size; i++)
if (ReadCh(data + i) < 0)
return i;
return -i;
}
| true |
d139bd046d5844832b3dd07a56872bd5424076a3 | C++ | Mariam-Marie/Day-2 | /day2.cpp | UTF-8 | 269 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
int main() {
int i, h, m, s;
printf("Please enter a number : ");
scanf("%d", &i);
h = (i/3600);
m = (i - (3600*h))/60;
s = (i - (3600*h)-(60*m));
printf("hours: %d \n", h);
printf("minutes: %d \n", m);
printf("seconds: %d", s);
return 0;
}
| true |
076d89f5fafc7b20e7f78b0ee99a40b4cc91dcd0 | C++ | hansionz/Cpp_Code | /StackObj/StackObj.cpp | UTF-8 | 723 | 3.59375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class StackType
{
public:
StackType()
{}
void Print()
{
cout << "StackType:" << this << endl;
}
private:
//不能再堆上创建,我们可以考虑直接把operator new和new的定位表达式声明为私有的
//将operator new声明为私有的,就把new的定位表达式也声明为私有的了
void* operator new(size_t size);
void operator delete(void* p);
};
int main()
{
StackType st1;//ok
st1.Print();
//StackType st2 = new StackType();//不行,因为operator new被屏蔽了
//StackType* st3 = (StackType*)malloc(sizeof(StackType));
//new(st3)StackType();//不行,因为new的定位表达式也被屏蔽
return 0;
}
| true |
a88784eac938c16e515f374a1435b559b1cf7196 | C++ | SmileOrDie/A_VM | /srcs/error/MissingArgument.hpp | UTF-8 | 461 | 2.9375 | 3 | [] | no_license | #ifndef MISSINGARGUMENT_HPP
#define MISSINGARGUMENT_HPP
#include <exception>
#include <string>
class MissingArgument: public std::exception {
public:
MissingArgument(const std::string &funct);
MissingArgument();
~MissingArgument();
MissingArgument(MissingArgument const & src);
MissingArgument& operator=(MissingArgument const & rhs);
private:
const std::string _funct;
virtual const char* what() const throw ();
};
#endif | true |
add16d1602e64a8a4e8bc99a7811eb9a2fc0090b | C++ | bulacu-magda/Alemia | /data/preprocessed/train/student_62/sources/SunFlower.cpp | UTF-8 | 1,329 | 2.765625 | 3 | [] | no_license | #include "SunFlower.h"
bool SunFlower::Draw(Panel& panel)
{
COORD Center = this->getCenterOfDrawing();
if (panel.getChar(Center.X, Center.Y) == SPACE)
{
panel.setChar(Center.X - 1, Center.Y - 1, SUNFLOWER);
panel.setChar(Center.X - 1, Center.Y, SUNFLOWER);
//panel.setChar(Center.X - 1, Center.Y + 1, SUNFLOWER);
panel.setChar(Center.X, Center.Y - 1, SUNFLOWER);
panel.setChar(Center.X, Center.Y, SUNFLOWER);
panel.setChar(Center.X, Center.Y + 1, L'p'); //doar estetic pt tulpina
panel.setChar(Center.X + 1, Center.Y - 1, SUNFLOWER);
panel.setChar(Center.X + 1, Center.Y, SUNFLOWER);
//panel.setChar(Center.X + 1, Center.Y + 1, SUNFLOWER);
return true;
}
else
{
return false;
}
}
bool SunFlower::Erase(Panel& panel)
{
COORD Center = this->getCenterOfDrawing();
if (panel.getChar(Center.X, Center.Y) == SUNFLOWER)
{
panel.setChar(Center.X - 1, Center.Y - 1, SPACE);
panel.setChar(Center.X - 1, Center.Y, SPACE);
panel.setChar(Center.X - 1, Center.Y + 1, SPACE);
panel.setChar(Center.X, Center.Y - 1, SPACE);
panel.setChar(Center.X, Center.Y, SPACE);
panel.setChar(Center.X, Center.Y + 1, SPACE);
panel.setChar(Center.X + 1, Center.Y - 1, SPACE);
panel.setChar(Center.X + 1, Center.Y, SPACE);
panel.setChar(Center.X+1, Center.Y+1, SPACE);
return 1;
}
else
{
return 0;
}
}
| true |
7afdead7774a06dd97f2bd0f6b853a80ca75ce65 | C++ | haved/DafCompiler | /Old/OldCpp/Compiler/src/parsing/NameScopeParser.cpp | UTF-8 | 3,729 | 2.875 | 3 | [] | no_license | #include "parsing/NameScopeParser.hpp"
#include "parsing/lexing/Lexer.hpp"
#include "parsing/DefinitionParser.hpp"
#include "parsing/ErrorRecovery.hpp"
#include "DafLogger.hpp"
unique_ptr<NameScopeExpression> null_nse() {
return unique_ptr<NameScopeExpression>();
}
void parseGlobalDefinitionList(Lexer& lexer, std::vector<unique_ptr<Definition>>& definitions) {
while(lexer.hasCurrentToken() && lexer.currType() != SCOPE_END) {
if(lexer.currType() == STATEMENT_END) {
lexer.advance(); //Eat ';'
continue; //Extra semicolons are OK
}
bool pub = lexer.currType()==PUB;
if(pub)
lexer.advance();
unique_ptr<Definition> definition = parseDefinition(lexer, pub);
if(definition) //A nice definition was returned, and has eaten it's own semicolon
definitions.push_back(std::move(definition));
else if(lexer.hasCurrentToken()) //Error occurred, but already printed
skipUntilNewDefinition(lexer);
}
}
unique_ptr<NameScopeExpression> parseNameScope(Lexer& lexer) {
assert(lexer.currType() == SCOPE_START);
int startLine = lexer.getCurrentToken().line;
int startCol = lexer.getCurrentToken().col;
lexer.advance(); //Eat '{'
std::vector<unique_ptr<Definition>> definitions;
parseGlobalDefinitionList(lexer, definitions); //Fills definitions
if(lexer.expectToken(SCOPE_END))
lexer.advance(); //Eat '}'
return std::make_unique<NameScope>(std::move(definitions), TextRange(lexer.getFile(), startLine, startCol, lexer.getPreviousToken())); //Bit ugly
}
NameScope emptyNameScope(Lexer& lexer) {
return NameScope(std::vector<unique_ptr<Definition>>(), TextRange(lexer.getFile(), 0,0,0,0)); //No tokens, no nothing
}
void parseFileAsNameScope(Lexer& lexer, optional<NameScope>* scope) {
assert(lexer.getPreviousToken().type == NEVER_SET_TOKEN); //We are at the start of the file
if(!lexer.hasCurrentToken()) { //Token-less file
*scope = emptyNameScope(lexer);
return;
}
int startLine = lexer.getCurrentToken().line;
int startCol = lexer.getCurrentToken().col;
std::vector<unique_ptr<Definition>> definitions;
parseGlobalDefinitionList(lexer, definitions);
lexer.expectToken(END_TOKEN);
if(lexer.getPreviousToken().type == NEVER_SET_TOKEN) { //We never ate anything!
assert(definitions.empty());
*scope = emptyNameScope(lexer);
return;
}
int endLine = lexer.getPreviousToken().line; //Must be some kind of token
int endCol = lexer.getPreviousToken().endCol;
*scope = NameScope(std::move(definitions), TextRange(lexer.getFile(), startLine, startCol, endLine, endCol));
}
unique_ptr<NameScopeExpression> parseNameScopeReference(Lexer& lexer) {
assert(lexer.currType() == IDENTIFIER);
lexer.advance(); //Eat identifier
return unique_ptr<NameScopeExpression>( new NameScopeReference(std::string(lexer.getPreviousToken().text), TextRange(lexer.getFile(), lexer.getPreviousToken())) );
}
unique_ptr<NameScopeExpression> parseNameScopeExpressionSide(Lexer& lexer) {
switch(lexer.currType()) {
case IDENTIFIER: return parseNameScopeReference(lexer);
case SCOPE_START: return parseNameScope(lexer);
default: break;
}
logDafExpectedToken("a name-scope expression", lexer);
return null_nse();
}
unique_ptr<NameScopeExpression> parseNameScopeExpression(Lexer& lexer) {
unique_ptr<NameScopeExpression> side = parseNameScopeExpressionSide(lexer);
if(!side)
return side;
while(lexer.currType() == CLASS_ACCESS) {
lexer.advance(); //Eat '.'
if(!lexer.expectProperIdentifier())
return null_nse();
std::string name(lexer.getCurrentToken().text);
side = std::make_unique<NameScopeReference>(std::move(side), std::move(name), TextRange(lexer.getFile(), lexer.getCurrentToken()));
lexer.advance(); //Eat identifier
}
return side;
}
| true |
5f5528629317612005f06d6a0555f4330942b801 | C++ | yechang1897/algorithm | /math/leetcode_172.cpp | UTF-8 | 596 | 3.65625 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int trailingZeroes(int n) {
int zero = 0;
while (n > 0) {
n /= 5;
zero += n;
}
return zero;
}
int trailingZeroes_2(int n) {
int zeroCount = 0;
// We need to use long because currentMultiple can potentially become
// larger than an int.
long currentMultiple = 5;
while (n >= currentMultiple) {
zeroCount += (n / currentMultiple);
currentMultiple *= 5;
}
return zeroCount;
}
int main() {
int n = 100;
cout << trailingZeroes_2(n);
} | true |
e417a58ef544bed7a759d96e9ee4dfcb03eeb12d | C++ | Liu-cp/Json-file | /VQA_questions/Program/Program/Program.cpp | UTF-8 | 2,335 | 2.71875 | 3 | [] | no_license | // Program.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "json/json.h"
using namespace std;
typedef struct Questions
{
int image_id;
string question;
int question_id;
}Questions;
int Find(vector<int> image, int image_id)
{
for (int i = 0; i < image.size(); i++)
if (image[i] == image_id)
return i;
return -1;
}
void GetInformation(vector<int> imageID)
{
//ifstream infile_json("txt/v2_OpenEnded_mscoco_train2014_questions.json");
//ofstream outfile("txt/train2014_questions.json");
ifstream infile_json("txt/v2_OpenEnded_mscoco_val2014_questions.json");
ofstream outfile("txt/val2014_questions.json");
//ifstream infile_json("txt/v2_OpenEnded_mscoco_test2015_questions.json");
//ofstream outfile("txt/test.json");
vector<Questions> questions;
int last_imageid = 0;
Json::Reader reader;
Json::Value root;
if(reader.parse(infile_json, root))
{
for(int i = 0; i < root["questions"].size(); i++)
{
int image_id = root["questions"][i]["image_id"].asInt();
if(last_imageid == image_id || Find(imageID, image_id) != -1)
{
cout << image_id << " ";
Questions ques;
ques.image_id = root["questions"][i]["image_id"].asInt();
ques.question = root["questions"][i]["question"].asString();
ques.question_id = root["questions"][i]["question_id"].asInt();
questions.push_back(ques);
last_imageid = image_id;
}
}
}
Json::Value root_out;
for(int i = 0; i < questions.size(); i++)
{
Json::Value child;
child["image_id"] = Json::Value(questions[i].image_id);
child["question"] = Json::Value(questions[i].question);
child["question_id"] = Json::Value(questions[i].question_id);
root_out["questions"].append(child);
}
//Json::StyledWriter sw;
Json::FastWriter fw;
outfile << fw.write(root_out);
infile_json.close();
outfile.close();
}
int main()
{
vector<int> target;
//ifstream infile("txt/human_train.txt");
ifstream infile("txt/human_val.txt");
char temp_char[10];
while (infile.getline(temp_char, 10))
{
target.push_back(atoi(temp_char));
//cout << target.back() << " ";
}
infile.close();
GetInformation(target);
}
| true |
b6c9f0120ec2c79c4b2ca118faa3da1bcc424cc5 | C++ | anuj108/Codeforces | /dragons-sol.cpp | UTF-8 | 573 | 2.796875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<pair<int, int>> v;
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
v.push_back({x, y});
}
sort(v.begin(), v.end());
bool isvalid = true;
for (int i = 0; i < m; i++)
{
if (n <= v[i].first)
{
isvalid = false;
break;
}
n += v[i].second;
}
if (isvalid)
cout << "YES"
<< "\n";
else
cout << "NO"
<< "\n";
} | true |
52ce69e1812176c1249c8c2c43b6d190feb9935b | C++ | sudhir5595/LeetCode | /July LeetCoding Challange/05 - Hamming Distance.cpp | UTF-8 | 692 | 3.515625 | 4 | [] | no_license | class Solution {
public:
int hammingDistance(int x, int y) {
int answer=0;
while(x||y){ //checking for atleast one of them is positive
if(x&&y){ //if both x and y are positive
if(x%2!=y%2) answer++;
x/=2;
y/=2;
}
else if(x){ //if control comes over there that means one of them become 0, checking if x is positive then continue
if(x%2) answer++;
x/=2;
}
else{ //else we only left with y and x becomes 0
if(y%2) answer++;
y/=2;
}
}
return answer;
}
};
| true |
c32ee7237e0b857fdaa36b650e92454de62417ba | C++ | Ming-J/LeetCode | /C++ Primer/Ch7_Class/E7_5.cpp | UTF-8 | 586 | 3.296875 | 3 | [] | no_license | #include <iostream>
struct Person{
std::string name;
std::string address;
std::string getName() const{
return name;
}
std::string getAddress() const{
return address;
}
}
/*
The function should be const, since we will not modify the this object.
We are simply just getting the member function.
If we have a const Person, he can only call member functions with
the same constness. If the member functions are declares to be
const, both a const Person and a person can utilise. Having const
member functions effective increases their flexibility.
*/
| true |
7339e617ddf268fbf12a348ad5032c7543278f1c | C++ | DOGGY-SAINT/designPatternClassDesign | /code/group3/ll/Composite Entity Pattern/main.cpp | UTF-8 | 259 | 2.546875 | 3 | [] | no_license | #include "Client.h"
#include<iostream>
using namespace std;
int main()
{
Client* client = new Client();
client->setInfo("Sam", "Tom");
client->printInfo();
client->setInfo("Stephon", "Joe");
client->printInfo();
return 0;
} | true |
17aef14b046e1672e54665c07cb41afd85a42009 | C++ | LukasJoswiak/rec | /src/process/paxos/leader.cpp | UTF-8 | 12,723 | 2.640625 | 3 | [] | no_license | #include "process/paxos/leader.hpp"
#include <functional>
#include <thread>
#include <unordered_map>
#include "process/paxos/compare.hpp"
#include "spdlog/spdlog.h"
#include "server/code.hpp"
#include "server/servers.hpp"
namespace process {
namespace paxos {
Leader::Leader(
common::SharedQueue<Message>& message_queue,
common::SharedQueue<std::pair<std::optional<std::string>, Message>>&
dispatch_queue,
std::string& address)
: PaxosProcess(message_queue, dispatch_queue, address),
scout_id_(0),
active_(false) {
ballot_number_.set_number(0);
ballot_number_.set_address(address);
logger_ = spdlog::get("leader");
}
void Leader::Run() {
// Begin listening for incoming messages.
Process::Run();
}
void Leader::Handle(Message&& message) {
if (message.type() == Message_MessageType_PROPOSAL) {
Proposal p;
message.message().UnpackTo(&p);
HandleProposal(std::move(p), message.from());
} else if (message.type() == Message_MessageType_ADOPTED) {
Adopted a;
message.message().UnpackTo(&a);
HandleAdopted(std::move(a), message.from());
} else if (message.type() == Message_MessageType_PREEMPTED) {
Preempted p;
message.message().UnpackTo(&p);
HandlePreempted(std::move(p), message.from());
} else if (message.type() == Message_MessageType_P1B) {
HandleP1B(std::move(message), message.from());
} else if (message.type() == Message_MessageType_P2B) {
HandleP2B(std::move(message), message.from());
} else if (message.type() == Message_MessageType_DECISION) {
Decision d;
message.message().UnpackTo(&d);
HandleDecision(std::move(d), message.from());
} else if (message.type() == Message_MessageType_STATUS) {
Status s;
message.message().UnpackTo(&s);
HandleStatus(std::move(s), message.from());
} else if (message.type() == Message_MessageType_LEADER_CHANGE) {
LeaderChange l;
message.message().UnpackTo(&l);
HandleLeaderChange(std::move(l), message.from());
}
}
void Leader::HandleStatus(Status&& s, const std::string& from) {
logger_->debug("received status message");
std::string principal = PrincipalServer(s.live());
if (!IsLeader() && address_ == principal &&
s.live_size() >= kQuorum) {
// This is the principal server among the alive servers. Increase ballot
// number to be above current leader and attempt to become leader.
SpawnScout(leader_ballot_number_.number() + 1);
}
}
void Leader::HandleLeaderChange(LeaderChange&& l, const std::string& from) {
logger_->debug("received leader change with ballot address {}",
l.leader_ballot_number().address());
leader_ballot_number_ = l.leader_ballot_number();
if (active_ && address_ != leader_ballot_number_.address()) {
logger_->info("{} demoted", address_);
active_ = false;
}
}
void Leader::HandleProposal(Proposal&& p, const std::string& from) {
logger_->debug("received proposal from {}", from);
if (!IsLeader()) {
return;
}
int slot_number = p.slot_number();
if (proposals_.find(slot_number) == proposals_.end()) {
proposals_[slot_number] = p.command();
assert(commander_message_queue_.find(slot_number) ==
commander_message_queue_.end());
SpawnCommander(slot_number, p.command());
}
}
void Leader::HandleAdopted(Adopted&& a, const std::string& from) {
logger_->debug("received Adopted from {}", from);
if (CompareBallotNumbers(ballot_number_, a.ballot_number()) == 0) {
logger_->info("{} promoted to leader", address_);
// Recover any values and add the command to proposals_ to be reproposed.
RecoverValues(a.accepted());
// Propose all commands that have been accepted by other servers. Must have
// received enough responses such that this server was able to reconstruct
// the value from the coded chunks.
for (const auto& it : proposals_) {
int slot_number = it.first;
Command command = it.second;
// Notify the replica of the proposed command for each slot.
ReconstructedProposal p;
p.set_slot_number(slot_number);
p.set_allocated_command(new Command(command));
Message m;
m.set_type(Message_MessageType_RECONSTRUCTED_PROPOSAL);
m.mutable_message()->PackFrom(p);
dispatch_queue_.push(std::make_pair(address_, m));
// Spawn commander to reach consensus on reconstructed command.
SpawnCommander(slot_number, command);
}
// TODO: Send no-ops for slots without enough data to reconstruct.
leader_ballot_number_ = a.ballot_number();
active_ = true;
}
}
void Leader::HandlePreempted(Preempted&& p, const std::string& from) {
logger_->debug("received Preempted from {}", from);
logger_->info("{} demoted", address_);
if (p.ballot_number().address() < address_) {
// This server has a higher address than the ballot from the server we were
// preempted by, so try to become leader again with a higher ballot.
SpawnScout(std::max(ballot_number_.number(),
p.ballot_number().number()) + 1);
} else {
// Preempted by a server with a higher address. Set leader equal to address
// in preempting ballot and don't try to become leader again.
leader_ballot_number_ = p.ballot_number();
active_ = false;
}
}
void Leader::HandleP1B(Message&& m, const std::string& from) {
// Deliver the message by adding it to the correct scout message queue.
P1B p;
m.message().UnpackTo(&p);
auto scout_id = p.scout_id();
if (scout_message_queue_.find(scout_id) != scout_message_queue_.end()) {
auto scout_queue = scout_message_queue_.at(p.scout_id());
scout_queue->push(m);
}
}
void Leader::HandleP2B(Message&& m, const std::string& from) {
// Deliver the message by adding it to the correct commander message queue.
P2B p;
m.message().UnpackTo(&p);
int slot_number = p.slot_number();
// It's possible to receive late P2Bs after a decision has been received and
// the slot has been cleared. Make sure an active commander exists for the
// slot before handling it.
if (commander_message_queue_.find(slot_number) !=
commander_message_queue_.end()) {
auto commander_queue = commander_message_queue_.at(slot_number);
commander_queue->push(m);
}
}
void Leader::HandleDecision(Decision&& d, const std::string& from) {
commanders_.erase(d.slot_number());
commander_message_queue_.erase(d.slot_number());
}
void Leader::SpawnScout(int ballot_number) {
logger_->trace("spawning scout with ballot number {}", ballot_number);
// Clean up state from previous scout.
scouts_.erase(scout_id_);
scout_message_queue_.erase(scout_id_);
ballot_number_.set_number(ballot_number);
// Create a new shared queue to pass messages to the scout.
scout_message_queue_[scout_id_] =
std::make_shared<common::SharedQueue<Message>>();
scouts_.emplace(scout_id_, paxos::Scout(*scout_message_queue_[scout_id_],
dispatch_queue_, address_,
ballot_number_));
// This syntax is necessary to refer to the correct overloaded Scout::Run
// function.
// See https://stackoverflow.com/a/14306975/986991.
std::thread(static_cast<void (paxos::Scout::*)(int)>(&paxos::Scout::Run),
&scouts_.at(scout_id_), scout_id_).detach();
++scout_id_;
}
void Leader::SpawnCommander(int slot_number, Command command) {
logger_->trace("spawning commander for slot {}", slot_number);
// Create a SharedQueue for the commander to allow passing of messages to it.
commander_message_queue_[slot_number] =
std::make_shared<common::SharedQueue<Message>>();
// If a commander exists for this slot, remove it so a new commander can be
// created.
if (commanders_.find(slot_number) != commanders_.end()) {
commanders_.erase(slot_number);
}
// Create a commander and run it on its own thread.
auto pair = commanders_.emplace(slot_number,
std::make_shared<paxos::Commander>(
*commander_message_queue_[slot_number], dispatch_queue_, address_,
ballot_number_, slot_number, command));
// Make sure the new commander was successfully inserted.
assert(std::get<1>(pair) == true);
std::thread(&paxos::Commander::Run, std::move(commanders_.at(slot_number)))
.detach();
}
std::string Leader::PrincipalServer(
const google::protobuf::RepeatedPtrField<std::string>& servers) {
std::string principal;
for (const auto& server : servers) {
if (server > principal) {
principal = server;
}
}
return principal;
}
bool Leader::IsLeader() {
return active_ && address_ == leader_ballot_number_.address();
}
void Leader::RecoverValues(
const google::protobuf::RepeatedPtrField<PValue>& accepted_pvalues) {
if (Code::kCodingEnabled) {
// Recover erasure coded values by building up enough chunks to recover the
// original data.
// Map of slot number -> map of ballot number -> vector of pvalues received
// from acceptors for the slot and ballot.
std::unordered_map<int,
std::unordered_map<BallotNumber, std::vector<PValue>, BallotHash,
BallotEqualTo>> pvalues;
// TODO: Don't recover value if it has already been learned.
// Need to determine if this server received enough responses for each slot
// to be able to reconstruct the original data value, in which case it can
// be reproposed. Otherwise, a no-op will be proposed for the slot.
for (const auto& pvalue : accepted_pvalues) {
int slot_number = pvalue.slot_number();
const BallotNumber& ballot_number = pvalue.ballot_number();
if (pvalues.find(slot_number) == pvalues.end()) {
pvalues[slot_number] =
std::unordered_map<BallotNumber, std::vector<PValue>, BallotHash,
BallotEqualTo>();
}
auto& slot_pvalues = pvalues[slot_number];
if (slot_pvalues.find(ballot_number) == slot_pvalues.end()) {
slot_pvalues[ballot_number] = std::vector<PValue>();
}
auto& slot_ballot_pvalues = slot_pvalues[ballot_number];
slot_ballot_pvalues.push_back(pvalue);
if (slot_ballot_pvalues.size() == Code::kOriginalBlocks) {
// Received enough responses to regenerate data for this slot.
logger_->trace("regenerating command for slot {}", slot_number);
int block_size = slot_ballot_pvalues[0].command().value().size();
// Recover original value from original and redundant shares received
// from acceptors.
cm256_block blocks[Code::kOriginalBlocks];
int i = 0;
for (const auto& pvalue : slot_ballot_pvalues) {
// Make sure size of each block is the same.
assert(pvalue.command().value().size() == block_size);
blocks[i].Index = pvalue.command().block_index();
blocks[i].Block = (unsigned char*) pvalue.command().value().data();
++i;
}
bool success = Code::Decode(blocks, block_size);
assert(success == true);
// TODO: Might need to store this on the heap if values become large
// Create recovered string of correct size, then fill it with data from
// each block. Blocks might be returned out of order.
std::string recovered_value(block_size * Code::kOriginalBlocks, '0');
for (int i = 0; i < Code::kOriginalBlocks; ++i) {
int index = blocks[i].Index;
recovered_value.replace(index * block_size, block_size, std::string((char*) blocks[i].Block));
}
// TODO: Might need to store this on the heap
Command command = Command(slot_ballot_pvalues[0].command());
command.set_value(recovered_value);
command.clear_block_index();
proposals_[slot_number] = command;
}
}
} else {
// Recover non erasure coded values by selecting the command for each slot
// with the highest ballot.
// Map of slot number -> ballot number, used to keep track of the highest
// ballot seen for each slot.
std::unordered_map<int, BallotNumber> ballots;
for (const auto& pvalue : accepted_pvalues) {
int slot_number = pvalue.slot_number();
const BallotNumber& ballot_number = pvalue.ballot_number();
if (ballots.find(slot_number) != ballots.end()) {
if (CompareBallotNumbers(ballots[slot_number], ballot_number) <= 0) {
// If ballot number is less than one we've already seen, skip this
// pvalue.
continue;
}
}
ballots[slot_number] = ballot_number;
proposals_[slot_number] = pvalue.command();
}
}
}
} // namespace paxos
} // namespace process
| true |
a9000742df74db01e842d421898b6259a57ac205 | C++ | haoweiliang1996/spiderAndTrain | /structs.h | UTF-8 | 693 | 3.453125 | 3 | [] | no_license | #include <string>
using namespace std;
struct douNode {
string left, right;
douNode(string left, string right) {
this->left = left;
this->right = right;
}
bool operator< (const douNode& rhs) const {
if (left != rhs.left)
return left < rhs.left;
return right < rhs.right;
}
};
struct triNode {
string left, current, right;
triNode(string left, string current, string right) {
this->left = left;
this->current = current;
this->right = right;
}
bool operator< (const triNode& rhs) const {
if (left != rhs.left)
return left < rhs.left;
if (current != rhs.current)
return current < rhs.current;
return right < rhs.right;
}
}; | true |
857fa278fcb8f8b05be04bd8550eaeaec722d164 | C++ | Limeman/competitive_programming | /Leetcode/Remove Duplicates from Sorted Array/solution.cpp | UTF-8 | 571 | 3.390625 | 3 | [] | no_license | #include<vector>
/*
Solution to the Remove Duplicates from Sorted Array problem
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
*/
class Solution {
public:
int removeDuplicates(std::vector<int>& nums) {
if (nums.size() == 0) {
return 0;
}
else {
int i = 0;
for (int j = 0; j < nums.size(); ++j) {
if (nums[i] != nums[j]) {
++i;
nums[i] = nums[j];
}
}
return i + 1;
}
}
}; | true |
bee3967c4656aefbbb226f16b856bc5054bea745 | C++ | gusl0801/ShootingGame | /CBackBuffer.cpp | UTF-8 | 733 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#include "CBackBuffer.h"
#define ERASE_COLOR RGB(255,255,255)
CBackBuffer::CBackBuffer(HWND hWnd, const RECT &rtClientSize)
:m_hWnd(hWnd), m_rtClientSize(rtClientSize)
{
m_hBrush = CreateSolidBrush(ERASE_COLOR);
HDC hdc = ::GetDC(hWnd);
m_hDC = CreateCompatibleDC(hdc);
m_hBmp = CreateCompatibleBitmap(hdc, rtClientSize.right, rtClientSize.bottom);
SelectObject(m_hDC, m_hBmp);
DeleteDC(hdc);
}
CBackBuffer::~CBackBuffer()
{
if (m_hBrush) DeleteObject(m_hBrush);
if (m_hBmp) DeleteObject(m_hBmp);
if (m_hDC) DeleteDC(m_hDC);
}
void CBackBuffer::Present()
{
HDC hdc = ::GetDC(m_hWnd);
BitBlt(hdc, 0, 0, m_rtClientSize.right, m_rtClientSize.bottom,
m_hDC, 0, 0, SRCCOPY);
DeleteDC(hdc);
}
| true |
45b2824871718a216f2e5bf4d48f18fbcb935b49 | C++ | LeeKangW/CPP_Study | /STL_Univ/STL_Univ/소스.cpp | WINDOWS-1252 | 428 | 2.890625 | 3 | [
"MIT"
] | permissive | #include"default.h"
using namespace std;
class X {
private:
int num;
public:
X(int k) :num(k){}
friend ostream& operator<<(ostream& os, const X& k);
};
ostream& operator<<(ostream& os, const X& k)
{
os << k.num;
return os;
}
void change(X& a, X& b);
int main() {
X a{ 1 };
X b{ 2 };
change(a, b);
cout << a <<","<< b << endl;
//save("ҽ.cpp");
}
void change(X& a, X& b){
X c{ a };
a = b;
b = c;
}
| true |
dbdc25e289161adf9a07eb0dcbcb17da3436591f | C++ | charlesg3/faux | /tests/copy.cpp | UTF-8 | 2,951 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sched.h>
#include <utilities/time_arith.h>
static int g_cores;
static int g_iterations = 4096;
static int g_write_size = 4096;
static int g_writes = 10000;
static void create_file(char *filename);
static void copy_file(char *in_s, char *out_s);
static void remove_file(char *filename);
//static int g_socket_map[40] = {0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3};
static void copy_file(char *in_s, char *out_s)
{
int in_fd = open(in_s, O_RDONLY);
int out_fd = open(out_s, O_RDWR | O_CREAT, 0777);
char buf[16384];
int readsize;
while((readsize = read(in_fd, buf, sizeof(buf))))
{
int ret __attribute__((unused));
ret = write(out_fd, buf, readsize);
assert(ret == readsize);
}
close(in_fd);
close(out_fd);
}
void child_func(int id)
{
char dest[64];
for(int i = 0; i < g_iterations; i++)
{
char src[64];
snprintf(src, sizeof(src), "f%d", rand() % g_cores);
snprintf(dest, 64, "p%d.%d.%d", id, i, rand());
copy_file(src, dest);
remove_file(dest);
}
}
static void create_file(char *filename)
{
char buf[g_write_size];
int fd = open(filename, O_WRONLY | O_CREAT, 0777);
for(int i = 0; i < g_writes; i++)
{
if(write(fd, buf, g_write_size) < 0)
assert(false);
}
close(fd);
}
static void remove_file(char *filename)
{
int ret __attribute__((unused)) = unlink(filename);
assert(ret == 0);
}
int main(int ac, char **av)
{
char *cores_s = getenv("cpucount");
if(!cores_s)
{
fprintf(stderr, "cpucount not specified on command line, using 1.\n");
cores_s = "1";
}
g_cores = atoi(cores_s);
char *filesize_s = getenv("FILESIZE");
if(!filesize_s)
{
filesize_s = "128";
fprintf(stderr, "filesize not specified on command line, using %s.\n", filesize_s);
}
int filesize_k = atoi(filesize_s);
int filesize_b = 1024 * filesize_k;
assert(filesize_b >= g_write_size);
g_writes = filesize_b / g_write_size;
for(int i = 0; i < g_cores; i++)
{
char fname[128];
snprintf(fname, sizeof(fname), "f%d", i);
create_file(fname);
}
int children[g_cores];
for(int i = 0; i < g_cores; i++)
{
pid_t child = fork();
if(child == 0)
{
srand(i);
child_func(i);
exit(0);
}
else
children[i] = child;
}
for(int i = 0; i < g_cores; i++)
waitpid(children[i], NULL, 0);
for(int i = 0; i < g_cores; i++)
{
char fname[128];
snprintf(fname, sizeof(fname), "f%d", i);
remove_file(fname);
}
return 0;
}
| true |
8c89427bd36bf205849cdf445f2e31c2c1856776 | C++ | Gundoctor/MyTest | /FinalProject/Game/Source/GameObject/Controllers/CameraController.cpp | UTF-8 | 1,928 | 2.65625 | 3 | [] | no_license | #include "GamePCH.h"
CameraController::CameraController() :
m_currentFlags(0)
{
}
CameraController::~CameraController()
{
}
void CameraController::OnEvent(InputEvent *pEvent)
{
if (pEvent->GetDeviceType() == DeviceType::Keyboard)
{
if (pEvent->GetKeyState() == KeyState::Pressed)
{
if (pEvent->GetKeyID() == 'A')
{
m_currentFlags |= CAMERA_LEFT;
}
if (pEvent->GetKeyID() == 'D')
{
m_currentFlags |= CAMERA_RIGHT;
}
if (pEvent->GetKeyID() == 'W')
{
m_currentFlags |= CAMERA_UP;
}
if (pEvent->GetKeyID() == 'S')
{
m_currentFlags |= CAMERA_DOWN;
}
if (pEvent->GetKeyID() == 'Q')
{
m_currentFlags |= CAMERA_ZOOM_OUT;
}
if (pEvent->GetKeyID() == 'E')
{
m_currentFlags |= CAMERA_ZOOM_IN;
}
}
else if (pEvent->GetKeyState() == KeyState::Released)
{
if (pEvent->GetKeyID() == 'A')
{
m_currentFlags &= ~CAMERA_LEFT;
}
if (pEvent->GetKeyID() == 'D')
{
m_currentFlags &= ~CAMERA_RIGHT;
}
if (pEvent->GetKeyID() == 'W')
{
m_currentFlags &= ~CAMERA_UP;
}
if (pEvent->GetKeyID() == 'S')
{
m_currentFlags &= ~CAMERA_DOWN;
}
if (pEvent->GetKeyID() == 'Q')
{
m_currentFlags &= ~CAMERA_ZOOM_OUT;
}
if (pEvent->GetKeyID() == 'E')
{
m_currentFlags &= ~CAMERA_ZOOM_IN;
}
}
}
}
unsigned int CameraController::GetCurrentFlags()
{
return m_currentFlags;
} | true |
f608894fc9b35f8513e3c8da137d9d0871f9d0f7 | C++ | RavivTrichter/ATOOP | /Exercise2/Destination.h | UTF-8 | 1,099 | 2.953125 | 3 | [] | no_license | //
// Created by Admin on 19/05/2018.
//
#ifndef HW2_DESTINATION_H
#define HW2_DESTINATION_H
#include "Station.h"
#include "Vehicle.h"
#include <memory>
class Destination {
public:
Destination(weak_ptr<Station> station, shared_ptr<Vehicle> vehicle, int weight,const string& name); // C'tor
public:
//bool visited; // a data member that represents if the Node has been visited in DFS or not
/** Getters And Setters **/
const weak_ptr<Station> &getStation() const;
void setStation(const weak_ptr<Station> &station);
const shared_ptr<Vehicle> &getVehicle() const;
void setVehicle(const shared_ptr<Vehicle> &vehicle);
int getWeight() const;
void setWeight(int weight);
bool operator==(const weak_ptr<Destination> rhs);
const string &getStationName() const;
/** Data Members **/
bool visitedForMulti = false;
private:
weak_ptr<Station> station; // describes the destination station
shared_ptr<Vehicle> vehicle; // the type of vehicle in the edge
int weight;
string stationName;
};
#endif //HW2_DESTINATION_H
| true |
a791efb9c0d1dd6e4ca8502edb3d98565807f7e5 | C++ | mmf19144/programming2020 | /Ilya_prokofev/MatrixClass.cpp | UTF-8 | 5,971 | 3.796875 | 4 | [
"MIT"
] | permissive | #include <algorithm>
#include <fstream>
using namespace std;
class column
{
int* matrix;
const size_t dim;
const size_t column_idx;
public:
column(const size_t dim, int* m, const size_t col_id) : matrix(m), dim(dim), column_idx(col_id) {}
int& operator[](const size_t row)//column element reference
{
if (row > dim)
{
throw invalid_argument("Row index is greater than dimension");
}
return matrix[dim * (row - 1) + column_idx - 1];
}
};
class row
{
int* matrix;
const size_t dim;
const size_t row_idx;
public:
row(const size_t dim, int* m, const size_t _raw_id) : matrix(m), dim(dim), row_idx(_raw_id) {}
int& operator[](const size_t column)//row element reference
{
if (column > dim)
{
throw invalid_argument("Column index is greater than dimension");
}
return matrix[dim * (column - 1) + row_idx - 1];
}
friend ostream& operator<< (ostream& os, const row& m) {
for (size_t i = 0; i < m.dim; i++) {
os << m.matrix[m.row_idx * m.dim + i];
os << " ";
}
return os;
}
};
class Matrix
{
int* data; //matrix
size_t dim; //dimension
static int* allocate_matrix(int n) // memory allocation
{
int* L = new int[n * n];
for (size_t i = 0; i < n * n; i++) {
L[i] = 0;
}
return L;
}
public:
Matrix() : dim(0), data(nullptr) //default constructor
{}
Matrix(size_t n) : dim(n) //identity matrix constructor
{
data = allocate_matrix(n);
for (size_t i = 0; i < n; i++)
{
data[i * dim + i] = 1;
}
}
Matrix(size_t n, int m) : dim(n)
{
data = allocate_matrix(n);
for (size_t i = 0; i < n; i++)
{
data[i * dim + i] = m;
}
}
Matrix(size_t n, int* D) : dim(n) //diagonal matrix constructor
{
data = allocate_matrix(n);
for (size_t i = 0; i < n; i++)
{
data[i * dim + i] = D[i];
}
}
Matrix(const Matrix& that) : dim(that.dim) //copy constructor
{
this->data = allocate_matrix(dim);
for (size_t i = 0; i < dim * dim; i++)
{
this->data[i] = that.data[i];
}
}
void clear_matrix()
{
delete[] data;
}
int dimension()
{
return this->dim;
}
Matrix& operator=(const Matrix& that)
{
this->clear_matrix();
this->data = nullptr;
this->dim = that.dim;
this->data = allocate_matrix(dim);
for (size_t i = 0; i < dim; i++)
{
this->data[i] = that.data[i];
}
return *this;
}
Matrix operator+(const Matrix& that) const //matrix addition //function does not change this
{
if (this->dim != that.dim)
{
throw invalid_argument("wrong dimention");
}
int n1 = this->dim;
Matrix temp(n1);
for (size_t i = 0; i < n1 * n1; i++)
{
temp.data[i] = this->data[i] + that.data[i];
}
return temp;
}
void operator+=(const Matrix& that)
{
*this = *this + that;
}
void operator-=(const Matrix& that)
{
*this = *this - that;
}
void operator*=(const Matrix& that)
{
*this = *this * that;
}
Matrix operator-(const Matrix& that) const //substraction of matrices
{
if (this->dim != that.dim)
{
throw invalid_argument("wrong dimention");
}
size_t n1 = this->dim;
Matrix temp(n1);
for (size_t i = 0; i < n1*n1; i++)
{
temp.data[i] = this->data[i] - that.data[i];
}
return temp;
}
Matrix operator*(const Matrix& that) const //matrix multiplication
{
if (this->dim != that.dim)
{
throw invalid_argument("wrong dimention");
}
size_t n1 = this->dim;
Matrix temp(n1);
for (size_t i = 1; i <= n1; i++)
{
for (size_t j = 1; j <= n1; j++)
{
temp[i][j] = 0;
for (size_t k = 1; k <= n1; k++)
{
temp[i][j] += (*this)[k][j] * that[i][k];
}
}
}
return temp;
}
bool operator==(const Matrix& that) const //comparison of matrices
{
if (this->dim != that.dim)
{
return false;
}
for (size_t i = 0; i < dim; i++)
{
if (this->data[i] != that.data[i])
{
return false;
}
}
return true;
}
bool operator!=(const Matrix& that) const
{
return !(*this == that);
}
Matrix operator!() const //matrix transpose
{
Matrix res(*this);
for (size_t i = 1; i <= dim; i++)
{
for (size_t j = i + 1; j <= dim; j++)
{
swap(res[i][j], res[j][i]);
}
}
return res;
}
Matrix operator()(size_t raw, size_t column) const //minor, obtained by deleting the specifier raw and column
{
if (raw > dim)
{
throw invalid_argument("row index is greater than dim");
}
if (column > dim)
{
throw invalid_argument("column index is greater than dim");
}
Matrix res(this->dim - 1);
for (size_t i = 0; i < raw - 1; i++)
{
for (size_t j = 0; i < column - 1; j++)
{
res[i][j] = (*this)[i][j];
}
}
for (size_t i = raw; i < dim - 1; i++)
{
for (size_t j = 0; i < column - 1; j++)
{
res[i][j] = (*this)[i + 1][j];
}
}
for (size_t i = 0; i < raw - 1; i++)
{
for (size_t j = column; i < dim - 1; j++)
{
res[i][j] = (*this)[i][j + 1];
}
}
for (size_t i = raw; i < dim - 1; i++)
{
for (size_t j = column; i < dim - 1; j++)
{
res[i][j] = (*this)[i + 1][j + 1];
}
}
return res;
}
row operator[](size_t index) const//line access
{
if (index > dim)
{
throw invalid_argument("raw is greater than dim");
}
return { dim, data, index };
}
column operator()(const size_t index)//column access
{
if (index > dim)
{
throw invalid_argument("column is greater than dim");
}
return { dim, data, index };
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (size_t i = 0; i < m.dim; i++) {
os << m[i];
os << "\n";
}
return os;
}
friend istream& operator>>(istream& os, const Matrix& m) {
for (size_t i = 0; i < m.dim * m.dim; i++) {
os >> m.data[i];
}
return os;
}
~Matrix()
{
this->clear_matrix();
}
};
int main()
{
ifstream input("input.txt");
ofstream output("output.txt");
size_t dim, k;
input >> dim >> k; //reading data
Matrix A(dim), B(dim), C(dim), D(dim);
input >> A >> B >> C >> D;
input.close();
Matrix K(dim, k);
output << ((A + (B * (!C)) + K) * (!D));
return 0;
} | true |
2c136b71f6d831064828552a71805bdc8f1f83ab | C++ | ggzor/competitive-programming | /Kattis/orderlyclass.cpp | UTF-8 | 1,151 | 2.75 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
int main() {
string A, B;
getline(cin, A);
getline(cin, B);
int N = A.size();
auto left =
distance(A.begin(), mismatch(A.begin(), A.end(), B.begin()).first);
auto right =
distance(A.rbegin(), mismatch(A.rbegin(), A.rend(), B.rbegin()).first);
right = N - right - 1;
vector<vector<int>> idx(26, vector<int>());
for (int i = right; i < N; ++i) {
idx[B[i] - 'a'].push_back(i);
}
long long count = 0;
for (int i = 0; i <= left; ++i) {
int c = A[i] - 'a';
auto it = lower_bound(idx[c].begin(), idx[c].end(), i);
if (it != idx[c].end()) {
if (*it == i)
it++;
for (; it < idx[c].end(); it++) {
int j = *it;
int d = j - i + 1;
bool valid = true;
for (int k = 1; k < d; ++k) {
if (A[i + k] != B[j - k]) {
valid = false;
break;
}
}
if (valid) {
/* cout << i << ' ' << j << '\n'; */
count++;
}
}
}
}
cout << count << '\n';
}
| true |
0db9532071f6fc563d45049957b6311c20e801d8 | C++ | yanhongjuan/Algorithm | /sort/sort6_shell.cpp | UTF-8 | 1,330 | 3.515625 | 4 | [] | no_license | /*@brief:希尔排序*/
/*目的:利用插入排序简单,同时克服插入排序每次只交换两个元素的缺点*/
/*定义增量序列,递减的序列间隔,最后间隔为1进行插入排序*/
/*更小间隔的排序任然保持上一间隔有序*/
/*适用于数据量大的排序*/
/*希尔排序的时间复杂度和增量序列有关,{1,2,4,8..}这种为o(n^2),它是不稳定排序*/
/*参考博客:https://blog.csdn.net/zpznba/article/details/88407089 但是程序是错的,增量错误*/
#include <iostream>
#include <vector>
using namespace std;
void shell_sort(vector<int> &vec,int n)
{
int LenGap = 2;//
int gap = n/LenGap;//下标增量
while(gap>=1)
{
for(int i = gap;i<n;i++)
{
int num = vec[i];
int j = i-gap;
for(;j>=0;j=j-gap)
{
if(vec[j]>num)
vec[j+gap] = vec[j];
else break;
}
vec[j+gap] = num;
}
gap = gap/LenGap;//缩小增量为上一个的一半
}
}
int main()
{
int n;
vector<int> vec;
while(cin>>n)
{
vec.push_back(n);
if(cin.get()=='\n')
break;
}
int m = vec.size();
shell_sort(vec,m);
for(int i = 0;i<m;i++)
{
cout<<vec[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
91a2651062ccefc451c5b9c2a770dbccfc2db692 | C++ | yuting-zhang/UVa | /10945 - Mother bear/bear.cpp | UTF-8 | 761 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdio>
using namespace std;
bool is_char(char ch){
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
}
char to_uppercase(char ch){
if (ch >= 'A' && ch <= 'Z')
return ch;
return ch - ('a' - 'A');
}
int main(){
string line;
while (getline(cin, line) && line != "DONE"){
int head = 0, rear = line.size();
bool palindrome = true;
while (head < rear){
while (head < rear && !is_char(line[head]))
head++;
while (head < rear && !is_char(line[rear]))
rear--;
if (to_uppercase(line[head]) != to_uppercase(line[rear])){
palindrome = false;
break;
}
head++;
rear--;
}
if (palindrome)
printf("You won't be eaten!\n");
else
printf("Uh oh..\n");
}
}
| true |
441226cddc2c0bb381f31adb583af576a7ba806d | C++ | fazeelkhalid/University-of-Okara-Oop-final-2020 | /Q2/student.h | UTF-8 | 675 | 2.90625 | 3 | [] | no_license | #pragma once
#ifndef student_H
#include"user.h"
#include<iostream>
using namespace std;
class student:public user {
private:
char *name;
int sclass; // student class
public:
student() {
name = NULL;
sclass = 0;
}
void setStudentinfo() {
name = new char[36];
cout << "\nEnter student name without space : ";
cin >> name;
while (sclass <= 0) {
cout << "\nEnter student class : ";
cin >> sclass;
}
setUser();
}
void printStudentInfo() {
cout << "\nstudent name : " << name;
cout << "\nstudent class : " << sclass;
printUserNameandPin();
}
~student() {
if (name != NULL) {
delete[]name;
sclass = 0;
}
}
};
#endif // !student_H
| true |
bc05df82a4d94994a3b493e226e93d9780b0c736 | C++ | uym2/HGT_triplets | /tripPairs/RootedTree.cpp | UTF-8 | 24,275 | 2.828125 | 3 | [] | no_license | #include <cstdlib> // for exit
#include "rooted_tree.h"
#include "hdt.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <string>
/**************/
/* uym2 added */
void RootedTree::countLeaves(){
if (this->isLeaf()) {
this->n = 1;
return;
}
int nSum = 0;
for(TemplatedLinkedList<RootedTree*> *i = this->children; i != NULL; i = i->next) {
RootedTree *childI = i->data;
childI->countChildren();
nSum += childI->n;
}
this->n = nSum;
}
void RootedTree::__set_label__(stack<RootedTree*> &stk, string &label, bool &wait_for_int_lab){
if (label != ""){
if (!wait_for_int_lab){
RootedTree *p = this->factory->getRootedTree(label);
//cout << "Added one tree to the factory" << endl;
stk.push(p);
} else {
stk.top()->name = label;
}
}
label = "";
wait_for_int_lab = false;
}
bool RootedTree::read_newick_str(string str){
this->maxDegree = 0;
char c;
bool wait_for_int_lab = false;
bool is_at_root = true;
stack<RootedTree*> stk;
string label = "";
string::iterator it = str.begin();
while (it != str.end()){
c = *it;
if (c == '('){
if (is_at_root){
stk.push(this);
is_at_root = false;
}
else{
stk.push(NULL);
}
label = "";
++it;
} else if (c == ',') {
this->__set_label__(stk,label,wait_for_int_lab);
++it;
} else if (c == ')'){
this->__set_label__(stk,label,wait_for_int_lab);
RootedTree *q = stk.top();
stk.pop();
unsigned int numChildren = 0;
TemplatedLinkedList<RootedTree*> *children = NULL;
while (q != NULL && q != this){
numChildren++;
TemplatedLinkedList<RootedTree*> *newItem = factory->getTemplatedLinkedList();
newItem->data = q;
newItem->next = children;
children = newItem;
q = stk.top();
stk.pop();
}
if (q == NULL){
q = this->factory->getRootedTree();
}
q->children = children;
q->numChildren = numChildren;
for (TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
i->data->parent = q;
if (numChildren > this->maxDegree)
this->maxDegree = numChildren;
stk.push(q);
label = "";
wait_for_int_lab = true;
++it;
} else if (c == ';'){
stk.pop();
break;
} else if (c == ':'){
this->__set_label__(stk,label,wait_for_int_lab);
string se = "";
++it;
c = *it;
while (c != ',' && c != ')' && c != ';'){
se += c;
++it;
c = *it;
}
double e = strtod(se.c_str(),NULL);
stk.top()->edge_length = e;
wait_for_int_lab = false;
}
else {
label += c;
++it;
}
}
return true;
}
bool RootedTree::read_newick_file(string treeFile){
this->maxDegree = 0;
ifstream fin;
fin.open(treeFile.c_str());
char c;
bool wait_for_int_lab = false;
bool is_at_root = true;
stack<RootedTree*> stk;
string label = "";
while (!fin.eof()){
fin >> c;
if (c == '('){
if (is_at_root){
stk.push(this);
is_at_root = false;
}
else{
stk.push(NULL);
}
label = "";
}
else if (c == ',') {
this->__set_label__(stk,label,wait_for_int_lab);
} else if (c == ')'){
this->__set_label__(stk,label,wait_for_int_lab);
RootedTree *q = stk.top();
stk.pop();
unsigned int numChildren = 0;
TemplatedLinkedList<RootedTree*> *children = NULL;
while (q != NULL && q != this){
numChildren++;
TemplatedLinkedList<RootedTree*> *newItem = factory->getTemplatedLinkedList();
newItem->data = q;
newItem->next = children;
children = newItem;
q = stk.top();
stk.pop();
}
if (q == NULL){
q = this->factory->getRootedTree();
}
q->children = children;
q->numChildren = numChildren;
for (TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
i->data->parent = q;
if (numChildren > this->maxDegree)
this->maxDegree = numChildren;
stk.push(q);
label = "";
wait_for_int_lab = true;
} else if (c == ';'){
stk.pop();
break;
} else if (c == ':'){
this->__set_label__(stk,label,wait_for_int_lab);
double e;
fin >> e;
stk.top()->edge_length = e;
wait_for_int_lab = false;
}
else {
label += c;
}
}
fin.close();
return true;
}
void RootedTree::mark_active(TripletCounter *tripCount){
if (this->isLeaf())
return;
bool is_active = false;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next){
RootedTree* curr = i->data;
curr->mark_active(tripCount);
is_active = is_active || tripCount->isActive[curr->idx];
}
tripCount->isActive[this->idx] = is_active;
}
bool RootedTree::remove_child(RootedTree *child){
if (child->parent != this)
return false;
if (children == NULL)
return false;
if (children->data == child){
TemplatedLinkedList<RootedTree*> *temp = children;
children = children->next;
temp->next = NULL;
temp->data = NULL;
child->parent = NULL;
numChildren--;
return true;
}
for(TemplatedLinkedList<RootedTree*> *i = children; i->next != NULL; i = i->next){
if (child == i->next->data){
TemplatedLinkedList<RootedTree*> *temp = i->next;
i->next = i->next->next;
child->parent = NULL;
numChildren--;
return true;
}
}
return false;
}
RootedTree* RootedTree::reroot_at_edge(RootedTree* node, double x){
RootedTree* v = node;
if (v == this) // v is the root
return this;
/*for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next){
if (v == i->data)
return this; // v is one of the root's children
}*/
RootedTree *u = v->parent;
RootedTree *w = u->parent;
double ev = v->edge_length;
double eu = u->edge_length;
RootedTreeFactory *tFactory = new RootedTreeFactory();
RootedTree *newRoot = tFactory->getRootedTree();
newRoot->factory = tFactory;
//RootedTree *newRoot = this->factory->getRootedTree();
//newRoot->factory = this->factory;
u->remove_child(v);
newRoot->children = NULL;
newRoot->addChild(v);
newRoot->addChild(u);
v->edge_length = ev-x;
u->edge_length = x;
while(w != NULL){
v = w;
w = w->parent;
ev = v->edge_length;;
u->addChild(v);
v->edge_length = eu;
u = v;
eu = ev;
}
if (u->numChildren == 1){
// suppress unifurcation
// u has a single child; it is v = u->children->data
v = u->children->data;
double e = u->edge_length + v->edge_length;
w = u->parent;
w->remove_child(u);
v->edge_length = e;
w->addChild(v);
}
return newRoot;
}
void RootedTree::write_newick(ofstream &fout){
this->__write_newick__(fout);
fout << ";";
}
void RootedTree::__write_newick__(ofstream &fout){
if (this->isLeaf()){
fout << this->name;
if (this->edge_length >= 0)
fout << ":" << this->edge_length;
}
else {
fout << "(";
// first child
RootedTree *firstChild = this->children->data;
firstChild->__write_newick__(fout);
// the remaining children
for (TemplatedLinkedList<RootedTree*> *i = children->next; i != NULL; i = i->next){
fout << ",";
i->data->__write_newick__(fout);
}
fout << ")" << this->name;
if (this->edge_length >= 0)
fout << ":" << this->edge_length;
}
}
string RootedTree::toString(){
string myString = "";
this->__to_string__(myString);
myString += ";";
return myString;
}
void RootedTree::__to_string__(string &myString){
if (this->isLeaf()){
myString += this->name;
if (this->edge_length >= 0){
myString += ":";
std::ostringstream convertor;
convertor << this->edge_length;
myString += convertor.str(); //std::to_string(this->edge_length);
}
}
else {
myString += "(";
// first child
RootedTree *firstChild = this->children->data;
firstChild->__to_string__(myString);
// the remaining children
for (TemplatedLinkedList<RootedTree*> *i = children->next; i != NULL; i = i->next){
myString += ",";
i->data->__to_string__(myString);
}
myString += ")";
myString += this->name;
if (this->edge_length >= 0){
myString += ":";
std::ostringstream convertor;
convertor << this->edge_length;
myString += convertor.str(); //std::to_string(this->edge_length);
}
}
}
void RootedTree::print_leaves(){
if (this->isLeaf())
std::cout << this->name << " ";
else {
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next) {
i->data->print_leaves();
}
}
}
unsigned int RootedTree::set_all_idx(unsigned int startIdx){
unsigned int currIdx = startIdx;
this->set_idx(currIdx);
currIdx++;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
currIdx = t->set_all_idx(currIdx);
}
return currIdx;
}
void RootedTree::count_nodes(){
if (this->isLeaf())
this->nodeCounts = 1;
else{
unsigned int count = 1;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
t->count_nodes();
count += t->nodeCounts;
}
this->nodeCounts = count;
}
}
RootedTree* RootedTree::search_idx(unsigned int idx){
if(this->idx == idx)
return this;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
RootedTree *result = t->search_idx(idx);
if (result)
return result;
}
return NULL;
}
RootedTree* RootedTree::search_name(string name){
if(this->name == name)
return this;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
RootedTree *result = t->search_name(name);
if (result)
return result;
}
return NULL;
}
RootedTree* RootedTree::copyTree(RootedTreeFactory *factory){
// create a deep copy of tree t
//if (factory == NULL) factory = new RootedTreeFactory(NULL);
if (factory == NULL) factory = this->factory;
string tree_str = this->toString();
RootedTree *t_new = factory->getRootedTree();
t_new->factory = factory;
t_new->read_newick_str(tree_str);
return t_new;
}
RootedTree* RootedTree::down_root(RootedTree *u) {
// we assume that u is a grandchild of the root
RootedTreeFactory *factory = new RootedTreeFactory(NULL);
RootedTree *v = factory->getRootedTree();
RootedTree *v1 = factory->getRootedTree();
RootedTree *v2 = u->copyTree(factory);
// make a copy for each sister of u and make them the children of v1
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
if (i->data != u->parent){
v1->addChild(i->data->copyTree(factory));
}
}
// make a copy for each child of the root except for u->parent and make them the children of v1
for(TemplatedLinkedList<RootedTree*> *i = u->parent->children; i != NULL; i = i->next)
{
if (i->data != u) {
v1->addChild(i->data->copyTree(factory));
}
}
v->addChild(v1);
v->addChild(v2);
return v;
}
/*************/
void RootedTree::initialize(string name)
{
parent = altWorldSelf = NULL;
children = NULL;
level = maxDegree = 0;
numZeroes = numChildren = 0;
// Soda13 counting stuff set to default to -1 so we can print if they're not -1...
n = -1;
// Color 1 is standard...
color = 1;
this->name = name;
this->factory = NULL;
this->edge_length = -1;
}
bool RootedTree::isLeaf()
{
return numChildren == 0;
}
bool RootedTree::isRoot()
{
return this->parent == NULL;
}
void RootedTree::compute_d2root(){
if (this->isRoot())
this->d2root = 0;
for(TemplatedLinkedList<RootedTree*> *i = this->children; i != NULL; i = i->next){
RootedTree* t = i->data;
t->d2root = this->d2root + t->edge_length;
t->compute_d2root();
}
}
void RootedTree::addChild(RootedTree *t)
{
// uym2 added: if t has a parent, remove it from the parent's children first
if (t->parent != NULL){
t->parent->remove_child(t);
}
numChildren++;
t->parent = this;
TemplatedLinkedList<RootedTree*> *newItem = factory->getTemplatedLinkedList();
newItem->data = t;
newItem->next = children;
children = newItem;
}
RootedTree* RootedTree::getParent()
{
return parent;
}
void RootedTree::toDot()
{
cout << "digraph g {" << endl;
cout << "node[shape=circle];" << endl;
toDotImpl();
cout << "}" << endl;
}
vector<RootedTree*>* RootedTree::getList()
{
vector<RootedTree*>* list = new vector<RootedTree*>();
getListImpl(list);
return list;
}
bool RootedTree::prune_subtree(RootedTree* u){
RootedTree* w = u->parent;
if (w == NULL){
cerr << "Are you trying to remove the root?" << endl;
return false;
}
if (!w->remove_child(u)){
cerr << "Could not remove leaf!" << endl;
return false;
}
if (w->numChildren < 1){
cerr << "The tree has unifurcation?" << endl;
return false;
}
else if (w->numChildren == 1){
// supress unifurcation
//cerr << "Supress unifurcation after removing leaf ..." << endl;
RootedTree *v = w->children->data;
double l = v->edge_length;
w->remove_child(v);
if (w->parent == NULL) { // the leaf we are trying to remove is a child of the root
// w will replace v after the following commands
w->name = v->name;
while(v->children != NULL){
RootedTree *t = v->children->data;
double l1 = t->edge_length;
w->addChild(t);
t->edge_length = l+l1;
}
} else {
RootedTree *p = w->parent;
double l1 = w->edge_length;
p->remove_child(w);
p->addChild(v);
v->edge_length = l+l1;
}
}
return true;
}
bool RootedTree::pairAltWorld(RootedTree *t, bool do_pruning, TripletCounter *tripCount)
{
//bool error = false;
vector<RootedTree*>* l = t->getList();
map<string, RootedTree*> altWorldLeaves;
for(vector<RootedTree*>::iterator i = l->begin(); i != l->end(); i++)
{
RootedTree *leaf = *i;
altWorldLeaves[leaf->name] = leaf;
}
delete l;
l = getList();
map<string, RootedTree*>::iterator altWorldEnd = altWorldLeaves.end();
for(vector<RootedTree*>::iterator i = l->begin(); i != l->end(); i++)
{
RootedTree *leaf = *i;
map<string, RootedTree*>::iterator j = altWorldLeaves.find(leaf->name);
if (j == altWorldEnd)
{
// This leaf wasn't found in the input tree!
if (do_pruning){
// prune the leaf out from the first tree then continue
//cerr << leaf->name << " didn't exist in the second tree. Pruning it out from the first tree..." << endl;
if (this->prune_subtree(leaf)){
continue;
}
else {
cerr << "Could not remove leaf. Aborting!" << endl;
//error = true;
delete l;
return false;
}
} else {
cerr << "Leaves don't agree! Aborting! (" << leaf->name << " didn't exist in the second tree)" << endl;
//error = true;
delete l;
return false;
}
}
// If we got this far, we found the match! Setup bidirectional pointers!
leaf->altWorldSelf = j->second;
j->second->altWorldSelf = leaf;
// Delete result
altWorldLeaves.erase(j);
}
// Is there results left in altWorldLeaves? If so it had more leaves than we do...
if (altWorldLeaves.size() > 0)
{
if (tripCount != NULL){
for(map<string,RootedTree*>::iterator i = altWorldLeaves.begin(); i != altWorldLeaves.end(); i++){
//cerr << i->first << " didn't exist in the first tree. It will be ignored in the second tree..." << endl;
/*if (t->prune_subtree(i->second)){
cerr << "Success!" << endl;
} else
cerr << "Failed to remove the species out!" << endl; */
tripCount->isActive[i->second->idx] = false;
}
} else {
cerr << "Leaves don't agree! Aborting! (" << altWorldLeaves.begin()->first << " didn't exist in the first tree)";
if (altWorldLeaves.size() > 1)
cerr << " (and " << (altWorldLeaves.size() - 1) << " other leaves missing from first tree!)";
cerr << endl;
//error = true;
delete l;
return false;
}
}
delete l;
return true;
}
void RootedTree::colorSubtree(int c)
{
color = c;
if (altWorldSelf != NULL)
{
altWorldSelf->color = c;
if (altWorldSelf->hdtLink != NULL)
{
altWorldSelf->hdtLink->mark();
}
}
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
i->data->colorSubtree(c);
}
}
void RootedTree::markHDTAlternative()
{
if (altWorldSelf != NULL)
{
if (altWorldSelf->hdtLink != NULL)
{
altWorldSelf->hdtLink->markAlternative();
}
}
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
i->data->markHDTAlternative();
}
}
bool RootedTree::isError()
{
return this->error;
}
void RootedTree::toDotImpl()
{
cout << "n" << this << "[label=\"";
if (isLeaf() && numZeroes > 0) cout << "0's: " << numZeroes;
else cout << name;
cout << "\"];" << endl;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
t->toDotImpl();
cout << "n" << this << " -> n" << t << ";" << endl;
}
}
void RootedTree::getListImpl(vector<RootedTree*>* list)
{
if (isLeaf())
{
list->push_back(this);
}
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
t->level = level + 1;
t->getListImpl(list);
}
}
void RootedTree::computeNullChildrenData()
{
if (isLeaf()) return;
bool allZeroes = true;
numZeroes = 0;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
i->data->computeNullChildrenData();
if (i->data->numZeroes == 0) allZeroes = false;
else numZeroes += i->data->numZeroes;
}
if (!allZeroes) numZeroes = 0;
}
RootedTree* RootedTree::contract(RootedTreeFactory *factory)
{
computeNullChildrenData();
return contractImpl(factory);
}
RootedTree* RootedTree::contractImpl(RootedTreeFactory *factory)
{
if (isLeaf()) return this; // reuse leaves!!
if (factory == NULL) factory = new RootedTreeFactory(this->factory);
INTTYPE_REST totalNumZeroes = 0;
RootedTree *firstNonZeroChild = NULL;
RootedTree *ourNewNode = NULL;
for(TemplatedLinkedList<RootedTree*> *i = children; i != NULL; i = i->next)
{
RootedTree *t = i->data;
if (t->numZeroes > 0) totalNumZeroes += t->numZeroes;
else
{
if (firstNonZeroChild == NULL) firstNonZeroChild = t->contractImpl(factory);
else
{
if (ourNewNode == NULL)
{
ourNewNode = factory->getRootedTree();
ourNewNode->addChild(firstNonZeroChild);
}
ourNewNode->addChild(t->contractImpl(factory));
}
}
}
// Have we found >= 2 non-zero children?
if (ourNewNode == NULL)
{
// No... We only have 1 non-zero children!
if (firstNonZeroChild->numChildren == 2)
{
RootedTree *zeroChild = firstNonZeroChild->children->data;
RootedTree *otherOne = firstNonZeroChild->children->next->data;
if (zeroChild->numZeroes == 0)
{
RootedTree *tmp = otherOne;
otherOne = zeroChild;
zeroChild = tmp;
}
if (zeroChild->numZeroes != 0 && !otherOne->isLeaf())
{
// The 1 child has a zero child and only 2 children, the other not being a leaf, i.e. we can merge!
zeroChild->numZeroes += totalNumZeroes;
return firstNonZeroChild;
}
// if (zeroChild->numZeroes == 0) it's not a zerochild!!
}
// The child doesn't have a zero child, i.e. no merge...
ourNewNode = factory->getRootedTree();
ourNewNode->addChild(firstNonZeroChild);
}
// We didn't merge below --- add zero-leaf if we have any zeros...
if (totalNumZeroes > 0)
{
RootedTree *zeroChild = factory->getRootedTree();
zeroChild->numZeroes = totalNumZeroes;
ourNewNode->addChild(zeroChild);
}
return ourNewNode;
}
void RootedTree::__count_children__(RootedTree *t) {
if (t->isLeaf()) {
t->n = 1;
return;
}
int nSum = 0;
for(TemplatedLinkedList<RootedTree*> *i = t->children; i != NULL; i = i->next) {
RootedTree *childI = i->data;
this->__count_children__(childI);
nSum += childI->n;
}
t->n = nSum;
}
void RootedTree::countChildren(){
this->__count_children__(this);
}
bool __wayToSort__(RootedTree* i, RootedTree* j){
return i->d2root < j->d2root;
}
vector<RootedTree*> RootedTree::sort_leaf_by_d2root(){
this->compute_d2root();
vector<RootedTree*> L = *this->getList(); // leafset
sort(L.begin(),L.end(),__wayToSort__);
return L;
}
void __sum_d2root__(RootedTree *t, double & nleaves, double d2root, double & acc_sum){
if (t->isLeaf()){
nleaves += 1;
acc_sum += d2root;
} else {
for (TemplatedLinkedList<RootedTree*> *i = t->children; i != NULL; i = i->next){
__sum_d2root__(i->data, nleaves, d2root + i->data->edge_length, acc_sum);
}
}
}
double RootedTree::mean_d2root(){
double acc_sum = 0;
double nleaves = 0;
__sum_d2root__(this, nleaves, 0, acc_sum);
return acc_sum/nleaves;
}
| true |
0fdc7d4a97ae4bb79827c46842a857b40bd12872 | C++ | JingxueLiao/Data_Structures_and_Algorithms | /problems/find_the_duplicate_number.cpp | UTF-8 | 872 | 3.484375 | 3 | [
"MIT"
] | permissive | // Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.
// Assume that there is only one duplicate number, find the duplicate one.
// Note:
// You must not modify the array (assume the array is read only).
// You must use only constant, O(1) extra space.
// Your runtime complexity should be less than O(n2).
// There is only one duplicate number in the array, but it could be repeated more than once.
#include <vector>
using namespace std;
int FindDuplicate(const vector<int> &nums) {
if (nums.empty())
return 0;
int fast = 0, slow = 0;
do {
fast = nums[nums[fast]];
slow = nums[slow];
} while (fast != slow);
fast = 0;
while (fast != slow) {
fast = nums[fast];
slow = nums[slow];
}
return fast;
}
| true |
8147c119479938d37fc9a0b98679ead4db766571 | C++ | baris-topal/Polynomial_Calculation | /Polinom_Hesaplaması.cpp | UTF-8 | 4,022 | 2.953125 | 3 | [] | no_license |
#include <iostream>
#include <string>
using namespace std;
void yaz(int kat[], int kuv[], int boyut) {
string poli;
for (int i = 0; i < boyut; i++) {
if (kat[i] == 0) {}
else if (kuv[i] == 0 && kat[i] != 0) {
poli = poli + " " + to_string(kat[i]) + " +";
}
else {
poli = poli + " " + to_string(kat[i]) + "x^" + to_string(kuv[i]) + " +";
}
}
poli.pop_back();
cout << poli << endl;
}
void topla(int p1_kat[], int p1_ust[], int p1_boyut) {
int p2_boyut, * p2_kat, * p2_ust, * temp_kat, * temp_ust;
cout << "Toplanacak polinomun eleman sayisini giriniz: ";
cin >> p2_boyut;
p2_kat = new int[p2_boyut];
p2_ust = new int[p2_boyut];
for (int i = 0; i < p2_boyut; i++) {
cout << i + 1 << ". elemanin katsayisi: ";
cin >> p2_kat[i];
cout << i + 1 << ". elemanin kuvveti: ";
cin >> p2_ust[i];
}
cout << "Polinom: ";
yaz(p2_kat, p2_ust, p2_boyut);
int temp_boyut = p1_boyut + p2_boyut;
temp_kat = new int[temp_boyut];
temp_ust = new int[temp_boyut];
for (int i = 0; i < temp_boyut; i++) {
if (i < p1_boyut) {
temp_kat[i] = p1_kat[i];
temp_ust[i] = p1_ust[i];
}
else {
temp_kat[i] = p2_kat[i - p1_boyut];
temp_ust[i] = p2_ust[i - p1_boyut];
}
}
int son = temp_boyut, temp;
for (int i = 0; i < son; i++)
{
for (int j = i + 1; j < son; j++)
{
if (temp_ust[i] == temp_ust[j]) {
temp_kat[i] += temp_kat[j];
temp = temp_kat[j];
temp_kat[j] = temp_kat[son - 1];
temp_kat[son - 1] = temp;
temp = temp_ust[j];
temp_ust[j] = temp_ust[son - 1];
temp_ust[son - 1] = temp;
son--;
}
}
for (int k = 0; k < i; k++) {
if (temp_ust[i] == temp_ust[k]) {
temp_kat[k] += temp_kat[i];
temp = temp_kat[i];
temp_kat[i] = temp_kat[son - 1];
temp_kat[son - 1] = temp;
temp = temp_ust[i];
temp_ust[i] = temp_ust[son - 1];
temp_ust[son - 1] = temp;
i--;
son--;
}
}
}
cout << "Polinom Toplamasi: ";
yaz(temp_kat, temp_ust, son);
}
void cikar(int p1_kat[], int p1_ust[], int p1_boyut) {
int p2_boyut, * p2_kat, * p2_ust, * temp_kat, * temp_ust;
cout << "Cikarilacak polinomun eleman sayisini giriniz: ";
cin >> p2_boyut;
p2_kat = new int[p2_boyut];
p2_ust = new int[p2_boyut];
for (int i = 0; i < p2_boyut; i++) {
cout << i + 1 << ". elemanin katsayisi: ";
cin >> p2_kat[i];
cout << i + 1 << ". elemanin kuvveti: ";
cin >> p2_ust[i];
}
cout << "Polinom: ";
yaz(p2_kat, p2_ust, p2_boyut);
int temp_boyut = p1_boyut + p2_boyut;
temp_kat = new int[temp_boyut];
temp_ust = new int[temp_boyut];
for (int i = 0; i < temp_boyut; i++) {
if (i < p1_boyut) {
temp_kat[i] = p1_kat[i];
temp_ust[i] = p1_ust[i];
}
else {
temp_kat[i] = p2_kat[i - p1_boyut];
temp_ust[i] = p2_ust[i - p1_boyut];
}
}
int son = temp_boyut, temp;
for (int i = 0; i < son; i++)
{
for (int j = i + 1; j < son; j++)
{
if (temp_ust[i] == temp_ust[j]) {
temp_kat[i] -= temp_kat[j];
temp = temp_kat[j];
temp_kat[j] = temp_kat[son - 1];
temp_kat[son - 1] = temp;
temp = temp_ust[j];
temp_ust[j] = temp_ust[son - 1];
temp_ust[son - 1] = temp;
son--;
}
}
for (int k = 0; k < i; k++) {
if (temp_ust[i] == temp_ust[k]) {
temp_kat[k] -= temp_kat[i];
temp = temp_kat[i];
temp_kat[i] = temp_kat[son - 1];
temp_kat[son - 1] = temp;
temp = temp_ust[i];
temp_ust[i] = temp_ust[son - 1];
temp_ust[son - 1] = temp;
i--;
son--;
}
}
}
cout << "Polinom Cikarmasi: ";
yaz(temp_kat, temp_ust, son);
}
int main()
{
int* p1_kat, * p1_ust, p1_boyut;
cout << "Polinomun eleman sayisini giriniz: ";
cin >> p1_boyut;
p1_kat = new int[p1_boyut];
p1_ust = new int[p1_boyut];
int sayac = 0;
while (sayac < p1_boyut) {
cout << sayac + 1 << ". elemanin katsayisi: ";
cin >> p1_kat[sayac];
cout << sayac + 1 << ". elemanin kuvveti: ";
cin >> p1_ust[sayac];
sayac++;
}
cout << "Polinom: ";
yaz(p1_kat, p1_ust, p1_boyut);
topla(p1_kat, p1_ust, p1_boyut);
cikar(p1_kat, p1_ust, p1_boyut);
}
| true |
cd6067dd3edc5e10035c388f25016134f150846c | C++ | trojancode95/Day-toDay-Codes | /Sorting-Algorithms/ShellSort.cpp | UTF-8 | 654 | 3.3125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int shellsort(int arr[],int n)
{
for(int gap=n/2;gap>0;gap/=2)
{
for(int i=gap;i<n;i+=1)
{
int temp=arr[i];
int j;
for(j=i;j>=gap && arr[j-gap]>temp;j-=gap)
arr[j]=arr[j-gap];
arr[j]=temp;
}
}
return 0;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
shellsort(arr,n);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
/*
Sample Input:
5
2 4 1 5 4
Sample Output:
1 2 4 4 5
*/
| true |
862c86adb063c4c08a36d5d2ceb47c641fa89adb | C++ | abrdo/Widget_library---in_CPP | /MyWidgetApplications/selectorlist.cpp | UTF-8 | 4,034 | 2.515625 | 3 | [] | no_license | #include "selectorlist.hpp"
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
using namespace genv;
using namespace dowi;
SelectorList::SelectorList(int x, int y, int sx, int sy) : Widget(x,y,sx,sy){
_items = {};
_selected_index = -1;
_leading = _fonthight+2;
_scroll_shift = 0;
}
SelectorList::~SelectorList(){
for(auto item : _items)
delete item;
}
void SelectorList::new_item(string itemtext){
int y = 5 + _items.size()*_leading;
_items.push_back(new StaticTextComp(5, y, itemtext, 200,200,200));
}
void SelectorList::delete_selected(){
if(_selected_index != -1){
// modification of _y coordinates:
for(int i = _items.size()-1; _selected_index < i; i--){
_items[i]->set_y(_items[i-1]->get_y());
}
// deletion:
_items.erase(_items.begin()+_selected_index);
_selected_index = -1;
}
else cerr<<"warning: Can't delete, because there is no selection in SelectorList."<<endl;
}
void SelectorList::handle(event ev){
focus_by_click(ev);
/*
if(ev.keycode == key_delete)
delete_selected();
*/
if(focusing_click(ev)){
if(ev.pos_x<_x+_size_x-22){
int new_sel_ind = (ev.pos_y + _scroll_shift -_y-5)/_leading;
if(new_sel_ind < _items.size()) _selected_index = new_sel_ind;
}else if(ev.pos_y < _y+22){
_scroll_shift-=20;
}else if(ev.pos_y > _y+_size_y-22){
_scroll_shift+=20;
}
}
if(_targeted){
if(ev.button == btn_wheelup)
_scroll_shift-=4;
if(ev.button == btn_wheeldown)
_scroll_shift+=4;
}
if(_focused && ev.keycode== key_up && _selected_index != 0 && _selected_index != -1){
_selected_index--;
_scroll_shift = min(_scroll_shift, _items[_selected_index]->get_y()-3);
_scroll_shift = max(_scroll_shift, _items[_selected_index]->get_y()+_leading+3 - _size_y);
}
if(_focused && ev.keycode== key_down && _selected_index != -1){
_selected_index++;
if(_selected_index > _items.size()-1) _selected_index =_items.size()-1;
_scroll_shift = min(_scroll_shift, _items[_selected_index]->get_y()-3);
_scroll_shift = max(_scroll_shift, _items[_selected_index]->get_y()+_leading+3 - _size_y);
}
// _scroll_shift, _selected_index adjust, if it became invalid:
if(_items.size()*_leading+10 < _size_y) // the length of the displayed list is shorter then the _size_y
_scroll_shift = 0;
else if(_scroll_shift < 0)
_scroll_shift = 0;
else if(_scroll_shift > _items.size()*_leading+10 - _size_y)
_scroll_shift = _items.size()*_leading+10 - _size_y;
if(_selected_index < -1)
_selected_index = -1;
else if(_selected_index > _items.size()-1 && _selected_index != -1)
_selected_index = _items.size()-1;
}
void SelectorList::show(genv::canvas &c) const{
c<<move_to(_x,_y)<<color(_bgcol_r, _bgcol_g, _bgcol_b)<<box(_size_x, _size_y);
canvas canv;
canv.open(_size_x+1, 5+_items.size()*_leading+1);
canv.load_font(__fontfile, __fontsize);
canv.transparent(true);
// SELECT:
if(_selected_index != -1){
if(_focused)canv<<color(240,240,0);
else canv<<color(0.8*240 + 0.2*_bgcol_r, 0.8*240 + 0.2*_bgcol_g, 0.8*0 + 0.2*_bgcol_b);
canv<<move_to(4, 5 + _selected_index*(_leading))<<box(_size_x-8, _leading);
}
// LIST:
if(_selected_index != -1) _items[_selected_index]->set_rgb(50,50,50);
for(auto item : _items){
item->show(canv);
}
if(_selected_index != -1) _items[_selected_index]->set_rgb(200,200,200);
c<<stamp(canv, 0, 0+_scroll_shift, _size_x, _size_y, _x, _y);
// ScrollBar
c<<color(150,150,150);
c<<move_to(_x+_size_x-2, _y+2)<<box(-20, (_size_y-4));
c<<color(100,100,100);
c<<move_to(_x+_size_x-2, _y+2)<<box(-20,20);
c<<move_to(_x+_size_x-2, _y+_size_y-2)<<box(-20,-20);
// Frame
show_frame();
}
| true |
a12cfbfe82341d6e2f33e574c296834cfe633f7f | C++ | DavidLaMartina/RideTheWorm | /utility.cpp | UTF-8 | 19,646 | 3.390625 | 3 | [] | no_license | /**************************************************************************************************
* Project: Reusable Utility Functions
* Author: David LaMartina
* Date: January 17, 2018
* Description: These utility functions are applicable to a variety of programs. They are primarily
* used for validating numerical entries and converting them from strings to integers, and for
* verifying whether those integers are within a specified range. generateRandomInt also generates
* a pseudo-random integer using the CPU clock, and calling pauseSec between calls to
* generateRandomInt prevents duplicate "randomized" values.
*************************************************************************************************/
#include "utility.hpp"
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
using std::ostringstream;
#include <ctime>
using std::time;
#include <cstdlib>
using std::rand;
using std::srand;
#include <vector>
using std::vector;
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <iomanip>
using std::fixed;
using std::setprecision;
/**************************************************************************************************
* validateWordString: Re-prompts for string entry until the string is only letters (no spaces,
* numbers or other characters). Returns that string to calling function. Meant to be used
* following a program-specific prompt for string entry. Takes integer value for upper bounds of
* string length.
*************************************************************************************************/
string validateWordString(int stringLimit)
{
string userInput;
bool errFlag = false;
do
{
// Get string entry
getline(cin, userInput);
// Check whether string is appropriate length
if ( userInput.length() <= stringLimit && userInput.length() > 0 )
{
errFlag = true;
// Check whether all characters are letters
for (unsigned i = 0; i < userInput.length(); i++)
{
if ( !(isalpha(userInput[i])) )
{
errFlag = false;
}
}
}
else
{
errFlag = false;
}
if ( errFlag == false )
{
cout << "Invalid entry. Enter a word of " << stringLimit << " or fewer characters. ";
}
}
while ( errFlag == false );
return userInput;
}
/**************************************************************************************************
* validateWordString: Re-prompts for string entry until the string is only letters or SPACES (No
* numbres or other characters). Returns that string to calling function. Meant to be used
* following a program-specific prompt for string entry. Takes integer value for upper bounds of
* string length.
*************************************************************************************************/
string validateWordsString(int stringLimit)
{
string userInput;
bool errFlag = false;
do
{
// Get string entry
getline(cin, userInput);
// Check whether string is appropriate length
if ( userInput.length() <= stringLimit && userInput.length() > 0 )
{
errFlag = true;
// Check whether all characters are letters or spaces
for ( unsigned i = 0; i < userInput.length(); i++ )
{
if ( !isalpha(userInput[i]) && userInput[i] != ' ' )
{
errFlag = false;
}
}
}
else
{
errFlag = false;
}
if ( errFlag == false )
{
cout << "Invalid entry. Enter a string of " << stringLimit << " or fewer characters. ";
}
}
while ( errFlag == false );
return userInput;
}
/**************************************************************************************************
* validateWordString: Re-prompts for string entry until the string is within the specified length
* parameters.
*************************************************************************************************/
string validateStringLength(int stringLimit)
{
string userInput;
bool errFlag = false;
do
{
// Get user string input
getline(cin, userInput);
// Output error message if string is empty or too long
if ( userInput.length() > stringLimit || userInput.length() == 0 )
{
cout << "Invalid entry. Enter a string of " << stringLimit << " or fewer characters. ";
}
// Else set error flag to true so string can be returned
else
{
errFlag = true;
}
}
while ( errFlag == false );
return userInput;
}
/**************************************************************************************************
* validateIntString: This function accepts a string by value and an integer by reference. It
* returns a boolean value based upon whether or not the string represents an integer, and if the
* string does represent an integer, it also alters the referenced integer to become that integer.
*
* Idea for testing characters to validate integer entries found at
* http://www.cplusplus.com/forum/beginner/48769
*************************************************************************************************/
bool validateIntString(string stringIn, int& intIn)
{
// Check whether first character is a +, - or digit.
if ((stringIn[0] == '+') || (stringIn[0] == '-') || (isdigit(stringIn[0])))
{
// If any subsequent character is not a digit, the strings does not
// represent an integer.
for (unsigned count = 1; count < stringIn.length(); count++)
{
if (!(isdigit(stringIn[count])))
{
return false;
}
}
// If the first character is valid, and all of the subsequent characters are digits, then
// the string represents an integer. Modify referenced integer and return true.
stringstream convertString(stringIn);
convertString >> intIn;
return true;
}
// If the first character is not valid, then the string does not represent
// an integer.
else
{
return false;
}
}
/**************************************************************************************************
* validateIntRangeInc: Accepts an integer value to be evaluated, as well as 2 more integer values
* to be treated as upper and lower bounds (inclusive)
*************************************************************************************************/
bool validateIntRangeInc(int intIn, int lowerBounds, int upperBounds)
{
if ( (intIn >= lowerBounds) && (intIn <= upperBounds) )
{
return true;
}
else
{
return false;
}
}
/**************************************************************************************************
* validateIntRangeExc: Accepts an integer value to be evaluated, as well as 2 more integer values
* to be treated as upper and lower bounds (exclusive)
*************************************************************************************************/
bool validateIntRangeExc(int intIn, int lowerBounds, int upperBounds)
{
if ( (intIn > lowerBounds) && (intIn < upperBounds) )
{
return true;
}
else
{
return false;
}
}
/**************************************************************************************************
* validateNumEntryInc: Accepts a string, placeholder integer reference, and two ints for upper
* and lower bounds. If the string represents an integer entry within range of specified bounds,
* returns true and modifies placeholder integer accordingly. Returns false otherwise.
*************************************************************************************************/
bool validateNumEntryInc(string entryIn, int& intIn, int lowBounds, int upBounds)
{
// Check whether the entry is an integer without a negative or positive sign
if ( (validateIntString(entryIn, intIn)) && (entryIn[0] != '+') && (entryIn[0] != '-') )
{
// Check whether the integer is within the range of menu options
if ( (validateIntRangeInc(intIn, lowBounds, upBounds)) )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/**************************************************************************************************
* returnValidInt: Re-prompts user for a valid integer entry between upper and lower bounds until
* they have provided a valid entry; returns that valid integer. Uses a boolean flag and stream
* object to validate a string parameter as an integer.
*
* This function is meant to be called following an initial prompt specific to the program.
* The function will re-prompt generically following invalid entries.
*
* Adapted from code presented by TA Long Le in Piazza pinned thread Topic Discussion: Utility
* Functions on January 16, 2018
*************************************************************************************************/
int returnValidInt(int lowBounds, int upBounds)
{
bool errFlag = false; // boolean variable for evaluating result; default to false
string userInput; // string for storing user input
int validInt; // return integer
do
{
// Collect input
getline(cin, userInput);
// Create stringstream object and initialize with input string
stringstream inputStream(userInput);
// Check whether the string can be converted to an integer and whether there are any
// characters left over
if ( inputStream >> validInt && !(inputStream >> userInput) )
{
// Checks whether the input was within specified bounds (parameters)
if ( (validInt > upBounds) || (validInt < lowBounds) )
{
cout << "Invalid input. Enter an integer between " << lowBounds;
cout << " and " << upBounds << ". ";
}
// If the input WAS within bounds, set the error flag to true
else
{
errFlag = true;
}
}
// Entry wasn't an integer at all
else
{
cout << "Invalid input. Enter an integer between " << lowBounds;
cout << " and " << upBounds << ". ";
}
}
while (errFlag == false);
return validInt;
}
/**************************************************************************************************
* returnValidDouble: Re-prompts user for a valid double entry between upper and lower bounds and
* of a certain number of characters until they have provided a valid entry; returns that valid
* double. Uses a boolean flag and stream object to validate a string parameter as an integer.
*
* This function is meant to be called following an initial prompt specific to the program. The
* function will re-prompt generically following invalid entries.
*
* Adapted from code presented by TA Long Le in Piazza pinned thread Topic Discussion: Utility
* Functions on January 16, 2018
*************************************************************************************************/
double returnValidDouble(double lowBounds, double upBounds, int digLimit)
{
bool errFlag = false; // boolean variable for evaluating result; default to false
string userInput; // string for storing user input
double validDouble; // return double
do
{
// Collect input
getline(cin, userInput);
// stringstream object and initialize with input string
stringstream inputStream(userInput);
// Check whether the string can be converted to a double, whether there are any characters
// left over, and whether there are too many characters
if ( inputStream >> validDouble && !(inputStream >> userInput)
&& userInput.length() <= (digLimit + 1) )
{
// Check whether the input is in within specified bounds
if ( (validDouble > upBounds) || (validDouble < lowBounds) )
{
cout << "Invalid input. Enter a number between " << lowBounds << " and ";
cout << upBounds << " of " << digLimit << " or fewer digits. ";
}
// If the input WAS within bounds, set the error flag to true
else
{
errFlag = true;
}
}
// Entry wasn't a double at all
else
{
cout << "Invalid input. Enter a number between " << lowBounds << " and ";
cout << upBounds << " of " << digLimit << " or fewer digits. ";
}
}
while (errFlag == false);
return validDouble;
}
/**************************************************************************************************
* generateRandInt: Accepts integer values for upper and lower bounds and generates a random
* integer within those bounds. Any program that uses generateRandInt needs to place the following
* in the main function:
*
* #include<ctime>
* srand(time(NULL));
*
* Format for pseudo-random number generator found at:
* www.math.uaa.alaska.edu/~afkjm/csce211/handouts/RandomFunctions.pdf
*************************************************************************************************/
int generateRandInt(int lowBounds, int upBounds)
{
return (rand() % ( (upBounds + 1) - lowBounds ) ) + lowBounds;
}
/**************************************************************************************************
* generateRandomInt: Accepts integer values for upper and lower bounds and generates a random
* integer within those bounds.
*
* Format for pseudo-random number generator found in Starting Out with C++ Early Object, 9th
* Edition by Tony Gaddis, pages 134-136
*************************************************************************************************/
int generateRandomInt(int lowerBounds, int upperBounds)
{
// pause 1 second to ensure proper seeding
pauseSec(1);
unsigned seed = time(0);
srand(seed);
return (( rand() % (upperBounds - lowerBounds + 1)) + lowerBounds);
}
/**************************************************************************************************
* pauseSec: Accepts an integer value for a number of seconds and pauses the computer for that
* many seconds. Primarily inteded to avoid duplicate "random" integer outputs from
* generateRandomInt, which is seeded by the current time in the computer's clock.
*
* Idea for pause function from https://ubuntuforums.org/archive/index.php/t-42361.html
*************************************************************************************************/
void pauseSec(int numSec)
{
// Establish the time at which the function will end: the current time plus the number of
// seconds passed in as an argument
int waitTime = time(0) + numSec;
// Keep an empty loop running until the current time equals the fixed end time
while (waitTime > time(0));
}
/**************************************************************************************************
* generateProbInt: Accepts a vector of integers representing probabilities (element / sum of
* elements) of various events, and returns an integer (index value + 1) corresponding to one of
* those events.
*************************************************************************************************/
int generateProbInt(vector<int> vec)
{
int sum = 0; // holds sum of all elements
int randInt; // holds value generated via random integer generator
int sumLower = 0; // lower limit for value testing
int sumUpper = 0; // upper limit for value testing
// calculate sum of all elements
for ( unsigned i = 0; i < vec.size(); i++ )
{
sum += vec[i];
}
// generate random integer between 1 and the sum of all elements
randInt = generateRandomInt( 1, sum );
// Test whether each vector element is between the sum of all elements up to that index value
// (upper limit) and the sum of all elements up to the index value before (lower limit)
for ( unsigned i = 0; i < vec.size(); i++ )
{
if ( i > 0 )
{
sumLower += vec[i-1];
}
sumUpper += vec[i];
if ( ( sumLower < randInt ) && ( randInt <= sumUpper ) )
{
return i + 1;
}
}
}
/**************************************************************************************************
* convertIntToString: Accepts an integer and returns a converted string
*
* Idea for converting ints to strings from http://www.cplusplus.com/articles/D9j2Nwbp
*************************************************************************************************/
string convertIntToString(int intIn)
{
ostringstream converter; // output stream for conversion
converter << intIn; // stream the integer characters into converter
return converter.str(); // extract and return the string
}
/**************************************************************************************************
* convertDoubleToString: Accepts a double value and returns a converted string
*************************************************************************************************/
string convertDoubleToString(double doubleIn)
{
ostringstream converter;
converter << fixed;
converter << setprecision(1);
converter << doubleIn;
return converter.str();
}
/**************************************************************************************************
* convertStringToInt: Converts string to int - meant to be used internally, not with a user's
* input. Returns 0 if input can't be converted.
*************************************************************************************************/
int convertStringToInt(string stringIn)
{
stringstream intStream(stringIn); // stream object for conversion
int returnInt; // valid integer for return
string testString; // used to test whether there are any characters left
// Check whether the string can be converted to an int and whether there are characters left
if ( intStream >> returnInt && !(intStream >> testString) )
{
return returnInt;
}
// Return 0 if conversion fails
else
{
return 0;
}
}
/**************************************************************************************************
* convertStringToDouble: Converts string to double - meant to be used internally, not with a
* user's input. Returns 0 if input can't be converted.
*************************************************************************************************/
double convertStringToDouble(string stringIn)
{
stringstream doubleStream(stringIn); // stream object for conversion
double returnDouble; // valid double for return
string testString; // tests whether there are any characters left
// Check whether string can be converted to double and whether there are any characters left
if ( doubleStream >> returnDouble && !(doubleStream >> testString) )
{
return returnDouble;
}
// Return 0 if conversion fails
else
{
return 0.00;
}
}
| true |
24b7ae17ecf9fcadaff1149ffb501065a6be50da | C++ | kuki-xie/- | /336多关键字排序/336.cpp | UTF-8 | 872 | 3.34375 | 3 | [] | no_license | //
// main.cpp
// 336多关键字排序
//
// Created by 谢容海 on 2020/12/18.
//
#include <iostream>
#include <algorithm>
using namespace std;
struct stu{
char name[20];
int age,score;
}stu[100];// 整数小于等于100
bool compare(struct stu stu1,struct stu stu2){
if (stu1.score != stu2.score) {
return stu1.score > stu2.score;
}
else{
if (strcmp(stu1.name,stu2.name) != 0) {
return strcmp(stu1.name, stu2.name) < 0;
}
else
return stu1.age < stu2.age;
}
}
int main(){
int n,i = 0;
cin >> n;// n个学生的数据
for (i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].age >> stu[i].score;
}
sort(stu, stu + n, compare);
for (i = 0; i < n; i++) {
cout << stu[i].name << ' ' << stu[i].age << ' ' << stu[i].score << endl;
}
return 0;
}
| true |
d2efa4cf11d7ccadccc2600dc6b42c2c0cce67fb | C++ | sadads1337/fit-gl | /src/Kononov/Common/Scene/DirectionInputController.cpp | UTF-8 | 2,507 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "DirectionInputController.hpp"
namespace Kononov {
void DirectionInputController::update(float /*delta*/) {}
void DirectionInputController::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
m_lastPosition = event->pos();
m_mousePressed = true;
}
}
void DirectionInputController::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton && m_mousePressed) {
handleMove(event->pos());
m_mousePressed = false;
}
}
void DirectionInputController::mouseMoveEvent(QMouseEvent *event) {
if (m_mousePressed) {
handleMove(event->pos());
}
}
void DirectionInputController::handleMove(const QPoint &position) {
auto diff = position - m_lastPosition;
m_yaw -= static_cast<float>(diff.x()) * m_sensitivity;
m_pitch -= static_cast<float>(diff.y()) * m_sensitivity;
m_lastPosition = position;
if (m_object != nullptr) {
m_object->setRotation(getRotation());
}
}
QQuaternion DirectionInputController::getRotation() const noexcept {
return QQuaternion::fromEulerAngles(m_pitch, m_yaw, 0);
}
QVector3D DirectionInputController::getWalkDirection() const noexcept {
return QQuaternion::fromEulerAngles(0, m_yaw, 0)
.rotatedVector(QVector3D(0, 0, -1));
}
QVector3D DirectionInputController::getRightDirection() const noexcept {
return QQuaternion::fromEulerAngles(0, m_yaw, 0)
.rotatedVector(QVector3D(1, 0, 0));
}
// NOLINTNEXTLINE(readability-convert-member-functions-to-static)
QVector3D DirectionInputController::getUpDirection() const noexcept {
return QVector3D(0, 1, 0);
}
const std::shared_ptr<PositionedObject> &
DirectionInputController::getObject() const noexcept {
return m_object;
}
void DirectionInputController::setObject(
const std::shared_ptr<PositionedObject> &object) {
m_object = object;
if (m_object != nullptr) {
m_object->setRotation(getRotation());
}
}
float DirectionInputController::getSensitivity() const noexcept {
return m_sensitivity;
}
void DirectionInputController::setSensitivity(float sensitivity) {
DirectionInputController::m_sensitivity = sensitivity;
}
float DirectionInputController::getYaw() const noexcept { return m_yaw; }
void DirectionInputController::setYaw(float yaw) {
DirectionInputController::m_yaw = yaw;
}
float DirectionInputController::getPitch() const noexcept { return m_pitch; }
void DirectionInputController::setPitch(float pitch) {
DirectionInputController::m_pitch = pitch;
}
} // namespace Kononov
| true |
bbbc063fa4371524c61fbeb5ca27c41c444cdc08 | C++ | DrGr4f1x/raytracing-ref | /core/texture.h | UTF-8 | 1,206 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
#include "noise.h"
class Texture
{
public:
virtual Vec3 value(float u, float v, const Vec3& p) const = 0;
};
class ConstantTexture : public Texture
{
public:
ConstantTexture(const Vec3& c)
: m_color(c)
{}
Vec3 value(float u, float v, const Vec3& p) const override
{
return m_color;
}
private:
const Vec3 m_color;
};
class CheckerTexture : public Texture
{
public:
CheckerTexture(const Texture* evenTex, const Texture* oddTex)
: m_evenTex(evenTex)
, m_oddTex(oddTex)
{}
Vec3 value(float u, float v, const Vec3& p) const override;
private:
const Texture* m_evenTex{ nullptr };
const Texture* m_oddTex{ nullptr };
};
class NoiseTexture : public Texture
{
public:
NoiseTexture() = default;
NoiseTexture(float s)
: m_scale(s)
{}
Vec3 value(float u, float v, const Vec3& p) const override;
private:
Perlin m_noise;
float m_scale{ 1.0f };
};
class ImageTexture : public Texture
{
public:
ImageTexture() = default;
ImageTexture(unsigned char* pixels, int A, int B)
: m_data(pixels)
, m_nx(A)
, m_ny(B)
{}
Vec3 value(float u, float v, const Vec3& p) const override;
private:
unsigned char* m_data{ nullptr };
int m_nx{ 0 };
int m_ny{ 0 };
}; | true |
c8c35a0188f5274f1091255f9e8a0fe288bb556f | C++ | EvaristArdon/portafolio_00361518 | /Ejercicios labo/Labo 2/Ejercicio5c.cpp | UTF-8 | 643 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
void TorrHanoi(int discos,int Orig,int Aux, int Dest){
if(discos==1)
cout<<"Sujeta el disco de la torre "<<Orig<<" y colocalo en la torre "<<Dest<<endl;
else{
TorrHanoi(discos-1,Orig,Dest,Aux);
cout<<"Sujeta el disco de la torre "<<Orig<<" y colocalo en la torre "<<Dest<<endl;
TorrHanoi(discos-1,Aux,Orig,Dest);
}
}
int main()
{
int discos=0,Orig=1,Aux=2,Dest=3;
cout<<"Ingrese el numero de discos: ";
cin>>discos;
cout<<"Para resolver la torre con "<<discos<<" realizar los siguientes pasos\n";
TorrHanoi(discos,Orig,Aux,Dest);
return 0;
}
| true |
7da349d70f4186303106ac7697fdaba3b157b035 | C++ | sweetmentor/Learning-cpp | /hello-cpp-world.cc | UTF-8 | 1,161 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main() {
// std::cout << " / |" << std::endl;
// std::cout << " /____|" << std::endl;
// std::cout << " /|" << std::endl;
// std::cout << " / |" << std::endl;
// std::cout << " / |" << std::endl;
// std::cout << " / |" << std::endl;
// std::cout << " /____|" << std::endl;
// working with strings
// string phrase = "Code Institute";
// string phrasesub;
// phrasesub = phrase.substr(8, 3);
// cout << phrasesub;
// working with numbers
// cout << 5 + 2;
// int wnu = 5;
// double dnum = 5.5;
// double sump = wnu + dnum;
// cout << sump;
// Getting user input
// double age;
// cout << "Enter your age: ";
// cin >> age;
// cout << "You are " << age << " years old.";
// string name;
// cout << "What is your name? ";
// cin >> name;
// cout << "Your name is " << name ;
string name;
cout << "What is your name? ";
getline (cin, name);
cout << "Your name is " << name << " Hello " << name;
return 0;
}
| true |
bebb2d56f0a5e4de7286382222b08bfb2f911793 | C++ | Apelcina/Super-Matching | /Super-Matching/src/utility_funcs.cpp | UTF-8 | 879 | 3.875 | 4 | [] | no_license | #include <iostream>
void swap(int* arr, int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
int partition(int* arr, int low, int high)
{
int j = low;
int pivot = arr[high];
for(int i = low; i < high; i++)
if(arr[i] <= pivot)
{
swap(arr, i, j);
j++;
}
swap(arr, j, high);
return j;
}
void quickSort(int* arr, int low, int high)
{
int pi;
if (low < high)
{
pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void binarySearch(int* arr, int size, int target)
{
int low = 0;
int high = size - 1;
int mid;
while(low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == target)
{
std::cout << "Quicksort binary search found " << arr[mid] << " in both arrays." << std::endl;
break;
}
else if(arr[mid] <= target)
low = mid + 1;
else
high = mid - 1;
}
}
| true |
27a7ac2d023e26818b7cd4dd3369f030f1c3b643 | C++ | Crazyremi/ITSA-C- | /c_mm37.cpp | UTF-8 | 514 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
if(a==0&&b==0)
cout << "origin\n";
else if(a==0)
cout << "y-axis\n";
else if (b==0)
{
cout << "x-axis\n";
}
else if (a>0&&b>0)
{
cout << "1st Quadrant\n";
}
else if (a>0&&b<0)
{
cout << "4th Quadrant\n";
}
else if (a<0&&b>0)
{
cout << "2nd Quadrant\n";
}
else if (a<0&&b<0)
{
cout << "3rd Quadrant\n";
}
} | true |
ea93dec74fcba1ec7743028c6aa16eb59c6212e1 | C++ | piecedigital/GGPOPLUSR | /src/util/procutil.cpp | UTF-8 | 989 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <"procutil.h">
#include <stdexcept>
#include <Windows.h>
#include <Psapi.h>
namespace util {
bool get_module_bounds(const char* name, uintptr_t* start, uintptr_t* end) {
const auto module = GetModuleHandle(name);
if (module == nullptr) {
return false;
}
MODULEINFO info;
GetModuleInformation(GetCurrentProcess(), module, &info, sizeof(info));
*start = (uintptr_t)info.lpBaseOfDll;
*end = *start + info.SizeOfImage;
return true;
}
uintptr_t sigscan(const char* name, const char* pattern, const char* mask) {
uintptr_t start, end;
if (!get_module_bounds(name, &start, &end))
throw std::runtime_error("Module not Loaded (?)");
const auto last_scan = end - strlen(mask) - 1;
for (auto addr = start; addr < last_scan; addr++) {
for (size_t i = 0;; i++) {
if (mask[i] == '\0') {
return addr;
}
if (mask[i] != '?' && sig[i] != *(char*)(addr + i))
break;
}
}
throw std::runtime_error("Signature not found");
}
} | true |
c20936f9febc0722384b6bd88678e27920dca246 | C++ | Hd0702/Search_Engine | /queryprocessor.cpp | UTF-8 | 5,974 | 2.9375 | 3 | [] | no_license | #include "queryprocessor.h"
/**
* @brief queryProcessor::queryProcessor : this takes user input and sets into our processor
* @param qur : this is the user query we're going to analyze
*/
queryProcessor::queryProcessor(string qur)
{
query = qur;
}
/**
* @brief queryProcessor::splitQuery : this stems every query and removes all stop words
*/
void queryProcessor::splitQuery() {
readstop.stopWords();
//THIS METHOD TAKES OUR QUERY AND SPLITS IT AND STEMS IT
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char>> tokens(query,sep);
boost::tokenizer<boost::char_separator<char>>::iterator iter = tokens.begin();;
if(*iter == "AND") { //Handles AND words
++iter;
while(iter != tokens.end()) {
if(*iter != "NOT") { //go through everything until it hits a NOT and iadd it to and
string find = *iter;
boost::algorithm::to_lower(find);
if(!readstop.stops.contains(find)) {
Porter2Stemmer::stem(find);
and_vect.push_back(readQuery(find));
ands.push_back(find);
}
iter++;
}
else { //if we found not
//once we find not we go through the rest of the query and add it to not vector
iter++;
while(iter != tokens.end()) { //add all nots
string find = *iter;
boost::algorithm::to_lower(find);
if(!readstop.stops.contains(find)) {
Porter2Stemmer::stem(find);
not_vect.push_back(readQuery(find));
nots.push_back(find);
}
iter++;
}
return;
}
}
}
else if(*iter == "OR") { //Handles OR words
++iter;
while(iter != tokens.end()) { //take every word and check if its NOT
if(*iter != "NOT") { // go through the rest of the vect,until we Hit NOT
string find = *iter;
boost::algorithm::to_lower(find);
if(!readstop.stops.contains(find)) {
Porter2Stemmer::stem(find);
or_vect.push_back(readQuery(find));
ors.push_back(find);
}
iter++;
}
else { //if we found not
iter++;
while(iter != tokens.end()) { //add all nots
string find = *iter;
boost::algorithm::to_lower(find);
if(readstop.stops.contains(find)) {
Porter2Stemmer::stem(find);
nots.push_back(find);
not_vect.push_back(readQuery(find));
}
iter++;
}
return;
}
}
}
else { //only one word
string find = *iter;
boost::algorithm::to_lower(find);
Porter2Stemmer::stem(find);
//we're going to add that to or vector anyway
or_vect.push_back(readQuery(find));
return;
}
}
//You must use this method regardless of Boolean value
/**
* @brief queryProcessor::readQuery : this takes all of our seperate vectors and loads in the word from
* the index value, and then we compare all of our results\n
* this is essentially the heart of the user input section of the project
* @param find : this is our individual word that we are going to analyze
* @return : this may look really complex, but think of it as a pair with key string and the value is essentially
* an ID# a boolean set to true for AND words, and a double for the total score
*/
pair<string,vector<pair<pair<int,bool>,double>>> queryProcessor::readQuery(string find) {
reads.open("indexInterface.txt");
pair<string,vector<pair<pair<int,bool>,double>>> WordQue;
if(!reads) {
cerr << "indexInterface could not be opened!";
exit(EXIT_FAILURE);
}
else {
int totalQ,totalWord;
string top50;
reads >> totalQ;
reads >> totalWord;
reads.ignore('\n');
getline(reads, top50,'\n');
string buffer;
//We use while true since writing IndexInt. creates newline at the end
while(true) {
getline(reads,buffer);
if(buffer.empty())
break;
//tokenize and stem every word in the query
boost::char_separator<char> sep(" ");
boost::tokenizer< boost::char_separator<char> > tok(buffer, sep);
boost::tokenizer<boost::char_separator<char>>::iterator iter = tok.begin();
//if the word in the index file is our word we're looking for, save all the ID and score values
if(*iter == find) {
WordQue.first = find;
iter++;
while(iter != tok.end()) {
//turn them all into proper casts and store them into our add pair
int id = boost::lexical_cast<int>(*iter);
iter++;
double score = boost::lexical_cast<double>(*iter);
pair<pair<int,bool>,double> add;
add.first.first = id;
add.first.second = false;
add.second = score;
WordQue.second.push_back(add);
iter++;
}
break;
}
}
//sort all the queues into ascending order so most important comes first
sort(WordQue.second.begin(), WordQue.second.end(), []( const std::pair<pair<int,bool>, int> &p1,
const std::pair<pair<int,bool>, double> &p2 )
{
return (p1.second > p2.second);
} );
reads.close();
return WordQue;
}
}
| true |
a2d01402016f713d0cc5c7c37a8e3420a9b44deb | C++ | Alaxe/noi2-ranking | /2020/solutions/E/PDP-Varna/PDP/balans.cpp | UTF-8 | 386 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
int n;
char a;
int brAB;
int brCD;
int brB;
cin >> n;
cin >> a;
if(a == 'a' || a == 'b')
{
brAB++;
}
if(a == 'c' || a == 'd')
{
brCD++;
}
if(brAB == brCD)
{
brB++;
}
cout << brB << endl;
return 0;
}
| true |
2467a3860089ea360b9939a7894f0156237a6eb3 | C++ | buresm11/mirunInterpreter | /src/Visitor.h | UTF-8 | 42,495 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include "tlVisitor.h"
#include "tlParser.h"
#include "Runtime.h"
#include "IntObj.h"
#include "StringObj.h"
#include "BoolObj.h"
#include "ArrayObj.h"
#include "ContextValue.h"
#include "FuncArgDeclContext.h"
#include "Function.h"
#include "FuncArg.h"
#include "Scope.h"
//#define DEBUG_ENABLED
#ifdef DEBUG_ENABLED
#define Debug(x) std::cout << x;
#else
#define Debug(x)
#endif
class Runtime;
class Visitor : public tlVisitor
{
Runtime * runtime;
Scope * scope;
public:
Visitor(Runtime * runtime) : runtime(runtime)
{
scope = runtime->create_new_scope();
}
Scope * get_scope()
{
return scope;
}
antlrcpp::Any visitParse(tlParser::ParseContext *context)
{
Debug(": parse" << std::endl);
ContextValue * context_value = visit(context->top_block());
return context_value;
}
antlrcpp::Any visitTop_block(tlParser::Top_blockContext *context)
{
Debug(": top_block" << std::endl);
for(int i=0; i < context->function_decl().size(); i++)
{
ContextValue * context_value = visit(context->function_decl().at(i));
if(context_value->has_error()) return context_value;
else delete context_value;
}
for (int i=0; i < context->statement().size(); i++)
{
ContextValue * context_value = visit(context->statement().at(i));
if(context_value->has_error() || context_value->has_done()) return context_value;
else delete context_value;
}
return new ContextValue();
}
antlrcpp::Any visitBlock(tlParser::BlockContext *context)
{
Debug(": block" << std::endl);
for (int i=0; i < context->statement().size(); i++)
{
ContextValue * context_value = visit(context->statement().at(i));
if(context_value->has_error() || context_value->has_done()) return context_value;
else delete context_value;
}
return new ContextValue();
}
antlrcpp::Any visitStatement(tlParser::StatementContext *context)
{
Debug(": statement" << std::endl);
ContextValue * context_value_statement = NULL;
if(context->variable_def() != NULL)
{
context_value_statement = visit(context->variable_def());
}
else if(context->assignment() != NULL)
{
context_value_statement = visit(context->assignment());
}
else if(context->if_statement() != NULL)
{
context_value_statement = visit(context->if_statement());
}
else if(context->while_statement() != NULL)
{
context_value_statement = visit(context->while_statement());
}
else if(context->function_call() != NULL)
{
context_value_statement = visit(context->function_call());
}
else if(context->return_statement() != NULL)
{
context_value_statement = visit(context->return_statement());
}
else { /* Not possible */ }
return context_value_statement;
}
antlrcpp::Any visitVariable_def(tlParser::Variable_defContext *context)
{
Debug(": variable_def" << std::endl);
if(context->index() != NULL)
{
ContextValue * context_value_index = visit(context->index());
if(context_value_index->has_error()) return context_value_index;
int index = ((IntObj *)context_value_index->get_obj())->get_value();
delete_expression(context_value_index);
return new_array_variable_def(context->Type_identifier()->getText(), context->Identifier()->getText(), index);
}
else
{
return new_variable_def(context->Type_identifier()->getText(), context->Identifier()->getText());
}
}
ContextValue* new_variable_def(std::string type, std::string name)
{
Debug(": new variable" << std::endl);
Obj * var = NULL;
if(type.compare("string") == 0)
{
var = new StringObj();
}
else if(type.compare("int") == 0)
{
var = new IntObj();
}
else if(type.compare("bool") == 0)
{
var = new BoolObj();
}
else
{
return new ContextValue(NULL, new Error(5, "Unexpexted type " + type));
}
return scope->current_environment()->create_variable(name, var);
}
ContextValue* new_array_variable_def(std::string type, std::string name, int index)
{
Debug(": new array variable" << std::endl);
if(index == 0)
{
return new ContextValue(NULL, new Error(6, "Cannon create array sized 0"));
}
Obj ** var = new Obj*[index];
Type type_content;
if(type.compare("string") == 0)
{
type_content = StringType;
for(int i=0;i<index;i++)
{
var[i] = new StringObj();
}
}
else if(type.compare("int") == 0)
{
type_content = IntType;
for(int i=0;i<index;i++)
{
var[i] = new IntObj();
}
}
else if(type.compare("bool") == 0)
{
type_content = BoolType;
for(int i=0;i<index;i++)
{
var[i] = new BoolObj();
}
}
else
{
return new ContextValue(NULL, new Error(5, "Unexpexted type " + type));
}
Array * array = new Array(var, index);
Obj * array_var = new ArrayObj( array, type_content);
ContextValue * context_value_allocate = runtime->allocate_on_heap(array);
if(context_value_allocate->has_error()) return context_value_allocate;
else delete context_value_allocate;
return scope->current_environment()->create_variable(name, array_var);
}
antlrcpp::Any visitAssignment(tlParser::AssignmentContext *context)
{
Debug(": assignment" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
if(context->index() != NULL)
{
ContextValue * context_value_index = visit(context->index());
if(context_value_index->has_error()) return context_value_index;
int index = ((IntObj *)context_value_index->get_obj())->get_value();
delete_expression(context_value_index);
Obj * obj = context_value_expression->get_obj();
delete context_value_expression;
return scope->current_environment()->set_array_variable(context->Identifier()->getText(), obj, index);
}
else
{
Obj * obj = context_value_expression->get_obj();
delete context_value_expression;
return scope->current_environment()->set_variable(context->Identifier()->getText(), obj);
}
}
antlrcpp::Any visitIf_statement(tlParser::If_statementContext *context)
{
Debug(": if_statement" << std::endl);
ContextValue * context_value_if = visit(context->if_stat());
if(context_value_if->has_error() || context_value_if->has_done())
{
return context_value_if;
}
if(!((BoolObj*)context_value_if->get_obj())->get_value())
{
delete_expression(context_value_if);
for(int i=0; i < context->else_if_stat().size(); i++)
{
ContextValue * context_value_else_if = visit(context->else_if_stat().at(i));
if(context_value_else_if->has_error() || context_value_else_if->has_done())
{
return context_value_else_if;
}
if(((BoolObj*)context_value_else_if->get_obj())->get_value())
{
delete_expression(context_value_else_if);
return new ContextValue();
}
else delete_expression(context_value_else_if);
}
}
else
{
delete_expression(context_value_if);
return new ContextValue();
}
if(context->else_stat() != NULL)
{
ContextValue * context_value_else = visit(context->else_stat());
if(context_value_else->has_error() || context_value_else->has_done())
{
return context_value_else;
}
delete context_value_else;
}
return new ContextValue();
}
antlrcpp::Any visitIf_stat(tlParser::If_statContext *context)
{
Debug(": if_stat" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
if(context_value_expression->get_obj()->get_type() != BoolType)
{
delete_expression(context_value_expression);
return new ContextValue(NULL, new Error(12, "If Condition is not bool"));
}
if(((BoolObj*)context_value_expression->get_obj())->get_value())
{
scope->create_new_environment();
ContextValue * contex_value_if_block = visit(context->block());
scope->remove_top_environment();
if(contex_value_if_block->has_error() || contex_value_if_block->has_done())
{
delete_expression(context_value_expression);
return contex_value_if_block;
}
delete contex_value_if_block;
}
return context_value_expression;
}
antlrcpp::Any visitElse_if_stat(tlParser::Else_if_statContext *context)
{
Debug(": else_if_stat" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
if(context_value_expression->get_obj()->get_type() != BoolType)
{
delete_expression(context_value_expression);
return new ContextValue(NULL, new Error(12, "If Condition is not bool"));
}
if(((BoolObj*)context_value_expression->get_obj())->get_value())
{
scope->create_new_environment();
ContextValue * contex_value_else_if_block = visit(context->block());
scope->remove_top_environment();
if(contex_value_else_if_block->has_error() || contex_value_else_if_block->has_done())
{
delete_expression(context_value_expression);
return contex_value_else_if_block;
}
delete contex_value_else_if_block;
}
return context_value_expression;
}
antlrcpp::Any visitElse_stat(tlParser::Else_statContext *context)
{
Debug(": else_stat" << std::endl);
scope->create_new_environment();
ContextValue * contex_value_else_block = visit(context->block());
scope->remove_top_environment();
if(contex_value_else_block->has_error() || contex_value_else_block->has_done())
{
return contex_value_else_block;
}
delete contex_value_else_block;
return new ContextValue();
}
antlrcpp::Any visitWhile_statement(tlParser::While_statementContext *context)
{
Debug(": while_statement" << std::endl);
while(true)
{
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
if(context_value_expression->get_obj()->get_type() != BoolType)
{
delete_expression(context_value_expression);
return new ContextValue(NULL, new Error(12, "While Condition is not bool"));
}
bool ex = ((BoolObj*)context_value_expression->get_obj())->get_value();
delete_expression(context_value_expression);
if(!ex)
{
break;
}
else
{
scope->create_new_environment();
ContextValue * contex_value_while_block = visit(context->block());
scope->remove_top_environment();
if(contex_value_while_block->has_error() || contex_value_while_block->has_done())
{
return contex_value_while_block;
}
delete contex_value_while_block;
}
}
return new ContextValue();
}
antlrcpp::Any visitFunction_decl(tlParser::Function_declContext *context)
{
Debug(": func_decl" << std::endl);
FuncArgDeclContext * func_decl_context_type = visit(context->func_decl_type());
if(func_decl_context_type->has_error())
{
return ContextValue(NULL, new Error(func_decl_context_type->get_error()->get_id(), func_decl_context_type->get_error()->get_text()));
}
std::string name = func_decl_context_type->get_func_arg()->get_name();
FuncArg * return_type = func_decl_context_type->get_func_arg();
delete func_decl_context_type;
Function * function;
if(context->func_decl_type_list() == NULL)
{
function = new Function(context->block(), return_type);
}
else
{
std::vector<FuncArgDeclContext*> func_decl_context_args = visit(context->func_decl_type_list());
FuncArg ** args = new FuncArg*[func_decl_context_args.size()];
for(int i=0; i< func_decl_context_args.size(); i++)
{
if(func_decl_context_args.at(i)->has_error())
{
for(int j=0;j<func_decl_context_args.size();j++)
{
delete func_decl_context_args.at(j)->get_func_arg();
}
for(int j=i;j<func_decl_context_args.size();j++)
{
delete func_decl_context_args.at(j);
}
delete [] args;
return ContextValue(NULL, new Error(func_decl_context_args.at(i)->get_error()->get_id(), func_decl_context_args.at(i)->get_error()->get_text()));
}
args[i] = func_decl_context_args.at(i)->get_func_arg();
delete func_decl_context_args.at(i);
}
function = new Function(context->block(), return_type, args, func_decl_context_args.size());
}
return runtime->create_new_function(name, function);
}
antlrcpp::Any visitFunc_decl_type_list(tlParser::Func_decl_type_listContext *context)
{
Debug(": func_decl_type_list" << std::endl);
std::vector<FuncArgDeclContext *> func_decl_context_args;
for(int i=0; i< context->func_decl_type_arg().size(); i++)
{
FuncArgDeclContext * func_decl_context_arg = visit(context->func_decl_type_arg().at(i));
func_decl_context_args.push_back(func_decl_context_arg);
}
return func_decl_context_args;
}
antlrcpp::Any visitFunc_decl_type_arg(tlParser::Func_decl_type_argContext *context)
{
Debug(": func_decl_type_arg" << std::endl);
if(context->func_decl_type() != NULL)
{
return visit(context->func_decl_type());
}
else if(context->func_decl_array_type() != NULL)
{
return visit(context->func_decl_array_type());
}
else
{
return new FuncArgDeclContext(NULL, new Error(14, "Syntax error"));
}
}
antlrcpp::Any visitFunc_decl_type(tlParser::Func_decl_typeContext *context)
{
Debug(": func_decl_type" << std::endl);
std::string type_string = context->Type_identifier()->getText();
Type arg_type;
if(type_string.compare("string") == 0)
{
arg_type = StringType;
}
else if(type_string.compare("int") == 0)
{
arg_type = IntType;
}
else if(type_string.compare("bool") == 0)
{
arg_type = BoolType;
}
else
{
return new FuncArgDeclContext(NULL, new Error(13, "Unknown type"));
}
FuncArg * func_arg = new FuncArg(context->Identifier()->getText(), false, arg_type);
return new FuncArgDeclContext(func_arg, NULL);
}
antlrcpp::Any visitFunc_decl_array_type(tlParser::Func_decl_array_typeContext *context)
{
Debug(": func_decl_array_type" << std::endl);
std::string type_string = context->Type_identifier()->getText();
Type arg_type;
if(type_string.compare("string") == 0)
{
arg_type = StringType;
}
else if(type_string.compare("int") == 0)
{
arg_type = IntType;
}
else if(type_string.compare("bool") == 0)
{
arg_type = BoolType;
}
else
{
return new FuncArgDeclContext(NULL, new Error(13, "Unknown type"));
}
FuncArg * func_arg = new FuncArg(context->Identifier()->getText(), true, arg_type);
return new FuncArgDeclContext(func_arg, NULL);
}
antlrcpp::Any visitPrintFunctionCall(tlParser::PrintFunctionCallContext *context)
{
Debug(": print function" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
runtime->print(context_value_expression->get_obj(), false);
delete_expression(context_value_expression);
return new ContextValue();
}
antlrcpp::Any visitPrintLnFunctionCall(tlParser::PrintLnFunctionCallContext *context)
{
Debug(": print function" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
runtime->print(context_value_expression->get_obj(), true);
delete_expression(context_value_expression);
return new ContextValue();
}
antlrcpp::Any visitScanFunctionCall(tlParser::ScanFunctionCallContext *context)
{
Debug(": scan function" << std::endl);
if(context->index() != NULL)
{
ContextValue * context_value_index = visit(context->index());
if(context_value_index->has_error()) return context_value_index;
int index = ((IntObj *)context_value_index->get_obj())->get_value();
delete_expression(context_value_index);
return runtime->scan(context->Identifier()->getText(), index, scope);
}
return runtime->scan(context->Identifier()->getText(), scope);
}
antlrcpp::Any visitIdentifierFunctionCall(tlParser::IdentifierFunctionCallContext *context)
{
Debug(": function" << std::endl);
ContextValue * context_value_func = invoke(context->Identifier()->getText(), context->expression());
if(context_value_func->has_error())
{
return context_value_func;
}
delete_expression(context_value_func);
return new ContextValue();
}
ContextValue * invoke(std::string name, std::vector<tlParser::ExpressionContext *> expressions)
{
int args_size = expressions.size();
if(args_size == 0)
{
return runtime->invoke_function(name, NULL, args_size);
}
Obj ** args = new Obj*[args_size];
for(int i=0;i< args_size; i++)
{
ContextValue * context_value_expression = visit(expressions.at(i));
if(context_value_expression->has_error())
{
for(int j=0; j<i; j++)
{
delete args[i];
}
delete [] args;
return context_value_expression;
}
else
{
args[i] = context_value_expression->get_obj();
}
delete context_value_expression;
}
return runtime->invoke_function(name, args, args_size);
}
antlrcpp::Any visitFunctionCallExpression(tlParser::FunctionCallExpressionContext *context)
{
Debug(": function_call_expression" << std::endl);
ContextValue * context_value_func = invoke(context->Identifier()->getText(), context->expression());
return context_value_func;
}
antlrcpp::Any visitReturn_statement(tlParser::Return_statementContext *context)
{
Debug(": return statement" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
context_value_expression->set_done(true);
return context_value_expression;
}
antlrcpp::Any visitIdentifierExpression(tlParser::IdentifierExpressionContext *context)
{
Debug(": identifier" << std::endl);
if(context->index() != NULL)
{
ContextValue * context_value_index = visit(context->index());
if(context_value_index->has_error()) return context_value_index;
int index = ((IntObj *)context_value_index->get_obj())->get_value();
delete_expression(context_value_index);
return scope->current_environment()->look_up_array_variable(context->Identifier()->getText(), index);
}
else
{
return scope->current_environment()->look_up_variable(context->Identifier()->getText());
}
}
antlrcpp::Any visitIndex(tlParser::IndexContext *context)
{
Debug(": index" << std::endl);
ContextValue * context_value_expression = visit(context->expression());
if(context_value_expression->has_error())
{
return context_value_expression;
}
else
{
if(context_value_expression->get_obj()->get_type() == IntType)
{
return context_value_expression;
}
else
{
delete context_value_expression->get_obj();
delete context_value_expression;
return new ContextValue(NULL, new Error(4, "Index is not a number"));
}
}
}
antlrcpp::Any visitNumberExpression(tlParser::NumberExpressionContext *context)
{
Debug(": number_expression" << std::endl);
int number;
try
{
number = std::stoi(context->Number()->getText());
}
catch(std::invalid_argument & e)
{
return new ContextValue(NULL, new Error(1, "Unknown number"));
}
catch(std::out_of_range & e)
{
return new ContextValue(NULL, new Error(2, "Integer out of range"));
}
Obj * obj = new IntObj(number);
return new ContextValue(obj, NULL);
}
antlrcpp::Any visitStringExpression(tlParser::StringExpressionContext *context)
{
Debug(": string_expression" << std::endl);
std::string string = context->String()->getText().substr(1, context->String()->getText().size() -2 );
return new ContextValue(new StringObj(string), NULL);
}
antlrcpp::Any visitBoolExpression(tlParser::BoolExpressionContext *context)
{
Debug(": bool_expression" << std::endl);
bool value;
if(context->Bool()->getText().compare("true") == 0)
{
value = true;
}
else
{
value = false;
}
Obj * obj = new BoolObj(value);
return new ContextValue(obj, NULL);
}
antlrcpp::Any visitLtExpression(tlParser::LtExpressionContext *context)
{
Debug(": lt_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() < ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator < unsupported types" ));
}
}
antlrcpp::Any visitGtExpression(tlParser::GtExpressionContext *context)
{
Debug(": gt_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() > ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator > unsupported types" ));
}
}
antlrcpp::Any visitNotEqExpression(tlParser::NotEqExpressionContext *context)
{
Debug(": not_eq_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() != ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
if(contex_value_l->get_obj()->get_type() == StringType && contex_value_r->get_obj()->get_type() == StringType)
{
Obj * return_obj = new BoolObj(((StringObj*)(contex_value_l->get_obj()))->get_value() != ((StringObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
if(contex_value_l->get_obj()->get_type() == BoolType && contex_value_r->get_obj()->get_type() == BoolType)
{
Obj * return_obj = new BoolObj(((BoolObj*)(contex_value_l->get_obj()))->get_value() != ((BoolObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator != unsupported types" ));
}
}
antlrcpp::Any visitModulusExpression(tlParser::ModulusExpressionContext *context)
{
Debug(": modulus_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(((IntObj*)(contex_value_l->get_obj()))->get_value() % ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator % unsupported types" ));
}
}
antlrcpp::Any visitNotExpression(tlParser::NotExpressionContext *context)
{
Debug(": not_expression" << std::endl);
ContextValue* contex_value = visit(context->expression());
if(contex_value->has_error()) return contex_value;
if(contex_value->get_obj()->get_type() == BoolType)
{
Obj * return_obj = new BoolObj(!((BoolObj*)(contex_value->get_obj()))->get_value());
delete_expression(contex_value);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expression(contex_value);
return new ContextValue(NULL, new Error(3, "Operator ! unsupported types" ));
}
}
antlrcpp::Any visitMultiplyExpression(tlParser::MultiplyExpressionContext *context)
{
Debug(": multiply_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(((IntObj*)(contex_value_l->get_obj()))->get_value() * ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator * unsupported types" ));
}
}
antlrcpp::Any visitGtEqExpression(tlParser::GtEqExpressionContext *context)
{
Debug(": gt_eq_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() >= ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator >= unsupported types" ));
}
}
antlrcpp::Any visitDivideExpression(tlParser::DivideExpressionContext *context)
{
Debug(": divide_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(((IntObj*)(contex_value_l->get_obj()))->get_value() / ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator / unsupported types" ));
}
}
antlrcpp::Any visitOrExpression(tlParser::OrExpressionContext *context)
{
Debug(": or_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == BoolType && contex_value_r->get_obj()->get_type() == BoolType)
{
Obj * return_obj = new BoolObj(((BoolObj*)(contex_value_l->get_obj()))->get_value() || ((BoolObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator || unsupported types" ));
}
}
antlrcpp::Any visitUnaryMinusExpression(tlParser::UnaryMinusExpressionContext *context)
{
Debug(": unary_minus_expression" << std::endl);
ContextValue* contex_value = visit(context->expression());
if(contex_value->has_error()) return contex_value;
if(contex_value->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(-((IntObj*)(contex_value->get_obj()))->get_value());
delete_expression(contex_value);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expression(contex_value);
return new ContextValue(NULL, new Error(3, "Operator - unsupported types" ));
}
}
antlrcpp::Any visitEqExpression(tlParser::EqExpressionContext *context)
{
Debug(": eq_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() == ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
if(contex_value_l->get_obj()->get_type() == StringType && contex_value_r->get_obj()->get_type() == StringType)
{
Obj * return_obj = new BoolObj(((StringObj*)(contex_value_l->get_obj()))->get_value() == ((StringObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
if(contex_value_l->get_obj()->get_type() == BoolType && contex_value_r->get_obj()->get_type() == BoolType)
{
Obj * return_obj = new BoolObj(((BoolObj*)(contex_value_l->get_obj()))->get_value() == ((BoolObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator == unsupported types" ));
}
}
antlrcpp::Any visitAndExpression(tlParser::AndExpressionContext *context)
{
Debug(": and_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == BoolType && contex_value_r->get_obj()->get_type() == BoolType)
{
Obj * return_obj = new BoolObj(((BoolObj*)(contex_value_l->get_obj()))->get_value() && ((BoolObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator && unsupported types" ));
}
}
antlrcpp::Any visitAddExpression(tlParser::AddExpressionContext *context)
{
Debug(": add_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(((IntObj*)(contex_value_l->get_obj()))->get_value() + ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
if(contex_value_l->get_obj()->get_type() == StringType && contex_value_r->get_obj()->get_type() == StringType)
{
Obj * return_obj = new StringObj(((StringObj*)(contex_value_l->get_obj()))->get_value() + ((StringObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator + unsupported types" ));
}
}
antlrcpp::Any visitSubtractExpression(tlParser::SubtractExpressionContext *context)
{
Debug(": substract_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new IntObj(((IntObj*)(contex_value_l->get_obj()))->get_value() - ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator - unsupported types" ));
}
}
antlrcpp::Any visitLtEqExpression(tlParser::LtEqExpressionContext *context)
{
Debug(": lt_eq_expression" << std::endl);
ContextValue* contex_value_l = visit(context->expression().at(0));
if(contex_value_l->has_error()) return contex_value_l;
ContextValue* contex_value_r = visit(context->expression().at(1));
if(contex_value_r->has_error())
{
delete_expression(contex_value_l);
return contex_value_r;
}
if(contex_value_l->get_obj()->get_type() == IntType && contex_value_r->get_obj()->get_type() == IntType)
{
Obj * return_obj = new BoolObj(((IntObj*)(contex_value_l->get_obj()))->get_value() <= ((IntObj*)(contex_value_r->get_obj()))->get_value());
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(return_obj, NULL);
}
else
{
delete_expressions(contex_value_l, contex_value_r);
return new ContextValue(NULL, new Error(3, "Operator <= unsupported types" ));
}
}
void delete_expression(ContextValue* contex_value)
{
delete contex_value->get_obj();
delete contex_value;
}
void delete_expressions(ContextValue* contex_value_l, ContextValue* contex_value_r)
{
delete contex_value_l->get_obj();
delete contex_value_r->get_obj();
delete contex_value_l;
delete contex_value_r;
}
}; | true |
f7c2db7d563187d1a0356ab8ac831a828b5621df | C++ | mdarafat1819/Timus-OJ | /1209 - 1, 10, 100, 1000...(using b_search).cpp | UTF-8 | 615 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
#define SIZE 65537
#define u_int unsigned int
using namespace std;
int b_search(u_int ara[], int l, int r, u_int k)
{
if(l > r) return 0;
int mid = l + (r - l) / 2;
if(ara[mid] == k) return 1;
if(ara[mid] < k) return b_search(ara, mid + 1, r, k);
if(ara[mid] > k) return b_search(ara, l, mid - 1, k);
}
int main()
{
int t;
cin>>t;
u_int ans[SIZE], k, i;
for(i = 1; i < SIZE; i++) ans[i] = (i * (i - 1)) / 2 + 1;
while(t--)
{
cin>>k;
if(b_search(ans, 0, SIZE - 1, k)) cout<<"1 ";
else cout<<"0 ";
}
return 0;
}
| true |
6acfbc2c92937e8a3f2d9e0e90f321fd92dbdc75 | C++ | idgetto/PancakeArduino | /PancakePrinter/Extruder.cpp | UTF-8 | 750 | 2.921875 | 3 | [] | no_license | #include "Extruder.h"
#include <Arduino.h>
Extruder::Extruder(Adafruit_DCMotor *pumpMotor,
Adafruit_DCMotor *solenoidMotor) :
_pumpMotor{pumpMotor},
_solenoidMotor{solenoidMotor} {
}
void Extruder::extrudeOn(float speed) {
openValve();
runPump(speed);
delay(850);
}
void Extruder::extrudeOff() {
stopPump();
closeValve();
delay(500);
}
void Extruder::runPump(int speed) {
_pumpMotor->setSpeed(255);
_pumpMotor->run(FORWARD);
}
void Extruder::stopPump() {
_pumpMotor->run(RELEASE);
}
void Extruder::openValve() {
_solenoidMotor->setSpeed(255);
_solenoidMotor->run(FORWARD);
}
void Extruder::closeValve() {
_solenoidMotor->run(RELEASE);
}
| true |
402072750f75f75b9bc9d0a59bd75378af59298a | C++ | vu1p3n0x/GameGame | /GameGame/GameGame/textobject.h | UTF-8 | 988 | 2.5625 | 3 | [] | no_license | // FILE: textobject.h
// DATE: 2/25/13
// DESC: declaration of the class to manage an object of text
#ifndef TEXTOBJECT_H
#define TEXTOBJECT_H
// #define _CRT_SECURE_NO_WARNINGS
#include <string>
#include "graphicsobject.h"
#ifndef FONTOBJECT_H
class FontObject;
#endif
class TextObject
{
private:
struct VertexType
{
D3DXVECTOR3 position;
D3DXVECTOR2 texture;
};
std::string m_text;
ID3D11Buffer* m_vertexBuffer;
ID3D11Buffer* m_indexBuffer;
int m_vertexCount;
int m_indexCount;
float m_positionX, m_positionY;
float m_red, m_blue, m_green;
bool m_recreate;
friend class FontObject;
void Recreate(GraphicsObject* graphics, FontObject* font);
public:
TextObject();
TextObject(const TextObject& textobject);
~TextObject();
bool Initialize(GraphicsObject* graphics, std::string text, float positionX, float positionY);
void Shutdown();
void SetText(std::string text);
void SetPosition(float positionX, float positionY);
};
#include "fontobject.h"
#endif | true |
c7eee53ec3cc4882b6839836cc8eddba648848f2 | C++ | kolusask/Snake | /field.hpp | UTF-8 | 735 | 2.515625 | 3 | [] | no_license | #ifndef FIELD_H
#define FIELD_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdlib.h>
#include "snake.hpp"
#define TILE_WIDTH 50
#define TILE_HEIGHT 50
enum Tiles { EMPTY, HEAD, TAIL, TREAT };
class Field {
public:
Field(const int w, const int h, const unsigned snake_len);
~Field();
int update(Directions dir);
private:
int draw();
void show();
void drop_treat();
const int width;
const int height;
int snake_length;
int treat_x;
int treat_y;
Snake snake;
Tiles **map;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *head_texture;
SDL_Texture *tail_texture;
SDL_Texture *treat_texture;
friend void handle(Field*);
};
#endif
| true |
d1ae870bc0d8f031e5c65ad3a535eb842f9cccff | C++ | cms-analysis/HeavyFlavorAnalysis-Bs2MuMu | /ana-naegeli/ncFormula.cpp | UTF-8 | 5,845 | 2.890625 | 3 | [] | no_license | /*
* ncFormula.cpp
*
* Created by Christoph Nägeli <christoph.naegeli@psi.ch> on 02.07.12.
*
*/
// my headers
#include "ncFormula.h"
// Standard headers
#include <algorithm>
#include <utility>
#include <queue>
using std::string;
ncFormula::ncFormula() : fName(""), fOp(false)
{}
ncFormula::ncFormula(std::string name, bool op) : fName(name), fOp(op)
{}
#pragma mark -
static ncTree<ncFormula> *read_exp1(string::iterator b, string::iterator e,string::iterator &last);
// read single expression
static ncTree<ncFormula> *read_exp6(string::iterator b, string::iterator e, string::iterator &last)
{
ncTree<ncFormula> *result;
if (*b == '(') {
int paraCount = 1;
last = b+1;
while (paraCount > 0 && last != e) {
if (*last == '(') paraCount++;
else if (*last == ')') paraCount--;
last++;
}
if (paraCount > 0) throw string("Paranthesis does not close");
result = read_exp1(b+1, last-1, last);
last++; // skipp paranthesis
} else if (*b == '!') {
result = new ncTree<ncFormula>(ncFormula("!",true));
result->setChild2(read_exp6(b+1,e,last));
} else {
char specials[] = {'_','.'}; // append here?
for (last = b; last != e &&
( ('a' <= *last && *last <= 'z') ||
('A' <= *last && *last <= 'Z') ||
('0' <= *last && *last <= '9') ||
(std::find(specials, specials+sizeof(specials)/sizeof(char), *last) != specials+sizeof(specials)/sizeof(char)) ); ++last) {}
result = new ncTree<ncFormula>(ncFormula(string(b,last),false));
}
return result;
} // read_exp6()
// parse *,/
static ncTree<ncFormula> *read_exp5(string::iterator b, string::iterator e, string::iterator &last)
{
ncTree<ncFormula> *result = read_exp6(b, e, last);
while (last != e && (*last == '*' || *last == '/') ) {
ncTree<ncFormula> *child1 = result;
result = new ncTree<ncFormula>(ncFormula(string(last,last+1),true));
b = last+1;
ncTree<ncFormula> *child2 = read_exp6(b, e, last);
result->setChild1(child1);
result->setChild2(child2);
}
return result;
} // read_exp5()
// parse +,-
static ncTree<ncFormula> *read_exp4(string::iterator b, string::iterator e, string::iterator &last)
{
ncTree<ncFormula> *result = read_exp5(b,e,last);
while (last != e && (*last == '+' || *last == '-') ) {
ncTree<ncFormula> *child1 = result;
result = new ncTree<ncFormula>(ncFormula(string(last,last+1),true));
b = last+1;
ncTree<ncFormula> *child2 = read_exp5(b, e, last);
result->setChild1(child1);
result->setChild2(child2);
}
return result;
} // read_exp4()
// parse <=,...
static ncTree<ncFormula> *read_exp3(string::iterator b, string::iterator e, string::iterator &last)
{
ncTree<ncFormula> *result = read_exp4(b,e,last);
char ops [] = {'<','>','=','!'};
char *ops_end = ops + sizeof(ops)/sizeof(char);
string opname;
// skip the operator
do {
opname = "";
while (last != e && (std::find(ops, ops_end, *last) != ops_end))
opname.push_back(*last++);
if (opname.size() > 0) {
b = last;
ncTree<ncFormula> *child1 = result;
ncTree<ncFormula> *child2 = read_exp4(b,e,last);
result = new ncTree<ncFormula>(ncFormula(opname,true));
result->setChild1(child1);
result->setChild2(child2);
}
} while (opname.size() > 0);
return result;
} // read_exp3()
// parse &&
static ncTree<ncFormula> *read_exp2(string::iterator b, string::iterator e, string::iterator &last)
{
string opName = "&&";
ncTree<ncFormula> *result = read_exp3(b,e,last);
while (last != e && std::search(last,e,opName.begin(),opName.end()) == last) {
b = last + 2;
ncTree<ncFormula> *child1 = result;
ncTree<ncFormula> *child2 = read_exp3(b, e, last);
result = new ncTree<ncFormula>(ncFormula(opName,true));
result->setChild1(child1);
result->setChild2(child2);
}
return result;
} // read_exp2()
// parse ||
static ncTree<ncFormula> *read_exp1(string::iterator b, string::iterator e, string::iterator &last)
{
string opName = "||";
ncTree<ncFormula> *result = read_exp2(b, e, last);
while (last != e && std::search(last,e,opName.begin(),opName.end()) == last) {
b = last + 2;
ncTree<ncFormula> *child1 = result;
ncTree<ncFormula> *child2 = read_exp2(b, e, last);
result = new ncTree<ncFormula>(ncFormula(opName,true));
result->setChild1(child1);
result->setChild2(child2);
}
return result;
} // read_exp1()
#pragma mark -
ncTree<ncFormula> *read_formula(std::string formula)
{
std::string::iterator it;
it = std::remove(formula.begin(),formula.end(),' ');
it = std::remove(formula.begin(),it,'\t');
it = std::remove(formula.begin(),it,'\n');
it = std::remove(formula.begin(),it,'\r');
formula.erase(it,formula.end());
return read_exp1(formula.begin(),formula.end(),it);
} // read_formula()
std::set<string> get_cuts(ncTree<ncFormula> *tree)
{
std::set<string> result;
std::queue<ncTree<ncFormula> *> q;
ncFormula *formula;
// iterate the tree
q.push(tree);
while (!q.empty()) {
tree = q.front();
formula = tree->getData();
if ( formula->isOp() && (formula->getName().compare("||") == 0 || formula->getName().compare("&&") == 0) ) {
if (tree->getChild1())
q.push(tree->getChild1());
if (tree->getChild2())
q.push(tree->getChild2());
} else
result.insert(tree->toString(false));
q.pop();
}
return result;
} // get_cuts()
std::set<string> get_dependencies(ncTree<ncFormula> *tree)
{
std::set<string> result;
std::queue<ncTree<ncFormula> *> q;
ncFormula *formula;
// iterate the tree
q.push(tree);
while (!q.empty()) {
tree = q.front();
formula = tree->getData();
if (formula->isOp()) {
if (tree->getChild1()) q.push(tree->getChild1());
if (tree->getChild2()) q.push(tree->getChild2());
} else {
string s = formula->getName();
if(std::find_if(s.begin(),s.end(),isalpha) != s.end())
result.insert(s);
}
q.pop();
}
return result;
} // get_dependencies()
| true |
50508fbb7d5ea20d78ccf4c7fba4812cfefe1c24 | C++ | nhoudelot/antedominium-by-traction | /texture.cpp | ISO-8859-1 | 1,783 | 2.625 | 3 | [] | no_license | #include "stuff.hpp"
#include "texture.hpp"
Texture::Texture(int pwidth, int pheight, unsigned long *pdata)
{
int i;
width = pwidth;
height = pheight;
data = new unsigned long[width*height];
for (i=0;i<width*height;i++)
{
data[i] = pdata[i];
}
}
Texture::Texture(int pwidth, int pheight)
{
int i;
width = pwidth;
height = pheight;
data = new unsigned long[width*height];
for (i=0;i<width*height;i++)
{
data[i] = 0xFF000000;
}
}
Texture::~Texture()
{
delete [] data;
}
void Texture::upload()
{
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &ID);
glBindTexture(GL_TEXTURE_2D, ID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if((width == 512 && height == 512) ||
(width == 256 && height == 256) ||
(width == 128 && height == 128) ||
(width == 64 && height == 64))
{
//ei mipmappeja, 4 vrikomponenttia (R, G, B, alpha), korkeus, leveys,
//ei reunusta, pikselidatan formaatti, pikselidatan tyyppi, itse data
// glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data);
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data);
}
else
{
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//tehdn mipmapit
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data);
}
}
| true |
7e951114cde2224cf7f9072f0d6207ea56fc3533 | C++ | Francisco0947/COJ | /1493 - Geometrical Task II.cpp | UTF-8 | 510 | 3.296875 | 3 | [] | no_license | # include <iostream>
# include <cstdio>
using namespace std;
int main()
{
string x;
cin>>x;
if(x == "circle")
{
double radio;
cin>>radio;
radio = 3.14*(radio* radio);
cout<<radio;
}else if(x == "triangle")
{
double base,altura;
cin>>base>>altura;
base = (base * altura)/2;
cout<<base;
}else if(x == "rhombus")
{
double a,b;
cin>>a>>b;
a = (a*b)/2;
cout<<a;
}
return 0;
}
| true |
b0c9032e726f2e9993b726d147440745c558ea08 | C++ | guithin/BOJ | /15668/Main.cpp | UTF-8 | 670 | 2.59375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n;
int pick[11];
int chk[11];
void back(int cur) {
if (cur == 11) {
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= min(i, 10 - i); j++) {
int a = 0, b = 0;
for (int k = 0; k <= i; k++) {
a *= 10; a += pick[k];
}
for (int k = 0; k <= j; k++) {
b *= 10; b += pick[k + i + 1];
}
if (a + b == n && a && b) {
printf("%d + %d\n", a, b);
exit(0);
}
}
}
return;
}
for (int i = 0; i < 10; i++) {
if (!chk[i]) {
chk[i] = 1;
pick[cur] = i;
back(cur + 1);
chk[i] = 0;
}
}
}
int main() {
scanf("%d", &n);
back(1);
printf("-1\n");
return 0;
} | true |
2714d718152ac3871a44b0a3cc83b848e24e954b | C++ | jamesbertel/CS-211-x | /lab24/queue.cpp | UTF-8 | 3,179 | 4.0625 | 4 | [] | no_license | #include <iostream>
using namespace std;
typedef char el_t;
class Queue
{
private:
struct QueueNode
{ el_t letter; // letter in the node
QueueNode *next; // Pointer to the next node
};
// declare the following:
// Pointer to the front of the Queue
QueueNode * front;
// Pointer to the rear of the Queue
QueueNode * rear;
// Number of items in Queue
int * count;
public:
Queue(); // Constructor
~Queue(); // Destructor
// Queue operations
void enqueue(el_t);
void dequeue(el_t &);
void displayAll() const;
bool isEmpty() const;
};
// implement the public methods highlighted in bold here
Queue::Queue()
{ rear = front = NULL; count = 0; }
Queue::~Queue()
{ rear = front = NULL; count = 0; }
void Queue::enqueue(el_t let)
{
QueueNode *newNode;
newNode = new QueueNode;
newNode->next = NULL;
newNode->letter = let;
//Change front and back pointers,
//depending if the queue is empty or already contains data
if (isEmpty())
{
front = newNode;
rear = newNode;
}
else
{
rear->next = newNode;
rear = newNode;
}
}
}
void Queue::dequeue(el_t & let)
{
if(isEmpty())
cout << "The queue is empty.\n" << endl;
else
{
front = front->next;
//let = front;
count--;
}
qNode *temp;
if(isEmpty())
{
cout << "No data currently queued" << endl;
}
else
{
//Store data from front node in val
val = front->data;
//Remove front node, delete
temp = front;
front = front->next;
delete temp;
//Update queueNum
queueNum--;
}
}
void Queue::displayAll() const
{
if(isEmpty())
cout << " [ empty ] " << endl;
else
{
cout << endl;
QueueNode * p = new QueueNode;
p->next = front;
cout << front->letter << " ";
p = p->next;
cout << endl;
while(rear != NULL)
{
cout << p->letter << " ";
p = p->next;
}
cout << endl;
}
}
bool Queue::isEmpty() const
{
if(front==NULL)
return true;
else
return false;
}
int main ()
{
Queue q;
el_t c;
cout << " initial Queue contents " << endl;
q.displayAll();
q.dequeue(c);
q.enqueue('a');
cout << endl << " Queue contents after adding a: " << endl;
q.displayAll();
q.enqueue('b');
q.enqueue('c');
q.enqueue('d');
q.enqueue('e');
q.enqueue('f');
cout << endl << " Queue contents after adding b-f: " << endl;
q.displayAll();
q.dequeue(c);
cout << endl << c << endl;
cout << endl << " Queue contents after removing one element: " << endl;
q.displayAll();
q.dequeue(c);
cout << endl << " Removed element: " << c << endl;
cout << endl << " Queue contents after removing another element: " << endl;
q.displayAll();
q.enqueue('g');
q.enqueue('h');
q.enqueue('i');
cout << endl << " Queue contents after adding g, h, i: " << endl;
q.displayAll();
q.dequeue(c);
q.dequeue(c);
q.dequeue(c);
q.dequeue(c);
cout << endl << " Queue contents after removing 4 elements: " << endl;
q.dequeue(c);
q.dequeue(c);
cout << endl << " final Queue contents : " << endl;
q.displayAll();
return 0;
}
| true |
c4c1c320e7d6d38727e6645b079f198ec7c66f20 | C++ | chupakabr/coursera-cpp-solutions | /CourseraCpp/week03/task1.cpp | UTF-8 | 1,534 | 2.953125 | 3 | [] | no_license | //
// Created by Valeriy Chevtaev on 11/4/13.
// Copyright (c) 2013 7bit. All rights reserved.
//
#include <iostream>
#include <vector>
#include "task1.h"
#include "random_graph.h"
using namespace std;
void week03::task1::run(int argc, const char** argv) {
if (argc < 1) {
cerr << "Path to a file having test data should be specified as an argument to the command..." << endl;
return;
}
cout << "Running Week 03 Task 1 with file " << argv[1] << "..." << endl;
const bool useTestDataFile = true;
if (!useTestDataFile) {
// Generate test list of pairs: number of vertices_ -> graph density in percent
vector<pair<int, int>> test_data;
test_data.push_back(pair<int, int>(2, 100));
test_data.push_back(pair<int, int>(3, 100));
test_data.push_back(pair<int, int>(5, 100));
test_data.push_back(pair<int, int>(8, 100));
// Iterate through all test situations and simulate
for (pair<int, int> graph_data : test_data) {
random_graph g(graph_data.first, graph_data.second);
cout << endl << "--------------------------------" << endl << g << endl;
cout << " * MST: " << *g.build_mst().get() << endl;
}
} else {
// Load data from specified file
random_graph g(argv[1]);
cout << endl << "--------------------------------" << endl << g << endl;
cout << " * MST: " << *g.build_mst().get() << endl;
}
cout << endl << "Week 03 Task 1 has been finished." << endl;
}
| true |
10807366a4f8210b7c69646174c8523a4b5431de | C++ | thejosess/Informatica-UGR | /2ºAÑO/1ºCuatrimestre/ED/Practicas/practica2/src/Termino.cpp | UTF-8 | 864 | 3.5625 | 4 | [] | no_license | #include "Termino.h"
bool Termino::operator==(const Termino& termino)
{
return this->getPalabra() == termino.getPalabra();
}
istream& operator>>(istream& is, Termino& term)
{
string def, palabrita;
getline(is, palabrita, ';');
getline(is, def, '\n');
term.setDefinicion(def);
term.setPalabra(palabrita);
return is;
}
ostream& operator<<(ostream& os, const Termino& term)
{
int aux = term.getNumDefiniciones();
for(int i = 0 ; i < aux ; i++)
{
os << term.palabra <<";" << term.definiciones[i] << "\n" << endl ;
}
return os;
}
void Termino :: setDefinicion(string definicion){
this->definiciones.resize(1);
this->definiciones[0] = definicion;
}
void Termino::addDefinicion(string definicionNueva){
definiciones.resize(getNumDefiniciones()+1);
definiciones[getNumDefiniciones()-1] = definicionNueva;
}
| true |
d19ad447fce271ecf8cd5956e5179a94c12ee3b7 | C++ | APGRoboCop/jk_botti | /neuralnet.h | UTF-8 | 2,012 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "new_baseclass.h"
/******************************************************************* CNeuron */
class CNeuron : public class_new_baseclass
{
public:
int m_num_inputs;
double *m_weights;
CNeuron(): m_num_inputs(0), m_weights(nullptr) {}
CNeuron(int num_inputs, double in_weights[]);
int get_num_inputs() const { return m_num_inputs; }
static int calc_needed_weights(int num_inputs);
};
/************************************************************** CNeuronLayer */
class CNeuronLayer : public class_new_baseclass
{
public:
int m_num_neurons;
CNeuron *m_neurons;
CNeuronLayer(): m_num_neurons(0), m_neurons(nullptr) {}
CNeuronLayer(int num_neurons, int num_inputs_per_neuron, CNeuron in_neurons[], double in_weights[]);
int get_num_neurons() const { return m_num_neurons; }
static int calc_needed_weights(int num_neurons, int num_inputs_per_neuron);
};
/**************************************************************** CNeuralNet */
class CNeuralNet : public class_new_baseclass
{
private:
int m_num_inputs;
int m_num_outputs;
int m_num_hidden;
int m_num_neurons_per_hidden;
int m_widest_weight_array;
int m_widest_layer;
double m_bias;
double m_activation_response;
int m_num_layers;
CNeuronLayer *m_layers;
int m_num_weights;
double *m_weights;
int m_num_neurons;
CNeuron *m_neurons;
double *run_internal(const double orig_inputs[], double target_outputs[], double *ptr1, double *ptr2) const;
public:
CNeuralNet(int num_inputs, int num_outputs, int num_hidden, int num_neurons_per_hidden);
~CNeuralNet();
int get_num_weights() const { return m_num_weights; }
int get_num_inputs() const { return m_num_inputs; }
int get_num_outputs() const { return m_num_outputs; }
void reset_weights_random();
double *get_weights(double weights[]) const;
void put_weights(double weights[]);
double *run(const double inputs[], double outputs[]) const;
double *run(const double inputs[], double outputs[], const double scales[]) const;
void print() const;
};
| true |
6d39722f76bc84d66d7566ddca4774aed3ac120f | C++ | aditk3/JUCE-Projects | /MIDI Connect/Source/MidiPianoRoll.h | UTF-8 | 4,220 | 3.15625 | 3 | [] | no_license | //==============================================================================
/// @file MidiPianoRoll.h
/// A component that displays a piano roll animation of incoming midi messages.
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
/// A Component that displays a midi note in piano roll notation.
struct PianoRollNote : public Component {
/// Constructor. This should set the note's keynum and velocity members.
PianoRollNote(int key, int vel);
/// Destructor.
~PianoRollNote();
/// Should fill the local bounds (rectangle) of the note with the color red.
void paint(Graphics& g);
/// The key number of this midi note.
int keynum = 0;
/// The velocity of this midi note.
int velocity = 0;
/// Set to true by the update() function when an incoming message is
/// this note's note off. At that point the total pixel width for
/// drawing the note is known.
bool haveNoteOff = false;
};
/// A subclass of juce's AnimatedAppComponent that displays a moving
/// 'piano roll' display of incoming midi notes. The piano roll moves left
/// to right across the component at a speed determined by FPS and PPF (see
/// below).
struct MidiPianoRoll : public AnimatedAppComponent {
/// Constructor. This should set the animation's frames per second to FPS.
MidiPianoRoll();
/// Destructor. This should clear any active PianoRollNotes.
~MidiPianoRoll();
/// Automatically called after each update() to paint the piano roll component.
/// Your method should set the component's background color to black.
void paint(Graphics& g) override;
/// Adds or completes a PianoRollNote given an incoming midi message. If the
/// message is a NoteOn then a new PianoRollNote will be added
/// to the end of the notes array (see below) and to this component with its height
/// should be set to 128th of the height of the PianoRollComponent.
/// Thus, midi note 127 (the highest note possible) will be drawn at the top
/// of the display (Y position 0) and the Y position of midi note 0 will be at
/// the height (bottom) of the display less the height of the note. Since the
/// new PianoRollNote has not yet been turned off its initial X position and
/// width will be 0 and its width will increase by PPF until its NoteOff arrives.
/// If the incoming midi message is a noteOff then that note will be found and
/// have its haveNoteOff value set to true if it has not already been
/// turned off.
void addMidiMessage(const MidiMessage& message);
/// Deletes all PianoRollNotes in the notes array (see below).
void clear();
//==============================================================================
/// Called at the frame rate to animate the active PianoRollNotes. Your method
/// should iterate over the notes array moving them left to right in a manner
/// dependant on whether or not the note has already received its note off or
/// not. If it has, then the note needs to have its X position incremented by
/// PPF with its Y position remaining the same. However if it has not yet received
/// its note off then its current width should be be incremented by PPF with its
/// height remaining the same. Once the note has been animated, check to see
/// if its X position is beyond the right side of the component, and if it is,
/// the note should be erased from from the notes array, see std::vector's
/// erase() method. Note that when the subcomponent is deleted JUCE will remove
/// it from its parent component automatically.
void update() override;
/// A vector of child components, each child representing a visible midi note.
/// PianoRollNotes can be added using std::vector's push_back() method.
std::vector<std::unique_ptr<PianoRollNote>> notes;
/// Frames per second, the rate at which the animation runs.
const int FPS = 50;
/// Pixels per frame, the number of pixels each note moves per frame.
const int PPF = 2;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MidiPianoRoll)
};
| true |
6d3a2331816f656d525e44f241c746e5380cf42d | C++ | openbmc/phosphor-net-ipmid | /crypt_algo.hpp | UTF-8 | 6,682 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <vector>
namespace cipher
{
namespace crypt
{
/**
* @enum Confidentiality Algorithms
*
* The Confidentiality Algorithm Number specifies the encryption/decryption
* algorithm field that is used for encrypted payload data under the session.
* The ‘encrypted’ bit in the payload type field being set identifies packets
* with payloads that include data that is encrypted per this specification.
* When payload data is encrypted, there may be additional “Confidentiality
* Header” and/or “Confidentiality Trailer” fields that are included within the
* payload. The size and definition of those fields is specific to the
* particular confidentiality algorithm. Based on security recommendations
* encrypting IPMI traffic is preferred, so NONE is not supported.
*/
enum class Algorithms : uint8_t
{
NONE, /**< No encryption (mandatory , not supported) */
AES_CBC_128, /**< AES-CBC-128 Algorithm (mandatory option) */
xRC4_128, /**< xRC4-128 Algorithm (optional option) */
xRC4_40, /**< xRC4-40 Algorithm (optional option) */
};
/**
* @class Interface
*
* Interface is the base class for the Confidentiality Algorithms.
*/
class Interface
{
public:
/**
* @brief Constructor for Interface
*/
explicit Interface(const std::vector<uint8_t>& k2) : k2(k2) {}
Interface() = delete;
virtual ~Interface() = default;
Interface(const Interface&) = default;
Interface& operator=(const Interface&) = default;
Interface(Interface&&) = default;
Interface& operator=(Interface&&) = default;
/**
* @brief Decrypt the incoming payload
*
* @param[in] packet - Incoming IPMI packet
* @param[in] sessHeaderLen - Length of the IPMI Session Header
* @param[in] payloadLen - Length of the encrypted IPMI payload
*
* @return decrypted payload if the operation is successful
*/
virtual std::vector<uint8_t>
decryptPayload(const std::vector<uint8_t>& packet,
const size_t sessHeaderLen,
const size_t payloadLen) const = 0;
/**
* @brief Encrypt the outgoing payload
*
* @param[in] payload - plain payload for the outgoing IPMI packet
*
* @return encrypted payload if the operation is successful
*
*/
virtual std::vector<uint8_t>
encryptPayload(std::vector<uint8_t>& payload) const = 0;
/**
* @brief Check if the Confidentiality algorithm is supported
*
* @param[in] algo - confidentiality algorithm
*
* @return true if algorithm is supported else false
*
*/
static bool isAlgorithmSupported(Algorithms algo)
{
if (algo == Algorithms::AES_CBC_128)
{
return true;
}
else
{
return false;
}
}
protected:
/**
* @brief The Cipher Key is the first 128-bits of key “K2”, K2 is
* generated by processing a pre-defined constant keyed by Session
* Integrity Key (SIK) that was created during session activation.
*/
std::vector<uint8_t> k2;
};
/**
* @class AlgoAES128
*
* @brief Implementation of the AES-CBC-128 Confidentiality algorithm
*
* AES-128 uses a 128-bit Cipher Key. The Cipher Key is the first 128-bits of
* key “K2”.Once the Cipher Key has been generated it is used to encrypt
* the payload data. The payload data is padded to make it an integral numbers
* of blocks in length (a block is 16 bytes for AES). The payload is then
* encrypted one block at a time from the lowest data offset to the highest
* using Cipher_Key as specified in AES.
*/
class AlgoAES128 final : public Interface
{
public:
static constexpr size_t AESCBC128ConfHeader = 16;
static constexpr size_t AESCBC128BlockSize = 16;
/**
* If confidentiality bytes are present, the value of the first byte is
* one (01h). and all subsequent bytes shall have a monotonically
* increasing value (e.g., 02h, 03h, 04h, etc). The receiver, as an
* additional check for proper decryption, shall check the value of each
* byte of Confidentiality Pad. For AES algorithm, the pad bytes will
* range from 0 to 15 bytes. This predefined array would help in
* doing the additional check.
*/
static constexpr std::array<uint8_t, AESCBC128BlockSize - 1> confPadBytes =
{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
/**
* @brief Constructor for AlgoAES128
*
* @param[in] - Session Integrity key
*/
explicit AlgoAES128(const std::vector<uint8_t>& k2) : Interface(k2) {}
AlgoAES128() = delete;
~AlgoAES128() = default;
AlgoAES128(const AlgoAES128&) = default;
AlgoAES128& operator=(const AlgoAES128&) = default;
AlgoAES128(AlgoAES128&&) = default;
AlgoAES128& operator=(AlgoAES128&&) = default;
/**
* @brief Decrypt the incoming payload
*
* @param[in] packet - Incoming IPMI packet
* @param[in] sessHeaderLen - Length of the IPMI Session Header
* @param[in] payloadLen - Length of the encrypted IPMI payload
*
* @return decrypted payload if the operation is successful
*/
std::vector<uint8_t> decryptPayload(const std::vector<uint8_t>& packet,
const size_t sessHeaderLen,
const size_t payloadLen) const override;
/**
* @brief Encrypt the outgoing payload
*
* @param[in] payload - plain payload for the outgoing IPMI packet
*
* @return encrypted payload if the operation is successful
*
*/
std::vector<uint8_t>
encryptPayload(std::vector<uint8_t>& payload) const override;
private:
/**
* @brief Decrypt the passed data
*
* @param[in] iv - Initialization vector
* @param[in] input - Pointer to input data
* @param[in] inputLen - Length of input data
*
* @return decrypted data if the operation is successful
*/
std::vector<uint8_t> decryptData(const uint8_t* iv, const uint8_t* input,
const int inputLen) const;
/**
* @brief Encrypt the passed data
*
* @param[in] input - Pointer to input data
* @param[in] inputLen - Length of input data
*
* @return encrypted data if the operation is successful
*/
std::vector<uint8_t> encryptData(const uint8_t* input,
const int inputLen) const;
};
} // namespace crypt
} // namespace cipher
| true |
91648713b046e1aa37ab6ba49fb8d88ee24fde9f | C++ | TTeun/TDJ | /week2/uppertri/19.cc | UTF-8 | 275 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
size_t index(size_t nFighters, size_t one, size_t two) {
return one > two ? index(nFighters, two, one) :
one * nFighters - (one * one + one) / 2 + two - one - 1;
}
int main(int argc, char * argv[]) {
return 0;
} | true |
25e2cc5c4013b61d0463f60232af6bf9db2ed624 | C++ | N0I0C0K/VJ_training | /temp.cpp | UTF-8 | 150 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int a=5,b=6,c=7, f;
f= c>b>a;
cout<<f;
return 0;
}
| true |
1269abc3eec6c387d5586114470191f1a702722c | C++ | Lihit/LeetCode | /Medium/419. Battleships in a Board.cpp | UTF-8 | 1,549 | 3.609375 | 4 | [] | no_license | // Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's,
// empty slots are represented with '.'s. You may assume the following rules:
// You receive a valid board, made of only battleships or empty slots.
// Battleships can only be placed horizontally or vertically. In other words, they can only be made of
// the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
// At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
// Example:
// X..X
// ...X
// ...X
// In the above board there are 2 battleships.
// Invalid Example:
// ...X
// XXXX
// ...X
// This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
//
#include <iostream>
#include <map>
#include <vector>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int countBattleships(vector<vector<char> >& board) {
int boardHeight = board.size();
int ret=0;
for (int i = 0; i < boardHeight; ++i)
{
int boardWidth=board[i].size();
for (int j = 0; j < boardWidth; ++j)
{
//cout the head of the battleship
if(board[i][j]=='X' && (i==0 || board[i-1][j]!='X') && (j==0 || board[i][j-1]!='X')) ret++;
}
}
return ret;
}
};
int main(int argc, char const *argv[])
{
cout << "hello world" << endl;
return 0;
} | true |
da3f1a57369800e870618b652735c68bb969999b | C++ | gaolichen/contest | /topcoder/124_2/250/250.cpp | UTF-8 | 4,953 | 2.8125 | 3 | [] | no_license | //program framework generated with WishingBone's parser :)-
//common header
#include <iostream>
#include <vector>
#include <string>
#include <deque>
#include <map>
#include <set>
#include <list>
#include <algorithm>
#include <utility>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
//64 bit integer definition
#ifdef WIN32
#define in_routine(type,spec) \
istream& operator>>(istream& s,type &d){char b[30];s>>b;sscanf(b,spec,&d);return s;}
#define out_routine(type,spec) \
ostream& operator<<(ostream& s,type d){char b[30];sprintf(b,spec,d);s<<b;return s;}
typedef signed __int64 i64; in_routine(i64,"%I64d") out_routine(i64,"%I64d")
typedef unsigned __int64 u64; in_routine(u64,"%I64u") out_routine(u64,"%I64u")
#else
typedef signed long long i64;
typedef unsigned long long u64;
#endif
//common routines
#ifdef WIN32
#define min(a,b) _cpp_min(a,b)
#define max(a,b) _cpp_max(a,b)
#endif
#define abs(a) ((a)>0?(a):-(a))
int gcd(int a,int b){for(int c;b;c=a,a=b,b=c%b);return a;}
int lcm(int a,int b){return a/gcd(a,b)*b;}
//output routine
ostream& operator<<(ostream& s,string d){
s<<'\"'<<d.c_str()<<'\"';
return s;
}
template <class T>
ostream& operator<<(ostream& s,vector<T> d){
s<<"{";
for (vector<T>::iterator i=d.begin();i!=d.end();i++)
s<<(i!=d.begin()?",":"")<<*i;
s<<"}";
return s;
}
//parsing routine
template <class T>
vector<basic_string<T> > parse(const basic_string<T> &s,const basic_string<T> &delim){
vector<basic_string<T> > ret(0);
for (int b,e=0;;ret.push_back(s.substr(b,e-b)))
if ((b=s.find_first_not_of(delim,e))==(e=s.find_first_of(delim,b)))
return ret;
}
class MakeTeam{
public:
string lastOne(int n,vector<string> names){
int i,j;
string ret;
if(names.size()<n){
ret="NO TEAM";
return ret;
}
int min=100000;
for(i=0;i<n;i++)
if(names[i].length()<=min){
min=names[i].length();
j=i;
}
for(i=n;i<names.size();i++)
if(names[i].length()>min){
min=names[i].length();
j=i;
}
return names[j];
}
};
void test0(){
int n=4;
string _names[]={"BO","CHUCK","AL","DON","TOM"};
vector<string> names(_names+0,_names+sizeof(_names)/sizeof(string));
string lastOne= "TOM";
MakeTeam _MakeTeam;
string ret=_MakeTeam.lastOne(n,names);
cout<<"--------------------test 0--------------------"<<endl;
cout<<"n = "<<n<<endl;
cout<<"names = "<<names<<endl;
cout<<"expected to return "<<lastOne<<endl;
cout<<"your method returns "<<ret<<endl;
if (ret==lastOne)
cout<<endl<<"Pass!"<<endl<<endl;
else
cout<<endl<<"Fail!!!!!!!!!! aoao~~~~~~~~~~~~"<<endl<<endl;
}
void test1(){
int n=2;
string _names[]={"BOB"};
vector<string> names(_names+0,_names+sizeof(_names)/sizeof(string));
string lastOne= "NO TEAM";
MakeTeam _MakeTeam;
string ret=_MakeTeam.lastOne(n,names);
cout<<"--------------------test 1--------------------"<<endl;
cout<<"n = "<<n<<endl;
cout<<"names = "<<names<<endl;
cout<<"expected to return "<<lastOne<<endl;
cout<<"your method returns "<<ret<<endl;
if (ret==lastOne)
cout<<endl<<"Pass!"<<endl<<endl;
else
cout<<endl<<"Fail!!!!!!!!!! aoao~~~~~~~~~~~~"<<endl<<endl;
}
void test2(){
int n=3;
string _names[]={"JIM","BOB","TOM","AL","HAL"};
vector<string> names(_names+0,_names+sizeof(_names)/sizeof(string));
string lastOne= "TOM";
MakeTeam _MakeTeam;
string ret=_MakeTeam.lastOne(n,names);
cout<<"--------------------test 2--------------------"<<endl;
cout<<"n = "<<n<<endl;
cout<<"names = "<<names<<endl;
cout<<"expected to return "<<lastOne<<endl;
cout<<"your method returns "<<ret<<endl;
if (ret==lastOne)
cout<<endl<<"Pass!"<<endl<<endl;
else
cout<<endl<<"Fail!!!!!!!!!! aoao~~~~~~~~~~~~"<<endl<<endl;
}
void test3(){
int n=6;
string _names[]={"SAM","SAP","SAX","BO","SAD","SSM","SAL","HAL","RED"};
vector<string> names(_names+0,_names+sizeof(_names)/sizeof(string));
string lastOne= "SAL";
MakeTeam _MakeTeam;
string ret=_MakeTeam.lastOne(n,names);
cout<<"--------------------test 3--------------------"<<endl;
cout<<"n = "<<n<<endl;
cout<<"names = "<<names<<endl;
cout<<"expected to return "<<lastOne<<endl;
cout<<"your method returns "<<ret<<endl;
if (ret==lastOne)
cout<<endl<<"Pass!"<<endl<<endl;
else
cout<<endl<<"Fail!!!!!!!!!! aoao~~~~~~~~~~~~"<<endl<<endl;
}
void test4(){
int n=2;
string _names[]={"STOTTLEMEYER","EMPENTHALLERSTEIN","AL","DEFORESTATION","JON"};
vector<string> names(_names+0,_names+sizeof(_names)/sizeof(string));
string lastOne= "DEFORESTATION";
MakeTeam _MakeTeam;
string ret=_MakeTeam.lastOne(n,names);
cout<<"--------------------test 4--------------------"<<endl;
cout<<"n = "<<n<<endl;
cout<<"names = "<<names<<endl;
cout<<"expected to return "<<lastOne<<endl;
cout<<"your method returns "<<ret<<endl;
if (ret==lastOne)
cout<<endl<<"Pass!"<<endl<<endl;
else
cout<<endl<<"Fail!!!!!!!!!! aoao~~~~~~~~~~~~"<<endl<<endl;
}
int main(){
test0();
test1();
test2();
test3();
test4();
return 0;
}
| true |
49d69bfdd47031e9af62a5183ca28479f95d9654 | C++ | anhendric/Physium | /Sources/DrawWindow.h | UTF-8 | 756 | 2.578125 | 3 | [] | no_license | #ifndef DRAWWINDOW_INCLDUED
#define DRAWWINDOW_INCLDUED
#include "ScribbleDocument.h"
///////////////////////////////////////////////////////////////////
//
// DrawWindow - Child Window that manages drawing
//
///////////////////////////////////////////////////////////////////
class DrawWindow: public CPWindow
{
protected:
// Data abstracted into Document class
ScribbleDocument * m_doc;
public:
// Constructor takes a window rectangle and a pointer to the document
DrawWindow(PegRect rect, ScribbleDocument * doc);
//Overwritten function to Draw ScribbleDocument
virtual void Draw();
// Overwritten function to handle pointer events
virtual void OnLButtonUp(const PegPoint &p);
virtual void OnPointerMove(const PegPoint &p);
};
#endif
| true |
bd8bcfb4c6c4f6c52c35d1ab0453911975ad5781 | C++ | RolandoAndrade/NubeUCABManager | /server/usermanager.cpp | UTF-8 | 847 | 2.859375 | 3 | [] | no_license | #include "usermanager.h"
bool UserManager::addUser(QString user, QString password, QString home)
{
return addUserToFile(user.toStdString(), password.toStdString(), home.toStdString()+"/"+user.toStdString());
}
bool UserManager::removeUser(QString user)
{
return removeUsersFromFile(user.toStdString());
}
QVariantList UserManager::readUsers()
{
createDirectory("users");
vector<string> v({"blue","green","red","yellow"});
int i = 0;
LoginInfo l = getUsersFromFile();
QVariantList users;
for(auto a: l)
{
QVariantMap data;
data.insert("thename", a.first.c_str());
data.insert("thepass", a.second.first.c_str());
data.insert("theroute", a.second.second.c_str());
data.insert("thecolor", (v[i++%v.size()]).c_str());
users.append(data);
}
return users;
}
| true |