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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5ac34af8c3093bc2ef1dc5342fee76a13e66bcb9 | C++ | ShiqiHe000/DG_wave_c | /src/dg_unit.cpp | UTF-8 | 1,855 | 2.734375 | 3 | [] | no_license | #include "dg_unit.h"
#include "dg_param.h"
#include <vector>
/// @brief
/// constructor (default).
/// default: level = 0, n = min poly order, m = max poly order
/// index = {0, 0, 0}, mpi_f = false, x/ycoords = {0.0, 0.0}
/// solution = nullptr.
Unit::Unit() : n(grid::nmin), m(grid::nmin)
{
facen = std::vector<std::vector<Face>>(4);
ref_x = std::vector<double>(2);
ref_y = std::vector<double>(2);
// initialize element reference boudaries. Reference space [-1, 1]
ref_x[0] = -1.0; ref_y[0] = -1.0;
ref_x[1] = 1.0; ref_y[1] = 1.0;
}
// default construtor1
Unit::Face::Face() : hlevel{}, porderx{}, pordery{}, key{}, rank{}
{
ref_x = std::vector<double> {-1.0, 1.0};
ref_y = std::vector<double> {-1.0, 1.0};
}
// constructor2
Unit::Face::Face(char c, int h, int nx, int ny, long long int k, int r, double* ref1, double* ref2)
: face_type(c), hlevel(h), porderx(nx), pordery(ny), key(k), rank(r)
{
ref_x = std::vector<double> {ref1[0], ref1[1]};
ref_y = std::vector<double> {ref2[0], ref2[1]};
}
// constructor3
Unit::Face::Face(char c, int h, int nx, int ny, long long int k, int r, std::vector<double>& ref1, std::vector<double>& ref2)
: face_type(c), hlevel(h), porderx(nx), pordery(ny), key(k), rank(r)
{
ref_x = ref1;
ref_y = ref2;
}
// copy constructor ------------------------------------------------
Unit::Face::Face(const Face& face){ // copy another instance
face_type = face.face_type;
hlevel = face.hlevel;
porderx = face.porderx;
pordery = face.pordery;
key = face.key;
rank = face.rank;
ref_x = face.ref_x;
ref_y = face.ref_y;
}
Unit::Face::Face(const std::vector<Face>::iterator p){ // copy by pointer
face_type = p -> face_type;
hlevel = p -> hlevel;
porderx = p -> porderx;
pordery = p -> pordery;
key = p -> key;
rank = p -> rank;
ref_x = p -> ref_x;
ref_y = p -> ref_y;
}
| true |
53cf6df3c8dfe45c62c9a1f0ab06897091465aba | C++ | JPedroSilveira/projeto-robotica-para-a-vida | /Clube de Robótica - Botão e Buzzer/Clube de Robica - Bot苚 e Buzzer/botao_basico/botao_basico.ino | UTF-8 | 475 | 2.765625 | 3 | [
"MIT"
] | permissive | const int botao = 7;
const int led = 13;
int leitura_botao = 0;
void setup() {
Serial.begin(9600);
pinMode(botao, INPUT);
pinMode(led, OUTPUT);
}
void loop() {
leitura_botao = digitalRead(botao);
Serial.println(leitura_botao);
if(leitura_botao == 1){
digitalWrite(led, HIGH);
//se o botao for pressionado liga o led
}else{
digitalWrite(led, LOW);
//se o botao nao estiver sendo pressionado desliga o led
}
}
| true |
fd487b1568cde3a473812f0892cfa4ec4efd1372 | C++ | wyattwhiting/CS162 | /programs/program05/LinkedList.cpp | UTF-8 | 12,925 | 3.671875 | 4 | [] | no_license | /******************************************************
** File: LinkedList.cpp
** Author: Wyatt Whiting
** Date: 2020-12-02
** Description: linked list class implementation
******************************************************/
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include "LinkedList.h"
#define LL LinkedList
using namespace std;
/*******************************************************
* Function: LL::LinkedList()
* Description: linked list class constructor
* Parameters: none
* Pre-Conditions: list does not exist
* Post-Conditions: list exists
*******************************************************/
LL::LinkedList()
{
//list start with no elements and NULL head
this->length = 0;
this->head = NULL;
}
/*******************************************************
* Function: LL::~LinkedList()
* Description: linked list destructor
* Parameters: none
* Pre-Conditions: list exists
* Post-Conditions: list no longer exists
*******************************************************/
LL::~LinkedList() { this->clear(); }
/*******************************************************
* Function: int LL::getLength()
* Description: returns number of elements in linked list
* Parameters: none
* Pre-Conditions: none
* Post-Conditions: none
*******************************************************/
int LL::getLength() { return this->length; }
/*******************************************************
* Function: void LL::print()
* Description: prints elements of linked list
* Parameters: none
* Pre-Conditions: none
* Post-Conditions: elements of linked list are printed
* to screen
*******************************************************/
void LL::print()
{
//start at head node
Node *curr = head;
for (int i = 0; i < length; i++)
{
cout << curr->val << ' '; //print current value
curr = curr->next; //go to next node
}
//print extra line
cout << endl;
}
/*******************************************************
* Function: void LL::clear()
* Description: deletes all the nodes of a linked list
* Parameters: none
* Pre-Conditions: linked list has nodes in heap
* Post-Conditions: nodes are deleted from heap
*******************************************************/
void LL::clear()
{
while (this->length != 0) //until we get length of 0
{
Node *curr = head; //current node pointer
for (int i = 0; i < (this->length) - 1; i++)
curr = curr->next; //go to second to last Node
delete curr->next; //delete the next Node
this->length--; //reduce the length
}
delete head; //delete the head
//reset to default state
head = NULL;
length = 0;
}
/*******************************************************
* Function: unsigned int LL::pushFront(int val)
* Description: adds new node to beginning of list
* Parameters: int val - value to add to list
* Pre-Conditions: linked list object exists
* Post-Conditions: new node is added to beginning of list
*******************************************************/
unsigned int LL::pushFront(int val)
{
this->length++;
Node *temp = head; //save pointer to old head
head = new Node(val, temp); //head replaced with pointer to new node
return this->length;
}
/*******************************************************
* Function: unsigned int LL::pushBack(int val)
* Description: adds new node with value to end of list
* Parameters: int val - value for new node
* Pre-Conditions: list exist
* Post-Conditions: node with value 'val' added to end of list
*******************************************************/
unsigned int LL::pushBack(int val)
{
//increment length
this->length++;
//if no elements, just set it
if (head == NULL)
head = new Node(val);
//otherwise
else
{
Node *curr = head; //start at head
while (curr->next != NULL) //until we get to end of list
{
curr = curr->next; //increment the curr pointer
}
//curr is now pointing to end of list
//add new node to next pointer
curr->next = new Node(val);
}
//return
return this->length;
}
/*******************************************************
* Function: unsigned int LL::insert(int val, unsigned int index)
* Description: inserts new node at specified index
* Parameters: int val - value for new node
* unsigned int index - index for new node
* Pre-Conditions: list exists and 'index' is in valid range
* Post-Conditions: node with value 'val' added to linked list
* at index 'index'
*******************************************************/
unsigned int LL::insert(int val, unsigned int index)
{
if (index == 0)
return pushFront(val); //if at beginning just call pushFront
if (index == length)
return pushBack(val); //if at back just call pushBack
//if beyond possible index to add
if (index > this->length)
{
//print error message and do nothing
cout << "ERROR: Index outside possible range" << endl;
return this->length;
}
//once here, index is validated
Node *curr = this->head; //curr is pointer to current node
for (int i = 0; i < index - 1; i++)
{
curr = curr->next;
}
Node *next = curr->next; //store pointer to following element
curr->next = new Node(val, next); //insert the new node with saved pointer
//increment length
this->length++;
//return length
return this->length;
}
/*******************************************************
* Function: void LL::sortAscending()
* Description: calls recursive merge sort for ascending order
* Parameters: none
* Pre-Conditions: list is unordered
* Post-Conditions: list is sorted in ascending order
*******************************************************/
void LL::sortAscending() { mergeSort(&(this->head), true); }
/*******************************************************
* Function: void LL::sortDescending()
* Description: calls recursive merge sort for descending order
* Parameters: none
* Pre-Conditions: list is unordered
* Post-Conditions: list is sorted in descending order
*******************************************************/
void LL::sortDescending() { mergeSort(&(this->head), false); }
/*******************************************************
* Function: void LL::mergeSort(Node ** begin, bool ascend)
* Description: revursive merge sort function for linked list.
* Works by changing pointers, not values.
* Parameters: Node ** begin - double pointer to beinning of linked list
* bool ascend - bool to indicate if sorting should be in ascending order
* Pre-Conditions: list is undordered
* Post-Conditions: list is sorted in order according to 'ascend'
*******************************************************/
void LL::mergeSort(Node ** begin, bool ascend)
{
//let's get some variables going
Node * start = *begin;
Node * n1;
Node * n2;
//base case: if list is empty or one element, do nothing
if (start == NULL || start->next == NULL)
return;
//split list into halves
split(&n1, &n2, start);
//recursive call for mergeSort on each half, now that split() has
//split them into two null-terminated lists starting at n1 and n2
mergeSort(&n1, ascend);
mergeSort(&n2, ascend);
//set the dereferenced double pointer to result of merged halves
*begin = mergeLists(n1, n2, ascend);
}
/*******************************************************
* Function: void LL::split(Node * listStart, Node ** first, Node ** second)
* Description: splits linked list into two independ linked list
* Parameters: Node * listStart - beginning of list
* Node ** first - double pointer to node at start of first half of list
* Node ** second - double pointer to node at start of second half of list
* Pre-Conditions: list exists, and listStart points to beginning of the list to be split
* Post-Conditions: first set to beginning of first half, same with second for second half
*******************************************************/
void LL::split(Node ** first, Node ** second, Node * listStart)
{
//some local node pointers
Node * n1 = listStart->next;
Node * n2 = listStart;
while (n1 != NULL) //until n1 is the end of th list
{
n1 = n1->next; //advance n1 by 1
if (n1 != NULL) //if that didn't hit the end
{
//increment them both
n1 = n1->next;
n2 = n2->next;
}
}
//set address of 'first' to start of list
*first = listStart;
//set address of 'second' to node after n2
*second = n2->next;
//split the list at the n2 node to make two new independant lists
n2->next = NULL;
}
/*******************************************************
* Function: Node * LL::mergeLists(Node * n1, Node * n2, bool ascend)
* Description: returns pointer to beginning of merged list
* Parameters: Node * n1 - pointer to first Node of first half to merge
* Node * n2 - pointer to first Node of second half to merge
* Pre-Conditions: halves must be split
* Post-Conditions: returns pointer to merged list
*******************************************************/
Node * LL::mergeLists(Node * n1, Node * n2, bool ascend)
{
//local node pointer
Node * sorted = NULL;
//base case: function gets passed n1 or n2 which are NULL, indicating there is no next element to sort
if (n1 == NULL)
return n2;
if (n2 == NULL)
return n1;
//determine which smaller
//if n1 is smaller
if (ascend)
{
if (n1->val <= n2->val)
{
//put n1 into sorted list
sorted = n1;
//next element determined by recurisve call with remaining elements
sorted->next = mergeLists(n1->next, n2, ascend);
}
else //otherwise...
{
//do the opposite
sorted = n2;
sorted->next = mergeLists(n1, n2->next, ascend);
}
}
//for desceding order
else
{
if (n1->val >= n2->val)
{
//put n1 into sorted list
sorted = n1;
//next element determined by recurisve call with remaining elements
sorted->next = mergeLists(n1->next, n2, ascend);
}
else //otherwise...
{
//do the opposite
sorted = n2;
sorted->next = mergeLists(n1, n2->next, ascend);
}
}
//once code reaches here, base cases must have been reached, so return the sorted list
return sorted;
}
/*******************************************************
* Function: bool LL::isPrime(unsigned int val)
* Description: returns if function argument is prime
* Parameters: unsigned int val - value to check primeness of
* Pre-Conditions: none
* Post-Conditions: none, state of list unchanged
*******************************************************/
bool LL::isPrime(unsigned int val)
{
//deal with edge cases
if (val == 2 || val == 3)
return true;
//loop through all possible factors
for (int i = 2; i < (int)(val / 2); i++)
if (val % i == 0) //if factor is found
return false; //it's not prime
//if here, must be prime
return true;
}
/*******************************************************
* Function: int LL::countPrimes()
* Description: counts the number of primes in a list
* Parameters: none
* Pre-Conditions: none
* Post-Conditions: none - state unchanged
*******************************************************/
int LL::countPrimes()
{
if (this->length == 0)
return 0; //if list is empty there can be no primes
//hacky fix, don't want to track down bug
if (this->length == 1 && isPrime(this->head->val)) return 1;
Node * curr = head; //current node to check
int primeCount = 0; //count of prime numbers
//loop through all nodes
for (int i = 0; i < this->length - 1; i++)
{
//only if the current node value is greater than or equal to 2
if (curr->val >= 2)
//add to prime count
primeCount += isPrime(curr->val);
//advance curr pointer
curr = curr->next;
}
//return total found primes
return primeCount;
} | true |
63cba1512a7b33adc145f09671e7b214d4542aa1 | C++ | zoozooll/glsamples | /sampleB_8_3/src/main/jni/hellocpp/MyCompoundShape.cpp | GB18030 | 3,416 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include "MyCompoundShape.h"
MyCompoundShape::MyCompoundShape(
btDynamicsWorld* dynamicsWorld,
btScalar mass,
btVector3 pos,
float restitutionIn,
float frictionIn,
int texId_capusleSide,//Ҳid
int texId_buttomBall,//ײԲid
int texId_topBall,//Բid
int texId_bottomCircle,//ײԲεid
int texId_topCircle,//Բεid
int texId_cylinderSide//Բid
)
{
int scale = 4;//ű
btVector3 halfExtents(1,0.125,1);//Բİ
halfExtents = halfExtents * scale;
float radio = 0.05f * scale;//ʾİ뾶
float height = 1.5f * scale;//ʾмԲĸ߶
btCollisionShape* top = new btCylinderShape(halfExtents);//Բ
btCollisionShape* pin = new btCapsuleShape(radio,height);//
top->setMargin(0.01);//ԲıԵֵ
pin->setMargin(0.01);//ýҵıԵֵ
btCompoundShape* compound = new btCompoundShape();//״
compound->addChildShape(btTransform::getIdentity(),top);//Բ״ӵ״
compound->addChildShape(btTransform::getIdentity(),pin);//״ӵ״
btVector3 localInertia;//
top->calculateLocalInertia(mass,localInertia);//
body = new btRigidBody(mass,0,compound,localInertia);//
btTransform tr;
tr.setIdentity();//任ʼ
tr.setOrigin(pos);//λ
body->setCenterOfMassTransform(tr);//ĵ
body->setAngularVelocity(btVector3(0,7,0));//ýٶ
body->setLinearVelocity(btVector3(0,0,0.2));//ٶ
body->setFriction(btSqrt(1));//Ħϵ
dynamicsWorld->addRigidBody(body);//ӵ
body->setDamping(0.00001f,0.0001f);//
tc = new TexCapsule(
radio,//뾶
height,//߶
texId_capusleSide,//Ҳid
texId_buttomBall,//ײԲid
texId_topBall,//Բid
30//зֵķ n
);//ƽҶ
tcs = new TexCylinderShape(
texId_bottomCircle,//ײԲεid
texId_topCircle,//Բεid
texId_cylinderSide,//Բid
30,//зַ
halfExtents//
);//ʼԲƽyᣬԲƽxozϵ//Բ
}
void MyCompoundShape::drawSelf()
{
MatrixState::pushMatrix();//ֳ
btTransform trans;
trans = body->getWorldTransform(); //ȡı任Ϣ
trans.getOpenGLMatrix(MatrixState::currMatrix); //ǰľø任Ϣ
if(body->isActive())//жϸǷɶ
{
tc->capuleSide->mFlagK = 0;//ý
tc->bottomBall->mFlagK = 0;//ý
tcs->bottomCircle->mFlagK = 0;//Բ
tcs->cylinderSide->mFlagK = 0;//Բ
}
else
{
tc->capuleSide->mFlagK = 1;//ý
tc->bottomBall->mFlagK = 1;//ý
tcs->bottomCircle->mFlagK = 1;//Բ
tcs->cylinderSide->mFlagK = 1;//Բ
}
tc->drawSelfNoBody();//ƽ
tcs->drawSelfNoBody();//Բ
MatrixState::popMatrix();//ֳָ
}
btRigidBody* MyCompoundShape::getBody()
{
return body;//ָ
}
| true |
a6648432d60b584c2c0b0a01733cd6a1287e5fa4 | C++ | gaolichen/contest | /homework/p279_3/p279_3.cpp | UTF-8 | 434 | 3.125 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
double f(double x,double y){
return x+y;
}
void runge_kutta(int n,double x,double y,double h,double (*f)(double,double)){
double k1,k2,k3,k4;
printf("y(%.1lf) = %.2lf\n",x,y);
if(n==0)return ;
k1=f(x,y);
k2=f(x+h*0.5,y+h*0.5*k1);
k3=f(x+h*0.5,y+h*0.5*k2);
k4=f(x+h,y+h*k3);
y+=h/6.0*(k1+2*k2+2*k2+k4);
runge_kutta(n-1,x+h,y,h,f);
}
int main(){
runge_kutta(20,0,-1.0,0.1,f);
return 0;
} | true |
1d250ee5673b6739d70176ea2bd187e199690f13 | C++ | francoisludewig/MecaSolid | /Tests/Solid/TestSolid.cpp | UTF-8 | 8,757 | 2.765625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <cmath>
#include <fstream>
#include "../Resource/DoublePrecision.h"
#include "Solid/Solid.h"
#include "Basis.h"
using namespace std;
using namespace Luga::Meca::Solid;
TEST(Solid,UpdatePositionTranslation){
Solid s;
Vector v(M_PI,M_PI/2,M_PI/4);
double dt = 0.0001;
s.Velocity(v);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateX() , M_PI *dt));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateY() , M_PI/2*dt));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateZ() , M_PI/4*dt));
}
TEST(Solid,UpdateVelocityTranslation){
Solid s;
Vector f(M_PI,M_PI/2,M_PI/4);
double mass = 10.;
double dt = 0.0001;
s.Force(f);
s.Mass(mass);
s.UpdateVelocities(dt);
ASSERT_TRUE(isEquals( s.Velocity().ComponantX() , M_PI *dt/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantY() , M_PI/2*dt/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantZ() , M_PI/4*dt/mass));
}
TEST(Solid,UpdateVelocityAndPositionTranslation){
Solid s;
Vector f(M_PI,M_PI/2,M_PI/4);
double mass = 10.;
double dt = 0.0001;
s.Force(f);
s.Mass(mass);
s.UpdateVelocities(dt);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.Velocity().ComponantX() , M_PI *dt/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantY() , M_PI/2*dt/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantZ() , M_PI/4*dt/mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateX() , M_PI *dt*dt/mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateY() , M_PI/2*dt*dt/mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateZ() , M_PI/4*dt*dt/mass));
}
TEST(Solid,UpdateVelocityAndPositionTranslationThetaMethod){
Solid s;
Vector f(M_PI,M_PI/2,M_PI/4);
double mass = 10.;
double dt = 0.0001;
double T = 0;
s.Force(f);
s.Mass(mass);
for(int i = 0 ; i < 10 ; i++){
T += dt;
s.UpdatePosition(dt/2.);
s.UpdateVelocities(dt);
s.UpdatePosition(dt/2.);
}
ASSERT_TRUE(isEquals( s.Velocity().ComponantX() , M_PI *T/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantY() , M_PI/2*T/mass));
ASSERT_TRUE(isEquals( s.Velocity().ComponantZ() , M_PI/4*T/mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateX(), M_PI *T*T/2./mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateY() , M_PI/2*T*T/2./mass));
ASSERT_TRUE(isEquals( s.B().Origin().CoordinateZ() , M_PI/4*T*T/2./mass));
}
TEST(Solid,UpdatePositionRotationX){
Solid s;
Vector w(M_PI/6,0.,0.);
double dt = 1;
s.AngularVelocity(w);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantX() , M_PI/6));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantReal() , cos(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantI() , sin(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantJ() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantK() , 0));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantX() , 1));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantY() ,cos(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantZ() ,sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantY() ,-sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantZ() , cos(M_PI/6)));
}
TEST(Solid,UpdatePositionRotationY){
Solid s;
Vector w(0 ,M_PI/6, 0);
double dt = 1;
s.AngularVelocity(w);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantY() , M_PI/6));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantReal() , cos(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantI() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantJ() , sin(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantK() , 0));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantX() , cos(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantZ() ,-sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantY() , 1));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantX() , sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantZ() , cos(M_PI/6)));
}
TEST(Solid,UpdatePositionRotationZ){
Solid s;
Vector w(0 , 0, M_PI/6);
double dt = 1;
s.AngularVelocity(w);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.AngularVelocity().ComponantZ() , M_PI/6));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantReal() , cos(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantI() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantJ() , 0));
ASSERT_TRUE(isEquals( s.B().Orientation().ComponantK() , sin(M_PI/12)));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantX() , cos(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantY() , sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantX() ,-sin(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantY() , cos(M_PI/6)));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantZ() ,1));
}
TEST(Solid,UpdatePositionRotationXYZ){
Solid s;
Vector w;
double dt = 1;
// Rotation X
w.SetComponants(M_PI,0,0);
s.AngularVelocity(w);
s.UpdatePosition(dt);
// Rotation Y
w.SetComponants(0,M_PI,0);
s.AngularVelocity(w);
s.UpdatePosition(dt);
// Rotation Z
w.SetComponants(0,0,M_PI);
s.AngularVelocity(w);
s.UpdatePosition(dt);
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantX() , 1));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisX().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantY() , 1));
ASSERT_TRUE(isEquals( s.B().AxisY().ComponantZ() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantX() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantY() , 0));
ASSERT_TRUE(isEquals( s.B().AxisZ().ComponantZ() , 1));
}
TEST(Solid,UpdateAngularVelocity){
Solid s;
Vector M(M_PI,-M_PI/2,M_PI/5);
Matrix I(M_PI,0,0,
0,M_PI,0,
0,0,M_PI);
double dt = 1;
s.Inertia(I);
s.Momentum(M);
s.UpdateVelocities(dt);
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantX(),M.ComponantX()*dt/M_PI));
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantY(),M.ComponantY()*dt/M_PI));
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantZ(),M.ComponantZ()*dt/M_PI));
}
TEST(Solid,IO_Operator){
Solid s,t;
Vector w,v;
// Rotation X
w.SetComponants(M_PI,-M_PI/2,M_PI/4);
s.AngularVelocity(w);
// Translation
v.SetComponants(-M_PI,-3*M_PI/2,7*M_PI/4);
s.Velocity(v);
s.UpdatePosition(1.);
ofstream fichierOut("testSolid.txt", ios::out | ios::trunc);
if(fichierOut){
fichierOut << s;
fichierOut.close();
}
ifstream fichierIn("testSolid.txt", ios::in);
if(fichierIn){
fichierIn >> t;
fichierIn.close();
}
ASSERT_TRUE(isEquals(s.B().Orientation().ComponantReal(),t.B().Orientation().ComponantReal()));
ASSERT_TRUE(isEquals(s.B().Orientation().ComponantI(),t.B().Orientation().ComponantI()));
ASSERT_TRUE(isEquals(s.B().Orientation().ComponantJ(),t.B().Orientation().ComponantJ()));
ASSERT_TRUE(isEquals(s.B().Orientation().ComponantK(),t.B().Orientation().ComponantK()));
ASSERT_TRUE(isEquals(s.B().Origin().CoordinateX(),t.B().Origin().CoordinateX()));
ASSERT_TRUE(isEquals(s.B().Origin().CoordinateY(),t.B().Origin().CoordinateY()));
ASSERT_TRUE(isEquals(s.B().Origin().CoordinateZ(),t.B().Origin().CoordinateZ()));
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantX(),t.AngularVelocity().ComponantX()));
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantY(),t.AngularVelocity().ComponantY()));
ASSERT_TRUE(isEquals(s.AngularVelocity().ComponantZ(),t.AngularVelocity().ComponantZ()));
ASSERT_TRUE(isEquals(s.Velocity().ComponantX(),t.Velocity().ComponantX()));
ASSERT_TRUE(isEquals(s.Velocity().ComponantY(),t.Velocity().ComponantY()));
ASSERT_TRUE(isEquals(s.Velocity().ComponantZ(),t.Velocity().ComponantZ()));
remove("testSolid.txt");
}
| true |
4c5f942f096745d258cd345097223914ecfabc95 | C++ | vasoov/arduino-dht11-ldr-lcd | /arduino-dht11-lcd2004-ldr.ino | UTF-8 | 1,722 | 2.890625 | 3 | [
"MIT"
] | permissive | //Read temperature, humidity and brighness sensors
#include <dht.h>
#include <LiquidCrystal_I2C.h>
//LCD display is defined as device number 0x27 on the I2C bus
LiquidCrystal_I2C lcd(0x27, 20, 4);
//DHT11 is connected to pin 8
dht DHT;
#define sensorPinDHT11 8
//Light sensor is connected to analog 0
#define sensorPinLDR 0
int sensorDataLDR = 0;
float brightness = 0;
//Raspberry Pi is connected to Serial 0
#define serialPi Serial
void setup() {
lcd.begin(20, 4); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display
lcd.init();
lcd.backlight();
serialPi.begin(9600); //Arduino to serial monitor
}
void loop() {
//Read DHT11 sensor data
int sensorData = DHT.read11(sensorPinDHT11);
float temperature = DHT.temperature;
float humidity = DHT.humidity;
sensorDataLDR = analogRead(sensorPinLDR);
brightness = ((float)sensorDataLDR / (float)1024) * 100.0;
//Print temperature
lcd.setCursor(0, 0);
lcd.print("Temperature ");
lcd.print(temperature);
lcd.print(" C");
//Print humidity
lcd.setCursor(0, 1);
lcd.print("Humidity ");
lcd.print(humidity);
lcd.print(" %");
//Print brightness level
lcd.setCursor(0, 2);
lcd.print("Brightness ");
lcd.setCursor(0, 2);
lcd.print("Brightness ");
lcd.print(brightness);
lcd.print(" %");
//Send temperature, humidity, brightness data to Raspberry Pi
serialPi.print("<");
serialPi.print(temperature);
serialPi.print(",");
serialPi.print(humidity);
serialPi.print(",");
serialPi.print(brightness);
serialPi.println(">");
//Wait for 10 seconds
delay(10000);
}
| true |
d8468a06006b4a39f35a1788655f7b06781a534d | C++ | houjing1/Example | /crazyflie_sim/src/motorDynamics.cpp | UTF-8 | 693 | 2.609375 | 3 | [] | no_license | /*
* motorDynamics.cpp
*
* Created On : 28/06/18
* Author : Jingyuan Hou
* Email : jingyuan.hou@mail.utoronto.ca
*/
#include "crazyflie_sim/motorDynamics.h"
// Static data memeber
Parameter MotorDynamics::param;
// Compute 4 motor output rpm from 4 motor ouput pwm
// Input: motor_pwm as 4 by 1 [motor1,motor2,motor3,motor4] vector
// Output: motor_rpm attribute
const Eigen::Vector4d& MotorDynamics::compute_motor_rpm(const Eigen::Vector4d& motor_pwm){
motor_rpm(0) = param.a1 * motor_pwm(0) + param.a2;
motor_rpm(1) = param.a1 * motor_pwm(1) + param.a2;
motor_rpm(2) = param.a1 * motor_pwm(2) + param.a2;
motor_rpm(3) = param.a1 * motor_pwm(3) + param.a2;
return motor_rpm;
}
| true |
94d862c0c4d21ae7f64bf309f6660e98ff6639b2 | C++ | KamikazeChan/Contest | /Regional 2014/2014 Beijing Online/HDU 5037 Frog.cpp | UTF-8 | 1,432 | 2.71875 | 3 | [] | no_license | /*
** HDU 5037 Frog
** Created by Rayn @@ 2014/09/22
*/
#include <cmath>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
inline int nextInt()
{
char ch = getchar();
bool flag = false;
while((ch < '0' || ch > '9') && ch != '-') ch = getchar();
if(ch == '-') {
flag = true;
ch = getchar();
}
int ret = 0;
while(ch >= '0' && ch <= '9') {
ret = ret * 10 + (ch - '0');
ch = getchar();
}
if(flag) ret = -ret;
return ret;
}
const int MAXN = 200005;
int rock[MAXN];
int main()
{
#ifdef _Rayn
freopen("in.txt", "r", stdin);
#endif
int T, cases = 0;
scanf("%d", &T);
while(T--)
{
int n, m, l;
scanf("%d%d%d", &n, &m, &l);
for(int i = 0; i < n; ++i) {
rock[i] = nextInt();
}
rock[n++] = 0;
rock[n++] = m;
sort(rock, rock + n);
int res = 0, pre = l;
for(int i = 1; i < n; ++i) {
int x = (rock[i] - rock[i-1]) % (l + 1);
int y = (rock[i] - rock[i-1]) / (l + 1);
if(pre + x >= l + 1) {
pre = x;
res += y * 2 + 1;
} else {
pre = pre + x;
res += y * 2;
}
}
printf("Case #%d: %d\n", ++cases, res);
}
return 0;
}
| true |
49266bf9d3c3c0906859e9d1b9859306c5d8a8a8 | C++ | thegamer1907/Code_Analysis | /Codes/AC/534.cpp | UTF-8 | 715 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
using namespace std;
bool perfect(int x) {
int t = 0;
while(x > 0) {
t += x % 10;
x /= 10;
}
return (10 == t) ? true : false;
}
int run()
{
int k = 0;
scanf("%d", &k);
int x = 1, cnt = 0;
while(cnt < k) {
if(perfect(x)) {cnt ++;}
if(cnt == k) break;
x ++;
}
printf("%d\n", x);
return 0;
}
int main(int argc, char * argv[])
{
run();
return 0;
}
| true |
a1e86356f8be23af5469ea43ddb69110d0c9fc2e | C++ | touhiduzzaman-tuhin/computer-graphics-C-Plus-Plus-projects-university-life | /blink1/main.cpp | UTF-8 | 1,501 | 2.71875 | 3 | [] | no_license |
#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdio.h>
#include <math.h>
float p = -10;
int state = 1;
bool direction=true;
int k;
void circle(GLfloat rx, GLfloat ry, GLfloat cx, GLfloat cy)
{
glBegin(GL_TRIANGLE_FAN);
glVertex2f(cx, cy);
for(int i = 0; i <= 101; i++)
{
float angle = 2.0f * 3.14156f * i/100;
float x = rx * cosf(angle);
float y = ry * sinf(angle);
glVertex2f((x + cx), (y + cy));
}
glEnd();
}
void init (void)
{
glClearColor (0, 0, 0, 0); // Background Color
glMatrixMode(GL_PROJECTION); /* initialize viewing values */
glLoadIdentity();
glOrtho(-10, 10, -10, 10, -10, 10); // To specify the coordinate & Specify the distances to the nearer and farther depth
}
void timer(int){
if(p <-8.10){
p += 0.00005;
}
else{
p = -10;
}
glutPostRedisplay();
glutTimerFunc(1000/60,timer,0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
k=p*p*p*p*p*p;
glColor3ub(1, (k*10)%255, 1);
circle(2, 2, p+2, -1);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); //Double Frame
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("map");
init ();
glutDisplayFunc(display);
glutTimerFunc(0,timer,0);
glutMainLoop();
return 0; /* ISO C requires main to return int. */
}
| true |
cefd84dd6f00e9896430aebaee112ef6b5982dd1 | C++ | Blawker/Kassiopeia | /KEMField/Source/Math/Array/include/KFMPointwiseArrayMultiplier.hh | UTF-8 | 1,885 | 2.75 | 3 | [] | no_license | #ifndef KFMPointwiseArrayMultiplier_H__
#define KFMPointwiseArrayMultiplier_H__
#include "KFMBinaryArrayOperator.hh"
namespace KEMField
{
/**
*
*@file KFMPointwiseArrayMultiplier.hh
*@class KFMPointwiseArrayMultiplier
*@brief
*@details
*
*<b>Revision History:<b>
*Date Name Brief Description
*Fri Sep 28 15:39:37 EDT 2012 J. Barrett (barrettj@mit.edu) First Version
*
*/
template<typename ArrayType, unsigned int NDIM>
class KFMPointwiseArrayMultiplier : public KFMBinaryArrayOperator<ArrayType, NDIM>
{
public:
KFMPointwiseArrayMultiplier(){};
~KFMPointwiseArrayMultiplier() override{};
void Initialize() override
{
;
};
void ExecuteOperation() override
{
if (IsInputOutputValid()) {
ArrayType* in1ptr = this->fFirstInput->GetData();
ArrayType* in2ptr = this->fSecondInput->GetData();
ArrayType* outptr = this->fOutput->GetData();
unsigned int n_elem = this->fFirstInput->GetArraySize();
for (unsigned int i = 0; i < n_elem; i++) {
outptr[i] = (in1ptr[i]) * (in2ptr[i]);
}
}
}
private:
virtual bool IsInputOutputValid() const
{
if (this->fFirstInput && this->fSecondInput && this->fOutput) {
//check they have the same size/num elements
if (this->HaveSameNumberOfElements(this->fFirstInput, this->fOutput) &&
this->HaveSameNumberOfElements(this->fSecondInput, this->fOutput)) {
//check they have the same dimensions/shape
if (this->HaveSameDimensions(this->fFirstInput, this->fOutput) &&
this->HaveSameDimensions(this->fSecondInput, this->fOutput)) {
return true;
}
}
}
return false;
}
};
} // namespace KEMField
#endif /* __KFMPointwiseArrayMultiplier_H__ */
| true |
bde20444f3468b0aa790ce667333384a6dfb66b1 | C++ | heyzwming/HumanHungry | /HumanHungry/myskill/src/Shoot.cpp | UTF-8 | 10,216 | 2.953125 | 3 | [] | no_license | /********************************************************************
* *
* 射门函数函数名: Shoot *
* 实现功能: 射门,朝向位置是按照场上球门的位置做相应的逻辑获得的 *
* *
* *
* 返回参数 无 *
* *
********************************************************************/
#include "Shoot.h"
#include "GetBall.h"
// 追逐球
// 调用GetBall的相关函数来 拿到球
// TODO: 不理解为什么do_chase_ball 要朝向球门接球?
PlayerTask do_chase_ball(const WorldModel* model,int runner_id){
// get_ball_plan 朝向某个角色拿球
// 第一个参数 runner_id : 函数执行者 / 接球 球员
// 第二个参数 receiver_id : 传球 球员
// 当 两个参数相同 朝向球门接球
return get_ball_plan(model, runner_id, runner_id);
}
/*
获得球员位置和朝向,球的位置,
打开吸球开关,
判断球是否被球员控制住,如果控制住则直接射门。
控球的判断方法:小球到车的距离是否小于某个值;车到球的矢量角度是否和车头的矢量角度之差的绝对值是否小于某个值
*/
// 球员停止运动 如果小球在球员脚上,球员已经控到了球,则执行射门
PlayerTask do_wait_touch(const WorldModel* model, int runner_id){
PlayerTask task;
const point2f& pos = model->get_our_player_pos(runner_id);
//const point2f& get_our_player_pos(int id)const;
const point2f& ball = model->get_ball_pos();
const float& player_dir = model->get_our_player_dir(runner_id);
// 设置task中的吸球开关为true,小车吸球
task.needCb = true;
// 判断球是否在小车车头吸球嘴上
// 二个判断条件:小球到车的距离是否小于某个值;车到球的矢量角度是否和车头的矢量角度之差的绝对值是否小于某个值
if ((ball - pos).length() < BALL_SIZE / 2 + MAX_ROBOT_SIZE + 5 && (anglemod(player_dir - (ball - pos).angle()) < PI / 6)){
// 设置task中的踢球参数:
// kickPower 踢球力量
// needKick 平踢球开关
// isChipKick 挑球开关
task.kickPower = 127;
task.needKick = true;
task.isChipKick = false;
}
return task;
}
/*
获得球员位置 和 朝向,
获得球的位置 和 球员到球的向量的角度,
判断球员有没有控到球,如果没有则让球员朝向球
*/
PlayerTask do_stop_ball_and_shoot(const WorldModel* model, int runner_id){
PlayerTask task;
const point2f& pos = model->get_our_player_pos(runner_id);
const point2f& ball = model->get_ball_pos();
const float& dir = model->get_our_player_dir(runner_id);
const float& dir_ball = (fabs(anglemod(dir - (ball - pos).angle())));
// 判断球是否被球员控制(是否在吸球嘴上),球员的朝向角度 - 球员位置指向球位置的向量角度
// TODO: 控球的判断方法:球员是否面向着球(角度差)
bool player_oriente_ball = (fabs(anglemod(dir - (ball - pos).angle()))) < PI / 6;
//如果球没有被球员控住,则让球员朝向球的方向
if (!player_oriente_ball){
task.target_pos = pos;
task.orientate = (ball - pos).angle();
}
//如果球在车头吸球嘴上,needCb吸球开关吸球
else{
task.needCb = true;
}
return task;
}
// 拿球
PlayerTask do_turn_and_shoot(const WorldModel* model, int runner_id){
PlayerTask task;
const point2f& pos = model->get_our_player_pos(runner_id);
const point2f& ball = model->get_ball_pos();
//TODO: 重载运算符“-”号的作用
const point2f& opp = -FieldPoint::Goal_Center_Point;
// 如果球到球员的距离小于15 则前去接球
if ((ball - pos).length() < 15){
// 该方法实现的是 将极坐标转为二维向量,
// 传入参数 : 极坐标的长度与角度
// 返回值 : 二维向量的x和y
task.target_pos = ball + Maths::polar2vector(15,(pos- ball).angle());
task.orientate = (ball - pos).angle();
}
// 否则 调用 GetBall类的相关方法去拿球
else
{
//GetBall get_ball;
task = get_ball_plan(model, runner_id, runner_id);
}
/*else
{
task.target_pos = ball + Maths::polar2vector(11,(ball - opp).angle());
task.orientate = (opp - ball).angle();
}*/
return task;
}
//调整车位置方向,到 对方球门指向球的向量的 方向位置
PlayerTask do_adjust_dir(const WorldModel* model, int runner_id){
PlayerTask task;
const point2f& ball = model->get_ball_pos();
// opp_goal : 对方球门的二维坐标
const point2f& opp_goal = -FieldPoint::Goal_Center_Point;
const point2f& player = model->get_our_player_pos(runner_id);
// TODO: back2ball_p 为目标 位置 赋值号右边的意思?
const point2f& back2ball_p = ball + Maths::polar2vector(20, (ball - opp_goal).angle());
task.target_pos = back2ball_p;
task.orientate = (opp_goal - ball).angle();
return task;
}
//射门
PlayerTask do_shoot(const WorldModel* model, int runner_id){
PlayerTask task;
// opp_goal 对方球门中心
const point2f& opp_goal = -FieldPoint::Goal_Center_Point;
const point2f& ball = model->get_ball_pos();
const point2f& player = model->get_our_player_pos(runner_id);
const float& dir = model->get_our_player_dir(runner_id);
// 布尔类型变量 get_ball 拿到球
// 球到球员的距离小于 拿到球的阈值(宏定义16)-2.5 && 球员角度与球角度差 的绝对值 小于一定的值 为1
bool get_ball = (ball - player).length() < get_ball_threshold - 2.5 && (fabs(anglemod(dir - (ball - player).angle())) < PI / 6);
// 如果拿到球了 准备射门
if (get_ball){
task.kickPower = 127;
task.needKick = true;
task.isChipKick = false;
}
// 对方球门 到 球的向量 的角度
float opp_goal_to_ball = (ball - opp_goal).angle();
// TODO:fast_shoot 的意义
task.target_pos = ball + Maths::polar2vector(fast_shoot, opp_goal_to_ball);
task.orientate = (opp_goal - ball).angle();
task.flag = 1;
return task;
}
/*
对射门前的一些状态进行判断,并决定是否射门
*/
PlayerTask player_plan(const WorldModel* model, int robot_id){
cout << "int shoot skill" << endl;
PlayerTask task;
bool ball_moving_to_head;
//射门需要用到的参数
const point2f& kicker_pos = model->get_our_player_pos(robot_id); // 球员位置
const point2f& ball_pos = model->get_ball_pos(); // 球的位置
const point2f& last_ball_pos = model->get_ball_pos(1); // 获得上一帧球的位置
const float kicker_dir = model->get_our_player_dir(robot_id); // 球员角度
const point2f& opp = -FieldPoint::Goal_Center_Point; // 对方球门
//对方球门位置与射门球员位置矢量方向角 与 射门球员朝向角之差
float kick2opp_kickdir_angle = anglemod((opp - kicker_pos).angle() - kicker_dir);
//球与射门球员位置矢量方向角 与 射门球员朝向角之差
float kick2ball_kickdir_angle = anglemod((ball_pos - kicker_pos).angle() - kicker_dir);
// 对方球门与射门球员位置矢量方向角 与 射门球员朝向角向角之差 的绝对值 小于某个值时为true,
// 即判断射门球员是否朝向着对方球门
bool toward_oppgoal = fabs(kick2opp_kickdir_angle) < PI / 4;
// 球与射门球员位置矢量方向角 与 射门球员朝向角之差 的绝对值 小于某个值时为true,即判断球是否在射门球员前方
bool ball_front_head = fabs(kick2ball_kickdir_angle) < PI / 3;
// 球当前帧位置和上一帧位置差,即球位移量
point2f vector_s = ball_pos - last_ball_pos;
// 球员右侧位置
point2f head_right = kicker_pos + Maths::polar2vector(Center_To_Mouth,anglemod(kicker_dir + PI/6));
// 球员左侧位置
point2f head_left = kicker_pos + Maths::polar2vector(Center_To_Mouth, anglemod(kicker_dir - PI / 6));
//车头中间位置
point2f head_middle = kicker_pos + Maths::polar2vector(7, kicker_dir);
//车头右侧位置到球位移矢量
point2f vector_a = head_right - ball_pos ;
//车头左侧位置到球位移矢量
point2f vector_b = head_left - ball_pos;
//车头中间位置到球位移矢量
point2f vector_c = head_middle - ball_pos;
bool wait_touch, stop_ball;
bool wait_touch_condition_a, wait_touch_condition_b;
// 如果 球与上一帧的位移差 小于 Vision_ERROR(2)
if (vector_s.length() < Vision_ERROR){
//判断球是否朝球员头移动
ball_moving_to_head = false;
}
else
{
//求 球员头中间位置到球位移矢量 vector_c 和 球与上一帧的位移量 vector_s之间的夹角
float angle_sc = acos(dot(vector_c, vector_s) / (vector_c.length() *vector_s.length()));
//判断球是否朝球员头移动
ball_moving_to_head = angle_sc < PI/6 && angle_sc > -PI/6;
}
//射门条件a:球是否在射门车车头方向,并且车头朝向对方球门
wait_touch_condition_a = ball_front_head && toward_oppgoal;
//射门条件b:满足条件a的同时是否满足球在车头方向并朝车头运动
wait_touch_condition_b = ball_moving_to_head && wait_touch_condition_a;
//停球判断布尔变量
stop_ball = (ball_front_head &&ball_moving_to_head&&!toward_oppgoal);
//等球判断布尔变量
wait_touch = wait_touch_condition_b;
//ShootMethods枚举变量
ShootMethods method;
if (wait_touch)//等球判断,WaitTouch方法
method = WaitTouch;
else if (stop_ball)//停球判断, StopBall方法
method = StopBall;
else if (!toward_oppgoal)//没有朝向对方球门判断,AdjustDir方法
method = AdjustDir;
else if ((ball_pos - kicker_pos).length() < get_ball_threshold+5 && (anglemod(kicker_dir - (ball_pos - kicker_pos).angle()) < PI / 6))//判断球在车头吸球嘴位置,ShootBall方法
method = ShootBall;
else
method = ChaseBall;//拿球方法
// 由当前的模式枚举method 执行相应的方法
switch (method)
{
case None:
break;
case ChaseBall:
task = do_chase_ball(model, robot_id);
break;
case WaitTouch:
task = do_wait_touch(model, robot_id);
break;
case StopBall:
task = do_stop_ball_and_shoot(model, robot_id);
break;
case AdjustDir:
task = do_adjust_dir(model, robot_id);
break;
case ShootBall:
task = do_shoot(model, robot_id);
break;
default:
break;
}
cout << "out shoot skill" << endl;
return task;
} | true |
4e6051eba814fe6cef67fbe0543ba2bf8144be20 | C++ | sturdevant/736_p2 | /nodes/Cluster.h | UTF-8 | 913 | 2.609375 | 3 | [] | no_license |
#ifndef _CLUSTER_H_
#define _CLUSTER_H_
#include <string.h>
#include <float.h>
#include <vector>
#include "Point.h"
#include <iostream>
#define N_DIMENSION 2
class Point;
class Cluster {
public:
Cluster(Point* pt, unsigned long id);
Cluster(unsigned long id);
~Cluster();
void addPt(Point* pt);
void printCheckPoints();
int removePt(Point* pt);
unsigned long getId() { return id; }
unsigned long getPtCount() { return ptCount; }
double getSqrDistToCheckPoint(Point* pt, int* retIndex);
void addCheckPoint(Point* pt);
void moveCheckPoint(int index, Point* newPt);
void moveCheckPoint(Point* oldPt, Point* newPt);
void removeCheckPoint(int index);
void removeCheckPoint(Point* pt);
std::vector<Point*>* getCheckPoints() { return &checkPoints; }
private:
unsigned long ptCount;
unsigned long id;
std::vector<Point*> checkPoints;
};
#endif // _CLUSTER_H_
| true |
e0d9ef25eb499ee15ed1e32ec1dc7ed430431959 | C++ | CS231/c-primer-plus | /chcount.cpp | UTF-8 | 258 | 3.1875 | 3 | [] | no_license | #include<stdio.h>
#define PERIOD '.'
int main(void)
{
int ch;
int charcount = 0;
while((ch = getchar()) != PERIOD)
{
if(ch != '\"' && ch != '\'')
charcount++;
}
printf("There are %d non-quote characters.\n", charcount);
return 0;
}
| true |
3769cdd8532b4d266fa771fecfab312f3fc338a1 | C++ | ldionne/sandbox | /static_optional.hpp | UTF-8 | 2,952 | 2.890625 | 3 | [] | no_license | /*!
* @file
* This file defines `dyno::detail::static_optional`.
*/
#ifndef DYNO_DETAIL_STATIC_OPTIONAL_HPP
#define DYNO_DETAIL_STATIC_OPTIONAL_HPP
#include <boost/operators.hpp>
#include <boost/spirit/include/classic_safe_bool.hpp>
#include <boost/type_traits/remove_reference.hpp>
namespace dyno {
namespace detail {
namespace static_optional_detail {
template <typename Derived, typename T, bool IsValid>
class static_optional_base
: public boost::spirit::classic::safe_bool<
static_optional_base<Derived, T, IsValid>
>,
public boost::totally_ordered<static_optional_base<Derived, T, IsValid> >
{
protected:
typedef typename boost::remove_reference<T>::type value_type;
typedef value_type* pointer;
typedef value_type const* const_pointer;
typedef value_type& reference;
typedef value_type const& const_reference;
bool operator_bool() const { return IsValid; }
public:
// get (references)
const_reference operator*() const;
reference operator*();
const_reference get() const { return **this; }
reference get() { return **this; }
friend const_reference get(Derived const& self) { return *self; }
friend reference get(Derived& self) { return *self; }
// get_value_or, get_optional_value_or
const_reference get_value_or(const_reference def) const;
reference get_value_or(reference def);
friend reference
get_optional_value_or(Derived& self, reference def)
{ return self.get_value_or(def); }
friend const_reference
get_optional_value_or(Derived const& self, const_reference def)
{ return self.get_value_or(def); }
// get (pointers)
const_pointer get_ptr() const;
pointer get_ptr();
friend const_pointer get(Derived const* self) { return self->get_ptr(); }
friend pointer get(Derived* self) { return self->get_ptr(); }
friend const_pointer
get_pointer(Derived const* self) { return self->get_ptr(); }
friend pointer get_pointer(Derived* self) { return self->get_ptr(); }
// comparison operators
bool operator!() const { return !static_cast<bool>(*this); }
friend bool operator==(self_type const& x, self_type const& y) {
return x && y ? *x == *y : !(x || y);
}
friend bool operator<(self_type const& x, self_type const& y) {
return y && (!x || *x < *y);
}
// misc
const_pointer operator->() const;
pointer operator->();
friend void swap(self_type& x, self_type& t);
};
// [new in 1.34]
template<class T> inline optional<T> make_optional ( T const& v ) ;
// [new in 1.34]
template<class T> inline optional<T> make_optional ( bool condition, T const& v ) ;
} // end namespace static_optional_detail
/*!
*
*/
template <typename T>
} // end namespace detail
} // end namespace dyno
#endif // !DYNO_DETAIL_STATIC_OPTIONAL_HPP
| true |
6f65eb723e27a3b1a3e4e1b7f8e9d5ad1826f2ff | C++ | nischay123/cplusplusprograms | /recursion/mersort.cpp | UTF-8 | 916 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void merge(int a[] ,int s,int mid ,int e){
int n1 = mid-s +1;
int n2 = e-mid;
int n =e-s+1;
int temp[n];
int i=s;
int j=mid+1 ;
int k=0;
while(i<=mid && j<=e){
if(a[i]<a[j]){
temp[k] = a[i];
i++;
k++;
}
else if(a[i]>=a[j]){
temp[k] = a[j];
j++;
k++;
}
}
while(i<=mid){
temp[k] = a[i];
i++;
k++;
}
while(j<=e){
temp[k] = a[j];
j++;
k++;
}
k=0;
for(int i=s ;i<=e;i++){
a[i] = temp[k];
k++;
}
}
void mergeSort(int a[] ,int start,int end){
if(start>=end){
return ;
}else{
int mid = (start+end)/2;
mergeSort(a, start , mid);
mergeSort(a, mid+1, end);
merge(a , start ,mid ,end);
}
}
int main()
{
int array[] = {7,4,6,9,2,53,7,8,3,1,34};
int n = sizeof(array)/sizeof(int);
mergeSort(array ,0,n-1);
for(int i=0;i<n;i++){
cout<<" "<<array[i];
}
/* code */
return 0;
} | true |
fd66fd1a3ebfb965a8f8500faf636174ef4f84b9 | C++ | rowensimpson/5th_Group_Project | /Serial.ino.ino | UTF-8 | 465 | 2.953125 | 3 | [] | no_license | // arduino serial feeder code
int data[500];
int bob = 0;
void setup() {
Serial.begin(9600); // setup serial
}
void loop() {
// set up the time range
for(int n = 0; n <= 499; n++)
data[n] = n;
// passing the data through
for(int i = 0; i <= (sizeof(data)/sizeof(int))-1; i++)
{
if(data[i]%5 == 0){bob++;}
Serial.print(data[i]);
Serial.print(',');
Serial.println(bob);
delay(250);
}
}
| true |
7a7516650311b2817ac0d459c9ff7b5761328d04 | C++ | Childcity/MultithreadedUdpReceiver | /Common/Protocol/Message.cpp | UTF-8 | 1,603 | 2.6875 | 3 | [
"MIT"
] | permissive | //
// Created by childcity on 14.09.20.
//
#include "Message.h"
#include "packing.h"
#include "../Utils.hpp"
void Message::Pack(Message &inMsg, unsigned char *outBuff)
{
inMsg.MessageSize = sizeof(Message);
packi16(outBuff, (uint16_t)inMsg.MessageSize);
*(outBuff + 2) = (uint8_t)inMsg.MessageType;
packi64(outBuff + 2 + 1, (uint64_t)inMsg.MessageId);
packi64(outBuff + 2 + 1 + 8, (uint64_t)inMsg.MessageData);
//unsigned messageSize = pack(outBuff, "HCQQ",
// (uint16_t)inMsg.MessageSize,
// (uint8_t)inMsg.MessageType,
// (uint64_t)inMsg.MessageId,
// (uint64_t)inMsg.MessageData);
// put size of massage to its position
//packi16(outBuff, messageSize);
//inMsg.MessageSize = static_cast<uint16_t>(messageSize);
}
void Message::UnPack(unsigned char *inBuff, Message &outMsg)
{
outMsg.MessageSize = (uint16_t)unpacku16(inBuff);
outMsg.MessageType = (uint8_t) * (inBuff + 2);
outMsg.MessageId = (uint64_t)unpacku64(inBuff + 2 + 1);
outMsg.MessageData = (uint64_t)unpacku64(inBuff + 2 + 1 + 8);
//unpack(inBuff, "HCQQ", &outMsg.MessageSize,
// &outMsg.MessageType,
// &outMsg.MessageId,
// &outMsg.MessageData);
}
void Message::dump() const
{
DEBUG("Message:\n"
<< "\tMessageSize:\t" << MessageSize << "\n"
<< "\tMessageType:\t" << (int)MessageType << "\n"
<< "\tMessageId: \t" << MessageId << "\n"
<< "\tMessageData:\t" << MessageData);
}
| true |
f980b79875ef004f217f1c42cc188ba53017dd1a | C++ | MrJiu/eBox_Framework | /example/5.uart/5.command_frame.cpp | GB18030 | 2,486 | 2.625 | 3 | [
"MIT"
] | permissive | /**
******************************************************************************
* @file main.cpp
* @author shentq
* @version V1.2
* @date 2016/08/14
* @brief ebox application example .
******************************************************************************
* @attention
*
* No part of this software may be used for any commercial activities by any form
* or means, without the prior written consent of shentq. This specification is
* preliminary and is subject to change at any time without notice. shentq assumes
* no responsibility for any errors contained herein.
* <h2><center>© Copyright 2015 shentq. All Rights Reserved.</center></h2>
******************************************************************************
*/
/**
* 1 һ֡ʾʹ֡ͨѶ
* 2 $֡ͷ߳Ҫʼ
* 3 ֡β߳ݷ
* 4 ɺӡܵݣ´ν
*/
#include "ebox.h"
#include "bsp_ebox.h"
/* ̷ */
#define EXAMPLE_NAME "command frame example"
#define EXAMPLE_DATE "2018-08-06"
#define HEAD '$'
#define END '!'
#define NEEDHEAD 0
#define NEEDDATA 1
#define DATAEND 2
uint8_t state = NEEDHEAD;
char rcv[100]; // ܵݣ100
int i;
void test()
{
LED1.toggle();
uint8_t c;
c = UART.read();
switch(state)
{
case NEEDHEAD:
if(c == HEAD)
{
i = 0;
rcv[i++] = c;
state = NEEDDATA;
//UART.printf("ݣɺ β\r\n"); // ˾ص֮ԭ
}
break;
case NEEDDATA:
if(c == END)
{
rcv[i] = c;
state = DATAEND;
}
else
{
rcv[i++] = c;
}
break;
}
}
void setup()
{
ebox_init();
UART.begin(115200);
print_log(EXAMPLE_NAME,EXAMPLE_DATE);
UART.attach(test,RxIrq);
UART.interrupt(RxIrq,ENABLE);
}
float x, y;
int main(void)
{
setup();
UART.printf("֡ͷ $ \r\n");
while(1)
{
if(state == DATAEND)
{
UART.printf(rcv);
for(int i = 0; i < 100; i ++)
rcv[i] = 0;
state = NEEDHEAD;
}
}
}
| true |
8689135b95b9dc039487fbfb4cb6f7fb2556085e | C++ | NaioTechnologies/MMeteo | /src/DHT.cpp | UTF-8 | 5,618 | 2.890625 | 3 | [] | no_license | /* DHT library
MIT license
written by Adafruit Industries
*/
#include "DHT.h"
#include "Logger.h"
#include "Types.h"
DHT::DHT(uint8_t pin, uint8_t type, uint8_t count)
{
_pin = pin;
_type = type;
_count = count;
firstreading = true;
oldhum = 666;
oldtemp = 666;
}
void DHT::begin(void)
{
// set up the pins!
pinMode(_pin, INPUT);
digitalWrite(_pin, HIGH);
_lastreadtime = 0;
}
//boolean S == Scale. True == Farenheit; False == Celcius
float DHT::readTemperature(bool S)
{
float f;
Logger::logLnF("->DHT::readTemperature");
for(int i = 0 ; i < MAX_SENSOR_READ_TRIES ; i++ )
{
if ( read() )
{
switch (_type)
{
case DHT11:
f = data[2];
if(S)
{
f = convertCtoF(f);
}
//oldtemp = f;
//return f;
case DHT22:
case DHT21:
f = data[2] & 0x7F;
f *= 256;
f += data[3];
f /= 10;
if (data[2] & 0x80)
{
f *= -1;
}
if(S)
{
f = convertCtoF(f);
}
//oldtemp = f;
//return f;
}
}
if( ( f > -30 ) && ( f <= 80 ) )
{
oldtemp = f;
return f;
}
}
Logger::logLnF("DHT::readTemperature fail");
oldtemp = 666;
return oldtemp;
}
float DHT::convertCtoF(float c)
{
return c * 9 / 5 + 32;
}
float DHT::readHumidity(void)
{
float lastHumidityMeasure[DHT_HUMIDITY_AVERAGE_MEASURES];
float medianHumidityMeasure[DHT_HUMIDITY_AVERAGE_MEASURES];
float filteredHumidityMeasure[DHT_HUMIDITY_AVERAGE_MEASURES];
float measure = 0;
ubyte measureCount = 0;
ubyte filteredCount = 0;
ubyte floatFilteredCount = 0;
Logger::logLnF("->DHT::readHumidity");
for( ubyte i = 0; i < DHT_HUMIDITY_AVERAGE_MEASURES ; i++ )
{
lastHumidityMeasure[i] = 666;
}
for( ubyte i = 0; i < DHT_HUMIDITY_AVERAGE_MEASURES ; i++ )
{
lastHumidityMeasure[i] = directReadHumidity();
}
for( ubyte i = 0; i < DHT_HUMIDITY_AVERAGE_MEASURES ; i++ )
{
if( lastHumidityMeasure[i] != 666 )
{
medianHumidityMeasure[measureCount] = lastHumidityMeasure[i];
measureCount++;
}
}
//Bubble sorting
for( int x = 0 ; x < measureCount ; x++)
{
for( int y = 0 ; y < measureCount-1; y++ )
{
if( medianHumidityMeasure[y] > medianHumidityMeasure[y+1] )
{
float temp = medianHumidityMeasure[y+1];
medianHumidityMeasure[y+1] = medianHumidityMeasure[y];
medianHumidityMeasure[y] = temp;
}
}
}
float median = medianHumidityMeasure[ measureCount / 2 ];
// filter far from median value
for( ubyte i = 0; i < measureCount ; i++ )
{
if( ( medianHumidityMeasure[i] > median - DHT_HUMIDITY_MEDIAN_MARGIN ) && ( medianHumidityMeasure[i] < median + DHT_HUMIDITY_MEDIAN_MARGIN ) )
{
filteredHumidityMeasure[filteredCount] = medianHumidityMeasure[i];
filteredCount++;
floatFilteredCount = floatFilteredCount + 1;
}
}
// compute average value of filterer values.
for( ubyte i = 0; i < filteredCount ; i++ )
{
measure = measure + filteredHumidityMeasure[filteredCount];
}
if( filteredCount != 0 )
{
measure = measure / floatFilteredCount;
}
else
{
measure = 666;
}
return measure;
}
float DHT::directReadHumidity(void)
{
float f;
for(int i = 0 ; i < MAX_SENSOR_READ_TRIES ; i++ )
{
if (read())
{
switch (_type)
{
case DHT11:
f = data[0];
//oldhum = f;
//return f;
case DHT22:
case DHT21:
f = data[0];
f *= 256;
f += data[1];
f /= 10;
//oldhum = f;
//return f;
}
}
if( ( f > 0 ) && ( f <= 100 ) )
{
oldhum = f;
return f;
}
}
Logger::logLnF("DHT::readHumidity fail");
oldhum = 666;
return oldhum;
}
boolean DHT::read(void)
{
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
unsigned long currenttime;
// pull the pin high and wait 250 milliseconds
digitalWrite(_pin, HIGH);
delay(250);
currenttime = millis();
if (currenttime < _lastreadtime)
{
// ie there was a rollover
_lastreadtime = 0;
}
if (!firstreading && ((currenttime - _lastreadtime) < 2000))
{
return true; // return last correct measurement
//delay(2000 - (currenttime - _lastreadtime));
}
firstreading = false;
/*
Serial.print("Currtime: "); Serial.print(currenttime);
Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
*/
_lastreadtime = millis();
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
// now pull it low for ~20 milliseconds
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delay(20);
cli();
digitalWrite(_pin, HIGH);
delayMicroseconds(40);
pinMode(_pin, INPUT);
// read in timings
for ( i=0; i< MAXTIMINGS; i++)
{
counter = 0;
while (digitalRead(_pin) == laststate)
{
counter++;
delayMicroseconds(1);
if (counter == 255)
{
break;
}
}
laststate = digitalRead(_pin);
if (counter == 255) break;
// ignore first 3 transitions
if ( ( i >= 4 ) && ( i % 2 == 0) )
{
// shove each bit into the storage bytes
data[j/8] <<= 1;
if (counter > _count)
{
data[j/8] |= 1;
}
j++;
}
}
sei();
/*
Serial.println(j, DEC);
Serial.print(data[0], HEX); Serial.print(", ");
Serial.print(data[1], HEX); Serial.print(", ");
Serial.print(data[2], HEX); Serial.print(", ");
Serial.print(data[3], HEX); Serial.print(", ");
Serial.print(data[4], HEX); Serial.print(" =? ");
Serial.println(data[0] + data[1] + data[2] + data[3], HEX);
*/
// check we read 40 bits and that the checksum matches
if ( (j >= 40) && (data[4] == ( (data[0] + data[1] + data[2] + data[3]) & 0xFF) ) )
{
return true;
}
return false;
}
| true |
c9291f7cfd97e9860ceb48ac3cfe69f292f47f7a | C++ | nibalizer/cs162 | /program3.cpp | UTF-8 | 1,863 | 3.21875 | 3 | [] | no_license | // Spencer Krum
// CS162
// Karla Fant
// Program 3
// DBAD License
// Oct 23, 2010
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "file.cpp"
#include "index.cpp"
#include "program3.h"
using namespace std;
int main () {
intro();
/* file file1;
file file2;
file1.readfile();
file1.displayfile();
char namez[20];
cin.get(namez, 20, '\n');
cin.ignore(20, '\n');
int t;
t = file2.comparefilename(namez);
cout << t << endl;
*/
index awesome_index;
userinterface(awesome_index);
return 0;
}
void userinterface(index& awesome_index){
int selection = -1;
//while(true){
cout << "Please pick one of the 4 options below" << endl;
cout << "1 - Print out whole database" << endl;
cout << "2 - Add a file to database" << endl;
cout << "3 - Search database by filename" << endl;
cout << "4 - Quit" << endl;
cin >> selection;
switch (selection) {
case 1: {
awesome_index.display();
break;
}
case 2: {
file awesome_new_file;
awesome_new_file.readfile();
awesome_index.extend(awesome_new_file);
break;
}
case 3: {
searchdb(awesome_index);
break;
}
case 4:
exit (0);
break;
default :
cout << "Please enter 1, 2, 3, or 4." << endl;
// }
}
}
void searchdb(index& awesome_index){
char filename[20];
cout << "File name: " << endl;
cin.get(filename, 20, '\n');
cin.ignore(20, '\n');
awesome_index.find(filename);
}
void intro(){
cout << "CS 162 Program 3" << endl;
cout << "File Indexing program." << endl;
}
| true |
46fcf33f2c39e0db6e8c14230d41bb27129f5a89 | C++ | AlexeiVazquez/Funciones | /Introduccion/suma.cpp | UTF-8 | 304 | 3.4375 | 3 | [] | no_license | #include <iostream>
void suma(int,int);
using namespace std;
int main(){
int a,b;
cout<<"Introduce el valor 1:";
cin>>a;
cout<<"Introduce el valor 2:";
cin>>b;
suma(a,b);
return 0;
}
void suma(int a,int b){
int c=a+b;
cout<<"El resultado de "<<a<<"+"<<b<<" es:"<<c<<endl;
}
| true |
f266a0533b39b54ad4204cb3bbbe307fd9d56c58 | C++ | Bab95/Programs | /LeetCode/Problems/769.Maximum_Chunks_to_Make_Sorted.cpp | UTF-8 | 854 | 2.65625 | 3 | [] | no_license | class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int n = arr.size();
vector<int> group(n,-1);
for(int i=0;i<n;++i){
//find min val from right for this..
int val;
if(group[i]!=-1){
val = group[i];
}else{
val = arr[i];
}
//group[i] = val;
int start = i;
int finish;
for(int j=n-1;j>=i;j--){
if(arr[j]<=arr[i]){
finish = j;
break;
}
}
for(int k=start;k<=finish;k++){
group[k] = val;
}
}
set<int> chunks;
for(int i=0;i<group.size();++i){
chunks.insert(group[i]);
}
return chunks.size();
}
};
| true |
2c85db76f492c31771ae0ccc6abee206a6a9780e | C++ | KFlaga/FlagRTS | /GameCore/UnitWeaponSet.h | UTF-8 | 1,995 | 2.875 | 3 | [] | no_license |
#pragma once
#include <Array.h>
#include "DataTypes.h"
namespace FlagRTS
{
class Unit;
class Weapon;
class WeaponDefinition;
class CommandTarget;
// Set of weapons that unit can use
// Except storing them also determines which weapons to use against target
// Stores and switches active weapon -> attack state/command can read it
// and use it
// If unit have multiple weapons for the target it may use only one
// If unit should use more than one weapon it should have it 'turreted', so
// basicaly weapon will fire independly of unit ( ofc attack command will try to focus
// all weapons on same target )
class UnitWeaponSet
{
private:
Unit* _owner;
Array<Weapon*> _weapons;
Weapon* _currentWeapon;
public:
UnitWeaponSet();
UnitWeaponSet(Unit* owner, const Array<std::pair<WeaponDefinition*, bool>>& weaponList);
~UnitWeaponSet();
std::pair<Weapon*, float> GetWeaponWithMaxRangeAgainstTarget(Unit* target);
// Refreshes weapon cooldowns
void Update(float ms);
// Returns all unit's weapons
const Array<Weapon*>& GetWeapons() const;
// Returns weapon with given name ( == def name ) or 0 if not found
Weapon* FindByName(const string& name);
// Returns pair of :
// - best weapon that can be currently used for given target or 0
// if none can be used ( best = highest dps + within range )
// - flag that indicates if target is within range of this weapon
// ( if true is within range )
// if target is beyond reach, unit should move closer before use
std::pair<Weapon*, bool> GetWeaponForTarget(CommandTarget* target);
// Returns weapon unit is attacking with now or 0 if
// unit is not attacking
Weapon* GetCurrentWeapon() const { return _currentWeapon; }
// Sets weapon as currently used ( which means unit started to attack )
void SetCurrentWeapon(Weapon* weapon) { _currentWeapon = weapon; }
// Reset currently used weapons ( which means unit ended attack )
void ReleaseWeapon() { _currentWeapon = 0; }
};
} | true |
e5d5c706d6ff1d3a9bbcc34e6de4958aaa412c89 | C++ | stone725/CompetitiveProgramming | /AtCoder/abc141/abc141_d.cpp | UTF-8 | 496 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<int> a(n);
for (auto &&i : a)
{
cin >> i;
}
priority_queue<int> b(begin(a), end(a));
for (int i = 0; i < m; i++)
{
b.push(b.top() / 2);
b.pop();
}
long long ans = 0;
for (int i = 0; i < n; i++)
{
ans += b.top();
b.pop();
}
cout << ans << "\n";
} | true |
926c673f33c1108b684dea17da6be739c310a97e | C++ | kyle620/Bluetooth-Windows-App | /BluetoothGUI/BluetoothGUI/bluetoothgui.cpp | UTF-8 | 5,488 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "bluetoothgui.h"
#include <QtCore>
#include <QString>
#include <QtGui>
using std::find;
using namespace Qt;
BluetoothGUI::BluetoothGUI(QWidget *parent)
: QMainWindow(parent),bled_connectionSatus(false)
{
ui.setupUi(this);
}
BluetoothGUI::~BluetoothGUI()
{
}
/* This method gets called any time the user presses the connect button */
void BluetoothGUI::button_connectClicked()
{
QString input = ui.serial_portList->currentText();
ui.LOG->setText("Current text is: " + input);
if (input == "Select a device"){
ui.LOG->append("User selsected 'Select a device'"); // do nothing, user did not select device Might add a message to the user if this happens
}
else {
// check if we alreay are connected
if (!bled_connectionSatus) {
// not conbected, need to open COM port user selected
for (QVector<QSerialPortInfo>::iterator it = serialList.begin(); it != serialList.end(); it++) {
// format of the string should be "PortName: Description
// i.e. COM12: Bluegigia
if (input == (*it).portName() + ": " + (*it).description()) {
bled112 = new BLED112();
bledThread = new QThread();
setupConnections(); // this method will setup the signals and slots used to connect the threads
bled112->doSetup(bledThread, *it); // setup the values inside bled112 object
bled112->moveToThread(bledThread); // move object to run in the thread
bledThread->start(); // begin thread
break;
}
} // end of for loop
}
else {
ui.LOG->append("Already connected!");
}
} // end of else
} // end of button_connectClicked()
/*
This method is invoked when the user clicks the disconect button
it will disconnect the BLED112 from the serial port
*/
void BluetoothGUI::button_disconnectClicked()
{
// check make sure we have a connection to close
if (bled_connectionSatus) {
// connected to a device need to close
ui.button_connect->setText("Attach");
ui.button_connect->setStyleSheet("QPushButton#button_connect{background-color: light grey}");
// update background thread
emit disconnect();
bled_connectionSatus = false;
while (!bledThread->isFinished()) {
//qDebug() << "Thread still running";
}
// delete pointers
delete bled112;
delete bledThread;
}
else ui.LOG->append("Not connected to a device");
}
void BluetoothGUI::button_scanClicked() {
// first make sure that we are connected to a BLED112 device
if (!bled_connectionSatus)
ui.LOG->append("Unavailable to scan, please connect to a device first");
else {
ui.LOG->append("Unavailable to scan, please connect to a device first");
emit scanBLE();
}
}
/* This method is used to accept the signal from the BLED112 running in background
when the LOG UI element needs updated this function handles it */
void BluetoothGUI::onUpdateLOG(QString msg)
{
ui.LOG->append("BLED112 Thread: " + msg);
}
/* This is the slot used to accept the signal from the BLED112 running in background
it gets called when emit(signal, onConnect(arg)) is called from the
background thread */
void BluetoothGUI::onConnect(bool status)
{
if (status) {
// true
bled_connectionSatus = true;
// tell the user by setting the background color to green, and change text to say attatched
ui.button_connect->setStyleSheet("QPushButton#button_connect{background-color: green}");
ui.button_connect->setText("Attatched!");
}
else {
// could not connect to device tell user
ui.button_connect->setStyleSheet("QPushButton#button_connect{background-color: red}");
ui.button_connect->setText("Retry!");
while (!bledThread->isFinished()) {
//qDebug() << "Thread still running";
}
// delete pointers
delete bled112;
delete bledThread;
}
}
void BluetoothGUI::dropbox_serial_portList(int a)
{
// first allocate room in the vector, this will help efficiency becasue push_back is costly
serialList.reserve(10);
QVector<QSerialPortInfo>::iterator it;
// Example use QSerialPortInfo
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
if (!checkList(info)) {
serialList.push_back(info);
ui.serial_portList->addItem(info.portName() + ": " + info.description());
qDebug() << "Name : " << info.portName();
qDebug() << "Description : " << info.description();
qDebug() << "Manufacturer: " << info.manufacturer();
}
}
}
/* This method will check if a port is already in the list, it returns true if found */
bool BluetoothGUI::checkList(const QSerialPortInfo& elem)
{
QVector<QSerialPortInfo>::iterator begin_ = serialList.begin();
QVector<QSerialPortInfo>::iterator end_ = serialList.end();
for (; begin_ != end_; begin_++) {
if ((*begin_).portName() == elem.portName())
return true;
}
return false;
}
/* This method will setup the signals and slots between the main UI thread and background thread */
void BluetoothGUI::setupConnections()
{
ui.LOG->append("Inside setupConnections");
// setup the signals to listen for from BLE112 object
connect(bled112, SIGNAL(connectBLED(bool)), this, SLOT(onConnect(bool))); // signal emitted when opening serial port, response handled by BluetoothGUI in onConnect
connect(this, SIGNAL(disconnect()), bled112, SLOT(onDisconnect())); // signnal emitted when usere presses disonnect, response handled by BLED112 in onDisconcet
connect(bled112, SIGNAL(updateLOG(QString)), this, SLOT(onUpdateLOG(QString)));
connect(this, SIGNAL(scanBLE()), bled112, SLOT(onScan()));
}
| true |
297460c0c8db1c1d3a4d040bd7c3c40c25dd0e2d | C++ | RuiLiu1217/Practice | /move/_0583_DeleteOperationForTwoStrings.cpp | UTF-8 | 3,209 | 3.578125 | 4 | [] | no_license | #include "headers.hpp"
/*
Now, dp[i][j]dp[i][j] refers to the number of deletions required to
equalize the two strings if we consider the strings' length upto (i-1)^{th}
index and (j-1)^{th} index for s1 and s2 respectively. Again, we fill
in the dp array in a row-by-row order. Now, in order to fill the entry
for dp[i][j], we need to consider two cases only:
(1) The characters s1[i-1] and s2[j-1] match with each other. In
this case, we need to replicate the entry corresponding to dp[i-1][j-1] itself.
This is because, the matched character doesn't need to be deleted from any of the strings.
(2) The characters s1[i-1] and s2[j-1] don't match with each other. In this
case, we need to delete either the current character of s1 or s2. Thus, an
increment of 1 needs to be done relative to the entries corresponding to the
previous indices. The two options available at this moment are dp[i-1][j] and dp[i][j−1].
Since, we are keeping track of the minimum number of deletions required, we
pick up the minimum out of these two values.
*/
int LeetCode::_0583_DeleteOperationForTwoStrings::minDistance_DP_nonLCS_based(std::string word1, std::string word2) {
const int m = word1.size();
const int n = word2.size();
DP = std::vector<std::vector<int>>(m + 1, std::vector<int>(n + 1, 0));
for(int i = 0; i <= m; ++i) {
for(int j = 0; j <= n; ++j) {
if(i == 0 || j == 0) {
DP[i][j] = i + j;
} else if(word1[i-1] == word2[j-1]) {
DP[i][j] = DP[i-1][j-1];
} else {
DP[i][j] = 1 + std::min(DP[i-1][j], DP[i][j-1]);
}
}
}
return DP[m][n];
}
int LeetCode::_0583_DeleteOperationForTwoStrings::minDistance_LCS_DP_based(std::string word1, std::string word2) {
const int m = word1.size();
const int n = word2.size();
DP = std::vector<std::vector<int>>(m + 1, std::vector<int>(n + 1, 0));
for(int i = 0; i <= m; ++i) {
for(int j = 0; j <= n; ++j) {
if(i == 0 || j == 0) {
continue;
}
if(word1[i - 1] == word2[j - 1]) {
DP[i][j] = DP[i-1][j-1] + 1;
} else {
DP[i][j] = std::max(DP[i][j-1], DP[i-1][j]);
}
}
}
return m + n - 2 * DP[m][n];
}
int LeetCode::_0583_DeleteOperationForTwoStrings::minDistance_LCS_based(std::string word1, std::string word2) {
const int m = word1.size();
const int n = word2.size();
DP = std::vector<std::vector<int>>(m + 1, std::vector<int>(n + 1, 0));
return m + n - 2 * lcs(word1, word2, m, n);
}
// 如何计算最长公共子序列
int LeetCode::_0583_DeleteOperationForTwoStrings::lcs(std::string& s1, std::string& s2, int m, int n) {
if(m == 0 || n == 0) {
return 0;
}
if(DP[m][n] > 0) {
return DP[m][n];
}
if(s1[m-1] == s2[n-1]) {
return DP[m][n] = 1 + lcs(s1, s2, m-1, n-1);
} else {
return DP[m][n] = std::max(lcs(s1, s2, m-1, n), lcs(s1,s2,m, n-1));
}
}
int LeetCode::_0583_DeleteOperationForTwoStrings::minDistance(std::string word1, std::string word2) {
return minDistance_DP_nonLCS_based(word1, word2);
} | true |
dd83d5682e441c4d46048fed11a74e3f0f345a3c | C++ | haigaz15/Intro_To_OOP | /C++HomeWork/FirstQuestion/FirstQuestion.cpp | UTF-8 | 393 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int n;
int sum = 0;
cout << "Enter your number: " << endl;
cin >> n;
for (int i = 2; i < n; i++) {
if (i % 2 != 0) {
sum = sum + i;
}
}
cout << "The sum is: " << sum << endl;
system("pause");
return 0;
}
// largest value for n if it is int is: 2147483647
// largesr value for n if it is unsigned int : 2,147,483,647 | true |
d8d2fe0f831e849549d417751091d53da483144f | C++ | IITamas/Spoj-Programs | /6694.cpp | UTF-8 | 243 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
Problem:D-playing with Marbles
Programmer:Iles Illes Tamas
Date:2019.04.25
*/
int main()
{
int k;
while (cin>>k&&k!=0)
{
k++;
cout<<(3*k*k-k)/2<<endl;
}
return 0;
}
| true |
ada40bdfada9ff6f66bc027ae03eb4ee1c38b74f | C++ | kkwoo0620/Hello-World | /DataStructure/DataStructure/practice.cpp | UHC | 1,030 | 4.09375 | 4 | [] | no_license | #include<iostream>
using namespace std;
int Factorial(int n)
{
if (n == 1)
return 1;
else
return n * Factorial(n - 1);
}
int Fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
int BSearchRecur(int ar[], int first, int last, int target)
{
if (first > last)
return -1;
int mid = (first + last) / 2;
if (ar[mid] == target)
return mid;
else
{
if (ar[mid] < target)
return BSearchRecur(ar, mid + 1, last, target);
else
return BSearchRecur(ar, first, mid - 1, target);
}
}
void HanoiTower(int num, char from, char by, char to)
{
if (num == 1)
cout << " 1 " << from << " " << to << " ̵" << endl;
else
{
HanoiTower(num - 1, from, to, by);
cout << " " << num << " " << from << " " << to << " ̵" << endl;
HanoiTower(num - 1, by, from, to);
}
}
int main()
{
int result = Fibonacci(10);
cout << result << endl;
cout << Factorial(5)<<endl;
HanoiTower(3, 'a', 'b', 'c');
} | true |
542448286c3ede49b46464a90a0313282c2c7753 | C++ | Thinker222/EricLearnsDataStructures-Algorithms | /Sequence/SequenceTest.cpp | UTF-8 | 637 | 2.828125 | 3 | [] | no_license | #include "Sequence.cpp"
#include <iostream>
#include <cstdlib>
int main()
{
using namespace Data_Structures;
Sequence seq;
Sequence seq2;
for(int i = 0; i < 20; i++)
{
seq.insert(i);
std::cout << seq2.current() << std::endl;
}
for(int i = 0; i < 20; i++)
{
seq2.attach(i);
std::cout << seq2.current() << std::endl;
}
seq.debug();
seq2.debug();
seq.start();
for(int i = 0; i < 15; i++)
{
seq.remove_current();
}
seq.advance();
seq.advance();
std::cout << seq.current() << std::endl;
seq.remove_current();
seq.debug();
return 0;
} | true |
4d0f41825ef73dc488970a69ad1fa876e5cd00c7 | C++ | InvincibleTyphoon/Qt-ExpressJSLogin | /Qt/Qt-ExpressJSLogin/LoginRequester.cpp | UTF-8 | 1,406 | 2.546875 | 3 | [] | no_license | #include "LoginRequester.h"
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
//singletone patterns
LoginRequester* LoginRequester::instance = new LoginRequester();
LoginRequester* LoginRequester::getInstance(){
return instance;
}
LoginRequester::LoginRequester()
{
serverUrl = "http://localhost:3000";
manager = new QNetworkAccessManager();
}
bool LoginRequester::requestLogin(QString id, QString password){
//for synchronous execution
QByteArray postData;
postData.append("id=" + id +"&");
postData.append("password=" + password);
return sendPostRequest(QString("/login/requestLogin"),postData);
}
bool LoginRequester::sendPostRequest(QString& directory, QByteArray& postData){
QString requestUrl = serverUrl + directory;
request.setUrl(requestUrl);
reply = manager->post(request,postData);
QEventLoop eventLoop;
connect(manager,SIGNAL(finished(QNetworkReply*)), &eventLoop,SLOT(quit()));
qDebug()<<"wait for answer";
// wait for reply
eventLoop.exec();
qDebug()<<"Received answer";
if(reply->error()){
qDebug() <<"reply error !";
return NULL;
}
//parsing
QString answer = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(answer.toUtf8());
qDebug()<<doc.object()["success"].toBool();
return doc.object()["success"].toBool();
}
| true |
522adb88d047aa67c0d5bae9d919c08e76bf303d | C++ | neta-vega/Tetris-Game | /shape.cpp | UTF-8 | 9,009 | 2.578125 | 3 | [] | no_license | #include "player.h"
#include "human.h"
#include "Computer.h"
#include "board.h"
#include "game.h"
#include "menu.h"
#include "point.h"
#include "shape.h"
#include "utils.h"
#pragma warning (disable:4996)
using namespace std;
#include <iostream>
#include <windows.h>
#include <process.h>
#include <conio.h>
#include <time.h>
#include <thread>
#include <chrono>
#include <stdlib.h>
#include <stdio.h>
void Shape::setPointArr(Point p1, Point p2, Point p3, Point p4)
{
point_arr[0] = p1;
point_arr[1] = p2;
point_arr[2] = p3;
point_arr[3] = p4;
}
void Shape::setPrevPointArr(Point p1, Point p2, Point p3, Point p4)
{
prev_point_arr[0] = p1;
prev_point_arr[1] = p2;
prev_point_arr[2] = p3;
prev_point_arr[3] = p4;
}
void Shape::generateShapes(int random)
{
const int two = 2, three = 3, one = 1, four = 4;
Point point_arr[4];
int point_index = 0;
switch (random)
{
case 0: // J shape
curr_shape[0][0] = HASHTAG; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = ' ';
curr_shape[1][0] = ' '; curr_shape[1][1] = ' '; curr_shape[1][2] = HASHTAG; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, three);
break;
case 1: // I shape
curr_shape[0][0] = HASHTAG; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = HASHTAG;
curr_shape[1][0] = ' '; curr_shape[1][1] = ' '; curr_shape[1][2] = ' '; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(one, four);
break;
case 2: // L shape
curr_shape[0][0] = HASHTAG; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = ' ';
curr_shape[1][0] = HASHTAG; curr_shape[1][1] = ' '; curr_shape[1][2] = ' '; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, three);
break;
case 3: // [] shape
curr_shape[0][0] = ' '; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = ' ';
curr_shape[1][0] = ' '; curr_shape[1][1] = HASHTAG; curr_shape[1][2] = HASHTAG; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, two);
break;
case 4: // S shape
curr_shape[0][0] = ' '; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = ' ';
curr_shape[1][0] = HASHTAG; curr_shape[1][1] = HASHTAG; curr_shape[1][2] = ' '; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, three);
break;
case 5: // T shape
curr_shape[0][0] = HASHTAG; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = HASHTAG; curr_shape[0][3] = ' ';
curr_shape[1][0] = ' '; curr_shape[1][1] = HASHTAG; curr_shape[1][2] = ' '; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, three);
break;
case 6: // Z shape
curr_shape[0][0] = HASHTAG; curr_shape[0][1] = HASHTAG; curr_shape[0][2] = ' '; curr_shape[0][3] = ' ';
curr_shape[1][0] = ' '; curr_shape[1][1] = HASHTAG; curr_shape[1][2] = HASHTAG; curr_shape[1][3] = ' ';
curr_shape[2][0] = ' '; curr_shape[2][1] = ' '; curr_shape[2][2] = ' '; curr_shape[2][3] = ' ';
curr_shape[3][0] = ' '; curr_shape[3][1] = ' '; curr_shape[3][2] = ' '; curr_shape[3][3] = ' ';
this->setHeightWidth(two, three);
break;
}
//initializing the point array
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (curr_shape[i][j] == HASHTAG)
{
int jPlus4 = j + 4;
point_arr[point_index].setValue(jPlus4, i);
point_index++;
}
}
}
setPointArr(point_arr[0], point_arr[1], point_arr[2], point_arr[3]);
}
void Shape::rotate(Shape& actual_shape, Board& board, Input direction)
{//rotating the shape inside the shape's matrix
Point point_arr[4];
int point_index = 0;
savePrevShape(actual_shape);
if (direction == COUTERCLOCKWISE) //ROTATE counterclockwise
{
char temp = actual_shape.curr_shape[0][0];
actual_shape.curr_shape[0][0] = actual_shape.curr_shape[3][0];
actual_shape.curr_shape[3][0] = actual_shape.curr_shape[3][3];
actual_shape.curr_shape[3][3] = actual_shape.curr_shape[0][3];
actual_shape.curr_shape[0][3] = temp;
temp = actual_shape.curr_shape[0][1];
actual_shape.curr_shape[0][1] = actual_shape.curr_shape[2][0];
actual_shape.curr_shape[2][0] = actual_shape.curr_shape[3][2];
actual_shape.curr_shape[3][2] = actual_shape.curr_shape[1][3];
actual_shape.curr_shape[1][3] = temp;
temp = actual_shape.curr_shape[0][2];
actual_shape.curr_shape[0][2] = actual_shape.curr_shape[1][0];
actual_shape.curr_shape[1][0] = actual_shape.curr_shape[3][1];
actual_shape.curr_shape[3][1] = actual_shape.curr_shape[2][3];
actual_shape.curr_shape[2][3] = temp;
temp = actual_shape.curr_shape[1][1];
actual_shape.curr_shape[1][1] = actual_shape.curr_shape[2][1];
actual_shape.curr_shape[2][1] = actual_shape.curr_shape[2][2];
actual_shape.curr_shape[2][2] = actual_shape.curr_shape[1][2];
actual_shape.curr_shape[1][2] = temp;
}
if (direction == CLOCKWISE) //ROTATE clockwise
{
char temp = actual_shape.curr_shape[3][3];
actual_shape.curr_shape[3][3] = actual_shape.curr_shape[3][0];
actual_shape.curr_shape[3][0] = actual_shape.curr_shape[0][0];
actual_shape.curr_shape[0][0] = actual_shape.curr_shape[0][3];
actual_shape.curr_shape[0][3] = temp;
temp = actual_shape.curr_shape[1][3];
actual_shape.curr_shape[1][3] = actual_shape.curr_shape[3][2];
actual_shape.curr_shape[3][2] = actual_shape.curr_shape[2][0];
actual_shape.curr_shape[2][0] = actual_shape.curr_shape[0][1];
actual_shape.curr_shape[0][1] = temp;
temp = actual_shape.curr_shape[2][3];
actual_shape.curr_shape[2][3] = actual_shape.curr_shape[3][1];
actual_shape.curr_shape[3][1] = actual_shape.curr_shape[1][0];
actual_shape.curr_shape[1][0] = actual_shape.curr_shape[0][2];
actual_shape.curr_shape[0][2] = temp;
temp = actual_shape.curr_shape[1][2];
actual_shape.curr_shape[1][2] = actual_shape.curr_shape[2][2];
actual_shape.curr_shape[2][2] = actual_shape.curr_shape[2][1];
actual_shape.curr_shape[2][1] = actual_shape.curr_shape[1][1];
actual_shape.curr_shape[1][1] = temp;
}
int _x = coordinate.getX();
int _y = coordinate.getY();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (actual_shape.curr_shape[i][j] == HASHTAG)
{
int newX = _x + j;
int newY = _y + i;
point_arr[point_index].setValue(newX, newY);
point_index++;
}
}
}
actual_shape.setPointArr(point_arr[0], point_arr[1], point_arr[2], point_arr[3]);
actual_shape.setHeightWidth(actual_shape.getWidth(), actual_shape.getHeight()); //switching the height and width as the shape rotates
}
int Shape::getHeight()
{
return this->height;
}
int Shape::getWidth()
{
return this->width;
}
void Shape::setHeightWidth(const int& h, const int& w)
{
this->height = h;
this->width = w;
}
void Shape::savePrevShape(Shape& actual_shape)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
actual_shape.prev_shape[i][j] = actual_shape.curr_shape[i][j];
}
}
setPrevPointArr(point_arr[0], point_arr[1], point_arr[2], point_arr[3]);
}
int Shape::firstOccurenceOfCurrShapeK(Shape& curr_shape)
{ //returning the first occurence of the shape inside the shape's matrix from the bottom - in which row it occured
for (int k = 3; k >= 0; k--)
{
for (int l = 0; l < 4; l++)
{
if (curr_shape.curr_shape[k][l] == HASHTAG)
{
return k;
}
}
}
}
int Shape::firstOccurenceOfCurrShapeL(Shape& curr_shape)
{//returning the first occurence of the shape inside the shape's matrix from the left - in which column it occured
for (int l = 0; l <= 3; l++)
{
for (int k = 0; k <= 3; k++)
{
if (curr_shape.curr_shape[k][l] == HASHTAG)
{
return l;
}
}
}
}
void Shape::ableToMove(Shape& curr_shape, Board& board)
{
if (isStuckV2(curr_shape, board))
{
canMove = false;
}
}
| true |
ecf79d983dec270a95adc857ae62df7a7f6ff20d | C++ | lihaosheng123/DirectX3D-Tool-Game | /DirectX9/sound.h | SHIFT_JIS | 1,791 | 2.671875 | 3 | [] | no_license | //=============================================================================
//
// TEh [sound.h]
// Author : AKIRA TANAKA
//
//=============================================================================
#ifndef _SOUND_H_
#define _SOUND_H_
//*****************************************************************************
// TEht@C
//*****************************************************************************
typedef enum
{
SOUND_LABEL_BGM000 = 0, // BGM0
SOUND_LABEL_BGM001, // BGM1
SOUND_LABEL_BGM002, // BGM2
SOUND_LABEL_SE_SHOT, // eˉ
SOUND_LABEL_SE_HIT, // qbg
SOUND_LABEL_SE_EXPLOSION, //
SOUND_LABEL_MAX,
} SOUND_LABEL;
//*****************************************************************************
// p[^\̒`
//*****************************************************************************
typedef struct
{
char *pFilename; // t@C
int nCntLoop; // [vJEg
} SOUNDPARAM;
class CSound
{
private:
IXAudio2 *g_pXAudio2 ; // XAudio2IuWFNgւ̃C^[tFCX
IXAudio2MasteringVoice *g_pMasteringVoice ; // }X^[{CX
IXAudio2SourceVoice *g_apSourceVoice[SOUND_LABEL_MAX] ; // \[X{CX
BYTE *g_apDataAudio[SOUND_LABEL_MAX] ; // I[fBIf[^
DWORD g_aSizeAudio[SOUND_LABEL_MAX] ; // I[fBIf[^TCY
public:
CSound();
~CSound();
HRESULT Init(HWND hWnd);
void Uninit(void);
HRESULT Play(SOUND_LABEL label);
void Stop(SOUND_LABEL label);
void StopAll(void);
HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition);
HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset);
};
#endif
| true |
0d9669ead1efa12d3336b1d5fc0275e084b4dd65 | C++ | enigmacodemaster/Algorithms_and_dataStructures | /leetcode/leetcode_104_递归.cpp | UTF-8 | 445 | 3.21875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
TreeNode* ptr = root;
TreeNode* left_ptr = ptr->left;
TreeNode* right_ptr = ptr->right;
int left_depth = maxDepth(left_ptr);
int right_depth = maxDepth(right_ptr);
if (left_depth > right_depth)
return left_depth + 1;
else
return right_depth + 1;
}
};
| true |
4c3d0707abc6fbc7ff37573ee31d27cd8f8c7020 | C++ | davschne/accelerated-cpp | /ch06/ex-6-2.cpp | UTF-8 | 1,559 | 3.296875 | 3 | [] | no_license | // 6-2. Write a program to test the `find_urls` function.
#include <iostream>
using std::cout;
using std::endl;
#include <numeric>
using std::accumulate;
#include <string>
using std::string;
#include <vector>
using std::vector;
using vec = std::vector<string>;
#include <unordered_set>
using set = std::unordered_set<string>;
#include "find_urls.h"
struct TestCase {
string input;
set expected;
};
int main() {
vector<TestCase> cases {
TestCase {
"Visit us on the web at http://malware.com/hackme and subscribe!",
set {"http://malware.com/hackme"}
},
TestCase {
"Thanks for visiting https://spyware.org . Download your files here: ftp://spyware.org/infectme",
set {"https://spyware.org", "ftp://spyware.org/infectme"}
},
TestCase {
"Edge cases like a://b are fun. Not every ://is a url://",
set {"a://b"}
}
};
for (const TestCase& test_case : cases) {
vector<string> result {find_urls(test_case.input)};
set result_set(result.begin(), result.end());
const set& expected = test_case.expected;
if (result_set != test_case.expected) {
cout << "Test case failed." << endl;
cout << "result: " << accumulate(result.cbegin(), result.cend(), string {}) << endl;
cout << "expected: " << accumulate(expected.cbegin(), expected.cend(), string {}) << endl;
return 1;
}
}
cout << "All tests passed!" << endl;
return 0;
}
| true |
4a25c586fde55f2891361198b8cbc08406c2363e | C++ | dzhemini/Deykstri | /AlgoritmDeykstri/AlgoritmDeykstri/AlgoritmDeykstri.cpp | UTF-8 | 1,820 | 2.6875 | 3 | [] | no_license | /// \file AlgoritmDeykstri.cpp
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<iomanip>
#include<conio.h>
using namespace std;
void read_from_file(int* n,int* start,int*finish,int* ves) ///chtenie faila
{
ifstream f("deikstra.txt");
if(!f) cout<<"File error!\n";
else
{
f >> *n >> *start>> *finish;
for(int i=0;i<*n;i++)
for(int j=0;j<*n;j++)
f>>*(ves+i*10+j);
}
}
int find_minimum(int* n,bool* used,int* metka) ///poisk minimuma
{
int min;
for(int i=0;i<*n;i++)
if (*(used+i)==false) {min=i;break;}
for(int i=0;i<*n;i++)
if(*(used+i)==false && *(metka+min)>*(metka+i)) min=i;
return min;
}
void find_neighbours(int a,int n,int* ves,bool* used,int* metka)
{
for(int i=0;i<n;i++)
if(*(ves+a+i*10)!=0 && !*(used+i) && *(metka+i)>*(ves+a+i*10)+*(metka+a))
*(metka+i)=*(ves+a+i*10)+*(metka+a);
*(used+a)=true;
}
void otladka(int* n,int* metka,bool* used) ///otladka
{
for(int i=0;i<*n;i++)
cout<<i+1<<':'<<*(metka+i)<<' '<<*(used+i)<<' ';
cout<<"\n";
}
bool finish_program(int* n,bool* used) ///okonchanie programmy
{
bool f=true;
for(int i=0;i<*n;i++)
if(!*(used+i)) f=false;
return f;
}
int main()
{
int start,finish,n; ///inicializacia peremennyh
int ves[10][10],metka[10]; ///massivy
bool used[10];
read_from_file(&n,&start,&finish,&ves[0][0]); ///ispolzovanie finkcii chteniya fayla
start--; ///nachalo
finish--; ///end
for(int i=0;i<n;i++)
{metka[i]=100;used[i]=false;}
metka[start]=0;
while(!finish_program(&n,&used[0]))
{
int nowusing=find_minimum(&n,&(used[0]),&(metka[0]));
find_neighbours(nowusing,n,&ves[0][0],&used[0],&metka[0]);
/*otladka(&n,&metka[0],&used[0]);*/
}
cout<<metka[finish];
cin.get();
} | true |
f7f9d4b59524dd1c29f61e554e8fb39d1bc1d52c | C++ | diogo23/1D_histogram | /main.cpp | UTF-8 | 691 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include "include/utils/utils.h"
#include "include/Histrogram.h"
int main() {
std::cout << "Starting Algorithm!" << std::endl;
HistogramInitValues histogramInitValues = getHistogramInitValues();
Histrogram Histogram(histogramInitValues.configProbabilities, histogramInitValues.colorVector);
for(const auto& robotSensedColor : histogramInitValues.colorSensedVector){
std::cout << "Going to move robot";
Histogram.moveRobot();
std::cout << "Color sensed: \"" + robotSensedColor << "\" ; Going to calculate probabilities:";
Histogram.robotSenseColor(robotSensedColor);
std::cout << std::endl;
}
return 0;
} | true |
800142decf32d6f1a1af30e02ff9231943690065 | C++ | CiprianBeldean/omega-Y | /src/game/Session.cpp | UTF-8 | 986 | 2.578125 | 3 | [] | no_license | #include "Session.h"
#include "Game.h"
#include "../net/NetHost.h"
#include "../net/NetClient.h"
Session::Session(SessionConfig cfg)
: type_(cfg.type) {
if (type_ == SessionType::HOST)
pNetHost_ = new NetHost(cfg.hostPort);
else
pNetClient_ = new NetClient(cfg.hostAddress, cfg.hostPort);
}
Session::~Session() {
//close network connections
if (pNetHost_)
delete pNetHost_, pNetHost_ = nullptr;
if (pNetClient_)
delete pNetClient_, pNetClient_ = nullptr;
// destroy the game
if (game_)
destroyGame();
}
void Session::initializeGame() {
assertDbg(game_ == nullptr);
game_ = new Game(gameCfg_);
game_->onStart.forward(onGameStart);
game_->onEnd.forward(onGameEnd);
}
void Session::destroyGame() {
assertDbg(game_ && !game_->isStarted());
delete game_, game_ = nullptr;
}
NetAdapter* Session::netAdapter() const {
NetAdapter* pAdapter = type_ == SessionType::HOST ? (NetAdapter*)pNetHost_ : (NetAdapter*)pNetClient_;
assertDbg(pAdapter);
return pAdapter;
}
| true |
1002ffa483b78e281e1e49623c9afc1a6d1b8b28 | C++ | eliseyOzerov/school | /huffmanCompression/Huffman.h | UTF-8 | 867 | 2.5625 | 3 | [] | no_license | //
// Created by Elisey on 13/05/2019.
//
#ifndef HUFFMANCOMPRESSION_HUFFMAN_H
#define HUFFMANCOMPRESSION_HUFFMAN_H
#include <vector>
#include <fstream>
#include <queue>
#include <iostream>
#include <unordered_map>
class Huffman {
private:
struct Node{
char c;
int weight = 1;
Node* right = nullptr;
Node* left = nullptr;
Node()=default;
Node(char c): c(c){}
};
Node* ROOT;
std::vector<Node*> priorityQueue;
std::unordered_map<char, std::pair<int, std::string>> charMap;
Node* popMin();
void createCodes(Node* root, std::string code);
void createEncodingTree();
void readFile(const std::string &path);
public:
void encode(const std::string &in, const std::string &out);
void decode(const std::string &in, const std::string &out);
};
#endif //HUFFMANCOMPRESSION_HUFFMAN_H
| true |
c780b9aba158740efcdcd02d1651ca81915b6fdc | C++ | nosnosnosnos/paiza | /POH6_sugoroku/POH6_sugoroku/main.cpp | UTF-8 | 989 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
unsigned int N,M;
int List[100];
int GOTO[100];
unsigned short chk[100]; //1:true 2:false
void loop(){
for (unsigned int i = 0; i < N; i++){
GOTO[i] = List[i] + i;
}
stack<unsigned int> st;
unsigned int _i = 0;
for (unsigned int i = N - 1; i > 0; i--){
if (List[i] == _i){
chk[i] = 1;
st.push(i);
}
_i++;
}
while (!st.empty()){
unsigned int index = st.top();
st.pop();
for (unsigned int i = N - 1; i > 0; i--){
if (index == GOTO[i]){
if (chk[i] == 1){
continue;
}
chk[i] = 1;
st.push(i);
}
}
}
}
int main(void){
//8
//0 6 - 2 - 2 0 1 - 1 0
//6
//7
//3
//4
//2
//5
//10
memset(chk, 0, sizeof(chk));
memset(List, 0, sizeof(List));
cin >> N;
for (int i = 0; i < N; i++){
cin >> List[i];
}
cin >> M;
loop();
for (int i = 0; i < M; i++){
unsigned int buf;
cin >> buf;
cout << ((chk[buf] == 1) ? "Yes" : "No") << endl;
}
return 0;
}
| true |
f88b37454036b3ffab186ba2bf0703142a30e4b8 | C++ | arthurWangSuper/C-primer | /Chapter15/vectorwithinhert.cpp | UTF-8 | 579 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <memory>
#include "Quote.h"
using namespace std;
int main(int argc,char**argv)
{
vector<shared_ptr<Quote>> basket;
//Bulk_quote *pBQ = new Bulk_quote(string("Sting"),19.9,10,0.9);
//basket.push_back(make_shared<Quote>("Sting",19.9));
basket.push_back(make_shared<Bulk_quote>("justin",19.9,10,0.25));
//cout<<basket.back()->net_price(15)<<endl;
double sum = 0.0;
for(auto elem:basket)
sum += elem->net_price(10);
cout<<"total price: "<<sum<<endl;
return 0;
} | true |
ad5cca7f78d18feaeabea4ff3f18bd234320d87e | C++ | rmartella/opencv_projects | /FingerTipTracking/src/TimeManager.cpp | UTF-8 | 1,096 | 2.953125 | 3 | [] | no_license | /*
* TimeManager.cpp
*
* Created on: 24/11/2015
* Author: rey
*/
#include "TimeManager.h"
TimeManager::TimeManager() {
}
TimeManager::~TimeManager() {
}
double TimeManager::CalculateFrameRate(bool writeToConsole) {
// Variables estaticas que almacenan los incrementos del tiempo
static double framesPerSecond = 0.0f; // Se almacenan los frames por segundo
static double startTicks = getTickCount(); // Se almacena el tiempo de inicio
static double lastTicks = getTickCount(); // Se almacena el tiempo del ulimo frame
static char strFrameRate[50] = { 0 }; // Almacenamos la cadena para el titulo de la ventana
static double currentFPS = 0.0f; // Se almacena el valor actual de los frames por segundos
currentTicks = getTickCount();
int DeltaTime = currentTicks - lastTicks;
++framesPerSecond;
if ((currentTicks - startTicks) / getTickFrequency() > 1.0f) {
startTicks = currentTicks;
if (writeToConsole)
fprintf(stderr, "Current Frames Per Second: %d\n",
int(framesPerSecond));
currentFPS = framesPerSecond;
framesPerSecond = 0;
}
return currentFPS;
}
| true |
a6f23c8e70c756e8204a50b1c9f823acc1d27465 | C++ | weekend27/OfferAlgs | /src/cpp/FirstNotRepeatingChar.cpp | UTF-8 | 451 | 2.765625 | 3 | [] | no_license | class Solution {
public:
int FirstNotRepeatingChar(string str) {
if (str.length() == 0) {
return -1;
}
int hash[256] = {0};
int i = 0;
while (str[i] != '\0') {
hash[str[i]]++;
i++;
}
i = 0;
while (str[i] != '\0') {
if (1 == hash[str[i]]) {
return i;
}
i++;
}
return -1;
}
};
| true |
db731c3cb015ece184aa45aeddfeac90ac445f5c | C++ | kwokth2016/Smart-garden | /smart/smart.ino | UTF-8 | 2,757 | 2.609375 | 3 | [] | no_license | #include <dht.h>
dht DHT;
#define DHT11_PIN 7
#define light A1
#define water A0
#define water2 A2
#define soil A3
#define pump1 4
#define pump2 5
#define ledstrip 8
#define buzzer 9
#define atomizer 10
#define fan1 11
#define fan2 12
void setup(){
Serial.begin(9600);
pinMode(buzzer, OUTPUT);
pinMode(ledstrip,OUTPUT);
pinMode(atomizer,OUTPUT);
pinMode(fan1,OUTPUT);
pinMode(fan2,OUTPUT);
pinMode(pump1,OUTPUT);
pinMode(pump2,OUTPUT);
}
void prepareJson(){
Serial.print("{");
Serial.print("\"water\": ");
Serial.print(analogRead(water));
Serial.print(",");
Serial.print("\"light\": ");
Serial.print(analogRead(light));
Serial.print(",");
Serial.print("\"temperature\": ");
Serial.print(DHT.temperature);
Serial.print(",");
Serial.print("\"humidity\": ");
Serial.print(DHT.humidity);
Serial.print(",");
Serial.print("\"Soil\": ");
Serial.print(analogRead(soil));
Serial.print(",");
Serial.print("\"water2\": ");
Serial.print(analogRead(water2));
Serial.println("}");
}
void alert(){
int waterlevel = analogRead(water);
if(waterlevel<50)
{
tone(buzzer, 250); // Send 1KHz sound signal...
delay(1000); // ...for 1 sec
noTone(buzzer); // Stop sound...
delay(1000); // ...for 1sec
}
int waterlevel2 = analogRead(water2);
if(waterlevel2<50)
{
tone(buzzer, 500); // Send 0.5KHz sound signal...
delay(1000); // ...for 1 sec
noTone(buzzer); // Stop sound...
delay(1000); // ...for 1sec
}
int temp = DHT.temperature;
if(temp<15)
{
tone(buzzer, 1000); // Send 1KHz sound signal...
delay(1000); // ...for 1 sec
noTone(buzzer); // Stop sound...
delay(1000); // ...for 1sec
}
if(temp>35)
{
tone(buzzer, 2000); // Send 2KHz sound signal...
delay(1000); // ...for 1 sec
noTone(buzzer); // Stop sound...
delay(1000); // ...for 1sec
}
}
void response(){
int lightlevel = analogRead(light);
int temperaturelevel = DHT.temperature;
int humiditylevel = DHT.humidity;
int soilmoisturelevel = analogRead(soil);
//led strip
if(lightlevel>450)
analogWrite(ledstrip,255);
else
analogWrite(ledstrip,0);
//fan and exhaust fan
if(temperaturelevel > 35){
digitalWrite(fan1,HIGH);
analogWrite(fan2,255);
}
else{
digitalWrite(fan1,HIGH);
analogWrite(fan2,0);
}
if(humiditylevel < 50 )
analogWrite(atomizer,255);
else
analogWrite(atomizer,0);
if(soilmoisturelevel > 700)
{
analogWrite(pump1,255);
analogWrite(pump2,255);
}
else
{
analogWrite(pump1,0);
analogWrite(pump2,0);
}
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
prepareJson();
alert();
response();
delay(1000);
}
| true |
34f8ca35bff50e255b0a5c94ef8fe0ff81168e0b | C++ | farescom/FTIMSGame | /Game/Parser/Syntax.cpp | UTF-8 | 855 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<vector>
#include<string>
#include<fstream>
#include<conio.h>
//#include "Key_words.h"
#include "Syntax.h"
using namespace std;
//void otworz_plik(string name, vector<string> &wczytane_slowa)
//{
// string linia;
// fstream plik;
//
// plik.open(name,ios::in);
// if(plik.good())
// {
// while(!plik.eof()-1)
// {
// getline(plik,linia);
// wczytane_slowa.push_back(linia);
// }
// plik.close();
// }
// else
// {
// cout<<"fail";
// }
//}
/*
void szukaj_slow(string slowo, string name)
{
int ile_wystapien=0;
vector <string> slowa_w_skrypcie;
string nazwa_pliku = "baza_slow.txt";
otworz_plik(nazwa_pliku,slowa_w_skrypcie);
for(int i=0; i<slowa_w_skrypcie.size(); i++)
{
if(slowa_w_skrypcie[i] == slowo)
ile_wystapien++;
}
cout<<"Ilosc wystapien slowa : "<<ile_wystapien<<endl;
}*/
| true |
91eb06f13af0ed8d8f16b7fbde444d9c11377a6f | C++ | corozco10/StubbornPlayer | /main.cpp | UTF-8 | 401 | 2.90625 | 3 | [] | no_license | //Author:Christian Orozco
#include "SecretDoor/SecretDoor.h"
#include <iostream>
using namespace std;
int main()
{
int timeswon;
int number;
SecretDoor game;
cout<<"How many times do you want to play?\n";
cin>>number;
for(int i=0;i<number;i++)
{
game.newGame();
game.guessDoorC();
game.guessDoorC();
if(game.isWinner() == true)
timeswon++;
}
cout<<timeswon<<endl;
return 0;
}
| true |
73fcc7493aca48d74dcd2c5e93dbb1a653f1981f | C++ | kemely2018/ADA | /LABORATORIO 7/punto_medio.cpp | UTF-8 | 1,995 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <ctime>
#define MAX_SIZE 8000
using namespace std;
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int particion(int* A,int p,int r){
int x,i,j,tmp;
x=A[r];
i=p-1;
for(j=p;j<=r-1;j++){
if(A[j]<=x){
i++;
swap(&A[i],&A[j]);
}
}
swap(&A[i+1],&A[r]);
return i+1;
}
void quickSort(int *A, int p, int r) {
int q;
if (p<r){
q = particion(A,p,r);
quickSort(A,p,q-1);
quickSort(A,q+1,r);
}
}
void sortByRow(int **mat, int n) {
for (int i = 0; i < n; i++)
//sort(mat[i], mat[i] + n);
quickSort(mat[i],0,n-1);
}
void printMat(int **mat, int n) {
ofstream archivo;
archivo.open("resultado.txt",ios::in);
int medio=(n/2)-1;
for (int i = 0; i < n; i++) {
archivo<<mat[i][medio]<<endl;
//cout << mat[i][medio] << " ";
}
archivo.close();
}
void leer(){
string s;
ifstream salida;
salida.open("resultado.txt");
while(!salida.eof()){
getline( salida, s );
cout << s <<endl;
}
salida.close();
}
int main(){
unsigned t0, t1;
int **numbers=new int*[MAX_SIZE];
ifstream inputFile;
for( int i=0; i<MAX_SIZE; i++ ){
numbers[i] = new int[MAX_SIZE];
}
t0=clock();
inputFile.open("datos.txt");
for(int countRows = 0; countRows < MAX_SIZE; countRows++)
{
for(int countColumns = 0; countColumns < MAX_SIZE; countColumns++)
{
inputFile >> numbers[countRows][countColumns];
}
}
inputFile.close();
sortByRow(numbers,MAX_SIZE);
printMat(numbers,MAX_SIZE);
t1=clock();
double time = (double(t1-t0)/CLOCKS_PER_SEC);
cout << "Execution Time: " << time << endl;
leer();
for( int i=0; i<MAX_SIZE; i++ ){
delete[] numbers[i];
}
delete[] numbers;
return 0;
}
| true |
cd1028b5599d609af667ade3f4531043cf8d5475 | C++ | Wizmann/ACM-ICPC | /POJ/2/2983.cc | UTF-8 | 1,251 | 2.734375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
int n,ask,num;
typedef struct node
{
int from,to,weight;
void setnode(int a,int b,int c)
{
from=a;to=b;weight=c;
}
}node;
node g[200010];
int dis[1010];
int min,max;
bool bellman_ford()
{
for(int i=min;i<=max;i++) dis[i]=1<<20;
dis[min]=0;
bool over;
for(int i=0;i<=max-min;i++)
{
over=true;
for(int k=0;k<num;k++)
{
if(dis[g[k].from]+g[k].weight>dis[g[k].to])
{
dis[g[k].to]=dis[g[k].from]+g[k].weight;
over=false;
}
}
if(over) break;
}
for(int i=0;i<num;i++)
{
if(dis[g[i].from]+g[i].weight>dis[g[i].to]) return false;
}
return true;
}
int main()
{
freopen("input.txt","r",stdin);
int a,b,c;
char cmd[3];
while(scanf("%d%d",&n,&ask)!=EOF)
{
min=1<<20;max=-1;
memset(g,0,sizeof(g));
memset(dis,0,sizeof(dis));
num=0;
for(int i=0;i<ask;i++)
{
scanf("%s",cmd);
if(*cmd=='P')
{
scanf("%d%d%d",&a,&b,&c);
g[num++].setnode(a,b,c);
g[num++].setnode(b,a,-c);
}
else
{
scanf("%d%d",&a,&b);
g[num++].setnode(a,b,1);
}
if(a>max) max=a;
if(a<min) min=a;
if(b>max) max=b;
if(b<min) min=b;
}
if(bellman_ford()) puts("Reliable");
else puts("Unreliable");
}
return 0;
}
| true |
317a60800bd641244a793adec75e60e30d439a81 | C++ | TejasPatil80178/LeetCode_Problems | /ConstructBinaryTreeFormInorderPostOrderTraversal.cpp | UTF-8 | 1,073 | 3.25 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int p = inorder.size()-1;
return bt(inorder,postorder,0,p,p);
}
int search(vector<int>& in,int s,int e,int val){
for(int i = s;i<=e;i++){
if(in[i]==val) return i;
}
return 0;
}
TreeNode* bt(vector<int>& in,vector<int>& post,int s,int e,int& p){
if(s>e) return NULL;
TreeNode* r = new TreeNode(post[p--]);
if(s==e) return r;
int index = search(in,s,e,r->val);
r->right = bt(in,post,index+1,e,p);
r->left = bt(in,post,s,index-1,p);
return r;
}
};
| true |
a8f078f1c9664c434ebb5701b9b7fe0df6eceb8e | C++ | MarcoBetance0327/C_plus_plus | /14. Archivos/Ejercicio 2.cpp | UTF-8 | 529 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
using namespace std;
void lectura();
int main(){
lectura();
}
void lectura(){
ifstream archivo;
string texto, nombreA;
cout<<"Digite el archivo a buscar: "; getline(cin, nombreA);
archivo.open(nombreA.c_str(), ios::in);
if(archivo.fail()){
cout<<"No se pudo abrir el archivo...";
exit(1);
}
while(!archivo.eof()){
getline(archivo, texto);
cout<<texto<<endl;
}
archivo.close();
}
| true |
b3fcb8c6501afc7e3cde8b1843d85f67aa9b1712 | C++ | wongdu/Alsa | /UtilsPoisx.cpp | UTF-8 | 3,808 | 2.84375 | 3 | [] | no_license |
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include "UtilsPoisx.h"
struct EventStructure
{
pthread_mutex_t mutex;
pthread_cond_t cond;
volatile bool signalled;
bool manual;
};
struct AtomicBoolStruct
{
pthread_mutex_t mutex;
bool value;
};
int EventInit(EventStru **event, enum EventType type)
{
int code = 0;
struct EventStructure *data = (struct EventStructure *)malloc(sizeof(struct EventStructure));
if (!data)
{
raise(SIGTRAP);
}
if ((code = pthread_mutex_init(&data->mutex, NULL)) < 0)
{
free(data);
return code;
}
if ((code = pthread_cond_init(&data->cond, NULL)) < 0)
{
pthread_mutex_destroy(&data->mutex);
free(data);
return code;
}
data->manual = (type == EVENT_TYPE_MANUAL);
data->signalled = false;
*event = data;
return 0;
}
void EventDestroy(EventStru *event)
{
if (event)
{
pthread_mutex_destroy(&event->mutex);
pthread_cond_destroy(&event->cond);
free(event);
}
}
int EventWait(EventStru *event)
{
int code = 0;
pthread_mutex_lock(&event->mutex);
if (!event->signalled)
{
code = pthread_cond_wait(&event->cond, &event->mutex);
}
if (code == 0)
{
if (!event->manual)
{
event->signalled = false;
}
pthread_mutex_unlock(&event->mutex);
}
return code;
}
static inline void add_ms_to_ts(struct timespec *ts,unsigned long milliseconds)
{
ts->tv_sec += milliseconds / 1000;
ts->tv_nsec += (milliseconds % 1000) * 1000000;
if (ts->tv_nsec > 1000000000)
{
ts->tv_sec += 1;
ts->tv_nsec -= 1000000000;
}
}
int EventTimedWait(EventStru *event, unsigned long milliseconds)
{
int code = 0;
pthread_mutex_lock(&event->mutex);
if (!event->signalled)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
add_ms_to_ts(&ts, milliseconds);
code = pthread_cond_timedwait(&event->cond, &event->mutex, &ts);
}
if (code == 0)
{
if (!event->manual)
{
event->signalled = false;
}
}
pthread_mutex_unlock(&event->mutex);
return code;
}
int EventTry(EventStru *event)
{
int ret = EAGAIN;
pthread_mutex_lock(&event->mutex);
if (event->signalled)
{
if (!event->manual)
{
event->signalled = false;
}
ret = 0;
}
pthread_mutex_unlock(&event->mutex);
return ret;
}
int EventSignal(EventStru *event)
{
int code = 0;
pthread_mutex_lock(&event->mutex);
code = pthread_cond_signal(&event->cond);
event->signalled = true;
pthread_mutex_unlock(&event->mutex);
return code;
}
void EventReset(EventStru *event)
{
pthread_mutex_lock(&event->mutex);
event->signalled = false;
pthread_mutex_unlock(&event->mutex);
}
uint64_t GetTimeNaSec(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ((uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec);
}
AtomicBoolStruct* AtomicBoolInit()
{
struct AtomicBoolStruct *pData = (struct AtomicBoolStruct *)malloc(sizeof(struct AtomicBoolStruct));
if (!pData)
{
raise(SIGTRAP);
}
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0)
{
goto cleanup;
}
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0)
{
goto cleanup;
}
if (pthread_mutex_init(&pData->mutex, &attr) != 0)
{
goto cleanup;
}
if (pthread_mutexattr_destroy(&attr) != 0)
{
pthread_mutex_destroy(&pData->mutex);
return NULL;
}
return pData;
cleanup:
return NULL;
}
void AtomicBoolDestroy(AtomicBoolStruct *event)
{
if (event)
{
pthread_mutex_destroy(&event->mutex);
}
}
void SetAtomicBool(AtomicBoolStruct *ptr, bool val)
{
if (ptr)
{
pthread_mutex_lock(&ptr->mutex);
ptr->value = val;
pthread_mutex_unlock(&ptr->mutex);
}
}
bool GetAtomicBool(AtomicBoolStruct *ptr)
{
bool bOldValue;
if (ptr)
{
pthread_mutex_lock(&ptr->mutex);
bOldValue = ptr->value;
pthread_mutex_unlock(&ptr->mutex);
}
return bOldValue;
}
| true |
6566c0fc5b2883385d477f5501f9f1a106a3696b | C++ | Diren52/Data-Abstraction-and-structures | /WeatherValue/WeatherValuetest.cpp | UTF-8 | 1,945 | 3.515625 | 4 | [] | no_license | #include "WeatherValue.h"
#include <iostream>
void testplan1();
void testplan2();
void testplan3();
void testplan4();
void testplan5();
void testplan6();
using namespace std;
int main()
{
cout << "Test 1: Defualt constructor";
testplan1();
cout << "Test 2:initializing using the default constructor ";
testplan2();
cout << "Test 3: checks the copy constructor";
testplan3();
cout << "Test 4: Checks the setter functions ";
testplan4();
cout << "Test 5: checking the conversion calculation ";
testplan5();
return 0;
}
ostream & operator <<( ostream & os, const Date & D )
{
os << D.getDay() << " " << D.getMonth() << " " << D.getYear();
return os;
}
ostream & operator <<( ostream & os, const Time & T )
{
os << T.getHour() << " " << T.getMinutes() << " ";
return os;
}
void testplan1()
{
WeatherValue wD;
cout << wD.getDate() << " " << wD.getTime()<< " " << wD.getSolarRadiation() << " " << wD.getWindSpeed() << endl;
}
void testplan2()
{
Date dte;
Time tme;
WeatherValue wD(dte, tme, 10, 20);
cout << wD.getDate() << " " << wD.getTime()<< " " << wD.getSolarRadiation() << " " << wD.getWindSpeed() << endl;
}
void testplan3()
{
Date dte;
Time tme;
WeatherValue oD(dte, tme, 10.0, 20.0);
WeatherValue wD(oD);
cout << wD.getDate() << " " << wD.getTime()<< " " << wD.getSolarRadiation() << " " << wD.getWindSpeed() << endl;
}
void testplan4()
{
Date dte(21, 3, 2017);
Time tme(12, 30);
WeatherValue wD;
wD.setDate(dte);
wD.setTime(tme);
wD.setSolarRadiation(988);
wD.setWindSpeed(1233);
cout << wD.getDate() << " " << wD.getTime()<< " " << wD.getSolarRadiation() << " " << wD.getWindSpeed() << endl;
}
void testplan5()
{
WeatherValue wD;
cout << wD.convertSolarRadiation(6000) <<endl; // expect 1.0
}
| true |
12ab0d9574abbd8543f0d0939891653ca7f716d5 | C++ | ZainabIftikhar/FileSystem | /Folder.h | UTF-8 | 548 | 2.515625 | 3 | [] | no_license | #pragma once
#include <string>
#include "Item.h"
#include <vector>
using namespace std;
class Folder:public Item
{
public:
Folder(string,string);
string getPath(){
return path;
}
void setPointer(Item*);
void Delete();
void DeleteItem(string);
Item* changeDir(string);
bool ifChanged();
void Show();
void Access(string, string);
void Save(ofstream &f);
Item * Resume(ifstream &f,string);
void Load(ifstream &f);
bool SeeExists(string);
~Folder(void);
private:
vector <Item*> itr;
string path;
};
| true |
9d363215397b458a54cf89c1901badb1689ec3e9 | C++ | Richie47/kattis | /conundrum.cpp | UTF-8 | 604 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include <string>
using std::cin;
using std::cout;
using std::string;
int main(int argc, char** argv) {
int p = 0, e = 1, r = 2, days = 0;
string s;
cin >> s;
for(int i = 0; i < s.length(); i++) {
if(i == p) {
if(s.at(i) != 'P')
days++;
p += 3;
}
else if(i == e) {
if(s.at(i) != 'E')
days++;
e += 3;
}
else if(i == r) {
if(s.at(i) != 'R')
days++;
r += 3;
}
}
cout << days;
return 0;
}
| true |
bb50b22c8831af0e80347d68f2ff199c502fa47f | C++ | uncerso/MPP | /usd.cpp | UTF-8 | 1,570 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <thread>
#include <sys/wait.h>
using namespace std;
void sigChildHandler(int signo) {
int status;
while (1) {
pid_t pid = waitpid(-1, &status, WNOHANG);
if (pid == -1) break;
}
}
struct msg_type {
int code;
int value;
};
void run_apps(const char * name) {
switch (fork()) {
case -1 :
cerr << "Cannot fork\n";
break;
case 0:
execlp(name, name+2, nullptr);
cerr << "Cannot run " << name << "\n";
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
constexpr int socket_family = 41;
constexpr int socket_type = 2;
constexpr int socket_protocol = 0;
constexpr int maxlen = 60;
struct sigaction act;
memset (&act, 0, sizeof(act));
act.sa_handler = sigChildHandler;
if (sigaction(SIGCHLD, &act, 0)) {
cerr << "Sigaction error\n";
return 1;
}
int sock_id = socket(socket_family, socket_type, socket_protocol);
if (sock_id < 0) {
cerr << "Cannot create socked, error: " << sock_id << '\n';
return 0;
}
char msg[maxlen+1];
memset(msg, 0, sizeof(msg));
char app_name[7];
memcpy(app_name, "./app_", 7);
while (true) {
int err = recv(sock_id, msg, maxlen, 0);
if (err == 0) {
auto p = reinterpret_cast<msg_type *>(msg);
cout << "code: " <<p->code << " value: " << p->value << endl;
if (p->code == 1) {
app_name[5] = p->value + '0';
run_apps(app_name);
}
}
}
return 0;
} | true |
f340fb0a87c42d833728bb1b8ba12dfd09ae3127 | C++ | HarshitShukla25/leetcode-solutions | /removekdigitstogetsmallestnumber.cpp | UTF-8 | 883 | 2.734375 | 3 | [] | no_license | class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
stack<char> s;
//removing the peak elements
for(char c : num)
{
while(!s.empty() && k>0 && s.top()>c)
{
s.pop();
k--;
}
if(!s.empty() || c!='0')
s.push(c);
}
//Now delete elements from top of stack agar k abhi bhi nhi khatam hua
while(!s.empty()&&k>0)
{
s.pop();
k--;
}
if(s.empty())
return "0";
// kuch ni bs stack ko string me kr rhe aur koi extra space ni use kr rhe
while(!s.empty())
{
num[n-1] = s.top();
s.pop();
n--;
}
return num.substr(n);
}
}; | true |
6ed70dc59275ad68d4c994248dcb8ecf9767e253 | C++ | Enhex/GUI | /src/gui/text_edit.cpp | UTF-8 | 8,874 | 2.515625 | 3 | [
"LLVM-exception",
"Apache-2.0"
] | permissive | #include "text_edit.h"
#include "../include_glfw.h"
#include "../framework/application.h"
text_edit::text_edit()
{
style = element_name;
auto& input_manager = context->input_manager;
input_manager.mouse_press.subscribe(this, [this](int button, int mods) {
on_mouse_press();
});
input_manager.mouse_release.subscribe_global_unfocused(this, [this](int button, int mods) {
//NOTE: frame_start only sends global events
context->input_manager.frame_start.unsubscribe_global(this);
});
input_manager.double_click.subscribe(this, [this](int button, int mods) {
on_double_click();
});
input_manager.key_press.subscribe(this, [this](int key, int mods) {
on_key_press(key, mods);
});
input_manager.key_repeat.subscribe(this, [this](int key, int mods) {
on_key_press(key, mods);
});
input_manager.character.subscribe(this, [this](unsigned int codepoint) {
on_character(codepoint);
});
input_manager.focus_end.subscribe(this, [this]() {
clear_selection();
});
// subscribe so text_edit will be able to capture focus
input_manager.focus_start.subscribe(this, [this]() {});
input_manager.mouse_release.set_continue_propagating(this, true);
}
void text_edit::on_str_changed()
{
update_glyphs();
on_text_changed();
}
void text_edit::update_glyph_positions()
{
auto& vg = context->vg;
nvgSave(vg);
init_font(vg); // for correct font size
auto const max_glyphs = str.size();
auto const absolute_position = get_position();
num_glyphs = nvgTextGlyphPositions(vg, X(absolute_position), Y(absolute_position), str.c_str(), nullptr, glyphs.get(), (int)max_glyphs);
if(cursor_pos > num_glyphs)
cursor_pos = num_glyphs;
nvgRestore(vg);
}
void text_edit::update_glyphs_no_bounds()
{
auto const max_glyphs = str.size();
glyphs = std::make_unique<NVGglyphPosition[]>(max_glyphs);
update_glyph_positions();
}
void text_edit::update_glyphs()
{
update_glyphs_no_bounds();
update_bounds();
}
void text_edit::set_cursor_to_mouse_pos()
{
// only need to use X position because it's already known the click is inside the element rectangle, and single-line text is used.
auto& input_manager = context->input_manager;
auto const mouse_x = X(input_manager.mouse_pos);
bool glyph_clicked = false;
for (auto i = num_glyphs; i-- > 0;)
{
auto const& glyph = glyphs[i];
auto const x_mid = glyph.x + (glyph.maxx - glyph.minx) / 2;
// check if the glyph was clicked
if (mouse_x >= glyph.minx &&
mouse_x <= x_mid) {
cursor_pos = i;
glyph_clicked = true;
break;
}
else if (mouse_x >= x_mid &&
mouse_x <= glyph.maxx) {
cursor_pos = i+1;
glyph_clicked = true;
break;
}
}
// if clicked past the last character, position the cursor at the end of the text
if(!glyph_clicked) {
auto const abs_text_end = X(get_position()) + text_bounds[2];
if(mouse_x > abs_text_end) {
cursor_pos = str.size();
}
}
}
void text_edit::on_mouse_press()
{
clear_selection();
set_cursor_to_mouse_pos();
selection_start_pos = cursor_pos;
context->input_manager.frame_start.subscribe_global(this, [this]() {
on_frame_start();
});
}
void text_edit::on_frame_start()
{
set_cursor_to_mouse_pos();
selection_end_pos = cursor_pos;
}
void text_edit::on_double_click()
{
// check if didn't start selecting already
if(selection_start_pos == selection_end_pos && !str.empty()){
// if double clicked whitespace select it and all the adjacent whitespaces
if(str[cursor_pos] == ' ')
{
bool found = false;
for(selection_start_pos = cursor_pos; selection_start_pos > 0; --selection_start_pos){
if(str[selection_start_pos] != ' '){
++selection_start_pos; // exclude whitespace
found = true;
break;
}
}
if(!found){
// for loop ends at index 1, but if the first character is whitespace start should be 0.
if(str[0] == ' '){
selection_start_pos = 0;
}
}
auto const size = str.size();
selection_end_pos = size;
for(auto i = cursor_pos; i < size; ++i){
if(str[i] != ' '){
selection_end_pos = i;
break;
}
}
}
// find previous and next whitespaces and select the text between them
else{
bool found = false;
for(selection_start_pos = cursor_pos; selection_start_pos > 0; --selection_start_pos){
if(str[selection_start_pos] == ' '){
++selection_start_pos; // exclude whitespace
found = true;
break;
}
}
if(!found){
// for loop ends at index 1, but if the first character is not whitespace start should be 0.
if(str[0] != ' '){
selection_start_pos = 0;
}
}
auto const size = str.size();
selection_end_pos = size;
for(auto i = cursor_pos; i < size; ++i){
if(str[i] == ' '){
selection_end_pos = i;
break;
}
}
}
cursor_pos = selection_end_pos;
}
}
void text_edit::on_key_press(int key, int mods)
{
switch (key) {
case GLFW_KEY_BACKSPACE:
if(has_selection()) {
delete_selection();
}
else if (cursor_pos > 0) {
str.erase(--cursor_pos, 1);
on_str_changed();
}
break;
case GLFW_KEY_DELETE:
if(has_selection()) {
delete_selection();
}
else if (cursor_pos < str.size()) {
str.erase(cursor_pos, 1);
on_str_changed();
}
break;
case GLFW_KEY_LEFT:
if (cursor_pos > 0)
{
auto const select = mods & GLFW_MOD_SHIFT;
if(select && !has_selection()) {
selection_start_pos = cursor_pos;
}
--cursor_pos;
if(select)
selection_end_pos = cursor_pos;
}
break;
case GLFW_KEY_RIGHT:
if (cursor_pos < str.size())
{
auto const select = mods & GLFW_MOD_SHIFT;
if(select && !has_selection()) {
selection_start_pos = cursor_pos;
}
++cursor_pos;
if(select)
selection_end_pos = cursor_pos;
}
break;
case GLFW_KEY_HOME:
cursor_pos = 0;
break;
case GLFW_KEY_END:
cursor_pos = str.size();
break;
case GLFW_KEY_C:
if (mods & GLFW_MOD_CONTROL) {
auto& app = static_cast<application&>(*context);
auto low_pos = std::min(selection_start_pos, selection_end_pos);
auto high_pos = std::max(selection_start_pos, selection_end_pos);
glfwSetClipboardString(app.window, str.substr(low_pos, high_pos - low_pos).c_str());
}
break;
case GLFW_KEY_V:
if (mods & GLFW_MOD_CONTROL) {
delete_selection();
auto& app = static_cast<application&>(*context);
auto const cstr = glfwGetClipboardString(app.window);
str.insert(cursor_pos, cstr);
cursor_pos += strlen(cstr);
on_str_changed();
}
break;
case GLFW_KEY_A:
if(mods & GLFW_MOD_CONTROL) {
select_all();
}
break;
}
}
void text_edit::on_character(unsigned codepoint)
{
if(!is_valid_character(codepoint))
return;
if(has_selection()) {
delete_selection();
}
str.insert(str.begin() + cursor_pos++, codepoint);
on_str_changed();
//NOTE: no need to update glyphs when deleting since the deleted glyphs won't be accessed.
}
void text_edit::draw(NVGcontext* vg)
{
// draw selection background
if(has_selection())
{
if (glyphs == nullptr)
update_glyphs();
auto const absolute_position = get_position();
auto const x_start = selection_start_pos == 0 ?
X(absolute_position) : // may have no characters, position at the start.
glyphs[selection_start_pos-1].maxx; // position at the end of the previous character
auto const x_end = selection_end_pos == 0 ?
X(absolute_position) :
glyphs[selection_end_pos-1].maxx;
nvgBeginPath(vg);
nvgRect(vg,
x_start, Y(absolute_position),
x_end - x_start, Y(size));
nvgFillColor(vg, selection_color);
nvgFill(vg);
}
text::draw(vg);
auto& input_manager = context->input_manager;
// draw cursor
if (this == input_manager.focused_element)
{
if (glyphs == nullptr)
update_glyphs();
auto const absolute_position = get_position();
auto const x_pos = cursor_pos == 0 ?
X(absolute_position) : // may have no characters, position at the start.
glyphs[cursor_pos-1].maxx; // position at the end of the previous character
nvgBeginPath(vg);
nvgMoveTo(vg, x_pos, Y(absolute_position));
nvgLineTo(vg, x_pos, Y(absolute_position) + Y(size));
nvgStrokeColor(vg, nvgRGBA(255, 255, 255, 255));
nvgStrokeWidth(vg, 1.0f);
nvgStroke(vg);
}
}
void text_edit::update_text()
{
clear_selection();
on_str_changed();
}
void text_edit::post_layout()
{
// glyph positions may change
if (glyphs != nullptr)
update_glyph_positions();
}
void text_edit::delete_selection()
{
//NOTE: if there's no selection 0 chars will be erased
auto low_pos = std::min(selection_start_pos, selection_end_pos);
auto high_pos = std::max(selection_start_pos, selection_end_pos);
str.erase(low_pos, high_pos - low_pos);
cursor_pos = low_pos;
clear_selection();
on_str_changed();
}
void text_edit::select_all()
{
selection_start_pos = 0;
selection_end_pos = str.size();
cursor_pos = selection_end_pos;
}
void text_edit::move_cursor_to_end()
{
cursor_pos = str.size();
} | true |
2351a4045a7f14107e4b1e2f15c10852582c89e1 | C++ | KrishnaSaiTarun/LeetCode | /0101. Symmetric Tree.cpp | UTF-8 | 732 | 3.296875 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return isMirror(root->left, root->right);
}
bool isMirror(TreeNode* l_tree, TreeNode* r_tree){
if(l_tree == NULL && r_tree == NULL) return true;
if(l_tree == NULL || r_tree == NULL) return false;
return (l_tree->val == r_tree->val && isMirror(l_tree->left, r_tree->right) && isMirror(l_tree->right, r_tree->left));
}
};
| true |
9bc839e7eaa1ee4b730066ad36b6e7c7b70163b2 | C++ | DanDoge/course_pku | /Practice of Data Structure and Algorithm/practice/001-003.cpp | UTF-8 | 1,359 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int prec[4048];
int size = 2000;
int init(){
for(int i = 1; i < 4048; i += 1){
prec[i] = i;
}
return 0;
}
int get_prec(int idx){
return (prec[idx] == idx) ? idx : (prec[idx] = get_prec(prec[idx]));
}
int main(int argc, char const *argv[]) {
std::ios::sync_with_stdio(false);
int num_cases = 0;
cin >> num_cases;
for(int i = 1; i <= num_cases; i += 1){
if(i > 1){
cout << endl;
}
cout << "Scenario #" << i << ":" << endl;
int num_bug, num_inter;
cin >> num_bug >> num_inter;
init();
int sus = 0;
for(int j = 1; j <= num_inter; j += 1){
int from, to;
cin >> from >> to;
int from_prec = get_prec(from);
int from_inter_prec = get_prec(from + size);
int to_prec = get_prec(to);
int to_inter_prec = get_prec(to + size);
if(from_prec == to_prec || from_inter_prec == to_inter_prec){
sus = 1;
}else{
prec[from_prec] = to_inter_prec;
prec[from_inter_prec] = to_prec;
}
}
if(sus){
cout << "Suspicious bugs found!" << endl;
}else{
cout << "No suspicious bugs found!" << endl;
}
}
return 0;
}
| true |
b1fd40371621869cdc9746b553c9f67f68d47c86 | C++ | spiricn/Wt | /include/wt/gui/Layout.h | UTF-8 | 2,093 | 2.53125 | 3 | [] | no_license | #ifndef WT_GUI_H
#define WT_GUI_H
#include "wt/stdafx.h"
#include "wt/FrameBuffer.h"
#include "wt/gui/View.h"
#include "wt/gui/ProgressView.h"
#include "wt/gui/Button.h"
#include "wt/gui/SliderView.h"
#include "wt/gui/CircleView.h"
#include "wt/gui/Checkbox.h"
#include "wt/gui/ListView.h"
#include "wt/EventManager.h"
#include "wt/EventEmitter.h"
namespace wt
{
namespace gui
{
class WindowManager;
class Layout : public View{
public:
Layout(Layout* parent, EventManager* eventManager, AGameInput* input);
~Layout();
void setVisible(bool visible);
bool isVisible() const;
void setVerticalCellSpacing(float spacing);
void setHorizontalCellSpacing(float spacing);
void setDefaultFont(Font* font);
void setGridSize(uint32_t numRows, uint32_t numColumns);
void removeView(View* view);
void setColor(const Color& color);
void setDefaultScaleMode(View::ScalingMode mode);
template<class T>
T* createView(const String& name="");
View* findView(const String& name);
template<class T>
T* findView(const String& name);
View* viewAt(float x, float y);
void draw(ICanvas& c);
bool handleEvent(const EventPtr evt);
void addView(View* view);
void setSize(const glm::vec2& size);
void setPosition(const glm::vec2& position);
private:
typedef std::map<uint32_t, View*> ViewMap;
private:
View* mFocus;
ViewMap mViews;
View* mHoverView;
View* mDragView;
View* mClickView;
Font* mDefaultFont;
uint32_t mNumGridRows;
uint32_t mNumGridColumns;
View::ScalingMode mDefaultScaleMode;
bool mNeedsRescale;
float mVerticalCellSpacing;
float mHorizontalCellSpacing;
bool mVisible;
}; // </Layout>
template<class T>
T* Layout::createView(const String& name){
T* res = NULL;
addView( res = new T(this, getEventManager(), getInput()) );
res->setName(name);
return res;
}
template<class T>
T* Layout::findView(const String& name){
for(ViewMap::iterator i=mViews.begin(); i!=mViews.end(); i++){
if(i->second->getName().compare(name)==0){
return static_cast<T*>(i->second);
}
}
return NULL;
}
} // </gui>
} // </wt>
#endif // </WT_LAYOUT_H>
| true |
cf179c3e15a3cd581011a14d0c790a1d91345611 | C++ | c-chou7/mapDemo | /main.cpp | GB18030 | 2,700 | 3.59375 | 4 | [] | no_license | /*
1. ӡзĿ
2. ӡȵλáٶȵһڽӵ㺣ζҪ͵ĵ㡣дһΪ isValley
ij
3. ҳӡߵ͵λü亣ΡдһΪ extremes ĺ
ijá
4. ĺ isPeak(), ʹ 8 ڽӵжϷ㣬ֻʹ 4 ڽжϡ
*/
#include<iostream>
#include<Windows.h>
#include<fstream>
#include<string>
#define MAXSIZE 64
void isPeak(int grid[MAXSIZE][MAXSIZE], int r, int c);
void isValley(int grid[MAXSIZE][MAXSIZE], int r, int c);
using namespace std;
int main(void) {
int map[MAXSIZE][MAXSIZE] = { 0 }; //ʼ
ifstream file; //ļ
string filename; //洢ļ
string choice; //ѡֵǹȵ
int rowsCount = 0; //洢ļ
int colsCount = 0; //洢ļ
cout << "Ҫļ:";
cin >> filename;
file.open(filename.c_str());
if (file.fail()) {
cout << "ļʧ!" << endl;
return 1;
}
file >> rowsCount >> colsCount; //
if (rowsCount > MAXSIZE || colsCount > MAXSIZE) {
cout << "ļݴ,С" << endl;
return 1;
}
for (int i = 0; i < rowsCount; i++) { //ļ
for (int j = 0; j < colsCount; j++) {
file >> map[i][j];
}
}
int n = 0; //˳ѭʾ
while (n == 0) {
system("cls");
cout << "ѡֵorȵ:";
cin >> choice;
if (choice == "ֵ") {
isPeak(map, rowsCount, colsCount);
system("pause");
}
else if (choice == "ȵ") {
isValley(map, rowsCount, colsCount);
system("pause");
}else {
n = 1;
}
}
system("pause");
return 0;
}
void isPeak(int grid[MAXSIZE][MAXSIZE], int r, int c){
for (int i = 1; i < r - 1; i++) {
for (int j = 1; j < c - 1; j++) {
if(grid[i][j] > grid[i - 1][j]&&
grid[i][j] > grid[i + 1][j] &&
grid[i][j] > grid[i][j - 1] &&
grid[i][j] > grid[i][j + 1]) {
cout << "ֵΪ " << i << " " << j << endl;
cout << "ֵΪ" << grid[i][j]<<endl;
}
}
}
}
void isValley(int grid[MAXSIZE][MAXSIZE], int r, int c){
for (int i = 1; i < r - 1; i++) {
for (int j = 1; j < c - 1; j++) {
if (grid[i][j] < grid[i - 1][j] &&
grid[i][j] < grid[i + 1][j] &&
grid[i][j] < grid[i][j - 1] &&
grid[i][j] < grid[i][j + 1]) {
cout << "ȵΪ " << i << " " << j << endl;
cout << "ȵΪ" << grid[i][j] << endl;
}
}
}
}
| true |
8c474dea48127c69a95766a9b520538d5044d67e | C++ | DemyCode/raytracer | /src/scene/object/plane.cc | UTF-8 | 1,608 | 2.984375 | 3 | [] | no_license | //
// Created by mehdi on 19/02/2020.
//
#include "plane.hh"
Plane::Plane(Vector3 point, Vector3 normal, TextureMaterial* textureMaterial)
{
this->point_ = point;
this->normal_ = normal.normalize();
this->textureMaterial_ = textureMaterial;
}
std::optional<Vector3> Plane::intersect(Ray ray) {
// double denom = this->normal_.dot(ray.getDirection());
// if (denom > 1e-6)
// {
// Vector3 p0l0 = this->point_ - ray.getPoint();
// double t = p0l0.dot(this->normal_) / denom;
// return ray.getPoint() + ray.getDirection() * t;
// }
// return std::nullopt;
// Vector3 AB = this->b_ - this->a_;
// Vector3 AC = this->c_ - this->a_;
Vector3 crossed = this->normal_;
double A = crossed.getX();
double B = crossed.getY();
double C = crossed.getZ();
double x0 = this->point_.getX();
double y0 = this->point_.getY();
double z0 = this->point_.getZ();
double Vx = ray.getDirection().getX();
double Vy = ray.getDirection().getY();
double Vz = ray.getDirection().getZ();
double Px = ray.getPoint().getX();
double Py = ray.getPoint().getY();
double Pz = ray.getPoint().getZ();
double num = - A * Px + A * x0
- B * Py + B * y0
- C * Pz + C * z0;
double denum = A * Vx + B * Vy + C * Vz;
if (denum == 0)
return std::nullopt;
double t = num / denum;
return Vector3(Vx * t + Px, Vy * t + Py, Vz * t + Pz);
}
Vector3 Plane::normal(Vector3 point) {
(void) point;
//return (this->b_ - this->a_).cross(this->c_ - this->a_);
return this->normal_;
} | true |
c7d16131f99de62797da587ba991b09e1a05b82d | C++ | leagues58/VigenereBreaker | /findKeyLetter.h | UTF-8 | 617 | 2.65625 | 3 | [] | no_license | /**************************
Project 1, CSCE 557
Author: Eric Reeves
Last Modified: 1/25/2016
Header file for findKeyLetter.cpp
*************************/
#ifndef FINDKEYLETTER_H
#define FINDKEYLETTER_H
#include <iostream>
#include <vector>
#include <string>
#include "printVector.h"
#include "translateLetters.h"
using namespace std;
vector<char> findKeyLetter(int, vector<char> &characters);
float dotProduct(vector<float> standard, vector<float> letterCount);
vector<float> shiftVector (vector<float> &letterCount);
int innerSum(vector<float> &letterCount);
const int ALPHABETSIZE = 26;
#endif // FINDKEYLETTER_H | true |
18928c2906b3c83b660e6b2b2f2c4825362b513a | C++ | onievui/Fire-Watch | /Game/Arrow.cpp | SHIFT_JIS | 3,159 | 2.890625 | 3 | [] | no_license | #include "Arrow.h"
#include "ResourceManager.h"
#include "RenderManager.h"
#include "Map.h"
/// <summary>
/// RXgN^
/// </summary>
/// <param name="_pos">oW</param>
/// <param name="_angle">is</param>
Arrow::Arrow(const Vector2& _pos, const float _angle)
: state(ArrowState::NORMAL_ARROW)
, pos(_pos)
, vel(Vector2::createWithAngleNorm(_angle, 12))
, angle(_angle)
, textureIndex()
, animeCount()
, collider(RectRotateCollider(&pos, { 0,0 }, &vel, 36, 6, &angle))
, texture(ResourceManager::getIns()->getTexture(TextureID::TEXTURE_ARROW)) {
}
/// <summary>
/// XV
/// </summary>
void Arrow::update() {
pos += vel;
//RďԂȂAj[Vs
if (state == ArrowState::FIRE_ARROW) {
++animeCount;
textureIndex = (animeCount % 30 < 15 ? 1 : 2);
}
//Xe[Wɂ邩̔
insideAreaCheck();
}
/// <summary>
/// `揈
/// </summary>
void Arrow::draw() {
//jĂȂΕ`悷
if (state != ArrowState::DESTROYED) {
RenderManager* render_manager = RenderManager::getIns();
render_manager->drawRotaGraphF(pos.x, pos.y, 1.5f, angle + PI * 3 / 4, texture->getResource(textureIndex), true);
//RďԂȂ疾o
if (state == ArrowState::FIRE_ARROW) {
render_manager->changeScreen(ScreenType::LightAlphaScreen);
SetDrawBlendMode(DX_BLENDMODE_ADD, 255);
render_manager->drawRotaGraphF(pos.x, pos.y, 0.8f, 0.0f,
ResourceManager::getIns()->getTexture(TextureID::TEXTURE_LIGHT1)->getResource(), true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
render_manager->changeScreen(ScreenType::MapScreen);
}
}
}
/// <summary>
/// RC_[̎擾
/// </summary>
/// <returns>
/// RC_[
/// </returns>
RectRotateCollider* Arrow::getCollider() {
return &collider;
}
/// <summary>
/// U͂̎擾
/// </summary>
/// <returns></returns>
int Arrow::getPower() {
//ʏԂȂ1_[W
if (state == ArrowState::NORMAL_ARROW) {
return 1;
}
//RďԂȂ1_[W
else if (state == ArrowState::FIRE_ARROW) {
return 1;
}
return 0;
}
/// <summary>
/// cĂ邩ǂ̊mF
/// </summary>
/// <returns>
/// cĂ邩ǂ
/// </returns>
bool Arrow::isAlive() {
return (state != ArrowState::DESTROYED ? true : false);
}
/// <summary>
/// RďԂǂ̎擾
/// </summary>
/// <returns>
/// RďԂǂ
/// </returns>
bool Arrow::isFire() {
return state == ArrowState::FIRE_ARROW;
}
/// <summary>
/// GƏՓ˂̏
/// </summary>
void Arrow::hitEnemy() {
state = ArrowState::DESTROYED;
}
/// <summary>
/// ƏՓ˂̏
/// </summary>
void Arrow::hitFire() {
if (state == ArrowState::NORMAL_ARROW) {
state = ArrowState::FIRE_ARROW;
}
}
/// <summary>
/// Xe[Wɂ邩̔
/// </summary>
void Arrow::insideAreaCheck() {
//Xe[WOȂ
if (pos.x < 0.0f || pos.x > Map::GRID_COLS*Map::DEFAULT_GRID_SIZE ||
pos.y < 0.0f || pos.y > Map::GRID_ROWS*Map::DEFAULT_GRID_SIZE) {
state = ArrowState::DESTROYED;
}
}
| true |
a5d6cdc5fad898eef2c60d5094fb4a911d7fd35d | C++ | A-World/CPPConceptsInterviewPreparation | /boqian/advancedC++/advanced_023.cpp | UTF-8 | 1,445 | 3.9375 | 4 | [] | no_license | /*
Introduction to C++ :
Video : Advanced C++ Define Implicit Type Conversion
Category C Tryout with two classes.
// This program will not compile.
*/
#include <iostream>
#include <string>
using namespace std;
// Forward declaration.
class Two ;
class One
{
public :
One() {}
One (Two t);
operator Two ();
};
class Two
{
public:
Two () {}
Two (One o);
operator One();
};
// Function Definations
One :: One (Two t)
{
cout << "One :: One (Two t)" <<endl;
}
One :: operator Two()
{
Two t;
cout << "One :: operator Two()"<<endl;
return t;
}
Two :: Two(One o)
{
cout << "Two :: Two(One o)"<<endl;
}
Two :: operator One()
{
One o;
cout <<"Two :: operator One()"<<endl;
return o;
}
int main()
{
One o1;
One o2;
One o3;
Two t1;
Two t2;
Two t3;
One ot = t1;
//Two to = o1;
// As expected, I got comilation error on line One ot = t1; as call to function are ambiguous.
// Two :: operator One()
// One :: One (Two t)
// So there are two functions that can be used.
// So as per design principle discussed in previous example, we shall only practice one converstion methods.
// I'll recommend to use method 1, i.e. Convert other type object into your type.
return 0;
} | true |
4d042225af762a80b44df2b70b7b532a66e62481 | C++ | Jiwangreal/learn_cpp_with_me | /P75/Calculator/Exception.h | GB18030 | 2,335 | 3.4375 | 3 | [] | no_license | #ifndef _EXCEPTION_H_
#define _EXCEPTION_H_
#include <exception>
#include <string>
//̳exception
class Exception : public std:exception
{
public:
//Ϊ˷ֹת
explicit expException(const char* message) : message_(message)
{
FillStackTrace();
}
explicit expException(const std::string& message) : message_(message)
{
FillStackTrace();
}
//׳쳣throw()ʾ׳쳣
virtual ~Exception() throw()
{
}
//whatǻ麯︲wahtҲ׳쳣
virtual const char* what() const throw();
const char* StackTrace() const throw();
private:
void FillStackTrace();
std:string message_;
std::string stackTrace_;//ڷ쳣ĵطջϢ浽ַstackTrace_
//ڹthrow SyntaxError("Not a valid expression");ʱͰѵǰĵջϢջд뵽stackTrace_
};
//
class SyntaxError : public Exception
{
public:
explicit SyntaxError(const char* message) : Exception(message)
{
}
//ӹ캯ҲҪ
explicit SyntaxError(const std::string& message) : Exception(message)
{
}
virtual ~SyntaxError() throw()
{
}
//ﲻٸwhat
};
//DZ־ãûõĴ
class FileStreamError : public Exception
{
public:
explicit FileStreamError(const char* message) : Exception(message)
{
}
//ӹ캯ҲҪ
explicit FileStreamError(const std::string& message) : Exception(message)
{
}
virtual ~FileStreamError() throw()
{
}
//ﲻٸwhat
};
// class CheckNumberError : public Exception
// {
// public:
// explicit CheckNumberError(const char* message) : Exception(message)
// {
// }
// //ӹ캯ҲҪ
// explicit CheckNumberError(const std::string& message) : Exception(message)
// {
// }
// virtual ~CheckNumberError() throw()
// {
// }
// //ﲻٸwhat
// };
#endif //_EXCEPTION_H_ | true |
03728e789087ef63064e720ca5f9fef1e964c7e3 | C++ | imharsh94/ALGO-DS | /lcs.cpp | UTF-8 | 520 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
string s,t;
int lcs(int m,int n)
{
int l[m+1][n+1];
for(int i=0; i<=m; i++)
{
for(int j=0; j<=n; j++)
{
if(i==0 || j==0)
l[i][j] = 0;
else if(s[i-1] == t[j-1])
l[i][j] = l[i-1][j-1]+1;
else
l[i][j] = max(l[i][j-1],l[i-1][j]);
}
}
return l[m][n];
}
int main()
{
cin>>s;
t = reverse(s.begin(), s.end());
int m = s.length();
int n = t.length();
cout<< lcs(m,n)<<endl;
return 0;
}
| true |
736576a107fec0786f8c1eca536d8bab85216d24 | C++ | Rubentxu/Ilargia | /libIlargia/include/core/logicbrick/sensor/Sensor.h | UTF-8 | 1,077 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef ILARGIA_SENSOR_H
#define ILARGIA_SENSOR_H
#include <core/logicbrick/LogicBrick.h>
#include "mathfu/vector.h">
namespace Ilargia {
enum class Pulse { PM_IDLE, PM_TRUE, PM_FALSE };
enum class TapMode { TAP_OUT, TAP_IN };
struct Sensor : LogicBrick {
// Config Values
float frequency = 0;
bool invert = false;
bool tap = false;
Pulse pulse = Pulse::PM_IDLE;
// Values
float tick = 0;
bool positive = false;
bool firstExec = true;
bool initialized = false;
TapMode firstTap = TapMode::TAP_IN;
TapMode lastTap = TapMode::TAP_OUT;
};
enum class MouseEvent {
MOUSEMOTION = 0x400, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEWHEEL
};
template <typename Entity>
struct MouseSensor : Sensor<MouseSensor> {
MouseEvent mouseEvent = MouseEvent::MOUSEMOTION;
Entity target;
MouseEvent mouseEventSignal;
mathfu::Vector<float, 2> positionSignal;
int amountScrollSignal;
};
}
#endif //ILARGIA_SENSOR_H
| true |
9cedbc07ce12d143a8c34e082d4251d927ec2456 | C++ | XB32Z/motor_controllers | /include/motor_controllers/motor/dc_motor_factory.h | UTF-8 | 4,386 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive |
/**
* @file dc_motor_factory.h
* @author Pierre Venet
* @brief Declaration of a helper class to construct DC motors from pins
* directly.
* @version 0.1
* @date 2021-05-09
*
* @copyright Copyright (c) 2021
*
*/
#pragma once
#include <motor_controllers/communication/channel_builder.h>
#include <motor_controllers/communication/i_communication_interface.h>
#include <motor_controllers/motor/dc_motor.h>
#include <memory> // std::move, std::make_unique, std::unique_ptr
#include <optional> // std::optional
#include <vector> // std::vector
namespace motor_controllers {
namespace motor {
/**
* @brief Helper class to construct DCMotor from pin numbers
*
* As it is always the same process to instanciate DCMotors, this class wrapps
* the code such that it is easier to use.
*
* @tparam CommunicationInterface
* @tparam PWMChannelConfiguration
* @tparam BinaryChannelConfiguration
*/
template <class CommunicationInterface, class PWMChannelConfiguration,
class BinaryChannelConfiguration>
class DCMotorFactory {
public:
struct Configuration {
// Motor PWM and direction channel configuration
PWMChannelConfiguration pwmChannelConfiguration;
double pwmFrequency = 20000;
std::vector<BinaryChannelConfiguration> directionChannelsConfiguration;
// Encoder binary channels configurations
BinaryChannelConfiguration encoderChannelAConfiguration;
std::optional<BinaryChannelConfiguration> encoderChannelBConfiguration;
int encoderResolution;
double encoderSamplingFrequency = 500;
// Direction
std::vector<communication::BinarySignal> forwardConfiguration;
std::vector<communication::BinarySignal> backwardConfiguration;
std::vector<communication::BinarySignal> stopConfiguration;
// Motor constants
double minDutyCycle;
double maxSpeed;
// Controller constants
double Kp = 1.0, Ki = 0.0, Kd = 0.0;
std::chrono::microseconds dt = std::chrono::microseconds(10);
};
public:
DCMotorFactory(std::unique_ptr<CommunicationInterface> communicationInterface)
: communicationInterface_(std::move(communicationInterface)) {}
~DCMotorFactory() = default;
DCMotorFactory(const DCMotorFactory&) = delete;
DCMotorFactory& operator=(const DCMotorFactory&) = delete;
public:
DCMotor::Ref createMotor(const Configuration& configuration) {
DCMotor::Configuration motorConf = DCMotor::Configuration();
// Motor channels
motorConf.pwmChannel = this->communicationInterface_->configureChannel(
configuration.pwmChannelConfiguration);
motorConf.pwmFrequency = configuration.pwmFrequency;
for (const auto& channelConf :
configuration.directionChannelsConfiguration) {
motorConf.directionControl.emplace_back(
this->communicationInterface_->configureChannel(channelConf));
}
// Encoder
auto encoderChannelA = this->communicationInterface_->configureChannel(
configuration.encoderChannelAConfiguration);
if (configuration.encoderChannelBConfiguration) {
// Quadrature encoder
auto encoderChannelB = this->communicationInterface_->configureChannel(
*configuration.encoderChannelBConfiguration);
motorConf.encoder = std::make_unique<encoder::Encoder>(
std::move(encoderChannelA), std::move(encoderChannelB),
configuration.encoderResolution);
} else {
// Single encoder
motorConf.encoder = std::make_unique<encoder::Encoder>(
std::move(encoderChannelA), configuration.encoderResolution);
}
motorConf.forwardConfiguration = configuration.forwardConfiguration;
motorConf.backwardConfiguration = configuration.backwardConfiguration;
motorConf.stopConfiguration = configuration.stopConfiguration;
// Motor constants
motorConf.minDutyCycle = configuration.minDutyCycle;
motorConf.maxSpeed = configuration.maxSpeed;
// Controller constants
motorConf.Kp = configuration.Kp;
motorConf.Ki = configuration.Ki;
motorConf.Kd = configuration.Kd;
return std::unique_ptr<DCMotor>(new DCMotor(motorConf));
}
void startCommunication() { this->communicationInterface_->start(); }
void stopCommunication() { this->communicationInterface_->stop(); }
private:
std::unique_ptr<CommunicationInterface> communicationInterface_;
};
} // namespace motor
} // namespace motor_controllers
| true |
e7b8f2a93e840dcd958a08db76a5478cb98c62c8 | C++ | Prichman/galaxy_game | /src/actor.cpp | UTF-8 | 855 | 2.96875 | 3 | [] | no_license | #include "actor.h"
#include <iostream>
Actor::Actor()
: speed_(0, 0) {}
Actor::~Actor() {
}
void Actor::LoadSprite(const std::string &path) {
if(!texture_.loadFromFile(path)) {
std::cout << "Can't load texture from \"" << path << "\"" << std::endl;
return;
}
sprite_.setTexture(texture_);
}
void Actor::GameUpdate() {
sprite_.move(speed_.x, speed_.y);
}
void Actor::SetSpeed(float x, float y) {
speed_.x = x;
speed_.y = y;
}
sf::Vector2f Actor::GetSpeed() const {
return speed_;
}
void Actor::SetPos(float x, float y) {
sprite_.setPosition(x, y);
}
sf::Vector2f Actor::GetPos() const {
return sprite_.getPosition();
}
sf::FloatRect Actor::bounding_rect() const {
return sprite_.getGlobalBounds();
}
void Actor::draw(sf::RenderTarget &target, sf::RenderStates states) const {
target.draw(sprite_, states);
}
| true |
f0b8a135dbbdcc2e24675315dee455bc3c3b15ac | C++ | wowkin2/test-tasks-summer-2012 | /2/pr3.cpp | WINDOWS-1251 | 3,926 | 3.1875 | 3 | [] | no_license | /**
* @file pr3.cpp
* @brief Task2
* @task 3.
: < >, <>, < >.
,
. .
* @author Volodymyr Spodaryk
* @email spodaryk.volodymyr@i.ua
* ----------------------------------------------------------------------*/
#include <vcl.h>
//#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
#define NUMBER 3 //Number of Results
struct Result{
int Month;
int Plan;
int Fact;
};
//------------------------- prototype functions -----------------------//
/**
* @brief Fill fields in struct
* @param[in] Array to fill
* @return void
*/
void Fill(Result **p);
/**
* @brief Show data in array
* @param[in] Array to show
* @param[in] Message before array
* @return void
*/
void Show(Result **p,const char *c);
/**
* @brief Sort Results by Field
* @param[in] Pointer source
* @param[in] field follow which should be sorting
* @post array of Results is sorted
* @return void
*/
void Sorting(Result **p);
/**
* @brief Print full name of month by number
* @param[in] Number of month
* @return void
*/
void GetMonth(int a);
//--------------------------- main function ---------------------------//
int main(void)
{
Result *x[NUMBER];
cout << "Hello, this is a Result-manager.\n"
<< "Input integer coords of " << NUMBER
<< " Result (month number, plan, factically production): \n";
Fill(x);
clrscr();
Show(x, "Inputed data:\n");
Sorting(x);
cout << endl;
Show(x, "Sorted data:\n");
delete []x;
// cin.get();
getch();
return 0;
}
//------------------------ realization of prototype ------------------//
void Fill(Result **p)
{
for(int i=0;i<NUMBER;i++)
{
cout << "[" << i+1 << "]: ";
p[i] = (Result*) malloc (sizeof(Result));
cin >> p[i]->Month >> p[i]->Plan >> p[i]->Fact;
}
}
void Show(Result **p,const char *c)
{
cout << c;
for(int i=0; i<NUMBER; i++)
{
GetMonth(p[i]->Month);
cout << p[i]->Plan << "\t" << p[i]->Fact << endl;
}
}
void Sorting(Result **p)
{
Result *tmp;
for(int i=0; i < NUMBER; i++)
for(int j=i+1; j < NUMBER; j++)
{
if(p[i]->Fact - p[i]->Plan > p[j]->Fact - p[j]->Plan)
{
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
return;
}
void GetMonth(int a)
{
switch(a)
{
case 1: cout << "January \t"; break;
case 2: cout << "February \t"; break;
case 3: cout << "March \t"; break;
case 4: cout << "April \t"; break;
case 5: cout << "May \t"; break;
case 6: cout << "June \t"; break;
case 7: cout << "July \t"; break;
case 8: cout << "August \t"; break;
case 9: cout << "September\t"; break;
case 10: cout << "October \t"; break;
case 11: cout << "November\t"; break;
case 12: cout << "December\t"; break;
default: cout << "No month\t";
}
}
| true |
81e7134a25ce937f4f8d5008eb6f1f9c253fbddd | C++ | ItaiOz/Chicken-Invaders | /source/Board.cpp | UTF-8 | 953 | 3.109375 | 3 | [] | no_license | #include "Board.h"
Board::Board()
{
m_file.open("levels.txt");
if (!m_file.is_open())
{
throw std::runtime_error("Can't load file");
}
// test file open
// get current line
for (std::string name; getline(m_file, name, '\n');)
{
m_levels.push_back(name);
}
m_file.close();
getnewline();
}
Board& Board::instance()
{
static Board instance;
return instance;
}
void Board::getnewline()
{
if (m_levels.empty())
return;
int name;
std::string T;
T = m_levels.front();
m_levels.pop_front();
std::stringstream geek(T);
while (geek >> name)m_line.push_back(name);
// for (auto& i : m_line)
// std::cout << i << "\n";
}
//returns database sizes
int Board::getData()
{
int i;
i = m_line.front();
m_line.pop_front();
// std::cout << i << "\n";
return i;
} | true |
bda43319ef3754d0615d8e750aef22d72bd0d700 | C++ | dguest/susy-analysis | /analysis/src/BtagBuffer.cxx | UTF-8 | 1,063 | 2.625 | 3 | [] | no_license | #include "BtagBuffer.hh"
#include "TTree.h"
#include <stdexcept>
BtagBuffer::BtagBuffer(TTree* tree, std::string branch):
m_has_err(false)
{
set(tree, branch, &m_scale_factor);
std::string err_branch = branch + "_err";
if (tree->GetBranch(err_branch.c_str())) {
set(tree, branch + "_err", &m_scale_factor_err);
m_has_err = true;
}
}
double BtagBuffer::sf(TagSF tag_sf) const {
if (tag_sf == TagSF::NOMINAL) return m_scale_factor;
if (!m_has_err) throw std::runtime_error("no tagging SF error provided");
switch (tag_sf) {
case TagSF::UP: return m_scale_factor + m_scale_factor_err;
case TagSF::DOWN: return m_scale_factor - m_scale_factor_err;
default: throw std::logic_error("soemthign wrong in " __FILE__);
}
}
void BtagBuffer::set(TTree* tree, std::string branch, void* address) {
unsigned ret_code;
tree->SetBranchStatus(branch.c_str(), 1, &ret_code);
if (ret_code != 1) {
throw std::runtime_error("branch: " + branch +
", where the fuck is it?");
}
tree->SetBranchAddress(branch.c_str(), address);
}
| true |
c61370966bfd0fd4a4254f5c529bee16d7f6d705 | C++ | TheGupta2012/Data-Structures | /Stacks, Queues, Linked Lists/qlinks.cpp | UTF-8 | 2,039 | 3.640625 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
int data;
struct node* next;
};
typedef struct node nd;
nd* rear;
nd* front;
class Q
{
public: void insert(int item)
{
nd* temp;
temp=new node;
temp->data=item;
temp->next=NULL;
//important...if you check the condition that rear == front then it will give an error why?
//as when you have inserted the first element , you still would have front==rear and not
//just in the emty queue case...
if(rear==NULL)
{rear=temp;
front=rear;}
else
{
rear->next=temp;
rear=temp;
}
}
int del()
{
if(front==NULL)
return -1;
else
{
int dat=front->data;
if(front==rear)
{front=NULL;
rear=NULL;
return dat;}
else
{
front=front->next;
return dat;
}
}
}
void disp()
{
if(front==NULL)
cout<<"\nEmpty queue...";
else
{
nd* temp;
temp=front;
cout<<"\nFront element:"<<front->data;
cout<<"\nRear element:"<<rear->data;
cout<<"\nList:";
while(temp!=NULL)
{cout<<temp->data<<":";
temp=temp->next;}
}
}
};
int main()
{
Q q;
cout<<"\n\t\t\t\t\t\tQUEUE USING LINKED LIST\nInsert element-(1)\nDelete element-(2)\nView queue-(3)\nExit-(-1)";
int choice,it;
while (true)
{ cout<<"\nEnter choice:";
cin>>choice;
if(choice!=-1)
{
switch(choice)
{
case 1: cout<<"Enter item:";
cin>>it;
q.insert(it);
break;
case 2: int b;
b = q.del();
if(b!=-1)
{cout<<"Element deleted.\nUpdated queue:\n";
q.disp();}
else
cout<<"\nEmpty queue.";
break;
case 3: cout<<"QUEUE is:-";
q.disp();
break;
default: cout<<"invalid enter again.";
}
}
else
{
cout<<"Okay.";
break;
}
}
return 0;
}
| true |
7b21bc0559f9707f4a0e204a4078cd96fa72dc53 | C++ | SuperLiuYinXin/offer | /数据流中的中位数.cpp | UTF-8 | 1,742 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <queue>
/*****************************/
/* filename: 数据流中的中位数.cpp */
/* abstract:
如何得到一个数据流中的中位数?
如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 */
/* author : liuyinxin */
/* time: 2019-02-20 17:26:43 */
/*****************************/
/*****************************/
using namespace std;
// 思路
// 维护一个最大最和最小堆
// 大于的放在一个队,小于的放在一个堆
class Solution {
private:
// 数据类型 底层容器 比较函数
priority_queue<int, vector<int>, less<int>> p;
priority_queue<int, vector<int>, greater<int>> q;
public:
/**
* 如果小堆为空,
* 最小堆放的是中位数后面的
* 最大堆放的是中位数前面的
*/
void Insert(int num)
{
if (p.empty() || num <= p.top())
p.push(num);
else
q.push(num);
// 这样保证p 比q只可能多一个
if (p.size() == q.size() + 2) {
// 把最小的放入最大堆中
q.push(p.top());
p.pop();
}
// 这样就相等了
if (p.size() + 1 == q.size()) {
p.push(q.top());
q.pop();
}
}
double GetMedian()
{
return p.size() == q.size() ? (p.top() + q.top()) / 2.0 : p.top();
}
};
using namespace std;
int main(){
return 0;
}
| true |
a030d12c4b8d6310cdecb4e7f973eb6ee1517174 | C++ | swapnilpathak14/C--VS-CODE | /MY C++ JOURNEY/SearchArr.cpp | UTF-8 | 398 | 2.984375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int linearsearch(int arr[],int n, int key){
for(int x=0;x<n;x++){
if(arr[x]==key){
return x;
}
}
return -1;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int x=0;x<n;x++){
cin>>arr[x];
}
int key;
cin>>key;
cout << linearsearch(arr, n, key) << endl;
return 0;
} | true |
42c06e9bc85ec6aac3237d5bb2e4516a2ed560d9 | C++ | ViktorYastrebov/practice | /practice_cmake_repo/design_patterns/syb_visitor/Syb/TypeAlias.h | UTF-8 | 6,749 | 2.828125 | 3 | [] | no_license | /**
\brief Implement functionality for aliasing types for overloading.
It's needed then we need to redefine behavior of some generic function
for some particular set of fields but not types.
So the user can make type alias and then use it for specializing templates.
*/
#ifndef SYB_TYPE_ALIAS_H
#define SYB_TYPE_ALIAS_H
#if 0
#include "Syb.h"
#include "HistList.h"
#else
#include "Syb.h"
#include "HistList.h"
#endif
#include <boost/call_traits.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/utility/value_init.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
//#include "misc/getenv.h"
#include <list>
namespace qx {
namespace syb {
/**
\brief Tag for marking any class as an alias
*/
struct NewTypeTag{};
/**
\brief Actual type alias implementation.
The aliases implementation uses Curiously Recurring Template
Pattern idiom. So \a AliasT should be child of NewType<AliasT,..>.
By default the value is initialized using boost::value_initialized.
\tparam AliasT new name for a type
\tparam T old name for a type
\tparam EnableT boost::enable_if helper
*/
template<typename AliasT,typename T, typename EnableT=void>
struct NewType : public NewTypeTag {
inline NewType() : val_(boost::value_initialized<T>().data()) {}
inline explicit NewType(T const& v) : val_(v) {}
/// \brief setter
inline void val(T const& v) { val_ = v; }
/// \brief getter
inline T const& val() const { return val_; }
/// \brief reference getter
inline T& val() { return val_; }
// inline operator T() const { return val_; }
template<typename GmapFunT>
inline static void gmap(AliasT& p, GmapFunT const& s) {
s(p.val());
}
template<typename GmapFunT>
inline static void gmap(const AliasT& p, GmapFunT const& s) {
s(p.val());
}
private:
T val_;
};
template<typename T, typename EnableT=void>
struct UnAlias:Ret<T> {};
/** \brief The function gets alias value if it's an alias or simply
returns its parameter if it's not.
*/
template<typename T>
inline typename boost::disable_if<
boost::is_base_of<NewTypeTag,T>
,T
>::type const&
unAlias(T const& v) { return v; }
template<typename T>
inline typename boost::disable_if<
boost::is_base_of<NewTypeTag,T>
,T
>::type&
unAlias(T& v) { return v; }
template<typename T>
struct UnAlias<T,typename boost::enable_if<
boost::is_base_of<NewTypeTag,T>
>::type>:Ret<typename boost::remove_const<typename T::ValueType>::type>{};
template<typename T>
inline typename boost::enable_if<
boost::is_base_of<NewTypeTag,T>
,typename T::ValueType
>::type const&
unAlias(T const& v) { return v.val(); }
template<typename T>
inline typename boost::enable_if<
boost::is_base_of<NewTypeTag,T>
,typename T::ValueType
>::type&
unAlias(T& v) { return v.val(); }
/**
\brief Similar to \a NewType but stores reference of aliased type
rather than value itself
The class is mostly needed for adjusting behaviour of classes that
is impossible to change. Because it's some 3rd party or it have
some fragile interface.
*/
template<typename AliasT, typename T, typename EnableT=void>
struct NewTypeRef : NewTypeTag {
inline explicit NewTypeRef(T& v):val_(v){}
inline T& val() const { return val_; }
private:
T& val_;
template<typename GmapFunT>
inline static void gmap(AliasT& p, GmapFunT const& s) {
s(p.val());
}
template<typename GmapFunT>
inline static void gmap(const AliasT& p, GmapFunT const& s) {
s(p.val());
}
};
/**
\brief Helper function for implicit aliased type setting.
*/
template<typename AliasT,typename T>
inline NewTypeRef<AliasT,T> alias(T& v) {
return NewTypeRef<AliasT,T>(v);
}
/**
\brief \a NewTypeRef should be cleared out
*/
template<typename AliasT,typename T, typename EnableT>
struct CleanType<NewTypeRef<AliasT,T>, EnableT>:Ret<T>{};
/**
\brief \a NewTypeRef should be cleared out
*/
template<typename AliasT,typename T>
inline T& cleanType(NewTypeRef<AliasT,T> const& v) { return v.val(); }
template<typename AliasT,typename T, typename EnableT>
struct TypeName<NewTypeRef<AliasT,T>, EnableT> {
inline static std::string value() {
return TypeName<AliasT>::value();
}
};
template <typename T>
typename boost::enable_if<
boost::is_base_of<NewTypeTag,typename boost::remove_const<T>::type>
, bool
>::type
operator<(const T& a, const T& b)
{
return a.val() < b.val();
}
}
}
/**
\brief The macros defines all a new class this the name as the alias,
and needed helper functions.
\param n Name of an alias
\param v Type that the new alias will have
*/
#define NEWTYPE(n,v) \
struct n:syb::NewType<n,v > \
{ \
inline n(){} \
inline n(v const& val) : syb::NewType<n,v >(val){} \
typedef v ValueType; \
typedef void spine_tag_t; \
static std::string sybTypeName() { return #n; } \
};
#define NEWTYPE_WITH_DEFAULT(n,v,d) \
struct n:syb::NewType<n,v > \
{ \
inline n() : syb::NewType<n,v >(d){} \
inline n(v const& val) : syb::NewType<n,v >(val){} \
typedef v ValueType; \
typedef void spine_tag_t; \
static std::string sybTypeName() { return #n; } \
};
#define NEWTYPE_LAZY_LOAD(n,v,o) \
struct n:syb::NewTypeLazyLoad<n,v,o > \
{ \
inline n(){} \
inline n(v const& val) : syb::NewTypeLazyLoad<n,v,o >(val){} \
typedef v ValueType; \
typedef void spine_tag_t; \
static std::string sybTypeName() { return #n; } \
};
#endif
| true |
c4c3c5514341a42458788c397c8de876008b665c | C++ | Lammatian/AdventOfCode | /2020/24/sol.cpp | UTF-8 | 3,153 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <set>
#include "util.h"
using namespace std;
// https://www.redblobgames.com/grids/hexagons/
// Cube coordinates
struct HexDir {
int x, y, z;
};
bool operator<(const HexDir& h1, const HexDir& h2) {
return h1.x < h2.x
|| (h1.x == h2.x && h1.y < h2.y)
|| (h1.x == h2.x && h1.y == h2.y && h1.z < h2.z);
}
HexDir get_hex(const string& directions) {
HexDir result {0, 0, 0};
char last = ' ';
for (auto& c: directions) {
if (c == 'e') {
if (last == ' ') {
result.x++;
result.y--;
} else if (last == 's') {
result.z++;
result.y--;
} else {
result.x++;
result.z--;
}
last = ' ';
} else if (c == 'w') {
if (last == ' ') {
result.x--;
result.y++;
} else if (last == 's') {
result.x--;
result.z++;
} else {
result.z--;
result.y++;
}
last = ' ';
} else if (c == 's') {
last = 's';
} else {
last = 'n';
}
}
return result;
}
ll sol1(vector<string>& lines) {
set<HexDir> flipped;
for (auto& line: lines) {
HexDir cur = get_hex(line);
if (flipped.find(cur) == flipped.end()) {
flipped.emplace(cur);
} else {
flipped.erase(cur);
}
}
return flipped.size();
}
vector<HexDir> neighbours(HexDir h) {
vector<HexDir> result;
result.push_back({h.x + 1, h.y, h.z - 1});
result.push_back({h.x + 1, h.y - 1, h.z});
result.push_back({h.x, h.y + 1, h.z - 1});
result.push_back({h.x, h.y - 1, h.z + 1});
result.push_back({h.x - 1, h.y, h.z + 1});
result.push_back({h.x - 1, h.y + 1, h.z});
return result;
}
set<HexDir> evolve(set<HexDir>& state) {
set<HexDir> evolution;
map<HexDir, int> ncount;
for (auto& h: state) {
for (auto& nh: neighbours(h)) {
ncount[nh]++;
}
}
for (auto& entry: ncount) {
HexDir h = entry.first;
int count = entry.second;
if (state.find(h) != state.end() && (count == 1 || count == 2)) {
evolution.emplace(h);
} else if (state.find(h) == state.end() && count == 2) {
evolution.emplace(h);
}
}
return evolution;
}
ll sol2(vector<string>& lines) {
set<HexDir> flipped;
for (auto& line: lines) {
HexDir cur = get_hex(line);
if (flipped.find(cur) == flipped.end()) {
flipped.emplace(cur);
} else {
flipped.erase(cur);
}
}
for (int i = 0; i < 100; ++i) {
flipped = evolve(flipped);
}
return flipped.size();
}
int main(int argc, char** argv) {
string filename = argc > 1 ? argv[1] : "input.txt";
ifstream f(filename);
auto lines = util::readlines(f);
cout << sol1(lines) << endl;
cout << sol2(lines) << endl;
return 0;
}
| true |
a92d75ce499ce69d6110a6b80ba9ad0379328e2b | C++ | rlj1202/problemsolving | /baekjoon/1704_fish_cake_tycoon/main.cpp | UTF-8 | 308 | 2.59375 | 3 | [] | no_license | #include <iostream>
int M, N;
int grid[20][20];
int main() {
scanf("%d %d", &M, &N);
for (int m = 0; m < M; m++) {
for (int n = 0; n < N; n++) {
scanf("%d", &grid[m][n]);
}
}
for (int m = 0; m < M; m++) {
for (int n = 0; n < N; n++) {
printf("%d", 0);
}
printf("\n");
}
return 0;
}
| true |
efef669b29c6040a4e8259b4436ed39ecf67b297 | C++ | f-tischler/ParallelSystems | /Exercise10/mmul/summa_seq.h | UTF-8 | 8,011 | 2.6875 | 3 | [] | no_license | #ifndef SUMMA_SEQ_H
#define SUMMA_SEQ_H
#include "matrix.h"
#include "gsl/gsl"
#include <iostream>
#include "naive_seq.h"
#include <iomanip>
#include <cmath>
struct summa_sequential { size_t blocks = 4; bool print = false; };
template<typename T>
using block_t = std::array<matrix<T>, 3>;
template<typename T>
using block_grid_t = std::vector<std::vector<block_t<T>>>;
template<typename T>
matrix<T> compute_outer_product(
const matrix<T>& a,
const typename matrix<T>::size_type column_index,
const matrix<T>& b,
const typename matrix<T>::size_type row_index);
template<typename T>
void print_blocks(const block_grid_t<T>& blocks);
template<typename T>
void update_blocks(block_grid_t<T>& blocks, const size_t k);
template<typename T>
void update_block(std::array<matrix<T>, 3>& block, size_t k);
template<typename T>
void copy_col(matrix<T>& dest, const matrix<T>& src, size_t column);
template<typename T>
void copy_row(matrix<T>& dest, const matrix<T>& src, size_t row);
inline size_t get_num_blocks_per_dim(const size_t n, const size_t num_procs);
template<typename T>
matrix<T> multiply(const matrix<T>& a, const matrix<T>& b, const summa_sequential opt)
{
Expects(a.n() == b.n());
const auto n = a.n();
const auto blocks_per_dim = get_num_blocks_per_dim(n, opt.blocks);
if (blocks_per_dim == 1)
{
return multiply(a, b, naive_sequential());
}
const auto block_size = n / blocks_per_dim;
block_grid_t<T> blocks(blocks_per_dim);
for (auto& row : blocks)
{
row.resize(blocks_per_dim,
{
matrix<T>(block_size),
matrix<T>(block_size),
matrix<T>(block_size, 0)
});
}
// build blocks
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
const auto block_y = i / block_size;
const auto block_x = j / block_size;
auto& block = blocks[block_y][block_x];
const auto block_offset_x = block_x * block_size;
const auto local_x = j - block_offset_x;
const auto block_offset_y = block_y * block_size;
const auto local_y = i - block_offset_y;
block[0](local_y, local_x) = a(i, j);
block[1](local_y, local_x) = b(i, j);
}
}
if(opt.print) print_blocks(blocks);
// assign initial data distribution
auto old_blocks = blocks;
for (auto y = gsl::narrow<long>(blocks_per_dim - 1); y >= 0; --y)
{
for (auto x = gsl::narrow<long>(blocks_per_dim - 1); x >= 0; --x)
{
const auto src_a_y = y % blocks_per_dim;
const auto src_a_x = (-x - y) % blocks_per_dim;
const auto src_b_y = (-x - y) % blocks_per_dim;
const auto src_b_x = x % blocks_per_dim;
blocks[y][x][0] = old_blocks[src_a_y][src_a_x][0];
blocks[y][x][1] = old_blocks[src_b_y][src_b_x][1];
}
}
// main loop
if (opt.print) print_blocks(blocks);
for (size_t k = 0; k < a.n(); ++k)
{
// update local block
update_blocks(blocks, k % block_size);
// send/receive new rows/columns
old_blocks = blocks;
for (auto y = gsl::narrow<long>(blocks_per_dim - 1); y >= 0; --y)
{
for (auto x = gsl::narrow<long>(blocks_per_dim - 1); x >= 0; --x)
{
auto& block = blocks[y][x];
auto& block_a = block[0];
auto& block_b = block[1];
const auto neighbour_x = x == 0
? blocks_per_dim - 1
: x - 1;
const auto neighbour_y = y == 0
? blocks_per_dim - 1
: y - 1;
copy_row(block_b, old_blocks[neighbour_y][x][1], k % block_size);
copy_col(block_a, old_blocks[y][neighbour_x][0], k % block_size);
}
}
if (opt.print) print_blocks(blocks);
}
auto c = matrix<T>(n);
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
const auto block_y = i / block_size;
const auto block_x = j / block_size;
auto& block = blocks[block_y][block_x];
const auto block_offset_x = block_x * block_size;
const auto local_x = j - block_offset_x;
const auto block_offset_y = block_y * block_size;
const auto local_y = i - block_offset_y;
c(i, j) = block[2](local_y, local_x);
}
}
return c;
}
inline size_t get_num_blocks_per_dim(const size_t n, const size_t num_procs)
{
Expects(n > 0);
Expects(num_procs > 0);
if (num_procs == 1) return 1;
const auto procs_per_dim = gsl::narrow<size_t>(
std::floor(std::sqrt(num_procs)));
const auto num_procs_used = procs_per_dim * procs_per_dim;
if (num_procs_used != num_procs)
{
std::cout << "warning only using "
<< num_procs_used << " out of "
<< num_procs << " processors " << std::endl;
}
if (n % procs_per_dim != 0)
{
std::cout << "error: n (" << n
<< ") not divisible by processor count ("
<< procs_per_dim << ")" << std::endl;
throw;
}
return procs_per_dim;
}
template<typename T>
matrix<T> compute_outer_product(
const matrix<T>& a,
const typename matrix<T>::size_type column_index,
const matrix<T>& b,
const typename matrix<T>::size_type row_index)
{
Expects(a.n() == b.n());
matrix<T> c(a.n());
for (size_t i = 0; i < a.n(); ++i)
{
for (size_t j = 0; j < b.n(); ++j)
{
c(i, j) = a(i, column_index) * b(row_index, j);
}
}
return c;
}
template<typename T>
void print_blocks(const block_grid_t<T>& blocks)
{
const auto block_size = blocks[0][0][0].n();
const auto num_blocks = blocks.size();
const auto n = block_size * num_blocks;
for (size_t i = 0; i < n; ++i)
{
const auto block_i = i / block_size;
const auto block_offset_i = block_i * block_size;
const auto local_i = i - block_offset_i;
if (i > 0 && i % block_size == 0)
{
for (size_t m = 0; m < 3; ++m)
{
std::cout << std::setfill('-') << std::setw(n * 3 + num_blocks - 1) << "-";
std::cout << " ";
}
std::cout << std::endl;
}
for (size_t m = 0; m < 3; ++m)
{
for (size_t block_j = 0; block_j < num_blocks; ++block_j)
{
const auto& block = blocks[block_i][block_j];
const auto& mat = block[m];
for (size_t j = 0; j < block_size; ++j)
{
std::cout << std::setfill(' ') << std::setw(2) << mat(local_i, j) << " ";
}
if (block_j + 1 == num_blocks) continue;
std::cout << "|";
}
std::cout << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
template<typename T>
void copy_row(matrix<T>& dest, const matrix<T>& src, size_t row)
{
for (size_t m = 0; m < dest.n(); ++m)
{
dest(row, m) = src(row, m);
}
}
template<typename T>
void copy_col(matrix<T>& dest, const matrix<T>& src, size_t column)
{
for (size_t m = 0; m < dest.n(); ++m)
{
dest(m, column) = src(m, column);
}
}
template<typename T>
void update_block(block_t<T>& block, size_t k)
{
const auto& a = block[0];
const auto& b = block[1];
auto& c = block[2];
c += compute_outer_product(a, k, b, k);
}
template<typename T>
void update_blocks(block_grid_t<T>& blocks, const size_t k)
{
for (auto& block_row : blocks)
{
for (auto& block : block_row)
{
update_block(block, k);
}
}
}
#endif // SUMMA_SEQ_H
| true |
0776dd145a54a84f889657aa5b7f9d1f732f5b75 | C++ | AkritiAgarwal09/DSA | /GeeksForGeeks/DP/6. Count Number of Subset with Given Difference/code.cpp | UTF-8 | 938 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int countSubsetSumWithDifference(int arr[], int n, int diff)
{
int sum = 0;
for(int i=0;i<n;i++)
sum += arr[i] ;
int SubsetSum = (diff+sum)/2 ;
int dp[n+1][SubsetSum+1] ;
for(int i=0;i<=SubsetSum;i++)
dp[0][i] = 0;
for(int i=0;i<=n;i++)
dp[i][0] = 1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=SubsetSum;j++)
{
if(arr[i-1]<=j)
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]] ;
else
dp[i][j] = dp[i-1][j] ;
//cout<<dp[i][j]<<" " ;
}
//cout<<endl ;
}
return dp[n][SubsetSum] ;
}
int main() {
int n;
cin>>n ;
int arr[n],diff ;
for(int i=0;i<n;i++)
cin>>arr[i] ;
cin>>diff ;
cout<<countSubsetSumWithDifference(arr,n,diff) ;
return 0;
} | true |
01b5e24adf845c9aaaa194524efc88be846f310c | C++ | stonedcoldsoup/fungus_libs | /libs/fungus_booster/fungus_concurrency/fungus_concurrency_communication.h | UTF-8 | 2,111 | 2.84375 | 3 | [] | no_license | #ifndef FUNGUSCONCURRENCY_COMMUNICATION_H
#define FUNGUSCONCURRENCY_COMMUNICATION_H
#include "fungus_concurrency_common.h"
namespace fungus_concurrency
{
using namespace fungus_util;
class FUNGUSCONCURRENCY_API comm
{
public:
struct FUNGUSCONCURRENCY_API discard_message_callback
{
virtual void discard(const any_type &m_message) = 0;
};
private:
FUNGUSUTIL_NO_ASSIGN(comm);
class impl;
impl *pimpl_;
comm(impl *pimpl_);
friend class process;
public:
comm(size_t max_channels, size_t cmd_io_nslots, sec_duration_t timeout_period, discard_message_callback *m_discard_message = nullptr);
~comm();
typedef int channel_id;
enum {null_channel_id = -1};
struct event
{
enum type
{
none,
channel_open,
channel_deny,
channel_lost,
channel_clos
};
type t;
channel_id id;
int data;
event(): t(none), id(null_channel_id), data(0) {}
event(const event &e): t(e.t), id(e.id), data(e.data) {}
event(type t, channel_id id, int data): t(t), id(id), data(data) {}
};
channel_id open_channel(comm *mcomm, int data);
bool close_channel(channel_id id, int data);
void close_all_channels(int data);
bool does_channel_exist(channel_id id) const;
bool is_channel_open(channel_id id) const;
bool channel_send(channel_id id, const any_type &m_message);
bool channel_receive(channel_id id, any_type &m_message);
bool channel_discard(channel_id id, size_t n = 1);
bool channel_discard_all(channel_id id);
void all_channels_discard_all();
void dispatch();
bool peek_event(event &event) const;
bool get_event(event &event);
void clear_events();
};
}
#endif
| true |
6017d64d781aa8d41fd3d9f8aa153979707fc002 | C++ | ZibeSun/Oj-C | /有点套路的选择结构题 (20分).cpp | GB18030 | 544 | 3.328125 | 3 | [] | no_license | #include<stdio.h>
int main()
{ int x,y;
scanf("%d",&x);
if(x>=2)
{ y=x*x;
}
else if((-2<=x)&&(x<2))
{ y=2*x;
}
else if(x<-2)
{ y=-x*x;
}
printf("%d",y);
return 0;
}
/*Ŀ
ֶκһֱΪѡṹϰ֣ŴѾĿ··ֶκݸxֵ
һx(-100 <= x <= 100)xֵ
ÿf(x)
-3
-9*/
| true |
309789ed52b361390d281153b8eba1c92e7e3a77 | C++ | HarukaSunada/Game | /DungeonGame/game/Sprite.cpp | SHIFT_JIS | 1,793 | 2.703125 | 3 | [] | no_license | #include "stdafx.h"
#include "Sprite.h"
Sprite::Sprite()
{
m_angle = 0;
m_scale = D3DXVECTOR2(1.0f, 1.0f);
m_backColor = D3DCOLOR_ARGB(255, 255, 255, 255);
}
Sprite::~Sprite()
{
Release();
}
void Sprite::Init()
{
D3DXCreateSprite(g_pd3dDevice, &g_pSprite);
D3DXIMAGE_INFO imgInfo; //摜i[p\
m_angle = 0.0f;
//eNX`Ǎ
D3DXCreateTextureFromFileEx(g_pd3dDevice, this->m_texFileName, 0, 0, 0, 0, D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_DEFAULT, 0xff000000, &imgInfo, NULL, &this->g_pTexture);
//eNX`̒_Zbg
//this->m_texCenter = D3DXVECTOR2((float)imgInfo.Width / 2, (float)imgInfo.Height / 2);
this->m_texCenter = D3DXVECTOR2(0.0f, (float)imgInfo.Height / 2);
RECT rec = { 0, 0, imgInfo.Width, imgInfo.Height }; //`̈
memcpy(&this->m_rect, &rec, sizeof(RECT)); //`̈Zbg
SetupMatrices();
}
void Sprite::Draw()
{
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND); //XvCg`Jn
g_pSprite->SetTransform(&this->m_transformMatrix); //ϊsZbg
//XvCgɃeNX`\t
g_pSprite->Draw(this->g_pTexture, &this->m_rect,
&D3DXVECTOR3(this->m_texCenter.x, this->m_texCenter.y, 0.0f), NULL, this->m_backColor);
g_pSprite->End(); //XvCg`I
}
void Sprite::SetupMatrices()
{
D3DXMatrixIdentity(&this->m_transformMatrix); //[hs
D3DXMatrixTransformation2D(&this->m_transformMatrix, NULL, 0.0f,
&this->m_scale,NULL, D3DXToRadian(this->m_angle), &this->m_position); //ϊs쐬
}
void Sprite::Release()
{
if (g_pSprite != nullptr) {
g_pSprite->Release();
g_pSprite = nullptr;
}
if (g_pTexture != nullptr) {
g_pTexture->Release();
g_pTexture = nullptr;
}
} | true |
3d9463a1961c6db8c36ff21fe89ddd9ef2139caf | C++ | akash37/Programming-Practice | /data structures/pointers.cpp | UTF-8 | 275 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
cout<<"N = "<<n<<endl;
cout<<"location of n"<<&n<<endl;
int *ptr;
cout<<"ptr"<<ptr<<endl;
cout<<"location of ptr"<<&ptr<<endl;
ptr = &n;
cout<<"ptr"<<ptr<<endl;
cout<<*ptr;
int x;
cout<<x;
} | true |
03dc566f89d827e6f6de2dce5b6e55bb3ad0df28 | C++ | JipBoesenkool/CSE167F17_Project4 | /src/renderer/model/Mesh.cpp | UTF-8 | 2,891 | 3.03125 | 3 | [] | no_license | //
// Created by Jip Boesenkool on 26/10/2017.
//
#include "Mesh.h"
//Static (global)
Mesh Mesh::ParseObj(const char* filepath)
{
Mesh mesh;
std::vector<glm::vec3> vertices;
std::vector<glm::vec3> normals;
float vx, vy, vz; // vertex coordinates
float vnx, vny, vnz; // vertex normals
unsigned int vindex[3], nindex[3];
float r,g,b; // vertex color
std::string firstToken;
std::string vnPair;
//Parse .obj
std::ifstream file(filepath);
std::string line;
while ( std::getline(file, line) )
{
std::istringstream iss(line);
iss >> firstToken;
if (firstToken == "v")
{
iss >> vx >> vy >> vz;// >> vertX >> vertY >> vertZ;
vertices.push_back( glm::vec3(vx,vy,vz) );
//TODO: store colors
}
else if (firstToken == "vn")
{
iss >> vnx >> vny >> vnz;// normX>>normY>>normZ
normals.push_back( glm::vec3(vnx,vny,vnz) );
}
else if(firstToken == "f")
{
//done parsing vectors, collect them into mesh
if(mesh.m_vertices.size() == 0)
{
mesh.m_vertices.resize( vertices.size() );
for( int i = 0; i < vertices.size(); ++i ) {
mesh.m_vertices[i] = Vertex{vertices[i], normals[i], glm::vec2(0)};
}
}
for( int i = 0; i < 3; ++i ) {
iss >> vnPair;
int delimPos = vnPair.find("//");
int spacing = 2;
if(delimPos < 0)
{
delimPos = vnPair.find("/");
spacing = 1;
}
vindex[i] = std::stoi( vnPair.substr(0, delimPos) );
nindex[i] = std::stoi( vnPair.substr(delimPos + spacing, vnPair.size()) );
mesh.m_indices.push_back( vindex[i]-1 );
}
}
}
mesh.Normalize();
return mesh;
}
//Public Functions
void Mesh::Normalize()
{
glm::vec3 min = glm::vec3(99.0f);
glm::vec3 max = glm::vec3(-99.0f);
glm::vec3 total = glm::vec3(0.0f);
for( int i = 0; i < m_vertices.size(); ++i )
{
//min
if(m_vertices[i].m_position.x < min.x) { min.x = m_vertices[i].m_position.x; }
if(m_vertices[i].m_position.y < min.y) { min.y = m_vertices[i].m_position.y; }
if(m_vertices[i].m_position.z < min.z) { min.z = m_vertices[i].m_position.z; }
//max
if(m_vertices[i].m_position.x > max.x) { max.x = m_vertices[i].m_position.x; }
if(m_vertices[i].m_position.y > max.y) { max.y = m_vertices[i].m_position.y; }
if(m_vertices[i].m_position.z > max.z) { max.z = m_vertices[i].m_position.z; }
//to get midpoint
total += m_vertices[i].m_position;
}
glm::vec3 div = glm::vec3( (float)m_vertices.size() );
total = total/div;
//resize
glm::vec3 boundingBox = max - min;
//get biggest size
float maxBound = boundingBox.x;
if(boundingBox.y > maxBound){ maxBound = boundingBox.y; };
if(boundingBox.z > maxBound){ maxBound = boundingBox.z; };
float boundSize = 2.0f;
float newscale = boundSize/maxBound;
glm::vec3 newposition = glm::vec3(0.0f) - total;
for( int i = 0; i < m_vertices.size(); ++i ) {
m_vertices[i].m_position += newposition;
m_vertices[i].m_position *= newscale;
}
}
| true |
dc6c091db93f64875135fdf2ff93e72db63899d6 | C++ | JackNull/BranchPredictors | /test/2level-automaton-sature-test.cc | UTF-8 | 778 | 2.84375 | 3 | [] | no_license | #include "../sim/predictor_2level.h"
#include "catch.hpp"
TEST_CASE("AutomatonSature next state") {
AutomatonSature automaton(2);
REQUIRE(automaton.nextState(0, true) == 1);
REQUIRE(automaton.nextState(1, true) == 2);
REQUIRE(automaton.nextState(2, true) == 3);
REQUIRE(automaton.nextState(3, true) == 3);
REQUIRE(automaton.nextState(0, false) == 0);
REQUIRE(automaton.nextState(1, false) == 0);
REQUIRE(automaton.nextState(2, false) == 1);
REQUIRE(automaton.nextState(3, false) == 2);
}
TEST_CASE("AutomatonSature predict") {
AutomatonSature automaton(2);
REQUIRE(automaton.predict(0) == false);
REQUIRE(automaton.predict(1) == false);
REQUIRE(automaton.predict(2) == true);
REQUIRE(automaton.predict(3) == true);
}
| true |
2784af4ab5e583fa34778b63f08ee1250f6501d6 | C++ | vudph/basic-cplus | /dp/decorator/VerticalScrollBarDecorator.cpp | UTF-8 | 516 | 2.65625 | 3 | [] | no_license | #include "VerticalScrollBarDecorator.h"
#include <iostream>
VerticalScrollBarDecorator::VerticalScrollBarDecorator(Window *window) : WindowDecorator(window){
}
void VerticalScrollBarDecorator::draw() {
WindowDecorator::draw();
drawVerticalScrollBar();
}
void VerticalScrollBarDecorator::drawVerticalScrollBar() {
std::cout << "Draw vertical scrollbar \n";
}
std::string VerticalScrollBarDecorator::getDescription() {
return WindowDecorator::getDescription() + ", including vertical scrollbar";
}
| true |
163481853ef659ae1e4b0dedc8cb972bdf0f0784 | C++ | cjxgm/cctt | /source/token-tree/error.cpp | UTF-8 | 2,764 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | #include "error.hpp"
#include "../util/string.hpp"
#include <fmt/format.hpp>
#include "../util/style.inl"
namespace cctt
{
[[noreturn]] auto throw_scanning_error(
Source_Location loc,
char const* first,
char const* last,
char const* reason
) -> void
{
auto msg = fmt::format(
STYLE_LOCATION "{}:{}" STYLE_NORMAL " "
"\"" STYLE_SOURCE "{}" STYLE_NORMAL "\": {}"
, loc.line
, loc.column
, util::quote_without_delimiters({first, last})
, reason
);
throw Parsing_Error{msg};
}
[[noreturn]] auto throw_scanning_error_of_missing_pair(
Source_Location loc,
char const* first,
char const* last,
char const* missing_pair
) -> void
{
auto reason = fmt::format(
"missing paired \"" STYLE_SOURCE "{}" STYLE_NORMAL "\"."
, util::quote_without_delimiters(missing_pair)
);
throw_scanning_error(loc, first, last, reason.data());
}
[[noreturn]] auto throw_parsing_error(
Source_Location loc,
Token const* tk,
char const* reason
) -> void
{
throw_scanning_error(loc, tk->first, tk->last, reason);
}
[[noreturn]] auto throw_parsing_error2(
Source_Location loc0,
Token const* tk0,
Source_Location loc1,
Token const* tk1,
char const* reason
) -> void
{
auto msg = fmt::format(
STYLE_LOCATION "{}:{}" STYLE_NORMAL " "
"\"" STYLE_SOURCE "{}" STYLE_NORMAL "\" and "
STYLE_LOCATION "{}:{}" STYLE_NORMAL " "
"\"" STYLE_SOURCE "{}" STYLE_NORMAL "\": "
"{}"
, loc0.line
, loc0.column
, util::quote_without_delimiters({tk0->first, tk0->last})
, loc1.line
, loc1.column
, util::quote_without_delimiters({tk1->first, tk1->last})
, reason
);
throw Parsing_Error{msg};
}
[[noreturn]] auto throw_parsing_error_of_missing_pair(
Source_Location loc,
Token const* pair,
char const* missing_pair
) -> void
{
auto reason = fmt::format(
"missing paired \"" STYLE_SOURCE "{}" STYLE_NORMAL "\"."
, util::quote_without_delimiters(missing_pair)
);
throw_parsing_error(loc, pair, reason.data());
}
[[noreturn]] auto throw_parsing_error_of_unpaired_pair(
Source_Location open_loc,
Token const* open,
Source_Location closing_loc,
Token const* closing
) -> void
{
throw_parsing_error2(open_loc, open, closing_loc, closing, "unmatching pair.");
}
}
| true |
b5beeaf29293f5425e8be930f07e315744ac139d | C++ | sl1296/acm-code | /cf-725A-1 Accepted.cpp | UTF-8 | 430 | 2.640625 | 3 | [] | no_license |
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
char s[200100];
int main(){
int n;
while(scanf("%d%s",&n,s)!=EOF){
int l=strlen(s);
int ans=0;
for(int i=0;i<l;i++){
if(s[i]=='>')break;
ans++;
}
for(int i=l-1;i>-1;i--){
if(s[i]=='<')break;
ans++;
}
printf("%d\n",ans);
}
return 0;
}
| true |
ff8bba6aecc3d6b8ba8fe327f2f08b52cbc3c5f9 | C++ | zhangq49/JianzhiOffer | /recall/12.path_in_a_matrix.cpp | UTF-8 | 1,976 | 3.78125 | 4 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
bool has_path_in_matrix_core(const vector<vector<char>>& matrix, const string& path,
vector<vector<bool>>& visited, int& visited_path_length,
int row, int col) {
if (path[visited_path_length] == '\0')
return true;
bool has_path = false;
if (row >= 0 && row < matrix.size() && col >= 0 && col < matrix[0].size() &&
matrix[row][col] == path[visited_path_length] && !visited[row][col]) {
visited[row][col] = true;
++visited_path_length;
has_path = has_path_in_matrix_core(matrix, path, visited, visited_path_length, row - 1, col) ||
has_path_in_matrix_core(matrix, path, visited, visited_path_length, row, col + 1) ||
has_path_in_matrix_core(matrix, path, visited, visited_path_length, row + 1, col) ||
has_path_in_matrix_core(matrix, path, visited, visited_path_length, row, col - 1);
if (!has_path) {
--visited_path_length;
visited[row][col] = false;
}
}
return has_path;
}
bool has_path_in_matrix(const vector<vector<char>>& matrix, const string& path) {
int rows = matrix.size();
int cols = matrix[0].size();
if (rows == 0 || path.length() == 0) return false;
vector<bool> visited_row(cols, false);
vector<vector<bool>> visited(rows, visited_row);
int visited_path_length = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (has_path_in_matrix_core(matrix, path, visited, visited_path_length, i, j))
return true;
}
}
return false;
}
int main() {
int rows, cols;
cin >> rows >> cols;
cout << "Please input a matrix: " << endl;
vector<char> matrix_row(cols, '\0');
vector<vector<char>> matrix(rows, matrix_row);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
cout << "Please input a path: " << endl;
string path;
cin >> path;
bool has_path = has_path_in_matrix(matrix, path);
cout << boolalpha << has_path << endl;
return 0;
} | true |
35049a5e0e772dd568b2822749cddc5f8207090c | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/libs/thread/example/shared_monitor.cpp | UTF-8 | 3,351 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcr... | permissive | // Copyright (C) 2012 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/lock_algorithms.hpp>
#include <boost/thread/thread_only.hpp>
#if defined BOOST_THREAD_DONT_USE_CHRONO
#include <boost/chrono/chrono_io.hpp>
#endif
#include <cassert>
#include <vector>
#define EXCLUSIVE 1
#define SHARED 2
#define MODE SHARED
class A
{
#if MODE == EXCLUSIVE
typedef boost::mutex mutex_type;
#elif MODE == SHARED
typedef boost::shared_mutex mutex_type;
#else
#error MODE not set
#endif
typedef std::vector<double> C;
mutable mutex_type mut_;
C data_;
public:
A() : data_(10000000) {}
A(const A& a);
A& operator=(const A& a);
void compute(const A& x, const A& y);
};
A::A(const A& a)
{
#if MODE == EXCLUSIVE
boost::unique_lock<mutex_type> lk(a.mut_);
#elif MODE == SHARED
boost::shared_lock<mutex_type> lk(a.mut_);
#else
#error MODE not set
#endif
data_ = a.data_;
}
A&
A::operator=(const A& a)
{
if (this != &a)
{
boost::unique_lock<mutex_type> lk1(mut_, boost::defer_lock);
#if MODE == EXCLUSIVE
boost::unique_lock<mutex_type> lk2(a.mut_, boost::defer_lock);
#elif MODE == SHARED
boost::shared_lock<mutex_type> lk2(a.mut_, boost::defer_lock);
#else
#error MODE not set
#endif
boost::lock(lk1, lk2);
data_ = a.data_;
}
return *this;
}
void
A::compute(const A& x, const A& y)
{
boost::unique_lock<mutex_type> lk1(mut_, boost::defer_lock);
#if MODE == EXCLUSIVE
boost::unique_lock<mutex_type> lk2(x.mut_, boost::defer_lock);
boost::unique_lock<mutex_type> lk3(y.mut_, boost::defer_lock);
#elif MODE == SHARED
boost::shared_lock<mutex_type> lk2(x.mut_, boost::defer_lock);
boost::shared_lock<mutex_type> lk3(y.mut_, boost::defer_lock);
#else
#error MODE not set
#endif
boost::lock(lk1, lk2, lk3);
assert(data_.size() == x.data_.size());
assert(data_.size() == y.data_.size());
for (unsigned i = 0; i < data_.size(); ++i)
data_[i] = (x.data_[i] + y.data_[i]) / 2;
}
A a1;
A a2;
void test_s()
{
A la3 = a1;
for (int i = 0; i < 150; ++i)
{
la3.compute(a1, a2);
}
}
void test_w()
{
A la3 = a1;
for (int i = 0; i < 10; ++i)
{
la3.compute(a1, a2);
a1 = la3;
a2 = la3;
#if defined BOOST_THREAD_DONT_USE_CHRONO
boost::this_thread::sleep_for(boost::chrono::seconds(1));
#endif
}
}
int main()
{
#if defined BOOST_THREAD_DONT_USE_CHRONO
typedef boost::chrono::high_resolution_clock Clock;
typedef boost::chrono::duration<double> sec;
Clock::time_point t0 = Clock::now();
#endif
std::vector<boost::thread*> v;
boost::thread thw(test_w);
v.push_back(&thw);
boost::thread thr0(test_w);
v.push_back(&thr0);
boost::thread thr1(test_w);
v.push_back(&thr1);
boost::thread thr2(test_w);
v.push_back(&thr2);
boost::thread thr3(test_w);
v.push_back(&thr3);
for (std::size_t i = 0; i < v.size(); ++i)
v[i]->join();
#if defined BOOST_THREAD_DONT_USE_CHRONO
Clock::time_point t1 = Clock::now();
std::cout << sec(t1-t0) << '\n';
#endif
return 0;
}
| true |
f8477400ad36205ffbdf711a255502277d59de98 | C++ | masayano/usefulHacks | /patternHunter/src/analyzeWord.cpp | UTF-8 | 8,127 | 2.75 | 3 | [] | no_license | /*******************************************************
/
/ Copyright 2014, Masahiro Yano
/ Licensed under the BSD licenses.
/ https://github.com/masayano
/
/ What is this?
/
/ [tab separated word count file"s": word, count]
/ -> [tab separated word slope/average file:
/ word,
/ slope of smoothed probability / average,
/ JSON word number history (not smoothed),
/ JSON word smoothed probability history]
/
/********************************************************/
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <sstream>
#include <iomanip>
const double MIN_AVERAGE_PROBABILITY = 1.0e-6;
typedef boost::char_separator<char> char_separator;
typedef boost::tokenizer<char_separator> tokenizer;
char_separator tabSep("\t");
const std::vector<std::string> splitString(const std::string& str) {
std::vector<std::string> parts;
tokenizer tokens(str, tabSep);
for (const auto& part : tokens) {
parts.push_back(part);
}
return parts;
}
void loadFile(
std::map<std::string, std::pair<std::vector<int>, std::vector<double> > >& smoothedMatrix,
std::vector<std::map<std::string, int> >& wordCounters,
std::vector<double>& totalWordNums,
const std::string& fileName) {
std::map<std::string, int> wordCounter;
int totalWordNum = 0;
std::ifstream ifs(fileName.c_str());
std::string buf;
while(ifs && std::getline(ifs, buf)) {
const auto parts = splitString(buf);
const auto& word = parts[0];
const auto& count = boost::lexical_cast<int>(parts[1]);
wordCounter[word] = count;
const auto& it = smoothedMatrix.find(word);
if(it == std::end(smoothedMatrix)) {
smoothedMatrix[word] = std::make_pair(std::vector<int>(), std::vector<double>());
}
totalWordNum += 1;
}
wordCounters .push_back(wordCounter);
totalWordNums.push_back(static_cast<double>(totalWordNum));
}
void makeMatrix(
std::map<std::string, std::pair<std::vector<int>, std::vector<double> > >& smoothedMatrix,
const std::vector<std::map<std::string, int> >& wordCounters,
const std::vector<double>& totalWordNums) {
const auto wordTypeNum = static_cast<double>(smoothedMatrix.size());
for(int i = 0; i < wordCounters.size(); ++i) {
const auto& wordCounter = wordCounters [i];
const auto& totalWordNum = totalWordNums[i];
const auto& totalNumAfterSmoothed = totalWordNum + wordTypeNum;
for(const auto& elem : smoothedMatrix) {
const auto& key = elem.first;
const auto& it = wordCounter.find(key);
int smoothedNumber;
if(it != std::end(wordCounter)) {
smoothedNumber = (*it).second + 1; // smoothing
} else {
smoothedNumber = 1; // smoothing
}
const auto probability = smoothedNumber / totalNumAfterSmoothed;
smoothedMatrix[key].first .push_back(smoothedNumber);
smoothedMatrix[key].second.push_back(probability);
}
}
}
const std::vector<double> range(int num) {
std::vector<double> output;
for(int i = 0; i < num; ++i) {
output.push_back(i);
}
return output;
}
double calcSlope(
const std::vector<double>& values_x,
const std::vector<double>& values_y) {
const auto length = static_cast<double>(values_x.size());
const auto average_x = std::accumulate(std::begin(values_x), std::end(values_x), 0.0) / length;
const auto average_y = std::accumulate(std::begin(values_y), std::end(values_y), 0.0) / length;
double coVar = 0;
double var_x = 0;
for(int i = 0; i < length; ++i) {
const auto xDiff = values_x[i] - average_x;
const auto yDiff = values_y[i] - average_y;
coVar += (xDiff * yDiff);
var_x += (xDiff * xDiff);
}
return coVar / var_x;
}
const std::vector<std::pair<double, std::string> > calcSlope(
const std::map<std::string, std::pair<std::vector<int>, std::vector<double> > >& smoothedMatrix) {
std::vector<std::pair<double, std::string> > results;
const auto length = (*std::begin(smoothedMatrix)).second.first.size();
const auto values_x = range(length);
for(const auto& elem : smoothedMatrix) {
const auto& key = elem.first;
const auto& values_y = elem.second.second;
const auto z = calcSlope(values_x, values_y);
const auto average = std::accumulate(std::begin(values_y), std::end(values_y), 0.0) / length;
results.push_back(std::make_pair(z / average, key));
}
std::sort(std::begin(results), std::end(results), std::greater<std::pair<double, std::string>>());
return results;
}
const std::string getDate() {
time_t now;
time(&now);
const auto date = localtime(&now);
const auto year = date->tm_year + 1900;
const auto month = date->tm_mon + 1;
const auto day = date->tm_mday;
const auto hour = date->tm_hour;
const auto minute = date->tm_min;
std::stringstream ss;
ss << year << "_" << month << "_" << day << "_" << hour << "_" << minute;
return ss.str();
}
const std::string makeStrProbArray(const std::vector<double>& probArray) {
std::stringstream output;
output << "[";
for(int i = 0; i < probArray.size(); ++i) {
output << std::setprecision(3) << probArray[i];
if(i != probArray.size()-1) {
output << ", ";
}
}
output << "]";
return output.str();
}
const std::string makeStrNumArray(const std::vector<int>& numArray) {
std::stringstream output;
output << "[";
for(int i = 0; i < numArray.size(); ++i) {
output << numArray[i] - 1;
if(i != numArray.size()-1) {
output << ", ";
}
}
output << "]";
return output.str();
}
void writeResults(
const std::vector<std::pair<double, std::string> >& results,
std::map<std::string, std::pair<std::vector<int>, std::vector<double> > >& smoothedMatrix) {
const auto fileName = "analysis/" + getDate() + ".log";
std::ofstream ofs(fileName.c_str());
for(const auto& elem : results) {
const auto& slope = elem.first;
const auto& key = elem.second;
const auto& value = smoothedMatrix[key];
const auto& probArray = value.second;
const auto strProbArray = makeStrProbArray(probArray);
const auto averageProb = std::accumulate(std::begin(probArray), std::end(probArray), 0.0) / probArray.size();
if(averageProb > MIN_AVERAGE_PROBABILITY) {
const auto strNumArray = makeStrNumArray(value.first);
ofs
<< key
<< "\t"
<< std::setprecision(3) << slope
<< "\t"
<< strNumArray
<< "\t"
<< strProbArray
<< std::endl;
}
}
}
int main(int argc, char** argv) {
std::map<std::string, std::pair<std::vector<int>, std::vector<double> > > smoothedMatrix;
std::vector<std::map<std::string, int> > wordCounters;
std::vector<double> totalWordNums;
if(argc >= 2) {
for(int i = 1; i < argc; ++i) {
const auto fileName = argv[i];
std::cout << "[Load for analyzing] " << fileName << std::endl;
loadFile(
smoothedMatrix,
wordCounters,
totalWordNums,
fileName);
}
makeMatrix(
smoothedMatrix,
wordCounters,
totalWordNums);
const auto results = calcSlope(smoothedMatrix);
writeResults(
results,
smoothedMatrix);
} else {
std::cout << "Usage: python analyzeWord.py [word count file name(s)]" << std::endl;
}
return 0;
}
| true |
219fa6335fafe44883ce1672db990debe7ce725f | C++ | noriyukit/experimental | /overload/overload.cc | UTF-8 | 796 | 3.453125 | 3 | [] | no_license | #include "overload.h"
#include <iostream>
using namespace std;
using namespace overload;
struct A {
~A() {
cout << __func__ << endl;
}
A() {
}
A(const A&) {
cout << "copy!" << endl;
}
A(A&&) {
cout << "move!" << endl;
}
int operator()() {
cout << "void void" << __func__ << endl;
return 0;
}
int operator()(int) {
cout << __func__ << endl;
return a;
}
int operator()(int, int) {
cout << __func__ << endl;
return 2;
}
void operator()(double) {
cout << "void double" << endl;
}
int a;
};
int main() {
{
A a;
Overload<int(), int(int), int(int, int), void(double)> oo = a;
decltype(oo) o = std::move(oo);
o();
cout << o(10) << endl;
cout << o(10, 20) << endl;
o(1.0);
}
return 0;
}
| true |
ec51c7a4a4d0731e7ee8dbad7f10091a19293dce | C++ | recurze/ProjectEuler | /14.cpp | UTF-8 | 936 | 2.859375 | 3 | [] | no_license | /**
* File : 14.cpp
* Author : recurze
* Date : 12:35 27.12.2018
* Last Modified Date: 14:45 27.12.2018
*/
#include <cstdio>
#include <algorithm>
const int N = 5050505;
int ans[N] = {0};
int run(long long n) {
if (n == 1 || (n < N && ans[n])) return ans[n];
int x;
if (n&1) {
x = run((3*n + 1)>>1) + 2;
} else {
x = run(n >> 1) + 1;
}
if (n < N) ans[n] = x;
return x;
}
int main() {
int t; scanf("%d", &t);
int a[t];
for (int tc = 0; tc < t; ++tc) { scanf("%d", &a[tc]); }
int m = *std::max_element(a, a + t);
for (int i = 0; i < m; ++i) { run(i + 1); }
int max[m + 1] = {0, 1};
for (int i = 2; i <= m; ++i) {
if (ans[max[i - 1]] <= ans[i]) {
max[i] = i;
} else {
max[i] = max[i - 1];
}
}
for (int i = 0; i < t; ++i) {
printf("%d\n", max[a[i]]);
}
}
| true |
82c0c2604fe8992afc218dbb0be0067b0177d7fa | C++ | Israel0806/CCOMP-1 | /Clase13/Car.cpp | UTF-8 | 393 | 3.109375 | 3 | [] | no_license | #include "Car.h"
#include <string>
#include <sstream>
using namespace std;
Car::Car(const string &myLicense,const int myYear,const string &myStyle)
: Vehicle (myLicense,myYear), style(myStyle) {}
string Car::getDesc()
{
stringstream ss;
ss<<year;
return "Year: " + ss.str() + "\nStyle: " + style + "\nLicense: " + license;
}
string Car::getStyle()
{
return style;
}
| true |
0eab3f60d00a76680ee4a7abc9d662508e68a4f7 | C++ | yuan-feng/graphics | /tiny_render/main_3_depth_buffer.cpp | UTF-8 | 3,688 | 2.6875 | 3 | [] | no_license | #include "geometry.h"
#include "model.h"
#include "tga_image.h"
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
namespace {
constexpr const int kWidth = 800;
constexpr const int kHeight = 800;
} // namespace
Vec3f GetBarycentric(Vec3f A, Vec3f B, Vec3f C, Vec3f P) {
Vec3f s[2];
for (int i = 2; i--;) {
s[i][0] = C[i] - A[i];
s[i][1] = B[i] - A[i];
s[i][2] = A[i] - P[i];
}
Vec3f u = cross(s[0], s[1]);
if (std::abs(u[2]) > 1e-2) {
return Vec3f(1.f - (u.x + u.y) / u.z, u.y / u.z, u.x / u.z);
}
return Vec3f(-1, 1, 1);
}
void DrawTriangle(const Vec3f *pts,
std::array<float, kWidth * kHeight> &zbuffer, TGAImage &image,
const TGAColor &color, const TGAImage *texture,
const Vec2i *uv) {
Vec2f bboxmin(std::numeric_limits<float>::max(),
std::numeric_limits<float>::max());
Vec2f bboxmax(-std::numeric_limits<float>::max(),
-std::numeric_limits<float>::max());
Vec2f clamp(image.width() - 1, image.height() - 1);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
bboxmin[j] = std::max(0.f, std::min(bboxmin[j], pts[i][j]));
bboxmax[j] = std::min(clamp[j], std::max(bboxmax[j], pts[i][j]));
}
}
Vec3f P;
for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) {
for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) {
Vec3f barycentric_weight = GetBarycentric(pts[0], pts[1], pts[2], P);
if (barycentric_weight.x < 0 || barycentric_weight.y < 0 ||
barycentric_weight.z < 0) {
continue;
}
P.z = 0;
Vec2i pixel_uv;
for (int i = 0; i < 3; i++) {
P.z += pts[i][2] * barycentric_weight[i];
pixel_uv += uv[i] * barycentric_weight[i];
}
TGAColor texture_color = texture->Get(pixel_uv[0], pixel_uv[1]);
if (zbuffer[int(P.x + P.y * kWidth)] < P.z) {
zbuffer[int(P.x + P.y * kWidth)] = P.z;
image.Set(P.x, P.y, texture_color);
}
}
}
}
Vec3f WorldToScreen(Vec3f v) {
return Vec3f(int((v.x + 1.) * kWidth / 2. + .5),
int((v.y + 1.) * kHeight / 2. + .5), v.z);
}
int main(int argc, char **argv) {
std::unique_ptr<Model> model;
if (2 == argc) {
model = std::make_unique<Model>(argv[1]);
} else {
model = std::make_unique<Model>("../obj/african_head.obj");
}
std::unique_ptr<TGAImage> texture_image = std::make_unique<TGAImage>();
if (!texture_image->ReadTgaFile("../obj/african_head_diffuse.tga")) {
std::cerr << "Failed to read tga file." << std::endl;
}
texture_image->FlipVertically();
std::array<float, kWidth * kHeight> zbuffer;
std::fill(zbuffer.begin(), zbuffer.end(), -std::numeric_limits<float>::max());
Vec3f light_dir(0, 0, -1); // define light_dir
TGAImage image(kWidth, kHeight, TGAImage::RGB);
for (int i = 0; i < model->nfaces(); i++) {
std::vector<size_t> face = model->face(i);
Vec3f screen_coords[3];
Vec3f world_coords[3];
Vec2i uv[3];
for (int j = 0; j < 3; j++) {
world_coords[j] = model->vert(face[j]);
screen_coords[j] = WorldToScreen(world_coords[j]);
uv[j] = model->uv(i, j);
}
Vec3f n = (world_coords[2] - world_coords[0]) ^
(world_coords[1] - world_coords[0]);
n.Normalize();
float intensity = n * light_dir;
const auto intensity_v = static_cast<unsigned char>(intensity * 255);
const auto color = TGAColor(intensity_v, intensity_v, intensity_v, 255);
DrawTriangle(screen_coords, zbuffer, image, color, texture_image.get(), uv);
}
image.FlipVertically();
image.WriteTgaFile("output.tga");
return 0;
} | true |
1a4d0994575b4b63ccfff391a6002ddac61a697d | C++ | dustinslade/Sector_TD | /WorldObj.h | UTF-8 | 2,776 | 3.25 | 3 | [] | no_license | #ifndef WORLDOBJ_H
#define WORLDOBJ_H
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "World.h"
class World;
class WorldObj{
public:
/*
Pre-condition: Valid x and y positions are passed
Post-condition: objSprite's initial position is set
Parameters: an x and y position
Return Values: none
*/
WorldObj(int posX, int posY);
/*
Pre-condition: none
Post-condition: none
Parameters: none
Return Values: none
*/
virtual ~WorldObj();
/*
Pre-condition: the particular WorldObj has an initialized image that has been loaded into the objSprite
Post-condition: objSprite has not been changed
Parameters: none
Return Values: the sprite associated with a WorldObj
*/
sf::Sprite GetobjSprite() const { return objSprite; }
/*
Pre-condition: the child obj has set the position of it's sprite
Post-condition: objSprite's position has not been changed
Parameters: none
Return Values: the x position of objSprite
*/
int GetposX() const { return objSprite.GetPosition().x; }
/*
Pre-condition: the child obj has set the position of it's sprite
Post-condition: objSprite's position has not been changed
Parameters: none
Return Values: the y position of objSprite
*/
int GetposY() const { return objSprite.GetPosition().y; }
/*
Pre-condition: Valid x and y positions are passed, World dimensions are assumed (fixed)
Post-condition: a boolean value is set and returned
Parameters: an x and y position and a World
Return Values: true if the position is within the bounds, false otherwise
*/
bool MoveBoundary(int posX, int posY);
/*
Pre-condition: the position passed is not out of bounds (MoveBoundary returns true)
Post-condition: objSprite is moved to a new position
Parameters: an x and y position and a World
Return Values: none
*/
void MoveObj(int posX, int posY);
/*
Pre-condition: an objSprite is loaded
Post-condition: objSprite is rotated
Parameters: an angle in degrees
Return Values: none
*/
void RotateObj(float angle) { objSprite.SetRotation(angle); }
/*
Pre-condition: an objSprite needs a center
Post-condition: objSprite is centered
Parameters: position of center
Return Values: none
*/
void SetCenter(float x, float y){ objSprite.SetCenter(x, y); }
protected:
sf::Sprite objSprite;
private:
};
#endif // WORLDOBJ_H
| true |