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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
903d28f9057c5d3c9e99223f45e0fe7df8ce59a2 | C++ | zgbzsu2008/boost_asio_for_linux | /handler_work.hpp | UTF-8 | 1,397 | 2.546875 | 3 | [] | no_license | #ifndef BOOST_ASIO_DETAIL_HANDLER_WORK_HP
#define BOOST_ASIO_DETAIL_HANDLER_WORK_HPP
#include "associated_executor.hpp"
#include "noncopyable.hpp"
#include "system_executor.hpp"
#include "handler_invoke_helpers.hpp"
namespace boost::asio::detail {
template <typename Handler, typename Executor = typename associated_executor<Handler>::type>
class handler_work : public noncopyable
{
public:
explicit handler_work(Handler& handler) : executor_(associated_executor<Handler>::get(handler)) {}
~handler_work() { executor_.on_work_finished(); }
static void start(Handler& handler)
{
Executor ex(associated_executor<Handler>::get(handler));
ex.on_work_started();
}
template <typename Function>
void complate(Function&& function, Handler& handler) {
executor_.dispatch(std::forward<Function>(function), associated_executor<Handler>::get(handler));
}
private:
typename associated_executor<Handler>::type executor_;
};
template <typename Handler>
class handler_work<Handler, system_executor> : public noncopyable {
public:
explicit handler_work(Handler&) {}
~handler_work() {}
static void start(Handler&) {}
template <typename Function>
void complate(Function&& function, Handler& handler)
{
boost_asio_handler_invoke_helpers::invoke(function, handler);
}
};
} // namespace boost::asio::detail
#endif // !BOOST_ASIO_DETAIL_HANDLER_WORK_HPP
| true |
ddf7ef0234ffe3c164aeb9601103d23a53afb24b | C++ | cotitan/httpd | /src/router.cpp | UTF-8 | 2,023 | 2.609375 | 3 | [] | no_license | #include "controller.h"
#include "my_io.h"
#include <cstring>
#include <cstdio>
#include <unistd.h>
#define DEBUG_MODE
#ifdef DEBUG_MODE
#define DEBUG printf
#else
#define DEBUG
#endif
#ifndef SEGSIZE
#define SEGSIZE 10240
#endif
struct thread_params {
int connfd;
char *header;
int len;
};
int route(int connfd, const httpRequest &req) {
string url = req.getUrl();
DEBUG("Req on : %s\n", url.c_str());
controller *ctrller = NULL;
size_t epos = url.find('/', 0 + 1);
// if on root directory
if (epos == string::npos) {
ctrller = new controller;
} else if (url.substr(0, 8) == "/picture") {
ctrller = new pic_controller;
}
int status = ctrller->handle(connfd, req);
delete ctrller;
return status;
}
void *accept_req(void* param_) {
// pthread_detach(pthread_self());
struct thread_params param = *(struct thread_params *)param_;
int connfd = param.connfd;
char *header = param.header, *pos;
int nread = param.len;
if ((pos = strstr(header, "\r\n\r\n")) == NULL) {
return (void *)-1;
}
/*
while (nread && nread <= SEGSIZE
&& (pos = strstr(header, "\r\n\r\n")) == NULL) {
nread += read(connfd, header + nread, SEGSIZE);
header[nread] = 0;
}
*/
// printf("%s\n", header);
httpRequest req(header);
if (req.getMethod() == ERR) {
return (void *) -1;
}
// printf("%d %s\n", req.getMethod(), req.getUrl().c_str());
if (req.getMethod() == POST) {
int content_length = req.getContentLength();
char *data = new char[content_length + 1];
if (data == NULL)
perror("fail to allocate memory for new\n");
nread -= pos + 4 - header;
memcpy(data, pos + 4, nread);
while (nread < content_length) {
nread += readn(connfd, data + nread,
min(SEGSIZE, content_length - nread));
data[nread] = 0;
}
req.setData(data);
}
if (route(connfd, req) == -1) {
DEBUG("Finish accept_req!\n");
return (void *) -1;
}
// delete[] data; // will be deleted in httpRequest::~httpRequest()
// pthread_exit((void *)0);
DEBUG("Finish accept_req!\n");
return NULL;
}
| true |
b507f6a338a5a0abec3e00f0ad7eadf446101b6b | C++ | AbhishekPratik1810/my_cpp_dsa_practice | /9.31 Trees - Transit Tree Path.cpp | UTF-8 | 768 | 2.625 | 3 | [] | no_license | //https://atcoder.jp/contests/abc070/tasks/abc070_d
#include<iostream>
#include<vector>
#include<map>
using namespace std;
#define ll long long
int v;
ll depth[100001]={};
bool vis[100001] = {};
map<int,vector<pair<int,int>>> adjList;
void dfs(int root){
vis[root]=1;
for(auto i : adjList[root]){
if(!vis[i.first]){
depth[i.first]=depth[root]+i.second;
dfs(i.first);
}
}
}
int main(){
cin>>v;
int from,to,wt;
for(int i=0;i<v-1;i++){
cin>>from>>to>>wt;
adjList[from].push_back({to,wt});
adjList[to].push_back({from,wt});
}
int q,k;
cin>>q>>k;
dfs(k);
for(int i=0;i<q;i++){
cin>>from>>to;
cout<<depth[from]+depth[to]<<endl;
}
}
| true |
3bb9fcff3133046f30b0394441e00fb11c1111c0 | C++ | rheehot/Algorithm-53 | /2164.cpp | UTF-8 | 302 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
int main() {
int N;
cin >> N;
queue <int> queue;
for (int i = 1; i <= N; i++) {
queue.push(i);
}
while (queue.size() > 1) {
queue.pop();
queue.push(queue.front());
queue.pop();
}
cout << queue.front() << endl;
return 0;
} | true |
262b48b5a3fab5b1b7136cea05f0b6b4609856bc | C++ | guiRodrigues/BinaryCalculator | /main.cpp | UTF-8 | 2,526 | 3.859375 | 4 | [] | no_license | /*
* ~> Problemas com o tipo de dado { long long ~ int }
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int Power(int base, int exponent){
int response=1;
for(int i=1; i<=exponent; i++) response*=base;
return response;
}
void BinaryToDecimal(){
int counter=0, sum=0;
bool invalidNumber=false;
// Qual a razao do DIGIT ser long long int
long long int number=0, digit=0;
cout << "\n\n~> OK, now you need input the binary number:\n";
cin >> number;
while(number>0){
digit=number%10;
if(digit!=0 && digit!=1){
invalidNumber=true;
break;
}
if(digit==1) sum+=Power(2,counter);
counter++;
number/=10;
}
if(invalidNumber) cout << "\n\n~> I'm sorry, I can't solve the problem, you input a invalid value\n\n\n";
else cout << "\n\n°°°{ " << sum << " }°°°\n\n\n";
}
void DecimalToBinary(){
int number=0;
cout << "\n\n~> OK, now you need input the decimal number:\n";
cin >> number;
long long binaryNumber = 0;
int remainder, i = 1;
while (number!=0)
{
remainder = number%2;
number /= 2;
binaryNumber += remainder*i;
i *= 10;
}
cout << "\n\n°°°{ " << binaryNumber << " }°°°\n\n\n";
}
void Exercise(){
int operation=0;
cout << "\n\n~> Ok, now you will choose the type of exercise:\n~~~~~> { 1 } to decimal~binary;\n~~~~~> { 2 } to binary~decimal\n\n";
cin >> operation;
if(operation==1) cout << ( rand()%100 )+1 << "\n\n";
else if(operation) cout << "wait\n\n";
}
int main() {
int operation=0;
bool end=false;
while(!end) {
cout << "\n\n~> Hello User\n~> Welcome to the binary calculator\n";
cout << "~> So, to start you need choose the operation:\n";
cout << "~> Press { 1 } to BINARY ~ DECIMAL\n";
cout << "~> Press { 2 } to DECIMAL ~ BINARY\n";
cout << "~> Press { 3 } to exercise\n";
cin >> operation;
while (operation!=1 && operation!=2 && operation!=3) {
cout << "~> Invalid operation, write again" << "\n";
cin >> operation;
}
if (operation == 1) BinaryToDecimal();
else if (operation == 2) DecimalToBinary();
else if(operation == 3) Exercise();
cout << "~> Another operation? Press { 1 } to continue or { 2 } to finish.\n";
cin >> operation;
if(operation==2) end=true;
}
return 0;
} | true |
5754909c009d476df5b430de2a76ce64644a80ed | C++ | yuting-zhang/UVa | /10179 - Irreducable Basic Fractions/fractions.cpp | UTF-8 | 894 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define UPPERBOUND 32000
vector<int> primes;
void sieve() {
bitset<UPPERBOUND> bs;
bs.set();
bs[0] = bs[1] = false;
for (long long i = 2; i < UPPERBOUND; i++)
if (bs[i]) {
for (long long j = i * i; j < UPPERBOUND; j += i)
bs[j] = false;
primes.push_back(static_cast<int>(i));
}
}
long long Euler_totient(int N) {
long long phi = N;
int index = 0, factor = primes[index];
while (factor * factor <= N) {
if (N % factor == 0)
phi -= phi / factor;
while (N % factor == 0)
N /= factor;
factor = primes[++index];
}
if (N != 1)
phi -= phi / N;
return phi;
}
int main(){
sieve();
int N;
while (scanf("%d", &N) && N) {
printf("%lld\n", Euler_totient(N));
}
return 0;
}
| true |
ea9c05698ef6045c7cdd961a133066fe60e25cd7 | C++ | y2kiah/icarus | /Icarus/source/Application/Impl/Timer_win32.cpp | UTF-8 | 3,340 | 2.671875 | 3 | [] | no_license | /* Timer_win32.cpp
Author: Jeff Kiah
Orig.Date: 5/21/12
*/
#include "Application/Timer.h"
#if defined(WIN32)
#include "Utility/Debug.h"
#include <cmath>
// Static Variables
int64_t Timer::sTimerFreq = 0;
double Timer::sSecondsPerCount = 0;
double Timer::sMillisecondsPerCount = 0;
#ifdef _DEBUG
bool Timer::sInitialized = false;
#endif
// Static Functions
#ifdef _DEBUG
bool Timer::initialized() { return sInitialized; }
#endif
int64_t Timer::timerFreq()
{
return sTimerFreq;
}
double Timer::secondsPerCount()
{
return sSecondsPerCount;
}
int64_t Timer::queryCounts()
{
_ASSERTE(sInitialized);
int64_t now = 0;
QueryPerformanceCounter((LARGE_INTEGER *)&now);
return now;
}
int64_t Timer::countsSince(int64_t startCounts)
{
_ASSERTE(sInitialized);
int64_t now = 0;
QueryPerformanceCounter((LARGE_INTEGER *)&now);
return now - startCounts;
}
double Timer::secondsSince(int64_t startCounts)
{
_ASSERTE(sInitialized);
int64_t now = 0;
QueryPerformanceCounter((LARGE_INTEGER *)&now);
return static_cast<double>(now - startCounts) * sSecondsPerCount;
}
double Timer::secondsBetween(int64_t startCounts, int64_t stopCounts)
{
_ASSERTE(sInitialized);
return static_cast<double>(stopCounts - startCounts) * sSecondsPerCount;
}
bool Timer::initHighPerfTimer()
{
SetThreadAffinityMask(GetCurrentThread(), 1);
// get high performance counter frequency
BOOL result = QueryPerformanceFrequency((LARGE_INTEGER *)&sTimerFreq);
if (result == 0 || sTimerFreq == 0) {
debugPrintf("Timer::initTimer: QueryPerformanceFrequency failed (error %d)\n", GetLastError());
return false;
}
sSecondsPerCount = 1.0 / static_cast<double>(sTimerFreq);
sMillisecondsPerCount = sSecondsPerCount * 1000.0;
// test counter function
int64_t dummy = 0;
result = QueryPerformanceCounter((LARGE_INTEGER *)&dummy);
if (result == 0) {
debugPrintf("Timer::initTimer: QueryPerformanceCounter failed (error %d)\n", GetLastError());
return false;
}
#ifdef _DEBUG
sInitialized = true;
#endif
return true;
}
// Member Functions
void Timer::start()
{
_ASSERTE(sInitialized);
QueryPerformanceCounter((LARGE_INTEGER *)&mStartCounts);
//mStartTickCount = GetTickCount64();
mStopCounts = mStartCounts;
//mStopTickCount = mStartTickCount;
mCountsPassed = 0;
mMillisecondsPassed = 0;
mSecondsPassed = 0;
}
double Timer::stop()
{
_ASSERTE(sInitialized);
// query the current counts from QPC and GetTickCount64
QueryPerformanceCounter((LARGE_INTEGER *)&mStopCounts);
//mStopTickCount = GetTickCount64();
// get time passed since start() according to QPC and GetTickCount64
mCountsPassed = mStopCounts - mStartCounts;
//int64_t ticksPassed = mStopTickCount - mStartTickCount;
// find the difference between the two clocks
//double diff = mMillisecondsPassed - ticksPassed;
//if (abs(diff) > DISCREPANCY_MS_CHECK) { // check for discrepancy > X ms
// if the discrepancy is large, QPC probably skipped so we should trust GetTickCount64
// debugPrintf("Timer::stop: QPC discrepency detected (difference %fms)\n", diff);
// mMillisecondsPassed = static_cast<double>(ticksPassed);
// mSecondsPassed = ticksPassed * 0.001;
//} else {
mSecondsPassed = min(static_cast<double>(mCountsPassed) * sSecondsPerCount, 0.0);
mMillisecondsPassed = mSecondsPassed * 1000.0;
//}
return mMillisecondsPassed;
}
#endif // ifdef WIN32 | true |
0d0dca6dafd57fa17e0af0b6b1269781d8579831 | C++ | janmejay/medida | /src/medida/counter.cc | UTF-8 | 2,226 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | //
// Copyright (c) 2012 Daniel Lundin
//
#include "medida/counter.h"
#include <atomic>
#include <sstream>
namespace medida {
class Counter::Impl {
public:
Impl(std::int64_t init = 0);
~Impl();
void process(MetricProcessor& processor);
std::int64_t count() const;
void set_count(std::int64_t n);
void inc(std::int64_t n = 1);
void dec(std::int64_t n = 1);
void clear();
const std::string& attribute_signature() const;
private:
std::atomic<std::int64_t> count_;
std::string attr_sig_;
};
Counter::Counter(std::int64_t init) : impl_ {new Counter::Impl {init}} { }
Counter::~Counter() { }
void Counter::process(MetricProcessor& processor) {
processor.process(*this); // FIXME: pimpl?
}
std::int64_t Counter::count() const {
return impl_->count();
}
void Counter::set_count(std::int64_t n) {
return impl_->set_count(n);
}
void Counter::inc(std::int64_t n) {
impl_->inc(n);
}
void Counter::dec(std::int64_t n) {
impl_->dec(n);
}
void Counter::clear() {
impl_->clear();
}
const std::string& Counter::attribute_signature() const {
return impl_->attribute_signature();
}
// === Implementation ===
Counter::Impl::Impl(std::int64_t init) : count_ {init} {
std::stringstream ss;
ss << "initial_value='" <<count_ << "'";
attr_sig_ = ss.str();
}
Counter::Impl::~Impl() { }
std::int64_t Counter::Impl::count() const {
return count_.load(std::memory_order_relaxed);
}
void Counter::Impl::set_count(std::int64_t n) {
count_.store(n, std::memory_order_relaxed);
}
void Counter::Impl::inc(std::int64_t n) {
count_.fetch_add(n, std::memory_order_relaxed);
}
void Counter::Impl::dec(std::int64_t n) {
count_.fetch_sub(n, std::memory_order_relaxed);
}
void Counter::Impl::clear() {
set_count(0);
}
const std::string& Counter::Impl::attribute_signature() const {
return attr_sig_;
}
}
| true |
26d88862477fc13274e1dfc25ee85b282be22583 | C++ | mhcrnl/1000ProgrameCpp | /cpp/exo63-1.cc | UTF-8 | 2,751 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
// ----------------------------------------------------------------------
class Animal {
public:
Animal(string, string);
~Animal();
void affiche() const;
protected:
string nom;
string continent;
};
void Animal::affiche() const {
cout<<"Je suis un " << nom << " et je vis en " << continent << endl;
}
Animal::Animal(string nom, string continent)
:nom(nom), continent(continent)
{
cout<< "Nouvel animal protege"<< endl;
}
Animal::~Animal() {
cout<< "Je ne suis plus protege"<< endl;
}
// --------------------------------------------------------------------
class EnDanger {
public:
void affiche() const;
EnDanger(unsigned int);
~EnDanger();
protected:
unsigned int nombre;
};
void EnDanger::affiche() const {
cout << "Il ne reste que " << nombre
<< " individus de mon espece sur Terre" << endl;
}
EnDanger::EnDanger(unsigned int nombre)
: nombre(nombre) {
cout << "Nouvel animal en danger" << endl;
}
EnDanger::~EnDanger() {
cout<< "ouf! je ne suis plus en danger"<< endl;
}
// --------------------------------------------------------------------
class Gadget {
public:
void affiche() const;
void affiche_prix() const;
Gadget(string, double);
~Gadget();
protected:
string nom;
double prix;
};
void Gadget::affiche() const {
cout << "Mon nom est " << nom << endl;
}
void Gadget::affiche_prix() const {
cout << "Achetez-moi pour " << prix
<< " francs et vous contribuerez a me sauver!" << endl;
}
Gadget::Gadget(string nom, double prix)
: nom(nom), prix(prix) {
cout<< "Nouveau gadget"<< endl;
}
Gadget::~Gadget() {
cout<< "Je ne suis plus un gadget"<< endl;
}
// ----------------------------------------------------------------------
class Peluche : public Animal, public EnDanger, public Gadget {
public:
void etiquette() const;
Peluche(string, string, string, unsigned int, double);
~Peluche();
};
void Peluche::etiquette() const {
cout << "Hello," << endl;
Gadget::affiche();
Animal::affiche();
EnDanger::affiche();
affiche_prix();
cout<<endl;
}
Peluche::Peluche(string nom_animal, string nom_gadget,
string continent, unsigned int nombre, double prix)
: Animal(nom_animal, continent), EnDanger(nombre),
Gadget(nom_gadget, prix)
{ cout << "Nouvelle peluche" << endl; }
Peluche::~Peluche() {
cout << "Je ne suis plus une peluche" << endl;
}
// ----------------------------------------------------------------------
int main()
{
Peluche panda("Panda","Ming","Asie", 200, 20.0);
Peluche serpent("Cobra","Ssss","Asie", 500, 10.0);
Peluche toucan("Toucan","Bello","Amerique", 1000, 15.0);
panda.etiquette();
serpent.etiquette();
toucan.etiquette();
return 0;
}
| true |
6415a55068cc3054756fa36e42177a6a20a009a6 | C++ | mwerlberger/imp | /deprecated/imageutilities/src/iucore/linearmemory.h | UTF-8 | 1,646 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) ICG. All rights reserved.
*
* Institute for Computer Graphics and Vision
* Graz University of Technology / Austria
*
*
* This software is distributed WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notices for more information.
*
*
* Project : Utilities for IPP and NPP images
* Module : Memory (linear) base class
* Class : LinearMemory
* Language : C++
* Description : Implementation of linear memory base class
*
* Author : Manuel Werlberger
* EMail : werlberger@icg.tugraz.at
*
*/
#ifndef LINEARMEMORY_H
#define LINEARMEMORY_H
#include "globaldefs.h"
#include "coredefs.h"
namespace iu {
/** \brief LinearMemory Base class for linear memory classes.
*/
class LinearMemory
{
public:
LinearMemory() :
length_(0)
{ }
LinearMemory(const LinearMemory& from) :
length_(from.length_)
{ }
LinearMemory(const unsigned int& length) :
length_(length)
{ }
virtual ~LinearMemory()
{ }
/** Returns the number of elements saved in the device buffer. (length of device buffer) */
unsigned int length() const
{
return length_;
}
/** Returns the total amount of bytes saved in the data buffer. */
virtual size_t bytes() const {return 0;}
/** Returns the bit depth of the data pointer. */
virtual unsigned int bitDepth() const {return 0;}
/** Returns flag if the image data resides on the device/GPU (TRUE) or host/GPU (FALSE) */
virtual bool onDevice() const {return false;}
private:
unsigned int length_;
};
} // namespace iu
#endif // LINEARMEMORY_H
| true |
5585825bdbc4d68851636152065f7878a5008e97 | C++ | iLovebugs/Arduino | /I2C working/SNEP.cpp | UTF-8 | 5,311 | 2.71875 | 3 | [] | no_license | #include "SNEP.h"
SNEP::SNEP(NFCLinkLayer *linkLayer) :
_linkLayer(linkLayer){
}
SNEP::~SNEP(){
}
// Receives a SNEP request from the client.
// Arguments: data will be set to point to the received NDEF message
// request[0] will be set the the SNEP request type and request[1] will be set to acceptable length if SNEP request type is Get
// Returns the length of the received NDEF message
uint32_t SNEP::receiveRequest(uint8_t *&data){
//Act as server, acts as the SNEP server process present on NFC-enabled devices.
uint32_t result = _linkLayer->openLinkToClient(true);
if(RESULT_OK(result)){
Serial.println(F("SNEP>receiveData: CONNECTED."));
result = _linkLayer->receiveFromClient(data,true);
if(RESULT_OK(result)){
if(data[0] != SNEP_SUPPORTED_VERSION){
Serial.print(F("SNEP>receiveData: Recieved an SNEP message of an unsupported version: "));
Serial.println(data[0]);
return SNEP_UNSUPPORTED_VERSION;
}
// Manage the request that was sent as argument
if(data[1] == SNEP_PUT_REQUEST){
data = &data[6]; //Discard SNEP header
Serial.println(F("SNEP>receiveData: Receiving a SNEP put request"));
Serial.print(F("SNEP>receiveData: Length: "));
uint32_t length = data[2];
Serial.print(F("0x"));
Serial.println(length, HEX);
return data[2]; //returing length of NDEF message
}
else{ // If a request without any NDEF message is retrieved(Reject, Continue or Get), no data can be returned.
data = '\0';
return SNEP_UNEXPECTED_REQUEST;
}
}
}
return result;
}
// Transmits a SNEP response to the client. A link must have been established before this function is called
// Arguments: NDEFMessage is the NDEF message to be sent
// length is the length of the NDEF message to be sent
// response is the response type to be used
// Returns the length of the received NDEF message
uint32_t SNEP::transmitSuccess(){
SNEP_PDU *snepResponse;
// Incapsulate the NDEF message into a SNEP response message
// TODO METODER FÖR ATT TILLDELA SKIT!
snepResponse-> version = SNEP_SUPPORTED_VERSION;
snepResponse-> type = SNEP_SUCCESS;
snepResponse-> length = 0; // ********************************************************** Här är något fel kanske med length eller SNEP_PDU_HEADER_LEN******************************
/*
snepResponse->version = SNEP_SUPPORTED_VERSION;
snepResponse->type = SNEP_SUCCESS;
snepResponse->length = 0;*/
uint32_t result = _linkLayer->transmitToServer((uint8_t *)snepResponse, SNEP_PDU_HEADER_LEN,false);
_linkLayer->closeLinkToClient(); //Recieve a DISC pdu, Client tears down the connection. TODO: ADD TEST IF DISC?
return result;
}
// Transmits a SNEP request to the server. A link must have been established before this function is called
// Arguments: NDEFMessage is the NDEF message to be sent
// length is the length of the NDEF message to be sent
// request[0] is the the SNEP request type and request[1] is the acceptable length if SNEP request type is Get
// Returns the length of the received NDEF message
//why *& as argument?
uint32_t SNEP::transmitPutRequest(uint8_t *NDEFMessage, uint8_t length){
uint32_t result;
//Opening link to server.
result = _linkLayer->openLinkToServer(true);
//if data-link was succesfully established continue, else abort.
if(RESULT_OK(result)){
//Build SNEP frame
SNEP_PDU *snepRequest = (SNEP_PDU *) ALLOCATE_HEADER_SPACE(NDEFMessage, SNEP_PDU_HEADER_LEN);
snepRequest -> version = SNEP_SUPPORTED_VERSION;
snepRequest -> type = SNEP_PUT_REQUEST;
snepRequest -> length = 0x0000 + length;
//caller must check the result
result = _linkLayer -> transmitToServer((uint8_t *)snepRequest, length + SNEP_PDU_HEADER_LEN, true);
}
return result;
}
// Receives a SNEP response from the server. A link must have been established before this function is called
// Arguments: data will be set to point to the received NDEF message
// responseType is the response type of the received NDEF message
// Returns the length of the received NDEF message
uint32_t SNEP::receiveResponse(uint8_t *&data){
uint32_t result = _linkLayer->receiveFromClient(data,true);
if(RESULT_OK(result)){
if(data[0] != SNEP_SUPPORTED_VERSION){
Serial.print(F("SNEP>receiveData: Recieved an SNEP message of an unsupported version: "));
Serial.println(data[0]);
return SNEP_UNSUPPORTED_VERSION;
}
if(data[1] == SNEP_SUCCESS){
_linkLayer -> closeLinkToServer();
return 0; //in all other cases there is no information present, return 0.
}else //In case of Reject or Continue
return SNEP_UNEXPECTED_RESPONSE;
}
return result; //error code from receiveFromClient
}
/*
SNEP_PDU::SNEP_PDU{
parameters[0] = 0;
parameters[1] = 0;
parameters[2] = 0;
parameters[3] = 0;
parameters[4] = 0;
parameters[5] = 0;
}
uint8_t SNEP_PDU:: set*/
| true |
2de5defe31c4263c00c2ef0b9067b58b5bb4a191 | C++ | rmiya56/TakeALook | /areaselectpixmap/areaselectpixmapitem.cpp | UTF-8 | 2,289 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "areaselectpixmapitem.h"
#include "../utility/mouseeventutil.h"
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
AreaSelectPixmapItem::AreaSelectPixmapItem()
: QGraphicsPixmapItem()
{
}
AreaSelectPixmapItem::AreaSelectPixmapItem(QImage image)
: AreaSelectPixmapItem::AreaSelectPixmapItem()
{
setImage(image);
}
void AreaSelectPixmapItem::setImage(QImage image)
{
setPixmap(QPixmap::fromImage(image));
}
QRect AreaSelectPixmapItem::areaRect()
{
if (areaSelectItem)
return areaSelectItem->toQRect();
else
return pixmap().rect();
}
void AreaSelectPixmapItem::clearAreaRect()
{
if (areaSelectItem)
{
delete areaSelectItem;
areaSelectItem = nullptr;
}
}
void AreaSelectPixmapItem::cropAreaRect()
{
QPixmap cropped = pixmap().copy(areaRect());
setPixmap(cropped);
setPos(pos() + areaRect().topLeft());
clearAreaRect();
}
void AreaSelectPixmapItem::setDragSelect(bool is_active)
{
area_selection_is_active = is_active;
}
void AreaSelectPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "press (pixmap)";
clearAreaRect();
if(!area_selection_is_active) return;
if (event->button() == Qt::LeftButton)
{
initLeftButtonPos = event->pos();
expandingRect = new ExpandingRectItem(QRectF(initLeftButtonPos, initLeftButtonPos), this);
}
else // Right button
{
initLeftButtonPos = QPointF();
}
//QGraphicsPixmapItem::mousePressEvent(event);
}
void AreaSelectPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(!area_selection_is_active) return;
if (!initLeftButtonPos.isNull())
expandingRect->setRect(QRectF(initLeftButtonPos, event->pos()));
}
void AreaSelectPixmapItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "release (pixmap)";
QGraphicsPixmapItem::mouseReleaseEvent(event);
if(!area_selection_is_active) return;
if(event->button() == Qt::LeftButton)
{
if (!expandingRect) return;
if (!MouseEventUtil::isValidDragMove(initLeftButtonPos, event->pos())) return;
areaSelectItem = new AreaSelectItem(expandingRect->rect(), this);
delete expandingRect;
expandingRect = nullptr;
}
}
| true |
cd80d2e8974009cd6764b9ba1a85f4b6e75c55ad | C++ | martonantoni/pixie | /include/pixie/system/FormatThousands.h | UTF-8 | 982 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
inline std::string FormatThousands(int Value)
{
if(Value>=0)
return Value<1000?fmt::sprintf("%d",Value):Value<1000000?fmt::sprintf("%d,%.03d",Value/1000,Value%1000):fmt::sprintf("%d,%.03d,%.03d",Value/1000000,(Value/1000)%1000,Value%1000);
else
{
int AbsValue=std::abs(Value);
return AbsValue<1000?fmt::sprintf("-%d",AbsValue):AbsValue<1000000?fmt::sprintf("-%d,%.03d",AbsValue/1000,AbsValue%1000):fmt::sprintf("-%d,%.03d,%.03d",AbsValue/1000000,(AbsValue/1000)%1000,AbsValue%1000);
}
}
inline std::string FormatThousands64(__int64 Value)
{
if(!Value)
return "0";
__int64 AbsValue=Abs(Value);
std::string Result;
for(;;)
{
__int64 NextAbsValue=AbsValue/1000;
if(NextAbsValue)
Result=fmt::sprintf("%03d",AbsValue%1000)+(Result.length()?","+Result:Result);
else
{
Result=fmt::sprintf("%d",AbsValue%1000)+(Result.length()?","+Result:Result);
break;
}
AbsValue=NextAbsValue;
}
return Value>=0?Result:fmt::sprintf("-%s",Result);
}
| true |
b98e9061d8df9b8072d0fc33778e8ab596037b7a | C++ | green-fox-academy/GerBer1234 | /week-01/day-2/coding_hours/main.cpp | UTF-8 | 269 | 2.703125 | 3 | [] | no_license | #include <iostream>
int main(int argc, char* args[]) {
std::cout << "A Green Fox attendee codes about " << 17*5*6 << " hours in a semester." << std::endl;
std::cout << ((17.*5*6)/(17*52))*100 << "% coding hours in the semester." << std::endl;
return 0;
} | true |
0a20aff5c82832ad7c3143138eb04c089687b48a | C++ | Anirgb00/gfg-Covid-codes | /gfgtesting.cpp | UTF-8 | 430 | 2.734375 | 3 | [] | no_license | int a[1001];
int cnt=0;
int check(int a[],int cnt){
int flag = 0;
for(int i=0;i<cnt-1;i++){
if(a[i] >= a[i+1]){
flag = 1;
break; }
}
if(flag == 0) return 1;
else if(flag == 1) return 0;
}
int cnt = 0;
bool isBST(Node* root) {
// Your code here
isBST(root->left);
a[cnt++] = root->data;
isBST(root->right);
if(check(n,cnt) == 0) return false;
else return true;
}
| true |
1a3f93751886d9adc10f78b32d4cdea8f7d07fd6 | C++ | JackZhouSz/ebpd_vs2015 | /PCM/qt_gui/toolbars/animesh_enum.hpp | UTF-8 | 4,409 | 2.640625 | 3 | [] | no_license | #ifndef ANIMATED_MESH_ENUM_HPP__
#define ANIMATED_MESH_ENUM_HPP__
/// @brief Enumerants used by Animesh
// =============================================================================
namespace EAnimesh {
// =============================================================================
/// Define some flags corresponding to different cases a vertex is in when
/// fitted into the implicit surfaces with the gradient march.
/// This helps to see what is happening.
enum Vert_state {
POTENTIAL_PIT, ///< the vertex is going away from its base potential
GRADIENT_DIVERGENCE, ///< collision detected
NB_ITER_MAX, ///< stopped before reaching base potential because the surface is too far
NOT_DISPLACED, ///< The vertex is already on the right iso-surface
FITTED, ///< The vertex has been succesfully fitted on its base potential
OUT_VERT, ///< Vertex starts inside another surface than its own
NORM_GRAD_NULL, ///< Gradient norm is null can't set a proper marching direction
PLANE_CULLING,
CROSS_PROD_CULLING,
// Always keep this at the end ------------------------
NB_CASES
};
// -----------------------------------------------------------------------------
/// Different Possibilities to compute the vertex color of the animesh
enum Color_type {
CLUSTER, ///< Color different by bone cluster
NEAREST_JOINT, ///< Color different by joint cluster
BASE_POTENTIAL, ///< Color based on the potential
GRAD_POTENTIAL, ///< The current gradient potential of the vertex
SSD_INTERPOLATION, ///< Color based on the ssd interpolation factor
SMOOTHING_WEIGHTS, ///< Color based on the smoothing weights
ANIM_SMOOTH_LAPLACIAN, ///< Color based on the animated smoothing weights
ANIM_SMOOTH_CONSERVATIVE, ///< Color based on the animated smoothing weights
NORMAL, ///< Color based on mesh current animated normals
USER_DEFINED, ///< Uniform color defined by user
SSD_WEIGHTS, ///< SSD weights are painted on the mesh
VERTICES_STATE, ///< Color based on the stop case encounter while fitting @see EAnimesh::Vert_state
MVC_SUM, ///< Color mean value coordinates sum at each vertex
FREE_VERTICES, ///< Distinguish vertices deformed by non linear energy from others (rigidly transformed)
EDGE_STRESS, ///< Color vertices with average edges streching/compression from rest pose
AREA_STRESS, ///< Color vertices with average tris areas streching/compression from rest pose
GAUSS_CURV, ///< Color vertices with gaussian curvature
DISPLACEMENT ///< binnary Color for vertex moved previously by the deformation algorithm
};
// -----------------------------------------------------------------------------
enum Smooth_type {
LAPLACIAN, ///< Based on the centroid of the first ring neighborhood
CONSERVATIVE, ///< Try to minimize changes with the rest position
TANGENTIAL, ///< Laplacian corrected with the mesh normals
HUMPHREY ///< Laplacian corrected with original points position
};
// -----------------------------------------------------------------------------
/// Geometric deformations mode of the vertices
enum Blending_type {
DUAL_QUAT_BLENDING = 0, ///< Vertices are deformed with dual quaternions
MATRIX_BLENDING, ///< Vertices are deformed with the standard SSD
RIGID ///< Vertices follows rigidely the nearest bone
};
// -----------------------------------------------------------------------------
enum Cluster_type {
/// Clusterize the mesh computing the euclidean dist to each bone
EUCLIDEAN,
/// Use bone weights to define the clusters. A vertex will be associated to
/// highest bone weight influence.
FROM_WEIGHTS
};
// -----------------------------------------------------------------------------
/// Painting modes for the different mesh attributes
enum Paint_type {
PT_SSD_INTERPOLATION,
PT_SSD_WEIGHTS,
PT_CLUSTER
};
// -----------------------------------------------------------------------------
}
// END EAnimesh NAMESPACE ======================================================
#endif // ANIMATED_MESH_ENUM_HPP__
| true |
be23de9458669b2455c4416cbd4b0779349e4506 | C++ | cwlseu/Algorithm | /leetcode/leetCode_power_of_three.cpp | UTF-8 | 388 | 2.953125 | 3 | [] | no_license | #include <climits>
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && ((int)pow(3, (int)(log(INT_MAX)/log(3))) % n == 0);
}
};
int main(int argc, char const *argv[])
{
Solution solve;
std::cout << solve.isPowerOfThree(100);
cout<< solve.isPowerOfThree(81);
return 0;
} | true |
29244c8cd0345c57818b929b83e08128aff0d67f | C++ | NetBurner/MobileControlledLedStrip | /ledStrip.cpp | UTF-8 | 21,305 | 2.578125 | 3 | [] | no_license | #include "ledStrip.h"
#include <constants.h>
#include <HiResTimer.h>
#include <stdio.h>
#include <stdlib.h>
#include "spiInterface.h"
extern SpiInterface *gSpi;
HiResTimer* hrTimer = nullptr;
LedStrip::LedStrip()
{
}
bool LedStrip::InitializeLedStrip()
{
if( gSpi == nullptr )
{
iprintf( "Unable to initialize LED strip, SPI interface is unavailable.\r\n" );
return false;
}
gSpi->WriteSpi( m_clearBits, 2 ); // Send the first two clear bytes
m_setColor.SetLedValues( double( 0.5 ), double( 0.5 ), double( 0.5 ) );
return true;
}
void LedStrip::SetLedValues( int i, uint8_t r, uint8_t g, uint8_t b )
{
if( i < 0 || i > gLedCount )
{
iprintf( "SetLed: Index outside of led range %d\r\n", i );
return;
}
m_ledStrip[ i ].SetLedValues( r, g, b );
}
void LedStrip::SetLedValues( int i, double r, double g, double b )
{
if( i < 0 || i > gLedCount )
{
iprintf( "SetLed: Index outside of led range %d\r\n", i );
return;
}
m_ledStrip[ i ].SetLedValues( r, g, b );
}
void LedStrip::SetActiveColor( uint8_t r, uint8_t g, uint8_t b )
{
m_setColor.SetLedValues( r, g, b );
m_colorChanged = true;
//iprintf( "Active Color set to %d %d %d\r\n", m_setColor.GetRed(), m_setColor.GetGreen(), m_setColor.GetBlue() );
}
void LedStrip::SetActiveColor( double r, double g, double b )
{
m_setColor.SetLedValues( r, g, b );
m_colorChanged = true;
//printf( "Active Color set to %f %f %f\r\n", m_setColor.GetRedD(), m_setColor.GetGreenD(), m_setColor.GetBlueD() );
}
void LedStrip::GetLedValues( int i, uint8_t( &v )[ 3 ] )
{
if( i < 0 || i > gLedCount )
{
iprintf( "GetLedValues: Index outside of led range %d\r\n", i );
return;
}
v[ 0 ] = m_ledStrip[ i ].GetRed();
v[ 1 ] = m_ledStrip[ i ].GetGreen();
v[ 2 ] = m_ledStrip[ i ].GetBlue();
}
void LedStrip::SetCurVis( LedVis v )
{
m_reset = true;
m_currentVisual = v;
}
void LedStrip::ClearLeds()
{
// Write color bits
for( int i = 0; i < gLedCount; i++ )
{
m_ledStrip[ i ].SetLedValues( uint8_t( 0 ), uint8_t( 0 ), uint8_t( 0 ) );
}
WriteLeds();
//OSTimeDly( 1 );
}
void LedStrip::WriteLeds()
{
// Write color bits
for( int i = 0; i < gLedCount; i++ )
{
m_ledStrip[ i ].WriteLedValues();
}
// Write clear bits
//iprintf( "Writing clear bit\r\n" );
gSpi->WriteSpi( m_clearBits, 2 ); // Have to send one final byte to latch the last byte
//OSTimeDly( 1 );
}
void LedStrip::PlayKnightRiderAnim()
{
iprintf( "Starting KnightRiderAnim\r\n" );
int activeIndex = 0;
bool inc = true;
while( m_currentVisual == eLedVisKnightRider && !m_reset )
{
for( int i = inc ? 0 : gLedCount - 1;
inc ? i < gLedCount : i >= 0;
inc ? i++ : i-- )
{
int step = ( ( activeIndex - i ) > 0 ) ? ( activeIndex - i ) : ( i - activeIndex );
double stepVal = step * .25;
uint8_t actColRed = m_setColor.GetRed();
uint8_t actColGreen = m_setColor.GetGreen();
uint8_t actColBlue = m_setColor.GetBlue();
// If the led is close enough to the active led and has a high enough color value, reduce it, otherwise
// just turn it off.
if( actColRed != 0 )
{
actColRed = ( ( actColRed > stepVal ) && ( step <= 3 ) ) ? uint8_t( actColRed - ( actColRed * stepVal ) ) : 0;
}
if( actColGreen != 0 )
{
actColGreen = ( ( actColGreen > stepVal ) && ( step <= 3 ) ) ? uint8_t( actColGreen - ( actColGreen * stepVal ) ) : 0;
}
if( actColBlue != 0 )
{
actColBlue = ( ( actColBlue > stepVal ) && ( step <= 3 ) ) ? uint8_t( actColBlue - ( actColBlue * stepVal ) ) : 0;
}
m_ledStrip[ i ].SetLedValues( actColRed, actColGreen, actColBlue );
}
WriteLeds();
// Delay so we can process we posts
OSTimeDly( 1 );
if( (activeIndex == 0 && !inc) || (activeIndex == 63 && inc) )
{
inc = !inc;
}
activeIndex = inc ? activeIndex + 1 : activeIndex - 1;
}
iprintf( "Leaving knight rider\r\n" );
m_reset = false;
}
void LedStrip::PlayTwinkle()
{
uint32_t activeLowInc = 0;
uint32_t activeHighInc = 0;
uint32_t activeLowDec = 0;
uint32_t activeHighDec = 0;
uint32_t spawnCount = 0;
uint32_t maxAge = 0;
bool changeRed = false;
bool changeGreen = false;
bool changeBlue = false;
double redMod = 0.0;
double greenMod = 0.0;
double blueMod = 0.0;
m_colorChanged = true;
ClearLeds();
while( m_currentVisual == eLedVisTwinkle && !m_reset )
{
// If the set color has changed, then we need to compute all of these values
if( m_colorChanged )
{
maxAge = m_setColor.GetRed() + m_setColor.GetGreen() + m_setColor.GetBlue() + 1;
// Put restrictions on the maxage so it isn't too short or too long
maxAge = (maxAge < 100) ? 100 : maxAge;
maxAge = (maxAge > 250) ? 250 : maxAge;
changeRed = m_setColor.GetRed() != 0;
changeGreen = m_setColor.GetGreen() != 0;
changeBlue = m_setColor.GetBlue() != 0;
redMod = changeRed ? m_setColor.GetRedD() * .5 : 0.0;
greenMod = changeGreen ? m_setColor.GetGreenD() * .5 : 0.0;
blueMod = changeBlue ? m_setColor.GetBlueD() * .5 : 0.0;
while( greenMod > 0.01 || redMod > 0.01 || blueMod > 0.01 )
{
greenMod *= 0.5;
redMod *= 0.5;
blueMod *= 0.5;
}
m_colorChanged = false;
}
// Find next twinkle start index
int spawned = 0;
// Don't spawn more than 48 at any given time, and no more than 5 in one cycle
while( ( spawnCount < 48 ) && ( spawned < 5 ) )
{
bool foundSpawn = false;
int spawnInd = rand() % 64;
// Don't reset LED that are in the process of decrementing
if( ( spawnInd < 32 ) &&
( ( activeLowInc & ( 1 << spawnInd ) ) == 0) &&
( ( activeLowDec & ( 1 << spawnInd ) ) == 0) )
{
activeLowInc |= (1 << spawnInd);
foundSpawn = true;
}
else if( ( spawnInd >= 32 ) &&
( ( activeHighInc & ( 1 << ( spawnInd % 32 ) ) ) == 0 ) &&
( ( activeHighDec & ( 1 << ( spawnInd % 32 ) ) ) == 0 ) )
{
activeHighInc |= ( 1 << ( spawnInd % 32 ) );
foundSpawn = true;
}
else
{
spawnInd = rand() % 64;
}
if( foundSpawn )
{
// Set the base color
m_ledStrip[ spawnInd ].SetLedValues( uint8_t( 0 ), uint8_t( 0 ), uint8_t( 0 ) );
// Ensure we at least get 10
uint32_t curMaxAge = ( rand() % ( maxAge - 10 ) ) + 10;
// This is just to cut way down on the max age, which gives a nicer affect
double ageScaled = ( curMaxAge * ( double( ( rand() % 91 ) + 10 ) / 100.0 ) );
m_ledStrip[ spawnInd ].SetMaxAge( uint32_t( ageScaled ) + 1 );
spawnCount++;
spawned++;
}
}
// Increment and decrement set twinkles as needed
for( int i = 0; i < gLedCount; i++ )
{
bool inc = false;
bool dec = false;
if( ( i < 32 ) ? activeLowInc & ( 1 << i ) : activeHighInc & ( 1 << ( i % 32 ) ) )
{
inc = true;
}
// Decrement color
else if( ( i < 32 ) ? activeLowDec & ( 1 << i ) : activeHighDec & ( 1 << ( i % 32 ) ) )
{
dec = true;
}
// These values are used to determine how long a light should be on, and how fast it should inc and dec
uint32_t curAge = m_ledStrip[ i ].GetRed() + m_ledStrip[ i ].GetGreen() + m_ledStrip[ i ].GetBlue();
double modScale = ( inc || dec ) ? ( curAge / double( m_ledStrip[ i ].GetMaxAge() ) ) * 2.0 : 0.0;
if( inc )
{
m_ledStrip[ i ].SetLedValues( changeRed ? m_ledStrip[ i ].GetRedD() + redMod + ( redMod * modScale ) : double( 0 ),
changeGreen ? m_ledStrip[ i ].GetGreenD() + greenMod + ( greenMod * modScale ) : double( 0 ),
changeBlue ? m_ledStrip[ i ].GetBlueD() + blueMod + ( blueMod * modScale ) : double( 0 ) );
// Move lights that have hit the peak from inc to dec
bool ledIsMax = ( changeRed && ( m_ledStrip[ i ].GetRed() >= m_setColor.GetRed() ) ) ||
( changeGreen && ( m_ledStrip[ i ].GetGreen() >= m_setColor.GetGreen() ) ) ||
( changeBlue && ( m_ledStrip[ i ].GetBlue() >= m_setColor.GetBlue() ) );
if( ledIsMax || ( m_ledStrip[ i ].GetMaxAge() < curAge ) )
{
if( i < 32 )
{
activeLowInc &= ~( 1 << i );
activeLowDec |= ( 1 << i );
}
else
{
activeHighInc &= ~( 1 << ( i % 32 ) );
activeHighDec |= ( 1 << ( i % 32 ) );
}
}
}
else if( dec )
{
m_ledStrip[ i ].SetLedValues( changeRed ? double( m_ledStrip[ i ].GetRedD() - redMod - ( redMod * modScale ) ) : double( 0 ),
changeGreen ? double( m_ledStrip[ i ].GetGreenD() - greenMod - ( greenMod * modScale ) ) : double( 0 ),
changeBlue ? double( m_ledStrip[ i ].GetBlueD() - blueMod - ( blueMod * modScale ) ) : double( 0 ) );
// Remove lights that have finished dec
bool ledIsBase = ( m_ledStrip[ i ].GetRed() <= 0 ) &&
( m_ledStrip[ i ].GetGreen() <= 0 ) &&
( m_ledStrip[ i ].GetBlue() <= 0 ) ;
if( ledIsBase )
{
if( i < 32 )
{
activeLowDec &= ~( 1 << i );
}
else
{
activeHighDec &= ~( 1 << ( i % 32 ) );
}
// Turn off if we have hit the base
m_ledStrip[ i ].SetLedValues( uint8_t( 0 ), uint8_t( 0 ), uint8_t( 0 ) );
spawnCount--;
}
}
else
{
m_ledStrip[ i ].SetLedValues( uint8_t( 0 ), uint8_t( 0 ), uint8_t( 0 ) );
}
}
WriteLeds();
OSTimeDly( 1 );
}
m_reset = false;
}
void LedStrip::PlayBitCounter()
{
uint32_t lowRange = 1;
uint32_t highRange = 0;
uint32_t bitTest = 0;
while( m_currentVisual == eLedVisBitCounter && !m_reset )
{
for( int i = 0; i < gLedCount; i++ )
{
bitTest = 1 << ( i % 32 );
bool setBit = ( ( i < 32 ) && ( bitTest & lowRange ) ) ||
( ( i >= 32 ) && ( bitTest & highRange ) );
if( setBit )
{
m_ledStrip[ gLedCount - i - 1 ].SetLedValues( m_setColor );
}
else
{
m_ledStrip[ gLedCount - i - 1 ].SetLedValues( uint8_t( 0 ), uint8_t( 0 ), uint8_t( 0 ) );
}
}
lowRange++;
// If we have gone through the low range, add one to our high range counter
if( lowRange == 0 )
{
highRange++;
}
WriteLeds();
// Delay so we can process we posts
OSTimeDly( 5 );
}
m_reset = false;
}
void LedStrip::PlayColorWave()
{
uint32_t curIndex = 0;
uint32_t curIndex2 = 38;
Led curColor;
Led curColor2;
while( m_currentVisual == eLedVisColorWave && !m_reset )
{
// If we are at the beginning, set the color
if( curIndex == 0 )
{
curColor.SetLedValues( uint8_t( rand() % 64 ), uint8_t( rand() % 64 ), uint8_t( rand() % 64 ) );
}
if( curIndex2 == 0 )
{
curColor2.SetLedValues( uint8_t( rand() % 64 ), uint8_t( rand() % 64 ), uint8_t( rand() % 64 ) );
}
bool curIndHigh = curIndex > curIndex2;
for( uint32_t i = 0; i < gLedCount; i++ )
{
bool useCurInd = false;
bool useCurInd2 = false;
if( curIndHigh && i <= curIndex2 )
{
useCurInd2 = true;
}
else if( curIndHigh && i <= curIndex )
{
useCurInd = true;
}
else if( !curIndHigh && i <= curIndex )
{
useCurInd = true;
}
else if( !curIndHigh && i <= curIndex2 )
{
useCurInd2 = true;
}
if( useCurInd )
{
uint32_t scaleIndex = ( ( curIndex - i ) < 9 ) ? curIndex - i : 9;
double colorScale = scaleIndex / double( 10.0 );
double newRed = curColor.GetRedD() - ( curColor.GetRedD() * colorScale );
double newGreen = curColor.GetGreenD() - ( curColor.GetGreenD() * colorScale );
double newBlue = curColor.GetBlueD() - ( curColor.GetBlueD() * colorScale );
m_ledStrip[ i ].SetLedValues( newRed, newGreen, newBlue );
}
else if( useCurInd2 )
{
uint32_t scaleIndex = ((curIndex2 - i) < 9) ? curIndex2 - i : 9;
double colorScale = scaleIndex / double( 10.0 );
double newRed = curColor2.GetRedD() - (curColor2.GetRedD() * colorScale);
double newGreen = curColor2.GetGreenD() - (curColor2.GetGreenD() * colorScale);
double newBlue = curColor2.GetBlueD() - (curColor2.GetBlueD() * colorScale);
m_ledStrip[ i ].SetLedValues( newRed, newGreen, newBlue );
}
}
curIndex = ( curIndex + 1 ) % ( gLedCount + 10 );
curIndex2 = ( curIndex2 + 1) % ( gLedCount + 10 );
WriteLeds();
OSTimeDly( 1 );
}
m_reset = false;
}
void LedStrip::PlayPulse()
{
ClearLeds();
bool changeRed = false;
bool changeGreen = false;
bool changeBlue = false;
double redMod = 0.0;
double greenMod = 0.0;
double blueMod = 0.0;
bool inc = true;
double step = 0.5;
m_colorChanged = true;
while( m_currentVisual == eLedVisPulse && !m_reset )
{
if( m_colorChanged )
{
changeRed = m_setColor.GetRed() != 0;
changeGreen = m_setColor.GetGreen() != 0;
changeBlue = m_setColor.GetBlue() != 0;
redMod = changeRed ? m_setColor.GetRedD() * .025 : 0.0;
greenMod = changeGreen ? m_setColor.GetGreenD() * .025 : 0.0;
blueMod = changeBlue ? m_setColor.GetBlueD() * .025 : 0.0;
m_colorChanged = false;
}
bool setLongDelay = false;
// Increment and decrement as needed
for( int i = 0; i < gLedCount; i++ )
{
// These values are used to determine how long a light should be on, and how fast it should inc and dec
if( inc )
{
m_ledStrip[ i ].SetLedValues( changeRed ? m_ledStrip[ i ].GetRedD() + redMod + ( redMod * step ) : double( 0 ),
changeGreen ? m_ledStrip[ i ].GetGreenD() + greenMod + ( greenMod * step ) : double( 0 ),
changeBlue ? m_ledStrip[ i ].GetBlueD() + blueMod + ( blueMod * step ) : double( 0 ) );
}
else
{
m_ledStrip[ i ].SetLedValues( changeRed ? double( m_ledStrip[ i ].GetRedD() - redMod - ( redMod * step ) ) : double( 0 ),
changeGreen ? double( m_ledStrip[ i ].GetGreenD() - greenMod - ( greenMod * step ) ) : double( 0 ),
changeBlue ? double( m_ledStrip[ i ].GetBlueD() - blueMod - ( blueMod * step ) ) : double( 0 ) );
}
}
if( inc )
{
// Move lights that have hit the peak from inc to dec
bool ledIsMax = (changeRed && (m_ledStrip[ 0 ].GetRed() >= m_setColor.GetRed())) ||
(changeGreen && (m_ledStrip[ 0 ].GetGreen() >= m_setColor.GetGreen())) ||
(changeBlue && (m_ledStrip[ 0 ].GetBlue() >= m_setColor.GetBlue()));
step += 0.5;
if( ledIsMax )
{
inc = false;
}
}
else
{
bool ledIsBase = (m_ledStrip[ 0 ].GetRed() <= 0) &&
(m_ledStrip[ 0 ].GetGreen() <= 0) &&
(m_ledStrip[ 0 ].GetBlue() <= 0);
step -= 0.5;
if( ledIsBase )
{
inc = true;
setLongDelay = true;
}
}
WriteLeds();
OSTimeDly( setLongDelay ? 5 : 1 );
}
m_reset = false;
}
void LedStrip::PlayColorChange()
{
ClearLeds();
Led changeColor1;
Led changeColor2;
double redDif = 0.0;
double greenDif = 0.0;
double blueDif = 0.0;
uint32_t center = gLedCount / 2;
bool evenLedCount = ( gLedCount % 2 ) == 0;
uint32_t step = 0;
bool setLongDelay = false;
bool inc = true;
while( m_currentVisual == eLedVisColorChange && !m_reset )
{
if( step == 0 )
{
changeColor1.SetLedValues( uint8_t( rand() % 128 ), uint8_t( rand() % 128 ), uint8_t( rand() % 128 ) );
do
{
changeColor2.SetLedValues( uint8_t( rand() % 128 ), uint8_t( rand() % 128 ), uint8_t( rand() % 128 ) );
redDif = changeColor1.GetRedD() - changeColor2.GetRedD();
greenDif = changeColor1.GetGreenD() - changeColor2.GetGreenD();
blueDif = changeColor1.GetBlueD() - changeColor2.GetBlueD();
} while( ( ( redDif < 0 ? -1 * redDif : redDif ) < 0.5 ) &&
( ( greenDif < 0 ? -1 * greenDif : greenDif ) < 0.5 ) &&
( ( blueDif < 0 ? -1 * blueDif : blueDif ) < 0.5 ) );
setLongDelay = false;
}
for( uint32_t i = 0; i < gLedCount; i++ )
{
uint32_t distFromSource = 0;
// This is a modifier so that we can get both of the middle LEDs in strips with an even number
uint32_t distMod = evenLedCount ? 1 : 0;
if( inc )
{
// Distance from center
distFromSource = ( i <= center - distMod ) ? ( center - distMod ) - i : i - center;
}
else
{
// Distance from closest end
distFromSource = ( i <= center - distMod ) ? i : ( gLedCount - distMod ) - i;
}
if( distFromSource <= step )
{
double newRed = changeColor2.GetRedD() + ( redDif * ( distFromSource / double( center ) ) );
double newGreen = changeColor2.GetGreenD() + ( greenDif * ( distFromSource / double( center ) ) );
double newBlue = changeColor2.GetBlueD() + ( blueDif * ( distFromSource / double( center ) ) );
m_ledStrip[ i ].SetLedValues( newRed, newGreen, newBlue );
}
}
step = ( step + 1 ) % ( gLedCount / 2 );
if( step == 0 )
{
setLongDelay = true;
inc = !inc;
}
WriteLeds();
OSTimeDly( setLongDelay ? 5 : 1 );
}
m_reset = false;
}
void LedStrip::Main()
{
while( 1 )
{
switch( m_currentVisual )
{
case eLedVisDefault:
{
m_reset = false;
WriteLeds();
break;
}
case eLedVisKnightRider:
{
PlayKnightRiderAnim();
break;
}
case eLedVisTwinkle:
{
PlayTwinkle();
break;
}
case eLedVisBitCounter:
{
PlayBitCounter();
break;
}
case eLedVisColorWave:
{
PlayColorWave();
break;
}
case eLedVisPulse:
{
PlayPulse();
break;
}
case eLedVisColorChange:
{
PlayColorChange();
break;
}
case eLedVisNone:
default:
{
break;
}
}
OSTimeDly( TICKS_PER_SECOND / 2 );
}
}
| true |
15fe70505718a4091511a6b4820f30dc20217675 | C++ | wspeed0711/cfile | /P/1288.cpp | UTF-8 | 568 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int n, a[ 50 ];
scanf( "%d", &n );
for( int i = 0; i < n; i ++ )
{
scanf( "%d", &a[ i ] );
}
int step1 = 0;
for( int i = 0; i < n; i ++ )
{
if( a[ i ] == 0 )
{
break;
}
step1 ++;
}
int step2 = 0;
for( int i = n - 1; i >= 0; i -- )
{
if( a[ i ] == 0 )
{
break;
}
step2 ++;
}
if( ( step1 & 1 ) == 1 || ( step2 & 1 ) == 1 )
{
printf( "YES\n" );
}
else{
printf( "NO\n" );
}
return 0;
}
| true |
25cc2a772a1d6c2fc977b03501f10270e739cab7 | C++ | pal-0123/Competitive-Database | /CodeChef/ANWCC02.cpp | UTF-8 | 671 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("output.txt", "w", stdout);
#endif
int n,m;
cin >> n >> m;
int i,j;
int c[n];
int km[m];
for (i=0;i<n;i++){
cin >> c[i];
}
for (i=0;i<m;i++){
cin >> km[i];
}
int ans=0;
if (n==m){
for (i=0;i<n;i++){
ans+=c[i]*km[i];
}
cout << ans << "\n";
}
else {
int temp=0;
for (i=0;i<n-m+1;i++){
temp=0;
for (j=0;j<m;j++){
temp+=c[i+j]*km[j];
}
if (temp>ans){
ans=temp;
}
}
cout << ans << "\n";
}
return 0;
} | true |
2a14ca120cbec73201ddd63fd9a73110e382bfa9 | C++ | jcarvajal288/RLEngine | /src/Party.hpp | UTF-8 | 1,830 | 3.390625 | 3 | [] | no_license | #ifndef RLNS_PARTY_HPP
#define RLNS_PARTY_HPP
#include "Actor.hpp"
#include <vector>
namespace rlns
{
/*--------------------------------------------------------------------------------
Class : Party
Description : Groups Actors together into a unit that fights together. The
player's party is one of these, but monsters are also grouped
and spawned as parties.
Parents : None
Children : None
Friends : None
--------------------------------------------------------------------------------*/
class Party
{
// Member Variables
private:
std::vector<ActorPtr> members;
// If this is the player's party, the leader is the member that the player
// is currently controlling. If it's a monster party, this is the member
// that all the other members follow.
size_t leader;
// Static Members
private:
static PartyPtr playerParty;
// Member Functions
public:
Party(): leader(0) {}
Party(std::vector<ActorPtr> m)
: members(m), leader(0) {}
ActorPtr getLeader() const { return members.at(leader); }
void setLeader(const size_t l) { leader = l; }
void addMember(const ActorPtr);
std::vector<ActorPtr> getMembers() const;
void moveLeader(const DirectionType);
// Static Functions
static PartyPtr getPlayerParty() { return playerParty; }
};
// Inline Functions
inline void Party::addMember(const ActorPtr actor)
{
members.push_back(actor);
}
inline std::vector<ActorPtr> Party::getMembers() const
{
return members;
}
}
#endif
| true |
0fbf77e7491fa76ab93e1707492d923b39d17948 | C++ | anujinpurevdorj/gitlearn | /2019/1sar/1-8-hexademical.cpp | UTF-8 | 743 | 2.8125 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
inline char hexchar(int x) {
if (x < 10) return '0' + x;
return 'A' + x - 10;
}
int main(){
int n,m=2,i=1;
cin >> n;
while(n > m){
m = pow(2,i);
i ++;
}
i -=2;
int l = (i+1)/4;
if((i+1) % 2 != 0){
l ++;
}
int a[i+1],k=0;
char b[l];
for(int j = i; j >= 0; j --){
if(pow(2,j) <= n){
cout << 1;
a[k] = 1;
n -= pow(2,j);
}else{
cout << 0;
a[k]=0;
}
k ++;
}
cout << endl;
m = 0;
n = 0;
k = l-1;
for(int j = i; j >= 0 ; j --){
if(m < 4){
if(a[j] == 1){
n += pow(2,m);
}
m ++;
}else{
b[k] = hexchar(n);
m = 0;
n = 0;
k --;
j ++;
}
}
b[k] = hexchar(n);
for(k = 0; k < l; k ++){
cout << b[k] << " ";
}
}
| true |
2a66fbe922fbd600823a9164697932920e732650 | C++ | NikkiR97/Data-Structures-Code | /lib/lab05/src/queue.cpp | UTF-8 | 3,294 | 3.90625 | 4 | [] | no_license | //
// Created by Bryan on 9/30/2017.
//
#include "queue.h"
#include <iostream>
namespace lab5{
queue::queue() :head(nullptr),tail(nullptr),size(0){}
queue::queue(std::string &data) {
head=tail=new node(data);
size=1;
}
queue::queue(const queue &original) {
if (original.head!= nullptr) {
node *original_tmp = original.head;
node *tmp = head = new node(original_tmp->data);
original_tmp = original_tmp->next;
while (original_tmp != nullptr) {
tmp->next = new node(original_tmp->data);
tmp = tmp->next;
tail=tmp;
original_tmp = original_tmp->next;
}
}
}
queue::~queue() {
//step 1 create destructor similar to linked list
for(node*current=head, *next; current!= nullptr ; current=next )
{
next=current->next;
delete current;
}
}
queue &queue::operator=(const queue &RHS) {
if(this != &RHS)
{
if (head!= nullptr)
delete this;
if (RHS.head!= nullptr) {
node *RHS_tmp = RHS.head;
node *tmp = head = new node(RHS_tmp->data);
RHS_tmp = RHS_tmp->next;
while (RHS_tmp != nullptr) {
tmp->next=new node(RHS_tmp->data);
tmp=tmp->next;
tail=tmp;
RHS_tmp = RHS_tmp->next;
}
}
}
return *this;
}
bool queue::isEmpty() const {
return size==0;
}
unsigned queue::queueSize() const {
return size;
}
std::string queue::top() const {
//step 1 return top item of queue
return head -> data;
}
void queue::enqueue(std::string &data) {
//head and tail can be pointing to nothing
if (head == nullptr || tail == nullptr) {
head = tail = new node(data);
size++;
} else {
//step 1 create a new node
node *temp = new node(data); //temp is pointing to the address of the new node
//step 2 update next of node pointed to by tail with address of new node
tail->next = temp; //next will point to whatever address the temp is pointing
//step 3 update tail with address of new node
tail = temp;
//step 4 update size of stack variable
size++;
// make sure to check if head is pointing to something
//if (head->next != nullptr) {
//head = head->next;
//}
}
}
void queue::dequeue() {
//step 1 store address of current top node (pointed to by head) in a node*
if (head != nullptr || tail != nullptr) {
node *temp;
temp = head;
//step 2 update head with address of second node
head = head->next;
//step 3 delete node pointed to by address stored in step 1
delete temp;
//step 4 update size of stack variable
size--;
// make sure to check if head is pointing to something
}
}
void queue::printqueue(){
node *temp = head ;
int checker=0;
while(temp != nullptr){ //-> next
std::cout << temp -> data << " ";
temp = temp ->next;
checker=1;
}
std::cout << std::endl;
if(checker != 1) {
std::cout << "There are no nodes to print the contents of." << std::endl;
}
}
node* queue::returnHead(){
return head;
}
} | true |
ac46db298cf4964ed9b21daff912f7c762d8195b | C++ | lehuubao1810/CTDLGT | /Tree/main.cpp | UTF-8 | 3,687 | 3.5625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Node{
int key;
Node *left;
Node *right;
Node *parent;
};
struct Tree{
Node * root;
int NumberNode;
};
Node* createNode(int);
void InitTree(Tree &);
bool put(Node*,Tree &);
void TravelNLR(Node*);
void TravelLNR(Node*);
void TravelLRN(Node*);
Node * SearchTree(Node *root, int x);
Node * SearchTreeDQ(Node *root, int x);
void DeleteNode(Node *);
int NumberLeaf(Node *);
int HightTree(Node *);
int main()
{
Tree T;
InitTree(T);
Node *n;
//3, 17, 2,35,18,33,19
put(createNode(3),T);
put(createNode(17),T);
put(createNode(2),T);
put(createNode(35),T);
put(createNode(18),T);
put(createNode(33),T);
put(createNode(19),T);
cout<<"NLR-------\n";
TravelNLR(T.root);
cout<<"LNR-------\n";
TravelLNR(T.root);
cout<<"LRN-------\n";
TravelLRN(T.root);
// DeleteNode(SearchTree(T.root,33));
// cout<<"LRN-------\n";
// TravelLRN(T.root);
return 0;
}
Node* createNode(int k){
Node *n=new Node;
n->key=k;
n->left=NULL;
n->right=NULL;
n->parent=NULL;
return n;
}
void InitTree(Tree &T){
T.root=NULL;
T.NumberNode=0;
}
bool put(Node*n,Tree &T){
Node *p=T.root;
if(T.root==NULL){
T.root=n;
return true;
}
while((n->key>p->key&&p->right!=NULL)||(n->key<p->key&&p->left!=NULL)){
if(n->key==p->key)
return false;
else{
if(n->key>p->key)
p=p->right;
else
p=p->left;}
}
if(n->key>p->key)
p->right=n;
else
p->left=n;
n->parent=p;
return true;
}
void TravelNLR(Node *p){
if(p!=NULL){
cout<<p->key<<'\n';
TravelNLR(p->left);
TravelNLR(p->right);
}
}
void TravelLNR(Node *p){
if(p!=NULL){
TravelLNR(p->left);
cout<<p->key<<'\n';
TravelLNR(p->right);
}
}
void TravelLRN(Node *p){
if(p!=NULL){
TravelLRN(p->left);
TravelLRN(p->right);
cout<<p->key<<'\n';
}
}
Node * SearchTree(Node *root, int x){
Node *p=root;
while(p!=NULL){
if(p->key==x) return p;
if(p->key>x) p=p->left;
if(p->key<x) p=p->right;
}
return NULL;
}
Node * SearchTreeDQ(Node *root, int x){
Node* p=root;
if(p==NULL) return NULL;
else {
if(p->key==x) return root;
if(p->key>x) return SearchTreeDQ(p->left,x);
if(p->key<x) return SearchTreeDQ(p->right,x);
}
}
void DeleteNode(Node *p){
Node *q=NULL;
if(p->left==NULL&&p->right==NULL) // node la
delete p;
else {if(p->left==NULL&&p->right!=NULL) // 1 con phai
if(p->key>p->parent->key)
p->parent->right=p->right;
else p->parent->left=p->right;
if(p->left!=NULL&&p->right==NULL) // 1 con trai
if(p->key>p->parent->key)
p->parent->right=p->left;
else p->parent->left=p->left;
if(p->left!=NULL&&p->right!=NULL){ // no co 2 con
q=p->left;
while(q->right!=NULL)
q=q->right;
q->parent->right=q->left;
p->key=q->key;
p=q;
}
delete p;
}
}
int NumberLeaf(Node *root){
Node* p=root;
if(p==NULL) return 0;
if(p->left==NULL&&p->right==NULL)
return 1;
else return NumberLeaf(p->left)+NumberLeaf(p->right);
}
int HightTree(Node *root){
Node *p=root;
if(p==NULL) return -1;
if(p->left==NULL&&p->right==NULL)
return 0;
else { int T=HightTree(p->left);
int P=HightTree(p->right);
return T>P?T+1:P+1;
}
}
| true |
6aa138d95f8279e79cbdc823f04f389b0ca92472 | C++ | cassLaffan/CPP_ARAIG | /Final Project/Exoskeleton.cpp | UTF-8 | 616 | 3.0625 | 3 | [] | no_license | #include "Exoskeleton.h"
namespace finalProject{
Exoskeleton::Exoskeleton(std::string name, float intense, float timeVar){
//can't have intensity greater than 100%
if(intense <= 100.00 && intense >= 0 && timeVar >= 0){
stimulationName = name;
intensity = intense;
duration = timeVar;
}
else{
throw "Your numbers are off! exo";
}
}
void Exoskeleton::display(std::ostream& ostr) const{
ostr << " TYPE: " << stimulationName << std::endl;
ostr << " INTENSITY: " << intensity << std::endl;
ostr << " DURATION: " << duration << std::endl;
}
}
| true |
36a2dcdbc4390bfc2cd9df6d714682777c000ada | C++ | amirzhad/Awesomely-Complex-Machines-ACM- | /ACM1.cpp | UTF-8 | 3,053 | 3.1875 | 3 | [] | no_license | /*
Author:
Amir Zhad
2018-02-21
Description:
The director of Awesomely Complex Machines (ACM) whose task is to maximize the amount of money that ACM makes during the restructuring.
Source:
https://github.com/amirzhad/Awesomely-Complex-Machines-ACM-.git
Compile: (Ubuntu)
g++ -std=gnu++11 ACM1.cpp -o ACM1.exe
Run: (Windows)
ACM1.exe
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <strstream>
#include <ostream>
using namespace std;
ifstream input("input.txt");
long long N, C, D;
long long a[100000][4];
long long profit[100000];
int case_number = 0;
long long chosen_machine;
int read_case()
{
//reads each case and corresponding N C D and also the machines details to array a
string line;
input >> N >> C >> D;
for (long long i = 0; i < N; i++)
{
input >> a[i][0] >> a[i][1] >> a[i][2] >> a[i][3];
}
return 1;
}
int count_highest_profit()
{
//computes the primary highest profit based on the machines details and available dollars (C)
for (long long i = 0; i < N; i++)
{
if (C < a[i][1])
profit[i] = 0;
else
profit[i] = C - a[i][1] + a[i][2] + (D-a[i][0])*a[i][3];
}
return 1;
}
long long find_best_profit()
{
// finds the highest profit machine
long long max = 0;
long long max_index = -1;
for (long long i = 0; i < N; i++)
{
if (profit[i] > max)
{
max = profit[i];
max_index = i;
}
}
return max_index;
}
int coming_profit(long long current_machine_index)
{
long long buget = C - a[current_machine_index][1] + a[current_machine_index][2];
// computes the profit if we choose other machines
for (long long i = 0; i < N; i++)
{
if (a[i][0] <= a[current_machine_index][0])
{
continue;
}
if (((a[i][0] - a[current_machine_index][0] - 1)*a[current_machine_index][3] + buget) >= a[i][1]) // can we buy it?
{
profit[i] = (a[i][0] - a[current_machine_index][0] - 1)*a[current_machine_index][3] + buget + (D-a[i][0])*a[i][3] + a[i][2] - a[i][1];
}
}
return 1;
}
long long max_profit()
{
//finds the most accessable profit
if (N == 0 || chosen_machine==-1)
return C; //if there is not machine, we simply save the amout we have
long long max = 0;
for (long long i = 0; i < N; i++)
{
if (profit[i] > max)
max = profit[i];
}
if (C > max)
return C;
return max;
}
long long find_better()
{
long long buget = C - a[chosen_machine][1] + a[chosen_machine][2];
long long tmp;
for (long long i = 0; i < chosen_machine; i++)
{
tmp = C - a[i][1] + a[i][2] + (a[chosen_machine][0] - a[i][0])*a[chosen_machine][3];
if (tmp > max_profit())
profit[chosen_machine] = tmp;
}
return 1;
}
int main()
{
int exit_condition = 0;
while (!exit_condition)
{
read_case();
if (N == 0 && C == 0 && D == 0)
{
exit_condition = 1;
continue;
}
count_highest_profit();
chosen_machine = find_best_profit();
find_better();
coming_profit(chosen_machine);
cout << "Case " << ++case_number << ": " << max_profit() << "\n";
}
input.close();
cout << "Finished, please press Enter...";
getchar();
return 0;
}
| true |
905eda948c914a9e912e5dd1c3f9db4d4ea940fb | C++ | razzie/PotatoGame | /source/Potato.cpp | ISO-8859-2 | 1,766 | 2.53125 | 3 | [] | no_license | /*
* Copyright (C) Gbor Grzsny <gabor@gorzsony.com> - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*/
#include <Windows.h>
#include "Potato.hpp"
#include "Demo.hpp"
using namespace raz::literal;
static raz::MemoryPool<100_MB> render_thread_memory;
Potato::Settings::Settings(int argc, char** argv) :
screen_width(1366),
screen_height(768),
fullscreen(false),
render_distance(200.f)
{
}
Potato::Potato(int argc, char** argv) :
m_settings(argc, argv)
{
}
Potato::~Potato()
{
}
const Potato::Settings& Potato::getSettings() const
{
return m_settings;
}
raz::Thread<game::GameThread>& Potato::getGameThread()
{
return m_game_thread;
}
raz::Thread<gfx::RenderThread>& Potato::getRenderThread()
{
return m_render_thread;
}
int Potato::run()
{
auto exit_code_future = m_exit_code.get_future();
//superviseThread( m_game_thread.start(std::ref(*this), nullptr) );
superviseThread( m_render_thread.start(std::ref(*this), &render_thread_memory) );
raz::Thread<Demo> demo_thread;
superviseThread( demo_thread.start(std::ref(*this)) );
int exit_code = exit_code_future.get();
m_render_thread.stop();
m_game_thread.stop();
return exit_code;
}
void Potato::exit(int code, const char* msg)
{
if (msg)
{
MessageBoxA(NULL, msg, "Exit message", MB_OK);
}
m_exit_code.set_value(code);
}
void Potato::superviseThread(std::future<void> future)
{
auto supervisor = [](Potato* potato, std::shared_future<void> future) -> void
{
try
{
future.get();
}
catch (std::future_error&)
{
}
catch (std::exception& e)
{
potato->exit(-1, e.what());
return;
}
//potato->exit(0, nullptr);
};
std::thread t(supervisor, this, std::move(future));
t.detach();
}
| true |
8454f85e0a9ed85d69bcaead11e28f65c87a6c70 | C++ | MaryRybalka/library | /main.cpp | UTF-8 | 4,766 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <exception>
#include <fstream>
using namespace std;
class Autor;
class Book {
string name;
string author;
public:
Book(const string name, const string author) {
this->name = name;
this->author = author;
}
const string getName() const {
return name;
}
const string getAuthor() const {
return author;
}
};
class Library {
private:
vector<const Book *> books;
void reloadBooks() {
books.clear();
ifstream f;
f.open("../Library");
string newLine;
string newName;
string newAut;
while (!f.eof()) {
newName = "";
newAut = "";
getline(f, newLine);
int i = 0;
while (newLine[i] != '-') {
newName += newLine[i++];
}
i++;
while (newLine[i] != '\0') {
newAut += newLine[i++];
}
books.push_back(new Book(newName, newAut));
}
f.close();
}
public:
const Book *findBook(string name, string autor) {
reloadBooks();
for (auto &book : books) {
if ((book->getName() == name) && (book->getAuthor() == autor)) return book;
}
return new Book("empty", "empty");
}
vector<const Book *> findBookByAutor(string autor) {
reloadBooks();
vector<const Book *> autorBook;
for (auto &book : books) {
if (book->getAuthor() == autor)
autorBook.push_back(book);
}
return autorBook;
}
vector<const Book *> findBookByName(string name) {
reloadBooks();
vector<const Book *> thisBook;
for (auto &book : books) {
if (book->getName() == name)
thisBook.push_back(book);
}
return thisBook;
}
};
class Worker : public Library {
int askAboutChoise() {
cout << "Wanna choose one of this books? 1 - Yes/ -1 - No" << endl;
int choise = 0;
cin >> choise;
if (choise == 1) {
cout << "Write number of this book." << endl;
cin >> choise;
}
return choise;
}
public:
const Book *giveBook(string name, string author) {
const Book *fBook = findBook(name, author);
if (fBook->getAuthor() == "empty") throw logic_error("There are no needs book in the library");
return fBook;
}
const Book *giveBookByAutor(string author) {
vector<const Book *> fBook = findBookByAutor(author);
if (fBook.empty()) throw logic_error("There are no needs book of this author in the library");
else {
cout << "There are all books of " << author << " in this list below: " << endl;
for (int i = 0, len = fBook.size(); i < len; i++) {
cout << i << ") " << fBook[i]->getName() << endl;
}
cout << endl;
int choise = askAboutChoise();
if (choise == -1) throw runtime_error("Goodbye");
return fBook[choise % fBook.size()];
}
}
const Book *giveBookByName(string name) {
vector<const Book *> fBook = findBookByName(name);
if (fBook.empty()) throw logic_error("There are no needs book with this name in the library");
else {
cout << "There are all authors, who has book with this name '" << name << "' in this list below: " << endl;
for (int i = 0, len = fBook.size(); i < len; i++) {
cout << i << ") " << fBook[i]->getAuthor() << endl;
}
cout << endl;
int choise = askAboutChoise();
if (choise == -1) throw logic_error("");
return fBook[choise % fBook.size()];
}
}
};
class Customer : protected Worker {
public:
bool askAboutBook(string _name, string _author) {
try {
const Book *needsBook;
if (_name == "") needsBook = giveBookByAutor(_author);
else {
if (_author == "") needsBook = giveBookByName(_name);
else needsBook = giveBook(_name, _author);
}
cout << "i've got '" << needsBook->getName() << " " << needsBook->getAuthor() << "' book." << endl;
return true;
}
catch (exception &e) {
cout << e.what() << endl;
return false;
}
}
};
int main() {
Customer Bob;
Bob.askAboutBook("white whale", "");
Bob.askAboutBook("", "fedor dostoyevsky");
Bob.askAboutBook("weak heart", "fedor dostoyevsky");
Bob.askAboutBook("bobo dead", "joseph brodsky");
Bob.askAboutBook("bobo is dead", "joseph brodsky");
return 0;
} | true |
444dcc0627dea53100437233d90b236bfbd0681d | C++ | 120189471/CPP | /Exercise/Main/Main_4_11.cpp | GB18030 | 1,103 | 2.78125 | 3 | [] | no_license | int main_4_11(){
bool flag;
char cval;
short sval;
unsigned short usval;
int ival;
unsigned int uival;
long lval;
unsigned long ulval;
float fval;
double dval=0.0;
/*
3.1415926L + 'a'; //a->int->double
dval + ival; //int->double
dval + fval; //float->double
ival = dval; //dval->int,ȥС
flag = dval; //dval=0"false":"true"
cval + fval; //char->int->float;
sval + cval; //short->int;char->int
cval + lval; //char->long;
ival + ulval; //int->unsigned long
usval + ival; //ռռС
uival + lval; //ռռС
*/
int ia[10];
int* iaPtr = ia; //תָ
return 0;
} | true |
6ef4cbf03d59666e71b7655c94f58b51124aa57f | C++ | ukibs/GameEngine | /GameEngine/GameEngine/ActionManager.cpp | UTF-8 | 2,264 | 3.046875 | 3 | [] | no_license | #include "ActionManager.h"
ActionManager::ActionManager()
{
}
ActionManager::~ActionManager()
{
actions.clear();
}
void ActionManager::addAction(Action action)
{
actions.push_back(action);
}
void ActionManager::addAction(string name, string keyName)
{
Action newAction(name);
newAction.addKey(keyName);
actions.push_back(newAction);
}
void ActionManager::addAction(string name,int numKeys, string keyName, ...) {
Action newAction(name);
va_list arguments;
va_start(arguments, keyName);
for (int i=0; i<numKeys; i++) {
newAction.addKey(keyName);
keyName = va_arg(arguments, string);
}
newAction.addKey(keyName);
va_end(arguments);
actions.push_back(newAction);
}
void ActionManager::removeAction(string name)
{
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++) {
if (actionIt->getAction()==name) {
//hay que probarlo!!
actions.erase(actionIt);
}
}
}
void ActionManager::update()
{
InputManager::GetInstance().keyboardCheck();
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++)
{
actionIt->update();
}
}
bool ActionManager::getDown(string name)
{
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++)
{
if (actionIt->getAction() == name)
{
return actionIt->getDown();
}
}
cout << "no existe la accion" << endl;
return false;
}
bool ActionManager::getPressed(string name)
{
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++) {
if (actionIt->getAction() == name) {
return actionIt->getPressed();
}
}
cout << "no existe la accion" << endl;
return false;
}
bool ActionManager::getReleased(string name)
{
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++) {
if (actionIt->getAction() == name) {
return actionIt->getReleased();
}
}
printf("no existe la accion");
return false;
}
Action* ActionManager::getActionByName(string name)
{
for (vector <Action>::iterator actionIt = actions.begin(); actionIt != actions.end(); actionIt++) {
if (actionIt->getAction() == name) {
return &(*actionIt);
}
}
printf("no existe la accion");
return NULL;
}
| true |
3526c0958bf771a97dd1d23c8f1c49a50c80b6d1 | C++ | JasonFevang/ticTacToe | /ticTacToe/Player.cpp | UTF-8 | 605 | 3.28125 | 3 | [] | no_license | #include "All.h"
Player::Player(Board *board, marker symbol, bool isAI){
pboard = board; //dependancy injection
this->symbol = symbol;
this->isAI = isAI; //Sets the player to be an AI or human
}
// Player destructor, deletes memory allocation to pboard
Player::~Player()
{
delete pboard;
}
//Plays a symbol on the specified square 1-9
void Player::play(int square) {
pboard->playSquare(square, symbol);
}
//returns the symbol of the current player
marker Player::getSymbol() {
return symbol;
}
//Gets the Player's square
int Player::choice() {
int choice;
cin >> choice;
return choice;
}
| true |
b639f62afbf43c1e9d77ff7cd20516de392d2239 | C++ | yuliy/sport_programming | /codeforces/001/A/main.cpp | UTF-8 | 256 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
long long n, m, a;
cin >> n >> m >> a;
long long x = n / a;
long long y = m / a;
if (a*x < n)
++x;
if (a*y < m)
++y;
cout << x * y << endl;
return 0;
}
| true |
51d1450a78e612680ff74b8f1b18034b59c24568 | C++ | sousablde/CPP | /Arrays/main.cpp | UTF-8 | 1,401 | 3.84375 | 4 | [] | no_license |
#include <iostream>
using namespace std;
// Could declare variables here! string numbers[] = {"one", "two", "three"};
void show1(const int nElements, string texts[]) {
// cout << sizeof(texts) << endl; returns sizeof pointer!
//to go around this and not have just the size of the pointer
//we pass the number of elements as well
for (int i = 0; i < nElements; i++) {
cout << texts[i] << endl;
}
}
//this function is exactly the same as show 1
//except that we are using a pointer to the array
void show2(const int nElements, string *texts) {
// cout << sizeof(texts) << endl; returns sizeof pointer!
for (int i = 0; i < nElements; i++) {
cout << texts[i] << endl;
}
}
//to retain the actual number of elements we pass it as reference
//this will allow us to use sizeof without having to pass the number of elements
void show3(string (&texts)[3]) {
// cout << sizeof(texts) << endl; returns sizeof pointer!
for (int i = 0; i < sizeof(texts) / sizeof(string); i++) {
cout << texts[i] << endl;
}
}
char *getMemory() {
char *pMem = new char[100];
return pMem;
}
void freeMemory(char *pMem) {
delete[] pMem;
}
int main() {
string texts[] = {"apple", "orange", "banana"};
cout << sizeof(texts) << endl;
show3(texts);
char *pMemory = getMemory();
freeMemory(pMemory);
return 0;
}
| true |
a4fc11b99bad14306bddd84619480d90ef2fcbcc | C++ | rodolfo15625/algorithms | /tc/testprograms/BombMan.cpp | UTF-8 | 8,143 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define REP(i,n) for (int i = 0; i < (int)n; i++)
#define FOR(i, a, b) for (int i = a; i <= b; i++)
typedef long long ll;
bool vis[55][55][105];
struct Node{
int x,y,b,t;
Node(int _x, int _y, int _b, int _t){
x=_x;y=_y;b=_b;t=_t;
}
bool operator < (const Node p)const{
if(p.t==t)return p.b<b;
return p.t<t;
}
};
int dx[]={-1,1,0,0};
int dy[]={0,0,1,-1};
struct BombMan {
int shortestPath( vector <string> maze, int bombs ) {
priority_queue<Node> Q;
int sx,sy,ex,ey;
REP(i,maze.size())REP(j,maze[i].size()){
if(maze[i][j]=='B')sx=i,sy=j;
if(maze[i][j]=='E')ex=i,ey=j;
}
Q.push(Node(sx,sy,0,0));
memset(vis,0,sizeof vis);
vis[sx][sy][0]=1;
while(!Q.empty()){
Node cur=Q.top();Q.pop();
if(cur.x==ex && cur.y==ey)return cur.t;
REP(i,4){
int X=cur.x+dx[i];
int Y=cur.y+dy[i];
if(min(X,Y)>=0 && X<maze.size() && Y<maze[0].size()){
if(maze[X][Y]=='#'){
//# wall
if(vis[X][Y][cur.b+1]==0 && (cur.b+1)<=bombs){
Q.push(Node(X,Y,cur.b+1,cur.t+3));
vis[X][Y][cur.b+1]=1;
}
}else{
//. free
if(vis[X][Y][cur.b]==0){
Q.push(Node(X,Y,cur.b,cur.t+1));
vis[X][Y][cur.b]=1;
}
}
}
}
}
return -1;
}
};
// BEGIN CUT HERE
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing BombMan (500.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1358450776;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 500.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
BombMan _obj;
int _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
string maze[] = {".....B.",
".#####.",
".#...#.",
".#E#.#.",
".###.#.",
"......."};
int bombs = 1;
_expected = 8;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}
case 1:
{
string maze[] = {"B.#.#.#...E"};
int bombs = 2;
_expected = -1;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}
case 2:
{
string maze[] = {"..#####",
"B.#####",
"..#####",
"#######",
"####...",
"####.E."};
int bombs = 4;
_expected = 17;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}
case 3:
{
string maze[] = {".#.#.#.#B#...#.#...#.#...#.#...#.#...#.#.#.......",
".#.#.#.#.#.###.###.#.###.#.#.###.###.#.#.#.###.##",
".#.#.#...#.#.#.#.#.#...#.....#.#.#...#...#.#.#...",
".#.#.###.#.#.#.#.#.###.#.#####.#.###.###.#.#.###.",
".............#.#...#...#.....#.#.#...#.#.#.....#.",
"##.#######.###.#.#####.#.#####.#.###.#.#.#.#.####",
".#.#.....#...#...#.#...#...#.#.#...#...#...#.....",
".#######.#.#####.#.#.#.#.###.#.###.#.#####.#.####",
".#.#.#.#...#.#.#.#.#.#.......#...#.#...#.#.#.....",
".#.#.#.###.#.#.#.#.#####.#####.###.###.#.#.######",
".....#...#.#...#...#...#...#...#...#.#.#.........",
"####.###.#.###.###.#.###.#.#.###.###.#.#.########",
".......#.........#.#.#.#.#.#.#.#.........#...#...",
".#.###.#########.#.#.#.#.###.#.#####.#.#.#.###.##",
".#.#.........#.#.#.#.#.....#.#.#.....#.#.........",
"############.#.#.#.#.#.#####.#.#.################",
".#...........#...#.#.#.#...#.#.#...#.#.#.....#...",
".#####.#####.###.#.#.#.#.###.#.#.###.#.#.#####.##",
".......#...#.#.#.....#...#...#.#.#.#.#...........",
"##########.#.#.#####.#.###.###.#.#.#.#.##########",
".....#...#.....#.#...#.......#.#...#.......#.....",
"##.#.###.#.###.#.#.#.#.#####.#.#.###.#######.####",
"...#...#...#.......#.....#.#...#...#.......#.....",
"####.#.#.#########.#.###.#.#####.###.#.#######.##",
".#...#...#.........#.#.....#.........#.#.#.#.....",
".#####.#.#.###.#######.#.###.#.#########.#.#.####",
".......#.#.#...#.......#.....#.#.#.......#.#.#.#.",
"########.#.#.#.#####.#.###.#.###.#.#######.#.#.#.",
".........#.#.#.#.....#...#.#.........#.#.........",
"################.#.#.#.#.#.#.#.#######.#.########",
".................#.#.#.#.#.#.#...........#.......",
"########.#####.#.###.#.#.#####.###.#.#####.###.##",
".........#...#.#...#.#.#...#.....#.#.........#...",
".#####.#####.#.###.#.###.#.#.#.#.#.#####.#.###.#.",
".#.....#.........#.#.#...#.#.#.#.#.#.....#...#.#.",
"####.#####.###.#.#.#.#.#.#.###.###.#.#.#.#.#####.",
".....#.....#.#.#.#.#.#.#.#.#...#...#.#.#.#...#...",
"####.#.#.###.#.#.###.#.###.#.#.#####.#.#.#.######",
".....#.#.#.#...#...#.#...#.#.#...#...#.#.#.......",
"##########.#.#.#.#####.###.#.#.###.#.###.#####.##",
"...#.#...#...#.#.....#.#...#.#...#.#.#.......#...",
".#.#.#.#.#.#.#.#.#.#.###.#.#########.###.#.#.#.#.",
".#.#...#...#.#.#.#.#...#.#...#.......#...#.#.#.#.",
"##.###.#.#.###.#.#.#.#.#####.#.#.#.###.#.########",
".......#.#...#.#.#.#.#.#.....#.#.#...#.#.........",
"####.#######.#.#####.#.###.#.#.###.#.#.#.########",
"E..#.......#.#.....#.#.#.#.#.#.#...#.#.#.........",
"##.#.#.#.###.###.###.###.#.#.###.#.#.#.#.#######.",
".....#.#...#.#.....#.#.....#...#.#.#.#.#.....#..."};
int bombs = 3;
_expected = 76;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}
/*case 4:
{
string maze[] = ;
int bombs = ;
_expected = ;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}*/
/*case 5:
{
string maze[] = ;
int bombs = ;
_expected = ;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}*/
/*case 6:
{
string maze[] = ;
int bombs = ;
_expected = ;
_received = _obj.shortestPath(vector <string>(maze, maze+sizeof(maze)/sizeof(string)), bombs); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << _expected << endl;
cout << " Received: " << _received << endl;
}
}
}
// END CUT HERE
| true |
5dcf39868982a8f1139aae35c36ffed3aa183ffc | C++ | MiloSi/algorithm_study | /manage_leb/ml.cpp | UTF-8 | 997 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <memory.h>
using namespace std;
const long long MOD = 1000000007;
long long table[10001][16];
//Using bitmask
// a = 0, b = 1, c = 2, d = 3;
long long solution(string& str) {
int len = str.length() -1;
memset(table, 0, sizeof(table));
int shift = str[0] - 'A';
int admin = 1 << shift;
for (int j = 1; j <= 15; j++) {
if (j & admin && j & 1) {
table[0][j] = 1;
}
}
for (int i = 1; i <= len; i++) {
int shift = str[i] - 'A';
int admin = 1 << shift;
for (int j = 1; j <= 15; j++) {
if (j & admin) {
for (int k = 1; k <= 15; k++) {
if (k & j) {
table[i][j] = (table[i][j] + table[i - 1][k]) % MOD;
}
}
}
}
}
long long retval = 0;
for (int i = 1; i <= 15; i++) {
retval = (retval + table[len][i]) % MOD;
}
return retval;
}
int main() {
int testcase;
cin >> testcase;
for (int t = 1; t <= testcase; t++) {
string str;
cin >> str;
cout << "#" << t << " " << solution(str) << endl;
}
}
| true |
4c14e21ac70fe8aa67bf3ac958d49a5d1166793e | C++ | DaliaEl-Sayed/Security | /At&t.cpp | UTF-8 | 2,238 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "stdio.h"
#include <string>
#include <math.h>
using namespace std ;
int main(){
string txt_init , key_init ;
vector <int> txt2num, key2num , result ;
vector <char> txt,key ;
vector <char> ch = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
vector <int> ch_decimal = {65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90};
cin >> key_init;
cin >> txt_init ;
for (int i = 0 ; i < txt_init.length() ; i++){
txt.push_back(txt_init[i]);
}
int counter = 0 ;
int index =0;
while (counter != txt.size()){
key.push_back(key_init[index]);
index++;
if(index == key_init.length()){
index = 0 ;
}
counter ++ ;
}
for (int i = 0 ; i < txt.size() ; i++){
for (int j = 0 ; j< ch.size(); j++) {
if (ch[j]==txt[i]){
txt2num . push_back (j);
}
if (ch[j]==key[i]){
key2num . push_back (j);
}
}
}
cout << "Vigenere: ";
for (int i = 0 ; i < txt.size() ; i++){
result.push_back((txt2num[i]+key2num[i])%26);
cout << ch[result[i]] ;
}
////////////////////////////////////////////////////////////////////////vigenere
cout << endl ;
txt2num.clear();
key2num.clear ();
vector <int> re_de ;
for (int i = 0 ; i < txt.size() ; i++){
for (int j = 0 ; j< ch.size(); j++) {
if (ch[j]==txt[i]){
txt2num . push_back (ch_decimal[j]);
}
if (ch[j]==key[i]){
key2num . push_back (ch_decimal[j]);
}
}
}
cout << "Vernam: ";
for (int i = 0 ; i < txt2num.size() ; i++){
int xx = (int)txt2num.at(i);
int yy = (int)key2num.at(i);
int zz = xx xor yy ;
printf("%02hhX", zz);
}
cout << endl << "One-Time Pad: ";
if (key_init.length() == txt_init.length()){
cout << "YES";
}
else {
cout << "NO";
}
return 0 ;
} | true |
e13477b0f312fa85f14b5d06d1b31a9a8257f7db | C++ | jsewalton/PHYSCI-70 | /assets/Edwards_final_project_final.ino | UTF-8 | 12,329 | 2.53125 | 3 | [] | no_license | // Jessica Edwards, PS70 Final Project Code, Spring 2021
#include <FastLED.h>
#include <WiFi.h> // esp32 library
#include <FirebaseESP32.h> // firebase library
#define FIREBASE_HOST "" // the project name address from firebase id
#define FIREBASE_AUTH "" // the secret key generated from firebase
#define WIFI_SSID "" // input your home or public wifi name
#define WIFI_PASSWORD "" // password of wifi ssid
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN1 12
#define PIN2 27
#define PIN3 33
#define PIN4 25
#define PIN5 4
#define NUM_LEDS 10
#define BRIGHTNESS 64
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];
#define UPDATES_PER_SECOND 1000
long previousMillis = 0;
long interval = 1000 / UPDATES_PER_SECOND;
// This example shows several ways to set up and use 'palettes' of colors
// with FastLED.
//
// These compact palettes provide an easy way to re-colorize your
// animation on the fly, quickly, easily, and with low overhead.
//
// USING palettes is MUCH simpler in practice than in theory, so first just
// run this sketch, and watch the pretty lights as you then read through
// the code. Although this sketch has eight (or more) different color schemes,
// the entire sketch compiles down to about 6.5K on AVR.
//
// FastLED provides a few pre-configured color palettes, and makes it
// extremely easy to make up your own color schemes with palettes.
//
// Some notes on the more abstract 'theory and practice' of
// FastLED compact palettes are at the bottom of this file.
CRGBPalette16 currentPalette;
TBlendType currentBlending;
String led_status = ""; // led status received from firebase
String hex = "";
//Define FirebaseESP32 data object
FirebaseData firebaseData;
void setup() {
Serial.begin(115200);
delay( 3000 ); // power-up safety delay
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // try to connect with wifi
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
Serial.println();
Serial.print("Connected to ");
Serial.println(WIFI_SSID);
Serial.print("IP Address is : ");
Serial.println(WiFi.localIP()); // print local IP address
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to firebase
Firebase.reconnectWiFi(true);
Firebase.set(firebaseData, "/LED_STATUS", "off");
Firebase.set(firebaseData, "/COLOR", "");
// Initialize five LED strips
FastLED.addLeds<LED_TYPE, PIN1, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.addLeds<LED_TYPE, PIN2, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.addLeds<LED_TYPE, PIN3, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.addLeds<LED_TYPE, PIN4, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.addLeds<LED_TYPE, PIN5, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness( BRIGHTNESS );
// Begin in the "off" setting
currentPalette = CRGBPalette16(CRGB::Black);
fill_solid( currentPalette, 10, CRGB::Black);
}
void loop()
{
// Gone with the delay! Used millis() instead
unsigned long currentMillis = millis();
Firebase.get(firebaseData, "/LED_STATUS"); // get led status input from firebase
led_status = firebaseData.stringData(); // change to e.g. intData() or boolData()
Serial.println(led_status);
Firebase.get(firebaseData, "/COLOR");
hex = firebaseData.stringData();
Serial.println(hex);
if (led_status == "off") { // compare the input of led status received from firebase
if (currentMillis - previousMillis > interval) { // save the last time you blinked the LED
previousMillis = currentMillis;
Serial.println("off");
currentPalette = CRGBPalette16(CRGB::Black); // solid black
fill_solid( currentPalette, 10, CRGB::Black);
static uint8_t startIndex = 0;
startIndex = startIndex + 1; // startIndex increments control the speed (larger int = faster speed)
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "color") {
if (currentMillis - previousMillis > interval) {
Serial.println("color");
long number = (long) strtol( &hex[1], NULL, 16); // turn HEX string to RGB numbers
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;
currentPalette = CRGBPalette16(CRGB( r, g, b));
fill_solid( currentPalette, 10, CRGB( r, g, b));
static uint8_t startIndex = 0;
startIndex = startIndex + 1;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "romantic") {
if (currentMillis - previousMillis > interval) {
Serial.println("romantic");
RomanticPalette();
currentBlending = LINEARBLEND; // built-in light show styles
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "vibes") {
if (currentMillis - previousMillis > interval) {
Serial.println("vibes");
currentPalette = PartyColors_p;
currentBlending = NOBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 50;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "sunrise") {
if (currentMillis - previousMillis > interval) {
Serial.println("sunrise");
SunrisePalette();
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "chill") {
if (currentMillis - previousMillis > interval) {
Serial.println("chill");
ChillPalette();
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "waves") {
if (currentMillis - previousMillis > interval) {
Serial.println("waves");
currentPalette = OceanColors_p;
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "winter") {
if (currentMillis - previousMillis > interval) {
Serial.println("winter");
WinterPalette();
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "christmas") {
if (currentMillis - previousMillis > interval) {
Serial.println("christmas");
ChristmasPalette();
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 10;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
else if (led_status == "birthday") {
if (currentMillis - previousMillis > interval) {
Serial.println("birthday");
BirthdayPalette();
currentBlending = LINEARBLEND;
static uint8_t startIndex = 0;
startIndex = startIndex + 50;
FillLEDsFromPaletteColors( startIndex);
FastLED.show();
}
}
}
void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
uint8_t brightness = 255;
for (int i = 0; i < NUM_LEDS; ++i) {
leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);
colorIndex += 3;
}
}
// There are several different palettes of colors demonstrated here.
//
// FastLED provides several 'preset' palettes: RainbowColors_p, RainbowStripeColors_p,
// OceanColors_p, CloudColors_p, LavaColors_p, ForestColors_p, and PartyColors_p.
//
// Additionally, you can manually define your own color palettes, or you can write
// code that creates color palettes on the fly. All are shown here.
void RomanticPalette()
{
CRGB color1 = CRGB(92, 10, 60);
CRGB color2 = CRGB(121, 21, 81);
CRGB color3 = CRGB(245, 111, 134);
CRGB color4 = CRGB(210, 65, 117);
CRGB color5 = CRGB(188, 52, 118);
currentPalette = CRGBPalette16(
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1);
}
void WinterPalette()
{
CRGB color1 = CRGB(17, 60, 207);
CRGB color2 = CRGB(191, 245, 253);
CRGB color3 = CRGB(255, 255, 255);
currentPalette = CRGBPalette16(
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1);
}
void SunrisePalette()
{
CRGB color1 = CRGB(183, 44, 60);
CRGB color2 = CRGB(255, 154, 0);
CRGB color3 = CRGB(255,77,0);
CRGB color4 = CRGB(255,103,0);
CRGB color5 = CRGB(255, 219, 0);
currentPalette = CRGBPalette16(
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1);
}
void ChristmasPalette()
{
CRGB color1 = CRGB(255, 0, 0);
CRGB color2 = CRGB(0, 255, 0);
CRGB color3 = CRGB(202, 184, 81);
currentPalette = CRGBPalette16(
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1);
}
void ChillPalette()
{
CRGB color1 = CRGB(57, 162, 174);
CRGB color2 = CRGB(113, 196, 194);
CRGB color3 = CRGB(227, 188, 181);
currentPalette = CRGBPalette16(
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1, color2, color3,
color1);
}
void BirthdayPalette()
{
CRGB color1 = CRGB(21, 35, 194);
CRGB color2 = CRGB(3, 120, 252);
CRGB color3 = CRGB(90, 31, 189);
CRGB color4 = CRGB(255, 165, 255);
CRGB color5 = CRGB(173, 68, 249);
currentPalette = CRGBPalette16(
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1, color2, color3, color4, color5,
color1);
} | true |
f29814acabe53cf84bf4372e296ce06bbbe68271 | C++ | Spritutu/hiquotion_cpp | /AdvancedLib/PokerLib/IPokerArea.h | GB18030 | 1,352 | 2.5625 | 3 | [] | no_license | // IPokerArea.h: interface for the IPokerArea class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_IPOKERAREA_H__3FD1517B_61DD_4A93_8113_D017449E5004__INCLUDED_)
#define AFX_IPOKERAREA_H__3FD1517B_61DD_4A93_8113_D017449E5004__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Poker.h"
#include "PokerColumnArea.h"
#include "..\..\FoudationLib\DataStructLib\PointerList.h"
class IPokerArea : public IUIHandler
{
public:
IPokerArea();
IPokerArea(int count, CPoint relativePosition);
virtual ~IPokerArea();
// ʼʱ
void add(int columnIndex, CPoker *poker);
// ˿ж
void setPokerColumnArea(int count, CPoint relativePosition);
// жǷƵķ
virtual BOOL canDrop(CPoker *poker, CPoint relativeTopLeft=CPoint(0, 0)) { return FALSE; };
// ȡһƵλ
CPoint getNextDrop();
// Ʒ
virtual void drop(CPoker *poker);
// ȡʰȡֽƵλ
virtual int getPickupIndex(CPoker *poker);
// ʰƷ
virtual void pickup(CPoker *poker);
protected:
CPointerList<CPokerColumnArea *> m_pokerColumnArea;
int m_count;
int m_pokerDropIndex;
int m_pokerPickupIndex;
};
#endif // !defined(AFX_IPOKERAREA_H__3FD1517B_61DD_4A93_8113_D017449E5004__INCLUDED_)
| true |
4b741f4835b23993218d2a46f2813335e2335945 | C++ | vslavik/poedit | /deps/boost/libs/spirit/classic/phoenix/test/stl_tests.cpp | UTF-8 | 2,780 | 2.75 | 3 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0"
] | permissive | /*=============================================================================
Phoenix V1.2.1
Copyright (c) 2001-2003 Joel de Guzman
Use, modification and distribution is subject to 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)
==============================================================================*/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <boost/detail/lightweight_test.hpp>
#define PHOENIX_LIMIT 15
#include <boost/spirit/include/phoenix1_primitives.hpp>
#include <boost/spirit/include/phoenix1_composite.hpp>
#include <boost/spirit/include/phoenix1_functions.hpp>
#include <boost/spirit/include/phoenix1_operators.hpp>
#include <boost/spirit/include/phoenix1_binders.hpp>
#include <boost/spirit/include/phoenix1_special_ops.hpp>
using namespace phoenix;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
struct print_ { // a typical STL style monomorphic functor
typedef void result_type;
void operator()(int n0) { cout << "got 1 arg " << n0 << " \n"; }
};
functor<print_> print = print_();
///////////////////////////////////////////////////////////////////////////////
int
main()
{
///////////////////////////////////////////////////////////////////////////////
//
// STL algorithms
//
///////////////////////////////////////////////////////////////////////////////
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
for_each(v.begin(), v.end(), arg1 *= 2);
for (int m = 0; m < 5; ++m, (cout << ','))
{
cout << v[m];
BOOST_TEST(v[m] == (m+1)*2);
}
cout << endl;
for_each(v.begin(), v.end(), print(arg1));
vector<int>::iterator it = find_if(v.begin(), v.end(), arg1 > 5);
if (it != v.end())
cout << *it << endl;
///////////////////////////////////////////////////////////////////////////////
//
// STL iterators and containers
//
///////////////////////////////////////////////////////////////////////////////
BOOST_TEST((arg1[0])(v) == v[0]);
BOOST_TEST((arg1[1])(v) == v[1]);
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
list<int>::iterator first = l.begin();
list<int>::iterator last = l.end();
BOOST_TEST((*(++arg1))(first) == 2);
BOOST_TEST((*(----arg1))(last) == 4);
///////////////////////////////////////////////////////////////////////////////
//
// End asserts
//
///////////////////////////////////////////////////////////////////////////////
return boost::report_errors();
}
| true |
317cee910f503acf48da2052a216d9e097dff30d | C++ | chenxp-github/SmallToolsV2 | /common/sharedmemory.cpp | UTF-8 | 2,541 | 2.640625 | 3 | [] | no_license | #include "sharedmemory.h"
#include "sys_log.h"
#include "mem_tool.h"
#include <sys/ipc.h>
#include <sys/shm.h>
CSharedMemory::CSharedMemory()
{
this->InitBasic();
}
CSharedMemory::~CSharedMemory()
{
this->Destroy();
}
status_t CSharedMemory::InitBasic()
{
WEAK_REF_CLEAR();
this->m_ShmId = -1;
m_Flags = 0;
m_Data = NULL;
m_Name = 0;
m_Size = 0;
return OK;
}
status_t CSharedMemory::Init()
{
this->InitBasic();
return OK;
}
status_t CSharedMemory::Destroy()
{
WEAK_REF_DESTROY();
this->Close();
this->InitBasic();
return OK;
}
status_t CSharedMemory::Close()
{
if(this->m_ShmId < 0)
return ERROR;
if(m_Data)
{
int ret = shmdt(m_Data);
ASSERT(ret == 0);
m_Data = NULL;
}
return OK;
}
status_t CSharedMemory::Unlink()
{
this->Close();
if(m_ShmId >= 0)
{
int ret = shmctl(m_ShmId,IPC_RMID,0);
ASSERT(ret >= 0);
m_ShmId = -1;
return OK;
}
else
{
int tmpid = shmget(m_Name,0,0);
if(tmpid >= 0)
{
int ret = shmctl(tmpid,IPC_RMID,0);
ASSERT(ret >= 0);
return OK;
}
}
return ERROR;
}
status_t CSharedMemory::OpenCreate(int size)
{
status_t ret = this->Open(size,SHM_R|SHM_W|IPC_CREAT|IPC_EXCL);
this->SetIsOwner(true);
return ret;
}
status_t CSharedMemory::OpenReadOnly()
{
return this->Open(0,SHM_R|IPC_EXCL);
}
status_t CSharedMemory::SetName(int name)
{
m_Name = name;
return OK;
}
status_t CSharedMemory::Open(int size, uint32_t flags)
{
ASSERT(m_Name != 0);
ASSERT(m_ShmId < 0);
m_ShmId = shmget(m_Name,size,flags);
if(m_ShmId < 0)
{
XLOG(LOG_LEVEL_ERROR,LOG_MODULE_COMMON,
"open shared memory 0x%x fail,mode=0x%x",m_Name,flags
);
return ERROR;
}
m_Data = (char*)shmat(m_ShmId,0,0);
ASSERT(m_Data);
struct shmid_ds ds;
memset(&ds,0,sizeof(ds));
ASSERT(shmctl(m_ShmId,IPC_STAT,&ds) == 0);
m_Size = ds.shm_segsz;
return OK;
}
status_t CSharedMemory::OpenReadWrite()
{
return this->Open(0,SHM_R|SHM_W|IPC_EXCL);
}
int CSharedMemory::GetSize()
{
return m_Size;
}
char *CSharedMemory::GetData()
{
return m_Data;
}
status_t CSharedMemory::Zero()
{
ASSERT(m_Data);
memset(m_Data,0,m_Size);
return OK;
}
| true |
2889d38c4a7675dd12693ccb24186c0ec25994aa | C++ | XzoRit/C--Playground | /rvalue_references/rvalue_references.cpp | UTF-8 | 8,734 | 3.1875 | 3 | [
"BSL-1.0"
] | permissive | // rvalue_references.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost/move/move.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
#include <utility>
#include <memory>
using namespace std;
namespace std_ext
{
template<typename T>
typename remove_reference<T>::type&&
move(T&& obj)
{
typedef typename remove_reference<T>::type&& ReturnType;
return static_cast<ReturnType>(obj);
}
}
struct NameImpl
{
NameImpl()
: fname("")
, sname("")
{
}
NameImpl(string fn, string sn)
: fname(fn)
, sname(sn)
{
}
string fname;
string sname;
};
class Name
{
public:
~Name()
{
delete m_impl;
m_impl = nullptr;
}
Name()
: m_impl(new NameImpl())
{
}
Name(string fname, string sname)
: m_impl(new NameImpl(fname, sname))
{
}
// copy ctor
Name(Name const& other)
: m_impl(nullptr)
{
//cout << __FUNCTION__ << " Name const& ";
if(other.m_impl)
m_impl = new NameImpl(*other.m_impl);
}
/*
// copy assignment
Name& operator=(Name const& other)
{
//cout << __FUNCTION__ << " Name const& ";
Name(other).swap(*this);
return (*this);
}
*/
// move ctor
Name(Name&& other)
: m_impl(other.m_impl)
{
//cout << __FUNCTION__ << " Name&& ";
other.m_impl = nullptr;
}
/*
// move assignment
Name& operator=(Name&& other)
{
//cout << __FUNCTION__ << " Name&& ";
Name(move(other)).swap(*this);
return (*this);
}
*/
// unified assignment operator
Name& operator=(Name other)
{
//cout << __FUNCTION__ << " Name ";
Name(other).swap(*this);
return (*this);
}
void swap(Name& other)
{
std::swap(m_impl, other.m_impl);
}
string fname() const
{
return m_impl->fname;
}
string sname() const
{
return m_impl->sname;
}
private:
NameImpl* m_impl;
};
ostream& operator<<(ostream& os, Name const& n)
{
//cout << __FUNCTION__ << " Name const& ";
os << '{' << n.fname() << ", " << n.sname() << '}';
return os;
}
class Names
{
public:
typedef vector<Name> NamesCont;
typedef NamesCont::value_type value_type;
~Names(){};
Names()
: m_names()
{
}
// copy ctor
Names(Names const& other)
: m_names(other.m_names)
{
cout << __FUNCTION__ << " Names const& ";
}
/*
// copy assignment
Names& operator=(Names const& other)
{
cout << __FUNCTION__ << " Names const& ";
Names(other).swap(*this);
return (*this);
}
*/
// move ctor
Names(Names&& other)
: m_names(move(other.m_names))
{
cout << __FUNCTION__ << " Names&& ";
}
/*
// move assignment
Names& operator=(Names&& other)
{
cout << __FUNCTION__ << " Names&& ";
Names(move(other)).swap(*this);
return (*this);
}
*/
// unified assignment operator
Names& operator=(Names other)
{
cout << __FUNCTION__ << " Names ";
other.swap(*this);
return (*this);
}
/*
// boost.move copy assignment
Names& operator=(BOOST_COPY_ASSIGN_REF(Names) other)
{
cout << __FUNCTION__ << " BOOST_COPY_ASSIGN_REF ";
Names(other).swap(*this);
return (*this);
}
// boost.move move ctor
Names(BOOST_RV_REF(Names) other)
: m_names(boost::move(other.m_names))
{
cout << __FUNCTION__ << " BOOST_RV_REF ";
}
// boost.move move assignment
Names& operator=(BOOST_RV_REF(Names) other)
{
cout << __FUNCTION__ << " BOOST_RV_REF ";
Names(boost::move(other)).swap(*this);
return (*this);
}
*/
void swap(Names& other)
{
m_names.swap(other.m_names);
}
NamesCont& cont()
{
return m_names;
}
private:
BOOST_COPYABLE_AND_MOVABLE(Names)
NamesCont m_names;
};
ostream& operator<<(ostream& os, Names& n)
{
//cout << __FUNCTION__ << " Names const& ";
for_each(n.cont().begin(), n.cont().end(),
[&os](Name const& name)
{
os << name;
});
return os;
}
void printNames(Names names)
{
cout << __FUNCTION__ << " Names ";
cout << names;
cout << '\n';
}
/*
void printNames(Names&& names)
{
cout << __FUNCTION__ << " Names&& ";
cout << names;
cout << '\n';
}
void printNames(Names const&& names)
{
cout << __FUNCTION__ << " Names const&& ";
cout << names;
cout << '\n';
}
void printNames(Names const& names)
{
cout << __FUNCTION__ << " Names const& ";
cout << names;
cout << '\n';
}
void printNames(Names& names)
{
cout << __FUNCTION__ << " Names& ";
cout << names;
cout << '\n';
}
*/
Names getNames()
{
cout << __FUNCTION__ << " ";
Names names;
names.cont().reserve(3);
names.cont().push_back(Name("a", "b"));
names.cont().push_back(Name("e", "f"));
names.cont().push_back(Name("c", "d"));
return names.cont().empty() ? Names() : names;
}
const Names getConstNames()
{
return getNames();
}
auto nameComparer =
[](Name const& n1, Name const& n2)
{ return (n1.sname() < n2.sname()); };
Names sortedNames(Names names)
{
cout << __FUNCTION__ << " Names ";
cout << "sort starts ";
sort(names.cont().begin(), names.cont().end(), nameComparer);
cout << "sort ends ";
return names;
}
const Names sortedConstNames(Names names)
{
return sortedNames(names);
}
class Person
{
public:
~Person()
{
}
Person()
: m_name()
{
}
Person(string fname, string sname)
: m_name(fname, sname)
{
}
Person(Person const& other)
: m_name(other.m_name)
{
cout << __FUNCTION__ << " Person const& ";
}
Person& operator=(Person const& other)
{
cout << __FUNCTION__ << " Person const& ";
Person(other).swap(*this);
return *this;
}
Person(Person&& other)
: m_name(move(other.m_name))
{
cout << __FUNCTION__ << " Person&& ";
}
Person& operator=(Person&& other)
{
cout << __FUNCTION__ << " Person&& ";
Person(move(other)).swap(*this);
return *this;
}
void swap(Person& other)
{
m_name.swap(other.m_name);
}
string fname() const
{
return m_name.fname();
}
string sname() const
{
return m_name.sname();
}
private:
Name m_name;
};
Name changeFnameTo(Name const& n, string newFname)
{
return Name(newFname, n.sname());
}
Person changeFnameTo(Person const& p, string newFname)
{
return Person(newFname, p.sname());
}
int main()
{
cout << "RVO\n\n";
Names const n1 = getNames();
printNames(getNames());
Names n2 = sortedNames(getNames());
cout << "\n\n";
cout << "Names\n\n";
Names n3 = sortedNames(n1);
printNames(n3);
printNames(n2);
printNames(n1);
n3 = n2;
n3 = getNames();
cout << "\n\n";
printNames(getNames());
printNames(sortedNames(getNames()));
cout << "\n\n";
printNames(getConstNames());
printNames(sortedConstNames(getNames()));
cout << "\n\n";
Names const n4 = getNames();
printNames(n4);
cout << "\n\n";
Names const& n5 = getNames();
//n5.push_back("d");
getNames().cont().push_back(Name("a", "b"));
cout << "\n\n";
cout << "Name\n\n";
Name na1;
Name na2("John", "Doe");
na1 = changeFnameTo(na2, "Jane");
cout << "\n\n";
cout << "Person\n\n";
Person p1;
Person p2("John", "Doe");
p1 = changeFnameTo(p2, "Jane");
cout << "\n\n";
cout << "Names\n\n";
vector<Names> allNames;
allNames.reserve(10);
Names nas1 = getNames();
Names nas2 = getNames();
allNames.push_back(move(nas1));
allNames.push_back(move(nas2));
cout << "\n\n";
cout << "Perfect Forwarding\n\n";
shared_ptr<Name> spn1 = shared_ptr<Name>(new Name("John", "Doe"));
auto spn2 = make_shared<Name>("John", "Doe");
cout.flush();
return 0;
} | true |
7fce5732d74ef0df81d4c8fade244453281621f4 | C++ | j-aquib/Load-Balancer | /loadbalancer.cpp | UTF-8 | 515 | 2.609375 | 3 | [] | no_license | //loadbalancer.cpp
#ifndef LOADBALANCER_H
#include "loadbalancer.h"
#endif
int loadbalancer::getTime()
{
return systemTime;
}
void loadbalancer::incTime()
{
systemTime++;
}
void loadbalancer::addRequest(request r)
{
requestQueue.enqueue(r);
incTime();
}
request loadbalancer::getRequest()
{
incTime();
if(!requestQueue.isEmpty())
{
request r = requestQueue.dequeue();
return r;
}
}
bool loadbalancer::isRequestQueueEmpty()
{
return requestQueue.isEmpty();
} | true |
683db5c9e25f128116fe2b073e727ed8e8c88811 | C++ | nelk/cs349 | /helicopter_game/aabullet.h | UTF-8 | 370 | 2.625 | 3 | [] | no_license |
#ifndef AABULLET_H
#define AABULLET_H
#include "entity.h"
class AABullet : public Entity {
public:
AABullet(float x, float y, float vx, float vy);
virtual ~AABullet() {}
void paint(XInfo &xinfo);
void update(float delta);
const static int SPEED = 50000.0f; //SQUARED VALUE!!
private:
const static int WIDTH = 5;
const static int HEIGHT = 5;
};
#endif
| true |
ee8a13c36ab2446bf374c5d34a2bb0cdd920911e | C++ | hemant-45/Coding-Interview-Questions | /ModOfBigNumer.cpp | UTF-8 | 292 | 2.78125 | 3 | [] | no_license | // Program to Compute Mod a Big Number Represented as String
#include<bits/stdc++.h>
using namespace std;
int main(){
string str="1263514634434085740385345";
int n=10;
int res=0;
for(int i=0;i<str.length();i++)
res=(res*10+str[i]-'0')%10;
cout<<res;
return 0;
}
| true |
af5e6cf1df305c1341e554fa996e2ab0dec23b61 | C++ | lvke-neu/Leetcode | /9-回文数.cpp | UTF-8 | 503 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<math.h>
using namespace std;
bool isPalindrome(int x)
{
if(x<0)
return 0;
vector<int> v;
while(x!=0)
{
v.push_back(x%10);
x/=10;
}
bool flag=true;
int i=0;
int j=v.size()-1;
while(i<j&&i!=j)
{
if(v[i]!=v[j])
{
flag=false;
break;
}
i++;
j--;
}
return flag;
}
int main()
{
cout<<isPalindrome(10)<<endl;
return 0;
}
| true |
b4e71134999282119b3e0c20cd44cac606ae2fb2 | C++ | sankeerth/Heap | /MaxHeap.cpp | UTF-8 | 2,912 | 3.515625 | 4 | [] | no_license | #include "MaxHeap.h"
#include "log.h"
#include <limits.h>
template <typename T>
void MaxHeap<T>::insert(T key)
{
if (Heap<T>::isHeapFull()) {
Heap<T>::reallocate();
}
Heap<T>::heap_size++;
int index = Heap<T>::getCurrentIndex();
Heap<T>::heap_array[index] = key;
while (index > 0 && (Heap<T>::heap_array[index] > Heap<T>::heap_array[Heap<T>::parent(index)])) {
Heap<T>::swap(Heap<T>::heap_array[index], Heap<T>::heap_array[Heap<T>::parent(index)]);
index = Heap<T>::parent(index);
}
}
template <typename T>
void MaxHeap<T>::remove(int index)
{
if (index > Heap<T>::getCurrentIndex()) {
LOG("Index provided is greater than the number of elements in heap");
return;
}
increase(index, INT_MAX);
extractMax();
}
template <typename T>
void MaxHeap<T>::increase(int index, int value)
{
if (Heap<T>::heap_array[index]->distance() > value) {
LOG("Given value is greater than the one present at the index. \
Call decrease instead");
return;
}
//Heap<T>::heap_array[index] = value;
Heap<T>::heap_array[index]->set(value);
while (index > 0 && (Heap<T>::heap_array[index] > Heap<T>::heap_array[Heap<T>::parent(index)])) {
Heap<T>::swap(Heap<T>::heap_array[index], Heap<T>::heap_array[Heap<T>::parent(index)]);
index = Heap<T>::parent(index);
}
}
template <typename T>
void MaxHeap<T>::decrease(int index, int value)
{
if (Heap<T>::heap_array[index]->distance() < value) {
LOG("Given value is greater than the one present at the index. \
Call increase instead");
return;
}
}
template <typename T>
T MaxHeap<T>::getMin()
{
LOG("Object of MaxHeap is created. Need to create MinHeap!!");
}
template <typename T>
T MaxHeap<T>::extractMin()
{
LOG("Object of MaxHeap is created. Need to create MinHeap!!");
}
template <typename T>
T MaxHeap<T>::getMax()
{
if (Heap<T>::isHeapEmpty()) {
LOG("heap is empty");
//return INT_MAX;
}
return Heap<T>::heap_array[0];
}
template <typename T>
T MaxHeap<T>::extractMax()
{
if (Heap<T>::isHeapEmpty()) {
LOG("heap is empty");
//return INT_MAX;
}
if (Heap<T>::heap_size == 1) {
Heap<T>::heap_size--;
return Heap<T>::heap_array[0];
}
T maximum = Heap<T>::heap_array[0];
Heap<T>::heap_array[0] = Heap<T>::heap_array[Heap<T>::getCurrentIndex()];
Heap<T>::heap_size--;
heapify(0);
return maximum;
}
template <typename T>
void MaxHeap<T>::heapify(int index)
{
int maximum = index;
if (Heap<T>::heap_array[maximum] < Heap<T>::heap_array[Heap<T>::left(index)] &&
Heap<T>::left(index) < Heap<T>::heap_size) {
maximum = Heap<T>::left(index);
}
if (Heap<T>::heap_array[maximum] < Heap<T>::heap_array[Heap<T>::right(index)] &&
Heap<T>::right(index) < Heap<T>::heap_size) {
maximum = Heap<T>::right(index);
}
if (index != maximum) {
Heap<T>::swap(Heap<T>::heap_array[index], Heap<T>::heap_array[maximum]);
heapify(maximum);
}
}
//template class MaxHeap<int>;
template class MaxHeap<Node*>; | true |
d609eb14d130b58d2f28bacfc5762d7598c765d4 | C++ | MoonlightEngEnt/ChatWindowGui | /ChatControlWindowQTProject/model/framepacket.cpp | UTF-8 | 420 | 2.59375 | 3 | [] | no_license | #include "framepacket.h"
#include <QDebug>
FramePacket::FramePacket(QObject *parent) :
QObject(parent)
{
}
QStringList FramePacket::packetData() const
{
return _packetData;
}
void FramePacket::setPacketData(QStringList data)
{
_packetData = data;
qDebug() << "Got Frame Packet";
for (int i =0; i < _packetData.length(); i++){
qDebug() << _packetData[i];
}
emit packetDataChanged();
}
| true |
033977f1d962443cb2cbdaa31acc925f6b09acb7 | C++ | Lodour/ACM-ICPC | /codes/UVa/401.cpp | UTF-8 | 778 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define fastin ios_base::sync_with_stdio(0);cin.tie(0);
const string ss = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
const string tt = "A 3 HIL JM O 2TUVWXY51SE Z 8 ";
char f(char c) {
int p = ss.find(c);
if (p == (int)string::npos) return ' ';
return tt[p];
}
int solve(string &s) {
int rt = 3;
int i = 0, j = (int)s.size() - 1;
for (; i <= j; i++, j--) {
if (s[i] != s[j]) rt &= 2;
if (s[i] != f(s[j])) rt &= 1;
}
return rt;
}
int main() {
#ifdef MANGOGAO
freopen("data.in", "r", stdin);
#endif
string s;
const string a[] = {"not a palindrome.", "a regular palindrome.", "a mirrored string.", "a mirrored palindrome."};
while (cin >> s)
cout << s << " -- is " << a[solve(s)] << endl << endl;
return 0;
}
| true |
673dc30bb5ff742deb13c7b00bb782587b1d8bf5 | C++ | blashu/LogicalCircuit | /CellProcessStrategy.h | UTF-8 | 3,617 | 3.046875 | 3 | [] | no_license | #ifndef CELLPROCESSSTRATEGY_H
#define CELLPROCESSSTRATEGY_H
#include "Bus.h"
#include <string>
class CellProcessStrategy
{
public:
CellProcessStrategy();
// Поскольку стратегия может содержать поля, которые могут изменяться
// в зависимости от расчетов и типа ячейки, то был введен этот интерфейс
// (по мотивам паттерна Prototype).
virtual CellProcessStrategy* clone() const = 0;
virtual size_t inodes_min() const = 0;
virtual size_t inodes_max() const = 0;
virtual size_t onodes_min() const = 0;
virtual size_t onodes_max() const = 0;
void process( const ibus_t& in, const obus_t& out );
void stop_process();
virtual const std::wstring& cell_type_name() = 0;
// Проверяет, корректно ли новое количество входов/выходов.
//
// inCount - новое количество входов;
// outCount - новое количество выходов.
// Возвращяемое значение: поясняющее сообщение об ошибке.
// Если вернет noErrorMessage, то ошибки нет, иначе - есть.
virtual const std::wstring& is_valid_node_count( size_t inCount, size_t outCount ) const;
// Корректировка количества входов/выходов.
//
// updatingType - тип узла, который был обновлен;
// inCount - количество входов;
// outCount - количество выходов.
// Возвращяемое значение: поясняющее сообщение об ошибке.
// Если вернет noErrorMessage, то ошибки нет, иначе - есть.
virtual const std::wstring& correct_node_count( NodeTypes updatingType,
size_t &inCount, size_t &outCount ) const;
// Корректировка количества входов/выходов.
//
// oldInCount - старое количество входов;
// newInCount - новое количество входов;
// oldOutCount - старое количество выходов.
// newOutCount - новое количество выходов.
// Возвращяемое значение: поясняющее сообщение об ошибке.
// Если вернет noErrorMessage, то ошибки нет, иначе - есть.
const std::wstring& correct_node_count( size_t oldInCount, size_t &newInCount,
size_t oldOutCount, size_t &newOutCount ) const;
public:
static const std::wstring noErrorMessage;
protected:
// Производится первая инерация расчета элемента после остановки
// процесса расчета или нет?
inline bool has_just_started();
// Произвести обсчет элемента.
virtual void do_process( const ibus_t& in, const obus_t& out ) = 0;
// Функция вызывается, когда процесс расчета остановлен.
virtual void do_stop_process(){}
private:
enum ErrorMessageTypes
{
EMT_INCOUNT_MORE_THAN_MAX = 0x00 ,
EMT_OUTCOUNT_MORE_THAN_MAX ,
EMT_EMT_NUMBER
};
static const std::wstring errorMessages[ EMT_EMT_NUMBER ];
private:
bool is_process_in_progress;
};
inline bool CellProcessStrategy::has_just_started()
{
return !is_process_in_progress;
}
#endif // CELLPROCESSSTRATEGY_H
| true |
b1f212a2d0591243b689bdb36d4391d614d5e337 | C++ | mannu2411/CPP-Codes | /lisa_workbook.cpp | UTF-8 | 766 | 2.859375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int l=m;
int page_num=1;
int arr[n];
int special=0;;
int start=1;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int k=0;k<n;k++){
for(int j=1;j<=arr[k];j++){
cout<<"j="<<j<<" ";
if(j>l){
page_num++;
l=l+m;
cout<<"page NUmber="<<page_num<<" ";
}
if(j==page_num){
special++;
cout<<"j_special="<<j<<" ";
cout<<"special="<<special<<endl;
cout<<"j="<<j<<" ";
}
}
page_num++;
l=m;
}
cout<<special;
return 0;
}
| true |
8fe942d53b380901817390a9bb81b963cd4b1ce4 | C++ | LayerDE/CppProgramming | /loesungen/blatt-01/ApproximateEulersNumberMain.cpp | UTF-8 | 675 | 2.984375 | 3 | [] | no_license | // Copyright 2018, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Axel Lehmann <lehmann@cs.uni-freiburg.de>.
#include <stdio.h>
#include <math.h>
#include "./ApproximateEulersNumber.cpp"
int main(int argc, char** argv) {
// Store n for both algorithms.
int a1 = 15;
int a2 = 100000000;
// Print results for bot algorithms and the internal value.
printf("Eulers number after %2d iterations (using method 1): %1.10f\n",
a1, approximateEulersNumber(a1));
printf("Eulers with step width 1/%d (method 2) : %1.10f\n",
a2, approximateEulersNumberAlternative(a2));
printf("Internal value of E : %1.10f\n", M_E);
}
| true |
9bac709ae0f8fedc33d9ef48c52fb360d97a8559 | C++ | DanShai/Genetic-Programming | /src/SubExpression.cpp | UTF-8 | 409 | 2.546875 | 3 | [] | no_license | /*
* File: SubExpression.cpp
* Author: dan
*
* Created on April 11, 2015, 6:35 PM
*/
#include "SubExpression.h"
SubExpression::SubExpression(std::string expre, std::string op){
this->_mexp = expre;
this->_mop = op;
}
std::string SubExpression::getExp(){
return this->_mexp;
}
std::string SubExpression::getOp(){
return this->_mop;
}
SubExpression::~SubExpression() {
}
| true |
469911be69d56ae26dedb8f1afa06b0f445d11ed | C++ | Quadroue4/Algorithm | /1761-1.cpp | UTF-8 | 2,247 | 3 | 3 | [] | no_license | //1761-1.cpp
//1761.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N,M;
int parent[40001];
int depth[40001];
int cost[40001];
int dp[40001][17]; //2^0 부터 2^16 까지 필요하므로. (1~40000)
int cost_dp[40001][17];
vector<pair<int,int>> informations[40001];
bool used[40001];
void initialize(){
for(int i=2;i<=N;i++){
dp[i][0] = parent[i];
cost_dp[i][0] = cost[i];
}
int bit = 1;
while(bit <= 16){
for(int i=2;i<=N;i++){
dp[i][bit] = dp[dp[i][bit-1]][bit-1];
cost_dp[i][bit] = cost_dp[i][bit-1]+cost_dp[dp[i][bit-1]][bit-1];
}
bit++;
}
}
int LCA(int a,int b){
if(depth[a] > depth[b]){ // depth가 a <= b 가 되도록 만듬.
int temp = a;
a = b;
b = temp;
}
int i = 16;
int sum = 0;
while(depth[a] != depth[b]){
while(depth[dp[b][i]] < depth[a]){
i--;
}
sum += cost_dp[b][i];
b = dp[b][i];
}
while(a != b){
i=16;
while(dp[a][i] == dp[b][i]){
if(i>0)
i--;
else
break;
}
sum += cost_dp[a][i];
sum += cost_dp[b][i];
//cout<<cost_dp[a][i]<<" "<<cost_dp[b][i]<<"\n";
a = dp[a][i];
b = dp[b][i];
}
return sum;
}
void dfs(int a,int dep){
for(int i=0;i<informations[a].size();i++){
int temp = informations[a][i].first;
int c = informations[a][i].second;
if(temp != 1 && parent[temp] == 0){
depth[temp] = dep+1;
parent[temp] = a;
cost[temp] = c;
dfs(temp,dep+1);
}
}
}
int main(){
scanf("%d",&N);
for(int i=0;i<N-1;i++){
int s,e,c;
scanf("%d %d %d",&s,&e,&c);
informations[min(s,e)].push_back({max(s,e),c});
informations[max(s,e)].push_back({min(s,e),c});
}
depth[1] = 1;
dfs(1,1);//1을 루트로 설정.
initialize(); //1을 넣으면 2^1 위의 조상을 찾고, 거기부터 ~~ 2^17승까지 찾도록 명령.
scanf("%d",&M);
for(int i=0;i<M;i++){
int s,e;
scanf("%d %d",&s,&e);
cout<<LCA(s,e)<<"\n";
}
} | true |
64854134337a8286bb9eedbd6e0acb9c65425531 | C++ | FoxerLee/Leetcode | /submission/cpp/0001.cpp | UTF-8 | 452 | 3.0625 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>obj;
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < nums.size(); j++) {
if (nums[i] + nums[j] == target && i != j) {
obj.push_back(i);
obj.push_back(j);
return obj;
}
}
}
}
};
| true |
7041211b93058cda83dbf6a7f49eade20b24f300 | C++ | pra11chit/competitive | /spoj/ONP.cpp | UTF-8 | 943 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
void transform(stack<char> str, stack<char> str1) {
int size = str.size();
for (int a = 0; a < size; ++a) {
cout << str.top();
str.pop();
}
int size1 = str1.size();
for (int b = 0; b < size1; ++b) {
cout << str1.top();
str1.pop();
}
}
int main () {
int T;
cin >> T;
while (T > 0)
{
stack<char> str, str1;
string ex;
cin >> ex;
int i = ex.size() - 1;
while(i >= 0) {
if (ex[i] != ')' && ex[i] != '(') {
if (ex[i] != '+' && ex[i] != '-' && ex[i] != '*' && ex[i] != '/' && ex[i] != '^') {
str.push(ex[i]);
}
else
{
str1.push(ex[i]);
}
}
i--;
}
transform(str, str1);
T--;
}
return 0;
} | true |
c3b7b36c83d46a316e38835991d90761d39f749b | C++ | FallenRecruit/Led-Strip-Controller | /Led-Strip-Controller/Arduinocode/Arduinocode.ino | UTF-8 | 828 | 3.0625 | 3 | [] | no_license | String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
String commandString = "";
int led1Pin = 9;
int led2Pin = 10;
int led3Pin = 11;
boolean isConnected = false;
void setup() {
Serial.begin(57600);
pinMode(led1Pin,OUTPUT);
pinMode(led2Pin,OUTPUT);
pinMode(led3Pin,OUTPUT);
}
void loop() {
if(stringComplete)
{
stringComplete = false;
inputString = "";
}
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
| true |
0000800e42a1b9aa8211cc192bd986859fbc8e59 | C++ | FRENSIE/FRENSIE | /packages/monte_carlo/collision/photon/test/tstAbsorptionPhotoatomicReaction.cpp | UTF-8 | 6,869 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | //---------------------------------------------------------------------------//
//!
//! \file tstAbsorptionPhotoatomicReaction.cpp
//! \author Alex Robinson
//! \brief Absorption photoatomic reaction unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// FRENSIE Includes
#include "MonteCarlo_AbsorptionPhotoatomicReaction.hpp"
#include "Data_ACEFileHandler.hpp"
#include "Data_XSSEPRDataExtractor.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Testing Variables
//---------------------------------------------------------------------------//
std::shared_ptr<MonteCarlo::PhotoatomicReaction> ace_absorption_reaction;
//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
// Check that the reaction type can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction, getReactionType_ace )
{
FRENSIE_CHECK_EQUAL( ace_absorption_reaction->getReactionType(),
MonteCarlo::HEATING_PHOTOATOMIC_REACTION );
}
//---------------------------------------------------------------------------//
// Check that the threshold energy can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction, getThresholdEnergy_ace )
{
FRENSIE_CHECK_EQUAL( ace_absorption_reaction->getThresholdEnergy(),
exp( -1.381551055796E+01 ) );
}
//---------------------------------------------------------------------------//
// Check that the number of photons emitted from the rxn can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction,
getNumberOfEmittedPhotons_ace )
{
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedPhotons( 1e-3 ),
0u );
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedPhotons( 20.0 ),
0u );
}
//---------------------------------------------------------------------------//
// Check that the number of electrons emitted from the rxn can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction,
getNumberOfEmittedElectrons_ace )
{
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedElectrons( 1e-3 ),
0u );
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedElectrons( 20.0 ),
0u );
}
//---------------------------------------------------------------------------//
// Check that the number of positrons emitted from the rxn can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction,
getNumberOfEmittedPositrons_ace )
{
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedPositrons( 1e-3 ),
0u );
FRENSIE_CHECK_EQUAL(
ace_absorption_reaction->getNumberOfEmittedPositrons( 20.0 ),
0u );
}
//---------------------------------------------------------------------------//
// Check that the cross section can be returned
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction, getCrossSection_ace )
{
double cross_section =
ace_absorption_reaction->getCrossSection( exp( -1.381551055796E+01 ) );
FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 9.916958825662E-07, 1e-12 );
cross_section =
ace_absorption_reaction->getCrossSection( exp( 1.151292546497E+01 ) );
FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 9.999864243970E+04, 1e-12 );
}
//---------------------------------------------------------------------------//
// Check that the absorption reaction can be simulated
FRENSIE_UNIT_TEST( AbsorptionPhotoatomicReaction, react_ace )
{
MonteCarlo::PhotonState photon( 0 );
photon.setEnergy( 20.0 );
photon.setDirection( 0.0, 0.0, 1.0 );
MonteCarlo::ParticleBank bank;
Data::SubshellType shell_of_interaction;
ace_absorption_reaction->react( photon, bank, shell_of_interaction );
FRENSIE_CHECK( photon.isGone() );
FRENSIE_CHECK_EQUAL( shell_of_interaction, Data::UNKNOWN_SUBSHELL );
}
//---------------------------------------------------------------------------//
// Custom Setup
//---------------------------------------------------------------------------//
FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();
std::string test_ace_file_name;
unsigned test_ace_file_start_line;
FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS()
{
ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_ace_file",
test_ace_file_name, "",
"Test ACE file name" );
ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_ace_file_start_line",
test_ace_file_start_line, 1,
"Test ACE file start line" );
}
FRENSIE_CUSTOM_UNIT_TEST_INIT()
{
{
// Create a file handler and data extractor
std::shared_ptr<Data::ACEFileHandler> ace_file_handler(
new Data::ACEFileHandler( test_ace_file_name,
"82000.12p",
test_ace_file_start_line ) );
std::shared_ptr<Data::XSSEPRDataExtractor> xss_data_extractor(
new Data::XSSEPRDataExtractor(
ace_file_handler->getTableNXSArray(),
ace_file_handler->getTableJXSArray(),
ace_file_handler->getTableXSSArray() ) );
// Extract the energy grid and cross section
std::shared_ptr<std::vector<double> > energy_grid(
new std::vector<double>( xss_data_extractor->extractPhotonEnergyGrid() ) );
Utility::ArrayView<const double> raw_heating_cross_section =
xss_data_extractor->extractLHNMBlock();
Utility::ArrayView<const double>::iterator start =
std::find_if( raw_heating_cross_section.begin(),
raw_heating_cross_section.end(),
[](double cs){ return cs != 0.0; } );
std::shared_ptr<std::vector<double> > heating_cross_section(
new std::vector<double>( start, raw_heating_cross_section.end() ) );
// Process the heating cross section
for( size_t i = 0; i < heating_cross_section->size(); ++i )
(*heating_cross_section)[i] = std::log( (*heating_cross_section)[i] );
size_t heating_threshold_index =
energy_grid->size() - heating_cross_section->size();
// Create the heating reaction
ace_absorption_reaction.reset(
new MonteCarlo::AbsorptionPhotoatomicReaction<Utility::LogLog>(
energy_grid,
heating_cross_section,
heating_threshold_index,
MonteCarlo::HEATING_PHOTOATOMIC_REACTION ) );
}
}
FRENSIE_CUSTOM_UNIT_TEST_SETUP_END();
//---------------------------------------------------------------------------//
// end tstAbsorptionPhotoatomicReaction.cpp
//---------------------------------------------------------------------------//
| true |
f7a3d2b66164d940bb69cfcc263140de42c34108 | C++ | peter88037/LeetCode | /129. Sum Root to Leaf Numbers.cpp | UTF-8 | 734 | 3.796875 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
int sum = 0;
sumRootToLeafNum(root, 0, sum);
return sum;
}
void sumRootToLeafNum(TreeNode *root, int curNum, int &sum) {
if(!root) return;
curNum = curNum*10 + root->val;
cout<<curNum<<endl;
if(!root->left && !root->right) sum += curNum;
if(root->left) sumRootToLeafNum(root->left, curNum, sum);
if(root->right) sumRootToLeafNum(root->right, curNum, sum);
}
}; | true |
bb188b28794329cdee130f794f91fb62d90fd352 | C++ | pokerfaceSad/algorithm | /刷题/leetcode-66.cpp | UTF-8 | 912 | 3.421875 | 3 | [] | no_license | # include <iostream>
# include <vector>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int length = digits.size();
for (int index = length-1 ; index >= 0 ; index--) {
if(digits[index] != 9) {
digits[index]++;
return digits;
} else {
digits[index] = 0;
if (index == 0) {
vector<int> res;
res.push_back(1);
res.insert(res.end(), digits.begin(), digits.end());
return res;
}
}
}
return digits;
}
};
int main() {
vector<int> v;
v.push_back(9);
v.push_back(9);
v.push_back(9);
v.push_back(9);
Solution s;
vector<int> res = s.plusOne(v);
for (int i : res) {
cout << i << endl;
}
return 0;
} | true |
23273eca9a3681dd7308122d0d268a12322eba7f | C++ | rylo5688/DropBucket-Client | /fileexplorerscene.cpp | UTF-8 | 13,252 | 2.703125 | 3 | [] | no_license | #include "fileexplorerscene.h"
/**
* @brief FileExplorerScene::FileExplorerScene
* Constructor for File Explorer
*/
FileExplorerScene::FileExplorerScene()
{
Q_INIT_RESOURCE(resources);
allowClicks_ = true;
curr_x_ = 0;
curr_y_ = 0;
factory_ = new SimpleDirectoryFactory();
DirectoryToJson();
}
/**
* @brief FileExplorerScene::SignInSuccess
* Handles the sign in process when the sign in is successful
* @param directoriesArray Directory array from server response
* @param filesArray File array from server resposne
*/
void FileExplorerScene::SignInSuccess(QJsonArray directoriesArray, QJsonArray filesArray) {
CreateDirectoryComposite(directoriesArray, filesArray);
qDebug() << "Composite created";
HandleSyncSignal(directoriesArray, filesArray);
LoadScene(root_dir_);
curr_dir_ = root_dir_;
}
/**
* @brief FileExplorerScene::EnableScene
* Allows for interaction with the FileExplorerScene
*/
void FileExplorerScene::EnableScene() {
allowClicks_ = true;
}
/**
* @brief FileExplorerScene::DisableScene
* Disallows for interaction with the FileExplorerScene
*/
void FileExplorerScene::DisableScene() {
allowClicks_ = false;
}
/**
* @brief FileExplorerScene::DirectoryToJson
* Reads the Dropbucket directory and makes a JSON reflective of it. CURRENT UNUSED.
* @return QJsonDocument of the current directory status
*/
QJsonDocument FileExplorerScene::DirectoryToJson() {
// TODO: Add "directories"
QString dropbucketDirPath = QDir::homePath() + "/Dropbucket/";
QDir dropbucketDir(dropbucketDirPath);
QDirIterator it(dropbucketDirPath, QStringList() << "*", QDir::Files, QDirIterator::Subdirectories);
QJsonArray array;
while(it.hasNext()) {
QJsonObject fileObj;
QJsonObject fileInfoObj;
QString filePath = it.next();
QFileInfo fi(filePath);
QFile file(filePath);
QString md5;
if(file.open(QFile::ReadOnly)) {
md5 = QCryptographicHash::hash(file.readAll(), QCryptographicHash::Md5).toHex();
}
QString relativePath = filePath;
relativePath.remove(0, dropbucketDirPath.length());
fileObj.insert(relativePath, md5);
array.push_back(fileObj);
}
QJsonObject fileSystemObject;
fileSystemObject.insert("fs_objects", array);
QJsonDocument doc(fileSystemObject);
return doc;
}
/**
* @brief FileExplorerScene::AddIcons
* Adds icons to the scene
* @param contents Contents of the directory to add the icons of
*/
void FileExplorerScene::AddIcons(std::vector<Directory*> contents) {
std::vector<Directory*>::iterator it;
int offset_x = 50;
int offset_y = 10;
for(it = contents.begin(); it != contents.end(); it++){
AddIcon(curr_x_ + offset_x, curr_y_ + offset_y, *it);
curr_x_ += 56 + offset_x;
if(curr_x_ > 1200) {
curr_x_ = 0;
curr_y_ += 100;
}
}
}
/**
* @brief FileExplorerScene::AddIcon
* Adds a icon to the scene
* @param x X location
* @param y Y location
* @param toAdd Directory to add
*/
void FileExplorerScene::AddIcon(int x, int y, Directory* toAdd) {
qDebug() << "adding icon";
toAdd->setPos(QPointF(x,y));
addItem(toAdd);
curr_loaded_.push_back(toAdd);
update();
}
/**
* @brief FileExplorerScene::LoadCurrDirParent
* Loads the current directories parent
*/
void FileExplorerScene::LoadCurrDirParent() {
if(curr_dir_ != root_dir_) {
Directory *toLoad = curr_dir_->getParent();
if(toLoad != nullptr) {
LoadScene(toLoad);
}
}
}
/**
* @brief FileExplorerScene::LoadScene
* Loads a directory to the scene
* @param dir Directory to load
*/
void FileExplorerScene::LoadScene(Directory* dir) {
if(curr_loaded_.size() != 0) {
std::vector<Directory*>::iterator it;
for(it = curr_loaded_.begin(); it != curr_loaded_.end(); it++) {
removeItem(*it);
}
}
curr_loaded_.clear();
curr_dir_ = dir;
curr_x_ = 0;
curr_y_ = 0;
std::vector<Directory*> contents = dir->getContents();
AddIcons(dir->getContents());
UpdateDirectoryLabelSignal(dir->getRelativePath());
update();
}
/**
* @brief FileExplorerScene::CreateDirectoryComposite
* Creates the Directory composite of the Bucket's current file structure
* @param directoriesArray Array of the directories on Bucket
* @param filesArray Array of the files in Bucket
*/
void FileExplorerScene::CreateDirectoryComposite(QJsonArray directoriesArray, QJsonArray filesArray) {
qDebug() << "Creating composite";
QJsonArray::iterator it;
// First create all the directories, root dir first
Directory *root = factory_->createDir(0, 0, "folder", "/");
root->setRelativePath("/");
directoryMap_["/"] = root;
root_dir_ = root;
for(it = directoriesArray.begin(); it != directoriesArray.end(); it++) {
QString relativePath = (*it).toString();
QStringList splitPath = relativePath.split("/", QString::SkipEmptyParts);
Directory *newDir = factory_->createDir(0, 0, "folder", splitPath[splitPath.size()- 1]);
newDir->setRelativePath(relativePath);
directoryMap_[relativePath] = newDir;
splitPath.pop_back();
QString parent = splitPath.join('/') + '/';
Folder* p = qgraphicsitem_cast<Folder*>(directoryMap_[parent]);
p->AddDir(newDir);
newDir->setParent(p);
}
// Directories created - fill them files
for(it = filesArray.begin(); it != filesArray.end(); it++) {
QJsonObject fileObj = (*it).toObject();
QString relativePath = fileObj.keys()[0];
QStringList splitPath = relativePath.split("/", QString::SkipEmptyParts);
QString fileName = splitPath[splitPath.length() - 1];
QString parent;
Directory *file = factory_->createDir(0, 0, "file", fileName, fileObj[relativePath].toString());
connect(file, &DataFile::Deleted, this, &FileExplorerScene::FileDeleted);
connect(NetworkManager::getInstance(), &NetworkManager::FileDeleteSuccessfulSignal, file, &Directory::NetworkDeleteSuccessful);
file->setRelativePath(relativePath);
if(splitPath.size() == 1) {
// File is in root directory
parent = "/";
}
else {
splitPath.pop_back();
parent = splitPath.join('/') + '/';
}
Folder* p = qgraphicsitem_cast<Folder*>(directoryMap_[parent]);
file->setParent(p);
p->AddDir(file);
}
}
/**
* @brief FileExplorerScene::FileDeleted
* Removes the deleted file from the FileExplorerScene
* @param deleted The deleted File
*/
void FileExplorerScene::FileDeleted(Directory *deleted) {
FileDeletedSignal(deleted->getRelativePath());
removeItem(deleted);
LoadScene(curr_dir_);
update();
}
/**
* @brief FileExplorerScene::ClearComposite
* Clears the Composite structure (Could have memory leak, not sure)
*/
void FileExplorerScene::ClearComposite() {
delete root_dir_;
directoryMap_.clear();
}
/**
* @brief FileExplorerScene::Sync
* Recreates the composite and loads the root scene when a sync is needed
* @param directoriesArray Directories on the Bucket
* @param filesArray Files in the bucket
*/
void FileExplorerScene::Sync(QJsonArray directoriesArray, QJsonArray filesArray) {
ClearComposite();
CreateDirectoryComposite(directoriesArray, filesArray);
HandleSyncSignal(directoriesArray, filesArray);
LoadScene(root_dir_);
curr_dir_ = root_dir_;
}
/**
* @brief FileExplorerScene::dragMoveEvent
* Handles when a file to be uploaded is dragged around the scene
* @param event Scene drag drop event
*/
void FileExplorerScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event) {
event->acceptProposedAction();
}
/**
* @brief FileExplorerScene::dragEnterEvent
* Handles when a file to be upload enters the scene
* @param event Scene drag drop event
*/
void FileExplorerScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
event->acceptProposedAction();
}
// https://wiki.qt.io/Drag_and_Drop_of_files
/**
* @brief FileExplorerScene::dropEvent
* Handles when a file is dropped into the scene
* @param event Scene drag drop event
*/
void FileExplorerScene::dropEvent(QGraphicsSceneDragDropEvent *event) {
const QMimeData* mimeData = event->mimeData();
if(mimeData->hasUrls()) {
QStringList pathList;
QList<QUrl> urlLIst = mimeData->urls();
QList<QUrl>::iterator it;
for(it = urlLIst.begin(); it != urlLIst.end(); it++) {
QByteArray md5 = QCryptographicHash::hash(mimeData->data(GetMimeType(mimeData)), QCryptographicHash::Md5);
QString Md5 = md5.toHex();
QString url = (*it).toLocalFile();
AddFile(url, Md5);
pathList.append(url);
}
qDebug() << pathList;
// Now we can open and do stuff with the files - want to add file to scene
}
}
/**
* @brief FileExplorerScene::AddFile
* Adds the uploaded file to the Directory composite and to the sceen
* @param filePath File path to the added file
* @param md5 Md5 of the file
*/
void FileExplorerScene::AddFile(QString filePath, QString md5) {
QStringList splitPath = filePath.split("/", QString::SkipEmptyParts);
const QDir pathDir(filePath);
QString relativePath;
qDebug() << curr_dir_->getRelativePath();
if(curr_dir_->getRelativePath() != "/") {
relativePath = curr_dir_->getRelativePath() + splitPath[splitPath.length()-1];
}
else {
relativePath = splitPath[splitPath.length()-1];
}
QString dropbucketDir = QDir::homePath() + "/Dropbucket" + "/" + relativePath;
qDebug() << dropbucketDir;
qDebug() << relativePath;
if(!pathDir.exists() && !QFileInfo::exists(dropbucketDir)) {
// Check it is a directory and that the file doesn't already exist
// Create the file - add it to the directory
Directory* file = factory_->createDir(0, 0, "file", splitPath[splitPath.length()-1], md5);
connect(file, &Directory::Deleted, this, &FileExplorerScene::FileDeleted);
connect(NetworkManager::getInstance(), &NetworkManager::FileDeleteSuccessfulSignal, file, &Directory::NetworkDeleteSuccessful);
file->setRelativePath(relativePath);
file->setParent(curr_dir_);
curr_dir_->AddDir(file);
curr_x_ += 50;
LoadScene(curr_dir_);
curr_x_ += 56;
if(curr_x_ > 1200) {
curr_x_ = 0;
curr_y_ += 100;
}
NetworkManager::getInstance()->FilePost(filePath, curr_dir_->getRelativePath());
FileAddedSignal(dropbucketDir);
}
else {
// Will enter here when the file exists in Dropbucket dir
QFile fileToSave(dropbucketDir);
QFile *file = new QFile(filePath);
file->open(QIODevice::ReadOnly);
fileToSave.resize(file->size());
QByteArray data = file->readAll();
fileToSave.open(QIODevice::WriteOnly);
fileToSave.write(data);
file->close();
fileToSave.close();
}
}
/**
* @brief FileExplorerScene::GetMimeType
* Gets the Mime type from MimeData
* @param inData Data to check
* @return Mime type
*/
QString FileExplorerScene::GetMimeType(const QMimeData *inData) {
if(inData->hasHtml()){
return "text/html";
}
else if(inData->hasText()) {
return "text/plain";
}
else if(inData->hasImage()) {
return "image/*";
}
else {
return "Couldn't determine MIME type";
}
}
/**
* @brief FileExplorerScene::getDirectoryKeys
* Gets the directory keys from the directory map
* @return Directory keys
*/
QStringList FileExplorerScene::getDirectoryKeys() {
QStringList directories;
std::map<QString, Directory*>::iterator it;
for(it = directoryMap_.begin(); it != directoryMap_.end(); it++) {
directories.push_back(it->first);
}
return directories;
}
/**
* @brief FileExplorerScene::mousePressEvent
* Handles when a mouse is clicked on the scene.
* @param event Mouse event
*/
void FileExplorerScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(allowClicks_) {
QGraphicsScene::mousePressEvent(event);
if(itemAt(event->scenePos(), QTransform()) != nullptr) {
QGraphicsItem *clicked = itemAt(event->scenePos(), QTransform());
if(event->button() == Qt::LeftButton) {
qDebug() << clicked->type();
if(clicked->type() == 65538) {
// Folder - open its contents
if(clicked != root_dir_) {
Folder* dir = qgraphicsitem_cast<Folder*>(clicked);
if(clicked != nullptr) {
LoadScene(dir);
}
else {
qDebug() << "error";
}
}
}
}
else if(event->button() == Qt::RightButton) {
if(clicked->type() == 65539) {
qDebug() << "File!";
}
}
}
}
}
| true |
29b7138fe2628c42b24f61103cb9049f735bbbac | C++ | TheTryton/gnoise | /gnoise/include/modules/non_generator_modules/modifiers/exponent/noise_exponent_module.hpp | UTF-8 | 852 | 2.703125 | 3 | [] | no_license | #pragma once
#include "../noise_modifier_module.hpp"
GNOISE_NAMESPACE_BEGIN
inline constexpr float default_exponent = 2.0f;
class noise_exponent_module;
struct exponent
{
inline static float apply(const noise_exponent_module* module, float x);
};
class noise_exponent_module : public noise_modifier_module_base<1, exponent, noise_exponent_module>
{
public:
noise_exponent_module() noexcept = default;
public:
inline float exponent() const
{
return _exponent;
}
void set_exponent(float exponent);
private:
float _exponent = default_exponent;
};
inline float exponent::apply(const noise_exponent_module * module, float x)
{
return std::pow(x, module->exponent());
}
GNOISE_NAMESPACE_END | true |
d6803387164ccd578d8a4fccd7e5fcca31810f8d | C++ | mayankamencherla/cracking-the-coding-interview-solutions | /sorting-and-searching/binary-search.cpp | UTF-8 | 1,315 | 4.09375 | 4 | [
"MIT"
] | permissive | /**
* Implementation of binary search
*/
#include <vector>
#include <iostream>
using namespace std;
int binarySearchIter(vector<int>& v, int search)
{
int low = 0; int high = v.size()-1;
while (low <= high)
{
int mid = (low + high) / 2;
if (v[mid] == search) return mid;
else if (v[mid] < search) low = mid+1;
else high = mid-1;
}
return -1;
}
int binarySearchRec(vector<int>& v, int search, int start, int end)
{
if (start > end) return -1;
int mid = (start + end) / 2;
if (v[mid] == search) return mid;
else if (v[mid] < search) return binarySearchRec(v, search, mid+1, end);
return binarySearchRec(v, search, start, mid-1);
}
int binarySearchRec(vector<int>& v, int search)
{
return binarySearchRec(v, search, 0, v.size()-1);
}
int main()
{
vector<int> v = {1, 4, 5, 6, 8, 9, 11, 14, 15, 17, 18};
for (int elem : v)
{
int search = elem;
int res1 = binarySearchRec(v, search);
int res2 = binarySearchIter(v, search);
printf("Recursively searching for %d in the array yields : %d as the index where %d lies \n\n", search, res1, search);
printf("Iteratively searching for %d in the array yields : %d as the index where %d lies \n\n", search, res2, search);
}
}
| true |
292bbf66f01a1417efbefeaff9cf0583faaff3f0 | C++ | Guykor/CPP_Projects | /cpp_ex3/HashMap.hpp | UTF-8 | 18,545 | 3.546875 | 4 | [] | no_license | /**
* @file HashMap.hpp
* @author Guy Kornblit
*
* @brief HashMap generic container.
*
*/
// ------------------------------ includes ------------------------------
#include "iostream"
#include <array>
#include <vector>
#include <stdexcept>
// -------------------------- const definitions -------------------------
#define LOWER_LOAD_FACTOR 1.0/4
#define UPPER_LOAD_FACTOR 3.0/4
#define INIT_CAPACITY 16
#define MIN_CAPACITY 1
#define TABLE_SIZE_FACTOR 2
#define KEY_NOT_FOUND_MSG "The Key supplied isn't in map"
#define NO_ELEMS 0
#define MISMATCH_INPUT_LEN_MSG "HashMap: the input vectors should be in the same size."
#define FIRST_BUCKET 0
// ------------------------------ HashMap Definition -----------------------------
using namespace std;
/**
* HashMap class template, that stores const pairs of keys and values.
* the Map is implemented with simple hash function and open addressing method.
* includes const forward iterator.
* @tparam KeyT typename that supports comparing, std::hash operation and copy constructible.
* @tparam ValueT KeyT typename that supports comparing, std::hash operation and copy constructible.
*/
template <typename KeyT, typename ValueT>
class HashMap
{
private:
// -------------- Const Definitions -------------
/**
* element in map, implementation guarantees that the value won't be changed after
* inserted to map (one exception with the vectors input constructor).
*/
typedef std::pair<KeyT, ValueT> _pair;
/**
* buckets as part of the open address implementation.
*/
typedef vector<_pair> Bucket;
/**
* an Object that stores a map element meta data, i.e reference to the pair and it's index
* inside it's bucket.
*/
typedef struct ElemMeta
{
_pair &elem;
int idxInBucket;
} ElemMeta;
// -------------- members -------------
/**
* number of elements (pairs) stored in the instance.
*/
int _nElements;
/**
* map capacity, i.e number of buckets.
*/
int _capacity;
/**
* pointer to an array of buckets in heap.
*/
Bucket *_hashTable;
// -------------- Methods -------------
/**
* access to a pair element in the map based on it's key, if the key is in map, a reference
* to pair will be returned, and the idx of the bucket will be updated in the arg supplied.
* otherwise, if the key not in map, an exception will be thrown.
* @param key - lookup value.
* @throws out of range exception if the key isn't in the Map.
* @return ElemMeta object by value, containing a reference to the pair and it's bucket idx.
*/
ElemMeta _getPairByKey(const KeyT &key) const
{
Bucket &b = _hashTable[_hash(key)];
for (int i = 0; i < (int)b.size(); i++)
{
if (b[i].first == key)
{
return ElemMeta{b[i], i};
}
}
throw std::out_of_range(KEY_NOT_FOUND_MSG);
}
/**
* hash a key and bind the value to a valid bucket idx.
* @param key key to hash
* @return int by value of the relevant idx in map.
*/
int _hash(const KeyT& key) const noexcept
{
return std::hash<KeyT>()(key) & (capacity() - 1);
}
/**
* this function resizes the array of buckets to a given capacity,
* it do so by building a new HashMap with the new capacity, re-hashing all elements
* accordingly and than setting the current instance with the temp instance fields.
* @param newSize - given new size of the element, the function will check that this number
* is valid (according to current status of the map).
*/
void _resizeTable(int newSize)
{
if (size() <= newSize && newSize >= MIN_CAPACITY)
{
HashMap resized = HashMap(newSize);
for (auto it = this->cbegin(); it != cend(); ++it)
{
resized.insert(it->first, it->second);
}
*this = std::move(resized);
}
}
/**
* constructor that build a map with a given size.
* @param capacity - number
*/
HashMap(const int capacity)
: _nElements(NO_ELEMS), _capacity(capacity), _hashTable(new Bucket[_capacity]) {}
/**
* assignment operator helper function, swaps between two HashMaps their members.
* @param first hash map to move the second into
* @param second hash map it's members we want to take.
*/
friend void _swap(HashMap &first, HashMap &second) noexcept
{
std::swap(first._nElements, second._nElements);
std::swap(first._capacity, second._capacity);
std::swap(first._hashTable, second._hashTable);
}
public:
/**
* Default constructor, construct an empty HashMap.
*/
HashMap()
: HashMap(INIT_CAPACITY){}
/**
* ctor that receives vector of keys and vector of values and insert them to HashMap
* respectively.
* if a key appears more than one time in the keys vector, the value linked to this key will
* be override with the latter value.
* @param keys vector of type KeyT
* @param values vector of type ValueT
*/
HashMap(const vector<KeyT>& keys, const vector<ValueT> &values)
: HashMap(INIT_CAPACITY)
{
if (keys.size() != values.size())
{
throw std::invalid_argument(MISMATCH_INPUT_LEN_MSG);
}
for (int i = 0; i < (int)keys.size(); ++i)
{
(*this)[keys[i]] = values[i];
}
}
/**
* copy ctor.
* assumes that there is only one key per value (every pair is unique).
*/
HashMap(const HashMap &other)
: _nElements(other.size()), _capacity(other.capacity()),
_hashTable(new Bucket[other.capacity()])
{
for (int i = 0; i < other.capacity(); ++i)
{
_hashTable[i] = other._hashTable[i];
}
}
/**
* move copy ctor.
*/
HashMap(HashMap && other) noexcept
{
_hashTable = other._hashTable;
other._hashTable = nullptr;
_nElements = other.size();
_capacity = other.capacity();
}
/**
* HashMap destructor.
*/
~HashMap()
{
delete[] _hashTable;
}
/**
* assignment operator implementation using copy-swap idiom
* @param other object to copy from.
* @return reference of the Map instance after assignment.
*/
HashMap& operator=(HashMap other)
{
_swap(*this, other);
return *this;
}
/**
* @return the number of key,value pairs in the HashMap.
*/
int size() const noexcept {return _nElements; }
/**
* @return capacity of the HashMap.
*/
int capacity() const noexcept {return _capacity; }
/**
* @return bool value stating if the HashMap is empty.
*/
bool empty() const noexcept {return _nElements == 0; }
/**
* Gets a key and a value and inserts them in the HashMap
* @param key of type KeyT
* @param value of type ValueT
* @return true if insertion was successful, false otherwise (if the key already in map).
*/
bool insert(const KeyT &key, const ValueT &value) noexcept
{
if (containsKey(key))
{
return false;
}
_nElements++;
_hashTable[_hash(key)].push_back({key, value}); //copy or move key and val to buck.
if (getLoadFactor() > UPPER_LOAD_FACTOR)
{
_resizeTable(capacity() * TABLE_SIZE_FACTOR);
}
return true;
}
/**
* gets a key and checks if it exist in the HashMap.
* @param key KeyT type
* @return bool stating if the Hashmap contains the key.
*/
bool containsKey(const KeyT &key) const noexcept
{
try
{
_getPairByKey(key);
return true;
}
catch (std::out_of_range& e)
{
return false;
}
}
/**
* Gets a Key and returns the value linked to it in the map, if the key exists in Map.
* @param key KeyT
* @throws if the Key isn't in the map.
* @return reference to the value linked to the key.
*/
ValueT& at(const KeyT &key)
{
return _getPairByKey(key).elem.second;
}
/**
* Gets a Key and returns the value linked to it in the map, if the key exists in Map.
* @param key KeyT
* @throws if the Key isn't in the map.
* @return const reference to the value linked to the key.
*/
const ValueT& at(const KeyT &key) const
{
return _getPairByKey(key).elem.second;
}
/**
* gets a key and erases it and value linked to it.
* @param key KeyT
* @return true if removal was successful, false otherwise.
*/
bool erase(const KeyT key) noexcept
{
try
{
int bucketIdx = _hash(key);
auto it = _hashTable[bucketIdx].begin();
_hashTable[bucketIdx].erase(it + _getPairByKey(key).idxInBucket);
--_nElements;
if (getLoadFactor() < LOWER_LOAD_FACTOR)
{
_resizeTable(capacity() / TABLE_SIZE_FACTOR);
}
return true;
}
catch (std::out_of_range &e)
{
return false;
}
}
/**
* returns the current LoadFactor status
* @return load factor of type double.
*/
double getLoadFactor() const noexcept
{
return (size() / (double) capacity());
}
/**
* gets a key and returns the size (num of elems) in the bucket containing the key.
* if the key isn't in the Map, an exceptions will be raised.
* @param key KeyT
* @return size of bucket of type int.
*/
int bucketSize(const KeyT &key) const
{
return _hashTable[bucketIndex(key)].size();
}
/**
* gets a key and returns the idx of the bucket the the key is in.
* @throws an expection if the key is not in the Map.
* @param key
* @return idx of the bucket the the key is in.
*/
int bucketIndex(const KeyT &key) const
{
if (!containsKey(key))
{
throw std::out_of_range(KEY_NOT_FOUND_MSG);
}
return _hash(key);
}
/**
* removes all the elements in the map, capacity of the map will remain unchanged.
*/
void clear() noexcept
{
for (int i = 0; i < capacity(); ++i)
{
_hashTable[i].clear();
}
_nElements = 0;
}
/**
* access operator, if a given key isn't in map, a new pair containing the key with a default
* value will be created and a reference to the value will be return (and will allow changing
* it).
* @param key - search value in map
* @return reference to the value linked to the map, if the key doesn't exist in map, the new
* pair default value ref will be returned.
*/
ValueT& operator[](const KeyT& key) noexcept
{
try
{
return _getPairByKey(key).elem.second;
}
catch (std::out_of_range &e)
{
ValueT valueDefault = ValueT();
insert(key, valueDefault);
return _getPairByKey(key).elem.second;
}
}
/**
* const access operator, if a given key isn't in map, a random value reference will be
* returned.
* @param key - search value in map
* @return reference to the value linked to the map
*/
const ValueT& operator[](const KeyT& key) const noexcept
{
try
{
return _getPairByKey(key).elem.second;
}
catch (std::out_of_range &e)
{
return cbegin()->second;
}
}
/**
* checks if two HashMap instances have identical sets of values (key-value relation and same
* number of elements)
* @param other another hash map to compare with
* @return true if the same, false otherwise.
*/
bool operator==(const HashMap& other) const
{
if (size() == other.size())
{
try
{
for (auto it = other.cbegin(); it != other.cend(); ++it)
{
if (_getPairByKey(it->first).elem.second != it->second)
{
return false;
}
}
return true;
}
catch (std::out_of_range &e)
{
return false;
}
}
return false;
}
/**
* returns true if there's a difference between the two maps in one of the pairs, of in the
* number of elements stored in them.
*/
bool operator!=(const HashMap& other) const
{
return !((*this) == other);
}
/**
* Const Forward Iterator class to the hashMap.
*/
class const_iterator
{
public:
//iterator traits//
typedef const_iterator self_type;
typedef const _pair* pointer;
typedef const _pair value_type;
typedef const _pair& reference;
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
private:
typedef typename Bucket::const_iterator vectorIterator;
/**
* reference to the HashMap instance linked to this Iterator.
*/
const HashMap &_map;
/**
* current Bucket that the iterator is in.
*/
int _currBucket;
/**
* pointer to the current bucket in the map, kept as a member to save a lot of accesses
* in map.
*/
Bucket *_bucketPtr = nullptr;
/**
* pointer to an pair<KeyT, ValueT> element in the map.
*/
vectorIterator _pairPtr;
/**
* sets the _bucketPtr to the first bucket in HashMap that is not empty,
* and updates the index of that bucket to _currBucket;
*/
void _nextBucket()
{
for (int i = ++_currBucket; i < _map.capacity(); ++i)
{
if (!(_map._hashTable[i]).empty())
{
_bucketPtr = &(_map._hashTable[i]);
_pairPtr = _bucketPtr->cbegin();
_currBucket = i;
return;
}
}
_setEnd();
}
/**
* this function progresses the member of the iterator to the next pair.
* this function makes sure that the iterator won't jump over to the next bucket unless
* we've reached all pairs stored in the current bucket.
*/
void _nextPair()
{
if (++_pairPtr == _bucketPtr->cend())
{
_nextBucket();
}
}
/**
* Sets the end point of the iterator by default to the last bucket end() iterator.
* @return ref to the iterator with updated members.
*/
self_type& _setEnd()
{
_currBucket = _map.capacity() - 1;
_bucketPtr = &_map._hashTable[_currBucket];
_pairPtr = _bucketPtr->cend();
return *this;
}
public:
/**
* finds the first occupied bucket in the HashMap and sets the iterator to point
* at it's first element (pair).
* if the Map is empty than the iterator will point to the cend().
*/
const_iterator(const HashMap& map, int startFromBucket) noexcept
: _map(map), _currBucket(startFromBucket - 1)
{
if (!map.empty())
{
_nextBucket();
}
else
{
_setEnd();
}
}
/**
* returns a reference to a pair
*/
reference operator*() const { return *_pairPtr; }
/**
* returns a pointer to a pair.
*/
pointer operator->() const { return _pairPtr.operator->(); }
/**
* pre increment, i.e move iterator so it will point to the following element in map.
*/
self_type& operator++()
{
_nextPair();
return *this;
}
/**
* post increment to the following pair.
*/
self_type operator++(int)
{
const_iterator tmp = *this; // based on std::vector::iterator "operator=" overload.
_nextPair();
return tmp;
}
/**
* comparison between two iterators.
* @return true iff the iterators points on the same element in map.
*/
bool operator==(const const_iterator &other) const
{
return _pairPtr == other._pairPtr;
}
/**
* @return true iff the iterators points to different elements.
*/
bool operator!=(const const_iterator &other) const
{
return _pairPtr != other._pairPtr;
}
};
/**
* returns const_iterator points to the first Bucket-chronological-order element in map.
*/
const_iterator begin() const noexcept
{
return const_iterator(*this, 0);
}
/**
* returns const_iterator points to the last Bucket-chronological-order element in map.
*/
const_iterator end() const noexcept
{
return const_iterator(*this, capacity());
}
/**
* returns const_iterator points to the first Bucket-chronological-order element in map.
*/
const_iterator cbegin() const noexcept
{
return const_iterator(*this, 0);
}
/**
* returns const_iterator points to the last Bucket-chronological-order element in map.
*/
const_iterator cend() const noexcept
{
return const_iterator(*this, capacity());
}
};
| true |
b32079925f13555e0f2b05f8d2fd13c4f7b733d6 | C++ | Taylor-Reid/CatPicture | /src/CatPictureApp.cpp | UTF-8 | 1,194 | 2.546875 | 3 | [] | no_license | #include "cinder/app/AppBasic.h"
#include "cinder/gl/gl.h"
using namespace ci;
using namespace ci::app;
using namespace std;
const int SURFACE_WIDTH = 1024;
const int SURFACE_HEIGHT = 1024;
class CatPictureApp : public AppBasic {
public:
void setup();
void mouseDown( MouseEvent event );
void update();
void draw();
void drawRect(int x,int y,int height, int width, int red, int green, int blue);
void drawGradientRect(int x,int y,int height, int width, int red1, int green1, int blue1,int red2, int green2, int blue2);
void prepareSettings(Settings* settings);
private:
Surface* mySurface_;
int frameNumber_;
};
void CatPictureApp::prepareSettings(Settings* settings){
(*settings).setWindowSize(640,480);
(*settings).setResizable(false);
}
void CatPictureApp::setup(){
mySurface_ = new Surface(SURFACE_WIDTH,SURFACE_HEIGHT,false);
frameNumber_=0;
}
void CatPictureApp::drawRect(){
}
void CatPictureApp::drawGradientRect(){
}
void CatPictureApp::mouseDown( MouseEvent event )
{
}
void CatPictureApp::update()
{
frameNumber_++;
uint8_t* dataArray = (*mySurface_).getData();
}
void CatPictureApp::draw()
{
}
CINDER_APP_BASIC( CatPictureApp, RendererGl )
| true |
8ac8b8119b6082493938c1f187760aba6f7d755f | C++ | LIMTAECHEON/Study | /enemyManager.h | UHC | 3,214 | 2.65625 | 3 | [] | no_license | #pragma once
#include "gameNode.h"
#include "enemy.h"
#include "minion.h"
#include "minion2.h"
#include "minion3.h"
class bullet;
class rockman;
class stageMap;
class enemyManager: public gameNode
{
private:
typedef vector<enemy*> vEnemy; // ʹ vector
typedef vector<enemy*>::iterator viEnemy;
private:
vEnemy _vMinion; // ⺻ ̴Ͼ
viEnemy _viMinion;
bullet* _bullet; // ( Ѿ)
rockman* _rm; // rockman Ŭ
enemy* _enemy; // enemy Ŭ
image* _boomImg; // ̹
RECT _boomRc; // RECT
POINTFLOAT _boomPos; // ̹ ǥ
image* _itemImg; // ̹
RECT _itemRc; // RECT
POINTFLOAT _itemPos; // ̹ ǥ
float _itemProbeY = 0; // ȼ 浹 Y
int _count = 0; // (ӵ)
int _index = 0; // ()
int _count2 = 0; // (ӵ)
int _index2 = 0; // ()
int _motion = 0; // 浹 ó Ȯ
int _enemyShowCount = 0; // ʹ īƮ
bool _check01 = false; // ʹ ð bool
bool _check02 = false;
bool _check03 = false;
bool _check04 = false;
bool _check05 = false;
bool _check06 = false;
bool _check07 = false;
float _checkX; // , ǥ X ǥ
float _checkY; // , ǥ Y ǥ
float _cameraX; // stageMap _cameraX set
float _cameraY; // stageMap _cameraY set
public:
enemyManager();
~enemyManager();
HRESULT init();
void release();
void update();
void render();
void imageInit(); // ̹ ǥ Լ
void enemyManagerDynamic(); // Ҵ Լ
void setMinion(int type); // enemy Ŭ ǥ, Ÿ Ҵ Լ
void deleteMinion(int enemyNum); // minion Լ
void imageSetFrame(); // ̹ Լ
void minionBulletFire(); // ʹ Լ
void collision(); // ʹ 浹 Լ
void itmePixelCheck(); // ȼ 浹 Լ
void posCheck(float x, float y); // , ǥ Լ
void deleteSpinMinion(); // ʹ Լ
// enemyManager &Լ ٸ Ŭ ϱ get Լ
int getMotion() { return _motion; }
enemy* getEnemy() { return _enemy; }
RECT getItemRc() { return _itemRc; }
vector<enemy*> getVMinion() { return _vMinion; }
vector<enemy*>::iterator getVIMinion() { return _viMinion; }
// Ŭ(stageMap) Set Լ
void setCameraX(float cameraX) { _cameraX = cameraX; }
void setCameraY(float cameraY) { _cameraY = cameraY; }
// rockman Ŭ ִ̾ 巹 ũ Լ
void setRockmanMemoryAddressLink(rockman* player) { _rm = player; }
};
| true |
1e0fbf8a37e5961768a68d3160d33e2bb35b18a0 | C++ | adibyte95/codechef_problems | /chef and chain.cpp | UTF-8 | 629 | 2.9375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t>0)
{
string s;
cin>>s;
int count1=0,count2=0;
int flag1=0,flag2=0;
for(int i=0;i<s.length();i++)
{
if(flag1==1)
{
if(s[i]!='+')
count1++;
flag1=0;
}
else if(flag1==0)
{
if(s[i]!='-')
count1++;
flag1=1;
}
if(flag2==1)
{
if(s[i]!='-')
count2++;
flag2=0;
}
else if(flag2==0)
{
if(s[i]!='+')
count2++;
flag2=1;
}
}
cout<<min(count1,count2)<<endl;
t--;
}
return 0;
}
| true |
a596df0d3b63b53bb49347e88568661b5c82a3ed | C++ | ShereenKhoja/TicTacToeMVP | /ModelViewPresenter_TicTacToe/TicTacToePresenter.h | UTF-8 | 1,090 | 2.625 | 3 | [] | no_license | //***************************************************************************
// File name: TicTacToePresenter.h
// Author: Chadd Williams
// Date: 3/22/2017
// Class: CS485
// Assignment: Model View Presenter Example
// Purpose: Demonstrate how the Model View Presenter is used
// This project was based on some ideas presented here:
// https://github.com/ericmaxwell2003/ticTacToe
//***************************************************************************
#pragma once
#include "TicTacToeModel.h"
#include "ITicTacToePresenter.h"
#include "ITicTacToePresenter.h"
class TicTacToePresenter : public ITicTacToePresenter
{
public:
TicTacToePresenter (ITicTacToeView *pcView) ;
virtual ~TicTacToePresenter () = default;
// from View
virtual void setMove (int x, int y);
virtual void setName1 (std::string name);
virtual void setName2 (std::string name);
virtual void setSymbol1 (std::string);
virtual void setSymbol2 (std::string);
virtual void resetGame ();
private:
ITicTacToeView *mpcTTTView;
TicTacToeModel mcTTTModel;
}; | true |
322f0886dea53a6db91ef065d7c512090799e0e9 | C++ | aaafwd/Online-Judge | /Volume 002 (200-299)/244.cpp | UTF-8 | 4,136 | 2.984375 | 3 | [] | no_license | /* @JUDGE_ID: 19899RK 244 C++ "By Anadan" */
// Train Time
// Accepted (0.000 seconds with low memory spent)
#ifdef ONLINE_JUDGE
#define NDEBUG
#endif
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <vector>
constexpr double eps = 1e-7;
constexpr int kFeetsInMile = 5280;
double max_speed, acceleration, station_delay;
std::vector<double> distances, out_times, moving_times;
constexpr bool eq(double a, double b) {
return (a > b) ? (a - b < eps) : (b - a < eps);
}
void solve() {
const int size = distances.size();
for (int i = size - 1; i > 0; --i) {
distances[i] -= distances[i - 1];
}
bool in_miles;
if (max_speed > 100 && acceleration > 100) {
in_miles = true;
max_speed /= kFeetsInMile;
acceleration /= kFeetsInMile;
} else {
in_miles = false;
for (int i = 1; i < size; ++i) {
distances[i] *= kFeetsInMile;
}
}
// 0 -> max_speed: t1 = max_speed/acceleration; s = acceleration*t1^2/2
// max_speed -> 0: <same>
// middle: t2 = (S - acceleration*t1^2)/max_speed = S/max_speed - t1
// moving_time = t1 + t2 + t1 = t1 + S/max_speed
const double acceleration_time = max_speed / acceleration;
moving_times.resize(size);
moving_times[0] = 0;
for (int i = 1; i < size; ++i) {
const double t2 = distances[i] / max_speed;
assert(t2 >= acceleration_time);
moving_times[i] = acceleration_time + t2;
}
out_times.resize(size);
out_times[0] = 0;
for (int i = 1; i < size; ++i) {
out_times[i] = out_times[i - 1] + moving_times[i] + station_delay;
}
double back_train_time = 0;
int right = size - 1;
for (; right > 0; --right) {
// In-time at pos @(right - 1).
const double in_time_right = back_train_time + moving_times[right];
if (out_times[right - 1] < in_time_right) break;
const double in_time_left = out_times[right - 1] - station_delay;
const double out_time_right = in_time_right + station_delay;
if (out_time_right < in_time_left) {
back_train_time = out_time_right;
continue;
}
// Meeting at pos @(right - 1).
const double meeting_time = std::max(in_time_right, in_time_left);
double distance = 0;
for (int i = 1; i < right; ++i) {
distance += distances[i];
}
if (!in_miles) distance /= kFeetsInMile;
std::printf(
" Meeting time: %.1lf minutes\n Meeting distance: %.3lf miles from "
"metro center hub, in station %d\n",
meeting_time, distance, right - 1);
return;
}
const int left = right - 1;
double distance = 0;
for (int i = 1; i < right; ++i) {
distance += distances[i];
}
double time_diff = out_times[left] - back_train_time;
double meeting_time = out_times[left];
bool count_reverse = false;
if (time_diff < 0) {
time_diff = -time_diff;
meeting_time = back_train_time;
count_reverse = true;
}
time_diff = moving_times[right] - time_diff;
time_diff *= 0.5;
meeting_time += time_diff;
double distance_diff = 0;
if (time_diff <= acceleration_time) {
distance_diff = acceleration * time_diff * time_diff * 0.5;
} else {
time_diff -= acceleration_time;
distance_diff = max_speed * (acceleration_time * 0.5 + time_diff);
}
if (count_reverse) {
distance += distances[right] - distance_diff;
} else {
distance += distance_diff;
}
if (!in_miles) distance /= kFeetsInMile;
std::printf(
" Meeting time: %.1lf minutes\n Meeting distance: %.3lf miles from "
"metro center hub\n",
meeting_time, distance);
}
int main() {
int test_case = 0;
double x;
distances.reserve(32);
out_times.reserve(32);
moving_times.reserve(32);
while (1) {
distances.clear();
while (std::scanf("%lf", &x) == 1 && x) {
if (distances.empty()) {
if (eq(x, -1.0)) break;
distances.push_back(0.0);
}
distances.push_back(x);
}
if (distances.empty()) break;
std::scanf("%lf%lf%lf", &max_speed, &acceleration, &station_delay);
if (test_case++) std::putchar('\n');
std::printf("Scenario #%d:\n", test_case);
solve();
}
return 0;
}
/* @END_OF_SOURCE_CODE */
| true |
26e2af989cd3c986102c5bd5673004c939350202 | C++ | mndarren/Code-Lib | /c_cpp_lib/sorting/Sort.cpp | UTF-8 | 4,742 | 3.703125 | 4 | [
"Apache-2.0"
] | permissive | /*@author Zhao Xie <11/02/2013>
**@file Sort.cpp*/
/*quickSort
Quick Sort sorts in place. Its time is O(n^2) in the worst case but O(NlogN) when each pivot is near the median of its segment.
This section shows two versions of qs_partition(). quicksort() itself sorts the values in the array a[] from index low through index high.
*/
const int MIN_SIZE = 10;
template <class ItemType>
void partition(ItemType a[], int low,int high,
ItemType pivot,int &i,int &j)
{
int lastS1 = low-1;
int firstU = low;
int firstS3 = high+1;
while(firstU<firstS3)
if (a[firstU]<pivot)
exchange(a[firstU++],a[++lastS1]);
else if (a[firstU]==pivot)
++firstU;
else
exchange(a[firstU],a[--firstS3]);
i = lastS1;
j = firstS3;
}
template <class ItemType>
void quickSort(ItemType a[],int low,int high)
{
if (high-low+1 < MIN_SIZE)
insertionSort(a,low,high);
else
{
ItemType pivot=a[low];
int i,j;
partition(a,low,high,pivot,i,j);
quickSort(a,low,i);
quickSort(a,j,high);
}
}
//littleTools
template <class ItemType>
void exchange(ItemType& a,ItemType& b)
{
ItemType temp;
temp = a;
a = b;
b = temp;
}
//insertionSort
template <class ItemType>
void insertionSort(ItemType a[],int low,int high)
{
for(int i=low; i<high;++i)
{
for(int j=i+1; j>low; --j)
if (a[j-1]>a[j])
exchange(a[j-1],a[j]);
else
break;
}
}
/*mergeSort
Merge Sort's time is always O(n log n), but the merge step requires additional space equal to that occupied by the values being sorted.
This function sorts the values in the array a[] from index low through index high.
*/
template <class ItemType>
void merge(ItemType a[],int low,int mid,int high)
{
ItemType b[high+1]; //local copy
int i1 = low;
int i2 = mid+1;
int index = low;
//copy the values into b[]
for (int i=low;i<=high;++i)
b[i] = a[i];
while(i1<=mid&&i2<=high)
{
if (b[i1]<b[i2])
a[index++] = b[i1++];
else
a[index++] = b[i2++];
}
while(i1<=mid)
a[index++] = b[i1++];
while(i2<=high)
a[index++] = b[i2++];
}
template <class ItemType>
void mergeSort(ItemType a[],int low,int high)
{
if(low<high)
{
int mid = low + (high-low)/2;
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
merge(a,low,mid,high);
}
}
//bubbleSort
template <class ItemType>
void bubbleSort(ItemType a[],int low,int high)
{
bool sorted = false;
for(int i=low+1,k=1;!sorted&&i<=high;i++,k++)
{
sorted = true;
for (int j=low;j<=high-k;j++)
{
if(a[j]>a[j+1])
{
exchange(a[j],a[j+1]);
sorted = false;
}//end if
}//end for
}//end for
}
//selectionSort
template <class ItemType>
void selectionSort(ItemType a[],int low,int high)
{
for(int last = high;last>=low+1;last--)
{
int largest = findIndexofLargest(a,low,last);
exchange(a[largest],a[last]);
}
}
template <class ItemType>
int findIndexofLargest(ItemType a[],int low,int high)
{
int index = low;
for (int i=low+1;i<=high;i++)
if (a[index]<a[i])
index = i;
return index;
}
//radixSort
template <class ItemType>
void radixSort(ItemType a[],int low,int high)
{
int radix = 10;
//compute digits
int digits = 1;
int largest = a[low];
for (int i=low+1;i<=high;i++)
if (largest<a[i])
largest = a[i];
int flag = 1;
while(flag)
{
largest = largest/radix;
if (largest != 0)
digits++;
else
flag = 0;
}
radixS(a,low,high,radix,digits);
}
template <class ItemType>
void radixS(ItemType a[],int low,int high,int radix,int digits)
{
LinkedQueue<int> q[radix];
int factor = 1;
int digit;
int index;
for (int k=0;k<digits;++k)
{
for (int i=low;i<=high;++i)
{
digit = (a[i]/factor)%radix;
(q[digit]).enqueue(a[i]);
}
index = low;
for (int d=0;d<radix;++d)
while(!(q[d]).empty())
a[index++] = (q[d]).dequeue();
factor = factor*radix;
}
}
/*heapSort:
Heap Sort sorts in place and its time is always O(n log n).
This function sorts the items in the array a[] from index 0 to index n-1.
*/
template <class ItemType>
void heapSort(ItemType a[],int n)
{
// Build the heap in a[0..n-1].
for (int i=(n-2)/2; i>=0;--i)
walk_down(a,i,n-1);
// Tear the heap down.
for(int i=n-1;i>0;--i)
{
exchange(a[0],a[i]);
walk_down(a,0,i-1);
}
}
// Swaps the element initially in a[root] DOWN until the
// heap property is restored. a[last] is the last data item.
template <class ItemType>
void walk_down(ItemType a[],int parent,int last)
{
int max_child;
bool done=false;
while(2*parent+1<=last && !done)
{
max_child=2*parent+1;
if(a[max_child+1]>a[max_child])
++max_child;
if(max_child<last&&a[max_child]>a[parent])
{
exchange(a[max_child],a[parent]);
parent = max_child;
}
else
done=true;
}
} | true |
9623c9eb838009ab9746f2d8572e8dd956ef6c4e | C++ | oooooverflow/MyPainting | /161220126_系统工程/二维图元项目/项目文件/polygon.cpp | UTF-8 | 1,995 | 3.015625 | 3 | [] | no_license | #include "polygon.h"
#include <qmath.h>
#include <QDebug>
MyPolygon::MyPolygon(double angle)
{
this->angle = angle;
}
void MyPolygon::drawMyself(QImage *image, QColor* color) {
MyLine *tmp = new MyLine();
if(isdone) // 如果完成闭合,则连接最后一个点与第一个点
tmp->setPoint(lines[lines.size()-1], lines[0]);
else // 闭合未完成,连接当前点与上一个点
tmp->setPoint(lines[lines.size()-2], lines[lines.size()-1]);
tmp->drawMyself(image, color);
}
void MyPolygon::drawTheTotal(QImage *image, QColor* color) {
int x1, x2, y1, y2;
int sumx = 0, sumy = 0;
MyLine* tmp = new MyLine();
for(int i = 0; i < lines.size(); i++) {
sumx += lines[i].x();
sumy += lines[i].y();
}
int center_x = sumx / lines.size();
int center_y = sumy / lines.size();
for(int i = 0; i < lines.size(); i++) {
if(i == lines.size()-1) {
x1 = getNewX(lines[i].x(), center_x, lines[i].y(), center_y, angle);
y1 = getNewY(lines[i].x(), center_x, lines[i].y(), center_y, angle);
x2 = getNewX(lines[0].x(), center_x, lines[0].y(), center_y, angle);
y2 = getNewY(lines[0].x(), center_x, lines[0].y(), center_y, angle);
}
else {
x1 = getNewX(lines[i].x(), center_x, lines[i].y(), center_y, angle);
y1 = getNewY(lines[i].x(), center_x, lines[i].y(), center_y, angle);
x2 = getNewX(lines[i+1].x(), center_x, lines[i+1].y(), center_y, angle);
y2 = getNewY(lines[i+1].x(), center_x, lines[i+1].y(), center_y, angle);
}
tmp->setPoint(QPoint(x1,y1), QPoint(x2,y2));
tmp->drawMyself(image, color);
}
}
int MyPolygon::getNewX(int x, int xr, int y, int yr, double angle) {
return (int)(xr+(x-xr)*qCos(angle)-(y-yr)*qSin(angle));
}
int MyPolygon::getNewY(int x, int xr, int y, int yr, double angle) {
return (int)(yr+(x-xr)*qSin(angle)+(y-yr)*qCos(angle));
}
| true |
ead6d521da49e6c9174db048d99e61d2f6d560ab | C++ | yannik-schmitzer/hrw | /Gartenplaner/graphicsscene.h | UTF-8 | 1,792 | 2.5625 | 3 | [] | no_license | #ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <QDropEvent>
#include <QLabel>
#include <QPixmap>
#include <QMimeData>
#include <QGraphicsRectItem>
#include <QGraphicsProxyWidget>
class GraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
/**
* @brief Constructor
* @param parent is the hierarchical preciding object and is null by default
*/
explicit GraphicsScene(QObject *parent = nullptr);
/**
* @brief This method reacts on the pressed mouse.
* @param mouseEvent is the corresponding event and contains details about it (i.e. positions).
*/
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
/**
* @brief This method reacts on the released mouse, after a press.
* @param mouseEvent is the corresponding event and contains details about it (i.e. positions).
*/
void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
/**
* @brief This method reacts on the moved mouse.
* @param mouseEvent is the corresponding event and contains details about it (i.e. positions).
*/
void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent);
/**
* @brief m_x and m_y to save position values
*/
int m_x,m_y;
signals:
/**
* @brief mousePressed signal to mainwindow
* @param xPos
* @param yPos
*/
void mousePressed(int xPos, int yPos);
/**
* @brief mouseReleased signal to mainwindow
* @param xPos
* @param yPos
*/
void mouseReleased(int xPos, int yPos);
/**
* @brief mouseMoved signal to mainwindow
* @param xPos
* @param yPos
*/
void mouseMoved(int xPos, int yPos);
};
#endif // GRAPHICSSCENE_H
| true |
b05b399e0565db6a5183a74b04763f93bfa946be | C++ | xFlowDev/2D-RPG-Game | /SfmlTest/SfmlTest/Game.hpp | ISO-8859-1 | 1,284 | 2.65625 | 3 | [] | no_license | #pragma once
#ifndef GAME_H
#define GAME_H
#include <chrono>
#include <iostream>
#include "Variables.hpp"
#include "GameScreen.hpp"
#include "MenuScreen.hpp"
class Game {
public:
Game();
~Game();
void GameLoop();
private:
sf::RenderWindow GameWindow;
sf::View view;
GameState GameState;
MenuScreen menuScreen;
GameScreen gameScreen;
//timer: Fr das Messen der Zeit vom ersten Starten des GameLoops
//currentTime: enthllt immer die Zeit zu der die Updates gemessen werden
//newTime: immer der Zeitpunkt am Anfang des GameLoop
//now: Fr das Abmessen einer Sekunde um die Updates/s und FPS zu messen
TIME_POINT timer, currentTime, newTime, now;
//frameTime: Die Zeit die ein Frame/Update bentigt
//diff: Zum Abmessen einer Sekunde, wenn diff grer als 1s ist dann wird die Anzahl der UPS und FPS ausgegeben
DURATION frameTime, diff;
double dt, accumulator;
int Updates, FPS;
const int DebugFontSize = 18;
sf::Color DebugTextColor = sf::Color::White;
sf::Font DebugFont;
sf::Vector2f FpsTextPosition = sf::Vector2f(0.f, 0.f);
sf::Text FpsText;
sf::Vector2f UpdatesTextPosition = sf::Vector2f(0.f, DebugFontSize + 6.f);
sf::Text UpdatesText;
void Update();
void Draw();
void setDebugText();
void setDebugTextPosition();
};
#endif // !GAME_H | true |
282f57ce481c74f94538dc5f2577f91f596ab903 | C++ | Lepidora/Xylena | /Texture.h | UTF-8 | 1,834 | 2.96875 | 3 | [] | no_license | #pragma once
//System includes
#include <vector>
#include <memory>
//OpenGL include
#include "OpenGL.h"
//Local includes
#include "GLTypes.h"
namespace Xylena {
//Structs
/*struct TextureImage {
std::vector<char> data;
int width;
int height;
};*/
//Typedefs
//typedef GLuint TextureImage;
class Texture {
protected:
///Stores an index for keeping track of animated textures
unsigned long index;
///Stores an array of images for rendering animated textures
std::vector<TextureImage> images;
public:
Texture();
~Texture() {};
///Gets the image at the current value of index, then increments index. This is also used to get the texture if only one texture image is stored
TextureImage getNextTexture();
void tickAnimation();
///Gets the texture at the specified index. Throws std::out_of_bounds if the given index is larger than the size of the images vector
TextureImage getTextureAtIndex(unsigned long _index);
///Sets the texture at the specified index. Throws std::out_of_bounds if the given index is larger than the size of the images vector
void setTextureAtIndex(TextureImage textureID, unsigned long _index);
///Adds a texture to the end of the images vector
void addTexture(TextureImage textureID);
///Increment and decrement index by a given amount. If the amount given is larger than the size of the images vector, it will wrap around
void incrementIndex(unsigned long amount);
void decrementIndex(unsigned long amount);
///Set index to the given index. Throws std::out_of_bounds if the given index is larger than the size of the images vector
void setIndex(unsigned long _index);
};
//Typedefs
typedef std::shared_ptr<Texture> TexturePtr;
}
| true |
af85a0a49be064b4cbb271b9f414968138afa196 | C++ | bednikova/SDP | /LinkedQueue/main.cpp | UTF-8 | 298 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include "LinkedQueue.h"
using namespace std;
int main()
{
LinkedQueue<int> queue;
queue.enqueue(3);
queue.enqueue(55);
queue.enqueue(455);
while(!queue.isEmpty())
{
cout << queue.first() << " ";
queue.dequeue();
}
return 0;
}
| true |
5f6f78208ad2a4de0e6defdd608d1429fb8ca025 | C++ | thedm/esp-mqtt-nodes | /template/template.ino | UTF-8 | 3,439 | 2.6875 | 3 | [] | no_license | /**
* ESP MQTT sensornode example.
*
* Example ESP node that reads sensors and publishes the data to
* MQTT.
*
* Usage:
*
* 1. Update all <------------> parts with your sensor specific code.
* 2. Update/extend settings.h
* 3. Create a credentials.h with all passwords. See settings.h for
* corresponding comments. Do not commit this header file.
*/
#include <Arduino.h>
#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <PubSubClient.h>
#include "settings.h"
#include "credentials.h"
ESP8266WiFiMulti wifiMulti;
WiFiClientSecure wclient;
PubSubClient client(mqttHost, mqttPort, wclient);
// Define sensors here. For example:
// DHT dht11(D3, DHT11);
// <------------>
void setup() {
Serial.begin(115200);
delay(100);
Serial.println();
// Initialize sensors. For example:
// dht11.begin();
// <------------>
// Add wifi networks. wifiMulti supports multiple networks.
// and retries to connect to all of them until it succeeds.
wifiMulti.addAP(ssid0, ssid0Password);
wifiMulti.addAP(ssid1, ssid1Password);
// Wait till connected.
while(wifiMulti.run() != WL_CONNECTED){
Serial.println("WiFi connection failed, retrying.");
delay(500);
}
// Initialize OTA updates. Must `begin` after wifiMulti.run.
// OTA does not work reliable with all ESP boards (WiMos works well).
// Restart of Arduino IDE might be required before node appears.
ArduinoOTA.setHostname(sensorHostname);
ArduinoOTA.setPassword(otaPassword);
ArduinoOTA.begin();
}
bool measureAndPublish() {
// Read sensors and publish to MQTT
// Wifi and client are connected when this function is called.
// Return false when reading failed, to retry faster then the normal
// update cycle.
// <------------>
// Example function:
// float t = dht11.readTemperature();
// if (isnan(t)) {
// Serial.print("[DHT11] no temperature or humidity\n");
// return false;
// }
// Serial.print("[DHT11]");
// Serial.println(t);
// // Send to MQTT as float with 1 decimal.
// client.publish(mqttSensorTopic, String(t, 1).c_str());
// return true;
}
unsigned long lastUpdate = 0;
void loop() {
if(wifiMulti.run() != WL_CONNECTED) {
Serial.println("WiFi not connected!");
delay(1000);
return;
}
// else connected
ArduinoOTA.handle();
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(sensorHostname, mqttUser, mqttPassword)) {
Serial.println("Connected to MQTT server, checking cert");
if (wclient.verify(mqttFingerprint, mqttHost)) {
Serial.println("certificate matches");
} else {
Serial.println("certificate doesn't match");
client.disconnect();
delay(10000);
return;
}
} else {
Serial.println("Could not connect to MQTT server");
delay(1000);
return;
}
}
if (client.connected()) {
client.loop();
if (millis() - lastUpdate >= updateInterval) {
if (measureAndPublish()) {
lastUpdate = millis();
} else {
// retry earlier on error
lastUpdate = millis() - updateInterval + retyInterval;
}
}
}
}
| true |
57955d83f77dce165e356fe2bfb561ee139e26a5 | C++ | pnorbert/adiosvm | /Tutorial/gs-mpiio/simulation/writer.cpp | UTF-8 | 4,274 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "writer.h"
#include <iostream>
#define CHECK_ERR(func) \
{ \
if (err != MPI_SUCCESS) \
{ \
int errorStringLen; \
char errorString[MPI_MAX_ERROR_STRING]; \
MPI_Error_string(err, errorString, &errorStringLen); \
printf("Error at line %d: calling %s (%s)\n", __LINE__, #func, \
errorString); \
} \
}
Writer::Writer(const Settings &settings, const GrayScott &sim,
const MPI_Comm comm)
: settings(settings), comm(comm)
{
// #IO# make initializations, declarations as necessary
// information from settings
// <double>("F", settings.F);
// <double>("k", settings.k);
// <double>("dt", settings.dt);
// <double>("Du", settings.Du);
// <double>("Dv", settings.Dv);
// <double>("noise", settings.noise);
// 3D variables
// <double> U, V
// global dimensions: {settings.L, settings.L, settings.L},
// starting offset: {sim.offset_z, sim.offset_y, sim.offset_x},
// local block size: {sim.size_z, sim.size_y, sim.size_x}
// u and v has ghost cells
// local memory block size: {sim.size_z + 2, sim.size_y + 2, sim.size_x + 2}
// output data starts at offset: {1, 1, 1}
// information: <int> step is a single value
/*
* MPI Subarray data type for writing/reading parallel distributed arrays
* See case II for array with ghost cells:
* https://wgropp.cs.illinois.edu/courses/cs598-s15/lectures/lecture33.pdf
*/
int fshape[3] = {(int)settings.L, (int)settings.L, (int)settings.L};
int fstart[3] = {(int)sim.offset_z, (int)sim.offset_y, (int)sim.offset_x};
int fcount[3] = {(int)sim.size_z, (int)sim.size_y, (int)sim.size_x};
err = MPI_Type_create_subarray(3, fshape, fcount, fstart, MPI_ORDER_C,
MPI_DOUBLE, &filetype);
CHECK_ERR(MPI_Type_create_subarray for file type)
err = MPI_Type_commit(&filetype);
CHECK_ERR(MPI_Type_commit for file type)
}
void Writer::open(const std::string &fname)
{
int cmode;
MPI_Info info;
MPI_Offset headersize = sizeof(header);
/* Users can set customized I/O hints in info object */
info = MPI_INFO_NULL; /* no user I/O hint */
/* set file open mode */
cmode = MPI_MODE_CREATE; /* to create a new file */
cmode |= MPI_MODE_WRONLY; /* with write-only permission */
/* collectively open a file, shared by all processes in MPI_COMM_WORLD */
std::string s = fname + ".u";
err = MPI_File_open(comm, s.c_str(), cmode, info, &fh);
CHECK_ERR(MPI_File_open to write)
int rank;
MPI_Comm_rank(comm, &rank);
if (!rank)
{
unsigned long long L = static_cast<unsigned long long>(settings.L);
struct header h = {L, L, L};
MPI_Status status;
MPI_File_write(fh, &h, sizeof(h), MPI_BYTE, &status);
}
err =
MPI_File_set_view(fh, headersize, MPI_DOUBLE, filetype, "native", info);
CHECK_ERR(MPI_File_set_view)
MPI_Barrier(comm);
}
void Writer::write(int step, const GrayScott &sim)
{
/* sim.u_ghost() provides access to the U variable as is */
/* sim.u_noghost() provides a contiguous copy without the ghost cells */
const std::vector<double> &u = sim.u_noghost();
const std::vector<double> &v = sim.v_noghost();
MPI_Status status;
int nelem = (int)(sim.size_z * sim.size_y * sim.size_x);
err = MPI_File_write_all(fh, u.data(), nelem, MPI_DOUBLE, &status);
CHECK_ERR(MPI_File_write_all)
}
void Writer::close()
{
/* collectively close the file */
err = MPI_File_close(&fh);
CHECK_ERR(MPI_File_close);
}
void Writer::print_settings()
{
std::cout << "Simulation writes data using engine type: "
<< "native MPI-IO" << std::endl;
}
| true |
1b5dabb69b20c0503b9ea0749b986848a2cdd008 | C++ | rustushki/asgard | /distro/src/graphicsEngine/Animation.h | UTF-8 | 1,941 | 3.03125 | 3 | [] | no_license | #ifndef ANIMATION_H
#define ANIMATION_H
#include "externals.h"
#include "AnimationState.h"
#include "RectBlitter.h"
class Animation
{
private:
// Helper for Constructors. Initialize Animation members.
void init(uint width, uint height, uint sps, uint ssRows, uint ssCols);
// Status of animation for observation.
AnimationState status;
// Still Dimensions
uint height, width;
// Number of frames since last still update.
uint frameCounter;
// Still being displayed currently.
uint currentStill;
// Rate at which stills are updated. Stills per second.
uint sps;
// Sprite Sheet. Hot Pink is transparent.
std::shared_ptr<SDL_Surface> spriteSheet;
// Dimensions of spritesheet.
uint ssCols, ssRows;
public:
// Constructor. Makes sprite sheet by reading a File.
Animation(std::string filename, uint width, uint height, uint sps,
uint ssRows, uint ssCols);
// Constructor. Makes sprite sheet with an SDL_Surface*
Animation(SDL_Surface* surf, uint width, uint height, uint sps, uint
ssRows, uint ssCols);
// Constructor. Makes sprite sheet and assumes there is only 1 frame.
Animation(SDL_Surface* surf);
// Updates the current still.
void advance();
// Adds 1 to the frame counter.
void incFrameCounter();
// Returns true when the animation is ready to advace.
bool needsUpdate();
// Blits this animation to the screen, updating the provided rect on the
// screen.
void updateRect(SDL_Rect r, uint offsetX, uint offsetY);
// Return the total count of stills for the assigned spritesheet.
uint getStillCount();
// Accessors.
uint getWidth();
uint getHeight();
uint getSPS();
AnimationState getStatus();
// Mutators.
void setSPS(uint sps);
};
#endif//ANIMATION_H
| true |
188774c70ced8b6c1fbdf7459eea3cc3c4179ae3 | C++ | LargeDumpling/Programming-Contest | /OnlineJudges/UVa(29)/10003 Cutting Sticks/code.cpp | UTF-8 | 815 | 2.65625 | 3 | [] | no_license | /*
Author: LargeDumpling
Email: LargeDumpling@qq.com
Edit History:
2015-11-30 File created.
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int L,n,num[55],f[55][55];
int min(int a,int b)
{
return ((a)<(b)?(a):(b));
}
int dp(int l,int r)
{
if(f[l][r]!=-1)return f[l][r];
if(l==r)return (f[l][r]=0);
f[l][r]=2147483647;
for(int i=l;i<r;i++)
f[l][r]=min(f[l][r],dp(l,i)+dp(i+1,r)+num[r]-num[l-1]);
return f[l][r];
}
int main()
{
freopen("code.in","r",stdin);
freopen("code.out","w",stdout);
while(scanf("%d",&L)==1&&L)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
num[n+1]=L;
memset(f,-1,sizeof(f));
printf("The minimum cutting is %d.\n",dp(1,n+1));
}
fclose(stdin);
fclose(stdout);
return 0;
}
| true |
2ace0649dc14754e7b2aa407108051a9744e51ea | C++ | adityaXXX/Spoj | /ABCPATH.cpp | UTF-8 | 2,184 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int X[8] = {1, 1, 1, 0, 0, -1, -1, -1};
int Y[8] = {0, 1, -1, 1, -1, 0, -1, 1};
int a[51][51];
bool visited[51][51];
int moves[51][51];
int h, w, Max = 0;
void dfs(int x, int y){
visited[x][y] = true;
int Tx, Ty;
for(int i = 0; i < 8; i++){
// std::cout << "Parent = " << x << " " << y << '\n';
Tx = x + X[i];
Ty = y + Y[i];
// std::cout << "Child = " << Tx << " " << Ty << '\n';
if(Tx < h && Tx >= 0 && Ty < w && Ty >= 0){
// std::cout << "In Limits = " << Tx << " " << Ty << '\n';
if(!visited[Tx][Ty] && a[Tx][Ty] == a[x][y] + 1){
moves[Tx][Ty] = moves[x][y] + 1;
if(moves[Tx][Ty] > Max)
Max = moves[Tx][Ty];
// std::cout << "In = " << Tx << " " << Ty << '\n';
dfs(Tx, Ty);
}
}
}
}
int main(){
for(int z = 1; ; z++){
std::cin >> h >> w;
if(h == 0 && w == 0)
break;
string s;
bool flag = false;
Max = 0;
std::vector<pair<int, int>> v;
for(int i = 0; i < h; i++){
std::cin >> s;
for(int j = 0; j < w; j++){
a[i][j] = s[j] - 65;
if(a[i][j] == 0){
v.push_back(make_pair(i, j));
flag = true;
}
}
}
memset(visited, false, sizeof(visited));
memset(moves, 0, sizeof(moves));
for(int i = 0; i < v.size(); i++){
dfs(v[i].first, v[i].second);
}
// std::cout << "Original" << '\n';
// for(int i = 0; i < h; i++){
// for(int j = 0; j < w; j++)
// std::cout << a[i][j] << ' ';
// std::cout << '\n';
// }
// std::cout << "Moves" << '\n';
// for(int i = 0; i < h; i++){
// for(int j = 0; j < w; j++)
// std::cout << moves[i][j] << ' ';
// std::cout << '\n';
// }
// std::cout << "Visited" << '\n';
// for(int i = 0; i < h; i++){
// for(int j = 0; j < w; j++)
// std::cout << visited[i][j] << ' ';
// std::cout << '\n';
// }
// std::cout << "Max = " << Max + 1 << '\n';
if(Max == 0 && !flag)
std::cout << "Case " << z << ": " << Max << '\n';
else
std::cout << "Case " << z << ": " << ++Max << '\n';
}
}
| true |
117918bdf83a55b5ebdbf041cbd8921ede7f7f93 | C++ | supercamel/EmbeddedToolKit | /examples/sigslot/main.cpp | UTF-8 | 1,000 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <etk/etk.h>
using namespace std;
/**
Signals and slots are very useful in event-driven programming because they
provide an easy way of de-coupling event sources from event handlers.
Here's an example
You have a temperature controller beer brewer. You have a temperature sensor
and a heater element that needs to turn off at the right temperature.
*/
class TempSensor
{
public:
void check_temperature()
{
something_detected_signal.emit(10.5);
}
etk::Signal1<void, float> something_detected_signal;
};
class Controller
{
public:
Controller() :
something_measured_slot(this, &Controller::on_something_measured)
{
}
void on_something_measured(float m)
{
cout << "measured " << m << endl;
}
etk::Slot1<Controller, void, float> something_measured_slot;
};
int main()
{
TempSensor sensor;
Controller controller;
sensor.something_detected_signal.connect(controller.something_measured_slot);
sensor.check_temperature();
}
| true |
065361fd6798f286c8804b6e2752ef4a87244964 | C++ | NazarPonochevnyi/Programming-Labs | /Programming/Sem1/Lab8/lab8_with_templates/module.h | UTF-8 | 1,711 | 3.515625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*
14. Використовувати (лінійні) односпрямовані списки без заголовної
ланки (мал. а) або з заголовною ланкою (мал. б) при наступному їхньому
описі
Параметр L позначає список, а параметри Е, Е1 — дані типу ТЕ, до яких
можна застосовувати операції присвоювання і перевірки на рівність. {ТЕ =
double}
Визначити рекурсивні функції, що:
а) визначає, чи входить елемент Е в список L;
б) підраховує число входжень елемента Е в список L;
в) знаходить максимальний елемент непорожнього списку L;
г) заміняє в списку L всі входження E1 на E2;
д) виводить список у файл.
*/
template <typename T>
struct Node {
Node<T>* prev;
T data;
Node<T>* next;
};
template <typename T>
Node<T> create_list();
template <typename T>
void append_item(Node<T> &L, T item);
template <typename T>
bool in_list(Node<T> &L, T item);
template <typename T>
unsigned int count_item(Node<T> &L, T item, unsigned int amount = 0);
template <typename T>
T max_item(Node<T> &L);
template <typename T1, typename T2>
void replace_item(Node<T1> &L, T1 item1, T2 item2);
template <typename T>
void write_to_file(Node<T> &L, string filename, string result = "");
template <typename T>
void show_list(Node<T> &L, string result = "");
| true |
b58034b7ef31399cfdc18cb576fe8204f87b79e5 | C++ | vmware/concord-bft | /storage/include/memorydb/client.h | UTF-8 | 5,463 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2018-2019 VMware, all rights reserved
// Objects of ClientIterator contain an iterator for the in memory
// object store (implemented as a map) along with a pointer to the map.
//
// Objects of Client are implementations of an in memory database
// (implemented as a map).
//
// The map contains key value pairs of the type KeyValuePair. Keys and values
// are of type Sliver.
#pragma once
#include <map>
#include "util/sliver.hpp"
#include "key_comparator.h"
#include "storage/db_interface.h"
#include <functional>
#include "log/logger.hpp"
#include "storage/storage_metrics.h"
namespace concord {
namespace storage {
namespace memorydb {
class Client;
typedef std::function<bool(const Sliver &, const Sliver &)> Compare;
typedef std::map<Sliver, Sliver, Compare> TKVStore;
class ClientIterator : public concord::storage::IDBClient::IDBClientIterator {
friend class Client;
public:
ClientIterator(Client *_parentClient)
: logger(logging::getLogger("concord.storage.memorydb")), m_parentClient(_parentClient) {}
virtual ~ClientIterator() {}
// Inherited via IDBClientIterator
KeyValuePair first() override;
KeyValuePair last() override;
KeyValuePair seekAtLeast(const Sliver &_searchKey) override;
KeyValuePair seekAtMost(const Sliver &_searchKey) override;
KeyValuePair previous() override;
KeyValuePair next() override;
KeyValuePair getCurrent() override;
bool isEnd() override;
Status getStatus() override;
private:
logging::Logger logger;
// Pointer to the Client.
Client *m_parentClient;
// Current iterator inside the map.
TKVStore::const_iterator m_current;
};
// In-memory IO operations below are not thread-safe.
// get/put/del/multiGet/multiPut/multiDel operations are not synchronized and
// not guarded by locks. The caller is expected to use those APIs via a
// single thread.
//
// The default KeyComparator provides lexicographical ordering. If 'a' is shorter than 'b' and they match up to the
// length of 'a', then 'a' is considered to precede 'b'.
class Client : public IDBClient {
public:
Client(const KeyComparator &comp = KeyComparator{})
: logger(logging::getLogger("concord.storage.memorydb")),
comp_(comp),
map_([this](const Sliver &a, const Sliver &b) { return comp_(a, b); }) {}
void init(bool readOnly = false) override;
concordUtils::Status get(const Sliver &_key, Sliver &_outValue) const override;
concordUtils::Status get(const Sliver &_key, char *&buf, uint32_t bufSize, uint32_t &_size) const override;
concordUtils::Status has(const Sliver &_key) const override;
virtual IDBClientIterator *getIterator() const override;
virtual concordUtils::Status freeIterator(IDBClientIterator *_iter) const override;
virtual concordUtils::Status put(const Sliver &_key, const Sliver &_value) override;
virtual concordUtils::Status del(const Sliver &_key) override;
concordUtils::Status multiGet(const KeysVector &_keysVec, ValuesVector &_valuesVec) override;
concordUtils::Status multiPut(const SetOfKeyValuePairs &_keyValueMap, bool sync = false) override;
concordUtils::Status multiDel(const KeysVector &_keysVec) override;
concordUtils::Status rangeDel(const Sliver &_beginKey, const Sliver &_endKey) override;
bool isNew() override { return true; }
ITransaction *beginTransaction() override;
TKVStore &getMap() { return map_; }
void setAggregator(std::shared_ptr<concordMetrics::Aggregator> aggregator) override {
storage_metrics_.setAggregator(aggregator);
}
/*
* A metrics class for the in memory storage type.
* We collect the metrics in the same way we do in the whole project; Once an operation has been executed we count it
* in a local metric variable and once in a while we update the aggregator.
* Recall that the in memory db is quite simple and therefor it has only few relevant metrics to collect.
*/
class InMemoryStorageMetrics : public StorageMetricsBase {
public:
InMemoryStorageMetrics()
: StorageMetricsBase({"storage_inmemory", std::make_shared<concordMetrics::Aggregator>()}, 100),
keys_reads_(metrics_.RegisterAtomicCounter("storage_inmemory_total_read_keys")),
total_read_bytes_(metrics_.RegisterAtomicCounter("storage_inmemory_total_read_bytes")),
keys_writes_(metrics_.RegisterAtomicCounter("storage_inmemory_total_written_keys")),
total_written_bytes_(metrics_.RegisterAtomicCounter("storage_inmemory_total_written_bytes")) {
metrics_.Register();
update_metrics_ = std::make_unique<concord::util::PeriodicCall>([this]() { updateMetrics(); },
update_metrics_interval_millisec_);
}
~InMemoryStorageMetrics() {}
void updateMetrics() override { metrics_.UpdateAggregator(); }
concordMetrics::AtomicCounterHandle keys_reads_;
concordMetrics::AtomicCounterHandle total_read_bytes_;
concordMetrics::AtomicCounterHandle keys_writes_;
concordMetrics::AtomicCounterHandle total_written_bytes_;
};
InMemoryStorageMetrics &getStorageMetrics() { return storage_metrics_; }
private:
logging::Logger logger;
// Keep a copy of comp_ so that it lives as long as map_
KeyComparator comp_;
// map that stores the in memory database.
TKVStore map_;
// Metrics
mutable InMemoryStorageMetrics storage_metrics_;
};
} // namespace memorydb
} // namespace storage
} // namespace concord
| true |
1a49cb16b9a8ef5b90cd7724ab5de06b084b9f21 | C++ | guitar0322/MegamanX4-mod | /Projectile.cpp | UTF-8 | 1,587 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "Projectile.h"
void Projectile::Init(string targetTag, string hitEffectName, int damage, float activeLimit)
{
_targetTag = TAGMANAGER->GetTag(targetTag);
_hitEffectName = hitEffectName;
_damage = damage;
_activeLimit = activeLimit;
_activeTime = 0;
_isNeedEffectDir = false;
}
void Projectile::Update()
{
_activeTime += TIMEMANAGER->getElapsedTime();
if (_activeTime >= _activeLimit) {
gameObject->SetActive(false);
_activeTime = 0;
}
}
void Projectile::OnTriggerEnter(GameObject* gameObject)
{
if (gameObject->tag == _targetTag) {
this->gameObject->SetActive(false);
if (_hitEffectName.compare("none") != 0) {
if (_isNeedEffectDir == true) {
string effectName = _hitEffectName;
if (_dir == false)
effectName.append("_right");
else
effectName.append("_left");
EffectManager::getInstance()->EmissionEffect(effectName, transform->GetX(), transform->GetY());
}
else {
EffectManager::getInstance()->EmissionEffect(_hitEffectName, transform->GetX(), transform->GetY());
}
}
gameObject->GetComponent<ObjectInfo>()->Damage(_damage);
}
}
void Projectile::Fire(int x, int y, bool dir)
{
_dir = dir;
_activeTime = 0;
transform->SetPosition(x, y);
gameObject->GetComponent<BoxCollider>()->prevCol.clear();
if (dir == false) {
gameObject->GetComponent<Animator>()->SetClip(
gameObject->GetComponent<Animator>()->GetClip("right")
);
}
else {
gameObject->GetComponent<Animator>()->SetClip(
gameObject->GetComponent<Animator>()->GetClip("left")
);
}
gameObject->SetActive(true);
}
| true |
8e38b5d1fae719d55175420b858dbb5021493d6a | C++ | KillerOfFriend/PersonalTests | /TreeModel/Models/TableModel.h | UTF-8 | 3,287 | 2.890625 | 3 | [] | no_license | #ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <memory>
#include <map>
#include <QAbstractTableModel>
#include <QDateTime>
#include <QObject>
namespace Models
{
//-----------------------------------------------------------------------------
class TTableItem : public QObject
{
Q_OBJECT
public:
TTableItem(QObject* inParent = nullptr); // Конструктор по умолчанию
~TTableItem(); // Диструктор
void setItemID(quint64 inID); // Метод задаст ID айтема
quint64 itemID(); // Метод вернёт ID айтема
void setItemName(QString inName); // Метод задаст имя айтема
QString itemName(); // Метод вернёт имя айтема
void setItemDateTime(QDateTime inDateTime); // Метод задаст время\дату айтема
QDateTime itemDateTime(); // Метод вренёт время\дату айтема
void setItemDouble(double inDouble); // Метод задаст Double значение айтема
double itemDouble(); // Метод вернёт Double значение айтема
private:
quint64 fID = 0; // ID айтема
QString fName = ""; // Имя айтема
QDateTime fDateTime; // Время\дата
double fDouble = 0.0; // Double значение
};
//-----------------------------------------------------------------------------
class TTableModel : public QAbstractTableModel, public std::map<quint64, std::shared_ptr<TTableItem>>
{
Q_OBJECT
public:
enum class eColIndex : quint8 { ciID = 0, ciName, ciDateTime, ciDouble, ciColCount }; // Список столбцов модели
TTableModel(QObject* inParent = nullptr); // Конструктор по умолчанию
~TTableModel(); // Диструктор
// Методы требующие обязательной реализации
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; // Метод вернтёт количество строк (элементов) указанного айтема
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; // Метод вернёт колчиестов столбцов указанного айтема
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; // Метод вернёт данные по индексу указанного айтема
// Переопределённые методы
virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; // Метод вернёт данные для указанного столбца
// Свои методы
bool init(); // Метод инициализирует модель
private:
std::array<QString, static_cast<quint8>(eColIndex::ciColCount)> fHeadersText; // Надписи заголовков
void initHeadersText(); // Метод инициализирует заголовки
};
//-----------------------------------------------------------------------------
}
#endif // TABLEMODEL_H
| true |
d6e9b6fd394f438448be06df57b5bb1b35b3d3a0 | C++ | flyingtoaster0/CS4471TREE | /PredatorAndPrey/PredatorAndPrey/PushButton.cpp | UTF-8 | 937 | 2.859375 | 3 | [] | no_license | #include "PushButton.h"
#include <iostream>
PushButton::PushButton() : Clickable()
{
}
PushButton::PushButton(float x, float y, float width, float height, std::string label) : Clickable(x, y, width, height, label)
{
// Hardcoded color. Change this later maybe
this->upColor = vec3(0.5, 0.0, 0.8);
this->downColor = vec3(1.0, 1.0, 1.0) - this->upColor;
this->setColor(upColor);
}
void PushButton::mouseDown(float x, float y)
{
if(overlap(x,y))
{
if (getState() == UP)
{
//dowork
}
setState(DOWN);
setColor(downColor);
}
}
void PushButton::mouseUp(float x, float y)
{
if(getState() == DOWN && overlap(x,y))
{
this->executeAction();
}
setState(UP);
setColor(upColor);
}
void PushButton::setState(int state)
{
this->state = state;
}
int PushButton::getState()
{
return this->state;
}
void PushButton::setColor(vec3 color)
{
this->color = color;
}
vec3 PushButton::getColor()
{
return this->color;
} | true |
7b04f86bb9662fc6bf4c9da02ac4e58af4ebba0e | C++ | zakidane/Huffman-Text-File-Compression | /huffman.cpp | UTF-8 | 3,156 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <typeinfo>
#include <queue>
#include <vector>
#include <bits/stdc++.h>
#include "huffman.hpp"
using namespace std;
int main() {
string line, file, compressedString, decompressedLine;
int sizeArray, index;
vector<MinHeapNode>CharArray;
cout << "INpUt fILe NamE: " << endl;
getline(cin, file);
ifstream infile(file);
ofstream compressedfile("compressed.txt");
ofstream decompressedfile("decompressed.txt");
while(getline(infile, line,'\n')){
putIntoArray(line, CharArray);
}
sizeArray = CharArray.size();
cout << "size of charArray is " << sizeArray << endl;
char heapData[sizeArray];
int heapFrequencies[sizeArray];
for(int i = 0; i < sizeArray; i++){
heapData[i] = CharArray[i].data;
heapFrequencies[i] = CharArray[i].freq;
}
//declare a Minheap node to store the pointer to the minheap top
//this variable will be an input when decoding the compressed binary fILe
MinHeapNode* root;
//this line will assign binary codes to each struct of the vector
std::vector<MinHeapNode* > v = HuffmanCodes(heapData, heapFrequencies, sizeArray, root);
// This pushes the vector of struct pointers into a returnHashTable
//that assigns them to indexes according to the character's ascii code
std::vector<MinHeapNode*> hashTable = returnHashTable(v);
vector<MinHeapNode*>::iterator i;
int n = 0;
//define a temporary character and integer index hashValue
//then loop through the line to get a character, get the hashvalue
//associated with the character, retrive the corresponding Minheap pointer
//associated with the character and print out the binaryCode of the character
//We do this for all the characters in the line in their order of appearance
//the following three lines reset the infile stream to start reading from
//the beginning of the file again.
infile.clear();
infile.seekg (0, ios::beg);
line = "";
int x = 1;
while(getline(infile, line)){
cout << line << endl;
for(unsigned int i = 0; i < line.size();i++){
index = returnHashValue(line[i]);
compressedString += hashTable[index]->binaryCode;
}
compressedString+= "-";
cout << "line " << x << " " << compressedString << endl;
cout << " for " << line << endl;
x++;
//append a dummy string and add line to the output file
compressedfile << compressedString << endl;
compressedString = "";
line = "";
}
//close both the input file and the output file that has all the binaryCode
infile.close();
compressedfile.close();
//open the compressed.txt file to translate it back to its oriignal text
ifstream compressedInput("compressed.txt");
while(getline(compressedInput, compressedString)){
decompressedLine = decompression(compressedString, root);
cout << "decompressed Line: " << endl;
cout << decompressedLine << endl;
decompressedfile << decompressedLine << endl;
}
decompressedfile.close();
return 0;
}
| true |
357f506f46904aaa6ca29e3271a1cf63a62a93e6 | C++ | changkk/ckrobotics | /Coding Practice/36. Lowest Common Ancestor of a Binary Tree.cpp | UTF-8 | 2,541 | 3.671875 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
Goal: Find lowest common ancester
Find the first meeting node = common ancester
ex)
3 - 5 - 2 - 4
3 - 5
DFS for each node, and if found, save the path => O(2n) - O(n)
And Compare until they have same node, if different, return the previous node.
=> O(n)
O(n) time O(n) space
q =
save all the parent - child node, and start from the target node, go up by saving the path
and compare
O(n) time + O(k+i) => O(n)
O(n) + O(k+i)
unordered_map<TreeNode*> child - parent;
path = 3 5
class Solution {
public:
unordered_map<TreeNode*, TreeNode*> parent;
void saveParent(TreeNode* node){
if(node->left)
{
parent[node->left] = node;
saveParent(node->left);
}
if(node->right)
{
parent[node->right] = node;
saveParent(node->right);
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* &p, TreeNode* &q) {
if(!root) return root;
saveParent(root);
vector<TreeNode*> pathP;
vector<TreeNode*> pathQ;
while(p!=root) // mistake. Forgot to push itself
{
pathP.push_back(p); // [5]
p = parent[p]; // 3
}
pathP.push_back(p); //[3]
while(q!=root)
{
pathQ.push_back(q); //[4 2 5]
q = parent[q];
}
pathQ.push_back(q); // [4 2 5 3]
// [5 3] [1 3]
int i = pathP.size()-1;
int j = pathQ.size()-1; // mistake. Start from n not n-1
while(pathP[i] == pathQ[j]) // [5 3] [4 2 5 3]
{
if(i==0) return pathP[i];
if(j==0) return pathQ[j];
i--;
j--;
}
return pathP[i+1];
}
};
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* &p, TreeNode* &q){
// If target node is not found, just make left or right as NULL
if(!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(!left) return right;
if(!right) return left;
return root;
}
}; | true |
0031a154b619b48c08c38659a081360ca08b54ea | C++ | naturalistic/CodeJamPractice | /Africa2010/reversewords.cpp | UTF-8 | 695 | 3 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main() {
ifstream input("B-large-practice.in");
ofstream output("B-large-practice.out");
int cases;
input >> cases;
input.get();
string line;
for(int c=1; c<=cases; c++) {
getline(input, line);
istringstream iss(line);
vector<string> v;
string word;
while(iss >> word)
{
v.push_back(word);
}
output << "Case #" << c << ": ";
// assume at least one item...
if(v.size() != 0) {
for(vector<string>::iterator it=--v.end(); it!=v.begin(); it--) {
output << *it << " ";
}
output << v.at(0);
}
output << endl;
}
return 0;
}
| true |
c15a914fd8fdcb7ba8f3d8a2ad67e7f8437f9abf | C++ | ColWalterEKurtz/cppgen | /SrcMainCpp.cpp | UTF-8 | 7,531 | 2.921875 | 3 | [] | no_license | // -----------------------------------------------------------------------------
// SrcMainCpp.cpp SrcMainCpp.cpp
// -----------------------------------------------------------------------------
/**
* @file
* @brief This file holds the implementation of the SrcMainCpp class.
* @author Col. Walter E. Kurtz
* @version 2018-05-03
* @copyright GNU General Public License - Version 3.0
*/
// -----------------------------------------------------------------------------
// Includes Includes
// -----------------------------------------------------------------------------
#include "SrcMainCpp.h"
// -----------------------------------------------------------------------------
// Used namespaces Used namespaces
// -----------------------------------------------------------------------------
using namespace std;
// -----------------------------------------------------------------------------
// Construction Construction
// -----------------------------------------------------------------------------
// ----------
// SrcMainCpp
// ----------
/*
*
*/
SrcMainCpp::SrcMainCpp()
{
m_binary = "BinaryNotSet";
}
// -----------------------------------------------------------------------------
// Setter methods Setter methods
// -----------------------------------------------------------------------------
// ---------
// setBinary
// ---------
/*
*
*/
void SrcMainCpp::setBinary(const string& name)
{
m_binary = name;
}
// -----------------------------------------------------------------------------
// Getter methods Getter methods
// -----------------------------------------------------------------------------
// ---------
// getBinary
// ---------
/**
*
*/
string SrcMainCpp::getBinary() const
{
return m_binary;
}
// -----------------------------------------------------------------------------
// Internal methods Internal methods
// -----------------------------------------------------------------------------
// ----------
// printLines
// ----------
/*
*
*/
void SrcMainCpp::printLines(ofstream& target) const
{
printHeader(target, true);
target << endl;
printLongFrame(target, "Includes", 0);
target << "// #include <cstdlib>" << endl;
target << "// #include <climits>" << endl;
target << "// #include <cfloat>" << endl;
target << "// #include <cmath>" << endl;
target << "// #include <ctime>" << endl;
target << "// #include <list>" << endl;
target << "// #include <stack>" << endl;
target << "// #include <vector>" << endl;
target << "// #include <queue>" << endl;
target << "// #include <deque>" << endl;
target << "// #include <set>" << endl;
target << "// #include <map>" << endl;
target << "// #include <random>" << endl;
target << "// #include <algorithm>" << endl;
target << "// #include <string>" << endl;
target << "// #include <sstream>" << endl;
target << "// #include <fstream>" << endl;
target << "// #include <iomanip>" << endl;
target << "#include <iostream>" << endl;
target << "#include \"message.h\"" << endl;
target << "#include \"cli.h\"" << endl;
target << endl;
target << endl;
printLongFrame(target, "Used namespaces", 0);
target << "using namespace std;" << endl;
target << endl;
target << endl;
printLongFrame(target, "Functions", 0);
target << endl;
target << "// --------" << endl;
target << "// showHelp" << endl;
target << "// --------" << endl;
target << "/**" << endl;
target << " * @brief This function shows the program's help." << endl;
target << " */" << endl;
target << "void showHelp()" << endl;
target << "{" << endl;
target << " cout << endl;" << endl;
target << " cout << \"NAME\" << endl;" << endl;
target << " cout << \" " << getBinary() << " - foo bar baz\" << endl;" << endl;
target << " cout << endl;" << endl;
target << " cout << \"SYNOPSIS\" << endl;" << endl;
target << " cout << \" " << getBinary() << " {-h|-v} show help resp. version and exit\" << endl;" << endl;
target << " cout << endl;" << endl;
target << " cout << \"DESCRIPTION\" << endl;" << endl;
target << " cout << \" ask not what " << getBinary() << " can do for you - ask what you can do for " << getBinary() << "\" << endl;" << endl;
target << " cout << endl;" << endl;
target << " cout << \"OPTIONS\" << endl;" << endl;
target << " cout << \" -h show help and exit\" << endl;" << endl;
target << " cout << \" -v show version and exit\" << endl;" << endl;
target << " cout << endl;" << endl;
target << " cout << \"EXAMPLES\" << endl;" << endl;
target << " cout << endl;" << endl;
target << "}" << endl;
target << endl;
target << "// -----------" << endl;
target << "// showVersion" << endl;
target << "// -----------" << endl;
target << "/**" << endl;
target << " * @brief This function shows the program's version." << endl;
target << " */" << endl;
target << "void showVersion()" << endl;
target << "{" << endl;
target << " cout << \"" << getVersion() << "\" << endl;" << endl;
target << "}" << endl;
target << endl;
target << "// ----" << endl;
target << "// main" << endl;
target << "// ----" << endl;
target << "/**" << endl;
target << " * @brief The program starts in this function." << endl;
target << " *" << endl;
target << " * @param argc holds the number of passed command-line arguments." << endl;
target << " * @param argv holds the list of passed command-line arguments." << endl;
target << " *" << endl;
target << " * @return" << endl;
target << " * Value | Meaning" << endl;
target << " * ----: | :------" << endl;
target << " * 0 | The requested operation finished successfully." << endl;
target << " * 1 | The requested operation failed." << endl;
target << " */" << endl;
target << "int main(int argc, char** argv)" << endl;
target << "{" << endl;
target << " // create command-line parser" << endl;
target << " cli cmdl;" << endl;
target << endl;
target << " // parse command-line" << endl;
target << " if ( cmdl.parse(argc, argv) )" << endl;
target << " {" << endl;
target << " // SHOW_HELP" << endl;
target << " if (cmdl.operation == cli::SHOW_HELP)" << endl;
target << " {" << endl;
target << " showHelp();" << endl;
target << " }" << endl;
target << endl;
target << " // SHOW_VERSION" << endl;
target << " else if (cmdl.operation == cli::SHOW_VERSION)" << endl;
target << " {" << endl;
target << " showVersion();" << endl;
target << " }" << endl;
target << endl;
target << " // DEFAULT" << endl;
target << " else if (cmdl.operation == cli::DEFAULT)" << endl;
target << " {" << endl;
target << " // say hello" << endl;
target << " msg::nfo(\"hello world\");" << endl;
target << " }" << endl;
target << " }" << endl;
target << endl;
target << " // invalid command-line" << endl;
target << " else" << endl;
target << " {" << endl;
target << " // signalize trouble" << endl;
target << " return 1;" << endl;
target << " }" << endl;
target << endl;
target << " // signalize success" << endl;
target << " return 0;" << endl;
target << "}" << endl;
}
| true |
be82f040d9568c1662c8b437c1a1017e298b8ed2 | C++ | timatlee/ACNH-AutoPusher | /src/main.cpp | UTF-8 | 4,921 | 2.921875 | 3 | [] | no_license | #include <LiquidCrystal.h>
#include <Arduino.h>
#include <Keypad.h>
#include <Servo.h>
#include <arduino-timer.h>
const int LCD_TIMER=2500;
// Various variables.
int iDeflection = 48;
int iDelay = 500;
int iHoldDelay = 500;
bool bRunning = false;
// LCD setup
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
int iDisplayCycle = 0;
// Keypad setup.
const byte KEYPAD_ROWS = 2;
const byte KEYPAD_COLS = 4;
char hexaKeys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'}};
byte rowPins[KEYPAD_ROWS] = {A5, A4};
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);
// Servo setup
Servo mainServo;
int servoPosition = 0;
// Timer setup
auto timer = timer_create_default(); // create a timer with default settings
uintptr_t timerClickTask = 0;
uintptr_t lcdTimerTask = 0;
/*
** Shows the state of affairs to the serial interface.
*/
bool printSerialSetting(void *)
{
Serial.println("ACNH A button clicker, the debug interface.");
Serial.print("Run State: ");
if (bRunning)
{
Serial.println("Is running. A to stop.");
}
else
{
Serial.println("Is not running. B to test, A to start.");
}
Serial.print("Deflection (1/4): ");
Serial.println(iDeflection);
Serial.print("Delay (2/5): ");
Serial.println(iDelay);
Serial.print("HoldDelay (3/6):");
Serial.println(iHoldDelay);
Serial.print("Total cycle time iHoldDelay + Delay): ");
Serial.println(iHoldDelay + iDelay);
Serial.println();
return (true);
}
/*
** Shows the state of things to the LCD display.
** Top line is the setting (and buttons to adjust)
** Second line is the value.
*/
bool printLCDSettings(void *)
{
lcd.clear();
switch (iDisplayCycle % 5)
{
case 0:
lcd.setCursor(0, 0);
lcd.print("Deflection (1/4)");
lcd.setCursor(0, 1);
lcd.print(iDeflection);
break;
case 1:
lcd.setCursor(0, 0);
lcd.print("Hold Delay (2,5)");
lcd.setCursor(0, 1);
lcd.print(iHoldDelay);
break;
case 2:
lcd.setCursor(0, 0);
lcd.print("Push Delay (3,6)");
lcd.setCursor(0, 1);
lcd.print(iDelay);
break;
case 3:
lcd.setCursor(0, 0);
lcd.print("Total Cycle: ");
lcd.setCursor(0, 1);
lcd.print(iHoldDelay + iDelay);
break;
default:
lcd.setCursor(0, 0);
lcd.print("A start/stop.");
if (!bRunning)
{
lcd.setCursor(0, 1);
lcd.print("B to test");
}
}
iDisplayCycle++;
return (true);
}
/*
** Actually press the button.
*/
bool doPulse(void *)
{
mainServo.write(iDeflection);
delay(iHoldDelay);
mainServo.write(servoPosition);
return (true);
}
/*
** Setup activities..
*/
void setup()
{
//set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// put your setup code here, to run once:
Serial.begin(9600);
// Setup the main server
mainServo.attach(6);
mainServo.write(0);
Serial.println("Setup complete");
lcd.setCursor(0, 0);
lcd.print("ACNH AutoClicker");
iDisplayCycle = 0;
timer.every(10000, printSerialSetting);
lcdTimerTask = timer.every(LCD_TIMER, printLCDSettings);
}
/*
** Handles keypresses from the keypad. Called from loop().
*/
void parseInput(char c)
{
if (!bRunning)
{
switch (c)
{
case '1':
iDeflection++;
iDisplayCycle = 0;
break;
case '4':
iDeflection--;
iDisplayCycle = 0;
break;
case '2':
iHoldDelay += 50;
iDisplayCycle = 1;
break;
case '5':
iHoldDelay -= 50;
iDisplayCycle = 1;
break;
case '3':
iDelay += 50;
iDisplayCycle = 2;
break;
case '6':
iDelay -= 50;
iDisplayCycle = 2;
break;
case 'B':
doPulse(0);
break;
}
}
switch (c)
{
case 'A':
if (bRunning)
{
bRunning = false;
if (timerClickTask != 0)
{
timer.cancel(timerClickTask);
timerClickTask = 0;
}
}
else
{
bRunning = true;
timerClickTask = timer.every(iDelay + iHoldDelay, doPulse);
}
break;
}
// Make sure the values we've set are within sane limtes.
iDeflection = constrain(iDeflection, 0, 180);
iHoldDelay = constrain(iHoldDelay, 200, 10000);
iDelay = constrain(iDelay, iHoldDelay, 10000);
// Update the LCD now. This is cheesed a bit by setting the displaycycle in the switch statement above. Sometimes this is a bit weird if the timer event triggers immediately after pressing a number on the keypad.
if (!bRunning)
{
timer.cancel(lcdTimerTask);
printLCDSettings(0);
lcdTimerTask = timer.every(LCD_TIMER, printLCDSettings);
}
}
void loop()
{
// Tick the timer.
timer.tick();
// Do keypad stuff.
char customKey = customKeypad.getKey();
if (customKey)
{
Serial.print("Console received: ");
Serial.println(customKey);
parseInput(customKey);
}
}
| true |
5317328f7b009bfa80b720ca7b4c01fed0416bc9 | C++ | Teamforalgorithm/study_codes | /rokwon/6-1_최단_경로_알고리즘/1238_파티.cpp | UTF-8 | 1,298 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<queue>
using namespace std;
int sum_distan[1001];
int N,M,X;
void dijkstra( vector< pair<int,int> > arr[]) {
priority_queue< pair<int,int> > q;
q.push({0, X});
int min_distan[1001];
for (int i = 1; i < N; i++)
min_distan[i] = 210000000;
while(!q.empty()) {
int vertex = q.top().second;
int cost = -q.top().first;
if ( cost < min_distan[vertex] ) {
min_distan[vertex] = cost;
for (int i = 0; i < arr[vertex].size(); i++)
q.push({ -(arr[vertex][i].second+cost), arr[vertex][i].first});
}
q.pop();
}
for(int i = 1; i < N; i++)
sum_distan[i] += min_distan[i];
};
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int a,b,c;
cin >> N >> M >> X;
N++;
vector< pair<int,int> > arr[1001];
vector< pair<int,int> > back_arr[1001];
for(int i = 0; i < M; i++) {
cin >> a >> b >> c;
arr[a].push_back({b,c});
back_arr[b].push_back({a,c});
}
dijkstra(arr);
dijkstra(back_arr);
int ans = *max_element(sum_distan, sum_distan+N);
cout << ans;
return 0;
} | true |
b6264c95a0338335e1348f9cb8cd64f48fd2d63e | C++ | kompanpawel/PROI | /Heroes/include/save_error.h | UTF-8 | 289 | 2.671875 | 3 | [] | no_license | #ifndef SAVE_ERROR_H
#define SAVE_ERROR_H
#include <string>
class save_error
{
std::string except;
public:
save_error(): except{"error while saving"} {}
save_error(std::string except_): except{except_} {}
std::string what() {return except;}
};
#endif // SAVE_ERROR_H
| true |
b5e9ec0a460509fc6e37b5afc707ae4d8df91ce3 | C++ | lamloei/GitHub | /AT.LAMLOEI/Node32pico/node32pico_at_lamloei/node32pico_at_lamloei.ino | UTF-8 | 827 | 2.546875 | 3 | [] | no_license | #include <Wire.h>
#define _CC_C10 (c[i]==char(10))
#define _CC_C13 (c[i-1]==char(13))
#define _CC0 (c[0]=='a'||c[0]=='A')
#define _CC1 (c[1]=='t'||c[1]=='T')
#define _CC2 (c[2]=='.')
int i=0;
char c[8192];
char d;
void clearChar() {
memset(c, (char)0, sizeof c);
}
void setup() {
Serial.begin(115200);
}
void loop() {
if ( Serial.available() ) {
c[i] = Serial.read();
if( c[i] == '\n') {
if (i==3 && _CC0 && _CC1 & _CC_C13 & _CC_C10 ) {
Serial.println();
Serial.println("OK");
} else if (i==4 && _CC0 && _CC1 && _CC2 & _CC_C13 & _CC_C10 ) {
Serial.println();
Serial.println("OK.LAMLOEI");
} else {
Serial.println();
Serial.println("ERROR");
}
clearChar();
i=0;
} else {
Serial.print(c[i]);
i++;
}
}
}
| true |
9ea21a536eb908a05be46c75019bdf152dde4617 | C++ | gawbi/ch09 | /twodarray.cpp | UHC | 641 | 3.890625 | 4 | [] | no_license | // file: twodarray.c
#include<stdio.h>
#define ROWSIZE 2
#define COLSIZE 3
int main(void)
{
// 2 迭
int td[ROWSIZE][COLSIZE];
// 2 迭ҿ
td[0][0] = 1; td[0][1] = 2; td[0][2] = 3;
td[1][0] = 4; td[1][1] = 5; td[1][2] = 6;
printf("ݺ for ̿Ͽ \n");
for (int i = 0; i < ROWSIZE; i++)
{
for (int j = 0; j < COLSIZE; j++)
printf("td[%d][%d] == %d ", i, j, td[i][j]);
printf("\n");
}
return 0;
}
/*
ݺ for ̿Ͽ
td[0][0] == 1 td[0][1] == 2 td[0][2] == 3
td[1][0] == 4 td[1][1] == 5 td[1][2] == 6
*/ | true |
657fc680efa2e7255af7c5cd702f83fd184b52ec | C++ | arrows-1011/CPro | /AOJ/Volume10/1046.cpp | UTF-8 | 1,814 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <cstring>
using namespace std;
#define MAX 20
#define INF 1e9
int H,W,ax,ay,bx,by;
char field[MAX][MAX];
string str;
const int dx[] = {-1,0,0,1,0};
const int dy[] = {0,-1,1,0,0};
struct State{
int sx,sy,gx,gy;
State(int sx,int sy,int gx,int gy) : sx(sx),sy(sy),gx(gx),gy(gy) {}
};
bool inField(int y,int x){
return 0 <= y && y < H && 0 <= x && x < W;
}
int getDir(char ch){
if(ch == '4') return 0;
if(ch == '8') return 1;
if(ch == '2') return 2;
if(ch == '6') return 3;
return 4;
}
void bfs(){
int size = str.size();
bool visited[MAX][MAX][MAX][MAX][MAX];
memset(visited,0,sizeof(visited));
visited[ay][ax][by][bx][0] = true;
queue<State> Q;
queue<int> Count;
Q.push(State(ax,ay,bx,by));
Count.push(0);
while(!Q.empty()){
State s = Q.front(); Q.pop();
int cnt = Count.front(); Count.pop();
if(s.sx == s.gx && s.sy == s.gy){
cout << cnt << " " << s.sy << " " << s.sx << endl;
return;
}
int dir = getDir(str[cnt%size]);
int Gx = s.gx + dx[dir], Gy = s.gy + dy[dir];
if(!inField(Gy,Gx)) Gx = s.gx, Gy = s.gy;
for(int i = 0 ; i < 5 ; i++){
int nx = s.sx + dx[i], ny = s.sy + dy[i];
if(!inField(ny,nx)) continue;
if(field[ny][nx] == '#') continue;
if(visited[ny][nx][Gy][Gx][(cnt+1)%size]) continue;
visited[ny][nx][Gy][Gx][(cnt+1)%size] = true;
Q.push(State(nx,ny,Gx,Gy));
Count.push(cnt+1);
}
}
cout << "impossible" << endl;
}
int main(){
while(cin >> H >> W, (H|W)){
for(int i = 0 ; i < H ; i++){
for(int j = 0 ; j < W ; j++){
cin >> field[i][j];
if(field[i][j] == 'A'){
ax = j, ay = i;
}else if(field[i][j] == 'B'){
bx = j, by = i;
}
}
}
cin >> str;
bfs();
}
return 0;
}
| true |
501a4b005d4f40d4dab38ecff0835cfa7091bcdd | C++ | msherve16/Assignment4 | /Assignment4E/Assignment4E/Source.cpp | UTF-8 | 1,007 | 3.765625 | 4 | [] | no_license | ////////////////////////
//Morgan Sherve
//Assignment 4 Exercise 11.13
///////////////////////////////
#include <iostream>
using namespace std;
Course::Course(const string& courseName, int capacity)
{
numberOfStudents = 0;
this -> courseName = coursename;
this-> capacity = capacity;
students = new string[capacity];
}
Course::~Course()
{
delete [] students;
}
string Course:: getCourseName() const
{
return courseName;
}
void Course::addStudent (const string& name)
{
numberOfStudents++;
}
//Homework:
int dropStudent (const string& name)
{
numberOfStudents--;
}
int clear()
{
students == 0;
}
string* Course::getStudents const
{
return students;
}
//Homework:
int* doubleCapacity (const int* list, int size)
{
int newSize;
newSize = (2*size);
list = new int [newSize];
}
int main()
{
int addStudent ("Emily"), ("George"), ("Kayli");
int dropStudent ("Fred");
cout << "Total students in course: " << numberOfStudents << endl;
return 0;
}
| true |
6dcd099be91abd3b39a7273f48c279d77f122c3c | C++ | Assylzhan-Izbassar/Algorithms-and-Data-Structures | /week_13/graph-thory:dfs/№111540.cpp | UTF-8 | 1,395 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int g[100001][100001];
bool used[100001];
int n;
vector<int> ans;
int counter = 0;
void dfs(int u)
{
used[u] = true;
counter++;
ans.push_back(u);
for(size_t i=0; i < n; ++i)
{
if(g[i][u] == 1 && !used[i])
{
dfs(i);
}
}
}
int main()
{
int m;
cin >> n >> m;
for(size_t i=0; i < n; ++i)
used[i] = false;
for(size_t i=0; i < n; ++i)
for(size_t j=0; j < n; ++j)
g[i][j] = 0;
int x,y;
for(size_t i=0; i < m; ++i)
{
cin >> x >> y;
x = x - 1;
y = y - 1;
g[x][y] = 1;
}
int comp = 0;
for(size_t i=0; i < n; ++i)
{
if(!used[i])
{
comp++;
dfs(i);
ans.clear();
counter = 0;
}
}
cout << comp << endl;
for(size_t i=0; i < n; ++i)
used[i] = false;
for(size_t i=0; i < n; ++i)
{
if(!used[i])
{
dfs(i);
if(counter != 0)
{
cout << counter << endl;
for(size_t i=0; i < ans.size(); ++i)
{
cout << ans[i]+1 << " ";
}
cout << endl;
}
ans.clear();
counter = 0;
}
}
return 0;
} | true |
a62ad4b8e98c3812aa8c9874a974f5dd570d8df2 | C++ | caj07/437_Assignment2 | /437_Assignment2/TAAssignmentStatement.cpp | UTF-8 | 1,017 | 2.921875 | 3 | [] | no_license | #include "TAAssignmentStatement.h"
#include "TAType.h"
#include "TATerm.h"
TAAssignmentStatement::TAAssignmentStatement() :
TAAtomicStatement(), m_target(), m_expression(), m_concurrentTemp()
{
}
TAAssignmentStatement::TAAssignmentStatement(TATerm * target, TATerm * expression) :
TAAtomicStatement(), m_target(target), m_expression(expression), m_concurrentTemp()
{
if (target->getType().getTypeNumber() != expression->getType().getTypeNumber()) {
throw std::invalid_argument("Target and expression are not of the same type");
}
}
TAAssignmentStatement::~TAAssignmentStatement()
{
}
void TAAssignmentStatement::concurrentEvaluate()
{
m_concurrentTemp = &m_expression->evaluate();
}
void TAAssignmentStatement::concurrentAssign()
{
m_target->val = *m_concurrentTemp;
m_concurrentTemp = nullptr;
}
void TAAssignmentStatement::evaluate()
{
m_target->val = m_expression->evaluate();
}
void TAAssignmentStatement::list(ostream & os) const
{
m_target->list(os);
os << " = ";
m_expression->list(os);
}
| true |
90f47deed875777e31c5ad3d3689803f1554c33b | C++ | WindowsNT/tu | /rest.h | UTF-8 | 12,796 | 2.84375 | 3 | [] | no_license | #ifndef _REST_H
#define _REST_H
#include <functional>
#include <utility>
#include <memory>
#pragma once
namespace RESTAPI {
using namespace std;
typedef vector<char> DATA;
inline std::vector<std::wstring> &split(const std::wstring &s, wchar_t delim, std::vector<std::wstring> &elems) {
std::wstringstream ss(s);
std::wstring item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
inline std::vector<std::wstring> split(const std::wstring &s, wchar_t delim) {
std::vector<std::wstring> elems;
split(s, delim, elems);
return elems;
}
class data_provider
{
public:
virtual size_t s() = 0;
virtual size_t Read(char* Buff, size_t sz) = 0;
virtual bool CanOnce() = 0;
virtual std::tuple<const char*, size_t> Once() = 0;
};
class memory_data_provider : public data_provider
{
private:
size_t size;
const char* ptr;
size_t fp = 0;
public:
memory_data_provider(const char* a, size_t sz)
{
fp = 0;
ptr = a;
size = sz;
}
virtual size_t s()
{
return size;
}
virtual size_t Read(char* Buff, size_t sz)
{
size_t av = size - fp;
if (av < sz)
sz = av;
memcpy(Buff, ptr + fp, sz);
fp += sz;
return sz;
}
virtual bool CanOnce()
{
return true;
}
virtual std::tuple<const char*, size_t> Once()
{
return make_tuple<const char*, size_t>((const char*&&)ptr, (size_t&&)size);
}
};
class file_data_provider : public data_provider
{
private:
HANDLE hY;
public:
file_data_provider(HANDLE h)
{
hY = h;
}
virtual size_t s()
{
LARGE_INTEGER li;
GetFileSizeEx(hY, &li);
return (size_t)li.QuadPart;
}
virtual size_t Read(char* Buff, size_t sz)
{
DWORD A = 0;
if (sz > 4294967296LL)
sz = 4*1024*1024;
if (!ReadFile(hY, Buff, (DWORD)sz, &A, 0))
return 0;
return A;
}
virtual bool CanOnce()
{
return false;
}
virtual std::tuple<const char*, size_t> Once()
{
return make_tuple<const char*, size_t>(0,0);
}
};
class data_writer
{
public:
virtual DWORD Write(const char* Buff, DWORD sz) = 0;
virtual size_t s() = 0;
};
class memory_data_writer : public data_writer
{
private:
vector<char> p;
public:
virtual size_t s()
{
return p.size();
}
virtual DWORD Write(const char* Buff, DWORD sz)
{
auto s1 = p.size();
p.resize(s1 + sz);
memcpy(p.data() + s1, Buff, sz);
return sz;
}
vector<char>& GetP() { return p; }
};
class file_data_writer : public data_writer
{
private:
HANDLE hY;
public:
file_data_writer(HANDLE h)
{
hY = h;
}
virtual size_t s()
{
LARGE_INTEGER li;
GetFileSizeEx(hY, &li);
return (size_t)li.QuadPart;
}
virtual DWORD Write(const char* Buff, DWORD sz)
{
DWORD A = 0;
if (!WriteFile(hY, Buff, sz, &A, 0))
return 0;
return A;
}
};
class ihandle
{
private:
HINTERNET hX = 0;
std::shared_ptr<size_t> ptr = std::make_shared<size_t>();
public:
// Closing items
void Close()
{
if (!ptr || ptr.use_count() > 1)
{
ptr.reset();
return;
}
ptr.reset();
if (hX != 0)
InternetCloseHandle(hX);
hX = 0;
}
ihandle()
{
hX = 0;
}
~ihandle()
{
Close();
}
ihandle(const ihandle& h)
{
Dup(h);
}
ihandle(ihandle&& h)
{
Move(std::forward<ihandle>(h));
}
ihandle(HINTERNET hY)
{
hX = hY;
}
ihandle& operator =(const ihandle& h)
{
Dup(h);
return *this;
}
ihandle& operator =(ihandle&& h)
{
Move(std::forward<ihandle>(h));
return *this;
}
void Dup(const ihandle& h)
{
Close();
hX = h.hX;
ptr = h.ptr;
}
void Move(ihandle&& h)
{
Close();
hX = h.hX;
ptr = h.ptr;
h.ptr.reset();
h.hX = 0;
}
operator HINTERNET() const
{
return hX;
}
};
class REST
{
private:
wstring Agent = L"REST";
ihandle hI;
ihandle hI2;
wstring Host;
bool ssl = false;
public:
REST(const wchar_t* ag = 0)
{
if (ag)
Agent = ag;
}
void Disconnect()
{
hI.Close();
hI2.Close();
}
HRESULT Connect(const wchar_t* host, bool SSL = false, unsigned short Port = 0, DWORD flg = 0,const wchar_t* user= 0,const wchar_t* pass = 0)
{
if (_wcsicmp(Host.c_str(), host) != 0)
Disconnect();
Host = host;
ssl = SSL;
if (!hI)
hI = InternetOpen(Agent.c_str(), INTERNET_OPEN_TYPE_DIRECT, 0, 0, 0);
if (!hI)
return E_UNEXPECTED;
if (!hI2)
{
if (SSL)
hI2 = InternetConnect(hI, host, Port ? Port : INTERNET_DEFAULT_HTTPS_PORT, user, pass, INTERNET_SERVICE_HTTP, INTERNET_FLAG_SECURE | flg, 0);
else
hI2 = InternetConnect(hI, host, Port ? Port : INTERNET_DEFAULT_HTTP_PORT, user, pass, INTERNET_SERVICE_HTTP, flg, 0);
}
if (!hI2)
return E_UNEXPECTED;
InternetSetStatusCallback(hI2, 0);
return S_OK;
}
ihandle RequestWithBuffer(const wchar_t* url, const wchar_t* verb = L"POST", std::initializer_list<wstring> hdrs = {}, const char * d = 0, size_t sz = 0, std::function<HRESULT(size_t sent, size_t tot, void*)> fx = nullptr, void* lp = 0, bool Once = true,DWORD ExtraSecurityFlags = 0)
{
memory_data_provider m(d, sz);
return Request2(url, m, Once, verb, hdrs, fx, lp, 0, 0, 0, 0, ExtraSecurityFlags);
}
ihandle RequestWithFile(const wchar_t* url, const wchar_t* verb = L"POST", std::initializer_list<wstring> hdrs = {}, HANDLE hX = INVALID_HANDLE_VALUE, std::function<HRESULT(size_t sent, size_t tot, void*)> fx = nullptr, void* lp = 0, DWORD ExtraSecurityFlags = 0)
{
file_data_provider m(hX);
return Request2(url, m, true, verb, hdrs, fx, lp,0,0,0,0,ExtraSecurityFlags);
}
ihandle Request2(const wchar_t* url, data_provider& dp, bool Once = true, const wchar_t* verb = L"POST", std::initializer_list<wstring> hdrs = {}, std::function<HRESULT(size_t sent, size_t tot, void*)> fx = nullptr, void* lp = 0, const char* extradata1 = 0, DWORD extradatasize1 = 0,const char* extradata2 = 0,DWORD extradatasize2 = 0,DWORD ExtraSecurityFlags = 0)
{
if (!url)
return 0;
wstring nurl;
ihandle hI3;
if (_wcsnicmp(url, L"http://", 7) == 0 || _wcsnicmp(url, L"https://", 8) == 0)
{
Disconnect();
hI = InternetOpen(Agent.c_str(), INTERNET_OPEN_TYPE_DIRECT, 0, 0, 0);
if (_wcsicmp(verb,L"GET") == 0)
{
hI3 = InternetOpenUrl(hI, url, 0, 0, ssl ? INTERNET_FLAG_SECURE : 0, 0);
return hI3;
}
else
{
URL_COMPONENTS u = { 0 };
size_t ms = wcslen(url);
u.dwStructSize = sizeof(u);
unique_ptr<TCHAR> hn(new TCHAR[ms]);
unique_ptr<TCHAR> un(new TCHAR[ms]);
unique_ptr<TCHAR> pwd(new TCHAR[ms]);
unique_ptr<TCHAR> dir(new TCHAR[ms]);
unique_ptr<TCHAR> ex(new TCHAR[ms]);
u.lpszHostName = hn.get();
u.dwHostNameLength = (DWORD)ms;
u.lpszUserName = un.get();
u.dwUserNameLength = (DWORD)ms;
u.lpszPassword = pwd.get();
u.dwPasswordLength = (DWORD)ms;
u.lpszUrlPath = dir.get();
u.dwUrlPathLength = (DWORD)ms;
u.lpszExtraInfo = ex.get();
u.dwExtraInfoLength = (DWORD)ms;
InternetCrackUrl(url, 0, 0, &u);
nurl = u.lpszUrlPath;
nurl += u.lpszExtraInfo;
url = nurl.c_str();
TCHAR* acct[] = { L"*/*",0 };
if (_wcsnicmp(url, L"http://", 7) == 0)
Connect(u.lpszHostName, false);
else
Connect(u.lpszHostName, true);
hI3 = HttpOpenRequest(hI2, verb, url, 0, 0, (LPCTSTR*)acct, ssl ? INTERNET_FLAG_SECURE : 0, 0);
}
}
else
{
TCHAR* acct[] = { L"*/*",0 };
hI3 = HttpOpenRequest(hI2, verb, url, 0, 0, (LPCTSTR*)acct, ssl ? INTERNET_FLAG_SECURE : 0, 0);
}
if (!hI3)
return 0;
if (ExtraSecurityFlags)
{
DWORD dwFlags = 0;
DWORD dwBuffLen = sizeof(dwFlags);
InternetQueryOption(hI3, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen);
dwFlags |= ExtraSecurityFlags;
InternetSetOption(hI3, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof(dwFlags));
}
for (size_t i = 0; i < hdrs.size(); i++)
{
auto h = (hdrs.begin() + i);
if (h->length())
{
BOOL fx2 = HttpAddRequestHeaders(hI3, (LPCWSTR)h->c_str(), (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
if (!fx2)
continue;
}
}
if (((Once && dp.CanOnce()) || dp.s() == 0) && !extradata1 && !extradata2)
{
auto o = dp.Once();
BOOL ldr = HttpSendRequest(hI3, 0, 0, (LPVOID)get<0>(o),(DWORD) get<1>(o));
if (!ldr)
{
if (GetLastError() == 12044)
ldr = HttpSendRequest(hI3, 0, 0, (LPVOID)get<0>(o), (DWORD)get<1>(o));
if (!ldr)
return 0;
}
if (fx)
fx(get<1>(o), get<1>(o),lp);
return hI3;
}
BOOL ldr = HttpSendRequestEx(hI3, 0, 0, 0, 0);
if (!ldr)
return 0;
auto tot = dp.s();
size_t Sent = 0;
vector<char> b(4096);
DWORD a = 0;
if (extradata1)
InternetWriteFile(hI3, extradata1, extradatasize1, &a);
for (;;)
{
memset(b.data(), 0, 4096);
auto ri = dp.Read(b.data(), 4096);
if (!ri)
break;
if (!InternetWriteFile(hI3, b.data(), (DWORD)ri, &a))
{
DWORD dwe = 0;
wchar_t rep[1000] = { 0 };
DWORD dwb = 1000;
InternetGetLastResponseInfo(&dwe, rep, &dwb);
return 0;
}
if (a != ri)
return 0;
Sent += ri;
if (fx)
{
auto rst = fx(Sent, tot, lp);
if (FAILED(rst))
return 0;
}
}
if (extradata2)
InternetWriteFile(hI3, extradata2, extradatasize2, &a);
HttpEndRequest(hI3, 0, 0, 0);
return hI3;
}
long Headers(ihandle& hI3,std::map<wstring,wstring>& t)
{
vector<wchar_t> lpOutBuffer(10000);
DWORD dwSize = 10000;
if (!HttpQueryInfo(hI3, HTTP_QUERY_RAW_HEADERS_CRLF,
(LPVOID)lpOutBuffer.data(), &dwSize, NULL))
return E_FAIL;
vector<wstring> str;
wstring s = lpOutBuffer.data();
split(s, '\n',str);
for (auto& a : str)
{
vector<wstring> str2;
wcscpy_s(lpOutBuffer.data(), 10000, a.c_str());
wchar_t* a1 = wcschr(lpOutBuffer.data(), ':');
if (!a1)
continue;
*a1 = 0;
a1++;
if (wcslen(a1) && a1[wcslen(a1) - 1] == '\r')
a1[wcslen(a1) - 1] = 0;
while (wcslen(a1) && *a1 == ' ')
a1++;
t[lpOutBuffer.data()] = a1;
}
dwSize = 10000;
if (!HttpQueryInfo(hI3, HTTP_QUERY_STATUS_CODE,
(LPVOID)lpOutBuffer.data(), &dwSize, NULL))
return E_FAIL;
return _wtoi(lpOutBuffer.data());
}
HRESULT ReadToFile(ihandle& hI3, HANDLE hX, std::function<HRESULT(unsigned long long, unsigned long long, void*)> fx = nullptr, void* lp = 0)
{
file_data_writer w(hX);
return Read2(hI3, w, fx, lp);
}
HRESULT ReadToMemory(ihandle& hI3, vector<char>& m, std::function<HRESULT(unsigned long long, unsigned long long, void*)> fx = nullptr, void* lp = 0)
{
memory_data_writer w;
auto e = Read2(hI3, w, fx, lp);
m = w.GetP();
return e;
}
HRESULT Read2(ihandle& hI3, data_writer& dw, std::function<HRESULT(unsigned long long, unsigned long long, void*)> fx = nullptr, void* lp = 0)
{
size_t Size = 0;
unsigned long bfs = 10000;
TCHAR ss[10000] = { 0 };
if (!HttpQueryInfo(hI3, HTTP_QUERY_CONTENT_LENGTH, ss, &bfs, 0))
Size = (size_t)-1;
else
Size = (size_t)_ttoi64(ss);
BOOL ld = TRUE;
unsigned long long TotalTransferred = 0;
for (;;)
{
DWORD n;
unique_ptr<char> Buff(new char[10100]);
BOOL F = InternetReadFile(hI3, Buff.get(), 10000, &n);
if (F == false && ld == TRUE)
{
ld = FALSE;
InternetSetOption(hI, INTERNET_OPTION_HTTP_DECODING, (void*)&ld, sizeof(BOOL));
F = InternetReadFile(hI3, Buff.get(), 10000, &n);
}
if (F == false)
return E_FAIL;
if (n == 0)
break;
TotalTransferred += n;
if (dw.Write(Buff.get(), n) != n)
return E_FAIL;
if (fx)
{
auto rst = fx(TotalTransferred, Size, lp);
if (FAILED(rst))
return E_ABORT;
}
}
return S_OK;
}
inline vector<char> datareturn(ihandle& r)
{
vector<char> out;
ReadToMemory(r, out);
return out;
}
inline string textreturn(ihandle& r)
{
vector<char> out;
ReadToMemory(r, out);
out.resize(out.size() + 1);
char* p = (char*)out.data();
return p;
}
};
}
#endif // _REST_H | true |
ab040ffd8cf1724b7d75276666b0715278acd384 | C++ | alex-77/Estructuras | /Tarea 3/Ejercicio2/main.cpp | UTF-8 | 2,773 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include "LinkedList.h"
using namespace std;
using namespace vcn;
int main()
{
int tamN,tamM;
int n, m;
LinkedList<int> * M = new LinkedList<int>();
LinkedList<int> * N = new LinkedList<int>();
LinkedList<int> * P = new LinkedList<int>();
cout << "Dame el total de numeros de la lista N" << endl;
cin >> tamN;
for (int i = 0; i < tamN; i++){
cout << "Dame el " << (i + 1) << " numero de n" << endl;
cin >> n;
N->insertBack(n);
}
cout << "Dame el total de numeros de la lista M" << endl;
cin >> tamM;
for (int i = 0; i < tamM; i++){
cout << "Dame el " << (i + 1) << " numero de m" << endl;
cin >> m;
M->insertBack(m);
}
int opcion=0;
cout << endl << "Lita N:" << endl;
cout << *N;
cout << endl << "Lita M:" << endl;
cout << *M;
cout<<"1)N U M"<<endl;
cout<<"2)N - M"<<endl;
cout<<"3)M - N"<<endl;
cout<<"4)N * M"<<endl;
cout<<"5)N interseccion M"<<endl;
cin>>opcion;
switch( opcion)
{
case 1:
for(int i=0; i<tamM; i++){
int unio=0;
if(M->at(i)->getInfo()==N->at(i)->getInfo()&&N->at(i)->getInfo()==M->at(i)->getInfo()){
unio=M->at(i)->getInfo();
P->insert(unio, i);
}
else{
unio= M->at(i)->getInfo();
P->insert(unio, i);
unio=N->at(i)->getInfo();
P->insert(unio,i);
}
}
break;
case 2:
for(int i=0; i<tamM; i++){
int aux=0;
if(N->at(i)->getInfo()!=M->at(i)->getInfo()&&M->at(i)->getInfo()!=N->at(i)->getInfo())
aux=N->at(i)->getInfo();
P->insert(aux, i);
}
break;
case 3:
for(int i=0; i<tamM; i++){
int aux=0;
if(M->at(i)->getInfo()!=N->at(i)->getInfo()&&N->at(i)->getInfo()!=M->at(i)->getInfo())
aux=N->at(i)->getInfo();
P->insert(aux, i);
}
break;
case 4:
for(int i=0; i<tamM; i++){
int producto=0;
for(int j=0; j<tamN; j++){
producto= N->at(i)->getInfo() * M->at(j)->getInfo();
P->insert(producto, i);
}
}
break;
case 5:
for(int i=0; i<tamM; i++){
int unio=0;
if(M->at(i)->getInfo()==N->at(i)->getInfo()&&N->at(i)->getInfo()==M->at(i)->getInfo()){
unio=M->at(i)->getInfo();
P->insert(unio, i);
}
}
break;
default: cout<<"opcion Invalida" <<endl;
};
cout << endl << "Lita P:" << endl;
cout << *P;
delete M;
delete N;
delete P;
return 0;
}
| true |