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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e45bdc2d9a1b14e3db279245e2e62200dda4a965 | C++ | 536BLF/BLF | /Testing/Ben_MostRecent/BLF536/BLF536.ino | UTF-8 | 6,661 | 2.71875 | 3 | [] | no_license | #include "Macros.h"
#include <AFMotor.h>
#include "Car.h"
#include "Sensor.h"
#include "Tester.h"
int j;
enum {INIT, READ_2_LINE, READ_LEFT_LINE, READ_RIGHT_LINE, READ_NO_LINE, INTERSECTION} state = INIT;
Sensor leftSensor(PIN_ANALOG_0, WHITE_LINE);
Sensor rightSensor(PIN_ANALOG_1, WHITE_LINE);
Tester tester;
Car BLF536;
AF_DCMotor MotorLeft(4);
AF_DCMotor MotorRight(3);
/*
Function: setup
Description: Initializes our loop
*/
void setup() {
Serial.begin(9600);
leftSensor.Init_Sensors();
rightSensor.Init_Sensors();
BLF536.MotorRightPtr = &MotorRight;
BLF536.MotorLeftPtr = &MotorLeft;
//BLF536.System_Identification();
}
/*
Function: loop
Description: Our main while loop that runs forever
*/
void loop() {
// Serial.println("here");
// tester.Start_Timer();
// BLF536.Sample_Time();
/*
BLF536.System_Identification();
leftSensor.ReadAllSensors();
rightSensor.ReadAllSensors();
leftSensor.Sensor_Error_Calc();
rightSensor.Sensor_Error_Calc();
BLF536.Total_Error_Calc(2);
*/
BLF536.motorDiffPWM = 100;
BLF536.MotorDiff();
// --- Uncomment any of these below if you want to see specific outputs --- //
//tester.System_Id();
//tester.Print_Total_Error();
// tester.Print_Total_Error();
// tester.Print_Sensor_Values();
// tester.Print_Line_Val();
// tester.Display_Timer();
}
/*
Function: FSM
Description: The finite state machine to determine which state the vehicle is currently in
--- THIS FUNCTION IS CURRENTLY INCOMPLETE - 11/5 ---
*/
void FSM(void) {
switch (state) {
case INIT: break;
case READ_2_LINE: {
Follow();
break;
}
case READ_LEFT_LINE: {
Follow();
break;
}
case READ_RIGHT_LINE: {
Follow();
break;
}
case READ_NO_LINE: {
Open_Run();
break;
}
case INTERSECTION: {
Intersection();
break;
}
default: state = INIT;
}
}
/*
Function: Read_Sate
Description: The function that determines the next state based on what the sensors are seeing.
--- THIS FUNCTION IS CURRENTLY INCOMPLETE - 11/8 ---
*/
void Read_State(void) {
boolean lostLeft, lostRight;
int errorCalcSel;
leftSensor.ReadAllSensors();
rightSensor.ReadAllSensors();
lostLeft = Check_Lost_Left_Line();
lostRight = Check_Lost_Right_Line();
if (lostLeft) leftSensor.Hold_Value();
if (lostRight) rightSensor.Hold_Value();
if (Check_Intersection()) {
state = INTERSECTION;
}
if (lostLeft && lostRight) {
state = READ_NO_LINE;
errorCalcSel = 2;
}
if (lostLeft && !lostRight) {
state = READ_RIGHT_LINE;
errorCalcSel = 1;
}
if (!lostLeft && lostRight) {
state = READ_LEFT_LINE;
errorCalcSel = 0;
}
if (!lostLeft && !lostRight) {
state = READ_2_LINE;
errorCalcSel = 2;
}
leftSensor.Sensor_Error_Calc();
rightSensor.Sensor_Error_Calc();
BLF536.Total_Error_Calc(errorCalcSel);
}
/*
Function: Check_Intersection
Description: Checks the RIGHT sensor to see if it sees a corner. If it does, then it changes the FSM to the intersection state to handle this intersection
*/
int Check_Intersection(void) {
if ( rightSensor.sensorVals_T0[4] > ON_LINE_THRESHOLD && rightSensor.sensorVals_T0[5] > ON_LINE_THRESHOLD
&& rightSensor.sensorVals_T0[6] > ON_LINE_THRESHOLD && rightSensor.sensorVals_T0[7] > ON_LINE_THRESHOLD) {
return 1;
}
return 0;
}
/*
Function: Check_Lost_Right_Line
Description: checks to see if the analog1 sensor lost the line. Returns 1 if it did, else it returns 0
*/
int Check_Lost_Right_Line(void) {
if ( rightSensor.sensorVals_T0[0] < OFF_LINE_THRESHOLD && rightSensor.sensorVals_T0[1] < OFF_LINE_THRESHOLD
&& rightSensor.sensorVals_T0[2] < OFF_LINE_THRESHOLD && rightSensor.sensorVals_T0[3] < OFF_LINE_THRESHOLD
&& rightSensor.sensorVals_T0[4] < OFF_LINE_THRESHOLD && rightSensor.sensorVals_T0[5] < OFF_LINE_THRESHOLD
&& rightSensor.sensorVals_T0[6] < OFF_LINE_THRESHOLD && rightSensor.sensorVals_T0[7] < OFF_LINE_THRESHOLD) {
return 1;
}
return 0;
}
int Check_Found_Right_Line(void) {
if ( rightSensor.sensorVals_T0[0] > ON_LINE_THRESHOLD || rightSensor.sensorVals_T0[1] > ON_LINE_THRESHOLD
|| rightSensor.sensorVals_T0[2] > ON_LINE_THRESHOLD || rightSensor.sensorVals_T0[3] > ON_LINE_THRESHOLD
|| rightSensor.sensorVals_T0[4] > ON_LINE_THRESHOLD || rightSensor.sensorVals_T0[5] > ON_LINE_THRESHOLD
|| rightSensor.sensorVals_T0[6] > ON_LINE_THRESHOLD || rightSensor.sensorVals_T0[7] > ON_LINE_THRESHOLD) {
return 1;
}
return 0;
}
/*
Function: Check_Lost_Left_Line
Description: checks to see if the analog0 sensor lost the line. Returns 1 if it did, else it returns 0
*/
int Check_Lost_Left_Line(void) {
if ( leftSensor.sensorVals_T0[0] < OFF_LINE_THRESHOLD && leftSensor.sensorVals_T0[1] < OFF_LINE_THRESHOLD
&& leftSensor.sensorVals_T0[2] < OFF_LINE_THRESHOLD && leftSensor.sensorVals_T0[3] < OFF_LINE_THRESHOLD
&& leftSensor.sensorVals_T0[4] < OFF_LINE_THRESHOLD && leftSensor.sensorVals_T0[5] < OFF_LINE_THRESHOLD
&& leftSensor.sensorVals_T0[6] < OFF_LINE_THRESHOLD && leftSensor.sensorVals_T0[7] < OFF_LINE_THRESHOLD) {
return 1;
}
return 0;
}
int Check_Found_Left_Line(void) {
if ( leftSensor.sensorVals_T0[0] > ON_LINE_THRESHOLD || leftSensor.sensorVals_T0[1] > ON_LINE_THRESHOLD
|| leftSensor.sensorVals_T0[2] > ON_LINE_THRESHOLD || leftSensor.sensorVals_T0[3] > ON_LINE_THRESHOLD
|| leftSensor.sensorVals_T0[4] > ON_LINE_THRESHOLD || leftSensor.sensorVals_T0[5] > ON_LINE_THRESHOLD
|| leftSensor.sensorVals_T0[6] > ON_LINE_THRESHOLD || leftSensor.sensorVals_T0[7] > ON_LINE_THRESHOLD) {
return 1;
}
return 0;
}
void Intersection(void) {
switch (random() % 3) {
case 0: RightTurnOL(); break;
case 1: GoStraightOL(); break;
case 2: LeftTurnOL(); break;
}
}
void GoStraightOL(void) {
long timer = millis();
while (millis() - timer < STRAIGHTTIME) {
BLF536.motorDiffPWM = 0;
BLF536.MotorDiff();
}
return;
}
void RightTurnOL(void) {
long timer = millis();
while (millis() - timer < RIGHTTURNTIME) {
BLF536.MotorRightPtr->setSpeed(5);
BLF536.MotorLeftPtr->setSpeed(255);
}
}
void LeftTurnOL() {
long timer = millis();
while (millis() - timer < LEFTTURNTIME) {
BLF536.MotorRightPtr->setSpeed(255);
BLF536.MotorLeftPtr->setSpeed(100);
}
}
void Follow(void) {
}
void Open_Run(void) {
}
int Controller(long error, int controllertype) {
}
| true |
631938f7b820dd4d75e8a243d40c0d32904afc27 | C++ | Varinderr/Basic-Programs | /reverse string.cpp | UTF-8 | 309 | 2.953125 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
void reverse(string& str)
{
{
int n = str.length();
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
}
int main()
{
int n;
{
string str = "geeks for geeks";
reverse(str);
cout << str;
getch();
}
} | true |
09b311e4d924f6fce528b52c3d9287b82e84ed0b | C++ | luizalbertocviana/cracking-coding-problems | /ch1/q1.cpp | UTF-8 | 947 | 3.640625 | 4 | [] | no_license | #include <args.hpp>
#include <iostream>
#include <set>
#include <string>
// determine whether a string has all unique characters
bool unique(const std::string& col){
// we are going to use a set to determine whether we see a character
// more than once
std::set<char> set {};
for (char c : col){
// if c is already present, we have seen it more than once, and
// return false
if (set.count(c)){
return false;
}
// otherwise we are seeing c for the first time, so we register it
else{
set.insert(c);
}
}
// if no character of col was seen more than once, we return true
return true;
}
int main(int argc, char** argv){
auto args {get_args(argc, argv)};
if (args.size() == 2){
std::string str {args[1]};
if (unique(str)){
std::cout << str << " has no repeated characters\n";
}
else{
std::cout << str << " has repeated characters\n";
}
}
return 0;
}
| true |
8c814b57f23337680244e55092276716c4be53e7 | C++ | HyungseobKim/Hon | /hon_source/Asterisk/Text.h | UTF-8 | 5,046 | 3.25 | 3 | [] | no_license | #ifndef TEXT_H
#define TEXT_H
/*!*******************************************************************
\headerfile Text.h <>
\author Kim HyungSeob
\par email: hn02415 \@ gmail.com
\brief Header file for Text Class.
\copyright
All content 2018 DigiPen (USA) Corporation, all rights reserved.
********************************************************************/
#include <string>
#include <unordered_map>
#include "Font.h"
#include "Window.h"
#include "Vector.h"
#include "Mesh.h"
/*!*******************************************************************
\class Text
\brief
Holds characters to print and has methods to draw.
********************************************************************/
class Text
{
public:
/*!*******************************************************************
\brief Default Constructor.
********************************************************************/
Text() = default;
/*!*******************************************************************
\brief
Constructor set string and font in once.
\param text_string
Characters to print.
\param text_font
Pointer to font to use for this text.
********************************************************************/
Text(std::string text_string, Font & text_font);
/*!*******************************************************************
\brief
Prints text by getting information from font and setting to a
sprite and then passing to draw function.
\param window
Pointer to window that has draw function that will be used.
********************************************************************/
void Draw(Window * window, const float & depth);
void DirectProjectionDraw(Window * window, const float & depth);
/*!*******************************************************************
\brief
Getter method for string.
\return
Characters to print.
********************************************************************/
std::string GetString() const { return m_string; }
/*!*******************************************************************
\brief
Set string to print.
\param text_string
Characters to print.
********************************************************************/
void SetString(const std::string & text_string);
/*!*******************************************************************
\brief
Getter method for font.
\return
Pointer to font.
********************************************************************/
const Font * GetFont() const { return m_font; }
/*!*******************************************************************
\brief
Set pointer to font.
\param text_font
Pointer to font.
********************************************************************/
void SetFont(Font & text_font);
/*!*******************************************************************
\brief
Set position of text.
\param x
x position.
\param y
y position.
********************************************************************/
void SetPosition(float x, float y);
/*!*******************************************************************
\brief
Set position of text.
\param position
Position to set.
********************************************************************/
void SetPosition(Vector2f position) { m_position = position; }
/*!*******************************************************************
\brief
move position of text.
\param position
Position to move.
********************************************************************/
void Move(Vector2f position) { m_position += position; }
/*!*******************************************************************
\brief
get position of text.
\return
position of the text.
********************************************************************/
Vector2f GetPosition() { return m_position; }
/*!*******************************************************************
\brief
Set scale of text.
\param x
x scale.
\param y
y scale.
\param z
z scale.
********************************************************************/
void SetScale(float x, float y, float z)
{
m_sprite.GetTransform().SetScale(Vector3f(x, y, z));
}
/*!*******************************************************************
\brief
Set scale of text.
\param scale
Scale to set.
********************************************************************/
void SetScale(Vector3f scale) { m_sprite.GetTransform().SetScale(scale); }
void SetShader(Shader * input_shader) { m_pShader = input_shader; }
void SetDepth(float depth) { m_sprite.SetDepth(depth); }
private:
std::string m_string{}; //!< Characters to print.
Font * m_font = nullptr; //!< Pointer to font.
Sprite m_sprite; //!< Holds information of each character. Used for drawing function.
Vector2f m_position; //!< Position of text.
Shader * m_pShader;
int m_lineLimit = 0; //!< Maximum length of each line. 0 is assumed as no limit.
Vector2f UpdateText(Vector2f & position, char & current_char);
};
#endif | true |
16a16980f0c0698d4f5ceee159f56866af70c653 | C++ | mohitpandey94/SPOJ-Solutions | /spoj/ANARC09A/ANARC09A-13179594.cpp | UTF-8 | 1,527 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct st {
char a[10000];
long int top;
long int index[10000];
};
void push (struct st *s, char val, int i) {
s->a[++(s->top)]=val;
s->index[s->top]=i ;
}
long int pop (struct st *s) { long int item=s->index[s->top]; --(s->top); return item; }
int main() {
int t,i; struct st s;
char p[2005],next;
long int cnt=0,len,k,j=0,temp; t=0;
while (scanf("%s",&p)) {
if (p[0]=='-') break;
t++;
s.top=-1; cnt=j=0;k=0;
len=strlen(p);
for (i=0; i < len; i++) {
if (p[i] == '{')
push (&s, p[i],i);
else if (p[i]=='}') {
if (s.top==-1) {
cnt++;
push(&s,'{',i);
}
else {
temp=pop(&s); p[i]=p[temp]='!';
}
}
}
i=0;
for (i=0;i<len;i++) {
if (p[i]!='!') {
k++;
}
}
if (s.top!=-1) {
cnt += k/2;
}
printf("%d. %ld\n",t,cnt);
}
return 0;
}
| true |
41bad805c7ab4a7878340ad4b5dbc3ca262cbab7 | C++ | eldridger/dataexchange-diffmerge | /src/Merger.cpp | UTF-8 | 7,593 | 3.078125 | 3 | [] | no_license |
#include <vector>
#include <iostream>
#include <string>
#include "Merger.h"
//merged node, new node
void setFlags(Node* mNode, Node* nNode) {
//Neither are empty = DIFF
std::vector<Node*>::iterator it1 = mNode->children.begin();
std::vector<Node*>::iterator it2 = nNode->children.begin();
while (it1 != mNode->children.end()) {
while (it2 != nNode->children.end()) {
if ((*it1)->isMerge != (*it2)->isMerge) {
(*it1)->isMerge = (*it2)->isMerge;
std::cout << "MERGEFLAG: " << (*it1)->fullString << std::endl;
}
if ((*it1)->isDiff != (*it2)->isDiff) {
(*it1)->isDiff = (*it2)->isDiff;
std::cout << "DIFFFLAG: " << (*it1)->fullString << std::endl;
}
if ((*it1)->hasChange != (*it2)->hasChange) {
(*it1)->hasChange = (*it2)->hasChange;
std::cout << "CHANGEFLAG: " << (*it1)->fullString << std::endl;
}
++it2;
}
++it1;
}
}
Node* Merger::merge(const Node * node1, const Node * node2) {
Node* mergedNode = node1->clone();
Node* first = node1->clone();
Node* second = node2->clone();
//Copy vector of nodes to lists to avoid iterator invalidation of removing mid-vector
//std::list<Node*> first;
//std::copy(node1->children.begin(), node1->children.end(), std::back_inserter(first));
//std::list<Node*> second;
//std::copy(node2->children.begin(), node2->children.end(), std::back_inserter(second));
//std::copy(node1->children.begin(), node1->children.end(), std::back_inserter(mergedNode->children));
std::cout << "FIRST: " << first->children.size() << std::endl << "SECOND: " << second->children.size() << std::endl;
if (first->fullString != second->fullString) {
//std::list<Node*>::iterator it = first.begin();
//std::list<Node*>::iterator innerIT = second.begin();
std::vector<Node*>::iterator it = first->children.begin();
std::vector<Node*>::iterator innerIT = second->children.begin();
std::cout << std::endl << "COMPARING: " << std::endl;
std::cout << std::right << first->fullString << std::endl;
std::cout << std::left << "WITH: " << std::endl;
std::cout << std::right << second->fullString << std::endl << std::endl << std::endl;
std::cout << "Children of Node 1..." << std::endl;
int i = 1;
while (it != first->children.end()) {
std::cout << "Child " << i << ": " << (*it)->fullString << std::endl;
i++;
it++;
}
std::cout << "Children of Node 2..." << std::endl;
i = 1;
while (innerIT != second->children.end()) {
std::cout << "Child " << i << ": " << (*innerIT)->fullString << std::endl;
i++;
innerIT++;
}
it = first->children.begin();
innerIT = second->children.begin();
while (it != first->children.end()) {
if (innerIT == second->children.end()) {
innerIT = second->children.begin();
}
while (innerIT != second->children.end()) {
std::string firstString = (*it)->fullString;
std::string secondString = (*innerIT)->fullString;
if (firstString == secondString) {
//it = first.erase(it);
//innerIT = second.erase(innerIT);
(*it)->matched = true;
(*innerIT)->matched = true;
++it;
++innerIT;
break;
}
else {
if (innerIT != second->children.end()) ++innerIT;
}
}
if(it != first->children.end()) ++it;
}
it = first->children.begin();
innerIT = second->children.begin();
int firstSize = first->children.size();
int secondSize = second->children.size();
while (it != first->children.end()) {
if ((*it)->matched) {
firstSize--;
}
++it;
}
while (innerIT != second->children.end()) {
if ((*innerIT)->matched) {
secondSize--;
}
++innerIT;
}
std::cout << "Sizes after matching nodes" << std::endl;
std::cout << "FIRST SIZE: " << firstSize << std::endl << "SECOND SIZE: " << secondSize << std::endl;
//if (first.empty() && second.empty()) {
if (firstSize == 0 && secondSize == 0) {
std::cout << "Nodes are the same! nothing to diff/merge!" << std::endl;
}
else if (firstSize == 0) {// first.empty()) {
//FIRST EMPTY = ADDITION MERGE
std::cout << "First is empty!!!" << std::endl;
std::cout << "BEFORE FIRST EMPTY: " << std::endl;
std::vector<Node*>::iterator it = second->children.begin();
unsigned int index = 0;
while (it != second->children.end()) {
if (!(*it)->matched) {
std::cout << (*it)->fullString << " -- ";
(*it)->isMerge = true;
(*it)->matched = true;
second->children.insert(it, new ValueNode("++++", false));
it = second->children.begin() + ++index;
++it;
}
if(it != second->children.end()) ++it;
}
mergedNode = second->clone();
mergedNode->setFullString();
//std::cout << "FULLSTRING: " << mergedNode->fullString << std::endl;
}
else if (secondSize == 0){// second.empty()) {
//SECOND EMPTY = REMOVAL MERGE
std::cout << "Second is empty!!!" << std::endl;
std::vector<Node*>::iterator it = first->children.begin();
std::vector<Node*>::iterator secondit = second->children.begin();
int index = 0;
//Match remaining nodes in first with node1 and set isMerge to true
while (it != first->children.end()) {
if (!(*it)->matched) {
(*it)->isMerge = true;
second->children.insert(secondit, new ValueNode("----", false));
secondit = second->children.begin() + index;
++secondit;
}
if (it != first->children.end()) ++it;
if (secondit != second->children.end()) ++secondit;
++index;
}
mergedNode = second->clone();
mergedNode->setFullString();
std::cout << "FULLSTRING: " << mergedNode->fullString << std::endl;
}
else {
//Neither are empty = DIFF
std::vector<Node*>::iterator it = first->children.begin();
std::vector<Node*>::iterator innerIT = second->children.begin();
while (it != first->children.end()) {
//std::cout << "GETTING CHANGE FLAG" << (*it)->fullString << std::endl;
if (!(*it)->matched) (*it)->hasChange = true;
++it;
}
while (innerIT != second->children.end()) {
//std::cout << "GETTING CHANGE FLAG" << (*innerIT)->fullString << std::endl;
if (!(*innerIT)->matched) (*innerIT)->hasChange = true;
++innerIT;
}
it = first->children.begin();
innerIT = second->children.begin();
//std::cout << "SDFDSADSFDSAFDSAFDSAFDSAFDSAFDSAFDSA: " << std::endl;
while (it != first->children.end()) {
//std::cout << "first-- " << (*it)->fullString << std::endl << std::endl;
if (innerIT == second->children.end()) {
innerIT = second->children.begin();
}
int index = 0;
while (innerIT != second->children.end()) {
//std::cout << "second-- " << (*it)->fullString << std::endl << std::endl;
if (!(*it)->matched && !(*innerIT)->matched) {
Node* m = merge(*it, *innerIT);
m->setFullString();
second->children.erase(innerIT);
innerIT = second->children.begin() + index;
second->children.insert(innerIT, m);
innerIT = second->children.begin() + index;
innerIT++;
index++;
second->setFullString();
std::cout << "merged return-- " << m->fullString << std::endl << std::endl;
}
if(innerIT != second->children.end()) ++innerIT;
++index;
}
++it;
}
mergedNode = second->clone();
}
}
else {
std::cout << "Nodes are the same! nothing to diff/merge!" << std::endl;
}
return mergedNode;
}
void Merger::print(std::list<Node*> printList) {
std::cout << "*********** MERGED ***********" << std::endl << std::endl;
for (std::list<Node*>::const_iterator it = printList.begin(); it != printList.end(); ++it) {
std::cout << (*it)->fullString << std::endl;
}
}
| true |
33e6d034e0f2191c7083954c4779f62489da63b0 | C++ | daniil6/RBKLib | /src/parse_string_v1/parsestring_v1.cpp | UTF-8 | 4,782 | 2.859375 | 3 | [] | no_license | #include "parse_string_v1/parsestring_v1.h"
CParseStringV1::CParseStringV1()
{
m_root = nullptr;
}
CParseStringV1::~CParseStringV1()
{
}
void CParseStringV1::DeleteTree(StringTree* node)
{
if(node != nullptr) {
DeleteTree(node->GetLeft());
DeleteTree(node->GetRight());
delete node;
node = nullptr;
}
}
void CParseStringV1::TreeCopyProcess(StringTree* tree, StringTree* treeCopy)
{
if(tree->GetLeft() != nullptr || tree->GetRight() != nullptr) {
treeCopy->SetLeft(new StringTree(tree->GetLeft()->GetData()));
TreeCopyProcess(tree->GetLeft(), treeCopy->GetLeft());
treeCopy->SetRight(new StringTree(tree->GetRight()->GetData()));
TreeCopyProcess(tree->GetRight(), treeCopy->GetRight());
treeCopy->SetData(tree->GetData());
}
}
StringTree* CParseStringV1::TreeCopy(StringTree* tree)
{
StringTree* treeCopy = new StringTree("_");
TreeCopyProcess(tree, treeCopy);
return treeCopy;
}
StringTree* CParseStringV1::Make(std::string str_entry)
{
m_root = new StringTree(str_entry);
for(auto rit = str_entry.rbegin(); rit != str_entry.rend(); ++rit)
if(*rit == '*' || *rit == '/' || rit == str_entry.rend() - 1)
TraversalTree(m_root);
return m_root;
}
std::string CParseStringV1::CharToString(char symbol)
{
std::string chartostring = "";
chartostring += symbol;
return chartostring;
}
void CParseStringV1::CreatTree(StringTree* node, char signOne, char signTwo)
{
std::string str = node->GetData();
std::stack<std::string> stackBorder;
std::string content;
for(auto rit = str.rbegin(); rit != str.rend(); ++rit) {
if(*rit == ')')
stackBorder.push("skobka");
if(*rit == '(') {
if(!stackBorder.empty())
stackBorder.pop();
else {
// wxMessageBox(wxT("Error. Something wrong"));
break;
}
}
if(stackBorder.empty()) {
if(*rit == signOne || *rit == signTwo) {
if(!content.empty()) {
node->SetData(CharToString(*rit));
node->SetLeft(new StringTree(content));
node->SetRight(new StringTree(CharToString('0')));
node = node->GetRight();
content.clear();
}
} else
content.insert(0, CharToString(*rit));
} else
content.insert(0, CharToString(*rit));
}
if(!content.empty())
node->SetData(content);
}
void CParseStringV1::DeleteBracket(StringTree* node)
{
if(node != nullptr) {
DeleteBracket(node->GetLeft());
DeleteBracket(node->GetRight());
std::string str = node->GetData();
while(str.back() == '\0')
str.pop_back();
if(str.front() == '(' && str.back() == ')')
str = str.substr(1, str.find_last_of(str.back()) - 1);
node->SetData(str);
}
}
bool CParseStringV1::CheckPlusMinusSign(std::string str)
{
bool nosign = false;
std::stack<std::string> stackBorder;
for(auto rit = str.rbegin(); rit != str.rend(); ++rit) {
if(*rit == ')')
stackBorder.push("skobka");
if(*rit == '(') {
if(!stackBorder.empty())
stackBorder.pop();
else {
// wxMessageBox(wxT("Error. Something wrong"));
break;
}
}
if(stackBorder.empty())
if(*rit == '+' || *rit == '-')
nosign = true;
}
return nosign;
}
void CParseStringV1::CheckAggregateFunction(StringTree* node)
{
const std::string MassAggregateFunc[6] = { "SUM", "MAX", "MIN", "CNT", "AVG", "MDN" };
std::string str = node->GetData();
while(str.back() == '\0')
str.pop_back();
for(int i = 0; i < 6; i++) {
if(str.find(MassAggregateFunc[i]) != std::string::npos) {
str = str.substr(3);
if(str.front() == '(' && str.back() == ')')
str = str.substr(1, str.find_last_of(str.back()) - 1);
node->SetData(MassAggregateFunc[i]);
node->SetLeft(new StringTree(CharToString('0')));
node->SetRight(new StringTree(str));
i = 6;
}
}
}
void CParseStringV1::TraversalTree(StringTree* node)
{
if(node != nullptr) {
if(CheckPlusMinusSign(node->GetData()))
CreatTree(node, '+', '-');
else {
CreatTree(node, '*', '/');
DeleteBracket(node);
if(node->GetData().size() > 3)
CheckAggregateFunction(node);
}
TraversalTree(node->GetLeft());
TraversalTree(node->GetRight());
}
} | true |
aa1a1e6e9e24d9449dad7a040411e8f0d7900b43 | C++ | ogoodman/serf | /cpp/reactor/data_reader.h | UTF-8 | 931 | 2.75 | 3 | [] | no_license | #ifndef DATA_READER_HPP_
#define DATA_READER_HPP_
#include <serf/reactor/reader.h>
namespace serf {
class DataHandler;
class Reactor;
/** \brief Moves data from a socket to a handler.
*
* Readers are added to the reactor and each time their socket
* becomes ready to read, their run function is called. The
* run function of a DataReader simply reads a chunk of up to 4k
* of data from its socket and passes it to its handler. If the
* socket return 0 bytes, i.e. if it has been closed, the reader
* will remove itself from the reactor, which will, in turn,
* cause it and its DataHandler to be deleted.
*/
class DataReader : public Reader {
public:
DataReader(int fd, DataHandler* handler);
~DataReader();
int fd() const;
void run(Reactor* reactor);
private:
int fd_;
DataHandler* handler_;
};
}
#endif
| true |
11ae84a576072b0e41a25a3fd8705edc191b4a74 | C++ | ailyanlu/acm-code | /template/uni/Geometry/point.cc | UTF-8 | 1,742 | 3.421875 | 3 | [] | no_license | struct point {
double x, y;
point() {
}
point(double _x, double _y) : x(_x), y(_y){};
void input() {
scanf("%lf%lf", &x, &y);
}
void output() {
printf("%.2f %.2f\n", x, y);
}
bool operator==(point a) const {
return dblcmp(a.x - x) == 0 && dblcmp(a.y - y) == 0;
}
bool operator<(point a) const {
return dblcmp(a.x - x) == 0 ? dblcmp(y - a.y) < 0 : x < a.x;
}
double len() {
return hypot(x, y);
}
double len2() {
return x * x + y * y;
}
double distance(point p) {
return hypot(x - p.x, y - p.y);
}
point add(point p) {
return point(x + p.x, y + p.y);
}
point sub(point p) {
return point(x - p.x, y - p.y);
}
point mul(double b) {
return point(x * b, y * b);
}
point div(double b) {
return point(x / b, y / b);
}
double dot(point p) //点积
{
return x * p.x + y * p.y;
}
double det(point p) //叉积
{
return x * p.y - y * p.x;
}
double rad(point a, point b) {
point p = *this;
return fabs(
atan2(fabs(a.sub(p).det(b.sub(p))), a.sub(p).dot(b.sub(p))));
}
point trunc(double r) {
double l = len();
if (!dblcmp(l))
return *this;
r /= l;
return point(x * r, y * r);
}
point rotleft() {
return point(-y, x);
}
point rotright() {
return point(y, -x);
}
point rotate(point p, double angle) //绕点p逆时针旋转angle角度
{
point v = this->sub(p);
double c = cos(angle), s = sin(angle);
return point(p.x + v.x * c - v.y * s, p.y + v.x * s + v.y * c);
}
}; | true |
5c06cd7619d338458ada61ec8a7a08be5f08e54e | C++ | b04902009/2018-fc | /hw1/hw1.cpp | UTF-8 | 2,793 | 3.59375 | 4 | [] | no_license | /*****************************************************************************************
Write a program to price the American put and its delta based on the CRR binomial tree.
Inputs: (1) S (spot price), (2) X (strike price), (3) r (risk-free interest rate),
(4) s (volatility), (5) T (years), (6) n (number of periods).
Output: put price and delta.
For example, assume S = 100, X = 105, r = 0.03, s = 0.25, T = 1, and n = 300.
Then the put price is 11.4336 and the delta is −0.5066.
*****************************************************************************************/
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double S, X, T, s, r;
int n;
printf("Spot price: "); scanf("%lf", &S);
printf("Strike price: "); scanf("%lf", &X);
printf("Risk-free interest rate: "); scanf("%lf", &r);
printf("Volatility: "); scanf("%lf", &s);
printf("Maturity in years: "); scanf("%lf", &T);
printf("Number of periods: "); scanf("%d", &n);
double R = exp(r * T/n);
double u = exp(s * sqrt(T/n)), d = 1 / u;
double p = (R-d) / (u-d);
// Initial values at time t
/*
The CRR method ensures that the tree is recombinant.
This property allows that the value at each final node be calculated directly by
S_n = S * u^(N_u - N_d)
where N_u(N_d) is the number of up(down) ticks.
*/
double P[n+1];
for(int i = 0; i <= n; i++){
double Sn = S * pow(u, 2*i-n); // N_u = i, N_d = n-i => N_u - N_d = 2*i-n
P[i] = X - Sn; // The option value at each final node = Strike price - Spot price
if(P[i] < 0) P[i] = 0;
}
// Move to earlier times
/*
C_{t-\Delta t,i} = (p*C_{t,i+1} + (1-p)*C_{t,i-1}) / R,
where C_{t,i} is the option's value for the i^th node at time t.
=> C_{t-\Delta t,i} = p0 * C_{t,i+1} + p1 *C_{t,i-1}),
where p0 = p / R and p1 = (1-p) / R
*/
double p0 = p / R;
double p1 = (1-p) / R;
double h; // hedge ratio
for(int j = n-1; j >= 0; j--){ // period j
for(int i = 0; i <= j; i++){ // node i
P[i] = p0 * P[i+1] + p1 * P[i]; // Binomial value C_{j,i}
double e = X - S * pow(u, 2*i-j); // Exercise value
if(P[i] < e) P[i] = e; // American option: value = max(Binomial Value, Exercise Value)
}
if(j == 1)
h = (P[1]-P[0])/(S*u-S*d);
}
printf("American put price: %lf\nDelta: %lf\n", P[0], h);
return 0;
}
/*
S = 50; X = 50; r = 0.05; s = 0.2; T = 0.5; n = 100;
put price: 2.3246
delta: -0.432792
S = 100, K = 105, r = 0.03, s = 0.25, T = 1, and n = 300
put price: 11.4336
delta: −0.5066
*/
| true |
630191f543311d94d8dd29dc34e0aa62a6f31dc6 | C++ | SBNSoftware/sbndaq-artdaq | /sbndaq-artdaq/Generators/SBND/NevisTPC/nevishwutils/TimeUtils.cpp | UTF-8 | 407 | 2.59375 | 3 | [] | no_license | #include "TimeUtils.h"
namespace nevistpc {
long diff_time_microseconds(struct timeval t2, struct timeval t1){
return (t2.tv_sec*1e6 + t2.tv_usec - t1.tv_sec*1e6 - t1.tv_usec);
}
float diff_time_milliseconds(struct timeval t2, struct timeval t1){
float micro = (float)(t2.tv_sec*1e6 + t2.tv_usec - t1.tv_sec*1e6 - t1.tv_usec);
return micro/1000.;
}
} // end of namespace nevistpc
| true |
7f335332c80bd19bf3ae85abb15ffed0da720df4 | C++ | pm95/Duplicate-Remover | /LinkedList.h | UTF-8 | 1,272 | 3.890625 | 4 | [] | no_license | #ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include "Node.h"
template <class T>
class LinkedList
{
public:
Node<T> *head;
Node<T> *tail;
LinkedList()
{
this->head = nullptr;
this->tail = nullptr;
}
~LinkedList()
{
while (this->head != nullptr)
{
Node<T> *temp = this->head;
this->head = this->head->next_node;
delete temp;
}
}
void add_node(T data)
{
Node<T> *node = new Node<T>(data);
this->_add_to_end(node);
}
void print()
{
Node<T> *head = this->head;
while (head != nullptr)
{
std::cout << head->data << " --> ";
head = head->next_node;
}
std::cout << "NULL" << std::endl;
}
private:
void _add_to_end(Node<T> *node)
{
// if list is empty, add this node as head of the list
if (this->head == nullptr)
this->head = node;
// if list is empty, add this node as tail of the list also
if (this->tail == nullptr)
this->tail = node;
else
{
this->tail->next_node = node;
this->tail = this->tail->next_node;
}
}
};
#endif | true |
acfae5cd4a5ebede5509aa83417f3dcfaa57510f | C++ | lulzzz/ChildProcess | /src/ChildProcess.Native/ErrnoExceptions.hpp | UTF-8 | 543 | 2.59375 | 3 | [
"MIT"
] | permissive | // Copyright (c) @asmichi (https://github.com/asmichi). Licensed under the MIT License. See LICENCE in the project root for details.
#pragma once
class ErrnoError
{
public:
ErrnoError(int err) noexcept : err_(err) {}
int GetError() const noexcept { return err_; }
private:
const int err_;
};
class CommunicationError : public ErrnoError
{
public:
CommunicationError(int err) noexcept : ErrnoError(err) {}
};
class BadRequestError : public ErrnoError
{
public:
BadRequestError(int err) noexcept : ErrnoError(err) {}
};
| true |
9b25536bac15df19ada6a47bf7ebc2c175393f70 | C++ | FPStudies/ALHE_CardStacking | /Cards_heuristics/tests/testNormal.h | UTF-8 | 2,382 | 3.296875 | 3 | [] | no_license | /**
* @file testNormal.h
* @brief Plik klasy podstawowego testu
*
*/
#ifndef TEST_NORMAL_H
#define TEST_NORMAL_H
#include "testInterface.h"
#include "testCardsHeuristic.h"
#include <fstream>
#include <iostream>
#include <sstream>
/**
* @brief Klasa podstawowego testu
*
*/
class TestNormal: public TestCardsHeuristic{
/**
* @brief Nazwy trybów działania programu
*
*/
const static char* keyword[4];
public:
/**
* @brief Stwórz nowy obiekt Test Normal
*
* @param int maksymalna ilość pokoleń
*/
TestNormal(const unsigned int& maxNumberOfIterations);
/**
* @brief Usuń obiekt Test Normal
*
*/
virtual ~TestNormal();
/**
* @brief Stwórz nowy obiekt Test Normal kopiując inny
*
* @param other obiekt do skopiowania
*/
TestNormal(const TestNormal& other);
/**
* @brief Uruchom odpowiedni test metody genetycznej
*
* @param keyword nazwa trybu działania
* @param path ścieżka do pliku z poleceniami
*/
virtual int runTest(const std::string& keyword, const std::string& path) override;
/**
* @brief Uruchom test metody genetycznej
*
* @param path ścieżka do pliku z poleceniami
*/
virtual void runTestBasic(const std::string& path) override;
/**
* @brief Uruchom test algorytmu genetycznego z minimalnym wypisem do strumienia
*
* @param path ścieżka do pliku z poleceniami
* @return int reprezentacja wyniku
*/
virtual int runTestSilent(const std::string& path) override;
/**
* @brief Uruchom test algorytmu zachłannego
*
* @param path ścieżka do pliku z poleceniami
*/
virtual void runTestHeuristic(const std::string& path) override;
/**
* @brief Uruchom test algorytmu z minimalnym wypisem do strumienia
*
* @param path ścieżka do pliku z poleceniami
* @return int reprezentacja wyniku
*/
virtual int runTestHeuristicSilent(const std::string& path) override;
/**
* @brief Kopiowanie obiektu klasy TestNormal
*
* @return TestNormal* wskaźnik na kopię
*/
virtual TestNormal* clone() const override;
/**
* @brief Sprawdź czy string jest trybem działania programu
*
* @param word string
* @return true jest
* @return false nie jest
*/
virtual bool isKeyword(const std::string& word) const override;
};
#endif | true |
a16c669d0c8f102607f46cd90937d692a67629b3 | C++ | THU-changc17/Hotel-reservation-and-management | /src/data_object.h | UTF-8 | 3,076 | 2.59375 | 3 | [] | no_license | #ifndef DATA_OBJECT_H
#define DATA_OBJECT_H
#include"all_headers.h"
#include"connection.h"
class client_user
{
private:
QString sid,pwd;
public:
explicit client_user();
explicit client_user(const QString &nsid,const QString &npwd);
virtual QString get_sid() const;
virtual QString get_pwd() const;
virtual void set_sid(const QString &nsid); //名词前加n均表示new,用于赋值
virtual void set_pwd(const QString &npwd);
void load_database(const QString &sid);
};
class customer:public client_user
{
private:
QString sid,pwd;
public:
void set_sid(const QString &nsid);
void set_pwd(const QString &npwd);
QString get_sid() const;
QString get_pwd() const;
void save_database_reg()const;
bool load_database(const QString &sid,const QString &pwd)const;
};
class adminer:public client_user
{
private:
QString sid,pwd;
public:
void set_sid(const QString &nsid);
void set_pwd(const QString &npwd);
QString get_sid() const;
QString get_pwd() const;
void save_database_reg()const;
bool load_database(const QString &sid,const QString &pwd)const;
};
class hotel
{
private:
QString id,name,star,city,area,evaluation;
public:
explicit hotel();
explicit hotel(QString nid,QString nname,QString nstar,QString ncity,QString narea,QString nevaluation);
QString get_id()const;
QString get_name()const;
QString get_star()const;
QString get_city()const;
QString get_area()const;
QString get_roomtype()const;
QString get_price()const;
QString get_evaluation()const;
void load_database(QString nid);
void load_database_name(QString nname);
void save_database()const;
};
struct room
{
QString num;
QString roomtype;
QString price;
QString message;
QString hotelname;
struct room *next;
};
class linkedlist
{
public:
linkedlist();
int len;
struct room data;
struct room * add(QString nnum,QString nroomtype,QString nprice,QString nmessage,QString hotelname);
struct room* createlist(QString hotelname);
void display(struct room *head,QString hotelname);
struct room * delet(QString nnum,QString hotelname);
void save_database_reg(QString nnum);
QString search(struct room *head,QString nnum);
room* get_head();
room *head;
};
class order
{
private:
QString name,idcard,phonenumber,roomnum,hotelname,time;
public:
explicit order();
explicit order(QString nname,QString nidcard,QString nphonenumber,QString nroomnum,QString nhotelname,QString ndays);
QString get_name()const;
QString get_idcard()const;
QString get_phonenumber()const;
QString get_roomnum()const;
QString get_hotelname()const;
QString get_time()const;
void save_database()const;
};
class plat
{
private:
QString phone,name,star,city,area,state;
public:
explicit plat();
explicit plat(QString nphone,QString nname,QString nstar,QString ncity,QString narea,QString nstate);
void save_database()const;
};
#endif // DATA_OBJECT_H
| true |
f97bee720ef3de187c1153df8313c0616e43c921 | C++ | UTEC-PE/binary-tree-Joe-08 | /iterador.h | UTF-8 | 676 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include "nodo.h"
using namespace std;
class iterador{ // Falta
private:
Nodo *corriente;
public:
stack<Nodo*> miStack;
iterador(){
corriente = NULL;
}
iterador(Nodo* nodo){
this->corriente = nodo;
}
iterador operator++(){
miStack.pop();
corriente = miStack.top();
}
bool operator!=(iterador other){
return corriente->dato != other.corriente->dato;
}
int operator*(){
return corriente->dato;
}
iterador setStack(stack<Nodo*> s){
miStack = s;
return *this;
}
iterador begin(){
this->corriente = miStack.top();
return *this;
}
}; | true |
7d77bd96abb29037faac163e1b7f77c8e2d3ac66 | C++ | rimsa/GameSelector | /include/GameSelector/util/GameSort.h | UTF-8 | 922 | 2.640625 | 3 | [] | no_license | #ifndef GAMESORT_H
#define GAMESORT_H
#include <QObject>
class Game;
class GameComparator;
class GameSort : public QObject {
Q_OBJECT
Q_ENUMS(OrderType)
public:
enum OrderType {
ByName,
ByGenre,
ByDeveloper,
ByPublisher,
ByYear,
BySize,
};
friend class GameComparator;
GameSort(OrderType type = ByName, Qt::SortOrder order = Qt::AscendingOrder, QObject* parent = 0);
virtual ~GameSort();
OrderType type() const { return m_type; }
void setType(OrderType type);
Qt::SortOrder order() const { return m_order; }
void setOrder(Qt::SortOrder order);
public slots:
void sort(QList<Game*>& games);
signals:
void typeChanged(GameSort::OrderType type);
void orderChanged(Qt::SortOrder order);
private:
OrderType m_type;
Qt::SortOrder m_order;
};
Q_DECLARE_METATYPE(GameSort::OrderType)
#endif // GAMESORT_H
| true |
1dbba091bbb301f3446651834edfca4dcf087b43 | C++ | AliTaheriNastooh/LightOJ_Problem | /Q1019/main.cpp | UTF-8 | 2,048 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
#define MAX1 102
#define inf 1<<7
vector<int > arr[MAX1];
vector<int> weight[MAX1];
int dikstra(int s,int t){
int visited[MAX1];
int color1[MAX1];
int dis[MAX1];
priority_queue<pair<int ,int> > q;
memset(visited,0, sizeof(visited));
memset(color1,0, sizeof(color1));
memset(dis,inf,sizeof(dis));
dis[s]=0;
color1[s]=1;
q.push(make_pair(0,s));
while(!q.empty()){
pair<int,int> u=q.top();
q.pop();
if(color1[u.second]==2)continue;
if(u.second==t)return dis[u.second];
color1[u.second]=2;
for(int i=0;i<arr[u.second].size();i++){
int v=arr[u.second][i];
if(color1[v]==0){
color1[v]=1;
dis[v]=dis[u.second]+weight[u.second][i];
q.push(make_pair(dis[u.second]+weight[u.second][i],v));
}
if(color1[v]==1 && dis[v]>dis[u.second]+weight[u.second][i]){
// q.push(make_pair(v,u.second+weight[u.second][i]));
dis[v]=dis[u.second]+weight[u.second][i];
}
}
}
return inf;
}
int main() {
int T;cin>>T;
for(int t=0;t<T;t++){
int n;cin>>n;
int m;cin>>m;
map<pair<int,int>,int> mp;
for(int i=0;i<MAX1;i++){
arr[i].clear();
weight[i].clear();
}
for(int i=0;i<m;i++){
int u;cin>>u;
int v;cin>>v;
int w;cin>>w;
arr[u].push_back(v);
int res=inf;
auto it=mp.find(make_pair(u,v));
if(it!=mp.end()){
res=it->second;
}
mp[make_pair(u,v)]=min(res,w);
weight[u].push_back(min(res,w));
}
cout<<"Case "<<t+1<<": ";
int res=dikstra(1,n);
if(res==inf){
cout<<"Impossible"<<endl;
}else{
cout<<res<<endl;
}
}
return 0;
} | true |
80fa2447871d77e0138c5c3b758f45982965274d | C++ | karak/TopologyOriented | /Graph.h | WINDOWS-1257 | 18,623 | 2.78125 | 3 | [] | no_license | #pragma once
#include "Vector2.h"
#include "Geometry.h"
typedef std::size_t index_t;
static const index_t NOTHING = -1;
class RegionItemBase
{
public:
RegionItemBase() : he_(NOTHING)
{
}
RegionItemBase(index_t he) : he_(he)
{
}
index_t boundingHalfedge() const
{
return he_;
}
private:
index_t he_; //one of bounding halfedge CCW
};
class RegionItem : public RegionItemBase
{
public:
RegionItem() : RegionItemBase(), site_()
{
}
//of Euclid plane
RegionItem(index_t he, const Vector2& site) : RegionItemBase(he), site_(site)
{
}
const Vector2C site() const
{
return Vector2C(site_);
}
private:
Vector2 site_;
};
class RegionItemC : public RegionItemBase
{
public:
RegionItemC() : RegionItemBase(), site_()
{
}
//of infinite plane
RegionItemC(index_t he) : RegionItemBase(he), site_(Vector2C::infinity())
{
}
const Vector2C& site() const
{
return site_;
}
private:
Vector2C site_;
};
class EdgeItem
{
public:
/***
* @param vs start vertex id
* @param ve end vertex id
* @param rl left region id
* @param rr right region id
* @param b bisector cache
*/
EdgeItem(index_t vs, index_t ve, index_t rl, index_t rr, const Line2& b) : bisector_(b)
{
v[0] = vs;
v[1] = ve;
r[0] = rl;
r[1] = rr;
}
EdgeItem() : bisector_()
{
v[0] = v[1] = NOTHING;
r[0] = r[0] = NOTHING;
}
EdgeItem(const EdgeItem& rhs) : bisector_(rhs.bisector_)
{
v[0] = rhs.v[0];
v[1] = rhs.v[1];
r[0] = rhs.r[0];
r[1] = rhs.r[1];
}
index_t startVertex() const { return v[0]; }
index_t endVertex() const { return v[1]; }
const Line2& bisector() const { return bisector_; }
static index_t forwardHalfedge(index_t e)
{
return e << 1;
}
static index_t backwardHalfedge(index_t e)
{
return e << 1 | 1;
}
static index_t forwardBit(index_t he)
{
return he & 1;
}
static index_t backwardBit(index_t he)
{
return forwardBit(he) ^ 1;
}
static index_t parentEdge(index_t he)
{
return he >> 1;
}
private:
friend class RootGraph;
index_t v[2];
index_t r[2];
Line2 bisector_;
};
class VertexItem
{
public:
static const std::size_t DEGREE = 3;
VertexItem()
{
std::fill(halfedges, halfedges + DEGREE, NOTHING);
}
VertexItem(const VertexItem& rhs)
{
std::copy(rhs.halfedges, rhs.halfedges + DEGREE, halfedges);
}
//out-halfedges in CCW-order
VertexItem(index_t he0, index_t he1, index_t he2, const Circumcircle& circumcircle) : circumcircle(circumcircle)
{
halfedges[0] = he0;
halfedges[1] = he1;
halfedges[2] = he2;
}
index_t halfedgeCW(index_t he) const
{
return halfedges[(indexOf(he) + 2) % DEGREE];
}
index_t halfedgeCCW(index_t he) const
{
return halfedges[(indexOf(he) + 1) % DEGREE];
}
index_t halfedgeAround(std::size_t i) const
{
return halfedges[i];
}
template<typename FuncT>
FuncT forEachHalfedge(FuncT f) const
{
return std::for_each(halfedges, halfedges + DEGREE, f);
}
//out-halfedges in CCW order
index_t halfedges[DEGREE];
Circumcircle circumcircle;
private:
int indexOf(index_t he) const;
};
#include <array>
class RootGraph
{
public:
RootGraph(const Vector2& p0, const Vector2& p1, const Vector2& p2);
RootGraph(const RootGraph& rhs);
public:
/* edge/halfedge */
//structure
index_t mateHalfedge(index_t he) const
{
return (he ^ 0x1);
}
index_t startVertexOfEdge(index_t e) const
{
return E[e].startVertex();
}
index_t endVertexOfEdge(index_t e) const
{
return E[e].endVertex();
}
index_t startVertexOfHalfedge(index_t he) const
{
index_t edge = he >> 1;
index_t outBit = he & 0x1;
return E[edge].v[outBit];
}
index_t endVertexOfHalfedge(index_t he) const
{
return startVertexOfHalfedge(mateHalfedge(he));
}
index_t nextHalfedge(index_t he) const
{
return mateHalfedge(
halfedgeCWAroundVertex(startVertexOfHalfedge(he), mateHalfedge(he))
);
}
index_t parentEdge(index_t he) const
{
return EdgeItem::parentEdge(he);
}
index_t forwardHalfedge(index_t e) const
{
return EdgeItem::forwardHalfedge(e);
}
index_t backwardHalfedge(index_t e) const
{
return EdgeItem::backwardHalfedge(e);
}
index_t leftRegionOfHalfedge(index_t he) const
{
index_t e = parentEdge(he);
return E[e].r[EdgeItem::forwardBit(he)];
}
index_t rightRegionOfHalfedge(index_t he) const
{
index_t e = parentEdge(he);
return E[e].r[EdgeItem::backwardBit(he)];
}
template<typename FuncT>
FuncT forEachEdge(FuncT f) const
{
for (index_t e = 0; e < Ne; ++e) f(e);
return f;
}
/* property */
const Line2& bisector(index_t e) const
{
return E[e].bisector();
}
index_t maxIdOfEdge() const
{
return Ne;
}
public:
/* vertex */
index_t halfedgeCWAroundVertex(index_t v, index_t he) const
{
return V[v].halfedgeCW(he);
}
index_t halfedgeCCWAroundVertex(index_t v, index_t he) const
{
return V[v].halfedgeCCW(he);
}
index_t halfEdgeAroundVertex(index_t v, std::size_t i) const
{
return V[v].halfedgeAround(i);
}
index_t regionAroundVertex(index_t v, std::size_t i) const
{
return leftRegionOfHalfedge(halfEdgeAroundVertex(v, i));
}
template<typename FuncT>
FuncT forEachHalfedgeAroundVertex(index_t v, FuncT f) const
{
return V[v].forEachHalfedge(f);
}
/* property */
const Circumcircle& circumcircle(index_t v) const
{
return V[v].circumcircle;
}
index_t maxIdOfVertex() const
{
return Nv;
}
public:
/* region */
template<typename FuncT>
FuncT forEachHalfedgeAroundRegion(index_t r, FuncT f) const
{
const auto h0 = boundingHalfedge(r);
auto h = h0;
do
{
f(h);
h = halfedgeCCWAroundRegion(r, h);
} while (h != h0);
return f;
}
template<typename FuncT>
FuncT forEachVertexAroundRegion(index_t r, FuncT f) const
{
forEachHalfedgeAroundRegion(r, [&](index_t he)
{
f(startVertexOfHalfedge(he));
});
return f;
}
index_t halfedgeCCWAroundRegion(index_t r, index_t he) const
{
return halfedgeCWAroundVertex(
endVertexOfHalfedge(he),
mateHalfedge(he)
);
}
template<typename FuncT>
FuncT forEachRegion(FuncT f) const
{
for (index_t r = 0; r < Nr; ++r) f(r);
return f;
}
const Vector2C site(index_t r) const
{
return r == 0? RInf_.site() : R_[r-1].site();
}
index_t maxIdOfRegion() const
{
return Nr;
}
private:
const index_t boundingHalfedge(index_t r) const
{
return regionItem(r).boundingHalfedge();
}
const RegionItemBase& regionItem(index_t r) const
{
return r == 0? static_cast<const RegionItemBase&>(RInf_) : R_[r-1];
}
public:
static const std::size_t Nr = 4;
static const std::size_t NrEuclid = Nr - 1;
static const std::size_t Ne = 6;
static const std::size_t Nv = 4;
RegionItemC RInf_;
std::array<RegionItem, NrEuclid> R_;
std::array<EdgeItem, Ne> E;
std::array<VertexItem, Nv> V;
};
#include <hash_set>
#include <cassert>
template<class GraphT>
class InducedSubgraph
{
public:
/**
* @param G target graph
* @param root id of vertex to start from
* @param p predicate which meet any vertex in subgraph must meet
*/
template<typename PredVertex>
InducedSubgraph(const GraphT& G, const Vector2& site, index_t root, PredVertex pred)
: site_(site), boundaryHalfedges_(), bisectors_(), circumcircles_()
{
std::hash_set<index_t> visitedVertices;
std::vector<index_t> tmpBoundaryHalfEdges;
dfs0(G, root, pred, visitedVertices, tmpBoundaryHalfEdges);
construct(G, site, tmpBoundaryHalfEdges);
}
InducedSubgraph(InducedSubgraph&& rhs)
: site_(rhs.site_)
, n_(rhs.n_)
, boundaryHalfedges_(rhs.boundaryHalfedges_)
, bisectors_(rhs.bisectors_)
, circumcircles_(rhs.circumcircles_)
{
rhs.circumcircles_ = 0;
rhs.bisectors_ = 0;
rhs.boundaryHalfedges_ = 0;
rhs.n_ = 0;
}
private:
//avoid compiler bug(miss-matching)
InducedSubgraph(const InducedSubgraph&);
InducedSubgraph& operator=(const InducedSubgraph&);
public:
~InducedSubgraph()
{
delete[] circumcircles_; circumcircles_ = 0;
delete[] bisectors_; bisectors_ = 0;
delete[] boundaryHalfedges_; boundaryHalfedges_ = 0;
}
const Vector2C site() const
{
return Vector2C(site_);
}
const std::size_t cycleLength() const
{
return n_;
}
index_t halfedgeAroundVertex(index_t v, index_t i) const
{
assert(i < 3);
index_t hes[3];
halfedgesAroundVertex(v, hes);
return hes[i];
}
void halfedgesAroundVertex(index_t v, index_t hes[3]) const
{
hes[0] = boundaryHalfedges_[v];
hes[1] = v;
hes[2] = (v - 1) % n_;
}
/** @attention return as id of super-graph */
index_t boundaryHalfedge(index_t vs) const
{
return boundaryHalfedges_[vs];
}
//for PrintableGraph
template<typename FuncT>
FuncT forEachRegion(FuncT f) const
{
f(static_cast<index_t>(0));
return (f);
}
//for PrintableGraph
const Vector2C site(index_t r) const
{
assert(r == 0);
return site();
}
//for PrintableGraph
template<typename FuncT>
FuncT forEachEdge(FuncT f) const
{
for (index_t e = 0; e < n_; ++e) f(e);
return (f);
}
//for PrintableGraph
index_t startVertexOfEdge(index_t e) const
{
return e;
}
//for PrintableGraph
index_t endVertexOfEdge(index_t e) const
{
return (e + 1) % n_;
}
//for PrintableGraph
const Circumcircle& circumcircle(index_t v) const
{
return circumcircles_[v];
}
//for PrintableGraph
const Line2& bisector(index_t e) const
{
return bisectors_[e];
}
private:
void construct(const GraphT& G, const Vector2& site, const std::vector<index_t>& tmpBoundaryHalfEdges)
{
n_ = tmpBoundaryHalfEdges.size();
if (n_ > 0)
{
boundaryHalfedges_ = new index_t[n_];
bisectors_ = new Line2[n_];
circumcircles_ = new Circumcircle[n_];
//TODO: error handling
for (index_t i = 0; i < n_; ++i)
{
const auto he = tmpBoundaryHalfEdges[i];
const auto rightSite = G.site(G.rightRegionOfHalfedge(he));
const auto leftSite = G.site(G.leftRegionOfHalfedge(he));
const auto b = ::bisector(site, leftSite.asEuclidPoint()); //TODO: ConformalΉ
const auto c = ::circumcircle(Vector2C(site), rightSite, leftSite);
std::clog << "b="<<b<<'\n';
std::clog << "q="<<c.center()<<'\n';
boundaryHalfedges_[i] = he;
bisectors_[i] = b;
circumcircles_[i] = c;
}
}
}
private:
Vector2 site_;
index_t n_; //number of edges/vertices
index_t* boundaryHalfedges_;
Line2* bisectors_;
Circumcircle* circumcircles_;
private:
//depth first search
template<typename PredVertex>
static void dfs0(
const GraphT& G,
index_t root,
PredVertex p,
std::hash_set<index_t>& visitedEdges,
std::vector<index_t>& boundaryHalfEdges
)
{
const bool predResult = p(root);
std::clog << IdString('V', root).c_str() << (predResult? 'o':'x') << '\n';
G.forEachHalfedgeAroundVertex(root, [&](index_t he)
{
InducedSubgraph<GraphT>::dfs(
G,
he,
predResult,
p,
visitedEdges,
boundaryHalfEdges
);
});
}
//depth first search
template<typename PredVertex>
static void dfs(
const GraphT& G,
index_t currentHalfedge,
bool prevPredResult,
PredVertex p,
std::hash_set<index_t>& visitedEdges,
std::vector<index_t>& boundaryHalfEdges
)
{
const auto currentEdge = G.parentEdge(currentHalfedge);
std::clog << "|_" << IdString('E', currentEdge).c_str() << "=>\n";
const auto range = visitedEdges.equal_range(currentEdge);
if (range.first != range.second)
{
std::clog << "<=\n";
return;
}
visitedEdges.insert(range.first, currentEdge); //update
const auto currentVertex = G.endVertexOfHalfedge(currentHalfedge);
const bool predResult = p(currentVertex);
std::clog << " ." << IdString('V',currentVertex).c_str() << (predResult? 'o':'x') << '\n';
if (prevPredResult != predResult)
{
if (predResult)
{
std::clog << " BOUNDARY " << IdString('H', currentHalfedge) << '\n';
std::clog << "<=\n";
boundaryHalfEdges.push_back(currentHalfedge);
return; //end
}
else
{
const auto backHalfedge = G.mateHalfedge(currentHalfedge);
std::clog << " BOUNDARY " << IdString('H', backHalfedge) << '\n';
boundaryHalfEdges.push_back(backHalfedge);
}
}
G.forEachHalfedgeAroundVertex(currentVertex, [&G, predResult, &p, &visitedEdges, &boundaryHalfEdges](index_t he)
{
InducedSubgraph<GraphT>::dfs(G, he, predResult, p, visitedEdges, boundaryHalfEdges);
});
}
};
#include <iostream>
template<class GraphT>
class DifferenceGraph
{
public:
DifferenceGraph(const GraphT& G, InducedSubgraph<GraphT>&& T)
: G_(G)
, T_(std::move(T))
{
}
DifferenceGraph(DifferenceGraph&& rhs)
: G_(rhs.G_)
, T_(std::move(rhs.T_))
{
}
~DifferenceGraph()
{
}
//for PrintableGraph
template<typename FuncT>
FuncT forEachRegion(FuncT f) const
{
G_.forEachRegion(f);
T_.forEachRegion([&](index_t r) { f(r + regionOffset()); });
return f;
}
//for PrintableGraph
const Vector2C site(index_t r) const
{
const auto dr = regionOffset();
return (r < dr)? G_.site(r) : T_.site(r - dr);
}
template<typename FuncT>
FuncT forEachVertexAroundRegion(index_t r, FuncT f) const
{
//when r is of sub-graph
const auto n = T_.cycleLength();
if (r == regionOffset())
{
const auto dv = vertexOffset();
for (index_t v = 0; v < n; ++v)
f(v + dv);
return f;
}
//when r is boolean operated region of super-graph <=> r is left-region of each boundary-halfedge
for (index_t v = 0; v < n; ++v)
{
const auto heFirst = T_.boundaryHalfedge(v);
if (r == G_.leftRegionOfHalfedge(heFirst))
{
f(v);
const auto heLast = G_.mateHalfedge(T_.boundaryHalfedge((v+1)%n));
for (index_t he = heFirst; he != heLast; he = G_.halfedgeCCWAroundRegion(r, he))
{
f(G_.endVertexOfHalfedge(he));
}
return f;
}
}
//when is r is an unmodified region of super-graph
return G_.forEachVertexAroundRegion(r, f);
}
index_t forwardHalfedge(index_t e) const
{
return EdgeItem::forwardHalfedge(e);
}
index_t backwardHalfedge(index_t e) const
{
return EdgeItem::backwardHalfedge(e);
}
//for PrintableGraph
template<typename FuncT>
FuncT forEachEdge(FuncT f) const
{
G_.forEachEdge(f); //TODO: remove filter
T_.forEachEdge([&](index_t e) { f(e + edgeOffset()); });
return f;
}
//for PrintableGraph
index_t startVertexOfEdge(index_t e) const
{
const auto de = edgeOffset();
if (e >= de)
{
const auto dv = vertexOffset();
return T_.startVertexOfEdge(e - de) + dv;
}
else
{
for (index_t v = 0; v < T_.cycleLength(); ++v)
{
const auto heSuper = T_.boundaryHalfedge(v);
const auto e2 = EdgeItem::parentEdge(heSuper);
if (e == e2 && G_.forwardHalfedge(e) == heSuper)
{
const auto dv = vertexOffset();
return v + dv;
}
}
return G_.startVertexOfEdge(e);
}
}
index_t endVertexOfHalfedge(index_t he) const
{
const auto e = parentEdge(he);
return (he == EdgeItem::forwardHalfedge(e))? endVertexOfEdge(e) : startVertexOfEdge(e);
}
//for PrintableGraph
index_t endVertexOfEdge(index_t e) const
{
const auto de = edgeOffset();
const auto dv = vertexOffset();
if (e >= de)
{
return T_.endVertexOfEdge(e - de) + dv;
}
else
{
for (index_t v = 0; v < T_.cycleLength(); ++v)
{
const auto heSuper = T_.boundaryHalfedge(v);
const auto e2 = EdgeItem::parentEdge(heSuper);
if (e == e2 && G_.backwardHalfedge(e) == heSuper)
{
const auto dv = vertexOffset();
return v + dv;
}
}
return G_.endVertexOfEdge(e);
}
}
index_t parentEdge(index_t he) const
{
return EdgeItem::parentEdge(he);
}
index_t leftRegionOfHalfedge(index_t he) const
{
const auto de = edgeOffset();
const auto e = parentEdge(he);
return (e < de)? G_.leftRegionOfHalfedge(he) : (0 + regionOffset());
}
index_t regionAroundVertex(index_t v, index_t i) const
{
const auto dv = vertexOffset();
if (v < dv)
{
return G_.regionAroundVertex(v, i);
}
else
{
switch (i)
{
case 0:
return 0 + regionOffset();
case 1:
return G_.rightRegionOfHalfedge(T_.boundaryHalfedge(v));
case 2:
return G_.leftRegionOfHalfedge(T_.boundaryHalfedge(v));
default:
assert(0);
return NOTHING;
}
}
}
template<typename FuncT>
FuncT forEachHalfedgeAroundVertex(index_t v, FuncT f) const
{
const auto dv = vertexOffset();
return (v < dv)? forEachHalfedgeAroundVertexSuper(v, f) : forEachHalfedgeAroundVertexSub(v - dv, f);
}
//for PrintableGraph
const Circumcircle& circumcircle(index_t v) const
{
const auto dv = vertexOffset();
return (v < dv)? G_.circumcircle(v) : T_.circumcircle(v - dv);
}
//for PrintableGraph
const Line2& bisector(index_t e) const
{
const auto de = edgeOffset();
return (e < de)? G_.bisector(e) : T_.bisector(e - de);
}
index_t maxIdOfRegion() const
{
return G_.maxIdOfRegion() + 1;
}
index_t maxIdOfEdge() const
{
return G_.maxIdOfEdge() + T_.cycleLength();
}
index_t maxIdOfVertex() const
{
return G_.maxIdOfVertex() + T_.cycleLength();
}
private:
index_t edgeOffset() const
{
return G_.maxIdOfEdge();
}
index_t vertexOffset() const
{
return G_.maxIdOfVertex();
}
index_t regionOffset() const
{
return G_.maxIdOfRegion();
}
template<typename FuncT>
FuncT forEachHalfedgeAroundVertexSuper(index_t v, FuncT f) const
{
G_.forEachHalfedgeAroundVertex(v, [this, &f](index_t he)
{
for (index_t v = 0; v < T_.cycleLength(); ++v)
{
if (he == T_.boundaryHalfedge(v))
{
f(v); //boundaryHalfedge of v = v
return;
}
}
f(he);
});
return f;
}
template<typename FuncT>
FuncT forEachHalfedgeAroundVertexSub(index_t v, FuncT f) const
{
index_t hes[3];
T_.halfedgesAroundVertex(v, hes);
f(hes[0]);
f(hes[1]);
f(hes[2]);
return f;
}
private:
const GraphT& G_;
InducedSubgraph<GraphT> T_;
};
| true |
091a91b6072fbade29d7e9a3f18bbe4ea9e8be47 | C++ | 20-1-SKKU-OSS/2020-1-OSS-7 | /C-Plus-Plus/BOJ/14502.cpp | UTF-8 | 1,488 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int N, M; //가로, 세로
int arr[8][8];
int arr2[8][8];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
int result;
void bfs(void)
{
int arr3[8][8];
int number=0;
queue <pair <int, int > > q;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
{
arr3[i][j] = arr2[i][j];
if (arr3[i][j] == 2)
q.push(make_pair(i, j));
}
while (!q.empty())
{
int ny, nx,x,y;
y = q.front().first;
x = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
ny = y + dy[i];
nx = x + dx[i];
if (nx >= 0 && ny >=0 && nx<M && ny<N)
if (arr3[ny][nx] == 0) {
arr3[ny][nx] = 2;
q.push(make_pair(ny, nx));
}
}
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
if (arr3[i][j] == 0)
number++;
result = max(number, result);
}
void makewall(int cnt)
{
if (cnt == 3)
{
bfs();
return;
}
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
if (arr2[i][j] == 0)
{
arr2[i][j] = 1;
makewall(cnt + 1);
arr2[i][j] = 0;
}
}
int main(void)
{
cin >> N >> M;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
cin >> arr[i][j];
for (int i = 0; i<N; i++)
for (int j = 0; j<M; j++)
if (arr[i][j] == 0)
{
for (int m = 0; m < N; m++)
for (int n = 0; n < M; n++)
arr2[m][n] = arr[m][n];
arr2[i][j] = 1;
makewall(1);
arr2[i][j] = 0;
}
cout << result;
return 0;
}
| true |
6d582dc734ea6e76f7d980ec662e50746e991428 | C++ | ju5tinz/GraphicsUFOProject | /Flyer.cpp | UTF-8 | 5,567 | 2.96875 | 3 | [] | no_license | #include "Flyer.h"
Flyer::Flyer(std::string objFilename, GLuint shaderProgram, glm::mat4 model) :
shaderProg(shaderProgram), model(model) {
std::ifstream objFile(objFilename); // Open obj file
// If the file has been opened
if (objFile.is_open()) {
std::vector<GLuint> vertex_indices;
std::vector<GLuint> normal_indices;
std::vector<glm::vec3> input_vertices;
std::vector<glm::vec3> input_normals;
std::string line;
// Read lines from file
while (std::getline(objFile, line)) {
std::stringstream ss;
ss << line;
// Read first char of line
std::string label;
ss >> label;
// If the the first char is v, then it is a vertex
// Add the vertex to the points vector
if (label == "v") {
glm::vec3 point;
ss >> point.x >> point.y >> point.z;
input_vertices.push_back(point);
}
if (label == "vn") {
glm::vec3 normal;
ss >> normal.x >> normal.y >> normal.z;
input_normals.push_back(normal);
}
if (label == "f") {
/*
std::string vec1str, vec2str, vec3str;
std::getline(ss, vec1str, '/');
vec1str.erase(0, 1);
ss.ignore(256, ' ');
std::getline(ss, vec2str, '/');
ss.ignore(256, ' ');
std::getline(ss, vec3str, '/');
GLuint vec1, vec2, vec3;
vec1 = std::stoul(vec1str);
vec2 = std::stoul(vec2str);
vec3 = std::stoul(vec3str);
glm::ivec3 face;
face.x = vec1 - 1;
face.y = vec2 - 1;
face.z = vec3 - 1;
faces.push_back(face);
*/
std::string vertex1, vertex2, vertex3;
GLuint vertexIndex[3], uvIndex[3], normalIndex[3];
//sscanf(ss.str(), "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
std::string token;
std::getline(ss, token, '/');
vertexIndex[0] = atoi(token.c_str());
std::getline(ss, token, '/');
std::getline(ss, token, ' ');
normalIndex[0] = atoi(token.c_str());
//std::getline(ss, token, ' ');
std::getline(ss, token, '/');
vertexIndex[1] = atoi(token.c_str());
std::getline(ss, token, '/');
std::getline(ss, token, ' ');
normalIndex[1] = atoi(token.c_str());
//std::getline(ss, token, ' ');
std::getline(ss, token, '/');
vertexIndex[2] = atoi(token.c_str());
std::getline(ss, token, '/');
std::getline(ss, token, ' ');
normalIndex[2] = atoi(token.c_str());
vertex_indices.push_back(vertexIndex[0]);
vertex_indices.push_back(vertexIndex[1]);
vertex_indices.push_back(vertexIndex[2]);
normal_indices.push_back(normalIndex[0]);
normal_indices.push_back(normalIndex[1]);
normal_indices.push_back(normalIndex[2]);
}
}
for (GLuint i = 0; i < vertex_indices.size(); i++) {
points.push_back(input_vertices[vertex_indices[i]]);
normals.push_back(input_normals[normal_indices[i]]);
indices.push_back(i);
}
}
// If the file cannot be opened
else {
std::cerr << "Can't open the file " << objFilename << std::endl;
}
objFile.close(); //close file
// set max and min points to the first point in points
float max_x = points[0].x;
float min_x = points[0].x;
float max_y = points[0].y;
float min_y = points[0].y;
float max_z = points[0].z;
float min_z = points[0].z;
// find min and max values for x, y, z
for (int i = 1; i < points.size(); i++) {
glm::vec3 point = points[i];
if (point.x > max_x)
max_x = point.x;
if (point.x < min_x)
min_x = point.x;
if (point.y > max_y)
max_y = point.y;
if (point.y < min_y)
min_y = point.y;
if (point.z > max_z)
max_z = point.z;
if (point.z < min_z)
min_z = point.z;
}
// find center for x, y, z
float center_x = (max_x + min_x) / 2;
float center_y = (max_y + min_y) / 2;
float center_z = (max_z + min_z) / 2;
glm::vec3 center_vec = glm::vec3(0, 0, 0);
//float max_dist = 0;
for (int i = 0; i < points.size(); i++) {
points[i].x -= center_x;
points[i].y -= center_y;
points[i].z -= center_z;
}
// Generate a vertex array (VAO) and a vertex buffer objects (VBO).
glGenVertexArrays(1, &vao);
glGenBuffers(2, vbo);
glGenBuffers(1, &ebo);
// Bind to the VAO.
glBindVertexArray(vao);
// Bind to the first VBO. We will use it to store the points.
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
// Pass in the data.
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)* points.size(),
points.data(), GL_STATIC_DRAW);
// Enable vertex attribute 0.
// We will be able to access points through it.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)* normals.size(),
normals.data(), GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
// Bind to the ebo
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
// Pass in the data.
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(),
indices.data(), GL_STATIC_DRAW);
// Unbind from the EBO.
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Unbind from the VAO.
glBindVertexArray(0);
}
void Flyer::draw() {
glUseProgram(shaderProg);
glUniformMatrix4fv(glGetUniformLocation(shaderProg, "model"), 1, GL_FALSE, glm::value_ptr(model));
// Bind to the VAO.
glBindVertexArray(vao);
// Draw triangles
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
// Unbind from the VAO.
glBindVertexArray(0);
}
void Flyer::update(glm::mat4 transform) {
model = transform * model;
} | true |
9f53320ece6838897b33d4b08d2fa6eff55e52fa | C++ | geefr/IKEngine | /src/joint.cpp | UTF-8 | 3,021 | 2.6875 | 3 | [
"BSD-2-Clause"
] | permissive |
#include "joint.h"
#include "limb.h"
#ifdef IKENGINE_OSG
# include <osg/ShapeDrawable>
#endif
namespace IKEngine
{
Joint::Joint( Servo* servo, const vec3& rotationAxis )
: m_servo{ servo }
, m_position{ 0.0, 0.0, 0.0 }
, m_rotation{ 0.0, 0.0, 0.0 }
, m_servoAxis{ rotationAxis }
{
}
Joint::~Joint()
{
}
std::shared_ptr<Limb> Joint::next() const
{
return m_next;
}
void Joint::next( std::shared_ptr<Limb> l )
{
m_next = l;
}
#ifdef IKENGINE_OSG
// All geometry/nodes are created in this method, a fresh set is created every time
osg::ref_ptr<osg::Group> Joint::createOsgGeometry()
{
m_osgTransform = new osg::PositionAttitudeTransform();
m_osgTransform->setReferenceFrame( osg::Transform::ReferenceFrame::RELATIVE_RF );
m_osgTransform->setPosition( osg::Vec3d( m_position.x(), m_position.y(), m_position.z() ) );
// +90 degrees in X for IKEngine -> osg
// Rotation of joint itself
osg::Quat attitude( m_rotation.x() + osg::PI_2, osg::X_AXIS,
m_rotation.y(), osg::Y_AXIS,
m_rotation.z(), osg::Z_AXIS );
// Rotation from the servo
float servoRot{ osg::DegreesToRadians(m_servo->get()) };
osg::Quat servoAttitude( (m_servoAxis.x() * servoRot) + osg::PI_2, osg::X_AXIS,
(m_servoAxis.y() * servoRot), osg::Y_AXIS,
(m_servoAxis.z() * servoRot), osg::Z_AXIS );
m_osgTransform->setAttitude( attitude * servoAttitude ) ;
m_osgGeometry = new osg::Sphere();
m_osgGeometry->setRadius(0.02);
m_osgDrawable = new osg::ShapeDrawable( m_osgGeometry );
m_osgDrawable->setColor( osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f) );
m_osgGeode = new osg::Geode();
m_osgGeode->addDrawable( m_osgDrawable );
m_osgTransform->addChild( m_osgGeode );
if( m_next )
{
m_osgTransform->addChild( m_next->createOsgGeometry() );
}
return m_osgTransform;
}
// Getter for the osg node
osg::ref_ptr<osg::Group> Joint::osgGeometry() const
{
return m_osgTransform;
}
// Call to update the gometry for the robot's parameters
void Joint::updateOsgGeometry()
{
if( !m_osgTransform ) return;
m_osgTransform->setPosition( osg::Vec3d( m_position.x(), m_position.y(), m_position.z() ) );
// +90 degrees in X for IKEngine -> osg
float servoRot{ osg::DegreesToRadians(m_servo->get()) };
osg::Quat attitude( m_rotation.x() + osg::PI_2, osg::X_AXIS,
m_rotation.y(), osg::Y_AXIS,
m_rotation.z(), osg::Z_AXIS );
osg::Quat servoAttitude( (m_servoAxis.x() * servoRot) + osg::PI_2, osg::X_AXIS,
(m_servoAxis.y() * servoRot), osg::Y_AXIS,
(m_servoAxis.z() * servoRot), osg::Z_AXIS );
m_osgTransform->setAttitude( attitude * servoAttitude ) ;
if( !m_next )
{
return;
}
m_next->updateOsgGeometry();
}
#endif
};
| true |
2c6d245c997c42ab2a260ed7c2d3d65ada10f6cf | C++ | simdjson/simdjson | /include/simdjson/generic/dom_parser_implementation.h | UTF-8 | 3,856 | 2.5625 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSL-1.0"
] | permissive | #ifndef SIMDJSON_GENERIC_DOM_PARSER_IMPLEMENTATION_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#define SIMDJSON_GENERIC_DOM_PARSER_IMPLEMENTATION_H
#include "simdjson/generic/base.h"
#include "simdjson/internal/dom_parser_implementation.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
// expectation: sizeof(open_container) = 64/8.
struct open_container {
uint32_t tape_index; // where, on the tape, does the scope ([,{) begins
uint32_t count; // how many elements in the scope
}; // struct open_container
static_assert(sizeof(open_container) == 64/8, "Open container must be 64 bits");
class dom_parser_implementation final : public internal::dom_parser_implementation {
public:
/** Tape location of each open { or [ */
std::unique_ptr<open_container[]> open_containers{};
/** Whether each open container is a [ or { */
std::unique_ptr<bool[]> is_array{};
/** Buffer passed to stage 1 */
const uint8_t *buf{};
/** Length passed to stage 1 */
size_t len{0};
/** Document passed to stage 2 */
dom::document *doc{};
inline dom_parser_implementation() noexcept;
inline dom_parser_implementation(dom_parser_implementation &&other) noexcept;
inline dom_parser_implementation &operator=(dom_parser_implementation &&other) noexcept;
dom_parser_implementation(const dom_parser_implementation &) = delete;
dom_parser_implementation &operator=(const dom_parser_implementation &) = delete;
simdjson_warn_unused error_code parse(const uint8_t *buf, size_t len, dom::document &doc) noexcept final;
simdjson_warn_unused error_code stage1(const uint8_t *buf, size_t len, stage1_mode partial) noexcept final;
simdjson_warn_unused error_code stage2(dom::document &doc) noexcept final;
simdjson_warn_unused error_code stage2_next(dom::document &doc) noexcept final;
simdjson_warn_unused uint8_t *parse_string(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept final;
simdjson_warn_unused uint8_t *parse_wobbly_string(const uint8_t *src, uint8_t *dst) const noexcept final;
inline simdjson_warn_unused error_code set_capacity(size_t capacity) noexcept final;
inline simdjson_warn_unused error_code set_max_depth(size_t max_depth) noexcept final;
private:
simdjson_inline simdjson_warn_unused error_code set_capacity_stage1(size_t capacity);
};
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
inline dom_parser_implementation::dom_parser_implementation() noexcept = default;
inline dom_parser_implementation::dom_parser_implementation(dom_parser_implementation &&other) noexcept = default;
inline dom_parser_implementation &dom_parser_implementation::operator=(dom_parser_implementation &&other) noexcept = default;
// Leaving these here so they can be inlined if so desired
inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(size_t capacity) noexcept {
if(capacity > SIMDJSON_MAXSIZE_BYTES) { return CAPACITY; }
// Stage 1 index output
size_t max_structures = SIMDJSON_ROUNDUP_N(capacity, 64) + 2 + 7;
structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] );
if (!structural_indexes) { _capacity = 0; return MEMALLOC; }
structural_indexes[0] = 0;
n_structural_indexes = 0;
_capacity = capacity;
return SUCCESS;
}
inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept {
// Stage 2 stacks
open_containers.reset(new (std::nothrow) open_container[max_depth]);
is_array.reset(new (std::nothrow) bool[max_depth]);
if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; }
_max_depth = max_depth;
return SUCCESS;
}
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
#endif // SIMDJSON_GENERIC_DOM_PARSER_IMPLEMENTATION_H | true |
473bb43589b8423d1547f2ff1153a0a74f84e76d | C++ | thatdude-cpu/Codedump | /CC++/pegelstand.cpp | ISO-8859-1 | 981 | 2.609375 | 3 | [
"MIT"
] | permissive | # include <stdlib.h>
# include <stdio.h>
# include <windows.h>
# include <math.h>
void gotoxy (short x, short y)
{
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X=x-1;
pos.Y=y-1;
SetConsoleCursorPosition(hcon , pos);
}
int main (void)
{
int d;
double wert,min=0,max=0,Summe=0.0,durchschnitt=0,schw=0 ;
for(d=0;d<=9;d++)
{
do
{
printf("Bitte Pegelstand fuer %02d:00 eingeben[m]:",d+3);
scanf ("%lf",&wert);
if(wert > 1)
{
printf("Neueingabe\n");
}
}
while((wert<0.0) || (wert > 1));
if (d==1)
{
min=max=wert;
}
else if(wert<min)
{
wert=min;
}
else if(wert>max)
{
max=wert;
}
Summe=Summe+wert;
}
printf("kleinster Pegelstand %lf\n",min);
durchschnitt=Summe/10;
printf("groeter Pegelstand %lf\n",max);
schw=max-min;
printf("groete Pegelschwankung %lf\n",schw);
printf("Durchschnitt %8.2lf\n",durchschnitt);
if(wert<0.25)
{
printf("Achtung Pegelunterschreitung\n");
}
system ("pause");
return 0;
}
| true |
371eb2c457abd4329a83b1dce5040bb1fb4b88f9 | C++ | gumeniukcom/aptu-os | /labs/504/aleksandrov.yuriy/05_filesystem/import.cpp | UTF-8 | 910 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include "meta_fs.h"
#include <string>
using namespace std;
int main (int argc, char *argv[]) {
try
{
if (argc != 4)
{
cout << "Usage: import root host_file fs_file" << endl;
return -2;
}
else
{
Meta_FS fs(argv[1]);
ifstream source(argv[2], ios::binary);
if (!source)
{
throw FSException("Can't open file to import");
}
fs.check_availability(source);
Inode inode = fs.get_inode(argv[3], source);
if (inode.is_dir)
{
throw FSException(string("'") + inode.name + "' is a directory");
}
fs.write_data(inode, source);
}
return 0;
}
catch (const FSException exc)
{
cerr << exc.what() << endl;
return -1;
}
}
| true |
566282f2eed75264a3cb5d97a06b04e7d09e5435 | C++ | Taohid0/C-and-C-Plus-Plus | /GCD again/main.cpp | UTF-8 | 307 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int gcd (int a,int b){
int remainder;
while(1)
{
remainder = a%b;
if(remainder==0){
return b;
}
a = b;
b = remainder;
}
}
int main()
{
cout << gcd(48,6) << endl;
return 0;
}
| true |
8b0968045b25710f8e32992731d0471fa9adac7d | C++ | miyamotononno/atcoder | /others/aoj/DPL/maximum_rectangle/maximum_rect.cpp | UTF-8 | 1,056 | 2.921875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "module.hpp"
using namespace std;
/*
最大長方形問題
https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/3/DPL_3_B
*/
int calcMaximumArea(const vector<vector<int>>& memo) {
int ans = 0;
for (int h=0; h<memo.size(); h++) {
vector<int> d = memo[h];
// for_each(d.begin(), d.end(), [](int x) { std::cout << x << ","; });
ans = max(ans, calcMaximumHistogram(d));
}
return ans;
}
int main(){
int H, W;
cin >> H >> W;
char blocks[H][W];
for (int i=0; i<H; i++) {
for (int j=0; j<W; j++) {
cin >> blocks[i][j];
}
}
vector<vector<int>> memo(H, vector<int>(W)); // 上にどれだけの高さがあるか
for (int h=0; h<H; h++) {
for (int w=0; w<W; w++) {
if (h==0) {
memo[0][w] = blocks[0][w]=='.'?1:0;
continue;
}
memo[h][w] = blocks[h][w]=='.'?memo[h-1][w]+1:0;
}
}
cout << calcMaximumArea(memo) << endl;
return 0;
} | true |
4918a4f599deac11a6d35e949c8d4f7c7608d950 | C++ | antaljanosbenjamin/raytracer | /src/Utils/Scene.cpp | UTF-8 | 12,695 | 2.8125 | 3 | [] | no_license | #include "Utils/Scene.h"
#include <cstring>
#include <iostream>
#include <thread>
#include "Lights/PointLight.h"
int Scene::TRACE_DEPTH = 5;
Scene::Scene(Camera cam_init, int screenW, int screenH, Color *img)
: cam(cam_init), screenWidth(screenW), screenHeight(screenH), mutex(), nextPixelNumber(0),
image(img) {}
Scene::~Scene() {}
void Scene::addObject(std::shared_ptr<Object> object) { objects.emplace_back(std::move(object)); }
void Scene::addLight(std::shared_ptr<Light> light) { lights.emplace_back(std::move(light)); }
void Scene::render() {
std::thread threads[4];
for (int i = 0; i < 4; ++i)
threads[i] = std::thread(Scene::renderTask, this);
for (auto &th : threads)
th.join();
nextPixelNumber = 0;
Color *targetImage = new Color[screenWidth * screenHeight];
for (int i = 0; i < 4; ++i)
threads[i] = std::thread(Scene::smoothTask, this, targetImage);
for (auto &th : threads)
th.join();
std::memcpy(image, targetImage, screenWidth * screenHeight);
delete[] targetImage;
}
RayHit Scene::intersectAll(Ray &r) {
RayHit hit;
hit.hittingTime = -1.0f;
for (const auto &object : objects) {
Number tNew = object->intersect(r, hit);
if (tNew >= 0 && (tNew < hit.hittingTime || hit.hittingTime < 0)) {
hit.hittedObject = object;
hit.hittingTime = tNew;
}
}
return hit;
}
Color Scene::trace(Ray &r, int d) {
if (d >= TRACE_DEPTH)
return ambientLight.Lout;
RayHit hit = intersectAll(r);
if (hit.hittingTime > 0.0f) {
hit.intersectPoint = r.source + r.direction * hit.hittingTime;
hit.normal = hit.hittedObject->getNormalAtPoint(hit.intersectPoint).getNormalized();
/* Azért nem lehet itt, mert akkor nem tudjuk, a refractban, hogy belülről vagy kívülről
megyünk. Ezért kell a Rough/reflective blokkon belülre rakni. if (hit.normal * r.direction >
0){ hit.normal = hit.hittedObject->getNormalAtPoint(hit.intersectPoint).getNormalized();
//hit.normal = -1.0f * hit.normal;
}*/
Color ret(0.0f, 0.0f, 0.0f);
if (hit.hittedObject->material->isRough()) {
// return Color(0, 1, 0);
Color ka = hit.hittedObject->getKA(hit.intersectPoint);
ret = ka * ambientLight.Lout;
for (const auto &light : lights) {
Vector shadowDir((light->getDirection(hit.intersectPoint)));
Ray shadowRay(hit.intersectPoint + shadowDir.getNormalized() * 0.01f, shadowDir);
RayHit shadowHit = intersectAll(shadowRay);
if (shadowHit.hittingTime.value < 0.0f ||
(shadowHit.hittingTime * shadowRay.direction).length() >=
light->getDistance(hit.intersectPoint)) {
Color intensity = light->getIntensity(hit.intersectPoint);
Color kd = hit.hittedObject->getKD(hit.intersectPoint);
Color ks = hit.hittedObject->getKS();
Number shine = hit.hittedObject->getShininess();
Number cosa = (shadowRay.direction.getNormalized() & hit.normal);
Vector h = (shadowRay.direction.getNormalized() - r.direction.getNormalized())
.getNormalized();
Number cosh = (h & hit.normal);
Color plusDiffuse = intensity * kd * cosa;
Color plusSpecular = intensity * ks * npow(cosh, shine);
ret = ret + plusDiffuse + plusSpecular;
}
}
} else {
if (hit.hittedObject->material->isReflective()) {
Vector reflectedDir =
hit.hittedObject->material->reflect(r.direction.getNormalized(), hit.normal)
.getNormalized();
Color F =
hit.hittedObject->material->Fresnel(r.direction.getNormalized(), hit.normal);
Ray reflectedRay(hit.intersectPoint + 0.01f * reflectedDir,
reflectedDir.getNormalized());
ret = ret + F * trace(reflectedRay, d + 1);
}
if (hit.hittedObject->material->isRefractive()) {
Vector refractedDir;
if (hit.hittedObject->material->refract(r.direction.getNormalized(), hit.normal,
refractedDir)) {
Color F = hit.hittedObject->material->Fresnel(r.direction.getNormalized(),
hit.normal);
Ray refractedRay(hit.intersectPoint + 0.01f * refractedDir, refractedDir);
Color traced = trace(refractedRay, d + 1);
Color plus = (Color(1.0f, 1.0f, 1.0f) - F) * traced;
ret = ret + plus;
} else {
Vector reflectedDir =
hit.hittedObject->material->reflect(r.direction.getNormalized(), hit.normal)
.getNormalized();
Ray reflectedRay(hit.intersectPoint + 0.01f * reflectedDir, reflectedDir);
Color traced = trace(reflectedRay, d + 1);
ret = ret + traced;
}
}
}
Number maxI = ret.getMaxIntensity();
if (maxI > 1.0f) {
ret = ret / maxI;
}
// ret = ret * luminanceComma / luminance;
if (!(ret.r > 0 && ret.g > 0 && ret.b > 0)) {
hit.normal = hit.hittedObject->getNormalAtPoint(hit.intersectPoint).getNormalized();
}
return ret;
}
return ambientLight.Lout;
}
void Scene::build() {
ambientLight.Lout = Color(0.7f, 0.7f, 1.0f);
/// Room
KDFunction squaredKD = [](const Vector &v) {
int x = nabs(v.getX() / 4.0).value;
int z = nabs(v.getZ() / 4).value;
if (v.getX() < 0.0f)
x++;
if (v.getZ() < 0.0f)
z++;
x = x % 2;
z = z % 2;
Color ret((x * 0.5f + 0.5f) / 2.0f, 0.2f, (z * 0.5f + 0.3f) / 2.0f);
return ret;
};
KDFunction diagonalKD = [](const Vector &v) {
Vector copy = v.rotateByY(Number(M_PI / 4));
int x = nabs(copy.getX() / 4.0).value;
int z = nabs(copy.getZ() / 4).value;
if (copy.getX() < 0.0f)
x++;
if (copy.getZ() < 0.0f)
z++;
x = x % 2;
z = z % 2;
Color ret((x * 0.2f + 0.1f) / 2.0f, 0.8f, (z * 1.6f + 0.3f) / 2.0f);
return ret;
};
Material *diagonal = new TableMaterial(Number(0), Number(5), Color(0.0f, 0.0f, 0.0f),
Color(1.0f, 0.3f, 0.3f) / 2, Color(0.3, 0.3, 0.3), ROUGH,
diagonalKD, diagonalKD);
Material *squared = new TableMaterial(Number(0), Number(5), Color(0.0f, 0.0f, 0.0f),
Color(1.0f, 0.3f, 0.3f) / 2, Color(0.3, 0.3, 0.3), ROUGH,
squaredKD, squaredKD);
Color goldN = Color(0.17f, 0.35f, 1.5f);
Color goldK = Color(3.1f, 2.7f, 1.9f);
Color goldF0 = Material::makeF0(goldN, goldK);
Material *gold =
new Material(Number(0), Number(0), goldF0, Color(0, 0, 0), Color(0, 0, 0), REFLECTIVE);
std::shared_ptr<Plane> bottom = std::make_shared<Plane>(squared, Number(100), Number(100));
addObject(std::move(bottom));
std::shared_ptr<Plane> top = std::make_shared<Plane>(diagonal, Number(100), Number(100));
top->setRotateZ(Number(M_PI));
top->setShift(Vector(0, 25, 0));
addObject(std::move(top));
std::shared_ptr<InfiniteCylinder> roomCylinder =
std::make_shared<InfiniteCylinder>(gold, Number(30));
addObject(std::move(roomCylinder));
/// Glass cylinder
Color glassN = Color(1.5f, 1.5f, 1.5f);
Color glassK = Color(0.0f, 0.0f, 0.0f);
Color glassF0 = Material::makeF0(glassN, glassK);
Material *glass =
new Material(Number(1.5f), Number(0), glassF0, Color(0, 0, 0), Color(0, 0, 0), REFRACTIVE);
std::shared_ptr<InfiniteCylinder> glassCylinder =
std::make_shared<InfiniteCylinder>(glass, Number(3));
glassCylinder->setRotateZ(Number(M_PI / 6));
addObject(std::move(glassCylinder));
/// Silver cylinder
Color silverN = Color(0.14f, 0.16f, 0.13f);
Color silverK = Color(4.1f, 2.4f, 3.1f);
Color silverF0 = Material::makeF0(silverN, silverK);
Material *silver =
new Material(Number(0), Number(0), silverF0, Color(0, 0, 0), Color(0, 0, 0), REFLECTIVE);
std::shared_ptr<InfiniteCylinder> silverCylinder =
std::make_shared<InfiniteCylinder>(silver, Number(4));
silverCylinder->setRotateZ(Number(-M_PI / 7));
silverCylinder->setShift(Vector(15, 5, 10));
addObject(std::move(silverCylinder));
/// Textured cylinder
KDFunction cylinderKD = [](const Vector &v) {
Vector copy = v.rotateByY(Number(M_PI / 4));
return Color(nsin(v.getY() * 1.1), ncos(copy.getY() * 0.8), ncos(v.getZ()));
};
Material *cylinderMaterial = new TableMaterial(
Number(0), Number(5), Color(0.0f, 0.0f, 0.0f), Color(1.0f, 0.3f, 0.3f) / 2,
Color(0.3, 0.3, 0.3), ROUGH, cylinderKD, cylinderKD);
std::shared_ptr<InfiniteCylinder> texturedCylinder =
std::make_shared<InfiniteCylinder>(cylinderMaterial, Number(3));
texturedCylinder->setRotateX(Number((M_PI / 6) * 5));
texturedCylinder->setRotateY(Number((M_PI / 6) * 4));
texturedCylinder->setShift(Vector(-10, 0, 2));
addObject(std::move(texturedCylinder));
/// Point lights
std::shared_ptr<PointLight> blueLight =
std::make_shared<PointLight>(Vector(10, 10, 10), Color(0, 0, 50));
addLight(std::move(blueLight));
std::shared_ptr<PointLight> redLight =
std::make_shared<PointLight>(Vector(-5, 20, 15), Color(50, 0, 0));
addLight(std::move(redLight));
}
void Scene::smoothOutEdges() {
for (int xPos = 1; xPos < screenWidth - 1; xPos++) {
for (int yPos = 1; yPos < screenHeight - 1; yPos++) {
if (needSmoothing(xPos, yPos))
image[yPos * screenWidth + xPos] = getSmoothedColor(xPos, yPos);
}
}
}
bool Scene::needSmoothing(int xPos, int yPos) {
if (xPos == 0 || xPos == screenWidth - 1 || yPos == 0 || yPos == screenHeight - 1)
return false;
Color c1 = image[yPos * screenWidth + xPos];
Color c2 = image[(yPos + 1) * screenWidth + xPos];
Color c3 = image[yPos * screenWidth + xPos + 1];
Color c4 = image[(yPos + 1) * screenWidth + xPos + 1];
Color sum = c1 + c2 + c3 + c4;
Color average = sum / 4;
if (c1 < average / 2 || c1 > average * 2)
return true;
return false;
}
Color Scene::getSmoothedColor(int xPos, int yPos) {
Color sum;
int antialiasing = 4;
Number step(1.0 / antialiasing);
for (Number xSubPos = xPos - 0.5 + step / 2; xSubPos < xPos + 0.5; xSubPos += step) {
for (Number ySubPos = yPos - 0.5 + step / 2; ySubPos < yPos + 0.5; ySubPos += step) {
Ray ray = cam.getRay(xSubPos.value, ySubPos.value);
Color subColor = trace(ray, 0);
sum = sum + subColor;
}
}
return sum / (antialiasing * antialiasing);
}
void Scene::renderTask(Scene *scene) {
scene->mutex.lock();
while (scene->nextPixelNumber < scene->screenWidth * scene->screenWidth) {
int myNextPixelNumber = scene->nextPixelNumber++;
scene->mutex.unlock();
int yPos = myNextPixelNumber / scene->screenWidth;
int xPos = myNextPixelNumber % scene->screenWidth;
Ray ray = scene->cam.getRay(xPos, yPos);
scene->image[yPos * scene->screenWidth + xPos] = scene->trace(ray, 0);
scene->mutex.lock();
}
scene->mutex.unlock();
}
void Scene::smoothTask(Scene *scene, Color *targetImage) {
scene->mutex.lock();
while (scene->nextPixelNumber < scene->screenWidth * scene->screenWidth) {
int myNextPixelNumber = scene->nextPixelNumber++;
scene->mutex.unlock();
int yPos = myNextPixelNumber / scene->screenWidth;
int xPos = myNextPixelNumber % scene->screenWidth;
if (scene->needSmoothing(xPos, yPos))
targetImage[yPos * scene->screenWidth + xPos] = scene->getSmoothedColor(xPos, yPos);
else
targetImage[yPos * scene->screenWidth + xPos] =
scene->image[yPos * scene->screenWidth + xPos];
scene->mutex.lock();
}
scene->mutex.unlock();
}
| true |
9f63a0ba7c03c9c1f796f3a1dd99e6b30552a75f | C++ | farhanch67/OOP-Programs-in-Cplusplus | /home task 1.cpp | UTF-8 | 446 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct phone{
int code;
int exchange;
int number;
};
int main()
{
phone my,your;
my.code=212;
my.exchange=767;
my.number=8900;
cout<<"Enter your Area Code,Exchange and Number :";
cin>>your.code>>your.exchange>>your.number;
cout<<"My Number is"<<" ("<<my.code<<") "<<my.exchange<<" "<<my.number<<endl;
cout<<"Your number is "<<" ("<<your.code<<") "<<your.exchange<<" "<<your.number;
return 0;
}
| true |
cfc5fcc2282416f46e2ba0f017c876a83e1259b1 | C++ | searleser97/DistribuitedSystems | /Proyectos/sergio/Proyecto 3/src/Reply.cpp | UTF-8 | 1,173 | 2.71875 | 3 | [] | no_license | #include "../include/Reply.h"
#include <iostream>
#include <string.h>
Reply::Reply(int iport) { localSocket = new DatagramSocket(iport); }
Message *Reply::getRequest() {
auto *msg = new Message();
DatagramPacket pq((char *)msg, sizeof(Message));
localSocket->receive(pq);
address = pq.getAddress();
port = pq.getPort();
operation = msg->operation;
requestId = msg->requestId;
if (history.count({address, requestId})) {
auto saved = history[{address, requestId}];
sendReply(saved.first + msg->offset, saved.second - msg->offset);
return getRequest();
}
return msg;
}
void Reply::sendReply(const char *arguments, size_t len) {
if (!history.count({address, requestId}))
history[{address, requestId}] = {arguments, len};
auto *msg = new Message();
msg->type = Message::Type::reply;
msg->operation = operation;
msg->requestId = requestId;
msg->length = len;
if (msg->length > Message::MAX_DATA_SIZE) {
msg->MF = true;
msg->length = Message::MAX_DATA_SIZE;
}
memcpy(msg->arguments, arguments, msg->length);
DatagramPacket paquete((char *)msg, sizeof(Message), address, port);
localSocket->send(paquete);
}
| true |
085871d0ebe20ea6aa1815a666a95d44311ed4ad | C++ | hykilpikonna/School-CppAssignments | /homeworks/b004-delivery.cpp | UTF-8 | 1,615 | 3.453125 | 3 | [
"MIT"
] | permissive | //
// Created by Hykilpikonna on 9/28/20.
//
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Input
printf("Enter weight of package in kilograms: ");
double weight;
cin >> weight;
printf("Enter length of package in meters: ");
double length;
cin >> length;
printf("Enter width of package in meters: ");
double width;
cin >> width;
printf("Enter height of package in meters: ");
double height;
cin >> height;
// Create a list of statements
vector<string> statements;
if (weight < 0) statements.emplace_back("weight cannot be negative");
else if (weight > 27) statements.emplace_back("too heavy");
if (length < 0) statements.emplace_back("length cannot be negative");
if (width < 0) statements.emplace_back("width cannot be negative");
if (height < 0) statements.emplace_back("height cannot be negative");
if (length * width * height > 0.1) statements.emplace_back("too large");
// Meet requirements
if (statements.empty())
{
printf("Accepted.");
}
else
{
// Print those statements
printf("Rejected: ");
for (int i = 0; i < statements.size(); i++)
{
// If there are multiple statements, add "and" before the last one
if (i == statements.size() - 1 && statements.size() > 1) printf("and ");
// Print statement/
cout << statements[i];
// Print comma after statement
if (i < statements.size() - 1) printf(", ");
}
cout << endl;
}
return 0;
} | true |
d06c3ff1c56173c7f9efb325d93341e87d4e9592 | C++ | MAD1364/Practice | /c/practice/Computer_Programming_Practice_77.cpp | UTF-8 | 3,016 | 3.234375 | 3 | [] | no_license | /*
File: Computer_Programming_Practice_77.cpp
Author: Mario Delagarza
C.S.1428.001
Lab Section: L07
Program: P77
--/--/--
This program
Input:
Constants:
Output:
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main ( )
{
const double DISCOUNT_PERCENTAGE = .20,
FREE_SHIPPING_LIMIT = 150.00,
SHIPPING_CHARGE = 8.50,
SALES_TAX_RATE = .0825;
double price_of_item,
total = 0.0,
shipping,
discounted_total,
tax,
amount_owed;
int number_of_items;
ofstream fout;
fout.open ("prog4_001out.txt");
if ( !fout )
{
cout << "Output file failed to open. ***Program Terminating.***";
return -1;
}
cout << "Enter the number of items purchased: ";
cin >> number_of_items;
cout << endl;
if ( number_of_items == 0 )
{
cout << endl
<< "Come back again soon!" << endl;
return -2;
}
for ( int i = 0; i < number_of_items; i++ )
{
cout << "Enter the item price: ";
cin >> price_of_item;
total = total + price_of_item;
}
discounted_total = total - ( total * DISCOUNT_PERCENTAGE );
if ( discounted_total >= FREE_SHIPPING_LIMIT )
{
shipping = 0;
}
else
{
shipping = SHIPPING_CHARGE;
}
tax = discounted_total * SALES_TAX_RATE;
amount_owed = discounted_total + shipping + tax;
fout << "Mario Delagarza" << endl
<< "C.S.1428.001" << endl
<< "Lab Section: L07" << endl
<< "--/--/--" << endl << endl
<< fixed << setprecision(2)
<< "Total Purchases: $" << setw(6) << total << endl
<< "Discounted Total: " << setw(6) << discounted_total << endl
<< "Tax Rate: " << setw(8) << setprecision(4) << SALES_TAX_RATE << endl
<< "Tax: " << setw(6) << setprecision(2) << tax << endl
<< "Shipping: " << setw(6) << shipping << endl << endl
<< "Total Amount Due: $" << setw(6) << amount_owed << endl;
cout << endl
<< "Mario Delagarza" << endl
<< "C.S.1428.001" << endl
<< "Lab Section: L07" << endl
<< "--/--/--" << endl << endl
<< fixed << setprecision (2)
<< "Total Purchases: $" << setw(6) << total << endl
<< "Discounted Total: " << setw(6) << discounted_total << endl
<< "Tax Rate: " << setw(8) << setprecision(4) << SALES_TAX_RATE << endl
<< "Tax: " << setw(6) << setprecision(2) << tax << endl
<< "Shipping: " << setw(6) << shipping << endl << endl
<< "Total Amount Due: $" << setw(6) << amount_owed << endl << endl << endl
<< "A copy for your records can be found in prog4_001out.txt" << endl;
system ("PAUSE > NUL");
fout.close();
return 0;
}
| true |
feb66c5abfa006d06824951b700644171fa5c604 | C++ | hallgchris/Osmium | /nbody/src/UI.cpp | UTF-8 | 4,381 | 2.546875 | 3 | [] | no_license | #include "UI.h"
#include "components/PhysicsComponent.h"
#include "components/PathComponent.h"
#include <imgui.h>
#include <render/entity/components/PlayerControlFPV.h>
namespace ui
{
static int32_t entitySelectionIndex = 0;
void update(std::shared_ptr<os::Scene> scene, TimeState *timeState, int32_t *exp)
{
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", timeState->delta, ImGui::GetIO().Framerate);
if (ImGui::CollapsingHeader("Camera"))
{
std::shared_ptr<os::LogicalEntity> camera;
for (auto &&ent : scene->getLogicalEnts())
if (std::get<0>(ent) == "Camera")
camera = std::get<1>(ent);
if (camera.get() != nullptr)
{
auto cameraTransform = camera->getComponent<os::Transform<3, float_t>>("Transform");
glm::vec3 temp = cameraTransform->getPosition();
ImGui::InputFloat3("Camera position", (GLfloat *) &temp);
cameraTransform->setPosition(temp);
temp = cameraTransform->getRotation();
ImGui::InputFloat3("Camera rotation", (GLfloat *) &temp);
cameraTransform->setRotation(temp);
auto playerControl = camera->getComponent<os::PlayerControlFPV>("Control");
float_t tempFloat = playerControl->getMoveSpeed();
ImGui::SliderFloat("Move speed", &tempFloat, 10'000'000.0f, 10'000'000'000.0f, "%.3e m/s", 3);
playerControl->setMoveSpeed(tempFloat);
} else
{
ImGui::Text("No LogicalEntity \"Camera\" found in scene");
}
}
if (ImGui::CollapsingHeader("Time Controls"))
{
char deltaString[37] = "Scaled delta: %.3f";
if (timeState->paused || timeState->reversed)
{
strcat(deltaString, " (");
if (timeState->paused) strcat(deltaString, "PAUSED");
if (timeState->paused && timeState->reversed) strcat(deltaString, ", ");
if (timeState->reversed) strcat(deltaString, "REVERSED");
strcat(deltaString, ")");
}
ImGui::Text(deltaString, timeState->delta * timeState->deltaMultiplier);
ImGui::SliderFloat("Speed", &timeState->deltaMultiplier, 0.0f, 1e12f, "%.3e seconds/second", 10);
if (ImGui::Button("Toggle pause"))
timeState->paused = !timeState->paused;
ImGui::SameLine();
if (ImGui::Button("Toggle reverse"))
timeState->reversed = !timeState->reversed;
}
if (ImGui::CollapsingHeader("Physics Settings"))
{
ImGui::InputInt("Exp", exp, 1);
}
if (ImGui::CollapsingHeader("Entity Details"))
{
worldList physicsEnts;
for (worldEnt ent : scene->getWorldEnts())
if (std::get<1>(ent)->getComponent<PhysicsComponent<3, double_t>>("Physics") != nullptr)
physicsEnts.push_back(ent);
if (physicsEnts.size() == 0)
{
ImGui::Text("No Entity with Physics component found in scene");
return;
}
if (ImGui::Button("Previous"))
entitySelectionIndex--;
ImGui::SameLine();
if (ImGui::Button("Next")) entitySelectionIndex++;
if (entitySelectionIndex >= (int32_t) physicsEnts.size()) entitySelectionIndex = 0;
if (entitySelectionIndex < 0)
entitySelectionIndex = (int32_t) (physicsEnts.size() - 1);
auto selectedEnt = physicsEnts[entitySelectionIndex];
ImGui::SameLine();
ImGui::Text("%d: \"%s\"", entitySelectionIndex, std::get<0>(selectedEnt).c_str());
auto transform = std::get<1>(selectedEnt)->getComponent<os::Transform<3, double_t>>("Transform");
auto physics = std::get<1>(selectedEnt)->getComponent<PhysicsComponent<3, double_t>>("Physics");
auto path = std::get<1>(selectedEnt)->getComponent<PathComponent<3, double_t>>("Path");
glm::vec3 tempvec = transform->getPosition();
ImGui::InputFloat3("Entity position (m)", (GLfloat *) &tempvec);
transform->setPosition(tempvec);
tempvec = physics->getVelocity();
ImGui::InputFloat3("Entity velocity (m/s)", (GLfloat *) &tempvec);
physics->setVelocity(tempvec);
tempvec = physics->getAcceleration();
ImGui::InputFloat3("Entity acceleration(m/s/s)", (GLfloat *) &tempvec);
tempvec = physics->getForce();
ImGui::InputFloat3("Entity force (N)", (GLfloat *) &tempvec);
float_t tempfloat = (float_t) physics->getMass();
ImGui::SliderFloat("Entity mass (kg)", &tempfloat, 1.0f, 1e35f, "%.3e kg", 35.0f);
physics->setMass(tempfloat); // yes I know this limits mass to float precision, i'll work something out
if (path != nullptr && ImGui::TreeNode("Trail options"))
{
path->showUIOptions();
ImGui::TreePop();
}
}
ImGui::Render();
}
}
| true |
8a719d2380752a9b9fc5560c9df24cd787fbcb79 | C++ | dbaumeister/dbcpu | /operators/ProjectionOperator.h | UTF-8 | 647 | 2.765625 | 3 | [] | no_license | //
// Created by dbaumeister on 17.06.15.
//
#ifndef PROJECT_PROJECTIONOPERATOR_H
#define PROJECT_PROJECTIONOPERATOR_H
#include "Operator.h"
class ProjectionOperator : public Operator{
public:
ProjectionOperator() = delete;
ProjectionOperator(const std::vector<unsigned>& projectionIndices, Operator& child)
: child(child), projectionIndices(projectionIndices){}
void open();
bool next();
std::vector<Register*> getOutput();
void close();
private:
std::vector<Register*> registers;
Operator& child;
const std::vector<unsigned>& projectionIndices;
};
#endif //PROJECT_PROJECTIONOPERATOR_H
| true |
500231581a5a78e8dedd59f328df8dcc0641fbb9 | C++ | gjbex/training-material | /CPlusPlus/Tbb/Tree/src/sum_task.h | UTF-8 | 1,393 | 2.90625 | 3 | [
"CC-BY-4.0"
] | permissive | #ifndef SUM_TASK_HDR
#define SUM_TASK_HDR
#include <tbb/tbb.h>
#include "tree.h"
template<typename T>
class SumTask : public tbb::task {
private:
Node<T>* node_;
T* sum_;
public:
SumTask(Node<T>* node, T* sum) : node_ {node}, sum_ {sum} {}
tbb::task* execute() override;
};
template<typename T>
std::size_t sum_values(Node<T>* node) {
std::size_t sum = (*node)();
if (node->left())
sum += sum_values(node->left());
if (node->right())
sum += sum_values(node->right());
return sum;
}
template<typename T>
tbb::task* SumTask<T>::execute() {
if (node_->nr_descendants() < 1000) {
*sum_ += sum_values(node_);
} else {
*sum_ += (*node_)();
tbb::task_list list;
T left_sum {0.0};
T right_sum {0.0};
int count {1};
if (node_->left()) {
list.push_back(*new(allocate_child()) SumTask(node_->left(),
&left_sum));
++count;
}
if (node_->right()) {
list.push_back(*new(allocate_child()) SumTask(node_->right(),
&right_sum));
++count;
}
set_ref_count(count);
spawn_and_wait_for_all(list);
*sum_ += left_sum + right_sum;
}
return nullptr;
}
#endif
| true |
c97bef565faee0e9ac10fb7fa92e94ec6c361eb3 | C++ | Radu1999/SAT-reduction | /src/cpp_implementation/task2.h | UTF-8 | 6,700 | 3.03125 | 3 | [] | no_license | // Copyright 2020
// Authors: Radu Nichita, Matei Simtinică
#ifndef TASK2_H_
#define TASK2_H_
#include "task.h"
/*
* Task2
* You have to implement 4 methods:
* read_problem_data - read the problem input and store it however you see fit
* formulate_oracle_question - transform the current problem instance into a SAT instance and write the oracle input
* decipher_oracle_answer - transform the SAT answer back to the current problem's answer
* write_answer - write the current problem's answer
*/
class Task2 : public Task {
private:
// TODO: define necessary variables and/or data structures
int n, m, k;
int vertice[100][100];
std::map<int, std::string> reverse_code;
std::map<std::string, int> code;
std::string verdict;
std::vector<int> solution;
public:
void solve() override {
read_problem_data();
formulate_oracle_question();
ask_oracle();
decipher_oracle_answer();
write_answer();
}
void clean() {
code.clear();
reverse_code.clear();
verdict.clear();
solution.clear();
}
void solve_for_task3() {
formulate_oracle_question();
ask_oracle();
decipher_oracle_answer();
}
void read_problem_data() override {
// TODO: read the problem input (in_filename) and store the data in the object's attributes
std::ifstream input(in_filename.c_str());
input >> n >> m >> k;
int v1, v2;
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= n; j++) {
vertice[i][j] = 0;
}
}
for(int i = 0; i < m; i++) {
input >> v1 >> v2;
vertice[v1][v2] = 1;
vertice[v2][v1] = 1;
}
input.close();
}
void formulate_oracle_question() {
// TODO: transform the current problem into a SAT problem and write it (oracle_in_filename) in a format
// understood by the oracle
std::ofstream ask_oracle(oracle_in_filename.c_str());
int total_non_edges = n * (n - 1) / 2 - m;
ask_oracle << "p cnf " << m * k << " " << k +
total_non_edges * k * (k - 1) +
(k - 1) * k * n / 2 +
(n - 1) * n * k / 2 << "\n";
int available_code = 1, current_code1, current_code2;
std::string name1, name2;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= k; j++) {
name1 = std::to_string(i) + "_" + std::to_string(j);
code.insert({name1, available_code});
reverse_code.insert({available_code++, name1});
}
}
//making sure 2 vertices that arent connected
//dont belong to the found clique
for(int i = 1; i < n; i++) {
name1 = std::to_string(i) + "_";
for(int j = i + 1; j <= n; j++) {
if(!vertice[i][j]) {
name2 = std::to_string(j) + "_";
for(int q = 1; q <= k; q++) {
for(int w = 1; w <= k; w++) {
if(q != w) {
current_code1 = code.find(name1 + std::to_string(q))->second;
current_code2 = code.find(name2 + std::to_string(w))->second;
ask_oracle << -current_code1 << " " << -current_code2 <<" 0\n";
}
}
}
}
}
}
//making sure the clique is complete
for(int i = 1; i <= k; i++) {
for(int j = 1; j <= n; j++) {
ask_oracle << code.find(std::to_string(j) + "_" + std::to_string(i))->second
<<" ";
}
ask_oracle << "0 \n";
}
//make sure there are different vertices in the clique
for(int i = 1; i <= n; i++) {
name1 = std::to_string(i) + "_";
for(int j = 1; j < k; j++) {
for(int q = j + 1; q <= k; q++) {
current_code1 = code.find(name1 + std::to_string(q))->second;
current_code2 = code.find(name1 + std::to_string(j))->second;
ask_oracle << -current_code1 << " " << -current_code2 <<" 0\n";
}
}
}
for(int i = 1; i < n ; i++) {
name1 = std::to_string(i) + "_";
for(int j = i + 1; j <= n; j++) {
name2 = std::to_string(j) + "_";
for(int q = 1; q <= k; q++) {
current_code1 = code.find(name1 + std::to_string(q))->second;
current_code2 = code.find(name2 + std::to_string(q))->second;
ask_oracle << -current_code1 << " " << -current_code2 <<" 0\n";
}
}
}
ask_oracle.close();
}
void decipher_oracle_answer() {
// TODO: extract the current problem's answer from the answer given by the oracle (oracle_out_filename)
std::ifstream oracle_out(oracle_out_filename.c_str());
oracle_out >> verdict;
if(!verdict.compare("True")) {
int size, value, split;
oracle_out >> size;
std::string name, vertix_name;
for(int i = 0; i < size; i++) {
oracle_out >> value;
if(value > 0) {
name = reverse_code.find(value)->second;
vertix_name = "";
split = 0;
for(int j = 0; j < name.size(); j++) {
if(name[j] == '_') {
break;
} else if(!split) {
vertix_name += name[j];
}
}
solution.push_back(std::stoi(vertix_name));
}
}
}
oracle_out.close();
}
void write_answer() override {
// TODO: write the answer to the current problem (out_filename)
std::ofstream output(out_filename.c_str());
output << verdict << "\n";
if(!verdict.compare("True")) {
for(int i = 0; i < solution.size(); i++) {
output << solution[i] << " ";
}
}
output.close();
}
void set_k(int m) {
k = m;
}
int get_k() {
return k;
}
int get_verdict() {
if(!verdict.compare("True")) {
return 1;
}
return 0;
}
std::vector<int> get_solution() {
return solution;
}
};
#endif // TASK2_H_
| true |
8226a119c97bcacf234af7468124d250a3928684 | C++ | iwtbam/leetcode | /code/lt0973.cpp | UTF-8 | 989 | 3.09375 | 3 | [] | no_license | #include <vector>
#include <utility>
#include <queue>
using namespace std;
class Solution {
public:
struct cmp
{
bool operator()(const pair<int, double>& p1, const pair<int, int>& p2)
{
return p1.second < p2.second;
}
};
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<pair<int, double>, vector<pair<int, double>>, cmp> q;
int size = points.size();
for(int i = 0; i < size; i++)
{
pair<int, double> temp = {i, dis(points[i])};
q.push(temp);
if(i >= K)
q.pop();
}
vector<vector<int>> res = {};
while(!q.empty())
{
res.push_back(points[q.top().first]);
q.pop();
}
return res;
}
inline double dis(vector<int>& point)
{
return point[0] * point[0] + point[1] * point[1];
}
}; | true |
c47b72df1be1afd691e06976d849ec145461b7b8 | C++ | likema/sqlite3pp | /test/testselect.cpp | UTF-8 | 1,234 | 2.796875 | 3 | [] | no_license | #include <string>
#include <iostream>
#include "sqlite3pp.h"
using namespace std;
int main()
{
try {
sqlite3pp::database db("test.db");
sqlite3pp::transaction xct(db, true);
{
sqlite3pp::query qry(db, "SELECT id, name, phone FROM contacts");
for (int i = 0; i < qry.column_count(); ++i) {
cout << qry.column_name(i) << "\t";
}
cout << endl;
for (sqlite3pp::query::iterator i = qry.begin(); i != qry.end(); ++i) {
for (int j = 0; j < qry.column_count(); ++j) {
cout << (*i).get<char const*>(j) << "\t";
}
cout << endl;
}
cout << endl;
qry.reset();
for (sqlite3pp::query::iterator i = qry.begin(); i != qry.end(); ++i) {
int id;
char const* name, *phone;
std::tie(id, name, phone) = (*i).get_columns<int, char const*, char const*>(0, 1, 2);
cout << id << "\t" << name << "\t" << phone << endl;
}
cout << endl;
qry.reset();
for (sqlite3pp::query::iterator i = qry.begin(); i != qry.end(); ++i) {
int id = 0;
std::string name, phone;
(*i).getter() >> sqlite3pp::ignore >> name >> phone;
cout << id << "\t" << name << "\t" << phone << endl;
}
}
}
catch (exception& ex) {
cout << ex.what() << endl;
}
}
| true |
4dbf5fd7ff44cbc77dcccfe7831fda229f3ddb7a | C++ | Chai-YD/CPP_exe | /library_file_code/main.cpp | UTF-8 | 2,235 | 3.515625 | 4 | [] | no_license | #include "book.h"
void initialize();
void addBook();
void borrowBook();
void returnBook();
void displayBook();
int main(){
int selector;
while(1){
cout<<"0--退出\n";
cout<<"1--初始化文件\n";
cout<<"2--添加书籍\n";
cout<<"3--借书\n";
cout<<"4--还书\n";
cout<<"5--显示所有书目信息\n";
cout<<"请选择(0-5):\n";
cin>>selector;
if(selector == 0){
break;
}
switch(selector){
case 1:
initialize();break;
case 2:
addBook();break;
case 3:
borrowBook();break;
case 4:
returnBook();break;
case 5:
displayBook();break;
}
}
return 0;
}
//函数的实现
void initialize(){
ofstream outfile("book");
Book::resetTotal();
outfile.close();
}
void addBook(){
char ch[20];
Book *bp;
ofstream outfile("book",ofstream::app);//以app方式打开,调至文件尾
Book::addTotal();
cout<<"请输入书名:";cin>>ch;
bp = new Book(ch);
outfile.write(reinterpret_cast<const char*>(bp),sizeof(*bp));
delete bp;
outfile.close();
}
void borrowBook(){
int bookNo,readerNo;
fstream iofile("book");
Book bk;
cout<<"请输入书号和读者号:";cin>>bookNo>>readerNo;
iofile.seekg((bookNo - 1)*sizeof(Book));
iofile.read(reinterpret_cast<char*>(&bk),sizeof(Book));
bk.borrow(readerNo);
iofile.seekp((bookNo-1)*sizeof(Book));
iofile.write(reinterpret_cast<char*>(&bk),sizeof(Book));
iofile.close();
}
void returnBook(){
int bookNo;
fstream iofile("book");
Book bk;
cout<<"请输入书号:";cin>>bookNo;
iofile.seekg((bookNo-1)*sizeof(Book));
bk.Return();
iofile.seekp((bookNo-1)*sizeof(Book));
iofile.write(reinterpret_cast<char*>(&bk),sizeof(Book));
iofile.close();
}
void displayBook(){
ifstream infile("book");
Book bk;
infile.read(reinterpret_cast<char*>(&bk),sizeof(Book));
while(!infile.eof()){
bk.display();
infile.read(reinterpret_cast<char*>(&bk),sizeof(Book));
}
infile.close();
}
| true |
4dd882360e520ed42a6797d2c6989c187e47034d | C++ | parallaxinc/PropWare | /PropWare/serial/i2c/i2cslave.h | UTF-8 | 19,210 | 2.515625 | 3 | [
"MIT"
] | permissive | /**
* @file PropWare/serial/i2c/i2cslave.h
*
* @author Markus Ebner
* @author David Zemon
*
* @copyright
* The MIT License (MIT)<br>
* <br>Copyright (c) 2013 David Zemon<br>
* <br>Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:<br>
* <br>The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.<br>
* <br>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <PropWare/gpio/pin.h>
#include <PropWare/concurrent/runnable.h>
#include <PropWare/gpio/simpleport.h>
namespace PropWare {
/**
* @brief Basic I2C slave driver
*
* Requires that the SDA and SCL pins have sufficient pull-ups. These should be selected based on the capacitance of the
* devices on the I2C bus, and the expected clock speed.
*
* The driver supports restarts and only 7-bit addressing.
* The driver does not support clock stretching.
*
* @warning If the timeslot between start & restart, restart & restart, or stop and start is too small (depending on
* the master), a transmission might be completely lost, due to the onReceive callback taking too much time.
*/
class I2CSlave: public Runnable {
public:
static const Pin::Mask DEFAULT_SCL_MASK = Pin::Mask::P28;
static const Pin::Mask DEFAULT_SDA_MASK = Pin::Mask::P29;
public:
/**
* @brief Create an I2CSlave object (requires static allocation of buffer and stack)
*
* @param[in] address Address to join the bus as slave with
* @param[in] sclMask Pin mask for the SCL pin
* @param[in] sdaMask Pin mask for the SDA pin
* @param[in] buffer Receive buffer to store messages as they arrive
* @param[in] stack Reserved stack space that can be used for a new cog to execute the `run()` method
*
* @param <UserDataType> Type of the userData that can be set and is then passed to all callback functions
*
* @warning Providing a `buffer` that is too small will lead to received messages being truncated.
*/
template<size_t BUFFER_SIZE, size_t STACK_SIZE>
I2CSlave (const uint8_t address, uint8_t (&buffer)[BUFFER_SIZE], const uint32_t (&stack)[STACK_SIZE],
const Pin::Mask sclMask = DEFAULT_SCL_MASK, const Pin::Mask sdaMask = DEFAULT_SDA_MASK)
: Runnable(stack),
m_slaveAddress(address),
m_scl(sclMask),
m_sda(sdaMask),
m_buffer(buffer),
m_bufferUpperBound(BUFFER_SIZE - 1),
m_bufferPtr(BUFFER_SIZE) {
}
/**
* @brief Create an I2C slave object (Allows dynamic allocation of buffer and stack)
*
* @param[in] address Address to join the bus as slave with
* @param[in] sclMask Pin mask for the SCL pin
* @param[in] sdaMask Pin mask for the SDA pin
* @param[in] buffer Receive buffer to store messages as they arrive
* @param[in] bufferSize Size of the receive buffer, that will hold a received message (-> maximal message
* size)
* @param[in] stack Reserved stack space that can be used for a new cog to execute the `run()` method
* @param[in] stackSize Size of the reserved stack (in measured in 32-bit words, not bytes)
*
* @warning Providing a `buffer` that is too small will lead to received messages being truncated.
*/
I2CSlave (const uint8_t address, uint8_t *buffer, const size_t bufferSize, const uint32_t *stack,
const size_t stackSize, const Pin::Mask sclMask = DEFAULT_SCL_MASK,
const Pin::Mask sdaMask = DEFAULT_SDA_MASK)
: Runnable(stack, stackSize),
m_slaveAddress(address),
m_scl(sclMask),
m_sda(sdaMask),
m_buffer(buffer),
m_bufferUpperBound(bufferSize - 1),
m_bufferPtr(bufferSize) {
}
/**
* @brief Enter the loop that will watch and operate the bus.
*/
void run () {
this->m_scl.set_dir_in();
this->m_sda.set_dir_in();
this->m_scl.clear();
this->m_sda.clear();
const uint_fast8_t slaveAddress = this->m_slaveAddress;
while (true) {
this->await_start();
while (true) {
const uint_fast8_t address = this->read_address();
if ((address >> 1) == slaveAddress) { // Master is talking to us
this->send_ack(); // Tell master we are there
if (address & BIT_0) { // Master wants us to speak
this->m_requestEnded = false;
this->on_request();
break;
} else { // Master wants us to listen
const bool restart = this->read_to_end();
this->on_receive();
this->reset_receive_buffer();
if (!restart)
break; // received stop, go back to outer loop and await new start
}
} else // Master is talking to another slave
//The next thing that interests us now is the next start -> go to await_start();
break;
}
}
}
/**
* @brief Get the amount of bytes in the receive buffer
*
* @return The amount of bytes in the receive buffer
*/
size_t available () const {
return this->m_bufferUpperBound - this->m_bufferPtr + 1;
}
/**
* @brief Read the next byte from the receiveBuffer
*
* @return The next byte from the receiveBuffer, `-1` when none is available.
*/
int read () {
if (this->m_bufferPtr <= this->m_bufferUpperBound)
return this->m_buffer[this->m_bufferPtr++];
else
return -1;
}
/**
* @brief Send the given byte of data on the bus during a request from the bus master.
*
* @param[in] data Byte to send to the requesting master.
*
* @warning Calling this method too late may result in a defective state of the i2c state machine.
*/
void write (const uint8_t data) {
if (!this->m_requestEnded) {
uint32_t dataMask; //Initialized by setting BIT_7 in asm below
__asm__ volatile(
" mov %[_dataMask], #128 \n\t" // Initialize the mask that specifies the bit from the byte to send
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for the clock to be low first
" or dira, %[_SDAMask] \n\t" // Take SDA >after< clock is low (master has sda, since he is sending an ACK)
"loop%=: "
" test %[_data], %[_dataMask] wz \n\t" // Test whether bit to send is 0 or 1
" muxnz outa, %[_SDAMask] \n\t" // Set the bit on the bus while the clock is low
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // Wait for the next clock cycle to start
" shr %[_dataMask], #1 wz \n\t" // Shift the mask one down to select the next lower bit
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for the clock cycle to end
"if_nz brs #loop%= \n\t" // Continue until dataMask is 0 (no bit left)
//wait for ack
" andn dira, %[_SDAMask] \n\t" // Set SDA to input, because master has to pull it down
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // Wait for the ACK-Clock to begin
" test %[_SDAMask], ina wz \n\t" // Test whether master pulled SDA down or not
"if_z mov %[_requestEnded], #0 \n\t" // SDA low -> ACK
"if_nz mov %[_requestEnded], #1 \n\t" // SDA high -> NAK
: // Output
[_dataMask] "+r"(dataMask),
[_requestEnded] "+r"(this->m_requestEnded)
: // Input
[_SDAMask] "r"(this->m_sda.get_mask()),
[_SCLMask] "r"(this->m_scl.get_mask()),
[_data] "r"(data));
}
}
protected:
/**
* @brief Invoked when a request for data is received from the I2C master
*
* Data should be transmitted via I2CSlave::write()
*
* @warning This method should have the data to send on the bus prepared.
* Taking too long before transmit starts could corrupt the I2C state machines.
*/
virtual void on_request () = 0;
/**
* @brief Invoked when data has been received from the I2C master
*
* Data should be retrieved via calls to I2CSlave::read()
*
* @warning If the execution of this takes too long, data on the bus might be missed.
*/
virtual void on_receive () = 0;
private:
/**
* @brief Wait for a start / restart condition on the bus.
*/
void await_start () const {
__asm__ volatile(
"loop%=: "
" waitpeq %[_SDAMask], %[_SDAMask] \n\t" // Wait for sda to be high
" waitpne %[_SDAMask], %[_SDAMask] \n\t" // Wait for sda to get low
" test %[_SCLMask], ina wz \n\t" // If scl was high while sda got low...
"if_z brs #loop%= \n\t" // ... return, otherwise: start anew
: // Output
: // Input
[_SDAMask] "r"(this->m_sda.get_mask()),
[_SCLMask] "r"(this->m_scl.get_mask()));
}
/**
* @brief Read one byte from the bus without sending any response.
*/
uint_fast8_t read_address () const {
uint32_t result;
uint32_t bitCounter;
__asm__ volatile(
FC_START("ReadAddressStart", "ReadAddressEnd")
" mov %[_result], #0 \n\t"
" mov %[_bitCounter], #8 \n\t"
"nextBit%=: "
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for clock to get low (should already be low at this time)
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // Wait for clock to get high
" test %[_SDAMask], ina wc \n\t" // Read bit from bus ...
" rcl %[_result], #1 \n\t" // ... and store in result
" djnz %[_bitCounter], #" FC_ADDR("nextBit%=", "ReadAddressStart") " \n\t"
FC_END("ReadAddressEnd")
:[_result] "+r"(result),
[_bitCounter] "+r"(bitCounter)
:[_SDAMask] "r"(this->m_sda.get_mask()),
[_SCLMask] "r"(this->m_scl.get_mask())
);
return result;
}
/**
* @brief Wait for the next clock and pull the data line down to signal the master an ACK
*/
inline __attribute__((always_inline)) void send_ack () const {
//The code does not work anymore when removing inline and attribute always_inline. Why is this?
__asm__ volatile(
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for SCL to be low first
" or dira, %[_SDAMask] \n\t" // Take SDA and ...
" andn outa, %[_SDAMask] \n\t" // ... pull it down
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // Wait for SCL to go high ...
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // ... and wait for it to go low again
" andn dira, %[_SDAMask] \n\t" // Let go of SDA again (high by float)
: : // Inputs
[_SDAMask] "r"(this->m_sda.get_mask()),
[_SCLMask] "r"(this->m_scl.get_mask()));
}
/**
* @brief Read all bytes the master sends until either a restart or a stop condition is received
*
* @return `true` if a restart condition was received, `false` if a stop condition was received
*/
bool read_to_end () {
uint32_t result;
uint32_t bitCounter;
uint32_t isRestart;
while (true) {
__asm__ volatile(
" mov %[_isRestart], #2 \n\t"
" mov %[_bitCounter], #7 \n\t"
" mov %[_result], #0 \n\t"
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for scl to be low first
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // Wait for scl to go high
" test %[_SDAMask], ina wc \n\t" // Read bit and...
" rcl %[_result], #1 \n\t" // ... store in result
"if_c brs #DetectRestart%= \n\t" // The first bit of a received byte may be b7, or a stop / restart
// If sda was high, it can only be a restart
"DetectStop%=: "
" test %[_SCLMask], ina wz \n\t" // scl went low -> no chance for a stop-condition to be detected ...
"if_z brs #loop%= \n\t" // ... continue receiving data bits
" test %[_SDAMask], ina wz \n\t"
"if_nz mov %[_isRestart], #0 \n\t" // stop detected. Set isRestart to false ...
"if_nz brs #ReceiveEnd%= \n\t" // ... and exit
" brs #DetectStop%= \n\t"
"DetectRestart%=: "
" test %[_SCLMask], ina wz \n\t" // scl went low -> no chance for a (re)start-condition to be detected ...
"if_z brs #loop%= \n\t" // ... continue receiving data bits
" test %[_SDAMask], ina wz \n\t"
"if_z mov %[_isRestart], #1 \n\t" // restart detected. Set isRestart to true...
"if_z brs #ReceiveEnd%= \n\t" // ... and exit
" brs #DetectRestart%= \n\t"
"loop%=: " // for(int i = 0; i < 8; ++i) {
" waitpne %[_SCLMask], %[_SCLMask] \n\t" // Wait for ...
" waitpeq %[_SCLMask], %[_SCLMask] \n\t" // ... next clock
" test %[_SDAMask], ina wc \n\t" // Read bit and...
" rcl %[_result], #1 \n\t" // ... store in result
" sub %[_bitCounter], #1 wz \n\t"
"if_nz brs #loop%= \n\t" // }
"ReceiveEnd%=: "
: // Outputs
[_result] "+r"(result),
[_bitCounter] "+r"(bitCounter),
[_isRestart] "+r"(isRestart)
: // Inputs
[_SDAMask] "r"(this->m_sda.get_mask()),
[_SCLMask] "r"(this->m_scl.get_mask()));
if (2 == isRestart) {
this->send_ack();
this->append_receive_buffer(static_cast<uint8_t>(result));
} else {
return static_cast<bool>(isRestart);
}
}
}
/**
* @brief Add a byte to the receive buffer that the user can then later fetch from it in the onReceive handler.
*/
void append_receive_buffer (const uint8_t data) {
if (this->m_bufferPtr)
this->m_buffer[--this->m_bufferPtr] = data;
}
/**
* @brief Reset the receiveBuffer's state for the next message. This throws away bytes that the user did not fetch in the handler.
*/
void reset_receive_buffer () {
this->m_bufferPtr = this->m_bufferUpperBound + 1;
}
private:
const uint8_t m_slaveAddress;
const Pin m_scl;
const Pin m_sda;
/**
* Buffer storing the received messages
*/
uint8_t *m_buffer;
/**
* receiveBufferSize - 1
*/
uint32_t m_bufferUpperBound;
/**
* Index always pointing to the last written element in the receiveBuffer (= receive_buffer_size when empty)
*/
uint32_t m_bufferPtr;
bool m_requestEnded;
};
}
| true |
da69abd95b62c79bc83b1cf4dc2e3472eca9b4eb | C++ | baur-krykpayev/leetcode | /solutions/easy/728. Self Dividing Numbers.cpp | UTF-8 | 688 | 3.609375 | 4 | [] | no_license | /*
* Problem: 728. Self Dividing Numbers [easy]
* Source : https://leetcode.com/problems/self-dividing-numbers/description/
* Solver : Baur Krykpayev
* Date : 4/11/2018
*/
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right)
{
vector<int> ret;
for (int i = left; i <= right; i++)
{
int num = i;
bool non = false;
while(num && !non)
{
int cur = num%10;
if (!cur || i%cur){non = true;}
num /= 10;
}
if (!non) {ret.push_back(i);}
}
return ret;
}
}; | true |
346ff10fe8ed0930e9d665cb9966112a1f9ab644 | C++ | cppbear/Advanced_Programming | /Exam_4/Exam_4/Transport.h | UTF-8 | 1,965 | 3.484375 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class Truck
{
private:
int ID;
double TotalCost;
double TotalIncome;
public:
Truck(int id) { ID = id; TotalCost = 0.0; TotalIncome = 0.0; }
virtual double cost(int targetDistance, int weight) = 0;
virtual double price(int targetDistance) = 0;
void transport(int targetDistance, int weight)
{
if (cost(targetDistance, weight) == -1)
return;
TotalCost += cost(targetDistance, weight);
TotalIncome += price(targetDistance);
}
double getTotalCost() const { return TotalCost; }
double getTotalIncome() const { return TotalIncome; }
int getID() const { return ID; }
};
class NormalTruck : public Truck
{
private:
int maxDistance;
public:
NormalTruck(int id, int maxDistance) :Truck(id) { this->maxDistance = maxDistance; }
double cost(int targetDistance, int weight)
{
if (targetDistance > maxDistance)
return -1;
else
return (double)weight * (double)targetDistance;
}
double price(int targetDistance)
{
if (targetDistance > maxDistance)
return -1;
else
{
double price = (double)targetDistance * 5.0;
if (price < 100.0)
return 100.0;
else
return price;
}
}
};
class AdvancedTruck : public Truck
{
public:
AdvancedTruck(int id) :Truck(id) {}
double cost(int targetDistance, int weight)
{
return (double)weight * (double)targetDistance + 50.0;
}
double price(int targetDistance)
{
double price = (double)targetDistance * 8.0;
if (price < 150.0)
return 150.0;
else
return price;
}
};
class LongDistanceTruck : public AdvancedTruck
{
public:
LongDistanceTruck(int id) :AdvancedTruck(id) {}
double price(int targetDistance)
{
double price;
double temp = (double)targetDistance * 8.0;
if (temp < 150.0)
price = 150.0;
else
price = temp;
if (targetDistance < 30)
return price * 1.1;
else
return price * 0.9;
}
};
| true |
f6b68caf1f0c415efe528295e7a4a9f5cfa4674f | C++ | vmichal/Competitive | /ACM/2019-winter/1/minimal_coverage.cpp | UTF-8 | 1,548 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <utility>
#include <map>
#include <queue>
#include <algorithm>
std::vector<std::vector<int>> read_neighbours(int M) {
std::vector<std::vector<int>> segments(M);
while (true) {
int l, r;
std::cin >> l >> r;
if (l == 0 && r == 0) {
std::cin.ignore(10, '\n');
return segments;
}
if (l < r && l >= 0 && r <= M)
segments[l].push_back(r);
}
}
/*We are given a list of edges without weight between node 0 and node M and we should find the shortest path.
It's BFS time!*/
void solve() {
int M;
std::cin >> M;
std::vector<std::vector<int>> neighbours = read_neighbours(M);
std::vector<int> predecessors(M + 1, -1);
std::queue<int> waiting;
waiting.push(0);
while (!waiting.empty()) {
int const vertex = waiting.front();
waiting.pop();
for (int const nei : neighbours[vertex])
if (predecessors[nei] == -1) {//we have not visited this one yet
predecessors[nei] = vertex;
if (nei == M)
break;
waiting.push(nei);
}
}
if (predecessors[M] == -1)
std::cout << 0 << '\n';
else {
std::vector<std::pair<int, int>> path;
int vertex = M;
while (vertex) {
int const pred = predecessors[M];
path.push_back({ pred, vertex });
vertex = pred;
}
std::reverse(path.begin(), path.end());
std::cout << path.size() << '\n';
for (auto const pair : path)
std::cout << pair.first << ' ' << pair.second << '\n';
}
std::cout << '\n';
}
int main(int, char**) {
int t;
std::cin >> t;
for (int i = 0; i < t; ++i)
solve();
}
| true |
09e19fefeb0df1c41907560351589d75a3f824ff | C++ | hightemplarzzyy/2018-Game | /Root Folder/Game/World/world/world.h | GB18030 | 1,114 | 2.515625 | 3 | [
"MIT"
] | permissive | #pragma once
#pragma once
#include "..\..\Render Engine\toolbox\color.h"
#include "..\world config\worldconfigs.h"
#include "..\terrain\terrain.h"
#include "..\generator\perlinnoisegenerator.h"
using namespace std;
class World {
public:
static const Color BACK_COLOR; //ɫ
static const int CHUNK_COUNT = 5; //ηΪ5*5
static const int SIZE = 100; //δС
static const int MAX_ALTITUDE = 8; //ߺ
static const int DESIRED_VERTEX_COUNT = 138; //ÿ138?
private:
WorldConfigs m_Configs;
vector<vector<Terrain>> m_Terrains;
public:
World(const WorldConfigs &_configs);
Terrain getTerrain(int gridX, int gridZ);
vector<vector<Terrain>> getTerrains();
WorldConfigs getWorldConfigs();
private:
float generateHeights(vector<vector<float>> &heights, PerlinNoiseGenerator noise);
void generateTerrains(const vector<vector<float>> &heights, const vector<vector<vec3>> &normals);
void generateTerrain(int gridX, int gridZ, int chunkLength, const vector<vector<float>> &heights, const vector<vector<vec3>> &normals);
}; | true |
4a14d2c1d2e9c81a4c49ed2502d5df5e0d86b1b6 | C++ | luoshenseeker/UVS | /Class/Bigint.cpp | UTF-8 | 6,702 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <vector>
/*
*¿ÉÒÔ¿¼ÂÇʹÓ÷´Âëϵͳ
*/
using namespace std;
class BigInteger
{
private:
static const int BASE = 10000;
static const int WIDTH = 4;
vector<int> s;
int flag;
public:
inline bool IsMinus()const { return flag<0;}
BigInteger(long long int x = 0){*this = x;}
BigInteger operator = (string& str);
BigInteger operator = (long long& x);
BigInteger operator + (const BigInteger& b) const;
BigInteger operator - (const BigInteger& b) const;
BigInteger operator - () const{ BigInteger c = *this;c.flag *= -1;return c;}
BigInteger operator * (const BigInteger& b) const;
BigInteger operator * (const int& b) const;
bool comp(const BigInteger& b) const;
bool operator < (const BigInteger& b) const;
bool operator > (const BigInteger& b) const{ return b<*this;}
bool operator != (const BigInteger& b) const{ return b<*this || *this<b;}
bool operator == (const BigInteger& b) const{ return !(b<*this) && !(*this<b);}
bool operator <= (const BigInteger& b) const{ return !(b<*this);}
bool operator >= (const BigInteger& b) const{ return !(*this<b);}
friend ostream& operator << (ostream &out, const BigInteger& x);
};
ostream& operator << (ostream &out, const BigInteger& x)
{
if(x.IsMinus())out << "-";
out << x.s.back();
char buf[10];
for(int i = x.s.size()-2; i >= 0; i--){
snprintf(buf, 10, "%04d", x.s[i]);
for(int j = 0; j<(int)strlen(buf); j++)out << buf[j];
}
return out;
}
istream& operator >> (istream &in, BigInteger& x)
{
string s;
if(!(in >> s))return in;
//****string handle------to delete the prefix zeros***
string::iterator ptr = s.begin();
while(*ptr == '-')++ptr;
while(*ptr == '0' && s.length() > 1){
s.erase(ptr);
/*++ptr;---------------------------THE BIG BUG!!!!!!!
After the first letter erased,
the ptr still point to the first
letter, but the position became
the previous second letter automatically!!!!
*/
}
#ifdef DEBUG
cout << s << endl;
#endif // DEBUG
x = s;
return in;
}
BigInteger fac(int n);
int main()
{
BigInteger a, b;
//cin >> a >> b;
#ifdef DEBUG
cout << "a:" << a << ' ' << "b:" << b << endl;
#endif // DEBUG
int n;
cin >> n;
cout << fac(n);
return 0;
}
BigInteger fac(int n)
{
BigInteger x = 1;
for(int i = 1; i <= n; i++){
BigInteger y = i;
x = x * i;
}
return x;
}
BigInteger BigInteger::operator=(long long& x)
{
s.clear();
//Wrong way
// while(x){
// s.push_back(x%BASE);
// x/=BASE;
// }
if(x<0){
flag = -1;x*=-1;
}
else if(x>0){
flag = 1;
}
else{
flag = 0;
}
do{
s.push_back(x%BASE);
x/=BASE;
}while(x);
return *this;
}
#define VA//VA and VB two versions
BigInteger BigInteger::operator=(string& str)
{
s.clear();
if(str[0] == '-'){
flag = -1;
str = str.substr(1, str.length()-1);
}
else if(str[0] != '0'){
flag = 1;
}
else{
flag = 0;//ÊÇ·ñÐèÒª·µ»Ø0.
}
int x, len = ((str.length()-1)/WIDTH+1);
int start, end;
#ifdef VA
for(int i = 0; i<len; i++){
end = str.length()-WIDTH*i;
start = max(0, end-WIDTH);
x = 0;
for(int j = start; j<end; j++){
x = x*10 + str[j] - '0';
}
s.push_back(x);
}
#endif // VA
#ifdef VB
for(int i = 0; i<len; i++){
end = str.length()-WIDTH*i;
start = max(0, end-WIDTH);
sscanf(str.substr(start, end-start).c_str(), "%d", &x);
s.push_back(x);
}
#endif // VB
return *this;
}
bool BigInteger::comp(const BigInteger& b) const
{
if(s.size() != b.s.size())return s.size()<b.s.size();
for(int i = s.size()-1; i>=0; i--){
if(s[i] != b.s[i])return s[i]<b.s[i];
}
return false;//Equal
}
bool BigInteger::operator<(const BigInteger& b) const
{
if(flag<b.flag)return true;
else if(flag>b.flag)return false;
else if(flag<0)return b.comp(*this);
else if(flag>0)return (*this).comp(b);
else return false;
}
BigInteger BigInteger::operator+(const BigInteger& b) const
{
BigInteger c;
c.s.clear();
if(IsMinus() != b.IsMinus()){
//calculate the absolute value
//set the pointer
if((*this).comp(b)){
BigInteger const * sml = this;
BigInteger const * big = &b;
//start calculate
int x;
for(unsigned int i = 0, g = 0; ; i++){
if(g == 0 && i>=big->s.size())break;
if(i<sml->s.size())x = big->s[i] - sml->s[i] -g;
else x = big->s[i]-g;
if(x<0){
x += BASE;
g = 1;
}
else g = 0;
c.flag = big->flag;
c.s.push_back(x);
}
return c;
}
else {
BigInteger const * sml = &b;
BigInteger const * big = this;
//start calculate
int x;
for(unsigned int i = 0, g = 0; ; i++){
if(g == 0 && i>=big->s.size())break;
if(i<sml->s.size())x = big->s[i] - sml->s[i] -g;
else x = big->s[i]-g;
if(x<0){
x += BASE;
g = 1;
}
else g = 0;
c.flag = big->flag;
c.s.push_back(x);
}
return c;
}
}
else{
c.flag = flag;
int x;
for(unsigned int i = 0, g = 0; ; i++){
if(g == 0 && i>=s.size() && i>=b.s.size())break;
x = g;
if(i < s.size())x += s[i];
if(i < b.s.size())x += b.s[i];
c.s.push_back(x % BASE);
g = x/BASE;
}
return c;
}
}
BigInteger BigInteger::operator-(const BigInteger& b) const
{
return (*this+(-b));
}
BigInteger BigInteger::operator*(const int& b) const
{
BigInteger c;
c.s.clear();
int bflag = b>0? 1 : -1;
c.flag = flag * bflag;
long long g = 0;
for(unsigned int i = 0; ; i++){
if(g == 0 && i>=s.size())break;
if(i < s.size())g = s[i]*b;
for(unsigned int j = 0; ; j++){
if(g == 0)break;
if(j>c.s.size())c.s.push_back(g%BASE);
else {
g += c.s[j];
c.s[j] = g%BASE;
}
g /= BASE;
}
}
return c;
}
| true |
6cc62da78c95db109a4746700172cbab4c7d252f | C++ | Mrremrem/Mental-math | /HeadersAndSources/MathFunctions.cpp | UTF-8 | 945 | 3.3125 | 3 | [
"MIT"
] | permissive | #include "MathFunctions.h"
MathFunctions::MathFunctions()
{}
MathFunctions::~MathFunctions()
{}
unsigned MathFunctions::terms(int begin, int end, int difference)
{
return (end - begin) / difference + 1;
}
unsigned MathFunctions::gcd(unsigned first, unsigned second)
{
// checks if a zero was passed
if (first == 0)
{
return second;
}
else if (second == 0)
{
return first;
}
// Swaps second number with first to make the first number larger by default
if (first < second)
{
unsigned temp = second;
second = first;
first = temp;
}
unsigned remainder = first % second;
// using recursion to make things easier
return gcd(second, remainder);
}
unsigned MathFunctions::lcm(unsigned first, unsigned second)
{
return first * second / gcd(first, second);
}
int MathFunctions::randomInt(int min, int max)
{
return rand() % max + min;
}
| true |
b3efde9d6e96eab1edcfa6448d3ddc6a5ffb1f94 | C++ | WeakKnight/OpenGL3.3 | /OpenGLBaseTemplate/System/SystemTexture.cpp | UTF-8 | 6,548 | 2.515625 | 3 | [] | no_license |
#include "SystemTexture.hpp"
#include "Shader.hpp"
#include "SOIL.h"
//====================================================================================================
bool TGA2DTexture::init(const std::string& szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
// GLbyte* pBits = readTGABits(szFileName.c_str(),
// &(_width),
// &(_height),
// &(_components),
// &(_format));
unsigned char * image = SOIL_load_image(szFileName.c_str(), &_width, &_height, &_components, SOIL_LOAD_RGB);
if(image == nullptr)
{
return false;
}
//
this->_texturePath = szFileName;
//
glGenTextures(1, &(this->_textureId));
glBindTexture(GL_TEXTURE_2D, this->_textureId);
//
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
//glGenerateMipmap(GL_TEXTURE_2D);
/*
glTexImage2D(GL_TEXTURE_2D,
0,
GL_COMPRESSED_RGB,
this->_width,
this->_height,
0,
this->_format,
GL_UNSIGNED_BYTE, pBits);
free(pBits);
*/
SOIL_free_image_data(image);
if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
minFilter == GL_LINEAR_MIPMAP_NEAREST ||
minFilter == GL_NEAREST_MIPMAP_LINEAR ||
minFilter == GL_NEAREST_MIPMAP_NEAREST)
{
glGenerateMipmap(GL_TEXTURE_2D);
}
//
glBindTexture(GL_TEXTURE_2D, 0);
return true;
}
//====================================================================================================
//====================================================================================================
CubeMapTexture::CubeMapTexture():
_faces()
{
}
//====================================================================================================
bool CubeMapTexture::init(const std::string& cubeTextureName, const std::vector<std::string>& faces)
{
if (faces.size() != 6)
{
return false;
}
this->_texturePath = cubeTextureName;
this->_faces = faces;
glGenTextures(1, &_textureId);
unsigned char* image = nullptr;
glBindTexture(GL_TEXTURE_CUBE_MAP, _textureId);
for(GLuint i = 0; i < faces.size(); i++)
{
image = SOIL_load_image(faces[i].c_str(), &_width, &_height, 0, SOIL_LOAD_RGB);
// if (!image)
// {
// int a = 0;
// }
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return true;
}
//====================================================================================================
//====================================================================================================
SystemTexture::SystemTexture()
{
destroy();
}
//====================================================================================================
SystemTexture::~SystemTexture()
{
destroy();
}
//====================================================================================================
void SystemTexture::destroy()
{
for (auto& t : _textureCache)
{
if (!t.second)
{
continue;
}
if (t.second->_textureId > 0)
{
glDeleteTextures(1, &t.second->_textureId);
}
delete t.second;
}
_textureCache.clear();
}
//====================================================================================================
const Texture* SystemTexture::getTexture(const std::string& fileName) const
{
auto itr = _textureCache.find(fileName);
if (itr == _textureCache.cend())
{
return nullptr;
}
return itr->second;
}
//====================================================================================================
bool SystemTexture::addTextureCache(Texture* texture)
{
if (!texture)
{
return false;
}
auto findTex = getTexture(texture->getTexturePath());
if (!findTex)
{
_textureCache[texture->getTexturePath()] = texture;
}
return true;
}
//====================================================================================================
Texture* SystemTexture::createTGA2DTexture(const std::string& szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
auto findTex = getTexture(szFileName);
if (findTex)
{
return (Texture*)findTex;
}
//
auto newTAGTexture = new TGA2DTexture;
if (!newTAGTexture->init(szFileName, minFilter, magFilter, wrapMode))
{
delete newTAGTexture;
newTAGTexture = nullptr;
return nullptr;
}
//
addTextureCache(newTAGTexture);
return newTAGTexture;
}
//====================================================================================================
Texture* SystemTexture::createCubeMapTexture(const std::string& cubeTextureName, const std::vector<std::string>& faces)
{
auto findTex = getTexture(cubeTextureName);
if (findTex)
{
return (Texture*)findTex;
}
//
auto newCubeMapTexture = new CubeMapTexture;
if (!newCubeMapTexture->init(cubeTextureName, faces))
{
delete newCubeMapTexture;
newCubeMapTexture = nullptr;
return nullptr;
}
//
addTextureCache(newCubeMapTexture);
return newCubeMapTexture;
}
//====================================================================================================
| true |
8f4b9f4a761d506463bb577ce5469c52810e7364 | C++ | shindong96/2021_winter_vacation_code_file | /66. 경로 탐색(DFS 인접리스트 방법).cpp | UTF-8 | 1,528 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
/*
66. 경로 탐색(DFS : 인접리스트 방법)
방향그래프가 주어지면 1번 정점에서 N번 정점으로 가는 모든 경로의 가지 수를 출력하는 프
로그램을 작성하세요. 아래 그래프에서 1번 정점에서 5번 정점으로 가는 가지 수는
1 2 3 4 5
1 2 5
1 3 4 5
1 4 2 5
1 4 5
총 6 가지입니다.
▣ 입력설명
첫째 줄에는 정점의 수 N(1<=N<=20)와 간선의 수 M가 주어진다. 그 다음부터 M줄에 걸쳐 연
결정보가 주어진다.
▣ 출력설명
총 가지수를 출력한다.
*/
class node {
public:
int value;
bool visit;
vector<node*> node_list;
node() {
value = 0;
visit = false;
}
node(int n) {
value = n;
visit = false;
}
void insert(node* nod) {
node_list.push_back(nod);
}
int size() {
return node_list.size();
}
};
void DFS(node, int, int*);
int main() {
int n, m, count = 0;
cin >> n >> m;
node* a = new node[n+1];
for (int i = 0; i < n + 1; i++) a[i].value = i;
for (int i = 0; i < m; i++) {
int b, c;
cin >> b >> c;
a[b].insert(&a[c]);
}
a[1].visit = true;
DFS(a[1], n, &count);
cout << count;
delete[] a;
return 0;
}
void DFS(node nod, int n, int* count) {
for (int i = 0; i < nod.size(); i++) {
if (nod.node_list[i]->value == n) (*count)++;
else if (nod.node_list[i]->visit == false) {
nod.node_list[i]->visit = true;
DFS(*nod.node_list[i], n, count);
nod.node_list[i]->visit = false;
}
}
}
| true |
af8a1a6bcca18a71ff4efc053ccc2a98cd577637 | C++ | aashimawadhwa/cpp-programs | /insertion_sort.cpp | UTF-8 | 389 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
using namespace std;
void swap(int &a, int &b)
{
int temp=a;
a=b;
b=temp;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=1;i<n;i++){
int j=i;
while (arr[j-1]>arr[j] && j>0)
{
swap(arr[j-1],arr[j]);
j--;
}
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
} | true |
760d8aa899879a3e85f1d5b5896712b0a9de6d48 | C++ | zzrpsd/BuzRouter | /bus.cpp | UTF-8 | 803 | 2.515625 | 3 | [] | no_license | #include "bus.h"
void Bus::initialize( void )
{
/* Pinouts */
pinouts.resize( bits[0].pin_shapes.size() );
for ( auto p = 0; p < pinouts.size(); ++p ) {
auto& pinout = pinouts[p];
auto& dir = pinout.direction;
if ( bits.size() == 1 ) continue;
// x-/y-oordinates of bit 0 and bit 1
const auto& c0 = bits[0].pin_shapes[p].lower.coor;
const auto& c1 = bits[1].pin_shapes[p].lower.coor;
// Horizontal if the x-coordinates are the same.
dir = ( c0[0] == c1[0] );
pinout.bit_order = ( c0[dir] > c1[dir] );
pinout.pin_shapes.resize( bits.size() );
for ( auto i = 0; i < bits.size(); ++i ) {
pinout.pin_shapes[i] = bits[i].pin_shapes[p];
}
if ( !pinout.bit_order ) std::reverse( pinout.pin_shapes.begin(),
pinout.pin_shapes.end() );
}
}
| true |
516abfffa5cf5a4bfcdcf050e72684ae65a11483 | C++ | pigatron-industries/xen_midi2cv | /src/drivers/PitchCvOutput.h | UTF-8 | 836 | 2.90625 | 3 | [
"Unlicense"
] | permissive | #ifndef PitchCvOutput_h
#define PitchCvOutput_h
#include <inttypes.h>
#define PITCH_MIN_VOLTAGE -10
#define PITCH_MAX_VOLTAGE 10
class PitchCvOutput {
public:
PitchCvOutput(uint8_t dataPin, uint8_t latchPin, uint8_t clockPin, uint8_t size);
/**
* Set a value of a single output. The actual output is not sent until a call to sendData is made.
* @param index The index of the AD420 IC which the output is being set for.
* @param value The value to set.
*/
void setValue(uint8_t index, uint16_t value);
void setVoltage(uint8_t index, float voltage);
/**
* Sends all data to the AD420 ICs.
*/
void sendData();
int getSize() { return _size; }
private:
uint8_t _dataPin;
uint8_t _latchPin;
uint8_t _clockPin;
uint8_t _size;
uint16_t* _data;
};
#endif
| true |
8e29ae3b53bc14208f38908472c69cd5fcb303a2 | C++ | alanc9016/leetcode | /studies/Graphs/main.cpp | UTF-8 | 2,910 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
#include <queue>
class Graph {
public:
Graph(int size) :
size(size) {
adj.resize(size);
}
void insert(int,int);
void bfs(int s);
void dfs();
void dfs_util(int,bool*);
void topo_sort();
void dfs_visit(int,bool*);
void printGraph();
int countComponents();
private:
std::vector<std::vector<int>> adj;
int size;
std::stack<int> stack;
};
void Graph::insert(int u, int v) {
adj[u].push_back(v);
}
void Graph::printGraph() {
for (int u = 0; u < size; u++) {
std::cout << u;
for (auto v : adj[u])
std::cout << "-> " << v;
std::cout << std::endl;
}
}
void Graph::dfs() {
bool *visited = new bool[size];
for (int i = 0; i < size; i++)
visited[i] = false;
for (int u = 0; u < size; u++) {
if (!visited[u]) {
visited[u] = true;
std::cout << u << std::endl;
dfs_util(u,visited);
}
}
}
void Graph::dfs_util(int u, bool visited[]) {
for (auto v : adj[u]) {
if (!visited[v]) {
visited[v] = true;
std::cout << v << std::endl;
dfs_util(v, visited);
}
}
}
void Graph::topo_sort() {
bool *visited = new bool[size];
for (int i = 0; i < size; i++)
visited[i] = false;
for (int u = 0; u < size; u++) {
if (!visited[u]) {
visited[u] = true;
dfs_visit(u,visited);
}
}
int x = stack.size();
for (int i = 0; i < x; i++) {
std::cout << stack.top() << std::endl;
stack.pop();
}
}
void Graph::dfs_visit(int u,bool *visited) {
for (auto v : adj[u]) {
if (!visited[v]) {
visited[v] = true;
dfs_visit(v,visited);
}
}
stack.push(u);
}
void Graph::bfs(int s) {
std::queue<int> queue;
bool *visited = new bool[size];
for (int i = 0; i < size; i++)
visited[i] = false;
queue.push(s);
while (!queue.empty()) {
int x = queue.front();
queue.pop();
std::cout << x << std::endl;
for (int v : adj[x]) {
if (!visited[v]) {
visited[v] = true;
queue.push(v);
}
}
}
}
int Graph::countComponents() {
int res = 0;
bool *visited = new bool[size];
for (int i = 0; i < size; i++)
visited[i] = false;
for(int i = 0; i < size; i++) {
if (!visited[i]) {
res++;
visited[i] = true;
dfs_visit(i,visited);
}
}
return res;
}
main() {
Graph graph = Graph(5);
graph.insert(0,1);
graph.insert(0,4);
graph.insert(1,4);
graph.topo_sort();
std::cout << graph.countComponents();
/* graph.printGraph(); */
/* graph.bfs(0); */
/* graph.dfs(); */
}
| true |
3ae21af276d4e7e567d756a8ccf239a150a26ed1 | C++ | Duckle29/Relay-timer | /firmware/relay_timer/relay_timer.ino | UTF-8 | 3,415 | 2.65625 | 3 | [] | no_license |
const uint8_t CA_offset = 8;
// A, B, C, D, E, F, G, DP, CA1, CA2, CA3, CA4
const uint8_t seg_pins[] = {2, 4, 5, 6, 7, 8, 12,13, 3, 9, 10, 11};
const uint8_t relay_pin = A1;
const uint8_t pot_pin = A0;
const uint8_t btn_pin = A2;
const uint8_t buz_pin = A3;
const uint8_t beep_period = 1000; // Length of beep + break in ms
const uint8_t beeps = 6; // How many beeps
const bool relay_logic = 1; // 1 = relay on while counting, off otherwise.
// program variables
int16_t timer = 9999;
uint8_t digits[4] = {0,0,0,0};
uint32_t timer_start = 0, button_pushed = 0;
const uint16_t multiplex_time = 40; // 25fps
void setup()
{
for (uint8_t i = 0; i < sizeof(seg_pins) / sizeof(seg_pins [0]); i++)
{
pinMode(seg_pins [i], OUTPUT);
}
pinMode(relay_pin, OUTPUT);
pinMode(buz_pin, OUTPUT);
pinMode(pot_pin, INPUT);
pinMode(btn_pin, INPUT_PULLUP);
digitalWrite(relay_pin, !relay_logic); // Set relay to default state
}
void loop()
{
timer_setup(); // Let the user choose the time. Blocks while waiting for btn.
while (timer > 0)
{
handle_timer();
handle_leds();
}
digitalWrite(relay_pin, !relay_logic);
if (timer = 0) // Only beep if the timer naturally reached 0
{
uint8_t beep_cnt = 0;
while(beep_cnt < beeps)
{
digitalWrite(buz_pin, HIGH);
delay(beep_period/2);
digitalWrite(buz_pin, LOW);
delay(beep_period/2);
beep_cnt++;
handle_leds();
}
}
while(!digitalRead(btn_pin)) // Wait for the user to release the button (in case they reset the timer)
{}
delay(10);
while (digitalRead(btn_pin))
{
handle_leds();
}
}
void handle_timer()
{
if (!digitalRead(btn_pin))
{
button_pushed = millis();
}
// If the button has been pushed recently, (1-2 seconds ago), check if it still is. If it is, reset timer.
if (millis() - button_pushed > 1000 && millis() - button_pushed < 2000 && !digitalRead(btn_pin))
{
timer = -1; // set timer to -1 to avoid the buzzer beeping
return;
}
timer -= (millis()-timer_start);
split_digits(timer);
}
uint8_t digit_patterns[][8] = {
{1,1,1,1,1,1,0,0}, // 0
{0,1,1,0,0,0,0,0}, // 1
{1,1,0,1,1,0,1,0}, // 2
{1,1,1,1,0,0,1,0}, // 3
{0,1,1,0,0,1,1,0}, // 4
{1,0,1,1,0,1,1,0}, // 5
{1,0,1,1,1,1,1,1}, // 6
{1,1,1,0,0,0,0,0}, // 7
{1,1,1,1,1,1,1,0}, // 8
{1,1,1,1,0,1,1,1} // 9
};
uint32_t last_draw = 0;
void handle_leds()
{
if(millis() - last_draw >= multiplex_time)
{
last_draw = millis();
for(uint8_t cur_dig=0; cur_dig<4; cur_dig++)
{
// Turn off all digits
for(uint8_t k=0; k<4; k++)
{
digitalWrite(seg_pins[k+CA_offset], 0);
}
// Turn on/off correct segments
for(uint8_t i=0; i<8; i++)
{
digitalWrite(seg_pins[i], digit_patterns[digits[cur_dig], i]);
}
// turn on current digit
digitalWrite(seg_pins[cur_dig+CA_offset], 1); // Turn on current digit
delay(multiplex_time/4);
}
}
}
void split_digits(uint16_t x)
{
digits[0] = x / 1000;
digits[1] = (x - 1000*digits[0]) / 100;
digits[2] = (x - 1000*digits[0] - 100*digits[1]) / 10;
digits[3] = (x - 1000*digits[0] - 100*digits[1] - 10*digits[2]);
}
void timer_setup()
{
while(digitalRead(btn_pin))
{
timer = map(analogRead(pot_pin), 0, 1023, 0, 9999);
split_digits(timer);
handle_leds();
}
// Button has been pushed to start the timer, save current time for time-keeping.
timer_start = millis();
digitalWrite(relay_pin, relay_logic);
} | true |
ec76c6c2487c76632dd72cb53c8ce5a04219347e | C++ | FChia11/GirlScriptCode | /Operators.cpp | UTF-8 | 566 | 3.671875 | 4 | [] | no_license | // ASSIGNMENT OPERATOR (=)
#include <iostream>
using namespace std;
int main ()
{
int a, b;
a = 6;
b = 4;
a = x;
b = 5;
cout << 'a:';
cout << a;
cout << 'b:';
cout << b;
}
// ARITHMETIC OPERATORS + COMPOUND ASSIGNEMENTS
#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a -= 2;
cout << a;
}
// CONDITIONAL TERNARY OPERATOR
#include <iostream>
using namespace std;
int main ()
{
int a, b, c;
a = 2;
b = 1;
c= (a>b) ? a : b
cout << c << '\n';
}
| true |
167cccf7688536bf5aea3581afe3a55824bba489 | C++ | eric0410771/Game_Theory_CPP | /episode.h | UTF-8 | 4,699 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <list>
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <chrono>
#include <numeric>
#include "board.h"
#include "action.h"
#include "agent.h"
struct action_reward{
bool legal_action;
int reward;
};
typedef action_reward action_reward;
class statistic;
class episode {
friend class statistic;
public:
episode() : ep_state(initial_state()), ep_score(0), ep_time(0) { ep_moves.reserve(10000); }
public:
board& state() { return ep_state; }
const board& state() const { return ep_state; }
board::reward score() const { return ep_score; }
void open_episode(const std::string& tag) {
ep_open = { tag, millisec() };
}
void close_episode(const std::string& tag) {
ep_close = { tag, millisec() };
}
action_reward apply_action(action move) {
action_reward output;
board::reward reward = move.apply(state());
if (reward == -1) {
output.legal_action = false;
output.reward = -1;
return output;
}
output.legal_action = true;
output.reward = reward;
ep_moves.emplace_back(move, reward, millisec() - ep_time);
ep_score += reward;
return output;
}
agent& take_turns(agent& play, agent& evil) {
ep_time = millisec();
return (std::max(step() + 1, size_t(9)) % 2) ? evil : play;
}
agent& last_turns(agent& play, agent& evil) {
return take_turns(evil, play);
}
public:
size_t step(unsigned who = -1u) const {
int size = ep_moves.size(); // 'int' is important for handling 0
switch (who) {
case action::slide::type: return (size - 1) / 2;
case action::place::type: return (size - (size - 1) / 2);
default: return size;
}
}
time_t time(unsigned who = -1u) const {
time_t time = 0;
size_t i = 2;
switch (who) {
case action::place::type:
if (ep_moves.size()) time += ep_moves[0].time, i = 1;
// no break;
case action::slide::type:
while (i < ep_moves.size()) time += ep_moves[i].time, i += 2;
break;
default:
time = ep_close.when - ep_open.when;
break;
}
return time;
}
std::vector<action> actions(unsigned who = -1u) const {
std::vector<action> res;
size_t i = 2;
switch (who) {
case action::place::type:
if (ep_moves.size()) res.push_back(ep_moves[0]), i = 1;
// no break;
case action::slide::type:
while (i < ep_moves.size()) res.push_back(ep_moves[i]), i += 2;
break;
default:
res.assign(ep_moves.begin(), ep_moves.end());
break;
}
return res;
}
public:
friend std::ostream& operator <<(std::ostream& out, const episode& ep) {
out << ep.ep_open << '|';
for (const move& mv : ep.ep_moves) out << mv;
out << '|' << ep.ep_close;
return out;
}
friend std::istream& operator >>(std::istream& in, episode& ep) {
ep = {};
std::string token;
std::getline(in, token, '|');
std::stringstream(token) >> ep.ep_open;
std::getline(in, token, '|');
for (std::stringstream moves(token); !moves.eof(); moves.peek()) {
ep.ep_moves.emplace_back();
moves >> ep.ep_moves.back();
ep.ep_score += action(ep.ep_moves.back()).apply(ep.ep_state);
}
std::getline(in, token, '|');
std::stringstream(token) >> ep.ep_close;
return in;
}
protected:
struct move {
action code;
board::reward reward;
time_t time;
move(action code = {}, board::reward reward = 0, time_t time = 0) : code(code), reward(reward), time(time) {}
operator action() const { return code; }
friend std::ostream& operator <<(std::ostream& out, const move& m) {
out << m.code;
if (m.reward) out << '[' << std::dec << m.reward << ']';
if (m.time) out << '(' << std::dec << m.time << ')';
return out;
}
friend std::istream& operator >>(std::istream& in, move& m) {
in >> m.code;
m.reward = 0;
m.time = 0;
if (in.peek() == '[') {
in.ignore(1);
in >> std::dec >> m.reward;
in.ignore(1);
}
if (in.peek() == '(') {
in.ignore(1);
in >> std::dec >> m.time;
in.ignore(1);
}
return in;
}
};
struct meta {
std::string tag;
time_t when;
meta(const std::string& tag = "N/A", time_t when = 0) : tag(tag), when(when) {}
friend std::ostream& operator <<(std::ostream& out, const meta& m) {
return out << m.tag << "@" << std::dec << m.when;
}
friend std::istream& operator >>(std::istream& in, meta& m) {
return std::getline(in, m.tag, '@') >> std::dec >> m.when;
}
};
static board initial_state() {
return {};
}
static time_t millisec() {
auto now = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
}
private:
board ep_state;
board::reward ep_score;
std::vector<move> ep_moves;
time_t ep_time;
meta ep_open;
meta ep_close;
};
| true |
330dd4a6e6e6408c28052b7f697da81c08ea9b28 | C++ | mariosgit/mbCVio | /mbCVio.cpp | UTF-8 | 4,107 | 2.578125 | 3 | [] | no_license | #include "mbCVio.h"
#include <mbLog.h>
mbCVio::mbCVio() :
_adc0(0),
_adc1(0),
_dacOffset(4000),
mcp(),
dac0(0),
dac1(1),
adcadr(0b01101001)
{
}
void mbCVio::setDACOffset(float val)
{
float fval = fmax(5.0f, val);
fval = fmin(-5.0f, fval);
_dacOffset = fval; // 2000 = 0V, 0 = -5V, 4000 = +5V
dac1.analogWrite(1, _dacOffset); // 0=ADCVref=1,024; 1=DACVref=2,048V
}
bool mbCVio::begin()
{
bool result = true;
/*// set second DAC adr to 1 (LED7 pin)
mcp.digitalWrite(7, HIGH);
Wire.beginTransmission(0x60);
Wire.write(0b01100001);
mcp.digitalWrite(7, LOW);
Wire.write(0b01100110); //new adr = 1
Wire.write(0b01100111); //confirmation
Wire.endTransmission();
*/
// test port expander
mcp.begin(); // use default address 0
mcp.pinMode(0, OUTPUT);
mcp.pinMode(1, OUTPUT);
mcp.pinMode(2, OUTPUT);
mcp.pinMode(3, OUTPUT);
mcp.pinMode(4, OUTPUT);
mcp.pinMode(5, OUTPUT);
mcp.pinMode(6, OUTPUT);
mcp.pinMode(7, OUTPUT);
// DAC
dac0.begin(); // initialize i2c interface
dac1.begin(); // initialize i2c interface
dac0.setVref(1,1,1,1);
dac1.setVref(1,1,1,1);
dac0.setGain(1, 1, 1, 1);
dac1.setGain(1, 1, 1, 1);
dac0.analogWrite(2000,2000,2000,2000);
dac1.analogWrite(0000,_dacOffset,2000,2000); // 0=ADCVref=1,024; 1=DACVref=2,048V
// ADC
Wire.beginTransmission(adcadr);
// Send configuration command
// Continuous conversion mode, Channel-1, 12-bits resolution
Wire.write(0x10);
uint8_t retadc = Wire.endTransmission();
// 0:success
// 1:data too long to fit in transmit buffer
// 2:received NACK on transmit of address
// 3:received NACK on transmit of data
// 4:other error
result &= (retadc == 0);
// Serial.print("adc result:"); Serial.println(retadc);
// Teensy Internal DACs, Pin3 as Gate
analogWriteResolution(12);
pinMode(3, OUTPUT);
return result;
}
bool channel = false;
bool active = true;
void mbCVio::adc()
{
if(!active)
return;
unsigned int data[2];
// Start I2C Transmission
Wire.beginTransmission(adcadr);
// Select data register
if(channel)
Wire.write(0x10);
else
Wire.write(0x30);
// Stop I2C Transmission
Wire.endTransmission();
// Request 2 bytes of data
Wire.requestFrom(adcadr,2);
// Read 2 bytes of data
// raw_adc msb, raw_adc lsb
if(Wire.available() == 2)
{
data[0] = Wire.read();
data[1] = Wire.read();
// Convert the data to 12-bits
int16_t raw_adc = (data[0] & 0x0F) * 256 + data[1];
if(raw_adc > 2047)
{
raw_adc -= 4096;
}
if(channel)
_adc0 = raw_adc;
else
_adc1 = raw_adc;
// if(channel)
// LOG << "ADC0: ";
// else
// LOG << "\t\tADC1: ";
// LOG << raw_adc <<"\n";
}
else
{
// LOG << "Digital Value of Analog Input is : FAIL\n";
// active = false;
}
channel = !channel;
}
bool leddir = true;
void mbCVio::led(uint8_t &ledpin)
{
mcp.digitalWrite(ledpin, LOW);
if(leddir)
ledpin = (ledpin+1);
else
ledpin = (ledpin-1);
if(ledpin == 0)
leddir = true; //up
if(ledpin == 7)
leddir = false; //down
mcp.digitalWrite(ledpin, HIGH);
// Serial.print("led:");
// Serial.println(ledpin);
}
// internal DAC, goes to 3.3V only !
float phase = 0.0;
float twopi = 3.14159 * 2;
void mbCVio::loop()
{
float val = sin(phase) * 2000.0 + 2000.0;
// Log.notice("\t\t\t\tdac: %d\n", (uint16_t)val);
phase = phase + twopi * 0.01;
if (phase >= twopi)
{
phase = 0;
}
// analogWrite(A14, (int)val);
// digitalWrite(3, (phase > 3.14));
dac0.analogWrite(2, (uint16_t)val);
dac0.analogWrite(3, (uint16_t)val);
dac0.analogWrite(0, (uint16_t)val);
dac0.analogWrite(1, (uint16_t)val);
dac1.analogWrite(2, (uint16_t)val);
dac1.analogWrite(3, (uint16_t)val);
}
| true |
bb654da111380ef29b9e75f8e2054a2c56e2947f | C++ | liweiliv/DBStream | /util/delegate.h | UTF-8 | 874 | 2.65625 | 3 | [] | no_license | #pragma once
template <class F>
F* create_delegate(F* f)
{
return f;
}
#define _MEM_DELEGATES(_Q,_NAME)\
template <class T, class R, class ... P>\
struct _mem_delegate ## _NAME\
{\
T* m_t;\
R (T::*m_f)(P ...) _Q;\
_mem_delegate ## _NAME(T* t, R (T::*f)(P ...) _Q):m_t(t),m_f(f) {}\
_mem_delegate ## _NAME(const _mem_delegate ## _NAME &m):m_t(m.m_t),m_f(m.m_f){}\
_mem_delegate ## _NAME& operator=(const _mem_delegate ## _NAME &m){m_t=m.m_t;m_f=m.m_f;return *this;}\
R operator()(P ... p) _Q\
{\
return (m_t->*m_f)(p ...);\
}\
};\
\
template <class T, class R, class ... P>\
_mem_delegate ## _NAME<T,R,P ...> create_delegate(T* t, R (T::*f)(P ...) _Q)\
{\
_mem_delegate ##_NAME<T,R,P ...> d(t,f);\
return d;\
}
_MEM_DELEGATES(, Z)
_MEM_DELEGATES(const, X)
_MEM_DELEGATES(volatile, Y)
_MEM_DELEGATES(const volatile, W)
| true |
e76ca70fa1924101661d7d68fa7a0a841bb4a497 | C++ | emrul-chy/Competitive-Programming | /UVa/11000 - Bee.cpp | UTF-8 | 441 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
int main()
{
long long int n, i, sum,sum1, f[102];
while(scanf("%lld", &n)==1)
{
if(n<0) break;
f[0] =0;
f[1] =1;
sum = f[0];
sum1 = f[0] + f[1];
for(i=2; i<=(n+1); i++)
{
f[i] = f[i-2] + f[i-1];
sum+=f[i-1];
sum1+=f[i];
}
printf("%lld %lld\n", sum, sum1);
}
return 0;
}
| true |
dcef547db4b8d24f99041eff1b097268607ed73e | C++ | neer1304/SPOJ | /The_Shortest_Path_spoj.cpp | UTF-8 | 5,297 | 3.21875 | 3 | [] | no_license | #include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include<string.h>
/* Do not break from dijkstra even if you get the target node costed me 4 WA's */
using namespace std;
typedef pair< int, int > pii;
/*
Set MAX according to the number of nodes in the graph. Remember,
nodes are numbered from 1 to N. Set INF according to what is the
maximum possible shortest path length going to be in the graph.
This value should match with the default values for d[] array.
*/
const int MAX = 10010;
const int INF = 999999;
/*
pair object for graph is assumed to be (node, weight). d[] array
holds the shortest path from the source. It contains INF if not
reachable from the source.
*/
vector< pii > G[MAX];
int d[MAX];
/*
The dijkstra routine. You can send a target node too along with
the start node.
*/
void dijkstra(int start, int target)
{
// printf("In dijkstra\n");
int u, v, i, c, w;
/*
Instead of a custom comparator struct or class, we can use
the default comparator class greater<T> defined in queue.h
*/
priority_queue< pii, vector< pii >, greater< pii > > Q;
/*
Reset the distance array and set INF as initial value. The
source node will have weight 0. We push (0, start) in the
priority queue as well that denotes start node has 0 weight.
*/
memset(d, 999999, sizeof d);
// start - node 0 -weight
Q.push(pii(start, 0));
d[start] = 0;
/*
As long as queue is not empty, check each adjacent node of u
*/
while(!Q.empty())
{
// printf("In dijkstra while loop\n");
u = Q.top().first; // node
c = Q.top().second; // node cost so far
Q.pop(); // remove the top item.
/*
We have discarded the visit array as we do not need it.
If d[u] has already a better value than the currently
popped node from queue, discard the operation on this node.
*/
if(d[u] < c) continue;
/*
In case you have a target node, check if u == target node.
If yes you can early return d[u] at this point.
*/
/*
if (u==target)
{
if(d[u] !=INF)
printf("%d\n",d[u]);
else
printf("NO\n");
return;
}
*/
/*
Traverse the adjacent nodes of u. Remember, for the graph,,
the pair is assumed to be (node, weight). Can be done as
you like of course.
*/
for(i = 0; i < G[u].size(); i++)
{
v = G[u][i].first; // node
w = G[u][i].second; // edge weight
/*
Relax only if it improves the already computed shortest
path weight.
*/
if(d[v] > d[u] + w)
{
d[v] = d[u] + w;
Q.push(pii(v, d[v]));
}
}
}
// d[target] == INF ? printf("NO\n") : printf("%d\n", d[target]);
printf("%d\n",d[target]);
// printf("NO\n");
}
int main()
{
// int n, e, i, u, v, w, start,target;
/*
Read a graph with n nodes and e edges.
*/
int t,i,j,n,nr,cost;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
char name[n][11];
memset(name[n],0,sizeof name[n]);
for(i = 1; i <= n; i++)
G[i].clear();
for(i=1;i<=n;i++)
{
scanf("%s",name[i]);
int p;
scanf("%d",&p);
for(j=1;j<=p;j++)
{
scanf("%d %d",&nr,&cost);
G[i].push_back(pii(nr, cost));
}
}
int r;
scanf("%d",&r);
for(j=0;j<r;j++)
{
char src[11];
char dest[11];
memset(src,0,11);
memset(dest,0,11);
scanf("%s %s",src,dest);
// printf("src - %s dest - %s\n",src,dest);
int is=0,id=0;
for(i=1;i<=n;i++)
{
// printf("In strcmp name[i] is %s\n",name[i]);
if(!strcmp(name[i],src))
{
is = i;
}
if(!strcmp(name[i],dest))
{
id = i;
}
}
// printf("is - %d id - %d\n",is,id);
dijkstra(is,id);
}
}
// printf("In main\n");
// Reset the graph
#if 0
for(i = 1; i <= n; i++)
G[i].clear();
/*
Read all the edges. u to v with cost w
*/
for(i = 0; i < e; i++)
{
scanf("%d %d %d", &u, &v, &w);
G[u].push_back(pii(v, w));
// G[v].push_back(pii(u, w)); // only if bi-directional
}
/*
For a start node call dijkstra.
*/
scanf("%d %d", &start, &target);
dijkstra(start, target);
/*
Output the shortest paths from the start node.
*/
/* printf("Shortest path from node %d:\n", start);
for(i = 1; i <= n; i++) {
if(i == start) continue;
if(d[i] >= INF) printf("\t to node %d: unreachable\n", i);
else printf("\t to node %d: %d\n", i, d[i]);
}
*/
}
#endif // 0
return 0;
}
| true |
82f0f66890eb6c6c2e5532d66202137e91664142 | C++ | csce-4600/project-2 | /Problem 1 /source/main.cpp | UTF-8 | 7,164 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <cstdio>
#include <ctime>
#include <unistd.h>
#include <chrono>
using namespace std;
// Random value generator; uses normal distribution for random values
class Generator {
default_random_engine generator;
normal_distribution<double> distribution;
double min;
double max;
public:
Generator(double mean, double stddev, double min, double max) :
distribution(mean, stddev), min(min), max(max)
{}
double operator ()() {
while (true) {
double number = this->distribution(generator);
if (number >= this->min && number <= this->max)
return number;
}
}
};
struct process {
int processId;
int cpuCycles;
int memFootprint;
};
// Start pid from
int init_pid = 0;
// Number of processes required
int numProcessesRequired;
// Where all processes will be stored
process* pArray;
// Random value generator
Generator randCycle(6000.0, 2000.0, 1000.0, 11000.0);
Generator randMemFootprint(100.0, 50.0, 1.0, 200.0);
int getProcessID() {
return init_pid++;
}
void printAllProcesses(process* p) {
for (int i = 0; i < numProcessesRequired; i++)
cout << "PID: " << p[i].processId << "\t\t CPU cyles: " << p[i].cpuCycles << "\t\t Memory footprint:" << p[i].memFootprint << endl;
}
// Set values for each individual process
process createProcess() {
process p;
p.processId = getProcessID();
p.cpuCycles = randCycle();
p.memFootprint = randMemFootprint();
return p;
}
void createAllProcesses() {
// Loops until all processes are initialized with mem and cycle values
for (int i = 0; i < numProcessesRequired; i++)
pArray[i] = createProcess();
}
void sleepNanoSeconds(int sleepTime)
{
auto sleepStart = chrono::high_resolution_clock::now();
int sleepedNanoSeconds = 0;
do
{
sleepedNanoSeconds = chrono::duration_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now() - sleepStart).count();
}
while(sleepedNanoSeconds < sleepTime);
}
int simulateProcesses() {
bool flagRunSimulation = true; // the variable is false when the simulation has finished
int currentCycle = 0; // the cycle that is now simulated
int cyclesUntilProcFinish = 0; // the number of cycles remaining until the current executing process finishes computing
int availableMemory = 10240; // the amount of available memory remaining in KB; at first, we have 10Mb = 10 * 1024 KB = 10240KB
int indexOfCurrentlyExecutingProcess = 0;
void *allocatedMemory = NULL;
auto memAllocStart = chrono::high_resolution_clock::now();
auto totalTimeStart = chrono::high_resolution_clock::now();
cyclesUntilProcFinish = pArray[0].cpuCycles;
if (pArray[0].memFootprint <= availableMemory) { // check to see that we have enough memory,
// Using high resolution clock as Joseph mentioned
allocatedMemory = malloc(pArray[0].memFootprint * 1024); // beacuse memFootPrint represents the amount of memory in KB and 1KB = 1024B
if (allocatedMemory == NULL) {
cout << "Error allocating memory for the process with pid " << pArray[0].processId << endl;
return -2; // return error code -2
}
availableMemory -= pArray[0].memFootprint;
indexOfCurrentlyExecutingProcess = 0;
}
else {
cout << "Error allocating memory for the first process with pid " << pArray[0].processId << endl;
return -1; // return error code -1(not enough memory for the first process)
}
while (flagRunSimulation == true) {
if (currentCycle % 50 == 0 && ((currentCycle / 50) < numProcessesRequired)) {
int numberOfArrivingProcess = currentCycle / 50; // the number of the process that has arrived
cout << "PID " << pArray[numberOfArrivingProcess].processId << " arrived at cycle " << currentCycle << ". It has a memory footprint of " <<
pArray[numberOfArrivingProcess].memFootprint << " and it requires " << pArray[numberOfArrivingProcess].cpuCycles << " cycles to execute" << endl;
cout << "Currently executing PID " << pArray[indexOfCurrentlyExecutingProcess].processId << endl;
}
++currentCycle;
--cyclesUntilProcFinish;
if (cyclesUntilProcFinish == 0) {
free(allocatedMemory);
auto memAllocEnd = chrono::high_resolution_clock::now();
// 1000000 = milisecond
int sleepTime = 1000000 * pArray[indexOfCurrentlyExecutingProcess].cpuCycles;
//usleep(sleepTime);
sleepNanoSeconds(sleepTime);
allocatedMemory = NULL;
availableMemory += pArray[indexOfCurrentlyExecutingProcess].memFootprint; // retrieve memory
cout << ">> PID " << pArray[indexOfCurrentlyExecutingProcess].processId << " finished executing in cycle " << currentCycle << ". Execution time for malloc and free: " << chrono::duration_cast<chrono::nanoseconds>(memAllocEnd - memAllocStart).count() << " nanoseconds\n\n";
if (indexOfCurrentlyExecutingProcess == (numProcessesRequired - 1)) {
auto totalTimeEnd = chrono::high_resolution_clock::now();
cout << "Total program execution time: " << (chrono::duration_cast<chrono::nanoseconds>(totalTimeEnd - totalTimeStart).count()) << " nanoseconds" << endl;
cout << "Number of processor cycles required to compute all the processes: " << currentCycle << endl;
flagRunSimulation = false;
}
else { // the currently executing project has finished, and the next process from the waiting queue must start
indexOfCurrentlyExecutingProcess++;
cyclesUntilProcFinish = pArray[indexOfCurrentlyExecutingProcess].cpuCycles;
if (pArray[indexOfCurrentlyExecutingProcess].memFootprint <= availableMemory) { // check to see that we have enough memory,
memAllocStart = chrono::high_resolution_clock::now(); // timing needs to be restarted for new process
allocatedMemory = malloc(pArray[indexOfCurrentlyExecutingProcess].memFootprint * 1024); // beacuse memFootPrint represents the amount of memory in KB and 1KB = 1024B
if (allocatedMemory == NULL) {
cout << "Error allocating memory for the process with pid " << pArray[indexOfCurrentlyExecutingProcess].processId << endl;
return -2; // return error code -2
}
availableMemory -= pArray[indexOfCurrentlyExecutingProcess].memFootprint;
}
else {
cout << "Error allocating memory for the process with pid " << pArray[indexOfCurrentlyExecutingProcess].processId << endl;
return -1; // return error code -1(not enough memory for the first process)
}
cout << "Starting execution of PID " << pArray[indexOfCurrentlyExecutingProcess].processId << " in cycle " << currentCycle + 1 << " with a memory footprint of " << pArray[indexOfCurrentlyExecutingProcess].memFootprint << endl;
}
}
}
return 0; // succesful function execution
}
int main(int argc, char **argv) {
// Error handling
if (argc < 2) {
cout << "Error!" << "\nUsage: " << argv[0] << " [REQUIRED: number of processes] [OPTIONAL: start pid from]\n" << endl;
return -1;
}
if (argv[2]) init_pid = atoi(argv[2]);
numProcessesRequired = atoi(argv[1]);
// Create process array with number of process required
pArray = new process[numProcessesRequired];
// Initialize processes with random mem and cycle requirements
createAllProcesses();
// Simulate the memory allocation
simulateProcesses();
// Cleanup
delete pArray;
return 0;
} | true |
c98afe029cd2b606d8e28b29b5be291a8fc494d4 | C++ | jasonlarue/csci104-coursework | /hw6/hw6-sample/crawler.cpp | UTF-8 | 4,535 | 3.125 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <set>
#include <unordered_set>
using namespace std;
unordered_set<string> pageParser(ifstream &ifile, string filepath) {
unordered_set<string> links;
char c;
string workingString;
ifile >> noskipws;
while (ifile >> c) {
//we need to convert everything to lower as queries are case insensitive
c = tolower(c);
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
workingString = workingString + c;
}
//if we find a [ keep parsing words as normal, but when we get to a ] stop
//parsing, skip the ( and put everything into linkPath until we get to )
else if (c == '[') {
workingString = "";
while (ifile >> c) {
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
workingString = workingString + c;
} else if (c == ']') {
workingString = "";
string linkPath;
ifile >> c; //we do this to ignore the '('
while (ifile >> c) {
if (c == ')') {
break;
} else {
linkPath = linkPath + c;
}
}
links.insert(linkPath);
cout << "adding link " << linkPath << endl;
break;
} else if (workingString != "") {
workingString = "";
}
}
}
else if (workingString != "") {
workingString = "";
}
}
//we do this because entries in links are inserted similar to a stack, so
//they are in reverse order. this ensures the order is correct before return
unordered_set<string> linksToReturn;
unordered_set<string>::iterator it = links.begin();
while (it != links.end()) {
linksToReturn.insert(*it);
it++;
}
return linksToReturn;
}
void crawlerHelper(string inputPath, set<string> &setOfPages, ofstream &output){
ifstream ifile;
ifile.open(inputPath.c_str());
//if ifile fails, this means this link is invalid and we shouldn't add it
if (ifile.fail()) {
cout << "404, didnt find " << inputPath << endl;
ifile.close();
return;
}
//if inputPath represents a webpage we haven't seen already, add it to the
//list of pages we've seen and output it
if (setOfPages.find(inputPath) == setOfPages.end()) {
setOfPages.insert(inputPath);
cout << "were adding " << inputPath << endl;
output << inputPath << endl;
}
unordered_set<string> links = pageParser(ifile,inputPath);
//loop through all links that this page contains and recursivley call helper
unordered_set<string>::iterator it = links.begin();
while (it != links.end()) {
//this if statement ensures we only explore pages we haven't seen already
if (setOfPages.find((*it)) == setOfPages.end()) {
cout << "now calling func for " << *it << endl;
crawlerHelper((*it), setOfPages, output);
}
it++;
}
ifile.close();
return;
}
int main(int argc, char const *argv[]) {
string pathToConfig = "config.txt";
if (argc >= 1) {
pathToConfig = argv[1];
}
ifstream config;
config.open(pathToConfig.c_str());
string INDEX_FILE;
string OUTPUT_FILE;
char charin;
string tempInput;
string tempValue;
string tempLineOfFile;
bool readingValue = false;
while (getline(config,tempLineOfFile)) {
stringstream ss;
ss.str(tempLineOfFile);
while (ss >> charin) {
if (charin == '#') {
break;
}
else if (charin == '=') {
readingValue = true;
}
else if (readingValue == false) {
if (charin != ' ') {
tempInput = tempInput + charin;
}
}
else if (readingValue == true) {
if (charin != ' ') {
tempValue = tempValue + charin;
}
}
}
if (tempInput == "INDEX_FILE") {
INDEX_FILE = tempValue;
} else if (tempInput == "OUTPUT_FILE") {
OUTPUT_FILE = tempValue;
}
tempInput = "";
tempValue = "";
readingValue = false;
}
//open index and initialize set and output that we will need for crawlerHelper
ifstream index;
index.open(INDEX_FILE.c_str());
string input = "";
set<string> setOfPages;
ofstream output;
output.open(OUTPUT_FILE.c_str());
//for each file listed in index, call crawlerHelper
cout << "INDEX_FILE is " << INDEX_FILE << endl;
while (getline(index,input)) {
cout << "input is " << input << endl;
if (input != "") {
crawlerHelper(input, setOfPages, output);
}
}
index.close();
output.close();
return 0;
}
| true |
89c67505dea283c9b8e07c32cd9d31b653f8b16c | C++ | zl1704/zlcompiler | /src/parser/Parser.cpp | UTF-8 | 37,483 | 2.71875 | 3 | [] | no_license | /*
* Parser.cpp
*
* Created on: 2017年12月8日
* Author: ZL
*/
#include "Parser.hpp"
Parser::Parser(Lexer* L, Log* log) :
L(L), log(log) {
this->keywords = L->getKeyWords();
L->nextToken();
mode = 0;
lastmode = 0;
errorEndPos = -1;
}
/**
*CompilationUnit = ClassDeclaration
*/
CompilationUnit* Parser::parseCompilationUnit() {
if (util::debug)
cout << endl << "==========Parser start:" << endl;
int pos = L->getToken()->pos;
vector<Tree*> defs;
while (L->getToken()->id != Token::EOF_) {
defs.push_back(ClassDeclaration());
}
return TreeMaker::TopLevel(pos, defs, L->getSource());
}
/**
* ClassDeclaration= CLASS Ident ClassBody
*
*/
ClassDecl* Parser::ClassDeclaration() {
int pos = L->getToken()->pos;
Modifiers* mods = modifiersOpt();
accept(Token::CLASS);
string class_name = this->ident();
vector<Tree*> defs = classBody(class_name);
return TreeMaker::makeClassDecl(pos, mods, class_name, defs);
}
//ClassBody = "{" {ClassBodyDeclaration} "}"
vector<Tree*> Parser::classBody(string className) {
accept(Token::LBRACE);
if (L->getToken()->pos <= errorEndPos) {
//错误恢复
skip(true, false, false);
if (L->getToken()->id == Token::LBRACE)
L->nextToken();
}
vector<Tree*> defs;
while (L->getToken()->id != Token::RBRACE
&& L->getToken()->id != Token::EOF_) {
util::appendList(defs, classBodyDeclaration(className));
if (L->getToken()->pos <= errorEndPos) {
//错误恢复
skip(true, true, false);
if (L->getToken()->id == Token::LBRACE)
L->nextToken();
}
}
accept(Token::RBRACE);
return defs;
}
/**
* ClassBodyDeclaration=
“;”
| [STATIC] BLOCK
| ModifiersOpt
( Type Ident
( VariableDeclaratorsRest ";" | MethodDeclaratorRest )
| VOID Ident MethodDeclaratorRest
| Ident ConstructorDeclaratorRest )
*
*/
vector<Tree*> Parser::classBodyDeclaration(string className) {
if (L->getToken()->id == Token::SEMI) {
L->nextToken();
vector<Tree*> nullList;
return nullList;
} else {
int pos = L->getToken()->pos;
Modifiers* mods = modifiersOpt();
//[静态]{构造块}
if (L->getToken()->id == Token::LBRACE
&& (mods->flags & Flags::StandardFlags & ~Flags::STATIC) == 0) {
return util::ListOf((Tree*) block(pos, mods->flags));
} else {
//提前保存name,后面需要函数名称需要判断
string name = L->getToken()->name;
pos = L->getToken()->pos;
Expression* type;
bool isVoid = (L->getToken()->id == Token::VOID);
if (isVoid) {
type = TreeMaker::makeTypeIdent(pos, TypeTags::VOID);
L->nextToken();
} else {
type = parseType();
}
//构造方法
if (L->getToken()->id == Token::LPAREN
&& type->getTag() == Tree::IDENT) {
if (className.compare(name) != 0)
reportSyntaxError(pos, "错误的方法声明");
return util::ListOf(
methodDeclaratorRest(pos, mods, 0, Name::init, true));
} else {
pos = L->getToken()->pos;
name = ident();
//一般方法
if (L->getToken()->id == Token::LPAREN) {
return util::ListOf(
(Tree*) methodDeclaratorRest(pos, mods, type, name,
isVoid));
} else { //成员变量
vector<Tree*> defs;
defs = variableDeclaratorsRest(pos, mods, type, name, defs);
accept(Token::SEMI);
return defs;
}
}
}
}
}
/** MethodDeclaratorRest =
* FormalParameters ( MethodBody)
* ConstructorDeclaratorRest =
* "(" FormalParameterListOpt ")" MethodBody
*/
Tree* Parser::methodDeclaratorRest(int pos, Modifiers* mods,
Expression* restype, string name, bool isVoid) {
vector<VariableDecl*> params = formalParameters();
Block* body = NULL;
if (L->getToken()->id == Token::LBRACE) {
body = block(L->getToken()->pos, 0);
} else {
// test abstract method
accept(Token::SEMI);
}
MethodDecl* method = TreeMaker::makeMethodDecl(pos, mods, restype, name,
params, body);
return method;
}
/**
* Block = "{" BlockStatements "}"
*/
Block* Parser::block(int pos, long long flags) {
accept(Token::LBRACE);
vector<Statement*> stats = blockStatements();
Block* block = TreeMaker::makeBlock(pos, flags, stats);
accept(Token::RBRACE);
block->endPos = L->getToken()->pos;
return block;
}
/*
* !!!
*
* BlockStatements = ( BlockStatement )+
* BlockStatement = LocalVariableDeclarationStatement
* | [Ident ":"] Statement
* LocalVariableDeclarationStatement
* = Type VariableDeclarators ";"
*/
vector<Statement*> Parser::blockStatements() {
vector<Statement*> stats;
int lastErrPos = -1;
while (true) {
int pos = L->getToken()->pos;
switch (L->getToken()->id) {
//直接返回的情况
case Token::RBRACE:
case Token::CASE:
case Token::DEFAULT:
case Token::EOF_:
return stats;
case Token::LBRACE:
case Token::IF:
case Token::FOR:
case Token::WHILE:
case Token::DO:
case Token::SWITCH:
case Token::RETURN:
case Token::BREAK:
case Token::CONTINUE:
case Token::SEMI:
case Token::ELSE:
//暂不支持
// case Token::FINALLY: case Token::CATCH: case Token::TRY:case Token::THROW:case Token::SYNCHRONIZED:
stats.push_back(parseStatement());
break;
//还可以支持其他情况: 内部类...
//case Token::CLASS:
default:
string name = L->getToken()->name;
Expression* t = term(TYPE | EXPR);
if ((lastmode & TYPE) != 0
&& L->getToken()->id == Token::IDENTIFIER) {
//变量声明
pos = L->getToken()->pos;
Modifiers* mods = TreeMaker::Mods(-1, 0);
vector<Statement*> vdefs;
util::appendList(stats, variableDeclarators(mods, t, vdefs));
accept(Token::SEMI);
} else {
//一条表达式语句
stats.push_back(TreeMaker::makeExec(pos, checkExprStat(t)));
accept(Token::SEMI);
}
break;
}
if (L->getToken()->pos == lastErrPos)
return stats;
if (L->getToken()->pos <= lastErrPos) {
skip(true, true, true);
lastErrPos = L->getToken()->pos;
}
}
return stats;
}
Statement* Parser::parseStatement() {
vector<Statement*> nulllist;
int pos = L->getToken()->pos;
switch (L->getToken()->id) {
case Token::LBRACE:
return block(L->getToken()->pos, 0);
break;
case Token::IF: {
L->nextToken();
Expression* cond = parExpression();
Statement* thenpart = parseStatement();
Statement* elsepart = NULL;
if (L->getToken()->id == Token::ELSE) {
L->nextToken();
elsepart = parseStatement();
}
return TreeMaker::makerIf(pos, cond, thenpart, elsepart);
}
case Token::FOR: {
L->nextToken();
accept(Token::LPAREN);
vector<Statement*> inits =
L->getToken()->id == Token::SEMI ? nulllist : forInit();
accept(Token::SEMI);
Expression* cond =
L->getToken()->id == Token::SEMI ? NULL : parseExpression();
accept(Token::SEMI);
vector<ExpressionStatement*> steps;
if (L->getToken()->id != Token::LPAREN)
steps = forUpdate();
accept(Token::RPAREN);
Statement* body = parseStatement();
return TreeMaker::makeForLoop(pos, inits, cond, steps, body);
}
case Token::WHILE: {
L->nextToken();
Expression* cond = parExpression();
Statement* body = parseStatement();
return TreeMaker::makeWhileLoop(pos, cond, body);
}
case Token::DO: {
L->nextToken();
Statement* body = parseStatement();
accept(Token::WHILE);
Expression* cond = parExpression();
accept(Token::SEMI);
return TreeMaker::makeDoLoop(pos, body, cond);
}
case Token::SWITCH: {
L->nextToken();
Expression* selector = parExpression();
accept(Token::LBRACE);
vector<Case*> cases = switchBlockStatementGroups();
accept(Token::RBRACE);
return TreeMaker::makeSwitch(pos, selector, cases);
}
case Token::RETURN: {
L->nextToken();
Expression* result =
L->getToken()->id == Token::SEMI ? NULL : parseExpression();
accept(Token::SEMI);
return TreeMaker::makeReturn(pos, result);
}
case Token::BREAK: {
L->nextToken();
string label = L->getToken()->id == Token::IDENTIFIER ? ident() : "";
accept(Token::SEMI);
return TreeMaker::makeBreak(pos, label);
}
case Token::CONTINUE: {
L->nextToken();
string label = L->getToken()->id == Token::IDENTIFIER ? ident() : "";
accept(Token::SEMI);
return TreeMaker::makeContinue(pos, label);
}
case Token::ELSE: {
reportSyntaxError(pos, "没有前置 if 的 else ");
L->nextToken();
//暂时跳过这个错误
return TreeMaker::makeSkip(pos);
}
case Token::SEMI: {
L->nextToken();
return TreeMaker::makeSkip(pos);
}
default:
Expression* expr = parseExpression();
ExpressionStatement * stat = TreeMaker::makeExec(pos, expr);
accept(Token::SEMI);
return stat;
}
}
template<class T>
vector<T> Parser::moreStatementExpressions(int pos, Expression* first,
vector<T> stats) {
stats.push_back(TreeMaker::makeExec(pos, checkExprStat(first)));
while (L->getToken()->pos == Token::COMMA) {
L->nextToken();
pos = L->getToken()->pos;
Expression* t = parseExpression();
stats.push_back(TreeMaker::makeExec(pos, checkExprStat(t)));
}
return stats;
}
/*
* ForInit = StatementExpression MoreStatementExpressions
| { FINAL } Type VariableDeclarators
*/
vector<Statement*> Parser::forInit() {
vector<Statement*> stats;
int pos = L->getToken()->pos;
if (L->getToken()->id == Token::FINAL) {
return variableDeclarators(optFinal(0), parseType(), stats);
} else {
Expression* t = term(EXPR | TYPE);
if ((lastmode & TYPE) != 0 && L->getToken()->id == Token::IDENTIFIER)
return variableDeclarators(modifiersOpt(), t, stats);
else
return moreStatementExpressions(pos, t, stats);
}
}
/**
* ForUpdate = StatementExpression MoreStatementExpressions
*/
vector<ExpressionStatement*> Parser::forUpdate() {
vector<ExpressionStatement*> stats;
return moreStatementExpressions(L->getToken()->pos, parseExpression(),
stats);
}
vector<Case*> Parser::switchBlockStatementGroups() {
vector<Case*> cases;
while (true) {
int pos = L->getToken()->pos;
switch (L->getToken()->id) {
case Token::CASE: {
L->nextToken();
Expression* pat = parseExpression();
accept(Token::COLON);
vector<Statement*> stats = blockStatements();
cases.push_back(TreeMaker::makeCase(pos, pat, stats));
break;
}
case Token::DEFAULT: {
L->nextToken();
accept(Token::COLON);
vector<Statement*> stats = blockStatements();
cases.push_back(TreeMaker::makeCase(pos, NULL, stats));
break;
}
case Token::RBRACE:
case Token::EOF_:
return cases;
default:
L->nextToken(); // 保证进程.
reportSyntaxError(pos,
Token::tokenStr(Token::CASE) + ","
+ Token::tokenStr(Token::DEFAULT) + ","
+ Token::tokenStr(Token::RBRACE));
}
}
}
/**
* FormalParameters = "(" [ FormalParameterList ] ")"
*/
vector<VariableDecl*> Parser::formalParameters() {
vector<VariableDecl*> params;
VariableDecl* lastParam = 0;
accept(Token::LPAREN);
if (L->getToken()->id != Token::RPAREN) {
params.push_back(lastParam = formalParameter());
while ((lastParam->mods->flags & Flags::VARARGS) == 0
&& L->getToken()->id == Token::COMMA) { //参数1,参数2...
L->nextToken();
params.push_back(lastParam = formalParameter());
}
}
accept(Token::RPAREN);
return params;
}
VariableDecl* Parser::formalParameter() {
Modifiers* mods = optFinal(Flags::PARAMETER);
Expression* type = parseType();
return variableDeclaratorId(mods, type);
}
MethodInvocation* Parser::arguments(Expression* t) {
int pos = L->getToken()->pos;
vector<Expression*> args = arguments();
return TreeMaker::makeApply(pos, t, args);
}
vector<Expression*> Parser::arguments() {
vector<Expression*> args;
if (L->getToken()->id == Token::LPAREN) {
L->nextToken();
if (L->getToken()->id != Token::RPAREN) {
args.push_back(parseExpression());
while (L->getToken()->id == Token::COMMA) {
L->nextToken();
args.push_back(parseExpression());
}
}
accept(Token::RPAREN);
} else {
reportSyntaxError(L->getToken()->pos,
"需要 " + Token::tokenStr(Token::LPAREN));
}
return args;
}
Expression* Parser::argumentsOpt(Expression* t) {
if ((mode & EXPR) != 0 && L->getToken()->id == Token::LPAREN) {
mode = EXPR;
return arguments(t);
} else {
return t;
}
}
/**
* VariableDeclaratorId = Ident BracketsOpt
*/
VariableDecl* Parser::variableDeclaratorId(Modifiers* mods, Expression* type) {
int pos = L->getToken()->pos;
string name = ident();
type = bracketsOpt(type);
return TreeMaker::makeVarDef(pos, mods, name, type, NULL);
}
template<class T>
vector<T> Parser::variableDeclarators(Modifiers* mods, Expression* type,
vector<T> vdefs) {
int pos = L->getToken()->pos;
return variableDeclaratorsRest(pos, mods, type, ident(), vdefs);
/**
* 原来使用,pos是ident下个token的位置,参数入栈:从右向左
*/
// return variableDeclaratorsRest(L->getToken()->pos, mods, type, ident(),
// vdefs);
}
/**
*VariableDeclaratorsRest = VariableDeclaratorRest { "," VariableDeclarator }
*/
template<class T>
vector<T> Parser::variableDeclaratorsRest(int pos, Modifiers* mods,
Expression* type, string name, vector<T> vdefs) {
vdefs.push_back(variableDeclaratorRest(pos, mods, type, name));
while (L->getToken()->id == Token::COMMA) {
L->nextToken();
vdefs.push_back(
variableDeclaratorRest(L->getToken()->pos, mods, type,
ident()));
}
return vdefs;
}
/**
* VariableDeclaratorRest = BracketsOpt ["=" VariableInitializer]
*/
VariableDecl* Parser::variableDeclaratorRest(int pos, Modifiers* mods,
Expression* type, string name) {
type = bracketsOpt(type);
Expression* init = NULL;
if (L->getToken()->id == Token::EQ) {
L->nextToken();
init = variableInitializer();
}
return TreeMaker::makeVarDef(pos, mods, name, type, init);
}
/**
* VariableInitializer = ArrayInitializer | Expression
*/
Expression* Parser::variableInitializer() {
return L->getToken()->id == Token::LBRACE ?
arrayInitializer(L->getToken()->pos, NULL) : parseExpression();
}
/**
* ArrayInitializer = "{" [VariableInitializer {"," VariableInitializer}] [","] "}"
*
*/
Expression* Parser::arrayInitializer(int pos, Expression* t) {
accept(Token::LBRACE);
vector<Expression*> defs;
if (L->getToken()->id == Token::RBRACE) {
defs.push_back(variableInitializer());
while (L->getToken()->id == Token::COMMA) {
L->nextToken();
if (L->getToken()->id == Token::RBRACE)
break;
defs.push_back(variableInitializer());
}
}
accept(Token::RBRACKET);
vector<Expression*> nullList;
return TreeMaker::makeNewArray(pos, t, nullList, defs);
}
Expression* Parser::arrayCreatorRest(int pos, Expression* elemtype) {
accept(Token::LBRACKET);
vector<Expression*> nulllist;
//int a[][] = new int[]{0,123}
if (L->getToken()->id == Token::RBRACKET) {
accept(Token::RBRACKET);
elemtype = bracketsOpt(elemtype);
if (L->getToken()->id == Token::LBRACE) {
return arrayInitializer(pos, elemtype);
} else {
Expression* t = TreeMaker::makeNewArray(pos, elemtype, nulllist,
nulllist);
reportSyntaxError(pos, "缺少数组维度");
return t;
}
} else { // int a[][] = new int[5][6];
vector<Expression*> dims;
dims.push_back(parseExpression());
accept(Token::RBRACKET);
while (L->getToken()->id == Token::LBRACKET) { //[
int pos = L->getToken()->pos;
L->nextToken();
if (L->getToken()->id == Token::RBRACKET) { //] 允许new int[5][][]
elemtype = bracketsOptCont(elemtype, pos);
} else {
dims.push_back(parseExpression());
accept(Token::RBRACKET);
}
}
return TreeMaker::makeNewArray(pos, elemtype, dims, nulllist);
}
}
PrimitiveTypeTree* Parser::basicType() {
PrimitiveTypeTree* t = TreeMaker::makeTypeIdent(L->getToken()->pos,
typetag(L->getToken()->id));
L->nextToken();
return t;
}
/**
*
*/
Expression* Parser::parseType() {
return term(TYPE);
}
Expression* Parser::parExpression() {
accept(Token::LPAREN);
Expression* t = parseExpression();
accept(Token::RPAREN);
return t;
}
/**
*
*/
Expression* Parser::parseExpression() {
return term(EXPR);
}
//在递归调用过程中可能会改变当前mode
Expression* Parser::term(int newmode) {
int premode = mode;
mode = newmode;
Expression* t = term();
lastmode = mode;
mode = premode;
return t;
}
/**
* Expression = Expression1 [ExpressionRest]
* ExpressionRest = [AssignmentOperator Expression1]
* AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" |
* "&=" | "|=" | "^=" |
* "%=" | "<<=" | ">>=" | ">>>="
* Type = Type1
* TypeNoParams = TypeNoParams1
* StatementExpression = Expression
* ConstantExpression = Expression
* 一条语句 int a = a+3*b; 表达式: x++; fun(1,3);
* 一个(不是因子)项(term)是一个可能被高优先级的运算符x和/分开,但不能被低优先级运算符分开的表达式。
*
*
*
*
*/
Expression* Parser::term() {
Expression* t = term1();
if ((mode & EXPR) != 0 && L->getToken()->id == Token::EQ
|| L->getToken()->id >= Token::PLUSEQ
&& L->getToken()->id <= Token::GTGTGTEQ)
return termRest(t);
else
return t;
}
Expression* Parser::termRest(Expression* t) {
switch (L->getToken()->id) {
case Token::EQ: {
int pos = L->getToken()->pos;
L->nextToken();
mode = EXPR;
Expression* t1 = term();
return TreeMaker::makeAssign(pos, t, t1);
}
case Token::PLUSEQ:
case Token::SUBEQ:
case Token::STAREQ:
case Token::SLASHEQ:
case Token::PERCENTEQ:
case Token::AMPEQ:
case Token::BAREQ:
case Token::CARETEQ:
case Token::LTLTEQ:
case Token::GTGTEQ:
case Token::GTGTGTEQ: {
int pos = L->getToken()->pos;
Token* tt = L->getToken();
L->nextToken();
mode = EXPR;
Expression* t1 = term();
return TreeMaker::makeAssignOp(pos, optag(tt->id), t, t1);
}
default:
return t;
}
}
/** Expression1 = Expression2 [Expression1Rest]
*
*/
Expression* Parser::term1() {
Expression* t = term2();
if ((mode & EXPR) != 0 && L->getToken()->id == Token::QUES)
return term1Rest(t);
else
return t;
}
/** Expression1Rest = ["?" Expression ":" Expression1]
* 三元表达式
*/
Expression* Parser::term1Rest(Expression* t) {
if (L->getToken()->id == Token::QUES) {
int pos = L->getToken()->pos;
L->nextToken();
Expression* t1 = term();
accept(Token::COLON);
Expression* t2 = term();
return TreeMaker::makeConditional(pos, t, t1, t2);
} else
return t;
}
/**
* Expression2 = Expression3 [Expression2Rest]
*/
Expression* Parser::term2() {
Expression* t = term3();
if ((mode & EXPR) != 0 && prec(L->getToken()->id) >= TreeInfo::orPrec) {
mode = EXPR;
return term2Rest(t, TreeInfo::orPrec);
}
return t;
}
/*
* Expression2Rest = {infixop Expression3}
* | Expression3 instanceof Type
* infixop = "||"
* | "&&"
* | "|"
* | "^"
* | "&"
* | "==" | "!="
* | "<" | ">" | "<=" | ">="
* | "<<" | ">>" | ">>>"
* | "+" | "-"
* | "*" | "/" | "%"
* 二元表达式
* x+y*z-((x+y)/x -x)
*/
Expression* Parser::term2Rest(Expression* t, int minprec) {
vector<Expression*> odStack; //值栈
vector<int> opStack; //操作数栈
vector<int> posStack; // pos栈
//20个子表达式 够用了
odStack.resize(20);
opStack.resize(20);
posStack.resize(20);
int top = 0;
odStack[0] = t;
//int startPos = L->getToken()->pos;
//第一个操作符优先级 最低,退出解析
int topOp = Token::ERROR;
int topOpPos = -1;
while (prec(L->getToken()->id) >= minprec) {
opStack[top] = topOp;
posStack[top] = topOpPos;
topOp = L->getToken()->id;
topOpPos = L->getToken()->pos;
top++;
L->nextToken();
odStack[top] = term3();
//栈顶操作符优先级大于当前操作符优先级 ,将前两个数(top,top-1)合并,放入top-1
while (top > 0 && prec(topOp) >= prec(L->getToken()->id)) {
odStack[top - 1] = TreeMaker::makeBinary(topOpPos, optag(topOp),
odStack[top - 1], odStack[top]);
top--;
topOp = opStack[top];
topOpPos = posStack[top];
}
}
t = odStack[0];
return t;
}
/** Expression3 = PrefixOp Expression3
* | "(" Expr | TypeNoParams ")" Expression3
* | Primary {Selector} {PostfixOp}
* Primary = "(" Expression ")"
* | Literal
* | [TypeArguments] THIS [Arguments]
* | [TypeArguments] SUPER SuperSuffix
* | NEW [TypeArguments] Creator
* | Ident { "." Ident }
* [ "[" ( "]" BracketsOpt "." CLASS | Expression "]" )
* | Arguments
* | "." ( CLASS | THIS | [TypeArguments] SUPER Arguments | NEW [TypeArguments] InnerCreator )
* ]
* | BasicType BracketsOpt "." CLASS
* PrefixOp = "++" | "--" | "!" | "~" | "+" | "-"
* PostfixOp = "++" | "--"
* Type3 = Ident { "." Ident } [TypeArguments] {TypeSelector} BracketsOpt
* | BasicType
* TypeNoParams3 = Ident { "." Ident } BracketsOpt
* Selector = "." [TypeArguments] Ident [Arguments]
* | "." THIS
* | "." [TypeArguments] SUPER SuperSuffix
* | "." NEW [TypeArguments] InnerCreator
* | "[" Expression "]"
* TypeSelector = "." Ident [TypeArguments]
* SuperSuffix = Arguments | "." Ident [Arguments]
*
* 不能被操作符分隔的最小子表达式
*/
Expression* Parser::term3() {
int pos = L->getToken()->pos;
Expression* t = NULL;
bool loop = true;
switch (L->getToken()->id) {
//单目操作符 ++ -- ! ~ + -
case Token::PLUSPLUS:
case Token::SUBSUB:
case Token::BANG:
case Token::TILDE:
case Token::PLUS:
case Token::SUB:
if ((mode & EXPR) != 0) {
int token = L->getToken()->id;
L->nextToken();
mode = EXPR;
// -整数 直接处理, -浮点数 由一元表达式处理
if (token == Token::SUB
&& (L->getToken()->id == Token::INTLITERAL
|| L->getToken()->id == Token::LONGLITERAL)) {
mode = EXPR;
t = literal(Name::hyphen, pos);
} else {
t = term3();
return TreeMaker::makeUnary(pos, unoptag(token), t);
}
} else {
illegal();
return t;
}
break;
//括号表达式
case Token::LPAREN:
if ((mode & EXPR) != 0) {
L->nextToken();
mode = EXPR | TYPE | NOPARAMS;
//先获取下一个term3
t = term3();
//再分别判断 term-rest表达式
t = termRest(term1Rest(term2Rest(t, TreeInfo::orPrec)));
accept(Token::RPAREN);
lastmode = mode;
mode = EXPR;
//强制类型转换
if ((lastmode & EXPR) == 0) {
Expression* t1 = term3();
return TreeMaker::makeTypeCast(pos, t, t1);
} else if ((lastmode & TYPE) != 0) {
switch (L->getToken()->id) {
case Token::BANG:
case Token::TILDE:
case Token::LPAREN:
case Token::THIS:
case Token::SUPER:
case Token::INTLITERAL:
case Token::LONGLITERAL:
case Token::FLOATLITERAL:
case Token::DOUBLELITERAL:
case Token::CHARLITERAL:
case Token::STRINGLITERAL:
case Token::TRUE:
case Token::FALSE:
case Token::NULL_:
case Token::NEW:
case Token::IDENTIFIER:
case Token::ASSERT:
case Token::ENUM:
case Token::BYTE:
case Token::SHORT:
case Token::CHAR:
case Token::INT:
case Token::LONG:
case Token::FLOAT:
case Token::DOUBLE:
case Token::BOOLEAN:
case Token::VOID:
Expression* t1 = term3();
return TreeMaker::makeTypeCast(pos, t, t1);
}
}
}
t = TreeMaker::makeParens(pos, t);
break;
case Token::THIS:
if ((mode & EXPR) != 0) {
mode = EXPR;
t = TreeMaker::makeIdent(pos, Name::_this);
L->nextToken();
//this(...) 调用构造方法
t = argumentsOpt(t);
} else {
illegal();
return t;
}
break;
//暂不支持
//case Token::SUPER
//字面常量
case Token::INTLITERAL:
case Token::LONGLITERAL:
case Token::FLOATLITERAL:
case Token::DOUBLELITERAL:
case Token::CHARLITERAL:
case Token::STRINGLITERAL:
case Token::TRUE:
case Token::FALSE:
case Token::NULL_:
if ((mode & EXPR) != 0) {
mode = EXPR;
t = literal("", L->getToken()->pos);
} else {
illegal();
return t;
}
break;
//new 构造
case Token::NEW:
if ((mode & EXPR) != 0) {
mode = EXPR;
L->nextToken();
t = creator(pos);
} else {
illegal();
return t;
}
break;
//以标识符开始的情况
case Token::IDENTIFIER:
t = TreeMaker::makeIdent(pos, ident());
loop = true;
while (loop) {
pos = L->getToken()->pos;
switch (L->getToken()->id) {
//数组声明 int a[][]
case Token::LBRACKET:
L->nextToken();
if (L->getToken()->id == Token::RBRACKET) {
L->nextToken();
t = TreeMaker::makeArray(pos, t);
// a[].CLASS情况 ---暂不支持
} else { //数组访问情况 a[0]
if ((mode & EXPR) != 0) {
mode = EXPR;
Expression* t1 = term();
t = TreeMaker::makeIndexed(pos, t, t1);
}
accept(Token::RBRACKET);
}
loop = false;
break;
//方法调用 ident(args)
case Token::LPAREN:
if ((mode & EXPR) != 0) {
mode = EXPR;
t = arguments(t);
}
loop = false;
break;
//ident.{CLASS|SUPER|THIS|NEW} 无需继续循环
//ident.ident. ...需要继续循环(IDENTIFIER), 直到找到符合终结语法
case Token::DOT:
L->nextToken();
if ((mode & EXPR) != 0) {
switch (L->getToken()->id) {
case Token::THIS:
mode = EXPR;
t = TreeMaker::makeSelect(pos, t, Name::_this);
L->nextToken();
loop = false;
break;
case Token::SUPER:
mode = EXPR;
t = TreeMaker::makeSelect(pos, t, Name::super);
L->nextToken();
loop = false;
break;
case Token::CLASS:
mode = EXPR;
t = TreeMaker::makeSelect(pos, t, Name::_class);
L->nextToken();
loop = false;
break;
default:
break;
}
}
if (!loop)
break;
t = TreeMaker::makeSelect(pos, t, ident());
break;
default:
loop = false;
break;
}
}
break;
case Token::BYTE:
case Token::SHORT:
case Token::CHAR:
case Token::INT:
case Token::LONG:
case Token::FLOAT:
case Token::DOUBLE:
case Token::BOOLEAN:
case Token::STRING: //string类型
t = bracketsSuffix(bracketsOpt(basicType()));
break;
default:
illegal();
return t;
}
//完成剩余部分 主要是方法调用后语法部分
//fun()[1] fun().fun2()...
while (true) {
int pos2 = L->getToken()->pos;
if (L->getToken()->id == Token::LBRACKET) {
L->nextToken();
if ((mode & TYPE) != 0) {
int oldmode = mode;
mode = TYPE;
if (L->getToken()->id == Token::RBRACKET) {
L->nextToken();
t = bracketsOpt(t);
t = TreeMaker::makeArray(pos2, t);
//Type 声明,找到直接返回
return t;
}
mode = oldmode;
}
if ((mode & EXPR) != 0) {
mode = EXPR;
Expression* t1 = term();
t = TreeMaker::makeIndexed(pos2, t, t1);
//表达式需要循环下去
}
accept(Token::RBRACKET);
} else if (L->getToken()->id == Token::DOT) {
L->nextToken();
if (L->getToken()->id == Token::SUPER && (mode & EXPR) != 0) {
mode = EXPR;
t = TreeMaker::makeSelect(pos2, t, Name::super);
L->nextToken();
t = argumentsOpt(t);
} else {
t = TreeMaker::makeSelect(pos2, t, ident());
t = argumentsOpt(t);
}
} else {
break;
}
}
while ((L->getToken()->id == Token::PLUSPLUS
|| L->getToken()->id == Token::SUBSUB) && (mode & EXPR) != 0) {
mode = EXPR;
int tag = 0;
if (L->getToken()->id == Token::PLUSPLUS) {
tag = Tree::POSTINC;
} else {
tag = Tree::POSTDEC;
}
t = TreeMaker::makeUnary(L->getToken()->pos, tag, t);
L->nextToken();
}
return t;
}
/** BracketsOpt = {"[" "]"}
*/
Expression* Parser::bracketsOpt(Expression* t) {
if (L->getToken()->id == Token::LBRACKET) {
int pos = L->getToken()->pos;
L->nextToken();
t = bracketsOptCont(t, pos);
}
return t;
}
/**
* BracketsSuffixExpr = "." CLASS
*/
Expression* Parser::bracketsSuffix(Expression* t) {
if ((mode & EXPR) != 0 && L->getToken()->id == Token::DOT) {
mode = EXPR;
int pos = L->getToken()->pos;
L->nextToken();
accept(Token::CLASS);
if (L->getToken()->pos == errorEndPos) {
string name = NULL;
if (L->getToken()->id == Token::IDENTIFIER) {
name = L->getToken()->name;
L->nextToken();
} else {
name = Name::error;
}
t = TreeMaker::makeSelect(pos, t, name);
} else {
t = TreeMaker::makeSelect(pos, t, Name::_class);
}
} else if ((mode & TYPE) != 0) {
mode = TYPE;
} else {
reportSyntaxError(L->getToken()->pos, "需要 .class");
}
return t;
}
/**
* 多维数组
*/
ArrayTypeTree* Parser::bracketsOptCont(Expression* t, int pos) {
accept(Token::RBRACKET);
t = bracketsOpt(t);
return TreeMaker::makeArray(pos, t);
}
/**
* /** Creator = Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest )
*/
Expression* Parser::creator(int newpos) {
//基本类型数组情况 new int[5][5]
switch (L->getToken()->id) {
case Token::BYTE:
case Token::SHORT:
case Token::CHAR:
case Token::INT:
case Token::LONG:
case Token::FLOAT:
case Token::DOUBLE:
case Token::BOOLEAN:
return arrayCreatorRest(newpos, basicType());
default:
break;
}
/**
* !!!!
*/
//类 类型 new A(args) , new A[5][5]...
//先只支持 直接调用构造函数 ,不支持内部类(new A.B)
Ident* t = TreeMaker::makeIdent(L->getToken()->pos, ident());
//类数组
if (L->getToken()->id == Token::LBRACKET) {
Expression* e = arrayCreatorRest(newpos, t);
return e;
} else if (L->getToken()->id == Token::LPAREN) {
vector<Expression*> args = arguments();
return TreeMaker::makeNewClass(newpos, args, t);
} else {
reportSyntaxError(newpos, "new 语法错误");
return NULL;
}
}
Modifiers* Parser::optFinal(long long flags) {
Modifiers* mods = modifiersOpt();
mods->flags |= flags;
return mods;
}
Expression* Parser::checkExprStat(Expression* t) {
switch (t->getTag()) {
case Tree::PREINC:
case Tree::PREDEC:
case Tree::POSTINC:
case Tree::POSTDEC:
case Tree::ASSIGN:
case Tree::BITOR_ASG:
case Tree::BITXOR_ASG:
case Tree::BITAND_ASG:
case Tree::SL_ASG:
case Tree::SR_ASG:
case Tree::USR_ASG:
case Tree::PLUS_ASG:
case Tree::MINUS_ASG:
case Tree::MUL_ASG:
case Tree::DIV_ASG:
case Tree::MOD_ASG:
case Tree::APPLY:
case Tree::NEWCLASS:
case Tree::ERRONEOUS:
return t;
default:
reportSyntaxError(t->pos, "无法识别的语句");
return t;
}
}
Modifiers* Parser::modifiersOpt() {
long long flags = 0;
int pos = L->getToken()->pos;
bool t = false;
while (true) {
long long flag = 0;
switch (L->getToken()->id) {
case Token::PRIVATE:
flag = Flags::PRIVATE;
break;
case Token::PROTECTED:
flag = Flags::PROTECTED;
break;
case Token::PUBLIC:
flag = Flags::PUBLIC;
break;
case Token::STATIC:
flag = Flags::STATIC;
break;
// case Token::TRANSIENT:
// flag = Flags::TRANSIENT;
break;
case Token::FINAL:
flag = Flags::FINAL;
break;
// case ABSTRACT:
// flag = Flags.ABSTRACT;
// break;
// case NATIVE:
// flag = Flags.NATIVE;
// break;
// case Token::VOLATILE:
// flag = Flags.VOLATILE;
// break;
// case Token::SYNCHRONIZED:
// flag = Flags::SYNCHRONIZED;
// break;
// case Token::STRICTFP:
// flag = Flags::STRICTFP;
break;
case Token::ERROR:
flag = 0;
L->nextToken();
break;
default:
t = true;
}
if (t)
break;
if ((flags & flag) != 0)
reportSyntaxError(L->getToken()->pos, "重复的修饰符");
L->nextToken();
flags |= flag;
}
return TreeMaker::Mods(pos, flags);
}
//Ident = IDENTIFIER
string Parser::ident() {
if (L->getToken()->id == Token::IDENTIFIER) {
string name = L->getToken()->name;
L->nextToken();
return name;
} else {
accept(Token::IDENTIFIER);
return "error";
}
}
/**
* !!!
* 字面常量 没有通用基类,没有想到比较好的办法
* 先粗糙解决。
*/
Expression* Parser::literal(string prefix, int pos) {
Expression* t = NULL;
switch (L->getToken()->id) {
case Token::INTLITERAL:
t = TreeMaker::makeLiteral(pos, TypeTags::INT,
prefix + L->getToken()->name);
break;
case Token::LONGLITERAL:
t = TreeMaker::makeLiteral(pos, TypeTags::LONG,
prefix + L->getToken()->name);
break;
case Token::DOUBLELITERAL:
t = TreeMaker::makeLiteral(pos, TypeTags::DOUBLE, L->getToken()->name);
break;
case Token::FLOATLITERAL:
t = TreeMaker::makeLiteral(pos, TypeTags::FLOAT, L->getToken()->name);
break;
case Token::CHARLITERAL:
t = TreeMaker::makeLiteral(pos, TypeTags::CHAR, L->getToken()->name);
break;
case Token::STRINGLITERAL:
// t = TreeMaker::makeLiteral(pos, TypeTags::CLASS, L->getToken()->name);
t = TreeMaker::makeLiteral(pos, TypeTags::STRING, L->getToken()->name);
break;
case Token::TRUE:
case Token::FALSE:
t = TreeMaker::makeLiteral(pos, TypeTags::BOOLEAN,
L->getToken()->name == "true" ? "1" : "0");
break;
case Token::NULL_:
t = TreeMaker::makeLiteral(pos, TypeTags::BOT, L->getToken()->name);
break;
default:
reportSyntaxError(pos, "解析语法(literal)异常");
}
L->nextToken();
return t;
}
void Parser::accept(int token) {
if (L->getToken()->id == token) {
L->nextToken();
} else {
reportSyntaxError(L->getToken()->pos, "需要 " + Token::tokenStr(token));
}
}
int Parser::typetag(int token) {
switch (token) {
case Token::BYTE:
return TypeTags::BYTE;
case Token::CHAR:
return TypeTags::CHAR;
case Token::SHORT:
return TypeTags::SHORT;
case Token::INT:
return TypeTags::INT;
case Token::LONG:
return TypeTags::LONG;
case Token::FLOAT:
return TypeTags::FLOAT;
case Token::DOUBLE:
return TypeTags::DOUBLE;
case Token::BOOLEAN:
return TypeTags::BOOLEAN;
case Token::STRING:
return TypeTags::STRING;
default:
return -1;
}
}
//跳过一些词元 用来错误恢复
void Parser::skip(bool stopAtMemberDecl, bool stopAtIdentifier,
bool stopAtStatement) {
while (true) {
switch (L->getToken()->id) {
case Token::SEMI:
L->nextToken();
return;
case Token::PUBLIC:
case Token::FINAL:
case Token::ABSTRACT:
case Token::MONKEYS_AT:
case Token::EOF_:
case Token::CLASS:
case Token::INTERFACE:
case Token::ENUM:
return;
case Token::IMPORT:
case Token::LBRACE:
case Token::RBRACE:
case Token::PRIVATE:
case Token::PROTECTED:
case Token::STATIC:
case Token::TRANSIENT:
case Token::NATIVE:
case Token::VOLATILE:
case Token::SYNCHRONIZED:
case Token::STRICTFP:
case Token::LT:
case Token::BYTE:
case Token::SHORT:
case Token::CHAR:
case Token::INT:
case Token::LONG:
case Token::FLOAT:
case Token::DOUBLE:
case Token::BOOLEAN:
case Token::VOID:
if (stopAtMemberDecl)
return;
break;
case Token::IDENTIFIER:
if (stopAtIdentifier)
return;
break;
case Token::CASE:
case Token::DEFAULT:
case Token::IF:
case Token::FOR:
case Token::WHILE:
case Token::DO:
case Token::TRY:
case Token::SWITCH:
case Token::RETURN:
case Token::THROW:
case Token::BREAK:
case Token::CONTINUE:
case Token::ELSE:
case Token::FINALLY:
case Token::CATCH:
if (stopAtStatement)
return;
break;
}
L->nextToken();
}
}
int Parser::optag(int token) {
switch (token) {
case Token::BARBAR:
return Tree::OR;
case Token::AMPAMP:
return Tree::AND;
case Token::BAR:
return Tree::BITOR;
case Token::BAREQ:
return Tree::BITOR_ASG;
case Token::CARET:
return Tree::BITXOR;
case Token::CARETEQ:
return Tree::BITXOR_ASG;
case Token::AMP:
return Tree::BITAND;
case Token::AMPEQ:
return Tree::BITAND_ASG;
case Token::EQEQ:
return Tree::EQ;
case Token::BANGEQ:
return Tree::NE;
case Token::LT:
return Tree::LT;
case Token::GT:
return Tree::GT;
case Token::LTEQ:
return Tree::LE;
case Token::GTEQ:
return Tree::GE;
case Token::LTLT:
return Tree::SL;
case Token::LTLTEQ:
return Tree::SL_ASG;
case Token::GTGT:
return Tree::SR;
case Token::GTGTEQ:
return Tree::SR_ASG;
case Token::GTGTGT:
return Tree::USR;
case Token::GTGTGTEQ:
return Tree::USR_ASG;
case Token::PLUS:
return Tree::PLUS;
case Token::PLUSEQ:
return Tree::PLUS_ASG;
case Token::SUB:
return Tree::MINUS;
case Token::SUBEQ:
return Tree::MINUS_ASG;
case Token::STAR:
return Tree::MUL;
case Token::STAREQ:
return Tree::MUL_ASG;
case Token::SLASH:
return Tree::DIV;
case Token::SLASHEQ:
return Tree::DIV_ASG;
case Token::PERCENT:
return Tree::MOD;
case Token::PERCENTEQ:
return Tree::MOD_ASG;
case Token::INSTANCEOF:
return Tree::TYPETEST;
default:
return -1;
}
}
int Parser::unoptag(int token) {
switch (token) {
case Token::PLUS:
return Tree::POS;
case Token::SUB:
return Tree::NEG;
case Token::BANG:
return Tree::NOT;
case Token::TILDE:
return Tree::COMPL;
case Token::PLUSPLUS:
return Tree::PREINC;
case Token::SUBSUB:
return Tree::PREDEC;
default:
return -1;
}
}
int Parser::prec(int token) {
int op = optag(token);
return (op >= 0) ? TreeInfo::opPrec(op) : -1;
}
void Parser::reportSyntaxError(int pos, string msg) {
setErrorEndPos(pos);
log->report(pos, Log::ERROR_Parser, msg);
}
void Parser::illegal() {
if ((mode & EXPR) != 0)
reportSyntaxError(L->getToken()->pos, "错误的表达式的开始");
else
reportSyntaxError(L->getToken()->pos, "错误的类型的开始");
}
void Parser::setErrorEndPos(int errPos) {
if (errPos > errorEndPos)
errorEndPos = errPos;
}
Parser::~Parser() {
}
| true |
e3cb67d2756d805cd135176cf68f1492322836f1 | C++ | BBBBBwen/Qwirkle | /LinkedList.cpp | UTF-8 | 2,174 | 3.953125 | 4 | [] | no_license | #include "LinkedList.h"
#include <random>
#include <iostream>
LinkedList::LinkedList() :
head(nullptr),
maxTiles(0) {
}
LinkedList::~LinkedList() {
for(int i = 0; i < maxTiles; i++) {
Node* del = head;
head = head->next;
if(del) {
delete del;
del = nullptr;
}
}
}
int LinkedList::getSize() {
return maxTiles;
}
//add a tile to a node and add that node to the LinkedList
void LinkedList::addNote(Tile tile) {
Node* newNode = new Node(tile, nullptr, nullptr);
if(head == nullptr) {
head = newNode;
} else {
Node* curr = head;
while(curr->next != nullptr) {
curr = curr->next;
}
newNode->previous = curr;
curr->next = newNode;
}
this->maxTiles++;
}
//delete the node that the tile belonged to
void LinkedList::deleteNode(Tile delTile) {
Node* curr = head;
while(curr != nullptr && curr->tile != delTile) {
curr = curr->next;
}
if(curr) {
if(curr == head) {
head = head->next;
} else if(curr->next == nullptr) {
curr->previous->next = nullptr;
} else {
curr->previous->next = curr->next;
curr->next->previous = curr->previous;
}
}
delete curr;
curr = nullptr;
this->maxTiles--;
}
//get the certain tile from the LinkedList
Tile LinkedList::get(int index) {
Node* curr = head;
for(int i = 0; i < index; i++) {
curr = curr->next;
}
Tile newTile = curr->tile;
return newTile;
}
//draw a tile from a random node and delete the node
Tile LinkedList::draw() {
int rand = getRandom();
Tile newTile = get(rand);
deleteNode(newTile);
return newTile;
}
//get a random integer for other purpose
int LinkedList::getRandom() {
int rand = -1;
std::random_device engine;
std::uniform_int_distribution<int> dist(0, maxTiles - 1);
while(rand < 0) {
rand = dist(engine);
}
return rand;
}
//replace the tile from a random node
Tile LinkedList::replaceTile(Tile tile) {
Tile newTile = draw();
addNote(tile);
return newTile;
}
| true |
90c5043771b92714f995fef2cb7e0c2b43db037d | C++ | AdamMartinCote/ElevationJukebox | /project/server/src/https-server/Admin.cpp | UTF-8 | 2,111 | 2.65625 | 3 | [] | no_license | #include <rapidjson/document.h>
#include "Admin.hpp"
#include <common/database/Database.hpp>
#include <http-server/http/exception/MissingTokenException.hpp>
#include <http-server/http/exception/InvalidTokenException.hpp>
#include "https/exception/AuthenticationFailureException.hpp"
namespace elevation {
Admin Admin::extractAdminDataFromRequest(const Pistache::Rest::Request& request) {
rapidjson::Document jsonDocument;
jsonDocument.Parse(request.body().c_str());
bool fieldsValid = (jsonDocument.IsObject()
&& jsonDocument.HasMember("usager")
&& jsonDocument.HasMember("mot_de_passe")
&& jsonDocument["usager"] != '\0'
&& jsonDocument["mot_de_passe"] != '\0');
if (!fieldsValid) {
throw BadRequestException{};
}
auto token = request.headers().getRaw("X-Auth-Token").value();
if (token.empty() || std::stoul(token) == 0) {
throw InvalidTokenException{token};
}
std::string username = jsonDocument["usager"].GetString();
std::string motDePasse = jsonDocument["mot_de_passe"].GetString();
uint32_t id = std::stoul(token);
return Admin{username, motDePasse, id};
}
Admin Admin::getAdminDataFromRequestToken(const Pistache::Rest::Request& request) {
auto token = request.headers().getRaw("X-Auth-Token").value();
if (token.empty()) {
throw MissingTokenException{};
}
uint32_t id = std::stoul(token);
if (id == 0) {
throw InvalidTokenException{token};
}
Database* db = Database::instance();
if (!db->isAdminConnected(id)) {
throw AuthenticationFailureException{token};
}
return Admin{"", "", id};
}
Admin::Admin(std::string username, std::string motDePasse, uint32_t id)
: m_username(username)
, m_motDePasse(motDePasse)
, m_id(id)
{ }
std::string Admin::getUsername() const {
return this->m_username;
}
std::string Admin::getMotDePasse() const {
return this->m_motDePasse;
}
uint32_t Admin::getId() const {
return this->m_id;
}
} // namespace elevation
| true |
b90ff2b7001ba55bcd6d81fbce5a9d672970c028 | C++ | seantyh/Heimdallr | /ChartParserChart.h | UTF-8 | 1,302 | 2.953125 | 3 | [] | no_license | #ifndef CHARTPARSERCHART_H
#define CHARTPARSERCHART_H
#include <unordered_set>
#include "MatchedDepRule.h"
#include <functional>
typedef MatchedDepRule EdgeType;
typedef std::unordered_set<const EdgeType*> EdgeCPtrSetType;
typedef vector<const EdgeType*> EdgeCPtrVec;
typedef std::function<bool(const EdgeType*)> CompleteEdgePred;
class ChartParserChart
{
private:
int n_complete;
int end_pos;
EdgeCPtrVec completed_edges;
EdgeCPtrVec full_edges;
EdgeCPtrSetType edge_set;
void clear();
void sort_full_edges();
CompleteEdgePred complete_edge_pred;
public:
typedef EdgeCPtrSetType::iterator iterator_t;
typedef std::pair<iterator_t, bool> pair_t;
ChartParserChart() : n_complete(0), end_pos(0){}
// interface of underlying edge_set
pair_t insert(const EdgeType* edge);
iterator_t begin() { return edge_set.begin(); }
iterator_t end() { return edge_set.end(); }
size_t size() const { return edge_set.size(); }
void erase(const EdgeType* edge) { edge_set.erase(edge); }
void set_complete_predicate(CompleteEdgePred pred) { complete_edge_pred = pred; }
// Chart operations
void reset(int end_dot_pos = 0);
int get_full_edges_count() const;
EdgeCPtrVec get_inactive_edges() const;
const EdgeCPtrVec& get_full_edges() const;
};
#endif //CHARTPARSERCHART_H | true |
c3099cd54c5cd884e2c8562f4a8127906fea8562 | C++ | Hyeongho/Academic_Materials | /C++ 4주차/복사 생성자와 대입 연산자/main.cpp | UTF-8 | 186 | 2.625 | 3 | [] | no_license | #include "Vector.h"
int main()
{
srand((unsigned int)time(NULL));
Vector u(3), v, w(3);
u.SetRand();
v = u;
w.add(u, v);
u.Print(" U ");
v.Print(" V ");
w.Print("U+V");
} | true |
31fc4ad83b3fac015f68180bf3b6ce1b5c79ff08 | C++ | bvsk35/Hopping_Bot | /GPS_Berkley/src/gps_agent_pkg/include/gps_agent_pkg/positioncontroller.h | UTF-8 | 2,532 | 2.8125 | 3 | [
"BSD-2-Clause",
"MIT"
] | permissive | /*
Controller that moves the arm to a position, either in joint space or in task
space.
*/
#pragma once
// Headers.
#include <Eigen/Dense>
// Superclass.
#include "gps_agent_pkg/controller.h"
#include "gps/proto/gps.pb.h"
namespace gps_control
{
class PositionController : public Controller
{
private:
// P gains.
Eigen::VectorXd pd_gains_p_;
// D gains.
Eigen::VectorXd pd_gains_d_;
// I gains.
Eigen::VectorXd pd_gains_i_;
// Integral terms.
Eigen::VectorXd pd_integral_;
Eigen::VectorXd i_clamp_;
// Maximum joint velocities.
Eigen::VectorXd max_velocities_;
// Temporary storage for Jacobian.
Eigen::MatrixXd temp_jacobian_;
// Temporary storage for joint angle offset.
Eigen::VectorXd temp_angles_;
// Current target (joint space).
Eigen::VectorXd target_angles_;
// Current target (task space).
Eigen::VectorXd target_pose_;
// Latest joint angles.
Eigen::VectorXd current_angles_;
// Latest joint angle velocities.
Eigen::VectorXd current_angle_velocities_;
// Latest pose.
Eigen::VectorXd current_pose_;
//Eigen::VectorXd torques_;
// Current mode.
gps::PositionControlMode mode_;
// Current arm.
gps::ActuatorType arm_;
// Time since motion start.
ros::Time start_time_;
// Time of last update.
ros::Time last_update_time_;
public:
// Constructor.
PositionController(ros::NodeHandle& n, gps::ActuatorType arm, int size);
// Destructor.
virtual ~PositionController();
// Update the controller (take an action).
virtual void update(RobotPlugin *plugin, ros::Time current_time, boost::scoped_ptr<Sample>& sample, Eigen::VectorXd &torques);
// Configure the controller.
virtual void configure_controller(OptionsMap &options);
// Check if controller is finished with its current task.
virtual bool is_finished() const;
// Reset the controller -- this is typically called when the controller is turned on.
virtual void reset(ros::Time update_time);
// Should this report when position achieved?
bool report_waiting;
};
}
/*
note that this thing may be running at the same time as the trial controller in order to control the left arm
would be good to have the following functionality:
1. go to a position (with maximum speed limit and high gains)
2. go to a position task space (Via J^T control)
3. hold position with variable stiffness
4. signal when at position with a timeout and variable stiffness (integral term?)
*/
| true |
07e91e4690faa15469a5ad6a40d2c5b9ade6d416 | C++ | SongKAY/code | /Leetcode/300. 最长上升子序列.cpp | UTF-8 | 458 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n==0)
return 0;
int result = 1;
vector<int> dp(n,1);
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
dp[i] = max(dp[i],dp[j]+1);
result = max(dp[i],result);
}
}
}
return result;
}
};
| true |
8d978afdac48788e712986f4b5f30e1d016e581f | C++ | whenugopal/qcode | /day1/11_comparsionoftriplets.cpp | UTF-8 | 852 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include<string.h>
using namespace std;
int main()
{
// stringstream sa,sb;
// string stra,strb;
// getline(cin, stra);
// getline(cin, strb);
// replace( stra.begin(), stra.end(), ',', ' ');
// replace( strb.begin(), strb.end(), ',', ' ');
// sa << stra;
// sb << strb;
// int x = 0;
// while (sa >> x)
// {
// cout << x << endl;
// }
// x = 0;
// while (sb >> x)
// {
// cout << x << endl;
// }
string str;
getline(cin, str); // For reading complete line with spaces
stringstream ss(str);
vector<int>arr;
int x;
while(ss >> x){
arr.push_back(x);
if(ss.peek() == ' ')ss.ignore();
}
for(int val : arr)cout<<arr<<" ";
}
| true |
b8ad56aa64761e61a1957ad608e6a2cd78d15f30 | C++ | matheux50295/Data-Structures | /Graph/CountNearest0inMatrixBFS.cpp | UTF-8 | 1,708 | 3.203125 | 3 | [] | no_license | /*
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
*/
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int n=matrix.size();
int m=matrix[0].size();
vector<vector<int>> res(n,vector<int>(m));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(matrix[i][j]==0)
res[i][j]=0;
else{
queue<pair<int,int>> Q;
Q.push({i,j});
int c,distance=0;
bool flag=true;
while(flag){
c=Q.size();
while(c--){
int k=Q.front().first;
int l=Q.front().second;
Q.pop();
if(matrix[k][l]==0){
res[i][j]=distance;
flag=false;
break;
}
if(k+1<n)
Q.push({k+1,l});
if(k-1>=0)
Q.push({k-1,l});
if(l+1<m)
Q.push({k,l+1});
if(l-1>=0)
Q.push({k,l-1});
}
distance++;
}
}
}
}
return res;
}
};
| true |
a9149363884852b96feef675439a8738f5582b4c | C++ | xr71/udacity-cpp-nd | /p1_multifiles/05_pointers.cpp | UTF-8 | 3,195 | 4.375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using std::vector;
void AddOne(int *);
int* AddOnePtr(int &);
int main(void)
{
int i = 5;
int j = 6;
std::cout << "the memory address of i is: " << &i << std::endl;
std::cout << "the memory address of j is: " << &j << std::endl;
/*
*
* At this point, you might be wondering why the same symbol & can be used
* to both access memory addresses and, as you've seen before, pass
* references into a function. This is a great thing to wonder about.
* The overloading of the ampersand symbol & and the * symbol probably
* contribute to much of the confusion around pointers.
* The symbols & and * have a different meaning,
* depending on which side of an equation they appear.
* This is extremely important to remember. For the & symbol,
* if it appears on the left side of an equation
* (e.g. when declaring a variable), it means that the variable is
* declared as a reference. If the & appears on the right side of an
* equation, or before a previously defined variable, it is used to return
* a memory address, as in the example above.
*
*/
// for example, if we want to store the address of the var i from above
int *ptr_i = &i;
std::cout << "the variable containing the address to i is: " << ptr_i << std::endl;
// Once you have a pointer, you may want to retrieve the object it is
// pointing to. In this case, the `*` symbol can be used again. This time,
// however, it will appear on the right hand side of an equation or in
// front of an already-defined variable, so the meaning is different.
// In this case, it is called the "dereferencing operator", and it returns
// the object being pointed to.
std::cout << "the value that the pointer address of i is: " << *ptr_i << std::endl;
// we can also create pointers of different types
vector<int> v = {1,2,3,4};
vector<int> *ptr_v = &v;
std::cout << "we have a vector address that points a vector v: " << std::endl;
std::cout << ptr_v << std::endl;
std::cout << "the first element of this vector (*ptr_v)[0] is: " << (*ptr_v)[0] << std::endl;
// we can modify a value directly by passing a pointer to a function
std::cout << std::endl;
i = 10;
// we a pointer to i called ptr_i
AddOne(ptr_i);
std::cout << *ptr_i << std::endl;
// we can do the same by returning a pointer;
i = 10;
int* ptr_i2 = AddOnePtr(i);
std::cout << *ptr_i2 << std::endl;
}
void AddOne(int *num)
{
// When using pointers with functions, some care should be taken.
// If a pointer is passed to a function and then assigned to a variable
// in the function that goes out of scope after the function finishes
// executing, then the pointer will have undefined behavior at that point -
// the memory it is pointing to might be overwritten by other parts of
// the program.
(*num)++;
}
int* AddOnePtr(int &j)
{
// we can also use a function to return a pointer
j++;
return &j;
}
| true |
5c8e2e324c9a6437cd92f8a76aeaebfddc537506 | C++ | ayavorsk/AbstractVM | /srcs/AbstractVM.cpp | UTF-8 | 2,652 | 2.84375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* AbstractVM.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ayavorsk <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/12 17:14:40 by ayavorsk #+# #+# */
/* Updated: 2018/05/12 17:14:44 by ayavorsk ### ########.fr */
/* */
/* ************************************************************************** */
#include "AbstractVM.hpp"
AbstractVM::AbstractVM()
{}
template <typename T>
void Overflow_Underflow_check(long double nbr)
{
if (nbr > std::numeric_limits<T>::max())
throw std::overflow_error("Error : Value overflow error ");
if (nbr < std::numeric_limits<T>::min())
throw std::underflow_error("Error : Value underflow error ");
}
IOperand const * AbstractVM::createInt8(std::string const & value ) const
{
int nbr = std::stoi(value);
Overflow_Underflow_check<int8_t>(nbr);
return new Operand<int8_t>(nbr, Int8);
}
IOperand const * AbstractVM::createInt16(std::string const & value ) const
{
int nbr = std::stoi(value);
Overflow_Underflow_check<int16_t>(nbr);
return new Operand<int16_t>(nbr, Int16);
}
IOperand const * AbstractVM::createInt32(std::string const & value ) const
{
long nbr = std::stoi(value);
Overflow_Underflow_check<int32_t>(nbr);
return new Operand<int32_t>(nbr, Int32);
}
IOperand const * AbstractVM::createFloat(std::string const & value ) const
{
float nbr = std::stof(value);
return new Operand<float>(nbr, Float);
}
IOperand const * AbstractVM::createDouble(std::string const & value ) const
{
long double nbr = std::stold(value);
Overflow_Underflow_check<double>(nbr);
std::cout << nbr << std::endl;
return new Operand<double>(nbr, Double);
}
IOperand const* AbstractVM::createOperand(eOperandType type, std::string const& value) const
{
static IOperand const * (AbstractVM::*create[5])(std::string const & value) const;
create[Int8] = &AbstractVM::createInt8;
create[Int16] = &AbstractVM::createInt16;
create[Int32] = &AbstractVM::createInt32;
create[Float] = &AbstractVM::createFloat;
create[Double] = &AbstractVM::createDouble;
return ((this->*create[type])(value));
}
AbstractVM::~AbstractVM(){}
| true |
be8a99f52e2d61bea4fb139312cf455d5c7092b0 | C++ | ScenarioCPP/scenario | /common/src/animator.cpp | UTF-8 | 1,896 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "animator.h"
#include<QDebug>
/*!
* \brief Animator::Animator
*/
Animator::Animator(QObject* parent) : QObject(parent),m_count(0),m_frame_index(0),m_frame_value(0),m_mode("pause") { }
/*!
* \brief animate
*/
void Animator::animate() {
if(m_mode == "loop") loop();
}
/*!
* \brief changeFrameSet
* \param frame_set
* \param mode
* \param delay
* \param frame_index
*/
void Animator::changeFrameSet(FramesContainer frame_set, QString mode, int delay, int frame_index)
{
if (m_frame_set == frame_set) { return; }
m_count = 0;
m_delay = delay;
m_frame_set = frame_set;
m_frame_index = frame_index;
m_frame_value = frame_set[frame_index];
m_mode = mode;
}
/*!
* \brief loop
* catch up any missed cycles
*/
void Animator::loop()
{
m_count ++;
while(m_count > m_delay)
{
m_count -= m_delay;
m_frame_index = (m_frame_index < m_frame_set.size()-1) ? m_frame_index + 1 : 0;
m_frame_value = m_frame_set[m_frame_index];
}
}
/*!
* \brief mode
* \return
*/
QString Animator::mode() const
{
return m_mode;
}
/*!
* \brief count
* \return
*/
int Animator::count() const { return m_count; }
/*!
* \brief delay
* \return
*/
int Animator::delay() const { return m_delay; }
/*!
* \brief frame_set
* \return
*/
FramesContainer Animator::frame_set() const { return m_frame_set; }
/*!
* \brief frame_index
* \return
*/
int Animator::frame_index() const { return m_frame_index; }
/*!
* \brief frame_value
* \return
*/
int Animator::frame_value() const { return m_frame_value; }
/*!
* \brief current_frame_rect
* \param ts
* \return
* ot sure what to do with this one yet, gives the current frame rectangle from the given
* TileSet object
*/
QRectF Animator::current_frame_rect(const TileSetPtr ts) const { return ts->frames()->at(m_frame_value)->to_rect(); }
| true |
f10969fc0f928bb1f45424484025bb5e7b1d6270 | C++ | fenixrw/HackerRank | /Algorithms/Implementation/feliperw_climbing-the-leaderboard_solution.cpp | UTF-8 | 1,266 | 2.90625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
stack<unsigned long long> rank_score;
unsigned long long n,m;
cin >> n;
for(unsigned long long i=0; i<n;i++)
{
unsigned long long score;
cin >> score;
if(rank_score.empty())
{
rank_score.push(score);
}
else if(rank_score.top() != score)
{
rank_score.push(score);
}
}
cin >> m;
for(unsigned long long i=0; i<m;i++)
{
unsigned long long aliceScore;
cin >> aliceScore;
unsigned long long rank = 1;
while(!rank_score.empty())
{
if(aliceScore > rank_score.top())
{
rank_score.pop();
}
else
{
rank = rank_score.size();
if(aliceScore < rank_score.top())
{
rank++;
}
break;
}
}
cout << rank << endl;
}
return 0;
}
| true |
4ca20614fe768e287c17f9803a601c329d7dbacb | C++ | jordantangy/pandemic-b | /sources/Dispatcher.cpp | UTF-8 | 385 | 2.546875 | 3 | [] | no_license | #include "Dispatcher.hpp"
using namespace std;
using namespace pandemic;
Player& Dispatcher::fly_direct(City city){
if(actual == city){
throw invalid_argument("You cannot fly from your current city to itself");
}
if(board.contains_researchCenter(actual)) {
actual = city;
}
else {
return Player::fly_direct(city);
}
return *this;
} | true |
17294abe332b67464a13860bf179233eef589d71 | C++ | evgenypanin/Stiven_Prata_book_cpp | /chapter_10_1/lesson_6/move_func.cpp | UTF-8 | 338 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include "move.h"
Move::Move(double a, double b)
{
m_x = a;
m_y = b;
}
void Move::showmove() const
{
std::cout << "\nX = " << m_x
<< "\nY = " << m_y << std::endl;
}
Move Move::add(const Move & m)
{
m_x += m.m_x;
m_y += m.m_y;
return *this;
}
void Move::reset(double a, double b)
{
m_x = a;
m_y = b;
}
| true |
333e8560b8ff30658bf5bbe56c605420ab4d9fb6 | C++ | musakhan18/OOP | /OOP Mini Project 2/OOP Mini Project 2/Bike.cpp | UTF-8 | 4,384 | 3.0625 | 3 | [] | no_license | #include "Bike.h"
Bike::Bike(char* Cn, char* Col, char* Vtype, int NoWheels, int power, float H, bool DB, bool SS) :Vehicle(Cn, Col, Vtype, NoWheels, power)
{
Height = H;
DiscBrake = DB;
SelfStart = SS;
}
Bike::Bike(const Bike& obj) :Vehicle(obj)
{
Height = obj.Height;
SelfStart = obj.SelfStart;
DiscBrake = obj.DiscBrake;
}
void Bike::SetHeight(float H)
{
Height = H;
}
void Bike::SetDiscBrake(bool DB)
{
DiscBrake = DB;
}
void Bike::SetSelfStart(bool SS)
{
SelfStart = SS;
}
void Bike::SetNumberOfBikes(int Num)
{
NumberOfBikes += Num;
}
int Bike::GetNumberOfBikes()const
{
return NumberOfBikes;
}
float Bike::GetHeight()const
{
return Height;
}
bool Bike::GetDiscBrake()const
{
return DiscBrake;
}
bool Bike::GetSelfStart()const
{
return SelfStart;
}
void Bike::CheckType()
{
int no = GetNumberOfWheels();
if (no == 2)
{
char* type = new char[5]{ 'B','i','k','e','\0' };
SetTypeOfVehicle(type);
}
}
Bike& Bike::operator=(const Bike& rhs)
{
SetCompanyName(rhs.GetCompanyName());
SetColor(rhs.GetColor());
SetTypeOfVehicle(rhs.GetTypeOfVehicle());
SetPowerCC(rhs.GetPowerCC());
SetNumberOfWheels(rhs.GetNumberOfWheels());
Height = rhs.Height;
SelfStart = rhs.SelfStart;
DiscBrake = rhs.DiscBrake;
return *this;
}
void Bike::display()const
{
cout << endl;
cout << "__________________________________________________________________________________________________________" << endl;
cout << "Company Color Wheels Power Type Height SelfStart DiscBrake " << endl;
cout << "----------------------------------------------------------------------------------------------------------" << endl;
cout << " " << GetCompanyName() << " " << GetColor() << " " << GetNumberOfWheels() << " " << GetPowerCC() << " " << GetTypeOfVehicle() <<" " <<Height << " " << GetSelfStart() << " " << GetDiscBrake() << endl;;
cout << "==========================================================================================================" << endl;
}
istream& Bike::input(istream& inp)
{
char* name = new char[15];
cout << "Enter Company Name: "; inp >> name;
char* colr = new char[10];
cout << "Enter Color Of Bike: "; inp >> colr;
int wheel;
cout << "Enter Number of wheels: ";inp >> wheel;
if (wheel == 2)
{
SetNumberOfWheels(wheel);
}
else
{
cout << "Bike has only 2 Wheels" << endl;
SetNumberOfWheels(2);
}
int p;
cout << "Enter Power OF Bike: ";inp >> p;
SetPowerCC(p);
float h;
cout << "Enter Height OF Bike: ";inp >> h;
cout << "Self Start" << endl;
cout << "-----------" << endl;
cout << "Press (1) if Self Start" << endl;
cout << "Press (2) if Not Self Start" << endl;
int choice;
inp >> choice;
bool SS ;
bool DB ;
if (choice == 1)
{
SS = true;
}
else if (choice == 2)
{
SS = false;
}
SetSelfStart(SS);
choice = 0;
cout << "Disk Brake" << endl;
cout << "-----------" << endl;
cout << "Press (1) if Disk Brake" << endl;
cout << "Press (2) if Not Disk Brake" << endl;
inp >> choice;
if (choice == 1)
{
DB = true;
}
else if (choice == 2)
{
DB = false;
}
SetDiscBrake(DB);
char* type = new char[5]{ 'B','i','k','e','\0' };
SetTypeOfVehicle(type);
SetCompanyName(name);
SetColor(colr);
SetHeight(h);
return inp;
}
ostream& Bike::output(ostream& out)const
{
cout << endl;
cout << "__________________________________________________________________________________________________________" << endl;
cout << "Company Color Wheels Power Type Height SelfStart DiscBrake " << endl;
cout << "----------------------------------------------------------------------------------------------------------" << endl;
cout << " " << GetCompanyName() << " " << GetColor() << " " << GetNumberOfWheels() << " " << GetPowerCC() << " " << GetTypeOfVehicle() << " " << Height << " " << GetSelfStart() << " " << GetDiscBrake() << endl;;
cout << "==========================================================================================================" << endl;
return out;
}
Bike::~Bike()
{
Height = 0;
} | true |
ef41a63bce71c712015e9c9da94fc610d6e9d1e1 | C++ | CToothAero/ASCIIRogueLike | /GameSystem.cpp | UTF-8 | 585 | 2.875 | 3 | [] | no_license | #include "GameSystem.h"
CGameSystem::CGameSystem(std::mt19937& random)
{
randomNumberGen = random;
player.createPlayer();
}
CGameSystem::~CGameSystem(void)
{
}
void CGameSystem::playGame(void){
CLevel level(randomNumberGen);
level.loadMap("levelDesign.txt", player);
bool isDone = false;
while(!isDone){
level.printMap();
characterMove(level);
level.updateMonsters(player);
}
}
void CGameSystem::characterMove(CLevel& useLevel){
char input;
printf("Enter move command: ");
input = getch();
useLevel.movePlayer(input, player);
} | true |
191e45ccddc8561158dcb329391cd82b89829a61 | C++ | lapl/Maratona | /Seletiva/Seletiva - Contest 1/C.cpp | UTF-8 | 629 | 2.703125 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <string>
#include <cmath>
#include <map>
#define FOR(i,a,b) for(int i = (a); i < (b); ++i)
#define REP(i,a) FOR(i,0,(a))
using namespace std;
typedef vector<int> vi;
int main () {
int tc;
cin >> tc;
while(tc--) {
vi v;
int x;
while(cin >> x && x) {
v.push_back(x);
}
sort(v.begin(),v.end(),greater<int>());
int ans=0;
bool ok = 1;
REP(i,v.size()) {
ans+= (2*pow(v[i],i+1));
if(ans > 5000000) { ok=0;break; }
}
if(ok) printf("%d\n", ans);
else printf("Too expensive\n");
}
return 0;
}
| true |
733e611020614c07255d76848c8e0c1497dc8e60 | C++ | HibaZubair/THIRD-SEMESTER-DEC-19 | /OOP(CPP stuff)/cpp 1.cpp | UTF-8 | 450 | 3.71875 | 4 | [] | no_license | #include<iostream>
int sum(int n ,int arr);
using namespace std;
int main()
{
int n, i, sol;
cout<<"Enter the size of an array ";
cin>>n;
int arr[n];
cout<<"Enter elements\n ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
sol=sum(n,arr[n]);
cout<<sol;
return 0;
}
int sum(int n,int arr[n])
{
int ans=0;
int i=0;
for(i=0;i<n;i++)
{
ans=ans+arr[i];
}
cout<<"The sum of the elements is = "<<ans;
return ans;
}
| true |
b1292aeacfbca6052a073f1b61e9bde2959b912d | C++ | mayah/workspace | /base/containers/vectors_io_test.cc | UTF-8 | 220 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "base/containers/vectors_io.h"
#include <gtest/gtest.h>
TEST(VectorsIOTest, print)
{
std::stringstream ss;
std::vector<int> vs { 1, 2, 3, 4, 5 };
ss << vs;
EXPECT_EQ("1 2 3 4 5", ss.str());
}
| true |
9e48129ccd9e3d7e94db09187104274f08997202 | C++ | hhhhsdxxxx/pat | /advanced/p1085.cpp | UTF-8 | 597 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
bool is_suitable(int min, int max, int p){
if(max/min == p && max%min == 0 || max/min < p)
return true;
return false;
}
int main(int argc, char const *argv[])
{
int N, p;
cin >> N >> p;
int *num = new int[N];
for(int i = 0; i < N; i++)
cin >> num[i];
sort(num, num+N);
int cnt = 0, ptr = 0;
while(cnt < N-ptr){
int l = ptr, h = N;
while(l < h-1){
if(is_suitable(num[ptr], num[(h+l)/2], p))
l = (h+l)/2;
else
h = (h+l)/2;
}
if(cnt < l+1-ptr)
cnt = l+1-ptr;
ptr++;
}
cout << cnt;
return 0;
} | true |
2efd9667a55c8cb159a96dfae202bd2bbe50a039 | C++ | justenjoyit/tiny-server | /ThreadPoolLib.h | UTF-8 | 2,129 | 2.515625 | 3 | [] | no_license | #ifndef THREADPOOLLIB_H
#define THREADPOOLLIB_H
#include<iostream>
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<strings.h>
#include<string>
#include<list>
#include<semaphore.h>
#include<vector>
#include<set>
void* manageThread(void*);
void* manageTask(void*);
void* childFunc(void*);
const int maxThreadNum=100000;
class Task
{
public:
void* (*myFunc)(void*,void*);
void* args;
void* rtns;
Task(void*(*func)(void*,void*),void*a,void*r)
{
myFunc=func;
args=a;
rtns=r;
}
Task();
Task(const Task&);
};
class TaskList
{
private:
std::list<Task*> myTaskList;
public:
//pthread_mutex_t _task_mutex;
TaskList();
~TaskList();
void addTask(void*(*func)(void*,void*),void*,void*);
void popFront();
Task* getFront();
int getSize();
};
class Thread
{
public:
pthread_t tid;
pthread_mutex_t _thread_node_mutex;
pthread_cond_t _thread_node_cond;
Task* _node_task;
Thread();
~Thread();
Thread(const Thread*);
};
class WaitingThread
{
public:
std::list<Thread*> myWaitingThreadList;
public:
//pthread_mutex_t _waiting_list_mutex;
~WaitingThread();
void addThread(Thread*);
Thread* getTop();
void popTop();
int getSize();
WaitingThread();
};
class ActiveThread
{
private:
std::list<Thread*> myActiveThreadList;
public:
//pthread_mutex_t _active_list_mutex;
~ActiveThread();
void addThread(Thread*);
void erase(Thread*);
ActiveThread();
int getSize();
};
class ThreadPool
{
private:
TaskList _taskList;
WaitingThread _waitingList;
ActiveThread _activeList;
pthread_t thread_manager,task_manager;
pthread_cond_t thread_manager_cond,task_manager_cond;
pthread_mutex_t thread_pool_mutex,thread_manager_mutex,task_manager_mutex,_active_list_mutex,_waiting_list_mutex,_task_mutex;
int size;
int largestNum,smallestNum;
int basicSize;
std::set<pthread_t> tids;
public:
void* child_func(void*);
void* manage_thread(void*);
void* manage_task(void*);
public:
ThreadPool(int);
~ThreadPool();
void initPool();
void addTask(void*(*func)(void*,void*),void*,void*);
void initSystem();
};
#endif
| true |
b76c428ad509160abfd51b50780e6d45e1bf4576 | C++ | GDDXH/First-year-of-University | /hdu.cpp/杭电2041.cpp | UTF-8 | 355 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int size,i,a[50]={0,1,1,2};
for(i=4;i<=40;i++)
{
a[i]=a[i-1]+a[i-2];
}
scanf("%d",&size);
while(size--)
{
scanf("%d",&i);
printf("%d\n",a[i]);
}
return 0;
}
| true |
910c74672977cafafe785c790749a1f4674c4f98 | C++ | jambamamba/libedgetpu | /port/blocking_counter.h | UTF-8 | 2,404 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DARWINN_PORT_BLOCKING_COUNTER_H_
#define DARWINN_PORT_BLOCKING_COUNTER_H_
#include <condition_variable> // NOLINT
#include <mutex> // NOLINT
#include "port/std_mutex_lock.h"
#include "port/thread_annotations.h"
namespace platforms {
namespace darwinn {
// This class allows a thread to block for a pre-specified number of actions.
// Based on absl implementation, execpt that std::mutex is used as opposed to
// absl::Mutex.
// TODO: Remove this implementation when we fully migrate to absl.
// See: cs/absl/synchronization/blocking_counter.h
class BlockingCounter {
public:
explicit BlockingCounter(int initial_count) : count_(initial_count) {}
BlockingCounter(const BlockingCounter&) = delete;
BlockingCounter& operator=(const BlockingCounter&) = delete;
// BlockingCounter::DecrementCount()
//
// Decrements the counter's "count" by one, and return "count == 0". This
// function requires that "count != 0" when it is called.
//
// Memory ordering: For any threads X and Y, any action taken by X
// before it calls `DecrementCount()` is visible to thread Y after
// Y's call to `DecrementCount()`, provided Y's call returns `true`.
bool DecrementCount();
// BlockingCounter::Wait()
//
// Blocks until the counter reaches zero. This function may be called at most
// once. On return, `DecrementCount()` will have been called "initial_count"
// times and the blocking counter may be destroyed.
//
// Memory ordering: For any threads X and Y, any action taken by X
// before X calls `DecrementCount()` is visible to Y after Y returns
// from `Wait()`.
void Wait();
private:
std::mutex mutex_;
std::condition_variable cv_;
int count_;
};
} // namespace darwinn
} // namespace platforms
#endif // DARWINN_PORT_BLOCKING_COUNTER_H_
| true |
af8e6bfdb4c5e73180c8c7465c5a703fed15eeb3 | C++ | Soondt/OOP | /Bai_tap/Geometry.cpp | UTF-8 | 399 | 3.125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Geometry {
public:
// virtual khong chi toi ham cha ma khi cout ra no se chi toi ham con
// dang tinh truu tuong cua class
virtual double perimeter() = 0;
virtual double area() = 0;
virtual void display()
{
cout << "Perimeter: " << perimeter() << endl;
cout << "Area: " << area() << endl;
}
};
| true |
f161462bb2c22f6b710a9f55c31bb8dd2da2d50c | C++ | xshellk/Linux_code | /fuxi/io/testSelect/io.cc | UTF-8 | 595 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<sys/select.h>
#include<unistd.h>
#include<stdio.h>
using namespace std;
int main()
{
fd_set fd;
FD_ZERO(&fd);
FD_SET(0,&fd);
string str;
for(;;)
{
cout << "Please input > ";
fflush(stdout);
int ret = select(2,&fd,NULL,NULL,NULL);
cin >> str;
if(ret < 0)
{
cout << "select error" << endl;
exit(2);
}else if(ret == 0)
{
cout << "don't get anything" << endl;
}
if(FD_ISSET(0,&fd))
{
cout << "output is > " << str << endl;
}
FD_ZERO(&fd);
FD_SET(0,&fd);
}
return 0;
}
| true |
34c733c4c210e4269dc26d6ebf32da17f619e046 | C++ | z0CoolCS/CompetitiveProgramming | /Codeforces/743A-AntonandDanik.cpp | UTF-8 | 324 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int contA=0,contD=0;
char c;
while(n--){
cin>>c;
if(c=='A')
contA++;
else
contD++;
}
if(contA>contD)
cout<<"Anton";
else if(contA==contD)
cout<<"Friendship";
else
cout<<"Danik";
return 0;
}
| true |
8bb483c065a0172353fce1fc97591b6c45f067b7 | C++ | HideakiImamura/MyCompetitiveProgramming | /ABC060_ARC073/b2.cpp | UTF-8 | 360 | 2.671875 | 3 | [] | no_license | //
// Created by 今村秀明 on 2017/05/03.
//
#include <stdio.h>
int main(int argc, char ** argv){
int a, b, c;
bool flag = 0;
scanf("%d %d %d", &a, &b, &c);
for (int i=1; i<=b; i++){
if (a*i % b == c){
flag = 1;
}
}
if(flag){
printf("YES");
}else{
printf("NO");
}
return 0;
} | true |
555913e86ae445a10ad93bd11f34e477e0490fe0 | C++ | Coolnesss/gbe | /sound.h | UTF-8 | 1,162 | 2.546875 | 3 | [] | no_license | #pragma once
#include <inttypes.h>
#include <unordered_map>
#include "sound_defs.h"
#define TCLK_HZ 4194304u
#define SAMPLE_RATE 44000u
class Sound {
public:
Sound();
void update(unsigned tclk);
bool hasNewSample();
void getSamples(sample_t *left, sample_t *right);
void writeByte(uint16_t addr, uint8_t val);
uint8_t readByte(uint16_t addr);
bool mute_ch1;
bool mute_ch2;
bool mute_ch3;
bool mute_ch4;
unsigned long samples;
private:
bool sample_ready;
unsigned clock;
sample_t lsample, rsample;
int8_t wave_pattern_ram[16];
sample_t sample_map[16];
sample_t square_map[33];
enum direction { Decrease, Increase };
struct CH1;
struct CH2;
struct CH3;
struct CH4;
struct CTRL;
struct LengthCounter;
CH1* Channel1;
CH2* Channel2;
CH3* Channel3;
CH4* Channel4;
CTRL* Control;
LengthCounter* Ch1_Length;
LengthCounter* Ch2_Length;
LengthCounter* Ch3_Length;
LengthCounter* Ch4_Length;
std::unordered_map<uint16_t, uint8_t*> reg_pointers;
sample_t updateCh1(unsigned tclock);
sample_t updateCh2(unsigned tclock);
sample_t updateCh3(unsigned tclock);
sample_t updateCh4(unsigned tclock);
};
// 1 step = n/64 sec | true |
3f38f716e6db5a9712951dfe8127f184ee73280d | C++ | ennehekma/atom | /test/testPrintFunctions.cpp | UTF-8 | 4,410 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#include <sstream>
#include <catch.hpp>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_vector.h>
#include "Atom/printFunctions.hpp"
namespace atom
{
namespace tests
{
int computeCartesianToTwoLineElementsTestFunction(
const gsl_vector* independentVariables, void* parameters, gsl_vector* residuals )
{
gsl_vector_set( residuals, 0, 1.2 );
gsl_vector_set( residuals, 1, 2.3 );
gsl_vector_set( residuals, 2, 3.4 );
gsl_vector_set( residuals, 3, 4.5 );
gsl_vector_set( residuals, 4, 5.6 );
gsl_vector_set( residuals, 5, 6.7 );
return GSL_SUCCESS;
}
int computeAtomTestFunction(
const gsl_vector* independentVariables, void* parameters, gsl_vector* residuals )
{
gsl_vector_set( residuals, 0, 1.2 );
gsl_vector_set( residuals, 1, 2.3 );
gsl_vector_set( residuals, 2, 3.4 );
return GSL_SUCCESS;
}
struct Parameters{ };
TEST_CASE( "Print Cartesian state to Two-Line-Elements table header", "[print]" )
{
// Set expected output string.
std::ostringstream tableHeader;
tableHeader
<< "# i RAAN e AoP M "
<< "n f1 f2 f3 f4 "
<< "f5 f6 "
<< std::endl;
REQUIRE( printCartesianToTleSolverStateTableHeader( ) == tableHeader.str( ) );
}
TEST_CASE( "Print Cartesian state to Two-Line-Elements solver state", "[print]" )
{
// Set initial guess for GSL solver.
gsl_vector* initialGuess = gsl_vector_alloc( 6 );
gsl_vector_set( initialGuess, 0, 0.1 );
gsl_vector_set( initialGuess, 1, 0.2 );
gsl_vector_set( initialGuess, 2, 0.3 );
gsl_vector_set( initialGuess, 3, 0.4 );
gsl_vector_set( initialGuess, 4, 0.5 );
gsl_vector_set( initialGuess, 5, 0.6 );
// Set up dummy GSL solver.
Parameters parameters;
gsl_multiroot_function testFunction
= { &computeCartesianToTwoLineElementsTestFunction,
6,
¶meters };
const gsl_multiroot_fsolver_type* solverType = gsl_multiroot_fsolver_hybrids;
gsl_multiroot_fsolver* solver = gsl_multiroot_fsolver_alloc( solverType, 6 );
gsl_multiroot_fsolver_set( solver, &testFunction, initialGuess );
// Set expected output string.
std::ostringstream tableRow;
tableRow << "0 0.1 0.2 0.3 0.4 0.5 "
<< "0.6 1.2 2.3 3.4 4.5 "
<< "5.6 6.7 "
<< std::endl;
REQUIRE( printCartesianToTleSolverState( 0, solver ) == tableRow.str( ) );
}
TEST_CASE( "Print Atom solver table header", "[print-atom-solver]")
{
// Set expected output string.
std::ostringstream tableHeader;
tableHeader
<< "# v1_x v1_y v1_z "
<< "f1 f2 f3 "
<< std::endl;
REQUIRE( printAtomSolverStateTableHeader( ) == tableHeader.str( ) );
}
TEST_CASE( "Print Atom solver state", "[print]" )
{
// Set initial guess for GSL solver.
gsl_vector* initialGuess = gsl_vector_alloc( 3 );
gsl_vector_set( initialGuess, 0, 0.1 );
gsl_vector_set( initialGuess, 1, 0.2 );
gsl_vector_set( initialGuess, 2, 0.3 );
// Set up dummy GSL solver.
Parameters parameters;
gsl_multiroot_function testFunction = { &computeAtomTestFunction, 3, ¶meters };
const gsl_multiroot_fsolver_type* solverType = gsl_multiroot_fsolver_hybrids;
gsl_multiroot_fsolver* solver = gsl_multiroot_fsolver_alloc( solverType, 3 );
gsl_multiroot_fsolver_set( solver, &testFunction, initialGuess );
// Set expected output string.
std::ostringstream tableRow;
tableRow << "0 0.1 0.2 0.3 "
<< "1.2 2.3 3.4 "
<< std::endl;
REQUIRE( printAtomSolverState( 0, solver ) == tableRow.str( ) );
}
TEST_CASE( "Print element", "[print]" )
{
REQUIRE( printElement( "test", 10 ) == "test " );
REQUIRE( printElement( 1.2345, 10, '.' ) == "1.2345...." );
}
} // namespace tests
} // namespace atom
| true |
f1b9f032eb93207663bbedb507b2ee10fb287f23 | C++ | mikosz/CoconutTools | /coconut-tools-concurrent/src/main/c++/coconut-tools/concurrent/LockableInstance.hpp | UTF-8 | 1,190 | 3 | 3 | [] | no_license | #ifndef COCONUTTOOLS_CONCURRENT_LOCKABLEINSTANCE_HPP_
#define COCONUTTOOLS_CONCURRENT_LOCKABLEINSTANCE_HPP_
#include <mutex>
#include "LockingPtr.hpp"
#include "LockTraits.hpp"
namespace coconut_tools {
namespace concurrent {
// TODO: Lockable* needs redesign
template <class T, class M = std::mutex>
class LockableInstance {
public:
using Mutex = M;
using ReadLock = typename LockTraits<Mutex>::SharedLock;
using WriteLock = typename LockTraits<Mutex>::UniqueLock;
using ReadLocked = LockingPtr<const T, M, ReadLock>;
using WriteLocked = LockingPtr<T, M, WriteLock>;
template <class... Args>
LockableInstance(Args&&... args) :
object_(std::forward<Args>(args)...)
{
}
Mutex& mutex() const volatile {
return const_cast<Mutex&>(mutex_);
}
ReadLocked lock() const volatile {
return ReadLocked(static_cast<const volatile T&>(object_), mutex());
}
WriteLocked lock() volatile {
return WriteLocked(static_cast<volatile T&>(object_), mutex());
}
private:
mutable Mutex mutex_;
T object_;
};
} // namespace concurrent
} // namespace CoconutTools
#endif /* COCONUTTOOLS_CONCURRENT_LOCKABLEINSTANCE_HPP_ */
| true |
43d2cf2fb4ec8c5232d75e77385e1cebbdf9ae1e | C++ | ChrisLane/Cpp---Expression-Evaluation | /src/evalobjmain.cpp | UTF-8 | 2,012 | 2.953125 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
#include "evalobj.h"
int main(int argc, const char *argv[]) {
/**
* Test 1
*/
Exp *e1, *e2, *e3, *e4, *e5;
ExpList *l = nullptr;
l = new ExpList(new Constant(23), l);
l = new ExpList(new Constant(42), l);
l = new ExpList(new Constant(666), l);
e1 = new OpApp(plusop, l);
cout << e1->eval(nullptr) << endl; // should print 731
/**
* Test 2
*/
l = nullptr;
l = new ExpList(new Constant(5), l);
l = new ExpList(new Constant(3), l);
l = new ExpList(new Constant(2), l);
e1 = new OpApp(plusop, l);
l = nullptr;
l = new ExpList(new Var("x"), l);
l = new ExpList(new Var("x"), l);
l = new ExpList(new Var("x"), l);
e2 = new OpApp(timesop, l);
e1 = new Let("x", e1, e2);
cout << e1->eval(nullptr) << endl; // should print 1000
/**
* Test 3
*/
l = nullptr;
l = new ExpList(new Constant(5), l);
l = new ExpList(new Constant(3), l);
l = new ExpList(new Constant(2), l);
e1 = new OpApp(plusop, l);
l = nullptr;
l = new ExpList(new Var("y"), l);
l = new ExpList(new Var("x"), l);
l = new ExpList(new Var("z"), l);
e2 = new OpApp(timesop, l);
e3 = new Let("x", e1, e2);
e4 = new Let("y", new Constant(5), e3);
e5 = new Let("z", new Constant(40), e4);
cout << e5->eval(nullptr) << endl; // should print 2000
/**
* Test 4
*/
l = nullptr;
l = new ExpList(new Constant(3), l);
l = new ExpList(new Var("x"), l);
e2 = new OpApp(plusop, l);
l = nullptr;
l = new ExpList(new Constant(9), l);
l = new ExpList(new Var("x"), l);
e5 = new OpApp(plusop, l);
e4 = new Let("x", new Constant(4), e5);
l = nullptr;
l = new ExpList(e4, l);
l = new ExpList(new Var("x"), l);
e3 = new OpApp(plusop, l);
e1 = new Let("x", new Let("x", new Constant(2), e2), e3);
cout << e1->eval(nullptr) << endl; // should print 18
}
| true |
d1ee00ef31d891aed56494e5398d88100027875a | C++ | imyjalil/NCRwork | /C++/Assignment 2/program 2/program 2.cpp | UTF-8 | 1,269 | 3.640625 | 4 | [] | no_license | #include "pch.h"
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Student
{
int rno, m1, m2, total;
char grade;
string name;
public:
friend void result(Student s[], int n);
friend istream& operator >> (istream& cin, Student &s);
friend ostream& operator <<(ostream& cout, Student s);
};
istream& operator >> (istream& cin, Student &s)
{
cout << "enter rno and name: ";
cin >> s.rno;
getline(cin, s.name);
cout << "enter 2 marks: ";
cin >> s.m1 >> s.m2;
s.total = s.m1 + s.m2;
return cin;
}
ostream& operator<<(ostream& cout, Student s)
{
cout << "Name: " << s.name << endl << "Roll no: " << s.rno << endl;
cout << "Marks: m1: " << s.m1 << ", m2: " << s.m2 << endl;
cout << "Total: " << s.total << endl;
cout << "Grade: " << s.grade << endl << endl;
return cout;
}
void generate_results(Student s[], int n)
{
for (int i = 0; i < n; i++)
{
if (s[i].total >= 15)
s[i].grade = 'A';
else if (s[i].total >= 10 && s[i].total < 15)
s[i].grade = 'B';
else if (s[i].total >= 5 && s[i].total < 10)
s[i].grade = 'C';
else
s[i].grade = 'F';
}
}
int main()
{
const int n = 2;
Student s1[n];
for (int i = 0; i < n; i++) cin >> s1[i];
result(s1, n);
for (int i = 0; i < n; i++) cout << s1[i];
return 0;
} | true |
be276386ead92cc507babab7b70ba19728bff6bf | C++ | matovitch/dmit | /lib/include/dmit/com/logger.hpp | UTF-8 | 987 | 2.578125 | 3 | [] | no_license | #pragma once
#include "dmit/com/singleton.hpp"
#include "dmit/com/type_flag.hpp"
#include <sstream>
#include <ostream>
namespace dmit
{
namespace fmt { struct Formatable; } // To avoid depending upon dmit::fmt
namespace com
{
namespace logger
{
class Sub
{
public:
Sub(std::ostream& os);
template <class Type, DMIT_COM_TYPE_FLAG_CHECK_IS_NOT(fmt::Formatable, Type)>
Sub& operator<<(const Type& notLoggable)
{
_oss << notLoggable;
return *this;
}
const std::ostringstream& stream() const;
void flush();
void clear();
~Sub();
private:
std::ostringstream _oss;
std::ostream& _os;
};
} // namespace logger
struct Logger : Singletonable
{
Logger();
logger::Sub _out;
logger::Sub _err;
};
} // namespace com
} // namespace dmit
#define DMIT_COM_LOG_OUT dmit::com::TSingleton<dmit::com::Logger>::instance()._out
#define DMIT_COM_LOG_ERR dmit::com::TSingleton<dmit::com::Logger>::instance()._err
| true |
0b3454c4ef4bf3a59bf646507cb3a9588fa2008c | C++ | swayamxd/noobmaster69 | /CTCI/1-Data-Structures/1-Arrays-and-Strings/Suvo/1-3-URLify.cpp | UTF-8 | 541 | 3.15625 | 3 | [] | no_license | // CPP program to convert string
// to char array
#include <iostream>
#include <string.h>
using namespace std;
// driver code
int main()
{
string s;
cout << "Enter the string" << endl;
getline(cin,s);
char p[s.length()];
int i,j;
for (i = 0; i < s.length(); i++) {
if (s[i]==' '){
p[i] = '%';
p[i-1] = '2';
p[i-2] = '0';
cout << p[i];
cout << p[i-1];
cout << p[i-2];
}
else{
p[i] = s[i];
cout << p[i];
}
// cout << p[i];
}
return 0;
}
| true |
1d640f26913866d186ec53d4e32378560cc45aa0 | C++ | SINAABBASI/Useful-Algorithms | /topological_sort.cpp | UTF-8 | 585 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<int> adj[111111];
bool end[11111];
bool see[11111];
stack < int > s;
////find cycle in graph
bool dfs(int v){
see[v]=1;
for(int i =0 ;i <adj[v].size(); i++){
int u =adj[v][i];
if(!see[u])dfs(u);
if(end[u] == false)return 0;
}
end[v] = 1;
st.push(v);
return 1;
}
bool topo(){
memset(see,0,sizeof see);
memset(end,0,sizeof end);
for(int i =0 ;i < n; i++)
if(!see[u] && !dfs(i))return 0;
return 1;
}
int main(){
if(topo()){
while(!st.empty()){
cout<<st.top()<<" ";
st.pop();
}
}
else
cout<<-1;
} | true |
b4a463c760690f5cf012050c76ff393b13572dd0 | C++ | MorariuT/ONI | /Ciupercute fermecate/main.cpp | UTF-8 | 850 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
ifstream fin("ciuperci.in");
ofstream fout("ciuperci.out");
int main()
{
int n = 0;
int num_prime = 0;
int num_divizibile = 0;
int i = 1;
int ciuperci = 0;
fin >> n;
while(i <= n)
{ //Pentru fiecare ciuperca6
fin >> ciuperci;
int d = ciuperci-1;
int j = 2;
int num = 0;
while(j <= d)
{
if(ciuperci % j == 0)
{
num = num+1;
}
j = j+1;
}
if(num > 0)
{
num_divizibile = num_divizibile+1;
}
if(num == 0)
{
num_prime = num_prime+1;
}
i = i+1;
}
fout << num_prime << " " << num_divizibile << endl;
return 0;
}
| true |
58f27d8681b9acc0765b83261a87cf6ee952a00c | C++ | karangoel16/leetcode | /53.maximum-subarray.141493490.ac.cpp | UTF-8 | 984 | 3.375 | 3 | [] | no_license | /*
* [53] Maximum Subarray
*
* https://leetcode.com/problems/maximum-subarray/description/
*
* algorithms
* Easy (40.23%)
* Total Accepted: 287.1K
* Total Submissions: 713.7K
* Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
*
*
* Find the contiguous subarray within an array (containing at least one
* number) which has the largest sum.
*
*
* For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
* the contiguous subarray [4,-1,2,1] has the largest sum = 6.
*
*
* click to show more practice.
*
* More practice:
*
* If you have figured out the O(n) solution, try coding another solution using
* the divide and conquer approach, which is more subtle.
*
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxpre=nums[0],maxhere=nums[0];
for(int i=1;i<nums.size();i++){
maxpre=std::max(maxpre+nums[i],nums[i]);
maxhere=std::max(maxpre,maxhere);
}
return maxhere;
}
};
| true |
8f92906951cf4d16de1ee02452e2834d01f0f55c | C++ | JulesJae/piscineCPP | /d01/ex03/ZombieHorde.cpp | UTF-8 | 1,010 | 3.171875 | 3 | [] | no_license | #include "ZombieHorde.hpp"
#include <iostream>
#include <ctime>
char const *ZombieHorde::_names[] = { "Philidor", "Anand", "Karpov", "Kasparov", "Fischer", "Laskin", "Lasker", "Capablanca", "Alekhine" };
ZombieHorde::ZombieHorde(int n)
{
int i(0);
int random;
int size;
this->_n = n;
if (n < 0)
{
std::cout << "ZombieHorde: creation parameter must be a positive number\n";
return;
}
try {
this->_zombies = new Zombie[n];
std::srand(std::time(nullptr));
size = sizeof(ZombieHorde::_names) / sizeof(char*);
while (i < n)
{
random = std::rand() % size;
this->_zombies[i].name = ZombieHorde::_names[random];
i++;
}
} catch (std::bad_alloc &e)
{
std::cout << " Exception bad Alloc catched\n";
}
}
ZombieHorde::~ZombieHorde()
{
if (this->_n > 0)
{
std::cout << "Bye bye my dear champs ...\n";
delete[] this->_zombies;
}
}
void ZombieHorde::announce() const
{
int i(0);
while (i < this->_n)
{
this->_zombies[i].advert();
i++;
}
}
| true |