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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
79a671892ae582c540cae013af16f74592fc4626 | C++ | keyto123/whatever | /TheGame/player.cpp | UTF-8 | 1,490 | 2.796875 | 3 | [] | no_license | #include "player.h"
#include "utils.h"
Player::Player(const char* name, Stats stats, int job = 0) : Job(job), Alive(name, stats) {
Player::job = job;
}
int Player::exp_up(int exp_gain) {
if(total_exp == MAX_EXP) {
return 0;
}
total_exp += exp_gain;
if(stats.level == MAX_LEVEL) {
return 0;
}
if(stats.experience < 100) {
if(stats.experience + exp_gain >= 100) {
stats.experience = 100;
level_up();
} else {
stats.experience += exp_gain;
}
}
return 1;
}
int Player::set_exp(int exp) {
stats.experience = exp;
return 1;
}
int Player::add_job_bonus(int job) {
uint8_t* current_stat = &(stats.max_hp);
for (int i = 0; i < 6; i++) {
utils.get_file_line(JOB_STATS_PATH, i);
}
}
int Player::change_job(int job) {
Player::job.change_job(job);
stats.level = 1;
add_job_bonus(job);
}
int Player::level_up() {
if(stats.level == MAX_LEVEL)
return 0;
stats.level++;
set_exp(0);
for(int i = 0, rnd; i < 6; i++) {
rnd = utils.get_random_value();
stat_up(i, rnd);
}
return 1;
}
int Player::stat_up(int stat, int rnd, int amount = 1) {
if (stat == HP) {
if (stats.max_hp != MAX_HP && rnd < stats.hp_growth) {
stats.max_hp = stats.max_hp + amount > MAX_HP ? MAX_HP : stats.max_hp + amount;
stats.hp += stats.max_hp;
}
return 1;
}
uint8_t* update_stat = &(stats.max_hp) + stat;
uint8_t* growth_stat = &(stats.hp_growth) + stat;
if (*update_stat != MAX_STATS && rnd < *growth_stat) {
++*update_stat;
return 1;
}
return 1;
} | true |
d1fe070ea3bafca53655042cea8c8d18f85cebd6 | C++ | Maklowic/Tic-Tac-Toe-with-AI | /tic tac toe vol. 2/bot.h | UTF-8 | 2,349 | 3.234375 | 3 | [] | no_license | #pragma once
#include <vector>
#include "board.h"
struct botPlay
{
botPlay() {}
botPlay(int Score) : score(Score){}
int x;
int y;
int score;
};
class Bot {
public:
// Initializes the Bot player
void init(int botPlayer);
// Performs the Bot move
void performMove(Board& board);
private:
botPlay getBestMove(Board& board, int player, int depth);
int _botPlayer; ///< Index of the Bot
int _humanPlayer; ///< Index of the player
};
void Bot::init(int botPlayer) {
_botPlayer = botPlayer;
_humanPlayer = _botPlayer == X_VAL ? O_VAL : X_VAL;
}
void Bot::performMove(Board& board) {
float a;
if (board.getSize() == 3) {
a = 1000;
}
else {
a = 1.4;
}
int cal_depth = a * board.getSize() - board.getMark();
botPlay bestMove = getBestMove(board, _botPlayer, cal_depth);
board.setVal(bestMove.x, bestMove.y, _botPlayer);
}
botPlay Bot::getBestMove(Board& board, int whoPlays, int depth)
{
int retv = board.checkVictory();
if (depth == 0) return 0;
if (retv == _botPlayer) // if Bot won, return great
{
return botPlay(10 + depth);
}
else if (retv == _humanPlayer) // if human won, return low
{
return botPlay(-depth - 10);
}
else if (retv == TIE_VAL) // if nobody won, return 0
{
return botPlay(0);
}
std::vector<botPlay> moves;
// loop through board
for (int y = 0; y < board.getSize(); y++)
{
for (int x = 0; x < board.getSize(); x++)
{
if (board.getVal(x, y) == NO_VAL)
{
botPlay move;
move.x = x;
move.y = y;
board.setVal(x, y, whoPlays);
// check if a good move
move.score = getBestMove(board, whoPlays == _botPlayer ? _humanPlayer : _botPlayer, depth - 1).score;
moves.push_back(move);
board.setVal(x, y, NO_VAL);
}
}
}
// pick the best move
int bestMove = 0;
if (whoPlays == _botPlayer)
{
int bestScore = -1000;
for (size_t i = 0; i < moves.size(); i++)
{
if (moves[i].score > bestScore)
{
bestMove = i;
bestScore = moves[i].score;
}
}
}
else
{
int bestScore = 1000;
for (size_t i = 0; i < moves.size(); i++)
{
if (moves[i].score < bestScore)
{
bestMove = i;
bestScore = moves[i].score;
}
}
}
// return it
return moves[bestMove];
} | true |
8e0820a448c3343b4abd968c57941078e2d0d38b | C++ | pdpreez/SwallowEngine | /Swallow/src/Swallow/Core/Timestep.cpp | UTF-8 | 354 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #include "swpch.hpp"
#include "Timestep.hpp"
namespace Swallow {
Timestep::Timestep(float time)
:m_Time(time)
{
}
Timestep::~Timestep(){}
Timestep::Timestep(const Timestep& cpy)
{
if (this != &cpy)
*this = cpy;
}
Timestep &Timestep::operator=(const Timestep& rhs)
{
if (this != &rhs)
this->m_Time = rhs.m_Time;
return *this;
}
} | true |
700520205a6f3472af1d1ace89f0559e94f87cab | C++ | solareenlo/42cpp-module-03 | /ex02/main.cpp | UTF-8 | 1,857 | 2.53125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tayamamo <tayamamo@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/27 07:06:33 by tayamamo #+# #+# */
/* Updated: 2021/05/28 17:29:02 by tayamamo ### ########.fr */
/* Copyright 2021 */
/* ************************************************************************** */
#include "FragTrap.hpp"
#include "ScavTrap.hpp"
#include "ClapTrap.hpp"
int main(void) {
FragTrap fragTrap("F");
ScavTrap scavTrap("S");
ClapTrap clapTrap("C");
fragTrap.rangeAttack("X");
scavTrap.rangeAttack("X");
clapTrap.rangeAttack("X");
std::cout << std::endl;
fragTrap.meleeAttack("X");
scavTrap.meleeAttack("X");
clapTrap.meleeAttack("X");
std::cout << std::endl;
fragTrap.vaulthunter_dot_exe("B");
fragTrap.vaulthunter_dot_exe("C");
fragTrap.vaulthunter_dot_exe("D");
fragTrap.vaulthunter_dot_exe("E");
fragTrap.vaulthunter_dot_exe("F");
fragTrap.vaulthunter_dot_exe("G");
std::cout << std::endl;
scavTrap.challengeNewcomer("A");
scavTrap.challengeNewcomer("B");
scavTrap.challengeNewcomer("C");
std::cout << std::endl;
fragTrap.takeDamage(200);
scavTrap.takeDamage(200);
fragTrap.vaulthunter_dot_exe("G");
scavTrap.challengeNewcomer("A");
return (0);
}
| true |
6e1122a91a2a04e8686b400c2cc7c5ffbf0be980 | C++ | CLDP/USACO-Training | /Section-2/lamps.cpp | UTF-8 | 4,334 | 2.703125 | 3 | [] | no_license | /*
ID: CHN
PROG: lamps
LANG: C++
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n, c;
vector<string> ans[16];
vector<int> on, off;
bool lamp[101];
bool check(string s) {
for (int i = 0; i < on.size(); ++i)
if (s[on[i]] == '0') return false;
for (int i = 0; i < off.size(); ++i)
if (s[off[i]] == '1') return false;
return true;
}
int main() {
freopen("lamps.in", "r", stdin);
freopen("lamps.out", "w", stdout);
cin >> n >> c;
for (int i = 0; i < n; ++i) lamp[i] = true;
int a;
while (true) {
cin >> a;
if (a == -1) break;
on.push_back(a-1);
}
while (true) {
cin >> a;
if (a == -1) break;
off.push_back(a-1);
}
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
// not change 3k+1
string s;
for (int p = 0; p < n; ++p)
if (lamp[p]) s += '1'; else s += '0';
if (check(s)) ans[i * 8 + j * 4 + k * 2].push_back(s);
for (int p = 0; p < n; p += 3) lamp[p] = !lamp[p];
// change 3k+1
s = "";
for (int p = 0; p < n; ++p)
if (lamp[p]) s += '1'; else s += '0';
if (check(s)) ans[i * 8 + j * 4 + k * 2 + 1].push_back(s);
for (int p = 0; p < n; p += 3) lamp[p] = !lamp[p];
for (int p = 0; p < n; p += 2) lamp[p] = !lamp[p];
}
for (int p = 1; p < n; p += 2) lamp[p] = !lamp[p];
}
for (int p = 0; p < n; ++p) lamp[p] = !lamp[p];
}
vector<string> anst;
if (c == 0) {
anst = ans[0];
} else
if (c == 1) {
for (int i = 0; i < ans[1].size(); ++i) anst.push_back(ans[1][i]);
for (int i = 0; i < ans[2].size(); ++i) anst.push_back(ans[2][i]);
for (int i = 0; i < ans[4].size(); ++i) anst.push_back(ans[4][i]);
for (int i = 0; i < ans[8].size(); ++i) anst.push_back(ans[8][i]);
} else
if (c == 2) {
for (int i = 0; i < ans[0].size(); ++i) anst.push_back(ans[0][i]);
for (int i = 0; i < ans[3].size(); ++i) anst.push_back(ans[3][i]);
for (int i = 0; i < ans[5].size(); ++i) anst.push_back(ans[5][i]);
for (int i = 0; i < ans[6].size(); ++i) anst.push_back(ans[6][i]);
for (int i = 0; i < ans[9].size(); ++i) anst.push_back(ans[9][i]);
for (int i = 0; i < ans[10].size(); ++i) anst.push_back(ans[10][i]);
for (int i = 0; i < ans[12].size(); ++i) anst.push_back(ans[12][i]);
} else
if (c % 2 == 1) {
for (int i = 0; i < ans[1].size(); ++i) anst.push_back(ans[1][i]);
for (int i = 0; i < ans[2].size(); ++i) anst.push_back(ans[2][i]);
for (int i = 0; i < ans[4].size(); ++i) anst.push_back(ans[4][i]);
for (int i = 0; i < ans[8].size(); ++i) anst.push_back(ans[8][i]);
for (int i = 0; i < ans[7].size(); ++i) anst.push_back(ans[7][i]);
for (int i = 0; i < ans[11].size(); ++i) anst.push_back(ans[11][i]);
for (int i = 0; i < ans[13].size(); ++i) anst.push_back(ans[13][i]);
for (int i = 0; i < ans[14].size(); ++i) anst.push_back(ans[14][i]);
} else
if (c % 2 == 0) {
for (int i = 0; i < ans[0].size(); ++i) anst.push_back(ans[0][i]);
for (int i = 0; i < ans[3].size(); ++i) anst.push_back(ans[3][i]);
for (int i = 0; i < ans[5].size(); ++i) anst.push_back(ans[5][i]);
for (int i = 0; i < ans[6].size(); ++i) anst.push_back(ans[6][i]);
for (int i = 0; i < ans[9].size(); ++i) anst.push_back(ans[9][i]);
for (int i = 0; i < ans[10].size(); ++i) anst.push_back(ans[10][i]);
for (int i = 0; i < ans[12].size(); ++i) anst.push_back(ans[12][i]);
for (int i = 0; i < ans[15].size(); ++i) anst.push_back(ans[15][i]);
}
sort(anst.begin(), anst.end());
if (anst.size() > 0) {
for (int i = 0; i < anst.size(); ++i) {
if (i == 0 || anst[i] != anst[i-1]) cout << anst[i] << endl;
}
} else {
cout << "IMPOSSIBLE" << endl;
}
return 0;
}
| true |
3e199b2f4fa7514404f7eaa776be383e782772f0 | C++ | ashleyh/kakoune | /src/word_db.hh | UTF-8 | 1,013 | 2.703125 | 3 | [
"Unlicense"
] | permissive | #ifndef word_db_hh_INCLUDED
#define word_db_hh_INCLUDED
#include "buffer.hh"
#include <set>
namespace Kakoune
{
class String;
// maintain a database of words available in a buffer
class WordDB : public BufferChangeListener_AutoRegister
{
public:
WordDB(const Buffer& buffer);
void on_insert(const Buffer& buffer, BufferCoord begin, BufferCoord end) override;
void on_erase(const Buffer& buffer, BufferCoord begin, BufferCoord end) override;
std::vector<String> find_prefix(const String& prefix) const;
private:
using WordToLines = std::map<String, std::vector<LineCount>>;
using LineToWords = std::map<LineCount, std::vector<String>>;
void add_words(LineCount line, const String& content);
LineToWords::iterator remove_line(LineToWords::iterator it);
void update_lines(LineToWords::iterator begin, LineToWords::iterator end,
LineCount num);
WordToLines m_word_to_lines;
LineToWords m_line_to_words;
};
}
#endif // word_db_hh_INCLUDED
| true |
a5b0c6490923d632173e06beb5d2965322b43202 | C++ | jiaxin96/MyTemplate | /c++/最小生成树.cpp | UTF-8 | 1,991 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
using namespace std;
#define MAX 100
#define MAXCOST 0x7fffffff
int graph[MAX][MAX];
int prim(int graph[][MAX], int n)
{
int lowcost[MAX]; // 记录到已经找到的子图的最短距离 0为找到
int mst[MAX]; // 记录最小距离的终点 0为在子图中
int i, j, min, minid, sum = 0;
mst[1] = 0;
lowcost[1] = 0;
// 初始化到1的距离 此时mst中只有1
for (i = 2; i <= n; i++)
{
lowcost[i] = graph[1][i];
mst[i] = 1;
}
for (i = 2; i <= n; i++) // 循环n-1次 把所有点加入mst集合中
{
min = MAXCOST;
minid = 0;
for (j = 2; j <= n; j++)
{
if (lowcost[j] < min && lowcost[j] != 0) // 从第二个开始寻找最小权值边 和对应的点
{
min = lowcost[j];
minid = j;
}
}
cout << "V" << mst[minid] << "-V" << minid << "=" << min << endl;
sum += min;
lowcost[minid] = 0;
// 更新 lowcase mst
for (j = 2; j <= n; j++)
{
if (graph[minid][j] < lowcost[j])
{
lowcost[j] = graph[minid][j];
mst[j] = minid;
}
}
}
return sum;
}
int main()
{
int i, j, k, m, n;
int x, y, cost;
ifstream in("input.txt");
in >> m >> n;//m=顶点的个数,n=边的个数
//初始化图G
for (i = 1; i <= m; i++)
{
for (j = 1; j <= m; j++)
{
graph[i][j] = MAXCOST;
}
}
//构建图G
for (k = 1; k <= n; k++)
{
in >> i >> j >> cost;
graph[i][j] = cost;
graph[j][i] = cost;
}
//求解最小生成树
cost = prim(graph, m);
//输出最小权值和
cout << "最小权值和=" << cost << endl;
return 0;
} | true |
dbf06bbcf21a883c63bbdac17fa2cfc09194c0e5 | C++ | gasburner/OJ | /niuke/3.cpp | UTF-8 | 1,112 | 3.65625 | 4 | [] | no_license | /*请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。*/
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str==nullptr||length<=0)
{return ;}
int orignalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (str[i]!='\0')
{ orignalLength++;
if (str[i]==' ')
{numberOfBlank++;}
i++;
}
int newLength= orignalLength + numberOfBlank *2;
if (newLength > length)
{return;}
int indexOfOriginal = orignalLength ;
int indexOfNew = newLength;
while (indexOfOriginal >=0 && indexOfNew > indexOfOriginal)
{if (str[indexOfOriginal] == ' ')
{str[indexOfNew--]='0';
str[indexOfNew--]='2';
str[indexOfNew--]='%';
}
else
{str[indexOfNew--]=str[indexOfOriginal];
}
indexOfOriginal--;
}
}
};
| true |
812f0e8c0da9821eaa05da751599018d0a565c46 | C++ | trslater/cpp | /cpp-essential-training/Chap04/struct.cpp | UTF-8 | 313 | 2.90625 | 3 | [] | no_license | // struct.cpp by Bill Weinman [bw.org]
// updated 2022-06-16
#include <fmt/core.h>
#include <iostream>
using fmt::format;
using std::cout;
struct S {
int i {};
double d {};
const char * s {};
};
int main() {
S s1 { 3, 47.9, "string one" };
cout << format("s1: {}, {}, {}\n", s1.i, s1.d, s1.s);
}
| true |
705044fde6a71242f1318b296f15e40ac4a6cd3d | C++ | yidansun0112/Exchange-Matching-Engine | /docker-deploy/src/database.cpp | UTF-8 | 12,970 | 2.71875 | 3 | [] | no_license | #include "database.hpp"
pthread_mutex_t dbmutex = PTHREAD_MUTEX_INITIALIZER;
int Database::trans_id=0;
void Database::openDatabase(){
C = new connection("dbname=exchange user=postgres password=passw0rd host=db port=5432");
if (C->is_open()) {
cout << "Opened database successfully: " << C->dbname() << endl;
} else {
cerr << "Can't open database" << endl;
throw exception();
}
string command="set transaction isolation level serializable;";
executeSql(command);
}
void Database::dropTable(){
string dropHeader="DROP TABLE IF EXISTS";
string dropEnder="CASCADE;\n";
string dropAccount=dropHeader+" ACCOUNT "+dropEnder;
string dropSymbol=dropHeader+" SYMBOL "+dropEnder;
string dropOrder=dropHeader+" ORDERS "+dropEnder;
string dropTotal=dropAccount+dropSymbol+dropOrder+"\n";
executeSql(dropTotal);
}
void Database::createTableSymbol(){
string header="CREATE TABLE IF NOT EXISTS SYMBOL\n(";
string ender=");\n";
string name="NAME VARCHAR(50) NOT NULL,\n";
string owner="OWNER INT NOT NULL,\n";
string amount="AMOUNT FLOAT,\n";
string primary_key="CONSTRAINT SYMPK PRIMARY KEY(NAME,OWNER),\n";
string foreign_key="CONSTRAINT OWNERFK FOREIGN KEY(OWNER) REFERENCES ACCOUNT(ID) ON DELETE SET NULL ON UPDATE CASCADE,\n";
string amount_nonneg="CONSTRAINT amountnonneg CHECK (AMOUNT>=0)\n";
string total=header+name+owner+amount+primary_key+foreign_key+amount_nonneg+ender;
executeSql(total);
}
void Database::createTableAccount(){
string header="CREATE TABLE IF NOT EXISTS ACCOUNT\n(";
string ender=");\n";
string id="ID INT NOT NULL,\n";
string balance="BALANCE FLOAT,\n";
string primary_key="CONSTRAINT IDPK PRIMARY KEY(ID),\n";
string baln_nonneg="CONSTRAINT balnnonneg CHECK (BALANCE>=0)\n";
string total=header+id+balance+primary_key+baln_nonneg+ender;
executeSql(total);
}
void Database::createTableOrder(){
createType();
createStatus();
string header="CREATE TABLE IF NOT EXISTS ORDERS\n(";
string ender=");\n";
string id="ID SERIAL NOT NULL,\n";
string symbol="SYM VARCHAR(50),\n";
string amount="AMOUNT FLOAT,\n";
string price="PRICE FLOAT,\n";
string type="TYPE type,\n";
string status="STATUS status,\n";
string account_id="ACCOUNT_ID INT,\n";
string trans_id="TRANS_ID INT,\n";
string time="TIME BIGINT NOT NULL,\n";
string primary_key="CONSTRAINT ORDERPK PRIMARY KEY(ID),\n";
string foreign_key="CONSTRAINT ACCOUNTFK FOREIGN KEY(ACCOUNT_ID) REFERENCES ACCOUNT(ID) ON DELETE SET NULL ON UPDATE CASCADE,\n";
string price_pos="CONSTRAINT pricepos CHECK (PRICE>0)\n";
string total=header+id+symbol+amount+price+type+status+account_id+trans_id+time+primary_key+foreign_key+price_pos+ender;
executeSql(total);
}
void Database::executeSql(string sql){
work W(*C);
W.exec(sql);
W.commit();
}
void Database::createTables(){
dropTable();
createTableAccount();
createTableSymbol();
createTableOrder();
trans_id=0;
}
void Database::disconnect(){
C->disconnect();
}
void Database::createType(){
string begin="DO $$ BEGIN\n";
string ifnot="IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname='type') THEN\n";
string create="CREATE TYPE type AS ENUM('sell','buy');\n";
string endif="END IF;\n";
string end="END $$;\n";
string total=begin+ifnot+create+endif+end;
executeSql(total);
}
void Database::createStatus(){
string begin="DO $$ BEGIN\n";
string ifnot="IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname='status') THEN\n";
string create="CREATE TYPE status AS ENUM('open','canceled','executed');\n";
string endif="END IF;\n";
string end="END $$;\n";
string total=begin+ifnot+create+endif+end;
executeSql(total);
}
string Database::createAccount(int id, double balance){
stringstream ss;
ss<<"INSERT INTO ACCOUNT VALUES("<<id<<","<<balance<<");\n";
string command=ss.str();
try{
executeSql(command);
}catch(pqxx::unique_violation &e){
return "This id already exists";
}catch(pqxx::check_violation &e){
return "Account balance cannot be negative";
}
return "success";
}
string Database::createSymbol(string name, int owner, int amount){
stringstream ss;
work W(*C);
ss<<"INSERT INTO SYMBOL VALUES("<<W.quote(name)<<","<<owner<<","<<amount<<") ";
ss<<"ON CONFLICT ON CONSTRAINT SYMPK DO UPDATE ";
ss<<"SET AMOUNT=SYMBOL.AMOUNT+"<<amount<<";\n";
W.commit();
string command=ss.str();
try{
executeSql(command);
}catch(pqxx::foreign_key_violation &e){
return "This id does not exist in Account";
}catch(pqxx::check_violation &e){
return "Symbol amount cannot be negative";
}
return "success";
}
string Database::createOrder(string name,double amount,double price, int account_id){
pthread_mutex_lock(&dbmutex);
int orderid=trans_id;
trans_id++;
pthread_mutex_unlock(&dbmutex);
stringstream ss;
work W(*C);
ss<<"INSERT INTO ORDERS (SYM,AMOUNT,PRICE,TYPE,STATUS,ACCOUNT_ID,TRANS_ID,TIME) VALUES(";
double amt=amount>0?amount:-amount;
ss<<W.quote(name)<<","<<amt<<","<<price<<",";
W.commit();
long time=getCurrTime();
try{
if(amount<0){
ss<<"'sell'"<<",";
minusSellAmount(name,-amount,account_id);
}else if(amount>0){
ss<<"'buy'"<<",";
minusBuyBalance(amount,price,account_id);
}else{
return "Order amount cannot be zero";
}
ss<<"'open'"<<","<<account_id<<","<<orderid<<","<<time<<");\n";
string command=ss.str();
executeSql(command);
}catch(pqxx::foreign_key_violation &e){
return "This id does not exist in Account";
}catch(pqxx::check_violation &e){
if(price<=0){
return "limit price should be positive";
}
if(amount<0){
return "You don't have enough amount to sell";
}else {
return "You don't have enough balance to buy";
}
}catch (MyException &e){
return e.what();
}
if(amount<0){
matchSellOrder(name, -amount, price, account_id, orderid);
}else{
matchBuyOrder(name, amount, price, account_id, orderid);
}
stringstream sss;
sss<<"success id is "<<orderid;
return sss.str();
}
void Database::minusSellAmount(string name,double amount,int account_id){
stringstream ss;
work W(*C);
ss<<"UPDATE SYMBOL SET AMOUNT=SYMBOL.AMOUNT-"<<amount<<" WHERE SYMBOL.NAME="<<W.quote(name);
ss<<" AND OWNER="<<account_id<<";\n";
W.commit();
string command=ss.str();
string select="SELECT * FROM SYMBOL "+command.substr(command.find("WHERE"));
work w(*C);
result r=w.exec(select);
w.commit();
if(r.size()==0){
throw MyException("Cannot find this symbol");
}
executeSql(command);
}
void Database::minusBuyBalance(double amount, double price,int account_id){
stringstream ss;
double cost=price*amount;
ss<<"UPDATE ACCOUNT SET BALANCE=BALANCE-"<<cost<<" WHERE ID="<<account_id<<";\n";
cout<<ss.str();
executeSql(ss.str());
}
vector<string> Database::queryOrder(int trans_id, int account_id){
stringstream ss;
vector<string> v;
ss<<"SELECT * FROM ORDERS WHERE TRANS_ID="<<trans_id<<" AND ACCOUNT_ID="<<account_id<<";\n";
work W(*C);
result r=W.exec(ss.str());
W.commit();
int num_rows=r.size();
cout<<num_rows<<endl;
for(result::const_iterator row=r.begin();row!=r.end();++row){
if(string(row[5].c_str())=="open"){
stringstream ss;
ss<<"open shares="<<row[2].c_str();
v.push_back(ss.str());
}
if(string(row[5].c_str())=="canceled"){
stringstream ss;
ss<<"canceled shares="<<row[2].c_str()<<" time="<<row[8];
v.push_back(ss.str());
}
if(string(row[5].c_str())=="executed"){
stringstream ss;
ss<<"executed shares="<<row[2].c_str()<<" price="<<row[3].c_str()<<" time="<<row[8];
v.push_back(ss.str());
}
}
return v;
}
vector<string> Database::cancelOrder(int trans_id, int account_id){
stringstream s1;
s1<<"SELECT * FROM ORDERS WHERE TRANS_ID="<<trans_id<<" AND ACCOUNT_ID="<<account_id<<" AND STATUS='open';\n";
work W(*C);
result r=W.exec(s1.str());
W.commit();
if(r.size()!=0){
result::const_iterator row=r.begin();
string type=row[4].as<string>();
string name=row[1].as<string>();
double amount=row[2].as<double>();
double price=row[3].as<double>();
int account_id=row[6].as<int>();
if(type=="buy"){
editBuyBalance(price,0,amount,account_id);
}else{
createSymbol(name,account_id,amount);
}
}
stringstream ss;
ss<<"UPDATE ORDERS SET STATUS='canceled', TIME="<<getCurrTime()<<" WHERE TRANS_ID="<<trans_id<<" AND ACCOUNT_ID="<<account_id<<" AND STATUS='open';\n";
executeSql(ss.str());
return queryOrder(trans_id, account_id);
}
void Database::matchSellOrder(string name, double amount, double price, int account_id, int trans_id){
stringstream ss;
ss<<"SELECT * FROM ORDERS WHERE STATUS='open' AND TYPE='buy' AND PRICE>="<<price<<" AND SYM="<<"'"<<name<<"'";
ss<<"ORDER BY PRICE DESC, TRANS_ID;\n";
work W(*C);
result r=W.exec(ss.str());
W.commit();
int num_row=r.size();
int i=0;
while(amount>0&&i<num_row){
result::const_iterator row=r.begin();
int buy_transId=row[7].as<int>();
int buy_accountId=row[6].as<int>();
double buy_amount=row[2].as<double>();
double buy_price=row[3].as<double>();
double execPrice=price;
double execAmount=amount;
cout<<i<<"round"<<"buy price is "<<buy_price<<endl;
if(buy_transId<trans_id){
execPrice=buy_price;
}
if(amount==buy_amount){
changeStatus(trans_id,execPrice);
changeStatus(buy_transId,execPrice);
amount=0;
}else if(amount<buy_amount){
changeStatus(trans_id,execPrice);
addNewLine(buy_transId, execPrice,amount,name, buy_accountId,"'buy'");
amount=0;
}else{
changeStatus(buy_transId,execPrice);
addNewLine(trans_id, execPrice,buy_amount,name,account_id,"'sell'");
amount-=buy_amount;
execAmount=buy_amount;
}
addBuyAmount(name,buy_accountId,execAmount);
addSellBalance(execAmount,execPrice,account_id);
editBuyBalance(buy_price,execPrice,execAmount,buy_accountId);
i++;
}
}
void Database::matchBuyOrder(string name, double amount, double price, int account_id, int trans_id){
stringstream ss;
ss<<"SELECT * FROM ORDERS WHERE STATUS='open' AND TYPE='sell' AND PRICE<="<<price<<" AND SYM="<<"'"<<name<<"'";
ss<<"ORDER BY PRICE, TRANS_ID;\n";
work W(*C);
result r=W.exec(ss.str());
W.commit();
int num_row=r.size();
int i=0;
while(amount>0&&i<num_row){
result::const_iterator row=r.begin();
int sell_transId=row[7].as<int>();
int sell_accountId=row[6].as<int>();
double sell_amount=row[2].as<double>();
double sell_price=row[3].as<double>();
double execPrice=price;
double execAmount=amount;
if(sell_transId<trans_id){
execPrice=sell_price;
}
if(amount==sell_amount){
changeStatus(trans_id,execPrice);
changeStatus(sell_transId,execPrice);
amount=0;
}else if(amount<sell_amount){
changeStatus(trans_id,execPrice);
addNewLine(sell_transId, execPrice,amount,name, sell_accountId,"'sell'");
amount=0;
}else{
changeStatus(sell_transId,execPrice);
addNewLine(trans_id, execPrice,sell_amount,name,account_id,"'buy'");
amount-=sell_amount;
execAmount=sell_amount;
}
addBuyAmount(name,account_id,execAmount);
addSellBalance(execAmount,execPrice,sell_accountId);
editBuyBalance(price,execPrice,execAmount,account_id);
i++;
}
}
void Database::addBuyAmount(string name,int owner, double amount){
createSymbol(name,owner,amount);
}
void Database::addSellBalance(double amount, double price, int account_id){
stringstream ss;
double income=amount*price;
ss<<"UPDATE ACCOUNT SET BALANCE=BALANCE+"<<income<<"WHERE ID="<<account_id<<";\n";
executeSql(ss.str());
}
void Database::addNewLine(int trans_id, double price,double amount,string name, int account_id, string type){
stringstream s1;
s1<<"UPDATE ORDERS SET AMOUNT=ORDERS.AMOUNT-"<<amount<<" WHERE TRANS_ID="<<trans_id<<" AND STATUS='open';\n";
executeSql(s1.str());
stringstream s2;
s2<<"INSERT INTO ORDERS (SYM,AMOUNT,PRICE,TYPE,STATUS,ACCOUNT_ID,TRANS_ID,TIME) VALUES(";
s2<<"'"<<name<<"',"<<amount<<","<<price<<","<<type<<","<<"'executed',"<<account_id<<","<<trans_id<<","<<getCurrTime()<<");\n";
executeSql(s2.str());
}
void Database::changeStatus(int trans_id, double price){
stringstream ss;
ss<<"UPDATE ORDERS SET STATUS='executed', TIME="<<getCurrTime()<<", PRICE="<<price<<" WHERE TRANS_ID="<<trans_id<<" AND STATUS='open';\n";
executeSql(ss.str());
}
long Database::getCurrTime(){
time_t now=time(NULL);
return (long)now;
}
void Database::editBuyBalance(double buy_price, double execPrice, double amount, int account_id){
if(buy_price!=execPrice){
stringstream ss;
double toAdd=(buy_price-execPrice)*amount;
ss<<"UPDATE ACCOUNT SET BALANCE=BALANCE+"<<toAdd<<" WHERE ID="<<account_id<<";\n";
executeSql(ss.str());
}
}
| true |
fb72dd2cdc2ea625508378fc0596c1fc8ead451d | C++ | milindbhavsar/Leetcode-Templates-and-Examples | /code/0897. Increasing Order Search Tree.h | UTF-8 | 1,345 | 3.5625 | 4 | [] | no_license | /*
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
Note:
The number of nodes in the given tree will be between 1 and 100.
Each node will have a unique integer value from 0 to 1000.
*/
class Solution {
private:
void helper(TreeNode*root, TreeNode* &prev, TreeNode* & res){
if(root->left) helper(root->left,prev,res);
if(!prev){
res=root;
}
else{
prev->left=NULL;
prev->right=root;
}
prev=root;
if(root->right) helper(root->right,prev,res);
}
public:
TreeNode* increasingBST(TreeNode* root) {
TreeNode *prev=NULL, *res=NULL;
if(!root) return NULL;
helper(root,prev,res);
//最后的节点下面要清空
prev->left=prev->right=NULL;
return res;
}
};
| true |
5a6d96c1b9e5088ec5712124bb4e6254ba272f2c | C++ | Tingwei-Jen/SLAM_Project02 | /include/myslam/mappoint.h | UTF-8 | 1,730 | 2.703125 | 3 | [] | no_license | #ifndef MAPPOINT_H
#define MAPPOINT_H
#include "myslam/common_include.h"
#include "myslam/frame.h"
namespace myslam
{
// forward declare :
//if there is any change in Frame.h or Frame.cpp, mappoint.cpp will not compile.
//class Frame;
class MapPoint
{
public:
typedef std::shared_ptr<MapPoint> Ptr;
unsigned long id_; // ID
static unsigned long factory_id_; // factory id
bool good_; // whether a good point
Vector3d pos_; // Position in world
Vector3d norm_; // Normal of viewing direction
Mat descriptor_; // Descriptor for matching
list<Frame*> observed_frames_; // key-frames that can observe this point
//只要使用前置宣告 (Forward Declaration) 的方式,並且將原來的實名物件轉換成物件指標的宣告方式,
//就能夠避免在表頭檔中 #include 其他表頭檔而造成的編譯依存關係。
int visible_times_; // being visible in current frame
int matched_times_; // being an inliner in pose estimation
public:
MapPoint();
MapPoint(
unsigned long id,
const Vector3d& position,
const Vector3d& norm,
Frame* frame = nullptr,
const Mat& descriptor=Mat()
);
inline cv::Point3f getPositionCV() const {
return cv::Point3f( pos_(0,0), pos_(1,0), pos_(2,0) );
}
//factory method
static MapPoint::Ptr createMapPoint();
static MapPoint::Ptr createMapPoint(
const Vector3d& pos_world,
const Vector3d& norm_,
const Mat& descriptor,
Frame* frame );
};
}
#endif //MAPPOINT_H | true |
60e8bcb8fb17695e3c8696c2a12ef3dd3f8d9462 | C++ | sholsapp/gallocy | /test/test_singleton.cpp | UTF-8 | 2,117 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gtest/gtest.h"
#include "libgallocy.h"
class SingletonHeapTests: public ::testing::Test {
protected:
virtual void TearDown() {
__reset_memory_allocator();
}
};
TEST_F(SingletonHeapTests, ZeroMalloc) {
void* ptr = NULL;
ptr = local_internal_memory.malloc(0);
ASSERT_NE(ptr, (void*) NULL);
}
TEST_F(SingletonHeapTests, SimpleMalloc) {
char* ptr = (char*) local_internal_memory.malloc(sizeof(char) * 16);
ASSERT_NE(ptr, (void *) NULL);
memset(ptr, 'A', 15);
ptr[15] = 0;
ASSERT_EQ(strcmp(ptr, "AAAAAAAAAAAAAAA"), 0);
local_internal_memory.free(ptr);
}
TEST_F(SingletonHeapTests, SmallMalloc) {
char* ptr = (char*) local_internal_memory.malloc(1);
ASSERT_TRUE(ptr != NULL);
ptr[0] = 'A';
ASSERT_EQ(*ptr, 'A');
}
TEST_F(SingletonHeapTests, MediumMalloc) {
int sz = 4312;
char* ptr = (char*) local_internal_memory.malloc(sz);
ASSERT_TRUE(ptr != NULL);
for (int i = 0; i < sz; i++)
ptr[i] = 33 + (i % 126 - 33);
for (int i = 0; i < sz; i++)
ASSERT_EQ(ptr[i], 33 + (i % 126 - 33));
local_internal_memory.free(ptr);
}
TEST_F(SingletonHeapTests, BigMalloc) {
int sz = 4096 * 16;
char* ptr = (char*) local_internal_memory.malloc(sz);
ASSERT_TRUE(ptr != NULL);
for (int i = 0; i < sz; i++)
ptr[i] = 33 + (i % 126 - 33);
for (int i = 0; i < sz; i++)
ASSERT_EQ(ptr[i], 33 + (i % 126 - 33));
local_internal_memory.free(ptr);
}
TEST_F(SingletonHeapTests, ManyMalloc) {
char* ptr;
for (int i = 0; i < 4096; i++) {
ptr = (char*) local_internal_memory.malloc(32);
ASSERT_TRUE(ptr != NULL);
for (int j = 0; j < 32; j++)
ptr[j] = 'A';
for (int j = 0; j < 32; j++)
ASSERT_EQ(ptr[j], 'A');
local_internal_memory.free(ptr);
}
}
TEST_F(SingletonHeapTests, ReuseAllocation) {
char* ptr1 = NULL;
char* ptr2 = NULL;
ptr1 = (char*) local_internal_memory.malloc(64);
memset(ptr1, 'A', 64);
local_internal_memory.free(ptr1);
ptr2 = (char*) local_internal_memory.malloc(16);
memset(ptr2, 'B', 16);
ASSERT_EQ(ptr1, ptr2);
}
| true |
ee5f69f4519b0919543b46b6d4c5d1539c692bc9 | C++ | ReFantasy/IPL | /sample/ch09/P424F9_29.cpp | UTF-8 | 2,389 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include "opencv2/opencv.hpp"
#include "utility/utility.hpp"
#include "algorithm/algorithm.hpp"
using namespace std;
using namespace cv;
bool IsSame(const Mat A, const Mat B)
{
Mat dif = A - B;
for (auto it = dif.begin<uchar>(); it != dif.end<uchar>(); it++)
{
if (*it != 0)
return false;
}
return true;
}
// 9.5-22
Mat D_G(const Mat F, const Mat G, const Mat se, int n)
{
Mat res;
if (n == 0)
{
return F;
}
else if (n == 1)
{
dilate(F, res, se);
bitwise_and(res, G, res);
return res;
}
else
{
res = D_G(F, G, se, n - 1);
return D_G(res, G, se, 1);
}
}
// 9.5-24
Mat E_G(const Mat F, const Mat G, const Mat se, int n)
{
Mat res;
if (n == 0)
{
return F;
}
else if (n == 1)
{
erode(F, res, se);
bitwise_or(res, G, res);
return res;
}
else
{
res = E_G(F, G, se, n - 1);
return E_G(res, G, se, 1);
}
}
// 9.5-25
Mat RGD(const Mat F, const Mat G, const Mat se)
{
Mat res_k_1 = F;
Mat res_k = D_G(F, G, se, 1);
while (!IsSame(res_k, res_k_1))
{
res_k_1 = res_k;
res_k = D_G(res_k, G, se, 1);
}
return res_k;
}
Mat Open(const Mat src, const Mat se)
{
Mat res;
erode(src, res, se);
dilate(res, res, se);
return res;
}
int main(int argc, char*argv[])
{
Mat src = imread("../data/DIP3E_Original_Images_CH09/Fig0929(a)(text_image).tif", 0);
cv::threshold(src, src, 205, 255, THRESH_BINARY);
Mat se = getStructuringElement(cv::MORPH_RECT, cv::Size(1,51));
Mat b;
erode(src, b, se, { -1,-1 }, 1);
Mat c = Open(src, se);
se = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
Mat d = RGD(c, src, se);
imshow("a", src);
imshow("b", b);
imshow("c", c);
imshow("d", d);
waitKey();
return 0;
}
//Mat B = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
//Mat F(9, 10, CV_8UC1, Scalar(0));
//for (int i = 1; i <= 4; i++)
//{
// for (int j = 1; j <= 6; j++)
// {
// F.at<uchar>(i, j) = 255;
// }
//}
//F.at<uchar>(1, 6) = 255;
//F.at<uchar>(4, 1) = 255;
//F.at<uchar>(4, 2) = 255;
//
//Mat G(9, 10, CV_8UC1, Scalar(0));
//G.at<uchar>(2, 2) = 255;
//G.at<uchar>(3, 2) = 255;
//G.at<uchar>(3, 3) = 255;
//G.at<uchar>(4, 3) = 255;
//for (int i = 5; i <= 7; i++)
//{
// for (int j = 3; j <= 5; j++)
// {
// G.at<uchar>(i, j) = 255;
// }
//}
//G.at<uchar>(6, 4) = 0;
//
//Mat res = EGF(F, G, B, 30);
//resize(res, res, { 100,90 });
//imshow("res", res);
| true |
61283475dad033e939c72c1d7b8c49f456691ab2 | C++ | dmin0211/Codeforces-Round-719 | /1520A.cpp | UTF-8 | 896 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstring>
using namespace std;
bool visit[30];
int main(){
int t=0;
int number_size=0;
cin>>t;
for (int i = 0; i < t; ++i) {
cin>>number_size;
memset(visit,false,30);
for (int j = 0; j < number_size; ++j) {
char tmp,prev;
if(j!=0) prev=tmp;
cin>>tmp;
// cout<<tmp<<"\t"<<int(tmp)<<"\t"<<int('A')<<endl;
int temp = tmp-'A';
if(visit[temp]) {
if(prev==tmp) {
if(j==number_size-1) cout<<"YES"<<endl;
continue;
}
cout<<"NO"<<endl;
// break;
j=number_size;
string temp;
getline(cin,temp);
}
visit[temp]=true;
if(j==number_size-1) cout<<"YES"<<endl;
}
}
} | true |
7dbaceff320dbca5631bbaa069dd4895b22a5ca5 | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/700-799/797A-kFactorization.cpp | UTF-8 | 534 | 2.9375 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <vector>
int main(){
long n; int k; scanf("%ld %d", &n, &k);
std::vector<long> factors;
long div(2);
while(n > 1){
if(n % div == 0){factors.push_back(div); n /= div;}
else{++div;}
}
if(factors.size() < k){puts("-1");}
else{
for(int p = 0; p < k - 1; p++){printf("%ld ", factors[p]);}
long lastFactor(1);
for(long p = k - 1; p < factors.size(); p++){lastFactor *= factors[p];}
printf("%ld\n", lastFactor);
}
return 0;
}
| true |
07766b483bc536a4d7cb2ddad1577f7c741f1f95 | C++ | firewood/topcoder | /atcoder/abc_207/e.cpp | UTF-8 | 1,821 | 2.53125 | 3 | [] | no_license | #include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
#include <iostream>
#include <sstream>
#include <numeric>
#include <map>
#include <set>
#include <queue>
#include <vector>
using namespace std;
static const int64_t MOD = 1000000007;
struct modint {
int64_t x;
modint() { }
modint(int _x) : x(_x) { }
operator int() const { return (int)x; }
modint operator+(int y) { return (x + y + MOD) % MOD; }
modint operator+=(int y) { x = (x + y + MOD) % MOD; return *this; }
modint operator-(int y) { return (x - y + MOD) % MOD; }
modint operator-=(int y) { x = (x - y + MOD) % MOD; return *this; }
modint operator*(int y) { return (x * y) % MOD; }
modint operator*=(int y) { x = (x * y) % MOD; return *this; }
modint operator/(int y) { return (x * modpow(y, MOD - 2)) % MOD; }
modint operator/=(int y) { x = (x * modpow(y, MOD - 2)) % MOD; return *this; }
static modint modinv(int a) { return modpow(a, MOD - 2); }
static modint modpow(int a, int b) {
modint x = a, r = 1;
for (; b; b >>= 1, x *= x) if (b & 1) r *= x;
return r;
}
};
int64_t solve(int64_t N, std::vector<int64_t> A) {
modint ans = 0;
vector<vector<modint>> dp(N + 1, vector<modint>(N + 1, 0)), tot(N + 1, vector<modint>(N + 1, 0));
tot[0][0] = 1;
int64_t sum = 0;
for (int i = 0; i < N; ++i) {
sum += A[i];
for (int j = 1; j <= N; ++j) {
dp[i][j] = tot[j - 1][sum % j];
}
for (int j = 1; j <= N; ++j) {
tot[j][sum % (j + 1)] += dp[i][j];
}
}
for (int i = 0; i < N; ++i) {
ans += dp[N - 1][i + 1];
}
return ans;
}
int main() {
#if DEBUG || _DEBUG
freopen("in.txt", "r", stdin);
// freopen("in_1.txt", "r", stdin);
#endif
int64_t N;
std::cin >> N;
std::vector<int64_t> A(N);
for (int i = 0; i < N; i++) {
std::cin >> A[i];
}
cout << solve(N, std::move(A)) << endl;
return 0;
}
| true |
d86ad5f701c459423e314aef6f4e061dc899093c | C++ | BenjaminSchulte/fma | /fma65816/include/lang/InstructionArguments.hpp | UTF-8 | 5,207 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef __FMA65816_LANG_INSTRUCTIONARGUMENTS_H__
#define __FMA65816_LANG_INSTRUCTIONARGUMENTS_H__
#include <fma/interpret/ParameterList.hpp>
#include <fma/types/Base.hpp>
#include <fma/symbol/Reference.hpp>
#include <fma/assem/Operand.hpp>
#include <fma/Project.hpp>
namespace FMA65816 {
namespace lang {
struct InstructionArgument {
enum Type {
INVALID,
INDIRECT,
INDIRECT_X,
IMMEDIATE,
DIRECT_PAGE,
LONG_ADDRESS,
LONG_INDIRECT,
REG_A,
REG_X,
REG_Y,
REG_S,
ADDRESS
};
enum ValueType {
VALUE_NONE,
VALUE_NUMBER,
VALUE_SYMBOL
};
InstructionArgument()
: type(INVALID), valueType(VALUE_NONE) {}
InstructionArgument(Type type)
: type(type), valueType(VALUE_NONE) {}
InstructionArgument(Type type, const uint64_t &number)
: type(type), valueType(VALUE_NUMBER), number(number) {}
InstructionArgument(Type type, const FMA::symbol::ReferencePtr &reference)
: type(type), valueType(VALUE_SYMBOL), reference(reference) {}
~InstructionArgument() {
}
FMA::assem::Operand *createOperand(InstructionArgument *other=NULL) const;
FMA::assem::Operand *createValueOperand(InstructionArgument *other) const;
FMA::assem::Operand *createValueOperand() const;
Type type;
ValueType valueType;
uint64_t number;
FMA::symbol::ReferencePtr reference;
};
class InstructionArguments {
public:
InstructionArguments(const FMA::interpret::ContextPtr &context, FMA::Project *project, const FMA::interpret::GroupedParameterList ¶ms);
~InstructionArguments();
inline bool isValid() const { return valid; }
inline bool absolute() const { return numArgs == 1 && left->type==InstructionArgument::ADDRESS; }
inline bool immediate() const { return numArgs == 1 && left->type==InstructionArgument::IMMEDIATE; }
inline bool move() const { return numArgs == 2 && left->type==InstructionArgument::IMMEDIATE && right->type==InstructionArgument::IMMEDIATE; }
inline bool indirect() const { return numArgs == 1 && left->type==InstructionArgument::INDIRECT; }
inline bool longIndirect() const { return numArgs == 1 && left->type==InstructionArgument::LONG_INDIRECT; }
inline bool indirectY() const { return numArgs == 2 && left->type==InstructionArgument::INDIRECT && right->type==InstructionArgument::REG_Y; }
inline bool longIndirectY() const { return numArgs == 2 && left->type==InstructionArgument::LONG_INDIRECT && right->type==InstructionArgument::REG_Y; }
inline bool directPage() const { return numArgs == 1 && left->type==InstructionArgument::DIRECT_PAGE; }
inline bool longAddress() const { return numArgs == 1 && left->type==InstructionArgument::LONG_ADDRESS; }
inline bool absoluteX() const { return numArgs == 2 && left->type==InstructionArgument::ADDRESS && right->type==InstructionArgument::REG_X; }
inline bool absoluteY() const { return numArgs == 2 && left->type==InstructionArgument::ADDRESS && right->type==InstructionArgument::REG_Y; }
inline bool absoluteS() const { return numArgs == 2 && left->type==InstructionArgument::ADDRESS && right->type==InstructionArgument::REG_S; }
inline bool absoluteLongX() const { return numArgs == 2 && left->type==InstructionArgument::LONG_ADDRESS && right->type==InstructionArgument::REG_X; }
inline bool absoluteLongY() const { return numArgs == 2 && left->type==InstructionArgument::LONG_ADDRESS && right->type==InstructionArgument::REG_Y; }
inline bool directPageX() const { return numArgs == 2 && left->type==InstructionArgument::DIRECT_PAGE && right->type==InstructionArgument::REG_X; }
inline bool directPageY() const { return numArgs == 2 && left->type==InstructionArgument::DIRECT_PAGE && right->type==InstructionArgument::REG_Y; }
inline bool indirectX() const { return numArgs == 2 && left->type==InstructionArgument::INDIRECT && right->type==InstructionArgument::REG_X; }
inline bool registerA() const { return numArgs == 1 && left->type==InstructionArgument::REG_A; }
inline bool registerX() const { return numArgs == 1 && left->type==InstructionArgument::REG_X; }
inline bool registerY() const { return numArgs == 1 && left->type==InstructionArgument::REG_Y; }
inline bool implicit() const { return numArgs == 0; }
inline FMA::assem::Operand *createLeftOperand() const { return left->createOperand(); }
inline FMA::assem::Operand *createRightOperand() const { return right->createOperand(); }
FMA::assem::Operand *createOperand() const;
inline InstructionArgument *getLeft() const { return left; }
inline InstructionArgument *getRight() const { return right; }
protected:
InstructionArgument *analyzeArgs(const FMA::types::TypePtr ¶m);
InstructionArgument *analyzeImmediate(const FMA::types::ObjectPtr &value);
InstructionArgument *analyzeNumber(const FMA::types::ObjectPtr &value);
InstructionArgument *analyzeTypedNumber(const FMA::types::ObjectPtr &value);
InstructionArgument *analyzeSymbol(const FMA::types::ObjectPtr &value);
InstructionArgument *analyzeRegister(const FMA::types::ObjectPtr &value);
InstructionArgument *left;
InstructionArgument *right;
FMA::interpret::ContextPtr context;
FMA::Project *project;
bool valid;
uint8_t numArgs;
};
}
}
#endif
| true |
8bdae4056cd370ccdb3de60848a79a4bbf02ce02 | C++ | 74kw/ICPP | /CPP_07_soubory_pretezovani/Main.cpp | UTF-8 | 4,108 | 2.90625 | 3 | [] | no_license | #include "Person.h"
#include <fstream>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
static void WriteString(std::ofstream& output, const std::string& obj) {
int stringLength = obj.length();
output.write((const char*)&stringLength, sizeof(stringLength));
output.write(obj.c_str(), stringLength);
}
static std::string ReadString(std::ifstream& input) {
int stringLength = 0;
input.read((char*)&stringLength, sizeof(int));
char* temp = new char[stringLength + 1];
temp[stringLength] = '\0';
input.read(temp, stringLength);
std::string string = temp;
delete [] temp;
return string;
}
static void SaveText() {
Person os1 = Person("Adam","Novak",Address("Moravcova","Praha",28002),Date(20,10,2000));
Person os2 = Person("Josef", "Trnka", Address("Hlodavcova", "Brno", 38000), Date(11, 3, 2002));
Person os3 = Person("Ondrej", "Novotny", Address("Rudova", "Pardubice", 48000), Date(8, 12, 1995));
int const pocet = 3;
Person pole[pocet];
pole[0] = os1;
pole[1] = os2;
pole[2] = os3;
std::ofstream output{ "output.txt" };
if (!output)
throw std::runtime_error("Bad file path");
//output.open("output.txt", std::ios_base::out);
output << pocet << std::endl;
for (int i = 0; i < pocet; i++)
{
output << pole[i];
}
output.close();
}
static void SaveBinary() {
Person os1 = Person("Adam","Novak",Address("Moravcova","Praha",28002),Date(20,10,2000));
Person os2 = Person("Josef", "Trnka", Address("Hlodavcova", "Brno", 38000), Date(11, 3, 2002));
Person os3 = Person("Ondrej", "Novotny", Address("Rudova", "Pardubice", 48000), Date(8, 12, 1995));
int const pocet = 3;
Person pole[pocet];
pole[0] = os1;
pole[1] = os2;
pole[2] = os3;
//open stream
std::ofstream outputBinary{ "binary.dat", std::ios_base::out | std::ios_base::binary };
if (!outputBinary)
throw std::runtime_error("Bad file path");
// write size of array
outputBinary.write((const char*)&pocet, sizeof(pocet));
for (int i = 0; i < pocet; i++)
{
//WriteString(outputBinary, pole[i].GetFirstName());
//WriteString(outputBinary, pole[i].GetLastName());
//outputBinary.write((const char*)&pole[i].GetDate(), sizeof(pole[i].GetDate()));
//WriteString(outputBinary, pole[i].GetAddress().GetStreet());
//WriteString(outputBinary, pole[i].GetAddress().GetCity());
//int zip = pole[i].GetAddress().GetZipCode();
//outputBinary.write((const char*)&zip, sizeof(zip));
pole[i].ToBinary(outputBinary);
}
outputBinary.close();
}
static void LoadText() {
std::ifstream input{ "output.txt" };
if (!input)
throw std::runtime_error("Bad file path");
int pocet = 0;
input >> pocet;
Person* pole = new Person[pocet];
for (int i = 0; i < pocet; i++)
{
pole[i] = Person{};
input >> pole[i];
std::cout << pole[i];
}
delete[] pole;
}
static void LoadBinary() {
//open stream
std::ifstream inputBinary{ "binary.dat", std::ios_base::in | std::ios_base::binary };
if (!inputBinary)
throw std::runtime_error("Bad file path");
int pocet = 0;
// read size of array
inputBinary.read((char*)&pocet, sizeof(int));
Person* pole = new Person[pocet];
for (int i = 0; i < pocet; i++)
{
//pole[i] = Person();
//pole[i].SetFirstName(ReadString(inputBinary));
//pole[i].SetLastName(ReadString(inputBinary));
//Date datum;
//inputBinary.read((char*)&datum, sizeof(datum));
//pole[i].SetDate(datum);
//Address adresa;
//adresa.SetStreet(ReadString(inputBinary));
//adresa.SetCity(ReadString(inputBinary));
//int zip;
//inputBinary.read((char*)&zip, sizeof(zip));
//adresa.SetZipCode(zip);
//pole[i].SetAddress(adresa);
pole[i].LoadBinary(inputBinary);
std::cout << pole[i];
}
delete[] pole;
}
int main() {
SaveBinary();
LoadBinary();
//Memory LEAK Check start
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
_CrtDumpMemoryLeaks();
//Memory Leak Check end
}
| true |
d132136686d56cc865781e923c7d7ea52a9a1bd0 | C++ | pconrad/old_pconrad_cs16 | /14F/lect/10.13/argvArgc/argvArgcDemo.cpp | UTF-8 | 302 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <cmath> // #include <math.h> is what we would write in a C program
#include <cstdlib> // for atof
int main(int argc, char *argv[]) {
double x = atof(argv[1]);
cout << "x=" << x << endl;
cout << "sqrt(x)=" << sqrt(x) << endl;
return 0;
}
| true |
bb823bc22b7b1d123efcf85d7740b1a6efb79a61 | C++ | fanyazhi/Scientific-Computing | /CompactSPICE/src/circuit.cpp | UTF-8 | 1,843 | 2.625 | 3 | [] | no_license | /*
* circuit.cpp
* ODESolver
* This file contains functions for RC circuit and CS amplifier
*
* Created by Yijia Chen (yc2366) and Yazhi Fan (yf92) on 4/18/18.
* Copyright © 2018 Yijia and Yazhi. All rights reserved.
*
*/
#include "circuit.h"
using namespace std;
using namespace Eigen;
// ----------------------------------------------------------------------------------------
VectorXd RCcircuit(double t, VectorXd X) {
double C1 = 1E-12, C2 = 1E-12; //F
double R1 = 10E3, R2 = 10E3, R3 = 10E3; //ohms
Matrix2d M;
M(0, 0) = (-1.0) * ((1/C1/R1) + (1/C1/R2));
M(0, 1) = 1/C1/R2;
M(1, 0) = 1/C2/R2;
M(1, 1) = (-1.0) * ((1/C2/R2) + (1/C2/R3));
Vector2d B;
B(0) = currentSource(t)/C1;
B(1) = 0;
Vector2d f;
f = M*X+B;
return f;
}
VectorXd CSamplifier(double t, VectorXd x) {
double IS = 5E-6; //A
double k = 0.7;
double VTH = 1.0; //V
double VT = 26E-3; //V
//get ID,EKV
double ID = EKV (x(0), x(1), IS, k, VTH, VT);
double VDD = 5; //V
double RG = 10E3, RL = 10E3; //ohms
double C1 = 1E-12, C2 = 1E-12; //F
Vector2d f;
f(0) = (-1.0/RG/C1) * x(0) + (currentSource(t)/C1);
f(1) = (-1.0*ID/C2) - ((1/RL/C2)*x(1)) + (VDD/RL/C2);
return f;
}
double currentSource (double t) {
double T = 20; //s
if (fmod(t*1E9, T) < 1) return 1E5 * fmod(t, T/1E9);
else if (fmod(t*1E9, T) < 10) return 1E-4;
else if (fmod(t*1E9, T) < 11) return (-1.0)*1E5*fmod(t, T/1E9) + 11E-4;
else return 0;
}
double EKV (double VGS, double VDS, double IS, double k, double VTH, double VT) {
double IF = IS*pow( log(1+exp( (k*(VGS - VTH)) / (2*VT) )) , 2);
double IR = IS*pow( log(1+exp( (k*(VGS - VTH)-VDS) / (2*VT) )) , 2);
double ID = IF - IR;
return ID;
} | true |
9a73c7cd12f3c3bd46bf2781308af15d738c3034 | C++ | alissastanderwick/OpenKODE-Framework | /01_Develop/libXMCocos2D-v3/Source/3d/StringTool.cpp | GB18030 | 4,023 | 2.75 | 3 | [
"MIT"
] | permissive | #include "3d/StringTool.h"
namespace cocos3d
{
StringTool::StringTool()
{
}
StringTool::~StringTool()
{
}
std::vector<std::string> StringTool::StringSplitByString(const std::string &str, const std::string &strKey, int IgnoreCase /* = false */)
{
std::vector<std::string> Result;
const char *cpPos = NULL;
const char *pLastPos = NULL;
char *pStart = new char[str.size() + 1];
strncpy(pStart, str.c_str(), str.size() + 1);
Result.clear();
pLastPos = NULL;
for (int i = 0; i < str.size(); i++)
{
int nCompareResult = 0;
/* if (IgnoreCase)
{
nCompareResult = strnicmp(pStart + i, strKey.c_str(), strKey.size());
}
else*/
{
nCompareResult = strncmp(pStart + i, strKey.c_str(), strKey.size());
}
if (!nCompareResult)
{
pStart[i] = '\0';
if (pLastPos)
{
Result.push_back(std::string(pLastPos) );
pLastPos = pStart + i + strKey.size();
pLastPos = NULL;
}
i += strKey.size() - 1;
}
else
{
if (!pLastPos) // һַĿʼ
{
pLastPos = pStart + i;
}
}
}
if (pLastPos)
{
Result.push_back(std::string(pLastPos) );
pLastPos = NULL;
}
delete []pStart;
return Result;
}
std::vector<std::string> StringTool::StringSplitByChar(const std::string &str, char cKey, int IgnoreCase /* = false */)
{
std::vector<std::string> Result;
const char *cpPos = NULL;
const char *pLastPos = NULL;
char *pStart = new char[str.size() + 1];
strncpy(pStart, str.c_str(), str.size() + 1);
Result.clear();
pLastPos = NULL;
for (int i = 0; i < str.size(); i++)
{
int nCompareResult = -1;
if (IgnoreCase)
{
nCompareResult = toupper(pStart[i]) - toupper(cKey);
}
else
{
nCompareResult = pStart[i] - cKey;
}
if (!nCompareResult)
{
pStart[i] = '\0';
if (pLastPos)
{
Result.push_back(std::string(pLastPos) );
pLastPos = pStart + i + 1;
pLastPos = NULL;
}
}
else
{
if (!pLastPos) // һַĿʼ
{
pLastPos = pStart + i;
}
}
}
if (pLastPos)
{
Result.push_back(std::string(pLastPos) );
pLastPos = NULL;
}
delete []pStart;
return Result;
}
std::string StringTool::getFileName(const std::string& filepath)
{
size_t index1 = filepath.find_last_of('\\');
size_t index2 = filepath.find_last_of('/');
size_t index = (index1 != -1 && index1 > index2 ? index1 : index2);
size_t length = filepath.length();
std::string output = filepath.substr(index + 1, length);
return output;
}
std::string StringTool::getFileName(const std::string& filepath,const std::string& expName)
{
size_t index1 = filepath.find_last_of('\\');
size_t index2 = filepath.find_last_of('/');
size_t index = (index1 != -1 && index1 > index2 ? index1 : index2);
size_t length = filepath.length();
std::string filename = filepath.substr(index + 1, length);
length = filename.length();
std::string output = filename.substr(0, (length-expName.length()-1));
return output;
}
std::string StringTool::getFilePath(const std::string& filename)
{
int index1 = filename.find_last_of('\\');
int index2 = filename.find_last_of('/');
int index = (index1 != -1 && index1 > index2 ? index1 : index2);
std::string filepath = filename.substr(0,index+1);
return filepath;
}
std::string StringTool::toString(bool b)
{
return b ? "true" : "false";
}
void StringTool::fromString(const std::string &str, bool& b)
{
b = str == "true";
}
}
| true |
f34a5aebcce2a9a15303018c9f145722202c2ceb | C++ | YosenChen/CodePractice | /OJLeetCode/TwoSum_sol1_map.cpp | UTF-8 | 1,163 | 2.8125 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> M;
map<int, int>::iterator it;
vector<int> res;
for (int i=0; i<nums.size(); i++) // O(NlogN)
{
M[nums[i]] = i; // std::map::operator[], Complexity: Logarithmic in size.
// how about more than 1 index with the same value?
// You may assume that each input would have exactly one solution.
}
for (int i=0; i<nums.size(); i++) // O(NlogN)
{
if ((it = M.find(target-nums[i])) != M.end()) // std::map::find, Complexity: Logarithmic in size.
{
if (it->second == i) continue; // index1 must be less than index2
// here we can guarantee that i < (it->second), think about why
res.push_back(i+1);
res.push_back(it->second+1);
return res;
}
}
return res;
}
};
/*
Submission Details
16 / 16 test cases passed.
Status: Accepted
Runtime: 36 ms
Submitted: 0 minutes ago
Your runtime beats 8.84% of cpp submissions.
*/ | true |
a7c3db311851308ceddc6343b6ad5cbb417fc58a | C++ | MaraPapMann/pprbf | /src/benchmark_arith_innerproduct/common/innerproduct.cpp | UTF-8 | 2,408 | 2.5625 | 3 | [] | no_license | #include "innerproduct.h"
int32_t test_inner_product_circuit(e_role role, char * address, uint16_t port, seclvl seclvl,uint32_t nvals,
uint32_t bitlen, uint32_t nthreads, e_mt_gen_alg mt_alg,e_sharing sharing, uint32_t r, uint32_t c)
{
// Initialization.
ABYParty * party = new ABYParty(role, address, port, seclvl, bitlen, nthreads, mt_alg);
vector<Sharing*>&sharings = party -> GetSharings();
ArithmeticCircuit *circ = (ArithmeticCircuit*) sharings[sharing] -> GetCircuitBuildRoutine();
share * s_x_vec, * s_y_vec, * res;
uint8_t x, y;
// Total number of elements in matrix.
uint32_t num = r * c;
// Create x / y values array.
uint8_t * xvals = (uint8_t * ) malloc((num) * sizeof(uint8_t));
uint8_t * yvals = (uint8_t * ) malloc((num) * sizeof(uint8_t));
// Fill the matrix according to role.
uint32_t i;
if (role == SERVER)
srand(1000);
else
srand(2000);
for (i = 0; i < num; i++) {
x = rand() % 2;
xvals[i] = x;
}
for (i = 0; i < num; i++) {
y = rand() % 2;
yvals[i] = y;
}
// Put arrays in gate as SIMD shares.
s_x_vec = circ -> PutSharedSIMDINGate(num, xvals, bitlen);
s_y_vec = circ -> PutSharedSIMDINGate(num, yvals, bitlen);
s_x_vec = circ->PutMULGate(s_x_vec, s_y_vec); // Now each nval is a value, need to be transposed so that each wire stands for one value.
s_x_vec = circ->PutSplitterGate(s_x_vec); // Transposed.
// Summing up products for each dot product.
for(int i=0; i< num/c; i++)
{
int idx = i*c;
for(int j=1; j<c; j++)
{
s_x_vec->set_wire_id(idx, circ->PutADDGate(s_x_vec->get_wire_id(idx), s_x_vec->get_wire_id(idx+j))); // Put the summation result into the right pos
}
}
// Setting dot products into the front of the share.
for(int i=0; i<num/c; i++)
{
s_x_vec->set_wire_id(i, s_x_vec->get_wire_id(i*c));
}
// Discard all unnecessary wires except for the dot products.
s_x_vec->set_bitlength(num/c);
res = circ -> PutSharedOUTGate(s_x_vec);
party -> ExecCircuit();
uint32_t out_bitlen, out_nvals, * out_vals;
res -> get_clear_value_vec( & out_vals, & out_bitlen, & out_nvals);
//for (int i=0;i<out_nvals;i++)
// cout<<out_vals[i]<<" ";
//cout<<endl;
free(xvals);
free(yvals);
delete party;
return 0;
} | true |
3512ffd9a798c44cae53af99d0464879eb243d46 | C++ | tanmaygandhi2/apccodes | /Queuearray.cpp | UTF-8 | 473 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
int backind=-1;
int frontind=0;
int qu[1000];
void push(int x)
{
++backind;
qu[backind]=x;
}
void pop()
{
qu[frontind]=0;
++frontind;
}
bool isempty()
{
if(backind<frontind)
return true;
else
return false;
}
int top()
{
return qu[frontind];
}
int main(){
push(5);
cout<<top();
push(1);
cout<<top();
push(18);
pop();
cout<<top();
return 0;
}
| true |
da46cecf62b28021c13eb7b7eee513f9f0a6ca19 | C++ | vvstormhao/MyTests | /CPP/leetCode/No00028/main.cpp | UTF-8 | 2,522 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
return KMP(haystack, needle);
}
void GetNext(string &needle, int *pNext, int arrySize)
{
if (nullptr == pNext || 0 == arrySize)
{
return;
}
int i = 0;
int j = 1;
pNext[0] = -1;
auto nSize = needle.size();
while (j < nSize && i < nSize)
{
if (j == -1 || needle.at(i) == needle.at(j))
{
printf("i is %d, j is %d, needle[i] is %c, needle[j] is %c", i, j, needle.at(i), needle.at(j));
pNext[j] = i;
printf("next %d is %d\n", j, pNext[j]);
++i;
++j;
}
else
{
printf("look for pNest[%d - 1] ", j);
j = pNext[j-1];
printf("j now is %d\n", j);
}
}
}
int KMP(string &haystack, string &needle)
{
const int nHayStackSize = haystack.size();
const int nNeedleSize = needle.size();
int next[nNeedleSize];
GetNext(needle, next, nNeedleSize);
int i = 0, j = 0;
while (i < nHayStackSize && j < nNeedleSize)
{
if (haystack.at(i) == needle.at(j))
{
++i;
++j;
}
else
{
j = next[j];
}
}
return j == nNeedleSize ? j - i : -1 ;
}
int ViolentMatch(string &haystack, string needle){
int nHayStackSize = haystack.size();
int nNeedleSize = needle.size();
if (0 == nHayStackSize || 0 == nNeedleSize || nNeedleSize > nHayStackSize)
{
return -1;
}
int i = 0, j = 0;
while (i < nHayStackSize && j < nNeedleSize)
{
if (haystack.at(i) != needle.at(j))
{
j = 0;
i = i - j + 1;
}
else
{
++i;
++j;
}
}
return j != nNeedleSize ? -1 : i - j;
}
};
int main()
{
Solution s;
string neddle = "abcdabca";
int *pNext = new int(neddle.size());
s.GetNext(neddle, pNext, neddle.size());
for (auto i = 0; i < neddle.size(); ++i)
{
printf("%d ", pNext[i]);
}
printf("\n");
return 1;
} | true |
6e00245a72be353131bf866a21bdc6c5b1c36262 | C++ | edubeckha/Compiladores | /TrabalhoII/implementacao/st.cpp | UTF-8 | 7,643 | 3.109375 | 3 | [] | no_license | /*Ja previamente definido por Laércio Lima Pilla e ampliado para aceitar funcoes e outros tipos de estruturas*/
#include "st.h"
#include "ast.h"
using namespace ST;
extern SymbolTable symtab;
/*Cria uma nova variavle na tabela de simbolos*/
AST::Node * SymbolTable::newVariable ( std::string id, Tipos::Tipo tipoVariavel, AST::Node * next, bool inicializada ) {
AST::Variable * retorno = new AST::Variable ( id, tipoVariavel, next );
if ( checkId ( id ) ) {
yyerror ( "Erro semantico: redefinicao da variavel %s\n", id.c_str() );
retorno->temErro ( true );
}
else {
//std::cout << Tipos::tipoParaString(tipoVariavel, true) << std::endl;
Symbol entry ( tipoVariavel, variable, 0, inicializada );
addSymbol ( id, entry );
}
return retorno; //Creates variable node anyway
}
/*Assign em variaveis*/
AST::Node * SymbolTable::assignVariable ( std::string id ) {
if(!checkId(id)){
if(tabelaOrigem != NULL){
return tabelaOrigem->assignVariable(id);
} else{
yyerror("Variável ainda não definida! %s\n", id.c_str());
}
}
entryList[id].initialized = true;
return new AST::Variable(id, entryList[id].type, NULL); //Creates variable node anyway
}
/*Retorna um nodo do tipo variavel para uso*/
AST::Node * SymbolTable::useVariable ( std::string id ) {
AST::Variable * retorno;
if ( !checkId ( id ) ) {
if ( tabelaOrigem != NULL ) {
return tabelaOrigem->useVariable ( id );
} else {
yyerror ( "Erro semantico: variavel %s ainda nao declarada.\n", id.c_str() );
}
AST::Variable * retErro = new AST::Variable ( id, entryList[id].type, NULL );
retErro->temErro ( true );
return retErro; //forca a criacao de um nodo
}
if ( !entryList[id].initialized && ! ( entryList[id].type == Tipos::complexo ) ) {
yyerror ( "Erro semantico: variavel %s ainda nao inicializada.\n", id.c_str() );
retorno = new AST::Variable ( id, entryList[id].type, NULL );
retorno->temErro ( true );
}
return new AST::Variable ( id, entryList[id].type, NULL ); //Creates variable node anyway
}
/*Retorna o tipo de simbolo, passando um id como parametro*/
Tipos::Tipo SymbolTable::returnType ( std::string id ) {
return entryList[id].type;
}
/*Realiza a coersao de um tipo na tabela de simbolos*/
void SymbolTable::realizaCoercao ( std::string id ) {
if ( !checkId ( id ) ) {
return;
}
entryList[id].type = Tipos::real;
}
/*Cria uma nova funcao na tabela de simbolos*/
AST::Node * SymbolTable::newFunction ( std::string id, Tipos::Tipo tipoVariavel, std::vector<AST::Variable *> parametros ) {
if ( checkId ( id ) ) {
yyerror ( "Erro semantico: função %s já existe.\n", id.c_str() );
} else {
Symbol entry ( tipoVariavel, funcao, parametros, false );
addSymbol ( id, entry );
}
return new AST::Funcao(id, tipoVariavel, parametros);
}
/*Define o corpo da funcao e caso ela nao foi declarada, a mesma eh criada*/
AST::Node * SymbolTable::assignFunction ( std::string id, Tipos::Tipo tipoVariavel, std::vector<AST::Variable *> parametros, AST::Node * body ) {
if ( ! checkId ( id ) ) {
this->newFunction ( id, tipoVariavel, parametros );
}
ST::Symbol tmp = this->getFunction ( id );
for ( int i = 0; i < parametros.size(); i++ ) {
if ( tmp.parametros.at ( i )->tipo != parametros.at ( i )->tipo ) {
std::cout << "Atenção: tipo de parametro incompativel. \n" << std::endl;
}
}
entryList[id].initialized = true;
return new AST::Funcao(id, tipoVariavel, parametros);
}
/*Retorna uma funcao ja declarada para uso*/
AST::Funcao* SymbolTable::useFunction (std::string id ){
if ( !checkId ( id ) ) {
if ( tabelaOrigem != NULL ) {
return tabelaOrigem->useFunction ( id );
} else {
yyerror ( "Erro semantico: funcao %s ainda nao declarada.\n", id.c_str() );
}
}
if(entryList[id].kind != funcao){
yyerror ( "Erro semantico: %s nao representa uma funcao.\n", id.c_str() );
//temErro = true
}
AST::Funcao* func = new AST::Funcao ( id, entryList[id].type, entryList[id].parametros );
if ( !entryList[id].initialized ) {
yyerror ( "Erro semantico: variavel %s ainda nao inicializada.\n", id.c_str() );
//temErro = true
}
return func; //Creates variable node anyway
}
/*Retorna um simbolo da tabela de simbolos*/
Symbol SymbolTable::getSymbol ( std::string id ) {
assert ( checkId ( id ) );
ST::Symbol retorno = this->entryList.at ( id );
return retorno;
}
/*Adiciona uma nova classe na tabela de simbolos e retorna um nodo classe para uso a partir dessa operacao*/
AST::Classe* SymbolTable::newClass(std::string id, ST::SymbolTable* tabelaSimbolosClasse, AST::Block* escopoClasse, AST::ConstrutorClasse* construtor){
if ( checkId ( id ) ) {
yyerror ( "Erro semantico: ja existe uma classe com o nome %s\n", id.c_str() );
}
else {
Symbol entry ( tabelaSimbolosClasse, construtor );
addSymbol ( id, entry );
}
return new AST::Classe ( id, escopoClasse, tabelaSimbolosClasse, construtor );
}
/*Retorna o nodo de uma classe previamente definida*/
AST::Classe* SymbolTable::useClass(std::string id){
if(!checkId(id)){
yyerror("Erro semantico: classe referida nao existe \n");
return new AST::Classe(id, NULL);
}
ST::Symbol classe = this->entryList.at(id);
if(classe.kind != ST::classe){
yyerror("Erro semantico: objeto nao tenta referenciar uma classe \n");
}
AST::Classe* c = new AST::Classe(id, NULL, classe.tabelaClasse, classe.construtor);
return c;
}
/*Cria um novo objeto na tabela de simbolos e retorna um nodo do tipo objeto para uso*/
AST::Objeto* SymbolTable::newObjeto(std::string id, AST::Classe* classePertencente){
if ( checkId ( id ) ) {
yyerror ( "Erro semantico: ja existe um objeto com o nome %s\n", id.c_str() );
}
else {
Symbol entry ( classePertencente );
addSymbol ( id, entry );
}
return new AST::Objeto ( id, classePertencente );
}
/*Retorna um objeto previamente declarado*/
AST::Objeto* SymbolTable::useObjeto(std::string id){
if(!checkId(id)){
yyerror("Erro semantico: objeto nao existe \n");
}
ST::Symbol objeto = this->entryList.at(id);
if(objeto.kind != ST::objeto){
yyerror("Erro semantico: variavel nao e do tipo objeto \n");
std::cout << std::endl;
}
AST::Objeto* c = new AST::Objeto(id, objeto.classePertencente);
return c;
}
/*Cria novo atributo de classe*/
AST::Atributo* SymbolTable::newAtributo(AST::Variable* var, AST::Classe* classePertencente){
AST::Atributo* atri = new AST::Atributo ( var, classePertencente );
if ( checkId ( var->id ) && this->entryList.at(var->id).kind == ST::atributo ) {
yyerror ( "Erro semantico: ja existe um atributo com o nome %s\n", var->id.c_str() );
}
else {
Symbol entry ( var, classePertencente );
addSymbol ( var->id, entry );
}
return atri;
}
/*Assign em atributos de uma classe*/
AST::Atributo* SymbolTable::assignAtributo ( AST::Variable* var, AST::Classe* classePertencente ){
AST::Atributo * retorno = new AST::Atributo ( var, classePertencente );
if ( !checkId ( var->id ) ) {
yyerror ( "Atributo ainda não definida! %s\n", var->id.c_str() );
retorno->temErro ( true );
}
classePertencente->tabelaSimbolos->entryList[var->id].initialized = true;
return retorno; //retorna o nodo de qualquer jeito
}
/*Usa atributo de classe*/
AST::Atributo* SymbolTable::useAtributo(std::string id){
if(!checkId(id)){
yyerror("Erro semantico: atributo nao existe \n");
}
ST::Symbol atributo = this->entryList.at(id);
if(atributo.kind != ST::atributo){
yyerror("Erro semantico: variavel nao e um atributo de classe \n");
std::cout << std::endl;
}
AST::Atributo* a = new AST::Atributo(atributo.var, atributo.classePertencente);
return a;
}
| true |
efae9ebf3641e919ab7d7a6324e87c03d4802e59 | C++ | heikipikker/cve_2013_0640_full_exploit | /deobsfuscation/deobsfuscation/string_decode.cc | UTF-8 | 1,363 | 2.875 | 3 | [] | no_license | #include "string_decode.h"
#include <memory>
StringDecode* StringDecode::Get(){
static StringDecode* r_interface = nullptr;
if(r_interface==nullptr){
static std::tr1::shared_ptr<StringDecode> share;
r_interface = reinterpret_cast<StringDecode*>(&share);
}
return r_interface;
}
bool StringDecode::ReplaceString(const char* func_name,char* src,char* dst){
size_t func_name_len = strlen(func_name);
while(*src){
if(strncmp(src,func_name,func_name_len)==0){
if(*(src + func_name_len)=='('){
++src += func_name_len;
if(*src!='\''){
--src -= func_name_len;
*dst++ = *src++;
continue;
}
++src;
string argv[3];
while(*src!='\''){
argv[0].append(1,*src++);
}
src += 2;
while(*src!=','){
argv[1].append(1,*src++);
}
++src;
while(*src!=')'){
argv[2].append(1,*src++);
}
++src;
string result = Decode(argv[0],atoi(argv[1].c_str()),atoi(argv[2].c_str()));
*dst++ = '"';
strcpy(dst,result.c_str());
dst += result.length();
*dst++ = '"';
}
else{
*dst++ = *src++;
}
}
else{
*dst++ = *src++;
}
}
return true;
}
string StringDecode::Decode(string c,unsigned long d,unsigned long e){
unsigned long idx = d % c.length();
string s = "";
while (s.length() < c.length()){
s += c[idx];
idx = (idx + e) % c.length();
}
return s;
} | true |
92f8be19250587c33a2f7745edfcd828a5a88617 | C++ | Josephnicolay/Fisica_Computacional-1_2020-II | /EjemHeader.cpp | UTF-8 | 449 | 3.53125 | 4 | [] | no_license | /**
* Programa para ilustrar el uso de los headers
* definidos por el usuario
*/
//Incluyo el header de la librería estándar de entrada y salida
#include <iostream>
using namespace std;
// Incluyo el header de la librería de usuario
#include "suma.hpp"
// Programa
int main()
{
// Definimos dos números
int a = 2, b = 100;
// Usamos la función declarada en el header
cout << "a+b= " << SumaEnteros(a, b) << endl;
}
| true |
416cd5dda643ce8932348e9003df291c7a686ea2 | C++ | yuyafu/leetcode | /hello/isPalindInt.cpp | UTF-8 | 416 | 2.953125 | 3 | [] | no_license | //
// isPalindInt.cpp
// hello
//
// Created by 静静 on 2/4/17.
// Copyright © 2017年 jing. All rights reserved.
//
#include <stdio.h>
bool isPalindInt(int x) {
//边界条件
if(x<0 || (x!=0 && x%10 == 0)) return false;
int revInt = 0;
//很好的判断条件
while (x > revInt) {
revInt = revInt*10 + x%10;
x/=x;
}
return (x==revInt) || (x==revInt/10);
}
| true |
6b97fd1b5da60a71e19a06e91a5b369adf6fd05a | C++ | Mbaey/MyDataStruct- | /homework/sort&search/AVL_CSDN_ERROR.cpp | GB18030 | 13,730 | 3.703125 | 4 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
#define LH +1 //
#define EH 0 //ȸ
#define RH -1 //Ҹ
#define EQ(a,b) ((a) == (b))
#define LT(a,b) ((a) < (b))
#define LQ(a,b) ((a) <= (b))
//Ԫ
typedef struct Student
{
int key;
string major;
Student(){}
Student(int k,string s) : key(k), major(s){}
}ElementType;
ostream& operator<<(ostream& out, const Student& s)
{
out<<"("<<s.key<<","<<s.major<<")";
return out;
}
istream& operator>>(istream& in,Student& s)
{
in>>s.key>>s.major;
}
typedef int KeyType;//ؼ
typedef struct AVLNode
{
ElementType data;
int bf;
struct AVLNode* lchild;
struct AVLNode* rchild;
AVLNode(){}
AVLNode(ElementType& e, int ibf=EH, AVLNode* lc=NULL, AVLNode* rc=NULL)
: data(e), bf(ibf), lchild(lc),rchild(rc){}
}AVLNode, *AVL;
/*
*Description: ʼ(ʵԲ)
*/
void initAVL(AVL& t)
{
t = NULL;
}
/*
*Description: ƽ
*/
void destroyAVL(AVL& t)
{
if(t)
{
destroyAVL(t->lchild);
destroyAVL(t->rchild);
delete t;
t = NULL;
}
}
//ǰ
void preOrderTraverse(AVL t)
{
if(t)
{
cout<<t->data<<" ";
preOrderTraverse(t->lchild);
preOrderTraverse(t->rchild);
}
}
//
void inOrderTraverse(AVL t)
{
if(t)
{
inOrderTraverse(t->lchild);
cout<<t->data<<" ";
inOrderTraverse(t->rchild);
}
}
//ǰƽ
void printAVL(AVL t)
{
cout<<"inOrder: "<<endl;
inOrderTraverse(t);
cout<<endl;
cout<<"preOrder: "<<endl;
preOrderTraverse(t);
cout<<endl;
}
/*
Description:
ڸָtָƽеݹزijؼֵkeyԪأ
ҳɹָԪؽָ,ؿָ롣
ҪҲԷһboolֵ
*/
AVLNode* searchAVL(AVL& t, KeyType key)
{
if((t == NULL)||EQ(key,t->data.key))
return t;
else if LT(key,t->data.key) /* м */
return searchAVL(t->lchild,key);
else
return searchAVL(t->rchild,key); /* м */
}
/*
Description:
*pΪĶ֮pָµ㣬ת
֮ǰĸ㡣Ҳ˵˵RR.
*/
void L_Rotate(AVLNode* &p)
{
AVLNode * rc = NULL;
rc = p->rchild; //rcָp
p->rchild = rc->lchild;//rcҽΪp
rc->lchild = p;
p = rc; //pָµĸ
}
/*
Description:
*pΪĶ֮pָµ㣬ת
֮ǰĸ㡣Ҳ˵˵LL.
*/
void R_Rotate(AVLNode* &p)
{
AVLNode * lc = NULL;
lc = p->lchild; //lcָp
p->lchild = lc->rchild; //lcҽΪp
lc->rchild = p;
p = lc; //pָµĸ
}
/*ָtָΪĶƽת
LLתLRת
ƽӵĸıʵܼԼͼͳ
*/
void leftBalance(AVLNode* &t)
{
AVLNode* lc = NULL;
AVLNode* rd = NULL;
lc = t->lchild;
switch(lc->bf)
{
case LH: //LLת
t->bf = EH;
lc->bf = EH;
R_Rotate(t);
break;
case EH: //deleteAVLҪinsertAVLò
t->bf = LH;
lc->bf = RH;
R_Rotate(t);
break;
case RH: //LRת
rd = lc->rchild;
switch(rd->bf)
{
case LH:
t->bf = RH;
lc->bf = EH;
break;
case EH:
t->bf = EH;
lc->bf = EH;
break;
case RH:
t->bf = EH;
lc->bf = LH;
break;
}
rd->bf = EH;
L_Rotate(t->lchild);//дL_Rotate(lc);õò
R_Rotate(t);
break;
}
}
/*ָtָΪĶƽת
RRתRLת
*/
void rightBalance(AVLNode* &t)
{
AVLNode* rc = NULL;
AVLNode *ld = NULL;
rc = t->rchild;
switch(rc->bf)
{
case LH: //RLת
ld = rc->lchild;
switch(ld->bf)
{
case LH:
t->bf = EH;
rc->bf = RH;
break;
case EH:
t->bf = EH;
rc->bf = EH;
break;
case RH:
t->bf = LH;
rc->bf = EH;
break;
}
ld->bf = EH;
R_Rotate(t->rchild);//дR_Rotate(rc);õò
L_Rotate(t);
break;
case EH: //deleteAVLҪinsertAVLò
t->bf = RH;
rc->bf = LH;
L_Rotate(t);
break;
case RH: //RRת
t->bf = EH;
rc->bf = EH;
L_Rotate(t);
break;
}
}
/*
ƽĶtвںeͬؼֵĽ㣬һ
ԪΪe½㣬truefalseʹ
ʧȥƽ⣬ƽתtallerӳt
*/
bool insertAVL(AVL& t, ElementType& e, bool& taller)
{
if(t == NULL)
{
t = new AVLNode(e); //Ԫ
taller = true;
}
else
{
if(EQ(e.key, t->data.key)) //Ѻùؼ֣
{
taller = false;
return false;
}
else if(LT(e.key, t->data.key))//вҲ
{
if(!insertAVL(t->lchild, e, taller))//ʧ
{
return false;
}
if(taller) //ɹ
{
switch(t->bf)
{
case LH: //ԭt
leftBalance(t); //ƽ
taller = false;
break;
case EH: //ԭtȸ
t->bf = LH; //
taller = true; //
break;
case RH: //ԭt
t->bf = EH; //ȸ
taller = false;
break;
}
}
}
else //вҲ
{
if(!insertAVL(t->rchild, e, taller))//ʧ
{
return false;
}
if(taller) //ɹ
{
switch(t->bf)
{
case LH: //ԭt
t->bf = EH;
taller = false;
break;
case EH: //ԭtȸ
t->bf = RH;
taller = true;
break;
case RH: //ԭt
rightBalance(t);//ƽ
taller = false;
break;
}
}
}
}
return true; //ɹ
}
/*
ƽĶtдںeͬؼֵĽ㣬ɾ֮
truefalseɾʹ
ʧȥƽ⣬ƽתshorterӳt䰫
*/
bool deleteAVL(AVL& t, KeyType key, bool& shorter)
{
if(t == NULL) //ڸԪ
{
return false; //ɾʧ
}
else if(EQ(key, t->data.key)) //ҵԪؽ
{
AVLNode* q = NULL;
if(t->lchild == NULL) //Ϊ
{
q = t;
t = t->rchild;
delete q;
shorter = true;
}
else if(t->rchild == NULL) //Ϊ
{
q = t;
t = t->lchild;
delete q;
shorter = true;
}
else //,
{
q = t->lchild;
while(q->rchild)
{
q = q->rchild;
}
t->data = q->data;
deleteAVL(t->lchild, q->data.key, shorter); //еݹɾǰ
}
}
else if(LT(key, t->data.key)) //м
{
if(!deleteAVL(t->lchild, key, shorter))
{
return false;
}
if(shorter)
{
switch(t->bf)
{
case LH:
t->bf = EH;
shorter = true;
break;
case EH:
t->bf = RH;
shorter = false;
break;
case RH:
rightBalance(t); //ƽ
if(t->rchild->bf == EH)//עͼ˼һ
shorter = false;
else
shorter = true;
break;
}
}
}
else //м
{
if(!deleteAVL(t->rchild, key, shorter))
{
return false;
}
if(shorter)
{
switch(t->bf)
{
case LH:
leftBalance(t); //ƽ
if(t->lchild->bf == EH)//עͼ˼һ
shorter = false;
else
shorter = true;
break;
case EH:
t->bf = LH;
shorter = false;
break;
case RH:
t->bf = EH;
shorter = true;
break;
}
}
}
return true;
}
int main(int argc, char *argv[])
{
AVL t ;
initAVL(t);
bool taller = false;
bool shorter = false;
int key;
string major;
ElementType e;
int choice = -1;
bool flag = true;
while(flag)
{
cout<<"--------------------"<<endl;
cout<<"0. print"<<endl
<<"1. insert"<<endl
<<"2. delete"<<endl
<<"3. search"<<endl
<<"4. exit"<<endl
<<"--------------------"<<endl
<<"please input your choice: ";
cin>>choice;
switch(choice)
{
case 0:
printAVL(t);
cout<<endl<<endl;
break;
case 1:
inOrderTraverse(t);
cout<<endl<<"input the elements to be inserted,end by 0:"<<endl;
while(cin>>key && key)
{
major="CS";
ElementType e(key,major);
if(insertAVL(t,e,taller))
{
cout<<"insert element "<<e<<" successfully"<<endl;
}
else
{
cout<<"there already exists an element with key "<< e.key<<endl;
}
}
//while(cin>>e && e.key)
// {
// if(insertAVL(t,e,taller))
// {
// cout<<"insert element "<<e<<" successfully"<<endl;
// }
// else
// {
// cout<<"there already exists an element with key "<< e.key<<endl;
// }
// }
cout<<"after insert: "<<endl;
printAVL(t);
cout<<endl<<endl;
break;
case 2:
inOrderTraverse(t);
cout<<endl<<"input the keys to be deleted,end by 0:"<<endl;
while(cin>>key && key)
{
if(deleteAVL(t,key,shorter))
{
cout<<"delete the element with key "<<key<<" successfully"<<endl;
}
else
{
cout<<"no such an element with key "<<key<<endl;
}
}
cout<<"after delete: "<<endl;
printAVL(t);
cout<<endl<<endl;
break;
case 3:
inOrderTraverse(t);
cout<<endl<<"input the keys to be searched,end by 0:"<<endl;
while(cin>>key && key)
{
if(searchAVL(t,key))
cout<<key<<" is in the tree"<<endl;
else
cout<<key<<" is not in the tree"<<endl;
}
cout<<endl<<endl;
break;
case 4:
flag = false;
break;
default:
cout<<"error! watch and input again!"<<endl<<endl;
}
}
destroyAVL(t);
system("PAUSE");
return EXIT_SUCCESS;
}
// BBTree bst;
// int a[]= { 1,2,3,4,5, 10,9,8,7,6};
// for(auto i : a)
// bst.insert_BBT(i);
//
// bst.delete_BBT(5);
// bst.dispaly();
// cout << endl<< endl;
// bst.delete_BBT(4);
// bst.dispaly();
// cout << endl<< endl;
// bst.delete_BBT(9);
// bst.dispaly();
// cout << endl<< endl;
// bst.delete_BBT(1); | true |
42480a854183b1b4c417fb789a5e5ca7bbcff643 | C++ | andreihu/asio-fsm | /include/afsm/util/fmt.hpp | UTF-8 | 430 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
// thirdparty
#include <fmt/format.h>
// std
#include <system_error>
template <> struct fmt::formatter<std::error_code> {
template <typename ParseContext> constexpr auto parse(ParseContext &ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const std::error_code &ec, FormatContext &ctx) {
return format_to(ctx.out(), "error_code({}): {}", ec.value(), ec.message());
}
}; | true |
c0bff345b6d4df3e460423ecc621f74fec7a5e57 | C++ | Pipi24/OJ | /second_time_111/二叉树/589. N 叉树的前序遍历.cpp | UTF-8 | 748 | 3.328125 | 3 | [] | no_license | /*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> res;
stack<Node*> stk;
if (!root) return res;
stk.push(root);
while (stk.size())
{
auto t = stk.top();
stk.pop();
res.push_back(t->val);
for (int i = t->children.size() - 1; ~i; i -- ) //从最后一个儿子节点往前遍历
stk.push(t->children[i]);
}
return res;
}
};
| true |
60280633c160d9169f0684cef5b8237a740aced4 | C++ | JonnySunny/Courses-Project | /C++ Applications/VotingSystem/Project 1 - Waterfall Voting/src/plurality.h | UTF-8 | 1,127 | 3.09375 | 3 | [] | no_license | /**
* @file plurality.h
*
* @copyright Spring 2018 CSci 5801 Team 10, All rights reserved.
*/
#ifndef SRC_PLURALITY_H_
#define SRC_PLURALITY_H_
// Includes
#include <vector>
#include "./algorithm.h"
// Forward declarations
class Ballot;
class Candidate;
/**************************************************************************/
/**
@brief The plurality method. Assigns ballots to candidates based on highest preference. Winners are the candidates with the highest vote counts.
*/
class Plurality : public Algorithm {
public:
Plurality(std::vector<Ballot> b, std::vector<Candidate> c, int = 0);
~Plurality() {}
/**
@brief Implementation of abstract function.
Main function: runs the plurality algorithm to assign votes to candidates. Sorts candidates by decreasing vote count.
*/
void run();
/**
@brief Implementation of abstract function.
Print the winners of the election.
*/
void printResults();
private:
/**
@brief Sorts candidates from most votes to least votes.
*/
void sortCandidates();
};
#endif // SRC_PLURALITY_H_
| true |
19477eac06cff8d2a77a41a218f85af8f673e888 | C++ | BruceWang1030/Tetris | /include/blocks/Block.h | UTF-8 | 1,482 | 3.25 | 3 | [] | no_license | #ifndef _BLOCK_H_
#define _BLOCK_H_
#include <tuple>
#include <vector>
#include <memory>
class Block : public std::enable_shared_from_this<Block>
{
protected:
//the coordinates_ records the bottom left corner of the block (might be empty block)
std::tuple<int, int> coordinates_;
//4 rotationTypes: (indexed by curentRotation)
std::vector<std::vector<std::vector<char>>> rotationTypes_;
//0: initial; 1: right 90 degree; 2: 180 degree; 3: left 90 degree
int currentRotation_;
//To-do need to add ways to modify the creationLevel_ from level side
int creationLevel_;
char blockChar_;
//This function sets the currentRotaion_ to 0
virtual void initializeRotationTypes();
public:
virtual ~Block(){};
// Rotations
void rotateClockwise();
void rotateCounterClockwise();
//get the letter denotated for type of block: I, O, L, J ......
// virtual char getBlockChar() = 0;
// GETTERS
std::tuple<int, int> getCoordinates() const;
std::vector<std::vector<char>> getCurrRotation();
std::vector<std::vector<char>> getClockwiseRotation();
std::vector<std::vector<char>> getCounterClockwiseRotation();
int getCreationLevel() const;
char getBlockChar() const;
int getCurrRotationNumber() const;
// SETTERS
void setCoordinates(std::tuple<int, int>);
void setCharToHint();
void setRotation(int);
friend std::ostream &operator<<(std::ostream &, Block &);
};
#endif
| true |
6e9c8c6247adf1b0d80476dd500ac0802ddd6965 | C++ | LKinahan/SpaceInvaders | /CInvader.h | UTF-8 | 498 | 2.828125 | 3 | [] | no_license | #pragma once
#include "CGameObject.h"
/**
*
* @brief This is the game invader class
*
* The game invader class with its own unique constructor to set the size, sprite, and lives.
*
* @author
*
*/
class CInvader:
public CGameObject
{
public:
/** @brief The class constructor
*
* @details This method will take a velocity in and create a new invader
*
* @param pos The starting position for the new invader
* @return Nothing to return
*/
CInvader(cv::Point2f);
};
| true |
0ad45e7b7288055e2964390929a3502c21a192cd | C++ | chistyakova-ann/MyWork | /src/search_char.cpp | UTF-8 | 317 | 2.671875 | 3 | [] | no_license | #include "../include/search_char.h"
int search_char(char32_t c, const char32_t* array){
char32_t ch;
int curr_pos = 0;
for(char32_t* p = const_cast<char32_t*>(array); (ch = *p++); ){
if(ch == c){
return curr_pos;
}
curr_pos++;
}
return THERE_IS_NO_CHAR;
}
| true |
761f13b57d1e716fc70dfa6a6ce7fa672fb86bbb | C++ | JaceRiehl/Council-Of-Jerrys | /src/Level.cpp | UTF-8 | 1,397 | 2.859375 | 3 | [] | no_license | #include "Level.h"
Level::Level(string n, PlayableCharacter* pc, map<string, Room*> levelRooms, string openingText) : key(n), jerry(pc), rooms(levelRooms), openingMessage(openingText)
{
nextRoom = "town";
}
Level::Level(string levelKey, string startingRoom, map<string, Room*> levelRooms) : key(levelKey), nextRoom(startingRoom), rooms(levelRooms)
{
#ifdef RELEASE
ioInfo = new IOInfo();
#else
ioInfo = new IOInfo("./data/levelTestOutput.txt", "");
#endif // RELEASE
}
string Level::run(PlayableCharacter* player)
{
state = RUNNING;
Window window;
window.display(openingMessage, ioInfo->getOutputStream());
while(true)
{
if(rooms.find(nextRoom) == rooms.end())
break;
Room* currentRoom = rooms[nextRoom];
XMLSaveData::Data.room = nextRoom.c_str();
nextRoom = currentRoom->run(player);
}
return nextRoom;
}
void Level::setStartingRoom(string room)
{
if(isAllAscii(room))
{
nextRoom = room;
return;
}
cerr << "INVALID STRING!" << endl;
}
bool Level::isNotAscii(int c)
{
return (c < 0) || (c >= 128);
}
bool Level::isAllAscii(string s)
{
for(const auto& c : s)
{
if(isNotAscii(c))
return false;
}
return true;
}
int Level::returnState()
{
return state;
}
const string Level::getKey() const
{
return key;
}
| true |
015eef71b38e289d8084c57fcf6f0a3e10d6bc1b | C++ | GreateCode/curlion | /src/connection_manager.cpp | UTF-8 | 8,770 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "connection_manager.h"
#include "connection.h"
#include "log.h"
#include "socket_factory.h"
#include "socket_watcher.h"
#include "timer.h"
namespace curlion {
static inline LoggerProxy WriteManagerLog(void* manager_idenditifier) {
return Log() << "Manager(" << manager_idenditifier << "): ";
}
ConnectionManager::ConnectionManager(const std::shared_ptr<SocketFactory>& socket_factory,
const std::shared_ptr<SocketWatcher>& socket_watcher,
const std::shared_ptr<Timer>& timer) :
socket_factory_(socket_factory),
socket_watcher_(socket_watcher),
timer_(timer) {
multi_handle_ = curl_multi_init();
curl_multi_setopt(multi_handle_, CURLMOPT_TIMERFUNCTION, CurlTimerCallback);
curl_multi_setopt(multi_handle_, CURLMOPT_TIMERDATA, this);
curl_multi_setopt(multi_handle_, CURLMOPT_SOCKETFUNCTION, CurlSocketCallback);
curl_multi_setopt(multi_handle_, CURLMOPT_SOCKETDATA, this);
}
ConnectionManager::~ConnectionManager() {
}
void ConnectionManager::StartConnection(const std::shared_ptr<Connection>& connection) {
CURL* easy_handle = connection->GetHandle();
auto iterator = running_connections_.find(easy_handle);
if (iterator != running_connections_.end()) {
WriteManagerLog(this) << "Try to start an already running connection(" << connection.get() << "). Ignored.";
return;
}
WriteManagerLog(this) << "Start a connection(" << connection.get() << ").";
if (socket_factory_ != nullptr) {
curl_easy_setopt(easy_handle, CURLOPT_OPENSOCKETFUNCTION, CurlOpenSocketCallback);
curl_easy_setopt(easy_handle, CURLOPT_OPENSOCKETDATA, this);
curl_easy_setopt(easy_handle, CURLOPT_CLOSESOCKETFUNCTION, CurlCloseSocketCallback);
curl_easy_setopt(easy_handle, CURLOPT_CLOSESOCKETDATA, this);
}
else {
curl_easy_setopt(easy_handle, CURLOPT_OPENSOCKETFUNCTION, nullptr);
curl_easy_setopt(easy_handle, CURLOPT_CLOSESOCKETFUNCTION, nullptr);
}
connection->WillStart();
running_connections_.insert(std::make_pair(easy_handle, connection));
curl_multi_add_handle(multi_handle_, easy_handle);
}
void ConnectionManager::AbortConnection(const std::shared_ptr<Connection>& connection) {
CURL* easy_handle = connection->GetHandle();
auto iterator = running_connections_.find(easy_handle);
if (iterator == running_connections_.end()) {
WriteManagerLog(this) << "Try to abort a not running connection(" << easy_handle << "). Ignored.";
return;
}
WriteManagerLog(this) << "Abort a connection(" << easy_handle << ").";
running_connections_.erase(easy_handle);
curl_multi_remove_handle(multi_handle_, easy_handle);
}
curl_socket_t ConnectionManager::OpenSocket(curlsocktype socket_type, curl_sockaddr* address) {
WriteManagerLog(this) << "Open socket for "
<< "type " << socket_type << "; "
<< "address family " << address->family << ", "
<< "socket type " << address->socktype << ", "
<< "protocol " << address->protocol << '.';
curl_socket_t socket = socket_factory_->Open(socket_type, address);
if (socket != CURL_SOCKET_BAD) {
WriteManagerLog(this) << "Socket(" << socket << ") is opened.";
}
else {
WriteManagerLog(this) << "Open socket failed.";
}
return socket;
}
bool ConnectionManager::CloseSocket(curl_socket_t socket) {
WriteManagerLog(this) << "Close socket(" << socket << ").";
bool is_succeeded = socket_factory_->Close(socket);
if (is_succeeded) {
WriteManagerLog(this) << "Socket(" << socket << ") is closed.";
}
else {
WriteManagerLog(this) << "Close socket(" << socket << ") failed.";
}
return is_succeeded;
}
void ConnectionManager::SetTimer(long timeout_ms) {
WriteManagerLog(this) << "Set timer for " << timeout_ms << " milliseconds.";
timer_->Stop();
if (timeout_ms >= 0) {
timer_->Start(timeout_ms, std::bind(&ConnectionManager::TimerTriggered, this));
}
}
void ConnectionManager::TimerTriggered() {
WriteManagerLog(this) << "Timer triggered.";
int running_count = 0;
curl_multi_socket_action(multi_handle_, CURL_SOCKET_TIMEOUT, 0, &running_count);
CheckFinishedConnections();
}
void ConnectionManager::WatchSocket(curl_socket_t socket, int action, void* socket_pointer) {
static void* const kIsNotNewSocketTag = reinterpret_cast<void*>(1);
//Ensure that StopWatching won't be called with a new socket that never watched.
if (socket_pointer == kIsNotNewSocketTag) {
WriteManagerLog(this) << "Socket(" << socket << ") is changed. Stop watching it.";
socket_watcher_->StopWatching(socket);
}
else {
WriteManagerLog(this) << "Socket(" << socket << ") is added.";
curl_multi_assign(multi_handle_, socket, kIsNotNewSocketTag);
}
if (action == CURL_POLL_REMOVE) {
WriteManagerLog(this) << "Socket(" << socket << ") is removed.";
return;
}
SocketWatcher::Event event = SocketWatcher::Event::Read;
switch (action) {
case CURL_POLL_IN:
break;
case CURL_POLL_OUT:
event = SocketWatcher::Event::Write;
break;
case CURL_POLL_INOUT:
event = SocketWatcher::Event::ReadWrite;
break;
}
WriteManagerLog(this) << "Watch socket(" << socket << ") for "
<< (event == SocketWatcher::Event::Read ? "read" :
(event == SocketWatcher::Event::Write ? "write" : "read/write"))
<< " event.";
socket_watcher_->Watch(socket, event, std::bind(&ConnectionManager::SocketEventTriggered,
this,
std::placeholders::_1,
std::placeholders::_2));
}
void ConnectionManager::SocketEventTriggered(curl_socket_t socket, bool can_write) {
WriteManagerLog(this) << "Socket(" << socket << ") " << (can_write ? "write" : "read") << " event triggered.";
int action = can_write ? CURL_CSELECT_OUT : CURL_CSELECT_IN;
int running_count = 0;
curl_multi_socket_action(multi_handle_, socket, action, &running_count);
CheckFinishedConnections();
}
void ConnectionManager::CheckFinishedConnections() {
while (true) {
int msg_count = 0;
CURLMsg* msg = curl_multi_info_read(multi_handle_, &msg_count);
if (msg == nullptr) {
break;
}
if (msg->msg == CURLMSG_DONE) {
curl_multi_remove_handle(multi_handle_, msg->easy_handle);
auto iterator = running_connections_.find(msg->easy_handle);
if (iterator != running_connections_.end()) {
auto connection = iterator->second;
running_connections_.erase(iterator);
WriteManagerLog(this)
<< "Connection(" << connection.get() << ") is finished with result " << msg->data.result << '.';
connection->DidFinish(msg->data.result);
}
}
}
}
curl_socket_t ConnectionManager::CurlOpenSocketCallback(void* clientp,
curlsocktype socket_type,
curl_sockaddr* address) {
ConnectionManager* manager = static_cast<ConnectionManager*>(clientp);
return manager->OpenSocket(socket_type, address);
}
int ConnectionManager::CurlCloseSocketCallback(void* clientp, curl_socket_t socket) {
ConnectionManager* manager = static_cast<ConnectionManager*>(clientp);
return manager->CloseSocket(socket);
}
int ConnectionManager::CurlTimerCallback(CURLM* multi_handle, long timeout_ms, void* user_pointer) {
ConnectionManager* manager = static_cast<ConnectionManager*>(user_pointer);
manager->SetTimer(timeout_ms);
return 0;
}
int ConnectionManager::CurlSocketCallback(CURL* easy_handle,
curl_socket_t socket,
int action,
void* user_pointer,
void* socket_pointer) {
ConnectionManager* manager = static_cast<ConnectionManager*>(user_pointer);
manager->WatchSocket(socket, action, socket_pointer);
return 0;
}
} | true |
f6b6a5c56a71087e49f77bcfbf665c1082a43f41 | C++ | mockingbird225/TagCloud | /Partition.cpp | UTF-8 | 324 | 2.703125 | 3 | [] | no_license | #include "Partition.hpp"
void Partition::addRect(string word, double xLeft, double yLeft, double l, double b, double frequency) {
rectPartitions.push_back(new Rectangle(xLeft, yLeft, l, b, word, frequency));
}
void Partition::print() {
for(int i = 0; i < rectPartitions.size(); i++) {
rectPartitions[i]->print();
}
}
| true |
833e055e4f5e34e32879f85350c1f7652f49474a | C++ | Datos2Sem22018/Proyecto3.2 | /node.h | UTF-8 | 400 | 3.59375 | 4 | [] | no_license | #ifndef NODE_H
#define NODE_H
#include <iostream>
/**
* Clase Nodo, utilizada para almacenar
* @tparam T
*/
template <class T>
class Node {
public:
T data;
Node* next;
Node<T> (T var);
};
/**
* Constructor de la clase Nodo
* @tparam T
* @param var : valor a almacenar
*/
template <class T>
Node<T>::Node(T var) {
this->data = var;
this->next = nullptr;
}
#endif // NODE_H
| true |
2e1f13ad881619629fa9eed7c712ead79ac63e93 | C++ | fuadsaud/BlockSoccer | /Point.cpp | UTF-8 | 381 | 3.234375 | 3 | [] | no_license | #include "Point.h"
Point::Point() {
x = y = z = 0;
}
Point::Point(float x, float y, float z) {
Point::x = x;
Point::y = y;
Point::z = z;
}
Point* Point::operator+(const Point* p) const {
Point self = *this;
Point* result = new Point(
p->x + self.x,
p->y + self.y,
p->z + self.z);
return result;
}
| true |
ddfc2f8803f64204b6b1505426ccad091480645c | C++ | GDC-CEG/Galaxy-Shooter | /HeroShip.h | UTF-8 | 2,417 | 3.8125 | 4 | [] | no_license | #include"SFML\Graphics.hpp"
#include"Bullets.h"
const int VEL=10;//Velocity with which ship will move i.e. 10 pixels
class HeroShip
{
public:
sf::IntRect box; // a box to store the dimensions i.e.x,y,width and height of ship
sf::RectangleShape rect; //rectangle shape that is displayed
int xVel,yVel; // variables to store horizontal and vertical velocity
Bullets *myBullets[20]; // array of bullet ptr objects; 20 Bullets to fire
int num_of_bullets; // to keep track of how many bullets have been fired
HeroShip(); // constructor
void handleEvents(); // to get input from user
void update(); // to update values
void display(sf::RenderWindow *window); //to display values
void shoot(); //if user wants to shoot a bullet
};
HeroShip::HeroShip()
{
box.left=200; // ship’s initial position is (200,500) on screen
box.top=500;
box.height=20; // height and weight of ship is 20x20
box.width=20;
rect.setSize(sf::Vector2f(box.width,box.height)); //dimension of rect to display
rect.setFillColor(sf::Color::Red); // color of the ship
xVel=0; // initially x and y velocity are 0
yVel=0;
num_of_bullets=0; // initially bullets fired is 0
}
void HeroShip::handleEvents()
{
//top or down
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
yVel=-VEL;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
yVel=VEL;
else
yVel=0;
//left or right
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
xVel=-VEL;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
xVel=VEL;
else
xVel=0;
// if Z key is pressed shoot func is called which fires a bullet
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
shoot();
}
void HeroShip::update()
{
//update values
box.left+=xVel;
box.top+=yVel;
//update the position of fired bullets
for(int i=0;i<num_of_bullets;i++)
myBullets[i]->update();
}
void HeroShip::display(sf::RenderWindow *window)
{
//display the fired bullets
for(int i=0;i<num_of_bullets;i++)
myBullets[i]->display(window);
//set the x,y values of the rectangle i.e. ship to be displayed
rect.setPosition(box.left,box.top);
window->draw(rect); // draw on the window
}
void HeroShip::shoot()
{
if(num_of_bullets<20)
{
// creates a new bullet
myBullets[num_of_bullets]=new Bullets(box.left+box.width/2,box.top-10);
num_of_bullets++; // increment the bullet counter
}
}
| true |
d4fb1d75fa28640517c789d7d5f1bb55797719a3 | C++ | patrick1964/Data-Structures-Work | /in class 1.cpp | UTF-8 | 1,988 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
struct pasInfo
{
string name;
string tnum;
int ffnum;
double price;
int fnum;
string seat;
string date;
};
static vector<pasInfo> pas;
void enterPas(){
pasInfo temp;
string t;
cout<<"enter Passenger Name then press enter: ";
cin.ignore();
getline(cin, temp.name);
cout<<"enter Ticket Number in format [#######] then press enter: ";
getline(cin, temp.tnum);
cout<<"enter Frequent Flyer Number (valid alphanumeric or 0) then press enter: ";
cin>>temp.ffnum;
cout<<"enter Ticket Price in format [##.##] then press enter: ";
cin>>temp.price;
cout<<"enter flight Number in format [####] then press enter: ";
cin>>temp.fnum;
cout<<"enter the seat location then press enter: ";
cin.ignore();
getline(cin, temp.seat);
cout<<"enter flight date then press enter: ";
getline(cin, temp.date);
pas.push_back(temp);
}
void searchPas(){
if(!pas.empty()){
string temp;
cout<<"enter the ticket number: ";
cin.ignore();
getline(cin, temp);
cout<<temp<<endl;
for(int i=0; i< pas.size();i++){
if(pas[i].tnum.compare(temp)==0){
cout<<"name: "<<pas[i].name<<endl;
cout<<"ticket number: "<<pas[i].tnum<<endl;
if(pas[i].ffnum!=0)
cout<<"frequent flyer number: "<<pas[i].ffnum<<endl;
cout<<"ticket price: $"<<pas[i].price<<endl;
cout<<"flight number: "<<pas[i].fnum<<endl;
cout<<"seat location: "<<pas[i].seat<<endl;
cout<<"flight date: "<<pas[i].date<<endl;
}
}
}else
cout<<"no passangers entered"<<endl;
}
int main(){
int task=1;
while(task!=0){
cout<<"what would you like to do now? [to enter a passanger enter 1 to search for a passanger enter 2 to exit enter 0: ";
cin>>task;
if(task==1)
enterPas();
if(task==2)
searchPas();
if(task==0)
cout<<"Initilizing hack..."<<endl<<endl<<endl<<"na, just kidding professor. have a good day!";
}
}
| true |
0c1e8057f3b2495fe69bdd7afb7f98a7155d4074 | C++ | MustBeDeletedOne/ass | /compiler/include/emit.hpp | UTF-8 | 400 | 2.5625 | 3 | [] | no_license | #ifndef __ASS_EMIT_HPP__
#define __ASS_EMIT_HPP__
#include <string>
namespace ass {
class emitter {
public:
emitter(std::string filename);
void emit(std::string code);
void emit_line(std::string code);
void header_line(std::string code);
void write_file();
private:
std::string filename, header, code;
};
}
#endif // __ASS_EMIT_HPP__ | true |
a5c86d3a3c2e923f80b5e7a44b6a072017984175 | C++ | R-Sandor/AminoAcidMatcher | /solutionPts.h | UTF-8 | 403 | 3.078125 | 3 | [] | no_license | using namespace std;
class SolutionPts
{
public:
SolutionPts(){}
~SolutionPts(){}
void setvals(int i, double a, double b, double c){id = i; x = a; y=b; z=c;}
int getid(){return id;}
double getx(){return x;}
double gety(){return y;}
void display(){cout<<"#"<<id<<" at ("<<x<<", "<<y<<", "<< z<< ")"<<endl;}
private:
int id;
double x;
double y;
double z;
};
| true |
550f28e5b702e9b13f3ddb75e61d30a7c42f1320 | C++ | chriswpark00/C_Algorithm | /day01/pointer_01.cpp | UHC | 439 | 3.6875 | 4 | [] | no_license | #include <stdio.h>
void swap(int *x, int *y); // a, b
int main(){
int a = 10;
int b = 20;
printf("%d, %d\n", a, b);
swap(&a, &b);
printf("%d, %d\n", a, b);
return 0;
}
// ### ϳ??
// main() Լ
// ܺ Լ ȭ ٶ
void swap(int *a, int *b){
int pointer = *a;
*a = *b;
*b = pointer;
}
| true |
a74c0f11902171467ee9662f357a01f7f2b71f80 | C++ | koosaga/olympiad | /ICPC/CERC/cerc2018_d.cpp | UTF-8 | 1,227 | 2.78125 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #include <bits/stdc++.h>
using namespace std;
using lint = long long;
using real_t = long double;
using pi = pair<int, int>;
real_t Tf, Vf, Hf;
real_t Td, Vd, Hd;
real_t joobjoob(){
real_t frisbee_run = sqrt(2 * Hf);
real_t distance = frisbee_run * Vf;
return max(frisbee_run + Tf, distance / Vd + Td) + distance / Vd;
}
bool trial(real_t x){
real_t alloc_for_dog = min(x - Td, sqrt(2.0 * Hd / 3.0));
real_t can_run = sqrt(6 * Hd) * alloc_for_dog - 1.5 * (alloc_for_dog * alloc_for_dog);
real_t alloc_for_frisbee = min(x - Tf, sqrt(2 * Hf));
real_t frisbee_pos = Hf - 0.5 * alloc_for_frisbee * alloc_for_frisbee;
return can_run >= frisbee_pos;
}
real_t get_pos(real_t x){
return (x - Tf) * Vf;
}
int main(){
cin >> Tf >> Vf >> Hf;
cin >> Td >> Vd >> Hd;
if((int)round(Vf) >= (int)round(Vd)){
printf("%.10Lf\n", joobjoob());
return 0;
}
real_t minimum_meet = (Tf * Vf - Td * Vd) / (Vf - Vd);
real_t maximum_meet = sqrt(2 * Hf) + Tf;
if(minimum_meet > maximum_meet){
printf("%.10Lf\n", joobjoob());
return 0;
}
real_t s = minimum_meet;
real_t e = maximum_meet;
for(int i=0; i<100; i++){
real_t m = (s + e) / 2;
if(trial(m)) e = m;
else s = m;
}
printf("%.10Lf\n", s + get_pos(s) / Vd);
}
| true |
68de386cf8b491db262ec6779f923d1d0533d1c5 | C++ | jimmyshuyulee/duke-ece751 | /025_expr_eval2/expr.h | UTF-8 | 1,902 | 3.71875 | 4 | [] | no_license | #include <sstream>
#include <string>
class Expression {
public:
Expression() {}
virtual std::string toString() const = 0;
virtual ~Expression() {}
};
class NumExpression : public Expression {
protected:
long number;
public:
NumExpression(long num) : number(num) {}
std::string toString() const {
std::stringstream ss;
ss << number;
return ss.str();
}
virtual ~NumExpression() {}
};
class OperationExpression : public Expression {
protected:
Expression * lOperand;
Expression * rOperand;
std::string oper;
OperationExpression(Expression * lhs, Expression * rhs, std::string op) :
lOperand(lhs),
rOperand(rhs),
oper(op) {}
public:
virtual std::string toString() const {
std::stringstream ss;
ss << "(" << lOperand->toString() << " " << oper << " " << rOperand->toString()
<< ")";
return ss.str();
}
virtual ~OperationExpression() {
delete lOperand;
delete rOperand;
}
};
class PlusExpression : public OperationExpression {
public:
PlusExpression(Expression * lhs, Expression * rhs) :
OperationExpression(lhs, rhs, "+") {}
// std::string toString() const {}
virtual ~PlusExpression() {}
};
class MinusExpression : public OperationExpression {
public:
MinusExpression(Expression * lhs, Expression * rhs) :
OperationExpression(lhs, rhs, "-") {}
// std::string toString() const {}
virtual ~MinusExpression() {}
};
class TimesExpression : public OperationExpression {
public:
TimesExpression(Expression * lhs, Expression * rhs) :
OperationExpression(lhs, rhs, "*") {}
// std::string toString() const {}
virtual ~TimesExpression() {}
};
class DivExpression : public OperationExpression {
public:
DivExpression(Expression * lhs, Expression * rhs) :
OperationExpression(lhs, rhs, "/") {}
// std::string toString() const {}
virtual ~DivExpression() {}
};
| true |
7f63da3b7c06c4623e38b0f3142efdbc5795bf50 | C++ | qseft0402/2019_POSD | /資料/R1/HW7/fs/src/null_iterator.h | UTF-8 | 452 | 2.90625 | 3 | [] | no_license | #ifndef NULL_ITERATOR
#define NULL_ITERATOR
#include "node_iterator.h"
class NullIterator:public NodeIterator
{
public:
NullIterator(Node* node): _node(node) {}
void first()
{
//definition by yourself
}
Node* currentItem()
{
return this->_node;
}
void next()
{
//
}
bool isDone()
{
return true;
}
private:
Node* _node;
};
#endif
| true |
e86825cee57ce3767b16828b3b4bc9f7029557ef | C++ | Khairul-Anam-Mubin/UVa-Solutions | /10038 - Jolly Jumpers.cpp | UTF-8 | 1,012 | 2.53125 | 3 | [] | no_license | /***
** Author: Khairul Anam Mubin
** Bangladesh University of Business and Technology,
** Dept. of CSE.
***/
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long i,j,temp,n,a[3000],sum,sum1;
while(scanf("%lld",&n)==1)
{
sum=0;
sum1=0;
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
}
for(i=1;i<n;i++){
a[i]=fabs(a[i]-a[i+1]);
}
for(j=1;j<n-1;j++){
for(i=1;i<=n-1-j;i++){
if(a[i]>a[i+1]){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
for(i=1;i<n;i++){
sum+=i;
}
for(i=1;i<n;i++){
sum1+=a[i];
}
if(a[1]==1 && a[n-1]==n-1 && sum==sum1){
printf("Jolly\n");
}
else if(n==1){
printf("Jolly\n");
}
else{
printf("Not jolly\n");
}
}
return 0;
}
| true |
922ad879db8c61a9c9581b5a73862995d48b2c52 | C++ | ailyanlu1/c100 | /P3/BitInputStream.cpp | UTF-8 | 430 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
* P3
* BitInputStream.cpp
* Implementation of BitInputStream class
*
* Author: Jay Dey cs100vaj
* Author: Joshua Yuen cs100vbc
*/
#include "BitInputStream.hpp"
void BitInputStream::fill()
{
buf = in.get();
nbits = 0;
}
int BitInputStream::readBit()
{
// all bits in buffer are read
if( nbits == 8 )
fill();
// get bit at appropriate location
int bit = 1 & (buf >> (7 - nbits));
nbits++;
return bit;
}
| true |
9e665a82255eab9544ccccb91419e137ced706f3 | C++ | jjzhang166/SWAG | /src/vertical_slider.cpp | UTF-8 | 1,477 | 2.640625 | 3 | [] | no_license | #include "vertical_slider.h"
#include "event_queue.h"
#include <iostream>
Vertical_slider::Vertical_slider()
{
Enable_fixed_width();
}
Widget* Vertical_slider::Clone() const
{
return new Vertical_slider(*this);
}
void Vertical_slider::Set_pane_position(float p)
{
float max_y = Get_size().y-pane_size;
pane_position = p<0?0:p>max_y?max_y:p;
pane_reference = pane_position/max_y;
Push_event(Event(this, "moved"));
}
void Vertical_slider::Set_pane_fraction(float p)
{
float max_y = Get_size().y-pane_size;
float pp = p*max_y;
pane_position = pp<0?0:pp>max_y?max_y:pp;
pane_reference = p<0?0:p>1?1:p;
Push_event(Event(this, "moved"));
}
void Vertical_slider::Handle_event(const ALLEGRO_EVENT& event)
{
Vector2 p = Get_position();
Vector2 s = Get_size();
if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
{
float pane_y_diff = event.mouse.y-(p.y + pane_position);
if(event.mouse.x >= p.x && event.mouse.x <= p.x + s.x
&& pane_y_diff >= 0 && pane_y_diff < pane_size)
{
holding_pane = pane_y_diff;
}
}
if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
{
holding_pane = -1;
}
if(event.type == ALLEGRO_EVENT_MOUSE_AXES)
{
if(holding_pane != -1 && event.mouse.dy)
{
float new_y = (event.mouse.y - p.y) - holding_pane;
float max_y = Get_size().y-pane_size;
Set_pane_fraction(new_y/max_y);
}
if(event.mouse.dz)
{
float p = Get_pane_fraction();
p -= event.mouse.dz/scroll_units;
Set_pane_fraction(p);
}
}
}
| true |
fae2aaa77190242722ca1a1582540831baaffa8e | C++ | Pranit5895/DATA-STRUCTURES-CPP | /Dynamic-Programming/Floyd-Warshall.cpp | UTF-8 | 1,390 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
void floyds_algorithm(int parent_array[][10], int no_of_vertices)
{
int i, j, k;
for (k = 0; k < no_of_vertices; k++)
{
for (i = 0; i < no_of_vertices; i++)
{
for (j = 0; j < no_of_vertices; j++)
{
if ((parent_array[i][k] * parent_array[k][j] != 0) && (i != j))
{
if ((parent_array[i][k] + parent_array[k][j] < parent_array[i][j]) || (parent_array[i][j] == 0))
{
parent_array[i][j] = parent_array[i][k] + parent_array[k][j];
}
}
}
}
}
for (i = 0; i < no_of_vertices; i++)
{
cout << "\nThe Minimum with cost for node :" << i << endl;
for (j = 0; j < no_of_vertices; j++)
{
cout << parent_array[i][j] << "\t";
}
}
}
int main()
{
int parent_array[10][10], no_of_vertices;
cout << "Enter the number of vertices : ";
cin >> no_of_vertices;
cout << "Input the values for adjacency matrix of order "<< no_of_vertices<<" x "<< no_of_vertices<<" : "<<endl;
for (int i = 0; i < no_of_vertices; i++)
{
for (int j = 0; j < no_of_vertices; j++)
{
cin >> parent_array[i][j];
}
}
floyds_algorithm(parent_array, no_of_vertices);
} | true |
18e71155be973885734ddaded4ffc989b3d2b7b0 | C++ | yamikumo-DSD/my_game_project_unified | /source/destroy_enemy_rate.cpp | UTF-8 | 2,983 | 2.625 | 3 | [] | no_license | //destroy_enemy_rate.cpp
#include "destroy_enemy_rate.h"
#include "decl_static_image_handler.h"
#include "image_pool.h"
#include <type_traits>
#include "lock_weight_to_rate.h"
#include "mathematics.h"
#include "print_digit.h"
#include <boost/lexical_cast.hpp>
#include "debug_value.h"
#include <boost/format.hpp>
#ifndef DER
#define DER DestroyEnemyRate::
#endif
namespace MyGameProject
{
struct DER Impl
{
STATIC_IMAGE_HANDLER(_period_img)
STATIC_IMAGE_HANDLER(_0_img)
STATIC_IMAGE_HANDLER(_1_img)
STATIC_IMAGE_HANDLER(_2_img)
STATIC_IMAGE_HANDLER(_3_img)
STATIC_IMAGE_HANDLER(_4_img)
STATIC_IMAGE_HANDLER(_5_img)
STATIC_IMAGE_HANDLER(_6_img)
STATIC_IMAGE_HANDLER(_7_img)
STATIC_IMAGE_HANDLER(_8_img)
STATIC_IMAGE_HANDLER(_9_img)
std::string rate_text;
Point2D pos;
int count{0};
int pal{255};
bool is_enable{true};
Impl(float _rate, Point2D _pos) noexcept
//:rate_text(boost::lexical_cast<std::string>(_rate)),
:rate_text(boost::str(boost::format("%.1f") % _rate)),
pos(_pos)
{}
};
DER DestroyEnemyRate(int _x, int _y, float _rate) noexcept
:pimpl(std::make_unique<Impl>(_rate, Point2D(static_cast<Real>(_x), static_cast<Real>(_y))))
{
}
DER ~DestroyEnemyRate(void) noexcept = default;
#ifndef ALIASES
#define ALIASES \
auto& count{pimpl->count}; \
auto& pos{pimpl->pos};
#endif
void DER draw(void) const noexcept
{
ALIASES;
if (count > 0)
{
for (int i = 0; i != 3; ++i)
{
try
{
print_digit
(
gp::level(28), static_cast<int>(pos.x() + 30 * i), static_cast<int>(pos.y()), 1.5, pimpl->pal, pimpl->rate_text[i],
Impl::_period_img(),
Impl::_0_img(), Impl::_1_img(), Impl::_2_img(), Impl::_3_img(), Impl::_4_img(),
Impl::_5_img(), Impl::_6_img(), Impl::_7_img(), Impl::_8_img(), Impl::_9_img()
);
}
catch (Unprintable)
{
}
}
}
}
void DER update(void) noexcept
{
ALIASES;
pos += Point2D(1, -1);
pimpl->pal -= 10;
if (count == 20) { pimpl->is_enable = false; }
++count;
}
bool DER get_flag(void) const noexcept { return pimpl->is_enable; }
template<typename String>
auto load_digit(String&& _path) noexcept
{
ImagePool::add(_path);
return ImagePool::get(std::forward<String>(_path));
}
void DER load_digit_images(void) noexcept
{
using namespace std::literals;
auto root{ "../../data/img/"s };
Impl::_period_img() = load_digit(root + "dot.png");
Impl::_0_img() = load_digit(root + "digit_000.png");
Impl::_1_img() = load_digit(root + "digit_001.png");
Impl::_2_img() = load_digit(root + "digit_002.png");
Impl::_3_img() = load_digit(root + "digit_003.png");
Impl::_4_img() = load_digit(root + "digit_004.png");
Impl::_5_img() = load_digit(root + "digit_005.png");
Impl::_6_img() = load_digit(root + "digit_006.png");
Impl::_7_img() = load_digit(root + "digit_007.png");
Impl::_8_img() = load_digit(root + "digit_008.png");
Impl::_9_img() = load_digit(root + "digit_009.png");
}
} | true |
c534fef20c12c9d5e1a176190d260e9e7dc06c0e | C++ | alaksana96/SoftwareEngineering2 | /Lab3/FarthestPoint.cpp | UTF-8 | 1,297 | 3.875 | 4 | [] | no_license | /*
* FarthestPoint.cpp
*
* Created on: Nov 12, 2016
* Author: LaksanaAufar
*
* Write a (global) function which takes as argument a vector of points and
* returns the index of the one which is farthest from the origin. Write a main
* to test the function.
*/
#include <iostream>
#include <vector>
#include "point.hpp"
using namespace std;
int farthestPoint(vector<Point>& points);
/*
int main(){
vector<Point> vecPoint;
double xin, yin;
cout << "Enter x: " << endl;
cin >> xin;
cout << "Enter y: " << endl;
cin >> yin;
while(xin != 0 && yin != 0){
Point vp(xin, yin);
vecPoint.push_back(vp);
cout << "Enter x: " << endl;
cin >> xin;
cout << "Enter y: " << endl;
cin >> yin;
}
for(int i = 0; i < vecPoint.size(); i++){ //Print out the points in the vector
cout << vecPoint[i].getPoint() << endl;
}
int index = farthestPoint(vecPoint);
cout << "the index is: " << index << "\nthe point is: " << vecPoint[index].getPoint() << endl;
return 0;
}
int farthestPoint(vector<Point>& points){
Point furthest(0,0); //initialized to the origin
int index = 0;
for(int i = 0; i < points.size(); i++){
double distance = furthest.get_distance();
Point p = points[i];
if(p.get_distance() > distance){
furthest = p;
index = i;
}
}
return index;
}
*/
| true |
ee9b859b29acbbded34326acce5f89434b0c7fc0 | C++ | Ixilthrin/SMURF | /graphics/include/GuiGlyph.h | UTF-8 | 1,015 | 2.890625 | 3 | [] | no_license | #ifndef GENG_GUI_GLYPH_H
#define GENG_GUI_GLYPH_H
#include <map>
struct GuiGlyph
{
/// The left position of the character image in the texture.
int x;
/// The top position of the character image in the texture.
int y;
/// The width of the character image in the texture.
int width;
/// The height of the character image in the texture.
int height;
/// How much the current position should be offset when copying the image from the texture to the screen.
int offsetX;
/// How much the current position should be offset when copying the image from the texture to the screen.
int offsetY;
/// How much the current position should be advanced after drawing the character.
int xAdvance;
/// The texture page where the character image is found. (Not currently used.)
int page;
std::map<char, int> kernings;
GuiGlyph() : x(0), y(0), width(0), height(0), offsetX(0), offsetY(0), xAdvance(0), page(0) { }
};
#endif
| true |
d3bf13f9b09d0a9a111503c429ea90be85b549ef | C++ | sgumhold/cgv | /cgv/math/geom.h | UTF-8 | 3,201 | 3.34375 | 3 | [] | permissive | #pragma once
#include "fmat.h"
namespace cgv {
namespace math {
//! rotate vector v around axis n by angle a (given in radian)
/*! the cos and sin functions need to be implemented for type T.*/
template <typename T>
cgv::math::fvec<T, 3> rotate(const cgv::math::fvec<T, 3>& v, const cgv::math::fvec<T, 3>& n, T a)
{
cgv::math::fvec<T, 3> vn = dot(n, v)*n;
return vn + cos(a)*(v - vn) + sin(a)*cross(n, v);
}
//! compute a rotation axis and a rotation angle in radian that rotates v0 onto v1.
/*! An alternative solution is given by the negated axis with negated angle. */
template <typename T>
void compute_rotation_axis_and_angle_from_vector_pair(const cgv::math::fvec<T, 3>& v0, const cgv::math::fvec<T, 3>& v1, cgv::math::fvec<T, 3>& axis, T& angle)
{
axis = cross(v0, v1);
T len = axis.length();
if (len > 2 * std::numeric_limits<T>::epsilon())
axis *= T(1) / len;
else
axis[1] = T(1);
angle = atan2(len, dot(v0, v1));
}
//! decompose a rotation matrix into axis angle representation
/*! The implementation assumes that R is orthonormal and that det(R) = 1, thus no reflections are handled.
Negation of axis and angle yield another solution.
The function returns three possible status values:
- 0 ... axis and angle where unique up to joined negation
- 1 ... angle is M_PI can be negated independently of axis yielding another solution
- 2 ... angle is 0 and axis can be choosen arbitrarily.
*/
template <typename T>
int decompose_rotation_to_axis_and_angle(const cgv::math::fmat<T, 3, 3>& R, cgv::math::fvec<T, 3>& axis, T& angle)
{
axis(0) = R(2, 1) - R(1, 2);
axis(1) = R(0, 2) - R(2, 0);
axis(2) = R(1, 0) - R(0, 1);
T len = axis.length();
T tra = R.trace();
if (len < 2 * std::numeric_limits<T>::epsilon()) {
if (tra < 0) {
for (unsigned c = 0; c<3; ++c)
if (R(c, c) > 0) {
axis(c) = T(1);
angle = M_PI;
break;
}
return 1;
}
else {
axis(1) = T(1);
angle = 0;
return 2;
}
}
else {
axis *= T(1) / len;
angle = atan2(len, tra - T(1));
return 0;
}
}
//! Given two vectors v0 and v1 extend to orthonormal frame and return 3x3 matrix containing frame vectors in the columns.
/*! The implementation has the following assumptions that are not checked:
- v0.length() > 0
- v1.length() > 0
- v0 and v1 are not parallel or anti-parallel
If the result matrix has columns x,y, and z,
- x will point in direction of v0
- z will point orthogonal to x and v1
- y will point orthogonal to x and z as good as possible in direction of v1. If v0 and v1 are orthogonal, y is in direction of v1. */
template <typename T>
cgv::math::fmat<T, 3, 3> build_orthogonal_frame(const cgv::math::fvec<T, 3>& v0, const cgv::math::fvec<T, 3>& v1)
{
cgv::math::fmat<T, 3, 3> O;
cgv::math::fvec<T, 3>& x = (cgv::math::fvec<T, 3>&)O(0, 0);
cgv::math::fvec<T, 3>& y = (cgv::math::fvec<T, 3>&)O(0, 1);
cgv::math::fvec<T, 3>& z = (cgv::math::fvec<T, 3>&)O(0, 2);
x = v0;
x.normalize();
z = cross(v0, v1);
z.normalize();
y = cross(z, x);
return O;
}
}
} | true |
bd14218c2076274169d8de03c8895538462eb108 | C++ | carlostojal/opendb | /InsertData.cpp | UTF-8 | 581 | 3.15625 | 3 | [] | no_license | #include "InsertData.h"
using namespace std;
InsertData::InsertData(Table* table1)
{
table = table1;
}
void InsertData::render()
{
vector<Column> cols = table->structure;
vector<Column> data;
cout << "\n** Insert into \"" << table->name << "\" **\n" << endl;
for (unsigned int i = 0; i < cols.size(); i++)
{
Column currentCol = cols.at(i);
Column newCol = Column();
newCol.name = currentCol.name;
cout << currentCol.name << ": ";
cin >> newCol.value;
data.push_back(newCol);
}
Row row = Row(data);
table->data.push_back(row);
table->saveData();
}
| true |
1112b26b8a5067dd1753d935a49e98b698d56783 | C++ | grastvei007/device | /msg/messagepair.h | UTF-8 | 835 | 2.875 | 3 | [] | no_license | #ifndef MESSAGEPAIR_H
#define MESSAGEPAIR_H
#include <QObject>
class MessagePair
{
public:
enum Type
{
eFloat = 0,
eString,
eBool,
eInt
};
MessagePair();
void setKey(QString aKeyName);
void setType(Type aType);
void setFloatFromBytes(char *aValue); ///< 4 bytes
void setStringFromBytess(char *aValue, int aSize);
void setBoolFromByte(char c); ///< val 0 of 1
void setIntFromBytes(char *aValue); ///< 4 bytes
QString getKey() const;
Type getType() const;
double getFloatValue() const;
QString getStringValue() const;
bool getBoolValue() const;
int getIntValue() const;
private:
QString mKey;
Type mType;
double mDoubleValue;
int mIntValue;
QString mStringValue;
bool mBoolValue;
};
#endif // MESSAGEPAIR_H
| true |
23ae5ecc16ec24338f6ba9e23496f12fb316220e | C++ | kmj91/kmj-api | /2019_06_30_Gunbird/2019_06_30_Gunbird/ObjectEffect.cpp | UTF-8 | 1,193 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#include "ObjectEffect.h"
ObjectEffect::ObjectEffect(int iType, int iPosX, int iPosY)
{
m_ComprehensiveType = df_COMPREHENSIVE_TYPE_NEUTRAL;
m_Type = iType;
m_X = iPosX;
m_Y = iPosY;
switch (m_Type) {
case df_TYPE_OBJECT_EFFECT_KABOOM_1:
m_iSpriteIndex = df_SPRITE_ITEM_KABOOM_1_1;
m_iAnimeStart = df_SPRITE_ITEM_KABOOM_1_1;
m_iAnimeEnd = df_SPRITE_ITEM_KABOOM_1_9;
m_iAnimeCount = 0;
break;
}
}
ObjectEffect::~ObjectEffect()
{
}
bool ObjectEffect::Action()
{
//m_Y = m_Y + df_SPEED_SCROLL;
// 좀더 입체감이 느껴짐
m_Y = m_Y + df_SPEED_SCROLL + 4;
if (Animation(df_DELAY_EFFECT)) {
return true;
}
return false;
}
void ObjectEffect::Draw()
{
g_cSprite.DrawSprite(m_iSpriteIndex, m_X, m_Y, g_bypDest, g_iDestWidth, g_iDestHeight, g_iDestPitch);
}
//------------------------------------
// 애니메이션 처리
// iAnimeDelay : 프레임 딜레이 값
//------------------------------------
bool ObjectEffect::Animation(int iAnimeDelay)
{
if (m_iAnimeCount < iAnimeDelay) {
++m_iAnimeCount;
}
else {
m_iAnimeCount = 0;
++m_iSpriteIndex;
if (m_iSpriteIndex > m_iAnimeEnd) {
return true;
}
}
return false;
}
| true |
2d3626d4f1e5fdd7f1b75af2a1b7b9ebd404fe6f | C++ | andy-sheng/leetcode | /proj/alog/581. Shortest Unsorted Continuous Subarray/581. Shortest Unsorted Continuous Subarray.h | UTF-8 | 2,022 | 3.140625 | 3 | [
"MIT"
] | permissive | //
// 581. Shortest Unsorted Continuous Subarray.h
// leetcode
//
// Created by andysheng on 2019/10/7.
// Copyright © 2019 Andy. All rights reserved.
//
#ifndef _81__Shortest_Unsorted_Continuous_Subarray_h
#define _81__Shortest_Unsorted_Continuous_Subarray_h
#include <vector>
using namespace std;
namespace ShortestUnsortedContinuousSubarray {
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int lowBoundary = -1;
int highBoundary = -2; // just for ascending input case. (-2 - -1 + 1 = 0)
// find left boundary
for (int i = 0; i < nums.size() - 1; ++i) {
if (nums[i] > nums[i + 1]) {
int smallest = nums[i + 1];
for (int j = i + 1; j < nums.size(); ++j) {
smallest = smallest <= nums[j] ? smallest : nums[j];
}
for (int j = 0; j <= i; ++j) {
if (nums[j] > smallest) {
lowBoundary = j;
break;
}
}
break;
}
}
// find right boundary
for (int i = (int)nums.size() - 1; i > 0; --i) {
if (nums[i] < nums[i - 1]) {
int biggest = nums[i - 1];
for (int j = i - 1; j >= lowBoundary; --j) {
biggest = biggest >= nums[j] ? biggest : nums[j];
}
for (int j = (int)nums.size() - 1; j >= i; --j) {
if (nums[j] < biggest) {
highBoundary = j;
break;
}
}
break;
}
}
return highBoundary - lowBoundary + 1;
}
};
}
#endif /* _81__Shortest_Unsorted_Continuous_Subarray_h */
| true |
325c7a8cfb8cd3887aec7fb9e8e962757bd4b678 | C++ | ligand-lg/leetcode | /codingInterview/27_字符串排列.cpp | UTF-8 | 785 | 3.0625 | 3 | [] | no_license | #include "../leetcode.h"
class Solution {
vector<string> help(const string &str, int index) {
if (index < 0)
return {""};
vector<string> ans;
auto pre_ans = help(str, index-1);
for (auto s : pre_ans) {
for (int i = 0; i <= s.length(); ++i) {
s.insert(s.begin() + i, str[index]);
ans.push_back(s);
s.erase(s.begin() + i);
}
}
return ans;
}
public:
vector<string> Permutation(string str) {
if (str.length() == 0) return {};
auto _ans = help(str, str.length() - 1);
set<string> set_ans(_ans.begin(), _ans.end());
return vector<string>(set_ans.begin(), set_ans.end());
}
};
int main() {
Solution s;
for (auto str : s.Permutation("ab")) {
cout << str << endl;
}
return 0;
}
| true |
4820586574ca2d533b4ec6e16fa5c187767e48f9 | C++ | zeienko-vitalii/se-cpp | /zeienko-vitalii/src/zeienko01/Manipulator.cpp | UTF-8 | 962 | 2.84375 | 3 | [
"MIT"
] | permissive | /**
* @file Manipulator.cpp
* Realization of the Manipulator class.
* @author Vitalii Zeienko
* @version 0.0.3
* @date 2017.09.09
*/
#include "Manipulator.h"
#include <stdio.h>
const int Manipulator::MIN_NUM_BTNS = 2;
const int Manipulator::MAX_NUM_BTNS = 20;
Manipulator::Manipulator(void) : amountOfButtons(MIN_NUM_BTNS), typeOfManipulator(Mouse) {
// Setting the deafult parameters for the CManipulator class' attributes
printf("Constructor without params is called!\n");
}
Manipulator::Manipulator(int amountOfBtns, Type typeOfManip) :
amountOfButtons(amountOfBtns), typeOfManipulator(typeOfManip) {
printf("Constructor with params is called!\n");
}
Manipulator::Manipulator(const Manipulator& Manipulator) :
amountOfButtons(Manipulator.amountOfButtons), typeOfManipulator(Manipulator.typeOfManipulator) {
printf(" Copiyng constructor is called!\n");
}
Manipulator::~Manipulator() {
printf("~Manipulator()\n");
}
| true |
e6a20b69f877a454738ac26d4008e920346d8ae2 | C++ | Napradean-Andrei/University | /Doubly Linked List on Array/main.cpp | UTF-8 | 6,159 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stdlib.h>
#include <assert.h>
template <typename T>
struct Node
{
T info;
int next;
int prev;
};
template <typename T>
class List
{
private:
int cap = 100;
int size = 0;
int firstEmpty = 0;
int tail = -1;
int head = -1;
Node<T> elems[100];
bool(*r)(T, T);
public:
List(bool(*cmp)(T, T) = [](T a, T b) {return a <= b; }) : r{ cmp } {
for (int i = 0; i < 100; ++i) {
elems[i].next = i + 1;
elems[i].prev = i - 1;
}
elems[0].prev = -1;
elems[99].next = -1;
}
int first() {
if (size) {
return 0;
}
//throw std::runtime_error{ "Empty list" };
}
int last() {
if (size) {
return size - 1;
}
//throw std::runtime_error{ "Empty list" };
}
bool valid(int pos) {
return pos >= 0 && pos < size;
}
int next(int pos) {
if (valid(pos + 1)) {
return pos + 1;
}
//throw std::runtime_error{ "Invalid position" };
}
int prev(int pos) {
if (valid(pos - 1)) {
return pos - 1;
}
//throw std::runtime_error{ "Invalid position" };
}
void getElement(T& e, int p) {
int current = head;
if (valid(p)) {
for (int i = 0; i < p; ++i) {
current = elems[current].next;
}
e = elems[current].info;
}
}
int getPosition(T e) {
int current = head;
for (int i = 0; i < size; ++i) {
if (elems[current].info == e) {
return i;
}
current = elems[current].next;
}
throw std::runtime_error{ "Element not found" };
}
void insert(T e) {
//pre: e- TElem
//post: returns nothing modifies the list
if (size == cap) {
throw std::runtime_error{ "List is full" };
}
elems[firstEmpty].info = e;
if (!size) {
elems[firstEmpty].prev = -1;
head = firstEmpty;
tail = head;
firstEmpty = elems[firstEmpty].next;
elems[firstEmpty].prev = -1;
elems[head].next = -1;
++size;
return;
}
if (r(e, elems[head].info)) {
int aux = elems[firstEmpty].next;
elems[firstEmpty].prev = -1;
elems[firstEmpty].next = head;
elems[head].prev = firstEmpty;
head = firstEmpty;
firstEmpty = aux;
if (aux != -1) {
elems[aux].prev = -1;
}
}
else {
int current = head;
while (current != -1 && r(elems[current].info, e)) {
current = elems[current].next;
}
if (current == -1) {
elems[firstEmpty].prev = tail;
elems[tail].next = firstEmpty;
tail = firstEmpty;
firstEmpty = elems[firstEmpty].next;
if (firstEmpty != -1) {
elems[firstEmpty].prev = -1;
}
elems[tail].next = -1;
}
else {
int aux = elems[firstEmpty].next;
elems[firstEmpty].next = current;
elems[firstEmpty].prev = elems[current].prev;
elems[elems[current].prev].next = firstEmpty;
elems[current].prev = firstEmpty;
firstEmpty = aux;
if (aux != -1) {
elems[aux].prev = -1;
}
}
}
++size;
}
void remove(int p, T& e) {
//pre: p is the position e is TElem
//post: returns nothing modifies the list
int current = head;
if (valid(p)) {
for (int i = 0; i < p; ++i) {
current = elems[current].next;
}
e = elems[current].info;
if (p == 0) {
int aux = firstEmpty;
head = elems[head].next;
firstEmpty = elems[head].prev;
elems[firstEmpty].next = aux;
elems[firstEmpty].prev = -1;
elems[head].prev = -1;
}
else if (p == size - 1) {
int aux = firstEmpty;
firstEmpty = tail;
tail = elems[tail].prev;
elems[firstEmpty].next = aux;
elems[firstEmpty].prev = -1;
elems[tail].next = -1;
elems[aux].prev = firstEmpty;
}
else {
int aux = firstEmpty;
elems[elems[current].prev].next = elems[current].next;
elems[elems[current].next].prev = elems[current].prev;
firstEmpty = current;
elems[current].next = aux;
elems[current].prev = -1;
elems[aux].prev = current;
}
}
--size;
}
bool search(T e) {
//pre: e is a TElem
//post: returns true or false wether the elem was found or not
int current = head;
while (current != -1) {
if (elems[current].info == e) {
return true;
}
current = elems[current].next;
}
return false;
}
void print() {
std::cout << "\nThe current list is: ";
int current = head;
while (current != -1) {
std::cout << elems[current].info << " ";
current = elems[current].next;
}
}
void tests()
{
List<int> l;
// for insert function
l.insert(2);
assert(l.size() == 1);
// for search function
assert(l.search(2) == true);
// for valid function
assert(l.valid(0) == true);
// for first function
assert(l.first() == 0);
// for last function
assert(l.last() == 0);
// for remove function
//l.remove(0,2);//
assert(l.size() == 0);
l.insert(2);
l.insert(3);
l.insert(1);
// for next function
assert(l.next(1) == 2);
// for prev function
assert(l.prev(1) == 0);
// for getPosition function
assert(l.getPosition(2) == 1);
}
~List() {}
};
void testList() {
List<int> l;
for (int i = 0; i < 5; ++i) {
l.insert(i);
}
l.insert(-1);
l.insert(3);
l.insert(9);
//l.print();
//std::cout<<std::endl;
int a;
l.remove(4, a);
l.remove(0, a);
l.remove(5, a);
//l.print();
l.insert(0);
//l.print();
}
int main()
{
List<int> l;
testList();
int a, b, value, nr,p;
char c;
std::cout << "Please input the instructions (enter 'E' to exit): \n A to add to list\n D to delete \n T to show all\n S to search the first x students with grades grater than value";
l.insert(5);
l.insert(2);
l.insert(3);
l.insert(7);
l.insert(10);
l.insert(10);
l.insert(9);
l.insert(7);
do {
std::cin >> c;
switch (c) {
case 'A': std::cout << "give element to be added: ";
std::cin >> a;
l.insert(a);
break;
case 'D':
std::cout << "give element to be deleted: ";
std::cin >> a;
std::cout << "give pos: ";
std::cin >> p;
l.remove(p,a);
break;
case 'S': std::cout << "give value: ";
std::cin >> value;
if(l.search(value))
std::cout << "student found ";
else
std::cout << "student not found";
break;
case 'T': ;
l.print();
break;
case 'E': std::cout << "\nExiting program...\n\n";
break;
default: std::cout << "\nInvalid input entered\n\n";
}
} while (c != 'E');
return 0;
} | true |
283447074ab81c6cd49193d980241d875d033a78 | C++ | heiseish/CPLib | /Math/StringParser.hpp | UTF-8 | 1,107 | 3.15625 | 3 | [] | no_license | #include <string>
/**
Python Eval in C++
*/
class Parser {
private:
std::string input;
int stringidx = 0;
inline char peek() {
return input[stringidx];
}
inline char get() {
return input[stringidx++];
}
inline int expression();
inline int number() {
int result = get() - '0';
while (peek() >= '0' && peek() <= '9') {
result = 10*result + get() - '0';
}
return result;
}
inline int factor() {
if (isalpha(peek())) {
return g[get()];
} else if (peek() == '(') {
get(); // '('
int result = expression();
get(); // ')'
return result;
}
return 0; // error
}
inline int term() {
int result = factor();
while (stringidx < input.length() && (peek() == '*' || peek() == '/'))
if (get() == '*')
result *= factor();
return result;
}
inline int expression() {
int result = term();
while (stringidx < input.length() && (peek() == '+' || peek() == '-'))
if (get() == '+')
result += term();
else
result -= term();
return result;
}
public:
void compute(std::string& s) {
input = s;
stringidx = 0;
return expression();
}
}
| true |
85f70178862f98012ea5e3cd7d670838c9df20f5 | C++ | emisner15/Die-Roller- | /RNG.h | UTF-8 | 1,009 | 3.546875 | 4 | [] | no_license | #ifndef RNG_H
#define RNG_H
#include <ctime>
#include <cstdlib>
using namespace std;
class RNG
{
private:
public:
//by default, use current time as seed
RNG()
{
srand(time(NULL));
}
//also allow custom seed
RNG(int seed)
{
srand(seed);
}
//returns a number between low and high
int generateInt(int low = 0, int high = RAND_MAX)
{
int next_number = rand();
next_number = (next_number % (high + 1 - low)) + low;
}
// all types of possible die rolls
int rollD4()
{
return generateInt(1,4);
}
int rollD6()
{
return generateInt(1, 6);
}
int rollD8()
{
return generateInt(1,8);
}
int rollD10()
{
return generateInt(1,10);
}
int rollD12()
{
return generateInt(1,12);
}
int rollD20()
{
return generateInt(1,20);
}
};
#endif // RNG_H
| true |
9877e850dc992dcc97a07358392089f5f03648c8 | C++ | WolfireGames/overgrowth | /Projects/bullet3-2.89/examples/ThirdPartyLibs/Gwen/Controls/Text.cpp | UTF-8 | 2,041 | 2.546875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"Zlib"
] | permissive | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Gwen.h"
#include "Gwen/Controls/Text.h"
#include "Gwen/Skin.h"
#include "Gwen/Utility.h"
using namespace Gwen;
using namespace Gwen::ControlsInternal;
GWEN_CONTROL_CONSTRUCTOR(Text)
{
m_Font = NULL;
m_Color = Gwen::Colors::Black; // TODO: From skin somehow..
SetMouseInputEnabled(false);
}
Text::~Text()
{
// NOTE: This font doesn't need to be released
// Because it's a pointer to another font somewhere.
}
void Text::RefreshSize()
{
if (!GetFont())
{
Debug::AssertCheck(0, "Text::RefreshSize() - No Font!!\n");
return;
}
Gwen::Point p(1, GetFont()->size);
if (Length() > 0)
{
p = GetSkin()->GetRender()->MeasureText(GetFont(), m_String);
}
if (p.x == Width() && p.y == Height())
return;
SetSize(p.x, p.y);
InvalidateParent();
Invalidate();
}
Gwen::Font* Text::GetFont()
{
return m_Font;
}
void Text::SetString(const UnicodeString& str)
{
m_String = str;
Invalidate();
}
void Text::SetString(const String& str) { SetString(Gwen::Utility::StringToUnicode(str)); }
void Text::Render(Skin::Base* skin)
{
if (Length() == 0 || !GetFont()) return;
skin->GetRender()->SetDrawColor(m_Color);
skin->GetRender()->RenderText(GetFont(), Gwen::Point(0, 0), m_String);
}
void Text::Layout(Skin::Base* /*skin*/)
{
RefreshSize();
}
Gwen::Point Text::GetCharacterPosition(int iChar)
{
if (Length() == 0 || iChar == 0)
{
return Gwen::Point(1, 0);
}
UnicodeString sub = m_String.substr(0, iChar);
Gwen::Point p = GetSkin()->GetRender()->MeasureText(GetFont(), sub);
if (p.y >= m_Font->size)
p.y -= m_Font->size;
return p;
}
int Text::GetClosestCharacter(Gwen::Point p)
{
int iDistance = 4096;
int iChar = 0;
for (size_t i = 0; i < m_String.length() + 1; i++)
{
Gwen::Point cp = GetCharacterPosition(i);
int iDist = abs(cp.x - p.x) + abs(cp.y - p.y); // this isn't proper
if (iDist > iDistance) continue;
iDistance = iDist;
iChar = i;
}
return iChar;
}
void Text::OnScaleChanged()
{
Invalidate();
} | true |
bb0a42a400f4454af390399192f8d05a0d432cc0 | C++ | prasadnallani/LeetCodeProblems | /Medium/1004-MaxConsecutiveOnesIII.cpp | UTF-8 | 2,296 | 3.828125 | 4 | [] | no_license |
/*
* Author: Raghavendra Mallela
*/
/*
* LeetCode 1004: Max Consecutive Ones III
*
* Given a binary array nums and an integer k, return the maximum number of
* consecutive 1's in the array if you can flip at most k 0's.
*
* Example 1:
* Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
* Output: 6
* Explanation: [1,1,1,0,0,1,1,1,1,1,1]
* Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
*
* Example 2:
* Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
* Output: 10
* Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
* Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
*
* Constraints:
* 1 <= nums.length <= 105
* nums[i] is either 0 or 1.
* 0 <= k <= nums.length
*/
/* Approach followed is a sliding window technique where there
* are 2 pointers wStart and wEnd and wEnd will be traversing
* the entire numbers.
* . If we encounter 0 at wEnd, then we start decrementing K
* . If k < 0, then we start incrementing wStart ie.., we have
* more number of 0's than k.
* . If there is 0 at wStart, then we start incrementing K bcz
* we need to have only one's.
* Once we are done with traversing, the number of consecutive
* 1's are calculated using window length
*/
int longestOnes(vector<int>& nums, int k) {
// Basecase: check if the input nums is empty
if (nums.empty()) {
// Input vector is empty, return
return 0;
}
// Initialize the window variables
int wStart = 0;
int wEnd = 0;
// Traverse the window for whole input array
while (wEnd < nums.size()) {
// If the current number is 0 at WEnd, then reduce the k
// as only k 0's can be flipped
if (nums[wEnd] == 0) {
// Reduce k
k--;
}
// Check if more than k 0's are flipped, then slide the window
if (k < 0) {
// Check if the num at wStart is zero, then increase the
// k as we are removing one zero from our window
k += (nums[wStart] == 0 ? 1 : 0);
// Increment the wStart
wStart++;
}
// Increment the window
wEnd++;
}
// Now window size is the number of consecutive 1's after flipping
// k zeros
return wEnd - wStart;
}
| true |
e07bfd39947e82828d1e91d9b84f5c0aa2181570 | C++ | JohannesRuder/workspace | /mylib/team.h | UTF-8 | 1,289 | 2.921875 | 3 | [] | no_license | //
// Created by hannes on 11.02.18.
//
#ifndef TEAM_H_
#define TEAM_H_
#include <string> // for string
#include <vector> // for vector
#include <opencv2/core/core.hpp> // IWYU pragma: keep
#include <opencv2/core/persistence.hpp> // for FileStorage (ptr only), File...
#include <qt5/QtCore/qstring.h> // for QString
#include "player.h" // for Player
class Team
{
private:
QString name_;
std::vector<Player> players_;
public:
explicit Team() = default;
explicit Team(const QString& name);
void SetName(const QString& name);
const QString& GetName() const;
void AddPlayer(const Player& player);
const std::vector<Player>& GetPlayers() const;
const Player& GetPlayer(int player_number) const;
bool operator==(const Team& rhs) const;
void Write(cv::FileStorage& file_storage) const;
void Read(const cv::FileNode& node);
};
inline void write(cv::FileStorage& file_storage, const std::string&, const Team& x)
{
x.Write(file_storage);
}
inline void read(const cv::FileNode& node, Team& x, const Team& default_value = Team())
{
if (node.empty())
{
x = default_value;
}
else
{
x.Read(node);
}
}
#endif // TEAM_H_
| true |
86140c2049b495d5bdbf88ab0d28410bebb9b797 | C++ | RyoFuji2005/ShilitoriCPP | /shilitori.cpp | UTF-8 | 9,188 | 3.046875 | 3 | [
"MIT"
] | permissive |
// (c)2021 Ryo Fujinami.
#include <iostream>
#include <map>
#include <random>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <unistd.h>
#include "converters.hpp"
// 乱数初期化
std::mt19937 initialize_rand() {
std::srand(std::time(NULL));
std::mt19937 mt(std::rand());
return mt;
}
std::mt19937 mt = initialize_rand();
// ランダム削除
std::vector<std::string> remove_random(std::vector<std::string> list) {
std::uniform_int_distribution<> rand(0, list.size() - 1);
list.erase(list.begin() + rand(mt));
return list;
}
// 要素削除
std::vector<std::string> remove_element(std::vector<std::string> list, std::string text) {
size_t length = list.size();
for (int i = 0; i < length; i++) {
if (list[i] == text) {
list.erase(list.begin() + i);
}
}
return list;
}
// 辞書を縮小
std::map<std::string, std::vector<std::string>> cut_word(std::map<std::string, std::vector<std::string>> dict) {
std::vector<std::string> list = {};
for (const auto& item : dict) {
list.push_back(item.first);
}
std::uniform_int_distribution<> rand(0, list.size() - 1);
for (int i = 0; i < 520; i++) {
int num = rand(mt);
if (dict[list[num]].size() != 0) {
dict[list[num]] = remove_random(dict[list[num]]);
}
}
return dict;
}
std::map<std::string, std::vector<std::string>> light_word_dict = cut_word(full_word_dict);
// 要素数をカウント
unsigned int count_words(std::map<std::string, std::vector<std::string>> dict) {
unsigned int count = 0;
for (const auto& item : dict) {
count += item.second.size();
}
return count;
}
// 最小をカウント
unsigned int minor_words(std::map<std::string, std::vector<std::string>> dict) {
unsigned int minor = 30;
for (const auto& item : dict) {
if (minor > item.second.size()) {
minor = item.second.size();
}
}
return minor;
}
// 要素存在確認
bool find_element(std::vector<std::string> list, std::string text) {
for (const auto& item : list) {
if (item == text) {
return true;
}
}
return false;
}
// 文字列スライス
std::vector<std::string> slice_text(std::string str) {
int pos;
unsigned char lead;
int char_size;
std::vector<std::string> list = {};
for (pos = 0; pos < str.size(); pos += char_size) {
lead = str[pos];
if (lead < 0x80) {
char_size = 1;
}
else if (lead < 0xE0) {
char_size = 2;
}
else if (lead < 0xF0) {
char_size = 3;
}
else {
char_size = 4;
}
list.push_back(str.substr(pos, char_size));
}
return list;
}
// エラー判定
bool judge_error(std::string pword, std::string pwf, std::string cwe,
std::vector<std::string> occur) {
std::vector<std::string> sliced_p = slice_text(pword);
if (pwf != cwe) {
std::cout << "初めの文字を確認してください" << std::endl;
}
else if (sliced_p.size() <= 1) {
std::cout << "1文字の単語は禁止です" << std::endl;
}
else if (sliced_p.size() > 10) {
std::cout << "10文字より多い単語は禁止です" << std::endl;
}
else if (find_element(occur, pword)) {
std::cout << "その言葉はもう出ています" << std::endl;
}
else {
return false;
}
return true;
}
// 終了判定
bool judge_end(std::map<std::string, std::vector<std::string>> dict, std::string pword, std::string pwe, std::string cwe) {
if (pwe == "ン") {
std::cout << "「ン」が付きました" << std::endl << "あなたの負けです" << std::endl
<< "お疲れ様でした" << std::endl << std::endl;
}
else if (dict[pwe].size() == 0) {
std::cout << "もう言葉を思いつきません" << std::endl << "私の負けです" << std::endl
<< "お疲れ様でした" << std::endl << std::endl;
}
else {
return false;
}
return true;
}
// ランダム選択
std::string choice_random(std::vector<std::string> list) {
std::uniform_int_distribution<> rand(0, list.size() - 1);
return list[rand(mt)];
}
// ルール表示
void print_rule() {
std::cout << " ルール" << std::endl;
std::cout << "* 1文字だけの単語は禁止です" << std::endl;
std::cout << "* 10文字以上の単語は禁止です" << std::endl;
std::cout << "* 名詞を入力して\"Enter\"を押してください" << std::endl;
std::cout << "* 最後に\"ン\"がついた時あなたの負けです" << std::endl;
std::cout << "* 一度使われた単語は使えません" << std::endl;
std::cout << "* 通常音と濁音・破裂音は区別しません" << std::endl;
std::cout << "* カタカナ又はひらがなで入力してください" << std::endl;
}
// オプション表示
void print_option() {
std::cout << " オプション" << std::endl;
std::cout << "-f すべての単語を利用します" << std::endl;
std::cout << "-w 終了時に入力しません" << std::endl;
std::cout << "-h ヘルプを表示します" << std::endl;
std::cout << "-r ルールを表示しません" << std::endl;
std::cout << "-c 単語数を表示しません" << std::endl;
}
// メイン
int main(int argc, char* argv[]) {
bool opt_f = false;
bool opt_w = false;
bool opt_r = false;
bool opt_c = false;
int opt;
while ((opt = getopt(argc, argv, "fwhrc")) != -1) {
switch (opt) {
case 'f':
opt_f = true;
break;
case 'w':
opt_w = true;
break;
case 'r':
opt_r = true;
break;
case 'c':
opt_c = true;
break;
case 'h':
print_option();
return 0;
default:
std::cout << "error: オプション \"" << opt << "\" は存在しません";
return 1;
}
}
std::map<std::string, std::vector<std::string>> word_dict;
if (opt_f) {
word_dict = full_word_dict;
}
else {
word_dict = light_word_dict;
}
if (!opt_r) {
print_rule();
}
if (!opt_c) {
std::cout << "( 合計単語数:" << count_words(word_dict) << "、最小単語数:" << minor_words(word_dict) << " )" << std::endl;
}
if (!opt_r || !opt_c) {
std::cout << std::endl;
}
std::string cwe = "リ";
std::vector<std::string> occur = {}; // 出現リスト
int num = 1; // 現在の回数
std::string cword = "シリトリ";
std::string pwe = "始";
occur.push_back(cword);
std::cout << " " << num << " 回目" << std::endl;
std::cout << pwe << ":" << cword << std::endl;
std::string pword, pwf, copy, element;
std::string long_character = "ー";
std::vector<std::string> sliced_p, sliced_c;
while (true) {
std::cout << cwe << ":";
std::cin >> pword;
std::cout << std::endl;
sliced_p = slice_text(pword);
if (pword == "") {
std::cout << "入力してください" << std::endl;
continue;
}
copy = "";
size_t length = sliced_p.size();
bool error = false;
for (int i = 0; i < length; i++) {
element = sliced_p[i];
if (!find_element(kana_list, element)) {
error = true;
}
copy += kana_dict[element];
}
if (error) {
std::cout << "カタカナ又はひらがなで入力してください" << std::endl;
continue;
}
pword = copy;
sliced_p = slice_text(pword);
element = sliced_p.back();
if (element == long_character) {
element = sliced_p.rbegin()[1];
pwe = long_dict[element];
pwf = sliced_p[0];
}
else {
pwe = sliced_p.back();
pwf = sliced_p[0];
pwe = voice_dict[pwe];
pwf = voice_dict[pwf];
}
word_dict[cwe] = remove_element(word_dict[cwe], pword);
if (judge_error(pword, pwf, cwe, occur)) {
continue;
}
else if (judge_end(word_dict, pword, pwe, cwe)) {
break;
}
occur.push_back(pword);
std::string cword = choice_random(word_dict[pwe]);
word_dict[pwe] = remove_element(word_dict[pwe], cword);
occur.push_back(cword);
sliced_c = slice_text(cword);
element = sliced_c.back();
if (element == long_character) {
element = sliced_c.rbegin()[1];
cwe = long_dict[element];
}
else {
element = sliced_c.back();
cwe = voice_dict[element];
}
num += 1;
std::cout << "\n " << num << " 回目" << std::endl;
std::cout << pwe << ":" << cword << std::endl;
}
if (!opt_w) {
std::cin >> element;
}
return 0;
}
| true |
ea4465de17a0ce17b1ef6b18808c667f4e90eea9 | C++ | rafaelhdr/tccsauron | /Sauron/Common/Line.h | UTF-8 | 273 | 2.953125 | 3 | [] | no_license | #pragma once
namespace sauron
{
class Line
{
public:
Line(double rWall, double theta)
: m_rWall(rWall), m_theta(theta){
}
inline double getRWall() const { return m_rWall; }
inline double getTheta() const { return m_theta; }
private:
double m_rWall, m_theta;
};
}
| true |
74de149bf4ab9d3cfb52095f74e1c8b3fab0afaa | C++ | AntSworD/ACM | /HDU/2056.cpp | UTF-8 | 967 | 2.96875 | 3 | [] | no_license | #include<stdio.h>
double x[4],y[4],t;
void sortx()
{
int i,j;
for(i=1;i<4;i++)
for(j=0;j<3;j++)
{
if(x[j]>x[j+1])
{
t=x[j];
x[j]=x[j+1];
x[j+1]=t;
}
}
}
void sorty()
{
int i,j;
for(i=1;i<4;i++)
for(j=0;j<3;j++)
{
if(y[j]>y[j+1])
{
t=y[j];
y[j]=y[j+1];
y[j+1]=t;
}
}
}
int main()
{
double a,b,c,d,k,h,s;;
while(scanf("%lf %lf %lf %lf",&a,&b,&c,&d)!=EOF)
{
if(a<c)
{
x[0]=a;
x[1]=c;
}
else
{
x[0]=c;
x[1]=a;
}
if(b<d)
{
y[0]=b;
y[1]=d;
}
else
{
y[0]=d;
y[1]=b;
}
scanf("%lf %lf %lf %lf",&a,&b,&c,&d);
if(a<c)
{
x[2]=a;
x[3]=c;
}
else
{
x[2]=c;
x[3]=a;
}
if(b<d)
{
y[2]=b;
y[3]=d;
}
else
{
y[2]=d;
y[3]=b;
}
if(y[3]<=y[0]||y[2]>=y[1]||x[3]<=x[0]||x[2]>=x[1])
printf("0.00\n");
else
{
sortx();
sorty();
k=x[2]-x[1];
h=y[2]-y[1];
s=k*h;
printf("%.2lf\n",s);
}
}
return 0;
} | true |
5217ba6d0b1da0f5b70105460c0cf73712939020 | C++ | nCine/nCine | /unit_tests/gtest_statichashset.cpp | UTF-8 | 7,194 | 3.15625 | 3 | [
"MIT"
] | permissive | #include "gtest_statichashset.h"
namespace {
class StaticHashSetTest : public ::testing::Test
{
protected:
void SetUp() override { initHashSet(hashset_); }
HashSetTestType hashset_;
};
TEST_F(StaticHashSetTest, Capacity)
{
const unsigned int capacity = hashset_.capacity();
printf("Capacity: %u\n", capacity);
ASSERT_EQ(capacity, Capacity);
}
TEST_F(StaticHashSetTest, Size)
{
const unsigned int size = hashset_.size();
printf("Size: %u\n", size);
ASSERT_EQ(size, Size);
ASSERT_EQ(calcSize(hashset_), Size);
}
TEST_F(StaticHashSetTest, LoadFactor)
{
const float loadFactor = hashset_.loadFactor();
printf("Size: %u, Capacity: %u, Load Factor: %f\n", Size, Capacity, loadFactor);
ASSERT_FLOAT_EQ(loadFactor, Size / static_cast<float>(Capacity));
}
TEST_F(StaticHashSetTest, Clear)
{
ASSERT_FALSE(hashset_.isEmpty());
hashset_.clear();
printHashSet(hashset_);
ASSERT_TRUE(hashset_.isEmpty());
ASSERT_EQ(hashset_.size(), 0u);
ASSERT_EQ(hashset_.capacity(), Capacity);
}
TEST_F(StaticHashSetTest, InsertElements)
{
printf("Inserting elements\n");
for (unsigned int i = Size; i < Size * 2; i++)
hashset_.insert(i);
for (unsigned int i = 0; i < Size * 2; i++)
ASSERT_TRUE(hashset_.contains(i));
ASSERT_EQ(hashset_.size(), Size * 2);
ASSERT_EQ(calcSize(hashset_), Size * 2);
}
TEST_F(StaticHashSetTest, FailInsertElements)
{
printf("Trying to insert elements already in the hashset\n");
for (unsigned int i = 0; i < Size * 2; i++)
hashset_.insert(i);
for (unsigned int i = 0; i < Size * 2; i++)
ASSERT_TRUE(hashset_.contains(i));
ASSERT_EQ(hashset_.size(), Size * 2);
ASSERT_EQ(calcSize(hashset_), Size * 2);
}
TEST_F(StaticHashSetTest, RemoveElements)
{
printf("Original size: %u\n", hashset_.size());
printf("Removing a couple elements\n");
printf("New size: %u\n", hashset_.size());
hashset_.remove(5);
hashset_.remove(7);
printHashSet(hashset_);
ASSERT_FALSE(hashset_.contains(5));
ASSERT_FALSE(hashset_.contains(7));
ASSERT_EQ(hashset_.size(), Size - 2);
ASSERT_EQ(calcSize(hashset_), Size - 2);
}
TEST_F(StaticHashSetTest, CopyConstruction)
{
printf("Creating a new hashset with copy construction\n");
HashSetTestType newHashset(hashset_);
printHashSet(newHashset);
assertHashSetsAreEqual(hashset_, newHashset);
ASSERT_EQ(hashset_.size(), Size);
ASSERT_EQ(calcSize(hashset_), Size);
ASSERT_EQ(newHashset.size(), Size);
ASSERT_EQ(calcSize(newHashset), Size);
}
TEST_F(StaticHashSetTest, MoveConstruction)
{
printf("Creating a new hashset with move construction\n");
HashSetTestType newHashset = nctl::move(hashset_);
printHashSet(newHashset);
ASSERT_EQ(hashset_.size(), 0);
ASSERT_EQ(newHashset.capacity(), Capacity);
ASSERT_EQ(newHashset.size(), Size);
ASSERT_EQ(calcSize(newHashset), Size);
}
TEST_F(StaticHashSetTest, AssignmentOperator)
{
printf("Creating a new hashset with the assignment operator\n");
HashSetTestType newHashset;
newHashset = hashset_;
printHashSet(newHashset);
assertHashSetsAreEqual(hashset_, newHashset);
ASSERT_EQ(hashset_.size(), Size);
ASSERT_EQ(calcSize(hashset_), Size);
ASSERT_EQ(newHashset.size(), Size);
ASSERT_EQ(calcSize(newHashset), Size);
}
TEST_F(StaticHashSetTest, MoveAssignmentOperator)
{
printf("Creating a new hashset with the move assignment operator\n");
HashSetTestType newHashset;
newHashset = nctl::move(hashset_);
printHashSet(newHashset);
ASSERT_EQ(hashset_.size(), 0);
ASSERT_EQ(newHashset.capacity(), Capacity);
ASSERT_EQ(newHashset.size(), Size);
ASSERT_EQ(calcSize(newHashset), Size);
}
TEST_F(StaticHashSetTest, SelfAssignment)
{
printf("Assigning the hashset to itself with the assignment operator\n");
hashset_ = hashset_;
printHashSet(hashset_);
ASSERT_EQ(hashset_.size(), Size);
ASSERT_EQ(calcSize(hashset_), Size);
}
TEST_F(StaticHashSetTest, Contains)
{
const int key = 1;
const bool found = hashset_.contains(key);
printf("Key %d is in the hashset: %d\n", key, found);
ASSERT_TRUE(found);
}
TEST_F(StaticHashSetTest, DoesNotContain)
{
const int key = 10;
const bool found = hashset_.contains(key);
printf("Key %d is in the hashset: %d\n", key, found);
ASSERT_FALSE(found);
}
TEST_F(StaticHashSetTest, Find)
{
const int key = 1;
const int *value = hashset_.find(key);
printf("Key %d is in the hashset: %d - Value: %d\n", key, value != nullptr, *value);
ASSERT_TRUE(value != nullptr);
ASSERT_EQ(*value, key);
}
TEST_F(StaticHashSetTest, ConstFind)
{
const HashSetTestType &constHashset = hashset_;
const int key = 1;
const int *value = constHashset.find(key);
printf("Key %d is in the hashset: %d - Value: %d\n", key, value != nullptr, *value);
ASSERT_TRUE(value != nullptr);
ASSERT_EQ(*value, key);
}
TEST_F(StaticHashSetTest, CannotFind)
{
const int key = 10;
const int *value = hashset_.find(key);
printf("Key %d is in the hashset: %d\n", key, value != nullptr);
ASSERT_FALSE(value != nullptr);
}
TEST_F(StaticHashSetTest, FillCapacity)
{
printf("Creating a new hashset to fill up to capacity (%u elements)\n", Capacity);
HashSetTestType newHashset;
for (unsigned int i = 0; i < Capacity; i++)
newHashset.insert(i);
ASSERT_EQ(newHashset.size(), Capacity);
for (unsigned int i = 0; i < Capacity; i++)
ASSERT_TRUE(newHashset.contains(i));
}
TEST_F(StaticHashSetTest, RemoveAllFromFull)
{
printf("Creating a new hashset to fill up to capacity (%u elements)\n", Capacity);
HashSetTestType newHashset;
for (unsigned int i = 0; i < Capacity; i++)
newHashset.insert(i);
printf("Removing all elements from the hashset\n");
for (unsigned int i = 0; i < Capacity; i++)
newHashset.remove(i);
ASSERT_EQ(newHashset.size(), 0);
ASSERT_EQ(calcSize(newHashset), 0);
}
const int BigCapacity = 512;
const int LastElement = BigCapacity / 2;
using HashSetStressTestType = nctl::StaticHashSet<int, BigCapacity, nctl::FNV1aHashFunc<int>>;
TEST_F(StaticHashSetTest, StressRemove)
{
printf("Creating a new hashset with a capacity of %u and filled up to %u elements\n", BigCapacity, LastElement);
HashSetStressTestType newHashset;
for (int i = 0; i < LastElement; i++)
newHashset.insert(i);
ASSERT_EQ(newHashset.size(), LastElement);
printf("Removing all elements from the hashset\n");
for (int i = 0; i < LastElement; i++)
{
newHashset.remove(i);
ASSERT_EQ(newHashset.size(), LastElement - i - 1);
for (int j = i + 1; j < LastElement; j++)
ASSERT_TRUE(newHashset.contains(j));
for (int j = 0; j < i + 1; j++)
ASSERT_FALSE(newHashset.contains(j));
}
ASSERT_EQ(newHashset.size(), 0);
}
TEST_F(StaticHashSetTest, StressReverseRemove)
{
printf("Creating a new hashset with a capacity of %u and filled up to %u elements\n", BigCapacity, LastElement);
HashSetStressTestType newHashset;
for (int i = 0; i < LastElement; i++)
newHashset.insert(i);
ASSERT_EQ(newHashset.size(), LastElement);
printf("Removing all elements from the hashset\n");
for (int i = LastElement - 1; i >= 0; i--)
{
newHashset.remove(i);
ASSERT_EQ(newHashset.size(), i);
for (int j = i - 1; j >= 0; j--)
ASSERT_TRUE(newHashset.contains(j));
for (int j = LastElement; j >= i; j--)
ASSERT_FALSE(newHashset.contains(j));
}
ASSERT_EQ(newHashset.size(), 0);
}
}
| true |
cf5e77eec8cfdbe59a32012105fe849266463a60 | C++ | cbritopacheco/rodin | /src/Rodin/Variational/QuadratureRule.h | UTF-8 | 2,620 | 2.9375 | 3 | [
"BSL-1.0"
] | permissive | #ifndef RODIN_VARIATIONAL_QUADRATURERULE_H
#define RODIN_VARIATIONAL_QUADRATURERULE_H
#include <vector>
#include <utility>
#include "Rodin/Math.h"
#include "Rodin/Geometry.h"
#include "MFEM.h"
namespace Rodin::Variational
{
class QuadratureRule
{
using Key = std::pair<Geometry::Type, size_t>;
static std::map<Key, QuadratureRule> s_rules;
struct ValueType
{
Scalar weight;
Math::Vector point;
};
public:
static const QuadratureRule& get(Geometry::Type geometry, size_t order)
{
Key key{geometry, order};
auto search = s_rules.lower_bound(key);
if (search != s_rules.end() && !(s_rules.key_comp()(key, search->first)))
{
// key already exists
return search->second;
}
else
{
size_t dim;
switch (geometry)
{
case Geometry::Type::Point:
{
dim = 0;
break;
}
case Geometry::Type::Segment:
{
dim = 1;
break;
}
case Geometry::Type::Square:
case Geometry::Type::Triangle:
{
dim = 2;
break;
}
case Geometry::Type::Cube:
case Geometry::Type::Prism:
case Geometry::Type::Pyramid:
case Geometry::Type::Tetrahedron:
{
dim = 3;
break;
}
}
const mfem::IntegrationRule& ir = mfem::IntRules.Get(static_cast<int>(geometry), order);
auto it = s_rules.insert(search, {key, QuadratureRule(ir, dim)});
return it->second;
}
}
QuadratureRule(const mfem::IntegrationRule& ir, size_t dim)
{
m_points.reserve(ir.GetNPoints());
for (int i = 0; i < ir.GetNPoints(); i++)
{
const mfem::IntegrationPoint& ip = ir.IntPoint(i);
m_points.push_back(ValueType{ip.weight, Internal::ip2vec(ip, dim)});
}
}
QuadratureRule(const QuadratureRule&) = default;
QuadratureRule(QuadratureRule&&) = default;
inline
size_t size() const
{
return m_points.size();
}
inline
Scalar getWeight(size_t i) const
{
assert(i < m_points.size());
return m_points[i].weight;
}
inline
const Math::Vector& getPoint(size_t i) const
{
assert(i < m_points.size());
return m_points[i].point;
}
private:
std::vector<ValueType> m_points;
};
}
#endif
| true |
3360645325a87904c51265070dcc3e57754ab397 | C++ | masamichiIto/atcoder_ | /cpp/kp06.cpp | UTF-8 | 960 | 3.109375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int x,y;
cin >> x >> y;
if(x < 10){
cout << "xは10より小さい" << endl;
}
else if(x > 20){
cout << "xは10より小さくなくて,20より大きい" << endl;
}
else if(x == 15){
cout << "xは10より小さくなくて,20より大きくなくて,15である" << endl;
}
else{
cout << "xは10より小さくなくて,20より大きくなくて,15でもない" << endl;
}
if(x >= 20){
cout << "xは20以上" << endl;
}
if(x == 5){
cout << "xは5" << endl;
}
if(x != 100){
cout << "xは100ではない" << endl;
}
if(!(x == y)){
cout << "xとyは等しくない" << endl;
}
if (x == 10 && y == 10){
cout << "xとyは10" << endl;
}
if(x==10 || y==10){
cout << "xかyは10" << endl;
}
cout << "終了" << endl;
} | true |
6c4ff3b0123103376552c7ad5aad687fd8206344 | C++ | jackytop/VARE | /base/header/DenseField2D.h | UTF-8 | 2,844 | 2.734375 | 3 | [] | no_license | //----------------//
// DenseField2D.h //
//-------------------------------------------------------//
// author: Wanho Choi @ Dexter Studios //
// Jaegwang Lim @ Dexter Studios //
// Julie Jang @ Dexter Studios //
// last update: 2018.04.25 //
//-------------------------------------------------------//
#ifndef _BoraDenseField2D_h_
#define _BoraDenseField2D_h_
#include <Bora.h>
BORA_NAMESPACE_BEGIN
template <class T>
class DenseField2D : public Grid2D, public Array<T>
{
public:
DenseField2D( const MemorySpace memorySpace=kHost )
{
DenseField2D::initialize( Grid2D(), memorySpace );
}
void initialize( const Grid2D& grid, MemorySpace memorySpace=kHost )
{
Grid2D::operator=( grid );
Array<T>::initialize( grid.numCells(), memorySpace );
}
void setGrid( const Grid2D& grid )
{
Grid2D::operator=( grid );
Array<T>::resize( grid.numCells() );
}
BORA_FUNC_QUAL
T& operator()( const size_t i, const size_t j )
{
const size_t index = Grid2D::cellIndex( i, j );
return Array<T>::operator[]( index );
}
BORA_FUNC_QUAL
const T& operator()( const size_t i, const size_t j ) const
{
const size_t index = Grid2D::cellIndex( i, j );
return Array<T>::operator[]( index );
}
BORA_FUNC_QUAL
T lerp( const Vec2f& p /*voxel space*/ ) const
{
const size_t i = Clamp( size_t(p.x-0.5f), (size_t)0, _nx-2 );
const size_t j = Clamp( size_t(p.y-0.5f), (size_t)0, _ny-2 );
const Vec2f corner = Grid2D::cellCenter( i, j );
const float x = Clamp( (p.x - corner.x), 0.f, 1.f );
const float y = Clamp( (p.y - corner.y), 0.f, 1.f );
const DenseField2D<T>& f = (*this);
const T c00 = f(i, j )*(1.f-x) + f(i+1, j )*x;
const T c10 = f(i, j+1 )*(1.f-x) + f(i+1, j+1 )*x;
return c00*(1.f-y) + c10*y;
}
BORA_FUNC_QUAL
T catrom( const Vec3f& p /*voxel space*/ ) const
{
return T(0);
}
DenseField2D<T>& operator=( const DenseField2D<T>& field )
{
Grid2D::operator=( field );
Array<T>::operator=( field );
return (*this);
}
bool swap( DenseField2D<T>& field )
{
if( Grid2D::operator!=( field ) )
{
COUT << "Error@DenseField2D::exchange(): Grid2D mismatch." << ENDL;
return false;
}
Array<T>::swap( field );
return true;
}
};
BORA_NAMESPACE_END
#endif
| true |
e1f210f6d579bd871ccaafa95f6fa3ce5d5bdaea | C++ | dbowker/othello | /setupBoard.cpp | UTF-8 | 646 | 2.546875 | 3 | [] | no_license | /*
* File: setupBoard
* Author: dan bowker
* Project: othello
*
* setup the initial state of the board.
*
* Created on February 7, 2012, 7:30 PM
*/
#include "othello.h"
void setupBoard(char b[BS]) {
int i;
for (i = 0; i < BS; i++)
b[i] = ' ';
b[bsToAi(4,4)] = C;
b[bsToAi(5,5)] = C;
b[bsToAi(4,5)] = H;
b[bsToAi(5,4)] = H;
/*
b[62] = H;
b[73] = H;
b[63] = C;
b[72] = C;
*/
// xppppppppp112345678p212345678p312345678p412345678p512345678p612345678p712345678p812345678pxppppppppx
// strncpy(b," O XO OO XOOOO XO OO O O ",BS);
}
| true |
0722a52ee74ec2f817440a3c1c7e712107a5b43b | C++ | RoberInside/TPV | /P2/ProyectosSDL/HolaSDL/Texture.h | UTF-8 | 581 | 2.859375 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
using uint = unsigned int;
class Texture
{
public:
Texture();
~Texture();
bool loadTexture(SDL_Renderer* renderer, std::string const& path, uint rows, uint cols);
void render(SDL_Renderer* renderer, const SDL_Rect& desRect);
void renderFrame(SDL_Renderer* renderer, const SDL_Rect& destRect, uint row, uint col);
uint getFrameWidth() { return frameWidth; };
uint getFrameHeight() { return frameHeight; };
private:
SDL_Texture *texture;
uint frameWidth;
uint frameHeight;
};
| true |
7e7bbdf6ff99bb86f402150ec618730753ec3b37 | C++ | Longseabear/AlgorithmStudy | /2583.cpp | UTF-8 | 1,243 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int map[102][102];
vector<int> rv;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
void setMap(int sx, int sy, int ex, int ey) {
for (int i = sy; i <= ey; i++) {
for (int j = sx; j <= ex; j++) {
map[i][j] = 0;
}
}
}
int main() {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
map[i][j] = 1;
while (k--) {
int sx, sy, ex, ey;
scanf("%d %d %d %d", &sx, &sy, &ex, &ey);
setMap(sx + 1, sy + 1, ex, ey);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (map[i][j] == 1) {
int res = 1;
map[i][j] = 0;
queue<pair<int,int>> q;
q.push(pair<int, int>(i, j));
while (!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
if (map[cur.first + dy[k]][cur.second + dx[k]] == 1) {
res++;
map[cur.first + dy[k]][cur.second + dx[k]] = 0;
q.push(pair<int, int>(cur.first + dy[k], cur.second + dx[k]));
}
}
}
rv.push_back(res);
}
}
}
printf("%d\n", rv.size());
sort(rv.begin(), rv.end());
for (int k : rv) {
printf("%d ", k);
}
} | true |
a50e645100801b70782f7187ae93039d83e86cbd | C++ | Tim-Paik/cpp | /date/20210613/成绩.cpp | UTF-8 | 330 | 3.171875 | 3 | [] | no_license | //平均数 最大值 最小值
#include<iostream>
using namespace std;
int a[5];
int main() {
for(int i=0;i<5;i++)
cin >> a[i];
cout << (a[0]+a[1]+a[2]+a[3]+a[4])/5 << " ";
int max=0,min=a[0];
for(int i=0;i<5;i++) {
max = max>a[i]?max:a[i];
min = min<a[i]?min:a[i];
}
cout << max << " " << min << endl;
return 0;
}
| true |
e3da7daf05e3fe9595932393b56b48ef1e586efb | C++ | patches11/djcontroller | /djController.ino | UTF-8 | 3,754 | 2.5625 | 3 | [] | no_license | #include <Bounce.h> // Bounce library makes button change detection easy
#include <Encoder.h>
const int channel = 1;
const int debounce = 5;
const int buttonVel = 127;
const int numButtons = 28;
const int analogChange = 2;
int muxChannel[16][4]={
{0,0,0,0}, //channel 0
{1,0,0,0}, //channel 1
{0,1,0,0}, //channel 2
{1,1,0,0}, //channel 3
{0,0,1,0}, //channel 4
{1,0,1,0}, //channel 5
{0,1,1,0}, //channel 6
{1,1,1,0}, //channel 7
{0,0,0,1}, //channel 8
{1,0,0,1}, //channel 9
{0,1,0,1}, //channel 10
{1,1,0,1}, //channel 11
{0,0,1,1}, //channel 12
{1,0,1,1}, //channel 13
{0,1,1,1}, //channel 14
{1,1,1,1} //channel 15
};
int controlPin[] = {14, 15, 16, 17}; //set contol pins in array
int buttonPins[numButtons] = {
//top
4, 5, 7, 8, 9, 10,
//red
11, 12, 13, 20, 21,
//bottom
39, 38, 27, 26, 22, 23, 24, 25,
//encoder 40 41 not working
40, 41, 42,
//Flick
43, 44,
28, 29,
30, 31
};
Encoder encs[3] = {Encoder(0, 1), Encoder(2, 3), Encoder(18, 19)};
long encPos[3] = {0, 0, 0};
Bounce buttons[numButtons] = {Bounce(4, debounce), Bounce(5, debounce), Bounce(7, debounce), Bounce(8, debounce), Bounce(9, debounce), Bounce(10, debounce),
Bounce(11, debounce), Bounce(12, debounce), Bounce(13, debounce), Bounce(20, debounce), Bounce(21, debounce),
Bounce(39, debounce), Bounce(38, debounce), Bounce(27, debounce), Bounce(26, debounce), Bounce(22, debounce), Bounce(23, debounce), Bounce(24, debounce), Bounce(25, debounce),
Bounce(40, debounce), Bounce(41, debounce), Bounce(42, debounce),
Bounce(43, debounce), Bounce(44, debounce),
Bounce(28, debounce), Bounce(29, debounce),
Bounce(30, debounce), Bounce(31, debounce) };
int SIG_pin = 45; //read pin
int potVal[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int readMux(int channel){
//loop through the four control pins
for(int i = 0; i < 4; i ++){
//turn on/off the appropriate control pins according to what channel we are trying to read
digitalWrite(controlPin[i], muxChannel[channel][i]);
}
//read the value of the pin
int val = analogRead(SIG_pin);
//return the value
return val;
}
void setup() {
Serial.begin(31250);//open serail port @ midi speed
for(int i=0;i<numButtons;i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SIG_pin,INPUT);
//set our control pins to output
for (int i = 0;i<4;i++) {
pinMode(controlPin[i],OUTPUT);
digitalWrite(controlPin[i],LOW);
}
}
void loop() {
for(int i=0;i<numButtons;i++) {
buttons[i].update();
// Note On messages when each button is pressed
if (buttons[i].fallingEdge()) {
usbMIDI.sendNoteOn(i+60, buttonVel, channel); // 62 = D4
}
// Note Off messages when each button is released
if (buttons[i].risingEdge()) {
usbMIDI.sendNoteOff(i+60, 0, channel); // 60 = C4
}
}
//encoders
for(int i = 0;i<3;i++) {
long newVal;
newVal = encs[i].read();
if (newVal > encPos[i]) {
usbMIDI.sendNoteOn(i,127,127);
encPos[i] = newVal;
}
if (newVal < encPos[i]) {
usbMIDI.sendNoteOn(i,1,127);
encPos[i] = newVal;
}
}
//Analog
for(int i = 0;i<16;i++) {
int tempa = readMux(i);
if (tempa <= analogChange) {
tempa = 0;
}
if (tempa >= 1023 - analogChange) {
tempa = 1023;
}
if (abs(tempa - potVal[i]) > analogChange || (tempa == 0 && potVal[i] != 0)) {
potVal[i] = tempa;
usbMIDI.sendPitchBend(map(tempa,0,1023,0,16363),i);
}
}
}
// MIDI Controllers should discard incoming MIDI messages.
//while (usbMIDI.read()) {
//}
//}
| true |
cebba2e04149c6216a3c244e3a8c654baf4810b5 | C++ | WolfCub15/Systems_of_Linear_Equations | /SLE/methods.cpp | UTF-8 | 6,926 | 3.125 | 3 | [] | no_license | #include "methods.h"
void printMatrixA(const vector<vector<double>> &A) {
for (int i = 0; i < A.size(); ++i) {
for (int j = 0; j < A[0].size(); ++j) {
cout << A[i][j] << ' ';
}
cout << '\n';
}
}
void printAnsX(const vector<double>& x){
for (int i = 0; i < x.size(); ++i) {
cout << fixed << setprecision(10) << "x" << i << " : " << x[i] << '\n';
}
cout << '\n';
}
vector<vector<double>> inputMatrixA(int n) {
vector<vector<double>> A(n, vector<double>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> A[i][j];
}
}
return A;
}
vector<double> inputB(int n) {
vector<double> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
return v;
}
vector<vector<double>> randomMatrixA(int n) {
mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
vector<vector<double>> A(n, vector<double>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
double val = gen() % 100;
if (i == j) A[i][j] = val * 99 * n + 1234;
else A[i][j] = val;
}
}
return A;
}
vector<double> randomB(int n) {
mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
vector<double> vec(n);
for (int i = 0; i < n; ++i) {
vec[i] = gen() % 100 + 123 * n;
}
return vec;
}
void makeBeautifulMatrix(vector<vector<double>> & a, vector<double>& b, double eps){
int n = a.size();
for (int i = 0; i < n; ++i) {
double ma = fabs(a[i][i]);
int ind = i;
for (int j = i + 1; j < n; ++j) {
if (fabs(a[j][i]) > ma + eps) {
ma = fabs(a[j][i]);
ind = j;
}
}
swap(a[i], a[ind]);
swap(b[i], b[ind]);
}
}
double determinant(vector<vector<double>> A) {
double det = 1;
const double EPS = 1e-9;
for (int i = 0; i < A.size(); ++i) {
int k = i;
for (int j = i + 1; j < A.size(); ++j) {
if (abs(A[j][i]) > abs(A[k][i]))
k = j;
}
if (abs(A[k][i]) < EPS) {
det = 0;
break;
}
swap(A[i], A[k]);
if (i != k) {
det = -det;
}
det *= A[i][i];
for (int j = i + 1; j < A.size(); ++j) {
A[i][j] /= A[i][i];
}
for (int j = 0; j < A.size(); ++j) {
if (j != i && abs(A[j][i]) > EPS) {
for (int k = i + 1; k < A.size(); ++k) {
A[j][k] -= A[i][k] * A[j][i];
}
}
}
}
return det;
}
vector<double> cramer(const vector<vector<double>>& A, const vector<double>& b, double eps, int& iterations) {
vector<double> x;
x.reserve(b.size());
double det = determinant(A);
vector<double> ds;
ds.reserve(b.size());
if (fabs(det) > 1e-9) {
for (int i = 0; i < (int)A.size(); ++i) {
vector<vector<double>> tmp = A;
for (int j = 0; j < tmp.size(); ++j)
tmp[j][i] = b[j];
ds.push_back(determinant(tmp));
}
}
else cout << "The system has infinitely many solutions or is incompatible\n";
for (double di : ds) {
double ans = di / det;
x.push_back(ans);
}
return x;
}
vector<double> gauss(vector<vector<double>> A, vector<double> b, double eps, int& iterations) {
int n = A.size();
vector<double> x(n, 0);
for (int q = 0; q < n; ++q) {
for (int i = q + 1; i < n; ++i) {
double k = A[i][q] / A[q][q];
for (int j = q; j < n; ++j) {
A[i][j] -= k * A[q][j];
}
b[i] -= k * b[q];
}
}
x[n - 1] = b[n - 1] / A[n - 1][n - 1];
for (int i = n - 2; i >= 0; --i) {
double sum = 0;
for (int j = i + 1; j < n; ++j) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
}
double converge(const vector<vector<double>>& A, const vector<double>& x, const vector<double>& b) {
double ans = 0;
int n = A.size();
for (int i = 0; i < n; ++i) {
double sum = 0;
for (int j = 0; j < n; ++j) {
sum += A[i][j] * x[j];
}
ans += pow(b[i] - sum, 2);
}
return sqrt(ans);
}
vector<double> simpleIteration(const vector<vector<double>>& A, const vector<double>& b, double eps, int &count) {
int size = b.size();
vector<double> x(size, 0);
while (true) {
count++;
if (count >= 500) break;
vector<double> currentVariableValues = b;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) if (i != j) {
currentVariableValues[i] -= A[i][j] * x[j];
}
currentVariableValues[i] /= A[i][i];
}
if (converge(A, x, b) < eps) {
break;
}
x = currentVariableValues;
}
return x;
}
vector<double> seidel(const vector<vector<double>>& A, const vector<double>& b, double eps, int &count) {
int n = A.size();
vector<double> x(n,0),pr(n,0);
int max_count = 500;
do {
for (int i = 0; i < n; ++i) {
x[i] = 0;
double sum = 0;
for (int j = 0; j < n; ++j) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
}
count++;
max_count--;
} while (converge(A, x, b) >= eps && max_count);
return x;
}
vector<double> relaxation(const vector<vector<double>>& A, const vector<double>& b, double eps,int &count) {
int n = A.size();
vector<double> x(n, 0), xn(n, 0);
int max_count = 500;
mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
double w = (100 + gen() % 100);
w /= 100;
do {
for (int i = 0; i < n; ++i) {
x[i] = b[i];
double sum = 0;
for (int j = 0; j < n; ++j) {
if(i!=j) x[i]-= A[i][j] * x[j];
}
x[i] /= A[i][i];
x[i] = w * x[i] + xn[i] - xn[i] * w;
xn[i] = x[i];
}
count++;
max_count--;
} while (converge(A, x, b) >= eps && max_count);
return x;
}
vector<double> jacobi(const vector<vector<double>>& A, const vector<double>& b, double eps, int& count) {
int n = A.size();
vector<double> x(n, 0);
vector<double> x0 = b;
int max_count = 500;
count = 0;
do {
for (int i = 0; i < n; ++i) {
x[i] = b[i];
for (int j = 0; j < n; ++j) {
if (i != j) {
x[i] -= A[i][j] * x0[j];
}
}
x[i] /= A[i][i];
x0 = x;
}
count++;
max_count--;
} while (converge(A, x, b) >= eps && max_count);
return x;
}
| true |
402d2de9aa4493518642f2e00e01e786508e0c83 | C++ | IgorYunusov/Mega-collection-cpp-1 | /CPP_cookbok_source/10-9.cpp | UTF-8 | 733 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
const static int BUF_SIZE = 4096;
using std::ios_base;
int main(int argc, char** argv)
{
std::ifstream in(argv[1],
ios_base::in | ios_base::binary); // Use binary mode so we can
std::ofstream out(argv[2], // handle all kinds of file
ios_base::out | ios_base::binary); // content.
// Make sure the streams opened okay...
char buf[BUF_SIZE];
do {
in.read(&buf[0], BUF_SIZE); // Read at most n bytes into
out.write(&buf[0], in.gcount()); // buf, then write the buf to
} while (in.gcount() > 0); // the output.
// Check streams for problems...
in.close();
out.close();
} | true |
8112905ca237134ad921112539a0ffdab64180c8 | C++ | gs0622/leetcode | /combinations.cc | UTF-8 | 671 | 3.109375 | 3 | [] | no_license | /* https://leetcode.com/problems/combinations/description/
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
void helper(int n, int i, int k, vector<int>&cmb, vector<vector<int>>& res) {
if (k==0) {
res.push_back(cmb);
return;
}
for (int j=i; j<=n; ++j) {
cmb.push_back(j);
helper(n, j+1, k-1, cmb, res);
cmb.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
vector<int> cmb;
vector<vector<int>> res;
int i=1;
helper(n, i, k, cmb, res);
return res;
}
};
int main(){
Solution s;
vector<vector<int>> res = s.combine(4,2);
for (auto x: res) {
for (auto y: x) cout << y << " ";
cout << endl;
}
}
| true |
9e8efbe62ca86751b3db96eb73669788c43c3b68 | C++ | 15831944/Utility | /Network/SocketChannel.h | UTF-8 | 1,938 | 2.765625 | 3 | [] | no_license | /*
* File: SocketChannel.h
* Author: 0007989
*
* Created on 2014年1月27日, 上午 11:03
*/
#ifndef UTILITY_SOCKETCHANNEL_H
#define UTILITY_SOCKETCHANNEL_H
#include <mutex>
#include "SocketBase.h"
namespace KGI_TW_Der_Utility
{
///
/// SocketChannel
/// Use socket TCP protocol to communicate
///
/// After client connect to a SocketServer, SocketServer will create a SocketChannel and notify
/// SocketServerListener to receive the new connected client.
/// \sa SocketServer,SocketChannel,SocketServerListener
class SocketChannel : public SocketBase {
public:
SocketChannel( int socketID );
SocketChannel(const SocketChannel& orig);
virtual ~SocketChannel();
void Close(){ Disconnect(); }
// \param timeoutUS in us unit, 0 => disable timeout
// \return 0 => success
int SetWriteTimeout( int timeoutUS );
PROP_GETSET_BYVALUE( int, WriteTryCounts, m_WriteTryCounts );
// \param timeoutUS in us unit, 0 => disable timeout
// \return 0 => success
int SetReadTimeout( int timeoutUS );
virtual int Read( char *pBuffer, int bufferSize, int startPos );
virtual int Write( const char *pBuffer, int bufferSize );
/// \brief 配合設定 recv timieout的模式來讀取資料
/// 需先呼叫 SetReadTimeout() 設定接收資料的timeout時間
/// \param pIsTimeout 傳回此次接收結果是否為timieout。如果為timeout時,傳回的接收資料數一般都是-1
/// \return 傳回已接收到的資料數
virtual int Read( char *pBuffer, int bufferSize, int startPos, bool* pIsTimeout );
protected:
mutable std::mutex m_Object; //!< lock for synchronize socket access
int m_WriteTryCounts; //!< the maximum times for retry send()
protected:
/// Initialize the information of socket, such as remote ip and port
void InitInfo();
};
}
#endif /* UTILITY_SOCKETCHANNEL_H */
| true |
37a90acd7e2c455e6098835bfe721532ee6d53b0 | C++ | Hackerifyouwant/IIM_Judge | /answer_code/PN.cpp | UTF-8 | 763 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int main(){
int n, m, cnt;
cin >> n >> m >> cnt;
vector< vector <int > > martix(n, vector<int>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> martix[i][j];
}
}
cnt %= 4;
for(int s = 0; s < cnt; s++){
vector< vector<int> >new_martix(m, vector<int>(n));
for(int i = m - 1, k = 0; i >= 0 && k < m; i--, k++){
for(int j = 0; j < n; j++){
new_martix[k][j] = martix[j][i];
}
}
swap(n , m);
martix = new_martix;
}
for(auto c : martix){
for(auto g : c){
cout << g << " ";
}
cout << endl;
}
return 0;
} | true |
d696561e447e2017d94cdfb37791a580f07c1208 | C++ | viveksinghvi/Competitive-Coding-Playbook | /sortComparison/main.cpp | UTF-8 | 1,172 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool way (vector<int>a,vector <int>b ){
if (a[0]==b[0]){
if (a[2]==b[2]){
return a[1]<b[1];
}
return a[2]<b[2];
}
return a[0]<b[0];
}
int main()
{
int n,time,stile,scost,cost,tile;
long d;
cin >>n>>d;
vector <vector<int> > a(n,vector<int>(3));
for (int i=0;i<n;i++){
for (int j=0;j<3;j++){
cin >>a[i][j];
}
}
sort(a.begin(),a.end(),way);
time=a[0][0];
stile=a[0][2];
scost=a[0][1];
tile=0;
cost=0;
for (int i=0;i<n;i++){
if (a[i][0]>time){
if (tile+stile*(a[i][0]-time)>=d){
cost=cost+scost*((d-tile)/stile ==0?((d-tile)/stile):((d-tile)/stile+1));
break;
}
else {
cost+=scost*(a[i][0]-time);
}
if (a[i][2]>stile){
stile=a[i][2];
scost=a[i][1];
}
time=a[i][0];
}
}
cout<<cost<<endl;
return 0;
}
| true |
cad914d998c8705abce0d71b53a77a8bf97c982a | C++ | rising-stark/Competitive-Questions | /Hackerearth/Micro_and_Prime_Prime.cpp | UTF-8 | 6,069 | 3.140625 | 3 | [] | no_license | /*
The function to look up for the logic/solution is void solve() at the bottom.
Above the solve function is main function which calls the solve function simply.
https://www.hackerearth.com/practice/math/number-theory/primality-tests/practice-problems/algorithm/micro-and-prime-prime-1/description/
Problem Description:
Micro just learned about prime numbers. But he quickly got bored of them, so he defined a new kind of numbers and called them Prime Prime Numbers.
A number X is Prime Prime if number of prime numbers from 1 to X (inclusive) are prime.
Now he wants to find out the number of Prime Prime numbers from L to R (inclusive). Help Micro with it.
Input:
First line consists of a single integer T denoting number of test cases
Following T lines consists of two space separated integers denoting L and R
Output:
Print the number of Prime Prime Numbers for each between L and R for each test case in a new line.
Constraints:
1 <= T <= 10^5
1 <= L, R <= 10^6
Sample Input:
2
3 10
4 12
SAMPLE OUTPUT
4
5
Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
*/
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
#define ALL(x) x.begin(), x.end()
#define maxx(a,b,c) max(a, max(b,c))
#define minn(a,b,c) min(a, min(b,c))
using namespace std;
const int mod=1e9+7;
const int inf = (1<<30);
string toBin(ll a);
void printMat(int arr[], int n);
void printMat(vector<int> arr, int n);
void printMat(vector<vector<int> > arr, int n, int m);
void printMat(vector<int> arr[], int n);
void solve();
//void printMat(int arr[][], int n, int m);
void printMap(unordered_map<int, int> mp);
void printMap(unordered_map<ll, ll> mp);
void printMap(unordered_map<char, int> mp);
void printMap(unordered_map<string, int> mp);
void printMap(map<int, int> mp);
void printMap(map<ll, ll> mp);
void printMap(map<char, int> mp);
void printMap(map<string, int> mp);
void printSet(set<int> s);
void printSet(set<ll> s);
void printSet(set<char> s);
void printSet(set<string> s);
void printSet(unordered_set<int> s);
void printSet(unordered_set<ll> s);
void printSet(unordered_set<char> s);
void printSet(unordered_set<string> s);
string toBin(ll a){
string s="";
while(a>0){
if(a&1){
s="1"+s;
}else{
s="0"+s;
}
a>>=1;
}
return s;
}
void printMat(int arr[], int n){
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}cout<<endl;
}
void printMat(vector<int> arr, int n){
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}cout<<endl;
}
void printMat(vector<int> arr[], int row, int col){
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<arr[i][j]<<" ";
}cout<<endl;
}cout<<endl;
}
void printMat(vector<vector<int> > arr, int row, int col){
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<arr[i][j]<<" ";
}cout<<endl;
}cout<<endl;
}
void printMap(unordered_map<int, int> mp){
unordered_map<int, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(unordered_map<ll, ll> mp){
unordered_map<ll, ll>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(unordered_map<char, int> mp){
unordered_map<char, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(unordered_map<string, int> mp){
unordered_map<string, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(map<int, int> mp){
map<int, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(map<ll, ll> mp){
map<ll, ll>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(map<char, int> mp){
map<char, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printMap(map<string, int> mp){
map<string, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" -->"<<it->second<<endl;
}
cout<<endl;
}
void printSet(set<int> s){
set<int>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
void printSet(set<ll> s){
set<ll>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
void printSet(set<char> s){
set<char>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it);
}cout<<endl;
}
void printSet(set<string> s){
set<string>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
void printSet(unordered_set<int> s){
unordered_set<int>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
void printSet(unordered_set<ll> s){
unordered_set<ll>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
void printSet(unordered_set<char> s){
unordered_set<char>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it);
}cout<<endl;
}
void printSet(unordered_set<string> s){
unordered_set<string>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<(*it)<<" ";
}cout<<endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
int t;
//cin>>t;
t=1;
while(t--){
solve();
}
return 0;
}
void solve(){
int i, j, n;
n=1000000;
bitset<1000001> arr(0);
std::vector<int> prime;
unordered_set<int> s;
arr[0]=arr[1]=1;
for(i=2;i*i<=n;i++){
if(arr[i]==1)
continue;
for(j=i*i;j<=n;j+=i){
arr[j]=1;
}
}
int c=0;
for(i=1;i<=n;i++){
if(arr[i]==0){
c++;
s.insert(i);
}
if(s.find(c)!=s.end()){
prime.pb(i);
}
}
//printMat(prime, prime.size());
int t;
cin>>t;
while(t--){
int l, r;
cin>>l>>r;
cout<<upper_bound(prime.begin(), prime.end(), r)-upper_bound(prime.begin(), prime.end(), l-1)<<endl;
}
}
| true |
271242bd0218a482fab1e2d5225aed3a6cfb250e | C++ | namhong2001/Algo | /aoj/jlis.cpp | UTF-8 | 1,164 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <limits>
#include <algorithm>
using namespace std;
const int N_MAX = 100;
const long long NEGINF = numeric_limits<long long>::min();
int A[N_MAX];
int B[N_MAX];
int cache[N_MAX+1][N_MAX+1];
int n, m;
int solve(int a_pos, int b_pos) {
int &ret = cache[a_pos+1][b_pos+1];
if (ret == -1) {
long long a = a_pos == -1 ? NEGINF : A[a_pos];
long long b = b_pos == -1 ? NEGINF : B[b_pos];
long long max_elem = max(a, b);
ret = 2;
for (int i=a_pos+1; i<n; ++i) {
if (A[i] > max_elem) {
ret = max(ret, solve(i, b_pos)+1);
}
}
for (int i=b_pos+1; i<m; ++i) {
if (B[i] > max_elem) {
ret = max(ret, solve(a_pos, i)+1);
}
}
}
return ret;
}
int main() {
int c;
cin >> c;
while (c--) {
cin >> n >> m;
memset(cache, -1, sizeof(cache));
for (int i=0; i<n; ++i) {
cin >> A[i];
}
for (int i=0; i<m; ++i) {
cin >> B[i];
}
cout << solve(-1, -1) - 2 << endl;
}
return 0;
}
| true |
a0e0963ad6ca77428bb326d6c63735f7d2e0022a | C++ | arthurarp/Maratonas-de-programacao | /tep/3 - /contest/B/b.cpp | UTF-8 | 451 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(void)
{
int N;
cin >> N;
if (N % 4 == 0 || N % 7 == 0)
{
cout << "Yes\n";
return 0;
}
else
for (int four = 1; four < 100; ++four)
{
for (int seven = 1; seven < 100; ++seven)
{
int sum = 4 * four + 7 * seven;
if (sum == N)
{
cout << "Yes\n";
return 0;
}
}
}
cout << "No\n";
return 0;
} | true |
b516461b8ea70673f8850dabb44638ad360ab3b8 | C++ | tewarig/OOP-With-CPP-assignments | /assignment-1/answer1.cpp | UTF-8 | 534 | 4.0625 | 4 | [] | no_license | //To find greatest of three numbers.
#include <iostream>
using namespace std;
#define INT_MIN -2147483627 ;
int findMax(int num1,int num2,int num3){
int min = INT_MIN;
if(num1>min)
{
min = num1;
}
if(num2>min)
{
min = num2;
}
if(num3>min)
{
min = num3;
}
return min;
}
int main()
{
int num1,num2,num3;
cout<<"Please, enter three numbers"<<"\n";
cin>>num1>>num2>>num3;
int max = findMax(num1,num2,num3);
cout<<"the max number is: ";
cout<<max;
return 0;
}
| true |
8ab29624f9913829ea29f04d14aae02375ec8c0d | C++ | HNSS-US/DelTech | /CSC/CSC114/GaddisExamples/Chapter10/Pr10-10.cpp | UTF-8 | 1,083 | 4.1875 | 4 | [
"MIT"
] | permissive | // This program demonstrates the tolower and stoi functions.
#include <iostream>
#include <cctype> // For tolower
#include <string>
using namespace std;
int main()
{
string input; // To hold user input
int total = 0; // Accumulator
int count = 0; // Loop counter
double average; // To hold the average of numbers
// Get the first number.
cout << "This program will average a series of numbers.\n";
cout << "Enter the first number or Q to quit: ";
getline(cin, input);
// Process the number and subsequent numbers.
while (tolower(input[0]) != 'q')
{
total += stoi(input); // Keep a running total
count++; // Count the numbers entered
// Get the next number.
cout << "Enter the next number or Q to quit: ";
getline(cin, input);
}
// If any numbers were entered, display their average.
if (count != 0)
{
average = static_cast<double>(total) / count;
cout << "Average: " << average << endl;
}
return 0;
} | true |
17b66a8207581f0e42635c00382b9cf9d7d3bf0b | C++ | bogdan-kovalchuk/June-leetcoding-challenge | /day_28.cpp | UTF-8 | 1,338 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <set>
#include <stack>
#include <algorithm>
using std::vector;
using std::string;
using std::unordered_map;
using std::multiset;
using std::stack;
class Solution {
public:
vector<string> findItinerary(vector<vector<string>> &tickets) {
unordered_map<string, multiset<string>> g;
vector<string> itinerary;
if (tickets.empty()) return itinerary;
for (auto t : tickets) g[t[0]].insert(t[1]);
stack<string> dfs;
dfs.push("JFK");
while (!dfs.empty()) {
string airport = dfs.top();
if (g[airport].empty()) {
itinerary.push_back(airport);
dfs.pop();
} else {
dfs.push(*(g[airport].begin()));
g[airport].erase(g[airport].begin());
}
}
std::reverse(itinerary.begin(), itinerary.end());
return itinerary;
}
};
int main() {
vector<vector<string>> tickets = {{"MUC", "LHR"},
{"JFK", "MUC"},
{"SFO", "SJC"},
{"LHR", "SFO"}};
Solution solution = Solution();
vector<string> res = solution.findItinerary(tickets);
return 0;
}
| true |
d4e578d5013622c6ca5a372e24e2cf2704458b4b | C++ | xiaopeng-whu/Calculator-complier | /Calculator/Calculator/MyStack.h | GB18030 | 1,036 | 3.90625 | 4 | [] | no_license | #pragma once
#include <iostream>
#define MAX 100
using namespace std;
template <class T>
class MyStack
{
public:
T data[MAX];
int top;
public:
void init(); // ʼջ
bool empty(); // жջǷΪ
T getTop(); // ȡջԪ(ջ)
void push(T x); // ջ
T pop(); // ջ
};
template<class T>
void MyStack<T>::init()
{
this->top = 0;
}
template<class T>
bool MyStack<T>::empty()
{
return this->top == 0 ? true : false;
}
template<class T>
T MyStack<T>::getTop()
{
if (empty())
{
cout << "ջΪգ\n";
exit(1);
}
return this->data[this->top - 1];
}
template<class T>
void MyStack<T>::push(T x)
{
if (this->top == MAX)
{
cout << "ջ\n";
exit(1);
}
this->data[this->top] = x;
this->top++;
}
template<class T>
T MyStack<T>::pop()
{
if (this->empty())
{
cout << "ջΪ! \n";
exit(1);
}
T e = this->data[this->top - 1];
this->top--;
return e;
}
| true |
35125973400f0fbb4079899cb005b08e35bfb580 | C++ | lanpham09/OmniFrameExecutable | /OmniFrame3/Configuration5DOF_Producer.cpp | UTF-8 | 6,652 | 2.78125 | 3 | [] | no_license | #include "Producers/Configuration5DOF_Producer.h"
Configuration5DOF_Producer::Configuration5DOF_Producer( std::string name, distanceUnits units, Math::Frame in_frame, unsigned int historyLength ):
PositionProducer(name, units, in_frame, historyLength)
{
_constPosition = Math::Position(Math::Zero(),in_frame,units);
_direction = Math::Direction(0,0,1, in_frame );
p_positionProducer = 0;
p_DirectionProducer = 0;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( const Math::Configuration5DOF& config, std::string name):
PositionProducer(name,config.getUnits(),config.getFrame(),1)
{
PositionProducer::asPositionHistoryPointer()->append(config.position().asVector());
_constPosition = config.position();
_direction = config.direction();
assert( _constPosition.getFrame() == _direction.getFrame() );
p_positionProducer = 0;
p_DirectionProducer = 0;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( const Math::Position& pos, const Math::Direction& dir, std::string name):
PositionProducer(name,pos.getUnits(),pos.getFrame(),1)
{
PositionProducer::asPositionHistoryPointer()->append(pos.asVector());
_constPosition = pos;
_direction = dir;
assert( _constPosition.getFrame() == _direction.getFrame() );
p_positionProducer = 0;
p_DirectionProducer = 0;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( PositionProducer* pProducer, const Math::Direction& dir )
{
_constPosition = Math::Position();
_direction = dir;
p_positionProducer = pProducer;
p_DirectionProducer = 0;
assert( pProducer->getFrame() == _direction.getFrame() );
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( const Math::Position& pos, DirectionProducer* pdir, std::string name):
PositionProducer(name,pos.getUnits(),pos.getFrame(),1)
{
PositionProducer::asPositionHistoryPointer()->append(pos.asVector());
_constPosition = pos;
_direction = Math::Direction();
p_positionProducer = 0;
p_DirectionProducer = pdir;
assert( _constPosition.getFrame() == p_DirectionProducer->getFrame() );
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( PositionProducer* pProducer, DirectionProducer* oProducer )
{
_constPosition = Math::Position();
_direction = Math::Direction();
p_positionProducer = pProducer;
p_DirectionProducer = oProducer;
assert( p_positionProducer->getFrame() == p_DirectionProducer->getFrame() );
this->_p_positionHistory->appendIfChanged(_constPosition);
}
Configuration5DOF_Producer::Configuration5DOF_Producer( const Configuration5DOF_Producer& other ):
PositionProducer(other), DirectionProducer(other)
{
_constPosition = other._constPosition;
p_positionProducer = other.p_positionProducer;
p_DirectionProducer = other.p_DirectionProducer;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
bool Configuration5DOF_Producer::getConfiguration5DOF(Math::Configuration5DOF& pose)
{
bool retValue = true;
if( p_positionProducer != 0 )
retValue &= p_positionProducer->getPosition(_constPosition);
if( p_DirectionProducer != 0 )
retValue &= p_DirectionProducer->getDirection(_direction);
pose = Math::Configuration5DOF( _constPosition, _direction );
this->_p_positionHistory->appendIfChanged(_constPosition);
return retValue;
}
Math::Configuration5DOF Configuration5DOF_Producer::returnConfiguration5DOF()
{
Math::Configuration5DOF temp;
getConfiguration5DOF(temp);
return temp;
}
Math::Frame Configuration5DOF_Producer::getFrame() const
{
Math::Frame pFrame = _constPosition.getFrame();
Math::Frame dFrame = _direction.getFrame();
if( p_positionProducer != 0 )
pFrame = p_positionProducer->getFrame();
if( p_DirectionProducer != 0 )
dFrame = p_DirectionProducer->getFrame();
assert( pFrame == dFrame );
return pFrame;
}
bool Configuration5DOF_Producer::getPosition(Math::Position &position, distanceUnits units)
{
bool retValue = true;
if( p_positionProducer != 0 )
retValue &= p_positionProducer->getPosition(_constPosition);
this->_p_positionHistory->appendIfChanged(_constPosition);
position = _constPosition;
position.convertToUnits( units );
return retValue;
}
AD_IO::distanceSensorVector* Configuration5DOF_Producer::asPositionHistoryPointer() const
{
if( p_positionProducer != 0 )
return p_positionProducer->asPositionHistoryPointer();
return PositionProducer::asPositionHistoryPointer();
}
string Configuration5DOF_Producer::positionProducerName() const
{
if( p_positionProducer != 0 )
return p_positionProducer->positionProducerName();
return PositionProducer::positionProducerName();
}
distanceUnits Configuration5DOF_Producer::getUnits() const
{
if( p_positionProducer != 0 )
return p_positionProducer->getUnits();
return PositionProducer::getUnits();
}
bool Configuration5DOF_Producer::getDirection(Math::Direction& dir)
{
bool retValue = true;
if( p_DirectionProducer != 0 )
retValue &= p_DirectionProducer->getDirection(_direction);
dir = _direction;
return retValue;
}
void Configuration5DOF_Producer::setPosition(const Math::Position & newPos)
{
assert( newPos.getFrame() == getFrame() );
_constPosition = newPos;
p_positionProducer = 0;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
void Configuration5DOF_Producer::setPosition(PositionProducer* newPosProducer)
{
assert( newPosProducer->getFrame() == getFrame() );
p_positionProducer = newPosProducer;
}
void Configuration5DOF_Producer::setDirection(const Math::Direction & newDir)
{
assert( newDir.getFrame() == getFrame() );
_direction = newDir;
p_DirectionProducer = 0;
}
void Configuration5DOF_Producer::setDirection(DirectionProducer* newDirProducer)
{
assert( newDirProducer->getFrame() == getFrame() );
p_DirectionProducer = newDirProducer;
}
void Configuration5DOF_Producer::setConfiguration5DOF(const Math::Configuration5DOF& other)
{
_constPosition = other.position();
_direction = other.direction();
p_positionProducer = 0;
p_DirectionProducer = 0;
this->_p_positionHistory->appendIfChanged(_constPosition);
}
| true |
7508e225d608bf9e6a8fbe3020657612f161376b | C++ | ngtcs1989/Artificial-Intelligence | /Resolution Refutation/sammy.cpp | UTF-8 | 6,170 | 2.5625 | 3 | [] | no_license |
/////////////////////////////////////
// File Name :
// Purpose :
// Creation Date : 21-03-2015
// Last Modified : <modified_date>
// Created By : Naveen Thomas
//////////////////////////////////////
#include <string>
#include <vector>
#include <map>
#include <list>
#include <iterator>
#include <set>
#include <queue>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>
#define CLR(a, x) memset( a, x, sizeof( a ) )
using namespace std;
#define getcx getchar_unlocked
#define ULL unsigned long long
#define CL vector<string>
vector<CL > clauses;
set<CL> visited;
struct CL_PAIR
{
int i;
int j;
int pos_i;
int pos_j;
CL_PAIR(int x, int y, int p, int q)
{
i=x;
j=y;
pos_i = p;
pos_j = q;
}
bool operator<(const CL_PAIR& x) const
{
return min(clauses[i].size(), clauses[j].size()) > min(clauses[x.i].size(), clauses[x.j].size());
}
};
priority_queue<CL_PAIR> candidates;
map<int, pair<int, int> > parent;
void printClause(int x)
{
cout<<"(";
for(int i=0; i< clauses[x].size(); i++)
{
if(i!=0)
cout<<" v ";
cout<<clauses[x][i];
}
cout<<")";
cout<<"\n";
}
void printClauses()
{
for(int i=0; i< clauses.size(); i++)
{
printClause(i);
}
}
void printClause(CL& cl)
{
cout<<"(";
for(int i=0; i< cl.size(); i++)
{
if(i!=0)
cout<<" v ";
cout<<cl[i];
}
cout<<")";
}
bool cmpClauses(const string& x, const string& y)
{
string str1=x;
string str2=y;
if(x[0]=='-')
str1 = x.substr(1, x.length());
if(y[0]=='-')
str2 = y.substr(1, y.length());
if(str1==str2 && x[0]=='-')
return true;
if(str1==str2 && y[0]=='-')
return false;
return str1<str2;
}
void formCandidatePairs(int x, int y)
{
int i=0; int j=0;
while(i!=clauses[x].size() && j!=clauses[y].size())
{
string str1 = clauses[x][i]; string str2 = clauses[y][j];
if(clauses[x][i][0] == '-')
str1= clauses[x][i].substr(1, clauses[x][i].length());
if(clauses[y][j][0] == '-')
str2= clauses[y][j].substr(1, clauses[y][j].length());
if(str1<str2)
i++;
else if(str1>str2)
j++;
else
{
if((clauses[x][i][0]=='-'&& clauses[y][j][0]!='-') || (clauses[x][i][0]!='-'&& clauses[y][j][0]=='-'))
candidates.push(CL_PAIR(x,y,i,j));
i++; j++;
}
}
}
bool checkIfVisited(CL clause)
{
int size = clause.size();
for(int i=0; i< size; i++)
{
if(visited.find(clause)!= visited.end())
return true;
clause.pop_back();
}
return false;
}
void printPath(int cl, string space)
{
cout<<space<<cl<<": ";
printClause(clauses[cl]);
if(parent.find(cl) != parent.end())
{
cout<<" ["<<(parent.find(cl)->second).first<<","<<(parent.find(cl)->second).second<<"]\n";
space += " ";
printPath((parent.find(cl)->second).first, space);
printPath((parent.find(cl)->second).second, space);
}
else
cout<<" input\n";
}
bool resolve(CL_PAIR current)
{
#ifdef DEBUG
string proposition;
if(clauses[current.i][current.pos_i][0] == '-')
proposition = clauses[current.j][current.pos_j];
else
proposition = clauses[current.i][current.pos_i];
cout<<"[Qsize="<<candidates.size()<<"] "<<"resolving "<<current.i<<" and "<<current.j<<" on "<<proposition<<": ";
printClause(clauses[current.i]);
cout<<" and ";
printClause(clauses[current.j]);
//cout<<"###########################################\n";
//printClause(current.i);
//printClause(current.j);
//cout<<"Resolving on proposition: "<<clauses[current.i][current.pos_i]<<" "<<clauses[current.j][current.pos_j]<<"\n";
#endif
// form new clause by resolution
CL newClause;
set<string> seen;
for(int i=0; i<clauses[current.i].size(); i++)
{
if(i != current.pos_i)
{
newClause.push_back(clauses[current.i][i]);
seen.insert(clauses[current.i][i]);
}
}
for(int i=0; i<clauses[current.j].size(); i++)
{
if(i != current.pos_j && seen.find(clauses[current.j][i])==seen.end() )
newClause.push_back(clauses[current.j][i]);
}
if(newClause.size()==0)
{
clauses.push_back(newClause);
#ifdef DEBUG
cout<<" --> ";
printClause(clauses[clauses.size()-1]);
#endif
#ifdef DEBUG
cout<<"\n"<<clauses.size()-1<<": ";
printClause(clauses.size()-1);
#endif
parent.insert(make_pair(clauses.size()-1,make_pair(current.i, current.j)));
visited.insert(newClause);
cout<<"success - empty clause!\n";
cout<<"-------------------------\n";
cout<<"proof trace:\n";
printPath(clauses.size()-1, "");
return true;
}
sort(newClause.begin(), newClause.end(), cmpClauses);
//if(visited.find(newClause) == visited.end())
if(!checkIfVisited(newClause))
{
clauses.push_back(newClause);
#ifdef DEBUG
cout<<" --> ";
printClause(clauses[clauses.size()-1]);
#endif
parent.insert(make_pair(clauses.size()-1,make_pair(current.i, current.j)));
visited.insert(newClause);
#ifdef DEBUG
cout<<"\n"<<clauses.size()-1<<": ";
printClause(clauses.size()-1);
#endif
// for new clause, generate clause pairs with existing clauses;
for(int i=0; i< clauses.size()-1; i++)
formCandidatePairs(i, clauses.size()-1);
}
return false;
}
int main(int argc, char* argv[])
{
if(argc<2)
{
cout<<"Invalid arguments..\n";
return 0;
}
#ifndef DEBUG
cout<<"Compile with -DDEBUG flag for detailed prints\n";
#endif
ifstream fp(argv[1]);
string line;
while(getline(fp, line))
{
if(line != "\n" && line[0] != '#')
{
istringstream iss(line);
clauses.push_back(CL());
while(iss)
{
string word; iss >> word;
if(word != "")
clauses[clauses.size()-1].push_back(word);
};
sort(clauses[clauses.size()-1].begin(), clauses[clauses.size()-1].end(), cmpClauses);
// for new clause, generate clause pairs with existing clauses;
for(int i=0; i< clauses.size()-1; i++)
formCandidatePairs(i, clauses.size()-1);
}
}
#ifdef DEBUG
cout<<"Initial Clauses\n";
printClauses();
#endif
bool result=false;
while(!candidates.empty())
{
CL_PAIR current = candidates.top();
candidates.pop();
if(resolve(current))
{
result = true;
break;
}
}
if(result)
cout<<"SUCCESS\n";
else
cout<<"\nFAILURE\n";
return 0;
}
| true |
02d195cf44ff1447aeec505af7a711b4ce1c9b1d | C++ | liuxueyang/liuxueyang.github.io | /assets/src/poj/1860_1.cpp | UTF-8 | 1,433 | 2.78125 | 3 | [] | no_license | #include <algorithm>
#include <cstring>
#include <queue>
#include <cstdio>
using namespace std;
const int N = 210, INF = 0x3f3f3f3f;
struct W {
W() {}
W(double r, double c) : r(r), c(c) {}
double r, c;
};
int st[N], n, cnt[N];
int e[N], ne[N], h[N], idx;
W w[N];
int S;
double V, dis[N];
void Init() {
idx = 0;
memset(h, -1, sizeof h);
memset(st, 0, sizeof st);
for (int i = 1; i <= n; ++i) {
dis[i] = 0;
}
memset(cnt, 0, sizeof cnt);
}
void Add(int a, int b, W c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
bool spfa() {
dis[S] = V;
queue<int> q;
q.push(S);
st[S] = 1;
while (!q.empty()) {
int t = q.front();
q.pop();
st[t] = 0;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
W _w = w[i];
double tmp = (dis[t] - _w.c) * _w.r;
if (tmp > dis[j]) {
dis[j] = tmp;
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j])
q.push(j);
}
}
}
return false;
}
int main() {
#ifdef _DEBUG
freopen("1860.in", "r", stdin);
#endif
int m;
scanf("%d%d%d%lf", &n, &m, &S, &V);
Init();
for (int i = 1; i <= m; ++i) {
int a, b;
double r1, c1, r2, c2;
scanf("%d%d%lf%lf%lf%lf", &a, &b, &r1, &c1, &r2, &c2);
Add(a, b, W(r1, c1));
Add(b, a, W(r2, c2));
}
printf("%s\n", (spfa() ? "YES" : "NO"));
return 0;
}
/*
* spfa 判斷正環
AC
*/
| true |
86262f4ced61cffee3e800d6f678eaa3fffb25bf | C++ | irstavr/1942-FeedTheBirds | /1942-FeedTheBirds/src/Animation/FlashingAnimation.cpp | UTF-8 | 851 | 2.640625 | 3 | [] | no_license | #include "../../include/Animation/FlashingAnimation.h"
FlashingAnimation::FlashingAnimation(frame_t n,
delay_t show,
delay_t hide,
animid_t id) :
repetitions(n),
hideDelay(hide),
showDelay(show),
Animation(id) {
}
void FlashingAnimation::setRepetitions(frame_t n) {
repetitions = n;
}
frame_t FlashingAnimation::getRepetitions(void) const {
return repetitions;
}
void FlashingAnimation::setHideDelay(delay_t d) {
hideDelay = d;
}
delay_t FlashingAnimation::getHideDelay(void) const {
return hideDelay;
}
void FlashingAnimation::setShowDelay(delay_t d) {
showDelay = d;
}
delay_t FlashingAnimation::getShowDelay(void) const {
return showDelay;
}
FlashingAnimation* FlashingAnimation::clone(animid_t newId) const {
return new FlashingAnimation(repetitions, hideDelay, showDelay, newId);
}
| true |
0a30ec14085d993fae5c4ecabe680ca085085d40 | C++ | scially/LintCode | /98.h | UTF-8 | 4,117 | 3.5625 | 4 | [] | no_license | /**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list, using constant space complexity.
*/
ListNode * sortList(ListNode * head) {
// write your code here
// 链表快排对于第一个要交换的数不好处理,单单只选择第一个可能退化为o(n2)
// 对于链表来说,归并排序容易些
//qsort(head, nullptr);
//return head;
return mergesort(head);
}
/*****************************qsort***********************************/
// qsort [head, end)
void qsort(ListNode *head, ListNode *end){
if(head == end) return;
if(head->next == end) return;
ListNode *p = __partition(head, end);
qsort(head, p);
qsort(p->next, end);
}
// qsort parition[head, end)
ListNode* __partition(ListNode *head, ListNode *end){
int v = head->val;
ListNode *p = head, *dummyhead = head;
dummyhead = dummyhead->next;
while(dummyhead != end){
if(dummyhead->val <= v){
p = p->next;
swap(p->val, dummyhead->val);
}
dummyhead = dummyhead->next;
}
swap(head->val, p->val);
return p;
}
/*****************************merge sort*****************************/
// merge sort[head, end)
ListNode* mergesort(ListNode *head){
if( head == nullptr || head->next == nullptr) return head;
ListNode *dummy = findmidNode(head);
ListNode *mid = dummy->next;
dummy->next = nullptr;
head = mergesort(head);
mid = mergesort(mid);
return merge(head, mid);
}
// find merge mid node[head, end)
ListNode *findmidNode(ListNode *head){
ListNode *fastnode = head, *slownode = head;
while(fastnode->next != nullptr && fastnode->next->next != nullptr){
slownode = slownode->next;
fastnode = fastnode->next->next;
}
return slownode;
}
// verson 1
// ListNode* merge(ListNode *head, ListNode *mid){
// ListNode auxhead(-1);
// auxhead.next = head;
// ListNode *dummyhead = &auxhead;
// ListNode *dummymid = mid;
// while(head != nullptr || dummymid != nullptr){
// if(head == nullptr){
// dummyhead->next = dummymid;
// dummyhead = dummymid;
// dummymid = dummymid->next;
// }
// else if( dummymid == nullptr){
// dummyhead->next = head;
// dummyhead = head;
// head = head->next;
// }
// else if(head->val < dummymid->val){
// dummyhead->next = head;
// dummyhead = head;
// head = head->next;
// }
// else{
// dummyhead->next = dummymid;
// dummyhead = dummymid;
// dummymid = dummymid->next;
// }
// }
// return auxhead.next;
// }
// verson 2
ListNode* merge(ListNode *head, ListNode *mid){
ListNode auxhead(-1);
auxhead.next = head;
ListNode *dummyhead = &auxhead;
ListNode *dummymid = mid;
while(head != nullptr && dummymid != nullptr){
if(head->val <= dummymid->val){
dummyhead->next = head;
dummyhead = head;
head = head->next;
}
else{
dummyhead->next = dummymid;
dummyhead = dummymid;
dummymid = dummymid->next;
}
}
if(head == nullptr) dummyhead->next = dummymid;
else dummyhead->next = head;
return auxhead.next;
}
}; | true |