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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
44350dd4d72d001120700b3837e68f7d2637b10a | C++ | shirataki707/ArduinoRobot | /pbl_main/pbl_main.ino | UTF-8 | 2,083 | 2.875 | 3 | [] | no_license | /* 後期PBL プログラム
*
* created : 2020/12/15
*
* contents : pbl_main.ino メインプログラム
* pbl_walk.ino 歩行プログラム
* pbl_pk.ino PK競技用の関数
*
*/
#include <Servo.h>
#include <Sensor.h>
Servo sv[4][3];
Sensor sensorRight(A0), sensorLeft(A1);
const float THRESHOLD = 60.0; // 距離の閾値
// ピン番号
const int MOTORPIN[4][3] = {{2, 3, 4},
{5, 6, 7},
{8, 9, 10},
{11, 12, 13}};
/* モータの位置とピン番号
* 右前足上からsv[0][0]~sv[0][2]
* 左前足上からsv[1][0]~sv[1][2]
* 右後足上からsv[2][0]~sv[2][2]
* 左後足上からsv[3][0]~sv[3][2]
*/
void setup() {
// ピン接続
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++) {
sv[i][j].attach(MOTORPIN[i][j]);
}
}
// 活動内容によって選択する
// changeBreakMode(); // 脚を折りたたむ : 収納時用
// pkStandby(); // モータ角度の初期化 : PK競技用
// walkStandby(); // モータ角度の初期化 : 歩行用
delay(5000); // 5秒待機
Serial.begin(9600); // シリアル通信の開始
}
void loop() {
// 活動内容によってコメントを外す
// 歩行
// walk();
/*
// PK競技
if(sensorLeft.sensing() < THRESHOLD) {
defendLeft();
}
// 右前方のセンシング
else if(sensorRight.sensing() < THRESHOLD) {
defendRight();
}
// else の場合は静止
*/
}
// 持ち運ぶ際に足を折りたたんで収納する
void changeBreakMode() {
const int BREAK_MOTORDEGREE[4][3] = {{90, 10, 90},
{90, 170, 95},
{90, 160, 90},
{90, 20, 90}};
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++) {
sv[i][j].write(BREAK_MOTORDEGREE[i][j]);
}
}
delay(10000);
}
| true |
19cdda56c78c9ca8c7b1afced8cfe29376f7828a | C++ | yycccccccc/Leetcode | /239.Sliding Window Maximum.cpp | UTF-8 | 2,068 | 3.75 | 4 | [] | no_license | 题意:
在窗口内返回最大值。
方法一:priority_queue
T(n) = nlogn;
思路:
1.因为最大堆的性质,每次能返回最大值,那么所有遍历到的点都放入heap中。
注意heap中的类型是pair,第一个元素是值,第二个元素师坐标位置。
2.如果坐标位置小于当前遍历到的位置-k,说明这个最大值已经不在窗口范围内,那么pop
3.如果遍历到的位置坐标大于k-1,即如果超出了第一个窗口的长度,那么每次都需要返回一个值,返回的就是heap顶的最大值。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
priority_queue<pair<int,int>>q;
vector<int> ret;
for(int i = 0; i < nums.size();++i){
while(!q.empty() && q.top().second <= i-k) q.pop();
q.push(make_pair(nums[i],i));
if(i >= k-1){
ret.push_back(q.top().first);
}
}
return ret;
}
};
方法2:deque,双向队列
T(n) = n;
思路:
1.双向队列的区别在于pop需要区分为pop_front()和pop_back(),push()也要区分前后
2.queue的顶部放的是目前的较大元素,只要遍历到的位置比k-1大,那么每次需要push进去一个新的值。
3.如果不为空且q的头部元素小于i-k,说明窗口已经移动走,那么直接把头部元素弹出。
如果q尾部的元素小于当前值,那么尾部元素跳出,push进去新的值。
注意:
q中存放的是坐标位置,便于比较窗口是否在其范围内以及是否应该在结果中push进去顶部元素。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int>vec;
deque<int>q;
for(int i = 0; i< nums.size();++i){
if(!q.empty() && q.front() <= i-k) q.pop_front();
while(!q.empty() && nums[q.back()] < nums[i]) q.pop_back();
q.push_back(i);
if(i >= k-1){
vec.push_back(nums[q.front()]);
}
}
return vec;
}
}; | true |
b7e5999cf1d29123408cfe8da5b91556309ac830 | C++ | vermouth1992/Leetcode | /cpp/1662.check-if-two-string-arrays-are-equivalent.cpp | UTF-8 | 2,592 | 3.453125 | 3 | [
"MIT"
] | permissive | /*
* @lc app=leetcode id=1662 lang=cpp
*
* [1662] Check If Two String Arrays are Equivalent
*
* https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/description/
*
* algorithms
* Easy (82.27%)
* Total Accepted: 232.5K
* Total Submissions: 279.3K
* Testcase Example: '["ab", "c"]\n["a", "bc"]'
*
* Given two string arrays word1 and word2, return true if the two arrays
* represent the same string, and false otherwise.
*
* A string is represented by an array if the array elements concatenated in
* order forms the string.
*
*
* Example 1:
*
*
* Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
* Output: true
* Explanation:
* word1 represents string "ab" + "c" -> "abc"
* word2 represents string "a" + "bc" -> "abc"
* The strings are the same, so return true.
*
* Example 2:
*
*
* Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
* Output: false
*
*
* Example 3:
*
*
* Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
* Output: true
*
*
*
* Constraints:
*
*
* 1 <= word1.length, word2.length <= 10^3
* 1 <= word1[i].length, word2[i].length <= 10^3
* 1 <= sum(word1[i].length), sum(word2[i].length) <= 10^3
* word1[i] and word2[i] consist of lowercase letters.
*
*
*/
#include "common.hpp"
class Solution {
public:
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
int word1WordIndex = 0;
int word1CharIndex = 0;
int word2WordIndex = 0;
int word2CharIndex = 0;
while (true) {
// both of them reaches the end
if (word1WordIndex >= word1.size() && word2WordIndex >= word2.size()) {
return true;
}
// one of them reaches the end
if (word1WordIndex >= word1.size() || word2WordIndex >= word2.size()) {
return false;
}
// compare the current char
if (word1.at(word1WordIndex).at(word1CharIndex) == word2.at(word2WordIndex).at(word2CharIndex)) {
// get next pos
word1CharIndex += 1;
if (word1CharIndex == word1.at(word1WordIndex).length()) {
word1WordIndex += 1;
word1CharIndex = 0;
}
word2CharIndex += 1;
if (word2CharIndex == word2.at(word2WordIndex).length()) {
word2WordIndex += 1;
word2CharIndex = 0;
}
} else {
return false;
}
}
}
};
| true |
05367ff04c9c29c8096781ea1ab4529a9c40c001 | C++ | chenzuhai/data-structure | /二叉树的构造.cpp | GB18030 | 1,486 | 3.65625 | 4 | [] | no_license | #include<iostream>
using namespace std;
#define Elemtype char
//ʼ
typedef struct Btree
{
Elemtype data;//ڵ
struct Btree *Lchild;//ָ
struct Btree *Rchild;//ָ
}Btree,*ptrBtree;
//
ptrBtree CreateBtree(char *pre, char*mid, int n)
{
char *p = NULL;
Btree *q = NULL;
if (n <= 0)
return NULL;
q = (Btree*)malloc(sizeof(Btree));
q->data = *pre;
p = mid;
for (p; p < mid + n; p++)
{
if (*p == *pre)
break;
}
int k = p - mid;
q->Lchild = CreateBtree(pre + 1, mid, k);
q->Rchild = CreateBtree(pre + 1 + k, p + 1, n - k -1 );
return q;
}
//ݹ
//
void PreOrder(ptrBtree T)
{
if (T)
{
cout << T->data << ' ';
PreOrder(T->Lchild);
PreOrder(T->Rchild);
}
}
//
void InOrder(ptrBtree T)
{
if (T)
{
InOrder(T->Lchild);
cout << T->data << ' ';
InOrder(T->Rchild);
}
}
//
void PostOrder(ptrBtree T)
{
if (T)
{
PostOrder(T->Lchild);
PostOrder(T->Rchild);
cout << T->data << ' ';
}
}
//ݽṹ7ҵ
void InOrder1(ptrBtree T)
{
if (T)
{
InOrder1(T->Lchild);
if(T->data>='A'&&T->data<='C')
cout << T->data << ' ';
InOrder1(T->Rchild);
}
}
int main()
{
Btree *b = NULL;
char pre[] = "ABDECFG";
char in[] = "DBEAFCG";
b = CreateBtree(pre, in, 7);
cout << "" << endl;
PreOrder(b);
cout << endl;
cout << "" << endl;
InOrder1(b);
cout << endl;
cout << "" << endl;
PostOrder(b);
return 0;
}
| true |
6b51043936036246b723049e95cc36406ad13b3f | C++ | PaulGrvd/cpptp4 | /main.cpp | UTF-8 | 9,133 | 2.71875 | 3 | [] | no_license | /*************************************************************************
main - fonction principale de l'application
-------------------
Début : Decembre 2019
Copyright : (C) 2019 par Paul Grévaud, Yohan MEYER (Binôme )
E-mail : yohan.meyer@insa-lyon.fr - paul.grevaud@insa-lyon.fr
*************************************************************************/
//---------- Réalisation de la classe <main> (fichier main.cpp) ------------
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include système
//------------------------------------------------------ Include personnel
#include "Logs.h"
#include "Fichier.h"
#include "Donnees.h"
#include <string>
#include <iostream>
//------------------------------------------------------------- Constantes
//----------------------------------------------------------------- PUBLIC
//----------------------------------------------------- Méthodes publiques
bool estExclusion(string option);
bool estHeure(string option);
bool estGraphe(string option);
int recupHeure(string option);
int main(int argc, char *argv[])
{
if(argc == 1)
{
cerr << "Pas de nom de fichier de logs." << endl;
return 0;
}
string nomFichierLog = string(argv[argc-1]);
if (nomFichierLog.find(".log") == string::npos)
{
cerr << "Le nom de fichier rentré ne contient pas l'extension '.log'." << endl;
return 0;
}
for(int i = 1 ; i <= argc-3 ; ++i)
{
if(estGraphe(string(argv[i])))
{
string nomFichierGraphe = string(argv[i+1]);
if (nomFichierGraphe.find(".dot") == string::npos)
{
cerr << "Le nom de fichier de graphe rentré ne contient pas l'extension '.dot'." << endl;
return 0;
}
}
}
Donnees data = Donnees();
bool traceGraphe = false;
switch(argc)
{
case 2:
data.update(0);
break;
case 3:
if(estExclusion(string(argv[1]))) // -e
data.update(1);
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
break;
case 4:
if(estGraphe(string(argv[1]))) // -g
{
traceGraphe = true;
data.update(0);
} else if(estHeure(string(argv[1]))) // -t
{
int heure;
heure = recupHeure(string(argv[2]));
if(heure == -1)
return 0;
data.update(2, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
break;
case 5:
if(estExclusion(string(argv[1]))) // -e
{
if(estGraphe(string(argv[2]))) // -g
{
traceGraphe = true;
data.update(1);
} else if(estHeure(string(argv[2]))) // -t
{
int heure;
heure = recupHeure(string(argv[3]));
if(heure == -1)
return 0;
data.update(3, heure);
}
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estHeure(string(argv[1]))) // -t
{
int heure;
heure = recupHeure(string(argv[2]));
if(heure == -1)
return 0;
if(estExclusion(string(argv[3]))) // -e
data.update(3, heure);
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estGraphe(string(argv[1]))) // -g
{
traceGraphe = true;
if(estExclusion(string(argv[3]))) // -e
data.update(1);
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
break;
case 6:
if(estHeure(string(argv[1]))) // -t
{
int heure;
heure = recupHeure(string(argv[2]));
if(heure == -1)
return 0;
if(estGraphe(string(argv[3]))) // -g
{
traceGraphe = true;
data.update(2, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estGraphe(string(argv[1]))) // -g
{
traceGraphe = true;
if(estHeure(string(argv[3]))) // -t
{
int heure;
heure = recupHeure(string(argv[4]));
if(heure == -1)
return 0;
data.update(2, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
break;
case 7:
if(estHeure(string(argv[1]))) // -t
{
int heure;
heure = recupHeure(string(argv[2]));
if(heure == -1)
return 0;
if(estGraphe(string(argv[3]))) // -g
{
traceGraphe = true;
if(estExclusion(string(argv[5]))) // -e
{
data.update(3, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estGraphe(string(argv[4]))) // -g
{
traceGraphe = true;
if(estExclusion(string(argv[3]))) // -e
{
data.update(3, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estGraphe(string(argv[1]))) // -g
{
traceGraphe = true;
if(estHeure(string(argv[3]))) // -t
{
int heure;
heure = recupHeure(string(argv[4]));
if(heure == -1)
return 0;
if(estExclusion(string(argv[5]))) // -e
data.update(3, heure);
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estHeure(string(argv[4]))) // -t
{
int heure;
heure = recupHeure(string(argv[5]));
if(heure == -1)
return 0;
if(estExclusion(string(argv[3]))) // -e
data.update(3, heure);
else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estExclusion(string(argv[1]))) // -e
{
if(estHeure(string(argv[2]))) // -t
{
int heure;
heure = recupHeure(string(argv[3]));
if(heure == -1)
return 0;
if(estGraphe(string(argv[4]))) // -g
{
traceGraphe = true;
data.update(3, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else if(estGraphe(string(argv[2]))) // -g
{
traceGraphe = true;
if(estHeure(string(argv[4]))) // -t
{
int heure;
heure = recupHeure(string(argv[5]));
if(heure == -1)
return 0;
data.update(3, heure);
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
} else
{
cerr << "Option non reconnue. Veuillez réessayer." << endl;
return 0;
}
break;
default:
break;
}
//cout << "Fin du gros switch." << endl;
Fichier monFic(nomFichierLog);
string line;
if(!monFic.etatFichier())
{
cerr << "Impossible d'ouvrir le fichier." << endl;
return 0;
}
do
//for(int i = 0 ; i < 10 ; ++i)
{
line = monFic.getLine();
if(line.compare("EOF") == 0 || line.compare("ERREUR") == 0 || line.compare("EOFF") == 0)
break;
Logs monLog(line);
data.ajouter(monLog.geturl_referer(), monLog.geturl_doc(), monLog.getheure());
} while(true);
//cout << endl << "Ligne de sortie : " << line << endl;
// EOFF -> ligne vide, EOF -> fin de fichier, ERREUR -> failbit ou badbit du flux de lecture activé
//data.afficher(2);
data.TopTen();
if(traceGraphe)
{
//cout << "Traçons le graphe !" << endl;
data.graph();
}
cout << "Fin du programme." << endl;
return 0;
} //----- Fin de main
bool estExclusion(string option)
{
if(option.compare("-e"))
{
//cerr << "Option non reconnue. Veuillez réessayer." << endl;
return false;
}
return true;
}
bool estHeure(string option)
{
if(option.compare("-t"))
{
//cerr << "Option non reconnue. Veuillez réessayer." << endl;
return false;
}
return true;
}
bool estGraphe(string option)
{
if(option.compare("-g"))
{
//cerr << "Option non reconnue. Veuillez réessayer." << endl;
return false;
}
return true;
}
int recupHeure(string option)
{
int heure;
if(option.length() > 2)
{
cerr << "Heure non valide. Veuillez réessayer." << endl;
return -1;
}
try
{
heure = stoi(option);
if(heure >= 24 || heure < 0)
{
cerr << "Heure non valide. Veuillez réessayer." << endl;
return -1;
}
//cout << heure << endl;
}
catch (std::invalid_argument const &e)
{
cerr << "Heure non valide. Veuillez réessayer." << endl;
return -1;
}
catch (std::out_of_range const &e)
{
cerr << "Heure non valide. Veuillez réessayer." << endl;
return -1;
}
return heure;
}
| true |
b1c9e010261dca2aecfc71d0c07941cbbc99d0df | C++ | Neelabh-Dubey/Construct-O-Bot | /8_travelling_handler/8_travelling_handler.ino | UTF-8 | 4,178 | 2.859375 | 3 | [] | no_license | /*
* Author list: Neelabh Dubey
* Filename:8_travelling_handler
* Theme:Construct-o-bot
* Fuctions: bool is_house(int),bool is_warehouse(int),int get_dir(int), align_bot(int),go(int),go_next_node(int)
* node_right(),node_left(),node_forward(),turn_180(), follow_walls(),follow_zic_zac(),
* go9_via8(),go9_via10(),return_to_10(),go_to_10(),go_to_8(),return_to_8(),go_next_node(int),go_30(),
* go_next_node(int),read_line(),follow_black_line(int),is_house(int),is_warehouse(int),!is_house(int),!is_warehouse(int)
* Global variables: current_dir, coordinates[int][int],to_dir,to_node,current_node, path[int][int],left_counter,line
*/
/*
* function name:is_house
* input : node number
* output : boolean
* logic : returns boolean value true if the building present at the node is a house
* example call : is_house(6);
*/
bool is_house(int nd){
if (nd >= 28 && nd <= 32) return true;
return false;
}
/*
* function name: is_warehouse
* input : node number
* output : boolean
* logic : returns a boolean value depending on the house is a warehouse or not
* example call : is_warehouse(14);
*/
bool is_warehouse(int nd){
if (nd >= 16 && nd <= 27) return true;
return false;
}
/*
* function: get_dir
* input:Final node number where the bot has to move to
* output:direction code
* logic:Returns direction in which the bot has to move to reach the final input node with respect to the current node
* example call:get_dir(9);
*/
int get_dir(int to_node) {
int to_dir = current_dir;
int a1 = coordinates[current_node][0];
int b1 = coordinates[current_node][1];
int a2 = coordinates[to_node][0];
int b2 = coordinates[to_node][1];
if (b2 > b1) to_dir = 1;
else if (a2 > a1) to_dir = 2;
else if (b1 > b2) to_dir = 3;
else if (a1 > a2) to_dir = 4;
return to_dir;
}
/*
* function: align_bot
* input:node number
* output:void
* logic:It instructs the bot to turn in an appropriate direction
* Example call: align_bot(8);
*/
void align_bot(int to_node) {
int to_dir = get_dir(to_node);
if ((current_dir == to_dir - 1) || (current_dir == 4 && to_dir == 1)) node_right();
else if ((current_dir == to_dir + 1) || (current_dir == 1 && to_dir == 4)) node_left();
else if (current_dir == to_dir) node_forward();
else if (abs(current_dir - to_dir) == 2) turn_180();
current_dir = to_dir;
}
/*
* function: go
* input: node number
* output: void
* logic:This function instructs the bot to move to the destined input node if there is a direct path between the current
* node and input node else it instructs it to move to a node from where it can find a direct path to the destined node
* Example call: go(10);
*/
void go(int node){
if(path[current_node][node] == 0){
if(node != 30 and !(current_node == 9 and current_dir == 3)) align_bot(node);
if((current_node == 4 && node == 14) || (current_node == 14 && node == 4)) follow_walls();
else if((current_node == 6 && node == 12)||(current_node == 12 && node == 6)) follow_zic_zac();
else if(current_node == 8 && node == 9) go9_via8();
else if(current_node == 10 && node == 9) go9_via10();
else if(current_node == 9 && node == 10){
if(current_dir == 3)return_to_10();
else go_to_10();
}
else if(current_node == 9 && node == 8){
if(current_dir == 3) return_to_8();
else go_to_8();
}
else if(current_node == 9 && node == 30) go_30();
else go_next_node(cost[current_node][node]);
if(!is_house(node) and !is_warehouse(node)) current_node = node;
}
else{
go(path[current_node][node]);
go(node);
}
}
/*
* function:go_next_node
* input:one tenth of encoder count b/w current node and next node
* output:void
* logic:It instructs the bot to follow the black line unless a node is found or left encoder completes 10*cst distance
* Example call: go_next_node(26):
*/
void go_next_node(int cst){
if(is_house(current_node)) deb(100);
left_counter = 0;
read_line();
cst*=10;
while(line != "BBB" && left_counter < cst){
follow_black_line(255);
read_line();
}
}
| true |
60c8d605ec2407cd7d8ecb158fb63eb6fac2d760 | C++ | ninfan/Arduino | /03_WebHuminity.ino | UTF-8 | 4,218 | 2.65625 | 3 | [] | no_license |
/*
Web Server
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
Huminity Library von https://github.com/adafruit/DHT-sensor-library
*/
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#define DHTPIN 2 // DHT Data Pin auf Arduino Pin 2
// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,2, 200);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
dht.begin();
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
client.println("Failed to read from DHT sensor");
} else {
float hif = dht.computeHeatIndex(f, h);
float hic = dht.computeHeatIndex(t, h, false);
client.print("Humidity ");
client.print(h);
client.print(" pro t");
client.print("Temperature ");
client.print(t);
client.print(" C ");
client.print(f);
client.print(" F pro t");
client.print("Heat index ");
client.print(hic);
client.print(" C ");
client.print(hif);
client.println(" F");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
| true |
82f1fee896e037b499c37b8a8709dda075d3268a | C++ | MachineMitch21/Things | /Engine/src/Texture2D.h | UTF-8 | 670 | 2.828125 | 3 | [] | no_license | #ifndef TEXTURE2D_H
#define TEXTURE2D_H
#include <GL/glew.h>
#include <string>
class Texture2D
{
public:
Texture2D();
Texture2D(const Texture2D& oldTex2D);
Texture2D(const std::string& file);
~Texture2D();
void Bind(unsigned int unit = 0) const;
void UnBind() const;
inline int GetWidth() const { return _width; };
inline int GetHeight() const { return _height; };
void Load(const std::string& file);
private:
unsigned int _rendererID;
std::string _filePath;
unsigned char* _pixelBuffer;
int _width;
int _height;
int _bytesPerPixel;
};
#endif // TEXTURE2D_H | true |
d94ac600156cba26ab097a1bdb791510f63665c6 | C++ | HelloSunyi/Elements-of-Programming-Interviews | /Chapter_21/c21_15.cpp | UTF-8 | 245 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int find_celebrity(const vector<int>& v){
int i = 0;
int j = 1;
while (j < v.size()) {
if (v[i][j]) {
i = j;
j++;
} else {
j++;
}
}
return i;
}
| true |
b6d8176102b0ef9f628c793e7d9f8b5c1f5b3baa | C++ | mosesx/NDInterpolator | /RBFInterpolator/BoxWeight.hpp | UTF-8 | 4,539 | 2.875 | 3 | [] | no_license | /**
* boxWeight.h
*
* Created on: \date Nov 15, 2010
* Author: \author mrehberg
*/
#ifndef BOXWEIGHT_H_
#define BOXWEIGHT_H_
/** \brief Weight function for partition of unity.
*
* Radialised 1-d Polynomial that is 0 on border of domain and 1 in the middle. Twice continously
* differentiable. based on Tobor, I.; Reuter, P. & Schlick, C. Efficient Reconstruction of Large
* Scattered Geometric Datasets using the Partition of Unity and Radial Basis Functions
*/
namespace NDInterpolator {
class BoxWeight {
public:
double eval(const ublas::vector<double>& inPoint, const ublas::vector<
double>& edgesL, const ublas::vector<double>& edgesR) const;
double
evalDiff(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha) const;
double
evalDiff2(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha) const;
double evalDiffMixed(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha1,
const unsigned alpha2) const;
private:
// serialization.
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
}
};
inline double BoxWeight::eval(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR) const {
double ret = 1.;
for (unsigned i = 0; i < inPoint.size(); i++) {
ret *= ((inPoint(i) - edgesL(i)) * (edgesR(i) - inPoint(i))) / (.25
* ((edgesR(i) - edgesL(i)) * (edgesR(i) - edgesL(i))));
}
// mathematica simplification of Poly(1-ret) in Horner form
// poly: -6x^5+15x^4-10x^3+1
return ret * ret * ret * (10 + ret * (-15 + 6 * ret));
}
inline double BoxWeight::evalDiff(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha) const {
// initialize with factor from derivation
const double dervFac = -(edgesR(alpha - 1) + edgesL(alpha - 1) - 2
* inPoint(alpha - 1)) / ((inPoint(alpha - 1) - edgesL(alpha - 1))
* (edgesR(alpha - 1) - inPoint(alpha - 1)));
double ret = 1.;
for (unsigned i = 0; i < inPoint.size(); i++) {
ret *= ((inPoint(i) - edgesL(i)) * (edgesR(i) - inPoint(i))) / (.25
* ((edgesR(i) - edgesL(i)) * (edgesR(i) - edgesL(i))));
}
// mathematica horner scheme
return ret * ret * ret * (-30 * dervFac + ret * (60 * dervFac - 30 * ret
* dervFac));
}
inline double BoxWeight::evalDiff2(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha) const {
// common denominator for derivative factors
const double denom = ((inPoint(alpha - 1) - edgesL(alpha - 1)) * (edgesR(
alpha - 1) - inPoint(alpha - 1)));
// initialize factor for first order derivative
const double dervFac = -(edgesR(alpha - 1) + edgesL(alpha - 1) - 2
* inPoint(alpha - 1)) / denom;
// initialize factor for second order derivative
const double dervFac2 = 2 / denom;
double ret = 1.0;
for (unsigned i = 0; i < inPoint.size(); i++) {
ret *= ((inPoint(i) - edgesL(i)) * (edgesR(i) - inPoint(i))) / (.25
* ((edgesR(i) - edgesL(i)) * (edgesR(i) - edgesL(i))));
}
// mathematica Horner Form
return ret * ret * ret * (60 * dervFac * dervFac - 30 * dervFac2 + ret
* (-180 * dervFac * dervFac + 60 * dervFac2 + (120 * dervFac
* dervFac - 30 * dervFac2) * ret));
}
double BoxWeight::evalDiffMixed(const ublas::vector<double>& inPoint,
const ublas::vector<double>& edgesL,
const ublas::vector<double>& edgesR, const unsigned alpha1,
const unsigned alpha2) const {
const double dervFacA1 = (edgesR(alpha1 - 1) + edgesL(alpha1 - 1) - 2
* inPoint(alpha1 - 1))
/ ((inPoint(alpha1 - 1) - edgesL(alpha1 - 1)) * (edgesR(alpha1 - 1)
- inPoint(alpha1 - 1)));
const double dervFacA2 = (edgesR(alpha2 - 1) + edgesL(alpha2 - 1) - 2
* inPoint(alpha2 - 1))
/ ((inPoint(alpha2 - 1) - edgesL(alpha2 - 1)) * (edgesR(alpha2 - 1)
- inPoint(alpha2 - 1)));
double ret = 1.0;
for (unsigned i = 0; i < inPoint.size(); i++) {
ret *= ((inPoint(i) - edgesL(i)) * (edgesR(i) - inPoint(i))) / (.25
* ((edgesR(i) - edgesL(i)) * (edgesR(i) - edgesL(i))));
}
// mathematica Horner Form
return dervFacA1 * dervFacA2 * ret * ret * ret * (90 + ret * (-240 + 150
* ret));
}
}
#endif /* BOXWEIGHT_H_ */
| true |
f5ecc7244bacd6feed586e0baa3d70ae7fb066fc | C++ | UESTCzhouyuchuan/Algorithmic | /ACM算法题/befsummer_trainOne2.cpp | WINDOWS-1252 | 1,656 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
//lazyǩ߶
using namespace std;
#define N 1000001
#define LL long long
#define mid (left+right)/2
#define lson r<<1,left,mid
#define rson r<<1|1,mid+1,right
typedef struct{
int left,right;
LL sum;
}dot;
dot Dot[N*4];
int father[N];
LL lazy[N];
void BuildTreeB(int r,int left,int right);
void QueryB(int r,int left,int right);
void UpdateB(int r,LL addnum);
LL Sum;
int main(void)
{
memset(father,0,sizeof(father));
memset(Dot,0,sizeof(Dot));
memset(lazy,0,sizeof(lazy));
int n,m;
scanf("%d %d",&n,&m);
BuildTreeB(1,1,n);
LL addnum;
int x1,x2;
int type,i;
while (m--)
{
scanf ("%d",&type);
if (type==0)
{
scanf ("%d %d %lld",&x1,&x2,&addnum);
for (i=x1;i<=x2;i++)
lazy[i]+=addnum;
}
else
{
Sum=0;
scanf ("%d %d %lld",&x1,&x2,&addnum);
for (i=x1;i<=x2;i++)
{
if (lazy[i])
{
UpdateB(father[i],lazy[i]);
lazy[i]=0;
}
}
QueryB(1,x1,x2);
printf("%lld\n",Sum);
}
}
return 0;
}
void BuildTreeB(int r,int left,int right)
{
Dot[r].left=left;Dot[r].right=right;Dot[r].sum=0;
if (left==right)
{
father[left]=r;
}
else
{
BuildTreeB(lson);
BuildTreeB(rson);
}
}
void QueryB(int r,int left,int right){
if (left==Dot[r].left&&right==Dot[r].right)
{
Sum+=Dot[r].sum;
}
else
{
int rt=r<<1;
if (right<=Dot[rt].right)
QueryB(rt,left,right);
else if (left>=Dot[rt+1].left)
QueryB(rt+1,left,right);
else
{
QueryB(rt,left,Dot[rt].right);
QueryB(rt+1,Dot[rt+1].left,right);
}
}
}
void UpdateB(int r,LL addnum){
Dot[r].sum+=addnum;
if (r==1)
{
return ;
}
UpdateB(r>>1,addnum);
}
| true |
64c30b0335d951dd53a64679e891a2fb6168d2de | C++ | balancedbanana/balancedbanana | /include/database/worker_details.h | UTF-8 | 880 | 2.703125 | 3 | [] | no_license | #pragma once
#include <database/Specs.h>
#include <string>
#include <cstdint>
#include <optional>
namespace balancedbanana {
namespace database {
struct worker_details {
//The id of the Worker.
uint64_t id;
std::string name;
//The specs of the worker.
std::optional<Specs> specs;
std::string public_key;
// true if empty, otherwise false;
bool empty = true;
inline bool operator==(const worker_details& rhs){
return ((!this->specs.has_value() && !rhs.specs.has_value()) ||
(this->specs.value() == rhs.specs.value()))
&& this->public_key == rhs.public_key
&& this->name == rhs.name
&& this->empty == rhs.empty;
}
};
}
} | true |
9a220de5bcd5e9b9def5b5b80c6c60b6627943ae | C++ | code-dreamer/CodeSnippets | /cpp/DebugTools.cpp | UTF-8 | 1,076 | 2.65625 | 3 | [] | no_license | #include "stdafx.h"
#include <csignal>
#include "DebugTools.h"
int DebugTools::ShowDebugMessageBox(const wchar_t* expression, const wchar_t* functionName,
const wchar_t* filename, unsigned lineNumber, const wchar_t* errorMessage)
{
wchar_t exeName[MAX_PATH];
GetModuleFileNameW(nullptr, exeName, MAX_PATH);
std::wstringstream customMessage;
if (errorMessage != nullptr) {
customMessage << L"Error message: '" << errorMessage << L"'" << std::endl;
}
std::wstringstream message;
message << L"Assertion failed!" << std::endl
<< std::endl
<< L"Program: " << exeName << std::endl
<< std::endl
<< L"Expression: '" << expression << L"'"
<< std::endl
<< customMessage.str()
<< std::endl
<< L"Function: " << functionName << std::endl
<< L"File: " << filename << std::endl
<< L"Line: " << lineNumber << std::endl;
return MessageBoxW(0, message.str().c_str(), L"Assertion", MB_ICONERROR | MB_ABORTRETRYIGNORE);
}
void DebugTools::AbortApplication()
{
raise(SIGABRT); \
_exit(3);
}
| true |
38b1adefa520cb45d3378b31c084886802899986 | C++ | michelleferd/CS112-1 | /lab01/Song.h | UTF-8 | 471 | 2.671875 | 3 | [] | no_license | /*
* Song.h
*
* Created on: Sep 10, 2019
* Author: mjs96
*/
#ifndef SONG_H
#define SONG_H
#include <string>
using namespace std;
class Song {
public:
Song();
string getTitle() const;
string getArtist() const;
unsigned getYear() const;
Song(const string& title, const string& artist, unsigned year);
void readFrom(istream& in);
void writeTo(ostream& out) const;
private:
string myTitle;
string myArtist;
unsigned myYear;
};
#endif /*SONG_H_*/
| true |
8124f295a59b6382d5eeb30767693e88942985ab | C++ | WhiZTiM/coliru | /Archive/75108322ff3341362f64b04488afdffc-61c3814520a8d4318f681038dc4b4da7/main.cpp | UTF-8 | 3,351 | 3.328125 | 3 | [] | no_license | #include <boost/operators.hpp>
#include <iostream>
#include <tuple>
#include <stdint.h>
template<typename T>
struct DefaultWrap : std::tuple<T> {
DefaultWrap(const T & t = T{}) : std::tuple<T>(t) {}
friend std::ostream& operator<<(std::ostream & os, const DefaultWrap<T> & t) { return os << std::get<0>(t); }
};
template<typename T>
struct NumericWrap : DefaultWrap<T>, boost::operators<NumericWrap<T>>
{
NumericWrap(T t = T{}) : DefaultWrap<T>(t) {}
operator T() const { return std::get<0>(*this); }
void operator +=(NumericWrap<T> v) { std::get<0>(*this) += v; }
void operator -=(NumericWrap<T> v) { std::get<0>(*this) -= v; }
};
template<typename T>
using Wrap = typename std::conditional<std::is_integral<T>::value, NumericWrap<T>, DefaultWrap<T>>::type;
using Int16 = Wrap<int16_t>;
using Int32 = Wrap<int32_t>;
using Int64 = Wrap<int64_t>;
template<typename T, class Head, class ...Tail>
struct Decorate : Head, Decorate<T, Tail...> {
Decorate(const T & t = T{}) : Head(), Decorate<T, Tail...>(t) {}
};
template<typename T, class Head>
struct Decorate<T, Head> : Head, Wrap<T> {
Decorate(const T & t = T{}) : Wrap<T>(t) {}
};
struct Alphabetic {};
struct Numeric {};
template<typename> struct IsAlphabetic : std::false_type {};
template<> struct IsAlphabetic<char> : std::true_type {};
template<typename> struct IsNumeric : std::false_type {};
template<> struct IsNumeric<int8_t > : std::true_type {};
template<> struct IsNumeric<int16_t> : std::true_type {};
template<> struct IsNumeric<int32_t> : std::true_type {};
template<> struct IsNumeric<int64_t> : std::true_type {};
template<> struct IsNumeric<uint8_t > : std::true_type {};
template<> struct IsNumeric<uint16_t> : std::true_type {};
template<> struct IsNumeric<uint32_t> : std::true_type {};
template<> struct IsNumeric<uint64_t> : std::true_type {};
template<template<class, typename ...> class WrapType, typename Head, typename ...Tail>
struct IsNumeric<WrapType<Head, Tail...>> : IsNumeric<Head> {};
template<template<class, typename ...> class WrapType, typename Head, typename ...Tail>
struct IsAlphabetic<WrapType<Head, Tail...>> : IsAlphabetic<Head> {};
using Number = Decorate<int , Numeric>;
using Letter = Decorate<char, Alphabetic>;
using Character = Decorate<char, Alphabetic, Numeric>;
struct is_alphabetic_tag {};
struct is_numeric_tag {};
struct is_alphanumeric_tag {};
template<typename T>
void print_(T t, is_alphanumeric_tag) {
std::cout << "Alphanumeric: " << t << std::endl;
}
template<typename T>
void print_(T t, is_alphabetic_tag) {
std::cout << "Alphabetic: " << t << std::endl;
}
template<typename T>
void print_(T t, is_numeric_tag) {
std::cout << "Numeric: " << t << std::endl;
}
template<typename T>
void print(T t) {
print_(t,
typename std::conditional<
IsNumeric<T>::value,
typename std::conditional<IsAlphabetic<T>::value, is_alphanumeric_tag, is_numeric_tag >::type,
is_alphabetic_tag
>::type());
}
int main() {
print(Number{42});
print(Letter{'L'});
print(Character{'c'});
Int32 i{3}, j{4}, k{5};
std::cout << (i + j - k) << std::endl;
};
| true |
ebbf3ca7ececb21dfd018777cc93f4f30f28d7ed | C++ | danyfang/SourceCode | /cpp/leetcode/NumberOfTeams.cpp | UTF-8 | 812 | 3.34375 | 3 | [
"MIT"
] | permissive | //Leetcode Problem No 1395 Number of Teams
//Solution written by Xuqiang Fang on 4 April, 2020
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution {
public:
int numTeams(vector<int>& r) {
const int n = r.size();
int ans = 0;
for(int i=0; i<n-2; ++i){
for(int j=i+1; j<n-1; ++j){
for(int k=j+1; k<n; ++k){
if((r[i] < r[j] && r[j] < r[k]) || (r[i] > r[j] && r[j] > r[k])){
ans++;
}
}
}
}
return ans;
}
};
int main(){
Solution s;
vector<int> r = {2,5,3,4,1};
cout << s.numTeams(r) << endl;
r = {2,1,3};
cout << s.numTeams(r) << endl;
r = {1,2,3,4};
cout << s.numTeams(r) << endl;
return 0;
}
| true |
60caccb30c503963b2e59f3287c09bda8538d7fa | C++ | RiceReallyGood/LeetCode_Revise | /201-300/211_Add_and_Search_Word - Data_structure_design.h | UTF-8 | 1,439 | 3.890625 | 4 | [] | no_license | #include <string>
#include <memory.h>
using namespace std;
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() { root = new TrieNode(); }
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* node = root;
for(char& c : word){
if(node->next[c - 'a'] == nullptr)
node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->isword = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(root, word, 0);
}
private:
class TrieNode{
public:
bool isword;
TrieNode* next[26];
TrieNode() : isword(false){ memset(next, 0, 26 * sizeof(TrieNode*)); }
};
TrieNode* root;
bool search(TrieNode* root, string& s, int index){
while(index < s.length() && s[index] != '.'){
if(root->next[s[index] - 'a'] == nullptr)
return false;
root = root->next[s[index++] - 'a'];
}
if(index == s.length())
return root->isword;
for(int c = 0; c < 26; c++){
if(root->next[c] != nullptr && search(root->next[c], s, index + 1))
return true;
}
return false;
}
}; | true |
66410143df233c72a083ce95cbe4014224b9a881 | C++ | bglasber/LogRipper | /src/parse_buffer.h | UTF-8 | 1,097 | 2.921875 | 3 | [] | no_license | #ifndef __PARSE_BUFFER_H__
#define __PARSE_BUFFER_H__
#include "token.h"
#include "config.h"
#include <mutex>
#include <condition_variable>
#include <list>
#include <vector>
#include <memory>
//A buffer of pointers to parsed lines
//Used to pass "units of work" between the components
struct ParseBuffer {
unsigned ind;
std::unique_ptr<std::vector<TokenWordPair>> parsed_lines[ LINES_IN_BUFFER ];
ParseBuffer();
void destroyBufferLines();
bool addLine( std::unique_ptr<std::vector<TokenWordPair>> line );
};
//Manages passing buffers back and forth using mutex/cv
//Destroys held buffers on destruction
class ParseBufferEngine {
std::mutex mut;
std::condition_variable cv;
std::list<std::unique_ptr<ParseBuffer>> ready_buffers;
bool term_when_out_of_buffers;
public:
ParseBufferEngine();
~ParseBufferEngine();
std::unique_ptr<ParseBuffer> getNextBuffer();
void termWhenOutOfBuffers();
void putNextBuffer( std::unique_ptr<ParseBuffer> buff );
//For unit tests
std::list<std::unique_ptr<ParseBuffer>> &getReadyBuffers();
};
#endif
| true |
bd2692d441238e0252066227f70a0d1f02a94faf | C++ | Bargor/tempest | /src/core/time/timer.h | UTF-8 | 2,298 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-happy-bunny",
"Zlib",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | // This file is part of Tempest-core project
// Author: Karol Kontny
#pragma once
#include <assert.h>
#include <chrono>
#include <core.h>
#include <cstdint>
#include <platform.h>
#include <ratio>
namespace tst {
namespace core {
using hr_clock = std::chrono::high_resolution_clock;
using sys_clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<hr_clock, std::chrono::microseconds>;
class timer {
public:
using clock_type = hr_clock;
public:
template<typename U, typename T>
using dur = std::chrono::duration<U, T>;
public:
timer() noexcept;
~timer() = default;
void start() noexcept;
void stop() noexcept;
void reset() noexcept;
std::chrono::microseconds get_time() const noexcept;
bool started() const noexcept;
time_point now() const noexcept;
private:
hr_clock m_timer;
std::chrono::time_point<hr_clock> m_lastStart;
dur<std::int64_t, std::nano> m_elapsedTime;
bool m_started;
};
TST_INLINE tst::core::timer::timer() noexcept : m_elapsedTime(std::chrono::nanoseconds::zero()), m_started(false) {
}
TST_INLINE void timer::start() noexcept {
m_started = true;
m_lastStart = m_timer.now();
}
TST_INLINE void timer::stop() noexcept {
assert(m_started);
m_elapsedTime += (m_timer.now() - m_lastStart);
m_started = false;
}
TST_INLINE void timer::reset() noexcept {
m_started = false;
m_elapsedTime = std::chrono::nanoseconds::zero();
}
TST_INLINE std::chrono::microseconds timer::get_time() const noexcept {
return m_started ? std::chrono::duration_cast<std::chrono::microseconds>(m_timer.now() - m_lastStart) :
std::chrono::duration_cast<std::chrono::microseconds>(m_elapsedTime);
}
TST_INLINE bool timer::started() const noexcept {
return m_started;
}
TST_INLINE time_point timer::now() const noexcept {
return m_started ? std::chrono::time_point_cast<std::chrono::microseconds>(m_timer.now()) :
std::chrono::time_point_cast<std::chrono::microseconds>(m_lastStart + m_elapsedTime);
}
} // namespace core
} // namespace tst
| true |
527de819d7fd36fd5b22e7cc2dbe65f8a31b73bf | C++ | keptan/frisbee | /src/main.cpp | UTF-8 | 5,380 | 2.640625 | 3 | [] | no_license | #include "hashDB.h"
#include "image.h"
#include "transactional.h"
#include "db_init.h"
#include "utility.h"
#include <cstdlib>
#include <algorithm>
void cutestArtists (Database& db)
{
const auto search = db.SELECT<std::string, double>("artist, (mu - sigma * 3) * min(10, COUNT(*)) as power"
" FROM artistScore JOIN image_artist_bridge USING (artist)"
" GROUP BY artist ORDER BY power");
for(const auto& [artist, power] : search)
{
std::cout << artist << ' ' << power << std::endl;
}
}
void cutestCharacters (Database& db)
{
const auto search = db.SELECT<std::string, double>("character, (mu - sigma * 3) * min(10, COUNT(*)) as power"
" FROM characterScore JOIN image_character_bridge USING (character)" );
for(const auto& [character, power] : search)
{
std::cout << character << ' ' << power << std::endl;
}
}
void readLegacyFiles (Database& db)
{
auto t = db.transaction();
insertTags(db, "../booru.csv");
insertTagScores(db, "../booruScores.csv");
insertArtists(db, "../artists.csv");
insertArtistScores(db, "../artistScores.csv");
insertIDScores(db, "../idScores.csv");
insertCharacterScores(db, "../charScores.csv");
insertCharacters(db, "../chars.csv");
t.commit();;
}
void scanDir (Database& db, const std::string& location)
{
cute::HashDB hashScan;
const auto search = db.SELECT<std::string, double, double, std::string>("* FROM path_meta_data");
for(const auto& [path, size, time, hash] : search)
{
const cute::PathMetaData data (size, time, hash);
hashScan.readInto(path, data);
}
hashScan.scanDirectoryRecursive(location);
auto transaction = db.INSERT("OR IGNORE INTO path_meta_data "
"(path, file_size, write_time, hash) "
"VALUES (?, ?, ?, ?)");
for(const auto& [path, data] : hashScan)
{
transaction.push(path.string(), (double) data.file_size, (double) data.write_time, data.hash);
}
}
void twitter (Database& db)
{
const auto cutest = db.SELECT<std::string, std::string, double>
(
"path, hash, (mu - sigma * 3) as score FROM "
"path_meta_data JOIN idScore USING (hash) "
"WHERE hash NOT IN (SELECT hash FROM used) "
"ORDER BY score DESC LIMIT 500 - (SELECT count(*) FROM used)"
);
const auto random = select_randomly(cutest.begin(), cutest.end());
if(random == cutest.end()) return;
const auto [path, hash, score] = *random;
std::string qHash = '"' + hash;
qHash = qHash + '"';
const auto characters = db.SELECT<std::string>("character FROM image_character_bridge WHERE hash = "+ qHash);
const auto artists = db.SELECT<std::string>("artist FROM image_artist_bridge WHERE hash = " + qHash);
const auto cutestTags = db.SELECT<std::string, double>("tag, (mu - sigma * 3) * min(10, COUNT(*)) "
"as power FROM tagScore JOIN image_tag_bridge USING (tag) GROUP BY tag");
auto tags = db.SELECT<std::string>("tag FROM image_tag_bridge WHERE hash = " + qHash);
std::sort(tags.begin(), tags.end(),
[&](const auto a, const auto b)
{
const auto [aTag] = a;
const auto [bTag] = b;
double aPower = 0;
double bPower = 0;
for(const auto& [tag, power] : cutestTags)
{
if(tag == aTag) aPower = power;
if(tag == bTag) bPower = power;
}
return aPower > bPower;
});
std::cout << '"' << path << '"' << std::endl;
std::cout << "cutescore: " << score << std::endl;
if(artists.size())
{
std::cout << "artist: ";
for(const auto& [a] : artists) std::cout << a << ' ';
}
if(characters.size()) std::cout << std::endl;
if(characters.size())
{
std::cout << "character: ";
for(const auto& [c] : characters) std::cout << c << ' ';
}
int i = 0;
std::cout << std::endl;
std::cout << std::endl;
for(const auto& [tag] : tags)
{
if(tag == "no_sauce") continue;
if(tag == "no_gelbooru") continue;
if(tag == "no_danbooru") continue;
if(tag == "danbooru") continue;
std::cout << tag << std::endl;
if(i++ > 3) break;
}
auto u = db.INSERT("OR IGNORE INTO used (hash) VALUES (?)");
u.push(hash);
}
int main (int argc, char** argv)
{
if(argc < 2)
{
std::cerr << "usage ./frisbee -i (no args) -d [dbFile] -s [location]" << std::endl;
std::cerr << "-i - init by trying to eat legacy cutegrab files from the current dir" << std::endl;
std::cerr << "-d - database location" << std::endl;
std::cerr << "-s - scan location" << std::endl;
return 0;
}
std::string dbName;
std::string scanLocation;
bool init = false;
bool scan = false;
bool dFlag = false;
bool sFlag = false;
for(int i = 1; i < argc; i++)
{
std::string arg = argv[i];
if( arg == "-i")
{
init = true;
continue;
}
if( arg == "-d")
{
sFlag = false;
dFlag = true;
continue;
}
if( arg == "-s")
{
dFlag = false;
sFlag = true;
scan = true;
continue;
}
if(dFlag)
{
dbName = arg;
continue;
}
if(sFlag)
{
scanLocation = arg;
continue;
}
}
if(!dbName.size())
{
std::cerr << "no filename provided, using in memory db" << std::endl;
dbName = ":memory:";
}
if(!scanLocation.size() && scan)
{
std::cerr << "no scan location provided, aborting!" << std::endl;
return 1;
}
Database db(dbName);
buildDatabases(db);
if(init) readLegacyFiles(db);
auto t = db.transaction();
if(scan) scanDir(db, scanLocation);
t.commit();
if(scan) twitter(db);
}
| true |
0db020d0f4e82817b219f0ed286a5d4b13c351e0 | C++ | Floral/Study | /数据结构与算法/算法笔记/Ch4/4_3/codeup_4_3_A.cpp | UTF-8 | 953 | 3.28125 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
int N, seq[20];
int sum = 0, count = 0;
void generateP(int n)
{
for (size_t i = 1; i <= 2; i++)
{
if (sum+i < N)
{
seq[n] = i;
sum+=i;
generateP(n+1);
sum-=i;
}else if (sum+i == N)
{
seq[n] = i;
count++;
}else
{
break;
}
}
}
// int getNum(int N) //N是剩余巧克力数
// {
// if (N == 1) //如果只剩一块,只有一种方案
// return 1;
// if (N == 2) //如果还剩两块,有两种方案
// return 2;
// return getNum(N-1) + getNum(N-2); //如果大于两块,可以看今天吃1块后有多少种方案,再加上如果今天吃两块的的方案数
// }
int main()
{
while (scanf("%d", &N)!=EOF)
{
count = 0;
generateP(0);
printf("%d\n", count);
}
return 0;
} | true |
df3f23d0ee6113a716093b6096905fd7e7590242 | C++ | 282951387/KFrame | /KFCommon/KFResult.h | UTF-8 | 1,610 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __KF_RESULT_H__
#define __KF_RESULT_H__
#include "KFInclude.h"
#include "KFEnum.h"
#include "KFUtility/KFMutex.h"
namespace KFrame
{
class KFBaseResult
{
public:
KFBaseResult()
{
_result = KFEnum::Ok;
}
virtual ~KFBaseResult() = default;
inline bool IsOk() const
{
return _result == KFEnum::Ok;
}
inline void Reset()
{
_result = KFEnum::Ok;
}
inline int32 GetResult() const
{
return _result;
}
inline void SetResult( int32 result )
{
_result = result;
}
protected:
// 执行结果
int32 _result;
};
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
template< class T >
class KFResult : public KFBaseResult
{
public:
typedef std::unique_ptr< KFResult< T > > UniqueType;
public:
KFResult()
{
_value = T();
}
inline void Reset()
{
_value = T();
_result = KFEnum::Ok;
}
public:
// 数值
T _value;
};
#define __NEW_RESULT__( type ) \
KFResult< type >::UniqueType kfresult( new KFResult< type >() );
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
}
#endif | true |
e2a1e891f37cd0853ebbe1d62c73091a248c4602 | C++ | voidloop/krakenapi | /libjson/_internal/Source/JSONNode_Mutex.cpp | UTF-8 | 6,560 | 2.78125 | 3 | [
"BSD-2-Clause",
"MIT"
] | permissive | #include "JSONNode.h"
#include "JSONGlobals.h"
#ifdef JSON_MUTEX_CALLBACKS
json_mutex_callback_t json_lock_callback = 0;
json_mutex_callback_t json_unlock_callback = 0;
void * global_mutex = 0;
void * manager_mutex = 0;
struct AutoLock {
public:
LIBJSON_OBJECT(AutoLock);
AutoLock(void) json_nothrow {
LIBJSON_CTOR;
json_lock_callback(manager_mutex);
}
~AutoLock(void) json_nothrow {
LIBJSON_DTOR;
json_unlock_callback(manager_mutex);
}
private:
AutoLock(const AutoLock &);
AutoLock & operator = (const AutoLock &);
};
#ifdef JSON_MUTEX_MANAGE
json_mutex_callback_t json_destroy = 0;
//make sure that the global mutex is taken care of too
struct auto_global {
public:
LIBJSON_OBJECT(auto_global;)
auto_global(void) json_nothrow { LIBJSON_CTOR; }
~auto_global(void) json_nothrow {
LIBJSON_DTOR;
if (global_mutex){
JSON_ASSERT_SAFE(json_destroy != 0, JSON_TEXT("No json_destroy in mutex managed mode"), return;);
json_destroy(global_mutex);
}
}
private:
auto_global(const auto_global &);
auto_global & operator = (const auto_global &);
};
auto_global cleanupGlobal;
#endif
void JSONNode::register_mutex_callbacks(json_mutex_callback_t lock, json_mutex_callback_t unlock, void * manager_lock) json_nothrow {
json_lock_callback = lock;
json_unlock_callback = unlock;
manager_mutex = manager_lock;
}
void JSONNode::set_global_mutex(void * mutex) json_nothrow {
global_mutex = mutex;
}
void JSONNode::set_mutex(void * mutex) json_nothrow {
makeUniqueInternal();
internal -> _set_mutex(mutex);
}
void * JSONNode::getThisLock(JSONNode * pthis) json_nothrow {
if (pthis -> internal -> mylock != 0){
return pthis -> internal -> mylock;
}
JSON_ASSERT(global_mutex != 0, JSON_TEXT("No global_mutex")); //this is safe, because it's just goingi to return 0 anyway
return global_mutex;
}
void JSONNode::lock(int thread) json_nothrow {
JSON_ASSERT_SAFE(json_lock_callback != 0, JSON_TEXT("No locking callback"), return;);
AutoLock lockControl;
//first, figure out what needs to be locked
void * thislock = getThisLock(this);
#ifdef JSON_SAFE
if (json_unlikely(thislock == 0)) return;
#endif
//make sure that the same thread isn't locking it more than once (possible due to complex ref counting)
JSON_MAP(int, JSON_MAP(void *, unsigned int) )::iterator it = json_global(THREAD_LOCKS).find(thread);
if (it == json_global(THREAD_LOCKS).end()){
JSON_MAP(void *, unsigned int) newthread;
newthread[thislock] = 1;
json_global(THREAD_LOCKS).insert(std::pair<int, JSON_MAP(void *, unsigned int) >(thread, newthread));
} else { //this thread already has some things locked, check if the current mutex is
JSON_MAP(void *, unsigned int) & newthread = it -> second;
JSON_MAP(void *, unsigned int)::iterator locker(newthread.find(thislock));
if (locker == newthread.end()){ //current mutex is not locked, set it to locked
newthread.insert(std::pair<void *, unsigned int>(thislock, 1));
} else { //it's already locked, don't relock it
++(locker -> second);
return; //don't try to relock, it will deadlock the program
}
}
//if I need to, lock it
json_lock_callback(thislock);
}
void JSONNode::unlock(int thread) json_nothrow{
JSON_ASSERT_SAFE(json_unlock_callback != 0, JSON_TEXT("No unlocking callback"), return;);
AutoLock lockControl;
//first, figure out what needs to be locked
void * thislock = getThisLock(this);
#ifdef JSON_SAFE
if (thislock == 0) return;
#endif
//get it out of the map
JSON_MAP(int, JSON_MAP(void *, unsigned int) )::iterator it = json_global(THREAD_LOCKS).find(thread);
JSON_ASSERT_SAFE(it != json_global(THREAD_LOCKS).end(), JSON_TEXT("thread unlocking something it didn't lock"), return;);
//get the mutex out of the thread
JSON_MAP(void *, unsigned int) & newthread = it -> second;
JSON_MAP(void *, unsigned int)::iterator locker = newthread.find(thislock);
JSON_ASSERT_SAFE(locker != newthread.end(), JSON_TEXT("thread unlocking mutex it didn't lock"), return;);
//unlock it
if (--(locker -> second)) return; //other nodes is this same thread still have a lock on it
//if I need to, unlock it
newthread.erase(locker);
json_unlock_callback(thislock);
}
#ifdef JSON_MUTEX_MANAGE
void JSONNode::register_mutex_destructor(json_mutex_callback_t destroy) json_nothrow {
json_destroy = destroy;
}
#endif
void internalJSONNode::_set_mutex(void * mutex, bool unset) json_nothrow {
if (unset) _unset_mutex(); //for reference counting
mylock = mutex;
if (mutex != 0){
#ifdef JSON_MUTEX_MANAGE
JSON_MAP(void *, unsigned int)::iterator it = json_global(MUTEX_MANAGER).find(mutex);
if (it == json_global(MUTEX_MANAGER).end()){
json_global(MUTEX_MANAGER).insert(std::pair<void *, unsigned int>(mutex, 1));
} else {
++it -> second;
}
#endif
if (isContainer()){
json_foreach(CHILDREN, myrunner){
(*myrunner) -> set_mutex(mutex);
}
}
}
}
void internalJSONNode::_unset_mutex(void) json_nothrow {
#ifdef JSON_MUTEX_MANAGE
if (mylock != 0){
JSON_MAP(void *, unsigned int)::iterator it = json_global(MUTEX_MANAGER).find(mylock);
JSON_ASSERT_SAFE(it != json_global(MUTEX_MANAGER).end(), JSON_TEXT("Mutex not managed"), return;);
--it -> second;
if (it -> second == 0){
JSON_ASSERT_SAFE(json_destroy, JSON_TEXT("You didn't register a destructor for mutexes"), return;);
json_global(MUTEX_MANAGER).erase(it);
}
}
#endif
}
#ifdef JSON_DEBUG
#ifndef JSON_LIBRARY
JSONNode internalJSONNode::DumpMutex(void) const json_nothrow {
JSONNode mut(JSON_NODE);
mut.set_name(JSON_TEXT("mylock"));
#ifdef JSON_MUTEX_MANAGE
if (mylock != 0){
mut.push_back(JSON_NEW(JSONNode(JSON_TEXT("this"), (long)mylock)));
JSON_MAP(void *, unsigned int)::iterator it = json_global(MUTEX_MANAGER).find(mylock);
if (it == json_global(MUTEX_MANAGER).end()){
mut.push_back(JSON_NEW(JSONNode(JSON_TEXT("references"), JSON_TEXT("error"))));
} else {
mut.push_back(JSON_NEW(JSONNode(JSON_TEXT("references"), it -> second)));
}
} else {
mut = (long)mylock;
}
#else
mut = (long)mylock;
#endif
return mut;
}
#endif
#endif
#else
#ifdef JSON_MUTEX_MANAGE
#error You can not have JSON_MUTEX_MANAGE on without JSON_MUTEX_CALLBACKS
#endif
#endif
| true |
8d75fdbc592fd6705801c2f2f998769e2a5d68a4 | C++ | DotStarMoney/TLG | /dev/src/thread/semaphore.cc | UTF-8 | 1,266 | 2.984375 | 3 | [] | no_license | #include "thread/semaphore.h"
#include <atomic>
#include <condition_variable>
#include <limits>
#include <shared_mutex>
#include "glog/logging.h"
namespace thread {
Semaphore::Semaphore(int32_t init_resource) : r_(init_resource) {
CHECK_GE(init_resource, 0);
}
// Using an atomic resource count here allows us to avoid locking in the common
// case. Multiple threads can acquire resource simultaneously lock free. The
// only lock contention will occur when releasing resource and threads are
// waiting.
//
// If there is plenty of resource to go around however, no locking will take
// place.
void Semaphore::P() {
std::shared_lock<std::shared_mutex> s_lock(m_);
if (r_.fetch_add(-1, std::memory_order_relaxed) <= 0) cv_.wait(s_lock);
}
bool Semaphore::TryP() {
if (r_.fetch_add(-1, std::memory_order_relaxed) <= 0) {
std::unique_lock<std::shared_mutex> lock(m_);
r_.fetch_add(1, std::memory_order_relaxed);
cv_.notify_one();
return false;
}
return true;
}
void Semaphore::V() {
if (r_.fetch_add(1, std::memory_order_relaxed) < 0) {
std::unique_lock<std::shared_mutex> lock(m_);
cv_.notify_one();
}
}
void Semaphore::Drain() {
r_ = std::numeric_limits<int32_t>::max();
cv_.notify_all();
}
} // namespace thread
| true |
465b1f318bed68963951ab4b82e577466f49a138 | C++ | siddhantttt/algorithms-ds-leetcode | /Rotate List/Rotate List/main.cpp | UTF-8 | 2,105 | 3.25 | 3 | [] | no_license | //Problem: https://leetcode.com/explore/learn/card/linked-list/213/conclusion/1295/
#include <vector>
#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
/*
Code is not clean. However, it is correct.
Method to be followed:
1. Connect the tail to the head.
2. Find the point and which there should be a break, i. e where the
new head should start from.
Edge cases:
1. When rotations are zero
2. When head is only one node.
*/
if (!head || !head->next || k == 0)
return head;
ListNode* temp = head;
ListNode *fast = head;
int length = 0, rotations, breakPoint;
while (temp){
temp = temp->next;
length++;
}
rotations = k%length;
if (!rotations)
return head;
breakPoint = length - rotations;
while (--breakPoint)
fast = fast->next;
ListNode* newHead = fast->next;
fast->next = NULL;
ListNode* node = newHead;
while (node->next)
node = node->next;
node->next = head;
return newHead;
}
};
int main(){
ListNode* head = new ListNode(1);
// ListNode* node1 = new ListNode(2);
// ListNode* node2 = new ListNode(3);
// ListNode* node3 = new ListNode(4);
// ListNode* node4 = new ListNode(5);
// head->next = node1;
// node1->next = node2;
// node2->next = node3;
// node3->next = node4;
// node4->next = NULL;
Solution().rotateRight(head, 5);
return 0;
}
| true |
a374a5110b9422509639dceb8575a0b4bed03614 | C++ | kylin0925/online_judge | /acm/c100/acm107.cpp | UTF-8 | 1,029 | 2.640625 | 3 | [] | no_license | /* @JUDGE_ID: 53xxxx 107 C++ */
/* @BEGIN_OF_SOURCE_CODE */
#include <stdio.h>
#include <math.h>
int main()
{
double hinit,lastno,notwork=0,toth=0,k,i,tt;
unsigned long n,t;
while(scanf("%lf %lf",&hinit,&lastno)==2)
{
if(hinit==0 && lastno==0) break;
notwork=0;
toth=0;
if(hinit==1 && lastno==1){ printf("0 1\n");}
else if((hinit-lastno)==1){ printf("1 %.0lf\n",hinit+lastno);}
else
{
for(k=2;;k++)
{
n=pow(lastno,1/k)+0.0000001;
t=pow((n+1),k);
if(t==hinit)
{
break;
}
}
tt=n;
for(i=0;i<k;i++)
{
notwork+=pow(tt,i);
toth+=pow(tt,i)*pow(tt+1,k-i);
}
printf("%.0lf %.0lf\n",notwork,toth+pow(tt,k));
}
}
return 0;
}
/* END_OF_SOURCE_CODE */
| true |
ad9885b96864fa911e4e3753de3d416e2aadb8ba | C++ | tgtn/arduino | /06_Robot_ocolire_obstacole/06_Robot_ocolire_obstacole.ino | UTF-8 | 4,664 | 2.75 | 3 | [] | no_license | #include "Arduino.h"
// senzor 1 (dreapta)
int trigPinSenzorDreapta = 9; // pinul pe care dam senzorului comanda de masurare
int echoPinSenzorDreapta = 10; // pinul pe care primim raspunsul
// senzor 2 (stanga)
#define trigPinSenzorStanga 13 // pinul pe care dam senzorului comanda de masurare
#define echoPinSenzorStanga 2 // pinul pe care primim raspunsul
double distantaDreapta, distantaStanga;
#define minDistance 20
#define ledPin LED_BUILTIN // led de semnalizare obstacol detectat
// viteza motoarelor
#define VITEZA_MOTOR_DREAPTA 879
#define VITEZA_MOTOR_STANGA 96
//definiti pinii utilizati pentru controlul motoarelor
//pinii enA si enB sunt folositi pentru a controla viteza motoarelor in functie de semnalul PWM
//pinii in1, in2, in3 si in4 sunt utilizati pentru a controla directia motoarelor(inainte sau inapoi)
//pinii folositi de primul motor
#define pinVitezaMotorDreapta 11 // enA
#define pinInainteMotorDreapta 6 // in1
#define pinInapoiMotorDreapta 7 // in2
//pinii folositi de al doilea motor
#define pinVitezaMotorStanga 3 // enB
#define pinInainteMotorStanga 5 //in3
#define pinInapoiMotorStanga 4 //in4
//
#define inainte HIGH
#define inapoi LOW
void setup() {
Serial.begin(9600);
pinMode(trigPinSenzorDreapta, OUTPUT);
pinMode(echoPinSenzorDreapta, INPUT);
pinMode(trigPinSenzorStanga, OUTPUT);
pinMode(echoPinSenzorStanga, INPUT);
pinMode(ledPin, OUTPUT);
//toti pinii utilizati de driverul L298N sunt OUTPUT
// pinii utilizati de primul motor
pinMode(pinVitezaMotorDreapta, OUTPUT);
pinMode(pinInainteMotorDreapta, OUTPUT);
pinMode(pinInapoiMotorDreapta, OUTPUT);
//pinii utilizati de al doilea motor
pinMode(pinVitezaMotorStanga, OUTPUT);
pinMode(pinInainteMotorStanga, OUTPUT);
pinMode(pinInapoiMotorStanga, OUTPUT);
directie(inainte, inainte);
viteza(0, 0);
delay(5000);
}
void loop() {
directie(inainte, inainte);
viteza(VITEZA_MOTOR_DREAPTA, VITEZA_MOTOR_STANGA);
// citirea de la senzor 1
distantaDreapta = readSensorValueCm(trigPinSenzorDreapta, echoPinSenzorDreapta);
// print: 2389ms = 41.19cm
// in baza 10;------v sau simplu: String(duration1)
// Serial.println("Senzor dreapta: " + String(duration1, 10) + "us = " + String(cm1) + "cm");
// all the above prints: 2389ms = 41.19cm
//citirea de la Senzorul 2
distantaStanga = readSensorValueCm(trigPinSenzorStanga, echoPinSenzorStanga);
// print: 2389ms = 41.19cm
// in baza 10;------v sau simplu: String(duration1)
// Serial.println("Senzor stanga: " + String(duration2, 10) + "us = " + String(cm2) + "cm");
// all the above prints: 2389ms = 41.19cm
if ((distantaDreapta > 0 && distantaDreapta < minDistance)
|| (distantaStanga > 0 && distantaStanga < minDistance)) {
String obstacolPePartea = "dreapta";
if (distantaStanga < distantaDreapta) {
obstacolPePartea = "stanga";
}
Serial.println(
"obstacol la senzorul " + obstacolPePartea + " la "
+ String(min(distantaDreapta, distantaStanga)) + "cm");
// aprindem led-ul builtin
digitalWrite(ledPin, HIGH);
if (obstacolPePartea == "dreapta") {
rotireRobot(inainte, inapoi);
} else {
rotireRobot(inapoi, inainte);
}
} else {
digitalWrite(ledPin, LOW);
}
delay(100);
}
void directie(int directiaMotorDreapta, int directiaMotorStanga) {
digitalWrite(pinInainteMotorDreapta, directiaMotorDreapta);
digitalWrite(pinInapoiMotorDreapta, !directiaMotorDreapta);
digitalWrite(pinInainteMotorStanga, directiaMotorStanga);
digitalWrite(pinInapoiMotorStanga, !directiaMotorStanga);
}
void viteza(int vitezaMotorDreapta, int vitezaMotorStanga) {
analogWrite(pinVitezaMotorDreapta, vitezaMotorDreapta);
analogWrite(pinVitezaMotorStanga, vitezaMotorStanga);
}
void rotireRobot(int directieMotorDreapta, int directieMotorStanga) {
directie(inapoi, inapoi);
viteza(0, 0);
delay(1000);
viteza(VITEZA_MOTOR_DREAPTA, VITEZA_MOTOR_STANGA);
delay(500);
directie(directieMotorDreapta, directieMotorStanga);
viteza(VITEZA_MOTOR_DREAPTA, VITEZA_MOTOR_STANGA);
delay(300);
}
double microsecondsToCentimeters(long microseconds) {
return (double) microseconds / (double) 58;
}
double readSensorValueCm(int triggerPin, int echoPin) {
trigerMeasurementSignal(triggerPin);
// get the value returned by the sensor on port echoPin
long duration1 = pulseIn(echoPin, HIGH);
// convert value read from sensor in microseconds to centimeters
return microsecondsToCentimeters(duration1);
}
void trigerMeasurementSignal(int triggerPin) {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
}
| true |
180bbe66220f87ef9a3af0fd951758a351907cc1 | C++ | rajat-gautam/Spoj-Solutions | /bit_mask/Tricks.cpp | UTF-8 | 1,320 | 2.921875 | 3 | [] | no_license | ALL_BITS is a number with all 1's set corresponding to the elements of domain.
__builtin_ctz
__builtin_clz
__builtin_popcount
returns undefined for an argument of zero.
long largest_power(long N)
{
N = N| (N>>1);
N = N| (N>>2);
N = N| (N>>4);
N = N| (N>>8);
return (N+1)>>1;
}
Notice what x - 1 does to bit representation of x.
x - 1 would find the first set bit from the end, and then set it to 0, and set all the bits following it.
Which means if x = 10101001010100
^
|
|
|
First set bit from the end
Then x - 1 becomes 10101001010(011)
All other bits in x - 1 remain unaffected.
This means that if we do (x & (x - 1)), it would just unset the last set bit in x (which is why x&(x-1) is 0 for powers of 2).
x ^ ( x & (x-1)) : Returns the rightmost 1 in binary representation of x.
Used in finding duplicates
A^0=A
A^A=0
A^(B^C)=(A^B)^C
General Property
Check if power of 2 : (x)&(x-1)==0
Set the i'th bit : b|(1<<i)
Unset the i'th bit : b&~(1<<i)
Check if i'th bit is set or not : b&(1<<i)!=0
Set union = a|b
Set intersection = a&b
Set subtraction = a & ~b
Set negation = ALL_BITS^A
Bit mask : Generate all sub array.
| true |
02223865006e06c2659328eb59cf0834ca4e9016 | C++ | cmu-db/noisepage | /src/include/execution/compiler/operator/update_translator.h | UTF-8 | 5,232 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include "execution/ast/identifier.h"
#include "execution/compiler/operator/operator_translator.h"
#include "execution/compiler/pipeline_driver.h"
#include "storage/storage_defs.h"
namespace noisepage::catalog {
class Schema;
} // namespace noisepage::catalog
namespace noisepage::planner {
class UpdatePlanNode;
} // namespace noisepage::planner
namespace noisepage::execution::compiler {
/**
* Update Translator
*/
class UpdateTranslator : public OperatorTranslator, public PipelineDriver {
public:
/**
* Create a new translator for the given update plan. The compilation occurs within the
* provided compilation context and the operator is participating in the provided pipeline.
* @param plan The plan.
* @param compilation_context The context of compilation this translation is occurring in.
* @param pipeline The pipeline this operator is participating in.
*/
UpdateTranslator(const planner::UpdatePlanNode &plan, CompilationContext *compilation_context, Pipeline *pipeline);
/**
* Does nothing.
* @param decls The top-level declarations.
*/
void DefineHelperFunctions(util::RegionVector<ast::FunctionDecl *> *decls) override {}
/**
* Initialize the storage interface and counters.
* @param pipeline The current pipeline.
* @param function The pipeline generating function.
*/
void InitializePipelineState(const Pipeline &pipeline, FunctionBuilder *function) const override;
/**
* Implement update logic where it fills in the update PR obtained from the StorageInterface struct
* with values from the child and then updates using this the table and all concerned indexes.
* If this is an indexed update, we do a delete followed by an insert.
* @param context The context of the work.
* @param function The pipeline generating function.
*/
void PerformPipelineWork(WorkContext *context, FunctionBuilder *function) const override;
/** Tear down the storage interface. */
void TearDownPipelineState(const Pipeline &pipeline, FunctionBuilder *function) const override;
/** Record the counters for Lin's models. */
void FinishPipelineWork(const Pipeline &pipeline, FunctionBuilder *function) const override;
/**
* @return The value (vector) of the attribute at the given index (@em attr_idx) produced by the
* child at the given index (@em child_idx).
*/
ast::Expr *GetChildOutput(WorkContext *context, uint32_t child_idx, uint32_t attr_idx) const override;
/**
* @return An expression representing the value of the column with the given OID.
*/
ast::Expr *GetTableColumn(catalog::col_oid_t col_oid) const override;
/** @return Throw an error, this is serial for now. */
util::RegionVector<ast::FieldDecl *> GetWorkerParams() const override { UNREACHABLE("Update is serial."); };
/** @return Throw an error, this is serial for now. */
void LaunchWork(FunctionBuilder *function, ast::Identifier work_func_name) const override {
UNREACHABLE("Update is serial.");
};
private:
// Generates the update on the table.
void GenTableUpdate(FunctionBuilder *builder) const;
// Declares the storage interface struct used to update.
void DeclareUpdater(FunctionBuilder *builder) const;
// Frees the storage interface struct used to update.
void GenUpdaterFree(FunctionBuilder *builder) const;
// Sets the columns oids that we are updating on.
void SetOids(FunctionBuilder *builder) const;
// Declares the projected row that we will be filling in and updating with.
void DeclareUpdatePR(FunctionBuilder *builder) const;
// Gets the projected row from the storage interface that we will be updating with.
void GetUpdatePR(FunctionBuilder *builder) const;
// Sets the values in the projected row that we are using to update.
void GenSetTablePR(FunctionBuilder *builder, WorkContext *context) const;
// Inserts this projected row into the table (used for indexed updates).
void GenTableInsert(FunctionBuilder *builder) const;
// Inserts into all indexes.
void GenIndexInsert(WorkContext *context, FunctionBuilder *builder, const catalog::index_oid_t &index_oid) const;
// Deletes from the table (used for indexed updates).
void GenTableDelete(FunctionBuilder *builder) const;
// Deletes from all indexes.
void GenIndexDelete(FunctionBuilder *builder, WorkContext *context, const catalog::index_oid_t &index_oid) const;
static std::vector<catalog::col_oid_t> CollectOids(const catalog::Schema &schema);
private:
// Storage interface for updates.
StateDescriptor::Entry si_updater_;
// Projected row that we use to update.
ast::Identifier update_pr_;
// Column oids that we are updating on (array).
ast::Identifier col_oids_;
// Schema of the table we are updating.
const catalog::Schema &table_schema_;
// All the column oids of the table we ae updating.
std::vector<catalog::col_oid_t> all_oids_;
// Projection map of the table that we are updating.
// This maps column oids to offsets in a projected row.
storage::ProjectionMap table_pm_;
// The number of updates that are performed.
StateDescriptor::Entry num_updates_;
};
} // namespace noisepage::execution::compiler
| true |
6b0d3d94d88cba7834af6ef9a559116d4c86f411 | C++ | nihk/Cap-Man | /Cap-Man/ScoreGraphicsComponent.cpp | UTF-8 | 1,212 | 3.171875 | 3 | [] | no_license | #include "ScoreGraphicsComponent.h"
ScoreGraphicsComponent::ScoreGraphicsComponent(std::unordered_map<int, Sprite>&& numberSprites)
: mNumberSprites(numberSprites)
, mScore(-1) {
}
ScoreGraphicsComponent::~ScoreGraphicsComponent() {
}
// state is the current accumulated score
void ScoreGraphicsComponent::update(float delta, int state) {
if (mScore != state) {
mScore = state;
mScoreDigits.clear();
if (state == 0) {
// Handle the initial case of the score being zero. The
// while looping logic in the else block doesn't handle
// a score of zero properly.
mScoreDigits.push_back(state);
} else {
while (state) {
mScoreDigits.push_back(state % 10);
state /= 10;
}
}
}
}
void ScoreGraphicsComponent::draw(const Renderer& renderer, const Rect& dest) {
// Copy
Rect scoreRect = dest;
for (auto rit = mScoreDigits.rbegin(); rit != mScoreDigits.rend(); ++rit) {
Sprite numberSprite = mNumberSprites.at(*rit);
numberSprite.draw(renderer, scoreRect);
scoreRect.setLeft(scoreRect.x() + scoreRect.width());
}
}
| true |
7e653436965943714be4e4437c61c819d5fc5c1e | C++ | pike4/CORE-Dev-Build-1.0 | /CORE/Source/Subsystems/Logging/LogFileStream.cpp | UTF-8 | 480 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "LogFileStream.h"
LogFileStream::LogFileStream(std::string fileName)
{
path = fileName;
}
void LogFileStream::log(std::string output)
{
outputFile << output;
}
void LogFileStream::flush()
{
outputFile.flush();
}
int LogFileStream::open()
{
outputFile.open(path, std::ofstream::out);
if (outputFile.good() && outputFile.is_open())
return 1;
else
return 0;
}
void LogFileStream::close()
{
outputFile.close();
} | true |
ed4aa44b69b3dad71798af33e702d4b98a266f92 | C++ | 99002630/Genesis | /SET 4/Array/array.cc | UTF-8 | 2,207 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include "array.h"
using namespace std;
template <typename T>
MyArray<T>::MyArray():m_arr(NULL), m_len(0){}
template<typename T>
MyArray<T>::MyArray(int len):m_arr(new int(len)),m_len(len){}
template<typename T>
MyArray<T>::~MyArray(){delete []m_arr;}
template<typename T>
void MyArray<T>::append(T val)
{
static int i=0;
m_arr[i]=val;
i++;
}
template<typename T>
T MyArray<T>::at(int index)
{
return m_arr[index];
}
template<typename T>
bool MyArray<T>::search(T key) const
{
for(int i=0;i<m_len;i++)
{
if(m_arr[i]==key)
{
cout<<key<<" Found and is in "<<i<<"th position\n";
return 1;
}
}
cout<<"Not Found\n";
return 0;
}
template<typename T>
T MyArray<T>::sum() const
{
T s=0;
for(int i=0;i<m_len;i++)
{
s+=m_arr[i];
}
return s;
}
template<typename T>
T MyArray<T>::min() const
{
T min=m_arr[0];
for(int i=1;i<m_len;i++)
{
if(m_arr[i]<min)
{
min=m_arr[i];
}
}
return min;
}
template<typename T>
T MyArray<T>::max() const
{
T max=0;
for(int i=0;i<m_len;i++)
{
if(m_arr[i]>max)
{
max=m_arr[i];
}
}
return max;
}
template<typename T>
void MyArray<T>::reverse()
{
for (int low = 0, high = m_len - 1; low < high; low++, high--)
{
swap(m_arr[low],m_arr[high]);
}
for (int i = 0; i < m_len; i++)
{
cout << m_arr[i] << " ";
}
cout<<endl;
}
template<typename T>
void MyArray<T>::sort()
{
int i, j, minimum, temp;
for (i = 0; i < m_len - 1; i++) {
minimum = i;
for (j = i + 1; j < m_len; j++)
if (m_arr[j] < m_arr[minimum])
minimum = j;
temp = m_arr[i];
m_arr[i] = m_arr[minimum];
m_arr[minimum] = temp;
}
for(i=0;i<m_len;i++)
{
cout<<m_arr[i]<<" ";
}
cout<<endl;
}
| true |
e4d070ea438571a2bc2b7cfa648522511dcb33df | C++ | Matthew-Yorke/Space-Strategy-Game-Prototype | /Space Strategy Game Prototype/Sprite.h | UTF-8 | 4,954 | 2.84375 | 3 | [] | no_license | //***************************************************************************************************************************************************
//
// File Name: Sprite.h
//
// Description:
// TODO: Add file description.
//
// Change History:
// Author Date Description
// Matthew D. Yorke MM/DD/YYYY TODO: Add Description.
//
//***************************************************************************************************************************************************
#ifndef Sprite_H
#define Sprite_H
#include <iostream>
#include "Graphics.h"
class Sprite
{
//************************************************************************************************************************************************
// Start Method Declarations
//************************************************************************************************************************************************
public:
//************************************************************************************************************************************************
//
// Method Name: Sprite
//
// Description:
// TODO: Add description.
//
// Arguments:
// theGraphics - TODO: Add description.
// theFilePath - TODO: Add description.
// theSourceX - TODO: Add description.
// theSourceY - TODO: Add description.
// theWidth - TODO: Add description.
// theHeight - TODO: Add description.
//
// Return:
// N/A
//
//************************************************************************************************************************************************
Sprite(Graphics& theGraphics, const std::string theFilePath, int theSourceX, int theSourceY, int theWidth, int theHeight);
//************************************************************************************************************************************************
//
// Method Name: ~Sprit
//
// Description:
// TODO: Add description.
//
// Arguments:
// N/A
//
// Return:
// N/A
//
//************************************************************************************************************************************************
virtual ~Sprite();
//************************************************************************************************************************************************
//
// Method Name: Draw
//
// Description:
// TODO: Add description.
//
// Arguments:
// theGraphics - TODO: Add description.
// theDestinationX - TODO: Add description.
// theDestinationY - TODO: Add description.
//
// Return:
// N/A
//
//************************************************************************************************************************************************
void Draw(Graphics& theGraphics, int theDestinationX, int theDestinationY);
//************************************************************************************************************************************************
//
// Method Name: Update
//
// Description:
// TODO: Add description.
//
// Arguments:
// theElapsedTime - TODO: Add description.
//
// Return:
// N/A
//
//************************************************************************************************************************************************
virtual void Update(float theElapsedTime) {};
virtual void SetAngle(float theAngle);
inline float GetAngle() {return mAngle;};
inline ALLEGRO_BITMAP* GetBitmap() {return mpSpriteSheet;};
protected:
private:
// There are currently no private methods for this class.
//************************************************************************************************************************************************
// End Method Declarations
//************************************************************************************************************************************************
//************************************************************************************************************************************************
// Start Member Vairable Declarations
//************************************************************************************************************************************************
public:
// There are currently no public member variables for this class.
protected:
int mHeight;
int mSourceX;
int mSourceY;
int mWidth;
float mAngle;
private:
ALLEGRO_BITMAP* mpSpriteSheet;
//************************************************************************************************************************************************
// End Member Vairable Declarations
//************************************************************************************************************************************************
};
#endif | true |
306c54fca1cdd7bb4c5545884ebb70c082176817 | C++ | jjbayer/fixi | /src/interpreter.hpp | UTF-8 | 666 | 2.890625 | 3 | [] | no_license | #pragma once
#include "token.hpp"
#include "stack.hpp"
#include "lookup.hpp"
#include <memory>
#include <unordered_map>
class Token;
struct InterpreterError: public std::runtime_error
{
InterpreterError(const std::string & what): std::runtime_error(what) {}
};
struct UndefinedVariable: public InterpreterError
{
UndefinedVariable(const Token & token): InterpreterError("Undefined variable: " + token.toString()) {}
};
class Interpreter
{
public:
Interpreter();
const Stack & stack() const { return stack_; }
void push(Token token);
private:
Stack stack_;
Lookup lookup_;
std::shared_ptr<std::vector<Token> > record_;
};
| true |
07041fd41506b9b20be2b25400d6a6ef77ceb228 | C++ | mohitm15/competitve_solns | /codeforces/Math_problem.cpp | UTF-8 | 2,119 | 2.8125 | 3 | [] | no_license | // contest: Technocup 2020 - Elimination Round 3, problem: (A) Math Problem, Accepted, #
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░
// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░
// ░░░░░░█░█░░▀░░░░░░░░▀░░█░█░░░░░
// ░░░░░░█░█░░░▀░░░░░░▀░░░█░█░░░░░
// ░░░░░░█░█░░░░▀░░░░▀░░░░█░█░░░░░
// ░░░░░░█░█▄░░░░▀░░▀░░░░▄█░█░░░░░
// ░░░░░░█░█░░░░░░██░░░░░░█░█░░░░░
// ░░░░░░█░▀░░░░░░░░░░░░░░▀░█░░░░░
// ░░░░░░█░░░░░░ ░░░░░ ░░░█░░░░░
// ░░░░░░█░░░░░░ ░ ░░░ ░ ░░░█░░░░░
// ░░░░░░▀░░░░░░ ░░ ░ ░░ ░░░▀░░░░░
// ░░░░░░░░░░░░░ ░░░ ░░░ ░░░░░░░░░
#include<bits/stdc++.h>
#define f0(i,n) for(long long int i=0;i<n;i++)
#define f1(i,n) for(int i=1;i<=n;i++)
#define f2(i,n) for(int i=2;i<=n;i++)
#define rf(j,n) for(int j=n-1;j>0;j--)
#define ll long long int
#define next cout<<endl
using namespace std;
int max(int a,int b)
{
int ans = (a>=b)?a:b;
return ans;
}
int min(int a,int b)
{
int ans = (a<=b)?a:b;
return ans;
}
int main()
{
int t;
cin>>t;
while(t--)
{
ll n,ans;
int a = INT_MIN,b= INT_MAX;
cin>>n;
vector<pair<int,int>>arr(n);
f0(i,n)
{
cin>>arr[i].first>>arr[i].second;
a = max(a,arr[i].first);
b = min(b,arr[i].second);
ans = max(0,(a-b));
}
cout<<ans<<endl;
}
return 0;
}
| true |
7f9a6170cf5bc76e5ce5266ced8939a5c0fef5b5 | C++ | kaitorque/ProSolve | /Prosolve-5 2018/Solutions & Test Cases/E. Good Neighbour/solution.cpp | UTF-8 | 1,345 | 3.140625 | 3 | [] | no_license | #include <bits/stdc++.h> // gcc or clang only
using namespace std;
// by default if variable is declared in global scope
// its value will be automatically initialized to zero
bool visited[10];
int dist_mat[10][10];
int H, N;
int tsp(int src, int current_cost, int num_visited)
{
// recursion stopping condition = if all houses have been visited
if (num_visited == N) {
if (dist_mat[src][H] == 0) // if there is no path between last house & initial house
return INT_MAX;
return current_cost + dist_mat[src][H]; // current cost + cost travelling back home
}
int cost=INT_MAX;
for (int i=0; i<N; i++) {
/**
* 1) if there is a path between src->i
* 2) no singleton traversal (src != i)
* 3) if `i` not visited before
*/
if (dist_mat[src][i] != 0 && src != i && visited[i] == false) {
visited[i]=true;
cost = min(cost, tsp(i, current_cost + dist_mat[src][i], num_visited + 1));
visited[i]=false;
}
}
return cost;
}
int main()
{
int P;
cin >> N >> H >> P;
for (int i=0; i<P; i++) {
int S, D, C;
cin >> S >> D >> C;
dist_mat[S][D] = dist_mat[D][S] = C; // undirected edge
}
visited[H]=true;
cout << tsp(H, 0, 1) << endl;
return 0;
} | true |
6b2fd4775d81a6b9121b8a7d4989e2491b3aeb99 | C++ | Dheeraj-cyber/OpenGL-Samples | /Material.h | UTF-8 | 471 | 2.84375 | 3 | [] | no_license | #pragma once
#include<GL/glew.h>
class Material
{
public:
Material();
Material(GLfloat sIntensity, GLfloat shine);
void UseMaterial(GLuint specularIntensityLocation, GLuint shininessLocation); //Specifies the lighting for our texture
~Material();
private:
GLfloat specularIntensity; //Specifies how much light should be there on the object
GLfloat shininess; //Shininess specifies how smooth the object will look. High value - light is very bright
};
| true |
91d47f52a93f285a8d0d82340738baeca6e5bcbf | C++ | Gr1dlock/OOP | /LR_4/LR_4/commands/add_model_command.h | UTF-8 | 426 | 2.609375 | 3 | [] | no_license | #ifndef ADD_MODEL_COMMAND_H
#define ADD_MODEL_COMMAND_H
#include <string>
#include "basecommand.h"
namespace commands
{
class AddModelCommand: public BaseCommand
{
public:
explicit AddModelCommand(std::string file_name, std::string model_name);
void execute(std::shared_ptr<mediator::Mediator> mediator) override;
private:
std::string _file_name;
std::string _model_name;
};
}
#endif // ADD_MODEL_COMMAND_H
| true |
f420bea5e05e10a7306101b586f4348c69573098 | C++ | tangsancai/algorithm | /PAT-A/1048. Find Coins.cpp | UTF-8 | 508 | 2.59375 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
using namespace std;
int coin[100005];
int main()
{
int N;
int payment;
scanf("%d%d",&N,&payment);
for(int i=0;i<N;i++)
{
scanf("%d",&coin[i]);
}
sort(coin,coin+N);
int i=0;
int j=N-1;
while((coin[i]+coin[j])!=payment&&i<j)
{
if((coin[i]+coin[j])<payment)
{
i++;
}
else
{
j--;
}
}
if(i==j)
{
printf("No Solution");
}
else if((coin[i]+coin[j])==payment)
{
printf("%d %d",coin[i],coin[j]);
}
}
| true |
9f0329ef9ed872f67965f3fecc73bc4a3316717c | C++ | wkurek/Caesar-cipher | /StreamReader.h | UTF-8 | 463 | 2.828125 | 3 | [] | no_license | #ifndef STREAMREADER
#define STREAMREADER
#include <iostream>
#include "Cipher.h"
class StreamReader
{
std::string path;
public:
/// @brief konstruktor
/// @param path ścieżka do pliku z treścią szyfru
StreamReader(std::string path);
/// @brief operator strumienia wejścia
/// @param cipher szyfr
/// @returns strumień czytający szyfr z pliku
StreamReader& operator>>(Cipher& cipher);
};
#endif
| true |
2ca279417ce52f55b430f8e8964e5cf89d268ff6 | C++ | RichW2/GD1P03-2DGPRW | /GD1P03-PaintTool/GD1P03-PaintTool/ToolsCanvas.cpp | UTF-8 | 1,522 | 2.765625 | 3 | [] | no_license | #include "ToolsCanvas.h"
ToolsCanvas::ToolsCanvas(sf::RenderWindow* _window)
{
m_toolsWindow = _window;
}
void ToolsCanvas::AddButton(Button* newButton)
{
allButtons.push_back(newButton);
}
Button* ToolsCanvas::IsMouseOverButton(sf::Vector2i mp)
{
for (int i = 0; i < allButtons.size(); i++) {
Button* currButton = allButtons[i];
if (mp.x > currButton->buttonPos.x && mp.x < currButton->buttonPos.x + currButton->buttonSize.x) {
if (mp.y > currButton->buttonPos.y && mp.y < currButton->buttonPos.y + currButton->buttonSize.y) {
return currButton;
}
}
}
return nullptr;
}
void ToolsCanvas::HighlightButton(Button* theButton)
{
if (theButton->buttonUse == BUTTONUSE_BRUSHBOX || theButton->buttonUse == BUTTONUSE_BRUSHDRAW || theButton->buttonUse == BUTTONUSE_BRUSHELLIPSE || theButton->buttonUse == BUTTONUSE_BRUSHLINE || theButton->buttonUse == BUTTONUSE_BRUSHPOLYGON || theButton->buttonUse == BUTTONUSE_STAR || theButton->buttonUse == BUTTONUSE_HEART)
{ //unhilights all other drawmode buttons
for (int i = 0; i < allButtons.size(); i++) {
if (allButtons[i]->buttonUse != BUTTONUSE_RAINBOWMODE)
allButtons[i]->DimButton(0);
}
theButton->DimButton(100);
}
}
Button* ToolsCanvas::GetLastButton()
{
return allButtons.back();
}
void ToolsCanvas::Draw()
{
m_toolsWindow->clear(sf::Color(200, 200, 200,255)); //set the tool canvas background to a nice grey colour
for (int i = 0; i < allButtons.size(); i++) {
allButtons[i]->DisplayButton(m_toolsWindow); //show all buttons
}
} | true |
8fedfed2f8e01563375209b7e492129acc57b606 | C++ | simtb/coding-puzzles | /leetcode-december-challenge/valid_mountain_array.cpp | UTF-8 | 818 | 3.21875 | 3 | [] | no_license | class Solution {
public:
bool validMountainArray(vector<int>& arr) {
int n = arr.size();
if (n < 3 || arr[0] > arr[1]){
return false;
}
bool isMountain = true;
bool increasing = true;
for (int i = 1; i < n; i++){
int current = arr[i];
int prev = arr[i - 1];
if (current == prev){
isMountain = false;
break;
}
else if (current < prev && increasing){
increasing = false;
}
else if (current > prev && !increasing){
isMountain = false;
break;
}
}
return isMountain && !increasing;
}
};
| true |
0e96b6fa84237798cbc6ec7158d17b88a2b977aa | C++ | gtm2654197/School-Projects | /Gravity_Sim/simulation.cpp | UTF-8 | 15,852 | 3.203125 | 3 | [] | no_license | #include "simulation.h"
#include "constants.h"
#include <cstdlib>
#include "math.h"
#include <iostream>
#include <SFML/Window/Mouse.hpp>
using namespace std;
Simulation::Simulation()
{
window.create(sf::VideoMode(SCREEN_WIDTH,SCREEN_HEIGHT), "Gravity Simulator");
window.setFramerateLimit(60);
// zoomX = SCREEN_WIDTH;
// zoomY = SCREEN_HEIGHT;
// view.setSize(sf::Vector2f(zoomX, zoomY));
// view.setCenter((SCREEN_WIDTH/2),(SCREEN_HEIGHT/2));
}
void Simulation::Draw()
{
//cycles through each particle and draws them
int i;
for(i = 0; i < particles.size(); i++)
{
window.draw(particles[i].circle);
}
}
void Simulation::processEvents()
{
sf::Event event;
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
{
window.close();
break;
}
case sf::Event::MouseButtonPressed:
{
//Right mouse button pressed
if(event.mouseButton.button == sf::Mouse::Right)
{
int collision = mouseCollision(event.mouseButton.x, event.mouseButton.y);
//if the mouse is not over an existing particle
if(collision == -1)
{
//save initial mouse position
double initialX, initialY, finalX, finalY;
initialX = sf::Mouse::getPosition(window).x;
initialY = sf::Mouse::getPosition(window).y;
//draw line while choosing direction of new particle and save final mouse position
while(sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
cout << "Start while loop" << endl;
sf::RectangleShape line;
line.setPosition(initialX, initialY);
finalX = sf::Mouse::getPosition(window).x;
finalY = sf::Mouse::getPosition(window).y;
double distance = sqrt((pow(finalX-initialX,2)) + (pow(finalY-initialY,2)));
line.setSize(sf::Vector2f(distance,2));
line.setFillColor(sf::Color::Cyan);
double angle = atan((finalY-initialY)/(finalX-initialX));
double pi = 4 * atan(1);
angle = angle*(180/pi);
if(finalX < initialX)
{
angle += 180;
}
line.setRotation(angle);
window.clear();
update();
Draw();
window.draw(line);
window.display();
}
cout << "End while loop" << endl;
//Calculate velocity of new particle
double deltaX, deltaY;
deltaX = (finalX-initialX)/50;
deltaY = (finalY-initialY)/50;
int random = rand() % 6;
//create new particle with above parameters
Particle newParticle;
newParticle.setSize(5);
newParticle.setColor(random);
newParticle.setPosition(initialX,initialY);
newParticle.setVelocity(deltaX,deltaY);
particles.push_back(newParticle);
}
}
break;
}
\
case sf::Event::MouseButtonReleased:
{
if(event.mouseButton.button == sf::Mouse::Left)
{
int collision = mouseCollision(event.mouseButton.x, event.mouseButton.y);
//Mouse over existing particle
if(collision > -1)
{
//get x and y locations, and radius of particle and mouse
double particleX, particleY, radius;
particleX = particles[collision].circle.getPosition().x;
particleY = particles[collision].circle.getPosition().y;
radius = particles[collision].circle.getRadius();
//get mouse position
int mouseX = sf::Mouse::getPosition(window).x;
int mouseY = sf::Mouse::getPosition(window).y;
//calculate new velocity based on where the particle is clicked
double deltaX, deltaY;
deltaX = (mouseX - particleX)/radius;
deltaY = (mouseY - particleY)/radius;
//set new velocity
particles[collision].velocityX = deltaX;
particles[collision].velocityY = deltaY;
}
//Mouse over empty space;
else
{
//create new particle at mouse position
Particle newParticle;
newParticle.setSize(5);
int random = rand() % 6;
newParticle.setColor(random);
int mouseX = sf::Mouse::getPosition(window).x;
int mouseY = sf::Mouse::getPosition(window).y;
newParticle.setPosition(mouseX, mouseY);
particles.push_back(newParticle);
}
}
break;
}
case sf::Event::MouseWheelScrolled:
{
//save mouse position
int mouseX = sf::Mouse::getPosition(window).x;
int mouseY = sf::Mouse::getPosition(window).y;
int collision = mouseCollision(mouseX, mouseY);
//if mouse is over existing particle
if(collision > -1)
{
cout << "Collision detected" << endl;
//if scroll wheel up, increase size
if(event.mouseWheelScroll.delta > 0)
{
cout << "Mousewheel up" << endl;
int radius = particles[collision].circle.getRadius();
particles[collision].setSize(radius + 1);
}
//if scroll wheel down, decrease size
else
{
cout << "Mousewheel down" << endl;
int radius = particles[collision].circle.getRadius();
if(radius > 0)
{
particles[collision].setSize(radius - 1);
}
}
}
break;
}
case sf::Event::KeyPressed:
{
cout << "Key Pressed" << endl;
//if key R is pressed
if(event.key.code == sf::Keyboard::R)
{
cout << "R Pressed" << endl;
//create 10 randomly positioned particles within window space
for(int i = 0; i < 10; i++)
{
int posX, posY, color, sign;
posX = rand() % SCREEN_WIDTH;
posY = rand() % SCREEN_WIDTH;
color = rand() % 7;
Particle temp;
temp.setPosition(posX,posY);
temp.setColor(color);
temp.setSize(5);
particles.push_back(temp);
}
}
// if(event.key.code == sf::Keyboard::Dash)
// {
// zoomX += 100;
// zoomY += 100;
// view.setSize(sf::Vector2f(zoomX, zoomY));
// }
// if(event.key.code == sf::Keyboard::Equal)
// {
// zoomX -= 100;
// zoomY -= 100;
// view.setSize(sf::Vector2f(zoomX, zoomY));
// }
break;
}
default:
{
break;
}
}
}
}
void Simulation::update()
{
int i,j;
for(i = 0; i < particles.size(); i++)
{
//get i particle position here so it doesn't loop through in next for loop, just does it once for each particle
double positionXi, positionYi;
positionXi = particles[i].circle.getPosition().x;
positionYi = particles[i].circle.getPosition().y;
//get mass for i particle
double massi = particles[i].getMass();
//initialize change in velocity variables, so we can pass it once after all changes are made
double deltaVx = 0; double deltaVy = 0;
for(j = 0; j < particles.size(); j++)
{
//skip instances when i == j
if(i != j)
{
int collision = particleCollision(i,j);
//if particle i does not collide with particle j
if(collision == -1)
{
//get j particle position and mass
double positionXj, positionYj, massj;
massj = particles[j].getMass();
positionXj = particles[j].circle.getPosition().x;
positionYj = particles[j].circle.getPosition().y;
//calculate distance between particle i and particle j
double distance = sqrt((pow(positionXi - positionXj, 2)) + (pow(positionYi - positionYj, 2)));
//calculate change in velocity and add to deltaVx and deltaVy for each particle j
deltaVx += ((massj/massi)/pow(distance,2)) * ((positionXj - positionXi)/distance);
deltaVy += ((massj/massi)/pow(distance,2)) * ((positionYj - positionYi)/distance);
}
//collision occurs between particles i and j
else
{
double radiusI, radiusJ;
//get radius of each particle
radiusI = particles[i].circle.getRadius();
radiusJ = particles[j].circle.getRadius();
//determine which particle is bigger and absorb the small into the big
if(radiusI >= radiusJ)
{
particleAbsorb(i,j);
if(j<i)
{
i--;
}
}
else
{
particleAbsorb(j,i);
i--;
}
}
}
}
//Change i particle value with deltaVx and deltaVy, calculated above
particles[i].changeVelocity(deltaVx, deltaVy);
double newVx, newVy;
newVx = particles[i].velocityX;
newVy = particles[i].velocityY;
particles[i].circle.move(newVx, newVy);
}
}
void Simulation::render()
{
window.clear();
// window.setView(view);
Draw();
window.display();
}
void Simulation::run()
{
while(window.isOpen())
{
processEvents();
update();
render();
}
}
//Checks if mouse is hovering over existing particle,
//returns -1 if over empty space
//returns index of particle in particle vector, otherwise
int Simulation::mouseCollision(float mouseX, float mouseY)
{
int collision = -1;
int i;
for(i = 0; i < particles.size() && collision == -1; i++)
{
double distance;
double deltaX, deltaY;
deltaX = mouseX - particles[i].circle.getPosition().x;
cout << "MouseX: " << mouseX << endl;
deltaY = mouseY - particles[i].circle.getPosition().y;
cout << "DeltaX: " << deltaX << ", Delta Y: " << deltaY << endl;
distance = sqrt((pow(deltaX, 2)) + (pow(deltaY, 2)));
cout << "Distance: " << distance;
double radius = particles[i].circle.getRadius();
cout << "Radius: " << radius;
if(distance <= radius)
{
collision = i;
}
}
cout << collision << endl;
return collision;
}
//Checks for particle collision between two particles
//returns -1 if no collision
//returns 1 if collision
int Simulation::particleCollision(int particle1, int particle2)
{
int collision = -1;
double distance, particle1X, particle1Y, particle2X, particle2Y, deltaX, deltaY;
//get x and y positions of each particle and calcultate difference
particle1X = particles[particle1].circle.getPosition().x;
particle1Y = particles[particle1].circle.getPosition().y;
particle2X = particles[particle2].circle.getPosition().x;
particle2Y = particles[particle2].circle.getPosition().y;
deltaX = particle2X - particle1X;
deltaY = particle2Y - particle1Y;
//calculate distance between two particles
distance = sqrt((pow(deltaX,2)) + (pow(deltaY,2)));
//get sum of the radii of both particles
double radius1, radius2, sumRadii;
radius1 = particles[particle1].circle.getRadius();
radius2 = particles[particle2].circle.getRadius();
sumRadii = radius1 + radius2;
//compare the sum with the distance do see if collision occurs
if(distance <= sumRadii)
{
collision = 1;
}
return collision;
}
//When particle collision occurs, particle absorb is called to
//absorb the smaller particles size into the bigger particle
//and then deletes smaller particle
void Simulation::particleAbsorb(int bigParticle, int smallParticle)
{
//Calculate the resulting radius of the absorbtion
double radiusBig, radiusSmall, radiusNew, areaBig, areaSmall, areaNew;
radiusBig = particles[bigParticle].circle.getRadius();
radiusSmall = particles[smallParticle].circle.getRadius();
areaBig = pow(radiusBig,2) * (4*atan(1));
areaSmall = pow(radiusSmall,2) * (4*atan(1));
areaNew = areaBig + areaSmall;
radiusNew = sqrt(areaNew/(4*atan(1)));
//If not first particle in index
if(smallParticle > 0)
{
//Delete the small particle
particles.erase(particles.begin()+smallParticle);
//give Big particle new radius
if(smallParticle<bigParticle)
{
particles[bigParticle-1].setSize(radiusNew);
}
else
{
particles[bigParticle].setSize(radiusNew);
}
}
//small particle is at position 0 in index
else
{
sf::Color bigColor;
double vxBig, vyBig, posxBig, posyBig;
vxBig = particles[bigParticle].getVelocityX();
vyBig = particles[bigParticle].getVelocityY();
posxBig = particles[bigParticle].circle.getPosition().x;
posyBig = particles[bigParticle].circle.getPosition().y;
particles[smallParticle].circle.setFillColor(particles[bigParticle].circle.getFillColor());
particles.erase(particles.begin() +bigParticle);
if(smallParticle > bigParticle)
{
particles[smallParticle-1].setSize(radiusNew);
particles[smallParticle-1].setPosition(posxBig, posyBig);
particles[smallParticle-1].setVelocity(vxBig, vyBig);
}
else
{
particles[smallParticle].setSize(radiusNew);
particles[smallParticle].setPosition(posxBig, posyBig);
particles[smallParticle].setVelocity(vxBig, vyBig);
}
}
}
| true |
77537813483e0a34b3c5514a98b3bdddc1d7c86c | C++ | kbaedal/vzray | /src/shapes/parallelogram.h | UTF-8 | 1,007 | 2.546875 | 3 | [] | no_license | #ifndef __PARALLELOGRAM_H__
#define __PARALLELOGRAM_H__ 1
#include "shape.h"
#include "vec3.h"
#include "point.h"
#include "ray.h"
#include "rgb.h"
class Parallelogram : public Shape
{
public:
Parallelogram(Point a_base, Vec3 a_u, Vec3 a_v, Material *a_material)
{
base = a_base;
u = a_u;
v = a_v;
material = a_material;
normal = versor(cross(u, v));
u_normal = versor(u);
v_normal = versor(v);
trans = new Transform;
}
~Parallelogram() { if(trans != NULL) delete trans; }
bool hit(const Ray &r, double min_dist, double max_dist, HitRecord &hit) const;
bool shadow_hit(const Ray &r, double min_dist, double max_dist) const;
bool get_random_point(const Point &view_pos, CRandomMersenne *rng, Point &light_pos) const;
//private:
Point base;
Vec3 u,
v,
normal,
u_normal,
v_normal;
private:
static const double kparall_epsilon;
};
#endif // __PARALLELOGRAM_H__
| true |
51c417072cb0d5cb92ca1de5d771ec9c5a45c20d | C++ | jsaisagar/cppWork | /binarySearch.cpp | UTF-8 | 832 | 3.640625 | 4 | [] | no_license |
@Author: Sai Sagar Jinka
#include <iostream>
using namespace std;
int binarySearch(int arr[], int first, int last, int x){
if(last > 1)
{
int mid = first + (last - 1)/2;
if(arr[mid] == x)
return mid;
if(arr[mid] > x)
return binarySearch(arr, first, mid - 1, x);
return binarySearch(arr, mid + 1, last, x);
return -1;
}
}
int main(){
int array[] = {1,3,4,5,7,8,9,90};
int n = sizeof(array)/sizeof(array[0]);
int index = binarySearch(array,0,n-1,5);
// cout << "The size of array is " << sizeof(array);
// cout << "The size of one element is " << sizeof(array[0]);
cout<<"The index of searched element is " << index << endl;
return 0;
}
| true |
4b4d48df9e7755c7458ce22217eff715b44f6cb6 | C++ | kmaragon/cxxmetrics | /cxxmetrics/skiplist.hpp | UTF-8 | 31,619 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef CXXMETRICS_PQSKIPLIST_HPP
#define CXXMETRICS_PQSKIPLIST_HPP
#include <atomic>
#include <array>
#include <random>
#include "internal/hazard_ptr.hpp"
namespace cxxmetrics
{
namespace internal
{
template<int TSize, int TBase = 2>
struct const_log
{
private:
static constexpr int l = (TSize % TBase) ? TSize + (TBase - (TSize % TBase)) : TSize;
public:
static_assert(TBase > 1, "const log is only useful for > 1");
static constexpr int value = (const_log<l / TBase, TBase>::value + 1);
};
template<int TBase>
struct const_log<1, TBase>
{
static constexpr int value = 0;
};
template<typename T, int TSize>
class skiplist_node
{
public:
static constexpr int width = const_log<TSize>::value;
using ptr = std::atomic<skiplist_node *>;
private:
static constexpr unsigned long DELETE_MARKER = ((unsigned long) 1) << ((sizeof(void *) * 8) - 1);
static constexpr uint16_t LEVEL_DELETE_MARKER = (uint16_t)1 << ((sizeof(uint16_t) * 8) - 1);
std::array<ptr, width> next_;
T value_;
std::atomic_uint_fast64_t refs_;
std::atomic_uint_least16_t level_;
std::atomic_uint_least8_t inlist_;
public:
constexpr static skiplist_node *marked_ptr(skiplist_node *ptr) noexcept
{
return reinterpret_cast<skiplist_node *>(reinterpret_cast<unsigned long>(ptr) | DELETE_MARKER);
}
constexpr static skiplist_node *unmarked_ptr(skiplist_node *ptr) noexcept
{
return reinterpret_cast<skiplist_node *>(reinterpret_cast<unsigned long>(ptr) & ~DELETE_MARKER);
}
constexpr static bool ptr_is_marked(skiplist_node *ptr) noexcept
{
return (reinterpret_cast<unsigned long>(ptr) & DELETE_MARKER) != 0;
}
int level() const noexcept
{
return level_.load() & ~LEVEL_DELETE_MARKER;
}
bool reference() noexcept
{
auto refs = refs_.load();
while (true)
{
if (refs == 0)
return false;
if (refs_.compare_exchange_strong(refs, refs + 1))
return true;
}
}
template<typename TAlloc>
void dereference(TAlloc &t) noexcept
{
auto refs = refs_.load();
while (true)
{
if (refs == 0)
return;
if (refs_.compare_exchange_strong(refs, refs - 1))
{
// we successfully dropped the references
if (refs == 1)
t.deallocate(this);
return;
}
}
}
bool is_marked() const noexcept
{
return ((uint16_t)level_.load() & LEVEL_DELETE_MARKER) != 0;
}
bool mark_for_deletion() noexcept
{
auto nlevel = level_.load();
while (true)
{
if (nlevel & LEVEL_DELETE_MARKER)
return false;
if (level_.compare_exchange_strong(nlevel, nlevel | LEVEL_DELETE_MARKER))
return true;
}
}
const T &value() const noexcept
{
return value_;
}
void init(const T &value, int level) noexcept
{
refs_ = 1;
level_ = level;
value_ = value;
for (int i = 0; i < width; i++)
next_[i] = nullptr;
}
std::pair<skiplist_node *, bool> next(int level) const noexcept
{
auto res = next_[level].load();
auto ptr = reinterpret_cast<skiplist_node *>(reinterpret_cast<unsigned long>(res) & ~DELETE_MARKER);
return std::make_pair(ptr, !ptr_is_marked(res));
}
// sets the next node as long as the node isn't being deleted
bool set_next(int level, skiplist_node *node) noexcept
{
next_[level] = node;
return (node == nullptr) || !node->is_marked();
}
// inserts the given node as the next node after this
bool insert_next(int level, skiplist_node *next, skiplist_node *node) noexcept
{
if (node != nullptr)
{
node->next_[level] = next;
}
return next_[level].compare_exchange_strong(next, node);
}
// replace the next node with newnext if expected is the next at this level
// requires that the next node has already been marked for deletion
bool remove_next(int level, skiplist_node *&expected, skiplist_node *newnext) noexcept
{
bool res = next_[level].compare_exchange_strong(expected, newnext);
expected = unmarked_ptr(expected);
return res;
}
bool mark_next_deleted(int level, skiplist_node *&if_matches) noexcept
{
if (ptr_is_marked(if_matches))
{
if_matches = unmarked_ptr(next_[level].load());
return false;
}
bool result = next_[level].compare_exchange_strong(if_matches, marked_ptr(if_matches));
if_matches = unmarked_ptr(if_matches);
return result;
}
void unmark_next(int level, skiplist_node *expected_next) noexcept
{
skiplist_node *marked = marked_ptr(expected_next);
if (!next_[level].compare_exchange_strong(marked, expected_next))
{
assert(!"Someone swapped the marked next before unmark_next");
}
}
};
template<typename T, int TSize, typename TAlloc>
class skiplist_node_pin;
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc> pin_node(skiplist_node<T, TSize> *node, TAlloc &allocator) noexcept;
template<typename T, int TSize, typename TAlloc>
class skiplist_node_pin
{
skiplist_node<T, TSize> *ptr_;
TAlloc *alloc_;
skiplist_node_pin(skiplist_node<T, TSize> *node, TAlloc &allocator) noexcept;
friend skiplist_node_pin<T, TSize, TAlloc> pin_node<T, TSize, TAlloc>(skiplist_node<T, TSize> *node, TAlloc &allocator) noexcept;
public:
skiplist_node_pin() noexcept;
skiplist_node_pin(const skiplist_node_pin &) noexcept;
skiplist_node_pin(skiplist_node_pin &&mv) noexcept;
~skiplist_node_pin() noexcept;
skiplist_node_pin &operator=(const skiplist_node_pin &cp) noexcept;
skiplist_node_pin &operator=(skiplist_node_pin &&mv) noexcept;
skiplist_node<T, TSize> *operator->() const noexcept;
operator bool() const noexcept;
bool operator==(const skiplist_node_pin &other) const noexcept;
bool operator!=(const skiplist_node_pin &other) const noexcept;
TAlloc &allocator() noexcept
{
return *alloc_;
}
skiplist_node<T, TSize> *get() const noexcept
{
return ptr_;
};
};
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc> pin_node(skiplist_node<T, TSize> *node, TAlloc &allocator) noexcept
{
if (node && !node->reference())
return skiplist_node_pin<T, TSize, TAlloc>();
return std::move(skiplist_node_pin<T, TSize, TAlloc>(node, allocator));
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::skiplist_node_pin(skiplist_node<T, TSize> *node, TAlloc &allocator) noexcept :
ptr_(node),
alloc_(&allocator)
{ }
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::skiplist_node_pin() noexcept :
ptr_(nullptr),
alloc_(nullptr)
{ }
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::skiplist_node_pin(const skiplist_node_pin &other) noexcept
{
ptr_ = other.ptr_;
if (ptr_ && !ptr_->reference())
ptr_ = nullptr;
alloc_ = other.alloc_;
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::skiplist_node_pin(skiplist_node_pin &&mv) noexcept :
ptr_(mv.ptr_),
alloc_(mv.alloc_)
{
mv.ptr_ = nullptr;
mv.alloc_ = nullptr;
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::~skiplist_node_pin() noexcept
{
if (ptr_ && alloc_)
ptr_->dereference(*alloc_);
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc> &skiplist_node_pin<T, TSize, TAlloc>::operator=(const skiplist_node_pin &cp) noexcept
{
auto cpptr = cp.ptr_;
if (ptr_ == cpptr)
return *this;
if (cpptr)
cpptr->reference();
if (ptr_ && alloc_)
ptr_->dereference(*alloc_);
ptr_ = cpptr;
alloc_ = cp.alloc_;
return *this;
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc> &skiplist_node_pin<T, TSize, TAlloc>::operator=(skiplist_node_pin &&mv) noexcept
{
auto mvptr = mv.ptr_;
if (ptr_ == mvptr)
return *this;
mv.ptr_ = nullptr;
if (ptr_ && alloc_)
ptr_->dereference(*alloc_);
ptr_ = mvptr;
alloc_ = mv.alloc_;
mv.alloc_ = nullptr;
return *this;
}
template<typename T, int TSize, typename TAlloc>
skiplist_node<T, TSize> *skiplist_node_pin<T, TSize, TAlloc>::operator->() const noexcept
{
return ptr_;
}
template<typename T, int TSize, typename TAlloc>
skiplist_node_pin<T, TSize, TAlloc>::operator bool() const noexcept
{
return (ptr_ != nullptr);
}
template<typename T, int TSize, typename TAlloc>
bool skiplist_node_pin<T, TSize, TAlloc>::operator==(const skiplist_node_pin &other) const noexcept
{
return (ptr_ == other.ptr_);
}
template<typename T, int TSize, typename TAlloc>
bool skiplist_node_pin<T, TSize, TAlloc>::operator!=(const skiplist_node_pin &other) const noexcept
{
return (ptr_ != other.ptr_);
}
}
template<typename T, int TSize, typename TLess = std::less<T>>
class skiplist
{
public:
static constexpr int width = internal::skiplist_node<T, TSize>::width;
private:
using pin = internal::skiplist_node_pin<T, TSize, skiplist>;
using node = internal::skiplist_node<T, TSize>;
using node_ptr = typename internal::skiplist_node<T, TSize>::ptr;
TLess cmp_;
node_ptr head_;
node_ptr freelist_head_;
static std::default_random_engine random_;
std::pair<pin, pin> find_location(const pin &start, int level, const T &value) const noexcept;
pin find_location(int level, const T &value) const noexcept;
std::pair<pin, pin> find_location(pin &before, int level, const T &value) noexcept;
void find_location(int level, const T &value, std::array<std::pair<pin, pin>, width> &into) noexcept;
void takeover_head(pin &newhead, pin &oldhead) noexcept;
void finish_insert(int level, pin &insertnode, std::array<std::pair<pin, pin>, width> &locations) noexcept;
void remove_node_from_level(int level, const pin &prev_hint, const pin &remnode) noexcept;
node *make_node(const T &value, int level);
void deallocate(node *nd);
auto pin_next_valid(int level, const pin &node) const
{
pin next = node;
while (true)
{
// this only gets called in non-const contexts or iterators which are run from
// a const context but can only be created from a non-const skiplist, which means
// this will still be safe
next = std::move(const_cast<skiplist *>(this)->pin_next(level, next).first);
if (!next)
return next;
if (!next->is_marked())
return std::move(next);
}
}
auto pin_next(int level, const pin &node)
{
while (true)
{
if (!node)
return std::move(std::make_pair(pin(), false));
auto nxt = node->next(level);
if (!nxt.first)
return std::move(std::make_pair(pin(), nxt.second));
auto pinned = std::move(internal::pin_node(nxt.first, *this));
if (pinned)
return std::move(std::make_pair(std::move(pinned), nxt.second));
if (node->is_marked())
return std::move(std::make_pair(pin(), nxt.second));
}
}
friend class internal::skiplist_node<T, TSize>;
public:
class iterator : public std::iterator<std::input_iterator_tag, T>
{
friend class skiplist;
internal::skiplist_node_pin<T, TSize, skiplist> node_;
skiplist *list_;
explicit iterator(internal::skiplist_node_pin<T, TSize, skiplist> &&node, skiplist *list) noexcept;
public:
iterator() noexcept;
iterator(const iterator &other) noexcept;
~iterator() noexcept;
iterator &operator++() noexcept;
bool operator==(const iterator &other) const noexcept;
bool operator!=(const iterator &other) const noexcept;
const T &operator*() const noexcept;
const T *operator->() const noexcept;
iterator &operator=(const iterator &other) noexcept;
};
skiplist() noexcept;
~skiplist();
bool erase(const T &value) noexcept
{
return erase(find(value));
}
bool erase(const iterator &value) noexcept;
bool insert(const T &value) noexcept;
iterator begin() noexcept;
iterator end() const noexcept;
iterator find(const T &value) noexcept;
};
// used as a macro to retry in atomic loops
#define yield_and_continue() std::this_thread::yield(); continue
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::iterator::iterator(internal::skiplist_node_pin<T, TSize, skiplist> &&node, skiplist *list) noexcept :
node_(std::move(node)),
list_(list)
{ }
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::iterator::iterator() noexcept
{ }
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::iterator::iterator(const iterator &other) noexcept :
node_(other.node_)
{
};
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::iterator::~iterator() noexcept
{
}
template<typename T, int TSize, typename TLess>
typename skiplist<T, TSize, TLess>::iterator &skiplist<T, TSize, TLess>::iterator::operator++() noexcept
{
if (!node_)
return *this;
node_ = list_->pin_next_valid(0, node_);
return *this;
}
template<typename T, int TSize, typename TLess>
bool skiplist<T, TSize, TLess>::iterator::operator==(const iterator &other) const noexcept
{
return node_ == other.node_;
};
template<typename T, int TSize, typename TLess>
bool skiplist<T, TSize, TLess>::iterator::operator!=(const iterator &other) const noexcept
{
return node_ != other.node_;
}
template<typename T, int TSize, typename TLess>
const T *skiplist<T, TSize, TLess>::iterator::operator->() const noexcept
{
if (!node_)
return nullptr;
return &node_->value();
}
template<typename T, int TSize, typename TLess>
const T &skiplist<T, TSize, TLess>::iterator::operator*() const noexcept
{
return node_->value();
}
template<typename T, int TSize, typename TLess>
typename skiplist<T, TSize, TLess>::iterator &skiplist<T, TSize, TLess>::iterator::operator=(const iterator &other) noexcept
{
node_ = other.node_;
return *this;
}
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::~skiplist()
{
auto flhead = freelist_head_.exchange(nullptr);
auto head = head_.exchange(nullptr);
while (head)
{
auto next = head->next(0);
delete head;
head = next.first;
}
while (flhead)
{
auto next = flhead->next(0);
delete flhead;
flhead = next.first;
}
}
template<typename T, int TSize, typename TLess>
std::default_random_engine skiplist<T, TSize, TLess>::random_;
template<typename T, int TSize, typename TLess>
skiplist<T, TSize, TLess>::skiplist() noexcept :
head_(nullptr),
freelist_head_(nullptr)
{
}
template<typename T, int TSize, typename TLess>
bool skiplist<T, TSize, TLess>::erase(const iterator &value) noexcept
{
if (value == end())
return false;
auto &rmnode = value.node_;
// first mark the node as being deleted
if (!rmnode->mark_for_deletion())
return false;
// now go through and remove it from the top level down to the bottom
pin cbefore;
for (int i = width - 1; i >= 0; i--)
{
while (true)
{
auto location = find_location(cbefore, i, rmnode->value());
cbefore = location.first;
// if the node isn't on this level, just break
if (location.second != rmnode || !location.first)
break;
// we marked the node as deleted... now let's remove it
remove_node_from_level(i, location.first, location.second);
break;
}
}
return true;
}
template<typename T, int TSize, typename TLess>
bool skiplist<T, TSize, TLess>::insert(const T &value) noexcept
{
std::uniform_int_distribution<int> generator(0, width-1);
int level = generator(random_);
std::array<std::pair<pin, pin>, width> locations;
// 1. root level insert logic
// here, the node either becomes the new head or gets
// inserted into the appropriate location in all of its
// levels
// find the insert locations
auto insnode = make_node(value, level);
auto insert_node = std::move(internal::pin_node(insnode, *this));
auto get_head = [this]() {
while (true)
{
auto headptr = head_.load();
if (!headptr)
return std::move(pin());
auto hptr = std::move(internal::pin_node(headptr, *this));
if (hptr)
return std::move(hptr);
}
};
auto head = std::move(get_head());
while (true)
{
if (!head)
{
// special case - the list is empty
node *current_head = nullptr;
for (int i = 1; i < width; i++)
insert_node->reference();
if (head_.compare_exchange_strong(current_head, insert_node.get()))
{
// 1a. we just set the new head.
// There is no additional housekeeping necessary
return true;
}
// doh! that didn't work
for (int i = 1; i < width; i++)
insert_node->dereference(*this);
head = std::move(internal::pin_node(current_head, *this));
if (!head)
head = std::move(get_head());
yield_and_continue();
}
find_location(0, value, locations);
// 2. We may be inserting a value that is already in the set. If so
// we'll just return a proper false value
// we establish that by seeing if the value is not less than the "after"
// which we already established as not being less than the value
if (locations[0].second && !cmp_(value, locations[0].second->value()) && !locations[0].second->is_marked())
{
// free the node - we dereference it because it's never added to the list
insert_node->dereference(*this);
return false;
}
// 3. There is in fact, already a head. But the value we're inserting
// belongs in front of it. So it needs to become the new head
if (!locations[0].first || (locations[0].first == head && head->is_marked()))
{
// for now, we will set our next to be the head on every level
// that will ensure that if any nodes get inserted after the head
// while we're operating, we'll catch them. But this means
// we'll need to go back and clean those up later
// point the nexts to the current head and add the references
// for the node to be head
insert_node->set_next(0, head.get());
for (int i = 1; i < width; i++)
{
insert_node->set_next(i, head.get());
insert_node->reference();
}
node *current_head = head.get();
if (head_.compare_exchange_strong(current_head, insert_node.get()))
{
// we have to finish the takeover as the head
// this will keep the state of the list valid
// in that there are no lost nodes. But will leave
// extra hops on levels beyond the old head's levels
takeover_head(insert_node, head);
// let the insert node get deleted
return true;
}
// we failed to make the node head, reset it's refcount to 1
for (int i = 1; i < width; i++)
insert_node->dereference(*this);
head = std::move(internal::pin_node(current_head, *this));
if (!head)
head = std::move(get_head());
yield_and_continue();
}
if (locations[0].first->is_marked())
{
// ok - well the node got marked - let's try again
head = std::move(get_head());
yield_and_continue();
}
// 4. This is a standard insert. We'll stick the node
// where it belongs in level 0. Once we do that. We're good to
// set it's other levels and return true
if (locations[0].first->insert_next(0, locations[0].second.get(), insert_node.get()))
{
// success!
for (int i = 1; i <= level; i++)
finish_insert(i, insert_node, locations);
// let the node get deleted when it's time
// the reference count is already one from making the node.
// And it'll bump up with the finish_insert calls
return true;
}
// now first is safe for removal until we pick it up again
head = std::move(get_head());
yield_and_continue();
}
}
template<typename T, int TSize, typename TLess>
typename skiplist<T, TSize, TLess>::iterator skiplist<T, TSize, TLess>::begin() noexcept
{
pin head;
while (true)
{
auto hd = head_.load();
if (!hd)
return iterator();
head = internal::pin_node(hd, *this);
if (!head)
{
yield_and_continue();
}
break;
}
if (head && head->is_marked())
head = std::move(pin_next_valid(0, head));
return iterator(std::move(head), this);
}
template<typename T, int TSize, typename TLess>
typename skiplist<T, TSize, TLess>::iterator skiplist<T, TSize, TLess>::end() const noexcept
{
return iterator();
}
template<typename T, int TSize, typename TLess>
typename skiplist<T, TSize, TLess>::iterator skiplist<T, TSize, TLess>::find(const T &value) noexcept
{
auto fndNode = find_location(0, value);
if (!fndNode)
return iterator();
return iterator(std::move(fndNode), this);
}
template<typename T, int TSize, typename TLess>
std::pair<internal::skiplist_node_pin<T, TSize, skiplist<T, TSize, TLess>>, internal::skiplist_node_pin<T, TSize, skiplist<T, TSize, TLess>>>
skiplist<T, TSize, TLess>::find_location(pin &before, int level, const T &value) noexcept
{
auto head_pair = [this]() {
auto head = head_.load();
while (head)
{
auto hd = std::move(internal::pin_node(head, *this));
if (hd)
return std::move(std::make_pair(std::move(hd), !head->is_marked()));
head = head_.load();
}
return std::move(std::make_pair(pin(), false));
};
auto after = before ? std::move(pin_next(level, before)) : std::move(head_pair());
while (after.first)
{
if (before)
{
// if our next node is marked for deletion
// or if it doesn't belong on this level (probably because
// it used to be head and got moved here)
if (after.first->is_marked() || after.first->level() < level)
{
if (before->is_marked() && before.get() != head_.load())
{
// there's no point removing after, because our before
// itself is now marked
before = pin();
after = std::move(head_pair());
continue;
}
remove_node_from_level(level, before, after.first);
after = std::move(pin_next(level, before));
yield_and_continue();
}
}
if (!cmp_(after.first->value(), value))
break;
before = std::move(after.first);
after = std::move(pin_next(level, before));
}
return std::move(std::make_pair(std::move(before), std::move(after.first)));
}
template<typename T, int TSize, typename TLess>
std::pair<typename skiplist<T, TSize, TLess>::pin, typename skiplist<T, TSize, TLess>::pin>
skiplist<T, TSize, TLess>::find_location(const pin &start, int level, const T &value) const noexcept
{
auto head_pair = [level, this]() {
pin head; // lol get it?
while (true)
{
auto hptr = head_.load();
if (!hptr)
return pin();
head = std::move(internal::pin_node(hptr, *const_cast<skiplist *>(this)));
if (head)
break;
}
while (head && head->is_marked())
head = pin_next_valid(level, head); // another pun, lolz
return head;
};
auto before = start;
auto after = before ? pin_next_valid(level, before) : head_pair();
while (after)
{
if (!cmp_(after->value(), value))
break;
before = after;
after = pin_next_valid(level, after);
}
return std::make_pair(before, after);
}
template<typename T, int TSize, typename TLess>
internal::skiplist_node_pin<T, TSize, skiplist<T, TSize, TLess>> skiplist<T, TSize, TLess>::find_location(int level, const T &value) const noexcept
{
pin cbefore;
for (int i = width - 1; i >= level; i--)
{
auto fnd = find_location(cbefore, i, value);
if (fnd.second && !cmp_(value, fnd.second->value()))
return fnd.second;
cbefore = fnd.first;
}
return pin();
}
template<typename T, int TSize, typename TLess>
void skiplist<T, TSize, TLess>::find_location(
int level,
const T &value,
std::array<std::pair<pin, pin>, width> &into) noexcept
{
pin cbefore;
for (int i = width - 1; i >= level; i--)
{
into[i] = std::move(find_location(cbefore, i, value));
if (!into[i].first)
{
auto &answer = into[i];
for (--i; i >= level; i--)
into[i] = answer;
break;
}
cbefore = into[i].first;
}
}
template<typename T, int TSize, typename TLess>
internal::skiplist_node<T, TSize> *skiplist<T, TSize, TLess>::make_node(const T &value, int level)
{
// try to get a node out of our free list
auto flhead = freelist_head_.load();
while (true)
{
if (flhead == nullptr) // nope, nothing in the freelist
break;
auto next = flhead->next(0).first;
if (freelist_head_.compare_exchange_strong(flhead, next))
{
flhead->init(value, level);
return flhead;
}
}
// We had no free nodes
auto result = new internal::skiplist_node<T, TSize>();
result->init(value, level);
return result;
}
template<typename T, int TSize, typename TLess>
void skiplist<T, TSize, TLess>::takeover_head(pin &newhead, pin &oldhead) noexcept
{
// In this phase, oldhead was the head and newhead is now the head
// however, all of newhead's next's are pointing to oldhead.
// this leaves us in a valid state. But it's sub-optimal.
// So this will make a best effort to not do that.
for (int i = width - 1; i > oldhead->level(); i--)
{
// for each level, we are ok for head to be next, but not for anyone's next
// to be in a transitory invalid state. So we'll just keep trying to remove
// head from the levels beyond where head should be
remove_node_from_level(i, newhead, oldhead);
}
}
template<typename T, int TSize, typename TLess>
void skiplist<T, TSize, TLess>::remove_node_from_level(int level, const pin &prev_hint, const pin &remnode) noexcept
{
// step 1: mark the remnode's next to ensure that nothing gets inserted to it's next
// if it's already marked, it either means someone else is removing the node
// or someone is removing the node after remnode. In that case, we'll need to
// try again later
std::pair<pin, bool> new_next;
while (true)
{
new_next = std::move(pin_next(level, remnode));
auto next_ptr = new_next.first.get();
if (!new_next.second)
return;
if (new_next.first && (next_ptr->is_marked() || next_ptr->level() < level))
{
remove_node_from_level(level, remnode, new_next.first);
continue;
}
if (remnode->mark_next_deleted(level, next_ptr))
break;
if (!new_next.second)
{
// someone marked before us. It'll either come back
// or someone else is deleting or has deleted this node
return;
}
yield_and_continue();
}
// step 2: mark prev's next as deleted if it's still remnode
pin prev = prev_hint;
node *expected_rm = remnode.get();
while (!prev->remove_next(level, expected_rm, new_next.first.get()))
{
if (expected_rm == remnode.get())
{
// our previous itself is also being deleted
// so it's next won't be updated ever
// but that also means that our prev would have
// changed. We'll have to go back and figure out
// who it is. Which we could do. Or we could
// let another thread do it later
// we'll unmark the node and try again later
remnode->unmark_next(level, new_next.first.get());
return;
}
// our prev_node isn't pointing to our remnode anymore.
// Something else would have been inserted in between
prev = pin_next(level, prev).first;
if (!prev)
return;
yield_and_continue();
}
remnode->dereference(*this);
}
template<typename T, int TSize, typename TLess>
void skiplist<T, TSize, TLess>::finish_insert(
int level,
pin &insertnode,
std::array<std::pair<pin, pin>, width> &locations) noexcept
{
// in this function, insertnode has already
// been inserted at level 0 - but it needs to be inserted
// at all of the the subsequent levels
// which we'll do as long as the node isn't marked
while (!insertnode->is_marked())
{
insertnode->reference();
if (locations[level].first && locations[level].first->insert_next(level, locations[level].second.get(), insertnode.get()))
{
// reference the node for this level
return;
}
insertnode->dereference(*this);
// that failed. We need to rescan the locations for the level
find_location(level, insertnode->value(), locations);
if (!locations[level].first)
{
// all the possible predecessors for the node have been removed.
// that means this one will have had to have been set up
break;
}
}
}
template<typename T, int TSize, typename TLess>
void skiplist<T, TSize, TLess>::deallocate(node *nd)
{
return;
// we can drop this into the freelist
auto flhead = freelist_head_.load();
while (true)
{
nd->set_next(0, flhead);
if (freelist_head_.compare_exchange_strong(flhead, nd))
break;
}
}
#undef yield_and_continue
}
#endif //CXXMETRICS_PQSKIPLIST_HPP
| true |
65e155c33703f41d2ac1f4ce8855a2e8e0a9f9a3 | C++ | caroriv/divisas | /tarea.cpp | ISO-8859-1 | 1,912 | 4.09375 | 4 | [
"MIT"
] | permissive | /*
-Pedir al usuario el valor que desea realizar el clculo de factorial.
-Cambiar el tipo de dato para poder hacer clculo ms grande.
-Validar la entrada del usuario (que sea un entero positivo), en caso de no cumplir este requerimiento se
debe pedir un valor vlido.
-Una vez terminado el clculo, preguntar al usuario si desea calcular otro valor o si desea salir del programa.
*/
#include <stdio.h>
double factorial(double x);
int main(){
double numero, calculo;
int condicion;
do{
//Ingresamos el nmero, para obtener el factorial.
printf("\n\nIngrese un numero: ");
scanf("%lf", &numero);
//Si el nmero es mayor a 0, se har el clculo del factorial.
if(numero > 0){
calculo = factorial (numero);
printf("El factorial del numero %.0lf es de: %.0lf ", numero, calculo);
}
//En caso de que sea negativo, va a mostrar el siguiente mensaje,
//hasta que el usuario ingrese un nmero positivo.
else{
do{
printf("\nOpcion invalida, intente de nuevo\n");
printf("\nIngrese un numero positivo: ");
scanf("%lf", &numero);
}while(numero < 0);
calculo = factorial (numero);
printf("\nEl factorial del numero %.0lf es de: %.0lf ", numero, calculo);
}
//Si ingresamos el nmero 1 se volver a pedir un nmero y podremos calcular otro factorial.
//Al menos que el usuario desee ingresar el nmero 0, para salir.
printf("\nDesea realizar otro calculo [Si=1][No=0]: ");
scanf("%d", &condicion);
}while(condicion != 0);
//Y cuando termine el programa se va a mostrar este mensaje.
printf("\n Hasta luego \n");
return 0;
}
double factorial(double x){
if(x == 0 || x == 1){
return 1;
}
else{
return x * factorial (x - 1);
}
}
| true |
2f1cba41d1e259dd591bf92fe19ac4969a357b33 | C++ | AndreyTokmakov/Design-Patterns | /ChainOfResponsibility.cpp | UTF-8 | 2,608 | 3.265625 | 3 | [] | no_license | //============================================================================
// Name : ChainOfResponsibility.cpp
// Created on : 19.04.2020
// Author : Tokmakov Andrey
// Version : 1.0
// Copyright : Your copyright notice
// Description : Chain of pesponsibility pattern tests
//============================================================================
#include "ChainOfResponsibility.h"
namespace ChainOfResponsibility_Pattern_Tests {
CriminalAction::CriminalAction(int complexity, CString description) :
complexity(complexity), description(description) {
}
//////////////////
Policeman::Policeman(int deduction) :
deduction(deduction), next(nullptr) {
}
Policeman::~Policeman() {
// delete next;
// std::cout << __FUNCTION__ << " " << typeid(*this).name() << std::endl;
}
std::shared_ptr<Policeman> Policeman::setNext(std::shared_ptr <Policeman> policeman) {
next = policeman;
return next;
}
void Policeman::investigate(std::shared_ptr<CriminalAction> criminalAction) {
if (deduction < criminalAction->complexity) {
if (next) {
next->investigate(criminalAction);
}
else {
std::cout << "This case is not disclosed to anyone." << std::endl;
}
}
else {
investigateConcrete(criminalAction->description);
}
}
void MartinRiggs::investigateConcrete(CString description) {
std::cout << "Case investigation '" << description << "' leads Sergeant Martin Riggs" << std::endl;
}
MartinRiggs::MartinRiggs(int deduction) : Policeman(deduction) {
}
void JohnMcClane::investigateConcrete(CString description) {
std::cout << "Case investigation '" << description << "' leads Detective John McClanes" << std::endl;
}
JohnMcClane::JohnMcClane(int deduction) : Policeman(deduction) {
}
void VincentHanna::investigateConcrete(CString description) {
std::cout << "Case investigation '" << description << "' leads Lieutenant Vincent Hanna" << std::endl;
}
VincentHanna::VincentHanna(int deduction) : Policeman(deduction) {
}
void Test()
{
std::shared_ptr<Policeman> policeman = std::make_shared<MartinRiggs>(3);
policeman->setNext(std::make_shared<JohnMcClane>(5))->setNext(std::make_shared<VincentHanna>(8));
policeman->investigate(std::make_shared<CriminalAction>(2, "Drug trade from Vietnam"));
policeman->investigate(std::make_shared<CriminalAction>(7, "Cheeky bank robbery in downtown Los Angeles"));
policeman->investigate(std::make_shared<CriminalAction>(5, "A series of explosions in downtown New York"));
}
} | true |
6014833ebc0ffbb19aa78cf550afe719c8f6d5fc | C++ | wrosecrans/graph | /include/graph/algorithm/spMatspMat.hpp | UTF-8 | 5,132 | 2.59375 | 3 | [] | no_license | //
// This file is part of Standard Graph Library (SGL)
// (c) Pacific Northwest National Laboratory 2018
//
// Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0
// International License
// https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Author: Scott McMillan
//
#pragma once
#include <tuple>
#include <map>
#include <algorithm>
#include <util.hpp>
#include <edge_list.hpp>
#include <plain_range.hpp>
//****************************************************************************
// A * B
//****************************************************************************
//****************************************************************************
/// @todo cannot currently pass "const &" for A or B
/// @todo Need to discuss interface options
template <typename ScalarT,
typename LGraphT, typename RGraphT,
typename MapOpT = std::multiplies<ScalarT>,
typename ReduceOpT = std::plus<ScalarT> >
edge_list<directed, ScalarT> spMatspMat(LGraphT &A, RGraphT &B)
{
edge_list<directed, ScalarT> edges(0);
edges.open_for_push_back();
// compute A * B
vertex_index_t i = 0; // row_it - A.begin();
for (auto row_it = A.begin(); row_it != A.end(); ++row_it, ++i)
{
// clear Row i of C
std::map<size_t, ScalarT> Ci_tmp;
for (auto const Ai_elt : *row_it)
{
auto k = std::get<0>(Ai_elt);
auto a_ik = std::get<1>(Ai_elt);
for (auto const Bk_elt : *(B.begin() + k))
{
auto j = std::get<0>(Bk_elt);
auto b_kj = std::get<1>(Bk_elt);
// TODO: Do we really want semiring support. If so,
// what is best way to deal with additive identity?
ScalarT tmp(MapOpT()(a_ik, b_kj)); // C_ij partial product
if (Ci_tmp.find(j) != Ci_tmp.end())
{
Ci_tmp[j] = ReduceOpT()(Ci_tmp[j], tmp);
}
else
{
Ci_tmp[j] = tmp;
}
}
}
// extract from the map and put in edge_list
for (auto const elt : Ci_tmp)
{
edges.push_back(i, elt.first, elt.second);
}
}
edges.close_for_push_back();
edges.template sort_by<0>();
return edges;
}
//****************************************************************************
// A * B'
//****************************************************************************
//****************************************************************************
// map
template<class InputIt1, class InputIt2,
class Output, class Compare, class Map>
void set_ewise_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Output &container, Compare comp, Map map)
{
while (first1 != last1 && first2 != last2) {
if (comp(*first1, *first2)) {
++first1;
} else {
if (!comp(*first2, *first1)) {
container.push_back(map(*first1, *first2));
//std::cout << "map = " << map(*first1, *first2) << std::endl;
++first1;
}
++first2;
}
}
}
//****************************************************************************
/// @todo cannot currently pass "const &" for A or BT
template <typename ScalarT,
typename LGraphT, typename RGraphT,
typename MapOpT = std::multiplies<ScalarT>,
typename ReduceOpT = std::plus<ScalarT> >
edge_list<directed, ScalarT> spMatspMatT(LGraphT &A, RGraphT &BT)
{
std::vector<ScalarT> products;
edge_list<directed, ScalarT> edges(0);
edges.open_for_push_back();
// compute A * B' with a series of sparse dot products
vertex_index_t row_idx = 0;
for (auto row_it = A.begin(); row_it != A.end(); ++row_it, ++row_idx)
{
vertex_index_t col_idx = 0;
for (auto col_it = BT.begin(); col_it != BT.end(); ++col_it, ++col_idx)
{
//std::cout << "Computing " << row_idx << "," << col_idx << std::endl;
products.clear();
set_ewise_intersection(
(*row_it).begin(), (*row_it).end(),
(*col_it).begin(), (*col_it).end(),
products,
[](auto &&a, auto &&bt) -> bool {
return std::get<0>(a) < std::get<0>(bt); },
[](auto &&a, auto &&bt) -> ScalarT {
return MapOpT()(std::get<1>(a), std::get<1>(bt)); });
if (!products.empty()) {
ScalarT res = std::accumulate(
products.begin(), products.end(), (ScalarT)0, ReduceOpT());
edges.push_back(row_idx, col_idx, res);
//std::cout << "Added element (" << row_idx << ","
// << col_idx << ") = " << res << std::endl;
products.clear();
}
}
}
edges.close_for_push_back();
//edges.template sort_by<0>(); // not necessary
return edges;
}
| true |
2577b4582b2627e6b744495bd1c5438843cc3c05 | C++ | greenfox-zerda-sparta/nagyzsuska | /week5/Day-4/taskmanager.cpp | UTF-8 | 2,003 | 3.25 | 3 | [] | no_license | #include "taskmanager.h"
#include "errorhandler.h"
#include "filehandler.h"
#include <iostream>
Todo::Todo(std::string file_name) {
m_filename = file_name;
m_errorhandler = new MyErrorHandler();
m_filehandler = new MyFileHandler();
}
Todo::~Todo() {
delete m_errorhandler;
delete m_filehandler;
}
void Todo::run(int argc, char** argv) {
switch (argc) {
case 3:
set_param(argv[2]);
case 2:
set_command(argv[1]);
break;
default:
break;
}
doTask();
}
void Todo::print_usage() {
m_errorhandler->print_error("CLI Todo application\n====================\n\nCommand line arguments:\n- l Lists all the tasks\n- a Adds a new task\n- r Removes an task\n- c Completes an task\n");
}
void Todo::list() {
m_filehandler->print_file(m_filename);
}
void Todo::add() {
if (m_param == "") {
m_errorhandler->print_error("Unable to add : No task is provided");
}
else {
m_filehandler->add(m_filename, m_param);
}
}
void Todo::remove() {
if (m_param == "") {
m_errorhandler->print_error("Unable to remove : No index is provided");
} else if (m_errorhandler->check_param(m_param, m_filehandler->get_count_of_lines(m_filename))) {
int a = atoi(m_param.c_str());
m_filehandler->remove_from_file(m_filename, a);
}
}
void Todo::doTask() {
if (m_command == "-l") {
list();
}
else if (m_command == "-a") {
add();
}
else if (m_command == "-r") {
remove();
}
else if (m_command == "-c") {
check_task();
}
else {
m_errorhandler->print_error("Unsupported argument\n\n");
print_usage();
}
}
void Todo::check_task() {
if (m_param == "") {
m_errorhandler->print_error("Unable to check : No index is provided");
}
else {
if (m_errorhandler->has_only_digit(m_param))
{
int a = atoi(m_param.c_str());
if (!m_errorhandler->index_is_out_of_bound(a, m_filehandler->get_count_of_lines(m_filename)))
{
m_filehandler->check_task(m_filename, a);
}
}
}
} | true |
0f79fd72c046cbbd19081d578d7d3aa942d5a6fd | C++ | rashedcs/LAB | /DS/Linear Search.cpp | UTF-8 | 529 | 3.640625 | 4 | [] | no_license |
#include <iostream>
using namespace std;
int main()
{
int arr[40], key,n,flag=0;
cout<<"Enter the number of elements in array : ";
cin>>n;
cout<<"The numbers are : ";
for (int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to search : ";
cin>>key;
for (int i=0; i<n; i++)
{
if (arr[i]==key)
{
flag=1;
cout<<"The number is found at "<<i;
break;
}
}
if (flag!=1) cout<<"Sorry, The number is not found "<<endl;
return 0;
}
| true |
34dc689fb695735294c3d64dd8b605b9e7945f0a | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#745_PrefixAndSuffixSearch.cpp | UTF-8 | 1,956 | 3.546875 | 4 | [
"MIT"
] | permissive | class TrieNode{
public:
static const int ALPHABET_SIZE = 27;
static const char FIRST_LETTER = char('a' - 1);
int max_weight;
vector<TrieNode*> children;
TrieNode(){
this->max_weight = 0;
this->children.resize(ALPHABET_SIZE, NULL);
}
void insert(const string& word, const int& weight){
TrieNode* node = this;
for(char c: word){
short int edge_id = c - FIRST_LETTER;
if(node->children[edge_id] == NULL){
node->children[edge_id] = new TrieNode();
}
node = node->children[edge_id];
node->max_weight = max(weight, node->max_weight);
}
}
void insert_prefixes_and_suffixes(const string& word, const int& weight){
for(int pos = (int)word.length(); pos >= 0; --pos){
insert(word.substr(pos) + string(1, FIRST_LETTER) + word, weight);
}
}
int get_max_weight(const string& prefix, const string& suffix){
string word = suffix + string(1, FIRST_LETTER) + prefix;
TrieNode* node = this;
for(char c: word){
short int edge_id = c - FIRST_LETTER;
if(node->children[edge_id] == NULL){
return -1;
}
node = node->children[edge_id];
}
return node->max_weight;
}
};
class WordFilter {
private:
TrieNode* trie;
public:
WordFilter(vector<string>& words) {
this->trie = new TrieNode();
for(int i = 0; i < words.size(); ++i){
trie->insert_prefixes_and_suffixes(words[i], i);
}
}
int f(string prefix, string suffix) {
return trie->get_max_weight(prefix, suffix);
}
};
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter* obj = new WordFilter(words);
* int param_1 = obj->f(prefix,suffix);
*/ | true |
5842d2862d5a7dc70e09f4ae4c7a40b28cc7f507 | C++ | xiweihuang/Primer | /chapter12/default_init.cpp | UTF-8 | 613 | 3.609375 | 4 | [] | no_license | // 默认初始化和值初始化
#include <iostream>
using namespace std;
// int a1[6];
// void print(int *p, int len) {
// for (size_t i = 0; i != len; ++i) {
// cout << *(p+i) << ", ";
// }
// cout << endl;
// }
// int main()
// {
// int a2[5];
// print(a1, 6); // 0, 0, 0, 0, 0, 0
// print(a2, 5); // 0, 0, 0, 0, 1439370272
// return 0;
// }
class Person {
public:
int a[10]; // 没有类内初始值,执行默认初始化。
};
int main()
{
Person p;
for (int i = 0; i < 10; ++i) {
cout << p.a[i] << ", "; // 1591000128, 32767, 0, 0, 0, 0, 0, 0, 0, 0
}
cout << endl;
return 0;
} | true |
f2e943f4e9bb94e3c1319c7c03a9588c7c3c8720 | C++ | gamburgm/Exercises | /sorts/heapsort.cpp | UTF-8 | 1,783 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <string>
using namespace std;
#define LEN 10
void buildHeap(int* arr);
void heapsort(int* arr);
void upheap(int* arr, int valIdx);
void downheap(int* arr, int valIdx, int maxIdx);
void swap(int* valOne, int* valTwo);
void printArray(int* arr);
int main() {
int arr[LEN];
for (int i = 0; i < LEN; i++) {
int x;
printf("Initialize index %d in array: ", i);
cin >> x;
arr[i] = x;
}
printf("Original Array:\n");
printArray(arr);
printf("Array in Heap form:\n");
buildHeap(arr);
printArray(arr);
printf("Sorted Array:\n");
heapsort(arr);
printArray(arr);
return 0;
}
void buildHeap(int* arr) {
for (int i = 1; i < LEN; i++)
upheap(arr, i);
}
void upheap(int* arr, int valIdx) {
if (valIdx == 0)
return;
int parentIdx = (valIdx - 1) / 2;
if (arr[valIdx] > arr[parentIdx]) {
swap(arr[valIdx], arr[parentIdx]);
upheap(arr, parentIdx);
}
}
void heapsort(int* arr) {
for (int i = 0; i < LEN; i++) {
int maxIdx = LEN - 1 - i;
swap(arr[0], arr[maxIdx]);
downheap(arr, 0, maxIdx - 1);
}
}
void downheap(int* arr, int valIdx, int maxIdx) {
int leftChildIdx = (2 * valIdx) + 1;
int rightChildIdx = (2 * valIdx) + 2;
int biggestChildIdx;
if (leftChildIdx > maxIdx)
return;
if (rightChildIdx > maxIdx)
biggestChildIdx = leftChildIdx;
else
biggestChildIdx = (arr[leftChildIdx] > arr[rightChildIdx] ? leftChildIdx : rightChildIdx);
if (arr[valIdx] < arr[biggestChildIdx]) {
swap(arr[valIdx], arr[biggestChildIdx]);
downheap(arr, biggestChildIdx, maxIdx);
}
}
void swap(int* valOne, int* valTwo) {
int temp = *valTwo;
*valTwo = *valOne;
*valOne = temp;
}
void printArray(int* arr) {
for (int i = 0; i < LEN; i++)
cout << "[" << arr[i] << "]";
printf("\n");
}
| true |
b8687a9fa0b326074701e2a4a4517cf3bf65b5c0 | C++ | munguia11/DATO3 | /DATO3.cpp | UTF-8 | 451 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct Dato{
int dato1;
char dato2[20];
};
int main (int argc, char**argv){
struct Dato var1;
struct Dato *ptr;
ptr=&var1;
cout<<"puntero= "<<&ptr<<endl;
cout<< "direccion de ptr"<< ptr<<endl;
cin >>(*ptr).dato1;
cout<<(*ptr).dato1<<endl;
cin>>ptr->dato1;
cout<<ptr->dato1<<endl;
cout<<"ingresar char"<<endl;
fflush(stdin);
cin.getline(ptr->dato2,20,'\n');
cout<<ptr->dato2<<endl;
return 0;
}
| true |
528c38f239ba3876d14957208d2ef1997c19da41 | C++ | cypherix93/cse328-project | /RealFluid/src/App/Drawing/GridDrawer/GridDrawer.cpp | UTF-8 | 3,233 | 3.125 | 3 | [
"MIT"
] | permissive | #include "GridDrawer.h"
GridDrawOptions::GridDrawOptions()
{
CellDimensions = 40;
DrawCellContents = true;
DrawCellOutline = true;
DrawCellVectors = true;
DrawParticles = true;
}
GridDrawOptions::~GridDrawOptions()
{
}
void DrawCellGrid(Grid* grid, GridDrawOptions* options)
{
if (options == nullptr)
options = new GridDrawOptions();
if (options->DrawParticles)
{
auto particles = grid->GetParticlesVector();
for (auto &particle : *particles)
{
DrawParticle(particle, options);
}
}
auto cells = grid->GetCellsVector();
for (auto &cell : *cells)
{
DrawCell(cell, options);
}
}
void DrawCell(FluidCell* cell, GridDrawOptions* options)
{
if (options->DrawCellVectors)
DrawCellVectors(cell, options);
if (options->DrawCellContents)
DrawCellContents(cell, options);
if (options->DrawCellOutline)
DrawCellOutline(cell, options);
}
void DrawCellContents(FluidCell* cell, GridDrawOptions* options)
{
auto x = cell->I * options->CellDimensions;
auto y = cell->J * options->CellDimensions;
auto z = cell->K * options->CellDimensions;
if (cell->Type == Empty)
return;
if (cell->Type == Solid)
{
glColor4f(0.8f, 0.63f, 0.44f, 1.0f);
}
else if (cell->Type == Surface)
{
glColor4f(0.75f, 0.85f, 0.95f, 1.0f);
}
else if (cell->Type == Full)
{
glColor4f(0.45f, 0.75f, 0.95f, 1.0f);
}
glBegin(GL_POLYGON);
glVertex3f(x, y, z);
x += options->CellDimensions;
glVertex3f(x, y, z);
y += options->CellDimensions;
glVertex3f(x, y, z);
x -= options->CellDimensions;
glVertex3f(x, y, z);
y -= options->CellDimensions;
glVertex3f(x, y, z);
glEnd();
}
void DrawCellOutline(FluidCell* cell, GridDrawOptions* options)
{
auto x = cell->I * options->CellDimensions;
auto y = cell->J * options->CellDimensions;
auto z = cell->K * options->CellDimensions;
glColor4f(1.0f, 1.0f, 1.0f, 0.2f);
glBegin(GL_LINE_LOOP);
glVertex3f(x, y, z);
x += options->CellDimensions;
glVertex3f(x, y, z);
y += options->CellDimensions;
glVertex3f(x, y, z);
x -= options->CellDimensions;
glVertex3f(x, y, z);
y -= options->CellDimensions;
glVertex3f(x, y, z);
glEnd();
}
void DrawCellVectors(FluidCell* cell, GridDrawOptions* options)
{
auto x = (cell->I * options->CellDimensions) + (options->CellDimensions / 2);
auto y = (cell->J * options->CellDimensions) + (options->CellDimensions / 2);
auto z = 0.0f;
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_LINES);
glVertex3f(x, y, z);
x += cell->U * options->CellDimensions;
y += cell->V * options->CellDimensions;
//z += cell->W * options->CellDimensions;
glVertex3f(x, y, z);
glEnd();
}
void DrawParticle(Particle* particle, GridDrawOptions* options)
{
glPointSize(6.0);
glColor4f(0.57f, 0.9f, 0.63f, 1.0f);
glBegin(GL_POINTS);
glVertex3f(
particle->X * options->CellDimensions,
particle->Y * options->CellDimensions,
particle->Z * options->CellDimensions
);
glEnd();
}
| true |
ba52f7ea8341e175d8ebea0b37aff6fbad49e019 | C++ | scheninsp/Cpp_Reps | /algorithms/longest_palindromic_substring_2.cpp | UTF-8 | 2,196 | 3.3125 | 3 | [] | no_license | //longest palindromic string 2
#include<string>
#include<algorithm>
#include<iostream>
using std::string;
using std::min;
using std::cout;
using std::endl;
static int lps_util(int* dp, int len, string& str){
int p0 = 1; //rightmost palindromic center
int p = 2; //rightmost palindromic length
dp[0] = 1;
dp[1] = 2;
int max_dp_pos = 1;
int max_dp_len = 2;
for (int i = 2; i < len; i++) {
if (i < p0 + p - 1) {
if (dp[2 * p0 - i] < min(p0 + p - i, i - p0 + 1)) {
dp[i] = dp[2 * p0 - i];
}
else {
int st = min(p0 + p - i, i - p0 + 1);
dp[i] = st;
while (i + st < len - 1 && i - st > 0 ){
if ((i + st + 1) % 2 == 0) {
int p1 = (i + st - 1) / 2;
int p2 = (i - st - 1) / 2;
if (str[p1] == str[p2]) { dp[i] += 2; }
else { break; }
}
st++;
}
}
}
else {//i >= p0+p-1
int st = 0;
dp[i] = st;
while (i + st < len - 1 && i - st > 0) {
if ((i + st + 1) % 2 == 0) {
int p1 = (i + st - 1) / 2;
int p2 = (i - st - 1) / 2;
if (str[p1] == str[p2]) { dp[i] += 2; }
else { break; }
}
st++;
}
}
//reset rightmost
if( i + dp[i] - 1 > p0 + p - 1){
p0 = i;
p = dp[i];
}
if (dp[i] > max_dp_len) {
max_dp_len = dp[i];
max_dp_pos = i;
}
}
return max_dp_pos;
};
string lps(string& str) {
unsigned long const len = str.size() * 2 + 1;
int* dp = new int[len];
memset(dp, 0, sizeof(int)*len);
int max_dp_pos = lps_util(dp, len, str);
int max_dp_len = dp[max_dp_pos];
int max_dp_pos_ori = (max_dp_pos - 1) / 2;
int max_dp_len_ori = (dp[max_dp_pos] + 1) / 2; //dp[i] does not include last #s
//print dp
for (int i = 0; i < len; i++) {
cout << i << ":" << (dp[i]+1)/2 <<" ";
}
cout << endl;
int pbegin = max_dp_pos_ori - max_dp_len_ori + 1;
int pend = max_dp_pos_ori + max_dp_len_ori - 1;
string str_p(str, pbegin, pend);
delete[] dp;
return str_p;
};
int main() {
string str = "abcbaaaabcddcba";
//string str = "abcbaabcddcba";
//string str = "abcba";
string x = lps(str);
cout << x << endl;
getchar();
return 0;
}; | true |
cf2c4c9f6afcc936830594d2f5dd0e96d46085f0 | C++ | franckycodes/gestion_de_stock_en_cpp | /strtools.cpp | UTF-8 | 2,003 | 3.296875 | 3 | [] | no_license | #include "strtools.h"
#include <string>
#include <string.h>
#include "conversiontools.h"
using namespace std;
std::string getStr(std::string mainStr, int minIndex, int maxIndex)
{
std::string result("");
for(int i(minIndex),c(maxIndex);i<c;i++)
{
result += mainStr[i];
}
return result;
}
int getTotalWords(std::string books)
{
int totalFound(0);
for(int i(0),c(books.size());i<c;i++)
{
//basic condition
//conditions || books[i]=="." || books[i]=="," || books[i]==""
if(books[i]==' ' || books[i]=='\n')
{
totalFound++;
}
}
return totalFound;
}
//for a symbol only
std::string replaceStr(std::string mainStr, std::string toReplace, std::string replacement, bool escapeSymbol)
{
std::string result("");
for(int i(0),c(mainStr.length());i<c;i++)
{
if(escapeSymbol){
if(mainStr[i]!=toReplace[0])
{
result+=mainStr[i];
}
}else{
if(mainStr[i]==toReplace[0])
{
mainStr[i]=replacement[0];
}
}
}
return escapeSymbol?result:mainStr;
}
std::string toUpperCase(std::string str)
{
/*for(int i(0),c(str.size());i<c;i++)
{
str[i]=strupr(str[i])
}*/
return "";
}
std::string toLowerCase(std::string str)
{
/*
for(int i(0),c(str.size());i<c;i++)
{
str[i]=strlwr(str[i])
}*/
return "";
}
//_rov_hello world_rov_
std::string replaceText(std::string mainStr, std::string toReplace, std::string replacement)
{
const int mainPos(mainStr.find(toReplace));
const int toReplaceSize(toReplace.size());
std::string result("");
for(int i(0),c(mainStr.size());i<c;i++)
{
if(i!=mainPos && i>=toReplaceSize)
{
result+=mainStr[i];
}
}
// for(int i(mainPos),c(mainPos+toReplace.size());i<c;i++)
// {
// result+=mainStr[i];
// }
return result;
}
| true |
fc6ced1cfb9a1681eee929b49abcd713810dffa8 | C++ | SourDumplings/CodeSolutions | /Book practices/《C++primer》 5th 练习代码/chapter13/Exercise13.44.cpp | UTF-8 | 1,173 | 3.203125 | 3 | [] | no_license | /*
@Date : 2018-01-03 21:08:09
@Author : 酸饺子 (changzheng300@foxmail.com)
@Link : https://github.com/SourDumplings
@Version : $Id$
*/
/*
p531
*/
#include <iostream>
#include <algorithm>
#include <utility>
#include <memory>
#include <cstring>
using namespace std;
using namespace std::placeholders;
class String
{
public:
String(): String("") {}
String(const char *);
~String();
size_t size() { return end - begin; }
void getStr() { for_each(begin, end, [] (const char &c) { cout << c; });}
private:
char *begin;
char *end;
static allocator<char> alloc;
};
allocator<char> String::alloc;
String::String(const char *s)
{
size_t l = strlen(s);
// printf("%u\n", l);
char* ucs = const_cast<char*>(s);
begin = alloc.allocate(l);
end = begin + l;
for_each(begin, end, [ucs] (char &c) mutable { alloc.construct(&c, *ucs++); });
}
String::~String()
{
for_each(begin, end, [] (char c) {alloc.destroy(&c); });
alloc.deallocate(begin, end-begin);
}
int main(int argc, char const *argv[])
{
String s2("abc");
String s1;
s1.getStr();
cout << endl;
s2.getStr();
cout << endl;
return 0;
}
| true |
92d2023d657516c6fe56a1d58f87f1db228f7062 | C++ | pig-zhang/pig-s | /数学运算符_循环结构.cpp | GB18030 | 4,605 | 4.1875 | 4 | [] | no_license | #include <iostream>
#include <stdio.h>
// ͷļ
// C/C++--ѧʽ/ѭṹ
int main() {
// C/C++ѧµĹ
// CС=ֵ==ڡ=ڡ
// <='Сڵڡ >='ڵڡ ڸֵҲнҸֵ
// ' == ' ʹڸж
// Ϊѧ
// ӷ+ - ˷ * / ģ%
// дʽҲѧдͬҪעŵȷʹ
// ΪֽΪѧ
// /Լ++/-- ʹ11
// ++/-- ڱǰߺ
// ++/--ڱǰ ʾٲӦ
// ++/--ڱ ʾȽӦ
// +=/-=ʽ
// ڡ֮ > a+=2 ʾa2
// ͬʱĻѧҲıʽ
// ˳ṹ
// ˵ѭṹʱͲòᵽC/C++
// > ||
// > '&&'
/*
*
* ѭṹطãʹࡢԸǿ
ѭṹwhiledo...whilefor
whileforʹý϶࣬do...whileҲдwhileʽ
˵˵while
ṹwhile(ʽ)
{
ѭ
}
ʽĽΪ١ 0 ʱѭ
while(i++<10) //iֵڵʱʽĽΪ١ѭ
{
printf(count %d ,i);
}
˵˵do...while
ṹdo
{
ѭ
}while(ʽ);
while䲻ͬǣdo...whileȽһѭ䣬жϱʽ
˵˵for䣬ʮֺõһ䣬Ľʹʮ־
forʹɷֺŸƱʽѭ̡ʼʽֻڿʼִѭ֮ǰִһΡ
жϱʽΪ(0)ִһѭȻ±ʽٴμжϱʽֵforһ
ѭڽһѭ֮ǰǷҪִѭпѭһҲִСѭ䲿ֿ
һһ䡣
ϵĽͣͦ
ʽ
ṹfor(ʼʽ;жϱʽ;±ʽ)
{
ѭ
}
whileƣжϱʽΪ١ 0 ֮ǰظѭ
for(i=0;i<100;i++)
{
printf("i count is %d\n",i);
}
i<100ʱظѭ䣬ִѭٽi++
˵ѭṹмѭṹ䲻òἰ
Ǿǣbreakcontinue
˼֪breakѭѭ
continueϿǼѭʵǣٽcontinueѭ
ֱӽһѭҪע
*
* */
return 0;
}
| true |
304b42d3efb00aa1e2c519548cadf7e06eec935f | C++ | Axe-hyx/leetcode-salute | /712.minimum-ascii-delete-sum-for-two-strings.cpp | UTF-8 | 1,197 | 3.0625 | 3 | [] | no_license | /*
* @lc app=leetcode id=712 lang=cpp
*
* [712] Minimum ASCII Delete Sum for Two Strings
*/
// @lc code=start
#include <bits/stdc++.h>
using namespace std;
// Time Complexity:
// Space Complexity:
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int n = s1.size(), m = s2.size();
int dp[n+1][m+1];
memset(dp, 0, sizeof(int) * (n+1) * (m+1));
for(int i = 1; i<=m; ++i){
dp[0][i] = dp[0][i-1] + s2[i-1];
}
for(int i = 1; i<=n; ++i){
dp[i][0] = dp[i-1][0] + s1[i-1];
for(int j = 1; j<=m; ++j){
if(s1[i-1] == s2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1] + s2[j-1]);
}
}
}
return dp[n][m];
}
};
int main(){
Solution sol;
string s1 = "sea", t1 = "eat";
cout<<sol.minimumDeleteSum(s1, t1)<<endl;
string s2 = "delete", t2 = "leet";
cout<<sol.minimumDeleteSum(s2, t2)<<endl;
string s3 = "kslcclpmfd", t3 = "guvjxozrjvzhe";
cout<<sol.minimumDeleteSum(s3, t3)<<endl;
return 0;
}
// @lc code=end
| true |
84c6fba859a3b9a556c76ed794c9956c2256a493 | C++ | Arbos/nwn2mdk | /dumpgr2/dumpgr2.cpp | UTF-8 | 23,133 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <set>
#include <map>
#include <string>
#include "gr2_file.h"
using namespace std;
void print_keys(GR2_property_key* k, std::set<GR2_property_key*>& printed,
int padding_size);
void print_key(GR2_property_key* k, std::set<GR2_property_key*>& printed,
int padding_size)
{
cout << string(padding_size, ' ').c_str();
cout << k->name << ": " << k->type << " ("
<< property_type_to_str(k->type) << ')';
if (k->length > 0)
cout << " [" << k->length << ']';
cout << endl;
// Print subkeys
if (k->keys)
print_keys(k->keys, printed, padding_size + 2);
}
void print_keys(GR2_property_key* k, std::set<GR2_property_key*>& printed,
int padding_size)
{
if (printed.find(k) != printed.end())
return;
printed.insert(k);
while (k->type != 0) {
print_key(k, printed, padding_size);
++k;
}
}
void print_keys(GR2_property_key* k)
{
if (!k)
return;
cout << "Types\n";
cout << "=====\n";
// This set keeps tracks of keys already printed so we don't print
// the same key more than once. This is needed because keys have
// circular references.
std::set<GR2_property_key*> printed;
print_keys(k, printed, 0);
cout << endl;
}
void print_float4(float q[4])
{
cout << '[' << q[0] << ", " << q[1] << ", " << q[2] << ", " << q[3]
<< ']';
}
template <typename T>
void print_vector(const Vector3<T>& v)
{
cout << '[' << +v.x << ", " << +v.y << ", " << +v.z << ']';
}
template <typename T>
void print_vector(const Vector4<T>& v)
{
cout << '[' << +v.x << ", " << +v.y << ", " << +v.z << ", " << +v.w
<< ']';
}
void print_art_tool_info(GR2_art_tool_info* ArtToolInfo)
{
cout << "Art Tool Info\n";
cout << "=============\n";
cout << "Name: " << ArtToolInfo->from_art_tool_name << endl;
cout << "Major Revision: " << ArtToolInfo->art_tool_major_revision
<< endl;
cout << "Minor Revision: " << ArtToolInfo->art_tool_minor_revision
<< endl;
cout << "Units per meter: " << ArtToolInfo->units_per_meter << endl;
cout << "Origin: ";
print_vector(ArtToolInfo->origin);
cout << endl;
cout << "Right Vector: ";
print_vector(ArtToolInfo->right_vector);
cout << endl;
cout << "Up Vector: ";
print_vector(ArtToolInfo->up_vector);
cout << endl;
cout << "Back Vector: ";
print_vector(ArtToolInfo->back_vector);
cout << endl;
cout << endl;
}
void print_exporter_info(GR2_exporter_info* ExporterInfo)
{
cout << "Exporter Info\n";
cout << "=============\n";
cout << "Name: " << ExporterInfo->exporter_name << endl;
cout << "Major Revision: " << ExporterInfo->exporter_major_revision
<< endl;
cout << "Minor Revision: " << ExporterInfo->exporter_minor_revision
<< endl;
cout << "Customization: " << ExporterInfo->exporter_customization
<< endl;
cout << "Build Number: " << ExporterInfo->exporter_build_number
<< endl;
cout << endl;
}
void print_file_info(GR2_file_info* info)
{
cout << "File Info\n";
cout << "==========\n";
cout << "From File Name: " << info->from_file_name << endl;
cout << "Textures Count: " << info->textures_count << endl;
cout << "Materials Count: " << info->materials_count << endl;
cout << "Skeletons Count: " << info->skeletons_count << endl;
cout << "VertexDatas Count: " << info->vertex_datas_count << endl;
cout << "TriTopologies Count: " << info->tri_topologies_count << endl;
cout << "Meshes Count: " << info->meshes_count << endl;
cout << "Models Count: " << info->models_count << endl;
cout << "TrackGroups Count: " << info->track_groups_count << endl;
cout << "Animations Count: " << info->animations_count << endl;
cout << endl;
}
void print_indent(int num_spaces)
{
while (num_spaces > 0) {
cout << ' ';
--num_spaces;
}
}
void print_transform(GR2_transform& Transform, const char* label,
int indent = 0)
{
print_indent(indent);
cout << label << ":\n";
print_indent(indent);
cout << " Flags: " << Transform.flags << endl;
print_indent(indent);
cout << " Translation: ";
print_vector(Transform.translation);
cout << endl;
print_indent(indent);
cout << " Rotation: ";
print_vector(Transform.rotation);
cout << endl;
print_indent(indent);
cout << " ScaleShear: [" << Transform.scale_shear[0] << ", "
<< Transform.scale_shear[3] << ", " << Transform.scale_shear[6]
<< endl;
print_indent(indent);
cout << " " << Transform.scale_shear[1] << ", "
<< Transform.scale_shear[4] << ", " << Transform.scale_shear[7]
<< endl;
print_indent(indent);
cout << " " << Transform.scale_shear[2] << ", "
<< Transform.scale_shear[5] << ", " << Transform.scale_shear[8]
<< ']' << endl;
}
void print_extended_data_value(GR2_extended_data& extended_data, int k, int v)
{
switch (extended_data.keys[k].type) {
case GR2_type_int32:
cout << extended_data.values[v].int32;
break;
case GR2_type_real32:
cout << extended_data.values[v].real32;
break;
case GR2_type_text:
cout << extended_data.values[v].text;
break;
default:
cout << "# WARNING: Unhandled case\n";
}
}
void print_extended_data(GR2_extended_data& extended_data)
{
if (!extended_data.keys)
return;
cout << " ExtendedData:\n";
for (int k = 0, v = 0; extended_data.keys[k].type != GR2_type_none;
++k) {
cout << " " << extended_data.keys[k].name << ':';
int n = extended_data.keys[k].length;
if (n == 0)
n = 1;
while (n > 0) {
cout << ' ';
print_extended_data_value(extended_data, k, v);
++v;
--n;
}
cout << endl;
}
}
void print_bone(GR2_bone& bone)
{
cout << "- Name: " << bone.name << endl;
cout << " ParentIndex: " << bone.parent_index << endl;
print_transform(bone.transform, "Transform", 2);
cout << " InverseWorldTransform: [";
for (int i = 0; i < 16; ++i) {
cout << bone.inverse_world_transform[i];
if ((i + 1)%4 == 0) {
if (i == 15)
cout << "]\n";
else
cout << "\n ";
}
else {
cout << ", ";
}
}
print_extended_data(bone.extended_data);
}
void print_bones(GR2_skeleton* skel)
{
for (int i = 0; i < skel->bones_count; ++i) {
cout << "# " << i << endl;
print_bone(skel->bones[i]);
}
}
void print_skeleton(GR2_skeleton* skel)
{
cout << "Skeleton\n";
cout << "========\n";
cout << "Name: " << skel->name << endl;
cout << "Bones Count: " << skel->bones_count << endl;
print_bones(skel);
cout << endl;
}
void print_skeletons(GR2_file_info* info)
{
for (int i = 0; i < info->skeletons_count; ++i)
print_skeleton(info->skeletons[i]);
}
void print_model(GR2_model* model)
{
cout << "Model\n";
cout << "=====\n";
cout << "Name: " << model->name << endl;
cout << "Skeleton: ";
if (model->skeleton)
cout << model->skeleton->name << endl;
else
cout << "NULL\n";
print_transform(model->initial_placement, "Initial Placement");
cout << "Mesh Bindings Count: " << model->mesh_bindings_count << endl;
cout << endl;
}
void print_models(GR2_file_info* info)
{
for (int i = 0; i < info->models_count; ++i)
print_model(info->models[i]);
}
void print_offsets(float offsets[4])
{
cout << " Offsets: ";
print_float4(offsets);
cout << endl;
}
void print_scales(float scales[4])
{
cout << " Scales: ";
print_float4(scales);
cout << endl;
}
void print_selectors(uint16_t selectors[4])
{
cout << " Selectors: [";
for (int i = 0; i < 4; ++i) {
cout << selectors[i];
if (i < 3)
cout << ", ";
}
cout << "]\n";
}
template <typename T>
void print_knots(const T& view)
{
cout << " Knots: # " << view.knots().size() << endl;
for (unsigned i = 0; i < view.knots().size(); ++i) {
cout << " - " << +view.encoded_knots()[i] << " # "
<< view.knots()[i] << endl;
}
}
template <typename T>
void print_controls(const T& view)
{
cout << " Controls: # " << view.controls().size() << endl;
for (unsigned i = 0; i < view.controls().size(); ++i) {
cout << " - ";
print_vector(view.encoded_controls()[i]);
cout << " # ";
print_vector(view.controls()[i]);
cout << endl;
}
}
void print_curve_positions(GR2_curve_data_DaK32fC32f* data)
{
for (int i = 0; i < data->knots_count; ++i) {
float x = data->controls[i * 3 + 0];
float y = data->controls[i * 3 + 1];
float z = data->controls[i * 3 + 2];
cout << " - [" << x << ", " << y << ", " << z
<< "]\n";
}
}
void print_curve_rotations(GR2_curve_data_DaK32fC32f* data)
{
for (int i = 0; i < data->knots_count; ++i) {
float x = data->controls[i * 4 + 0];
float y = data->controls[i * 4 + 1];
float z = data->controls[i * 4 + 2];
float w = data->controls[i * 4 + 3];
cout << " - [" << x << ", " << y << ", " << z
<< ", " << w << "]\n";
}
}
void print_curve_scaleshear(GR2_curve_data_DaK32fC32f* data)
{
for (int i = 0; i < data->knots_count; ++i) {
cout << " - [";
for (int j = 0; j < 9; ++j) {
cout << data->controls[i * 9 + j];
if (j != 8)
cout << ", ";
}
cout << "]\n";
}
}
void print_curve_data(GR2_curve_data_DaK32fC32f* data)
{
cout << " Padding: " << data->padding << endl;
cout << " Knots: # " << data->knots_count << endl;
for (int i = 0; i < data->knots_count; ++i)
cout << " - " << data->knots[i] << endl;
cout << " Controls: # " << data->controls_count << endl;
if (data->knots_count * 3 == data->controls_count)
print_curve_positions(data);
else if (data->knots_count * 4 == data->controls_count)
print_curve_rotations(data);
else if (data->knots_count * 9 == data->controls_count)
print_curve_scaleshear(data);
else
cout << "# WARNING: Unhandled case\n";
}
void print_curve_data(GR2_curve_data_DaConstant32f* data)
{
cout << " Controls: #" << data->controls_count << endl;
for (int i = 0; i < data->controls_count; ++i)
cout << " - " << data->controls[i] << endl;
}
void print_curve_data(GR2_curve_data_DaK16uC16u* data)
{
cout << " OneOverKnotScaleTrunc: " << data->one_over_knot_scale_trunc << endl;
cout << " ControlScaleOffsets: # " << data->control_scale_offsets_count << endl;
for (int i = 0; i < data->control_scale_offsets_count; ++i)
cout << " - " << data->control_scale_offsets[i] << endl;
GR2_DaK16uC16u_view view(*data);
print_knots(view);
cout << " Controls: # " << view.controls().size() << endl;
for (unsigned i = 0; i < view.controls().size(); ++i)
cout << " - " << view.encoded_controls()[i] << " # " << view.controls()[i] << endl;
}
void print_curve_data(GR2_curve_data_D4nK16uC15u* data)
{
cout << " ScaleOffsetTableEntries: "
<< data->scale_offset_table_entries << endl;
GR2_D4nK16uC15u_view view(*data);
print_selectors(view.selectors);
print_scales(view.scales);
print_offsets(view.offsets);
cout << " OneOverKnotScale: " << data->one_over_knot_scale << endl;
cout << " KnotsControls_count: " << data->knots_controls_count
<< endl;
print_knots(view);
print_controls(view);
}
void print_curve_data(GR2_curve_data_D4nK8uC7u* data)
{
cout << " ScaleOffsetTableEntries: "
<< data->scale_offset_table_entries << endl;
GR2_D4nK8uC7u_view view(*data);
print_selectors(view.selectors);
print_scales(view.scales);
print_offsets(view.offsets);
cout << " OneOverKnotScale: " << data->one_over_knot_scale << endl;
cout << " KnotsControls_count: " << data->knots_controls_count
<< endl;
print_knots(view);
print_controls(view);
}
void print_curve_data(GR2_curve_data_D3K16uC16u* data)
{
cout << " OneOverKnotScaleTrunc: " << data->one_over_knot_scale_trunc
<< endl;
cout << " ControlScales: [" << data->control_scales[0] << ", "
<< data->control_scales[1] << ", " << data->control_scales[2]
<< "]\n";
cout << " ControlOffsets: [" << data->control_offsets[0] << ", "
<< data->control_offsets[1] << ", " << data->control_offsets[2]
<< "]\n";
cout << " KnotsControls_count: " << data->knots_controls_count
<< endl;
GR2_D3K16uC16u_view view(*data);
print_knots(view);
print_controls(view);
}
void print_curve_data(GR2_curve_data_D3K8uC8u* data)
{
cout << " OneOverKnotScaleTrunc: " << data->one_over_knot_scale_trunc
<< endl;
cout << " ControlScales: [" << data->control_scales[0] << ", "
<< data->control_scales[1] << ", " << data->control_scales[2]
<< "]\n";
cout << " ControlOffsets: [" << data->control_offsets[0] << ", "
<< data->control_offsets[1] << ", " << data->control_offsets[2]
<< "]\n";
cout << " KnotsControls_count: " << data->knots_controls_count
<< endl;
GR2_D3K8uC8u_view view(*data);
print_knots(view);
print_controls(view);
}
void print_curve_data(GR2_curve_data_DaKeyframes32f* data)
{
cout << " Dimension: " << data->dimension << endl;
cout << " Controls: # " << data->controls_count << endl;
if (data->dimension == 3) {
for (int i = 0; i < data->controls_count/3; ++i) {
float x = data->controls[i * 3 + 0];
float y = data->controls[i * 3 + 1];
float z = data->controls[i * 3 + 2];
cout << " - [" << x << ", " << y << ", " << z
<< "]\n";
}
}
else if (data->dimension == 4) {
for (int i = 0; i < data->controls_count/4; ++i) {
float x = data->controls[i * 4 + 0];
float y = data->controls[i * 4 + 1];
float z = data->controls[i * 4 + 2];
float w = data->controls[i * 4 + 3];
cout << " - [" << x << ", " << y << ", " << z
<< ", " << w << "]\n";
}
}
else if (data->dimension == 9) {
for (int i = 0; i < data->controls_count/9; ++i) {
cout << " - [";
for (int j = 0; j < 9; ++j) {
cout << data->controls[i * 9 + j];
if (j != 8)
cout << ", ";
}
cout << "]\n";
}
}
else {
cout << "# WARNING: Unhandled case\n";
}
}
void print_curve(GR2_curve& curve)
{
cout << " Format: " << +curve.curve_data->curve_data_header.format;
cout << " ("
<< curve_format_to_str(curve.curve_data->curve_data_header.format)
<< ")\n";
cout << " Degree: " << +curve.curve_data->curve_data_header.degree
<< endl;
if (curve.curve_data->curve_data_header.format == DaK32fC32f) {
GR2_curve_data_DaK32fC32f* data =
(GR2_curve_data_DaK32fC32f*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == DaIdentity) {
GR2_curve_data_DaIdentity* data =
(GR2_curve_data_DaIdentity*)curve.curve_data.get();
cout << " Dimension: " << data->dimension << endl;
}
else if (curve.curve_data->curve_data_header.format == DaConstant32f) {
GR2_curve_data_DaConstant32f* data =
(GR2_curve_data_DaConstant32f*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == DaK16uC16u) {
GR2_curve_data_DaK16uC16u* data =
(GR2_curve_data_DaK16uC16u*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == D3Constant32f) {
GR2_curve_data_D3Constant32f* data =
(GR2_curve_data_D3Constant32f*)curve.curve_data.get();
cout << " Padding: " << data->padding << endl;
cout << " Controls: [" << data->controls[0] << ", "
<< data->controls[1] << ", " << data->controls[2] << "]\n";
}
else if (curve.curve_data->curve_data_header.format == D4Constant32f) {
GR2_curve_data_D4Constant32f* data =
(GR2_curve_data_D4Constant32f*)curve.curve_data.get();
cout << " Padding: " << data->padding << endl;
cout << " Controls: [" << data->controls[0] << ", "
<< data->controls[1] << ", " << data->controls[2] << ", "
<< data->controls[3] << "]\n";
}
else if (curve.curve_data->curve_data_header.format == D4nK16uC15u) {
GR2_curve_data_D4nK16uC15u* data =
(GR2_curve_data_D4nK16uC15u*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == D4nK8uC7u) {
GR2_curve_data_D4nK8uC7u* data =
(GR2_curve_data_D4nK8uC7u*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == D3K16uC16u) {
GR2_curve_data_D3K16uC16u* data =
(GR2_curve_data_D3K16uC16u*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == D3K8uC8u) {
GR2_curve_data_D3K8uC8u* data =
(GR2_curve_data_D3K8uC8u*)curve.curve_data.get();
print_curve_data(data);
}
else if (curve.curve_data->curve_data_header.format == DaKeyframes32f) {
GR2_curve_data_DaKeyframes32f* data =
(GR2_curve_data_DaKeyframes32f*)curve.curve_data.get();
print_curve_data(data);
}
else {
cout << "# WARNING: Unhandled case\n";
}
}
void print_vector_tracks(GR2_track_group* track_group)
{
cout << "VectorTracks Count: " << track_group->vector_tracks_count
<< endl;
for (int32_t i = 0; i < track_group->vector_tracks_count; ++i) {
auto& vector_track = track_group->vector_tracks[i];
cout << "- Name: " << vector_track.name << endl;
cout << " Dimension: " << vector_track.dimension << endl;
// print_curve(vector_track.ValueCurve);
}
}
void print_transform_track(GR2_transform_track& tt)
{
cout << "- Name: " << tt.name << endl;
cout << " PositionCurve:\n";
print_curve(tt.position_curve);
cout << " OrientationCurve:\n";
print_curve(tt.orientation_curve);
cout << " ScaleShearCurve:\n";
print_curve(tt.scale_shear_curve);
}
void print_transform_tracks(GR2_track_group* track_group)
{
cout << "TransformTracks Count: " << track_group->transform_tracks_count
<< endl;
for (int32_t i = 0; i < track_group->transform_tracks_count; ++i)
print_transform_track(track_group->transform_tracks[i]);
}
void print_transform_LOD_errors(GR2_track_group* track_group)
{
cout << "TransformLODErrors Count: "
<< track_group->transform_LOD_errors_count << endl;
for (int32_t i = 0; i < track_group->transform_LOD_errors_count; ++i)
cout << "- " << track_group->transform_LOD_errors[i] << endl;
}
void print_trackgroup(GR2_track_group* track_group)
{
cout << "TrackGroup\n";
cout << "----------\n";
cout << "Name: " << track_group->name << endl;
print_vector_tracks(track_group);
print_transform_tracks(track_group);
print_transform_LOD_errors(track_group);
cout << "TextTracks Count: " << track_group->text_tracks_count << endl;
cout << endl;
}
void print_trackgroups(GR2_file_info* info)
{
for (int i = 0; i < info->track_groups_count; ++i) {
cout << endl;
print_trackgroup(info->track_groups[i]);
}
}
void print_animation(GR2_animation* animation)
{
cout << "Animation\n";
cout << "=========\n";
cout << "Name: " << animation->name << endl;
cout << "Duration: " << animation->duration << endl;
cout << "Time Step: " << animation->time_step << endl;
cout << "Oversampling: " << animation->oversampling << endl;
cout << "TrackGroups: " << animation->track_groups_count << endl;
cout << endl;
for (int32_t i = 0; i < animation->track_groups_count; ++i)
print_trackgroup(animation->track_groups[i]);
cout << endl;
}
void print_animations(GR2_file_info* info)
{
for (int i = 0; i < info->animations_count; ++i)
print_animation(info->animations[i]);
}
void print_header(GR2_file& gr2)
{
cout << "Header\n";
cout << "======\n";
cout << "Magic: ";
for (int i = 0; i < 4; ++i)
cout << ' ' << hex << gr2.header.magic[i] << dec;
cout << endl;
cout << "Header size: " << gr2.header.size << endl;
cout << "Format: " << gr2.header.format << endl;
cout << "Reserved: " << gr2.header.reserved[0] << ' '
<< gr2.header.reserved[1] << endl;
cout << "Version: " << gr2.header.info.version << endl;
cout << "File size: " << gr2.header.info.file_size << endl;
cout << "CRC32: " << hex << gr2.header.info.crc32 << dec
<< endl;
cout << "Sections offset: " << gr2.header.info.sections_offset << endl;
cout << "Sections: " << gr2.header.info.sections_count << endl;
cout << "Type section: " << gr2.header.info.type_section << endl;
cout << "Type offset: " << gr2.header.info.type_offset << endl;
cout << "Root section: " << gr2.header.info.root_section << endl;
cout << "Root offset: " << gr2.header.info.root_offset << endl;
cout << "Tag: 0x" << hex << gr2.header.info.tag << dec
<< endl;
cout << "Extra: " << gr2.header.info.extra[0] << ' '
<< gr2.header.info.extra[1] << ' ' << gr2.header.info.extra[2]
<< ' ' << gr2.header.info.extra[3] << endl;
cout << endl;
}
void print_section(GR2_file::Section_header& section)
{
cout << "Section\n";
cout << "=======\n";
cout << "Compression: " << section.compression << endl;
cout << "Data offset: " << section.data_offset << endl;
cout << "Data size: " << section.data_size << endl;
cout << "Decompressed size: " << section.decompressed_size << endl;
cout << "Alignment: " << section.alignment << endl;
cout << "First 16 bit: " << section.first16bit << endl;
cout << "First 8 bit: " << section.first8bit << endl;
cout << "Relocations offset: " << section.relocations_offset << endl;
cout << "Relocations count: " << section.relocations_count << endl;
cout << "Marshallings offset: " << section.marshallings_offset << endl;
cout << "Marshallings count: " << section.marshallings_count << endl;
cout << endl;
}
void print_sections(GR2_file& gr2)
{
for (auto& section : gr2.section_headers)
print_section(section);
}
void print_gr2(GR2_file& gr2)
{
print_header(gr2);
print_sections(gr2);
print_file_info(gr2.file_info);
print_art_tool_info(gr2.file_info->art_tool_info);
print_exporter_info(gr2.file_info->exporter_info);
print_skeletons(gr2.file_info);
print_models(gr2.file_info);
print_animations(gr2.file_info);
}
void print_var(GR2_property_key* key, const char *name, std::map<GR2_property_key*, std::string>& visited)
{
if (visited.find(key) != visited.end())
return;
visited[key] = name;
for (auto k = key; k->type != 0; ++k)
if(k->keys)
print_var(k->keys, k->name, visited);
cout << "static GR2_property_key " << name << "_def[] = {\n";
for (auto k = key; k->type != 0; ++k) {
cout << "\t{ ";
cout << "GR2_property_type(" << k->type << "), ";
cout << '"' << k->name << "\", ";
if (k->keys)
//cout << k->name << "_def /* " << k->keys << "*/, ";
cout << visited[k->keys] << "_def, ";
else
cout << "nullptr, ";
cout << k->length << ", ";
cout << k->unknown1 << ", ";
cout << k->unknown2 << ", ";
cout << k->unknown3 << ", ";
cout << k->unknown4;
cout << " },\n";
}
cout << "\t{ GR2_type_none, 0, 0, 0, 0, 0, 0, 0}\n";
cout << "};\n\n";
}
void print_var(GR2_property_key* k)
{
std::map<GR2_property_key*, std::string> visited;
print_var(k, "gr2_type", visited);
}
int main(int argc, char* argv[])
{
if (argc < 2) {
cout << "Usage: dumpgr2 <file>\n";
return 1;
}
GR2_file::granny2dll_filename = "C:\\GOG Games\\Neverwinter Nights 2 Complete\\granny2.dll";
GR2_file gr2(argv[1]);
if (!gr2) {
cout << gr2.error_string() << endl;
return 1;
}
print_gr2(gr2);
return 0;
}
| true |
079b313e4339c4996360e5d96fb7738a8c362f00 | C++ | MiroBeno/Volume-Rendering | /VolumeRendering/ViewBase.h | UTF-8 | 2,017 | 2.515625 | 3 | [] | no_license | /****************************************/
// Projection and camera manager
/****************************************/
#ifndef _VIEW_H_
#define _VIEW_H_
#include "common.h"
//#define INT_WIN_WIDTH 800
//#define INT_WIN_HEIGHT 680
#define INT_WIN_WIDTH 799
#define INT_WIN_HEIGHT 715
struct View { // parameters for projection
ushort2 dims;
float3 origin;
float3 direction;
float3 right_plane;
float3 up_plane;
float3 light_pos;
bool perspective;
inline __host__ __device__ void get_ray(short2 pos, float3 *origin_vector, float3 *direction_vector) {
if (perspective) {
*origin_vector = origin;
*direction_vector = direction + (right_plane * (float) (pos.x - dims.x / 2));
*direction_vector = *direction_vector + (up_plane * (float) (pos.y - dims.y / 2));
//*direction_vector = vector_normalize(*direction_vector);
}
else {
*direction_vector = direction;
*origin_vector = origin + (right_plane * (float) (pos.x - dims.x / 2));
*origin_vector = *origin_vector + (up_plane * (float) (pos.y - dims.y / 2));
}
}
};
class ViewBase {
public:
static View view;
static float cam_matrix[16];
static float light_matrix[16];
static void update_view();
static void camera_rotate(float3 angles, bool reset = false);
static void camera_rotate(int3 pixels);
static void camera_rotate(int2 pixels);
static void camera_zoom(float distance);
static void camera_zoom(int pixels);
static void set_camera_position(float3 angles, float distance = 3.0f);
static void light_rotate(int2 pixels);
static void toggle_perspective(int update_mode);
static void set_viewport_dims(ushort2 dims, float scale = 1.0f);
private:
static void matrix_rotate(float matrix[], float3 angles, bool reset);
static float3 vector_rotate(float4 v, float rot_matrix[16]);
static const float2 distance_limits;
static float4 cam_pos;
static float4 light_pos;
static float pixel_ratio_rotation;
static float pixel_ratio_translation;
static float virtual_view_size;
};
#endif
| true |
517498206f6a6abb2c7306772fc11ddc045bf9ba | C++ | civilian/competitive_programing | /_investigacion/contests/un_marzo/spiralPrimes.cpp | UTF-8 | 1,577 | 3.234375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
#include <map>
#include <utility>
#define EPS 1e-7
using namespace std;
typedef long long LL;
bool IsPrimeSlow (LL x)
{
if(x<=1) return false;
if(x<=3) return true;
if (!(x%2) || !(x%3)) return false;
LL s=(LL)(sqrt((double)(x))+EPS);
for(LL i=5;i<=s;i+=6)
{
if (!(x%i) || !(x%(i+2))) return false;
}
return true;
}
map<pair<int,int>, int> spiralPrimes;
void createPrimes(){
int end = 1;
bool xadd = true;
bool xsub = false;
bool yadd = false;
bool ysub = false;
int x = 0;
int y = 0;
for(int i=2; i<10000;i++){
if(IsPrimeSlow(i)){
pair<int,int> pos;
pos = make_pair(x,y);
spiralPrimes[pos] = i;
if(xadd){
x++;
if(x==end){
xadd = false;
yadd = true;
}
}else if(yadd){
y++;
if(y==end){
yadd = false;
xsub = true;
}
}else if(xsub){
x--;
if(x==(end*-1)){
xsub = false;
ysub = true;
}
}
else if(ysub){
y--;
if(y==(end*-1)){
ysub = false;
xadd = true;
end++;
}
}
}
}
}
int main(){
createPrimes();
int test = 1;
while(true){
int a,b;
cin >> a;
if(a == -999)
break;
if(a != -999 && test > 1)
cout << endl ;
cin >> b;
pair<int,int> pos;
pos = make_pair(a,b);
cout <<"Case "<<test<<": The prime at location ("
<<a<<","<<b<<") is "<<spiralPrimes[pos]<<"."<< endl;
test++;
}
return 0;
}
| true |
6a1f5acc828077a5f5baabda586c90a1e0795ee4 | C++ | ranger9/ringlight | /ringlight/functions.ino | UTF-8 | 1,350 | 2.953125 | 3 | [] | no_license |
//turn all lights off and blink
void blinkMode()
{
for(int j=0; j<mode; j++)
{
for(int i=0; i<strip.numPixels(); i++)
{
strip.setPixelColor(i,(strip.Color(0,0,0)));
strip.show();
strip.setPixelColor(i,(strip.Color(128,0,0)));
strip.show();
}
delay(100);
}
}
//expandable light at definable location
void controlLight()
{
int stripMax = strip.numPixels(); //function to get the highest allowed value
//get the ending position
int endPos = lightPos + lightWidth;
//compensate for end positions greater than number of available pixels
if (endPos > stripMax)
{
endPos = (endPos - stripMax);
}
//light pixels depending on whether they go past pixel 0 or not
if (endPos > lightPos) //case where end position does NOT exceed number of pixels
{
for(int i=lightPos; i<(lightPos + lightWidth); i++)
{
strip.setPixelColor(i,(strip.Color(R,G,B)));
}
}
else if (lightPos > endPos)
{
for (int i=lightPos; i<(stripMax); i++)
{
strip.setPixelColor(i,(strip.Color(R,G,B)));
}
for (int i=0; i<(endPos+1); i++)
{
strip.setPixelColor(i,(strip.Color(R,G,B)));
}
}
}
| true |
2be9c8095700e2c99bad18a3869552ed6f056046 | C++ | UGEL4/LearnOpenGL | /LearnOpenGL/Src/Texture.cpp | WINDOWS-1252 | 2,046 | 2.8125 | 3 | [] | no_license | #include "Texture.h"
#include "stb_image.h"
#include "gl_inf.h"
Texture::Texture(const std::string& path, const char* texType, bool flipUV)
:m_RendererID(0)
,m_Width(0), m_Height(0), m_Channles(0)
,m_TextureBuffer(nullptr)
{
unsigned int len = std::strlen(texType);
m_TexType = new char[len + 1];
strcpy_s(m_TexType, len + 1, texType);
GLCALL(glGenTextures(1, &m_RendererID));
GLCALL(glBindTexture(GL_TEXTURE_2D, m_RendererID));
GLCALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
//GLCALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
//GLCALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);//GL_CLAMP_TO_EDGE
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_set_flip_vertically_on_load(flipUV);
m_TextureBuffer = stbi_load(path.c_str(), &m_Width, &m_Height, &m_Channles, 0);
if (m_TextureBuffer)
{
GLenum format;
if (m_Channles == 1)
format = GL_RED;
else if (m_Channles == 3)
format = GL_RGB;
else if (m_Channles == 4)
format = GL_RGBA;
GLCALL(glTexImage2D(GL_TEXTURE_2D, 0, format, m_Width, m_Height, 0, format, GL_UNSIGNED_BYTE, m_TextureBuffer));
GLCALL(glGenerateMipmap(GL_TEXTURE_2D));
GLCALL(glBindTexture(GL_TEXTURE_2D, 0));
stbi_image_free(m_TextureBuffer);
}
else
{
std::cout << "load image failed" << '\n';
stbi_image_free(m_TextureBuffer);
}
}
Texture::~Texture()
{
std::cout << "des" << std::endl;
GLCALL(glDeleteTextures(1, &m_RendererID));
delete m_TexType;
}
void Texture::Bind(unsigned int slot /*= 0*/)
{
GLCALL(glActiveTexture(GL_TEXTURE0 + slot));
GLCALL(glBindTexture(GL_TEXTURE_2D, m_RendererID));
}
void Texture::Unbind()
{
GLCALL(glBindTexture(GL_TEXTURE_2D, 0));
}
| true |
f5bc3fb369493624019087399a36d367245bd93e | C++ | VegLeMeccano/EUROBOT-2017 | /PICKY_PI/Distributeur.h | UTF-8 | 683 | 2.890625 | 3 | [] | no_license | #ifndef DISTRIBUTEUR_H
#define DISTRIBUTEUR_H
#include <iostream>
#include "Coord.h"
#include "Module.h"
#define NB_MODULE_DISTRIBUTEUR 4
using namespace std;
class Distributeur
{
public:
Distributeur();
Distributeur(Coord coord_);
Distributeur(bool polychrome_, Coord coord_);
bool is_empty();
int nb_module_available();
void remove_from_below();
Coord* get_coord();
void switchX();
void display();
protected:
private:
// contient 4 module, 1 premier en base, ... 4eme en haut
Module *module[NB_MODULE_DISTRIBUTEUR];
Coord coord;
};
#endif // DISTRIBUTEUR_H
| true |
73b0378dc8b51e4e3e6734e3653914d388cb7728 | C++ | jaggies/aed512emu | /lib/core/ram.h | UTF-8 | 1,654 | 3.265625 | 3 | [] | no_license | /*
* ram.h
*
* Created on: Sep 10, 2018
* Author: jmiller
*/
#ifndef RAM_H_
#define RAM_H_
#include <vector>
#include <cassert>
#include <iostream>
#include "peripheral.h"
template <bool debug>
class _Ram: public Peripheral {
public:
_Ram(int start, int size, const std::string& name = "RAM")
: Peripheral(start, size, name), _storage(size, 0) {
for (size_t i = 0; i < _storage.size(); i++) {
_storage[i] = i;
}
}
virtual ~_Ram() = default;
uint8_t read(int offset) override {
assert(offset >= 0 && (size_t) offset < _storage.size());
uint8_t result = _storage[offset];
if (debug) {
std::cerr << name() << "[0x" << std::hex << start() + offset << "] read "
<< (int) result << std::endl;
}
return result;
}
void write(int offset, uint8_t value) override {
assert(offset >= 0 && (size_t) offset < _storage.size());
if (debug) {
std::cerr << name() << "[0x" << std::hex << start() + offset << "] write "
<< (int) value << std::endl;
}
_storage[offset] = value;
}
void reset() override { } // Typically RAM doesn't reset
// This bypasses the above read/write to allow host access to RAM
uint8_t& operator[](size_t index) { assert(index < _storage.size()); return _storage[index]; }
protected:
std::vector<uint8_t> _storage;
};
typedef _Ram<false> Ram;
typedef _Ram<true> RamDebug;
#endif /* RAM_H_ */
| true |
42ae8f22bb3a29947d3202c8f4c0268b3c1754a3 | C++ | sturner84/LookingGlass | /lgTestingSupport.h | WINDOWS-1250 | 34,129 | 2.90625 | 3 | [
"MIT"
] | permissive | /**
* @file CppTestingSupport.h
*
* @brief Contains classes that support testing of c++ code.
*
* The classes in this header allow input/output to be redirected and for
* the output to be more easily compared. The Tokenizer class simplifies
* converting the output into string, int, or double tokens.
*
* @attention This needs to be linked with the Boost library and the boost
* library should come after the CppTesting library (on the linker command)
* Linux/Unix: boost_regex-mt
*
* @author saturner
* @date 2013-05-25
*/
//TODO create a testing class to help and that automatically
// prepends hint: to the messages sent to cxx
#ifndef CPPTESTINGSUPPORT_H_
#define CPPTESTINGSUPPORT_H_
#include <iostream>
#include <sstream>
#include <exception>
#include <vector>
#include <boost/regex.hpp>
#include <boost/format.hpp>
using std::cout;
using std::cin;
using std::stringstream;
using std::streambuf;
using std::string;
using std::vector;
namespace cpptesting {
/**
* @class StdIORedirector CppTestingSupport.h
* @brief Redirects cin/cout to allow i/o to be captured for testing
*
* This class allows cin and/or cout to be redirected and the data to be
* programmatically supplied or examined.
*
*/
class StdIORedirector
{
private:
stringstream outputStream;
streambuf* oldOutputStream;
bool outputRedirect;
stringstream inputStream;
streambuf* oldInputStream;
bool inputRedirect;
public:
/**
* @brief Sets up the class. No redirection is done.
*/
StdIORedirector();
/**
* @brief Cleans up the class. Restores cin/cout if needed.
*/
virtual ~StdIORedirector();
/**
* @brief Replaces cout with a different output stream. This needs to
* be done before cout is used.
*/
void redirectCout();
/**
* @brief Restores cout to its original state.
*/
void restoreCout();
/**
* @brief Resets the redirected output stream so that it is empty and
* clears the status flags.
*/
void resetOutput();
/**
* @brief Gets the output from the redirected stream.
*
* @return The output sent to the stream.
*/
string getOutput() {return outputStream.str();}
/**
* @brief Gets a reference to the output stream being used in the
* redirection.
*
* @return Output stream being used.
*/
stringstream& getOutputStream() {return outputStream;}
/**
* @brief Replaces cin with a different input stream. This needs to
* be done before cin is used.
*/
void redirectCin();
/**
* @brief Restores cin to its original state.
*/
void restoreCin();
/**
* @brief Puts the string data into the redirected input stream. Any
* data in the string is removed.
*
* @param data New input for the stream.
*/
void setInput(string data);
/**
* @brief Gets a reference to the input stream being used in the
* redirection.
*
* @return Input stream being used.
*/
stringstream& getInputStream() {return inputStream;}
/**
* @brief Returns true if cout was used (since it was redirected/reset).
*
* @return True if cout was used.
*/
bool wasCoutUsed();
/**
* @brief Returns true if cin was used (since it was redirected/reset).
*
* @return True if cin was used.
*/
bool wasCinUsed();
};
/**
* @class Tokenizer CppTestingSupport.h
* @brief Utility class to help tokenize strings.
*
* This class allows strings to be tokenized and it specifically supports
* strings, ints, and doubles but it will allow for tokenization with any
* regular expression.
*
* ints and doubles are can be extracted from the string either by looking at
* any numbers in the text (regardless of their relationship to other
* characters) or it can only extract separate values (i.e. surrounded by
* whitespace).
*
* For example, if you had "a5 b6 9 0", the first method would extract
* 5, 6, 9, 0 while the second (looking for separate numbers) would just
* extract 9, 0. See INT_MATCH, INT_MATCH_SEPARATE, FLOAT_MATCH,
* FLOAT_MATCH_SEPARATE for more details.
*
**/
class Tokenizer
{
public:
/**
* @brief Default tokenization for strings. Extracts anything not
* whitespace (i.e. \S).
*/
static const string MATCH;
/**
* @brief This matches integers that may be embedded in other text.
*
* This matches integers that may be embedded in other text.
* i.e. this should match "5", "6,", ":7", "a9b", etc.
* The expressions must start with with something that is not
* a ., a number, or a - sign (or the beginning of the expression)
* The value captured is simpily an optional - sign and one or more
* digits. The expression must not end with a decimal followed by
* a number. It can end with a decimal followed by something not
* a number (i.e. a period at the end of a sentence).
*/
static const string INT_MATCH;
/**
* @brief Regular expression for matching ints with printf like
* parameters for adding the set of characters before and after the
* int.
*
* Regular expression for matching ints with printf like
* parameters for adding the set of characters before and after the
* int. This is used with NUM_PREFIX and NUM_POSTFIX to create
* INT_MATCH_SEPARATE and it can be used in the createMatchString
* method to generate a regular expression with different
* pre/postfixes.
*
*/
static const string INT_MATCH_SEPARATE_BASE;
/**
* @brief Regular expression for matching ints that are considered
* separate tokens. This relies on NUM_PREFIX and NUM_POSTFIX and
* INT_MATCH_SEPARATE_BASE to determine what constitutes a separate
* token.
*
*/
static const string INT_MATCH_SEPARATE;
/**
* @brief This matches doubles that may be embedded in other text.
*
* This matches doubles that may be embedded in other text.
* i.e. this should match "5.5", "6,", ":7.3", "a9.74b", etc.
* The expressions must start with with something that is not
* a ., a number, or a - sign (or the beginning of the expression)
* The value captured is an optional - sign and one or more
* digits and a decimal point.
*/
static const string FLOAT_MATCH;
/**
* @brief Regular expression for matching double with printf like
* parameters for adding the set of characters before and after the
* double.
*
* Regular expression for matching double with printf like
* parameters for adding the set of characters before and after the
* double. This is used with NUM_PREFIX and NUM_POSTFIX to create
* FLOAT_MATCH_SEPARATE and it can be used in the createMatchString
* method to generate a regular expression with different
* pre/postfixes.
*
*/
static const string FLOAT_MATCH_SEPARATE_BASE;
/**
* @brief Regular expression for matching doubles that are considered
* separate tokens. This relies on NUM_PREFIX and NUM_POSTFIX and
* FLOAT_MATCH_SEPARATE_BASE to determine what constitutes a separate
* token.
*
*/
static const string FLOAT_MATCH_SEPARATE;
/**
* @brief This specifies the symbols allowed to come before a number
* if looking for a separate token.
*
* This specifies the symbols allowed to come before a number
* if looking for a separate token. By default, the allows characters
* are:
* whitespace i.e. " 5"
* beginning of the line i.e. "5"
* $ i.e. "$5"
* # i.e. "#5"
* + i.e. "+5"
* ( i.e. "(5"
* * i.e. "*5"
* : i.e. ":5"
* ; i.e. ";5"
* / i.e. "/5"
* , i.e. ",5"
* \ i.e. "\5"
* [ i.e. "[5"
* { i.e. "{5"
*/
static const string NUM_PREFIX;
/**
* @brief This specifies the symbols allowed to come after a number
* if looking for a separate token.
*
* This specifies the symbols allowed to come after a number
* if looking for a separate token. By default, the allows characters
* are:
* whitespace i.e. "5 "
* end of the line i.e. "5"
* a period i.e. "5." or "5. "
* ! i.e. "5!"
* ? i.e. "5?"
* % i.e. "5%"
* # i.e. "5#"
* / i.e. "5/"
* + i.e. "5+"
* * i.e. "5*"
* ) i.e. "5)"
* : i.e. "5:"
* ; i.e. "5;"
* , i.e. "5,"
* - i.e. "5-"
* \ i.e. "5\"
* } i.e. "5}"
* ] i.e. "5]"
*/
static const string NUM_POSTFIX;
/**
* @brief Tokenizes the string and stores it in a vector
*
* This method tokenizes the string and tries to convert the data
* into the appropriate type. If successful, it is stored in the vector.
*
* @attention This method requires that the >> and << operators be
* defined on the data type.
*
* @attention The tokenizer pulls out the 1st captured group from the
* regular expression. If more than one group is used, make sure that
* they are marked as uncaptured (i.e. ?:)
*
* @param data String to tokenize
* @param matches Vector to store the data
* @param pattern Pattern used to tokenize the data. This should match
* the intended tokens and not describe where the string is split.
* (i.e. \s would return a vector of whitespace and not the values
* delimited by the whitespace).
* The default value is to tokenize it into strings
*
* @return A vector with the tokens. This is a reference to matches.
*
*/
template <class T> static vector<T>& tokenize(string data,
vector<T> &matches, string pattern = MATCH);
/**
* @brief Tokenizes the string and stores it in a vector
*
* Specialization for strings
*
*
* @attention The tokenizer pulls out the 1st captured group from the
* regular expression. If more than one group is used, make sure that
* they are marked as uncaptured (i.e. ?:)
*
* @param data String to tokenize
* @param matches Vector to store the data
* @param pattern Pattern used to tokenize the data. This should match
* the intended tokens and not describe where the string is split.
* (i.e. \s would return a vector of whitespace and not the values
* delimited by the whitespace).
* The default value is to tokenize it into strings
*
* @return A vector with the tokens. This is a reference to matches.
*
*/
static vector<string>& tokenize(string data,
vector<string> &matches, string pattern);
/**
* @brief Creates a regular expression using the prefix, postfix, and
* the base.
*
* Creates a regular expression using the prefix, postfix, and
* the base. This assumes that base has two printf-like parameters in it
* that except string values.
*
* This is a convient way to use INT_MATCH_SEPARATE_BASE and
* FLOAT_MATCH_SEPARATE_BASE with different prefixes and/or postfixes.
*
* @param pre Set of valid characters that can proceed the token. This
* should be written as a regular expression and should use uncaptured
* groups.
* @param base Regular expression that matches the tokens to be found.
* This should have two printf-like parameters (%s) for the prefix and
* postfix. There should only be one capturing group in this
* expression.
* @param post Set of valid characters that can follow the token. This
* should be written as a regular expression and should use uncaptured
* groups.
*
* @return A string with the regular expression contains the prefix,
* postfix, and base.
*
*/
static string createMatchString(string pre, string base,
string post);
/**
* @brief Finds a double value in the data that is within delta of
* value.
*
* Convenience method that finds a double value in the data that
* is within delta of value.
*
* @param data String to tokenize
* @param value Value to find
* @param delta Distance from value allowed.
* @param pattern Regular expression to tokenize the data. By default,
* it is FLOAT_MATCH (any number regardless of surrounding text).
*
* @return true if the value is found
*
*/
static bool findInTokens(string data, double value, double delta,
string pattern = FLOAT_MATCH);
/**
* @brief Finds a double value in the dValues that is within delta of
* value.
*
* Convenience method that finds a double value in the data that
* is within delta of value.
*
* @param dValues List of tokens
* @param value Value to find
* @param delta Distance from value allowed.
*
* @return true if the value is found
*
*/
static bool findInTokens(vector<double> dValues, double value,
double delta);
/**
* @brief Finds an int value in the data.
*
* Convenience method that finds an int value in the data.
*
* @param data String to tokenize
* @param value Value to find
* @param pattern Regular expression to tokenize the data. By default,
* it is INT_MATCH (any int regardless of surrounding text).
*
* @return true if the value is found
*
*/
static bool findInTokens(string data, int value,
string pattern = INT_MATCH);
/**
* @brief Finds an int value in the data.
*
* Convenience method that finds an int value in the data.
*
* @param iValues list of tokens
* @param value Value to find
*
* @return true if the value is found
*
*/
static bool findInTokens(vector<int> iValues, int value);
/**
* @brief Finds a string value in the data.
*
* Convenience method that finds a string value in the data.
*
* @param data String to tokenize
* @param value Value to find
* @param ignoreCase True if case should be ignored. By default, this
* is true.
* @param partial Truie is the value to be found can match just part of
* a token (i.e. "a" would match "ab"). By default, this is false.
* @param pattern Regular expression to tokenize the data. By default,
* it is MATCH (any text).
*
* @return true if the value is found
*
*/
static bool findInTokens(string data, string value,
bool ignoreCase = true, bool partial = false,
string pattern = MATCH);
/**
* @brief Finds a string value in the data.
*
* Convenience method that finds a string value in the data.
*
* @param sValues List of tokens
* @param value Value to find
* @param ignoreCase True if case should be ignored. By default, this
* is true.
* @param partial Truie is the value to be found can match just part of
* a token (i.e. "a" would match "ab"). By default, this is false.
*
* @return true if the value is found
*
*/
static bool findInTokens(vector<string> sValues, string value,
bool ignoreCase = true, bool partial = false);
};
template <class T> vector<T>& Tokenizer::tokenize(string data,
vector<T> &matches, string pattern)
{
boost::regex matcher;
matcher.assign(pattern, boost::regex_constants::icase);
boost::sregex_token_iterator i(data.begin(), data.end(), matcher, 1);
boost::sregex_token_iterator j;
while(i != j)
{
stringstream value;
T cValue;
value << *i++;
value >> cValue;
if (!value.fail())
{
matches.push_back(cValue);
}
//*i++;
}
return matches;
}
/**
* @class StringUtil CppTestingSupport.h
* @brief Support class with some common string utility methods.
*
* This class contains a few common string utility methods to help manipulate
* text data. It can trim whitespace, change case, and removed a set of
* characters from the string.
*
**/
class StringUtil
{
public:
// --------------------------------------------------------------
/**
* @brief Removes the whitespace to the left of (before) the string.
*
* Removes the whitespace to the left of (before) the string.
*
* @param s String to be trimmed.
*
* @return Trimmed string.
*
*/
static inline std::string ltrim(std::string s)
{
size_t i;
for (i = 0; i < s.length() && std::isspace((int) s[i]); i++)
{
//nothing
}
s.erase(0,i);
return s;
}
// --------------------------------------------------------------
/**
* @brief Removes the whitespace to the right of (after) the string.
*
* Removes the whitespace to the right of (after) the string.
*
* @param s String to be trimmed. This parameter is modified.
*
* @return Trimmed string. This returns a reference to s.
*
*/
static inline std::string rtrim(std::string s)
{
size_t i;
//i will wrap around to npos
for (i = s.length() - 1; i != string::npos && std::isspace((int) s[i]); i--)
{
//nothing
}
if (i < s.length())
{
s.erase(i+1,s.length()-i);
}
return s;
}
// --------------------------------------------------------------
/**
* @brief Removes the whitespace to before and after the string.
*
* Removes the whitespace to the before and after the string.
*
* @param s String to be trimmed. This parameter is modified.
*
* @return Trimmed string. This returns a reference to s.
*
*/
static inline std::string trim(std::string s)
{
return ltrim(rtrim(s));
}
/**
* @brief Converts the string to upper case.
*
* Converts the string to upper case.
*
* @param str String to convert. This parameter is modified.
*
* @return String in all capital letters. This returns a reference to
* str.
*
*/
static string toUpper(std::string str);
/**
* @brief Converts the string to lower case.
*
* Converts the string to lower case.
*
* @param str String to convert. This parameter is modified.
*
* @return String in all lower case letters. This returns a reference
* to str.
*
*/
static string toLower(std::string str);
/**
* @brief Replaces a set of characters in the string with another char.
*
* Replaces a set of characters in the string with another char.
* If a character in str matches any of the characters in
* removeChars, it is replaced with replacement.
*
* @param str String to modify. This parameter is modified.
* @param removeChars Set of characters to remove.
* @param replacement Character to replace the removed characters.
*
* @return String with the characters replaced.
* This returns a reference to str.
*
*/
static string replaceChars(std::string str, std::string removeChars,
char replacement);
};
/**
* @class DiffStrings CppTestingSupport.h
* @brief Visually compares two string
*
* This class compares two strings and visually shows the differences
* between them. That is, it finds the common prefix and postfix (if
* any) and then displays the difference in []. So, comparing "abc" and
* "adc" would yield "a[b]c" and "a[d]c" for getAString, getBString
* respectively.
*
* If the pre/postfix is too long, it is shortened and an ellipsis (...)
* is added.
*
* Borrowed liberally from junit.org's org.junit.ComparisonFailure class.
* https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/ComparisonFailure.java
*
*/
class DiffStrings
{
private:
string aStr;
string bStr;
static const string ELLIPSIS;
static const string DIFF_START;
static const string DIFF_END;
void compareStrings(size_t maxSize);
size_t getPrefix();
size_t getPostfix(string a, string b);
string getDiffString(const string& str, size_t pre, size_t post,
size_t maxSize);
string addEllipsis(const string& str, size_t maxSize,
bool atBegin);
public:
/**
* @brief The maximum number of characters (minus the elipse) to show
* in the prefix/postfix when comparing two strings with compareStrings
*/
static const size_t MAX_CONTEXT_LEN;
/**
* @brief Visually displays the differences between two strings.
*
* This class compares two strings and visually shows the differences
* between them. That is, it finds the common prefix and postfix (if
* any) and then displays the difference in []. So, comparing "abc" and
* "adc" would yield "a[b]c" and "a[d]c" for getAString, getBString
* respectively.
*
* If the pre/postfix is too long, it is shortened and an ellipsis (...)
* is added.
*
* @param a The first string to compare.
* @param b The second string to compare.
* @param maxSize The maximum number of characters to show in the pre/postfix
* before adding an ellipsis. This defaults to 20.
*
*/
DiffStrings(string a, string b, size_t maxSize = MAX_CONTEXT_LEN);
/**
* @brief Determines if the strings passed to the constructor are equal.
*
* @return true if the strings are equal
*/
bool areEqual() const {return aStr == bStr;}
/**
* @brief Gets the value of the first string passed into the
* constructor with the differences shown. If the strings were the
* same, this returns a copy of the original string.
*
* @return The first string modified to show the differences.
*/
const string& getAString() const {return aStr;}
/**
* @brief Gets the value of the second string passed into the
* constructor with the differences shown. If the strings were the
* same, this returns a copy of the original string.
*
* @return The second string modified to show the differences.
*/
const string& getBString() const {return bStr;}
};
/**
* @class CompareOutput CppTestingSupport.h
* @brief Utility class to compare the tokens in two strings.
*
* This class compare the tokens in two strings and provides a little more
* information about how they are different. This can be used to find the
* first mismatched token.
*
*/
class CompareOutput
{
private:
size_t location;
int comparedSize;
bool success;
string lastExpectedToken;
string lastResultToken;
public:
/**
* @brief Compares expected and result by their tokens.
*
* Compares expected and result by their tokens. By default, it
* tokenizes all non-whitespace.
*
* The first mismatching token is marked and if there is a difference
* in the number of tokens, it is noted as well.
*
* @param expected The expected tokens
* @param result The actual tokens
* @param pattern The regular expression used to tokenize the data
*/
CompareOutput(string expected, string result,
string pattern = Tokenizer::MATCH);
/**
* @brief Determines if the number of tokens were equal.
*
* @return true if the number of tokens were equal.
*/
bool areEqualLength() {return comparedSize == 0;};
/**
* @brief Determines if there were more tokens in the expected value.
*
* @return true if there were more tokens in the expected value.
*/
bool isExpectedLonger() {return comparedSize == -1;};
/**
* @brief Determines if there were more tokens in the actual value.
*
* @return true if there were more tokens in the actual value.
*/
bool isResultLonger() {return comparedSize == 1;};
/**
* @brief Determines if the expected and actual were the same.
*
* @return true if they were the same.
*/
bool wasSuccessful() {return success;};
/**
* @brief Gets the last compared token in the expected value.
*
* Gets the last compared token in the expected value. If there is a
* mismatch, this is the token that did not match. If expected was
* longer than the actual, this is the first token not in the actual
* data. If the result was longer, this is "".
*
* @return The last compared token in the expected value.
*/
string getLastExpectedToken() {return lastExpectedToken;};
/**
* @brief Gets the last compared token in the result value.
*
* Gets the last compared token in the result value. If there is a
* mismatch, this is the token that did not match. If expected was
* longer than the actual, this is "". If the result was longer,
* this is first token not in the actual data.
*
* @return The last compared token in the result value.
*/
string getLastResultToken() {return lastResultToken;};
/**
* @brief Gets the location (of the token) of the first mismatch.
*
* @return The location (of the token) of the first mismatch.
*/
size_t getLocationOfMismatch() {return location;};
/**
* @brief Gets the result of the comparison as a standard message. This
* could be used as feedback in a test.
*
* Gets the result of the comparison as a standard message. This
* could be used as feedback in a test. This specifies the error and
* the location of the error.
*
* @return The result of the comparison as a message.
*/
string getStdMessage();
};
// -------------------------------------------------------------------------
/**
* @class StringDistance CppTestingSupport.h
* @brief Gets the DamerauLevenshtein distance between two strings.
*
* @author Schnook
* @version Oct 2, 2012
*/
class StringDistance {
private:
int* distanceTable;
std::map<char, int> letters;
int size;
static const int INIT_SIZE;
static StringDistance strDistance;
StringDistance();
void updateData(int length);
void initializeTable(int lenght1, int length2);
void initializeMap(std::string str1, std::string str2);
int computeDistance(std::string str1, std::string str2);
public:
~StringDistance();
// ----------------------------------------------------------
/**
* Gets the DamerauLevenshtein distance between two strings.
*
* The algorithm was taken from:
* http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
*
* @param str1 First string to compare
* @param str2 Second string to compare
*
* @return The number of edits needed to convert str1 to str2
*/
static size_t getDistance(std::string str1, std::string str2);
/**
* @brief Finds the n closest matches to str in values.
*
* Finds the n closest matches to str in values. The strings are ordered in
* the vector by closeness with the closest at the front. The method tries
* to return n values. If there are less than n strings in values, then
* all of them are returned. If there are multiple strings in values with
* the same distance from str, more than n values may be returned (it will
* return all of the ties unless it is >= n).
*
* @param str String to compare to the others
* @param values Set of strings to compare with
* @param n Number of matches to return
*
* @return A list of matches ordered by closeness to str
*/
static std::vector<std::string> getNClosest(std::string str,
const std::vector<std::string> & values, size_t n);
/**
* @brief Finds the n closest matches to str in values. The string
* returned has the comparisions between str and the other matches.
*
* Finds the n closest matches to str in values. The strings are ordered in
* the vector by closeness with the closest at the front. The method tries
* to return n values. If there are less than n strings in values, then
* all of them are returned. If there are multiple strings in values with
* the same distance from str, more than n values may be returned (it will
* return all of the ties unless it is >= n).
*
* This differs from getNClosest by returning the matches in the form
* of a string with comparisons between str and the other matches. So,
* if str = "abc" and values = {"abd", "lmc", "abcde"}, it will return
* as string in the form:
* Expected: ab[c] Found: ab[d]
* Expected: ab[c] Found: [lm]c
* Expected: abc[] Found: abc[de]
*
* @param str String to compare to the others
* @param values Set of strings to compare with
* @param n Number of matches to return
*
* @return A string with the comparisons between str and the other
* matches.
*/
static std::string getNClosestAsString(std::string str,
const std::vector<std::string> & values, size_t n);
};
}
#endif /* CPPTESTINGSUPPORT_H_ */
| true |
749f7f7307b08157b06a446c3ad8d8540dade7e6 | C++ | ardayildirim/LeetCode | /November LeetCoding Challenge/2.week/1-Binary_Tree_Tilt.cpp | UTF-8 | 1,048 | 3.703125 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int sum_list(TreeNode *root)
{
if(!root)
return 0;
int l = sum_list(root->left);
int r = sum_list(root->right);
return l + r + root->val;
}
public:
// O(n^2) runtime (bad for trees though)
int findTilt(TreeNode* root)
{
if(!root)
return 0;
int lsum = sum_list(root->left);
int rsum = sum_list(root->right);
if(lsum >= rsum)
{
return lsum - rsum + findTilt(root->left) + findTilt(root->right);
}
else
{
return rsum - lsum + findTilt(root->left) + findTilt(root->right);
}
}
}; | true |
9e6ea5c2fb63fe4612b1fca27f4cc4b12d64881f | C++ | kujjwal02/practice | /HackerRank/Algorithms/warmup/Time Conversion.cpp | UTF-8 | 778 | 3.421875 | 3 | [] | no_license | /*
Given a time in AM/PM format, convert it to military (-hour) time.
Note: Midnight is on a -hour clock, and on a -hour clock. Noon is on a -hour clock, and on a -hour clock.
Input Format
A single string containing a time in -hour clock format (i.e.: or ), where .
Output Format
Convert and print the given time in -hour format, where .
Sample Input
07:05:45PM
Sample Output
19:05:45
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main(){
int hh,mm,ss;
char t12[3];
scanf("%d:%d:%d%s",&hh,&mm,&ss,t12);
if (strcmp(t12,"PM")==0 && hh!=12) hh += 12 ;
if (strcmp(t12,"AM")==0 && hh==12) hh = 0 ;
printf("%02d:%02d:%02d",hh,mm,ss);
return 0;
}
| true |
08fd51ddaddc1cfb1dd803526662b22b9eb6a0ff | C++ | 010ric/ms_bfs | /graphtraversal/include/graphtraversal/ms_bfs/ms_bfs_anp.h | UTF-8 | 5,617 | 2.5625 | 3 | [] | no_license | //
// Created by 010ric on 28.11.19.
//
#ifndef GRAPHTRAVERSAL_MS_BFS_ANP_H
#define GRAPHTRAVERSAL_MS_BFS_ANP_H
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <bitset>
#include <graphtraversal/webgraph/webgraph.h>
#include <graphtraversal/bfs/bfs.h>
#include <boost/dynamic_bitset.hpp>
namespace graphtraversal {
class MS_BFS_ANP {
typedef uint64_t bitset;
private:
// graph containing all vertices and edges
graphtraversal::Webgraph webgraph;
std::double_t endresult;
uint64_t traversed_edges;
public:
/* bool isDuplicate(const std::vector<graphtraversal::BFS>& seen_bfs){
return (std::find(seen_bfs.begin(), seen_bfs.end(), bfs) != seen_bfs.end());
} */
struct find_vertex_by_value {
uint64_t v1;
find_vertex_by_value(uint64_t v2) : v1(v2) {}
bool operator () ( const graphtraversal::Vertex& check_vert) const {
return v1 == check_vert.vert_id;
}
};
bool check_bitset(std::vector<uint64_t > set_of_bitfields){
for(auto& bitfield : set_of_bitfields){
if(bitfield != 0){
return true;
}
}
return false;
}
bool check_full_bitset_vect(std::vector<uint64_t > set_of_bitfields){
bitset margin = 0;
bool all_filed = 1;
for(int i = 0; i < set_of_bitfields.size(); i++){
margin |= 1 << i;
}
for(auto& bitfield : set_of_bitfields){
if(bitfield != margin){
all_filed = 0;
}
}
return all_filed;
}
explicit MS_BFS_ANP(graphtraversal::Webgraph &webgraph, std::vector<graphtraversal::Vertex> &vert_set,
std::vector<graphtraversal::BFS > &bfs_set) : webgraph(webgraph) {
const int register_width = 64;
// Assumption vertices id start from 1
const uint64_t number_of_vertices = webgraph.vertices.size();
std::vector<bitset > seen(number_of_vertices, 0), visit(number_of_vertices, 0), visitNext(number_of_vertices, 0);
graphtraversal::Vertex vend = webgraph.getVertices().back();
for(auto& bfs : bfs_set) {
seen[bfs.getStartVertex().vert_id - 1] = -1;
visit[bfs.getStartVertex().vert_id - 1] = -1;
uint8_t dist = std::distance(bfs_set.begin(), std::find(bfs_set.begin(), bfs_set.end(), bfs));
seen[bfs.getStartVertex().vert_id - 1] &= 1ULL << dist;
visit[bfs.getStartVertex().vert_id - 1] &= 1ULL << dist;
}
double global_depth = 1;
double sum_arr[register_width] = {};
int16_t upper_margin = vend.vert_id, number_of_edges_traversed = 0;
while(check_bitset(visit) && !check_full_bitset_vect(seen)){
if(global_depth > 9){break;}
double closeness_addition = global_depth;
for(auto vect : vert_set){
int i = vect.vert_id;
if(visit[vect.vert_id - 1] == 0) {
;
}
else {
const graphtraversal::Vertex vert_found = webgraph.vertices[i - 1];
for(const auto& neighbour : webgraph.getNeighbours(vert_found.vert_id)){
visitNext[neighbour - 1] |= visit[i - 1];
number_of_edges_traversed++;
}
}
}
for(auto vect : vert_set){
int i = vect.vert_id;
if(visit[vect.vert_id - 1] == 0) {
;
}
else{
visitNext[i - 1] &= ~seen[i - 1];
seen[i - 1] |= visitNext[i - 1];
if(visitNext[i - 1] != 0){
bitset difference = visitNext[i - 1];
while(difference != 0){
if(difference & 1<<0){
sum_arr[(i % (register_width + 1)) - 1] += closeness_addition;
}
difference >>= 1;
}
}
}
}
visit = visitNext;
for(auto& bitset : visitNext){
bitset = 0;
}
global_depth++;
}
double sum_val = 0;
for(auto val : sum_arr){
if(val >= (number_of_vertices - 1)){
this->endresult += (number_of_vertices - 1) / val;
}
else {
// std::cout << " error: val calculated to low : " << val << std::endl;
}
}
// std::cout << "number of edges traversed : " << number_of_edges_traversed << std::endl;
this->traversed_edges = number_of_edges_traversed;
// this->endresult /= bfs_set.size();
// std::cout << " bfs_Set size : " << bfs_set.size() << std::endl;
}
~MS_BFS_ANP(){}
std::double_t getEndresult(){
return this->endresult;
}
std::uint64_t getTraversedEdges(){
return this->traversed_edges;
}
};
}
#endif GRAPHTRAVERSAL_MS_BFS_ANP_H | true |
91aae69c5b09a27ee7bb8a3329dcfdf43d82522a | C++ | KiillThemAll/cnc-vision | /rayreceiver.h | UTF-8 | 1,175 | 2.546875 | 3 | [] | no_license | #ifndef RAYRECEIVER_H
#define RAYRECEIVER_H
#include <QObject>
#include <QUdpSocket>
#include <QNetworkDatagram>
#include <QTimer>
#include <QThread>
typedef struct {
float mcs_x;
float mcs_y;
float mcs_z;
float mcs_b;
uint32_t state;
uint32_t played;
int32_t total;
} ray_payload_t;
class RayReceiver : public QObject
{
Q_OBJECT
Q_PROPERTY(bool connected READ connected NOTIFY connectionStateChanged)
public:
explicit RayReceiver(QObject *parent = nullptr);
enum State {
NotPlaying = 2,
Paused = 0,
Playing = 3
};
bool connected() const;
signals:
void stateChanged(State s);
void coordsChanged(float x, float y, float z, float b);
void connectionStateChanged(bool connected);
public slots:
void setLaserPower(float pwr);
void setTopExhaust(bool enabled);
void setBottomExhaust(bool enabled);
private slots:
void onReadyRead();
void onTimerTimeout();
private:
void processPayload(QNetworkDatagram datagram);
QUdpSocket *m_udp;
ray_payload_t m_payload;
QTimer m_timer;
bool m_connected;
State m_lastState;
};
#endif // RAYRECEIVER_H
| true |
411bf94a67c628da5233e509e7d9250cdc032c50 | C++ | Sayaten/StudyGameAI | /Chapter2_FSM/FiniteStateMachine/FiniteStateMachine/Global/EntityManager.h | UTF-8 | 553 | 2.734375 | 3 | [] | no_license | #pragma once
#include <map>
#include "BaseGameEntity.h"
class EntityManager
{
private:
typedef std::map<int, BaseGameEntity*> EntityMap;
private:
EntityMap m_EntityMap;
static EntityManager* instance;
EntityManager(){}
EntityManager(const EntityManager&);
EntityManager& operator=(const EntityManager&);
public:
static EntityManager* GetInstance();
void RegisterEntity(BaseGameEntity* NewEntity);
BaseGameEntity* GetEntityFromID(int id) const;
void RemoveEntity(BaseGameEntity* pEntity);
};
#define EntityMgr EntityManager::GetInstance() | true |
bddfb8290afe15302a62d73a552e58d715c9c7d3 | C++ | Floodon/analog | /bin/Association.cpp | UTF-8 | 1,580 | 2.5625 | 3 | [] | no_license | /*************************************************************************
Association - description
-------------------
debut : 14/01/2020
copyright : (C) 2020 par Enzo Boschere, Tuoyuan TAN
e-mail : $EMAIL$
*************************************************************************/
//---------- R��alisation de la classe <Association> (fichier Association.cpp) ------------
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include systeme
#include <stdio.h>
#include <cstdlib>
#include <string>
using namespace std;
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
//------------------------------------------------------ Include personnel
#include "Requete.h"
#include "Association.h"
//------------------------------------------------------------- Constantes
//----------------------------------------------------------------- PUBLIC
//----------------------------------------------------- Methodes publiques
Association::Association(){
NbrVisit = 0;
// constructeur par defaut
}//----- Fin de Methode
void Association::Ajouter(const Requete & Req){
MapReferants::iterator it;
it = Referers.find(Req.Referer);
if(it != Referers.end()){
it -> second.push_back(Req); //Ajouter une requete dans le vecteur "Requetes"
}else{
Requetes NouvellesRequetes;
NouvellesRequetes.push_back(Req);
Referers.insert(make_pair(Req.Referer,NouvellesRequetes));
}
NbrVisit++;
}
Association::~Association(){}
//----- Fin de Methode
| true |
cf35734992be2e5c51e48bcac178c1c91d7100da | C++ | Ajay2521/Tutorial-on-CPlusPlus- | /Ternary Operator.cpp | UTF-8 | 856 | 4.03125 | 4 | [] | no_license | /*In this program we will be seeing Conditional Expression which is also known as Ternary Operator avaliable in C++*/
/*conditional operator is also known as Ternary Operator it is defined as when the condition is true then first expression will excuted , if the condition fails then second expression will be excuted .*/
/*Syntax for Ternary Operator
Variable = Expression 1 ? Expression 2 : Expression 3 ;
*/
/*Note : This ternary operator is used to replace if...else statement*/
/*including preprocessor in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
int x = 10;
int y = 30;
/*In this when x is lesser than y ,then z takes the value of x, else z takes the value of y.*/
int z = ( x < y ) ? x : y ;
cout<< "\nValue of z is " << z << endl ;
} | true |
9031df28dd309ac5b3dc67b57b789f03451ddfd9 | C++ | vp7273/Electronic-Components | /Battery.h | UTF-8 | 611 | 2.859375 | 3 | [] | no_license | /*
* Battery.h
*
* Created on: Mar 16, 2018
* Author: Varika
*/
#ifndef BATTERY_H_
#define BATTERY_H_
#include "ElectronicComponent.h"
class Battery: public Electronic_Component
{
private:
double batteryValue;
public:
Battery () //default constructor
{
}
Battery(double &battery_value) //constructor with parameter defined INLINE
{
batteryValue = battery_value;
}
virtual double GetValue();
virtual const char* GetUnits();
virtual const char* GetDescription();
virtual ~Battery(); // virtual destructor
};
#endif /* BATTERY_H_ */
| true |
c163181061c351d87910587c289648bb2e5bb624 | C++ | yeahzdx/Leetcode | /双指针-Remove Duplicates fromS orted Array II.cpp | UTF-8 | 550 | 3.390625 | 3 | [] | no_license | #include"stage2.h"
/*
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
*/
int removeDuplicates(int A[], int n) {
if(NULL==A || n<=0)return 0;
if(n==1)return n;
int slow=1,fast=1;
bool flag=true;
while(fast<n){
if(A[fast]!=A[slow]){
A[slow++]=A[fast];
flag=true;
}
else if(flag){
A[slow++]=A[fast];
flag=false;
}
++fast;
}
return slow;
} | true |
502ed23e72a2560686d6774cd763f2199eecf035 | C++ | magicmoremagic/bengine-core | /src/time.cpp | UTF-8 | 1,422 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "pch.hpp"
#include "time.hpp"
namespace be {
///////////////////////////////////////////////////////////////////////////////
F64 tu_to_seconds(TU tu) noexcept {
return (F64)tu.count() / (F64)TU::period::den;
}
///////////////////////////////////////////////////////////////////////////////
TU seconds_to_tu(F64 seconds) noexcept {
return TU((U64)(seconds * TU::period::den));
}
///////////////////////////////////////////////////////////////////////////////
/// \brief Converts a microsecond-resolution unix timestamp into a
/// second-resolution time_t.
///
/// \details Remaining microseconds are rounded by truncation towards zero.
/// ie. timestamps before 1970 will be rounded forward to the next
/// closest second, while times after 1970 will be rounded back to the
/// previous second.
time_t ts_to_time_t_fast(TU ts) noexcept {
return ts.count() / TU::period::den;
}
///////////////////////////////////////////////////////////////////////////////
/// \brief Splits a microsecond-resolution unix timestamp into a
/// second-resolution time_t and the remainder of extra microseconds.
std::pair<time_t, U32> decompose_ts(TU ts) noexcept {
std::pair<time_t, U32> p { ts_to_time_t_fast(ts), 0 };
p.second = (U32)(ts.count() - (I64)p.first * TU::period::den);
if (ts.count() < 0 && p.second != 0) {
--p.first;
}
return p;
}
} // be
| true |
2607db36a3b64b3c93b9d3cbd139f877b214c188 | C++ | SeanCST/Algorithm_Problems | /JianZhi_Offer/DeleteDuplication.cpp | UTF-8 | 1,580 | 3.984375 | 4 | [] | no_license | /* 剑指 Offer - 删除链表中重复的结点
* 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
* 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
**/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == NULL || pHead->next == NULL) return pHead;
/*---------先为链表创建一个头结点---------*/
int firstNumber = pHead->val;
//假设我的头结点数值为-1
int myFirst = -1;
//万一链表的头结点也为-1,那么我就改成-2
if (myFirst == firstNumber)
{
myFirst = -2;
}
ListNode *head = new ListNode(myFirst);
head->next = pHead;
ListNode *pre = head;
ListNode *pNode = pre->next;
while(pNode != NULL) {
while(pNode->next != NULL && pNode->val == pNode->next->val) { // 遇到重复结点,pNode 前进
pNode = pNode->next;
}
if(pre->next != pNode) { // 进行删除操作
pre->next = pNode->next;
pNode = pNode->next;
} else { // 未遇到重复结点,pre 和 pNode 都前进
pre = pNode;
pNode = pNode->next;
}
}
return head->next;
}
}; | true |
2970099b27bad7f88af6b58dce75114203acb724 | C++ | drofp/MyRPS | /src/start_menu.cpp | UTF-8 | 2,024 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <boost/algorithm/string.hpp>
#include "start_menu.h"
using namespace std;
namespace myrps
{
StartMenu::StartMenu()
{
difficulty = SettingOption::kRandom;
for (int i = 0; i < num_options; i++)
{
options.push_back(options_list[i]);
}
game.SetComputerMode(difficulty);
}
void StartMenu::DisplayOptions()
{
cout << "Welcome to MyRPS! " << endl;
StartOption user_choice = GetUserChoice();
if (user_choice == StartOption::PLAY_GAME)
{
PlayGame();
}
else if (user_choice == StartOption::OPTIONS)
{
SettingOption choice = settings.DisplaySettings();
SetDifficulty(choice);
DisplayOptions();
}
}
void StartMenu::PlayGame()
{
game.PlayMatch();
}
void StartMenu::SetDifficulty(SettingOption choice)
{
difficulty = choice;
game.SetComputerMode(difficulty);
}
SettingOption StartMenu::GetCurrentDifficulty()
{
return difficulty;
}
bool StartMenu::ValidateUserChoice(string val){
return(val == "0" || val == "1" || val == "2");
}
StartOption StartMenu::ConvertUserChoice(string val)
{
StartOption user_choice;
if (stoi(val) == 0)
{
user_choice = StartOption::PLAY_GAME;
}
else if (stoi(val) == 1)
{
user_choice = StartOption::OPTIONS;
}
else if (stoi(val) == 2)
{
user_choice = StartOption::EXIT;
}
else
{
user_choice = StartOption::ERROR;
}
return user_choice;
}
StartOption StartMenu::GetUserChoice()
{
bool valid = false;
StartOption user_choice;
while (!valid)
{
string user_input;
cout << "Here are your options:" << endl;
for (unsigned int i = 0; i < options.size(); i++)
{
cout << options[i] << "(" << i << ")" << endl;
}
cout << "What would you like to do?: ";
cin >> user_input;
if(!ValidateUserChoice(user_input))
{
cout << "Please enter a valid option\n" << endl;
}
else
{
user_choice = ConvertUserChoice(user_input);
cout << endl;
valid = true;
}
}
return user_choice;
}
} // namespace myrps
| true |
93942095e6f8048743e64931013db69c941a3f54 | C++ | ji-one/algorithm-study | /baekjoon_study_wook/백트래킹/10819_dw.cpp | UTF-8 | 660 | 3.09375 | 3 | [] | no_license | //10819 차이를 최대로
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int arr[10];
int visited[10];
int answer;
void dfs(int cnt, int idx, int sum){
if(cnt == n-1){
answer = max(answer, sum);
return ;
}
for(int i=0; i<n; i++){
if(visited[i]) continue;
visited[i] = 1;
dfs(cnt+1, i, sum + abs(arr[idx] - arr[i]));
visited[i] = 0;
}
}
int main(){
cin >> n;
for(int i=0; i<n; i++){
cin >> arr[i];
}
for(int i=0;i <n; i++){
visited[i] = 1;
dfs(0,i,0);
visited[i] = 0;
}
cout << answer;
return 0;
} | true |
f66ca297f221cfac5d32e642d4e4bebebfd882eb | C++ | heX16/small_timer | /examples/mushrooms_cellar/mushrooms_cellar.ino | UTF-8 | 2,388 | 2.8125 | 3 | [] | no_license | #include <small_timer.hpp>
//////////////// Константы ////////////////
constexpr auto pinLight = 5;
constexpr auto pinVent = 6;
//constexpr auto pinLightButton = 7; //todo: добавить поддержку кнопки и таймер антидребезга
constexpr auto cEnable = 1;
constexpr auto cDisable = 0;
constexpr auto cMinute = 1000L*60;
//////////////// Таймеры ////////////////
//NOTE: используется класс csTimerDef - в нем время работы таймера задается при обьявлении.
csTimerDef <60*cMinute * 24> tLight; // Свет.
csTimerDef <60*cMinute * 8> tLightWork; // Свет, время работы.
csTimerDef <60*cMinute * 1> tVent; // Вент.
csTimerDef <30*cMinute> tVentWork; // Вент, время работы.
//////////////// SETUP ////////////////
void setup() {
Serial.begin(115200);
pinMode(pinLight, OUTPUT);
pinMode(pinVent, OUTPUT);
// первичный запуск таймеров.
// ускоренный запуск - после запуска контроллера таймеры отработают через секунду (затем будут работать в обычном режиме)
tLight.start(1000);
tVent.start(1000);
}
//////////////// LOOP ////////////////
void loop() {
// пример работы по состоянию:
// свет
if (tLight.run()) {
// запускаем таймер повторно
tLight.start();
// запускаем второй таймер - пока он активен свет будет включен
tLightWork.start();
}
// обработка таймера (заметка: run нельзя вызывать дважды или наоборот не вызывать)
if (tLightWork.run()) {
}
// обновляем свет - новое значение пишеться на каждом скане
digitalWrite(pinLight, tLightWork.enabled());
//todo: добавить поддержку включения света по кнопке
////////////////
// пример работы по событию таймера:
// вентилятор
if (tVent.run()) {
tVent.start();
tVentWork.start();
digitalWrite(pinVent, cEnable);
}
if (tVentWork.run()) {
digitalWrite(pinVent, cDisable);
}
}
| true |
e9e2a09792af26e1eaafee17f7f10b36c6933691 | C++ | tjfulle/lgrtk | /v3/hpc_index.hpp | UTF-8 | 4,189 | 2.765625 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <cstddef>
#include <type_traits>
#include <hpc_macros.hpp>
namespace hpc {
template <class Integral>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr std::enable_if_t<std::is_integral<Integral>::value, Integral> weaken(Integral i) noexcept {
return i;
}
#ifdef HPC_ENABLE_STRONG_INDICES
template <class Tag, class Integral = std::ptrdiff_t>
class index {
Integral i;
public:
using integral_type = Integral;
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index(std::ptrdiff_t i_in) noexcept : i(integral_type(i_in)) {}
HPC_ALWAYS_INLINE index() noexcept = default;
HPC_ALWAYS_INLINE index(index const&) noexcept = default;
HPC_ALWAYS_INLINE index(index&&) noexcept = default;
HPC_ALWAYS_INLINE index& operator=(index const&) noexcept = default;
HPC_ALWAYS_INLINE index& operator=(index&&) noexcept = default;
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index operator+(index const& other) const noexcept {
return index(i + other.i);
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index operator-(index const& other) const noexcept {
return index(i - other.i);
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index& operator++() noexcept {
++i;
return *this;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index operator++(int) const noexcept {
auto const old = *this;
++i;
return old;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index& operator--() noexcept {
--i;
return *this;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index operator--(int) const noexcept {
auto const old = *this;
--i;
return old;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator==(index const& other) const noexcept {
return i == other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator!=(index const& other) const noexcept {
return i != other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator>(index const& other) const noexcept {
return i > other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator<(index const& other) const noexcept {
return i < other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator>=(index const& other) const noexcept {
return i >= other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr bool operator<=(index const& other) const noexcept {
return i <= other.i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index& operator+=(index const& other) noexcept {
i += other.i;
return *this;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE index& operator-=(index const& other) noexcept {
i -= other.i;
return *this;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr integral_type get() const noexcept {
return i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE explicit constexpr operator integral_type() const noexcept {
return i;
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index operator*(integral_type const n) const noexcept {
return index(i * n);
}
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index operator/(integral_type const n) const noexcept {
return index(i / n);
}
template <class Tag2, class Integral2>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE explicit constexpr operator ::hpc::index<Tag2, Integral2>() const noexcept {
return i;
}
};
template <class L, class R>
class product_tag {};
template <class L, class R, class LI, class RI>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index<product_tag<L, R>, decltype(LI() * RI())>
operator*(index<L, LI> left, index<R, RI> right) noexcept {
return left.get() * right.get();
}
template <class L, class R, class LI, class RI>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr index<L, decltype(LI() / RI())>
operator/(index<product_tag<L, R>, LI> left, index<R, RI> right) noexcept {
return left.get() / right.get();
}
template <class Tag, class Integral>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr Integral weaken(index<Tag, Integral> i) noexcept {
return i.get();
}
template <class Tag, class Integral, class T>
HPC_ALWAYS_INLINE HPC_HOST_DEVICE constexpr T* operator+(T* p, index<Tag, Integral> i) noexcept {
return p + weaken(i);
}
#else
template <class Tag, class Integral = std::ptrdiff_t>
using index = Integral;
#endif
}
| true |
5fc0480100d0db209f276cec40c4cd35f17a506a | C++ | vstflugel/tinykactl | /test/Testplate.cpp | UTF-8 | 581 | 2.796875 | 3 | [] | no_license | /* KTH ACM Contest Template Library
*
* Testing/Template
*
* Credit:
* By Mattias de Zalenski
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
void init();
bool solve(int P);
int main() {
init();
// while-solve
int n = 0;
char c;
while (cin >> c) {
//if (n > 0) cout << endl;
string s; getline(cin, s);
cout << s << endl;
solve(n);
n++;
}
return 0;
}
/*
void init() {
}
bool solve(int P) {
int n; cin >> n;
if (cin.fail() || n == 0) return false;
return true;
}
*/
| true |
daeec567c96732c5eb18db78aeab29e6fab47c8b | C++ | wardwellj/Assignment2 | /ContactManager.cpp | UTF-8 | 904 | 2.984375 | 3 | [] | no_license | #include "ContactManager.h"
#include<stdlib.h>
#include<string>
#include<vector>
#include<iostream>
using namespace std;
ContactManager::ContactManager()
{
}
ContactManager::ContactManager(string name, string adress, string number, string birthday):a_name(name), a_adress(adress), a_phoneNum(number), a_birthday(birthday)
{
a_name = name;
a_adress = adress;
a_phoneNum = adress;
a_birthday = birthday;
}
string ContactManager::getName()
{
return a_name;
}
string ContactManager::getAdress()
{
return a_adress;
}
string ContactManager::getNum()
{
return a_phoneNum;
}
string ContactManager::getBirth()
{
return a_birthday;
}
void ContactManager::setName(string name)
{
a_name=name
}
void ContactManager::setAdress(string adress)
{
a_adress=adress
}
void ContactManager::setNum(string Number)
{
a_phoneNum = Number;
}
void ContactManager::setBirth(string bDay)
{
a_birthday = bDay;
}
| true |
b9b800c8af9a7ce377fa89eb9bdcd230e0259e3f | C++ | thenerdyouknow/Codeforces-Problems | /A/59A-Word.cpp | UTF-8 | 819 | 3.34375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/* Solving the logic for this problem is left as a exercise to the reader */
int main() {
string original_mixedcase_string;
int length_of_string,uppercase_count = 0;
cin.sync_with_stdio(false);//For faster I/O
cin >> original_mixedcase_string;
length_of_string = original_mixedcase_string.length();
for(int i=0;i<length_of_string;i++){
if(isupper(original_mixedcase_string[i])){
uppercase_count +=1;
}
}
if(uppercase_count>length_of_string/2){
for(int i=0;i<length_of_string;i++){
original_mixedcase_string[i] = toupper(original_mixedcase_string[i]);
}
}else{
for(int i=0;i<length_of_string;i++){
original_mixedcase_string[i] = tolower(original_mixedcase_string[i]);
}
}
cout << original_mixedcase_string;
}
| true |
a2d47d5fcef14ddf6194dc3fd8a84ee11cd8a887 | C++ | Luchanso/memoryjs | /lib/memory.h | UTF-8 | 1,858 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef MEMORY_H
#define MEMORY_H
#define WIN32_LEAN_AND_MEAN
#include <node.h>
#include <windows.h>
#include <TlHelp32.h>
class memory {
public:
memory();
~memory();
std::vector<MEMORY_BASIC_INFORMATION> getRegions(HANDLE hProcess);
template <class dataType>
dataType readMemory(HANDLE hProcess, DWORD64 address) {
dataType cRead;
ReadProcessMemory(hProcess, (LPVOID)address, &cRead, sizeof(dataType), NULL);
return cRead;
}
char* readBuffer(HANDLE hProcess, DWORD64 address, SIZE_T size) {
char* buffer = new char[size];
ReadProcessMemory(hProcess, (LPVOID)address, buffer, size, NULL);
return buffer;
}
char readChar(HANDLE hProcess, DWORD64 address) {
char value;
ReadProcessMemory(hProcess, (LPVOID)address, &value, sizeof(char), NULL);
return value;
}
template <class dataType>
void writeMemory(HANDLE hProcess, DWORD64 address, dataType value) {
WriteProcessMemory(hProcess, (LPVOID)address, &value, sizeof(dataType), NULL);
}
template <class dataType>
void writeMemory(HANDLE hProcess, DWORD64 address, dataType value, SIZE_T size) {
LPVOID buffer = value;
if (typeid(dataType) != typeid(char*)) {
buffer = &value;
}
WriteProcessMemory(hProcess, (LPVOID)address, buffer, size, NULL);
}
// Write String, Method 1: Utf8Value is converted to string, get pointer and length from string
// template <>
// void writeMemory<std::string>(HANDLE hProcess, DWORD address, std::string value) {
// WriteProcessMemory(hProcess, (LPVOID)address, value.c_str(), value.length(), NULL);
// }
// Write String, Method 2: get pointer and length from Utf8Value directly
void writeMemory(HANDLE hProcess, DWORD64 address, char* value, SIZE_T size) {
WriteProcessMemory(hProcess, (LPVOID)address, value, size, NULL);
}
};
#endif
#pragma once | true |
efc52238ef7c5916e6c8464ba65791b8a4139f09 | C++ | mmarques-ssz/ADS-ED1-20210420 | /ex3.cpp | ISO-8859-1 | 624 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <locale.h>
using namespace std;
int main(int argc, char** argv)
{
setlocale(LC_ALL, "");
string msg = "amanh ser";
cout << msg << endl;
msg.append(" feriado");
cout << msg << endl;
msg.push_back('!');
cout << msg << endl;
msg.pop_back();
msg.pop_back();
msg.pop_back();
cout << msg << endl;
msg.erase(0, 3);
cout << msg << endl;
msg.insert(3, ", quarta-feira,");
cout << msg << endl;
msg.replace(0, 3, "Amanh");
cout << msg << endl;
cout << msg.size() << endl;
msg.clear();
cout << msg.size() << endl;
return 0;
} | true |
4c98f90577c0cc6541435ca69505834df8dd023d | C++ | mikcel/dnd-game | /COMP_345_Project/StrategyTest.cpp | UTF-8 | 5,204 | 3.25 | 3 | [] | no_license | //!
//! @file
//! @brief Implementation file for the StrategyTest class
//!
#include "StrategyTest.h"
//! cppunit test cases registration
CPPUNIT_TEST_SUITE_REGISTRATION(StrategyTest);
//! test method for checking that the ally actually transforms into an enemy when attacked
//! the test executes an attack from the human player to the ally and checks if he obtains
//! the AggressorStrategy
void StrategyTest::allyTransformsToEnemy()
{
CharacterElement& player = *new CharacterElement("mom", new HumanPlayerStrategy());
CharacterElement& enemy = *new CharacterElement("fightest", new AggressorStrategy());
CharacterElement& ally = *new CharacterElement("mom", new FriendlyStrategy());
// Checks if the character element have the right strategy
CPPUNIT_ASSERT(dynamic_cast<HumanPlayerStrategy*>(player.getCharacterStrategy()) != nullptr);
CPPUNIT_ASSERT(dynamic_cast<AggressorStrategy*>(enemy.getCharacterStrategy()) != nullptr);
CPPUNIT_ASSERT(dynamic_cast<FriendlyStrategy*>(ally.getCharacterStrategy()) != nullptr);
// Perform multiple attacks
player.attack(enemy);
player.attack(ally);
enemy.attack(player);
// Checks if only the strategy of the ally has changed to and aggressor strategy
CPPUNIT_ASSERT(dynamic_cast<HumanPlayerStrategy*>(player.getCharacterStrategy()) != nullptr);
CPPUNIT_ASSERT(dynamic_cast<AggressorStrategy*>(enemy.getCharacterStrategy()) != nullptr);
CPPUNIT_ASSERT(dynamic_cast<AggressorStrategy*>(ally.getCharacterStrategy()) != nullptr);
if (system("CLS")) system("clear");
}
//! test method to check that the allies and the enemies are truly advancing towards the human player
//! Created an instance of the map, places an ally and player on it and checks that after 4 steps that
//! the distance between the enemy and the player as well as between the ally and the enemy becomes smaller
void StrategyTest::allyAndEnemyMovement()
{
// Create map and load its components
string character_name = "mom";
string map_name = "map5.4";
Character* character = readCharacterFile(character_name);
Map* map = readMapFile("SaveFiles/Maps/" + map_name + ".txt", map_name);
CharacterElement tempPlayer(*character, new HumanPlayerStrategy());
map->placePlayer(tempPlayer);
CharacterElement* player = &map->getPlayer();
CharacterElement* enemy;
CharacterElement* ally;
for (Element* element : map->getElements())
{
CharacterElement* characterElement = dynamic_cast<CharacterElement*>(element);
if (characterElement)
{
AggressorStrategy* aggressorStrategy = dynamic_cast<AggressorStrategy*>(characterElement->getCharacterStrategy());
FriendlyStrategy* friendlyStrategy = dynamic_cast<FriendlyStrategy*>(characterElement->getCharacterStrategy());
if (aggressorStrategy)
{
enemy = characterElement;
}
else if (friendlyStrategy)
{
ally = characterElement;
}
}
}
AggressorStrategy* aggressorStrategy = dynamic_cast<AggressorStrategy*>(enemy->getCharacterStrategy());
FriendlyStrategy* friendlyStrategy = dynamic_cast<FriendlyStrategy*>(ally->getCharacterStrategy());
Position playerPosition = player->getPosition();
Position enemyStartPosition = enemy->getPosition();
Position allyStartPosition = ally->getPosition();
float distanceX;
float distanceY;
// Calculate the initial distance from the enemy to the player using Pythagorean theorem
distanceX = enemyStartPosition.x - playerPosition.x;
distanceY = enemyStartPosition.y - playerPosition.y;
float startDistanceFromEnemyToPlayer = sqrt(distanceX * distanceX + distanceY * distanceY);
// Calculate the initial distance from the ally to the player using Pythagorean theorem
distanceX = allyStartPosition.x - playerPosition.x;
distanceY = allyStartPosition.y - playerPosition.y;
float startDistanceFromAllyToPlayer = sqrt(distanceX * distanceX + distanceY * distanceY);
std::list<std::pair<int, int>> pathOfEnemy = aggressorStrategy->calculateShortestPath(*map);
std::list<std::pair<int, int>> pathOfFriend = friendlyStrategy->calculateShortestPath(*map);
//for (int i = 0; i < 3; i++)
//{
aggressorStrategy->performMovementStepAI(*map, pathOfEnemy);
friendlyStrategy->performMovementStepAI(*map, pathOfFriend);
//}
Position enemyEndPosition = enemy->getPosition();
Position allyEndPosition = ally->getPosition();
// Calculate the distance from the enemy to the player using Pythagorean theorem after 4 steps performed
distanceX = enemyEndPosition.x - playerPosition.x;
distanceY = enemyEndPosition.y - playerPosition.y;
float endDistanceFromEnemyToPlayer = sqrt(distanceX * distanceX + distanceY * distanceY);
// Calculate the distance from the ally to the player using Pythagorean theorem after 4 steps performed
distanceX = allyEndPosition.x - playerPosition.x;
distanceY = allyEndPosition.y - playerPosition.y;
float endDistanceFromAllyToPlayer = sqrt(distanceX * distanceX + distanceY * distanceY);
// Check if the distance between the player and the enemy as well as between the player and the ally
// is smaller after the 4 steps executed
CPPUNIT_ASSERT(startDistanceFromEnemyToPlayer > endDistanceFromEnemyToPlayer);
CPPUNIT_ASSERT(startDistanceFromAllyToPlayer > endDistanceFromAllyToPlayer);
} | true |
3f411176ccaacda6427106514a2898efbccdc564 | C++ | zeroplusone/AlgorithmPractice | /Leetcode/1903. Largest Odd Number in String.cpp | UTF-8 | 388 | 3.140625 | 3 | [] | no_license | class Solution {
public:
string largestOddNumber(string num) {
int odd_index=-1;
for(int i=num.length()-1;i>=0;--i) {
if((num[i]-'0')%2==1) {
odd_index=i;
break;
}
}
if(odd_index==-1) {
return "";
} else {
return num.substr(0, odd_index+1);
}
}
};
| true |
331394133dc120ea31b1a37f3dc7bb230d2ac202 | C++ | apocalyptikz/Solitaire | /Program3/deck.cpp | UTF-8 | 2,114 | 3.609375 | 4 | [] | no_license | #include "deck.h"
//deck objects should do the following :
//
//have a deep copy constructor
//have a deep assignment operator
//default to a standard deck of 52 cards(see Other section for sequence)
//add a card to the top or bottom of the deck (pass card object)
//insert a card into the deck at some index (exit if invalid)
//remove a card from the top or bottom of the deck
//remove a card from the deck at some index
//return card at top of deck
//return card at bottom of deck
//clear the deck
//shuffle the deck
//test if the deck is empty
//overload the sequence operator [] and const and non const
//overload the += operator (for deck and card objects)
deck::deck()
{
for (size_t i = 0; i < card::STDVALUES; ++i)
{
for (size_t j = 0; j < card::STDSUITS; ++j)
{
//Contructs a card and inserts at back of _cards
_cards.emplace_back(card(card::STDVALUEABBRV[i],
card::STDSUITABBRV[j]));
}
}
}
deck::deck(const deck &deckIn)
{
for (size_t i = 0; i < card::STDCARDS - 1; ++i)
{
_cards.push_back(deckIn[i]);
}
}
deck::~deck()
{
}
void deck::add(const card &cardIn, bool top)
{
if (top)
_cards.insert(_cards.begin(), cardIn);
else
_cards.push_back(cardIn);
}
int deck::insert(const size_t &index, const card &cardIn)
{
if (&cardIn == NULL || index == -1)
return EXIT_FAILURE;
_cards.insert(_cards.begin() + index, cardIn);
return (int)index;
}
void deck::remove(bool top)
{
if (top)
_cards.erase(_cards.begin());
else
_cards.pop_back();
}
void deck::remove(const size_t &index)
{
_cards.erase(_cards.begin() + index);
}
void deck::shuffle()
{
std::random_shuffle(_cards.begin(), _cards.end());
}
deck& deck::operator+=(const deck &deckIn)
{
for (size_t i = 0; i < card::STDCARDS - 1; ++i)
{
_cards.push_back(deckIn[i]);
}
return *this;
}
deck& deck::operator+=(const card &cardIn)
{
add(cardIn, false);
return *this;
}
deck& deck::operator=(const deck &deckIn)
{
//Self assignment
if (this == &deckIn)
{
return *this;
}
_cards.clear();
for (size_t i = 0; i < card::STDCARDS - 1; ++i)
{
_cards.push_back(deckIn[i]);
}
return *this;
} | true |
866405f9da0c7d4727d1bf3b5d3255e6bdd401d8 | C++ | songhzh/The-Arena | /The Arena/The Arena/main.cpp | UTF-8 | 1,140 | 2.640625 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include "GameStateManager.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(1600, 900), "The Arena", sf::Style::Titlebar | sf::Style::Close);
sf::Texture logo_t;
logo_t.loadFromFile("Resources/Textures/title_logo.png");
sf::Sprite logo_s(logo_t);
logo_s.setPosition(sf::Vector2f(1410, 10));
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
GameStateManager gsm(&window);
while (window.isOpen())
{
sf::Event evt;
while (window.pollEvent(evt))
{
switch (evt.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::TextEntered:
//std::cout << evt.text.unicode << std::endl;;
break;
case sf::Event::KeyPressed:
gsm.keyPressed(evt.key.code);
//std::cout << evt.key.code << std::endl;
break;
case sf::Event::LostFocus:
gsm.setPause(true);
break;
case sf::Event::GainedFocus:
gsm.setPause(false);
break;
default:
break;
}
}
window.clear(sf::Color(100, 155, 100, 255));
window.draw(logo_s);
gsm.update();
window.display();
//sf::sleep(sf::milliseconds(100));
}
return 0;
} | true |
f8d4dcca4beccc925514260c9427ecf59d8199cb | C++ | tig/Tigger | /Experiments/WeatherBug/WeatherBug/WsHelpers.h | UTF-8 | 5,251 | 2.578125 | 3 | [
"MS-PL",
"MIT"
] | permissive | #pragma once
class WsError
{
WS_ERROR* m_h;
public:
WsError() :
m_h(0)
{
// Do nothing
}
~WsError()
{
if (0 != m_h)
{
WsFreeError(m_h);
}
}
HRESULT Create(__in_ecount_opt(propertyCount) const WS_ERROR_PROPERTY* properties,
__in ULONG propertyCount)
{
ASSERT(0 == m_h);
return WsCreateError(properties,
propertyCount,
&m_h);
}
HRESULT GetProperty(__in WS_ERROR_PROPERTY_ID id,
__out_bcount(bufferSize) void* buffer,
__in ULONG bufferSize)
{
ASSERT(0 != m_h);
ASSERT(0 != buffer);
return WsGetErrorProperty(m_h,
id,
buffer,
bufferSize);
}
template <typename T>
HRESULT GetProperty(__in WS_ERROR_PROPERTY_ID id,
__out T* buffer)
{
return GetProperty(id,
buffer,
sizeof(T));
}
HRESULT GetString(__in ULONG index,
__out WS_STRING* string)
{
ASSERT(0 != m_h);
ASSERT(0 != string);
return WsGetErrorString(m_h,
index,
string);
}
operator WS_ERROR*() const
{
return m_h;
}
};
class WsHeap
{
WS_HEAP* m_h;
public:
WsHeap() :
m_h(0)
{
// Do nothing
}
~WsHeap()
{
if (0 != m_h)
{
WsFreeHeap(m_h);
}
}
HRESULT Create(__in SIZE_T maxSize,
__in SIZE_T trimSize,
__in_opt const WS_HEAP_PROPERTY* properties,
__in ULONG propertyCount,
__in_opt WS_ERROR* error)
{
ASSERT(0 == m_h);
return WsCreateHeap(maxSize,
trimSize,
properties,
propertyCount,
&m_h,
error);
}
operator WS_HEAP*() const
{
return m_h;
}
};
class WsServiceProxy
{
WS_SERVICE_PROXY* m_h;
public:
WsServiceProxy() :
m_h(0)
{
// Do nothing
}
~WsServiceProxy()
{
if (0 != m_h)
{
Close(0, // async context
0); // error
WsFreeServiceProxy(m_h);
}
}
HRESULT Open(__in const WS_ENDPOINT_ADDRESS* address,
__in_opt const WS_ASYNC_CONTEXT* asyncContext,
__in_opt WS_ERROR* error)
{
ASSERT(0 != m_h);
return WsOpenServiceProxy(m_h,
address,
asyncContext,
error);
}
HRESULT Close(__in_opt const WS_ASYNC_CONTEXT* asyncContext,
__in_opt WS_ERROR* error)
{
ASSERT(0 != m_h);
return WsCloseServiceProxy(m_h,
asyncContext,
error);
}
WS_SERVICE_PROXY** operator&()
{
ASSERT(0 == m_h);
return &m_h;
}
operator WS_SERVICE_PROXY*() const
{
return m_h;
}
};
class WsServiceHost
{
WS_SERVICE_HOST* m_h;
public:
WsServiceHost() :
m_h(0)
{
// Do nothing
}
~WsServiceHost()
{
if (0 != m_h)
{
Close(0, // async context
0); // error
WsFreeServiceHost(m_h);
}
}
HRESULT Create(__in_ecount_opt(endpointCount) const WS_SERVICE_ENDPOINT** endpoints,
__in const USHORT endpointCount,
__in_ecount_opt(servicePropertyCount) const WS_SERVICE_PROPERTY* properties,
__in ULONG propertyCount,
__in_opt WS_ERROR* error)
{
ASSERT(0 == m_h);
return WsCreateServiceHost(endpoints,
endpointCount,
properties,
propertyCount,
&m_h,
error);
}
HRESULT Open(__in_opt const WS_ASYNC_CONTEXT* asyncContext,
__in_opt WS_ERROR* error)
{
ASSERT(0 != m_h);
return WsOpenServiceHost(m_h,
asyncContext,
error);
}
HRESULT Close(__in_opt const WS_ASYNC_CONTEXT* asyncContext,
__in_opt WS_ERROR* error)
{
ASSERT(0 != m_h);
return WsCloseServiceHost(m_h,
asyncContext,
error);
}
operator WS_SERVICE_HOST*() const
{
return m_h;
}
};
| true |
7ce73dfd6a966b76da75c2d7d1c99a513286ad67 | C++ | xxwsL/hello-world- | /leecode/inc/remove_nth_listnode_t.h | UTF-8 | 969 | 3.03125 | 3 | [] | no_license | #ifndef _remove_nth_listnode_t_h_
#define _remove_nth_listnode_t_h_
#include <iostream>
#include <vector>
#include "ListNode.h"
using namespace std;
ListNode* remove_nth_listnode_t_fi(ListNode* head, int n)
{
cout << "this is remove_nth_listnode test\n";
ListNode *node_tp = head;
vector<ListNode*> buf;
while(node_tp){
buf.push_back(node_tp);
node_tp = node_tp->next;
}
int pos = buf.size() - n;
if(pos == 0){
head = head->next;
}
else{
buf[pos - 1]->next = buf[pos]->next;
}
return head;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* end = head;
ListNode* cur = head;
for(int i = 1;i <= n;i++){
end = end->next;
}
if(end == NULL)return head->next;
while(end->next){
end = end->next;
cur = cur->next;
}
cur->next = cur->next->next;
return head;
}
#endif | true |
03e866a13281ccc187db55326d6aba40b1d260a3 | C++ | snytkine/router_lib | /RouterNode.h | UTF-8 | 2,869 | 2.8125 | 3 | [] | no_license | //
// Created by Snytkine, Dmitri (CORP) on 3/14/17.
//
#ifndef ROUTER_ROUTER_NODE_H
#define ROUTER_ROUTER_NODE_H
#include <iostream>
#include <vector>
#include <sstream>
#include <chrono>
#include <utility>
#include "node_result.h"
namespace router_lib {
using namespace std;
template<typename T>
class RouterNode {
public :
RouterNode<T>(string uri, T *ctrl, string name = "") : origUriPattern(uri),
controller_name(name),
controller(ctrl) {
//cout << "CREATED NODE for uri=[" << uri << "] origUriPattern=[" << origUriPattern << "]" << endl;
}
RouterNode<T>() : origUriPattern("/"), controller_name("ROOT"), controller() {}
RouterNode<T>(std::string uri) : origUriPattern(uri), controller() {}
RouterNode<T> *createRouterNode(string nodeUri, T &id, string name);
RouterNode<T> *createRouterNode(string nodeUri);
virtual T *getController() const {
return controller;
}
virtual string getParamName() const;
void setController(T *ctrl) {
controller = ctrl;
}
bool empty() const {
return controller == nullptr;
}
virtual RouterNode<T> *addRoute(string uri, T &controller, string ctrl_name = "");
virtual RouteResult<T> *findRoute(const string uri, paramsList *params = new paramsList()) const;
~RouterNode() {
if (children.size() > 0) {
//cout << " RouterNode " << origUriPattern << " destructor called " << endl; // never called?
children.clear();
delete controller;
}
}
//virtual string rest(const string s) const;
protected:
T *controller;
string controller_name;
string origUriPattern;
vector<RouterNode<T> *> children;
// This is where the work is done to match uri for this node, possibly extract router params and
// return a result.
// result may contain controller_id in which case the result is found
// or it may append extracted route params to params, generate the "restString" and return
// result with params and restString, in which case children will be searched for a match for the restString
virtual RouteResult<T> *getNodeResult(const string uri, paramsList *params = new paramsList()) const;
};
//template
//class RouterNode<int>;
//template<typename T>
//RouterNode<T>* createRouterNode(string nodeUri, T id, string name);
//template
//RouterNode<int>* createRouterNode(string nodeUri, int id, string name);
//template <typename T>
//RouterNode<T>* emptyNode();
}
#endif //ROUTER_ROUTER_NODE_H
| true |
8f49c00fe388dcccba495eb86180bbcee3e27282 | C++ | SccsAtmtn/leetcode | /240.cpp | UTF-8 | 2,755 | 2.96875 | 3 | [] | no_license | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0) return false;
int n = matrix[0].size();
if (n == 0) return false;
int upperx, uppery, bottomx, bottomy;
upperx = uppery = 0;
bottomx = m - 1;
bottomy = n - 1;
int t = 0;
while (!(upperx == bottomx && uppery == bottomy)) {
if (matrix[upperx][uppery] > target || matrix[bottomx][bottomy] < target) return false;
if (t == 0) {
int left = uppery, right = bottomy, ans;
while (left <= right) {
int mid = (left + right) / 2;
if (matrix[upperx][mid] == target) return true;
else
if (matrix[upperx][mid]<target) {
ans = mid;
left = mid + 1;
}
else right = mid - 1;
}
bottomy = ans;
left = upperx;
right = bottomx;
while (left <= right) {
int mid = (left + right) / 2;
if (matrix[mid][uppery] == target) return true;
else
if (matrix[mid][uppery]<target) {
ans = mid;
left = mid + 1;
}
else right = mid - 1;
}
bottomx = ans;
}
else {
int left = upperx, right = bottomx, ans;
while (left <= right) {
int mid = (left + right) / 2;
if (matrix[mid][bottomy] == target) return true;
else
if (matrix[mid][bottomy]<target) {
ans = mid;
left = mid + 1;
}
else right = mid - 1;
}
upperx = ans+1;
left = uppery;
right = bottomy;
while (left <= right) {
int mid = (left + right) / 2;
if (matrix[bottomx][mid] == target) return true;
else
if (matrix[bottomx][mid]<target) {
ans = mid;
left = mid + 1;
}
else right = mid - 1;
}
uppery = ans+1;
}
t = 1 - t;
}
if (matrix[upperx][uppery] == target) return true;
else return false;
}
}; | true |
9e64392f5347f680a977e8e0011c1916e7bbd89f | C++ | willsauer/invaders | /include/CSprite.h | UTF-8 | 2,152 | 2.53125 | 3 | [] | no_license | #ifndef CSPRITE_H
#define CSPRITE_H
/*
* CSprite.cpp
* Sprite class
*
* Created by Marcelo Cohen on 04/11.
* Copyright 2011 PUCRS. All rights reserved.
*
*/
#include <vector>
#include "CMultiImage.h"
#include "TexRect.h"
#include "tinyxml.h"
class CSprite : public CMultiImage, public TiXmlVisitor
{
public:
CSprite();
virtual ~CSprite();
bool loadSprite(char nomeArq[], int w, int h, int hSpace, int vSpace, int xIni, int yIni,
int column, int row, int total);
bool loadSpriteSparrowXML(char nomeArq[]);
void setXspeed(double xspeed);
void setYspeed(double yspeed);
void setCurrentFrame(int c);
bool setFrameRange(int first, int last);
void frameForward();
void frameBack();
void setAnimRate(int fdelay);
void update(double updateInterval);
void draw();
double getXspeed() { return xspeed; }
double getYspeed() { return yspeed; }
int getCurrentFrame() { return curframe; }
int getTotalFrames() { return totalFrames; }
bool bboxCollision(CSprite* other);
bool circleCollision(CSprite* other);
// TiXmlVisitor overrides
//virtual bool VisitEnter (const TiXmlDocument &);
//virtual bool VisitExit (const TiXmlDocument &);
virtual bool VisitEnter (const TiXmlElement &, const TiXmlAttribute *);
//virtual bool VisitExit (const TiXmlElement &);
//virtual bool Visit (const TiXmlDeclaration &);
//virtual bool Visit (const TiXmlText &);
//virtual bool Visit (const TiXmlComment &);
//virtual bool Visit (const TiXmlUnknown &);
private:
double xspeed,yspeed; // speed in pixels/s
int updateCount; // current count of updates
int firstFrame, lastFrame; // frame range
int curframe; // current frame
double curFrameD; // the current frame as double
int framecount,framedelay; // slow down the frame animation
int spriteW, spriteH; // width and height of a single sprite frame
};
#endif // CSPRITE_H
| true |
ddc4bfaca290fa7a987ce24feceb0b7e133be21b | C++ | Wishu969/Project-Euler | /VSstudio/project euler/problem40.cpp | UTF-8 | 392 | 2.78125 | 3 | [] | no_license | #include "problem40.h"
std::string problem40::s;
problem40::problem40()
{
}
problem40::~problem40()
{
}
void problem40::init()
{
for (int i = 1; s.length() <= 1000000; i++)
{
std::string temp = std::to_string(i);
s.append(temp);
}
}
int problem40::run()
{
init();
int j = 1;
for (int i = 1; i != 1000000; i *= 10)
{
j *= (int)s[i - 1] - 48;
}
std::cout << j;
return 0;
}
| true |
3fc65fdcd44381b4b03e73cbba6f60ba43f75e52 | C++ | SpaceMonkeyClan/FreeNOS-1.0.3 | /lib/libipc/Channel.h | UTF-8 | 2,364 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2015 Niek Linnenbank
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __LIBIPC_CHANNEL_H
#define __LIBIPC_CHANNEL_H
#include <Types.h>
/**
* @addtogroup lib
* @{
*
* @addtogroup libipc
* @{
*/
/**
* Unidirectional point-to-point messaging channel.
*/
class Channel
{
public:
/**
* Result codes.
*/
enum Result
{
Success,
InvalidArgument,
InvalidMode,
InvalidSize,
IOError,
ChannelFull,
NotFound,
NotSupported
};
/**
* Channel modes.
*/
enum Mode
{
Producer,
Consumer
};
public:
/**
* Constructor.
*
* @param mode Channel mode is either a producer or consumer
* @param messageSize Size of each individual message in bytes
*/
Channel(const Mode mode, const Size messageSize);
/**
* Destructor.
*/
virtual ~Channel();
/**
* Get message size
*
* @return Message size
*/
const Size getMessageSize() const;
/**
* Read a message.
*
* @param buffer Output buffer for the message.
*
* @return Result code.
*/
virtual Result read(void *buffer);
/**
* Write a message.
*
* @param buffer Input buffer for the message.
*
* @return Result code.
*/
virtual Result write(const void *buffer);
/**
* Flush message buffers.
*
* Ensures that all messages are written through caches.
*
* @return Result code.
*/
virtual Result flush();
protected:
/** Channel mode. */
const Mode m_mode;
/** Message size. */
const Size m_messageSize;
};
/**
* @}
* @}
*/
#endif /* __LIBIPC_CHANNEL_H */
| true |