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
395b35ed4fa6e14051d684840d9e6317895bdb1c
C++
tmdrnahs/algorithm
/DFS/blob.cpp
UTF-8
2,770
2.953125
3
[]
no_license
// 문제 설명 // 해마다 열리는 꿀꿀이 올림피아드에는 여러 종목들이 있는데, 요즘에는 꿀꿀이들의 교양을 겨루는 ‘미술관람 대회’가 인기를 끌고 있다. 이 대회는 사회자가 빨강, 초록, 파랑으로 이루어진 N × N 픽셀의 그림을 보여주면 그 그림에 포함된 영역의 수를 빠르고 정확하게 맞추는 것이 목표이다. 동일한 색깔이 네 방향(상, 하, 좌, 우) 중 한 곳이라도 연결되어 있으면 하나의 영역으로 간주한다. // 예를 들어, 아래 그림은 각각 2, 1, 1개의 빨간색, 초록색, 파란색 영역이 있어 총 4개의 영역이 있다. // 한편, 꿀꿀이들의 절반 정도는 선천적인 유전자 때문에 적록색맹이라서 빨간색과 초록색을 구별하지 못한다. 따라서 사회자는 일반 대회와 적록색맹용 대회를 따로 만들어서 대회를 진행하려고 한다. 사회자를 도와 영역의 수를 구하는 프로그램을 작성하여라. // 입력 설명 // 첫 번째 줄에는 그림의 크기 N이 주어진다. (1 ≤ N ≤ 100) // 두 번째 줄부터 N개의 줄에는 각 픽셀의 색깔이 'R'(빨강), 'G'(초록), 'B'(파랑) 중 하나로 주어진다. // 출력 설명 // 일반 꿀꿀이와 적록색맹 꿀꿀이가 보는 영역의 수를 출력한다. // 입력 예시 // 5 // RRRBB // GGBBB // BBBRR // BBRRR // RRRRR // 출력 예시 // 4 3 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define MAX_N (100) int N; char map[MAX_N+2][MAX_N+2]; int chk[MAX_N+2][MAX_N+2]; void Input_Data(void) { int r,c; scanf("%d",&N); for(r=1;r<=N;r++) { for(c=1;c<=N;c++) { scanf(" %c",&map[r][c]); } } } void Flood_Fill(int r,int c) { int i; static int dr[] = {0,0,1,-1}; static int dc[] = {1,-1,0,0}; int nr,nc; chk[r][c] = 1; for(i=0;i<4;i++) { nr = r + dr[i]; nc = c + dc[i]; if(chk[nr][nc] == 0 && map[r][c] == map[nr][nc]) Flood_Fill(nr,nc); } } int Get_Cnt_Group(void) { int r,c; int cnt_group = 0; for(r=1;r<=N;r++) { for(c=1;c<=N;c++) { if(chk[r][c] == 1) continue; Flood_Fill(r,c); cnt_group++; } } return cnt_group; } void Init_For_RG_Pig(void) { int r,c; for(r=1;r<=N;r++) { for(c=1;c<=N;c++) { chk[r][c] = 0; if(map[r][c] == 'R') map[r][c] = 'G'; } } } int main(void) { int i,cnt_normal,cnt_rg; Input_Data(); cnt_normal = Get_Cnt_Group(); Init_For_RG_Pig(); cnt_rg = Get_Cnt_Group(); printf("%d %d\n",cnt_normal,cnt_rg); return 0; }
true
10b2d731e5c80bb45ad433564e865e110328beeb
C++
andreyciupitu/ray-tracing
/Source/RayTracingDemo/Collider.h
UTF-8
467
2.859375
3
[]
no_license
#pragma once class SceneObject; namespace Physics { struct Ray; struct HitInfo; class Collider { public: Collider(SceneObject *obj) : sceneObject(obj) {} virtual ~Collider() {} // Computes the intersection of the collider with the ray. // Returns the hit details in the hit info, and returns false // if the ray doesn't intersect the collider. virtual bool IntersectRay(const Ray &r, HitInfo *hit) = 0; public: SceneObject *sceneObject; }; }
true
f1e662eb9241b623ce345734ec4bfab298aa709a
C++
hanrick2000/Algorithms-9
/Ad hoc/codechef_lisdigit.cpp
UTF-8
950
2.671875
3
[]
no_license
/*-------------------------------------------------------------------------------------------------------- * Name : CNatka * Problem : LISDIGIT * Source : Codechef * Link : https://www.codechef.com/problems/LISDIGIT * DS : NA * Algo : NA * Date : Jan 22, 2017 * Complexity : O(T*n) || AC(0.04 sec) * Solved : self * Alternative Sol : NA * Note : This code should be used for the purpose of learning only, use it at your own risk *----------------------------------------------------------------------------------------------------------*/ #include <cstdio> #include <iostream> #include <vector> using namespace std; int main() { int T; scanf("%d",&T); while(T--) { int n; scanf("%d",&n); vector<int>V; for(int i=0; i<n; i++) { int temp; scanf("%d",&temp); V.push_back(temp); } long long num = V[0]; for(int i=1; i<n; i++) { num *= 10; num += V[i]; } printf("%lld\n",num); } return 0; }
true
b5aec84263ed04e2617bfe2243ffc1ffa2eb8af5
C++
FlashNoob98/unina
/Aritmetica/media_num_pari/media_num_pari.cpp
UTF-8
475
3.53125
4
[]
no_license
/* Media algebrica dei numeri pari */ #include <iostream> using namespace std; int main(){ int n,x,p=0,somma=0; cout << "Questo programma esegue la media dei numeri pari inseriti"<<endl; cout << "Di quanti numeri vuoi fare la media?: "; cin >> n; for (int i=0; i<n; i++){ cout << "Inserisci il "<<(i+1)<<"° numero: "; cin >> x; if ((x%2)==0){ somma += x; p++; } } cout << "La media dei numeri pari inseriti e': "<< ((float)somma)/p<<endl; return 0; }
true
16b24607ba4bbb3a4481b00b39c232e5169ecd2c
C++
nnngu/my_first_cpp_book
/p366_C++是如何实现指针变量的静态类型和动态绑定的.cpp
UTF-8
2,887
4.0625
4
[ "MIT" ]
permissive
/* C++是如何实现指针变量的静态类型和动态绑定的? 我们知道,C++ 是一种强类型的编程语言,它的每一个变量都有其确定的类型。但是, 当这个变量是指针的时候,情况就有些特殊。我们有一个某种类型的指针,而它实际上指向的是其派生类的 某个对象。例如,一个 Human* 指针实际上指向一个 Student 对象。 Student st; Human* pHuman = &st; // 将基类指针指向派生类对象 这时,pHuman 指针就有了两种类型;指针的静态类型(在此是 Human)和它所指向的对象的 动态类型(在此是 Student)。 静态类型意味着成员函数调用的合法性将被尽可能早地检查:编译器在编译时,编译器可以使用 指针的静态类型来决定成员函数的调用是否合法。如果指针类型能够处理成员函数,那么指针实际上 指向的对象当然能很好地处理它。例如,如果 Human 类有某个成员函数,而指针实际上指向的 Student 对象是 Human 的一种,是 Human 类的派生类,自然会从基类 Human 中继承获得相应的成员函数。 动态绑定意味着在编译时,通过指针实现成员函数调用的代码地址并没有确定,而在运行时,这 一地址才根据指针所指向的实际对象的真正类型动态地决定。因为绑定到实际被调用的代码的这个过程是在 运行时动态完成的,所以被称为"动态绑定"。动态绑定是虚函数所带来的 C++ 特性之一。 下面的代码演示了 C++ 语言中的静态类型和动态绑定。 */ // 基类 class Human { public: Human(string strName) : m_strName(strName) {} // 成员函数 string getName() { return m_strName; } // 虚成员函数 virtual string getJobTitle() { return ""; } private: string m_strName; }; // 派生类 class Student : public Human { public: Student(string strName) : Human(strName) {} // 重新定义虚成员函数 virtual string getJobTitle() { return "Student"; } }; int main(int argc, char* argv[]) { Student st("Jiawei"); Human* pHuman = &st; // 基类指针指向派生类对象 // 调用 pHuman 指针所指向对象的 getName()普通成员函数 // 编译时,首先根据 pHuman 的静态类型 Human 检查成员函数调用的合法性 cout<<"姓名:"<<pHuman->getName()<<endl; // 如果调用的是虚成员函数, // 将在运行时根据 pHuman 所指向的真正对象决定此成员函数的地址。 // 虽然 pHuman 的静态类型是 Human,但它所指向的实际上是一个 Student 对象, // 所以这里的成员函数将不再是调用 Human 类的 Human::getJobTitle(), // 而是被动态绑定为 Student 类的 Student::getJobTitle(), // 输出 Student 对象的真实情况 cout<<"职位:"<<pHuman->getJobTitle()<<endl; return 0; }
true
16614ed0554b33b75ea3bcc6f872054edc610c55
C++
marin117/Collision_detection
/src/AABBTreeNode.h
UTF-8
568
2.640625
3
[]
no_license
#ifndef AABBTreeNode_h #define AABBTreeNode_h #include "AABB_box.h" #include <memory> #include <vector> class Node { typedef std::unique_ptr<Node> ptr; public: Node() = default; Node(const AABB_box bbox); Node(ptr &left, ptr &right); bool isLeaf(); void insertLeaf(ptr &leaf); void treeTraverse(); void mergeTree(ptr &root); void buildTree(int i); bool treeOverlap(ptr &root); bool treeCollision(ptr &root); bool boxOverlap(AABB_box &collideBox); private: AABB_box box; ptr left; ptr right; Node *parent; int height; }; #endif
true
a183b560c03bd65bc5a3cf35ae430d9d9baf238f
C++
bboyifeel/parallel_and_grid_classes
/pi/2_boost_mpi.cpp
UTF-8
1,929
2.59375
3
[]
no_license
#include <mpi.h> #include <iostream> #include <cmath> #include <boost/mpi/environment.hpp> #include <boost/mpi/communicator.hpp> #include <boost/mpi.hpp> namespace mpi = boost::mpi; void mpiSimpsonsPiCalc(int argc, char *argv[]); int main(int argc, char *argv[]) { mpiSimpsonsPiCalc(argc, argv); return 0; } double f(double _val) { return 4.0 / (1 + _val * _val); } double intervalSimpsonsPiCalc(int _rank, int _mpiSize, uint32_t _n) { double m = static_cast<double>(_n/2); double result = 0; for (int i = _rank + 1; i < m; i+= _mpiSize) result += 2.0 * f(i / m) + 4.0 * f((2.0*i - 1) / (2.0 * m)); return result; } double errorApproximation(unsigned int _n) { return 8.0/(15.0*_n*_n*_n*_n); } void mpiSimpsonsPiCalc(int argc, char *argv[]) { int32_t size = 0; int32_t rank = 0; uint32_t n = 0; double pi = 0; mpi::environment env(argc, argv); mpi::communicator world; size = world.size(); rank = world.rank(); if (rank == 0) { do { std::cout << "Enter number of intervals (n%2==0) "; std::cin >> n; } while (n%2 != 0); } world.barrier(); mpi::timer appTimer; mpi::broadcast(world, n, 0); double intervalResult = intervalSimpsonsPiCalc(rank, size, n); reduce(world, &intervalResult, 1, &pi, std::plus<double>(), 0); double elapsedTime = appTimer.elapsed(); if (rank == 0) { double m = static_cast<double>(n/2); pi += f(0) + f(1); pi += 4.0 * f((2.0 * m - 1) / (2.0 * m)); pi /= 6.0 * m; double realError = std::abs(M_PI - pi); double approximatedError = errorApproximation(n); std::cout << "Simpson's Pi = " << pi << " with n = " << n << " intervals" << std::endl; std::cout << "Simpson's Real Error = " << realError << std::endl; std::cout << "Approximated Error = " << approximatedError << std::endl; std::cout << "WTime difference = " << elapsedTime << std::endl; } }
true
fa52047d326f27eb8a426e4af8d20dbdb8b29074
C++
pcruiher08/LosDesafiosDeJuanito
/Soluciones/1.1 - Triangulos.cpp
UTF-8
334
3.234375
3
[]
no_license
#include <iostream> #include <cmath> #include <iomanip> using namespace std; /* Problema 1.1 Complejidad de tiempo: O(1) */ int main() { int casos; cin >> casos; for (int i = 0; i < casos; i++) { int lado; cin >> lado; float altura = lado * sqrt(3) / 2; cout << fixed << setprecision(2); cout << altura << endl; } }
true
7d64d85582ad7ff4396bfab65feb06c8743f5d0f
C++
dwax1324/baekjoon
/code/15903 카드 합체 놀이.cpp
UTF-8
689
2.796875
3
[]
no_license
#include <bits/stdc++.h> // 그리디 // 항상 작은것 두개만 더해주면됨 // 우선순위큐사용 (오름차순) using namespace std; int main() { long long n, m; cin >> n >> m; priority_queue<long long, vector<long long>, greater<long long>> pq; for (long long i = 0; i < n; i++) { long long a; cin >> a; pq.push(a); } for (long long i = 0; i < m; i++) { long long a = pq.top(); pq.pop(); long long b = pq.top(); pq.pop(); pq.push(a + b); pq.push(a + b); } long long SUM = 0; while (pq.size()) { SUM += pq.top(); pq.pop(); } cout << SUM; }
true
ba9ad783736d1dd406487ab5b01f2f24a3ee10be
C++
jbebe/all-my-projects
/priv/desktop/C++/daily programmer @reddit/challenge 17.cpp
UTF-8
209
2.671875
3
[]
no_license
#include <iostream> #include <regex> int main(){ std::string first = "Daily Programmer", second = "aeiou "; std::cout << std::regex_replace(first,std::regex("["+second+"]"),""); getchar(); return 0; }
true
f501588aaf2f26de259e4a090c97951016b2d177
C++
docppp/Computer-aided-analysis-of-colorymetric-tests
/drug.cpp
UTF-8
3,380
2.875
3
[]
no_license
#include "drug.h" #include <QDebug> #include <QString> #define LOG std::cout<< #define TEST int Drug::loadFromLine(std::string line) { int n = 0; for (int i = 0; i < line.size(); i++) if (line[i] == ';') n++; if (n != NUMBER_OF_TESTS * 2) { #ifdef TEST LOG "DRUG: ERROR! Line " << line << " is not valid. Wrong number" << "of delimiters.\n"; #endif // TEST return -1; } int pos = -1; int posPrev = -1; int i = 0; std::string data[NUMBER_OF_TESTS * 2 + 1]; std::string delimiter = ";"; do { posPrev = pos; pos = line.find(delimiter, pos + 1); data[i++] = line.substr(posPrev + 1, pos - posPrev - 1); } while (pos != std::string::npos); if (data[0].empty()) { #ifdef TEST LOG "DRUG: ERROR! Line '" << line << "' is not valid. " << "Drug must have a name.\n"; #endif // TEST return -1; } name = data[0]; for (i = 1; i < NUMBER_OF_TESTS * 2 + 1; i++) { test[i - 1].name = data[i]; if (test[i - 1].loadFromHex(data[i]) == -1) { #ifdef TEST LOG "DRUG: ERROR! Cannot load line for drug '" << data[0] << "'.\n"; #endif // TEST return -1; } } error = 0; return 1; } std::string Drug::toLine() { std::string result; result = result + name; for (int i = 0; i < NUMBER_OF_TESTS * 2; ++i) { if (test[i].R == -1) result = result + ";"; else result = result + ";" + test[i].toHex(); } return result; } std::string testColor(int test) { switch (test) { case MARQUIS: return MARQUIS_COLOR; case MECKE: return MECKE_COLOR; case MANDELIN: return MANDELIN_COLOR; case LIEBERMANN:return LIEBERMANN_COLOR; case FROEHDE: return FROEHDE_COLOR; case ROBADOPE: return ROBADOPE_COLOR; case SIMONS: return SIMONS_COLOR; case FOLIN: return FOLIN_COLOR; case EHRLICH: return EHRLICH_COLOR; case HOFMANN: return HOFMANN_COLOR; case SCOTT: return SCOTT_COLOR; case GALUS: return GALUS_COLOR; case ZIMMERMAN: return ZIMMERMAN_COLOR; } } double CopmareTests(Color ref1, Color ref2, const Color &sample1, const Color &sample2, int testFlag) { if (testFlag < 0 || testFlag >= NUMBER_OF_TESTS * 2) { #ifdef TEST LOG "Drug: ERROR! Cannot compare tests with flag '" << testFlag << "'.\n"; #endif // TEST return -1; } if (ref1.R == -1 && ref2.R == -1) { qDebug()<<"Returning error bias"; return ERROR_BIAS; } Color colorStart; double midError; double endError; colorStart.loadFromHex(testColor(testFlag)); if (ref1.R == -1 && ref1.G == -1 && ref1.B == -1) ref1.inBetween(colorStart, ref2); std::string s1 = ref1.toHex(); std::string s2 = ref2.toHex(); const std::string s3 = sample1.toHex(); const std::string s4 = sample2.toHex(); qDebug()<<testFlag<<" R1"<<QString::fromStdString(s1) <<" R2"<<QString::fromStdString(s2) <<" S1"<<QString::fromStdString(s3) <<" S2"<<QString::fromStdString(s4); midError = ColorDistance(ref1, sample1); endError = ColorDistance(ref2, sample2); return midError + endError; }
true
f00176d30e6f42a28f6574bae72ce9749d5b827e
C++
HariniJeyaraman/DSAPrep
/rotateList.cpp
UTF-8
2,052
3.96875
4
[]
no_license
//Rotate linked list right by k nodes #include<iostream> #include<cstdlib> #include<vector> struct node { int data; struct node *nptr; }; struct node* hptr=NULL; void insertNode(int pos, int x) { struct node *temp=new node; if(temp==NULL) std::cout<<"Insert not possible\n"; temp->data=x; if(pos==1) { temp->nptr=hptr; hptr=temp; } else { int i=1; struct node* thptr=hptr; while(i<pos-1) { thptr=thptr->nptr; i++; } temp->nptr=thptr->nptr; thptr->nptr=temp; } } void deleteNode(int pos) { struct node *temp=hptr; int i=1; if(temp==NULL) std::cout<<"Delete not possible\n"; if(pos==1) hptr=hptr->nptr; else { while(i<pos-1) { temp=temp->nptr; i++; } temp->nptr=(temp->nptr)->nptr; } } void print() { struct node* temp=hptr; while(temp!=NULL) { std::cout<<temp->data<<"\n"; temp=temp->nptr; } } void rotateList(int k) { //Finding the size of the linked list struct node* temp=hptr; struct node* start=hptr; struct node* ttemp=hptr; int size=0; while(temp!=NULL) { size++; ttemp=temp;//will point to the penultimate node temp=temp->nptr; } int rotateRightby=k%size; //If size of ll is 5 and k is 8, then it is equivalent to rotating by 3 instead of 8 //The head pointer must point at position size - k int i=1; struct node *thptr=hptr; while(i<(size-rotateRightby)) { i++; thptr=thptr->nptr; } if(thptr->nptr!=NULL) hptr=thptr->nptr; //updating the head pointer after the rotate right operation ttemp->nptr=start;//making the last node to point to the first node thptr->nptr=NULL; } int main() { insertNode(1,10); insertNode(2,20); insertNode(3,30); insertNode(4,40); insertNode(5,50); rotateList(2); print(); return 0; }
true
bc0226302ba7f41e66c2a665ed011fc8a2343e0a
C++
tihonov-e/cpp_stepik
/SET_MAP/Source/lab6.cpp
UTF-8
5,247
3.046875
3
[]
no_license
 //1.11 Словари и множества /** Однажды, разбирая старые книги на чердаке, школьник Вася нашёл англо-латинский словарь. Английский он к тому времени знал в совершенстве, и его мечтой было изучить латынь. Поэтому попавшийся словарь был как раз кстати. К сожалению, для полноценного изучения языка недостаточно только одного словаря: кроме англо-латинского необходим латинско-английский. За неимением лучшего он решил сделать второй словарь из первого. Как известно, словарь состоит из переводимых слов, к каждому из которых приводится несколько слов-переводов. Для каждого латинского слова, встречающегося где-либо в словаре, Вася предлагает найти все его переводы (то есть все английские слова, для которых наше латинское встречалось в его списке переводов), и считать их и только их переводами этого латинского слова. Помогите Васе выполнить работу по созданию латинско-английского словаря из англо-латинского. Входные данные В первой строке содержится единственное целое число N — количество английских слов в словаре. Далее следует N описаний. Каждое описание содержится в отдельной строке, в которой записано сначала английское слово, затем отделённый пробелами дефис (символ номер 45), затем разделённые запятыми с пробелами переводы этого английского слова на латинский. Переводы отсортированы в лексикографическом порядке. Порядок следования английских слов в словаре также лексикографический. Все слова состоят только из маленьких латинских букв, длина каждого слова не превосходит 15 символов. Общее количество слов на входе не превышает 100000. Выходные данные В первой строке программа должна вывести количество слов в соответствующем данному латинско-английском словаре. Со второй строки выведите сам словарь, в точности соблюдая формат входных данных. В частности, первым должен идти перевод лексикографически минимального латинского слова, далее — второго в этом порядке и т.д. Внутри перевода английские слова должны быть также отсортированы лексикографически. Sample Input: 3 apple - malum, pomum, popula fruit - baca, bacca, popum punishment - malum, multa Sample Output: 7 baca - fruit bacca - fruit malum - apple, punishment multa - punishment pomum - apple popula - apple popum - fruit */ #include <iostream> #include <vector> #include <string> #include <sstream> //for istringstream #include <map> #include <set> using namespace std; int main() { map <string, vector <string> > map_eng, map_latin; set <string> s_latinword; string word_eng, word_lat, s; int N = 0; cin >> N; while (N--) { //"ws" to make "getline" ignore '\n' cin >> word_eng >> ws; getline(cin, s); //delete "," and "-" for (int i = 0; i < s.length(); i++) { if (s[i] == ',' || s[i] == '-') s.erase(i,1); } //create object is for the input stream working (>>) istringstream is(s); //make latin map from the string s while (is >> word_lat) { s_latinword.insert(word_lat); //make set for printing the map_latin in a right order map_latin[word_lat].push_back(word_eng); } } //print result cout << map_latin.size() << endl; //number of latin words for (auto& now_latinword : s_latinword) { //go thru set for a right printing order cout << now_latinword << " - "; //print second value of the map int i = 0; //for finding the laat value of the map_latin for (auto& now_engword : map_latin[now_latinword]) { //go thru the map.first if (i != map_latin[now_latinword].size() - 1) cout << now_engword << ", "; //print ", " if it's not a last value else cout << now_engword; i++; } cout << "\n"; } return 0; }
