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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32824238d426ad3d0bb760712f4aaf7f74245465 | C++ | zhaohuizh/lintcode-cpp | /expression_add_operators/Solution.cpp | UTF-8 | 1,454 | 3.421875 | 3 | [] | no_license | #include<string>
#include<assert.h>
#include<vector>
using namespace std;
class Solution {
private:
void dfs(string& num, int target, vector<string>& res, int start, int last, string expression, int sum) {
int len = num.size();
if (start == len) {
if (sum == target) {
res.push_back(expression);
}
return;
}
for(int i = start; i < len; i++) {
int cur = stoi(num.substr(start, i + 1));
//第一个数字特殊处理
if (start == 0) {
assert(sum == 0);
dfs(num, target, res, i + 1, cur, "" + to_string(cur), cur);
} else {
dfs(num, target, res, i + 1, cur, expression + "+" + to_string(cur), sum + cur);
dfs(num, target, res, i + 1, cur, expression + "-" + to_string(cur), sum - cur);
dfs(num, target, res, i + 1, cur * last, expression + "+" + to_string(cur), sum - last + last * cur);
}
}
}
public:
/**
* @param num: a string contains only digits 0-9
* @param target: An integer
* @return: return all possibilities
*/
vector<string> addOperators(string &num, int target) {
vector<string> res;
dfs(num, target, res, 0, 0, "", 0);
return res;
}
};
int main() {
Solution s;
string str("123");
s.addOperators(str, 6);
return 1;
}
| true |
e11f03f7bc0b6daa112c2d6aef2284b9fc27a55d | C++ | faterazer/LeetCode | /0443. String Compression/Solution.cpp | UTF-8 | 708 | 2.984375 | 3 | [] | no_license | #include <algorithm>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int compress(vector<char>& chars)
{
int n = chars.size(), i = 0, idx = 0;
while (i < n) {
int ch = chars[i++], cnt = 1;
while (i < n && chars[i] == ch) {
++i;
++cnt;
}
chars[idx++] = ch;
if (cnt > 1) {
int start = idx;
while (cnt) {
chars[idx++] = cnt % 10 + '0';
cnt /= 10;
}
reverse(chars.begin() + start, chars.begin() + idx);
}
}
return idx;
}
};
| true |
efd5815bc67bf3d77d3b8b10f9b66f9af0bd7f08 | C++ | lxsang/ROS_stuffs | /src/multi_master_bridge/src/helpers/QuaternionHelper.cpp | UTF-8 | 953 | 2.78125 | 3 | [] | no_license |
#include "QuaternionHelper.h"
int QuaternionHelper::hash()
{
return _H("geometry_msgs/Quaternion");
}
void QuaternionHelper::rawToRosMsg(uint8_t* data)
{
geometry_msgs::Quaternion* ptr = new geometry_msgs::Quaternion;
memcpy(&ptr->x, data , sizeof(ptr->x));
memcpy(&ptr->y, data+sizeof(ptr->x) ,sizeof(ptr->y));
memcpy(&ptr->z, data + 2*sizeof(ptr->x),sizeof(ptr->z));
memcpy(&ptr->w, data + 3*sizeof(ptr->x),sizeof(ptr->w));
_rawsize = 4*sizeof(ptr->x);
_msg = (void*) ptr;
}
int QuaternionHelper::rosMsgToRaw(uint8_t** data)
{
geometry_msgs::Quaternion* ptr = (geometry_msgs::Quaternion*)_msg;
int len=4*sizeof(ptr->x);
*data = (uint8_t*) malloc(len);
memcpy(*data,&ptr->x, sizeof(ptr->x));
memcpy(*data + sizeof(ptr->x),&ptr->y, sizeof(ptr->y));
memcpy(*data + 2*sizeof(ptr->x),&ptr->z, sizeof(ptr->z));
memcpy(*data + 3*sizeof(ptr->x),&ptr->w, sizeof(ptr->w));
return len;
}
| true |
1a3c2d6a20e5081641526544ce432c4ac880ab54 | C++ | pranit-yawalkar/C_plus_plus_practice | /Bit_manipulation/bit_manipulation.cpp | UTF-8 | 685 | 3.15625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int getBit(int n, int pos){
// return (n>>pos) & 1;
return (n & (1<<pos)!=0);
}
int setBit(int n, int pos){
return (n | (1<<pos));
}
int clearBit(int n, int pos){
int mask = ~(1<<pos);
return (n & mask);
}
int updateBit(int n, int pos, int val){
int mask = ~(1<<pos);
n = n & mask;
return (n | (val<<pos));
}
int toggleBit(int n, int pos){
return (n xor (1<<pos));
}
int main(){
cout<<getBit(5, 2)<<endl;
// cout<<setBit(5, 1)<<endl;
// cout<<clearBit(5, 0)<<endl;
// cout<<updateBit(5, 3, 1)<<endl;
cout<<toggleBit(5, 0)<<endl;
return 0;
} | true |
ca9a9c00c50b5e2a5ea518ef82039ee0246bdded | C++ | pingsoli/cpp | /tutorials/effective_cpp/chapter02/05.cpp | UTF-8 | 2,643 | 3.875 | 4 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
//
// Item 5: Know what functions silently writes and calls.
//
// Compilers may implicitly generate a class's default constructor, copy
// constructor, copy assignment operator, and destructor.
//
// NOTE:
// If you declared a constructor, compilers won't generate a default
// constructor.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
class Empty
{
};
template <typename T>
class NamedObject
{
public:
NamedObject(const std::string& name, const T& value)
: nameValue{name},
objectValue{value}
{
}
private:
std::string nameValue;
T objectValue;
};
template <typename T>
class NewNamedObject
{
public:
NewNamedObject(std::string& name, const T& value)
: nameValue{name},
objectValue{value}
{
}
private:
std::string& nameValue; // this is now a reference
const T objectValue; // this is now const
};
int main(int argc, char** argv)
{
/////////////////////////////////////////////////////////////////////////////
//
// when to generate these functiions ?
// These functions are generated only if they are needed.
Empty e1, e2; // default constructor
Empty e3(e1); // copy constructor
e1 = e2; // copy assignment operator
NamedObject<int> n1("hello", 5);
// NamedObject<int> n1; // Error, no default constructor generated by compiler
NamedObject<int> n2(n1); // Copy constructor
// The compiler how to copy the object ?
// nameValue variable is std::string type, so copy constructor will invoke
// std::string copy constructor to do the job.
// and T is int type(built-in type), so n2.objectValue will be
// initialized by copying the bits in n1.objectValue.
/////////////////////////////////////////////////////////////////////////////
std::string oldDog("hello");
std::string newDog("world");
/////////////////////////////////////////////////////////////////////////////
NamedObject<int> p(newDog, 2);
NamedObject<int> s(oldDog, 14);
p = s;
/////////////////////////////////////////////////////////////////////////////
NewNamedObject<int> np(newDog, 2);
NewNamedObject<int> ns(oldDog, 14);
np = ns; // what will happen ?
// g++ give the error message
// error: use of deleted function ¡®NewNamedObject<int>& NewNamedObject<int>::operator=(const NewNamedObject<int>&)¡¯)
//
// why did this happened ?
// the compiler don't know how to affect valueName(is a reference)
/////////////////////////////////////////////////////////////////////////////
return 0;
}
| true |
4b984c4b9f65ade3248b9434947c08332327dcd8 | C++ | sanketpathak64/Data-Structures-and-Algorithms | /Data Structures/Oueue/Array Implementation/circularqueue.cpp | UTF-8 | 1,990 | 3.28125 | 3 | [] | no_license | #include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int size = 8;
typedef struct cqueue{
int front,rear,cap;
int *a;
}CQ;
CQ* init()
{
CQ *q = (CQ *)malloc(sizeof(CQ));
q->cap = size;
q->front = -1;
q->rear = -1;
q->a = (int *)malloc(size*sizeof(int));
}
bool isEmpty(CQ *q)
{
return q->front == -1;
}
bool isFull(CQ *q)
{
return (q->rear + 1) % q->cap == q->front;
}
int len(CQ *q)
{
return ( q->cap - q->front + q->rear + 1) % q->cap;
}
void enqueue(CQ *q,int data)
{
q->rear = (q->rear + 1) % q->cap;
q->a[q->rear] = data;
if(q->front == -1)
q->front = q->rear;
}
int dequeue(CQ *q)
{
int data = q->a[q->front];
if(q->front == q->rear)
{
q->front = q->rear = -1;
}
else
{
q->front = (q->front + 1) % q->cap;
}
return data;
}
//thanks gfg for display function
void display(CQ *q)
{
// cout<<"\nThe queue is as follows ";
if (q->front == -1)
{
printf("\nQueue is Empty");
return;
}
printf("\nElements in Circular Queue are: ");
if (q->rear >= q->front)
{
for (int i =q->front; i <= q->rear; i++)
printf("%d ",q->a[i]);
}
else
{
for (int i = q->front; i < size; i++)
printf("%d ", q->a[i]);
for (int i = 0; i <= q->rear; i++)
printf("%d ", q->a[i]);
}
}
int main()
{
CQ *queue = init();
int pos,opt;
while(1)
{
cout<<"\n1.enqueue\n2.dequeue\n3.display\nenter your option ";
int option, data, pos;
cin >> option;
if(option > 3 || option < 0)
break;
switch(option)
{
case 1:
cout<<"\nenter value to add ";
cin>>data;
enqueue(queue,data);
// cout<<"front "<<front<<" rear "<<rear<<endl;
break;
case 2:
if(isEmpty(queue))
{
cout<<"\nQueue is already empty\n";
}
else
dequeue(queue);
// cout<<"front "<<front<<" rear "<<rear<<endl;
break;
case 3:
display(queue);
break;
}
}
}
| true |
8d0e4969936d815b4d0d958129974eb196e01406 | C++ | chestnutprog/ohmydbms | /database/field.h | UTF-8 | 1,668 | 2.5625 | 3 | [] | no_license | //
// Created by Chestnut on 2020/11/11.
//
#ifndef OHMYDBMS_FIELD_H
#define OHMYDBMS_FIELD_H
#include "../helper.h"
class Column;
enum class FieldType
{
INTEGER,
VARCHAR,
TEXT,
DATETIME,
BOOLEAN
};
template <FieldType T, class U> class Field_Register;
class BaseField
{
static std::unordered_map<FieldType, std::function<std::unique_ptr<BaseField>(Column &)>> _factory;
public:
template <FieldType T, class U> struct Register
{
Register()
{
_factory[T] = &U::create;
}
};
virtual int size() = 0;
virtual bool not_null() = 0;
virtual void from_string(const std::optional<std::string> &str) = 0;
virtual void from_bytes(const char *source) = 0;
virtual std::shared_ptr<char> to_bytes() const = 0;
virtual std::optional<std::string> to_string() const = 0;
virtual bool operator<(const BaseField &b) const = 0;
virtual bool operator<(const std::string &b) const = 0;
// virtual bool operator>(const BaseField &b) const = 0;
// virtual bool operator>(const std::string &b) const = 0;
// virtual bool operator==(const BaseField &b) const = 0;
virtual bool operator==(const std::string &b) const = 0;
virtual ~BaseField()
{
}
static std::unique_ptr<BaseField> get(FieldType type, Column &column)
{
auto gen = _factory.at(type);
return gen(column);
}
static std::string type_to_string(FieldType type);
static FieldType string_to_type(std::string type);
};
#include "field_implements/field_implements.h"
#endif // OHMYDBMS_FIELD_H
| true |
708f3e42c9969ef5167e21e69796e8ca6c50c016 | C++ | aeremin/Codeforces | /alexey/Solvers/6xx/668/Solver668A.cpp | UTF-8 | 1,745 | 2.953125 | 3 | [] | no_license | #include <Solvers/pch.h>
#include "algo/io/baseio.h"
#include "iter/range.h"
#include "algo/io/printvector.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/668/problem/A
class Solver668A {
public:
void run();
};
void Solver668A::run() {
int n, m, q;
cin >> n >> m >> q;
struct Query { int a, b, c, d; };
deque<Query> queries;
for (int i : range(q)) {
int a, b;
cin >> a >> b;
int c = 1;
int d = 0;
if (a == 3)
cin >> c >> d;
queries.push_front({ a, b - 1, c - 1, d });
}
vector<vector<int>> field(n, vector<int>(m));
for (auto q : queries) {
if (q.a == 1) {
auto t = field[q.b][m - 1];
for (int i = m - 1; i > 0; --i)
field[q.b][i] = field[q.b][i - 1];
field[q.b][0] = t;
}
if (q.a == 2) {
auto t = field[n - 1][q.b];
for (int i = n - 1; i > 0; --i)
field[i][q.b] = field[i - 1][q.b];
field[0][q.b] = t;
}
if (q.a == 3) {
field[q.b][q.c] = q.d;
}
}
for (auto& line : field) {
printVector(line);
print('\n');
}
}
class Solver668ATest : public ProblemTest {};
TEST_F(Solver668ATest, Example1) {
string input = R"(2 2 6
2 1
2 2
3 1 1 1
3 2 2 2
3 1 2 8
3 2 1 8
)";
string output = R"(8 2
1 8
)";
setInput(input);
Solver668A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver668ATest, Example2) {
string input = R"(3 3 2
1 2
3 2 2 5
)";
string output = R"(0 0 0
0 0 5
0 0 0
)";
setInput(input);
Solver668A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
| true |
8af4e589a4aaa29560d3a74a78927361072ff845 | C++ | jkorn2324/Tower-Defense | /src/towerdefense/actor/game/enemy/Enemy.cpp | UTF-8 | 1,855 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "Enemy.h"
#include "Game.h"
#include "GameParameters.h"
#include "Level.h"
#include "LevelManager.h"
#include "EnemyManager.h"
#include "TileSpriteComponent.h"
#include "SpriteComponent.h"
#include "CollisionComponent.h"
#include "EnemyAIComponent.h"
#include "HealthComponent.h"
#include "ScaleSelectAnimationComponent.h"
namespace TowerDefense
{
EnemyType GetEnemyTypeFromLocalizedString(const std::string& string)
{
if(string == "green-enemy")
{
return EnemyType::GREEN_ENEMY;
}
return EnemyType::UNKNOWN;
}
Enemy::Enemy(Game *game)
: Actor(game)
{
mLevel = game->GetLevelManager()->GetActiveLevel();
EnemyManager* enemyManager = mLevel->GetEnemyManager();
mTransform.SetPosition(enemyManager->GetSpawnPosition());
mCollisionComponent = new CollisionComponent(this);
mCollisionComponent->SetSize(20.0f, 20.0f);
mEnemyAIComponent = new EnemyAIComponent(this, mLevel);
mEnemyAIComponent->SetMovementSpeed(100.0f);
mHealthComponent = new HealthComponent(this);
mHealthComponent->SetHealthChangedCallback(
std::bind(&Enemy::OnHealthChanged, this, std::placeholders::_1));
}
void Enemy::OnSpawn()
{
mLevel->GetEnemyManager()->AddEnemy(this);
}
void Enemy::OnDespawn()
{
// Here to remove enemy from enemy manager list.
// Prevents bug where enemy affectors crash game.
mLevel->GetEnemyManager()->RemoveEnemy(this);
}
struct LevelPathNodeData* Enemy::GetTargetPathNode() const
{
return mEnemyAIComponent->GetTargetPathNode();
}
void Enemy::OnHealthChanged(const HealthChangedEventData &eventData)
{
if(eventData.newHealth <= 0.0f)
{
Despawn();
}
}
} | true |
e3c8d04429be5396c253c7afe6b2bf12cd61b541 | C++ | java-xuechengzhi/MyYoung | /Array/productExceptSelf.cpp | UTF-8 | 837 | 3.328125 | 3 | [] | no_license | //
// Created by Xue on 2021/7/8.
//
#include "bits/stdc++.h"
using namespace std;
vector<int> productExceptSelf(vector<int>& nums) {
int length = nums.size();
vector<int> L(length, 0), R(length, 0);
vector<int> answer(length);
L[0] = 1;
for (int i = 1; i < length; i++) {
L[i] = nums[i - 1] * L[i - 1];
}
// R[i] 为索引 i 右侧所有元素的乘积
// 对于索引为 'length-1' 的元素,因为右侧没有元素,所以 R[length-1] = 1
R[length - 1] = 1;
for (int i = length - 2; i >= 0; i--) {
R[i] = nums[i + 1] * R[i + 1];
}
// 对于索引 i,除 nums[i] 之外其余各元素的乘积就是左侧所有元素的乘积乘以右侧所有元素的乘积
for (int i = 0; i < length; i++) {
answer[i] = L[i] * R[i];
}
return answer;
} | true |
8871cf1f2cb8c7cc17e87896ba85d5a27df8096c | C++ | ViniciusGardin/Prototipo_Serbena | /Marlio_Codigos/STM32_AD9833.ino | UTF-8 | 5,105 | 2.765625 | 3 | [] | no_license | /*
AD9833 Waveform Module vwlowen.co.uk
Using the first SPI port (SPI_1)
SS <--> PA4 <--> BOARD_SPI1_NSS_PIN
SCK <--> PA5 <--> BOARD_SPI1_SCK_PIN
MISO <--> PA6 <--> BOARD_SPI1_MISO_PIN
MOSI <--> PA7 <--> BOARD_SPI1_MOSI_PIN
Using the second SPI port (SPI_2)
SS <--> PB12 <--> BOARD_SPI2_NSS_PIN
SCK <--> PB13 <--> BOARD_SPI2_SCK_PIN
MISO <--> PB14 <--> BOARD_SPI2_MISO_PIN
MOSI <--> PB15 <--> BOARD_SPI2_MOSI_PIN
*/
#include <SPI.h>
SPIClass SPI_2(2); //Create an instance of the SPI Class called SPI_2 that uses the 2nd SPI Port
const int SINE = 0x2000; // Define AD9833's waveform register value.
const int TRIANGLE = 0x2002; // When we update the frequency, we need to
const int SQUARE = 0x2028; // define the waveform when we end writing.
const int SQUARE2 = 0x2020; // square/2
int wave = 0;
//int waveType = SINE;
int waveType = TRIANGLE;
int wavePin = 7;
const float refFreq = 25000000.0; // On-board crystal reference frequency
//#define FSYNC PA15 // Standard SPI pins for the AD9833 waveform generator.
#define FSYNC PB12
const int CLK = 13; // CLK and DATA pins are shared with the TFT display.
const int DATA = 11;
unsigned long freq = 1000; // Set initial frequency.
String inputString = "";
//ADC read
const int AnalogIn = PA5;
int ADread = 0;
int count = 0;
void setup() {
// Setup SPI 1: SPI1 works on APB2 (72 MHz)
// SPI.begin(); //Initialize the SPI_1 port.
// SPI.setBitOrder(MSBFIRST); // Set the SPI_1 bit order
// // AD9833 uses SPI MODE2
// SPI.setDataMode(SPI_MODE2);
// SPI.setClockDivider(SPI_CLOCK_DIV8); // clock speed =72 / 8 = 9 MHz (SPI_1 speed)
// pinMode(FSYNC, OUTPUT);
// Setup SPI 2: SPI2 works on APB1 (36 MHz)
SPI_2.begin(); //Initialize the SPI_2 port.
SPI_2.setBitOrder(MSBFIRST); // Set the SPI_2 bit order
SPI_2.setDataMode(SPI_MODE2); //Set the SPI_2 data mode 0
SPI_2.setClockDivider(SPI_CLOCK_DIV2); // clock speed =36 / 2 = 18 MHz (SPI_2 speed)
pinMode(FSYNC, OUTPUT);
AD9833reset(); // Reset AD9833 module after power-up.
delay(1);
AD9833setFrequency(freq); // Set the frequency output
AD9833setWaveform(SINE); // Set the Wave output
inputString.reserve(10);
Serial.begin(115200); //begins serial port at 1 Mbps
pinMode(PA5, INPUT);//defines pin 6 as A/D input
pinMode(PA4, OUTPUT); //put to GND analog input (PA5) neigboring pins to minimize noise
pinMode(PA6, OUTPUT);
digitalWrite(PA4, LOW);
digitalWrite(PA6, LOW);
}
void loop() {
Serial.write(analogRead(AnalogIn)>>2); //envia para a serial a leitura do AD em 8 bits (fs ~ 78 kS/s)
// count += 1;
// if (count == 1000) {
// WriteRegister(SINE);
// }
// if (count == 2000) {
// WriteRegister(SQUARE);
// count = 0;
// }
if ( Serial.available() ) {
// freq = Serial.parseInt();
// freq = constrain(freq, 1, 100);
// }
// if (Serial.read() == '\n' || Serial.read() == '\r') {
// }
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
freq = inputString.toInt();
inputString = "";
}
}
AD9833setFrequency(freq); //send freq to AD9833
return;
}
}
//Functions
// AD9833 documentation advises a 'Reset' on first applying power.
void AD9833reset() {
WriteRegister(0x100); // Write '1' to AD9833 Control register bit D8 for Reset
delayMicroseconds(2);
WriteRegister(0x000); // Write '0' to AD9833 Control register bit D8 for normal operation
}
// Set the waveform registers in the AD9833.
void AD9833setWaveform(int Waveform) {
WriteRegister(Waveform); // Exit & Reset to SINE, SQUARE or TRIANGLE
}
// Set the frequency registers in the AD9833.
void AD9833setFrequency(long frequency) {
long FreqWord = (frequency * pow(2, 28)) / refFreq;
int MSB = (int)((FreqWord & 0xFFFC000) >> 14); //Only lower 14 bits are used for data
int LSB = (int)(FreqWord & 0x3FFF);
//Set control bits 15 and 14 to 0 and 1, respectively, for frequency register 0
LSB |= 0x4000;
MSB |= 0x4000;
WriteRegister(0x2100);
WriteRegister(LSB); // Write lower 16 bits to AD9833 registers
WriteRegister(MSB); // Write upper 16 bits to AD9833 registers.
WriteRegister(0xC000); // Phase register
WriteRegister(SINE); // Exit & Reset to SINE, SQUARE or TRIANGLE
}
void WriteRegister(int dat) {
digitalWrite(FSYNC, LOW); // Set FSYNC low before writing to AD9833 registers
SPI_2.transfer16(dat); //transfer 16 bits
digitalWrite(FSYNC, HIGH); //Write done. Set FSYNC high
}
| true |
675ce816c1bb37a54dd200ae24d82ada35ab41a0 | C++ | HerbGlitch/SFML-Pong | /pong/handler/handler.cpp | UTF-8 | 888 | 2.71875 | 3 | [] | no_license | #include "handler.hpp"
#include "../game.hpp"
#include <iostream>
namespace herbglitch {
Handler::Handler(game::Data *data): data(data) {
load();
AddState(new state::Menu(data), false);
}
Handler::~Handler(){
for(State *state : states){ delete state; }
states.clear();
}
void Handler::load(){
config::load("pong/.res/settings.config", data->texture);
}
void Handler::update(){
for(State *state : states){ state->update(); }
}
void Handler::render(){
for(State *state : states){ state->render(); }
}
void Handler::AddState(State *state, bool isReplacing){
if(isReplacing){ RemoveState(); }
states.push_back(state);
}
void Handler::RemoveState(){
delete states.at(states.size() - 1);
states.erase(states.begin() + (states.size() - 1));
}
} | true |
6641c46f51026db39e4fc12c0bc7389cb8371038 | C++ | king-ton/CG1Project | /CGCamera.cpp | UTF-8 | 1,509 | 2.796875 | 3 | [] | no_license | #include "CGCamera.h"
#include "CGMath.h"
CGCamera::CGCamera() {
cguLookAt(0, 10, 10, 0, 0, 0, 0, 5, 0);
project_Matrix = CGMatrix4x4::getFrustum(-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 50.0f);
is_2D = false;
rotate = 0;
}
// GETTER
CGMatrix4x4 CGCamera::getProjectMatrix() {
return project_Matrix;
}
CGMatrix4x4 CGCamera::getViewMatrix() {
return view_Matrix;
}
bool CGCamera::is2D() {
return is_2D;
}
// SETTER
void CGCamera::is2D(bool state) {
is_2D = state;
if (is_2D)
cguLookAt(0, 10, 0, 0, 0, 0, 0, 0, -1);
else
cguLookAt(0, 10, 10, 0, 0, 0, 0, 5, 0);
}
void CGCamera::setProjectMatrix(CGMatrix4x4 projectMatrix) {
project_Matrix = projectMatrix;
}
void CGCamera::setViewMatrix(CGMatrix4x4 viewMatrix) {
view_Matrix = viewMatrix;
}
// METHODS
void CGCamera::draw() {
if (rotate != 0)
view_Matrix = view_Matrix * CGMatrix4x4::getRotationMatrixY(rotate);
}
void CGCamera::cguLookAt(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
CGMatrix4x4 V;
CGVec4 f, s, u, up;
f.set(centerX - eyeX, centerY - eyeY, centerZ - eyeZ, 0.0F);
f = CGMath::normalize(f);
up.set(upX, upY, upZ, 0);
s = CGMath::normalize(CGMath::cross(f, up));
u = CGMath::cross(s, f);
f = CGMath::scale(f, -1);
float R[16] = { s[X], s[Y], s[Z], 0,
u[X], u[Y], u[Z], 0,
f[X], f[Y], f[Z], 0,
0, 0, 0, 1 };
V.setFloatsFromRowMajor(R);
V = V * CGMatrix4x4::getTranslationMatrix((-1)*eyeX, (-1)*eyeY, (-1)*eyeZ);
view_Matrix = V;
} | true |
bc46c235f101a7aa6498f3750623a832d62dbadf | C++ | gkastrinis/talk-material | /exept.cpp | UTF-8 | 361 | 2.890625 | 3 | [] | no_license | #include <exception>
#include <iostream>
using namespace std;
void terminator() {
cout << "fsdfsfd" << endl;
exit(0);
}
void (*old)() = set_terminate(terminator);
class Botch {
public:
class Fruit {};
void f() { cout <<"Botch"<< endl;
throw Fruit();
}
~Botch() { throw 'c'; }
};
int main() {
try {
Botch b;
b.f();
} catch(...) {
cout << "inside"<< endl;
}}
| true |
2a6da36091cb42f43e60fd7c2d486f5eed368420 | C++ | g33kyaditya/OJs | /SPOJ/AE00.cpp | UTF-8 | 287 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
main()
{
long long int n,count = 0;
cin >> n;
for (long long int i = 1;i<=floor(sqrt(n));i++) {
for (long long int j = i+1;i*j<=n;j++)
count++;
}
cout << count + floor(sqrt(n)) << endl;
}
| true |
fc16005991c409fcef70d23c07dabbdd8f93a70b | C++ | joshgreifer/spe | /eng6/procs/samples.h | UTF-8 | 3,189 | 2.796875 | 3 | [] | no_license | #pragma once
#include "compound_processor.h"
#include "rand.h"
namespace sel {
namespace eng6 {
namespace proc {
namespace sample {
/*
Processor class naming convention:
Processor01x - Processor with no input ports and one output port of variable width
Processor01A<N> - Processor with no input ports and one output port with fixed width N
Processor1x1x - Processor with one input port and one output port, with the input port variable width and the output port width set to be the same as the input width
Processor1A1B<N,M> - Processor with one input port and one output port, with the port widths fixed at N, M respectively
... more complex cases:
Processor2Ax11<N> - Processor with two input ports and one output port. The first input port width is N, the second is variable. The output port width is 1 (scalar).
ProcessorX121 - Processor with variable number of input ports each of width 1 (scalar values) and two output ports of width 1.
Processor421x90 - Processor with four input ports, of widths two, one, variable and nine, and no output ports
*/
/*
Sample Sink Processor: ProcessorXx0 (Variable number of inputs each of variable width, no outputs)
*/
struct Logger : virtual ProcessorXx0, virtual public creatable<Logger>
{
std::ostream& ostream = std::cout;
virtual const std::string type() const override { return "Logger"; }
explicit Logger(std::ostream& ostr = std::cout) : ostream(ostr) {
set_port_alias("Logger.in", PORTID_0);
}
explicit Logger(params& params) : Logger() {}
void process() override
{
for (size_t i = 0; i < inports.size(); ++i) {
std::cout << "Port " << i + 1 << ": [ ";
for (auto v : *inports[i])
std::cout << v << " ";
std::cout << "]" << std::endl;
}
}
};
/*
Sample variable width in-out Processor: Processor1x1x (One input of variable width, one output with the same width as input)
*/
struct Doubler : Processor1x1x
{
void process() override
{
for (size_t i = 0; i < width; ++i)
out[i] = 2.0 * in[i];
}
};
/*
Sample aggregator Processor: Processor1x11 (One input of variable width, one output with scalar value)
*/
struct Summer : Aggregator
{
void process() override
{
outv = 0;
for (size_t i = 0; i < width; ++i)
outv += in[i];
outv = 0;
for (auto v : *piport) {
outv += v;
}
}
};
struct MyCompoundProc : public compound_processor
{
sel::eng6::proc::rand<7> rng;
Logger logger;
double num[3] = { 1, 4, 9 };
Const c = Const(&num[0], &num[3]);
Summer s;
virtual const std::string type() const override { return "MyCompoundProc"; }
MyCompoundProc() {
// No inputs
//AddInputProc(&c1);
// Output of this proc is the output of the random number generator
// add_output_proc(rng);
connect_procs(rng, logger);
connect_const(c, s);
connect_const(c, logger);
connect_procs(s, logger);
}
};
} // sample
} // proc
} // eng
} // sel
| true |
b0710387bb824a2c0cb01661c638293fc21ba3bc | C++ | lilberick/Competitive-programming | /online-judge-solutions/Codeforces/496A.cpp | UTF-8 | 425 | 2.578125 | 3 | [] | no_license | //https://codeforces.com/problemset/problem/496/A
//Lang : GNU C++14
//Time : 15 ms
//Memory : 0 KB
#include<iostream>
#include<vector>
using namespace std;
int main(){
int n,s=10000;cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++) cin>>v[i];
for(int i=1;i<n-1;i++){
vector<int> w=v;
w.erase(w.begin()+i);
int m=0;
for(int i=0;i<w.size()-1;i++) m=max(m,w[i+1]-w[i]);
s=min(s,m);
}
cout<<s<<endl;
return 0;
}
| true |
bbb2624f5bc017b182289f7a1100000aedf348e1 | C++ | dingdalong/mytest | /server/GameServer/ObjFight.cpp | UTF-8 | 3,044 | 2.640625 | 3 | [] | no_license | #include "ObjFight.h"
#include "Timer.h"
#include "BaseObj.h"
#include "CSVLoad.h"
CObjFight::CObjFight()
{
m_AttackSkill.clear();
m_HurtMap.clear();
}
CObjFight::~CObjFight()
{
m_AttackSkill.clear();
CleanHurtMap();
}
void CObjFight::FightRun()
{
int64 nNowTime = CTimer::GetTime64();
UpdateHurtMap(nNowTime);
ApplySkill(nNowTime);
}
void CObjFight::ActiveAttack(uint32 targettempid, int32 skillid, float x, float y, float z)
{
int32 nLev = 1;
int64 key = MAKE_SKILL_KEY(skillid, nLev);
CSVData::stSkill *skill = CSVData::CSkillDB::FindById(key);
if (skill)
{
m_AttackSkill.clear();
m_AttackSkill.nSkillID = skillid;
m_AttackSkill.nLev = nLev;
m_AttackSkill.nTime = CTimer::GetTime64();
m_AttackSkill.nTargetTempID = targettempid;
m_AttackSkill.x = x;
m_AttackSkill.y = y;
m_AttackSkill.z = z;
}
}
void CObjFight::ApplySkill(const int64 &time)
{
// 检查是否有技能需要使用
if (m_AttackSkill.isValid())
{
// 到达使用时间
if (time >= m_AttackSkill.nTime)
{
int64 key = MAKE_SKILL_KEY(m_AttackSkill.nSkillID, m_AttackSkill.nLev);
m_AttackSkill.pSkill = CSVData::CSkillDB::FindById(key);
if (m_AttackSkill.pSkill)
{
std::list<CBaseObj *> TargetList;
// 筛选目标
FilterTarget(TargetList);
for (auto &i : TargetList)
{
// 计算伤害
int32 nDamage = CalculateDamage(i);
if (nDamage > 0)
{
// 应用伤害
ApplyDamage(i, nDamage);
}
}
}
// 清理技能
m_AttackSkill.clear();
}
}
}
void CObjFight::FilterTarget(std::list<CBaseObj *> &list)
{
// 有目标
if (m_AttackSkill.nTargetTempID > 0)
{
CBaseObj *target = GetObj()->FindFromAoiList(m_AttackSkill.nTargetTempID);
list.push_back(target);
}
}
int32 CObjFight::CalculateDamage(CBaseObj *target)
{
int32 nDamage = 0;
CSVData::stSkill *skill = static_cast<CSVData::stSkill *>(m_AttackSkill.pSkill);
nDamage = skill->nBaseDamage;
return nDamage;
}
void CObjFight::ApplyDamage(CBaseObj *target, int32 value)
{
target->ChangeNowHP(value);
target->AddToHurtMap(GetObj()->GetTempID(), value);
if (target->GetNowHP() == 0)
{
//死亡
target->Die();
}
}
// 更新伤害列表
void CObjFight::UpdateHurtMap(const int64 &time)
{
// 更新伤害列表
std::map<int32, stHurt *>::iterator iter = m_HurtMap.begin();
for (; iter != m_HurtMap.end();)
{
stHurt *hurt = iter->second;
if (hurt->isNeedRemove(time))
{
delete hurt;
iter = m_HurtMap.erase(iter);
continue;
}
++iter;
}
}
void CObjFight::AddToHurtMap(uint32 tempid, int32 value)
{
std::map<int32, stHurt *>::iterator iter = m_HurtMap.find(tempid);
if (iter != m_HurtMap.end())
{
stHurt *hurt = iter->second;
hurt->nLastHurtTime = CTimer::GetTime();
hurt->nHurt += value;
}
else
{
stHurt *hurt = new stHurt;
hurt->nLastHurtTime = CTimer::GetTime();
hurt->nHurt = value;
m_HurtMap.insert(std::make_pair(tempid, hurt));
}
}
void CObjFight::CleanHurtMap()
{
for (auto &i : m_HurtMap)
{
delete i.second;
}
m_HurtMap.clear();
}
| true |
4707f5898251689eebdb78cdb678aa9271a5aca8 | C++ | kurkim0661/jihwan | /degine/전략패턴.cpp | UTF-8 | 1,698 | 3.296875 | 3 | [] | no_license | 동적으로 알고리즘을 교체할 수 있는 구조
알고리즘 인터페이스를 정의하고, 각각의 알고리즘 클래스별로 캡슐화하여 각각의 알고리즘을 교체 사용 가능하게 한다.
즉, 하나의 결과를 만드는 목적(메소드)은 동일하나, 그 목적을 달성할 수 있는 방법(전략, 알고리즘)이 여러가지가 존재
할 경우 기본이 되는 템플릿 메서드패턴과 함께 가장 많이 사용되는 패턴 중에 하나이다.
#include <iostream>
using namespace std;
class Strategy
{
public:
virtual void Algotithminterface() = 0;
};
class ConcreteStrategyA : public Strategy
{
public:
void Algotithminterface() override
{
cout<<"ConcreteStrategyA"<<endl;
}
};
class ConcreteStrategyB : public Strategy
{
public:
void Algotithminterface() override
{
cout<<"ConcreteStrategyB"<<endl;
}
};
class ConcreteStrategyC : public Strategy
{
public:
void Algotithminterface() override
{
cout<<"ConcreteStrategyC"<<endl;
}
};
class Context
{
public:
Context() : m_strategy(nullptr){}
~Context()
{
if(m_strategy)
{
delete m_strategy;
}
}
void ChangeStrategy(Strategy* pStrategy)
{
if(m_strategy)
{
delete m_strategy;
m_strategy = pStrategy;
}
};
void Contextinterface()
{
m_strategy->Algotithminterface();
}
private:
Strategy* m_strategy;
};
int main(void)
{
Context* pContext = new Context();
pContext->ChangeStrategy(new ConcreteStrategyA());
pContext->Contextinterface();
pContext->ChangeStrategy(new ConcreteStrategyB());
pContext->Contextinterface();
pContext->ChangeStrategy(new ConcreteStrategyC());
pContext->Contextinterface();
delete pContext;
return 0;
}
| true |
00e224089bf61025b5499626907c86a320625602 | C++ | sonwell/ib.cu | /include/bases/transforms.h | UTF-8 | 3,025 | 2.90625 | 3 | [] | no_license | #pragma once
#include "util/functional.h"
#include "util/math.h"
#include "algo/dot.h"
#include "algo/cross.h"
namespace bases {
template <typename ... composed>
struct composition {
std::tuple<composed...> functions;
template <typename arg_type>
constexpr decltype(auto)
operator()(arg_type&& arg) const
{
using namespace util::functional;
auto op = [] (auto&& x, auto& f) constexpr { return f(x); };
auto reduce = partial(foldl, op, arg);
return apply(reduce, functions);
}
constexpr composition(std::tuple<composed...> fns) :
functions{fns} {}
constexpr composition(composed... fns) :
functions{fns...} {};
};
template <typename ... left, typename ... right>
constexpr decltype(auto)
operator|(const composition<left...>& f, const composition<right...>& g)
{
return composition{std::tuple_cat(f.functions, g.functions)};
}
inline constexpr struct translate {
private:
template <typename shift_type>
constexpr decltype(auto)
evaluate(shift_type&& dx) const
{
return composition{
[=] __host__ __device__ (auto&& x) constexpr
{
using namespace util::functional;
return map(std::plus<void>{}, x, dx);
}
};
}
public:
template <std::size_t n>
constexpr decltype(auto)
operator()(const double (&dx)[n]) const
{
return evaluate(dx);
}
template <typename shift_type>
constexpr decltype(auto)
operator()(shift_type&& dx) const
{
return evaluate(std::forward<shift_type>(dx));
}
} translate;
inline constexpr struct shear {
private:
template <typename matrix_type>
constexpr decltype(auto)
evaluate(matrix_type&& m) const
{
using namespace util::functional;
return composition{
[=] (auto&& x) constexpr
{
auto k = [&] (const auto& y)
{
return algo::dot(x, y);
};
return map(k, m);
}
};
}
public:
template <std::size_t n, std::size_t m>
constexpr decltype(auto)
operator()(const double (&y)[n][m]) const
{
return evaluate(y);
}
template <typename matrix_type>
constexpr decltype(auto)
operator()(matrix_type&& y) const
{
return evaluate(std::forward<matrix_type>(y));
}
} shear;
inline constexpr struct rotate {
private:
template <typename axis_type>
__host__ __device__ decltype(auto)
evaluate(double angle, axis_type&& axis) const
{
using namespace util::functional;
using algo::dot;
using algo::cross;
auto l = sqrt(dot(axis, axis));
auto c = cos(angle);
auto s = sin(angle);
return composition{
[=] (auto&& x) constexpr
{
auto d = dot(axis, x) / l;
auto w = cross(axis, x);
auto f = [&] (double u, double v, double w)
{
return c * v + s * w / l + (1 - c) * d * u / l;
};
return map(f, axis, x, w);
}
};
}
public:
__host__ __device__ __forceinline__ decltype(auto)
operator()(double a, const double (&u)[3]) const
{
return evaluate(a, u);
}
template <typename axis_type>
constexpr decltype(auto)
operator()(double a, axis_type&& axis) const
{
return evaluate(a, std::forward<axis_type>(axis));
}
} rotate;
} // namespace bases
| true |
0aa1d3df3f64f5f685b89867c810d0f76c59300b | C++ | brodderickrodriguez/xor_nerual_net | /NeuralNetwork_1/Neural Network/Neuron/Neuron.hpp | UTF-8 | 1,263 | 2.78125 | 3 | [] | no_license | //
// Neuron.h
// NeuralNetwork_1
//
// Created by bcr@brodderick.com on 5/13/18.
// Copyright © 2018 BCR. All rights reserved.
//
#ifndef Neuron_h
#define Neuron_h
#include <vector>
#include <cmath>
struct Connection {
double weight, deltaWeight;
}; // Connection
class Neuron;
typedef std::vector<Neuron> Layer;
class Neuron {
public:
Neuron(unsigned numOutputs, unsigned myIndex);
void setOutputVal(double val) { m_outputVal = val; }
double getOutputVal(void) const { return m_outputVal; }
void feedForward(const Layer &prevLayer);
void calcOutputGradients(double targetVals);
void calcHiddenGradients(const Layer &nextLayer);
void updateInputWeights(Layer &prevLayer);
private:
static double eta; // [0.0...1.0] overall net training rate
static double alpha; // [0.0...n] multiplier of last weight change [momentum]
static double transferFunction(double x);
static double transferFunctionDerivative(double x);
// randomWeight: 0 - 1
static double randomWeight(void) { return rand() / double(RAND_MAX); }
double sumDOW(const Layer &nextLayer) const;
double m_outputVal;
std::vector<Connection> m_outputWeights;
unsigned m_myIndex;
double m_gradient;
}; // Neuron
#endif /* Neuron_h */
| true |
e661cd9ee4181bb3290500084311865ccf20d4cb | C++ | minsang0850/Program_Solving | /Programmers/DEV_Matching_2021/multilevel.cpp | UTF-8 | 1,073 | 2.78125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <unordered_map>
using namespace std;
unordered_map<string,int> up;
vector<int> v;
vector<int> solution(vector<string> enroll, vector<string> referral, vector<string> seller, vector<int> amount) {
vector<int> answer;
int size=enroll.size();
answer.resize(size);
v.resize(size);
for(int i=0; i<size; i++)
up[enroll[i]]=i;
int sell_size=seller.size();
for(int i=0; i<sell_size; i++){
//num : 판매자 번호
int num = up[seller[i]];
int value = amount[i]*100;
//판매자 꼬신사람
while(referral[num]!="-"){
int jul = value/10;
int mine = value-jul;
answer[num]+=mine;
if(jul!=0){
num=up[referral[num]];
value=jul;
}
else
break;
}
if(referral[num]=="-"){
int jul = value/10;
int mine = value-jul;
answer[num]+=mine;
}
}
return answer;
} | true |
56ca4794119235e45d683b6672f4749a7db750b2 | C++ | zcwwzdjn/OI | /SGU/533.cpp | UTF-8 | 445 | 2.75 | 3 | [] | no_license | #include <climits>
#include <cstdio>
#include <algorithm>
using std::min;
int m;
int main() {
scanf("%d", &m);
if (m == 21)
printf("1\n");
else {
int res = INT_MAX;
for (int up = 1; up <= 6; ++ up)
for (int lo = 1; lo <= 6; ++ lo) {
int n = m - (21 - up) - (21 - lo);
if (n >= 0 && n % 14 == 0)
res = min(res, n / 14 + 2);
}
if (res == INT_MAX)
printf("-1\n");
else
printf("%d\n", res);
}
return 0;
}
| true |
fd8129792a75db8afbc028be3e16cb4745f6c234 | C++ | layunne/Estrutura-de-Dados | /AVLTree/avltree.h | UTF-8 | 1,216 | 2.671875 | 3 | [] | no_license | #ifndef AVLTREE_H
#define AVLTREE_H
#include "node.h"
#include "treeADT.h"
#include "bintree.h"
template <class E>
class AVLTree : public Tree<E> {
private:
public:
AVLTree () {
}
~AVLTree () {
clear();
}
void clear() {
// Tree::clear();
}
// void add(const E& item) {
// Tree::add(item);
// }
// void remove(E item) {
// Tree::remove(item);
// }
// bool inTree(const E item) {
// return Tree::inTree(item);
// }
// const E lower() {
// return Tree::lower();
// }
// const E greater() {
// return Tree::greater();
// }
// QString toString() {
// return Tree::toString();
// }
// int countNode() const {
// return Tree::countNode();
// }
// int countLevel() const {
// return Tree::countLevel();
// }
// int countLeaf() const {
// return Tree::countLeaf();
// }
// int height() const {
// return Tree::height();
// }
// const Node<E> *getTree() {
// return Tree::getTree();
// }
// void addSubTree(Node<E>*& node) {
// Tree::addSubTree(node);
// }
// void toLeft() {
// }
};
#endif // AVLTREE_H
| true |
069fbe7a28e99a3d318ca6edbc6e6b63072ca503 | C++ | Ryuk17/LeetCode | /C++/11. Container With Most Water.cpp | UTF-8 | 414 | 2.984375 | 3 | [] | no_license | int maxArea(int* height, int heightSize) {
int area, temp,high;
area = 0;
temp = 0;
for(int i=0;i<heightSize;i++){
for(int j=i;j<heightSize;j++){
if (height[i]>height[j])
high = height[j];
else
high = height[i];
temp = (j-i)*high;
if (temp>area)
area = temp;
}
}
return area;
}
| true |
f463bfbde34069eed3baf6a130257e50ba4f9765 | C++ | sztony/LoraRemote | /transmitter/transmitter.ino | UTF-8 | 2,834 | 2.78125 | 3 | [] | no_license | /*
LoraRemote - Transmitter side
Simple, Lora based, long range remote control switch
Perfect for using the Adafruit Feather M0 Lora Board
*/
#include <SPI.h>
#include <RH_RF95.h>
/* for feather m0 */
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 3
// Change to the desired init Frequency in respect of the frequency range of the used module
#define RF95_FREQ 464.0
// you can define many different frequencys for multiple receivers (should be a few Mhz apart from each other)
// must match with the one set on the receiver
#define RECEIVER1 464.0
#define RECEIVER2 484.0
RH_RF95 rf95(RFM95_CS, RFM95_INT);
#define LED 13
// connect pushbuttons on the chosen pins; pushbutton should connect to ground level
#define RECEIVER1_ON 6
#define RECEIVER1_OFF 7
#define RECEIVER2_ON 8
#define RECEIVER2_OFF 9
#define LEDSEND 5 //connect an LED for transmitter activity display
float curFreq = RF95_FREQ;
void setup()
{
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
pinMode(LEDSEND, OUTPUT);
pinMode(RECEIVER1_ON, INPUT_PULLUP);
pinMode(RECEIVER1_OFF, INPUT_PULLUP);
pinMode(RECEIVER2_ON, INPUT_PULLUP);
pinMode(RECEIVER2_OFF, INPUT_PULLUP);
pinMode(RFM95_RST, OUTPUT);
digitalWrite(RFM95_RST, HIGH);
// manual reset
digitalWrite(RFM95_RST, LOW);
delay(10);
digitalWrite(RFM95_RST, HIGH);
delay(10);
while (!rf95.init()) {
while (1);
}
if (!rf95.setFrequency(RF95_FREQ)) {
while (1);
}
// Modem Config chosen for low data rate but long range
RH_RF95::ModemConfig modem_config = {
0x64, // Reg 0x1D: BW=62,5kHz, Coding=4/6, Header=explicit
0x94, // Reg 0x1E: Spread=512chips/symbol-> SF = 9, CRC=enable
0x00 // Reg 0x26: LowDataRate=OFF, Agc=OFF : 0x00
};
rf95.setModemRegisters(&modem_config);
rf95.spiWrite(RH_RF95_REG_0C_LNA, 0x23);//LNA to MAX
rf95.setPreambleLength(250);
rf95.setTxPower(23);
}
bool setFreq(float freq){
if(curFreq == freq) return true;
if (!rf95.setFrequency(freq)) {
return false;
}
delay(100);
curFreq = freq;
return true;
}
void setOutput(float freq, bool out){
digitalWrite(LEDSEND, HIGH);
setFreq(freq);
char data[] = "A0!";
if(out)
data[1] = '1';
else
data[1] = '0';
rf95.send((uint8_t *)data, sizeof(data));
rf95.waitPacketSent();
digitalWrite(LEDSEND, LOW);
}
void loop()
{
//define the desired button functions here, note: if a button is pushed, the digitalRead value is 0, else it is 1
//first receiver ON/OFF
if(digitalRead(RECEIVER1_ON) == 0)
setOutput(RECEIVER1, 1);
else if(digitalRead(RECEIVER1_OFF) == 0)
setOutput(RECEIVER1, 0);
//second receiver ON/OFF
else if(digitalRead(RECEIVER2_ON) == 0)
setOutput(RECEIVER2, 1);
else if(digitalRead(RECEIVER2_OFF) == 0)
setOutput(RECEIVER2, 0);
else
delay(10);
}
| true |
b508d43c854cc8cf42265e904ac4bc72f7de5d9a | C++ | 9OMShitikov/mipt-search | /lib/server/engine/ranking.cpp | UTF-8 | 829 | 2.703125 | 3 | [] | no_license | #include "ranking.h"
#include <stdexcept>
void DummyRanker::Init(IndexStats stats)
{
// Your code goes here
UNUSED(stats);
};
void DummyRanker::ProceedHit(Hit hit)
{
// Your code goes here
UNUSED(hit);
};
double DummyRanker::Complete()
{
// Your code goes here
return 0;
}
void BM25Ranker::Init(IndexStats stats)
{
// Your code goes here
UNUSED(stats);
}
void BM25Ranker::ProceedHit(Hit hit)
{
// Your code goes here
UNUSED(hit);
}
double BM25Ranker::Complete()
{
// Your code goes here
return 0;
}
std::shared_ptr<IRanker> CreateRanker(RankerType rankerType)
{
switch (rankerType)
{
case RankerType::DummyRanker:
{
return std::make_shared<DummyRanker>();
}
case RankerType::BM25:
{
return std::make_shared<BM25Ranker>();
}
default: throw std::runtime_error("Unimplemented ranker");
}
} | true |
e82d8418d668732077ef055b64d48fb2c76100d9 | C++ | yurivict/ChemWiz | /periodic-table-data.cpp | UTF-8 | 1,402 | 2.625 | 3 | [
"BSD-2-Clause",
"MIT"
] | permissive |
#include <nlohmann/json.hpp>
#include <boost/format.hpp>
#include <fstream>
#include <stdlib.h>
#include "periodic-table-data.h"
#include "xerror.h"
PeriodicTableData PeriodicTableData::singleInstance; // statically initialized instance
PeriodicTableData::PeriodicTableData() {
using json = nlohmann::json;
auto getStr = [](json &j) {return j.is_null() ? "" : j;};
auto getFlt = [](json &j) -> double {return j.is_null() ? 0. : (double)j;};
std::ifstream file;
file.open("contrib/Periodic-Table-JSON/PeriodicTableJSON.json", std::ifstream::in);
if (!file.is_open())
abort();
auto parsed = json::parse(file);
auto elts = parsed["elements"];
data.resize(elts.size());
unsigned eIdx = 0;
for (auto e : elts) {
auto &eData = data[eIdx++];
eData.name = e["name"];
eData.appearance = getStr(e["appearance"]);
eData.atomic_mass = e["atomic_mass"];
eData.boil = getFlt(e["boil"]);
eData.category = e["category"];
eData.symbol = e["symbol"];
symToElt[eData.symbol] = eIdx;
}
}
const PeriodicTableData::ElementData& PeriodicTableData::operator()(unsigned elt) const {
return data[elt-1];
}
unsigned PeriodicTableData::elementFromSymbol(const std::string &sym) const {
auto i = symToElt.find(sym);
if (i == symToElt.end())
ERROR(str(boost::format("Not an element name: %1%") % sym));
return i->second;
}
| true |
9c985c0a5fb932e80d9060d440846c4c07dcd6eb | C++ | USF-COT/LirLogger | /IFlowMeterListener.hpp | UTF-8 | 593 | 2.59375 | 3 | [] | no_license |
#ifndef IFLOWMETERLISTENER_HPP
#define IFLOWMETERLISTENER_HPP
#include <map>
#include <string>
#include <time.h>
using namespace std;
class IFlowMeterListener{
public:
virtual ~IFlowMeterListener(){}
virtual void flowMeterStarting() = 0; // Allows the listener to setup anything necessary on io thread
virtual void processFlowReading(time_t timestamp, int count, double flowRate) = 0; // readings are passed from io thread to this function
virtual void flowMeterStopping() = 0; // Allows the listener to close anything setup on the io thread
};
#endif
| true |
46e1031c601b6487b393130283cbe154a24e5426 | C++ | TimManders/Machiavelli | /MachiavelliServer/Server/Utils.h | UTF-8 | 635 | 2.765625 | 3 | [] | no_license | #pragma once
#include <random>
#include <algorithm>
class Utils
{
private:
static int seed;
static std::mt19937 rng;
static std::random_device dev;
static std::default_random_engine dre;
public:
static int RandomNumber(int max);
static int RandomNumber(int min, int max);
static std::default_random_engine GetRandomEngine();
static std::string ToLowerCase(std::string string);
static std::string <rim(std::string &s);
static std::string &rtrim(std::string &s);
static std::string &trim(std::string &s);
static std::string ToLowerAndTrim(std::string string);
static int ParseInt(std::string stoi);
};
| true |
b70668daf7cb60264966eba96547367e5e173199 | C++ | CapacitorSet/progetto-algoritmi | /src/analysis.cpp | UTF-8 | 3,639 | 2.953125 | 3 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | #include "analysis.h"
#include <iostream>
using namespace analysis;
// Pop an operand, push it into the list of nodes, and return a pointer to the node
Node *Implementation::fetch_operand(Engine::OperandStack &stack) {
nodes.push_front(pop(stack));
return &nodes.front();
}
// Initializes the circuit state to simple, childless flip flops
void Implementation::initialize(std::vector<Node> &state) {
for (size_t i = 0; i < state.size(); i++)
state[i] = {ast::Flipflop{i}, {}};
}
// Just creates a new node with the appropriate children
void Implementation::on_operator(ast::Operator astOperator, Engine::OperandStack &stack) {
switch (arity(astOperator)) {
case 1:
stack.push(Node{astOperator, {fetch_operand(stack)}});
break;
case 2:
stack.push(Node{astOperator, {fetch_operand(stack), fetch_operand(stack)}});
break;
}
}
std::string Path::toString(const ast::Module &module) const {
std::string ret = std::visit([&](auto &&token) { return module.name_of(token); }, path[0]);
for (size_t i = 1; i < path.size(); i++)
ret += " -> " + std::visit([&](auto &&token) { return module.name_of(token); }, path[i]);
return ret;
}
// Walk the graph starting from this output
void GraphWalker::walk_output(ast::Output output) {
current_lvalue_hierarchy.emplace_back(output);
walk(outputs[output.offset]);
current_lvalue_hierarchy.pop_back();
}
void GraphWalker::walk(const Node &node) {
Token token = node.token;
current_path.push_back(token);
std::visit([&](auto &&token) { return this->process(token); }, token);
for (Node *const child : node.children)
if (child != nullptr)
walk(*child);
current_path.pop_back();
}
// Add this input to the relevant logic cones, and update the shortest/longest path if needed
void GraphWalker::process(ast::Input input) {
for (const ast::LValue &item : current_lvalue_hierarchy)
logic_cones[item].emplace(input.offset);
uint16_t length = current_path.size();
if (length > longest_path.length())
longest_path.path = std::vector(current_path.begin(), current_path.end());
if (length < shortest_path.length() || shortest_path.length() == 0)
shortest_path.path = std::vector(current_path.begin(), current_path.end());
}
// Visit this FF if it hasn't been visited so far
void GraphWalker::process(ast::Flipflop ff) {
bool ff_was_visited = visited_ffs.find(ff) != visited_ffs.end();
if (ff_was_visited) {
LogicCone logic_cone = logic_cones[ff];
for (const ast::LValue &item : current_lvalue_hierarchy)
logic_cones[item].merge(logic_cone);
} else {
visited_ffs.emplace(ff);
current_lvalue_hierarchy.emplace_back(ff);
walk(flipflops[ff.offset]);
current_lvalue_hierarchy.pop_back();
}
}
void GraphWalker::process(ast::Operator) { ; }
void analysis::run(const ast::Module &module) {
std::vector<Node> inputs;
// The i-th input is just a childless wrapper around the ast::Input token
for (size_t i = 0; i < module.input_size(); i++)
inputs.push_back(Node{ast::Input{i}, {}});
Implementation impl;
Circuit ckt(module, impl);
ckt.evaluate(inputs);
GraphWalker walker(ckt);
for (size_t i = 0; i < ckt.outputs().size(); i++)
walker.walk_output(ast::Output{i});
std::cout << "Shortest path: " << walker.shortest_path.toString(module) << std::endl;
std::cout << "Longest path: " << walker.longest_path.toString(module) << std::endl;
for (size_t i = 0; i < module.output_size(); i++) {
ast::Output output{i};
std::cout << "Logic cone for " << module.name_of(output) << ":" << std::endl;
for (const size_t &item_idx : walker.logic_cones[output])
std::cout << " - " << module.name_of(ast::Input{item_idx}) << std::endl;
}
} | true |
1721b321b91e3117320387ddd1c06ec03bddb933 | C++ | chocholacek/Priority-queues | /src/ViolationHeap/violation_heap_tests.cpp | UTF-8 | 4,289 | 2.953125 | 3 | [
"MIT"
] | permissive | #define CATCH_CONFIG_MAIN
#include "../../catch/catch.hpp"
#include "violation_heap.hpp"
using vh = MC::ViolationHeap< int >;
struct Test : protected vh {
using Node = typename vh::Node;
using vh::Insert;
using vh::roots;
vh& base;
Test() : base(*this) {}
const Node* Insert(int k) {
return Insert(k, k);
}
const auto& Min() const {
REQUIRE_NOTHROW(vh::Min());
return vh::Min();
}
void DecreaseKey(const Node* n, int k) {
REQUIRE_NOTHROW(vh::DecreaseKey(n, k));
}
};
using Node = Test::Node;
TEST_CASE("Insert") {
Test t;
auto gm = [&t]() -> const Node & {
return t.Min();
};
SECTION("simple - one item") {
auto n = t.Insert(0);
REQUIRE(n->key == 0);
auto &min = gm();
CHECK(min.key == 0);
REQUIRE(min.next == &min);
REQUIRE(min.prev == nullptr);
REQUIRE(min.child == nullptr);
}
SECTION("multiple - two items lesser first") {
auto n = t.Insert(0);
auto m = t.Insert(1);
REQUIRE(n->next == m);
REQUIRE(m->next == n);
CHECK(n->key == 0);
CHECK(m->key == 1);
auto& min = gm();
CHECK(min.key == 0);
}
SECTION("multiple - two items larger first") {
auto m = t.Insert(1);
auto n = t.Insert(0);
REQUIRE(n->next == m);
REQUIRE(m->next == n);
CHECK(n->key == 0);
CHECK(m->key == 1);
auto& min = gm();
CHECK(min.key == 0);
}
}
TEST_CASE("ExtractMin") {
SECTION("Simple") {
Test t;
auto n = t.Insert(0);
auto i = t.base.ExtractMin();
REQUIRE_THROWS(t.base.Min());
CHECK(i->key == 0);
}
Test t;
t.Insert(0);
t.Insert(1);
t.Insert(2);
SECTION("Complicated - 3 elements") {
auto i = t.base.ExtractMin();
CHECK(i->key == 0);
auto& m = t.Min();
REQUIRE(m.key == 1);
REQUIRE(m.next != nullptr);
CHECK(m.next->key == 2);
REQUIRE(m.next->next == &m);
REQUIRE(m.prev == nullptr);
REQUIRE(m.child == nullptr);
}
SECTION("Complicated - 4 elements") {
t.Insert(3);
auto i = t.base.ExtractMin();
CHECK(i->key == 0);
auto&m = t.Min();
REQUIRE(m.key == 1);
// REQUIRE(m.child != nullptr);
// auto c = m.child;
// CHECK(c->key == 3);
// REQUIRE(c->prev == &m);
// REQUIRE(c->next != nullptr);
// REQUIRE(c->child == nullptr);
//
//
// auto c2 = c->next;
// CHECK(c2->key == 2);
// REQUIRE(c2->prev == c);
// REQUIRE(c2->next == nullptr);
// REQUIRE(c2->child == nullptr);
}
}
//TEST_CASE("Node - Replace") {
// using Node = vh::NodeType;
//
// Node r(0, 0);
// r.next = &r;
//
// SECTION("First - son") {
// Node n(1, 1);
// Node m(2, 2);
// n.next = &m;
// m.prev = &n;
// n.prev = &r;
//
// r.child = &n;
//
// Node x(3, 3);
// x.prev = &n;
// n.child = &x;
// Node y(4, 4);
// x.next = &y;
// y.prev = &x;
//
//// n.Replace(&x);
//// n.Replace(&y);
//
// Node z(5, 5);
// z.prev = &m;
// m.child = &z;
//
// Node a(6,6);
// a.prev = &z;
// z.next = &a;
//
// m.Replace(&z);
//// m.Replace(&a);
// }
//
//
//}
TEST_CASE("DecreaseKey") {
Test t;
auto f = t.Insert(5);
SECTION("single element - invalid key") {
REQUIRE_THROWS_AS(t.base.DecreaseKey(&t.Min(), 10), std::logic_error);
}
SECTION("single element - valid key") {
t.DecreaseKey(f, 0);
CHECK(t.Min().key == 0);
}
SECTION("multiple elements - no change") {
auto s = t.Insert(10);
t.DecreaseKey(s, 8);
auto& min = t.Min();
REQUIRE(min.key == 5);
REQUIRE(min.next->key == 8);
REQUIRE(min.next->next == &min);
}
SECTION("multiple elements - new min") {
auto s = t.Insert(10);
t.DecreaseKey(s, 0);
auto& min = t.Min();
REQUIRE(min.key == 0);
REQUIRE(min.next->key == 5);
REQUIRE(min.next->next == &min);
}
}
| true |
a4a9763865147a3e2d42e55cb79d16121daa936d | C++ | qt-web/SecuCarServer | /SecuCarServer/DBTableRecords/trackrecord.cpp | UTF-8 | 3,089 | 2.59375 | 3 | [] | no_license | #include "trackrecord.h"
#include "logger.h"
#include <sstream>
#include <string>
CTrackRecord::CTrackRecord()
{
}
CTrackRecord::CTrackRecord(int trackId, int deviceId, int startTimestmap, std::__cxx11::string startLocation, int endTimestamp, std::__cxx11::string endLocation, int distance, int maneouverAssessment)
{
m_trackId = trackId;
m_deviceId = deviceId;
m_startTimestamp = startTimestmap;
m_startLocation = startLocation;
m_endTimestamp = endTimestamp;
m_endLocation = endLocation;
m_distance = distance;
m_trackAssessment = maneouverAssessment;
LogRecord();
}
CTrackRecord::CTrackRecord(const CTrackRecord &rec)
{
m_trackId = rec.GetTrackId();
m_deviceId = rec.GetDeviceId();
m_startTimestamp = rec.GetStartTimestmap();
m_startLocation = rec.GetStartLocation();
m_endTimestamp = rec.GetEndTimestamp();
m_endLocation = rec.GetEndLocation();
m_distance = rec.GetDistance();
m_trackAssessment = rec.GetTrackAssessment();
}
int CTrackRecord::GetTrackId() const
{
return m_trackId;
}
int CTrackRecord::GetDeviceId() const
{
return m_deviceId;
}
int CTrackRecord::GetStartTimestmap() const
{
return m_startTimestamp;
}
std::string CTrackRecord::GetStartLocation() const
{
return m_startLocation;
}
int CTrackRecord::GetEndTimestamp() const
{
return m_endTimestamp;
}
std::string CTrackRecord::GetEndLocation() const
{
return m_endLocation;
}
int CTrackRecord::GetDistance() const
{
return m_distance;
}
int CTrackRecord::GetTrackAssessment() const
{
return m_trackAssessment;
}
void CTrackRecord::SetTrackId(int id)
{
m_trackId = id;
}
void CTrackRecord::SetDeviceId(int id)
{
m_deviceId = id;
}
void CTrackRecord::SetStartTimestamp(int timestamp)
{
m_startTimestamp = timestamp;
}
void CTrackRecord::SetStartLocation(std::string location)
{
m_startLocation = location;
}
void CTrackRecord::SetEndTimestamp(int timestamp)
{
m_endTimestamp = timestamp;
}
void CTrackRecord::SetEndLocation(std::string endLocation)
{
m_endLocation = endLocation;
}
void CTrackRecord::SetDistance(int distance)
{
m_distance = distance;
}
void CTrackRecord::SetTrackAssessment(int assessment)
{
m_trackAssessment = assessment;
}
void CTrackRecord::LogRecord()
{
LOG_INFO("trackId: %d, idDevice: %d, startDate: %d, startLocation: %s, endDate: %d, endLocation: %s, distance: %d, trackAssessment: %d",
m_trackId, m_deviceId, m_startTimestamp, m_startLocation.c_str(), m_endTimestamp, m_endLocation.c_str(), m_distance, m_trackAssessment);
}
std::__cxx11::string CTrackRecord::Serialize()
{
std::ostringstream ss;
ss << "idTrack:" << m_trackId << "," <<
"idDevice:" << m_deviceId << "," <<
"startDate:" << m_startTimestamp << "," <<
"startLocation:" << m_startLocation << "," <<
"endDate:" << m_endTimestamp << "," <<
"endLocation:" << m_endLocation << "," <<
"distance:" << m_distance << "," <<
"trackAssessment:" << m_trackAssessment;
return ss.str();
}
| true |
265ef219a174282f9e6c9fe8f246a568e05be24e | C++ | karaketir16/competitive | /karaketir16/CodeForces/C. Replace To Make Regular Bracket Sequence.cpp | UTF-8 | 2,352 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
#define pb push_back
#define fi first
#define sc second
#define inf 1000000000000000LL
#define MP make_pair
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define dbg(x) cerr<<#x<<":"<<x<<endl
#define N 100005
#define MOD 1000000007
#define orta ((a+b)/2)
using namespace std;
int main()
{
char ch;
scanf("%c",&ch);
int total=0;
int s=0;//{}
int n=0;//()
int k=0;//[]
int ku=0;//<>
int say=0;
stack<char> prt;
while(ch!='\n')
{
if(ch=='{')
{
s++;
total++;
prt.push('}');
}
if(ch=='<')
{
ku++;
total++;
prt.push('>');
}
if(ch=='[')
{
k++;
total++;
prt.push(']');
}
if(ch=='(')
{
n++;
total++;
prt.push(')');
}
//
//
//
if(ch=='}')
{
s--;
total--;
if(total<0)
{
cout<<"Impossible";
exit(0);
}
if(prt.top()!=ch)
{
say++;
}
prt.pop();
}
if(ch=='>')
{
ku--;
total--;
if(total<0)
{
cout<<"Impossible";
exit(0);
}
if(prt.top()!=ch)
{
say++;
}
prt.pop();
}
if(ch==']')
{
k--;
total--;
if(total<0)
{
cout<<"Impossible";
exit(0);
}
if(prt.top()!=ch)
{
say++;
}
prt.pop();
}
if(ch==')')
{
n--;
total--;
if(total<0)
{
cout<<"Impossible";
exit(0);
}
if(prt.top()!=ch)
{
say++;
}
prt.pop();
}
scanf("%c",&ch);
}
if(total>0)
{
cout<<"Impossible";
exit(0);
}
int test=abs(n)+abs(ku)+abs(k)+abs(s);
cout<<say;
return 0;
} | true |
cd1c52369ab0907c658bcc8e41d71fec51b689a6 | C++ | bailin1125/cluster-management | /jiqun_organization/login.cpp | GB18030 | 2,156 | 2.65625 | 3 | [] | no_license | #include <sstream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#pragma warning(disable : 4996)
using namespace std;
const string change = "\\HIGH_POWER_XRD";
//ע12ıӳ·ԼԱȷ
int main(int argc, char* argv[])
{
int i = 0, j = 0;
string command[10];
command[0] = "net use * /del /y";
command[1]="net use Z: \\\\10.1.1.10\\";
//cout << command[0] << endl;
//cout << command[1] << endl;
int flag = 0;
string name;
do
{
cout << "please enter your user name:" << endl;
cin >> name;
cout << "your username is :" << name << endl;
cout << "please type y or n to make sure" << endl;
char sure[20] = { '\0' };
cin >> sure;
if (sure[0] == 'y' &&sure[1] == '\0')
{
flag = 1;
}
else if (sure[0] == 'n' &&sure[1] == '\0')
{
cout << "try another time" << endl;
name.clear();
continue;
}
else
{
cout << "please type y or n " << endl;
cout << "try another time" << endl;
name.clear();
continue;
}
}while (flag == 0);
//ҪDzǹԱǵĻܼӺ
if (name == "tem_eds" || name == "sem_eds" || name == "sem" || name == "fib" || name == "ebsd_eds" || name == "xrf" || name == "xrd" || name == "xps" || name == "high_power_xrd" || name == "zem_3" || name == "hall" || name == "tem")
{
cout << "welcome the admin.!" << endl;
for (int i = 0; i < name.length(); i++)
{
if (name[i] >= 'a'&&name[i] <= 'z')
{
name[i] = name[i] - 32;
}
}
//cout << name << endl;
//system("pause");
system(command[0].c_str());
system((command[1] + name).c_str());
//cout << command[0] << endl;
//cout << command[1] + name << endl;
cout << "all total work done! type enter to exit." << endl;
system("pause");
return 0;
}
else
{
name = name + change;
system(command[0].c_str());
system((command[1] + name).c_str());
//cout << command[0] << endl;
//cout << command[1]+name << endl;
cout << "all total work done! type enter to exit." << endl;
system("pause");
return 0;
}
} | true |
4798055b9bd2f3da9e623e756bb6c68e71404c61 | C++ | kzufelt/C-Plus-Plus | /Lab 9/Food Fight.cpp | UTF-8 | 6,334 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <array>
#include <string>
#include <time.h>
#include <vector>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#include "restaurantClass.h"
int getOption(int minrange, int maxrange)//This function is more or less taken from one of the labs we did
{
int input = 0;
bool done = false;
while(!done)
{
cout << "Please select an option:" << endl;
input = 0;
cin >> input;
cin.ignore(1000,'\n');
if(cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Invalid option" << endl;
}
else if(input < minrange || input > maxrange)
{
cout << "Error: Invalid option number" << endl;
}
else
{
done = true;
}
}
return input;
}
string getName(string message)
{
string input = "";
bool done = false;
while(!done)
{
cout << message << endl;
input = "";
getline(cin, input);
if(cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Invalid name" << endl;
}
else
{
done = true;
}
}
return input;
}
int main()
{
restaurantClass restaurants;
string newrestaurantname, newRankingString, restaurantFileName, writeFile;
char newRankingChar[1];
int menuoption=0, totalrounds, newRankingInt, newRankingIntTens;
restaurants.size=0;
cout << "Food Fight\n";
restaurantFileName=getName("Please enter the name of a .txt file to upload restaurant data:\n");//Start to load data file
restaurantFileName.append(".txt");
fstream userFile (restaurantFileName);
while (!userFile.is_open())
{
cout << "Sorry. The filename you entered, \"" << restaurantFileName << "\", is not valid.\nPlease note that this program only accepts text files.\nPlease make sure that your file is in the same directory as this program.\n" << endl;
restaurantFileName=getName("Please enter a filename to upload restaurant data:\n");
restaurantFileName.append(".txt");
userFile.open (restaurantFileName);
}
if (userFile.is_open())
{
while ( userFile.good() )
{
getline(userFile,newrestaurantname,',');
restaurants.restaurantNames.push_back(newrestaurantname);
cout << newrestaurantname << " with a score of ";
getline(userFile,newRankingString);//This converts whatever comes after the "," to a string
newRankingChar[0]=newRankingString[newRankingString.size()-1];//This pulls the last digit of the string into a char
newRankingInt = atoi (newRankingChar);//This converts the ones digit to an int
if (newRankingString.size() > 1)
{
newRankingChar[0]=newRankingString[newRankingString.size()-2];//This pulls the tens digit of the string into a char
newRankingIntTens = atoi (newRankingChar);//This converts the tens digit to an int
}
else newRankingIntTens=0;
restaurants.rankings.push_back(newRankingInt+10*newRankingIntTens);
cout << newRankingString << "\n";
restaurants.size++;
}
}//End to load data file
do
{
cout << "\n\n\nMenu\n\n\t1 - Display all restaurants\n\t2 - Add a restaurant\n\t3 - Remove a restaurant\n\t4 - Shuffle the array\n\t5 - Begin the tournament\n\t6 - Save and Quit\n\t7 - Quit without saving\n";
cin >> menuoption;
cout << "\n\n";
if (menuoption==1)//Display
{
for (int n=0;n<restaurants.size;n++)
{
cout << restaurants.restaurantNames[n] << " with a score of " << restaurants.rankings[n] << endl;
}
cout << "Total Restaurants: " << restaurants.size << endl;
}
else if (menuoption==2)//Add
{
getline(cin,newrestaurantname);
newrestaurantname=getName("Which restaurant would you like to add?: ");
if (restaurants.findrestaurant(newrestaurantname)!=-1)
{
cout << "That restaurant is already in the list.\n";
continue;
}
else if (restaurants.findrestaurant(newrestaurantname)==-1)
{
restaurants.restaurantNames.push_back(newrestaurantname);
restaurants.rankings.push_back(0);
restaurants.size++;
cout << "Added " << newrestaurantname << " to the list.\n";
}
}
else if (menuoption==3)//Remove
{
cout << "\nWhich restaurant would you like to remove?:";
getline (cin,newrestaurantname);
getline (cin,newrestaurantname);
if (restaurants.findrestaurant(newrestaurantname)==-1)
{
cout << "That restaurant is not on the list";
continue;
}
else if (restaurants.findrestaurant(newrestaurantname)!=-1)
{
restaurants.rankings.erase (restaurants.rankings.begin() + restaurants.findrestaurant(newrestaurantname));
restaurants.restaurantNames.erase (restaurants.restaurantNames.begin() + restaurants.findrestaurant(newrestaurantname));
cout << "Removed " << newrestaurantname << " from the list.\n";
restaurants.size--;
}
}
else if (menuoption==4)//Shuffle
{
restaurants.shuffle();
for (int n=0;n<restaurants.size;n++)
{
cout << restaurants.restaurantNames[n] << " with a score of " << restaurants.rankings[n] << endl;
}
cout << "Total Restaurants: " << restaurants.size << endl;
}
else if (menuoption==5)//Tournament
{
totalrounds=0;
for (double n=1;n<10;n++)//This loop check to make sure that the number of restaurants on the list is a power of 2
{
if (restaurants.size == pow(2.0,n))
{
totalrounds=n;
cout << totalrounds;
}
}
if (totalrounds==0)
{
cout << "The total number of restaurants must be a power of 2.\n";
continue;
}
for(int n=0;n<totalrounds;n++)
{
restaurants.tournament(totalrounds,n);
}
cout << "\n\nTonight we will eat dinner at " << restaurants.roundVictors[0] << endl;
system ("pause");
}
else if (menuoption==6)//Save to file
{
getline(cin,restaurantFileName);
restaurantFileName=getName("What filename do you want to save to?:");
restaurantFileName.append(".txt");
ofstream writeFile;
writeFile.open (restaurantFileName);
while (!writeFile.is_open())
{
cout << "Sorry. The filename you entered, \"" << restaurantFileName << "\", is not valid.\n" << endl;
restaurantFileName=getName("Please enter a filename to upload restaurant data:\n");
restaurantFileName.append(".txt");
writeFile.open (restaurantFileName);
}
if (userFile.is_open())
{
for (int n=0;n<restaurants.size;n++)
{
writeFile << restaurants.restaurantNames[n] << ", " << restaurants.rankings[n] << endl;
}
}
writeFile.close();
}
}
while (menuoption < 6);
return 0;
} | true |
ee118cf0a714be0ab66d6b507ebad530375a3e8b | C++ | zjkang/algorithm | /leetcode/152. Maximum Product Subarray.cpp | UTF-8 | 1,351 | 3.71875 | 4 | [] | no_license | /*
Author: Zhengjian Kang
Email: zhengjian.kang@nyu.edu
Problem: Maximum Product Subarray
Source: https://leetcode.com/problems/maximum-product-subarray/#/description
Difficulty: Medium
Topic: {Array, Dynamic Programming}
Company: Linkedin
Note:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
*/
class Solution {
public:
int maxProduct(int A[], int n) {
int result = A[0];
int maximum = A[0], minimum = A[0];
int curMax = A[0], curMin = A[0];
for (int i = 1; i < n; ++i) {
curMax = max({A[i], A[i] * maximum, A[i] * minimum});
curMin = min({A[i], A[i] * maximum, A[i] * minimum});
maximum = curMax;
minimum = curMin;
result = max(result, maximum);
}
return result;
}
};
class Solution {
public:
int maxProduct(int A[], int n) {
int res = A[0], minimum = A[0], maximum = A[0];
for(int i=1; i<n; i++){
if(A[i] < 0)
swap(minimum, maximum);
minimum = min(A[i], A[i]*minimum);
maximum = max(A[i], A[i]*maximum);
res = max(res, maximum);
}
return res;
}
};
| true |
22d74743ce4e3d3bab96ba112551f63574ecd156 | C++ | ChristopherValdez/dice-roll-game | /Dice_Roll_v8/main.cpp | UTF-8 | 10,387 | 3.59375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Christopher Valdez
* Date: 02/12/20
* Purpose: Dice game version 8. This game needed to include certain required functions and is not optimal. Some functions were added to meet grading requirements.
*/
// System Libraries
#include <iostream> // Input/Output Library
#include <string>
#include <iomanip>
#include <fstream> // File in and out
#include <ctime>
#include <cmath>
using namespace std;
// User Libraries
// Global Constants, no Global Variables are allowed
// Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc...
// Function Prototypes
int diceRoll();
void gameRules();
void playGame(int&, int&);
void gameRatio(int, int);
void highScores();
void sSort(string[],int = 4); // String sort default arg
void sSort(int[],int = 4); // Int sort default arg
int lnrSrch(string [], int);
void swap(int,int,string,string);
bool stop(bool);
void exit();
// Execution Begins Here!
int main(int argc, char** argv) {
// Set the random number seed
srand(time(NULL));
// Declare Variables
int choice, wins = 0, losses = 0;
bool playing = true;
string error = "Error: Invalid Entry, Please choose from the menu.";
// Initialize or input i.e. set variable values
// Map inputs -> outputs
do
{
// Main Menu
cout << "1. Play a round of Craps." << endl;
cout << "2. View Win/Loss Ratio." << endl;
cout << "3. View the Game Rules." << endl;
cout << "4. View High Scores." << endl;
cout << "5. Exit Program" << endl;
cout << "Make your choice: "; // Take user input
cin >> choice; // Store user input in var
if(!cin) // If the choice is not int clear and output error string
{
cin.clear();
cin.ignore(123, '\n');
clog << "\n" << error << "\n" << endl;
}
else if(cin){ // If input is integer then check switch case and run function
switch(choice)
{
case 1: // Begin a game with var wins and losses
playGame(wins, losses);
break;
case 2: // Display win/loss ratio
gameRatio(wins, losses);
break;
case 3: // Display game rules
gameRules();
break;
case 4: // Run highscore function
highScores();
break;
case 5: // Change bool playing to false
playing = stop(playing);
break;
default: // If the user choice is not a valid choice output error string
cout << endl;
clog << error << endl;
cout << endl;
break;
}
}
}while(playing == true);
// Display the outputs
// Exit stage right or left!
exit();
return 0;
}
int diceRoll()
{
// Initialize variables
const int dice = 6;
int gameResult = 0;
int dResult1 = 0;
int dResult2 = 0;
dResult1 = rand() % dice + 1; // Generate a random number, modulo by 6 plus on to make the range of random number between 1 and 6.
dResult2 = rand() % dice + 1; // This is dome individually for both dice to simulate individual random rolls. The result is save to var.
cout << endl;
cout << "You roll " << dResult1 << " and " << dResult2 << endl; // Display the results of the roll.
gameResult = dResult1 + dResult2; // store rusults to var and return the var.
return gameResult;
}
void gameRatio(int wins,int losses)
{
// Initialize variables
int perConv = 100;
float total = wins+losses;
float ratio = 0.0f;
cout << endl;
// Output wins and losses
cout << "Total Wins: " << wins << endl;
cout << "Total Losses: " << losses << endl;
// If statment for when the wins and losses = 0 output nothing.
if (wins == 0 || losses == 0){
ratio = 0;
cout << "";
}
// If wins are greater than losses a win rate is displayed and the ratio is output.
else if (isgreaterequal(wins,losses)){
ratio = wins/total;
cout << "\nYou have a " << setprecision(1) << fixed << ratio*perConv << "% win rate." << endl;
}
// If losses are greater than wins a loss rate is displayed and the ratio is output.
else if(isgreater(losses, wins)){
ratio = losses/total;
cout << "\nYou have a " << setprecision(1) << fixed << ratio*perConv << "% loss rate." << endl;
}
cout << endl;
}
void playGame(int& wins,int& losses){
// Initialize variables
int comeOut = 0, roll = 0, point = 0;
bool reRoll = true;
// Comeout is the first roll and is used to determine if the next roll wins losses or goes to next round.
comeOut = diceRoll();
cout << "Your total is " << comeOut << endl;
cout << endl;
// If 7 or 11 is rolled the user wins, win message is displayed and the win count is incremented
if (comeOut == 7 || comeOut == 11){
cout << "You have won the round!\n" << endl;
wins++;
}
// If 2 or 3 or 12 is rolled the user losses, loss message is displayed and the loss count is incremented
else if (comeOut == 2 || comeOut == 3 || comeOut == 12){
cout << "You have lost the round.\n" << endl;
losses++;
}
else{ // Otherwise the Comeout becomes the point and is checked against the roll var to determine if the user wins, losses or rerolls.
point = comeOut;
cout << "point is " << point << endl;
// While the user does not roll the point or 7 the user rolls again.
while(reRoll == true){
// diceRoll function is called and stored to var roll
roll = diceRoll();
cout << "Your total is " << roll << endl;
cout << endl;
if (roll == point){ // If the user rolls the point they win.
cout << "You have won the round!\n" << endl; // Win message is displayed.
wins++; // Win is incremented
reRoll = false; // reRoll bool is changed to false.
}
else{
if (roll == 7){ // If the user rolls 7 they loss.
cout << "You have lost the round.\n" << endl; // loss message is displayed
losses++; // losses incremented
reRoll = false; // reRoll var is changed to false
}
}
}
}
}
void gameRules(){
cout << endl;
static int view = 0; // Static int to count page views
for(int i=0; i<=70 ;i++){
cout << "*"; // Boarder is with 71 * characters
}
// Game rules are displayed.
cout << "\nCraps is a game of dice. The player rolls two dice and the " << endl;
cout << "sum of the two dice is calculated. If the player rolls a 7 or 11, " << endl;
cout << "The round is won. If the player rolls a 2, 3, or 12 the round is lost. " << endl;
cout << "If the player rolls any other number it then becomes the point number. " << endl;
cout << "The object of the game then is to roll the point number again before " << endl;
cout << "rolling a 7." << endl;
for(int i=0; i<=70 ;i++){
cout << "*";
}
view++; // View count is incremented
cout << "\n" << endl;
cout << "You have viewed this page " << view << " times.\n" << endl; // View count is displayed
}
void highScores(){
const int SCORE_SIZE = 4;
string names[SCORE_SIZE]; // Names array
int scores[SCORE_SIZE]; // Scores array
ifstream inputFile;
ofstream outputFile;
inputFile.open("Score.txt"); // Open input file
for(int i=0; i<SCORE_SIZE; i++){ // For loop names and score into arrays
inputFile >> names[i];
inputFile >> scores[i];
}
inputFile.close(); // Close file
sSort(names); // Overloaded function with default arg int
sSort(scores); // Overloaded function with default arg int
cout << "\n" << setw(18) << "High Scores:\n" << endl;
for (int i=0; i<SCORE_SIZE; i++){ // For loop output names
cout << setw(11) << names[i]; // Score output
cout << setw(5) << scores[i] << endl;
}
cout << endl;
int index = lnrSrch(names, SCORE_SIZE); // Linear search
if(index == -1){
cout << "\nYour name is not on the high score list.\n" << endl;
}
else{
cout << "\n" << "Your Score is: ";
cout << scores[index] << "\n" << endl;
}
outputFile.open("HighScore.txt"); // Open input file
for(int i=0; i<SCORE_SIZE; i++){ // For loop names and score into arrays
outputFile << names[i] << endl;
outputFile << scores[i] << endl;
}
outputFile.close(); // Close file
}
void sSort(string a[], int n){ // Sort function for highscore names.
int startScan, minIndex;
string minValue;
for (startScan = 0; startScan < (n - 1); startScan++){
minIndex = startScan;
minValue = a[startScan];
for(int index = startScan + 1; index < n; index++){
if (a[index] < minValue){
minValue = a[index];
minIndex = index;
}
}
a[minIndex] = a[startScan];
a[startScan] = minValue;
}
}
void sSort(int a[], int n){ // Sort function for highscore scores.
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (n - 1); startScan++){
minIndex = startScan;
minValue = a[startScan];
for(int index = startScan + 1; index < n; index++){
if (a[index] < minValue){
minValue = a[index];
minIndex = index;
}
}
a[minIndex] = a[startScan];
a[startScan] = minValue;
}
}
int lnrSrch(string a[], int n){ // Linear search for user inout name from highscore list
string val;
cout << "What is your name: ";
cin >> val;
for (int i = 0; i < n; i++){
if (val == a[i]){
return i;
}
}
return -1;
}
bool stop(bool playing){ // Stop function is called to end game
playing = false;
return playing;
}
void exit(){ // Exit function to close program
cout << "\nClosing Program" << endl;
exit(0);
}
| true |
5e43021f59f54c2593d27d6716cffd0db9524931 | C++ | lasagnaphil/gengine | /gengine/Texture.cpp | UTF-8 | 3,370 | 3.046875 | 3 | [] | no_license | //
// Created by lasagnaphil on 19. 3. 14.
//
#include "Texture.h"
#include <iostream>
#include <cmath>
Ref<Texture> Texture::fromImage(Ref<Image> image) {
Ref<Texture> tex = Resources::make<Texture>();
tex->loadFromImage(image);
return tex;
}
Ref<Texture> Texture::fromNew(uint32_t width, uint32_t height) {
Ref<Texture> tex = Resources::make<Texture>();
tex->width = width;
tex->height = height;
tex->wrapS = GL_REPEAT;
tex->wrapT = GL_REPEAT;
tex->filterMin = GL_LINEAR_MIPMAP_LINEAR;
tex->filterMax = GL_LINEAR;
tex->imageFormat = GL_RGB;
tex->internalFormat = GL_RGB;
glGenTextures(1, &tex->id);
glBindTexture(GL_TEXTURE_2D, tex->id);
glTexImage2D(GL_TEXTURE_2D,
0, tex->internalFormat,
width, height,
0, tex->imageFormat, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
return tex;
}
Ref<Texture> Texture::fromSingleColor(glm::vec3 color) {
Ref<Texture> tex = Resources::make<Texture>();
tex->width = 1;
tex->height = 1;
tex->wrapS = GL_REPEAT;
tex->wrapT = GL_REPEAT;
tex->filterMin = GL_LINEAR_MIPMAP_LINEAR;
tex->filterMax = GL_LINEAR;
tex->imageFormat = GL_RGB;
tex->internalFormat = GL_RGB;
char data[3];
data[0] = std::max(0, std::min(255, (int)floorf(color.r * 256.0f)));
data[1] = std::max(0, std::min(255, (int)floorf(color.g * 256.0f)));
data[2] = std::max(0, std::min(255, (int)floorf(color.b * 256.0f)));
glGenTextures(1, &tex->id);
glBindTexture(GL_TEXTURE_2D, tex->id);
glTexImage2D(GL_TEXTURE_2D,
0, tex->internalFormat,
tex->width, tex->height,
0, tex->imageFormat, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
return tex;
}
void Texture::loadFromImage(Ref<Image> image) {
width = image->width;
height = image->height;
wrapS = GL_REPEAT;
wrapT = GL_REPEAT;
filterMin = GL_LINEAR_MIPMAP_LINEAR;
filterMax = GL_LINEAR;
int nrComponents = image->nrChannels;
if (nrComponents == 1) {
imageFormat = GL_RED;
internalFormat = GL_RED;
}
else if (nrComponents == 3) {
imageFormat = GL_RGB;
internalFormat = GL_RGB;
}
else if (nrComponents == 4) {
imageFormat = GL_RGBA;
internalFormat = GL_RGBA;
}
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D,
0, internalFormat,
width, height,
0, imageFormat, GL_UNSIGNED_BYTE, image->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterMin);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterMax);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::bind() {
glBindTexture(GL_TEXTURE_2D, id);
}
void Texture::dispose() {
glDeleteTextures(1, &id);
}
| true |
beff04ca800bf9feacd372a21eabcf04fe03f284 | C++ | jsgaobiao/CampusIROS | /ECSegmentation.cpp | UTF-8 | 2,608 | 2.734375 | 3 | [] | no_license | #include "ECSegmentation.h"
#define INF 21474836
ECSegmentation::ECSegmentation():treePtr(new pcl::search::KdTree<pcl::PointXYZ>),
cloudPtr(new pcl::PointCloud<pcl::PointXYZ>)
{
// Nothing to do
}
void ECSegmentation::initialize(double _clusterTolerance,
int _minClusterSize,
int _maxClusterSize)
{
cluster_indices.clear();
// Creating the KdTree object for the search method of the extraction
treePtr->setInputCloud (cloudPtr);
ec.setClusterTolerance (_clusterTolerance); // 0.02 means 2cm
ec.setMinClusterSize (_minClusterSize);
ec.setMaxClusterSize (_maxClusterSize);
ec.setSearchMethod (treePtr);
ec.setInputCloud (cloudPtr);
ec.extract (cluster_indices);
}
bool ECSegmentation::isPerson(std::vector<pcl::PointIndices>::const_iterator it)
{
double minX = INF;
double minY = INF;
double minZ = INF;
double maxX = -INF;
double maxY = -INF;
double maxZ = -INF;
for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit) {
double x = cloudPtr->points[*pit].x;
double y = cloudPtr->points[*pit].y;
double z = cloudPtr->points[*pit].z;
minX = x < minX ? x : minX;
minY = y < minY ? y : minY;
minZ = z < minZ ? z : minZ;
maxX = x > maxX ? x : maxX;
maxY = y > maxY ? y : maxY;
maxZ = z > maxZ ? z : maxZ;
}
if (maxZ - minZ < 0.6 || maxZ - minZ > 2.0) return false;
if (maxX - minX > 1.8 || maxY - minY > 1.8) return false;
if (maxZ > -0.1 || maxZ < -1.0) return false;
return true;
}
void ECSegmentation::getSegResult(std::vector<cv::Vec3f> &buffer, std::vector<cv::Vec3b> &bufferColor)
{
int objCnt = 0;
for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)
{
int B = std::rand() % 250;
int G = std::rand() % 250;
int R = std::rand() % 250;
if (! isPerson(it)) {
continue;
B = 255;
G = 0;
R = 0;
}
else {
B = 0;
G = 0;
R = 255;
}
for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit) {
buffer.push_back(cv::Vec3f(cloudPtr->points[*pit].x, cloudPtr->points[*pit].y, cloudPtr->points[*pit].z));
bufferColor.push_back(cv::Vec3b(B, G, R));
}
objCnt ++;
}
printf("Obj Num: %d\n", objCnt);
}
| true |
99b7e23d9bef528723db9f349fb05c714460878f | C++ | jkjan/Baekjoon | /15591.cpp | UTF-8 | 1,259 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <vector>
#define MAX_SIZE 5001
#define INF 1000000001
using namespace std;
typedef struct node {
int num, dist;
} node;
int N, Q;
vector<node> graph[MAX_SIZE];
void input();
int query();
int main() {
input();
for (int i = 0; i < Q; ++i) {
printf("%d\n", query());
}
return 0;
}
void input() {
int p, q, r;
scanf(" %d %d", &N, &Q);
for (int i = 0; i < N-1; ++i) {
scanf(" %d %d %d", &p, &q, &r);
graph[p].push_back({q, r});
graph[q].push_back({p, r});
}
}
int query() {
int k, v;
scanf(" %d %d", &k, &v);
queue<int> willVisit;
int dist[MAX_SIZE];
bool visited[MAX_SIZE] = {false, };
fill(dist, dist+MAX_SIZE, INF);
visited[v] = true;
willVisit.push(v);
int cnt = 0;
while (!willVisit.empty()) {
int nowVisit = willVisit.front();
willVisit.pop();
for (auto adj : graph[nowVisit]) {
if (!visited[adj.num]) {
dist[adj.num] = min(adj.dist, dist[nowVisit]);
willVisit.push(adj.num);
visited[adj.num] = true;
if (dist[adj.num] >= k)
cnt++;
}
}
}
return cnt;
}
| true |
637983f213b5b828391cdd2965dee0ef95b2416f | C++ | akraycek/fast-dat-parser | /parser.cpp | UTF-8 | 3,381 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include "block.hpp"
#include "functors.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"
int main (int argc, char** argv) {
std::unique_ptr<processFunctor_t> delegate;
size_t memoryAlloc = 200 * 1024 * 1024;
size_t nThreads = 1;
// parse command line arguments
for (auto i = 1; i < argc; ++i) {
const auto arg = argv[i];
size_t functorIndex = 0;
if (sscanf(arg, "-f%lu", &functorIndex) == 1) {
assert(delegate == nullptr);
if (functorIndex == 0) delegate.reset(new dumpHeaders());
else if (functorIndex == 1) delegate.reset(new dumpScripts());
else if (functorIndex == 2) delegate.reset(new dumpScriptIndexMap());
else if (functorIndex == 3) delegate.reset(new dumpScriptIndex());
else if (functorIndex == 4) delegate.reset(new dumpStatistics());
else if (functorIndex == 5) delegate.reset(new dumpTxOutIndex());
else if (functorIndex == 6) delegate.reset(new dumpOutputValuesOverHeight());
continue;
}
if (sscanf(arg, "-j%lu", &nThreads) == 1) continue;
if (sscanf(arg, "-m%lu", &memoryAlloc) == 1) continue;
if (delegate && delegate->initialize(arg)) continue;
assert(false);
}
assert(delegate != nullptr);
// pre-allocate buffers
const auto halfMemoryAlloc = memoryAlloc / 2;
FixedSlice iobuffer(halfMemoryAlloc);
std::cerr << "Allocated IO buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
FixedSlice buffer(halfMemoryAlloc);
std::cerr << "Allocated active buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
ThreadPool<std::function<void(void)>> pool(nThreads);
std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;
size_t count = 0;
size_t remainder = 0;
size_t accum = 0;
while (true) {
const auto rbuf = iobuffer.drop(remainder);
const auto read = fread(rbuf.begin, 1, rbuf.length(), stdin);
const auto eof = static_cast<size_t>(read) < rbuf.length();
accum += read;
// wait for all workers before overwrite
pool.wait();
// copy iobuffer to buffer, allows iobuffer to be modified independently after
memcpy(buffer.begin, iobuffer.begin, halfMemoryAlloc);
auto data = buffer.take(remainder + read);
std::cerr << "-- Parsed " << count << " blocks (read " << read / 1024 << " KiB, " << accum / 1024 / 1024 << " MiB total)" << (eof ? " EOF" : "") << std::endl;
while (data.length() >= 88) {
// skip bad data (e.g bitcoind zero pre-allocations)
if (data.peek<uint32_t>() != 0xd9b4bef9) {
data.popFrontN(1);
continue;
}
// skip bad data cont.
const auto header = data.drop(8).take(80);
if (!Block(header).verify()) {
data.popFrontN(1);
std::cerr << "--- Invalid block" << std::endl;
continue;
}
// do we have enough data?
const auto length = data.drop(4).peek<uint32_t>();
const auto total = 8 + length;
if (total > data.length()) break;
data.popFrontN(8);
// send the block data to the threadpool
const auto block = Block(header, data.drop(80));
pool.push([block, &delegate]() {
delegate->operator()(block);
});
count++;
data.popFrontN(length);
}
if (eof) break;
// assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)
remainder = data.length();
memcpy(iobuffer.begin, data.begin, remainder);
}
return 0;
}
| true |
a370f6fe7270a7aa4d6b972ab9949bc5aec131d9 | C++ | mykfu/cpp_ped_in | /2kurs-pedag/lesson_06.cpp | UTF-8 | 1,390 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<string>
#define out(X) (cout << #X << " = " << X << endl)
using namespace std;
void lesson_06() {
char ch = 'a';
cout << "ch = " << ch << endl;
cout << "(int) ch = " << (int) ch << endl;
ch++;
cout << "after increment\n";
cout << "ch = " << ch << endl;
cout << "(int) ch = " << (int) ch << endl;
char str[12] = "chars array";
char str2[] = {'c', 'h', 'a', 'r', '\0'};
const char* str3 = "chars dyn array";
cout << "str3 = " << str3 << endl;
str3 = "new text";
cout << "str3 = " << str3 << endl;
cout << "strlen(str3) = " << strlen(str3) << endl;
string str4 = "text example";
out(str4);
string str5("pointer text example");
// size(), length()
for (int i = 0; i < str4.size(); i++)
{
cout << "str4_i"<< i << " = "
<< str4.at(i) << endl;
//str4[i];
}
//str4.empty()
//str4.clear()
// str4.resize()
string str6 = "asdf1234";
out(str6);
int count = 0;
for (int i = 0; i < str6.length(); i++)
{
if (str6.at(i) >= '0' &&
str6.at(i) <= '9')
count++;
}
cout << "digits count is " << count << endl;
out(str6.front());
out(str6.back());
out(str6.back());
out(str6.substr(4, 2));
//modifying
str6.append("new text");
out(str6);
str6.insert(4, "ASDF");
out(str6);
str6.replace(0, 4, "REPLACED");
out(str6);
out(str6.find("EP"));
out((int)str6.find("EPPP"));
str6.erase(3, 6);
out(str6);
} | true |
0a084ca191f2051e55e51926e222f1c5a206c0ad | C++ | lineCode/entity_spell_system | /world_spells/world_spell_data.cpp | UTF-8 | 5,891 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "world_spell_data.h"
int WorldSpellData::get_id() {
return _id;
}
void WorldSpellData::set_id(int value) {
_id = value;
}
SpellEnums::ColliderType WorldSpellData::get_collider_type() {
return _collider_type;
}
void WorldSpellData::set_collider_type(SpellEnums::ColliderType value) {
_collider_type = value;
}
Vector3 WorldSpellData::get_collider_box_extents() {
return _collider_box_extents;
}
void WorldSpellData::set_collider_box_extents(Vector3 value) {
_collider_box_extents = value;
}
float WorldSpellData::get_collider_sphere_radius() {
return _collider_sphere_radius;
}
void WorldSpellData::set_collider_sphere_radius(float value) {
_collider_sphere_radius = value;
}
SpellEnums::TargetType WorldSpellData::get_target_type() {
return _target_type;
}
void WorldSpellData::set_target_type(SpellEnums::TargetType value) {
_target_type = value;
}
int WorldSpellData::get_target_bone_id() {
return _target_bone_id;
}
void WorldSpellData::set_target_bone_id(int value) {
_target_bone_id = value;
}
bool WorldSpellData::get_move() {
return _move;
}
void WorldSpellData::set_move(bool value) {
_move = value;
}
float WorldSpellData::get_movement_speed() {
return _movement_speed;
}
void WorldSpellData::set_movement_speed(float value) {
_movement_speed = value;
}
Vector3 WorldSpellData::get_movement_dir() {
return _movement_dir;
}
void WorldSpellData::set_movement_dir(Vector3 value) {
_movement_dir = value;
}
float WorldSpellData::get_max_dist() {
return _max_dist;
}
void WorldSpellData::set_max_dist(float value) {
_max_dist = value;
}
Ref<PackedScene> WorldSpellData::get_effect() {
return _effect;
}
void WorldSpellData::set_effect(Ref<PackedScene> value) {
_effect = value;
}
Vector3 WorldSpellData::get_effect_offset() {
return _effect_offset;
}
void WorldSpellData::set_effect_offset(Vector3 value) {
_effect_offset = value;
}
WorldSpellData::WorldSpellData() {
_id = 0;
_collider_type = SpellEnums::COLLIDER_TYPE_NONE;
_collider_sphere_radius = 1;
_target_type = SpellEnums::TARGET_TYPE_NONE;
_target_bone_id = 0;
_move = true;
_movement_speed = 10;
_max_dist = 400;
}
WorldSpellData::~WorldSpellData() {
_effect.unref();
}
void WorldSpellData::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_id"), &WorldSpellData::get_id);
ClassDB::bind_method(D_METHOD("set_id", "value"), &WorldSpellData::set_id);
ADD_PROPERTY(PropertyInfo(Variant::INT, "id"), "set_id", "get_id");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text_name"), "set_name", "get_name");
ClassDB::bind_method(D_METHOD("get_collider_type"), &WorldSpellData::get_collider_type);
ClassDB::bind_method(D_METHOD("set_collider_type", "value"), &WorldSpellData::set_collider_type);
ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_type", PROPERTY_HINT_ENUM, SpellEnums::BINDING_STRING_COLLIDER_TYPE), "set_collider_type", "get_collider_type");
ClassDB::bind_method(D_METHOD("get_collider_box_extents"), &WorldSpellData::get_collider_box_extents);
ClassDB::bind_method(D_METHOD("set_collider_box_extents", "value"), &WorldSpellData::set_collider_box_extents);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collider_box_extents"), "set_collider_box_extents", "get_collider_box_extents");
ClassDB::bind_method(D_METHOD("get_collider_sphere_radius"), &WorldSpellData::get_collider_sphere_radius);
ClassDB::bind_method(D_METHOD("set_collider_sphere_radius", "value"), &WorldSpellData::set_collider_sphere_radius);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "collider_sphere_radius"), "set_collider_sphere_radius", "get_collider_sphere_radius");
ClassDB::bind_method(D_METHOD("get_target_type"), &WorldSpellData::get_target_type);
ClassDB::bind_method(D_METHOD("set_target_type", "value"), &WorldSpellData::set_target_type);
ADD_PROPERTY(PropertyInfo(Variant::INT, "target_type", PROPERTY_HINT_ENUM, SpellEnums::BINDING_STRING_TARGET_TYPE), "set_target_type", "get_target_type");
ClassDB::bind_method(D_METHOD("get_target_bone_id"), &WorldSpellData::get_target_bone_id);
ClassDB::bind_method(D_METHOD("set_target_bone_id", "value"), &WorldSpellData::set_target_bone_id);
ADD_PROPERTY(PropertyInfo(Variant::INT, "target_bone_id"), "set_target_bone_id", "get_target_bone_id");
ClassDB::bind_method(D_METHOD("get_move"), &WorldSpellData::get_move);
ClassDB::bind_method(D_METHOD("set_move", "value"), &WorldSpellData::set_move);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "move"), "set_move", "get_move");
ClassDB::bind_method(D_METHOD("get_movement_speed"), &WorldSpellData::get_movement_speed);
ClassDB::bind_method(D_METHOD("set_movement_speed", "value"), &WorldSpellData::set_movement_speed);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "movement_speed"), "set_movement_speed", "get_movement_speed");
ClassDB::bind_method(D_METHOD("get_movement_dir"), &WorldSpellData::get_movement_dir);
ClassDB::bind_method(D_METHOD("set_movement_dir", "value"), &WorldSpellData::set_movement_dir);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "movement_dir"), "set_movement_dir", "get_movement_dir");
ClassDB::bind_method(D_METHOD("get_max_dist"), &WorldSpellData::get_max_dist);
ClassDB::bind_method(D_METHOD("set_max_dist", "value"), &WorldSpellData::set_max_dist);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "max_dist"), "set_max_dist", "get_max_dist");
ClassDB::bind_method(D_METHOD("get_effect"), &WorldSpellData::get_effect);
ClassDB::bind_method(D_METHOD("set_effect", "value"), &WorldSpellData::set_effect);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "effect", PROPERTY_HINT_RESOURCE_TYPE, "PackedScene"), "set_effect", "get_effect");
ClassDB::bind_method(D_METHOD("get_effect_offset"), &WorldSpellData::get_effect_offset);
ClassDB::bind_method(D_METHOD("set_effect_offset", "value"), &WorldSpellData::set_effect_offset);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "effect_offset"), "set_effect_offset", "get_effect_offset");
}
| true |
423d2497c390813ccb277544ac89d376eff0554e | C++ | plantree/Data-Structure-Algorithms | /DataStructure/Stack.h | UTF-8 | 1,911 | 3.796875 | 4 | [
"MIT"
] | permissive | #ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
namespace Stack{
struct StackNode;
typedef struct StackNode *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;
int IsEmpty(Stack S);
Stack CreateStack();
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
ElementType Pop(Stack S);
void DisposeStack(Stack S);
void Print(Stack S);
struct StackNode{
ElementType Element;
PtrToNode Next;
};
int IsEmpty(Stack S){
return S->Next == nullptr;
}
Stack CreateStack(){
Stack S = new StackNode;
S->Next = nullptr;
return S;
}
void MakeEmpty(Stack S){
if(S == nullptr){
return;
}else{
while(!IsEmpty(S)){
Pop(S);
}
}
}
void Push(ElementType X, Stack S){
PtrToNode tmpCell = new StackNode;
tmpCell->Element = X;
tmpCell->Next = S->Next;
S->Next = tmpCell;
}
ElementType Top(Stack S){
if(!IsEmpty(S)){
return S->Next->Element;
}
return -1;
}
ElementType Pop(Stack S){
if(!IsEmpty(S)){
ElementType tmp;
PtrToNode firstCell = S->Next;
tmp = firstCell->Element;
S->Next = firstCell->Next;
delete firstCell;
return tmp;
}
return -1;
}
void DisposeStack(Stack S){
PtrToNode P = S->Next, tmp;
S->Next = nullptr;
while(P != nullptr){
tmp = P->Next;
delete P;
P = tmp;
}
}
void Print(Stack S){
PtrToNode P = S->Next;
while(P != nullptr){
cout << P->Element << "->";
P = P->Next;
}
cout << endl;
}
}
#endif // STACK_H
| true |
ed595329566cf6e0e29e40bd1ed62d174310adac | C++ | abstractguy/TSO_project | /software/arduino-1.8.13/examples/10.StarterKit_BasicKit/p04_ColorMixingLamp/p04_ColorMixingLamp.ino | UTF-8 | 3,018 | 3.4375 | 3 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | /*
Arduino Starter Kit example
Project 4 - Color Mixing Lamp
This sketch is written to accompany Project 3 in the Arduino Starter Kit
Parts required:
- one RGB LED
- three 10 kilohm resistors
- three 220 ohm resistors
- three photoresistors
- red green and blue colored gels
created 13 Sep 2012
modified 14 Nov 2012
by Scott Fitzgerald
Thanks to Federico Vanzati for improvements
http://www.arduino.cc/starterKit
This example code is part of the public domain.
*/
const int greenLEDPin = 9; // LED connected to digital pin 9
const int redLEDPin = 10; // LED connected to digital pin 10
const int blueLEDPin = 11; // LED connected to digital pin 11
const int redSensorPin = A0; // pin with the photoresistor with the red gel
const int greenSensorPin = A1; // pin with the photoresistor with the green gel
const int blueSensorPin = A2; // pin with the photoresistor with the blue gel
int redValue = 0; // value to write to the red LED
int greenValue = 0; // value to write to the green LED
int blueValue = 0; // value to write to the blue LED
int redSensorValue = 0; // variable to hold the value from the red sensor
int greenSensorValue = 0; // variable to hold the value from the green sensor
int blueSensorValue = 0; // variable to hold the value from the blue sensor
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
// set the digital pins as outputs
pinMode(greenLEDPin, OUTPUT);
pinMode(redLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
}
void loop() {
// Read the sensors first:
// read the value from the red-filtered photoresistor:
redSensorValue = analogRead(redSensorPin);
// give the ADC a moment to settle
delay(5);
// read the value from the green-filtered photoresistor:
greenSensorValue = analogRead(greenSensorPin);
// give the ADC a moment to settle
delay(5);
// read the value from the blue-filtered photoresistor:
blueSensorValue = analogRead(blueSensorPin);
// print out the values to the Serial Monitor
Serial.print("raw sensor Values \t red: ");
Serial.print(redSensorValue);
Serial.print("\t green: ");
Serial.print(greenSensorValue);
Serial.print("\t Blue: ");
Serial.println(blueSensorValue);
/*
In order to use the values from the sensor for the LED, you need to do some
math. The ADC provides a 10-bit number, but analogWrite() uses 8 bits.
You'll want to divide your sensor readings by 4 to keep them in range
of the output.
*/
redValue = redSensorValue / 4;
greenValue = greenSensorValue / 4;
blueValue = blueSensorValue / 4;
// print out the mapped values
Serial.print("Mapped sensor Values \t red: ");
Serial.print(redValue);
Serial.print("\t green: ");
Serial.print(greenValue);
Serial.print("\t Blue: ");
Serial.println(blueValue);
/*
Now that you have a usable value, it's time to PWM the LED.
*/
analogWrite(redLEDPin, redValue);
analogWrite(greenLEDPin, greenValue);
analogWrite(blueLEDPin, blueValue);
}
| true |
bb2ec70aafeb933cf010d42c76d3db9d7b2bf800 | C++ | liu1700/Fire-Engine | /Fire-Engine/textclass.cpp | GB18030 | 4,443 | 2.71875 | 3 | [] | no_license |
//////////////////////////////////////////////////////////
//ļ: textclass.cpp : :2014/1/13
//////////////////////////////////////////////////////////
#include "textclass.h"
TextClass::TextClass()
{
m_pFW1Factory = NULL;
m_pFontWrapper = NULL;
m_FontType = NULL;
}
TextClass::TextClass(const TextClass& other)
{
}
TextClass::~TextClass()
{
}
bool TextClass::Initialze(ID3D11Device* device, ID3D11DeviceContext* deviceContext)
{
if(FAILED(FW1CreateFactory(FW1_VERSION, &m_pFW1Factory)))
return false;
if(!InitialzeSentence(device, 16.0f, 0xff0099ff, L"Arial"))
return false;
return true;
}
void TextClass::ShutDown()
{
m_pFontWrapper->Release();
m_pFW1Factory->Release();
if (m_FontType)
{
delete m_FontType;
m_FontType = NULL;
}
return;
}
void TextClass::Render(ID3D11DeviceContext* deviceContext, const wchar_t* text,
int positionX, int positionY, int flags)
{
m_pFontWrapper->DrawString(deviceContext, text, m_FontType->fontSize,
(float)positionX, (float)positionY, m_FontType->textColor, flags);
return;
}
bool TextClass::InitialzeSentence(ID3D11Device* device, float fontsize, UINT32 textcolor, const wchar_t* texttype)
{
m_FontType = new FontType;
if(!m_FontType)
return false;
m_FontType->fontSize = fontsize;
m_FontType->textColor = textcolor;
if(FAILED(m_pFW1Factory->CreateFontWrapper(device, texttype, &m_pFontWrapper)))
return false;
return true;
}
void TextClass::SetMousePosition(int mouseX, int mouseY, ID3D11DeviceContext* deviceContext)
{
char tempString[16];
char mouseString[16];
// mouseXתΪַʽ
_itoa_s(mouseX, tempString, 10);
strcpy_s(mouseString, "Mouse X:");
strcat_s(mouseString, tempString);
size_t stringSize1 = strlen(mouseString) + 1;
const size_t newsize1 = 100;
size_t convertedChars1 = 0;
wchar_t wcstring1[newsize1];
mbstowcs_s(&convertedChars1, wcstring1, stringSize1, mouseString, _TRUNCATE);
// Ⱦ
Render(deviceContext, (const wchar_t*)wcstring1, 200, 400);
// mouseYתΪַʽ
_itoa_s(mouseY, tempString, 10);
strcpy_s(mouseString, "Mouse Y:");
strcat_s(mouseString, tempString);
size_t stringSize2 = strlen(mouseString) + 1;
const size_t newsize2 = 100;
size_t convertedChars2 = 0;
wchar_t wcstring2[newsize2];
mbstowcs_s(&convertedChars2, wcstring2, stringSize2, mouseString, _TRUNCATE);
// Ⱦ
Render(deviceContext, (const wchar_t*)wcstring2, 200, 420);
}
bool TextClass::SetFps(int fps, ID3D11DeviceContext* deviceContext)
{
char tempString[16];
char fpsString[16];
float red, green, blue;
//
if(fps > 9999)
{
fps = 9999;
}
// תΪַʽ
_itoa_s(fps, tempString, 10);
// ַ
strcpy_s(fpsString, "Fps: ");
strcat_s(fpsString, tempString);
// 60fpsΪɫ
if(fps >= 60)
{
red = 0.0f;
green = 1.0f;
blue = 0.0f;
}
// 60fpsΪɫ
if(fps < 60)
{
red = 1.0f;
green = 1.0f;
blue = 0.0f;
}
// 30Ϊɫ
if(fps < 30)
{
red = 1.0f;
green = 0.0f;
blue = 0.0f;
}
size_t stringSize1 = strlen(fpsString) + 1;
const size_t newsize1 = 100;
size_t convertedChars1 = 0;
wchar_t wcstring1[newsize1];
mbstowcs_s(&convertedChars1, wcstring1, stringSize1, fpsString, _TRUNCATE);
// Ⱦ
Render(deviceContext, (const wchar_t*)wcstring1, 10, 20);
return true;
}
bool TextClass::SetCpu(int cpu, ID3D11DeviceContext* deviceContext)
{
char tempString[16];
char cpuString[16];
_itoa_s(cpu, tempString, 10);
strcpy_s(cpuString, "Cpu: ");
strcat_s(cpuString, tempString);
strcat_s(cpuString, "%");
size_t stringSize1 = strlen(cpuString) + 1;
const size_t newsize1 = 100;
size_t convertedChars1 = 0;
wchar_t wcstring1[newsize1];
mbstowcs_s(&convertedChars1, wcstring1, stringSize1, cpuString, _TRUNCATE);
// Ⱦ
Render(deviceContext, (const wchar_t*)wcstring1, 10, 40);
return true;
}
bool TextClass::SetRenerCount(int rendercount, ID3D11DeviceContext* deviceContext)
{
char tempString[32];
char rcString[32];
_itoa_s(rendercount, tempString, 10);
strcpy_s(rcString, "Render Count: ");
strcat_s(rcString, tempString);
size_t stringSize1 = strlen(rcString) + 1;
const size_t newsize1 = 100;
size_t convertedChars1 = 0;
wchar_t wcstring1[newsize1];
mbstowcs_s(&convertedChars1, wcstring1, stringSize1, rcString, _TRUNCATE);
// Ⱦ
Render(deviceContext, (const wchar_t*)wcstring1, 10, 60);
return true;
} | true |
3bacb24a6276f71260a5ed9c95b04ad118959b96 | C++ | tokitsu-kaze/ACM-Solved-Problems | /nowcoder/2018“今日头条杯”首届湖北省大学程序设计竞赛/104I. Five Day Couple.cpp | GB18030 | 1,571 | 2.578125 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
using namespace std;
const int N=1e5+100;
struct Trie{
int ch[2],sum,dep;
}T[N*32];
int root[N],sz;
void insert(int &i,int d,int x,int v){
T[++sz]=T[i],i=sz;
T[i].dep=d+1;
T[i].sum+=v; //ʱжϵһλd
if(d<0) return ;
int p=(x>>d)&1;
insert(T[i].ch[p],d-1,x,v);
}
void Query_max_xor(int L,int R,int d,int x,int &ans){
if(d<0) return ;
int p=(x>>d)&1;
if(T[ T[R].ch[p^1] ].sum-T[ T[L].ch[p^1] ].sum)
ans+=(p^1)*(1<<d),Query_max_xor(T[L].ch[p^1],T[R].ch[p^1],d-1,x,ans);
else ans+=p*(1<<d),Query_max_xor(T[L].ch[p],T[R].ch[p],d-1,x,ans);
}
void Query_equal_to_x(int L,int R,int d,int x,int &ans){
if(d<0) {ans+=T[R].sum-T[L].sum;return ;}
int p=(x>>d)&1;
if(p==1) ans+=T[ T[R].ch[0] ].sum-T[ T[L].ch[0] ].sum;
Query_equal_to_x(T[L].ch[p],T[R].ch[p],d-1,x-p*(1<<d),ans);
}
void Query_kth(int L,int R,int d,int x,int &ans){
if(d<0) return ;
int k=T[ T[R].ch[0] ].sum-T[ T[L].ch[0] ].sum;
if(k>=x) Query_kth(T[L].ch[0],T[R].ch[0],d-1,x,ans);
else ans+=(1<<d),Query_kth(T[L].ch[1],T[R].ch[1],d-1,x-k,ans);
}
int main(){
int i,m,n=0,L,R,ans,op,x;
while(scanf("%d",&n)!=EOF)
{
sz=0,root[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&x);
root[i]=root[i-1];
insert(root[i],30,x,1);
}
scanf("%d",&m);
while(m--)
{
scanf("%d%d%d",&x,&L,&R);
Query_max_xor(root[L-1],root[R],30,x,ans=0);
printf("%d\n",x^ans);
}
}
return 0;
} | true |
3b47d67e4f5c1ef367a6c6a6b222f96d55730ed8 | C++ | oudream/ccxx | /test/algorithm/binaryTree_sum1.hpp | UTF-8 | 1,669 | 3.359375 | 3 | [
"MIT"
] | permissive |
#include "global.h"
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode * m_pLeft;
BinaryTreeNode * m_pRight;
};
int count = 0;
void findPath(BinaryTreeNode *pTreeNode,
int expectedSum,
vector<int>& path,
int & currentSum)
{
if( !pTreeNode )
return;
currentSum += pTreeNode->m_nValue;
path.push_back(pTreeNode->m_nValue);
bool isLeaf = !(pTreeNode->m_pLeft) && !(pTreeNode->m_pRight);
if(currentSum == expectedSum && isLeaf)
{
vector<int>::iterator iter;
for(iter = path.begin(); iter != path.end(); iter++)
{
cout << *iter << "\t";
}
cout << endl;
}
if(pTreeNode->m_pLeft)
findPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);
if(pTreeNode->m_pRight)
findPath(pTreeNode->m_pRight, expectedSum, path, currentSum);
currentSum -= pTreeNode->m_nValue;
path.pop_back();
}
void addTree(BinaryTreeNode **T, int num)
{
if(*T == NULL)
{
*T = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
(*T)->m_nValue = num;
(*T)->m_pLeft = NULL;
(*T)->m_pRight = NULL;
}
else if((*T)->m_nValue > num)
addTree(&((*T)->m_pLeft), num);
else if((*T)->m_nValue < num)
addTree(&((*T)->m_pRight), num);
else
cout << "重复加入同一结点" << endl;
}
int testBinaryTreeSum11()
{
BinaryTreeNode * T = NULL;
addTree(&T, 10);
addTree(&T, 12);
addTree(&T, 5);
addTree(&T, 7);
addTree(&T, 4);
vector<int> path;
int sum = 0;
findPath(T, 22, path, sum);
return 0;
} | true |
8af2216eeba3cd7ed73d713cff8b8af6b4bb268a | C++ | nirattar1/advanced_cpp | /advanced_ex4/advanced_ex4/testContainers.cpp | UTF-8 | 5,054 | 3.265625 | 3 | [] | no_license |
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include "TException_t.h"
#include "Container_t.h"
#include "Array_t.h"
#include "List_t.h"
//-------------------------------------------------------------------
typedef enum
{
INCORRECT_INPUT
} MainErros;
string mainErrorsStr[] = {"incorrect input"};
//-------------------------------------------------------------------
typedef enum
{
INSERT,
REMOVE,
REMOVE_ALL,
FIND,
COUNT,
PRINT,
APPENND,
PREPENR,
EXIT
} Options;
//-------------------------------------------------------------------
string optionsName[] ={ "Insert",
"Remove",
"Remove All",
"Find",
"Count",
"Print",
"Append",
"Prepend",
"exit"};
//-------------------------------------------------------------------
//
// HELP FUNCTIOMS PROTOTYPES
//-------------------------------------------------------------------
void PrintOptions(void);
template<typename T> void TestInsert(Container_t<T>& _obj);
template<typename T> void TestRemove(Container_t<T>& _obj);
template<typename T> void TestRemoveAll(Container_t<T>& _obj);
template<typename T> void TestFind(Container_t<T>& _obj);
template<typename T> void TestCount(Container_t<T>& _obj);
template<typename T> void TestPrint(Container_t<T>& _obj);
//-------------------------------------------------------------------
//
// GLOBAL
//-------------------------------------------------------------------
template <class T>
struct TestFunc
{
static void(* const functions[])(Container_t<T>& _test);
};
template<typename T> void(* const TestFunc<T>::functions[])(Container_t<T>&)=
{
&TestInsert<T>,
&TestRemove<T>,
&TestRemoveAll<T>,
&TestFind<T>,
&TestCount<T>,
&TestPrint<T>
};
//-------------------------------------------------------------------
//
// HELP FUNCTIOMS IMPLEMENTATION
//-------------------------------------------------------------------
void PrintOptions()
{
for(int i=0; i<=EXIT ;i++)
{
cout << i << ". " << optionsName[i] << endl;
}
}
//-------------------------------------------------------------------
template<typename T> void TestInsert(Container_t<T>& _obj)
{
cout<<"please insert an item (int): "<<endl;
int item;
cin>>item;
try
{
_obj.Insert(item);
}
catch(TException_t<int>& err)
{
cout<<err.GetDesCription();
}
}
//-------------------------------------------------------------------
template<typename T>
void TestRemove(Container_t<T>& _obj)
{
if(_obj.Count() == 0)
{
cout<<"no items to remove"<<endl;
return;
}
cout<<"please choose an index(0-"<<(_obj.Count()-1)<<")"<<endl;
int index;
cin>>index;
try
{
T item = _obj.Remove(index);
cout<<"removed item is "<< item <<endl;
}
catch(TException_t<int>& err)
{
cout<<err.GetDesCription();
}
}
//-------------------------------------------------------------------
template<typename T>
void TestRemoveAll(Container_t<T>& _obj)
{
_obj.RemoveAll();
cout<<"all items was removed"<<endl;
}
//-------------------------------------------------------------------
template<typename T>
void TestFind(Container_t<T>& _obj)
{
if(_obj.Count() == 0)
{
cout<<"no items"<<endl;
return;
}
cout<<"please choose an index(0-"<<(_obj.Count()-1)<<")"<<endl;
int index;
cin>>index;
try
{
T item = _obj.Find(index);
cout<<"found item is "<< item <<endl;
}
catch(TException_t<int>& err)
{
cout<<err.GetDesCription();
}
}
//-------------------------------------------------------------------
template<typename T>
void TestCount(Container_t<T>& _obj)
{
cout<<"num of items is: "<<_obj.Count()<<endl;
}
/*----------------------------------------------------------------------------*/
template<typename T>
void TestPrint(Container_t<T>& _obj)
{
_obj.Print();
}
//-------------------------------------------------------------------
//
// MAIN
//-------------------------------------------------------------------
int main()
{
unsigned int choice=0;
unsigned int ArrOrList;
Array_t<int>* testArr;
List_t<int>* testList;
Container_t<int>* test;
cout<<"please choose array(0) or list(1)"<<endl;
cin>>ArrOrList;
while(ArrOrList > 1)
{
cout<<"wrong input, please enter 0 for array and 1 for list"<<endl;
cin>>ArrOrList;
}
try
{
if(ArrOrList == 0) // array
{
testArr = new Array_t<int>;
test = testArr;
}
if(ArrOrList == 1) //list
{
testList = new List_t<int>;
test = testList;
}
}
catch(TException_t<int>& err)
{
cout<<err.GetDesCription() << endl;
}
PrintOptions();
cout << endl <<"Please choose: " << endl;
cin >> choice;
while(choice < EXIT)
{
(*TestFunc<int>::functions[choice])(*test);
cout<<endl<<"/*---------------------------------------------*/" << endl;
cout << endl <<"Please choose: " << endl;
cin >> choice;
}
return 0;
}
| true |
c86a382114d111c1e3f7d26bcda328a44605cee0 | C++ | mdyang/oj-solutions | /nyist/25/main.cpp | UTF-8 | 996 | 2.8125 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
map<string,string> m;
set<string> s;
void put(const string&a,const string&b){
m[a]=b;
m[b]=a;
}
int main(){
put("A#","Bb");
put("C#","Db");
put("D#","Eb");
put("F#","Gb");
put("G#","Ab");
s.insert("Ab minor");
s.insert("A# major");
s.insert("A# minor");
s.insert("C# major");
s.insert("Db minor");
s.insert("D# major");
s.insert("D# minor");
s.insert("Gb major");
s.insert("Gb minor");
s.insert("G# major");
int c=0;
string str;
while(getline(cin,str)){
string dst=m[str.substr(0,2)];
if(dst.size()==0){
cout<<"Case "<<++c<<": UNIQUE\n";
continue;
}
str[0]=dst[0];
str[1]=dst[1];
//if(s.find(str)==s.end()){
cout<<"Case "<<++c<<": "<<str<<endl;
// continue;
//}
//cout<<"Case "<<++c<<": UNIQUE\n";
}
return 0;
}
| true |
adff276bab04d0891e789ee81001913fb241d186 | C++ | lwl0810/leetcode | /leetcode_355_design-twitter.cpp | UTF-8 | 3,928 | 3.5 | 4 | [] | no_license | //https://leetcode.com/problems/design-twitter/
class Twitter {
public:
/** Initialize your data structure here. */
Twitter() {
newsFeedNum = 10;
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
tweets.push_back(make_pair(tweetId, userId));
//make sure user can see userself's tweet
usersFollower[userId].insert(userId);
unordered_set<int>::iterator it = usersFollower[userId].begin();
for(; it != usersFollower[userId].end(); it++){
usersNewsFeed[*it].push_front(tweetId);
if(usersNewsFeed[*it].size() > newsFeedNum){
usersNewsFeed[*it].pop_back();
}
}
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
vector<int> getNewsFeed(int userId) {
vector<int> res;
deque<int> q = usersNewsFeed[userId];
for(int i = 0; i < q.size(); ++i){
res.push_back(q[i]);
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if(followerId == followeeId) return;
usersFollower[followeeId].insert(followerId);
refreshNewsFeed(followerId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
//user cannot unfollow userself
if(followerId == followeeId) return;
usersFollower[followeeId].erase(followerId);
refreshNewsFeed(followerId);
}
private:
void refreshNewsFeed(int followerId){
deque<int> tmp;
for(int i = tweets.size()-1; i >= 0; --i){
if(usersFollower[tweets[i].second].find(followerId) != usersFollower[tweets[i].second].end()){
tmp.push_back(tweets[i].first);
}
if(tmp.size() == newsFeedNum) break;
}
usersNewsFeed[followerId] = tmp;
}
//tweets first is tweetId second is userId
vector<pair<int,int>> tweets;
unordered_map<int, deque<int>> usersNewsFeed;
unordered_map<int, unordered_set<int>> usersFollower;
int newsFeedNum;
};
/*
class Twitter {
public:
Twitter() {
newsFeedNum = 10;
}
void postTweet(int userId, int tweetId) {
tweets.push_back(make_pair(tweetId, userId));
//make sure user can see userself's tweet
usersFollower[userId].insert(userId);
}
vector<int> getNewsFeed(int userId) {
vector<int> res;
for(int i = tweets.size()-1; i >= 0; --i){
if(usersFollower[tweets[i].second].find(userId) != usersFollower[tweets[i].second].end()){
res.push_back(tweets[i].first);
}
if(res.size() == newsFeedNum) break;
}
return res;
}
void follow(int followerId, int followeeId) {
if(followerId == followeeId) return;
usersFollower[followeeId].insert(followerId);
}
void unfollow(int followerId, int followeeId) {
//user cannot unfollow userself
if(followerId == followeeId) return;
usersFollower[followeeId].erase(followerId);
}
private:
//tweets first is tweetId second is userId
vector<pair<int,int>> tweets;
unordered_map<int, deque<int>> usersNewsFeed;
unordered_map<int, unordered_set<int>> usersFollower;
int newsFeedNum;
};
*/
/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* vector<int> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/
| true |
566d049d5d07ea56ebc18a1f578d7c3b58ce1730 | C++ | lake2010/peter_3DAOI | /src/App/mainWindow.hpp | UTF-8 | 4,256 | 2.875 | 3 | [] | no_license | #ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <string>
#include <iomanip>
#include <ctime>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QString>
#include "appsetting.hpp"
#include "capturesetting.hpp"
#include "../SDK/randomdigit.hpp"
#include "../Job/inspectiondata.hpp"
namespace App
{
/**
* @brief MainWindow
*
* MainWindow类可以加载配置文件和扫描指定程式文件夹内程式文件;没有
* 程式文件时,将自动调用类中的私有成员函数,生成默认的程式文件,并写入随
* 机生成的数据.
*
* 类的成员变量包含:
* 1.数据类型为AppSetting的成员(非软件运行必需的配置文件类)
* 2.数据类型为CaptureSetting的成员(软件运行必需的配置文件类)
* 3.数据类型为InspectionData的成员(检测程式文件数据的类)
* 类的成员函数功能包含:
* 1.加载配置文件
* 2.扫描程式文件
* 使用操作:
* 1.传入配置文件路径给loadSetting()函数,检测配置是否正确.
* 2.将存放程式文件夹路径传入scanJobFolder()函数,
* a.没有程式文件则自动生成默认文件,并写入随机生成的数据
* b.有则将程式文件打印在终端,用户选择程式文件并输出为xml文件
*
* @author peter
* @version 1.00 2017-11-22 peter
* note:create it
*/
class MainWindow
{
public:
//>>>--------------------------------------------------------------------------------
// constructor & destructor function
/**
* @brief MainWindow
* 默认构造函数
* @param N/A
* @return N/A
*/
MainWindow();
/**
* @brief ~MainWindow
* 析构函数
* @param N/A
* @return N/A
*/
virtual~MainWindow();
//>>>--------------------------------------------------------------------------------
// get function
Job::InspectionData inspectionData(){return this->m_inspectionData;}
//>>>--------------------------------------------------------------------------------
// load & scan function
/**
* @brief loadSetting
* 加载配置文件:
* 1.appSetting的配置文件
* 2.captureSetting的配置文件
* @param appSettingPath
* appSetting配置文件的路径
* @param captureSettingPath
* captureSetting配置文件的路径
* @return N/A
*/
void loadSetting( const QString& appSettingPath,
const QString& captureSettingPath );
/**
* @brief scanJobFolder
* 扫描程式文件目录下是否有程式文件
* 1.没有程式文件则自动创建,写入默认值
* 2.有程式文件则加载程式文件,读取数据信息
* @param path
* 待扫描的存放程式文件的文件夹路径
* @return N/A
*/
void scanJobFolder(const QString& path);
private:
//>>>--------------------------------------------------------------------------------
// generate data
/**
* @brief generateObjsRandomly
* 生成随机数据,当前数据包括:
* 1.默认的版本号.最后的编辑时间
* 2.默认的job程式名.原点位置.尺寸大小
* 3.随机的原件信息(原件名.中心点位置.长宽尺寸)
* @param chipCnt
* 需要生成数据的chip原件数量
* @param icCnt
* 需要生成数据的ic原件数量
* @return N/A
*/
void generateObjsRandomly(int chipCnt,int icCnt);
private:
App::AppSetting m_appSetting;
App::CaptureSetting m_captureSetting;
Job::InspectionData m_inspectionData;
};
}//End of namespace App
#endif // APPLICATION_HPP
| true |
0da43a5cb910785fc55b29a3574f44fc3ccb6ebc | C++ | yzcmf/Lintcode_FirstTime | /464_sort-integers-ii/sort-integers-ii.cpp | UTF-8 | 1,684 | 3.3125 | 3 | [] | no_license | /*
@Copyright:LintCode
@Author: yzcmf
@Problem: http://www.lintcode.com/problem/sort-integers-ii
@Language: C++
@Datetime: 16-06-26 03:49
*/
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void QuickSort(vector<int>& A, int start ,int end)
{
int l=start, r=end, mid=A[(l+r)/2];
while(l<=r)
{
while(l<=r && A[r]>mid) r--;
while(l<=r && A[l]<mid) l++;
if(l<=r)
{
swap(A[r],A[l]);
r--;
l++;
}
}
if(start<r)
QuickSort(A,start,r);
if(l<end)
QuickSort(A,l,end);
}
// void QuickSort(vector<int>& arr, int left, int right) {
// int i = left, j = right;
// int tmp;
// int pivot = arr[(left + right) / 2];
// /* partition */
// while (i <= j) {
// while (arr[i] < pivot)
// i++;
// while (arr[j] > pivot)
// j--;
// if (i <= j) {
// tmp = arr[i];
// arr[i] = arr[j];
// arr[j] = tmp;
// i++;
// j--;
// }
// };
// /* recursion */
// if (left < j)
// quickSort(arr, left, j);
// if (i < right)
// quickSort(arr, i, right);
// }
void sortIntegers2(vector<int>& A) {
// Write your code here
if(A.empty()) return;
QuickSort(A,0,A.size()-1);
}
};
| true |
c22426e8714f958a647f636bad2897bcf6e4f27a | C++ | gorkemguzeler/Data-Structures | /cs300-hw1/my_heap.cpp | UTF-8 | 10,391 | 3.421875 | 3 | [] | no_license | //
// my_heap.cpp
// cs300-hw1
//
// Created by gorkemg on 8.11.2020.
//
#include <stdio.h>
#include "my_heap.h"
#include <iostream>
using namespace std;
int memory_leak = 0 ;
My_heap::My_heap(){
heap_begin = nullptr;
blk = nullptr;
used_bytes = 0;
}
My_heap::~My_heap(){
memory_block * ptr = heap_begin;
cout << "At destruction, the heap had a memory leak of " << used_bytes << " bytes" << endl;
while (ptr != nullptr) {
heap_begin = heap_begin->right;
delete ptr;
ptr = heap_begin;
}
blk = nullptr;
}
memory_block * My_heap::bump_allocate(int num_bytes){
if(num_bytes <= (MAX_CAPACITY - used_bytes)){
if(heap_begin == nullptr){ //add to first position
memory_block* ptr = new memory_block(nullptr , nullptr ,true, num_bytes, 0 );
heap_begin = ptr;
blk = ptr;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
else{ //add to the end
memory_block* ptr = new memory_block(blk , nullptr ,true, num_bytes, (blk->starting_address + blk->size) );
blk->right = ptr;
blk = blk->right;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
}
else //no capacity
return nullptr;
}
memory_block * My_heap::first_fit_allocate(int num_bytes){
if(num_bytes <= (MAX_CAPACITY- used_bytes)){
memory_block * temp = heap_begin ;
while(temp != nullptr){ //starting from beginning check if any block is suitable.
if(temp->used == false && temp->size >= num_bytes ){
temp->used = true;
used_bytes = used_bytes + temp->size;
return temp;
}
temp = temp->right;
}
if(heap_begin == nullptr){ //add to first position
memory_block* ptr = new memory_block(nullptr , nullptr ,true, num_bytes, 0 );
heap_begin = ptr;
blk = ptr;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
else{ //add to the end
memory_block* ptr = new memory_block(blk , nullptr ,true, num_bytes , (blk->starting_address + blk->size) );
blk->right = ptr;
blk = blk->right;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
}
else //no capacity
return nullptr;
}
memory_block * My_heap::best_fit_allocate(int num_bytes){
if(num_bytes <= (MAX_CAPACITY - used_bytes)){
memory_block * temp = heap_begin ;
memory_block * smallest = nullptr ;
int count = 0;
while(temp != nullptr){ //starting from beginning check if any block is suitable.
if(temp->used == false && temp->size >= num_bytes ){
if(count == 0){ //only use for the first time
smallest = temp;
count = 1;
}
if(temp->size < smallest->size){
smallest = temp;
}
}
temp = temp->right;
}
if(count == 1){ //there is any empty slot
used_bytes = used_bytes + smallest->size;
smallest->used = true;
return smallest;
}
if(heap_begin == nullptr){ //add to first position
memory_block* ptr = new memory_block(nullptr , nullptr ,true, num_bytes, 0 );
heap_begin = ptr;
blk = ptr;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
else{ //add to the end
memory_block* ptr = new memory_block(blk , nullptr ,true, num_bytes, (blk->starting_address + blk->size));
blk->right = ptr;
blk = blk->right;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
}
else //no capacity
return nullptr;
}
memory_block * My_heap::first_fit_split_allocate(int num_bytes){
if(num_bytes <= (MAX_CAPACITY - used_bytes)){
memory_block * temp = heap_begin ;
while(temp != nullptr){ //starting from beginning check if any block is suitable.
if(temp->used == false && temp->size == num_bytes ){
temp->used = true;
used_bytes = used_bytes + num_bytes;
return temp;
}
else if(temp->used == false && temp->size > num_bytes ){ //split the block
temp->right = new memory_block(temp, temp->right, false, (temp->size - num_bytes), (temp->starting_address + num_bytes) ) ;
if(temp->right->right != nullptr){
temp->right->right->left = temp->right;
}
used_bytes = used_bytes + num_bytes;
temp->size = num_bytes;
temp->used = true;
return temp;
}
temp = temp->right;
}
if(heap_begin == nullptr){ //add to first position
memory_block* ptr = new memory_block(nullptr , nullptr ,true, num_bytes, 0 );
heap_begin = ptr;
blk = ptr;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
else{ //add to the end
memory_block* ptr = new memory_block(blk , nullptr ,true, num_bytes, (blk->starting_address + blk->size) );
blk->right = ptr;
blk = blk->right;
used_bytes = used_bytes + num_bytes;
ptr->used = true;
return ptr;
}
}
else //no capacity
return nullptr;
}
void My_heap::deallocate(memory_block* block_address){
if(block_address != nullptr){
block_address->used = false;
used_bytes = used_bytes - block_address->size;
if(block_address->right != nullptr){
if(block_address->right->used == false){ //delete right node
memory_block* to_be_deleted = block_address->right;
block_address->size = block_address->size + block_address->right->size;
if(block_address->right == blk){
blk = blk->left;
}
block_address->right = block_address->right->right;
if(block_address->right != nullptr){
block_address->right->left = block_address;
}
delete to_be_deleted;
}
}
if(block_address->left != nullptr){
if(block_address->left->used == false){ //delete current node
memory_block* to_be_deleted2 = block_address;
block_address->left->size = block_address->left->size + block_address->size;
if(block_address == blk){
blk = blk->left;
}
block_address->left->right = block_address->right;
if(block_address->right != nullptr){
block_address->right->left = block_address->left;
}
delete to_be_deleted2;
}
}
}
}
void My_heap::print_heap(){
int total_memory_blocks= 0;
int used_memory_blocks= 0;
memory_block * ptr = heap_begin;
memory_block * ptr1 = heap_begin;
memory_block * ptr2 = heap_begin;
while(ptr!= nullptr){
total_memory_blocks++;
ptr = ptr->right;
}
while(ptr1!= nullptr){
if(ptr1->used == true){
used_memory_blocks++;
}
ptr1=ptr1->right;
}
int free_memory_blocks= total_memory_blocks - used_memory_blocks ;
cout << "Maximum capacity of heap: 512B" << endl;
if(used_bytes < 0){
used_bytes = 0;
}
cout << "Currently used memory (B): " << used_bytes << endl;
cout << "Total memory blocks: " << total_memory_blocks << endl;
cout << "Total used memory blocks: " << used_memory_blocks << endl;
cout << "Total free memory blocks: " << free_memory_blocks << endl;
cout << "Fragmentation: " << get_fragmantation() << "%" << endl;
cout << "------------------------------" << endl;
int block_num = 0;
while(ptr2 != nullptr){
cout << "Block " << block_num << "\t\tUsed: ";
if(ptr2->used == false){
cout << "False" ;
}
else
cout << "True" ;
cout << "\t" << "Size (B): "<< ptr2->size << "\t" ;
cout << hex << "Starting address: 0x" << ptr2->starting_address << dec << "\n" ;
block_num++;
ptr2 = ptr2->right;
}
cout << "------------------------------" << endl;
cout << "------------------------------" << endl;
}
float My_heap::get_fragmantation(){
float fragmentation = 0, free_memory , biggest_free_block = 0;
free_memory = MAX_CAPACITY - used_bytes;
int free_mem_blocks = 0;
//to find biggest_free_block, we will go over each block end try to find the maximum one the compare with the free space after the last full node:
memory_block * temp = heap_begin ;
while(temp != nullptr){ //starting from beginning check if any block is suitable.
if(temp->used == false){
free_mem_blocks = free_mem_blocks + temp->size;
}
if(temp->used == false && temp->size > biggest_free_block){
biggest_free_block = temp->size;
}
temp = temp->right;
}
if(blk!=nullptr){
if(biggest_free_block < MAX_CAPACITY -(free_mem_blocks+ used_bytes ) )
{ //if biggest_free_block is lower than the the memory after the last node
biggest_free_block = MAX_CAPACITY -(free_mem_blocks+ used_bytes) ;
}
}
fragmentation = (free_memory - biggest_free_block)/free_memory*100;
return fragmentation;
}
| true |
b525eeea7b9b5b7414c4af457f17f90dd5242220 | C++ | WeiqiJust/Microfacet | /Microfacet/cube_texture.cpp | UTF-8 | 2,407 | 2.703125 | 3 | [] | no_license | #include "cube_texture.h"
#include <Magick++.h>
#include <string>
using namespace Magick;
void cube_texture::load_texture(const string filename, const int user_mip_level)
{
for (int i = 0; i < 6; i++)
{
string file = filename + "_" + std::to_string(i) + ".jpg";
Magick::Image image(file);
//Magick::Image image("T:/test.jpg");
if (image.columns() != image.rows())
cout << "Error: cube texture width and height are not same! : " << file << endl;
if (i == 0)
dim = min(image.columns(), image.rows());
else
{
if (dim != min(image.columns(), image.rows()))
cout << "Error: cube texture images are not in same size!" << endl;
dim = min(min(image.columns(), image.rows()), dim);
}
Magick::Quantum *pixels = image.getPixels(0, 0, image.columns(), image.rows());
vector<Vector3> face;
float* data_zrt = new float[image.columns()*image.rows()*image.channels()];
//vector<float> test_image;
for (int x = 0; x < image.columns(); x++)
for (int y = 0; y < image.rows(); y++)
{
int offset = image.channels() *(image.rows()*x + y);
Vector3 color = Vector3((float)pixels[offset] / 65535, (float)pixels[offset + 1] / 65535, (float)pixels[offset + 2]/65535);
face.push_back(color);
for (int k = 0; k < image.channels(); k++)
{
data_zrt[offset + k] = (float)pixels[offset + k]/65535;
//cout << data_zrt[offset + k] << " ";
//test_image.push_back((float)pixels[offset + k] / 65535);
}
}
data.push_back(face);
faces[i]->load_texture_from_data(image.columns(), image.rows(), image.channels(), data_zrt, user_mip_level);
SAFE_DELETE_ARR(data_zrt);
//string filetest = filename + "_test" + std::to_string(i) + ".jpg";
//save_image_color(filetest.c_str(), test_image, image.columns(), image.rows());
}
cout << "Finish loading cube texutre." << endl;
}
vector<Vector3> cube_texture::get_face(int face)
{
return data[face];
}
Vector3 cube_texture::get_texel(int face, int x, int y)
{
Vector3 texel;
faces[face]->get_texel(texel, x, y, 0);
return texel;
//return data[face][dim*x + y];
}
void cube_texture::get_sample(Vector3 &r,//codex::math::vector::vector<Number> &r,
const int face_index,
const Vector2 &uv,
const Vector2 &du_d, const Vector2 &dv_d,
const single_texture_sampler &sampler) const
{
if (face_index >= 0 && face_index < 6)
{
faces[face_index]->get_sample(r, uv, du_d, dv_d, sampler);
}
} | true |
d7e5637d93a64af8704c2d0d6395ea522d69a8ce | C++ | MKwiatosz/Programming | /ZADANIA_WDI_INFORMATYKA/WDI_GIT/2016-2017/kartkowka-1A-zad-2/piotr-janczyk.cpp | UTF-8 | 1,175 | 3.46875 | 3 | [] | no_license | /* 2016 Piotr Janczyk */
#include <stdio.h>
#include <time.h>
#include <iostream>
const int MAX = 12;
// Znajduje największy element w tablicy będący jednocześnie mniejszy od "limit"
// oraz liczbę jego wystąpień
void find_max_less_than(const int tab[MAX],
int limit,
/*out*/ int& max,
/*out*/ int& count) {
max = -1;
for (int i = 0; i < MAX; i++) {
if (tab[i] < limit) {
if (tab[i] > max) {
max = tab[i];
count = 1;
} else if (tab[i] == max) {
count++;
}
}
}
}
int main() {
int tab[MAX];
srand(time(NULL));
for (int i = 0; i < MAX; i++) {
tab[i] = (rand() % 1000) + 1;
std::cout << tab[i] << " ";
}
std::cout << std::endl;
int sum = 0;
int n = 0;
int limit = 1001;
while (n < 10) {
int max, maxCount;
find_max_less_than(tab, limit, max, maxCount);
maxCount = std::min(maxCount, 10 - n);
n += maxCount;
sum += max * maxCount;
limit = max;
}
std::cout << sum << std::endl;
}
| true |
0e26bcfbcc3a4d979b7c359d81c3df9df7bb4183 | C++ | Manjri/code-ninja | /multithreading/mutex.cpp | UTF-8 | 927 | 3.40625 | 3 | [] | no_license | /* implement/demo mutex using test_and_set hardware instruction https://en.wikipedia.org/wiki/Test-and-set
https://www.geeksforgeeks.org/introduction-of-process-synchronization/
this demo shows how to make a mutex using HW test_and_set instruction (like HW instructions jump etc)
*/
//This is a psuedo code in c. will not compile.
#define LOCKED 1
int test_and_set(int* lockptr){
int old_Value = *lockptr;
*lockptr = LOCKED; //set it to 1
return old_value;
}
volatile int lock = 0;
void critical(){
while(test_and_set(&lock) == 1){ //locked
; //just wait
}
//unlock -- bcs lock is now 0
enter_critical_Section //only one process can be here at a time
lock = 0; // release lock
}
//NOTE: for multithreaded programming, always visualize in terms of 2 threads atleast. while one is waiting line 18, locked. the other is at line 23, exiting so it
//needs to release lock and set it to 0 | true |
37d618befb70b2bc8a1b551209408b089d2924cc | C++ | lebaker/pocode | /test/WindowResizeTest/WindowResizeTest/WindowResizeTestApp.cpp | UTF-8 | 1,120 | 2.546875 | 3 | [] | no_license | #include "WindowResizeTestApp.h"
#include "poApplication.h"
#include "poCamera.h"
class MouseTracker : public poObject {
public:
MouseTracker() : poObject("Mouse Tracker") {}
virtual void draw() {
glColor3f(1,0,0);
mouse = globalToLocal(getWindowInvMousePosition());
glRectf(mouse.x-5, mouse.y-5, mouse.x+5, mouse.y+5);
}
poPoint mouse;
};
poObject *createObjectForID(uint uid) {
return new WindowResizeTestApp();
}
void setupApplication() {
// making the window too tall to fit on screen
// os x should resize it down
applicationCreateWindow(0, WINDOW_TYPE_NORMAL, "WindowResizeTest", 100, 100, 800, 2000);
}
void cleanupApplication() {
}
WindowResizeTestApp::WindowResizeTestApp() {
addModifier(new poCamera2D());
addChild(new MouseTracker());
}
void WindowResizeTestApp::update() {
// GLint viewport[4];
// glGetIntegerv(GL_VIEWPORT, viewport);
// // viewport is actually saved and restored in the draw look so this is meaningless
// printf("%d %d\n", viewport[2], viewport[3]);
// but the window isn't getting resized properly
printf("%.0f %.0f\n", getWindowWidth(), getWindowHeight());
} | true |
04c88b468b33ea42a93d88343915c1543aa3150a | C++ | yuiponpon/Atcoder | /ARC061/c.cpp | UTF-8 | 1,269 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
#define _GLIBCXX_DEBUG
using namespace std;
int main() {
string N;
cin >> N;
int64_t sum = 0;
for(int tmp=0;tmp < (1<<N.size()-1);tmp++) {
bitset<10> s(tmp);
// cout << s << endl;
vector<int64_t> select;
string n = {N[0]}; //N[0]はcharなのでstringに変換
select.push_back(stoi(n));
int start_index = 1;
for(int i=0;i<N.size()-1;i++) {
//s=1のとき(分離)
if(s.test(i)) {
n = {N[start_index]};
select.push_back(stoi(n));
start_index++;
}
//s=0のとき(結合)
else {
//selectの末尾の要素に数字を結合
n = {N[start_index]};
select[select.size()-1] *= 10;
select[select.size()-1] += stoi(n);
start_index++;
}
}
// for(int i=0;i<select.size();i++) {
// cout << select[i] << " ";
// }
// cout << endl;
// 配列selectの要素の総和を求める(答え)
for(int i=0;i<select.size();i++) {
sum += select[i];
}
}
cout << sum << endl;
return 0;
} | true |
3ec4c6a0f77b4cd1540a30ace98acb94820d6161 | C++ | justin0909/COEN243-244 | /COEN243_Assignemnt_4/testcar.cpp | UTF-8 | 1,594 | 4 | 4 | [] | no_license | // Assignemnt 4, problem 2: testcar.cpp
// The driver for the Car class
#include "Car.h"
#include <iostream>
using namespace std;
int main()
{
// initialize temporary variable
int carId;
string carBrand;
string carType;
// prompt user for information on car 1, and store values in temporary variables
cout << "\nPlease enter the information for Car 1:\n";
cout << "Car id: ";
cin >> carId;
cout << "Brand: ";
cin.ignore(1000,'\n'); // ignore any of the firsts 1000 characters in the buffer up to and including the new line character
getline(cin,carBrand);
cout << "Car Type: ";
getline(cin,carType);
cout << endl;
// instantiate class flight1 with user's information
Car car1( carId, carBrand, carType );
// prompt user for information on car 2, and store values in temporary variables
cout << "\nPlease enter the information for Car 2:\n";
cout << "Car ID: ";
cin >> carId;
cout << "Brand: ";
cin.ignore(1000,'\n'); // ignore any of the firsts 1000 characters in the buffer up to and including the new line character
getline(cin,carBrand);
cout << "Car Type: ";
getline(cin,carType);
cout << endl;
// instantiate class flight1 with user's information
Car car2( carId, carBrand, carType );
// Display both Cars' information
cout << "Car 1" << endl;
cout << "ID: " << car1.getId() << endl;
cout << "Brand: " << car1.getBrand() << endl;
cout << "Type: " << car1.getType() << endl;
cout << "\n\nCar 1" << endl;
cout << "ID: " << car2.getId() << endl;
cout << "Brand: " << car2.getBrand() << endl;
cout << "Type: " << car2.getType() << endl;
return 0;
} | true |
9217f7ab825c2fbbe0570eb07ad650759be18605 | C++ | doomsday861/Allofit | /XORGM.cpp | UTF-8 | 1,345 | 2.640625 | 3 | [] | no_license | /**
* XORGM codechef
* Kartikeya (doomsday861)
**/
#include<bits/stdc++.h>
#include<time.h>
#define ll long long
#define testcase ll t;cin>>t;while(t--)
#define timeb auto start = high_resolution_clock::now();
#define timee auto stop = high_resolution_clock::now();auto duration = duration_cast<seconds>(stop - start);cout << "Time taken by function: "<<duration.count() << "seconds" << endl;
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("output.ans", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
using namespace std::chrono;
//timeb
testcase
{
ll n;
cin >> n;
ll a[n];
ll b[n];
ll ax=0;
ll bx=0;
bool f=0;
for(ll i =0 ; i < n;i++)
{
cin >> a[i];
ax ^=a[i];
if(a[i]!=a[i-1] && i!=0)
f=1;
}
ll x=0;
for(ll i=0; i <n;i++)
{
cin>>b[i];
x ^=a[i]^b[i];
}
ll c[n];
for(ll i =0 ; i < n ; i++)
{
c[i] = a[i]^x;
}
bool f2=0;
sort(c,c+n);
sort(b,b+n);
for(ll i=0;i<n;i++)
{
if(c[i]!=b[i])
{
f2=1;
cout<<-1<<endl;
break;
}
}
if(!f2)
{
for(ll i=0;i<n;i++)
{
cout<<(a[i]^x)<<" ";
}
}
cout<<endl;
}
//timee
return 0;
} | true |
870e1d0d69d16f76ad70f2d6fc1ed1d73affca40 | C++ | facebook/openbmc | /common/recipes-core/pldmd/files/pldmd-util.cpp | UTF-8 | 5,511 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <string>
#include "CLI/CLI.hpp"
#include <libpldm-oem/pldm.h>
std::ostream& operator<<(std::ostream& os, uint8_t b) {
os << "0x" << std::hex << std::setw(2) << std::setfill('0') << +b;
return os;
}
static void
show_request_info(uint8_t bus, int eid, const std::vector<uint8_t>& data)
{
std::cout << "Request :"
<< "\n Bus = " << int(bus)
<< "\n Eid = " << int(eid)
<< "\n Data = ";
for (auto&d : data)
std::cout << d << ' ';
std::cout << std::endl;
}
static void
show_response_info(int ret, uint8_t* resp)
{
std::cout << "Response: \n"
<< " Return Code: " << ret << std::endl;
if (ret == 0) {
std::cout << " PLDM Request Bit : " << uint8_t(resp[0]>>7)
<< "\n PLDM Instance ID : " << uint8_t(resp[0]&0x3F)
<< "\n PLDM Type : " << uint8_t(resp[1]&0x3F)
<< "\n PLDM Command : " << resp[2]
<< "\n PLDM Completion Code : " << resp[3]
<< std::endl;
}
}
static void do_raw(uint8_t bus, int eid, std::vector<uint8_t>& data) {
show_request_info(bus, eid, data);
// bit 4:0 instance_id = 0,
// bit5 - rsvd, bit6 - dgram (false) bit7 - req (true)
data.insert(data.begin(), 0x80);
uint8_t* resp = nullptr;
size_t resp_len = 0;
int ret = oem_pldm_send_recv(bus, eid,
data.data(), data.size(),
&resp, &resp_len);
show_response_info(ret, resp);
if (ret == 0) {
std::cout << " PLDM Data : ";
for (size_t i = 4; i < resp_len; ++i)
std::cout << resp[i] << ' ';
std::cout << std::endl;
if (resp != nullptr)
free(resp);
} else {
std::cerr << "Failed code: " << ret << std::endl;
exit(1);
}
}
static void do_get_ver(uint8_t bus, int eid) {
std::vector<uint8_t> data{0x05, 0x02};
show_request_info(bus, eid, data);
// bit 4:0 instance_id = 0,
// bit5 - rsvd, bit6 - dgram (false) bit7 - req (true)
data.insert(data.begin(), 0x80);
uint8_t* resp = nullptr;
size_t resp_len = 0;
int ret = oem_pldm_send_recv(bus, eid,
data.data(), data.size(),
&resp, &resp_len);
show_response_info(ret, resp);
if (ret == 0 && resp[3] == 0) {
std::cout << " PLDM Data : ";
for (size_t i = 4; i < resp_len; ++i)
std::cout << resp[i] << ' ';
std::cout << std::endl;
if (resp)
free(resp);
} else {
std::cerr << "Failed code: " << ret << " resp[3]: " << resp[3] << std::endl;
exit(1);
}
}
static void do_get_effecter(uint8_t bus, int eid, std::vector<uint8_t>& payload) {
std::vector<uint8_t> data{};
// 0:5 pldm_type = 0x2 (PLDM for Platform
// Monitoring and Control) (6:7 hdr-version 0)
data.push_back(0x02);
// pldm_command 0x3A = GetStateEffecterStates
data.push_back(0x3A);
// Add data
data.insert(data.end(), payload.begin(), payload.end());
show_request_info(bus, eid, data);
// bit 4:0 instance_id = 0,
// bit5 - rsvd, bit6 - dgram (false) bit7 - req (true)
data.insert(data.begin(), 0x80);
uint8_t* resp = nullptr;
size_t resp_len = 0;
int ret = oem_pldm_send_recv(bus, eid,
data.data(), data.size(),
&resp, &resp_len);
show_response_info(ret, resp);
if (ret == 0 && resp[3] == 0) {
size_t numEffectors = (size_t)resp[4];
std::cout << " PLDM Data :\n"
<< " Effecter Count : " << numEffectors << std::endl;
for (size_t i = 0; i < numEffectors; ++i) {
std::cout << " " << i << ". OperationalState : " << int(resp[5+i*3])
<< "\n " << i << ". pendingState : " << int(resp[6+i*3])
<< "\n " << i << ". presentState : " << int(resp[7+i*3])
<< std::endl;
}
} else {
std::cerr << "Failed code: " << ret << " resp[4]: " << resp[4] << std::endl;
exit(1);
}
}
int main (int argc, char** argv)
{
// init CLI app
CLI::App app("\nPLDM daemon util. (Over MCTP)\n");
app.failure_message(CLI::FailureMessage::help);
// Allow flags/options to fallthrough from subcommands.
app.fallthrough();
// init options
std::string optionDescription;
// <bus number> option
uint8_t bus;
optionDescription = "(required) Setting Bus number.";
app.add_option("-b, --bus", bus, optionDescription)->required();
// <eid> option
int eid = 0;
optionDescription = "(default:0) Setting EID.";
app.add_option("-e, --eid", eid, optionDescription);
// <raw> option
std::vector<uint8_t> data = {};
optionDescription = "PLDM header without first byte (requset & instance id)";
auto opt_raw = app.add_subcommand("raw", "Execute raw PLDM command");
opt_raw->add_option("data", data, optionDescription)->required();
opt_raw->callback([&]() {do_raw(bus, eid, data);});
// <get-ver> option
optionDescription = "Get Firmware Parameter ( Type:0x05 Cmd:0x02 )";
auto opt_get_ver = app.add_subcommand("get-ver", optionDescription);
opt_get_ver->callback([&]() { do_get_ver(bus, eid); });
// <get-effector> option
optionDescription = "Get StateEffecter States ( Type:0x02 Cmd:0x3A )";
auto opt_get_effecterstat = app.add_subcommand("get-effecter", optionDescription);
opt_get_effecterstat->add_option("data", data, "effector req value")->expected(2)->required();
opt_get_effecterstat->callback([&]() {do_get_effecter(bus, eid, data);});
app.require_subcommand(/* min */ 1, /* max */ 1);
// parse and execute
CLI11_PARSE(app, argc, argv);
return 0;
}
| true |
ae774dae633be3a25ab7d570799ab9746e03fdc7 | C++ | SamiJones/Threading | /Coursework1/cw1Part1.cpp | UTF-8 | 5,422 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <unistd.h>
#include <string>
#include <cmath>
#include <time.h>
using namespace std;
//height and width of 2D array of points
#define ARRAY_WIDTH 1000
#define ARRAY_HEIGHT 50000
//horizontal distance between heights stored in each row of main array
//remains the same for every point and its immediate neighbours in row
//so long as this value is constant, its actual number value is unimportant
#define HORIZONTAL_POINT_DIST 50
#define DEGREES_PER_RADIAN 57.2958
//remove
void compareArrayValues(float** mainArray, float** resultArray, int height, int width)
{
int nextVal = width + 1;
if (nextVal == ARRAY_WIDTH)
nextVal = 0;
cout << "Height 1: " << mainArray[height][width] << endl;
cout << "Height 2: " << mainArray[height][nextVal] << endl;
cout << "Distance result = " << resultArray[height][width] << endl;
}
//remove
float** setupMainArray(void); //used for importing and converting data for main array from array.txt and storing it in mainArray
template <typename type> type** setup2DArrayOnHeap(void); //templated function to setup a 2D array on heap (must allocate arrays on heap due to their large size)
template <typename type> void delete2DArray(type** array); //templated function to release memory used for a given 2D array (must be called for each array)
int main ()
{
//create a clock object and set it equal to current processor time used by this process (measured in clock ticks)
clock_t t = clock();
//double-pointers used to point to 2D arrays
//the 2D arrays created have been set up on the heap due to their large size
float** mainArray = setupMainArray();
float** distanceArray = setup2DArrayOnHeap<float>();
float** angleArray = setup2DArrayOnHeap<float>();
//calculate distance results and populate corresponding array
for (int i = 0; i < ARRAY_HEIGHT; i++)
{
for (int j = 0; j < ARRAY_WIDTH; j++)
{
//set height value to compare with as that of next element in row
int nextColumn = j+1;
//special case:
//if we are looking at last element in row, "wrap around" and compare it with first element in that row
if (j == ARRAY_WIDTH - 1)
nextColumn = 0;
//calculate vertical distance between points being compared
float verticalDist = mainArray[i][nextColumn] - mainArray[i][j];
//Pythagoras' Theorem to calculate Euclidean distance between the points (hypotenuse of the triangle)
float hypotenuse = sqrt(pow(verticalDist, 2) + pow(HORIZONTAL_POINT_DIST, 2));
distanceArray[i][j] = hypotenuse;
//calculate angle of slope from one point to the next using basic trigonometry (theta = sin-1(opposite / hypotenuse))
angleArray[i][j] = DEGREES_PER_RADIAN * asin(verticalDist / hypotenuse);
}
}
//compareArrayValues(mainArray, distanceArray, 2963, 0);
//compareArrayValues(mainArray, angleArray, 2963, 0);
//release memory used for arrays before finishing program
delete2DArray<float>(mainArray);
delete2DArray<float>(distanceArray);
delete2DArray<float>(angleArray);
//set value of clock object to current processor time used minus processor time used at start of process
t = clock() - t;
//output time taken for program to complete (converting clock ticks to seconds)
cout << "The program took " << ((float)t / (float)CLOCKS_PER_SEC) << " seconds from start to finish.\n";
return 0;
}
float** setupMainArray(void)
{
//import data for main 2D array from text file
ifstream inFile;
inFile.open("array.txt");
//main array to hold the numbers to be operated on by threads
float** mainArray = setup2DArrayOnHeap<float>();
//temporary storage for numbers as strings before they are converted to floats
string** numbersAsStrings = setup2DArrayOnHeap<string>();
//imports data from array.txt into numbersAsStrings 2D array
for (int i = 0; i < ARRAY_HEIGHT; i++)
{
char character = inFile.get();
int columnIndex = 0;
//looks at file char by char
//checks for newline and space chars to delimit input
while (character != '\n')
{
if (character != ' ')
numbersAsStrings[i][columnIndex] += character;
else
columnIndex++;
character = inFile.get();
}
}
//convert strings imported from array.txt to floats (using string to float function) and store them in main array
for (int i = 0; i < ARRAY_HEIGHT; i++)
for (int j = 0; j < ARRAY_WIDTH; j++)
mainArray[i][j] = stof(numbersAsStrings[i][j]);
//deallocate memory used for numbersAsStrings as it is no longer needed
delete2DArray<string>(numbersAsStrings);
return mainArray;
}
//set up 2D array on the heap which matches the array dimensions ARRAY_HEIGHT and ARRAY_WIDTH
template <typename type>
type** setup2DArrayOnHeap(void)
{
//sets up a double-pointer and points it to a dynamically allocated array of pointers
type** newArray = new type*[ARRAY_HEIGHT];
//sets each element of newArray to point to a dynamically allocated array of variables of chosen type
for (int i = 0; i < ARRAY_HEIGHT; i++)
newArray[i] = new type[ARRAY_WIDTH];
//return double-pointer to array created
return newArray;
}
template <typename type>
void delete2DArray(type** array)
{
//iterate through every row of 2D array and free memory used for each row using array deallocation operator
for (int i = 0; i < ARRAY_HEIGHT; i++)
delete[] array[i];
//free memory used to hold the column data for the 2D array
delete[] array;
}
| true |
144a71de3ef28db2d05937a00999e99e7dbfb54c | C++ | joevarghesecoding/PracticeProblems | /PairsOfStringCharsWithUnderscore.cpp | UTF-8 | 729 | 3.84375 | 4 | [] | no_license | //Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
// Examples:
// solution("abc") // should return {"ab", "c_"}
// solution("abcdef") // should return {"ab", "cd", "ef"}
#include <string>
#include <vector>
using namespace std;
vector<string> solution(const string &s)
{
string under = "_";
string b = s;
vector<string> myString;
if(b.length() % 2 != 0)
b.append(under);
for(int i = 0; i < b.length()-1; i+=2)
{
string a = b.substr(i, 2);
myString.push_back(a);
}
return myString;
}
| true |
41ea76c65c0c48102ae2a47e857e02efa49190df | C++ | asm123/codes | /algorithms/Spoj/opbit.cpp | UTF-8 | 635 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
using namespace std;
inline int read ()
{
char c;
int n = 0;
while ((c = getchar_unlocked ()) < 48);
n += (c - '0');
while ((c = getchar_unlocked ()) >= 48)
n = n * 10 + (c - '0');
return n;
}
int main (void)
{
int T = read ();
while (T--)
{
int a = read (), b = read ();
if (a == b)
printf ("0\n");
else
{
int sa = sqrt (a), sb = sqrt (b);
int aNd, xOr;
aNd = xOr = (sa+1) * (sa+1) - sa*sa;
for (int i = sa+1; i < sb; i++)
{
int diff = (i+1) * (i+1) - i*i;
aNd &= diff;
xOr ^= diff;
}
printf ("%d\n", aNd & xOr);
}
}
return 0;
}
| true |
e257aa2c0f3677b0cbb6cc42a2acf699340203b5 | C++ | sklinkusch/scripts | /TC-programs/CIS-D/readlog.cc | UTF-8 | 6,636 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <time.h>
#include <unistd.h>
#include <sstream>
using namespace std;
/******************************************************************************
* readLOG *
* developped by Stefan Klinkusch, Free University of Berlin (2014) *
* reads # states, RHF energy, and CIS excitation energies from a GAMESS *
* .log file and writes the data to a binary .bin.dat file *
******************************************************************************/
void read_line(ifstream* inf, char* line_buf, int max_count){ // routine to read strings from a file (a line is saved into line_buf)
int count = 0; // #characters is set to zero
char c; // the read character
int end = 0; // dummy integer to see the end of line
while(end == 0 && inf->get(c)){ // loop as long as the end of line is not yet reached, reads each character c
line_buf[count++] = c; // saves the current character to the line_buf array
if(c == '\n') end = 1; // sets end to one if the end of line is reached
if(count == max_count){ // emergency exit if the line is too long
cerr << "Buffer overflow while parsing\n"; exit(1);
}
}
line_buf[count-1] = 0;
}
int main(int argc, char* argv[]){
if(argc != 4){
cerr << "Usage: ./readlog <GAMESS logfile> <# states> <output file>\n";
exit(1);
}
char line_buf[64000]; // line_buffer to save each read line as long as it is used
char ev[128]; // dummy string to save the excitation energy in eV
char kcal[128]; // dummy string to save the excitation energy in kcal/mol
char cm[128]; // dummy string to save the excitation wavenumber in cm^-1
char nm[128]; // dummy string to save the excitation wavelength in nm
char binfile[512]; // filename for binary outfile
sprintf(binfile, "%s.bin.dat", argv[1]); // appends .bin.dat to the input logfile name
ofstream datf(binfile); // defines datf as the output stream to the new binfile
double RHFen = 0.; // Final RHF Energy
char dumc[1024]; // dummy string for all nasty things to read from the input file
char sym[128]; // dummy string to save the symmetry of an excited state
ifstream inf(argv[1]); // defines inf as the input stream from the GAMESS logfile
int nros = atoi(argv[2]); // reads #states from the shell
datf.write((char *) &nros, sizeof(int)); // writes #states to the binfile (binary format)
double* cisvals = new double[nros]; // defines an array for the CIS excitation energies
ofstream outf; // defines an output stream for a readLOG logfile
cisvals[0] = 0.; // sets the CI excitation energy for the ground state to zero
outf.open(argv[3]); // opens the readLOG logfile (filename from the shell)
while(strcmp(" DENSITY CONVERGED", line_buf)!=0) read_line(&inf, line_buf,64000); // reads each line until "DENSITY CONVERGED" is reached
for(int i = 0; i < 5; i++) read_line(&inf, line_buf,64000); // reads four lines of junk data and one important line (the last line of the five ones)
istringstream ist(line_buf); // defines ist as a streamstring from the line_buf
for(int i = 0; i < 4; i++) ist >> dumc; // reads four words of junk and saves it in dumc
ist >> RHFen; // reads the RHF energy
outf << RHFen << "\n"; // writes the RHF energy to the readLOG logfile
datf.write((char *) &RHFen, sizeof(double)); // writes the RHF energy to the binfile (binary format)
while(strcmp(" CI-SINGLES EXCITATION ENERGIES",line_buf)!=0) read_line(&inf,line_buf,64000); // reads each line until "CI-SINGLES EXCITATION ENERGIES" is reached
for(int i = 0; i < 2; i++){ // reads two lines of junk
read_line(&inf, line_buf,64000);
}
for(int i = 1; i < (nros); i++){ // read now (nros-1) lines with excitation energies
read_line(&inf, line_buf,64000);
istringstream ist(line_buf); // defines a stringstream reading from line_buf
ist >> sym >> cisvals[i] >> ev >> kcal >> cm >> nm; // reads the symmetry, excitation energies (E_h, eV, kcal/mol, cm^-1, nm), only E_h is permanently saved
}
for(int i = 0; i < nros; i++){
outf << i << " " << cisvals[i] << "\n"; // writes CI excitation energies to the readLOG logfile
}
datf.write((char *) cisvals, sizeof(double)*nros); // writes CI excitation energies to the binfile (binary format)
datf.close(); // closes the binfile
outf.close(); // closes the readLOG logfile
}
| true |
885f652b1f2f4705b2f0f7a4b5bad7cc9e01821e | C++ | maoxiezhao/Cjing2D | /src/utils/size.inl | UTF-8 | 1,652 | 3.6875 | 4 | [] | no_license |
constexpr Size::Size(int w, int h) :
width(w), height(h)
{}
inline Size& Size::operator+=(const Size& other)
{
width += other.width;
height += other.height;
return *this;
}
inline Size& Size::operator-=(const Size& other)
{
width -= other.width;
height -= other.height;
return *this;
}
inline Size& Size::operator*=(int factor)
{
width *= factor;
height *= factor;
return *this;
}
inline Size& Size::operator/=(int divisor)
{
width /= divisor;
height /= divisor;
return *this;
}
inline bool Size::IsFlat()const
{
return (width == 0 && height == 0);
}
constexpr Size operator+(const Size& lhs, const Size& rhs)
{
return {lhs.width+rhs.width,lhs.height + rhs.height};
}
constexpr Size operator-(const Size& lhs, const Size& rhs)
{
return{ lhs.width-rhs.width,lhs.height - rhs.height };
}
constexpr Size operator*(const Size& lhs, int factor)
{
return{ lhs.width*factor,lhs.height *factor};
}
constexpr Size operator*(int factor, const Size& rhs)
{
return{ rhs.width*factor,rhs.height *factor };
}
constexpr Size operator/(const Size& lhs, int divisor)
{
return{lhs.width / divisor,lhs.height / divisor};
}
constexpr bool operator==(const Size& lhs, const Size& rhs)
{
return (lhs.width == rhs.width) && (lhs.height == rhs.height);
}
constexpr bool operator!=(const Size& lhs, const Size& rhs)
{
return (lhs.width != rhs.width) || (lhs.height != rhs.height);
}
constexpr bool operator<=(const Size& lhs, const Size& rhs)
{
return (lhs.width <= rhs.width) && (lhs.height <= rhs.height);
}
constexpr bool operator>=(const Size& lhs, const Size& rhs)
{
return (lhs.width >= rhs.width) && (lhs.height >= rhs.height);
} | true |
02d0ddf9d21e1814474e8a2785c97452791dbc70 | C++ | ironmanvim/mrnd_c_assignments | /day 1 and 2 assignments/examp/first.cpp | UTF-8 | 615 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *compress(char *s) {
char *res = (char *)malloc(sizeof(char) * strlen(s));
int k = 0;
int count = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == s[i + 1]) {
count++;
}
else if (count > 0) {
char temp[20];
_itoa(count+1, temp, 10);
res[k++] = s[i];
for (int j = 0; temp[j] != '\0'; j++) {
res[k++] = temp[j];
}
count = 0;
}
else {
res[k++] = s[i];
count = 0;
}
}
res[k++] = '\0';
return res;
}
int main() {
char quest[] = "abcdeff";
char *res = compress(quest);
printf("%s", res);
getchar();
} | true |
a6c4fe49c69fd5c3cd39f905ee8f36c3d6d034f5 | C++ | tontonialberto/robot_programming | /rp_06_eigen_templates/exercise/eigen_transform_sort.cpp | UTF-8 | 2,630 | 3.046875 | 3 | [] | no_license | #include <Eigen/Geometry>
#include "eigen_01_point_loading.h"
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
using namespace Eigen;
extern const char**environ;
inline Eigen::Matrix3f Rx(float theta) {
float c=cos(theta);
float s=sin(theta);
Eigen::Matrix3f R;
R <<
1, 0, 0,
0, c, -s,
0, s, c;
return R;
}
inline Eigen::Matrix3f Ry(float theta) {
float c=cos(theta);
float s=sin(theta);
Eigen::Matrix3f R;
R <<
c, 0, s,
0, 1, 0,
-s, 0, c;
return R;
}
inline Eigen::Matrix3f Rz(float theta) {
float c=cos(theta);
float s=sin(theta);
Eigen::Matrix3f R;
R <<
c, -s, 0,
s, c, 0,
0, 0, 1;
return R;
}
template <int idx>
struct CoordinateCompare_{
public:
// TODO
CoordinateCompare_(): index(idx) {}
bool operator()(Vector3f a, Vector3f b) {
return a[index] < b[index];
}
int index;
};
int main(int argc, char** argv) {
if (argc<8) {
cerr << "usage: " << environ[0] << " tx ty tz ax ay az filename";
return -1;
}
float ax, ay, az, tx, ty, tz;
tx=atof(argv[1]);
ty=atof(argv[2]);
tz=atof(argv[3]);
ax=atof(argv[4]);
ay=atof(argv[5]);
az=atof(argv[6]);
cerr << "translation: " << tx << " " << ty << " " << tz << endl;
cerr << "rotation: " << ax << " " << ay << " " << az << endl;
std::ifstream is(argv[7]);
Vector3fVector points;
int num_points = loadPoints(points, is);
cerr << "I read" << num_points << "from the stream " << endl;
Eigen::Isometry3f iso;
iso.linear()=Rx(ax)*Ry(ay)*Rz(az);
iso.translation()=Vector3f(tx, ty, tz);
cerr << "Isometry: " << endl;
cerr << iso.matrix() << endl;
Vector3fVector transformed_points(points.size());
for (size_t i=0; i<points.size(); ++i)
transformed_points[i] = iso*points[i];
bool run=true;
while (1) {
cerr << "Sorting: x, y, z" << endl;
char s;
cin >> s;
switch (s){
case 'x':
cerr << "sorting by x" << endl;
std::sort(transformed_points.begin(), transformed_points.end(), CoordinateCompare_<0>());
break;
case 'y':
cerr << "sorting by y" << endl;
std::sort(transformed_points.begin(), transformed_points.end(), CoordinateCompare_<1>());
break;
case 'z':
cerr << "sorting by z" << endl;
std::sort(transformed_points.begin(), transformed_points.end(), CoordinateCompare_<2>());
break;
default:
cout << "invalid option, exiting" << endl;
run=false;
}
if (! run)
break;
for(const auto& p: transformed_points){
cerr << p.transpose() << endl;
}
}
return 0;
}
| true |
ebdac832c04e82ff554e299c5cb850460a65e603 | C++ | xcaptain/casbin-cpp | /casbin/persist/Watcher.h | UTF-8 | 934 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef CASBIN_CPP_PERSIST_WATCHER
#define CASBIN_CPP_PERSIST_WATCHER
#include <string>
using namespace std;
// Watcher is the interface for Casbin watchers.
class Watcher {
public:
// SetUpdateCallback sets the callback function that the watcher will call
// when the policy in DB has been changed by other instances.
// A classic callback is Enforcer.LoadPolicy().
template <typename Func>
void SetUpdateCallback(Func func){
return;
}
// Update calls the update callback of other instances to synchronize their policy.
// It is usually called after changing the policy in DB, like Enforcer.SavePolicy(),
// Enforcer.AddPolicy(), Enforcer.RemovePolicy(), etc.
virtual void Update() = 0;
// Close stops and releases the watcher, the callback function will not be called any more.
virtual void Close() = 0;
};
#endif | true |
2c1b717e55926b489c79ac5769af76d9e892adce | C++ | Lovepreet-Singh-ACET/Data-Strucutres-cpp | /Patterns/pattern5.cpp | UTF-8 | 407 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
// Pattern
// 1
// 2 2
// 3 3 3
// 4 4 4 4
// 5 5 5 5 5
int main(){
#ifndef ONLINE_JDUGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int rows;
cin>>rows;
for(int i=1; i<=rows; i++){
for(int j=1; j<=i; j++){
cout << i << " ";
}
cout<<endl;
}
return 0;
} | true |
09ee01b5b5d37c070db1fbe91bed295dc3deb60a | C++ | ShunHattori/robocon2019_onSeason_remoteControl | /src/UnitProtocol.hpp | UTF-8 | 549 | 2.625 | 3 | [] | no_license | #pragma once
#include "Arduino.h"
typedef enum ASCII
{
STX = 0x02, // Start of Text
ETX = 0x03, // End of Text
ENQ = 0x05, // Enquiry
ACK = 0x06, // Acknowledge
} ControlCodes;
class UnitProtocol
{
public:
UnitProtocol(Stream *str);
int transmit(uint16_t arrayLenght, int *packet);
int receive(int *variableToStore);
void setTimeout(uint16_t timeoutTimeInMs);
private:
Stream *_myStream;
unsigned long _watchDogInitTime, _watchDogComparePrevTime;
uint16_t _timeoutMs, _arrayLenght;
bool _isTransmittable, _isReceivable;
}; | true |
79a9006ea36c9604993aaad1f9d123a85fda1bfa | C++ | seabeach000/stdFuture | /stdFuture/CThreadLocal.cpp | GB18030 | 4,166 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include "CThreadLocal.h"
#include <thread>
#include <mutex>
#include <iostream>
namespace wwxxgg {
namespace threadlocal {
thread_local call_context context;
//һ̬Աֱͨӵãstatic thread_local thread_local ǵȼ۵ģԷʵľǾ̬ݳԱ
call_context& call_context::for_thread() { return context; }
std::wstring call_context::to_string() const
{
if (video_channel == -1)
return L"[]";
if (layer == -1)
return L"[ch=" + std::to_wstring(video_channel) + L"]";
return L"[ch=" + std::to_wstring(video_channel) + L"; layer=" + std::to_wstring(layer) + L"]";
}
thread_local int g_n = 1;
void f()
{
g_n++;
printf("id=%d, n=%d\n", std::this_thread::get_id(), g_n);
}
void foo()
{
thread_local int i = 0;
printf("id=%d, n=%d\n", std::this_thread::get_id(), i);
i++;
}
void f2()
{
foo();
foo();
}
ThreadLocal::ThreadLocal()
{
}
ThreadLocal::~ThreadLocal()
{
}
void thread_func(const std::string& thread_name);
void ThreadLocal::test()
{
g_n++; //IJӰg_n߳t2t3еijʼֵ(ֵΪ1)
f();
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
f2();
std::thread t4(f2);
std::thread t5(f2);
t4.join();
t5.join();
/////////////////////////////////////
std::thread t11(thread_func, "t11");
std::thread t12(thread_func, "t12");
t11.join();
t12.join();
//////////////////////////////////////
//thread_local ÿһ߳̾ͻʼһ
std::thread t21([]() {
{
//ͬһ߳scoped_call_context call_context::for_thread()ͬһthread_local call_context
scoped_call_context save;
std::cout << " t21 " << call_context::for_thread().video_channel << std::endl;
call_context::for_thread().video_channel = 1;
call_context::for_thread().layer = 10;
std::cout << " t21 " << call_context::for_thread().video_channel << std::endl;
}
std::cout << " t21 " << call_context::for_thread().video_channel << std::endl;
});
int ret = [](int index)
{
int aa = index+=11;
return aa;
}(200);
std::thread t22([]() {
call_context::for_thread().video_channel = 2;
call_context::for_thread().layer = 20;
});
t21.join();
t22.join();
}
std::mutex cout_mutex;
//
class A {
public:
A() {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "create A" << std::endl;
}
~A() {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "destroy A" << std::endl;
}
int counter = 0;
int get_value() {
return counter++;
}
};
void thread_func(const std::string& thread_name) {
for (int i = 0; i < 3; ++i) {
thread_local A* a = new A();
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "thread[" << thread_name.c_str() << "]: a.counter:" << a->get_value() << std::endl;
}
return;
}
}
}
/*
ǰ3дӡܰthread_localγʼģԿÿ̶߳һγʼеg_n߳类ʼΪ1
Ϊ23ЩIJӰg_n߳t2t3еijʼֵ(ֵΪ1)Ȼt2t3߳ʱ߳еıֵѾΪ3
̡߳thread1thread2ӡֱΪ322
6дӡ˵һʵΪthread_localıر߳dzڵģͬͨʱڣstaticһijʼڣ
ȻûбΪstaticfooеthread_local i ÿ̵߳һִеʱʼÿ̸߳ۼӣ߳̽ʱͷš
b_key thread_localȻҲ static ģÿ߳һÿ߳ееùb_static staticȫֻһ̹߳
*/ | true |
79f26082df2c6001cd82ee3851df0215bf3f44b4 | C++ | bvan-dyc/CPP_MODULES | /CPP - M04/ex00/Sorcerer.cpp | UTF-8 | 987 | 3.21875 | 3 | [] | no_license | #include "Sorcerer.h"
Sorcerer::Sorcerer(std::string name, std::string title) : _title(title), _name(name)
{
std::cout << _name << ", " << _title << ", is born!" << std::endl;
}
Sorcerer::Sorcerer(Sorcerer const& src)
{
_title = src._title;
_name = src._name;
std::cout << _name << ", " << _title << ", is born!" << std::endl;
}
Sorcerer::~Sorcerer()
{
std::cout << _name << ", "<< _title << ", is dead.Consequences will never be the same!" << std::endl;
}
void Sorcerer::polymorph(Victim const& victim)
{
victim.getPolymorphed();
}
Sorcerer& Sorcerer::operator=(Sorcerer const& rhs)
{
_name = rhs.getName();
_title = rhs.getTitle();
return (*this);
}
std::ostream& operator<<(std::ostream& os, Sorcerer const& rhs)
{
os << "I am " << rhs.getName() << ", " << rhs.getTitle() << ", and i like ponies!" << std::endl;
return(os);
}
std::string const& Sorcerer::getName(void) const { return (_name); }
std::string const& Sorcerer::getTitle(void) const { return (_title); }
| true |
6cd60291213df29bc1f5071f4fc53a272debf6ba | C++ | acwilton/ModelCheckingAlgorithms | /src/ltl_parser.hh | UTF-8 | 4,348 | 2.71875 | 3 | [] | no_license | #ifndef LTL_PARSER_HH
#define LTL_PARSER_HH
#include <istream>
#include <string>
#include <functional>
#include <utility>
#include <optional>
#include <tuple>
#include "parser.hh"
#include "ltl.hh"
namespace parser {
template <typename AP>
class LTLParser {
public:
using Formula = mc::ltl::Formula<AP>;
LTLParser() = default;
LTLParser(Parser<Formula> const& apParser)
: apParser(apParser)
{}
LTLParser(LTLParser const&) = default;
LTLParser(LTLParser&&) = default;
~LTLParser() = default;
LTLParser& operator=(LTLParser const&) = default;
LTLParser& operator=(LTLParser&&) = default;
void setAPParser(Parser<Formula> const& newAPParser) {
apParser = newAPParser;
}
std::optional<Formula> operator()(ParserStream& pStream) const {
if (!pStream.match_token(SPEC)) {
pStream.reportError("Expected \"spec\" keyword at start of LTL specification.");
return std::nullopt;
}
if (!pStream.match_token(DEF)) {
pStream.reportError("Expected = after \"spec\".");
return std::nullopt;
}
auto opt_formula = match_formula(pStream);
if (!opt_formula) {
pStream.reportError("Unable to parse LTL formula.");
return opt_formula;
}
pStream.eat_whitespace();
if (!pStream.errors()) {
return opt_formula;
}
return std::nullopt;
}
private:
// Tokens
static constexpr auto LPAREN = R"(\()";
static constexpr auto RPAREN = R"(\))";
static constexpr auto EQUALS = R"(\=\=)";
static constexpr auto NOT_EQUALS = R"(\!\=)";
static constexpr auto LESSER = R"(<)";
static constexpr auto GREATER = R"(>)";
static constexpr auto LESS_EQ = R"(<\=)";
static constexpr auto GREAT_EQ = R"(>\=)";
static constexpr auto NUM = R"(-?[1-9][0-9]*)";
static constexpr auto AND = R"(&&)";
static constexpr auto OR = R"(\|\|)";
static constexpr auto NOT = R"(!)";
static constexpr auto UNTIL = "U";
static constexpr auto RELEASE = "R";
static constexpr auto FUTURE = "F";
static constexpr auto GLOBAL = "G";
static constexpr auto SPEC = R"(spec)";
static constexpr auto DEF = R"(=)";
std::optional<Formula> match_formula(ParserStream& pStream) const {
if (!pStream.match_token(LPAREN)) {
return std::nullopt;
}
auto errMsgGen = [](std::string name) {
return [name](int x) {
std::string posString = (x == 0) ? "first" : "second";
return "Failed to parse "+posString+" subformula of "+name+".";
};
};
std::optional<Formula> opt_formula;
if (pStream.match_token(GLOBAL)) {
opt_formula = parseFormula<1>(pStream, mc::ltl::make_global<AP>, errMsgGen(GLOBAL));
} else if (pStream.match_token(FUTURE)) {
opt_formula = parseFormula<1>(pStream, mc::ltl::make_future<AP>, errMsgGen(FUTURE));
} else if (pStream.match_token(UNTIL)) {
opt_formula = parseFormula<2>(pStream, mc::ltl::make_until<AP>, errMsgGen(UNTIL));
} else if (pStream.match_token(RELEASE)) {
opt_formula = parseFormula<2>(pStream, mc::ltl::make_release<AP>, errMsgGen(RELEASE));
} else if (pStream.match_token(NOT)) {
opt_formula = parseFormula<1>(pStream, mc::ltl::make_not<AP>, errMsgGen(NOT));
} else if (pStream.match_token(OR)) {
opt_formula = parseFormula<2>(pStream, mc::ltl::make_or<AP>, errMsgGen("||"));
} else if (pStream.match_token(AND)) {
opt_formula = parseFormula<2>(pStream, mc::ltl::make_and<AP>, errMsgGen(AND));
} else {
opt_formula = apParser(pStream);
}
if (!pStream.match_token(RPAREN)) {
pStream.reportError("Expected ) after formula.");
return std::nullopt;
}
return opt_formula;
}
template <int Arity, typename FactoryType>
auto parseFormula (ParserStream& pStream, FactoryType formulaFactory, std::function<std::string(int)>const& errMsg) const {
auto opt_subformulas = parseN<Arity,Formula>(std::bind(<LParser::match_formula, *this, std::placeholders::_1), pStream, errMsg);
return !opt_subformulas
? std::nullopt
: std::make_optional(std::apply(formulaFactory, *opt_subformulas));
};
Parser<Formula> apParser;
};
}
#endif
| true |
d46210e2785684db36100c700a731e10303d7289 | C++ | azure1016/leetcode_Cpp | /leetcode_Cpp/SearchInPivotedArray.cpp | UTF-8 | 799 | 3.171875 | 3 | [] | no_license | class Solution {
public:
bool search(vector<int>& nums, int target) {
if(nums.empty()) return false;
int head = 0,end = nums.size()-1,mid;
while(head<=end){
mid = (head + end)/2;
if(nums.at(mid)==target) return true;
else if(nums.at(mid)<nums.at(end)){//mid-end ascend
if(nums.at(mid)<target && nums.at(end)>=target) {
head = mid+1;
}
else end = mid-1;
}
else if(nums.at(mid)>nums.at(end)){//head-mid ascend
if(nums.at(head)<=target && nums.at(mid)>target){
end = mid-1;
}
else head = mid+1;
}
else end=end-1;
}
return false;
}
}; | true |
d1acac88ec68fb7b061d8d48b1ae18e2a3f0cb12 | C++ | datalate/another-jrpg | /level-editor/tileselectorscene.cc | UTF-8 | 1,592 | 2.6875 | 3 | [] | no_license | #include "tileselectorscene.hh"
#include <QDebug>
#include "common.hh"
using Level::TileInfo;
TileSelectorScene::TileSelectorScene() {
setBackgroundBrush(QBrush(QColor(Qt::darkGray)));
}
void TileSelectorScene::setTileSet(const std::unordered_map<unsigned int, TileInfo>& tileSet) {
unsigned int x{0};
unsigned int y{0};
for (auto const& tileInfo: tileSet) {
auto const& info{tileInfo.second};
TileItem* tile{new TileItem(x, y, info.id)};
qDebug() << QString::fromStdString(info.texture) << x << y;
// TODO: image/pixmap manager to reduce number of copies
const QImage img{"../img/" + QString::fromStdString(info.texture) + ".png"};
tile->setPixmap(QPixmap::fromImage(img));
addItem(tile); // transfer ownership
bool success{connect(tile, &TileItem::clicked, this, &TileSelectorScene::onTileClicked)};
Q_ASSERT(success);
tileSet_.push_back(tile);
x += 1;
}
//setSceneRect(0, 0, 2 * 32, 2 * 32);
emit tileSelected(tileSet_.front()); // Default tile
}
void TileSelectorScene::rePositionItems(const QSize& oldSize, const QSize& size) {
Q_UNUSED(oldSize);
const int width{size.width() / (int)TILE_WIDTH};
int x{0};
int y{0};
for (auto const& tile: tileSet_) {
tile->setTilePosition({x, y});
++x;
if (x == width) {
x -= width;
++y;
}
}
setSceneRect(0, 0, width * TILE_WIDTH, y * TILE_HEIGHT);
}
void TileSelectorScene::onTileClicked(TileItem* tile) {
emit tileSelected(tile);
}
| true |
fb1950e990e176c7f3ccc799705d2fc26d7adbf7 | C++ | NickcCosby/GameEngine | /GameEngine/GameEngine/Bitmap.cpp | UTF-8 | 3,796 | 2.828125 | 3 | [] | no_license | #include "Main.h"
#include <iterator>
//still needs implementation... probably
Bitmap * Bitmap::rotate(float angle)
{
//Bitmap* tempBitmap;
//return tempBitmap;
return nullptr;
}
Bitmap::Bitmap(std::string location)
{
std::ifstream input(location, std::ios::in | std::ios::binary | std::ios::ate);
// copies all data into buffer
if (_heapchk() != _HEAPOK)
DebugBreak();
int size = input.tellg();
input.seekg(0, std::ios::beg);
unsigned char *fileContent = new unsigned char[size];
input.read((char*)fileContent, size);
input.close();
width = (fileContent[18]+fileContent[19]*(int)pow(16, 2)+ fileContent[20]*(int)pow(16,4) + fileContent[21]*(int)pow(16,6));
height = (fileContent[22] + fileContent[23] * (int)pow(16, 2) + fileContent[24] * (int)pow(16, 4) + fileContent[25] * (int)pow(16, 6));
colors = new pixel[width*height];
nullPoints = new POINT[width*height];
nullPointsCount = 0;
int colorsLocation = (fileContent[10] + fileContent[11] * (int)pow(16, 2) + fileContent[12] * (int)pow(16, 4) + fileContent[13] * (int)pow(16, 6));
int tempLocation;
int colorsWritten = 0;
for (int bbb = height; bbb > 0; bbb--)
{
for (int aaa = 0; aaa < width; aaa++)
{
//tempLocation = (((aaa + (height - bbb)*width)*3) + colorsLocation);
tempLocation = (colorsWritten * 3) + colorsLocation;
colors[colorsWritten].b = fileContent[tempLocation];
colors[colorsWritten].g = fileContent[tempLocation + 1];
colors[colorsWritten].r = fileContent[tempLocation + 2];
if (colors[colorsWritten].b == 150 && colors[colorsWritten].g == 150 && colors[colorsWritten].r == 150)
{
nullPoints[nullPointsCount].x = colorsWritten % width;
nullPoints[nullPointsCount].y = (int)colorsWritten/(int)width;
nullPointsCount++;
}
colorsWritten++;
}
}
delete[] fileContent;
}
Bitmap::Bitmap(int givenWidth, int givenHeight)
{
width = givenWidth;
height = givenHeight;
nullPoints = new POINT[width*height];
nullPointsCount = 0;
colors = new pixel[width*height];
}
Bitmap::~Bitmap()
{
delete[] colors;
}
void Bitmap::setPixelColor(pixel tempColor, int x, int y)
{
colors[x + (width*y)] = tempColor;
}
Bitmap* Bitmap::createSubBitmap(RECT space)
{
int width, height;
height = space.top - space.bottom;
width = space.right - space.left;
Bitmap *tempBitmap = new Bitmap(width, height);
for (int curHeight = space.bottom; curHeight < space.top; curHeight++)
{
for (int curWidth = space.left; curWidth < space.right; curWidth++)
{
tempBitmap->setPixelColor(this->getColor(curWidth, curHeight), curWidth - space.left, curHeight - space.bottom);
if (this->getColor(curWidth, curHeight).b == 150 && this->getColor(curWidth, curHeight).g == 150 && this->getColor(curWidth, curHeight).r == 150)
{
tempBitmap->addNullPoint(curWidth - space.left, curHeight - space.bottom);
}
}
}
return tempBitmap;
}
/*Bitmap* Bitmap::scale(int newHeight, int newWidth)
{
int deltaHeight;
int deltaWidth;
double increaseRatioHeight;
double increaseRatioWidth;
deltaHeight = abs(newHeight - height);
deltaWidth = abs(newWidth - width);
increaseRatioHeight = deltaHeight / height;
increaseRatioWidth = deltaWidth / width;
pixel *newColors;
height = newHeight;
width = newWidth;
newColors = new pixel[height*width];
int pixelsRemaining;
int pixelOffset;
pixel* tempPixel;
for (int iii = 0; iii < height; iii++)
{
for (int bbb = 0; bbb < width; bbb++)
{
tempPixel = &newColors[getArrayPos(bbb, iii)];
if (pixelsRemaining < 1)
{
(*tempPixel).r = ((colors[getArrayPos(bbb, iii)].r + colors[getArrayPos(bbb-1, iii-1)].r) / 2);
(*tempPixel).r = ((colors[getArrayPos(bbb, iii)].r + colors[getArrayPos(bbb-1, iii-1)].r) / 2);
}
else
{
*tempPixel = colors[getArrayPos(bbb, iii)];
}
}
}
return this;
}
*/ | true |
ee3ff2e587c39daf6ba88ae94a35522a01e93717 | C++ | codedjinn/Barb2 | /Common/TextureDBIndex.h | UTF-8 | 740 | 2.765625 | 3 | [] | no_license | #ifndef TEXTUREDBINDEX_H_INCLUDED
#define TEXTUREDBINDEX_H_INCLUDED
#include <inttypes.h>
#include <map>
#include <string>
#include <vector>
class TextureDBIndex
{
public:
TextureDBIndex();
~TextureDBIndex();
/**
* Returns the offset of the texture into the texture database.
* @warning If the identifier is invalid, -1 is returned.
*/
int OffsetOfTexture(const std::string& identifier);
/**
* Load the index data from a file.
*/
void Load(FILE* file);
/**
* Debugging method, prints the contents of this index to the console.
*/
void PrintIndex() const;
std::vector<std::string> GetTextureList() const;
protected:
std::map<std::string, uint32_t> index;
};
#endif // TEXTUREDBINDEX_H_INCLUDED
| true |
e1d6de9acb34a56d082342b2ef9b15728fb247ff | C++ | DGolgovsky/Courses | /CPP_Deep/triangular_num.cpp | UTF-8 | 2,345 | 3.234375 | 3 | [
"Unlicense"
] | permissive | /*
* Напишите на языке C/C++ программу, определяющую номер треугольного числа
* (см. также последовательность A000217 в «Энциклопедии целочисленных
* последовательностей»).
*
* Примечание: число 0 (ноль) не считается принадлежащим ряду, который
* считается начинающимся с единицы: 1, 3, 6, 10, 15, 21, 28, ...
*
* Вход: одно целое (возможно, со знаком «плюс» и символом «перевод строки»
* \n) число в диапазоне от 1 до 9'223'372'036'854'775'807.
*
* Выход: порядковый номер поданного на вход числа в последовательности
* треугольных чисел или 0 (ноль), если такого числа в последовательности
* нет. Символ 0 (ноль) должен выдаваться и во всех случаях подачи на вход
* некорректных (отрицательных и лежащих вне допустимого диапазона
* положительных числовых, а также символьных / строковых) данных.
*
* Sample Input:
* 10
* Sample Output:
* 4
*/
#include <iostream>
#include <cstdint>
#include <string>
#include <errno.h>
using namespace std;
#define MAX 9223372036854775807
bool ReadA(int64_t &a)
{
std::string::size_type end = 0;
std::string str;
std::cin >> str;
std::size_t found = str.find_first_not_of("+\n0123456789");
if (found != std::string::npos)
return false;
else
a = stoull(str, NULL, 0);
long long value = 0;
if (!(value = std::stoll(str, &end, 10)) || errno)
return false;
std::string s = to_string(value);
if (a <= 0 || a > MAX)
return false;
else
return true;
}
int main(void)
{
int64_t a;
int64_t b = 0;
if (!ReadA(a)) {
std::cout << 0;
std::cout << std::endl;
return 0;
}
for (; a > 0; ++b)
a -= b;
std::cout << (a ? 0 : b - 1);
std::cout << std::endl;
return 0;
}
| true |
2c24c31dd2e8d741240e2d010a7fc853a0cf731d | C++ | dams333/Cours-OC | /Arith/Arith/main.cpp | UTF-8 | 287 | 3.296875 | 3 | [] | no_license | // Arith
#include <iostream>
using namespace std;
int main () {
double a, b;
cout << "Entrer a et b: ";
cin >> a >> b;
cout
<< "Le quotient de "
<< a
<< " et "
<< b
<< " vaut: "
<< (a/b)
<< "\n";
return 0;
}
| true |
baa91bfade8b9dbc03fe15987897af9e3cf1b287 | C++ | peichangliang123/UE4 | /Runtime/TypedElementRuntime/Public/Elements/Framework/TypedElementListObjectUtil.h | UTF-8 | 3,516 | 2.609375 | 3 | [] | no_license | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Elements/Framework/TypedElementList.h"
namespace TypedElementListObjectUtil
{
/**
* Test whether there are any objects in the given list of elements.
*/
TYPEDELEMENTRUNTIME_API bool HasObjects(const UTypedElementList* InElementList, const UClass* InRequiredClass = nullptr);
/**
* Test whether there are any objects in the given list of elements.
*/
template <typename RequiredClassType>
bool HasObjects(const UTypedElementList* InElementList)
{
return HasObjects(InElementList, RequiredClassType::StaticClass());
}
/**
* Count the number of objects in the given list of elements.
*/
TYPEDELEMENTRUNTIME_API int32 CountObjects(const UTypedElementList* InElementList, const UClass* InRequiredClass = nullptr);
/**
* Count the number of objects in the given list of elements.
*/
template <typename RequiredClassType>
int32 CountObjects(const UTypedElementList* InElementList)
{
return CountObjects(InElementList, RequiredClassType::StaticClass());
}
/**
* Enumerate the objects from the given list of elements.
* @note Return true from the callback to continue enumeration.
*/
TYPEDELEMENTRUNTIME_API void ForEachObject(const UTypedElementList* InElementList, TFunctionRef<bool(UObject*)> InCallback, const UClass* InRequiredClass = nullptr);
/**
* Enumerate the objects from the given list of elements.
* @note Return true from the callback to continue enumeration.
*/
template <typename RequiredClassType>
void ForEachObject(const UTypedElementList* InElementList, TFunctionRef<bool(RequiredClassType*)> InCallback)
{
ForEachObject(InElementList, [&InCallback](UObject* InObject)
{
return InCallback(CastChecked<RequiredClassType>(InObject));
}, RequiredClassType::StaticClass());
}
/**
* Get the array of objects from the given list of elements.
*/
TYPEDELEMENTRUNTIME_API TArray<UObject*> GetObjects(const UTypedElementList* InElementList, const UClass* InRequiredClass = nullptr);
/**
* Get the array of objects from the given list of elements.
*/
template <typename RequiredClassType>
TArray<RequiredClassType*> GetObjects(const UTypedElementList* InElementList)
{
TArray<RequiredClassType*> SelectedObjects;
SelectedObjects.Reserve(InElementList->Num());
ForEachObject<RequiredClassType>(InElementList, [&SelectedObjects](RequiredClassType* InObject)
{
SelectedObjects.Add(InObject);
return true;
});
return SelectedObjects;
}
/**
* Get the first object of the given type from the given list of elements.
*/
TYPEDELEMENTRUNTIME_API UObject* GetTopObject(const UTypedElementList* InElementList, const UClass* InRequiredClass = nullptr);
/**
* Get the first object of the given type from the given list of elements.
*/
template <typename RequiredClassType>
RequiredClassType* GetTopObject(const UTypedElementList* InElementList)
{
return Cast<RequiredClassType>(GetTopObject(InElementList, RequiredClassType::StaticClass()));
}
/**
* Get the last object of the given type from the given list of elements.
*/
TYPEDELEMENTRUNTIME_API UObject* GetBottomObject(const UTypedElementList* InElementList, const UClass* InRequiredClass = nullptr);
/**
* Get the last object of the given type from the given list of elements.
*/
template <typename RequiredClassType>
RequiredClassType* GetBottomObject(const UTypedElementList* InElementList)
{
return Cast<RequiredClassType>(GetBottomObject(InElementList, RequiredClassType::StaticClass()));
}
} // namespace TypedElementListObjectUtil
| true |
4b53c082a9936b36e61513aee41141fe209f7f32 | C++ | william-manning-levelex/VorteGrid | /Samples/MjgIntelFluidDemo_Part20/Particles/particleGroup.cpp | UTF-8 | 5,647 | 2.71875 | 3 | [] | no_license | /** \file particleGroup.cpp
\brief Group of particles and operations to perform on them.
\see http://www.mijagourlay.com/
\author Copyright 2009-2012 Dr. Michael Jason Gourlay; All rights reserved. Contact me at mijagourlay.com for licensing.
*/
#include "particleGroup.h"
#include <Core/Performance/perfBlock.h>
// Macros ----------------------------------------------------------------------
// Types -----------------------------------------------------------------------
ParticleGroup::~ParticleGroup()
{
Clear() ;
}
ParticleGroup::ParticleGroup( const ParticleGroup & that )
{
this->operator=( that ) ;
}
ParticleGroup & ParticleGroup::operator=( const ParticleGroup & that )
{
if( this != & that )
{ // Not self-copy.
Clear() ; // Delete all previous items in this object.
mParticles = that.mParticles ;
for( ConstIterator pclOpIter = that.mParticleOps.Begin() ; pclOpIter != that.mParticleOps.End() ; ++ pclOpIter )
{ // For each particle operation in the original group...
IParticleOperation * pclOpOrig = * pclOpIter ;
// Duplicate the original.
IParticleOperation * pclOpDupe = pclOpOrig->Clone() ;
// Remember the duplicate.
mParticleOps.PushBack( pclOpDupe ) ;
}
}
return * this ;
}
void ParticleGroup::Clear()
{
mParticles.Clear() ;
while( ! mParticleOps.Empty() )
{
IParticleOperation * pOp = mParticleOps.Back() ;
delete pOp ;
mParticleOps.PopBack() ;
}
}
/** Perform all particle operations in this group.
\see IParticleOperation
*/
void ParticleGroup::Update( float timeStep , unsigned uFrame )
{
PERF_BLOCK( ParticleGroup__Update ) ;
const size_t numOps = mParticleOps.Size() ;
for( size_t iOp = 0 ; iOp < numOps ; ++ iOp )
{ // Run operations in order.
IParticleOperation * pOp = mParticleOps[ iOp ] ;
pOp->Operate( mParticles , timeStep , uFrame ) ;
}
}
size_t ParticleGroup::IndexOfOperation( IParticleOperation * const pclOpAddress ) const
{
const size_t numOps = mParticleOps.Size() ;
for( size_t iOp = 0 ; iOp < numOps ; ++ iOp )
{ // For each particle operation...
IParticleOperation * const pOp = mParticleOps[ iOp ] ;
if( pclOpAddress == pOp )
{ // Found sought operation.
return iOp ;
}
}
return INVALID_INDEX ;
}
#include <Particles/Operation/pclOpFindBoundingBox.h>
#include <Particles/Operation/pclOpWind.h>
#include <Particles/Operation/pclOpAdvect.h>
#include <Particles/Operation/pclOpEvolve.h>
#include <Particles/Operation/pclOpAssignScalarFromGrid.h>
#include <Particles/Operation/pclOpPopulateVelocityGrid.h>
#include <Particles/Operation/pclOpEmit.h>
#include <Particles/Operation/pclOpKillAge.h>
#include <Particles/particleGroup.h>
#include <Particles/particleSystemManager.h>
ParticleGroup * CreateSampleParticleGroup( const Vec3 & basePosition , const Vec3 & acceleration )
{
ParticleGroup * pclGrpFlames = new ParticleGroup ;
// Start with particle destruction and creation operations.
{ // First kill particles to make room for new ones.
PclOpKillAge * pclOpKillAge = new PclOpKillAge ;
pclOpKillAge->mAgeMax = 90 ;
pclGrpFlames->PushBack( pclOpKillAge ) ;
}
{ // Second, emit new particles before moving them.
Particle emitterTemplate ;
emitterTemplate.mPosition = basePosition ;
emitterTemplate.mVelocity = Vec3( 0.0f , 0.0f , 2.0f ) ;
emitterTemplate.mSize = 0.0625f ; // Also see where Particles::Emit reassigns mSize. See calculation of pclSize.
emitterTemplate.mDensity = 1.0f ; // Actual value does not matter for this case.
# if ENABLE_FIRE
emitterTemplate.mFuelFraction = 0.0f ;
emitterTemplate.mFlameFraction = 0.0f ;
emitterTemplate.mSmokeFraction = 1.0f ;
# endif
Particle emitterSpread ;
emitterSpread.mPosition = Vec3( 0.5f , 0.5f , 0.5f ) ;
emitterSpread.mVelocity = Vec3( 0.5f , 0.5f , 0.5f ) ;
PclOpEmit * pclOpEmit = new PclOpEmit ;
pclOpEmit->mTemplate = emitterTemplate ;
pclOpEmit->mTemplate.mAngularVelocity = FLT_EPSILON * Vec3( 1.0f , 1.0f , 1.0f ) ;
pclOpEmit->mSpread = emitterSpread ;
pclOpEmit->mSpread.mDensity = 0.0f ;
pclOpEmit->mEmitRate = 100.0f ;
pclGrpFlames->PushBack( pclOpEmit ) ;
}
// Particle motion operations follow.
{
PclOpAccelerate * pclOpAccelerate = new PclOpAccelerate ;
pclOpAccelerate->mAcceleration = acceleration ;
pclGrpFlames->PushBack( pclOpAccelerate ) ;
}
{ // Wind replaces a portion of the particle velocity.
PclOpWind * pclOpWind = new PclOpWind ;
pclOpWind->mWindWeight = 0.02f ;
pclOpWind->mSrcWeight = 0.98f ;
pclOpWind->mWind = Vec3( 0.1f , 0.0f , 0.0f ) ;
pclGrpFlames->PushBack( pclOpWind ) ;
}
{ // Evolve runs after all operations that set velocity.
PclOpEvolve * pclOpEvolve = new PclOpEvolve ;
pclGrpFlames->PushBack( pclOpEvolve ) ;
}
{ // Find bounding box after particles have moved.
PclOpFindBoundingBox * pclOpFindBoundingBox = new PclOpFindBoundingBox ;
pclGrpFlames->PushBack( pclOpFindBoundingBox ) ;
}
return pclGrpFlames ;
}
| true |
106155994d095dd21d47323aa3246e499f63b43a | C++ | belyaev-mikhail/functional-hell | /matchers.hpp | UTF-8 | 23,867 | 2.78125 | 3 | [] | no_license | /*
* matchers.hpp
* author: Mikhail Beliaev
*
* ML-style pattern matching for C++
* As ambitious as that
* Ideas based on scala pattern matching and std::bind
*/
#ifndef MATCHERS_HPP_
#define MATCHERS_HPP_
#include <tuple>
#include <functional>
#include "matchers/match_structures.hpp"
#include "matchers/meta.hpp"
namespace functional_hell {
namespace matchers {
// a type you should return from unapply()
template<class ...Elems> using storage_t = match_result<impl_::wrapped_t<Elems>...>;
template<class ...Elems>
storage_t<Elems...> make_storage(Elems&&... elems) {
return storage_t<Elems...>{ std::forward<Elems>(elems)... };
}
/*************************************************************************************************/
namespace impl_ {
/*************************************************************************************************/
// calculate the magic tuple type by placeholders
template<class Tuple, class ...Args> struct applicate;
template<class Head, class ...Tail, class Arg0, class ...Args>
struct applicate< match_result<Head, Tail...>, Arg0, Args... > {
using elements = typename Arg0::template elements<Head>;
using type = merge_all_t<elements, typename applicate< match_result<Tail...>, Args... >::type >;
};
template<>
struct applicate< match_result<> > {
using type = merge_all_t<>;
};
template<class Head, class ...Tail, class Arg0, class ...Args>
struct applicate< const match_result<Head, Tail...>, Arg0, Args... > {
using elements = typename Arg0::template elements<Head>;
using type = merge_all_t<elements, typename applicate< const match_result<Tail...>, Args... >::type >;
};
template<>
struct applicate< const match_result<> > {
using type = merge_all_t<>;
};
template<class It, class Arg0, class ...Args>
struct applicate< match_sequence<It>, Arg0, Args... > {
using single = decltype(*std::declval<It>());
using elements = typename Arg0::template elements<impl_::wrapped_t<single>>;
using type = merge_all_t<elements, typename applicate< match_sequence<It>, Args... >::type >;
};
template<class It>
struct applicate< match_sequence<It> > {
using type = merge_all_t<>;
};
/*************************************************************************************************/
// call unapply_impl on all tree elements
template<std::size_t S, class Storage, class MatchRes, class ...Args>
struct unapplier {
static constexpr std::size_t K = sizeof...(Args) - S;
static bool doIt(const std::tuple<Args...>& matchers, Storage& storage, MatchRes&& mres) {
if(!std::get<K>(matchers).unapply_impl(storage, get<K>(mres))) return false;
return unapplier<S-1, Storage, MatchRes, Args...>
::doIt(matchers, storage, std::forward<MatchRes>(mres));
}
};
template<class Storage, class MatchRes, class ...Args>
struct unapplier<0, Storage, MatchRes, Args...> {
static bool doIt(const std::tuple<Args...>&, Storage&, MatchRes&&) {
return true;
}
};
// call unapply_impl on all tree elements
template<std::size_t S, class Storage, class MatchIter, class ...Args>
struct seq_unapplier {
static constexpr std::size_t K = sizeof...(Args) - S;
static bool doIt(const std::tuple<Args...>& matchers, Storage& storage, MatchIter begin, MatchIter end) {
if(begin == end) return false;
if(!std::get<K>(matchers).unapply_impl(storage, *begin)) return false;
return seq_unapplier<S-1, Storage, MatchIter, Args...>
::doIt(matchers, storage, ++begin, end);
}
};
template<class Storage, class MatchIter, class ...Args>
struct seq_unapplier<0, Storage, MatchIter, Args...> {
static bool doIt(const std::tuple<Args...>&, Storage&, MatchIter begin, MatchIter end) {
return begin == end;
}
};
// call unapply_impl on all tree elements
template<class Storage, class MatchIter, class Arg>
struct repeated_unapplier {
static bool doIt(const Arg& matcher, Storage& storage, MatchIter begin, MatchIter end) {
if(begin == end) return false;
if(!matcher.unapply_impl(storage, *begin)) return false;
++begin;
if(begin == end) return true;
return doIt(matcher, storage, begin, end);
}
};
/*************************************************************************************************/
template<class T> struct no_ref_c { using type = T; };
template<class T> struct no_ref_c<T&> { using type = T; };
template<class T> struct no_ref_c<T&&> { using type = T; };
template<class T> struct no_ref_c<match_reference<T>> { using type = T; };
template<class T> struct no_ref_c<match_reference<T>&> { using type = T; };
template<class T> struct no_ref_c<const match_reference<T>&> { using type = T; };
template<class T> struct no_ref_c<match_reference<T>&&> { using type = T; };
template<class T> using no_ref = typename no_ref_c<T>::type;
template<class T> struct lower_ref { using type = T; };
template<class T> struct lower_ref<match_reference<T>> { using type = T&; };
template<class T> struct lower_ref<match_reference<T>&> { using type = T&; };
template<class T> struct lower_ref<match_reference<T>&&> { using type = T&; };
template<class T> using lower_ref_t = typename lower_ref<T>::type;
template< class T >
T& unwrap( T& t ) {
return t;
}
template<class T>
T& unwrap(match_reference<T> ref) {
return ref.get();
}
/*************************************************************************************************/
} /* namespace impl_ */
/*************************************************************************************************/
template<class T, class = void>
struct compare_trait {
// static_assert(sizeof(T) <= 0, "You cannot use two similar placeholders for type that do not define eithe `==` or custom functional_hell::matchers::compare_trait");
template<class U, class V>
bool operator()(U&&, V&&) const {
return false;
}
};
template<class T>
struct compare_trait<T, impl_::enable_if_t<impl_::has_equality<T>>> {
template<class U, class V>
bool operator()(U&& lhv, V&& rhv) const {
return lhv == rhv;
}
};
/*************************************************************************************************/
struct matcher {};
/*************************************************************************************************/
// matcher for constants: matching is essentially an equality check
template<class H>
struct constant_matcher: matcher {
template<class V> using elements = impl_::nil_map;
impl_::wrapped_t<H> data;
constant_matcher(H h): data(h) {};
template<class T, class V>
bool unapply_impl(T&, V&& value) const{
auto cmp = compare_trait<impl_::no_ref<V>>{};
return cmp(std::forward<V>(value), data);
}
};
namespace impl_ {
template<class T, class = void>
struct toMatcher;
template<class T>
using toMatcher_t = typename toMatcher<T>::type;
} /* namespace impl_ */
/*************************************************************************************************/
template<class Matcher>
struct expand_matcher: matcher {
using base_t = Matcher;
Matcher base;
expand_matcher(const Matcher& base): base(base) {};
};
/*************************************************************************************************/
// matcher for complex structures with unapply and such: matching boils down to breaking values
// with unapply and passing results to lower-level matchers
template<class Lam, class ...Args>
struct tree_matcher: matcher {
Lam lam;
std::tuple<impl_::toMatcher_t<Args>...> matchers;
tree_matcher(Lam lam, const Args&... args): lam(lam), matchers{ args... } {}
template<class V>
using unapplied = decltype(
lam.unapply(std::forward<impl_::lower_ref_t<V>>(std::declval<impl_::lower_ref_t<V>>()))
);
template<class V>
using elements = typename impl_::applicate< unapplied<V>, impl_::toMatcher_t<Args>... >::type;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
auto ret = lam.unapply(impl_::unwrap(v));
if(!ret) return false;
return impl_::unapplier<sizeof...(Args), T, decltype(ret), impl_::toMatcher_t<Args>...>
::doIt(matchers, storage, std::move(ret));
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<tree_matcher> operator*() const {
return expand_matcher<tree_matcher>{*this};
}
};
/*************************************************************************************************/
// matcher for sequences
template<class Arg>
struct repeated_matcher: matcher {
impl_::toMatcher_t<Arg> matcher;
repeated_matcher(const Arg& arg): matcher{ arg } {}
template<class V>
using unapplied = decltype(
std::begin(std::forward<impl_::lower_ref_t<V>>(std::declval<impl_::lower_ref_t<V>>()))
);
template<class V>
using elements = typename impl_::applicate< match_sequence<unapplied<V>>, impl_::toMatcher_t<Arg> >::type;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
return impl_::repeated_unapplier<T, unapplied<V>, impl_::toMatcher_t<Arg>>
::doIt(matcher, storage, std::begin(impl_::unwrap(v)), std::end(impl_::unwrap(v)));
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<repeated_matcher> operator*() const {
return expand_matcher<repeated_matcher>{*this};
}
};
// matcher for sequences
template<class ...Args>
struct seq_matcher: matcher {
std::tuple<impl_::toMatcher_t<Args>...> matchers;
seq_matcher(const Args&... args): matchers{ args... } {}
template<class V>
using unapplied = decltype(
std::begin(std::forward<impl_::lower_ref_t<V>>(std::declval<impl_::lower_ref_t<V>>()))
);
template<class V>
using elements = typename impl_::applicate< match_sequence<unapplied<V>>, impl_::toMatcher_t<Args>... >::type;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
return impl_::seq_unapplier<sizeof...(Args), T, unapplied<V>, impl_::toMatcher_t<Args>...>
::doIt(matchers, storage, std::begin(impl_::unwrap(v)), std::end(impl_::unwrap(v)));
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<seq_matcher> operator*() const {
return expand_matcher<seq_matcher>{*this};
}
};
namespace impl_ {
struct make_seq_matcher {
template<class ...Args>
seq_matcher<impl_::toMatcher_t<Args>...> operator()(Args&&... args) {
return seq_matcher<impl_::toMatcher_t<Args>...>{ std::forward<Args>(args)... };
}
};
template<class T>
struct IsExpandMatcher {
static constexpr bool value = false;
};
template<class T>
struct IsExpandMatcher<expand_matcher<T>> {
static constexpr bool value = true;
};
}// namespace impl_
template<class ...Args>
struct break_matcher: matcher {
static constexpr size_t WHERE = impl_::find_first_arg<impl_::IsExpandMatcher, Args...>::value;
static constexpr size_t TOTAL = sizeof...(Args);
//using divider = impl_::Breaker<seq_matcher<>, impl_::toMatcher_t<Args>...>;
//using Pre = typename divider::Pre;
//using Mid = typename divider::Mid;
//using Pos = typename divider::Pos;
using TA = impl_::type_array<impl_::toMatcher_t<Args>...>;
using Pre = impl_::take_and_apply_template_t<WHERE, seq_matcher, impl_::toMatcher_t<Args>...>;
using Mid = typename impl_::nth_element_t<TA, WHERE>::base_t;
using Pos = impl_::drop_and_apply_template_t<WHERE+1, seq_matcher, impl_::toMatcher_t<Args>...>;
impl_::decay_t<impl_::toMatcher_t<Pre>> pre;
impl_::decay_t<impl_::toMatcher_t<Mid>> mid ;
impl_::decay_t<impl_::toMatcher_t<Pos>> pos;
break_matcher(const Args&... args):
pre(impl_::take_and_apply<WHERE>(impl_::make_seq_matcher{}, args...)),
mid(impl_::nth_element<TA, WHERE>::apply(args...).base),
pos(impl_::drop_and_apply<WHERE+1>(impl_::make_seq_matcher{}, args...)) {
}
template<class V>
using proxy = match_sequence< decltype(
std::begin(std::forward<impl_::lower_ref_t<V>>(std::declval<impl_::lower_ref_t<V>>()))
)>;
template<class V>
using elements = impl_::merge_all_t<
typename Pre::template elements<proxy<V>>,
typename Mid::template elements<proxy<V>>,
typename Pos::template elements<proxy<V>>
>;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
auto start = std::begin(impl_::unwrap(v));
auto end = std::end(impl_::unwrap(v));
auto mid0 = std::next(start, WHERE);
auto mid1 = std::next(end, -(TOTAL - WHERE - 1));
bool first = pre.unapply_impl(storage, proxy<V>{ start, mid0 });
if(!first) return false;
bool middle = mid.unapply_impl(storage, proxy<V>{ mid0, mid1 });
if(!middle) return false;
bool last = pos.unapply_impl(storage, proxy<V>{ mid1, end });
return last;
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<break_matcher> operator*() const {
return expand_matcher<break_matcher>{*this};
}
};
template<class ...Args>
seq_matcher<impl_::toMatcher_t<Args>...> Seq(Args&&... args) {
return seq_matcher<impl_::toMatcher_t<Args>...>{ std::forward<Args>(args)... };
}
template<class Arg>
repeated_matcher<impl_::toMatcher_t<Arg>> Repeat(Arg&& arg) {
return repeated_matcher<impl_::toMatcher_t<Arg>>{ std::forward<Arg>(arg) };
}
template<class ...Args>
typename std::enable_if<
impl_::find_first_arg<impl_::IsExpandMatcher, impl_::toMatcher_t<Args>...>::value != ~0U,
break_matcher<impl_::toMatcher_t<Args>...>
>::type
BSeq(Args&&... args) {
return break_matcher<impl_::toMatcher_t<Args>...>{ std::forward<Args>(args)... };
}
template<class ...Args>
typename std::enable_if<
impl_::find_first_arg<impl_::IsExpandMatcher, impl_::toMatcher_t<Args>...>::value == ~0U,
seq_matcher<impl_::toMatcher_t<Args>...>
>::type
BSeq(Args&&... args) {
return seq_matcher<impl_::toMatcher_t<Args>...>{ std::forward<Args>(args)... };
}
/*************************************************************************************************/
// or-matcher
template<class Lhv, class Rhv>
struct or_matcher: matcher {
impl_::toMatcher_t<Lhv> lhv;
impl_::toMatcher_t<Rhv> rhv;
or_matcher(const Lhv& lhv, const Rhv& rhv): lhv(lhv), rhv(rhv) {}
template<class V>
using elements = typename Lhv::template elements<V>;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
static_assert(std::is_same<
impl_::map2result_t<typename Rhv::template elements<V>>,
impl_::map2result_t<typename Lhv::template elements<V>>
>::value, "Or patterns can only be used with an identical set of placeholders");
bool left = lhv.unapply_impl(storage, v);
if(left) return true;
storage.destruct();
storage.construct();
bool right = rhv.unapply_impl(storage, v);
if(right) return true;
return false;
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<or_matcher> operator*() const {
return expand_matcher<or_matcher>{*this};
}
};
/*************************************************************************************************/
// and-matcher
template<class Lhv, class Rhv>
struct and_matcher: matcher {
impl_::toMatcher_t<Lhv> lhv;
impl_::toMatcher_t<Rhv> rhv;
and_matcher(const Lhv& lhv, const Rhv& rhv): lhv(lhv), rhv(rhv) {}
template<class V>
using elements = impl_::merge_maps_t<typename Lhv::template elements<V>, typename Rhv::template elements<V>>;
template<class T, class V>
bool unapply_impl(T& storage, V&& v) const {
bool left = lhv.unapply_impl(storage, v);
if(!left) return false;
bool right = rhv.unapply_impl(storage, v);
return right;
}
template<class V>
impl_::map2result_t<elements<V>> match(V&& v) const{
impl_::map2result_t<elements<V>> ret;
ret.construct();
if(!unapply_impl(ret, std::forward<V>(v))) return impl_::map2result_t<elements<V>>();
return std::move(ret);
}
template<class V>
impl_::map2result_t<elements<V>> operator >> (V&& v) const{
return match(std::forward<V>(v));
}
template<class V>
bool operator == (V&& v) const{
return static_cast<bool>(match(std::forward<V>(v)));
}
expand_matcher<and_matcher> operator*() const {
return expand_matcher<and_matcher>{*this};
}
};
/*************************************************************************************************/
namespace impl_ {
template<class U, class V>
bool compare_equal(U&& lhv, V&& rhv) {
using TT = typename std::common_type<no_ref<U>, no_ref<V>>::type;
compare_trait<no_ref<TT>> cp;
return cp(lhv, rhv);
}
} /* namespace impl_ */
// placeholder is not really a matcher: it matches anything and stores it into the match result object
template<std::size_t N>
struct placeholder : matcher {
placeholder() = default;
placeholder(const placeholder&) = default;
template<class U>
placeholder(U&&) {}
template<class V>
using elements = impl_::int_type_map< impl_::map_entry< N, V >, impl_::nil_map >;
template<class T, class V>
bool unapply_impl(T& storage, V&& value) const{
if(!storage) storage.construct();
if(is_set<N>(storage)) {
return impl_::compare_equal(get<N>(storage), value);
}
set<N>(storage, std::forward<V>(value));
return true;
}
expand_matcher<placeholder> operator*() const {
return expand_matcher<placeholder>{*this};
}
};
/*************************************************************************************************/
// ignore is not a matcher at all: it matches anything and does nothing about it, hence the name
struct ignore : matcher {
template<class V> using elements = impl_::nil_map;
template<class T, class V>
bool unapply_impl(T&, V&&) const {
return true;
}
expand_matcher<ignore> operator*() const {
return expand_matcher<ignore>{*this};
}
};
/*************************************************************************************************/
namespace placeholders{
static placeholder<0> _1;
static placeholder<1> _2;
static placeholder<2> _3;
static placeholder<3> _4;
static placeholder<4> _5;
static placeholder<5> _6;
static placeholder<6> _7;
static placeholder<7> _8;
static placeholder<8> _9;
static ignore _;
} /* namespace placeholders */
/*************************************************************************************************/
namespace impl_ {
template<class T>
using is_matcher = std::is_base_of<matcher, impl_::decay_t<T>>;
template<class T>
struct toMatcher<T, invoke<std::enable_if<is_matcher<T>::value>>> {
using type = impl_::decay_t<T>;
};
template<class T>
struct toMatcher<T, invoke<std::enable_if<std::is_placeholder<T>::value && !is_matcher<T>::value>>> {
using type = placeholder<std::is_placeholder<T>::value - 1>;
};
template<class T>
struct toMatcher<T, invoke<std::enable_if<!std::is_placeholder<T>::value && !is_matcher<T>::value>>> {
using type = constant_matcher<T>;
};
} /* namespace impl_ */
template<
class L, class R,
class = std::enable_if_t<
impl_::is_matcher<L>::value || impl_::is_matcher<R>::value
|| std::is_placeholder<L>::value || std::is_placeholder<R>::value
>
>
and_matcher<impl_::toMatcher_t<L>, impl_::toMatcher_t<R>> operator & (const L& l, const R& r) {
return and_matcher<impl_::toMatcher_t<L>, impl_::toMatcher_t<R>>(l, r);
}
template<
class L, class R,
class = std::enable_if_t<
impl_::is_matcher<L>::value || impl_::is_matcher<R>::value
|| std::is_placeholder<L>::value || std::is_placeholder<R>::value
>
>
or_matcher<impl_::toMatcher_t<L>, impl_::toMatcher_t<R>> operator | (const L& l, const R& r) {
return or_matcher<impl_::toMatcher_t<L>, impl_::toMatcher_t<R>> (l, r);
}
} /* namespace matchers */
} /* namespace functional_hell */
namespace std {
template<> struct is_placeholder<functional_hell::matchers::placeholder<0>> : public integral_constant<int, 1> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<1>> : public integral_constant<int, 2> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<2>> : public integral_constant<int, 3> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<3>> : public integral_constant<int, 4> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<4>> : public integral_constant<int, 5> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<5>> : public integral_constant<int, 6> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<6>> : public integral_constant<int, 7> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<7>> : public integral_constant<int, 8> {};
template<> struct is_placeholder<functional_hell::matchers::placeholder<8>> : public integral_constant<int, 9> {};
}
#endif /* MATCHERS_HPP_ */
| true |
9424fa2907694b272c4f79e122117eb6c59ef1e0 | C++ | wenshuiqing/Demo | /VulkanStudy/VulkanCode/VulkanCode/VulkanDevice.cpp | GB18030 | 5,926 | 2.765625 | 3 | [] | no_license | #include "VulkanDevice.h"
#include <set>
#include "VulkanWindow.h"
#include "VulkanInstance.h"
#include "VulkanLayerAndExtension.h"
VulkanDevice * VulkanDevice::instance = 0;
VulkanDevice::VulkanDevice()
{
}
VulkanDevice::~VulkanDevice()
{
}
VulkanDevice* VulkanDevice::GetInstance()
{
if (instance == nullptr)
instance = new VulkanDevice();
return instance;
}
void VulkanDevice::Init()
{
createSurface();
PickPhysicalDevice();
createLogicDevice();//豸豸
}
void VulkanDevice::Destroy()
{
vkDestroyDevice(device, nullptr);
vkDestroySurfaceKHR(VulkanInstance::GetInstance()->instance, surface, nullptr);
}
void VulkanDevice::createSurface()
{
if (surface != nullptr)return;
if (glfwCreateWindowSurface(VulkanInstance::GetInstance()->instance, VulkanWindow::GetInstance()->window, nullptr, &surface) != VK_SUCCESS) {
throw std::runtime_error("failed to create window surface!");
}
}
void VulkanDevice::PickPhysicalDevice()
{
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(VulkanInstance::GetInstance()->instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("failed to find GPUs with vulkan support!");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(VulkanInstance::GetInstance()->instance, &deviceCount, devices.data());
for (const auto&device : devices)
{
if (isDeviceSuitable(device)) {
physicalDevice = device;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU !");
}
}
void VulkanDevice::createLogicDevice()
{
QueueFamilyIndices indices = FindQueueFamilies();
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos = {};
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(),indices.presentFamily.value() };
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies)
{
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures = {};
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(requestDeviceExtensions.size());
createInfo.ppEnabledExtensionNames = requestDeviceExtensions.data();
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(requestLayers.size());
createInfo.ppEnabledLayerNames = requestLayers.data();
}
else
{
createInfo.enabledLayerCount = 0;
}
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
throw std::runtime_error("Failed to create logic device!");
}
//նоdeviceʱлᱻ٣ֶ
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
}
QueueFamilyIndices VulkanDevice::findQueueFamilies(VkPhysicalDevice device)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueCount > 0 && queueFamily.queueFlags&VK_QUEUE_GRAPHICS_BIT) {
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (queueFamily.queueCount > 0 && presentSupport) {
indices.presentFamily = i;
}
if (indices.isComplete())
break;
i++;
}
return indices;
}
SwapChainSupportDetails VulkanDevice::querySwapChainSupport(VkPhysicalDevice device)
{
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0) {
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0) {
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
QueueFamilyIndices VulkanDevice::FindQueueFamilies()
{
return findQueueFamilies(physicalDevice);
}
bool VulkanDevice::isDeviceSuitable(VkPhysicalDevice device)
{
//1.Զе֧
QueueFamilyIndices indices = findQueueFamilies(device);
//2.豸չ֧
bool extensionSupported =VulkanLayerAndExtension::GetInstance()->CheckExtensionSupport(requestDeviceExtensions,device);
bool swapChainAdequate = false;
if (extensionSupported) {
//2.1 ѯǰжϵ豸չĽsufaceģ֧Ƿ㹻
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
return indices.isComplete() && extensionSupported&&swapChainAdequate;
}
SwapChainSupportDetails VulkanDevice::QuerySwapChainSupport()
{
return querySwapChainSupport(physicalDevice);
}
| true |
0c38e53632bca8c3dfb5b3cc3bc8670838b0c458 | C++ | OutsideTheBoxProject/R | /LampBlink/LampBlink.ino | UTF-8 | 846 | 2.546875 | 3 | [] | no_license | #include <Process.h>
// switch on/off Philis Hue lamp via Yun
void setup()
{
Bridge.begin(); // Initialize the Bridge
}
void loop()
{
Process p;
p.runShellCommand("curl -X PUT -d '{\"on\":true, \"ct\" : 153, \"bri\":254 }' http://192.168.0.100/api/EE2Md-XKTaIjMj9J78ztSPZruD9l9P6A0SknxsJd/lights/1/state"); // switch on, ct 6500 K, brightness max
while(p.running());
delay(5000);
p.runShellCommand("curl -X PUT -d '{\"on\":false}' http://192.168.0.100/api/EE2Md-XKTaIjMj9J78ztSPZruD9l9P6A0SknxsJd/lights/2/state"); // switch off
while(p.running());
delay(5000);
p.runShellCommand("curl -X PUT -d '{\"on\":true,\"hue\":0, \"bri\":50 }' http://192.168.0.100/api/EE2Md-XKTaIjMj9J78ztSPZruD9l9P6A0SknxsJd/lights/1/state"); // switch on, Hue red, brightness 50
while(p.running());
delay(5000);
}
| true |
76ed5676b4f9357b2e2cfbf4ba19bd21e115ef0c | C++ | silentWatcher3/graphMat | /3d_graph_mat_decl.hpp | UTF-8 | 8,870 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream> // for std::cout set as default for std::ostream
#include <cstdint>
#include <atomic> // for std::atomic_bool
#include <functional> // for std::function
#include <optional>
#include <variant>
#include <future> // for std::promise
#include "matrix_base.hpp"
#include "3d_graph_box.hpp"
#include "direction.hpp"
/*
@notes about directions ->
The screen is considered to be parallel to the xy plane, hence DOWN, UP, LEFT, RIGHT are lines parallel the x or y axis only
And, -z axis is considered as BACK_FACING (PATAL)
+z axis is considered as FRONT_FACING (AAKASH)
*/
enum class MatrixLayer {
TOP,
DEEPEST,
ORIGIN
};
template<typename node_dtype, typename dimen_t = int32_t>
class Graph_Matrix_3D : Matrix_Base{
static_assert(std::is_signed_v<dimen_t>, "Dimension type must be a signed integral (for safety reasons, so that bugs don't appear due to unsigned subtractions)");
static_assert(std::is_default_constructible_v<node_dtype>, "The data type of values in the matrix must be default constructible");
// Now pointer support added
//static_assert( ! std::is_pointer_v<node_dtype>, "Currently it doesn't support using pointers to be the data held by each box, though it maybe implemented, but not now");
typedef Graph_Box_3D<node_dtype> graph_box_type;
typedef util::_coord<dimen_t> coord_type;
typedef std::variant<
std::function<node_dtype && ()>,
std::function<node_dtype && (int, int, int)>,
std::function<void (node_dtype&, int, int, int)>,
std::function<void (Graph_Box_3D<node_dtype>&)>
> Init_Func;
protected:
graph_box_type origin;
graph_box_type* top_left_front;
graph_box_type* top_left_back;
graph_box_type* bottom_left_front;
graph_box_type* bottom_left_back;
graph_box_type* top_right_front;
graph_box_type* top_right_back;
graph_box_type* bottom_right_front;
graph_box_type* bottom_right_back;
MemoryAlloc< Graph_Box_3D<node_dtype> > allocator;
dimen_t min_x, min_y, min_z; // ALWAYS NON-POSITIVES (since origin layer won't be removed so at max 0)
dimen_t max_x, max_y, max_z; // ALWAYS NON-NEGATIVES ( " " " " " " " " min 0)
coord_type total_abs; // total span of a single dimension
struct {
float expansion_speed{ Matrix_Base::init_expansion_speed }; //initially it will auto_expand statics::init_expansion_speed unit at time, each side
float curr_expansion_speed{ Matrix_Base::init_expansion_speed };
float increase_units{0.0}; // units to increase in each direction, in call to expand_once()
const int milliseconds_in_unit_time{ 1000 }; // by default consider it 1 second
//float last_increase_units; // @note @me - expansion speed itself behaves as this
std::atomic_bool expansion_flag{ false };
std::optional< Init_Func > initializer_function;
void set_initializer(const Init_Func& initialiser) {
initializer_function = initialiser;
}
void reset_initializer() {
this->initializer_function.reset();
}
int time_since_speed_updated{ 0 }; //after 10 time units, the __expansion_state.expansion_speed will be decremented/reset, so as to not unecessary keep increasing storage
}__expansion_state;
// AUTO EXPANSION LOGIC START
virtual void auto_expansion() override; //keeps expanding TILL expansion_flag is TRUE
virtual void expand_once();
virtual void expand_n_unit(const uint8_t);
// AUTO EXPANSION LOGIC END
struct {
graph_box_type* top_left_front;
graph_box_type* top_left_back;
graph_box_type* bottom_left_front;
graph_box_type* bottom_left_back;
graph_box_type* top_right_front;
graph_box_type* top_right_back;
graph_box_type* bottom_right_front;
graph_box_type* bottom_right_back;
coord_type total_abs;
} __capacity; //capacity data
void add_x_layer(int num = 1);
void inject_x_layer(int num = 1);
void pop_xplus_layer();
void pop_xminus_layer();
void add_y_layer(int num = 1);
void inject_y_layer(int num = 1);
void pop_yplus_layer();
void pop_yminus_layer();
void add_z_layer(int num = 1);
void inject_z_layer(int num = 1);
void pop_zplus_layer();
void pop_zminus_layer();
void disp_xy_layer(MatrixLayer ltype = MatrixLayer::TOP);
void disp_xy_layer(int lnum, std::ostream& os = std::cout);
template < typename _Func >
void for_each(graph_box_type* source, Direction, _Func); // func will receive only one param, ie. the node_dtype data
template<typename _Func>
void for_each(graph_box_type* begin, graph_box_type* end, Direction dir, _Func func);
//template < typename _Cond, typename _Func > // though this is an idea, but doesn't seem of much help
//void for_each(_Cond condition_function_takes_data_returns_direction_to_move, _Func); // func will receive only one param, ie. the node_dtype data
std::mutex m;
std::condition_variable auto_expansion_convar; // convar to signal the pause_auto_expansion() when auto() expansion actually stops
std::atomic_bool is_auto_paused; // extra bool to tell whether
public:
/**
* @note - It is `time based expansion`, that is the expansion rate decreases over time, and gains normal speed back up too, then again that
* For more customizarion, you can overload these, for a similar example using `unused space` in the matrix to decide whether to grow,
* see `world_plot.cpp` in the [WorldLine Simulator](https://github.com/adi-g15/worldLineSim) project
*
* @note2 - It expands equally at each plane, again, for more customization it can be overloaded :D
*/
virtual void pause_auto_expansion() override;
virtual void resume_auto_expansion() override;
// OVERLOAD similar to resume_auto_expansion(), just that for each new box, the callable is executed, and returned value assigned to box::data
template<typename Callable>
void resume_auto_expansion(Callable&&);
void set_expansion_rate(float);
graph_box_type* operator[](const coord_type&);
const graph_box_type* operator[](const coord_type&) const;
graph_box_type* operator[](const graph_position& pos);
const graph_box_type* operator[](const graph_position& pos) const;
// these are metadata for resize() function, and it's variants
enum class RESIZE_TYPE {
AUTO_EXPANSION, // called by auto expansion
MANUAL // manually called resize()
};
struct {
RESIZE_TYPE curr_resize_type{ RESIZE_TYPE::MANUAL };
bool add_or_inject_flag; // when auto expanding, this is used to `alternatively` add or inject planes, so that it doesn't just expand in one direction
} tmp_resize_data; // this will be used by ALL size INREASING member function (so better declare than pass always)
std::optional< Init_Func > data_initialiser;
void set_initialiser(const Init_Func& func) { data_initialiser = func; }
void reset_initialiser() { data_initialiser.reset(); }
void resize(const dimen_t, const dimen_t, const dimen_t, RESIZE_TYPE = RESIZE_TYPE::MANUAL);
void resize(const dimen_t, const dimen_t, const dimen_t, const Init_Func& data_initialiser, RESIZE_TYPE = RESIZE_TYPE::MANUAL);
std::tuple<dimen_t, dimen_t, dimen_t> get_size() const noexcept;
/*
A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.
*/
template<typename _Func, typename std::enable_if_t<std::is_invocable_r_v<node_dtype, _Func, dimen_t, dimen_t, dimen_t>>>
void for_all(_Func); // _Func is a lambda that receives modifiable reference to the data box
template<typename _Func, std::enable_if_t<std::is_invocable_r_v<void, _Func, node_dtype&>, int> = 0 >
void for_all(_Func); // _Func is a lambda that receives the 3 dimensions
graph_box_type* find(const node_dtype& value); // uses operator== for comparison
//template<typename UnaryPredicate>
//graph_box_type* find(UnaryPredicate& func);
graph_box_type* swastic_find(graph_box_type* plane_center, const node_dtype& value); // also needs a point to start from
//template<typename UnaryPredicate>
//graph_box_type* swastic_find(graph_box_type* plane_center, UnaryPredicate& func);
//enum class FINDER {
// SWASTIC, // only swastic finder currently
// BFS,
// AUTO
//};
//template<FINDER finder>
//graph_box_type* find(const node_dtype& value); // uses operator== for comparison
//template<FINDER finder, typename UnaryPredicate>
//graph_box_type* find(UnaryPredicate& func);
//template<std::enable_if_t< !std::is_pointer_v<node_dtype>, int> = 0 >
Graph_Matrix_3D();
//template<std::enable_if_t< std::is_pointer_v<node_dtype>, int> = 0 >
//Graph_Matrix_3D();
//template<std::enable_if_t< !std::is_pointer_v<node_dtype>, int> = 0 >
Graph_Matrix_3D(const coord_type& dimensions);
template<typename Func>
Graph_Matrix_3D(const coord_type& dimensions, Func&&); // with initialiser
~Graph_Matrix_3D();
};
| true |
fb6490914fadf14a1579ea1c9615edc66958d610 | C++ | betelgieser/SupercomputersPMI_2018 | /VTMatrix.h | WINDOWS-1251 | 5,008 | 3.625 | 4 | [] | no_license | #pragma once
#include <iostream>
class VTMatrix
{
private:
int *data;//
int *zero_block;//
int block_quantity;//-
int block_width;//
int block_capacity;//-
int matrix_width;//
int matrix_capacity;//-
int width_matrix_in_blocks;//
//
int getFirstElementBlock(int blockY, int blockX);
//
int getElementBlock(int row, int column);
//
void zerofication();
public:
// -
VTMatrix(int matrix_width, int block_width);
// -
~VTMatrix();
int getValue(int row, int column);//
void setValue(int row, int column, int value);//
int *getBlock(int blockY, int blockX);//
void readMatrixFromFile(std::string filePath);//
void printMatrix();//
void generateMatrix(int min_val, int max_val);
};
int VTMatrix::getFirstElementBlock(int blockY, int blockX)
{
//
int block_number = blockY * width_matrix_in_blocks - ((2.0 + (double)blockY - 1) / 2.0)*(double)blockY + blockX;
return block_number * block_capacity;
}
int VTMatrix::getElementBlock(int row, int column)
{
int element_number = (row % block_width) * block_width + (column % block_width);
int blockY = row / block_width;
int blockX = column / block_width;
int memory_shift = getFirstElementBlock(blockY, blockX);
return element_number + memory_shift;
}
void VTMatrix::zerofication()
{
for (int i = 0; i < matrix_capacity; i++)
data[i] = 0;
for (int i = 0; i < block_capacity; i++)
zero_block[i] = 0;
}
VTMatrix::VTMatrix(int matrix_width, int block_width)
{
this->block_width = block_width;
this->matrix_width = matrix_width;
width_matrix_in_blocks = matrix_width / block_width;
block_quantity = width_matrix_in_blocks * width_matrix_in_blocks;
block_capacity = block_width * block_width;
//
int zero_block_quantity = 0;
for (int x = 0; x < matrix_width / block_width; x++)
for (int y = 0; y < matrix_width / block_width; y++)
if (x < y)
zero_block_quantity++;
//
matrix_capacity = (block_quantity - zero_block_quantity) * block_capacity;
data = new int[matrix_capacity];
// 1
zero_block = new int[block_capacity];
zerofication();
}
VTMatrix::~VTMatrix()
{
delete[] data;
delete[] zero_block;
}
int VTMatrix::getValue(int row, int column)
{
if (column < row)
return 0;
return data[getElementBlock(row, column)];
}
void VTMatrix::setValue(int row, int column, int new_value)
{
if (column < row)
return;
data[getElementBlock(row, column)] = new_value;
}
int* VTMatrix::getBlock(int blockY, int blockX)
{
int* block;
if (blockX < blockY)
block = zero_block;
else
block = data + getFirstElementBlock(blockY, blockX);
return block;
}
void VTMatrix::readMatrixFromFile(std::string filePath)
{
zerofication();
std::fstream in(filePath);
std::string line;
int i = 0;
while (std::getline(in, line)) {
int j = 0;
std::stringstream linestream(line);
int value;
while (linestream >> value) {
setValue(i, j, value);
++j;
}
++i;
}
//if (in.is_open()) {
in.close();
//}
}
void VTMatrix::printMatrix() {
{
for (int i = 0;i < matrix_width;++i) {
for (int j = 0;j < matrix_width;++j)
std::cout << getValue(i, j) << " ";
std::cout << std::endl;
}
}
std::cout << std::endl;
}
void VTMatrix::generateMatrix(int min_val, int max_val)
{
std::mt19937 gen(time(0));
std::uniform_int_distribution<> uid(min_val, max_val);
for (int i = 0; i < matrix_width; i++)
{
for (int j = 0; j < matrix_width; j++)
{
if (i > j)
this->setValue(i, j, 0);
else
{
int rnd_num = uid(gen);
this->setValue(i, j, rnd_num);
}
}
}
} | true |
74e28ac82731ea48fec6aff223f9ef2b71f45e1d | C++ | hyzboy/ULRE | /inc/hgl/shadergen/MaterialDescriptorInfo.h | UTF-8 | 1,718 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#include<hgl/graph/VKShaderDescriptorSet.h>
#include<hgl/type/Map.h>
namespace hgl{namespace graph{
/**
* 材质描述符管理</p>
* 该类使用于SHADER生成前,用于统计编号set/binding
*/
class MaterialDescriptorInfo
{
uint descriptor_count;
ShaderDescriptorSetArray desc_set_array;
Map<AnsiString,AnsiString> struct_map;
Map<AnsiString,UBODescriptor *> ubo_map;
Map<AnsiString,SamplerDescriptor *> sampler_map;
public:
MaterialDescriptorInfo();
~MaterialDescriptorInfo()=default;
bool AddStruct(const AnsiString &name,const AnsiString &code)
{
struct_map.Add(name,code);
return(true);
}
bool GetStruct(const AnsiString &name,AnsiString &code) const
{
return(struct_map.Get(name,code));
}
bool hasStruct(const AnsiString &name) const
{
return(struct_map.KeyExist(name));
}
const UBODescriptor *AddUBO(VkShaderStageFlagBits ssb,DescriptorSetType set_type,UBODescriptor *sd);
const SamplerDescriptor *AddSampler(VkShaderStageFlagBits ssb,DescriptorSetType set_type,SamplerDescriptor *sd);
UBODescriptor *GetUBO(const AnsiString &name);
SamplerDescriptor *GetSampler(const AnsiString &name);
const DescriptorSetType GetSetType(const AnsiString &)const;
void Resort(); //排序产生set号与binding号
const uint GetCount()const
{
return descriptor_count;
}
const ShaderDescriptorSetArray &Get()const
{
return desc_set_array;
}
const bool hasSet(const DescriptorSetType &type)const
{
return desc_set_array[size_t(type)].count>0;
}
};//class MaterialDescriptorInfo
}}//namespace hgl::graph
| true |
9b56b3ac7ab7c010f7c43f2e1aebf4eae1229ec1 | C++ | delfilip/c- | /Auto komis (used car dealer programme)/ConsoleApplication1/ConsoleApplication1.cpp | UTF-8 | 5,658 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include<fstream>
#include <cstdlib>
#include <string>
#include <windows.h>
#include <stdio.h>
using namespace std;
class Auto
{
public:
string marka;
string model;
int rocznik;
string nazwiskoWlasciciela;
int cena;
void przeladuj(vector<Auto> &auta, fstream &plik)
{
Auto dane;
plik.open("Samochody.txt", ios::in);
if (plik.good() == false) cout << "Nie ma takiego pliku!" << endl;
string linia;
int nr_linii = 1;
while (getline(plik, linia))
{
if (nr_linii == 1) dane.marka = linia;
if (nr_linii == 2) dane.model = linia;
if (nr_linii == 3) dane.rocznik = atoi(linia.c_str());
if (nr_linii == 4) dane.nazwiskoWlasciciela = linia;
if (nr_linii == 5) {
dane.cena = atoi(linia.c_str());
nr_linii = 0;
auta.push_back(dane);
}
nr_linii++;
}
plik.close();
}
};
void dostepne(vector<Auto> &auta)
{
for (int i = 0; i < auta.size(); i++)
{
cout << auta[i].marka << " " << auta[i].model << " rocznik: " << auta[i].rocznik << ", cena: " << auta[i].cena << ", wlasciciel: P." << auta[i].nazwiskoWlasciciela << endl;
}
}
void dodajDoBazy(Auto &dane, fstream &plik)
{
plik.open("Samochody.txt", ios::app);
cout << "Podaj marke samochodu:" << endl;
cin >> dane.marka;
plik << dane.marka << endl;
cout << "Podaj model samochodu" << endl;
cin >> dane.model;
plik << dane.model << endl;
cout << "Podaj rocznik samochodu" << endl;
cin >> dane.rocznik;
plik << dane.rocznik << endl;
cout << "Podaj nazwisko wlasciciela" << endl;
cin >> dane.nazwiskoWlasciciela;
plik << dane.nazwiskoWlasciciela << endl;
cout << "Podaj cene samochodu" << endl;
cin >> dane.cena;
plik << dane.cena << endl;
plik.close();
}
void wyszukiwarka(vector<Auto> auta)
{
int gornaGranica, dolnaGranica, wiek;
string szukanaMarka, szukanyModel;
cout << "Podaj marke, ktorej poszukujesz:" << endl;
cin >> szukanaMarka;
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << endl;
cout << "Podaj model" << endl;
cin >> szukanyModel;
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << endl;
cout << "Ilu-letni maksymalnie moze byc samochod?" << endl;
cin >> wiek;
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << endl;
cout << "Podaj gorna granice ceny" << endl;
cin >> gornaGranica;
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << endl;
cout << "Szukam";
Sleep(500);
cout << ".";
Sleep(500);
cout << ".";
Sleep(500);
cout << "." << endl;
cout << "O to znalezione samochody:" << endl;
for (int i = 0; i < auta.size(); i++)
{
if ((auta[i].marka == szukanaMarka) && (auta[i].model == szukanyModel) && (auta[i].cena < gornaGranica)
&& (auta[i].rocznik >= 2019-wiek))
{
cout << auta[i].marka << " " << auta[i].model << ", cena " << auta[i].cena << " rocznik " << auta[i].rocznik << endl;
}
}
}
void usunAuto(vector<Auto> &auta, fstream &nowy)
{
string markaDoUsuniecia;
string takLubNie;
int licznik = 0;
cout << "Jaki samochod chcesz usunac?" << endl;
cout << "Podaj marke samochodu" << endl;
cin >> markaDoUsuniecia;
for (int i = 0; i < auta.size(); i++)
{
if (markaDoUsuniecia == auta[i].marka)
{
cout << "To ten samochod?" << endl;
cout << "Model:" << auta[i].model << endl;
cout << "Rocznik:" << auta[i].rocznik << endl;
cout << "Nazwisko wlasciciela:" << auta[i].nazwiskoWlasciciela << endl;
cout << "Cena:" << auta[i].cena << endl;
cin >> takLubNie;
if (takLubNie == "tak")
{
auta.erase(auta.begin() + i);
cout << "Auto usuniete." << endl;
}
}
}
remove("Samochody.txt");
nowy.open("Samochody.txt", ios::app);
for (int i = 0; i < auta.size(); i++)
{
nowy << auta[i].marka << endl;
nowy << auta[i].model << endl;
nowy << auta[i].rocznik << endl;
nowy << auta[i].nazwiskoWlasciciela << endl;
nowy << auta[i].cena << endl;
}
nowy.close();
}
void wiecejInfo(vector<Auto> auta)
{
string podanaMarka;
cout << "Podaj marke samochodu, ktory cie interesuje:" << endl;
cin >> podanaMarka;
cout << "Podaj model samochodu, ktory cie interesuje:" << endl;
}
int main()
{
Auto dane;
int wybor;
vector<Auto> auta;
fstream plik;
dane.przeladuj(auta, plik);
cout << "AUTO-KOMIS" << endl;
cout << "1. Wyswietl wszystkie dostepne auta" << endl;
cout << "2. Szukaj w bazie..." << endl;
cout << "3. Dodaj dane do bazy" << endl;
cout << "4. Usun auto z bazy" << endl;
cout << "5. Wyjdz z programu" << endl;
cout << "6. Wyczysc ekran" << endl;
do {
cin >> wybor;
switch (wybor)
{
case 1:
{
cout << "Obecna ilosc aut:" << auta.size() << endl;
dostepne(auta);
break;
}
case 2:
{
wyszukiwarka(auta);
break;
}
case 3:
{
auta.clear();
dodajDoBazy(dane, plik);
dane.przeladuj(auta, plik);
break;
}
case 4:
{
fstream nowy;
usunAuto(auta, nowy);
break;
}
case 5:
{
exit(0);
break;
}
case 6:
{
system("CLS");
cout << "AUTO-KOMIS" << endl;
cout << "1. Wyswietl wszystkie dostepne auta" << endl;
cout << "2. Szukaj w bazie..." << endl;
cout << "3. Dodaj dane do bazy" << endl;
cout << "4. Usun auto z bazy" << endl;
cout << "5. Wyjdz z programu" << endl;
cout << "6. Wyczysc ekran" << endl;
break;
}
}
} while (wybor != 5);
return 0;
}
| true |
46acd25fdf84189f073201bc0f5e05ace6b5fb2e | C++ | shadowoflove/Project2019 | /Game/Classes/ammo.cpp | GB18030 | 938 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "ammo.h"
void ammo::initial(std::string fileName,Vec2 currentPosition,int damge,int ammSpeed)
{
this->setPosition(currentPosition);
damage = damge; ammoSpeed = ammSpeed;
Frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(fileName);
return ;
}
ammo::ammo()
{
}
void ammo::changeTargetPosition(Vec2 targetPosition)
{
destination = targetPosition;
return;
}
void ammo::fresh() //ammoġupdateһLayerupdateӦõӽupdate
{
velocity = destination-getPosition();
this->setRotation(CC_RADIANS_TO_DEGREES(velocity.getAngle()));
velocity.normalize(); velocity *= ammoSpeed;
this->runAction(MoveTo::create(1 / velocity.length(), velocity + getPosition()));
/*
*Ҫͳһʱʾʽ
*ȷĸ
*Ӣ۹
*unitdataʼ
*ȫͳһٶȣ
*/
}
| true |
25daf6630f3b8e4d25aae2769fbae98c0df15d7b | C++ | samlovestech/GaussainMLE | /GaussainModel_MLE_NLOPT.cpp | UTF-8 | 1,920 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
#include <nlopt.hpp>
#include <cmath>
#include <fstream>
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
std::vector<double> *d = reinterpret_cast<std::vector<double>*>(my_func_data);
double mu = x[0];
double var = x[1];
int data_size = d->size();
if(grad) {
grad[0] = 0.0;
grad[1] = - data_size/(2.0*var);
for(int i = 0; i < data_size; i++) {
grad[0] += ((*d)[i] - mu)/var;
grad[1] += ((*d)[i] - mu)*((*d)[i] - mu)/(2.0*var*var);
}
}
//double func = data_size/sqrt(2*3.1415926*var);
double func = -data_size*log(2*3.1415926*var)/2.0;
for(int i = 0; i < data_size; i++) {
func -= (((*d)[i] - mu)*((*d)[i] - mu))/(2*var);
}
printf("size = %d\n", data_size);
// printf("mu = %f, var = %f\n", mu, var);
// printf("grad[0] = %f, grad[1] = %f\n", grad[0], grad[1]);
// printf("\n");
return func;
}
int main() {
std::vector<double> data;
// Read data from csv file....
// std::ifstream stockfile("hq_pure.csv");
std::ifstream stockfile("sam.csv");
std::string value;
if(stockfile.good()) {
while(getline(stockfile, value, '\n')) {
data.push_back(std::stod(value));
}
}
// use nlopt package to optimize the data...
nlopt_opt opt;
// NLOPT_LD_LBFGS Algorithms supprt unconstrained problems
opt = nlopt_create(NLOPT_LD_LBFGS, 2); /* algorithm and dimensionality */
nlopt_set_max_objective(opt, myfunc, &data);
nlopt_set_xtol_rel (opt, 1.0e-15);
double x[2] = {0.5,2}; /* some initial guess */
double minf; /* the minimum objective value, upon return */
nlopt_optimize(opt, x, &minf);
std::cout << "found maximum value at f(" << x[0] << ", " << x[1] << ") = " << minf << "\n" << std::endl;
nlopt_destroy(opt);
return 0;
}
| true |
147457a0f0c25e97a364032dcf81c012f557b16c | C++ | SleepyMan212/581test2 | /p3w3/tree_Diameter/tree_Diameter.cpp | UTF-8 | 1,150 | 2.859375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
queue<int> q;
int degree[100007];
int level[100007];
std::vector<int> G[100007];
int main(int argc, char const *argv[]) {
int nCase;
int num;
cin>>nCase;
while (nCase--) {
memset(degree,0,sizeof(degree));
memset(level,0,sizeof(level));
cin>>num;
for(int i=0; i<num; i++) G[i].clear();
int a,b;
for(int i=0; i<num-1; i++){
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
degree[a]++;
degree[b]++;
}
for(int i=0; i<num; i++){
if(degree[i]==1)
q.push(i);
}
int maxlevel=-1e9;
while (!q.empty()) {
int v = q.front(); q.pop();
for(int i=0; i<G[v].size(); i++ ){
int t=G[v][i];
degree[t]--;
if(degree[t]==1){
q.push(t);
level[t]=level[v]+1;
maxlevel=max(maxlevel,level[t]);
}
}
}
int c=0;
for(int i=0; i<num; i++){
if(level[i]==maxlevel) c++;
}
// diameter(G)=level(G)*2+|c|-1
cout<<maxlevel*2+c-1<<endl;
}
return 0;
}
/*
2
8
0 1
0 2
0 3
7 0
1 4
1 5
3 6
4
0 1
0 2
2 3
output
4
3
*/
| true |
957394bf5a9e0643c516e672e4b30ce09715b267 | C++ | weil0819/LeetCode | /Top Interview Questions/Binary_Tree_Level_Order_Traversal.cpp | UTF-8 | 2,434 | 3.9375 | 4 | [] | no_license | /*
Binary Tree Level Order Traversal
https://leetcode.com/explore/featured/card/top-interview-questions-easy/94/trees/628/
@date: May 11, 2020
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// Iterative method -- BFS -- queue<TreeNode*>
/*
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> helper;
helper.push(root);
while(!helper.empty()) {
int N = helper.size();
vector<int> tmp;
for(int i = 0; i < N; i++) {
TreeNode* node = helper.front();
tmp.push_back(node->val);
helper.pop();
if(node->left) helper.push(node->left);
if(node->right) helper.push(node->right);
}
res.push_back(tmp);
}
return res;
}
*/
// Recursive method -- DFS -- pre-order traversal
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL) return res;
DFSUtil(res, root, 0);
return res;
}
private:
void DFSUtil(vector<vector<int> >& res, TreeNode* node, int depth) {
if(node == NULL) return ;
if(depth >= res.size()) res.push_back(vector<int>());
res[depth].push_back(node->val);
DFSUtil(res, node->left, depth+1);
DFSUtil(res, node->right, depth+1);
}
}; | true |
f131ed33682730bfb83e05a0286b42df57a9b162 | C++ | pytorch/glow | /include/glow/PassManager/Pipeline.h | UTF-8 | 4,635 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GLOW_PASSMANAGER_PIPELINE_H
#define GLOW_PASSMANAGER_PIPELINE_H
#include "PassConfig.h"
#include "glow/Optimizer/GraphOptimizer/CompilationContext.h"
#include "glow/Support/Support.h"
#include <iterator>
namespace glow {
/// Base class for all pass pipelines providing some common functionality.
class PassPipelineBase {
protected:
/// \returns pass config at index \p i.
virtual const PassConfigBase &elementAt(size_t i) const = 0;
public:
/// Constructor.
PassPipelineBase() = default;
/// Destructor.
virtual ~PassPipelineBase() = default;
/// Dump a textual representation of the pipeline to \p os.
virtual void dump(llvm::raw_ostream &os = llvm::outs()) const;
/// \returns size of pipeline.
virtual size_t size() const = 0;
};
/// Implementation of a pipeline for executing a series of passes. Each pass
/// should be of type \p PASS or a type derived from it.
template <typename PASS>
class PassPipeline
: public PassPipelineBase,
private llvm::SmallVector<typename PASS::IRPassConfigTy, 16> {
public:
using IRPassConfigTy = typename PASS::IRPassConfigTy;
using PassIDTy = typename IRPassConfigTy::PassIDTy;
using Base = llvm::SmallVector<IRPassConfigTy, 16>;
using iterator = typename Base::iterator;
using const_iterator = typename Base::const_iterator;
private:
/// Removes the first instance of a pass with ID \p passID. \returns whether
/// an instance of the pass was successfully found and removed.
bool removeFirstInstanceOfPass(PassIDTy passID) {
for (auto it = begin(); it != end(); it++) {
if (static_cast<PassIDTy>(it->getID()) == passID) {
this->erase(it);
return true;
}
}
return false;
}
const PassConfigBase &elementAt(size_t i) const override { return at(i); }
public:
/// Constructor.
PassPipeline() = default;
/// Constructor for a PassPipeline from an initializer_list \p configs.
PassPipeline(std::initializer_list<IRPassConfigTy> configs) {
pushBack(configs);
}
/// \returns size of pipeline.
size_t size() const override { return Base::size(); }
/// Forward iterator creation methods.
///@{
iterator begin() { return Base::begin(); }
const_iterator begin() const { return Base::begin(); }
iterator end() { return begin() + size(); }
const_iterator end() const { return begin() + size(); }
/// @}
/// Helper to get the IRPassConfig at index \p i in the pipeline.
const IRPassConfigTy &at(size_t i) const {
const PassConfigBase &config = begin()[i];
return *static_cast<const IRPassConfigTy *>(&config);
}
/// Push a new \p IRPC to the end of the pipeline.
void pushBack(const IRPassConfigTy &IRPC) { Base::push_back(IRPC); }
/// Push \p configs to the end of the pipeline.
void pushBack(const std::initializer_list<IRPassConfigTy> &configs) {
for (auto &config : configs) {
pushBack(config);
}
}
/// Push \p configs to the end of the pipeline.
void pushBack(llvm::ArrayRef<IRPassConfigTy> configs) {
for (auto &config : configs) {
pushBack(config);
}
}
/// Push a new \p IRPC to the start of the pipeline.
void pushFront(const IRPassConfigTy &IRPC) { Base::insert(begin(), IRPC); }
/// Removes all instances of a pass with ID \p passID.
void removeAllInstancesOfPass(PassIDTy passID) {
while (removeFirstInstanceOfPass(passID)) {
}
}
/// Initialize the pipeline from a file with a name \p pipelineDefFilename.
virtual void initFromFile(llvm::StringRef pipelineDefFilename);
/// Dump pipeline definition into a file with a name \p pipelineDefFilename.
virtual void dumpToFile(llvm::StringRef pipelineDefFilename);
bool equals(const PassPipeline &other) const {
if (size() != other.size()) {
return false;
}
for (unsigned idx = 0, e = size(); idx < e; ++idx) {
if (!at(idx).equals(other.at(idx))) {
return false;
}
}
return true;
}
};
} // namespace glow
#endif // GLOW_PASSMANAGER_PIPELINE_H
| true |
9584360dbc994a9ff02c68be4035b7fc36e76487 | C++ | asa-dillahunty/CS201-Data-Structures-Library | /Phase1/me.cpp | UTF-8 | 5,025 | 3.25 | 3 | [] | no_license | /**
* @Author Asa Dillahunty
*
* CS201 Programming Project
*
* This program is written to implement
* learned algorithms in CS201
*
* CDA stands for Circular Dynamic Array
*/
#include <iostream>
#include <string>
#include <math.h>
#include <chrono>
#include "CircularDynamicArray.cpp"
bool testQuickSort() {
std::cout << "Starting Quick Sort Test" << std::endl;
CircularDynamicArray<int> list;
for (int j=1;j<16;j++) {
for (int k=10;k<1000000;k=k*10) {
for (int h=0;h<k;h+=2) {
list.addEnd(h);
list.addFront(h+1);
}
list.randomize();
list.quickSort();
for (int i=0;i<k;i++) {
if (i!=list[i]) return false;
}
list.clear();
}
}
std::cout << "Finished Quick Sort Test With No Errors" << std::endl;
return true;
}
bool testStableSort() {
std::cout << "Starting Stable Sort Test" << std::endl;
CircularDynamicArray<int> list;
for (int j=1;j<16;j++) {
for (int k=10;k<1000000;k=k*10) {
for (int h=0;h<k;h+=2) {
list.addEnd(h);
list.addFront(h+1);
}
list.randomize();
list.stableSort();
for (int i=0;i<k;i++) {
if (i!=list[i]) return false;
}
list.clear();
}
}
std::cout << "Finished Stable Sort Test With No Errors" << std::endl;
return true;
}
bool testRadixSort() {
std::cout << "Starting Radix Sort Test" << std::endl;
CircularDynamicArray<int> list;
for (int j=1;j<16;j++) {
for (int k=10;k<1000000;k=k*10) {
for (int h=0;h<k;h+=2) {
list.addEnd(h);
list.addFront(h+1);
}
list.randomize();
list.radixSort(j);
for (int i=0;i<k;i++) {
if (i!=list[i]) return false;
}
list.clear();
}
}
std::cout << "Finished Radix Sort Test With No Errors" << std::endl;
return true;
}
bool testWCSelect() {
std::cout << "Starting WCSelect Test" << std::endl;
CircularDynamicArray<int> list;
int total=500;
for (int j=0;j<total;j++) list.addEnd(j);
for (int j=1;j<total+1;j++) {
if (list.WCSelect(j) != j-1) {
return false;
}
}
for (int j=1;j<total+1;j++) {
list.randomize();
if (list.WCSelect(j) != j-1) {
return false;
}
}
std::cout << "Fished WCSelect Test With No Errors" << std::endl;
return true;
}
void timeWCSelect() {
CircularDynamicArray<int> list;
auto total = std::chrono::high_resolution_clock::now();
for (int numElements=449;numElements<450;numElements*=2) {
for (int h=0;h<numElements;h++) list.addEnd(h);
for (int j=0;j<numElements;j++) list.addFront(j);
for (int k=0;k<numElements;k++) list.addEnd(k);
for (int i=0;i<numElements;i+=2) {
list.addEnd(i);
list.addFront(i+1);
}
//This should be *4
using namespace std::chrono;
list.randomize();
auto start = high_resolution_clock::now();
for (int i=1;i<=list.length();i++)
if (list.WCSelect(i) != (i-1)/4) std::cout << "FUCK";
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
std::cout << numElements << "," << duration.count() << std::endl;
}
}
void timeSorts() {
CircularDynamicArray<int> list;
for (int numElements=1;numElements<50;numElements*=2) {
for (int h=0;h<numElements;h++) list.addEnd(h);
for (int j=0;j<numElements;j++) list.addFront(j);
for (int k=0;k<numElements;k++) list.addEnd(k);
for (int i=0;i<numElements;i+=2) {
list.addEnd(i);
list.addFront(i+1);
}
//This should be *4
using namespace std::chrono;
list.randomize();
auto start = high_resolution_clock::now();
list.quickSort();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
std::cout << numElements << "," << duration.count() << std::endl;
}
}
int main(int argc, char const *argv[]) {
std::cout << "Hello World!\n" << std::endl;
timeWCSelect();
if (!testWCSelect()) {
std::cout << "WCSelect Failed" << std::endl;
}
if (!testQuickSort()) {
std::cout << "Quick Sort Failed" << std::endl;
}
if (!testStableSort()) {
std::cout << "Stable Sort Failed" << std::endl;
}
if (!testRadixSort()) {
std::cout << "Radix Sort Failed" << std::endl;
}
return 0;
}
| true |
eb5a4c062f133361c3de4d1471ae4af6713c85c9 | C++ | hophacker/algorithm_coding | /test/a.cpp | UTF-8 | 357 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<priority_queue>
using namespace std;
//k < n/(log n)
int select_k_th(vector<int> arr, int k){
priority_queue<int> pq;
for (int i = 0; i < arr.size(); i++){
pq.push(arr[i]);
}
int ret;
for (int i = 0; i < k; i++){
ret = pq.top();
pq.pop();
}
return ret;
}
| true |
5a115050254072cc284fa82d1c9ca26dd6f0ee42 | C++ | umaumax/mtrace | /mtrace.cpp | UTF-8 | 10,086 | 2.515625 | 3 | [] | no_license | #include <dlfcn.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <cassert>
#include <chrono>
#include <csignal>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
namespace {
void exit_handler(int sig) { std::exit(128 + sig); }
struct ExitBySignal {
ExitBySignal() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = exit_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, nullptr);
}
} exit_by_signal;
} // namespace
#if __APPLE__
pid_t gettid() {
uint64_t tid64 = 0;
pthread_threadid_np(nullptr, &tid64);
return static_cast<pid_t>(tid64);
}
#elif __linux__
pid_t gettid() { return syscall(SYS_gettid); }
#else
#error "Non supported os"
#endif
uint64_t exp2_roundup(uint64_t x) {
if (x == 0) {
return 0;
}
int v = 1;
uint64_t y = x;
while (y >>= 1) {
v <<= 1;
}
if (x > v) {
v <<= 1;
}
return v;
}
class Counter {
public:
Counter() {}
void Add(uint64_t value) {
std::string key =
std::to_string((double)(exp2_roundup(value / 1000 / 1000)) / 1000.0 /
1000.0 * 1000.0 * 1000.0);
const int max_key_length = 16;
if (key.length() < max_key_length) {
key = std::string(max_key_length - key.length(), ' ') + key;
}
data_[key]++;
}
std::map<std::string, int> data_;
};
thread_local pid_t current_tid = gettid();
class Logger {
public:
Logger() {
ofs_.open("./mtrace.out." + std::to_string(current_tid));
if (!ofs_) {
std::cerr << "Failed to open file" << std::endl;
std::exit(1);
}
}
~Logger() {
if (ofs_) {
ofs_.close();
}
}
void Write(const std::string &text) {
ofs_ << current_tid << " " << text << std::endl;
}
private:
std::ofstream ofs_;
};
thread_local Logger logger;
class CounterManager {
public:
CounterManager(std::string name) : name_(name) {}
~CounterManager() {
std::cout << "name:" << name_ << std::endl;
std::cout << "tid:" << current_tid << std::endl;
std::cout << "# elapsed timep[ms]" << std::endl;
for (auto &v : counter_map_) {
const std::string &address = v.first;
Counter &counter = v.second;
for (auto &v : counter.data_) {
const std::string &value = v.first;
int count = v.second;
std::cout << address << " : " << value << ", " << count << std::endl;
}
}
}
Counter &Get(std::string key) {
if (counter_map_.find(key) == counter_map_.end()) {
counter_map_.insert(std::make_pair(key, Counter()));
}
return counter_map_[key];
}
std::string name_;
std::map<std::string, Counter> counter_map_;
};
thread_local CounterManager mutex_counter_manager("mutex");
thread_local CounterManager cond_counter_manager("cond");
#define HOOK(ret_type, func_name, ...) \
ret_type func_name(__VA_ARGS__); \
namespace { \
using func_name##_type = decltype(&func_name); \
func_name##_type orig_##func_name = []() { \
auto f = (func_name##_type)dlsym(RTLD_NEXT, #func_name); \
assert(f && "failed dlsym " #func_name); \
return f; \
}(); \
} \
ret_type func_name(__VA_ARGS__)
#if __APPLE__
#define FUNC_THROW_DECL
#elif __linux__
#define FUNC_THROW_DECL throw()
#else
#error "Non supported os"
#endif
extern "C" {
HOOK(int, pthread_mutex_lock, pthread_mutex_t *mutex) FUNC_THROW_DECL {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_mutex_lock(mutex);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_mutex_lock(mutex=" << mutex << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
std::string key = std::to_string((uintptr_t)mutex);
uint64_t elapsed_time =
(uint64_t)(hooked_func_elapsed * 1000.0 * 1000.0 * 1000.0);
mutex_counter_manager.Get(key).Add(elapsed_time);
return ret;
}
HOOK(int, pthread_mutex_unlock, pthread_mutex_t *mutex) FUNC_THROW_DECL {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_mutex_unlock(mutex);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_mutex_unlock(mutex=" << mutex << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
return ret;
}
HOOK(int, pthread_cond_signal, pthread_cond_t *cond) FUNC_THROW_DECL {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_cond_signal(cond);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_cond_signal(cond=" << cond << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
return ret;
}
HOOK(int, pthread_cond_broadcast, pthread_cond_t *cond) FUNC_THROW_DECL {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_cond_broadcast(cond);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_cond_broadcast(cond=" << cond << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
return ret;
}
HOOK(int, pthread_cond_wait, pthread_cond_t *cond, pthread_mutex_t *mutex) {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_cond_wait(cond, mutex);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_cond_wait(cond=" << cond << ", mutex=" << mutex
<< ") = " << ret << " <" << hooked_func_elapsed << ">";
logger.Write(ss.str());
std::string key = std::to_string((uintptr_t)mutex);
uint64_t elapsed_time =
(uint64_t)(hooked_func_elapsed * 1000.0 * 1000.0 * 1000.0);
cond_counter_manager.Get(key).Add(elapsed_time);
return ret;
}
HOOK(int, pthread_cond_timedwait, pthread_cond_t *cond, pthread_mutex_t *mutex,
const struct timespec *abstime) {
std::chrono::system_clock::time_point hooked_func_start =
std::chrono::system_clock::now();
int ret = orig_pthread_cond_timedwait(cond, mutex, abstime);
double hooked_func_elapsed =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - hooked_func_start)
.count() /
1000.0 / 1000.0 / 1000.0;
double timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
hooked_func_start.time_since_epoch())
.count() /
1000.0 / 1000.0;
if (abstime != nullptr) {
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_cond_timedwait(cond=" << cond << ", mutex=" << mutex
<< ", abstime.tv_sec=" << (int)(abstime->tv_sec)
<< ", abstime.tv_nsec=" << abstime->tv_nsec << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
} else {
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << timestamp << " "
<< "pthread_cond_timedwait(cond=" << cond << ", mutex=" << mutex
<< ", abstime=" << abstime << ") = " << ret << " <"
<< hooked_func_elapsed << ">";
logger.Write(ss.str());
}
std::string key = std::to_string((uintptr_t)mutex);
uint64_t elapsed_time =
(uint64_t)(hooked_func_elapsed * 1000.0 * 1000.0 * 1000.0);
cond_counter_manager.Get(key).Add(elapsed_time);
return ret;
}
}
| true |
39a0ff14ae070ba64a543dce383b58d255e75e51 | C++ | shivendrakrjha/Algorithms-with-cpp | /dijkstra.cpp | UTF-8 | 3,810 | 3.125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class queue
{
public:
int max_size;
int *data;
int *key;
int cur_len;
int temp;
queue(int max_size)
{
data = new int[max_size];
key = new int[max_size];
cur_len = 0;
}
void swap(int pos1, int pos2)
{
temp = data[pos1];
data[pos1] = data[pos2];
data[pos2] = temp;
}
void min_heapify(int i)
{
int l = i*2 +1;
int r = i*2 +2;
int smallest = i;
if(l < cur_len and key[data[l]] < key[data[i]])
{
smallest = l;
}
if (r < cur_len and key[data[r]] < key[data[smallest]])
{
smallest = r;
}
swap(i, smallest);
if(smallest != i)
{
min_heapify(smallest);
}
}
int parant(int i)
{
return int((i-1)/2);
}
void decrease_key(int new_key, int pos)
{
key[data[pos]] = new_key;
while(key[data[parant(pos)]] > key[data[pos]] and pos > 0)
{
swap(parant(pos), pos);
pos = parant(pos);
}
}
void insert(int key1, int data1)
{
data[cur_len] = data1;
key[data[cur_len]] = key1;
cur_len ++;
decrease_key(key1, cur_len-1);
}
int extract_min()
{
int drop = data[0];
swap(0, cur_len-1);
cur_len--;
min_heapify(0);
return drop;
}
queue(int ln, int * dta, int * ky)
{
cur_len = max_size = ln;
data = dta;
key = ky;
for (int i = int(ln/2) - 1; i >=0 ; i--)
{
min_heapify(i);
}
}
};
class graph
{
public:
int v;
int *V;
int **adj;
int **W;
int *dis;
int *par;
int *order;
graph(int vv)
{
v=vv;
V = new int[v];
for (int i = 0; i < v; i++)
{
V[i] = i;
}
adj = new int*[v];
W = new int *[v];
dis = new int[v];
par = new int[v];
order = new int [v];
}
void initialize(int root)
{
for (int i = 0; i < v; i++)
{
dis[i] = 1000;
par[i] = -1;
}
dis[root] = 0;
}
void relax(int u, int u_adj_ind)
{
int v = adj[u][u_adj_ind];
int w_u_v = W[u][u_adj_ind];
if (dis[u] + w_u_v < dis[v])
{
dis[v] = dis[u] + w_u_v;
par[v] = u;
}
}
void get_adj()
{
for (int i = 0; i < v; i++)
{
cin>>order[i]; //get noutorder for particular vertex
adj[i] = new int[order[i]]; //deciding adj array of each vertex acc. to outorder
W[i] = new int [order[i]]; //deciding weight array of each edje of v and its adjacent
for (int j = 0; j < order[i]; j++)
{
cin>>adj[i][j] >> W[i][j]; //getting actual name of ajdacent and the weight btw them
}
}
}
};
void dijkstra(graph *G, int root)
{
G->initialize(root);
queue *Q = new queue(G->v, G->V, G->dis);
queue *S = new queue(G->v);
int u;
int count = 0;
while (Q->cur_len != 0)
{
u = G->V[0];
for (int u_adj_ind = 0; u_adj_ind < G->order[u]; u_adj_ind++)
{
G->relax(u, u_adj_ind);
}
Q->extract_min();
}
}
int main()
{
graph *G = new graph(5);
G->get_adj();
dijkstra(G, 0);
for (int i = 0; i < G->v; i++)
{
cout<<i<<" is child of "<<G->par[i]<<endl;
}
return 0;
}
| true |