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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
57bbf7fd9ee442b947d69b7e1005ab46b52a8195 | C++ | 00mjk/Cross-Platform-Game-Engine | /Engine/src/AI/Astar.cpp | UTF-8 | 3,753 | 2.734375 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | #include "stdafx.h"
#include "Astar.h"
namespace Astar
{
static Generator* instance = 0;
GridCoord Heuristic::GetDelta(GridCoord source, GridCoord goal)
{
return GridCoord(abs(source.x - goal.x), abs(source.y - goal.y));
}
uint32_t Heuristic::Manhattan(GridCoord source, GridCoord goal)
{
auto delta = std::move(GetDelta(source, goal));
return static_cast<uint32_t>(10 * (delta.x + delta.y));
}
uint32_t Heuristic::Euclidean(GridCoord source, GridCoord goal)
{
auto delta = std::move(GetDelta(source, goal));
return static_cast<uint32_t>(10 * sqrt(pow(delta.x, 2) + pow(delta.y, 2)));
}
uint32_t Heuristic::Octagonal(GridCoord source, GridCoord goal)
{
auto delta = std::move(GetDelta(source, goal));
return static_cast <uint32_t>(10 * (delta.x + delta.y) + (-6) * ((delta.x < delta.y) ? delta.x : delta.y));
}
Generator::Generator()
{
SetDiagonalMovement(true);
SetHeuristic(&Heuristic::Octagonal);
m_Direction = {
{ 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
{ -1, -1 }, { 1, 1 }, { -1, 1 }, { 1, -1 }
};
}
Node* Generator::FindNodeOnList(const NodeSet& nodes, GridCoord coordinates)
{
for (Node* node : nodes)
{
if (node->m_Coordinates == coordinates)
{
return node;
}
}
return nullptr;
}
void Generator::ReleaseNodes(NodeSet& nodes)
{
for (auto it = nodes.begin(); it != nodes.end();)
{
delete* it;
it = nodes.erase(it);
}
}
Generator* Generator::GetInstance()
{
if (instance == 0)
{
instance = new Generator();
}
return instance;
}
void Generator::SetDiagonalMovement(bool enable)
{
m_Directions = (enable ? 8 : 4);
}
void Generator::SetHeuristic(HeuristicFunction function)
{
m_Heuristic = std::bind(function, std::placeholders::_1, std::placeholders::_2);
}
std::vector<Vector2f> Generator::FindPath(Vector2f source, Vector2f goal, AstarGrid* grid)
{
std::vector<Vector2f> path;
GridCoord sourceCoords, goalCoords;
if (!grid->PositionToGridCoord(source, sourceCoords))
return path;
if (!grid->PositionToGridCoord(goal, goalCoords))
return path;
Node* current = nullptr;
NodeSet openSet, closedSet;
openSet.insert(new Node(sourceCoords));
while (!openSet.empty())
{
current = *openSet.begin();
for (Node* node : openSet)
{
if (node->GetScore() <= current->GetScore())
{
current = node;
}
}
if (current->m_Coordinates == goalCoords)
{
break; // found the goal so exit
}
closedSet.insert(current);
openSet.erase(std::find(openSet.begin(), openSet.end(), current));
for (uint32_t i = 0; i < m_Directions; i++)
{
GridCoord newCoords(current->m_Coordinates + m_Direction[i]);
if (grid->DetectCollision(newCoords) || FindNodeOnList(closedSet, newCoords))
continue;
uint32_t totalcost = current->G + ((i < 4) ? 10 : 14);
Node* successor = FindNodeOnList(openSet, newCoords);
if (successor == nullptr)
{
successor = new Node(newCoords, current);
successor->G = totalcost;
successor->H = m_Heuristic(successor->m_Coordinates, goalCoords);
openSet.insert(successor);
}
else if (totalcost < successor->G)
{
successor->m_Parent = current;
successor->G = totalcost;
}
}
}
while (current != nullptr)
{
/*convert coordinates back into world positions*/
Vector2f position;
grid->GridCoordToPosition(current->m_Coordinates, position);
path.push_back(position);
current = current->m_Parent;
}
ReleaseNodes(openSet);
ReleaseNodes(closedSet);
return std::vector<Vector2f>();
}
Node::Node(GridCoord coordinates, Node* parent)
:m_Parent(parent), m_Coordinates(coordinates)
{
G = H = 0;
}
uint32_t Node::GetScore()
{
return G + H;
}
} | true |
5959f9e817e63bdd884e56c16163adef9002a033 | C++ | ryoo0424/algorithm | /Baekjoon/boj lecture/1. algorithm_IO/algorithm_IO.cpp | UHC | 1,339 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int a, b;
// Ʈ ̽ ־
while (cin >> a >> b) {}
// ---------------------------------- Է¹ޱ
fgets(s, 100, stdin); // ٲޱ Է¹ޱ ؾ
scanf("%[^\n]\n", s);
// ǥ: \n ü Է \n Է
// ٹٲ Է¹ ʱ յڿ ִ
// Է¹
// ϴ ϰ ں Է¹ް
// #11719 ٰ ϴ 츦 ϱ getline̳ scanf
getline(cin, s); // ٲ Է¹
// ----------------------------------
scanf("%1d", %x);
// %d ̿ ̸ŭ Է¹ް
// 12345 1,2,3,4,5 Է¹
// string Է¹ ASCII '0' ָ
// "%1d" 5 Է¹ 1,2,3,4,5 ε
// ----------------------------------
scanf("%10s", %s);
// ̰͵ ؼ Է¹
return 0;
}
| true |
86513b6925444b3b1a452c442543cbb2cad58f8f | C++ | cianmcintyre811/CodilityChallenges-CPP | /7.4_Fish.cpp | UTF-8 | 1,644 | 3.1875 | 3 | [] | no_license | /*
This one was a bit of a pain in the butt but I still did it solo. Made an early mistake of not realising that there
might be multiple fish going downstream, so I couldn't just discard them. Stack2 was previously a vector before I
realised it was unneccesary to have it be one, because the fish swimming up can be discarded after they're either eaten
or swim away, it's only the ones going down we have to keep track of.
https://codility.com/demo/results/training5J4RVT-GU6/
*/
int solution(vector<int> &A, vector<int> &B) {
vector<int> stack1;
int stack2 = 0;
int fishremaining = 0;
for (unsigned int i = 0 ; i < A.size() ; i++ ) {
// If a fish is going downstream, add it to the stack
if (B[i] == 1)
stack1.push_back(A[i]);
// If the fish is going upstream and there were previously some fish going downstream, note the size of the
// current one going up for comparing.
else if (!stack1.empty() )
stack2 = A[i];
// If there's no fish going downstream, any fish going upstream will just swim away safely
else if (stack1.empty()) {
fishremaining++;
}
// If there were fish going downstream before and if the latest upstream fish is bigger than at least the most
// recent one, the downstream fish will get eaten, so pop them off the stack. If the upstream fish eats them all
// then it swims away safely (add to fishremaining).
while (!stack1.empty() && stack1.back() < stack2) {
stack1.pop_back();
if (stack1.empty() )
fishremaining++;
}
// Since the upstream fish will either be eaten or swim away, reset it to zero.
stack2 = 0;
}
return fishremaining + stack1.size();
} | true |
de4013310e7348054dd12a94b2aaa82e9fe04e49 | C++ | erhanonal/ITU-Assignments | /BLG252E-Object Oriented Programming/Assignment1/main.cpp | UTF-8 | 9,070 | 3.703125 | 4 | [] | no_license | /*@erhanonal
Erhan Önal
Date: 25.03.2019
#include <iostream>
#include <fstream>
#include <vector>
#include <stdlib.h>
#include "Polynomial.h"
#include "Vector.h"
using namespace std;
/*Constructor for Vector Class
int s: Size of the vector
int* vals: Pointer to the array of vector values
*/
Vector::Vector(int s,int* vals){
size=s;
values=new int[size];
for(int i=0;i<size;i++){
values[i]=vals[i];
}
}
Vector::Vector(const Vector &objectIn){//Copy constructor for Vector Class
size=objectIn.size;
values=new int[size];
for(int i=0;i<size;i++){
values[i]=objectIn.values[i];
}
}
Vector::~Vector(){//Destructor for Vector Class
delete[] values;
}
/*Overloaded addition operator for Vector class
returns a vector with size 0 for an invalid operation between vectors of different sizes
*/
Vector Vector::operator+(const Vector &objectIn)const{
if(size==objectIn.size){
int sumValues[size];
for(int i=0;i<size;i++){
sumValues[i]=values[i]+objectIn.values[i];
}
return Vector(size,sumValues);
}else{
cout<<"Can't add vectors with different sizes"<<endl;
return Vector(0,NULL);
}
}
Vector Vector::operator*(int scalar)const {//Overloaded multiplication operator for scalar multiplication
int resultValues[size];
for(int i=0;i<size;i++){
resultValues[i]=values[i]*scalar;
}
return Vector(size,resultValues);
}
/*Overloaded multiplication operator for dot product
returns 0 for invalid operation with different sizes*/
int Vector::operator*(const Vector &objectIn)const{
if(size==objectIn.size){
int result=0;
for(int i=0;i<size;i++){
result+=values[i]*objectIn.values[i];
}
return result;
}else{
cout<<"Can't perform dot product on vectors with different sizes"<<endl;
return 0;
}
}
const Vector& Vector::operator=(const Vector &objectIn){//Overloaded assignment operator for Vector Class
size=objectIn.size;
delete[] values;
values=new int[size];
for(int i=0;i<size;i++){
values[i]=objectIn.values[i];
}
return *this;
}
ostream& operator<<(ostream& os,const Vector& objectIn){//Function for printing a vector
os<<"(";
for(int i=0;i<objectIn.size;i++){
os<<objectIn.values[i];
if(i!=objectIn.size-1){
os<<", ";
}
}
os<<")";
return os;
}
Polynomial::Polynomial(int d ,int* values_array){//Constuctor for Polynomial Class. int d : degree , int* values_array: array of coefficients
degree=d;
values=new int[degree+1];
for(int i=0;i<degree+1;i++){
values[i]=values_array[i];
}
}
Polynomial::Polynomial(const Polynomial &objectIn){//Copy constructor for polynomial class
degree=objectIn.degree;
values=new int[degree+1];
for(int i=0;i<degree+1;i++){
values[i]= objectIn.values[i];
}
}
Polynomial::~Polynomial(){//Destructor for Polynomial Class
delete[] values;
}
Polynomial Polynomial::operator+(const Polynomial& objectIn)const{//Overloaded addition operator for polynomials
if(degree>=objectIn.degree){
int sumValues[degree+1];
int i;
for(i=0;i<degree-objectIn.degree;i++){
sumValues[i]=values[i];
}
for(int j=0;j<objectIn.degree+1;j++){
sumValues[i]=values[i]+objectIn.values[j];
i++;
}
Polynomial sum(degree,sumValues);
return sum;
}else{
int sumValues[objectIn.degree+1];
int i;
for(i=0;i<objectIn.degree-degree;i++){
sumValues[i]=objectIn.values[i];
}
for(int j=0;j<degree+1;j++){
sumValues [i]=objectIn.values[i]+values[j];
i++;
}
Polynomial sum(objectIn.degree,sumValues);
return sum;
}
}
Polynomial Polynomial::operator*(const Polynomial& objectIn) const{//Overloadad multiplication operator for polynomials
int multiValues[degree+objectIn.degree+1];
for(int i=0;i<degree+objectIn.degree+1;i++){
multiValues[i]=0;
}
for(int i=0;i<degree+1;i++){
for(int j=0;j<objectIn.degree+1;j++){
multiValues[i+j]+=values[i]*objectIn.values[j];
}
}
Polynomial multi(degree+objectIn.degree,multiValues);
return multi;
}
const Polynomial& Polynomial::operator=(const Polynomial& objectIn){//Overloaded assignment operator for polynomials
degree=objectIn.degree;
delete[] values;
values=new int[degree+1];
for(int i=0;i<degree+1;i++){
values[i]=objectIn.values[i];
}
return *this;
}
ostream& operator<<(ostream& os,const Polynomial& objectIn){//Function for printing a polynomial
for(int i=0;i<objectIn.degree+1;i++){
if(objectIn.values[i]<0){
os<<" - ";
}else if(objectIn.values[i]>0 && i!=0){
os<<" + ";
}
if((abs(objectIn.values[i])!=1 || i==objectIn.degree) && objectIn.values[i]!=0){
os<<abs(objectIn.values[i]);
}
if(objectIn.values[i]!=0 && i!=objectIn.degree){
os<<"x";
}
if(objectIn.values[i]!=0 && i!=objectIn.degree && i!=objectIn.degree-1){
os<<"^"<<objectIn.degree-i;
}
}
return os;
}
int Polynomial::getDegree(){
return degree;
}
int* Polynomial::getValues(){
return values;
}
int Vector::getSize(){
return size;
}
int* Vector::getValues(){
return values;
}
void printAllPolynomials(int polyCount,vector<Polynomial> &polynomials){//Prints all Polynomials
cout<<"Polynomials: "<<endl;
for(int i=0;i<polyCount;i++){
cout<<i+1<<". "<<polynomials[i];
cout<<endl;
}
cout<<endl;
}
void printAllVectors(int vectorCount,vector<Vector> &vectors){//Prints all Vectors
cout<<"Vectors:"<<endl;
for(int i=0;i<vectorCount;i++){
cout<<i+1<<". "<<vectors[i];
cout<<endl;
}
cout<<endl;
}
void printOptions(){
cout<<"Possible Actions"<<endl;
cout<<"1. Print Polynomial and Vector lists"<<endl;
cout<<"2. Do a polynomial operation"<<endl;
cout<<"3. Do a vector operation"<<endl;
cout<<"4. Help: Print possible actions"<<endl;
cout<<"0. Exit the program"<<endl<<endl;
}
int main(){
ifstream polyFile;
polyFile.open("Polynomial.txt");
if(!polyFile){
cout<<"Could not open Polynomial file"<<endl;
return 1;
}
int polyCount;
polyFile>>polyCount;
vector<Polynomial> polynomials;
for(int i=0;i<polyCount;i++){
int degree;
polyFile>>degree;
int polyArray[degree+1];
for(int j=0;j<degree+1;j++){
int coeff;
polyFile>>coeff;
polyArray[j]=coeff;
}
Polynomial newPolynomial(degree,polyArray);
polynomials.push_back(newPolynomial);
}
ifstream vectorFile;
vectorFile.open("Vector.txt");
if(!vectorFile){
cout<<"Could not open Vector.txt"<<endl;
return 1;
}
int vectorCount;
vectorFile>>vectorCount;
vector<Vector> vectors;
for(int i=0;i<vectorCount;i++){
int size;
vectorFile>>size;
int vectorArray[size];
for(int j=0;j<size;j++){
int value;
vectorFile>>value;
vectorArray[j]=value;
}
Vector newVector(size,vectorArray);
vectors.push_back(newVector);
}
cout<<"Polynomial and Vector List Program!"<<endl;
cout<<"Polynomials and Vectors are read from text files!"<<endl<<endl;
printOptions();
bool finish =false;
while(!finish){
cout<<"Enter an option: ";
int selection;
cin>>selection;
if(selection==1){
printAllVectors(vectorCount,vectors);
printAllPolynomials(polyCount,polynomials);
}
else if(selection==2){
cout<<"Which polynomial operation would you like to do (+:addition, *:multiplication):"<<endl;
int operand1,operand2;
char operation;
cin>>operand1>>operation>>operand2;
if(operation=='+'){
if(operand1<1 || operand1>polyCount || operand2<1 || operand2>polyCount){
cout<<"Polynomial doesn't exist"<<endl;
}else{
cout<<"("<<polynomials[operand1-1]<<") + ("<<polynomials[operand2-1]<<") = "<<polynomials[operand1-1]+polynomials[operand2-1]<<endl;
}
}else if(operation=='*'){
if(operand1<1 || operand1>polyCount || operand2<1 || operand2>polyCount){
cout<<"Polynomial doesn't exist"<<endl;
}else{
cout<<"("<<polynomials[operand1-1]<<") * ("<<polynomials[operand2-1]<<") = "<<polynomials[operand1-1]*polynomials[operand2-1]<<endl;
}
}else {
cout<<"Unknown operation, try again"<<endl;
}
}
else if(selection==3){
cout<<"Which vector operation would you like to do (+:addition, *: scalar multiplication, .: dot product):"<<endl;
int operand1,operand2;
char operation;
cin>>operand1>>operation>>operand2;
if(operation=='+'){
if(operand1<1 || operand1>vectorCount || operand2<1 || operand2>vectorCount){
cout<<"Vector doesn't exist"<<endl;
}else{
cout<<vectors[operand1-1]<<" + "<<vectors[operand2-1]<<" = "<<vectors[operand1-1]+vectors[operand2-1]<<endl;
}
}else if(operation=='*'){
if(operand1<1 || operand1>vectorCount ){
cout<<"Vector doesn't exist"<<endl;
}else{
cout<<vectors[operand1-1]<<" * "<<operand2<<" = "<<vectors[operand1-1]*operand2<<endl;
}
}else if(operation=='.'){
if(operand1<1 || operand1>vectorCount || operand2<1 || operand2>vectorCount){
cout<<"Vector doesn't exist"<<endl;
}else{
cout<<vectors[operand1-1]<<" . "<<vectors[operand2-1]<<" = "<<vectors[operand1-1]*vectors[operand2-1]<<endl;
}
}else{
cout<<"Unknown operation, try again"<<endl;
}
}else if(selection==4){
printOptions();
}else if(selection==0){
finish =true;
return 0;
}else{
cout<<"Unknown command,try again "<<endl;
}
}
return 0;
}
| true |
e780f2bb0901946099f03a51735d4acd7d6129ee | C++ | bitmingw/LintcodeSolution | /121WordLadder2/main.cpp | UTF-8 | 2,123 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <unordered_set>
#include <string>
#include <queue>
using namespace std;
class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return a list of lists of string
*/
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> ladders;
queue<vector<string>> searchQ;
dict.insert(end);
vector<string> path;
path.push_back(start);
searchQ.push(path);
updateLadders(ladders, searchQ, dict, end);
return ladders;
}
void updateLadders(vector<vector<string>> &ladders, queue<vector<string>> &searchQ, unordered_set<string> &dict, string end) {
while (!searchQ.empty()) {
vector<string> path = searchQ.front();
searchQ.pop();
if (!ladders.empty() && path.size() > ladders.back().size()) return;
if (path.back() == end) {
if (ladders.empty() || path.size() == ladders.back().size())
ladders.push_back(path);
}
vector<string> options = genChanges(path.back(), dict);
unordered_set<string> pathSet(path.begin(), path.end());
for (auto op_it = options.begin(); op_it != options.end(); ++op_it) {
if (pathSet.find(*op_it) == pathSet.end()) {
path.push_back(*op_it);
searchQ.push(path);
path.pop_back();
}
}
}
}
vector<string> genChanges(string origin, unordered_set<string>& dict) {
vector<string> changes;
for (int i = 0; i < origin.size(); ++i) {
string s(origin);
for (char c = 'a'; c <= 'z'; ++c) {
if (c != origin[i]) {
s[i] = c;
if (dict.find(s) != dict.end())
changes.push_back(s);
}
}
}
return changes;
}
};
int main() {
Solution s;
return 0;
}
| true |
dedf4c3e13eec8113d6cc636f5539ebc4932ba46 | C++ | yudeeeth/Pdfquestions | /week2/c4.cpp | UTF-8 | 636 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
void print(vector<vector<int>> &sol, int i, int j){
while(i>=0 && j<sol[0].size()){
cout<<sol[i][j]<<" ";
i--;
j++;
}
}
int main() {
//code
int n;
cin>>n;
for(int it=0;it<n;it++){
int k;
cin>>k;
vector<vector<int>> arr(k,vector<int>(k));
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
cin>>arr[j][i];
}
}
int i=0;
int j=0;
while(j<arr[0].size()){
print(arr,i,j);
if(i==arr.size()-1) j++;
else i++;
}
cout<<endl;
}
return 0;
} | true |
0d13e3a82416fe77b91e57c0dfa12c4f63d3d48b | C++ | metaphysis/Code | /Books/PCC2/10/10.2.1.2.cpp | UTF-8 | 1,591 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int MAXV = 1010;
int stk[MAXV], top, connected[MAXV][MAXV];
int cntOfVertices, cntOfEdges;
void printStack()
{
cout << "STACK:";
for (int i = 0; i < top; i++) cout << ' ' << stk[i] + 1;
cout << '\n';
}
void dfs(int x)
{
stk[top++] = x;
for (int i = 0; i < cntOfVertices; i++) {
if (connected[x][i]) {
connected[x][i] = connected[i][x] = 0;
dfs(i);
break;
}
}
}
void hierholzer(int u)
{
top = 0, stk[top++] = u;
while (top > 0) {
printStack();
int going = 1;
for (int i = 0; i < cntOfVertices; ++i)
if (connected[stk[top - 1]][i]) {
going = 0;
break;
}
if (going) cout << stk[--top] << ' ';
else dfs(stk[--top]);
}
cout << '\n';
}
int main(int argc, char *argv[])
{
while (cin >> cntOfVertices >> cntOfEdges) {
memset(connected, 0, sizeof (connected));
int x, y;
for (int i = 0; i < cntOfEdges; i++) {
cin >> x >> y;
x--, y--;
connected[x][y] = connected[y][x] = 1;
}
int u = 0, cntOfOddDegree = 0;
for (int i = 0; i < cntOfVertices; i++) {
int degree = 0;
for (int j = 0; j < cntOfVertices; j++) degree += connected[i][j];
if (degree % 2 == 1) u = i, cntOfOddDegree++;
}
if (cntOfOddDegree == 0 || cntOfOddDegree == 2) hierholzer(u);
else cout << "No Euler path.\n";
}
return 0;
}
| true |
a0541500ad7aa6b70af84bbc211340858fe5e752 | C++ | xingfeT/c-practice | /day-001-100/day-066/problem-1/main.cpp | UTF-8 | 3,045 | 3.71875 | 4 | [] | no_license | /*
*
* Here is a version of a problem called "the random walk." It can be extended to two or
* three dimensions, and used to simulate molecular motion, to determine the effectiveness
* of reactor shielding, or to calculate a variety of other probabilities.
*
* Assume that your very tired and sleepy dog leaves his favorite lamppost on a warm
* summer evenings and staggers randomly either two steps in the direction toward home
* or one step in the opposite direction. After taking these steps, the dog again staggers,
* randomly two steps toward home or one step backward, and does this again, and again. If
* the pet reaches a total distance of 10 steps from the lamppost in the direction toward
* home, you find him and take him home. If the dog arrives back at the lamppost before
* reaching 10 steps in the direction towards home, he lies down and spend the night at the
* foot of the lamppost.
*
* Write a C program that simulates 500 summer evenings, and calculates and print the percentage
* of the time your pet sleeps at home for these evenings. (Hint: In a loop determine forward
* or backward based on the value of a random number.) Accumulate the distance the dog has reached
* toward your home. If the distance reaches 10, stop the loop and increment the home count. If the
* distance reaches 0 before it reaches 10, stop the loop but do not increment the home count. Repeat
* this loop 500 times and find the ratio of (home count)/500.0.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define global_variable static
global_variable const int Forward_Step = 2;
global_variable const int Backward_Step = 1;
global_variable const int Finish_Steps = 10;
global_variable const int Total_Simulations = 500;
global_variable bool Simulating = true;
int
GenerateNumber();
bool
IsForward(int);
bool
IsCloseToHome(int);
int
main()
{
int randomNumber = 0;
int moveCount = 0;
int currentSteps = 0;
int homeCount = 0;
srand(time(NULL));
for (int i = 0; i < 500; ++i)
{
Simulating = true;
moveCount = 0;
currentSteps = 0;
while (Simulating)
{
randomNumber = GenerateNumber();
if (IsForward(randomNumber))
{
// two steps forward
currentSteps += Forward_Step;
}
else
{
// one step backward
currentSteps -= Backward_Step;
}
if (IsCloseToHome(currentSteps))
{
// yay - goes home
++homeCount;
Simulating = false;
}
else if ((currentSteps == 0) || (moveCount > Finish_Steps && currentSteps <= 0))
{
// end simulation
Simulating = false;
}
++moveCount;
}
}
printf("Sleeps at home %.2f%c", (((float)homeCount/(float)Total_Simulations) * 100.0f), '%');
return 0;
}
int
GenerateNumber()
{
int result;
result = (1 + (rand() % 10));
return (result);
}
bool
IsForward(int randomNumber)
{
bool result = (randomNumber >= 5) ? true : false;
return (result);
}
bool
IsCloseToHome(int stepCount)
{
bool result = (stepCount >= Finish_Steps) ? true : false;
return (result);
}
| true |
14c276d3c255f151c2c900dd42409cb31cb4e33e | C++ | weaverjm3/JW_info_450_spring_2019 | /week2/practice2.cpp | UTF-8 | 428 | 3.5625 | 4 | [] | no_license |
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int num;
while (i)
{
cout << "Please enter a number to find out if it is prime! (Enter 0 to quit): ";
cin >> num;
if ((num == 2) || (num % 2 != 0))
{
cout << "This is a prime number" << endl;
}
else if (num == 0)
{
break;
}
else if (num % 2 == 0)
{
cout << "This is not a prime number" << endl;
}
}
}
| true |
e627ecfd5fdac97fbfb148c4cbbd6746aae56cdd | C++ | jeafonso/cpp_projects | /CppND-System-Monitor/src/linux_parser.cpp | UTF-8 | 8,882 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <dirent.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <vector>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// DONE: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
// BONUS: Update this to use std::filesystem
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
float LinuxParser::MemoryUtilization() {
float freeMem, totalMem, retorno, value;
std::string key, linha;
std::ifstream stream(kProcDirectory + kMeminfoFilename);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> value){
if(key == "MemFree"){
freeMem = value * 0.001;
}
if(key == "MemTotal"){
totalMem = value * 0.001;
}
}
}
}
retorno = (totalMem - freeMem) / totalMem;
return retorno;
}
long LinuxParser::UpTime() {
std::string linha;
long retorno = 0;
long tempo;
std::ifstream stream(kProcDirectory + kUptimeFilename);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> tempo){
retorno = tempo;
return retorno;
}
}
}
return retorno;
}
long LinuxParser::Jiffies() {
long idleJiffies = LinuxParser::IdleJiffies();
long activeJiffies = LinuxParser::ActiveJiffies();
return idleJiffies + activeJiffies;
}
long LinuxParser::ActiveJiffies(int pid) {
std::string linha, path, value;
path = kProcDirectory + "/" + std::to_string(pid) + kStatFilename;
long retorno, utime, stime, cutime, cstime;
int counter = 1;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(counter != 14){
line >> value;
counter++;
}
line >> utime >> stime >> cutime >> cstime;
break;
}
}
retorno = (utime + stime + cutime + cstime) / sysconf(_SC_CLK_TCK);
return retorno;
}
long LinuxParser::ActiveJiffies() {
std::string linha, path, value, key;
path = kProcDirectory + kStatFilename;
long retorno;
long user, nice, system, idle, iowait, irq, softirq, steal, active;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> user >> nice >> system >> idle >> iowait >>
irq >> softirq >> steal){
if (key == "cpu") {
active = user + nice + system + irq + softirq + steal;
}
}
}
}
retorno = active / sysconf(_SC_CLK_TCK);
return retorno;
}
long LinuxParser::IdleJiffies() {
std::string linha, path, value, key;
path = kProcDirectory + kStatFilename;
long retorno;
long user, nice, system, idle, iowait, irq, softirq, steal, idleTime;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> user >> nice >> system >> idle >> iowait >>
irq >> softirq >> steal){
if (key == "cpu") {
idleTime = idle + iowait;
}
}
}
}
retorno = idleTime / sysconf(_SC_CLK_TCK);
return retorno;
}
vector<string> LinuxParser::CpuUtilization() {
std::vector<std::string> retorno;
std::string linha, key, value;
std::ifstream stream(kProcDirectory + kStatFilename);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key){
if(key == "cpu"){
line >> value;
retorno.push_back(value);
return retorno;
}
}
}
}
return retorno;
}
int LinuxParser::TotalProcesses() {
int retorno = 0;
int value;
std::ifstream stream(kProcDirectory + kStatFilename);
std::string linha, key;
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> value){
if(key == "processes"){
retorno = value;
return retorno;
}
}
}
}
return retorno;
}
int LinuxParser::RunningProcesses() {
int retorno = 0;
int value;
std::ifstream stream(kProcDirectory + kStatFilename);
std::string linha;
std::string key;
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> value){
if(key == "procs_running"){
retorno = value;
return retorno;
}
}
}
}
return retorno;
}
string LinuxParser::Command(int pid) {
std::string retorno, path, linha, value;
path = kProcDirectory + "/" + std::to_string(pid) + kCmdlineFilename;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> value){
retorno = value;
return retorno;
}
}
}
return retorno;
}
string LinuxParser::Ram(int pid) {
std::string retorno, path, linha, key;
path = kProcDirectory + std::to_string(pid) + kStatusFilename;
int ramAux;
float value;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> value){
if(key == "VmSize:"){
ramAux = value * 0.001;
retorno = to_string(ramAux);
return retorno;
}
}
}
}
return retorno;
}
string LinuxParser::Uid(int pid) {
std::string retorno, path, linha, key, value;
path = kProcDirectory + std::to_string(pid) + kStatusFilename;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> key >> value){
if(key == "Uid:"){
retorno = value;
return retorno;
}
}
}
}
return retorno;
}
string LinuxParser::User(int pid) {
std::string retorno, path, linha, key, value, lixo, uId;
path = kPasswordPath;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::replace(linha.begin(), linha.end(), ':', ' ');
std::istringstream line(linha);
while(line >> value >> lixo >> key){
if(key == Uid(pid)){
retorno = value;
return retorno;
}
}
}
}
return retorno;
}
long LinuxParser::UpTime(int pid) {
long retorno = 0;
std::string path, linha, value;
int counter = 1;
long upTime;
path = kProcDirectory + "/" + std::to_string(pid) + kStatFilename;
std::ifstream stream(path);
if(stream.is_open()){
while(std::getline(stream, linha)){
std::istringstream line(linha);
while(line >> value){
if(counter == 21){
break;
}
counter++;
}
line >> upTime;
}
}
retorno = upTime / sysconf(_SC_CLK_TCK);
return retorno;
} | true |
436e7b8582a4a4bed3a05cf083bfa007bb3411eb | C++ | EngravedMemories/guo_jiacheng | /郭佳承 3-6 第二章作业/2.19/main.cpp | UTF-8 | 445 | 3.765625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a=0, b=0, c=0, sum=0, ave=0, pro=0;
cout <<"Input three different integers: ";
cin >>a>>b>>c;
sum=a+b+c;
ave=sum/3;
pro=a*b*c;
cout <<"Sum is "<<sum<<endl;
cout <<"Average is "<<ave<<endl;
cout <<"Product is "<<pro<<endl;
cout <<"Smallest is "<<min(min(a, b), c)<<endl;
cout <<"Largest is "<<max(max(a, b), c)<<endl;
}
| true |
21eaeebf23a0a62dcf4e15db4112f53b827a6a6c | C++ | LeeWooSang/Capstone_Design_TeamProject | /Server/2019-1GameServerProgramming/FrameWork/FrameWork/Sprite.cpp | UHC | 3,492 | 2.8125 | 3 | [] | no_license | #include "Sprite.h"
Sprite::Sprite()
{
Index = 0; // ʱȭ ڿ?
}
Sprite::~Sprite()
{
for (int i = 0; i < MAX_BMP; ++i)
{
if (BmpData[i].Bitmap != NULL)
DeleteObject(BmpData[i].Bitmap);
}
}
void Sprite::Entry(int Num, const char* path, int x, int y)
{
BITMAP TmpBit; // ̹ ̿ ʺ Ƽ Ѱֱ
BmpData[Num].Bitmap = (HBITMAP)LoadImage(NULL, path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); // ش ̹ ֱ
GetObject(BmpData[Num].Bitmap, sizeof(BITMAP), &TmpBit);
BmpData[Num].height = TmpBit.bmHeight;
BmpData[Num].width = TmpBit.bmWidth;
BmpData[Num].x = x;
BmpData[Num].y = y;
//GetObject(BmpData->Bitmap, sizeof(int), &BmpData[Num].width);
Index++; // Ʈ ̹ ÷ش.
}
void Sprite::Render(HDC* hdc, int Num)
{
HDC TmpDC = CreateCompatibleDC(*hdc);
HBITMAP m_oldbitmap = (HBITMAP)SelectObject(TmpDC, BmpData[Num].Bitmap);
BitBlt(*hdc, BmpData[Num].x, BmpData[Num].y, BmpData[Num].width, BmpData[Num].height, TmpDC, 0, 0, SRCCOPY);
DeleteDC(TmpDC);
DeleteObject(m_oldbitmap);
}
void Sprite::Render(HDC* hdc, int Num, UINT color)
{
HDC TmpDC = CreateCompatibleDC(*hdc);
HBITMAP m_oldbitmap = (HBITMAP)SelectObject(TmpDC, BmpData[Num].Bitmap);
TransparentBlt(*hdc, BmpData[Num].x, BmpData[Num].y, BmpData[Num].width, BmpData[Num].height, TmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height, color);
DeleteDC(TmpDC);
DeleteObject(m_oldbitmap);
}
void Sprite::Render(HDC* hdc, int Num, UINT color, float a)
{
BLENDFUNCTION bf;
bf.AlphaFormat = 0;
bf.BlendFlags = 0;
bf.BlendOp = AC_SRC_OVER;
bf.SourceConstantAlpha = (int)(a * 255.0f);
HDC TmpDC = CreateCompatibleDC(*hdc);
HDC AlphaTmpDC = CreateCompatibleDC(*hdc);
HBITMAP hBackBit = CreateCompatibleBitmap(*hdc, BmpData[Num].width, BmpData[Num].height);
HBITMAP m_oldbitmap = (HBITMAP)SelectObject(AlphaTmpDC, hBackBit);
HBITMAP m_oldbitmap1 = (HBITMAP)SelectObject(TmpDC, BmpData[Num].Bitmap);
BitBlt(AlphaTmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height, *hdc, BmpData[Num].x, BmpData[Num].y, SRCCOPY);
TransparentBlt(AlphaTmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height, TmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height, color);
AlphaBlend(*hdc, BmpData[Num].x, BmpData[Num].y, BmpData[Num].width, BmpData[Num].height, AlphaTmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height,bf);
//AlphaBlend()
DeleteDC(TmpDC);
DeleteDC(AlphaTmpDC);
DeleteObject(m_oldbitmap);
DeleteObject(m_oldbitmap1);
DeleteObject(hBackBit);
}
void Sprite::Render(HDC* hdc, int Num, float a)
{
BLENDFUNCTION bf;
bf.AlphaFormat = 0;
bf.BlendFlags = 0;
bf.BlendOp = AC_SRC_OVER;
bf.SourceConstantAlpha = (int)(a * 255.0f);
HDC AlphaTmpDC = CreateCompatibleDC(*hdc);
HBITMAP hBackBit = (HBITMAP)SelectObject(AlphaTmpDC, BmpData[Num].Bitmap);
AlphaBlend(*hdc, BmpData[Num].x, BmpData[Num].y, BmpData[Num].width, BmpData[Num].height, AlphaTmpDC, 0, 0, BmpData[Num].width, BmpData[Num].height, bf);
DeleteDC(AlphaTmpDC);
DeleteObject(hBackBit);
}
void Sprite::setLocation(int Num, int x, int y)
{
BmpData[Num].x = x;
BmpData[Num].y = y;
}
int Sprite::getX(int Num) { return BmpData[Num].x; }
int Sprite::getY(int Num) { return BmpData[Num].y; }
int Sprite::getWidth(int Num) { return BmpData[Num].width; }
int Sprite::getHeight(int Num) { return BmpData[Num].height; }
int Sprite::getIndex() { return Index; }
| true |
d970098855052043e1d5cc90ad0aceb5822b47e6 | C++ | Alice105973/PriorityQueues | /modules/PriorityQueues/src/ThinHeap.cpp | WINDOWS-1251 | 9,702 | 3.171875 | 3 | [] | no_license | #include <vector>
#include <cmath>
#include <cstddef>
#include <climits>
#include <iostream>
#include "../include/ThinHeap.h"
vector<int> Thin_Dijkstra(const vector < vector<pair<int, int>>>& graph) {
ThinHeap q;
vector<ThinElem> data(graph.size());
ThinElem a(0, 0);
data[0] = a;
q.insert(&data[0]);
for (size_t i = 1; i < graph.size(); i++) {
ThinElem c(i, INT_MAX);
data[i] = c;
q.insert(&data[i]);
} //
vector<int> S(graph.size()); // , dist
while (!q.isEmpty()) {
pair<int, int> v = q.extractMin(); // , (, )
S[v.first] = v.second; //
int amount = graph[v.first].size(); //
for (int i = 0; i < amount; i++) { //
int unum = graph[v.first][i].first; // i- v
q.relax(v.second, &data[unum], graph[v.first][i].second);
}
}
return S;
}
bool ThinElem::br_violation() {
if (this == NULL) return false;
if (left == NULL) //
return false;
if (right == NULL) //
if (rank == 1) // 1
return true;
else return false;
if (rank == right->rank + 2) // 2
return true;
return false;
}
bool ThinElem::p_violation() {
if (this == NULL) return false;
if (left == NULL)
if (isThin()) { // -
return true;
}
if (child == NULL) {
if (rank == 2) // = 2
{
return true;
}
else {
return false;
}
}
if (rank == child->rank + 3) { // 3
return true;
}
return false;
}
ThinElem* ThinElem::parent() {
if (left == NULL) // -
return NULL; //
ThinElem* x = this;
ThinElem* y = left;
while (y->child != x) {
x = y;
y = x->left;
}
return y;
}
void ThinElem::link(ThinElem* A) {
A->left = this; //
A->right = child; //
if (child != NULL)
child->left = A;
child = A; //
rank++; //
}
bool ThinElem::isThin() {
if (rank == 0) // 0
return false;
if (rank == 1) // = 1 -
return (child == NULL);
else // 2 ,
return (child->rank + 1) != rank;
}
void ThinHeap::insert(ThinElem* x) {
n++; //
x->left = NULL; //
x->right = NULL;
if (x->child == NULL)
x->rank = 0;
else x->rank = x->child->rank + 1;
if (first == NULL) { //
first = x; // x
last = x; //
}
else {
if (x->weight < first->weight) { // x
x->right = first; //
first = x; //
}
else {
last->right = x; //
last = x; //
}
}
}
pair<int, int> ThinHeap::extractMin() {
if (n == 1) { //
n--; //
ThinElem* tmp = first;
first = NULL;
last = NULL;
return pair<int, int>(tmp->num, tmp->weight); //
}
ThinElem* tmp = first;
n--;
ThinElem* nextx = NULL;
int max = -1;
first = first->right; //
if (first == NULL) //
last = NULL;
ThinElem* x = tmp->child; //
while (x != NULL) { //
if (x->isThin()) //
x->rank--; //
ThinElem* nextx = x->right;
insert(x); //
n--;
x = nextx; //
}
x = first; //
vector<ThinElem*> A(static_cast<size_t>(ceil(log2(n)) + 3), NULL); //
// i i
while (x != NULL) { //
nextx = x->right;
while (A[x->rank] != NULL) { //
if (A[x->rank]->weight < x->weight) // - x
swap(A[x->rank], x);
x->link(A[x->rank]); //
A[x->rank - 1] = NULL; //
}
A[x->rank] = x; //
if (x->rank > max) //
max = x->rank;
x = nextx;
}
//
first = NULL; //
last = NULL;
for (int i = 0; i <= max; i++)
if (A[i] != NULL) {
insert(A[i]); //
n--; // n
}
tmp->left = NULL;
tmp->right = NULL;
tmp->child = NULL;
return pair<int, int>(tmp->num, tmp->weight);
}
void ThinHeap::decreaseKey(ThinElem* x, int newWeight) {
if (newWeight > x->weight) return;
x->weight = newWeight; //
ThinElem* l = x->left;
if (x == first) // ()
return; //
if (l == NULL) { // x - ,
ThinElem* z = first;
while (z->right != x) {
z = z->right; //
}
if (x == last) // x -
last = z; // z
z->right = x->right; // x
insert(x); // ( )
n--; // n
return; //
}
if (x->weight >= x->parent()->weight) //
return; //
if (l->child == x) // x -
l->child = x->right; // x
else // x -
x->left->right = x->right;
if (x->right != NULL)
x->right->left = x->left;
insert(x); // x
n--; // n
while (l->br_violation() || l->p_violation())
{ //
//
while (l->br_violation() && l != NULL) {
if (l->isThin() == false) { //
ThinElem* ch = l->child; //
if (ch != NULL) {
l->child = ch->right; //
if (l->child != NULL)
l->child->left = l;
if (l->right != NULL)
l->right->left = ch;
ch->right = l->right;
l->right = ch;
ch->left = l;
}
}
else
l->rank--;
l = l->left;
}
//
while (l->p_violation() && l != NULL) {
if (l->left == NULL) { // l -
if (l->child == NULL) // 1
l->rank = 0;
else
l->rank = l->child->rank + 1;
l = NULL;
break;
}
ThinElem* le = l->left; // y
if (le->child == l)
le->child = l->right;
else
le->right = l->right;
if (l->right != NULL)
l->right->left = le;
insert(l);
n--;
l = le;
}
}
}
void ThinHeap::relax(int vweight, ThinElem* u, int uvweight) {
if (vweight + uvweight < u->weight) { //
decreaseKey(u, vweight + uvweight); //
}
}
| true |
728988e93f9280b949b9fae29935462517f4f641 | C++ | ditsing/plain-interpreter-guide | /8-interpreter/interpreter.h | UTF-8 | 2,056 | 2.921875 | 3 | [] | no_license | #ifndef INTERPRETER_H
#define INTERPRETER_H
#include <string>
#include <map>
#include <vector>
#include <stdexcept>
#include <memory>
#include "arith_expr.h"
#include "variable.h"
class Statement;
class Program;
class Program {
std::map<std::string, Variable> variable_map;
std::vector<std::unique_ptr<const Statement>> statements;
public:
const Variable &lookup_variable(const std::string &name) const;
Variable &lookup_variable(const std::string &name);
bool defined_variable(const std::string &name) const;
Variable &create_variable(const std::string &name, Expr::Type type);
void append_statement(const Statement *st);
void run();
};
class Statement {
public:
virtual void run() const = 0;
virtual ~Statement() {}
};
class Assignment: public Statement {
const std::string identifier;
const std::unique_ptr<const Expr> expr;
Variable &var;
public:
Assignment(
const std::string &&identifier,
const Expr *expr,
Variable &var) : identifier(identifier), expr(expr), var(var) {}
void run() const override;
};
class PrintStatement: public Statement {
const std::unique_ptr<const Expr> expr;
public:
PrintStatement(const Expr *expr) : expr(expr) {}
void run() const override;
};
#define THROW_ERROR_FORMAT(error_type, ...) {\
char *error_msg; \
asprintf(&error_msg, __VA_ARGS__); \
throw error_type(error_msg); \
}
#define THROW_ERROR_FORMAT_LINE(error_type, token, ...) {\
char *error_msg; \
asprintf(&error_msg, __VA_ARGS__); \
char *error_msg_2; \
asprintf(&error_msg_2, "%s at line %d column %d.", error_msg, token.line, token.column); \
throw error_type(error_msg_2); \
}
class CompilingError: public std::logic_error {
public:
CompilingError(const std::string &what) : std::logic_error(what) {}
CompilingError(const char *what) : std::logic_error(what) {}
};
class RuntimeError: public std::logic_error {
public:
RuntimeError(const std::string &what) : std::logic_error(what) {}
RuntimeError(const char *what) : std::logic_error(what) {}
};
#endif
| true |
094139f88eae52b012337741fe5cf0448965cfb5 | C++ | atioi/Iterative-methods | /Jacobi.cpp | UTF-8 | 1,882 | 3.046875 | 3 | [] | no_license | #include "other.h"
#include "estimator.h"
#include "residuum.h"
#include <iostream>
void Jacobi(double *A, int size, double *b, double *x_initial) {
double M[size * size];
double C[size];
/* Wzór operacyjny:
*
* x_next = - 1 / D * ( L + U ) * x_before + 1 / D * b
* M = - 1 / D * (L+U)
* C = 1/D * b
* x_next = M * x_before + C
*
* */
for (int n = 0; n < size; n++)
C[n] = b[n] / A[n * (size + 1)];
for (int k = 0; k < size; k++)
for (int j = 0; j < size; j++) {
int diag_index = k * (size + 1);
int i = j + (k * size);
M[i] = -A[i] / A[diag_index];
M[diag_index] = 0;
}
std::cout << std::endl << "M matrix:" << std::endl;
print_matrix(M, size);
std::cout << std::endl << "C vector: " << std::endl;
print_vector(C, size);
// Parameters:
int n_max = 10; // Maximum number of iterations
double TOLX = 1e-9; // Given error tolerance
double TOLF = 1e-9; // Given residuum tolerance
double residuum = 0.0;
double estimator = 0.0;
double x_next[size];
double *x_before = x_initial;
// Main loop:
for (int n = 0; n < n_max; n++) {
// Calculate x_next:
for (int k = 0; k < size; k++) {
x_next[k] = 0;
for (int j = 0; j < size; j++) {
int i = j + (k * size);
x_next[k] += (M[i] * x_before[j]);
}
x_next[k] += C[k];
}
residuum = calc_residuum(A, b, x_next, size);
estimator = calc_estimator(x_next, x_before, size);
print_results(n, x_next, size, residuum, estimator);
if (residuum <= TOLF && estimator <= TOLX)
break;
// Copy x_next to x_before:
for (int i = 0; i < size; i++)
x_before[i] = x_next[i];
}
}
| true |
cab542d8b3593075b9eacc87d679919ad3a570ff | C++ | wenzhuow/CS165 | /CS165/project1/shell_sort.cpp | UTF-8 | 518 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "project1.h"
void shell_sort(vector<int>& a, const vector<int>& gaps)
{
int n = a.size();
for (int index=0;index<gaps.size();index++)
{
int gap = gaps[index];
for (int i = gap; i < n; i ++)
{
int temp = a[i];
int j;
for (j = i; j >= gap && a[j - gap] > temp; j -= gap)
a[j] = a[j - gap];
a[j] = temp;
}
}
}
| true |
9ec03f9dbeb2176068c4665c7d0c966841ec69d5 | C++ | ldhshao/mylearnings | /qtlearnings/tabletest1/fruitmodel.cpp | UTF-8 | 1,747 | 2.96875 | 3 | [] | no_license | #include "fruitmodel.h"
#include <QtDebug>
///fruit
Fruit::Fruit(const QString &name, const float &price)
: m_name(name), m_price(price)
{
}
QString Fruit::name() const
{
return m_name;
}
float Fruit::price() const
{
return m_price;
}
void Fruit::setPrice(const float &price)
{
m_price = price;
}
///FruitModel
FruitModel::FruitModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void FruitModel::addFruit(const Fruit &animal)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_fruits << animal;
endInsertRows();
}
int FruitModel::rowCount(const QModelIndex & parent) const {
Q_UNUSED(parent);
return m_fruits.count();
}
QVariant FruitModel::data(const QModelIndex & index, int role) const {
if (index.row() < 0 || index.row() >= m_fruits.count())
return QVariant();
const Fruit &fruit = m_fruits[index.row()];
if (role == NameRole)
return fruit.name();
else if (role == PriceRole)
return QString("%1").arg(fruit.price(), 0, 'f', 2);
return QVariant();
}
void FruitModel::update(){
//qDebug()<<"update";
if (m_fruits.count() > 0)
{
Fruit &ft = m_fruits[0];
float fPrice = ft.price();
float fStep = 0.1;
static float fSign = 1;
if (fPrice >= 5.0)
fSign = -1;
else if (fPrice <= 2.5)
fSign = 1;
ft.setPrice(fPrice + fSign*fStep);
qDebug()<<"update: "<<ft.name()<<" "<<ft.price();
}
}
//![0]
QHash<int, QByteArray> FruitModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[PriceRole] = "cost";
return roles;
}
| true |
cafb618c70d18ab11e03aba8190184954c9037d1 | C++ | AmitBu/scrolleg-bluetooth-control | /ScrolLeg-HID.ino | UTF-8 | 3,235 | 2.859375 | 3 | [] | no_license | /**
* ScrolLeg - Arduino controlled bluetooth device, that lets you scroll with your legs
*
* Device contains 2 buttons and WT12 bluetooth chip
* Each buttons sends a different command to the blueooth chip,
* One for scroll up, one for down.
*
*
*/
#include <avr/pgmspace.h>
/**
* Up/Down button pin numbers
*/
#define UP_BUTTON 2
#define DOWN_BUTTON 4
/**
* WT12 Reset pin connection
*/
#define WT12_RESET 7
/**
* WT12 Setting
* Will run on setup()
*/
const char wt12_init_0[] PROGMEM = "SET BT NAME ScrolLeg";
const char wt12_init_1[] PROGMEM = "SET BT CLASS 00540";
const char wt12_init_2[] PROGMEM = "SET BT SSP 3 0";
const char wt12_init_3[] PROGMEM = "SET CONTROL AUTOCALL 0011 500 HID";
#define NUM_INIT_MSG 4
// http://forum.arduino.cc/index.php?topic=272313.0
// Initialize flash commands
PGM_P const string_table[] PROGMEM {
wt12_init_0,
wt12_init_1,
wt12_init_2,
wt12_init_3
};
char buffer[60]; // used for printing these init messages
// The Mouse HID command prefix, as hex array
const byte packetPrefix[] = { 0x9F, 0x05, 0xA1, 0x01 };
// Up/Down commands translated to hex array
byte MOUSE_UP[] = { 0x10, 0x00, 0x00 };
byte MOUSE_DOWN[] = { 0xF0, 0x00, 0x00 };
/**
* Communicates with BT chip in Serial
* Sends the entire packet, each byte in `Serial.write`
*/
void sendMousePacket(byte * packetExtra) {
// TODO: Check why loop doesn't work here
// Send the mouse HID packet prefix
Serial.write((byte)packetPrefix[0]);
Serial.write((byte)packetPrefix[1]);
Serial.write((byte)packetPrefix[2]);
Serial.write((byte)packetPrefix[3]);
// Sends the actual mouse action
Serial.write((byte)packetExtra[0]);
Serial.write((byte)packetExtra[1]);
Serial.write((byte)packetExtra[2]);
}
/**
* Scroll up command wrapper
* Send BT scroll up packet
*/
void mouseScrollUp() {
sendMousePacket(MOUSE_UP);
}
/**
* Scroll down command wrapper
* Send BT scroll up packet
*/
void mouseScrollDown() {
sendMousePacket(MOUSE_DOWN);
}
void log(String message) {
//Serial.println(message);
}
/**
* Checks button press
* Sends wanted commands to BT accrordingly
*/
void buttonActivity() {
// Up button pressed
if (digitalRead(UP_BUTTON) == HIGH) {
log("Up pressed");
mouseScrollUp();
}
// Down button pressed
else if (digitalRead(DOWN_BUTTON) == HIGH) {
log("Down pressed");
mouseScrollDown();
}
}
/**
* Starting bluetooth chip actions
*/
void initBluetooth() {
// Reset the WT12 module on startup, in case something gets stuck
pinMode(WT12_RESET, OUTPUT);
digitalWrite(WT12_RESET, HIGH);
delay(10);
digitalWrite(WT12_RESET, LOW);
log("\n\n");
delay(1000);
// Runs the startup commands that we defined above, on the bluetooth chip
for (byte i = 0; i < NUM_INIT_MSG; i++) {
strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i])));
Serial.println(buffer);
delay(100);
}
delay(1000);
Serial.flush();
log("RESET");
}
void setup() {
Serial.begin(115200);
pinMode(UP_BUTTON, INPUT_PULLUP);
pinMode(DOWN_BUTTON, INPUT_PULLUP);
initBluetooth();
}
void loop() {
buttonActivity();
delay(200);
}
| true |
796b5f03c21278dd667d4511e61ba31da070e297 | C++ | aliasad059/lonely_cells | /lonely_cells/cells_operations.cpp | UTF-8 | 6,275 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <graphics.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include "structs.h"
#include"linklists_operations.h"
void move_fun(struct cells * player,int cell_num,struct map_attribute *bin_map,int n){
system("cls");
struct cells_el * player_copy = player->head;
for (int i = 1 ; i< cell_num ; i++ , player_copy = player_copy ->next);
int choice;
printf("[1]North\n[2]South\n[3]Northeast\n[4]Northwest\n[5]Southeast\n[6]Southwest\n");
scanf("%d",&choice);
if (choice == 1) {
if( bin_map[(player_copy->cell->y - 1)*n +player_copy->cell->x].type == '3' ) {printf("Can not move to forbidden place\n") ;Sleep(2000);return;}
(player_copy ->cell-> y )--;
}
else if (choice == 2) {
if( bin_map[(player_copy->cell->y + 1)*n +player_copy->cell->x].type == '3' ) {printf("Can not move to forbidden place\n"); Sleep(2000);return;}
(player_copy ->cell-> y )++;
}
else if (choice == 3) {
if( bin_map[(player_copy->cell->y - 1)*n +player_copy->cell->x + 1].type == '3' ) {printf("Can not move to forbidden place\n"); Sleep(2000);return;}
if ( player_copy->cell->x %2 == 0){(player_copy ->cell-> y )-- ;(player_copy ->cell-> x )++ ;}
else if ( player_copy->cell->x %2 == 1)(player_copy ->cell-> x )++ ;
}
else if (choice == 4) {
if( bin_map[(player_copy->cell->y - 1)*n +player_copy->cell->x - 1].type == '3' ) {printf("Can not move to forbidden place\n");Sleep(2000); return;}
if ( player_copy->cell->x %2 == 0){(player_copy ->cell-> y )-- ;(player_copy ->cell-> x )-- ;}
else if ( player_copy->cell->x %2 == 1)(player_copy ->cell-> x )-- ;
}
else if (choice == 5) {
if( bin_map[(player_copy->cell->y + 1)*n +player_copy->cell->x + 1].type == '3' ) {printf("Can not move to forbidden place\n") ;Sleep(2000);return;}
if ( player_copy->cell->x %2 == 1){(player_copy ->cell-> y )++ ;(player_copy ->cell-> x )++ ;}
else if ( player_copy->cell->x %2 == 0)(player_copy ->cell-> x )++ ;
}
else if (choice == 6) {
if( bin_map[(player_copy->cell->y + 1)*n +player_copy->cell->x - 1].type == '3' ) {printf("Can not move to forbidden place\n") ;Sleep(2000);return;}
if ( player_copy->cell->x %2 == 1){(player_copy ->cell-> y )++ ;(player_copy ->cell-> x )-- ;}
else if ( player_copy->cell->x %2 == 0)(player_copy ->cell-> x )-- ;
}
}
void split_fun(struct cells * player , int cell_num,struct map_attribute *bin_map,int n){
struct cells_el * player_copy = player->head;
for (int i = 1 ; i < cell_num ; i++, player_copy = player_copy->next);
if ( bin_map[player_copy->cell->y * n + player_copy->cell->x].type != '2' ){printf("You are not at mitosis place\n");Sleep(2000);return;}
else if(player_copy->cell->point < 80) {printf("Not enough energy\n");Sleep(2000);return;}
else{
struct cell* new_cell1 = (struct cell *)malloc(sizeof(struct cell ));
struct cell* new_cell2 = (struct cell *)malloc(sizeof(struct cell ));
new_cell1->x = player_copy->cell->x; new_cell1->y = player_copy->cell->y;
cells_remove(player,cells_search_coordinate(player, player_copy ->cell->x, player_copy->cell->y ));
char cell1_name[15] ,cell2_name[15];
printf("Enter name of the first cell\n");
getchar();
gets(cell1_name);
printf("Enter name of the second cell\n");
gets(cell2_name);
strcpy(new_cell1->name,cell1_name);
strcpy(new_cell2->name,cell2_name);
new_cell1->point = 40;
new_cell2->point = 40;
printf("Choose location of %s compared to %s:\n[1]North\n[2]South\n[3]Northeast\n[4]Northwest\n[5]Southeast\n[6]Southwest\n",new_cell2->name,new_cell1->name);
int choice;
scanf("%d",&choice);
if (choice == 1) {
new_cell2->y = (new_cell1 -> y )-1;new_cell2->x = (new_cell1 -> x );
}
if (choice == 2) {
new_cell2->y = (new_cell1 -> y )+1;new_cell2->x = (new_cell1 -> x );
}
if (choice == 3) {
if(new_cell1->x %2 == 0){new_cell2->y = new_cell1 -> y - 1; new_cell2->x = new_cell1 -> x +1 ;}
else{new_cell2->y = new_cell1 -> y ; new_cell2->x = new_cell1 -> x +1 ;}
}
if (choice == 4) {
if(new_cell1->x %2 == 0){new_cell2->y = new_cell1 -> y - 1; new_cell2->x = new_cell1 -> x -1 ;}
else{new_cell2->y = new_cell1 -> y ; new_cell2->x = new_cell1 -> x -1 ;}
}
if (choice == 5) {
if(new_cell1->x %2 == 1){new_cell2->y = new_cell1 -> y + 1; new_cell2->x = new_cell1 -> x +1 ;}
else{new_cell2->y = new_cell1 -> y ; new_cell2->x = new_cell1 -> x +1 ;}
}
if (choice == 6) {
if(new_cell1->x %2 == 1){new_cell2->y = new_cell1 -> y + 1; new_cell2->x = new_cell1 -> x -1 ;}
else{new_cell2->y = new_cell1 -> y ; new_cell2->x = new_cell1 -> x -1 ;}
}
cells_push_back(player,new_cell1);
cells_push_back(player,new_cell2);
}
}
void boost_fun(struct cells * player , int cell_num,struct map_attribute *bin_map,int n){
struct cells_el * player_copy = player->head;
for(int i = 1 ; i< cell_num ; i++ ,player_copy = player_copy->next);
if(bin_map[player_copy->cell->y * n + player_copy->cell->x].type != '1'){printf("You are not at energy place\n");Sleep(2000); return;}
printf("Energy of this place is : %d\n",bin_map[player_copy->cell->y * n + player_copy->cell->x].point);
printf("How much energy do you want ? (at most 15 energy each time)\n");
int energy;
scanf("%d",&energy);
if(energy > 15) {printf("You are can get energy at most 15 each time\n"); Sleep(2000);return;}
if(bin_map[player_copy->cell->y * n + player_copy->cell->x].point < energy) {printf("Not enough energy \n");Sleep(2000); return;}
player_copy->cell->point += energy;
bin_map[player_copy->cell->y * n + player_copy->cell->x].point -= energy;
};
| true |
c5fc4bb9c1f9db5e02fd3c2350911ab7066b1e24 | C++ | golapraj/uva | /uva generating fast.cpp | UTF-8 | 553 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
bool fun(char a,char b)
{
if(tolower(a)==tolower(b))
return a<b;
return tolower(a)<tolower(b);
}
int main()
{
freopen("in.txt","r",stdin);
int l,t;
char s[10000];
scanf("%d",&t);
getchar();
while(t--)
{
gets(s);
l=strlen(s);
sort(s,s+l,fun);
printf("%s\n",s);
while(next_permutation(s,s+l))
printf("%s\n",s);
printf("\n");
}
return 0;
}
| true |
5c6f8cc7bed584ce0d65b409d0675dc52df7fe4f | C++ | firoorg/firo | /src/sigma/sigmaplus_proof.h | UTF-8 | 1,969 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef FIRO_SIGMA_SIGMAPLUS_PROOF_H
#define FIRO_SIGMA_SIGMAPLUS_PROOF_H
#include "params.h"
#include "r1_proof.h"
namespace sigma {
template<class Exponent, class GroupElement>
class SigmaPlusProof {
public:
int n;
int m;
GroupElement B_;
R1Proof<Exponent, GroupElement> r1Proof_;
std::vector<GroupElement> Gk_;
Exponent z_;
public:
SigmaPlusProof(int n, int m): n(n), m(m) {};
public:
bool operator==(const SigmaPlusProof& other) const {
return n == other.n &&
m == other.m &&
B_ == other.B_ &&
r1Proof_ == other.r1Proof_ &&
Gk_ == other.Gk_ &&
z_ == other.z_;
}
bool operator!=(const SigmaPlusProof& other) const {
return !(*this == other);
}
public:
inline int memoryRequired() const {
return B_.memoryRequired()
+ r1Proof_.memoryRequired(n, m)
+ B_.memoryRequired() * m
+ z_.memoryRequired();
}
inline unsigned char* serialize(unsigned char* buffer) const {
unsigned char* current = B_.serialize(buffer);
current = r1Proof_.serialize(current);
for (std::size_t i = 0; i < Gk_.size(); ++i)
current = Gk_[i].serialize(current);
return z_.serialize(current);
}
inline unsigned const char* deserialize(unsigned const char* buffer) {
unsigned const char* current = B_.deserialize(buffer);
current = r1Proof_.deserialize(current, n, m);
Gk_.resize(m);
for(int i = 0; i < m; ++i)
current = Gk_[i].deserialize(current);
return z_.deserialize(current);
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(B_);
READWRITE(r1Proof_);
READWRITE(Gk_);
READWRITE(z_);
}
};
} //namespace sigma
#endif // FIRO_SIGMA_SIGMAPLUS_PROOF_H
| true |
77dcf8e5bf6a35f0bd7a71575f19c800e5a1c9c2 | C++ | EndysGit/GraphicProject | /source/headers/Vertex.h | UTF-8 | 2,042 | 2.796875 | 3 | [] | no_license | //
// Created by Gleb Vorfolomeew on 27/08/2017.
//
#ifndef TEXTUREOGL_VERTEX_H
#define TEXTUREOGL_VERTEX_H
#include <map>
#include <vector>
#include "source/headers/ServiceGLEnum.h"
#include <exception>
class ConversionFail : public std::exception
{
public:
ConversionFail();
ConversionFail(const char* exception_message);
ConversionFail(const std::string &exception_message);
ConversionFail(const ConversionFail &conversionFail);
virtual ~ConversionFail();
virtual const char* what() const _NOEXCEPT override;
private:
std::string m_exception_message;
};
class Vertex_base
{
protected:
Vertex_base();
virtual ~Vertex_base();
virtual void addAttribute(AttributeType type, const std::vector<float> &attribute);
virtual void addAttribute(AttributeType type);
virtual void removeAttribute(AttributeType type);
virtual std::vector<float>& getAttribute(AttributeType type);
virtual bool equal(const Vertex_base& vertex) const;
virtual bool empty() const;
};
class Vertex : public Vertex_base
{
public:
Vertex();
explicit Vertex(AttributeType type);
Vertex(AttributeType type, const std::vector<float> &attribute);
Vertex(const Vertex &vertex);
virtual ~Vertex() override;
virtual void addAttribute(AttributeType type, const std::vector<float> &attribute) override;
virtual void addAttribute(AttributeType type) override;
virtual void removeAttribute(AttributeType type) override;
virtual std::vector<float>& getAttribute(AttributeType type) override;
virtual bool equal(const Vertex_base& vertex) const override ;
virtual bool empty() const override;
private:
std::map<AttributeType, std::vector<float> > m_labeled_vertex;
};
// TODO: Check and refactor
// architectural mistakes:
// because of dynamic_cast int "equal" function
// second argument here can't be const reference
bool operator==(const Vertex &vertex1, const Vertex &vertex2);
bool operator!=(const Vertex &vertex1, const Vertex &vertex2);
#endif //TEXTUREOGL_VERTEX_H
| true |
aca30308acae0eda3d7347cf7e8e546161026af4 | C++ | rebeccamurphy/Hackathon-2013 | /C++/winsocktutorial.cpp | UTF-8 | 11,653 | 3.03125 | 3 | [] | no_license | /*
Information Gleaned from the Windows Tutorial on Socket Programming (Winsock)
* The difference b/t blocking and non-blocking circuits
- blocking: old way
- "oh, you didn't successfully perform the operation you wanted? No API for you!"
- non-blocking: new way
- "you didn't finish it, but my function will return as soon as possible, idgaf.
I'll just send a message and it'll be k."
*** Things We Need (not necessarily in the right order) ***
1) initialize the winstock library
2) Set up socket
3) Close socket
---Definition for Byte Ordering---
Because protocols like TCP/IP have to work between different type of systems with different
type of byte ordering, the standard is that values are stored in big-endian format, also
called network byte order. For example, a port number (which is a 16-bit number) like 12345
(0x3039) is stored with its most significant byte first (ie. first 0x30, then 0x39). A
32-bit IP address is stored in the same way, each part of the IP number is stored in one byte,
and the first part is stored in the first byte. For example, 216.239.51.100 is stored as the
byte sequence '216,239,51,100', in that order.
4) sockaddr stuff
5) Connect the socket
6) Bind the socket (give it an address)
7) Listen for a reply
8) Accept
9) send and recv
*/
//=============================== initialize application and main ========================================
#include <iostream>
#define WIN32_MEAN_AND_LEAN
#include <winsock2.h>
#include <windows.h>
using namespace std;
class HRException
{
public:
HRException() :
m_pMessage("") {}
virtual ~HRException() {}
HRException(const char *pMessage) :
m_pMessage(pMessage) {}
const char * what() { return m_pMessage; }
private:
const char *m_pMessage;
};
const int REQ_WINSOCK_VER = 2; // Minimum winsock version required
const char DEF_SERVER_NAME[] = "www.google.com";
const int SERVER_PORT = 80;
const int TEMP_BUFFER_SIZE = 128;
const char HEAD_REQUEST_PART1[] =
{
"HEAD / HTTP/1.1\r\n" // Get root index from server
"Host: " // Specify host name used
};
const char HEAD_REQUEST_PART2[] =
{
"\r\n" // End hostname header from part1
"User-agent: HeadReqSample\r\n" // Specify user agent
"Connection: close\r\n" // Close connection after response
"\r\n" // Empty line indicating end of request
};
// IP number typedef for IPv4
typedef unsigned long IPNumber;
int main(int argc, char* argv[]) {
int iRet = 1;
WSADATA wsaData;
cout << "Initializing winsock... ";
if (WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0) {
// Check if major version is at least REQ_WINSOCK_VER
if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER) {
cout << "initialized.\n";
// Set default hostname:
const char *pHostname = DEF_SERVER_NAME;
// Set custom hostname if given on the commandline:
if (argc > 1)
pHostname = argv[1];
iRet = !RequestHeaders(pHostname);
} else {
cerr << "required version not supported!";
}
cout << "Cleaning up winsock... ";
// Cleanup winsock
if (WSACleanup()!=0) {
cerr << "cleanup failed!\n";
iRet = 1;
}
cout << "done.\n";
} else {
cerr << "startup failed!\n";
}
return iRet;
}
//============================== creating socket =========================================
// Lookup hostname and fill sockaddr_in structure:
cout << "Looking up hostname " << pServername << "... ";
FillSockAddr(&sockAddr, pServername, SERVER_PORT);
cout << "found.\n";
// Create socket
cout << "Creating socket... ";
if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
throw HRException("could not create socket.");
cout << "created.\n";
if (hSocket!=INVALID_SOCKET)
closesocket(hSocket);
//============================= connecting socket ========================================
// Connect to server
cout << "Attempting to connect to " << inet_ntoa(sockAddr.sin_addr)
<< ":" << SERVER_PORT << "... ";
if (connect(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
throw HRException("could not connect.");
cout << "connected.\n";
//============================== sending the request =====================================
cout << "Sending request... ";
// send request part 1
if (send(hSocket, HEAD_REQUEST_PART1, sizeof(HEAD_REQUEST_PART1)-1, 0)==SOCKET_ERROR)
throw HRException("failed to send data.");
// send hostname
if (send(hSocket, pServername, lstrlen(pServername), 0)==SOCKET_ERROR)
throw HRException("failed to send data.");
// send request part 2
if (send(hSocket, HEAD_REQUEST_PART2, sizeof(HEAD_REQUEST_PART2)-1, 0)==SOCKET_ERROR)
throw HRException("failed to send data.");
cout << "request sent.\n";
//================================== receiving the reponse ===============================
cout << "Dumping received data...\n\n";
// Loop to print all data
while(true) {
int retval;
retval = recv(hSocket, tempBuffer, sizeof(tempBuffer)-1, 0);
if (retval==0)
{
break; // Connection has been closed
}
else if (retval==SOCKET_ERROR)
{
throw HRException("socket error while receiving.");
}
else
{
// retval is number of bytes read
// Terminate buffer with zero and print as string
tempBuffer[retval] = 0;
cout << tempBuffer;
}
}
//=============================== request headers ========================================
/* Does these things
Resolve the hostname to its IP.
Create a socket.
Connect the socket to the remote host.
Send the HTTP request data.
Receive data and print it until the other side closes the connection.
Cleanup */
bool RequestHeaders(const char *pServername) {
SOCKET hSocket = INVALID_SOCKET;
char tempBuffer[TEMP_BUFFER_SIZE];
sockaddr_in sockAddr = {0};
bool bSuccess = true;
try {
// code goes here
}
catch(HRException e) {
cerr << "\nError: " << e.what() << endl;
bSuccess = false;
}
return bSuccess;
}
//============================= find host ip ==========================================
IPNumber FindHostIP(const char *pServerName) {
HOSTENT *pHostent;
// Get hostent structure for hostname:
if (!(pHostent = gethostbyname(pServerName)))
throw HRException("could not resolve hostname.");
// Extract primary IP address from hostent structure:
if (pHostent->h_addr_list && pHostent->h_addr_list[0])
return *reinterpret_cast<IPNumber*>(pHostent->h_addr_list[0]);
return 0;
}
void FillSockAddr(sockaddr_in *pSockAddr, const char *pServerName, int portNumber) {
// Set family, port and find IP
pSockAddr->sin_family = AF_INET;
pSockAddr->sin_port = htons(portNumber);
pSockAddr->sin_addr.S_un.S_addr = FindHostIP(pServerName);
}
//============================ initialize library ===========================================
const int iReqWinsockVer = 2; // Minimum winsock version required
WSADATA wsaData;
// V-- highest version V-- pointer to data struct that recieves details of implementation
if (WSAStartup(MAKEWORD(iReqWinsockVer,0), &wsaData)==0) {
// Check if major version is at least iReqWinsockVer
if (LOBYTE(wsaData.wVersion) >= iReqWinsockVer) {
/* ------- Call winsock functions here ------- */
}
else {
// Required version not available
}
// Cleanup winsock
if (WSACleanup()!=0) {
// cleanup failed
}
}
else {
// startup failed
}
//============================== set up =========================================
SOCKET hSocket;
// address family, type of socket, protocol
hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (hSocket==INVALID_SOCKET) {
// error handling code
}
//=============================== close ========================================
closesocket(hSocket);
//================================== sockaddr =====================================
sockaddr_in sockAddr1, sockAddr2;
// Set address family
sockAddr1.sin_family = AF_INET;
/* Convert port number 80 to network byte order and assign it to
the right structure member. */
sockAddr1.sin_port = htons(80);
/* inet_addr converts a string with an IP address in dotted format to
a long value which is the IP in network byte order.
sin_addr.S_un.S_addr specifies the long value in the address union */
sockAddr1.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
// Set address of sockAddr2 by setting the 4 byte parts:
sockAddr2.sin_addr.S_un.S_un_b.s_b1 = 127;
sockAddr2.sin_addr.S_un.S_un_b.s_b2 = 0;
sockAddr2.sin_addr.S_un.S_un_b.s_b3 = 0;
sockAddr2.sin_addr.S_un.S_un_b.s_b4 = 1;
//============================== connect =========================================
/* This code assumes a socket has been created and its handle
is stored in a variable called hSocket*/
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(80);
sockAddr.sin_addr.S_un.S_addr = inet_addr("192.168.0.5"); // *** this is a test IP address ***
// Connect to the server
// the socket, pointer with name of remote socket, size of pointed-to structure
if (connect(hSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr))!=0)
{
// error handling code
}
/* Note: the (sockaddr*) cast is necessary because connect requires a
sockaddr type variable and the sockAddr variable is of the sockaddr_in
type. It is safe to cast it since they have the same structure, but the
compiler naturally sees them as different types.*/
//================================== bind =====================================
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(80);
sockAddr.sin_addr.S_un.S_addr = INADDR_ANY; // use default
// Bind socket to port 80
// socket name, pointer with address to assign to socket, size of pointed-to structure
if (bind(hSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr))!=0)
{
// error handling code
}
//============================== listen =========================================
/* This code assumes the socket specified by
hSocket is bound with the bind function */
// bound, unconnectec socket, max length of pending-connections queue (default value)
if (listen(hSocket, SOMAXCONN)!=0) {
// error handling code
}
//============================= accept ==========================================
sockaddr_in remoteAddr;
int iRemoteAddrLen;
SOCKET hRemoteSocket;
iRemoteAddrLen = sizeof(remoteAddr);
// listening socket, pointer to buffer, pointer to length of prev. pointer's target
hRemoteSocket = accept(hSocket, (sockaddr*)&remoteAddr, &iRemoteAddrLen);
if (hRemoteSocket==INVALID_SOCKET) {
// error handling code
}
//============================== send and recv =========================================
// THIS IS IN BLOCKING MODE
char buffer[128];
while(true) {
// Receive data
int bytesReceived = recv(hRemoteSocket, buffer, sizeof(buffer), 0);
if (bytesReceived==0) { // connection closed
break;
}
else if (bytesReceived==SOCKET_ERROR) {
// error handling code
}
// Send received data back
if (send(hRemoteSocket, buffer, bytesReceived, 0)==SOCKET_ERROR)
{
// error handling code
}
}
| true |
aca4596fe043c10715abe1f7676b0cc256db270f | C++ | fabba/BH2013-with-coach | /Src/Modules/Sensing/FallDownStateDetector.h | UTF-8 | 2,383 | 2.796875 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file FallDownStateDetector.h
*
* This file declares a module that provides information about the current state of the robot's body.
*
* @author <a href="mailto:maring@informatik.uni-bremen.de">Martin Ring</a>
*/
#pragma once
#include "Representations/Infrastructure/SensorData.h"
#include "Representations/Infrastructure/FrameInfo.h"
#include "Representations/MotionControl/MotionInfo.h"
#include "Representations/Sensing/FallDownState.h"
#include "Representations/Sensing/InertiaSensorData.h"
#include "Tools/Module/Module.h"
#include "Tools/RingBufferWithSum.h"
MODULE(FallDownStateDetector)
REQUIRES(FilteredSensorData)
REQUIRES(InertiaSensorData)
USES(MotionInfo)
REQUIRES(FrameInfo)
PROVIDES_WITH_MODIFY_AND_DRAW(FallDownState)
LOADS_PARAMETER(int, fallTime) /**< The time (in ms) to remain in state 'falling' after a detected fall */
LOADS_PARAMETER(float, staggeringAngleX) /**< The threshold angle which is used to detect the robot is staggering to the back or front*/
LOADS_PARAMETER(float, staggeringAngleY) /**< The threshold angle which is used to detect the robot is staggering sidewards*/
LOADS_PARAMETER(float, fallDownAngleY) /**< The threshold angle which is used to detect a fall to the back or front*/
LOADS_PARAMETER(float, fallDownAngleX) /**< The threshold angle which is used to detect a sidewards fall */
LOADS_PARAMETER(float, onGroundAngle) /**< The threshold angle which is used to detect the robot lying on the ground */
END_MODULE
/**
* @class FallDownStateDetector
*
* A module for computing the current body state from sensor data
*/
class FallDownStateDetector: public FallDownStateDetectorBase
{
private:
/** Executes this module
* @param fallDownState The data structure that is filled by this module
*/
void update(FallDownState& fallDownState);
bool isFalling();
bool isStaggering();
bool isCalibrated();
bool specialSpecialAction();
bool isUprightOrStaggering(FallDownState& fallDownState);
FallDownState::Direction directionOf(float angleX, float angleY);
FallDownState::Sidestate sidewardsOf(FallDownState::Direction dir);
unsigned lastFallDetected;
/** Indices for buffers of sensor data */
ENUM(BufferEntry, accX, accY, accZ);
/** Buffers for averaging sensor data */
RingBufferWithSum<float, 15> buffers[numOfBufferEntrys];
public:
/**
* Default constructor.
*/
FallDownStateDetector();
};
| true |
e292acacff5d32fd265a30fb26592fe4350a6b21 | C++ | jessicaione101/online-judge-solutions | /UVa/357.cpp | UTF-8 | 690 | 3.203125 | 3 | [] | no_license | // https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=293
#include <iostream>
#include <vector>
const int kMax = 30001;
int main() {
std::vector<int> coins{1, 5, 10, 25, 50};
std::vector<int64_t> count(kMax);
count[0] = 1;
for (size_t i = 0; i < coins.size(); ++i)
for (int j = coins[i]; j < kMax; ++j)
count[j] += count[j - coins[i]];
int n;
while (std::cin >> n) {
if (count[n] > 1)
std::cout << "There are " << count[n] << " ways to produce "
<< n << " cents change." << std::endl;
else
std::cout << "There is only 1 way to produce "
<< n << " cents change." << std::endl;
}
return 0;
}
| true |
71034459fca8d24aabba9671e0d39ef17189620e | C++ | menegais1/VectorFigures | /src/ColorPicker/ColorSlider.h | UTF-8 | 1,170 | 2.765625 | 3 | [] | no_license | //Color picker secondary window, used to select colors variance between black and the color selected at
//the color picker main window
#ifndef COLORSLIDER_H
#define COLORSLIDER_H
#include "../Base/CanvasObject.h"
#include "../Vectors/Float3.h"
#include <vector>
#include <functional>
class ColorSlider : public CanvasObject {
public:
void mouse(int button, int state, int wheel, int direction, int x, int y) override;
void render() override;
bool pointIntersectsObject(Float3 point) override;
void setColors(Float3 bottomColor, Float3 topColor);
ColorSlider(Float3 position, int width, int height);
Float3 currentSample;
void translate(Float3 translationAmount);
void addOnValueChangedListener(std::function<void(Float3 color)> listener);
void notifyOnValueChangedListeners();
private:
int width;
int height;
bool mouseDragging;
bool mouseInside;
Float2 currentMousePosition;
Float3 *texture;
Float3 topColor;
Float3 bottomColor;
void generateTexture();
Float3 sampleTexture(Float2 position);
std::vector<std::function<void(Float3 color)>> onValueChangedListeners;
};
#endif | true |
b5dcd8b64c4b602e304d03698b5ffb412b754597 | C++ | n-jing/njinglib | /inc/hash_key.h | UTF-8 | 1,163 | 3.328125 | 3 | [] | no_license | #ifndef HASH_KEY_JJ_H
#define HASH_KEY_JJ_H
#include <unordered_map>
template <class T>
inline void hash_combine(std::size_t &seed, const T &v) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template<typename T, size_t d>
std::size_t HashFunc(const T &key)
{
size_t value = 0;
for (size_t i = 0; i < d; ++i)
hash_combine(value, key[i]);
return value;
}
template<typename T, size_t d>
std::size_t UnorderedHashFunc(const T &key)
{
T k = key;
std::sort(k.begin(), k.end());
size_t value = 0;
for (size_t i = 0; i < d; ++i)
hash_combine(value, k[i]);
return value;
}
template<typename T, size_t d>
bool EqualKey(const T &lhs, const T &rhs)
{
for (size_t i = 0; i < d; ++i)
{
if (lhs[i] != rhs[i])
return false;
}
return true;
}
template<typename T, size_t d>
bool UnorderedEqualKey(const T &lhs, const T &rhs)
{
T lower = lhs;
T upper = rhs;
std::sort(lower.begin(), lower.end());
std::sort(upper.begin(), upper.end());
for (size_t i = 0; i < d; ++i)
{
if (lower[i] != upper[i])
return false;
}
return true;
}
#endif // HASH_KEY_JJ_H
| true |
5640b58faafc40c942845e7ed23932d9a09a9cfd | C++ | vs256/GraphType-BreadthFirst-DepthFirst | /main.cpp | UTF-8 | 3,942 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "graphType.h"
using namespace std;
int main()
{
string vertices[] = { "Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"};
int amountOfCities = sizeof(vertices) / sizeof(vertices[0]);
graphType graph(amountOfCities);
int cityNumber;
char choice = 'Y';
//Creating graph of the city map
//Seattle(0) connecting points
graph.createGraph(0, 1); //connects to San Francisco(1)
graph.createGraph(0, 3); //connects to Denver(3)
graph.createGraph(0, 5); //connects to Chicago(5)
//San Francisco(1) connecting points
graph.createGraph(1, 0); //connects to Seattle(0)
graph.createGraph(1, 2); //connects to Los Angeles(2)
graph.createGraph(1, 3); //connects to Denver(3)
//Los Angeles(2) connecting points
graph.createGraph(2, 1); //connects to San Francisco(1)
graph.createGraph(2, 3); //connects to Denver(3)
graph.createGraph(2, 4); //connects to Kansas(4)
graph.createGraph(2, 10); //connects to Dallas(10)
//Denver(3) connecting points
graph.createGraph(3, 0); //connects to Seattle(0)
graph.createGraph(3, 1); //connects to San Francisco(1)
graph.createGraph(3, 2); //connects to Los Angeles(2)
graph.createGraph(3, 4); //connects to Kansas(4)
graph.createGraph(3, 5); //connects to Chicago(5)
//Kansas City(4) connecting points
graph.createGraph(4, 2); //connects to Los Angeles(2)
graph.createGraph(4, 3); //connects to Denver(3)
graph.createGraph(4, 5); //connects to Chicago(5)
graph.createGraph(4, 7); //connects to New York(7)
graph.createGraph(4, 8); //connects to Atlanta(8)
graph.createGraph(4, 10); //connects to Dallas(10)
//Chicago(5) connecting points
graph.createGraph(5, 0); //connects to Seattle(0)
graph.createGraph(5, 3); //connects to Denver(3)
graph.createGraph(5, 4); //connects to Kansas(4)
graph.createGraph(5, 6); //connects to Boston(6)
graph.createGraph(5, 7); //connects to New York(7)
//Boston(6) connecting points
graph.createGraph(6, 5); //connects to Chicago(5)
graph.createGraph(6, 7); //connects to New York(7)
//New York(7) connecting points
graph.createGraph(7, 4); //connects to Kansas(4)
graph.createGraph(7, 5); //connects to Chicago(5)
graph.createGraph(7, 6); //connects to Boston(6)
graph.createGraph(7, 8); //connects to Atlanta(8)
//Atlanta(8) connecting points
graph.createGraph(8, 4); //connects to Kansas(4)
graph.createGraph(8, 7); //connects to New York(7)
graph.createGraph(8, 9); //connects to Miami(9)
graph.createGraph(8, 10); //connects to Dallas(10)
graph.createGraph(8, 11); //connects to Houston(11)
//Miami(9) connecting points
graph.createGraph(9, 8); //connects to Atlanta(8)
graph.createGraph(9, 11); //connects to Houston(11)
//Dallas(10) connecting points
graph.createGraph(10, 2); //connects to Los Angeles(2)
graph.createGraph(10, 4); //connects to Kansas(4)
graph.createGraph(10, 8); //connects to Atlanta(8)
graph.createGraph(10, 11); //connects to Houston(11)
//Houston(11) connecting points
graph.createGraph(11, 8); //connects to Atlanta(8)
graph.createGraph(11, 9); //connects to Miami(9)
graph.createGraph(11, 10); //connects to Dallas(10)
cout << "Graph Traversals\n";
do
{
if (choice == 'Y')
{
cout << "Enter starting city using number from 0 - 11: ";
cin >> cityNumber;
cout << "You entered city name : " << vertices[cityNumber];
cout << "\n\nStarting at " << vertices[cityNumber] << ", " << amountOfCities << " cities are searched in this Depth-First Search order :\n";
graph.depthFirstTraversal(cityNumber, vertices);
cout << "\n\nStarting at " << vertices[cityNumber] << ", " << amountOfCities << " cities are searched in this Breadth-First Search order :\n";
graph.breadthFirstTraversal(cityNumber, vertices);
}
cout << "\nTry another city(Y / N) ";
cin >> choice;
choice = toupper(choice);
} while (choice != 'N');
return 0;
} | true |
80d70be55c37f760c98791ff9dc2655e90d6ded4 | C++ | uwcms/FinalStateAnalysis | /DataAlgos/interface/SmartTrigger.h | UTF-8 | 3,942 | 2.78125 | 3 | [] | no_license | #ifndef SMARTTRIGGER_ZE9BQMEK
#define SMARTTRIGGER_ZE9BQMEK
/*
* Choose the trigger to use from a list in a smart way.
*
* Author: Evan K. Friis, UW Madison
*
* The SmartTrigger is passed a comma separated list of TriggerGroups.
*
* example: "A|B, B_v*, C_v*"
*
* If [ez] is true, use the friendly '*' syntax. Otherwise use boost::regexp.
*
* This example has three trigger groups,
*
* 1) A OR B
* 2) B
* 3) C
*
*
* The SmartTrigger would first check group 1 (A || B) to see if A and B had
* the same prescale. If not, it considers the combo trigger untractable and
* marks it as invalid.
*
* The SmartTrigger then takes the Trigger with the lowest prescale in the list,
* with preference given to the triggers listed earlier.
*
* The SmartTrigger returns a SmartTriggerResult object giving the group index,
* result, and prescale of the chosen trigger. If none of the groups are found,
* it will return index = NGroups
*
*/
#include <string>
#include <vector>
// Fwd Declarations
namespace pat {
class TriggerEvent;
class TriggerPath;
class TriggerFilter;
class TriggerObjectStandAlone;
class PackedTriggerPrescales;
}
namespace edm {
class EventID;
class TriggerResults;
class TriggerNames;
}
struct SmartTriggerResult {
unsigned int group;
unsigned int prescale;
std::vector<std::string> paths;
bool passed;
};
/// Get the result for a single event using the pat::TriggerEvent
SmartTriggerResult smartTrigger(
const std::string& trgs, const pat::TriggerEvent& trgResult,
bool ez=false);
/// Get the result for a single event using the pat::TriggerObjectStandAlone
SmartTriggerResult smartTrigger(
const std::string& trgs, const edm::TriggerNames& names,
const pat::PackedTriggerPrescales& trgPrescales,
const edm::TriggerResults& trgResults,
bool ez=false);
/// This version caches the results across events to speed things up.
const SmartTriggerResult& smartTrigger(
const std::string& trgs, const pat::TriggerEvent& trgResult,
const edm::EventID& event, bool ez=false);
/// Get the result for a single event using the pat::TriggerObjectStandAlone
const SmartTriggerResult& smartTrigger(
const std::string& trgs, const edm::TriggerNames& names,
const pat::PackedTriggerPrescales& trgPrescales,
const edm::TriggerResults& trgResults,
const edm::EventID& event, bool ez=false);
/// Get the list of trigger paths matching a given pattern. If [ez] is
// true, use the friendly '*' syntax. Otherwise use boost::regexp.
std::vector<const pat::TriggerPath*> matchingTriggerPaths(
const pat::TriggerEvent& result,
const std::string& pattern, bool ez=false);
std::vector<int> matchingTriggerPaths(
const edm::TriggerNames& names,
const pat::PackedTriggerPrescales& trgPrescales,
const edm::TriggerResults& trgResults,
const std::string& pattern, bool ez=false);
/// Get the list of trigger filters matching a given pattern.
std::vector<const pat::TriggerFilter*> matchingTriggerFilters(
const pat::TriggerEvent& result,
const std::string& pattern, bool ez=false);
std::vector<const pat::TriggerFilter*> matchingTriggerFilters(
const std::vector<pat::TriggerObjectStandAlone>& trgObject, const edm::TriggerNames& names,
const std::string& pattern, bool ez=false);
/* std::vector<const pat::TriggerFilter*> matchingTriggerFilters( */
/* const std::vector<pat::TriggerObjectStandAlone>& trgObject, const edm::TriggerNames& names, const edm::Event& evt,const edm::TriggerResults& trgResults, */
/* const std::string& pattern, bool ez=false); */
/// Expose decision making method for testing. Not for general use.
SmartTriggerResult makeDecision(
const std::vector<std::vector<std::string> >& paths,
const std::vector<std::vector<unsigned int> >& prescales,
const std::vector<std::vector<unsigned int> >& results);
#endif /* end of include guard: SMARTTRIGGER_ZE9BQMEK */
| true |
24d85c51a8713871f4ebe39a241638e595bfd880 | C++ | alexvsezanyato/lab4 | /Line.cpp | UTF-8 | 669 | 3.046875 | 3 | [] | no_license | class Line: Shape {
public:
using Vec2 = sf::Vector2;
using Vec2f = sf::Vector2f;
using Positon = std::pair<Vec2f, Vec2f>;
private:
Position position;
public:
void setPos(Position);
Position getPos();
float getLength();
};
void Line::setPos(Position position) {
this->position = position;
return;
}
Position Line::getPos() {
Positon position = this->position;
return position;
}
float getLength() {
Position pos = getPos();
Vec2f a = pos.first;
Vec2f b = pos.second;
float length;
float x = abs(b.x - a.x);
float y = abs(b.y - a.y);
length = sqrt(pow(2, x) + pow(2, y));
return length;
}
| true |
d1f3f7a7466d9bd4390d8c1614402045777ce873 | C++ | vijaylaxmi26/competative | /Word_Break_Problem.cpp | UTF-8 | 1,130 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
bool match(string s)
{
string dictionary[]={ "i","like", "sam" , "sung", "samsung" , "mobile" , "ice", "cream" ,
"icecream" , "man" , "go", "mango"};
int l=sizeof(dictionary)/sizeof(dictionary[0]);
for(int i=0;i<l;i++){
//cout<<dictionary[i]<<endl;
if(s==dictionary[i]){
return true;
}
}
return false;
}
bool match_strings(string s,int i,int j,int l){
string str= s.substr(i,j-i+1);
if( i<l && j<l){
if(match(str)){
if(j==l-1){
return true;
}
return match_strings(s,i+str.length(),++j,l);
}else{
if(j==l-1){
return false;
}
return match_strings(s,i,++j,l);
}
}
}
void repeat(string s,int l)
{
int i=0,j=0;
if(match_strings(s,i,j,l)){
cout<<"True";
}else
cout<<"False";
return;
}
int main(){
cout<<"Enter the string: ";
string s;
cin>>s;
int l=s.length();
repeat(s,l);
return 0;
}
| true |
a9669e03180b97fd8a5d32380d671437d526b5ac | C++ | kelleyrw/pac | /packages/AnalysisTools/include/at/ConvertHypIndexToVectors.h | UTF-8 | 415 | 2.546875 | 3 | [] | no_license | #ifndef CONVERTHYPINDEXTOVECTORS_H
#define CONVERTHYPINDEXTOVECTORS_H
#include <vector>
namespace at
{
// function to convert a hyp index into a vector of mu/el indices
// NOTE: clears any contents on the reference vector arguments
void ConvertHypIndexToVectors(const int hyp_index, std::vector<int>& mu_indices, std::vector<int>& el_indices);
} // namespace at
#endif // CONVERTHYPINDEXTOVECTORS_H
| true |
238b4f1a9c6dcf88c4fc5d3848d58496de079087 | C++ | surabivishnupriya/AirlineReservation-Kal | /AirlineReservation/flight.cpp | UTF-8 | 3,243 | 2.921875 | 3 | [] | no_license | #include "stdafx.h"
#include "flight.h"
#include "Plane.h"
#include<iostream>
#include<iomanip>
using namespace std;
namespace AirlineReservation {
Flight::Flight( const std::string date, const std::string departureTime, const std::string arrivalTime, const std::string origin,
const std::string destination, const std::string departureAirport, const std::string airrvalAirport, const std::string airplanename, int airplaneseats, int airplanecols, const std::string flightNumber)
:mairplane(airplanename, airplaneseats, airplanecols)
{
mdate = date;
mdepartureTime = departureTime;
marrivalTime = arrivalTime;
morigin = origin;
mdestination = destination;
mdepartureAirport = departureAirport;
mairrvalAirport = airrvalAirport;
mAirplaneName=airplanename;
mFlightNumber = flightNumber;
}
void Flight::displayFlight() const
{
//const char airport[][10] = { "SEA", "HYD", "DEL","DWT", "KOL","LA" };
cout << setw(3) << mflightId << setw(15) << mdate << setw(13) << mdepartureTime
<< setw(15) << marrivalTime << setw(12) << morigin << setw(10) << mdestination << setw(24) << mdepartureAirport << setw(18) << mairrvalAirport << "\n";
}
void Flight::addFlight() const
{
/*cout << "Enter Depature Date";
cin >> mdate;
cout<<"Enter Depature Time"
*/
}
void Flight::setFlightId(int id)
{
mflightId = id;
}
int Flight::getFlightId() const
{
return mflightId;
}
void Flight::setAirplaneName(std::string& airplaneName) {
mAirplaneName = airplaneName;
}
string& Flight::getAirplaneName() {
return mAirplaneName;
}
void Flight::setFlightNumber(std::string& flightNumber) {
mFlightNumber = flightNumber;
}
const string& Flight::getFlightNumber() const {
return mFlightNumber;
}
void Flight::setDate(const std::string date)
{
mdate = date;
}
const std::string Flight::getDate() const
{
return mdate;
}
void Flight::setDepartureTime(const std::string departureTime)
{
mdepartureTime = departureTime;
}
const std::string Flight::getDepartureTime() const
{
return mdepartureTime;
}
void Flight::setArrivalTime(const std::string arrivalTime)
{
marrivalTime = arrivalTime;
}
const std::string Flight::getArrivalTime() const
{
return marrivalTime;
}
void Flight::setOrigin(const string& departureGate)
{
morigin = departureGate;
}
const string& Flight::getOrigin() const
{
return morigin;
}
void Flight::setDestination(const string& arrivalGate)
{
mdestination = arrivalGate;
}
const string& Flight::getDestination() const
{
return mdestination;
}
void Flight::setdepartureAirport(const std::string& departureAirport)
{
mdepartureAirport = departureAirport;
}
const std::string& Flight::getDepartureAirport() const
{
return mdepartureAirport;
}
void Flight::setAirrvalAirport(const std::string& airrvalAirport)
{
mairrvalAirport = airrvalAirport;
}
const std::string& Flight::getAirrvalAirpot() const
{
return mairrvalAirport;
}
void Flight::setFlightStatus(const flightstatusEnum flightStatus)
{
mflightStatus = flightStatus;
}
const flightstatusEnum Flight::getFlightStatus()
{
return mflightStatus;
}
Plane& Flight::getAirPlane()
{
return mairplane;
}
}
| true |
40dc89be21a2b850e1c6e2eca6ecfb761ad82865 | C++ | Abhishek765/DSA_Final | /Graphs/AlienDictionary.cpp | UTF-8 | 2,113 | 3.46875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void av()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
void dfs(vector<int> g[],int start,vector<bool>& vis,stack<int>& s, int V){
vis[start] = true;
// neighbours2
for(auto node: g[start]){
if(!vis[node])
dfs(g,node,vis,s,V);
}
s.push(start);
}
string topoSort(vector<int> g[],int V){
stack<int> s;
string ans;
vector<bool> vis(V,false);
for(int i=0;i<V;i++){
if(!vis[i])
dfs(g,i,vis,s,V);
}
while(!s.empty()){
ans.push_back((char)(s.top() + 'a'));
s.pop();
}
return ans;
}
string findOrder(string dict[], int N, int K) {
// Steps
// 1 - find the first point of difference between two adjacent pairs in arr
// and form the graph
// 2- Apply the topological sort and store the order in string
// make the graph for K no of alphabets
vector<int> g[K];
// traverse through the arr
for(int i=0; i<N-1; i++){
// finding the minlenght between two adjacent
int minLen = min(dict[i].length(), dict[i+1].length());
// cout<<"minLen: "<<minLen<<endl;
// compare two adjacent strings till minLen and find the first point of difference
for(int j=0;j<minLen; j++){
if(dict[i][j] != dict[i+1][j]){
// cout<<"first: "<<dict[i][j] <<" Second: "<<dict[i+1][j]<<endl;
// if found the first different character store it in graph and break the loop
g[dict[i][j] - 'a'].push_back(dict[i+1][j] - 'a');
break;
}
}
}
string ans;
// after we have our graph just topological sort
ans = topoSort(g,K);
// cout<<"ans: "<<ans<<endl;
return ans;
}
int main() {
av();
string words[] = {"baa", "abcd", "abca","cab" ,"cad"};
string ans = findOrder(words,5,4);
cout<<ans<<endl;
return 0;
} | true |
aaecb5716ad09ecaede9002ec8dd328c108cdd3b | C++ | kaolin/detritus | /src/highscores.cpp | UTF-8 | 3,754 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | #include <sqlite3.h>
#include "highscores.h"
#include <iostream>
using namespace std;
static std::ostream *myerror;
sqlite3* getDB(const char *filename) {
#ifdef DEBUG_MYERROR
(*myerror) << "OPENED DB:" << filename << endl;
#endif
sqlite3 *db;
int rc=0;
rc = sqlite3_open(filename,&db);
if (rc) {
#ifdef DEBUG_MYERROR
*myerror << "Can't open database: " << sqlite3_errmsg(db) << endl;
#endif
sqlite3_close(db);
return NULL;
}
return db;
}
void closeDB(sqlite3* db) {
sqlite3_close(db);
}
void errorDB(sqlite3* db) {
#ifdef DEBUG_MYERROR
*myerror << "DB Error: " << sqlite3_errmsg(db) << endl;
#endif
exit(EXIT_FAILURE);
}
HighScores::HighScores(const char *filename) {
myerror = getErrorStream();
failed = false;
hs = NULL;
dbname=new char[strlen(filename)+1];
strcpy(dbname,filename);
sqlite3* db = getDB(dbname);
sqlite3_stmt *stmt;
if (db != NULL) {
//SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'highscores' .. if not exists, create!
if (sqlite3_prepare(db,"CREATE TABLE IF NOT EXISTS highscores(name varchar(32),score int, stamp datetime);",-1,&stmt,0)) errorDB(db);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
closeDB(db);
} else {
#ifdef DEBUG_MYERROR
*myerror << "UNABLE TO LOAD DB: " << dbname << endl;
#endif
}
reloadScores();
}
bool HighScores::hasScores(void) { if (failed) return false; return hs != NULL; }
const HighScore* HighScores::getScores() {
if (failed) return NULL;
return hs;
}
HighScores::~HighScores() { if (hs) delete(hs); if (dbname) delete dbname; }
void HighScores::reloadScores(void) {
sqlite3 *db = getDB(dbname);
sqlite3_stmt *stmt;
int rc;
HighScore *next=NULL, *tmp;
char s[256];
if (hs) { delete(hs); hs = NULL; }
if (db == NULL) {
failed = true;
#ifdef DEBUG_MYERROR
(*myerror) << "unable to get db to load high scores" << endl;
#endif
} else {
if (sqlite3_prepare(db,"SELECT name, score, stamp FROM highscores ORDER BY score DESC, stamp ASC LIMIT 10;",-1,&stmt,0)) errorDB(db);
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
strncpy(s,(char*)sqlite3_column_text(stmt,0),255);
s[255]=0;
tmp = new HighScore(s,sqlite3_column_int(stmt,1));
if (hs == NULL) {
next = hs = tmp;
} else {
next->next = tmp;
next = tmp;
}
}
sqlite3_finalize(stmt);
closeDB(db);
}
}
void HighScores::addScore(const char* name, int score) {
if (failed) return;
sqlite3_stmt* stmt;
sqlite3* db = getDB(dbname);
if (sqlite3_prepare(db,"INSERT INTO highscores(name,score,stamp) VALUES(?,?,datetime('now'));",-1,&stmt,0)) errorDB(db);
if (sqlite3_bind_text(stmt,1,name,strlen(name),SQLITE_STATIC)) errorDB(db);
if (sqlite3_bind_int(stmt,2,score)) errorDB(db);
sqlite3_step(stmt); // returns rs, not ERROR
sqlite3_finalize(stmt);
closeDB(db);
reloadScores();
}
/* check to see if this is a new high score out of N */
bool HighScores::isHighScore(int score, int n) {
if (failed) return false;
if (score < 1) return false;
HighScore *next = hs;
while (n > 0 && next != NULL) {
if (score > next->score) return true;
next = next->next;
n--;
}
if (next == NULL && n >0) return true;
return false;
};
const char* HighScore::getName() const { return name; }
int HighScore::getScore() const { return score; }
bool HighScore::hasNext() const { return next != NULL; }
HighScore * HighScore::getNext() const { return next; }
HighScore::HighScore(const char *name, int score) {
this->score = score;
this->name = new char[strlen(name)+1];
strcpy(this->name,name);
this->next = NULL;
}
HighScore::~HighScore() {
if (next) delete(next);
delete(name);
}
| true |
dc840cb8b72734100b10e8a2e93d0756a346f2c6 | C++ | sudiptobd/UVA-Solving | /10004.cpp | UTF-8 | 1,212 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;
int main()
{
int n=0;
while(scanf("%d",&n)&&n)
{
int e;
scanf("%d",&e);
vector<int>v[n];
int a,b;
for(int i=0; i<e; i++)
{
scanf("%d %d",&a,&b);
v[a].push_back(b);
v[b].push_back(a);
}
queue<int>q;
for(int i=1; i<n; i++)q.push(i);
int ac[500]= {0};
int bc[500]= {0};
ac[0]=1;
for(int i=0; i<v[0].size(); i++)bc[v[0][i]]=1;
while(!q.empty())
{
int vq=q.front();
q.pop();
if(ac[vq]==0&&bc[vq]==0)q.push(vq);
else if(ac[vq]==1&&bc[vq]==0)
for(int i=0; i<v[vq].size(); i++)bc[v[vq][i]]=1;
else if(ac[vq]==0&&bc[vq]==1)
for(int i=0; i<v[vq].size(); i++)ac[v[vq][i]]=1;
}
int j,flag=0;
for(j=0; j<n; j++)
if(ac[j]&&bc[j])
{
flag=1;
break;
}
if(flag)printf("NOT BICOLORABLE.\n");
else printf("BICOLORABLE.\n");
}
return 0;
}
| true |
b338580f58cbea974d7cbc852f8186020144ea40 | C++ | zhiyaojia/Game | /parkour/parkour/MazeScreen.cpp | UTF-8 | 1,443 | 2.546875 | 3 | [] | no_license | #include "MazeScreen.h"
#include "Game.h"
#include "GameModeScreen.h"
#include "Renderer.h"
#include "OptionButton.h"
#include <iostream>
#include <vector>
#include <string>
#include <SDL/SDL.h>
using namespace std;
MazeScreen::MazeScreen(Game* game):UIScreen(game)
{
mNextButtonPos = Vector2(-130, 120);
mBackground = mGame->GetRenderer()->GetTexture("Assets/image/maze.png");
vector<Option*> mMapOptions;
vector<string> maps = mGame->mMazeMap;
for(auto s: maps)
{
string::size_type idx;
idx = s.find(".json");
if(idx == string::npos ) {continue;}
string name = s;
for(int i=0; i<name.length(); i++)
{
if(name[i] == '.')
{
name.erase(i, name.length()-i);
}
}
mMapOptions.push_back(new Option(name, mFont, [this, name](){ mGame->SetMazeMap(name);}, true));
}
AddOptionButton("MazeMapButton", "EMPTY", mMapOptions);
mNextButtonPos = Vector2(0, 50);
AddClickButton("StartButton", "EMPTY", [this]()
{
mGame->ChangeState(Game::MenuToGame);
mGame->SetGameMode(Game::Maze);
Close();
});
AddClickButton("DIYButton", "EMPTY", [this]()
{
mGame->ChangeState(Game::MenuToGame);
mGame->SetGameMode(Game::Build);
Close();
});
AddClickButton("BackButton", "EMPTY", [this]()
{
new GameModeScreen(mGame);
Close();
});
}
void MazeScreen::HandleKeyPress(int key)
{
UIScreen::HandleKeyPress(key);
if (key == SDLK_ESCAPE)
{
new GameModeScreen(mGame);
Close();
}
}
| true |
d16210d6feb2da32513ec13dbd3e4d8674226594 | C++ | valentinjacot/backupETHZ | /HPCI/exercises/ex07/solution_code/network/Network.h | UTF-8 | 7,954 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
* Network.h
*
* Created by Guido Novati on 30.10.18.
* Copyright 2018 ETH Zurich. All rights reserved.
*
*/
#pragma once
#include "Layers.h"
struct Network
{
std::mt19937 gen;
// Vector of layers, each defines a forward and bckward operation:
std::vector<Layer*> layers;
// Vector of parameters of each layer (two vectors must have the same size)
// Each Params contains the matrices of parameters needed by the corresp layer
std::vector<Params*> params;
// Vector of grads for each parameter. By definition they have the same size
std::vector<Params*> grads;
// Memory space where each layer can compute its output and gradient:
std::vector<Activation*> workspace;
// Number of inputs to the network:
int nInputs = 0;
// Number of network outputs:
int nOutputs = 0;
size_t alloc_batchSize = 0;
Network(const int seed = 0) : gen(seed) {};
void forward(
std::vector<std::vector<Real>>& O,
// one vector of input for each element in the mini-batch:
const std::vector<std::vector<Real>> I,
// layer ID at which to start forward operation:
const size_t layerStart = 0 // (zero means compute from input to output)
)
{
if(params.size()==0 || grads.size()==0 || layers.size()==0) {
printf("Attempted to access uninitialized network. Aborting\n");
abort();
}
// input is a minibatch of datapoints: one vector for each datapoint:
const size_t batchSize = I.size();
// allocate workspaces where we can write output of each layer
if (batchSize not_eq alloc_batchSize) {
clearWorkspace();
alloc_batchSize = batchSize;
workspace = allocateActivation(batchSize);
}
// User can overwrite the output of any upper layer (marked by layerStart)
// in order to see what happens if layer layerStart has a predefined output.
// ( this allows visualizing PCA components! )
const int inputLayerSize = workspace[layerStart]->layersSize;
//copy input onto output of input layer:
#pragma omp parallel for schedule(static)
for (size_t b=0; b<batchSize; b++)
{
assert(I[b].size() == (size_t) inputLayerSize );
// Input to the network is the output of input layer.
// Respective workspace is a matrix of size [batchSize]x[nInputs]
// Here we use row-major ordering: nInputs is the number of columns.
Real* const input_b = workspace[layerStart]->output + b * inputLayerSize;
// copy from function argument to workspace:
std::copy(I[b].begin(), I[b].end(), input_b);
}
// Start from layer after input. E.g. Input layer is 0. No need to backprop
// input layer has it has no parameters.
for (size_t j=layerStart+1; j<layers.size(); j++)
layers[j]->forward(workspace, params);
// copy output into vector of vectors: one vector for each element of batch
O.resize(batchSize);
#pragma omp parallel for schedule(static)
for (size_t b=0; b<batchSize; b++)
{
O[b].resize(nOutputs, 0);
assert(nOutputs == workspace.back()->layersSize);
// network output is the output of last layer.
// Respective workspace is a matrix of size [batchSize]x[nOutputs]
// Here we use row-major ordering: nOutputs is the number of columns.
Real* const output_b = workspace.back()->output + b * nOutputs;
// copy from function argument to workspace:
std::copy(output_b, output_b + nOutputs, O[b].begin());
}
}
void bckward(
// vector of size of mini-batch of gradients of error wrt to network output
const std::vector<std::vector<Real>> E,
// layer ID at which forward operation was started:
const size_t layerStart=0 // (zero means compute from input to output)
) const
{
//this function assumes that we already called forward propagation
if(params.size()==0 || grads.size()==0 || layers.size()==0)
{
printf("Attempted to access uninitialized network. Aborting\n");
abort();
}
// input is a minibatch of datapoints: one vector for each datapoint:
const size_t batchSize = E.size();
assert( (size_t) workspace.back()->batchSize == batchSize);
//copy input onto output of input layer:
#pragma omp parallel for schedule(static)
for (size_t b=0; b<batchSize; b++)
{
assert(E[b].size() == (size_t) nOutputs);
// Write d Err / d Out onto last layer of the network.
// Respective workspace is a matrix of size [batchSize]x[nOutputs]
// Here we use row-major ordering: nOutputs is the number of columns.
Real* const errors_b = workspace.back()->dError_dOutput + b * nOutputs;
// copy from function argument to workspace:
std::copy(E[b].begin(), E[b].end(), errors_b);
}
// Backprop starts at the last layer, which computes gradient of error wrt
// to its parameters and gradient of error wrt to it's input.
// Last layer to backprop is the one above input layer. Eg. if layerStart=0
// Then input layer was 0, which has no parametes and has no inputs to
// backprp the error grad to, last layer to backprop is layer 1.
for (size_t i = layers.size()-1; i >= layerStart + 1; i--)
layers[i]->bckward(workspace, params, grads);
}
// Helper function for forward with batchsize = 1
std::vector<Real> forward(const std::vector<Real>I, const size_t layerStart=0)
{
std::vector<std::vector<Real>> vecO (1, std::vector<Real>(nOutputs));
const std::vector<std::vector<Real>> vecI (1, I);
forward(vecO, vecI, layerStart);
return vecO[0];
}
// Helper function for forward with batchsize = 1)
void bckward(const std::vector<Real> E, const size_t layerStart = 0) const
{
std::vector<std::vector<Real>> vecE (1, E);
bckward(vecE, layerStart);
}
~Network() {
for(auto& p : grads) _dispose_object(p);
for(auto& p : params) _dispose_object(p);
for(auto& p : layers) _dispose_object(p);
for(auto& p : workspace) _dispose_object(p);
}
inline void clearWorkspace() {
for(auto& p : workspace) _dispose_object(p);
workspace.clear();
}
// Function to loop over layers and allocate workspace for network operations:
inline std::vector<Activation*> allocateActivation(size_t batchSize) const
{
std::vector<Activation*> ret(layers.size(), nullptr);
for(size_t j=0; j<layers.size(); j++)
ret[j] = layers[j]->allocateActivation(batchSize);
return ret;
}
// Function to loop over layers and allocate memory space for parameter grads:
inline std::vector<Params*> allocateGrad() const
{
std::vector<Params*> ret(layers.size(), nullptr);
for(size_t j=0; j<layers.size(); j++)
ret[j] = layers[j]->allocate_params();
return ret;
}
//////////////////////////////////////////////////////////////////////////////
/// Functions to build the network are defined in Network_buildFunctions.h ///
//////////////////////////////////////////////////////////////////////////////
template<int size> void addInput();
template<int nInputs, int size>
void addLinear(const std::string fname = std::string());
template<int size> void addSoftMax();
template<int size> void addLReLu();
template<int size> void addTanh();
template
<
int InX, int InY, int InC, //input image: x:width, y:height, c:channels
int KnX, int KnY, int KnC, //filter: x:width, y:height, c:channels
int Sx=1, // (Stride in x) Defaults to 1: advance one pixel at the time.
int Sy=1, // (Stride in y)
int Px=(KnX -1)/2, // (Padding in x) Defaults to value that makes output
int Py=(KnY -1)/2, // (Padding in y) image of the same size as input image.
int OpX=(InX -KnX +2*Px)/Sx+1, //Out image: same number of channels as KnC.
int OpY=(InY -KnY +2*Py)/Sy+1 //Default: uniform padding in all directions.
>
void addConv2D(const std::string fname = std::string());
};
#include "Network_buildFunctions.h"
| true |
f5328a8bb9024939b18ca1d61756f58bbe1f680f | C++ | xiabofei/leetcode | /2018/462_MinimumMovestoEqualArrayElementsII.cpp | UTF-8 | 518 | 3.03125 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <string>
#include <unordered_set>
#include <stack>
#include <queue>
#include <map>
#include <set>
using namespace std;
// 选1个元素+1 或 选1个元素-1
// 最小移动次数
// 解法: 排序 两头往中间靠拢
class Solution {
public:
int minMoves2(vector<int>& nums){
sort(nums.begin(), nums.end());
int b = 0;
int e = nums.size()-1;
int ret = 0;
while(b<e){
ret += nums[e--] - nums[b++];
}
return ret;
}
}; | true |
809b17cb1016cdec4163598cce2f57a3626a22fa | C++ | SYCstudio/OI | /Practice/2019.3.31/BZOJ5324.cpp | UTF-8 | 662 | 2.8125 | 3 | [
"MIT"
] | permissive | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxN=5010;
int n,H[maxN],F[maxN][maxN];
double Slope(int a,int b);
int main()
{
scanf("%d",&n);
for (int i=1; i<=n; i++) scanf("%d",&H[i]);
int Ans=0;
for (int r=1; r<=n; r++) {
Ans^=(F[r][r]=1);
if (r==1) continue;
Ans^=(F[r-1][r]=1);
int lst=r-1,sum=1;
for (int l=r-2; l>=1; l--) {
if (Slope(l,r)<Slope(lst,r)) sum+=min(F[l+1][lst],F[l+1][lst-1]),lst=l;
Ans^=(F[l][r]=sum+min(F[l][lst],F[l][lst-1]));
}
}
printf("%d\n",Ans);
return 0;
}
double Slope(int a,int b)
{
return (double)(H[a]-H[b])/(double)(a-b);
} | true |
71a545f3217b06fb295cd948b06744a8e816d8a6 | C++ | GNUDimarik/OsDev-3 | /user/bin/terminal/src/CommandLineInput.cpp | UTF-8 | 5,342 | 2.875 | 3 | [] | no_license | /**
* @file: CommandLineInput.cpp
*
* @date: Oct 24, 2017
* @author: Mateusz Midor
*/
#include "syscalls.h"
#include "Cout.h"
#include "StringUtils.h"
#include "CommandLineInput.h"
using namespace cstd;
using namespace cstd::ustd;
using namespace middlespace;
namespace terminal {
const char CommandLineInput::PROMPT[] {"> "};
char CommandLineInput::cwd[256];
void CommandLineInput::prompt() {
char cwd[256];
if (syscalls::getcwd(cwd, 255) < 0)
cout::format("[UNKNOWN CWD] %", PROMPT);
else
cout::format("% %", cwd, PROMPT);
}
void CommandLineInput::backspace() {
if (!input.empty()) {
input.pop_back();
cout::print("\x08"); // backspace
}
}
void CommandLineInput::putc(char c) {
input.push_back(c);
cout::print(&c, 1);
}
void CommandLineInput::clear() {
input.clear();
}
void CommandLineInput::install(const string& cmd_name) {
known_commands.push_back(cmd_name);
}
void CommandLineInput::help_me_out() {
if (syscalls::getcwd(cwd, sizeof(cwd)) < 0)
return;
bool multiple_results;
string filter_result;
if (input.find(' ') == string::npos) { // command not given, suggest command
std::tie(multiple_results, filter_result) = command_filter(input);
if (multiple_results)
cout::format("\n % \n\n% %%", filter_result, cwd, PROMPT, input);
else
suggest_cmd(filter_result);
}
else { // suggest param
string second_segment = input.substr(input.rfind(' ') + 1, input.length());
string common_pattern;
std::tie(multiple_results, filter_result, common_pattern) = folder_filter(cwd, second_segment);
if (multiple_results)
cout::format("\n % \n% %%", filter_result, cwd, PROMPT, input);
// else
if (!common_pattern.empty())
suggest_param(common_pattern);
}
}
/**
* @brief Erase entire command line input and replace with "cmd"
*/
void CommandLineInput::suggest_cmd(const string& cmd) {
for (s16 i = input.length()-1; i >= 0 ; i--)
cout::print("\x08"); // backspace
cout::format(cmd);
input = cmd;
}
/**
* @brief Erase last segment of command line parameter and replace with "param"
*/
void CommandLineInput::suggest_param(const string& param) {
for (s16 i = input.length()-1; i >= 0 ; i--) {
if (input[i] == ' ') // segment break (beginning of parameter)
break;
if (input[i] == '/') // path break (beginnig of path segment)
break;
cout::print("\x08"); // backspace
input.pop_back();
}
cout::format(param);
input += param;
}
/**
* @brief Match known commands against name patter
* @param pattern Command name beginning
* @return {false, name} if single command found
* {true, name_list} if multiple commands found
*/
std::tuple<bool, string> CommandLineInput::command_filter(const string& pattern) {
vector<string> found;
for (const string& c : known_commands)
if (c.find(pattern) == 0)
found.push_back(c);
if (found.empty())
return std::make_tuple(false, pattern);
else if (found.size() == 1)
return std::make_tuple(false, found.back());
else
return std::make_tuple(true, StringUtils::join_string(" ", found));
}
std::tuple<bool, string, string> CommandLineInput::folder_filter(const string& cwd, const string& param) {
string path;
string pattern;
size_t pivot = param.rfind('/');
if (pivot != string::npos) {
path = param.substr(0, pivot+1);
if (path[0] != '/')
path = cwd + "/" + path;
pattern = param.substr(pivot+1, param.length());
}
else {
path = cwd;
pattern = param;
}
u32 MAX_ENTRIES = 128; // should there be more in a single dir?
VfsEntry* entries = new VfsEntry[MAX_ENTRIES];
int fd = syscalls::open(path.c_str());
if (fd < 0) {
return {};
}
vector<string> found;
// filter results
int count = syscalls::enumerate(fd, entries, MAX_ENTRIES);
for (int i = 0; i < count; i++) {
const string& name (entries[i].name);
if (name == "." || name == "..")
continue;
if (name.find(pattern) == 0) {
if (entries[i].is_directory)
found.push_back(name + "/");
else
found.push_back(name);
}
}
// find common pattern
string common_pattern;
size_t i = 0;
bool done = found.empty();
while (!done) {
char common = found.front()[i];
for (const auto& s : found) {
if (s.length() <= i) {
done = true;
break;
}
if (s[i] != common) {
done = true;
break;
}
}
i++;
}
if (!found.empty())
common_pattern = found.front().substr(0, i-1);
delete[] entries;
syscalls::close(fd);
if (found.empty())
return std::make_tuple(false, pattern, common_pattern);
else if (found.size() == 1)
return std::make_tuple(false, found.back(), common_pattern);
else
return std::make_tuple(true, StringUtils::join_string(" ", found), common_pattern);
}
} /* namespace terminal */
| true |
dae9bb41ab4ad6963a15dbd05bee3ade4757b521 | C++ | teddy8997/LeetCode | /Medium/139. Word Break/wordBreak.cpp | UTF-8 | 881 | 3.203125 | 3 | [] | no_license | /*
參考: https://zxi.mytechroad.com/blog/leetcode/leetcode-139-word-break/
time complexity: O(n^2)
space complexity: O(n^2)
*/
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> sd(wordDict.begin(), wordDict.end());
return wordB(s, sd);
}
private:
unordered_map<string, bool> m;
bool wordB(string &s, unordered_set<string> &sd){
if(m.count(s)){
return m[s];
}
if(sd.count(s)){
m[s] = true;
return true;
}
for(int i = 1; i < s.size(); i++){
string left = s.substr(0, i);
string right = s.substr(i);
if(sd.count(left) && wordB(right, sd)){
m[s] = true;
return true;
}
}
m[s] = false;
return false;
}
}; | true |
4795d21561af011032f1fe3a2f4335e07d76e3eb | C++ | julianaabs/Zuma | /mapeamento.inl | UTF-8 | 3,039 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include "mapeamento.h"
#include "mainList.h"
//Construtor da classe
template <class object>
Map<object>::Map(Node<object> *auxInserido, Lista<object> *auxGame){
maisPosition = -1;
menosPosition = -1;
counterCombo = 0;
numberOfBalls = 0;
game = auxGame;
points = 0;
auxAfter = NULL;
auxBefore = NULL;
inserido = auxInserido;
}
/* Deleta a sequência de bolinhas iguais, sendo a cabeça da lista a primeira bolinha da sequência (auxBefore->next)
*/
template <class object>
void Map<object>::DeletarLista(){
Node<object> *cont = auxBefore->next;
while(cont!=auxAfter){
Node<object> *tmp = cont;
cont = tmp->next;
delete tmp;
}
game->fsize-=numberOfBalls;
}
/* Remove a sequência de bolinhas, além de realizar a verificação para saber se houve combo.
Após fazer a ligação das duas cadeias, se a verificação retornar true quer dizer que houve combo, assim
incrementando o valor do contador de combos. Dentro do while, é feita a ligação das duas novas cadeias e o processo
se repete sempre que houver sequência de bolinhas a serem removidas. */
template <class object>
void Map<object>::RemoveSeq(){
if(VerifySeq(inserido)==true){
Pontos();
DeletarLista();
auxBefore->next = auxAfter;
auxAfter->back = auxBefore;
inserido = auxBefore;
/* Loop da verificação dos combos */
while(VerifySeq(auxBefore)){
counterCombo++;
Pontos();
DeletarLista();
auxBefore->next = auxAfter;
auxAfter->back = auxBefore;
}
}
}
/* Realiza a contagem dos pontos do jogador de acordo com o número de bolinhas excluídas. Cada bolinha vale 10 pontos
e o jogador ganha 100 pontos extras por combo.
*/
template <class object>
void Map<object>::Pontos(){
if(numberOfBalls == 3){
points = 30;
}else if(numberOfBalls > 3){
for(int i=4; i<=numberOfBalls; i++){
points+=10;
}
}
if(counterCombo > 0){
points+=100;
}
}
/* Realiza a verificação de sequências com qualquer número de bolinhas realizando um tipo de "mapeamento". O nó que está
sendo inserido é passado como referência pois através dele será feito o mapeamento com os elementos da frente e os elementos
de trás (utilizando os nós 'before' e 'after'). Após o mapeamento, os índices da primeira e da última bolinhas da sequência
são guardados para poder eliminar aquela sequência e depois fazer o ligamento das duas cadeias restantes.
*/
template <class object>
bool Map<object>::VerifySeq(Node<object> *inserido){
auxAfter = inserido;
bool before, after;
while(auxAfter->data == inserido->data && auxAfter->next != NULL){
auxAfter = auxAfter->next;
after = true;
}
maisPosition = game.Indice(auxAfter->back);
auxBefore = inserido;
while(auxBefore->data == inserido->data && auxBefore->back != NULL){
auxBefore = auxBefore->back;
before = true;
}
menosPosition = game.Indice(auxBefore->next);
numberOfBalls = maisPosition - menosPosition;
if(before || after){
return true;
}
else{
return false;
}
numberOfBalls = maisPosition - menosPosition;
return false;
} | true |
a46650580e4d41afdc733df826d7ba0c7a13deff | C++ | StoneIron02/202101-CSE1101-004 | /5주차/실습/12211554강석철2_1.cpp | UTF-8 | 431 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
void printCmath(double x) {
cout << "ceil(x) : " << ceil(x) << endl;
cout << "exp(x) : " << exp(x) << endl;
cout << "log(x) : " << log(x) << endl;
cout << "sqrt(x) : " << sqrt(x) << endl;
cout << "fabs(x) : " << fabs(x) << endl;
cout << "pow(x,2) : " << pow(x,2) << endl;
}
int main() {
double x;
cout << "input x real number : ";
cin >> x;
printCmath(x);
}
| true |
3ee20d8ca559ca1d92ec7136907dd7a51b4dae7a | C++ | Brebl/Sdl2-wrapper | /src/brb_texture.cpp | UTF-8 | 5,708 | 2.5625 | 3 | [] | no_license | #include "pch.h"
namespace brb::sdl
{
Texture::Texture(const WindowRenderer& wr, const Font& f) :
texture_(nullptr),
texture_width_(0),
texture_height_(0),
renderer_(wr.get_renderer()),
font_(f.get_font()),
basecolor_(brb::sdl::col::basics::black)
{
basecolor_.a = 0xff;
SDL_SetRenderDrawColor(renderer_, basecolor_.r, basecolor_.g, basecolor_.b, basecolor_.a);
brb::log("texture created", texture_);
}
Texture::~Texture()
{
if (texture_ != nullptr) {
SDL_DestroyTexture(texture_);
brb::log("texture destroyed", texture_);
}
}
void Texture::set_font(const Font& f) {
font_ = f.get_font();
brb::log("texture font changed", texture_);
}
void Texture::set_basecolor(const SDL_Color& c, Uint8 alpha) {
basecolor_ = c;
basecolor_.a = alpha;
SDL_SetRenderDrawColor(renderer_, basecolor_.r, basecolor_.g, basecolor_.b, basecolor_.a);
brb::log("texture basecolor changed", texture_);
}
void Texture::clear() {
SDL_RenderClear(renderer_);
}
#ifdef __linux__
bool Texture::load_pic(const std::string& fname)
{
try
{
if (texture_) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
}
SDL_Surface* surface(IMG_Load(fname.c_str()));
if (!surface) {
throw(std::runtime_error("Image load, " + fname));
}
SDL_SetColorKey(surface, SDL_FALSE, SDL_MapRGB(surface->format, 255, 255, 255));
texture_ = SDL_CreateTextureFromSurface(renderer_, surface);
if (!texture_)
throw(std::runtime_error("SDL_CreateTextureFromSurface" + fname));
texture_width_ = surface->w;
texture_height_ = surface->h;
SDL_FreeSurface(surface);
brb::log("Image loaded", fname, Mode::all);
}
catch (const std::exception& e) {
brb::err("brb::sdl::load_pic", e.what());
return false;
}
return texture_ != nullptr;
}
#endif //linux
#ifdef _WIN32
bool Texture::load_pic(const std::wstring& wfname)
{
try
{
if (texture_) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
}
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string fname{ converter.to_bytes(wfname) };
SDL_Surface* surface(IMG_Load(fname.c_str()));
if (!surface) {
throw(std::runtime_error("Image load, " + fname + std::string(SDL_GetError())));
}
SDL_SetColorKey(surface, SDL_FALSE, SDL_MapRGB(surface->format, 255, 255, 255));
texture_ = SDL_CreateTextureFromSurface(renderer_, surface);
if (!texture_)
throw(std::runtime_error("SDL_CreateTextureFromSurface" + fname));
texture_width_ = surface->w;
texture_height_ = surface->h;
SDL_FreeSurface(surface);
brb::log("Image loaded", fname, Mode::all);
}
catch (const std::exception& e) {
brb::err("brb::sdl::load_pic", e.what());
return false;
}
return texture_ != nullptr;
}
#endif //win32
#ifdef __linux__
bool Texture::load_text(const std::string& text, const SDL_Color& col)
{
typedef std::basic_string<Uint16, std::char_traits<Uint16>, std::allocator<Uint16> > u16string;
try {
if (text.empty()) {
return false;
}
if (texture_) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
}
u16string utext(text.begin(), text.end());
SDL_Surface* surface(TTF_RenderUNICODE_Blended(font_, utext.c_str(), col));
if (!surface) {
throw std::runtime_error("TTF_RenderUNICODE_Blended: " + std::string(TTF_GetError()));
}
texture_ = SDL_CreateTextureFromSurface(renderer_, surface);
if (!texture_) {
throw std::runtime_error("SDL_CreateTextureFromSurface: " + std::string(SDL_GetError()));
}
texture_width_ = surface->w;
texture_height_ = surface->h;
SDL_FreeSurface(surface);
}
catch (const std::exception& e) {
brb::err("brb::sdl::load_text", e.what());
return false;
}
return texture_ != nullptr;
}
#endif //linux
#ifdef _WIN23
bool Texture::load_text(const std::wstring& text, const SDL_Color& col)
{
typedef std::basic_string<Uint16, std::char_traits<Uint16>, std::allocator<Uint16> > u16string;
try {
if (text.empty()) {
return false;
}
if (texture_) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
}
u16string utext(text.begin(), text.end());
SDL_Surface* surface(TTF_RenderUNICODE_Blended(font_, utext.c_str(), col));
if (!surface) {
throw std::runtime_error("TTF_RenderUNICODE_Blended: " + std::string(TTF_GetError()));
}
texture_ = SDL_CreateTextureFromSurface(renderer_, surface);
if (!texture_) {
throw std::runtime_error("SDL_CreateTextureFromSurface: " + std::string(SDL_GetError()));
}
texture_width_ = surface->w;
texture_height_ = surface->h;
SDL_FreeSurface(surface);
}
catch (const std::exception& e) {
brb::err("brb::sdl::load_text", e.what());
return false;
}
return texture_ != nullptr;
}
#endif //win32
void Texture::draw(
int x,
int y,
SDL_Rect* srcrect,
double angle,
SDL_Point* center,
SDL_RendererFlip flip)
{
//draw to render
//srcrect: witch part of the texture gets drawn, NULL whole pic
//dstrect: where the picture will be drawn, NULL stretch to whole screen
SDL_Rect dstrect = { x, y, texture_width_, texture_height_ };
if (srcrect != NULL) {
dstrect.w = srcrect->w;
dstrect.h = srcrect->h;
}
SDL_RenderCopyEx(renderer_, texture_, srcrect, &dstrect, angle, center, flip);
}
void Texture::draw_fullscreen()
{
SDL_RenderCopy(renderer_, texture_, NULL, NULL);
}
int Texture::return_width()
{
return texture_width_;
}
} | true |
1b5b6c9608af8fc9ebfa45928e101e1e2bc04076 | C++ | frog97/freelec_modern_c-_programming | /Project_Code/Project5 - Ch9/Owner.h | UHC | 872 | 2.9375 | 3 | [] | no_license | #ifndef _OWNER_H_
#define _OWNER_H_
#include <iostream>
#include "Contact.h"
class Owner {
private:
char name[20]; // ̸
char phoneNumber[13]; // ȭȣ
char email[30]; // ̸
char address[50]; // ּ
char twitterAccount[20]; // Ʈ
public:
// Է
void inputOwnerInfo(char *inName, char *inPhoneNumber = NULL, char *inEmail = NULL, char *inAddress = NULL, char *inTwitterAccount = NULL);
//
void printOwnerInfo();
//
void editOwnerInfo(char *inName, char *inPhoneNumber = NULL, char *inEmail = NULL, char *inAddress = NULL, char *inTwitterAccount = NULL);
// Contact Լ friend
friend void Contact::retrieveTwitterFollowing(Owner &owner);
};
#endif | true |
3f9925f59d39a95e3bae37896e2579631335d38c | C++ | ShanzhongXinzhijie/DemolisherWeapon | /DemolisherWeapon/Render/GaussianBlurRender.h | SHIFT_JIS | 2,110 | 2.6875 | 3 | [] | no_license | #pragma once
namespace DemolisherWeapon {
class GaussianBlurRender{
public:
GaussianBlurRender() = default;
~GaussianBlurRender() {
Release();
}
/// <summary>
///
/// </summary>
/// <param name="souce">ڂVF[_[\[Xr[</param>
/// <param name="dispersion">ڂ̋</param>
/// <param name="sampleScale">TvԊu(-11eNZԊu)(𑜓x6401eNZԊuȂAsampleScale = 640.0f)</param>
void Init(ID3D11ShaderResourceView*& souce, float dispersion, const CVector2& sampleScale = {-1.0f,-1.0f});
/// <summary>
/// ڂĐݒ
/// </summary>
/// <param name="souce">ڂVF[_[\[Xr[</param>
void ResetSource(ID3D11ShaderResourceView*& souce);
/// <summary>
///
/// </summary>
void Release();
/// <summary>
/// KEXu[
/// </summary>
void Blur();
/// <summary>
/// VF[_[\[Xr[̎擾
/// </summary>
/// <returns></returns>
ID3D11ShaderResourceView*& GetSRV() {
return m_outputYSRV;
}
private:
Shader m_vsx, m_vsy, m_ps;//VF[_
//̓eNX`
ID3D11ShaderResourceView* m_souce = nullptr;
//o̓eNX`
ID3D11Texture2D* m_outputX = nullptr;
ID3D11RenderTargetView* m_outputXRTV = nullptr;
ID3D11ShaderResourceView* m_outputXSRV = nullptr;
ID3D11Texture2D* m_outputY = nullptr;
ID3D11RenderTargetView* m_outputYRTV = nullptr;
ID3D11ShaderResourceView* m_outputYSRV = nullptr;
D3D11_TEXTURE2D_DESC m_texDesc;//eNX`
//萔obt@
//[gaussianblur.fx : CBBlur]
static const int NUM_WEIGHTS = 8;
struct SBlurParam {
CVector4 offset;
float weights[NUM_WEIGHTS];
float sampleScale;
};
SBlurParam m_blurParam;
ID3D11Buffer* m_cb = nullptr;
CVector2 m_sampleScale = { -1.0f,-1.0f };
CVector2 m_sampleScaleSetting = { -1.0f,-1.0f };
//Tv[
ID3D11SamplerState* m_samplerState = nullptr;
D3D11_VIEWPORT m_viewport;//r[|[g
};
}
| true |
53f8600013bd66d89592a4f02578f1b9138ce2be | C++ | Saurabh-12/learn_cpp | /oprator_loading/IOoverloading.cpp | UTF-8 | 1,028 | 3.828125 | 4 | [] | no_license | #include<iostream>
class Points
{
private:
double m_x, m_y, m_z;
public:
Points(double x = 0.0, double y = 0.0, double z = 0.0)
{
m_x = x;
m_y = y;
m_z = z;
}
friend std::ostream & operator<<(std::ostream &out, const Points &p);
friend std::istream & operator>>(std::istream &in, Points &p);
};
std::ostream & operator<<(std::ostream &out, const Points &p)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out<<"Point( "<<p.m_x<<", "<<p.m_y<<", "<<p.m_z<<" )";
return out;
}
std::istream & operator>>(std::istream &in, Points &p)
{
in >> p.m_x;
in >> p.m_y;
in >> p.m_z;
return in;
}
int main()
{
std::cout<<"Welcome saurabh \n";
Points point1(2.0, 3.5, 4.0);
Points point2(6.0, 7.5, 8.0);
std::cout<<point1<<" "<<point2<<"\n";
std::cout << "Enter a point: \n";
Points point;
std::cin >> point;
std::cout << "You entered: " << point << '\n';
return 0;
} | true |
0ef23435ac1b5bdc39970af997686392f3b7ec9a | C++ | saguila/EDA | /GISA2-01.cpp | UTF-8 | 553 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include "Stack.h"
void escribeDigitos(int numero) {
Stack <int> pila;
int calculo = 0;
do{ // Llenamos la pila
pila.push(numero % 10);
numero = numero / 10;
}while(numero > 0);
while(pila.size() > 0){
cout << pila.top();
if(pila.size() > 1) cout << " + ";
calculo =calculo + pila.top();
pila.pop();
}
cout << " = " << calculo << endl;
}
bool digitos() {
int n;
cin >> n;
if (n == -1)
return false;
escribeDigitos(n);
return true;
}
int main() {
while (digitos()){};
return 0;
}
| true |
6e4f58fb6499ac43430bcb1d5b71b971927a67be | C++ | kontai/CPlus | /L14重載運算和轉換/重載算術運算符.cpp | BIG5 | 1,887 | 3.75 | 4 | [] | no_license | /****************************************
[5/23/2017 21:18]
NMYB.cpp
****************************************/
#include<iostream>
#include<string>
using namespace std;
class Sales_item3
{
public:
Sales_item3(const string &book,const int units,const double amount):
isbn(book),unit_sold(units),revenue(amount){ }
/*
* ѩ+= , -= NBlݭn^OclassH,ҥHߺDW
* ѼƦCu@ӧΰ(B⤸this)
*/
Sales_item3& operator+=(const Sales_item3&);
Sales_item3& operator-=(const Sales_item3&);
friend ostream& operator<<(ostream &, const Sales_item3&);
private:
string isbn;
int unit_sold;
double revenue;
};
Sales_item3& Sales_item3::operator+=(const Sales_item3& rhs)
{
//"this->"iμg(wbclass@ΰ줺)
this->unit_sold += rhs.unit_sold;
this->revenue += rhs.revenue;
return *this;
}
Sales_item3 operator+(const Sales_item3& lhs,const Sales_item3& rhs){
/*
* pP@륿W[kB,ۥ[B,NGǵsH()
* B^ȫDreference,ҥHN@+,-B]non-class
*/
Sales_item3 ret(lhs);
ret += rhs;
return ret;
}
Sales_item3& Sales_item3::operator-=(const Sales_item3& rhs)
{
this->unit_sold -= rhs.unit_sold;
this->revenue -= rhs.revenue;
return *this;
}
Sales_item3 operator-(const Sales_item3& lhs, const Sales_item3& rhs) {
Sales_item3 ret(lhs);
ret -= rhs;
return ret;
}
ostream& operator<<(ostream& out, const Sales_item3& rhs){
out << rhs.isbn << "\t" << rhs.unit_sold << "\t" << rhs.revenue << endl;
return out;
}
int mainArithm() {
Sales_item3 item1(string("0-00-000"), 3, 20.0);
Sales_item3 item2(string("0-00-000"), 6, 120.0);
cout << item1 + item2 << endl;
Sales_item3 item3(item1);
item3 -= item1;
cout << item3 << endl;
system("pause");
return 0;
} | true |
8d492f9c9ff8c830dd7f7efdcb1fa2c0dca9d6ba | C++ | suptaphilip/C-Plus-Plus-Object-Oriented | /2. Class and Objects/1.Structre.cpp | UTF-8 | 1,187 | 4.125 | 4 | [
"MIT"
] | permissive | /*
write a proram to demonstrate structure in c++
*/
#include <iostream>
using namespace std;
struct Box
{
int length,width;
int Area()
{
return length*width;
}
};
int main(int argc, char const *argv[])
{
Box red;
red.length = 10;
red.width = 8;
cout << "Area is: " << red.Area() << endl;
return 0;
}
/*
In this chapter we will learn about class and objects
for learning classes first we need to understand the basic operations of structres
although classes are different from structure, the low level basic concept of classes are same as
structures
because classes are build on the basic concept of structures and evolve into a new programming paradism
called object oriented programming.
now, let's talk about struct
structs are mainly a package of variables and functions, it is also called as user defined data types
in a struct code block we can declare multiple variables and functions in a single code block as for the
requirements and access them using struct type variable
for accessing struct member variables we use dot(.) operators, sometimes which is called member access
operator
see the above code for better understanding
*/ | true |
de2ad90abfb1958a7127b85d7cc95592babe08a2 | C++ | arina237/3DS | /СТЗ/Лаб1/my_robot.h | WINDOWS-1251 | 1,639 | 2.703125 | 3 | [] | no_license | #pragma once
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
class MyRobot
{
public:
MyRobot() = default;
MyRobot(float width, float height,
float wheelWidth, float wheelDiameter,
float m_widtgTower, float m_heightTower,
float speed, float angularSpeed);
~MyRobot() = default;
//
void setSpeed(const float speed);
void setAngularSpeed(const float angularSpeed);
void setArea(Size2i area); //
int32_t setArea(Mat image);
int32_t setCenter(Mat image);
int32_t setCenter(float x, float y);
//
float getSpeed();
float getAngularSpeed();
int32_t rotate(int8_t buttonNumber);
void move(int8_t buttonNumber);
int32_t draw(Mat& outpytImage);
Point2i pointalculation(Point2i point, float angle);
int8_t checkPosition(Point2f point);
private:
Point2f m_center; //-
Size2i m_barrier; //
float m_width; //
float m_height; //
float m_widthTower; //
float m_heightTower; //
float m_wheelWidth; //
float m_wheelDiameter; //
float m_speed; //
float m_angularSpeed; //
float m_angle; //
float m_angleTower; //
Size2i m_area; //
}; | true |
640944dabd5f52342fef3b450e67569c033b735b | C++ | alur/LSBlur | /blurarea.cpp | UTF-8 | 3,217 | 2.625 | 3 | [] | no_license | #include "blurarea.h"
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// BlurArea - Constructor for BlurArea class.
//
// bmpWallpaper should be a pointer to a CBitmapEx class which contains a
// reconstruction of the wallpaper.
//
BlurArea::BlurArea(UINT X, UINT Y, UINT Width, UINT Height, CBitmapEx* bmpWallpaper, const char *szName, UINT Itterations)
{
// Store some values
m_X = X;
m_Y = Y;
m_Width = Width;
m_Height = Height;
m_Itterations = Itterations;
StringCchCopy(m_szName, MAX_PATH, szName);
// Initalize the bitmap handler
m_BitMapHandler = new CBitmapEx();
UpdateBackground(bmpWallpaper);
// Create Window
m_Window = CreateWindowEx(g_dwExStyle, g_szBlurHandler, szName, g_dwStyle, X, Y, Width, Height, g_hwndDesktop, NULL, g_hInstance, 0);
SetWindowLongPtr(m_Window, GWLP_USERDATA, (LONG)this);
SetWindowPos(m_Window, HWND_BOTTOM, 0,0,0,0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// ~BlurArea - Destructor
//
BlurArea::~BlurArea()
{
DestroyWindow(m_Window);
delete m_BitMapHandler;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Move - Moves the BlurArea
//
void BlurArea::Move(UINT X, UINT Y, CBitmapEx* bmpWallpaper)
{
m_X = X;
m_Y = Y;
if (bmpWallpaper)
{
UpdateBackground(bmpWallpaper);
}
SetWindowPos(m_Window, HWND_BOTTOM, X, Y, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Resize - Resizes the BlurArea
//
void BlurArea::Resize(UINT Width, UINT Height, CBitmapEx* bmpWallpaper)
{
m_Width = Width;
m_Height = Height;
if (bmpWallpaper)
{
UpdateBackground(bmpWallpaper);
}
SetWindowPos(m_Window, HWND_BOTTOM, 0, 0, Width, Height, SWP_NOACTIVATE | SWP_NOMOVE);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// SetItterations - Changes the number of itterations to do
//
void BlurArea::SetItterations(UINT Itterations, CBitmapEx* bmpWallpaper)
{
m_Itterations = Itterations;
if (bmpWallpaper)
{
UpdateBackground(bmpWallpaper);
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// UpdateBackground - Updates the image that is drawn
//
void BlurArea::UpdateBackground(CBitmapEx* bmpWallpaper)
{
// Copy over the wallpaper replica
m_BitMapHandler->Create(bmpWallpaper);
// Get the correct part of the wallpaper
m_BitMapHandler->Crop(m_X - GetSystemMetrics(SM_XVIRTUALSCREEN), m_Y - GetSystemMetrics(SM_YVIRTUALSCREEN), m_Width, m_Height);
// Apply blur
for (UINT i = 0; i < m_Itterations; i++)
m_BitMapHandler->GaussianBlur();
// Make sure that the window gets updated
if (m_Window)
{
RECT InvalidRect = {0, 0, m_Width, m_Height};
InvalidateRect(m_Window, &InvalidRect, false);
UpdateWindow(m_Window);
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Draw - Draws the blured area to DC
//
void BlurArea::Draw(HDC hDC)
{
m_BitMapHandler->Draw(hDC);
} | true |
8e39cc45159c6499fbaf914dd62c454300765c33 | C++ | kanicha/C.C-CS-2021_09_01-Test | /C.C++CS-2021_09_01-Test.cpp | UTF-8 | 2,958 | 3.625 | 4 | [] | no_license | // Sakamaki Daiki
#include <iostream>
int main()
{
char str[10];
do
{
int num1 = 0;
int num2 = 0;
int ans = 0;
printf("値を2つ入力してください \n");
scanf_s("%d", &num1);
scanf_s("%d", &num2);
printf("終了するには end を入力してください。\n");
scanf_s("%s", &str);
if (num1 % 2 == 0)
{
ans = num1 - num2;
printf("%d", ans);
}
else if (num1 % 2 == 1)
{
ans = num1 + num2;
printf("%d", ans);
}
} while (str, "end");
}
/// <summary>
/// 数値を2つ入力し、
/// 1番目に入力された値が奇数なら足し算、
/// 1番目に入力された値が偶数なら引き算を行うプログラムを作成せよ。
/// </summary>
void Work6()
{
int num1 = 0;
int num2 = 0;
int ans = 0;
printf("値を2つ入力してください \n");
scanf_s("%d", &num1);
scanf_s("%d", &num2);
if (num1 % 2 == 0)
{
ans = num1 - num2;
printf("%d", ans);
}
else if (num1 % 2 == 1)
{
ans = num1 + num2;
printf("%d", ans);
}
}
/// <summary>
/// 第6問のプログラムをループで行うようにし、
/// endと入力された場合終了するようにしてください。
/// endの入力は1番目の値の場所でも、2番目の値の場所でも、
/// 別途endの入力を受け付けるようでもどれでもいいです。
/// どこか一か所でendと入力して終了していれば正解とします。
/// </summary>
void Work7()
{
char str[10];
do
{
int num1 = 0;
int num2 = 0;
int ans = 0;
printf("値を2つ入力してください \n");
scanf_s("%d", &num1);
scanf_s("%d", &num2);
printf("終了するには end を入力してください。\n");
scanf_s("%s", &str);
if (num1 % 2 == 0)
{
ans = num1 - num2;
printf("%d", ans);
}
else if (num1 % 2 == 1)
{
ans = num1 + num2;
printf("%d", ans);
}
} while (str, "end");
}
/// <summary>
/// 第8問(10点)
/// 以下のプログラムをエラーを解決し、コンパイルエラーがない状態にし、
/// 実行できるようにしてください。
/// 解答がエラー個所をコメントアウトして実行できるようにするのはNGです。
/// (途中確認のためにコメントアウトをする分はOKです。)
/// 間違えている個所は4か所です。
/// </summary>
void Work8()
{
class Point
{
public:
Point() { Clear(); }
int Clear()
{
x = 0;
y = 0;
z = 0;
}
public:
int x, y, z;
};
{
Point point;
Point nextPoint;
nextPoint.x = 100;
nextPoint.y = 30;
while (1)
{
if (point.x < nextPoint.x)
{
point.x++;
}
else if (point.x > nextPoint.x)
{
point.x--;
}
if (point.y < nextPoint.y)
{
point.y++;
}
else if (point.y > nextPoint.y)
{
point.y--;
}
printf("pointX = %d\n", point.x);
printf("pointY = %d\n", point.y);
if (point.x == nextPoint.x &&
point.y == nextPoint.y)
{
break;
}
}
}
} | true |
ff89a6a27ab5d56588cdd63a6c7ceff733e22a99 | C++ | jflozanor/iso8583core | /unittest/testPadder.cpp | UTF-8 | 1,771 | 3.203125 | 3 | [] | no_license | #include "LeftPadder.h"
#include "RightPadder.h"
#include "NullPadder.h"
#include "gtest/gtest.h"
class testPadder : public ::testing::Test {
protected:
testPadder() {};
virtual ~testPadder() {};
virtual void SetUp(){};
virtual void TearDown(){};
};
TEST_F(testPadder, pad) {
std::string zero_test = "abc";
RightPadder::ZERO_PADDER->pad(zero_test, 15);
ASSERT_STREQ("abc000000000000", zero_test.c_str());
LeftPadder::ZERO_PADDER->pad(zero_test, 30);
ASSERT_STREQ("000000000000000abc000000000000", zero_test.c_str());
NullPadder::INSTANCE->pad(zero_test, 12312);
ASSERT_STREQ("000000000000000abc000000000000", zero_test.c_str());
std::string space_test = "abc";
RightPadder::SPACE_PADDER->pad(space_test, 15);
ASSERT_STREQ("abc ", space_test.c_str());
LeftPadder::SPACE_PADDER->pad(space_test, 30);
ASSERT_STREQ(" abc ", space_test.c_str());
NullPadder::INSTANCE->pad(space_test, 12312);
ASSERT_STREQ(" abc ", space_test.c_str());
}
TEST_F(testPadder, unpad) {
std::string zero_test = "000000000000000abc000000000000";
NullPadder::INSTANCE->unpad(zero_test);
ASSERT_STREQ("000000000000000abc000000000000", zero_test.c_str());
RightPadder::ZERO_PADDER->unpad(zero_test);
ASSERT_STREQ("000000000000000abc", zero_test.c_str());
LeftPadder::ZERO_PADDER->unpad(zero_test);
ASSERT_STREQ("abc", zero_test.c_str());
std::string space_test = " abc ";
NullPadder::INSTANCE->unpad(space_test);
ASSERT_STREQ(" abc ", space_test.c_str());
RightPadder::SPACE_PADDER->unpad(space_test);
ASSERT_STREQ(" abc", space_test.c_str());
LeftPadder::SPACE_PADDER->unpad(space_test);
ASSERT_STREQ("abc", space_test.c_str());
}
| true |
44078c64d5bbc7bfb17f0d92048cb7f4c99b0c7d | C++ | EdgarM-/Proyecto-Objetos | /lib/SFicha.h | UTF-8 | 3,292 | 2.65625 | 3 | [
"MIT"
] | permissive | /* Copyright (c) 2013 Santiago Quintero Pabón, Edgar Manuel Amézquita, Juan Camilo Arévalo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef SFicha_h
#define SFicha_h
class SJugador;
class SCasilla;
//! La clase SFicha es la base para las fichas
/*!
La clase define las funciones las funciones para modelar lo basico de una ficha como asignar a un jugador, conseguir o asignar la casilla donde esta la ficha
*/
class SFicha {
//! Jugador que posee la ficha
/*! \sa SJugador*/
protected:
SJugador* m_jugador;
//! Casilla en la que esta la ficha
/*! \sa SCasilla*/
SCasilla* m_casilla;
//! Entero que indica la casilla en la que se encuentra la ficha respecto al tablero empezando en 0, -1 indica que no esta en el tablero.
int m_posicion;
public:
//! Constructor
/*!
@ref m_jugador y @ref m_casilla empiezan en nullpointer.
\param posicion Entero que indica en que posicion empieza la ficha por defecto es -1
*/
SFicha(int posicion = -1)
: m_jugador(nullptr), m_casilla(nullptr), m_posicion(posicion)
{}
//!Devuelve la posicion en la que se encuentra la ficha respecto al tablero
/*!
\sa setPosicion(), getCasilla()
*/
int getPosicion()
{
return m_posicion;
}
//!Asigna a la ficha una posicion
/*!
\param posicion es un entero que indica en que posicion esta
\sa getPosicion(), setCasilla()
*/
void setPosicion(int posicion)
{
m_posicion = posicion;
}
//!Devuelve si la ficha se encuentra en alguna casilla
/*!
\sa getCasilla(), getPosicion()
*/
bool enTablero()
{
return (m_posicion >= 0);
}
//!Asigna a la ficha un Jugador
/*!
\param jugador es un puntero al jugador que posee la ficha
\sa getJugador(), SJugador
*/
void setJugador(SJugador* jugador)
{
m_jugador = jugador;
}
//!Devuelve el jugador al que le pertenece la ficha
/*!
\sa setJugador(), SJugador
*/
SJugador* getJugador()
{
return m_jugador;
}
//!Asigna a la ficha una casilla
/*!
\param casilla es una SCasilla la cual indica en que casilla esta la ficha
\sa getCasilla(),SCasilla
*/
void setCasilla(SCasilla* casilla)
{
m_casilla = casilla;
}
//!Devuelve la casilla en la cual esta la ficha
/*!
\sa setCasilla(), SCasilla
*/
SCasilla* getCasilla()
{
return m_casilla;
}
};
#endif // SFicha_h
| true |
4ffcad95c37f6e8351f80c01e4f2e95543005909 | C++ | roboFiddle/7405M_TowerTakeover_Code | /src/robot/RobotAux.cpp | UTF-8 | 1,109 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// Created by alexweiss on 8/12/19.
//
#include "Robot.hpp"
namespace meecan {
void Robot::setupMainLoop() {
mainLooper = new loops::Looper(0, "main");
mainLooper->flag_as_main();
loops::Loop *test = new loops::Loop();
test->onStart = [](){instance->lastState = -1;};
test->onDisable = [](){};
test->onLoop = [](){
if(pros::competition::is_disabled()) {
if(instance->lastState != 0)
instance->disabledInit();
instance->disabledLoop();
instance->lastState = 0;
}
else if(pros::competition::is_autonomous()) {
if(instance->lastState != 1)
instance->autonomousInit();
instance->autonomousLoop();
instance->lastState = 1;
}
else {
if(instance->lastState != 2)
instance->driverInit();
instance->driverLoop();
instance->lastState = 2;
}
};
std::shared_ptr<loops::Loop> ptr(test);
mainLooper->add(ptr);
}
}
void initialize() {
meecan::Robot::instance->robotInit();
}
void disabled() {}
void autonomous() {}
void opcontrol() {} | true |
2285c2d9039eefe714ff7b83bc065f9f7b377be8 | C++ | bang815/iFrogLab_F-60_UART | /Sample10-Android-Arduino-UART-LED/read/read.ino | UTF-8 | 820 | 2.71875 | 3 | [] | no_license | // 柯博文老師 www.powenko.com
#include <SoftwareSerial.h>
int ledPin = 10;
SoftwareSerial mySerial(10, 11); // RX, TX
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() {
while (mySerial.available()) {
delay(3);
char c = mySerial.read();
readString += c;
}
readString.trim();
if (readString.length() >0) {
if (readString == "m3 on"){
mySerial.println("switching on");
digitalWrite(ledPin, HIGH);
}
if (readString == "m3 off")
{
mySerial.println("switching off");
Serial.println("switching off");
digitalWrite(ledPin, LOW);
}
readString="";
}
}
| true |
64acb11837a7ccab81380890ce5f581e6b3bf059 | C++ | finnhittson/csds-397-hw3 | /research_assistant.h | UTF-8 | 1,196 | 3.1875 | 3 | [] | no_license | #ifndef RESEARCHASSISTANT_H_INCLUDE
#define RESEARCHASSISTANT_H_INCLUDE
#include "student.h"
#include "staff.h"
class ResearchAssistant : public Staff, public Student // definition of class ResearchAssistant with parent class of Student and Staff
{
public:
// default constructor ResearchAssistant(area, title, department, salary, id, name)
ResearchAssistant(std::string = "n/a", std::string = "n/a", std::string = "n/a", double = 0.00, int = 0, std::string = "n/a");
// default constructor ResearchAssistant(area, major, gpa, gradyear, id, name)
ResearchAssistant(std::string = "n/a", std::string = "n/a", double = 0.0, int = 0, int = 0, std::string = "n/a");
void set_research(std::string); // getter and setter for research variable
std::string get_research() const;
std::string print() const; // print function returning properties of object
bool default_student() const; // checks for student default values
bool default_staff() const; // checks for staff default values
private:
std::string research; // variable for research
bool ternary;
};
#endif // RESEARCHASSISTANT_H_INCLUDE
| true |
62d66c794964dbd2fe272041ff822533b1a7b5f1 | C++ | mililanirobotics/robot2013 | /2012Tracking/2013Tracking.cpp | UTF-8 | 7,743 | 2.578125 | 3 | [] | no_license | #include "WPILib.h"
#include "math.h"
/**
* This code is able to control a two motor system and get encoder values.
* Note that the drive system takes input from the left and right analog
* sticks of the Logitech controllers. If you want to use the normal
* joysticks, then change
*/
class RobotDemo : public SimpleRobot
{
RobotDrive arcade1; //Front left and right motors drive
RobotDrive arcade2; //Back left and right motors drive
Joystick leftstick; //For general drive, retrieval, and end game
Joystick rightstick; //For tracking and scoring
Jaguar drivefrontleft; //Jaguar connected to the top left motor
Jaguar drivebackleft; //Jaguar connected to the bot left motor
Jaguar drivefrontright; //Jaguar connected to the top right motor
Jaguar drivebackright; //Jaguar connected to the bot right motor
Jaguar shooter1; //Jaguar connected to a shooter motor
Jaguar shooter2; //Jaguar connected to a shooter motor
Jaguar retrieval; //Jaguar connected to the conveyer belt motor
Gyro vertical; //Vertical gyro reading angle in y for endgame
Gyro horizontal; //Horizontal gyro reading angle in x for drive correction
Encoder encodershooter; //Encoder connected to the shooter for RPM
Solenoid bridgedevice; //controls pneumatic bridge device
Victor turntable; //controls turret window motor
Victor bridgevictor; //controls window motor for deploying bridge device
Relay spike; //controls ringlight
Compressor compressor;
float distance(float heightpixel)
{
float fov = 54;
float widthtarget = 2 ;
float yresolution = 360;
float distance = widthtarget*yresolution/heightpixel/tan(fov*3.14159265/180);
return (distance);
}
public:
RobotDemo(void):
arcade1(drivefrontleft,drivefrontright), //Setting top left and top right motors to arcade 1
arcade2(drivebackleft,drivebackright), //Setting bot left and bot right motors to arcade 2
leftstick(1),
rightstick(2),
drivefrontleft(1),
drivebackleft(2),
drivefrontright(3),
drivebackright(4),
shooter1(5),
shooter2(6),
retrieval(7),
vertical(1,1), //Gyro(slot,channel)
horizontal(1,2),
encodershooter(1,2),
bridgedevice(3,1),
turntable(9),
bridgevictor(8),
spike(1,Relay::kForwardOnly),
compressor(1,2)
{
}
void Autonomous(void)
{
DriverStationLCD *screen = DriverStationLCD::GetInstance();
screen->PrintfLine(DriverStationLCD::kUser_Line1,"Autonomous");
screen->UpdateLCD();
while (IsAutonomous())
{
/* Locate & set up camera to be used*/
AxisCamera &camera = AxisCamera::GetInstance("10.28.53.11");
camera.WriteResolution(AxisCamera::kResolution_320x240);
camera.WriteCompression(80);//Compresses the image(?)
camera.WriteBrightness(50);//Sets the brightness to 80 on a scale from 0-100
int matches = 0;
float average = 0;
/* Turn on ringlight */
spike.Set(Relay::kOn);
/* Connect to DriverStation */
DriverStationLCD *screen = DriverStationLCD::GetInstance();
screen->PrintfLine(DriverStationLCD::kUser_Line1,"CAA Active");
screen->UpdateLCD();
/* Create pointer for current image */
HSLImage* originalHSLPointer;
originalHSLPointer = camera.GetImage();
/* COLOR PLANE EXTRACTION */
/* Move the image from HSL image pointer to 8-bit image pointer and extract color planes by luminance */
Image* pointer8bit = imaqCreateImage(IMAQ_IMAGE_U8, 0);
//int imaqExtractColorPlanes(const Image* image, ColorMode mode, Image* plane1, Image* plane2, Image* plane3);
imaqExtractColorPlanes(originalHSLPointer, IMAQ_HSL, NULL, NULL, pointer8bit);
delete originalHSLPointer;
/* THRESHOLD */
/* Move the image from 8-bit image pointer and filter using a brightness threshold */
//int imaqThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax, int useNewValue, float newValue);
imaqThreshold(pointer8bit, pointer8bit, 223, 255, int useNewValue, float newValue);
/* ADV MORPHOLOGY (SIZE FILTER) */
/* Filter image by size (remove small particles) */
/* ADV MORPHOLOGY (CONVEX HULL) */
/* Fill in holes in image */
/* CONVERSION (8-BIT TO 16-BIT) */
/* Convert image from 8-bit to 16-bit */
/* CONVERSION (16-BIT TO 8-BIT) */
/* Convert image from 16-bit to 8-bit */
/* SHAPE DETECTION (DETECT RECTANGLES) */
/* Detect rectangle shapes in image */
#if 0
ROI *roi;
Rect rectangle;
rectangle.top = 120;
rectangle.left = 0;
rectangle.width = 320;
rectangle.height = 120;
imaqAddRectContour(roi,rectangle);
#endif
static RectangleDescriptor recDescriptor =
{
10, // minWidth
200, // maxWidth
10, // minHeight
200 // maxHeight
};
static CurveOptions curveOptions = //extraction mode specifies what the VI identifies curves in the image. curve options are all the
{
IMAQ_NORMAL_IMAGE, // extractionMode
75, // threshold
IMAQ_NORMAL, // filterSize
25, // minLength
15, // rowStepSize
15, // columnStepSize
10, // maxEndPointGap
FALSE, // onlyClosed
FALSE // subpixelAccuracy
};
static ShapeDetectionOptions shapeOptions =
{
IMAQ_GEOMETRIC_MATCH_ROTATION_INVARIANT, // mode
NULL, // angle ranges
0, // num angle ranges
{75, 125}, // scale range
500 // minMatchScore
};
RectangleMatch* recmatch = imaqDetectRectangles(bitcast, &recDescriptor, &curveOptions, &shapeOptions, NULL, &matches);
//imaqDispose(roi);
average = recmatch->corner[0].x/4 + recmatch->corner[1].x/4 + recmatch->corner[2].x/4 + recmatch->corner[3].x/4;
//screen->PrintfLine(DriverStationLCD::kUser_Line5, "%f", average); //debugging code, perhaps?
#if 1
if (matches == 0)
{
imaqWriteFile(bitcast, "/tmp/bitcast.jpg", NULL);
}
if (average == 0) //does this make it stop moving if no matches are found?
{
turntable.Set(0.0);
}
else if (average > 170 && average < 180) //stop turret and print matches when centered
{
turntable.Set(0.0);
screen->PrintfLine(DriverStationLCD::kUser_Line2,"Match: %i %f", matches,distance(recmatch->height));
screen->UpdateLCD();
}
//go various speeds and directions based on image location. Far from center = high speed.
else if (average > 180 && average < 185)
{
turntable.Set(0.1);
}
else if (average > 185)
{
turntable.Set(0.25);
}
else if (average > 165 && average < 170)
{
turntable.Set(-0.1);
}
else if (average < 165)
{
turntable.Set(-0.25);
}
imaqDispose(bitcast);
imaqDispose(recmatch);
int count = 0;
if(average > 170 && average < 180)
{
//CHIAKAZING THE SHOOTER SPEEDS ARE SOMEWHAT ARBITRARY. TEST AND FIX.
shooter1.Set(.7);
shooter2.Set(.7);
Wait(5.0);
for(count = 0; count != 2; count++) {
retrieval.Set(1.0);
Wait(1.0);
retrieval.Set(0.0);
Wait(2);
}
shooter1.Set(0.0);
shooter2.Set(0.0);
retrieval.Set(0.0);
}
#endif
}
}
void OperatorControl(void)
{
DriverStationLCD *screen = DriverStationLCD::GetInstance();
screen->PrintfLine(DriverStationLCD::kUser_Line1,"Operator Control");
screen->UpdateLCD();
/*DriverStationLCD *screen = DriverStationLCD::GetInstance();
screen->UpdateLCD();
while (IsOperatorControl())
{
vic.Set(0.0);
screen->PrintfLine(DriverStationLCD::kUser_Line5,"no button");
screen->UpdateLCD();
while (stick1.GetRawButton(1)) {
screen->PrintfLine(DriverStationLCD::kUser_Line5,"Button1");
vic.Set(0.5);
}
while (stick1.GetRawButton(2)) {
screen->PrintfLine(DriverStationLCD::kUser_Line5,"Button2");
vic.Set(-0.5);
}
}*/
}
};
START_ROBOT_CLASS(RobotDemo);
| true |
524c2024858b8c19159f1b13e7ce8b60cb476510 | C++ | carvluc/URI_Online_Judge | /Há Muito, Muito Tempo Atrás - 1962.cpp | UTF-8 | 483 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<math.h>
using namespace std;
int main(){
long long int N, T, resposta;
cin>>N;
if(N>=1 && N<=100000){
while(N--){
cin>>T;
if(T>=0 && T<=pow(2,31)){
resposta = T - 2015;
if(resposta == 0 || resposta<0){
resposta = abs(resposta) + 1;
cout<< resposta + " A.C."<<endl;
}else{
cout<<resposta + " D.C."<<endl;
}
}
}
}
system("PAUSE");
return 0;
}
| true |
6d895954e1e0a16d6ac2a787bd67690e21d719c3 | C++ | Goom11/interview_practice | /deleteDups/deleteDups.cpp | UTF-8 | 630 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <map>
using std::cout;
using std::endl;
using std::list;
using std::map;
void deleteDups(list<int>& n) {
map<int, bool> table;
list<int>::iterator n_it = n.begin();
while (n_it != n.end()) {
if (table[*n_it]) {
n.erase(n_it);
n_it--;
} else {
table[*n_it] = true;
}
n_it++;
}
}
int main() {
int nums[] = {1, 2, 3, 4, 4, 4, 5, 4, 2, 6, 1, 7, 865};
list<int> num_list (nums, nums + 12);
deleteDups(num_list);
list<int>::iterator n_it = num_list.begin();
while (n_it != num_list.end()) {
cout << *n_it << endl;
n_it++;
}
}
| true |
c98be83e0e7c69e977925c6691ce974108700bd3 | C++ | Low-profile/ShenruoyangNa | /ll-compiler/expr.cpp | UTF-8 | 8,072 | 2.59375 | 3 | [] | no_license |
#include "parser.h"
using namespace std;
vector<unique_ptr<ExprAST>> Parser::Exprs(vector<token_t>::size_type idx, vector<token_t>::size_type &ret_idx, AST_node *node)
{
// auto n_expr = new AST_node("expr");
auto n_pexprs = new AST_node("_exprs");
auto tmp_idx = idx;
vector<unique_ptr<ExprAST>> node_n;
if (idx < tok_size)
{
while(true)
{
auto n_expr = new AST_node("expr");
auto args_n = Expr(idx, ret_idx, n_expr);
if(!args_n)
{
ret_idx = tmp_idx;
return node_n;
}
else if(ret_idx < tok_size && tokens[ret_idx].literal == ",")
{
node_n.push_back(move(args_n));
idx = ret_idx + 1;
continue;
}
node_n.push_back(move(args_n));
return node_n;
}
}
else
{
ret_idx = idx;
return node_n;
}
}
unique_ptr<ExprAST> Parser::Expr(vector<token_t>::size_type idx, vector<token_t>::size_type &ret_idx, AST_node *node)
{
if (idx < tok_size)
{
if (tokens[idx].type == T_True) // true
{
auto n_true = new AST_node("true");
node->appendChild(n_true);
ret_idx = idx + 1;
return llvm::make_unique<BoolExprAST>(true);
}
else if (tokens[idx].type == T_False) // false
{
auto n_false = new AST_node("false");
node->appendChild(n_false);
ret_idx = idx + 1;
return llvm::make_unique<BoolExprAST>(false);
}
else if (tokens[idx].type == T_IntConstant) // -?[0-9]+
{
auto n_constant = new AST_node("constant");
node->appendChild(n_constant);
ret_idx = idx + 1;
return llvm::make_unique<NumberExprAST>(atof(tokens[idx].literal.c_str()), integer_width);
}
else if (tokens[idx].type == T_Identifier) // ident
{
auto n_exprs = new AST_node("exprs");
auto n_expr = new AST_node("expr");
node->appendChild(new AST_node("n_ident"));
if (idx + 1 < tok_size)
{
if (tokens[idx + 1].literal == "[" ) // ident\[expr\]
{
auto expr_n = Expr(idx + 2, ret_idx, n_expr);
if(!expr_n || tokens[ret_idx].literal != "]")
{
ret_idx = idx + 1;
return llvm::make_unique<VariableExprAST>(tokens[idx].literal);
}
node->appendChild(n_expr);
ret_idx = ret_idx + 1;
return llvm::make_unique<ArrExprAST>(tokens[idx].literal,move(expr_n));
}
else if (tokens[idx + 1].literal == "(" ) // ident(<, expr>*)
{
auto exprs_n = Exprs(idx + 2, ret_idx, n_exprs);
if(tokens[ret_idx].literal == ")")
{
node->appendChild(n_exprs);
ret_idx = ret_idx + 1;
return llvm::make_unique<CallExprAST>(tokens[idx].literal,move(exprs_n));
}
else
{
ret_idx = idx + 1;
return llvm::make_unique<VariableExprAST>(tokens[idx].literal);
}
}
else
{
ret_idx = idx + 1;
return llvm::make_unique<VariableExprAST>(tokens[idx].literal);
}
}
else
{
ret_idx = idx + 1;
return llvm::make_unique<VariableExprAST>(tokens[idx].literal);
}
return llvm::make_unique<VariableExprAST>(tokens[idx].literal);
}
else if (tokens[idx].type == T_SizeOf
&& idx + 1 < tok_size && tokens[idx + 1].literal == "("
&& idx + 2 < tok_size && tokens[idx + 2].type == T_Identifier
&& idx + 3 < tok_size && tokens[idx + 3].literal == ")") // sizeof(ident)
{
node->appendChild(new AST_node("n_sizeof"));
node->appendChild(new AST_node("("));
node->appendChild(new AST_node("n_identifier"));
node->appendChild(new AST_node(")"));
ret_idx = idx + 4;
return llvm::make_unique<SizeofExprAST>(tokens[idx + 2].literal);
}
else if (
tokens[idx].type == T_Input && idx + 1 < tok_size
&& tokens[idx + 1].literal == "(" && idx + 2 < tok_size
&& tokens[idx + 2].literal == ")") // input()
{
node->appendChild(new AST_node("n_input"));
node->appendChild(new AST_node("("));
node->appendChild(new AST_node(")"));
ret_idx = idx + 3;
return llvm::make_unique<inputExprAST>();
}
else if (tokens[idx].literal == "(") // (
{
auto n_lexpr = new AST_node("expr");
auto n_binop = new AST_node("binop");
auto n_rexpr = new AST_node("expr");
auto n_expr = new AST_node("expr");
auto n_unaryop = new AST_node("unaryop");
auto n_expr2 = new AST_node("expr");
auto n_expr3 = new AST_node("expr");
string opr;
if (auto l_expr_n = Expr(idx + 1, ret_idx, n_lexpr)) // (expr
{
string op;
if (Binop(ret_idx, ret_idx, n_binop, op) )// (expr binop expr)
{
auto r_expr_n = Expr(ret_idx, ret_idx, n_rexpr);
if(!r_expr_n || tokens[ret_idx].literal != ")")
{
ret_idx = idx;
return nullptr;
}
node->appendChild(n_lexpr);
node->appendChild(n_binop);
node->appendChild(n_rexpr);
ret_idx = ret_idx + 1;
return llvm::make_unique<BinaryExprAST>(op,move(l_expr_n),move(r_expr_n));
}
else if (
tokens[ret_idx].literal == "?" && Expr(ret_idx + 1, ret_idx, n_expr2) && tokens[ret_idx].literal == ":" && Expr(ret_idx + 1, ret_idx, n_expr3) && tokens[ret_idx].literal == ")") // (expr ? expr : expr)
{
node->appendChild(n_lexpr);
node->appendChild(n_expr2);
node->appendChild(n_expr3);
ret_idx = ret_idx + 1;
return llvm::make_unique<NumberExprAST>(0, integer_width);
}
else
ret_idx = idx;
return nullptr;
}
else if (Unaryop(idx + 1, ret_idx, n_unaryop, opr)) // (unaryop expr)
{
auto expr_v = Expr(ret_idx, ret_idx, n_expr);
if(!expr_v || tokens[ret_idx].literal != ")")
{
ret_idx = idx;
return nullptr;
}
node->appendChild(new AST_node("("));
node->appendChild(n_unaryop);
node->appendChild(n_expr);
node->appendChild(new AST_node(")"));
ret_idx = ret_idx + 1;
return llvm::make_unique<UnaryExprAST>(opr,move(expr_v));
}
else
{
ret_idx = idx;
return nullptr;
}
}
else
{
ret_idx = idx;
return nullptr;
}
}
else
{
ret_idx = idx;
return nullptr;
}
}
| true |
83ba9f2de94b6e34f7f69aff4de8f99d04faffc4 | C++ | jaredmales/ExAOLab | /Bohlman/code/old_files/read_mixed_exp/read_mixed_exp.cpp | UTF-8 | 7,369 | 3.40625 | 3 | [] | no_license | /*! \file read_mixed_exp.cpp
\brief A documented file that takes 100 different pictures for 10 exposure times, for a total of 1000 images taken. Can subtract median photo from each.
Initializes the pylon resources, takes each photo and subtracts the median photo from each.
*/
#include "write_basler_fits.h"
// Subtracts a median image from the given file name
/** Gets the name of the file, opens it, opens the median file, subtracts the median file from the given file name, writes the new file.
* \return an integer: 0 upon exit success, 1 otherwise
*/
int subtract_images(char* file_name)
{
int exitCode = 0;
const char* median_name = "median_lowexp_image.fits"; // Name of the median image that is subtracted from each image
fitsfile *fptr1, *fptr2;
if (fits_open_file(&fptr1, file_name, READWRITE, &exitCode)) // Open image file passed in function
{
fits_report_error(stderr, exitCode); // if it does not exist, print out any fits error messages
return 1;
}
if (fits_open_file(&fptr2, median_name, READONLY, &exitCode)) // Open median image file
{
fits_report_error(stderr, exitCode); // If it does not exist, print out any fits error messages
return 1;
}
long fpixel[2] = { 1,1 }; // Instructs cfitsio to read a pixel at a time
double * pixel_arr1, * pixel_arr2, * new_arr;
pixel_arr1 = new double[640 * 480]; // Array that holds first image data
pixel_arr2 = new double[640 * 480]; // Array that holds second image data
new_arr = new double[640 * 480]; // Array that holds final image data
int nelements = 640 * 480;
if (fits_read_pix(fptr1, TDOUBLE, fpixel, nelements, NULL, pixel_arr1, NULL, &exitCode))
{ // Store image data into array
fits_report_error(stderr, exitCode); // Prints out any fits error messages
return 1;
}
if (fits_read_pix(fptr2, TLONGLONG, fpixel, nelements, NULL, pixel_arr2, NULL, &exitCode)) // Store image data into array
{
fits_report_error(stderr, exitCode); // Prints out any fits error messages
return 1;
}
int j, k; // Subtract median image from passed file and store value into new array
int width = 640, height = 480;
for (k = 0; k < height; ++k)
{
for (j = 0; j < width; ++j)
{
new_arr[k*width + j] = pixel_arr1[k*width + j] - pixel_arr2[k*width + j];
}
}
long fpixel2[2] = { 1,1 };
if (fits_write_pix(fptr1, TDOUBLE, fpixel2, nelements, new_arr, &exitCode) != 0) // Writes pointer values to the image
{
fits_report_error(stderr, exitCode); // Prints out any fits error messages
return 1;
}
fits_close_file(fptr1, &exitCode); // Close and free up everything
fits_close_file(fptr2, &exitCode);
delete(pixel_arr1);
delete(pixel_arr2);
delete(new_arr);
return exitCode;
}
// Main function
/** Initializes pylon resources, takes pictures, subtracts median image, closes all pylon resources.
* \return an integer: 0 upon exit success, 1 otherwise
*/
int main(int argc, ///< [in] the integer value of the count of the command line arguments
char* argv[] ///< [ch.ar] the integer value of the count of the command line arguments
)
{
int exitCode = 0;
int expArray[c_countOfImagesToGrab]; // Create an array of exposure values
int i, exp = 500; // 500, 900, 1300, 1800, 2200, 2600, 3000, 3400, 3800, 4200
for (i = 0; i < c_countOfImagesToGrab; i++)
{
if (i % 100 == 0 && i > 0)
exp = exp + 400;
expArray[i] = exp;
}
i = 0;
PylonInitialize(); // Initializes pylon runtime before using any pylon methods
try
{
CDeviceInfo info; // Variable for camera info
info.SetDeviceClass(Camera_t::DeviceClass()); // Get camera info
Camera_t camera(CTlFactory::GetInstance().CreateFirstDevice()); // Creates an instant camera object with the camera device found first.
for (int j = 0; j < c_countOfImagesToGrab; ++j) // For every image
{
string file_name = (string)camera.GetDeviceInfo().GetModelName() + " " + (string)camera.GetDeviceInfo().GetSerialNumber(); // Get camera name from model number and serial number
char* newstr = &file_name[0u]; // Cast camera name to char* because of cfitsio
CGrabResultPtr ptrGrabResult;
int exposure = expArray[j]; // Get desired exposure value from array
camera.Open(); // Open camera parameters
camera.ExposureAuto.SetValue(ExposureAuto_Off); // Turn off auto exposure
camera.ExposureTime.SetValue(exposure); // Set exposure to desired value
camera.StartGrabbing(1); // Starts the grabbing of c_countOfImagesToGrab images.
int tempcam = (int)camera.DeviceTemperature.GetValue(); // Get camera temperature
camera.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException); // Waits for an image and then retrieves it. A timeout of 5000 ms is used.
camera.Close(); // Close camera parameters
if (ptrGrabResult->GrabSucceeded()) // If image is grabbed successfully:
{
struct image *cam_image = new struct image; // Set up image struct
char real_filename[30]; // Set up image file name from given strings, exposure value, and image number
strncpy(real_filename, "!", sizeof(real_filename));
strcat(real_filename, "fitsimg_exp");
char exp_str[10];
sprintf(exp_str, "%d", exposure);
strcat(real_filename, exp_str);
char num_str[10];
sprintf(num_str, "_%d", i);
strcat(real_filename, num_str);
strcat(real_filename, ".fits");
cam_image->imgname = real_filename;
cam_image->imgGrab = ptrGrabResult;
cam_image->exposure = exposure;
cam_image->temp = tempcam;
cam_image->camname = newstr;
if (write_basler_fits(cam_image) != 0) // if image building did not work
{
throw "Bad process in fits image writing!"; // throw error
exitCode = 1;
}
else { // if image building did work
cout << "Image grab and write successful" << endl;
*(cam_image->imgname)++; // Subtract image
if (subtract_images(cam_image->imgname) == 0)
{
cout << "Median image subtracted" << endl;
}
else
{
cout << "Error in file subtracting process" << endl;
exitCode = 1;
}
// free struct
}
delete(cam_image);
}
else // If image is not grabbed successfully
{
cout << "Error: " << ptrGrabResult->GetErrorCode() << " " << ptrGrabResult->GetErrorDescription() << endl; //Prints an error
}
++i;
}
}
catch (const GenericException &e) // Provides error handling.
{
std::cerr << "An exception occurred." << endl
<< e.GetDescription() << endl;
exitCode = 1;
}
Pylon::PylonTerminate(); // Releases all pylon resources.
return exitCode;
}
| true |
7590422bccaab399dd7a400dacb19e006cecf81b | C++ | Benjamin-Crysup/protengine | /includes_pro/protengine_index_fasfa.h | UTF-8 | 2,787 | 2.59375 | 3 | [] | no_license | #ifndef PROTENGINE_INDEX_FASFA_H
#define PROTENGINE_INDEX_FASFA_H 1
#include <vector>
#include "whodun_compress.h"
#include "protengine_index_failgz.h"
/**The number of characters to take before splitting up into blocks.*/
#define FASFA_BLOCK_SIZE 1000
/**
* This will build a fasfa file from multiple source files..
* @param allSrc THe starting files.
* @param targetName THe name of the file to produce.
* @param temporaryFolder The folder to put temporary files in.
* @param numThread THe number of threads to use.
* @param maxByteLoad The number of bytes to load.
* @param useComp The compression method to use.
* @return Whether there was an exception.
*/
int buildComboFileFromFailgz(std::vector<FailGZReader*>* allSrc, const char* targetName, const char* temporaryFolder, int numThread, uintptr_t maxByteLoad, CompressionMethod* useComp);
/**Will read a fasfa file.*/
class FasfaReader{
public:
/**
* Opens up a fasfa file.
* @param fasfaFileName The name of the fasfa file.
* @param compMeth The compression method to use.
*/
FasfaReader(const char* fasfaFileName, CompressionMethod* compMeth);
/**
* Cleans up.
*/
~FasfaReader();
/**
* Loads in the data for a sequence.
* @param seqID The sequence index.
* @return Whether there was a problem loading.
*/
int loadInSequence(uintptr_t seqID);
/**The number of sequences in the current entry.*/
intptr_t numSequences;
/**The number of items in the current sequence (each item is two entries).*/
uintptr_t numInCurrent;
/**The current sequence.*/
uintptr_t* currentSequence;
private:
/**The file to read through.*/
FILE* actualFile;
/**The compression/decompression algorithm.*/
CompressionMethod* useComp;
/**THe currently loaded sequence offsets in the file.*/
intptr_t sequenceOffsets[FASFA_BLOCK_SIZE];
/**The currently loaded sequence low ind.*/
intptr_t seqOffLowInd;
/**The currently loaded sequence high ind.*/
intptr_t seqOffHigInd;
/**The space presently allocated for the docompression buffer.*/
uintptr_t decomAlloc;
/**The decompression buffer.*/
char* decomBuffer;
/**The file pointer buffer.*/
char* filptrBuffer;
/**The number of items allocated for the current sequence.*/
uintptr_t currentAlloc;
};
/**
* This will find a sequence in a fasfa file.
* @param failFile The failgz files used to build the fassa.
* @param fasfaFile The fasfa file in question.
* @param findSeqs The sequences to look for.
* @param findSeqInd The index of the first sequence.
* @param toReport The place to put all the found locations.
* @return Whether there was a problem.
*/
int findSequencesInFasfa(std::vector<FailGZReader*>* failFile, FasfaReader* fassaFile, std::vector<const char*>* findSeqs, uintptr_t findSeqInd, SequenceFindCallback* toReport);
#endif | true |
61c902da06c7739c887428ff1c4b967b7d08c3bc | C++ | ssh352/CppWorkStream | /BookSamples/CppPL_BS/CppFromBS1/main.cpp | UTF-8 | 3,162 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <limits>
#include <memory>
#include <cstddef>
using namespace std;
int test_si()
{
string from, to;
cin >> from >> to; // get source and target file names
ifstream is {from}; // input stream for file "from"
istream_iterator<string> ii {is}; // input iterator for stream
istream_iterator<string> eos {}; // input sentinel
ofstream os{to}; // output stream for file "to"
ostream_iterator<string> oo {os,"\n"}; // output iterator for stream
vector<string> b {ii,eos}; // b is a vector initialized from input [ii:eos)
sort(b.begin(),b.end()); // sor t the buffer
unique_copy(b.begin(),b.end(),oo); // copy buffer to output, discard replicated values
return !is.eof() || !os; // return error state (§2.2.1, §38.3)
}
void digits()
{
for(int i = 1;i!=10;++i)
cout << static_cast<char>('0'+i);
char c = 255;
int ci = c;
cout << ci << std::endl;
}
void test_limit()
{
cout << "size of long " << sizeof(1L) << '\n';
cout << "size of long long " << sizeof(1LL) << '\n';
cout << "largest float == " << std::numeric_limits<float>::max() << '\n';
cout << "char is signed == " << std::numeric_limits<char>::is_signed << '\n';
}
void g111(char c, signed char sc, unsigned char uc)
{
c = 255; // implementation-defined if plain chars are signed and have 8 bits
c = sc; // OK
c = uc; // implementation-defined if plain chars are signed and if uc’s value is too large
sc = uc; // implementation defined if uc’s value is too large
uc = sc; // OK: conversion to unsigned
sc = c; // implementation-defined if plain chars are unsigned and if c’s value is too large
uc = c; // OK: conversion to unsigned
}
void user123(const vector<int>& vx)
{
constexpr int bufmax = 1024;
alignas(int) int buffer[bufmax]; // uninitialized
const int max = min(vx.size(),bufmax/sizeof(int));
uninitialized_copy(vx.begin(),vx.begin()+max,buffer);
cout << buffer[0] << endl;
// ...
}
void testuse()
{
vector<int> tv{8,1,2,3};
user123(tv);
}
int testpf(char* str)
{
if (str)
return 0;
else
return -1;
}
void testpv(int* pi)
{
void* pv;
pv = pi;
int ti = 0;
//*pv ;
//++pv;
//cout << ti << endl;
int* pi2 = static_cast<int*>(pv);
cout << *pi2 << endl;
}
void testpointer()
{
int i1{10};
int* pi; //pointer to int
pi = &i1;
cout << *pi << endl;
char** ppc;
char c1{'d'};
char* pc=&c1;
ppc = &pc;
cout << "address of pc:" << ppc << "value of pc" << *ppc << endl;
cout << "value of char:" << **ppc << endl;
int* ap[15];
cout << ap[0] << endl;
int (*fp)(char*) ;
fp = testpf;
char* tc= "Hello World";
cout << "result" << fp(tc) << endl;
testpv(pi);
}
void print_mij(int* m, int dim1, int dim2)
{
for (int i = 0; i!=dim1; i++)
{
for (int j = 0; j!=dim2; j++)
cout << m[i*dim2+j] << '\t'; // obscure
cout << '\n';
}
}
int main()
{
cout << "Hello World!" << endl;
//test_si();
digits();
test_limit();
testuse();
testpointer();
return 0;
}
| true |
f812fb83043c25703f3550238fa970e90e963eac | C++ | Hesh0/Sabre3D | /Source/Sabre3D/Sabre3D.cpp | UTF-8 | 7,004 | 2.6875 | 3 | [] | no_license | #include "Sabre3Dstd.h"
#include "../Shader Handling/Shader.h"
#include "../Window/Window.h"
#include "../Graphics/OpenGLRenderer.h"
#include "../Graphics/3D/Mesh.h"
#include "../Graphics/Texture.h"
#include "../Math/S3DVectors/Vector.h"
#include "../Math/Mat4.h"
template <unsigned int N> struct Fib
{
enum
{
Val = Fib<N - 1>::Val + Fib<N - 2>::Val
};
};
template <> struct Fib <0> { enum { Val = 0 }; };
template <> struct Fib <1> { enum { Val = 1 }; };
#define TFib(n) Fib<(n)>::Val
#if defined(OPENGLCONTEXT)
int main()
{
#if 0
// printf("PI is %f\n", PI);
std::cout << TFib(45) << std::endl;
Mat4 mat1 = S3DMath::IdentityMatrix();
/*printf("Should be [1.00, 0.00, 0.00, 0.00]"
" [0.00, 1.00, 0.00, 0.00]"
" [0.00, 0.00, 1.00, 0.00]"
" [0.00, 0.00, 0.00, 1.00] is "); */
std::cout << mat1 << std::endl;
Mat4 mat2 = S3DMath::ScalingMatrix(2, 2, 2);
/*printf("Should be [2.00, 0.00, 0.00, 0.00]"
" [0.00, 2.00, 0.00, 0.00] "
" [0.00, 0.00, 2.00, 0.00]"
" [0.00, 0.00, 0.00, 1.00] is "); */
std::cout << mat2 << std::endl;
/*printf("Should be [1.00, 0.00, 0.00, 2.00]"
" [0.00, 1.00, 0.00, 2.00]"
" [0.00, 0.00, 1.00, 2.00]"
" [0.00, 0.00, 0.00, 1.00] is "); */
Mat4 mat3 = S3DMath::TranslationMatrix(2, 2, 2);
std::cout << mat3 << std::endl;
float mat0[] = {
2, 3, 4, 4,
7, 4, 3, 9,
1, 4, 5, 10,
11, 45, 17, 21
};
/*printf("Should be [2.00, 3.00, 4.00, 4.00]"
" [7.00, 4.00, 3.00, 9.00] "
" [1.00, 4.00, 5.00, 10.00]"
" [11.00, 45.00, 17.00, 21.00] is ");*/
Mat4 mat40 = S3DMath::ArbitraryMatrix(&mat0);
std::cout << mat40 << std::endl;
printf("mat1 * mat40 ");
mat1 *= mat40;
std::cout << "should be " << mat40 << "is " << mat1 << std::endl;
Vec4 vec(1.0f, 2.0f, 3.0f);
printf("Should be [1.00, 2.00, 3.00, 1.00] is ");
std::cout << vec << std::endl;
printf("After multiplication by identity matrix ");
printf("Should be [1.00, 2.00, 3.00, 1.00] is ");
vec = S3DMath::IdentityMatrix() * vec;
std::cout << vec << std::endl;
printf("Scaling Matrix with vector test:\n");
printf("Should be [2, 4, 6, 1] is ");
vec = S3DMath::ScalingMatrix(2, 2, 2) * vec;
std::cout << vec << std::endl;
Mat4 rotation = S3DMath::RotateXAxis(90);
Mat4 rotation1 = S3DMath::RotateYAxis(90);
Mat4 rotation2 = S3DMath::RotateZAxis(90);
Mat4 rotation3 = S3DMath::ArbitraryRotation(Vec3(1, 0, 0), 90);
Mat4 scale = S3DMath::ArbitraryScaleMatrix(Vec3(1, 0, 0), 2);
Mat4 projection = S3DMath::OrthoProjectionMat(Vec3(1, 0, 0));
printf("Rotation matrices:\n\n");
std::cout << rotation << std::endl;
std::cout << rotation1 << std::endl;
std::cout << rotation2 << std::endl;
std::cout << rotation3 << std::endl;
std::cout << scale << std::endl;
std::cout << projection << std::endl;
//float pi = acos(-1.0f);
float r = S3DMath::PI / 4.0f;
printf("r is %f\n", r);
printf("cos90 = %f, cos0 = %f\n", -std::cos(r), std::cos(0));
printf("sin90 = %.2f sin0 = %f\n", std::sin((90.0f / 180) * S3DMath::PI), std::sin(0));
Vec2 v1(2, 3);
Vec3 v2(2, 3, 4);
Vec4 v3(2, 3, 4, 5);
printf("%s, %s, %s\n", v1.ToString(), v2.ToString(), v3.ToString());
#endif
// places _CrtDumpMemoryLeaks() at every exit point in the program.
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Logger::Init();
Window window(1000, 1000 / 14 * 9, "Random");
window.Init();
OpenGLRenderer renderer;
GLint major, minor;
std::string msg("OpenGL vendor: ");
S3D_LOG("INFO", msg + reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
msg = "Renderer: ";
S3D_LOG("INFO", msg + reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
msg = "OpenGL Version: ";
S3D_LOG("INFO", msg + std::to_string(major) + "."+ std::to_string(minor));
msg = "GLSL Version: ";
S3D_LOG("INFO", msg + reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
GLenum triShaderTypes[] = {GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
// GLenum shaderTypes[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER};
// Shader cube(R"(Source\Shaders\Cube)", 2, shaderTypes);
Shader triShader(R"(Source\Shaders\Triangle)", triShaderTypes, _arrlen(triShaderTypes));
float points[] = {
+0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
+0.5f, +0.5f, 0.0f
};
/*float points[18] = {
-0.5f, -0.5f, 0.0f,
-0.5f, +0.5f, 0.0f,
+0.5f, +0.5f, 0.0f,
+0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
+0.5f, +0.5f, 0.0f
};
float texCoords[8] = {
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f
};
int indices[6] = {
0, 1, 2,
2, 3, 0
}; */
/* float points[] = {
-0.25f,-0.25f,-0.25f, // triangle 1 : begin
-0.25f,-0.25f, 0.25f,
-0.25f, 0.25f, 0.25f, // triangle 1 : end
0.25f, 0.25f,-0.25f, // triangle 2 : begin
-0.25f,-0.25f,-0.25f,
-0.25f, 0.25f,-0.25f, // triangle 2 : end
0.25f,-0.25f, 0.25f,
-0.25f,-0.25f,-0.25f,
0.25f,-0.25f,-0.25f,
0.25f, 0.25f,-0.25f,
0.25f,-0.25f,-0.25f,
-0.25f,-0.25f,-0.25f,
-0.25f,-0.25f,-0.25f,
-0.25f, 0.25f, 0.25f,
-0.25f, 0.25f,-0.25f,
0.25f,-0.25f, 0.25f,
-0.25f,-0.25f, 0.25f,
-0.25f,-0.25f,-0.25f,
-0.25f, 0.25f, 0.25f,
-0.25f,-0.25f, 0.25f,
0.25f,-0.25f, 0.25f,
0.25f, 0.25f, 0.25f,
0.25f,-0.25f,-0.25f,
0.25f, 0.25f,-0.25f,
0.25f,-0.25f,-0.25f,
0.25f, 0.25f, 0.25f,
0.25f,-0.25f, 0.25f,
0.25f, 0.25f, 0.25f,
0.25f, 0.25f,-0.25f,
-0.25f, 0.25f,-0.25f,
0.25f, 0.25f, 0.25f,
-0.25f, 0.25f,-0.25f,
-0.25f, 0.25f, 0.25f,
0.25f, 0.25f, 0.25f,
-0.25f, 0.25f, 0.25f,
0.25f,-0.25f, 0.25f
}; */
// Mesh mesh(points, texCoords, indices, _arrlen(points), _arrlen(texCoords), _arrlen(indices));
// Mesh cubem(points, _arrlen(points));
Mesh triangle(points, _arrlen(points));
//Texture tex(R"(Resources\dirtTexture.jpg)");
// shader.CreateProgram();
// cube.CreateProgram();
triShader.CreateProgram();
while (!window.OpenGLShouldClose())
{
window.OpenGLClear();
// shader.Bind();
// cube.Bind();
triShader.Bind();
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// tex.Bind(0);
renderer.Render(triangle);
window.OpenGLUpdate();
}
_CrtDumpMemoryLeaks(); // This is supposed to report any memory leaks to stderr before termination.
Logger::Destroy();
return 0;
}
#endif
#if defined(DX12CONTEXT)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
Logger::Init();
S3D_LOG("INFO", "Shit Started");
Window window(1000, 1000 / 14 * 9, "Random");
window.Init(hInstance, nCmdShow);
while (true)
window.Loop();
Logger::Destroy();
return 0;
}
#endif | true |
f37a966f2717f8e4fe298fea1cd65627ca5cd16f | C++ | pareenj/Coding | /Trees/Practice/Find Height of Binary Tree.cpp | UTF-8 | 350 | 3.328125 | 3 | [] | no_license | // Binary Tree - Implemenation in C++
// Find height of Binary Tree
#include <iostream>
using namespace std;
// Definition of Node for Binary Tree
struct Node
{
int data;
Node* left;
Node* right;
};
int FindHeight(Node* root)
{
if(root == NULL) return -1;
return (max(FindHeight(root->left), FindHeight(root->right))) + 1;
}
| true |
277bb5b23306c740292f070cbc23fbd52082f3e9 | C++ | BenoitStackler/Projet_irrlicht | /src/projectile.hpp | UTF-8 | 688 | 2.5625 | 3 | [] | no_license | /* projectile.hpp */
#ifndef PROJECTILE_HPP
#define PROJECTILE_HPP
#include <irrlicht.h>
class Character;
class Projectile
{
public:
Projectile(Character *caster, float speed, float damage);
Projectile(Character *caster);
Projectile();
void impact();
void move();
void position(irr::core::vector3df position);
void direction(irr::core::vector3df direction);
irr::core::vector3df position();
irr::core::vector3df direction();
irr::scene::ISceneNode* node();
private:
// Attributs
float m_speed;
float m_damage;
irr::core::vector3df m_position;
irr::core::vector3df m_direction;
irr::scene::ISceneNode *m_node;
};
#endif | true |
f87079c57cf3c8de1ccc50d153f2c2898204c1cc | C++ | ThierDev/Camera_Gimbal_Project | /Kalman_filter/Kalman_Lib.cpp | ISO-8859-2 | 1,855 | 3.078125 | 3 | [] | no_license | #include "Kalman_Lib.h"
Kalman::Kalman() {
Q_angle = 0.001f; // Erreur en position.
Q_error_s = 0.003f;// Erreur en vitesse.
R_measure = 0.03f;// Variance(v)
angle_after_kalman = 0.0f;// remet zro l'angle
speed_after_kalman = 0.0f; // remet zro l'erreur
// Ceci est la matrice de covariance d'erreur// t=0 , matrice==0
P[0][0] = 0.0f;
P[0][1] = 0.0f;
P[1][0] = 0.0f;
P[1][1] = 0.0f;
};
float Kalman::getAngle(float newAngle, float newRate, float dt) {
//tape-1// on calcul l'angle avec (\theta avec drive)
speed_after_kalman_corrected = newRate - speed_after_kalman;
angle_after_kalman += speed_after_kalman_corrected* dt; // ici on voit l'intgration
//tape-2 // Mise a jour de la matrice de covariance
P[0][0] += dt*(dt*(P[1][1]) - P[1][0] - P[0][1] + Q_angle);
P[0][1] -= dt*P[1][1];
P[1][0] -= dt*P[1][1];
P[1][1] += Q_error_s * dt;
//tape-4// Calcul du scalaire S
float S = P[0][0] + R_measure; // erreur totale (Estimation + Mesur)
//tape-5// Calcul du vecteur gain de kalman
float K[2];
K[0] = (P[0][0]) / S;
K[1] = (P[0][1]) / S;
//tape-3// On calcule l'angle \theta et le \theta\dot drive.
float y = newAngle - angle_after_kalman; // calcul de la variable d'innovation.
//Etape-6// on calcule l'angle avec une proportionnalite de kalman
angle_after_kalman += K[0] * y;
speed_after_kalman += K[1] * y;
//Etape-7// calcul de la matrice de covariance a posteriori.
float P00_temp = P[0][0];
float P01_temp = P[0][1];
P[0][0] -= K[0] * P00_temp;
P[0][1] -= K[0] * P01_temp;
P[1][0] -= K[1] * P00_temp;
P[1][1] -= K[1] * P01_temp;
return angle_after_kalman; // on retourne l'angle que l'on veut.
};
// pointeur qui permet de dfinir l'angle de dpart.
void Kalman::setAngle(float angle_after_kalman) { this->angle_after_kalman = angle_after_kalman; };
| true |
57d325ca80c201c0351b0f53221708808ec9f002 | C++ | bintrue/design-patterns-play | /zdekany/Chain of Responsibility/example.cpp | UTF-8 | 2,493 | 4.3125 | 4 | [] | no_license | #include <iostream>
using namespace std;
// Abstract class called Handler
// It is abstract because it has a pure virtual function.
// This prevents instances of Handler being created directly.
class Handler {
protected:
Handler *next;
public:
// Constructor
Handler() { next = NULL; }
// Pure virtual function
virtual void request(int value) = 0;
// Sets next handler in the chain
void setNextHandler(Handler *nextInLine) {
next = nextInLine;
}
};
// SpecialHandler is a type of Handler but has a limit and ID
// It also determines if it can handle the request or needs to send it on
// If it is the last in the chain and can't handle it, it lets the user know.
class specialHandler : public Handler {
private:
int limit;
int ID;
public:
specialHandler(int theLimit, int theID) {
limit = theLimit;
ID = theID;
}
// Handles incoming request
void request(int value) {
if (value < limit) {
cout << "Handler " << ID << " handled the request with a limit of " << limit << endl;
}
else if (next != NULL) {
// Passes it on to the next in the chain
next->request(value);
}
else {
// Last in chain, so let the user know it was unhandled.
cout << "Sorry, I am the last handler (" << ID << ") and I couldn't even handle that request." << endl;
}
}
};
int main ()
{
// Create three special handlers with ids "1, 2 and 3"
// Since a specialHandler is a type of "Handler" they are legal statements.
Handler *h1 = new specialHandler(10, 1);
Handler *h2 = new specialHandler(20, 2);
Handler *h3 = new specialHandler(30, 3);
// Chain up the handlers together
h1->setNextHandler(h2);
h2->setNextHandler(h3);
// Handled by handler 2 because handler 1 couldn't handle it,
// so it passed it on to handler 2 which could handle since it is less than 20
h1->request(18);
// No handler could handle this, so will trigger last handler's else
// statement showing that it is the last and still couldn't handle the request.
// You could also tack on a default version for the end if you like.
h1->request(40);
// Clean up our pointers
delete h1;
delete h2;
delete h3;
return 0;
}
| true |
fa63de54c78a51f33b0a59dd8617dd1f21d0c7f5 | C++ | 15831944/barry_dev | /src/DataField/FieldUtil.cpp | UTF-8 | 4,464 | 2.546875 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005
// Packet Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification is not permitted unless authorized in writing by a duly
// appointed officer of Packet Engineering, Inc. or its derivatives
//
//
// Modification History:
// 07/08/2012 Created by Chen Ding
////////////////////////////////////////////////////////////////////////////
#include "DataField/FieldUtil.h"
#include "SEUtil/StrValueInfo.h"
#include "Rundata/Rundata.h"
bool
AosFieldUtil::setFieldValue(
char *record_data,
const int record_len,
char *value,
const int value_len,
const AosStrValueInfo &valinfo,
AosRundata* rdata)
{
// This function assumes the record 'record_data' has a field whose start
// position is 'field_offset' and field length is 'field_len'. It
// copies the value 'value' into the field.
// 1. If 'value' is shorter than 'field_len', it will either left align
// (left_alignment == true) or right align (left_alignment == false)
// the contents.
// a. If it is left alignment, it sets the remaining bytes by
// 'back_padding'.
// b. If it is right alignment, it sets the leading unused bytes
// by 'front_padding'.
// 2. If 'value' is too long, the data is handled by 'data_too_long_policy'.
//
// Note that there are 'field_data_len' and 'field_len'. If no 'null' is
// appended at the end of a field, 'field_len' is always the same as
// 'field_data_len'. Otherwise, 'field_len' is 'field_data_len' + 1.
// bool set_field_null = (valinfo.field_len == valinfo.field_data_len + 1);
bool rslt = true;
/*
if (!value || value_len <= 0)
{
memset(&record_data[valinfo.field_offset], valinfo.back_padding, valinfo.field_data_len);
goto setTrailingNull;
}
*/
if (value_len > valinfo.field_data_len)
{
// Data are too long.
switch (valinfo.data_too_long_policy)
{
case AosDataTooLongPolicy::eTreatAsError:
//AosSetErrorU(rdata, "data_too_long") << enderr;
memset(&record_data[valinfo.field_offset], valinfo.back_padding, valinfo.field_data_len);
rslt = false;
goto setTrailingNull;
case AosDataTooLongPolicy::eResetRecord:
memset(&record_data[valinfo.field_offset], valinfo.too_long_padding, valinfo.field_data_len);
rslt = true;
goto setTrailingNull;
case AosDataTooLongPolicy::eIgnoreSilently:
rslt = true;
goto setTrailingNull;
case AosDataTooLongPolicy::eTrimLeft:
memcpy(&record_data[valinfo.field_offset], &value[value_len - valinfo.field_data_len],
valinfo.field_data_len);
rslt = true;
goto setTrailingNull;
case AosDataTooLongPolicy::eTrimRight:
default:
memcpy(&record_data[valinfo.field_offset], value, valinfo.field_data_len);
rslt = true;
goto setTrailingNull;
}
}
else if (value_len < valinfo.field_data_len)
{
int delta = valinfo.field_data_len - value_len;
switch (valinfo.data_too_short_policy)
{
case AosDataTooShortPolicy::eTreatAsError:
//AosSetErrorU(rdata, "data_too_short") << enderr;
memset(&record_data[valinfo.field_offset], valinfo.back_padding, valinfo.field_data_len);
rslt = false;
goto setTrailingNull;
case AosDataTooShortPolicy::eIgnoreSilently:
rslt = true;
goto setTrailingNull;
case AosDataTooShortPolicy::eCstr:
// Ketty 2014/01/11
rslt = true;
memcpy(&record_data[valinfo.field_offset], value, value_len);
record_data[valinfo.field_offset + value_len] = 0;
return rslt;
case AosDataTooShortPolicy::eAlignRight:
memset(&record_data[valinfo.field_offset], valinfo.front_padding, delta);
memcpy(&record_data[valinfo.field_offset+delta], value, value_len);
rslt = true;
goto setTrailingNull;
case AosDataTooShortPolicy::eAlignLeft:
default:
memcpy(&record_data[valinfo.field_offset], value, value_len);
memset(&record_data[valinfo.field_offset+value_len], valinfo.back_padding, delta);
if (valinfo.set_field_null) record_data[valinfo.field_offset + value_len] = 0;
rslt = true;
goto setTrailingNull;
}
}
else
{
// The same length as 'field_data_le'.
memcpy(&record_data[valinfo.field_offset], value, value_len);
rslt = true;
goto setTrailingNull;
}
setTrailingNull:
if (valinfo.set_trailing_null) record_data[valinfo.field_offset + valinfo.field_len] = 0;
return rslt;
}
| true |
72d4c3591cd20b4f8ae02e5b8f6b89331e86d28d | C++ | itsDhruv01/HiringProblem_1 | /Hiring.cpp | UTF-8 | 1,388 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
//#include<random>
#include<ctime>
using namespace std;
void getWeight(int *wt, int n)
{
for(int i=0; i<n; i++)
cin>>*wt++;
cout<<endl;
}
void getPermutation(int *p, int n)
{
for(int i=0; i<n; i++)
{
int j = 0;
*(p+i) = rand()% n + 1;
srand(time(NULL));
while(j<i)
{
if(*(p+j++)==*(p+i))
{
j=0;
*(p+i) = rand()%n +1;
}
}
}
}
void printPermutation(int *p, int n)
{
cout<<"Permutation Selected :";
for(int i=0; i<n; i++)
{
cout<<*(p+i)<<" ";
}
cout<<endl;
}
void getCandidate(int *wt, int *p, int n, int reqWt)
{
for(int i=0; i<n; i++)
{
if(*(wt+*(p+i)-1)==reqWt)
{
cout<<"Candidate "<<*(p+i)<<" is Selected\n";
return;
}
cout<<"Candidate "<<*(p+i)<<" is NOT Selected\n";
}
cout<<"No Candidate is Selected!\n";
}
int main()
{
int n;
cout<<"Enter Number of Candidates :";
cin>>n;
int weight[n];
cout<<"Enter Weight for Candidates\n";
getWeight(&weight[0], n);
int reqWt;
cout<<"Enter the Required Weight :";
cin>>reqWt;
int arr[n];
getPermutation(&arr[0], n);
printPermutation(&arr[0], n);
getCandidate(&weight[0], &arr[0], n, reqWt);
return 0;
}
| true |
1c2e96a9954e863517534ef6f3ea0a1db987b97a | C++ | qdaggett/FryydGames | /SpriteLib2/FHazard.cpp | UTF-8 | 1,108 | 2.8125 | 3 | [] | no_license | #include "FHazard.h"
#include <iostream>
FHazard::FHazard(float newX, float newY, int newS, int h, Sprite newM, float w, float g)
:Monster(newX, newY, newS, h, newM)
{
theWidth = w;
gLvl = g;
}
void FHazard::move(int backLimit, int frontLimit, int &thecounter)
{
//try to incorporate physics here
float temp = getY() - 5;
float xtemp = getX();
setY(temp);
monster.set_position(xtemp, temp);
}
void FHazard::Collisions(float playerx, float playery, float &phealth)
{
float distanceBetween;
float radiuses = 50.0f;
//the formula
distanceBetween = sqrt(pow(getY() - playery, 2) + pow(getX() - playerx, 2));
if (distanceBetween < radiuses && getHealth() > 0)
{
phealth -= 30;
setHealth(0);
}
}
void FHazard::checkTrigger(float playerx, float playery)
{
if (playerx > monster.get_position().x-60 && playerx < monster.get_position().x + theWidth)
{
if (playery >= 50)
{
Move = true;
}
}
}
bool FHazard::getMove()
{
return Move;
}
void FHazard::setMove(bool temp)
{
Move = temp;
}
void FHazard::reset(float x, float y)
{
setX(x);
setY(y);
monster.set_position(x, y);
} | true |
e9a78e870d9de26808eec8ec148bb3a85637873c | C++ | x0mka/Stud | /Queue.cpp | WINDOWS-1251 | 832 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include "Queue.h"
Queue::Queue()
{
length = 0;
};
Queue::~Queue()
{
};
void Queue::ExtractMax()
{
for (int counter = 0; counter < length - 1; counter++)
{
value[counter] = value[counter + 1];
key[counter] = key[counter + 1];
length--;
}
};
void Queue::Insert()
{
int k;
string str;
cout << " " << endl;
cin >> k;
cout << " " << endl;
cin >> str;
if (length == 0)
{
value[0] = str;
key[0] = k;
length++;
}
else
{
for (int counter = 0; counter < length; counter++)
{
if (key[counter] < k)
{
for (int i = length; i >= counter; i--)
{
value[i+1] = value[i];
key[i + 1] = key[i];
}
value[counter] = str;
key[counter] = k;
length++;
}
}
}
};
string Queue::Maximum()
{
return value[0];
}
| true |
aa942b468b189206777f1375a0218194c4647968 | C++ | egortrue/NeVK | /src/engine/scene/objects/camera.cpp | UTF-8 | 2,977 | 2.921875 | 3 | [] | no_license | #include "camera.h"
void Camera::update(float deltaTime) {
updatePosition(deltaTime);
updateDirections();
updateView();
}
void Camera::updateView() {
viewMatrix = glm::lookAt(
transform.position, // Позция камеры
transform.position + direction.front, // Позиция цели
direction.upper);
}
void Camera::updateProjection() {
projectionMatrix = glm::perspective(
glm::radians(projection.fov),
projection.aspect,
projection.near,
projection.far);
}
void Camera::updateProjection(Projection& projection) {
this->projection.fov = projection.fov;
this->projection.aspect = projection.aspect;
this->projection.near = projection.near;
this->projection.far = projection.far;
updateProjection();
}
void Camera::updateRotation(double xpos, double ypos) {
// Смещение мыши
double xoffset = xpos - mouse.pos.x;
double yoffset = mouse.pos.y - ypos;
// Новые координаты мыши
mouse.pos.x = xpos;
mouse.pos.y = ypos;
// Запишем градуcы поворота
transform.rotation.y += xoffset * speed.rotation;
transform.rotation.x += yoffset * speed.rotation;
// Лимиты поворота
if (transform.rotation.x > 89.0f)
transform.rotation.x = 89.0f;
if (transform.rotation.x < -89.0f)
transform.rotation.x = -89.0f;
// Нормализация градусной величины
transform.rotation.x = transform.rotation.x - 360 * (static_cast<int>(transform.rotation.x) / 360);
transform.rotation.y = transform.rotation.y - 360 * (static_cast<int>(transform.rotation.y) / 360);
transform.rotation.z = transform.rotation.z - 360 * (static_cast<int>(transform.rotation.z) / 360);
updateDirections();
updateView();
}
void Camera::updateDirections() {
// Обновим векторы направления движения (вектор вверх всегда константен)
glm::float3 front;
front.x = sin(glm::radians(transform.rotation.y)) * cos(glm::radians(transform.rotation.x));
front.y = sin(glm::radians(transform.rotation.x));
front.z = -cos(glm::radians(transform.rotation.y)) * cos(glm::radians(transform.rotation.x));
direction.front = glm::normalize(front);
direction.right = glm::normalize(glm::cross(direction.front, direction.upper));
}
void Camera::updatePosition(float deltaTime) {
if (!(move.left || move.right || move.up || move.down || move.forward || move.back)) {
return;
}
float shift = speed.movement * deltaTime;
if (move.up)
transform.position += shift * direction.upper;
if (move.down)
transform.position -= shift * direction.upper;
if (move.right)
transform.position += shift * direction.right;
if (move.left)
transform.position -= shift * direction.right;
if (move.forward)
transform.position += shift * direction.front;
if (move.back)
transform.position -= shift * direction.front;
}
| true |
df10fe6f02056068e9f615c1ec852a00c70b4035 | C++ | mukeshjais/FAANG-Leetcode-questions | /house_robber.cpp | UTF-8 | 452 | 2.703125 | 3 | [] | no_license | class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
for(int i=2;i<n;i++){
int max=0;
for(int j=0;j<i-1;j++){
if(nums[j]>max)
max=nums[j];
}
nums[i]+=max;
}
int max_sum=0;
for(int i=0;i<n;i++){
if(nums[i]>max_sum)
max_sum=nums[i];
}
return max_sum;
}
};
| true |
5f74106728ad9911a4e4ea2ce37e4c3c8e1f1359 | C++ | RoseySoft/bobcat | /bobcat/tty/echo.cc | UTF-8 | 332 | 2.828125 | 3 | [] | no_license | #include "tty.ih"
bool Tty::echo(EchoType type)
{
struct termios tty = d_tty;
switch (type)
{
case ON:
tty.c_lflag |= ECHO;
break;
case OFF:
tty.c_lflag &= ~ECHO;
break;
default:
break;
}
return tcsetattr(d_fd, TCSANOW, &tty) == 0;
}
| true |
02ab14966fc0356819f2d7f1abba966a1b42972b | C++ | minorfish/ACM | /UVA/11054.cpp | UTF-8 | 386 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
const int N = 100005;
long long wines[N];
int main () {
int n;
while (scanf ("%d", &n), n) {
for (int i = 0; i < n; i++) {
scanf ("%lld", &wines[i]);
}
long long count = labs(wines[0]);
for (int i = 1; i < n; i++) {
wines[i] += wines[i - 1];
count += labs(wines[i]);
}
printf ("%lld\n", count);
}
return 0;
}
| true |
1f74870ae6d87100261c4a79e81260caac770f13 | C++ | nikonikolov/c_compiler | /src/DataStructures/WhileLoop.cpp | UTF-8 | 2,110 | 2.703125 | 3 | [] | no_license | #include "WhileLoop.h"
WhileLoop::WhileLoop(BaseExpression* condition_in, Statement* single_statement_in, const StatementT& stat_type_in) :
Statement(stat_type_in), condition(condition_in), loop_body(NULL), single_statement(single_statement_in) {}
WhileLoop::WhileLoop(BaseExpression* condition_in, CompoundStatement* loop_body_in, const StatementT& stat_type_in) :
Statement(stat_type_in), condition(condition_in), loop_body(loop_body_in), single_statement(NULL) {}
WhileLoop::~WhileLoop(){
if(loop_body!=NULL) delete loop_body;
if(single_statement!=NULL) delete single_statement;
if(condition!=NULL) delete condition;
}
void WhileLoop::pretty_print(const int& indent){
string white_space, new_scope_indent=" ";
white_space.resize(indent, ' ');
cout<<white_space<<"WHILE LOOP"<<endl;
cout<<white_space<<"CONDITION: ";
if(condition!=NULL) condition->pretty_print(0);
cout<<endl;
if(loop_body!=NULL) loop_body->pretty_print(indent);
if(single_statement!=NULL) single_statement->pretty_print(indent);
}
void WhileLoop::renderasm(ASMhandle& context){
ASMhandle new_context(context);
string condition_check = new_context.get_assembly_label();
string loop_body_label = new_context.get_assembly_label();
if(stat_type==ST_while_loop){
// Branch to condition check
assembler.push_back(ss<<pad<<"b"<<condition_check<<endl);
assembler.push_back(ss<<pad<<"nop"<<endl);
}
assembler.push_back(ss<<loop_body_label<<":"<<endl);
// Execute loop body
if(single_statement!=NULL) single_statement->renderasm(new_context);
if(loop_body!=NULL) loop_body->renderasm(new_context, false);
assembler.push_back(ss<<condition_check<<":"<<endl);
// Perform condition check
if(condition==NULL) generate_error("Loop condition must be present");
ExprResult** cond_result = new ExprResult*(NULL);
condition->renderasm(new_context, cond_result);
(*cond_result)->load("$t5");
assembler.push_back(ss<<pad<<"bne"<<"$0, $t5, "<<loop_body_label<<endl);
assembler.push_back(ss<<pad<<"nop"<<endl);
context.exit_scope(new_context); // Correct $sp in branch delay slot if necessary
}
| true |
3ac860f3512b4af66e86974d55e5c67e2aae254a | C++ | yaokeepmoving/ELL | /libraries/predictors/neural/tcc/Activation.tcc | UTF-8 | 2,665 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: Activation.tcc (neural)
// Authors: Chris Lovett
//
////////////////////////////////////////////////////////////////////////////////////////////////////
// stl
#include <algorithm>
#include <limits>
namespace ell
{
namespace predictors
{
namespace neural
{
template <typename ElementType>
ElementType ActivationImpl<ElementType>::operator()(const ElementType input) const
{
return Apply(input);
}
template <typename ElementType>
ElementType ActivationImpl<ElementType>::ApplyIndex(const ElementType input, const math::IntegerTriplet& /*index*/) const
{
return Apply(input);
}
template <typename ElementType>
Activation<ElementType>::Activation(std::unique_ptr<ActivationImpl<ElementType>>& impl) : _impl(std::move(impl))
{}
template <typename ElementType>
Activation<ElementType>::Activation(ActivationImpl<ElementType>* impl) : _impl(impl)
{
}
template <typename ElementType>
Activation<ElementType>::Activation(const Activation<ElementType>& other) : _impl(std::move(other._impl->Copy()))
{}
template <typename ElementType>
Activation<ElementType>& Activation<ElementType>::operator=(const Activation<ElementType>& other)
{
if (this != &other)
{
auto temp = other._impl->Copy();
_impl.swap(temp);
}
return *this;
}
template <typename ElementType>
ElementType Activation<ElementType>::Apply(const ElementType input) const
{
return _impl->Apply(input);
}
template <typename ElementType>
ElementType Activation<ElementType>::operator()(const ElementType input) const
{
return _impl->Apply(input);
}
template <typename ElementType>
ElementType Activation<ElementType>::ApplyIndex(const ElementType input, const math::IntegerTriplet& index) const
{
return _impl->ApplyIndex(input, index);
}
template <typename ElementType>
void Activation<ElementType>::Apply(math::ColumnVector<ElementType>& input) const
{
input.Transform([this](ElementType value) { return _impl->Apply(value); });
}
template <typename ElementType>
void Activation<ElementType>::WriteToArchive(utilities::Archiver& archiver) const
{
archiver["activation"] << _impl;
}
template <typename ElementType>
void Activation<ElementType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
archiver["activation"] >> _impl;
}
}
}
}
| true |
afdb8e3894b69cd07597591e518d3f39e7caff5f | C++ | hazelguo/Computer-Network-Practicum | /MachineLearning/generate_similarity_matrix.cc | UTF-8 | 3,735 | 2.671875 | 3 | [] | no_license | #include "StudentInfo.h"
#include "BPNeuralNet.h"
using namespace std;
BPNeuralNet BP_neural_net;
StudentInfo *GetInputForOneStudent() {
int _school;
double _GPA;
double _IELTS;
int _TOEFL;
double _GRE_overall;
double _GRE_verbal;
double _GRE_writing;
int _research_intern;
int _company_intern;
int _paper;
printf("Please enter the id of your current university: ");
scanf("%d", &_school);
printf("Please enter your GPA: ");
scanf("%lf", &_GPA);
printf("Please enter your IELTS score (enter -1 if you don't have IELTS score): ");
scanf("%lf", &_IELTS);
printf("Please enter your TOEFL score (enter -1 if not): ");
scanf("%d", &_TOEFL);
printf("Please enter your overall GRE score (enter -1 if not): ");
scanf("%lf", &_GRE_overall);
printf("Please enter your GRE verbal score (enter -1 if not): ");
scanf("%lf", &_GRE_verbal);
printf("Please enter your GRE writing score (enter -1 if not): ");
scanf("%lf", &_GRE_writing);
printf("Please enter the number of research projects you have participated: ");
scanf("%d", &_research_intern);
printf("Please enter the number of company internship: ");
scanf("%d", &_company_intern);
printf("Please enter the number of papers you have participated: ");
scanf("%d", &_paper);
return new StudentInfo(_school, _GPA, _IELTS, _TOEFL, _GRE_overall,
_GRE_verbal, _GRE_writing, _research_intern, _company_intern, _paper, -1);
}
double calculate_similarity(StudentInfo* a, StudentInfo* b){
vector<double> properties;
vector<double> similarity(1);
StudentInfo::GetProperties(a, b, properties);
BP_neural_net.recognize(properties, similarity);
return similarity[0];
}
int main(){
/* vector<StudentInfo*> students_info;
BP_neural_net.GetWeightAndThreshold();
School::ReadIn("IOFiles/USASchool.in", "IOFiles/ChinaSchool.in");
StudentInfo::ReadIn(students_info, "IOFiles/StudentsInfo.in");
StudentInfo::Standardize(students_info);
int student_num = students_info.size();
FILE *fp;
fp = fopen("IOFiles/StudentSimilarityMatrix", "w");
for(int i = 0; i < student_num; ++i) {
for (int j = 0; j < student_num; ++j) {
double similarity = calculate_similarity(students_info[i], students_info[j]);
fprintf(fp, "%lf ", similarity);
}
fprintf(fp, "\n");
}
fclose(fp);
*/
vector<StudentInfo*> students_info;
// StudentSimilarity tmp;
// priority_queue<StudentSimilarity> pq;
// BP_neural_net.GetWeightAndThreshold();
School::ReadIn("IOFiles/USASchool.in", "IOFiles/ChinaSchool.in");
cerr << "What hapensss.s.....3" << endl;
StudentInfo::ReadIn(students_info, "IOFiles/StudentsInfo.in");
cerr << "What happensss.....0" << endl;
StudentInfo::Standardize(students_info);
cerr << "What happenss .........." << endl;
StudentInfo *student_info = GetInputForOneStudent();
//input_info.push_back(student_info);
//GetInputForOneStudent(student_info);
cerr << "what happensss......1" << endl;
StudentInfo::Standardize(student_info);
students_info.push_back(student_info);
int student_num = students_info.size();
FILE *fp = fopen("IOFiles/OriginalSimilarityMatrix", "w");
for(int i = 0; i < student_num; ++i) {
for (int j = 0; j < student_num; ++j) {
double similarity;
bool valuable;
StudentInfo::GetSimilarity(students_info[i], students_info[j], similarity, valuable);
if (valuable) fprintf(fp, "%lf ", similarity);
else fprintf(fp, "NULL ");
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
| true |
e8824bb001eb65e336f8a2f9c7e69b9fae4a213a | C++ | oraeng/px4_offboard_jw | /src/single_iris_hold_pos.cpp | UTF-8 | 7,584 | 2.515625 | 3 | [] | no_license | /**
* @file offb_node.cpp
* @brief Offboard control example node, written with MAVROS version 0.19.x, PX4 Pro Flight
* Stack and tested in Gazebo SITL
*/
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/TwistStamped.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>
#include <cmath>
mavros_msgs::State current_state;
void state_cb(const mavros_msgs::State::ConstPtr& msg){
current_state = *msg;
}
geometry_msgs::PoseStamped current_position;
void curr_pos_cb(const geometry_msgs::PoseStamped::ConstPtr& msg){
current_position = *msg;
}
geometry_msgs::PoseStamped des_Pos_msg;
void des_pos_cb(const geometry_msgs::PoseStamped::ConstPtr& msg){
des_Pos_msg = *msg;
}
geometry_msgs::TwistStamped current_velocity;
void curr_vel_cb(const geometry_msgs::TwistStamped::ConstPtr& msg){
current_velocity = *msg;
}
double quaternion_to_euler_angle(const geometry_msgs::PoseStamped msg){
double x = msg.pose.orientation.x;
double y = msg.pose.orientation.y;
double z = msg.pose.orientation.z;
double w = msg.pose.orientation.w;
// ROS_INFO("x: %f", x)z
// ROS_INFO("y: %f", y);
// ROS_INFO("z: %f", z);
// ROS_INFO("w: %f", w);
// // roll (x-axis rotation)
// double sinr_cosp = 2 * (w * x + y * z);
// double cosr_cosp = 1 - 2 * (x * x + y * y);
// angles.roll = std::atan2(sinr_cosp, cosr_cosp);
// // pitch (y-axis rotation)
// double sinp = 2 * (w * y - z * x);
// if (std::abs(sinp) >= 1)
// angles.pitch = std::copysign(M_PI / 2, sinp); // use 90 degrees if out of range
// else
// angles.pitch = std::asin(sinp);
// yaw (z-axis rotation)
double siny_cosp = 2 * (w * z + x * y);
double cosy_cosp = 1 - 2 * (y * y + z * z);
double yaw = std::atan2(siny_cosp, cosy_cosp);
// ROS_INFO("yaw: %f", yaw*180/3.14);
return yaw;
}
double Pos_PID_Controller(double Global_Pos, double Des_Pos, double Max_vel){
// 입력으로 Global Position 받음.
// PID Controller
double input = 0.5*(Des_Pos-Global_Pos) + 0.1*(Des_Pos-Global_Pos)*0.1 + 0.01*(Des_Pos-Global_Pos)/0.1;
// Saturation
if (input >= Max_vel){input = Max_vel;}
else if (input <= -Max_vel){input = -Max_vel;}
return input; //입력속도 출력함.
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "single_iris_hold_pos_Node");
ros::NodeHandle nh;
ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>
("mavros/state", 10, state_cb);
ros::Subscriber curr_pos_sub = nh.subscribe<geometry_msgs::PoseStamped>
("mavros/local_position/pose", 10, curr_pos_cb);
// ros::Subscriber curr_glob_pos_sub = nh.subscribe<geometry_msgs::PoseWithCovarianceStamped>
// ("mavros/global_position/local", 10, curr_glob_pos_cb);
ros::Subscriber curr_vel_sub = nh.subscribe<geometry_msgs::TwistStamped>
("mavros/local_position/velocity_body", 10, curr_vel_cb);
ros::Subscriber jw_topic_sub = nh.subscribe<geometry_msgs::PoseStamped>
("mavros/jw_topic", 10, des_pos_cb);
ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>
("mavros/setpoint_position/local", 10);
ros::Publisher body_rate_pub = nh.advertise<geometry_msgs::TwistStamped>
("mavros/setpoint_velocity/cmd_vel", 10);
ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
("mavros/cmd/arming");
ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
("mavros/set_mode");
//the setpoint publishing rate MUST be faster than 2Hz
ros::Rate rate(20.0);
// wait for FCU connection
while(ros::ok() && !current_state.connected){
ros::spinOnce();
rate.sleep();
}
// 필요한 변수 설정
geometry_msgs::PoseStamped pose; // Publisher msg
geometry_msgs::TwistStamped bodyrate;
bodyrate.twist.linear.x = 0.0;
double Gazebo_Init_pos[2] = {10, 0};
double Target_pos[2] = {-5,5};
double UAV_states[3] = {current_position.pose.position.x, current_position.pose.position.y, 0};
double max_vel = 3;
double psi = 0;
double Raidus = 5;
double Vel_uav = 1;
double Des_Alt = 5;
double Des_Pos[2] = {10,0};
double Position_Controll_Running = false;
//send a few setpoints before starting
for(int i = 100; ros::ok() && i > 0; --i){
local_pos_pub.publish(pose);
body_rate_pub.publish(bodyrate);
ros::spinOnce();
rate.sleep();
}
mavros_msgs::SetMode offb_set_mode;
offb_set_mode.request.custom_mode = "OFFBOARD";
mavros_msgs::CommandBool arm_cmd;
arm_cmd.request.value = true;
ros::Time last_request = ros::Time::now();
// 반복문 시작
while(ros::ok()){
if( current_state.mode != "OFFBOARD" &&
(ros::Time::now() - last_request > ros::Duration(1.0))){
if( set_mode_client.call(offb_set_mode) &&
offb_set_mode.response.mode_sent){
ROS_INFO("Offboard enabled");
}
last_request = ros::Time::now();
} else {
if( !current_state.armed &&
(ros::Time::now() - last_request > ros::Duration(1.0))){
if( arming_client.call(arm_cmd) &&
arm_cmd.response.success){
ROS_INFO("Vehicle armed");
}
last_request = ros::Time::now();
}
}
// 필요한 변수 입력
psi = quaternion_to_euler_angle(current_position);
UAV_states[0] = current_position.pose.position.x + Gazebo_Init_pos[0];
UAV_states[1] = current_position.pose.position.y + Gazebo_Init_pos[1];
UAV_states[2] = psi;
Des_Pos[0] = des_Pos_msg.pose.position.x;
Des_Pos[1] = des_Pos_msg.pose.position.y;
// Position 제어기
if (current_position.pose.position.z >= Des_Alt-0.5) //고도가 원하는 고도보다 50cm 이상일 때, 위치제어기 실행
{Position_Controll_Running = true;}
if (Position_Controll_Running == true){
// bodyrate.twist.linear.x = Pos_PID_Controller(UAV_states[0], Des_Pos[0],max_vel);
// bodyrate.twist.linear.y = Pos_PID_Controller(UAV_states[1], Des_Pos[1],max_vel);}
bodyrate.twist.angular.z = Pos_PID_Controller(psi , 0.78, max_vel);
}
else {
bodyrate.twist.linear.x = 0;
bodyrate.twist.linear.y = 0;
}
bodyrate.twist.linear.z = Pos_PID_Controller(current_position.pose.position.z , Des_Alt, max_vel);
// 메시지 퍼블리쉬.
body_rate_pub.publish(bodyrate);
// LOGGER
double rt = sqrt((Target_pos[0]-UAV_states[0])*(Target_pos[0]-UAV_states[0])+(Target_pos[1]-UAV_states[1])*(Target_pos[1]-UAV_states[1]));
ROS_INFO("================================");
// ROS_INFO("TEST_MSG: %f", des_Pos_msg.pose.position.x);
ROS_INFO("Radius: %f", rt);
ROS_INFO("UAV_x: %f", UAV_states[0] );
ROS_INFO("UAV_y: %f", UAV_states[1]);
ROS_INFO("Target_x: %f", Des_Pos[0]);
ROS_INFO("Target_y: %f", Des_Pos[1]);
ROS_INFO("psi: %f", psi);
ROS_INFO("================================");
ros::spinOnce();
rate.sleep();
}
return 0;
} | true |
b3e7ac52f8ea6e0e7047d45153b1780c8ace1b4b | C++ | deep-dream/virtual_gw | /src/ctrl_break_handler.h | UTF-8 | 987 | 3.0625 | 3 | [] | no_license | #pragma once
#include <windows.h>
#include <iostream>
class Ctrl_break_handler{
static BOOL CtrlHandler( DWORD fdwCtrlType )
{
switch( fdwCtrlType )
{
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
printf("Break event\n");
ctrl_break_pressed = true;
return TRUE;
}
printf("Unknown event!!!\n");
return FALSE;
}
public:
static int ctrl_break_pressed;
Ctrl_break_handler(){
ctrl_break_pressed = false;
if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) Ctrl_break_handler::CtrlHandler, TRUE ) ) {
std::cout << "ERROR: Could not set control handler\n";
throw std::exception();
}
std::cout << "Control Handler (Ctrl-Break interception) is installed.\n";
}
~Ctrl_break_handler(){
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) Ctrl_break_handler::CtrlHandler, FALSE );
}
};
int Ctrl_break_handler::ctrl_break_pressed=0; | true |
ed8cf7084badf103f584742c9365ad224737a6b3 | C++ | vcheesbrough/phishpi.actionhero | /phishpi.arduino/src/MessageDispatcher.h | UTF-8 | 990 | 2.71875 | 3 | [] | no_license | #ifndef _MessageDispatcher_
#define _MessageDispatcher_
#include "InboundMessageHandler.h"
#include <initializer_list>
#include <vector>
#include <map>
namespace phishpi
{
class MessageDispatcher {
public:
MessageDispatcher(std::initializer_list<phishpi::InboundMessageHandler*> handlers) : handlers(handlers)
{
}
void dispatchRawMessage(char * message) {
size_t messageLength = strlen(message);
if(messageLength >= 2) {
if(message[1] == ':') {
char messageType = message[0];
for(phishpi::InboundMessageHandler* handler : handlers) {
if(handler->messageTypeIdentifier() == messageType) {
handler->handleMessage(message+2);
}
}
}
}
}
private:
std::vector<phishpi::InboundMessageHandler*> handlers;
};
}
#endif | true |
19aecaa824763ca5c556b07d11a79fb233a957d2 | C++ | kurdybacha/concurrency | /src/task_system_queue_per_thread_with_stealing.h | UTF-8 | 1,431 | 3.109375 | 3 | [] | no_license | #pragma once
#include <atomic>
#include <task_queue.h>
#include <thread>
#include <vector>
namespace queue_per_thread_with_stealing {
class task_system {
public:
task_system() {
for (unsigned int i = 0; i != _threads_count; ++i)
_threads.emplace_back([&, i] { run(i); });
}
~task_system() {
for (auto &queue : _queues)
queue.stop();
for (auto &thread : _threads)
thread.join();
}
template <typename T>
void async(T &&task) {
auto i = _idx++;
for (unsigned int t = 0; t != _threads_count; ++t) {
if (_queues[(i + t) % _threads_count].try_push(std::forward<T>(task)))
return;
}
_queues[i % _threads_count].push(std::forward<T>(task));
}
private:
void run(unsigned int i) {
while (true) {
task_queue::task task;
for (unsigned int t = 0; t != _threads_count * 16; ++t) {
if (_queues[(i + t) % _threads_count].try_pop(task))
break;
}
if (!task && !_queues[i].pop(task))
break;
task();
}
}
const unsigned int _threads_count{std::thread::hardware_concurrency()};
std::vector<std::thread> _threads;
std::vector<task_queue> _queues{_threads_count};
std::atomic<unsigned int> _idx{0};
};
} // namespace queue_per_thread_with_stealing
| true |
5be9277f643ed7885ea67a6cca92f6fc964bbefd | C++ | EDCBlockchain/blockchain | /libraries/wallet/api_documentation_standin.cpp | UTF-8 | 2,284 | 2.546875 | 3 | [
"MIT"
] | permissive | // see LICENSE.txt
#include <iomanip>
#include <boost/algorithm/string/join.hpp>
#include <graphene/wallet/wallet.hpp>
#include <graphene/wallet/api_documentation.hpp>
namespace graphene { namespace wallet {
namespace detail {
namespace
{
template <typename... Args>
struct types_to_string_list_helper;
template <typename First, typename... Args>
struct types_to_string_list_helper<First, Args...>
{
std::list<std::string> operator()() const
{
std::list<std::string> argsList = types_to_string_list_helper<Args...>()();
argsList.push_front(fc::get_typename<typename std::decay<First>::type>::name());
return argsList;
}
};
template <>
struct types_to_string_list_helper<>
{
std::list<std::string> operator()() const
{
return std::list<std::string>();
}
};
template <typename... Args>
std::list<std::string> types_to_string_list()
{
return types_to_string_list_helper<Args...>()();
}
} // end anonymous namespace
struct help_visitor
{
std::vector<method_description> method_descriptions;
template<typename R, typename... Args>
void operator()( const char* name, std::function<R(Args...)>& memb )
{
method_description this_method;
this_method.method_name = name;
std::ostringstream ss;
ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "(";
ss << boost::algorithm::join(types_to_string_list<Args...>(), ", ");
ss << ")\n";
this_method.brief_description = ss.str();
method_descriptions.push_back(this_method);
}
};
} // end namespace detail
api_documentation::api_documentation()
{
fc::api<wallet_api> tmp;
detail::help_visitor visitor;
tmp->visit(visitor);
std::copy(visitor.method_descriptions.begin(), visitor.method_descriptions.end(),
std::inserter(method_descriptions, method_descriptions.end()));
}
} } // end namespace graphene::wallet
| true |
388784f89e9238f7ff9cf5316174c725cdd8aef1 | C++ | abhishek2208/Code | /Alternating Split of LinkedLIst.cpp | UTF-8 | 1,672 | 3.28125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* next;
};
struct node* append(struct node* head,int val)
{
struct node* new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=val;
struct node* temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=new_node;
new_node->next=NULL;
return head;
}
void printList(struct node *node)
{
while (node != NULL)
{
cout<<node->data<<" ";
node = node->next;
}
cout<<endl;
}
void split(struct node* head ,struct node** a,struct node** b)
{
struct node* curr=head;
struct node* curr1;
struct node* curr2;
if(head==NULL)
{
*a=NULL;
*b=NULL;
return;
}
*a=head;
*b=head->next;
curr2=*b;
curr1=*a;
curr=curr->next->next;
while(curr)
{
curr1->next=curr;
if(curr->next!=NULL)
curr2->next=curr->next;
else
{
curr2->next=NULL;
curr1->next->next=NULL;
return;
}
curr=curr->next->next;
curr1=curr1->next;
curr2=curr2->next;
}
curr1->next=NULL;
curr2->next=NULL;
};
int main()
{
struct node* head= (struct node*)malloc(sizeof(struct node));
head->data=4;
head->next=NULL;
head=append(head,5);
head=append(head,6);
head=append(head,7);
head=append(head,8);
printList(head);
struct node* a=NULL;
struct node* b=NULL;
split(head,&a,&b);
printList(a);
printList(b);
}
| true |
48dd243b728e67237159ea0376b486ed6d303732 | C++ | VladyslavLopata/SFML_Engine | /collisions.cpp | UTF-8 | 1,340 | 3.09375 | 3 | [] | no_license | #include "collisions.h"
void Collisions::resetCollisions(int *levelMap,int &lWidth, int &lHeight, int &tWidth, int &tHeight)
{
//reset the map with provided values
collisionMap.clear();
collisionMap.resize(lWidth * lHeight);
for(int i = 0; i < lWidth * lHeight; i++)
{
collisionMap[i] = levelMap[i];
}
this->lHeight = lHeight;
this->lWidth = lWidth;
this->tWidth = tWidth;
this->tHeight = tHeight;
}
bool Collisions::isWall(const sf::FloatRect &moveDir)
{
//change collider dimensions
sf::FloatRect plBot(moveDir.left + moveDir.width/3.0, moveDir.top, moveDir.width/3.0, moveDir.height);
//if collider goes off the map return collision
if(plBot.top/tHeight <= 0 || (plBot.top + plBot.height)/tHeight > lHeight
|| plBot.left/tWidth <= 0 || (plBot.left + plBot.width)/tWidth > lWidth)
{
return true;
}
//calculate rect vertices
int top = plBot.top/tHeight;
int left = plBot.left/tWidth;
int right = (plBot.left + plBot.width)/tWidth;
int bot = (plBot.top + plBot.height)/tHeight;
//return the collision if at least one of the vertices is colliding
return collisionMap[left + top * lWidth] || collisionMap[left + bot*lWidth]
||collisionMap[right + top * lWidth] || collisionMap[right + bot*lWidth];
}
| true |
3b10e858d7296067cabc61194843c89085c67ea0 | C++ | zzo30802/ffmpeg-windows | /webcam_audio_to_rtmp/src/DataManager.cpp | UTF-8 | 1,332 | 2.859375 | 3 | [] | no_license | #include "DataManager.h"
#include <iostream>
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/time.h>
}
// bool ErrorMesssage(const int &error_num) {
// char buf[1024]{0};
// // put error code to buf
// av_strerror(error_num, buf, sizeof(buf));
// std::cout << buf << std::endl;
// return false;
// }
//*********Data*********
Data::Data(char *src_data, int size, long long pts) {
this->data = new char[size]; // new an array of char
memcpy(this->data, src_data, size);
this->size = size;
this->pts = pts;
}
void Data::Release() {
if (this->data)
delete this->data;
data = 0;
size = 0;
}
//*********DataManager*********
void DataManager::Push(Data src_data) {
std::lock_guard<std::mutex> lock(mutex);
if (data_queue.size() > max_queue_size) {
data_queue.front().Release();
data_queue.pop_front();
}
data_queue.emplace_back(src_data);
}
Data DataManager::Pop() {
std::lock_guard<std::mutex> lock(mutex);
if (data_queue.empty())
return Data();
Data data = data_queue.front();
data_queue.pop_front();
return data;
}
// include QThread::start()
void DataManager::Start() {
is_exit = false;
QThread::start();
}
void DataManager::Stop() {
is_exit = true;
// Waiting for the thread to finish and then process the following code
QThread::wait();
} | true |
f4e9d9e35d356f8aba722ac7f2c9bcafd6f50b28 | C++ | VSFe/Algorithm | /CPP/etc/Gold I/17398.cpp | UTF-8 | 2,356 | 2.953125 | 3 | [] | no_license | /*
Problem: 통신망 분할 (17398)
Tier: Gold 1
Detail: BOJ의 인기스타, 방송인 권욱제는 통신 회사에 취업했다. 현재 이 통신 회사는 너무나 큰 통신망을 한 지사에서 관리하느라 큰 비용을 지불하고 있었다.
그래서 회사는 최근 IT의 트렌드 중 하나인 '탈중앙화'에 편승하여, 통신망을 분할하도록 결정했다. 그래서 욱제한테 통신망을 분할 할때 발생하는 비용을 분석하도록 지시했다.
현재 회사 망에는 1번부터 N번까지 총 N개의 통신 탑이 존재하며, 통신탑 간의 연결이 M개 존재한다.
이때 회사에서는 총 Q번 통신탑 간의 연결을 제거함으로써 하나의 통신망을 여러 개의 통신망으로 분리하려고 한다. 통신망이란, 통신탑의 연결을 통해 도달 가능한 통신탑들의 집합이다.
통신탑 간의 연결 관계를 제거할 때 드는 비용은 제거한 후 통신망이 두 개로 나누어진다면 나눠진 두 개의 통신망에 속한 통신탑들의 갯수의 곱이 되며, 나누어지지 않을 경우 0이다.
Comment: 다 끊어버리고 합치면 될 것 같은데...
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct connection {
int u, v;
bool enable;
connection() {}
connection(int a, int b, bool is) : u(a), v(b), enable(is) {}
};
connection cn[11];
int N, M, Q, uf[11], query[11];
long long ans = 0;
int find(int i) {
return (uf[i] < 0) ? i : (uf[i] = find(uf[i]));
}
void un(int i, int j) {
int pi = find(i);
int pj = find(j);
if(pi == pj) return;
uf[pi] += uf[pj];
uf[pj] = pi;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M >> Q;
for(int i = 1; i <= N; i++) uf[i] = -1;
for(int i = 1; i <= M; i++) {
int x, y;
cin >> x >> y;
cn[i] = {x, y, 1};
}
for(int i = 0; i < Q; i++) {
int tmp; cin >> tmp;
cn[tmp].enable = 0;
query[i] = tmp;
}
for(int i = 1; i <= M; i++) {
if(cn[i].enable) un(cn[i].u, cn[i].v);
}
for(int i = Q - 1; i >= 0; i--) {
int x = find(cn[query[i]].u), y = find(cn[query[i]].v);
if(x == y) continue;
ans += uf[x] * uf[y];
un(x, y);
}
cout << ans;
}
| true |
ef01efa8553929386e8627e6da3fe17b02066fb6 | C++ | iXerol/Longest-Increasing-Sequence | /C++ Version/LIS/main.cpp | UTF-8 | 399 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// main.cpp
// LIS
//
// Created by Xerol Wong on 4/28/18.
// Copyright © 2018 Xerol Wong. All rights reserved.
//
#include <iostream>
#include "QuadrupleList.h"
using namespace std;
int main(int argc, const char * argv[]) {
int t[10] = {3, 9, 6, 2, 8, 5, 7, 10};
QuadrupleList q(t, 7);
q.printLongestIncreasingSequence();
q.update(t, 7);
cout << endl;
q.printLongestIncreasingSequence();
}
| true |
1b174ad41e08237f2a451baaa2c7c07644342e01 | C++ | hy38/OOP_Project | /ConsultingRequest.cpp | UTF-8 | 1,142 | 2.984375 | 3 | [] | no_license | #include "ConsultingRequest.h"
#include <iostream>
#include <string>
using namespace std;
ConsultingRequest::ConsultingRequest(vector<Professor> _Members)
{
professorList = _Members;
}
int ConsultingRequest::ifRequest()
{
string _IdNumber;
cout << "상담하고싶은 교수님의 ID를 입력해주세요: ";
cin >> _IdNumber;
int index = professorList[0].searchIndexOfVector(professorList, _IdNumber); // search professor
if (!professorList[index].getSchedule())
{
professorList[index].setSchedule(!professorList[index].getSchedule());
cout << "상담 신청이 완료되었습니다." << endl;
printProfessorInfo(professorList[index]);
}
else
{
cout << "교수님이 바빠 상담 신청이 불가능합니다." << endl;
}
}
vector<Professor> ConsultingRequest::getProfessorList() { return professorList; }
void ConsultingRequest::printProfessorInfo(Professor _consultedProfessor)
{
cout << "교수님 ID: " << _consultedProfessor.getIdNumber() << endl;
if (_consultedProfessor.getSchedule())
cout << "상담신청이 예약됨." << endl;
}
| true |
4af422ebd2c32255ea4a4e23577909efe5aaf6aa | C++ | gakeane/C_Projects | /Sockets/network_utils.cpp | UTF-8 | 6,136 | 3.265625 | 3 | [] | no_license |
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
/*
DECLARATIONS
*/
int open_client_connection(const char* hostname, const char* port);
int open_server_connection(const char* port);
void close_client_connection(int sockfd);
void close_server_connection(int sockfd);
int send_message(int sockfd, char* msg_buffer);
int receive_message(int sockfd, char* msg_buffer, int buffer_size);
void error(const char* msg);
char* get_ip_address(struct sockaddr_in* addr);
/*
DEFINITIONS
*/
int open_client_connection(const char* hostname, const char* port) {
/* FUNCTION use to create a TCP socket connection from a client to a server
hostname: hostname or IP address of the server to connect to
port: The number of the port to connect to on the server
return: File descriptor identifier for the socket
*/
struct addrinfo* addrs; // linked list of internet addresses (list of addrinfo structures)
struct addrinfo hints = {0}; // an addrinfo structure which provides hints as to what the connection type should be like
hints.ai_family = AF_INET; // expected address family
hints.ai_socktype = SOCK_STREAM; // expected socket type
hints.ai_protocol = IPPROTO_TCP; // expected transport protocol
// get server address info from DNS
int status = getaddrinfo(hostname, port, &hints, &addrs);
if (status != 0) {
fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status)); // gai_stderror returns a error string givne the integer returned from getaddrinfo() or getnameinfo()
exit(1);
}
// create socket file
int sockfd = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
if (sockfd < 0) {
const char msg[] = "ERROR: Can't open socket";
error(msg);
}
// connect socket file to server
int connect_status = connect(sockfd, addrs->ai_addr, addrs->ai_addrlen);
if (connect_status < 0) {
const char msg[] = "ERROR: Connection failed";
error(msg);
}
freeaddrinfo(addrs); // free the memory dynamically allocated for the linked list of addrinfo structures
return sockfd; // return the reference to the socket file descriptor which has been connected
}
int open_server_connection(const char* port, int max_connections) {
/* Sets up a socket for a server and starts it listening on the specified port
Once the server is listening we can use accepts which will create a new socket to handle I/O with the client
The original socket will continue to listen for connections
port: The port the server will listen on
max_connections: The number of connections that the server will accept (Queue) at any one time
return: File descriptor identifier for the socket
*/
struct sockaddr_in serv_addr = {0}; // Structure contains an internet address for the server
serv_addr.sin_family = AF_INET; // Set to AF_INET for internet addressing
serv_addr.sin_port = htons(atoi(port)); // htons converts the port number from host byte order (little endian) to network byte order (big endian)
serv_addr.sin_addr.s_addr = INADDR_ANY; // INADDR_ANY sets the address to the address the server is running on (i.e. localhost)
// create a socket for the server
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
char msg[] = {"ERROR: Can't open socket"};
error(msg);
}
// bind the socket to the specified port
int bind_check = bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
if (bind_check < 0) {
char msg[] = {"ERROR: Can't bind socket"};
error(msg);
}
// set the socket to listen for incomming connections
// if there are more than max_connections that have not been accepted, the rest will be dropped
listen(sockfd, max_connections);
return sockfd;
}
// FIXME: I think both functions should send a shutdown signal, wait to read 0 of the buffer, then close the socket
void close_client_connection(int sockfd) {
/* FUNCTION cleanly terminates a session on the client side and then closes the socket
sockfd: File descriptor identifier for the socket to be closed
*/
close(sockfd);
}
void close_server_connection(int sockfd) {
/* FUNCTION cleanly terminates a session on the server side and then closes the socket
sockfd: File descriptor identifier for the socket to be closed
*/
close(sockfd);
}
int send_message(int sockfd, char* msg_buffer) {
/* Writes a message to a socket and checks no errors occured
sockfd: File descriptor identifier for the socket to sned message to
msg_buffer: The message to be sent
return: Number of bytes sent
*/
int n = send(sockfd, msg_buffer, strlen(msg_buffer), 0);
if (n < 0) {
char msg[] = {"ERROR: Failed writing to socket"};
error(msg);
}
return n;
}
int receive_message(int sockfd, char* msg_buffer, int buffer_size) {
/* Reads a message from a socket and checks no errors occured
sockfd: File descriptor identifier for the socket to read message from
msg_buffer: Array buffer will be stored in
return: Number of bytes read
*/
bzero(msg_buffer, buffer_size);
int n = recv(sockfd, msg_buffer, buffer_size, 0);
if (n < 0) {
char msg[] = {"ERROR: Failed reading from socket"};
error(msg);
}
return n;
}
char* get_ip_address(struct sockaddr_in* addr) {
/* Gets the IP address from a sockaddr_in stracture
addr: Address structure containin information about an internet device
return: IP address of the server (7 bytes, 4 bytes of sin_addr separated by dots)
*/
return inet_ntoa(addr->sin_addr);
}
void error(const char* msg) {
/* Prints an error message fallowed by the error message thrown by the last system call to fail
The program then terminates
msg: Message to be printed before the system call error
*/
perror(msg); // from stdio
exit(1); // from stdio
}
| true |
2678c961a863bc43957d297694526b0c4e881652 | C++ | rathyon/CGJ | /projects/lab0/qtrn.cpp | UTF-8 | 3,744 | 3.015625 | 3 | [] | no_license | #include "qtrn.h"
qtrn::qtrn()
{
}
qtrn::qtrn(float theta, vec3& axis)
{
float axis_length = axis.norm();
vec3 norm_axis = vec3(axis.x / axis_length, axis.y / axis_length, axis.z / axis_length);
float a = theta * (float)DEGREES_TO_RADIANS;
t = cos(a / 2.0f);
float s = sin(a / 2.0f);
x = norm_axis.x * s;
y = norm_axis.y * s;
z = norm_axis.z * s;
//this->clean();
//normalize(*this);
//normalize
s = 1.0f / (sqrt(t*t + x*x + y*y + z*z));
t *= s;
x *= s;
y *= s;
z *= s;
}
qtrn::qtrn(float t1, float x1, float y1, float z1) {
t = t1;
x = x1;
y = y1;
z = z1;
}
qtrn::~qtrn()
{
}
void normalize(qtrn& q) {
float s = 1.0f / q.norm();
q.t *= s;
q.x *= s;
q.y *= s;
q.z *= s;
}
void qtrn::clean() {
if (fabs(t) < QTHRESHOLD) t = 0.0f;
if (fabs(x) < QTHRESHOLD) x = 0.0f;
if (fabs(y) < QTHRESHOLD) y = 0.0f;
if (fabs(z) < QTHRESHOLD) z = 0.0f;
}
float qtrn::quadrance() {
return t*t + x*x + y*y + z*z;
}
float qtrn::norm() {
return sqrt(t*t + x*x + y*y + z*z);
}
qtrn qtrn::operator *(float f) {
qtrn sq;
sq.t = f * t;
sq.x = f * x;
sq.y = f * y;
sq.z = f * z;
return sq;
}
qtrn qtrn::operator *(qtrn& q) {
qtrn res;
res.t = t * q.t - x * q.x - y * q.y - z * q.z;
res.x = t * q.x + x * q.t + y * q.z - z * q.y;
res.y = t * q.y + y * q.t + z * q.x - x * q.z;
res.z = t * q.z + z * q.t + x * q.y - y * q.x;
return res;
}
qtrn qtrn::operator +(qtrn& q) {
qtrn res;
res.t = t + q.t;
res.x = x + q.x;
res.y = y + q.y;
res.z = z + q.z;
return res;
}
bool qtrn::operator ==(qtrn& q) {
return (fabs(t - q.t) < QTHRESHOLD && fabs(x - q.x) < QTHRESHOLD &&
fabs(y - q.y) < QTHRESHOLD && fabs(z - q.z) < QTHRESHOLD);
}
void toAngleAxis(qtrn& q, float& angle, vec3& axis) {
normalize(q);
angle = 2.0f * acos(q.t) * (float)RADIANS_TO_DEGREES;
float s = sqrt(1.0f - q.t*q.t);
if (s < QTHRESHOLD) {
axis.x = 1.0f;
axis.y = 0.0f;
axis.z = 0.0f;
}
else {
axis.x = q.x / s;
axis.y = q.y / s;
axis.z = q.z / s;
}
}
qtrn conjugate(qtrn& q) {
qtrn res = qtrn(q.t, -q.x, -q.y, -q.z);
return res;
}
qtrn inverse(qtrn& q) {
return conjugate(q) * (1.0f / q.quadrance());
}
mat4 toMat4(qtrn& q) {
normalize(q);
mat4 res;
float xx = q.x * q.x;
float xy = q.x * q.y;
float xz = q.x * q.z;
float xt = q.x * q.t;
float yy = q.y * q.y;
float yz = q.y * q.z;
float yt = q.y * q.t;
float zz = q.z * q.z;
float zt = q.z * q.t;
res[0][0] = 1.0f - 2.0f * (yy + zz);
res[0][1] = 2.0f * (xy + zt);
res[0][2] = 2.0f * (xz - yt);
res[0][3] = 0.0f;
res[1][0] = 2.0f * (xy - zt);
res[1][1] = 1.0f - 2.0f * (xx + zz);
res[1][2] = 2.0f * (yz + xt);
res[1][3] = 0.0f;
res[2][0] = 2.0f * (xz + yt);
res[2][1] = 2.0f * (yz - xt);
res[2][2] = 1.0f - 2.0f * (xx + yy);
res[2][3] = 0.0f;
res[3][0] = 0.0f;
res[3][1] = 0.0f;
res[3][2] = 0.0f;
res[3][3] = 1.0f;
transpose(res); // to compensate for teacher's implementation xD
return res;
}
qtrn LERP(qtrn q1, qtrn q2, float f) {
float cos_angle = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.t*q2.t;
float k0 = 1.0f - f;
float k1 = (cos_angle > 0) ? f : -f;
qtrn qi = (q1*k0) + (q2*k1);
normalize(qi);
return qi;
}
qtrn SLERP(qtrn q1, qtrn q2, float f) {
float angle = acos(q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.t*q2.t);
float k0 = sin((1 - f)*angle) / sin(angle);
float k1 = sin(f*angle) / sin(angle);
qtrn qi = (q1*k0) + (q2*k1);
normalize(qi);
return qi;
}
std::ostream& operator <<(std::ostream &output, qtrn& q) {
output << "qtrn: (" << q.t << ", " << q.x << ", " << q.y << ", " << q.z << ")" << std::endl;
float thetaf;
vec3 axis_f;
toAngleAxis(q, thetaf, axis_f);
output << "Angle = " << thetaf << std::endl;
output << "Axis = " << axis_f << std::endl;
return output;
}
| true |
63cd5eb85f37fa34fa2ada454d92e23478b0d523 | C++ | ChicoState/eggbeater | /cli/tests/SerialComm_test_port.cpp | UTF-8 | 3,025 | 2.703125 | 3 | [] | no_license | #include "gtest/gtest.h"
#include <memory>
#include <eggbeater/Serial.h>
#include <eggbeater/Discovery.h>
#include <iostream>
using namespace EggBeater;
class NoOpFixture : public ::testing::Test
{
public:
NoOpFixture()
{
// No-op
}
virtual ~NoOpFixture()
{
// No-op
}
virtual void SetUp()
{
// No-op
}
virtual void TearDown()
{
// No-op
}
};
TEST_F(NoOpFixture, SerialCommPort_test_echo)
{
uint16_t vid = 0x0483;
uint16_t pid = 0x5740;
SerialCommunication serial;
ByteArray data({0xff, 0x8f, 0x6f, 0x11});
ASSERT_NO_THROW(
Packet sendPacket(CommandType::Echo, data);
Packet recvPacket;
StringList ports;
try
{
StringList ports2(discover_devices(vid, pid));
for (auto port : ports2)
ports.push_back(port);
// ports = discover_devices(vid, pid);
}
catch (Exception e)
{
std::cout << e.msg() << std::endl;
throw e;
}
std::cout << "num ports: " << ports.size() << std::endl;
for (auto port : ports)
{
std::cout << "serial.open(" << port << ")" << std::endl;
std::flush(std::cout);
ASSERT_TRUE(serial.open(port));
std::cout << "send packet" << std::endl;
ASSERT_TRUE(serial.sendPacket(sendPacket));
std::cout << "receive packet" << std::endl;
ASSERT_TRUE(serial.receivePacket(recvPacket));
std::cout << "check command" << std::endl;
ASSERT_EQ(sendPacket.getCommandType(), recvPacket.getCommandType());
std::cout << "check data length" << std::endl;
ASSERT_EQ(sendPacket.getDataLength(), recvPacket.getDataLength());
std::cout << "check packet data" << std::endl;
//const uint8_t* sendData = sendPacket.getPacketData();
//const uint8_t* recvData = recvPacket.getPacketData();
Packet::ValueType sendData = sendPacket.getRawPacket();
Packet::ValueType recvData = recvPacket.getRawPacket();
std::cout << "get pointers from shared_ptr" << std::endl;
ByteArray* sendArray = sendData.get();
ByteArray* recvArray = sendData.get();
std::cout << "check for NULL pointers" << std::endl;
ASSERT_NE(sendArray, nullptr);
ASSERT_NE(recvArray, nullptr);
std::cout << "get packet length" << std::endl;
uint32_t len = sendData->size();
std::cout << "send packet length: " << len << std::endl;
std::cout << "recv packet length: " << recvData->size() << std::endl;
for (uint32_t i = 0; i < len; i++)
{
printf("%0.2x %0.2x\n", (int)((*sendData)[i]), (int)((*recvData)[i]));
EXPECT_EQ((*sendData)[i], (*recvData)[i]);
}
std::cout << "done" << std::endl;
serial.close();
}
);
std::cout << "outside ASSERT_NO_THROW" << std::endl;
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
75500cc19a8cdae23425e7cb021a70a88643060b | C++ | jimbui/Project-4_Graphs | /main.cpp | UTF-8 | 2,789 | 3.3125 | 3 | [] | no_license | #include "HashTable.h"
#include "Graph.h"
#include "DirGraph.h"
#include "Menu_Program.h"
int main()
{
cout << "4 tcejorP maeT" << endl << endl; // Insert new edge is the only algorithm for insertion required. Hash table can cause collisions.
Menu_Program() ;
// Get name --> vertex
// Method --> Reset sets each vertex object flag to false.
// Vertex contains linked list of edges... (edge->start = vertex)
//Edge e1(10, "Duh", "Barf");
//Edge e2(14, "Barf", "Duh");
//bool duhr = e1 < e2;
//bool areEdgesEqual = e1.isUndirectedEqual(e2);
//Graph<double>* undirectedCalc = new Graph<double>(23);
//undirectedCalc->BuildGraph();
//// After doing any search, be sure to call reset.
//try
//{
// undirectedCalc->BFS("V1");
// undirectedCalc->reset();
// bool duh = undirectedCalc->isConnected();
//}
//catch (const invalid_argument& e)
//{
// cerr << e.what() << endl;
//}
//undirectedCalc->DisplayAdjacencyList();
//DirGraph<double>* calculator = new DirGraph<double>(23);
//calculator->DisplayAdjacencyList();
//try
//{
// cout << "In-Degree of V1: " << calculator->indegree("V1") << endl;
//}
//catch (const invalid_argument& e)
//{
// cerr << e.what() << endl;
//}
//try
//{
// cout << "Edge: V1 <----> V2 = " << calculator->adjacent("V1", "V2") << endl;
//}
//catch (const invalid_argument& e)
//{
// cerr << e.what() << endl;
//}
//// Perform multiple insertions/deletions...
//while (true)
//{
// calculator->DisplayAdjacencyList();
// cout << "Use 'd' to delete and 'i' to insert: ";
// char deleteOrInsert;
// cin >> deleteOrInsert;
// cin.ignore();
// if (deleteOrInsert == 'd')
// {
// string v;
// cout << "Enter vertex to delete: ";
// cin >> v;
// cin.ignore();
// calculator->del(v);
// }
// else if (deleteOrInsert == 'i')
// {
// string u, v;
// double w;
// cout << "Enter Starting Vertex: ";
// cin >> u;
// cin.ignore();
// cout << "Enter Destination Vertex: ";
// cin >> v;
// cin.ignore();
// cout << "Enter Desired Weight: ";
// cin >> w;
// cin.ignore();
// cout << endl;
// try
// {
// calculator->insert(u, v, w);
// }
// catch (const invalid_argument& e)
// {
// cerr << e.what() << endl;
// }
// }
// else
// cout << "Invalid input." << endl;
// cout << endl;
//}
//delete calculator;
//HashTable<string, int>* hashBrown = new HashTable<string, int>(29, 0.5);
//hashBrown->insert("V1", 10);
//hashBrown->insert("V2", 20);
//// int val1 = hashBrown["V1"];
//hashBrown->DisplayElementList();
//hashBrown->clear();
//hashBrown->DisplayElementList();
cin.get();
return 0;
} | true |
90af4ed3e16ee43806388907605b001db8e11e24 | C++ | luxe/unilang | /source/code/scratch/old_repos/code-scraps/project/cpp/move_around_curses.cpp | UTF-8 | 8,946 | 3.640625 | 4 | [
"MIT"
] | permissive | #include <curses.h>
#include <menu.h>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
/* This program was written by David Eck and modified by Scotty Orr
*
* This program demonstrates "curses" mode. It must be run on command line.
* When it is run, the console window is converted into a simple kind of
* GUI made up of rows and columns of characters. In curses mode, the
* cursor can be moved to any character on the screen, and a character or
* string can be put there. The appearance of the characters can be changed
* by setting several "attributes": characters can be bold, they can be
* underlined, and they can be shown in reverse (with the foreground and
* background colors reversed.) The getch() function can be used
* to read characters typed by the user. In this demo program, the cursor
* is moved when the user presses an arrow key or the return key. When
* the user types an ordinary printable character, it is output at the
* current cursor position. The program also checks for several control
* chars in the input. A CONTROL-X will end the program. CONTROL-B will
* toggle the bold attribute. (That is, after you press CONTROL-B,
* characters will be displayed in bold mode until you press CONTROL-B
* again.) Similarly, CONTROL-U toggles underline mode, and CONTROL-R
* toggles reverse mode. CONTROL-N will return to normal characters.
* That is, it will make sure all the attributes are turned off.
*/
#include <ncurses.h>
#include <iostream>
using namespace std;
const char CTRL_B = 2; // Define names for some control characters.
const char CTRL_R = 18;
const char CTRL_U = 21;
const char CTRL_X = 24;
const char CTRL_N = 14;
bool curses_started = false; // This is set to true the first time
// the program enters curses mode.
void endCurses();
void startCurses();
void drawFrame(int, int, int, int);
int main() {
cout << "\nThis program will demonstrate curses. It will enter curses\n"
<< "mode when you press return. You can type characters and use\n"
<< "the arrow keys to move around. Press CONTROL-X to exit.\n"
<< "Use CONTROL-B, CONTROL-R, and CONTROL-U to go into bold,\n"
<< "reverse video, and underlined mode, respectively.\n\n"
<< "Press return to begin.\n";
char response;
cin.get(response);
startCurses(); // Enter curses mode.
drawFrame(0,0,LINES-1,COLS-1); // Draw a frame around the whole window.
// (The rest of the program will only use
// rows 1 to LINES-2 and columns 1 to
// COLS-1. LINES and COLS are predefined
// variables.)
move(LINES/2,COLS/2); // Move cursor to center of window.
int row,col; // The current row and column of the cursor.
bool bold = false; // Is the BOLD attribute currently on?
bool underline = false; // Is the UNDERLINE attribute currently on?
bool reverse = false; // Is the REVERSE attribute currently on?
bool done = false; // Will be set to true when the user presses
// CONTROL-X. This ends the loop and the program
while (!done) { // Get one char from the user and process it.
getyx(stdscr,row,col); // Get the current cursor position.
int ch = getch(); // Get the next character typed by the user.
switch (ch){
case CTRL_B: // Toggle BOLD attribute if user types CONTROL-B
bold = ! bold;
if (bold)
attron(A_BOLD);
else
attroff(A_BOLD);
break;
case CTRL_R: // Toggle REVERSE attribute if user types CONTROL-R
reverse = ! reverse;
if (reverse)
attron(A_REVERSE);
else
attroff(A_REVERSE);
break;
case CTRL_U: // Toggle UNDERLINE attribute if user types CONTROL-U
underline = ! underline;
if (underline)
attron(A_UNDERLINE);
else
attroff(A_UNDERLINE);
break;
case CTRL_N: // Turn off all attributes if user types CONTROL-N
attroff(A_BOLD);
attroff(A_REVERSE);
attroff(A_UNDERLINE);
break;
case CTRL_X: // End the loop if user types CONTROL-X
done = true;
break;
case '\n': // User pressed RETURN.
if (row < LINES-2)
move(row+1,1); // Move to beginning of next line.
else
move (row,1); // On last line. Move to start of the line.
break;
case KEY_UP: // Move cursor up, unless already at top of window.
if (row > 1)
move(row-1,col);
break;
case KEY_DOWN: // Move cursor down, unless already at bottom.
if (row < LINES-2)
move(row+1,col);
break;
case KEY_LEFT: // Move cursor left, unless already at left edge.
if (col > 1)
move(row,col-1);
break;
case KEY_RIGHT: // Move cursor right, unless already at right edge.
if (col < COLS-2)
move(row,col+1);
break;
case KEY_BACKSPACE: // User pressed the backspace key.
if (col > 1) {
// Cursor is not in the first column.
// Overwrite previous char with a space.
move(row,col-1);
addch(' ');
move(row,col-1);
}
else if (row > 1) {
// Cursor was in the first column, but not on the
// first row. Move to end of previous row and
// overwrite the last char on that row.
move(row-1,COLS-2);
addch(' ');
move(row-1,COLS-2);
}
break;
default:
if (ch >= ' ' && ch <= 126) {
// The user typed a printable character.
// Put it at the current cursor position. If that's
// the end of the row, move cursor to the next row
// (or, if already on the last row, to the beginning
// of the row.)
addch(ch);
if (col == COLS-2) {
if (row < LINES-2)
move(row+1,1);
else
move(row,col);
}
}
break;
} // end switch
refresh(); // Make sure any changes made become visible on screen.
} // end while
} // end main()
//---------------------------------------------------------------
// Support for entering and leaving curses mode
//---------------------------------------------------------------
/*
* This will exit curses mode and return the console to the usual
* line-oriented input/output mode. If it is called when curses
* mode is not in effect, it will have no effect.
*
*/
void endCurses() {
if (curses_started && !isendwin())
endwin();
}
/*
* This will put the console into curses mode. If curses mode is being
* entered for the first time, the screen will be cleared. If it is
* being re-entered after a call to endCurses(), then the previous
* screen contents will be restored.
*/
void startCurses() {
if (curses_started) {
refresh();
}
else {
initscr();
cbreak();
noecho();
intrflush(stdscr, false);
keypad(stdscr, true);
atexit(endCurses); // Make sure endCurses() is called when program ends.
curses_started = true;
}
}
//---------------------------------------------------------------
/*
* This routine draws a frame around a specified part of the console
* screen, using special characters such as ACS_ULCORNER and ACS_VLINE.
* The frame extends from startrow to endrow vertically and from
* startcol to endcol horizontally. (Rows and columns are numbered
* starting from 0.) Note that the interior of the frame extends
* from startrow+1 to endrow-1 vertically and from startcol+1 to
* endcol-1 horizontally.
*/
void drawFrame(int startrow, int startcol, int endrow, int endcol) {
int saverow, savecol;
getyx(stdscr,saverow,savecol);
mvaddch(startrow,startcol,ACS_ULCORNER);
for (int i = startcol + 1; i < endcol; i++)
addch(ACS_HLINE);
addch(ACS_URCORNER);
for (int i = startrow +1; i < endrow; i++) {
mvaddch(i,startcol,ACS_VLINE);
mvaddch(i,endcol,ACS_VLINE);
}
mvaddch(endrow,startcol,ACS_LLCORNER);
for (int i = startcol + 1; i < endcol; i++)
addch(ACS_HLINE);
addch(ACS_LRCORNER);
move(saverow,savecol);
refresh();
}
| true |
a7268b881accb2377b49d042a72e93800b769e99 | C++ | Lawrence37/algorithms | /sorting/shell_sort/shell_sort.hpp | UTF-8 | 1,925 | 3.8125 | 4 | [
"MIT"
] | permissive | #include <vector>
#include "../insertion_sort/insertion_sort.hpp"
#include "../../libraries/skip_iterator.hpp"
namespace {
/**
* Computes Sedgewick's gap numbers.
*
* @param limit The maximum gap needed. Must be at least 1.
* @return The gap numbers from smallest to largest.
*/
std::vector<long> sedgewickGaps(long limit) {
std::vector<long> gaps;
long pow_2 = 1;
long pow_4 = 1;
// Sedgewick's numbers alternate between two formulas. Keep calculating them
// until we meet or exceed the limit.
do {
gaps.push_back(9 * (pow_4 - pow_2) + 1);
gaps.push_back(pow_2 * (16 * pow_2 - 12) + 1);
pow_2 *= 2;
pow_4 *= 4;
} while (gaps.back() < limit);
// Backtrack if needed.
while (gaps.back() > limit) {
gaps.pop_back();
}
return gaps;
}
}
/**
* Perform Shell sort on a list.
*
* @param front A random access iterator to the front of the list.
* @param back A random access iterator to the back of the list.
*/
template<class RandAccessIterator>
void shellSort(RandAccessIterator front, RandAccessIterator back) {
if (back - front <= 1) {
return;
}
const auto length = back - front;
const std::vector<long> gaps = sedgewickGaps(length - 1);
SkipIterator<RandAccessIterator> sub_front, sub_back;
for (int gap_index = gaps.size() - 1; gap_index >= 0; gap_index--) {
const auto & gap = gaps[gap_index];
sub_front.setSpacing(gap);
sub_back.setSpacing(gap);
// Perform insertion sort for each possible offset.
for (int offset = 0; offset < gap; offset++) {
const auto first_iter = front + offset;
const auto last_iter =
first_iter + ((length - 1 - offset) / gap + 1) * gap;
sub_front.set(first_iter);
sub_back.set(last_iter);
insertionSort(sub_front, sub_back);
}
}
}
| true |
4e9ea9a5dbd09f574bc8b9761815ce1782831e6f | C++ | lineCode/zaf | /src/zaf/parsing/parsers/internal/utility.h | UTF-8 | 816 | 2.546875 | 3 | [] | no_license | #pragma once
#include <string>
#include <zaf/parsing/parser.h>
#include <zaf/parsing/xaml_node.h>
#include <zaf/reflection/creation.h>
namespace zaf {
namespace internal {
bool ParseAttributeToDoubleFloats(
const std::wstring& attribute,
float& float0,
float& float1);
bool ParseAttributeToQuaterFloats(
const std::wstring& attribute,
float& float0,
float& float1,
float& float2,
float& float3);
template<typename T>
std::shared_ptr<T> CreateObjectFromNode(const std::shared_ptr<XamlNode>& node) {
if (node->GetType() != XamlNode::Type::Element) {
return {};
}
auto object = CreateObjectByName<T>(node->GetValue());
if (!object) {
return {};
}
object->GetType()->GetParser()->ParseFromNode(*node, *object);
return object;
}
}
} | true |