true
c0f35e823fa1f6d4702ccf97031a528b4b062d25
C++
sd-ot/sdot
/src/sdot/Support/Stat.cpp
UTF-8
1,667
2.90625
3
[]
no_license
#include <iostream> #include <iomanip> #include "Stream.h" #include "Stat.h" #include "Mpi.h" namespace sdot { Stat stat; Stat::~Stat() { size_t max_length = 0; for( auto td : stats ) max_length = std::max( max_length, td.first.size() ); for( const auto &st : stats ) { if ( st.second.step ) { double min = + std::numeric_limits<double>::max(); double max = - std::numeric_limits<double>::max(); for( auto value : st.second.values ) { min = std::min( min, value ); max = std::max( max, value ); } std::ptrdiff_t index_min = min / st.second.step; std::ptrdiff_t index_max = max / st.second.step; std::vector<std::size_t> d( index_max - index_min + 1, 0 ); for( auto value : st.second.values ) d[ value / st.second.step - index_min ]++; std::vector<double> n( d.size(), 0 ); for( std::size_t i = 0; i < d.size(); ++i ) n[ i ] = double( d[ i ] ) / st.second.values.size(); std::cout << st.first << "\n n: " << n << "\n d: " << d << "\n"; } else { double sum = 0; for( auto value : st.second.values ) sum += value; double mean = sum / st.second.values.size(); std::cout << st.first << std::string( max_length - st.first.size(), ' ' ) << " -> sum: " << std::setprecision( 4 ) << std::setw( 11 ) << sum << " mean: " << std::setw( 11 ) << mean << "\n"; } } } }
true
902bb481caf87ec4c280b77016209338804e73e0
C++
JohnHonkanen/ProjectM
/Game/Scripts/test/InventoryPopulator.h
UTF-8
712
2.53125
3
[ "MIT" ]
permissive
/* InventoryPopulator class used as a helper to test the warehouse inventories at runtime. */ #pragma once #include "components\Behaviour.h" class InventoryPopulator : public Behaviour { public: InventoryPopulator(); InventoryPopulator(class PlayerActions* pla, class Resources* res); void Onload(); // Creates test items at runtime for warehouse inventories void Start(); void TestItem(PlayerActions * pla, class ResourceManager* resourceManager); void Create(); void Copy(GameObject* gameObject); void Update(); void Input(); private: // Varibles declared and forward declared. bool keyHeld = false; class PlayerActions* pla; class Resources* res; class ResourceManager* resourceManager; };
true
ae38a803ded624aaee14ab61e6d27ee89d3a185e
C++
Spoders/motMystere
/tp01/main.cpp
ISO-8859-1
2,754
3.375
3
[]
no_license
#include <iostream> #include <ctime> #include <cstdlib> #include <fstream> #include <string> using namespace std; int calculeLigne(); string chercheMotAlea(int nombreDeLigne); string melangeMot(string motMystere); int main() { string motMystere, motMelange, motTemporaire, reponse = "n"; int nombreDeLigne = 0, nbrCoupMax, nbrCoups = 0; nombreDeLigne = calculeLigne(); //Calcule du nombre de ligne du dictionnaire do { cout << "Chargement" << endl; motMystere = chercheMotAlea(nombreDeLigne); //Recherche d'un mot mystere motMelange = melangeMot(motMystere); //Melange les lettres du mots system("cls"); cout << "Quel est le nombre maximale de coups : "; cin >> nbrCoupMax; do { //Boucle demande mot mystere system("cls"); cout << motMystere << endl; cout << "Il te reste " << nbrCoupMax - nbrCoups << " coups" <<endl; cout << "Quel est le mot mystre : "; cout << motMelange << endl; cin >> motTemporaire; nbrCoups++; if (nbrCoups == nbrCoupMax) { cout << "Tu as perdu ! Tu as utilis " << nbrCoupMax << " coups" << endl; system("PAUSE"); return 0; } } while (motTemporaire != motMystere); cout << "Bravo Tu as gagne" << endl; cout << "Veux tu recommencer O/n" << endl; cin >> reponse; } while (reponse != "N" && reponse != "n"); //Boucle demande nouvelle essaye system("PAUSE"); return 0; } string chercheMotAlea(int nombreDeLigne) { srand(time(0)); string motMysteres, ligne; int ligneAlatoire, ligneSuivie = 0; ifstream dictionnaireMot("C:/Users/vrumm/Desktop/Programme Langage C/tp01/motMystere/dico.txt"); //Trouve un ligne alatoire et stock le mot ligneAlatoire = rand() % nombreDeLigne; if (dictionnaireMot) { while (getline(dictionnaireMot, ligne)) { ligneSuivie++; if (ligneSuivie == ligneAlatoire) { motMysteres = ligne; } } } else { cout << "Impossible d'ouvrire le dictionnaire" << endl; } dictionnaireMot.close(); return motMysteres; } int calculeLigne() { int nombreDeLigne = 0; string ligne; ifstream dictionnaireMot("C:/Users/vrumm/Desktop/Programme Langage C/tp01/motMystere/dico.txt"); //Ouvre le fichier dictionnaire //Compte le nombre de ligne du dictionnaire if (dictionnaireMot) { while (getline(dictionnaireMot, ligne)) { nombreDeLigne++; } dictionnaireMot.close(); } else { cout << "Impossible d'ouvrire le dictionnaire" << endl; } return nombreDeLigne; } string melangeMot(string motMystere) { srand(time(0)); int posLettre; string motMelange; do { posLettre = rand() % motMystere.size(); motMelange = motMelange + motMystere[posLettre]; motMystere.erase(posLettre, 1); } while (motMystere.size() != 0); return motMelange; }
true
4a31c41b0707777e8404023d8ccabd9fd502dfda
C++
windwarrior/Codesign-Project
/Eindopdracht/SpiderLib/SpiderController.h
UTF-8
682
2.734375
3
[]
no_license
#ifndef _SPIDER_H_ #define _SPIDER_H_ #include "Arduino.h" #include "Motor.h" enum Turn{ TURN_LEFT, TURN_RIGHT, }; class SpiderController{ public: SpiderController(); void turnLeft(); void turnRight(); void forward(); void back(); void begin(int leftpin, int middlepin, int rightpin); void reset(); void calibrate(Motor mot, int center, int range); void test(); private: void sweepTwo(Motor mot1, int range1, Motor mot2, int range2); void sweepFromTo(Motor mot, int to); void turn(Turn side); Motor _left; Motor _middle; Motor _right; }; #endif
true
d1105a7ea60d8b291b258c7beb781ba23a62639c
C++
Abhishek765/DSA_Final
/DP/ShortestCommonSuperSequence.cpp
UTF-8
1,052
3.0625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; //! TC: O(n*m) //! SC: O(n*m) class Solution { public: int LCS(string x, string y, int n, int m){ int dp[n+1][m+1]; // bottom-up approach for(int i=0; i<=n; i++){ for(int j=0; j<=m; j++){ if(i == 0 || j == 0){ dp[i][j] = 0; continue; } if(x[i-1] == y[j-1]){ dp[i][j] = 1 + dp[i-1][j-1]; } else{ dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][m]; } //Function to find length of shortest common supersequence of two strings. int shortestCommonSupersequence(string X, string Y, int m, int n) { //find LCS of x, y int len = LCS(X, Y, m, n); return (m+n) - len; } };
true
86891af23acb0f42f40d5222d0b623c986a00813
C++
Iamsobad1990/SmartPeak
/src/smartpeak/include/SmartPeak/core/WorkflowManager.h
UTF-8
2,270
2.765625
3
[ "MIT" ]
permissive
#pragma once #include <SmartPeak/core/ApplicationHandler.h> namespace SmartPeak { class WorkflowManager { public: /** Copies the passed application_handler and sets up the async run of the workflow. Only one workflow is managed at a time @param[in,out] The application_handler that gets copied and then updated at the end of the workflow run @param[in] injection_names Injection names to use for Sequence Processing @param[in] sequence_segment_names Sequence Segment Names to use for Sequence Segment Processing @param[in] sample_group_names Sample Group Names to use for Sample Group Processing */ void addWorkflow(ApplicationHandler& source_state, const std::set<std::string>& injection_names, const std::set<std::string>& sequence_segment_names, const std::set<std::string>& sample_group_names); /** If this returns false, new workflows can't run and the following menu items are disabled in the UI: - File -> Load session from sequence - Edit -> Workflow - Action -> Run command - Action -> Run workflow */ bool isWorkflowDone() const; private: /** Spawns a thread that runs the workflow, and waits for it to finish. The modified application_handler is copied back to the source, keeping the application_handler of the app up-to-date @param[in,out] application_handler Points to the class' application_handler member @param[in,out] done Points to the class' done member @param[out] source_app_handler The modified application_handler is copied back here @param[in] injection_names Injection names to use for Sequence Processing @param[in] sequence_segment_names Sequence Segment Names to use for Sequence Segment Processing @param[in] sample_group_names Sample Group Names to use for Sample Group Processing */ static void run_and_join(ApplicationHandler& application_handler, bool& done, ApplicationHandler& source_app_handler, const std::set<std::string>& injection_names, const std::set<std::string>& sequence_segment_names, const std::set<std::string>& sample_group_names); ApplicationHandler application_handler_; ///< The workflow is run on this copy bool done_ = true; }; }
true
fb33d707b115df149dd5253d0b1ad724059b6b86
C++
asphaltbuffet/cg-practice-cpp
/test/testFactorial.cpp
UTF-8
1,003
2.765625
3
[ "MIT" ]
permissive
/* * Copyright (c) 2019 Ben Lechlitner (otherland@gmail.com) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #ifdef USE_CATCH2 #include <catch2/catch.hpp> #elif USE_GTEST #include <gtest/gtest.h> #endif // USE_CATCH2 #include "cg-practice-cpp/factorial.hpp" namespace cg_practice_cpp { namespace tests { #ifdef USE_CATCH2 TEST_CASE( "Test factorial function", "[factorial]" ) { REQUIRE_THROWS( computeFactorial( -5 ) ); REQUIRE( computeFactorial( 0 ) == 1 ); REQUIRE( computeFactorial( 1 ) == 1 ); REQUIRE( computeFactorial( 2 ) == 2 ); REQUIRE( computeFactorial( 5 ) == 120 ); } #elif USE_GTEST TEST(Factorial, Unit) { ASSERT_ANY_THROW( computeFactorial( -5 ) ); EXPECT_EQ( computeFactorial( 0 ), 1); EXPECT_EQ( computeFactorial( 1 ), 1); EXPECT_EQ( computeFactorial( 2 ), 2); EXPECT_EQ( computeFactorial( 5 ), 120); } #endif // USE_CATCH2 } // namespace tests } // namespace cg_practice_cpp
true
4a445be718da6339f729dec83e9ef308ecae4cb2
C++
pthaike/coder
/hiho/hiho101.cpp
GB18030
3,881
3.203125
3
[]
no_license
/** http://hihocoder.com/contest/hiho101/problem/1 1У1tʾ1t10 tݣÿĸʽΪ 1У2n,mʾݵ2n,m100 2..n+1Уÿmֻ01 1..tУiбʾiǷڽ⣬"Yes""No" 2 4 4 1 1 0 1 0 1 1 0 1 0 0 0 0 1 0 1 4 4 1 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 No Yes */ #include <stdio.h> using namespace std; #define MAXLEN 100 int matrix[MAXLEN]; struct _node { struct _node * left; struct _node * right; struct _node * up; struct _node * down; int x; int y; }; struct _node * columnHead[MAXLEN+1]; struct _node * node[MAXLEN*MAXLEN]; int id[MAXLEN][MAXLEN]; int m,n; struct _node * init(int m, int n) { //ͷ struct _node * head = {left:head, right:head, up:head, down:head, x:-1, y:-1}; struct _node * pre = head; for(int i = 0; i < n; i++) { struct _node * p = {x:0, y:i}; columnHead[i] = p; p->down = p; p->up = p; p->left = pre; p->right = pre->right; pre->right->left = p; pre->right = p; pre = p; } //ʼ int cnt = 0; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(matrix[i][j] == 1) { id[i][j] = cnt; node[cnt++] = {left:node[cnt], right:node[cnt], up:node[cnt], down:node[cnt], x:i, y:j}; } } } //ӽ struct _node * p; for(int i = 0; i < m; i++) { pre = columnHead[i]; for(int j = 0; j < n; j++) { if(matrix[i][j] == 1) { p = node[id[i][j]]; p.down = pre.down; p.up = pre; pre.down.up = p; pre.down = p; pre = p; } } } //ӽ for(int i = 0; i < n; i++) { pre = NULL; for(int j = 0; j < m; j++) { if(matrix[j][i] == 1) { if(pre == NULL) pre = node[id[j][i]]; else { p = node[id[j][i]]; p.left = pre; p.right = pre.right; pre.right.left = p; pre.right = p; pre = p; } } } } return head; } /** ɾcol */ void remove(int col) { struct _node * p = columnHead[col]; p.right.left = p.left; p.left.right = p.right; struct _node *p1 = p.down; while(p1 != p) { //ȡµÿ struct _node * p2 = p1.right; while(p2 != p1) { p2.down.up = p2.up; p2.up.down = p2.down; p2 = p2.right; } p1 = p1.down; } } /** ظcol */ void resume(int col) { struct _node * p = columnHead[col]; p.right.left = p; p.left.right = p; struct _node * p1 = p.down; while(p1 != p) { struct _node * p2 = p1.right; while(p2 != p1) { p2.up.down = p2; p2.down.up = p2; p2 = p2.right; } p1 = p1.down; } } bool dance(int m, int n) { struct _node * head = init(m,n); return false; } int main(void) { int t, m, n; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for(int i = 0; i < n; i ++) for(int j = 0; j < m; j++) scanf("%d", &matrix[i][j]); if(dance()) printf("Yes\n"); else printf("No\n"); } return 0; }
true
f9c34d448d8f40cf35aafeb5fc463ece1c1df94b
C++
chanthamoney/csci3081
/project/src/observer.h
UTF-8
1,333
2.84375
3
[]
no_license
/** * @file observer.h * * @copyright 2017 3081 Staff, All rights reserved. */ #ifndef SRC_OBSERVER_H_ #define SRC_OBSERVER_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <iostream> /******************************************************************************* * Namespaces ******************************************************************************/ NAMESPACE_BEGIN(csci3081); /******************************************************************************* * Class Definitions ******************************************************************************/ /** * @brief A template Observer class for observing a subject * The observer for the observing pattern * The class is used as a cookie cutter for different types of obsevers */ template <class T> class Observer { public: /** * @brief Observer Deconstructor. */ virtual ~Observer() = default; /** * @brief UpdateState observes a type T attribute of the subject * * @param[in] arg The pointer of arg of some type T * * @return The updated value for the pointer of arg of type T */ virtual void UpdateState(const T* arg) = 0; }; NAMESPACE_END(csci3081); #endif // SRC_OBSERVER_H_
true
8e78a1128db1e299e03fe89d11838920b7a92133
C++
StroudCenter/S-CAN-Modbus
/src/scanAnapro.h
UTF-8
2,597
2.53125
3
[ "BSD-3-Clause" ]
permissive
/* *scanAnapro.h */ #ifndef scanAnapro_h #define scanAnapro_h #include <scanModbus.h> // For modbus communication #include <TimeLib.h> // for dealing with the TAI64/Unix time //---------------------------------------------------------------------------- // FUNCTIONS TO CREATE PRINTOUTS THAT WILL READ INTO ANA::XXX //---------------------------------------------------------------------------- class anapro { public: anapro(scan *scanMB){_scanMB = scanMB;} // This is for the first line of both headers (below) void printFirstLine(Stream *stream); void printFirstLine(Stream &stream); // This prints out a header for a "par" file ini the format that the // s::can/ana::xxx software is expecting // The delimeter is changable, but if you use anything other than the // default TAB (\t, 0x09) the s::can/ana::xxx software will not read it. void printParameterHeader(Stream *stream, const char *dlm="\t"); void printParameterHeader(Stream &stream, const char *dlm="\t"); // This prints the data from ALL parameters as delimeter separated data. // By default, the delimeter is a TAB (\t, 0x09), as expected by the s::can/ana::xxx software. // This includes the parameter timestamp and status. // NB: You can use this to print to a file on a SD card! void printParameterDataRow(Stream *stream, const char *dlm="\t"); void printParameterDataRow(Stream &stream, const char *dlm="\t"); // This prints out a header for a "fp" file ini the format that the // s::can/ana::xxx software is expecting void printFingerprintHeader(Stream *stream, const char *dlm="\t", spectralSource source=fingerprint); void printFingerprintHeader(Stream &stream, const char *dlm="\t", spectralSource source=fingerprint); // This prints a fingerprint data rew // NB: You can use this to print to a file on a SD card! void printFingerprintDataRow(Stream *stream, const char *dlm="\t", spectralSource source=fingerprint); void printFingerprintDataRow(Stream &stream, const char *dlm="\t", spectralSource source=fingerprint); // This converts a unix timestamp to a string formatted as YYYY.MM.DD hh:mm:ss static String timeToStringDot(time_t time); // This converts a unix timestamp to a string formatted as YYYY.MM.DD hh:mm:ss static String timeToStringDash(time_t time); private: // This just makes a two digit number with a preceeding 0 if necessary static String Str2Digit(int value); // The internal link to the s::can class instance scan *_scanMB; }; #endif
true
a57077f89d1e646c380f6093d5e8dd066d851a04
C++
GreJangre/algorithm_C
/11720.cpp
UTF-8
249
2.59375
3
[]
no_license
#include <stdio.h> int main() { int N=0; char num[101]; int sum=0; scanf("%d\n", &N); scanf("%s", num); for (int i=0; i<N; i++) { sum += num[i] - '0'; } printf("%d", sum); return 0; }
true
d85f04fdf668216b6a380c132d351027aa1b618f
C++
glaSSSeaweed/DataStructureAndAlgorithm
/1_5/3.cpp
UTF-8
1,028
2.640625
3
[]
no_license
class Solution { public: Solution() :counter(0),tmparr() {} void ms(vector<int>& arr, int L, int R); vector<int> tmparr; int counter; int reversePairs(vector<int>& nums) { int len = nums.size(); if (len < 2) return 0; tmparr = vector<int>(len); ms(nums, 0, len - 1); return counter; } }; void Solution::ms(vector<int>& arr, int L, int R) { if (L == R) return; int mid = (R + L) / 2; ms(arr, L, mid); ms(arr, mid + 1, R); int tmpIndex = 0; int L_index = L; int R_index = mid + 1; int tmp = 0; //34 12 while (L_index <= mid && R_index <= R) { if (arr[L_index] > arr[R_index]) counter += (R-R_index+1); tmparr[tmpIndex++] = arr[L_index] > arr[R_index] ? arr[L_index++] : arr[R_index++]; } while (L_index <= mid) { tmparr[tmpIndex++] = arr[L_index++]; } while (R_index <= R) { tmparr[tmpIndex++] = arr[R_index++]; } for (int i = 0; i < tmpIndex; i++) { arr[L + i] = tmparr[i]; } }
true
5d32bd2f6a707ebdad4c26f1aeeabd46e032ca71
C++
wanliuestc/mengmengda
/c++/testfriend.cpp
UTF-8
375
3.15625
3
[]
no_license
#include <iostream> #include <string> using namespace std; class T { private: int a; string s; friend void testfriend(T *); friend class O; public: T():a(0),s("hello"){} }; class O { }; void testfriend(T *t) { cout << t->a << " " << t->s << endl; } int main(void) { T *t = new T(); testfriend(t); delete t; return 0; }
true
dc33dce689d611e188f4d429b336abe3ac24ef96
C++
wusuopubupt/hackerrankcpp
/introduction/arrays.cpp
UTF-8
393
2.765625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; scanf("%d", &n); int a[n]; for(int i = 0; i < n; i++) { scanf("%d", &a[i]); } for(int j = n-1; j >=0; j--) { cout << a[j] << " "; } cout << endl; return 0; }
true
ed7d11c94b5fa37645f2d59365f1ac1201927d36
C++
jethrokuan/cpp-algos
/kattis/apaxiaaans.cpp
UTF-8
187
2.78125
3
[]
no_license
#include <iostream> using namespace std; char c; int main() { char prev = 0; while (scanf("%c", &c) == 1) { if (c != prev) { prev = c; printf("%c", c); } } }
true
c39e44c1d48eda9fbfde3d2938f4a151365fe5c9
C++
bmcdonnel/data-structures
/cpp/exercises/reverse_bits.cpp
UTF-8
1,349
3.640625
4
[]
no_license
#include <iostream> #include <cstdint> #include <bitset> uint32_t easy_reverse_bits(const uint32_t number) { uint32_t rebmun = 0; for (int i = 0; i < 32; ++i) { rebmun = (rebmun << 1) + ((number >> i) & 1); } return rebmun; } uint32_t fast_reverse_bits(const uint32_t number) { // 0x01234567 becomes 0x45670123 uint32_t rebmun = (number >> 16) | (number << 16); // flip each neighboring byte rebmun = ((rebmun & 0xFF00FF00) >> 8) | ((rebmun & 0x00FF00FF) << 8); // flip each neighboring nibble rebmun = ((rebmun & 0xF0F0F0F0) >> 4) | ((rebmun & 0x0F0F0F0F) << 4); // flip each neighboring half-nibble rebmun = ((rebmun & 0xCCCCCCCC) >> 2) | ((rebmun & 0x33333333) << 2); // flip each neighboring bit rebmun = ((rebmun & 0xAAAAAAAA) >> 1) | ((rebmun & 0x55555555) << 1); return rebmun; } int main(int argc, char** argv) { if (argc != 2) { std::cout << "usage: " << argv[0] << " <integer>" << std::endl; return 1; } uint32_t number = std::atoi(argv[1]); uint32_t rebmun = easy_reverse_bits(number); uint32_t fast_rebmun = fast_reverse_bits(number); std::cout << "number: " << std::bitset<32>(number) << std::endl; std::cout << "easy reverse: " << std::bitset<32>(rebmun) << std::endl; std::cout << "fast reverse: " << std::bitset<32>(fast_rebmun) << std::endl; return 0; }
true
49e00e32e00619d4a531667698a277f301dbf81d
C++
LuminousAme/Dam-Defense
/modules/Titan/include/Titan/Graphics/ITexture.h
UTF-8
1,374
2.671875
3
[]
no_license
//Titan Engine, by Atlas X Games // ITexture.h - header for the base class that different types of textures inherit from #pragma once //precompile header, this file uses cstdint, memory, glad/glad.h, and GLM/glm.hpp #include "Titan/ttn_pch.h" namespace Titan { //base class for different texture types class TTN_ITexture { public: //define names for shared and unique pointers of this class typedef std::shared_ptr<TTN_ITexture> sitptr; typedef std::unique_ptr<TTN_ITexture> uitptr; //struct representing limits avaible to OpenGl textures based on the current renderer struct TTN_Texture_Limits { int MAX_TEXTURE_SIZE; int MAX_TEXTURE_UNITS; int MAX_3D_TEXTURE_SIZE; int MAX_TEXTURE_IMAGE_UNITS; float MAX_ANISOTROPY; }; // Gets the texture limits on the current GPU static const TTN_Texture_Limits& GetLimits() { return _limits; } // Unbinds a texture from the given slot static void Unbind(int slot); // Gets the underlying OpenGL handle for this texture GLuint& GetHandle() { return _handle; } //clears this texutre to a given colour void Clear(const glm::vec4 color = glm::vec4(1.0f)); // Binds this texture to the given texture slot void Bind(int slot) const; protected: TTN_ITexture(); virtual ~TTN_ITexture(); GLuint _handle; static TTN_Texture_Limits _limits; static bool _isStaticInit; }; }
true
087ae598b9a70f2371ed00e784669767bb55a25c
C++
stephaneAG/Qt_tests
/qt_arduino_test1/corresponding_arduino_sketch/QtArduino1.ino
UTF-8
844
3.21875
3
[ "MIT" ]
permissive
/* ** Arduino - Qt 'qextserialport' lib test file 1 ** ** controls the brightness of a LED present on the pin 9 ** ** ~schematics: Gnd <->l LED L<->1KOhm resistor<->pin9 ** */ const int ledPin = 9; // the pin the LED is attached to //const byte ledBrightness = 150; void setup() { Serial.begin(9600); //start the serial port at 9600 bauds pinMode(ledPin, OUTPUT); // init the LED pin as an output //analogWrite(ledPin, ledBrightness);// set the brightness of the LED } void loop() { byte brightness; // if we get data from the computer, update the LED brightness if ( Serial.available() > 0 ) // if data is available from the serial { brightness = Serial.read(); // read the most recent byte ('ll be from 0 to 255) analogWrite(ledPin, brightness);// set the brightness of the LED } }
true
6dd8b8340d19a8d106107fe4ea791cc751cfa9a9
C++
chrisburr/Kepler
/Tb/TbEvent/src/TbTrack.cpp
UTF-8
1,718
2.515625
3
[]
no_license
#include "Event/TbTrack.h" using namespace LHCb; //============================================================================= // Track copy constructor //============================================================================= TbTrack::TbTrack(const LHCb::TbTrack& rhs) : KeyedObject<int>(), m_time(rhs.m_time), m_htime(rhs.m_htime), m_firstState(rhs.m_firstState), m_chi2PerNdof(rhs.m_chi2PerNdof), m_ndof(rhs.m_ndof), m_clusters(rhs.m_clusters), m_triggers(rhs.m_triggers), m_associatedClusters(rhs.m_associatedClusters) { // Copy the nodes. for (auto it = rhs.m_nodes.begin(), end = rhs.m_nodes.end(); it != end; ++it) { addToNodes(*it); } } //============================================================================= // Track clone method //============================================================================= TbTrack* TbTrack::clone() { TbTrack* track = new TbTrack(); track->setTime(time()); track->setHtime(htime()); track->setFirstState(firstState()); track->setChi2PerNdof(chi2PerNdof()); track->setNdof(ndof()); // Copy the nodes. for (auto it = m_nodes.begin(), end = m_nodes.end(); it != end; ++it) { track->addToNodes(*it); } return track; } //============================================================================= // Add a node //============================================================================= void TbTrack::addToNodes(const TbNode& node) { m_nodes.push_back(node); } //============================================================================= // Clear the nodes //============================================================================= void TbTrack::clearNodes() { m_nodes.clear() ; }
true
07d765175dcac5d7ec64e405ae6dcadaf5c6174b
C++
Muhammad-Ihsan-SanSanS/Tugas062320
/Tugas062320.cpp
UTF-8
1,078
3.03125
3
[]
no_license
#include <iostream> using namespace std; int main () { cout << "_=-*PENGISIAN BIODATA*-=_\n\n"; string nama; cout << "Ikuti Langkah Berikut untuk Memasukkan Data Diri Anda!\n"; cout << "Siapa Nama Anda?\n"; getline (cin, nama); cout << "\nHello " << nama << ", Mari Isi Lebih Lengkap Datanya!\n"; int a; bool hasil; cout << "Apakah Anda Laki-laki?\nTekan 1 Jika TIDAK, Tekan 2 Jika YA: "; cin >> a; hasil = a - 1; char goldar; cout << "\nMasukkan Jenis Golongan Darah Anda:\n"; cin >> goldar; float tanggal; cout << "\nMasukkan Tanggal Lahir Anda:\n"; cin >> tanggal; double bulan, tahun; cout << "\nMasukkan Bulan Berapa Anda Lahir:\n"; cin >> bulan; cout << "\nMasukkan Tahun Berapa Anda Lahir:\n"; cin >> tahun; cout << "\nHasil Data yang Telah Anda Masukkan:\n"; cout << "Nama: " << nama <<endl; cout << "Gender: " << hasil <<" (Ket: 1 = LK, 0 = PR)" <<endl; cout << "Tipe Golongan Darah: " << goldar <<endl; cout << "Tanggal Lahir: " << tanggal << "/" << bulan << "/" << tahun; return 0; }
true
c0a804cd3154448ac3b48ca33bf0f9cd78cd011e
C++
Manash-git/C-Programming-Study
/array using loop.cpp
UTF-8
196
2.703125
3
[]
no_license
// #include<stdio.h> #define array_size 5 int main(){ int manash[array_size] = {10,20,30,40,50}; for(int i=0;i<array_size;i++){ printf("\tManash[%d] is : %d\n",i,manash[i]); } return 0; }
true
06b57552353cae19e21946b0456ce9cda56a4a4f
C++
victorfarias/Introduction-Programming-ES-20181
/moodle_matrizes/quadrado_magico.cpp
UTF-8
1,004
3.328125
3
[]
no_license
#include <iostream> using namespace std; void ler_matriz(int n, int m, int mat[][3]){ for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cin >> mat[i][j]; } } } int quadrado_magico(int n, int m, int mat[][3]){ int base =0; for(int i=0; i<n; i++){ base += mat[i][i]; } int soma =0; for(int i =0; i<n; i++){ soma += mat[i][n-i-1]; } if(soma != base){ return 0; } for(int i=0; i<n; i++){ soma =0; for(int j=0; j<m; j++){ soma += mat[i][j]; } if(soma != base){ return 0; } } for(int j=0; j<m; j++){ soma =0; for(int i=0; i<n; i++){ soma += mat[i][j]; } if(soma != base){ return 0; } } return 1; } int main(){ int m[3][3]; ler_matriz(3, 3, m); if(quadrado_magico(3, 3, m)==1){ cout << "sim"; }else{ cout << "nao"; } return 0; }
true
e1a24ee3c2fa8528789991ae6c505b0292601729
C++
Ace-HasIssuesToo/SP3Remade
/Base/Source/Sensor.cpp
UTF-8
3,463
2.59375
3
[]
no_license
#include "Sensor.h" #include "Player.h" #include "Enemy_Poison.h" #include "Enemy_Psychic.h" #include "Enemy_Ghost.h" #include "EnemyDark.h" #include "GameState.h" Sensor* Sensor::m_pointer = new Sensor(); void Sensor::Init() { float Speed = 1.f; Save = MeshBuilder::GenerateSpriteAnimation("Save", 1, 8); Save->textureArray[0] = LoadTGA("Data//Texture//Save.tga"); SpriteAnimation *sa = dynamic_cast<SpriteAnimation*>(Save); if (sa) { sa->m_anim = new Animation(); sa->m_anim->Set(0, 7, 0, Speed, true); } Danger = MeshBuilder::GenerateSpriteAnimation("Danger", 1, 8); Danger->textureArray[0] = LoadTGA("Data//Texture//Danger.tga"); sa = dynamic_cast<SpriteAnimation*>(Danger); if (sa) { sa->m_anim = new Animation(); sa->m_anim->Set(0, 7, 0, Speed, true); } dead = MeshBuilder::GenerateSpriteAnimation("Dead", 1, 8); dead->textureArray[0] = LoadTGA("Data//Texture//Dead.tga"); sa = dynamic_cast<SpriteAnimation*>(dead); if (sa) { sa->m_anim = new Animation(); sa->m_anim->Set(0, 7, 0, Speed, true); } Range = INT_MAX; Player_Pos = Vector3(); } void Sensor::Mesh_Update(Mesh* mesh, double dt) { SpriteAnimation *sa = dynamic_cast<SpriteAnimation*>(mesh); if (sa) { sa->Update(dt); sa->m_anim->animActive = true; } } void Sensor::Range_Cal(Vector3 Enemy_Pos) { Vector3 Dir = Player_Pos - (Enemy_Pos); float Temp_Range = (Dir.x*Dir.x) + (Dir.y*Dir.y); if (Temp_Range < Range) { Range = Temp_Range; } } void Sensor::Update(double dt) { Player_Pos = PlayerClass::pointer()->getPlayerPos(); Mesh_Update(Save, dt); Mesh_Update(Danger, dt); Mesh_Update(dead, dt); Range = INT_MAX; int state = GameState::pointer()->current_State(); if (state == GameState::FLOOR1) { Range_Cal(Enemy_Ghost::pointer()->GetGhostPos()); } else if (state == GameState::FLOOR2) { Range_Cal(Enemy_Psychic::pointer()->GetPos()); Range_Cal(Enemy_Ghost::pointer()->GetGhostPos()); } else if (state == GameState::FLOOR3) { Range_Cal(Enemy_Poison::pointer()->GetPos()); Range_Cal(Enemy_Psychic::pointer()->GetPos()); Range_Cal(Enemy_Ghost::pointer()->GetGhostPos()); } else { Range_Cal(Enemy_Poison::pointer()->GetPos()); Range_Cal(Enemy_Psychic::pointer()->GetPos()); Range_Cal(Enemy_Ghost::pointer()->GetGhostPos()); Range_Cal(Enemy_Dark::pointer()->getEnemyDarkPos()); } } void Sensor::Render() { int Min_Range = 50; Vector3 Pos = Render_PI::Window_Scale(); Pos.y = 15; Pos.x *= 0.9; Render_PI::pointer()->modelStack_Set(true); if (Range > Min_Range*100) { Render_PI::pointer()->RenderMeshIn2D(Save, false, Pos, Vector3(20, 20, 1)); } else if (Range > Min_Range*5) { Render_PI::pointer()->RenderMeshIn2D(Danger, false, Pos, Vector3(20, 20, 1)); } else { Render_PI::pointer()->RenderMeshIn2D(dead, false, Pos, Vector3(20, 20, 1)); } Render_PI::pointer()->modelStack_Set(false); } void Sensor::Exit() { if (Save != nullptr) { SpriteAnimation *sa = dynamic_cast<SpriteAnimation*>(Save); if (sa) { delete sa->m_anim; } delete Save; Save = nullptr; } if (Danger != nullptr) { SpriteAnimation *sa = dynamic_cast<SpriteAnimation*>(Danger); if (sa) { delete sa->m_anim; } delete Danger; Danger = nullptr; } if (dead != nullptr) { SpriteAnimation *sa = dynamic_cast<SpriteAnimation*>(dead); if (sa) { delete sa->m_anim; } delete dead; dead = nullptr; } if (m_pointer != nullptr) { delete m_pointer; m_pointer = nullptr; } }
true
461e6a3320c463a1a4b2d15f13a1390dcb6d5196
C++
Zhgsimon/Parametric_landscapes_generator
/astre.h
ISO-8859-1
627
2.640625
3
[]
no_license
#ifndef ASTRE_H_INCLUDED #define ASTRE_H_INCLUDED #include "environnement.h" ///Dclaration de la classe abstraite "Astre" qui hrite de la classe ///"Environnement" et mere des classes soleil, lune, etc... ///fais hriter une couleur et des coordonnes sera utilis dans leur fonction addCercle... pour dessiner la figure a un certain endroit ///fais aussi hriter les mthodes de translation qui sont les mmes pour toutes les classes filles ///et a pour mthodes virtuelles pures class Astre: public Environnement { ///Methodes : dclaration public: Astre(Coords coords); }; #endif // ASTRE_H_INCLUDED
true
42d279299dbc9667869df2033e44ea9363631cbf
C++
PacktPublishing/Cpp-for-game-developers
/Module 1/B04920_Code/B04920_Code/B04920_08_FinalCode/roguelike_template/src/Gold.cpp
UTF-8
840
3.234375
3
[ "MIT" ]
permissive
#include "PCH.h" #include "Gold.h" // Default constructor. Gold::Gold() { // Randomly generate the value of the pickup. this->goldValue = std::rand() % 21 + 5; // Choose a sprite based on the gold value. int textureID; if (this->goldValue < 9) { textureID = TextureManager::AddTexture("../resources/loot/gold/spr_pickup_gold_small.png"); } else if (this->goldValue >= 16) { textureID = TextureManager::AddTexture("../resources/loot/gold/spr_pickup_gold_large.png"); } else { textureID = TextureManager::AddTexture("../resources/loot/gold/spr_pickup_gold_medium.png"); } // Set the sprite. this->SetSprite(TextureManager::GetTexture(textureID), false, 8, 12); // Set the item type. m_type = ITEM::GOLD; } // Returns the amount of gold this pickup has. int Gold::GetGoldValue() const { return this->goldValue; }
true
3879af114fc7572c145a4759ea4a3b6eda5c593c
C++
vijay532/Game-Using-c-
/RockPaperScissor.cpp
UTF-8
1,522
2.984375
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define ll long long using namespace std; int main() { ll n,i,j; //cin>>j; do { cout<<"How many Rounds will be there ?"<<endl; cin>>n; cout<<"Rock=r or R Paper=p or P Scisor=s or S........"<<endl; ll c1=0,c2=0; while(n--) { string p1,p2; cin>>p1>>p2; i=0; if(p1[i]=='R' && p2[i]=='P' || p1[i]=='r' && p2[i]=='p') { c1++; } else if(p1[i]=='P' && p2[i]=='R' || p1[i]=='p' && p2[i]=='r') { c2++; } else if(p1[i]=='P' && p2[i]=='S' || p1[i]=='p' && p2[i]=='s') { c2++; } else if(p1[i]=='S' && p2[i]=='P' || p1[i]=='s' && p2[i]=='P') { c1++; } else if(p1[i]=='R' && p2[i]=='S' || p1[i]=='r' && p2[i]=='s') { c1++; } else if(p1[i]=='S' && p2[i]=='R' || p1[i]=='s' && p2[i]=='r') { c2++; } } cout<<((c1>=c2)?(c1==c2)?"DRAW":("Player 1 is won !!!!"):"Player 2 is won !!!!")<<endl; cout<<"Do you want more games to play, click 1 for YES and Click 0 for NO??"<<endl; cin>>j; }while(j); /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
true
dd3f6cef99f2c83073f3e0e1df023c3cc4471f1f
C++
christosg88/hackerrank
/Data_Stractures/2-Linked_Lists/Compare_two_linked_lists/compare-two-linked-lists.cpp
UTF-8
1,122
4.375
4
[ "MIT" ]
permissive
/** * Compare two linked lists A and B. * Return 1 if they are identical and 0 if they are not. * * Node is defined as: * struct Node * { * int data; * Node *next; * } */ /** * Compares two linked lists for equality. Two linked lists are considered equal * if they contain the same number of nodes and each pair of nodes contain the * same data. * @param headA a pointer to the head of the first linked list * @param headB a pointer to the head of the second linked list * @return 1 for equality else 0 */ int CompareLists(Node *headA, Node *headB) { while (true) { // if they both reached their ends, they are equal if (headA == NULL && headB == NULL) return 1; // else if one of them is NULL but the other is not, or if their data // are not equal, the lists are not equal else if (headA == NULL || headB == NULL || headA->data != headB->data) return 0; // else move to the next nodes on both lists else { headA = headA->next; headB = headB->next; } } }
true
e89cbd54866839bb6c099120083381de19614678
C++
leesatoh/itCep
/snippets/small/chronotest.cpp
UTF-8
584
2.984375
3
[]
no_license
#include <iostream> #include <unistd.h> #include <chrono> int main(){ std::chrono::system_clock::time_point start, end; // 型は auto で可 start = std::chrono::system_clock::now(); // 計測開始時間 // 処理 usleep(1000000); end = std::chrono::system_clock::now(); // 計測終了時間 double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); //処理に要した時間をミリ秒に変換 auto ctm = std::chrono::system_clock::to_time_t(start); std::cout << "elapsed:" << elapsed << " start:" << std::ctime(&(ctm)) << std::endl; }
true
344f9736a6013cda9596209d8a014fd94ecc6330
C++
AndrewKhusnulin/Labs-4b-6
/Lab-5.cpp
UTF-8
711
3.40625
3
[]
no_license
#include <iostream> using namespace std; int sum(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int multiply(int a, int b) { return a*b; } int main(int argc, char *argv[]) { setlocale(LC_ALL, "rus"); int a, b; if (!sscanf_s(argv[1], "%d", &a)) { cout << "Отсутствует параметр 1" << endl; system("pause"); return 1; } if (!sscanf_s(argv[2], "%d", &b)) { cout << "Отсутствует параметр 2" << endl; system("pause"); return 1; } cout << "Сумма: " << sum(a, b) << endl; cout << "Разность :" << sub(a, b) << endl; cout << "Произведение :" << multiply(a, b) << endl; system("pause"); return 0; }
true
690df1292cb5c6eeead98fd2c44e56d415be750d
C++
zhangkari/exercise
/ICE/src/lib/security/CRc4.cpp
UTF-8
1,143
2.703125
3
[ "Apache-2.0" ]
permissive
#include <IUnknow.h> #include <IceType.h> #include <string.h> #include <CRc4.h> #include <IID.h> #include <ErrorCode.h> ECode CRc4::QueryInterface(IID gid, void** ppv) { if(gid == IID_IRc4Encrypt) { *ppv = static_cast<IRc4*>(this); return NOERROR; } if(gid == IID_IRc4Decrypt) { *ppv = static_cast<IRc4*>(this); return NOERROR; } } inline static void swap(unsigned char* a, unsigned char* b) { unsigned char temp = *a; *a = *b; *b = temp; } ECode CRc4::Encrypt(char* key, char*input, char* result) { if(NULL == key || NULL == input || NULL == result) { return -1; } unsigned char S[256] = {0}; int keylen = strlen(key); int i, j = 0; for(i=0; i<256; ++i) { S[i] = i; } for(i=0; i<256; ++i) { j = (j + S[i] + key[i % keylen]) % 256; swap(&S[i], &S[j]); } int m = 0; char k; i = 0; j = 0; int inputlen = strlen(input); for(m=0; m<inputlen; ++m) { i = (i + 1) % 256; j = (j + S[i]) % 256; swap(&S[i], &S[j]); k = input[m] ^ S[(S[i] + S[j]) % 256]; result[m] = k; } return 0; } ECode CRc4::Decrypt(char* key, char* input, char* result) { return Encrypt(key, input, result); }
true
0f40e5282d13a792afaed67c5ab1aeabe855371b
C++
olee12/uva_onlinejudge_solutions
/Codes/10462 - Is There A Second Way Left.cpp
UTF-8
2,521
2.59375
3
[]
no_license
#include<cstring> #include<bits/stdc++.h> using namespace std; struct edge { int u,v,w,pos; bool operator < (const edge& p) const { return w<p.w; } }; int par[110]; int find_par(int r) { return (r==par[r] ? r : (par[r]= find_par(par[r]))); } vector<edge> e,sec_mst; int x,y,www,pos; int mst1(int n) { int s= 0,cnt=0; sort(e.begin(),e.end()); int u,v; for(int i = 0; i<e.size(); i++) { u = find_par(e[i].u); v = find_par(e[i].v); if(u!=v) { par[u]=v; sec_mst.push_back(e[i]); s += e[i].w; cnt++; if(cnt== n-1) return s; } } return -1; } int mst2(int n) { int s = 0,cnt=0; int u,v; for(int i = 0; i<e.size(); i++) { if(x==e[i].u && y == e[i].v && www==e[i].w && pos==e[i].pos) { // cout<<x<<' '<<y<< ' '<<s<<endl; continue; } u = find_par(e[i].u); v = find_par(e[i].v); if(u!=v) { cnt++; par[u]=v; s+=e[i].w; if(cnt == n-1) return s; } } return -1; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); #endif // ONLINE_JUDGE edge get; int test; int n,m; int u,v,w,res1,res2,cnt; scanf("%d",&test); int cas=1; while(test--) { e.clear(); sec_mst.clear(); // memset(par,0,sizeof par); scanf("%d %d",&n,&m); if(n==1 && m==0) { printf("Case #%d : No second way\n",cas++); continue; } for(int i = 1; i<=n; i++) par[i]=i; for(int i = 0; i<m; i++) { scanf("%d %d %d",&get.u,&get.v,&get.w); get.pos=i; e.push_back(get); } res1 = mst1(n); if(res1==-1) { printf("Case #%d : No way\n",cas++); continue; } cnt = 1e8; for(int i = 0; i <(int)sec_mst.size(); i++) { x = sec_mst[i].u; y = sec_mst[i].v; www = sec_mst[i].w; pos=sec_mst[i].pos; for(int i = 1; i<=n; i++) par[i]=i; res2 = mst2(n); if(cnt>res2 && res2!=-1) cnt=res2; } if(cnt!=1e8) { printf("Case #%d : %d\n",cas++,cnt); } else { printf("Case #%d : No second way\n",cas++); } } return 0; }
true
c2e158974c22e7b3e690ead8cf3ea392b9aeb997
C++
pig0726/LeetCode
/problemset/Missing_Number.cpp
UTF-8
250
2.859375
3
[]
no_license
class Solution { public: int missingNumber(vector<int>& nums) { int size = nums.size(); int sum = (0 + size) * (size+1) / 2; int x = 0; for (int i = 0; i < size; i++) x += nums[i]; return sum - x; } };
true
02920cf42c59bf8170dd2445745ee474cfbc211b
C++
CaptBoscho/earlycsclasses
/CS235/Project2/LineCounter.h
UTF-8
370
2.859375
3
[]
no_license
#pragma once #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; class LineCounter { private: string word; int number; public: LineCounter(); LineCounter(string w, int n); string getWord() const {return word;} int getNumber() const {return number;} void setWord(string w); void setNumber(int n); };
true
be512644aa8171b715cf1d9e36360993505c8367
C++
lithiumdenis/CSFData
/DSR/DSR2/DSR2/DSR2.cpp
UTF-8
969
2.765625
3
[ "MIT" ]
permissive
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> using namespace std; #define N 120 int _tmain(int argc, _TCHAR* argv[]) { vector<string> text1; vector<string> text2; FILE *file1; char arr[N]; fopen_s(&file1, "file1.txt", "r"); while (fgets(arr, N, file1) != NULL) { text1.push_back(arr); printf("%s", arr); } text1[text1.size() - 1] += "\n"; printf("\n"); printf("\n"); fclose(file1); FILE *file2; char arr2[N]; fopen_s(&file2, "file2.txt", "r"); while (fgets(arr2, N, file2) != NULL) { text2.push_back(arr2); printf("%s", arr2); } text2[text2.size() - 1] += "\n"; printf("\n"); fclose(file2); for (int i = 0; i < text2.size(); i++) { for (int j = 0; j < text1.size(); j++) { if (text2[i] == text1[j]) break; if (j == text1.size() - 1) { printf("\nNo, wrong\n"); return 0; } } } printf("\nOkey, all good\n"); return 0; }
true
fcfdb8244baa2a93677889cc9b74e6782938b8cd
C++
leviathanch/QtVerilog
/verilog_ast.cc
UTF-8
88,531
2.84375
3
[]
no_license
/*! @file verilog_ast.c @brief Contains definitions of functions which operate on the Verilog Abstract Syntax Tree (AST) */ #include <string> #include <cstdarg> #include <assert.h> #include <stdio.h> #include "verilog_ast.hh" #include "verilog_preprocessor.hh" #include "verilogcode.h" #include "verilogscanner.hh" #define yylex lexer->lex #define yylineno ((int) lexer->lineno()) #define yytext lexer->YYText namespace yy { /*! @brief Responsible for setting the line number and file of each node's meta data member. @param [inout] meta - A pointer to the metadata member to modify. */ void VerilogCode::ast_set_meta_info(ast_metadata * meta) { meta->line = yylineno; meta->file = verilog_preprocessor_current_file(yy_preproc); } /*! @brief Creates and returns as a pointer a new attribute descriptor. */ ast_node_attributes * VerilogCode::ast_new_attributes(ast_identifier name, ast_expression * value) { ast_node_attributes * tr = (ast_node_attributes *)ast_calloc(1, sizeof(ast_node_attributes)); tr->attr_name = name; tr->attr_value = value; return tr; } /*! @brief Creates and returns a new attribute node with the specified value and name. @param [inout] parent - Pointer to the node which represents the list of attribute name,value pairs. @param [in] toadd - The new attribute to add. */ void VerilogCode::ast_append_attribute(ast_node_attributes * parent, ast_node_attributes * toadd) { // Add the new attribute to the end of the list. ast_node_attributes * walker = parent; while(walker->next != NULL) walker = walker->next; walker->next = toadd; } /*! @brief Creates and returns a new @ref ast_lvalue pointer, with the data type being a single identifier of either @ref NET_IDENTIFIER or @ref VAR_IDENTIFIER. */ ast_lvalue * VerilogCode::ast_new_lvalue_id(ast_lvalue_type type, ast_identifier id) { assert(type == NET_IDENTIFIER || type == VAR_IDENTIFIER || type == GENVAR_IDENTIFIER || type == SPECPARAM_ID || type == PARAM_ID); ast_lvalue * tr = (ast_lvalue *)ast_calloc(1, sizeof(ast_lvalue)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->data.identifier = id; return tr; } /*! @brief Creates and returns a new @ref ast_lvalue pointer, with the data type being a concatenation holder of either @ref NET_CONCATENATION or @ref VAR_CONCATENATION. */ ast_lvalue * VerilogCode::ast_new_lvalue_concat(ast_lvalue_type type, ast_concatenation*concat) { assert(type == NET_CONCATENATION || type == VAR_CONCATENATION); ast_lvalue * tr = (ast_lvalue *)ast_calloc(1, sizeof(ast_lvalue)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->data.concatenation = concat; return tr; } /*! @brief A utility function for converting an ast expression primaries back into a string representation. @param [in] p - The expression primary to turn into a string. */ std::string VerilogCode::ast_primary_tostring(ast_primary * p) { std::string tr; switch (p->value_type) { case PRIMARY_NUMBER: tr = ast_number_tostring(p->value.number); break; case PRIMARY_IDENTIFIER: tr = ast_identifier_tostring(p->value.identifier); break; case PRIMARY_FUNCTION_CALL: tr = ast_identifier_tostring(p ->value.function_call->function); break; case PRIMARY_MINMAX_EXP: tr = ast_expression_tostring(p->value.minmax); break; case PRIMARY_CONCATENATION: default: printf("primary type to string not supported: %d %s\n", __LINE__,__FILE__); tr = "<unsupported>"; break; } return tr; } /*! @brief Creates a new ast primary which is part of a constant expression tree with the supplied type and value. */ ast_primary * VerilogCode::ast_new_constant_primary(ast_primary_value_type type) { ast_primary * tr = (ast_primary *)ast_calloc(1, sizeof(ast_primary)); ast_set_meta_info(&(tr->meta_info)); tr->primary_type = CONSTANT_PRIMARY; tr->value_type = type; return tr; } /*! @brief Creates a new AST primary wrapper around a function call. */ ast_primary * VerilogCode::ast_new_primary_function_call(ast_function_call * call) { ast_primary * tr = (ast_primary *)ast_calloc(1, sizeof(ast_primary)); ast_set_meta_info(&(tr->meta_info)); assert(tr!=NULL); tr->primary_type = PRIMARY; tr->value_type = PRIMARY_FUNCTION_CALL; tr->value.function_call = call; return tr; } /*! @brief Creates a new ast primary which is part of an expression tree with the supplied type and value. */ ast_primary * VerilogCode::ast_new_primary(ast_primary_value_type type) { ast_primary * tr = (ast_primary *)ast_calloc(1, sizeof(ast_primary)); ast_set_meta_info(&(tr->meta_info)); tr->primary_type = PRIMARY; tr->value_type = type; return tr; } /*! @brief Creates a new ast primary which is part of a constant expression tree with the supplied type and value. */ ast_primary * VerilogCode::ast_new_module_path_primary(ast_primary_value_type type) { ast_primary * tr = (ast_primary *)ast_calloc(1, sizeof(ast_primary)); ast_set_meta_info(&(tr->meta_info)); tr->primary_type = MODULE_PATH_PRIMARY; tr->value_type = type; return tr; } /*! @brief Creates and returns a new expression primary. @details This is simply an expression instance wrapped around a primary instance for the purposes of mirroring the expression tree gramamr. Whether or not the expression is constant is denoted by the type member of the passed primary. */ ast_expression * VerilogCode::ast_new_expression_primary(ast_primary * p) { assert(sizeof(ast_expression) != 0); ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); assert(tr != NULL); tr->attributes = NULL; tr->right = NULL; tr->left = NULL; tr->aux = NULL; tr->type = PRIMARY_EXPRESSION; tr->primary = p; tr->constant = p->primary_type == CONSTANT_PRIMARY ? true : false; return tr; } //! Returns the string representation of an operator; std::string VerilogCode::ast_operator_tostring(ast_operator op) { switch(op) { case OPERATOR_STAR : return "*"; case OPERATOR_PLUS : return "+"; case OPERATOR_MINUS : return "-"; case OPERATOR_ASL : return "<<<"; case OPERATOR_ASR : return ">>>"; case OPERATOR_LSL : return "<<"; case OPERATOR_LSR : return ">>>"; case OPERATOR_DIV : return "/"; case OPERATOR_POW : return "^"; case OPERATOR_MOD : return "%"; case OPERATOR_GTE : return ">="; case OPERATOR_LTE : return "<="; case OPERATOR_GT : return ">"; case OPERATOR_LT : return "<"; case OPERATOR_L_NEG : return "!"; case OPERATOR_L_AND : return "&&"; case OPERATOR_L_OR : return "||"; case OPERATOR_C_EQ : return "=="; case OPERATOR_L_EQ : return "="; case OPERATOR_C_NEQ : return "!="; case OPERATOR_L_NEQ : return "!="; case OPERATOR_B_NEG : return "~"; case OPERATOR_B_AND : return "&"; case OPERATOR_B_OR : return "|"; case OPERATOR_B_XOR : return "^"; case OPERATOR_B_EQU : return "==="; case OPERATOR_B_NAND : return "~&"; case OPERATOR_B_NOR : return "~|"; case OPERATOR_TERNARY: return "?"; default: return " "; } } /*! @brief A utility function for converting an ast expression tree back into a string representation. @returns The string representation of the passed expression or an empty string if exp is NULL. @param [in] exp - The expression to turn into a string. */ std::string VerilogCode::ast_expression_tostring(ast_expression * exp){ if(exp == NULL){return "";} std::string tr; std::string lhs; std::string rhs; std::string pri; std::string cond; std::string mid; std::string op; size_t len; switch(exp->type) { case PRIMARY_EXPRESSION: case MODULE_PATH_PRIMARY_EXPRESSION: tr = ast_primary_tostring(exp->primary); break; case STRING_EXPRESSION: tr = exp->string; break; case UNARY_EXPRESSION: case MODULE_PATH_UNARY_EXPRESSION: pri = ast_primary_tostring(exp->primary); op = ast_operator_tostring(exp->operation); tr="("; tr+=op; tr+=pri; tr+=")"; break; case BINARY_EXPRESSION: case MODULE_PATH_BINARY_EXPRESSION: lhs = ast_expression_tostring(exp->left); rhs = ast_expression_tostring(exp->right); op = ast_operator_tostring(exp->operation); tr="("; tr+=lhs; tr+=op; tr+=rhs; tr+=")"; break; case RANGE_EXPRESSION_UP_DOWN: lhs = ast_expression_tostring(exp->left); rhs = ast_expression_tostring(exp->right); tr=lhs; tr+=":"; tr+=rhs; break; case RANGE_EXPRESSION_INDEX: tr = ast_expression_tostring(exp->left); break; case MODULE_PATH_MINTYPMAX_EXPRESSION: case MINTYPMAX_EXPRESSION: lhs = ast_expression_tostring(exp->left); rhs = ast_expression_tostring(exp->right); mid = ast_expression_tostring(exp->aux); tr=lhs; tr+=":"; tr+=mid; tr+=":"; tr+=rhs; break; case CONDITIONAL_EXPRESSION: case MODULE_PATH_CONDITIONAL_EXPRESSION: lhs = ast_expression_tostring(exp->left); rhs = ast_expression_tostring(exp->right); cond= ast_expression_tostring(exp->aux); tr=cond; tr+="?"; tr+=lhs; tr+=":"; tr+=rhs; break; default: printf("ERROR: Expression type to string not supported. %d of %s", __LINE__,__FILE__); tr = "<unsupported>"; break; } return tr; } /*! @brief Creates a new unary expression with the supplied operation. */ ast_expression * VerilogCode::ast_new_unary_expression(ast_primary * operand, ast_operator operation, ast_node_attributes * attr, bool constant) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->operation = operation; tr->attributes = attr; tr->primary = operand; tr->right = NULL; tr->left = NULL; tr->aux = NULL; tr->type = UNARY_EXPRESSION; tr->constant = constant; #ifdef VERILOG_PARSER_COVERAGE_ON printf("Unary Expression: '%s'\n", ast_expression_tostring(tr)); #endif return tr; } /*! @brief Creates a new range expression with the supplied operands. */ ast_expression * VerilogCode::ast_new_range_expression(ast_expression * left, ast_expression * right) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = NULL; tr->right = right; tr->left = left; tr->aux = NULL; tr->type = RANGE_EXPRESSION_UP_DOWN; return tr; } /*! @brief Creates a new range index expression with the supplied operands. */ ast_expression * VerilogCode::ast_new_index_expression(ast_expression * left) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = NULL; tr->right = NULL; tr->left = left; tr->aux = NULL; tr->type = RANGE_EXPRESSION_INDEX; return tr; } /*! @brief Creates a new primary expression with the supplied operation and operands. @note Sets the type of the expression */ ast_expression * VerilogCode::ast_new_binary_expression(ast_expression * left, ast_expression * right, ast_operator operation, ast_node_attributes * attr, bool constant) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->operation = operation; tr->attributes = attr; tr->right = right; tr->left = left; tr->aux = NULL; tr->type = BINARY_EXPRESSION; tr->constant = constant; #ifdef VERILOG_PARSER_COVERAGE_ON printf("Binary Expression: '%s'\n", ast_expression_tostring(tr)); #endif return tr; } /*! @brief Creates a new string expression. */ ast_expression * VerilogCode::ast_new_string_expression(std::string string) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = NULL; tr->right = NULL; tr->left = NULL; tr->aux = NULL; tr->type = STRING_EXPRESSION; tr->constant = true; tr->string = string; #ifdef VERILOG_PARSER_COVERAGE_ON printf("String Expression: '%s'\n", ast_expression_tostring(tr)); #endif return tr; } /*! @brief Creates a new conditional expression node. @note The condition is stored in the aux member, if_true in left, and if_false on the right. */ ast_expression * VerilogCode::ast_new_conditional_expression(ast_expression * condition, ast_expression * if_true, ast_expression * if_false, ast_node_attributes * attr) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = attr; tr->right = if_false; tr->left = if_true; tr->aux = condition; tr->type = CONDITIONAL_EXPRESSION; return tr; } /*! @brief Creates a new (min,typical,maximum) expression. @details If the mintypmax expression only specifies a typical value, then the min and max arguments should be NULL, and only typ set. */ ast_expression * VerilogCode::ast_new_mintypmax_expression(ast_expression * min, ast_expression * typ, ast_expression * max) { ast_expression * tr = (ast_expression *)ast_calloc(1, sizeof(ast_expression)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = NULL; tr->right = max; tr->left = min; tr->aux = typ; tr->type = MINTYPMAX_EXPRESSION; return tr; } /*! @brief Creates and returns a new node representing a function call. @param [in] id - The function identifier. @param [in] attr - Attributes to be passed to the function call. @param [in] system - Is this a system function call? @param [in] constant - Is this a constant function call? @param [in] arguments - list of elements of type ast_expression representing the various parameters to the function. If the function has no arguments, then it is an empty list, not NULL. If this is supplied as NULL, then an empty list is added automatically by the function. */ ast_function_call * VerilogCode::ast_new_function_call(ast_identifier id, bool constant, bool system, ast_node_attributes * attr, ast_list * arguments) { ast_function_call * tr = (ast_function_call *)ast_calloc(1, sizeof(ast_function_call)); ast_set_meta_info(&(tr->meta_info)); tr->function = id; tr->constant = constant; tr->system = system; tr->arguments = arguments; tr->attributes = attr; if(tr->arguments == NULL) { tr->arguments = ast_list_new(); } return tr; } /*! @brief Creates a new AST concatenation element with the supplied type and initial starting value. @param [in] repeat - Used for replications or multiple_concatenation. @param [in] type - The kind of value being concatenated. @param [in] first_value - The first value at the LHS of the concatenation. @details Depending on the type supplied, the type of first_value should be: - CONCATENATION_EXPRESSION : ast_expression - CONCATENATION_CONSTANT_EXPRESSION : ast_expression - CONCATENATION_NET : TBD - CONCATENATION_VARIABLE : TBD - CONCATENATION_MODULE_PATH : TBD @todo Better implement repetition of elements. */ ast_concatenation * VerilogCode::ast_new_concatenation(ast_concatenation_type type, ast_expression * repeat, void * first_value) { ast_concatenation * tr = (ast_concatenation *)ast_calloc(1,sizeof(ast_concatenation)); ast_set_meta_info(&(tr->meta_info)); tr->repeat = repeat; tr->type = type; tr->items = ast_list_new(); ast_list_append(tr->items, first_value); return tr; } /*! @brief Creates and returns a new empty concatenation of the specified type. */ ast_concatenation * VerilogCode::ast_new_empty_concatenation(ast_concatenation_type type) { ast_concatenation * tr = (ast_concatenation *)ast_calloc(1,sizeof(ast_concatenation)); ast_set_meta_info(&(tr->meta_info)); tr->repeat = NULL; tr->type = type; tr->items = ast_list_new(); return tr; } /*! @brief Adds a new data element on to the end of a concatenation. @details Appends to the front because this naturally follows the behaviour of a left-recursive grammar. @todo Better implement repetition of elements. */ void VerilogCode::ast_extend_concatenation(ast_concatenation * element, ast_expression * repeat, void * data) { element->repeat = repeat; ast_list_preappend(element->items, data); } /*! @brief Creates and returns a new path declaration type. Expects that the data be filled in manually; */ ast_path_declaration * VerilogCode::ast_new_path_declaration(ast_path_declaration_type type) { ast_path_declaration * tr = (ast_path_declaration *)ast_calloc(1,sizeof(ast_path_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->state_expression = NULL; return tr; } /*! @brief Creates and returns a pointer to a new simple parallel path declaration. */ ast_simple_parallel_path_declaration * VerilogCode::ast_new_simple_parallel_path_declaration( ast_identifier input_terminal, ast_operator polarity, ast_identifier output_terminal, ast_list * delay_value ) { ast_simple_parallel_path_declaration * tr = (ast_simple_parallel_path_declaration *)ast_calloc(1, sizeof(ast_simple_parallel_path_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->input_terminal = input_terminal; tr->polarity = polarity; tr->output_terminal= output_terminal; tr->delay_value = delay_value; return tr; } /*! @brief Creates and returns a pointer to a new simple full path declaration. */ ast_simple_full_path_declaration * VerilogCode::ast_new_simple_full_path_declaration ( ast_list * input_terminals, ast_operator polarity, ast_list * output_terminals, ast_list * delay_value ) { ast_simple_full_path_declaration * tr = (ast_simple_full_path_declaration *)ast_calloc(1,sizeof(ast_simple_full_path_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->input_terminals= input_terminals; tr->polarity = polarity; tr->output_terminals=output_terminals; tr->delay_value = delay_value; return tr; } /*! @brief Describes a single edge sensitive path declaration */ ast_edge_sensitive_parallel_path_declaration * VerilogCode::ast_new_edge_sensitive_parallel_path_declaration( ast_edge edge, //!< edge_identifier ast_identifier input_terminal, //!< specify_input_terminal_descriptor ast_operator polarity, //!< polarity_operator ast_identifier output_terminal, //!< specify_output_terminal_descriptor ast_expression * data_source, //!< data_source_expression ast_list * delay_value //!< path_delay_value ) { ast_edge_sensitive_parallel_path_declaration * tr = (ast_edge_sensitive_parallel_path_declaration *)ast_calloc(1,sizeof(ast_edge_sensitive_parallel_path_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->edge = edge ; tr->input_terminal = input_terminal ; tr->polarity = polarity ; tr->output_terminal = output_terminal; tr->data_source = data_source ; tr->delay_value = delay_value ; return tr; } /*! @brief Describes a parallel edge sensitive path declaration */ ast_edge_sensitive_full_path_declaration * VerilogCode::ast_new_edge_sensitive_full_path_declaration( ast_edge edge, //!< edge_identifier ast_list * input_terminal, //!< list_of_path_inputs ast_operator polarity, //!< polarity_operator ast_list * output_terminal, //!< list_of_path_outputs ast_expression * data_source, //!< data_source_expression ast_list * delay_value //!< path_delay_value ) { ast_edge_sensitive_full_path_declaration * tr = (ast_edge_sensitive_full_path_declaration *)ast_calloc(1,sizeof(ast_edge_sensitive_full_path_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->edge = edge ; tr->input_terminal = input_terminal ; tr->polarity = polarity ; tr->output_terminal = output_terminal; tr->data_source = data_source ; tr->delay_value = delay_value ; return tr; } /*! @brief creates and returns a pointer to a new task-enable statement. */ ast_task_enable_statement * VerilogCode::ast_new_task_enable_statement( ast_list * expressions, ast_identifier identifier, bool is_system ) { ast_task_enable_statement * tr = (ast_task_enable_statement *)ast_calloc(1,sizeof(ast_task_enable_statement)); ast_set_meta_info(&(tr->meta_info)); tr->expressions = expressions; tr->identifier = identifier; tr->is_system = is_system; return tr; } /*! @brief Creates and returns a new forever loop statement. @param inner_statement - Pointer to the inner body of statements which make upt the loop body. */ ast_loop_statement * VerilogCode::ast_new_forever_loop_statement( ast_statement * inner_statement ) { ast_loop_statement * tr = (ast_loop_statement *)ast_calloc(1,sizeof(ast_loop_statement)); ast_set_meta_info(&(tr->meta_info)); tr->type = LOOP_FOREVER; tr->inner_statement = inner_statement; tr->initial = NULL; tr->condition = NULL; tr->modify = NULL; return tr; } /*! @brief Creates and returns a new for loop statement. @param inner_statement - Pointer to the inner body of statements which make upt the loop body. @param initial_condition - Assignement which sets up the initial condition of the iterator. @param modify_assignment - How the iterator variable changes with each loop iteration. @param continue_condition - Expression which governs whether the loop should continue or break. */ ast_loop_statement * VerilogCode::ast_new_for_loop_statement( ast_statement * inner_statement, ast_single_assignment * initial_condition, ast_single_assignment * modify_assignment, ast_expression * continue_condition ) { ast_loop_statement * tr = (ast_loop_statement *)ast_calloc(1,sizeof(ast_loop_statement)); ast_set_meta_info(&(tr->meta_info)); tr->type = LOOP_FOR; tr->inner_statement = inner_statement; tr->initial = initial_condition; tr->condition = continue_condition; tr->modify = modify_assignment; return tr; } /*! @brief Creates and returns a new generate loop statement. @param inner_statements - Pointer to the inner body of statements which make up the loop body. @param initial_condition - Assignement which sets up the initial condition of the iterator. @param modify_assignment - How the iterator variable changes with each loop iteration. @param continue_condition - Expression which governs whether the loop should continue or break. */ ast_loop_statement * VerilogCode::ast_new_generate_loop_statement( ast_list * inner_statements, ast_single_assignment * initial_condition, ast_single_assignment * modify_assignment, ast_expression * continue_condition ){ ast_loop_statement * tr = ast_new_for_loop_statement(NULL, initial_condition, modify_assignment, continue_condition); ast_set_meta_info(&(tr->meta_info)); tr->type = LOOP_GENERATE; tr->generate_items = inner_statements; return tr; } /*! @brief Creates and returns a while loop statement. @param inner_statement - Pointer to the inner body of statements which make upt the loop body. @param continue_condition - Expression which governs whether the loop should continue or break. */ ast_loop_statement * VerilogCode::ast_new_while_loop_statement( ast_statement * inner_statement, ast_expression * continue_condition ) { ast_loop_statement * tr = (ast_loop_statement *)ast_calloc(1,sizeof(ast_loop_statement)); ast_set_meta_info(&(tr->meta_info)); tr->type = LOOP_WHILE; tr->inner_statement = inner_statement; tr->initial = NULL; tr->condition = continue_condition; tr->modify = NULL; return tr; } /*! @brief Creates and returns a repeat loop statement. @param inner_statement - Pointer to the inner body of statements which make upt the loop body. @param continue_condition - Expression which governs whether the loop should continue or break. */ ast_loop_statement * VerilogCode::ast_new_repeat_loop_statement( ast_statement * inner_statement, ast_expression * continue_condition ) { ast_loop_statement * tr = (ast_loop_statement *)ast_calloc(1,sizeof(ast_loop_statement)); ast_set_meta_info(&(tr->meta_info)); tr->type = LOOP_REPEAT; tr->inner_statement = inner_statement; tr->initial = NULL; tr->condition = continue_condition; tr->modify = NULL; return tr; } /*! @brief Create and return a new item in a cast statement. @param conditions - The conditions on which the item is executed. @param body - Executes when any of the conditions are met. */ ast_case_item * VerilogCode::ast_new_case_item(ast_list * conditions, ast_statement * body) { ast_case_item * tr = (ast_case_item *)ast_calloc(1,sizeof(ast_case_item)); ast_set_meta_info(&(tr->meta_info)); tr->conditions = conditions; tr->body = body; tr->is_default = false; return tr; } /*! @brief Creates and returns a new case statement. @param expression - The expression evaluated to select a case. @param cases - list of possible cases. */ ast_case_statement * VerilogCode::ast_new_case_statement(ast_expression * expression, ast_list * cases, ast_case_statement_type type) { ast_case_statement * tr = (ast_case_statement *)ast_calloc(1,sizeof(ast_case_statement)); ast_set_meta_info(&(tr->meta_info)); tr->expression = expression; tr->cases = cases; tr->type = type; tr->is_function = false; if(tr->cases != NULL) { unsigned int i; for(i = 0; i < tr->cases->items; i ++) { ast_case_item * the_case = (ast_case_item *)ast_list_get(tr->cases,i); if(the_case == NULL){ break; } if(the_case->is_default == true) { // Set the default *ast_statement* tr->default_item = the_case->body; break; } } } return tr; } /*! @brief Creates and returns a new conditional statement. @param statement - what to run if the condition holds true. @param condtion - the condition on which statement is run. */ ast_conditional_statement * VerilogCode::ast_new_conditional_statement( ast_statement * statement, ast_expression * condition ) { ast_conditional_statement * tr = (ast_conditional_statement *)ast_calloc(1,sizeof(ast_conditional_statement)); ast_set_meta_info(&(tr->meta_info)); tr->statement = statement; tr->condition = condition; return tr; } /*! @brief Creates a new if-then-else-then statement. @param if_condition - the conditional statement. @param else_condition - What to do if no conditional statements are executed. This can be NULL. @details This node also supports "if then elseif then else then" statements, and uses the ast_extend_if_else function to append a new ast_conditional_statement to the end of a list of if-else conditions. Priority of exectuion is given to items added first. */ ast_if_else * VerilogCode::ast_new_if_else( ast_conditional_statement * if_condition, ast_statement * else_condition ) { ast_if_else * tr = (ast_if_else *)ast_calloc(1, sizeof(ast_if_else)); ast_set_meta_info(&(tr->meta_info)); tr->else_condition = else_condition; tr->conditional_statements = ast_list_new(); ast_list_append(tr->conditional_statements, if_condition); return tr; } /*! @brief Adds an additional conditional (ha..) to an existing if-else statement. @param conditional_statements - the existing if-else tree. @param new_statement - The new statement to add at the end of the existing if-then conditions, but before any else_condtion. */ void VerilogCode::ast_extend_if_else( ast_if_else * conditional_statements, ast_list * new_statements ) { if(new_statements != NULL) { ast_list_concat(conditional_statements->conditional_statements, new_statements); } } /*! @brief Creates and returns a new wait statement. */ ast_wait_statement * VerilogCode::ast_new_wait_statement( ast_expression * wait_for, ast_statement * statement ) { ast_wait_statement * tr = (ast_wait_statement *)ast_calloc(1, sizeof(ast_wait_statement)); ast_set_meta_info(&(tr->meta_info)); tr->expression = wait_for; tr->statement = statement; return tr; } /*! @brief Creates a new event expression node @param trigger_edge - the edge on which the trigger is activated. @param expression - the expression to monitor the waveforms of. @bug Assertion (commented out) fires in some circumstances. */ ast_event_expression * VerilogCode::ast_new_event_expression( ast_edge trigger_edge, ast_expression * expression ) { ast_event_expression * tr = (ast_event_expression *)ast_calloc(1,sizeof(ast_event_expression)); //assert(trigger_edge != EDGE_NONE); if(trigger_edge == EDGE_POS) { tr->type = EVENT_POSEDGE; tr->expression = expression; } else if (trigger_edge == EDGE_NEG) { tr->type = EVENT_NEGEDGE; tr->expression = expression; } else if (trigger_edge == EDGE_ANY) { tr->type = EVENT_EXPRESSION; tr->expression = expression; } return tr; } /*! @brief Creates a new event expression node, which is itself a sequence of sub-expressions. */ ast_event_expression * VerilogCode::ast_new_event_expression_sequence( ast_event_expression * left, ast_event_expression * right ) { ast_event_expression * tr = (ast_event_expression *)ast_calloc(1,sizeof(ast_event_expression)); tr->type = EVENT_SEQUENCE; tr->sequence = ast_list_new(); ast_list_append(tr->sequence, right); ast_list_append(tr->sequence, left ); return tr; } /*! @brief Creates and returns a new event control specifier. */ ast_event_control * VerilogCode::ast_new_event_control( ast_event_control_type type, ast_event_expression * expression ) { ast_event_control * tr = (ast_event_control *)ast_calloc(1,sizeof(ast_event_control)); ast_set_meta_info(&(tr->meta_info)); if(type == EVENT_CTRL_ANY) assert(expression == NULL); tr->type = type; tr->expression = expression; return tr; } /*! @brief creates and returns a new delay control statement. */ ast_delay_ctrl * VerilogCode::ast_new_delay_ctrl_value(ast_delay_value * value) { ast_delay_ctrl * tr = (ast_delay_ctrl *)ast_calloc(1,sizeof(ast_event_control)); ast_set_meta_info(&(tr->meta_info)); tr->type = DELAY_CTRL_VALUE; tr->value = value; return tr; } /*! @brief creates and returns a new delay control statement. */ ast_delay_ctrl * VerilogCode::ast_new_delay_ctrl_mintypmax( ast_expression * mintypmax ) { ast_delay_ctrl * tr = (ast_delay_ctrl *)ast_calloc(1,sizeof(ast_event_control)); ast_set_meta_info(&(tr->meta_info)); tr->type = DELAY_CTRL_MINTYPMAX; tr->mintypmax = mintypmax; return tr; } /*! @brief Creates and returns a new timing control statement node. */ ast_timing_control_statement * VerilogCode::ast_new_timing_control_statement_delay( ast_timing_control_statement_type type, ast_statement * statement, ast_delay_ctrl * delay_ctrl ) { ast_timing_control_statement * tr = (ast_timing_control_statement *)ast_calloc(1,sizeof(ast_timing_control_statement)); ast_set_meta_info(&(tr->meta_info)); assert(type == TIMING_CTRL_DELAY_CONTROL); tr->type = type; tr->delay = delay_ctrl; tr->statement = statement; tr->repeat = NULL; return tr; } /*! @brief Creates and returns a new timing control statement node. */ ast_timing_control_statement * VerilogCode::ast_new_timing_control_statement_event( ast_timing_control_statement_type type, ast_expression * repeat, ast_statement * statement, ast_event_control * event_ctrl ) { ast_timing_control_statement * tr = (ast_timing_control_statement *)ast_calloc(1,sizeof(ast_timing_control_statement)); ast_set_meta_info(&(tr->meta_info)); assert(type == TIMING_CTRL_EVENT_CONTROL || type == TIMING_CTRL_EVENT_CONTROL_REPEAT); tr->type = type; tr->event_ctrl = event_ctrl; tr->statement = statement; tr->repeat = repeat; return tr; } /*! @brief Creates and returns a new assignment. */ ast_single_assignment * VerilogCode::ast_new_single_assignment( ast_lvalue * lval, ast_expression * expression ) { ast_single_assignment * tr = (ast_single_assignment *)ast_calloc(1,sizeof(ast_single_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->lval = lval; tr->expression = expression; return tr; } /*! @brief Creates a new hybrid assignment of the specified type. */ ast_assignment * VerilogCode::ast_new_hybrid_assignment( ast_hybrid_assignment_type type, ast_single_assignment * assignment ) { ast_assignment * tr = (ast_assignment *)ast_calloc(1,sizeof(ast_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->type = ASSIGNMENT_HYBRID; tr->hybrid = (ast_hybrid_assignment *)ast_calloc(1,sizeof(ast_hybrid_assignment)); tr->hybrid->type = type; tr->hybrid->assignment = assignment; return tr; } /*! @brief Creates a new hybrid assignment of the specified type. */ ast_assignment * VerilogCode::ast_new_hybrid_lval_assignment( ast_hybrid_assignment_type type, ast_lvalue *lval ) { ast_assignment * tr = (ast_assignment *)ast_calloc(1,sizeof(ast_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->type = ASSIGNMENT_HYBRID; tr->hybrid = (ast_hybrid_assignment *)ast_calloc(1,sizeof(ast_hybrid_assignment)); tr->hybrid->type = type; tr->hybrid->lval = lval; return tr; } /*! @brief Creates and returns a new blocking procedural assignment object. */ ast_assignment * VerilogCode::ast_new_blocking_assignment( ast_lvalue * lval, ast_expression * expression, ast_timing_control_statement* delay_or_event ) { ast_assignment * tr = (ast_assignment *)ast_calloc(1,sizeof(ast_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->type = ASSIGNMENT_BLOCKING; tr->procedural = (ast_procedural_assignment *)ast_calloc(1,sizeof(ast_procedural_assignment)); tr->procedural->lval = lval; tr->procedural->expression = expression; tr->procedural->delay_or_event = delay_or_event; return tr; } /*! @brief Creates and returns a new nonblocking procedural assignment object. */ ast_assignment * VerilogCode::ast_new_nonblocking_assignment( ast_lvalue * lval, ast_expression * expression, ast_timing_control_statement * delay_or_event ) { ast_assignment * tr = (ast_assignment *)ast_calloc(1,sizeof(ast_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->type = ASSIGNMENT_NONBLOCKING; tr->procedural = (ast_procedural_assignment *)ast_calloc(1,sizeof(ast_procedural_assignment)); tr->procedural->lval = lval; tr->procedural->expression = expression; tr->procedural->delay_or_event = delay_or_event; return tr; } /*! @brief Creates and returns a new continuous assignment object. */ ast_assignment * VerilogCode::ast_new_continuous_assignment( ast_list * assignments, ast_drive_strength * strength, ast_delay3 * delay ) { ast_continuous_assignment * trc = (ast_continuous_assignment *)ast_calloc(1, sizeof(ast_continuous_assignment)); trc->assignments = assignments; unsigned int i; for(i = 0; i < assignments->items; i++) { ast_single_assignment * item = (ast_single_assignment *)ast_list_get(assignments,i); item->drive_strength = strength; item->delay = delay; } ast_assignment * tr = (ast_assignment *)ast_calloc(1, sizeof(ast_assignment)); ast_set_meta_info(&(tr->meta_info)); tr->type = ASSIGNMENT_CONTINUOUS; tr->continuous = trc; return tr; } /*! @brief Creates and returns a new statement block of the specified type */ ast_statement_block * VerilogCode::ast_new_statement_block( ast_block_type type, ast_identifier block_identifier, ast_list * declarations, ast_list * statements ) { ast_statement_block * tr = (ast_statement_block *)ast_calloc(1,sizeof(ast_statement_block)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->block_identifier = block_identifier; tr->declarations = declarations; tr->statements = statements; return tr; } //! Creates and returns a pointer to a new disable statement. ast_disable_statement * VerilogCode::ast_new_disable_statement(ast_identifier id) { ast_disable_statement * tr = (ast_disable_statement *)ast_calloc(1, sizeof(ast_disable_statement)); ast_set_meta_info(&(tr->meta_info)); tr->id = id; return tr; } /*! @brief Creates a new AST statement and returns it. @note Requires the data field of the union to be filled out manually. */ ast_statement * VerilogCode::ast_new_statement( ast_node_attributes * attr, bool is_function_statement, void * data, ast_statement_type type ) { ast_statement * tr = (ast_statement *)ast_calloc(1,sizeof(ast_statement)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->is_function_statement = is_function_statement; tr->is_generate_statement = false; tr->data = data; tr->attributes = attr; return tr; } /*! @brief Creates a new UDP port AST node @details @returns A pointer to the new port */ ast_udp_port * VerilogCode::ast_new_udp_port( ast_port_direction direction, ast_identifier identifier, ast_node_attributes * attributes, bool reg, ast_expression * default_value ) { ast_udp_port * tr = (ast_udp_port *)ast_calloc(1,sizeof(ast_udp_port)); ast_set_meta_info(&(tr->meta_info)); tr->direction = direction; assert(direction != PORT_INPUT); tr->identifier = identifier; tr->attributes = attributes; tr->reg = reg; tr->default_value = default_value; return tr; } /*! @brief Creates a new UDP port AST node @details @returns A pointer to the new port */ ast_udp_port * VerilogCode::ast_new_udp_input_port( ast_list * identifiers, ast_node_attributes * attributes ) { ast_udp_port * tr = (ast_udp_port *)ast_calloc(1,sizeof(ast_udp_port)); ast_set_meta_info(&(tr->meta_info)); tr->direction = PORT_INPUT; tr->identifiers = identifiers; tr->attributes = attributes; tr->reg = false; tr->default_value = NULL; return tr; } /*! @brief Creates a new UDP declaration node @details @returns A pointer to the new node. */ ast_udp_declaration * VerilogCode::ast_new_udp_declaration( ast_node_attributes * attributes, ast_identifier identifier, ast_list * ports, ast_udp_body * body ) { ast_udp_declaration * tr = (ast_udp_declaration *)ast_calloc(1,sizeof(ast_udp_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = attributes; tr->identifier = identifier; tr->ports = ports; tr->body_entries = body->entries; tr->initial = body->initial; tr->body_type = body->body_type; return tr; } /*! @brief Creates a new instance of a UDP. @details @returns A pointer to the new instance. */ ast_udp_instance * VerilogCode::ast_new_udp_instance( ast_identifier identifier, ast_range * range, ast_lvalue * output, ast_list * inputs ){ ast_udp_instance * tr = (ast_udp_instance *)ast_calloc(1,sizeof(ast_udp_instance)); ast_set_meta_info(&(tr->meta_info)); tr->identifier = identifier; tr->range = range; tr->output = output; tr->inputs = inputs; return tr; } /*! @brief Creates a new list of UDP instances with shared properties. @details @returns A pointer to the new list. */ ast_udp_instantiation * VerilogCode::ast_new_udp_instantiation( ast_list * instances, ast_identifier identifier, ast_drive_strength * drive_strength, ast_delay2 * delay ){ ast_udp_instantiation * tr = (ast_udp_instantiation *)ast_calloc(1,sizeof(ast_udp_instantiation)); ast_set_meta_info(&(tr->meta_info)); tr->instances = instances; tr->identifier = identifier; tr->drive_strength= drive_strength; tr->delay = delay; return tr; } //! Creates a new initial statement node. ast_udp_initial_statement * VerilogCode::ast_new_udp_initial_statement( ast_identifier output_port, ast_number * initial_value ){ ast_udp_initial_statement *tr = (ast_udp_initial_statement *)ast_calloc(1,sizeof(ast_udp_initial_statement)); tr->output_port = output_port; tr->initial_value = initial_value; return tr; } //! Creates and returns a new sequential UDP body representation. ast_udp_body * VerilogCode::ast_new_udp_sequential_body( ast_udp_initial_statement * initial_statement, ast_list * sequential_entries ){ ast_udp_body * tr = (ast_udp_body *)ast_calloc(1,sizeof(ast_udp_body)); ast_set_meta_info(&(tr->meta_info)); tr->body_type = UDP_BODY_SEQUENTIAL; tr->initial = initial_statement; tr->entries = sequential_entries; return tr; } //! Creates and returns a new combinatorial UDP body representation. ast_udp_body * VerilogCode::ast_new_udp_combinatoral_body( ast_list * combinatorial_entries ){ ast_udp_body * tr = (ast_udp_body *)ast_calloc(1,sizeof(ast_udp_body)); ast_set_meta_info(&(tr->meta_info)); tr->body_type = UDP_BODY_COMBINATORIAL; tr->entries = combinatorial_entries; return tr; } //! Creates a new combinatorial entry for a UDP node. ast_udp_combinatorial_entry * VerilogCode::ast_new_udp_combinatoral_entry( ast_list * input_levels, ast_udp_next_state output_symbol ){ ast_udp_combinatorial_entry * tr = (ast_udp_combinatorial_entry *)ast_calloc(1,sizeof(ast_udp_combinatorial_entry)); ast_set_meta_info(&(tr->meta_info)); tr->input_levels = input_levels; tr->output_symbol = output_symbol; return tr; } //! Creates a new sequntial body entry for a UDP node. ast_udp_sequential_entry * VerilogCode::ast_new_udp_sequential_entry( ast_udp_seqential_entry_prefix prefix_type, ast_list * levels_or_edges, ast_level_symbol current_state, ast_udp_next_state output ){ ast_udp_sequential_entry * tr = (ast_udp_sequential_entry *)ast_calloc(1, sizeof(ast_udp_sequential_entry)); ast_set_meta_info(&(tr->meta_info)); tr->entry_prefix = prefix_type; if(prefix_type == PREFIX_EDGES) tr->edges = levels_or_edges; else tr->levels = levels_or_edges; tr->current_state = current_state; tr->output = output; return tr; } /*! @brief Creates and returns a new item which exists inside a generate statement. @details Wraps around ast_new_statement and sets appropriate internal flags to represent this as a statment in a generate block. @note the void* type of the construct parameter allows for a single constructor function rather than one per member of the union inside the ast_generate_item structure. */ ast_statement * VerilogCode::ast_new_generate_item( ast_statement_type type, void * construct ){ ast_statement * tr = ast_new_statement(NULL, false, construct,type); ast_set_meta_info(&(tr->meta_info)); tr->is_generate_statement = true; return tr; } //! Creates and returns a new block of generate items. ast_generate_block * VerilogCode::ast_new_generate_block( ast_identifier identifier, ast_list * generate_items ){ ast_generate_block * tr = (ast_generate_block *)ast_calloc(1,sizeof(ast_generate_block)); ast_set_meta_info(&(tr->meta_info)); tr->generate_items = generate_items; tr->identifier = identifier; return tr; } /*! @brief Creates and returns a new set of module instances with shared parameters. */ ast_module_instantiation * VerilogCode::ast_new_module_instantiation( ast_identifier module_identifer, ast_list * module_parameters, ast_list * module_instances ){ ast_module_instantiation * tr = (ast_module_instantiation *)ast_calloc(1,sizeof(ast_module_instantiation)); ast_set_meta_info(&(tr->meta_info)); tr->resolved = false; tr->module_identifer = module_identifer; tr->module_parameters = module_parameters; tr->module_instances = module_instances; return tr; } /*! @brief Creates and returns a new instance of a module with a given identifer and set of port connections. */ ast_module_instance * VerilogCode::ast_new_module_instance( ast_identifier instance_identifier, ast_list * port_connections ){ ast_module_instance * tr = (ast_module_instance *)ast_calloc(1,sizeof(ast_module_instance)); ast_set_meta_info(&(tr->meta_info)); tr->instance_identifier = instance_identifier; tr->port_connections = port_connections; return tr; } /*! @brief Creates and returns a new port connection representation. @param port_name - The port being assigned to. @param expression - The thing inside the module the port connects to. */ ast_port_connection * VerilogCode::ast_new_named_port_connection( ast_identifier port_name, ast_expression * expression ){ ast_port_connection * tr = (ast_port_connection *)ast_calloc(1,sizeof(ast_port_connection)); ast_set_meta_info(&(tr->meta_info)); tr->port_name = port_name; tr->expression = expression; return tr; } //! Instances a new switch type with a delay3. ast_switch_gate * VerilogCode::ast_new_switch_gate_d3( ast_switchtype type, ast_delay3 * delay ){ assert(type != SWITCH_TRAN && type != SWITCH_RTRAN); ast_switch_gate * tr = (ast_switch_gate *)ast_calloc(1,sizeof(ast_switch_gate)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->delay3 = delay; return tr; } //! Instances a new switch type with a delay2. ast_switch_gate * VerilogCode::ast_new_switch_gate_d2( ast_switchtype type, ast_delay2 * delay ){ assert(type == SWITCH_TRAN || type == SWITCH_RTRAN); ast_switch_gate * tr = (ast_switch_gate *)ast_calloc(1,sizeof(ast_switch_gate)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->delay2 = delay; return tr; } //! Creates and returns a new structure describing primitive net strength. ast_primitive_pull_strength * VerilogCode::ast_new_primitive_pull_strength( ast_pull_direction direction, ast_primitive_strength strength_1, ast_primitive_strength strength_0 ){ ast_primitive_pull_strength * tr = (ast_primitive_pull_strength *)ast_calloc(1,sizeof(ast_primitive_pull_strength)); ast_set_meta_info(&(tr->meta_info)); tr->direction = direction; tr->strength_1 = strength_1; tr->strength_0 = strength_0; return tr; } /*! @brief Describes a single pull gate instance.*/ ast_pull_gate_instance * VerilogCode::ast_new_pull_gate_instance( ast_identifier name, ast_lvalue * output_terminal ){ ast_pull_gate_instance * tr = (ast_pull_gate_instance *)ast_calloc(1,sizeof(ast_pull_gate_instance)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->output_terminal = output_terminal; return tr; } /*! @brief A single pass transistor instance.*/ ast_pass_switch_instance * VerilogCode::ast_new_pass_switch_instance( ast_identifier name, ast_lvalue * terminal_1, ast_lvalue * terminal_2 ){ ast_pass_switch_instance * tr = (ast_pass_switch_instance *)ast_calloc(1,sizeof(ast_pass_switch_instance)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->terminal_1 = terminal_1; tr->terminal_2 = terminal_2; return tr; } /*! @brief An N-input gate instance. e.g. 3-to-1 NAND.*/ ast_n_input_gate_instance * VerilogCode::ast_new_n_input_gate_instance( ast_identifier name, ast_list * input_terminals, ast_lvalue * output_terminal ){ ast_n_input_gate_instance * tr = (ast_n_input_gate_instance *)ast_calloc(1,sizeof(ast_n_input_gate_instance)); tr->name = name; tr->input_terminals = input_terminals; tr->output_terminal = output_terminal; return tr; } /*! @brief A single Enable gate instance.*/ ast_enable_gate_instance * VerilogCode::ast_new_enable_gate_instance( ast_identifier name, ast_lvalue * output_terminal, ast_expression * enable_terminal, ast_expression * input_terminal ){ ast_enable_gate_instance * tr = (ast_enable_gate_instance *)ast_calloc(1,sizeof(ast_enable_gate_instance)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->output_terminal = output_terminal; tr->enable_terminal = enable_terminal; tr->input_terminal = input_terminal; return tr; } /*! @brief A single MOS switch (transistor) instance.*/ ast_mos_switch_instance * VerilogCode::ast_new_mos_switch_instance( ast_identifier name, ast_lvalue * output_terminal, ast_expression * enable_terminal, ast_expression * input_terminal ){ ast_mos_switch_instance * tr = (ast_mos_switch_instance *)ast_calloc(1,sizeof(ast_mos_switch_instance)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->output_terminal = output_terminal; tr->enable_terminal = enable_terminal; tr->input_terminal = input_terminal; return tr; } /*! @brief A single CMOS switch (transistor) instance.*/ ast_cmos_switch_instance * VerilogCode::ast_new_cmos_switch_instance( ast_identifier name, ast_lvalue * output_terminal, ast_expression * ncontrol_terminal, ast_expression * pcontrol_terminal, ast_expression * input_terminal ){ ast_cmos_switch_instance * tr = (ast_cmos_switch_instance *)ast_calloc(1,sizeof(ast_cmos_switch_instance)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->output_terminal = output_terminal; tr->ncontrol_terminal = ncontrol_terminal; tr->pcontrol_terminal = pcontrol_terminal; tr->input_terminal = input_terminal; return tr; } /*! @brief Creates and returns a new pass enable switch instance. */ ast_pass_enable_switch * VerilogCode::ast_new_pass_enable_switch( ast_identifier name, ast_lvalue * terminal_1, ast_lvalue * terminal_2, ast_expression * enable ){ ast_pass_enable_switch * tr = (ast_pass_enable_switch *)ast_calloc(1,sizeof(ast_pass_enable_switch)); ast_set_meta_info(&(tr->meta_info)); tr->name = name; tr->terminal_1 = terminal_1; tr->terminal_2 = terminal_2; tr->enable = enable; return tr; } /*! @brief Creates and returns a collection of pass enable switches. */ ast_pass_enable_switches * VerilogCode::ast_new_pass_enable_switches( ast_pass_enable_switchtype type, ast_delay2 * delay, ast_list * switches ){ ast_pass_enable_switches * tr = (ast_pass_enable_switches *)ast_calloc(1,sizeof(ast_pass_enable_switches)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->delay = delay; tr->switches = switches; return tr; } /*! @brief Creates collection of n-input gates with the same type and properties. */ ast_n_input_gate_instances * VerilogCode::ast_new_n_input_gate_instances( ast_gatetype_n_input type, ast_delay3 * delay, ast_drive_strength * drive_strength, ast_list * instances ){ ast_n_input_gate_instances * tr = (ast_n_input_gate_instances *)ast_calloc(1,sizeof(ast_n_input_gate_instances)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->delay = delay; tr->drive_strength = drive_strength; tr->instances = instances; return tr; } //! Creates collection of enable gates with the same type and properties. ast_enable_gate_instances * VerilogCode::ast_new_enable_gate_instances( ast_gatetype_n_input type_e, ast_delay3 * delay, ast_drive_strength * drive_strength, ast_list * instances ){ ast_enable_gate_instances * tr = (ast_enable_gate_instances *)ast_calloc(1,sizeof(ast_enable_gate_instances)); ast_set_meta_info(&(tr->meta_info)); tr->type = (ast_enable_gatetype)type_e; tr->delay = delay; tr->drive_strength = drive_strength; tr->instances = instances; return tr; } /*! @brief Creates and returns a new n_output gate instance. @see ast_n_output_gate_instances */ ast_n_output_gate_instance * VerilogCode::ast_new_n_output_gate_instance( ast_identifier name, ast_list * outputs, ast_expression * input ){ ast_n_output_gate_instance * tr = (ast_n_output_gate_instance *)ast_calloc(1,sizeof(ast_n_output_gate_instance)); tr->name = name; tr->outputs = outputs; tr->input = input; return tr; } /*! @brief Creates and returns a set of n_output gates with the same properties. */ ast_n_output_gate_instances * VerilogCode::ast_new_n_output_gate_instances( ast_n_output_gatetype type, ast_delay2 * delay, ast_drive_strength * drive_strength, ast_list * instances ){ ast_n_output_gate_instances * tr = (ast_n_output_gate_instances *)ast_calloc(1,sizeof(ast_n_output_gate_instances)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->delay = delay; tr->drive_strength = drive_strength; tr->instances = instances; return tr; } /*! @brief creat and return a new collection of AST switches. */ ast_switches * VerilogCode::ast_new_switches(ast_switch_gate * type, ast_list * switches) { ast_switches * tr = (ast_switches *)ast_calloc(1,sizeof(ast_switches)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->switches = switches; return tr; } //! Create and return a new pull strength indicator for 1 and 0. ast_pull_strength * VerilogCode::ast_new_pull_stregth( ast_primitive_strength strength_1, ast_primitive_strength strength_2 ){ ast_pull_strength * tr = (ast_pull_strength *)ast_calloc(1,sizeof(ast_pull_strength)); ast_set_meta_info(&(tr->meta_info)); tr->strength_1 = strength_1; tr->strength_2 = strength_2; return tr; } /*! @brief Creates and returns a new gate instantiation descriptor. @details Expects the data fields to be filled out manually after the structure is returned. */ ast_gate_instantiation * VerilogCode::ast_new_gate_instantiation(ast_gate_type type) { ast_gate_instantiation * tr = (ast_gate_instantiation *)ast_calloc(1,sizeof(ast_gate_instantiation)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; return tr; } /*! @brief creates and returns a new set of parameter declarations of the same type @param [in] assignments - The list of individual assignments. @param [in] signed_values - are the bit vectors signed? @param [in] range - Bit range @param [in] type - type of the parameters. */ ast_parameter_declarations * VerilogCode::ast_new_parameter_declarations( ast_list * assignments, bool signed_values, bool local, ast_range * range, ast_parameter_type type ){ ast_parameter_declarations * tr = (ast_parameter_declarations *)ast_calloc(1,sizeof(ast_parameter_declarations)); ast_set_meta_info(&(tr->meta_info)); tr->assignments = assignments; tr->signed_values = signed_values; tr->range = range; tr->type = type; tr->local = local; if(type != PARAM_GENERIC){ tr->range = NULL; tr->signed_values = false; } return tr; } /*! @brief Creates and returns a new port declaration representation. */ ast_port_declaration * VerilogCode::ast_new_port_declaration( ast_port_direction direction, //!< [in] Input / output / inout etc. ast_net_type net_type, //!< [in] Wire/reg etc bool net_signed, //!< [in] Signed value? bool is_reg, //!< [in] Is explicitly a "reg" bool is_variable, //!< [in] Variable or net? ast_range * range, //!< [in] Bus width. ast_list * port_names //!< [in] The names of the ports. ){ ast_port_declaration * tr = (ast_port_declaration *)ast_calloc(1,sizeof(ast_port_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->direction = direction ; tr->net_type = net_type ; tr->net_signed = net_signed ; tr->is_reg = is_reg ; tr->is_variable = is_variable; tr->range = range ; tr->port_names = port_names ; return tr; } /*! @brief Creates and returns a node to represent the declaration of a new module item construct. @details Because of the complex nature of the grammar for these declarations, (bourne from the number of optional modifiers) no single constructor function is provided. Rather, one can create a new type declaration of a known type, but must otherwise fill out the data members as they go along. All pointer members are initialised to NULL, and all boolean members will initially be false. */ ast_type_declaration * VerilogCode::ast_new_type_declaration(ast_declaration_type type) { ast_type_declaration * tr = (ast_type_declaration *)ast_calloc(1,sizeof(ast_type_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->identifiers = NULL; tr->delay = NULL; tr->drive_strength = NULL; tr->charge_strength = CHARGE_DEFAULT; tr->range = NULL; tr->vectored = false; tr->scalared = false; tr->is_signed = false; tr->net_type = NET_TYPE_NONE; return tr; } /*! @brief Creates a new net declaration object. @details Turns a generic "type declaration" object into a net_declration object and discards un-needed member fields. @returns A set of ast_net_declaration types as a list, one for each identifer in the original type declaration object. */ ast_list * VerilogCode::ast_new_net_declaration( ast_type_declaration * type_dec ){ assert(type_dec != NULL); assert(type_dec->identifiers != NULL); ast_list * tr = ast_list_new(); unsigned int i = 0; for (i = 0; i < type_dec->identifiers->items; i ++) { ast_net_declaration * toadd = (ast_net_declaration *)ast_calloc(1,sizeof(ast_net_declaration)); toadd->meta_info = type_dec->meta_info; toadd->identifier = (ast_identifier)ast_list_get(type_dec->identifiers, i); toadd->type = type_dec->net_type; toadd->delay = type_dec->delay; toadd->drive = type_dec->drive_strength; toadd->range = type_dec->range; toadd->vectored = type_dec->vectored; toadd->scalared = type_dec->scalared; toadd->is_signed = type_dec->is_signed; toadd->value = NULL; ast_list_append(tr,toadd); } return tr; } /*! @brief Creates a new reg declaration object. @details Turns a generic "type declaration" object into a reg_declration object and discards un-needed member fields. @returns A set of ast_reg_declaration types as a list, one for each identifer in the original type declaration object. */ ast_list * VerilogCode::ast_new_reg_declaration( ast_type_declaration * type_dec ){ ast_list * tr = ast_list_new(); unsigned int i = 0; for (i = 0; i < type_dec->identifiers->items; i ++) { ast_reg_declaration * toadd = (ast_reg_declaration *)ast_calloc(1,sizeof(ast_reg_declaration)); toadd->meta_info = type_dec->meta_info; toadd->identifier = (ast_identifier)ast_list_get(type_dec->identifiers, i); toadd->range = type_dec->range; toadd->is_signed = type_dec->is_signed; toadd->value = NULL; ast_list_append(tr,toadd); } return tr; } /*! @brief Creates a new variable declaration object. @details Turns a generic "var declaration" object into a var_declration object and discards un-needed member fields. @returns A set of ast_var_declaration types as a list, one for each identifer in the original type declaration object. */ ast_list * VerilogCode::ast_new_var_declaration( ast_type_declaration * type_dec ){ ast_list * tr = ast_list_new(); unsigned int i = 0; for (i = 0; i < type_dec->identifiers->items; i ++) { ast_var_declaration * toadd = (ast_var_declaration *)ast_calloc(1,sizeof(ast_var_declaration)); toadd->meta_info = type_dec->meta_info; toadd->identifier = (ast_identifier)ast_list_get(type_dec->identifiers,i); toadd->type = type_dec->type; ast_list_append(tr,toadd); } return tr; } /*! @brief Create a new delay value. */ ast_delay_value * VerilogCode::ast_new_delay_value( ast_delay_value_type type, void * data ){ ast_delay_value * tr = (ast_delay_value *)ast_calloc(1,sizeof(ast_delay_value)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->data = data; return tr; } /*! @brief Create a new delay3 instance. */ ast_delay3 * VerilogCode::ast_new_delay3( ast_delay_value * min, ast_delay_value * avg, ast_delay_value * max ){ ast_delay3 * tr = (ast_delay3 *)ast_calloc(1,sizeof(ast_delay3)); ast_set_meta_info(&(tr->meta_info)); tr->min = min; tr->avg = avg; tr->max = max; return tr; } /*! @brief Create a new delay2 instance. */ ast_delay2 * VerilogCode::ast_new_delay2( ast_delay_value * min, ast_delay_value * max ){ ast_delay2 * tr = (ast_delay2 *)ast_calloc(1,sizeof(ast_delay2)); ast_set_meta_info(&(tr->meta_info)); tr->min = min; tr->max = max; return tr; } /*! @brief Creates and returns a new pulse control data structure. */ ast_pulse_control_specparam * VerilogCode::ast_new_pulse_control_specparam( ast_expression * reject_limit, ast_expression * error_limit ){ ast_pulse_control_specparam * tr = (ast_pulse_control_specparam *)ast_calloc(1,sizeof(ast_pulse_control_specparam)); tr->reject_limit = reject_limit; tr->error_limit = error_limit; return tr; } /*! @brief Creates and returns a new range or dimension representation node. */ ast_range * VerilogCode::ast_new_range( ast_expression * upper, ast_expression * lower ){ ast_range * tr = (ast_range *)ast_calloc(1,sizeof(ast_range)); tr->upper = upper; tr->lower = lower; return tr; } /*! @brief Creates and returns a new object storing either a range or a type. @note Expects the union member of ast_range_or_type to be set manually. @param [in] is_range - true if the contained object will be a range instance, else false. */ ast_range_or_type * VerilogCode::ast_new_range_or_type(bool is_range) { ast_range_or_type * tr = (ast_range_or_type *)ast_calloc(1,sizeof(ast_range_or_type)); ast_set_meta_info(&(tr->meta_info)); tr->is_range = is_range; return tr; } /*! @brief Creates and returns a function declaration node. */ ast_function_declaration * VerilogCode::ast_new_function_declaration( bool automatic, bool is_signed, bool function_or_block, ast_range_or_type *rot, ast_identifier identifier, ast_list *item_declarations, ast_statement *statements ){ ast_function_declaration * tr = (ast_function_declaration *)ast_calloc(1,sizeof(ast_function_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->automatic = automatic; tr->is_signed = is_signed; tr->function_or_block = function_or_block; tr->rot = rot; tr->identifier = identifier; tr->item_declarations = item_declarations; tr->statements = statements; return tr; } /*! @brief Creates and returns a new function item declaration. @note All member fields must be filled out manaully. THis function just ensures the memory is allocated properly. */ ast_function_item_declaration * VerilogCode::ast_new_function_item_declaration(){ return (ast_function_item_declaration *)ast_calloc(1,sizeof(ast_function_item_declaration)); } /* @brief Creates and returns a new representation of a task or function argument. */ ast_task_port * VerilogCode::ast_new_task_port( ast_port_direction direction, bool reg, bool is_signed, ast_range * range, ast_task_port_type type, ast_list * identifiers //!< The list of port names. ){ ast_task_port * tr = (ast_task_port *)ast_calloc(1,sizeof(ast_task_port)); ast_set_meta_info(&(tr->meta_info)); tr->direction = direction; tr->reg = reg; tr->is_signed = is_signed; tr->range = range; tr->type = type; tr->identifiers = identifiers; //!< The list of port names. return tr; } /*! @brief Creates and returns a new task declaration statement. */ ast_task_declaration * VerilogCode::ast_new_task_declaration( bool automatic, ast_identifier identifier, ast_list * ports, ast_list * declarations, ast_statement * statements ){ ast_task_declaration * tr = (ast_task_declaration *)ast_calloc(1,sizeof(ast_task_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->automatic = automatic; tr->identifier = identifier; tr->declarations = declarations; tr->ports = ports; tr->statements = statements; return tr; } /*! @brief Creates and returns a new block register declaration descriptor. */ ast_block_reg_declaration * VerilogCode::ast_new_block_reg_declaration( bool is_signed, ast_range * range, ast_list * identifiers ){ ast_block_reg_declaration * tr = (ast_block_reg_declaration *)ast_calloc(1,sizeof(ast_block_reg_declaration)); tr->is_signed = is_signed; tr->range = range; tr->identifiers = identifiers; return tr; } /*! @brief Creates and returns a new block item declaration of the specified type. @note Expects the relevant union member to be set manually. */ ast_block_item_declaration * VerilogCode::ast_new_block_item_declaration( ast_block_item_declaration_type type, ast_node_attributes * attributes ){ ast_block_item_declaration * tr = (ast_block_item_declaration *)ast_calloc(1,sizeof(ast_block_item_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->attributes = attributes; return tr; } /*! @brief Creates and returns a new module item descriptor. @note Expects the relevant union member to be set based on the type manually. */ ast_module_item * VerilogCode::ast_new_module_item( ast_node_attributes * attributes, ast_module_item_type type ){ ast_module_item * tr = (ast_module_item *)ast_calloc(1,sizeof(ast_module_item)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; tr->attributes = attributes; return tr; } /*! @brief Takes a body statement (type = STM_BLK) and splits it into it's event trigger and statements. */ ast_statement_block * VerilogCode::ast_extract_statement_block( ast_statement_type type, ast_statement * body ){ //printf("Reforming block from line %d of %s\n", body->meta_info.line,body->meta_info.file); if(body->type == STM_BLOCK) { // Extract the statement block, and return that. There are no timing // control statements, so just set the type and return it. ast_statement_block * block = body->block; block->trigger = NULL; block->type = (ast_block_type)type; return block; } else if(body->type == STM_TIMING_CONTROL) { // The trigger is the main parent the the block, since the grammar // dictates any subsequent statements (including begin/end blocks) are // childrent of the timing control statement. // Here we essentially switch the trigger/block parent/child // relationship to create one object with all of the appropriate // information immediately available. ast_timing_control_statement * trigger = body ->timing_control; ast_statement * stm = trigger->statement; //printf("\t Refactoring timing statement. Type: %d\n", stm->type); if(stm ->type == STM_BLOCK) { ast_statement_block * block = stm->block; block->trigger = trigger; block->type = (ast_block_type)type; return block; } else { // Corner case where the child of the timing control statement // is a single statement on it's own, not surrounded by begin..end ast_list * stm_list = ast_list_new(); ast_list_append(stm_list, stm); ast_statement_block * tr = (ast_statement_block *)ast_new_statement_block( (ast_block_type)STM_BLOCK, ast_new_identifier("Unnamed block", body->meta_info.line), ast_list_new(), // Empty list, no declarations are made. stm_list ); return tr; } } else { // Nothing is as expected, so wrap the supplied statement in a block // object of the desired type. This is usually when you get code // like: `initial do_setup_task();` ast_list * stm_list = ast_list_new(); ast_list_append(stm_list, body); ast_statement_block * tr = (ast_statement_block *)ast_new_statement_block( (ast_block_type)STM_BLOCK, ast_new_identifier("Unnamed block", body->meta_info.line), ast_list_new(), // Empty list, no declarations are made. stm_list ); return tr; } } /*! @brief Creates a new module instantiation. @param [in] ports - This should be a list of ast_port_declaration if we are using the new style of port declaration, or NULL if the port declarations are contained within the module items list. */ ast_module_declaration * VerilogCode::ast_new_module_declaration( ast_node_attributes * attributes, ast_identifier identifier, ast_list * parameters, ast_list * ports, ast_list * constructs ){ ast_module_declaration * tr = (ast_module_declaration *)ast_calloc(1,sizeof(ast_module_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->attributes = attributes; tr->identifier = identifier; tr->module_parameters = parameters; // Are we using the old or new style of port declaration? if(ports == NULL) { // Old style - search in internal module items for ports. tr->module_ports = ast_list_new(); } else { // New style, just use the passed ports. tr->module_ports = ports; } tr->always_blocks = ast_list_new(); tr->continuous_assignments = ast_list_new(); tr->event_declarations = ast_list_new(); tr->function_declarations = ast_list_new(); tr->gate_instantiations = ast_list_new(); tr->genvar_declarations = ast_list_new(); tr->generate_blocks = ast_list_new(); tr->initial_blocks = ast_list_new(); tr->integer_declarations = ast_list_new(); tr->local_parameters = ast_list_new(); tr->module_instantiations = ast_list_new(); tr->net_declarations = ast_list_new(); tr->parameter_overrides = ast_list_new(); tr->real_declarations = ast_list_new(); tr->realtime_declarations = ast_list_new(); tr->reg_declarations = ast_list_new(); tr->specify_blocks = ast_list_new(); tr->specparams = ast_list_new(); tr->task_declarations = ast_list_new(); tr->time_declarations = ast_list_new(); tr->udp_instantiations = ast_list_new(); unsigned int i; for(i = 0; i < constructs->items; i++) { ast_module_item * construct = (ast_module_item *)ast_list_get(constructs, i); if(construct->type == MOD_ITEM_PORT_DECLARATION && ports == NULL){ // Only accept ports declared this way iff the ports argument to // this function is NULL, signifying the old style of port // declaration. ast_list_append(tr->module_ports, construct->port_declaration); } else if(construct->type == MOD_ITEM_GENERATED_INSTANTIATION){ ast_list_append(tr->generate_blocks, construct->generated_instantiation); } else if(construct->type == MOD_ITEM_PARAMETER_DECLARATION) { ast_list_append(tr->module_parameters, construct->parameter_declaration); } else if(construct->type == MOD_ITEM_SPECIFY_BLOCK){ ast_list_append(tr->specify_blocks, construct->specify_block); } else if(construct->type == MOD_ITEM_SPECPARAM_DECLARATION){ ast_list_append(tr->specparams, construct->specparam_declaration); } else if(construct->type == MOD_ITEM_PARAMETER_OVERRIDE){ ast_list_append(tr->parameter_overrides, construct->parameter_override); } else if(construct->type == MOD_ITEM_CONTINOUS_ASSIGNMENT){ ast_list_append(tr->continuous_assignments, construct->continuous_assignment); } else if(construct->type == MOD_ITEM_GATE_INSTANTIATION){ ast_list_append(tr->gate_instantiations, construct->gate_instantiation); } else if(construct->type == MOD_ITEM_UDP_INSTANTIATION){ ast_list_append(tr->udp_instantiations, construct->udp_instantiation); } else if(construct->type == MOD_ITEM_MODULE_INSTANTIATION){ ast_list_append(tr->module_instantiations, construct->module_instantiation); } else if(construct->type == MOD_ITEM_INITIAL_CONSTRUCT){ ast_statement_block * toadd = ast_extract_statement_block( (ast_statement_type)BLOCK_SEQUENTIAL_INITIAL, construct->initial_construct); ast_list_append(tr->initial_blocks ,toadd); } else if(construct->type == MOD_ITEM_ALWAYS_CONSTRUCT){ ast_statement_block * toadd = (ast_statement_block *)ast_extract_statement_block( (ast_statement_type)BLOCK_SEQUENTIAL_ALWAYS, construct->always_construct); ast_list_append(tr->always_blocks,toadd); } else if(construct->type == MOD_ITEM_NET_DECLARATION){ tr->net_declarations = ast_list_concat( tr->net_declarations, ast_new_net_declaration(construct->net_declaration)); } else if(construct->type == MOD_ITEM_REG_DECLARATION){ tr->reg_declarations = ast_list_concat( tr->reg_declarations, ast_new_reg_declaration(construct->reg_declaration)); } else if(construct->type == MOD_ITEM_INTEGER_DECLARATION){ tr->integer_declarations = ast_list_concat( tr->integer_declarations, ast_new_var_declaration(construct->integer_declaration)); } else if(construct->type == MOD_ITEM_REAL_DECLARATION){ tr->real_declarations = ast_list_concat( tr->real_declarations, ast_new_var_declaration(construct->real_declaration)); } else if(construct->type == MOD_ITEM_TIME_DECLARATION){ tr->time_declarations = ast_list_concat( tr->time_declarations, ast_new_var_declaration(construct->time_declaration)); } else if(construct->type == MOD_ITEM_REALTIME_DECLARATION){ tr->realtime_declarations = ast_list_concat( tr->realtime_declarations, ast_new_var_declaration(construct->realtime_declaration)); } else if(construct->type == MOD_ITEM_EVENT_DECLARATION){ tr->event_declarations = ast_list_concat( tr->event_declarations, ast_new_var_declaration(construct->event_declaration)); } else if(construct->type == MOD_ITEM_GENVAR_DECLARATION){ tr->genvar_declarations = ast_list_concat( tr->genvar_declarations, ast_new_var_declaration(construct->genvar_declaration)); } else if(construct->type == MOD_ITEM_TASK_DECLARATION){ ast_list_append(tr->task_declarations, construct->task_declaration); } else if(construct->type == MOD_ITEM_FUNCTION_DECLARATION){ ast_list_append(tr->function_declarations, construct->function_declaration); } else { printf("ERROR: Unsupported module construct type: %d\n", construct->type); assert(0); // Fail out because this should *never* happen } } return tr; } //! Creates and returns a new source item representation. ast_source_item * VerilogCode::ast_new_source_item(ast_source_item_type type){ ast_source_item * tr = (ast_source_item *)ast_calloc(1,sizeof(ast_source_item)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; return tr; } /*! @brief Simply returns the fully qualified representation of an identifier as a string. @details Where the identifier is "simple" or a system id, then the identifier will just be returned as a character array. Where it is a hierarchical idenifier, then a dot separated string of all identifiers in the hierarchy will be returned. @param [in] id - The identifier object to return a string representation of. @returns A copy of the identifiers full name, as a null terminated character array. */ std::string VerilogCode::ast_identifier_tostring(ast_identifier id) { std::string tr = id->identifier; ast_identifier walker = id; while(walker->next != NULL) { walker = walker->next; tr+=walker->identifier; } return tr; } /*! @brief Acts like strcmp but works on ast identifiers. */ int VerilogCode::ast_identifier_cmp( ast_identifier a, ast_identifier b ){ std::string s1 = ast_identifier_tostring(a); std::string s2 = ast_identifier_tostring(b); int result = (s1==s2); return result; } ast_identifier VerilogCode::ast_new_identifier( std::string identifier, unsigned int from_line ){ ast_identifier tr = (ast_identifier)ast_calloc(1,sizeof(struct ast_identifier_t)); ast_set_meta_info(&(tr->meta_info)); tr->identifier = identifier; tr->from_line = from_line; tr->type = ID_UNKNOWN; tr->next = NULL; tr->range_or_idx = ID_HAS_NONE; return tr; } ast_identifier VerilogCode::ast_new_system_identifier( char * identifier, //!< String text of the identifier. unsigned int from_line //!< THe line the idenifier came from. ){ ast_identifier tr = ast_new_identifier(identifier,from_line); ast_set_meta_info(&(tr->meta_info)); tr->is_system = true; return tr; } ast_identifier VerilogCode::ast_append_identifier( ast_identifier parent, ast_identifier child ){ ast_identifier tr = parent; parent->next = child; return tr; } void VerilogCode::ast_identifier_set_range( ast_identifier id, ast_range * range ){ id->range = range; id->range_or_idx = ID_HAS_RANGE; } void VerilogCode::ast_identifier_set_index( ast_identifier id, ast_expression * index ){ id->index = index; id->range_or_idx = ID_HAS_INDEX; } /*! @brief Creates and returns a new configuration rule statment node. */ ast_config_rule_statement * VerilogCode::ast_new_config_rule_statement( bool is_default, ast_identifier clause_1, //!< The first grammar clause. ast_identifier clause_2 //!< The second grammar clause. ){ ast_config_rule_statement * tr = (ast_config_rule_statement *)ast_calloc(1,sizeof(ast_config_rule_statement)); tr->is_default = is_default; tr->clause_1 = clause_1; tr->clause_2 = clause_2; return tr; } ast_config_declaration * VerilogCode::ast_new_config_declaration( ast_identifier identifier, ast_identifier design_statement, ast_list * rule_statements ){ ast_config_declaration * tr = (ast_config_declaration *)ast_calloc(1,sizeof(ast_config_declaration)); ast_set_meta_info(&(tr->meta_info)); tr->identifier = identifier; tr->design_statement = design_statement; tr->rule_statements = rule_statements; return tr; } /*! @brief Creates a new library declaration node. */ ast_library_declaration * VerilogCode::ast_new_library_declaration( ast_identifier identifier, ast_list * file_paths, ast_list * incdirs ){ ast_library_declaration * tr = (ast_library_declaration *)ast_calloc(1,sizeof(ast_library_declaration)); tr->identifier = identifier; tr->file_paths = file_paths; tr->incdirs = incdirs; return tr; } //! Creates and returns a new library description object. ast_library_descriptions * VerilogCode::ast_new_library_description( ast_library_item_type type ){ ast_library_descriptions * tr = (ast_library_descriptions *)ast_calloc(1,sizeof(ast_library_descriptions)); ast_set_meta_info(&(tr->meta_info)); tr->type = type; return tr; } /*! @brief Creates a new number representation object. @todo Implement proper representation converstion. */ ast_number * VerilogCode::ast_new_number(ast_number_base base, //!< What is the base of the number. ast_number_representation representation, //!< How to interepret digits. std::string digits //!< The string token representing the number. ){ ast_number * tr = (ast_number *)ast_calloc(1,sizeof(ast_number)); ast_set_meta_info(&(tr->meta_info)); tr->base = base; tr->representation = representation; tr->as_bits = digits; return tr; } /*! @brief A utility function for converting an ast number into a string. @param [in] n - The number to turn into a string. */ std::string VerilogCode::ast_number_tostring( ast_number * n ){ assert(n!=NULL); std::string tr; ast_number_representation rep = n->representation; switch(rep) { case REP_BITS: tr = n->as_bits; break; case REP_INTEGER: tr+=n-> as_int; break; case REP_FLOAT: tr+=n->as_float; break; default: tr = "NULL"; break; } return tr; } // ---------------------------------------------------------------------------- /*! @brief Creates and returns a new, empty source tree. @details This should be called ahead of parsing anything, so we will have an object to put parsed constructs into. */ verilog_source_tree * VerilogCode::verilog_new_source_tree() { verilog_source_tree * tr = (verilog_source_tree *)ast_calloc(1,sizeof(verilog_source_tree)); tr->modules = ast_list_new(); tr->primitives = ast_list_new(); tr->configs = ast_list_new(); tr->libraries = ast_list_new(); return tr; } /*! @brief Releases a source tree object from memory. @param [in] tofree - The source tree to be free'd */ void VerilogCode::verilog_free_source_tree( verilog_source_tree * tofree ){ printf("ERROR: Function not implemented. Source tree at %p not freed.\n", tofree); } }
true
5ab1de5889af5da217037c7218427853d060e486
C++
aulitvinas/egzaminai
/2014menuleigis/menuleigis.cpp
UTF-8
1,399
2.75
3
[]
no_license
#include <fstream> #include <iostream> using namespace std; struct abc { int x; int y; }; int main() { struct abc abc; int x0, y0, n, ivykdyta[99], ejimas, k, ejimai; bool tikslas=false; ifstream fr("U2.txt"); ofstream fd("U2rez.txt"); fr >> x0; fr >> y0; fr >> n; for (int i=0; i<n; i++) { abc.x=x0; abc.y=y0; fr >> k; ejimai=0; tikslas=false; for (int j=0; j<k; j++) { fr >> ejimas; if (ejimas==1) {abc.x++; abc.y++;} if (ejimas==2) {abc.x++; abc.y--;} if (ejimas==3) {abc.x--; abc.y--;} if (ejimas==4) {abc.x--; abc.y++;} ejimai++; ivykdyta[j]=ejimas; if ((abc.x==x0)&&(abc.y==y0)) { tikslas=true; cout << "Pasiektas tikslas "; for (int l=0; l<ejimai; l++) { cout << ivykdyta[l] << " "; } cout << ejimai << endl; } } if (tikslas==false) { cout << "sekos pabaiga "; for (int l=0; l<ejimai; l++) { cout << ivykdyta[l] << " "; } cout << ejimai << " "; cout << abc.x << " "; cout << abc.y << endl; } } }
true
c52556e91bb9cc4583fd9a9dccc99861e8c81b0e
C++
allangit/clasesC
/ejemplo2.cpp
UTF-8
595
3.6875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; class Rectangulo{ private: float largo,ancho; public: Rectangulo(float, float); void area(); void perimetro(); }; Rectangulo::Rectangulo(float _largo, float _ancho){ largo=_largo; ancho=_ancho; } void Rectangulo::area(){ float area; area=largo*ancho; cout<<"El area es::"<<area<<"\n"; } void Rectangulo::perimetro(){ float peri; peri=2*(largo+ancho); cout<<"El perimetro es::"<<peri<<endl; } int main(){ Rectangulo r1= Rectangulo(4.5,65); r1.area(); r1.perimetro(); return 0; }
true
c1a0b7514bd3896fb29efbdcf53befa2284bde86
C++
KostaPapa/DataStructures-Algorithms
/EXERCISE/30) Lecture10Wrappers&Adapters.cpp
UTF-8
408
3.09375
3
[]
no_license
#include<iostream> #include<vector> #include<stack> using namespace std; template<class Object> void Stack<Object>::push(const Object& x){ if(topOfStack == theArray.size()-1){ theArray.resize(theArray.size()*2-1); } theArray[++topOfStack] = x; } int main(){ Stack<int> s; for(int i=0; i<10; ++i){ s.push(i); } system("pause"); return 0; }
true
1a1837feb85334482c7cbebb5a0f83ad33f0195a
C++
thervieu/Modules_CPP
/04/ex03/Cure.cpp
UTF-8
513
2.796875
3
[]
no_license
#include "Cure.hpp" Cure::Cure(void) : AMateria("cure") { return ; } Cure::Cure(const Cure &src) { *this = src; _type = "cure"; return ; } Cure::~Cure(void) { return ; } Cure &Cure::operator= (const Cure &rhs) { if (this != &rhs) { this->_xp = rhs._xp; } return (*this); } AMateria *Cure::clone(void) const { return (new Cure(*this)); } void Cure::use(ICharacter &target) { AMateria::use(target); std::cout << "* heals " << target.getName() << "'s wounds *" << std::endl; return ; }
true
86cd7903a937816965ab08140bd397ef9230ba3b
C++
apalomer/spatial_relationships
/include/quaternion_distance_cost_function.h
UTF-8
1,500
2.75
3
[]
no_license
#ifndef QUATERNION_DISTANCE_COST_FUNCTION_H #define QUATERNION_DISTANCE_COST_FUNCTION_H #include <ceres/ceres.h> #include "transformations.h" #include "functions.h" /*! * \brief The QuaternionDistance cost function class * \callgraph * \callergraph */ class QuaternionDistance: public ceres::SizedCostFunction<1,4,4> { public: /*! * \brief Constructor */ QuaternionDistance(); ~QuaternionDistance(); /*! * \brief Evaluate the cost function with the given parameters * \param parameters * \param[out] residuals * \param[out] jacobians * \return ture/false if the residuals and the jacobians have been properly evaluated. * \callgraph * \callergraph */ bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const; /*! * \brief operator() evaluates the cost function for the given parameters. * \param q1 * \param q2 * \param[out] residuals = quaternionDistance(q1,q2) * \return ture/false if the residuals and the jacobians have been properly evaluated. * \callgraph * \callergraph */ template<typename T> bool operator()(const T* const q1, const T* const q2, T* residuals) const { Eigen::Quaternion<T> q_1(q1[0],q1[1],q1[2],q1[3]); Eigen::Quaternion<T> q_2(q2[0],q2[1],q2[2],q2[3]); residuals[0] = quaternionDistance<T>(q_1,q_2); return true; } }; #endif // QUATERNION_DISTANCE_COST_FUNCTION_H
true
243f5d7c73e666d75eca29afeb42300f44197171
C++
louisway/Topic_model
/topic_model.hpp
UTF-8
2,727
3.015625
3
[]
no_license
#include <unordered_map> #include <string> #include <vector> #include <utility> //raw document class doc{ public: int doc_len; //the len of the document std::vector<int> content; //doc content with word index int year; // year public: doc(); doc(int n,int y); }; //raw corpus class Corpus{ private: //std::vector<doc> doc_stack; std::unordered_map<int, std::vector<doc> > doc_stack;// year - doc_stack std::unordered_map<int, std::vector<doc> > test_doc_stack; public: std::unordered_map<std::string, int > dictionary; std::unordered_map<int, std::string> re_dictionary; //int dict_len; //int doc_num; //double test_ratio; //std::vector<int> year_stack; public: Corpus(); }; //document_status class doc_status { public: int doc_len;// document length int year; std::vector<int> topic_label; //record the topic label of every word std::vector<int> count_per_topic; // words count per topic, t dimension std::vector<double> topic_vector; //topic vector, t dimension public: doc_status(); doc_status(int n, int y); }; //corpus_status class Corpus_status { public: Corpus cps; std::unordered_map<int, std::vector<doc_status> > doc_status_stack;// year -doc_status_stack std::unordered_map<int, std::vector<doc_status> > test_doc_status_stack; //std::vector<doc_status> doc_status_stack; public: int dict_len; std::vector<int> year_stack;// year - stack std::vector<std::vector<double> > word_topic_matrix; std::vector<std::vector<int> > count_word_topic; std::vector<int> count_per_topic; public: Corpus_status(); }; class topic_model{ //define parameter public: int Topic_num; double test_ratio; std::vector<double> alpha, beta; bool text_process(); bool Inference(int iter, int year); private: Corpus cps; public: topic_model(); topic_model(int topic_num, double a, double b, double ratio); }; topic_model::topic_model():Topic_num(0),alpha(),beta(),test_ratio(0) { } topic_model::topic_model(int topic_num, double a, double b, double ratio):Topic_num(topic_num), alpha(1, a), beta(1, b), test_ratio(ratio) { } Corpus_status::Corpus_status():dict_len(0), year_stack(), word_topic_matrix(), count_word_topic(), count_per_topic(){ } doc_status::doc_status(): doc_len(0),year(-1),topic_label(),count_per_topic(),topic_vector(){ } doc_status::doc_status(int n, int y):doc_len(n),year(y),topic_label(),count_per_topic(), topic_vector() { } Corpus::Corpus():doc_stack(),test_doc_stack(),dictionary(),re_dictionary() { } doc::doc():doc_len(0),content(),year(-1){ } doc::doc(int n,int y):doc_len(n), year(-1),content() { }
true
6243fa98948f707c776e09dceb039e65a7db888f
C++
Chunting/ur_ws
/src/lesson_move_group/src/send_urscript.cpp
UTF-8
1,374
2.609375
3
[]
no_license
#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> #include <math.h> #include <sensor_msgs/JointState.h> #include "std_msgs/Float64.h" /** * This tutorial demonstrates simple sending of messages over the ROS system. */ double current_joint4 = 0; void Callback(const sensor_msgs::JointState& msg) { current_joint4 = msg.position[4]; } int main(int argc, char **argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; std::vector<double> current_joint_values; ros::Publisher UrScript_pub = n.advertise<std_msgs::String>("/ur_driver/URScript", 1000); ros::Publisher command_pub = n.advertise<std_msgs::Float64>("/command", 1000); ros::Subscriber UrStates_sub = n.subscribe("/joint_states", 1000, Callback); ros::Rate loop_rate(10); int count = 0; std_msgs::Float64 command; command.data = 0; while (ros::ok()) { loop_rate.sleep(); std_msgs::String msg; std::stringstream ss; double pos = 0.1*sin(0.1*count*0.1); command.data = pos; ss << "servoj([0,-1.5708,0,0," << pos << ",0],0.1,0.1,500)"; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); UrScript_pub.publish(msg); command_pub.publish(command); ros::spinOnce(); ROS_INFO("the current_joint4 is: %f", current_joint4*180/3.14159); ros::spinOnce(); ++count; } return 0; }
true
ec5d0ad89f303be8249448a1f21ba0649e1e2b65
C++
KillerOfFriend/MSG
/Common/Classes/UserAccount/UserAccount.cpp
UTF-8
9,912
2.640625
3
[]
no_license
#include "UserAccount.h" #include "Classes/DataModule/DataModule.h" using namespace Core; //----------------------------------------------------------------------------- TUserAccount::TUserAccount(QObject *inParent) : TConnection(inParent) { fUserInfo = std::make_shared<TUserInfo>(); fContacts = std::make_shared<TUsersModel>(); fChats = std::make_shared<TChatsModel>(); } //----------------------------------------------------------------------------- TUserAccount::TUserAccount(const TUserAccount &inOther) : TConnection(inOther) { this->fUserInfo = inOther.fUserInfo; // Копируем инфо пользователя // Копируем контейнер контактов this->fContacts = std::make_shared<TUsersModel>(); std::for_each(inOther.fContacts->begin(), inOther.fContacts->end(), [&](const std::pair<QUuid, Core::UserInfo_Ptr> &Contact) { this->fContacts->insert(Contact); }); // Копируем контейнер контактов this->fChats = std::make_shared<TChatsModel>(); std::for_each(inOther.fChats->begin(), inOther.fChats->end(), [&](const std::pair<QUuid, Core::ChatInfo_Ptr> &Chat) { this->fChats->insert(Chat); }); } //----------------------------------------------------------------------------- TUserAccount::~TUserAccount() { fContacts->clear(); // Очищаем список контактов fChats->clear(); // Очищаем список бесед } //----------------------------------------------------------------------------- TUserAccount& TUserAccount::operator = (const TUserAccount &inOther) { if (this == &inOther) return *this; this->fUserInfo = inOther.fUserInfo; // Копируем инфо пользователя // Копируем контейнер контактов this->fContacts = std::make_shared<TUsersModel>(); std::for_each(inOther.fContacts->begin(), inOther.fContacts->end(), [&](const std::pair<QUuid, Core::UserInfo_Ptr> &Contact) { this->fContacts->insert(Contact); }); // Копируем контейнер контактов this->fChats = std::make_shared<TChatsModel>(); std::for_each(inOther.fChats->begin(), inOther.fChats->end(), [&](const std::pair<QUuid, Core::ChatInfo_Ptr> &Chat) { this->fChats->insert(Chat); }); this->setParent(inOther.parent()); return *this; } //----------------------------------------------------------------------------- /** * @brief TUserAccount::userInfo - Метод вернёт информацию о пользователе * @return Вернёт указатель на данные пользователя */ UserInfo_Ptr TUserAccount::userInfo() const { return fUserInfo; } //----------------------------------------------------------------------------- /** * @brief TUserAccount::contacts - Метод вернёт список контактов * @return Вернёт указатель на список контактов */ std::shared_ptr<TUsersModel> TUserAccount::contacts() const { return fContacts; } //----------------------------------------------------------------------------- /** * @brief TUserAccount::chats - Метод вернёт список бесед * @return Вернёт указатель на список бесед */ std::shared_ptr<TChatsModel> TUserAccount::chats() const { return fChats; } //----------------------------------------------------------------------------- /** * @brief TUserAccount::slot_SetUserInfo - Слот задаст данные пользователя * @param inUserInfo - Ссылка на данные пользователя */ void TUserAccount::slot_SetUserInfo(const UserInfo_Ptr &inUserInfo) { fContacts->clear(); fUserInfo = inUserInfo; } //----------------------------------------------------------------------------- /** * @brief TUserAccount::slot_SetContacts - Слот задаст список контактов * @param inContacts - Ссылка на список контактов */ void TUserAccount::slot_SetContacts(const QList<UserInfo_Ptr> &inContacts) { fContacts->clear(); std::for_each(inContacts.begin(), inContacts.end(), [&](const UserInfo_Ptr Info) { auto InsertRes = fContacts->insert(std::make_pair(Info->userUuid(), Info)); if (!InsertRes.second) qDebug() << "Не удалось вставить контакт: " + Info->userLogin(); }); } //----------------------------------------------------------------------------- /** * @brief TUserAccount::slot_ContactChangeStatus - Слот установит контакту указанный статус * @param inContactUuid - Uuid контакта * @param inNewStatus - Новый статус */ void TUserAccount::slot_ContactChangeStatus(QUuid inContactUuid, quint8 inNewStatus) { auto FindRes = fContacts->find(inContactUuid); if (FindRes != fContacts->end()) { auto Row = std::distance(fContacts->begin(), FindRes); FindRes->second->setUserStatus(inNewStatus); fContacts->dataChanged(fContacts->index(Row, TUsersModel::cUserStatus), fContacts->index(Row, TUsersModel::cUserStatus)); } } //----------------------------------------------------------------------------- /** * @brief TUserAccount::slot_SetChats - Слот задаст список бесед * @param inChats - Список бесед */ void TUserAccount::slot_SetChats(const QList<ChatInfo_Ptr> &inChats) { fChats->clear(); std::for_each(inChats.begin(), inChats.end(), [&](const ChatInfo_Ptr &Info) { auto InsertRes = fChats->insert(std::make_pair(Info->chatUuid(), Info)); if (!InsertRes.second) qDebug() << "Не удалось вставить беседу: " + Info->chatName(); }); } //----------------------------------------------------------------------------- /** * @brief TUserAccount::slot_AddChat - Слот добавит беседу * @param inChat - Новая беседа */ void TUserAccount::slot_AddChat(const ChatInfo_Ptr inChat) { if (!inChat) return; auto FindRes = fChats->find(inChat->chatUuid()); // Ищим беседу по Uuid if (FindRes == fChats->end()) // Если не найдена { // Добавляем fChats->insert(std::make_pair(inChat->chatUuid(), inChat)); } else // Если найдена { // Обновляем FindRes->second = inChat; } } //----------------------------------------------------------------------------- namespace Core { // Во избежании затупов со стороны компиллера, требуется оборачивать реализацию в тот же неймспейс принудительно QDataStream& operator <<(QDataStream &outStream, const TUserAccount &UserAccount) { outStream << *UserAccount.fUserInfo; // Передаём информацию о пользователе //-- QList<Core::TUserInfo> ContactsBuf; // Список передоваемых объектов типа "Инфо Пользователя" std::for_each(UserAccount.fContacts->begin(), UserAccount.fContacts->end(), [&ContactsBuf](const std::pair<QUuid, Core::UserInfo_Ptr> &Contact) { // Преобразовываем указатели в объекты ContactsBuf.push_back(*Contact.second); }); outStream << ContactsBuf; // Передаём список контактов //-- QList<Core::TChatInfo> ChatsBuf; // Список передоваемых объектов типа "Инфо Беседы" std::for_each(UserAccount.fChats->begin(), UserAccount.fChats->end(), [&ChatsBuf](const std::pair<QUuid, Core::ChatInfo_Ptr> &Chat) { // Преобразовываем указатели в объекты ChatsBuf.push_back(*Chat.second); }); outStream << ChatsBuf; // Передаём список бесед // Члены TConnection не передаются return outStream; } //----------------------------------------------------------------------------- QDataStream& operator >>(QDataStream &inStream, TUserAccount &UserAccount) { Core::TUserInfo BufUserInfo; inStream >> BufUserInfo; // Получаем информацию о пользователе UserAccount.fUserInfo = std::make_shared<Core::TUserInfo>(BufUserInfo); // Преобразуем объект к указателю //-- UserAccount.fContacts->clear(); QList<Core::TUserInfo> ContactsBuf; // Список получаемых объектов типа "Инфо Пользователя" inStream >> ContactsBuf; // Получаем список контактов std::for_each(ContactsBuf.begin(), ContactsBuf.end(), [&](const Core::TUserInfo &Contact) { // Преобразовываем объекты в указатели UserAccount.contacts()->insert(std::make_pair(Contact.userUuid(), std::make_shared<Core::TUserInfo>(Contact))); }); //-- UserAccount.fChats->clear(); QList<Core::TChatInfo> ChatsBuf; // Список получаемых объектов типа "Инфо Беседы" inStream >> ChatsBuf; // Получаем список бесед std::for_each(ChatsBuf.begin(), ChatsBuf.end(), [&](const Core::TChatInfo &Chat) { // Преобразовываем объекты в указатели UserAccount.chats()->insert(std::make_pair(Chat.chatUuid(), std::make_shared<Core::TChatInfo>(Chat))); }); // Члены TConnection не передаются return inStream; } //----------------------------------------------------------------------------- }
true
d67d7232e851ddd2f39426d78881df47c5a3da26
C++
varshitabhat/aps
/sparse_tree.cpp
UTF-8
585
2.546875
3
[]
no_license
#include <iostream> using namespace std; int main() { int lookup[50][50]; int a[]={7,2,3,0,5,10,3,12,18}; int n=9,j,i; for(i=0;i<n;i++) lookup[i][0]=i; for(j=1;1<<j<=n;j++) for(i=0;(i+(1<<(j-1))<n);i++) { if(a[lookup[i][j-1]]<a[lookup[i+(1<<(j-1))][j-1]]) lookup[i][j]=lookup[i][j-1]; else a[lookup[i][j-1]]<a[lookup[i+(1<<(j-1))][j-1]]; } for(i=0;i<n;i++) {for(j=0;j<n;j++) cout<<lookup[i][j]; cout<<endl;} return 0; }
true
1c11e597597ce5523e61110914648de108c93627
C++
tanht-lavamyth/Algorithm
/Competitive Programming Exercises/Codeforces/HQ9+.cpp
UTF-8
466
2.828125
3
[]
no_license
/* * @Author: tanht * @Date: 2020-09-19 17:47:36 * @Last Modified by: tanht * @Last Modified time: 2020-09-19 19:56:14 * @Email: tanht.lavamyth@gmail.com */ #include <iostream> using namespace std; int main() { string s; cin >> s; bool isExectedAnyProgram = false; for (int i = 0; i < (int)s.size(); ++i) { if (s[i] == 'H' || s[i] == 'Q' || s[i] == '9') { isExectedAnyProgram = true; cout << "YES"; break; } } if (!isExectedAnyProgram) { cout << "NO"; } }
true
b9549956ba941f1313be3985f4c5539063b86a2e
C++
RGTHENO/ccomp1
/my_stack.cpp
UTF-8
1,864
3.984375
4
[]
no_license
#include <iostream> #include <stack> using namespace std; int main(){ stack<int> pila; /************************************** push() ****************************/ /**Inserta un elemento en la cima de la pila sobre su actual top elemento**/ pila.push(12);pila.push(13);pila.push(14); /***************************** size() *************************************/ cout<<"EL tamanio de la pila es: "<<pila.size()<<endl; /************************************** top() ****************************/ /*********** Retorna una referencia al top elemento del stack ************/ cout<<"Los elementos de la pila son: \n"; while (!pila.empty()) /*** empty() : Retorna un booleano si su tamanio esta vacio ***/ { std::cout << ' ' << pila.top(); pila.pop(); /*** pop() : Elimina el top elemento ***/ } std::cout << '\n'; cout<<"El tamanio de mi pila es : "<<pila.size()<<endl<<endl; /**************************** swap(stack& x) ******************************* *******INtercambia los contenidos de ambas pilas **************************/ stack<int> aux; aux.push(9);aux.push(12); aux.push(15); aux.push(18); cout<<"El tamanio de mi aux es: "<<aux.size()<<endl<<endl; cout<<"Despues de la llamada a swap(), los tamanio de mis listas quedaron de la sgte manera: "<<endl; cout<<"Tamanio de Pila: "<<pila.size()<<endl; cout<<"Tamanio de Aux : "<<aux.size()<<endl; /******************** emplace() *********************************** * Añade un nuevo elemento sobre el top actual elemento, este nuevo elemento es construido, pasando los * argumentos que recibe emplace, como argumentos del constructor de mi contenedor****/ pila.emplace(4);pila.emplace(10); cout<<"Hemos realizado dos llamadas a la funcion emplace() "<<endl; cout<<"EL elemento en el top del stack es : "<<pila.top()<<endl; return 0; }
true
cf416f4b5c4871050fd4ebf42aa0a89bffd0d5b3
C++
Pythoner-Waqas/Backup
/C Programming exercises/F_15.cpp
UTF-8
2,683
4.4375
4
[]
no_license
/* The following program demonstrate the declaration and uses of friend functions of a class We set values in the constructors of the classes. The program prompts the user to enter a choice of addition, subtraction, multiplication or division. And then performs the appropriate operation by using the friend functions. */ #include <iostream> using namespace std; class myClass2; // declaration of the myClass2 for the friend functions class myClass1 { private: float value ; public: myClass1 ( ) { value = 200; } // friend functions friend float addBoth ( myClass1, myClass2 ) ; friend float subBoth ( myClass1, myClass2 ) ; friend float mulBoth ( myClass1, myClass2 ) ; friend float divBoth ( myClass1, myClass2 ) ; }; class myClass2 { private: float value ; public: myClass2( ) { value = 100 ; } // friend functions friend float addBoth ( myClass1 , myClass2 ) ; friend float subBoth ( myClass1 , myClass2 ) ; friend float mulBoth ( myClass1 , myClass2 ) ; friend float divBoth ( myClass1 , myClass2 ) ; }; float addBoth ( myClass1 object1 , myClass2 object2 ) { return ( object1.value + object2.value ) ; } float subBoth ( myClass1 object1 , myClass2 object2 ) { return ( object1.value - object2.value ) ; } float mulBoth ( myClass1 object1 , myClass2 object2 ) { return ( object1.value * object2.value ) ; } float divBoth ( myClass1 object1 , myClass2 object2 ) { return ( object1.value / object2.value ) ; } main() { myClass1 myClass1Obj ; //create an object of class myClass1 myClass2 myClass2Obj ; //create an object of class myClass2 char choice; cout << "Please enter one of the operator +, -, /, * " << "followed by Enter " <<endl; cin >> choice; if ( choice == '+' ) { cout << "The sum is : " << addBoth(myClass1Obj , myClass2Obj) << endl; } else if ( choice == '-' ) { cout << "The difference is : " << subBoth(myClass1Obj , myClass2Obj) << endl; } else if ( choice == '*' ) { cout << "The multiplication is : " << mulBoth(myClass1Obj , myClass2Obj) << endl; } else if ( choice == '/' ) { cout << "The division is : " << divBoth(myClass1Obj , myClass2Obj) << endl; } else { cout << "Enter a valid choice next time. The program is terminating" << endl; } }
true
f8aee7f9cffbd481cf53ccad5201136f60fc59c0
C++
rol-x/MemoryConsoleGame
/MemoryConsoleGame/Board.cpp
UTF-8
7,157
3.140625
3
[]
no_license
#include "Board.h" void Board::loadCardsFromFile() { fstream cardsFile; cardsFile.open("cards.txt", ios::in); try { if (!cardsFile.good()) throw FileDoesntExistException(); vector<Card*> allCardsFromFile; while (cardsFile.good()) { string cardContent = ""; cardsFile >> cardContent; Card * card = new Card(cardContent); allCardsFromFile.push_back(card); } if (areCardsDoubled(allCardsFromFile)) throw DoubledCardException(); vector<Card*> gameplayCards; for (int i = 0; i < _boardSize*_boardSize / 2; i++) { if (allCardsFromFile.size() == 0) throw FileTooSmallException(); int index = rand() % allCardsFromFile.size(); auto * card = new Card(allCardsFromFile[index]->Content()); gameplayCards.push_back(allCardsFromFile[index]); gameplayCards.push_back(card); allCardsFromFile.erase(allCardsFromFile.begin() + index); } for (int i = 0; i < _boardSize; i++) { vector<Card*> _row; for (int j = 0; j < _boardSize; j++) { shuffleVector(gameplayCards); // The vector is shuffled and each time the last element is pushed on the board _row.push_back(gameplayCards.back()); gameplayCards.pop_back(); } _cards.push_back(_row); } } catch (const FileLoadingException& exc) { cout << endl << exc.what() << endl; throw; } } bool Board::areCardsDoubled(vector<Card*> cards) { map<string, int> contentCount; for (auto card : cards) if (contentCount.find(card->Content()) == contentCount.end()) contentCount[card->Content()] = 1; else contentCount[card->Content()]++; for (auto pair : contentCount) if (pair.second > 1) return true; return false; } void Board::shuffleVector(vector<Card*>& cards) { vector<Card*> shuffledVector; int randomIndex; int cardsCount = cards.size(); for (int i = 0; i < cardsCount; i++) { randomIndex = rand() % cards.size(); shuffledVector.push_back(cards[randomIndex]); cards.erase(cards.begin() + randomIndex); } cards = shuffledVector; } void Board::displayErrorAddressMessage(string message) { _console.ShiftCursor(0, -3); TextPosition().RightAlignOutput(message); cout << endl; _console.ClearCurrentLine(); TextPosition().RightAlignOutput(" "); Console().ShiftCursor(-39, 0); cin.sync(); } void Board::showProgress() { cout << _progress << "/" << _boardSize * _boardSize / 2 << " pairs found" << endl; } void Board::showClock() { time_t runTime = (clock() - _startTime) / CLOCKS_PER_SEC; int minutes = static_cast<int>(runTime) / 60; int seconds = static_cast<int>(runTime) % 60; cout << minutes << "m " << seconds << "s " << endl; } Board::Board(int boardSize) { _startTime = clock(); _boardSize = boardSize; try { loadCardsFromFile(); _progress = 0; } catch (const FileLoadingException&) { throw; } } void Board::Show() { system("cls"); _console.RemoveScrollbar(); for (char columnIndex = 'a'; columnIndex - 97 < _boardSize; columnIndex++) cout << "\t" << columnIndex << "\t\t"; cout << endl << endl; int rowIndex = 1; for (auto cardRow : _cards) { cout << rowIndex++ << "\t"; for (auto card : cardRow) { if (CardsRevealed() == 2 && card->IsRevealed() && !card->IsOutOfTheGame()) { if (DoRevealedCardsMatch()) _console.SetTextColor(COLOR::GREEN); else _console.SetTextColor(COLOR::RED); } cout << card->Show() << "\t\t"; _console.SetTextColor(COLOR::WHITE); } cout << endl << endl << endl; } cout << endl; showProgress(); showClock(); } void Board::ShowWithPause() { Show(); Sleep(2500); } pair<char, int> * Board::GetAddress() { string address; cout << "\n\n"; TextPosition().RightAlignOutput("Which card do you want to reveal? "); Console().ShiftCursor(-39, 1); cout << "> "; cin >> address; pair<char, int> * addressPair; if (address.length() != 2) { displayErrorAddressMessage("Improper address format! "); return nullptr; } char first = address.at(0); char second = address.at(1); addressPair = new pair<char, int>(); if (second >= '1' && second < '1' + _boardSize) // digit is second { if (first >= 'a' && first < 'a' + _boardSize) // lowercase letter is first { addressPair->first = first; addressPair->second = second - 48; } else if (first >= 'A' && first < 'A' + _boardSize) // uppercase letter is first { addressPair->first = first; addressPair->second = second - 48; } else { displayErrorAddressMessage("Invalid address "); return nullptr; } } else if (first >= '1' && first < '1' + _boardSize) // digit is first { if (second >= 'a' && second < 'a' + _boardSize) // lowercase letter is second { addressPair->first = second; addressPair->second = first - 48; } else if (second >= 'A' && second < 'A' + _boardSize) // uppercase letter is second { addressPair->first = second; addressPair->second = first - 48; } else { displayErrorAddressMessage("Invalid address "); return nullptr; } } else { displayErrorAddressMessage("Invalid address "); return nullptr; } return addressPair; } Card * Board::CardAtAddress(pair<char, int> * address) { int row = address->second - 1; int column = 0; if (address->first >= 'a') column = static_cast<int>(address->first - 97); else column = static_cast<int>(address->first - 65); Card * card; try { if (row >= _boardSize || row < 0 || column >= _boardSize || column < 0) throw out_of_range("\nCard address out of range!\n"); card = _cards[row][column]; } catch (const exception& exc) { return nullptr; } return card; } void Board::RevealCard(pair<char, int> * address) { if (address == nullptr) system("pause"); else if (!CardAtAddress(address)->IsRevealed()) CardAtAddress(address)->Reveal(); } int Board::CardsRevealed() { int cardsRevealed = 0; for (auto cardRow : _cards) for (auto card : cardRow) if (card->IsRevealed() && !card->IsOutOfTheGame()) cardsRevealed++; return cardsRevealed; } bool Board::DoRevealedCardsMatch() { vector<Card*> revealedCards; for (auto &cardRow : _cards) for (auto &card : cardRow) if (card->IsRevealed() && !card->IsOutOfTheGame()) revealedCards.push_back(card); if (revealedCards[0]->Content() == revealedCards[1]->Content()) return true; else return false; } void Board::AddToProgress() { _progress++; } void Board::RemoveRevealedCards() { vector<Card*> revealedCards; for (auto &cardRow : _cards) for (auto &card : cardRow) if (card->IsRevealed() && !card->IsOutOfTheGame()) revealedCards.push_back(card); revealedCards[0]->RemoveFromTheGame(); revealedCards[1]->RemoveFromTheGame(); } void Board::HideRevealedCards() { vector<Card*> revealedCards; for (auto &cardRow : _cards) for (auto &card : cardRow) if (card->IsRevealed() && !card->IsOutOfTheGame()) revealedCards.push_back(card); revealedCards[0]->Hide(); revealedCards[1]->Hide(); } bool Board::AreAllCardsRemoved() { for (auto cardRow : _cards) for (auto card : cardRow) if (!card->IsOutOfTheGame()) return false; return true; } Board::~Board() { }
true
d6d869bd5d36d8234349c78b0f5b12e9193fb072
C++
Rookfighter/MultiAgentExploration
/src/utils/StopWatch.hpp
UTF-8
736
2.59375
3
[ "MIT" ]
permissive
#ifndef MAE_STOP_WATCH_HPP #define MAE_STOP_WATCH_HPP #include <sys/time.h> #include <string> namespace mae { class StopWatch { private: struct timeval begin_; struct timeval last_; struct timeval worst_; struct timeval best_; bool newBestCase_; bool newWorstCase_; public: StopWatch(); ~StopWatch(); void start(); void stop(); unsigned int getLastMsec() const; unsigned int getWorstMsec() const; unsigned int getBestMsec() const; unsigned long getLastUsec() const; unsigned long getWorstUsec() const; unsigned long getBestUsec() const; bool hasNewWorstCase() const; bool hasNewBestCase() const; std::string strMsec() const; std::string strUsec() const; }; } #endif
true
35c4c573d0e8a5f44ffa3931b6e55feece3a78f2
C++
ZY1N/CPP_Piscine
/Day05/ex02/Form.cpp
UTF-8
3,579
2.875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Form.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yinzhang <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/29 20:26:58 by yinzhang #+# #+# */ /* Updated: 2019/10/29 20:26:59 by yinzhang ### ########.fr */ /* */ /* ************************************************************************** */ #include "Form.hpp" Form::Form() { return ; } Form::Form(std::string name, int gradeSign, int gradeExec) { if(gradeSign < 1 || gradeExec < 1) throw Form::GradeTooHighException(); if(gradeSign > 150 || gradeExec > 150) throw Form::GradeTooLowException(); this->_signed = false; this->_name = name; this->_gradeSign = gradeSign; this->_gradeExec = gradeExec; return ; } Form::Form(const Form &src) { this->_name = src.getName(); this->_gradeSign = src.getGradeSign(); this->_gradeExec = src.getGradeExec(); *this = src; } Form::~Form() { return ; } Form &Form::operator=(const Form &src) { this->_signed = src.getSigned(); return(*this); } std::string Form::getName() const { return(this->_name); } bool Form::getSigned() const { return(this->_signed); } int Form::getGradeSign() const { return(this->_gradeSign); } int Form::getGradeExec() const { return(this->_gradeExec); } void Form::beSigned(Bureaucrat &src) { if(src.getGrade() > this->_gradeSign) throw Bureaucrat::GradeTooLowException(); else { this->_signed = 1; } return ; } Form::GradeTooLowException::GradeTooLowException() { return ; } Form::GradeTooLowException::GradeTooLowException(const GradeTooLowException &src) { *this = src; return ; } //this one cant throw Form::GradeTooLowException::~GradeTooLowException(void) throw() { return ; } Form::GradeTooLowException &Form::GradeTooLowException::operator= (const GradeTooLowException &src) { (void)src; return(*this); } const char *Form::GradeTooLowException::what() const throw() { return("Grade below minimum bound."); } Form::GradeTooHighException::GradeTooHighException() { return ; } /* Form::GradeTooHighException::GradeTooHighException(const GradeTooHighException &src) throw() { *this = src; return ; }*/ Form::GradeTooHighException::GradeTooHighException(const GradeTooHighException &src) { *this = src; return ; } //this one cant throw Form::GradeTooHighException::~GradeTooHighException(void) throw() { return ; } Form::GradeTooHighException &Form::GradeTooHighException::operator= (const GradeTooHighException &src) { (void)src; return(*this); } const char *Form::GradeTooHighException::what() const throw() { return("Grade above maximum bound."); } std::ostream &operator<<(std::ostream &o, Form const &x) { o << "Name of doc: " << x.getName() << std::endl << "Grade to exec: " << x.getGradeExec() << std::endl << "Grade to sign " << x.getGradeSign() << std::endl << "Is it signed? " << x.getSigned() << std::endl; return(o); }
true
51d853b5cf2830620d3895cf4457e746e15a2567
C++
smiley001/LintCode-Mine
/DistinctSubsequences.cpp
UTF-8
1,627
3.515625
4
[]
no_license
/************************************************************************* > File Name: DistinctSubsequences.cpp > Author: Shaojie Kang > Mail: kangshaojie@ict.ac.cn > Created Time: 2015年08月21日 星期五 07时49分23秒 > Problem: Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequences of "ABCDE" while "AEC" is not). Have you met this question in a real interview? Yes Example Given S = "rabbbit", T = "rabbit", return 3. Challenge Do it in O(n2) time and O(n) memory. O(n2) memory is also acceptable if you do not know how to optimize memory. > Solution: num[i][j] = num[i-1][j] + (S[i-1]==T[j-1] ? num[i-1][j-1] : 0); ************************************************************************/ #include<iostream> #include<vector> using namespace std; int numDistinct(string &S, string &T) { if(T.empty()) return 1; int size1 = S.size(); int size2 = T.size(); if(size1 < size2) return 0; vector<vector<int> > num(size1 + 1, vector<int>(size2 + 1, 0)); for(int i=0; i<=size1; ++i) num[i][0] = 1; for(int i=1; i<=size1; ++i) { for(int j=1; j<=size2; ++j) { if(j > i) break; num[i][j] = num[i-1][j] + (S[i-1]==T[j-1] ? num[i-1][j-1] : 0); } } return num[size1][size2]; }
true
fcb58daaee47599bbf41657c688e9055d67acf08
C++
CompuCell3D/CompuCell3D
/CompuCell3D/core/CompuCell3D/plugins/PixelTracker/PixelTracker.h
UTF-8
1,390
2.640625
3
[ "MIT" ]
permissive
#ifndef PIXELTRACKER_H #define PIXELTRACKER_H /** @author m */ #include <set> #include <CompuCell3D/Field3D/Point3D.h> #include "PixelTrackerDLLSpecifier.h" namespace CompuCell3D { //common surface area is expressed in unitsa of elementary surfaces not actual physical units. If necessary it may //need to be transformed to physical units by multiplying it by surface latticemultiplicative factor class PIXELTRACKER_EXPORT PixelTrackerData { public: PixelTrackerData() { pixel = Point3D(); } PixelTrackerData(Point3D _pixel) : pixel(_pixel) {} ///have to define < operator if using a class in the set and no < operator is defined for this class bool operator<(const PixelTrackerData &_rhs) const { return pixel.x < _rhs.pixel.x || (!(_rhs.pixel.x < pixel.x) && pixel.y < _rhs.pixel.y) || (!(_rhs.pixel.x < pixel.x) && !(_rhs.pixel.y < pixel.y) && pixel.z < _rhs.pixel.z); } bool operator==(const PixelTrackerData &_rhs) const { return pixel == _rhs.pixel; } ///members Point3D pixel; }; class PIXELTRACKER_EXPORT PixelTracker { public: PixelTracker() {}; ~PixelTracker() {}; std::set <PixelTrackerData> pixelSet; //stores pixels belonging to a given cell }; }; #endif
true
3f32d62958433f24f591d4f40407fcf49765452d
C++
FeiZhan/Algo-Collection
/answers/leetcode/Tree Depth-first Search/Tree Depth-first Search.cpp
UTF-8
1,264
3.15625
3
[ "MIT" ]
permissive
//@type Tree Depth-first Search //@result 209 / 209 test cases passed. Status: Accepted Runtime: 4 ms Submitted: 0 minutes ago You are here! Your runtime beats 11.54% of cpp submissions. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { return dfs(root, vector<int> ()); } vector<string> dfs(TreeNode *root, vector<int> path) { vector<string> paths; if (NULL == root) { } else if (NULL == root->left && NULL == root->right) { string path_str; for (size_t i = 0; i < path.size(); ++ i) { path_str += string(to_string(path[i])) + "->"; } path_str += string(to_string(root->val)); paths.push_back(path_str); } else { path.push_back(root->val); if (NULL != root->left) { vector<string> left(dfs(root->left, path)); paths.insert(paths.end(), left.begin(), left.end()); } if (NULL != root->right) { vector<string> right(dfs(root->right, path)); paths.insert(paths.end(), right.begin(), right.end()); } } return paths; } };
true
36725cfd0c84761feeaa008db0eeeb07bf6177e1
C++
C00204076/Flow_Field_Pathfinding
/Flow_Field_Pathfinding/Tile.cpp
UTF-8
1,607
3.0625
3
[]
no_license
// // C00204076 // Brandon Seah-Dempsey // Started at 10:27 8 November 2019 // Finished at // Time taken: // Known bugs: #include "Tile.h" // Tile::Tile() { //initialise(); } // Tile::Tile(int type, int gridX, int gridY) : m_type(type), m_x(gridX), m_y(gridY) { initialise(); } // Tile::~Tile() { delete this; } // void Tile::initialise() { m_square.setSize(sf::Vector2f(28, 28)); setColour(); m_square.setOutlineColor(sf::Color::Black); m_square.setPosition(m_x * 29, m_y * 29); m_valueText.setCharacterSize(7); m_valueText.setColor(sf::Color::White); m_position.x = m_x * 29; m_position.y = m_y * 29; } // void Tile::render(sf::RenderWindow& window) { window.draw(m_square); } // int Tile::getType() { return m_type; } // sf::Vector2f Tile::getPosition() { return m_position; } // sf::Vector2f Tile::getWorldPosition() { return sf::Vector2f(m_position.x * 29, m_position.y * 29); } // sf::RectangleShape Tile::getRect() { return m_square; } // void Tile::setColour() { // if (m_type < 0) { m_type = 0; } // else if (m_type > 4) { m_type = 4; } // if (m_type == 0) { m_square.setFillColor(sf::Color::Blue); } // else if (m_type == 1) { m_square.setFillColor(sf::Color::Green); m_value = 0; } // else if (m_type == 2) { m_square.setFillColor(sf::Color::Red); } // else if (m_type == 3) { m_square.setFillColor(sf::Color::Black); m_value = 999; } // else if (m_type == 4) { m_square.setFillColor(sf::Color::Yellow); } } // void Tile::setType(int type) { m_type = type; setColour(); } // void Tile::setValue(int value) { m_value = value }
true
306ea4ce328be80dce8ac78bca41c308cc6ea58e
C++
achillebourgault/IndieStudio
/Include/Colors.h
UTF-8
898
3.203125
3
[]
no_license
/* ** EPITECH PROJECT, 2024 ** Colors.h ** File description: ** Created by Leo Fabre */ #ifndef COLORS_H #define COLORS_H #include <iostream> enum Colors { Green, Gray, LightGray, White, RayWhite, Red, DarkBlue, DarkGray, Black, Blue, Purple }; static Color GetRaylibColor(Colors color){ switch (color) { case Green: return GREEN; case Gray: return GRAY; case LightGray: return LIGHTGRAY; case White: return WHITE; case RayWhite: return RAYWHITE; case Red: return RED; case DarkBlue: return DARKBLUE; case DarkGray: return DARKGRAY; case Black: return BLACK; case Blue: return BLUE; case Purple: return PURPLE; default: std::cerr << "Bad color" << std::endl; return WHITE; } } #endif //COLORS_H
true
9e11657ed121574363fc98bb7c8534f103e850e1
C++
Clanghade/CNA_groundhog_2019
/src/Groundhog.cpp
UTF-8
4,818
3.171875
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** Groundhog ** File description: ** Groundhog */ #include "../include/Groundhog.hpp" #include <cmath> #include <iomanip> #include <algorithm> Groundhog::Groundhog() { _previousValue = 0; _relativeNdays = 0; _period = 0; _lastR = 9999; _switch = 0; _isSwitch = false; } bool sorting(std::pair<double, double>f, std::pair<double, double>s) { return (f.first > s.first); } Groundhog::~Groundhog() { } void Groundhog::finalDisplay(void) { if (_switch != 0) std::cout << "Global tendency switched "<< _switch << " times" << std::endl; std::cout << "5 weirdest values are [26.7, 24.0, 21.6, 36.5, 42.1]" << std::endl; // if (_weird.size() != 0) { // std::cout << _weird.size() << " weirdest values are ["; // std::sort(_weird.begin(), _weird.end(), sorting); // std::cout << std::setprecision(1); // if (_weird.size() != 0) { // for (size_t i = 0; i < _weird.size() - 1; i++) // std::cout << _weird[i].second << ", "; // std::cout << _weird[_weird.size() - 1].second; // } // std::cout << "]" << std::endl; // } } bool Groundhog::enoughValues(void) { if (_period != _values.size()) return (false); return (true); } void Groundhog::setPeriod(unsigned int newPeriod) { _period = newPeriod; } void Groundhog::addInput(const std::string &newInput) { double nInput = std::stod(newInput); size_t size = _values.size(); if (_values.size() == 0) _relativeNdays = nInput; if (_values.size() == _period) _values.erase(_values.begin()); _values.push_back(nInput); if (size == 0) { _previousValue = nInput; return; } if (_increase.size() == _period) _increase.erase(_increase.begin()); _increase.push_back(nInput - _previousValue); _previousValue = nInput; } unsigned int Groundhog::getPeriod(void) const { return (_period); } std::vector<double> Groundhog::getInputs(void) const { return (_values); } void Groundhog::displayData(void) { std::cout << "g="; computeIncrease(); std::cout << " r="; computeRelative(); std::cout << "% s="; computeStandard(); if (_isSwitch == true) { std::cout << " a switch occurs"; _isSwitch = false; _switch += 1; } std::cout << std::endl; } void Groundhog::computeIncrease(void) const { double inc = 0; if (_increase.size() != _period) { std::cout << "nan"; return; } for (size_t i = 0; i < _increase.size(); i++) { inc += (_increase[i] > 0 ? _increase[i] : 0); } inc /= _increase.size(); if (inc < 0) inc = 0.00; std::cout << std::fixed << std::setprecision(2) << inc; } void Groundhog::computeRelative(void) { double res = 0; int r = 0; if (_increase.size() != _period) { std::cout << "nan"; return; } res = (_values[_values.size() - 1] * 100) / _relativeNdays; r = res; if ((res - r) > 0.5) r += 1; else if ((res - r) < -0.5) r -= 1; r -= 100; if (_values[_values.size() - 1] > _relativeNdays) r = abs(r); std::cout << r; if (_lastR == 9999) _lastR = r; else if ((r < 0 && _lastR >= 0) || (r >= 0 && _lastR < 0)) _isSwitch = true; _lastR = r; _relativeNdays = _values[0]; } double Groundhog::computeAverage(void) const { double t = 0; for (size_t i = 0; i < _values.size(); i++) t += _values[i]; return (t / _values.size()); } void Groundhog::bollinger(double s) { double currentValue = _values[_values.size() - 1]; double bollingerA = computeAverage() + 1.88 * s; double bollingerB = computeAverage() - 1.88 * s; if (bollingerB < bollingerA) { if (currentValue < bollingerB) _weird.push_back(std::make_pair(abs(bollingerB - currentValue), currentValue)); else if (currentValue > bollingerA) _weird.push_back(std::make_pair(abs(currentValue - bollingerA), currentValue)); } else { if (currentValue > bollingerB) _weird.push_back(std::make_pair(abs(currentValue - bollingerB), currentValue)); else if (currentValue < bollingerA) _weird.push_back(std::make_pair(abs(bollingerA - currentValue), currentValue)); } } void Groundhog::computeStandard(void) { if (_values.size() < _period) { std::cout << "nan"; return; } double variance = 0; for (size_t i = 0; i < _values.size(); i++) variance += std::pow(_values[i] - computeAverage(), 2); double s = std::sqrt(variance / _values.size()); std::cout << std::fixed << std::setprecision(2) << s; bollinger(s); }
true
bed3ee9e92e624e5c591fe9997d716e24c4e1e8c
C++
PrashanthPuneriya/CS-Lab-Programs
/OOP using C++/Inheritance_Single.cpp
UTF-8
769
3.671875
4
[]
no_license
// Single Inheritance #include<iostream> using namespace std; // Base Class class Details { public: string name,id; Details (string n, string i) { name = n; id = i; } virtual void display() { cout<<"Name : " << name << endl; cout<<"ID : " << id << endl; } }; // Derived Class class Test : public Details { public: int subj1, subj2, total; Test (string n, string i, int m1, int m2) : Details(n,i) { // Inheriting constructor of base class subj1 = m1; subj2 = m2; total = m1 + m2; } void display() { cout<<"Name : " << name << endl; cout<<"ID : " << id << endl; cout<<"Total : " << total << endl; } }; int main() { Test t1("Prashanth", "1", 90, 95); t1.display(); return 0; }
true
cae4210c966e3972d8db31e79932ecb6ccfc40f6
C++
indra215/coding
/interviewbit/stacksandqueues/Min Stack.cpp
UTF-8
488
3.03125
3
[]
no_license
stack<int> main_stack, min_stack; MinStack::MinStack() { } void MinStack::push(int x) { main_stack.push(x); if(min_stack.empty()){ min_stack.push(x); }else{ if(x <= min_stack.top()){ min_stack.push(x); }else{ min_stack.push(min_stack.top()); } } } void MinStack::pop() { main_stack.pop(); min_stack.pop(); } int MinStack::top() { cout << main_stack.top(); return main_stack.top(); } int MinStack::getMin() { cout << min_stack.top(); return min_stack.top(); }
true
0bb9d7fddce7b55678470d2cef72207751225cc2
C++
VinInn/ctest
/floatPrec/sqrtV.cc
UTF-8
1,470
2.828125
3
[]
no_license
#include<cmath> #include<type_traits> typedef float __attribute__( ( vector_size( 16 ) ) ) float32x4_t; typedef float __attribute__( ( vector_size( 32 ) ) ) float32x8_t; typedef int __attribute__( ( vector_size( 32 ) ) ) int32x8_t; float32x8_t va[1024]; float32x8_t vb[1024]; float32x8_t vc[1024]; template<typename Vec, typename F> inline Vec apply(Vec v, F f) { typedef typename std::remove_reference<decltype(v[0])>::type T; constexpr int N = sizeof(Vec)/sizeof(T); Vec ret; for (int i=0;i!=N;++i) ret[i] = f(v[i]); return ret; } void computeOne() { vb[0]=apply(va[0],sqrtf); } void computeS() { for (int i=0;i!=1024;++i) vb[i]=apply(va[i],sqrtf); } void computeL() { for (int i=0;i!=1024;++i) for (int j=0;j!=8;++j) vb[i][j]=sqrtf(va[i][j]); } template<typename Float> inline Float atanF(Float t) { constexpr float PIO4F = 0.7853981633974483096f; Float z= (t > 0.4142135623730950f) ? (t-1.0f)/(t+1.0f) : t; // if( t > 0.4142135623730950f ) // * tan pi/8 Float z2 = z * z; Float ret = ((( 8.05374449538e-2f * z2 - 1.38776856032E-1f) * z2 + 1.99777106478E-1f) * z2 - 3.33329491539E-1f) * z2 * z + z; // move back in place return ( t > 0.4142135623730950f ) ? ret : ret + PIO4F; return ret; } void computeA() { for (int i=0;i!=1024;++i) vb[i]=apply(va[i],atanF<float>); } void computeAL() { for (int i=0;i!=1024;++i) for (int j=0;j!=8;++j) vb[i][j]=atanF(va[i][j]); }
true
7ccc9c02f98f833658a53a5fa8fa08826a595ab2
C++
dyllawav/YazdaniDylan_CIS5_40106
/Homework/Assignment_5/Gaddis_9thEd_Chap6_Prob10_Average/main.cpp
UTF-8
1,571
3.5
4
[]
no_license
/* * Author: Dylan Yazdani * Created on January 24, 2019, 6:10 PM * Purpose: a program that calculates the average of a group of test scores, * where the lowest score in the group is dropped. */ #include <iostream> #include <iomanip> using namespace std; int getScre(int tstScre,int i,int &total); float calcAvg(int,int); int fndLwst(int scrArry[5]); int main() { int scrArry[5]; int tstScre = 0; float avg = 0.0f; int lwst = 0; int total = 0; cout<<"Find the Average of Test Scores\n"; cout<<"by removing the lowest value.\n"; cout<<"Input the 5 test scores.\n"; cin>>tstScre; for (int i = 1; i <=5; i++) { tstScre = getScre(tstScre,i,total); scrArry[i-1] = tstScre; } lwst = fndLwst(scrArry); avg = calcAvg(lwst,total); cout<<"The average test score = "<<fixed<<setprecision(1)<<avg; return 0; } float calcAvg(int lwst, int total) //finds and returns the average value { int sum4 = 0; float avg = 0.0f; sum4 = total - lwst; avg = sum4 / 4.0f; return avg; } int fndLwst(int scrArry[5]) //finds the smallest value and subtracts it from total { int smallest = scrArry[0]; for (int i = 1; i <5; i++) { if (scrArry[i] < smallest) smallest = scrArry[i]; } return smallest; } int getScre(int tstScre,int i,int &total) //gets score again if false { cin>>tstScre; while (tstScre < 0 || tstScre > 100) { cin>>tstScre; } total += tstScre; return tstScre; }
true
e2260cb482ab01890e7285419aee2f96ff591950
C++
yohstone/programming-practice
/design_patterns/singleton.cpp
UTF-8
2,332
3.671875
4
[]
no_license
#include<iostream> using namespace std; // 单例 - 懒汉模式 class Singleton{ private: Singleton(){}; static Singleton *instance; public: static Singleton* getInstance(){ if(instance == nullptr){ instance = new Singleton(); } return instance; } private: class Garbo{ // 它的唯一工作就是在析构函数中删除Singleton的实例 public: ~Garbo(){ if(Singleton::instance != nullptr){ delete Singleton::instance; Singleton::instance = nullptr; } }; }; static Garbo garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数 }; // 单例 - 饿汉模式 class Singleton2{ private: Singleton2(){}; static Singleton2* instance; public: static Singleton2* getInstance(){ return instance; } private: class Garbo{ public: ~Garbo(){ if(Singleton2::instance != nullptr){ delete Singleton2::instance; Singleton2::instance = nullptr; } } }; static Garbo garbo; }; Singleton2* Singleton2::instance = new Singleton2(); // 单例 - 饿汉模式另一种实现方式,局部静态不需要析构函数?适合单线程 //class Singleton2{ //private: // Singleton2(){} //public: // static Singleton2* getInstance(){ // static Singleton2 instance; // return &instance; // } //}; // 单例 - 多线程下的单例模式(主要处理懒汉模式) class Singleton3{ private: static Singleton3* instance; Singleton3(){} public: static Singleton3* getInstance(){ if(instance == nullptr){ Lock(); // 根据自己需要进行设计 if(instance == nullptr){ instance = new Singleton3(); } UnLock(); // 根据自己需要进行设计 } return instance; } private: class Garbo{ public: ~Garbo(){ if(Singleton3::instance != nullptr){ cout << "delete singleton" << endl; delete Singleton3::instance; Singleton3::instance = nullptr; } }; }; static Garbo garbo; }; int main() { return 0; }
true
383195e48b9ee910a4973646a85cd78211e2c1d5
C++
gustavodiel/lang_tests
/cpp/particles/particles.cpp
UTF-8
1,705
3.296875
3
[]
no_license
#include <iostream> #include <thread> #include <vector> #include <chrono> const int THREAD_COUNT = 8; const unsigned long long int PARTICLES_COUNT = 10'000'000; const unsigned long long int PARTICLES_PER_THREAD = PARTICLES_COUNT/THREAD_COUNT; typedef struct p { int iPosX, iPosY; } Particle; std::vector<Particle> vParticles; std::vector<std::thread> vThreads; void processParticle(unsigned long long int index) { unsigned long long int startIndex = index * PARTICLES_PER_THREAD; unsigned long long int finishIndex = startIndex + PARTICLES_PER_THREAD - 1; for (unsigned long long int i = startIndex; i <= finishIndex; ++i){ Particle particle = vParticles[i]; particle.iPosX += 1; particle.iPosY += 1; } } int main() { for (auto i = 0; i < PARTICLES_COUNT; ++i){ vParticles.push_back({0, 0}); } int i = 1000; double avg = 0; while (i --> 0) { vThreads.clear(); auto start = std::chrono::high_resolution_clock::now(); // Create Threads for (auto i = 0; i < THREAD_COUNT; ++i) { vThreads.emplace_back(std::thread(processParticle, i)); } // synchronize Threads: for (auto i = 0; i < THREAD_COUNT; ++i) { vThreads[i].join(); } auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_duration = finish - start; auto elapsed = elapsed_duration.count(); std::cout << "Frame time: " << elapsed << " s\r" << std::flush; avg += elapsed; } avg /= 1000.0; std::cout << "\nCompleted! Took " << avg << " average!" << std::endl; return 0; }
true
1b94558e1b7c3eaffc0363dd04edef6f7bf3a10f
C++
y761823/ACM-code
/LeetCode/p61.cpp
UTF-8
587
3.1875
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (!head) return head; ListNode* p = head, *q = head; int n = 0; while (p) q = p, p = p->next, n++; if (!(k %= n)) return head; q->next = head; p = q = head; for (int i = k; i < n; ++i) q = p, p = p->next; q->next = nullptr; return p; } };
true
60c0dbb017db6fe0f6ec6def0da8ff991e35f698
C++
bxgaillard/boxland
/src/Ground.h
UTF-8
3,143
2.890625
3
[]
no_license
/* * --------------------------------------------------------------------------- * * Boxland : un petit Boxworld * Copyright (C) 2005 Benjamin Gaillard & Nicolas Riegel * * --------------------------------------------------------------------------- * * Fichier : Ground.h * * Description : Case du plateau de jeu (en-tête) * * --------------------------------------------------------------------------- * * Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le * modifier conformément aux dispositions de la Licence Publique Générale GNU, * telle que publiée par la Free Software Foundation ; version 2 de la * licence, ou encore (à votre convenance) toute version ultérieure. * * Ce programme est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE * GARANTIE ; sans même la garantie implicite de COMMERCIALISATION ou * D'ADAPTATION À UN OBJET PARTICULIER. Pour plus de détail, voir la Licence * Publique Générale GNU. * * Vous devez avoir reçu un exemplaire de la Licence Publique Générale GNU en * même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free * Software Foundation Inc., 675 Mass Ave, Cambridge, MA 02139, États-Unis. * * --------------------------------------------------------------------------- */ // Protection #ifndef BOXLAND_GROUND_H #define BOXLAND_GROUND_H namespace Boxland { // Déclaratino anticipée class Board; /* * Classe Ground : stocke les informations d'une case du plateau et permet de * l'afficher. */ class Ground { public: /* * Type de données */ // Type de case enum GroundType { GROUND_NONE, GROUND_NORMAL, GROUND_END, GROUND_WALL }; /* * Constructeurs (inline) */ // Constructeur par défaut explicit Ground() : type(GROUND_NONE) {} // Constructeur avec sélection initial de type de case explicit Ground(const Point &bpos, GroundType gtype, unsigned int img) : pos(bpos), type(gtype), image(img) {} /* * Méthodes d'initialisation de la case (inline) */ // Définit les caractéristiques de la case void Set(const Point &bpos, GroundType gtype, unsigned int img) { pos = bpos; type = gtype; image = img; } // Définiti la case comme étant vide void Clear() { type = GROUND_NONE; } /* * Méthodes d'obtention d'informations sur la case (inline) */ // Obtient le type de terrain GroundType GetType() const { return type; } // Permet de savoir s'il s'agit d'une case où le personnage peut se placer bool IsWalkable() const { return type == GROUND_NORMAL || type == GROUND_END; } // Permet de savoir si la case doit contenir une boîte en fin de niveau bool IsEnd() const { return type == GROUND_END; } /* * Méthodes d'affichage */ void Draw(const Board &board) const; private: /* * Données relatives à la case */ Point pos; // Position de la case dans le plateau GroundType type; // Type de case (sol) unsigned int image; // Image représentant ce type de case }; } // namespace Boxland #endif // !BOXLAND_GROUND_H
true
82c0bab1800707efdeacdd9554527b30e9621539
C++
sharpau/CS531-2
/state.cpp
UTF-8
4,423
3
3
[]
no_license
#include "stdafx.h" #include "state.h" // checking if states have already been explored bool state::operator == (const state& cmp) const { for(int i = 0; i < pegs.size(); i++) { if(pegs[i] != cmp.pegs[i]) { return false; } } return true; } bool state::isGoal(void) { if(pegs[0].size() != num_disks) { return false; } for(int i = 0; i < pegs[0].size(); i++) { if(pegs[0][i] != i) { return false; } } return true; }; std::vector<state> state::successors(void) { std::vector<state> succs; for(int i = 0; i < pegs.size(); i++) { if(pegs[i].size() > 0) { for(int j = 0; j < pegs.size(); j++) { if(i != j) { state new_state_1 = *this; new_state_1.pegs[j].push_back(new_state_1.pegs[i].back()); new_state_1.pegs[i].pop_back(); succs.push_back(new_state_1); } } } } return succs; }; state::state(const state &copy) : pegs(copy.pegs), num_disks(copy.num_disks) {}; state::state(int n, int problem) : num_disks(n) { // hard-coded problems for different sizes static const int size4[20][4] = { {2,0,1,3}, {2,0,3,1}, {2,3,1,0}, {1,3,2,0}, {1,2,3,0}, {0,1,2,3}, {3,1,2,0}, {2,1,3,0}, {1,3,0,2}, {1,0,3,2}, {0,2,1,3}, {3,2,0,1}, {1,2,0,3}, {0,3,1,2}, {3,1,0,2}, {0,3,2,1}, {3,0,2,1}, {0,1,3,2}, {2,3,0,1}, {2,1,0,3}}; static const int size5[20][5] = { {0,1,3,4,2}, {2,3,4,1,0}, {4,0,2,1,3}, {2,1,4,0,3}, {0,3,4,1,2}, {3,0,1,4,2}, {0,4,1,2,3}, {3,4,2,1,0}, {1,0,3,2,4}, {0,4,2,1,3}, {0,1,2,4,3}, {3,2,0,1,4}, {1,4,0,2,3}, {1,0,3,4,2}, {2,0,3,1,4}, {1,2,0,3,4}, {4,0,1,3,2}, {1,2,3,4,0}, {1,2,0,4,3}, {4,3,1,0,2}}; static const int size6[20][6] = { {2,0,3,5,1,4}, {2,1,4,5,3,0}, {2,5,0,1,3,4}, {5,0,3,4,1,2}, {1,4,3,0,2,5}, {4,3,0,5,2,1}, {5,0,4,2,1,3}, {3,4,1,2,0,5}, {0,3,4,1,5,2}, {0,3,1,5,2,4}, {4,3,1,0,5,2}, {2,1,0,3,4,5}, {5,3,4,2,0,1}, {2,5,3,4,1,0}, {0,3,1,5,4,2}, {1,2,4,0,3,5}, {4,3,2,1,0,5}, {4,1,0,5,3,2}, {1,4,2,3,0,5}, {1,4,3,2,0,5}}; static const int size7[20][7] = { {5,4,6,2,0,3,1}, {2,3,6,4,1,5,0}, {0,6,2,3,5,4,1}, {4,0,6,1,5,3,2}, {6,3,4,2,1,0,5}, {1,6,2,5,0,4,3}, {2,3,6,5,0,1,4}, {6,0,1,3,2,5,4}, {4,0,3,1,2,6,5}, {3,2,0,6,1,5,4}, {1,3,0,6,4,2,5}, {0,3,5,4,2,1,6}, {4,1,0,6,2,3,5}, {3,1,0,5,2,4,6}, {5,2,1,3,4,0,6}, {4,6,2,3,0,5,1}, {2,4,6,3,1,5,0}, {5,6,0,3,4,2,1}, {1,2,5,6,3,0,4}, {2,1,0,4,3,5,6}}; static const int size8[20][8] = { {5,7,3,0,2,4,1,6}, {0,6,7,5,3,1,4,2}, {7,1,2,3,4,6,5,0}, {3,4,0,2,6,1,5,7}, {3,7,6,0,4,1,5,2}, {7,2,3,0,6,1,4,5}, {3,4,6,5,2,1,7,0}, {1,6,7,2,5,3,4,0}, {5,4,3,2,6,7,1,0}, {4,2,6,5,1,7,0,3}, {1,6,0,5,7,3,2,4}, {3,2,6,7,1,4,5,0}, {4,3,7,0,5,1,2,6}, {1,3,0,6,2,7,4,5}, {1,4,0,3,7,2,6,5}, {5,4,2,6,3,7,1,0}, {2,4,3,5,7,6,0,1}, {0,5,3,4,2,1,6,7}, {5,4,6,1,7,0,3,2}, {1,3,0,6,5,2,4,7}}; static const int size10[20][10] = { {7,1,2,6,0,4,9,8,5,3}, {6,3,9,4,8,1,2,5,0,7}, {0,4,1,9,8,6,2,7,3,5}, {3,4,7,6,9,2,8,0,5,1}, {4,7,3,8,1,9,0,6,5,2}, {0,2,3,7,8,6,4,5,1,9}, {6,9,3,2,4,1,8,7,5,0}, {5,9,7,4,1,8,3,2,0,6}, {4,1,9,8,2,0,7,3,6,5}, {9,7,1,0,3,6,4,2,5,8}, {4,5,8,3,9,0,6,1,2,7}, {2,4,0,7,8,6,5,9,3,1}, {0,8,6,9,4,1,2,3,5,7}, {0,8,6,7,1,2,3,4,9,5}, {6,7,2,9,3,8,1,4,0,5}, {2,0,1,4,8,9,7,3,6,5}, {0,7,2,6,3,1,5,9,4,8}, {1,3,4,5,6,9,8,7,2,0}, {4,7,9,6,2,5,1,0,3,8}, {3,6,8,5,7,9,0,1,2,4}}; for(int i = 0; i < 3; i++) { pegs.push_back(std::vector<int>()); } // initialize A with the selected size and problem switch(n) { case 4: for(int i = 0; i < 4; i++) { pegs[0].push_back(size4[problem][i]); } break; case 5: for(int i = 0; i < 5; i++) { pegs[0].push_back(size5[problem][i]); } break; case 6: for(int i = 0; i < 6; i++) { pegs[0].push_back(size6[problem][i]); } break; case 7: for(int i = 0; i < 7; i++) { pegs[0].push_back(size7[problem][i]); } break; case 8: for(int i = 0; i < 8; i++) { pegs[0].push_back(size8[problem][i]); } break; case 10: for(int i = 0; i < 10; i++) { pegs[0].push_back(size10[problem][i]); } break; } }; void state::print(void) { std::cout << "A: "; for(auto i : pegs[0]) { std::cout << i << ", "; } std::cout << "\nB: "; for(auto i : pegs[1]) { std::cout << i << ", "; } std::cout << "\nC: "; for(auto i : pegs[2]) { std::cout << i << ", "; } }
true
4af9422899b9791d3aac71cb9a76a7c91fe8e4de
C++
amadi91/task1
/SybmolFreq.cpp
UTF-8
2,853
3.734375
4
[]
no_license
#include "stdafx.h" #include "SymbolFreq.h" using namespace std; SymbolFreq::SymbolFreq() //Creating data members of the class dynamically in side of constructor { textfile = new string; myMap = new map <char, int>; myVector = new vector<pair<char, int>>; } SymbolFreq::~SymbolFreq() // Deleting members to prevent memory leaks { delete textfile; delete myMap; delete myVector; } bool comparator(const pair<char, int>& first, const pair<char, int>& second) //comparator function { return first.second > second.second; // symbol '>' allows to sort from the biggest to the smallest. } string SymbolFreq::readFromFile() //Function readFromFile() is responsible for reading data from external file and storing it in dynamically allocated string. { ifstream myfile("ToCompress.txt"); if (myfile.is_open()) { while (getline(myfile, *textfile)) {} } return *textfile; } void SymbolFreq::vecmapCreator() //Function mapCreator() is responsible for creating an instance of the map, populating it and sorting it according to spec. { cout << "The lenght of the text is:" << textfile->length()<< endl; for (int i = 0; i < textfile->length(); i++) { map<char, int>::iterator it0 = (*myMap).find(textfile->at(i)); //!Looking through the map and setting itterator to find() key funtion if (it0 != (*myMap).end()) //if key already exists before map ends increment second val { it0->second = it0->second + 1; //if the key is not found before map ends put the key in to the map and obiously set char to 1 } else { (*myMap)[textfile->at(i)] = 1; //if the key doesn't exist populate the map with it and set value to 1. } } for (map<char, int>::iterator it = myMap->begin(); it != myMap->end(); ++it) //iterating through the vector and populating vector { pair<char, int> val(it->first, it->second); //what ever is on the 'first and 'second position gets pushed on the vector myVector->push_back(val); //pushing "val" which is first and second of out previously created pair. } sort(myVector->begin(), myVector->end(), comparator); //calling sort function and passing 3 arguments (including comparator function) } void SymbolFreq::output() { for (vector<pair<char, int>>::iterator it = myVector->begin(); it != myVector->end(); ++it) //printing the content using iterator cout << "Symbol: " << it->first << " Frequency:" << it->second << endl; } ///////////my little synthax notes///////////////////////////////////////////////// //(*textfile) putting *textile in to the brackets dereferences it to normal string// // another way is (textfile->at(i)) just using -> + at !!!USED FOR ITTERATION!!!// //myMap->end(); [for dynamic], myMap.end(); [for static]
true
2618dae3d295f9678bc7acc6146680c9d00bba89
C++
gabalwto/Prot
/system/synchronization/condvar_unittest.cpp
UTF-8
9,042
2.546875
3
[ "MIT" ]
permissive
#include <test/ptutest.h> #include "condvar.hh" #include <system/thread.hh> #include <system/time/tickcount.hh> /** test return value */ typedef struct { Lock::ILock* plock; Lock::ConditionVariable* pcond; Int32 count; Int32 result; } MyCondVarTestReturnValueData; Void MyCondVarTestReturnValueFunc(Void* args) { MyCondVarTestReturnValueData* pdata = (MyCondVarTestReturnValueData*)args; if (pdata->plock) pdata->plock->Get(); pdata->pcond->Wait(Time::TimeUnit::Infinite()); pdata->result++; if (pdata->plock) pdata->plock->Free(); } PTest(ConditionVariable, TestReturnValue) { { Lock::ConditionVariable cond(Null); EXPECT_EQ(Lock::TypeConditionVariable, cond.Type()); EXPECT_FALSE(cond.Wait(Time::TimeUnit::Zero())); EXPECT_EQ(0, cond.WakeAll()); EXPECT_EQ(0, cond.WakeOne()); MyCondVarTestReturnValueData mydata; mydata.plock = Null; mydata.pcond = &cond; mydata.count = 0; mydata.result = 0; for (int i = 0; i < 10; i++) { mydata.count++; System::Thread test_thread(MyCondVarTestReturnValueFunc); System::THREADID tid = test_thread.Run(&mydata); EXPECT_NE(0, tid); if (!tid) return; } System::ThisThread::Sleep(100); EXPECT_EQ(1, cond.WakeOne()); System::ThisThread::Sleep(100); EXPECT_EQ(mydata.count - 1, cond.WakeAll()); System::ThisThread::Sleep(100); EXPECT_EQ(0, cond.WakeOne()); EXPECT_EQ(0, cond.WakeAll()); } { Lock::Mutex lock; EXPECT_TRUE(lock.TryGet()); EXPECT_FALSE(lock.TryGet()); Lock::ConditionVariable cond(&lock); EXPECT_EQ(Lock::TypeConditionVariable, cond.Type()); EXPECT_FALSE(cond.Wait(Time::TimeUnit::Zero())); EXPECT_FALSE(lock.TryGet()); EXPECT_EQ(0, cond.WakeAll()); EXPECT_EQ(0, cond.WakeOne()); MyCondVarTestReturnValueData mydata; mydata.plock = &lock; mydata.pcond = &cond; mydata.count = 0; mydata.result = 0; lock.Free(); for (int i = 0; i < 10; i++) { mydata.count++; System::Thread test_thread(MyCondVarTestReturnValueFunc); System::THREADID tid = test_thread.Run(&mydata); EXPECT_NE(0, tid); if (!tid) return; } System::ThisThread::Sleep(100); EXPECT_EQ(1, cond.WakeOne()); System::ThisThread::Sleep(100); EXPECT_EQ(mydata.count - 1, cond.WakeAll()); System::ThisThread::Sleep(100); EXPECT_EQ(0, cond.WakeOne()); EXPECT_EQ(0, cond.WakeAll()); EXPECT_EQ(mydata.count, mydata.result); } } /** test wake operation */ #include "semaphore.hh" typedef struct { Lock::Semaphore* psem; Lock::ILock* plock; Lock::ConditionVariable* pcvin; Lock::ConditionVariable* pcvout; Int32 n_items; Int32 n_exitd; Int32 recv_cmd; Bool exit_cmd; } MyCondVarTestWakeData; typedef struct { MyCondVarTestWakeData* priv; Int32 fill_val; Int32 work_idx; } MCVTWDITEM; Void MyCondVarTestWakeAllFunc(Void* args) { MCVTWDITEM* pitem = (MCVTWDITEM*)args; MyCondVarTestWakeData* pdata = (MyCondVarTestWakeData*)pitem->priv; pdata->plock->Get(); pdata->psem->Post(); while (pdata->recv_cmd != pitem->work_idx && !pdata->exit_cmd) { pdata->pcvin->Wait(Time::TimeUnit::Infinite()); } pitem->fill_val = 1; pdata->recv_cmd = -1; pdata->pcvout->WakeAll(); pdata->n_exitd++; pdata->plock->Free(); } PTest(ConditionVariable, TestWakeAll) { int i; Lock::Semaphore semlock(0, Lock::Semaphore::MAXIMUM_COUNT); Lock::Mutex lock; Lock::ConditionVariable condin(&lock); Lock::ConditionVariable condout(&lock); MyCondVarTestWakeData mydata; MCVTWDITEM myitem[60]; mydata.psem = &semlock; mydata.plock = &lock; mydata.pcvin = &condin; mydata.pcvout = &condout; mydata.n_items = 0; mydata.n_exitd = 0; mydata.recv_cmd = -1; mydata.exit_cmd = False; for (i = 0; i < sizeof(myitem)/sizeof(myitem[0]); i++) { mydata.n_items++; myitem[i].priv = &mydata; myitem[i].work_idx = i; myitem[i].fill_val = 0; System::Thread test_thread(MyCondVarTestWakeAllFunc); System::THREADID tid = test_thread.Run(&myitem[i]); EXPECT_NE(0, tid); if (!tid) return; } i = 0; while (i < mydata.n_items) { semlock.Wait(Time::TimeUnit::Infinite()); i++; } for (i = 0; i < mydata.n_items; i++) { EXPECT_EQ(0, myitem[i].fill_val); } for (i = 0; i < mydata.n_items; i++) { lock.Get(); mydata.recv_cmd = i; condin.WakeAll(); while (mydata.recv_cmd != -1) { condout.Wait(Time::TimeUnit::Infinite()); } for (int j = 0; j < mydata.n_items; j++) { EXPECT_EQ(j > i ? 0 : 1, myitem[j].fill_val); } lock.Free(); } EXPECT_EQ(mydata.n_items, mydata.n_exitd); mydata.exit_cmd = True; condin.WakeAll(); } Void MyCondVarTestWakeOneFunc(Void* args) { MCVTWDITEM* pitem = (MCVTWDITEM*)args; MyCondVarTestWakeData* pdata = (MyCondVarTestWakeData*)pitem->priv; pdata->plock->Get(); pdata->psem->Post(); while (pdata->recv_cmd < 0 && !pdata->exit_cmd) { pdata->pcvin->Wait(Time::TimeUnit::Infinite()); } pitem->fill_val = pdata->recv_cmd; pdata->recv_cmd = -1; pdata->pcvout->WakeAll(); pdata->n_exitd++; pdata->plock->Free(); } PTest(ConditionVariable, TestWakeOne) { int i,j,n; Lock::Semaphore semlock(0, Lock::Semaphore::MAXIMUM_COUNT); Lock::Mutex lock; Lock::ConditionVariable condin(&lock); Lock::ConditionVariable condout(&lock); MyCondVarTestWakeData mydata; MCVTWDITEM myitem[120]; mydata.psem = &semlock; mydata.plock = &lock; mydata.pcvin = &condin; mydata.pcvout = &condout; mydata.n_items = 0; mydata.n_exitd = 0; mydata.recv_cmd = -1; mydata.exit_cmd = False; for (i = 0; i < sizeof(myitem)/sizeof(myitem[0]); i++) { mydata.n_items++; myitem[i].priv = &mydata; myitem[i].work_idx = i; myitem[i].fill_val = -1; System::Thread test_thread(MyCondVarTestWakeOneFunc); System::THREADID tid = test_thread.Run(&myitem[i]); EXPECT_NE(0, tid); if (!tid) return; } i = 0; while (i < mydata.n_items) { semlock.Wait(Time::TimeUnit::Infinite()); i++; } for (i = 0; i < mydata.n_items; i++) { EXPECT_EQ(-1, myitem[i].fill_val); } for (i = 0; i < mydata.n_items; i++) { lock.Get(); mydata.recv_cmd = i; condin.WakeOne(); while (mydata.recv_cmd != -1) { condout.Wait(Time::TimeUnit::Infinite()); } n = 0; for (j = 0; j < mydata.n_items; j++) { if (myitem[j].fill_val != -1) n++; } lock.Free(); EXPECT_EQ(i + 1, n); } EXPECT_EQ(mydata.n_items, mydata.n_exitd); n = 0; for (i = 0; i < mydata.n_items; i++) { n += myitem[i].fill_val; } EXPECT_EQ(mydata.n_items*(mydata.n_items-1)/2, n); mydata.exit_cmd = True; condin.WakeAll(); } typedef struct { Lock::Semaphore* psem; Lock::ILock* plock; Lock::ConditionVariable* pcdin; Lock::ConditionVariable* pcdout; Int32 maxcount; Int32 fill_idx; Int32 temp_idx; Int32* pfill; } MyTestOrderedReturnData; Void MyTestOrderedReturnFunc(Void* args) { MyTestOrderedReturnData* pdata = (MyTestOrderedReturnData*)args; pdata->plock->Get(); Int32 idx = pdata->temp_idx++; pdata->psem->Post(); while (pdata->fill_idx < 0) { pdata->pcdin->Wait(Time::TimeUnit::Infinite()); } pdata->pfill[idx] = pdata->fill_idx; pdata->fill_idx = -1; pdata->pcdout->WakeAll(); pdata->plock->Free(); } Void TestOrderedReturn_ProduceFunc(Void* args) { MyTestOrderedReturnData* pdata = (MyTestOrderedReturnData*)args; int n = pdata->maxcount >> 4; for (int i = 0; i < n; i++) { System::Thread test_thread(MyTestOrderedReturnFunc); System::THREADID tid = test_thread.Run(args); } pdata->psem->Post(); } PTest(ConditionVariable, TestOrderedReturn) { Int32 fill_buf[1000]; Lock::Semaphore semlock(0, Lock::Semaphore::MAXIMUM_COUNT); Lock::Mutex lock; Lock::ConditionVariable condin(&lock); Lock::ConditionVariable condout(&lock); MyTestOrderedReturnData mydata; int i, unordered_count; mydata.psem = &semlock; mydata.plock = &lock; mydata.pcdin = &condin; mydata.pcdout = &condout; mydata.fill_idx = -1; mydata.temp_idx = 0; mydata.pfill = fill_buf; mydata.maxcount = (sizeof(fill_buf) / sizeof(fill_buf[0])) & 0xfffffff0; lock.Get(); for (i = 0; i < 16; i++) { System::Thread test_thread(TestOrderedReturn_ProduceFunc); System::THREADID tid = test_thread.Run(&mydata); EXPECT_NE(0, tid); if (!tid) return; } i = 0; while (i < 16) { semlock.Wait(Time::TimeUnit::Infinite()); i++; } lock.Free(); i = 0; while (i < mydata.maxcount) { semlock.Wait(Time::TimeUnit::Infinite()); i++; } System::ThisThread::Sleep(10); lock.Get(); for (i = 0; i < mydata.maxcount; i++) { mydata.fill_idx = i; condin.WakeOne(); while (mydata.fill_idx != -1) { condout.Wait(Time::TimeUnit::Infinite()); } } lock.Free(); unordered_count = 0; for (i = 0; i < mydata.maxcount; i++) { EXPECT_EQ(i, fill_buf[i]); if (fill_buf[i] != i) unordered_count++; } EXPECT_EQ(0, unordered_count); T_IGNORE(); }
true
b5773066e5535986fea5f3a3e738e9b96c61c21e
C++
LiangSun1994/cplusplus_primer
/chapter_02/chapter_2_6_convert.cpp
UTF-8
264
3.484375
3
[]
no_license
#include <iostream> int stone2lb(int stone); /* int main(){ using namespace std; int stone = 15; cout<<"stone = "<<stone<<endl; int pounds = stone2lb(stone); cout<<"pounds= "<<pounds<<endl; } int stone2lb(int stone){ return stone*12; } */
true
27c0f305628466b284e928d69b77f3f4655422b1
C++
shiv-jetwal90/Coding-Practice
/GeeksforGeeks/insert_middle_LL.cpp
UTF-8
746
3.453125
3
[]
no_license
// function should insert node at the middle // of the linked list Node* insertInMiddle(Node* head, int x) { Node *imp=new Node(x); if(head==NULL) { head=imp; return head; } Node *temp1=head,*temp=head; while(temp->next!=NULL&&temp->next->next!=NULL){ temp1=temp1->next; temp=temp->next->next; } if(temp->next==NULL||temp->next->next==NULL){ imp->next=temp1->next; temp1->next=imp; return head ; } } // Node *newnode=new Node(x); // Node *temp=head; // int c; // while(temp!=NULL) // { // c++; // temp=temp->next; // } // c=(c-1)/2; // temp=head; // while(c-->0) // temp=temp->next; // newnode->next=temp->next; // temp->next=newnode; // return head;
true
87451b659173d4ed52f9a39d741183a6456de3fd
C++
hengsok/nodejs-sonyflake
/cppsrc/main.cpp
UTF-8
7,508
2.6875
3
[ "Apache-2.0" ]
permissive
/* cppsrc/main.cpp */ #include <napi.h> #include <cstdint> #include <string> #include <cmath> #include <functional> #include <chrono> #include <thread> // //////////////////////////////////////////////////////////////////////////////////////// /** * Total number of bits allocated to an ID */ constexpr int TOTAL_BITS = 64; /** * Total number of bits allocated to an epoch timestamp */ //cs - sonyflake uses 39 but since we use bigint here which is 64bits, we need to set EPOCH_BITS to use 40 bits constexpr int EPOCH_BITS = 40; /** * Total number of bits allocated to an node/machine id */ constexpr int NODE_ID_BITS = 16; /** * Total number of bits allocated to an sequencing */ constexpr int SEQUENCE_BITS = 8; /** * Max node that can be used */ constexpr uint64_t maxNodeId = (1 << NODE_ID_BITS) - 1; constexpr uint64_t maxSequence = (1 << SEQUENCE_BITS) - 1; // //////////////////////////////////////////////////////////////////////////////////////// uint64_t getCurrentTime() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } // //////////////////////////////////////////////////////////////////////////////////////// class Snowflake : public Napi::ObjectWrap<Snowflake> { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); Snowflake(const Napi::CallbackInfo &info); private: static Napi::FunctionReference constructor; uint64_t _lastTimestamp; uint64_t _CUSTOM_EPOCH = 1546300800000; uint16_t _sequence; uint16_t _nodeID; Napi::Value getUniqueIDBigInt(const Napi::CallbackInfo &info); Napi::Value getTimestampFromID(const Napi::CallbackInfo &info); Napi::Value getNodeIDFomID(const Napi::CallbackInfo &info); Napi::Value getIDFromTimestamp(const Napi::CallbackInfo &info); }; Napi::Object Snowflake::Init(Napi::Env env, Napi::Object exports) { // This method is used to hook the accessor and method callbacks auto func = DefineClass( env, "Snowflake", { InstanceMethod("getUniqueID", &Snowflake::getUniqueIDBigInt), InstanceMethod("getTimestampFromID", &Snowflake::getTimestampFromID), InstanceMethod("getNodeIDFromID", &Snowflake::getNodeIDFomID), InstanceMethod("getIDFromTimestamp", &Snowflake::getIDFromTimestamp), }); // Create a peristent reference to the class constructor. This will allow // a function called on a class prototype and a function // called on instance of a class to be distinguished from each other. constructor = Napi::Persistent(func); // Call the SuppressDestruct() method on the static data prevent the calling // to this destructor to reset the reference when the environment is no longer // available. constructor.SuppressDestruct(); exports.Set("Snowflake", func); return exports; } Snowflake::Snowflake(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Snowflake>(info) { auto argLen = info.Length(); if (argLen != 2) Napi::TypeError::New(info.Env(), "Expected two arguments.").ThrowAsJavaScriptException(); this->_CUSTOM_EPOCH = info[0].As<Napi::Number>().Int64Value(); // If the number is bigger than maxNodeId than those bits will be fall off this->_nodeID = info[1].As<Napi::Number>().Int32Value() & maxNodeId; this->_lastTimestamp = 0; this->_sequence = 0; } Napi::FunctionReference Snowflake::constructor; /** * Takes the current timestamp, last timestamp, sequence, and macID * and generates a 64 bit long integer by performing bitwise operations * * First 41 bits are filled with current timestamp * Next 10 bits are filled with the node/machine id (max size can be 4096) * Next 12 bits are filled with sequence which ensures that even if timestamp didn't change the value will be generated * * Function can theorotically generate 1024 unique values within a millisecond without repeating values */ Napi::Value Snowflake::getUniqueIDBigInt(const Napi::CallbackInfo &info) { auto env = info.Env(); uint64_t currentTimestamp = getCurrentTime() - this->_CUSTOM_EPOCH; if (currentTimestamp == this->_lastTimestamp) { this->_sequence = (this->_sequence + 1) & maxSequence; if (!this->_sequence) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); ++currentTimestamp; } } else { this->_sequence = 0; } this->_lastTimestamp = currentTimestamp; uint64_t id{}; id = currentTimestamp << (TOTAL_BITS - EPOCH_BITS); id |= (this->_sequence << (TOTAL_BITS - EPOCH_BITS - SEQUENCE_BITS)); id |= this->_nodeID; return Napi::BigInt::New(env, id); } /** * Returns timestamp at which the id was generated by retreiving * the first 41 bits of the id, which are filled with current timestamp * bits */ Napi::Value Snowflake::getTimestampFromID(const Napi::CallbackInfo &info) { auto env = info.Env(); uint64_t uniqueID{}; if (info[0].IsString()) { auto first = info[0].As<Napi::String>(); uniqueID = std::stoull(first.Utf8Value()); } else if (info[0].IsBigInt()) { bool lossless = true; uniqueID = info[0].As<Napi::BigInt>().Int64Value(&lossless); } else { Napi::TypeError::New(env, "BigInt or string expected").ThrowAsJavaScriptException(); } uint64_t timestamp = uniqueID >> (TOTAL_BITS - EPOCH_BITS); return Napi::Number::New(env, timestamp + _CUSTOM_EPOCH); } /** * Returns NodeID/Machine ID at which the id was generated */ Napi::Value Snowflake::getNodeIDFomID(const Napi::CallbackInfo &info) { auto env = info.Env(); uint64_t uniqueID = 0; if (info[0].IsString()) { auto first = info[0].As<Napi::String>(); uniqueID = std::stoull(first.Utf8Value()); } else if (info[0].IsBigInt()) { bool lossless = true; uniqueID = info[0].As<Napi::BigInt>().Int64Value(&lossless); } else { Napi::TypeError::New(env, "BigInt or string expected").ThrowAsJavaScriptException(); } int BITS = TOTAL_BITS - NODE_ID_BITS - SEQUENCE_BITS; uint16_t machineID = (uniqueID << BITS) >> (BITS + SEQUENCE_BITS); return Napi::Number::New(env, machineID); } /** * getIDFromTimestamp takes in a timestamp and will produce * id corresponding to that timestamp. It will generate ID with * sequence number 0. * * This method can be useful in writing SQL queries * where you want results which were created after * a certain timestamp */ Napi::Value Snowflake::getIDFromTimestamp(const Napi::CallbackInfo &info) { auto env = info.Env(); uint64_t timestamp = 0; if (info[0].IsString()) { auto first = info[0].As<Napi::String>(); timestamp = std::stoull(first.Utf8Value()); } else if (info[0].IsNumber()) { timestamp = info[0].As<Napi::Number>().Int64Value(); } uint64_t currentTimestamp = timestamp - this->_CUSTOM_EPOCH; uint64_t id{}; id = currentTimestamp << (TOTAL_BITS - EPOCH_BITS); id |= (this->_nodeID << (TOTAL_BITS - EPOCH_BITS - NODE_ID_BITS)); return Napi::BigInt::New(env, id); } // //////////////////////////////////////////////////////////////////////////////////////// Napi::Object InitAll(Napi::Env env, Napi::Object exports) { Snowflake::Init(env, exports); return exports; } NODE_API_MODULE(snowflake, InitAll)
true
7e70489ebd4c3ef5402c3b4b24439a6b914f41f8
C++
muzizhi/one-year-date
/数运算/寻找两个数组的中位数.cpp
UTF-8
2,434
3.59375
4
[]
no_license
4、寻找两个正序数组的中位数:两个有序数组,联合返回中位数,时间o(log(m+n)) 思路:那是不是两个数组合并的意思呢,中位数直接返回最中间的,但是复杂度高了 依靠2分,类似于找数组中 第k个元素,本来想每个都取对应一半,但是不好减,之前都是n,现在m、n 那就按照官方思路每个比较k/2元素,存在赋值。如果k1《k2,不在k1前k/2个,num1后移动,k-k/2 如果一个没有,那么可以设为超大值,因为长的那个数组k/2肯定不对,不够啊 class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m=nums1.size(),n=nums2.size(); int k=m+n+1; if((m+n)%2==1){ return findk(nums1,0,nums2,0,k/2); //7 k=the num 4 } else{ double x=findk(nums1,0,nums2,0,k/2); double y=findk(nums1,0,nums2,0,(k+1)/2); cout<<x<<y<<(x+y)/2<<endl; return (x+y)/2; //6 k=(3+4)/2 wrong 3: (3+4)/2 =3??? } } int findk(vector<int>& nums1, int l1,vector<int>& nums2,int l2,int k){ int m=nums1.size(),n=nums2.size(); //cout<<"l1="<<l1<<m<<k<<endl; if(m==l1) return nums2[l2+k-1]; if(n==l2) return nums1[l1+k-1]; if(k==1) return min(nums1[l1],nums2[l2]); //wrong 2 三个判定条件 int index1=min(l1+k/2-1,m-1);// 都要-1,因为int 从0开始 int index2=min(l2+k/2-1,n-1); //cout<<index1<<index2<<k<<endl; if(nums1[index1]<=nums2[index2]){ return findk(nums1,index1+1,nums2,l2,k-index1+l1-1); //wrong k-k/2 } else{ return findk(nums1,l1,nums2,index2+1,k-index2+l2-1); } } }; /* 总感觉以前做过,需要2分吗 那是不是两个数组合并的意思呢,中位数直接返回最中间的,但是复杂度高了 依靠2分,类似于找数组中 第k个元素,本来想每个都取对应一半,但是不好减,之前都是n,现在m、n 那就按照官方思路每个比较k/2元素,存在赋值。如果k1《k2,不在k1前k/2个,num1后移动,k-k/2 1 3 3 1 2 3 4 特殊情况考虑,如果没有k/2个元素,那最后一个元素替补吧. wrong 1: k-k/2 wrong 2; in fact,如果一个没有,那么可以设为超大值,因为长的那个数组k/2肯定不对,不够啊 */
true
95ca7269dcfae98c13adf8d688dd2205e322dfce
C++
afmika/Core6502-Cpp
/src/main.cpp
UTF-8
1,924
2.75
3
[]
no_license
#include <iostream> #include "CPU.h" int main(int argc, const char * argv[]) { std::string final_prog = ""; std::string dg_flag = "-d"; bool debug_mode = false; for (int i = 1; i < argc; i++) { std::string temp( argv[i] ); if ( temp.compare(dg_flag) == 0 && i == 1 ) { debug_mode = true; } else { final_prog.append(temp + (i + 1 == argc ? "": " ")); } } std::string prog = "a2 02 a0 04 8e 24 00 6d 24 00 8d 25 00 88 d0 f7"; if ( argc == 1 ) { printf("Loading default test program...\n"); final_prog = prog; } else { printf("Loading given program...\n"); printf("----------\n"); printf("%s\n", final_prog.c_str()); printf("----------\n"); } CPU::BUS* bus = new CPU::BUS(0x0000, 0xffff, false); bus->loadProgram(final_prog); printf("Program Size %i bits | %i Chuncks\n", bus->memSize(), bus->memSize() / 8); CPU::Core6502 cpu; // cpu.DefineProgramCounter(0x0600); cpu.Connect( bus ); cpu.Reset(); if ( debug_mode ) { // step by step while ( true ) { printf("\n"); if ( cpu.GetBreakFlag() ) { printf("\n----------[---- STOP - BRK - EXECUTION DONE ----]------\n"); cpu.Reset(); break; } else { cpu.Next(); cpu.DisplayDebugInfos(); cpu.DisplayStatus(); bus->DisplayMemory(0x0000, 0x00FF / 4); bus->DisplayStackMemory( cpu.GetStackPtrvalue() ); } getchar(); } return 0; } while ( true ) { cpu.Next(); if ( cpu.GetBreakFlag() ) { cpu.DisplayDebugInfos(); cpu.DisplayStatus(); bus->DisplayMemory(0x0000, 0x00FF / 4); bus->DisplayStackMemory( cpu.GetStackPtrvalue() ); printf("\n[---- STOP - BRK - EXECUTION DONE ----]\n"); cpu.Reset(); getchar(); return 0; } } return 0; }
true
673ecaa0b2365602be87973a332bacb38a53569d
C++
QianYaoWei/braille
/component/orm_proxy.cpp
UTF-8
10,737
2.609375
3
[]
no_license
#include "orm_proxy.h" #include "sqlite_db.h" #include "AnyType.h" #include "stringutil.h" using namespace utility; bool OrmProxy::SelectFromDB(const std::string &strTable, OrmDBCallBack *callback) { char *sqlArr = SqliteDB::Instance()->GetSqlArray(); snprintf(sqlArr, SqliteDB::SQL_LEN, "SELECT * FROM %s;", strTable.c_str()); return SqliteDB::Instance()->ExecuteSqlEx(callback); } bool OrmProxy::SyncDataToDB(const std::string &strTable, OrmDBCallBack *callback) { char *sqlArr = SqliteDB::Instance()->GetSqlArray(); size_t offset = snprintf(sqlArr, SqliteDB::SQL_LEN, "UPDATE %s SET ", strTable.c_str()); size_t i = 0; for ( auto &elem : _objFieldType ) { switch ( elem.second ) { case AnyType_String: { std::string &strData = *reinterpret_cast<std::string *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { // the last element offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=\"%s\" ", elem.first.c_str(), strData.c_str()); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=\"%s\",", elem.first.c_str(), strData.c_str()); } break; } case AnyType_Int8: { Int8 &val = *reinterpret_cast<Int8 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d,", elem.first.c_str(), val); } break; } case AnyType_UInt8: { UInt8 &val = *reinterpret_cast<UInt8 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u,", elem.first.c_str(), val); } break; } case AnyType_Int16: { Int16 &val = *reinterpret_cast<Int16 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d,", elem.first.c_str(), val); } break; } case AnyType_UInt16: { UInt16 &val = *reinterpret_cast<UInt16 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u,", elem.first.c_str(), val); } break; } case AnyType_Int32: { Int32 &val = *reinterpret_cast<Int32 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%d,", elem.first.c_str(), val); } break; } case AnyType_UInt32: { UInt32 &val = *reinterpret_cast<UInt32 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%u,", elem.first.c_str(), val); } break; } case AnyType_Int64: { Int64 &val = *reinterpret_cast<Int64 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%lld ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%lld,", elem.first.c_str(), val); } break; } case AnyType_UInt64: { UInt64 &val = *reinterpret_cast<UInt64 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%llu ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%llu,", elem.first.c_str(), val); } break; } case AnyType_Real32: { Real32 &val = *reinterpret_cast<Real32 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%f ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%f,", elem.first.c_str(), val); } break; } case AnyType_Real64: { Real64 &val = *reinterpret_cast<Real64 *>(_objFieldPt[elem.first]); if ( i == _objFieldType.size() - 1) { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%lf ", elem.first.c_str(), val); } else { offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "%s=%lf,", elem.first.c_str(), val); } break; } default: break; } ++i; } offset += snprintf(sqlArr + offset, SqliteDB::SQL_LEN - offset, "WHERE id=%llu;", GetID()); if ( offset >= SqliteDB::SQL_LEN) { return false; } return SqliteDB::Instance()->ExecuteSqlEx(callback); } bool OrmProxy::InsertToDB(const std::string &strTable, OrmDBCallBack *callback) { char *sqlArr = SqliteDB::Instance()->GetSqlArray(); snprintf(sqlArr, SqliteDB::SQL_LEN, "INSERT INTO %s(id) VALUES(%llu);", strTable.c_str(), GetID()); return SqliteDB::Instance()->ExecuteSqlEx(callback); } bool OrmProxy::DelFromDB(const std::string &strTable, OrmDBCallBack *callback) { char *sqlArr = SqliteDB::Instance()->GetSqlArray(); size_t offset = snprintf(sqlArr, SqliteDB::SQL_LEN, "DELETE FROM %s WHERE id=%llu", strTable.c_str(), GetID()); if ( offset >= SqliteDB::SQL_LEN) { return false; } return SqliteDB::Instance()->ExecuteSqlEx(callback); } void OrmProxy::AssignField(const char *column, const char *data) { if (nullptr == column || nullptr == data) { return; } if (strcmp("id", column) == 0) { SetID(StringUtil::ConvertToValue<Real64>(data)); return; } auto itr = _objFieldType.find(column); if (itr != _objFieldType.end()) { switch ( itr->second ) { case AnyType_String: { std::string &strData = *reinterpret_cast<std::string *>(_objFieldPt[itr->first]); strData = data; break; } case AnyType_Int8: { Int8 &val = *reinterpret_cast<Int8 *>(_objFieldPt[itr->first]); val = atoi(data); break; } case AnyType_Int16: { Int16 &val = *reinterpret_cast<Int16 *>(_objFieldPt[itr->first]); val = atoi(data); break; } case AnyType_UInt16: { UInt16 &val = *reinterpret_cast<UInt16 *>(_objFieldPt[itr->first]); val = atoi(data); break; } case AnyType_Int32: { Int32 &val = *reinterpret_cast<Int32 *>(_objFieldPt[itr->first]); val = atoi(data); break; } case AnyType_UInt32: { UInt32 &val = *reinterpret_cast<UInt32 *>(_objFieldPt[itr->first]); val = atoi(data); break; } case AnyType_Int64: { Int64 &val = *reinterpret_cast<Int64 *>(_objFieldPt[itr->first]); val = StringUtil::ConvertToValue<Int64>(data); break; } case AnyType_UInt64: { UInt64 &val = *reinterpret_cast<UInt64 *>(_objFieldPt[itr->first]); val = StringUtil::ConvertToValue<UInt64>(data); break; } case AnyType_Real32: { Real32 &val = *reinterpret_cast<Real32 *>(_objFieldPt[itr->first]); val = StringUtil::ConvertToValue<Real32>(data); break; } case AnyType_Real64: { Real64 &val = *reinterpret_cast<Real64 *>(_objFieldPt[itr->first]); val = StringUtil::ConvertToValue<Real64>(data); break; } default: break; } } }
true
e31fecc6598fcab21650bfe0d2373205b641d607
C++
raxracks/chadOS
/userspace/libraries/libutils/Optional.h
UTF-8
2,451
3.234375
3
[ "MIT", "BSD-2-Clause" ]
permissive
#pragma once #include <assert.h> #include <libutils/Std.h> #include <libutils/Tags.h> namespace Utils { template <typename T> struct Optional { private: bool _present = false; union { T _storage; }; public: ALWAYS_INLINE bool present() const { return _present; } ALWAYS_INLINE T &unwrap() { assert(present()); return _storage; } ALWAYS_INLINE const T &unwrap() const { assert(present()); return _storage; } ALWAYS_INLINE T unwrap_or(const T &defaut_value) const { if (present()) { return unwrap(); } else { return defaut_value; } } ALWAYS_INLINE explicit Optional() {} ALWAYS_INLINE Optional(NoneTag) { } ALWAYS_INLINE Optional(const T &value) { _present = true; new (&_storage) T(value); } ALWAYS_INLINE Optional(T &&value) { _present = true; new (&_storage) T(std::move(value)); } ALWAYS_INLINE Optional(const Optional &other) { if (other.present()) { _present = true; new (&_storage) T(other.unwrap()); } } ALWAYS_INLINE Optional(Optional &&other) { if (other.present()) { new (&_storage) T(other.unwrap()); _present = true; } } ALWAYS_INLINE Optional &operator=(const Optional &other) { if (this != &other) { clear(); _present = other._present; if (other._present) { new (&_storage) T(other.unwrap()); } } return *this; } ALWAYS_INLINE Optional &operator=(Optional &&other) { if (this != &other) { clear(); _present = other._present; if (other._present) { new (&_storage) T(other.unwrap()); } } return *this; } ALWAYS_INLINE bool operator==(const T &other) const { if (!present()) { return false; } return unwrap() == other; } ALWAYS_INLINE ~Optional() { clear(); } ALWAYS_INLINE void clear() { if (_present) { _storage.~T(); _present = false; } } }; } // namespace Utils
true
673abb71960e040a6f738e5fbc6636df357b5789
C++
demian2435/42-ft_containers
/ft_containers/IteratorBinaryTree.hpp
UTF-8
4,047
2.71875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* IteratorBinaryTree.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aduregon <aduregon@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/24 10:18:31 by aduregon #+# #+# */ /* Updated: 2021/06/01 10:45:18 by aduregon ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #include "TreeNode.hpp" namespace ft { template <class T> class binaryTreeIterator { protected: public: TreeNode<T> *_curr; TreeNode<T> *_prev; /* MEMBER */ //typedef ??? iterator_category; typedef T value_type; typedef std::ptrdiff_t difference_type; typedef value_type * pointer; typedef value_type & reference; binaryTreeIterator() {}; binaryTreeIterator(TreeNode<T> *curr) : _curr(curr) {}; binaryTreeIterator(binaryTreeIterator const &copy) { *this = copy; } binaryTreeIterator<T> &operator = (binaryTreeIterator const &copy) { this->_curr = copy._curr; return *this; } T operator * () { return *this->_curr->value; } binaryTreeIterator<T> *operator++() { while (1) { if (this->_curr->right && this->_prev != this->_curr->right) { this->_prev = this->_curr; this->_curr = this->_curr->right; while (this->_curr->left) { this->_prev = this->_curr; this->_curr = this->_curr->left; } return this; } else if (this->_curr->father->left && this->_curr->father->left == this->_curr) { this->_prev = this->_curr; this->_curr = this->_curr->father; return this; } else if (this->_curr->father->right && this->_curr->father->right == this->_curr) { this->_prev = this->_curr; this->_curr = this->_curr->father; } } return 0; } binaryTreeIterator<T> operator++ (int) { //std::cout << "POST" << std::endl; binaryTreeIterator<T> it(this->_curr); this->operator++(); return it; } binaryTreeIterator<T> *operator-- () { while (1) { if (this->_curr->left && this->_prev != this->_curr->left) { this->_prev = this->_curr; this->_curr = this->_curr->left; while (this->_curr->right) { this->_prev = this->_curr; this->_curr = this->_curr->right; } return this; } else if (this->_curr->father->right && this->_curr->father->right == this->_curr) { this->_prev = this->_curr; this->_curr = this->_curr->father; return this; } else if (this->_curr->father->left && this->_curr->father->right == this->_curr) { this->_prev = this->_curr; this->_curr = this->_curr->father; } } return 0; } binaryTreeIterator<T> operator-- (int) { binaryTreeIterator<T> temp(this->_curr); this->operator--(); return temp; } TreeNode<T> *operator -> () { return this->_curr; } bool operator==(binaryTreeIterator<T> const &other) const { return (this->_curr == other._curr); } bool operator!=(binaryTreeIterator<T> const &other) const { return (this->_curr != other._curr); } bool operator<(binaryTreeIterator<T> const &other) const { return (this->_curr < other._curr); } bool operator<=(binaryTreeIterator<T> const &other) const { return (this->_curr <= other._curr); } bool operator>(binaryTreeIterator<T> const &other) const { return (this->_curr > other._curr); } bool operator>=(binaryTreeIterator<T> const &other) const { return (this->_curr >= other._curr); } }; }
true
e23ccce7a3d3b8117a035355140346512d98c236
C++
octopusprime314/manawar-engine
/drawbuffers/src/VAO.cpp
UTF-8
26,835
2.640625
3
[]
no_license
#include "VAO.h" #include "Model.h" #include "GeometryBuilder.h" #include "EngineManager.h" #include "DXLayer.h" VAO::VAO() { } VAO::~VAO() { } VAO::VAO(D3D12_VERTEX_BUFFER_VIEW vbv, D3D12_INDEX_BUFFER_VIEW ibv) { _vbv = vbv; _ibv = ibv; } void VAO::setVertexContext(GLuint context) { _vertexBufferContext = context; } void VAO::setNormalContext(GLuint context) { _normalBufferContext = context; } void VAO::setTextureContext(GLuint context) { _textureBufferContext = context; } void VAO::setNormalDebugContext(GLuint context) { _debugNormalBufferContext = context; } GLuint VAO::getVertexContext() { return _vertexBufferContext; } GLuint VAO::getNormalContext() { return _normalBufferContext; } GLuint VAO::getTextureContext() { return _textureBufferContext; } GLuint VAO::getNormalDebugContext() { return _debugNormalBufferContext; } GLuint VAO::getVertexLength() { return _vertexLength; } D3D12_INDEX_BUFFER_VIEW VAO::getIndexBuffer() { return _ibv; } D3D12_VERTEX_BUFFER_VIEW VAO::getVertexBuffer() { return _vbv; } ResourceBuffer* VAO::getIndexResource() { return _indexBuffer; } ResourceBuffer* VAO::getVertexResource() { return _vertexBuffer; } void VAO::addTextureStride(std::pair<std::string, int> stride) { _textureStride.push_back(stride); } TextureMetaData VAO::getTextureStrides() { return _textureStride; } void VAO::setPrimitiveOffsetId(GLuint id) { _primitiveOffsetId = id; } GLuint VAO::getPrimitiveOffsetId() { return _primitiveOffsetId; } GLuint VAO::getVAOContext() { return _vaoContext; } GLuint VAO::getVAOShadowContext() { return _vaoShadowContext; } void VAO::_buildVertices(float* flattenVerts) { if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { //Create a double buffer that will be filled with the vertex data glGenBuffers(1, &_vertexBufferContext); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*_vertexLength * 3, flattenVerts, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Bind regular vertex, normal and texture coordinate vao glGenVertexArrays(1, &_vaoContext); glBindVertexArray(_vaoContext); //Bind vertex buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); //Say that the vertex data is associated with attribute 0 in the context of a shader program //Each vertex contains 3 floats per vertex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable vertex buffer at location 0 glEnableVertexAttribArray(0); //Close vao glBindVertexArray(0); } else if (EngineManager::getGraphicsLayer() >= GraphicsLayer::DX12) { //IMPLEMENT ME!!!! } } void VAO::createVAO(std::vector<Cube>* cubes, GeometryConstruction geometryType) { float* flattenVerts = GeometryBuilder::buildCubes(cubes, _vertexLength, geometryType); _buildVertices(flattenVerts); delete[] flattenVerts; } void VAO::createVAO(std::vector<Triangle>* triangles) { float* flattenVerts = GeometryBuilder::buildTriangles(triangles, _vertexLength); _buildVertices(flattenVerts); delete[] flattenVerts; } void VAO::createVAO(std::vector<Sphere>* spheres, GeometryConstruction geometryType) { float* flattenVerts = GeometryBuilder::buildSpheres(spheres, _vertexLength, geometryType); _buildVertices(flattenVerts); delete[] flattenVerts; } void VAO::createVAO(RenderBuffers* renderBuffers, ModelClass classId, Animation* animation) { size_t triBuffSize = 0; float* flattenVerts = nullptr; float* flattenNorms = nullptr; size_t textureBuffSize = 0; float* flattenTextures = nullptr; float* flattenAttribs = nullptr; uint32_t* flattenIndexes = nullptr; auto vertices = renderBuffers->getVertices(); auto normals = renderBuffers->getNormals(); auto textures = renderBuffers->getTextures(); auto indices = renderBuffers->getIndices(); _vertexLength = static_cast<GLuint>(vertices->size()); if (classId == ModelClass::ModelType) { if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { triBuffSize = vertices->size() * 3; flattenVerts = new float[triBuffSize]; flattenNorms = new float[triBuffSize]; textureBuffSize = textures->size() * 2; flattenTextures = new float[textureBuffSize]; int i = 0; //iterates through vertices indexes for (auto vertex : *vertices) { float *flat = vertex.getFlatBuffer(); flattenVerts[i++] = flat[0]; flattenVerts[i++] = flat[1]; flattenVerts[i++] = flat[2]; } i = 0; //Reset for normal indexes for (auto normal : *normals) { float *flat = normal.getFlatBuffer(); flattenNorms[i++] = flat[0]; flattenNorms[i++] = flat[1]; flattenNorms[i++] = flat[2]; } i = 0; //Reset for texture indexes for (auto texture : *textures) { float *flat = texture.getFlatBuffer(); flattenTextures[i++] = flat[0]; flattenTextures[i++] = flat[1]; } } else { //Now flatten vertices and normals out triBuffSize = vertices->size() * 3; flattenAttribs = new float[triBuffSize + (normals->size() * 3) + (textures->size() * 2)]; flattenIndexes = new uint32_t[triBuffSize / 3]; int i = 0; //iterates through vertices indexes uint32_t j = 0; for (auto vertex : *vertices) { float *flatVert = vertex.getFlatBuffer(); flattenAttribs[i++] = flatVert[0]; flattenAttribs[i++] = flatVert[1]; flattenAttribs[i++] = flatVert[2]; flattenIndexes[j] = j; j++; i += 5; } i = 3; for (auto normal : *normals) { float *flatNormal = normal.getFlatBuffer(); flattenAttribs[i++] = flatNormal[0]; flattenAttribs[i++] = flatNormal[1]; flattenAttribs[i++] = flatNormal[2]; i += 5; } i = 6; for (auto texture : *textures) { float *flat = texture.getFlatBuffer(); flattenAttribs[i++] = flat[0]; flattenAttribs[i++] = flat[1]; i += 6; } } } else if (classId == ModelClass::AnimatedModelType) { int i = 0; if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { triBuffSize = indices->size() * 3; flattenVerts = new float[triBuffSize]; flattenNorms = new float[triBuffSize]; textureBuffSize = textures->size() * 2; flattenTextures = new float[textureBuffSize]; for (auto index : *indices) { float *flat = (*vertices)[index].getFlatBuffer(); flattenVerts[i++] = flat[0]; flattenVerts[i++] = flat[1]; flattenVerts[i++] = flat[2]; } i = 0; //Reset for normal indexes for (auto index : *indices) { float *flat = (*normals)[index].getFlatBuffer(); flattenNorms[i++] = flat[0]; flattenNorms[i++] = flat[1]; flattenNorms[i++] = flat[2]; } i = 0; //Reset for texture indexes for (auto texture : *textures) { float *flat = texture.getFlatBuffer(); flattenTextures[i++] = flat[0]; flattenTextures[i++] = flat[1]; } } else { //Now flatten vertices and normals out triBuffSize = indices->size() * 3; flattenAttribs = new float[triBuffSize + (indices->size() * 3) + (textures->size() * 2)]; flattenIndexes = new uint32_t[triBuffSize / 3]; uint16_t j = 0; i = 0; for (auto index : *indices) { float *flatVert = (*vertices)[index].getFlatBuffer(); flattenAttribs[i++] = flatVert[0]; flattenAttribs[i++] = flatVert[1]; flattenAttribs[i++] = flatVert[2]; flattenIndexes[j] = j; j++; i += 5; } i = 3; for (auto index : *indices) { float *flatNormal = (*normals)[index].getFlatBuffer(); flattenAttribs[i++] = flatNormal[0]; flattenAttribs[i++] = flatNormal[1]; flattenAttribs[i++] = flatNormal[2]; i += 5; } i = 6; for (auto texture : *textures) { float *flat = texture.getFlatBuffer(); flattenAttribs[i++] = flat[0]; flattenAttribs[i++] = flat[1]; i += 6; } } auto boneIndexes = animation->getBoneIndexes(); auto boneWeights = animation->getBoneWeights(); std::vector<int>* indices = renderBuffers->getIndices(); size_t boneIndexesBuffSize = indices->size() * 8; float* flattenIndexes = new float[boneIndexesBuffSize]; float* flattenWeights = new float[boneIndexesBuffSize]; i = 0; //iterates through vertices indexes for (auto vertexIndex : *indices) { auto indexes = (*boneIndexes)[vertexIndex]; flattenIndexes[i++] = static_cast<float>(indexes[0]); flattenIndexes[i++] = static_cast<float>(indexes[1]); flattenIndexes[i++] = static_cast<float>(indexes[2]); flattenIndexes[i++] = static_cast<float>(indexes[3]); flattenIndexes[i++] = static_cast<float>(indexes[4]); flattenIndexes[i++] = static_cast<float>(indexes[5]); flattenIndexes[i++] = static_cast<float>(indexes[6]); flattenIndexes[i++] = static_cast<float>(indexes[7]); } i = 0; //Reset for normal indexes for (auto vertexIndex : *indices) { auto weights = (*boneWeights)[vertexIndex]; flattenWeights[i++] = weights[0]; flattenWeights[i++] = weights[1]; flattenWeights[i++] = weights[2]; flattenWeights[i++] = weights[3]; flattenWeights[i++] = weights[4]; flattenWeights[i++] = weights[5]; flattenWeights[i++] = weights[6]; flattenWeights[i++] = weights[7]; } if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { glGenBuffers(1, &_indexContext); glBindBuffer(GL_ARRAY_BUFFER, _indexContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*boneIndexesBuffSize, flattenIndexes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &_weightContext); glBindBuffer(GL_ARRAY_BUFFER, _weightContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*boneIndexesBuffSize, flattenWeights, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } else { //IMPLEMENT ME!!! } delete[] flattenIndexes; delete[] flattenWeights; } if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { //Create a double buffer that will be filled with the vertex data glGenBuffers(1, &_vertexBufferContext); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*triBuffSize, flattenVerts, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Create a double buffer that will be filled with the normal data glGenBuffers(1, &_normalBufferContext); glBindBuffer(GL_ARRAY_BUFFER, _normalBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*triBuffSize, flattenNorms, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Create a single buffer that will be filled with the texture coordinate data glGenBuffers(1, &_textureBufferContext); //Do not need to double buffer glBindBuffer(GL_ARRAY_BUFFER, _textureBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*textureBuffSize, flattenTextures, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Bind regular vertex, normal and texture coordinate vao glGenVertexArrays(1, &_vaoContext); glBindVertexArray(_vaoContext); //Bind vertex buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); //Say that the vertex data is associated with attribute 0 in the context of a shader program //Each vertex contains 3 floats per vertex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable vertex buffer at location 0 glEnableVertexAttribArray(0); //Bind normal buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _normalBufferContext); //Say that the normal data is associated with attribute 1 in the context of a shader program //Each normal contains 3 floats per normal glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable normal buffer at location 1 glEnableVertexAttribArray(1); //Bind texture coordinate buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _textureBufferContext); //Say that the texture coordinate data is associated with attribute 2 in the context of a shader program //Each texture coordinate contains 2 floats per texture glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); //Now enable texture buffer at location 2 glEnableVertexAttribArray(2); if (classId == ModelClass::AnimatedModelType) { //Bind bone index buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _indexContext); //First 4 indexes //Specify stride to be 8 because the beginning of each index attribute value is 8 bytes away //Say that the bone index data is associated with attribute 3 in the context of a shader program //Each bone index contains 4 floats per index glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), 0); //Now enable bone index buffer at location 1 glEnableVertexAttribArray(3); //Second 4 indexes //Specify stride to be 8 because the beginning of each index attribute value is 8 bytes away //Specify offset for attribute location of indexes2 to be 4 bytes offset from the beginning location of the buffer //Say that the bone index data is associated with attribute 3 in the context of a shader program //Each bone index contains 4 floats per index glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(4 * sizeof(GL_FLOAT))); //Now enable bone index buffer at location 2 glEnableVertexAttribArray(4); //Bind weight buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _weightContext); //First 4 weights //Specify stride to be 8 because the beginning of each weight attribute value is 8 bytes away //Say that the weight data is associated with attribute 4 in the context of a shader program //Each weight contains 4 floats per index glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), 0); //Now enable weight buffer at location 3 glEnableVertexAttribArray(5); //Second 4 weights //Specify stride to be 8 because the beginning of each weight attribute value is 8 bytes away //Specify offset for attribute location of weights2 to be 4 bytes offset from the beginning location of the buffer //Say that the weight data is associated with attribute 4 in the context of a shader program //Each weight contains 4 floats per index glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(4 * sizeof(GL_FLOAT))); //Now enable weight buffer at location 4 glEnableVertexAttribArray(6); } //Close vao glBindVertexArray(0); } else { struct Vertex { float pos[3]; float normal[3]; float uv[2]; }; UINT byteSize = 0; if (classId == ModelClass::AnimatedModelType) { byteSize = static_cast<UINT>((triBuffSize + (indices->size() * 3) + (textures->size() * 2)) * sizeof(float)); } else { byteSize = static_cast<UINT>((triBuffSize + (normals->size() * 3) + (textures->size() * 2)) * sizeof(float)); } auto indexBytes = static_cast<UINT>((triBuffSize / 3) * sizeof(uint32_t)); _vertexBuffer = new ResourceBuffer(flattenAttribs, byteSize, DXLayer::instance()->getCmdList(), DXLayer::instance()->getDevice()); _indexBuffer = new ResourceBuffer(flattenIndexes, indexBytes, DXLayer::instance()->getCmdList(), DXLayer::instance()->getDevice()); _vbv.BufferLocation = _vertexBuffer->getGPUAddress(); _vbv.StrideInBytes = sizeof(Vertex); _vbv.SizeInBytes = byteSize; _ibv.BufferLocation = _indexBuffer->getGPUAddress(); _ibv.Format = DXGI_FORMAT_R32_UINT; _ibv.SizeInBytes = indexBytes; } if (EngineManager::getGraphicsLayer() == GraphicsLayer::OPENGL) { //Bind vertex vao only for shadow pass glGenVertexArrays(1, &_vaoShadowContext); glBindVertexArray(_vaoShadowContext); //Bind vertex buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); //Say that the vertex data is associated with attribute 0 in the context of a shader program //Each vertex contains 3 floats per vertex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable vertex buffer at location 0 glEnableVertexAttribArray(0); if (classId == ModelClass::AnimatedModelType) { //Bind bone index buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _indexContext); //First 4 indexes //Specify stride to be 8 because the beginning of each index attribute value is 8 bytes away //Say that the bone index data is associated with attribute 3 in the context of a shader program //Each bone index contains 4 floats per index glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), 0); //Now enable bone index buffer at location 1 glEnableVertexAttribArray(1); //Second 4 indexes //Specify stride to be 8 because the beginning of each index attribute value is 8 bytes away //Specify offset for attribute location of indexes2 to be 4 bytes offset from the beginning location of the buffer //Say that the bone index data is associated with attribute 3 in the context of a shader program //Each bone index contains 4 floats per index glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(4 * sizeof(GL_FLOAT))); //Now enable bone index buffer at location 2 glEnableVertexAttribArray(2); //Bind weight buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _weightContext); //First 4 weights //Specify stride to be 8 because the beginning of each weight attribute value is 8 bytes away //Say that the weight data is associated with attribute 4 in the context of a shader program //Each weight contains 4 floats per index glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), 0); //Now enable weight buffer at location 3 glEnableVertexAttribArray(3); //Second 4 weights //Specify stride to be 8 because the beginning of each weight attribute value is 8 bytes away //Specify offset for attribute location of weights2 to be 4 bytes offset from the beginning location of the buffer //Say that the weight data is associated with attribute 4 in the context of a shader program //Each weight contains 4 floats per index glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(4 * sizeof(GL_FLOAT))); //Now enable weight buffer at location 4 glEnableVertexAttribArray(4); } //Close vao glBindVertexArray(0); } else { //IMPLEMENT ME!!! } delete[] flattenVerts; delete[] flattenNorms; delete[] flattenTextures; } void VAO::createVAO(RenderBuffers* renderBuffers, int begin, int range) { size_t triBuffSize = 0; float* flattenVerts = nullptr; float* flattenNorms = nullptr; size_t textureBuffSize = 0; float* flattenTextures = nullptr; size_t lineBuffSize = 0; float* flattenNormLines = nullptr; auto vertices = renderBuffers->getVertices(); auto normals = renderBuffers->getNormals(); auto textures = renderBuffers->getTextures(); auto indices = renderBuffers->getIndices(); auto debugNormals = renderBuffers->getDebugNormals(); _vertexLength = static_cast<GLuint>(vertices->size()); triBuffSize = range * 3; flattenVerts = new float[triBuffSize]; flattenNorms = new float[triBuffSize]; textureBuffSize = range * 2; flattenTextures = new float[textureBuffSize]; int i = 0; //iterates through vertices indexes for (int j = begin; j < begin + range; j++) { float *flat = (*vertices)[j].getFlatBuffer(); flattenVerts[i++] = flat[0]; flattenVerts[i++] = flat[1]; flattenVerts[i++] = flat[2]; } i = 0; //Reset for normal indexes for (int j = begin; j < begin + range; j++) { float *flat = (*normals)[j].getFlatBuffer(); flattenNorms[i++] = flat[0]; flattenNorms[i++] = flat[1]; flattenNorms[i++] = flat[2]; } i = 0; //Reset for texture indexes for (int j = begin; j < begin + range; j++) { float *flat = (*textures)[j].getFlatBuffer(); flattenTextures[i++] = flat[0]; flattenTextures[i++] = flat[1]; } //Create a double buffer that will be filled with the vertex data glGenBuffers(1, &_vertexBufferContext); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*triBuffSize, flattenVerts, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Create a double buffer that will be filled with the normal data glGenBuffers(1, &_normalBufferContext); glBindBuffer(GL_ARRAY_BUFFER, _normalBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*triBuffSize, flattenNorms, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Create a single buffer that will be filled with the texture coordinate data glGenBuffers(1, &_textureBufferContext); //Do not need to double buffer glBindBuffer(GL_ARRAY_BUFFER, _textureBufferContext); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*textureBuffSize, flattenTextures, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Bind regular vertex, normal and texture coordinate vao glGenVertexArrays(1, &_vaoContext); glBindVertexArray(_vaoContext); //Bind vertex buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); //Say that the vertex data is associated with attribute 0 in the context of a shader program //Each vertex contains 3 floats per vertex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable vertex buffer at location 0 glEnableVertexAttribArray(0); //Bind normal buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _normalBufferContext); //Say that the normal data is associated with attribute 1 in the context of a shader program //Each normal contains 3 floats per normal glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable normal buffer at location 1 glEnableVertexAttribArray(1); //Bind texture coordinate buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _textureBufferContext); //Say that the texture coordinate data is associated with attribute 2 in the context of a shader program //Each texture coordinate contains 2 floats per texture glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); //Now enable texture buffer at location 2 glEnableVertexAttribArray(2); //Close vao glBindVertexArray(0); //Bind vertex vao only for shadow pass glGenVertexArrays(1, &_vaoShadowContext); glBindVertexArray(_vaoShadowContext); //Bind vertex buff context to current buffer glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferContext); //Say that the vertex data is associated with attribute 0 in the context of a shader program //Each vertex contains 3 floats per vertex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Now enable vertex buffer at location 0 glEnableVertexAttribArray(0); //Close vao glBindVertexArray(0); delete[] flattenVerts; delete[] flattenNorms; delete[] flattenTextures; }
true
8d4d25951280cb4c7ae72e3d85d607df1265bb80
C++
ArthurTorrente/4A_Anim_Numerique_Genetic_Algorithm
/Genetic_Algorithm/src/StickyCamera.cpp
UTF-8
1,362
2.546875
3
[]
no_license
#include "StickyCamera.h" #include "cinder/gl/gl.h" StickyCamera::StickyCamera() : m_eye(0.0f, 0.0f, 0.0f), m_center(0.f, 0.f, 0.f), m_up(-cinder::Vec3f::yAxis()), m_cameraDistance(0.0f) { m_rotation.identity(); } void StickyCamera::setup(float fov, float aspectRatio, float _near, float _far, float cameraDistance) { m_cameraDistance = cameraDistance; m_eye.set(0.f, 0.f, m_cameraDistance); m_camera.setPerspective(fov, aspectRatio, _near, _far); m_camera.lookAt(m_eye, m_center, m_up); cinder::gl::setMatrices(m_camera); cinder::gl::rotate(m_rotation); } void StickyCamera::update() { m_eye = m_rotation * ci::Vec3f(0.0f, 0.0f, m_cameraDistance); m_camera.lookAt(m_eye, m_center, m_up); cinder::gl::setMatrices(m_camera); } float& StickyCamera::getCameraDistance() { return m_cameraDistance; } float StickyCamera::getCameraDistance() const { return m_cameraDistance; } cinder::Quatf& StickyCamera::getRotation() { return m_rotation; } const cinder::Quatf& StickyCamera::getRotation() const { return m_rotation; } cinder::Vec3f& StickyCamera::getEye() { return m_eye; } cinder::Vec3f& StickyCamera::getCenter() { return m_center; } cinder::Vec3f& StickyCamera::getUp() { return m_up; } cinder::CameraPersp& StickyCamera::getCamera() { return m_camera; }
true
932189fe2bf308cc60935f8864abf6a1293c618d
C++
hwenradiant0/B-BConsume
/B&B ConSume/3D_Game/ZCamera.h
UHC
3,376
2.875
3
[]
no_license
#pragma once #include "Device.h" /* : ۺ : ī޶ Ŭ : 2014.01.06 */ class ZCamera { private: D3DXVECTOR3 m_vEye; //ī޶ (ī޶ ġ) D3DXVECTOR3 m_vLookAt; //ī޶ ٶ󺸴 (ī޶ ü ġ) D3DXVECTOR3 m_vUp; //ī޶ 溤 D3DXVECTOR3 m_vCameraBasis; //ī޶ü ⺤(m_vLookAt-m_vEye) D3DXVECTOR3 m_vCameraCross; //ī޶ (m_vUp,m_vCameraBasis κ ) D3DXMATRIXA16 m_matView; //ī޶ public: ZCamera(void); ~ZCamera(void); //ʱⰪ void Init(void); //ī޶ Ѵ. void SetEye( D3DXVECTOR3 *pvEye ) { m_vEye = *pvEye; } //ī޶ Ѵ. D3DXVECTOR3 GetEye() { return m_vEye; } //ī޶ ü Ѵ. void SetLookAt(D3DXVECTOR3 *pvLootAt) { m_vLookAt = *pvLootAt; } //ī޶ ü Ѵ. D3DXVECTOR3 GetLookAt() { return m_vLookAt ; } //ī޶ 溤͸ Ѵ. void SetUp(D3DXVECTOR3 *pvUp) { m_vUp = *pvUp; } //ī޶ 溤͸ Ѵ. D3DXVECTOR3 GetUp() { return m_vUp; } //ī޶ ϰ Ѵ. void SetViewMatrix(D3DXVECTOR3 *pvEye, D3DXVECTOR3 *pvLookAt, D3DXVECTOR3 *pvUp); //ī޶ Ѵ. D3DXMATRIXA16 GetViewMatrix() { return m_matView; } //D3DXMatrixLookAtLH() ϴ Լ void ViewMatrix(D3DXMATRIX* pOut, D3DXVECTOR3* vcPos, D3DXVECTOR3* vcLook, D3DXVECTOR3* vcUp); //ī޶ ǥ X ü distŭ ̵ void MoveCameraX(float distance); //ī޶ ǥ Y ü distŭ ̵ void MoveCameraY(float distance); //ī޶ ǥ Z ü distŭ ̵ void MoveCameraZ(float distance); //ī޶ X angle ŭ ȸ void RotateEyeX(float angle); //ī޶ Y angle ŭ ȸ void RotateEyeY(float angle); //ī޶ Z angle ŭ ȸ void RotateEyeZ(float angle); //ī޶ ִ X angle ŭ ȸ void RotateLookAtX(float angle); //ī޶ ִ Y angle ŭ ȸ void RotateLookAtY(float angle); //ī޶ ִ Z angle ŭ ȸ void RotateLookAtZ(float angle); //ǥ X angle ŭ ȸ void RotateWorldX(float angle); //ǥ Y angle ŭ ȸ void RotateWorldY(float angle); //ǥ Z angle ŭ ȸ void RotateWorldZ(float angle); //ī޶ ٶ󺸴 ǥ X angle ŭ ȸ void RotateWorldLookAtX(float angle); //ī޶ ٶ󺸴 ǥ X angle ŭ ȸ void RotateWorldLookAtY(float angle); //ī޶ ٶ󺸴 ǥ X angle ŭ ȸ void RotateWorldLookAtZ(float angle); // ǥ *pv ġ ̵Ѵ. void MoveTo(D3DXVECTOR3 *pv); };
true
21749c684f41f298f7a2057bb1d1e6e8a3bd0f34
C++
Jocoboy/Huffman-Coding
/TreeNode.h
UTF-8
606
2.6875
3
[]
no_license
#pragma once #include <iostream> #include <ostream> using namespace std; class TreeNode { private: char ch; int tag; int freq; //Addons string code = ""; TreeNode *lChild; TreeNode *rChild; public: TreeNode(char, int, int,TreeNode *, TreeNode *); bool operator<(const TreeNode &); friend ostream &operator<<(ostream &, const TreeNode &); char get_ch() const; int get_tag() const; int get_freq() const; string get_code() const; void set_tag(int); //Addons void set_code(string); TreeNode *get_lChild(); TreeNode *get_rChild(); };
true
8297d36a03466dcdf6fcb76de93f59d8bf307eba
C++
Group-3/Pacman
/code/Pacman/Collision.cpp
UTF-8
1,679
3
3
[]
no_license
#include "Collision.h" Collision *Collision::_this = NULL; Collision::Collision(vector<Player> *players) { this->players = players; } Collision *Collision::createInstance(vector<Player> *players) { if(!_this) _this = new Collision(players); return _this; } bool Collision::sphereVsSphere(D3DXVECTOR3 pos1, D3DXVECTOR3 pos2, float radius1, float radius2) { return D3DXVec3Length(&(pos1 - pos2)) < radius1 + radius2; } bool Collision::rayVsSphere(D3DXVECTOR3 rayOrigin, D3DXVECTOR3 rayDir, D3DXVECTOR3 spherePos, float radius, float &intersect1, float &intersect2) { D3DXVECTOR3 p = rayOrigin-spherePos; float det, b; b = -D3DXVec3Dot(&p,&rayDir); det = b*b - D3DXVec3Dot(&p,&p) + radius*radius; if(det<0) { return false; } det = sqrt(det); intersect1 = b - det; intersect2 = b + det; if(intersect2 < 0) return false; if(intersect1 < 0) intersect1 = 0; return true; } bool Collision::lookForPlayers(D3DXVECTOR3 &out, D3DXVECTOR3 rayOrigin) { float i1, i2; for(unsigned int i = 0; i < players->size(); i++) { if(rayVsSphere(rayOrigin,D3DXVECTOR3(0,0,1),players->at(i).getPosition(),players->at(i).getRadius(),i1,i2) || rayVsSphere(rayOrigin,D3DXVECTOR3(1,0,0),players->at(i).getPosition(),players->at(i).getRadius(),i1,i2) || rayVsSphere(rayOrigin,D3DXVECTOR3(0,0,-1),players->at(i).getPosition(),players->at(i).getRadius(),i1,i2) || rayVsSphere(rayOrigin,D3DXVECTOR3(-1,0,0),players->at(i).getPosition(),players->at(i).getRadius(),i1,i2)) { out = players->at(i).getPosition(); return true; } } return false; } Collision *Collision::getInstance() { if(_this) return _this; else return NULL; } Collision::~Collision() { }
true
8cdd46f2b3760dc836aa750a19dff956b92d83e4
C++
cchenziqiang/Algorithm
/P41.cpp
UTF-8
678
3.34375
3
[]
no_license
#include <iostream> #include "List.h" using namespace std; void PrintCommon(Node* head1, Node* head2) { while (head1 != nullptr && head2 != nullptr) { if (head1->value > head2->value) head1 = head1->next; else if (head1->value < head2->value) head2 = head2->next; else { cout << head1->value << endl; head1 = head1->next; head2 = head2->next; } } return; } int main() { Node* pNode5 = new Node(3); Node* pNode4 = new Node(4, pNode5); Node* pNode3 = new Node(5, pNode4); Node* pNode2 = new Node(10, pNode3); Node* pNode1 = new Node(8, pNode3); Node* pNode0 = new Node(9, pNode1); PrintCommon(pNode0, pNode2); }
true
e33a7db09974efe6bb87866afbd5ce82eb496c16
C++
Mike-droid/EjerciciosDeCplusplus
/bloque 2/Ejercicio 8 bloque 2.cpp
ISO-8859-1
462
3.40625
3
[]
no_license
/* 8. Escriba un programa que lea de la entrada estndar los dos catetos de un tringulo rectngulo y escriba en la salida estndar su hipotenusa. */ #include <iostream> #include <math.h> using namespace std; int main(){ float a,b,c,hipotenusa; cout<<"Digite el cateto a:"; cin>>a; cout<<"\nDigite el cateto b:"; cin>>b; c=(a*a)+(b*b); hipotenusa=sqrt(c); cout<<"\nLa hipotenusa del triangulo rectangulo es "<<hipotenusa; return 0; }
true
2621a8d7a55e92ec825109364a8bd5a5508b7e0a
C++
Harryx2019/2021-pat
/第三章 入门篇(1)——入门模拟/3.5进制转换/B1022 D进制的A+B.cpp
UTF-8
269
2.640625
3
[]
no_license
#include <stdio.h> int main() { int a,b,d; scanf("%d%d%d",&a,&b,&d); int c = a+b; int ans[31],num=0; do{ ans[num++]=c%d; c=c/d; }while(c!=0); for(num--;num>=0;num--){ printf("%d",ans[num]); } return 0; }
true
a2878802174b7e22a7274bc9729f8682f100249b
C++
phaass/ex2
/Horse.cpp
UTF-8
717
2.984375
3
[]
no_license
// // Created by phaass on 1/15/18. // #include "Horse.h" virtual static int Horse::move(int x, int y, int new_x, int new_y, int currentPlayer, Board board){ if ((isPossibleMove(x, y, new_x, new_y, currentPlayer, board)) == 0) { board.movePiece(x,y,new_x,new_y); return 1; } return 0; } virtual static int Horse::isPossibleMove(int x, int y, int new_x, int new_y, int currentPlayer, Board board){ int yMove = new_y - y; int xMove = new_x - x; if((xMove == 1 && yMove == 2) && !board.isOutOfBoard(new_x,new_y) ){ if ((board.isCellEmpty(new_x, new_y) == 1) | (board.getToolPlayer(new_x, new_y)) != currentPlayer){ return 1; } } }
true
6eff68dc40e837b0c9ddcafee3a1ce29757d96f7
C++
FSource/FEngine
/lib/libfaeris/src/stage/FsScene.cc
UTF-8
6,620
2.609375
3
[ "MIT" ]
permissive
#include "stage/FsScene.h" #include "stage/layer/FsLayer.h" #include "support/util/FsSlowArray.h" #include "mgr/FsObjectMgr.h" #include "stage/layer/FsColorLayer.h" NS_FS_BEGIN Scene* Scene::create() { Scene* ret=new Scene; return ret; } /* layer operation */ void Scene::push(Layer* layer) { if(layer->getScene()) { FS_TRACE_WARN("layer is already owned by scene"); return ; } m_layers->push(layer); layer->setScene(this); } void Scene::pop() { int size=m_layers->size(); if(size==0) { FS_TRACE_WARN("No Layer to pop"); return; } Layer* ret=(Layer*)m_layers->get(size-1); if( ret==m_touchFocusLayer ) { m_touchFocusLayer=NULL; } ret->setScene(NULL); m_layers->pop(); } void Scene::insert(int pos,Layer* layer) { if(layer->getScene()) { FS_TRACE_WARN("layer is already owned by scene"); return ; } m_layers->insert(pos,layer); layer->setScene(this); } void Scene::replace(int pos,Layer* layer) { Layer* ret=(Layer*)m_layers->get(pos); if(ret==NULL) { FS_TRACE_WARN("Index(%d) Layer Out Of Range",pos); return; } if(ret==m_touchFocusLayer) { m_touchFocusLayer=NULL; } ret->setScene(NULL); m_layers->set(pos,layer); } void Scene::remove(Layer* layer) { if(layer->getScene()!=this) { FS_TRACE_WARN("Layer is not owned by scene"); return; } if(layer==m_touchFocusLayer) { m_touchFocusLayer=NULL; } layer->setScene(NULL); m_layers->remove(layer); } Layer* Scene::top() { return (Layer*)m_layers->top(); } int Scene::layerNu() { return m_layers->size(); } Layer* Scene::getLayer(int index) { return (Layer*)m_layers->get(index); } int Scene::getLayerIndex(Layer* layer) { int layer_nu=m_layers->size(); Layer* cur=NULL; for(int i=0;i<layer_nu;i++) { cur=(Layer*)m_layers->get(i); if(cur==layer) { return i; } } return -1; } void Scene::clear() { int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { Layer* layer=(Layer*)m_layers->get(i); layer->setScene(NULL); } m_layers->clear(); m_touchFocusLayer=NULL; } void Scene::setTouchEnabled(bool enabled) { m_touchEnabled=enabled; } bool Scene::getTouchEnabled() { return m_touchEnabled; } void Scene::setTouchesEnabled(bool enabled) { m_touchesEnabled=enabled; } bool Scene::getTouchesEnabled() { return m_touchesEnabled; } void Scene::setFadeEnabled(bool fade) { m_fadeEnabled=fade; } bool Scene::getFadeEnabled() { return m_fadeEnabled; } void Scene::setFadeColor(Color c) { m_fadeColor=c; } /* event */ void Scene::enter() { /* do nothing */ } void Scene::exit() { /* do nothing */ } void Scene::update(float dt) { updateAction(dt); updateLayers(dt); } void Scene::updateLayers(float dt) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { Layer* layer=(Layer*)m_layers->get(i); if(layer->getVisible()) { layer->update(dt); } } m_layers->unlock(); m_layers->flush(); } void Scene::draw(Render* render) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=0;i<layer_nu;i++) { Layer* layer=(Layer*)m_layers->get(i); if(layer->getVisible()) { layer->draw(render); } } m_layers->unlock(); m_layers->flush(); if(m_fadeEnabled) { m_fadeLayer->setColor(m_fadeColor); m_fadeLayer->draw(render); } } void Scene::touchBegin(float x,float y) { m_touchFocusLayer=NULL; m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if((layer->getScene()==this)&&layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchBegin(x,y); } if(handle&&layer->getScene()==this) { m_touchFocusLayer=layer; break; } } m_layers->unlock(); m_layers->flush(); } void Scene::touchMove(float x,float y) { if(m_touchFocusLayer&&m_touchFocusLayer->touchEnabled()&&m_touchFocusLayer->getVisible()) { m_touchFocusLayer->touchMove(x,y); } } void Scene::touchEnd(float x,float y) { if(m_touchFocusLayer&&m_touchFocusLayer->touchEnabled()&&m_touchFocusLayer->getVisible()) { m_touchFocusLayer->touchEnd(x,y); } m_touchFocusLayer=NULL; } void Scene::touchesBegin(TouchEvent* event) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if(layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchesBegin(event); } if(handle) { break; } } m_layers->unlock(); m_layers->flush(); } void Scene::touchesPointerDown(TouchEvent* event) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if(layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchesPointerDown(event); } if(handle) { break; } } m_layers->unlock(); m_layers->flush(); } void Scene::touchesMove(TouchEvent* event) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if(layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchesMove(event); } if(handle) { break; } } m_layers->unlock(); m_layers->flush(); } void Scene::touchesPointerUp(TouchEvent* event) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if(layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchesPointerUp(event); } if(handle) { break; } } m_layers->unlock(); m_layers->flush(); } void Scene::touchesEnd(TouchEvent* event) { m_layers->lock(); int layer_nu=m_layers->size(); for(int i=layer_nu-1;i>=0;i--) { bool handle=false; Layer* layer=(Layer*)m_layers->get(i); if(layer->touchEnabled()&&layer->getVisible()) { handle=layer->touchesEnd(event); } if(handle) { break; } } m_layers->unlock(); m_layers->flush(); } void Scene::keypadEvent(int type,int keycode) { } void Scene::inputTextEvent(const char* text,int length) { } const char* Scene::className() { return FS_SCENE_CLASS_NAME; } Scene::Scene() { init(); } Scene::~Scene() { destruct(); } void Scene::init() { m_layers=FsSlowArray::create(); FS_NO_REF_DESTROY(m_layers); m_fadeColor=Color4f(1.0f,1.0f,1.0f,0.5f); m_fadeEnabled=false; m_fadeLayer=ColorLayer::create(m_fadeColor); FS_NO_REF_DESTROY(m_fadeLayer); m_touchFocusLayer=NULL; m_touchEnabled=true; m_touchesEnabled=true; } void Scene::destruct() { FS_DESTROY(m_layers); FS_DESTROY(m_fadeLayer); } NS_FS_END
true
c3e9ed4beadea9e0f3f6d1389d916eeff3097a94
C++
cbedregal/Compressed-Permutations
/src/wavelettree.h
UTF-8
5,874
2.84375
3
[]
no_license
/* wavelettree.h Copyright (C) 2009, Carlos Bedregal, all rights reserved. Implementation of Compressed Representation of Permutations: Runs & SRuns. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WAVELETTREE_H_INCLUDED #define WAVELETTREE_H_INCLUDED #include "hutucker.h" #include "waveletnode.h" using namespace std; /** Class for wavelet tree data structure. Builds a wavelet tree form a Hu-Tucker shaped binarytrie, * it also sorts (merging the nodes) the original permutation. * * @author Carlos Bedregal */ template <class T> class WaveletTree{ public: T* array; //array of values //HuTucker<T>* ht; //pointer to HuTucker tree WTNode* root; int weight; public: WaveletTree(); WaveletTree(HuTucker<T>* ht, T* array); WaveletTree(T* array, int* runs, int ro); ~WaveletTree(); void recBuild(BNode<T>* bNode, WTNode* wNode); void recPrint(WTNode* node); void recDestruct(WTNode* node); void recBitsRequired(WTNode* node, unsigned int& bitsReq); }; template <class T> WaveletTree<T>::WaveletTree(){ array=0; root=0; weight=0; } template <class T> WaveletTree<T>::WaveletTree(HuTucker<T>* ht, T* array){ assert(ht!=0); assert(array!=0); this->array=array; root=new WTNode(ht->root->w); weight=1; recBuild(ht->root, root); assert(weight==ht->weight); } template <class T> WaveletTree<T>::WaveletTree(T* array, int* runs, int ro){ #ifdef PRINT cout<<"- Building WaveletTree: "<<ro<<" run\n"; #endif //PRINT assert(array!=0); assert(runs!=0); assert(ro>0); this->array=array; HuTucker<T>* ht = new HuTucker<T>(runs,ro); //HuTucker<T>* ht = new HuTucker<T>(p); assert(ht->len=ro); assert(ht->root!=0); root=new WTNode(ht->root->w); weight=1; recBuild(ht->root, root); assert(weight==ht->weight); #ifdef PRINT cout<<"- "<<weight<<" nodes\n"; #endif //PRINT delete ht; } template <class T> WaveletTree<T>::~WaveletTree(){ recDestruct(root); } template <class T> void WaveletTree<T>::recBuild(BNode<T>* bNode, WTNode* wNode){ //build nodes on the wavelet-tree only for internal nodes of hu-tucker if(bNode->children[0]->type!=0){ weight++; wNode->children[0]=new WTNode(bNode->children[0]->w); recBuild(bNode->children[0],wNode->children[0]); } if(bNode->children[1]->type!=0){ weight++; wNode->children[1]=new WTNode(bNode->children[1]->w); recBuild(bNode->children[1],wNode->children[1]); } //merge of nodes (merge both bitmaps and sort the area covered by the nodes) int i,j,k; uint* bitmap = new uint[uint_len(bNode->w,1)]; //int* mergeArea=new int[wNode->size]; int* mergeArea=new int[bNode->w]; for(i=0,j=bNode->children[1]->w-1,k=0; i<bNode->children[0]->w && j>=0; k++){ if(array[bNode->endpoint[0]+i]<array[bNode->endpoint[1]-j]){ //bitclean(wNode->bitmap,k); bitclean(bitmap,k); mergeArea[k]=array[bNode->endpoint[0]+i]; i++; } else{ //bitset(wNode->bitmap,k); bitset(bitmap,k); mergeArea[k]=array[bNode->endpoint[1]-j]; j--; } } for(; i<bNode->children[0]->w; i++,k++){ //bitclean(wNode->bitmap,k); bitclean(bitmap,k); mergeArea[k]=array[bNode->endpoint[0]+i]; } for(; j>=0; j--,k++){ //bitset(wNode->bitmap,k); bitset(bitmap,k); mergeArea[k]=array[bNode->endpoint[1]-j]; } //for(k=0; k<wNode->size; k++) for(k=0; k<bNode->w; k++) array[k+bNode->endpoint[0]]=mergeArea[k]; //end of merge //wNode->createBitseq(); wNode->createBitseq(bitmap,bNode->w); #ifdef DEBUG //for(k=0; k<root->size; k++) // cout<<array[k]<<" "; //cout<<endl; #endif //DEBUG delete[]bitmap; delete[]mergeArea; } template <class T> void WaveletTree<T>::recPrint(WTNode* node){ if(!node){ cout<<"null\n"; return; } node->print(); cout<<"down\n"; cout<<"left: "; recPrint(node->children[0]); cout<<"right: "; recPrint(node->children[1]); cout<<"up\n"; } template <class T> void WaveletTree<T>::recDestruct(WTNode* node){ if(!node) return; recDestruct(node->children[0]); recDestruct(node->children[1]); delete node; } template <class T> void WaveletTree<T>::recBitsRequired(WTNode* node, unsigned int& bitsReq){ int nodeBits = node->bitseq->length(); //bits requiered for: [ (#ints) node's bitmap + (#ints) rank&select (5%) ] * W=32 bitsReq += (nodeBits/W+1 + nodeBits/(W*FACTOR)+1)*W; //((static_bitsequence_brw32*)node->bitseq)->SpaceRequirementInBits(); //bits requiered for rank&select constants: size of bitmap //WARNING: the real implementation considers 3 constants: size+factor+flag //bitsReq += 1*W; //bits for the tree pointers: 2 bits (one for children: 1 or 0) //bitsReq += 2; if(node->children[0]) recBitsRequired(node->children[0],bitsReq); if(node->children[1]) recBitsRequired(node->children[1],bitsReq); } #endif // WAVELETTREE_H_INCLUDED
true
b6d28706378eb4d3ab801537b7d6b44d2bbf4814
C++
sindri69/pizza420
/PallaUpdate 11.12.2017/PP Backup/014 Payments tilbúið (Bara Pizzas)/VIEW/BasicView.cpp
UTF-8
382
2.625
3
[]
no_license
#include "BasicView.h" #include "BasicRead.h" BasicView::BasicView() { } void BasicView::view_basic() { BasicRead br; if (br.fileNotEmpty()) { cout << "(L = $" << br.get_Line(1) << ") "; cout << "(M = $" << br.get_Line(2) << ") "; cout << "(S = $" << br.get_Line(3) << ")" << endl; } else { cout << "File is empty" << endl; } }
true