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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ea0efd8042ba0b0ab2daf83984700b10b2386fb7 | C++ | dapperfu/bot_01 | /HAL/HAL.ino | UTF-8 | 518 | 2.953125 | 3 | [
"BSD-3-Clause"
] | permissive |
int analogValue_3 = 0;
void setup() {
Serial.begin(115200);
}
void loop() {
// Analog Input 3
Serial.print("A3=");
Serial.print(analogValue_3);
delay(250);
Serial.print(",");
// Analog Input 4
analogValue_4 = analogRead(4);
Serial.print("A4=");
Serial.print(analogValue_4);
Serial.print(",");
// Analog Input 5
analogValue_5 = analogRead(5);
Serial.print("A5=");
Serial.print(analogValue_5);
Serial.print(",");
Serial.println("");
delay(250);
}
| true |
7c7667382ba2def64d525e57158fa96304ddaf40 | C++ | Salanyel/PlateFormer | /Tile.cpp | UTF-8 | 423 | 3 | 3 | [] | no_license | #include "Tile.h"
Tile::Tile(TILE_TYPE type) : m_type(type)
{
}
Tile::~Tile()
{
}
TILE_TYPE Tile::getType()
{
return m_type;
}
void Tile::setType(TILE_TYPE type)
{
m_type = type;
}
bool Tile::isSolid()
{
switch (m_type)
{
case T_BLOCK:
return true;
case T_MAPWALL:
return true;
default:
return false;
}
}
bool Tile::isNextLevel()
{
if (m_type == T_NEXTLEVEL)
return true;
else
return false;
}
| true |
646ba19a22116ba3b9241e7916a1876ee57e6e3f | C++ | MajorasCoffee/New-Projects | /Project39/Project39/Source.cpp | UTF-8 | 256 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class animal {
public:
void emotions(string emotion) {
cout << emotion << endl;
}
};
class cat: public animal{};
int main() {
cat cat;
cat.emotions("Grrrr");
system("PAUSE");
return 0;
} | true |
265d4fc3350c335d689c4c0ac4be1900d26e9ad5 | C++ | mkalafut/matt-statics | /src/main.cpp | UTF-8 | 323 | 2.90625 | 3 | [] | no_license |
#include "Person.cpp"
int main()
{
// Initialize both Person classes.
Person person1 = Person("Jake the Dog", "512 Treehouse Lane");
Person person2 = Person("Mike Wazowski", "22 You-Got-Your-Life-Back-Lane");
// Call the display functions of both classes.
person1.display();
person2.display();
return 0;
}
| true |
4ab2cc2220e7be1ddf8ca12197bd94fdbd72c28a | C++ | fredmorcos/attic | /Projects/Autocal/attic/autocal-20100821/src/schedule.cpp | UTF-8 | 1,161 | 2.703125 | 3 | [
"Unlicense"
] | permissive | #include "schedule.h"
#include <limits>
Schedule::Schedule(QObject *parent) :
QObject(parent), _fitness(std::numeric_limits<int>::min())
{
}
void Schedule::_putUnfixedTasks()
{
_unfixedTasks.clear();
for (int i = 0; i < _tasks.length(); i++)
if (!(_tasks.at(i)->fixed()))
_unfixedTasks.append(_tasks.at(i));
}
QList<Task *> Schedule::unfixedTaskList()
{
return _unfixedTasks;
}
QList<Task *> Schedule::taskList()
{
return _tasks;
}
void Schedule::addTask(Task *task)
{
_tasks.append(task);
task->setParent(this);
connect(task, SIGNAL(somethingChanged()), this, SLOT(someTaskChanged()));
sortSchedule();
if (!(task->fixed()))
_putUnfixedTasks();
emit tasksChanged();
}
void Schedule::deleteTask(int index)
{
Task *t = _tasks.takeAt(index);
t->deleteLater();
sortSchedule();
if (!(t->fixed()))
_putUnfixedTasks();
emit tasksChanged();
}
void Schedule::someTaskChanged()
{
sortSchedule();
_putUnfixedTasks();
emit tasksChanged();
}
void Schedule::sortSchedule()
{
qSort(_tasks);
}
int Schedule::fitness()
{
return _fitness;
}
void Schedule::setFitness(int newValue)
{
_fitness = newValue;
emit fitnessChanged(newValue);
}
| true |
52343c94199782b870345fc6407462ee4bac3c4e | C++ | aljozu/OOP2_FP | /particles_container.h | UTF-8 | 1,127 | 2.953125 | 3 | [] | no_license | //
// Created by lojaz on 23/11/2020.
//
#ifndef PLSDIOSITO_PARTICLES_CONTAINER_H
#define PLSDIOSITO_PARTICLES_CONTAINER_H
#include "Particle.h"
class particles_container : public sf::Drawable {
std::vector<std::shared_ptr<Particle>> particle_container;
bool sick;
//std::vector<Particle> particle_container;
virtual void draw(sf::RenderTarget &renderTarget, sf::RenderStates renderStates) const;
public:
//default constructor
particles_container();
//constructor with a number of given particles
explicit particles_container(size_t size, bool sick);
//default destructor
~particles_container() override;
//returns the container
std::vector<std::shared_ptr<Particle>> getContainer();
//another function to draw
void drawContainer(sf::RenderWindow &window);
//size of the container
size_t size();
//ovearloading the [] operator
std::shared_ptr<Particle> & operator[](int);
//overloading the assignment operator
particles_container & operator=(const std::vector<std::shared_ptr<Particle>>&);
};
#endif //PLSDIOSITO_PARTICLES_CONTAINER_H
| true |
572d70b0bcfaf335ffe6260e33a8850eb0abc2ff | C++ | onartz/AmbifluxRobot | /AmbifluxRobotARNL/AmbifluxRobot/MessagePool.cpp | UTF-8 | 874 | 2.71875 | 3 | [] | no_license | #include "MessagePool.h"
Pool::Pool(size_t max_size = 10, size_t spin_time = 50)
: max_size(max_size), spin_time(spin_time)
{}
Pool::~Pool()
{
myMutex.lock();
//mtx.lock();
while (data.size()) data.pop();
myMutex.unlock();
//mtx.unlock();
}
size_t Pool::size() const
{
myMutex.lock();
size_t result = data.size();
myMutex.unlock();
return result;
}
void Pool::push(T item)
{
myMutex.lock();
while (data.size() >= max_size)
{
myMutex.unlock();
ArUtil::sleep(spin_time);
myMutex.lock();
}
data.push(item);
myMutex.unlock();
}
T Pool::pop()
{
myMutex.lock();
while (data.size() <= 0)
{
myMutex.unlock();
ArUtil::sleep(spin_time);
myMutex.lock();
}
T item = data.front(); data.pop();
myMutex.unlock();
return item;
}
} | true |
72e174bdbfba15237993c5f44494845c08f2601c | C++ | ian-wigley/Xenon | /Xenon-Original_C++_Code/demo3/demo3.cpp | UTF-8 | 3,819 | 2.984375 | 3 | [] | no_license | //-------------------------------------------------------------
//
// Program: Demo 3
//
// Author: John M Phillips
//
// Started: 20/08/00
//
// Remarks: This is a simple program using the GameSystem library
// which lets you view a 2 layer scrolling tile map.
//
//-------------------------------------------------------------
#include "demo3.h"
//-------------------------------------------------------------
// Constants
const char *GRAPHICS_DIRECTORY = "..\\..\\Demo3\\Graphics\\";
const char *LEVELS_DIRECTORY = "..\\..\\Demo3\\Levels\\";
const char *LEVEL_NAME = "test.fmp";
const int PLAYER_START_OFFSET = 64;
//-------------------------------------------------------------
// Create an instance of the application class
// GameSystem will run this automatically
CDemo3 myApp("Demo 3");
//-------------------------------------------------------------
// Initialize the demo
//
// Return: true if successful
bool CDemo3::initialize()
{
// initialize the GameSystem framework
if (!gsCApplication::initialize())
return false;
// create the keyboard handler and screen window
if (!m_keyboard.create())
return false;
if (!m_screen.createWindowed(getWindow()))
return false;
// load level
if (!createLevel())
return false;
m_stars.initialize(16);
return true;
}
//-------------------------------------------------------------
// Main loop : draws level to the screen and test the keyboard
//
// Return: true if successful
// false if error or ESCAPE pressed
bool CDemo3::mainloop()
{
// clear the screen to black
m_screen.clear(gsCColour(gsBLACK));
// draw starfield
m_stars.draw();
// draw our level
drawLevel();
// flip the screen to view
m_screen.flip();
// move level for next frame
moveLevel();
// test for ESCAPE pressed and exit demo if so
gsKeyCode key = m_keyboard.getKey();
if (key == gsKEY_ESCAPE)
return false;
return true;
}
//-------------------------------------------------------------
// Shutdown demo
bool CDemo3::shutdown()
{
destroyLevel();
// destroy the screen and keyboard handler
m_screen.destroy();
m_keyboard.destroy();
// exit
return gsCApplication::shutdown();
}
//-------------------------------------------------------------
// Load our level
//
// Return: true if success
// false if error
bool CDemo3::createLevel()
{
if (!m_level.load(LEVEL_NAME,LEVELS_DIRECTORY,GRAPHICS_DIRECTORY))
return false;
m_level.reset();
m_ship_y = m_level.m_back_layer.getSizeInPixels().getY() - PLAYER_START_OFFSET;
return true;
}
//-------------------------------------------------------------
// Destroy our level
void CDemo3::destroyLevel()
{
m_level.destroy();
}
//-------------------------------------------------------------
// Draw the level
void CDemo3::drawLevel()
{
setLayerPositions(m_ship_y);
m_level.m_back_layer.draw();
m_level.m_front_layer.draw();
}
//-------------------------------------------------------------
// Move the level
void CDemo3::moveLevel()
{
m_stars.move(4);
if (m_keyboard.testKey(gsKEY_UP)) {
m_ship_y -= 4;
}
if (m_keyboard.testKey(gsKEY_DOWN)) {
m_ship_y += 4;
}
}
//-------------------------------------------------------------
void CDemo3::setLayerPositions(int ship_y)
{
int mh = m_level.m_back_layer.getSizeInPixels().getY();
int by = -(mh - (mh - ship_y) / 2 + PLAYER_START_OFFSET / 2 - m_screen.getSize().getY());
m_level.m_back_layer.setPosition(gsCPoint(0,by));
int fy = -(ship_y + PLAYER_START_OFFSET - m_screen.getSize().getY());
m_level.m_front_layer.setPosition(gsCPoint(0,fy));
}
//-------------------------------------------------------------
| true |
81017822ea2fb73c4ab2c874a174be56f3ae6bf3 | C++ | takayoshi-k/neopixelsheet | /src/HappyReiwa.cpp | UTF-8 | 1,443 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "HappyReiwa.h"
namespace SpresenseNeoPixel
{
HappyReiwa::HappyReiwa() : font()
{
step = 0;
shuku_color[0] = 0x00041400;
shuku_color[1] = 0x00061800;
shuku_color[2] = 0x00081C00;
shuku_color[3] = 0x000A2000;
shuku_color[4] = 0x000C2400;
shuku_color[5] = 0x000E2800;
shuku_color[6] = 0x00102C00;
shuku_color[7] = 0x00123000;
}
void HappyReiwa::draw(RenderTarget<uint32_t> &target)
{
// currently this implementation is assuming the rendertarget has fixed size 32x8.
for(uint32_t y=0; y<font.getHeight(); y++){
uint32_t x;
uint32_t pixcol;
// Charactor "Shuku" will change the color every frame.
for(x=0; x<10; x++){
pixcol = *font.getPixel(x, y);
if(pixcol) {
pixcol = shuku_color[(y + step/2) % 8];
}
target.setPixel(x, y, &pixcol);
}
// Other charactor is as same color.
for(; x<font.getWidth(); x++){
pixcol = *font.getPixel(x, y);
if(pixcol) {
#if 0
if((step/8) >= 8) {
pixcol = 0x00010101 * (16 - (step/8)) + 0x00010101;
}else{
pixcol = 0x00010101 * (step/8) + 0x00010101;
}
#else
pixcol = 0x00080808;
#endif
}
target.setPixel(x, y, &pixcol);
}
}
step++;
if(step >= 8*8*2) step = 0;
}
}
| true |
73d2577b14967e07b4d476b880308e15821acb5f | C++ | fuchsto/waitfree-containers-mc | /include/mc/atomic.h | UTF-8 | 2,033 | 3.25 | 3 | [] | no_license | #ifndef __MC__ATOMIC_H__
#define __MC__ATOMIC_H__
#ifdef _MC__SIMULATE_STDATOMIC
#include <mutex>
#else
#include <atomic>
#endif
namespace mc {
#ifndef _MC__SIMULATE_STDATOMIC
/**
* @brief Alias for ::std::atomic<T>.
*/
template<typename T>
using Atomic = ::std::atomic<T>;
#else
/**
* @brief Custom blocking emulation of std::atomic.
*/
template<typename T>
class Atomic
{
private:
typedef ::mc::Atomic<T> self_t;
private:
mutable ::std::mutex _mutex;
T _value;
public:
Atomic() = default;
Atomic(T desired) : _value(desired) {
// {{{
} // }}}
T load() const {
// {{{
_mutex.lock();
T tmp = _value;
_mutex.unlock();
return tmp;
} // }}}
void store(const T & v) {
// {{{
_mutex.lock();
_value = v;
_mutex.unlock();
} // }}}
bool is_lock_free() const {
// {{{
return false;
} // }}}
operator T () const {
// {{{
return load();
} // }}}
T exchange(T desired) {
// {{{
_mutex.lock();
T old = _value;
_value = desired;
_mutex.unlock();
return old;
} // }}}
bool compare_exchange_strong(T & expected, T desired) {
// {{{
bool success = false;
_mutex.lock();
if (_value == expected) {
_value = desired;
success = true;
}
else {
expected = _value;
}
_mutex.unlock();
return success;
} // }}}
bool compare_exchange_weak(T & expected, T desired) {
// {{{
return compare_exchange_strong(expected, desired);
} // }}}
T operator=(T desired)
{ // {{{
store(desired);
return desired;
} // }}}
public:
/**
* @brief Atomic variables are not CopyAssignable, forbid
* assignment operator on class type.
*/
self_t & operator=(const self_t &) = delete;
/**
* @brief Atomic variables are not CopyAssignable, forbid
* copy constructor.
*/
Atomic(const self_t &) = delete;
};
#endif // MC__STDATOMIC
} // namespace mc
#endif // __MC__ATOMIC_H__
| true |
b4351e702d33a470c14b34ed0af72ce09e49dce7 | C++ | mastayb/config-parser | /config_lexer_test.cpp | UTF-8 | 6,044 | 2.984375 | 3 | [] | no_license | #include "config_lexer.h"
#include "gtest/gtest.h"
#include <sstream>
#include <stdexcept>
namespace
{
TEST(ScanTest, EOFTokenLexed)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource("");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
SimpleConfig::Token testToken= {SimpleConfig::END_OF_FILE, "", 0};
EXPECT_TRUE(!testTokens.empty());
EXPECT_EQ(testTokens.front().type, SimpleConfig::END_OF_FILE);
}
TEST(ScanTest, LeftBracketTokenLexed)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource("[");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::LEFT_BRACKET);
}
TEST(ScanTest, RightBracketLexed)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource("]");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::RIGHT_BRACKET);
}
TEST(ScanTest, EqualsLexed)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource("=");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::EQUALS);
}
TEST(ScanTest, WhitespaceSkipped)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" ] ");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::RIGHT_BRACKET);
}
TEST(ScanTest, NewlinesCounted)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource("\n\n\n ]");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().lineNum, 4);
}
TEST(ScanTest, StringLiteralLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" \"Hello World!\"");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::STRING);
EXPECT_EQ(testTokens.front().lexeme, "Hello World!");
EXPECT_EQ(testTokens.front().lineNum, 1);
}
TEST(ScanTest, CommentLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" \"Hello World!\" #Comment here \n ]");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens.front().type, SimpleConfig::STRING);
EXPECT_EQ(testTokens.front().lexeme, "Hello World!");
EXPECT_EQ(testTokens.front().lineNum, 1);
EXPECT_EQ(testTokens[1].type, SimpleConfig::RIGHT_BRACKET);
EXPECT_EQ(testTokens[1].lexeme, "]");
EXPECT_EQ(testTokens[1].lineNum, 2);
}
TEST(ScanTest, BoolLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" True FALSE");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens[0].type, SimpleConfig::BOOL);
EXPECT_EQ(testTokens[0].lexeme, "True");
EXPECT_EQ(testTokens[0].lineNum, 1);
EXPECT_EQ(testTokens[1].type, SimpleConfig::BOOL);
EXPECT_EQ(testTokens[1].lexeme, "FALSE");
EXPECT_EQ(testTokens[1].lineNum, 1);
}
TEST(ScanTest, IntLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" -0x1234FFFF");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens[0].type, SimpleConfig::INTEGER);
EXPECT_EQ(testTokens[0].lexeme, "-0x1234FFFF");
EXPECT_EQ(testTokens[0].lineNum, 1);
}
TEST(ScanTest, RealNumberLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" -1432.4352e3 ");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens[0].type, SimpleConfig::REAL_NUMBER);
EXPECT_EQ(testTokens[0].lexeme, "-1432.4352e3");
EXPECT_EQ(testTokens[0].lineNum, 1);
}
TEST(ScanTest, BadNumberFormatThrows)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" -1.432.4352e3 ");
EXPECT_THROW(l.Scan(testSource), std::logic_error);
}
TEST(ScanTest, IdLexingWorks)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" test ");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens[0].type, SimpleConfig::IDENTIFIER);
EXPECT_EQ(testTokens[0].lexeme, "test");
EXPECT_EQ(testTokens[0].lineNum, 1);
}
TEST(ScanTest, UnterminatedStringThrows)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" \"no termination ");
EXPECT_THROW(l.Scan(testSource), std::logic_error);
}
TEST(ScanTest, UnexpecetedCharThrows)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" $ ");
EXPECT_THROW(l.Scan(testSource), std::logic_error);
}
TEST(ScanTest, TokenSequenceMatchesExpected)
{
SimpleConfig::ConfigLexer l;
std::istringstream testSource(" test = true #comment\n\n test2 = 100 \n [Section] \n test4 = \"str\" \n ");
const std::vector<SimpleConfig::Token> testTokens = l.Scan(testSource);
EXPECT_EQ(testTokens[0].type, SimpleConfig::IDENTIFIER);
EXPECT_EQ(testTokens[0].lexeme, "test");
EXPECT_EQ(testTokens[0].lineNum, 1);
EXPECT_EQ(testTokens[1].type, SimpleConfig::EQUALS);
EXPECT_EQ(testTokens[1].lexeme, "=");
EXPECT_EQ(testTokens[1].lineNum, 1);
EXPECT_EQ(testTokens[2].type, SimpleConfig::BOOL);
EXPECT_EQ(testTokens[2].lexeme, "true");
EXPECT_EQ(testTokens[2].lineNum, 1);
EXPECT_EQ(testTokens[3].type, SimpleConfig::IDENTIFIER);
EXPECT_EQ(testTokens[3].lexeme, "test2");
EXPECT_EQ(testTokens[3].lineNum, 3);
EXPECT_EQ(testTokens[4].type, SimpleConfig::EQUALS);
EXPECT_EQ(testTokens[4].lexeme, "=");
EXPECT_EQ(testTokens[4].lineNum, 3);
EXPECT_EQ(testTokens[5].type, SimpleConfig::INTEGER);
EXPECT_EQ(testTokens[5].lexeme, "100");
EXPECT_EQ(testTokens[5].lineNum, 3);
EXPECT_EQ(testTokens[7].type, SimpleConfig::IDENTIFIER);
EXPECT_EQ(testTokens[7].lexeme, "Section");
EXPECT_EQ(testTokens[7].lineNum, 4);
EXPECT_EQ(testTokens[11].type, SimpleConfig::STRING);
EXPECT_EQ(testTokens[11].lexeme, "str");
EXPECT_EQ(testTokens[11].lineNum, 5);
}
}
| true |
3e7588fd36276a2cd7829145b49e550e3a53fa0d | C++ | Kiritow/OJ-Problems-Source | /HDOJ/4549_autoAC.cpp | UTF-8 | 1,396 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;
const int MOD=1e9+7;
struct Matrix
{
long long mat[2][2];
};
Matrix mul(Matrix a,Matrix b)
{
Matrix ret;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
ret.mat[i][j]=0;
for(int k=0;k<2;k++)
{
ret.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
ret.mat[i][j]%=(MOD-1);
}
}
return ret;
}
Matrix pow_M(Matrix a,int n)
{
Matrix ret;
memset(ret.mat,0,sizeof(ret.mat));
ret.mat[0][0]=ret.mat[1][1]=1;
Matrix temp=a;
while(n)
{
if(n&1)ret=mul(ret,temp);
temp=mul(temp,temp);
n>>=1;
}
return ret;
}
long long pow_m(long long a,long long n)
{
long long ret=1;
long long temp=a%MOD;
while(n)
{
if(n&1)
{
ret*=temp;
ret%=MOD;
}
temp*=temp;
temp%=MOD;
n>>=1;
}
return ret;
}
int main()
{
int a,b,n;
Matrix tmp;
tmp.mat[0][0]=0;
tmp.mat[0][1]=tmp.mat[1][0]=tmp.mat[1][1]=1;
while(scanf("%d%d%d",&a,&b,&n)==3)
{
Matrix p=pow_M(tmp,n);
int ans=(pow_m(a,p.mat[0][0])*pow_m(b,p.mat[1][0]))%MOD;
printf("%d\n",ans);
}
return 0;
}
| true |
ffe5757c8ef757b05f28572d9b7f4e1ddfa62798 | C++ | LaoZZZZZ/bartender-1.1 | /src/patternparser.h | UTF-8 | 1,723 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2015, Lu Zhao <luzhao1986@gmail.com>
*
* This file is part of bartender project.
*/
#ifndef PATTERNPARSER_H
#define PATTERNPARSER_H
#include "filebuf.h"
#include "sequence.h"
#include <memory>
#include <string>
#include <fstream>
#include <algorithm>
namespace barcodeSpace{
/**
* A general pattern that parses the sequence file.
* Its subclass is designed to handle a specific file format,like fastq,fasta..
*/
class patternParser
{
public:
patternParser(const string& file):
line_num_(0), _file(file), _nakeHandler(NULL){
_nakeHandler = fopen(this->_file.c_str(),"r");
if(!(_nakeHandler)){
throw runtime_error(string("can not open file ") + _file);
}
fb_.reset(new FileBuf(this->_nakeHandler));
}
void parse(Sequence& r,bool& success,bool& done){
this->parseImp(r,success,done);
}
void reset(){
fclose(this->_nakeHandler);
this->fb_.reset();
_nakeHandler = fopen(this->_file.c_str(),"r");
if(!(_nakeHandler)){
throw runtime_error(string("can not open file ") + _file);
}
fb_.reset(new FileBuf(this->_nakeHandler));
}
virtual ~patternParser(){
fclose(this->_nakeHandler);
}
size_t CurrentLine()const {return line_num_ + 1;}
private:
virtual void parseImp(Sequence&,bool&,bool&) = 0;
patternParser(const patternParser&);
patternParser& operator=(const patternParser&);
protected:
std::unique_ptr<FileBuf> fb_;
size_t line_num_;
private:
std::string _file;
FILE* _nakeHandler;
};
}
#endif // PATTERNPARSER_H
| true |
8132f0bb040950e5ea38901002130582bcfa2c1a | C++ | tmtmazum/sfml-wrappers | /2dGraphics.h | UTF-8 | 1,408 | 3.125 | 3 | [] | no_license | #ifndef GRAPHICS_2D
#define GRAPHICS_2D
#include <vector>
namespace Graphics2d
{
class color
{
int r,g,b;
color(int rv = 0, int gv = 0, int bv = 0);
} /*black(0,0,0), red(255,0,0), blue(0,0,255), green(0,255,0)*/;
class drawable
{
int a;
};
class pos : public drawable
{
public:
// Variables
int x,y;
// Constructors
pos(int, int);
// Operators Overloaded:
void operator %(pos a) // Alias for move_to(..)
{ move_to(a.x, a.y); }
// Methods
void offset(pos a);
void move_to(int c, int d);
};
class rectangle: public pos
{public:
// Variables:
int width, height;
// Constructors:
rectangle(pos position, int width, int height);
rectangle(int x, int y, int width, int height);
rectangle(int width, int height);
// Operators Overloaded:
// Methods:
};
class graphic
{public:
drawable object;
color fill, outline_color;
float outline;
int rx, ry;
};
class group: public pos
{public:
// Variables:
std::vector<drawable> objects;
// Constructors:
group(pos p);
// Methods:
void add(drawable);
void add(pos);
};
}
#endif // GRAPHICS_2D
| true |
306b4925b54d93497265633b842206c8cb1c6a14 | C++ | aljo242/pt-three-ways | /src/oo/Scene.h | UTF-8 | 527 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include "oo/Primitive.h"
#include <memory>
#include <vector>
namespace oo {
class Scene : public Primitive {
std::vector<std::unique_ptr<Primitive>> primitives_;
Vec3 environment_;
public:
void setEnvironmentColour(const Vec3 &colour) { environment_ = colour; }
void add(std::unique_ptr<Primitive> primitive);
[[nodiscard]] bool intersect(const Ray &ray,
IntersectionRecord &intersection) const override;
[[nodiscard]] Vec3 environment(const Ray &ray) const;
};
} | true |
af551f8637fb214fb953b0d5a032afb6ea6329ce | C++ | cristian0710/Taller_2 | /4_struct_anidada.cpp | UTF-8 | 1,223 | 3.546875 | 4 | [] | no_license | #include <stdio.h>
struct promedio
{
float n1, n2, n3;
};
struct alumno
{
char nom[30];
int edad, grd;
promedio prom;
};
//PROTOTIPOS
void datos();
void prom(float a,float b,float c);
void imprimir();
//DIFINICION DE ESTRUCTURA
alumno estudiante;
int main()
{
datos();
imprimir();
}
void prom(float a,float b,float c)
{
float r;
r=(a+b+c)/3;
printf("\nEl promedio es: %1.1f",r);
}
void datos()
{
printf("Ingrese nombre: ");
scanf("%s",estudiante.nom);
printf("Ingrese grado: ");
scanf("%d",&estudiante.grd);
printf("Ingrese edad: ");
scanf("%d",&estudiante.edad);
printf("Ingrese nota 1: ");
scanf("%f",&estudiante.prom.n1);
printf("Ingrese nota 2: ");
scanf("%f",&estudiante.prom.n2);
printf("Ingrese nota 3: ");
scanf("%f",&estudiante.prom.n3);
}
void imprimir()
{
printf("\n");
printf("Nombre: %s\n",estudiante.nom);
printf("Grado: %d\n",estudiante.grd);
printf("Edad: %d\n",estudiante.edad);
printf("Nota 1: %1.1f\n",estudiante.prom.n1);
printf("Nota 2: %1.1f\n",estudiante.prom.n2);
printf("Nota 3: %1.1f\n",estudiante.prom.n3);
prom(estudiante.prom.n1,estudiante.prom.n2,estudiante.prom.n3);
}
| true |
e98c36160c8e72b673235e6422b1c7f25ea9fa3c | C++ | tomn46037/Arduino-MQTT-Desklamp | /MQTT_Lights/MQTT_Lights.ino | UTF-8 | 4,636 | 2.546875 | 3 | [] | no_license | // tomn CLS (Cubicle Lighting System)
#include <avr/wdt.h>
// Stuff for the motors
#include <AFMotor.h>
#include <Servo.h>
// Able to control 4 lights!
// AF_DCMotor motor1(1); Cannot use motor 1 as Digital Pin 11 is used with SPI and Ethernet
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);
// There are 4 motors. 0 = Descired, 1 = Current, 2 = Reported
int motorSpeeds[4][3];
// Stuff for the MQTT client
#include <SPI.h>
#include <Wire.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xE4, 0xBA, 0xF0, 0xFE, 0xED };
byte server[] = { 206, 246, 158, 179 };
// Only 128 character messages are supported.
// Longer messages are UNDEFINED! (ie.. You will crash the Arduino.)
char topic_buff[25];
char message_buff[128];
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.println(topic);
// create character buffer with ending null terminator (string)
int i = 0;
for(i=0; i<128; i++) {
message_buff[i] = '\0';
}
for(i=0; i<length; i++) {
message_buff[i] = payload[i];
}
// Chop the string off at 22 - that's the widt of the display
message_buff[length] = '\0';
String msgString = String(message_buff);
Serial.println("Payload: " + msgString);
if ( strncmp( topic, "/arduino/lights/status", 22 ) == 0 ) {
return;
}
// If we get a message to just lights, set them all to this value
if ( strncmp( topic, "/arduino/lights/all", 19) == 0 )
{
Serial.print("All Lights - ");
Serial.println( topic );
for ( int c = 0; c < 4; c++ ) {
motorSpeeds[c][0] = msgString.toInt();
}
return;
}
// If we get a "directory" then set the individual light number to this value
if ( strncmp( topic, "/arduino/lights/", 16) == 0 )
{
Serial.println(topic);
int light = topic[16]-48;
motorSpeeds[light-1][0] = msgString.toInt();
}
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("tomn CLS!");
// Turn off the lights
// motor1.setSpeed(0);
// motor1.run(FORWARD);
motor2.setSpeed(0);
motor2.run(FORWARD);
motor3.setSpeed(0);
motor3.run(FORWARD);
motor4.setSpeed(0);
motor4.run(FORWARD);
// We're alive, enable the watch dog
wdt_enable(WDTO_8S);
Serial.println("Starting Network");
Ethernet.begin(mac);
Serial.print("IP: ");
Serial.println(Ethernet.localIP());
// Tell the watchdog we're still alive
wdt_reset();
if (client.connect("arduinoClient", "arduino", "moo837388d")) {
client.publish("hello","hello world from tomn CLS");
client.subscribe("/arduino/lights/#");
}
// Tell the watchdog we're still alive
wdt_reset();
}
void loop() {
// Tell the watchdog we're still alive
wdt_reset();
client.loop();
setMotors();
delay(7);
if ( !client.connected() ) {
// Sshhhhhhh.
Serial.println("Going quietly into the night.");
while(1){}
}
}
void setMotors() {
for ( int c = 0; c < 4; c++ ) {
if ( motorSpeeds[c][0] > 255 ) { motorSpeeds[c][0] = 255; }
if ( motorSpeeds[c][0] < 0 ) { motorSpeeds[c][0] = 0; }
// Check to see if we desire a speed change
if ( motorSpeeds[c][0] > motorSpeeds[c][1] ) {
motorSpeeds[c][1]++;
motorSpeeds[c][2] = 1;
}
if ( motorSpeeds[c][0] < motorSpeeds[c][1] ) {
motorSpeeds[c][1]--;
motorSpeeds[c][2] = 1;
}
// If we've reached equalibrimu then tell the world.. ONCE.
if ( motorSpeeds[c][2] && motorSpeeds[c][0] == motorSpeeds[c][1] ) {
motorSpeeds[c][2] = 0;
String topicString = String("/arduino/lights/status/")+(c+1);
topicString.toCharArray(topic_buff, 25);
String msgString = String("")+(motorSpeeds[c][1]);
msgString.toCharArray(message_buff, 128);
client.publish(topic_buff,message_buff);
}
}
// motor1.setSpeed(motorSpeeds[0][1]);
//if ( motorSpeeds[0][1] == 0 ) {
// motor1.run(RELEASE);
//} else {
// motor1.run(FORWARD);
//}
// motor1.run(FORWARD);
motor2.setSpeed(motorSpeeds[1][1]);
if ( motorSpeeds[1][1] == 0 ) {
motor2.run(RELEASE);
} else {
motor2.run(FORWARD);
}
motor3.setSpeed(motorSpeeds[2][1]);
if ( motorSpeeds[2][1] == 0 ) {
motor3.run(RELEASE);
} else {
motor3.run(FORWARD);
}
motor4.setSpeed(motorSpeeds[3][1]);
if ( motorSpeeds[3][1] == 0 ) {
motor4.run(RELEASE);
} else {
motor4.run(FORWARD);
}
}
| true |
7ea8ca64cbc1a29fb56348b289a8d48f38e7e40a | C++ | VishnuArun/Robot-Simulation | /Robot_Simulator/iteration3/src/pose.h | UTF-8 | 2,023 | 2.859375 | 3 | [
"MIT"
] | permissive | /**
* @file pose.h
*
* @copyright 2017 3081 Staff, All rights reserved.
*
*/
#ifndef SRC_POSE_H_
#define SRC_POSE_H_
/*******************************************************************************
* Includes
******************************************************************************/
#include "src/common.h"
/*******************************************************************************
* Namespaces
******************************************************************************/
NAMESPACE_BEGIN(csci3081);
/*******************************************************************************
* Class Definitions
******************************************************************************/
/**
* @brief A simple representation of the position/orientation of an entity
* within the Arena.
*
* NOTE: Origin (0,0) is at the upper left corner of the Arena.
*/
struct Pose {
public:
/**
* @brief Default constructor. Initialize the pose to (0,0,0)
*/
Pose() {}
/**
* @brief Constructor
*
* @param in_x The X component of the Pose.
* @param in_y The Y component of the Pose.
*/
Pose(double in_x, double in_y) : x(in_x), y(in_y) {}
Pose(double in_x, double in_y, double in_theta)
: x(in_x),
y(in_y),
theta(in_theta) {}
/**
* @brief Default assignment operator. Simply copies the (x,y) values of
* another Pose.
*
* @param other The Pose object to copy from.
*
* @return The left-hand-side Pose object that is now identical (in value)
* to `other`.
*/
Pose &operator=(const Pose &other) = default;
double x{0};
double y{0};
double theta{0.0};
};
/*******************************************************************************
* Forward Decls
******************************************************************************/
constexpr double deg2rad(double deg) { return deg * M_PI / 180.0; }
constexpr double rad2deg(double rad) { return rad * 180.0 / M_PI; }
NAMESPACE_END(csci3081);
#endif /* SRC_POSE_H_ */
| true |
4fc4ade50b34695eb6b687d18f2d58910e105df6 | C++ | Jeremy-Martin4794/CS2-projects | /infix2prefix/stack.hpp | UTF-8 | 3,417 | 3.296875 | 3 | [] | no_license | // Jeremy Martin
// Project 3 stack interface header file
// 11/1/2020
#ifndef CS2_STACK_HPP_
#define CS2_STACK_HPP_
////////////////////////////////////////////////////////////////////////////
//
// File: stack.hpp
//
// Programmer:
// Updated: 10/2019
//
//
// Do not change the names of the classes or methods. Otherwise, instructor
// tests will not work.
//
#include <new>
#include <iostream>
#include "string.hpp"
#include<cassert>
////////////////////////////////////////////////////////////////////////////
//
template<typename T>
class Node {
public:
T data;
Node* next;
Node() { next = 0; }
Node(T value) { data = value; next = 0; }
};
////////////////////////////////////////////////////////////////////////////
// CLASS INV:
//
//
template <typename T>
class stack {
public:
stack() { tos = 0; length = 0; }
stack(const stack<T>&);
~stack();
void swap(stack<T>&);
stack<T>& operator=(stack<T>);
bool operator==(const stack<T>) const;
bool empty() const { return tos == 0; }
bool full() const;
T top() const { assert(tos != 0); return tos->data; }
T pop();
void push(const T&);
private:
Node<T>* tos;
int length;
};
/////////////////////////////////////////////////////////////////////////////
//foo->bar() is the same as (*foo).bar()
template <typename T>
stack<T>::stack(const stack<T>& org) {
tos = 0;
length = 0;
Node<T>* orgTos = org.tos;
Node<T>* middle = 0;
Node<T>* bottom = 0;
while (orgTos != 0) {
bottom = new Node<T>(orgTos->data);
if (tos == 0) tos = bottom;
if (middle == 0) middle = tos;
if (middle != bottom) middle->next = bottom;
middle = middle->next;
orgTos = orgTos->next;
++length;
}
}
template <typename T>
stack<T>::~stack() {
Node<T>* temp;
while (tos != 0) {
temp = tos;
tos = tos->next;
delete temp;
}
}
template <typename T>
void stack<T>::swap(stack<T>& tos2) {
int len = length;
length = tos2.length;
tos2.length = len;
Node<T>* temp = tos;
tos = tos2.tos;
tos2.tos = temp;
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> rhs) {
Node<T>* rhsTos = rhs.tos;
Node<T>* del;
Node<T>* middle = 0;
Node<T>* bottom = 0;
if (this != &rhs) {
length = rhs.length;
while (tos != 0) {
del = tos;
tos = tos->next;
if (del != 0)
delete del;
}
while (rhsTos != 0) {
bottom = new Node<T>(rhsTos->data);
if (tos == 0) tos = bottom;
if (middle == 0) middle = tos;
if (middle != bottom) middle->next = bottom;
middle = middle->next;
rhsTos = rhsTos->next;
}
}
return *this;
}
template <typename T>
bool stack<T>::operator==(const stack<T> rhs) const {
int found = 0;
Node<T>* temp1 = tos;
Node<T>* temp2 = rhs.tos;
if (length == rhs.length) {
if ((temp1 == 0) && (temp2 == 0)) return true;
while ((temp1 != 0) && (temp2 != 0)) {
if (temp1->data != temp2->data)
found = -1;
temp1 = temp1->next;
temp2 = temp2->next;
}
if (found == 0)
return true;
}
return false;
}
template <typename T>
bool stack<T>::full() const {
Node<T>* temp = new Node<T>;
if (temp == 0)
return true;
delete temp;
return false;
}
template <typename T>
T stack<T>::pop() {
--length;
Node<T>* temp = tos;
tos = tos->next;
T value = temp->data;
if (temp != 0)
delete temp;
return value;
}
template <typename T>
void stack<T>::push(const T& value) {
++length;
Node<T>* newNode = new Node<T>(value);
newNode->next = tos;
tos = newNode;
}
#endif
| true |
748ca5932b63d38d4c8bad15c8a34e6b9172cb50 | C++ | bentglasstube/gam | /text.cc | UTF-8 | 1,012 | 3 | 3 | [
"MIT"
] | permissive | #include "text.h"
// TODO replace with spritemap
Text::Text(const std::string& file, int width, int height) : file_(file), width_(width), height_(height) {}
void Text::draw(Graphics& graphics, const std::string& text, int x, int y, Text::Alignment alignment) const {
SDL_Rect source = { 0, 0, width_, height_ };
SDL_Rect dest = { x, y, width_, height_ };
switch (alignment) {
case Alignment::Left:
break;
case Alignment::Center:
dest.x -= width_ / 2 * text.length();
break;
case Alignment::Right:
dest.x -= width_ * text.length();
break;
}
for (std::string::const_iterator i = text.begin(); i != text.end(); ++i) {
unsigned int n = 0;
if ((*i) >= ' ' && (*i) <= '~') n = (*i) - ' ';
source.x = width_ * (n % 16);
source.y = height_ * (n / 16);
graphics.blit(file_, &source, &dest);
if ((*i) == '\n' && alignment == Alignment::Left) {
dest.x = x;
dest.y += height_;
} else {
dest.x += width_;
}
}
}
| true |
dcbc63ce95390ba9b034234cce57815763bb2883 | C++ | aldoshkind/y_me | /projector_elliptic.h | UTF-8 | 1,336 | 3.03125 | 3 | [] | no_license | #pragma once
#include "projector.h"
class projector_elliptic : public projector
{
public:
/*constructor*/ projector_elliptic ()
{
//
}
virtual /*destructor*/ ~projector_elliptic ()
{
//
}
double x_to_lon (double x) const
{
return x / ((1 / 2.0) * (1 / M_PI)) - M_PI;
}
double y_to_lat (double y) const
{
double ts = exp(y / ((1 / 2.0) * (1 / M_PI)) - M_PI);
double phi = M_PI_2 - 2.0 * atan(ts);
double dphi = 1.0;
double a = 6378137.000;
double b = 6356752.3142;
double eccentr = sqrt(1.0 - (b / a) * (b / a));
int i = 0;
for(i = 0 ; fabs(dphi) > 0.000000001 && i < 30 ; i += 1)
{
double con = eccentr * sin (phi);
dphi = M_PI_2 - 2 * atan(ts * pow((1.0 - con) / (1.0 + con), eccentr / 2.0)) - phi;
phi += dphi;
}
return phi;
}
double lon_to_x (double lon) const
{
return (1.0 / 2.0) * (1.0 / M_PI) * (lon + M_PI);
}
double lat_to_y (double lat) const
{
// b - малая полуось, а - большая.
double a = 6378137.000;
double b = 6356752.3142;
double eccentr = sqrt(1.0 - (b / a) * (b / a));
double e_sin_lat = eccentr * sin(lat);
double coef = ((1.0 - e_sin_lat) / (1.0 + e_sin_lat));
coef = pow(coef, eccentr / 2.0);
return (1 / 2.0) * (1 / M_PI) * (M_PI - log(tan(M_PI / 4.0 + lat / 2.0) * coef));
}
};
| true |
e212c504f2f0d6afedcd0d2ea22aa4ce1088ddd9 | C++ | kimphuongtu135/OOP345 | /opp2/RecordSet.cpp | UTF-8 | 2,733 | 3.046875 | 3 | [] | no_license | // Name:Kim Phuong Tu
// Seneca Student ID:148886179
// Seneca email: kptu@myseneca.ca
// Date of completion: Jan 22,2020
//
// I confirm that the content of this file is created by me,
// with the exception of the parts provided to me by my professor.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "RecordSet.h"
using namespace std;
namespace sdds
{
RecordSet::RecordSet() {
str = nullptr;
numstr = 0;
}
RecordSet::RecordSet(const char* name) {
ifstream myfile(name); // open file "name"
std::string substr; // create a substring
if (myfile) {
while (!myfile.eof()) {
getline(myfile, substr, ' '); // read file from beginning till substr and remove the ' '
numstr++;
}
}
str = new std::string[numstr]; // dynamic allocation the str with new number of index
myfile.seekg(0); // load file back to begining without re-opening
if (myfile) {
int count = 0;
while (!myfile.eof()) {
getline(myfile, substr, ' '); // read file from beginning till substr and remove the ' '
str[count] = substr;
count++;
}
}
/*for (int i = 0; i < numstr; i++) {
getline(myfile, substr, ' '); // read the file until str[i] and remove the ' '
str[i] = substr;
}*/
myfile.close();// close file
}
RecordSet::RecordSet(const RecordSet& record) {
//shallow copy static memory
numstr = record.numstr;
//allocate dynamic memory
if (record.str != nullptr) {
str = new std::string[numstr];
for (int i = 0; i < numstr; i++) {
str[i] = record.str[i];
}
}
else {
str = nullptr;
numstr = 0;
}
}
RecordSet& RecordSet::operator=(const RecordSet& record) {
// check self-assigment
if (this != &record) {
//shallow copy static memory
numstr = record.numstr;
//deallocate previously allocated memory
delete[] str;
//allocate new dynamic memory
if (record.str != nullptr) {
str = new std::string[numstr];
for (int i = 0; i < numstr; i++) {
str[i] = record.str[i];
}
}
else {
str = nullptr;
numstr = 0;
}
}
return *this;
}
std::size_t RecordSet::size()const {
return numstr;
}
std::string RecordSet::getRecord(size_t num)const {
if (num < size() && num >= 0) {
return str[num];
}
else {
return "";
}
}
RecordSet::~RecordSet() {
delete[] str;
}
//Move constructor
RecordSet::RecordSet(RecordSet&& record) {
str = nullptr;
*this = std::move(record);
}
//Move Assignment operator
RecordSet& RecordSet::operator =(RecordSet&& record) {
if (this != &record) {
delete[] str;
str = record.str;
numstr = record.numstr;
record.str = nullptr;
record.numstr = 0;
}
return *this;
}
} | true |
8f2b9db6cb16762a067af5a97450f6a654de30e7 | C++ | vastamat/Data-Oriented-Design-Practice | /Dode/Dode/ECS/World.cpp | UTF-8 | 2,860 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "World.h"
namespace dode
{
World::World( const std::string& _IdentificationName )
: m_IdentificationName(_IdentificationName)
{
}
World::~World()
{
}
World::World( World && _Other ) noexcept
: m_EntityManager(std::move(_Other.m_EntityManager))
, m_ComponentManagers( std::move( _Other.m_ComponentManagers ) )
, m_Systems( std::move( _Other.m_Systems ) )
, m_IdentificationName( std::move( _Other.m_IdentificationName ) )
{
}
World & World::operator=( World && _Other ) noexcept
{
m_EntityManager = std::move( _Other.m_EntityManager );
m_ComponentManagers = std::move( _Other.m_ComponentManagers );
m_Systems = std::move( _Other.m_Systems );
m_IdentificationName = std::move( _Other.m_IdentificationName );
return *this;
}
void World::OnEnter()
{
for ( auto& system : m_Systems )
{
system->Initialize();
}
}
void World::OnExit()
{
for ( auto& system : m_Systems )
{
system->Uninitialize();
}
}
void World::UpdateSystems( float _DeltaTime )
{
for ( auto& system : m_Systems )
{
system->Update( *this, _DeltaTime );
}
}
Entity World::CreateEntity()
{
return m_EntityManager.Create();
}
void World::DestroyEntity( Entity _Entity )
{
//Remove Entity from Systems
for ( auto& System : m_Systems )
{
System->UnregisterEntity( _Entity );
}
//Remove Entity Components from managers
const ComponentMask& componentMask = m_EntityManager.GetComponentMaskForEntity( _Entity );
for ( size_t componentTypeId = 0; componentTypeId < componentMask.size(); componentTypeId++ )
{
if ( componentMask[componentTypeId] )
{
auto& baseComponentManager = m_ComponentManagers[componentTypeId];
baseComponentManager->RemoveComponent( _Entity );
}
}
m_EntityManager.RecycleEntity( _Entity );
}
void World::AddSystem( std::unique_ptr<System> _System )
{
m_Systems.emplace_back( std::move( _System ) );
}
void World::UpdateEntityInSystems( Entity _Entity, const ComponentMask & oldComponentMask, const ComponentMask & newComponentMask )
{
for ( auto& System : m_Systems )
{
const ComponentMask& systemSignature = System->GetSystemSignature();
if ( systemSignature == oldComponentMask )
{
System->UnregisterEntity( _Entity );
}
else if ( systemSignature == newComponentMask )
{
System->RegisterEntity( _Entity );
}
}
}
}
| true |
3a332fa33dfc313f5728006adf78ccde1f74f13a | C++ | kenrick95/code-archive | /2015-04-09 NTUACM Session 7/aa.cpp | UTF-8 | 1,495 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
//#include <bits/stdc++.h>
#define INF 1000000007
#define INFLL 9223372036854775807LL
typedef long long int64;
typedef unsigned long long qword;
using namespace std;
/**
* @problem
* @url
* @status
*/
bool car(int n) {
if (n % 2 == 0)
return false;
bool prime = true;
// square-free
for (int i = 3; i < sqrt(n) + 1; i += 2) {
if (n % (i*i) == 0) {
// printf("%d\n", i);
return false;
}
if (n % i == 0)
prime = false;
}
if (prime)
return false;
int temp = n;
// for all prime divisors p of n
// (n - 1) % (p - 1) == 0
for (int i = 3; i < n; i += 2) {
int p = i;
if (temp < i)
break;
if (temp % p == 0) {
// printf("%d %d\n", temp, p);
// p is prime divisor
if ((n - 1) % (p - 1) != 0) {
return false;
}
while (temp % p == 0)
temp = temp / p;
}
}
return true;
}
int main(){
// freopen("test.in","r",stdin);
// freopen("test.out","w",stdout);
int n;
while (scanf("%d", &n) != EOF) {
if (n == 0) break;
if (car(n))
printf("The number %d is a Carmichael number.\n", n);
else
printf("%d is normal.\n", n);
}
return 0;
}
| true |
c3e75b7039d84adfd9a9e83126a1716f50e7b92f | C++ | Devenda/Cuby_Firmware | /components/ui/touch.cpp | UTF-8 | 4,299 | 2.59375 | 3 | [] | no_license | /* Touch Pad Interrupt Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <driver/gpio.h>
#include <vector>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "driver/touch_pad.h"
#include "soc/rtc_periph.h"
#include "soc/sens_periph.h"
#include "touch.h"
static const char *TAG = "Touch";
#define TOUCH_THRESH_PERCENT (80)
#define TOUCHPAD_FILTER_TOUCH_PERIOD (10)
bool Touch::touched = false;
Touch::Touch(std::vector<touch_pad_t> pads, xQueueHandle touchQueue)
{
// TODO: size 1: als beiden tegelijk ingedrukt blijven wordt er mss een gemist
_rawTouchQueue = xQueueCreate(1, sizeof(int));
_pads = pads;
_touchQueue = touchQueue;
// Create internal touch task handler
xTaskCreate(this->tp_touch_handler_wrapper, "tp_touch_handler", 8192, this, 5, NULL);
tp_init();
}
void Touch::tp_init(void)
{
// Initialize touch pad peripheral, it will start a timer to run a filter
ESP_LOGI(TAG, "Initializing touch");
touch_pad_init();
// If use interrupt trigger mode, should set touch sensor FSM mode at 'TOUCH_FSM_MODE_TIMER'.
touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
// Set reference voltage for charging/discharging
// For most usage scenarios, we recommend using the following combination:
// the high reference valtage will be 2.7V - 1V = 1.7V, The low reference voltage will be 0.5V.
touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V);
// Init touchpads
tp_touch_pad_init();
// Initialize and start a software filter to detect slight change of capacitance.
touch_pad_filter_start(TOUCHPAD_FILTER_TOUCH_PERIOD);
// Set threshold
tp_set_threshold();
// Register touch interrupt ISR
touch_pad_isr_register(tp_rtc_intr, this);
// Enable interrupt
touch_pad_intr_enable();
}
void Touch::tp_touch_pad_init()
{
for (int i = 0; i < _pads.size(); i++)
{
//init RTC IO and mode for touch pad.
touch_pad_config(_pads[i], TOUCH_THRESH_PERCENT);
}
}
/*
Read values sensed at all available touch pads.
Use 2 / 3 of read value as the threshold
to trigger interrupt when the pad is touched.
Note: this routine demonstrates a simple way
to configure activation threshold for the touch pads.
Do not touch any pads when this routine
is running (on application start).
*/
void Touch::tp_set_threshold()
{
uint16_t touch_value;
for (int i = 0; i < _pads.size(); i++)
{
//read filtered value
touch_pad_read_filtered(_pads[i], &touch_value);
ESP_LOGI(TAG, "test init: touch pad [%d] val is %d", _pads[i], touch_value);
//set interrupt threshold.
ESP_ERROR_CHECK(touch_pad_set_thresh(_pads[i], touch_value * 5 / 10));
}
}
/*
Handle an interrupt triggered when a pad is touched.
Recognize what pad has been touched and save it in a table.
*/
void Touch::tp_rtc_intr(void *arg)
{
Touch *tp = (Touch *)arg;
uint32_t pad_intr = touch_pad_get_status();
//clear interrupt
touch_pad_clear_status();
if (Touch::touched == false)
{
for (int i = 0; i < tp->_pads.size(); i++)
{
if ((pad_intr >> (int)tp->_pads[i]) & 0x01)
{
// ets_printf("Pad %d touched", i);
Touch::touched = true;
xQueueSendFromISR(tp->_rawTouchQueue, &tp->_pads[i], NULL);
}
}
}
}
void Touch::tp_touch_handler_wrapper(void *_this)
{
static_cast<Touch *>(_this)->tp_touch_handler();
}
void Touch::tp_touch_handler()
{
touch_pad_t touchedPad;
while (1)
{
if (xQueueReceive(_rawTouchQueue, &touchedPad, portMAX_DELAY))
{
// ESP_LOGI(TAG, "pad %d touched", touchedPad);
xQueueSendToBack(_touchQueue, &touchedPad, portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(200));
Touch::touched = false;
}
}
}
Touch::~Touch(){
ESP_LOGI(TAG, "Destructor called");
}
| true |
474f1b586b57df4467f77b50165e9eb29bb07d19 | C++ | GreatDanton/Training | /Cpp/thinkLikeAProgrammer/6.recursion/1.sum_of_integers.cpp | UTF-8 | 988 | 4.5625 | 5 | [] | no_license | /*
* Problem 1:
*
* Write a recursive function that is given an array of integers and the size of
* the array as parameters. The function returns the sum of the integers in the
* array.
*/
#include <iostream>
int arraySumRecursive(int integers[], int size) {
if (size == 0) {
return 0;
}
int lastNumber = integers[size - 1];
int allButLastSum = arraySumRecursive(integers, size - 1);
return lastNumber + allButLastSum;
}
// count number of 0 in integers array
int zeroCountRecursive(int numbers[], int size) {
if (size == 0) {
return 0;
}
int count = zeroCountRecursive(numbers, size - 1);
if (numbers[size - 1] == 0) {
count++;
}
return count;
}
int main() {
int integers[3] = {3, 2, 1};
int sum = arraySumRecursive(integers, 3);
std::cout << sum << std::endl;
int numbers[5] = {0, 1, 0, 3, 5};
int sum2 = zeroCountRecursive(numbers, 5);
std::cout << sum2 << std::endl;
return 0;
} | true |
0cbbb510e92d01cb6a680e201233863eccc57517 | C++ | kalyankondapally/temp | /common/HwcList.h | UTF-8 | 5,018 | 2.8125 | 3 | [] | no_license | /*
// Copyright (c) 2017 Intel Corporation
//
// 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 COMMON_HWC_HWCLIST_H
#define COMMON_HWC_HWCLIST_H
//namespace intel {
//namespace ufo {
//namespace hwc {
namespace hwcomposer {
// This class is a specialisation for managing lists of objects, used in a variety of situations as an alternative to vectors
// In particular, it minimises reallocations by assigning elements to an unused list
template <class T>
class HwcList
{
public:
HwcList() :
mpElement(NULL),
mSize(0)
{
}
uint32_t size() const
{
return mSize;
}
bool isEmpty() const
{
return 0 == mSize;
}
// Empty the layer list
void clear()
{
while (mpElement)
{
Element* pNext = pop_front();
sUnusedElements.push_front(pNext);
}
}
bool grow(uint32_t newSize)
{
while (mSize < newSize)
{
Element* pNew;
if (sUnusedElements.size() == 0)
{
// Need to allocate a new element
pNew = new(std::nothrow) Element();
if (pNew == NULL)
{
// Failure case, caller must handle if they care
return false;
}
}
else
{
// Just take the element from the front of the unused list
pNew = sUnusedElements.pop_front();
pNew->clear();
}
push_back(pNew);
}
return true;
}
bool shrink(uint32_t newSize)
{
// Shrink if needed
while (mSize > newSize)
{
Element* pOld = pop_front();
sUnusedElements.push_front(pOld);
}
// Make sure this list doesnt keep on growing
while (sUnusedElements.size() > cMaxUnusedElements)
{
Element* pOld = sUnusedElements.pop_front();
delete pOld;
}
return true;
}
// Resize the layer list obtaining any additional elements from or returning any unneeded elements to the source list
// Note, the elements added will have stale contents. Make sure the caller initialises everything appropriately
bool resize(uint32_t newSize)
{
if (mSize < newSize)
{
// Grow if needed
return grow(newSize);
}
else if (mSize > newSize)
{
return shrink(newSize);
}
return true;
}
T& operator[](uint32_t index)
{
Element* pLayer = mpElement;
HWCASSERT(index < mSize);
while (index)
{
HWCASSERT(pLayer);
pLayer = pLayer->mpNext;
index--;
}
return pLayer->mElement;
}
const T& operator[](uint32_t index) const
{
const Element* pLayer = mpElement;
HWCASSERT(index < mSize);
while (index)
{
HWCASSERT(pLayer);
pLayer = pLayer->mpNext;
index--;
}
return pLayer->mElement;
}
private:
// Helper internal class
class Element
{
public:
Element() : mpNext(NULL) {}
void clear() { mElement.clear(); }
T mElement;
Element* mpNext;
};
// Helper to remove the requested element from the front of the list
Element* pop_front()
{
HWCASSERT(mpElement && mSize);
Element* pElement = mpElement;
mpElement = mpElement->mpNext;
mSize--;
return pElement;
}
// Helper to add requested element to the front of the list
void push_front(Element* pElement)
{
HWCASSERT(pElement);
pElement->mpNext = mpElement;
mpElement = pElement;
mSize++;
}
// Helper to add requested element to the back of the list
void push_back(Element* pElement)
{
Element **ppElement = &mpElement;
while (*ppElement)
ppElement = &((*ppElement)->mpNext);
*ppElement = pElement;
pElement->mpNext = NULL;
mSize++;
}
private:
const static uint32_t cMaxUnusedElements = 64;
static HwcList<T> sUnusedElements;
Element* mpElement;
uint32_t mSize;
};
template <class T> HwcList<T> HwcList<T>::sUnusedElements;
};
//}; // namespace hwc
//}; // namespace ufo
//}; // namespace intel
#endif // INTEL_UFO_HWC_HWCLIST_H
| true |
be2b9ba5801d1a95f31d1ca585bec6ad84bff826 | C++ | MarcToussaint/rai | /rai/Optim/retired/optimization_obsolete.cxx | UTF-8 | 30,101 | 2.5625 | 3 | [
"MIT"
] | permissive | /* ------------------------------------------------------------------
Copyright (c) 2011-2020 Marc Toussaint
email: toussaint@tu-berlin.de
This code is distributed under the MIT License.
Please see <root-path>/LICENSE for details.
-------------------------------------------------------------- */
//===========================================================================
//added Sep 2013
///// return type for a function that returns a square potential $f(x) = x^T A x - 2 a^T x + c
//struct SqrPotential;
///// return type for a function that returns a square potential $f(x,y) = [x,y]^T [A,C; C^T,B] [x,y] - 2 [a,b]^T [x,y] + c$
//struct PairSqrPotential;
/// Given a chain $x_{0:T}$ of variables, implies a cost function
/// $f(x) = \sum_{i=0}^T f_i(x_i)^T f_i(x_i) + \sum_{i=1}^T f_{ij}(x_i,x_j)^T f_{ij}(x_i,x_j)$
/// and we can access local Jacobians of f_i and f_{ij}
struct VectorChainFunction;
///// Given a chain $x_{0:T}$ of variables, implies a cost function
///// $f(x) = \sum_{i=0}^T f_i(x_i) + \sum_{i=1}^T f_{ij}(x_i,x_j)$
///// and we can access local SqrPotential approximations of f_i and f_{ij}
//struct QuadraticChainFunction;
//double evaluateSP(const SqrPotential& S, const arr& x) {
// return scalarProduct(x,S.A*x) - 2.*scalarProduct(S.a,x) + S.c;
//}
//double evaluatePSP(const PairSqrPotential& S, const arr& x, const arr& y) {
// double f=0.;
// f += scalarProduct(x,S.A*x);
// f += scalarProduct(y,S.B*y);
// f += 2.*scalarProduct(x,S.C*y);
// f -= 2.*scalarProduct(S.a,x);
// f -= 2.*scalarProduct(S.b,y);
// f += S.c;
// return f;
//}
//double evaluateCSP(const rai::Array<SqrPotential>& fi, const rai::Array<PairSqrPotential>& fij, const arr& x) {
// double f=0.;
// uint T=fi.N-1;
// for(uint t=0; t<=T; t++) {
// f += evaluateSP(fi(t), x[t]);
// if(t<T) f += evaluatePSP(fij(t), x[t], x[t+1]);
// }
// return f;
//}
//void recomputeChainSquarePotentials(rai::Array<SqrPotential>& fi, rai::Array<PairSqrPotential>& fij, QuadraticChainFunction& f, const arr& x, uint& evals) {
// uint T=fi.N-1;
// for(uint t=0; t<=T; t++) {
// f.fq_i(fi(t) , t, x[t]); evals++;
// if(t<T) f.fq_ij(fij(t), t, t+1, x[t], x[t+1]);
// }
//}
//void sanityCheckUptodatePotentials(const rai::Array<SqrPotential>& R, QuadraticChainFunction& f, const arr& x) {
// if(!sanityCheck) return;
// SqrPotential R_tmp;
// for(uint t=0; t<R.N; t++) {
// f.fq_i(R_tmp, t, x[t]);
// CHECK((maxDiff(R(t).A,R_tmp.A) + maxDiff(R(t).a,R_tmp.a) + fabs(R(t).c-R_tmp.c))<1e-6,"potentials not up-to-date");
// }
//}
//double evaluateQCF(QuadraticChainFunction& f, const arr& x) {
// double cost=0.;
// uint T=x.d0-1;
// cost += f.fq_i(NoPot, 0, x[0]);
// for(uint t=1; t<=T; t++) {
// cost += f.fq_i(NoPot, t, x[t]);
// cost += f.fq_ij(NoPairPot, t-1, t, x[t-1], x[t]);
// }
// return cost;
//}
double evaluateVCF(VectorChainFunction& f, const arr& x) {
double ncost=0., pcost=0.;
uint T=x.d0-1;
arr y;
f.fv_i(y, NoArr, 0, x[0]); ncost += sumOfSqr(y);
for(uint t=1; t<=T; t++) {
f.fv_i(y, NoArr, t, x[t]); ncost += sumOfSqr(y);
f.fv_ij(y, NoArr, NoArr, t-1, t, x[t-1], x[t]); pcost += sumOfSqr(y);
//cout <<t <<' ' <<sumOfSqr(y) <<endl;
}
//cout <<"node costs=" <<ncost <<" pair costs=" <<pcost <<endl;
return ncost+pcost;
}
/*double ScalarGraphFunction::f_total(const arr& X){
uint n=X.d0;
uintA E=edges();
double f=0.;
for(uint i=0;i<n;i++) f += fi(nullptr, i, X[i]);
for(uint i=0;i<E.d0;i++) f += fij(nullptr, nullptr, E(i,0), E(i,1), X[E(i,0)], X[E(i,1)]);
return f;
}
struct Tmp:public ScalarFunction{
ScalarGraphFunction *sgf;
double fs(arr* grad, const arr& X){
uint n=X.d0,i,j,k;
uintA E=sgf->edges();
double f=0.;
arr gi, gj;
if(grad) (*grad).resizeAs(X);
for(i=0;i<n;i++){
f += sgf->fi((grad?&gi:nullptr), i, X[i]);
if(grad) (*grad)[i]() += gi;
}
for(k=0;k<E.d0;k++){
i=E(k,0);
j=E(i,1);
f += sgf->fij((grad?&gi:nullptr), (grad?&gj:nullptr), i, j, X[i], X[j]);
if(grad) (*grad)[i]() += gi;
if(grad) (*grad)[j]() += gj;
}
return f;
}
};
Tmp convert_ScalarFunction(ScalarGraphFunction& f){
Tmp tmp;
tmp.sgf=&f;
return tmp;
}*/
/// preliminary
uint optNodewise(arr& x, VectorChainFunction& f, OptOptions o) {
struct MyVectorFunction:VectorFunction {
VectorChainFunction* f;
uint t;
arr x_ref;
uint* evals;
void fv(arr& y, arr& J, const arr& x) {
arr yij, Ji, Jj;
f->fv_i(y, J, t, x); (*evals)++;
if(t>0) {
f->fv_ij(yij, (!!J?Ji:NoArr), (!!J?Jj:NoArr), t-1, t, x_ref[t-1], x);
y.append(yij);
if(!!J) J.append(Jj);
}
if(t<f->get_T()) {
f->fv_ij(yij, (!!J?Ji:NoArr), (!!J?Jj:NoArr), t, t+1, x, x_ref[t+1]);
y.append(yij);
if(!!J) J.append(Ji);
}
}
};
uint evals = 0;
MyVectorFunction f_loc;
f_loc.f = &f;
f_loc.evals = &evals;
ofstream fil;
double fx=evaluateVCF(f, x);
if(o.verbose>0) fil.open("z.nodewise");
if(o.verbose>0) fil <<0 <<' ' <<eval_count <<' ' <<fx <<endl;
if(o.verbose>1) cout <<"optNodewise initial cost " <<fx <<endl;
OptOptions op;
op.stopTolerance=o.stopTolerance, op.stopEvals=10, op.maxStep=o.maxStep, op.verbose=0;
uint k;
for(k=0; k<o.stopIters; k++) {
arr x_old=x;
for(uint t=0; t<=f.get_T(); t++) {
f_loc.x_ref = x;
f_loc.t = t;
//checkGradient(loc_f, x[t], 1e-4);
optNewton(x[t](), f_loc, op);
if(o.verbose>1) cout <<"optNodewise " <<k <<" > " <<t <<' ' <<evaluateVCF(f, x) <<endl;
}
for(uint t=f.get_T()-1; t>0; t--) {
f_loc.x_ref = x;
f_loc.t=t;
//checkGradient(loc_f, x[t], 1e-4);
optNewton(x[t](), f_loc, op);
if(o.verbose>1) cout <<"optNodewise " <<k <<" < " <<t <<' ' <<evaluateVCF(f, x) <<endl;
}
fx = evaluateVCF(f, x);
if(o.verbose>0) fil <<evals <<' ' <<eval_count <<' ' <<fx <<endl;
if(maxDiff(x, x_old)<o.stopTolerance) break;
}
if(o.fmin_return) *o.fmin_return=fx;
if(o.verbose>0) fil.close();
if(o.verbose>1) gnuplot("plot 'z.nodewise' us 1:3 w l", nullptr, true);
return evals;
}
/// preliminary
//uint optDynamicProgramming(arr& x, QuadraticChainFunction& f, OptOptions o) {
// uint T=x.d0-1,n=x.d1;
// uint evals=0;
// arr y(x);
// double damping=o.damping;
// rai::Array<SqrPotential> V(T+1);
// rai::Array<SqrPotential> fi(T+1), fi_at_y(T+1);
// rai::Array<PairSqrPotential> fij(T), fij_at_y(T);
// arr Bbarinv(T,n,n);
// arr bbar(T,n);
// arr Id = eye(n,n);
// recomputeChainSquarePotentials(fi, fij, f, x, evals);
// //double fx = evaluateQCF(f, x);
// double fx = evaluateCSP(fi, fij, x);
// ofstream fil;
// if(o.verbose>0) fil.open("z.DP");
// if(o.verbose>0) fil <<0 <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>1) cout <<"optDP initial cost " <<fx <<endl;
// for(uint k=0; k<o.stopIters; k++) {
// //backward
// arr Bbar,C_Bbarinv;
// double cbar;
// init(V(T),n);
// for(uint t=T; t--;) {
// //f.fqi (&fi(t+1) , t+1, x[t+1]); evals++; //potentials should always be up-to-date (see recomputeChainSquarePotentials below)
// //f.fqij(&fij(t), t, t+1, x[t], x[t+1]);
// Bbar = fij(t).B + fi(t+1).A + V(t+1).A + damping*Id;
// bbar[t] = fij(t).b + fi(t+1).a + V(t+1).a + damping*x[t+1];
// cbar = fij(t).c + fi(t+1).c + V(t+1).c + damping*sumOfSqr(x[t+1]);
// inverse_SymPosDef(Bbarinv[t](), Bbar);
// V(t).c = cbar - scalarProduct(bbar[t], Bbarinv[t] * bbar[t]);
// C_Bbarinv = fij(t).C*Bbarinv[t];
// V(t).a = fij(t).a - C_Bbarinv * bbar[t];
// V(t).A = fij(t).A - C_Bbarinv * ~fij(t).C;
// }
// //forward
// arr step;
// double fy_from_V0;
// if(!o.clampInitialState) {
// arr Bbarinv0,bbar0;
// Bbar = fi(0).A + V(0).A + damping*Id;
// bbar0 = fi(0).a + V(0).a + damping*x[0];
// cbar = fi(0).c + V(0).c + damping*sumOfSqr(x[0]);
// inverse_SymPosDef(Bbarinv0, Bbar);
// step = Bbarinv0*bbar0 - y[0];
// if(o.maxStep>0. && length(step)>o.maxStep) step *= o.maxStep/length(step);
// y[0]() += step;
// //y[0] = Bbarinv0*bbar0;
// fy_from_V0 = cbar - scalarProduct(bbar0, Bbarinv0 * bbar0);
// }
// for(uint t=0; t<T; t++) {
// step = Bbarinv[t]*(bbar[t] - (~fij(t).C)*y[t]) - y[t+1];
// if(o.maxStep>0. && length(step)>o.maxStep) step *= o.maxStep/length(step);
// y[t+1]() += step;
// //y[t+1] = Bbarinv[t]*(bbar[t] - (~fij(t).C)*y[t]);
// }
// recomputeChainSquarePotentials(fi_at_y, fij_at_y, f, y, evals);
// double fy=evaluateCSP(fi_at_y, fij_at_y, y);
// if(sanityCheck) {
// double fy_exact=evaluateQCF(f, y);
// CHECK(fabs(fy-fy_exact)<1e-6,"");
// }
// if(sanityCheck) {
// //in the LGQ case, the fy above (V_0(x_0)) is exact and returns the cost-to-go
// //.. we only need to subtract the damping cost:
// double damping_cost=damping*sqrDistance(y,x);
// fy_from_V0 -= damping_cost;
// //.. but that estimate is useless in the non-linear case and we need to recompute potentials...
// //CHECK(fabs(fy_from_V0-evaluateQCF(f, y))<1e-6,"");
// }
// if(fy<=fx) {
// if(maxDiff(x,y)<o.stopTolerance) { x=y; fx=fy; break; }
// x=y;
// fx=fy;
// fi = fi_at_y;
// fij = fij_at_y;
// damping /= 5.;
// } else {
// damping *= 10.;
// }
// if(o.verbose>1) cout <<"optDP " <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>0) fil <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// }
// if(o.verbose>0) fil.close();
// if(o.verbose>1) gnuplot("plot 'z.DP' us 1:3 w l",nullptr,true);
// return evals;
//}
//void updateFwdMessage(SqrPotential& Sj, PairSqrPotential& fij, const SqrPotential& Ri, const SqrPotential& Si, double damping, const arr& x_damp) {
// SqrPotential Sbar;
// arr Sbarinv, C_Sbarinv;
// arr Id = eye(Si.A.d0,Si.A.d1);
// Sbar.A = fij.A + Ri.A + Si.A + damping*Id;
// Sbar.a = fij.a + Ri.a + Si.a + damping*x_damp;
// Sbar.c = fij.c + Ri.c + Si.c + damping*sumOfSqr(x_damp);
// inverse_SymPosDef(Sbarinv, Sbar.A);
// Sj.c = Sbar.c - scalarProduct(Sbar.a, Sbarinv * Sbar.a);
// C_Sbarinv = (~fij.C)*Sbarinv;
// Sj.a = fij.b - C_Sbarinv * Sbar.a;
// Sj.A = fij.B - C_Sbarinv * fij.C;
//}
//void updateBwdMessage(SqrPotential& Vi, PairSqrPotential& fij, const SqrPotential& Rj, const SqrPotential& Vj, double damping, const arr& x_damp) {
// SqrPotential Vbar;
// arr Vbarinv, C_Vbarinv;
// arr Id = eye(Vi.A.d0,Vi.A.d1);
// Vbar.A = fij.B + Rj.A + Vj.A + damping*Id;
// Vbar.a = fij.b + Rj.a + Vj.a + damping*x_damp;
// Vbar.c = fij.c + Rj.c + Vj.c + damping*sumOfSqr(x_damp);
// inverse_SymPosDef(Vbarinv, Vbar.A);
// Vi.c = Vbar.c - scalarProduct(Vbar.a, Vbarinv * Vbar.a);
// C_Vbarinv = fij.C*Vbarinv;
// Vi.a = fij.a - C_Vbarinv * Vbar.a;
// Vi.A = fij.A - C_Vbarinv * ~fij.C;
//}
/// preliminary
//uint optMinSumGaussNewton(arr& x, QuadraticChainFunction& f, OptOptions o) {
// struct LocalQuadraticFunction:QuadraticFunction {
// QuadraticChainFunction *f;
// uint t;
// arr x;
// SqrPotential *S,*V,*R;
// uint *evals;
// bool updateR;
// double fq(SqrPotential& S_loc, const arr& x) {
// CHECK(&S_loc,"");
// if(updateR) {
// f->fq_i(*R , t, x); (*evals)++;
// } else updateR = true;
// S_loc.A = V->A+S->A+R->A;
// S_loc.a = V->a+S->a+R->a;
// S_loc.c = V->c+S->c+R->c;
// return evaluateSP(S_loc,x);
// }
// };
// uint T=x.d0-1,n=x.d1;
// uint evals=0;
// arr y(x);
// double damping=o.damping;
// uint rejects=0;
// rai::Array<SqrPotential> V(T+1); //bwd messages
// rai::Array<SqrPotential> S(T+1); //fwd messages
// rai::Array<SqrPotential> Rx(T+1),Ry(T+1); //node potentials at x[t] (=hat x_t)
// rai::Array<PairSqrPotential> fij(T);
// for(uint t=0; t<=T; t++) { init(S(t),n); init(V(t),n); }
// //helpers
// arr Sbarinv(T+1,n,n),Vbarinv(T+1,n,n);
// arr Id = eye(n,n);
// arr C_Sbarinv,C_Vbarinv;
// //get all potentials
// recomputeChainSquarePotentials(Rx, fij, f, x, evals);
// //double fy;
// double fx = evaluateCSP(Rx, fij, x);
// //fx = evaluateQCF(f, x);
// sanityCheckUptodatePotentials(Rx, f, x);
// //update fwd & bwd messages
// for(uint t=1; t<=T; t++) updateFwdMessage(S(t), fij(t-1), Rx(t-1), S(t-1), damping, x[t-1]);
// for(uint t=T-1; t--;) updateBwdMessage(V(t), fij(t), Rx(t+1), V(t+1), damping, x[t+1]);
// ofstream fil;
// if(o.verbose>0) fil.open("z.MSGN");
// if(o.verbose>0) fil <<0 <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>1) cout <<"optMSGN initial cost " <<fx <<endl;
// for(uint k=0; k<o.stopIters; k++) {
// y=x;
// //fy=fx;
// Ry=Rx;
// sanityCheckUptodatePotentials(Ry, f, y);
// bool fwd = (k+1)%2;
// for(uint t=fwd?0:T-1; fwd?t<=T:t>0; t+=fwd?1:-1) {
// SqrPotential Vbar,Sbar;
// //update fwd & bwd messages
// if(t>0) {
// f.fq_ij(fij(t-1), t-1, t, y[t-1], y[t]);
// updateFwdMessage(S(t), fij(t-1), Ry(t-1), S(t-1), damping, x[t-1]);
// }
// if(t<T) {
// f.fq_ij(fij(t), t, t+1, y[t], y[t+1]);
// updateBwdMessage(V(t), fij(t), Ry(t+1), V(t+1), damping, x[t+1]);
// }
// sanityCheckUptodatePotentials(Ry, f, y);
// if(!t && o.clampInitialState) {
// y[0] = x[0];
// Ry(0)=Rx(0);
// continue;
// }
// //iterate GaussNewton to find a new local y[t]
// LocalQuadraticFunction f_loc;
// f_loc.f = &f;
// f_loc.t = t;
// f_loc.evals = &evals;
// f_loc.S = &S(t);
// f_loc.V = &V(t);
// f_loc.R = &Ry(t); //by setting this as reference, each recomputation of R is stored directly in R(t)
// f_loc.x = x[t];
// f_loc.updateR=false;
// OptOptions op;
// op.stopTolerance=o.stopTolerance, op.stopEvals=10, op.maxStep=o.maxStep, op.verbose=0;
// NIY//optNewton(y[t](), f_loc, op);
// sanityCheckUptodatePotentials(Ry, f, y);
// }
// //compute total cost
// double fy=evaluateCSP(Ry, fij, y);
// if(sanityCheck) {
// double fy_exact=evaluateQCF(f, y);
// CHECK(fabs(fy-fy_exact)<1e-6,"");
// }
// if(fy<=fx) {
// rejects=0;
// if(maxDiff(x,y)<o.stopTolerance) { x=y; fx=fy; break; }
// x=y;
// fx=fy;
// Rx=Ry;
// damping *= .2;
// } else {
// rejects++;
// if(rejects>=5 && damping>1e3) break; //give up //&& maxDiff(x,y)<stoppingTolerance
// damping *= 10.;
// }
// if(o.verbose>1) cout <<"optMSGN " <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>0) fil <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// }
// if(o.verbose>1) cout <<"optMSGN " <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>0) fil <<evals <<' ' <<eval_cost <<' ' <<fx <<' ' <<damping <<endl;
// if(o.verbose>0) fil.close();
// if(o.verbose>1) gnuplot("plot 'z.MSGN' us 1:3 w l",nullptr,true);
// return evals;
//}
struct sConvert {
struct VectorChainFunction_ScalarFunction:ScalarFunction { //actual converter objects
VectorChainFunction* f;
VectorChainFunction_ScalarFunction(VectorChainFunction& _f):f(&_f) {}
virtual double fs(arr& grad, arr& H, const arr& x);
};
struct VectorChainFunction_VectorFunction:VectorFunction { //actual converter objects
VectorChainFunction* f;
VectorChainFunction_VectorFunction(VectorChainFunction& _f):f(&_f) {}
virtual void fv(arr& y, arr& J, const arr& x);
};
// struct VectorChainFunction_QuadraticChainFunction:QuadraticChainFunction {
// VectorChainFunction *f;
// VectorChainFunction_QuadraticChainFunction(VectorChainFunction& _f):f(&_f) {}
// virtual uint get_T() { return f->get_T(); }
// virtual double fq_i(SqrPotential& S, uint i, const arr& x_i);
// virtual double fq_ij(PairSqrPotential& S, uint i, uint j, const arr& x_i, const arr& x_j);
// };
// #ifndef libRoboticsCourse
// struct ControlledSystem_1OrderMarkovFunction:KOrderMarkovFunction {
// ControlledSystem *sys;
// ControlledSystem_1OrderMarkovFunction(ControlledSystem& _sys):sys(&_sys){}
// uint get_T(){ return sys->get_T(); }
// uint get_k(){ return 1; }
// uint get_n(){ return sys->get_xDim(); }
// uint get_m(uint t);
// void phi_t(arr& phi, arr& J, uint t, const arr& x_bar, const arr& z=NoArr, const arr& J_z=NoArr);
// };
// struct ControlledSystem_2OrderMarkovFunction:KOrderMarkovFunction {
// ControlledSystem *sys;
// ControlledSystem_2OrderMarkovFunction(ControlledSystem& _sys):sys(&_sys){}
// uint get_T(){ return sys->get_T(); }
// uint get_k(){ return 2; }
// uint get_n(){ return sys->get_xDim()/2; }
// uint get_m(uint t);
// void phi_t(arr& phi, arr& J, uint t, const arr& x_bar, const arr& z=NoArr, const arr& J_z=NoArr);
// };
// #endif
};
Convert::operator VectorChainFunction& () {
if(!self->vcf) {
}
if(!self->vcf) HALT("");
return *self->vcf;
}
//Convert::operator QuadraticChainFunction&() {
// if(!self->qcf) {
// if(self->vcf) self->qcf = new sConvert::VectorChainFunction_QuadraticChainFunction(*self->vcf);
// }
// if(!self->qcf) HALT("");
// return *self->qcf;
//}
double sConvert::VectorChainFunction_ScalarFunction::fs(arr& grad, arr& H, const arr& x) {
uint T=f->get_T();
arr z; z.referTo(x);
z.reshape(T+1, z.N/(T+1)); //x as chain representation (splitted in nodes assuming each has same dimensionality!)
double cost=0.;
arr y, J, Ji, Jj;
if(!!grad) {
grad.resizeAs(x);
grad.setZero();
}
if(!!H) NIY;
for(uint t=0; t<=T; t++) { //node potentials
f->fv_i(y, (!!grad?J:NoArr), t, z[t]);
cost += sumOfSqr(y);
if(!!grad) {
grad[t]() += 2.*(~y)*J;
}
}
for(uint t=0; t<T; t++) {
f->fv_ij(y, (!!grad?Ji:NoArr), (!!grad?Jj:NoArr), t, t+1, z[t], z[t+1]);
cost += sumOfSqr(y);
if(!!grad) {
grad[t]() += 2.*(~y)*Ji;
grad[t+1]() += 2.*(~y)*Jj;
}
}
return cost;
}
void sConvert::VectorChainFunction_VectorFunction::fv(arr& y, arr& J, const arr& x) {
uint T=f->get_T();
arr z; z.referTo(x);
z.reshape(T+1, z.N/(T+1)); //x as chain representation (splitted in nodes assuming each has same dimensionality!)
//probing dimensionality (ugly..)
arr tmp;
f->fv_i(tmp, NoArr, 0, z[0]);
uint di=tmp.N; //dimensionality at nodes
if(T>0) f->fv_ij(tmp, NoArr, NoArr, 0, 1, z[0], z[1]);
uint dij=tmp.N; //dimensionality at pairs
//resizing things:
arr yi(T+1, di); //the part of y which will collect all node potentials
arr yij(T, dij); //the part of y which will collect all pair potentials
arr Ji; Ji .resize(uintA{T+1, di, z.d0, z.d1}); //first indices as yi, last: gradient w.r.t. x
arr Jij; Jij.resize(uintA{T, dij, z.d0, z.d1}); //first indices as yi, last: gradient w.r.t. x
Ji.setZero();
Jij.setZero();
arr y_loc, J_loc, Ji_loc, Jj_loc;
uint t, i, j;
//first collect all node potentials
for(t=0; t<=T; t++) {
f->fv_i(y_loc, (!!J?J_loc:NoArr), t, z[t]);
yi[t] = y_loc;
if(!!J) {
for(i=0; i<di; i++) for(j=0; j<z.d1; j++) //copy into the right place...
Ji.elem(uintA{t, i, t, j}) = J_loc(i, j);
}
}
//then collect all pair potentials
for(t=0; t<T; t++) {
f->fv_ij(y_loc, (!!J?Ji_loc:NoArr), (!!J?Jj_loc:NoArr), t, t+1, z[t], z[t+1]);
yij[t] = y_loc;
if(!!J) {
for(i=0; i<dij; i++) for(j=0; j<z.d1; j++) //copy into the right place...
Jij.elem(uintA{t, i, t, j}) = Ji_loc(i, j);
for(i=0; i<dij; i++) for(j=0; j<z.d1; j++) //copy into the right place...
Jij.elem(uintA{t, i, t+1, j}) = Jj_loc(i, j);
}
}
yi.reshape((T+1)*di);
Ji.reshape((T+1)*di, x.N);
yij.reshape(T*dij);
Jij.reshape(T*dij, x.N);
y=yi; y.append(yij);
if(!!J) { J=Ji; J.append(Jij); }
}
//double sConvert::VectorChainFunction_QuadraticChainFunction::fq_i(SqrPotential& S, uint i, const arr& x_i) {
// arr y,J;
// f->fv_i(y, (!!S?J:NoArr), i, x_i);
// if(!!S) {
// S.A=~J * J;
// S.a=~J * (J*x_i - y);
// S.c=sumOfSqr(J*x_i - y);
// }
// return sumOfSqr(y);
//}
//double sConvert::VectorChainFunction_QuadraticChainFunction::fq_ij(PairSqrPotential& S, uint i, uint j, const arr& x_i, const arr& x_j) {
// arr y,Ji,Jj;
// f->fv_ij(y, (!!S?Ji:NoArr), (!!S?Jj:NoArr), i, j, x_i, x_j);
// if(!!S) {
// S.A=~Ji*Ji;
// S.B=~Jj*Jj;
// S.C=~Ji*Jj;
// S.a=~Ji*(Ji*x_i + Jj*x_j - y);
// S.b=~Jj*(Ji*x_i + Jj*x_j - y);
// S.c=sumOfSqr(Ji*x_i + Jj*x_j - y);
// }
// return sumOfSqr(y);
//}
// #ifndef libRoboticsCourse
// uint sConvert::ControlledSystem_1OrderMarkovFunction::get_m(uint t){
// uint T=get_T();
// if(t==0) return sys->get_xDim() + sys->get_phiDim(t) + sys->get_xDim();
// if(t==T-1) return sys->get_xDim() + sys->get_phiDim(t) + sys->get_phiDim(T);
// return sys->get_xDim() + sys->get_phiDim(t);
// } //dynamic gap plus task costs
// void sConvert::ControlledSystem_1OrderMarkovFunction::phi_t(arr& phi, arr& J, uint t, const arr& x_bar, const arr& z, const arr& J_z){
// arr x0(x_bar,0);
// arr x1(x_bar,1);
// sys->setx(x0);
// //dynamics
// arr J0, J1;
// getTransitionCostTerms(*sys, true, phi, J0, J1, x0, x1, t);
// if(!!J){
// J.resize(J0.d0, J0.d1+J1.d1);
// J.setMatrixBlock(J0,0,0);
// J.setMatrixBlock(J1,0,J0.d1);
// }
// //task phi w.r.t. x0
// arr _phi, _J;
// sys->getTaskCosts(_phi, _J, t);
// _J.insColumns(x0.N, x1.N);
// for(uint i=0;i<_J.d0;i++) for(uint j=x0.N;j<_J.d1;j++) _J(i,j) = 0.;
// phi.append(_phi);
// if(!!J) J.append(_J);
// if(t==get_T()-1){ //second task phi w.r.t. x1 in the final factor
// sys->setx(x1);
// sys->getTaskCosts(_phi, _J, t+1);
// phi.append(_phi);
// if(!!J){
// _J.insColumns(0, x0.N);
// for(uint i=0;i<_J.d0;i++) for(uint j=0;j<x1.N;j++) _J(i,j) = 0.;
// J.append(_J);
// }
// }
// if(t==0){ //initial x0 constraint
// double prec=1e4;
// arr sys_x0;
// sys->get_x0(sys_x0);
// phi.append(prec*(x0-sys_x0));
// if(!!J){
// _J.setDiag(prec,x0.N);
// _J.insColumns(x0.N, x1.N);
// for(uint i=0;i<_J.d0;i++) for(uint j=0;j<x1.N;j++) _J(i,x0.N+j) = 0.;
// J.append(_J);
// }
// }
// }
// uint sConvert::ControlledSystem_2OrderMarkovFunction::get_m(uint t){
// uint T=get_T();
// uint nq = get_n();
// if(t==0) return 3*nq + sys->get_phiDim(0) + sys->get_phiDim(1);
// if(t==T-2) return nq + sys->get_phiDim(t+1) + sys->get_phiDim(T);
// return nq + sys->get_phiDim(t+1);
// } //dynamic-gap task-costs
// void sConvert::ControlledSystem_2OrderMarkovFunction::phi_t(arr& phi, arr& J, uint t, const arr& x_bar, const arr& z, const arr& J_z){
// uint n=get_n();
// CHECK(x_bar.d0==3 && x_bar.d1==n,"");
// arr q0(x_bar,0);
// arr q1(x_bar,1);
// arr q2(x_bar,2);
// double tau=sys->get_tau();
// double _tau2=1./(tau*tau);
// arr x0=q0; x0.append((q1-q0)/tau);
// arr x1=q1; x1.append((q2-q0)/(2.*tau));
// arr x2=q2; x2.append((q2-q1)/tau);
// //dynamics
// double h=1e-1;
// phi = h*_tau2*(q2-2.*q1+q0); //penalize acceleration
// if(!!J){ //we todoalso need to return the Jacobian
// J.resize(n,3,n);
// J.setZero();
// for(uint i=0;i<n;i++){ J(i,2,i) = 1.; J(i,1,i) = -2.; J(i,0,i) = 1.; }
// J.reshape(n,3*n);
// J *= h*_tau2;
// }
// //task phi w.r.t. x2
// arr _phi, _J;
// sys->setx(x1);
// sys->getTaskCosts(_phi, _J, t+1);
// phi.append(_phi);
// if(!!J) {
// arr Japp(_J.d0,3*n);
// Japp.setZero();
// Japp.setMatrixBlock(_J.sub(0,-1,0,n-1), 0, 1*n); //w.r.t. q1
// Japp.setMatrixBlock((-0.5/tau)*_J.sub(0,-1,n,-1), 0, 0); //w.r.t. q0
// Japp.setMatrixBlock(( 0.5/tau)*_J.sub(0,-1,n,-1), 0, 2*n); //w.r.t. q2
// J.append(Japp);
// }
// if(t==0){
// double prec=1e4;
// arr sys_x0;
// sys->get_x0(sys_x0);
// phi.append(prec*(x0-sys_x0));
// _J = diag(prec,x0.N);
// if(!!J){
// arr Japp(_J.d0,3*n);
// Japp.setZero();
// Japp.setMatrixBlock(_J.sub(0,-1,0,n-1) - (1./tau)*_J.sub(0,-1,n,-1), 0, 0); //w.r.t. q0
// Japp.setMatrixBlock((1./tau)*_J.sub(0,-1,n,-1), 0, 1*n); //w.r.t. q1
// J.append(Japp);
// }
// }
// if(t==0){ //also add costs w.r.t. q0 and (q1-q0)/tau
// sys->setx(x0);
// sys->getTaskCosts(_phi, _J, 0);
// phi.append(_phi);
// if(!!J) {
// arr Japp(_J.d0,3*n);
// Japp.setZero();
// Japp.setMatrixBlock(_J.sub(0,-1,0,n-1) - (1./tau)*_J.sub(0,-1,n,-1), 0, 0); //w.r.t. q0
// Japp.setMatrixBlock((1./tau)*_J.sub(0,-1,n,-1), 0, 1*n); //w.r.t. q1
// J.append(Japp);
// }
// }
// uint T=get_T();
// if(t==T-2){
// sys->setx(x2);
// sys->getTaskCosts(_phi, _J, T);
// phi.append(_phi);
// if(!!J) {
// arr Japp(_J.d0,3*n);
// Japp.setZero();
// Japp.setMatrixBlock(_J.sub(0,-1,0,n-1) + (1./tau)*_J.sub(0,-1,n,-1), 0, 2*n); //w.r.t. q2
// Japp.setMatrixBlock((-1./tau)*_J.sub(0,-1,n,-1), 0, 1*n); //w.r.t. q1
// J.append(Japp);
// }
// }
// }
// #endif
VectorChainCost::VectorChainCost(uint _T, uint _n) {
T=_T; n=_n;
A.resize(T+1, n, n); a.resize(T+1, n);
Wi.resize(T, n, n); Wj.resize(T, n, n); w.resize(T, n);
for(uint t=0; t<=T; t++) generateConditionedRandomProjection(A[t](), n, 100.);
for(uint t=0; t<T; t++) {
generateConditionedRandomProjection(Wi[t](), n, 100.);
generateConditionedRandomProjection(Wj[t](), n, 100.);
}
rndUniform(a, -1., 1., false);
rndUniform(w, -1., 1., false);
nonlinear=false;
}
void VectorChainCost::fv_i(arr& y, arr* J, uint i, const arr& x_i) {
if(!nonlinear) {
y = A[i]*x_i + a[i];
if(J) *J = A[i];
} else {
arr xi=atan(x_i);
y = A[i]*xi + a[i];
if(J) {
arr gi(xi.N);
for(uint k=0; k<gi.N; k++) gi(k) = 1./(1.+x_i(k)*x_i(k));
*J = A[i]*diag(gi);
}
}
}
void VectorChainCost::fv_ij(arr& y, arr* Ji, arr* Jj, uint i, uint j, const arr& x_i, const arr& x_j) {
if(!nonlinear) {
y=Wi[i]*x_i + Wj[i]*x_j + w[i];
if(Ji) *Ji = Wi[i];
if(Jj) *Jj = Wj[i];
} else {
arr xi=atan(x_i);
arr xj=atan(x_j);
y=Wi[i]*xi + Wj[i]*xj + w[i];
if(Ji && Ji) {
arr gi(xi.N), gj(xi.N);
for(uint k=0; k<gi.N; k++) gi(k) = 1./(1.+x_i(k)*x_i(k));
for(uint k=0; k<gj.N; k++) gj(k) = 1./(1.+x_j(k)*x_j(k));
*Ji = Wi[i]*diag(gi);
*Jj = Wj[i]*diag(gj);
}
}
}
SlalomProblem::SlalomProblem(uint _T, uint _K, double _margin, double _w, double _power) {
T=_T;
n=2;
K=_K;
margin = _margin;
w = _w;
power = _power;
}
double border(double* grad, double x, double power=8.) {
if(x>0.) { if(grad) *grad=0.; return 0.; }
double y = pow(x, power);
if(grad) *grad = power*pow(x, power-1.);
return y;
}
double tannenbaum(double* grad, double x, double power=8.) {
double y=x*x;
if(grad) *grad = power*pow(y-floor(y), power-1.) * (2.*x);
y=floor(y) + pow(y-floor(y), power);
return y;
}
void SlalomProblem::fv_i(arr& y, arr& J, uint i, const arr& x_i) {
eval_count++;
CHECK_EQ(x_i.N, 2, "");
y.resize(1); y(0)=0.;
if(!!J) { J.resize(1, 2); J.setZero(); }
if(!(i%(T/K))) {
uint obstacle=i/(T/K);
if(obstacle&1) { //top obstacle
double d=(x_i(0)-1.)/margin;
// y(0) = tannenbaum((J?&(*J)(0,0):nullptr), d, power);
y(0) = border((!!J?&J(0, 0):nullptr), d, power);
if(!!J) J(0, 0) /= margin;
} else {
double d=-(x_i(0)+1.)/margin;
// y(0) = tannenbaum((J?&J(0,0):nullptr), d, power);
y(0) = border((!!J?&J(0, 0):nullptr), d, power);
if(!!J) J(0, 0) /= -margin;
}
}
}
void SlalomProblem::fv_ij(arr& y, arr& Ji, arr& Jj, uint i, uint j, const arr& x_i, const arr& x_j) {
y.resize(1);
double tau=.01;
arr A= {1., tau, 0., 1.}; A.reshape(2, 2);
arr M=w*diag({2./(tau*tau), 1./tau}); //penalize variance in position & in velocity (control)
y=M*(x_j - A*x_i);
if(!!Ji) { Ji = -M*A; }
if(!!Jj) { Jj = M; }
}
//===========================================================================
#include "optimization_obsolete.h"
#ifdef RAI_GSL
#include <gsl/gsl_cdf.h>
bool DecideSign::step(double x) {
N++;
sumX+=x;
sumXX+=x*x;
if(N<=10) return false;
if(!sumX) return true;
double m=sumX/N;
double s=sqrt((sumXX-sumX*m)/(N-1));
double t=sqrt(N)*fabs(m)/s;
double T=gsl_cdf_tdist_Pinv(1.-1e-6, N-1); //decide with error-prob 1e-4 if sign is significant
if(t>T) return true;
return false;
}
#else
bool DecideSign::step(double x) { NIY; }
#endif
void OnlineRprop::init(OptimizationProblem* _m, double initialRate, uint _N, const arr& w0) {
rprop.init(initialRate);
t=0;
m=_m;
N=_N;
perm.setRandomPerm(N);
w=w0;
signer.resize(w.N);
for(uint i=0; i<w.N; i++) signer(i).init();
l=0.;
e=0.;
rai::open(log, "log.sgd");
}
void OnlineRprop::step() {
arr grad;
double err;
l += m->loss(w, perm(t%N), &grad, &err);
e += err;
for(uint i=0; i<w.N; i++) {
if(signer(i).step(grad(i))) { //signer is certain
grad(i) = signer(i).sign(); //hard assign the gradient to +1 or -1
rprop.step(w, grad, &i); //make an rprop step only in this dimension
signer(i).init();
//cout <<"making step in " <<i <<endl;
} else if(signer(i).N>1000) {
grad(i) = 0.;
rprop.step(w, grad, &i); //make an rprop step only in this dimension
signer(i).init();
//cout <<"assuming 0 grad in " <<i <<endl;
}
}
log <<t
<<" time= " <<rai::timerRead()
<<" loss= " <<l/(t%BATCH+1)
<<" err= " <<e/(t%BATCH+1)
<<endl;
cout <<t
<<" time= " <<rai::timerRead()
<<" loss= " <<l/(t%BATCH+1)
<<" err= " <<e/(t%BATCH+1)
<<endl;
t++;
if(!(t%N)) perm.setRandomPerm(N);
if(!(t%BATCH)) {
l=0.;
e=0.;
}
}
| true |
7eaf073391bd4eb8c41f4a47a9d8988333c5d2d0 | C++ | KitFung/competitive-programming | /hdu1847.cpp | UTF-8 | 1,478 | 3.140625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#define MAXN 1010
/**
当 g(x)=k 时,表明对于任意一个 0≤i<k,都存在 x 的一个后继 y 满足 g(y)=i。也就是说,当某枚棋子的 SG 值 是 k 时,我们可以把它变成 0、变成 1、⋯、变成 k−1,但绝对不能保持 k 不变。不知道你能不能根据这个联想到Nim游戏,Nim游戏的规则就是:每次 选择一堆数量为 k 的石子,可以把它变成 0、变成 1、…、变成 k−1,但绝对不能保持 k不变。这表明,如果将 n 枚棋子所在的顶点的 SG值看 作 n 堆相应数量的石子,那么这个Nim游戏的每个必胜策略都对应于原来这 n 枚棋子的必胜策略!这也与以下结论(Sprague-Grundy Theorem)相对应:
**/
int SG[MAXN], able[MAXN], f[MAXN];
const int choose = 9;
void init() {
f[0] = 1;
for(int i = 1; i <= choose; ++i)
f[i] = f[i-1]*2;
}
void GetSG(int n) {
memset(SG, 0, sizeof(SG));
for(int i = 0; i <= n; ++i) {
memset(able, 0, sizeof(able));
for(int j = 0; j <= choose && f[j] <= i; ++j)
able[SG[i-f[j]]] = 1;
for(int j = 0; j <= n; ++j)
if(!able[j]) {
SG[i] = j;
break;
}
}
}
int main() {
init();
GetSG(MAXN);
int n;
while(scanf("%d", &n) != EOF) {
if(SG[n] != 0)
printf("Kiki\n");
else
printf("Cici\n");
}
return 0;
} | true |
127b4dae8e25a346729c36cbc09a484155ca241d | C++ | BisonRobotics/NRMC2019 | /src/utilities/src/config.cpp | UTF-8 | 1,272 | 2.578125 | 3 | [] | no_license | #include <utilities/config.h>
using namespace utilities;
Config::Config(std::string package_name) : package_name(package_name)
{
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, std::string ¶m, std::string default_param)
{
nh->param<std::string>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam::%s]: %s = %s", package_name.c_str(), nh->getNamespace().c_str(), name.c_str(), param.c_str());
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, int ¶m, int default_param)
{
nh->param<int>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam]: %s = %i", package_name.c_str(), name.c_str(), param);
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, double ¶m, double default_param)
{
nh->param<double>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam]: %s = %f", package_name.c_str(), name.c_str(), param);
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, bool ¶m, bool default_param)
{
nh->param<bool>(name, param, default_param);
if (param)
{
ROS_INFO("[%s::Config::loadParam]: %s = true", package_name.c_str(), name.c_str());
}
else
{
ROS_INFO("[%s::Config::loadParam]: %s = false", package_name.c_str(), name.c_str());
}
} | true |
793b68d3230d84a1980b1325f4e338758055242b | C++ | alourei/Digit | /DetectorPadGeometry.C | UTF-8 | 3,151 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include "DetectorPadGeometry.h"
ClassImp(DetectorPadGeometry);
DetectorPadGeometry::DetectorPadGeometry(){
//Default Constructor
}
DetectorPadGeometry::DetectorPadGeometry(const Int_t nRows){
X0=-90;
Y0=-30;
numberOfRows=nRows;
numberOfColumns=new Int_t[numberOfRows];
padSizeX=new Int_t[numberOfRows];
padSizeY=new Int_t[numberOfRows];
}
DetectorPadGeometry::~DetectorPadGeometry(){
delete[] numberOfColumns;
delete[] padSizeX;
delete[] padSizeY;
}
void DetectorPadGeometry::SetPadSizesX(Int_t *size){
for(Int_t i=0;i<numberOfRows;i++){
SetPadSizeX(i,size[i]);
}
}
void DetectorPadGeometry::SetPadSizesY(Int_t *size){
for(Int_t i=0;i<numberOfRows;i++){
SetPadSizeY(i,size[i]);
}
}
void DetectorPadGeometry::SetNumberOfColumns(Int_t *column){
for(Int_t i=0;i<numberOfRows;i++){
SetNumberOfColumns(i,column[i]);
}
}
Int_t DetectorPadGeometry::GetRowNumber(TVector3 position){
Double_t x=position.X();
Double_t z=position.Z();
Double_t sumLength=Y0;
Int_t row=-1;
for(Int_t i=0;i<numberOfRows;i++){
//cout<<"X "<<x<<" pad "<<padSizeY[i]<<" Sum "<<sumLength<<endl;
if(x>sumLength && x<sumLength+padSizeY[i]){
row=i+1;
break;
}
else
sumLength+=padSizeY[i];
}
return row;
}
Int_t DetectorPadGeometry::GetColumnNumber(TVector3 position){
Int_t Row=GetRowNumber(position);
//cout<<Row<<endl;
Double_t z=position.Z();
Double_t sumLength=X0;
Int_t column=-1;
for(Int_t i=0;i<numberOfColumns[Row-1];i++){
//cout<<"X "<<z<<" pad "<<padSizeX[Row-1]<<" Sum "<<sumLength<<endl;
if(z>sumLength && z<sumLength+padSizeX[Row-1]){
column=i+1;
break;
}
else
sumLength+=padSizeX[Row-1];
}
return column;
}
Int_t DetectorPadGeometry::CalculatePad(Int_t row,Int_t column){
//cout<<"row "<<row<<" nCols["<<row<<"]"<<numberOfColumns[row-1]<<endl;
if(row<0 || row>numberOfRows||column>numberOfColumns[row-1]||column<=0)
return -1;
else{
Int_t pad=0;
for(Int_t i=0;i<row;i++){
for(Int_t j=0;j<numberOfColumns[i-1];j++){
pad++;
}
}
return pad+column;
}
}
Int_t DetectorPadGeometry::CalculatePad(TVector3 position){
Int_t row=GetRowNumber(position);
Int_t column=GetColumnNumber(position);
return CalculatePad(row,column);
}
void DetectorPadGeometry::AddBinContent(Int_t bin,Double_t content){
Double_t value=this->GetBinContent(bin);
value+=content;
this->SetBinContent(bin,value);
return;
}
void DetectorPadGeometry::ConstructGeometry(){
Int_t sumX=X0;
Int_t sumY=Y0;
for(Int_t row=0;row<numberOfRows;row++){
for(Int_t column=0;column<numberOfColumns[row];column++){
numberOfPads++;
this->AddBin(sumX+column*padSizeX[row],sumY,sumX+(column+1)*padSizeX[row],sumY+(1)*padSizeY[row]);
cout<<row<<" "<<column<<" Bin "<<sumX+column*padSizeX[row]<<" "<<sumY<<" "<<sumX+(column+1)*padSizeX[row]<<" "<<sumY+(1)*padSizeY[row]<<endl;
}
//sumX+=padSizeX[row];
sumY+=padSizeY[row];
cout<<"------------------------------------------------------------------"<<endl;
}
}
| true |
f88f1b21a2e440c4e38085991bc7c4ce44f3a320 | C++ | PennTao/TestGUI | /socketcomm.cpp | UTF-8 | 833 | 2.953125 | 3 | [] | no_license | #include "socketcomm.h"
SocketComm::SocketComm(QObject *parent) :
QObject(parent)
{
}
void SocketComm::connectToServer(QString host, qint16 port){
socket = new QTcpSocket();
socket->connectToHost(host,port);
socket->waitForConnected(2000);
connect(socket,SIGNAL(connected()),this,SLOT(onConnect()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(onDisconnect()),Qt::DirectConnection);
}
void SocketComm::sendToServer(QString & data){
QByteArray outData;
outData.append(data);
socket->write(outData);
qDebug() << "Sending data, data = "<< data;
}
void SocketComm::disconnectFromServer(){
socket->close();
}
void SocketComm::onConnect()
{
qDebug() << "Connected to Server";
}
void SocketComm::onDisconnect()
{
qDebug() << "Disconnected from Server";
}
| true |
33be546c33a2381423c51ae0952a8d8b3fb0c1f1 | C++ | moevm/oop | /6304/Timofeev_A/lab2/basis.cpp | UTF-8 | 1,322 | 3.484375 | 3 | [] | no_license | #include "basis.h"
Point::Point()
{
x = 0.0;
y = 0.0;
}
Point::Point(double _x, double _y)
: x(_x), y(_y)
{
}
void Point::Set_X(double _x)
{
x = _x;
}
void Point::Set_Y(double _y)
{
y = _y;
}
double Point::Get_X() const
{
return this->x;
}
double Point::Get_Y() const
{
return this->y;
}
Colour::Colour(const int red, const int green, const int blue)
{
Red = red;
Blue = blue;
Green = green;
}
void Colour::SetColour(int _Red, int _Green, int _Blue)
{
Red = _Red;
Green = _Green;
Blue = _Blue;
}
int Colour::GetRed() const
{
return Red;
}
int Colour::GetGreen() const
{
return Green;
}
int Colour::GetBlue() const
{
return Blue;
}
Point operator+(const Point & lhs, const Point & rhs)
{
return Point(lhs.Get_X() + rhs.Get_X(), lhs.Get_Y() + rhs.Get_Y());
}
Point operator-(const Point & lhs, const Point & rhs)
{
return Point(lhs.Get_X() - rhs.Get_X(), lhs.Get_Y() - rhs.Get_Y());
}
ostream& operator<<(ostream & stream, const Colour& rgb)
{
stream << "Red = " << rgb.GetRed()
<< " Green = " << rgb.GetGreen()
<< " Blue = " << rgb.GetBlue() << endl;
return stream;
}
ostream & operator<<(ostream & stream, const Point & p)
{
stream << "x = " << p.Get_X() << ", y = " << p.Get_Y();
return stream;
} | true |
ad8ebac47fd4937282393a433a984b00ff811bbe | C++ | alexandraback/datacollection | /solutions_5686275109552128_1/C++/Prime21/B.cpp | GB18030 | 1,505 | 2.515625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <queue>
#include <set>
#include <map>
#define REP(I,A,B) for(int I=A,END=B;I<=END;I++)
#define REPD(I,A,B) for(int I=A,END=B;I>=END;I--)
#define RI(X) scanf("%d",&X)
#define RS(X) scanf("%s",&X)
#define GCH getchar()
#define PCH(X) putchar(X)
#define MAX(A,B) (((A)>(B))?(A):(B))
#define MIN(A,B) (((A)<(B))?(A):(B))
#define MS(X,Y) memset(X,Y,sizeof(X))
#define MC(X,Y,var,len) memcpy((X),(Y),sizeof(var)*(len))
#define debug(...) fprintf(stderr,__VA_ARGS__)
using namespace std;
/*
һȷ
ôǼһд k
ȻǿԼÿһ ֮ǰҪֳɼ
*/
const int MAXN=1005;
int d;
int p[MAXN]={0};
int ans;
void open()
{
freopen("B.in","r",stdin);
freopen("B.out","w",stdout);
}
void close()
{
fclose(stdin);
fclose(stdout);
}
void init()
{
RI(d);
p[0]=0;
REP(i,1,d)
{
RI(p[i]);
p[0]=max(p[0],p[i]);
}
ans=p[0];
}
void work()
{
int tmp=0;
REP(x,1,p[0])
{
tmp=x;
REP(i,1,d)
tmp+=p[i]/x+(p[i]%x!=0)-1;
if (ans>tmp)
ans=tmp;
}
printf("%d\n",ans);
}
int main()
{
open();
int _=0;
RI(_);
REP(__,1,_)
{
printf("Case #%d: ",__);
init();
work();
}
init();
close();
return 0;
}
| true |
57023666e4442fa68169787a5eb74c86dbcc7da5 | C++ | MugenMan/mugen | /61_бинарн ifstream.cpp | UTF-8 | 437 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
int main()
{
int a;
short i;
//std::cout<<"Enter number: "<<std::flush;
//std::cin >> a;
std::ifstream f("binary.txt", std::ios::binary);
while (!f.eof())
{
while (f.read((char *)&i, sizeof(short)))
f.read((char *)&i, sizeof(short));
std::cout << i*3 << std::endl;
//std::cout << a << std::endl;
}
f.close();
} | true |
f41f7bd70cf2e17038ca5e5f3b27fc32f24bfbed | C++ | ZNLeskowsky/znl-repo | /mpscqueue.hpp | UTF-8 | 6,298 | 2.546875 | 3 | [
"BSL-1.0"
] | permissive | // Lock-free MPSC intrusive and non-intrusive queues based on
// Vyukov, Dmitry,
// http://www.1024cores.net/home/lock-free-algorithms/queues/
//
// Copyright (C) 2018 Zoltan N. Leskowsky
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef ZNL_MPSC_QUEUE_HPP_INCLUDED
#define ZNL_MPSC_QUEUE_HPP_INCLUDED
#include <atomic>
#include <cstddef>
#include <utility>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(_MSC_VER)
#endif
namespace znl {
namespace detail {
} //namespace detail
class SLinkable
{
public:
SLinkable() = default; // can't be made protected
SLinkable( const SLinkable& ) : SLinkable() {} //= delete;
SLinkable( SLinkable&& ) : SLinkable() {} //= delete;
SLinkable& operator=( const SLinkable& ) {} //= delete;
SLinkable& operator=( SLinkable&& ) {} //= delete;
protected:
friend class MPSCIntrQueueBase;
const std::atomic<const SLinkable*>* immutable_next() const { return &_next; }
private:
friend class MPSCQueueBase;
std::atomic<const SLinkable*>* mutable_next() const { return &_next; }
private:
mutable std::atomic<const SLinkable*> _next;
};
template<typename T> class MPSCQueue;
template<typename T>
class MPSCNode : public SLinkable
{
public:
MPSCNode() = default;
MPSCNode( const MPSCNode& node_ ) : _value( node_._value ) {}
MPSCNode( MPSCNode&& node_ ) : _value( std::move( node_._value ) ) {}
explicit MPSCNode( const T& value_ ) : _value( value_ ) {}
explicit MPSCNode( T&& value_ ) : _value( std::move( value_ ) ) {}
MPSCNode& operator=( const MPSCNode& node_ ) = default;
MPSCNode& operator=( MPSCNode&& node_ ) = default;
void set_value( const T& value_ ) { _value = value_; }
void set_value( T&& value_ ) { _value = std::move( value_ ); }
const T& get_value() const { return _value; }
private:
friend class MPSCQueueBase;
friend class MPSCQueue<T>;
T& get_mutable_value() { return _value; }
T&& get_move_value() & { return std::move( _value ); }
const MPSCNode* load_next( std::memory_order order_ ) const {
return static_cast<const MPSCNode*>( SLinkable::immutable_next()->load( order_ ) );
}
private:
T _value;
};
class MPSCQueueBase
{
protected:
MPSCQueueBase() = default;
MPSCQueueBase( const SLinkable& stub_ );
void init( const SLinkable& stub_ ) {
_first.store( &stub_, std::memory_order_relaxed );
_last.store( &stub_, std::memory_order_relaxed );
}
void clear_next( const SLinkable& linkable_, std::memory_order order_ = std::memory_order_relaxed ) {
linkable_.mutable_next()->store( nullptr, order_);
}
const SLinkable* exchange_last( const SLinkable& linkable_, std::memory_order order_ = std::memory_order_acq_rel ) {
return _last.exchange( &linkable_, order_ ); // may block
}
void store_next( const SLinkable& prev_, const SLinkable& linkable_, std::memory_order order_ = std::memory_order_relaxed ) {
prev_.mutable_next()->store( &linkable_, order_);
}
void push( const SLinkable& linkable_ );
void store_first( const SLinkable* linkable_, std::memory_order order_ ) { _first.store( linkable_, order_ ); }
const SLinkable* load_first( std::memory_order order_ ) const { return _first.load( order_ ); }
const SLinkable* load_last( std::memory_order order_ ) const { return _last.load( order_ ); }
//TODO:
bool push_in_process() const { return false; }
private:
std::atomic<const SLinkable*> _last;
std::atomic<const SLinkable*> _first;
};
// Intrusive queue
class MPSCIntrQueueBase : public MPSCQueueBase
{
protected:
MPSCIntrQueueBase() : MPSCQueueBase( _stub ) {}
const SLinkable* pop();
private:
SLinkable _stub;
};
template<class T>
class MPSCIntrQueue : public MPSCIntrQueueBase
{
public:
MPSCIntrQueue() = default;
void push( const T& val_ ) { MPSCQueueBase::push( val_ ); }
const T* pop() { return static_cast<const T*>( MPSCIntrQueueBase::pop() ); }
};
// Non-intrusive queue
template<typename T>
class MPSCQueue : public MPSCQueueBase
{
public:
MPSCQueue() : _stub( new MPSCNode<T>() ) { MPSCQueueBase::init( *_stub ); }
~MPSCQueue() {
MPSCNode<T>* first = const_cast<MPSCNode<T>*>( load_first( std::memory_order_relaxed ) );
MPSCNode<T>* next;
for( MPSCNode<T>* node = first; node; node = next ) {
next = const_cast<MPSCNode<T>*>( node->load_next( std::memory_order_relaxed ) );
delete node;
if( next == first ) {
break;
}
}
}
void push( const T& value_ ) {
MPSCQueueBase::push( *new MPSCNode<T>( value_ ) );
}
void push( T&& value_ ) {
MPSCQueueBase::push( *new MPSCNode<T>( std::move( value_ ) ) );
}
bool pop( T& value_ ) {
MPSCNode<T>* first = const_cast<MPSCNode<T>*>( load_first( std::memory_order_relaxed ) );
MPSCNode<T>* next = const_cast<MPSCNode<T>*>( first->load_next( std::memory_order_acquire ) );
if( next ) {
store_first( next, std::memory_order_relaxed );
assign_or_move( value_, next->get_mutable_value() );
delete first;
return true;
}
return false;
}
bool waiting_pop( T& value_ ) {
do {
MPSCNode<T>* first = const_cast<MPSCNode<T>*>( load_first( std::memory_order_relaxed ) );
MPSCNode<T>* next = const_cast<MPSCNode<T>*>( first->load_next( std::memory_order_acquire ) );
if( next ) {
store_first( next, std::memory_order_relaxed );
assign_or_move( value_, next->get_mutable_value() );
delete first;
return true;
}
} while( push_in_process() );
return false;
}
private:
inline static void assign_value( T& to_, T& from_ ) { to_ = from_; }
inline static void move_value( T& to_, T& from_ ) { to_ = std::move( from_ ); }
inline static void swap_value( T& to_, T& from_ ) { std::swap( to_, from_ ); }
// override for particular T where more efficient:
inline static void assign_or_move( T& to_, T& from_ ) { move_value( to_, from_ ); }
const MPSCNode<T>* load_first( std::memory_order order_ ) const {
return static_cast<const MPSCNode<T>*>( MPSCQueueBase::load_first( order_ ) );
}
//inline static bool is_valued( const T& val_ ) { return false; }
private:
const MPSCNode<T>* _stub;
};
} //namespace znl
#endif //ZNL_MPSC_QUEUE_HPP_INCLUDED
| true |
5ef76ab790f38adf9005b68e8706366ee67d63cb | C++ | jonathenzc/Algorithm | /LeetCode/iter1/c++/652.find-duplicate-subtrees.cpp | UTF-8 | 2,224 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string, vector<TreeNode*>> map;
serialize(root, map);
vector<TreeNode*> ret;
for (auto iter : map) {
if (iter.second.size() > 1) {
ret.push_back(iter.second[0]);
}
}
return ret;
}
private:
string serialize(TreeNode* root, unordered_map<string, vector<TreeNode*>>& map) {
if (root == nullptr) {
return "#";
}
string serializeStr = to_string(root->val) + serialize(root->left, map) + serialize(root->right, map);
if (map.count(serializeStr) == 1) {
map[serializeStr].push_back(root);
}
else {
vector<TreeNode*> v(1, root);
map[serializeStr] = v;
}
return serializeStr;
}
};
void testPrint(TreeNode* treeNode) {
queue<pair<TreeNode*, int>> treeQ;
treeQ.push(pair<TreeNode*, int>(treeNode, 1));
int curLv = 1;
while (!treeQ.empty()) {
pair<TreeNode*, int>tmpPair = treeQ.front();
treeQ.pop();
if (curLv != tmpPair.second) {
curLv = tmpPair.second;
cout << endl;
}
cout << tmpPair.first->val << " ";
if (tmpPair.first->left != NULL) {
treeQ.push(pair<TreeNode*, int>(tmpPair.first->left, tmpPair.second + 1));
}
if (tmpPair.first->right != NULL) {
treeQ.push(pair<TreeNode*, int>(tmpPair.first->right, tmpPair.second + 1));
}
}
}
void testCase1() {
TreeNode* t1 = new TreeNode(1);
TreeNode* t2 = new TreeNode(2);
TreeNode* t3 = new TreeNode(3);
TreeNode* t4 = new TreeNode(4);
TreeNode* t5 = new TreeNode(2);
TreeNode* t6 = new TreeNode(4);
TreeNode* t7 = new TreeNode(4);
t5->left = t6;
t3->left = t5;
t3->right = t7;
t2->left = t4;
t1->left = t2;
t1->right = t3;
Solution s;
vector<TreeNode*> v = s.findDuplicateSubtrees(t1);
for (TreeNode* node : v) {
testPrint(node);
cout << endl;
cout << endl;
}
}
int main(void)
{
testCase1();
cout << endl;
return 0;
} | true |
2eb833934f7e27663b8827ae1c5b96af36d2fd1b | C++ | xlcy32x/LeetCodeQuestions | /Questions/easy/Plus_One.cpp | UTF-8 | 1,745 | 3.75 | 4 | [] | no_license | #include "..\..\Header\inc.h"
class Solution : public SolutionBase<Solution>
{
public:
Solution()
{
std::cout<<"Given a non-empty array of digits representing a non-negative integer, plus one to the integer."<<std::endl;
std::cout<<"The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit."<<std::endl;
std::cout<<"You may assume the integer does not contain any leading zero, except the number 0 itself."<<std::endl;
std::cout<<"Example 1:"<<std::endl;
std::cout<<"Input: [1,2,3]"<<std::endl;
std::cout<<"Output: [1,2,4]"<<std::endl;
std::cout<<"Explanation: The array represents the integer 123."<<std::endl;
std::cout<<"Example 2:"<<std::endl;
std::cout<<"Input: [4,3,2,1]std::endl;
std::cout<<"Output: [4,3,2,2]"<<std::endl;
std::cout<<"Explanation: The array represents the integer 4321."<<std::endl;
}
std::vector<int> plusOne(std::vector<int>& digits)
{
if(digits[digits.size() -1] == 9)
{
std::vector<int> newDigits;
newDigits.reserve(digits.size() + 1);
}
else
{
++digits[digits.size() -1];
}
return digits;
}
//test case to be input here
void Do(const std::string& s)
{
std::cout<<"Result : "<<FindLastWord(s)<<std::endl;
}
};
int main()
{
std::unique_ptr<SolutionBase<Solution>> solutionPtr(new Solution);
solutionPtr->Do("a");
solutionPtr->Do("a ");
solutionPtr->Do(" a ");
solutionPtr->Do("a ");
solutionPtr->Do(" a ");
solutionPtr->Do(" aaaaa ");
std::cin.get();
} | true |
673d8c2509ef6b4d3658f854d4fb65f7cbec9e42 | C++ | weifangwei86/sat_atpg | /src/circuit_graph.cpp | UTF-8 | 5,846 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "circuit_graph.h"
#include "util/log.h"
#include <sstream>
#include <map>
#include <set>
const char* make_gate_name(Gate::Type type)
{
switch(type) {
case Gate::Type::And:
return "AND";
break;
case Gate::Type::Nand:
return "NAND";
break;
case Gate::Type::Not:
return "NOT";
break;
case Gate::Type::Or:
return "OR";
break;
case Gate::Type::Nor:
return "NOR";
break;
case Gate::Type::Xor:
return "XOR";
break;
case Gate::Type::Xnor:
return "XNOR";
break;
case Gate::Type::Buff:
return "BUFF";
break;
case Gate::Type::Undefined:
return "UNDEFINED";
break;
}
assert(false);
return "???";
}
Gate::Gate(IdMaker& id_maker, Gate::Type type, Line* output, std::vector<Line*>&& inputs)
: m_id_maker(id_maker)
, m_type(type)
, m_inputs(inputs)
, m_output(output)
, m_id(id_maker.gate_make_id())
{
bool is_expandable = inputs.size() > 2;
if (!is_expandable) {
m_expanded_gate_ptrs = { this };
} else {
Type top_gate = Type::Undefined;
Type other_gates = Type::Undefined;
switch (m_type) {
case Type::And:
top_gate = Type::And;
other_gates = Type::And;
break;
case Type::Nand:
top_gate = Type::Nand;
other_gates = Type::And;
break;
case Type::Or:
top_gate = Type::Or;
other_gates = Type::Or;
break;
case Type::Nor:
top_gate = Type::Nor;
other_gates = Type::Or;
break;
default:
assert(false);
break;
}
Line* second_input = m_inputs.back();
for (auto it = m_inputs.rbegin() + 1; it != m_inputs.rend(); ++it) {
bool is_top_gate = it == m_inputs.rend() - 1;
Line* first_input = *it;
Type type = is_top_gate ? top_gate : other_gates;
Line* output = nullptr;
if (is_top_gate) {
output = m_output;
} else {
m_expanded_lines.emplace_back(id_maker.line_make_id(), true);
Line& line = m_expanded_lines.back();
line.name = m_output->name;
line.name += "_E_";
line.name += std::to_string(std::distance(m_inputs.rbegin(), it));
output = &line;
}
m_expanded_gate.emplace_back(id_maker, type, output, std::vector<Line*>{first_input, second_input});
Gate& gate = m_expanded_gate.back();
m_expanded_gate_ptrs.push_back(&gate);
second_input = gate.get_output();
}
}
}
const std::vector<Gate*>& Gate::get_expanded() const
{
return m_expanded_gate_ptrs;
}
std::string Gate::get_str() const
{
std::stringstream ss;
ss << m_output->name << " = " << make_gate_name(m_type) << "(";
for (auto it = m_inputs.begin(); it != m_inputs.end() - 1; ++it) {
ss << (*it)->name << ", ";
}
ss << m_inputs.back()->name;
ss << ")";
return ss.str();
}
Line* CircuitGraph::add_input(const std::string& name)
{
Line* p_line = ensure_line(name);
assert(p_line);
m_inputs.push_back(p_line);
return p_line;
}
Line* CircuitGraph::add_output(const std::string& name)
{
Line* p_line = ensure_line(name);
assert(p_line);
if (!p_line->is_output) {
p_line->is_output = true;
m_outputs.push_back(p_line);
}
return p_line;
}
Gate* CircuitGraph::add_gate(Gate::Type type, const std::vector<std::string>& input_names, const std::string& output_name)
{
std::vector<Line*> inputs;
for (size_t i = 0; i < input_names.size(); ++i) {
const std::string input_name = input_names.at(i);
Line* p_input = ensure_line(input_name);
inputs.push_back(p_input);
}
Line* p_output = ensure_line(output_name);
m_gates.emplace_back(*this, type, p_output, std::move(inputs));
Gate& gate = m_gates.back();
p_output->source = &gate;
for (size_t i = 0; i < gate.get_inputs().size(); ++i) {
gate.get_inputs().at(i)->connect_as_input(&gate, i);
}
// Gate validation
switch(gate.type()) {
case Gate::Type::And:
case Gate::Type::Nand:
case Gate::Type::Or:
case Gate::Type::Nor:
assert(gate.inputs().size() >= 2);
break;
case Gate::Type::Xor:
case Gate::Type::Xnor:
assert(gate.inputs().size() == 2);
break;
case Gate::Type::Not:
case Gate::Type::Buff:
assert(gate.inputs().size() == 1);
break;
default:
assert(false);
}
return &gate;
}
Line* CircuitGraph::get_line(const std::string& name)
{
auto it = m_name_to_line.find(name);
if (it != m_name_to_line.end()) {
return it->second;
}
return nullptr;
}
const Line* CircuitGraph::get_line(const std::string& name) const
{
auto it = m_name_to_line.find(name);
if (it != m_name_to_line.end()) {
return it->second;
}
return nullptr;
}
const std::vector<Line*>& CircuitGraph::get_inputs() const
{
return m_inputs;
}
const std::vector<Line*>& CircuitGraph::get_outputs() const
{
return m_outputs;
}
const std::deque<Gate>& CircuitGraph::get_gates() const
{
return m_gates;
}
const std::deque<Line>& CircuitGraph::get_lines() const
{
return m_lines;
}
std::string CircuitGraph::get_graph_stats() const
{
std::stringstream ss;
ss << "# " << m_inputs.size() << " input" << (m_inputs.size() > 1 ? "s" : "") << "\n";
ss << "# " << m_outputs.size() << " output" << (m_outputs.size() > 1 ? "s" : "") << "\n";
ss << "# " << m_lines.size() << " line" << (m_lines.size() > 1 ? "s" : "") << "\n";
ss << "# " << m_gates.size() << " gate" << (m_gates.size() > 1 ? "s" : "") << ":\n";
std::map<Gate::Type, size_t> gate_types;
for (const auto& gate : m_gates) {
++gate_types[gate.get_type()];
}
for (const auto& type_count_pair : gate_types) {
ss << "# ";
ss << type_count_pair.second << " ";
ss << make_gate_name(type_count_pair.first);
ss << "\n";
}
return ss.str();
}
Line* CircuitGraph::ensure_line(const std::string& name)
{
auto it = m_name_to_line.find(name);
if (it != m_name_to_line.end()) {
return it->second;
}
m_lines.emplace_back(line_make_id());
Line& line = m_lines.back();
line.name = name;
m_name_to_line[name] = &line;
it = m_name_to_line.find(name);
return &line;
}
| true |
d6fa82eacbacfdef4a4f5fd5a55dde30a216949e | C++ | rongwl/btclite | /src/unit_test/network/src/protocol/message_tests.cpp | UTF-8 | 3,153 | 2.546875 | 3 | [] | no_license | #include "protocol/message_tests.h"
#include "stream.h"
namespace btclite {
namespace unit_test {
using namespace network::protocol;
TEST_F(MessageHeaderTest, Constructor)
{
EXPECT_EQ(0, header1_.magic());
EXPECT_EQ("", header1_.command());
EXPECT_EQ(0, header1_.payload_length());
EXPECT_EQ(0, header1_.checksum());
EXPECT_EQ(magic_, header2_.magic());
EXPECT_EQ(command_, header2_.command());
EXPECT_EQ(payload_length_, header2_.payload_length());
EXPECT_EQ(checksum_, header2_.checksum());
EXPECT_EQ(magic_, header3_.magic());
EXPECT_EQ(command_, header3_.command());
EXPECT_EQ(payload_length_, header3_.payload_length());
EXPECT_EQ(checksum_, header3_.checksum());
}
TEST_F(MessageHeaderTest, ConstructFromRaw)
{
util::MemoryStream ms;
ms << header2_;
MessageHeader header(ms.Data());
EXPECT_EQ(header, header2_);
}
TEST_F(MessageHeaderTest, OperatorEqual)
{
EXPECT_NE(header1_, header2_);
EXPECT_EQ(header2_, header3_);
header3_.set_magic(kTestnetMagic);
EXPECT_NE(header2_, header3_);
header3_.set_magic(header2_.magic());
header3_.set_command("foo");
EXPECT_NE(header2_, header3_);
header3_.set_command(header2_.command());
header3_.set_payload_length(123);
EXPECT_NE(header2_, header3_);
header3_.set_payload_length(header2_.payload_length());
header3_.set_checksum(123);
EXPECT_NE(header2_, header3_);
}
TEST_F(MessageHeaderTest, Set)
{
header1_.set_magic(header2_.magic());
header1_.set_command(header2_.command());
header1_.set_payload_length(header2_.payload_length());
header1_.set_checksum(header2_.checksum());
EXPECT_EQ(header1_, header2_);
header1_.set_command(std::string("foofoofoofoofoo"));
EXPECT_EQ("foofoofoofoo", header1_.command());
header1_.set_command(std::move(std::string("barbarbarbar")));
EXPECT_EQ("barbarbarbar", header1_.command());
}
TEST_F(MessageHeaderTest, Clear)
{
header2_.Clear();
EXPECT_EQ(header1_, header2_);
}
TEST_F(MessageHeaderTest, ValidateHeader)
{
EXPECT_FALSE(header1_.IsValid());
EXPECT_FALSE(header1_.IsValid(kMainnetMagic));
EXPECT_FALSE(header1_.IsValid(kTestnetMagic));
EXPECT_FALSE(header1_.IsValid(kRegtestMagic));
EXPECT_TRUE(header2_.IsValid());
EXPECT_FALSE(header2_.IsValid(kTestnetMagic));
EXPECT_FALSE(header2_.IsValid(kRegtestMagic));
EXPECT_TRUE(header3_.IsValid());
header1_.set_magic(kMainnetMagic);
header1_.set_command("foo");
EXPECT_FALSE(header1_.IsValid());
header1_.set_magic(kMainnetMagic);
header1_.set_command(msg_command::kMsgVersion);
header1_.set_payload_length(kMaxMessageSize+1);
EXPECT_FALSE(header1_.IsValid());
}
TEST_F(MessageHeaderTest, Serialize)
{
std::vector<uint8_t> vec;
util::ByteSink<std::vector<uint8_t> > byte_sink(vec);
util::ByteSource<std::vector<uint8_t> > byte_source(vec);
header2_.Serialize(byte_sink);
header1_.Deserialize(byte_source);
EXPECT_EQ(header1_, header2_);
}
} // namespace unit_test
} // namespace btclite
| true |
2843c4c51e39412b81d6ceb7992ca3be70df5c2b | C++ | glorianayeli/Multiplo | /tareaa3.cpp | UTF-8 | 2,322 | 4 | 4 | [] | no_license | //1.- Leer un numero y mostrar el factorial del numero, mismo que se describe con el símbolo n! ejemplo:
//5! y se obtiene multiplicando todos los números de el 1 al numero = 1 *2 *3 *4 *5 = 120. No probar con números mayores a 19.
#include <iostream>
using namespace std;
int main()
{
int numero,factorial=1;
cout<<"Ingresa un numero";
cin>>numero;
for(int i=1;i<=numero;i++)
{
factorial*=i;
}
cout<<factorial;
}
//2.- Leer un numero base y una potencia y mediante ciclos obtener el resultado de elevar el
//numero base a la potencia indicada. Ejemplo base=3, potencia = 4, el resultado es 3^4, es decir = 3 x 3 x 3 x 3=81
#include <iostream>
using namespace std;
int main()
{
int numero, potencia, total=1;
cout<<"Ingresa un numero";
cin>>numero;
cout<<"Ingrea la potencia";
cin>>potencia;
for(int i=1;i<=potencia;i++)
{
total*=numero;
}
cout<<total;
}
/*
3.- Realice un programa que permita dar como salida la población de dos países (a y b), teniendo
en cuenta para tal propósito lo siguiente:
* En el Primer Año el País “a” tiene menos población que el país “b”
* Las Tazas de crecimiento de los países “a” y “b” son de 6% y 3% anuales respectivamente.
* Se debe dar como salidas las poblaciones desde el segundo año hasta que la población de “a” exceda a la población de “b”,
además la cantidad de años que transcurrieron para que esto sucediera
*/
#include <iostream>
using namespace std;
int main()
{
float ciudad1,ciudad2;
int anos=0;
cout<<"Ingresa poblacion de ciudad uno";
cin>>ciudad1;
cout<<"Ingresa poblacion de ciudad dos";
cin>>ciudad2;
if(ciudad1<ciudad2)
{
while(ciudad2>ciudad1)
{
ciudad1=ciudad1+(ciudad1*.6);
ciudad2=ciudad2+(ciudad2*.3);
anos++;
}
cout<<"poblacion de cuidad1:"<<"\t"<<ciudad1<<endl;
cout<<"poblacion de cuidad2:"<<"\t"<<ciudad2<<endl;
cout<<"Años que pasaron:"<<"\t"<<anos;
}
else
{
cout<<"poblacion de cuidad1:"<<"\t"<<ciudad1<<endl;
cout<<"poblacion de cuidad2:"<<"\t"<<ciudad2<<endl;
cout<<"Años que pasaron:"<<"\t"<<anos;
}
}
| true |
d7568395e3fba889d787d412ab5f13c45998d1f0 | C++ | DonCastillo/go-fish-mvc | /include/MockCard.h | UTF-8 | 494 | 2.609375 | 3 | [] | no_license | /*!
\file MockCard class header
*/
#ifndef MOCKCARD_H_INCLUDED
#define MOCKCARD_H_INCLUDED
#include <string>
#include "gmock/gmock.h"
class MockCard : public Card {
public:
explicit MockCard(int s, int r) :
Card(s, r) {}
virtual ~MockCard() {}
MOCK_METHOD0(getSuit, std::string());
MOCK_METHOD0(getRank, std::string());
MOCK_METHOD1(formatRank, std::string(int pRank));
MOCK_METHOD1(formatSuit, std::string(int pSuit));
};
#endif // MOCKCARD_H_INCLUDED
| true |
8b496312e3b6645265f111819ac6f5c8fb52a7b1 | C++ | XiaoHsiang/A9 | /Advanced-homework09.cpp | BIG5 | 566 | 3.0625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
void is_fortunate(int,int,int);
int main(void){
int born_year,born_month,born_day;
printf("пJXͤ:");
scanf("%d%d%d",&born_year,&born_month,&born_day);
is_fortunate(born_year,born_month,born_day);
return 0;
system("pause");
}
void is_fortunate(int year,int month,int day){
int result;
result=(month*2+day)%3;
switch(result){
case 0:
printf("q");
break;
case 1:
printf("N");
break;
case 2:
printf("jN");
break;
}
}
| true |
72066359f6742082936995c0bde78d516f2d21e6 | C++ | chromium/chromium | /remoting/ios/persistence/host_pairing_info.h | UTF-8 | 2,077 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_IOS_PERSISTENCE_HOST_PAIRING_INFO_H_
#define REMOTING_IOS_PERSISTENCE_HOST_PAIRING_INFO_H_
#include <string>
namespace remoting {
class Keychain;
// A HostPairingInfo contains details to negotiate and maintain a connection
// to a remote Chromoting host. This is an entity in a backing store.
class HostPairingInfo {
public:
HostPairingInfo(const HostPairingInfo&);
HostPairingInfo(HostPairingInfo&&);
~HostPairingInfo();
// Loads a record from the keychain.
// If a record does not exist, return a new record with a blank secret.
static HostPairingInfo GetPairingInfo(const std::string& user_id,
const std::string& host_id);
// Commit this record to the keychain.
void Save();
// Properties supplied by the host server.
const std::string& user_id() const { return user_id_; }
const std::string& host_id() const { return host_id_; }
const std::string& pairing_id() const { return pairing_id_; }
void set_pairing_id(const std::string& pairing_id) {
pairing_id_ = pairing_id;
}
const std::string& pairing_secret() const { return pairing_secret_; }
void set_pairing_secret(const std::string& pairing_secret) {
pairing_secret_ = pairing_secret;
}
// The keychain is used to fetch and store host pairing data. The default
// implementation uses system keychain API. We can supply a custom keychain
// for testing. Passing null will restore the default keychain.
static void SetKeychainForTesting(Keychain* keychain);
private:
HostPairingInfo(const std::string& user_id,
const std::string& host_id,
const std::string& pairing_id,
const std::string& pairing_secret);
std::string user_id_;
std::string host_id_;
std::string pairing_id_;
std::string pairing_secret_;
};
} // namespace remoting
#endif // REMOTING_IOS_PERSISTENCE_HOST_PAIRING_INFO_H_
| true |
422aedebd81f3927e45ef0961da02d11b075d479 | C++ | YXL76/my-cpp-library | /my-cpp-library/include/BinaryTree/BinaryTree.h | UTF-8 | 1,361 | 2.78125 | 3 | [
"MIT"
] | permissive | #pragma once
/**
* \Author: YXL
* \LastUpdated: 2018/04/02 22:30:00
* \Description:
*/
#ifndef BINARY_TREE_H
#define BINARY_TREE_H
#include <functional>
namespace yxl
{
template <typename T>
class BinaryTree
{
public:
using ttask = std::function<void(T*&)>;
using itask = std::function<void(int&)>;
using iitask = std::function<void(int&, const int&)>;
using ittask = std::function<void(int&, T*&)>;
constexpr BinaryTree() = default;
virtual ~BinaryTree() = default;
constexpr BinaryTree(const BinaryTree& that) = default;
constexpr BinaryTree(BinaryTree&& that) noexcept = default;
virtual bool empty(T*& node) = 0;
virtual int size(T*& node) = 0;
virtual int height(T*& node) = 0;
virtual int width(T*& node) = 0;
virtual void clear(T*& node) = 0;
virtual void build(T*& node, T* const& that) = 0;
virtual void traversal(T*& node, ttask& pre, ttask& in, ttask& post) = 0;
virtual void level_traversal(T*& node, int& count, ittask& point, iitask& line, itask& plane) = 0;
BinaryTree& operator=(const BinaryTree& right) = default;
BinaryTree& operator=(BinaryTree&& right) noexcept = default ;
};
} // namespace yxl
#endif // !BINARY_TREE_H
| true |
cb71e9dbda8b76f9b94f066e2850362693a9d798 | C++ | awrucker/Lab-7-CSC-2111 | /2111/CSC2110/Permutation.h | UTF-8 | 418 | 2.65625 | 3 | [] | no_license | #if !defined (PERMUTATION_H)
#define PERMUTATION_H
#include "ListArray.h"
using CSC2110::ListArray;
#include "Integer.h"
using CSC2110::Integer;
#include "Random.h"
using CSC2110::Random;
namespace CSC2110
{
class Permutation
{
private:
int r;
ListArray<Integer>* numbers;
Random* random;
public:
Permutation(int r, int n);
virtual ~Permutation();
int next();
};
}
#endif
| true |
88b359beb7a7a58299775f3cc1eea3773e99d320 | C++ | Arjunkhera/Competitive_Programming | /HackerBlocks/factorial_problem.cpp | UTF-8 | 963 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<cmath>
#include<climits>
using namespace std;
typedef long long int ll;
map<ll,ll> factors;
int answer;
void solve(ll n,ll k){
ll lowest=INT_MAX,minimum;
ll factor,temp;
map<ll,ll>::iterator i = factors.begin();
while(i != factors.end()){
minimum = 0;
factor = i->first;
temp = n;
while(temp){
minimum += temp/factor;
temp /= factor;
}
minimum = (minimum/i->second);
if(minimum < lowest)
lowest = minimum;
i++;
}
answer = lowest;
}
void factorize(ll n){
while(n%2 == 0){
factors[2]++;
n = n/2;
}
for(ll i = 3; i <= sqrt(n); i = i+2){
if(n%i==0)
factors[i] = 0;
while(n%i == 0){
factors[i]++;
n = n/i;
}
}
if(n > 2)
factors[n] = 1;
}
int main(){
ll t,n,k;
cin>>t;
while(t--){
cin>>n>>k;
factorize(k);
solve(n,k);
factors.clear();
cout<<answer<<endl;
}
return 0;
}
| true |
c3611c5002df425686a7b47ddfde9750a1be8e88 | C++ | delsner/goldene-sieben | /card.cpp | UTF-8 | 825 | 3.28125 | 3 | [] | no_license | //
// Created by Daniel Elsner on 17.03.17.
//
#include <iostream>
#include "card.h"
using namespace std;
Card::Card(const Color &color_, CardValue value_) : color_(color_), value_(value_) {}
const Color &Card::getColor_() {
return color_;
}
void Card::setColor_(const Color &color_) {
Card::color_ = color_;
}
int Card::compare(Card c1, Card c2) {
if (CardValue::compare(c1.getValue_(), c2.getValue_()) == 1) {
return 1;
} else if (CardValue::compare(c1.getValue_(), c2.getValue_()) == -1) {
return -1;
} else {
return 0;
}
}
bool Card::equals(Card c1, Card c2) {
return c1.getValue_() == c2.getValue_() && c1.getColor_() == c2.getColor_();
}
CardValue Card::getValue_() const {
return value_;
}
void Card::setValue_(CardValue value_) {
Card::value_ = value_;
}
| true |
85f84b337c826207ea697bc0e7e37ec6d7b7a8e0 | C++ | kyler618/Dijkstra-Implementation-with-Qt | /vertex.cpp | UTF-8 | 4,077 | 2.671875 | 3 | [] | no_license | #include <QMouseEvent>
#include <QEvent>
#include <QtDebug>
#include "vertex.h"
#include "impl.h"
#include "edge.h"
Vertex::Vertex(int x, int y, QWidget *parent)
: QLabel(parent)
{
setVisible(true);
setAlignment(Qt::AlignCenter);
setGeometry(x-20, y-20, 40, 40);
setStyleSheet("border : 2px solid;"
"border-radius : 20px;"
"border-color : black;"
);
installEventFilter(this);
connect(this, SIGNAL(selected(Vertex*,bool)), parent, SLOT(draw(Vertex*,bool)));
}
void
Vertex::changeColor(const QString& color){
QString style{"border : 2px solid;"
"border-radius : 20px;"
"border-color : "};
setStyleSheet(style.append(color));
}
void
Vertex::add_to_list(Edge* edge){
adjacency_list.push_front(edge);
}
void
Vertex::remove_from_list(Edge* edge){
adjacency_list.remove(edge);
}
bool
Vertex::contains(Vertex* vertex){
for(Edge* edge : adjacency_list)
if(edge->contains(vertex)) return true;
return false;
}
std::forward_list <Edge*>*
Vertex::getList(){
return &adjacency_list;
}
void
Vertex::drawingMode_trigger(bool drawing){
send = drawing;
if( !drawing && styleSheet().contains("border-color : yellow") )
emit selected(this,true);
}
void
Vertex::filter_trigger(bool executing, Impl* impl){
send = executing;
if(executing)
{
disconnect(this, SIGNAL(selected(Vertex*,bool)), this->parentWidget(), SLOT(draw(Vertex*,bool)));
connect(this, SIGNAL(selected(Vertex*, bool)), impl, SLOT(execution(Vertex*, bool)));
emit selected(this);
}
else
{
setText("");
if(!styleSheet().contains("border-color : black"))
changeColor("black");
for(Edge* edge : adjacency_list)
edge->changeColor("black");
installEventFilter(this);
connect(this, SIGNAL(selected(Vertex*,bool)), this->parentWidget(), SLOT(draw(Vertex*,bool)));
}
}
void
Vertex::send_self(){
emit selected(this);
}
bool
Vertex::eventFilter(QObject *, QEvent *event){
switch(event->type()) {
case QEvent::Paint:
QLabel::paintEvent(static_cast<QPaintEvent*>(event));
return true;
case QEvent::MouseButtonRelease:
if(isHover)
isHover = !isHover;
break;
case QEvent::MouseButtonPress:
switch(static_cast<QMouseEvent*>(event)->button()){
case Qt::LeftButton:
lastPoint = static_cast<QMouseEvent*>(event)->pos();
if(send)
emit selected(this, true);
else
isHover = true;
break;
case Qt::RightButton:
if(send) break;
if(styleSheet().contains("border-color : yellow")) emit selected(this);
// delete all adjacent edge first
for(Edge* edge : adjacency_list)
edge->remove(edge->get_adjacentVertex(this));
adjacency_list.clear();
disconnect();
removeEventFilter(this);
deleteLater();
break;
default: break;
}
break;
case QEvent::MouseMove:
if(isHover){
int new_x{x() + static_cast<QMouseEvent*>(event)->pos().x() - lastPoint.x()};
int new_y{y() + static_cast<QMouseEvent*>(event)->pos().y() - lastPoint.y()};
if(!(new_x < 0 || new_y < 0 ||
parentWidget()->size().width()-40 < new_x ||
parentWidget()->size().height()-40 < new_y ))
move(new_x, new_y);
repaint();
}
break;
default:
break;
}
return true;
}
| true |
8698732adcecb5b34759becce0413d9ac2d3ba5e | C++ | MartinKrat/chip-8 | /key_opcode.cpp | UTF-8 | 1,778 | 3.34375 | 3 | [] | no_license | #include<stdio.h>
/*Function key_opcode reads each character from the input. *
Moreover key_opcode checks if each opcode consists of 4 characters *
and if each character is a number (1 to 9) or a letter (a,b,c,d,e,f). *
Then, key_opcode transforms this string to a real hex-number and *
stores it in opcode2. After that key_opcode returns opcode2 . */
unsigned short key_opcode(void)
{
int counter=0, i, no_emit=0;
unsigned short opcode2=0, opcode3=0;
char key_str[4];
char key;
while(1)
{
key = getchar();
if(key!=10)
{
if(counter<4)
{
key_str[counter] = key;
++counter;
}
if(counter==4)
{
counter=0;
for(i=0;i<4;++i)
{
if(key_str[i]>47)
{
if(key_str[i]<58)
{
opcode3 = (unsigned short) (key_str[i]-48);
opcode3 = opcode3<<(12-i*4);
opcode2 = opcode2 + opcode3;
opcode3 = 0;
}
else if((key_str[i]>64) && (key_str[i]<71))
{
opcode3 = (unsigned short) (key_str[i]-55);
opcode3 = opcode3<<(12-i*4);
opcode2 = opcode2 + opcode3;
opcode3 = 0;
}
else if((key_str[i]>96) && (key_str[i]<103))
{
opcode3 = (unsigned short) (key_str[i]-87);
opcode3 = opcode3<<(12-i*4);
opcode2 = opcode2 + opcode3;
opcode3 = 0;
}
else
{
opcode3 = 0;
i = 4;
no_emit = 1;
printf("bad opcode \n");
}
}
else
{
opcode3 = 0;
i = 4;
no_emit = 1;
printf("bad opcode\n");
}
}
if(no_emit==0)
{
return(opcode2);
}
opcode2 = 0; /*reset opcode2 to 0 */
no_emit = 0; /*reset no_emit to 0 */
key_str[counter] = key;
}
}
if(key==10)
{
counter=0;
}
}
}
| true |
a84822026a879e8c33733e8cab25af7decb647ba | C++ | Marseloz/PoolsideGUI | /udp_client.cpp | UTF-8 | 2,329 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "udp_client.h"
#include <QNetworkDatagram>
#include <sstream>
UDP_Client::UDP_Client()
{
uv_interface = new IServerData();
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 7755);
connect(udpSocket, &QUdpSocket::readyRead,
this, &UDP_Client::readPendingDatagrams);
udpHostAddress = "127.0.0.1";
udpHostPort = 26782;
messageType = MESSAGE_NORMAL;
}
UDP_Client::~UDP_Client()
{
udpSocket->close();
delete udpSocket;
delete uv_interface;
delete timeoutTimer;
}
void UDP_Client::run()
{
try {
connectToHost();
}
catch (const std::invalid_argument& error) {
qDebug() << "[UDP_CLIENT_ERROR] " << error.what();
}
exec();
}
int UDP_Client::exec()
{
while(1)
{
QByteArray msg;
msg = uv_interface->generateMessage(messageType);
// qDebug() << "[UDP_CLIENT] Sending message type " << messageType << "||" << msg.size();
QNetworkDatagram datagram;
datagram.setData(msg);
udpSocket->writeDatagram(datagram);
msleep(100);
}
}
void UDP_Client::readPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
QNetworkDatagram datagram = udpSocket->receiveDatagram();
QByteArray msg = datagram.data();
bool exception_caught = false;
try {
uv_interface->parseMessage(msg, messageType);
}
catch(const std::invalid_argument& error) {
// qDebug() << "[UDP_CLIENT_ERROR] " << error.what();
exception_caught = true;
}
if(!exception_caught) {
// qDebug() << "[UDP_CLIENT] Message parced " << messageType << "||" << msg.size();
emit dataUpdated();
}
}
}
void UDP_Client::connectToHost()
{
QHostAddress udpQHostAddress;
if(!udpQHostAddress.setAddress(udpHostAddress)) {
std::stringstream stream;
stream << "Parsing UDP Host Address error. Address: [" <<
udpHostAddress.toStdString() << "]";
throw std::invalid_argument(stream.str());
return;
}
udpSocket->connectToHost(udpHostAddress, udpHostPort);
if (!udpSocket->waitForConnected(1000)) {
throw std::invalid_argument("Can't connect to host, connection timeout");
}
}
| true |
7206121320573fe4e4322b8210c5a3edd6062f43 | C++ | sky-lzy/Homework | /Code/9-1.cpp | UTF-8 | 826 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << " ++++++++++++++++ " << endl;
cout << " XX公司人事管理系统 " << endl << endl;
cout << " ++++++++++++++++ " << endl << endl;
cout << "#################" << endl << endl;
cout << " 主菜单 " << endl;
cout << " 1. 数据录入 " << endl;
cout << " 2. 数据查询 " << endl;
cout << " 3. 数据保存 " << endl;
cout << " 4. 退出 " << endl;
cout << " 请选择序号(1-4) " << endl;
cout << "#################" << endl;
return 0;
} | true |
087d3d42713cdba6f22b4ec6fa58a70c03b2ee18 | C++ | roonm813/teamnote-2019 | /stl_reference/vector.cpp | UHC | 2,741 | 3.59375 | 4 | [] | no_license | //2018.00.00 roonm813 writes.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printV(vector<int>* v){
for(int i = 0; i < v->size(); i++)
cout << (*v).at(i) << " ";
cout << endl<<endl;
}
int main(void){
vector<int> v;
v.reserve(8); // vector size 8
cout << "capacitiy : "<< v.capacity() << endl;
cout << "max size : " << v.max_size() <<endl<<endl;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
v.push_back(100);
v.pop_back();
v.push_back(60);
v.push_back(70);
v.push_back(80);
v.push_back(90);
v.push_back(100);
cout << "over capacitiy! what happen? "<< endl;
cout << "capacitiy : "<< v.capacity() << endl <<endl;
/* ϴ 2 */
cout << "vector size : " << v.size() << endl;
for(int i = 0; i < v.size(); i++)
cout << v[i] << " ";// []ڷ , [] üũ ʴ´.
cout << endl;
v.resize(9); //resize ϴ
for(int i = 0; i <v.size(); i++)
cout << v.at(i) << " ";//at function size üũؼ return
cout << endl<<endl;
/*fornt back element*/
cout << "front element : " << v.front() <<endl;
cout << "back element : " << v.back() << endl;
/*empty*/
if(v.empty())
cout << "vector is empty" << endl;
else
cout << "vector is NOT empty" << endl;
/*sort* , compareԼ , boll compare(type a, type b)*/
sort(v.begin(), v.end(), greater<int>());
printV(&v);
/*insert and assign*/
vector<int> destV;
v.insert(v.begin()+2, -1); //(position iterator, value)
v.insert(v.begin()+4, 3, -2); //(position iterator, size, value)
destV.assign(v.begin()+6, v.end());
printV(&v);
printV(&destV);
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
destV.assign(array, array+10); //assign from array is possible
printV(&destV);
/*erase and clear*/
destV.erase(destV.begin()); //erase first element
destV.erase(destV.begin()+3, destV.begin()+6); //erase 3, 4, 5 th index element
printV(&destV);
destV.clear();
if(destV.empty())
cout << "empty after clear "<<endl <<endl;
/*using iterator and reverse interator*/
vector<int>::iterator it;
for(it = v.begin(); it != v.end(); it++) //end Ŵ rit
cout << *it << " ";
cout <<endl;
vector<int>:: reverse_iterator rit;
for(rit = v.rbegin(); rit != v.rend(); rit++)
cout << *rit << " ";
cout << endl;
return 0;
}
| true |
1fcf2d70f38e8e566ce8c290ba753fa4e316f9e9 | C++ | tgxworld/CS1020E | /tutorials/8/sorted_stack.cpp | UTF-8 | 1,687 | 3.875 | 4 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
void printStack(stack<int> intStack) {
while(!intStack.empty()) {
cout << intStack.top() << " ";
intStack.pop();
}
cout << endl;
}
void insertOrder(stack<int>& intStack, int value) {
int temp;
if(value < intStack.top()) {
temp = intStack.top();
intStack.pop();
if(intStack.empty()) {
intStack.push(value);
} else {
insertOrder(intStack, value);
}
intStack.push(temp);
} else if(value >= intStack.top()) {
intStack.push(value);
}
}
void sortStack(stack<int>& intStack) {
if(!intStack.empty()) {
int temp = intStack.top();
intStack.pop();
sortStack(intStack);
if(intStack.empty()) {
intStack.push(temp);
} else {
insertOrder(intStack, temp);
}
}
}
void deleteNumber(stack<int>& intStack, int value) {
if(intStack.top() == value) {
intStack.pop();
return;
} else {
int temp = intStack.top();
intStack.pop();
if(intStack.empty()) {
return;
} else {
deleteNumber(intStack, value);
}
intStack.push(temp);
}
}
int main() {
stack<int> intStack;
for(int i = 0; i < 5; ++i) {
intStack.push(i);
}
insertOrder(intStack, -1);
insertOrder(intStack, 5);
insertOrder(intStack, -100);
insertOrder(intStack, 100);
deleteNumber(intStack, 100);
deleteNumber(intStack, -100);
deleteNumber(intStack, 5);
deleteNumber(intStack, -1);
intStack.push(24);
intStack.push(1231231);
intStack.push(-1231);
intStack.push(12453);
intStack.push(1231532);
printStack(intStack);
sortStack(intStack);
printStack(intStack);
return 0;
}
| true |
1a7f8cd5f568362b62ca41f64452b14daff8c88f | C++ | alisezgin/ARALGIS | /ARALGIS/ChangeDetection/ProcessingAlgorithms/RobustMatcher.h | UTF-8 | 10,518 | 2.703125 | 3 | [] | no_license | #pragma once
#include "DisplayMatches.h"
#include "Settings.h"
class RobustMatcher
{
private:
// pointer to the feature point detector object
cv::Ptr<cv::FeatureDetector> detector;
// pointer to the feature descriptor extractor object
cv::Ptr<cv::DescriptorExtractor> extractor;
float ratio; // max ratio between 1st and 2nd NN
bool isImageToBeDisplayed;
public:
RobustMatcher() : ratio(0.7f)
{
// SURF is the default feature
detector = new cv::SurfFeatureDetector();
extractor = new cv::SurfDescriptorExtractor();
}
// Set the feature detector
void setFeatureDetector(
cv::Ptr<cv::FeatureDetector>& detect)
{
detector = detect;
}
// Set the descriptor extractor
void setDescriptorExtractor(
cv::Ptr<cv::DescriptorExtractor>& desc)
{
extractor = desc;
}
void setRatio(float aRatio)
{
ratio = aRatio;
}
void setDisplay(bool aDisplay)
{
isImageToBeDisplayed = aDisplay;
}
// Match feature points using symmetry test and RANSAC
// returns homography matrix
void match(cv::Mat& image1, cv::Mat& image2, // input images
// output matches and keypoints
std::vector<cv::DMatch>& matchesOut,
std::vector<cv::KeyPoint>& keypoints1,
std::vector<cv::KeyPoint>& keypoints2,
std::vector<cv::DMatch>& matches1All,
std::vector<cv::KeyPoint>& keypoints1All,
std::vector<cv::DMatch>& matches2All,
std::vector<cv::KeyPoint>& keypoints2All)
{
int64 tick1, tick2, tick3;
// 1b. Extraction of the SURF descriptors
cv::Mat descriptors1, descriptors2;
// 1a. Detection of the SURF features
tick1 = cv::getTickCount();
detector->detect(image1, keypoints1);
tick2 = cv::getTickCount();
extractor->compute(image1, keypoints1, descriptors1);
tick3 = cv::getTickCount();
#ifdef DEBUG_PRINT_FINAL1
DEBUG_PRINT("Image1 KeyPoint %.3f secs Descriptor %.3f TOTaL TIME %.3f\n",
((tick2 - tick1) / cv::getTickFrequency()), ((tick3 - tick2) / cv::getTickFrequency()), ((tick3 - tick1) / cv::getTickFrequency()));
#endif
tick1 = cv::getTickCount();
detector->detect(image2, keypoints2);
tick2 = cv::getTickCount();
extractor->compute(image2, keypoints2, descriptors2);
tick3 = cv::getTickCount();
#ifdef DEBUG_PRINT_FINAL1
DEBUG_PRINT("Image2 KeyPoint %.3f secs Descriptor %.3f TOTaL TIME %.3f\n",
((tick2 - tick1) / cv::getTickFrequency()), ((tick3 - tick2) / cv::getTickFrequency()), ((tick3 - tick1) / cv::getTickFrequency()));
#endif
// 2. Match the two image descriptors
// Construction of the matcher
cv::BFMatcher matcher;
// from image 1 to image 2
// based on k nearest neighbours (with k=2)
std::vector<std::vector<cv::DMatch>> matches1;
#ifdef DEBUG_PRINT_FINAL1
DEBUG_PRINT("starting 1st KNN\n");
DEBUG_PRINT("Keypoint Sizes %d %d\n", keypoints1.size(), keypoints2.size());
#endif
// void DescriptorMatcher::knnMatch(const Mat& queryDescriptors, const Mat& trainDescriptors,
// vector<vector<DMatch>>& matches, int k,
// const Mat& mask=Mat(), bool compactResult=false )
// !!!!! fiirst one is the TEST Image, second one is the TRAIN Image
matcher.knnMatch(descriptors2, descriptors1, matches1, 2); // vector of matches (up to 2 per entry)
// return 2 nearest neighbours
DEBUG_PRINT("starting 2nd KNN\n");
// from image 2 to image 1
// based on k nearest neighbours (with k=2)
std::vector<std::vector<cv::DMatch>> matches2;
matcher.knnMatch(descriptors1, descriptors2, matches2, 2); // vector of matches (up to 2 per entry)
// return 2 nearest neighbours
#ifdef DEBUG_PRINT_FINAL1
DEBUG_PRINT("KNN finshed\n");
#endif
#ifdef DISPLAY_PRINTS_DEBUG
DEBUG_PRINT("Initial Num Matches1 %d Num Matches2 %d \n\n", matches1.size(), matches2.size());
#endif
/// New code to get all of the data
for (std::vector<std::vector<cv::DMatch>>::iterator
matchIterator = matches1.begin();
matchIterator != matches1.end(); ++matchIterator)
{
matches1All.push_back((*matchIterator)[0]);
}
for (std::vector<std::vector<cv::DMatch>>::iterator
matchIterator = matches2.begin();
matchIterator != matches2.end(); ++matchIterator)
{
matches2All.push_back((*matchIterator)[0]);
}
for (int jj = 0; jj < (int) keypoints1.size(); jj++)
{
keypoints1All.push_back(keypoints1[jj]);
}
for (int jj = 0; jj < (int) keypoints2.size(); jj++)
{
keypoints2All.push_back(keypoints2[jj]);
}
//////////// end of new code
///////////// bora 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#ifdef DISPLAY_IMAGES_DEBUG_MATCHER
if (isImageToBeDisplayed)
{
char title1[1000];
DisplayMatches matchDisplayer1;
strcpy_s(title1, "MATCHES img1-->img2 Feature-1 \0");
matchDisplayer1.displayMatchesInitial(image1, image2, matches1, matches2,
keypoints1, keypoints2, title1);
}
#endif
///////////// bora 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// 3. Remove matches for which NN ratio is
// > than threshold
// clean image 1 -> image 2 matches
int removed1 = ratioTest(matches1);
// clean image 2 -> image 1 matches
int removed2 = ratioTest(matches2);
#ifdef DISPLAY_PRINTS_DEBUG
DEBUG_PRINT("After Ratio Test Num Matches1 %d Num Matches2 %d RM1 %d RM2 %d\n\n", matches1.size() - removed1, matches2.size() - removed2, removed1, removed2);
#endif
///////////// bora 2 ###############################
#ifdef DISPLAY_IMAGES_DEBUG_MATCHER
if (isImageToBeDisplayed)
{
DisplayMatches matchDisplayer2;
char title2[1000];
strcpy_s(title2, "MATCHES img1-->img2 Features After Ratio Test \0");
matchDisplayer2.displayMatchesRatioTest(image1, image2, matches1, matches2,
keypoints1, keypoints2, title2);
}
#endif
///////////// bora 2 ###############################3
// 4. Remove non-symmetrical matches
//std::vector<cv::DMatch> symMatches;
symmetryTest(matches1, matches2, matchesOut); //matchesOut // symMatches
#ifdef DISPLAY_PRINTS_DEBUG
DEBUG_PRINT("After Symetry Test Num Matches1 %d \n\n", matchesOut.size()); //symMatches
#endif
///////////// bora 3 ###############################
#ifdef DISPLAY_IMAGES_DEBUG_MATCHER
if (isImageToBeDisplayed)
{
DisplayMatches matchDisplayer3;
char title3[1000];
strcpy_s(title3, "MATCHES img1-->img2 Features After Symetry Test \0");
matchDisplayer3.displayMatchesSymetryTest(image1, image2, matchesOut, //symMatches
keypoints1, keypoints2, title3);
}
#endif
}
// Clear matches for which NN ratio is > than threshold
// return the number of removed points
// (corresponding entries being cleared,
// i.e. size will be 0)
int ratioTest(std::vector<std::vector<cv::DMatch>> &matches)
{
int removed = 0;
// for all matches
for (std::vector<std::vector<cv::DMatch>>::iterator
matchIterator = matches.begin();
matchIterator != matches.end(); ++matchIterator)
{
// if 2 NN has been identified
if (matchIterator->size() > 1)
{
// check distance ratio
if ((*matchIterator)[0].distance /
(*matchIterator)[1].distance > ratio)
{
matchIterator->clear(); // remove match
removed++;
}
}
else
{ // does not have 2 neighbours
matchIterator->clear(); // remove match
removed++;
}
}
return removed;
}
// Insert symmetrical matches in symMatches vector
void symmetryTest(
const std::vector<std::vector<cv::DMatch>>& matches1,
const std::vector<std::vector<cv::DMatch>>& matches2,
std::vector<cv::DMatch>& symMatches)
{
// for all matches image 1 -> image 2
for (std::vector<std::vector<cv::DMatch>>::const_iterator matchIterator1 = matches1.begin();
matchIterator1 != matches1.end();
++matchIterator1)
{
// ignore deleted matches
if (matchIterator1->size() >= 2)
{
// for all matches image 2 -> image 1
for (std::vector<std::vector<cv::DMatch>>::const_iterator matchIterator2 = matches2.begin();
matchIterator2 != matches2.end();
++matchIterator2)
{
// ignore deleted matches
if (matchIterator2->size() >= 2)
{
// Match symmetry test
if (((*matchIterator1)[0].queryIdx == (*matchIterator2)[0].trainIdx) &&
((*matchIterator2)[0].queryIdx == (*matchIterator1)[0].trainIdx))
{
// add symmetrical match
symMatches.push_back(
cv::DMatch((*matchIterator1)[0].queryIdx,
(*matchIterator1)[0].trainIdx,
(*matchIterator1)[0].distance));
break; // next match in image 1 -> image 2
}
}
}
}
}
}
// Identify good matches using RANSAC
// Return homography matrix
cv::Mat homographyTest(
const std::vector<cv::DMatch>& matches,
const std::vector<cv::KeyPoint>& keypoints1,
const std::vector<cv::KeyPoint>& keypoints2,
std::vector<cv::DMatch>& inlier_matchesOut)
{
// Convert keypoints into Point2f
std::vector<cv::Point2f> points1, points2;
for (std::vector<cv::DMatch>::const_iterator it = matches.begin();
it != matches.end();
++it)
{
// Get the position of left keypoints
float x = keypoints2[it->queryIdx].pt.x;
float y = keypoints2[it->queryIdx].pt.y;
points1.push_back(cv::Point2f(x, y));
// Get the position of right keypoints
x = keypoints1[it->trainIdx].pt.x;
y = keypoints1[it->trainIdx].pt.y;
points2.push_back(cv::Point2f(x, y));
}
// Compute F matrix using RANSAC
std::vector<uchar> inliers(points1.size(), 0);
cv::Mat inlier_mask, homography;
std::vector<cv::KeyPoint> inliers1, inliers2;
if (matches.size() >= 4)
{
const double ransac_thresh = 2.5f; // RANSAC inlier threshold
homography = findHomography(points1, points2,
cv::RANSAC, ransac_thresh, inlier_mask);
for (unsigned i = 0; i < matches.size(); i++)
{
if (inlier_mask.at<uchar>(i))
{
int new_i = static_cast<int>(inliers1.size());
inliers1.push_back(keypoints2[matches[i].queryIdx]);
inliers2.push_back(keypoints1[matches[i].trainIdx]);
//inlier_matchesOut.push_back(DMatch(new_i, new_i, 0));
inlier_matchesOut.push_back(matches[i]);
}
}
}
return homography;
}
}; | true |
8e024cda7e32af086709c2bcb3ac8e7e2e290a41 | C++ | kunal121/C-And-Cpp-Questions | /Kartik/constructorparameterized.cpp | UTF-8 | 384 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
class test
{
int i;
public:
test()
{
cout<<"default constructor\n";
i=10;
}
test(int a)
{
cout<<"parameterized constructor\n";
i=a;
}
void show()
{
cout<<i;
}
};
int main()
{
test obj1,obj2(25);
obj1.show();//10
obj2.show();//parameter
return 0;
}
| true |
7a594eff477bea6a993828da5a07090aab829b75 | C++ | zjucsxxd/Kazaam | /ReadWAV/ReadWAV/WavBot.hpp | UTF-8 | 3,025 | 3 | 3 | [] | no_license | #ifndef __AudioThread
#define __AudioThread
#include "byteStructure.hpp"
#include "fmodRecord.h"
#include <cstdio>
#include <exception>
#include <iostream>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
typedef
enum {
waitingForFile,
waitingOnRead,
reading,
waitingOnFFT,
FFT,
waitingOnWrite,
writing
} PoolStage;
class
AudioThread
{
friend class Kazaam;
private:
FILE *f;
string WavFileName;
long dataPointer;
long fileSize;
PoolStage stage;
int channel0Len, channel1Len;
vector<short> channel0;
vector<short> channel1;
void setFileName(string fname);
int readData(); //Fill the channel buffers with data from wav file
int writeData(FILE *f); // write out to ???
void reset(); // reset back to original state
void analyze(); //FFT and whatnot
void record();
public:
AudioThread();
~AudioThread();
};
AudioThread::
AudioThread()
{
WavFileName = "";
dataPointer = 40; // The byte offset where data size is
channel0Len = channel0.size();
channel1Len = channel1.size();
stage = waitingForFile;
}
AudioThread::
~AudioThread()
{
//Make sure that our buffers are empty
channel0.clear();
channel1.clear();
}
void AudioThread::
setFileName(string fname)
{
WavFileName = fname;
stage = waitingOnRead;
}
int AudioThread::
readData()
{
stage = reading;
//Open the File
try
{
f = fopen(WavFileName.c_str(), "rb");
}
catch(exception &e)
{
cout << e.what() << endl;
return -1;
}
fseek(f, dataPointer, SEEK_SET); // Move the File pointer to data subchunk
//Read the size from the subchunk header
LongFromChar val;
byte a = fgetc(f);
byte b = fgetc(f);
byte c = fgetc(f);
byte d = fgetc(f);
long size = charToLong(a,b,c,d);
/*The data subchunk is arranged with interleaved channels
* [channel0][channel1][channel0][channel1]
* short short short short
*/
while (dataPointer < size + 40)
{
a = fgetc(f);
b = fgetc(f);
c = fgetc(f);
d = fgetc(f);
channel0.push_back(charToShort(a,b)); //Left channel
channel1.push_back(charToShort(c,d)); //Right channel
dataPointer += 4; //Skip to the next block
}
fclose(f);
dataPointer = 40; // Reset data pointer
stage = waitingOnFFT; // Move to the next section in the pool
return 1;
}
void AudioThread::
reset()
{
WavFileName = ""; // Clear the file name
fileSize = -1; //Reset file size
stage = waitingForFile; //Reset the stage
}
void AudioThread::
analyze()
{
}
void AudioThread::
record()
{
}
//Read Shorts from Chars
struct ShortFromChar
{
byte a, b;
};
//Read Longs from Chars
struct LongFromChar
{
byte a, b, c, d;
};
//Little Endian only
unsigned long charToLong(byte a, byte b, byte c, byte d)
{
LongFromChar val;
val.a = a;
val.b = b;
val.c = c;
val.d = d;
unsigned long *l = (unsigned long*) &val;
return *l;
}
//Little Endian only
unsigned short charToShort(byte a, byte b)
{
ShortFromChar val;
val.a = a;
val.b = b;
unsigned short *s = (unsigned short*) &val;
return *s;
}
#endif | true |
6083768f7da32181676b577401dab50ecba38c7b | C++ | ravi-ojha/competitive-sport | /spoj/FASHION/fashion.cpp | UTF-8 | 394 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf(" %d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int res = 0;
int a[n];
int b[n];
for(int i=0;i<n;i++)
{
scanf(" %d",&a[i]);
}
for(int i=0;i<n;i++)
{
scanf(" %d",&b[i]);
}
sort(a,a+n);
sort(b,b+n);
for(int i=0;i<n;i++)
{
res += a[i]*b[i];
}
printf("%d\n",res);
}
return 0;
}
| true |
4789182c18a8eb3063764f73657b940bbfead44b | C++ | SOFTK2765/PS | /BOJ/10813.cpp | UTF-8 | 444 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int a[101];
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
return;
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
for(int i=0;i<n;i++)
a[i] = i+1;
while(m--)
{
int n1, n2;
scanf(" %d %d", &n1, &n2);
swap(&a[n1-1], &a[n2-1]);
}
for(int i=0;i<n;i++)
printf("%d ", a[i]);
return 0;
} | true |
431bf922b0141c703fff2ce3d625adbf4ff09018 | C++ | clw5180/My-notes-of-C-and-exercises-of-CppPrimer-5th | /C++ Primer第5版个人答案/Chapter8/Exercise 8.9.cpp | UTF-8 | 280 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
istream &Print(istream& is)
{
string str;
while (is >> str)
cout << str << endl;
is.clear();
return is;
}
int main()
{
istringstream inStringStream("aaa");
Print(inStringStream);
return 0;
} | true |
d87df631f2a56bd9a8b9a4b7422a1402879adbbd | C++ | jnrdrgz/SDL_Playground | /opengl/test/f.cpp | UTF-8 | 998 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <alloca.h>
struct ShaderProgramSource
{
std::string VertexSource;
std::string FragmentSource;
};
static ShaderProgramSource ParseShader(std::string filepath)
{
std::ifstream stream(filepath);
enum class ShaderType
{
NONE = -1, VERTEX = 0, FRAGMENT = 1
};
std::string line;
std::stringstream ss[2];
ShaderType type = ShaderType::NONE;
auto _p = [](const std::string& l, const std::string& v) {return l.find(v) != std::string::npos; };
while (getline(stream, line)) {
if (_p(line, "#shader"))
{
if (_p(line, "vertex")) type = ShaderType::VERTEX;
else if (_p(line, "fragment")) type = ShaderType::FRAGMENT;
}
else {
ss[(int)type] << line << "\n";
}
}
return { ss[0].str(),ss[1].str() };
}
int main(){
ShaderProgramSource a = ParseShader("Basic.shader");
std::cout << "vertex\n";
std::cout << a.VertexSource << "\n";
std::cout << "fragment\n";
std::cout << a.FragmentSource << "\n";
} | true |
5d46e450a3f65465a28115370f45833371b93e36 | C++ | Jerromylynn/The-first-stage | /求a+aa+aaa……的值.cpp | UTF-8 | 210 | 2.875 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
void plus(int *m,int a){
*m=(*m)*10+a;
}
int main(){
int a,n,m=0;
int sum=0;
scanf("%d%d",&a,&n);
m=a;
for(int i=0;i<n;i++){
sum+=m;
plus(&m,a);
}
printf("%d",sum);
return 0;
}
| true |
c75936992d6e5e274ef472ea57f908262a713642 | C++ | lozinska/OOP345 | /ws4/at_home/Notifications.cpp | UTF-8 | 2,894 | 3.390625 | 3 | [] | no_license | // Workshop 4 - Containers
// w4.cpp
// Krystyna Lopez
// 2019/02/13
#include"Notifications.h"
namespace sict {
//Default constructor
//
Notifications::Notifications() {};
//A one argument constructor that dynamically allocate memory for the specified number of pointers
//
Notifications::Notifications(int mxNum):max_num(mxNum) {
if (max_num > 0) {
mess = new const Message*[max_num];
}
else *this = Notifications();
};
//Copy constructor
//
Notifications::Notifications(const Notifications& note) : mess(new const Message*[note.max_num]) {
*this = note;
};
//Copy assignment operator
//
Notifications& Notifications:: operator=(const Notifications& note){
if (this != ¬e) {
delete[] mess;
mess = new const Message*(*note.mess);
max_num = note.max_num;
currentNum = note.currentNum;
}
return *this;
};
//Move constructor
//
Notifications::Notifications(Notifications&& note) {
*this = std::move(note);
};
//Move assignment operator
//
Notifications& Notifications::operator=(Notifications&& note) {
if (this != ¬e) {
delete[] mess;
mess = note.mess;
max_num = note.max_num;
currentNum = note.currentNum;
note.mess = nullptr;
note.max_num = 0;
note.currentNum = 0;
}
return *this;
};
//A modifier that receives a reference to an unmodifiable Message object
//
Notifications& Notifications::operator+=(const Message& msg) {
if (!msg.empty() && currentNum <= max_num) {
mess[currentNum++] = &msg;
}
return *this;
};
//A modifier that receives a reference to an unmodifiable Message object
//
Notifications& Notifications::operator-=(const Message&msg) {
bool found = false;
int i;
for (i = 0; i < currentNum && !found; i++) {
if (mess[i] == &msg)
{
found = true;
}
}
if (found) {
for (; i < currentNum; i++) {
mess[i - 1] = mess[i];
}
if (currentNum) {
mess[currentNum - 1] = nullptr;
currentNum--;
}
}
return *this;
};
//A query that inserts into os stream
//
void Notifications::display(std::ostream& os) const {
if (currentNum!=0&&mess!=nullptr) {
for (int i = 0; i < currentNum; i++) {
mess[i]->display(os);
}
}
};
//A query that returns the number of Message objects pointed to by the current object
//
size_t Notifications::size() const {
return currentNum;
};
//Destructor
//
Notifications::~Notifications() {
delete[] mess;
}
//Non-friend helper function
//
std::ostream& operator<<(std::ostream& os, const Notifications& note) {
note.display(os);
return os;
};
} | true |
d3b7d443cb174a734f1ae73f90232c742db52dec | C++ | ElizabethYasmin/MoveSeman | /stdMove.cpp | ISO-8859-1 | 2,281 | 4.03125 | 4 | [] | no_license | /* el move estndar funciona en realidad como un conversor de tipo
se utiliza para decirle al compilador que utilice un objeto como
si fuera un rvalue,lo que significa que se puede mover*/
#include <cstdio>
#include <vector>//para usar std::vector
#include <string>
#include <utility>
void message(const std::string & s) {//funcion para mostrar un mensaje en la pantalla
puts(s.c_str());
fflush(stdout);
}
void disp_vector(const std::vector<std::string> & v) {//Funcion que muestra los vectores
size_t size = v.size();
printf("vector size: %ld\n", size);
if(size) {
for( std::string s : v ) {
printf("[%s]", s.c_str());/*c_str devuelve un const char* que apunta
a una cadena terminada en nulo (es decir, una cadena de estilo C).
Es til cuando quiere pasar el "contenido" de un std::string a una
funcin que espera trabajar con una cadena de estilo C.*/
}
puts("");//salto de linea
}
fflush(stdout);
}
//EL STD::MOVE SE PUEDE USAR PARA REALIZAR UNA FUNCION DE INTERCAMBIO(sin utilizar copia)
template <typename T>
void swap(T & a,T & b){
message("llamando swap()");
T tmp(std::move(a));
a=std::move(b);
b=std::move(tmp);
}
int main( int argc, char ** argv ) {
/*std::vector ->Un vector es una matriz dinmica con
almacenamiento manejado automticamente.
Se puede acceder a los elementos de un vector con la misma
eficacia que los de una matriz, con la ventaja de que los
vectores pueden cambiar dinmicamente de tamao.*/
std::vector<std::string> v1 = { "uno", "dos", "tres", "cuatro", "cinco" };
/*std::string (a diferencia de una cadena C) puede contener el carcter \0.*/
std::vector<std::string> v2 = { "seis", "siete", "ocho", "nueve", "diez" };
message("v1");
disp_vector(v1);
message("v2");
disp_vector(v2);
message("-----------------------------------");
//FUNCION ESTANDAR SWAP
//std::swap(v1,v2);
//FUNCION SWAP
//::swap(v1,v2);
//COPIANDO ELEMENTOS
//v2=v1;
//MOVIENDO V1 A V2
//v2=std::move(v1);//funcion plantilla de move/conversor
// de tipo que dice que esto se puede mover
message("v1");
disp_vector(v1);
message("v2");
disp_vector(v2);
return 0;
}
| true |
48363d29bd713b9a91013080137ed6fae51c88b1 | C++ | team3130/Granite | /Granite/src/Commands/RobotSensors.cpp | UTF-8 | 2,118 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include "RobotSensors.h"
#include "Subsystems/Chassis.h"
#include "Video.h"
RobotSensors::RobotSensors()
{
arduino = new SerialPort(57600, SerialPort::kMXP);
arduino->SetWriteBufferMode(SerialPort::kFlushOnAccess);
timer = new Timer();
this->SetRunWhenDisabled(true);
}
RobotSensors::~RobotSensors()
{
delete arduino;
delete timer;
}
// Called just before this Command runs the first time
void RobotSensors::Initialize()
{
timer->Reset();
timer->Start();
SmartDashboard::PutString("DB/String 9", "Test 3130");
}
// Called repeatedly when this Command is scheduled to run
void RobotSensors::Execute()
{
if(timer->Get() > 0.05) {
timer->Reset();
timer->Start();
size_t nTurns = 0;
double turn = 0;
RobotVideo::GetInstance()->mutex_lock();
nTurns = RobotVideo::GetInstance()->HaveHeading();
if(nTurns > 0) turn = RobotVideo::GetInstance()->GetTurn(0);
if(nTurns > 1) {
double turn2 = RobotVideo::GetInstance()->GetTurn(1);
if(fabs(turn2) < fabs(turn)) turn = turn2;
}
RobotVideo::GetInstance()->mutex_unlock();
if (nTurns>0) {
int res = 0.5 * (fabs(turn) + 1.5);
std::ostringstream oss2;
oss2 << "Target: " << res;
SmartDashboard::PutString("DB/String 2", oss2.str());
if (fabs(turn) < 1.5) res = 0;
if (res > 9) res = 9;
std::ostringstream oss;
oss << "Solid " << res << "\n";
arduino->Write(oss.str(), oss.str().size());
}
else {
SmartDashboard::PutString("DB/String 2", "no target");
}
}
std::ostringstream oss0;
oss0 << "Angle: " << ChassisSubsystem::GetInstance()->GetAngle();
SmartDashboard::PutString("DB/String 0", oss0.str());
std::ostringstream oss1;
oss1 << "Pos: " << ChassisSubsystem::GetInstance()->GetDistance();
SmartDashboard::PutString("DB/String 1", oss1.str());
}
// Make this return true when this Command no longer needs to run execute()
bool RobotSensors::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void RobotSensors::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void RobotSensors::Interrupted()
{
}
| true |
699d256f7572839203bbb95ebd573a430295d3d1 | C++ | yujincheng08/bisoncpp | /bisonc++/atdollar/operatorinsert.cc | UTF-8 | 552 | 2.5625 | 3 | [] | no_license | #include "atdollar.ih"
std::ostream &operator<<(std::ostream &out, AtDollar const &atd)
{
out << "At line " << atd.d_lineNr << ", block pos. " << atd.d_pos <<
", length: " << atd.d_length << ": `" <<
atd.text() << "' (Pattern = " << atd.d_pattern << ')';
if (atd.d_tag.length())
out << "; <" << atd.d_tag << '>';
if (atd.d_nr == numeric_limits<int>::max())
out << " $";
else
out << ' ' << atd.d_nr;
if (atd.d_refByScanner)
out << " (ref. by scanner)";
return out;
}
| true |
25a193061dc5e827f419049841898e46659c189c | C++ | chiawei716/Course-OOP2019 | /HW05/E14056431/HW05_01/HW05_01.cpp | UTF-8 | 1,201 | 3.34375 | 3 | [] | no_license | // Copyright © 2019 趙珈葦. All Rights Reserved.
// 系級: 機械109
// 學號: E14056431
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>
// #1: outint() -> lambda_1
auto lambda_1 = [](int n) { std::cout << n << " "; };
// #2: f100 -> lambda_2
auto lambda_2 = [](const int & n) { return n > 100; };
int main()
{
int vals[10] = { 50, 100, 90, 180, 60, 210, 415, 88, 188, 201 };
std::list<int> yadayada(vals, vals + 10);
std::list<int> etcetera(vals, vals + 10);
std::cout << "Original lists:\n";
for_each(yadayada.begin(), yadayada.end(), lambda_1); // #1 - Replace outint() with lambda_1 functor
std::cout << std::endl;
for_each(etcetera.begin(), etcetera.end(), lambda_1);
std::cout << std::endl;
yadayada.remove_if(lambda_2); // #2 - Replace f100 with lambda_2 functor
etcetera.remove_if([](const int & n) {return n > 200; }); // #3 - Replace TooBig<int>(200) with functor
std::cout << "Trimmed lists:\n";
for_each(yadayada.begin(), yadayada.end(), lambda_1);
std::cout << std::endl;
for_each(etcetera.begin(), etcetera.end(), lambda_1);
std::cout << std::endl;
std::cin.get();
return 0;
}
| true |
8b7529cf16b0ef59858459d26c1fad79ddf9cb00 | C++ | famo7/project-trains | /include/PersonVagn.h | UTF-8 | 711 | 2.765625 | 3 | [] | no_license | // Filename: PersonVagn.h
// Written by: Farhan Mohamed
// Created date: 14/10/2020
// Last modified: 11/01/2020
/* Description: Header file containing the class definition for PersonVagn class.
*/
#ifndef PROJECT_PERSONVAGN_H
#define PROJECT_PERSONVAGN_H
#include "Vagn.h"
class PersonVagn: public Vagn {
private:
int sitPlatser;
bool internet;
public:
// constructor
PersonVagn(int uniqId, int type, int sitP, bool inter);
// getters
int getSitplatser() const{return sitPlatser;}
bool getInternet() const{return internet;}
// overriden print method
void print(ostream &os) override;
// overriden destructor
~PersonVagn() override;
};
#endif //PROJECT_PERSONVAGN_H
| true |
c8240aca953a050aa419aece3f3069b9befa34b0 | C++ | xellie4/IEP_LAB | /Lucrarea4/VladAdrian/main.cpp | UTF-8 | 1,006 | 3.765625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Countries{
private:
string name, climate;
float population;
public:
Countries(string name, string climate, float population):name(name), climate(climate), population(population){}
~Countries(){};
void getName(){
cout<<name<<'\n';
}
void getClimate(){
cout<<climate<<'\n';
}
void getPopulation(){
cout<<population<<'\n';
}
Countries(const Countries &CountriesSec){
name = CountriesSec.name;
climate = CountriesSec.climate;
population = CountriesSec.population;
};
Countries& operator = (const Countries &countries){
return *this;
};
};
int main(){
Countries romania("Romania","temperat",19.31);
Countries romania2 = Countries(romania);
Countries romania3(romania2);
romania.getName();
romania2.getClimate();
romania3.getPopulation();
return 0;
} | true |
7a3b32596bdb2971d970b5d2d08475809671b44a | C++ | zinsmatt/Graph | /graph_kernel/include/adjacencymatrix.h | UTF-8 | 3,135 | 3.390625 | 3 | [] | no_license | #ifndef ADJACENCYMATRIX_H
#define ADJACENCYMATRIX_H
#include "edge.h"
#include "squarematrix.h"
#include "graphcontainer.h"
#include "types.h"
#include <map>
class AdjacencyMatrix : private SquareMatrix<Edge*>, public GraphContainer
{
private:
std::map<ElementId, int> idToIndex; //!< map between node id and index in the matrix
/* \brief Direct access to the matrix
* \param index
* \return a pointer to the edge if it exists, else nullptr
* */
Edge* get(int x,int y) { return this->SquareMatrix<Edge*>::get(x,y); }
/* \brief const access to the matrix
* \param index
* \return a const pointer to the edge if it exists, else nullptr
* */
const Edge* get(int x,int y) const { return this->SquareMatrix<Edge*>::get(x,y); }
/* \brief Get the node index in the matrix
* \param a pointer to the node
* \return index if the node exist, else -1
* */
int getNodeIndex(Node *n);
public:
/* just for tests*/
/* \brief Constructor
* \param size of the matrix and an initial value
* */
AdjacencyMatrix(int size, Edge* initValue = nullptr);
/* \brief Constructor without parameter
* */
AdjacencyMatrix();
/* \brief Destructor
* */
virtual ~AdjacencyMatrix();
/* \brief Add a Node to the matrix
* \param a pointer to the node
* \return throw exception if problem
* */
virtual void addNode(Node* node);
/* \brief Remove a node from the matrix
* \param a pointer to the node to remove
* \return throw exception if problem
* */
virtual void removeNode(Node* node);
/* \brief Add an edge to the matrix
* \param a pointer to the edge
* \return throw exception if problem
* */
virtual void addEdge(Edge *edge);
/* \brief Remove an edge from the matrix
* \param a pointer to the edge to remove
* \return throw exception if problem
* */
virtual void removeEdge(Edge *edge);
/* \brief Get an edge (may be use this method when Graph::getEdge() because faster ?)
* \param two pointers to the nodes
* \return a pointeur to the edge if it exists, else nullptr
* */
virtual Edge* getEdge(Node* n1, Node *n2);
// TEMPORAIRE PAS UTILE
/* \brief Get the matrix only
* \return a reference to the square matrix
* */
// SquareMatrix<Edge*>& getMatrix() { return static_cast<SquareMatrix<Edge*>&>(*this); }
// PAS UTILE getNbNode plutot
/* \brief Get the size of the matrix
* */
// int size() const { return this->SquareMatrix<Edge*>::size(); }
/* \brief Get a string that describes the object
* \return an std::string containing the description
* */
virtual std::string toString() const;
/* \brief Get the number of nodes in the matrix
* */
int getNbNodes() const { return idToIndex.size(); }
};
/* \brief operator << to ouput an adjacency matrix
* \param output stream and a reference to the matrix
* \return a reference to the stream
* */
std::ostream& operator<<(std::ostream& os, AdjacencyMatrix& m);
#endif // ADJACENCYMATRIX_H
| true |
8b917662e596365801b4850d1127598d84d054bc | C++ | narodnik/zkfrag | /include/libdark/pirromean/gate.hpp | UTF-8 | 1,714 | 2.546875 | 3 | [] | no_license | #ifndef LIBDARK_PIRROMEAN_GATE_HPP
#define LIBDARK_PIRROMEAN_GATE_HPP
#include <memory>
#include <vector>
#include <libdark/pirromean/portal.hpp>
namespace libdark {
template <typename CurveType>
class pirr_gate
{
public:
typedef typename CurveType::ec_scalar ec_scalar;
typedef typename pirr_portal<CurveType>::ptrlist portal_ptrlist;
typedef std::shared_ptr<pirr_gate> ptr;
typedef std::vector<ptr> ptrlist;
pirr_gate(size_t index);
ptr clone_public() const;
size_t index() const;
bool is_start() const;
bool is_end() const;
bool has_challenge() const;
const ec_scalar& challenge() const;
void set_challenge(const ec_scalar& challenge);
void compute_challenge();
bool has_empty_input_witnesses() const;
portal_ptrlist inputs() const;
portal_ptrlist outputs() const;
std::string pretty(size_t indent=0) const;
private:
enum class position_type
{
start,
default_,
end
};
template <typename GatePtrType>
friend void link(GatePtrType start, GatePtrType end);
template <typename GatePtrType, typename PortalPtrType>
friend void connect(
GatePtrType start, PortalPtrType portal, GatePtrType end);
const size_t index_;
position_type position_ = position_type::default_;
// Gates collectively own the portals
portal_ptrlist inputs_, outputs_;
ec_scalar challenge_;
};
template <typename GatePtrType>
void link(GatePtrType start, GatePtrType end);
template <typename GatePtrType, typename PortalPtrType>
void connect(GatePtrType start, PortalPtrType portal, GatePtrType end);
} // namespace libdark
#include <libdark/impl/pirromean/gate.ipp>
#endif
| true |
d2ce22f736646aa82e84ef3fb2f5c7ce655f3d38 | C++ | nileshkulkarni/Compilers | /Level3/110050007-110050034/ast.cc | UTF-8 | 20,695 | 2.53125 | 3 | [] | no_license |
/*********************************************************************************************
cfglp : A CFG Language Processor
--------------------------------
About:
Implemented by Tanu Kanvar (tanu@cse.iitb.ac.in) and Uday
Khedker (http://www.cse.iitb.ac.in/~uday) for the courses
cs302+cs306: Language Processors (theory and lab) at IIT
Bombay.
Release date Jan 15, 2013. Copyrights reserved by Uday
Khedker. This implemenation has been made available purely
for academic purposes without any warranty of any kind.
Documentation (functionality, manual, and design) and related
tools are available at http://www.cse.iitb.ac.in/~uday/cfglp
***********************************************************************************************/
#include<iostream>
#include<fstream>
using namespace std;
#include "user-options.hh"
#include "error-display.hh"
#include "local-environment.hh"
#include "symbol-table.hh"
#include "ast.hh"
#include "basic-block.hh"
#include "procedure.hh"
#include "program.hh"
#include <iomanip>
#define replace(r) ((r.data_type == double_data_type)? r.double_ret : (r.data_type == float_data_type)? r.float_ret : r.int_ret)
#define assign_replace(r,v) ((r.data_type == double_data_type)? r.double_ret =v: (r.data_type == float_data_type)? r.float_ret =v: r.int_ret =v)
Ast::Ast()
{}
Ast::~Ast()
{}
bool Ast::check_ast(int line)
{
report_internal_error("Should not reach, Ast : check_ast");
}
Data_Type Ast::get_data_type()
{
report_internal_error("Should not reach, Ast : get_data_type");
}
void Ast::print_value(Local_Environment & eval_env, ostream & file_buffer)
{
report_internal_error("Should not reach, Ast : print_value");
}
Eval_Result & Ast::get_value_of_evaluation(Local_Environment & eval_env)
{
report_internal_error("Should not reach, Ast : get_value_of_evaluation");
}
void Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result)
{
report_internal_error("Should not reach, Ast : set_value_of_evaluation");
}
////////////////////////////////////////////////////////////////
Assignment_Ast::Assignment_Ast(Ast * temp_lhs, Ast * temp_rhs)
{
lhs = temp_lhs;
rhs = temp_rhs;
}
Assignment_Ast::~Assignment_Ast()
{
delete lhs;
delete rhs;
}
/*
void Assignment_Ast::set_data_type(Data_Type data_type)
{
node_data_type=data_type;
}
*/
Data_Type Assignment_Ast::get_data_type()
{
return node_data_type;
}
bool Assignment_Ast::check_ast(int line)
{
if (lhs->get_data_type() == rhs->get_data_type())
{
node_data_type = lhs->get_data_type();
return true;
}
cout<<lhs->get_data_type() <<" : "<<rhs->get_data_type()<<endl;
report_error("Assignment statement data type not compatible", line);
}
void Assignment_Ast::print_ast(ostream & file_buffer)
{
file_buffer << AST_SPACE << "Asgn:\n";
file_buffer << AST_NODE_SPACE"LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")\n";
file_buffer << AST_NODE_SPACE << "RHS (";
rhs->print_ast(file_buffer);
file_buffer << ")";
}
Eval_Result & Assignment_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result & result = rhs->evaluate(eval_env, file_buffer);
if (result.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
lhs->set_value_of_evaluation(eval_env, result);
// Print the result
print_ast(file_buffer);
lhs->print_value(eval_env, file_buffer);
return result;
}
/////////////////////////////////////////////////////////////////
Name_Ast::Name_Ast(string & name, Symbol_Table_Entry & var_entry)
{
variable_name = name;
variable_symbol_entry = var_entry;
}
Name_Ast::~Name_Ast()
{}
Data_Type Name_Ast::get_data_type()
{
return variable_symbol_entry.get_data_type();
}
void Name_Ast::print_ast(ostream & file_buffer)
{
file_buffer << "Name : " << variable_name;
}
void Name_Ast::printFormatted(ostream & file_buffer , Eval_Result_Ret R){
file_buffer<< std::fixed << std::setprecision(2) ;
if(R.data_type == int_data_type)
file_buffer<<R.int_ret;
else if(R.data_type == float_data_type)
file_buffer<<R.float_ret;
else if(R.data_type == double_data_type)
file_buffer<<setprecision(4)<<R.double_ret;
}
void Name_Ast::print_value(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result_Value * loc_var_val = eval_env.get_variable_value(variable_name);
Eval_Result_Value * glob_var_val = interpreter_global_table.get_variable_value(variable_name);
file_buffer << "\n" << AST_SPACE << variable_name << " : ";
if (!eval_env.is_variable_defined(variable_name) && !interpreter_global_table.is_variable_defined(variable_name))
file_buffer << "undefined";
else if (eval_env.is_variable_defined(variable_name) && loc_var_val != NULL)
{
//cout<<"enum is "<<loc_var_val->get_result_enum()<<endl;
if ((loc_var_val->get_result_enum() == int_result) || (loc_var_val->get_result_enum() == float_result)){
printFormatted(file_buffer , loc_var_val->get_value());
}
else
report_internal_error("Result type can only be int and float");
}
else
{
if ((glob_var_val->get_result_enum() == int_result) || (glob_var_val->get_result_enum() == float_result))
{
if (glob_var_val == NULL)
file_buffer << "0\n";
else
printFormatted(file_buffer , glob_var_val->get_value()); }
else
report_internal_error("Result type can only be int and float");
}
file_buffer << "\n";
}
Eval_Result & Name_Ast::get_value_of_evaluation(Local_Environment & eval_env)
{
if (eval_env.does_variable_exist(variable_name))
{
Eval_Result * result = eval_env.get_variable_value(variable_name);
return *result;
}
Eval_Result * result = interpreter_global_table.get_variable_value(variable_name);
result->set_variable_status(true);
return *result;
}
void Name_Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result)
{
// cout<<"comes here"<<endl;
Eval_Result_Value * i;
if (result.get_result_enum() == int_result)
{
i = new Eval_Result_Value_Int();
i->set_value(result.get_value());
}
if (result.get_result_enum() == float_result)
{
i = new Eval_Result_Value_Float();
i->set_value(result.get_value());
}
if (eval_env.does_variable_exist(variable_name))
eval_env.put_variable_value(*i, variable_name);
else
interpreter_global_table.put_variable_value(*i, variable_name);
// cout<<"goes from here"<<endl;
}
Eval_Result & Name_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
return get_value_of_evaluation(eval_env);
}
///////////////////////////////////////////////////////////////////////////////
template <class DATA_TYPE>
Number_Ast<DATA_TYPE>::Number_Ast(DATA_TYPE number, Data_Type constant_data_type)
{
constant = number;
node_data_type = constant_data_type;
}
template <class DATA_TYPE>
Number_Ast<DATA_TYPE>::~Number_Ast()
{}
template <class DATA_TYPE>
Data_Type Number_Ast<DATA_TYPE>::get_data_type()
{
return node_data_type;
}
template <class DATA_TYPE>
void Number_Ast<DATA_TYPE>::printFormatted(ostream & file_buffer , Eval_Result_Ret R){
file_buffer<<std::fixed << std::setprecision(2);
if(R.data_type == int_data_type)
file_buffer<<R.int_ret;
else if(R.data_type == float_data_type)
file_buffer<<setprecision(2)<<R.float_ret;
else if(R.data_type == double_data_type)
file_buffer<<setprecision(4)<<R.double_ret;
}
template <class DATA_TYPE>
void Number_Ast<DATA_TYPE>::print_ast(ostream & file_buffer)
{
Eval_Result_Ret R;
R.data_type = node_data_type;
assign_replace(R , constant);
file_buffer << "Num : ";
printFormatted(file_buffer , R);
}
template <class DATA_TYPE>
Eval_Result & Number_Ast<DATA_TYPE>::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if (node_data_type == int_data_type)
{
Eval_Result_Value_Int & result = *new Eval_Result_Value_Int();
result.set_value(constant);
return result;
}
if (node_data_type == float_data_type)
{
Eval_Result_Value_Float & result = *new Eval_Result_Value_Float();
result.set_value(constant);
return result;
}
if (node_data_type == double_data_type)
{
Eval_Result_Value_Double & result = *new Eval_Result_Value_Double();
result.set_value(constant);
return result;
}
}
///////////////////////////////////////////////////////////////////////////
IfElse_Ast ::IfElse_Ast(Ast * _condition , Goto_Ast * if_Goto, Goto_Ast * else_Goto){
condition = _condition;
ifGoto = if_Goto;
elseGoto = else_Goto;
}
IfElse_Ast ::~IfElse_Ast(){
delete(condition);
delete(ifGoto);
delete(elseGoto);
}
void IfElse_Ast :: print_ast(ostream & file_buffer){
file_buffer << AST_SPACE << "If_Else statement: " ;
condition->print_ast(file_buffer);
file_buffer<<"\n";
file_buffer<<AST_NODE_SPACE<<"True Successor: " <<ifGoto->get_bb();
file_buffer<<"\n";
file_buffer<<AST_NODE_SPACE<<"False Successor: "<<elseGoto->get_bb();
}
Eval_Result & IfElse_Ast:: evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result_Value_Goto & ret = *new Eval_Result_Value_Goto();
// file_buffer<<"here and there : "<<result.get_value()<<endl;
file_buffer << AST_SPACE << "If_Else statement: " ;
condition->print_ast(file_buffer);
file_buffer<<"\n";
Eval_Result & result = condition->evaluate(eval_env, file_buffer);
file_buffer<<AST_NODE_SPACE<<"True Successor: " <<ifGoto->get_bb();
file_buffer<<"\n";
file_buffer<<AST_NODE_SPACE<<"False Successor: "<<elseGoto->get_bb();
file_buffer<<"\n";
if((result.get_value()).int_ret != 0){
file_buffer<<AST_SPACE<<"Condition True : Goto (BB "<<ifGoto->get_bb()<<")";
ret.set_value(ifGoto->get_bb());
}
else{
file_buffer<<AST_SPACE<<"Condition False : Goto (BB "<<elseGoto->get_bb()<<")";
ret.set_value(elseGoto->get_bb());
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////
Goto_Ast :: Goto_Ast(int _bb){
bb = _bb;
}
Goto_Ast :: ~Goto_Ast(){}
int Goto_Ast :: get_bb(){
return bb;
}
void Goto_Ast :: print_ast(ostream & file_buffer){
file_buffer << AST_SPACE <<"Goto statement:\n";
file_buffer << AST_NODE_SPACE << "Successor: "<<bb<<"\n";
};
Eval_Result & Goto_Ast:: evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result & result = *new Eval_Result_Value_Goto();
Eval_Result_Ret gotoRet;
gotoRet.data_type = int_data_type;
gotoRet.int_ret =bb;
result.set_value(gotoRet);
print_ast(file_buffer);
file_buffer << AST_SPACE << "GOTO (BB "<<bb<<")";
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////
Expression_Ast :: Expression_Ast(Ast * _lhs , Ast * _rhs , OperatorType _op){
lhs = _lhs;
assert(_rhs != NULL) ;
rhs = _rhs;
if((_op == GE) || (_op == EQ) || (_op == NE) || (_op == LT) || (_op == GT) || (_op == LE))
node_data_type = int_data_type;
else
node_data_type = lhs->get_data_type(); //## TO-DO , DONE
op = _op;
}
Expression_Ast :: Expression_Ast(Ast * _atomic_exp , Data_Type _T){
lhs = _atomic_exp;
rhs = NULL;
node_data_type = _T;
}
bool Expression_Ast::check_ast(int line)
{
if(rhs == NULL){
return true;
}
if ((lhs->get_data_type() == rhs->get_data_type())
|| (((lhs->get_data_type() == float_data_type) || (lhs->get_data_type() == double_data_type))
&&
((rhs->get_data_type() == float_data_type) || (rhs->get_data_type() == double_data_type))))
{
if((op == GE) || (op == EQ) || (op == NE) || (op == LT) || (op == GT) || (op == LE))
node_data_type = int_data_type;
else
node_data_type = lhs->get_data_type(); //## TO-DO , DONE
return true;
}
cout<<"rhs data type "<<rhs->get_data_type()<<endl;
cout<<"lhs data type "<<lhs->get_data_type()<<endl;
cout<<"Operator "; printOperator(cout , op); cout<<endl;
report_error("Expression statement data type not compatible", line);
}
Data_Type Expression_Ast::get_data_type()
{
return node_data_type;
}
void Expression_Ast :: print_ast(ostream & file_buffer){
if(rhs == NULL){
lhs->print_ast(file_buffer);
return;
}
file_buffer <<"\n";
file_buffer << AST_NODE_SPACE;
if((op == GE) || (op == EQ) || (op == NE) || (op == LT) || (op == GT) || (op == LE))
file_buffer << "Condition: ";
else
file_buffer << "Arith: ";
printOperator(file_buffer , op);
file_buffer <<"\n";
file_buffer << AST_CONDITION_SPACE << "LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")";
file_buffer << "\n" << AST_CONDITION_SPACE<< "RHS (";
rhs->print_ast(file_buffer);
file_buffer<<")";
}
void Expression_Ast :: printOperator(ostream& file_buffer,Expression_Ast::OperatorType op){
if(rhs == NULL){
file_buffer<<"CASTED EXP: NO OP";
return;
}
switch(op){
case GT: file_buffer<<"GT";break;
case LT: file_buffer<<"LT";break;
case LE: file_buffer<<"LE";break;
case GE: file_buffer<<"GE";break;
case EQ: file_buffer<<"EQ";break;
case NE: file_buffer<<"NE";break;
case PLUS: file_buffer<<"PLUS";break;
case MINUS: file_buffer<<"MINUS";break;
case MULT: file_buffer<<"MULT";break;
case DIV: file_buffer<<"DIV";break;
}
}
Eval_Result &Expression_Ast :: evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result *temp;
Eval_Result_Ret res;
Eval_Result_Ret lVal;
Eval_Result_Ret rVal;
if(node_data_type == float_data_type){
temp = new Eval_Result_Value_Float();
}
else if(node_data_type == double_data_type){
temp = new Eval_Result_Value_Double();
}
else if(node_data_type == int_data_type){
temp = new Eval_Result_Value_Int();
}
Eval_Result &result = *temp;
lVal =(lhs->evaluate(eval_env,file_buffer)).get_value();
if(rhs == NULL){
res.data_type = node_data_type;
assign_replace(res , replace(lVal));
// cout<<"node_data_type is "<<((node_data_type == float_data_type)? "FLOAT" : "INT") << " \n" ;
}
else{
rVal =(rhs->evaluate(eval_env,file_buffer)).get_value();
res.data_type = node_data_type;
// cout<<"node_data_type is "<<((node_data_type == float_data_type)? "FLOAT" : "INT") << " \n" ;
switch(op){
case GT:
assign_replace(res , replace(lVal)>replace(rVal));
break;
case LT:
assign_replace(res , replace(lVal) < replace(rVal));
break;
case EQ:
assign_replace(res , replace(lVal) ==replace(rVal));
break;
case NE:
assign_replace(res , replace(lVal) !=replace(rVal));
break;
case GE:
assign_replace(res , replace(lVal) >=replace(rVal));
break;
case LE:
assign_replace(res , replace(lVal) <=replace(rVal));
break;
case PLUS:
assign_replace(res , replace(lVal) + replace(rVal));
break;
case MINUS:
assign_replace(res , replace(lVal) - replace(rVal));
break;
case MULT:
assign_replace(res , replace(lVal) * replace(rVal));
break;
case DIV:
assign_replace(res , replace(lVal) / replace(rVal));
break;
}
}
result.set_value(res);
return result;
}
///////////////////////////////////////////////////////////////////////////
UnaryExpression_Ast :: UnaryExpression_Ast(Ast *_exp , Expression_Ast::OperatorType _op){
exp = _exp;
node_data_type = exp->get_data_type();
op = _op;
}
void UnaryExpression_Ast :: printOperator(ostream& file_buffer,Expression_Ast::OperatorType op){
switch(op){
case Expression_Ast::UMINUS: file_buffer<<"UMINUS";break;
}
}
UnaryExpression_Ast :: ~UnaryExpression_Ast(){
}
Data_Type UnaryExpression_Ast :: get_data_type(){
return node_data_type;
}
void UnaryExpression_Ast :: print_ast(ostream & file_buffer){
file_buffer <<"\n";
//exp->printOperator(file_buffer,op); //## TO-DO
file_buffer << AST_NODE_SPACE;
file_buffer << "Arith: ";
printOperator(file_buffer,op);
file_buffer <<"\n";
file_buffer << AST_NODE_SPACE<< "LHS (";
exp->print_ast(file_buffer);
file_buffer << ")";
}
void UnaryExpression_Ast :: print_value(Local_Environment & eval_env, ostream & file_buffer){
file_buffer << replace(evaluate(eval_env , file_buffer).get_value());
}
Eval_Result & UnaryExpression_Ast :: evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result *temp;
if(node_data_type == float_data_type){
temp = new Eval_Result_Value_Float();
}
else if(node_data_type == double_data_type){
temp = new Eval_Result_Value_Double();
}
else if(node_data_type == int_data_type){
temp = new Eval_Result_Value_Int();
}
Eval_Result &result = *temp;
Eval_Result_Ret res;
res.data_type = node_data_type;
Eval_Result_Ret lVal =(exp->evaluate(eval_env,file_buffer)).get_value();
switch(op){
case Expression_Ast::UPLUS:
assign_replace(res , replace(lVal));
break;
case Expression_Ast::UMINUS:
assign_replace(res , -replace(lVal));
break;
default:
file_buffer<<"UnaryExpression : Wrong OP Entered \n";
exit(-1);
}
result.set_value(res);
return result;
}
////////////////////////////////////////////////////////////
Function_call_Ast::Function_call_Ast(list<Ast *> arguments_ , string proc_){
arguments = arguments_;
proc = proc_;
Procedure * referred_procedure = program_object.get_procedure(proc);
assert(referred_procedure!=NULL);
node_data_type = referred_procedure->get_return_type();
}
Function_call_Ast::~Function_call_Ast(){
}
Data_Type Function_call_Ast::get_data_type(){
return node_data_type;
}
void Function_call_Ast::print_ast(ostream & file_buffer){
file_buffer<<"\n"<<AST_SPACE<<"FN CALL: "<<proc<<"(";
list<Ast *>::iterator it;
for(it = arguments.begin();it != arguments.end(); it++){
file_buffer<<"\n";
file_buffer<<AST_NODE_SPACE;
(*it)->print_ast(file_buffer);
}
file_buffer<<")";
}
Eval_Result & Function_call_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result *temp;
if(node_data_type == float_data_type){
temp = new Eval_Result_Value_Float();
}
else if(node_data_type == double_data_type){
temp = new Eval_Result_Value_Double();
}
else if(node_data_type == int_data_type){
temp = new Eval_Result_Value_Int();
}
else{
assert(node_data_type == void_data_type);
temp = new Eval_Result_Value_Return;
temp->set_result_enum(void_result);
}
Eval_Result &result = *temp;
Procedure * referred_procedure = program_object.get_procedure(proc);
assert(referred_procedure!=NULL);
list<Eval_Result_Ret> evaluated_arguments;
list<Ast *>::iterator it;
for(it=arguments.begin();it!=arguments.end();it++){
Eval_Result_Ret t1 = (*it)->evaluate(eval_env , file_buffer).get_value();
evaluated_arguments.push_back(t1);
}
//cout<<"About to evaluate function_call : "<<endl;
Eval_Result &temp2 = referred_procedure->evaluate(file_buffer , evaluated_arguments);
if(temp2.get_value().data_type != void_data_type)
result.set_value(temp2.get_value());
/*
if(node_data_type == float_data_type || node_data_type == int_data_type){
file_buffer<<AST_NODE_SPACE <<"return : ";
if(node_data_type == float_data_type)
file_buffer<<result.get_value().float_ret;
else
file_buffer<<result.get_value().int_ret;
file_buffer<<" \n";
}
*/
//cout<<"Evaluating Function_call : Done "<<endl;
return result;
}
//////////////////////////////////////////////////////////////////////////////
Return_Ast::Return_Ast(){
node_data_type = void_data_type;
exp = NULL;
}
Return_Ast::Return_Ast(Ast *exp_){
assert(exp_!=NULL);
exp = exp_;
node_data_type = exp->get_data_type();
}
Return_Ast::~Return_Ast()
{}
Data_Type Return_Ast::get_data_type(){
return node_data_type;
}
void Return_Ast::print_ast(ostream & file_buffer){
file_buffer << AST_SPACE << "RETURN ";
if(node_data_type == void_data_type){
file_buffer<<"<NOTHING>\n";
return;
}
exp->print_ast(file_buffer);
file_buffer<<"\n";
}
Eval_Result & Return_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result & result = *new Eval_Result_Value_Return();
Eval_Result_Ret ret;
if(exp!=NULL)
ret =(exp->evaluate(eval_env,file_buffer)).get_value();
else
ret.data_type = void_data_type;
result.set_value(ret);
print_ast(file_buffer);
return result;
}
template class Number_Ast<int>;
template class Number_Ast<float>;
| true |
edadd59b2d690c815be4a441b136235451cbf1b3 | C++ | ninghang/accompany | /UHCore/CppInterface/base.cpp | UTF-8 | 1,505 | 2.78125 | 3 | [] | no_license | #include "history.h"
#include "Python.h"
#include <string>
#include <iostream>
#include <exception>
#include <stdio.h>
PythonInterface::PythonInterface(const char* modulePath) {
PythonInterface::modulePath = modulePath;
}
PythonInterface::~PythonInterface() {
if (pInstance != NULL) {
Py_DECREF(pInstance);
}
Py_Finalize();
}
PyObject* PythonInterface::getClassInstance() {
if (pInstance == NULL) {
Py_Initialize();
if (modulePath != NULL) {
PyRun_SimpleString("import sys");
PyRun_SimpleString(("sys.path.append(\"" + std::string(modulePath) + "\")").c_str());
}
std::string modName = getModuleName();
PyObject *pName = PyString_FromString(modName.c_str());
PyObject *pModule = PyImport_Import(pName);
Py_DECREF(pName);
char* fileName = PyModule_GetFilename(pModule);
char* argv[1] = { fileName };
PySys_SetArgvEx(1, argv, 0);
PyObject *pDict = PyModule_GetDict(pModule);
Py_DECREF(pModule);
PyObject *pClass = PyDict_GetItemString(pDict, getClassName().c_str());
Py_DECREF(pDict);
pInstance = PyObject_CallObject(pClass, NULL);
Py_DECREF(pClass);
}
return pInstance;
}
PyObject* PythonInterface::callMethod(const char* methodName, const char* arg1) {
char* m = strdup(methodName);
char* f = strdup("(s)");
PyObject *pValue = PyObject_CallMethod(getClassInstance(), m, f, arg1);
delete m;
delete f;
if (pValue != NULL) {
return pValue;
} else {
std::cout << "Error while calling method" << '\n';
PyErr_Print();
return NULL;
}
}
| true |
149f1d365a7e7505a7026e959a0d83e655bb0774 | C++ | jonjesbuzz/cards | /cpp/src/cards.cpp | UTF-8 | 2,415 | 3.5 | 4 | [
"MIT"
] | permissive | #include "cards.h"
#include <cstdlib>
#include <ctime>
#include <sstream>
Card::Card(Rank rank, Suit suit) :
rank(rank), suit(suit) {
}
Card::Card(const Card& c1):
rank(c1.rank), suit(c1.suit) {
}
Card::~Card() {
}
std::string Card::to_string() const {
std::string suit_s;
switch(suit) {
case Suit::SPADE:
suit_s = "Spade";
break;
case Suit::CLUB:
suit_s = "Club";
break;
case Suit::HEART:
suit_s = "Heart";
break;
case Suit::DIAMOND:
suit_s = "Diamond";
break;
default:
return std::string("Error");
}
std::string rank_s;
switch(rank) {
case Rank::ACE:
rank_s = "Ace";
break;
case Rank::JACK:
rank_s = "Jack";
break;
case Rank::QUEEN:
rank_s = "Queen";
break;
case Rank::KING:
rank_s = "King";
break;
default:
rank_s = std::to_string(static_cast<int>(rank));
break;
}
std::stringstream stream;
stream << rank_s << " of " << suit_s;
return stream.str();
}
Rank Card::get_rank() const {
return this->rank;
}
Suit Card::get_suit() const {
return this->suit;
}
std::ostream& operator<<(std::ostream &strm, const Card &c) {
return strm << c.to_string();
}
Deck::Deck() :
num_cards(52) {
cards.reserve(num_cards);
for (auto i = 0; i < num_cards; i++) {
cards.emplace_back(static_cast<Rank>(i%13 + 1), static_cast<Suit>(i/13));
}
}
Deck::~Deck() {
}
void Deck::shuffle(int random_count) {
std::srand(std::time(0));
auto a = 0;
auto b = 0;
for (auto i = 0; i < random_count; i++) {
a = i % num_cards;
do {
b = std::rand() % num_cards;
} while (a == b);
std::swap(cards[a], cards[b]);
}
}
Card Deck::get_card(int index) const {
return cards[index];
}
std::string Deck::to_string() const {
std::stringstream stream;
for (auto i = 0; i < num_cards; i++) {
auto s = cards[i].to_string();
stream << s;
if (i % 4 == 3) {
stream << std::endl;
} else {
stream << "\t";
}
}
return stream.str();
}
std::ostream& operator<<(std::ostream &strm, const Deck &d) {
return strm << d.to_string();
}
| true |
87c4fd695a5d1e5f7867cb046fd123c483d9bf5a | C++ | hoboaki/engineplan | /Scratch/LowLevelGraphics/VulkanSample/AeVulkanLib/ae/base/AutoSpPtr.hpp | UTF-8 | 10,311 | 2.8125 | 3 | [] | no_license | // 文字コード:UTF-8
#if defined(AE_BASE_INCLUDED_AUTOSPPTR_HPP)
#else
#define AE_BASE_INCLUDED_AUTOSPPTR_HPP
#include <ae/base/IAllocator.hpp>
#include <ae/base/Pointer.hpp>
//------------------------------------------------------------------------------
namespace ae::base {
/// @addtogroup AeBase-Memory
//@{
/// AutoPtrのAllocator指定版。
template <typename T>
class AutoSpPtr {
public:
/// @name コンストラクタとデストラクタ
//@{
/// デフォルトで作成。
AutoSpPtr() {}
/// 0引数 Init() で作成。
AutoSpPtr(::ae::base::IAllocator& allocator) { Init(allocator); }
/// 1引数 Init() で作成。
template <typename A0>
AutoSpPtr(::ae::base::IAllocator& allocator, A0 a0)
{
Init(allocator, a0);
}
/// 2引数 Init() で作成。
template <typename A0, typename A1>
AutoSpPtr(::ae::base::IAllocator& allocator, A0 a0, A1 a1)
{
Init(allocator, a0, a1);
}
/// 3引数 Init() で作成。
template <typename A0, typename A1, typename A2>
AutoSpPtr(::ae::base::IAllocator& allocator, A0 a0, A1 a1, A2 a2)
{
Init(allocator, a0, a1, a2);
}
/// 4引数 Init() で作成。
template <typename A0, typename A1, typename A2, typename A3>
AutoSpPtr(::ae::base::IAllocator& allocator, A0 a0, A1 a1, A2 a2, A3 a3)
{
Init(allocator, a0, a1, a2, a3);
}
/// 5引数 Init() で作成。
template <typename A0, typename A1, typename A2, typename A3, typename A4>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4)
{
Init(allocator, a0, a1, a2, a3, a4);
}
/// 6引数 Init() で作成。
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5)
{
Init(allocator, a0, a1, a2, a3, a4, a5);
}
/// 7引数 Init() で作成。
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6)
{
Init(allocator, a0, a1, a2, a3, a4, a5, a6);
}
/// 8引数 Init() で作成。
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7)
{
Init(allocator, a0, a1, a2, a3, a4, a5, a6, a7);
}
/// 9引数 Init() で作成。
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7,
typename A8>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7,
A8 a8)
{
Init(allocator, a0, a1, a2, a3, a4, a5, a6, a7, a8);
}
/// 10引数 Init() で作成。
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7,
typename A8,
typename A9>
AutoSpPtr(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7,
A8 a8,
A9 a9)
{
Init(allocator, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
}
/// 破棄責任を委譲して作成。
AutoSpPtr(const AutoSpPtr<T>& ptr) { *this = ptr; }
/// 破棄責任を委譲して作成。
template <typename OtherType>
AutoSpPtr(const AutoSpPtr<OtherType>& ptr)
{
*this = ptr;
}
/// デストラクタ
~AutoSpPtr() { Reset(); }
//@}
/// @name 取得
//@{
/// ポインタが設定されていなければtrueを返す。
bool IsNull() const { return ptr_.IsNull(); }
/// ポインタが設定されていればtrueを返す。
bool IsValid() const { return ptr_.IsValid(); }
/// ポインタの参照を取得する。
T& Ref() const
{
AE_BASE_ASSERT(IsValid());
return *ptr_;
}
/// @brief ポインタの値をそのまま取得する。
/// @details 設定されていないときは0を返します。
T* Get() const { return ptr_.Get(); }
//@}
/// @name 破棄
//@{
/// ポインタを設定していない状態にする。
void Reset()
{
if (IsNull()) {
return;
}
T* ptr = ptr_.Get();
ptr_.Reset();
ptr->~T();
operator delete(ptr, allocatorPtr_.Ref());
allocatorPtr_.Reset();
}
//@}
/// @name 生成
//@{
void Init(::ae::base::IAllocator& allocator)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T());
}
template <typename A0>
void Init(::ae::base::IAllocator& allocator, A0 a0)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0));
}
template <typename A0, typename A1>
void Init(::ae::base::IAllocator& allocator, A0 a0, A1 a1)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1));
}
template <typename A0, typename A1, typename A2>
void Init(::ae::base::IAllocator& allocator, A0 a0, A1 a1, A2 a2)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2));
}
template <typename A0, typename A1, typename A2, typename A3>
void Init(::ae::base::IAllocator& allocator, A0 a0, A1 a1, A2 a2, A3 a3)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3));
}
template <typename A0, typename A1, typename A2, typename A3, typename A4>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4));
}
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4, a5));
}
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4, a5, a6));
}
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4, a5, a6, a7));
}
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7,
typename A8>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7,
A8 a8)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4, a5, a6, a7, a8));
}
template <
typename A0,
typename A1,
typename A2,
typename A3,
typename A4,
typename A5,
typename A6,
typename A7,
typename A8,
typename A9>
void Init(
::ae::base::IAllocator& allocator,
A0 a0,
A1 a1,
A2 a2,
A3 a3,
A4 a4,
A5 a5,
A6 a6,
A7 a7,
A8 a8,
A9 a9)
{
PrepareCtor(allocator);
ptr_.Reset(new (allocator) T(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9));
}
//@}
/// @name 演算子オーバーロード
//@{
/// 特別な代入演算子。
AutoSpPtr<T>& operator=(const AutoSpPtr<T>& rHS)
{
Reset();
if (rHS.IsValid()) {
ptr_.Set(*rHS.ptr_);
allocatorPtr_ = rHS.allocatorPtr_;
rHS.ptr_.Reset();
rHS.allocatorPtr_.Reset();
}
return *this;
}
/// 特別な代入演算子。
template <typename OtherType>
AutoSpPtr<T>& operator=(const AutoSpPtr<OtherType>& rHS)
{
Reset();
if (rHS.IsValid()) {
ptr_.Set(*rHS.ptr_);
allocatorPtr_ = rHS.allocatorPtr_;
rHS.ptr_.Reset();
rHS.allocatorPtr_.Reset();
}
return *this;
}
/// 参照演算子。
T& operator*() const { return Ref(); }
/// 参照演算子
T* operator->() const
{
AE_BASE_ASSERT(IsValid());
return Get();
}
//@}
private:
mutable Pointer<T> ptr_;
mutable Pointer<IAllocator> allocatorPtr_;
//------------------------------------------------------------------------------
void PrepareCtor(::ae::base::IAllocator& allocator)
{
Reset();
allocatorPtr_.Set(allocator);
}
};
//@}
} // namespace ae::base
#endif
// EOF
| true |
e3b11bdcfafa840a949e2296022c0b5c65036693 | C++ | tres-xxx/Codeforces-Exercises | /A/1300-1399/1399A-RemoveSmallest.cpp | UTF-8 | 443 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
using namespace std;
int main(){
int t;
cin >> t;
string ans[t];
for(int i = 0; i < t; i++){
ans[i] = "-";
int n;
cin >> n;
int a[n];
for(int j = 0; j < n; j++){ cin >> a[j];}
sort(a,n+a);
for(int j = 0; j < n-1; j++){
if((a[j+1]-a[j]) > 1){ ans[i] = "NO";break;}
}
if(ans[i] != "NO"){ans[i] = "YES";}
}
for(int i = 0; i < t; i++){
cout << ans[i] << endl;
}
return 0;
}
| true |
5e4b60439e5d6068cfb38fa25a3b4422c59a3948 | C++ | vostokorient/vostok | /C++2/wifi.cpp | UTF-8 | 443 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int pasw, x, n, m=10;
cout<<"Введите пароль: "<<endl;
cin>>pasw;
cout<<"Введите разрядность: "<<endl;
cin>>n;
for(x=pow(m,n); x>0; x--)
{
cout<<x<<endl;
if(x==pasw)
{
cout<<endl<<"Success PASSWORD is: "<<x<<endl<<endl;
break;
}
}
return 0;
} | true |
e005aad06c3da6cf31290ed016507661eb2f494b | C++ | syanush/rhotetris | /tests/test1.cpp | UTF-8 | 2,871 | 3 | 3 | [
"MIT"
] | permissive | #include "gtest/gtest.h"
#include "Piece.hpp"
using namespace RhoTetris;
namespace {
// The test case name and the test name.
// You should not use underscore (_) in the names.
TEST(PieceTestCase, CheckPieces) {
auto& pieces = Piece::getPieces();
Body actual = pieces[0].getBody();
Body expected {{0, 0}, {0, 1}, {0, 2}, {0, 3}};
EXPECT_EQ(expected, actual);
}
TEST(PieceTestCase, CheckWidth) {
auto& pieces = Piece::getPieces();
auto& b0 = pieces[0].getBody();
auto width = pieces[0].getWidth();
EXPECT_EQ(1, width);
}
TEST(PieceTestCase, CheckHeight) {
auto& pieces = Piece::getPieces();
auto& b0 = pieces[0].getBody();
auto height = pieces[0].getHeight();
EXPECT_EQ(4, height);
}
TEST(PieceTestCase, CheckSkirt0) {
const auto& pieces = Piece::getPieces();
const auto& b0 = pieces[0].getBody();
const auto& actual = RhoTetris::getSkirt(b0);
const Skirt expected{0};
EXPECT_EQ(expected, actual);
}
TEST(PieceTestCase, CheckSkirt4) {
const auto& pieces = Piece::getPieces();
const auto& b4 = pieces[4].getBody();
const auto& actual = RhoTetris::getSkirt(b4);
const Skirt expected{1, 0, 0};
EXPECT_EQ(expected, actual);
}
TEST(PointTestCase, ComparePoints) {
EXPECT_TRUE(Point(1, 1) < Point(2, 1));
EXPECT_TRUE(Point(1, 1) < Point(1, 2));
EXPECT_TRUE(Point(1, 1) <= Point(1, 1));
}
TEST(PieceTestCase, CompareBodies) {
std::vector<Point> b1{Point(1, 1), Point(2, 1), Point(1, 2)};
std::vector<Point> b2{Point(2, 1), Point(1, 2), Point(1, 1)};
EXPECT_EQ(b1, b2);
}
TEST(PieceTestCase, RotateBodies) {
Body body{Point(0, 0)};
Body rotated = RhoTetris::rotate(body);
EXPECT_EQ(body, rotated);
}
void ShouldHaveRotationIndex1(size_t pieceIndex) {
auto& pieces = Piece::getPieces();
auto& piece = pieces[pieceIndex];
Piece rotated1 = *piece.nextRotation();
EXPECT_EQ(piece, rotated1);
}
void ShouldHaveRotationIndex2(size_t pieceIndex) {
auto& pieces = Piece::getPieces();
auto& piece = pieces[pieceIndex];
Piece rotated1 = *piece.nextRotation();
EXPECT_NE(piece, rotated1);
Piece rotated2 = *rotated1.nextRotation();
EXPECT_EQ(piece, rotated2);
}
void ShouldHaveRotationIndex4(size_t pieceIndex) {
auto& pieces = Piece::getPieces();
auto& piece = pieces[pieceIndex];
Piece rotated1 = *piece.nextRotation();
EXPECT_NE(piece, rotated1);
Piece rotated2 = *rotated1.nextRotation();
EXPECT_NE(piece, rotated2);
Piece rotated3 = *rotated2.nextRotation();
EXPECT_NE(piece, rotated3);
Piece rotated4 = *rotated3.nextRotation();
EXPECT_EQ(piece, rotated4);
}
TEST(PieceTestCase, TestRotations) {
auto& pieces = Piece::getPieces();
ShouldHaveRotationIndex2(0);
ShouldHaveRotationIndex4(1);
ShouldHaveRotationIndex4(2);
ShouldHaveRotationIndex2(3);
ShouldHaveRotationIndex2(4);
ShouldHaveRotationIndex1(5);
ShouldHaveRotationIndex4(6);
}
} // namespace
| true |
fbfd80af475356e9e3c4c0e0c5c8bf73c6dc92a2 | C++ | Dream-Dev-Team/Labor_OOS1 | /Labor_3/L3_A4/main.cpp | UTF-8 | 1,356 | 2.734375 | 3 | [] | no_license | //////////////////////////////////////////////////////
//Dateiname: L3_A4
//Autoren: Maxim Becht (mabeit10@hs-esslingen.de), Aaron Müller (aamuit00@hs-esslingen.de)
//Enthaltene Module: Point.h, Ciurcle.h, Polygonline.h, PolygonElement.h
//Entwicklungsbeginn: 11.06.2020 Entwicklungsende: 18.06.2020
//Zeitaufwand gesamt: to much
//Letzte Modifikationen: 18.06.2020
//////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "Circle.h"
#include "Polygonline.h"
using namespace std;
// Hauptprogramm
int main(void)
{
Point p1(0, 0);
const Point p2(2, 2);
const Point p3(3, 3);
Circle c(p1, 1.1);
cout << "Circle c: " << c << endl;
p1 = p1 + 0.5;
p1 = 0.5 + p1;
cout << "p1: " << p1 << endl;
cout << "p2: " << p2 << endl;
cout << "p3: " << p3 << endl;
Point p4 = p1 + p2 - p3 + 4.0;
cout << "p4: " << p4 << endl;
p1 = -p4;
cout << "p1: " << p1 << endl;
cout << "p4: " << p4 << endl;
Point p5 = p1++;
cout << "p5: " << p5 << endl;
cout << "p1: " << p1 << endl;
p5 = ++++++++p1;
cout << "p5: " << p5 << endl;
cout << "p1: " << p1 << endl;
cout << "p2: " << p2 << endl;
cout << "p3: " << p3 << endl;
cout << "p4: " << p4 << endl;
Polygonline l1;
cout << "l1: " << l1 << endl;
(l1 + p1) + p2;
cout << "l1: " << l1 << endl;
const Polygonline l2(p4);
l1 + l2;
cout << "l1: " << l1 << endl;
cout << "l2: " << l2 << endl;
return 0;
} | true |
1d9c5a8b9f5db42dfc2df16362439f38d359c425 | C++ | jayjayjetpain/CS3353-Algorithms | /Lab1/src/SortAlgos.h | UTF-8 | 6,048 | 4.03125 | 4 | [] | no_license | #pragma once
#ifndef SORTALGOS_H
#define SORTALGOS_H
#include <iostream>
#include <string>
#include <vector>
/* SortAlgos holds the implementation of the three main sorts of the lab - Bubble Sort, Insertion Sort, and Merge Sort - as well as their
* "inner" functions that need to be called to execute them. This class is not a sub-class of Sort or any other class; instead, its header
* file is included in Sort.cpp so that Sort's function pointer can use the memory locations of the (static) sort functions in this file's
* definition to dynamically assign/run the methods without directly interacting with that class (concrete implementation decoupled from
* the interface of Algorithms -> Sort as per the Strategy design pattern)
*/
template<typename T>
class SortAlgos {
public:
static void BubbleSort(std::vector<T>&);
static void MergeSort(std::vector<T>&);
static void InsertionSort(std::vector<T>&);
private:
static void swap(T*, T*);
static void mergeSort(std::vector<T>&, int, int);
static void merge(std::vector<T>&, int, int, int);
};
//templated bubble sort, static for better memory management and access via the function pointer in Sort class
template<typename T>
void SortAlgos<T>::BubbleSort(std::vector<T>& list)
{
bool swapped = true; //boolean to check if the list is iterated with/without swapping values
int n = list.size(); //local variable of the list's size
//until there is no swapping in an iteration
while(swapped == true)
{
swapped = false; //sets to false since no swap has happened at the beginning
//loops through the list, swapping values when needed
for (int i = 0; i < (n - 1); i++)
{
//only swap values if the current value is larger than the one that proceeds it
if (list.at(i) > list.at(i+1))
{
//calls member static function swap which takes the memory addressed of the two elements to swap, and swaps their places
swap(&list.at(i), &list.at(i+1));
swapped = true; //if we make it here then something has been swapped
}
}
//after every iteration through the list, the last element in the list will be the largest value, so we can lower our loop
//constraints each time to go for faster sorting
n = n - 1;
}
}
//templated public version of the merge sort algorithm used as the static method called by the function pointer
template<typename T>
void SortAlgos<T>::MergeSort(std::vector<T>& list)
{
//calls the private version of merge sort which takes a front and end index of the vector as well as the vector itself
mergeSort(list,0,list.size()-1);
}
//the "true" recursive function of merge sort called by the public function and itself to mimic the division provcess of Merge Sort
template<typename T>
void SortAlgos<T>::mergeSort(std::vector<T>& list, int left, int right)
{
//if the left index is less than the right index, i.e. the sub-vector size > 1, then we can still divide further
if(left < right)
{
int mid = (left + right)/2; //finds the middle of the current sub-vector
//divies the left side from the left to the middle value and the right side from one past the middle to the right
mergeSort(list, left, mid);
mergeSort(list, mid + 1, right);
//after dividing into both sub-vector, call this merge function to merge and sort the values back together
merge(list, left, mid, right);
}
}
//templated Insertion Sort implementation, static for better memory management and to be called by Sort's function pointer
template<typename T>
void SortAlgos<T>::InsertionSort(std::vector<T>& list)
{
int i,j;
T comp;
//loops from the 2nd element to the end
for(i = 1; i < list.size(); i++)
{
comp = list.at(i); //sets the key value to be compared against
j = i - 1; //sets index j for the copying of values in the while loop
//until j is either below 0 or the value at j is a smaller value than the key value...
while(j >= 0 && list.at(j) > comp)
{
list.at(j+1) = list.at(j); //move the values larger than the key to the left of it
j--;
}
list.at(j + 1) = comp; //and put the key in its proper, sorted place
}
}
//sub-function for Bubble Sort, static since the main method is; swaps two values using their memory addresses
template<typename T>
void SortAlgos<T>::swap(T* one, T* two)
{
T temp = *one;
*one = *two;
*two = temp;
}
//merging function called in each recursion of merge sort to re-unite the sub-vectors and sort them along the way; based loosely on model developed in class
template<typename T>
void SortAlgos<T>::merge(std::vector<T>& list, int left, int mid, int right)
{
std::vector<T> t1; //temp vector for comparisons
//makes local varibles for left and right (not parameters; in parameter, left = start, right = end)
int i = left;
int j = mid + 1;
//until left and right go past their left and right sub-vectors
while(i <= mid && j <= right)
{
//compare the values at left/right to know which to push to the temp vector
if(list.at(i) <= list.at(j))
{
t1.push_back(list.at(i)); //if i (left) is less, then push it to the temp vector and increment it
i++;
}
else
{
t1.push_back(list.at(j)); //if j (right) is less, then push it to the temp vector and increment it
j++;
}
}
//copy the remaining values to the temp array
while(i <= mid)
{
t1.push_back(list.at(i)); //if the loop was terminated by j going past left (end) then copy the rest of the first sub-vector
i++;
}
while(j <= right)
{
t1.push_back(list.at(j)); //if the loop was terminated by i going past mid (middle) then copy the rest of the first sub-vector
j++;
}
//then recopy the values that are now in the proper order in the temp vector back to the actual vector to finish sorting the sub-vectors
for (i = left; i <= right; i += 1)
{
list.at(i) = t1.at(i - left);
}
}
#endif // SortAlgos_H | true |
40f2418d06be77de0ced1ef5358e79f50708ed0d | C++ | Sireis/SelfDrivingCar | /SelfDrivingCar/SelfDrivingCar/Source/Circle.cpp | UTF-8 | 2,610 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "Circle.h"
#include "Rectangle.h"
namespace Drawing
{
void Circle::init ()
{
original_vertices[0] = m[0]; original_vertices[1] = m[1];
original_vertices[2] = 0.0;
for (int i = 1; i < number_of_points; ++i)
{
original_vertices[9 * i + 0] = m[0] + radius * sin (2 * 3.1415926535*(i - 1) / (number_of_points - 2));
original_vertices[9 * i + 1] = m[1] + radius * cos (2 * 3.1415926535*(i - 1) / (number_of_points - 2));
original_vertices[9 * i + 2] = 0.0;
}
}
Circle::Circle ()
:
Drawable(10,Vec2(0,0),Vec2(0,1))
{
}
Circle::Circle (const Vec2 m, const float radius, const float * rgba, Drawable * parent)
:
Drawable(((int)(2*3.1415926535*radius/0.005)),m,Vec2(0,1)),
radius(radius)
{
this->parent = parent;
init ();
for (int i = 0; i < number_of_points; ++i)
{
original_vertices[9 * i + 3] = rgba[0];
original_vertices[9 * i + 4] = rgba[1];
original_vertices[9 * i + 5] = rgba[2];
original_vertices[9 * i + 6] = rgba[3];
}
}
Circle::~Circle ()
{
}
void Circle::set_color (float angle, const float * rgba)
{
int index = angle / (2* 3.1415926535) * (number_of_points - 1) + 1;
int count = (number_of_points - 1) / 12;
int n = 0;
for (int i = 0; i < count; ++i)
{
n = (index - (count / 2) + i) % (number_of_points - 1) ;
if (n <= 0)
{
n = (number_of_points - n - 1);
}
vertices[9 * n + 3] = model_vertices[9 * n + 3] = original_vertices[9 * n + 3] = rgba[0];
vertices[9 * n + 4] = model_vertices[9 * n + 4] = original_vertices[9 * n + 4] = rgba[1];
vertices[9 * n + 5] = model_vertices[9 * n + 5] = original_vertices[9 * n + 5] = rgba[2];
vertices[9 * n + 6] = model_vertices[9 * n + 6] = original_vertices[9 * n + 6] = rgba[3];
}
}
void Circle::draw ()
{
glBindBuffer (GL_ARRAY_BUFFER, VBO);
glBufferSubData (GL_ARRAY_BUFFER, 0, number_of_points * Environment::shader.vertex_buffer_line_length * sizeof (float), vertices);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, Environment::shader.vertex_buffer_line_length * sizeof (float), (void*)0);
glEnableVertexAttribArray (0);
glVertexAttribPointer (1, 4, GL_FLOAT, GL_FALSE, Environment::shader.vertex_buffer_line_length * sizeof (float), (void*)(3 * sizeof (float)));
glEnableVertexAttribArray (1);
glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, Environment::shader.vertex_buffer_line_length * sizeof (float), (void*)(7 * sizeof (float)));
glEnableVertexAttribArray (2);
//if (texture != nullptr)
//{
// texture->use ();
//}
glDrawArrays (GL_TRIANGLE_FAN, 0, number_of_points);
}
} | true |
f756ad00ee31d8bbc05a55c04abb87fce0ecb0f3 | C++ | johnw188/me405 | /tests/radio_test.cc | UTF-8 | 4,628 | 2.953125 | 3 | [] | no_license | //======================================================================================
/** \file radio_test.cc
* This file contains a program to test the packet and/or text mode drivers for
* the nRF24L01 radio modems on the ME405 boards.
*
* Revisions
* \li 02-03-08 JRR Original file, for testing text based drivers
* \li 03-30-08 JRR Modified to test packet based drivers
*/
//======================================================================================
// System headers included with < >
#include <stdlib.h> // Standard C library
#include <avr/io.h> // Input-output ports, special registers
#include <avr/interrupt.h> // Interrupt handling functions
// User written headers included with " "
#include "rs232.h" // Serial port header
#include "nRF24L01_text.h" // Nordic nRF24L01 radio module header
#include "stl_us_timer.h" // Task timer and time stamp header
//#include "me405comm.h" // Package construction
/** This is the baud rate divisor for the serial port. It should give 9600 baud for the
* CPU crystal speed in use, for example 26 works for a 4MHz crystal */
#define BAUD_DIV 52 // For Mega128 with 8MHz crystal
//--------------------------------------------------------------------------------------
/** The main function is the "entry point" of every C program, the one which runs first
* (after standard setup code has finished). For mechatronics programs, main() runs an
* infinite loop and never exits.
*/
int main ()
{
char input_char; // A character typed by the user
static unsigned long dummy = 0L; // For sending pings only occasionally
unsigned char ping_count = 0; // Something sent along with a ping
// Create a timer for the heck of it
task_timer a_timer;
// Create a serial port object. The time will be printed to this port, which
// should be hooked up to a dumb terminal program like minicom on a PC
rs232 the_serial (BAUD_DIV, 1);
// Print a greeting message. This is almost always a good thing because it lets
// the user know that the program is actually running
the_serial << endl << endl << "ME405: Radio Text Interface Test" << endl;
// Create a bit-banged SPI port interface object. Masks are SCK, MISO, MOSI
spi_bb_port my_SPI (PINB, PORTB, DDRB, 0x02, 0x04, 0x08);
// Set up a radio module object. Parameters are port, DDR, and bitmask for each
// line SS, CE, and IRQ; last parameter is debugging serial port's address
nRF24L01_text my_radio (PORTE, DDRE, 0x40, PORTE, DDRE, 0x80, &my_SPI, 0x01,
&the_serial);
// Give a long, overly complex message to make sure multi-packet strings work
my_radio <<
"Hello, this is the radio module text mode test program. It mostly works."
<< endl;
// Enable interrupt processing; the receiver needs this
sei ();
// Run the main scheduling loop, in which the action to run is done repeatedly.
// In the future, we'll run tasks here; for now, just do things in a simple loop
while (true)
{
// Check if the user has typed something. If so, either clear the counter to
// a reading of zero time or write a carriage return and linefeed
if (the_serial.check_for_char ())
{
input_char = the_serial.getchar ();
if (input_char == 'c') // 'c' means carriage return
{
the_serial << endl;
ping_count = 0;
}
else if (input_char == 'd') // 'd' means dump registers
my_radio.dump_regs (&the_serial);
else if (input_char == 't')
the_serial << "Local time: " << a_timer.get_time_now () << endl;
else if (input_char == 'r')
my_radio.reset ();
else if (input_char == 's')
my_radio.reset ();
}
// Periodically transmit some nonsense
if (++dummy > 100000)
{
dummy = 0L;
my_radio << "hey was ist das fuer ein kram " << a_timer.get_time_now () << endl;
}
// If there's a character available in the buffer, print it
if (my_radio.check_for_char ())
the_serial.putchar (my_radio.getchar ());
}
return (0);
}
| true |
9c99ead6f24f51d4d49f16d2bd07076eb7bd7234 | C++ | ErickCR12/Scrabble | /ClientProject/gui/DraggableTile.h | UTF-8 | 1,646 | 2.921875 | 3 | [] | no_license | #ifndef DRAGGABLETILE_H
#define DRAGGABLETILE_H
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
#include <iostream>
#include <QTextStream>
#include <string>
#include "clientlogic/Board.hpp"
//! \brief The DraggableTile class is a QGraphicsRectItem that can be dragged around a QGraphicsView. Is used as the scrabble tiles.
class DraggableTile : public QGraphicsRectItem
{
public:
//! \brief DraggableTile constructor. Set flags of selectable and draggable to true.
//! \param paren: widget parent of draggableTile.
DraggableTile(QGraphicsItem* parent = 0);
//! \brief setAnchorPoint function sets the position of the draggableTile to the QPointF received as parameter.
//! \param anchorPoint: QPointF
void setAnchorPoint(const QPointF& anchorPoint);
void printGameBoard(Board* board);
//! \brief setUndraggable function sets flags of selectable and draggable to false.
void setUndraggable();
//! \brief getter for letter attribute
//! \return string: letter attribute
std::string getLetter();
//! \brief settter for letter attribute
//! \param string: new letter value
void setLetter(string letter);
protected:
//! \brief event that makes the tile draggable
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
//! \brief this event registers when the draggable tile is released. Checks if theres an QRectF item close
//! and set as a new anchor point the position of this QRectF
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
private:
QPointF anchorPoint;
bool m_dragged;
std::string letter;
};
#endif // DRAGGABLETILE_H
| true |
869da352d93b4247508b36f76bb6b5b2cd6eba59 | C++ | votslot/pvc | /lib/cbuff.cpp | UTF-8 | 5,346 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <assert.h>
#include "GL/glew.h"
#include "cbuff.h"
int BaseBuffer::m_globCount = 0;
void BaseBuffer::checkError()
{
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR)
{
printf("Buffer operation error %d %x \n", err,err);
}
}
BaseBuffer::BaseBuffer()
{
m_ndx = m_globCount;
m_globCount++;
}
void SSBBuffer::bind(int bi) const
{
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, bi, gb);
}
void SSBBuffer::init()
{
glGenBuffers(1, &gb);
checkError();
}
unsigned int SSBBuffer::getMaxSizeInBytes()
{
GLint size;
glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &size);
return size;
}
void SSBBuffer::setData(void *pD, unsigned int sizeInBytes)
{
GLint maxtb = 0;
glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &maxtb);
if (sizeInBytes > (unsigned int)maxtb)
{
printf("Error buff size \n");
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, gb);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeInBytes, pD, GL_STATIC_READ);
sz = sizeInBytes;
checkError();
}
void SSBBuffer::allocate(unsigned int sizeInBytes)
{
GLint maxtb = 0;
glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &maxtb);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, gb);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeInBytes, NULL, GL_DYNAMIC_COPY);
sz = sizeInBytes;
checkError();
}
void* SSBBuffer::allocateVram(unsigned int sizeInBytes)
{
glBindBuffer(GL_SHADER_STORAGE_BUFFER, gb);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeInBytes, NULL, GL_DYNAMIC_COPY); checkError();
GLvoid* p = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
checkError();
return p;
}
void SSBBuffer::getData(unsigned int sizeInBytes, void *pOut)
{
glBindBuffer(GL_SHADER_STORAGE_BUFFER, gb);
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeInBytes, pOut);
checkError();
}
// TexR32f
void TexR32f::init(int width,int height)
{
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, width, height, 0, GL_RED, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
void TexR32f::bind(int bi) const
{
glBindImageTexture(bi, tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32F);
}
// TexU32
void TexU32::init(int width, int height)
{
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, width, height, 0, GL_RED, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
checkError();
}
void TexU32::bind(int bi) const
{
glBindImageTexture(bi, tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);
checkError();
}
//another option is to attach the buffer to a buffer texture with glTextureBuffer(),
//bind the texture to an image unit with glBindImageTexture(),
//and access the data in the compute shader using imageLoad().
unsigned int tboType = GL_RGBA32F;
void TBOBuffer::init()
{
glGenTextures(1, &tex);
glGenBuffers(1, &gb);
checkError();
}
void TBOBuffer::bind(int bi) const
{
glBindImageTexture(bi, tex, 0, GL_FALSE, 0, GL_READ_WRITE, tboType);
checkError();
}
void TBOBuffer::setData(void *pD, unsigned int sizeInBytes)
{
GLint maxtb = 0;
glGetIntegerv(GL_MAX_TEXTURE_BUFFER_SIZE, &maxtb);
if (sizeInBytes > (unsigned int)maxtb)
{
checkError();
}
//const unsigned int target = GL_TEXTURE_BUFFER_EXT;
const unsigned int target = GL_TEXTURE_BUFFER;
glBindBuffer(target,gb); checkError();
glBufferData(target, sizeInBytes, NULL, GL_DYNAMIC_COPY); checkError();
unsigned char *pMem = (unsigned char*)glMapBufferRange(target,0,sizeInBytes,GL_MAP_WRITE_BIT); checkError();
memcpy(pMem, pD, sizeInBytes); checkError();
glUnmapBuffer(target); checkError();
glBindTexture(target, tex); checkError();
glTexBuffer(target, tboType, gb); checkError();
}
// --- CSShader ---------------
CSShader::CSShader()
{
for (int i = 0; i < m_maxBuffs; i++) m_bindTable[i] = -1;
m_szx = m_szy = m_szz = 1;
}
void CSShader::initFromSource(const char *pSrc)
{
extern GLuint LoadShader(GLenum type, const GLchar *shaderSrc);
GLuint csShader = LoadShader(GL_COMPUTE_SHADER, pSrc);
m_program = glCreateProgram(); BaseBuffer::checkError();
glAttachShader(m_program,csShader); BaseBuffer::checkError();
glLinkProgram(m_program); BaseBuffer::checkError();
int localWorkGroupSize[3];
glGetProgramiv(m_program, GL_COMPUTE_WORK_GROUP_SIZE, localWorkGroupSize);
m_szx = localWorkGroupSize[0];
m_szy = localWorkGroupSize[1];
m_szz = localWorkGroupSize[2];
assert(m_szx > 0);
BaseBuffer::checkError();
}
void CSShader::setBufferBinding(const BaseBuffer *pBuff, int bIndex)
{
int n = pBuff->m_ndx;
m_bindTable[n] = bIndex;
}
void CSShader::bindBuffer(const BaseBuffer *pBuff)
{
int n = m_bindTable[pBuff->m_ndx];
pBuff->bind(n);
}
void CSShader::execute(int x, int y, int z, std::initializer_list <SSBBuffer*> inputs)
{
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glUseProgram(m_program);
int i = 0;
for (SSBBuffer* bf : inputs) {
bf->bind(i);
i++;
}
glDispatchCompute(x, y, z);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glUseProgram(0);
}
| true |
eb4a70c51d39ace944773e5b979806b4405b0161 | C++ | mrtakata/competitive-programming | /codeforces/59 - Codeforces Beta Round #55 (Div. 2)/a.cpp | UTF-8 | 916 | 2.78125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long int
using namespace std;
char toLowercase(char c){
return char(c - 'A' + 'a');
}
char toUppercase(char c){
return char(c + 'A' - 'a');
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
char input[100];
cin >> input;
// count occurrences
int n_lower = 0, n_upper, total;
int i = 0;
while(input[i] != '\0'){
if(input[i] > 96){
n_lower++;
}
i++;
}
total = i;
n_upper = total - n_lower;
// res
if(n_lower >= n_upper){
i = 0;
while(input[i] != '\0'){
if(input[i] > 96){
cout << input[i];
}
else{
cout << toLowercase(input[i]);
}
i++;
}
}
else{
i = 0;
while(input[i] != '\0'){
if(input[i] < 96){
cout << input[i];
}
else{
cout << toUppercase(input[i]);
}
i++;
}
}
cout << endl;
return 0;
}
| true |
4f9c485ed8a6c56798783eac3d46f0a9d6f4cce6 | C++ | guigzzz/HPC | /Coursework 5/include/puzzler/puzzles/edit_distance.hpp | UTF-8 | 4,290 | 2.65625 | 3 | [] | no_license | #ifndef puzzler_puzzles_edit_distance_hpp
#define puzzler_puzzles_edit_distance_hpp
#include <random>
#include <sstream>
#include <vector>
#include <climits>
#include <cassert>
#include <algorithm>
#include "puzzler/core/puzzle.hpp"
namespace puzzler
{
class EditDistancePuzzle;
class EditDistanceInput;
class EditDistanceOutput;
class EditDistanceInput
: public Puzzle::Input
{
public:
std::vector<uint8_t> s;
std::vector<uint8_t> t;
EditDistanceInput(const Puzzle *puzzle, int scale)
: Puzzle::Input(puzzle, scale)
{}
EditDistanceInput(std::string format, std::string name, PersistContext &ctxt)
: Puzzle::Input(format, name, ctxt)
{
PersistImpl(ctxt);
}
virtual void PersistImpl(PersistContext &conn) override final
{
conn.SendOrRecv(s);
conn.SendOrRecv(t);
}
};
class EditDistanceOutput
: public Puzzle::Output
{
public:
unsigned distance;
EditDistanceOutput(const Puzzle *puzzle, const Puzzle::Input *input)
: Puzzle::Output(puzzle, input)
{}
EditDistanceOutput(std::string format, std::string name, PersistContext &ctxt)
: Puzzle::Output(format, name, ctxt)
{
PersistImpl(ctxt);
}
virtual void PersistImpl(PersistContext &conn) override
{
conn.SendOrRecv(distance);
}
};
class EditDistancePuzzle
: public PuzzleBase<EditDistanceInput,EditDistanceOutput>
{
protected:
void ReferenceExecute(
ILog *log,
const EditDistanceInput *pInput,
EditDistanceOutput *pOutput
) const
{
int m=pInput->s.size();
int n=pInput->t.size();
std::vector<uint8_t> s=pInput->s; // Length m
std::vector<uint8_t> t=pInput->t; // Length n
std::vector<unsigned> dStg( size_t(m+1)*(n+1) );
// Helper to provide 2d accesses
auto d=[&](int i,int j) -> unsigned &
{
assert(i<=m && j<=n);
return dStg.at( i*size_t(n+1)+j );
};
for(int i=0; i<=m; i++){
d(i,0) = i;
}
for(int j=0; j<=n; j++){
d(0,j) = j;
}
for(int j=1; j<=n; j++){
log->LogVerbose("Row %u", j);
for(int i=1; i<=m; i++){
if( s[i-1] == t[j-1] ){
d(i,j) = d(i-1,j-1);
}else{
d(i,j) = 1 + std::min(std::min( d(i-1,j), d(i,j-1) ), d(i-1,j-1) );
}
}
}
auto distance=d(m,n);
log->LogInfo("Distance = %u", distance);
pOutput->distance=distance;
}
virtual void Execute(
ILog *log,
const EditDistanceInput *input,
EditDistanceOutput *output
) const =0;
public:
virtual std::string Name() const override
{ return "edit_distance"; }
virtual bool HasBitExactOutput() const override
{ return true; }
virtual bool CompareOutputs(ILog */*log*/, const EditDistanceInput * /*input*/, const EditDistanceOutput *ref, const EditDistanceOutput *got) const override
{
return ref->distance==got->distance;
}
virtual std::shared_ptr<Input> CreateInput(
ILog * /*log*/,
int scale
) const override
{
std::mt19937 rnd(time(0)); // Not the best way of seeding...
std::uniform_real_distribution<> udist;
auto params=std::make_shared<EditDistanceInput>(this, scale);
params->s.resize(scale);
for(int i=0; i<scale; i++){
params->s[i]=rnd()%256;
}
params->t=params->s;
for(int i=0; i<(int)sqrt(scale); i++){
int len=rnd()%10;
int start=rnd() % (params->t.size()-1);
len = std::min( len, int(params->t.size()-start) );
assert(start+len <= (int)params->t.size() );
switch(rnd()%3){
case 0:
params->t.insert(params->t.begin()+start, len, 0);
std::generate_n(params->t.begin()+start, len, [&](){ return rnd()%256; });
break;
case 1:
params->t.erase(params->t.begin()+start, params->t.begin()+start+len);
break;
case 2:
std::generate_n(params->t.begin()+start, len, [&](){ return rnd()%256; });
break;
default:
assert(0);
}
}
return params;
}
};
};
#endif
| true |
4e8b158720c24d68bc6631bec8fcd0793f9410f7 | C++ | phisn/PixelJumper2 | /source/EditorCore/classiccontext/ClassicContextManager.h | UTF-8 | 8,557 | 2.5625 | 3 | [] | no_license | #pragma once
#include "ClassicContextWorldNode.h"
#include "TransitiveContextNode.h"
#include "EditorCore/WindowManager.h"
#include "EditorCore/EditorFailureScene.h"
namespace Editor::ClassicContext
{
class ClassicContextManager
{
public:
ClassicContextManager(Resource::ContextID contextID)
:
contextID(contextID)
{
// error handling is already done inside
initializeContextContent() &&
initializeWorldNodes() &&
initializeTransitiveConnectionNodes();
}
~ClassicContextManager()
{
for (Node* node : nodes)
delete node;
}
void draw(sf::RenderTarget* target)
{
for (Node* node : nodes)
node->draw(target);
}
bool createWorldNode(Resource::WorldID worldID)
{
typedef std::tuple<SQLiteString> CreateWorldTuple;
CreateWorldTuple createWorld;
if (!Database::Statement<CreateWorldTuple>(
EditorDatabase::Instance(),
"SELECT name FROM world WHERE id = ?",
worldID).execute(createWorld))
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to retrive information to create world in contextwindow '" + std::to_string(worldID) + "'"));
return false;
}
WorldNode* node = new WorldNode(worldID, std::get<0>(createWorld));
nodes.push_back(node);
worlds.push_back(node);
return true;
}
bool createTransitiveNode(Resource::WorldEntryID entryID)
{
typedef std::tuple<SQLiteInt, SQLiteInt, SQLiteString> CreateTransitiveTuple;
CreateTransitiveTuple createTransitive;
if (!Database::Statement<CreateTransitiveTuple>(
EditorDatabase::Instance(),
"SELECT outputid, inputid, name FROM transitive WHERE id = ?",
entryID).execute(createTransitive))
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to retrive information to create transitive in contextwindow '" + std::to_string(entryID) + "'"));
return false;
}
WorldNode* outputNode = findWorldNodeByID(std::get<0>(createTransitive));
WorldNode* inputNode = findWorldNodeByID(std::get<1>(createTransitive));
if (outputNode == NULL || inputNode == NULL)
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to find nodes to create transitive in contextwindow '" + std::to_string(entryID) + "'"));
return false;
}
TransitiveNode* node = new TransitiveNode(
outputNode,
inputNode,
entryID,
std::get<2>(createTransitive));
outputNode->addTransitiveConnection(inputNode, node);
inputNode->addTransitiveConnection(outputNode, node);
outputNode->notifyBoundsChanged();
inputNode->notifyBoundsChanged();
nodes.push_back(node);
transitives.push_back(node);
return true;
}
bool removeWorldNode(Resource::WorldID worldID)
{
decltype(worlds)::iterator iterator = std::find_if(
worlds.begin(),
worlds.end(),
[worldID](WorldNode* node)
{
return node->getID() == worldID;
});
if (iterator == worlds.end())
return false;
nodes.erase(std::find(
nodes.begin(),
nodes.end(),
*iterator));
worlds.erase(iterator);
return true;
}
bool removeTransitiveNode(Resource::WorldEntryID entryID)
{
decltype(transitives)::iterator iterator = std::find_if(
transitives.begin(),
transitives.end(),
[entryID](TransitiveNode* node)
{
return node->getID() == entryID;
});
TransitiveNode* node = *iterator;
if (node == NULL)
return false;
node->getSource()->removeTransitiveConnection(node);
node->getTarget()->removeTransitiveConnection(node);
nodes.erase(std::find(
nodes.begin(),
nodes.end(),
(Node*)*iterator));
transitives.erase(iterator);
return true;
}
Node* findNodeByPoint(sf::Vector2f coord) const
{
for (Node* node : nodes)
if (node->contains(coord))
{
return node;
}
return NULL;
}
WorldNode* findWorldNodeByPoint(sf::Vector2f coord) const
{
for (WorldNode* node : worlds)
if (node->contains(coord))
{
return node;
}
return NULL;
}
WorldNode* findWorldNodeByID(Resource::WorldID id) const
{
for (WorldNode* node : worlds)
if (node->getID() == id)
{
return node;
}
return NULL;
}
TransitiveNode* findTransitiveNodeByID(Resource::WorldEntryID id) const
{
for (TransitiveNode* node : transitives)
if (node->getID() == id)
{
return node;
}
return NULL;
}
void PullNodeToFront(Node* node)
{
nodes.splice(
nodes.end(),
nodes,
std::find(
nodes.begin(),
nodes.end(),
node));
}
void findCollidingNodes(sf::FloatRect rect, std::vector<Node*>& collidingNodes)
{
for (Node* node : nodes)
if (doesRectContainRect(rect, node->getGlobalBounds()))
{
collidingNodes.push_back(node);
}
}
Resource::ContextID getContextID() const
{
return contextID;
}
private:
Resource::ContextID contextID;
std::string name, description;
std::list<Node*> nodes;
std::vector<TransitiveNode*> transitives;
std::vector<WorldNode*> worlds;
bool initializeContextContent()
{
typedef std::tuple<Database::SQLiteString, Database::SQLiteString> ContextNameTuple;
ContextNameTuple thisTuple;
if (!Database::Statement<ContextNameTuple>(
EditorDatabase::Instance(),
"SELECT name, description FROM context WHERE id = ?", contextID).execute(thisTuple))
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to load context information '" + std::to_string(contextID) + "'"));
return false;
}
name = std::move(std::get<0>(thisTuple));
description = std::move(std::get<1>(thisTuple));
return true;
}
bool initializeWorldNodes()
{
typedef std::tuple<SQLiteInt, SQLiteString> NodeWorldTuple;
Database::Statement<NodeWorldTuple> findWorlds(
EditorDatabase::Instance(),
"SELECT id, name FROM world WHERE contextid = ?", contextID);
for (const NodeWorldTuple& tuple : findWorlds)
{
WorldNode* node = new WorldNode(
std::get<0>(tuple),
std::get<1>(tuple));
nodes.push_back(node);
worlds.push_back(node);
}
if (!findWorlds)
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to load worlds for context '" + std::to_string(contextID) + "'",
[this]() -> bool
{
return removeContextFromDatabase();
}));
return false;
}
return true;
}
bool initializeTransitiveConnectionNodes()
{
typedef std::tuple<SQLiteInt, SQLiteString, SQLiteInt, SQLiteInt> NodeTransitiveTuple;
Database::Statement<NodeTransitiveTuple> findTransitives(
EditorDatabase::Instance(),
"SELECT id, name, outputid, inputid FROM transitive WHERE contextid = ?", contextID);
for (const NodeTransitiveTuple& tuple : findTransitives)
{
Resource::WorldEntryID entryID = std::get<0>(tuple);
WorldNode* outputNode = findWorldNodeByID(std::get<2>(tuple));
WorldNode* inputNode = findWorldNodeByID(std::get<3>(tuple));
if (outputNode == NULL || inputNode == NULL)
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Got invalid worldID in transitive '" + std::to_string(entryID) + "'",
[entryID]() -> bool
{
return Database::Statement<>(
EditorDatabase::Instance(),
"DELETE FROM transitive WHERE id = ?", entryID).execute();
}));
return false;
}
TransitiveNode* node = new TransitiveNode(
outputNode,
inputNode,
std::get<0>(tuple),
std::get<1>(tuple));
outputNode->addTransitiveConnection(inputNode, node);
inputNode->addTransitiveConnection(outputNode, node);
outputNode->notifyBoundsChanged();
inputNode->notifyBoundsChanged();
nodes.push_back(node);
transitives.push_back(node);
}
if (!findTransitives)
{
Framework::Core::PushChildScene(new EditorFailureScene(
"Failed to load transitives for context '" + std::to_string(contextID) + "'",
[this]() -> bool
{
return removeContextFromDatabase();
}));
return false;
}
return true;
}
bool removeContextFromDatabase()
{
return Database::Statement<>(
EditorDatabase::Instance(),
"DELETE FROM context WHERE id = ?", contextID).execute();
}
bool doesRectContainRect(sf::FloatRect rect1, sf::FloatRect rect2) const
{
return (rect1.left < rect2.left + rect2.width)
&& (rect1.top < rect2.top + rect2.height)
&& (rect2.left < rect1.left + rect1.width)
&& (rect2.top < rect1.top + rect1.height);
}
};
}
| true |
cc9d8dfaa977d31ece447ca1358f65cedb563309 | C++ | Klarmanj/AverageBowlingCalulator | /BowlingCalculator.cpp | UTF-8 | 2,425 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function is called to display the *'s and welcome message to welcome the user to the program.
void welcomeMessage() {
const int STARS_LENGTH = 60;
const int SIDE_STAR_LENGTH = 7;
cout << setw(STARS_LENGTH) << setfill('*') << "" << endl;
cout << setw(SIDE_STAR_LENGTH) << "" << " Welcome to my Average Bowling Scores Counter "
<< setw(SIDE_STAR_LENGTH) << "" << endl;
cout << setw(STARS_LENGTH) << "" << endl;
cout << endl;
}
// This function is called when the scores are inputted into s1-4 and the average is then calculated and stored in an array
int GetAverageScore(int s1, int s2, int s3, int s4){
int totalScore = s1 + s2 + s3 + s4;
int average = totalScore / 4;
return average;
}
// This function prints the final outcome that is sent to the console.
void PrettyPrintResults(string bowlerName[10], int bowlingScores[10][4], int average[10]){
for (int i = 0; i < 10; i++){
cout << bowlerName[i] + " scores are: " << endl;
for (int j = 0; j < 4; j++){
cout << bowlingScores[i][j] << endl;
}
cout << bowlerName[i] + "'s average score is: " << average[i] << endl;
}
}
// This function does all the calculations in terms of grabbing the names and the scores from the test file, and sending
// all the information to the print results function
bool GetBowlingData(string bowlerName[10], int bowlingScores[10][4], int average[10]){
int s1, s2, s3, s4;
int i = 0;
string names;
ifstream inputFile;
inputFile.open("BowlingScores.txt");
if (!inputFile)
return false;
while (getline(inputFile, names, ' ')) {
inputFile >> s1 >> s2 >> s3 >> s4;
bowlerName[i] = names;
bowlingScores[i][0] = s1;
bowlingScores[i][1] = s2;
bowlingScores[i][2] = s3;
bowlingScores[i][3] = s4;
average[i] = GetAverageScore(s1, s2, s3, s4);
i++;
}
return true;
}
// The main function calls all other functions to perform all the calculations and printing of the results.
int main(){
int average[10];
string bowlerName[10];
int bowlingScores[10][4];
string names;
welcomeMessage();
if (GetBowlingData(bowlerName, bowlingScores, average)) {
PrettyPrintResults(bowlerName, bowlingScores, average);
}
else
return -1;
}
| true |
894cac0109934df072b5e0ad88092b2d5e2c7384 | C++ | FrankBotos/SFML-Topdown-Player-Character | /worldObject.h | UTF-8 | 797 | 2.828125 | 3 | [
"MIT"
] | permissive | //This is a class that should be inherited from by all "physical objects" in the game world
//Inheriting from this class will enable collision checking with player character
#pragma once
#include <SFML\Graphics.hpp>
#include <string>
//inhereting from drawable for syntactically clean drawing
//inheriting from Transformable so that object may be altered if needed
class WorldObject : public sf::Drawable {
private:
sf::Sprite _sprite;
sf::Texture _texture;
int spriteWidth;
int spriteHeight;
int xPos;
int yPos;
public:
WorldObject(std::string filename, int width, int height, int _xPos, int _yPos);
~WorldObject();
//implementing draw function for easier draw syntax
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
sf::FloatRect getCollisionBox();
};
| true |
2b4426f5989eb255cf49bb3f8f21d93a22c79d27 | C++ | Infinidat/infinitrace | /trace_instrumentor/util.cpp | UTF-8 | 3,488 | 2.59375 | 3 | [] | no_license | /*
* util.cpp: Various stand-alone functions for getting and manipulating string representations.
*
* File Created on: Feb 4, 2013 by Yitzik Casapu of Infindiat
* Original code by Yotam Rubin <yotamrubin@gmail.com>, 2012, Sponsored by infinidat (http://infinidat.com)
* Maintainer: Yitzik Casapu of Infindiat
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.
*/
#include "util.h"
#include <cctype>
using namespace clang;
using namespace std;
std::string getLiteralExpr(ASTContext &ast, Rewriter *Rewrite, const clang::Stmt *S)
{
SourceManager *SM = &ast.getSourceManager();
int Size = Rewrite->getRangeSize(S->getSourceRange());
if (Size == -1) {
return std::string("");
}
const char *startBuf = SM->getCharacterData(S->getLocStart());
return std::string(startBuf, Size);
}
std::string normalizeTypeName(const std::string& type_str) {
// Find and chop off any template arguments
const std::string::size_type template_arg_pos = type_str.find('<');
std::string replaced = type_str.substr(0, template_arg_pos);
// Reeplace spaces and scope resolution (::) operators with _
replaced = replaceAll(replaced, " ", "_");
return replaceAll(replaced, "::", "_");
}
std::string normalizeStr(const char *source_str, const char *preserve_chars)
{
string normalized(source_str);
unsigned n_trailing_underscores = 0;
for (size_t i = 0; i < normalized.length(); i++) {
if (! isalnum(normalized[i]) && (NULL == strchr(preserve_chars, normalized[i]))) {
normalized[i] = '_';
n_trailing_underscores++;
}
else {
n_trailing_underscores = 0;
}
}
normalized.erase(normalized.length() - n_trailing_underscores, string::npos);
return replaceAll(normalized, "__", "_");
}
std::string normalizeExpr(const std::string& expr)
{
string normalized(expr);
replaceAll(normalized, "->", ".");
static const char preserve_chars[] = "_.";
return normalizeStr(replaceAll(normalized, "->", ".").c_str(), preserve_chars);
}
static inline bool isCPlusPlus(LangOptions const& langOpts)
{
return langOpts.CPlusPlus != 0;
}
std::string castTo(LangOptions const& langOpts, const std::string& orig_expr, const std::string& cast_type)
{
if (isCPlusPlus(langOpts)) {
return "reinterpret_cast<" + cast_type + ">(" + orig_expr + ")";
} else {
return "(" + cast_type + ") (" + orig_expr + ")";
}
}
std::string getCallExprFunctionName(const clang::CallExpr *CE)
{
const FunctionDecl *callee = CE->getDirectCallee();
if (NULL == callee) {
return std::string();
}
return callee->getQualifiedNameAsString();
}
std::string& replaceAll(
std::string &result,
const std::string& replaceWhat,
const std::string& replaceWithWhat)
{
while(1)
{
const int pos = result.find(replaceWhat);
if (pos==-1) break;
result.replace(pos,replaceWhat.size(),replaceWithWhat);
}
return result;
}
| true |
d206d964e41b7c598d15e8915e4e587f91a84cff | C++ | onsar/osec | /arduino/libraries/FaBo_212_LCD_PCF8574/examples/Scroll/Scroll.ino | UTF-8 | 1,544 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | /*
This is an Example for the FaBo LCD I2C Brick.
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
compatible library 23 Mar 2016
by Hideki Yamauchi
This example code is in the public domain.
http://fabo.io/212.html
*/
// include the library code:
#include <Wire.h>
#include <FaBoLCD_PCF8574.h>
// initialize the library
FaBoLCD_PCF8574 lcd;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
delay(1000);
}
void loop() {
// scroll 13 positions (string length) to the left
// to move it offscreen left:
for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
// scroll one position left:
lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
// scroll 29 positions (string length + display length) to the right
// to move it offscreen right:
for (int positionCounter = 0; positionCounter < 29; positionCounter++) {
// scroll one position right:
lcd.scrollDisplayRight();
// wait a bit:
delay(150);
}
// scroll 16 positions (display length + string length) to the left
// to move it back to center:
for (int positionCounter = 0; positionCounter < 16; positionCounter++) {
// scroll one position left:
lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
// delay at the end of the full loop:
delay(1000);
}
| true |
8110a43cb82eda07556144d95121f702c1ffb644 | C++ | zlaval/ELTE_Prog | /objektum_elvu_programozas/complex/Complex.cpp | UTF-8 | 728 | 3.40625 | 3 | [] | no_license | #include "Complex.h"
#include <cmath>
Complex::Complex(double r, double i) {
this->r = r;
this->i = i;
}
Complex Complex::operator+(Complex oc) const {
return Complex(r + oc.r, i + oc.i);
}
Complex Complex::operator-(Complex oc) const {
return Complex(r - oc.r, i - oc.i);
}
Complex Complex::operator*(Complex oc) const {
return Complex(r * oc.r - i * oc.i, i * oc.r + r * oc.i);
}
Complex Complex::operator/(Complex oc) const {
double denominator = pow(oc.r, 2) + pow(oc.i, 2);
return Complex((r * oc.r + i * oc.i) / denominator, (i * oc.r - r * oc.i) / denominator);
}
std::ostream &operator<<(std::ostream &o, const Complex &p) {
o << "(" << p.r << " + " << p.i << "i)";
return o;
}
| true |
0aea4b50acaedfca049f22180c1c86e04a697048 | C++ | raghuramos1987/personal | /leet/threeSum.cpp | UTF-8 | 1,107 | 2.96875 | 3 | [] | no_license | /*******************************************************************
* File Name :
* Purpose :
* Created By : Raghuram Onti Srinivasan
* Email onti@cse.ohio-state.edu
*******************************************************************/
#include <stdio.h>
#include <vector>
#include <map>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <malloc.h>
#include <stdbool.h>
#include <math.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int getSum(vector<int> in, int ind)
{
vector<int> sum(in.size()-1,0);
int i,j;
for(i=ind;i<sum.size();i++)
{
sum[i] = in[ind]+in[i+1];
}
for(i=0;i<sum.size();i++)
cout<<sum[i]<<" ";
cout<<endl;
for(j=ind;j<sum.size();j++)
for(i=j+1;i<in.size();i++)
{
cout<<sum[j]+in[i]<<" ";
if(!(sum[j]+in[i]))
cout<<"Found one "<<i<<endl;
}
cout<<endl;
return 0;
}
int main()
{
int in[] = {5,0,-1,1,-5,1};
vector<int> inp (in, in+6);
for(int i=0;i<inp.size();i++)
cout<<inp[i]<<" ";
cout<<endl;
for(int i=0;i<inp.size()-1;i++)
getSum(inp, i);
}
| true |
cb3e5ec90ec5b1e894f5d76e08553d57d0038e2d | C++ | dugo/practicas-sistemas-ugr | /ed/Curso 05-06/matriz T/ejemplos.h | UTF-8 | 681 | 2.875 | 3 | [] | no_license | //fichero ejemplos.h
#ifndef __EJEMPLOS_H
#define __EJEMPLOS_H
#include <list>
#include "matriz.h"
template <class T>
class coordenadas{
public:
coordenadas(T d, int f, int c);
int nfila() const;
int ncol() const;
T dato() const;
private:
T dat;
int fila;
int columna;
};
template <class T>
bool operator<(const coordenadas<T> &d,const coordenadas<T> &c);
#include "ejemplos.template"
bool magica(const matriz<int> &entrada);
template <class T>
list<T> minimos_fila(const matriz<T> &entrada);
matriz<int> multiplicar(const list<matriz<int> > &entrada);
template <class T>
list<coordenadas<T> > ordenada(const matriz<T> &entrada);
#endif
| true |
ddc319dfc40ffea714a7d3e1766456af0ed06072 | C++ | luciocf/Problems | /IOI/IOI 2010/quality.cpp | UTF-8 | 968 | 2.734375 | 3 | [] | no_license | // IOI 2010 - Quality of Living
// Lúcio Cardoso
#include <bits/stdc++.h>
#include "quality.h"
using namespace std;
const int maxn = 3e3+10;
int n, m, a, b;
int num[maxn][maxn], soma[maxn][maxn];
bool ok(int x)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
soma[i][j] = soma[i][j-1]+soma[i-1][j]-soma[i-1][j-1];
if (num[i][j] > x) soma[i][j]++;
else if (num[i][j] < x) soma[i][j]--;
}
}
for (int i = a; i <= n; i++)
for (int j = b; j <= m; j++)
if (soma[i][j]-soma[i-a][j]-soma[i][j-b]+soma[i-a][j-b] <= 0)
return true;
return false;
}
int busca(void)
{
int ini = 1, fim = n*m, ans = fim+1;
while (ini <= fim)
{
int mid = (ini+fim)>>1;
if (ok(mid)) ans = mid, fim = mid-1;
else ini = mid+1;
}
return ans;
}
int rectangle(int R, int C, int H, int W, int Q[3001][3001])
{
n = R, m = C, a = H, b = W;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
num[i+1][j+1] = Q[i][j];
return busca();
}
| true |
61b2841c32eb8571cbff44a6311b1fa69b8c6e98 | C++ | alkaidlong/PaperDemo | /Dev/Common/MedusaCore/Core/Geometry/Rect2.h | UTF-8 | 6,012 | 3.09375 | 3 | [] | no_license | #pragma once
#include "Core/Geometry/Point2.h"
#include "Core/Geometry/Size2.h"
#include "Core/Math/MathHeader.h"
MEDUSA_BEGIN;
template<typename T>
class Rect2
{
public:
const static Rect2 Zero;
const static Rect2 Max;
Point2<T> Origin;
Size2<T> Size;
T* GetBuffer(){return (T*)this;}
T Left()const{return Origin.X;}
T Right()const{return Origin.X+Size.Width;}
T HorizontalCenter()const{return Origin.X+0.5f*Size.Width;}
T Bottom()const{return Origin.Y;}
T Top()const{return Origin.Y+Size.Height;}
T VerticalCenter()const{return Origin.Y+0.5f*Size.Height;}
Point2<T> LeftBottom()const{return Origin;}
Point2<T> LeftCenter()const{return Point2<T>(Origin.X,Origin.Y+0.5f*Size.Height);}
Point2<T> LeftTop()const{return Point2<T>(Origin.X,Origin.Y+Size.Height);}
Point2<T> MiddleBottom()const{return Point2<T>(Origin.X+0.5f*Size.Width,Origin.Y);}
Point2<T> MiddleCenter()const{return Point2<T>(Origin.X+0.5f*Size.Width,Origin.Y+0.5f*Size.Height);}
Point2<T> MiddleTop()const{return Point2<T>(Origin.X+0.5f*Size.Width,Origin.Y+Size.Height);}
Point2<T> RightBottom()const{return Point2<T>(Origin.X+Size.Width,Origin.Y);}
Point2<T> RightCenter()const{return Point2<T>(Origin.X+Size.Width,Origin.Y+0.5f*Size.Height);}
Point2<T> RightTop()const{return Point2<T>(Origin.X+Size.Width,Origin.Y+Size.Height);}
bool Contains(const Point2<T>& point)const
{
return point.X>=Left()&&point.X<=Right()&&point.Y>=Bottom()&&point.Y<=Top();
}
bool Contains(const Rect2& rect)const
{
return Contains(rect.LeftBottom())&&Contains(rect.RightTop());
}
bool IsIntersect(const Rect2& rect)const
{
return !(Left()>rect.Right()||Right()<rect.Left()||Top()<rect.Bottom()||Bottom()>rect.Top());
}
bool IsDisjoint(const Rect2& rect)const
{
return Right() <= rect.Left() || Left()>=rect.Right() || Top() <= rect.Bottom() || Bottom()>=rect.Top();
}
bool IsEmpty()const
{
return Size.IsEmpty();
}
void Inflate(const Point2<T>& amount)
{
Origin-=amount;
Size+=amount*2;
}
T Area()const{return Size.Area();}
static Rect2 Intersect(const Rect2& rect1,const Rect2& rect2)
{
if (rect1.IsEmpty()||rect2.IsEmpty())
{
return Rect2::Zero;
}
T right1=rect1.Right();
T right2=rect2.Right();
T top1=rect1.Top();
T top2=rect2.Top();
T maxLeft=Math::Max(rect1.Left(),rect2.Left());
T maxBottom=Math::Max(rect1.Bottom(),rect2.Bottom());
T minRight=Math::Min(rect1.Right(),rect2.Right());
T minTop=Math::Min(rect1.Top(),rect2.Top());
if (minRight>maxLeft&&minTop>maxBottom)
{
return Rect2(maxLeft,maxBottom,minRight-maxLeft,minTop-maxBottom);
}
return Rect2::Zero;
}
void Intersect(const Rect2& val)
{
if (val.IsEmpty())
{
*this=Rect2::Zero;
return;
}
T right1=Right();
T right2=val.Right();
T top1=Top();
T top2=val.Top();
T maxLeft=Math::Max(Left(),val.Left());
T maxBottom=Math::Max(Bottom(),val.Bottom());
T minRight=Math::Min(Right(),val.Right());
T minTop=Math::Min(Top(),val.Top());
if (minRight>maxLeft&&minTop>maxBottom)
{
Origin.X=maxLeft;
Origin.Y=maxBottom;
Size.Width=minRight-maxLeft;
Size.Height=minTop-maxBottom;
}
Origin=Point2<T>::Zero;
Size=Size2<T>::Zero;
}
static Rect2 Union(const Rect2& rect1,const Rect2& rect2)
{
if (rect1.IsEmpty())
{
return rect2;
}
if (rect2.IsEmpty())
{
return rect1;
}
T right1=rect1.Right();
T right2=rect2.Right();
T top1=rect1.Top();
T top2=rect2.Top();
T minLeft=Math::Min(rect1.Left(),rect2.Left());
T minBottom=Math::Min(rect1.Bottom(),rect2.Bottom());
T maxRight=Math::Max(rect1.Right(),rect2.Right());
T maxTop=Math::Max(rect1.Top(),rect2.Top());
return Rect2(minLeft,minBottom,maxRight-minLeft,maxTop-minBottom);
}
void Union(const Rect2& val)
{
RETURN_IF_EMPTY(val);
if (IsEmpty())
{
*this=val;
return;
}
T right1=Right();
T right2=val.Right();
T top1=Top();
T top2=val.Top();
T minLeft=Math::Min(Left(),val.Left());
T minBottom=Math::Min(Bottom(),val.Bottom());
T maxRight=Math::Max(Right(),val.Right());
T maxTop=Math::Max(Top(),val.Top());
Origin.X=minLeft;
Origin.Y=minBottom;
Size.Width=maxRight-minLeft;
Size.Height=maxTop-minBottom;
}
public:
Rect2(void){}
template<typename T1>
Rect2(const Point2<T1>& origin,const Size2<T1>& size):Origin(origin),Size(size){}
Rect2(const Point2<T>& origin,const Size2<T>& size):Origin(origin),Size(size){}
template<typename T1>
Rect2(T1 x,T1 y,T1 width,T1 height):Origin((T)x,(T)y),Size((T)width,(T)height){}
Rect2(T x,T y,T width,T height):Origin(x,y),Size(width,height){}
template<typename T1>
Rect2(const Rect2<T1>& rect):Origin(rect.Origin),Size(rect.Size){}
template<typename T1>
Rect2& operator=(const Rect2<T1>& rect){Origin=rect.Origin;Size=rect.Size;return *this;}
template<typename T1>
Rect2& operator=(T1 val){Origin=val;Size=val;return *this;}
template<typename T1>
bool operator==(const Rect2<T1>& rect)const{return Math::IsEqual(Origin,rect.Origin)&&Math::IsEqual(Size,rect.Size);}
template<typename T1>
bool operator!=(const Rect2<T1>& rect)const{return !operator==(rect);}
template<typename T1>
bool operator<(const Rect2<T1>& rect)const{return Origin<rect.Origin&&Size<rect.Size;}
template<typename T1>
bool operator<=(const Rect2<T1>& rect)const{return Origin<=rect.Origin&&Size<=rect.Size;}
template<typename T1>
bool operator>(const Rect2<T1>& rect)const{return Origin>rect.Origin&&Size>rect.Size;}
template<typename T1>
bool operator>=(const Rect2<T1>& rect)const{return Origin>=rect.Origin&&Size>=rect.Size;}
intp GetHashCode()const{return Origin.GetHashCode()^Size.GetHashCode();}
};
template<typename T>
WEAK_MULTIPLE_DEFINE const Rect2<T> Rect2<T>::Zero(0,0,0,0);
template<typename T>
WEAK_MULTIPLE_DEFINE const Rect2<T> Rect2<T>::Max(0,0,Math::Values<T>::Max,Math::Values<T>::Max);
//[PRE_DECLARE_BEGIN]
typedef Rect2<int> Rect2I;
typedef Rect2<uint> Rect2U;
typedef Rect2<float> Rect2F;
//[PRE_DECLARE_END]
MEDUSA_END;
| true |
7d7b69282cadf8e99f159ce5b6ffb76dcd861935 | C++ | goatman/M5AtomMatrix | /serial01/Touchdesigner-Arduino/Serial_Input_Rev1/Serial_Input_Rev1.ino | UTF-8 | 795 | 3.015625 | 3 | [
"MIT"
] | permissive |
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte
int switchPin = 12;
int ledPin = 11;
void setup() {
// start serial port at 9600 bps:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP); // digital sensor is on digital pin 12
//establishContact(); // send a byte to establish contact until receiver responds
}
void loop() {
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
analogWrite(ledPin, inByte);
}
thirdSensor = digitalRead(switchPin);
Serial.println(thirdSensor);
//Serial.println(inByte);
}
| true |
24c9fa4820981bf0555998025d71d576e78ab192 | C++ | PhenomJ/2D_TileMap_Games | /RPG_Game/Sprite.cpp | UTF-8 | 3,357 | 2.515625 | 3 | [] | no_license | #include <fstream>
#include <reader.h>
#include "Sprite.h"
#include "GameSystem.h"
#include "Frame.h"
#include "Texture.h"
#include "ResourceManager.h"
Sprite::Sprite(LPCWSTR texturefileName, LPCWSTR scriptfileName, float rotate) : _currnetFrame(0), _frameTime(0.0f), _srcTexture(NULL),
_texturefileName(texturefileName), _scriptfileName(scriptfileName), _rotate(rotate)
{
}
Sprite::~Sprite()
{
}
void Sprite::Init(int srcX, int srcY, int x, int y, float frameDelay, D3DCOLOR color)
{
_device3d = GameSystem::GetInstance()->GetDevice3d();
_sprite = GameSystem::GetInstance()->GetSprite();
_srcTexture = ResourceManager::GetInstance()->LoadTexture(_texturefileName);
{
Frame* frame = new Frame();
frame->Init(_srcTexture, srcX, srcY, x, y, _rotate,frameDelay, color);
_frameList.push_back(frame);
}
_currnetFrame = 0;
_frameTime = 0.0f;
}
void Sprite::Init()
{
_device3d = GameSystem::GetInstance()->GetDevice3d();
_sprite = GameSystem::GetInstance()->GetSprite();
_srcTexture = ResourceManager::GetInstance()->LoadTexture(_texturefileName);
//json Parsing
{
std::vector<std::string> script = ResourceManager::GetInstance()->LoadScript(_scriptfileName);
for (int i = 0 ; i < script.size(); i++)
{
std::string record = script[i];
Json::Value root;
Json::Reader reader;
bool isSuccess = reader.parse(record, root);
if (isSuccess)
{
std::string texture = root["texture"].asString();
int x = root["x"].asInt();
int y = root["y"].asInt();
int width = root["width"].asInt();
int height = root["height"].asInt();
double framedelay = root["framedelay"].asDouble();
if (_rotate == 0)
_rotate = root["rotate"].asInt();
Frame* frame = new Frame();
frame->Init(_srcTexture, x, y, width, height, _rotate,framedelay, D3DCOLOR_ARGB(255, 255, 255, 255));
_frameList.push_back(frame);
}
}
}
_currnetFrame = 0;
_frameTime = 0.0f;
}
void Sprite::Deinit()
{
std::vector<Frame*>::iterator itr = _frameList.begin();
for (itr = _frameList.begin(); itr != _frameList.end(); itr++)
{
Frame* frame = (*itr);
frame->Deinit();
delete frame;
}
_frameList.clear();
_srcTexture = NULL;
}
void Sprite::Render()
{
if (_currnetFrame < _frameList.size())
{
_frameList[_currnetFrame]->SetPosition(_x, _y);
_frameList[_currnetFrame]->Render();
}
}
void Sprite::Reset()
{
Init();
std::vector<Frame*>::iterator itr = _frameList.begin();
for (itr = _frameList.begin(); itr != _frameList.end(); itr++)
{
Frame* frame = (*itr);
frame->Reset();
}
}
void Sprite::Release()
{
std::vector<Frame*>::iterator itr = _frameList.begin();
for (itr = _frameList.begin(); itr != _frameList.end(); itr++)
{
Frame* frame = (*itr);
frame->Release();
}
_srcTexture->Release();
}
void Sprite::Update(float deltaTime)
{
_frameTime += deltaTime;
if (_frameList[_currnetFrame]->GetFrameDelay() <= _frameTime)
{
_frameTime = 0.0f;
_currnetFrame = (_currnetFrame + 1) % _frameList.size();
}
}
void Sprite::SetPosition(float posX, float posY)
{
_x = posX;
_y = posY;
}
void Sprite::ChangeColor(D3DCOLOR color)
{
_device3d = GameSystem::GetInstance()->GetDevice3d();
std::vector<Frame*>::iterator itr = _frameList.begin();
for (itr = _frameList.begin(); itr != _frameList.end(); itr++)
{
Frame* frame = (*itr);
frame->ChangeColor(color);
}
} | true |
1952666c45786663b24ae35a23f90f19a13f639b | C++ | lukaszwoznica/algorithms-and-data-structures | /bst.cpp | UTF-8 | 3,128 | 3.65625 | 4 | [] | no_license | <iostream>
#include <queue>
#include <cmath>
using namespace std;
struct Details{
string name;
double ratio;
int position;
};
struct Compare{
bool operator ()( Details & el1, Details & el2){
if(el1.ratio < el2.ratio)
return true;
if(el1.ratio > el2.ratio)
return false;
if(el1.position < el2.position)
return true;
if(el1.position > el2.position)
return false;
return false;
}
};
struct Node{
int price;
Node *left, *right;
priority_queue<Details, vector<Details>, Compare> p_que;
Node(int price, Details new_el){
left = right = NULL;
this->price = price;
p_que.push(new_el);
}
void print(){
cout << p_que.top().name << endl;
}
};
class BST{
public:
Node *root;
BST(){
root = NULL;
}
Node * search(int key){
Node *v = root;
while(v != NULL && v->price != key){
if(v->price < key)
v = v->right;
else
v = v->left;
}
return v;
}
void insert(int price, Details new_el) {
if(!root)
root = new Node(price, new_el);
else{
Node *current = root;
Node *parent = NULL;
while(current){
if (current->price == price){
current->p_que.push(new_el);
return;
}
if (current->price > price) {
parent = current;
current = current->left;
}
else {
parent = current;
current = current->right;
}
}
current = new Node(price, new_el);
if (parent->price > current->price)
parent->left = current;
else
parent->right = current;
}
}
void remove(Node *remove_el){
if (!remove_el->p_que.empty())
remove_el->p_que.pop();
}
};
int main(){
int operations_num, voices, price;
float avg, ratio;
string name;
char oper_type;
BST tree;
Details new_element;
cin >> operations_num;
for(int i = 0; i < operations_num; i++){
cin >> oper_type;
if(oper_type == 'A'){
cin >> avg >> voices >> price >> name;
new_element.name = name;
new_element.ratio = avg / 5 * floor(voices / 1000);
new_element.position = i;
tree.insert(price, new_element);
}
else if(oper_type == 'S'){
cin >> price >> ratio;
Node *temp = tree.search(price);
if(!temp || temp->p_que.empty() || temp->p_que.top().ratio < ratio)
cout << "-" << endl;
else{
temp->print();
tree.remove(temp);
}
}
}
return 0;
} | true |
3a1c0161744fa72dcba11c26f9e5277607e9ffac | C++ | crimsondusk/cobalt | /src/types/udp.cc | UTF-8 | 3,431 | 2.71875 | 3 | [] | no_license | #include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include "udp.h"
#include "bytestream.h"
#include "format.h"
#include "flood_throttle.h"
namespace cbl
{
// -----------------------------------------------------------------------------
//
udp_socket::udp_socket() :
m_blocking( false ) {}
// -----------------------------------------------------------------------------
//
udp_socket::~udp_socket() {}
// -----------------------------------------------------------------------------
//
// Initializes the socket with the given port
//
bool udp_socket::init( uint16 port )
{
m_error = "";
m_socket = socket( AF_INET, SOCK_DGRAM, 0 );
if( blocking() == false )
{
int flags = fcntl( m_socket, F_GETFL, 0 );
if( flags < 0 || fcntl( m_socket, F_SETFL, flags | O_NONBLOCK ) != 0 )
{
m_error = "Unable to set socket as non-blocking";
return false;
}
}
return true;
}
// -----------------------------------------------------------------------------
//
// Binds this socket with the given port for hosting.
//
bool udp_socket::bind( uint16 port )
{
struct sockaddr_in svaddr;
memset( &svaddr, 0, sizeof svaddr );
svaddr.sin_family = AF_INET;
svaddr.sin_port = htons( port );
svaddr.sin_addr.s_addr = htonl( INADDR_ANY );
if( ::bind( m_socket, reinterpret_cast<struct sockaddr*>( &svaddr ), sizeof svaddr ) == -1 )
{
m_error = string( "Couldn't bind to port " ) + (int) port;
return false;
}
return true;
}
// -----------------------------------------------------------------------------
//
// Ticks this socket. This must be called repeadetly for the socket to function.
//
bool udp_socket::tick()
{
struct sockaddr_in claddr;
socklen_t socklen = sizeof claddr;
char packet[5120];
int n = recvfrom( m_socket, packet, sizeof packet, 0,
reinterpret_cast<struct sockaddr*>( &claddr ), &socklen );
if( n == -1 )
{
// We got an error, though EWOULDBLOCK is silent as it means no packets recieved.
if( errno != EWOULDBLOCK )
perror( "CoUDPSocket: recvfrom error:" );
return;
}
ip_address addr( ntohl( claddr.sin_addr.s_addr ), ntohs( claddr.sin_port ) );
// Ignore this request if the sender is throttled
if( m_throttle.is_host_throttled( addr ))
{
if( is_verbose() )
print( "-- Ignoring UDP packet from throttled host %1\n", addr );
return;
}
bytestream in( packet, n );
incoming( in, addr );
}
// -----------------------------------------------------------------------------
//
// Launches the given bytestream packet to the specified IP address.
//
bool udp_socket::launch( const bytestream& data, const ip_address& addr )
{
struct sockaddr_in claddr = addr.to_sockaddr_in();
int res = sendto( m_socket, data.data(), data.length(), 0,
reinterpret_cast<struct sockaddr*>( &claddr ), sizeof claddr );
if( res == -1 )
{
if( is_verbose() )
perror( "Unable to launch packet" );
return false;
}
return true;
}
// -----------------------------------------------------------------------------
//
// Adds the given IP address to the flood queue for the given amount of
// seconds. All messages from throttled addresses are ignored.
//
void udp_socket::throttle( CoIPAddress addr, int secs )
{
m_throttle.add_host( addr, time::now() + secs );
}
}
| true |