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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8b4be9ee9a84f403019a49d43935c8c93744f290 | C++ | DukeLaze/kattis | /pot/app.cpp | UTF-8 | 325 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
int main(){
int n;
std::cin >> n;
unsigned long sum = 0;
for(int i = 0; i < n; i++){
int mangled;
std::cin >> mangled;
//remove last digit, use last digit
sum += std::pow(mangled/10, mangled%10);
}
std::cout << sum << std::endl;
} | true |
b4ced84b700e6f4668d2ead5fa774a0af0a53d90 | C++ | silent-silence/CodeRefactor | /Errors/TypeError.hpp | UTF-8 | 565 | 2.953125 | 3 | [] | no_license | //
// Created by 17271 on 2019/5/25.
//
#ifndef CODEREFACTOR_TYPEERROR_H
#define CODEREFACTOR_TYPEERROR_H
#include <string>
#include <exception>
/// @brief Throw this while type specifiers are illegal
class TypeError : public std::exception {
public:
explicit TypeError(const char *error)
: m_msg{error}
{}
explicit TypeError(std::string error)
: m_msg{error.data()}
{}
~TypeError() override = default;
const char *what() const noexcept override
{
return m_msg.data();
}
private:
const std::string m_msg;
};
#endif //CODEREFACTOR_TYPEERROR_H
| true |
ef690397c82c4e456ddd771fc800fa44417af98a | C++ | Taxiway/TC_Codes | /QuadraticLaw.cpp | WINDOWS-1252 | 4,447 | 3.28125 | 3 | [] | no_license | // Orz AekdyCoin 侰
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <functional>
#include <cctype>
#include <string>
using namespace std;
#define all(X) (X).begin(), (X).end()
#define sz(a) int((a).size())
typedef long long ll;
class QuadraticLaw
{
public:
long long getTime(long long d);
};
long long QuadraticLaw::getTime(long long d)
{
long long x = sqrt(double(d));
while (x * x <= d) ++x;
long long down = 0, up = x;
while (down + 1 < up) {
long long mid = (down + up) >> 1;
if (mid + mid * mid <= d) {
down = mid;
} else {
up = mid;
}
}
return down;
}
// BEGIN CUT HERE
/*
// PROBLEM STATEMENT
//
"Nmec's quadratic law: how many minutes the teacher was late to the lesson, that many minutes squared he'll end the lesson earlier."
In other words, if the teacher is t minutes late (for some non-negative integer t), he should end the lesson t2 minutes early. Of course, this means the teacher can't be too late, because a lesson can't end before even starting. It is, however, possible for the teacher to arrive and end the lesson immediately (in fact, he then only arrives to tell the students that the lesson's cancelled).
You're given a long long d. The lesson was supposed to take d minutes. Compute and return the largest non-negative integer t such that the teacher can be t minutes late.
DEFINITION
Class:QuadraticLaw
Method:getTime
Parameters:long long
Returns:long long
Method signature:long long getTime(long long d)
CONSTRAINTS
-d will be between 1 and 1,000,000,000,000,000,000, inclusive.
EXAMPLES
0)
1
Returns: 0
The lesson was supposed to take 1 minute. The teacher can only be 0 minutes late, in which case he ends the lesson 0 minutes early (i.e. he arrives and ends the lecture on time).
1)
2
Returns: 1
It's possible for the teacher to be 1 minute late and end the lecture 1 minute early (so there's no lecture at all).
2)
5
Returns: 1
3)
6
Returns: 2
4)
7
Returns: 2
5)
1482
Returns: 38
6)
1000000000000000000
Returns: 999999999
7)
31958809614643170
Returns: 178770270
*/
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
template<typename T>
void print(T a) {
cerr << a;
}
void print(long long a) {
cerr << a << "LL";
}
void print(string a) {
cerr << '"' << a << '"';
}
template<typename T>
void print(vector<T> a) {
cerr << "{";
for (unsigned i = 0; i != a.size(); i++) {
if (i != 0) cerr << ", ";
print(a[i]);
}
cerr << "}" << endl;
}
template<typename T>
void eq(int n, T have, T need) {
if (have == need) {
cerr << "Case " << n << " passed." << endl;
} else {
cerr << "Case " << n << " failed: expected ";
print(need);
cerr << " received ";
print(have);
cerr << "." << endl;
}
}
template<typename T>
void eq(int n, vector<T> have, vector<T> need) {
if(have.size() != need.size()) {
cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
print(have);
print(need);
return;
}
for(unsigned i = 0; i < have.size(); i++) {
if(have[i] != need[i]) {
cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
print(have);
print(need);
return;
}
}
cerr << "Case " << n << " passed." << endl;
}
void eq(int n, string have, string need) {
if (have == need) {
cerr << "Case " << n << " passed." << endl;
} else {
cerr << "Case " << n << " failed: expected ";
print(need);
cerr << " received ";
print(have);
cerr << "." << endl;
}
}
int main() {
{
QuadraticLaw theObject;
eq(0, theObject.getTime(1L),0L);
}
{
QuadraticLaw theObject;
eq(1, theObject.getTime(2L),1L);
}
{
QuadraticLaw theObject;
eq(2, theObject.getTime(5L),1L);
}
{
QuadraticLaw theObject;
eq(3, theObject.getTime(6L),2L);
}
{
QuadraticLaw theObject;
eq(4, theObject.getTime(7L),2L);
}
{
QuadraticLaw theObject;
eq(5, theObject.getTime(1482L),38L);
}
{
QuadraticLaw theObject;
eq(6, theObject.getTime(1000000000000000000L),999999999L);
}
{
QuadraticLaw theObject;
eq(7, theObject.getTime(31958809614643170L),178770270L);
}
}
// END CUT HERE
| true |
901c58056e09473226655f94af4e95ed7a9373d0 | C++ | MasterLeen/cpp- | /C++String类实现/MyString.h | GB18030 | 674 | 2.96875 | 3 | [] | no_license | #ifndef MYSTRING_H
#define MYSTRING_H
#include <string.h>//cԵstring
#include <iostream>
class MyString {
public:
MyString(const char* str = NULL);
MyString(const MyString& rhs);
MyString& operator = (const MyString& rhs);
MyString& operator = (MyString&& str) noexcept;
MyString(MyString&& str)noexcept;//ƶ캯
~MyString();
MyString operator + (const MyString& str);
char& operator [] (size_t index);
const char* c_str();
bool operator == (const MyString& str);
friend std::ostream& operator << (std::ostream& os,const MyString& str);
friend std::istream& operator >> (std::istream& is,MyString& str);
private:
char* m_data;
};
#endif
| true |
7e4476f428b2d4017b865a4382f601b73af1c011 | C++ | Cyberpatinho/OBI | /Soluções/Jogo de Tabuleiro.cpp | UTF-8 | 1,047 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define endl '\n'
int mat[105][105];
int main(){
ios_base::sync_with_stdio(0);
int n; cin >>n;
for(int i = 1; i<=n; i++){
for(int j = 1; j<=n; j++){
cin >>mat[i][j];
}
}
int arr[2];
for(int i = 2; i<=n; i++){
arr[0] = arr[1] = 0;
arr[mat[i-1][i-1]]++; arr[mat[i-1][i]]++; arr[mat[i][i-1]]++;
mat[i][i] = (arr[0] > arr[1]);
for(int j = i+1; j<=n; j++){
arr[0] = arr[1] = 0;
arr[mat[i-1][j-1]]++; arr[mat[i-1][j]]++; arr[mat[i][j-1]]++;
mat[i][j] = (arr[0] > arr[1]);
}
for(int j = i+1; j<=n; j++){
arr[0] = arr[1] = 0;
arr[mat[j-1][i-1]]++; arr[mat[j-1][i]]++; arr[mat[j][i-1]]++;
mat[j][i] = (arr[0] > arr[1]);
}
}
/*
for(int i = 1; i<=n; i++){
for(int j = 1; j<=n; j++){
cout <<mat[i][j] <<" ";
}
cout <<endl;
}*/
cout <<mat[n][n] <<endl;
return 0;
}
| true |
cc58f5993c18cf47b4dc3d16e7ba1598a4da47e7 | C++ | gvma/Computer-Graphics | /cube/cube.h | UTF-8 | 5,128 | 3.25 | 3 | [] | no_license | #include <time.h>
#include <string>
using namespace std;
// 0 - face, 1 - top, 2 - back, 3 - down, 4 - left, 5 - right
const double colorMap[6][3] = {{1, 1, 1}, {0, 0, 1}, {1, 241 / 255.0, 25 / 255.0}, {0, 1, 0}, {253 / 255.0, 126 / 255.0, 0}, {1, 0, 0}};
const int n = 3; const int cycleSize = 2*n + 2*(n - 2);
struct Cube
{
int face[6][n][n];
void initCube() { for (int i = 0; i < 6; i ++) for (int j = 0; j < n; j ++) for (int k = 0; k < n; k ++) face[i][j][k] = i; }
string calculateHash() { string h = ""; for (int i = 0; i < 6; i ++) for (int j = 0; j < n; j ++) for (int k = 0; k < n; k ++) h += face[i][j][k]; return(h); }
bool operator<(const Cube& b) const
{
for (int i = 0; i < 6; i ++)
for (int j = 0; j < n; j ++)
for (int k = 0; k < n; k ++)
if (face[i][j][k] < b.face[i][j][k]) return(true);
else if (face[i][j][k] > b.face[i][j][k]) return(false);
return(false);
}
};
void rotateFace(int face[n][n], bool reverse)
{
for (int k = 0; k < n / 2; k ++)
{
if (reverse)
for (int i = 0; i < n - 1 - 2 * k; i ++)
{
int aux = face[0 + k][i + k];
face[0 + k][i + k] = face[i + k][n - 1 - k];
face[i + k][n - 1 - k] = face[n - 1 - k][n - 1 - i - k];
face[n - 1 - k][n - 1 - i - k] = face[n - 1 - i - k][0 + k];
face[n - 1 - i - k][0 + k] = aux;
}
else
for (int i = 0; i < n - 1 - 2 * k; i ++)
{
int aux = face[0 + k][i + k];
face[0 + k][i + k] = face[n - 1 - i - k][0 + k];
face[n - 1 - i - k][0 + k] = face[n - 1 - k][n - 1 - i - k];
face[n - 1 - k][n - 1 - i - k] = face[i + k][n - 1 - k];
face[i + k][n - 1 - k] = aux;
}
}
}
void moveR(Cube &c, int number, bool reverse)
{
if (reverse)
for (int i = 0; i < n; i ++)
{
int aux = c.face[0][n - 1 - i][number];
c.face[0][n - 1 - i][number] = c.face[1][n - 1 - i][number];
c.face[1][n - 1 - i][number] = c.face[2][i][number];
c.face[2][i][number] = c.face[3][i][number];
c.face[3][i][number] = aux;
}
else
for (int i = 0; i < n; i ++)
{
int aux = c.face[3][i][number];
c.face[3][i][number] = c.face[2][i][number];
c.face[2][i][number] = c.face[1][n - 1 - i][number];
c.face[1][n - 1 - i][number] = c.face[0][n - 1 - i][number];
c.face[0][n - 1 - i][number] = aux;
}
if (number == 0) rotateFace(c.face[5], reverse);
if (number == n - 1) rotateFace(c.face[4], reverse);
}
void moveU(Cube &c, int number, bool reverse)
{
if (reverse)
for (int i = 0; i < n; i ++)
{
int aux = c.face[0][number][i];
c.face[0][number][i] = c.face[4][number][i];
c.face[4][number][i] = c.face[2][number][n - 1 - i];
c.face[2][number][n - 1 - i] = c.face[5][number][n - 1 - i];
c.face[5][number][n - 1 - i] = aux;
}
else
for (int i = 0; i < n; i ++)
{
int aux = c.face[5][number][n - 1 - i];
c.face[5][number][n - 1 - i] = c.face[2][number][n - 1 - i];
c.face[2][number][n - 1 - i] = c.face[4][number][i];
c.face[4][number][i] = c.face[0][number][i];
c.face[0][number][i] = aux;
}
if (number == 0) rotateFace(c.face[1], !reverse);
if (number == n - 1) rotateFace(c.face[3], !reverse);
}
void moveF(Cube &c, int number, bool reverse)
{
if (reverse)
for (int i = 0; i < n; i ++)
{
int aux = c.face[1][n - 1 - number][i];
c.face[1][n - 1 - number][i] = c.face[5][n - 1 - i][number];
c.face[5][n - 1 - i][number] = c.face[3][n - 1 - number][n - 1 - i];
c.face[3][n - 1 - number][n - 1 - i] = c.face[4][i][number];
c.face[4][i][number] = aux;
}
else
for (int i = 0; i < n; i ++)
{
int aux = c.face[5][n - 1 - i][number];
c.face[5][n - 1 - i][number] = c.face[1][n - 1 - number][i];
c.face[1][n - 1 - number][i] = c.face[4][i][number];
c.face[4][i][number] = c.face[3][n - 1 - number][n - 1 - i];
c.face[3][n - 1 - number][n - 1 - i] = aux;
}
if (number == 0) rotateFace(c.face[0], !reverse);
if (number == n - 1) rotateFace(c.face[2], !reverse);
}
void moveCube(Cube &c, unsigned char key, int number)
{
switch (key)
{
case 'R': moveR(c, number, (number > n / 2) - false); break;
case 'r': moveR(c, number, (number > n / 2) - true); break;
case 'U': moveU(c, number, (number > n / 2) - false); break;
case 'u': moveU(c, number, (number > n / 2) - true); break;
case 'F': moveF(c, number, (number > n / 2) - false); break;
case 'f': moveF(c, number, (number > n / 2) - true); break;
default: break;
}
}
void randomScramble(Cube &c)
{
srand(time(NULL)); char op[7] = "RUFruf";
for (int i = 0; i < 100; i ++)
{
int number = rand() % n;
moveCube(c, op[rand() % 6], number == n / 2 ? number - 1 : number);
}
}
void readScramble(Cube &c)
{
randomScramble(c); return;
int number; char op;
FILE *scrambleFile = fopen("cube/scramble", "r"); if (scrambleFile == NULL) return;
while (fscanf(scrambleFile, "%d%c", &number, &op) != EOF) moveCube(c, op, number - 1);
fclose(scrambleFile);
}
| true |
4365ea855839f01e6dfee313a986ef60065e903b | C++ | abdalimran/Online_Judge_Solutions | /URI Solutions/1020.cpp | UTF-8 | 295 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int ind,y,m,d;
cin>>ind;
y=ind/365;
ind=(ind%365);
m=ind/30;
ind=(ind%30);
d=ind;
cout<<y<<" ano(s)"<<endl;
cout<<m<<" mes(es)"<<endl;
cout<<d<<" dia(s)"<<endl;
return 0;
}
| true |
981f814a1c43c569243346569687fb5b960980bc | C++ | ldcduc/leetcode-training | /cpp/find-the-difference.cpp | UTF-8 | 412 | 2.984375 | 3 | [] | no_license | /* Problem url: https://leetcode.com/problems/find-the-difference
* Code by: ldcduc
* */
class Solution {
public:
char findTheDifference(string s, string t) {
char result = 0;
for (auto c : s) {
result -= c;
}
for (auto c : t) {
result += c;
}
return result;
}
};
/*
* Comment by ldcduc
* Suggested tags: string, fun
*
* */
| true |
2005e54baf8b69ce939a59c817185fabc43cca19 | C++ | Alankvuong/A12-DFS_and_BFS_directed_edges | /main.cpp | UTF-8 | 4,446 | 3.34375 | 3 | [] | no_license | /***************************************************
* Programmed by : Ethan Bockler, Tim Diersing, *
* Alan Vuong *
* Assignment : A11 : DFS and BFS *
* *
* This program will demonstrate a depth - first *
* and breadth - first search of a directed graph. *
****************************************************/
#include "main_header.h"
#include "BfsGraph.h"
#include "DfsGraph.h"
/***********************************************************
* This program implements a DFS and BFS search algorithm
* on a directed graph and attempts to find and identify
* the edges. This program will also output the origin
* vertex, destination vertex, and total distance traveled.
**************************************************************/
int main() {
// Prints heading
PrintHeader();
// Creates object for BFS and DFS
DfsGraph dfs;
BfsGraph bfs;
// Adds the node and edges for the dfs graph
cout << " DFS" << endl << "-----" << endl;
dfs.addNode("Chicago");
dfs.addNode("Seattle");
dfs.addNode("Boston");
dfs.addNode("San Francisco");
dfs.addNode("Denver");
dfs.addNode("New York");
dfs.addNode("Los Angeles");
dfs.addNode("Kansas City");
dfs.addNode("Atlanta");
dfs.addNode("Dallas");
dfs.addNode("Houston");
dfs.addNode("Miami");
// Add edges for dfs graph
dfs.addEdge("Chicago", "Seattle", 2097);
dfs.addEdge("Chicago", "Boston", 983);
dfs.addEdge("Denver", "Chicago", 1003);
dfs.addEdge("New York", "Chicago", 787);
dfs.addEdge("Seattle", "Denver", 1331);
dfs.addEdge("Boston", "New York", 214);
dfs.addEdge("Seattle", "San Francisco", 807);
dfs.addEdge("Denver", "San Francisco", 1267);
dfs.addEdge("Kansas City", "New York", 1260);
dfs.addEdge("Kansas City", "Chicago", 533);
dfs.addEdge("Kansas City", "Denver", 599);
dfs.addEdge("San Francisco", "Los Angeles", 381);
dfs.addEdge("Los Angeles", "Denver", 1015);
dfs.addEdge("Dallas", "Los Angeles", 1435);
dfs.addEdge("Dallas", "Kansas City", 496);
dfs.addEdge("New York", "Atlanta", 888);
dfs.addEdge("Kansas City", "Atlanta", 864);
dfs.addEdge("Dallas", "Atlanta", 781);
dfs.addEdge("Houston", "Dallas", 239);
dfs.addEdge("Houston", "Atlanta", 810);
dfs.addEdge("Atlanta", "Miami", 661);
dfs.addEdge("Miami", "Houston", 1187);
dfs.addEdge("Kansas City", "Los Angeles", 1663);
// Starting point of DFS
dfs.Dfs("Denver");
cout << "-----------------------" << endl;
cout << endl;
// Prints the initial, terminal, and edge type
dfs.print();
// ********* BFS ****************
cout << endl << " BFS" << endl << "-----" << endl;
// Adds node for BFS
bfs.addNode("Chicago");
bfs.addNode("Seattle");
bfs.addNode("Boston");
bfs.addNode("San Francisco");
bfs.addNode("Denver");
bfs.addNode("New York");
bfs.addNode("Los Angeles");
bfs.addNode("Kansas City");
bfs.addNode("Atlanta");
bfs.addNode("Dallas");
bfs.addNode("Houston");
bfs.addNode("Miami");
// Adds edges for BFS
bfs.addEdge("Chicago", "Seattle", 2097);
bfs.addEdge("Chicago", "Boston", 983);
bfs.addEdge("Denver", "Chicago", 1003);
bfs.addEdge("New York", "Chicago", 787);
bfs.addEdge("Seattle", "Denver", 1331);
bfs.addEdge("Boston", "New York", 214);
bfs.addEdge("Seattle", "San Francisco", 807);
bfs.addEdge("Denver", "San Francisco", 1267);
bfs.addEdge("Kansas City", "New York", 1260);
bfs.addEdge("Kansas City", "Chicago", 533);
bfs.addEdge("Kansas City", "Denver", 599);
bfs.addEdge("San Francisco", "Los Angeles", 381);
bfs.addEdge("Los Angeles", "Denver", 1015);
bfs.addEdge("Dallas", "Los Angeles", 1435);
bfs.addEdge("Dallas", "Kansas City", 496);
bfs.addEdge("New York", "Atlanta", 888);
bfs.addEdge("Kansas City", "Atlanta", 864);
bfs.addEdge("Dallas", "Atlanta", 781);
bfs.addEdge("Houston", "Dallas", 239);
bfs.addEdge("Houston", "Atlanta", 810);
bfs.addEdge("Atlanta", "Miami", 661);
bfs.addEdge("Miami", "Houston", 1187);
bfs.addEdge("Kansas City", "Los Angeles", 1663);
bfs.Bfs("Denver");
bfs.print();
cout << "\n";
bool connection = dfs.isStronglyConnected();
if (connection == true)
{
cout << "A directed graph is said to be strongly connected if there is a path between all pairs of vertices.\n";
cout << "According to the definition, the graph ** IS ** strongly connected because each node can access every other node\n";
cout << "at any point within the graph." << endl;
}
else
{
cout << "The graph is not strongly connected.";
}
return 0;
} | true |
24b06c93e3795f40244948b11d6d73cbfe1b1ff0 | C++ | fsilvestrim/saliency_map | /src/main.cpp | UTF-8 | 10,290 | 2.65625 | 3 | [] | no_license | #include "OrientedPyr.h"
#include "argparse.hpp"
#include "fusion_methods.hpp"
#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
//#define VISUAL
//#define SHOW_FINAL
//#define SHOW_ORIENTATION
struct hyperparams {
int num_layers = 4;
int center_sigma = 2;
int surround_sigma = 5;
int orientation_sigma = 1;
int orientation_amount = 4;
int o_gardor_size = 10;
double o_gardor_sigma = 5.0;
double o_gardor_lambd = 5.0;
double o_gardor_gamma = 1.0;
double o_gardor_psi = 0.0;
boost::filesystem::path out_path;
} settings;
void on_off_contrasts(GaussPyr center_pyr, GaussPyr surround_pyr,
std::vector<cv::Mat> &on_off, std::vector<cv::Mat> &off_on) {
//DoG contrast is obtained by subtracting center from
//surround and vice versa
for (int l = 0; l < settings.num_layers; ++l) {
cv::Mat center_surround = center_pyr.getLayer(l) - surround_pyr.getLayer(l);
cv::threshold(center_surround, center_surround, 0, 1, cv::THRESH_TOZERO);
on_off.push_back(center_surround);
cv::Mat surround_center = surround_pyr.getLayer(l) - center_pyr.getLayer(l);
cv::threshold(surround_center, surround_center, 0, 1, cv::THRESH_TOZERO);
off_on.push_back(surround_center);
}
}
void show_image(std::string header, cv::Mat img, bool scale=false)
{
cv::namedWindow(header, cv::WINDOW_AUTOSIZE);
if (scale) cv::normalize(img, img, 0, 255, cv::NORM_MINMAX, CV_8UC1);
cv::imshow(header, img);
cv::waitKey(0);
cv::destroyWindow(header);
}
void show_two_images(std::string header, cv::Mat left, cv::Mat right)
{
cv::Mat merged(left.size().height, left.size().width+right.size().width, CV_32F);
cv::Mat in_left(merged, cv::Rect(0, 0, left.size().width, left.size().height));
left.copyTo(in_left);
cv::Mat in_right(merged, cv::Rect(left.size().width, 0, right.size().width, right.size().height));
right.copyTo(in_right);
show_image(header, merged);
}
void save_image(cv::Mat image, std::string outPath) {
cv::Mat outImage;
image.convertTo(outImage, CV_8UC1, 255);
cv::imwrite(outPath, outImage);
}
void process_image(boost::filesystem::path image_path) {
std::cout << "Processing '" << image_path << "' ..." << std::endl;
// load img
cv::Mat image;
image = cv::imread(image_path.string(), CV_LOAD_IMAGE_COLOR);
if (!image.data) {
std::cout << "Skipping: Could not open or find the image" << std::endl;
return;
}
// convert to lab
cv::Mat image_lab;
cv::cvtColor(image, image_lab, CV_RGB2Lab);
image_lab.convertTo(image_lab, CV_32FC3);
image_lab /= 255.0f;
//get channels
cv::Mat channels[3];
cv::split(image_lab, channels);
std::vector<cv::Mat> conspicuity_maps;
std::string lab_verbsose[3] = {"L (black/white)", "A (green/red)", "B (blue/yellow)"};
// LAB channels iteration
for (int i = 0; i < 3; ++i) {
//center-surround - pyramids
GaussPyr center_pyr = GaussPyr(channels[i], settings.num_layers, settings.center_sigma);
GaussPyr surround_pyr = GaussPyr(channels[i], settings.num_layers, settings.surround_sigma);
#ifdef VISUAL
show_two_images("Center/Surround Pyramid Layer for " + lab_verbsose[i], center_pyr.getLayer(0), surround_pyr.getLayer(0));
#endif
//center-surround contrasts
std::vector<cv::Mat> on_off, off_on;
on_off_contrasts(center_pyr, surround_pyr, on_off, off_on);
#ifdef VISUAL
show_two_images("Center/Surround Contrast 4 Upper Layer for " + lab_verbsose[i], on_off[0], off_on[0]);
#endif
//center-surround - feature maps
cv::Mat on_off_feature, off_on_feature;
on_off_feature = fusion_across_scale_addition(on_off);
off_on_feature = fusion_across_scale_addition(off_on);
#ifdef VISUAL
show_two_images("Center/Surround Feature (fused) for " + lab_verbsose[i], on_off_feature, off_on_feature);
#endif
//contrast - pyramids
GaussPyr on_off_contrast = GaussPyr(on_off_feature, settings.num_layers, settings.center_sigma);
GaussPyr off_on_contrast = GaussPyr(off_on_feature, settings.num_layers, settings.surround_sigma);
//contrast - feature maps
cv::Mat on_off_contrast_feature, off_on_contrast_feature;
on_off_contrast_feature = fusion_across_scale_addition(on_off_contrast.getLayers());
off_on_contrast_feature = fusion_across_scale_addition(off_on_contrast.getLayers());
#ifdef VISUAL
show_two_images("Center/Surround Contrast Feature (fused) for " + lab_verbsose[i], on_off_contrast_feature, off_on_contrast_feature);
#endif
//conspicuity maps
std::vector<cv::Mat> contrast_features = {on_off_contrast_feature, off_on_contrast_feature};
conspicuity_maps.push_back(fusion_arithmetic_mean(contrast_features));
#ifdef VISUAL
show_image("Conspicuity Feature for " + lab_verbsose[i], conspicuity_maps[i]);
#endif
}
//orientation
GaussPyr center_pyr = GaussPyr(channels[0], settings.num_layers, settings.center_sigma);
LaplacianPyr lap_pyr = LaplacianPyr(center_pyr, settings.orientation_sigma);
OrientedPyr or_pyr = OrientedPyr(lap_pyr,
settings.orientation_amount,
settings.o_gardor_size,
settings.o_gardor_sigma,
settings.o_gardor_lambd,
settings.o_gardor_gamma,
settings.o_gardor_psi);
//orientations - features
std::vector<cv::Mat> orientation_features;
for (int j = 0; j < settings.orientation_amount; ++j) {
orientation_features.push_back(fusion_across_scale_addition(or_pyr.orientationMaps[j]));
}
//conspicuity maps for orientation
cv::Mat orientation_feature;
orientation_feature = fusion_max(orientation_features);
conspicuity_maps.push_back(orientation_feature);
#if defined(VISUAL) || defined(SHOW_ORIENTATION)
show_image("Conspicuity Feature for Orientation", orientation_feature, true);
#endif
//saliency
cv::Mat saliency = fusion_arithmetic_mean(conspicuity_maps);
#if defined(VISUAL) || defined(SHOW_FINAL)
show_image("Final", saliency);
#endif
//save
std::string output_path = (settings.out_path / image_path.stem()).string() + "_saliency.png";
save_image(saliency, output_path);
}
int main(int argc, const char **argv) {
int num_layers = 4;
int center_sigma = 5;
int surround_sigma = 20;
//params
ArgumentParser parser;
parser.addArgument("-i", "--input", 1, false);
parser.addArgument("-o", "--output", 1, false);
parser.addArgument("-l", "--layers", 1);
parser.addArgument("-c", "--center", 1);
parser.addArgument("-s", "--surround", 1);
parser.addArgument("-a", "--oamount", 1);
parser.addArgument("-t", "--osigma", 1);
parser.addArgument("--gardor_size", 1);
parser.addArgument("--gardor_sigma", 1);
parser.addArgument("--gardor_lambd", 1);
parser.addArgument("--gardor_gamma", 1);
parser.addArgument("--gardor_psi", 1);
parser.parse(argc, argv);
std::string input = parser.retrieve<std::string>("input");
std::string output = parser.retrieve<std::string>("output");
if(parser.exists("--layers")) settings.num_layers = std::stoi(parser.retrieve<std::string>("layers"),nullptr,0);
if(parser.exists("--center")) settings.center_sigma = std::stoi(parser.retrieve<std::string>("center"),nullptr,0);
if(parser.exists("--surround")) settings.surround_sigma = std::stoi(parser.retrieve<std::string>("surround"),nullptr,0);
if(parser.exists("--oamount")) settings.orientation_amount = std::stoi(parser.retrieve<std::string>("oamount"),nullptr,0);
if(parser.exists("--osigma")) settings.orientation_sigma = std::stoi(parser.retrieve<std::string>("osigma"),nullptr,0);
if(parser.exists("--gardor_size")) settings.o_gardor_size = std::stoi(parser.retrieve<std::string>("gardor_size"),nullptr,0);
if(parser.exists("--gardor_sigma")) settings.o_gardor_sigma = std::stoi(parser.retrieve<std::string>("gardor_sigma"),nullptr,0);
if(parser.exists("--gardor_lambd")) settings.o_gardor_lambd = std::stoi(parser.retrieve<std::string>("gardor_lambd"),nullptr,0);
if(parser.exists("--gardor_gamma")) settings.o_gardor_gamma = std::stoi(parser.retrieve<std::string>("gardor_gamma"),nullptr,0);
if(parser.exists("--gardor_psi")) settings.o_gardor_psi = std::stoi(parser.retrieve<std::string>("gardor_psi"),nullptr,0);
//input
boost::filesystem::path input_path(input);
if (!boost::filesystem::exists(input_path)) {
std::cout << "Input path '" << input << "' not found." << std::endl;
return -1;
}
//output
boost::filesystem::path output_path(output);
if (!boost::filesystem::is_directory(output_path)) {
std::cout << "Ouput path '" << output << "' must be a directory (and it's not)." << std::endl;
return -1;
}
if (boost::filesystem::exists(output_path))
boost::filesystem::remove_all(output_path);
boost::filesystem::create_directory(output_path);
settings.out_path = output_path;
//process
if (boost::filesystem::is_regular_file(input_path)) {
std::cout << "You inputed just one image." << std::endl;
process_image(input_path);
} else if (boost::filesystem::is_directory(input_path)) {
std::cout << "You inputed a directory. walking through its content." << std::endl;
boost::regex pattern("\\S+.(jpg|png)$"); // list all files starting with a
for (boost::filesystem::recursive_directory_iterator iter(input_path), end; iter != end; ++iter) {
std::string name = iter->path().filename().string();
if (regex_match(name, pattern)) {
process_image(iter->path());
} else {
std::cout << "Skipping '" << iter->path().string() << "' because it doesn't match the file type"
<< std::endl;
}
}
}
std::cout << "DONE! Check results at '" << settings.out_path.string() << std::endl;
return 0;
}
| true |
c26408637e29477b10b92fc88720ed241822a223 | C++ | zjnu-acm/judge | /judge-site/src/test/resources/sample/program/re/1002.cpp | UTF-8 | 246 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #include<stdio.h>
int main() {
char c1, c2, c3, c4, c5;
c1 = 'C', c2 = 'h', c3 = 'i', c4 = 'n', c5 = 'a';
c1 = c1 + 4, c2 = c2 + 4, c3 = c3 + 4, c4 = c4 + 4, c5 = c5 + 4;
printf("%s%s%s%s%s", c1, c2, c3, c4, c5);
return 0;
}
| true |
fb4606a5f5b18d2e510681794fb56d47bc67b7ec | C++ | samratnagarjuna/CodeSamples | /C++/Robo Kabaddi Game/Game/Libraries/Agents/Agent/agent.cpp | UTF-8 | 2,168 | 2.9375 | 3 | [] | no_license | //
// agent.cpp
// XbeeInterface
//
// Created by Samrat Nagarjuna Pasila on 12/09/14.
// Copyright (c) 2014 Samrat Nagarjuna Pasila. All rights reserved.
//
#include "agent.h"
#include <iostream>
#include <stdlib.h>
Agent::Agent() {
init();
}
Agent::Agent(int x,int y) {
init();
pos = new Pos2d(x,y);
}
Agent::Agent(const Agent& other_agent) {
copy_other_agent(other_agent);
}
Agent& Agent::operator = (const Agent& other_agent) {
if (this != &other_agent) {
clean();
copy_other_agent(other_agent);
}
return *this;
}
Agent::Agent(const BYTE* addr64, const BYTE* network_addr, int x, int y) {
init();
set_addr64(addr64);
set_network_addr(network_addr);
pos = new Pos2d(x,y);
}
void Agent::init() {
pos = NULL;
addr64 = NULL;
network_addr = NULL;
}
void Agent::copy_other_agent(const Agent& other_agent) {
init();
set_addr64(other_agent.addr64);
set_network_addr(other_agent.network_addr);
set_position(other_agent.pos->get_x(), other_agent.pos->get_y());
}
void Agent::clean() {
delete pos;
delete[] addr64;
delete[] network_addr;
pos = NULL;
addr64 = NULL;
network_addr = NULL;
}
void Agent::set_addr64(const BYTE* addr64) {
if (addr64) {
this->addr64 = (!this->addr64) ? new BYTE[SIZE_ADDR64] : this->addr64;
memcpy(this->addr64, addr64, SIZE_ADDR64);
}
else {
if (this->addr64) {
delete[] this->addr64;
this->addr64 = NULL;
}
}
}
BYTE* Agent::get_addr64() {
return addr64;
}
BYTE* Agent::get_network_addr() {
return network_addr;
}
void Agent::set_network_addr(const BYTE* network_addr) {
if (network_addr) {
this->network_addr = (!this->network_addr) ?
new BYTE[SIZE_NETWORK_ADDR] : this->network_addr;
memcpy(this->network_addr, network_addr, SIZE_NETWORK_ADDR);
}
else {
if (this->network_addr) {
delete[] this->network_addr;
this->network_addr = NULL;
}
}
}
void Agent::set_position(int x, int y) {
pos = (!pos) ? new Pos2d() : pos;
pos->set_position(x, y);
}
Agent::~Agent() {
clean();
} | true |
1508d3a24a0ddd715d5c6fd3e1c9de122dc0ae6f | C++ | amendy/UrlaubOsnabrueck | /UrlaubOsnabrueck/Graph.cpp | UTF-8 | 6,806 | 3.359375 | 3 | [] | no_license | #include "Graph.h"
#include <list>
#include <fstream>
#include <algorithm>
#include <limits>
#include <map>
//---------------------------------------------------------------------------------------------------------------------
Graph::~Graph()
{
for (std::list<Edge*>::iterator it = m_edges.begin(); it != m_edges.end(); it++)
{
delete *it;
}
for (std::list<Node*>::iterator it = m_nodes.begin(); it != m_nodes.end(); it++)
{
delete *it;
}
}
//---------------------------------------------------------------------------------------------------------------------
Node& Graph::addNode(Node* pNewNode)
{
if (findNode(pNewNode->getID()) != NULL)
{
throw "Duplicated NodeID";
}
m_nodes.push_back(pNewNode);
return *pNewNode;
// TEST:
// Testen Sie die Funktion, indem Sie indem Sie einen Graph mit ein paar Nodes in main.cpp erstellen
// Testen Sie mit der Funktion 'findNode', ob die hinzugefügten Nodes im Graph vorhanden sind.
}
//---------------------------------------------------------------------------------------------------------------------
Edge& Graph::addEdge(Edge* pNewEdge)
{
m_edges.push_back(pNewEdge);
std::list<Node*>::iterator itSrcNode;
itSrcNode = std::find(m_nodes.begin(), m_nodes.end(), &pNewEdge->getSrcNode());
if (itSrcNode == m_nodes.end())
{
addNode(&pNewEdge->getSrcNode());
}
std::list<Node*>::iterator itDstNode;
itDstNode = std::find(m_nodes.begin(), m_nodes.end(), &pNewEdge->getDstNode());
if (itDstNode == m_nodes.end())
{
addNode(&pNewEdge->getDstNode());
}
return *pNewEdge;
}
//---------------------------------------------------------------------------------------------------------------------
void Graph::remove(Node& rNode)
{
for (std::list<Edge*>::iterator it = m_edges.begin(); it != m_edges.end(); )
{
Edge* pCurrentEdge = *it;
if (pCurrentEdge->isConnectedTo(rNode))
{
// erase gibt uns einen Iterator auf das Element nach dem gelöschten Element zurück
it = m_edges.erase(it);
}
else
{
it++;
}
}
m_nodes.remove(&rNode);
delete &rNode;
}
//---------------------------------------------------------------------------------------------------------------------
void Graph::remove(Edge& rEdge)
{
m_edges.remove(&rEdge);
delete &rEdge;
}
//---------------------------------------------------------------------------------------------------------------------
Node* Graph::findNode(const std::string& id)
{
for (std::list<Node*>::iterator it = m_nodes.begin(); it != m_nodes.end(); it++)
{
Node* pCurrentNode = *it;
if (pCurrentNode->getID() == id)
{
return pCurrentNode;
}
}
return NULL;
}
Node* Graph::showNode() {
for (std::list<Node*>::iterator it = m_nodes.begin(); it != m_nodes.end(); it++)
{
Node* pCurrentNode = *it;
return pCurrentNode;
}
}
//---------------------------------------------------------------------------------------------------------------------
std::vector<Edge*> Graph::findEdges(const Node& rSrc, const Node& rDst)
{
std::vector<Edge*> ret;
// - findet alle edges, mit rSrc als Source-Node und rDst als Destination-Node.
// - füge die Zeiger der Edges in den vector 'ret' ein.
return ret;
// TEST:
// Testen Sie die Funktion, indem Sie indem Sie einen Graph mit ein paar Nodes und Edges in main.cpp erstellen
// und anschließend ein paar Edges im Graph suchen.
// Prüfen Sie, ob Edges gefunden wurden und geben Sie die gefunden Edges auf der Kommandozeile aus!
}
//---------------------------------------------------------------------------------------------------------------------
void Graph::findShortestPathDijkstra(std::deque<Edge*>& rPath, const Node& rSrcNode, const Node& rDstNode)
{
Node* src = findNode(rSrcNode.getID());
Node* dst = findNode(rDstNode.getID());
if (src == NULL || dst == NULL)
{
return;
}
std::list<Node*> Q;
std::map<Node*, RouteInfo> nodeInfo;
for (std::list<Node*>::iterator it = m_nodes.begin(); it != m_nodes.end(); it++)
{
nodeInfo[*it] = { std::numeric_limits<double>::max(), NULL, NULL };
Q.push_back(*it);
}
nodeInfo[src].dist = 0;
while (!Q.empty())
{
Node* u = Q.front(); // erstes Element in der Liste
for (std::list<Node*>::iterator it = Q.begin(); it != Q.end(); it++)
{
if (nodeInfo[*it].dist < nodeInfo[u].dist)
{
u = *it;
}
}
Q.remove(u);
// Abbruchbedingung
if (u == dst)
{
for (Node* pCurrentNode = dst;
nodeInfo[pCurrentNode].prevEdge != NULL;
pCurrentNode = nodeInfo[pCurrentNode].prevNode)
{
rPath.push_front(nodeInfo[pCurrentNode].prevEdge);
}
return;
}
for (std::list<Edge*>::iterator it = u->getOutEdges().begin(); it != u->getOutEdges().end(); it++)
{
Edge* pNeighbourEdge = *it;
Node* pNeighbourNode = &pNeighbourEdge->getDstNode();
double newDistance = nodeInfo[u].dist + pNeighbourEdge->getWeight();
if (newDistance < nodeInfo[pNeighbourNode].dist)
{
RouteInfo& vInfo = nodeInfo[pNeighbourNode];
vInfo.dist = newDistance;
vInfo.prevNode = u;
vInfo.prevEdge = pNeighbourEdge;
}
}
}
/*
Ein häufiges Anwendungsproblem für Graphen-Anwendungen besteht darin,
den Pfad zwischen verschiedenen Nodes zu finden, die direkt oder indirekt über Edges miteinander verbunden sind.
Um den optimalsten Pfad(den mit den geringsten Kantengewichten) zu finden, gibt es den Dijkstra-Algorithmus!
Pseudocode (Quelle: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
>>>
function Dijkstra(Graph, source):
create vertex set Q
for each vertex v in Graph: // Initialization
dist[v] ← INFINITY // Unknown distance from source to v
prev[v] ← UNDEFINED // Previous node in optimal path from source
add v to Q // All nodes initially in Q (unvisited nodes)
dist[source] ← 0 // Distance from source to source
while Q is not empty:
u ← vertex in Q with min dist[u] // Source node will be selected first
remove u from Q
for each neighbor v of u: // where v is still in Q.
alt ← dist[u] + length(u, v)
if alt < dist[v]: // A shorter path to v has been found
dist[v] ← alt
prev[v] ← u
return dist[], prev[]
<<<
Betrachten Sie den Pseudocode und setzen Sie ihn in C++ um.
Sortieren Sie am Ende das Ergebnis in die richtige Reihenfolge um
und geben sie die kürzeste Route zwischen rSrcNode und rDstNode als Liste von Edges zurück.
TEST:
Testen Sie diese Funktion, indem Sie einen Graph in main.cpp erstellen
und sich die kürzesteste Route zwischen 2 Nodes zurückgeben lassen.
*/
}
//---------------------------------------------------------------------------------------------------------------------
| true |
da9511551e8ec3bc645e9ac768e591e5baa1fcf8 | C++ | mava4233/Pac-Man-Example | /Arkanoid/Map.h | UTF-8 | 599 | 2.640625 | 3 | [] | no_license | // Map.h
#pragma once
#include "State.h"
#include "Collider.h"
class Tile;
class Pellet;
class Map
{
public:
Map(System& system);
~Map();
Collider* GetWallCol();
Collider* GetPelletCol();
std::vector<Tile*> GetTileList(){ return TileList; };
std::vector<Pellet*> GetPelletList() { return PelletList; };
private:
std::vector<Tile*> TileList;
std::vector<Pellet*> PelletList;
public:
bool LoadMap(char* File);
void RenderMap(SDL_Surface* Surf_Display, int MapX, int MapY);
private:
int m_map_width;
int m_map_height;
int m_tile_size;
System m_systems;
Collider* m_collider;
};
| true |
af730f825c9ddae806d3eebf9938e30652cd76ef | C++ | sopyer/Shadowgrounds | /ui/AmbientSoundManager.h | UTF-8 | 1,208 | 2.53125 | 3 | [] | no_license | #ifndef AMBIENT_SOUND_MANAGER_H
#define AMBIENT_SOUND_MANAGER_H
namespace sfx {
class SoundLooper;
} // sfx
namespace game
{
class GameUI;
}
namespace ui
{
struct AmbientSoundManagerData;
class AmbientSoundManager
{
public:
AmbientSoundManager(game::GameUI* gameUI_, sfx::SoundLooper* looper_);
virtual ~AmbientSoundManager();
void clearAllAmbientSounds();
void setNextFreeAmbientSound();
void setSelectedAmbientSound(int i);
int getSelectedAmbientSound();
void setAmbientSoundRange(int i, float f);
void setAmbientSoundClip(int i, int clipQuarters);
void setAmbientSoundPosition(int i, const Vector& pos);
void setAmbientSoundRollOff(int i, int rollOff);
void setAmbientSoundVolume(int i, int volume);
void setAmbientSoundName(int i, const char *name);
void makeAmbientSoundFromDefString(int i, const char* defString);
void startAmbientSound(int i);
void stopAmbientSound(int i, bool immediately);
void setListenerPosition(const Vector& listenerPosition);
void run();
int getAmbientSoundNumberByName(const char *name);
void selectAmbientSoundByName(const char *name);
private:
AmbientSoundManagerData* m;
};
}
#endif
| true |
ce055ac1b9e33157dc9fa0489f4669b8f8214f4b | C++ | winash12/VPTree | /purec++/Test.cpp | UTF-8 | 2,380 | 3.25 | 3 | [] | no_license | // Example of using the GeographicLib::NearestNeighbor class. Read lon/lat
// points for coast from coast.txt and lon/lat for vessels from vessels.txt.
// For each vessel, print to standard output: the index for the closest point
// on coast and the distance to it.
// This requires GeographicLib version 1.47 or later.
// Compile/link with, e.g.,
// g++ -I/usr/local/include -lGeographic -L/usr/local/bin -Wl,-rpath=/usr/local/lib -o coast coast.cpp
// Run time for 30000 coast points and 46217 vessels is 3 secs.
#include <iostream>
#include <exception>
#include <vector>
#include <fstream>
#include <GeographicLib/NearestNeighbor.hpp>
#include <GeographicLib/Geodesic.hpp>
using namespace std;
using namespace GeographicLib;
// A structure to hold a geographic coordinate.
struct pos {
double _lat, _lon;
pos(double lat = 0, double lon = 0) : _lat(lat), _lon(lon) {}
};
// A class to compute the distance between 2 positions.
class DistanceCalculator {
private:
Geodesic _geod;
public:
explicit DistanceCalculator(const Geodesic& geod) : _geod(geod) {}
double operator() (const pos& a, const pos& b) const {
double d;
_geod.Inverse(a._lat, a._lon, b._lat, b._lon, d);
if ( !(d >= 0) )
// Catch illegal positions which result in d = NaN
throw GeographicErr("distance doesn't satisfy d >= 0");
return d;
}
};
int main() {
try {
// Read in coast
vector<pos> coast;
double lat, lon;
{
ifstream is("coast.txt");
if (!is.good())
throw GeographicErr("coast.txt not readable");
while (is >> lon >> lat)
coast.push_back(pos(lat, lon));
if (coast.size() == 0)
throw GeographicErr("need at least one location");
}
// Define a distance function object
DistanceCalculator distance(Geodesic::WGS84());
// Create NearestNeighbor object
NearestNeighbor<double, pos, DistanceCalculator>
coastset(coast, distance);
ifstream is("vessels.txt");
double d;
int count = 0;
vector<int> k;
while (is >> lon >> lat) {
++count;
d = coastset.Search(coast, distance, pos(lat, lon), k);
if (k.size() != 1)
throw GeographicErr("unexpected number of results");
cout << k[0] << " " << d << "\n";
}
}
catch (const exception& e) {
cerr << "Caught exception: " << e.what() << "\n";
return 1;
}
}
| true |
e16583353b4154861359044e6ed2fd9a8325326d | C++ | cmf41013/Algorithms | /Graph/Shortest-path Algorithms/Bellman Ford/main.cpp | UTF-8 | 982 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include "WeightedSparseGraph.h"
#include "ReadWeightedGraph.h"
#include "BellmanFord.h"
using namespace std;
// 测试Bellman-Ford算法
int main() {
string filename = "test.txt";
int V = 5;
// 有向图
WeightedSparseGraph<int> g = WeightedSparseGraph<int>(V, true);
ReadWeightedGraph<WeightedSparseGraph<int>, int> readGraph(g, filename);
cout<<"Test Bellman-Ford: "<<endl<<endl;
BellmanFord<WeightedSparseGraph<int>, int> bellmanFord(g, 0);
if( bellmanFord.negativeCycle() )
cout<<"The graph contain negative cycle!"<<endl;
else
for( int i = 1 ; i < V ; i ++ ) {
if (bellmanFord.hasPathTo(i)) {
cout << "Shortest Path to " << i << " : " << bellmanFord.shortestPathTo(i) << endl;
bellmanFord.showPath(i);
}
else
cout << "No Path to " << i << endl;
cout << "----------" << endl;
}
return 0;
}
| true |
76d9781fa66149f8a0b08f4b33e8e6c37f72e9be | C++ | dtdsouza/URI | /1006.cpp | UTF-8 | 314 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <locale.h>
#include <iomanip>
using namespace std;
int main()
{
setlocale(LC_ALL,"Portuguese");
double A,B,C,MEDIA;
cin >> A >> B >> C;
MEDIA = (A*2/10) + (B*3/10) + (C*5/10);
cout << "MEDIA = " <<fixed<<setprecision(1)<<MEDIA<<endl;
cin.get();
return 0;
}
| true |
cc8c05f2b75e58e61ff9f130a672a59910ce6c02 | C++ | ArgentumHeart/mipt-1st-term | /sem02/010.cpp | UTF-8 | 554 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
char unleveling(char c);
char get_a_letter();
//-------------------------------------------------------------
char get_a_letter() {
char input;
do {
cin >> input;
} while ( !(((input >= 'a') && (input <= 'z')) || ((input >= 'A') && (input <= 'Z'))));
return input;
}
char unleveling(char c)
{
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
return c;
}
int main()
{
for (int i = 0; i < 10; i++)
cout <<unleveling(get_a_letter());
cout <<endl;
return 0;
} | true |
2cac3fb6d0bb82caba65f71d79ccd1e257b63df9 | C++ | sheldak/IntroductionToComputerScience | /Agnieszka/6_1_2.cpp | UTF-8 | 465 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int N = 6;
bool odwaz(int t[N], int masa, int frst=0){
if(frst==N){
return false;
}
for(int i=frst;i<N;i++){
if(masa-t[i]==0) return true; // masa zostala osiagnieta
if(masa-t[i]<0)
continue; // odwaznik za duzy
if(odwaz(t, masa-t[i], i+1))return true;
}
return false;
}
main(){
int t[]={2,3,5,8,9,23};
cout<< odwaz(t, 34);
}
| true |
3b6832c77a72746012dd05d667985449c83357c0 | C++ | bhankey/webserver | /RequestHandler/Envp.cpp | UTF-8 | 1,673 | 2.9375 | 3 | [] | no_license | //
// Created by sergey on 22.03.2021.
//
#include "../includes/Envp.hpp"
Envp::Envp(char **_envp) {
for (int i = 0; _envp[i] != NULL; i++) {
envp.push_back(splitNameVal(_envp[i]));
}
}
Envp::Envp(const Envp &environment): envp(environment.envp) {
}
Envp &Envp::operator=(const Envp &environment) {
if (this != &environment) {
envp = environment.envp;
}
return *this;
}
std::string Envp::getenv(const std::string& name) {
for (std::vector<std::vector<std::string> >::iterator it = envp.begin(); it != envp.end(); ++it) {
if ((*it)[0] == name) {
return ((*it)[1]);
}
}
return ("");
}
std::vector<std::string> Envp::splitNameVal(const std::string& str) {
std::vector<std::string> tokens(2);
size_t pos = str.find_first_of('=');
tokens[0] = str.substr(0, pos);
tokens[1] = str.substr(pos + 1, std::string::npos);
return (tokens);
}
void Envp::putenv(const std::string &name, const std::string &value) {
for (std::vector<std::vector<std::string> >::iterator it = envp.begin(); it != envp.end(); ++it) {
if ((*it)[0] == name) {
(*it)[1] = value;
return;
}
}
std::vector<std::string> env(2);
env[0] = name;
env[1] = value;
envp.push_back(env);
}
char **Envp::getenvp() {
char **CEnvp = new char *[envp.size() + 1]();
for (size_t i = 0; i < envp.size(); i++) {
std::string env = envp[i][0] + "=" + envp[i][1];
CEnvp[i] = new char[env.size() + 1]();
env.copy(CEnvp[i], env.size());
CEnvp[i][env.size()] = '\0';
}
CEnvp[envp.size()] = NULL;
return CEnvp;
}
std::vector<std::vector<std::string> > Envp::getenvpVector() {
return envp;
}
Envp::~Envp() {
}
Envp::Envp() {
}
| true |
6be1a3158a5bd38868d706d83757bfee7701183b | C++ | suumquique/obfuscator | /config.cpp | UTF-8 | 2,594 | 3.21875 | 3 | [] | no_license | #include "main.hpp"
BOOL getCurrentFlagValue(wstring fullString) {
// Конец строки, показывающий, что значение флага установлено как true
wstring endings[] = { L"=true", L"=1" };
// Проходим все строки из массива endings
for (wstring ending : endings) {
// Каждую строку сравниваем с концом полной строки конфига
if (fullString.length() >= ending.length()) {
if (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending)) return TRUE;
}
}
return FALSE;
}
Config* parseConfigFile(wfstream& configFile) {
// Создаем экземпляр конфига и заполяем все поля нулями (то есть false)
Config* config = new Config;
memset(config, 0x00, sizeof(Config));
wstring currentConfigString; // Текущая строка конфига, из которогой будем парсить название флага и его значение
wstring currentFlag; // Строковое значение текущего флага
BOOL currentFlagValue; // Значение текущего флага (true или false)
// Считываем конфиг построчно
while (getline(configFile, currentConfigString)) {
// "Вырезаем" из начала строки название нашего флага
currentFlag = currentConfigString.substr(0, currentConfigString.find_first_of(L'='));
// Получаем текущее значение флага (true или false)
currentFlagValue = getCurrentFlagValue(currentConfigString);
if (currentFlag == CONFIG_DELETE_COMMENTS) {
config->deleteComments = currentFlagValue;
}
if (currentFlag == CONFIG_RENAME_VARIABLES) {
config->renameVariables = currentFlagValue;
}
if (currentFlag == CONFIG_RENAME_FUNCTIONS) {
config->renameFunctions = currentFlagValue;
}
if (currentFlag == CONFIG_SHUFFLE_FUNCTIONS) {
config->shuffleFunctions = currentFlagValue;
}
if (currentFlag == CONFIG_ADD_TRASH_VARIABLES) {
config->addTrashVariables = currentFlagValue;
}
if (currentFlag == CONFIG_ADD_TRASH_FUNCTIONS) {
config->addTrashFunctions = currentFlagValue;
}
if (currentFlag == CONFIG_ADD_TRASH_LOOPS) {
config->addTrashLoops = currentFlagValue;
}
if (currentFlag == CONFIG_ADD_TRASH_COMMENTS) {
config->addTrashComments = currentFlagValue;
}
if (currentFlag == CONFIG_DELETE_SPACES) {
config->deleteSpaces = currentFlagValue;
}
}
return config;
} | true |
fea90bc40ea874762b963f2dfaa90f22654ff4e9 | C++ | adechan/School | /Undergrad/First Year/Programming in C/Elementary Algorithms/nFactorial.cpp | UTF-8 | 313 | 3.4375 | 3 | [] | no_license | // It displays the factorial of a n number.
#include "stadfx.h"
include <iostream>
int factorialNumber(int n)
{
if (n == 0 || n == 1) return 1;
else
return n * factorialNumber(n - 1);
}
int main()
{
int n;
std::cout << "Spune un numar: ";
std::cin >> n;
std::cout << factorialNumber(n);
return 0;
}
| true |
c1bf9d4ba5d29bd6c25b2e846bc44904ef223c1f | C++ | morleyxjtu/Web-crawler | /DiskMultiMap.cpp | UTF-8 | 8,326 | 3.109375 | 3 | [] | no_license | #define _CRT_SECURE_NO_DEPRECATE
#include "DiskMultiMap.h"
#include <functional>
using namespace std;
DiskMultiMap::DiskMultiMap(){}
DiskMultiMap::~DiskMultiMap(){
//close all open file
bf.close();
}
bool DiskMultiMap::createNew(const std::string& filename, unsigned int numBuckets) {
//if the object has been called to open or create a hash table, close first
if (bf.isOpen()) {
bf.close();
}
if (bf.createNew(filename.c_str())) {
bf.write(numBuckets, 0); //# of buckets, 0 when created
bf.write(-1, 4); //tracking the head of removed nodes, initially -1 means no such nodes
BinaryFile::Offset bucketStart = 8; //the space for buckets starts at offset 8
//initialize each bucket with -2
for (unsigned int i = 0; i < numBuckets; i++) {
bf.write(-2, bucketStart); //-2 means the bucket is empty
bucketStart += 4; //move to next bucket
}
return true;
}
else { //return false if not able to create
return false;
}
}
bool DiskMultiMap::openExisting(const std::string& filename) {
//if the object has been called to open or create a hash table, close first
if (bf.isOpen()) {
bf.close();
}
//open existing file
if (bf.openExisting(filename.c_str())) {
return true;
}
else
{
return false;//return false if not able to open
}
}
void DiskMultiMap::close() {
//only close when there are files already open
if (bf.isOpen()) {
bf.close();
}
}
bool DiskMultiMap::insert(const std::string& key, const std::string& value, const std::string& context) {
//return false if the user tries to insert any key, value or context field with more than 120 or more characters
if (key.size() > MAX_DATA_LENGTH || value.size() > MAX_DATA_LENGTH || context.size() > MAX_DATA_LENGTH) {
return false;
}
//create the hash value and bucket position for the key
int numBuckets;
bf.read(numBuckets, 0);
hash<string>str_hash; //built-in hash function return a hash value
int index = 8 + str_hash(key) % numBuckets*4; //index of the buckets starting at 8
//check if there is space that can be reused
//return offest to insert new node
BinaryFile::Offset newNode;
BinaryFile::Offset reuse;
bf.read(reuse, 4);
if (reuse == -1) { //if no nodes were removed
newNode = bf.fileLength(); //new location is end of the file
}
else { //if nodes were removed
newNode = reuse; //new location is the head of the removed nodes
Node temp;
bf.read(temp, reuse); //new head of the removed nodes is stored in the next of current node
reuse = temp.next;
bf.write(reuse, 4); //write the new head of the removed nodes into head file
}
//add the new node into the right location and change corresponding bucket (head)
BinaryFile::Offset head;
bf.read(head, index); //get the current offset of head node for this bucket
Node in(key.c_str(), value.c_str(), context.c_str(), head); //push current node to the front
bf.write(in, newNode); //write the new node into the new location
head = newNode;
bf.write(head, index); //update the head offset
return true;
}
DiskMultiMap::Iterator DiskMultiMap::search(const std::string& key) {
if (key.size() > MAX_DATA_LENGTH) { //if the length of key is bigger han max size, return invalid iterator
DiskMultiMap::Iterator it;
return it;
}
//find the bucket index using built-in hash function
int numBuckets;
bf.read(numBuckets, 0);
hash<string>str_hash; //built-in hash function return a hash value
int index = 8 + str_hash(key) % numBuckets * 4; //index of the buckets starting at 8
//read the head of the linked list
BinaryFile::Offset head;
bf.read(head, index);
BinaryFile::Offset node = head;
//for each node in the linked list
while (node != -2)
{
Node temp;
if (!bf.read(temp, node)) { //read the node
cout << "Error reading from file!\n";
break;
}
else {
if (strcmp(temp.key, key.c_str()) == 0) { //check if the key of the node match the target key
DiskMultiMap::Iterator it(node, this); //if yes, return iterator pointing to this node
return it;
}
}
node = temp.next; //move to next node
}
//if not found the node with target key, return empty iterator in invalid state
DiskMultiMap::Iterator it;
return it;
}
int DiskMultiMap::erase(const std::string& key, const std::string& value, const std::string& context) {
//return 0 if the user tries to insert any key, value or context field with more than 120 or more characters
if (key.size() > MAX_DATA_LENGTH || value.size() > MAX_DATA_LENGTH || context.size() > MAX_DATA_LENGTH) {
return 0;
}
int numErase = 0;
//create the bucket index for the key
int numBuckets;
bf.read(numBuckets, 0);
hash<string>str_hash; //built-in hash function return a hash value
int index = 8 + str_hash(key) % numBuckets * 4; //index of the buckets starting at 8
BinaryFile::Offset prev = index; //save the node offset of previous node, initially bucket position
BinaryFile::Offset node;
bf.read(node, index); //save the node offset of current node, initially the first node
while (node != -2) //if not the last node
{
Node temp;
bf.read(temp, node); //read the content of current node
BinaryFile::Offset nextNodeLoc = temp.next; //the location of next node
//if the value and the context of the current node match
if (strcmp(temp.key, key.c_str()) == 0 && strcmp(temp.value, value.c_str()) == 0 && strcmp(temp.context, context.c_str()) == 0) {
bf.write(temp.next, prev); //previous node point to next node
//update removed nodes list
BinaryFile::Offset empty_head; //the head of the empty nodes list
bf.read(empty_head, 4); //read the current head of the empty node list
temp.next = empty_head; //connect current removed node with previous removed node
bf.write(temp, node); //update the new temp indisk
empty_head = node; //put current removed node to the front of removed-node list
bf.write(empty_head, 4); //update new empty head
numErase++;
}
//if not match, change previous node to current node
else {
prev = node; //prev = the location of "next" member variable in current node
}
node = nextNodeLoc; //advance to next node
}
return numErase;
}
void DiskMultiMap::printAll() {
/*
int a;
char b[121], c[121], d[121];
char e[1];
bf.read(a, 776);
bf.read(b, 121, 412);
bf.read(c, 121, 533);
bf.read(d, 122, 654);
bf.read(e, 1, 775);
cout << a << " " << b << " " << c <<" "<<d<<" "<<e<< endl;*/
int numBuckets;
bf.read(numBuckets, 0);
BinaryFile::Offset loc = 8;
for (int i = 0; i < numBuckets; i++) {
BinaryFile::Offset head;
bf.read(head, loc);
BinaryFile::Offset node = head;
while (node != -2)
{
Node temp;
if (!bf.read(temp, node)) {
cout << "Error reading from node"<<node<<endl;
return;
}
else {
cout << node << " ";
printf(temp.key);
std::cout << " ";
printf(temp.value);
std::cout << " ";
printf(temp.context);
std::cout << " ";
cout << temp.next << endl;
node = temp.next;
}
}
loc = loc + 4;
}
}
////////////////////////////////////////////////////////
//create iterator in an invalid state
DiskMultiMap::Iterator::Iterator(): state(false), target(0), parent(nullptr) {}
DiskMultiMap::Iterator::Iterator(BinaryFile::Offset n, DiskMultiMap* d): state(true), target(n), parent(d) {}
bool DiskMultiMap::Iterator::isValid() const {
return state;
}
DiskMultiMap::Iterator& DiskMultiMap::Iterator::operator++() {
//do nothing if the iterator called is invalid
if (!isValid())
return *this;
Node currNode;
Node nextNode;
parent->bf.read(currNode, target); //get the current node
BinaryFile::Offset node = currNode.next;
//for each node in the linked list
while (node != -2) {
parent->bf.read(nextNode, node); //read next node
if (strcmp(nextNode.key, currNode.key) == 0) { //if next node has the same key as current node
target = node; //change current iterator to point to next node
return *this;
}
node = nextNode.next;
}
//if none of the rest nodes in the same bucket has the same key
state = false; //set state to be invalid
return *this;
}
MultiMapTuple DiskMultiMap::Iterator::operator*() {
MultiMapTuple m;
Node temp;
parent->bf.read(temp, target); //read current node
//copy data to MultiMapTuple object
m.key = temp.key;
m.value = temp.value;
m.context = temp.context;
return m;
} | true |
f35fa1b348c347dd61535e99aa22474c97e69373 | C++ | OSLL/ground-truth-builder | /hedge_pos_publisher/src/pos_publisher.cpp | UTF-8 | 1,678 | 2.640625 | 3 | [] | no_license | #include <ros/ros.h>
#include <hedge_pos_publisher/hedge_pos.h>
extern "C" {
#include "hedge_pos_publisher/hedgehog_proxy.h"
}
using hedge_pos_publisher::hedge_pos; // hedge position message
bool terminateProgram = false;
void CtrlHandler(int signum)
{
terminateProgram=true;
}
hedge_pos get_hedge_pos(HedgehogProxy& hedge_proxy) {
hedge_pos res;
while((!terminateProgram) && (!hedge_proxy.terminationRequired())) {
PositionValue pos = hedge_proxy.get_position();
if (pos.ready) {
res.address = pos.address;
res.timestamp = pos.timestamp;
res.x = pos.x / 1000.;
res.y = pos.y / 1000.;
res.z = pos.z / 1000.;
break;
}
}
return res;
}
int main(int argc, char** argv)
{
signal (SIGINT, CtrlHandler);
signal (SIGQUIT, CtrlHandler);
ros::init(argc, argv, "pos_publisher");
ros::NodeHandle main_node;
HedgehogProxy hedge_proxy;
std::string default_topic = "/beacons";
double rate = 10.0; // atof(argv[0]);
ros::Rate loop_rate(rate);
ros::Publisher pos_publisher = main_node.advertise<hedge_pos>(default_topic, 1000);
while ((!terminateProgram) && (!hedge_proxy.terminationRequired()) && ros::ok())
{
if (!hedge_proxy.haveNewValues())
continue;
hedge_pos tmp = get_hedge_pos(hedge_proxy);
ROS_INFO("address: %d, timestamp: %d, [X=%.3f, Y= %.3f, Z=%.3f]",
(int) tmp.address,
(int) tmp.timestamp,
(float) tmp.x, (float) tmp.y, (float) tmp.z);
pos_publisher.publish(tmp);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| true |
7da63cf7272eae3b0439081df14185703dc52f87 | C++ | alaneos777/club | /codeforces/547C.cpp | UTF-8 | 1,175 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using lli = long long int;
const int MX = 5e5;
auto divsSieve(int n){
vector<vector<int>> divs(n);
for(int i = 1; i <= n; ++i){
for(int j = i; j <= n; j += i){
divs[j].push_back(i);
}
}
return divs;
}
auto muSieve(int n){
vector<int> mu(n+1, -1);
mu[0] = 0, mu[1] = 1;
for(int i = 2; i <= n; ++i){
if(mu[i]){
for(int j = 2*i; j <= n; j += i){
mu[j] -= mu[i];
}
}
}
return mu;
}
const auto mu = muSieve(MX);
const auto divs = divsSieve(MX);
lli comb(lli r){
return r * (r - 1) / 2;
}
int main(){
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, q;
cin >> n >> q;
vector<int> a(n);
for(int & ai : a){
cin >> ai;
}
vector<int> cnt(MX+1);
vector<bool> shelf(n);
lli ans = 0;
for(int i = 0; i < q; ++i){
int x;
cin >> x;
--x;
int ai = a[x];
if(shelf[x]){
shelf[x] = 0;
for(int d : divs[ai]){
ans -= mu[d] * comb(cnt[d]);
cnt[d]--;
ans += mu[d] * comb(cnt[d]);
}
}else{
shelf[x] = 1;
for(int d : divs[ai]){
ans -= mu[d] * comb(cnt[d]);
cnt[d]++;
ans += mu[d] * comb(cnt[d]);
}
}
cout << ans << "\n";
}
return 0;
} | true |
cae78d05019dd9ca63f49c6b5be03de0a51d7418 | C++ | radovan-wagner/Filip_DateTime | /DateTime_Lib/Test.cpp | UTF-8 | 1,334 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include "DateTime_Lib.h"
int main()
{
DateTime d0("13.10.1998 03:02:01", ".", " ", ":");
d0.show();
DateTime d1(10, 9, 2020, 23, 22, 23);
d1.show();
// DateTime d2(10, 9, 2020, 23, 22, 23);
DateTime d2(11, 11, 2019, 22, 23, 22);
d2.show();
system("pause");
system("cls");
if (d1 > d2) // >, <, == funguju
{
std::cout << d1 << " is later than " << d2 << std::endl;
}
else if (d1 < d2) {
std::cout << d1 << " is sooner than " << d2 << std::endl;
}
else if (d1 == d2)
{
std::cout << "They are same." << std::endl;
}
else
{
std::cout << "Error." << std::endl;
return -1;
}
system("pause");
system("cls");
d1.show();
d2.show();
std::cout << "\n";
std::cout << "Test +n: " << d2 + 40 << std::endl; //+n funguje
std::cout << "Test -n: " << d1 - 30 << std::endl; //-n funguje
std::cout << "Test d1 - d2: " << d1 - d2 << std::endl; // Pridal som -n funguje
std::cout << "Test --: " << --d1 << std::endl; //-- funguje
std::cout << "Test ++: " << ++d2 << std::endl; //++ funguje
std::cout << "Test []: " << d1[0] << std::endl; //[] funguje
std::cout << "Difference between 2 days (in sec), d1 - d2 (d1 > d2): " << d1 - d2 << std::endl;
system("pause");
return 0;
}
| true |
6d1aa9dc89eb2c1e2b1026ecb686f294b73e31b5 | C++ | Alaxe/noi2-ranking | /2019/solutions/E/AVD-Plovdiv/odd.cpp | UTF-8 | 387 | 2.515625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
int a,b,i,k,br=0,br2=0,br3=0;
cin>>a>>b;
for(i=a;i<=b;i++)
{
for(k=1;k<=i/2;k++)
{
br++;
}
br2=br;
if(br2%2!=0)
{
br3++;
}
}
cout<<br3<<endl;
return 0;
}
| true |
f84a708700afcc45393962e7b81a7925d41a2eb7 | C++ | RubisetCie/mario-constructor-master | /Headers/Core/placeable.hpp | UTF-8 | 683 | 2.5625 | 3 | [] | no_license | /* Creator : Matthieu (Rubisetcie) Carteron
Language: C++
*/
#ifndef PLACEABLE_INCLUDED
#define PLACEABLE_INCLUDED
#include <SFML/Graphics.hpp>
enum ID {ID_USELESS, ID_PLAYER, ID_CHECKPOINT, ID_INVISIBLE, ID_ENEMY, ID_WONTFALL, ID_SHELL, ID_STOMPABLE};
class Placeable : public sf::Drawable
{
public :
Placeable();
virtual void setPosition(const sf::Vector2f& pos) = 0;
virtual void update() = 0;
virtual void secureUpdate() = 0;
virtual void afterUpdate() = 0;
virtual sf::Vector2f getPosition() const = 0;
virtual sf::Vector2f getSize() const = 0;
virtual ID getID() const = 0;
bool m_destroyed;
};
#endif
| true |
d5ba0b5e64da9df1a8b7ee4af9e9b5f3dfd6aa8e | C++ | MdAman02/problem_solving | /search/ternary_search/codeforces/F1355E/Solution.cpp | UTF-8 | 2,639 | 2.984375 | 3 | [
"MIT"
] | permissive | // problem name: Restorer Distance
// problem link: https://codeforces.com/contest/1355/problem/E
// contest link: https://codeforces.com/contest/1355
// time: (?)
// author: reyad
// other_tags: binary search, greedy, math, sorting
// difficulty_level: medium
// note: this problem can also be solved using binary_search
// to see solution for binary_search see search/binary_search/codeforces/F1355E/Solution.cpp
// solution idea:
// the cost curve would be somewhat like below:
// . .
// . .
// . .
// . .
// . .
// so we just have to find the height of lowest cost point
#include <bits/stdc++.h>
using namespace std;
#define N 100010
const long long inf = (long long)1e18;
int h[N];
int n, a, r, m;
long long calc(long long lev) {
long long put = 0;
long long remove = 0;
for(int i=0; i<n; i++) {
if(h[i] <= lev) {
put = put + lev - h[i];
} else {
remove = remove + h[i] - lev;
}
}
// now, some elements to put, some to remove and some to move
// the num of elements can be removed is cnt = min(put, remove) and
// cnt element should be moved only when move cost(m) < put cost(a) + remove cost(r)
// and other remaining should be removed or put just normally
// so,
long long cnt = min(put, remove);
put -= cnt;
remove -= cnt;
return put * a + remove * r + cnt * min(a + r, m);
}
int main() {
scanf("%d %d %d %d", &n, &a, &r, &m);
for(int i=0; i<n; i++) {
scanf("%d", &h[i]);
}
long long minCost = inf;
int s = 0, e = (int)1e9; // height range 0...1e9
// note: e - s > 1 condition is a must
// cause if e = s + 1
// then __m1 = s + s + e = s + s + s + 1 = 3*s + 1
// and __m2 = s + e + e = s + (s+1) + (s+1) = 3*s + 2
// so, __m2 = __m1 + 1
// and it is then possible m1 = (__m1 / 3) = s
// and m2 = (__m2 / 3) = s
// i.e. m1 == m2
// which is something we do not want and it would totally ignore value e
// and would provide us wrong result
while(e - s > 1) {
long long m1 = (0LL + s + s + e) / 3;
long long m2 = (0LL + s + e + e) / 3;
if(calc(m1) > calc(m2)) {
/**
* m1 provides much more than
* so, we should pull down the m1 until
* it equals or provides
* less value than m2
*/
s = m1 + 1; // we should add 1 to avoid infinite loop
// and also +1 is totally okay
// cause calc(m1) > calc(m2) i.e. m1 can never the answer while m2 is present
} else {
// its the reverse of situation of previous situation
e = m2;
}
}
printf("%lld\n", min(calc(s), calc(e)));
return 0;
} | true |
3e527944deb5ead114887d28371ef85db3b91095 | C++ | leohfigueiredo/Arduino | /TESTE_SENSOR_HC/TESTE_SENSOR_HC.ino | UTF-8 | 1,168 | 2.75 | 3 | [] | no_license | /*
* created by Rui Santos,
http://randomnerdtutorials.com
*
* Complete Guide for Ultrasonic Sensor
HC
-
SR04
*
Ultrasonic sensor Pins:
VCC: +5VDC
Trig : Trigger (INPUT)
-
Pin11
Echo: Echo (OUTPUT)
-
Pin 12
GND: GND
*/
int trigPin = 8; //Trig - green Jumper
int echoPin = 9; //Echo - yellow Jumper
long duration, cm,inches;
void setup()
{
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
}
void loop()
{
// The sensor is triggered by a HIGH pulse of 10 or more
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin,LOW);
delayMicroseconds(5);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin,INPUT);
duration =pulseIn(echoPin,HIGH);
// convert the time into a distance
cm =(duration/2)/29.1;
inches =(duration/2)/74;
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(250);
}
| true |
ab06e40d3817694da5e5de7aa717bb71354a5d66 | C++ | Alex-Nabu/ftp | /src/auth.cpp | UTF-8 | 758 | 3.03125 | 3 | [] | no_license | #include "../includes/auth.h"
auth::auth()
{
cur_user_index = -1;
ifstream fin("auth");
userInfo user;
while(fin >> user.username >> user.password >> user.directory)
{
users.push_back(user);
}
}
bool auth::login(string name, string passwd)
{
if(name == "anonymous")
{
cur_user_index = 0;
return true;
}
for(vector<userInfo>::iterator it = users.begin(); it != users.end(); it++)
{
if(it->username == name && it->password == passwd)
{
cur_user_index = it - users.begin();
return true;
}
}
cur_user_index = -1;
return false;
}
auth::userInfo auth::getCurUser()
{
if(cur_user_index == -1) throw string("Invalid user!");
else return users[cur_user_index];
}
bool auth::isLoggedin()
{
return cur_user_index != -1;
}
| true |
f608c63f8be5f7d6a7b00257f605e1ea71e2ec7c | C++ | DeepCoreSystem/Nextion-LCD-library | /src/drawing.cpp | UTF-8 | 8,508 | 2.9375 | 3 | [] | no_license | /* drawing.cpp
*
* Arduino platform library for Itead Nextion displays
* Instruction set : https://nextion.tech/instruction-set/
*
* Library implements almost of the basic and ehnached display function
* but none (yet) of the professional ones.
*
* Please read nxt_lcd.h for some more info
*
* (c) Guarguaglini Alessandro - ilguargua@gmail.com
*
* This file include the following class methods:
*
* Public:
* - writeStr()
* - drawArea()
* - drawLine()
* - drawCircle()
* - addWavePoint()
* - addWaveBytes()
* - waveUpdtEn()
*
*/
#include <Arduino.h>
#include "nxt_lcd.h"
/*
* writeStr() - write string to display.
* "msg" is the string to be displayed (can reside in program memory using the F() macro), "x" and "y" are
* coordinate of upper left corner, "w" and "h" the width and heigth of msg box, "font" is the ID of one
* of the (preloaded) font, "fCol" and "Bcol" are foreground and background color, "Xcen" is the horizontal
* centering (0-left,1-center,2-right), "Ycen" is vertical centering (0-up,1-center,2-down). You can omit the
* last 5 parameters, see nxt_lcd.h for defaults. strlen(msg) + 42 <= NXT_BUF_SIZE, or an error is returned.
*/
uint8_t NxtLcd::writeStr(const char* msg, uint16_t x,uint16_t y,uint16_t w,
uint16_t h,uint8_t font,uint16_t fCol,
uint16_t bCol, uint8_t xCen, uint8_t yCen)
{
if(initialized == 0) return notInit;
if(strlen(msg) + 42 > NXT_BUF_SIZE) return dataTooBig;
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("xstr %u,%u,%u,%u,%u,%u,%u,%u,%u,1,\"%s\"%c%c%c"),x,y,w,h,
font,fCol,bCol,xCen,yCen,msg,NXT_MSG_END);
#else
snprintf((char *)sendBuf,NXT_BUF_SIZE,"xstr %u,%u,%u,%u,%u,%u,%u,%u,%u,1,\"%s\"%c%c%c",x,y,w,h,
font,fCol,bCol,xCen,yCen,msg,NXT_MSG_END);
#endif
//serialLogInt("xstr sendBuf len",strlen((char *)sendBuf));
return writeBuf();
}
/*
* drawArea() - draw a rectangle to display.
* "x" and "y" are coordinate of upper left corner, "w" and "h" the width and heigth of the box. "filled" specify
* if the area will be filled (1) or empty (0). "color" is the color used to fill/draw area (RGB 565)
*/
uint8_t NxtLcd::drawArea(uint16_t x, uint16_t y, uint16_t w, uint16_t h,uint16_t color, uint8_t filled){
if(initialized == 0) return notInit;
char cmd[5];
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
if(filled > 0) strncpy_P(cmd,PSTR("fill"),5);
else{
strncpy_P(cmd,PSTR("draw"),5);
w += x;
h += y;
}
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("%s %u,%u,%u,%u,%u%c%c%c"),cmd,x,y,w,h,color,NXT_MSG_END);
#else
if(filled > 0) strncpy(cmd,"fill",5);
else{
strncpy(cmd,"draw",5);
w += x;
h += y;
}
snprintf((char *)sendBuf,NXT_BUF_SIZE,"%s %u,%u,%u,%u,%u%c%c%c",cmd,x,y,w,h,color,NXT_MSG_END);
#endif
return writeBuf();
}
/*
* drawLine() - draw a line from coordinate "x","y" to coordinate "x1","y1", using "color" as ink
*/
uint8_t NxtLcd::drawLine(uint16_t x, uint16_t y, uint16_t x1, uint16_t y1,uint16_t color){
if(initialized == 0) return notInit;
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("line %u,%u,%u,%u,%u%c%c%c"),x,y,x1,y1,color,NXT_MSG_END);
#else
snprintf((char *)sendBuf,NXT_BUF_SIZE,"line %u,%u,%u,%u,%u%c%c%c",x,y,x1,y1,color,NXT_MSG_END);
#endif
return writeBuf();
}
/*
* drawCircle() - draw a circle with center at coordinate "x","y" having radius "r" and using "color"
* as ink. filled used as in drawArea()
*
*/
uint8_t NxtLcd::drawCircle(uint16_t x, uint16_t y, uint16_t r, uint16_t color, uint8_t filled){
if(initialized == 0) return notInit;
char cmd[5];
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
if(filled > 0) strncpy_P(cmd,PSTR("cirs"),5);
else strncpy_P(cmd,PSTR("cir"),4);
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("%s %u,%u,%u,%u%c%c%c"),cmd,x,y,r,color,NXT_MSG_END);
#else
if(filled > 0) strncpy(cmd,"cirs",5);
else strncpy(cmd,"cir",4);
snprintf((char *)sendBuf,NXT_BUF_SIZE,"%s %u,%u,%u,%u%c%c%c",cmd,x,y,r,color,NXT_MSG_END);
#endif
return writeBuf();
}
/*
* addWavePoint() - add a single point to the wave object "waveId" at channel "ch".
* wave object can have up to 4 channels, see 'ch' property in Nextion editor (can't be changed at runtime).
* "value" limit is 0 to 255, or 0 to wave object heigth, if you want to see the whole trace.
*/
uint8_t NxtLcd::addWavePoint(uint8_t waveId,uint8_t ch, uint8_t value){
if(initialized == 0) return notInit;
if(ch > 3) return invalidData;
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("add %u,%u,%u%c%c%c"),waveId,ch,value,NXT_MSG_END);
#else
snprintf((char *)sendBuf,NXT_BUF_SIZE,"add %u,%u,%u%c%c%c",waveId,ch,value,NXT_MSG_END);
#endif
return writeBuf();
}
/*
* addWaveBytes() - add "len" bytes to wave object channel at once. In this case len can exceed the
* NXT_BUF_SIZE limit, if so the transmission of data will be splitted in chunks that fits
* into the buffer.
*/
uint8_t NxtLcd::addWaveBytes(uint8_t waveId,uint8_t ch, uint8_t* bytes, uint16_t len){
if(initialized == 0) return notInit;
if(ch > 3) return invalidData;
uint8_t res = replyCmdFail;
uint16_t chkSize = len;
//uint8_t iter = (len / NXT_BUF_SIZE) + 1;//1;
uint8_t cnt = 0;
while(len > 0){
bufReset(sendBuf);
if(cnt > 0) delay(20); //after 1° run we need a little delay
chkSize = (len > NXT_BUF_SIZE) ? NXT_BUF_SIZE : len;
#ifdef ARDUINO_ARCH_AVR
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("addt %u,%u,%u%c%c%c"),waveId,ch,chkSize,NXT_MSG_END);
#else
snprintf((char *)sendBuf,NXT_BUF_SIZE,"addt %u,%u,%u%c%c%c",waveId,ch,chkSize,NXT_MSG_END);
#endif
//serialLogStr("addWaveBytes sendBuf",sendBuf);
//This seems critical for the timing
res = writeBuf(replyTDReady,100);
if(res != replyCmdOk){
//serialLogInt("addWaveBytes res",res);
//serialLogInt("addWaveBytes iter",iter);
//serialLogInt("addWaveBytes cnt",cnt);
//serialLogInt("addWaveBytes len",len);
//serialLogInt("addWaveBytes chkSize",chkSize);
return res;
}
bufReset(sendBuf);
memcpy(sendBuf,&bytes[cnt],chkSize);
res = writeBuf(replyTDEnd,20,chkSize);
if(res != replyCmdOk) return res;
cnt += chkSize;
len -= chkSize;
//iter--;
}
return replyCmdOk;
}
/*
* clearWaveCh() - clear data of channel "ch" in "waveId"
*/
uint8_t NxtLcd::clearWaveCh(uint8_t waveId, uint8_t ch){
if(initialized == 0) return notInit;
if(ch > 3 && ch != 255) return invalidData;
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("cle %u,%u%c%c%c"),waveId,ch,NXT_MSG_END);
#else
snprintf((char *)sendBuf,NXT_BUF_SIZE,"cle %u,%u%c%c%c",waveId,ch,NXT_MSG_END);
#endif
return writeBuf();
}
/*
* waveUpdtEn() - enable (en=1) or disable(en=0) the screen updating of the wave objects on current
* page
*/
uint8_t NxtLcd::waveUpdtEn(uint8_t en){
if(initialized == 0) return notInit;
if(en > 1 ) return invalidData;
char cmd[9];
bufReset(sendBuf);
#ifdef ARDUINO_ARCH_AVR
if(en == 1) strncpy_P(cmd,PSTR("ref_star"),9);
else strncpy_P(cmd,PSTR("ref_stop"),9);
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("%s%c%c%c"),cmd,NXT_MSG_END);
#else
if(en == 1) strncpy(cmd,"ref_star",9);
else strncpy(cmd,"ref_stop",9);
snprintf((char *)sendBuf,NXT_BUF_SIZE,"%s%c%c%c",cmd,NXT_MSG_END);
#endif
return writeBuf();
}
#ifdef ARDUINO_ARCH_AVR
uint8_t NxtLcd::writeStr(const __FlashStringHelper* msg, uint16_t x,uint16_t y,uint16_t w,
uint16_t h,uint8_t font,uint16_t fCol,
uint16_t bCol, uint8_t xCen, uint8_t yCen)
{
if(initialized == 0) return notInit;
if(strlen_P((char *)msg) + 42 > NXT_BUF_SIZE) return dataTooBig;
bufReset(sendBuf);
snprintf_P((char *)sendBuf,NXT_BUF_SIZE,PSTR("xstr %u,%u,%u,%u,%u,%u,%u,%u,%u,1,\"%S\"%c%c%c"),x,y,w,h,
font,fCol,bCol,xCen,yCen,msg,NXT_MSG_END);
//serialLogInt("xstr pgm, msg len",strlen_P((char *)msg));
return writeBuf();
}
#endif
| true |
3611d0f6bc68edeb2ec97c67fc6e5d832ab6f82c | C++ | Tha-Davong/CS205Project-MatixLibrary | /Project/templateUtil.h | UTF-8 | 672 | 2.734375 | 3 | [] | no_license | //
// Created by Vithlaithla Long on 7/6/21.
//
#ifndef CS205PROJECT_TEMPLATEUTIL_H
#define CS205PROJECT_TEMPLATEUTIL_H
#include <type_traits>
#include <complex>
#define IF(...) typename std::enable_if< (__VA_ARGS__), bool >::type = true
template< class T, class U >
constexpr bool is_same_t = std::is_same<T, U>::value;
template<typename T>
struct is_complex_t : public std::false_type {};
template<typename T>
struct is_complex_t<std::complex<T>> : public std::true_type {};
template<typename T>
constexpr bool is_complex = is_complex_t<T>::value;
template<typename T >
constexpr bool is_arithmetic_t = std::is_arithmetic<T>::value;
#endif //CS205PROJECT_TEMPLATEUTIL_H | true |
a4761cbbab649dd28cc03cc541db5570589765f0 | C++ | paniwani/ImageProcessing | /ImageArray/src/ImageArray.cxx | UTF-8 | 1,326 | 2.75 | 3 | [] | no_license | #include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include <iostream>
typedef itk::Image< int, 3 > ImageType;
void WriteITK(ImageType::Pointer image, std::string name) {
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
WriterType::SetGlobalWarningDisplay(false);
writer->SetFileName(name.c_str());
writer->SetInput(image);
std::cout<<"Writing: "<<name<<std::endl;
writer->Update();
}
int main()
{
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
ImageType::IndexType start;
ImageType::SizeType size;
start[0] = start[1] = start[2] = 0;
size[0] = size[1] = size[2] = 200;
region.SetSize( size );
region.SetIndex( start );
image->SetRegions( region );
image->Allocate();
image->FillBuffer(0);
int * ptr = image->GetBufferPointer();
ptr[40000] = 1;
//ImageType::PixelContainerPointer imageArray = image->GetPixelContainer();
//*imageArray[250] = 1;
/*
typedef itk::ImageRegionIterator<ImageType> IteratorType;
IteratorType it(image,image->GetLargestPossibleRegion());
it.GoToBegin();
int count=0;
for (int i=0; i<400; i++)
{
++it;
std::cout << count++ << std::endl;DAV
}
it.Set(1);
*/
WriteITK(image,"foo.hdr");
//system("pause");
return 0;
}
| true |
35604d618a2875a4097fd03b783774eec270f637 | C++ | Anshuman-UCSB/Advent-of-code-2020 | /Day 16/main.cpp | UTF-8 | 5,243 | 3 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <fstream>
#include <vector>
#include <sstream>
#include <utility>
using namespace std;
void p1();
void p2();
struct Rule{
string name;
vector<pair<int, int>> ranges;
Rule(){};
Rule(vector<pair<int, int>> range, string n):ranges(range), name(n){}
};
vector<int> readTicket(string inp){
stringstream ss(inp);
int temp;
char c;
ss>>temp;
vector<int> out = {temp};
while(ss>>c>>temp){
out.push_back(temp);
}
return out;
}
vector<vector<int>> inputTickets(){
fstream file("input");
string line;
vector<vector<int>> out;
while(getline(file, line)){
if(line.back() == '\r')
line.pop_back();
line.push_back(',');
out.emplace_back();
stringstream ss(line);
int temp;
char c;
while(ss>>temp>>c){
out.back().push_back(temp);
}
}
return out;
}
vector<Rule> rules(){
vector<Rule> out;
out.emplace_back(vector<pair<int, int>>{make_pair(40,261), make_pair(279,955)}, "departure location");
out.emplace_back(vector<pair<int, int>>{make_pair(33,375), make_pair(394,963)}, "departure station");
out.emplace_back(vector<pair<int, int>>{make_pair(39,863), make_pair(877,970)}, "departure platform");
out.emplace_back(vector<pair<int, int>>{make_pair(30,237), make_pair(256,955)}, "departure track");
out.emplace_back(vector<pair<int, int>>{make_pair(47,731), make_pair(741,950)}, "departure date");
out.emplace_back(vector<pair<int, int>>{make_pair(38,301), make_pair(317,954)}, "departure time");
out.emplace_back(vector<pair<int, int>>{make_pair(26,598), make_pair(623,969)}, "arrival location");
out.emplace_back(vector<pair<int, int>>{make_pair(50,835), make_pair(854,971)}, "arrival station");
out.emplace_back(vector<pair<int, int>>{make_pair(44,535), make_pair(549,958)}, "arrival platform");
out.emplace_back(vector<pair<int, int>>{make_pair(36,672), make_pair(685,967)}, "arrival track");
out.emplace_back(vector<pair<int, int>>{make_pair(34,217), make_pair(236,974)}, "class");
out.emplace_back(vector<pair<int, int>>{make_pair(29,469), make_pair(483,970)}, "duration");
out.emplace_back(vector<pair<int, int>>{make_pair(45,111), make_pair(120,965)}, "price");
out.emplace_back(vector<pair<int, int>>{make_pair(32,751), make_pair(760,954)}, "route");
out.emplace_back(vector<pair<int, int>>{make_pair(25,321), make_pair(339,954)}, "row");
out.emplace_back(vector<pair<int, int>>{make_pair(38,423), make_pair(438,958)}, "seat");
out.emplace_back(vector<pair<int, int>>{make_pair(45,798), make_pair(813,954)}, "train");
out.emplace_back(vector<pair<int, int>>{make_pair(40,487), make_pair(503,954)}, "type");
out.emplace_back(vector<pair<int, int>>{make_pair(46,916), make_pair(938,949)}, "wagon");
out.emplace_back(vector<pair<int, int>>{make_pair(25,160), make_pair(184,957)}, "zone");
return out;
}
int p1Invalid(vector<Rule>& rules, vector<int>& ticket){
for(int num:ticket){
for(Rule r: rules){
for(auto p: r.ranges){
if(p.first<=num && num <=p.second){
goto next;
}
}
}
return num;
next:;
}
return 0;
}
bool satisfiesRule(int num, vector<pair<int, int>>& range){
for(auto& p: range){
if(p.first<=num && num<=p.second){
return true;
}
}
return false;
}
int main(){
vector<Rule> rs(rules());
vector<int> ticket = {73,59,83,127,137,151,71,139,67,53,89,79,61,109,131,103,149,97,107,101};
vector<vector<int>> otherTickets(inputTickets());
int p1= 0;
for(auto v: otherTickets){
p1+=(p1Invalid(rs, v));
}
cout<<"Part 1: "<<p1<<endl;
for(int i =0;i<otherTickets.size();i++){
if(p1Invalid(rs,otherTickets[i])){ //invalid ticket
otherTickets.erase(otherTickets.begin()+i--);
}
}
"By now, otherTickets is only valids.";
vector<string> possibleTemplate;
for(auto r: rs){
possibleTemplate.push_back(r.name);
}
vector<vector<string>> possibles;
for(int k = 0;k<20;k++){
possibles.emplace_back(vector<string>(possibleTemplate));
}
for(auto& v: possibles){
cout<<"[";
string delim = "";
for(auto& r: v){
cout<<delim<<r;
delim = ", ";
}cout<<"]"<<endl;
}
map<string, vector<pair<int, int>>> rm;
for(auto r: rs){
rm[r.name] = r.ranges;
}
for(auto valid: otherTickets){
for(int i = 0;i<20;i++){
for(int j = 0;j<possibles.size();j++){
cout<<j<<endl;
string ruleName = possibles[i][j];
if(!satisfiesRule(valid[i],rm[ruleName])){
cout<<valid[i]<<" Doesn't satisfy "<<ruleName<<endl;
cout<<possibles[i].size()<<endl;
possibles[i].erase(possibles[i].begin()+j++);
}
}
}
}
} | true |
9e0008cf7dc9c344e0eb2106743170e71f30a91e | C++ | Jthompson715/github.io | /Data Structures/Lab 8b Queue/Thompson_Jeremy_Lab8b_QueueDriver.cpp | UTF-8 | 3,812 | 3.75 | 4 | [] | no_license | // QueueDriver.cpp : Defines the entry point for the console application.
//"Lab 8b, The \"QueueDriver.cpp\" Program \n";
//"Programmer: JEREMY THOMPSON\n";
//"Editor(s) used: JNotePad\n";
//"Compiler(s) used: VC++ 2013\n";
#include <iostream>
#include "Thompson_Jeremy_Lab8b_Queue.h"
#include "Thompson_Jeremy_Lab8b_Queue.h" //ifndef test
using namespace std;
int main()
{
// print my name and this assignment's title
cout << "Lab 8b, The \"QueueDriver.cpp\" Program \n";
cout << "Programmer: JEREMY THOMPSON\n";
cout << "Editor(s) used: JNotePad\n";
cout << "Compiler(s) used: VC++ 2013\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl;
// create the queue
Queue <int> myQueue;
for (int i = 0; i < 12; i++)
{
myQueue.push(i);
}
int queuePeek;
int queueCopy;
int queuePop;
// display queue contents
cout << "The queue currently contains the following elements: " << endl;
for (Queue<int> copy = myQueue; !copy.isEmpty(); copy.pop(queueCopy))
{
copy.peek(queuePeek);
cout << queuePeek << " ";
}
if (myQueue.isEmpty() == true)
cout << "\nThe isEmpty function IS NOT working as the queue is NOT empty." << endl;
else
cout << "\nThe isEmpty function IS working properly as the queue is NOT empty." << endl;
if (myQueue.pop(queuePop) == true)
cout << "The pop function IS working as there ARE elements in the queue." << endl;
else
cout << "The pop function IS NOT working as there ARE elements in the queue to pop." << endl;
if (myQueue.peek(queuePeek) == true)
{
cout << "Expected 'peek' output is 1." << endl;
cout << "Actual 'peek' output is: " << queuePeek << endl;
}
myQueue.makeEmpty();
if (myQueue.isEmpty() == true)
cout << "The makeEmpty function IS working as the queue is now empty." << endl;
else
cout << "The makeEmpty function IS NOT working as the queue is now empty." << endl;
{
Queue <int> myQueue1;
for (int i = 0; i < 12; i++)
{
myQueue.push(i);
}
// object testing with assignment UPON declaration
const Queue<int> copy = myQueue;
cout << "\nObject copy test with assignment UPON declaration";
if (copy.isEmpty() == true)
cout << "\nThe isEmpty function IS NOT working as there are elements in the queue." << endl;
else
cout << "\nThe isEmpty function IS working as there are elements in the queue." << endl;
int queuePeek;
if (copy.peek(queuePeek) == true)
{
cout << "Expected 'peek' output is 0." << endl;
cout << "Actual 'peek' output is: " << queuePeek << endl;
}
}
// object testing with assignment AFTER declaration
{
Queue <int> myQueue1;
for (int i = 0; i < 12; i++)
{
myQueue.push(i);
}
Queue<int> copy = myQueue;
cout << "\nObject copy test with assignment AFTER declaration";
if (copy.isEmpty() == true)
cout << "\nThe isEmpty function IS NOT working as elements are in the queue." << endl;
else
cout << "\nThe isEmpty function IS working as there are elements in the queue." << endl;
int queuePop;
if (copy.pop(queuePop) == true)
cout << "The pop function IS working as there are elements to pop." << endl;
else
cout << "The pop function IS NOT working as there are elements to pop." << endl;
if (copy.peek(queuePop) == true)
{
cout << "Expected 'peek' output is 1." << endl;
cout << "Actual 'peek' output is: " << queuePeek << endl;
}
copy.makeEmpty();
if (copy.isEmpty() == true)
cout << "The makeEmpty function IS working as the queue is now empty." << endl;
else
cout << "The makeEmpty function IS NOT working as the queue is now empty." << endl;
}
cout << "\nPress ENTER to continue...";
cin.get();
} | true |
5ad74abf25578f4cae301423c18f3de5a41e5453 | C++ | CleverWang/VisualStudioProjects | /DesignPatterns/Flyweight/ShapeFactory.cpp | UTF-8 | 444 | 3.421875 | 3 | [] | no_license | #include "ShapeFactory.h"
#include <iostream>
std::unordered_map<std::string, Shape*> ShapeFactory::circleMap;
Shape * ShapeFactory::getCircle(const std::string & color)
{
auto iter = circleMap.find(color);
if (iter == circleMap.end())
{
Circle *circle = new Circle(color);
circleMap.insert({ color, circle });
std::cout << "Creating circle of color : " + color << std::endl;
return circle;
}
else
{
return iter->second;
}
}
| true |
d68d232b274cf86f90aed22e08be95d6e9b9f0ba | C++ | RobertKraaijeveld/GrandeOmegaVisualization | /lib/DataProcesser/src/StatisticalAnalyzer/Point/IClusteringPoint.h | UTF-8 | 1,182 | 3.0625 | 3 | [] | no_license | #ifndef IClusteringPoint_H
#define IClusteringPoint_H
#include "../GenericVector/GenericVector.h"
#include <map>
#include <numeric>
#include <iostream>
class IClusteringPoint
{
public:
//const makes sures the getters dont modify the derived object, which is required for the operator overload
virtual GenericVector getVector() const = 0;
virtual int getClusterId() const = 0;
virtual void setVector(GenericVector newVector) = 0;
virtual void setClusterId(int newCentroidId) = 0;
//bit useless, but necessary to use this in a map
bool operator<(const IClusteringPoint &other) const
{
float myVectorSum = std::accumulate(getVector().values.begin(), getVector().values.end(), 0.0);
float otherVectorSum = std::accumulate(other.getVector().values.begin(), other.getVector().values.end(), 0.0);
return myVectorSum < otherVectorSum;
}
//done in order to make STL vector searching algorithms for this type work
bool operator==(const IClusteringPoint &other) const
{
if (getVector().values == other.getVector().values)
return true;
else
return false;
}
};
#endif
| true |
4be42df65cbe7d0c7d269218d985c852dd558a47 | C++ | ssmktr/Algorism_Study | /Algorism_Study/Step001/Question01/Question01.cpp | UTF-8 | 629 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
vector<int> solution(vector<int> heights)
{
vector<int> answer;
answer.resize(heights.size());
for (int j = 0; j < answer.size(); ++j)
{
int value = heights[j];
answer[j] = 0;
for (int i = j; i >= 0; --i)
{
if (value < heights[i])
{
value = heights[i];
answer[j] = i + 1;
break;
}
}
}
return answer;
}
int main()
{
vector<int> heights = { 6, 9, 5, 7, 4 };
vector<int> result = solution(heights);
for (int i = 0; i < result.size(); ++i)
cout << result[i] << ", ";
cout << endl << endl;
system("pause");
return 0;
}
| true |
776a694ee44751c835bf362af8e9abbe965cb00b | C++ | willytai/LogicRegression | /src/myUsage.cpp | UTF-8 | 699 | 3.140625 | 3 | [] | no_license | #include "myUsage.h"
void MyUsage::report(bool repTime, bool repMem) {
cout << endl;
if (repTime) {
setTimeUsage();
cout << "Period time used : " << setprecision(4)
<< _periodUsedTime << " seconds" << endl;
cout << "Total time used : " << setprecision(4)
<< _totalUsedTime << " seconds" << endl;
}
if (repMem) {
setMemUsage();
cout << "Total memory used: " << setprecision(4)
<< _currentMem << " M Bytes" << endl;
}
cout << endl;
}
double MyUsage::GetTimeUsage() {
setTimeUsage();
return _periodUsedTime;
}
double MyUsage::GetMemUsage() {
setMemUsage();
return _currentMem;
}
| true |
b17fae5491bb6ab1f61b68bc83dda5420028776e | C++ | kylechiu3201/CS-225-Final-Project | /test.cpp | UTF-8 | 11,330 | 3.125 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include "airport/airport.h"
#include "airports/airports.h"
#include "catch/catch.hpp"
#include "graph/edge.h"
#include "graph/graph.h"
using std::vector;
void printGraph(Airports airports) {
// Vertices are fine
std::cout << "Vertices: " << std::endl;
auto vertices = airports.getVertices();
auto edges = airports.getEdges();
for (auto v : vertices) /* std::cout << v.get_port_ID() << std::endl; */
std::cout << v.get_ICAO() << std::endl;
std::cout << std::endl << std::endl << std::endl;
for (auto e : edges)
std::cout << e.source.get_port_ID() << " to " << e.dest.get_port_ID()
<< std::endl;
}
bool check_dup(vector<int> vec) {
unordered_map<int, int> m;
for (auto ele : vec) {
m[ele]++;
if (m[ele] == 2) {
return true;
}
}
return false;
}
bool check_tol(double ans, double tol, double calc) {
return calc >= ans - tol && calc <= ans + tol;
}
bool bfs_test(vector<Vertex> path, vector<std::string> sol) {
REQUIRE(path.size() == sol.size());
for (unsigned x = 0; x < path.size(); x++) {
REQUIRE(path[x].get_name() == sol[x]);
}
return true;
}
bool bfs_comp(vector<vector<Vertex>> b, vector<vector<std::string>> sol) {
REQUIRE(b.size() == sol.size());
for (unsigned x = 0; x < b.size(); x++) {
REQUIRE(b[x].size() == sol[x].size());
for (unsigned y = 0; y < b[x].size(); y++) {
REQUIRE(b[x][y].get_name() == sol[x][y]);
}
}
return true;
}
TEST_CASE("Graph is created from small subset of data", "[weight=1][part=1]") {
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/testroutes.dat");
REQUIRE(airports.getVertices().size() == 11);
}
TEST_CASE("test lat/long distance calculation") {
Airport port1;
port1.set_lat(53.32055555555556);
port1.set_long(-1.7297222222222221);
Airport port2;
port2.set_lat(53.32055555555556);
port2.set_long(-1.7297222222222221);
REQUIRE(0 == Airport::get_distance(port1, port2, 'K'));
port1.set_lat(53.32055555555556);
port1.set_long(-1.7297222222222221);
port2.set_lat(53.31861111111111);
port2.set_long(-1.6997222222222223);
REQUIRE(2.004 == Airport::get_distance(port1, port2, 'K'));
}
TEST_CASE("Correct fields for vertices", "[weight=1][part=1]") {
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/testroutes.dat");
vector<Vertex> vec = airports.getVertices();
REQUIRE(vec.size() == 11);
vector<std::string> sol = {"ONE", "TWO", "THR", "FOU", "FIV", "SIX",
"SEV", "EIG", "NIN", "TEN", "ELE"};
vector<std::string> IATA;
for (int x = 0; x < (int)vec.size(); x++) {
IATA.push_back(vec[x].get_IATA());
}
REQUIRE(sol == IATA);
REQUIRE(airports.get_graph().edgeExists(vec[0], vec[1]));
double ans = 106.71;
double tol = 0.01;
// REQUIRE((airports.get_graph().getEdgeWeight(vec[0],vec[1]) >= ans-tol) &&
// (airports.get_graph().getEdgeWeight(vec[0],vec[1])<=ans+tol));
REQUIRE(
check_tol(ans, tol, airports.get_graph().getEdgeWeight(vec[0], vec[1])));
}
TEST_CASE("dijkstras- no path available") {
std::ofstream file("data/dtest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "UAL,1,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "SW,2,TWO,2,THR,3,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/dtest.dat");
airports.create_dijkstras("\"ONE\"");
vector<Vertex> path = airports.shortest_path("\"FOUR\"");
REQUIRE(path.size() == 1); // If path size is 1, then no path exists.
}
TEST_CASE("dijkstras - graph with forward/back edges") {
std::ofstream file("data/dtest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "UAL,1,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "UAL,1,TWO,1,ONEE,2,123,,0,jun" << std::endl;
file << "SW,2,TWO,2,THR,3,123,,0,jun" << std::endl;
file << "SW,2,THR,2,TWO,3,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/dtest.dat");
airports.create_dijkstras("\"ONE\"");
vector<Vertex> path = airports.shortest_path("\"THR\"");
airports.shortest_to_text("\"THR\"");
REQUIRE(path.size() == 3);
REQUIRE(path[0].get_name() == "name 1");
REQUIRE(path[1].get_name() == "name 2");
REQUIRE(path[2].get_name() == "name 3");
}
TEST_CASE("dijkstras - takes shorter path") {
std::ofstream file("data/dtest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "UAL,1,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "UAL,1,TWO,1,ONEE,2,123,,0,jun" << std::endl;
file << "SW,2,TWO,2,THR,3,123,,0,jun" << std::endl;
file << "SW,2,THR,2,TWO,3,123,,0,jun" << std::endl;
file << "EVA,4,THRE,3,FOU,4,123,,0,jun" << std::endl;
file << "EVA,4,FOU,3,FIVE,4,123,,0,jun" << std::endl;
file << "UAL,1,ONEE,1,FOU,2,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/dtest.dat");
airports.create_dijkstras("\"ONE\"");
vector<Vertex> path = airports.shortest_path("\"FIVE\"");
airports.shortest_to_text("\"FIVE\"");
REQUIRE(path.size() == 3);
REQUIRE(path[0].get_name() == "name 1");
REQUIRE(path[1].get_name() == "name 4");
REQUIRE(path[2].get_name() == "name 5");
Graph g = airports.get_graph();
double short_dist = g.getEdgeWeight(airports.get_port_map()["\"ONE\""],
airports.get_port_map()["\"FOUR\""]) +
g.getEdgeWeight(airports.get_port_map()["\"FOUR\""],
airports.get_port_map()["\"FIVE\""]);
REQUIRE(short_dist == airports.shortest_dist("\"FIVE\""));
double long_dist = g.getEdgeWeight(airports.get_port_map()["\"ONEE\""],
airports.get_port_map()["\"TWO\""]) +
g.getEdgeWeight(airports.get_port_map()["\"TWO\""],
airports.get_port_map()["\"THR\""]) +
g.getEdgeWeight(airports.get_port_map()["\"THRE\""],
airports.get_port_map()["\"FOU\""]) +
g.getEdgeWeight(airports.get_port_map()["\"FOU\""],
airports.get_port_map()["\"FIVE\""]);
REQUIRE(long_dist > short_dist);
}
TEST_CASE("dijkstras - checks node only if necessary (efficiency)") {
std::ofstream file("data/dtest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "UAL,1,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "UAL,1,TWO,1,ONEE,2,123,,0,jun" << std::endl;
file << "SW,2,TWO,2,THR,3,123,,0,jun" << std::endl;
file << "SW,2,THR,2,TWO,3,123,,0,jun" << std::endl;
file << "EVA,4,THRE,3,FOU,4,123,,0,jun" << std::endl;
file << "EVA,4,FOU,3,FIVE,4,123,,0,jun" << std::endl;
file << "UAL,1,ONEE,1,FOU,2,123,,0,jun" << std::endl;
file << "UAL,1,ONEE,1,TEN,2,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/dtest.dat");
vector<int> check = airports.create_dijkstras("\"ONEE\"");
// for(int x =0 ; x<(int)check.size();x++){
// std::cout << check[x] << " ";
// }
REQUIRE(check.size() == 6);
}
TEST_CASE("dijkstras - checks node each node once (efficiency)") {
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/testroutes.dat");
vector<int> check = airports.create_dijkstras("\"ONEE\"");
// for(int x =0 ; x<(int)check.size();x++){
// std::cout << check[x] << " ";
// }
REQUIRE(check.size() == 11);
REQUIRE(check_dup(check) == false);
}
TEST_CASE(
"Correct vertices for vertices of strongly connected graph of an airline "
"with no inbound edges",
"[weight=1][part=1]") {
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/teststronglyroutes.dat");
vector<vector<Vertex>> vec = airports.getStronglyConnected("\"EA\"");
REQUIRE(vec.size() == 4);
vector<vector<std::string>> check;
for (auto i : vec) {
vector<std::string> temp;
for (auto j : i) temp.push_back(j.get_IATA());
check.push_back(temp);
}
vector<vector<std::string>> sol = {
{"ONE"}, {"THR", "FOU"}, {"FIV", "SIX"}, {"EIG", "NIN", "TEN"}, {"ELE"}};
REQUIRE(sol == check);
}
TEST_CASE("BFS - empty data set") {
std::ofstream file("data/bfstest.dat",
std::ofstream::out | std::ofstream::trunc);
Airports airports("data/bfstest.dat", "data/testairlines.dat",
"data/testroutes.dat");
vector<vector<Vertex>> b = airports.bfs();
vector<Vertex> path;
for (unsigned x = 0; x < b.size(); x++) {
for (unsigned y = 0; y < b[x].size(); y++) {
path.push_back(b[x][y]);
}
}
REQUIRE(path.size() == 0);
}
TEST_CASE("BFS - Traverses the whole graph with the correct path") {
std::ofstream file("data/bfstest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "SW,2,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "SW,2,ONEE,1,FOUR,4,123,,0,jun" << std::endl;
file << "SW,2,FOUR,4,THR,3,123,,0,jun" << std::endl;
file << "SW,2,FOUR,4,SIX,6,123,,0,jun" << std::endl;
file << "SW,2,SIX,6,SEVE,7,123,,0,jun" << std::endl;
file << "SW,2,SEVE,7,FIVE,5,123,,0,jun" << std::endl;
file << "SW,2,FIVE,5,EIG,8,123,,0,jun" << std::endl;
file << "SW,2,EIG,8,NINE,9,123,,0,jun" << std::endl;
file << "SW,2,NINE,9,TEN,10,123,,0,jun" << std::endl;
file << "SW,2,TEN,10,ELE,11,123,,0,jun" << std::endl;
file << "SW,2,ELE,11,TWO,2,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/bfstest.dat");
vector<vector<Vertex>> b = airports.bfs();
vector<Vertex> path;
REQUIRE(b.size() == 1); // traversal is connected
for (unsigned x = 0; x < b.size(); x++) {
for (unsigned y = 0; y < b[x].size(); y++) {
path.push_back(b[x][y]);
}
}
REQUIRE(path.size() == 11);
vector<std::string> sol = {"name 1", "name 2", "name 4", "name 3",
"name 6", "name 7", "name 5", "name 8",
"name 9", "name 10", "name 11"};
REQUIRE(bfs_test(path, sol));
}
TEST_CASE("BFS - Traverse a graph with multiple components") {
std::ofstream file("data/bfstest.dat",
std::ofstream::out | std::ofstream::trunc);
file << "SW,2,ONEE,1,TWO,2,123,,0,jun" << std::endl;
file << "SW,2,TWO,2,THR,3,123,,0,jun" << std::endl;
file << "SW,2,FOUR,4,SIX,6,123,,0,jun" << std::endl;
file << "SW,2,SIX,6,SEVE,7,123,,0,jun" << std::endl;
file << "SW,2,SEVE,7,FIVE,5,123,,0,jun" << std::endl;
file << "SW,2,FIVE,5,EIG,8,123,,0,jun" << std::endl;
Airports airports("data/testairports.dat", "data/testairlines.dat",
"data/bfstest.dat");
vector<vector<Vertex>> b = airports.bfs();
REQUIRE(b.size() == 5);
vector<vector<std::string>> sol = {
{"name 1", "name 2", "name 3"},
{"name 4", "name 6", "name 7", "name 5", "name 8"},
{"name 9"},
{"name 10"},
{"name 11"}};
REQUIRE(bfs_comp(b, sol));
}
| true |
4cc1828986d536c901d4026cdfbbf98e9db51346 | C++ | MohammadAlhourani/GamesEngineeringPathfindingProject | /GamesEngineeringProject/GamesEngineeringProject/ThreadPool.cpp | UTF-8 | 1,684 | 3.25 | 3 | [] | no_license | #include "ThreadPool.h"
ThreadPool::ThreadPool() {
numThreads = std::thread::hardware_concurrency() - 1;
for (int i = 0; i < numThreads; i++)
{
m_threads.push_back(std::thread(&ThreadPool::infiniteLoopFunc, this));
}
}
ThreadPool::~ThreadPool()
{
}
void ThreadPool::push(std::function<void()> func)
{
std::unique_lock<std::mutex> lock(m_lock);
m_function_queue.push(func);
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
lock.unlock();
m_data_condition.notify_one();
}
void ThreadPool::done()
{
std::unique_lock<std::mutex> lock(m_lock);
m_accept_functions = false;
lock.unlock();
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
m_data_condition.notify_all();
//notify all waiting threads.
}
void ThreadPool::infiniteLoopFunc(ThreadPool* t_pool)
{
std::function<void()> func;
while (true)
{
{
std::unique_lock<std::mutex> lock(t_pool->m_lock);
t_pool->m_data_condition.wait(lock, [&]() {return !t_pool->m_function_queue.empty() || t_pool->m_accept_functions; });
if (!t_pool->m_accept_functions && t_pool->m_function_queue.empty())
{
//lock will be release automatically.
//finish the thread loop and let it join in the main thread.
return;
}
func = t_pool->m_function_queue.front();
t_pool->m_function_queue.pop();
//release the lock
}
func();
}
}
int ThreadPool::getThreadNums()
{
return numThreads;
}
| true |
d68f6571b97fb312e01138c2a2755047189d03fc | C++ | jaspermacnaughton/Mandelbrot-Set | /src/main.cpp | UTF-8 | 1,314 | 2.984375 | 3 | [] | no_license | #include "complex.h"
double getInput(string displayString) {
double x;
cout << displayString;
cin >> x;
cin.ignore();
return x;
}
int main() {
const int n = 10; // Number of iterations to check if number in mandlebrot
double startx = getInput("Enter start X point: ");
double stopx = getInput("Enter stop X point: ");
if (startx >= stopx) {
cout << "Error! starting X point must be less than stopping X point" << endl;
cin.get();
return 1;
}
double starty = getInput("Enter start Y point (will be complex component): ");
double stopy = getInput("Enter start Y point (will be complex component): ");
if (starty >= stopy) {
cout << "Error! starting Y point must be less than stopping Y point" << endl;
cin.get();
return 1;
}
double stepsize = getInput("Enter stepsize: ");
if (stepsize <= 0) {
cout << "Error! Stepsize must be a positive value. You entered: " << to_string(stepsize) << endl;
cin.get();
return 1;
}
complex c;
double x;
double y = stopy;
while (y >= starty) {
x = startx;
cout << " ";
while (x <= stopx) {
c.setVals(x, y);
if (accept(c, n)) {
cout << "X";
}
else {
cout << "_";
}
x += stepsize;
}
cout << endl;
y -= stepsize;
}
cin.get();
return 0;
} | true |
92bc7338f85e7c7c883598be97140b4b0b384c50 | C++ | JonasKnarbakk/Snake | /src/SDL/SDLManager.cpp | UTF-8 | 3,600 | 3.34375 | 3 | [] | no_license | /*
* @file: SDLManager.cpp
* @author: Stig M. Halvorsen <halsti@nith.no>
* @version: 1.0.0 <11.02.2013>
*
* @description: Singleton class to be used for SDL initialization,
* window management, and rendering (blit'ing).
* NB: Ment for games, so it's containing a Master/Main
* window.
*/
#include <sstream>
#include "SDLManager.h"
SDLManager::SDLManager()
{
m_mainWindow = 0;
}
/* Initializes SDL with the given flags */
void SDLManager::init(Uint32 flags)
{
if (SDL_Init(flags))
{
std::stringstream msg;
msg << "Could not initialize SDL: " << SDL_GetError();
throw SDLError(msg.str());
}
}
/* Quits SDL, windows close when they go out of scope */
SDLManager::~SDLManager()
{
SDL_Quit();
}
/* Creates a SDL window, se SDL documentation for flag options. */
int SDLManager::createWindow(const std::string& title,
const int& width, const int& height,
const int& x, const int& y,
const Uint32& flags,
const bool& mainWindow)
{
// Create the window where we will draw.
SDL_Window* window = SDL_CreateWindow(
title.c_str(), x, y, width, height, flags
);
// Check for errors
if (window == NULL)
{
std::stringstream msg;
msg << "Could not create window; \"" << title
<< "\", details: " << SDL_GetError();
throw SDLError(msg.str());
}
// We must call SDL_CreateRenderer in order for draw calls to affect this window.
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) // Check for render errors
{
std::stringstream msg;
SDL_DestroyWindow(window); // clean up
msg << "Could not create window renderer; \"" << title
<< "\", details: " << SDL_GetError();
throw SDLError(msg.str());
}
// Select the color for drawing. It is set to black here.
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
// Clear the entire screen to our selected color.
SDL_RenderClear(renderer);
// Retrieve the index of the new window by getting current size
int index = m_windows.size();
// Create and add the new window
m_windows.push_back(
std::unique_ptr<SDLWindow>(
new SDLWindow(window, renderer, true)
)
);
// Set main window if not already set or asked to
if (mainWindow || (m_mainWindow == 0))
{
m_mainWindow = index;
}
renderWindow(index); // Render window immediately
return index;
}
/* Sets the main/master window */
void SDLManager::setMainWindow(const unsigned int& windowIndex)
{
if ((m_windows.size() > windowIndex) && m_windows[windowIndex]->m_open)
{
m_mainWindow = windowIndex;
}
}
/* Returns the renderer to the specified window */
SDL_Renderer* SDLManager::getRenderer(const unsigned int& windowIndex) const
{
if (m_windows.size() > windowIndex)
{
return m_windows[windowIndex]->m_renderer;
}
return NULL;
}
/* Returns the index of the main/master window */
const unsigned int* SDLManager::getMainWindow() const
{
return &m_mainWindow;
}
/* Closes the given window (index) */
void SDLManager::closeWindow(const unsigned int& windowIndex)
{
if (m_windows.size() > windowIndex)
{
m_windows[windowIndex]->m_open = false;
SDL_DestroyRenderer(m_windows[windowIndex]->m_renderer);
SDL_DestroyWindow(m_windows[windowIndex]->m_window);
}
}
/* Renders/blits the given window (index) */
void SDLManager::renderWindow(const unsigned int& windowIndex)
{
if ((m_windows.size() > windowIndex) && m_windows[windowIndex]->m_open)
{
SDL_RenderPresent(m_windows[windowIndex]->m_renderer);
}
}
/* Renders/blits all open windows */
void SDLManager::render()
{
for (unsigned int i = 0; i < m_windows.size(); ++i)
{
renderWindow(i);
}
}
| true |
de7bd10d5b26790af81600225fa757215bef4af2 | C++ | DrChenXX/homework | /大一/实验5/4.松雅的旅馆.cpp | UTF-8 | 331 | 2.703125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n,d;
cin >> n >> d;
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int ans = 2;
for (int i = 1; i < n; i++)
{
if (a[i] - a[i - 1] > 2 * d)
{
ans = ans + 2;
}
if (a[i] - a[i - 1] == 2 * d)
{
ans = ans + 1;
}
}
cout << ans;
return 0;
}
| true |
1dc56e182996d022bda2ce723f977d75801ce0e2 | C++ | adityasunny1189/C-PlusPlus_Basics | /C++ STL/vector2.cpp | UTF-8 | 492 | 3.75 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
vector<int> v;
cout << "Insert Elements:" << endl;
for(int i = 0; i < 5; i++) {
int num;
cin >> num;
v.push_back(num);
}
cout << "Arrays Elements are: " << endl;
for(auto x: v) {
cout << x << " ";
}
cout << endl;
cout << "Vector Size: " << v.size() << endl;
cout << "Vector Capacity: " << v.capacity() << endl;
v.pop_back();
} | true |
7c89d966cbeb19182cb4e64da44cdcba4a09f77d | C++ | Whatop/Pord | /Pord_/SpaceEngine-master/Space/UI.h | UTF-8 | 724 | 2.546875 | 3 | [] | no_license | #pragma once
class UI : public Singleton<UI>, public Object
{
Sprite* m_BGHpBar;
Sprite* m_HpBar;
Sprite* m_DashUI;
Sprite* m_DashBlind;
Sprite* m_HealUI;
Sprite* m_HealBlind;
Sprite* m_Karma;
Sprite* m_State;
Sprite* m_StateBar;
Sprite* m_BGStateBar;
Sprite* m_State_RGB;
Sprite* m_State_Fire;
Sprite* m_State_Poison;
TextMgr* m_HpText;
TextMgr* m_DashText;
TextMgr* m_HealText;
TextMgr* m_KarmaText;
TextMgr* m_StateText;
public:
UI();
~UI();
int m_MaxHp;
int m_Hp;
float m_HpGage;
float m_StateGage;
float m_DashCooldown;
float m_HealCooldown;
std::string m_CurrentState;
float m_Fire;
float m_Poison;
int Karma;
void Init();
void Release();
void Update();
void Render();
};
| true |
817bb1cc6983d97e7adf1192dec0142938905623 | C++ | vivekkj123/C-with-DS | /All About C/Arrays/3. Max element from Array.cpp | UTF-8 | 340 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | // You can take input from user. Also can solve directly if you are sure.
#include<iostream>
using namespace std;
int main(){
int max=0;
int a[5]={5, 6, 7, 4, 3};
for(int i=0; i<5; i++){
if(a[i]>max)
max=a[i];
}
cout<<max<<" is the maximum number in this arrry.";
return 0;
}
| true |
dc01d75c132cbb0abbdae9291c76c293e359ee82 | C++ | mahaveer-rulaniya/7dc | /function programiz/sumofnatural.cpp | UTF-8 | 277 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int sum(int n){
if(n!= 0){
return n + sum(n-1);
}
}
int main(){
int a;
cout<< "please input the number upto which sum is to be calculated : \n";
cin >> a;
cout << "Sum is :: "<< sum(a)<< endl;
} | true |
b0d271de66390ef3723ab5c1a0fa8f41a2a922d3 | C++ | aznboystride/ricefryer | /main.cpp | UTF-8 | 686 | 3.25 | 3 | [] | no_license | #include <Windows.h>
#include "Fryer.h"
int main()
{
Fryer fryer;
while (1) {
cout << "\n----------Current State----------: " << fryer.GetState() << endl;
cout << "\t1. Cook" << endl;
cout << "\t2. Stop Cook" << endl;
cout << "\t3. Lock Lid" << endl;
cout << "\t4. Unlock Lid" << endl;
cout << "\tEnter choice: ";
int ch;
cin >> ch;
cout << "\t";
switch (ch) {
case 1:
fryer.cookButton();
break;
case 2:
fryer.stopCookButton();
break;
case 3:
fryer.closeLidButton();
break;
case 4:
fryer.openLidButton();
break;
default:
cout << "Invalid Option" << endl;
}
cout << "\t";
system("pause");
system("cls");
}
return 0;
} | true |
96f6ca896f8382a9297ceb7c062ef653bcea9959 | C++ | Damokenl/TwoDRender | /TwoDRender/TwoDRender.cpp | UTF-8 | 7,502 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
//Note: always include before gl or glfw
#include <GL/glew.h>
//GLEW handles the keyboard and window
#include <glfw3.h>
GLFWwindow* window;
#include <glm/glm.hpp>
using namespace glm;
#include "common\shader.hpp"
#include <common\texture.hpp>
int main( void )
{
// Initialise GLFW
if( !glfwInit() )
{
fprintf( stderr, "Failed to initialize GLFW\n" );
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 1);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow( 800, 800, "TwoDRender", NULL, NULL); //1024 768
if( window == NULL ){
fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
glfwTerminate();
return -1;
}
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
//Tutorial 2 stuff
//GLuint programID = LoadShaders("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader");
GLuint programID = LoadShaders("TexturedVertexShader.vertexshader", "TexturedFragmentShader.fragmentshader");
GLuint VertexArrayID = GLuint();
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
static const GLfloat g_vertex_buffer_data[] = {
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
GLuint Texture; //= loadDDS("uvtemplate.DDS");
const char * imagepath = "GrassTestSmall.bmp";
//START
printf("Reading image %s\n", imagepath);
// Data read from the header of the BMP file
unsigned char header[54];
unsigned int dataPos;
unsigned int imageSize;
unsigned int width, height;
// Actual RGB data
unsigned char * data;
// Open the file
FILE * file = fopen(imagepath, "rb");
if (!file) { printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath); getchar(); return 0; }
// Read the header, i.e. the 54 first bytes
// If less than 54 bytes are read, problem
if (fread(header, 1, 54, file) != 54) {
printf("Not a correct BMP file\n");
fclose(file);
return 0;
}
// A BMP files always begins with "BM"
if (header[0] != 'B' || header[1] != 'M') {
printf("Not a correct BMP file\n");
fclose(file);
return 0;
}
// Make sure this is a 24bpp file
if (*(int*)&(header[0x1E]) != 0) { printf("Not a correct BMP file\n"); fclose(file); return 0; }
if (*(int*)&(header[0x1C]) != 24) { printf("Not a correct BMP file\n"); fclose(file); return 0; }
// Read the information about the image
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
width = *(int*)&(header[0x12]);
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
if (dataPos == 0) dataPos = 54; // The BMP header is done that way
// Create a buffer
data = new unsigned char[imageSize];
// Read the actual data from the file into the buffer
fread(data, 1, imageSize, file);
// Everything is in memory now, the file wan be closed
fclose(file);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
// OpenGL has now copied the data. Free our own version
delete[] data;
fclose(file);
// Poor filtering, or ...
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// ... nice trilinear filtering.
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
// Return the ID of the texture we just created
Texture = textureID;
//END
GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler");
static const GLfloat g_uv_buffer_data[]{
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 0.0f,
1.f, 1.f,
0.f, 1.f
};
GLuint uvbuffer;
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_uv_buffer_data), g_uv_buffer_data, GL_STATIC_DRAW);
do{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
glUseProgram(programID);
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture);
// Set our "myTextureSampler" sampler to user Texture Unit 0
glUniform1i(TextureID, 0);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1, // attribute. No particular reason for 1, but must match the layout in the shader.
2, // size : U+V => 2
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 12 * 3); // 12*3 indices starting at 0 -> 12 triangles
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteProgram(programID);
glDeleteTextures(1, &Texture);
glDeleteVertexArrays(1, &VertexArrayID);
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
| true |
022cb2bc52c04ee34c9e98bec763fdbaf07da364 | C++ | HyangRim/Algorithm_Back | /2455.cpp | UHC | 549 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int remax = -987654321;
int arr[4][2];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 2; y++) {
cin >> arr[x][y];
}
}
int ans = 0;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 2; y++) {
if (y == 0) {//.
if (ans - arr[x][y] < 0)
ans = 0;
else
ans -= arr[x][y];
}
else {//Ÿ.
ans += arr[x][y];
if (remax < ans) remax = ans;
}
}
}
cout << remax;
return 0;
} | true |
6375782f10c85a79f5f491168ae9e437c94559c6 | C++ | Tempoblink/cxxp | /ch07_Classes/exercise_7_01.cpp | UTF-8 | 1,416 | 3.765625 | 4 | [] | no_license | /*
* 使用2.6.1节练习定义的Sales_data类为1.6节(第21页)的交易处理程序编写一个新版本。
*/
#include <iostream>
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
std::istream &read(std::istream &is, Sales_data &book) {
double price = 0.0;
is >> book.bookNo >> book.units_sold >> price;
book.revenue = book.units_sold * price;
return is;
}
std::ostream &print(std::ostream &os, const Sales_data &book) {
double avg_price = 0.0;
if (book.units_sold)
avg_price = book.revenue / book.units_sold;
os << book.bookNo << " "
<< book.units_sold << " "
<< book.revenue << " "
<< avg_price << std::endl;
return os;
}
void combine(Sales_data &book1, Sales_data &book2) {
if (book1.bookNo != book2.bookNo)
return;
book1.units_sold += book2.units_sold;
book1.revenue += book2.revenue;
}
int main(void) {
Sales_data total;
if (read(std::cin, total)) {
Sales_data trans;
while (read(std::cin, trans)) {
if (total.bookNo == trans.bookNo) {
combine(total, trans);
} else {
print(std::cout, total);
total = trans;
}
}
print(std::cout, total);
} else {
std::cerr << "No data?" << std::endl;
}
return 0;
}
| true |
552130db7b5bffd2f159c330af67c989fe7dd72e | C++ | AAI1234S/cpp | /function/function_over.cpp | UTF-8 | 418 | 3.171875 | 3 | [
"MIT"
] | permissive | #include<iostream>
void display(int ch, float len)
{
std::cout<<"ch="<<ch<<std::endl;
std::cout<<"len="<<len<<std::endl;
}
void display(float ch, float len)
{
std::cout<<"ch="<<ch<<std::endl;
std::cout<<"len="<<len<<std::endl;
}
void display(char ch, double len)
{
std::cout<<"ch1="<<ch<<std::endl;
std::cout<<"len1="<<len<<std::endl;
}
int main()
{
char c='a';
double l=20.2;
display(c,l);
return 0;
}
| true |
8741f4a4e69fed9790bf10d71ddee3cd5a97511e | C++ | suyuan945/LeetCode | /173_BSTIterator/173_BSTIterator.cpp | UTF-8 | 2,525 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *BuildTree(vector<int> preorder){
TreeNode dummy(0);
TreeNode* root = &dummy;
for (int i = 0; i < preorder.size(); ++i){
root->left = new TreeNode(preorder[i]);
root = root->left;
}
return dummy.left;
}
void PrintTree(TreeNode* root){
vector<vector<int> > result;
if (!root) return;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> cur_vec;
while (!q.empty()) {
TreeNode* t = q.front();
q.pop();
if (t == NULL) {
result.push_back(cur_vec);
cur_vec.resize(0);
if (q.size() > 0) {
q.push(NULL);
}
} else {
cur_vec.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
for (auto vv : result){
for (auto v : vv){
cout << v << ", ";
}
cout << endl;
}
return;
}
class BSTIterator {
private:
stack<TreeNode*> st;
public:
BSTIterator(TreeNode *root) {
find_left(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (st.empty())
return false;
return true;
}
/** @return the next smallest number */
int next() {
TreeNode* top = st.top();
st.pop();
if (top->right != NULL)
find_left(top->right);
return top->val;
}
/** put all the left child() of root */
void find_left(TreeNode* root){
TreeNode* p = root;
while (p != NULL){
st.push(p);
p = p->left;
}
}
};
class BSTIteratorMy {
public:
BSTIteratorMy(TreeNode *root) {
p = root;
/*while (p || !stk.empty()){
while (p){
stk.push(p);
p = p->left;
}
p = stk.top();
stk.pop();
cout << p->val;
p = p->right;
}*/
}
/** @return whether we have a next smallest number */
bool hasNext() {
return (p || !stk.empty());
}
/** @return the next smallest number */
int next() {
int val = 0;
if (p || !stk.empty()){
while (p){
stk.push(p);
p = p->left;
}
p = stk.top();
stk.pop();
val = p->val;
p = p->right;
}
return val;
}
private:
TreeNode *p;
stack<TreeNode*> stk;
};
int main(int argc, char *argv[]){
auto t = BuildTree(vector<int>{1, 4, 5, 4, 3});
BSTIterator i = BSTIterator(t);
while (i.hasNext()) {
cout << i.next();
}
system("pause");
return 0;
}
| true |
c09d4944acd22d6687bf5bccbdbbe58b443c8548 | C++ | chloro-pn/raft | /asio_wrapper/timer.h | UTF-8 | 1,149 | 3.015625 | 3 | [] | no_license | #ifndef TIMER_H
#define TIMER_H
#include "asio.hpp"
#include "log.h"
#include <memory>
#include <functional>
namespace puck {
class TimerHandle {
public:
TimerHandle():cancel_(false) {
}
bool Canceled() const {
return cancel_;
}
void Cancel() {
cancel_ = true;
}
private:
bool cancel_;
};
template <typename T>
class Timer : public std::enable_shared_from_this<Timer<T>> {
private:
std::function<void(const asio::error_code& ec)> fn_;
asio::io_context& io_;
T ms_;
asio::steady_timer st_;
std::shared_ptr<TimerHandle> handle_;
public:
Timer(std::function<void(const asio::error_code& ec)> fn, asio::io_context& io, T s) :
fn_(fn),
io_(io),
ms_(s),
st_(io_),
handle_(std::make_shared<TimerHandle>()){
}
std::shared_ptr<TimerHandle> Start() {
size_t i = st_.expires_after(ms_);
assert(i == 0);
auto self = this->shared_from_this();
st_.async_wait([self](const asio::error_code& ec)-> void {
if(self->handle_->Canceled() == true) {
return;
}
self->fn_(ec);
});
return handle_;
}
};
}
#endif // TIMER_H
| true |
05654977833fd33fdee69109ba8b2a6b361d2f3c | C++ | zztttt/LeetCode | /0059. Spiral Matrix II/sol.cpp | UTF-8 | 1,034 | 2.796875 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret(n, vector<int>(n, -1));
int count = 1;
int rlow = 0, rhigh = n - 1, clow = 0, chigh = n - 1;
while(rlow <= rhigh && clow <= chigh){
// top row
for(int i = clow; i <= chigh; ++i){
ret[rlow][i] = count++;
}
// right col
for(int i = rlow + 1; i <= rhigh; ++i){
ret[i][chigh] = count++;
}
// avoid duplicate
if(rlow != rhigh){
// bottom row
for(int i = chigh - 1; i >= rlow; --i){
ret[rhigh][i] = count++;
}
}
if(clow != chigh){
// left col
for(int i = rhigh - 1; i >= rlow + 1; --i){
ret[i][clow] = count++;
}
}
rlow++;rhigh--;
clow++;chigh--;
}
return ret;
}
}; | true |
67d7330849205930a3dcb8337010ecf372373424 | C++ | RallyWRT/ppsocket | /TUDT/P2PUdtTest/P2PUdtTest.cpp | GB18030 | 2,915 | 2.75 | 3 | [] | no_license | // P2PUdtTest.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
#include "udt.h"
//#include "TNetworkListener.h"
#include "StrFuns.h"
//#include "TConn.h"
class ConnHandler:
public UDT::TConnection
{
public:
ConnHandler(UDT::TConnectMng *pMng,UDTSOCKET u=UDT::INVALID_SOCK)
:TConnection(pMng,u)
{};
virtual void OnConnected(bool bSuccess)
{
if (bSuccess)
{
cout<<"ӳɹ"<<endl;
}
else
{
cout<<"ʧܣ"<<endl;
}
}
virtual void OnData(const char* pData, int ilen)
{
cout<<"OnData:"<<pData<<endl;
if(this->Send(pData,ilen))
{
cout<<"Echo Succeed."<<endl;
}
}
protected:
private:
};
void TestConn2(int iPort)
{
UDT::TConnectMngTemplate<ConnHandler> mng(iPort,NULL);
cout<<"Echo Server ɣ˿:"<<iPort<<endl;
cout<<"ҪͲݣconnect ip port"<<endl;
string strCmd;
char buf[128];
while(strCmd!="exit")
{
cin.getline(buf,128);
vector<string> vecParams;
StrFuns::Tokenize(buf,vecParams," ");
if(vecParams.empty())
{
continue;
}
if(vecParams[0]=="exit")
{
break;
}
else if(vecParams[0]=="connect")
{
if(vecParams.size()!=3)
{
cout<<"param count should be 2."<<endl;
continue;
}
cout<<"connecting to :"<<vecParams[1]<<endl;
//ShootTo(*pNetbase,vecParams[1],atoi(vecParams[2].c_str()));
sockaddr_in dist;
dist.sin_family = AF_INET;
dist.sin_addr.s_addr = inet_addr(vecParams[1].c_str());
dist.sin_port = htons(atoi(vecParams[2].c_str()));
ConnHandler conn(&mng);
if(!conn.ConnectToEx((sockaddr *)&dist,sizeof(dist)))
{
cout<<"connect failed."<<endl;
continue;
}
int i = 0;
while (!conn.IsReady() && i<1000)
{
Sleep(10);
i++;
}
//conn.ConnectToEx((sockaddr *)&dist,sizeof(dist));
cout<<"ʹ"<<endl;
if(!conn.Send("Hello,triger echo!",19))
{
cout<<"send error"<<endl;
continue;
}
cout<<"ȴ10롭"<<endl;
Sleep(10*1000);
//conn.Close(); //Զ
cout<<"ɣӶϿ"<<endl;
}
else
{
cout<<"Unknow cmd:"<<vecParams[0]<<endl;
cout<<"cmd list:"<<endl;
cout<<"\tconnect <addr> <port>"<<endl;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//UDT5001˿ڣݣ10ʾӦȻرա
int iPort = 0;
if(argc==2)
{
iPort = atoi(argv[1]);
}
else
{
cout<<"ҪʹõUDT˿ںţ"<<endl;
cin>>iPort;
if (iPort<0 || iPort>=65535)
{
cout<<"UDT˿ں"<<endl;
getchar();
return 0;
}
}
TestConn2(iPort);
return 0;
}
| true |
ff1140f47c9b46a68f0177cad28b94811c9b6138 | C++ | jsj2008/Three.cpp | /Three.cpp/three/others/Utils.cpp | UTF-8 | 2,618 | 2.828125 | 3 | [] | no_license | //
// Utils.cpp
// Three.cpp
//
// Created by Saburo Okita on 30/06/14.
// Copyright (c) 2014 Saburo Okita. All rights reserved.
//
#include "Utils.h"
#include <sstream>
#include <glm/gtc/quaternion.hpp>
using namespace std;
namespace three {
string Utils::toString( const vector<int>& vec ) {
stringstream ss;
ss << "[";
for( int i = 0; i < vec.size() - 1; i++ )
ss << i << ", ";
ss << vec[vec.size()-1] << "]";
return ss.str();
}
string Utils::toString( const vector<float>& vec ) {
stringstream ss;
ss << "[";
for( int i = 0; i < vec.size() - 1; i++ )
ss << i << ", ";
ss << vec[vec.size()-1] << "]";
return ss.str();
}
string Utils::toString( const vector<glm::vec2>& vec ) {
stringstream ss;
ss << "[";
for( int i = 0; i < vec.size() - 1; i++ )
ss << Utils::toString( vec[i] ) << ", ";
ss << Utils::toString(vec[vec.size()-1]) << "]";
return ss.str();
}
string Utils::toString( const vector<glm::vec3>& vec ) {
stringstream ss;
ss << "[";
for( int i = 0; i < vec.size() - 1; i++ )
ss << Utils::toString( vec[i] ) << ", ";
ss << Utils::toString(vec[vec.size()-1]) << "]";
return ss.str();
}
string Utils::toString( const glm::vec2& vec ) {
char temp[100];
sprintf( temp, "(%.2f, %.2f)", vec.x, vec.y );
return string( temp );
}
string Utils::toString( const glm::vec3& vec ) {
char temp[100];
sprintf( temp, "(%.2f, %.2f, %.2f)", vec.x, vec.y, vec.z );
return string( temp );
}
string Utils::toString( const glm::vec4& vec ) {
char temp[100];
sprintf( temp, "(%.2f, %.2f, %.2f, %.2f)", vec.x, vec.y, vec.z, vec.w );
return string( temp );
}
string Utils::toString( const glm::quat& vec ) {
char temp[100];
sprintf( temp, "(%.2f, %.2f, %.2f, %.2f)", vec.x, vec.y, vec.z, vec.w );
return string( temp );
}
string Utils::toString( const glm::mat4x4& mat ) {
char temp[255];
sprintf( temp, "|%6.2f %6.2f %6.2f %6.2f|\n|%6.2f %6.2f %6.2f %6.2f|\n|%6.2f %6.2f %6.2f %6.2f|\n|%6.2f %6.2f %6.2f %6.2f|",
mat[0][0], mat[0][1], mat[0][2], mat[0][3],
mat[1][0], mat[1][1], mat[1][2], mat[1][3],
mat[2][0], mat[2][1], mat[2][2], mat[2][3],
mat[3][0], mat[3][1], mat[3][2], mat[3][3] );
return string( temp );
}
} | true |
391e594e42d3b6f656bf5bb66e0562b68219bce6 | C++ | haichangyang/xd0615 | /lesson7/code2.c.ino | UTF-8 | 960 | 2.578125 | 3 | [] | no_license | #include <MsTimer2.h> //定时器库的头文件
int pinInterrupt=7;
int income=0;
//中断服务程序
void onChange()
{
if ( digitalRead(pinInterrupt) == LOW )
income=0;
}
void onTimer()
{
digitalWrite(6,LOW);
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
digitalWrite(2,income&0x1);
digitalWrite(3,(income>>1)&0x1);
digitalWrite(4,(income>>2)&0x1);
digitalWrite(5,(income>>3)&0x1);
delay(10);
income++;
if(income==10) income=0;
}
void setup()
{
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
Serial.begin(9600); //初始化串口
pinMode( pinInterrupt, INPUT);//设置管脚为输入
MsTimer2::set(1000, onTimer); //设置中断,每1000ms进入一次中断服务程序 onTimer()
attachInterrupt( digitalPinToInterrupt(pinInterrupt), onChange, CHANGE);
MsTimer2::start(); //开始计时
}
void loop()
{
}
| true |
2631e949f6acb1169814f6a4457d876f44b44918 | C++ | Arganancer/SideScrollingFighter | /9_1_TP2_SideScrollingFighter/delete_account.cpp | UTF-8 | 3,197 | 2.875 | 3 | [
"MIT"
] | permissive | #include "delete_account.h"
#include "input_manager.h"
#include "account_controller.h"
#include "game.h"
delete_account::delete_account()
{
// Confirmation View
delete_confirmation_message_ = text("", Vector2f(0, 0), text::placeholder);
yes_ = button( "Yes", Vector2f(0, 0),text::normal);
yes_.set_position(sf::Vector2f(game::view_width / 2 - yes_.get_text_size() - 20, game::view_height / 2));
no_ = button("no", Vector2f(0, 0),text::normal);
no_.set_position(sf::Vector2f(game::view_width / 2 + 20, game::view_height / 2));
// Account Selection view
nb_of_accounts_ = account_controller::get_nb_of_accounts();
accounts_ = new button[nb_of_accounts_];
const auto distance_between_buttons = 30;
title_ = text("Account Deletion", sf::Vector2f(0, 0), text::title);
title_.set_position(sf::Vector2f(game::view_width / 2 - title_.get_text_size() / 2, 60));
account_selection_text_ = text("Select an account to delete from the following list:", sf::Vector2f(0, 0), text::placeholder);
account_selection_text_.set_position(sf::Vector2f(game::view_width / 2 - account_selection_text_.get_text_size() / 2, 90));
std::vector<sf::String> accounts = account_controller::get_accounts_screen_name();
for (size_t i = 0; i < nb_of_accounts_; i++)
{
accounts_[i] = button(accounts[i], Vector2f(0, 0), text::normal);
accounts_[i].set_position(Vector2f(game::view_width / 2 - accounts_[i].get_text_size() / 2, 150 + distance_between_buttons * i));
}
back_ = button("Back", sf::Vector2f(0, 0), text::normal_plus);
back_.set_position(Vector2f(game::view_width / 2 - back_.get_text_size() / 2, 180 + distance_between_buttons * nb_of_accounts_));
delete_confirmation_is_active_ = false;
account_to_delete_ = "";
}
void delete_account::draw(sf::RenderWindow& main_win)
{
if (delete_confirmation_is_active_)
{
yes_.draw(main_win);
no_.draw(main_win);
delete_confirmation_message_.draw(main_win);
}
else
{
title_.draw(main_win);
account_selection_text_.draw(main_win);
for (size_t i = 0; i < nb_of_accounts_; i++)
{
accounts_[i].draw(main_win);
}
back_.draw(main_win);
}
}
menu_factory::menu_factory::type_menu delete_account::update()
{
if (!delete_confirmation_is_active_)
{
for (size_t i = 0; i < nb_of_accounts_; i++)
{
if (accounts_[i].update())
{
account_to_delete_ = accounts_[i].get_text_string();
delete_confirmation_message_.set_string("Are you sure you wish to delete the account " + account_to_delete_ + "?");
delete_confirmation_message_.set_position(sf::Vector2f(
game::view_width / 2 - delete_confirmation_message_.get_text_size() / 2,
game::view_height / 2 - 30));
delete_confirmation_is_active_ = true;
}
}
if (back_.update())
{
return menu_factory::menu_factory::account_management_e;
}
}
if(delete_confirmation_is_active_)
{
if(yes_.update())
{
account_controller::delete_account(account_to_delete_);
delete_confirmation_is_active_ = false;
return menu_factory::menu_factory::account_management_e;
}
if (no_.update())
{
delete_confirmation_is_active_ = false;
}
}
return menu_factory::menu_factory::delete_account_e;
}
delete_account::~delete_account()
{
} | true |
2d1f5f9e03ac597dfe7bc00d507a0b23d806bcbe | C++ | shadowmydx/leetcode | /Valid Sudoku.cpp | UTF-8 | 1,897 | 3.328125 | 3 | [] | no_license | class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
int len1 = board.size();
if (!len1)
return true;
int len2 = board[0].size();
for (int i = 0;i < len1;i++)
for (int j = 0;j < len2;j++)
{
if (board[i][j] != '.')
{
int num = board[i][j];
bool flag1 = checkRow(i,j,num,board);
bool flag2 = checkCol(i,j,num,board);
bool flag3 = checkCel(i,j,num,board);
if (!flag1 || !flag2 || !flag3)
return false;
}
}
return true;
}
bool checkRow(int row,int col,int num,vector<vector<char> > &board)
{
for (int i = 0;i < 9;i++)
{
if (col == i)
continue;
if (board[row][i] == num)
return false;
}
return true;
}
bool checkCol(int row,int col,int num,vector<vector<char> > &board)
{
for (int i = 0;i < 9;i++)
{
if (row == i)
continue;
if (board[i][col] == num)
return false;
}
return true;
}
bool checkCel(int row,int col,int num,vector<vector<char> > &board)
{
int top = getTop(row);
int left = getTop(col);
for (int i = 0;i < 3;i++)
for (int j = 0;j < 3;j++)
{
if (top + i == row && left + j == col)
continue;
if (board[top+i][left+j] == num)
return false;
}
return true;
}
int getTop(int row)
{
int tmp = row % 9;
if (tmp >= 6)
return 6;
else if (tmp >= 3)
return 3;
else
return 0;
}
}; | true |
7c88ff7d364a40790e989d7ebc846e34b50ec427 | C++ | aratius/OFBeginer | /src/utils/Ground.cpp | UTF-8 | 294 | 2.53125 | 3 | [] | no_license | //
// Ground.cpp
// beginner
//
// Created by 松本新 on 2020/12/15.
//
#include "Ground.hpp"
void Ground::init(float _radius, float _y) {
radius = _radius;
yPos = _y;
}
void Ground::display () {
ofSetColor(0, 0, 0);
ofDrawCircle(ofGetWidth()/2, yPos, radius);
}
| true |
3e3336ba3a3f6c0823829e7060bca01c9b0cc1ce | C++ | john15518513/leetcode | /cpp/constructtherectangle.cpp | UTF-8 | 211 | 2.578125 | 3 | [] | no_license | class Solution {
public:
vector<int> constructRectangle(int area) {
int target = int(sqrt(area));
while (area%target != 0) target--;
return vector<int> {area/target,target};
}
};
| true |
43e8f9c32f495497b0b766ced77dffb3981d1fb6 | C++ | EdwinJosue16/Proyecto_Integrador_Redes-SO | /src/Green/RespondHeartbitRequest.cpp | UTF-8 | 5,020 | 2.703125 | 3 | [] | no_license | #include "RespondHeartbitRequest.hpp"
#include "Payloads/LinkLayerPayload.hpp"
#include "Payloads/HeartbeatPayload.hpp"
#include "Log.hpp"
RespondHeartbitRequest::RespondHeartbitRequest()
{
// This module will receive messages of awake neighbors only.
this->wakeUpStatus.status = NeighbourStatus::WAKE_UP;
}
RespondHeartbitRequest::~RespondHeartbitRequest()
{
}
int RespondHeartbitRequest::run()
{
Log::append("***** Respond Request ***** < The Responder has started its execution. >");
this->consumeForever();
Log::append("***** Respond Request ***** < The Responder has ended its execution. >");
return EXIT_SUCCESS;
}
void RespondHeartbitRequest::consume(const payload_ptr &data)
{
this->attendRequest(data);
}
void RespondHeartbitRequest::attendRequest(payload_ptr request)
{
// It expects to receive herbeat requests only.
auto linkLayerPayload = std::static_pointer_cast<LinkLayerPayload>(request);
auto heartbeatPayload = std::static_pointer_cast<HeartbeatPayload>(linkLayerPayload->payload);
if (heartbeatPayload->type == HeartbeatPayload::HEARBEAT_REQUEST)
{
Log::append("***** Respond Request ***** < A heartbeat request was received. >");
// It propagates the request to the handler.
this->respondRequestTo(request);
}
// It updload the timestamp of the neighbor who send the request and its marked as awake.
Log::append("***** Respond Request ***** < A heartbeat answer was received. >");
// Final destination id indicates to who the message was meant to.
this->notifyReplyToVisitor(linkLayerPayload->sourceId);
this->uploadStatusTable(linkLayerPayload->sourceId);
}
void RespondHeartbitRequest::respondRequestTo(payload_ptr neighborRequest)
{
Log::append("***** Respond Request ***** < A heartbeat request will be processed. >");
auto request = std::static_pointer_cast<LinkLayerPayload>(neighborRequest);
// It builds up the heartbeat answer.
auto heartbeatPayload = std::make_shared<HeartbeatPayload>();
heartbeatPayload->type = HeartbeatPayload::HEARBEAT_ANSWER;
Log::append("***** Respond Request ***** < The heartbeat payload was built. >");
auto answer = std::make_shared<LinkLayerPayload>();
answer->type = LinkLayerPayload::HEARTBEAT_TYPE;
// The source id will be the intended final destination id of the request.
answer->sourceId = request->finalDestinationId;
// The destination node will be the one who sent the request.
answer->immediateDestinationId = request->sourceId;
answer->finalDestinationId = request->sourceId;
answer->payloadLength = heartbeatPayload->getBytesRepresentationCount();
answer->payload = heartbeatPayload;
Log::append("***** Respond Request ***** < The heartbeat answer was built. >");
// It sends the heartbeat answer to the correspoding neighbor who sent the request via associated transmitter
auto transmitter = this->redirectingTable.find(request->sourceId)->second;
if (transmitter != nullptr)
{
Log::append("***** Respond Request ***** < The transmitter was found: " + std::to_string(request->sourceId) + ". >");
}
else
{
Log::append("***** Respond Request ***** < The transmitter was NOT found: " + std::to_string(request->sourceId) + ". >");
}
transmitter->getQueue()->push(answer);
Log::append("***** Respond Request ***** < An answer has been sent to " +
std::to_string(request->sourceId) + " neighbor after receiving its heartbet request. >");
}
void RespondHeartbitRequest::notifyReplyToVisitor(uint8_t associatedNeighborId)
{
Log::append("***** Respond Request ***** < ...Notifying reply to visitor # >" + std::to_string(associatedNeighborId));
visitors[associatedNeighborId]->notifyReply();
}
void RespondHeartbitRequest::uploadStatusTable(uint8_t neighborId)
{
Log::append("***** Respond Request ***** < ...Uploading status (because is awake) of neighbour # >" + std::to_string(neighborId));
this->wakeUpStatus.timestamp.upload();
this->statusOfNeighbors->modifyStatus(neighborId, this->wakeUpStatus);
// It updates the timestamp of the neighbor status.
}
void RespondHeartbitRequest::setVisitors(std::map<DestinationId, Visitor *>& visitors)
{
this->visitors = visitors;
Log::append("***** Respond Request ***** < Set visitors >");
}
void RespondHeartbitRequest::setStatusTable(StatusTable *statusOfNeighbors)
{
this->statusOfNeighbors = statusOfNeighbors;
Log::append("***** Respond Request ***** < Set status table >");
}
void RespondHeartbitRequest::setRedirectingTable(std::map<DestinationId, Transmitter *> &redirectingTable)
{
this->redirectingTable = redirectingTable;
Log::append("***** Respond Request ***** < Set redirecting table >");
} | true |
a6a23aeb4ddf82849abc15489495ae179b83b2ad | C++ | swolka/zadania | /01/main.cpp | UTF-8 | 705 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{ int a, b, c;
cout << "Wpisz kolejno 3 dowolne liczby calkowite" << endl;
cout << "do obliczenia sredniej arytmetycznej z nich." << endl;
cout << " "<< endl;
cout << "Wpisz pierwsza liczbe:" << endl;
cout << "a= ";
cin >> a;
cout << " "<< endl;
cout << "Wpisz druga liczbe:"<< endl;
cout << "b= ";
cin >> b;
cout << " "<< endl;
cout << "Wpisz trzecia liczbe:"<<endl;
cout << "c= ";
cin >> c;
cout << " "<< endl;
cout << "Udalo Ci sie!! Srednia arytmetyczna z podanych trzech liczb wynosi="<< (a+b+c)/3 << endl;
//cout << "Hello world!" << endl;
return 0;
}
| true |
3145440d26f9c09993537165ba793b398ea29a14 | C++ | emrul-chy/Competitive-Programming | /UVa/10929 - You can say 11.cpp | UTF-8 | 478 | 2.765625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int main()
{
int i,j,s;
char n[1050];
while(1)
{
s=0;
scanf("%s",&n);
i=strlen(n);
for(j=0; j<i; j++)
{
s=s*10+n[j]-'0';
s=s%11;
}
if(s==0 && i==1) break;
else if(s==0)
printf("%s is a multiple of 11.\n",n);
else
printf("%s is not a multiple of 11.\n",n);
}
return 0;
}
| true |
de1250bb4237fbdad57742902cd153ed5dc1f6b5 | C++ | MoritzGue/Klangsynthese_JaMo | /src/OneZero.cpp | UTF-8 | 486 | 2.8125 | 3 | [] | no_license | #include "OneZero.h"
#include <cmath>
OneZero :: OneZero( double theZero ){
this->setZero( theZero );
z_1 = 0.0;
}
OneZero :: ~OneZero( void ){
}
void OneZero :: setZero( double theZero ){
// Normalize coefficients for unity gain.
if ( theZero > 0.0 )
b_0 = 1.0 / ((double) 1.0 + theZero);
else
b_0 = 1.0 / ((double) 1.0 - theZero);
b_1 = -theZero * b_0;
}
void OneZero :: setCoefficients(double b0, double b1){
b_0 = b0;
b_1 = b1;
}
| true |
49914a5f482cb173d382cfbaeccdbb83ec5be6ab | C++ | gizmore/yabfdbg | /util/GizStr.cpp | UTF-8 | 1,360 | 3.234375 | 3 | [
"MIT"
] | permissive | #include "GizStr.h"
#include "string.h"
#include "stdio.h"
GizStr::GizStr(int size)
{
buffer = new char[size+1];
length = 0;
buffer[length] = 0;
buf_len = size;
}
GizStr::GizStr(const char *s)
{
length = strlen(s);
buf_len = length + 1;
buffer = new char[buf_len];
memcpy(buffer, s, buf_len);
}
GizStr::GizStr(GizStr& dts)
{
GizStr(dts.buffer);
}
GizStr::~GizStr()
{
}
int GizStr::getLength()
{
return length;
}
char* GizStr::getBuffer()
{
return buffer;
}
int GizStr::getBufferLength()
{
return buf_len;
}
bool GizStr::expand(unsigned int n)
{
unsigned int assured = buf_len - length;
if (assured >= n)
return true;
char* old = buffer;
int nlen = buf_len + n;
buffer = new char[nlen];
if (buffer == 0) {
printf("DTStr::expand(size=%d) - OUT OF MEMORY!\n", n);
buffer = old;
return false;
}
buf_len = nlen;
memcpy(buffer, old, length+1);
delete old;
return true;
}
GizStr& GizStr::append(const char c)
{
if(expand(1)) {
buffer[length] = c;
length++;
buffer[length] = 0;
}
return *this;
}
GizStr& GizStr::append(const char *s)
{
int sl = strlen(s);
if(expand(sl)) {
memcpy(buffer+length, s, sl);
length += sl;
buffer[length] = 0;
}
return *this;
}
GizStr& GizStr::insert(const char *s, unsigned int pos)
{
return *this;
}
GizStr& GizStr::operator + (const char* s)
{
return append(s);
}
| true |
5260ae552c3b6e091db164b651abb16865e142a6 | C++ | szxie/CS308-Compiler | /P2T/node.h | UTF-8 | 1,007 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <llvm/IR/Value.h>
class CodeGenContext;
class NStatement;
class NExpression;
typedef std::vector<NStatement*> StatementList;
class Node {
public:
virtual ~Node() {}
virtual llvm::Value* codeGen(CodeGenContext& context)
{ return NULL; }
};
class NExpression : public Node {
};
class NStatement : public Node {
};
class NInteger : public NExpression {
public:
long long value;
NInteger(long long value) : value(value)
{ std::cout << value << std::endl; }
virtual llvm::Value* codeGen(CodeGenContext& context);
};
class NBinaryOperator : public NExpression {
public:
int op;
NExpression& lhs;
NExpression& rhs;
NBinaryOperator(NExpression& lhs, int op, NExpression& rhs) :
lhs(lhs), rhs(rhs), op(op)
{ std::cout<< op << std::endl; }
virtual llvm::Value* codeGen(CodeGenContext& context);
};
class NBlock : public NExpression {
public:
StatementList statements;
NBlock() {}
virtual llvm::Value* codeGen(CodeGenContext& context);
};
| true |
b9d9ce8a66884d4eceb001369776b3cbc533f0c7 | C++ | jimmy801/UVA | /UVA 10268 498'.cpp | BIG5 | 732 | 3.359375 | 3 | [] | no_license | // 1P-31 498'
// J@ӥNx
// ۿJ@sƦrNa_0,a_1....a_n
// Xa_0 * n * x^(n-1) + a_1 * (n-1) * x^(n-2) + ... + a_(n-1)
#include <iostream>
using namespace std;
int main()
{
int x; char a[1000];
while (cin >> x)
{
cin.ignore();
cin.get(a, 1000, '\n'); cin.ignore();
int int_a[1000] = { 0 };
int ans = 0;int n = 0;
for (int i = 0; i < strlen(a); i++)
{
if (a[i] == ' ')continue;
if (a[i] == '-')
{
int_a[n] = 0 - a[i + 1] + '0'; i++; n++;
continue;
}
int_a[n] = a[i] - '0';
n++;
}
for(int i = 0; i < n - 1; i++)
{
ans += int_a[i] * (n - i - 1) * pow(x, n - i - 2);
}
cout << ans << endl;
}
} | true |
6fd7644eafbf563ded25fb4b1aa0e40f0fdd3317 | C++ | Yhatoh/Programacion_competitiva | /codeforces/276C-Little_Girl_And_Maximum_Sum.cpp | UTF-8 | 1,150 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector< ll > FT;
void fenwickTree(int n){
FT.assign(n + 1, 0);
}
ll query(int n){
int i;
ll sum = 0;
for(i = n; i; i -= (i & (-i)))
sum += FT[i];
return sum;
}
void update(int i, ll x){
for(; i < FT.size(); i += (i & (-i)))
FT[i] += x;
}
void updateRange(int l, int r, ll x){
update(l, x);
update(r + 1, -x);
}
int readCumFreq(int index){
int sum = 0;
while(index > 0){
sum += FT[index];
index -= (index & -index);
}
return sum;
}
void printfFT(){
for(int i = 0; i <= FT.size(); i++)
cout << FT[i] << " ";
}
int main(){
int n, q, i, l, r;
ll sumAcum;
cin >> n >> q;
fenwickTree(n);
vector< ll > as(n);
vector< ll > mult(n);
i = 0;
while(n > i){
cin >> as[i];
i++;
}
sort(as.begin(), as.end());
while(q--){
cin >> l >> r;
updateRange(l, r, 1);
}
for(i = 1; i <= n; i++){
mult[i - 1] = readCumFreq(i);
}
sort(mult.begin(), mult.end());
sumAcum = 0;
i = 0;
while(n > i)
sumAcum += as[i] * mult[i++];
cout << sumAcum << "\n";
return 0;
} | true |
5f88e5ea4a051fefc4337cd4f6e63129f4d57268 | C++ | sandilya28/spoj | /PSYCHON.cpp | UTF-8 | 1,440 | 2.765625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <vector>
using namespace std;
int MAX = 10000000;
vector <bool> prime(MAX+1,1);
vector <int> p;
int main()
{
int limit = sqrt(MAX),size=0;
for (int i = 0; i < 3164; i++)
{
prime[i] = 1;
}
prime[0] = 0;
prime[1] = 0;
for(int i=2;i<limit;i++)
{
if(prime[i])
{
int j = 2*i;
while(j<=limit)
{
prime[j]=0;
j+=i;
}
}
}
for(int i=2;i<limit;i++)
{
if(prime[i])
{
p.push_back(i);
size++;
}
}
int t;
scanf("%d",&t);
while(t--)
{
int n;
int e=0,o=0;
scanf("%d",&n);
int x = n;
for(int i=0;i<size;i++)
{
int yolo = 0;
if(x%p[i]==0)
{
while(x%p[i]==0)
{
x=x/p[i];
yolo++;
if(x==0||x==1)
break;
}
if(yolo%2 ==0)
e++;
else
o++;
if(x==0||x==1)
break;
yolo=0;
}
}
if(x>1)
o++;
if(e>o)
printf("Psycho Number\n");
else
printf("Ordinary Number\n");
}
return 0;
}
| true |
453856592de0de34797d88ced25d8242b05d157c | C++ | Wirgiliusz/FlyAndShoot | /oknoprzegranej.h | UTF-8 | 1,436 | 2.921875 | 3 | [] | no_license | #ifndef OKNOPRZEGRANEJ_H
#define OKNOPRZEGRANEJ_H
/*!
* \file
* \brief Definicja klasy OknoPrzegranej.
*
* Plik zawiera definicję klasy OknoPrzegranej,
* która odpowiada za okno zakończenia gry.
*/
#include <QDialog>
namespace Ui {
class OknoPrzegranej;
}
/*!
* \brief Implementacja obiektu okna przegranej.
*
* Klasa odpowieda za obiekt okna końca gry.
*/
class OknoPrzegranej : public QDialog {
Q_OBJECT
public:
/*!
* \brief Konstruktor klasy OknoPrzegranej.
*
* Inicjalizuje okno przegranej.
* \param[in] *parent - wskaźnik na rodzica.
* \param[in] punkty - ilość uzyskanych punktów podczas gry.
*/
explicit OknoPrzegranej(QWidget *parent = nullptr, int punkty = 0);
/*!
* \brief Destruktor klasy OknoPrzegranej.
*
* Usuwa okno przegranej.
*/
~OknoPrzegranej();
private:
/*!
* \brief Wskaźnik na ui.
*
* Pole zawiera wskaźnik na ui,
* na którym umieszczone są widgety.
*/
Ui::OknoPrzegranej *ui;
private slots:
/*!
* \brief Slot obsłgujący przycisk zagraj ponownie.
*
* Funkcja obsługuje naciśnięcie przycisku
* zagraj ponownie. Restartuje grę.
*/
void on_pushButtonZagrajPonownie_clicked();
signals:
/*!
* \brief Sygnał restartu gry..
*
* Wysyła sygnał, który mówi oknu gry,
* aby zrestartować grę.
*/
void restartGry();
};
#endif // OKNOPRZEGRANEJ_H
| true |
6a41ffb78e263592a0b7cf721dace6f9a7ccf6ad | C++ | xUser5000/competitive-programming | /A/A. Pouring Rain/main.cpp | UTF-8 | 282 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
double d, h, v, e; cin >> d >> h >> v >> e;
double area = (d / 2) * (d / 2) * (22 / 7);
if (e * area > v) cout << "NO";
else printf("YES\n%.8f", area * h / (v - e * area));
return 0;
}
| true |
c54c80eefaa09e2fd03f1f29d74163ee4348a4fc | C++ | sigvebs/StandardCI | /src/MainApplication.cpp | UTF-8 | 10,164 | 2.578125 | 3 | [] | no_license | /*
* File: MainApplication.cpp
* Author: sigve
*
* Created on December 26, 2012, 3:26 PM
*/
#include "MainApplication.h"
//------------------------------------------------------------------------------
MainApplication::MainApplication(int* argc, char*** argv, string configFileName) : argc(argc), argv(argv) {
cout << configFileName << endl;
// Read the file. If there is an error, report it and exit.
try {
cfg.readFile(configFileName.c_str());
} catch (const FileIOException &fioex) {
cerr << "I/O error while reading config file." << endl;
exit(EXIT_FAILURE);
}
#if DEBUG
cout << "Reading configuration from file" << endl;
#endif
}
//------------------------------------------------------------------------------
void MainApplication::runConfiguration() {
bool cleanFiles = cfg.lookup("systemSettings.cleanFiles");
if(cleanFiles)
removeFiles();
// Setting up a Harmonic Oscillator orbital basis
mat interactionElements;
vec orbitalElements;
Basis basis = Basis(&cfg);
basis.createBasis();
string fileNameInteractionElements = createFileName("interactionElements");
string fileNameOrbitalElements = createFileName("orbitalElements");
// Setting the type of basis
WaveFunction *wf;
int dim = cfg.lookup("systemSettings.dim");
switch(dim){
case 1:
wf = new HarmonicOscillator1d(&cfg);
break;
case 2:
wf = new HarmonicOscillator2d(&cfg);
break;
}
// Setting the integrator
SpatialIntegrator *I;
int spatialIntegrator;
cfg.lookupValue("spatialIntegration.integrator", spatialIntegrator);
switch (spatialIntegrator) {
case MONTE_CARLO:
I = new MonteCarloIntegrator(&cfg);
break;
case GAUSS_LAGUERRE:
I = new GaussLaguerreIntegrator(&cfg, wf);
break;
case GAUSS_HERMITE:
I = new GaussHermiteIntegrator(&cfg);
break;
case INTERACTION_INTEGRATOR:
I = new InteractonIntegrator(&cfg);
break;
case MONTE_CARLO_IS:
I = new MonteCarloImportanceSampled(&cfg);
break;
}
cout << "spatialIntegrator = " << spatialIntegrator << endl;
// Loading interaction elements and orbital elements from file
// New elements are generated if needed.
if (!interactionElements.load(fileNameInteractionElements)
|| !orbitalElements.load(fileNameOrbitalElements)) {
cout << "Generating new orbital and interaction elements" << endl;
basis.setIntegrator(I);
basis.setWaveFunction(wf);
basis.computeInteractionelements();
basis.computeSpsEnergies();
interactionElements = basis.getInteractionElements();
orbitalElements = basis.getSpsEnergies();
interactionElements.save(fileNameInteractionElements);
orbitalElements.save(fileNameOrbitalElements);
} else
cout << "Interaction and orbital matrix elements found. Loading matrices from file." << endl;
cout << interactionElements << endl;
// Setting up all Slater Determinants
vector<vec> states = basis.getStates();
SlaterDeterminants SL = SlaterDeterminants(&cfg, states);
SL.createSlaterDeterminants();
vec spsEnergies = SL.computeSpsEnergies(orbitalElements);
vector<bitset<BITS> > slaterDeterminants = SL.getSlaterDeterminants();
cout << "Generated " << slaterDeterminants.size() << " Slater Determinants" << endl;
// Setting up the Hamiltonian matrix
HamiltonMatrix H = HamiltonMatrix(&cfg, slaterDeterminants, interactionElements, spsEnergies);
mat h;
string fileNameHamiltonian = createFileName("hamiltonian");
if (!h.load(fileNameHamiltonian)) {
cout << "Generating new Hamiltonian matrix" << endl;
H.computeMatrixElements();
h = H(0);
h.save(fileNameHamiltonian);
} else{
cout << "Hamilton matrix found. Loading matrix from file." << endl;
H.setHamiltonian(h);
}
// string fileNameImgHamiltonian = createFileName("imageHamiltonian");
// mat hImage = 50*h;
// hImage.save(fileNameImgHamiltonian, pgm_binary);
// Finding the initial ground state
vec eigval;
mat eigvec;
string fileNameEigval = createFileName("eigval");
string fileNameEigvec = createFileName("eigvec");
if (!eigval.load(fileNameEigval) || !eigvec.load(fileNameEigvec)) {
cout << "Diagonalizing the Hamiltonian matrix" << endl;
eig_sym(eigval, eigvec, h);
eigval.save(fileNameEigval);
eigvec.save(fileNameEigvec);
} else
cout << "Hamiltonian eigenvalues and eigenvectors loaded from file." << endl;
// Printing results
int samples = 0;
switch (spatialIntegrator) {
case MONTE_CARLO:
cfg.lookupValue("spatialIntegration.MonteCarlo.samples", samples);
break;
case GAUSS_LAGUERRE:
cfg.lookupValue("spatialIntegration.GaussLaguerre.samples", samples);
break;
case GAUSS_HERMITE:
cfg.lookupValue("spatialIntegration.GaussHermite.samples", samples);
break;
}
// Printing results
double k = correlationFactor(eigvec.col(0));
double w = cfg.lookup("systemSettings.w");
cout << "\nIntegrator \t Shells \t Orbitals \t w \t Energy \t K \t Samples \n";
cout << "-------------------------------------------------------------------------\n"
<< spatialIntegrator << " \t\t "
<< (int) cfg.lookup("systemSettings.shells") << " \t\t "
<< orbitalElements.size() << " \t\t "
<< w << " \t "
<< eigval.min() << " \t"
<< k << "\t"
<< samples << endl;
cout << "-------------------------------------------------------------------------\n";
// Time integration
// Plotting resutls
bool tIntegration;
tIntegration = cfg.lookup("systemSettings.timeIntegration");
if(tIntegration){
string fileOverlap = createFileName("overlap");
H.computeTimDepMatrixElements(orbitalElements.n_rows);
int nCI = eigvec.n_rows;
cx_vec C0(nCI);
C0.set_real(eigvec.col(0));
C0.set_imag(zeros(nCI, 1));
TimeIntegrator *T;
int tIntegrator = cfg.lookup("TimeIntegration.TimeIntegrator");
switch (tIntegrator) {
case FORWARD_EULER:
T = new ForwardEuler(&cfg, &H, C0);
break;
case BACKWARD_EULER:
cout << "BackwardEuler not yet implemented." << endl;
break;
case CRANK_NICOLSON:
T = new CrankNicolson(&cfg, &H, C0);
break;
case EXPONENTIAL:
T = new ExponentialPropagation(&cfg, &H, C0);
break;
}
double wLaser = cfg.lookup("systemSettings.wLaser");
wLaser *= w;
double dt = cfg.lookup("TimeIntegration.dt");
int end = floor(8*PI/(wLaser*dt));
cx_vec C(nCI);
cx_vec CPrev(nCI);
vec overlap(end);
C = C0;
CPrev = C;
for (int i = 0; i < end; i++) {
T->stepForward();
C = T->getCoefficients();
overlap[i] = pow(abs(cdot(C, C0)), 2);
}
overlap.save(fileOverlap, arma_ascii);
// Plotting resutls
bool plotResult;
plotResult = cfg.lookup("systemSettings.plotResult");
if(plotResult)
system("cd ..; cd PlottingResults; python plottingOverlap.py");
}
cout << "Run Complete" << endl;
}
//------------------------------------------------------------------------------
void MainApplication::finalize() {
}
//------------------------------------------------------------------------------
string MainApplication::createFileName(string baseName)
{
string path;
cfg.lookupValue("systemSettings.SIpath", path);
return path + fName(baseName);
}
//------------------------------------------------------------------------------
string MainApplication::fName(string baseName)
{
string fileName;
// string integrator;
int integrator, shells, dim, nParticles, samples, basisType, coordinateType;
double w, L;
cfg.lookupValue("systemSettings.w", w);
cfg.lookupValue("systemSettings.dim", dim);
cfg.lookupValue("systemSettings.basisType", basisType);
cfg.lookupValue("systemSettings.coordinateType", coordinateType);
cfg.lookupValue("systemSettings.nParticles", nParticles);
cfg.lookupValue("systemSettings.shells", shells);
cfg.lookupValue("spatialIntegration.integrator", integrator);
cfg.lookupValue("spatialIntegration.L", L);
if (integrator == MONTE_CARLO)
cfg.lookupValue("spatialIntegration.MonteCarlo.samples", samples);
else if (integrator == GAUSS_LAGUERRE)
cfg.lookupValue("spatialIntegration.GaussLaguerre.samples", samples);
else if (integrator == GAUSS_HERMITE)
cfg.lookupValue("spatialIntegration.GaussHermite.samples", samples);
else if (integrator == INTERACTION_INTEGRATOR)
samples = 0;
else if (integrator == MONTE_CARLO_IS)
cfg.lookupValue("spatialIntegration.MonteCarloIs.samples", samples);
ostringstream convert;
convert << "_basisType-" << basisType << "_coordinateType-"<< coordinateType << "_dim-" << dim << "_integrator-" << integrator << "_samples-" << samples << "_nParticles-" << nParticles << "_w-" << w << "_L-" << L << "_shells-" << shells ;
fileName = baseName + convert.str() + ".mat";
return fileName;
}
//------------------------------------------------------------------------------
double MainApplication::correlationFactor(vec p)
{
double k = 0;
for(int i=0;i<(int)p.n_elem; i++)
k += pow(abs(p[i]),4);
return 1.0/k;
}
//------------------------------------------------------------------------------
void MainApplication::removeFiles()
{
string path;
string command;
cfg.lookupValue("systemSettings.SIpath", path);
// command = "cd " + path + "; ls";
command = "cd " + path + "; rm *" + fName("");
cout << command << endl;
system(command.c_str());
}
//------------------------------------------------------------------------------
| true |
07feb538e83337d292b00cbc2fc1f8450c008142 | C++ | sherrymou/CS240-CPP | /Lab3/Lab3.cpp | UTF-8 | 415 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include "Bank.h"
using namespace std;
int main(int argc, char *argv[]) {
if (atoi(argv[1])>1000){
cout << "Maximum 1000 customers" << endl;
return 1;
}else{
if (argc == 2){
Bank bank = Bank(atoi(argv[1]));
bank.menu();
}else if (argc == 3){
Bank bank = Bank(atoi(argv[1]), argv[2]);
bank.menu();
}
return 1;
}
}
| true |
964db0ce65f16bedf5bf89da73e7842207d42d6a | C++ | Sidebail/KnittedAndInflatable | /Plugins/SceneFusion/ThirdParty/SceneFusionAPI/Includes/ksQuaternion.h | UTF-8 | 17,637 | 2.609375 | 3 | [] | no_license | /*************************************************************************
*
* KINEMATICOUP CONFIDENTIAL
* __________________
*
* Copyright (2017-2020) KinematicSoup Technologies Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of KinematicSoup Technologies Incorporated and its
* suppliers, if any. The intellectual and technical concepts contained
* herein are proprietary to KinematicSoup Technologies Incorporated
* and its suppliers and may be covered by Canadian and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from KinematicSoup Technologies Incorporated.
*/
#pragma once
#include <iostream>
#include <cmath>
#include <string>
#include <stdexcept>
#include "Exports.h"
#include "ksVector3.h"
#define KS_PI 3.14159265358979323846264338327950288419716939937510
#define KS_DEGREES_TO_RADIANS 0.01745329251994329576923690768489
#define KS_RADIANS_TO_DEGREES 57.295779513082320876798154814105
#define KS_FDEGREES_TO_RADIANS 0.01745329251994329576923690768489f
#define KS_FRADIANS_TO_DEGREES 57.295779513082320876798154814105f
namespace KS
{
class EXTERNAL ksQuaternion
{
private:
Scalar m_values[4];
enum{ X = 0, Y = 1, Z = 2, W = 3 };
public:
/**
* Default constructor.
*/
ksQuaternion()
{
m_values[X] = (Scalar)0.0;
m_values[Y] = (Scalar)0.0;
m_values[Z] = (Scalar)0.0;
m_values[W] = (Scalar)1.0;
}
/**
* Copy constructor.
*/
ksQuaternion(const ksQuaternion& q)
{
m_values[X] = q.x();
m_values[Y] = q.y();
m_values[Z] = q.z();
m_values[W] = q.w();
}
/**
* Initialized constructor.
*/
ksQuaternion(Scalar x, Scalar y, Scalar z, Scalar w)
{
m_values[X] = x;
m_values[Y] = y;
m_values[Z] = z;
m_values[W] = w;
}
/**
* Destructor
*/
~ksQuaternion() {}
/* Component access */
Scalar& x() { return m_values[X]; }
Scalar& y() { return m_values[Y]; }
Scalar& z() { return m_values[Z]; }
Scalar& w() { return m_values[W]; }
const Scalar& x() const { return m_values[X]; }
const Scalar& y() const { return m_values[Y]; }
const Scalar& z() const { return m_values[Z]; }
const Scalar& w() const { return m_values[W]; }
Scalar& operator[] (const int index) { return m_values[index]; }
/**
* Return a vector component of this ksQuaternion
*
* @return ksVector3
*/
ksVector3 Vec() const
{
return ksVector3{ m_values[X], m_values[Y], m_values[Z] };
}
/**
* Return first nonzero component's sign. If all components are zeros, return true.
*
* @return bool
*/
bool GetFirstNonZeroComponentSign()
{
for (int i = 0; i < 4; i++)
{
if (m_values[i] != 0)
{
return m_values[i] > 0;
}
}
return true;
}
/**
* Rotation composition
*
* @param const ksQuaternion& q
* @return ksQuaternion
*/
inline ksQuaternion operator* (const ksQuaternion& q) const
{
double tw = (q.w() * m_values[W]) - (q.x() * m_values[X]) - (q.y() * m_values[Y]) - (q.z() * m_values[Z]);
double tx = (q.w() * m_values[X]) + (q.x() * m_values[W]) - (q.y() * m_values[Z]) + (q.z() * m_values[Y]);
double ty = (q.w() * m_values[Y]) + (q.x() * m_values[Z]) + (q.y() * m_values[W]) - (q.z() * m_values[X]);
double tz = (q.w() * m_values[Z]) - (q.x() * m_values[Y]) + (q.y() * m_values[X]) + (q.z() * m_values[W]);
return ksQuaternion{ (Scalar)tx, (Scalar)ty, (Scalar)tz, (Scalar)tw };
}
/**
* Rotates a vector by a ksQuaternion.
*
* @param ksVector3 point to rotate.
* @return ksVector3 rotated point.
*/
inline ksVector3 operator* (ksVector3 point)
{
double num1 = m_values[X] * 2.0f;
double num2 = m_values[Y] * 2.0f;
double num3 = m_values[Z] * 2.0f;
double num4 = m_values[X] * num1;
double num5 = m_values[Y] * num2;
double num6 = m_values[Z] * num3;
double num7 = m_values[X] * num2;
double num8 = m_values[X] * num3;
double num9 = m_values[Y] * num3;
double num10 = m_values[W] * num1;
double num11 = m_values[W] * num2;
double num12 = m_values[W] * num3;
ksVector3 result;
result.x() = (float)((1.0 - (num5 + num6)) * point.x() + (num7 - num12) * point.y() + (num8 + num11) * point.z());
result.y() = (float)((num7 + num12) * point.x() + (1.0 - (num4 + num6)) * point.y() + (num9 - num10) * point.z());
result.z() = (float)((num8 - num11) * point.x() + (num9 + num10) * point.y() + (1.0 - (num4 + num5)) * point.z());
return result;
}
/**
* Unary minus.
*
* @return ksQuaternion
*/
inline ksQuaternion operator- () const
{
return ksQuaternion{ -m_values[X], -m_values[Y], -m_values[Z], -m_values[W] };
}
/**
* Rotation composition
*
* @param const ksQuaternion& q
* @return ksQuaternion&
*/
inline ksQuaternion& operator*= (const ksQuaternion& q)
{
double tw = (q.w() * m_values[W]) - (q.x() * m_values[X]) - (q.y() * m_values[Y]) - (q.z() * m_values[Z]);
double tx = (q.w() * m_values[X]) + (q.x() * m_values[W]) - (q.y() * m_values[Z]) + (q.z() * m_values[Y]);
double ty = (q.w() * m_values[Y]) + (q.x() * m_values[Z]) + (q.y() * m_values[W]) - (q.z() * m_values[X]);
double tz = (q.w() * m_values[Z]) - (q.x() * m_values[Y]) + (q.y() * m_values[X]) + (q.z() * m_values[W]);
m_values[X] = (Scalar)tx;
m_values[Y] = (Scalar)ty;
m_values[Z] = (Scalar)tz;
m_values[W] = (Scalar)tw;
return *this;
}
/**
* Equivalence.
*
* @param const ksQuaternion& q
* @return bool
*/
inline bool operator== (const ksQuaternion& q)
{
return m_values[X] == q.x() && m_values[Y] == q.y() && m_values[Z] == q.z() && m_values[W] == q.w();
}
/**
* Not equivalence.
*
* @param const ksQuaternion& q
* @return bool
*/
inline bool operator!= (const ksQuaternion& q)
{
return !(*this == q);
}
/**
* Normalize the ksQuaternion
*/
void Normalize()
{
// Computation of length can overflow easily because it
// first computes squared length, so we first divide by
// the largest coefficient.
Scalar m = (m_values[X] < 0.0f) ? -m_values[X] : m_values[X];
Scalar absy = (m_values[Y] < 0.0f) ? -m_values[Y] : m_values[Y];
Scalar absz = (m_values[Z] < 0.0f) ? -m_values[Z] : m_values[Z];
Scalar absw = (m_values[W] < 0.0f) ? -m_values[W] : m_values[W];
m = (absy > m) ? absy : m;
m = (absz > m) ? absz : m;
m = (absw > m) ? absw : m;
//std::cout << " m = " << m << ", absy = " << absy << ", absz = " << absz << ", absw = " << absw << std::endl;
// Scaling
m_values[X] /= m;
m_values[Y] /= m;
m_values[Z] /= m;
m_values[W] /= m;
// Normalize
Scalar length = (Scalar)sqrt(
m_values[X] * m_values[X]
+ m_values[Y] * m_values[Y]
+ m_values[Z] * m_values[Z]
+ m_values[W] * m_values[W]);
m_values[X] /= length;
m_values[Y] /= length;
m_values[Z] /= length;
m_values[W] /= length;
}
/**
* Return the inverse of the ksQuaternion
*
* @return ksQuaternion inversed ksQuaternion
*/
ksQuaternion Inverse() const
{
ksQuaternion ksQuaternion2;
float num2 = (((m_values[X] * m_values[X])
+ (m_values[Y] * m_values[Y]))
+ (m_values[Z] * m_values[Z]))
+ (m_values[W] * m_values[W]);
float num = 1 / num2;
ksQuaternion2.x() = (m_values[X] == 0.0f) ? 0.0f : -m_values[X] * num;
ksQuaternion2.y() = (m_values[Y] == 0.0f) ? 0.0f : -m_values[Y] * num;
ksQuaternion2.z() = (m_values[Z] == 0.0f) ? 0.0f : -m_values[Z] * num;
ksQuaternion2.w() = m_values[W] * num;
return ksQuaternion2;
}
/**
* Constructs a ksQuaternion that rotates one vector to another.
*
* @param ksVector3 startDirection
* @param ksVector3 endDirection
* @return ksQuaternion
*/
static ksQuaternion FromVectorDelta(ksVector3 startDirection, ksVector3 endDirection)
{
ksQuaternion q;
ksVector3 a = ksVector3::Cross(startDirection, endDirection);
q.w() = (float)std::sqrt((startDirection.MagnitudeSquared()) * (endDirection.MagnitudeSquared())) + ksVector3::Dot(startDirection, endDirection);
q.x() = a.x();
q.y() = a.y();
q.z() = a.z();
q.Normalize();
return q;
}
/**
* Constructs a ksQuaternion from an axis-angle.
*
* @param ksVector3 axis of rotation.
* @param float angle of rotation in degrees.
* @return ksQuaternion
*/
static ksQuaternion FromAxisAngle(ksVector3 axis, float angle)
{
angle *= (float)KS_DEGREES_TO_RADIANS;
return FromAxisAngleRadians(axis, angle);
}
/**
* Constructs a ksQuaternion from an axis-angle.
*
* @param ksVector3 axis of rotation.
* @param float angle of rotation in radians.
* @return ksQuaternion
*/
static ksQuaternion FromAxisAngleRadians(ksVector3 axis, float angle)
{
if (axis.MagnitudeSquared() == 0)
throw std::runtime_error("axis cannot be 0 vector");
axis.Normalize();
ksVector3 v = axis * (float)std::sin(0.5 * angle);
ksQuaternion result(v.x(), v.y(), v.z(), (float)std::cos(0.5 * angle));
result.Normalize();
return result;
}
/**
* Converts the ksQuaternion to axis-angle representation.
*
* @param ksVector3 &axis of rotation.
* @param float &angle of rotation in degrees.
*/
void ToAxisAngle(ksVector3 &axis, float &angle)
{
ToAxisAngleRadians(axis, angle);
angle *= (float)KS_RADIANS_TO_DEGREES;
}
/**
* Converts the ksQuaternion to axis-angle representation.
*
* @param ksVector3 &axis of rotation.
* @param float &angle of rotation in radians.
*/
void ToAxisAngleRadians(ksVector3 &axis, float &angle)
{
if (m_values[X] == 0 && m_values[Y] == 0 && m_values[Z] == 0)
{
axis.x() = 1.0f;
axis.y() = 0.0f;
axis.z() = 0.0f;
}
else
{
ksVector3 v(m_values[X], m_values[Y], m_values[Z]);
v.Normalize();
axis = v;
}
double msin = std::sqrt(m_values[X] * m_values[X] + m_values[Y] * m_values[Y] + m_values[Z] * m_values[Z]);
double mcos = m_values[W];
if (msin != msin)
{
double maxcoeff = std::fmax(std::abs(X), std::fmax(std::abs(Y), std::abs(Z)));
double _x = m_values[X] / maxcoeff;
double _y = m_values[Y] / maxcoeff;
double _z = m_values[Z] / maxcoeff;
msin = std::sqrt(_x * _x + _y * _y + _z * _z);
mcos = m_values[W] / maxcoeff;
}
angle = (float)std::atan2(msin, mcos) * 2;
if (angle > KS_PI)
angle -= 2 * (float)KS_PI;
else if (angle <= -KS_PI)
angle += 2 * (float)KS_PI;
}
/**
* Dot product of two ksQuaternions.
*
* @param const ksQuaternion& ksQuaternion 1
* @param const ksQuaternion& ksQuaternion 2
* @return Scalar
*/
static Scalar Dot(const ksQuaternion& q1, const ksQuaternion& q2)
{
return q1.x() * q2.x() + q1.y() * q2.y() + q1.z() * q2.z() + q1.w() * q2.w();
}
/**
* Apply a ksQuaternion rotation to a vector
*
* @param const ksVector3& vector
* @param const ksQuaternion& ksQuaternion
* @return ksVector3
*/
static ksVector3 TransformVector(const ksVector3& v, const ksQuaternion& q)
{
ksVector3 t = 2.0f * ksVector3::Cross(q.Vec(), v);
return v + (q.w() * t) + ksVector3::Cross(q.Vec(), t);
}
/**
* Spherically interpolates between two ksQuaternions.
*
* @param ksQuaternion& from - ksQuaternion to interpolate from.
* @param ksQuaternion& to - ksQuaternion to interpolate to.
* @param float t - value between 0 and 1 that determines the amount of interpolation.
* @return ksQuaternion interpolated ksQuaternion.
*/
static ksQuaternion Slerp(const ksQuaternion& from, const ksQuaternion& to, float t)
{
float num2;
float num3;
ksQuaternion ksQuaternion;
float num = t;
float num4 = (((from.x() * to.x()) + (from.y() * to.y())) + (from.z() * to.z())) + (from.w() * to.w());
bool flag = false;
if (num4 < 0.0f)
{
flag = true;
num4 = -num4;
}
if (num4 > 0.999999f)
{
num3 = 1.0f - num;
num2 = flag ? -num : num;
}
else
{
float num5 = std::acos(num4);
float num6 = 1.0f / std::sin(num5);
num3 = std::sin((1.0f - num) * num5) * num6;
num2 = flag ? (-std::sin(num * num5) * num6) : std::sin(num * num5) * num6;
}
ksQuaternion.x() = (num3 * from.x()) + (num2 * to.x());
ksQuaternion.y() = (num3 * from.y()) + (num2 * to.y());
ksQuaternion.z() = (num3 * from.z()) + (num2 * to.z());
ksQuaternion.w() = (num3 * from.w()) + (num2 * to.w());
return ksQuaternion;
}
/**
* Rotates a ksQuaternion using angular displacement.
*
* @param ksQuaternion& ksQuaternion to rotate.
* @param ksVector3& angularDisplacement in radians.
* @return ksQuaternion
*/
static ksQuaternion AddAngularDisplacementRadians(const ksQuaternion& quaternion,
const ksVector3& angularDisplacement)
{
float x = angularDisplacement.x();
float y = angularDisplacement.y();
float z = angularDisplacement.z();
float magnitude = std::sqrt(x * x + y * y + z * z);
if (magnitude <= 0)
return quaternion;
float cos = std::cos(magnitude / 2.0f );
float sin = std::sin(magnitude / 2.0f );
ksQuaternion rot;
rot.x() = x * sin / magnitude;
rot.y() = y * sin / magnitude;
rot.z() = z * sin / magnitude;
rot.w() = cos;
ksQuaternion result;
result.x() = rot.w() * quaternion.x() + rot.x() * quaternion.w()
+ rot.y() * quaternion.z() - rot.z() * quaternion.y();
result.y() = rot.w() * quaternion.y() - rot.x() * quaternion.z()
+ rot.y() * quaternion.w() + rot.z() * quaternion.x();
result.z() = rot.w() * quaternion.z() + rot.x() * quaternion.y()
- rot.y() * quaternion.x() + rot.z() * quaternion.w();
result.w() = rot.w() * quaternion.w() - rot.x() * quaternion.x()
- rot.y() * quaternion.y() - rot.z() * quaternion.z();
return result;
}
/**
* String
*
* @return std::string
*/
std::string ToString()
{
return "X=" + std::to_string(m_values[X]) +
", Y=" + std::to_string(m_values[Y]) +
", Z=" + std::to_string(m_values[Z]) +
", W=" + std::to_string(m_values[W]);
}
};
}
#undef KS_PI
#undef KS_DEGREES_TO_RADIANS
#undef KS_RADIANS_TO_DEGREES
#undef KS_FDEGREES_TO_RADIANS
#undef KS_FRADIANS_TO_DEGREES | true |
0893cd06c4e7819d1f25e1d14d69d94ddc2a99e6 | C++ | Haar-you/kyopro-lib | /Mylib/Geometry/Float/intersect_segments.cpp | UTF-8 | 1,661 | 2.734375 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Mylib/Geometry/Float/ccw.cpp"
#include "Mylib/Geometry/Float/geometry_template.cpp"
namespace haar_lib {
namespace intersect_segments_impl {
enum status_t { INTERSECTED,
OVERLAPPED,
NOT_INTERSECTED,
SAME };
template <typename T>
struct result {
status_t status;
std::vector<point<T>> crosspoints;
bool is_intersected() const { return status == status_t::INTERSECTED; }
bool is_overlapped() const { return status == status_t::OVERLAPPED; }
bool is_not_intersected() const { return status == status_t::NOT_INTERSECTED; }
bool is_same() const { return status == status_t::SAME; }
};
} // namespace intersect_segments_impl
template <typename T>
auto intersect_segments(const segment<T> &a, const segment<T> &b) {
using namespace intersect_segments_impl;
const T cr = cross(a, b);
if (abs(cr) == 0) { // parallel
if (check_ccw(a.from, a.to, b.from).value * check_ccw(a.from, a.to, b.to).value <= 0 and
check_ccw(b.from, b.to, a.from).value * check_ccw(b.from, b.to, a.to).value <= 0) {
return result<T>({status_t::OVERLAPPED, {}});
} else {
return result<T>({status_t::NOT_INTERSECTED, {}});
}
}
const T t1 = cross(b.from - a.from, diff(b)) / cr;
const T t2 = cross(b.from - a.from, diff(a)) / cr;
if (t1 < 0 or t1 > 1 or t2 < 0 or t2 > 1) { // no crosspoint
return result<T>({status_t::NOT_INTERSECTED, {}});
}
return result<T>({status_t::INTERSECTED, {a.from + diff(a) * t1}});
}
} // namespace haar_lib
| true |
78457fd53cc4bc18ff9ee6cf67a7377e0afc3cdd | C++ | JesusandMechaGodzilla/CS270P4 | /prog4/prog4/msh.cpp | UTF-8 | 5,641 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <unistd.h>
#include <sys/wait.h>
#define DN "0"
using namespace std;
map<string, string> sub = { { "ShowTokens", "0" },{ "PATH", "/bin:/usr/bin" } };
int glob;
vector<string> procs, dprocs;
vector<int> pids;
void myHandler(int sig) {
pid_t p;
if ((p = waitpid(-1, &sig, WNOHANG)) != -1) {
glob = p;
for (unsigned int i = 0; i < pids.size(); i++) {
if (p == pids[i]) {
dprocs.push_back(procs[i]);
pids.erase(pids.begin() + i);
procs.erase(procs.begin() + i);
}
}
}
}
int startProcess(vector<string> tokens, int fun) {
char* temp[100];
pid_t pid;
string path = sub["PATH"];
int retval, status;
string proc = tokens[1];
for (unsigned int i = 0; i < tokens.size() - 1; i++) {
temp[i] = const_cast<char*>(tokens[i + 1].c_str());
}
temp[tokens.size() - 2] = '\0';
pid = fork();
if (pid == 0) {
retval = execvp(temp[0], temp);
if (retval == -1) {
perror("exec");
exit(0);
}
return -1;
}
else if (pid > 0) {
if (fun == 0) {
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
if (fun == 1) {
do {
waitpid(pid, &status, WNOHANG);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
procs.push_back(proc);
pids.push_back(pid);
}
return -1;
}
else {
return -1;
}
}
int setvar(vector <string> tokens) {
if (tokens[2] == DN) {
tokens.push_back(DN);
return 1;
}
else if (tokens[3] != DN) {
return 1;
}
else {
sub[tokens[1]] = tokens[2];
}
return -1;
}
int setdir(vector <string> tokens) {
//char* buf;
//buf = get_current_dir_name();
//cout << buf << endl;
if (tokens.size() == 0) {
fprintf(stderr, "MSH: expected argument to \"cd\"\n");
}
else {
sub["PATH"] = tokens[1];
char* temp = const_cast<char*>(tokens[1].c_str());
if (chdir(temp) != 0) {
perror("MSH");
}
}
// buf = get_current_dir_name();
// cout << buf << endl;
// free(buf);
return -1;
}
int setprompt(vector <string> tokens, string & prompt) {
if (tokens.size() > 3) {
cout << "Too many parameters to setprompt." << endl;
return -1;
}
else {
prompt = tokens[1];
return -1;
}
}
int showprocs() {
cout << "Background Processes: " << endl;
for (unsigned int i = 0; i < procs.size(); i++) {
cout << " " << procs[i] << endl;
}
return -1;
}
int done(vector <string> tokens) {
if (tokens.size() > 3) {
cout << "Too many parameters to done." << endl;
return -1;
}
else {
int retval;
if (tokens[1] == DN) {
return 0;
}
else {
if (!isdigit(tokens[1][0])) {
cout << "Parameter to done must be a non-negative integer." << endl;
return -1;
}
else {
retval = stoi(tokens[1]);
if (retval < 0) {
cout << "Parameter to done must be a non-negative integer." << endl;
return -1;
}
else {
return retval;
}
}
}
}
}
int tovar(vector <string> tokens) {
return 0;
}
string read(string input) {
string temp, output;
for (unsigned int i = 0; i<input.size(); i++) {
if (input[i] == '^') {
int j = i + 1;
while (input[j] != ' ' && input[j] != '"' && input[j] != '\0') {
temp = temp + input[j];
j++;
}
temp = sub.find(temp)->second;
if (input[j] == ' ') temp = temp + ' ';
output = output + temp;
i = j;
}
else {
output = output + input[i];
}
}
return output;
}
vector <string> tokenizer(string input) {
int count = -1;
string token = "";
vector <string> tokens;
char temp;
bool cont = true;
while (cont) {
count++;
temp = input[count];
if (temp == ' ') {
while (temp == ' ') {
count++;
temp = input[count];
}
}
if (temp == '"') {
count++;
temp = input[count];
while (temp != '"' && temp != '\0') {
token = token + temp;
count++;
temp = input[count];
}
tokens.push_back(token);
token = "";
}
else if (temp != ' ' && temp != '\0') {
while ((temp != ' ') && (temp != '\0')) {
token = token + temp;
count++;
temp = input[count];
}
tokens.push_back(token);
token = "";
temp = input[count];
}
if (temp == '\0' || temp == '#') {
cont = false;
}
}
tokens.push_back(DN);
return tokens;
}
int functions(vector <string> tokens, string & prompt) {
int endval;
if (sub["ShowTokens"] == "1") {
for (unsigned int i = 0; i < tokens.size() - 1; i++) {
cout << "Token : " << tokens[i] << endl;
}
}
if (tokens[0] == "setvar") {
if (tokens.size() > 4) {
cout << "expected 3 tokens, got " << tokens.size() - 1 << " tokens." << endl;
}
setvar(tokens);
}
else if (tokens[0] == "setprompt") {
setprompt(tokens, prompt);
}
else if (tokens[0] == "setdir") {
setdir(tokens);
}
else if (tokens[0] == "showprocs") {
showprocs();
}
else if (tokens[0] == "done") {
endval = done(tokens);
return endval;
}
else if (tokens[0] == "run") {
startProcess(tokens, 0);
}
else if (tokens[0] == "fly") {
startProcess(tokens, 1);
}
else if (tokens[0] == "tovar") {
tovar(tokens);
}
else if (tokens[0] == "0") {
}
else {
cout << "invalid command: " << tokens[0] << endl;
}
signal(SIGCHLD, myHandler);
while (dprocs.size() > 0) {
cout << "Completed: " << dprocs[dprocs.size() - 1] << endl;
dprocs.pop_back();
}
cout << prompt;
return -1;
}
void loop() {
string input, prompt = "msh > ";
vector <string> tokens;
int status = -1;
cout << prompt;
while (status < 0 && getline(cin, input)) {
input = read(input);
tokens = tokenizer(input);
status = functions(tokens, prompt);
tokens.clear();
}
}
int main() {
loop();
return 0;
}
| true |
706a234777a90de5ab03d1074b4e5d57f23cd0a4 | C++ | tt-jsr/VMEngine | /Assembler.cpp | UTF-8 | 24,273 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include "Assembler.h"
#include "Machine.h"
#include "Instructions.h"
#include "Data.h"
#include <iostream>
namespace
{
struct ParseContext;
void Throw(ParseContext& ctx, const char *msg);
struct ParseContext
{
std::string line;
int pos;
int lineno;
vm::Machine& machine;
ParseContext(vm::Machine& mach)
:pos(0)
,lineno(0)
,machine(mach)
{}
char Nextc()
{
if (line[pos] == '\0')
return line[pos];
++pos;
return line[pos];
}
bool IsField() {
return line[pos] == '/';
}
bool IsQuoted() {
return line[pos] == '\"';
}
bool IsDigit()
{
if (line[pos] >= '0' && line[pos] <= '9')
return true;
return false;
}
bool IsChar()
{
if (line[pos] == '\0' || line[pos] == ' ' || line[pos] == '\t')
return false;
return true;
}
bool IsWS()
{
if (line[pos] == ' ' || line[pos] == '\t')
return true;
return false;
}
char Getc() {return line[pos];}
};
void Throw(ParseContext& ctx, const char *msg)
{
std::stringstream strm;
strm << msg << " at line " << ctx.lineno;
throw std::exception(strm.str().c_str());
}
std::string CollectWord(ParseContext&);
std::string CollectQuoted(ParseContext&);
std::string CollectField(ParseContext&);
void SkipWS(ParseContext& ctx)
{
while (ctx.IsWS())
{
ctx.Nextc();
}
}
bool CollectInteger(ParseContext& ctx, int& n)
{
SkipWS(ctx);
if (ctx.IsDigit() == false)
{
return false;
}
std::string s = CollectWord(ctx);
if (s.size() == 0)
{
return false;
}
n = strtol(s.c_str(), nullptr, 0);
return true;
}
vm::Data CollectData(ParseContext& ctx)
{
SkipWS(ctx);
if (ctx.IsField())
{
std::string s = CollectField(ctx);
return vm::DataObj::CreateField(s);
}
if (ctx.IsQuoted())
{
std::string s = CollectQuoted(ctx);
return vm::DataObj::CreateString(s);
}
if (ctx.IsDigit())
{
int n = 0;
if (CollectInteger(ctx, n) == false)
{
return nullptr;
}
return vm::DataObj::CreateInt(n);
}
std::string s = CollectWord(ctx);
if (s == "true")
{
return vm::DataObj::CreateInt(1);
}
if (s == "false")
{
return vm::DataObj::CreateInt(0);
}
return vm::DataObj::CreateVariable(s);
}
std::string CollectLabel(ParseContext& ctx)
{
SkipWS(ctx);
return CollectWord(ctx);
}
std::string CollectWord(ParseContext& ctx)
{
std::stringstream strm;
SkipWS(ctx);
while (ctx.IsChar())
{
strm << ctx.Getc();
ctx.Nextc();
}
return strm.str();
}
std::string CollectQuoted(ParseContext& ctx)
{
std::stringstream strm;
ctx.Nextc(); // consume the "
while (ctx.Getc() != '\0' && ctx.Getc() != '"')
{
strm << ctx.Getc();
ctx.Nextc();
}
ctx.Nextc(); // consume the "
return strm.str();
}
std::string CollectField(ParseContext& ctx)
{
std::stringstream strm;
ctx.Nextc(); // consume the /
while (ctx.Getc() != '\0' && ctx.Getc() != '/')
{
strm << ctx.Getc();
ctx.Nextc();
}
ctx.Nextc(); // consume the /
return strm.str();
}
vm::Push *ParsePush(ParseContext& ctx)
{
SkipWS(ctx);
vm::Data p = CollectData(ctx);
vm::Push *pInst = new vm::Push(p);
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Pop *ParsePop(ParseContext& ctx)
{
vm::Pop *pInst = new vm::Pop();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Test *ParseTest(ParseContext& ctx)
{
vm::Test *pInst = new vm::Test();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::TestIm *ParseTestIm(ParseContext& ctx)
{
SkipWS(ctx);
vm::Data p = CollectData(ctx);
vm::TestIm *pInst = new vm::TestIm(p);
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Except *ParseExcept(ParseContext& ctx)
{
SkipWS(ctx);
std::string s = CollectQuoted(ctx);
if (s.empty())
{
Throw(ctx, "Expected message");
}
vm::Except *pInst = new vm::Except();
pInst->lineno = ctx.lineno;
pInst->msg = s;
return pInst;
}
vm::JumpEQ *ParseJumpEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpEQ *pInst = new vm::JumpEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::JumpNEQ *ParseJumpNEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpNEQ *pInst = new vm::JumpNEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::JumpGTEQ *ParseJumpGTEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpGTEQ *pInst = new vm::JumpGTEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::JumpGT *ParseJumpGT(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpGT *pInst = new vm::JumpGT();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::JumpLTEQ *ParseJumpLTEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpLTEQ *pInst = new vm::JumpLTEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::JumpLT *ParseJumpLT(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::JumpLT *pInst = new vm::JumpLT();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Jump *ParseJump(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::Jump *pInst = new vm::Jump();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContEQ *ParseContEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContEQ *pInst = new vm::ContEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContNEQ *ParseContNEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContNEQ *pInst = new vm::ContNEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContGTEQ *ParseContGTEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContGTEQ *pInst = new vm::ContGTEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContGT *ParseContGT(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContGT *pInst = new vm::ContGT();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContLTEQ *ParseContLTEQ(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContLTEQ *pInst = new vm::ContLTEQ();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::ContLT *ParseContLT(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::ContLT *pInst = new vm::ContLT();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Halt *ParseHalt(ParseContext& ctx)
{
vm::Halt *pInst = new vm::Halt();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Break *ParseBreak(ParseContext& ctx)
{
vm::Break *pInst = new vm::Break();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::CallLibrary *ParseCallLib(ParseContext& ctx)
{
std::string s = CollectWord(ctx);
if (s.empty())
{
Throw(ctx, "Expected library name");
}
vm::CallLibrary *pInst = new vm::CallLibrary();
pInst->funcname = s;
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Call *ParseCall(ParseContext& ctx, std::string& targetName)
{
SkipWS(ctx);
targetName = CollectLabel(ctx);
if (targetName.size() == 0)
{
Throw(ctx, "Target name is empty");
}
vm::Call *pCall = new vm::Call();
pCall->lineno = ctx.lineno;
pCall->funcname = targetName;
return pCall;
}
vm::Return *ParseReturn(ParseContext& ctx)
{
vm::Return *pInst = new vm::Return();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Inc *ParseInc(ParseContext& ctx)
{
vm::Inc *pInst = new vm::Inc();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Add *ParseAdd(ParseContext& ctx)
{
vm::Add *pInst = new vm::Add();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Subtract *ParseSubtract(ParseContext& ctx)
{
vm::Subtract *pInst = new vm::Subtract();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Multiply *ParseMultiply(ParseContext& ctx)
{
vm::Multiply *pInst = new vm::Multiply();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::IntDivide *ParseIntDivide(ParseContext& ctx)
{
vm::IntDivide *pInst = new vm::IntDivide();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Dec *ParseDec(ParseContext& ctx)
{
vm::Dec *pInst = new vm::Dec();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::And *ParseAnd(ParseContext& ctx)
{
vm::And *pInst = new vm::And();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Or *ParseOr(ParseContext& ctx)
{
vm::Or *pInst = new vm::Or();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Equal *ParseEqual(ParseContext& ctx)
{
vm::Equal *pInst = new vm::Equal();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::NotEqual *ParseNotEqual(ParseContext& ctx)
{
vm::NotEqual *pInst = new vm::NotEqual();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::LoadVariable *ParseLoadVariable(ParseContext& ctx)
{
SkipWS(ctx);
std::string s = CollectWord(ctx);
vm::LoadVariable *pInst = new vm::LoadVariable(s);
pInst->lineno = ctx.lineno;
return pInst;
}
vm::StoreVariable *ParseStoreVariable(ParseContext& ctx)
{
SkipWS(ctx);
std::string s = CollectWord(ctx);
vm::StoreVariable *pInst = new vm::StoreVariable(s);
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Dup *ParseDup(ParseContext& ctx)
{
vm::Dup *pInst = new vm::Dup();
pInst->lineno = ctx.lineno;
return pInst;
}
vm::Swap *ParseSwap(ParseContext& ctx)
{
vm::Swap *pInst = new vm::Swap();
pInst->lineno = ctx.lineno;
return pInst;
}
}
namespace vm
{
Assembler::Assembler(void)
:pMachine(nullptr)
{
}
Assembler::~Assembler(void)
{
}
Assembler::Label *Assembler::GetLabel(const std::string& name)
{
auto it = labels.find(name);
if (it == labels.end())
{
return nullptr;
}
return &(it->second);
}
void Assembler::AddLabel(const std::string& name, int lineno)
{
auto it = labels.find(name);
if (it == labels.end())
{
Label label;
label.name = name;
label.target = pMachine->code.Size();
label.lineno = lineno;
labels.insert(labels_t::value_type(name, label));
}
else
{
Label& label = it->second;
label.target = pMachine->code.Size();
label.lineno = lineno;
for each(Instruction *pInst in label.instructions)
{
pInst->SetLabelTarget(label.target);
}
}
}
void Assembler::AddLabelTarget(const std::string& name, Instruction *pInst)
{
auto it = labels.find(name);
if (it == labels.end())
{
Label label;
label.name = name;
label.instructions.push_back(pInst);
labels.insert(labels_t::value_type(name, label));
}
else
{
Label& label = it->second;
pInst->SetLabelTarget(label.target);
label.instructions.push_back(pInst);
}
}
void Assembler::Assemble(Machine& machine, std::istream& strm)
{
pMachine = &machine;
ParseContext ctx(machine);
while (strm.eof() == false)
{
std::string line;
std::getline(strm, line);
++ctx.lineno;
if (strm.eof())
{
break;
}
if (line.size() == 0)
{
continue;
}
ctx.line = line;
ctx.pos = 0;
SkipWS(ctx);
if (ctx.Getc() == ';' || ctx.Getc() == '\0')
continue;
//std::cout << line << std::endl;
std::string s = CollectWord(ctx);
if (s[0] == ':') // label
{
std::string label = s.substr(1);
Label *pLabel = GetLabel(label);
if (pLabel && pLabel->lineno >= 0)
{
std::stringstream strm;
strm << "Label " << label << " already defined at line " << pLabel->lineno;
Throw(ctx, strm.str().c_str());
}
AddLabel(label, ctx.lineno);
}
else if (s == "function")
{
std::string name = CollectWord(ctx);
if (name.empty())
{
Throw(ctx, "No function name");
}
machine.scriptfuncs.insert(Machine::scriptfuncs_t::value_type(name, machine.code.Size()));
// This means that function names and labels share the same namespace
Label *pLabel = GetLabel(name);
if (pLabel && pLabel->lineno >= 0)
{
std::stringstream strm;
strm << "Function " << name << " already defined at line " << pLabel->lineno;
Throw(ctx, strm.str().c_str());
}
AddLabel(name, ctx.lineno);
}
else if (s == "var")
{
std::string name = CollectWord(ctx);
SkipWS(ctx);
Data pData = nullptr;
if (ctx.IsQuoted())
{
std::string s = CollectQuoted(ctx);
pData = DataObj::CreateString(s);
}
else
{
std::string s = CollectWord(ctx);
int n = strtol(s.c_str(), nullptr, 0);
pData = DataObj::CreateInt(n);
}
machine.StoreGlobalVariable(name, pData);
}
else if (s == "test")
machine.code.AddInstruction( ParseTest(ctx));
else if (s == "testim")
machine.code.AddInstruction( ParseTestIm(ctx));
else if(s == "except")
{
machine.code.AddInstruction( ParseExcept(ctx) );
}
else if (s == "jumpe")
{
std::string targetName;
Instruction *pInst = ParseJumpEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jumpne")
{
std::string targetName;
Instruction *pInst = ParseJumpNEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jumpgte")
{
std::string targetName;
Instruction *pInst = ParseJumpGTEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jumpgt")
{
std::string targetName;
Instruction *pInst = ParseJumpGT(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jumplte")
{
std::string targetName;
Instruction *pInst = ParseJumpLTEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jumplt")
{
std::string targetName;
Instruction *pInst = ParseJumpLT(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "jump")
{
std::string targetName;
Instruction *pInst = ParseJump(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "conte")
{
std::string targetName;
Instruction *pInst = ParseContEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "contne")
{
std::string targetName;
Instruction *pInst = ParseContNEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "contgte")
{
std::string targetName;
Instruction *pInst = ParseContGTEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "contgt")
{
std::string targetName;
Instruction *pInst = ParseContGT(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "contlte")
{
std::string targetName;
Instruction *pInst = ParseContLTEQ(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "contlt")
{
std::string targetName;
Instruction *pInst = ParseContLT(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "calllib")
{
Instruction *pInst = ParseCallLib(ctx);
machine.code.AddInstruction(pInst);
}
else if (s == "call")
{
std::string targetName;
Instruction *pInst = ParseCall(ctx, targetName);
AddLabelTarget(targetName, pInst);
machine.code.AddInstruction( pInst );
}
else if (s == "halt")
machine.code.AddInstruction( ParseHalt(ctx));
else if (s == "break")
machine.code.AddInstruction( ParseBreak(ctx));
else if (s == "return")
machine.code.AddInstruction( ParseReturn(ctx));
else if (s == "inc")
machine.code.AddInstruction( ParseInc(ctx));
else if (s == "dec")
machine.code.AddInstruction( ParseDec(ctx));
else if (s == "add")
machine.code.AddInstruction( ParseAdd(ctx));
else if (s == "sub")
machine.code.AddInstruction( ParseSubtract(ctx));
else if (s == "mult")
machine.code.AddInstruction( ParseMultiply(ctx));
else if (s == "idiv")
machine.code.AddInstruction( ParseIntDivide(ctx));
else if (s == "or")
machine.code.AddInstruction( ParseOr(ctx));
else if (s == "and")
machine.code.AddInstruction( ParseAnd(ctx));
else if (s == "eq")
machine.code.AddInstruction( ParseEqual(ctx));
else if (s == "neq")
machine.code.AddInstruction( ParseNotEqual(ctx));
else if (s == "load")
machine.code.AddInstruction( ParseLoadVariable(ctx));
else if (s == "store")
machine.code.AddInstruction( ParseStoreVariable(ctx));
else if (s == "push")
machine.code.AddInstruction( ParsePush(ctx));
else if (s == "pop")
machine.code.AddInstruction( ParsePop(ctx));
else if (s == "dup")
machine.code.AddInstruction( ParseDup(ctx));
else if (s == "swap")
machine.code.AddInstruction( ParseSwap(ctx));
else
{
std::stringstream strm;
strm << "Unknown instruction " << s << " at line " << ctx.lineno;
throw std::exception (strm.str().c_str());
}
}
auto it = labels.begin();
for (; it != labels.end(); ++it)
{
Label &Label = it->second;
if (Label.lineno < 0)
{
std::stringstream strm;
strm << "Label " << Label.name << " is not defined";
throw std::exception (strm.str().c_str());
}
}
}
}
| true |
a0e6329abeaeb998ba87c8a440f2c310a055500b | C++ | limoiie/my-oj | /problems/leetcode035.h | UTF-8 | 505 | 2.96875 | 3 | [] | no_license | //
// Created by limoi on 2018/1/25.
//
// LeetCode 035 search insert position
#include <vector>
using namespace std;
class SolutionLeetCode035 {
public:
int searchInsert(vector<int> & nums, int target) {
int lt = 0, rt = static_cast<int>(nums.size()) - 1;
while (lt <= rt) {
int md = (lt + rt) >> 1;
if (nums[md] < target) {
lt = md + 1;
} else {
rt = md - 1;
}
}
return lt;
}
};
| true |
9320d3732a99a1b5f5e9a7e5ffd6d89652e3b7fb | C++ | OS2World/DEV-SAMPLES-VisualAgeCPP4_Samples | /ioc/graph/curve.h | UTF-8 | 4,500 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | /******************************************************************************
* .FILE: curve.h *
* *
* .COPYRIGHT: *
* IBM Open Class Library *
* Licensed Material - Program-Property of IBM *
* (C) Copyright IBM Corp. 1992, 1997 - All Rights Reserved *
* *
* .DISCLAIMER: *
* The following [enclosed] code is sample code created by IBM *
* Corporation. This sample code is not part of any standard IBM product *
* and is provided to you solely for the purpose of assisting you in the *
* development of your applications. The code is provided 'AS IS', *
* without warranty of any kind. IBM shall not be liable for any damages *
* arising out of your use of the sample code, even if they have been *
* advised of the possibility of such damages. *
* *
* .NOTE: WE RECOMMEND USING A FIXED SPACE FONT TO LOOK AT THE SOURCE *
* *
******************************************************************************/
#include <istring.hpp>
class Curve : public Graphics
{
public:
float ivXStart;
float ivYStart;
float ivXFix1;
float ivYFix1;
float ivXFix2;
float ivYFix2;
float ivXFix3;
float ivYFix3;
float ivXEnd;
float ivYEnd;
Curve(int graphicsKey, IString id,
float xstart, float ystart,
float xfix1, float yfix1,
float xfix2, float yfix2,
float xfix3, float yfix3,
float xend, float yend)
: Graphics(graphicsKey, id),
ivXStart(xstart),
ivYStart(ystart),
ivXFix1(xfix1),
ivYFix1(yfix1),
ivXFix2(xfix2),
ivYFix2(yfix2),
ivXFix3(xfix3),
ivYFix3(yfix3),
ivXEnd(xend),
ivYEnd(yend)
{ }
IBoolean operator== (Curve const& curve) const
{
return (this->ivXStart == curve.ivXStart &&
this->ivYStart == curve.ivYStart &&
this->ivXFix1 == curve.ivXFix1 &&
this->ivYFix1 == curve.ivYFix1 &&
this->ivXFix2 == curve.ivXFix2 &&
this->ivYFix2 == curve.ivYFix2 &&
this->ivXFix3 == curve.ivXFix3 &&
this->ivYFix3 == curve.ivYFix3 &&
this->ivXEnd == curve.ivXEnd &&
this->ivYEnd == curve.ivYEnd);
}
void draw() const
{
cout << "drawing "
<< Graphics::id()
<< endl
<< "with starting point: "
<< "(" << this->ivXStart << "|"
<< this->ivYStart << ")"
<< endl
<< "and with fix points: "
<< "(" << this->ivXFix1 << "|" << this->ivYFix1 << ")"
<< "(" << this->ivXFix2 << "|" << this->ivYFix2 << ")"
<< "(" << this->ivXFix3 << "|" << this->ivYFix3 << ")"
<< endl
<< "and with ending point: "
<< "(" << this->ivXEnd << "|" << this->ivYEnd << ")"
<< endl;
}
void lengthOfCurve() const
{
cout << "Length of "
<< Graphics::id()
<< " is: "
<< (sqrt(pow(((this->ivXFix1) - (this->ivXStart)),2)
+ pow(((this->ivYFix1) - (this->ivYStart)),2))
+ sqrt(pow(((this->ivXFix2) - (this->ivXFix1)),2)
+ pow(((this->ivYFix2) - (this->ivYFix1)),2))
+ sqrt(pow(((this->ivXFix3) - (this->ivXFix2)),2)
+ pow(((this->ivYFix3) - (this->ivYFix2)),2))
+ sqrt(pow(((this->ivXEnd) - (this->ivXFix3)),2)
+ pow(((this->ivYEnd) - (this->ivYFix3)),2)))
<< endl;
}
};
| true |
994b1361e0aec8b1509ae951fdaaa72b216c8df6 | C++ | cache-tlb/problem_solving | /leet_code/212.Word.Search.II.cpp | UTF-8 | 1,993 | 2.625 | 3 | [] | no_license | class Solution {
public:
bool dfs(int mat_i, int mat_j, int w_pos) {
if (mat[mat_i][mat_j] == str[w_pos] && w_pos == str.length() - 1) return true;
// if (w_pos >= str.length()) return true;
if (mat[mat_i][mat_j] != str[w_pos]) return false;
vis[mat_i*m+mat_j] = 1;
if (mat_i + 1 < n && !vis[(mat_i+1)*m + mat_j]) {
if (dfs(mat_i+1, mat_j, w_pos+1)) return true;
}
if (mat_i - 1 >= 0 && !vis[(mat_i-1)*m + mat_j]) {
if (dfs(mat_i-1, mat_j, w_pos+1)) return true;
}
if (mat_j + 1 < m && !vis[mat_i*m+mat_j+1]) {
if (dfs(mat_i, mat_j+1, w_pos+1)) return true;
}
if (mat_j - 1 >= 0 && !vis[mat_i*m+mat_j-1]) {
if (dfs(mat_i, mat_j-1, w_pos+1)) return true;
}
vis[mat_i*m+mat_j] = 0;
return false;
}
bool find(const string &word) {
if (m==1 && n==1) {
for (int i = 0; i < word.length(); i++) {
if (word[i] != mat[0][0]) return false;
}
return true;
}
vis.resize(m*n);
str = word;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
memset(&vis[0], 0, m*n*sizeof(int));
if (dfs(i, j, 0)) return true;
}
}
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
std::vector<string> ret;
mat = board;
n = board.size();
if (!n) return ret;
m = board[0].size();
if (!m) return ret;
std::set<string> w;
for (int i = 0; i < words.size(); i++) {
w.insert(words[i]);
}
for (std::set<string>::iterator it = w.begin(); it != w.end(); it++) {
if (find(*it)) ret.push_back(*it);
}
return ret;
}
std::vector<std::vector<char> > mat;
std::vector<int> vis;
string str;
int m,n;
};
| true |
6272457c02958a0bb6ad88d2cdb97d807c98aa2c | C++ | HadrienMarcellin/ProDroneTasks | /task2/src/main.cpp | UTF-8 | 1,197 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include "logger.hpp"
#include <chrono>
using namespace std;
// On utilise typename et non pas classe pour eviter les confusions
template<typename Type> Type calculerSomme(Type operande1, Type operande2)
{
Type resultat = operande1 + operande2;
return resultat;
}
int main(int argc, char *argv[])
{
std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
const char *log_file;
if(argc < 2)
{
std::cout << "Usage: " << argv[0] << " <log filename>" << std::endl;
std::cout << "Default file is log.txt" << std::endl;
log_file = "log.txt";
}
else
{
log_file = argv[1];
}
Logger mylogger(log_file, start_time);
mylogger.open_file();
//Do things
bool val1 = true;
bool val2 = false;
double val3 = 1.0;
double val4 = 4.0;
double res1 = mylogger.write_log_to_file(val1);
double res2 = mylogger.write_log_to_file(val2);
double res3 = mylogger.write_log_to_file(val3);
double res4 = mylogger.write_log_to_file(val4);
mylogger.close_file();
return 1;
}
| true |
e8e601d2d012fad9ca7f57cdddc352be0788356e | C++ | pointer20qt/wudi | /2-16test/autoptr.cpp | GB18030 | 738 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include"autoptr.h"
using namespace std;
class tool{
public:
int value = 0;
tool(){
cout << "tool" << endl;
}
tool(int t){
cout << ",t" << t << endl;
}
tool(const tool&){
cout << "tool" << endl;
}
tool(tool&&){
cout << "toolƶ" << endl;
}
~tool(){
cout << "tool" << endl;
}
tool& operator = (tool&&){
cout << "toolƶֵ" << endl;
return *this;
}
tool& operator = (const tool&){
cout << "toolֵ" << endl;
return *this;
}
};
void run()
{
_autoptr<tool>ptr1{ new tool };
_autoptr<tool>ptr2(ptr1);
_autoptr<tool>ptr3;
ptr3 = ptr2;
(*ptr2).value;
ptr2->value;
}
int main()
{
run();
} | true |
b924b59db86f9af5827ad9a1f7f94a9e68d0c7e0 | C++ | YichengZhong/Top-Interview-Questions | /剑指OfferII072.求平方根/mySqrt.cpp | UTF-8 | 180 | 2.75 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / 2;
}
return res;
}
}; | true |
6ed789a98bcd0890c26debf653c9583409e55c8c | C++ | emilianotca/Realocacao_Interplanetaria | /include/Linked_Queue.h | UTF-8 | 926 | 2.921875 | 3 | [] | no_license | //
// Created by emilianotca on 10-Jul-21.
//
#ifndef REALOCACAO_INTERPLANETARIA_LINKED_QUEUE_H
#define REALOCACAO_INTERPLANETARIA_LINKED_QUEUE_H
#include "../include/Queue.h"
#include "../include/Queue_Cell.h"
#include <string>
class Linked_Queue : public Queue
{
public:
Linked_Queue();
~Linked_Queue();
virtual void insert(std::string element_data) override; // Cell insertion method
virtual std::string remove() override; // Cell removal method
virtual int element_count() const override; // Returns the cell count
virtual bool is_empty() const override; // Tests queue emptiness
virtual void print() const override; // Print current elements in queue
void clear(); // Delete the cells
void queue_jump(int position); // Cut in the queue
private:
Queue_Cell* front; // Holds the head
Queue_Cell* back; // Holds the tail
};
#endif //REALOCACAO_INTERPLANETARIA_LINKED_QUEUE_H
| true |
755969704ede16b420bd3e03ff131038b76f6f5b | C++ | reenboog/cross_platform_client_crud_sample | /Classes/FilteredResultCell.cpp | UTF-8 | 1,845 | 2.734375 | 3 | [] | no_license | //
// FilteredResultCell.cpp
// ttt_c_tracker
//
// Created by Alex Gievsky on 30.10.15.
//
//
#include "FilteredResultCell.h"
using namespace cocos2d;
using namespace std;
FilteredResultCell::FilteredResultCell() {
_back = nullptr;
_labelCalories = nullptr;
_labelDate = nullptr;
}
FilteredResultCell::~FilteredResultCell() {
}
bool FilteredResultCell::init(const string &date, int calories) {
if(!TableViewCell::init()) {
return false;
}
{
// back
_back = Sprite::create("bg_item.png");
addChild(_back);
_back->setPosition(Point::ZERO);
_back->setAnchorPoint(Point::ZERO);
}
{
// caption
_labelDate = Label::createWithTTF(date, "helvetica.ttf", 18);
_labelDate->setColor({93, 93, 93});
_labelDate->setOpacity(0.7 * 255);
_labelDate->setAnchorPoint({0, 0.0});
_labelDate->setPosition({_back->getContentSize().width * 0.04f, _back->getContentSize().height * 0.12f});
_back->addChild(_labelDate);
}
{
// calories
_labelCalories = Label::createWithTTF(StringUtils::format("%i", calories), "helvetica.ttf", 31);
_labelCalories->setColor({53, 172, 225});
_labelCalories->setAnchorPoint({0, 1.0});
_labelCalories->setPosition({_back->getContentSize().width * 0.04f, _back->getContentSize().height * 0.94f});
_back->addChild(_labelCalories);
}
return true;
}
FilteredResultCell* FilteredResultCell::create(const string &date, int calories) {
FilteredResultCell *result = new FilteredResultCell();
if(result && result->init(date, calories)) {
result->autorelease();
return result;
} else {
delete result;
result = NULL;
return NULL;
}
} | true |
bd998ffbe5ebe3a5397968aba5d157e641412b12 | C++ | Futaba-Kosuke/algorithm | /atcoder/educational_dp/1/e_knapsack2.cpp | UTF-8 | 1,073 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1LL << 60;
const int MAX_V = 100001;
typedef struct product {
ll w;
ll v;
} product;
ll solve (ll N, ll W, vector<product> products) {
vector<vector<ll>> dp_table(N+1, vector<ll>(MAX_V, INF));
ll result = 0;
dp_table.at(0).at(0) = 0;
for (ll i = 0; i < N; i++) {
for (ll v = 0; v < MAX_V; v++) {
if (v < products.at(i).v) {
dp_table.at(i+1).at(v) = dp_table.at(i).at(v);
} else {
dp_table.at(i+1).at(v) = min(
dp_table.at(i).at(v),
dp_table.at(i).at(v-products.at(i).v) + products.at(i).w
);
}
}
}
for (ll v = 0; v < MAX_V; v++) {
if (dp_table.at(N).at(v) <= W) {
result = v;
}
}
return result;
}
int main (void) {
ll N, W;
scanf("%lld %lld", &N, &W);
vector<product> products(N);
for (ll i = 0; i < N; i++) {
scanf("%lld %lld", &products.at(i).w, &products.at(i).v);
}
ll result = solve(N, W, products);
printf("%lld\n", result);
return 0;
}
| true |
34933bc9f8cd1d5759ecefd58ff2fe296ccaf133 | C++ | asmith-git/utilities | /include/asmith/utilities/id_holder.hpp | UTF-8 | 1,757 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2017 Adam Smith
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ASMITH_UTILITIES_ID_HOLDER_HPP
#define ASMITH_UTILITIES_ID_HOLDER_HPP
#include "id_generator.hpp"
namespace asmith {
/*!
\brief An interface objects that are linked to ID numbers.
\param T The type of ID to manage
\version 0.0
\data Created : 16th June 2017 Modified : 16th June 2017
\author Adam Smith
*/
template<class T>
class id_holder {
public:
typedef T id_t;
virtual ~id_holder() throw() {}
virtual T get_id() const throw() = 0;
};
/*!
\brief
\param T The type of ID to manage
\version 0.0
\data Created : 16th June 2017 Modified : 16th June 2017
\author Adam Smith
*/
template<class T>
class id_holder_example : public_id_holder {
private:
id_generator<T>& mGenerator;
const T mID;
public:
id_holder_example(id_generator<T>& aGenerator) throw() :
mGenerator(aGenerator),
mID(aGenerator.generate())
{}
id_holder_example(id_generator<T>& aGenerator, T aID) throw() :
mGenerator(aGenerator),
mID(aID)
{
mGenerator.use(aID);
}
virtual ~id_holder_example() throw() {
mGenerator.free(mID);
}
// Inherited from id_holder
T get_id() const throw() override {
return mID;
}
};
}
#endif | true |
d51b92dbe157063fb0facf1a0aecbac390a69f4d | C++ | SubhrojyotiRoy271/friendly-octo-doodle | /CPP DS/Stackquestions.cpp | UTF-8 | 3,796 | 3.40625 | 3 | [] | no_license | //1.
//Nearest Greater Element to the right
#include<bits/stdc++.h>
using namespace std;
vector<int> solve(int arr[],int n)
{
vector<int> v;
stack<int> st;
for(int i=n-1;i>=0;i--)
{
if(st.empty())
v.push_back(-1);
else if(!st.empty() && st.top()>arr[i])
v.push_back(st.top());
else
{
while(!st.empty() && st.top()<=arr[i])
{
st.pop();
}
if(st.empty())
{
v.push_back(-1);
}
else
{
v.push_back(st.top());
}
}
st.push(arr[i]);
}
reverse(v.begin(),v.end());
return v;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n=5;
int arr[n]={4,5,2,10,8};
int testcase;
cin>>testcase;
while(testcase--)
{
vector<int> ans=solve(arr,n);
for(auto a:ans)
{
cout<<a<<" ";
}
cout<<endl;
}
return 0;
}
//2.
//Nearest greater element to left
//(for this we just have to start for loop from beginning and no need of reverse the vector in last)
vector<int> solve(int arr[],int n)
{
vector<int> v;
stack<int> st;
for(int i=0;i<n;i++)
{
if(st.empty())
v.push_back(-1);
else if(!st.empty() && st.top()>arr[i])
v.push_back(st.top());
else
{
while(!st.empty() && st.top()<=arr[i])
{
st.pop();
}
if(st.empty())
{
v.push_back(-1);
}
else
{
v.push_back(st.top());
}
}
st.push(arr[i]);
}
return v;
}
//3.
//Nearest Smaller to left
vector<int> solve(int arr[],int n)
{
vector<int> v;
stack<int> st;
for(int i=0;i<n;i++)
{
if(st.empty())
v.push_back(-1);
else if(!st.empty() && st.top()<arr[i])
v.push_back(st.top());
else
{
while(!st.empty() && st.top()>=arr[i])
{
st.pop();
}
if(st.empty())
{
v.push_back(-1);
}
else
{
v.push_back(st.top());
}
}
st.push(arr[i]);
}
return v;
}
//4.
//Nearest Smaller to right
vector<int> solve(int arr[],int n)
{
vector<int> v;
stack<int> st;
for(int i=n-1;i>=0;i--)
{
if(st.empty())
v.push_back(-1);
else if(!st.empty() && st.top()<arr[i])
v.push_back(st.top());
else
{
while(!st.empty() && st.top()>=arr[i])
{
st.pop();
}
if(st.empty())
{
v.push_back(-1);
}
else
{
v.push_back(st.top());
}
}
st.push(arr[i]);
}
reverse(v.begin(),v.end());
return v;
}
//5.
//Valid Parenthesis one solution
unordered_map<char,int> m={{'(',-1},{'{',-2},{'[',-3},{')',1},{'}',2},{']',3}};
bool isValid(string s)
{
stack<char> st;
int n=s.size();
for(int i=0;i<n;i++)
{
if(m[s[i]]<0)
{
st.push(s[i]);
}
else
{
if(st.empty()) return false;
char top=st.top();
st.pop();
if(m[top]+m[s[i]]!=0)
return false;
}
}
if(st.empty()) return true;
return false;
}
//5.
//Valid Parenthesis another solution for O(1) space
//6.
//stock span
vector <int> calculateSpan(int price[], int n)
{
vector<int> ans(n);
stack<int> s;
for(int i = 0; i < n; i++)
{
while(!s.empty() && price[s.top()] <= price[i])
s.pop();
ans[i] = s.empty() ? (i + 1) : (i - s.top());
s.push(i);
}
return ans;
}
//7.
//Maximum Area Histogram
long long getMaxArea(long long arr[], int n)
{
stack<int> s;
vector<long long> left(n),right(n);
for(int i=0;i<n;i++)
{
while(!s.empty() && arr[s.top()]>=arr[i]) s.pop();
left[i]=s.empty()? -1:s.top();
s.push(i);
}
while(!s.empty()) s.pop();
for(int i=n-1;i>=0;i--)
{
while(!s.empty() && arr[s.top()]>=arr[i]) s.pop();
right[i]=s.empty()? n:s.top();
s.push(i);
}
long long ans = 0;
for(int i = 0; i < n ; i ++)
{
ans = max(ans,(abs(right[i]-left[i])-1)*arr[i]);
}
return ans;
} | true |
0179cee19410683f9a19713eb21c9b4f45854e3e | C++ | Greeninguy/Hash-Table | /Project4/Students.h | UTF-8 | 825 | 3.203125 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#define STUDENTPTR StudentNode*
/*
Students Object is a linked list of StudentNodes used to store and organize Students.
*/
class Students
{
public:
/*
StudentNode Object holds Student information and a few functionalities.
*/
class StudentNode {
public:
STUDENTPTR before;
STUDENTPTR after;
StudentNode(int id, string last, string first, string year);
int getId();
string getLast();
string getFirst();
string getYear();
private:
int studentID;
string lastName;
string firstName;
string studentYear;
};
void insert(int id, string last, string first, string year);
bool remove(int id);
STUDENTPTR lastStudent();
Students();
~Students();
private:
STUDENTPTR root;
};
| true |
efd2e30ae2ac4078d7a07ec7b2836770d007ad15 | C++ | danildudchenko/Fifteens | /Hw1903fifteens/Source.cpp | UTF-8 | 3,486 | 3.328125 | 3 | [] | no_license | #include "Header.h"
void main()
{
cout << "You are playing fifteens!!!\n"
<< "Press w/a/s/d for making some turns\n";
srand(time(0));
char arr[ROWS][COLS] =
{
{ '1','2' ,'3' },
{ '4', '5', '6'},
{ '7',' ','8' },
};
char win[ROWS][COLS] =
{
{ '1','2' ,'3' },
{ '4', '5', '6'},
{ '7','8',' ' },
};
int answer4 = 0;
cout << "\n choose difficulty 1-ULTRA EASY(TEST),2-CASUAL,3-200iqDonbassPlayer";
cin >> answer4;
switch (answer4)
{
default:cout << "Wrong symbol!";
case 1:Randomise1(arr, ROWS, COLS); break;
case 2:Randomise2(arr, ROWS, COLS); break;
case 3:Randomise3(arr, ROWS, COLS); break;
}
int RowPos = 2;
int ColPos = 1;
srand(time(0));
bool end = false;
do
{
for (int i = 0; i < ROWS; i++)
{
cout << "|";
for (int j = 0; j < COLS; j++)
{
cout << arr[i][j] << "|";
}
cout << endl;
}
char answer = _getch();
switch (answer)
{
case 'W':case 'w':MoveUp(arr, ROWS, COLS); break;
case 'S':case 's':MoveDown(arr, ROWS, COLS); break;
case 'D':case 'd':MoveRight(arr, ROWS, COLS); break;
case 'A':case 'a':MoveLeft(arr, ROWS, COLS); break;
default:cout << "Wrong symbol!" << endl; break;
}
int answer2 = WinCondition(arr, win, ROWS, COLS);
system("cls");
if (answer2 == 1)
{
cout << "You won! ty for game" << endl;
end = true;
}
} while (end == false);
}
void Randomise1(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
for (int i = 0; i < 5; i++)
{
int a = 1 + rand() % 4;
switch (a)
{
case 1:MoveUp(arr, ROWS, COLS); break;
case 2:MoveDown(arr, ROWS, COLS); break;
case 3:MoveRight(arr, ROWS, COLS); break;
case 4:MoveLeft(arr, ROWS, COLS); break;
}
}
}
void Randomise2(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
for (int i = 0; i < 50; i++)
{
int a = 1 + rand() % 4;
switch (a)
{
case 1:MoveUp(arr, ROWS, COLS); break;
case 2:MoveDown(arr, ROWS, COLS); break;
case 3:MoveRight(arr, ROWS, COLS); break;
case 4:MoveLeft(arr, ROWS, COLS); break;
}
}
}
void Randomise3(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
for (int i = 0; i < 5000; i++)
{
int a = 1 + rand() % 4;
switch (a)
{
case 1:MoveUp(arr, ROWS, COLS); break;
case 2:MoveDown(arr, ROWS, COLS); break;
case 3:MoveRight(arr, ROWS, COLS); break;
case 4:MoveLeft(arr, ROWS, COLS); break;
}
}
}
void MoveUp(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
int vP = RowPos;
if (vP + 1 < 3 && vP >= 0)
{
arr[RowPos][ColPos] = arr[RowPos + 1][ColPos];
arr[RowPos + 1][ColPos] = ' ';
RowPos += 1;
}
}
void MoveDown(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
int vP = RowPos;
if (vP + 1 <= 3 && vP > 0)
{
arr[RowPos][ColPos] = arr[RowPos - 1][ColPos];
arr[RowPos - 1][ColPos] = ' ';
RowPos -= 1;
}
}
void MoveRight(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
int hP = ColPos;
if (hP + 1 <= 3 && hP > 0)
{
arr[RowPos][ColPos] = arr[RowPos][ColPos - 1];
arr[RowPos][ColPos - 1] = ' ';
ColPos -= 1;
}
}
void MoveLeft(char arr[ROWS][COLS], const int ROWS, const int COLS)
{
int hP = ColPos;
if (hP + 1 < 3 && hP >= 0)
{
arr[RowPos][ColPos] = arr[RowPos][ColPos + 1];
arr[RowPos][ColPos + 1] = ' ';
ColPos += 1;
}
}
int WinCondition(char arr[ROWS][COLS], char win[ROWS][COLS], const int ROWS, const int COLS)
{
int answer3;
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
if (arr[i][j] == win[i][j])
answer3 = 1;
else
return -1;
}
}
return 1;
}
| true |
a32a4e56bf0e95add0c5ac948e4fd4ec4e8ad676 | C++ | CharlesBaudelaire/code | /数组的储存用法.cpp | UTF-8 | 509 | 3.078125 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
int main(){
int num;
double a[5];
int count=0;
for (int i=0;i<5;i++){
scanf("%d",&num);
if(num==0) break;
else {
switch(num){
case 1:a[i] = 3.00;break;
case 2:a[i] = 2.50;break;
case 3:a[i] = 4.10;break;
case 4:a[i] = 10.20;break;
default: a[i] =0;
}
count++;
}
}
printf("[1] apple\n[2] pear\n[3] orange\n[4] grape\n[0] exit\n");
for(int i=0; i<count; i++){
printf("price = %.2f\n", a[i]);
}
}
| true |
e1f76023bc96bdd6b11ce8b8ea2294a759ec3e3a | C++ | Scarlehh/Data_Structures_Cpp | /ArrayList/src/main.cpp | UTF-8 | 253 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include "ArrayList.h"
int main() {
char arr[3] = {'a', 'b', 'c'};
ArrayList<char> list(arr, 3);
std::cout << list.remove(4) << "\n";
list.add('d');
list.add('d');
std::cout << list << "\n";
list.removeAll('d');
return 0;
}
| true |
c84fb03538f482bc7c5ba41d57b4ad9c788c4096 | C++ | paulin-mipt/hot-pursuit-game | /CarGame/CarGame/UI/Coord.h | UTF-8 | 836 | 2.5625 | 3 | [] | no_license | #pragma once
#include "GlobalDefinitions.h"
namespace UI {
// координаты в игре
struct CCoordinates {
float x;
float y;
float angle;
CCoordinates( float _x, float _y, float _angle = 0 ) :
x( _x ),
y( _y ),
angle( _angle )
{}
CCoordinates& operator=( const Core::CCoordinates &coord )
{
this->x = coord.x;
this->y = coord.y;
return *this;
}
Core::CCoordinates ConvertToCoreCoordinates()
{
return Core::CCoordinates( x, y );
}
};
// координаты в окне
struct CWindowCoordinates {
float x;
float y;
CWindowCoordinates( float _x = 0, float _y = 0 ) :
x( _x ),
y( _y )
{}
};
CWindowCoordinates transateToWcoord( float x, float y, float cellSize, CWindowCoordinates indent, CSize mapSize );
} | true |
a4b04f1448ffcb9bffe604d1f46dad58685329ae | C++ | CZXHenry/Digital-Image-Processing | /hw1/hw1/main.cpp | GB18030 | 3,903 | 2.984375 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <stdio.h>
#include <Windows.h>
#include <fstream>
#include <opencv2\opencv.hpp>
#include "DigitalImageProcessing.h"
using namespace cv;
using namespace std;
const string FilePath = "44.png";
const string FileName = "44";
int UI();
struct ImageSize GetSize();
int GetGreyLevel();
void CreateRequiredImage(Mat InputImage);
int main()
{
double **filter=new double*[3];
for (int i = 0; i < 3; i++)
{
filter[i] = new double[3]{ 1,1,1 };
}
Mat InputImage = imread("44.png", IMREAD_GRAYSCALE);
DigitalImageProcessing test;
Mat OutputImage = test.Filter2d(InputImage, 3, 3, filter);
imwrite("44_output.png", OutputImage);
return 0;
}
/*int main()
{
Mat InputImage=imread(FilePath, IMREAD_GRAYSCALE);
Mat OutputImage;
DigitalImageProcessing Test;
char *OutputFileName=new char;
char isQuit;
while (1)
{
switch (UI())
{
case 1:
{
OutputImage = Test.Scaling(InputImage, GetSize());
sprintf(OutputFileName, (FileName +"_%dx%d.png").c_str(), OutputImage.cols, OutputImage.rows);
break;
}
case 2:
{
int GreyLevel = GetGreyLevel();
OutputImage = Test.Quantization(InputImage, GreyLevel);
sprintf(OutputFileName, (FileName +"_GreyLevel_%d.png").c_str(), GreyLevel);
break;
}
case 3:
{
CreateRequiredImage(InputImage);
cout << "ȫͼƬɣ뵽ĿĿ¼²鿴" << endl;
break;
}
}
if (!OutputImage.empty())
{
imwrite(OutputFileName, OutputImage);
}
cout << "һ㣬Q˳" << endl;
cin >> isQuit;
if (isQuit == 'Q')
{
break;
}
else
{
system("cls");
}
fflush(stdin);
}
return 0;
}
int UI()
{
cout << "ͼϵͳª棩" << endl;
cout << "-------------------------" << endl;
cout << "1." << endl;
cout << "2." << endl;
cout << "3.ĿҪͼƬ" << endl;
cout << "빦ǰţʹ44.pngвʾ" << endl;
int chose;
cin >> chose;
return chose;
}
struct ImageSize GetSize()
{
int width, height;
cout << "ͼķijͿ" << endl;
cout << "width : ";
cin >> width;
cout << endl << "height : ";
cin >> height;
return ImageSize(width, height);
}
int GetGreyLevel()
{
int GreyLevel;
cout << "Ҷȼ : ";
cin >> GreyLevel;
return GreyLevel;
}
void CreateRequiredImage(Mat InputImage)
{
DigitalImageProcessing Test;
Mat OutputImage;
OutputImage = Test.Scaling(InputImage, struct ImageSize(192, 128));
imwrite("44_192x128.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(96, 64));
imwrite("44_96x64.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(48, 32));
imwrite("44_48x32.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(24, 16));
imwrite("44_24x16.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(12, 8));
imwrite("44_12x8.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(300, 200));
imwrite("44_300x200.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(450, 300));
imwrite("44_450x300.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(500, 200));
imwrite("44_500x200.png", OutputImage);
OutputImage = Test.Quantization(InputImage, 128);
imwrite("44_128.png", OutputImage);
OutputImage = Test.Quantization(InputImage, 32);
imwrite("44_32.png", OutputImage);
OutputImage = Test.Quantization(InputImage, 8);
imwrite("44_8.png", OutputImage);
OutputImage = Test.Quantization(InputImage, 4);
imwrite("44_4.png", OutputImage);
OutputImage = Test.Quantization(InputImage, 2);
imwrite("44_2.png", OutputImage);
OutputImage = Test.Scaling(InputImage, struct ImageSize(192, 128));
imwrite("44_192*128.png", OutputImage);
}*/ | true |
c4d4af681bf1bcac7b755b9e55e1dd6258b70029 | C++ | vankenobi/my_first_examples | /haftanin_gunleri.cpp | UTF-8 | 553 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
char harf;
cout << "A,B,C,D,E harflerinden birini giriniz: ";
cin >> harf;
if (harf == 'A'){
cout << "bugun gunlerden pazartesi.\n";
}
else if (harf == 'B'){
cout << "bugun gunlerden sali."<<endl;
}
else if (harf == 'C'){
cout << "bugun gunlerden carsamba.\n"<<endl;
}
else if (harf == 'D'){
cout << "bugun gunlerden persembe.\n";
}
else if (harf == 'E'){
cout << "bugun gunlerden cuma.\n"<<endl;
}
else{
cout << "bugun haftasonu."<<endl;
}
system("PAUSE");
}
| true |