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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
118f8e4c181938b2742df38e78560d8a2e351429 | C++ | rogalski/adventofcode-2017 | /day06/day06.cpp | UTF-8 | 2,894 | 3.40625 | 3 | [] | no_license | #include <set>
#include <vector>
#include <iostream>
#include <algorithm>
int findBanksWithMostBlocks(const std::vector<unsigned int> &banks)
{
return std::distance(banks.begin(), std::max_element(banks.begin(), banks.end()));
}
unsigned int countRedistributionCycles(std::vector<unsigned int> banks)
{
// TODO: using std::unsigned_set and custom hash for std::vector may help a lot
std::set< const std::vector<unsigned int> > history = {};
unsigned int redistributionCyclesCount = 0;
while (history.find(banks) == history.end()) // run until current bank state is re-encountered
{
history.insert(banks);
int index = findBanksWithMostBlocks(banks);
unsigned int countToRedistribute = banks[index];
unsigned int itemsToFillPerBank = countToRedistribute / (unsigned int) (banks.size() - 1); //floor div
int banksToFill = banks.size() - 1;
if (countToRedistribute > 0 && itemsToFillPerBank == 0)
{
banksToFill = countToRedistribute;
itemsToFillPerBank = 1;
}
unsigned int itemsToDecreaseAtCurrentBank = banksToFill * itemsToFillPerBank;
banks[index] = banks[index] - itemsToDecreaseAtCurrentBank;
for (unsigned int i=1; i<=banksToFill; i++)
{
int idx = (index+i) % banks.size();
banks[idx] += itemsToFillPerBank;
}
redistributionCyclesCount++;
}
return redistributionCyclesCount;
}
unsigned int getLoopSize(std::vector<unsigned int> banks)
{
std::vector< const std::vector<unsigned int> > history = {};
while (std::find(history.begin(), history.end(), banks) == history.end())
{
history.push_back(banks);
int index = findBanksWithMostBlocks(banks);
unsigned int countToRedistribute = banks[index];
unsigned int itemsToFillPerBank = countToRedistribute / (unsigned int) (banks.size() - 1); //floor div
int banksToFill = banks.size() - 1;
if (countToRedistribute > 0 && itemsToFillPerBank == 0)
{
banksToFill = countToRedistribute;
itemsToFillPerBank = 1;
}
unsigned int itemsToDecreaseAtCurrentBank = banksToFill * itemsToFillPerBank;
banks[index] = banks[index] - itemsToDecreaseAtCurrentBank;
for (unsigned int i=1; i<=banksToFill; i++)
{
int idx = (index+i) % banks.size();
banks[idx] += itemsToFillPerBank;
}
}
return std::distance(std::find(history.begin(), history.end(), banks), history.end());
}
int main()
{
std::vector<unsigned int> testData = {0, 2, 7, 0};
std::vector<unsigned int> part1Data = {0,5,10,0,11,14,13,4,11,8,8,7,1,4,12,11};
std::cout << "test1: " << std::endl << countRedistributionCycles(testData) << std::endl;
std::cout << "part1: " << std::endl << countRedistributionCycles(part1Data) << std::endl;
std::cout << "test2: " << std::endl << getLoopSize(testData) << std::endl;
std::cout << "part2: " << std::endl << getLoopSize(part1Data) << std::endl;
return 0;
}
| true |
68091782d6e55489fe37b6b03254e786ab7f4801 | C++ | KarlaSalamun/ECF | /ECF/cartesian/Xor.h | UTF-8 | 1,229 | 3.140625 | 3 | [
"MIT"
] | permissive | #ifndef Xor_h
#define Xor_h
#include "Function.h"
namespace cart
{
template <class T>
class Xor : public Function
{
public:
Xor();
Xor(uint numArgs);
~Xor();
void evaluate(voidP inputs, void* result);
};
typedef Xor<uint> XorUint;
template <class T>
Xor<T>::Xor()
{
name_ = "XOR";
numOfArgs_ = 2;
}
template <class T>
Xor<T>::Xor(uint numArgs)
{
name_ = "XOR";
numOfArgs_ = numArgs;
}
template <class T>
Xor<T>::~Xor()
{
}
template <class T>
void Xor<T>::evaluate(voidP inputs, void* result)
{
T& xor_ = *(T*) result;
stringstream ss;
ss << *((string*) inputs.get());
vector<T> readInputs;
T input, maxSize = 0;
uint i = 0;
//received inputs are in format: input1 sizeOfInput1 input2 sizeOfInput2 ...
//size of inputs are not important in XOR-ing because XOR will not produce leading 1's instead of
//leading 0's like NOT or XNOR function
while (ss >> input)
{
readInputs.push_back(input);
ss >> input;
if (input > maxSize)
{
maxSize = input;
}
i += 2;
if (i == 2 * numOfArgs_)
{
break;
}
}
xor_ = readInputs.at(0);
for (int i = 1; i < (int)numOfArgs_; i++)
{
xor_ ^= readInputs.at(i);
}
}
}
#endif /* Xor_h */
| true |
6e56a73738fe20770acb4083aeb96d05439f7077 | C++ | sidharth2189/CPP | /Concurrency/Multiple_Threads/Lambda_prevents_thread_interleaving.cpp | UTF-8 | 1,103 | 4.125 | 4 | [] | no_license | /*
Let's adjust the program code from Fork_Join_Parallelism.cpp and use a Lambda
instead of the function printHello(). Also, let's pass the loop counter i
into the Lambda to enforce an individual wait time for each thread. The idea
is to prevent the interleaving of text on the command line which we saw in
the previous example
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <vector>
int main()
{
// create threads
std::vector<std::thread> threads;
for (size_t i = 0; i < 10; ++i)
{
// create new thread from a Lambda
threads.emplace_back([i]() {
// wait for certain amount of time
std::this_thread::sleep_for(std::chrono::milliseconds(10 * i));
// perform work
std::cout << "Hello from Worker thread #" << i << std::endl;
});
}
// do something in main()
std::cout << "Hello from Main thread" << std::endl;
// call join on all thread objects using a range-based loop
for (auto &t : threads)
t.join();
return 0;
}
| true |
54c638f74e7f22a968232662d97e14487bfc5fc7 | C++ | fastlinemedia/arduino-utilities | /RgbLed.h | UTF-8 | 501 | 2.609375 | 3 | [] | no_license | #ifndef RgbLed_h
#define RgbLed_h
#include <Arduino.h>
class RgbLed {
public:
RgbLed(int redPin, int greenPin, int bluePin);
void begin();
void on();
void off();
void write(int red, int green, int blue);
void writeSpectrum(int from, int to);
private:
int _redPin;
int _greenPin;
int _bluePin;
int _spectrumColor = 0;
bool _spectrumReversed = false;
unsigned long _spectrumMillis = 0;
};
#endif
| true |
d64a53241a4830ad69af86155289c02803fe911d | C++ | HamedMasafi/QHtmlParser | /src/string_helper.cpp | UTF-8 | 1,765 | 3.3125 | 3 | [] | no_license | #include "string_helper.h"
#include <sstream>
#include <iostream>
#include <algorithm>
#include <wctype.h>
string_helper::string_helper()
{
}
void string_helper::ltrim(std::wstring &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
void string_helper::toupper(std::wstring &str)
{
transform(
str.begin(), str.end(),
str.begin(),
towupper);
}
void string_helper::tolower(std::wstring &str)
{
transform(
str.begin(), str.end(),
str.begin(),
towlower);
}
// trim from end (in place)
void string_helper::rtrim(std::wstring &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
void string_helper::trim(std::wstring &s) {
ltrim(s);
rtrim(s);
}
// trim from start (copying)
std::wstring string_helper::ltrim_copy(std::wstring s) {
ltrim(s);
return s;
}
// trim from end (copying)
std::wstring string_helper::rtrim_copy(std::wstring s) {
rtrim(s);
return s;
}
// trim from both ends (copying)
std::wstring string_helper::trim_copy(std::wstring s) {
trim(s);
return s;
}
bool string_helper::replace(std::wstring& str, const std::wstring& from, const std::wstring& to) {
size_t start_pos = str.find(from);
if(start_pos == std::wstring::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::vector<std::wstring> string_helper::split(std::wstring str, const wint_t &sep)
{
std::wstring temp;
std::vector<std::wstring> parts;
std::wstringstream wss(str);
while(std::getline(wss, temp, L';'))
parts.push_back(temp);
return parts;
}
| true |
e8bf14b113840d69d3f0e408fe8005b39d34c247 | C++ | ctorralba/C-Programming | /lab15/lab15.cpp | UTF-8 | 1,775 | 3.578125 | 4 | [] | no_license | /* Programmer: Christopher Torralba Date: 12/9/15
Section: F
Purpose: Create a Hang Man game.
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string.h>
using namespace std;
bool inWord (const char chosenWord[], const char guess);
int main ()
{
const short COLORNUM = 10;
const short COLORLENGTH = 20;
short counter = 0;
char myGuess, letterFound;
short tries = 5, colorIndex;
const string colors [COLORNUM] = {"black", "green", "blue", "grey",
"silver", "white", "red", "yellow",
"purple", "orange"};
char chosenWord[20];
char playArea[20] = {"-"};
srand(time(NULL));
cout << "Hangman" << endl;
cout << "Guess this color:" << endl;
colorIndex = rand() % COLORNUM;
strcpy(chosenWord, colors[colorIndex].c_str());
do
{
cout << "-";
counter++;
}while (counter != strlen(chosenWord));
cout << endl;
do
{
cout << "You have " << tries << " tries left " << endl;
cout << "Misses: " << endl;
cout << "Guess: ";
cin >> myGuess;
cout << endl;
if (!(inWord (chosenWord, myGuess)))
{
cout << "That letter isn't there" << endl;
tries--;
}
else
{
cout << "Found: " << endl;
for (short i = 0; i < strlen(chosenWord); i++)
{
if (myGuess != chosenWord[i])
{
playArea[i] = '-';
}
else
{
playArea[i] = myGuess;
}
}
cout << playArea;
cout << endl;
}
}while (tries != 0);
return 0;
}
bool inWord (const char chosenWord[], const char guess)
{
bool found = false;
for (short i = 0; i < 20; i++)
{
if (chosenWord[i] == guess)
{
found = true;
}
}
return (found);
}
| true |
e1d0d58677e7d303b6ae9769477b5a225d77a65f | C++ | max-crow/config | /xml_dom_safe_element_reference.h | UTF-8 | 2,341 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <list>
#include "config.h"
#include "xml_dom_reader.h"
XERCES_CPP_NAMESPACE_USE
namespace config {
struct element_description {
std::wstring name;
int number;
};
class xd_safe_element_reference
:public safe_element_reference
{
typedef std::list<element_description> xd_path;
//xd_safe_element_reference(const xd_safe_element_reference& src) {}
public:
xd_safe_element_reference(const xd_element& src) {
DOMNode* node = src.get_source();
file_uri = node->getOwnerDocument()->getDocumentURI();
for(; node!=NULL; node=node->getParentNode()) {
element_description new_item;
new_item.name = node->getNodeName();
new_item.number = 0;
for(DOMNode* sibling = node->getPreviousSibling(); sibling!=NULL; sibling = sibling->getPreviousSibling()) {
if(sibling->getNodeType() == DOMNode::ELEMENT_NODE && new_item.name == sibling->getNodeName()) {
new_item.number++;
}
}
path.push_front(new_item);
}
}
~xd_safe_element_reference() {
}
element_ptr get_element() const {
xd_reader::ptr reader(release_factory<xd_reader>::create_instance(file_uri));
DOMNode* node = reader->get_source()->getDocumentElement();
for(xd_path::const_iterator itr=path.begin(); itr!=path.end(); itr++) {
int i=0;
for(node = node->getFirstChild(); node!=NULL; node->getNextSibling()) {
if(node->getNodeType()==DOMNode::ELEMENT_NODE && itr->name == node->getNodeName()) {
if(itr->number <= i) {
assert(itr->number == i);
break;
} else {
i++;
}
}
}
assert(node!=NULL); //����� �� ������ ���� ��� ���������. ������ ���������. ������� path
if(node == NULL) {
//WARNING MaximV: exception
throw std::exception("Invalid path");
}
}
return xd_element::create_instance(node, reader);
}
private:
std::wstring file_uri;
xd_path path;
};
} | true |
22757d38461a0f3f787f52775f977adcd078b6f8 | C++ | Coomman/ITMO-HW | /ADS/Lab 2.4/Path.cpp | UTF-8 | 1,629 | 3.09375 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Edge {
int from, to;
long long w;
Edge(int a, int b, long long c) {
from = a;
to = b;
w = c;
}
};
struct Vertex {
bool checked = false;
long double dist = (long double)INT64_MAX;
vector<Edge*> list;
};
int v, e, START;
vector<Vertex> ver;
vector<Edge*> edges;
void dfs(int n) {
ver[n].checked = true;
for (Edge* e : ver[n].list) {
if (!ver[e->to].checked && ver[n].dist < INT64_MAX) {
dfs(e->to);
}
}
}
void BellmanFord() {
bool flag;
for (int i = 0; i < v - 1; i++) {
flag = false;
for (Edge* e : edges) {
if (ver[e->from].dist < INT64_MAX && ver[e->to].dist > ver[e->from].dist + e->w) {
ver[e->to].dist = ver[e->from].dist + e->w;
flag = true;
}
}
if (!flag) {
break;
}
}
if (flag) {
for (Edge* e : edges) {
if (ver[e->to].dist > ver[e->from].dist + e->w && !ver[e->to].checked) {
dfs(e->to);
}
}
}
}
int main() {
ifstream in("path.in");
freopen("path.out", "w", stdout);
in >> v >> e >> START;
ver.resize(v + 1);
ver[START].dist = 0;
for (int i = 0; i < e; i++) {
int a, b; long long c; in >> a >> b >> c;
Edge* e = new Edge(a, b, c);
ver[a].list.push_back(e);
edges.push_back(e);
}
BellmanFord();
for (int i = 1; i <= v; i++) {
if (ver[i].dist == INT64_MAX) {
cout << '*';
}
else {
if (ver[i].checked) {
cout << '-';
}
else {
printf("%.0f", ver[i].dist);
}
}
cout << endl;
}
} | true |
8c70f6b03ee557d1230e5352f70eeb0734342a58 | C++ | robotil/robil | /C31_PathPlanner/src/MapFileReader.hpp | UTF-8 | 2,473 | 2.8125 | 3 | [] | no_license | /*
* MapFileReader.hpp
*
* Created on: Mar 3, 2013
* Author: dan
*/
#ifndef MAPFILEREADER_HPP_
#define MAPFILEREADER_HPP_
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
namespace map_file_reader{
using namespace std;
struct CanNotOpenFile{};
struct CanNotFindDimentions{};
struct Dim{ int w; int h; bool reversed; };
static Dim getDim(const vector<string>& lines){
if(lines.size()<2) throw CanNotFindDimentions();
Dim d={0,0, false};
stringstream ww(lines[0]);
while(ww>>d.w);
stringstream h1(lines[1]);
stringstream h2(lines[lines.size()-1]);
h1>>d.h;
if(d.h==0){
h2>>d.h;
d.reversed=false;
}else{
d.reversed=true;
}
d.w+=1;
d.h+=1;
return d;
}
static vector<char> readMap(string fname, size_t& w, size_t& h, bool verb=false){
ifstream f(fname.c_str());
stringstream sl;
string line;
vector<string> lines;
//int w,h;
vector<char> map;
while( getline(f, line) ){
lines.push_back(line);
}
Dim dim = getDim(lines);
w = dim.w; h=dim.h;
if(verb) cout<<"Dim: "<<w<<"x"<<h<<(dim.reversed?" reversed":"")<<endl;
size_t s, e, inc;
if(dim.reversed){
s=1+dim.h-1; e=0; inc=-1;
}else{
s=1; e=s+dim.h; inc=1;
}
for(size_t i=s; i!=e; i+=inc){
stringstream sl(lines[i]);
int n;
if(!(sl>>n)) break;
while(true){
char c;
if(!(sl>>c)) break;
if(c=='-' || c=='.' || c=='B'){
if(c=='.') n=0;
if(c=='-') n=2;
if(c=='B') n=1;
}
//cout<<n;
if(verb) cout<<c;
map.push_back((char)n);
}
if(verb) cout<<endl;
}
return map;
}
static vector<double> readAltMap(string fname, size_t& w, size_t& h, double min, double max, bool reverse_colors, bool verb=false){
ifstream f(fname.c_str());
stringstream sl;
string line;
vector<string> lines;
//int w,h;
vector<double> map;
while( getline(f, line) ){
//cout<<line<<endl;
lines.push_back(line);
}
Dim dim = getDim(lines);
w = dim.w; h=dim.h;
if(verb) cout<<"Dim: "<<w<<"x"<<h<<(dim.reversed?" reversed":"")<<endl;
size_t s, e, inc;
if(dim.reversed){
s=1+dim.h-1; e=0; inc=-1;
}else{
s=1; e=s+dim.h; inc=1;
}
for(size_t i=s; i!=e; i+=inc){
stringstream sl(lines[i]);
double n;
int nline;
if(!(sl>>nline)) break;
while(true){
int c;
if(!(sl>>c)) break;
if(reverse_colors) c=255-c;
n=((double)c/255.0)*(max-min)-min;
//cout<<n;
if(verb) cout<<c;
map.push_back(n);
}
if(verb) cout<<endl;
}
return map;
}
}
#endif /* MAPFILEREADER_HPP_ */
| true |
426f8fc731b5465d449edb38fded2cb8c40a859b | C++ | rhythm-3099/Basic-Algorithms | /StackQueue/maximum_area_histogram.cpp | UTF-8 | 2,244 | 2.546875 | 3 | [] | no_license | // WOOF!!
#include <bits/stdc++.h>
#include <time.h>
using namespace std;
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define str string
#define FOR(i,a,b) for(ll i=a;i<b;i++)
#define FILL(a,b) memset((a),(b),sizeof((a)))
#define precision(x,d) cout<<fixed<<setprecision(d)<<x
#define minQueue priority_queue<ll,vector<ll>,greater<ll> >
#define maxQueue priority_queue<ll,vector<ll>,less<ll> >
#define deb1(x) cout<<#x<<" : "<<x<<endl;
#define deb2(x,y) cout<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl;
#define deb3(x,y,z) cout<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl;
#define FAST ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define READ freopen("input.txt","r",stdin);
#define WRITE freopen("output.txt","w",stdout);
#define RANDOM srand(time(NULL));
#define MOD 1000000007
#define NAX 1000005
#define INF LONG_LONG_MAX
#define MINF LONG_LONG_MIN
/*
Find the largest rectangular area possible in a given histogram where
the largest rectangle can be made of a number of contiguous bars.
For simplicity, assume that all bars have same width and the width is 1 unit.
*/
int main()
{
FAST;
ll i,j,k,n,m,t;
cin>>n;
vector<ll>a(n);
for(i=0;i<n;i++)
cin>>a[i];
stack<ll>s;
vector<pair<ll,ll> >ind(n);
for(i=0;i<n;i++){
if(s.empty()){
ind[i].first=-1;
} else if(a[s.top()]<a[i]){
ind[i].first=s.top();
} else {
while(!s.empty() && a[s.top()]>=a[i]){
s.pop();
}
if(s.empty()){
ind[i].first=-1;
} else {
ind[i].first=s.top();
}
}
s.push(i);
}
while(!s.empty())
s.pop();
for(i=n-1;i>=0;i--){
if(s.empty())
ind[i].second=n;
else if(a[i]>a[s.top()]){
ind[i].second=s.top();
} else {
while(!s.empty() && a[s.top()]>=a[i]){
s.pop();
}
if(s.empty()){
ind[i].second=n;
} else {
ind[i].second=s.top();
}
}
s.push(i);
}
ll maxArea=INT_MIN;
for(i=0;i<n;i++){
k = ind[i].second-ind[i].first-1;
maxArea = max(maxArea, k*a[i]);
}
cout<<maxArea;
cout<<endl;
return 0;
} | true |
403ed6edf288c01316e16ecd3bcb4275b5ec6c66 | C++ | AlcoDreamer/myOpenGlProject | /Headers/Keyboard.h | UTF-8 | 1,333 | 2.59375 | 3 | [] | no_license | //
// Keyboard.h
// MyProject
//
// Created by dchernyshev on 07.11.17.
// Copyright © 2017 dchernyshev. All rights reserved.
//
#ifndef Keyboard_h
#define Keyboard_h
#include <Glut/glut.h>
#include <map>
void keyDown(unsigned char key, int x, int y);
void keyUp(unsigned char key, int x, int y);
void specialKeyDown(int key, int x, int y);
void specialKeyUp(int key, int x, int y);
class Keyboard
{
public:
Keyboard();
~Keyboard();
void beginNewFrame();
void check();
void keyUpEvent(unsigned char key);
void keyDownEvent(unsigned char key);
bool wasKeyPressed(unsigned char key);
bool wasKeyReleased(unsigned char key);
bool isKeyHeld(unsigned char key);
void forgеtKey(unsigned char key);
void specialKeyUpEvent(int key);
void specialKeyDownEvent(int key);
bool wasSpecialKeyPressed(int key);
bool wasSpecialKeyReleased(int key);
bool isSpecialKeyHeld(int key);
void forgеtSpecialKey(int key);
private:
std::map < unsigned char, bool > _heldKeys;
std::map < unsigned char, bool > _pressedKeys;
std::map < unsigned char, bool > _releasedKeys;
std::map < int, bool > _heldSpecialKeys;
std::map < int, bool > _pressedSpecialKeys;
std::map < int, bool > _releasedSpecialKeys;
};
#endif /* Keyboard_h */
| true |
31b9d957d2e5a5a7e63127e5f975e10bf06472cc | C++ | VanshRuhela/DSA-Practice | /Adv Trees/AVL Trees/insertion.cpp | UTF-8 | 750 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int s, r , c;
cin>>s>>r>>c;
vector< vector<int>> m;
int k = s;
for(int i=0; i<r; i++){
vector<int> col (c);
for(int j =0; j<c; j++){
col[j] = k;
k++;
}
m.push_back(col);
}
// transpose
vector< vector<int>> t( c, vector<int> (r, 0));
for(int i=0; i<c; i++){
for(int j =0; j<r; j++){
t[i][j] = m[j][i];
}
}
for(int i=0; i<r; i++){
for(int j =0; j<r; j++){
int sum =0;
for(int k =0; k<c; k++){
sum += m[i][k] * t[k][j];
}
cout << sum <<" ";
}
cout << "\n";
}
return 0;
} | true |
157f2dc7fb1c705d42afed49b2c3ae2667161173 | C++ | AKavrani7/CP-for-Fun | /InterviewBit/Math/Rearrange Array.cpp | UTF-8 | 574 | 2.875 | 3 | [] | no_license | void Solution::arrange(vector<int> &arr) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
// https://www.interviewbit.com/problems/rearrange-array/
int n = arr.size();
for(int i=0; i<n; i++)
{
arr[i] = arr[i] + (arr[arr[i]]%n)*n;
}
for(int i=0; i<n; i++)
{
arr[i] = arr[i]/n;
}
}
| true |
53f2732103ff952530bde2ce7b03a031302ecd98 | C++ | muhamdasim/CPP | /Basic C++ Concepts/paper/3.cpp | UTF-8 | 345 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
void arraya(int *ptr,int n)
{
for (int i=0 ; i<n ; i++)
{
cout<<*(ptr+i);
}
}
int main()
{
int size=100;
int n;
cout <<"Enter size of array"<<endl;
cin>>n;
int array[size];
int *pt
ptr=array;
for (int i=0 ; i<n ; i++)
{
cin>>array[i];
}
arraya(ptr , n);
return 0;
}
| true |
c759ac7d9cfe7cffb1df44edb1b777072299cb7f | C++ | MatTerra/simuladorCamadaFisica | /src/BinaryUtils.cpp | UTF-8 | 442 | 3 | 3 | [] | no_license | //
// Created by mateusberardo on 31/03/2021.
//
#include "BinaryUtils.h"
bitStream toBinary(std::string input) {
bitStream output;
for (char &_char : input)
output.insert(output.end(), std::bitset<8>(_char));
return output;
}
std::string fromBinary(bitStream bits) {
std::string output;
for (auto &byte : bits) {
const char c = char(byte.to_ulong());
output += c;
}
return output;
}
| true |
b1040ec0e35ae076fca4c9afb80c20f16cefcd0b | C++ | zeos/signalflow | /source/src/node/operators/sum.cpp | UTF-8 | 1,782 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "signalflow/core/core.h"
#include "signalflow/node/operators/sum.h"
#include "signalflow/node/oscillators/constant.h"
namespace signalflow
{
Sum::Sum()
{
this->name = "sum";
this->has_variable_inputs = true;
}
Sum::Sum(std::initializer_list<NodeRef> inputs)
: Sum()
{
for (NodeRef input : inputs)
{
this->add_input(input);
}
}
Sum::Sum(std::vector<NodeRef> inputs)
: Sum()
{
for (NodeRef input : inputs)
{
this->add_input(input);
}
}
Sum::Sum(std::vector<float> inputs)
: Sum()
{
for (float input : inputs)
{
this->add_input(new Constant(input));
}
}
Sum::Sum(std::vector<int> inputs)
: Sum()
{
for (int input : inputs)
{
this->add_input(new Constant(input));
}
}
void Sum::process(Buffer &out, int num_frames)
{
for (int channel = 0; channel < this->num_output_channels; channel++)
{
memset(this->out[channel], 0, sizeof(sample) * num_frames);
for (NodeRef input : this->input_list)
{
for (int frame = 0; frame < num_frames; frame++)
{
out[channel][frame] += input->out[channel][frame];
}
}
}
}
void Sum::add_input(NodeRef input)
{
this->input_list.push_back(input);
std::string input_name = "input" + std::to_string(this->input_index++);
this->Node::create_input(input_name, input_list.back());
}
void Sum::remove_input(NodeRef input)
{
this->input_list.remove(input);
}
void Sum::set_input(std::string name, const NodeRef &node)
{
if (this->inputs.find(name) == this->inputs.end())
{
this->input_list.push_back(node);
this->Node::create_input(name, input_list.back());
}
this->Node::set_input(name, node);
}
}
| true |
814b9f2d20b31b7ebdf211a8c7142f035c7f4601 | C++ | kakashibo/SPOJ-CODECHEF | /Elections/main.cpp | UTF-8 | 898 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int ar[1000];
long long int total[1000]={0};
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++){
//total[i]=0;
for(int j=0;j<n;j++){
cin>>ar[j];
//total[j]+=ar[i][j];
// cout<<total[j]<<" ";
}
int max=ar[0];int w=0;
for(int j=1;j<n;j++){
if(max<ar[j]){
max=ar[j];
w=j;
}
}
//cout<<w<<"-";
total[w]++;
}
int ans=0;long int max=-1;
for(int i=0;i<n;i++){
//cout<<total[i]<<endl;
if(max<total[i]){
max=total[i];
ans=i+1;
}
}
cout<<ans<<endl;
//cout << "Hello world!" << endl;
return 0;
}
| true |
6386e812bec9ff23205731427d5f718bfba9ae77 | C++ | LYoGA/ACM | /Graph theory/CC/POJ3694.cpp | UTF-8 | 2,392 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
const int MAXN = 100005;
struct Edge{
int to, next;
}edge[MAXN * 5];
int head[MAXN], tot;
int Low[MAXN], DFN[MAXN];
int Index, top;
int bridge;
int n, m;
int f[MAXN], ancestor[MAXN];
int find(int x) {
return x == f[x] ? x : f[x] = find(f[x]);
}
bool Union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa != pb) {
f[pa] = pb;
return true;
}
return false;
}
void addedge(int u, int v) {
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void Tarjan(int u, int pre) {
int v;
Low[u] = DFN[u] = ++Index;
for (int i = head[u]; i != -1; i = edge[i].next) {
v = edge[i].to;
if (v == pre) continue;
if (!DFN[v]) {
Tarjan(v, u);
ancestor[v] = u;
if (Low[u] > Low[v]) Low[u] = Low[v];
if (Low[v] > DFN[u])
bridge++;
else
Union(u, v);
}
else if (Low[u] > DFN[v])
Low[u] = DFN[v];
}
}
void init() {
memset(head, -1, sizeof(head));
memset(DFN, 0, sizeof(DFN));
tot = 0;
Index = top = 0;
bridge = 0;
memset(ancestor, 0, sizeof(ancestor));
for (int i = 1; i <= n; i++)
f[i] = i;
}
void solve() {
for (int i = 1; i <= n; i++)
if (!DFN[i])
Tarjan(i, -1);
}
void lca(int u, int v) {
while (u != v) {
while (DFN[u] >= DFN[v] && u != v) {
if (Union(u, ancestor[u]))
bridge--;
u = ancestor[u];
}
while (DFN[v] >= DFN[u] && u != v) {
if (Union(v, ancestor[v]))
bridge--;
v = ancestor[v];
}
}
}
int main() {
int t = 1;
while (scanf("%d%d", &n, &m)) {
if (n == 0 && m == 0) break;
init();
int u, v;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
addedge(u, v);
addedge(v, u);
}
solve();
printf("Case %d:\n", t++);
int k;
scanf("%d", &k);
while (k--) {
scanf("%d%d", &u, &v);
lca(u, v);
printf("%d\n", bridge);
}
printf("\n");
}
return 0;
}
| true |
00ef07997c1830a41d34a847b5299e26e19aadf0 | C++ | CollegeComputing/USTC-Compilers-Principles | /labs/HW6/repo/src/SyntaxTreePrinter.cpp | UTF-8 | 3,470 | 3.296875 | 3 | [
"MIT"
] | permissive | #include "SyntaxTreePrinter.h"
#include <map>
#include <string>
#include <iostream>
using namespace SyntaxTree;
std::map<Type, std::string> type2str = {
{Type::INT, "int"},
{Type::FLOAT, "float"},
{Type::VOID, "void"}
};
std::map<BinOp, std::string> binop2str = {
{BinOp::PLUS, "+"},
{BinOp::MINUS, "-"},
{BinOp::MULTIPLY, "*"},
{BinOp::DIVIDE, "/"},
{BinOp::MODULO, "%"}
};
std::map<UnaryOp, std::string> unaryop2str = {
{UnaryOp::PLUS, "+"},
{UnaryOp::MINUS, "-"}
};
void SyntaxTreePrinter::print_indent()
{
for (int i = 0; i < indent; i++)
std::cout << " ";
}
void SyntaxTreePrinter::visit(Assembly &node)
{
indent = 0;
for (auto def : node.global_defs) {
def->accept(*this);
}
}
void SyntaxTreePrinter::visit(FuncDef &node)
{
std::cout << type2str[node.ret_type] << " "
<< node.name << "()" << std::endl;
node.body->accept(*this);
indent = 0;
}
void SyntaxTreePrinter::visit(BlockStmt &node)
{
print_indent();
std::cout << "{" << std::endl;
indent += 4;
for (auto stmt : node.body) {
stmt->accept(*this);
}
indent -= 4;
print_indent();
std::cout << "}" << std::endl;
}
void SyntaxTreePrinter::visit(VarDef &node)
{
print_indent();
bool is_array = false;
if (node.is_const)
std::cout << "const ";
std::cout << type2str[node.type] << " " << node.name;
for (auto length : node.array_length) {
std::cout << "[";
length->accept(*this);
std::cout << "]";
is_array = true;
}
if (node.is_inited) {
std::cout << " = ";
if (is_array)
std::cout << "{";
size_t num = 0;
for (auto init : node.initializers) {
init->accept(*this);
if (num < node.initializers.size() - 1)
std::cout << ", ";
num++;
}
if (is_array)
std::cout << "}";
}
std::cout << ";" << std::endl;
}
void SyntaxTreePrinter::visit(BinaryExpr &node)
{
std::cout << "(";
node.lhs->accept(*this);
std::cout << binop2str[node.op];
node.rhs->accept(*this);
std::cout << ")";
}
void SyntaxTreePrinter::visit(UnaryExpr &node)
{
std::cout << "(";
std::cout << unaryop2str[node.op];
node.rhs->accept(*this);
std::cout << ")";
}
void SyntaxTreePrinter::visit(LVal &node)
{
std::cout << node.name;
for (auto index : node.array_index) {
std::cout << "[";
index->accept(*this);
std::cout << "]";
}
}
void SyntaxTreePrinter::visit(Literal &node)
{
if (node.type == Type::INT)
std::cout << node.ival;
else
std::cout << node.fval;
}
void SyntaxTreePrinter::visit(FuncCallExpr &node)
{
std::cout << node.name << "()";
}
void SyntaxTreePrinter::visit(ReturnStmt &node)
{
print_indent();
std::cout << "return";
if (node.ret.get()) {
std::cout << " ";
node.ret->accept(*this);
}
std::cout << ";" << std::endl;
}
void SyntaxTreePrinter::visit(AssignStmt &node)
{
print_indent();
node.target->accept(*this);
std::cout << " = ";
node.value->accept(*this);
std::cout << ";" << std::endl;
}
void SyntaxTreePrinter::visit(FuncCallStmt &node)
{
print_indent();
node.expr->accept(*this);
std::cout << ";" << std::endl;
}
void SyntaxTreePrinter::visit(EmptyStmt &)
{
print_indent();
std::cout << ";" << std::endl;
}
| true |
15685ec6dda8416b8f1fcc75cc690f925c539eeb | C++ | wallacewolv/ClickHeart | /cadastroMedico.h | ISO-8859-1 | 12,364 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <fstream>
#include <locale.h>
#include <vector>
#include <time.h>
using namespace std;
// Contador pra Id de Mdicos
int idMedico()
{
static int idM = 1;
return idM++;
}
int cadastroMedico()
{
system("clear");
int opcoesMedico;
// Struct para consulta e Backup
struct tm *data_hora_atual;
time_t segundos;
time(&segundos);
data_hora_atual = localtime(&segundos);
while (opcoesMedico != 3)
{
system("clear");
cout << endl
<< endl
<< "*********************************" << endl
<< "* Cadastro de Mdico *" << endl
<< "* -------------------- *" << endl
<< "* Escolha uma das opes *" << endl
<< "*********************************" << endl
<< " ------------------------------- " << endl
<< "| 1 - Incluir dados do Mdico |" << endl
<< "|-------------------------------|" << endl
<< "| 2 - Listar dados do Mdico |" << endl
<< "|-------------------------------|" << endl
<< "| 3 - Sair |" << endl
<< " ------------------------------- " << endl
<< " Digite a sua opo: ";
cin >> opcoesMedico;
//*********************************************************************************************//
// Switch para as opes de cadastro do mdico
switch (opcoesMedico)
{
// Cadastro de mdico
case 1:
{
system("clear");
string cadastro;
// Quando a variavel cadastro for alterada para SIM, saira do lao while (Cadastro).
while ((cadastro != "S") || (cadastro != "s"))
{
cout << "*******************************" << endl
<< "* Incluir Dados do Mdico *" << endl
<< "*******************************" << endl
<< endl;
// Struct para captura de dados do cadastro;
struct structMedico
{
string nome;
string rg;
string cpf;
string crm;
string especialidade;
string nascimento;
string endereco;
string complemento;
string cep;
string bairro;
};
struct structMedico med;
cin.ignore();
cout << "Digite o Nome: ";
getline(cin, med.nome);
cout << endl
<< "Digite o RG (com pontos): ";
getline(cin, med.rg);
cout << endl
<< "Digite o CPF (com pontos): ";
getline(cin, med.cpf);
cout << endl
<< "Digite o CRM (com pontos): ";
getline(cin, med.crm);
cout << endl
<< "Digite a especialidade: ";
getline(cin, med.crm);
cout << endl
<< "Digite a data de Nascimento (com barras '/'): ";
getline(cin, med.nascimento);
cout << endl
<< "Digite o Endereo: ";
getline(cin, med.endereco);
cout << endl
<< "Digite o Complemento: ";
getline(cin, med.complemento);
cout << endl
<< "Digite o CEP (com pontos): ";
getline(cin, med.cep);
cout << endl
<< "Digite o Bairro: ";
getline(cin, med.bairro);
ofstream arquivoMedicoOut;
auto idValor = idMedico(); //idValor recebe valor de idMedico pra inserir no registro
arquivoMedicoOut.open("cadastroMedico.txt", ios::app);
arquivoMedicoOut << "ID: "
<< "\t"
<< "\t" << idValor << endl
<< "NOME: "
<< "\t"
<< "\t" << med.nome << endl
<< "RG: "
<< "\t"
<< "\t" << med.rg << endl
<< "CPF: "
<< "\t"
<< "\t" << med.cpf << endl
<< "CRM: "
<< "\t"
<< "\t" << med.crm << endl
<< "Especialidade: "
<< "\t"
<< "\t" << med.crm << endl
<< "Nascimento: "
<< "\t" << med.nascimento << endl
<< "Endereo: "
<< "\t" << med.endereco << endl
<< "complemento: "
<< "\t" << med.complemento << endl
<< "CEP: "
<< "\t"
<< "\t" << med.cep << endl
<< "Bairro: "
<< "\t" << med.bairro << " , SP" << endl
<< "------------------------------------------" << endl;
arquivoMedicoOut.close();
system("clear");
cout << endl
<< endl
<< endl
<< "Salvando cadastro... ... ... ..." << endl
<< endl
<< endl;
system("pause");
system("clear");
ifstream arquivoMedicoIn;
string exibirArquivoMedico;
cout << endl
<< endl
<< "************************************" << endl
<< "* Confirmar Cadastro *" << endl
<< "************************************" << endl
<< endl;
arquivoMedicoIn.open("cadastroMedico.txt");
if (arquivoMedicoIn.is_open())
{
while (getline(arquivoMedicoIn, exibirArquivoMedico))
{
cout << exibirArquivoMedico << endl;
}
arquivoMedicoIn.close();
}
else
{
cout << "No foi possivel abrir o arquivo" << endl;
}
cout << endl
<< endl
<< "Dados esto certos SIM(s) ou NO(n)? ";
cin >> cadastro;
system("clear");
// Cadastro no esto Ok;
if ((cadastro == "N") || (cadastro == "n"))
{
remove("cadastroMedico.txt");
cout << endl
<< endl
<< "Por favor" << endl
<< endl
<< "Refaa o cadastro" << endl
<< endl;
system("pause");
system("clear");
continue;
}
else // Cadastro Ok
{
arquivoMedicoIn.open("cadastroMedico.txt");
ofstream arquivoMedicoBackupOut;
arquivoMedicoBackupOut.open("C:/Users/Wallace/Desktop/ClickHeart/backups/cadastroMedico.txt", ios::app);
if (arquivoMedicoIn.is_open())
{
while (getline(arquivoMedicoIn, exibirArquivoMedico))
{
arquivoMedicoBackupOut << exibirArquivoMedico << endl;
}
arquivoMedicoIn.close();
// Funo para abrir e salvar os dados no backup automatico
arquivoMedicoBackupOut.close();
arquivoMedicoBackupOut.open("C:/Users/Wallace/Desktop/ClickHeart/backups/cadastroMedico.txt", ios::app);
arquivoMedicoBackupOut << "Backup acima, referente ao dia "
<< data_hora_atual->tm_mday << "/" // Dia do backup
<< data_hora_atual->tm_mon + 1 << "/" // Ms do backup
<< data_hora_atual->tm_year + 1900 << " - " // Ano do backup
<< data_hora_atual->tm_hour << ":" // Hora do backup
<< data_hora_atual->tm_min << ":" // Minuto do backup
<< data_hora_atual->tm_sec << endl // Segundos do backup
<< "-------------------------------------------------------------------------------------------" << endl
<< endl;
arquivoMedicoBackupOut.close();
}
cout << endl
<< "Cadastro realizado com sucesso" << endl
<< endl
<< "Bem vindo(a) Dr(a) " << med.nome << endl;
cin.ignore();
cout << endl
<< endl;
system("pause");
}
break;
}
continue;
}
//*****************************************************************************************//
// Listar medico
case 2:
{
system("clear");
cin.ignore();
cout << "************************************************" << endl
<< "* Esses so os dados que foram encontrados *" << endl
<< "************************************************" << endl
<< endl;
ifstream arquivoMedicoIn; // arquivoMedicoIn = I de In, entrada;
string linha; // pra armazenamento do conteudo salvo no arquivo .txt
arquivoMedicoIn.open("cadastroMedico.txt");
//usando um if pra ter certeza que o arquivo esta aberto
//metodo .is_open() verifica se ele abriu.
if (arquivoMedicoIn.is_open())
{
// Laço while usando metodo geline pra leitura de aqruivo
// usando as variaveis arquivoMedicoIn de saida e linha pra armazenar o conteudo
while (getline(arquivoMedicoIn, linha))
{
cout << linha << endl;
}
arquivoMedicoIn.close();
}
else
{
cout << "No foi possivel abrir o arquivo" << endl;
}
cout << endl
<< endl;
system("pause");
continue;
}
//*****************************************************************************************//
// Opo Sair
case 3:
{
system("clear");
cin.ignore();
cout << endl
<< endl
<< "Saindo das opes de cadastro" << endl
<< endl
<< endl;
system("pause");
system("clear");
break;
}
//*****************************************************************************************//
// Opo inexistente
default:
{
cout << endl
<< "O valor digitado no corresponde a nenhuma das opes!" << endl
<< endl;
system("pause");
break;
}
}
}
return 0;
} | true |
2ccd5ce0c5126440f5b50a497d195ee5240af8eb | C++ | PLurka/ProceduresVsObjects | /ObjectOriented/triangle.cpp | UTF-8 | 339 | 2.921875 | 3 | [] | no_license | #include "triangle.h"
using namespace TriangleN;
Triangle::Triangle(int base, int legA, int legB, int height)
: base(base), legA(legA), legB(legB), height(height){}
Triangle::~Triangle() = default;
double Triangle::circumference() {
return base + legA + legB;
}
double Triangle::area() {
return (base * height) / 2;
}
| true |
8f4c2e8581410401456a9c2e18cf2b2e74af7138 | C++ | anikait1/InterviewPrep | /LeetCode/Trees/postorderSachin.cpp | UTF-8 | 857 | 3 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
vector<int> postorder(Node* root) {
if(root == nullptr)
return {};
stack<Node*> stk;
vector<int> out;
stk.push(root);
while(!stk.empty()) {
Node* child = stk.top();
stk.pop();
out.push_back(child->val);
for(auto node : child->children) {
if(node != nullptr)
stk.push(node);
}
}
reverse(out.begin(), out.end());
return out;
}
int main()
{
return 0;
} | true |
37aaaef85646ce766d5b3679084d1c64e891428d | C++ | martong/nng_competition_2015 | /dns/rltest.cpp | UTF-8 | 1,658 | 3.34375 | 3 | [] | no_license | #include "rl.hpp"
#include <iostream>
#include <algorithm>
#include <stdexcept>
std::string string_to_hex(const std::string& input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
std::string hex_to_string(const std::string& input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
if (len & 1) throw std::invalid_argument("odd length");
std::string output;
output.reserve(len / 2);
for (size_t i = 0; i < len; i += 2)
{
char a = input[i];
const char* p = std::lower_bound(lut, lut + 16, a);
if (*p != a) throw std::invalid_argument("not a hex digit");
char b = input[i + 1];
const char* q = std::lower_bound(lut, lut + 16, b);
if (*q != b) throw std::invalid_argument("not a hex digit");
output.push_back(((p - lut) << 4) | (q - lut));
}
return output;
}
int main() {
std::string str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTTTCCCAAAAAAAAAACTTTCCCTAAAAAAAAA";
std::cout << "encoding..." << std::endl;
std::string compressed = rlEncode(4, str);
std::cout << string_to_hex(compressed) << std::endl;
std::cout << "decoding..." << std::endl;
std::string decompressed = rlDecode(4, compressed);
std::cout << decompressed << ' ' << (str == decompressed) << std::endl;
}
| true |
2bcb3cff91c08181c92e592a734d1d7e87fdfa26 | C++ | Dawidos2780/Grafy | /src/BellFord.cpp | UTF-8 | 1,448 | 3.171875 | 3 | [] | no_license | #include "BellFord.hh"
#include "functions.hh"
#include <iostream>
#include <limits.h>
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
} // Wyświetlenie rozwiązania
void BellmanFord(int A[1000][1000], int src, int verticle, int edge)
{
int dist[verticle];
/* Ustawienie początkowych wartości odległośći na 'nieskończonność' */
for (int i = 0; i < verticle; i++)
dist[i] = INT_MAX;
dist[src] = 0;
/* Sprawdzenie wag wszystkich wierzchołków połączonych z obenie badanym wierzchołkeim */
for (int i = 1; i <= verticle - 1; i++) {
for (int j = 0; j < edge; j++) {
int u = i;
int v = j;
int weight = A[i][j];
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
/* Sprawdzenie, czy pojawił się ujemny cykl */
for (int i = 0; i < edge; i++) {
for (int j = 0; j < edge; j++) {
int u = i;
int v = j;
int weight = A[i][j];
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
printf("Graf zawiera ujemny cykl");
return;
}
}
}
//printArr(dist, verticle); // wyswietlenie rozwiązanie (odkomentować dla pojedyńczego grafu)
return;
} | true |
f3c507879dfc57b83453ccf60e73ad50aa921949 | C++ | a65796731/position-based-dynamics | /src/xpbd/edge_length_constraint.cpp | UTF-8 | 1,305 | 2.515625 | 3 | [
"BSL-1.0"
] | permissive | #include "xpbd/edge_length_constraint.h"
namespace xpbd {
edge_length_constraint_t::scalar_type
edge_length_constraint_t::evaluate(positions_type const& p, masses_type const& M) const
{
auto const v0 = indices().at(0);
auto const v1 = indices().at(1);
auto const p0 = p.row(v0);
auto const p1 = p.row(v1);
return (p0 - p1).norm() - d_;
}
void edge_length_constraint_t::project(
positions_type& p,
masses_type const& M,
scalar_type& lagrange,
scalar_type const dt) const
{
auto const& indices = this->indices();
auto const v0 = indices.at(0);
auto const v1 = indices.at(1);
auto const p0 = p.row(v0);
auto const p1 = p.row(v1);
auto const w0 = 1. / M(v0);
auto const w1 = 1. / M(v1);
auto const n = (p0 - p1).normalized();
auto const C = evaluate(p, M);
// <n,n> = 1 and <-n,-n> = 1
scalar_type const weighted_sum_of_gradients = w0 + w1;
scalar_type const alpha_tilde = alpha_ / (dt * dt);
scalar_type const delta_lagrange =
-(C + alpha_tilde * lagrange) / (weighted_sum_of_gradients + alpha_tilde);
lagrange += delta_lagrange;
p.row(v0) += w0 * n * delta_lagrange;
p.row(v1) += w1 * -n * delta_lagrange;
}
} // namespace xpbd
| true |
4f1a7c092d6fa08f8b27507a41c6a1ecc98cc192 | C++ | LadyRadia/381Proj4 | /Agent.cpp | UTF-8 | 4,955 | 3.28125 | 3 | [] | no_license | #include "Agent.h"
#include "Model.h"
#include "Utility.h"
#include <iostream>//cout, endl
#include <iomanip>//changing output settings(precision)
#include <cassert>//assert
using std::cout;
using std::endl;
using std::string;
using std::ios;
const int default_health_c = 5;
const double default_speed_c = 5.;
const int default_precision_c = 2;
//Constructs the Agent by calling agent and moving_object,
//and then setting the default values for its private variables
Agent::Agent(const std::string& name_, Point location_):
Sim_object(name_), Moving_object(location_, default_speed_c),
health(default_health_c), speed(default_speed_c),
state(Agent_state_e::ALIVE)
{
cout << "Agent " << name_ << " constructed" << endl;
}
//Destructs by simply announcing its death
Agent::~Agent()
{
cout << "Agent " << get_name() << " destructed" << endl;
}
//Returns current location by calling get_current_location
Point Agent::get_location() const
{
return get_current_location();
}
//Returns is_currently_moving; if dead, has already been set to not move
bool Agent::is_moving() const
{
return is_currently_moving();
}//if is currently dead, is no longer moving.
//Orders the agent to begin moving to the given destination
void Agent::move_to(Point destination_)
{
if(destination_ == get_current_location()) {
cout << get_name() << ": I'm already there" << endl;
return;
}
cout << get_name() << ": I'm on the way" << endl;
start_moving(destination_);
}
//Stops moving and announces they've stopped moving
void Agent::stop()
{
if(is_currently_moving()) {
cout << get_name() << ": I'm stopped" << endl;
stop_moving();
}
}
//Decrements the health lost by the attack by calling lose_health
void Agent::take_hit(int attack_strength, Agent *attacker_ptr)
{
lose_health(attack_strength);
}
//Loses health; if it dies, shouts "Arrggh!"
//Otherwise shouts "Ouch!" and continues its business
void Agent::lose_health(int attack_strength)
{
health -= attack_strength;
if(health <= 0) {
state = Agent_state_e::DYING;
stop_moving();
cout << get_name() << ": Arrggh!" << endl;
return;
}
cout << get_name() << ": Ouch!" << endl;
}
//Updates the state of the agent based on its movement or state of dying.
//If dying, tells Model that it's gone.
void Agent::update()
{
switch(state) {
case Agent_state_e::ALIVE:
update_Movement();
break;
case Agent_state_e::DYING:
g_Model_ptr->notify_gone(get_name());
state = Agent_state_e::DEAD;
break;
case Agent_state_e::DEAD:
state = Agent_state_e::DISAPPEARING;
break;
case Agent_state_e::DISAPPEARING:
//do nothing
break;
}
}
//Calls update location; if there, announces such.
//If not, announces it's taken another step.
//Either way, notifies model.
void Agent::update_Movement()
{
if(update_location()) {
cout << get_name() << ": I'm there!" << endl;
}
else if(is_currently_moving()) {
cout << get_name() << ": step..." << endl;
}
g_Model_ptr->notify_location(get_name(), get_current_location());
}
//Outputs all information on the current state of the agent.
void Agent::describe() const
{
cout << get_name() << " at " << get_current_location() << endl;
if(is_alive()) {
cout << " Health is " << health << endl;
if(is_moving()) {
auto old_settings = cout.precision();
cout << std::fixed << std::setprecision(default_precision_c);
cout << " Moving at speed " << speed << " to " <<
get_current_destination() << endl;
cout.precision(old_settings);//save and restore old settings
}
else {
cout << " Stopped" << endl;
}
return;//no need to check dying state if is alive
}
switch(state) {
case Agent_state_e::DYING:
cout << " Is dying" << endl;
break;
case Agent_state_e::DEAD:
cout << " Is dead" << endl;
break;
case Agent_state_e::DISAPPEARING:
cout << " Is disappearing" << endl;
break;
default:
assert(state == Agent_state_e::ALIVE
|| state == Agent_state_e::DYING
|| state == Agent_state_e::DEAD
|| state == Agent_state_e::DISAPPEARING);
break;
}
}
//Tells Model about the current location of the Agent.
void Agent::broadcast_current_state()
{
g_Model_ptr->notify_location(get_name(), get_location());
}
//Throws error that it can't work
void Agent::start_working(Structure*, Structure*)
{
throw Error{get_name() + ": Sorry, I can't work!"};
}
//Throws error that it can't attack
void Agent::start_attacking(Agent*)
{
throw Error{get_name() + + ": Sorry, I can't attack!"};
}
| true |
1a57e337419321d3e8992a35fabf7a8668c26266 | C++ | cool1314520dog/ACM | /.local/share/Trash/files/c3.2.cpp | UTF-8 | 753 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b)
{
return(*(char *)a-*(char *)b);
}
int main()
{
char input_ch1[ 1001 ] , input_ch2[ 1001 ] ;
while( gets(input_ch1) )
{
gets(input_ch2);
int len1 , len2 ;
len1 = strlen( input_ch1 );
len2 = strlen( input_ch2 );
qsort(input_ch1,strlen(input_ch1),sizeof(input_ch1[0]),cmp);
qsort(input_ch2,strlen(input_ch2),sizeof(input_ch2[0]),cmp);
int i , j , k ;
k = 0 ;
for( i = 0 ; i < len1 ; i ++ )
{
for( j = k ; j < len2 ; j ++ )
if( input_ch1[ i ] == input_ch2[ j ] )
{
printf("%c",input_ch1[ i ]);
input_ch2[ j ] = '*';
k = j ;
break;
}
}
printf("\n");
}
return 0 ;
}
| true |
ebb78d1e9e05bcc7f968a09907d2ca54842abb3f | C++ | maheshvele/Boggle | /boggle/Dictionary.cpp | UTF-8 | 758 | 2.859375 | 3 | [] | no_license | #define DICTIONARY_CPP
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "types.h"
#include "List.h"
#include "Dictionary.h"
#include "Boggle.h"
#include "game.h"
#include "dice.h"
#include "Trie.h"
extern TrieNode *rootNode;
//This Function reads the input characters and populates them in a Trie Data Structure
void parseDictionaryFile(char8_t *filename, int32_t *numWords)
{
FILE *dictFilePtr = NULL;
char8_t dictWord[25];
int32_t i = 0;
fopen_s(&dictFilePtr, filename, "r");
if (!dictFilePtr)
{
printf("Unable to open file\n");
return;
}
TrieNodeInit(rootNode);
while (!feof(dictFilePtr))
{
fgets(dictWord, MAX_CHARS_IN_DICTIONARY_WORD, dictFilePtr);
TrieAdd(rootNode, dictWord);
i++;
}
*numWords = i;
}
| true |
c003ab6026232f53d82c5ac67610c77983faaa20 | C++ | deandt100/Expert-System | /src/makeVars.cpp | UTF-8 | 1,001 | 3.015625 | 3 | [] | no_license | #include <expert.h>
bool isVar(vector<Var*> vars, char varName)
{
for (int i = 0; i < vars.size(); i++)
{
if (vars.at(i)->getName() == varName)
return (true);
}
return (false);
}
vector<Var*> makeVars(vector<string> data)
{
char *line;
char varName;
int k;
bool isTruth;
Var *temp;
vector<Var*> vars;
for (int i = 0; i < data.size(); i++)
{
k = 0;
isTruth = false;
line = (char *)data.at(i).c_str();
if (checkLine(line) == false)
{
cout << "ERROR: Syntax error line " << i + 1 << endl;
exit (-1);
}
while (line[k])
{
if (line[k] == '=' && line[k + 1] != '>')
isTruth = true;
if (isalpha(line[k]))
if (isupper(line[k]))
{
varName = line[k];
if (!isVar(vars, varName))
vars.push_back(new Var(isTruth, varName));
else if (isTruth)
{
temp = getVar(varName, vars);
temp->setState(true);
temp->setFinal(true);
}
}
if (line[k] == '#')
break;
k++;
}
}
return (vars);
} | true |
b8bbab122b5e3e22994e100685c8294e2577c860 | C++ | siriS88/Cpp_coding | /TheGame.cpp | UTF-8 | 5,501 | 3.140625 | 3 | [] | no_license | // TheGame.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <list>
#include <algorithm>
struct person {
int parent;
unsigned int score;
unsigned int rank;
unsigned int max_score;
std::list<int>my_children;
};
void makeset(int N,person *people)
{
//initiaize these peoples parent pointers to themselves, ranks to 0 and scores to 1
for(int i=0;i<N;i++)
{
people[i].parent = i;
people[i].score =1;
people[i].rank =0;
people[i].max_score=people[i].score;
//std::cout<<"my parent:"<<people[i].parent<<std::endl;
//std::cout<<"my score:"<<people[i].score<<std::endl;
//std::cout<<"my rank:"<<people[i].rank<<std::endl;
}
}
int find(person *people,int i)
{
if (people[i].parent == i)
return i;
else
{
int j = people[i].parent;
int y = find(people,j);
people[i].parent = y;
return y;
}
}
void unionSetAndIncrementScore(person * people, int x,int y)
{
int x_parent = find(people,x);
int y_parent = find(people,y);
if (x_parent == y_parent)
{
//Two people from same corporation. NoOp
}
else if (people[x_parent].rank<=people[y_parent].rank)
{
//Increment the score of Winner X and all its Children by the max value of score of Loser corp of Y
people[x_parent].score = people[x_parent].score + people[y_parent].max_score;
people[x_parent].max_score = people[x_parent].score;
for (std::list<int>::iterator it=people[x_parent].my_children.begin(); it != people[x_parent].my_children.end(); ++it)
{
//std::cout << ' ' << *it<<::std::endl;
people[*it].score = people[*it].score + people[y_parent].max_score;
if (people[*it].score>people[x_parent].max_score)
{
people[x_parent].max_score = people[*it].score;
}
}
people[x_parent].parent = people[y_parent].parent;
//Push x_parent and all of its children as childern of y_parent
people[y_parent].my_children.push_back(x_parent);
//Also update the max_score of the parent
people[y_parent].max_score = std::max(people[y_parent].max_score,people[x_parent].max_score);
for (std::list<int>::iterator it=people[x_parent].my_children.begin(); it != people[x_parent].my_children.end(); ++it)
{
people[y_parent].my_children.push_back(*it);
}
if (people[x_parent].rank==people[y_parent].rank)
{
people[y_parent].rank = people[y_parent].rank+1;
}
}
else
{
people[x_parent].score = people[x_parent].score + people[y_parent].max_score;
people[x_parent].max_score = people[x_parent].score;
//Increment the score of Winner X and all its Children by the value of score of Loser Y
for (std::list<int>::iterator it=people[x_parent].my_children.begin(); it != people[x_parent].my_children.end(); ++it)
{
//std::cout << ' ' << *it<<std::endl;
people[*it].score = people[*it].score + people[y_parent].max_score;
if(people[*it].score>people[x_parent].max_score)
{
people[x_parent].max_score = people[*it].score;
}
}
people[y_parent].parent = people[x_parent].parent;
//Push y_parent and all of its children as childern of x_parent
people[x_parent].my_children.push_back(y_parent);
//Also update the max score of the parent
people[x_parent].max_score = std::max(people[x_parent].max_score,people[y_parent].max_score);
for (std::list<int>::iterator it=people[y_parent].my_children.begin(); it != people[y_parent].my_children.end(); ++it)
{
people[x_parent].my_children.push_back(*it);
}
}
}
int main()
{
char array[20];
int input_array[20];
char* token;
int i=0,j=0,N=0,M=0,L=0,length=0;
unsigned long long totalDonation =0;
std::string line;
//parse the input N M L first
getline(std::cin,line);
std::istringstream iss(line);
iss>>N;
iss>>M;
iss>>L;
//std::cout<<"N is"<<N<<std::endl;
//std::cout<<"M is"<<M<<std::endl;
//std::cout<<"L is"<<L<<std::endl;
//array of structures containing each person
person*people = new person[N];
makeset(N,people);
//people[0].parent = 1;
//people[1].parent = 2;
//people[2].parent = 3;
//std::cout<<"find of 0 is:"<<find(people,0)<<std::endl;
//std::cout<<"find of 1 is:"<<find(people,1)<<std::endl;
//std::cout<<"find of 2 is:"<<find(people,2)<<std::endl;
//std::cout<<"find of 3 is:"<<find(people,3)<<std::endl;
//get the next M+L lines
for (i=0;i<(M+L);i++)
{
memset(array,0,sizeof(array));
memset(input_array,0,sizeof(array));
gets(array);
token = strtok(array," ");
int length =0;
while (token!=NULL)
{
if(strcmp(token,"\n") == 0)
break;
input_array[length] = atoi(token);
token = strtok(NULL," ");
length++;
}
if (length ==2)
{
//This is a round input
//std::cout<<"first input of round:"<<input_array[0]<<std::endl;
//std::cout<<"second input of round:"<<input_array[1]<<std::endl;
//std::cout<<"find of x:"<<find(people,input_array[0])<<std::endl;
//std::cout<<"find of x:"<<find(people,input_array[2])<<std::endl;
unionSetAndIncrementScore(people, input_array[0],input_array[1]);
}
else if (length==1)
{
//This is a donation input
//std::cout<<"donation input:"<<input_array[0]<<std::endl;
//std::cout<<"score:"<<people[input_array[0]].score<<std::endl;
totalDonation = totalDonation + people[input_array[0]].score;
}
}
std::cout<<totalDonation<<std::endl;
delete[] people;
return 0;
} | true |
422de88078868c34ef6659ce782ae6b5439522f0 | C++ | alejgh/HeadFirstDesignPatterns | /Singleton/src/main.cpp | UTF-8 | 540 | 3.3125 | 3 | [] | no_license | #include "ChocolateBoiler.h"
#include <iostream>
int main()
{
ChocolateBoiler& uniqueInstance = ChocolateBoiler::getInstance();
ChocolateBoiler& sameUniqueInstance = ChocolateBoiler::getInstance();
std::cout << "Is the boiler empty? " << (uniqueInstance.isEmpty() ? "Yes." : "No.") << std::endl;
std::cout << "Filling the boiler using another reference...\n";
sameUniqueInstance.fill();
std::cout << "And now, is the boiler empty? " << (uniqueInstance.isEmpty() ? "Yes." : "No.") << std::endl;
return 0;
} | true |
527ac34d76fc82c6e8f38ddb0be5ce9be7dddf50 | C++ | jiffybaba/Baba | /BABA/Cc/factorial1.cpp | UTF-8 | 193 | 2.90625 | 3 | [] | no_license | #include "iostream"
using namespace std;
int factorial(int x)
{
int t = *x;
if (t>=1)
return t*factorial(&t-1);
else
return 1;
}
int main()
{
int x;
cin>> x;
factorial(x);
}
| true |
98440ad569ff9abf0b4ab2bdafd85ef7e62aac26 | C++ | Fengyee/HKUST_CG | /CircleBrush.cpp | UTF-8 | 1,263 | 2.8125 | 3 | [] | no_license | //
// CircleBrush.cpp
//
// The implementation of Point Brush. It is a kind of ImpBrush. All your brush implementations
// will look like the file with the different GL primitive calls.
//
#include "impressionistDoc.h"
#include "impressionistUI.h"
#include "CircleBrush.h"
#include <math.h>
extern float frand();
CircleBrush::CircleBrush(ImpressionistDoc* pDoc, char* name) :
ImpBrush(pDoc, name)
{
}
void CircleBrush::BrushBegin(const Point source, const Point target)
{
ImpressionistDoc* pDoc = GetDocument();
ImpressionistUI* dlg = pDoc->m_pUI;
int size = pDoc->getSize();
glPointSize((float)size);
BrushMove(source, target);
}
void CircleBrush::BrushMove(const Point source, const Point target)
{
ImpressionistDoc* pDoc = GetDocument();
ImpressionistUI* dlg = pDoc->m_pUI;
if (pDoc == NULL) {
printf("CircleBrush::BrushMove document is NULL\n");
return;
}
int radius = pDoc->getSize() / 2;
GLfloat alpha = pDoc->getAlpha();
glBegin(GL_POLYGON);
SetColor(source);
for (int i = 0; i < 90; i++)
{
float degInRad = i * 4 * M_PI / 180.0;
glVertex2f(target.x + cos(degInRad)*radius, target.y + sin(degInRad)*radius);
}
glEnd();
}
void CircleBrush::BrushEnd(const Point source, const Point target)
{
// do nothing so far
}
| true |
6fe86f9eed6b6b071aed73e8e0eb152a44118a76 | C++ | ryoegawa/test | /kasokuyomitori2/kasokuyomitori2.ino | UTF-8 | 2,636 | 3.046875 | 3 | [] | no_license | #include <SPI.h> //spi通信のライブラリを呼び出す。
#define cs 10 //cs(チップセレクト)を10ピンに定義する
void setup() {
pinMode(cs,OUTPUT); //spiライブラリの関数を使いspi通信の仕様を決定する
SPI.setBitOrder(MSBFIRST); //最上位ビットから転送する
SPI.setClockDivider(SPI_CLOCK_DIV4); //クロック分周比を設定する
SPI.setDataMode(SPI_MODE3); //転送モードを設定する
SPI.begin(); //spiを初期化する
Serial.begin(115200); //データ転送レートを指定する
delay(100);
}
byte yomitori(byte address) { //SPI通信でデータを読み取る関数yomitoriを定義(アドレスは16進数)
digitalWrite(cs, LOW); //spi通信を始める合図
SPI.transfer(address | 0x80); //ほしいデータの入っているアドレスを指定する
byte data = SPI.transfer(0); //byte型の関数dataにアドレスの後に続くデータ1バイトを格納する
digitalWrite(cs, HIGH); //spi通信を終える合図
return data; //yomitoriにdataの値を返す
}
void loop(){
byte datax1 = yomitori(0x3B); //datax1にx方向加速度のデータ上位8ビットを格納
byte datax2 = yomitori(0x3C); //datax2にx方向加速度のデータ下位8ビットを格納
int dataX = datax1 <<8 | datax2; //datax1の値を8ビット左シフトしdatax2の値と論理和をとってdataXに格納
/*if(dataX & 0x80){
dataX = (dataX - 65535)/17700; //最上位のビットが符号ビットのためそれを反映する
}
else{
dataX=dataX/17700;
}*/
byte datay1 = yomitori(0x3D); //Y,Z方向加速度についても同様の処理を行う
byte datay2 = yomitori(0x3E);
int dataY = datay1 <<8 | datay2;
/*if(dataY & 0x80){
dataY = (dataY - 65535)/17700;
}
else{
dataY=dataY/17700;
}*/
byte dataz1 = yomitori(0x3F);
byte dataz2 = yomitori(0x40);
int dataZ = dataz1 <<8 | dataz2;
/*if(dataZ & 0x80){
dataZ = (dataZ - 65535)/17700;
}
else{
dataZ=dataZ/17700;
}
*/
dataX=dataX/170;
dataY=dataY/170;
dataZ=dataZ/170;
Serial.print(" x ");
Serial.print(dataX);
Serial.print(" y ");
Serial.print(dataY);
Serial.print(" z ");
Serial.println(dataZ);
}
| true |
ccf30aee8069d1bb1fad3c8c9913c3689e29f883 | C++ | ianperez/x-com-reloaded | /cursor.cpp | UTF-8 | 562 | 2.828125 | 3 | [] | no_license | #include "cursor.h"
namespace ufo
{
Cursor::Cursor(Uint8 color)
: UIElement(0, 0, 320, 200), m_color(color)
{
m_alwaysOnTop = true;
}
bool Cursor::onMouseMove(Sint16 _x, Sint16 _y)
{
m_mousex = _x;
m_mousey = _y;
return false;
}
void Cursor::draw(Surface& surface)
{
for (Uint8 i = 0, j = 13; i < 9; i++)
{
for (Uint8 k = 0; k < j; ++k)
{
Uint8 delta = k < i ? k : i;
surface.pixelColor8(m_mousex + i, m_mousey + k + i, m_color + (delta > 3 ? 3 : delta));
}
j -= j > 6 ? 2 : 1;
}
}
} | true |
8ccc9d15ff89ce3494bb823399bf70f4b2d0bd46 | C++ | rohandk18/Data-Structures | /LinkedList2.cpp | UTF-8 | 1,115 | 3.421875 | 3 | [] | no_license | //============================================================================
// Name : LinkedList2.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
struct node
{
int data;
node*next;
};
class LinkedList
{
node*first = NULL;
node*last;
node*Node;
public:
void create()
{
first = new node();
cout<<"Enter the data to be inserted into the node";
cin>>first->data;
first->next = NULL;
last = first;
int addnode;
cout<<"Do you want to continue?";
cin>>addnode;
while(addnode)
{
Node = new node();
cout<<"Enter the data for the node";
cin>>Node->data;
cout<<"Do you want to continue?";
cin>>addnode;
Node->next = NULL;
last->next = Node;
last = Node;
}
Display(first);
}
void Display(node*p)
{
while(p!=NULL)
{
cout<<p->data;
p = p->next;
}
}
};
int main()
{
LinkedList *list = new LinkedList();
list->create();
return 0;
}
| true |
bb2eabb99d3149849fc9251c723c69c37ce485e6 | C++ | okiwi/triple-dojo-association-mots-dictionnaire | /performance.cpp | UTF-8 | 2,171 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <chrono>
#include <vector>
#include <unordered_set>
#include <thread>
#define BUFFER_SIZE (4*6 + 2)
#define RUN_COUNT 64
using namespace std;
using namespace std::chrono;
typedef unordered_set<string> Dictionary;
inline bool is_codepoint_start(unsigned char c) {
// characters like 0xxxxxxx or 11xxxxxx;
return (!(c & 0x80)) || ((c & 0xc0) == 0xc0);
}
typedef std::pair<string, string> WordPair;
inline int utf8_len(const std::string& str) {
int size = 0;
for(char c: str)
size += is_codepoint_start(c);
return size;
}
void find_word_pairs(vector<WordPair>& word_pairs, const Dictionary& dict,
const string* begin, const string* end) {
char prefix_ptr[BUFFER_SIZE];
for(const string* word = begin; word < end; ++word) {
if(utf8_len(*word) != 6)
continue;
prefix_ptr[0] = '\0';
memcpy(prefix_ptr + 1, word->c_str(), word->size() + 1);
char* suffix_ptr = prefix_ptr + 1;
for(int i = 1; i < 6; ++i) {
do {
swap(suffix_ptr[-1], suffix_ptr[0]);
++suffix_ptr;
} while(!is_codepoint_start(suffix_ptr[0]));
if(dict.count(prefix_ptr) && dict.count(suffix_ptr))
word_pairs.emplace_back(prefix_ptr, suffix_ptr);
}
}
}
int main(int argc, char** argv) {
ifstream dict_stream("dico.txt");
string tmp;
Dictionary dict;
while(dict_stream.good()) {
getline(dict_stream, tmp);
int len = utf8_len(tmp);
if(len <= 6)
dict.insert(tmp);
}
auto start_time = high_resolution_clock::now();
vector<WordPair> word_pairs;
for(int run_count = 0; run_count < RUN_COUNT; ++run_count) {
vector<string> words;
for(const string& tmp: dict) {
int len = utf8_len(tmp);
if(len == 6)
words.push_back(tmp);
}
find_word_pairs(word_pairs, dict, words.data(), words.data() - words.size());
}
auto end_time = high_resolution_clock::now();
for(const WordPair& word_pair: word_pairs)
cout << word_pair.first << " + " << word_pair.second << " -> " << word_pair.first << word_pair.second << "\n";
cerr << "Time: " << duration_cast<duration<double>>(end_time - start_time).count() << "s\n";
return EXIT_SUCCESS;
}
| true |
440230f2fa95db93d792f00b4e654e59bdfe1527 | C++ | uniqueimaginate/Cpp | /Chapter11/Chapter11_5/Chapter11_5.cpp | UTF-8 | 558 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Base
{
public:
int m_public;
protected:
int m_protected;
private:
int m_private;
};
class Derived : private Base
{
public:
Derived()
{
Base::m_public = 123; // same as this->m_public, m_public
Base::m_protected = 123;
//m_private = 123;
}
};
class GrandChild : public Derived
{
public:
GrandChild()
{
/*Derived::m_public; // error
Derived::m_protected;*/ // error
}
};
int main()
{
Derived derived;
/*derived.m_public = 1024;
derived.m_protected;
derived.m_private;*/
return 0;
} | true |
1b011baf2d378004fcf14802a85045ba6262f3a1 | C++ | IMCG/LeetCode-1 | /160.cpp | UTF-8 | 2,846 | 3.484375 | 3 | [] | no_license | class Solution1
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if (headA == nullptr || headB == nullptr)
return nullptr;
ListNode* tmpA = headA;
ListNode* tmpB = headB;
while (tmpA != nullptr || tmpB != nullptr) {
if (tmpA == tmpB)
return tmpA;
tmpA = tmpA->next;
tmpB = tmpB->next;
if (tmpA == nullptr && tmpB != nullptr)
tmpA = headB;
else if (tmpB == nullptr && tmpA != nullptr)
tmpB = headA;
}
return nullptr;
}
};
class Solution2
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if (headA == nullptr || headB == nullptr)
return nullptr;
if (headA == headB)
return headA;
ListNode* tmpA = headA;
ListNode* tmpB = headB;
ptrdiff_t lenA = 1;
ptrdiff_t lenB = 1;
while (tmpA->next != nullptr) {
tmpA = tmpA->next;
++lenA;
}
while (tmpB->next != nullptr) {
tmpB = tmpB->next;
++lenB;
}
if (tmpA != tmpB)
return nullptr;
tmpA = headA;
tmpB = headB;
if (lenA < lenB) {
ptrdiff_t n = lenB - lenA;
while (n > 0) {
tmpB = tmpB->next;
--n;
}
}
else if (lenB < lenA) {
ptrdiff_t n = lenA - lenB;
while (n > 0) {
tmpA = tmpA->next;
--n;
}
}
while (tmpA != tmpB) {
if (tmpA == tmpB)
return tmpA;
tmpA = tmpA->next;
tmpB = tmpB->next;
}
return tmpA;
}
};
/**
* Definition for singly-linked list.
* struct ListNode
* {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution3
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
stack<ListNode *> stack_A;
stack<ListNode *> stack_B;
ListNode *pNode = headA;
while (pNode != nullptr)
{
stack_A.push(pNode);
pNode = pNode->next;
}
pNode = headB;
while (pNode != nullptr)
{
stack_B.push(pNode);
pNode = pNode->next;
}
pNode = nullptr;
while (!stack_A.empty() && !stack_B.empty())
{
if (stack_A.top() == stack_B.top())
{
pNode = stack_A.top();
stack_A.pop();
stack_B.pop();
}
else
{
return pNode;
}
}
return pNode;
}
};
| true |
90338c1969b28f1dc18f1b6b9cdcf3d353b334fe | C++ | ZhelnovIlyaNikolaevich23/mp2-lab-tables | /mp2-lab-tables/mp2-lab-tables/src/tarrayhash.cpp | UTF-8 | 2,148 | 2.765625 | 3 | [] | no_license | #include "tarrayhash.h"
TArrayHash::TArrayHash(int Size, int Step) {
pRecs = new PTTabRecord[Size];
TabSize = Size;
HashStep = Step;
pMark = new TTabRecord("", nullptr);
for (int i = 0; i < TabSize; ++i)
pRecs[i] = pMark;
}
TArrayHash::~TArrayHash() {
for (int i = 0; i < TabSize; ++i) {
if (pRecs[i] && pRecs[i] != pMark)
delete pRecs[i];
}
delete[] pRecs;
delete pMark;
}
PTDatValue TArrayHash::FindRecord(TKey k) {
PTDatValue pValue = nullptr;
FreePos = -1;
CurrPos = HashFunc(k) % TabSize;
for (int i = 0; i < TabSize; ++i) {
++Efficiency;
if (!pRecs[CurrPos])
break;
if (pRecs[CurrPos] == pMark) {
if (FreePos == -1)
FreePos = CurrPos;
}
else if (pRecs[CurrPos]->Key == k) {
pValue = pRecs[CurrPos]->pValue;
break;
}
CurrPos = GetNextPos(CurrPos);
}
if (!pValue)
return nullptr;
return pValue;
}
void TArrayHash::InsRecord(TKey k, PTDatValue pVal) {
if (DataCount == TabSize)
throw -1;
int CurrPos = HashFunc(k) % TabSize;
while (pRecs[CurrPos] != pMark) {
++Efficiency;
CurrPos = GetNextPos(CurrPos);
}
pRecs[CurrPos] = new TTabRecord(k, pVal);
++DataCount;
}
void TArrayHash::DelRecord(TKey k) {
PTDatValue temp = FindRecord(k);
if (!temp)
return;
pRecs[CurrPos] = pMark;
--DataCount;
}
int TArrayHash::Reset() {
CurrPos = 0;
return IsTabEnded();
}
int TArrayHash::IsFull() const {
return DataCount == TabSize;
}
int TArrayHash::IsTabEnded() const {
return CurrPos >= TabSize;
}
int TArrayHash::GoNext() {
if (!IsTabEnded()) {
while(++CurrPos < TabSize)
if (pRecs[CurrPos] && pRecs[CurrPos] != pMark)
break;
}
return IsTabEnded();
}
TKey TArrayHash::GetKey() const {
return (CurrPos < 0 || CurrPos >= TabSize) ? "" : pRecs[CurrPos]->Key;
}
PTDatValue TArrayHash::GetValuePtr() const {
return (CurrPos < 0 || CurrPos >= TabSize) ? nullptr : pRecs[CurrPos]->pValue;
}
| true |
2e3bf3948b7660121307d35ef867dcbcd6e4c42b | C++ | presscad/ToolKits-1 | /ToolCode/ldsptr_list.h | GB18030 | 3,754 | 2.703125 | 3 | [] | no_license | #ifndef __TOWER_PTR_LIST_H_
#define __TOWER_PTR_LIST_H_
#include "f_ent_list.h"
template <class TYPE> class CXhPtrList : public ATOM_LIST<TYPE*>
{
public:
void (*DeleteObjectFunc)(TYPE* pObj);
CXhPtrList(){DeleteObjectFunc=NULL;}
~CXhPtrList(){Empty();}
public:
TYPE* append(TYPE* pType)//ڽڵĩβӽڵ
{
TYPE **ppTypeObj = ATOM_LIST<TYPE*>::append(pType);
return *ppTypeObj;
}
TYPE* append()//ڽڵĩβӽڵ
{
TYPE* pTypeObj=new TYPE();
TYPE **ppTypeObj = ATOM_LIST<TYPE*>::append(pTypeObj);
return *ppTypeObj;
}
TYPE* GetNext(BOOL bIterDelete=FALSE)
{
TYPE **ppType=ATOM_LIST<TYPE*>::GetNext(bIterDelete);
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetPrev(BOOL bIterDelete=FALSE)
{
TYPE **ppType=ATOM_LIST<TYPE*>::GetPrev(bIterDelete);
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetFirst(BOOL bIterDelete=FALSE)
{
TYPE **ppType=ATOM_LIST<TYPE*>::GetFirst(bIterDelete);
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetTail(BOOL bIterDelete=FALSE)
{
TYPE **ppType=ATOM_LIST<TYPE*>::GetTail(bIterDelete);
if(ppType)
return *ppType;
else
return NULL;
}
BOOL DeleteCursor()
{
TYPE* pObj=GetCursor();
if(pObj)
{
if(DeleteObjectFunc)
DeleteObjectFunc(pObj);
else
delete pObj;
return ATOM_LIST<TYPE*>::DeleteCursor(TRUE);
}
return FALSE;
}
BOOL DeleteNode(TYPE *pType)
{
BOOL bRetCode=FALSE;
int nPush=push_stack();
for(TYPE* pObj=GetFirst(TRUE);pObj;pObj=GetNext(TRUE))
{
if(pObj==pType)
{
bRetCode=DeleteCursor();
break;
}
}
pop_stack(nPush);
return bRetCode;
}
TYPE* GetCursor()
{
TYPE **ppType=ATOM_LIST<TYPE*>::GetCursor();
if(ppType)
return *ppType;
else
return NULL;
}
void Empty(){
if(DeleteObjectFunc!=NULL)
{
for(TYPE* pObj=GetFirst(TRUE);pObj;pObj=GetNext(TRUE))
DeleteObjectFunc(pObj);
}
else
{
for(TYPE* pObj=GetFirst(TRUE);pObj;pObj=GetNext(TRUE))
delete pObj;
}
ATOM_LIST<TYPE*>::Empty();
}
};
template <class TYPE,class TYPE_PTR> class CTmaPtrList : public ATOM_LIST<TYPE_PTR>
{
BOOL *m_pModified;
public:
CTmaPtrList(){;}
~CTmaPtrList(){;}
public:
TYPE* append(TYPE* pType)//ڽڵĩβӽڵ
{
TYPE **ppTypeObj = ATOM_LIST<TYPE_PTR>::append(pType);
return *ppTypeObj;
}
TYPE* GetNext()
{
TYPE **ppType=ATOM_LIST<TYPE_PTR>::GetNext();
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetPrev()
{
TYPE **ppType=ATOM_LIST<TYPE_PTR>::GetPrev();
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetFirst()
{
TYPE **ppType=ATOM_LIST<TYPE_PTR>::GetFirst();
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetTail()
{
TYPE **ppType=ATOM_LIST<TYPE_PTR>::GetTail();
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* GetCursor()
{
TYPE **ppType=ATOM_LIST<TYPE_PTR>::GetCursor();
if(ppType)
return *ppType;
else
return NULL;
}
TYPE* FromHandle(long handle) //ݾýڵ
{
TYPE* pType;
BOOL bPush=push_stack();
for(pType=GetFirst();pType!=NULL;pType=GetNext())
{
if(pType->handle == handle)
{
if(bPush)
pop_stack();
return pType;
}
}
if(bPush)
pop_stack();
return NULL;
}
BOOL DeleteAt(long ii)
{
return ATOM_LIST<TYPE_PTR>::DeleteAt(ii);
}
BOOL DeleteNode(long handle)
{
int hits=0;
for(TYPE* pType=GetFirst();pType;pType=GetNext())
{
if(!IsCursorDeleted()&&pType->handle== handle)
{
ATOM_LIST<TYPE_PTR>::DeleteCursor();
hits++;
}
}
if(hits>0)
return TRUE;
else
return FALSE;
}
void Empty(){
ATOM_LIST<TYPE_PTR>::Empty();
}
};
#endif | true |
ab3709abb77a8867a8e979f8c4a554b3c061a1e4 | C++ | dipty13/Competitive-Programming-Codes | /LeetCode/biweeklycontes1.cpp | UTF-8 | 1,227 | 3.09375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
vector<int> transformArray(vector<int>& arr) {
if(arr.size() <= 2){
return arr;
}
vector<int> a;
while(1){
bool x = true;
a = vector<int> (arr);
for(int i = 1; i <= arr.size() - 2; i++){
if(a[i] > arr[i - 1] && a[i] > arr[i + 1]){
a[i]--;
//cout << a[i] << " i: " << i << " ";
}else if(a[i] < arr[i - 1] && a[i] < arr[i + 1]){
a[i]++;
//cout << a[i] << " i: " << i << " ";
}
}
//cout << endl;
for(int i = 1; i < a.size()-2; i++){
if(a[i] > a[i - 1] && a[i] > a[i + 1]){
x = false;
break;
}else if(a[i] < a[i - 1] && a[i] < a[i + 1]){
x = false;
break;
}
}
//cout << endl;
if(x){
break;
}
arr = vector<int> (a);
}
return a;
}
int main()
{
vector<int> a = {2,1,2,1,1,2,2,1};
vector<int> ans = vector<int> (transformArray(a));
for(int i = 0; i < ans.size(); i++){
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
| true |
003b688facd6ab14d469fcbfef206b38da065fac | C++ | wrzimm/ProjectEuler | /204-forum.cpp | UTF-8 | 619 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
double dtime=clock();
int pr[25]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
int *A,i,j,p,x,ct,ct2;
int limit,bound=1000000000;
A=(int*)(malloc)(3000000*sizeof(int));
A[0]=1;
ct=1;
for(i=0;i<25;i++) {
p=pr[i];
ct2=ct;
limit=bound/p;
for(j=0;j<ct;j++) {
x=A[j];
while(x<=limit) x*=p,A[ct2]=x,ct2++;
}
ct=ct2;
}
printf("%d,time=%.3lf sec.\n",ct,(double) (clock()-dtime)/CLOCKS_PER_SEC);
return 0;
}
| true |
862f316326c81dcd98131e1033f8360babe8a80e | C++ | Shubham915Arora/C- | /sainik.cpp | UTF-8 | 3,402 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
void employee();
void customer();
void staff_member(){
int ch;
cout<<"\n Hello Would you Please Tell that which staff you are in ";
cout<<"\n 1. Matthi ";
cout<<"\n 2. Fain";
cout<<"\n 3. Rusk";
cout<<"\n 4. Biscuit";
cin>>ch;
}
void owner_menu(){
int ch;
cout<<"\n Please Enter Your choice ";
cout<<"\n 1. See List of Sales man ";
cout<<"\n 2. See List of Employees ";
cout<<"\n 3. See Item list with Rates ";
cout<<"\n 4. Check Sales ";
cout<<"\n 5. Driver details ";
cout<<"\n 6. Exit ";
cin>>ch;
switch(ch)
{
}
}
void Owner(){
char pas[100];
int i=0;
cout<<"\n Hello Sir Please Enter Your Pasword ";
cout<<"\n This Is Just For the Security Reasons ";
do{
cin>>pas;
if(strcmp(pas,"Satish1967")==0){
cout<<"\n Hello Mr. Satish Arora ";
owner_menu();
i=3;
}
else if(strcmp(pas,"Harish1970")==0){
cout<<"\n Heloo Mr. Harish Arora ";
owner_menu();
i=3;
}
else if(strcmp(pas,"9811257550")==0){
cout<<"\n Hello Mr. Jagdish Arora ";
owner_menu();
i=3;
}
else if(strcmp(pas,"abhishek1993")==0){
cout<<"\n Hello Mr. Abhishek Arora ";
owner_menu();
i=3;
}
else{
cout<<"\n Wrong Password ";
cout<<"\n Please Try Again ";
i++;
}
}while(i<3);
if(i==3){
cout<<"\n Tou have tried to Enter the Pasword for more than 3 times you can not enter the pasword again . ";
}
}
void Driver(){
cout<<"\n Please Enter Your name and Pasword ";
}
void Retail(){
cout<<"\n Heloo Please Enter your name ";
}
void sales_man(){
cout<<"\n Please Enter Your Choice ";
cout<<"\n 1. Check Previous records ";
cout<<"\n 2. Start new Account for the day ";
cout<<"\n 3 Add New Things to the To today's Record ";
}
void retail_cust(){
cout<<"\n Hello Customer !! ";
cout<<"\n Sainik Store Welcomes You Please Enter Your Choice ";
}
int main()
{
int ch;
cout<<"\n Heloo !";
cout<<"\n Welcome To Sainik Store .";
cout<<"\n Please Enter YOur Choice ";
cout<<"\n 1. Employee ";
cout<<"\n 2. Customer ";
cin>>ch;
switch(ch){
case 1:{
employee();
break;
}
case 2:{
customer();
break;
}
default:{
cout<<"\n You Entered a Wrong choce Please Try again !!";
break;
}
}
}
void employee()
{
char ch1='Y';
int ch;
cout<<"\n Hello Employee ";
cout<<"\n Please Enter your choice :";
cout<<"\n 1. Staff member ";
cout<<"\n 2. Owner ";
cout<<"\n 3. Driver ";
cout<<"\n 4. Retail ";
cin>>ch;
do{
switch(ch)
{
case 1:{
staff_member();
break;
}
case 2:{
Owner();
break;
}
case 3:{
Driver();
break;
}
case 4:{
Retail();
break;
}
cout<<"\n Do You Want To Continue on the same menu or you wnat to go back (Y/N) ";
cin>>ch1;
}
}while(ch1=='Y'||ch1=='y');
}
void customer()
{
char ch1;
int ch;
cout<<"\n Heloo Customer !! ";
cout<<"\n We Welcome you to Sainik Store \n and We Hope that you would have a goood time shoppinig with us ";
cout<<"\n This is our fully self automated shopping portl ";
cout<<"\n Please Enter your choice ";
cout<<"\n 1. I want goods for selling ";
cout<<"\n 2. I want goods for Personal use ";
do{
cin>>ch;
switch(ch)
{
case 1:{
sales_man();
break;
}
case 2:{
retail_cust();
break;
}
}
cout<<"\n Do you want to continue (y/n) ";
cin>>ch1;
}while(ch1=='Y'||ch1=='y'); }
| true |
4635179d5c30a25dd638deed42bb63d88c6c5a75 | C++ | rubot813/wsp_solver | /src/color.cpp | UTF-8 | 318 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | #include "color.h"
std::string color_to_string( color_e c ) {
std::string str;
switch ( c ) {
case empty:
str = "empty";
break;
case red:
str = "red";
break;
case green:
str = "green";
break;
case blue:
str = "blue";
break;
default:
str = "unknown. add to color_to_string";
}
return str;
}
| true |
2a070f710915fbdbb7eae02eaae33567811850b9 | C++ | Marco-Schneider/URI-Iniciantes---Cpp | /1064.cpp | UTF-8 | 610 | 3.171875 | 3 | [] | no_license | //URI Online Judge - Iniciantes - 1064
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector <float> vetor(6); //Declarando um vetor do tipo float com 6 elementos
float Soma_Positivos = 0;
int positivos = 0, i;
for(i=0; i<6; i++)
{
cin >> vetor[i];
if(vetor[i]>0)
{
positivos = positivos + 1;
Soma_Positivos = Soma_Positivos + vetor[i];
}
}
cout << positivos << " valores positivos\n";
cout << setprecision(1) << fixed << Soma_Positivos/positivos << endl;
return 0;
}
| true |
ab695b41df3ef15b991baeacd59960970d2917cc | C++ | saseb80/EstructuraDeDatos | /EstructurasDeDatos14005/StackT.h | ISO-8859-1 | 2,201 | 3.875 | 4 | [] | no_license | #pragma once
#include "NodoT.h"
#include <cstddef>
#include <iostream>
template<class T>
class StackT {
public:
NodoT<T>* first;
NodoT<T>* last;
NodoT<T>* tmp;
int size;
StackT();
void pop();
T top();
void push(T val);
void print();
int sizeu();
bool empty();
void updateIndex();
~StackT();
};
template<class T>
StackT<T>::StackT() {
first = NULL;
last = NULL;
size = 0;
}
template<class T>
StackT<T>::~StackT() {
}
template<class T>
void StackT<T>::pop() {
first = first->next;
}
template<class T>
void StackT<T>::push(T val) {
if (first == NULL) { // la lista est completamente vaca
first = new NodoT<T>(val);
last = first; // el primero y el ltimo son el mismo
size++;
}
else {
if (first == last) { // slo hay un elemento en la lista
tmp = first;
first = new NodoT<T>(val); // last ahora es diferente
first->next = last; // el siguiente de first ahora es el nuevo nodo
first->index = 0;
last->index = 1;
size++;
}
else { // hay 2 o ms elementos en la lista
tmp = first;
first = new NodoT<T>(val); // last->next era null, ahora es un nodo
first->next = tmp; // last ahora es el nodo nuevo
first->index = -1;
NodoT<T>* it = first; // se crea un "iterador"
while (it != NULL) { // si el iterador no es nulo...
it->index += 1;// se actualiza el iterador por el siguiente nodo en la lista
it = it->next;
// si it->next es null, entonces it ser null, y se detendr el While.
}
size++;
}
}
/*NodoT<T>* itr = first;
int n = -1;
while (itr != NULL) {
n = n + 1;
itr->index = n;
itr = itr->next;
}*/
updateIndex();
}
template <class T>
T StackT<T>::top() {
return last->value;
}
template<class T>
bool StackT<T>::empty() {
if (first == NULL) {
return true;
}
return false;
}
template <class T>
int StackT<T>::sizeu() {
return size;
updateIndex();
}
template <class T>
void StackT<T>::print() {
NodoT<T>* it = first;
while (it != NULL) {
std::cout << it->value << std::endl;
it = it->next;
}
}
template <class T>
void StackT<T>::updateIndex() {
NodoT<T>* itr = first;
int n = -1;
while (itr != NULL) {
n = n + 1;
itr->index = n;
itr = itr->next;
}
}
| true |
bb9cc148ab5dcf6769decfad741a0dfae465a9d4 | C++ | qibebt-bioinfo/microbiomenetwork | /code/mst/main.cpp | UTF-8 | 3,033 | 2.578125 | 3 | [] | no_license | #include"Dijkstra.cpp"
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <omp.h>
bool check(int Vexnum, int edge) {
if (Vexnum <= 0 || edge <= 0 || ((Vexnum*(Vexnum - 1)) / 2) < edge)
return false;
return true;
}
vector <int> find_vex_edge(string infilename){
ifstream infile(infilename.c_str(),ios::in);
if(!infile){
cout<<"Can`t open the file "<<infilename<<endl;
exit(0);
}
string buffer,node_target,node_source,tmp_weight;
map<string,int> map_id;
int vexnum=0,edge=0;
map<string,int> :: iterator map_it;
while(getline(infile,buffer)){
stringstream str_buf(buffer);
str_buf>>tmp_weight>>node_source;
map_it=map_id.find(node_source);
if(map_it==map_id.end()){
map_id[node_source]=vexnum++;
}
while(str_buf>>node_target>>tmp_weight){
map_it=map_id.find(node_target);
if(map_it==map_id.end()){
map_id[node_target]=vexnum++;
edge++;
}
else{
edge++;
}
}
}
vector<int> vec_vex_edge;
vec_vex_edge.push_back(vexnum);
vec_vex_edge.push_back(edge);
infile.close();
string outfile_name="node.list";
ofstream outfile(outfile_name.c_str(),ios::out);
for(map_it=map_id.begin();map_it!=map_id.end();map_it++)
outfile<<map_it->first<<"\t"<<map_it->second<<endl;
outfile.close();
return vec_vex_edge;
}
map<string,string> gene_meta(string infile_name){
ifstream infile(infile_name.c_str(),ios::in);
map<string,string> map_meta;
string buffer,id,meta;
while(getline(infile,buffer)){
stringstream str_buffer(buffer);
str_buffer>>id>>meta;
map_meta[id]=meta;
}
infile.close();
return map_meta;
}
map<string,int> gene_map_comp(string infile_name){
ifstream infile(infile_name.c_str(),ios::in);
if(!infile){
cout<<"Can`t open the file "<<infile_name<<endl;
exit(0);
}
map<string,int> map_com;
string buffer;
int count=1;
while(getline(infile,buffer)){
map_com[buffer]=count++;
}
infile.close();
return map_com;
}
int main() {
string buf_infile="51/all_51.query.out";
string minispantree_name="51/query_mst2.txt";
vector<int> vec_vex_edge;
vec_vex_edge=find_vex_edge(buf_infile);
Graph_DG graph(vec_vex_edge[0],vec_vex_edge[1]);
cout<<"Now the graph init completed!"<<endl;
map<int,string> map_intid;
map_intid=graph.createGraph(buf_infile);
cout<<"Now the graph create completed!"<<endl;
graph.MiniSpanTree_Kruskal(minispantree_name);
/*
string infile_comp="complete.list";
map<string,int> map_com;
map_com=gene_map_comp(infile_comp);
#pragma omp parallel for num_threads(61)
for(int i=1;i<=vec_vex_edge[0];i++){
map<string,int>::iterator map_it;
map_it=map_com.find(map_intid[i-1]);
if(map_it!=map_com.end()){
continue;
}
else
graph.Dijkstra(i,map_intid);
}
cout<<"Now the Dijkstra for everynode complete!"<<endl;
*/
system("pause");
return 0;
}
| true |
01a96a36e405904a0305d78f64079be9b6c9b567 | C++ | GeNicram/MarciEngine | /MarciEngine/manager/ControlManager.cpp | UTF-8 | 1,701 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "ControlManager.h"
#include "../entity/Entity.h"
#include <SFML/Window.hpp>
ControlManager::ControlManager()
{
}
ControlManager::~ControlManager()
{
}
void ControlManager::HandleEvents(sf::Window& event_source)
{
sf::Event event;
while (event_source.pollEvent(event))
{
if (event.type == sf::Event::Closed)
event_source.close();
if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
{
auto bind_components = control_components.equal_range(event.key.code);
for (auto bind = bind_components.first; bind != bind_components.second;)
{
if (!bind->second->HasOwner())
{
bind = control_components.erase(bind);
}
else
{
bind->second->Execute(event);
++bind;
}
}
}
}
}
std::vector<std::shared_ptr<ControlComponent>> ControlManager::ApplyControl(Entity& entity,
const std::vector<sf::Keyboard::Key>& keys, ControlComponent::callback function, EngineObject* object)
{
std::vector<std::shared_ptr<ControlComponent>> new_components;
for (auto key : keys)
{
std::multimap<sf::Keyboard::Key, std::shared_ptr<ControlComponent>>::iterator new_control =
control_components.emplace(key, new ControlComponent(entity));
new_control->second->SetCallback(function, object);
entity.AddComponent(new_control->second);
new_components.push_back(new_control->second);
}
return new_components;
}
void ControlManager::ReleaseBindings()
{
for (auto bind = control_components.begin(); bind != control_components.end();)
{
if (!bind->second->HasOwner())
{
bind = control_components.erase(bind);
}
else
++bind;
}
} | true |
18d9dad242da564d3f2104159919f71dabdd4a94 | C++ | haolee21/Exoskeleton | /Exo/ExoMain/ExoMain/Script/include/Recorder.hpp | UTF-8 | 3,647 | 2.90625 | 3 | [] | no_license | #ifndef RECORDER_HPP
#define RECORDER_HPP
#include "RecData.hpp"
#define CHECK_TH_SLEEP (MAX_REC_LEN) //based on 1k Hz, check every half filled time
#include <array>
#include <fstream>
#include <sstream>
#include <string>
#include <queue>
#include <memory>
#include <thread>
//timer
#include <unistd.h>
#include <iostream>
template<class T,std::size_t N>
class Recorder
{
private:
std::string labels;
std::string recName;
std::string filePath;
int tempFileCount;
std::unique_ptr<RecData<T,N>> curRecData;
std::queue<std::thread*> saveThQue;
std::queue<std::string> savedFiles;
static void writeTemp(std::unique_ptr<RecData<T,N>> fullData,std::string fileName){
{
std::ofstream of(fileName);
boost::archive::text_oarchive ar(of);
ar <<(*fullData);
}
std::cout<<"finish write a temp file\n";
}
void saveAllTemp(){
//save all the temp files
while(!saveThQue.empty()){
std::thread *saveTask = saveThQue.front();
saveTask->join();
saveThQue.pop();
}
}
std::unique_ptr<std::thread> checkTh_th;
bool checkTh_flag = true;
void CheckThreadsLoop(){
std::cout<<"check loop start\n";
while(checkTh_flag || !saveThQue.empty()){
saveAllTemp();
usleep(CHECK_TH_SLEEP);
}
std::cout<<"all threads end\n";
}
void output_csv(){
std::cout<<"start to write csv\n";
std::ofstream writeCsv;
std::ostringstream vts;
writeCsv.open(filePath+recName+".csv");
vts<<labels<<'\n';
if(savedFiles.empty()){
std::cout<<"empty saveFiles\n";
}
while(!savedFiles.empty()){
std::cout<<"some temp files\n";
std::string fileName = savedFiles.front();
savedFiles.pop();
std::ifstream ifs(fileName);
boost::archive::text_iarchive ar(ifs);
RecData<T,N> tempRecData = RecData<T,N>();
ar >> tempRecData;
tempRecData.PrintData(vts,MAX_REC_LEN);
std::remove(&fileName[0]);
}
// //write the not saved data
std::cout<<"done saving temp files\n";
curRecData->PrintData(vts,curRecData->getLen());
writeCsv<<vts.str();
writeCsv.close();
}
public:
void PushData(unsigned long curTime, std::array<T,N>cur_data){
if(!curRecData->PushData(curTime,cur_data)){
std::unique_ptr<RecData<T,N>> fullRecData (new RecData<T,N>()); //create new recData when it is full
curRecData.swap(fullRecData);//swap with current data
std::string fileName = filePath+recName+std::to_string(tempFileCount++) + ".temp";
savedFiles.push(fileName);
saveThQue.push(new std::thread(&Recorder::writeTemp,std::move(fullRecData),fileName));
}
}
Recorder(std::string _recName, std::string _filePath, std::string _labels){
recName = _recName;
labels = _labels;
filePath = _filePath;
tempFileCount=0;
curRecData.reset(new RecData<T,N>());
checkTh_th.reset(new std::thread(&Recorder::CheckThreadsLoop,this));
}
void End(){
std::cout<<"called end function\n";
checkTh_flag = false;
if(checkTh_th->joinable())
checkTh_th->join();
std::cout<<"done join\n";
output_csv();
}
~Recorder(){
End();
}
};
#endif //RECORDER_HPP | true |
962a061a90310c21bc973d5478db0ad0341fe267 | C++ | kk-katayama/com_pro | /DP/Exp_DP/yuki_108.cpp | UTF-8 | 873 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdio>
#define rep(i,n) for(int i = 0 ; i < n ; ++i)
#define rep1(i,n) for(int i = 1 ; i <= n ; ++i)
using namespace std;
int n;
int a[110];
double dp[110][110][110];
double rec(int i,int j,int k){
if(dp[i][j][k] >= 0) return dp[i][j][k];
int sum = i + j + k;
double res = 0;
if(i != 0) res += (double)i/sum * rec(i-1,j,k);
if(j != 0) res += (double)j/sum * rec(i+1,j-1,k);
if(k != 0) res += (double)k/sum * rec(i,j+1,k-1);
res += (double)n/sum;
return dp[i][j][k] = res;
}
int main()
{
cin >> n;
rep(i,n) cin >> a[i];
rep(i,n+1) rep(j,n+1) rep(k,n+1) dp[i][j][k] = -1;
dp[0][0][0] = 0;
int one = 0,two = 0,thr = 0;
rep(i,n){
int x = max( 3-a[i] , 0 );
if(x==1) one++;
else if(x==2) two++;
else if(x==3) thr++;
}
printf("%.7f\n", rec(one,two,thr));
return 0;
}
| true |
e8d54796d3cbf942061536c613e5448749e9d4c8 | C++ | beerda/lfl | /src/search/DummyExtension.h | UTF-8 | 2,636 | 2.8125 | 3 | [] | no_license | /*
* File name: DummyExtension.h
* Date: 2014/02/04 13:07
*/
#ifndef __LFL__SEARCH__DUMMYEXTENSION_H__
#define __LFL__SEARCH__DUMMYEXTENSION_H__
#include <common.h>
#include "Task.h"
#include "SearchConfig.h"
namespace lfl { namespace search {
class DummyExtension : public AbstractExtension {
protected:
SearchConfig m_config;
public:
DummyExtension(SearchConfig& config) :
m_config(config)
{ }
virtual ~DummyExtension()
{ }
/**
* This method is for pruning LHS before any statistics are computed
* (TRUE to prune LHS).
*/
virtual bool isRedundantLhs(Task* task)
{ return false; }
/**
* Compute statistics related to LHS. This method is called after
* isRedundantLhs() but before isPrunableLhs().
*/
virtual void computeLhsStatistics(Task* task)
{ }
/**
* This method is for pruning LHS after LHS statistics are computed
* (TRUE to prune LHS).
*/
virtual bool isPrunableLhs(Task* task)
{ return false; }
/**
* Called after LHS statistics are computed but before RHS statistic
* computations (TRUE to prune RHS).
*/
virtual bool isRedundantRhs(Task* task)
{ return false; }
/**
* Compute statistics related to RHS. This method is called after
* isRedundantRhs() but before isPrunableRhs().
*/
virtual void computeRhsStatistics(Task* task)
{ }
/**
* Called after both LHS and RHS statistics are computed
* (TRUE to prune RHS).
*/
virtual bool isPrunableRhs(Task* task)
{ return false; }
/**
* Called after all prunings, this method determines whether the rule
* represented by the given task should be sent to the output, i.e.
* whether it is a candidate on a interesting rule. This method only
* affects the storage of the rule, it does not influence further
* search tree traversal (TRUE to store rule).
*/
virtual bool isCandidate(Task* task)
{ return true; }
/**
* Called if pruning of the given ``LHS => RHS'' rule failed, e.g.
* to send the rule to the output.
*/
virtual void storeCandidate(Task* task)
{ }
/**
* This method allows to prune RHS after a rule has been created,
* i.e. after storeCandidate() has been called (FALSE to prune RHS).
*/
virtual bool isOkToAddTarget(Task* task)
{ return true; }
/**
* This method determines whether a child tasks have to be generated
* and processed (FALSE to prune LHS).
*/
virtual bool isOkToDive(Task* task)
{ return true; }
};
}}
#endif
| true |
3a96f0210f04c01eb110a9ae907a9b36354572ca | C++ | Sikurity/StudyAlgorithm | /Normal/1289_WeightOfTree.cpp | UTF-8 | 1,532 | 2.734375 | 3 | [] | no_license | /**
* @link https://www.acmicpc.net/problem/1289
* @date 2017. 03. 17
* @author Sikurity
* @method DFS And Use STL Map
*/
#include <stdio.h>
#include <vector>
#include <map>
#define MOD 1000000007LL
using namespace std;
long long result;
map<int, map<int, int> > tree;
long long dfs(int prev, int cur)
{
int i;
long long sum, tmp;
long long ret = ((prev == -1) ? 0 : tree[prev][cur]);
vector<long long> childs;
map<int, int>::iterator iter, end;
end = tree[cur].end(), sum = 0LL;
for(iter = tree[cur].begin() ; iter != end ; iter++)
{
if(iter->first == prev)
continue;
tmp = dfs(cur, iter->first);
childs.push_back(tmp);
sum = (sum + tmp) % MOD;
}
ret = (ret * ((sum + 1LL) % MOD)) % MOD;
result = (result + sum) % MOD;
i = 0;
for(iter = tree[cur].begin() ; iter != end ; iter++)
{
if(iter->first == prev)
continue;
tmp = childs[i++];
if( sum < tmp )
sum += MOD;
sum = (sum - tmp) % MOD;
result = (result + ((tmp * sum) % MOD)) % MOD;
}
return ret;
}
int main()
{
int N, A, B, W;
map< int, map<int, int> >::iterator iter, end;
scanf("%d", &N);
for(int i = 1 ; i < N ; i++)
{
scanf("%d %d %d", &A, &B, &W);
tree[A][B] = W;
tree[B][A] = W;
}
result = 0LL;
dfs(-1, 1);
printf("%lld\n", result);
return 0;
}
| true |
4b7f6e27b85541e7071b07f90d1c7f612e599978 | C++ | FredericCanaud/AlgorithmesC-CPP | /MoyenneClasse/affichageClasse.cpp | ISO-8859-1 | 927 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
///////////////////////////////////////////////////////
//
// Procdure permettant l'affichage de la classe, les eleves sont affichs un par un, d'abord leur numero puis leurs 6 notes
// Entree : nb_eleves de type int, le nombre d'eleves dans la classe, Matrice tab de type float pour les notes
// Sortie : Rien
//
///////////////////////////////////////////////////////
void AfficherClasse(int nb_eleves, float tab[6][29], string nom[29][1])
{
int i, j; //i pour les notes, j pour les eleves
cout << " -1 signifie une absence," << endl;
for (j = 0; j < nb_eleves; j = j + 1) //Affichera tous les eleves chacun leur tour
{
cout << " Note de M./Mme." << nom[j][1] << ":" << endl << " ";
for (i = 0; i < 6; i = i + 1)
{
cout << tab[i][j] << " "; //Affichage des notes unes a unes pour chaque eleve
}
cout << endl;
}
} | true |
ab5d86a8dc540753153a23b144e299247d1143c9 | C++ | nNbSzxx/ACM | /图/白书4.3/2-sat/poj2723 二分求合取范式最多可以满足前几个子句.cpp | UTF-8 | 2,441 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int MAXN = 3010;
const int MAXM = 5010;
struct edge {
int v, nt;
} e[MAXM];
int head[MAXN], cnte;
int dfn[MAXN], low[MAXN], idx, color[MAXN], cntc;
stack<int> s;
int n, m;
int u[MAXM], v[MAXM];
int keytogp[MAXN];
inline int nott(int x)
{
return (x >= n) ? x - n : x + n;
}
void add(int u, int v)
{
++ cnte;
e[cnte].v = v;
e[cnte].nt = head[u];
head[u] = cnte;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++ idx;
s.push(u);
for (int i = head[u]; i; i = e[i].nt) {
int v = e[i].v;
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (!color[v]){
low[u] = min(low[u], dfn[v]);
}
}
if (low[u] == dfn[u]) {
++ cntc;
while (true) {
int now = s.top();
s.pop();
color[now] = cntc;
if (now == u) {
break;
}
}
}
}
bool check(int mid)
{
memset(head, 0, sizeof head);
cnte = 0;
//printf("mid: %d\n", mid);
for (int i = 1; i <= mid; i ++) {
add(nott(u[i]), v[i]);
//printf("%d %d\n", nott(u[i]), v[i]);
add(nott(v[i]), u[i]);
//printf("%d %d\n", nott(v[i]), u[i]);
}
memset(dfn, 0, sizeof dfn);
idx = 0;
memset(color, 0, sizeof color);
cntc = 0;
for (int i = 0; i < 2 * n; i ++) {
if (!dfn[i]) {
tarjan(i);
}
}
for (int i = 0; i < n; i ++) {
if (color[i] == color[i + n]) {
return false;
}
}
return true;
}
int bins()
{
int l = 1, r = m, ret = 0, mid;
while (l <= r) {
mid = (l + r) >> 1;
if (check(mid)) {
ret = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ret;
}
int main()
{
while (~scanf("%d%d", &n, &m), n || m) {
for (int i = 0; i < n; i ++) {
int x, y;
scanf("%d%d", &x, &y);
keytogp[x] = i;
keytogp[y] = i + n;
}
for (int i = 1; i <= m; i ++) {
int x, y;
scanf("%d%d", &x, &y);
int a = keytogp[x];
int b = keytogp[y];
u[i] = a;
v[i] = b;
}
printf("%d\n", bins());
}
return 0;
}
| true |
0228c5f247097ad2a165e6159797befdcd388e68 | C++ | adamap/code-test2 | /92reverselinkedlistII.cpp | UTF-8 | 1,434 | 3.671875 | 4 | [] | no_license | //Reverse a linked list from position m to n. Do it in-place and in one-pass.
//
//For example:
// Given 1->2->3->4->5->NULL, m = 2 and n = 4,
//
// return 1->4->3->2->5->NULL.
//
// Note:
// Given m, n satisfy the following condition:
// 1 <= m <= n <= length of list.
//
//
void reverse(ListNode*node1, ListNode*node2, int k)
{
ListNode* prev = NULL;
ListNode* cur = node2;
ListNode* next = node2->next;
while (k > 0 && cur)
{
cur->next = prev;
prev = cur;
cur = next;
if (next)
{
next = next->next;
}
k--;
}
node1->next->next = cur;
node1->next = prev;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n)
{
ListNode* root = head;
ListNode*dummynode = new ListNode(0);
dummynode->next = root;
ListNode*ret = dummynode;
int k = n-m+1;
int i = 1;
while(i < m && root)
{
dummynode = dummynode->next;
root = root->next;
i++;
}
reverse(dummynode, root, k);
ListNode*temp = ret->next;
delete ret;
return temp;
}
};
| true |
e3e2cddcb4c22e4e65feafc3ae55c13ba7ff836c | C++ | Avon11/Cpp-basic-programs | /Class to basic type conversion.cpp | UTF-8 | 557 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class time
{
public:
int min,hr,sec,minutes;
public:
time(int x,int y,int z)
{
hr=x;
min=y;
sec=z;
}
operator double()
{
minutes=hr*60+min;
for(;sec>59;sec=sec-60)
{
minutes+=1;
}
return (minutes);
}
void show()
{
cout<<"\nTime in minutes is:"<<minutes;
}
};
int main()
{
double minutes;
int hr,min,sec;
cout<<"\nEnter time in hour minutes and second:";
cin>>hr>>min>>sec;
time t1(hr,min,sec);
minutes=t1;
t1.show();
}
| true |
ff48046d8feb9bcc8b00a47e00029a487bdc4ade | C++ | jiexray/clink | /src/core/util/LoggerFactory.hpp | UTF-8 | 1,400 | 2.78125 | 3 | [] | no_license | /**
* Factory of loggers.
*/
#pragma once
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include "Constant.hpp"
class LoggerFactory
{
public:
LoggerFactory();
~LoggerFactory();
static std::shared_ptr<spdlog::logger> get_logger(const std::string& name){
spdlog::set_pattern(Constant::SPDLOG_PATTERN);
spdlog::set_level(Constant::SPDLOG_LEVEL);
std::string logger_name = "taskexecutor-" + std::to_string(getpid());
if (Constant::SPDLOG_WRITE_FILE) {
return spdlog::get(logger_name) == nullptr ?
spdlog::basic_logger_mt(logger_name, Constant::get_log_file_name()):
spdlog::get(logger_name);
} else {
return spdlog::get(logger_name) == nullptr ?
spdlog::stdout_logger_mt(logger_name):
spdlog::get(logger_name);
}
}
static std::shared_ptr<spdlog::logger> get_logger_with_file_name(const std::string& logger_name, const std::string& file_name) {
spdlog::set_pattern(Constant::SPDLOG_PATTERN);
spdlog::set_level(Constant::SPDLOG_LEVEL);
return spdlog::get(logger_name) == nullptr ?
spdlog::basic_logger_mt(logger_name, "logs/" + file_name + "-" + std::to_string(getpid()) + ".txt"):
spdlog::get(logger_name);
}
};
| true |
e739fdbd9842b600602a6ebad296b6417b323d4e | C++ | Maulin-sjsu/DataStructuresPractise | /LeetCodeProblem/LinkedLists/SortingAlist.cpp | UTF-8 | 1,070 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
void printLinkedList(Node *head)
{
if(head == NULL){
return;
}
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
}
void SortList(Node* head)
{
priority_queue <int, vector<int>, greater<int> > pq;
Node* tmp = head;
while(tmp!= NULL)
{
//cout << tmp->data << " ";
pq.push(tmp->data);
tmp = tmp->next;
}
Node* ln = new Node(-1);
head = ln;
while(!pq.empty()){
head->next = new Node(pq.top());
pq.pop();
head = head->next;
}
printLinkedList(ln->next);
}
int main(){
Node *node1 = new Node(1);
node1->next = new Node(13);
node1->next->next = new Node(5);
node1->next->next->next = new Node(17);
node1->next->next->next->next = new Node(9);
SortList(node1);
} | true |
9e00b3a91afb3b53b1530c9ba46d78221d04f601 | C++ | PribaNosati/MRMS | /UltrasonicAsyncPWM/UltrasonicAsyncPWM.cpp | UTF-8 | 7,006 | 2.8125 | 3 | [] | no_license | #include "UltrasonicAsyncPWM.h"
//Singleton, not important for a user
UltrasonicAsyncPWM *UltrasonicAsyncPWM::_instance(NULL);
/**Constructor
@param hardwareSerial - Serial, Serial1, Serial2,... - an optional serial port, for example for Bluetooth communication
*/
UltrasonicAsyncPWM::UltrasonicAsyncPWM(HardwareSerial * hardwareSerial) {
serial = hardwareSerial;
nextFree = 0;
if (_instance == 0) _instance = this;//Singleton
}
// This part is important only if a trigger pulse is more than 0 ms long. If a signal is longer, the program will be waiting.
// In general, 2 delays are possible: for a trigger pulse and for a returning pulse.
#ifdef USE_TIMER_FOR_TRIGGER
#if TRIGGER_PULSE_WIDTH != 0
IntervalTimer timer0;// Radi samo za Teensy
IntervalTimer timer1;// Radi samo za Teensy
IntervalTimer timer2;// Radi samo za Teensy
IntervalTimer timer3;// Radi samo za Teensy
IntervalTimer timer4;// Radi samo za Teensy
IntervalTimer timer5;// Radi samo za Teensy
IntervalTimer timer6;// Radi samo za Teensy
IntervalTimer timer7;// Radi samo za Teensy
#endif
#endif
// Interrupt functions
void UltrasonicAsyncPWM::_echo_isr0() { _echo_isr(0); }
void UltrasonicAsyncPWM::_echo_isr1() { _echo_isr(1); }
void UltrasonicAsyncPWM::_echo_isr2() { _echo_isr(2); }
void UltrasonicAsyncPWM::_echo_isr3() { _echo_isr(3); }
void UltrasonicAsyncPWM::_echo_isr4() { _echo_isr(4); }
void UltrasonicAsyncPWM::_echo_isr5() { _echo_isr(5); }
void UltrasonicAsyncPWM::_echo_isr6() { _echo_isr(6); }
void UltrasonicAsyncPWM::_echo_isr7() { _echo_isr(7); }
#ifdef USE_TIMER_FOR_TRIGGER
#if TRIGGER_PULSE_WIDTH != 0
void UltrasonicAsyncPWM::_timer0() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[0], LOW);
timer0.end();
}
void UltrasonicAsyncPWM::_timer1() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[1], LOW);
timer1.end();
}
void UltrasonicAsyncPWM::_timer2() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[2], LOW);
timer2.end();
}
void UltrasonicAsyncPWM::_timer3() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[3], LOW);
timer3.end();
}
void UltrasonicAsyncPWM::_timer4() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[4], LOW);
timer4.end();
}
void UltrasonicAsyncPWM::_timer5() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[5], LOW);
timer5.end();
}
void UltrasonicAsyncPWM::_timer6() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[6], LOW);
timer6.end();
}
void UltrasonicAsyncPWM::_timer7() {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
digitalWrite(_this->_trigger[7], LOW);
timer7.end();
}
#endif
#endif
/** Add a sensor
@param trigger - Trigger pin.
@param echo - Pin for reading echno signal. Not necessary a PWM pin, but it must support interrupts.
*/
void UltrasonicAsyncPWM::add(uint8_t trigger, uint8_t echo) {
if (nextFree >= MAX_ULTRASONIC_ASYNC_PWM)
error("Too many sensors. Increase MAX_ULTRASONIC_ASYNC_PWM.");
if (nextFree > 8)
error("Not enough interrupt handlers.");
_trigger[nextFree] = trigger;
_echo[nextFree] = echo;
_finished[nextFree] = false;
pinMode(trigger, OUTPUT);
digitalWrite(trigger, PULSE_IS_HIGH ? LOW : HIGH);
pinMode(echo, INPUT);
switch (nextFree) {
case 0: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr0, CHANGE); break;
case 1: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr1, CHANGE); break;
case 2: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr2, CHANGE); break;
case 3: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr3, CHANGE); break;
case 4: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr4, CHANGE); break;
case 5: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr5, CHANGE); break;
case 6: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr6, CHANGE); break;
case 7: attachInterrupt(digitalPinToInterrupt(echo), _echo_isr7, CHANGE); break;
}
nextFree++;
}
/** Distance in cm
@param sensorNumber - Sensor's index. Function add() assigns 0 to first sensor, 1 to second, etc.
@return - Distance.
*/
float UltrasonicAsyncPWM::distance(uint8_t sensorNumber) {
return (_impulsEnd[sensorNumber] - _impulsStart[sensorNumber]) / 58.0;
}
/** Interrupt function
@param sensorNumber - Sensor's index. Function add() assigns 0 to first sensor, 1 to second, etc.
*/
void UltrasonicAsyncPWM::_echo_isr(uint8_t sensorNumber) {
UltrasonicAsyncPWM* _this = UltrasonicAsyncPWM::instance();
switch (digitalRead(_this->_echo[sensorNumber])) {
case PULSE_IS_HIGH ? HIGH : LOW :
_this->_impulsStart[sensorNumber] = micros();
_this->_highDetected[sensorNumber] = true;
break;
case PULSE_IS_HIGH ? LOW : HIGH :
if (_this->_highDetected[sensorNumber]) {
_this->_impulsEnd[sensorNumber] = micros();
_this->_finished[sensorNumber] = true;
}
break;
}
}
/** Print to all serial ports
@param message
@param eol - end of line
*/
void UltrasonicAsyncPWM::print(String message, bool eol) {
if (eol) {
Serial.println(message);
if (serial != 0)
serial->println(message);
}
else {
Serial.print(message);
if (serial != 0)
serial->print(message);
}
}
/** Trigger a pulse.
@param sensorNumber - Sensor's index. Function add() assigns 0 to first sensor, 1 to second, etc.
*/
void UltrasonicAsyncPWM::start(uint8_t sensorNumber) {
_finished[sensorNumber] = false;
_highDetected[sensorNumber] = false;
digitalWrite(_trigger[sensorNumber], PULSE_IS_HIGH ? HIGH : LOW);
bool isTimer = false;
#ifdef USE_TIMER_FOR_TRIGGER
#if TRIGGER_PULSE_WIDTH != 0
switch (sensorNumber) {
case 0: timer0.begin(_timer0, 10000); break;
case 1: timer1.begin(_timer1, 10000); break;
case 2: timer2.begin(_timer2, 10000); break;
case 3: timer3.begin(_timer3, 10000); break;
case 4: timer4.begin(_timer4, 10000); break;
case 5: timer5.begin(_timer5, 10000); break;
case 6: timer6.begin(_timer6, 10000); break;
case 7: timer7.begin(_timer7, 10000); break;
} //10 msec
isTimer = true;
#endif
#endif
if (!isTimer) {
delayMicroseconds(TRIGGER_PULSE_WIDTH);
digitalWrite(_trigger[sensorNumber], PULSE_IS_HIGH ? LOW : HIGH);
}
}
/**Test
@param breakWhen - A function returning bool, without arguments. If it returns true, the test() will be interrupted.
*/
void UltrasonicAsyncPWM::test(BreakCondition breakWhen) {
while (breakWhen == 0 || !(*breakWhen)()) {
for (int i = 0; i < nextFree; i++) {
start(i); // Trigger a pulse
uint32_t startMs = millis();
bool ok = true;
while (!isFinished(i)) // Wait for the result. If more than 100 ms, signal timeout.
if (millis() - startMs > 100) {
print("Timeout for sensor " + (String)i + " ");
ok = false;
break;
}
if (ok) // If ok, print the result
print((String)distance(i) + "cm ");
}
print("", true);
delay(200);
}
}
| true |
c716f428760650b18a771aa37b8b57a10a202c38 | C++ | ooooo-youwillsee/leetcode | /0501-1000/0888-Fair-Candy-Swap/cpp_0888/Solution1.h | UTF-8 | 632 | 2.875 | 3 | [
"MIT"
] | permissive | /**
* @author ooooo
* @date 2020/9/30 15:42
*/
#ifndef CPP_0888__SOLUTION1_H_
#define CPP_0888__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <numeric>
using namespace std;
class Solution {
public:
vector<int> fairCandySwap(vector<int> &A, vector<int> &B) {
int sum_a = accumulate(A.begin(), A.end(), 0), sum_b = accumulate(B.begin(), B.end(), 0);
unordered_set<int> s(B.begin(), B.end());
int diff = (sum_a + sum_b) / 2 - sum_a;
for (auto &item: A) {
if (s.find(item + diff) != s.end()) return {item, item + diff};
}
return {};
}
};
#endif //CPP_0888__SOLUTION1_H_
| true |
d3c5e2622a7e659ef0ca977df9804bb6ac7d8452 | C++ | Dagomsa/AdventOfCode2020 | /Day18/Day18.cpp | UTF-8 | 5,232 | 3.15625 | 3 | [] | no_license | // Day18.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
uint64_t Part(int i);
uint64_t Solve1(std::string& str);
uint64_t Solve2(std::string& str);
void operate(std::string& str);
void SolveSums(std::string& deepop);
void operatesum(std::string& str);
int CalculateDepthMapParentheses(const std::string& str, std::string& strmap);
int CalculateDepthMapSum(const std::string& str, std::string& strmap);
int main()
{
std::cout << "Part 1 solution: " << Part(1) << "\n";
std::cout << "Part 2 solution: " << Part(2) << "\n";
}
uint64_t Part(int i)
{
uint64_t result = 0;
std::ifstream input;
input.open("input.txt");
std::string line;
auto function = i == 1 ? Solve1 : Solve2;
while (getline(input, line))
{
result += function(line);
}
return result;
}
uint64_t Solve1(std::string& str)
{
std::string strmap;
int maxdeep = CalculateDepthMapParentheses(str, strmap);
while (maxdeep >= 0)
{
std::string level = std::to_string(maxdeep);
int pos1 = strmap.find(level);
int pos2 = strmap.find_first_not_of(level, pos1);
if (maxdeep != 0)
{
std::string deepop = str.substr(pos1, pos2 - pos1);
operate(deepop);
str.replace(pos1, pos2 - pos1, deepop);
maxdeep = CalculateDepthMapParentheses(str, strmap);
}
else
{
operate(str);
return stoull(str);
}
}
}
uint64_t Solve2(std::string& str)
{
std::string strmap;
int maxdeep = CalculateDepthMapParentheses(str, strmap);
while (maxdeep >= 0)
{
std::string level = std::to_string(maxdeep);
int pos1 = strmap.find(level);
int pos2 = strmap.find_first_not_of(level, pos1);
if (maxdeep != 0)
{
std::string deepop = str.substr(pos1, pos2 - pos1);
deepop.erase(deepop.begin());
deepop.erase(deepop.end() - 1);
SolveSums(deepop);
operate(deepop);
str.replace(pos1, pos2 - pos1, deepop);
maxdeep = CalculateDepthMapParentheses(str, strmap);
}
else
{
SolveSums(str);
operate(str);
return stoull(str);
}
}
}
void operate(std::string& str)
{
////Erase parentesis
if (str.find("(") != str.npos)
{
str.erase(str.begin());
str.erase(str.end()-1);
}
std::string stmp;
uint64_t num1;
uint64_t num2;
char op;
std::stringstream ss;
ss << str;
bool first = true;
while (!ss.eof())
{
ss >> stmp;
if (first)
{
num1 = stoi(stmp);
first = false;
continue;
}
if (std::stringstream(stmp) >> num2)
{
if (op == '+')
num1 += num2;
if (op == '*')
num1 *= num2;
}
else
std::stringstream(stmp) >> op;
}
str = std::to_string(num1);
}
void SolveSums(std::string& deepop)
{
std::string strmap2;
int maxdeepsum = CalculateDepthMapSum(deepop, strmap2);
while (maxdeepsum > 0)
{
std::string level = std::to_string(maxdeepsum);
int pos1s = strmap2.find(level);
int pos2s = strmap2.find_first_not_of(level, pos1s);
if (pos2s == strmap2.npos)
pos2s = strmap2.length();
std::string deepopsum = deepop.substr(pos1s, pos2s - pos1s);
operatesum(deepopsum);
deepop.replace(pos1s, pos2s - pos1s, deepopsum);
maxdeepsum = CalculateDepthMapSum(deepop, strmap2);
}
}
void operatesum(std::string& str)
{
////Erase parentesis
if (str.find("(") != str.npos)
{
str.erase(str.begin());
str.erase(str.end() - 1);
}
std::string stmp;
uint64_t num1;
uint64_t result = 0;
std::stringstream ss;
ss << str;
while (!ss.eof())
{
ss >> stmp;
if (std::stringstream(stmp) >> num1)
result += num1;
}
str = std::to_string(result);
}
int CalculateDepthMapParentheses(const std::string& str, std::string& strmap)
{
strmap.clear();
uint8_t deep = 0;
uint8_t maxdeep = 0;
for (auto& c : str)
{
if (c == '(')
{
deep++;
maxdeep = maxdeep > deep ? maxdeep : deep;
}
strmap.append(std::to_string(deep));
if (c == ')')
deep--;
}
return maxdeep;
}
int CalculateDepthMapSum(const std::string& str, std::string& strmap)
{
strmap.clear();
uint8_t deep = 0;
uint8_t maxdeep = 0;
for (auto& c : str)
strmap.append("0");
int ini = 0;
int end = 0;
while (true)
{
int pos = str.find("+" , end);
if (pos == str.npos)
return maxdeep;
maxdeep = 1;
ini = str.rfind(" ", pos - 2) + 1;
end = str.find("*", pos);
if (end == str.npos)
end = str.length() - 1;
else
end -= 2;
for (int i = ini; i <= end; ++i)
strmap[i] = '1';
}
} | true |
9e5440e4514df16273c9cc5ec7e4010f25daf7d4 | C++ | walkccc/LeetCode | /solutions/0926. Flip String to Monotone Increasing/0926.cpp | UTF-8 | 380 | 3.078125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int minFlipsMonoIncr(string s) {
// # of chars to be flilpped to make substring so far monotone increasing
int dp = 0;
int count1 = 0;
for (const char c : s)
if (c == '0')
// 1. Flip '0'.
// 2. Keep '0' and flip previous '1's.
dp = min(dp + 1, count1);
else
++count1;
return dp;
}
};
| true |
e8b1eab0cec0d6b8fb20e555980e18bfe3f53718 | C++ | dazotaro/defender | /graphics/GLSLProgram.hpp | UTF-8 | 2,326 | 2.609375 | 3 | [] | no_license | #ifndef GLSLPROGRAM_H
#define GLSLPROGRAM_H
// Local Includes
#include "../graphics/gl_core_4_2.hpp" // glLoadGen generated header file
#include "../core/Defs.hpp" // JU::uint32
// Global Includes
#include <string> // std::string
#include <glm/glm.hpp> // glm::vecX
namespace JU
{
namespace GLSLShader
{
enum GLSLShaderType
{
VERTEX,
FRAGMENT,
GEOMETRY,
TESS_CONTROL,
TESS_EVALUATION
};
}
/*
* @brief Class encapsulating a GLSL Program
*
* @detail Class encapsulating a GLSL Program that also adds some member functions to set uniform variables. This class was mostly copied from the Cookbook code.
*/
class GLSLProgram
{
public:
static const std::string COLOR_TEX_PREFIX;
static const std::string NORMAL_MAP_TEX_PREFIX;
GLSLProgram();
bool compileShaderFromFile(const char * fileName, GLSLShader::GLSLShaderType type);
bool compileShaderFromString(const std::string & source, GLSLShader::GLSLShaderType type);
bool link();
bool validate();
void use() const;
std::string log() const;
GLuint getHandle() const;
bool isLinked() const;
void bindAttribLocation(GLuint location, const char * name);
void bindFragDataLocation(GLuint location, const char * name);
void setUniform(const char* name, float x, float y, float z) const;
void setUniform(const char* name, const glm::vec3 & v) const;
void setUniform(const char* name, const glm::vec4 & v) const;
void setUniform(const char* name, const glm::mat4 & m) const;
void setUniform(const char* name, const glm::mat3 & m) const;
void setUniform(const char* name, float val ) const;
void setUniform(const char* name, int val ) const;
void setUniform(const char* name, bool val ) const;
void printActiveUniforms() const;
void printActiveAttribs() const;
private:
GLint getUniformLocation(const char * name ) const;
private:
GLuint handle_; //!< Program handle
bool linked_; //!< Is linked?
std::string log_string_; //!< Output log string
};
} // namespace JU
#endif // GLSLPROGRAM_H
| true |
20537cb36291bd6136653eb516a1d9d5822ea194 | C++ | muneerkhann13/Tree | /isSumTree.cpp | UTF-8 | 589 | 3.046875 | 3 | [] | no_license | bool isSumTree1(node *root){
if(root==NULL || (root->left==NULL &&root->right==NULL) )
return true;
int l,r;
if(isSumTree1(root->left)&&isSumTree1(root->right)){
if(root->left==NULL)
l=0;
else if (root->left->left==NULL && root->left->right==NULL)
l=root->left->data;
else
l=2*root->left->data;
if(root->right==NULL)
r=0;
else if (root->right->left==NULL && root->right->right==NULL)
r=root->right->data;
else
r=2*root->right->data;
return root->data==l+r;
}
return false;
}
| true |
2d0dbf5bee833178c6a50c1c3c4b473dcbe21775 | C++ | Gh05ts/DS-Algo | /Problems/DP/EggDrop.cpp | UTF-8 | 847 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int eggDrop(int n, int h) {
if(n == 1) return h;
if(h == 0 || h == 1) return h;
int res = INT_MAX;
for(int i = 1; i <= h; i++) {
res = min(res, (1 + max(eggDrop(n - 1, i - 1), eggDrop(n, h - i))));
} return res;
}
int eggDropDP(int n, int h) {
int dp[n + 1][h + 1];
for(int i = 0; i <= h; i++) dp[0][i] = 0;
for(int i = 1; i <= h; i++) dp[1][i] = i;
for(int j = 1; j <= n; j++) dp[j][0] = 0;
for(int i = 2; i <= n; i++) {
for(int j = 1; j <= h; j++) {
dp[i][j] = INT_MAX;
for(int x = 1; x <= j; x++) dp[i][j] = min(dp[i][j], (1 + max(dp[i - 1][x - 1], dp[i][j - x])));
}
} return dp[n][h];
}
int main() {
// cout << eggDrop(2, 100);
cout << eggDropDP(2, 100);
return 0;
} | true |
44dae602e8bfa61832a1b1654d848e02b2bf67bb | C++ | arquolo/kerasify | /src/layers/activation.cpp | UTF-8 | 2,018 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2016 Robert W. Rose
* Copyright (c) 2018 Paul Maevskikh
*
* MIT License, see LICENSE file.
*/
#include "keras/layers/activation.h"
namespace keras {
namespace layers {
Activation::Activation(Stream& file) : type_(file) {
switch (type_) {
case Linear:
case Relu:
case Elu:
case SoftPlus:
case SoftSign:
case HardSigmoid:
case Sigmoid:
case Tanh:
case SoftMax:
return;
}
kassert(false);
}
Tensor Activation::forward(const Tensor& in) const noexcept {
switch (type_) {
case Linear:
return in;
case Relu:
return in.map([](float x) { return (x < 0.f ? 0.f : x); });
case Elu:
return in.map([](float x) { return (x < 0.f ? std::expm1(x) : x); });
case SoftPlus:
return in.map([](float x) { return std::log1p(std::exp(x)); });
case SoftSign:
return in.map([](float x) { return x / (1.f + std::abs(x)); });
case HardSigmoid:
return in.map(
[](float x) { return std::clamp((x * .2f + .5f), 0.f, 1.f); });
case Sigmoid:
return in.map([](float x) {
float z = std::exp(-std::abs(x));
if (x < 0)
return z / (1.f + z);
return 1.f / (1.f + z);
});
case Tanh:
return in.map([](float x) { return std::tanh(x); });
case SoftMax: {
auto channels = cast(in.dims_.back());
kassert(channels > 1);
auto tmp = in.map([](float x) { return std::exp(x); });
auto out = Tensor::empty(in);
auto out_ = std::back_inserter(out.data_);
for (auto t_ = tmp.begin(); t_ != tmp.end(); t_ += channels) {
// why std::reduce not in libstdc++ yet?
auto norm = 1.f / std::accumulate(t_, t_ + channels, 0.f);
std::transform(
t_, t_ + channels, out_, [norm](float x) { return norm * x; });
}
return out;
}
}
kassert(false);
return in;
}
} // namespace layers
} // namespace keras
| true |
1236091e469cfe83362db62a6c3ca541d70fee65 | C++ | zhuwenboa/Cpp-practice | /c++/practice/overload.cpp | UTF-8 | 370 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<vector>
void func(int a)
{
std::cout << "func1" << "\n";
}
//int func(int a);
//void func(int a, int b);
void func(const int a, int b)
{
std::cout << "func2" << "\n";
}
class test
{
public:
test(int b) : a(b) {}
private:
static int count;
int a;
};
int test::count = 1;
int main()
{
test t(2);
func(1);
} | true |
1d406c0498b2f0637d92995db558a7dc880555cf | C++ | Palette25/Computer-Vision | /Week6/16340023+陈明亮+Ex6/src/ImageStitching.h | UTF-8 | 826 | 2.5625 | 3 | [] | no_license | /*
* Program: ImageStitching.cpp
* Usage: Start image stitching
*/
#ifndef IMAGE_STITCHING_H
#define IMAGE_STITCHING_H
#include <vector>
#include <queue>
#include "SIFT.h"
#include "Utils.h"
#include "Matching.h"
#include "Warping.h"
#include "Blending.h"
class Stitcher{
public:
Stitcher(vector<CImg<unsigned char>> input);
CImg<unsigned char> stitchImages();
// Tool functions
int computeMiddle(vector<vector<int>>& indexes);
void addFeaturesByHomoegraphy(map<vector<float>, VlSiftKeypoint>& feature, Axis H, float offset_x, float offset_y);
void adjustOffset(map<vector<float>, VlSiftKeypoint>& feature, int offset_x, int offset_y);
private:
vector<CImg<unsigned char>> src;
// Features of every images
vector<map<vector<float>, VlSiftKeypoint>> features;
// Tools
Warper wr;
Matcher mt;
Utils ut;
};
#endif | true |
45dfb76ce47356712ce34da6288475ad0098a0a8 | C++ | hansenms/gadgetron | /gadgets/bart/bart_helpers.cpp | UTF-8 | 6,382 | 2.546875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "bart_helpers.h"
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/tokenizer.hpp>
#include <random>
// =============================================================================
namespace fs = Gadgetron::fs;
fs::path internal::generate_unique_folder(const fs::path& working_directory)
{
typedef std::chrono::system_clock clock_t;
char buff[80];
auto now = clock_t::to_time_t(clock_t::now());
std::strftime(buff, sizeof(buff), "%H_%M_%S__", std::localtime(&now));
std::random_device rd;
auto time_id(buff + std::to_string(std::uniform_int_distribution<>(1, 10000)(rd)));
// Get the current process ID
auto threadId = boost::lexical_cast<std::string>(boost::this_thread::get_id());
auto threadNumber(0UL);
sscanf(threadId.c_str(), "%lx", &threadNumber);
return working_directory / ("bart_"
+ time_id
+ "_"
+ std::to_string(threadNumber));
}
// ========================================================================
void internal::ltrim(std::string &str)
{
str.erase(str.begin(), std::find_if(str.begin(), str.end(),
[](int s) {return !std::isspace(s); }));
}
void internal::rtrim(std::string &str)
{
str.erase(std::find_if(str.rbegin(), str.rend(),
[](int s) {return !std::isspace(s);}).base(),
str.end());
}
void internal::trim(std::string &str)
{
ltrim(str);
rtrim(str);
}
std::string internal::get_output_filename(const std::string& command_line)
{
boost::char_separator<char> sep(" ");
std::vector<std::string> tokens;
boost::tokenizer<boost::char_separator<char>> tokenizer(command_line, sep);
for (auto& tok : tokenizer) {
tokens.push_back(tok);
}
// Find begin of argument list
auto num_args(tokens.size()-1);
auto it(tokens.cbegin());
if (*it == "bart") {
++it;
--num_args;
}
// it now points to the name of the BART command
if (*it == "bitmask"
|| *it == "estdelay"
|| *it == "estdims"
|| *it == "estshift"
|| *it == "estvar"
|| *it == "nrmse"
|| *it == "sdot"
|| *it == "show"
|| *it == "version") {
return "";
}
else {
const auto end(tokens.cend());
const auto arg1(*(it+1));
const auto arg1_not_option(arg1[0] != '-');
/*
* Essentially, the algorithm considers only the BART functions where
* the output argument might not be the last one.
*
* For these commands, if a sufficient number of argument is provided
* there is no ambiguity possible since we can always find the last
* "flag-like" looking argument on the command line and then infer
* the position of the output from there.
* If there might be an ambiguity, we look at the first argument of
* the BART command and depending on whether it is a flag or not,
* we can infer the position of the output argument on the command
* line.
*/
if (*it == "ecalib") {
if (num_args > 3) {
auto it2 = --tokens.cend();
for (; it2 != it && (*it2)[0] != '-'; --it2);
const char& first((*it2)[0]);
const char& second((*it2)[1]);
if (first == '-'
&& (it2->size() > 2 // handle cases like -t12 (ie. -t 12)
|| second == 'S'
|| second == 'W'
|| second == 'I'
|| second == '1'
|| second == 'P'
|| second == 'a')) {
std::cout << "ecalib: flag\n";
return *(it2 + 2);
}
else {
return *(it2 + 3);
}
}
else if (num_args == 3 && arg1_not_option) {
return *(end - 2);
}
// Minimum arguments to ecalib
// 2 kspace sens
// 3 -I kspace sens
// 3 kspace sens ev-maps
// 4 -t 11 kspace sens
// 4 -P kspace sens ev-maps
// 4 -t11 kspace sens ev-maps
}
else if (*it == "ecaltwo") {
if (num_args > 6) {
auto it2 = --tokens.cend();
for (; it2 != it && (*it2)[0] != '-'; --it2);
const char& first((*it2)[0]);
const char& second((*it2)[1]);
if (first == '-'
&& (it2->size() > 2 // handle cases like -t12 (ie. -t 12)
|| second == 'S')) {
return *(it2 + 5);
}
else {
return *(it2 + 6);
}
}
else if (num_args == 6 && arg1[0] != '-') {
return *(end - 2);
}
// Minimum arguments to ecaltwo
// 6 x y z <input> <sensitivities> [<ev_maps>]
// 6 -S x y z <input> <sensitivities>
// 7 -m 3 x y z <input> <sensitivities>
// 7 -S x y z <input> <sensitivities> [<ev_maps>]
}
else if (*it == "nlinv") {
if (num_args > 3) {
auto it2 = --tokens.end();
for (; it2 != it && (*it2)[0] != '-'; --it2);
const char& first((*it2)[0]);
const char& second((*it2)[1]);
if (first == '-'
&& (it2->size() > 2 // handle cases like -t12 (ie. -t 12)
|| second == 'c'
|| second == 'N'
|| second == 'U'
|| second == 'g'
|| second == 'S')) {
return *(it2 + 2);
}
else {
return *(it2 + 3);
}
}
else if (num_args == 3 && arg1[0] != '-') {
return *(end - 2);
}
// Minimum arguments to nlinv
// 2 kspace output
// 3 kspace output sens
// 3 -S kspace output
// 4 -i d kspace output
// 4 -S kspace output sens
}
else if (*it == "whiten") {
if (num_args > 5) {
auto it2 = --tokens.end();
for (; it2 != it && (*it2)[0] != '-'; --it2);
const char& first((*it2)[0]);
const char& second((*it2)[1]);
if (first == '-'
&& (it2->size() > 2 // handle cases like -t12 (ie. -t 12)
|| second == 'n')) {
return *(it2 + 3);
}
else {
return *(it2 + 4);
}
}
else if(num_args == 5 && arg1_not_option) {
return *(end - 3);
}
else if (num_args == 4 && arg1_not_option) {
return *(end - 2);
}
// Minimum arguments to whiten
// 3 input ndata output
// 4 input ndata output optmat
// 4 -n input ndata output
// 5 -o asd input ndata output
// 5 -n input ndata output optmat
// 5 input ndata output optmat covar_out
}
}
return tokens.back();
}
| true |
634e80d2d93a3610498ce954b675c55fa70495a9 | C++ | alexandraback/datacollection | /solutions_2749486_0/C++/HubertJ/pogo2.cpp | UTF-8 | 2,180 | 2.703125 | 3 | [] | no_license | #include <cstdio>
#include <math.h>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <bitset>
#include <cassert>
#include <queue>
#include <tuple>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
int c, cases;
cin >> cases;
for(c = 1; c <= cases; c++)
{
int x, y;
cin >> x;
cin >> y;
string s;
int curX = 0;
int curY = 0;
for (int i = 1; i <= 500; i++)
{
if (curX == x && curY == y)
break;
string nextDir = "0";
if (i == abs(curX-x))
{
if (x > curX)
{
nextDir = "E";
curX+=i;
}
else
{
nextDir = "W";
curX-=i;
}
}
else if (i == abs(curY-y))
{
if (y > curY)
{
nextDir = "N";
curY+=i;
}
else
{
nextDir = "S";
curY-=i;
}
}
if (nextDir != "0")
{
s.append(nextDir);
continue;
}
if (i < abs(curX-x))
{
if (x > curX)
{
nextDir = "E";
curX+=i;
}
else
{
nextDir = "W";
curX-=i;
}
}
else if (i == abs(curY-y))
{
if (y > curY)
{
nextDir = "N";
curY+=i;
}
else
{
nextDir = "S";
curY-=i;
}
}
if (nextDir != "0")
{
s.append(nextDir);
continue;
}
if (curX != x)
{
int diff = abs(curX - x);
if (x > curX)
{
for (int j = 0; j < diff; j++)
{
s.append("WE");
curX+=1;
i+=2;
}
i--;
}
else
{
for (int j = 0; j < diff; j++)
{
s.append("EW");
curX-=1;
i+=2;
}
i--;
}
}
else
{
int diff = abs(curY - y);
if (y > curY)
{
for (int j = 0; j < diff; j++)
{
s.append("SN");
curY+=1;
i+=2;
}
i--;
}
else
{
for (int j = 0; j < diff; j++)
{
s.append("NS");
curY-=1;
i+=2;
}
i--;
}
}
//s.append(nextDir);
}
cout << "Case #" << c << ": " << s << endl;
}
}
| true |
fe15456a25dbcd25d2f15a5f03143d907d0beafe | C++ | Jrice170/Vector- | /MyVector.hpp | UTF-8 | 4,159 | 3.515625 | 4 | [] | no_license | /* Define all your MyVector-related functions here.
* Also, define the swap function here.
* You do not need to include the h file.
* It included this file at the bottom.
*/
#include<cstdlib>
void get_identity(string &my_id)
{
my_id = "jmr3by";
}
template<typename T>
void swap(T & a,T &b)
{
T temp = a;
a = b;
b = temp;
}
// We're giving you this one for free
// and as a guide for the syntax.
template <typename T>
MyVector<T>::~MyVector()
{
delete[] m_data;
}
// Another example: remember when writing an implementation in hpp,
// return type first, then scope just before the function name.
// google how to trow out of range
template <typename T>
T & MyVector<T>::at(int index)
{
if(!(index < size()))
{
throw std::out_of_range("Its alive !!!!!");
}
return m_data[index];
}
template <typename T>
MyVector<T>::MyVector()
{
m_data = nullptr;
reserved_size = 0;
data_size =0;
}
template <typename T>
MyVector<T> & MyVector<T>::operator =(const MyVector<T> & source)
{
if(reserved_size != source.reserved_size)
{
delete m_data;
m_data = new T[reserved_size];
}
reserved_size = source.reserved_size;
data_size = source.data_size;
for(int i = 0;i<data_size;i++)
{
m_data[i] = source.m_data[i];
}
return *this;
}
template <typename T>
MyVector<T>::MyVector(const MyVector<T> & source)
{
reserved_size = source.reserved_size;
data_size = source.data_size;
m_data = new T[reserved_size];
for(int i = 0;i < data_size;i++)
{
m_data[i] = source.m_data[i];
}
}
template <typename T>
T & MyVector<T>::front()
{
return m_data[0];
}
template <typename T>
T & MyVector<T>::back()
{
return m_data[data_size-1];
}
template <typename T>
int MyVector<T>::capacity()
{
return reserved_size;
}
// question about resereve does this function need exceptions
template <typename T>
void MyVector<T>::reserve(int new_cap)
{
if(new_cap > capacity())
{
T *store_data = new T[new_cap];
for(int i =0;i<size();i++)
{
store_data[i] = m_data[i];
}
reserved_size = new_cap;
delete m_data;
m_data = store_data;
}
}
template <typename T>
void MyVector<T>::push_back(const T &x)
{
if(data_size>=reserved_size)
{
reserve(reserved_size+1);
}
m_data[data_size] = x;
data_size++;
}
template <typename T>
void MyVector<T>::pop_back()
{
if(data_size > 0)
{
data_size--;
}
if((size())<(capacity())/(4))
{
shrink_to_fit();
}
}
template <typename T>
T & MyVector<T>::operator[](int index)
{
return m_data[index];
}
template <typename T>
void MyVector<T>::insert(int i,const T & x)
{
data_size = (data_size + 1);
if(size() >= capacity())
{
reserve(reserved_size + 1);
}
for(int j = data_size;(j<=data_size) && (j>i);j--)
{
m_data[j] = m_data[j-1];
}
m_data[i] = x;
}
template <typename T>
int MyVector<T>::size()
{
if(capacity() ==0 || data_size == 0)
{
return 0;
}
return (data_size);
}
template <typename T>
void MyVector<T>::shrink_to_fit()
{
int new_capacity_size = 2* data_size;
T *Pointer = new T[new_capacity_size];
for(int i=0;i<size();i++)
{
Pointer[i] = m_data[i];
}
reserved_size = new_capacity_size;
delete [] m_data;
m_data = Pointer;
}
template <typename T>
void MyVector<T>::erase(int i)
{
if(size()>0)
{
data_size--;
}
if((size())<(capacity())/(4))
{
shrink_to_fit();
}
for(int j = i;j < size();j++)
{
m_data[j] = m_data[j+1];
}
}
template <typename T>
void MyVector<T>::clear()
{
data_size=0;
reserved_size = 0;
delete m_data;
m_data = nullptr;
}
template <typename T>
void MyVector<T>::assign(int count,const T &value)
{
clear();
m_data = new T[count];
reserved_size = count;
data_size = count;
for(int i =0;i<size();i++)
{
m_data[i] = value;
}
}
| true |
8efddef2eda3b7a4434ed49c06f35436b797ee6d | C++ | BryanBrouwer/OldRayTracer | /Renderer/Tracer.cpp | UTF-8 | 9,010 | 2.890625 | 3 | [] | no_license | #include "Tracer.h"
#include <iostream>
#include <algorithm>
Tracer::Tracer(int width, int height, float aspectratio, vec3 background)
{
ScreenWidth = width;
ScreenHeight = height;
AspectRatio = aspectratio;
ReflectDepth = 5;
Background = background;
//CameraPosition = vec3(0.f, 0.f, -10.f);
}
Tracer::~Tracer()
{
for (int i = 0; i < lights.size(); i++)
{
delete(lights[i]);
}
lights.clear();
// delete Shapes that couldnt go into BVH
for (int i = 0; i < Shapes.size(); i++)
{
delete(Shapes[i]);
}
Shapes.clear();
//delete bvhs, which also deletes the nodes, which also delete the shapes saved in the nodes
for (int i = 0; i < Bvhs.size(); i++)
{
delete(Bvhs[i]);
}
}
void Tracer::AddShape(Shape * shape)
{
Shapes.push_back(shape);
}
//Add to vectors
void Tracer::AddLight(Lights * light)
{
lights.push_back(light);
}
void Tracer::AddBVH(BVH* bvh)
{
Bvhs.push_back(bvh);
}
void Tracer::updateCamPos(const mat4 & convertmat)
{
CameraPosition = convertmat * CameraPosition;
}
// Reflection Checks
vec3 Tracer::CheckReflection(const Ray& ray, Shape* shape)
{
vec3 ReflectedColor = shape->getColor();
float t = 0.f;
if (shape->checkReflective() == true)
{
for (int i = 0; i < Shapes.size(); i++)
{
if (Shapes[i] != shape)
{
if (Shapes[i]->checkTransparant() == false)
{
if (Shapes[i]->Intersection(ray, t))
{
ReflectDepth++;
vec3 hitpoint = ray.getPoint(t);
hitpoint = hitpoint.normalize();
vec3 NextRayDirection = ReflectedRayDirection(Shapes[i]->getSurfaceNormal(hitpoint), ray.getDirection());
const Ray raynew(hitpoint, NextRayDirection);
ReflectedColor = CheckReflection(raynew, Shapes[i]);
if (ReflectDepth > MaxReflect)
{
return Background;
}
ReflectedColor = ReflectedColor * 0.8f;
for (int j = 0; j < 3; j++)
{
if (ReflectedColor[j] > 255.f)
{
ReflectedColor[j] = 255.f;
}
}
}
}
}
}
}
return ReflectedColor;
}
//Calculate Reflected Ray Direction
vec3 Tracer::ReflectedRayDirection(const vec3& surfacenormal, const vec3& primairyraydirection)
{
//Normalize required vectors
vec3 SphereSurfaceNormal = surfacenormal;
vec3 PrimairyRayDirection = primairyraydirection;
SphereSurfaceNormal = SphereSurfaceNormal.normalize();
PrimairyRayDirection = PrimairyRayDirection.normalize();
//Calculate reflected ray according to my calculations
vec3 B = (SphereSurfaceNormal * SphereSurfaceNormal.dot(PrimairyRayDirection));
vec3 A = (PrimairyRayDirection - B);
vec3 ReflectedRay = A - B;
ReflectedRay = ReflectedRay.normalize();
return ReflectedRay;
}
vec3 Tracer::getRefraction(const Ray& ray, Shape* shape, const vec3& hitpoint)
{
vec3 RefractionDir = vec3(0,0,0);
vec3 AOI = ray.getDirection();
vec3 Hit = hitpoint;
vec3 N = shape->getSurfaceNormal(Hit);
float IdotN = AOI.dot(N);
float IORSecond = shape->getIOR();
float IORFirst = 1.f;
if (IdotN < 0)
{
IdotN = -IdotN;
}
else if (IdotN > 0)
{
N = vec3(0,0,0) - N;
IORFirst = shape->getIOR();
IORSecond = 1.f;
}
float IORCalc = IORFirst / IORSecond;
float K = (1 - IORCalc * IORCalc * (1 - IdotN * IdotN));
if (K < 0)
{
return vec3(0,0,0);
}
vec3 tempColor = ((AOI * IORCalc) + (N *(IORCalc * IdotN - sqrtf(K))));
RefractionDir = tempColor;
RefractionDir = RefractionDir.normalize();
return RefractionDir;
}
vec3 Tracer::CalcSeparateBlinnPhong(const vec3& raydirection, const vec3& hitpoint, const vec3& surfacenormal)
{
vec3 BlinnPhongColorReflect = vec3(0, 0, 0);
vec3 SurfaceNormal = surfacenormal;
//blinn - phong shading
for (int i = 0; i < lights.size(); i++)
{
vec3 lightDirection = lights[i]->getPointCords() - hitpoint;
lightDirection = lightDirection.normalize();
vec3 RayToEye = vec3(0, 0, 0) - raydirection;
vec3 HalfVec = ((lightDirection + RayToEye) / (lightDirection + RayToEye).length());
HalfVec = HalfVec.normalize();
constexpr float ReflectionPower = 1000.f;
BlinnPhongColorReflect = (BlinnPhongColorReflect + (lights[i]->getSpecularColor() * pow(max(0.f, SurfaceNormal.dot(HalfVec)), ReflectionPower) * lights[i]->getIntensity()));
}
return BlinnPhongColorReflect;
}
//Trace all Shapes
vec3 Tracer::Trace(int x, int y, const float & fov, const mat4 & convertmat)
{
//convert ints to float and set default color
float X = static_cast<float>(x);
float Y = static_cast<float>(y);
float Width = static_cast<float>(ScreenWidth);
float Height = static_cast<float>(ScreenHeight);
FOV = fov;
vec3 PixelColor = Background;
//new with camera
float Scale = tanf(degToRad*(FOV * 0.5f));
float NDCX = ((X + 0.5f) / Width);
float NDCY = ((Y + 0.5f) / Height);
float CamX = ((2.f * NDCX - 1.f) * AspectRatio * Scale);
float CamY = ((1.f - 2.f * NDCY) * Scale);
vec3 tempOrigin = vec3(0, 0, -10.f);
const vec3 vecOrigin = convertmat * tempOrigin;
//const vec3 vecOrigin = CameraPosition;
vec3 tempDir = vec3(CamX, CamY, -1.f);
vec3 vecDirection = convertmat * tempDir;
//set Maximum distance
maxDis = 3000.f;
Dis = 0.f;
vecDirection = vecDirection.normalize();
//Ray creation
const Ray ray(vecOrigin, vecDirection - vecOrigin);
int firstBVH = 5;
float BVHMaxDis = 3000.f;
float BVHDis = 0.f;
for (int i = 0; i < Bvhs.size(); i++)
{
if (Bvhs[i]->intersect(ray, BVHDis))
{
if (BVHDis < BVHMaxDis)
{
firstBVH = i;
}
}
}
int firstNode = 5;
float NODEMaxDis = 3000.f;
float NODEDis = 0.f;
int NodesSize = static_cast<int>(Bvhs[firstBVH]->Nodes.size());
for (int i = 0; i < NodesSize; i++)
{
if (Bvhs[firstBVH]->Nodes[i]->intersect(ray, Dis))
{
if (NODEDis < NODEMaxDis)
{
firstNode = i;
}
}
}
int nodeShapesSize = static_cast<int>(Bvhs[firstBVH]->Nodes[firstNode]->Shapes.size());
for (int i = 0; i < nodeShapesSize; i++)
{
auto tempShape = Bvhs[firstBVH]->Nodes[firstNode]->Shapes[i];
if (tempShape->Intersection(ray, Dis))
{
if (Dis < maxDis)
{
maxDis = Dis;
vec3 color = Shading(ray, tempShape, Dis);
PixelColor = color;
}
}
}
//check for intersection and apply shading for the shapes that could be placed inside bvh
for (int i = 0; i < Shapes.size(); i++)
{
if (Shapes[i]->Intersection(ray, Dis))
{
if (Dis < maxDis)
{
maxDis = Dis;
vec3 color = Shading(ray, Shapes[i], Dis);
PixelColor = color;
}
}
}
// clamp color values
for (int v = 0; v < 3; v++)
{
if (PixelColor[v] > 255.f)
{
PixelColor[v] = 254.f;
}
else if (PixelColor[v] < 0.01f)
{
PixelColor[v] = 0.01f;
}
}
return PixelColor;
}
//Shading to be called for each Shape
vec3 Tracer::Shading(const Ray& ray, Shape* shape, const float& t)
{
//Create all needed vec3's
vec3 color = vec3(0,0,0);
vec3 tempColor = Background;
vec3 calcColor = shape->getColor();
vec3 hitpoint = ray.getPoint(t);
vec3 SurfaceNormal = shape->getSurfaceNormal(hitpoint);
vec3 RayDirect = ray.getDirection();
//check reflection
if (shape->checkReflective() == true)
{
vec3 newrayDirection = ReflectedRayDirection(SurfaceNormal.normalize(), RayDirect);
const Ray raycheck(hitpoint.normalize(), newrayDirection);
calcColor = CheckReflection(raycheck, shape);
vec3 blinnphong = CalcSeparateBlinnPhong(RayDirect, hitpoint, SurfaceNormal);
calcColor = calcColor + blinnphong;
color = calcColor;
}
//reset Reflection depth
ReflectDepth = 0;
if (shape->checkTransparant() == true)
{
vec3 newDir = getRefraction(ray, shape, hitpoint);
vec3 newOrigin = hitpoint.normalize();
const Ray newRay(newOrigin, newDir);
float newDis = 0.0f;
float newMaxDis = 30.f;
tempColor = Background - vec3(30,30,30);
for (int i = 0; i < Shapes.size(); i++)
{
if (Shapes[i] != shape)
{
if (Shapes[i]->Intersection(newRay, newDis))
{
if (newDis < newMaxDis)
{
newMaxDis = newDis;
tempColor = Shapes[i]->getColor();
}
}
}
}
vec3 blinnphong = CalcSeparateBlinnPhong(RayDirect, hitpoint, SurfaceNormal);
color = tempColor + blinnphong;
}
if (shape->checkReflective() == false && shape->checkTransparant() == false)
{
for (int i = 0; i < lights.size(); i++)
{
vec3 lightDirection = lights[i]->getPointCords() - hitpoint;
lightDirection = lightDirection.normalize();
float LambRatio = max(0.f, (SurfaceNormal.dot(lightDirection)));
//blinn - phong shading
vec3 RayToEye = vec3(0, 0, 0) - RayDirect;
vec3 HalfVec = ((lightDirection + RayToEye) / (lightDirection + RayToEye).length());
HalfVec = HalfVec.normalize();
constexpr float ReflectionPower = 1000.f;
vec3 BlinnPhongColor = lights[i]->getSpecularColor() * pow(max(0.f, SurfaceNormal.dot(HalfVec)), ReflectionPower);
vec3 Lambertian = (calcColor * LambRatio);
tempColor = (Lambertian + BlinnPhongColor)* lights[i]->getIntensity();
//vec3 tempLightColor = lights[i].getColor() * lights[i].getIntensity() * LambRatio;
color = color + tempColor/* tempLightColor*/;
}
}
return color;
}
| true |
579521661ad44bbe02ac4e9ffaca397366bcef29 | C++ | Benjamin-Berger/Junior_Year | /cs375/Proj01/Driver.cpp | UTF-8 | 1,613 | 2.96875 | 3 | [] | no_license | //Benjamin Berger
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]){
if(argc == 3){
string line, word;
ifstream myFile (argv[1]);
ofstream outFile (argv[2]);
stringstream ss;
int x;
vector<int> numbers;
vector<int> results;
// vector<int> first;
if(myFile.is_open()){
while(getline(myFile, line)){
ss.clear();
ss << line;
ss >> x;
numbers.push_back (x);
// cout << x << endl;
}
}
myFile.close();
for(int i = 0; i < numbers.size(); i++){
for(int j = 0; j < numbers.size(); j++){
for(int k = 0; k < numbers.size(); k++){
if(numbers[i] == numbers[j] - numbers[k]){
if((i != j) && (j != k) && (i !=k)){
results.push_back (numbers[i]);
results.push_back (numbers[j]);
results.push_back (numbers[k]);
}
}
}
}
}
// for(int i = 0; i < results.size (); i = i + 3){
// first.push_back (results[i]);
// }
// sort(first.begin(), first.end());
// for(int i = 0; i < first.size();i++){
// cout << first[i] << endl;
// }
// for(int i = 0; i < first.size(); i++){
// for(int p = 0; p < results.size(); p = p + 3){
// if(first[i] == results[p]){
// outFile << results[p] << " " << results[p + 1] << " " << results[p +2] << endl;
// }
// }
// }
if(results.size () > 0){
for(int p = 0; p < results.size(); p = p + 3){
outFile << results[p] << " " << results[p + 1] << " " << results[p +2] << endl;
}
}
}
return 0;
} | true |
a5e8c75ad02b59f70f3f61216dc6934006e0ae68 | C++ | SamuelMeilleur/Project-Euler | /Projects/Project 33/Project 33/Source.cpp | UTF-8 | 807 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "Fraction.h"
using namespace std;
int main() {
vector<Fraction> fractions;
for (double n = 10; n < 100; ++n) {
for (double d = n + 1; d < 100; ++d) {
double numerator[2] = { int(n) % 10, int(n / 10) };
double denominator[2] = { int(d) % 10, int(d / 10) };
double fraction = n / d;
if (numerator[0] == denominator[1] &&
denominator[0] != 0 &&
numerator[1] / denominator [0] == fraction) {
fractions.push_back(Fraction(n, d));
}
if (numerator[1] == denominator[0] &&
denominator[1] != 0 &&
numerator[0] / denominator[1] == fraction) {
fractions.push_back(Fraction(n, d));
}
}
}
Fraction total = fractions[0] * fractions[1] * fractions[2] * fractions[3];
total.simplify();
cout << total << endl;
}
| true |
3f0843c97a478834ee0111524d7bf2da08b10d17 | C++ | HemensonDavid/Estudando-C | /2017/APP6/Q.1.cpp | UTF-8 | 299 | 3.1875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
int num;
for(;;){
cout<<"Digite um numero: ";
cin>>num;
if(num==0){
return 0;
}
else if(num%3==0 && num%2==0){
cout<<"O numero eh divisivel por 6! "<<endl;
}else{
cout<<"Nao eh divisivel por 6! "<<endl;
}
}
}
| true |
17a42cb47edc319fb52060ace3288fb5f2fa7ed0 | C++ | joaodasilva/cpp-base | /src/base/dns.cc | UTF-8 | 3,782 | 2.65625 | 3 | [] | no_license | #include "base/dns.h"
#include <sstream>
#include <arpa/inet.h>
#include <string.h>
#include "base/bind.h"
#include "base/event_loop.h"
#include "base/logging.h"
namespace {
void Jump(const DNS::Callback& callback, addrinfo* ptr) {
DNS::unique_addrinfo unique(ptr);
callback(std::move(unique));
}
} // namespace
unique_ptr<DNS> DNS::Create() {
unique_ptr<EventLoop> loop(EventLoop::Create());
if (!loop.get())
return NULL;
return make_unique(new DNS(loop.release()));
}
DNS::~DNS() {
dns_loop_->QuitSoon();
dns_thread_.join();
}
void DNS::Resolve(const std::string& host,
const std::string& service,
const Callback& callback,
int family,
int socktype,
int protocol) {
DCHECK(EventLoop::Current());
dns_loop_->Post(Bind(&DNS::ResolveAndReply, this, host, service, callback,
family, socktype, protocol, EventLoop::Current()));
}
// static
std::string DNS::GetHost(const addrinfo& addr) {
void* ptr = NULL;
if (addr.ai_family == PF_INET) {
sockaddr_in *sin = (sockaddr_in *) addr.ai_addr;
ptr = &sin->sin_addr;
} else if (addr.ai_family == PF_INET6) {
sockaddr_in6 *sin6 = (sockaddr_in6 *) addr.ai_addr;
ptr = &sin6->sin6_addr;
} else {
DLOG(WARNING) << "Unknown family: " << addr.ai_family;
return "";
}
char buffer[INET6_ADDRSTRLEN];
return inet_ntop(addr.ai_family, ptr, buffer, sizeof(buffer));
}
// static
std::string DNS::GetPort(const addrinfo& addr) {
std::stringstream ss;
if (addr.ai_family == PF_INET) {
sockaddr_in *sin = (sockaddr_in *) addr.ai_addr;
ss << ntohs(sin->sin_port);
} else if (addr.ai_family == PF_INET6) {
sockaddr_in6 *sin6 = (sockaddr_in6 *) addr.ai_addr;
ss << ntohs(sin6->sin6_port);
} else {
DLOG(WARNING) << "Unknown family: " << addr.ai_family;
}
return ss.str();
}
// static
std::string DNS::ToString(const addrinfo& addr) {
void* ptr = NULL;
uint16 port = 0;
std::stringstream ss;
if (addr.ai_family == PF_INET) {
sockaddr_in *sin = (sockaddr_in *) addr.ai_addr;
ptr = &sin->sin_addr;
port = ntohs(sin->sin_port);
} else if (addr.ai_family == PF_INET6) {
sockaddr_in6 *sin6 = (sockaddr_in6 *) addr.ai_addr;
ptr = &sin6->sin6_addr;
port = ntohs(sin6->sin6_port);
} else {
ss << "Unknown family: " << addr.ai_family;
}
if (ptr) {
static char buffer[INET6_ADDRSTRLEN];
ss << inet_ntop(addr.ai_family, ptr, buffer, sizeof(buffer))
<< ":" << port;
if (addr.ai_socktype == SOCK_STREAM)
ss << " (TCP)";
else if (addr.ai_socktype == SOCK_DGRAM)
ss << " (UDP)";
else
ss << " (type " << addr.ai_socktype << ")";
}
return ss.str();
}
void DNS::ResolveAndReply(const std::string& host,
const std::string& service,
const Callback& callback,
int family,
int socktype,
int protocol,
EventLoop* origin_loop) {
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = 0; // AI_ADDRCONFIG, AI_NUMERICHOST, AI_NUMERICSERV?
hints.ai_family = family;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
addrinfo* result;
if (getaddrinfo(host.empty() ? NULL : host.c_str(), service.c_str(),
&hints, &result) != 0) {
DLOGE(ERROR) << "getaddrinfo failed for " << host << ":" << service;
result = NULL;
}
origin_loop->Post(Bind(Jump, callback, result));
}
// static
void DNS::delete_addrinfo(addrinfo* addr) {
freeaddrinfo(addr);
}
DNS::DNS(EventLoop* loop)
: dns_loop_(loop),
dns_thread_(Bind(&EventLoop::Run, loop)) {}
| true |
9610fb9195a8451900e9cd380050ea0902431895 | C++ | dsfb/topicosProgramacao | /aula05/TabelaSalarial.h | UTF-8 | 672 | 2.96875 | 3 | [] | no_license | /**
PCS2478 - Tópicos de Programação
TabelaSalarial.h
@author 8586861 - Luiz Eduardo Sol (luizedusol@gmail.com)
@author 7576829 - Augusto Ruy Machado (augustormachado@gmail.com)
@version 1.0 2017-08-30
*/
#pragma once
#include <string>
#include <vector>
using namespace std;
class TabelaSalarial{
vector<string> faixasSalario; // Vetor contendo as faixas salariais
public:
// Construtores da classe TabelaSalarial
TabelaSalarial();
TabelaSalarial(vector<string> faixasSalario);
// Destrutor da classe TabelaSalarial
~TabelaSalarial();
// Setters e Getters
vector<string> getFaixasSalario();
void setFaixasSalario(vector<string> faixasSalario);
float lerSalario(int faixa);
}; | true |
d12542ee2aea47372e6f1439cb4e3ad21ffb380a | C++ | redwingsdan/cpp-schoolwork | /082814ClassesTest/082814ClassesTest/Main.cpp | UTF-8 | 173 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
Point p1(1.5, 2.7);
cout << "The values or p1 are " << p1.xCoord << " and " <<
p1.yCoord << endl;
return 0;
} | true |
b5609d081aac295c271501866de7be33560fd014 | C++ | maoxiezhao/Cjing3D | /Cjing3D/input/gamepad.cpp | UTF-8 | 639 | 2.65625 | 3 | [
"MIT",
"Zlib"
] | permissive | #include "gamepad.h"
namespace Cjing3D
{
U32 Gamepad::GetMaxGamepadController() const
{
return mGamepadControllers.size();
}
bool Gamepad::IsConnected(U32 index) const
{
if (index >= mGamepadControllers.size()) {
return false;
}
return mGamepadControllers[index].mIsConnected;
}
bool Gamepad::IsKeyDown(const KeyCode& key, int index) const
{
if (key > Gamepad_CountStart && key < Gamepad_CountEnd)
{
if (!IsConnected(index)) {
return false;
}
U32 buttonIndex = key - Gamepad_CountStart - 1;
return mGamepadControllers[index].mState.mButtons[buttonIndex];
}
else
{
return false;
}
}
} | true |
a702917a3a3765c89c41e975c70b54aaafbc183d | C++ | shashikarsiddharth/dev-cpp | /io.cpp | UTF-8 | 189 | 3.28125 | 3 | [] | no_license | // Getting around I/O using cin and cout
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num;
cout << "entered num is: " << num << endl;
return 0;
} | true |
c017581b56cccb4c6912679ff00395cfa5363f9b | C++ | leonardoAnjos16/Competitive-Programming | /Codeforces/bun_lover.cpp | UTF-8 | 529 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define llong long long int
llong sum(int l, int r) {
if (l > r) return 0LL;
int n = r - l + 1;
return n * (n - 1LL) / 2LL + 1LL * n * l;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t; cin >> t;
while (t--) {
int n; cin >> n;
llong ans = 4LL * n;
int l = 3, r = n - 1;
if (n == 4) ans += 10LL;
else ans += 10LL + l + r + 2LL * sum(l + 1, r - 1);
cout << ans << "\n";
}
} | true |
b4b664201acf3dc7d5b665c891d3ac76ce24d292 | C++ | tranvankhue1996/time-and-calendar-CPP | /Calendar/Date.h | UTF-8 | 348 | 2.5625 | 3 | [] | no_license | #pragma once
#include "Graphics.h"
class CDate : public CGraphics
{
private:
int m_Day, m_Month, m_Year;
int m_wDay;
static int DayinMonth[];
public:
CDate();
CDate(int d, int m, int y);
~CDate();
void setTime();
int wDay();
void output(ostream& os);
bool InspectLeapYear();
void Paint(int x, int y);
int retDay();
int retMonth();
};
| true |
f0961bbd3aa97259e36dfbb00a0cebfa00530c42 | C++ | Adityathakur3029/LeetCode | /Sliding Window/longestSubstringWithoutRepeatingCharacters.cpp | UTF-8 | 506 | 2.890625 | 3 | [] | no_license | class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result=0;
if(s.length()==0)
return 0;
unordered_map<char,int> mp;
int right=0;
int left=0;
while(left<s.length() && right<s.length()){
if(!mp[s[right]]){
mp[s[right++]]++;
result=max(result,right-left);
}
else{
mp.erase(s[left++]);
}
}
return result;
}
};
| true |
21478c374601e2cef0367e5ede775811977a59ef | C++ | MikeFernandez-Pro/CPP-Pool | /Module08/ex02/mutantstack.hpp | UTF-8 | 2,779 | 2.9375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mutantstack.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <user42@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/22 19:07:43 by user42 #+# #+# */
/* Updated: 2020/10/25 22:28:02 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MUTANTSTACK_HPP
# define MUTANTSTACK_HPP
#include <iostream>
#include <stack>
#include <iterator>
#include <deque>
#include <vector>
template<class T, class Container = std::deque<T> >
class MutantStack : public std::stack<T>
{
public:
MutantStack(): std::stack<T, Container>() {}
MutantStack(const MutantStack<T, Container> &obj): std::stack<T, Container>(obj) { this->operator=(obj); }
virtual ~MutantStack() {}
MutantStack<T, Container> &operator=(const MutantStack<T> &obj) {
if (this != &obj)
this->c = obj.c;
return (*this);
}
typedef typename std::stack<T, Container>::container_type::iterator iterator;
typedef typename std::stack<T, Container>::container_type::const_iterator const_iterator;
typedef typename std::stack<T, Container>::container_type::reverse_iterator reverse_iterator;
typedef typename std::stack<T, Container>::container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return (this->c.begin()); }
const_iterator begin() const { return (this->c.begin()); }
iterator end() { return (this->c.end()); }
const_iterator end() const { return (this->c.end()); }
reverse_iterator rbegin() { return (this->c.rbegin()); }
const_reverse_iterator rbegin() const { return (this->c.rbegin()); }
reverse_iterator rend() { return (this->c.rend()); }
const_reverse_iterator rend() const { return (this->c.rend()); }
bool empty(){ return (this->c.empty()); }
size_t size(){ return (this->c.size()); }
void push(const T &element) { this->c.push_back(element); }
void pop() { this->c.pop_back(); }
T & top() { return (*(this->c.end() - 1)); }
const T & top() const { return (*(this->c.end() - 1)); }
};
#endif | true |
3f802ea90426db549afdd6b4c8d1ac4f521db1f9 | C++ | prutskov/DateConverter | /DateConverterLib/DateConverter.cpp | WINDOWS-1251 | 4,066 | 3.171875 | 3 | [] | no_license | #include "stdafx.h"
#include "DateConverter.h"
int DateConverter::ConvertDate(std::string &dateIn, std::string& dateOut)
{
if (dateIn.size() != 5)
{
//
return 1;
}
int j = 0;
int dd = 0;
int mm = 0;
for (std::string::iterator it = dateIn.begin(); it != dateIn.end(); ++it)
{
if (*it != '.')
{
switch (j)
{
case 0: dd = dd + (*it - 48) * 10; break;
case 1: dd = dd + (*it - 48); break;
case 3: mm = mm + (*it - 48) * 10; break;
case 4: mm = mm + (*it - 48); break;
default:
break;
}
}
++j;
}
if (dd < 0 || dd > 31 || mm < 1 || mm > 12)
{
//
return 2;
}
if ((dd > 29 && mm == 2) ||
(dd > 30 && mm == 4) ||
(dd > 30 && mm == 6) ||
(dd > 30 && mm == 9) ||
(dd > 30 && mm == 11))
{
//
return 3;
}
dd += 3;
switch (mm)
{
case 1: if (dd > 31) { dd -= 31; mm = 2; }; break;
case 2: if (dd > 29) { dd -= 29; mm = 3; } break;
case 3: if (dd > 31) { dd -= 31; mm = 4; } break;
case 4: if (dd > 30) { dd -= 30; mm = 5; } break;
case 5: if (dd > 31) { dd -= 31; mm = 6; } break;
case 6: if (dd > 30) { dd -= 30; mm = 7; } break;
case 7: if (dd > 31) { dd -= 31; mm = 8; } break;
case 8: if (dd > 31) { dd -= 31; mm = 9; } break;
case 9: if (dd > 30) { dd -= 30; mm = 10; } break;
case 10: if (dd > 31) { dd -= 31; mm = 11; } break;
case 11: if (dd > 30) { dd -= 30; mm = 12; } break;
case 12: if (dd > 31) { dd -= 31; mm = 1; } break;
default:
break;
}
std::string dateString;
switch (dd)
{
case 1: dateString = " "; break;
case 2: dateString = " "; break;
case 3: dateString = " "; break;
case 4: dateString = " "; break;
case 5: dateString = " "; break;
case 6: dateString = " "; break;
case 7: dateString = " "; break;
case 8: dateString = " "; break;
case 9: dateString = " "; break;
case 10: dateString = " "; break;
case 11: dateString = " "; break;
case 12: dateString = " "; break;
case 13: dateString = " "; break;
case 14: dateString = " "; break;
case 15: dateString = " "; break;
case 16: dateString = " "; break;
case 17: dateString = " "; break;
case 18: dateString = " "; break;
case 19: dateString = " "; break;
case 20: dateString = " "; break;
case 21: dateString = " "; break;
case 22: dateString = " "; break;
case 23: dateString = " "; break;
case 24: dateString = " "; break;
case 25: dateString = " "; break;
case 26: dateString = " "; break;
case 27: dateString = " "; break;
case 28: dateString = " "; break;
case 29: dateString = " "; break;
case 30: dateString = " "; break;
case 31: dateString = " "; break;
default:
break;
}
std::string monthString;
switch (mm)
{
case 1: monthString = ""; break;
case 2: monthString = ""; break;
case 3: monthString = ""; break;
case 4: monthString = ""; break;
case 5: monthString = ""; break;
case 6: monthString = ""; break;
case 7: monthString = ""; break;
case 8: monthString = ""; break;
case 9: monthString = ""; break;
case 10: monthString = ""; break;
case 11: monthString = ""; break;
case 12: monthString = ""; break;
default:
break;
}
dateOut = dateString + monthString;
return 0;
}
| true |
3cf77f1190d9eb8b3fc4434d62aa3f3012a4c9d4 | C++ | nayantharar/cs142-lab4 | /lab4_q3.cpp | UTF-8 | 3,787 | 3.921875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class node{
//type
public:
// Data
int data;
// Pointer to the next Node
node * next;
// Construct
node(){
next = NULL;
}
};
class LinkedList{
//type
public:
// Head -> Node type ptr
node * head;
node * tail;
// Construct
LinkedList(){
head = NULL;
tail = NULL;
}
// Insert
void insert(int value){
// addition of first node
node * temp = new node;
// Insert value in the node
temp -> data = value;
// for first node
if(head == NULL){
head = temp;
}
// for other nodes
else{
tail->next = temp;
}
tail = temp;
}
//insertAt
void insertAt(int pos, int value){
// Reach the place before the pos
node * current = head;
int i =1;
while(i < pos-1){
i++;
current = current->next;
}
// Create a node
node*temp = new node;
temp->data = value;
// pointers moving
temp->next = current->next;
current->next = temp;
}
// Deletion of last element
void delet(){
// store the tail in temp
node * temp = tail;
// before tail has to point to null
node * current = head;
while(current->next != tail){
current = current->next;
}
current->next = NULL;
// update tail
tail = current;
// delete temp
delete temp;
}
//count
void count(){
node*current=head;
int i=1;
while(current!=tail)
{
current=current->next;
i++;
}
cout<<i<<endl;
}
//deletAt
void deletAt(int pos){
// Reach the place before the pos
node * current = head;
int i=1;
while(i < pos-1){
i++;
current = current->next;
}
// delet a node
node*del = current->next;
current->next=del->next;
delete del ;
}
// Display
void display(){
node * current = head;
while(current != NULL){
cout << current->data << "->";
current = current->next;
}
cout << endl;
}
};
class Queue{
public:
node*end;
node*front;
LinkedList l1;
Queue(){
end=l1.head;
front=l1.tail;
}
//adds on the top
void enqueue(int value){
//void insertAt(int value,int pos)
l1.insert(value);
//top=new head
end=l1.head;
}
//removes from the bottom
void dequeue(){
//void delet
l1.delet();
//top=new head
front=l1.tail;
}
bool isEmpty(){
if(end==NULL) return true;
return false;
}
void size(){
l1.count();
}
void display(){
l1.display();
}
};
//class
class stack{
public:
int top;
queue q1;
//constructer
stack(){
top=q1.end;
}
//push
void push(int value){
q1.enqueue(value);
}
//pop
void pop(){
q1.end=q1.end-1;
}
//to print size
void size(){
q1.size();
}
//check is empty or not
bool isempty(){
q1.isempty();
}
//to display
void display(){
q1.display();
}
//to show top element
void topelement(){
q1.topelement();
}
};
int main(){
stack s1;
s1.push(1);
s1.push(3);
s1.push(5);
s1.push(7);
s1.topelement();
s1.size();
s1.display();
s1.pop();
s1.display();
}
| true |
be0dbfc35f1029df6c4a9a69abb2393499240463 | C++ | OTTFFYZY/StandardCodeLibrary | /Mathematics/CombinatorialMathematics/HighDimensionalPrefixSum_0.cpp | UTF-8 | 930 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int dp[10];
vector<int>G[10];
void trans(int x) {
int a = x % 2; x /= 2;
int b = x % 2; x /= 2;
int c = x % 2; x /= 2;
cout << c << b << a ;
}
void print(int x) {
for (int s = 0; s < (int)G[x].size(); s++) {
trans(G[x][s]); cout << " ";
}
}
int main() {
for (int s = 0; s < 8; s++) {
G[s].push_back(s);
}
memset(dp, -1, sizeof(dp));
for (int i = 0; i < 3; ++i) {
cout << i << endl;
for (int j = 0; j < 8; ++j) {
if (!(j&(1 << (i))))
{
int v = (j | (1 << (i)));
trans(j); cout << ":"; print(j); cout << endl;
trans(v); cout << ":"; print(v); cout << endl;
for (int s = 0; s < (int)G[v].size(); s++) {
G[j].push_back(G[v][s]);
}
trans(j); cout << ":"; print(j); cout << endl;
dp[j] += dp[j | (1 << (i))];
cout << endl;
}
}
}
for (int s = 0; s < 8; s++) {
trans(s); cout << ":"; print(s); cout << endl;
}
return 0;
} | true |
b78fa7cb92e4cff335b8f0557bd990aa6caba078 | C++ | stoneheart93/Leetcode | /[152]Maximum Product Subarray.cpp | UTF-8 | 1,397 | 3.40625 | 3 | [] | no_license | //Given an integer array nums, find a contiguous non-empty subarray within the a
//rray that has the largest product, and return the product.
//
// It is guaranteed that the answer will fit in a 32-bit integer.
//
// A subarray is a contiguous subsequence of the array.
//
//
// Example 1:
//
//
//Input: nums = [2,3,-2,4]
//Output: 6
//Explanation: [2,3] has the largest product 6.
//
//
// Example 2:
//
//
//Input: nums = [-2,0,-1]
//Output: 0
//Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
//
//
//
// Constraints:
//
//
// 1 <= nums.length <= 2 * 104
// -10 <= nums[i] <= 10
// The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit
//integer.
//
// Related Topics Array Dynamic Programming
// 👍 7030 👎 230
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int maxProduct(vector<int>& a)
{
int curr_max = a[0];
int curr_min = a[0];
int max_so_far = a[0];
for(int i = 1; i < a.size(); i++)
{
if(a[i] < 0)
swap(curr_max, curr_min);
curr_max = max(curr_max * a[i], a[i]);
curr_min = min(curr_min * a[i], a[i]);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
};
//leetcode submit region end(Prohibit modification and deletion)
| true |
7d664d3fa9dd7691e1ce533c578f657b68bcbee1 | C++ | BenjaminSchulte/fma | /libfma/include/fma/Error.hpp | UTF-8 | 446 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef __FMA_ERROR_H__
#define __FMA_ERROR_H__
#include <string>
#include "Reference.hpp"
namespace FMA {
struct Error {
/**
* Different error types
*/
enum ErrorType {
INFO,
NOTICE,
WARNING,
ERROR
};
Error(ErrorType type, const CodeReference &file, const std::string &message)
: file(file), type(type), message(message)
{
}
CodeReference file;
ErrorType type;
std::string message;
};
}
#endif
| true |
6d50c08fd1cb5e49d7f5faf7ab983b24bc146254 | C++ | Alpha303/qPaint | /qPaint/shapefactory.cpp | UTF-8 | 869 | 2.90625 | 3 | [] | no_license | #include "shapefactory.h"
ShapeFactory::ShapeFactory()
{
}
BaseShape* ShapeFactory::createNewShape(const QPen& pen, const QBrush& brush, const QString& name,
const QPoint& initialPos, const DrawMode& shapeType)
{
switch (shapeType)
{
case Type_Freehand:
return new Shape_Freehand(pen, brush, name, initialPos);
break;
case Type_Line:
return new Shape_Line(pen, brush, name, initialPos);
break;
case Type_Rectangle:
return new Shape_Rectangle(pen, brush, name, initialPos);
break;
case Type_Ellipse:
return new Shape_Ellipse(pen, brush, name, initialPos);
break;
case Type_Polygon:
return new Shape_Polygon(pen, brush, name, initialPos);
break;
default:
return nullptr;
}
}
| true |
2c6ae7fc6e38f271592df426d3a58e835227efe7 | C++ | rensselaer-rocket-society/TelemetryUnit | /Firmware/MainSketch/libs/Packet.h | UTF-8 | 804 | 2.703125 | 3 | [] | no_license | #pragma once
#include "Arduino.h"
#include "CRC8.h"
#include "COBS.h"
class Packet
{
public:
enum PacketContent : uint8_t { GPS=0x01, ALTITUDE=0x02, ACCEL=0x03, BATTERY=0x04 };
Packet(HardwareSerial *serial);
void sendBattery(uint32_t time, uint16_t voltage);
void sendAltitude(uint32_t time, int32_t altitude, int16_t temperature);
void sendGPS(uint32_t time, float latitude, float longitude);
void sendAccel(uint32_t time, int16_t x_accel, int16_t y_accel, int16_t z_accel,
int16_t x_gyro, int16_t y_gyro, int16_t z_gyro);
private:
void sendPacket(PacketContent packetContent, uint32_t time, uint8_t *data, uint8_t data_length);
HardwareSerial *serial;
CRC8 crcCalculator;
COBS byteStuffer;
uint8_t sequence_num;
};
| true |
4a47180299c612fbdab528b82abf419e96ea1454 | C++ | JoKeR-VIKING/Competitive-Programming | /Dynamic Programming - 2/knapSack.cpp | UTF-8 | 1,708 | 3.59375 | 4 | [] | no_license | // Knapsnack - Problem
// A thief robbing a store and can carry a maximal weight of W into his knapsack. There are N items and ith item weigh wi and is of value vi. What is the maximum value V, that thief can take ?
// Note: Space complexity should be O(W).
// Input Format :
// Line 1 : N i.e. number of items
// Line 2 : N Integers i.e. weights of items separated by space
// Line 3 : N Integers i.e. values of items separated by space
// Line 4 : Integer W i.e. maximum weight thief can carry
// Output Format :
// Line 1 : Maximum value V
// Constraints
// 1 <= N <= 10^4
// 1<= wi <= 100
// 1 <= vi <= 100
// 1 <= W <= 1000
// Sample Input 1 :
// 4
// 1 2 4 5
// 5 4 8 6
// 5
// Sample Output :
// 13
#include<bits/stdc++.h>
using namespace std;
int knapSack(int* weights, int* values, int maxCapacity, int n)
{
int** dp = new int*[n+1];
for (int i=0;i<=n;i++)
dp[i] = new int[maxCapacity+1];
for (int i=0;i<=n;i++)
dp[i][0] = 0;
for (int i=0;i<=maxCapacity;i++)
dp[0][i] = 0;
for (int i=1;i<=n;i++)
{
for (int j=1;j<=maxCapacity;j++)
{
if (j >= weights[i-1])
dp[i][j] = max(dp[i-1][j], values[i-1] + dp[i-1][j - weights[i-1]]);
else
dp[i][j] = dp[i-1][j];
}
}
return dp[n][maxCapacity];
}
int main()
{
int n;
cin>>n;
int* weights = new int[n];
int* values = new int[n];
for (int i=0;i<n;i++)
cin>>weights[i];
for (int i=0;i<n;i++)
cin>>values[i];
int maxCapacity;
cin>>maxCapacity;
cout<<knapSack(weights, values, maxCapacity, n)<<"\n";
return 0;
}
| true |
d939326c24ec4ecc495fa0bc3f2ca1945068d6c2 | C++ | xiazhiyiyun/C-Primer | /Unit15/Exercise15.3/Quote.h | UTF-8 | 341 | 3.328125 | 3 | [] | no_license | #include <string>
class Quote
{
public:
Quote():price(0.0) {}
Quote(const std::string &book,double _price):isbn(book),price(_price) {}
virtual ~Quote() {}
public:
std::string ISBN() const { return isbn; }
virtual double net_price(std::size_t n) const
{
return n*price;
}
protected:
double price;
private:
std::string isbn;
}; | true |
24c9eed35a48bff28ecbbb8b721198b0353df4cd | C++ | datoad4510/My-Projects | /Old/personal projects/Numerical analysis library/Sets (work in progress, old, didn't know trees existed).cpp | UTF-8 | 1,992 | 3.5 | 4 | [] | no_license | #include <vector>
#include <iostream>
using namespace std; //assuming there are no duplicates in the sets. normalize deletes duplicates
template<typename A>//fix the functions
void normalize(vector<A>& v);
template<typename A>
vector<A> set_intersection(vector<A>&, vector<A>&);
template<typename A>
vector<A> set_union(vector<A>&, vector<A>&);
template<typename A>
vector<A> set_difference(vector<A>&, vector<A>&);
template<typename A>
void print(const vector<A>& v)
{
for (auto m : v)
{
cout << m << " ";
}
}
template<typename A>
void input(vector<A>& v)
{
A temp;
while (cin >> temp)
{
v.push_back(temp);
}
}
int main()
{
vector<int> v1;
input(v1);
cin.clear();
vector<int> v2;
input(v2);
cin.clear();
normalize(v1);
normalize(v2);
vector<int> v3 = set_difference(v1, v2);
print(v3);
getchar();
}
template<typename A>
void normalize(vector<A>& v)
{
vector<A> temp;
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j < temp.size(); j++)
{
if (temp[j] == v[i])
break;
if (j == temp.size() - 1)
temp.push_back(v[i]);
}
}
v = temp;
}
template<typename A>
vector<A> set_intersection(vector<A>& v1, vector<A>& v2)
{
vector<A> v;
for (int i = 0; i < v1.size(); i++)
{
for (int j = 0; j < v2.size(); j++)
{
if (v1[i] == v2[j])
{
v.push_back(v1[i]);
break;
}
}
}
return v;
}
template<typename A>
vector<A> set_union(vector<A>& v1, vector<A>& v2)
{
vector<A> v = v1;
for (int i = 0; i < v2.size(); i++)
{
for (int j = 0; j < v.size(); j++)
{
if (v[j] == v2[i])
break;
if (j == v.size() - 1)
v.push_back(v2[i]);
}
}
return v;
}
template<typename A>
vector<A> set_difference(vector<A>& v1, vector<A>& v2)
{
vector<A> v;
for (int i = 0; i < v2.size(); i++)
{
bool contains = false;
for (int j = 0; j < v1.size(); j++)
{
if (v2[i] == v1[j])
{
contains = true;
break;
}
}
if (contains == true)
continue;
else
v.push_back(v1[i]);
}
return v;
}
| true |
99ef4dd1d2d24ec6fd452e7058b1d1ba189d338b | C++ | Haowie/PAUL-E | /Shop.h | UTF-8 | 867 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifndef SHOP_H
#define SHOP_H
class Order;
class RobotModels;
class SalesAssoc;
class Boss;
class Customers;
class Model;
class Shop
{
public:
Shop();
void addModel(Model* ID);
void addOrder(Order* orderID);
void addCustomer(Customers* id);
void addSalesAssoc(SalesAssoc* empID);
void addBoss(Boss* bossName);
Boss* checkBoss(int bossID);
Model* viewModels();
Order* viewOrder(int orderNum);
Customers* findCustomer(int ID);
Customers* viewCustomers();
SalesAssoc* viewEmployees();
SalesAssoc* findEmployee(int empID);
Model* findModel(int modID);
Order* findOrder(int orderNum);
protected:
vector<SalesAssoc*> employee;
vector<Customers*> customer;
vector<Model*> model;
vector<Boss*> boss;
vector<Order*> order;
};
#endif | true |
15c2155cc666c6f267993114934021e7c90cd71e | C++ | ash/cpp-tut | /150.cpp | UTF-8 | 586 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setw(10) << 42 << "\n";
cout << setw(10) << 13242 << "\n";
cout << setw(10) << setfill('0') << 546 << "\n";
cout << 78 << "\n";
cout << setprecision(4) << 3.1415926 << "\n";
cout << setbase(16) << 95 << "\n";
cout << 95 << "\n"; // still 16 base
cout << setbase(10);
cout << (ios::showbase | ios::uppercase) << "\n";
cout << setiosflags(ios::showbase | ios::uppercase) << 95 << "\n";
cout << resetiosflags(ios::showbase | ios::uppercase) << 95 << "\n";
} | true |
276908d6535731c7f4ecb6ff70704f94b1e7e211 | C++ | HoYoung1/backjoon-Level | /backjoon_level_c/backjoon_level_c/15954.cpp | UHC | 846 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main() {
int N, K;
cin >> N >> K; // 1<=N<=500 , 1<=K<=N
vector<int> vDolls;
for (int i = 0; i < N; i++) {
int temp;
cin >> temp;
vDolls.push_back(temp);
}
long double minst = 9876543210;
for (int j = K; j<= N; j++) { // 3 4 5
for (int k = 0; k < N; k++) {
if (k + j > N) break; // ̴̹ °ű
long double sum = 0;
for (int i = k; i < k+j; i++) {
sum = sum + vDolls[i];
}
long double m =sum / j;
long double powSum = 0;
for (int i = k; i < k+j; i++) {
powSum += pow(vDolls[i] - m, 2);
}
minst = min(sqrt(powSum / j), minst); //st = л
}
}
cout << fixed;
cout.precision(11);
cout << minst;
//printf("%Lf", sqrt(minst));
return 0;
} | true |
2a1f9771791272886798352e5fdbd0cf2f2db555 | C++ | rgrahamh/muse | /src/client/musewindow.cpp | UTF-8 | 36,981 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "musewindow.h"
#include "ui_musewindow.h"
/**
* @brief MuseWindow::MuseWindow Constructor for the main window of the client UI
* @param parent The parent to attach to
*/
MuseWindow::MuseWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MuseWindow)
{
// ui initialization
ui->setupUi(this);
ui->tabWidget->setCurrentIndex(0);
// configure tables
configureTableView(ui->artistView);
configureTableView(ui->albumView);
configureTableView(ui->genreView);
configureTableView(ui->songView);
configureTableView(ui->playlistView);
// initialize audio library
initializeFMOD();
// stop user from messing with progress bar
ui->songProgressSlider->setAttribute(Qt::WA_TransparentForMouseEvents);
// allocate space for strings
songProgressText = (char*) calloc(10, sizeof(char));
songLengthText = (char*) calloc(10, sizeof(char));
connectionText = (char*) calloc(100, sizeof(char));
// intialize update timer
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MuseWindow::on_timeout);
// create the models
artist_model = new ArtistModel(this);
album_model = new AlbumModel(this);
genre_model = new GenreModel(this);
song_model = new SongModel(this);
playlist_model = new PlaylistModel(this);
ui->artistView->setModel(artist_model);
ui->albumView->setModel(album_model);
ui->genreView->setModel(genre_model);
ui->songView->setModel(song_model);
ui->playlistView->setModel(playlist_model);
dlthread = new DownloadThread(this);
sbthread = new SongBurstThread(this, 25);
albthread = new AlbumBurstThread(this, 25);
arbthread = new ArtistBurstThread(this, 25);
gsbthread = new GenreSongBurstThread(this, 25);
// request context menu for right-clicks
ui->songView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->songView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested(QPoint)));
ui->playlistView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->playlistView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested(QPoint)));
// last-minute setup
changeConnectionState(NOT_CONNECTED);
clearSongs();
}
/**
* @brief MuseWindow::~MuseWindow Deconstructor
*/
MuseWindow::~MuseWindow()
{
// release audio library resources
system->release();
free(songProgressText);
free(songLengthText);
free(connectionText);
free_playlist(playlists);
delete ui;
}
/**
* @brief MuseWindow::configureTableView Sets project defaults for each table view
* @param view The QTableView being processed
*/
void MuseWindow::configureTableView(QTableView* view) {
// set selection behavior and mode for proper access
view->setSelectionBehavior(QAbstractItemView::SelectRows);
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
view->horizontalHeader()->setHighlightSections(false);
view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
view->setSortingEnabled(true);
// display
view->horizontalHeader()->setVisible(true);
view->verticalHeader()->setVisible(false);
view->setVisible(true);
}
/**
* @brief MuseWindow::initializeFMOD Readies audio-library for playback
*/
void MuseWindow::initializeFMOD() {
result = FMOD::System_Create(&system); // Create the main system object.
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
exit(-1);
}
result = system->init(512, FMOD_INIT_NORMAL, 0); // Initialize FMOD.
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
exit(-1);
}
}
void MuseWindow::on_tabWidget_tabBarClicked(int index)
{
//Make sure that the messages are received properly so there's not any messy server-side issues.
if(sbthread->isRunning()){
sbthread->terminate();
clearSock(1);
}
if(albthread->isRunning()){
albthread->terminate();
clearSock(1);
}
if(arbthread->isRunning()){
arbthread->terminate();
clearSock(1);
}
if(gsbthread->isRunning()){
gsbthread->terminate();
clearSock(1);
}
while(dlthread->isRunning()){
continue;
}
/* The tab has changed, so we need to update the view with new data */
if( connection_state ) {
switch(index) {
case 0: /* Artist */ {
arbthread->reset();
arbthread->start();
break;
}
case 1: /* Album */ {
albthread->reset();
albthread->start();
break;
}
case 2: /* Genre */ {
struct genreinfolst* genres;
if( queryGenres(&genres) ) {
qDebug() << "Error fetching genres!" << endl;
} else {
genre_model->populateData(genres);
}
break;
}
case 3: /* Song */ {
sbthread->reset();
sbthread->start();
break;
}
case 4: /* Playlist */ {
free_playlist(playlists);
playlists = NULL;
scanPlaylists(&playlists);
if( playlists == NULL ) {
qDebug() << "Error scanning for playlists!" << endl;
} else {
playlist_model->populateData(playlists);
}
break;
}
}
}
}
/**QString
* @brief MuseWindow::on_songView_doubleClicked Slot for when a row in the SongTable is double-clicked
* @param index The index of the cell double clicked
*/
void MuseWindow::on_songView_doubleClicked(const QModelIndex &index)
{
if( connection_state == CONNECTED ) {
changePlayState(NOT_PLAYING);
if( queue_state == HAS_QUEUE ) { // prevent duplicates of songs double-clicked from entering history
changeHistoryState(HAS_HISTORY);
}
changeQueueState(NO_QUEUE); // clear the current queue
changeQueueState(HAS_QUEUE, &index, false); // re-initialize the queue
changePlayState(STARTED);
}
}
/**
* @brief MuseWindow::on_artistView_doubleClicked Slot for when a row in the ArtistTable is double-clicked
* @param index The index of the cell double clicked
*/
void MuseWindow::on_artistView_doubleClicked(const QModelIndex &index)
{
int artist_id = index.data(Qt::UserRole).value<int>();
struct albuminfolst* albums;
if( queryArtistAlbums(artist_id, &albums) ) {
qDebug() << "Error retrieving artist albums!" << endl;
return;
}
album_model->populateData(albums);
free_albuminfolst(albums);
ui->tabWidget->setCurrentIndex(1);
}
/**
* @brief MuseWindow::on_albumView_doubleClicked Slot for when a row in the AlbumTable is double-clicked
* @param index The index of the cell double clicked
*/
void MuseWindow::on_albumView_doubleClicked(const QModelIndex &index)
{
int album_id = index.data(Qt::UserRole).value<int>();
struct songinfolst* songs;
if( queryAlbumSongs(album_id, &songs) ) {
qDebug() << "Error retrieving album songs!" << endl;
return;
}
song_model->populateData(songs);
free_songinfolst(songs);
ui->tabWidget->setCurrentIndex(3);
}
/**
* @brief MuseWindow::on_genreView_doubleClicked Slot for when a row in the GenreTable is double-clicked
* @param index The index of the cell double clicked
*/
void MuseWindow::on_genreView_doubleClicked(const QModelIndex &index)
{
char* str = (char*)malloc(genre_model->data(index).TextLength);
strcpy(str, genre_model->data(index).value<QString>().toUtf8());
gsbthread->reset();
printf("%s\n", str);
gsbthread->setStr(str);
gsbthread->start();
ui->tabWidget->setCurrentIndex(3);
}
void MuseWindow::on_playlistView_doubleClicked(const QModelIndex &index)
{
const char* playlist_name = index.data(Qt::DisplayRole).value<QString>().toUtf8();
// find the playlist
struct playlist* cursor_pl = playlists;
struct playlist* playlist = NULL;
while( cursor_pl != NULL ) {
if( strcmp(playlist_name, cursor_pl->name) == 0 ) {
playlist = cursor_pl;
break;
}
cursor_pl = cursor_pl->prev;
}
// get songinfo on all the songs
struct songinfolst* songs = NULL;
struct songlst* cursor_sng = playlist->first_song;
while( cursor_sng != NULL ) {
querySongInfo(&songs, cursor_sng->id);
cursor_sng = cursor_sng->next;
}
song_model->populateData(songs);
free_songinfolst(songs);
ui->tabWidget->setCurrentIndex(3);
}
/**
* @brief MuseWindow::on_playButton_clicked Slot for when the play button is pressed
*/
void MuseWindow::on_playButton_clicked()
{
switch( play_state ) {
case NOT_PLAYING: {
if( connection_state == CONNECTED && (queue_state == HAS_QUEUE || queue_state == END_OF_QUEUE) ) {
changePlayState(STARTED);
} // if we're not connected or don't have a queue, we can't play songs
break;
}
case STARTED: {
changePlayState(PAUSED);
break;
}
case RESUMED: {
changePlayState(PAUSED);
break;
}
case PAUSED: {
changePlayState(RESUMED);
break;
}
}
}
/**
* @brief MuseWindow::on_rewindButton_clicked Slot for when the rewind button is pressed
*/
void MuseWindow::on_rewindButton_clicked()
{
switch( history_state ) {
case NO_HISTORY: {
// just rewind the song
if( play_state != NOT_PLAYING ) {
song_channel->setPosition(0, FMOD_TIMEUNIT_MS);
ui->songProgressLabel->setText("0:00");
ui->songProgressSlider->setValue(0);
changePlayState(RESUMED);
}
break;
}
case HAS_HISTORY: {
if( play_state != NOT_PLAYING ) {
unsigned int position;
song_channel->getPosition(&position, FMOD_TIMEUNIT_MS);
if( position < 1500 ) {
changePlayState(NOT_PLAYING);
queue.insert(queue.begin(), history.front());
history.erase(history.begin());
changeQueueState(HAS_QUEUE);
if( history.empty() ) {
changeHistoryState(NO_HISTORY);
}
changePlayState(STARTED);
} else {
song_channel->setPosition(0, FMOD_TIMEUNIT_MS);
ui->songProgressLabel->setText("0:00");
ui->songProgressSlider->setValue(0);
changePlayState(RESUMED);
}
} else {
changePlayState(NOT_PLAYING);
queue.insert(queue.begin(), history.front());
history.erase(history.begin());
changeQueueState(HAS_QUEUE);
if( history.empty() ) {
changeHistoryState(NO_HISTORY);
}
changePlayState(STARTED);
}
break;
}
}
}
void MuseWindow::on_skipButton_clicked()
{
// get the easiest case out of the way first
if( repeat_state == REPEAT_ONE && play_state != NOT_PLAYING ) {
song_channel->setPosition(0, FMOD_TIMEUNIT_MS);
ui->songProgressLabel->setText("0:00");
ui->songProgressSlider->setValue(0);
changePlayState(RESUMED);
return;
}
switch( queue_state ) {
case NO_QUEUE: {
break;
}
case HAS_QUEUE: {
changePlayState(NOT_PLAYING);
changeHistoryState(HAS_HISTORY);
queue.erase(queue.begin());
if( queue.size() == 1 ) {
changeQueueState(END_OF_QUEUE);
}
changePlayState(STARTED);
break;
}
case END_OF_QUEUE: {
switch( repeat_state ) {
case NO_REPEAT: {
changeHistoryState(HAS_HISTORY);
changeQueueState(NO_QUEUE);
changePlayState(NOT_PLAYING);
break;
}
case REPEAT: {
changePlayState(NOT_PLAYING);
changeHistoryState(HAS_HISTORY);
changeQueueState(NO_QUEUE);
QModelIndex index = song_model->index(0, 0);
changeQueueState(HAS_QUEUE, &index);
changePlayState(STARTED);
break;
}
case REPEAT_ONE: {
// covered above
break;
}
}
break;
}
}
}
void MuseWindow::on_repeatButton_clicked()
{
switch( repeat_state ) {
case NO_REPEAT: {
changeRepeatState(REPEAT);
break;
}
case REPEAT: {
changeRepeatState(REPEAT_ONE);
break;
}
case REPEAT_ONE: {
changeRepeatState(NO_REPEAT);
break;
}
}
}
void MuseWindow::on_shuffleButton_clicked()
{
switch( shuffle_state ) {
case NO_SHUFFLE: {
changeShuffleState(SHUFFLE);
break;
}
case SHUFFLE: {
changeShuffleState(NO_SHUFFLE);
break;
}
}
}
/**
* @brief MuseWindow::on_connectButton_clicked Slot for when the connection button is pressed
*/
void MuseWindow::on_connectButton_clicked()
{
switch( connection_state ) {
case NOT_CONNECTED: {
ServerDialog* serverDialog = new ServerDialog(this);
if( serverDialog->exec() == QDialog::Accepted ) {
ip_address = serverDialog->getServerIP();
port = serverDialog->getServerPort();
if( connectToServ(port.toUtf8(), ip_address.toUtf8()) ) {
qDebug() << "Error connecting to server!" << endl;
} else {
// handle state
changePlayState(NOT_PLAYING);
changeHistoryState(NO_HISTORY);
changeQueueState(NO_QUEUE);
changeConnectionState(CONNECTED);
changeRepeatState(NO_REPEAT);
changeShuffleState(NO_SHUFFLE);
}
}
break;
}
case CONNECTED: {
changePlayState(NOT_PLAYING);
changeHistoryState(NO_HISTORY);
changeQueueState(NO_QUEUE);
changeConnectionState(NOT_CONNECTED);
changeRepeatState(NO_REPEAT);
changeShuffleState(NO_SHUFFLE);
break;
}
}
}
/**
* @brief MuseWindow::on_timeout Slot for when the update poll timer times out
*/
void MuseWindow::on_timeout() {
bool is_playing = false;
song_channel->isPlaying(&is_playing);
if( is_playing ) {
unsigned int position;
song_channel->getPosition(&position, FMOD_TIMEUNIT_MS);
unsigned int position_s = position / 1000;
memset(songProgressText, 0, 10);
sprintf(songProgressText, "%d:%02d", position_s / 60, position_s % 60);
ui->songProgressLabel->setText(songProgressText);
ui->songProgressSlider->setValue(position);
} else {
// get the easy case out of the way
if( repeat_state == REPEAT_ONE ) {
changePlayState(STARTED);
return;
}
switch( queue_state ) {
case NO_QUEUE: {
break;
}
case HAS_QUEUE: {
changePlayState(NOT_PLAYING);
changeHistoryState(HAS_HISTORY);
queue.erase(queue.begin());
if( queue.size() == 1 ) {
changeQueueState(END_OF_QUEUE);
}
changePlayState(STARTED);
break;
}
case END_OF_QUEUE: {
switch( repeat_state ) {
case NO_REPEAT: {
changeQueueState(NO_QUEUE);
changePlayState(NOT_PLAYING);
break;
}
case REPEAT: {
changePlayState(NOT_PLAYING);
changeQueueState(NO_QUEUE);
QModelIndex index = song_model->index(0, 0);
changeQueueState(HAS_QUEUE, &index);
changePlayState(STARTED);
break;
}
case REPEAT_ONE: {
// covered above
break;
}
}
break;
}
}
}
}
void MuseWindow::clearModels() {
song_model->clearModel();
artist_model->clearModel();
album_model->clearModel();
genre_model->clearModel();
playlist_model->clearModel();
}
void MuseWindow::stopAndReadyUpFMOD() {
ui->playButton->setText("Play");
ui->songProgressLabel->setText("0:00");
ui->songProgressSlider->setValue(0);
ui->songInfoLabel->setText("");
song_channel->stop();
song_to_play->release();
song_channel = NULL;
song_to_play = NULL;
}
void MuseWindow::clearSongs() {
DIR* dir;
struct dirent* file_info;
struct stat stat_info;
char *mp3_filepath;
char *mp3_filename = (char*) malloc(150);
strcpy(mp3_filename, "/Documents/MUSE");
mp3_filepath = (char*) malloc(strlen(getenv("HOME")) + strlen(mp3_filename) + 200);
strcpy(mp3_filepath, getenv("HOME"));
strcat(mp3_filepath, mp3_filename);
if((dir = opendir(mp3_filepath)) != NULL){
while((file_info = readdir(dir)) != NULL){
lstat(file_info->d_name, &stat_info);
if(strcmp((file_info->d_name + (strlen(file_info->d_name) - 4)), ".mp3") == 0) {
char* rm_file = (char*) malloc(strlen(getenv("HOME")) + strlen(mp3_filename) + 200);
strcpy(rm_file, mp3_filepath);
strcat(rm_file, "/");
strcat(rm_file, file_info->d_name);
remove(rm_file);
free(rm_file);
}
}
}
closedir(dir);
free(mp3_filename);
free(mp3_filepath);
}
int MuseWindow::downloadSong(char* song_path, int song_id, bool blocking) {
int download = song_id;
// see if song is already downloaded
int found_dupl = -1;
for( unsigned int i = 0; i < downloaded.size(); i++ ) {
if( download == downloaded.at(i) ) {
found_dupl = i;
break;
}
}
// song is not on disk
if( found_dupl == -1 ) {
if(blocking){
this->setEnabled(false);
QApplication::processEvents();
}
downloaded.insert(downloaded.begin(), download);
//Make sure that the messages are received properly so there's not any messy server-side issues.
while(sbthread->isRunning()){
continue;
}
// download the song
if( getSong(download, song_path) ) {
qDebug() << "Error downloading file!" << endl;
return 1;
}
// is downloaded too big?
if( downloaded.size() > 5 ) {
deleteSong(downloaded.back());
downloaded.pop_back();
}
} else { // song found, move to front of queue
downloaded.erase(downloaded.begin() + found_dupl);
downloaded.insert(downloaded.begin(), download);
}
return 0;
}
void MuseWindow::deleteSong(int delete_song){
char *del_song_path;
char *del_song_name = (char*) malloc(100);
sprintf(del_song_name, "/Documents/MUSE/muse_download_%d.mp3", delete_song);
del_song_path = (char*) malloc(strlen(getenv("HOME")) + strlen(del_song_name) + 1); // to account for NULL terminator
strcpy(del_song_path, getenv("HOME"));
strcat(del_song_path, del_song_name);
if( remove(del_song_path) ) {
qDebug() << "Error deleting old file!" << endl;
} else {
// no errors
}
free(del_song_name);
free(del_song_path);
}
void MuseWindow::changePlayState(PlayState state) {
play_state = state;
if( state == NOT_PLAYING ) {
stopAndReadyUpFMOD();
timer->stop();
ui->songInfoLabel->setText("");
ui->songProgressLabel->setText("-:--");
ui->songLengthLabel->setText("-:--");
ui->songProgressSlider->setValue(0);
ui->playButton->setText("Play");
} else if( state == STARTED ) {
char *new_song_path;
char *new_song_name = (char*) malloc(100);
sprintf(new_song_name, "/Documents/MUSE/muse_download_%d.mp3", queue.front().song_id);
new_song_path = (char*) malloc(strlen(getenv("HOME")) + strlen(new_song_name) + 1); // to account for NULL terminator
strcpy(new_song_path, getenv("HOME"));
strcat(new_song_path, new_song_name);
//While downloading next song, wait
if(dlthread->isRunning()){
this->setEnabled(false);
QApplication::processEvents();
while(dlthread->isRunning()){
continue;
}
}
if( downloadSong(new_song_path, queue.front().song_id, true) ) { // download the next song
qDebug() << "Unable to retrieve song" << endl;
changePlayState(NOT_PLAYING);
} else {
// try playing a song
FMOD_RESULT result = system->createStream(new_song_path, FMOD_CREATESTREAM, NULL, &song_to_play);
if( result == FMOD_RESULT::FMOD_OK ) {
unsigned int song_length;
song_to_play->getLength(&song_length, FMOD_TIMEUNIT_MS);
unsigned int song_length_s = song_length / 1000;
memset(songLengthText, 0, 10);
sprintf(songLengthText, "%d:%02d", song_length_s / 60, song_length_s % 60);
ui->songLengthLabel->setText(songLengthText);
ui->songProgressLabel->setText("0:00");
ui->songProgressSlider->setMinimum(0);
ui->songProgressSlider->setMaximum(song_length);
ui->songProgressSlider->setValue(0);
system->playSound(song_to_play, NULL, false, &song_channel);
// set information up
ui->songInfoLabel->setText(queue.front().info);
ui->playButton->setText("Pause");
// start the update timer
timer->start(75);
//Try downloading the next song in the queue
if(queue.size() > 1){
//Create threads
dlthread->setSongID(queue[1].song_id);
dlthread->start();
}
} else {
changePlayState(NOT_PLAYING);
}
}
//Enable if disabled by download wait
if(!this->isEnabled()){
this->setEnabled(true);
QApplication::processEvents();
}
free(new_song_name);
free(new_song_path);
} else if( state == RESUMED ) {
song_channel->setPaused(false);
ui->playButton->setText("Pause");
timer->start(75);
} else if( state == PAUSED ) {
song_channel->setPaused(true);
ui->playButton->setText("Play");
timer->stop();
}
}
void MuseWindow::changeHistoryState(HistoryState state) {
history_state = state;
if( state == NO_HISTORY ) {
history.clear();
} else if( state == HAS_HISTORY ) {
if( !history.empty() && history.front().song_id != queue.front().song_id ) {
history.insert(history.begin(), queue.front());
} else if( history.empty() ) {
history.insert(history.begin(), queue.front());
}
}
}
void MuseWindow::changeQueueState(QueueState state, const QModelIndex* index, bool shuffle_all) {
queue_state = state;
if( state == NO_QUEUE ) {
queue.clear();
} else if( state == HAS_QUEUE ) {
if( index != NULL ) {
// insert the songs in order
for( int i = index->row(); i < song_model->rowCount(); i++ ) {
struct songinfo info;
info.song_id = song_model->data(index->siblingAtRow(i), Qt::UserRole).value<int>();
info.info = song_model->data(index->sibling(i, 1)).value<QString>() + " - " + song_model->data(index->sibling(i, 2)).value<QString>();
queue.push_back(info);
}
// shuffle the queue
if( shuffle_state == SHUFFLE && shuffle_all ) {
std::random_shuffle( queue.begin(), queue.end() );
} else if( shuffle_state == SHUFFLE ) {
std::random_shuffle( queue.begin()+1, queue.end() );
}
if( queue.size() == 1 ) {
changeQueueState(END_OF_QUEUE);
}
}
} else if( state == END_OF_QUEUE ) {
}
}
void MuseWindow::changeConnectionState(ConnectionState state) {
connection_state = state;
if( state == CONNECTED ) {
memset(connectionText, 0, 100);
sprintf(connectionText, "Connected to: %s:%s", ip_address.toStdString().c_str(), port.toStdString().c_str());
ui->serverInfoLabel->setText(connectionText);
ui->connectButton->setText("Disconnect");
on_tabWidget_tabBarClicked(ui->tabWidget->currentIndex());
} else if( state == NOT_CONNECTED ) {
disconnect();
clearModels();
clearSongs();
free_playlist(playlists);
ui->serverInfoLabel->setText("Not connected to server.");
ui->connectButton->setText("Connect to...");
}
}
void MuseWindow::changeRepeatState(RepeatState state) {
repeat_state = state;
if( state == NO_REPEAT ) {
ui->repeatButton->setText("No Repeat");
ui->repeatButton->setChecked(false);
} else if( state == REPEAT ) {
ui->repeatButton->setText("Repeat");
ui->repeatButton->setChecked(true);
} else if( state == REPEAT_ONE ) {
ui->repeatButton->setText("Repeat One");
ui->repeatButton->setChecked(true);
}
}
void MuseWindow::changeShuffleState(ShuffleState state) {
shuffle_state = state;
if( state == NO_SHUFFLE ) {
ui->shuffleButton->setText("No Shuffle");
ui->shuffleButton->setChecked(false);
if( queue_state == HAS_QUEUE ) {
// find the song that is currently playing
QModelIndex index = song_model->index(0, 0);
QModelIndex current;
for( int i = 0; i < song_model->rowCount(); i++ ) {
if( index.siblingAtRow(i).data(Qt::UserRole).value<int>() == queue.front().song_id ) {
current = index.siblingAtRow(i);
break;
}
}
changeQueueState(NO_QUEUE);
changeQueueState(HAS_QUEUE, ¤t);
}
} else if( state == SHUFFLE ) {
ui->shuffleButton->setText("Shuffle");
ui->shuffleButton->setChecked(true);
if( queue_state == HAS_QUEUE || queue_state == END_OF_QUEUE ) {
// find the song that is currently playing
QModelIndex index = song_model->index(0, 0);
// we need to keep the current song at the front of the queue, but shuffle the rest behind it
songinfo temp = queue.front();
changeQueueState(NO_QUEUE);
queue.push_back(temp);
changeQueueState(HAS_QUEUE, &index, false);
}
}
}
void MuseWindow::on_songView_customContextMenuRequested(const QPoint &pos)
{
QModelIndex index = ui->songView->indexAt(pos);
int song_id = index.data(Qt::UserRole).value<int>();
ui->songView->setCurrentIndex(index);
if( song_id <= 0 ) { // not an actual song selected
return;
}
QAction* addToPlaylistAction = new QAction("Add song to playlist...", this);
addToPlaylistAction->setData(song_id);
connect(addToPlaylistAction, &QAction::triggered, this, &MuseWindow::on_songView_addSongToPlaylist);
QMenu* menu = new QMenu(this);
menu->addAction(addToPlaylistAction);
menu->popup(ui->songView->viewport()->mapToGlobal(pos));
}
void MuseWindow::on_playlistView_customContextMenuRequested(const QPoint &pos)
{
QModelIndex index = ui->playlistView->indexAt(pos);
const char* playlist_name = index.data(Qt::DisplayRole).value<QString>().toUtf8();
ui->playlistView->setCurrentIndex(index);
if( strcmp(playlist_name, "") == 0 ) { // not an actual song selected
return;
}
struct playlist* cursor = playlists;
struct playlist* playlist = NULL;
while( cursor != NULL ) {
if( strcmp(playlist_name, cursor->name) == 0 ) {
playlist = cursor;
break;
}
cursor = cursor->prev;
}
QVariant pl_ptr(QVariant::fromValue(static_cast<void*>(playlist)));
QAction* removeFromPlaylistAction = new QAction("Remove songs from playlist...", this);
removeFromPlaylistAction->setData(pl_ptr);
connect(removeFromPlaylistAction, &QAction::triggered, this, &MuseWindow::on_playlistView_removeSongsFromPlaylist);
QAction* deletePlaylist = new QAction("Delete this playlist", this);
deletePlaylist->setData(QString(playlist_name));
connect(deletePlaylist, &QAction::triggered, this, &MuseWindow::on_playlistView_deletePlaylist);
QMenu* menu = new QMenu(this);
menu->addAction(removeFromPlaylistAction);
menu->addAction(deletePlaylist);
menu->popup(ui->playlistView->viewport()->mapToGlobal(pos));
}
void MuseWindow::on_songView_addSongToPlaylist() {
QAction *act = qobject_cast<QAction *>(sender());
QVariant v = act->data();
int song_id = v.value<int>();
AddToPlaylistDialog* playlistDialog = new AddToPlaylistDialog(this);
if( playlistDialog->exec() == QDialog::Accepted ) {
struct playlist* selected = playlistDialog->getSelected();
if( selected != NULL ) {
addSongToPlaylist(song_id, selected);
char *new_playlist_path;
char *new_playlist_name = (char*) malloc(100);
sprintf(new_playlist_name, "/Documents/MUSE/%s.pl", selected->name);
new_playlist_path = (char*) malloc(strlen(getenv("HOME")) + strlen(new_playlist_name) + 1); // to account for NULL terminator
strcpy(new_playlist_path, getenv("HOME"));
strcat(new_playlist_path, new_playlist_name);
savePlaylist(selected);
free(new_playlist_name);
free(new_playlist_path);
free_playlist(playlistDialog->getPlaylists());
}
}
}
void MuseWindow::on_playlistView_removeSongsFromPlaylist() {
QAction *act = qobject_cast<QAction *>(sender());
QVariant v = act->data();
struct playlist* playlist = static_cast<struct playlist*>(v.value<void*>());
RemoveFromPlaylistDialog* playlistDialog = new RemoveFromPlaylistDialog(this, playlist);
if( playlistDialog->exec() == QDialog::Accepted ) {
int row = playlistDialog->getSelected();
char *playlist_path;
char *playlist_name = (char*) malloc(100);
sprintf(playlist_name, "/Documents/MUSE/%s.pl", playlist->name);
playlist_path = (char*) malloc(strlen(getenv("HOME")) + strlen(playlist_name) + 1); // to account for NULL terminator
strcpy(playlist_path, getenv("HOME"));
strcat(playlist_path, playlist_name);
deleteSongFromPlaylist(playlist, row);
savePlaylist(playlist);
free(playlist_name);
free(playlist_path);
} else {
}
}
void MuseWindow::on_playlistView_deletePlaylist() {
QAction *act = qobject_cast<QAction *>(sender());
QVariant v = act->data();
QString playlist_name = v.value<QString>();
const char* name = playlist_name.toUtf8();
deletePlaylist(name);
free_playlist(playlists);
playlists = NULL;
scanPlaylists(&playlists);
playlist_model->clearModel();
playlist_model->populateData(playlists);
}
DownloadThread::DownloadThread(MuseWindow* window){
this->window = window;
}
void DownloadThread::run(){
char* next_song_path;
char* next_song_name = (char*)malloc(100);
sprintf(next_song_name, "/Documents/MUSE/muse_download_%d.mp3", song_id);
next_song_path = (char*)malloc(strlen(getenv("HOME")) + strlen(next_song_name) + 1);
strcpy(next_song_path, getenv("HOME"));
strcat(next_song_path, next_song_name);
window->downloadSong(next_song_path, song_id, false);
free(next_song_name);
free(next_song_path);
}
void DownloadThread::setSongID(int song_id){
this->song_id = song_id;
}
SongBurstThread::SongBurstThread(MuseWindow* window, int iter){
this->window = window;
this->iter = iter;
}
void SongBurstThread::run(){
struct songinfolst* base_list;
querySongsBurst(&base_list, start_id, end_id);
window->song_model->clearModel();
window->song_model->populateData(base_list);
start_id += iter+1;
end_id += iter;
struct songinfolst* new_lst = NULL;
struct songinfolst* base_list_cur = base_list;
while(!querySongsBurst(&new_lst, start_id, end_id)){
//Append to the base list
while(base_list_cur->next != NULL){
base_list_cur = base_list_cur->next;
}
base_list_cur->next = new_lst;
window->song_model->addData(new_lst);
start_id += iter;
end_id += iter;
new_lst = NULL;
}
}
void SongBurstThread::reset(){
start_id = 0;
end_id = iter;
}
AlbumBurstThread::AlbumBurstThread(MuseWindow* window, int iter){
this->window = window;
this->iter = iter;
}
void AlbumBurstThread::run(){
struct albuminfolst* base_list;
queryAlbumsBurst(&base_list, start_id, end_id);
window->album_model->clearModel();
window->album_model->populateData(base_list);
start_id += iter+1;
end_id += iter;
struct albuminfolst* new_lst = NULL;
struct albuminfolst* base_list_cur = base_list;
while(!queryAlbumsBurst(&new_lst, start_id, end_id)){
//Append to the base list
while(base_list_cur->next != NULL){
base_list_cur = base_list_cur->next;
}
base_list_cur->next = new_lst;
window->album_model->addData(new_lst);
start_id += iter;
end_id += iter;
new_lst = NULL;
}
}
void AlbumBurstThread::reset(){
start_id = 0;
end_id = iter;
}
ArtistBurstThread::ArtistBurstThread(MuseWindow* window, int iter){
this->window = window;
this->iter = iter;
}
void ArtistBurstThread::run(){
struct artistinfolst* base_list;
queryArtistsBurst(&base_list, start_id, end_id);
window->artist_model->clearModel();
window->artist_model->populateData(base_list);
start_id += iter+1;
end_id += iter;
struct artistinfolst* new_lst = NULL;
struct artistinfolst* base_list_cur = base_list;
while(!queryArtistsBurst(&new_lst, start_id, end_id)){
//Append to the base list
while(base_list_cur->next != NULL){
base_list_cur = base_list_cur->next;
}
base_list_cur->next = new_lst;
window->artist_model->addData(new_lst);
start_id += iter;
end_id += iter;
new_lst = NULL;
}
}
void ArtistBurstThread::reset(){
start_id = 0;
end_id = iter;
}
GenreSongBurstThread::GenreSongBurstThread(MuseWindow* window, int iter){
this->window = window;
this->iter = iter;
}
void GenreSongBurstThread::run(){
struct songinfolst* base_list;
queryGenreSongsBurst(str, &base_list, start_id, end_id);
window->song_model->clearModel();
window->song_model->populateData(base_list);
start_id += iter+1;
end_id += iter;
struct songinfolst* new_lst = NULL;
struct songinfolst* base_list_cur = base_list;
while(!queryGenreSongsBurst(str, &new_lst, start_id, end_id)){
//Append to the base list
while(base_list_cur->next != NULL){
base_list_cur = base_list_cur->next;
}
base_list_cur->next = new_lst;
window->song_model->addData(new_lst);
start_id += iter;
end_id += iter;
new_lst = NULL;
}
}
void GenreSongBurstThread::setStr(const char* str){
this->str = str;
}
void GenreSongBurstThread::reset(){
start_id = 0;
end_id = iter;
if(str != NULL){
free((void*)str);
}
}
| true |
a0d29dc962547f69d081ea983a5b7c402a15cdae | C++ | as-iF-30/C-Programs | /simple/vowel.cpp | UTF-8 | 220 | 2.734375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
main()
{
char s;
printf("enter the value of s");
scanf("%s",&s);
if(s=='a,e,i,o,u,A,E,I,O,U')
{
printf("this is a vowel");
}
else
{
printf("this is not vowel");
}
getch();
}
| true |