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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
128a1b4607246cdce6fa0778114a0623e98b22ce | C++ | plops/Arduino_fastSIMplayingaround | /main_programm_control_exposureRH3/main_programm_control_exposureRH3.ino | UTF-8 | 8,338 | 2.828125 | 3 | [] | no_license | /*
Trigger for the Hamamatsu C11440
Trigger Mode: External Level Trigger
Set exposure time and exposure length
*/
// define all variables
int slm_ext_run=10; // starts hardware, activate running orders
int slm_trigger=11; // if high start showing image
int slm_out=9; // SLM LED enable signal, showing images when signal is High
int cam_in=2; // from arduino to camera_in (start exposure)
int cam_out=4; // from camera_out to arduino. signal is high if camera is ready for next exposure (output from camera to arduino)
int cam_out_G=3;
int aotf_enable=7; // if high switch AOTF to on / blanking mode as well
int aotf_signal=6; // set amplitude of sound wave of AOTF
int blinks=3; // number of blinks at the beginning
int countblinks=0;
int mindelay=10; // time for delay
int NumBlanks=0; // number of cylces the SLM keeps displaying a pattern before the camera and AOTF are ready for next pattern
//int rep=2; // number of repetitions of pos-switch-neg SLM displays and AOTF on-off-on sequences
//int NumDirs=3; // number of directions of grating
//int NumPhases=3; // number of phases of grating
int rep=1; // number of repetitions of pos-switch-neg SLM displays and AOTF on-off-on sequences
int NumDirs=3; // number of directions of grating
int NumPhases=7; // number of phases of grating
unsigned long mytimeout=3000; // Timeout in millisecs
int SLMPhase=0;
/*
while loops will loop continuously, and infinitely,
until the expression inside the parenthesis, () becomes false.
*/
//test if AOTF is working (try blinking)
void TestAOTF() {
countblinks=0;
while(countblinks<blinks){
digitalWrite(aotf_enable,LOW);
delay(200); // millisecond
digitalWrite(aotf_enable,HIGH);
delay(200);
countblinks=countblinks+1;
}
digitalWrite(aotf_enable,LOW); // after 3 blinks, aotf set to low = off
}
void setup() {
// allocate names to pins on arduino
//DIGITAL SIGNALS
//SLM
pinMode(slm_ext_run, OUTPUT); // output signal from arduino to SLM
pinMode(slm_trigger, OUTPUT); // D2,output signal from arduino to SLM
pinMode(slm_out, INPUT); // D3, iutput signal from arduino to SLM; signal == high, if image is shown
//CAMERA
pinMode(cam_in, OUTPUT); // output signal from arduino to camera; exposure while signal is high
pinMode(cam_out, INPUT); // iutput signal from camera to arduino; Camera Trigger ready output
pinMode(cam_out_G, INPUT);
//AOTF
pinMode(aotf_enable, OUTPUT); // output signal from arduino to AOTF; SLM is not illuminated but only for blink test
pinMode(aotf_signal, OUTPUT); // output signal from arduino to AOTF;
//SET SETTINGS
digitalWrite(aotf_signal,HIGH); //sets maximum possible amplitude
//of AOTF sound wave to maximum
digitalWrite(slm_ext_run,HIGH); //starts running order of SLM
TestAOTF();
}
void SLMCycle(int DoAOTF) { // processes one SLM cycle on-switch-off-switch, DoAOTF==0 mean Laser always off, DoAOTF==2 means Laser on Frame and Antiframe, DoAOTF==1 means Laser on only Frame
SLMPhase++; // To keept track of SLM position
while(digitalRead(slm_out)==LOW) {
delayMicroseconds(mindelay);} // while the signal of slm_out still Low, then do the delay in micorseconds untill the signal goes to High;
// this delay is for checking digitalRead not so often
// at the moment, there is no image on SLM, and wait that slm displays next image
// Now the positive image of grating is shown -> turn on the laser
if (DoAOTF>0) digitalWrite(aotf_enable,HIGH); // illuminate SLM
while(digitalRead(slm_out)==HIGH){
delayMicroseconds(mindelay);} // while the signal of slm_out still High, then do the delay in micorseconds untill the signal goes to Low;
// at the moment, there is a positive image on SLM, wait for SLM switching process
// Now SLM is under switching process the laser should be off, then the next step of SLM will be to change to negative image
if (DoAOTF>0) digitalWrite(aotf_enable,LOW); // stop illumination the SLM
// camera still integrating!
while(digitalRead(slm_out)==LOW) {
delayMicroseconds(mindelay);} // wait that SLM shows negative image
// SLM shows negative image
if (DoAOTF>1) digitalWrite(aotf_enable,HIGH); // illuminate the SLM again
while(digitalRead(slm_out)==HIGH){
delayMicroseconds(mindelay);} // wait that SLM switches to next grating
// SLM is now switching to the next grating
if (DoAOTF>1) digitalWrite(aotf_enable,LOW) ; // stop illuminating the SLM
}
void CheckSLMPos(void) // Checks the state of the SLM and introduces SLM dummy cycles if necessary
// void (does not return anything)
// the void inside the main()means that no return value go into main()
{
long TotalPhases=NumDirs*NumPhases;
while (SLMPhase%TotalPhases != 0) // != (not equal to) //If SLMPhase not the same as TotalPhases
SLMCycle(0);
SLMPhase=0;
}
void loop() {
unsigned long mytime; int wasreset; // 'unsigned' means no negative, show everything only in positive
digitalWrite(slm_trigger,LOW);
digitalWrite(aotf_enable,LOW);
CheckSLMPos();
while(digitalRead(cam_out)==LOW) { // Wait for Camera ready signal -> high
delayMicroseconds(mindelay);
}
mytime=millis();
wasreset=0;
//delay(2); // unit in msec
cli(); // disable the interrupts for the time that pricise timing is needed
//camera is reading out at the moment
//cam ready for exposure
for(int d=0;d<NumDirs;d++) // replications of the pattern // 'd++' means ' d=d+1'
for(int p=0;p<NumPhases;p++) // replications of the pattern
{
//if (~wasreset)
digitalWrite(cam_in,HIGH); //start camera intergration
while(!wasreset && digitalRead(cam_out_G)==LOW) { // Wait for global exposute to go high, // && means 'and'
if (millis() > mytime + mytimeout) // time out reached
wasreset=1;
}
if (wasreset) {delay(100);}
digitalWrite(slm_trigger,HIGH);
for(int i=0;i<rep;i++){ //1 replications of the pattern, but only run SLMCycle once in the first time (i=0)
SLMCycle(2); // 1 shutters only positive frames, 2 shutters both positive and negative frames
digitalWrite(slm_trigger,LOW); //here the arduino has time - so we set the sending trigger signal back to low
}
//if (~wasreset) // ~changes each bit to its opposite, means 'either 1 to 0 or 0 to 1'
digitalWrite(cam_in,LOW) ; //end integration of Camera --> readout starts
while(!wasreset && digitalRead(cam_out)==LOW){ // wait for camera ready signal to go high
delayMicroseconds(mindelay);
if (millis() > mytime + mytimeout) // time out reached
wasreset=1; // The brackets may be omitted after an if statement. If this is done, the next line (defined by the semicolon) becomes the only conditional statement.
}
if (wasreset) {delay(100);}
//for(int i=0;i<NumBlanks;i++){ // listen to the SLM for timing purposes
// SLMCycle(0);
// }
}
sei(); // allow the arduino to perform housekeeping stuff
delayMicroseconds(mindelay); //wait for SLM switching process
// remove the following part if you want to run Life mode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
while(digitalRead(cam_out)==LOW){ // wait for camera ready to go high
delayMicroseconds(mindelay);
}
delay(300); //wait for SLM switching process
while(digitalRead(cam_out)==HIGH){ // wait for camera ready to go low by itself (only for fixed number acquisition)
delayMicroseconds(mindelay);
}
}
| true |
0ff3e38beb728a279507f729bd7edbc0d5fa5938 | C++ | HHHKKKHHH/chi-dou-dou | /hkh-poj/1163.cpp | GB18030 | 937 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define max(a, b) (((a) > (b)) ? (a) : (b))
int row = 0; //
int num[50000] = {}; //
int res[50000] = {}; //DP
int main()
{
cin >> row;
int max = row * (row + 1) / 2 - 1; //±;
for (int i = 0; i <= max; i++)
{
cin >> num[i];
}
for (int i = row; i > 0; i--)
{
for (int index = 0; index < i; index++)
{
int loc = i * (i - 1) / 2 + index ; //ǰ±
if (loc + row > max) //ûһУŽΪǰֵ
{
res[loc] = num[loc];
}
else
{
//ƹʽǰŽ = ²ѡŽֵ + ǰֵ
res[loc] = max(res[loc + i], res[loc + i + 1]) + num[loc];
}
}
}
cout << res[0];
return 0;
} | true |
b670daec76f8f1c99dceb2f7983febcef1a0f72e | C++ | daviddoria/Helpers | /ParallelSort.hpp | UTF-8 | 1,731 | 2.765625 | 3 | [] | no_license | /*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef ParallelSort_HPP
#define ParallelSort_HPP
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template <typename T>
typename ParallelSort<T>::IndexedVectorType ParallelSort<T>::CreateInternalData(const VectorType& v)
{
IndexedVectorType pairs(v.size());
for(unsigned int i = 0; i < v.size(); i++)
{
pairs[i].index = i;
pairs[i].value = v[i];
}
return pairs;
}
template <typename T>
typename ParallelSort<T>::IndexedVectorType ParallelSort<T>::ParallelSortAscending(const VectorType& v)
{
IndexedVectorType internalData = CreateInternalData(v);
std::sort(internalData.begin(), internalData.end());
return internalData;
}
template <typename T>
typename ParallelSort<T>::IndexedVectorType ParallelSort<T>::ParallelSortDescending(const VectorType& v)
{
IndexedVectorType internalData = CreateInternalData(v);
std::sort(internalData.rbegin(), internalData.rend());
return internalData;
}
#endif
| true |
a430f5bf2e01fd3ec4dab1f6ed1d6b2ce1802c07 | C++ | iriszero48/HttpServer | /HttpServer/Convert.h | UTF-8 | 2,907 | 3.203125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <charconv>
#define __Convert_ToStringFunc__(x) #x
#define __Convert_ToString__(x) __Convert_ToStringFunc__(x)
#define __Convert_Line__ __Convert_ToString__(__LINE__)
template<typename...Args>
std::string __Convert_Combine__(Args&&... args)
{
std::string res;
(res.append(args), ...);
return res;
}
#define __Convert_ThrowEx__(...) throw std::runtime_error(__Convert_Combine__(__FILE__ ": " __Convert_Line__ ": ", __func__, ": ", __VA_ARGS__))
template<typename T, typename Str, typename Args>
[[nodiscard]] T __From_String_Impl__(const Str value, const Args args)
{
T res;
const auto begin = value.data();
const auto end = begin + value.length();
auto [p, e] = std::from_chars(begin, end, res, args);
if (e != std::errc{}) __Convert_ThrowEx__("convert error: invalid literal: ", p);
return res;
}
template<typename T, typename...Args>
[[nodiscard]] std::string __To_String_Impl__(const T& value, Args&& ... args)
{
char res[65] = { 0 };
auto [p, e] = std::to_chars(res, res + 65, value, std::forward<Args>(args)...);
if (e != std::errc{}) __Convert_ThrowEx__("convert error: invalid literal: ", p);
return res;
}
namespace Convert
{
template<typename T, std::enable_if_t<std::negation_v<typename std::disjunction<
typename std::is_integral<T>::value,
typename std::is_floating_point<T>::value
>::value>, int> = 0>
[[nodiscard]] std::string ToString(const T& value)
{
return std::string(value);
}
template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
[[nodiscard]] std::string ToString(const T value, const int base = 10)
{
return __To_String_Impl__<T>(value, base);
}
#ifdef _MSC_VER
template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
[[nodiscard]] std::string ToString(const T value)
{
return __To_String_Impl__<T>(value);
}
template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
[[nodiscard]] std::string ToString(const T value, const std::chars_format& fmt)
{
return __To_String_Impl__<T>(value, fmt);
}
template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
[[nodiscard]] std::string ToString(const T value, const std::chars_format& fmt, const int precision)
{
return __To_String_Impl__<T>(value, fmt, precision);
}
#endif
template<typename T, typename Str, std::enable_if_t<std::is_integral_v<T>, int> = 0>
[[nodiscard]] T FromString(const Str value, const int base = 10)
{
return __From_String_Impl__<T>(value, base);
}
#ifdef _MSC_VER
template<typename T, typename Str, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
[[nodiscard]] T FromString(const Str value, const std::chars_format& fmt = std::chars_format::general)
{
return __From_String_Impl__<T>(value, fmt);
}
#endif
}
#undef __Convert_ToStringFunc__
#undef __Convert_ToString__
#undef __Convert_Line__
#undef __Convert_ThrowEx__
| true |
219e1c0bf9957ed81eb786573ce802ce450210b2 | C++ | TeamCOMPAS/COMPAS | /src/Remnants.cpp | UTF-8 | 2,099 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "Remnants.h"
/*
* Calculate:
*
* (a) the maximum mass acceptance rate of this star, as the accretor, during mass transfer, and
* (b) the accretion efficiency parameter
*
*
* The maximum acceptance rate of the accretor star during mass transfer is based on stellar type: this function
* is for compact remnants (NS, BH).
*
* Mass transfer is assumed Eddington limited for BHs and NSs. The formalism of Nomoto/Claeys is used for WDs.
*
* For non compact objects:
*
* 1) Kelvin-Helmholtz (thermal) timescale if THERMAL (thermally limited) mass transfer efficiency
* 2) Choose a fraction of the mass rate that will be effectively accreted for FIXED fraction mass transfer (as in StarTrack)
*
*
* DBL_DBL CalculateMassAcceptanceRate(const double p_DonorMassRate, const double p_AccretorMassRate)
*
* @param [IN] p_DonorMassRate Mass transfer rate of the donor
* @param [IN] p_AccretorMassRate Thermal mass loss rate of the accretor (this star) - ignored here
* @return Tuple containing the Maximum Mass Acceptance Rate and the Accretion Efficiency Parameter
*/
DBL_DBL Remnants::CalculateMassAcceptanceRate(const double p_DonorMassRate, const double p_AccretorMassRate) {
double thisMassRate = CalculateEddingtonCriticalRate();
double acceptanceRate = std::min(thisMassRate, p_DonorMassRate);
double fractionAccreted = acceptanceRate / p_DonorMassRate;
return std::make_tuple(acceptanceRate, fractionAccreted);
}
/*
* Choose timestep for evolution
*
* Can obviously do this your own way
* Given in the discussion in Hurley et al. 2000
*
*
* ChooseTimestep(const double p_Time)
*
* @param [IN] p_Time Current age of star in Myr
* @return Suggested timestep (dt)
*/
double Remnants::ChooseTimestep(const double p_Time) const {
double dtk = std::min(std::max(0.1, 10.0 * std::max(0.1, 10.0 * p_Time)), 5.0E2);
double dte = dtk;
return std::max(dte, NUCLEAR_MINIMUM_TIMESTEP);
}
| true |
2bdae44096380be33d61aa82c8f94a983efb71be | C++ | matthewchiborak/SudsyHD | /Model/BoardObjectInteractSenders/BoardObjectInteractSender.cpp | UTF-8 | 549 | 2.59375 | 3 | [] | no_license | #include "BoardObjectInteractSender.h"
BoardObjectInteractSender::BoardObjectInteractSender()
: hasChild(false)
{
}
bool BoardObjectInteractSender::execute(BoardObject& me, Level& level)
{
if (senderTemplateMethod(me, level))
return true;
if (hasChild)
return child.get()->execute(me, level);
return false;
}
void BoardObjectInteractSender::addChild(std::unique_ptr<BoardObjectInteractSender> child)
{
if (hasChild)
{
this->child.get()->addChild(std::move(child));
return;
}
this->child = std::move(child);
hasChild = true;
}
| true |
35c15def092f3a657c5d1b9e292050311ea0820d | C++ | fade4j/FragmentaryDemosC | /DemosC/DemosC/cpp/ImoocPart4/Circle.cpp | UTF-8 | 159 | 2.765625 | 3 | [] | no_license | #include "Circle.h"
Circle::Circle(double radius) {
m_dRadius = radius;
}
double Circle::calcArea() {
return 3.14 * m_dRadius * m_dRadius;
}
| true |
1a6f5a33a6c9540cb15dd72555b6a7240c98e8cd | C++ | hxbc01/petruk_aritmatika | /infix2posfix.cpp | UTF-8 | 3,173 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <vector>
using namespace std;
// nama kelompok :
//Muhammad Arif A.F - 1907051020
//Muhammad Rasyid Singgih - 1907051014
//Muhammad Zulfikar - 2017051052
vector <string> realInfix;
vector <string> postfix;
bool isOperator(char checkOp);
int prcd(char checkPre);
void parsingInfix(string inpString);
void infixPostfix();
int main(){
string rawInfix;
char inpCh;
while(cin.get(inpCh)){
if(inpCh == '\n'){
break;
}
else if(inpCh != ' '){
rawInfix.push_back(inpCh);
}
}
parsingInfix(rawInfix);
infixPostfix();
return 0;
}
bool isOperator(char checkOp){
return (checkOp == '*' || checkOp == '/' || checkOp == '+' || checkOp == '-' || checkOp == '%');
}
int prcd(char checkPre){
if(checkPre == '*' || checkPre == '/' || checkPre == '%'){
return 4;
} else{
return 2;
}
}
void parsingInfix(string inpString){
string tampung;
for(unsigned int i = 0; i < inpString.length(); i++)
{
if((i == 0 && inpString[i] == '-' && inpString[i + 1] != '(') || isdigit(inpString[i])){
tampung.push_back(inpString[i]);
continue;
}
else if(tampung.length() != 0){
realInfix.push_back(tampung);
tampung.clear();
}
if(inpString[i] == '-' && ((isOperator(inpString[i - 1]) || inpString[i - 1] == '(') || (i == 0 && inpString[i + 1] == '('))){
realInfix.push_back("-1");
realInfix.push_back("*");
}
else if(inpString[i] != ' '){
realInfix.push_back(inpString.substr(i, 1));
}
}
if(tampung.length() != 0)
{
realInfix.push_back(tampung);
tampung.clear();
}
}
void infixPostfix(){
stack <string> opStack;
vector <string>::iterator itr;
int i = 0;
for(itr = realInfix.begin(); itr != realInfix.end(); itr++, i++)
{
if(isdigit(realInfix[i].back())){
postfix.push_back(realInfix[i]);
}
else if(realInfix[i] == "("){
opStack.push(realInfix[i]);
}
else if(realInfix[i] == ")"){
while(!opStack.empty() && opStack.top() != "("){
postfix.push_back(opStack.top());
opStack.pop();
}
opStack.pop();
}
else if(isOperator(realInfix[i][0])){
if(opStack.empty() || opStack.top() == "("){
opStack.push(realInfix[i]);
}
else{
while(!opStack.empty() && opStack.top() != "(" && (prcd(realInfix[i][0]) <= prcd((opStack.top())[0]))){
postfix.push_back(opStack.top());
opStack.pop();
}
opStack.push(realInfix[i]);
}
}
}
while(!opStack.empty()){
postfix.push_back(opStack.top());
opStack.pop();
}
cout << "Print : ";
for(itr = postfix.begin(); itr != postfix.end(); itr++){
cout << *itr << " ";
}
}
| true |
6f4887748684a7a21ca92cea1e8d5b35c9ec8d61 | C++ | koalaa13/Comp-Graphics | /Dithering/Dither.h | UTF-8 | 1,717 | 2.65625 | 3 | [] | no_license | //
// Created by koalaa13 on 6/22/20.
//
#ifndef HW3_DITHER_H
#define HW3_DITHER_H
#include "PNMImage.h"
#include "random"
#include "algorithm"
#include "cmath"
#include "string"
#include "vector"
struct Dither {
static void randomDithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void noDithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void
FloydSteinbergDithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void
JarvisJudiceNinkeDithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void
Sierra3Dithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void AtkinsonDithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void ordered8x8Dithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
static void
halftone4x4Dithering(PNMImage const &image, bool grad, std::string const &output, int bit, double gamma);
private:
static double *getData(PNMImage const &image, bool grad);
static std::vector<double> getValues(int maxValue, int bit);
static void drawGrad(double *data, PNMImage const &image) noexcept;
static double getLeft(std::vector<double> const &values, double value);
static double getRight(std::vector<double> const &values, double value);
static double getValueWithGamma(double value, double maxValue, double gamma);
static double sRGB(double value);
};
#endif //HW3_DITHER_H
| true |
7f84659fefe10128cf26845ac6dda1cb4269e4c7 | C++ | FroxCode/Portfolio-VTA | /src/Item.h | UTF-8 | 831 | 2.84375 | 3 | [
"MIT"
] | permissive | //Created by Dale Sinnott
#ifndef _ITEM_H_
#define _ITEM_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <memory>
#include "SDL_image.h"
class Item {
public:
enum LootType //lootTable
{
AK,
SHOTGUN,
GREEN,
YELLOW_SUNSHINE,
GYM_CANDY,
ELECTRIC_ICE,
VELVET_THUNDER
};
Item(SDL_Point _position, LootType _lootType, SDL_Renderer *r);
~Item();
void render(SDL_Renderer *r);
SDL_Rect bounds;
SDL_Texture* m_texture;
void setLootType(LootType newType) { lootType = newType; }
LootType getLootType() { return lootType; }
private:
LootType lootType;
int move_limiter = 3; //pixels to move
int originalY;
int movingTimer = 0;
bool switchDirection = false;
int const WIDTH = 32;
int const HEIGHT = 32;
};
#endif;
| true |
0759636fa3cba8d5f116934dd4fc5f9410f38971 | C++ | smartjinyu/LeetCode_2018 | /150_Evaluate_Reverse_Polish_Notation.cpp | UTF-8 | 1,471 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;
int evalRPN(vector<string>& tokens) {
stack<int> nums;
for(string str : tokens){
if(str.size() == 1 && str[0] == '+'){
if(!nums.empty()){
int num1 = nums.top(); nums.pop();
int num2 = nums.top(); nums.pop();
nums.push(num1 + num2);
}
} else if(str.size() == 1 && str[0] == '-'){
if(!nums.empty()){
int num1 = nums.top(); nums.pop();
int num2 = nums.top(); nums.pop();
nums.push(num2 - num1);
}
} else if(str.size() == 1 && str[0] == '*'){
if(!nums.empty()){
int num1 = nums.top(); nums.pop();
int num2 = nums.top(); nums.pop();
nums.push(num1 * num2);
}
} else if(str.size() == 1 && str[0] == '/'){
if(!nums.empty()){
int num1 = nums.top(); nums.pop();
int num2 = nums.top(); nums.pop();
nums.push(num2 / num1);
}
} else{
int num = stoi(str);
nums.push(num);
}
}
return nums.top();
}
int main(){
vector<string> tokens;
tokens.push_back("2"); tokens.push_back("1");
tokens.push_back("+"); tokens.push_back("-3"); tokens.push_back("*");
printf("%d\n",evalRPN(tokens));
return 0;
} | true |
f7fefc0d0190b1c4c0b70e22ab5a5e7da3d0b360 | C++ | AbyssAbbeba/MDS-picoblaze-AVR-ide | /IDE/compiler/core/CompilerExpr.cxx | UTF-8 | 13,964 | 2.71875 | 3 | [] | no_license | // =============================================================================
/**
* @brief
* C++ Implementation: ...
*
* ...
*
* (C) copyright 2013, 2014 Moravia Microsystems, s.r.o.
*
* @author Martin Ošmera <martin.osmera@moravia-microsystems.com>
* @ingroup Compiler
* @file CompilerExpr.cxx
*/
// =============================================================================
#include "CompilerExpr.h"
// Standard header files.
#include <cstring>
#include <cctype>
#include <cstdlib>
CompilerExpr::CompilerExpr ( CompilerSerializer & input )
{
deserialize(input);
}
CompilerExpr::CompilerExpr ( CompilerSourceLocation location )
{
m_operator = OPER_NONE;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( CompilerValue value,
CompilerSourceLocation location )
{
m_lValue = value;
m_operator = OPER_NONE;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( Operator oper,
CompilerValue value,
CompilerSourceLocation location )
{
m_operator = oper;
m_rValue = value;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( char oper,
CompilerValue value,
CompilerSourceLocation location )
{
m_operator = Operator(oper);
m_rValue = value;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( CompilerValue value,
Operator oper,
CompilerSourceLocation location )
{
m_operator = Operator(oper);
m_lValue = value;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( CompilerValue value,
char oper,
CompilerSourceLocation location )
{
m_operator = Operator(oper);
m_lValue = value;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( CompilerValue lValue,
Operator oper,
CompilerValue rValue,
CompilerSourceLocation location )
{
m_lValue = lValue;
m_operator = oper;
m_rValue = rValue;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr::CompilerExpr ( CompilerValue lValue,
char oper,
CompilerValue rValue,
CompilerSourceLocation location )
{
m_lValue = lValue;
m_operator = Operator(oper);
m_rValue = rValue;
m_location = location;
m_next = nullptr;
m_prev = nullptr;
}
CompilerExpr * CompilerExpr::first()
{
if ( nullptr == this )
{
return nullptr;
}
auto result = this;
while ( nullptr != result->m_prev )
{
result = result->m_prev;
}
return result;
}
CompilerExpr * CompilerExpr::last()
{
if ( nullptr == this )
{
return nullptr;
}
auto result = this;
while ( nullptr != result->m_next )
{
result = result->m_next;
}
return result;
}
CompilerExpr * CompilerExpr::insertLink ( CompilerExpr * chainLink )
{
if ( nullptr == chainLink )
{
return this;
}
if ( nullptr == this )
{
return chainLink;
}
CompilerExpr * chainLinkOrig = chainLink;
CompilerExpr * chainLinkLast = chainLink->last();
CompilerExpr * nextOrig = m_next;
chainLink = chainLink->first();
m_next = chainLink;
chainLink->m_prev = this;
chainLinkLast->m_next = nextOrig;
nextOrig->m_prev = chainLinkLast;
return chainLinkOrig;
}
CompilerExpr * CompilerExpr::appendLink ( CompilerExpr * chainLink )
{
if ( nullptr == chainLink )
{
return this;
}
if ( nullptr == this )
{
return chainLink;
}
CompilerExpr * chainLinkOrig = chainLink;
CompilerExpr * lastLink = last();
chainLink = chainLink->first();
lastLink->m_next = chainLink;
chainLink->m_prev = lastLink;
return chainLinkOrig;
}
CompilerExpr * CompilerExpr::prependLink ( CompilerExpr * chainLink )
{
if ( nullptr == chainLink )
{
return this;
}
if ( nullptr == this )
{
return chainLink;
}
CompilerExpr * chainLinkOrig = chainLink;
CompilerExpr * firstLink = first();
chainLink = chainLink->last();
chainLink->m_next = firstLink;
firstLink->m_prev = chainLink;
return chainLinkOrig;
}
void CompilerExpr::completeDelete ( CompilerExpr * expr )
{
expr->completeDelete();
}
void CompilerExpr::completeDelete()
{
if ( nullptr == this )
{
return;
}
m_lValue.completeDelete();
m_rValue.completeDelete();
if ( nullptr != m_next )
{
m_next->m_prev = nullptr;
m_next->completeDelete();
m_next = nullptr;
}
if ( nullptr != m_prev )
{
m_prev->m_next = nullptr;
m_prev->completeDelete();
m_prev = nullptr;
}
delete this;
}
CompilerExpr * CompilerExpr::operator [] ( int index )
{
auto result = this;
for ( int i = 0; i < index; i++ )
{
result = result->m_next;
if ( nullptr == result )
{
return nullptr;
}
}
return result;
}
CompilerExpr * CompilerExpr::copyEntireChain() const
{
if ( nullptr == this )
{
return nullptr;
}
auto result = copyChainLink();
auto next = this;
while ( nullptr != ( next = next->m_next ) )
{
result->appendLink(next->copyChainLink());
}
auto prev = this;
while ( nullptr != ( prev = prev->m_prev ) )
{
result->prependLink(prev->copyChainLink());
}
return result;
}
CompilerExpr * CompilerExpr::copyChainLink() const
{
if ( nullptr == this )
{
return nullptr;
}
auto result = new CompilerExpr();
CompilerValue * val;
val = m_lValue.makeCopy();
result->m_lValue = *val;
delete val;
val = m_rValue.makeCopy();
result->m_rValue = *val;
delete val;
result->m_operator = m_operator;
result->m_location = m_location;
return result;
}
CompilerExpr * CompilerExpr::unlink()
{
if ( nullptr != m_next )
{
m_next->m_prev = m_prev;
m_next = nullptr;
}
if ( nullptr != m_prev )
{
m_prev->m_next = m_next;
m_prev = nullptr;
}
return this;
}
std::ostream & operator << ( std::ostream & out,
const CompilerExpr::Operator & opr )
{
switch ( opr )
{
case CompilerExpr::OPER_NONE: break;
case CompilerExpr::OPER_ADD: out << "+"; break;
case CompilerExpr::OPER_SUB: out << "-"; break;
case CompilerExpr::OPER_MULT: out << "*"; break;
case CompilerExpr::OPER_DIV: out << "/"; break;
case CompilerExpr::OPER_MOD: out << "%"; break;
case CompilerExpr::OPER_DOT: out << "."; break;
case CompilerExpr::OPER_BOR: out << "|"; break;
case CompilerExpr::OPER_BXOR: out << "^"; break;
case CompilerExpr::OPER_BAND: out << "&"; break;
case CompilerExpr::OPER_LOR: out << "||"; break;
case CompilerExpr::OPER_LXOR: out << "^^"; break;
case CompilerExpr::OPER_LAND: out << "&&"; break;
case CompilerExpr::OPER_LOW: out << "low"; break;
case CompilerExpr::OPER_HIGH: out << "high"; break;
case CompilerExpr::OPER_EQ: out << "=="; break;
case CompilerExpr::OPER_NE: out << "!="; break;
case CompilerExpr::OPER_LT: out << "<"; break;
case CompilerExpr::OPER_LE: out << "<="; break;
case CompilerExpr::OPER_GE: out << ">="; break;
case CompilerExpr::OPER_GT: out << ">"; break;
case CompilerExpr::OPER_SHR: out << ">>"; break;
case CompilerExpr::OPER_SHL: out << "<<"; break;
case CompilerExpr::OPER_CALL: out << "call"; break;
case CompilerExpr::OPER_INT_PROM: out << "<+pos>"; break;
case CompilerExpr::OPER_ADD_INV: out << "<-neg>"; break;
case CompilerExpr::OPER_CMPL: out << "~"; break;
case CompilerExpr::OPER_NOT: out << "!"; break;
case CompilerExpr::OPER_ADD_ASSIGN: out << "+="; break;
case CompilerExpr::OPER_SUB_ASSIGN: out << "-="; break;
case CompilerExpr::OPER_MUL_ASSIGN: out << "*="; break;
case CompilerExpr::OPER_DIV_ASSIGN: out << "/="; break;
case CompilerExpr::OPER_MOD_ASSIGN: out << "%="; break;
case CompilerExpr::OPER_SHL_ASSIGN: out << "<<="; break;
case CompilerExpr::OPER_SHR_ASSIGN: out << ">>="; break;
case CompilerExpr::OPER_AND_ASSIGN: out << "&="; break;
case CompilerExpr::OPER_ORB_ASSIGN: out << "|="; break;
case CompilerExpr::OPER_XOR_ASSIGN: out << "^="; break;
case CompilerExpr::OPER_AT: out << "@"; break;
case CompilerExpr::OPER_INTERVALS: out << ".."; break;
case CompilerExpr::OPER_ASSIGN: out << "="; break;
case CompilerExpr::OPER_NAND: out << "!&"; break;
case CompilerExpr::OPER_HASH: out << "#"; break;
case CompilerExpr::OPER_REF: out << "&reference"; break;
case CompilerExpr::OPER_DEREF: out << "*dereference"; break;
case CompilerExpr::OPER_CONDITION: out << "?"; break;
case CompilerExpr::OPER_COLON: out << ":"; break;
case CompilerExpr::OPER_INDEX: out << "[index]"; break;
case CompilerExpr::OPER_INC: out << "post++"; break;
case CompilerExpr::OPER_DEC: out << "post--"; break;
case CompilerExpr::OPER_PRE_INC: out << "++pre"; break;
case CompilerExpr::OPER_PRE_DEC: out << "--pre"; break;
case CompilerExpr::OPER_DATATYPE: out << "datatype"; break;
case CompilerExpr::OPER_ARROW: out << "->"; break;
case CompilerExpr::OPER_COMMA: out << ","; break;
case CompilerExpr::OPER_SIZEOF: out << "sizeof"; break;
case CompilerExpr::OPER_FIXED_DATATYPE: out << "fixed-datatype"; break;
case CompilerExpr::OPER_CAST: out << "cast"; break;
case CompilerExpr::OPER_ADDR: out << "&addr"; break;
case CompilerExpr::OPER_DECLARATION: out << "declaration"; break;
case CompilerExpr::OPER_INIT: out << "=init"; break;
case CompilerExpr::OPER_PAIR: out << "pair"; break;
case CompilerExpr::OPER_POINTER: out << "*pointer"; break;
case CompilerExpr::OPER_ARRAY: out << "[array]"; break;
case CompilerExpr::OPER_FUNCTION: out << "function"; break;
case CompilerExpr::OPER_GENERIC: out << "generic"; break;
case CompilerExpr::OPER_ALIGNOF: out << "alignof"; break;
case CompilerExpr::OPER_ALIGNAS: out << "alignas"; break;
case CompilerExpr::OPER_ASSERT: out << "assert"; break;
case CompilerExpr::OPER_COMPOUND: out << "compound"; break;
}
return out;
}
std::ostream & operator << ( std::ostream & out,
const CompilerExpr * const expr )
{
if ( nullptr == expr )
{
out << "(<nullptr>)";
return out;
}
if ( CompilerExpr::OPER_NONE == expr->m_operator )
{
out << "(" << expr->lVal() << ")";
}
else
{
out << "(" << expr->lVal() << " " << expr->m_operator << " " << expr->rVal() << std::string(")");
}
out << " {";
out << expr->location();
out << "}";
if ( nullptr != expr->next() )
{
out << " | " << expr->next();
}
return out;
}
std::ostream & operator << ( std::ostream & out,
const CompilerExpr & expr )
{
out << &expr;
return out;
}
void CompilerExpr::serialize ( CompilerSerializer & output ) const
{
output.write ( (uint16_t) m_operator );
output << m_lValue << m_rValue << m_location;
if ( nullptr == m_next )
{
output << MARK_TERMINAL;
}
else
{
output << MARK_NEXT;
output << m_next;
}
}
void CompilerExpr::deserialize ( CompilerSerializer & input )
{
m_next = nullptr;
m_prev = nullptr;
m_operator = Operator(input.read_ui16());
input >> m_lValue >> m_rValue >> m_location;
SerializationMark mark;
input >> mark;
if ( MARK_NEXT == mark )
{
m_next = new CompilerExpr(input);
m_next->m_prev = this;
}
}
| true |
8497a4f3b719dd343ee67851b01138f3c68ea99a | C++ | Khodii/SyntheticTestCases | /CWE20/example1.cpp | UTF-8 | 577 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int berechneKontostand(int kontostand, int geldabnahme){
kontostand = kontostand - geldabnahme;
return kontostand;
}
int main() {
int kontostand = 1000;
int abgehoben;
cout << "Wie viel Geld wollen sie abheben?" << endl;
cin >> abgehoben;
/* Eingabe wird nicht auf Korrektheit (zum Beispiel negative Zahlen) ueberprueft sondern weiterverwendet */
kontostand = berechneKontostand(kontostand, abgehoben);
/* Bei einer negativen Eingabe wuerde sich der Kontostand unerwuenscht erhoehen */
cout << kontostand;
return 0;
}
| true |
b6924b9704b4802c6a5b41b36f9bf8dcd4bf5965 | C++ | ssanupam24/Practice-Code | /cpp-examples/min-increment-decrement.cpp | UTF-8 | 770 | 2.90625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> arr = {1, 100, 50, 100};
int small = *min_element(arr.begin(), arr.end());
int large = *max_element(arr.begin(), arr.end());
vector<vector<int>> dp(arr.size(), vector<int>(large+1, 0));
for (int i = small; i <= large; i++) {
dp[0][i] = abs(arr[0] - i);
}
for (int i = 1; i < arr.size(); i++) {
int min_elem = INT_MAX;
for (int j = small; j <= large; j++) {
min_elem = min(min_elem, dp[i-1][j]);
dp[i][j] = min_elem + abs(arr[i] - j);
}
}
int min_elem = INT_MAX;
for (int i = small; i <= large; i++) {
min_elem = min(min_elem, dp[arr.size() - 1][i]);
}
cout << min_elem;
return 0;
} | true |
1f73c300cb9b8465e5864f7c473f950c765ff949 | C++ | Aenohe/WAVM | /Include/Core/SExpressions.h | UTF-8 | 7,132 | 3.03125 | 3 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | #pragma once
#include "Core/Core.h"
#include "Core/MemoryArena.h"
#ifdef _WIN32
#pragma warning (disable:4512) // assignment operator could not be generated
#endif
namespace SExp
{
// The type of a S-expression node.
enum class SNodeType : uint8
{
Symbol,
String,
UnindexedSymbol,
Name,
SignedInt,
UnsignedInt,
Float,
Error,
Tree,
Attribute // A tree with two children implicitly separated by an '='
};
// A node in a tree of S-expressions
struct SNode
{
// The type of the node. Determines how to interpret the union.
SNodeType type;
union
{
const char* error;
uintp symbol;
const char* string;
int64 i64;
uint64 u64;
float64 f64;
SNode* children;
};
union
{
// If type==NodeType::String, contains the length of the string.
// string[stringLength] will be zero, but stringLength may not be the first zero in the string.
size_t stringLength;
// If type==NodeType::Float, contains a 32-bit float representation of the node.
float32 f32;
};
// The next node with the same parent.
SNode* nextSibling;
// The start of this node in the source file.
Core::TextFileLocus startLocus;
// The end of this node in the source file.
Core::TextFileLocus endLocus;
SNode(const Core::TextFileLocus& inStartLocus = Core::TextFileLocus(),SNodeType inType = SNodeType::Tree)
: type(inType)
, children(nullptr)
, stringLength(0)
, nextSibling(nullptr)
, startLocus(inStartLocus)
, endLocus(inStartLocus)
{}
};
// Iterates over sibling nodes in a S-expression tree.
struct SNodeIt
{
SNode* node;
Core::TextFileLocus previousLocus;
SNodeIt(): node(nullptr) {}
explicit SNodeIt(SNode* inNode,Core::TextFileLocus inPreviousLocus = Core::TextFileLocus())
: node(inNode), previousLocus(inPreviousLocus) {}
SNodeIt& operator++()
{
if(node)
{
previousLocus = node->endLocus;
node = node->nextSibling;
}
return *this;
}
SNodeIt operator++(int)
{
SNodeIt copy = *this;
++(*this);
return copy;
}
SNodeIt getChildIt() const
{
assert(node->type == SNodeType::Tree || node->type == SNodeType::Attribute);
return SNodeIt(node->children,node->startLocus);
}
SNode* operator->() const { return node; }
operator SNode*() const { return node; }
operator bool() const { return node != nullptr; }
};
// Parses a S-expression tree from a string, allocating nodes from arena, and using symbolIndexMap to map symbols to indices.
struct StringCompareFunctor { bool operator()(const char* left,const char* right) const
{
while(true)
{
if(*left == *right)
{
if(!*left) { return false; }
}
else if(*left < *right)
{
return true;
}
else
{
return false;
}
++left;
++right;
};
}};
typedef std::map<const char*,uintp,StringCompareFunctor> SymbolIndexMap;
CORE_API SNode* parse(const char* string,MemoryArena::Arena& arena,const SymbolIndexMap& symbolIndexMap);
// Parse an integer from a S-expression node.
inline bool parseInt(SNodeIt& nodeIt,int32& outInt)
{
if(nodeIt && nodeIt->type == SNodeType::SignedInt && nodeIt->u64 <= (uint64)-int64(INT32_MIN)) { outInt = (int32)-nodeIt->i64; ++nodeIt; return true; }
if(nodeIt && nodeIt->type == SNodeType::UnsignedInt && nodeIt->u64 <= (uint64)UINT32_MAX) { outInt = (int32)nodeIt->u64; ++nodeIt; return true; }
else { return false; }
}
inline bool parseInt(SNodeIt& nodeIt,int64& outInt)
{
if(nodeIt && nodeIt->type == SNodeType::SignedInt && nodeIt->u64 <= (uint64)-INT64_MIN) { outInt = -nodeIt->i64; ++nodeIt; return true; }
if(nodeIt && nodeIt->type == SNodeType::UnsignedInt) { outInt = nodeIt->u64; ++nodeIt; return true; }
else { return false; }
}
inline bool parseUnsignedInt(SNodeIt& nodeIt,uint64& outInt)
{
if(nodeIt && nodeIt->type == SNodeType::UnsignedInt) { outInt = nodeIt->u64; ++nodeIt; return true; }
else { return false; }
}
// Parse a float from a S-expression node.
inline bool parseFloat(SNodeIt& nodeIt,float32& outF32)
{
if(nodeIt && nodeIt->type == SNodeType::Float) { outF32 = nodeIt->f32;++nodeIt; return true; }
else if(nodeIt && nodeIt->type == SNodeType::SignedInt) { outF32 = -(float32)nodeIt->u64; ++nodeIt; return true; }
else if(nodeIt && nodeIt->type == SNodeType::UnsignedInt) { outF32 = (float32)nodeIt->u64; ++nodeIt; return true; }
else { return false; }
}
inline bool parseFloat(SNodeIt& nodeIt,float64& outF64)
{
if(nodeIt && nodeIt->type == SNodeType::Float) { outF64 = nodeIt->f64;++nodeIt; return true; }
else if(nodeIt && nodeIt->type == SNodeType::SignedInt) { outF64 = -(float64)nodeIt->u64; ++nodeIt; return true; }
else if(nodeIt && nodeIt->type == SNodeType::UnsignedInt) { outF64 = (float64)nodeIt->u64; ++nodeIt; return true; }
else { return false; }
}
// Parse a string from a S-expression node.
inline bool parseString(SNodeIt& nodeIt,std::string& outString)
{
if(nodeIt && nodeIt->type == SNodeType::String)
{
outString = std::string(nodeIt->string,nodeIt->stringLength);
++nodeIt;
return true;
}
else { return false; }
}
// Parse a S-expression tree or attribute node. Upon success, outChildIt is set to the node's first child.
inline bool parseTreelikeNode(SNodeIt nodeIt,SNodeType nodeType,SNodeIt& outChildIt)
{
if(nodeIt && nodeIt->type == nodeType) { outChildIt = nodeIt.getChildIt(); return true; }
else { return false; }
}
inline bool parseTreeNode(SNodeIt nodeIt,SNodeIt& outChildIt) { return parseTreelikeNode(nodeIt,SNodeType::Tree,outChildIt); }
inline bool parseAttributeNode(SNodeIt nodeIt,SNodeIt& outChildIt) { return parseTreelikeNode(nodeIt,SNodeType::Attribute,outChildIt); }
// Parse a S-expression symbol node. Upon success, outSymbol is set to the parsed symbol.
template<typename Symbol>
bool parseSymbol(SNodeIt& nodeIt,Symbol& outSymbol)
{
if(nodeIt && nodeIt->type == SNodeType::Symbol) { outSymbol = (Symbol)nodeIt->symbol; ++nodeIt; return true; }
else { return false; }
}
// Parse a S-expression tree node whose first child is a symbol. Sets outChildren to the first child after the symbol on success.
template<typename Symbol>
bool parseTaggedNode(SNodeIt nodeIt,Symbol tagSymbol,SNodeIt& outChildIt)
{
Symbol symbol;
return parseTreeNode(nodeIt,outChildIt) && parseSymbol(outChildIt,symbol) && symbol == tagSymbol;
}
// Parse a S-expression attribute node whose first child is a symbol. Sets outValue to the attribute value.
template<typename Symbol>
bool parseSymbolAttribute(SNodeIt nodeIt,Symbol keySymbol,SNodeIt& outValueIt)
{
Symbol symbol;
return parseAttributeNode(nodeIt,outValueIt) && parseSymbol(outValueIt,symbol) && symbol == keySymbol;
}
// Tries to parse a name from a SExp node (a string symbol starting with a $).
// On success, returns true, sets outString to the name's string, and advances node to the sibling following the name.
inline bool parseName(SNodeIt& nodeIt,const char*& outString)
{
if(nodeIt && nodeIt->type == SNodeType::Name)
{
outString = nodeIt->string;
++nodeIt;
return true;
}
else
{
return false;
}
}
}
| true |
b9d47fc6f460ece4b5fdecbb1d5cff6440c48181 | C++ | watrick/HelloWorld.cpp | /HelloWorld.cpp | UTF-8 | 218 | 2.71875 | 3 | [] | no_license | /* My first C++ program
Author: Patrick Fedigan
Date: 8/21/2013 */
#include <iostream>
int main() {
std::cout << "Hello, World!\n\n";
std::cout << "Press Enter to Continue";
std::cin.get();
return 0;
}
| true |
a09343b77b5f02da23fd678445a1783e2992508e | C++ | JerryZhou/opensc | /3rd/n3/code/extlibs/bullet/src/Physics/RigidBody/common/vec_utils.h | UTF-8 | 3,127 | 2.515625 | 3 | [] | no_license | /* [SCE CONFIDENTIAL DOCUMENT]
* $PSLibId$
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* All Rights Reserved.
*/
#ifndef __VEC_UTILS_H__
#define __VEC_UTILS_H__
#include <stdlib.h>
#include <vectormath_aos.h>
using namespace Vectormath::Aos;
static const float lenSqrTol = 1.0e-30f;
inline
Vector3
safeNormalize( Vector3 vec )
{
float lenSqr = lengthSqr( vec );
if ( lenSqr > lenSqrTol ) {
float lenInv = 1.0f/sqrtf(lenSqr);
return vec * lenInv;
} else {
return Vector3( 1.0f, 0.0f, 0.0f );
}
}
inline float square( float a )
{
return a * a;
}
//inline float randfloat() { return 2.0f*drand48() - 1.0f; }
//inline float randfloat() { return 2.0f*( (float)(rand()%1000000)/1.0e6f ) - 1.0f; }
inline float randfloat()
{
return 0.5f;
}
inline
Vector3
rand_perp( Vector3 vec )
{
Vector3 result;
Vector3 abs_vec = Vector3( absPerElem(vec) );
Vector3 cross_vec;
if ( ( abs_vec[0] > abs_vec[1] ) && ( abs_vec[0] > abs_vec[2] ) ) {
cross_vec = Vector3( 0.9f*randfloat(), 1.0f, 0.9f*randfloat());
} else {
cross_vec = Vector3( 1.0f, 0.9f*randfloat(), 0.9f*randfloat());
}
return cross(vec, cross_vec );
}
inline
Vector3
perp( Vector3 vec )
{
Vector3 result;
Vector3 core_vec = Vector3( vec );
Vector3 abs_vec = Vector3( absPerElem(vec) );
if ( ( abs_vec[0] > abs_vec[1] ) && ( abs_vec[0] > abs_vec[2] ) ) {
result[0] = -core_vec[2];
result[1] = 0.0f;
result[2] = core_vec[0];
} else {
result[0] = 0.0f;
result[1] = core_vec[2];
result[2] = -core_vec[1];
}
return Vector3( result );
}
inline
Vector3
unit_cross( Vector3 veca, Vector3 vecb )
{
Vector3 result;
result = cross(veca, vecb );
float lenSqr = lengthSqr(result);
if ( lenSqr > lenSqrTol ) {
float lenInv = 1.0f/sqrtf( lenSqr );
result *= lenInv;
} else {
result = normalize(perp( veca ));
}
return result;
}
inline
void angleAxis(const Quat &unitQuat,float &angle,Vector3 &axis)
{
const float epsilon=0.00001f;
if (fabsf(unitQuat.getW()) < 1.0f-epsilon && lengthSqr(unitQuat.getXYZ()) > epsilon) {
float angleHalf = acosf(unitQuat.getW());
float sinAngleHalf = sinf(angleHalf);
if(fabsf(sinAngleHalf) > 1.0e-10f) {
axis = unitQuat.getXYZ()/sinAngleHalf;
} else {
axis = unitQuat.getXYZ();
}
angle = 2.0f*angleHalf;
} else {
angle = 0.0f;
axis = Vector3(1.0f, 0.0f, 0.0f);
}
}
inline
void getPlaneSpace(const Vector3& n, Vector3& p, Vector3& q)
{
if (fabsf(n[2]) > 0.707f) {
// choose p in y-z plane
float a = n[1]*n[1] + n[2]*n[2];
float k = 1.0f/sqrtf(a);
p[0] = 0;
p[1] = -n[2]*k;
p[2] = n[1]*k;
// set q = n x p
q[0] = a*k;
q[1] = -n[0]*p[2];
q[2] = n[0]*p[1];
}
else {
// choose p in x-y plane
float a = n[0]*n[0] + n[1]*n[1];
float k = 1.0f/sqrtf(a);
p[0] = -n[1]*k;
p[1] = n[0]*k;
p[2] = 0;
// set q = n x p
q[0] = -n[2]*p[1];
q[1] = n[2]*p[0];
q[2] = a*k;
}
}
#endif /* __VEC_UTILS_H__ */
| true |
3801c6d17a50b24bc448554d7812c3443d5138c1 | C++ | mcopik/cxx-langstat | /test/unit/constexpr/ConstexprFac.cpp | UTF-8 | 709 | 2.65625 | 3 | [
"Apache-2.0",
"LLVM-exception"
] | permissive | // RUN: rm %t1.ast.json || true
// RUN: %clangxx %s -emit-ast -o %t1.ast
// RUN: %cxx-langstat --analyses=cea -emit-features -in %t1.ast -out %t1.ast.json --
// RUN: diff %t1.ast.json %s.json
// Don't ever use this code.
//
//
#include<iostream>
struct Fac{
constexpr Fac() : res(1){}
constexpr Fac(const int n){
if (n>1){
Fac f(n-1); // why this not constexpr?
res = n*f.get();
} else {
constexpr Fac f;
res = f.get();
}
}
constexpr int get() const{
return res;
}
int res;
};
int main(int argc, char** argv){
constexpr Fac f(10);
constexpr int x = f.get();
std::cout << x << std::endl;
}
| true |
b8e118b4451da51907c50d9fc0e1c12e724c605b | C++ | kush0603/Single-instance-share | /hac/HackKMP.cpp | UTF-8 | 782 | 2.640625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int sum=0;
int a[26],min=999999;
for(int i=0;i<26;i++)
{
cin>>a[i];
sum = sum+a[i];
if(min>a[i] && a[i]>0)
min = a[i];
}
string s="";
//cout<<min;
while(s.length()!=sum)
{
for(int i=0;i<26;i++)
{
if(a[i]==min && min !=999999)
{
a[i]=999999;
//cout<<a[i];
while(min--)
{
char c = 97+i;
//cout<<c;
s = s+c;
}
}
}
min = *min_element(a,a+25);
//cout<<s;
//cout<<s.length()<<"\n";
}
cout<<s;
}
| true |
2cbc2868d36667ed9fe11269a8873ac1e073fa63 | C++ | bazsodombiandras/StreamSearcher | /StreamSearcher/src/StreamSearch/StreamSearcher.h | UTF-8 | 2,675 | 3.296875 | 3 | [] | no_license | #pragma once
#include "../InputDataHandling/IInputDataSource.h"
#include <istream>
#include <set>
using namespace InputDataHandling;
using namespace std;
namespace StreamSearch
{
/// <summary>
/// Searches streams of data for multiple search terms.
/// </summary>
class StreamSearcher
{
private:
/// <summary>
/// The search terms.
/// </summary>
set<string> searchTerms;
/// <summary>
/// The results (found search terms in the data streams).
/// </summary>
set<string> results;
/// <summary>
/// The default constructor is disabled because the search terms are always needed to construct an instance (makes no sense to search for nothing).
/// </summary>
StreamSearcher() = delete;
/// <summary>
/// Search a single input data stream for the search terms.
/// </summary>
/// <param name="inputStream">the input data stream.</param>
void SearchStream(istream& inputStream);
public:
/// <summary>
/// Constructs an instance of this class based on a collection of search terms.
/// </summary>
/// <param name="searchTerms">The search terms.</param>
StreamSearcher(const set<string>& searchTerms);
/// <summary>
/// Allows copying the data of the stream searcher through the default copy constructor.
/// </summary>
/// <param name="">The instance to copy the data from.</param>
StreamSearcher(const StreamSearcher&) = default;
/// <summary>
/// Allows moving the data of the stream searcher through the default move constructor.
/// </summary>
/// <param name="">The instance to move the data from.</param>
StreamSearcher(StreamSearcher&&) = default;
/// <summary>
/// Gets the results of the last search.
/// </summary>
/// <returns>The results.</returns>
const set<string>& GetResults() const;
/// <summary>
/// SEarches all the input data for the search terms.
/// </summary>
/// <param name="inputDataSource">The input data source.</param>
void SearchInputData(IInputDataSource& inputDataSource);
/// <summary>
/// Allows copying the data of the stream searcher through the default copy assignment operator.
/// </summary>
/// <param name="">The instance to copy the data from.</param>
/// <returns>The instance into which the data has been copied.</returns>
StreamSearcher& operator= (const StreamSearcher&) = default;
/// <summary>
/// Allows moving the data of the stream searcher through the default move assignment operator.
/// </summary>
/// <param name="">The instance to move the data from.</param>
/// <returns>The instance into which the data has been moved.</returns>
StreamSearcher& operator= (StreamSearcher&&) = default;
};
}
| true |
a6707dd70e6c6745607cd0e0a2852dc3e30f809a | C++ | casen330/Design-Pattern | /命令模式/命令模式.cpp | GB18030 | 2,821 | 3.796875 | 4 | [] | no_license | //࣬ʵһһķ
#include<iostream>
#include<list>
using namespace std;
class Doctor
{
public:
void treat_eye(){
cout << "ҽ ۿƲ" << endl;
}
void treat_nose(){
cout << "ҽ ǿƲ" << endl;
}
};
//һ
class CommandTreat
{
public:
virtual void treat() = 0;
};
//
class CommandTreatEye:public CommandTreat
{
public:
CommandTreatEye(Doctor *doc)
{
m_doctor = doc;
}
void treat(){
m_doctor->treat_eye();
}
private:
Doctor *m_doctor;
};
class CommandTreatNose:public CommandTreat
{
public:
CommandTreatNose(Doctor *doc)
{
m_doctor = doc;
}
void treat(){
m_doctor->treat_nose();
}
private:
Doctor *m_doctor;
};
//ʿ
class BeautyNurse
{
public:
BeautyNurse(CommandTreat *comm)
{
m_command = comm;
}
void SubmittedCase()///ύ
{
m_command->treat();
}
private:
CommandTreat *m_command;
};
//ʿ
class HeadNurse
{
public:
HeadNurse(){
m_list.clear(); //list
}
void setCommand(CommandTreat *command)
{
m_list.push_back(command);
}
void SubmittedCase()///ύ
{
for (list<CommandTreat*>::iterator it = m_list.begin();
it != m_list.end(); it++)
{
(*it)->treat();
}
}
private:
CommandTreat *m_command;
list<CommandTreat*> m_list;
};
int main1(){
//1,ҽֱӿ
Doctor *doctor = new Doctor;
doctor->treat_eye();
delete doctor;
//2ͨҽͨۿƲ
Doctor *doctor1 = new Doctor;
CommandTreat *commandtreat = new CommandTreatEye(doctor1);
commandtreat->treat();
delete commandtreat;
delete doctor1;
return 0;
}
int main2(){
//ʿύ˿
Doctor *doctor2 = NULL;
CommandTreat *commandtreat = NULL;
BeautyNurse *nurse = NULL;
doctor2 = new Doctor;
commandtreat = new CommandTreatEye(doctor2);
nurse = new BeautyNurse(commandtreat);
nurse->SubmittedCase();
delete commandtreat;
delete nurse;
commandtreat = new CommandTreatNose(doctor2);
nurse = new BeautyNurse(commandtreat);
nurse->SubmittedCase();
delete doctor2;
delete commandtreat;
delete nurse;
return 0;
}
int main3(){
//ͨʿµ
Doctor *doctor3 = NULL;
HeadNurse *headnurse = NULL;
CommandTreat *commandtreat1 = NULL;
CommandTreat *commandtreat2 = NULL;
doctor3 = new Doctor;
commandtreat1 = new CommandTreatEye(doctor3);
commandtreat2 = new CommandTreatNose(doctor3);
headnurse = new HeadNurse();
headnurse->setCommand(commandtreat1); //ʿ
headnurse->setCommand(commandtreat2);
headnurse->SubmittedCase(); //ʿ´
delete doctor3;
delete commandtreat1;
delete commandtreat2;
delete headnurse;
return 0;
}
int main(){
//main1();
//main2();
main3();
return 0;
} | true |
021676583a372aeffd804b1e35bc216d83d3ee88 | C++ | funtalex/first_task | /Solver_of_Square_Equation.cpp | UTF-8 | 1,953 | 3.6875 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <assert.h>
const int INF_NUM_OF_ROOTS = 3;
/*!
\author Alex Sergeechev aka funtalex
\version 2.0
\brief This function solves an equation ax^2 + bx + c = 0
\param[in] a - coefficient for x^2
\param[in] b - coefficient for x
\param[in] c - constant element
\param[out] x1 - pointer of first root (if exist)
\param[out] x2 - pointer of second root (if exist)
\return number of roots
\warning don't enter nan or inf, only finite number
*/
int solve_equation(double a, double b, double c, double* x1, double* x2) {
assert(isfinite(a));
assert(isfinite(b));
assert(isfinite(c));
assert(isfinite(x1));
assert(isfinite(x2));
assert(x1 != x2);
if (a == 0) {
if (b == 0) {
if (c == 0) {
return INF_NUM_OF_ROOTS;
}
else {
return 0;
}
}
else {
*x1 = -c / b;
return 1;
}
}
else {
double disc = b * b - 4 * a * c;
if (disc > 0) {
double sqrt_disc = sqrt(disc);
*x1 = (-b - sqrt_disc) / (2 * a);
*x2 = (-b + sqrt_disc) / (2 * a);
return 2;
}
else if (disc == 0) {
*x1 = -b / (2 * a);
return 1;
}
else {
return 0;
}
}
assert(false); // must return before
}
int main() {
printf("Program - Solver of a square equation\n");
printf("Sergeechev Alex aka funtalex, 2021\n");
printf("Enter a, b, c - coeffitients for equation a* x ^ 2 + b * x + c\n");
double a = 0, b = 0, c = 0;
scanf("%lf %lf %lf", &a, &b, &c);
double x1 = 0, x2 = 0;
int numRoots = solve_equation(a, b, c, &x1, &x2);
switch (numRoots) {
case 0:
printf("No roots\n");
break;
case 1:
printf("x = %lf\n", x1);
break;
case 2:
printf("x1 = %lf\nx2 = %lf\n", x1, x2);
break;
case INF_NUM_OF_ROOTS:
printf("Any number\n");
break;
default:
printf("ERROR: Wrong number of roots = %d\n", numRoots);
}
return 0;
} | true |
8b54889a658358dadcb8a9f037207c147e9d85d7 | C++ | BenoitConstantin/CoursRenduMinecraft | /Cours de rendu -Levieux/moteurcraft/Exercice 1/_minecraft/base/my_physics.h | ISO-8859-1 | 2,200 | 2.71875 | 3 | [] | no_license | #pragma once
#include "engine/utils/types_3d.h"
#include "engine/render/camera.h"
class My_Physics
{
public :
static bool SegmentPlanIntersect(NYVert3Df segPoint1, NYVert3Df segPoint2, NYVert3Df vecteurPlan, NYVert3Df pointPlan, NYVert3Df* intersectPos)
{
NYVert3Df dirSegment = segPoint2 - segPoint1;
float denom = (dirSegment.scalProd(vecteurPlan));
if (denom == 0)
return false;
float t = (pointPlan - segPoint1).scalProd(vecteurPlan) / denom;
*intersectPos = segPoint1 + dirSegment*t;
return ((((*intersectPos) - segPoint1).scalProd((*intersectPos) - segPoint2)) < 0);
}
/*static bool IntersectCube(NYVert3Df segPoint1, NYVert3Df segPoint2,NYVert3Df cubePos, NYCube* cube, NYVert3Df* intersect)
{
if (cube == NULL)
return false;
///Une face ....
NYVert3Df faceNorm = NYVert3Df(cube->CUBE_SIZE, 0 , 0).vecProd( NYVert3Df(0,0, cube->CUBE_SIZE));
if (SegmentPlanIntersect(segPoint1, segPoint2, faceNorm, cubePos, intersect))
{
if ()
return true;
}
return false;
}*/
/**
* Attention ce code n'est pas optimal, il est comprhensible. Il existe de nombreuses
* versions optimises de ce calcul. Il faut donner les points dans l'ordre (CW ou CCW)
*/
static inline bool intersecDroiteCubeFace(NYVert3Df & debSegment, NYVert3Df & finSegment,
NYVert3Df & p1, NYVert3Df & p2, NYVert3Df & p3, NYVert3Df & p4,
NYVert3Df & inter)
{
//On calcule l'intersection
bool res = SegmentPlanIntersect(debSegment, finSegment, (p1-p2).vecProd(p1-p3), p2, &inter);
if (!res)
return false;
//On fait les produits vectoriels
NYVert3Df v1 = p2 - p1;
NYVert3Df v2 = p3 - p2;
NYVert3Df v3 = p4 - p3;
NYVert3Df v4 = p1 - p4;
NYVert3Df n1 = v1.vecProd(inter - p1);
NYVert3Df n2 = v2.vecProd(inter - p2);
NYVert3Df n3 = v3.vecProd(inter - p3);
NYVert3Df n4 = v4.vecProd(inter - p4);
//on compare le signe des produits scalaires
float ps1 = n1.scalProd(n2);
float ps2 = n2.scalProd(n3);
float ps3 = n3.scalProd(n4);
if (ps1 >= 0 && ps2 >= 0 && ps3 >= 0)
return true;
return false;
}
static int nysign(float value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
}; | true |
f84b98f9b1dbcf5c855147cff68b45d54f6a230e | C++ | greschd/exercises | /hpcse/week02/diffusion/src/threaded_v2.hpp | UTF-8 | 4,472 | 2.625 | 3 | [] | no_license | // Author: Dominik Gresch <greschd@ethz.ch>
// Date: 06.10.2014 03:31:53 CEST
// File: threaded_v2.hpp
#ifndef __THREADED_V2_HEADER
#define __THREADED_V2_HEADER
#include "common.hpp"
#include "../../barrier/barrier.hpp"
#include <cmath>
#include <vector>
#include <thread>
#include <iostream>
using namespace barrier;
namespace diffusion {
namespace threaded_v2 {
// factor = tau * D / delta^2
// edge values = boundary condition (not updated)
// rho / rho_new of size (n+2)x(m+2)
void iter_thread ( density_t & rho,
density_t & rho_new,
barrier_cl & b,
res_t const & factor,
res_t const & factor2,
count_t const & num_steps,
count_t const & n,
count_t const & m,
count_t const & n_lower,
count_t const & n_upper) {
for(count_t k = 0; k < num_steps; ++k) {
// avoid the swap
if(k % 2 == 0) {
for(count_t i = n_lower; i < n_upper; ++i) {
for(count_t j = 1; j < m + 1; ++j) {
rho_new[i][j] = factor2 * rho.at(i).at(j) +
factor * rho.at(i - 1).at(j) +
factor * rho.at(i + 1).at(j) +
factor * rho.at(i).at(j - 1) +
factor * rho.at(i).at(j + 1);
}
}
}
else {
for(count_t i = n_lower; i < n_upper; ++i) {
for(count_t j = 1; j < m + 1; ++j) {
rho[i][j] = factor2 * rho_new.at(i).at(j) +
factor * rho_new.at(i - 1).at(j) +
factor * rho_new.at(i + 1).at(j) +
factor * rho_new.at(i).at(j - 1) +
factor * rho_new.at(i).at(j + 1);
}
}
}
b.wait();
}
}
void iter( density_t & rho,
res_t const & tau,
res_t const & D,
res_t const & delta,
count_t num_steps,
count_t num_threads
) {
res_t factor = tau * D / (delta * delta);
res_t factor2 = 1 - 4 * factor;
count_t n = rho.size() - 2;
count_t m = rho[0].size() - 2;
// calculate which thread will do which rows
std::vector<count_t> n_borders(num_threads + 1);
for(count_t i = 0; i < num_threads ; ++i) {
n_borders[i] = count_t(1 + i * (n / res_t(num_threads)));
}
n_borders[num_threads] = n + 1; // to avoid roundoff errors
// threads vector
std::vector<std::thread> threads(num_threads - 1);
density_t rho_new(n + 2, row_t(m + 2));
barrier_cl b(num_threads);
for(count_t j = 0; j < num_threads - 1; ++j) {
threads[j] = std::thread( iter_thread,
std::ref(rho),
std::ref(rho_new),
std::ref(b),
factor,
factor2,
num_steps,
n,
m,
n_borders[j],
n_borders[j + 1]);
}
// compute in main thread
iter_thread(rho, rho_new, b, factor, factor2, num_steps, n, m, n_borders[num_threads - 1], n_borders[num_threads]);
for(std::thread & t: threads) {
t.join();
}
}
} // namespace threaded_v2
} // namespace diffusion
#endif //__THREADED_V2_HEADER
| true |
ebce309f901361a213d3119384fd1f814aef9d0b | C++ | danielkenwahlau/CSE-471 | /Step5/Synthie/AR.cpp | UTF-8 | 845 | 2.6875 | 3 | [] | no_license | /**
* \file AR.cpp
*
* \author Daniel Ken-Wah Lau
*/
#include "stdafx.h"
#include "AR.h"
#include "ToneInstrument.h"
/**
* constructor
*/
CAR::CAR()
{
m_duration = 0.1;
m_bpm = 120;
}
/**
* destructor
*/
CAR::~CAR()
{
}
/**
* sets the source
* \param source
*/
void CAR::SetSource(CAudioNode * source)
{
m_source = source;
m_bpm = m_source->GetBpm();
}
void CAR::Start()
{
m_time = 0;
}
bool CAR::Generate()
{
m_source->Generate();
m_frame[0] = m_source->Frame(0);
m_frame[1] = m_source->Frame(1);
// We return true until the time reaches the duration.
//seconds per beat * number of beats
m_time += GetSamplePeriod();
/*double timeHeld = 1 / (m_bpm / 60)*m_duration;*/
double timeHeld = 1.0 / (m_bpm / 60.0) * m_duration;
//return m_time < beatsHeld;
//return m_time < timeHeld;
return m_time < .5;
}
| true |
3eb0afbee67b81154938a6be7ce5d9627cd876a9 | C++ | fjsxy/leetcodeKiller | /Symmetric Tree/101.cpp | UTF-8 | 1,864 | 3.34375 | 3 | [] | no_license | /**
* @date: 19-6-10
* @author: fjsxy
* @type: leetcode
*/
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <list>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {//递归比较
public:
bool isSym(TreeNode* node1,TreeNode* node2)
{
if (node1 == NULL && node2 == NULL)
return true;
if (node1 == NULL || node2 == NULL || node1->val != node2->val)
return false;
return isSym(node1->left,node2->right) && isSym(node1->right,node2->left);
}
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
return isSym(root->left,root->right);
}
};
class Solution2 {//双队列层序遍历迭代
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
bool res = true;
queue<TreeNode*> que1,que2;
que1.push(root->left);
que2.push(root->right);
bool isOver = false;
while (!que1.empty() && !que2.empty())
{
TreeNode* tmp1 = que1.front();
TreeNode* tmp2 = que2.front();
que1.pop();
que2.pop();
if (tmp1 == NULL && tmp2 == NULL)
continue;
if (tmp1 == NULL || tmp2 == NULL || tmp1->val != tmp2->val)
{
res = false;
break;
}
que1.push(tmp1->left);
que1.push(tmp1->right);
que2.push(tmp2->right);
que2.push(tmp2->left);
}
return res;
}
};
int main() {
}
| true |
60ded36e4e0efb32dea5f1c551d2ae0c2c301c78 | C++ | purebluee/Leetcode | /cpp/15-3Sum.cpp | UTF-8 | 1,249 | 3.15625 | 3 | [] | no_license | //[-1, 0, 1, 2, -1, -4]
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
if (nums.size() < 3)
return res;
int first = 0, second = 1, third = nums.size() - 1;
for (; first < nums.size() - 2; first++) {
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
second = first + 1;
third = nums.size() - 1;
while (second < third) {
if (nums[first] + nums[second] + nums[third] == 0) {
res.push_back({nums[first], nums[second], nums[third]});
while (second < third && nums[second] == nums[second+1]) {
second++;
}
while (second < third && nums[third] == nums[third-1]) {
third--;
}
second++;
third--;
} else if (nums[first] + nums[second] + nums[third] > 0) {
third--;
} else {
second++;
}
}
}
return res;
}
};
| true |
a54b125d6777670b4a09fce90e956712f5f143d7 | C++ | dailongchen/InterviewQuestions | /Interview/Interview/reversePolishNotation.hpp | UTF-8 | 1,772 | 2.953125 | 3 | [] | no_license | //
// reversePolishNotation.hpp
// Interview
//
// Created by Solon Chen on 13/03/2018.
// Copyright © 2018 Solon. All rights reserved.
//
#ifndef reversePolishNotation_hpp
#define reversePolishNotation_hpp
#include <cassert>
#include <functional>
#include <memory>
#include <stdexcept>
#include <vector>
class ReversePolishNotation {
private:
class Node {
public:
typedef std::shared_ptr<Node> ptr;
public:
Node() {
}
Node(Node::ptr left,
Node::ptr right)
: m_left(left), m_right(right) {
}
virtual ~Node() {
}
virtual int GetValue() const = 0;
protected:
Node::ptr m_left;
Node::ptr m_right;
};
class OperatorNode : public Node {
public:
typedef std::function<int(int, int)> Func;
public:
OperatorNode(Func func,
Node::ptr left,
Node::ptr right)
: m_func(func), Node(left, right) {
}
virtual int GetValue() const {
if (m_left == nullptr || m_right == nullptr)
throw std::runtime_error("");
return m_func(m_left->GetValue(), m_right->GetValue());
}
private:
Func m_func;
};
class IntegerNode: public Node {
public:
IntegerNode(int val)
: m_val(val), Node() {
}
virtual int GetValue() const {
return m_val;
}
private:
int m_val;
};
public:
static ReversePolishNotation Create(const std::vector<std::string>& tokens);
int Calculate() const;
private:
ReversePolishNotation(Node::ptr root)
: m_root(root) {
}
private:
Node::ptr m_root;
};
#endif /* reversePolishNotation_hpp */
| true |
d951d639bff7d1a91fdd041a0bfe0c295a32489c | C++ | eddiehoyle/concussion | /src/CEngine/Timer.cc | UTF-8 | 366 | 2.546875 | 3 | [] | no_license | #include "Timer.hh"
namespace concussion {
Timer::Timer() : m_elapsed( 0 ) {}
void Timer::tick( float ms ) {
m_elapsed += std::chrono::duration< float, std::ratio< 1, 1000>>( ms );
}
void Timer::reset() {
m_elapsed = Elapsed::zero();
}
TimeStamp Timer::getTimeStamp() const {
return TimeStamp( this->m_elapsed.count() );
}
} // namespace concussion | true |
0ae54f50455e58fb6056f5cbc734b47a4f0863b5 | C++ | AjaXsb/Leetcode | /Middle of Linked List.cpp | UTF-8 | 451 | 3.375 | 3 | [] | no_license | /* https://leetcode.com/problems/middle-of-the-linked-list/ */
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* p1 = head;
ListNode* p2 = head;
if (head != NULL)
{
while (p2 != NULL && p2->next != NULL)
{
p2 = p2->next->next;
p1 = p1->next;
}
return p1;
}
return 0;
}
};
| true |
600d9e6feba0ebc27adf4333551272c229243251 | C++ | bog2k3/bugs | /bugs/serialization/ChromosomeSerialization.cpp | UTF-8 | 1,323 | 2.90625 | 3 | [] | no_license | /*
* ChromosomeSerialization.cpp
*
* Created on: Mar 31, 2015
* Author: bog
*/
#include "BinaryStream.h"
#include "GeneSerialization.h"
#include "../genetics/Genome.h"
BinaryStream& operator << (BinaryStream &stream, Chromosome::insertion const& ins) {
stream << ins.age << ins.index;
return stream;
}
BinaryStream& operator >> (BinaryStream &stream, Chromosome::insertion &ins) {
stream >> ins.age >> ins.index;
return stream;
}
BinaryStream& operator << (BinaryStream &stream, Chromosome const& chromosome) {
stream << (uint32_t)chromosome.genes.size();
for (Gene const &g : chromosome.genes)
stream << g;
stream << (uint16_t)chromosome.insertions.size();
for (Chromosome::insertion const &i : chromosome.insertions)
stream << i;
return stream;
}
BinaryStream& operator >> (BinaryStream &stream, Chromosome &chromosome) {
chromosome.genes.clear();
chromosome.insertions.clear();
uint32_t nGenes;
stream >> nGenes;
chromosome.genes.reserve(nGenes);
for (unsigned i=0; i<nGenes; i++) {
Gene g;
stream >> g;
chromosome.genes.push_back(g);
}
uint16_t nInsertions;
stream >> nInsertions;
chromosome.insertions.reserve(nInsertions);
for (unsigned i=0; i<nInsertions; i++) {
Chromosome::insertion ins;
stream >> ins;
chromosome.insertions.push_back(ins);
}
return stream;
}
| true |
0a288ee27b654c6682d82c5d8d0f573380cb71f5 | C++ | stArl23/onlineJudgeExam | /牛客网上交/数字反转.cpp | UTF-8 | 459 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main(){
string a,b;
while(cin>>a>>b){
string sum=to_string(atoi(a.c_str())+atoi(b.c_str()));
reverse(sum.begin(),sum.end());
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string sum1=to_string(atoi(a.c_str())+atoi(b.c_str()));
if(sum==sum1){
reverse(sum1.begin(),sum1.end());
cout<<sum1<<endl;
}else{
cout<<"NO"<<endl;
}
}
return 0;
}
| true |
0f901703a12fdeba7a12b8ac474f7858167b434d | C++ | CloseRange/AmyWare | /AmyWare/src/AmyWare/Utility/OrthographicCameraController.h | UTF-8 | 1,331 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "AmyWare/Renderer/OrthographicCamera.h"
#include "AmyWare/Utility/Timestep.h"
#include "AmyWare/Events/ApplicationEvent.h"
#include "AmyWare/Events/MouseEvent.h"
namespace AmyWare {
struct OrthographicCameraBounds {
float Left, Right, Bottom, Top;
float GetWidth() { return Right - Left; }
float GetHeight() { return Top - Bottom; }
};
class OrthographicCameraController {
public:
OrthographicCameraController(float aspectRatio, bool rotation=false);
void OnUpdate(Timestep ts);
void OnEvent(Event& e);
void Resize(float width, float height);
OrthographicCamera& GetCamera() { return camera; }
const OrthographicCamera& GetCamera() const { return camera; }
float GetZoomLevel() { return zoomLevel; }
void SetZoomLevel(float level) { zoomLevel = level; CalculateView(); }
const OrthographicCameraBounds& GetBounds() const { return bounds; }
private:
bool OnMouseScrolled(MouseScrolledEvent& e);
bool OnWindowResized(WindowResizeEvent& e);
void CalculateView();
float aspectRatio;
float zoomLevel = 1.0f;
float zoomRate = 0.5f;
OrthographicCameraBounds bounds;
OrthographicCamera camera;
glm::vec3 camPosition = { 0.0f, 0.0f, 0.0f };
float camRotation = 0.0f;
float camMoveSpeed = 1.0f;
float camRotationSpeed = 1.0f;
bool allowRotation;
};
}
| true |
f55a6224f10946eca0981271a32b895183bfac5b | C++ | mutexbunnie/master | /entitysource.h | UTF-8 | 543 | 2.546875 | 3 | [] | no_license | #ifndef ENTITYSOURCE_H
#define ENTITYSOURCE_H
#include <QString>
#include <QAbstractItemModel>
#include <QSqlQueryModel>
class EntitySource
{
public:
EntitySource(QString _name, QString _entityType, QString _query, QString _dataSourceName);
QString getName() { return name;}
QString getEntityType() { return entityType;}
QAbstractItemModel* getModel() {return model;}
private:
QString name;
QString query;
QString dataSourceName;
QString entityType;
QAbstractItemModel* model;
};
#endif //ENTITYSOURCE_H
| true |
1ef79fb3d82b8478eeca4841172319ce80b39d60 | C++ | VipulKhandelwal1999/Coding_Blocks | /20.Challenges_Sorting_And_Searching/10.Arrays_Insertion_Sort_II.cpp | UTF-8 | 1,927 | 4.4375 | 4 | [] | no_license | /*
Given an array A of size N , write a function that implements insertion sort on the array. Print the elements of sorted array.
Input Format
First line contains a single integer N denoting the size of the array. Next line contains N space seperated integers where ith integer is the ith element of the array.
Constraints
1 <= N <= 1000
|Ai| <= 1000000
Output Format
Output N space seperated integers of the sorted array in a single line.
Sample Input
4
3 4 2 1
Sample Output
1 2 3 4
Explanation
For each test case, write insertion sort to sort the array.
Logic:-
nsertion sort is a simple sorting algorithm that builds the final sorted array one item at a time.
Algorithm:
Step 1 − First element is already sorted.
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted
Step 5 − Insert the value
Step 6 − Repeat steps 2,3,4,5 until list is sorted
*/
#include <stdio.h>
#include <math.h>
#include <iostream>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(long long int arr[], long long int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
// A utility function to print an array of size n
void printArray(long long int arr[],long long int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test insertion sort */
int main()
{
long long int n;
cin>>n;
long long int arr[n];
for (int i = 0; i < n; i++)
cin>>arr[i];
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
| true |
517f524f14222396cf3dc17270e7ef55cec64d18 | C++ | kovalexius/legacy_cpp_wrappers | /common/smart_ptr.h | UTF-8 | 2,230 | 3.125 | 3 | [] | no_license | #pragma once
template <class T> class smart_ptr
{
public:
smart_ptr(T* pValue = NULL) : m_pValue(pValue), m_pnPtrCnt(pValue ? new int : NULL) {
if (pValue) *m_pnPtrCnt = 1;
}
~smart_ptr(void) {
free();
}
smart_ptr(const smart_ptr& rRight) : m_pValue(NULL), m_pnPtrCnt(NULL) {
*this = rRight;
}
smart_ptr& operator = (const smart_ptr& rRight)
{
if (m_pValue && m_pValue != rRight.m_pValue) free();
m_pValue = rRight.m_pValue;
if (m_pnPtrCnt = rRight.m_pnPtrCnt) *m_pnPtrCnt += m_pValue ? 1 : 0;
return *this;
}
inline operator T*() {
return m_pValue;
}
operator const T*() const {
return m_pValue;
}
T* operator ->() {
return m_pValue;
}
const T* operator ->() const {
return m_pValue;
}
T* get() {
return m_pValue;
}
const T* get() const {
return m_pValue;
}
void free() {
if (m_pValue && !--*m_pnPtrCnt)
{
delete m_pValue, m_pValue = NULL;
delete m_pnPtrCnt, m_pnPtrCnt = NULL;
}
}
private:
T* m_pValue;
int* m_pnPtrCnt;
};
template <class T> class const_smart_ptr
{
public:
const_smart_ptr(T* pValue = NULL) : m_pValue(pValue), m_pnPtrCnt(pValue ? new int : NULL) {
if (pValue) *m_pnPtrCnt = 1;
}
~const_smart_ptr(void) {
free();
}
const_smart_ptr(const const_smart_ptr& rRight) : m_pValue(NULL), m_pnPtrCnt(NULL) {
*this = rRight;
}
const_smart_ptr(const smart_ptr& rRight) : m_pValue(NULL), m_pnPtrCnt(NULL) {
*this = rRight;
}
const_smart_ptr& operator = (const const_smart_ptr& rRight)
{
if (m_pValue && m_pValue != rRight.m_pValue) free();
m_pValue = rRight.m_pValue;
if (m_pnPtrCnt = rRight.m_pnPtrCnt) *m_pnPtrCnt += m_pValue ? 1 : 0;
return *this;
}
const_smart_ptr& operator = (const smart_ptr& rRight)
{
if (m_pValue && m_pValue != rRight.m_pValue) free();
m_pValue = rRight.m_pValue;
if (m_pnPtrCnt = rRight.m_pnPtrCnt) *m_pnPtrCnt += m_pValue ? 1 : 0;
return *this;
}
operator const T*() const {
return m_pValue;
}
const T* operator ->() const {
return m_pValue;
}
const T* get() const {
return m_pValue;
}
void free() {
if (m_pValue && !--*m_pnPtrCnt)
{
delete m_pValue, m_pValue = NULL;
delete m_pnPtrCnt, m_pnPtrCnt = NULL;
}
}
private:
T* m_pValue;
int* m_pnPtrCnt;
};
| true |
1cdfb669efdc86d54711c8a56c84b428ba6e6f5b | C++ | datnguyen51/DataStructure | /Library/list.h | UTF-8 | 4,543 | 3.453125 | 3 | [] | no_license | #ifndef LIST_H
#define LIST_H
#include <algorithm>
#include "book.h"
template <class T>
struct Node
{
T data;
Node<T> *next;
};
template <class T>
class List
{
private:
Node<T> *head;
Node<T> *tail;
int count;
public:
List()
{
head = 0;
tail = 0;
count = 0;
};
void Add(T value)
{
Node<T> *n= Creat_Node(value);
if(IsEmpty())
head = tail = n;
else
{
tail->next = n;
tail = n;
}
count++;
};
void PrintAll() const
{
Node<T> *p = head;
while (p != 0)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
};
Node<T> *Creat_Node(T value)
{
Node<T> *p = new Node<T>;
p->data = value;
p->next = 0;
return p;
};
int Check(T value)
{
Node<T> *p = head;
while(p!=0)
{
if(p->data==value)
{
return 1;
break;
}
return 0;
}
};
void Insert_to_head(T value)
{
Node<T> *p = Creat_Node(value);
p->next = head;
head = p;
count++;
};
void Insert_to_tail(T value)
{
Node<T> *p = Creat_Node(value);
tail->next = p;
tail = p;
count++;
};
void Insert_to_possition(int pos, T value)
{
int i=1;
Node<T> *p = Creat_Node(value);
Node<T> *q = head;
if(pos == 1)
Insert_to_head(value);
else
{
for(i=1; i<pos-1; i++)
{
// i++;
q = q->next;
}
p->next = q->next;
q->next = p;
}
count++;
};
void Change(int pos, T value)
{
if(pos == 1)
{
Node<T> *q = head;
q->data = value;
}
else
{
Node<T> *p = head;
for(int i=1; i<pos-1; i++)
p = p->next;
p->next->data = value;
}
};
void Delete_Data_in_Pos(int pos)
{
if(pos == 1)
{
Node<T> *q = head;
head = head -> next;
delete q;
}
else
{
Node<T> *p = head;
for(int i=1; i<pos-1; i++)
p = p->next;
Node<T> *q = p->next;
p->next = p->next->next;
delete q;
}
count--;
};
int Count() const
{
return count;
};
void Count(T value)
{
int count = 0;
Node<T> *p = head;
while (p != 0)
{
// cout<<p->data<<" ";
if(p->data == value)
count++;
p = p->next;
}
cout<<"So phan tu "<<value<<" xuat hien: "<<count<<endl;
};
void Delete_Data(T value)
{
Node<T> *p = head;
int pos = 1;
while(!IsEmpty())
{
if(p->data == value)
{
Delete_Data_in_Pos(pos);
break;
}
p = p->next;
pos++;
}
};
void Delete_Tail()
{
Node<T> *p = head;
for(int i=1; i<count-1; i++)
p=p->next;
Node<T> *q = p->next;
p->next = p->next->next;
delete q;
count--;
};
void Swap(int pos1, int pos2)
{
Node<T> *p = head;
Node<T> *q = head;
T swap1, swap2;
for(int i=1; i<=count; i++)
{
if(i == pos1)
swap1 = p->data;
if(i == pos2)
swap2 = p->data;
p = p->next;
}
for(int i=1; i<=count; i++)
{
if(i == pos1)
q->data = swap2;
if(i == pos2)
q->data = swap1;
q = q->next;
}
cout<<swap1<<" "<<swap2<<endl;
};
void Reverse()
{
Node<T> *p = head;
Node<T> *cur = 0;
Node<T> *pre = 0;
while(p!=0)
{
cur = p;
p = p->next;
cur->next = pre;
pre = cur;
}
head = cur;
};
T Get_Item(int pos)
{
T x;
if(pos == 1)
{
x = head->data;
}
else
{
if(pos == count)
{
x = tail->data;
}
else
{
Node<T> *p = head;
for(int i=1; i<pos-1; i++)
p=p->next;
x = p->next->data;
}
}
return x;
};
T Find_pos_of_Item(T value)
{
int pos=1;
Node<T> *p = head;
while(!IsEmpty())
{
if(p->data == value)
{
return pos;
break;
}
p = p->next;
pos++;
}
};
int IsEmpty()
{
return head == 0;
};
T Max()
{
Node<T> *p = head;
T max = head->data;
for(int i=1; i<=count; i++)
{
if(p->data > max)
max = p->data;
p = p->next;
}
return max;
};
T Min()
{
Node<T> *p = head;
T min = head->data;
for(int i=1; i<=count; i++)
{
if(p->data < min)
min = p->data;
p = p->next;
}
return min;
};
// void Array_Reverse()
// {
// int i=1;
// Node<T> *p = head;
// while(p!=0)
// {
// a[i] = p->data;
// p = p->next;
// i++;
// }
// reverse(a, a+count+2);
// };
// void Array_Sort()
// {
// int i=1;
// Node<T> *p = head;
// while(p!=0)
// {
// a[i] = p->data;
// p = p->next;
// i++;
// }
// sort(a, a+count+1);
// };
// void Sort_Min_to_Max()
// {
// Array_Sort();
// for(int i=1; i<=count; i++)
// {
// T x = a[i];
// Change(i,x);
// }
// };
// void Sort_Max_to_Min()
// {
// Array_Sort();
// reverse(a, a+count+2);
// for(int i=1; i<=count; i++)
// {
// T x = a[i];
// Change(i,x);
// }
// };
};
#endif | true |
d5b106bb24de3a2a38ef0f6bfa13ab7e831bc3fb | C++ | vivekmyers/Math-Seminar-Project | /gpu/newton_gpu.cpp | UTF-8 | 8,656 | 2.640625 | 3 | [] | no_license | #define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cstdio>
#include <fstream>
const int WINDOW_WIDTH = 900;
const int WINDOW_HEIGHT = 900;
const char *WINDOW_TITLE = "Newton GPU";
void glfw_debug_callback(int error, const char *description)
{
printf("[GLFW] %d: %s\n", error, description);
}
void gl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *user_param)
{
const char *msg_type;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
msg_type = "Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
msg_type = "Deprecated";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
msg_type = "Undefined";
break;
case GL_DEBUG_TYPE_PORTABILITY:
msg_type = "Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
msg_type = "Performance";
break;
default:
msg_type = "Other";
break;
}
printf("[GL/%s] %s\n", msg_type, message);
}
bool draw = true;
const int MAX_ROOTS = 10;
GLfloat roots[2*MAX_ROOTS];
int num_roots;
GLfloat real_min, real_max, imag_min, imag_max;
void mouse_button_callback(GLFWwindow *window, int button, int action, int mod)
{
if (action == GLFW_PRESS) {
if (button == GLFW_MOUSE_BUTTON_LEFT && num_roots < MAX_ROOTS) {
double x, y;
glfwGetCursorPos(window, &x, &y);
GLfloat tw = real_max - real_min;
GLfloat th = imag_max - imag_min;
roots[2*num_roots] = (GLfloat) (x / WINDOW_WIDTH) * tw + real_min;
roots[2*num_roots+1] = imag_max - (GLfloat) (y / WINDOW_HEIGHT) * th;
printf("%d : %f + %fi\n",num_roots,roots[2*num_roots],roots[2*num_roots+1]);
++num_roots;
draw = true;
} else if (button == GLFW_MOUSE_BUTTON_RIGHT) {
--num_roots;
draw = true;
}
}
}
GLuint load_shader_from_file(const char *path, GLenum shader_type)
{
char *buffer;
std::ifstream file;
std::streampos size;
file.open(path, std::ios::binary | std::ios::ate);
if (file.is_open()) {
size = file.tellg();
buffer = new char[(size_t) size + 1];
file.seekg(0, std::ios::beg);
file.read(buffer, size);
file.close();
buffer[size] = 0;
} else {
printf("Unable to open shader file: %s\n", path);
return 0;
}
GLuint shader_id = glCreateShader(shader_type);
glShaderSource(shader_id, 1, &buffer, NULL);
glCompileShader(shader_id);
GLint shader_compiled = GL_FALSE;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &shader_compiled);
if (shader_compiled != GL_TRUE) {
printf("Failed to compile shader:\n%s\n", buffer);
GLint log_length, max_length;
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &max_length);
char *log = new char[max_length];
glGetShaderInfoLog(shader_id, max_length, &log_length, log);
if (log_length > 0) {
printf("%s\n", log);
}
delete[] log;
glDeleteShader(shader_id);
return 0;
}
delete[] buffer;
return shader_id;
}
int main()
{
int algorithm, samples, iterations;
GLfloat tolerance;
printf("[Normal]\n 1 | Newton\n 2 | Halley\n 3 | Laguerre\n");
printf(" 4 | Newton Approx\n 5 | Halley Approx\n");
printf("[Special]\n 0 | Nearest\n-1 | Laguerre Positive\n-2 | Laguerre Negative\n");
printf("algorithm: ");
scanf("%d", &algorithm);
int preset;
printf("preset: ");
scanf("%d", &preset);
if (preset == 1) {
num_roots = 0;
real_min = -1.f;
real_max = 1.f;
imag_min = -1.f;
imag_max = 1.f;
tolerance = 1e-8;
iterations = 100;
}
else if (preset == 2) {
num_roots = 0;
real_min = -1.f;
real_max = 1.f;
imag_min = -1.f;
imag_max = 1.f;
tolerance = 1e-2;
iterations = 30;
}
else {
printf("number of roots (max 10): ");
scanf("%d", &num_roots);
for (int i = 0; i < num_roots; ++i) {
printf("root %d: ", i + 1);
scanf("%f %f", roots + 2*i, roots + 2*i + 1);
}
printf("real range: ");
scanf("%f %f", &real_min, &real_max);
printf("imaginary range: ");
scanf("%f %f", &imag_min, &imag_max);
printf("tolerance: ");
scanf("%f", &tolerance);
printf("max iterations: ");
scanf("%d", &iterations);
}
printf("supersampling: ");
scanf("%d", &samples);
if (!glfwInit()) {
printf("GLFW initialization failed\n");
}
glfwSetErrorCallback(glfw_debug_callback);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow *window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, nullptr, nullptr);
if (!window) {
printf("Failed to create window\n");
}
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwMakeContextCurrent(window);
GLenum glew_error = glewInit();
if (glew_error != GLEW_OK) {
printf("GLEW initialization failed: %s\n", glewGetErrorString(glew_error));
}
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback((GLDEBUGPROC) gl_debug_callback, 0);
GLubyte palette_data[10*3] = {
0xff, 0x00, 0x00,
0x00, 0xff, 0x00,
0x00, 0x00, 0xff,
0xff, 0xff, 0x00,
0x00, 0xff, 0xff,
0xff, 0x00, 0xff,
0xff, 0x80, 0x00,
0x00, 0xff, 0x80,
0x80, 0x00, 0xff,
0xbb, 0xbb, 0xbb,
};
unsigned char palette_size = 10;
GLuint palette_texture;
glGenTextures(1, &palette_texture);
glBindTexture(GL_TEXTURE_1D, palette_texture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexStorage1D(GL_TEXTURE_1D, 1, GL_RGB8, 256);
glTexSubImage1D(GL_TEXTURE_1D, 0, 0, palette_size, GL_RGB, GL_UNSIGNED_BYTE, &palette_data);
GLuint vertex_shader, fragment_shader;
vertex_shader = load_shader_from_file("vertex.glsl", GL_VERTEX_SHADER);
switch (algorithm) {
case 1:
fragment_shader = load_shader_from_file("fragment_newton.glsl", GL_FRAGMENT_SHADER);
break;
case 2:
fragment_shader = load_shader_from_file("fragment_halley.glsl", GL_FRAGMENT_SHADER);
break;
case 3:
fragment_shader = load_shader_from_file("fragment_laguerre.glsl", GL_FRAGMENT_SHADER);
break;
case 4:
fragment_shader = load_shader_from_file("fragment_approx.glsl", GL_FRAGMENT_SHADER);
break;
case 5:
fragment_shader = load_shader_from_file("fragment_halley_approx.glsl", GL_FRAGMENT_SHADER);
break;
case -1:
fragment_shader = load_shader_from_file("fragment_laguerre_p.glsl", GL_FRAGMENT_SHADER);
break;
case -2:
fragment_shader = load_shader_from_file("fragment_laguerre_n.glsl", GL_FRAGMENT_SHADER);
break;
case 0:
fragment_shader = load_shader_from_file("fragment_test.glsl", GL_FRAGMENT_SHADER);
}
if (vertex_shader & fragment_shader == 0) {
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
printf("Failed to create shaders\n");
return 1;
}
GLuint program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
GLint link_status = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &link_status);
if (link_status != GL_TRUE) {
printf("Failed to link program\n");
GLint log_length, max_length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &max_length);
char *log = new char[max_length];
glGetProgramInfoLog(program, max_length, &log_length, log);
if (log_length > 0) {
printf("%s\n", log);
}
delete[] log;
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glDeleteProgram(program);
return 1;
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glUseProgram(program);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glUniform2f(0, real_min, imag_min);//bottom_right
glUniform2f(1, real_max - real_min, imag_max - imag_min);//view_size
glUniform1i(2, iterations);//iterations
glUniform1f(3, tolerance);//tolerance
glUniform1i(5, 0);//root_colors
glUniform1f(6, 1.f/samples/samples);//color_scaling
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
while (!glfwWindowShouldClose(window)) {
if (draw) {
printf("drawing\n");
draw = false;
glClear(GL_COLOR_BUFFER_BIT);
glUniform1i(4, num_roots);//root_count
glUniform2fv(8, num_roots, roots);//roots
for (int x = 0; x < samples; ++x) {
for (int y = 0; y < samples; ++y) {
glUniform2f(7, 2.f*x/WINDOW_WIDTH/samples - 1.f/WINDOW_WIDTH,
2.f*y/WINDOW_HEIGHT/samples - 1.f/WINDOW_HEIGHT);//offset
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
}
glfwSwapBuffers(window);
}
glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
| true |
1a54313f3574593e1ea6a5756e6bf129689daabb | C++ | Nhrkr/Language-Processors-Algos | /que2.cpp | UTF-8 | 1,509 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
fin.open("i1.txt");
fout.open("generated1.c");
char lhs,t;
int i;
fin>>t;
fin.close();
fin.open("i1.txt");
string rhs,text,text1,text2,line,term;
fout<<"#include<stdio.h>\nint i=0,ans;\nchar a[100];\n";
while(getline(fin,line))
{
//clearing error flags
rhs.clear();
text1.clear();
text.clear();
term.clear();
lhs=line[0];
rhs=line.substr(2,line.length()-1);
i=0;
while(rhs[i]!='\0')
{
text.append("if( ");
while(rhs[i]!='|' && rhs[i]!='\0')
{
//non terminal--call that function
if(isupper(rhs[i]))
{
text.append(string(1,rhs[i]) +"() && ");
}
//terminal--append
else if(islower(rhs[i]))
{
term = term + string(1,rhs[i]);
text.append("(a[i++]=='" + string(1,rhs[i]) + "') && ");
}
i++;
}
text.append("1)\nreturn 1;\ni=k;\n");
if(rhs[i]=='|')
i++;
}
if(rhs.find("~")!=string::npos)
{
text1="if(a[i]!='" + string(1,term[0]) + "'){ return 1; } else { " + text + "return 0;\n }";
fout<<line[0]<<"()\n{\nint k=i;\n"+ text1 +" \n}\n";
}
else
{
fout<<line[0]<<"(){ \nint k=i;\n "<< text <<" return 0;\n}\n";
}
}
fin.close();
fout<<"\nmain()\n{\ngets(a);\nans = "<<string(1,t)<<"();\nif(ans)\nprintf("<<"\"Success\""<<");\nelse\nprintf("<<"\"Failed\""<<");\n}";
fout.close();
}
| true |
287dcb58a1fafc5344c79b27e2c1d52ad61d5a8c | C++ | iuyoy/basicCSKnowledge | /leetcode/882. Reachable Nodes In Subdivided Graph/RNiSG.cpp | UTF-8 | 2,880 | 3.484375 | 3 | [] | no_license | /*
Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivisions are made to some of the edges.
The graph is given as follows: edges[k] is a list of integer pairs (i, j, n) such that (i, j) is an edge of the original graph,
and n is the total number of new nodes on that edge.
Then, the edge (i, j) is deleted from the original graph, n new nodes (x_1, x_2, ..., x_n) are added to the original graph,
and n+1 new edges (i, x_1), (x_1, x_2), (x_2, x_3), ..., (x_{n-1}, x_n), (x_n, j) are added to the original graph.
Now, you start at node 0 from the original graph, and in each move, you travel along one edge.
Return how many nodes you can reach in at most M moves.
Example 1:
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3
Output: 13
Explanation:
The nodes that are reachable in the final graph after M = 6 moves are indicated below.
Example 2:
Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4
Output: 23
Note:
0 <= edges.length <= 10000
0 <= edges[i][0] < edges[i][1] < N
There does not exist any i != j for which edges[i][0] == edges[j][0] and edges[i][1] == edges[j][1].
The original graph has no parallel edges.
0 <= edges[i][2] <= 10000
0 <= M <= 10^9
1 <= N <= 3000
A reachable node is a node that can be travelled to using at most M moves starting from node 0.
*/
// Dijkstra likely, use moves as comparison, not distance.
class Solution {
public:
int reachableNodes(vector<vector<int>>& edges, int M, int N) {
unordered_map<int, unordered_map<int, int>> graph;
for(vector<int> edge:edges){
graph[edge[0]][edge[1]] = edge[2];
graph[edge[1]][edge[0]] = edge[2];
}
vector<int> moves(N, -1);
vector<int> visited(N, 0);
moves[0] = M;
priority_queue<pair<int, int>> pq;
pq.push({M, 0});
int ret = 0;
while(pq.size()){
int i = pq.top().second;
pq.pop();
if(!visited[i]){
for(auto b:graph[i]){
int j = b.first, dis = b.second;
if(visited[j]){
if(moves[j] <= dis)
ret += min(dis-moves[j], moves[i]);
}else{
ret += min(moves[i], dis);
if(moves[i] - dis - 1 > moves[j]){
moves[j] = moves[i] - dis - 1;
pq.push({moves[j], j});
}
}
}
++ret;
visited[i] = 1;
}
}
return ret;
}
};
/*
[[0,1,10],[0,2,1],[1,2,2]]
6
3
[[0,1,10],[0,2,1],[1,2,2]]
8
3
[[0,1,10],[0,2,1],[1,2,2]]
11
3
[[0,1,4],[1,2,6],[0,2,8],[1,3,1]]
10
4
[[0,3,8],[0,1,4],[2,4,3],[1,2,0],[1,3,9],[0,4,7],[3,4,9],[1,4,4],[0,2,7],[2,3,1]]
8
5
*/ | true |
403d49f8266aa7b314459bdccffc9a66ee54689a | C++ | rutuja-patil923/Data-Structures-and-Algorithms | /BST/populateSuccessor.cpp | UTF-8 | 177 | 2.609375 | 3 | [] | no_license | node *pre=NULL;
void populateNext(struct node* root)
{
if(root==NULL)
return;
populateNext(root->left);
if(pre)
pre->next=root;
pre=root;
populateNext(root->right);
} | true |
4e3b2179fffa23f5d441c074b01c85a736be6d6c | C++ | Kpure1000/3DViewer | /3DViewer/graph/Sprite.h | UTF-8 | 4,979 | 2.546875 | 3 | [] | no_license | #ifndef SPRITE_H
#define SPRITE_H
#include"RenderStates.h"
#include"RenderTarget.h"
#include"Drawable.h"
namespace rtx
{
namespace graph
{
class Sprite : public Drawable
{
public:
Sprite() :VAO(0), VBO(0), EBO(0)
{
Vertex a;
a.position = glm::vec3(0.0f, 0.0f, 0.0f);
a.normal = glm::vec3(0.0f, 0.0f, 1.0f);
a.texCoords = glm::vec2(0.0f, 0.0f);
Vertex b;
b.position = glm::vec3(0.0f, 1.0f, 0.0f);
b.normal = glm::vec3(0.0f, 0.0f, 1.0f);
b.texCoords = glm::vec2(0.0f, 1.0f);
Vertex c;
c.position = glm::vec3(1.0f, 1.0f, 0.0f);
c.normal = glm::vec3(0.0f, 0.0f, 1.0f);
c.texCoords = glm::vec2(1.0f, 1.0f);
Vertex d;
d.position = glm::vec3(1.0f, 0.0f, 0.0f);
d.normal = glm::vec3(0.0f, 0.0f, 1.0f);
d.texCoords = glm::vec2(1.0f, 0.0f);
vertices.push_back(a);
vertices.push_back(b);
vertices.push_back(c);
vertices.push_back(d);
int indi[] = {
0,1,2,
2,3,0
};
indices.reserve(6);
indices.assign(indi, indi + 6);
SpriteInit();
}
Sprite(const std::string& filePath) :VAO(0), VBO(0), EBO(0)
{
m_texture.LoadFromFile(filePath);
Vertex a;
a.position = glm::vec3(0.0f, 0.0f, 0.0f);
a.normal = glm::vec3(0.0f, 0.0f, 1.0f);
a.texCoords = glm::vec2(0.0f, 0.0f);
Vertex b;
b.position = glm::vec3(0.0f, 1.0f, 0.0f);
b.normal = glm::vec3(0.0f, 0.0f, 1.0f);
b.texCoords = glm::vec2(0.0f, 1.0f);
Vertex c;
c.position = glm::vec3(1.0f, 1.0f, 0.0f);
c.normal = glm::vec3(0.0f, 0.0f, 1.0f);
c.texCoords = glm::vec2(1.0f, 1.0f);
Vertex d;
d.position = glm::vec3(1.0f, 0.0f, 0.0f);
d.normal = glm::vec3(0.0f, 0.0f, 1.0f);
d.texCoords = glm::vec2(1.0f, 0.0f);
vertices.push_back(a);
vertices.push_back(b);
vertices.push_back(c);
vertices.push_back(d);
int indi[] = {
0,1,2,
2,3,0
};
indices.reserve(6);
indices.assign(indi, indi + 6);
SpriteInit();
}
void SetTexture(const std::string filePath)
{
m_texture.LoadFromFile(filePath);
}
void SetTexture(const Texture& texture)
{
m_texture = texture;
}
private:
void SpriteInit()
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glEnableVertexAttribArray(0);
// normal
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal));
glEnableVertexAttribArray(1);
// texcoords
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texCoords));
glEnableVertexAttribArray(2);
// vertex tangent
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, tangent));
// vertex bitangent
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, bitangent));
glBindVertexArray(0);
}
virtual void Draw(const RenderTarget& target, RenderStates&& states)const
{
if (nullptr == states.GetShader())
{
target.Draw(indices, VAO);
}
// TODO: if shader not null
}
/**************************************************/
friend class RenderTarget;
unsigned int VAO, VBO, EBO;
vector<Vertex> vertices;
vector<unsigned int> indices;
Texture m_texture;
};
}
}
#endif // !SPRITE_H
| true |
9087c21b2ff180747aaca3d3b4aa88afc883a965 | C++ | VARTIOMIES/ohjelmointi-2-cplusplus | /student/06/network/main.cpp | UTF-8 | 4,698 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
const std::string HELP_TEXT = "S = store id1 i2\nP = print id\n"
"C = count id\nD = depth id\n";
std::vector<std::string> split(const std::string& s, const char delimiter, bool ignore_empty = false){
std::vector<std::string> result;
std::string tmp = s;
while(tmp.find(delimiter) != std::string::npos)
{
std::string new_part = tmp.substr(0, tmp.find(delimiter));
tmp = tmp.substr(tmp.find(delimiter)+1, tmp.size());
if(not (ignore_empty and new_part.empty()))
{
result.push_back(new_part);
}
}
if(not (ignore_empty and tmp.empty()))
{
result.push_back(tmp);
}
return result;
}
void print_web(const std::string& id,
const std::map<std::string,std::vector<std::string>>& data,
int depth)
{
if (data.find(id)!=data.end())
{
for (std::string connection : data.at(id))
{
std::string dots;
for (int i=0;i<depth;i++)
{
dots += "..";
}
std::cout<<dots;
std::cout << connection << std::endl;
if (data.find(connection)!=data.end())
{
print_web(connection,data,depth+1);
}
}
}
}
int count_web(const std::string& id,
const std::map<std::string,std::vector<std::string>>& data)
{
int amount=0;
if (data.find(id)==data.end())
{
return 0;
}
for (std::string connection : data.at(id))
{
if (data.find(connection)!=data.end())
{
amount += count_web(connection,data);
}
amount++;
//amount+=data.at(id).size();
}
return amount;
}
int max_depth(const std::string& id,
const std::map<std::string,std::vector<std::string>>& data,
int depth,
int max_of_all)
{
int new_max=1; //Määrittele
if (data.find(id)!=data.end())
{
for (std::string connection : data.at(id))
{
if (data.find(connection)!=data.end())
{
new_max = max_depth(connection,data,depth+1,depth+1);
}
if (new_max >= max_of_all)
{
max_of_all = new_max;
}
}
}
return max_of_all;
}
int main()
{
// TODO: Implement the datastructure here
std::map<std::string,std::vector<std::string>> data;
while(true){
std::string line;
std::cout << "> ";
getline(std::cin, line);
std::vector<std::string> parts = split(line, ' ', true);
std::string command = parts.at(0);
if(command == "S" or command == "s"){
if(parts.size() != 3){
std::cout << "Erroneous parameters!" << std::endl << HELP_TEXT;
continue;
}
std::string id1 = parts.at(1);
std::string id2 = parts.at(2);
// Lisätään tieto rakenteeseen
if (data.find(id1) == data.end())
{
data.insert({id1,{id2}});
}
else
{
data.at(id1).push_back(id2);
}
// TODO: Implement the command here!
} else if(command == "P" or command == "p"){
if(parts.size() != 2){
std::cout << "Erroneous parameters!" << std::endl << HELP_TEXT;
continue;
}
std::string id = parts.at(1);
std::cout<<id<<std::endl;
int depth = 1;
print_web(id,data,depth);
// TODO: Implement the command here!
} else if(command == "C" or command == "c"){
if(parts.size() != 2){
std::cout << "Erroneous parameters!" << std::endl << HELP_TEXT;
continue;
}
std::string id = parts.at(1);
std::cout<<count_web(id,data)<<std::endl;
// TODO: Implement the command here!
} else if(command == "D" or command == "d"){
if(parts.size() != 2){
std::cout << "Erroneous parameters!" << std::endl << HELP_TEXT;
continue;
}
std::string id = parts.at(1);
std::cout << max_depth(id,data,1,0)+1<<std::endl;
// TODO: Implement the command here!
} else if(command == "Q" or command == "q"){
return EXIT_SUCCESS;
} else {
std::cout << "Erroneous command!" << std::endl << HELP_TEXT;
}
}
}
| true |
6bcd87cc20c89b19ccf7332fd72123b4028cf31f | C++ | tmuttaqueen/MyCodes | /Online Judge Code/[Other] Online-Judge-Solutions-master_from github/Project Euler/346.cpp | UTF-8 | 555 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <set>
using namespace std;
int main(){
const long long MAX_VAL = 1000000000000LL;
set<long long> S;
S.insert(1);
for(long long b = 2;;++b){
long long aux = b*b + b + 1;
if(aux >= MAX_VAL) break;
while(aux < MAX_VAL){
S.insert(aux);
aux = aux * b + 1;
}
}
long long ans = 0;
for(set<long long> :: iterator it = S.begin();it != S.end();++it)
ans += *it;
cout << ans << '\n';
return 0;
}
| true |
baff7ebc1bfad6bae3e7dbf2cd58e3f2b31557fb | C++ | 1091390146/algorithm | /查找/binSearch.cpp | UTF-8 | 2,326 | 3.96875 | 4 | [] | no_license | # include<iostream>
using namespace std;
int binary_search(int arr[],int low , int high, int key)
{
// 通过递归二分查找 查找元素
if(low<=high){
int mid = (high+low) >> 1;
//若元素在中间
if(arr[mid] == key)
return mid;
// 若元素比中间的数小 那么它只可能在左边的子数组中 则可另high = mid -1
else if (arr[mid] > key)
return binary_search(arr,low,mid-1,key);
//否则 只可能在右边的子数组汇总 则可令low = mid+1
return binary_search(arr,mid+1,high,key);
}
// 该元素不在数组中
return -1;
}
/*
int binary_search(int arr[], int low, int high, int key)
{
//查找某元素是否存在于数组中 若存在,则返回下标;否则返回-1
while (low <= high) {
// 检查key是否在中间
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
// 如果x大于arr[mid] 则low = mid+1;否则high=mid-1
if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
*/
int main()
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
//使用sizeof(a)/sizeof(a[0])计算数组的长度;
//int length = sizeof(a)/sizeof(a[0]);
// 说明:sizeof()函数可以返回数组所占的内存,而sizeof(a[0])返回的是数组第一个元素所占的内存。
int n = sizeof(arr) / sizeof(arr[0]);
cout << n <<endl;
int result = binary_search(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
getchar();
return 0;
}
template <typename T> static int binSearch(T* A, T const & e, int lo, int hi){
while(1 < hi - lo){//有效查找区间的宽度缩短至1时,算法才终止
auto mi = (lo + hi) >> 1;// 以中点为轴点,经比较后确认深入
(e < mi) ? hi = mi : lo = mi; //[lo, mi)或[mi, hi)
}//出口时hi = lo + 1, 查找区间仅含一个元素A[lo]
return (e == A[lo]) ? lo : -1; //返回命中元素的秩或者-1
}
template <typename T> static int binSearch(T* A, T const & e, int lo, int hi){
while(lo < hi){
auto mi = (lo + hi) >> 1;
(e < A[mi]) ? hi = mi : lo = mi + 1; //[lo, mi)或(mi, hi)
}//出口时,A[lo = hi]为大于e的最小元素
return --lo;//故lo - 1即不大于e的元素的最大秩
} | true |
b15a316bb30d5d249b3eddcae3f13f09d65dd989 | C++ | tmolcard/PluriNotes | /relations.cpp | UTF-8 | 10,843 | 2.75 | 3 | [] | no_license | #include "relations.h"
#include "Notes.h"
#include <QDebug>
RelationManager* RelationManager::instance = nullptr;
RelationManager::RelationManager(): tabRelations(nullptr), nbRelations(0), nbMaxRelations(0){}
RelationManager::~RelationManager(){
for(unsigned int i=0; i<nbRelations; i++) delete tabRelations[i];
delete[] tabRelations;
}
void RelationManager::addRelation(Relation* rel){
if(rel->getTitre() == "Reference") throw("erreur, on ne peut ajouter une relation Reference. ");
for(unsigned int i=0; i <nbRelations; i++){
if(tabRelations[i]->getTitre() == rel->getTitre())
throw NotesException("erreur, relation existe déjà");
}
if(nbRelations == nbMaxRelations){
Relation** newRelations = new Relation*[nbMaxRelations+5];
for(unsigned int i=0; i<nbRelations; i++)
newRelations[i] = tabRelations[i];
Relation** oldRelations = tabRelations;
tabRelations = newRelations;
nbMaxRelations+=5;
if(oldRelations) delete[] oldRelations;
}
tabRelations[nbRelations++] = rel;
}
Relation& RelationManager::getRelation(QString _titre){
for(unsigned int i=0; i<nbRelations; i++){
if (tabRelations[i]->getTitre()==_titre) return *tabRelations[i];
}
throw NotesException(QString("Erreur, la relation n'existe pas."));
}
bool RelationManager::existeRelation(QString _titre){
for(unsigned int i=0; i<nbRelations; i++){
if (tabRelations[i]->getTitre()==_titre) return true;
}
return false;
}
void RelationManager::deleteRelation(QString _titre){
if(_titre == "Reference") throw("erreur, on ne peut supprimer la relation Reference.");
unsigned int i;
for(i=0; i<nbRelations && tabRelations[i]->getTitre() != _titre; i++){}
if(nbRelations != 0 && i <nbRelations)
{
if(tabRelations[i]->getTitre() == _titre)
{
delete tabRelations[i];
tabRelations[i] = tabRelations[--nbRelations];
}
}
}
void RelationManager::saveEveryRelationsXML(QXmlStreamWriter *stream){
stream->writeStartElement("Relations");
for(unsigned int i=0; i<nbRelations; i++){
this->tabRelations[i]->saveXML(stream);
}
stream->writeEndElement();
}
void RelationManager::createReference(){
for(unsigned int i=0; i <nbRelations; i++){
if(tabRelations[i]->getTitre() == "Reference")
throw NotesException("erreur, Reference existe déjà");
}
if(nbRelations == nbMaxRelations){
Relation** newRelations = new Relation*[nbMaxRelations+5];
for(unsigned int i=0; i<nbRelations; i++)
newRelations[i] = tabRelations[i];
Relation** oldRelations = tabRelations;
tabRelations = newRelations;
nbMaxRelations+=5;
if(oldRelations) delete[] oldRelations;
}
Relation* rel = new Relation("Reference", "relations fortes");
tabRelations[nbRelations++] = rel;
}
bool RelationManager::updateReference(const QString &idNote, const QString &texte){
NotesManager& NM = NotesManager::donneInstance();
if(NM.existeNote(idNote))
{
bool suite = true;
QRegExp regex("\\\\ref[{]([\\w]+)[}]");
QStringList list;
int pos = 0;
while( (pos = regex.indexIn(texte, pos)) != -1){
if(NM.existeNote(regex.cap(1)) && regex.cap(1) != idNote)
{
list << regex.cap(1);
}
else
{
suite = false;
}
pos += regex.matchedLength();
}
if(suite)
{
Relation& reference = getRelation("Reference");
Relation::Iterator it2 = reference.getIterator();
while (!it2.isdone()) {
if((*it2)->getx() == idNote)
{
reference.deleteCouple((*it2)->getx(), (*it2)->gety());
}
it2++;
}
QStringList::iterator it = list.begin();
while (it != list.end()) {
reference.addCouple(idNote, (*it));
++it;
}
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Relation::~Relation(){
for(unsigned int i=0; i<nbCouples; i++) delete tabCouples[i];
delete[] tabCouples;
}
void Relation::addCouple(QString _x, QString _y, QString _label){
bool stop = false;
for(unsigned int i=0; i <nbCouples; i++){
if(tabCouples[i]->getx() == _x && tabCouples[i]->gety() == _y)
throw NotesException("erreur, couple existe déjà");
if(tabCouples[i]->getx() == _y && tabCouples[i]->gety() == _x)
stop = true;
}
NotesManager& notes = NotesManager::donneInstance();
if(!notes.existeNote(_x) || !notes.existeNote(_y)){
throw NotesException("erreur, un des id n'existe pas");
}
if(nbCouples == nbMaxCouples){
Couple** newCouples = new Couple*[nbMaxCouples+5];
for(unsigned int i=0; i<nbCouples; i++)
newCouples[i] = tabCouples[i];
Couple** oldCouples = tabCouples;
tabCouples = newCouples;
nbMaxCouples+=5;
if(oldCouples) delete[] oldCouples;
}
Couple* couple = new Couple(_x,_y,_label);
tabCouples[nbCouples++] = couple;
if(!orientee && !stop){
addCouple(_y,_x, _label);
}
}
void Relation::deleteCouple(QString _x, QString _y){
unsigned int i;
for(i=0; i<nbCouples && ((tabCouples[i]->getx() != _x) || (tabCouples[i]->gety() != _y)); i++){}
if(nbCouples != 0 && i < nbCouples)
{
if(tabCouples[i]->getx() == _x && tabCouples[i]->gety() == _y)
{
delete tabCouples[i];
tabCouples[i] = tabCouples[--nbCouples];
if(!orientee)
{
deleteCouple(_y,_x);
}
}
}
}
Couple& Relation::getCouple(QString _x, QString _y){
for(unsigned int i=0; i<nbCouples; i++){
if (tabCouples[i]->getx()==_x && tabCouples[i]->gety() == _y) return *tabCouples[i];
}
throw NotesException(QString("Erreur, le couple n'existe pas."));
}
bool Relation::existeCouple(QString _x, QString _y){
for(unsigned int i=0; i <nbCouples; i++){
if(tabCouples[i]->getx() == _x && tabCouples[i]->gety() == _y) return true;
}
return false;
}
void Relation::saveXML(QXmlStreamWriter *stream){
stream->writeStartElement("relation");
stream->writeTextElement("titre", this->getTitre());
stream->writeTextElement("description", this->getDescription());
stream->writeTextElement("orientee", QString::number(this->orientee));
stream->writeStartElement("Couples");
if(!orientee)
{
bool existe = false;
QVector<QString> listeX;
QVector<QString> listeY;
for(unsigned int i = 0; i<nbCouples; i++)
{
existe = false;
for (int j = 0; j < listeX.size(); j++) {
if(tabCouples[i]->getx() == listeY.at(j) && tabCouples[i]->gety() == listeX.at(j))
{
existe = true;
}
}
if(!existe)
{
this->tabCouples[i]->saveXML(stream);
listeX << tabCouples[i]->getx();
listeY << tabCouples[i]->gety();
}
}
}
else
{
for(unsigned int i=0; i<nbCouples; i++)
{
this->tabCouples[i]->saveXML(stream);
}
}
stream->writeEndElement();
stream->writeEndElement();
}
void Couple::saveXML(QXmlStreamWriter *stream){
stream->writeStartElement("couple");
stream->writeTextElement("x", this->getx());
stream->writeTextElement("y", this->gety());
stream->writeTextElement("label", this->getLabel());
(*stream).writeEndElement();
}
void RelationManager::LoadRelationXML(QXmlStreamReader *stream){
unsigned int j = nbRelations;
QString titre;
QString description;
bool orientee;
QString x;
QString y;
QString label;
//QXmlStreamAttributes attributes = stream.attributes();
stream->readNext();
while(!(stream->tokenType() == QXmlStreamReader::EndElement && ( stream->name() == "relation" || stream->name() == "Relations" || stream->name() == "PluriNotes" && stream->name() != "Couples"))){
if(stream->tokenType() == QXmlStreamReader::StartElement) {
if(stream->name() == "titre"){
stream->readNext();
titre=stream->text().toString();
}
if(stream->name() == "description"){
stream->readNext();
description=stream->text().toString();
}
if(stream->name() == "orientee"){
stream->readNext();
orientee=stream->text().toInt();
if(titre =="Reference")
{
this->createReference();
}
else{
Relation* rel = new Relation(titre,description, orientee);
addRelation(rel);
}
j++;
}
if(stream->name() == "couple"){
while(stream->tokenType() != QXmlStreamReader::EndElement || (stream->name() != "couple" && stream->name() != "relation" && stream->name() != "Relations" && stream->name() != "PluriNotes" && stream->name() != "Couples")){
if(stream->tokenType() == QXmlStreamReader::StartElement) {
if(stream->name() == "x" )
{
stream->readNext();
x=stream->text().toString();
}
if(stream->name() == "y" )
{
stream->readNext();
y=stream->text().toString();
}
if(stream->name() == "label" )
{
stream->readNext();
label=stream->text().toString();
}
}
stream->readNext();
}
tabRelations[j-1]->addCouple(x,y,label);
}
}
stream->readNext();
}
}
void Relation::inverseOrientation(){
if(!orientee)
{
orientee = true;
}
else
{
for(unsigned int i=0; i < nbCouples; i++ ){
if(!existeCouple(tabCouples[i]->gety(),tabCouples[i]->getx()))
{
addCouple(tabCouples[i]->gety(),tabCouples[i]->getx(), tabCouples[i]->getLabel());
}
}
orientee = false;
}
}
| true |
3374566320d278efb32426c667cb44f103d7b975 | C++ | ankithans/Data-structures-algorithms | /Graph/08. cycle-detection-in-directed-graph-using-kahn's-algorithm.cpp | UTF-8 | 696 | 3.015625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void inputOutput() {
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
}
/*
Cycle Detection in Directed Graph using Kahn's Algorithm
I/p: 0------>1
<\ /
\ /
\ </
2------>3
Yes
1. Store indegree of every vertex.
2. Create a Queue, q
3. Add all 0 indegree vertices to the q
4. count = 0;
5. while (q is not empty)
{
a. u = q.pop();
b. For every adjacent v of u
i. Reduce indegree of v by 1.
ii. If indegree of v becomes 0, add v to the q.
c. count++;
}
6. return (count != v)
*/
int main() {
inputOutput();
return 0;
}
| true |
2b967c1b1a3818be70c4afb7bbe63a95cf239ebe | C++ | JamesBoer/Jinx | /Source/JxScript.h | UTF-8 | 4,577 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
The Jinx library is distributed under the MIT License (MIT)
https://opensource.org/licenses/MIT
See LICENSE.TXT or Jinx.h for license details.
Copyright (c) 2016 James Boer
*/
#pragma once
#ifndef JX_SCRIPT_H__
#define JX_SCRIPT_H__
namespace Jinx::Impl
{
class Script;
using ScriptIPtr = std::shared_ptr<Script>;
class Script final : public IScript, public std::enable_shared_from_this<Script>
{
public:
Script(RuntimeIPtr runtime, BufferPtr bytecode, Any userContext);
virtual ~Script();
RuntimeID FindFunction(LibraryPtr library, const String & name) override;
Variant CallFunction(RuntimeID id, Parameters params) override;
CoroutinePtr CallAsyncFunction(RuntimeID id, Parameters params) override;
bool Execute() override;
bool IsFinished() const override;
Variant GetVariable(const String & name) const override;
void SetVariable(const String & name, const Variant & value) override;
const String & GetName() const override { return m_name; }
Any GetUserContext() const override { return m_userContext; }
LibraryPtr GetLibrary() const override { return m_library; }
std::vector<String, Allocator<String>> GetCallStack() const;
enum class OnReturn
{
Continue,
Wait,
Finish,
};
std::shared_ptr<Runtime> GetRuntime() const { return std::static_pointer_cast<Runtime>(m_runtime); }
void CallBytecodeFunction(const FunctionDefinitionPtr & fnDef, OnReturn onReturn);
void Push(const Variant & value);
Variant Pop();
void Error(const char * message);
private:
Variant GetVariable(RuntimeID id) const;
void SetVariableAtIndex(RuntimeID id, size_t index);
void SetVariable(RuntimeID id, const Variant & value);
std::pair<CollectionPtr, Variant> WalkSubscripts(uint32_t subscripts, CollectionPtr collection);
Variant CallFunction(RuntimeID id);
Variant CallNativeFunction(const FunctionDefinitionPtr & fnDef);
bool IsIntegerPair(const Variant & value) const;
std::pair<int64_t, int64_t> GetIntegerPair(const Variant & value) const;
private:
// Pointer to runtime object
RuntimeIPtr m_runtime;
// Execution frame allows jumping to remote code (function calls) and returning
struct ExecutionFrame
{
ExecutionFrame(BufferPtr b, const char * n) : bytecode(b), reader(b), name(n) {}
explicit ExecutionFrame(FunctionDefinitionPtr fn) : ExecutionFrame(fn->GetBytecode(), fn->GetName()) {}
// Buffer containing script bytecode
BufferPtr bytecode;
// Binary reader - sequentially extracts data from bytecode buffer. The reader's
// current internal position acts as the current frame's instruction pointer.
BinaryReader reader;
// Function definition name. Note that storing a raw string pointer is reasonably safe,
// because shared pointers to other objects are referenced in this struct, and there is
// no other way to modify the containing string. I don't want to incur the expense of a
// safer string copy, which would cause an allocation cost for each function call.
const char * name;
// Top of the stack to clear to when this frame is popped
size_t stackTop = 0;
// Continue or pause execution at the end of this frame
OnReturn onReturn = OnReturn::Continue;
};
// Static memory pool for fast allocations
static const size_t ArenaSize = 4096;
StaticArena<ArenaSize> m_staticArena;
// Execution frame stack
std::vector<ExecutionFrame, StaticAllocator<ExecutionFrame, ArenaSize>> m_execution{ m_staticArena };
// Runtime stack
std::vector<Variant, StaticAllocator<Variant, ArenaSize>> m_stack{ m_staticArena };
// Track top of stack for each level of scope
std::vector<size_t, StaticAllocator<size_t, ArenaSize>> m_scopeStack{ m_staticArena };
// Collection of ID-index associations
struct IdIndexData
{
IdIndexData(RuntimeID i, size_t idx, size_t f) : id(i), index(idx), frameIndex(f) {}
RuntimeID id;
size_t index;
size_t frameIndex;
};
std::vector<IdIndexData, StaticAllocator<IdIndexData, ArenaSize>> m_idIndexData{ m_staticArena };
// Local function map
using LocalFunctionList = std::vector<RuntimeID, StaticAllocator<RuntimeID, ArenaSize>>;
LocalFunctionList m_localFunctions{ m_staticArena };
// Current library
LibraryIPtr m_library;
// User context pointer
Any m_userContext;
// Initial position of bytecode for this script
size_t m_bytecodeStart = 0;
// Is finished executing
bool m_finished = false;
// Runtime error
bool m_error = false;
// Script name
String m_name;
};
} // namespace Jinx::Impl
#endif // JX_SCRIPT_H__
| true |
0ffb650ff2cd0a386f8165ee83b2495ddee2fb2e | C++ | younies/unieativeTaxonomer | /unieativeTaxonomer/CoreTaxonomer.cpp | UTF-8 | 6,410 | 2.796875 | 3 | [] | no_license | //
// CorseTaxonomer.cpp
// unieativeTaxonomer
//
// Created by Younies Mahmoud on 8/8/16.
// Copyright © 2016 Younies Mahmoud. All rights reserved.
//
#include "CoreTaxonomer.hpp"
CoreTaxonomer::CoreTaxonomer(vector<YRJObject *> yrjVector , Hash * hash)
{
//setting up the hash
this->theHash = hash;
this->yrjVector = yrjVector;
//to calculate the size of the whole database hashed kmers
this->coreHashNodesSize = 0;
for(YRJObject* node : this->yrjVector)
this->coreHashNodesSize += node->getNumOfKmers();
//to build the hashed database
this->coreHashedNodes.resize(this->coreHashNodesSize);
//compy files in the coreHahsdNodes
this->fillAllTheCoreData();
//sort all the core data
cout << "starting sorting ..... \n";
std::sort(this->coreHashedNodes.begin(), this->coreHashedNodes.end() , hashedNodeCompare);
//the file is sorted
cout << "the hashed are sorted \n";
}
CoreTaxonomer::~CoreTaxonomer()
{
}
/*
//merge yrjUnieative inside the the core data
void CoreTaxonomer::copyYRJUnieativeInside(YRJUnieative & yrjUnieative)
{
yrjUnieative.fillTheHashedNodesVector();
for(LONGS i = 0 , n = yrjUnieative.hashedKmers.size() ; i < n ; ++ i)
this->coreHashedNodes[this->startIndex++] = yrjUnieative.hashedKmers[i];
yrjUnieative.clearAllTheData();
}
*/
void CoreTaxonomer::fillAllTheCoreData()
{
this->startIndex = 0;
for ( YRJObject* yrj: this->yrjVector)
{
ifstream fileStream(yrj->getMeThePath() );
//this->fileStream = &fileStream;
if(!fileStream.is_open())
{
cout<< "file not found!!!! from filling \n" + yrj->getMeThePath();
}
LONG kmerLength , numOfKmers;
fileStream.read( (char *)&kmerLength , sizeof(LONG));
fileStream.read( (char *) &numOfKmers , sizeof(LONG));
for (LONGS i = 0 , n = yrj->getNumOfKmers() ; i < n ; ++i )
{
//cout << "before reading\n";
LONG kmer ;
fileStream.read( (char *)&kmer , sizeof(LONG));
//cout << i << " " << kmer << endl;
HashedNode tempHahsed = this->theHash->getHashedNode( kmer);
tempHahsed.index = yrj->getIndex();
this->coreHashedNodes[ this->startIndex++] = tempHahsed;
}
fileStream.close();
yrj->clearTheCompleteKmers();
}
if(this->startIndex == this->coreHashNodesSize)
{
cout << "perfect filling\n";
}
this->startIndex = 0;
}
/**
Implementing the function that convert the kmer from LONGS kmer to the corresponding rawKmer and hashedPart which is the hidden part
*/
/*
HashedNode CoreTaxonomer::getTheHashedKmer(LONG kmer)
{
HashedNode ret;
bitset<sizeof(INT) * 8> first(0) , second(0);
bitset<sizeof(kmer) * 8> kmerBits(kmer);
int posFirst = 0 , posSecond = 0;
for(LONGS i = 0 , n = this->hash.size() ; i < n ; ++i )
{
if(this->hash[i])
{
first[posFirst++] = kmerBits[i];
}
else
{
second[posSecond++] = kmerBits[i];
}
}
ret.index = -1;
INT rawKmerINT = (INT)first.to_ulong();
INT hahsedINT = (INT)second.to_ulong();
ret.rawKmer.first = rawKmerINT >> (sizeof(SHORT) * 8);
ret.rawKmer.second = (rawKmerINT << (sizeof(SHORT) * 8 ) ) >> (sizeof(SHORT) * 8);
ret.hashedKmer.first = hahsedINT >> (sizeof(SHORT) * 8);
ret.hashedKmer.second = (hahsedINT << (sizeof(SHORT) * 8 ) ) >> (sizeof(SHORT) * 8);
return ret;
}
void CoreTaxonomer::updateHashValue(string hash)
{
//reverse the hash
reverse(hash.begin() , hash.end());
bitset<64> newBitHash;
for(LONGS i = 0 , n = hash.size() ; i < n ; ++i)
{
LONGS ii = i * 2;
if(hash[i] == '#' )
{
newBitHash[ii] = 1;
newBitHash[ii+1] = 1;
}
else
{
newBitHash[ii] = 0;
newBitHash[ii+1] = 0;
}
}
this->hash = newBitHash;
}
//reversing the bits of all the variable
LONG CoreTaxonomer::reverseKmer(LONG kmer)
{
int size = sizeof(LONG) * 8;
LONG ret = 0;
int kmerLastBit = kmer%2;
kmer /= 2;
ret |= kmerLastBit;
while (--size)
{
ret <<= 1;
kmerLastBit = kmer%2;
kmer /= 2;
ret |= kmerLastBit;
}
return ret;
}
*/
/**
getting the short name from the the database
*/
/*
vector<pair< short , short> > CoreTaxonomer::getShortNameFromKmer(LONG kmer)
{
HashedNode hashedKmer = getTheHashedKmer(kmer);
pair<LONGS, LONGS> startEnd = getThePlaceOfKmer(hashedKmer.rawKmer);
vector< pair<short, short> > ret;
if(startEnd.first == -1 || startEnd.second == -1) return ret;
ret.push_back(scanAtIndex( startEnd.first , hashedKmer.hashedKmer));
LONGS curr = 0;
for(LONGS i = startEnd.first + 1 ; i <= startEnd.second ; ++i)
{
pair<short, short> temp = scanAtIndex(i, hashedKmer.rawKmer);
if( temp.first == ret[curr].first)
ret[curr].second = min(ret[curr].second , temp.second );
else
{
++curr;
ret.push_back(temp);
}
}
return ret;
}
*/
/**
scanning the kmers
*/
/*
pair<short, short> CoreTaxonomer::scanAtIndex( LONGS index , pair<SHORT, SHORT> pairHashed)
{
pair<short, short> ret;
ret.first = this->coreHashedNodes[index].index;
ret.second = 0;
pair<SHORT, SHORT> comparedHash = this->coreHashedNodes[index].hashedKmer;
while( comparedHash.first != pairHashed.first)
{
++ret.second;
comparedHash.first >>= 2 ;
pairHashed.first >>= 2;
}
while( comparedHash.second != pairHashed.second)
{
++ret.second;
comparedHash.second >>= 2 ;
pairHashed.second >>= 2;
}
return ret;
}
*/
/*
pair<SHORT , SHORT> CoreTaxonomer::convertINTtoPairShort(INT kmerINT)
{
pair<SHORT , SHORT> ret;
ret.first = 0;
ret.second = 0;
ret.first = kmerINT >> (sizeof(ret.first) * 8);
ret.second = (kmerINT << (sizeof(ret.first) * 8)) >> (sizeof(ret.first) * 8);
return ret;
}
*/
| true |
2081fc6f148a0a023de54ef51fd40d51faddb99d | C++ | dumppool/mazerts | /trunk/Model/Tests/DebugAssetCollectionListener.h | UTF-8 | 1,185 | 2.8125 | 3 | [] | no_license | /**
* Demonstrate & test IAssetCollectionListener -interface
*/
#ifndef __DEBUGASSETCOLLECTIONLISTNER_H__
#define __DEBUGASSETCOLLECTIONLISTNER_H__
#include "../Asset/IAsset.h"
#include "../Asset/IAssetCollectionListener.h"
#include <iostream>
using namespace std;
class DebugAssetCollectionListener : public IAssetCollectionListener
{
public:
DebugAssetCollectionListener() {
AssetCollection::registerListener(this);
cout << "COLLECTION LISTENER: registered\n";
}
~DebugAssetCollectionListener() {
AssetCollection::unregisterListener(this);
cout << "COLLECTION LISTENER: unregistered\n";
}
void handleCreatedAsset(IAsset* instance)
{
cout << "COLLECTION LISTENER: asset (assettype " << instance->getAssetType()
<< ", iid " << instance->getIID() << ") was created\n";
}
void handleReleasedAsset(IAsset* instance)
{
cout << "COLLECTION LISTENER: asset (assettype " << instance->getAssetType()
<< ", iid " << instance->getIID() << ") is being destoyed\n";
}
};
#endif // __DEBUGASSETCOLLECTIONLISTNER_H__
| true |
4c0f4621f913a913c9c0e1137b670023f5e3081e | C++ | anassaeed72/CodeEval | /PrimePalindrome.cpp | UTF-8 | 910 | 3.375 | 3 | [] | no_license | //
// main.cpp
// PrimePalindrome
//
// Created by Anas Saeed on 16/03/2015.
// Copyright (c) 2015 Anas Saeed. All rights reserved.
// https://www.codeeval.com/open_challenges/3/
#include <iostream>
bool isPalindrome(std::string input){
int length = input.length();
for (int i = 0; i < length/2; i++) {
if (input[i] !=input[length -i -1])
return false;
}
return true;
}
bool prime(int input){
for (int i = 2; i<input/2; i++) {
if (input%i == 0) {
return false;
}
}
return true;
}
void printPrimePalindrome(){
int last = 0;
for (int index = 2; index<1000;index++ ) {
if (prime(index) == false) {
continue;
}
if (isPalindrome(std::to_string(index)))
last = index;
}
std::cout << last;
}
int main(int argc, const char * argv[]) {
printPrimePalindrome();
return 0;
}
| true |
e699699230d818bb8bcb54d0193b0e0c57670767 | C++ | Wyder7PL/Project_Demo | /src/abilities/GenericAbility.hpp | UTF-8 | 628 | 2.71875 | 3 | [] | no_license | #pragma once
#include "../Ability.hpp"
#include <vector>
namespace Demo
{
class GenericAbility : public Ability
{
public:
GenericAbility();
virtual ~GenericAbility();
public:
virtual Ability* Clone() override;
virtual Action ConstructAction(const Location& destination, bool targetingEnemy) override;
void AddDamageToAbility(const std::string& damage);
void AddEffectToAbility(const std::string& effect);
virtual std::vector<std::pair<std::string,int>> GetAbilityDamageData(const bool& isSupportive) override;
private:
std::vector<std::string> abilityAttacks;
std::vector<std::string> abilityEffects;
};
}
| true |
200b242760b1a9e87f5e3d4fb2ce8afda60d88dc | C++ | moevm/oop | /6383/KaramyshevAO/lab1.2/Shape.cpp | UTF-8 | 502 | 3.15625 | 3 | [] | no_license | #include "Shape.h"
Shape::Shape(Point cntr, Color clr) : cntr(cntr), clr(clr) {
static int next_ID = 0;
ID = next_ID++;
}
const Color& Shape::Get_Color() const { return clr; }
const Point& Shape::Get_Point() const { return cntr; }
const int Shape::Get_ID() const { return ID; }
ostream& operator <<(ostream &os, const Shape &c) {
os << c.Get_ID() << "\n";
os << '(' << c.cntr.x << ',' << c.cntr.y << ')' << " [" << c.clr.red << '|' << c.clr.green << '|' << c.clr.blue << "]\n";
return os;
}
| true |
91c2442c5aa549e6b703e53d537cdec7c054e290 | C++ | lineCode/Straights | /StraightsController.cc | UTF-8 | 3,798 | 2.890625 | 3 | [] | no_license | #include "StraightsController.h"
#include "HumanPlayer.h"
#include "ComputerPlayer.h"
#include "Card.h"
#include "Table.h"
#include "Command.h"
#include <iostream> //TODO: remove
using namespace std;
StraightsController::StraightsController(int seed): seed{seed} {
gameState = make_shared<GameState>();
deck = make_shared<Deck>(seed);
table = make_shared<Table>();
}
void StraightsController::newRound() {
clearGame();
deck->shuffle();
assignCards();
gameState->setStartPlayer();
}
void StraightsController::assignCards() {
for(int i = 0; i < players.size();i++) {
for(int j = RANK_COUNT*(i) ; j < RANK_COUNT*(i+1); ++j){
std::shared_ptr<Card> card = deck->getCards(j);
players[i]->addCard(card);
}
}
}
void StraightsController::enterPlayers(std::vector<string>& input) {
players.clear();
for (int i = 0; i < input.size(); ++i){
if (input[i] == "h"){
players.emplace_back(make_shared<HumanPlayer>(table, i+1));
} else if (input[i] == "c"){
players.emplace_back(make_shared<ComputerPlayer>(table, i+1));
}
}
gameState->setPlayers(players);
}
void StraightsController::startGame() {
deck = make_shared<Deck>(seed);
clearScores();
gameState->reset();
newRound();
}
void StraightsController::clearScores() {
for(int i = 0; i < players.size();i++){
players[i]->clearScore();
}
}
void StraightsController::clearGame() {
for(int i = 0; i < players.size();i++){
players[i]->clearCards();
}
table->clearTable();
gameState->clearHistory();
}
void StraightsController::rageQuit(int playerNum){
std::vector<std::shared_ptr<Card>> cards = players[playerNum]->getCards();
std::vector<std::shared_ptr<Card>> discards = players[playerNum]->getDiscards();
std::shared_ptr<Player> p = make_shared<ComputerPlayer>(cards, discards, table, playerNum + 1, players[playerNum]->getScore());
gameState->setPlayer(p);
players[playerNum] = p;
gameState->playerTurn();
}
void StraightsController::quitGame() {
exit(0);
}
std::shared_ptr<Table> StraightsController::getTable() {
return table;
}
void StraightsController::playCard(int i) { //TODO: Should this be moved to gameState?
int currPlayer = gameState->getCurrentPlayer();
std::shared_ptr<Card> card= players[currPlayer]->getCard(i);
bool playIsLegal = table->checkLegalPlay(card);
if (playIsLegal) {
players[currPlayer]->setCommand(Type::PLAY, *card);
gameState->addRecord(Type::PLAY,*card);
players[currPlayer]->play();
gameState->setCurrentPlayer();
} else if (!playIsLegal && players[currPlayer]->getNumOfAllLegalPlays() > 0) { // have a legal play but player played an illegal card
// show dialog message
gameState->setLegalStatus(false);
gameState->notifyObservers();
gameState->setLegalStatus(true);
} else {
players[currPlayer]->setCommand(Type::DISCARD, *card);
gameState->addRecord(Type::DISCARD,*card);
players[currPlayer]->discard();
gameState->setCurrentPlayer();
}
gameState->notifyObservers();
}
int StraightsController::getPlayerPoints(int num) const {
return players[num]->getScore();
}
int StraightsController::getPlayerDiscards(int num) const {
return players[num]->getNumDiscards();
}
std::vector<std::shared_ptr<Player>>& StraightsController::getPlayers() {
return players;
}
std::shared_ptr<Player>& StraightsController::getPlayer(int num) {
return players[num];
}
std::shared_ptr<GameState> StraightsController::getGameState() const {
return gameState;
}
void StraightsController::setSeed(int input){
seed = input;
}
| true |
e7ebfb72379e36021419dab79c3d7fb54aea798f | C++ | sheMnapion/http-server | /src/httpServer.cc | UTF-8 | 2,230 | 2.875 | 3 | [] | no_license | #include "httpServer.h"
static httpInfo innerHttpInfo;
void clear(httpInfo *information)
{
for(int i=0;i<100;i++){
information->getInfo[i]=0;
information->hostInfo[i]=0;
}
for(int i=0;i<1000;i++)
information->userAgentInfo[i]=0;
}
httpInfo analyzeExplorer(char *buf)
{
strPointer httpEditionPointer,hostPointer,userAgentPointer,acceptPointer;
char *bufCopy;
bufCopy=buf;
//printf("Buf:\n%s\n",buf);
clear(&innerHttpInfo);
innerHttpInfo.isValid=true;
if(strncmp(bufCopy,"POST",4)==0){
innerHttpInfo.requestType=POST;
httpEditionPointer=strstr(bufCopy,"HTTP/1.1");
if(httpEditionPointer==NULL){
innerHttpInfo.isValid=false;
return innerHttpInfo;
}
for(int i=0;bufCopy+i+5<httpEditionPointer;i++){
innerHttpInfo.postInfo[i]=bufCopy[5+i];
}
}
else if(strncmp(bufCopy,"GET",3)==0){
innerHttpInfo.requestType=GET;
httpEditionPointer=strstr(bufCopy,"HTTP/1.1");
if(httpEditionPointer==NULL){
innerHttpInfo.isValid=false;
return innerHttpInfo;
}
for(int i=0;bufCopy+i+4<httpEditionPointer;i++){
innerHttpInfo.getInfo[i]=bufCopy[4+i];
}
}
else{
innerHttpInfo.isValid=false;
return innerHttpInfo;
}
//printf("INNER SHOW:\n");
//show(innerHttpInfo);
hostPointer=strstr(bufCopy,"Host: ");
userAgentPointer=strstr(bufCopy,"User-Agent: ");
acceptPointer=strstr(bufCopy,"Accept: ");
//printf("Bufcopy:%p hostPointer:%p userAgent:%p acceptPointer:%p",bufCopy,hostPointer,userAgentPointer,acceptPointer);
if(hostPointer==NULL||userAgentPointer==NULL||acceptPointer==NULL){
innerHttpInfo.isValid=false;
return innerHttpInfo;
}
for(int i=0;;i++){
if(hostPointer[i+6]!='\r')
innerHttpInfo.hostInfo[i]=hostPointer[i+6];
else
break;
}
for(int i=0;;i++){
if(userAgentPointer[i+12]!='\n')
innerHttpInfo.userAgentInfo[i]=userAgentPointer[i+12];
else
break;
}
return innerHttpInfo;
}
void show(httpInfo information)
{
if(information.isValid==false)
printf("Invalid Connection info collected!\n");
else{
printf("%s:",information.requestType==POST?"post":"get");
printf("%s\n",information.getInfo);
printf("%s\n",information.postInfo);
printf("HostInfo:%s\n",information.hostInfo);
printf("UserAgent:%s\n",information.userAgentInfo);
}
}
| true |
47159ad3962ff78ebac13493f7bb5d0872146fb8 | C++ | fameowner99/AbstractVM | /inc/Wrapper.hpp | UTF-8 | 304 | 2.9375 | 3 | [] | no_license | #ifndef WRAPPER_HPP
# define WRAPPER_HPP
template <typename T>
class Wrapper_around
{
public:
Wrapper_around(T value)
: _value(value)
{ }
T operator *()
{
return _value;
}
virtual ~Wrapper_around()
{
delete _value;
}
T getValue()
{
return (_value);
}
private:
T _value;
};
#endif | true |
ad03d70c1290265da4408270bc0ed5d4cd870187 | C++ | Pnayaka/CPP-Working-Examples | /Distlib.cpp | UTF-8 | 769 | 3.296875 | 3 | [] | no_license |
class Distance
{
int iFeet;
float fInches;
public:
void setFeet(int);
int getFeet() const; //constant function
void setInches(float);
float getInches() const; //constant function
Distance add(Distance) const; //constant function
};
void Distance::setFeet(int x)
{
iFeet=x;
}
int Distance::getFeet() const //constant function
{
iFeet++; //ERROR!!
return iFeet;
}
void Distance::setInches(float y)
{
fInches=y;
}
float Distance::getInches() const //constant function
{
fInches=0.0; //ERROR!!
return fInches;
}
Distance Distance::add(Distance dd) const //constant
//function
{
Distance temp;
temp.iFeet=iFeet+dd.iFeet;
temp.setInches(fInches+dd.fInches);
iFeet++; //ERROR!!
return temp;
} | true |
522dbd3014ad3bdbfdde05891d5f6d46764a4b41 | C++ | shrimpboyho/combo | /combo/combo/main.cpp | UTF-8 | 346 | 2.515625 | 3 | [] | no_license | #include "stdafx.h"
#include "std_lib_facilities.h"
#include "combo.h"
int main(){
cout << "Hello world!" << endl;
int hello [4];
hello[0] = 1;
hello[1] = 16;
int goodbye [2];
goodbye[0] = 3;
goodbye[1] = 9;
combo objectification;
objectification.concat(hello, goodbye);
cout << concat[3];
keep_window_open();
return 0;
} | true |
ffd25deb51c0ccdbacf919a3094b860cc5ed6b34 | C++ | PJ-Finlay/Game-Room-App | /ui/views/gameplay.cpp | UTF-8 | 6,468 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "gameplay.h"
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QTime>
#include <QCoreApplication>
#include "../widgets/pushbuttonwithid.h"
#include <QDebug>
GamePlay::GamePlay(std::shared_ptr<Game> game, QWidget* parent) : View(parent)
{
//Initialize PIV's
this->game = game;
layout = new QStackedLayout(this);
this->setLayout(layout);
gamePlayIndex = -1;
optionsSelectorIndex = -1;
gameOverIndex = -1;
showOptionsSelector();
}
void GamePlay::showGamePlay()
{
playerConfiguration = playerSelection->getPlayerSelection();
if(gamePlayIndex < 0){
this->gameState = game->getGameState();
this->gameWidget = game->getGameWidget();
//Initialize GUI
QWidget* gamePlay = new QWidget(this);
//Create button that returns user the the GameChooser view
QPushButton* returnToGameChooserButton = new QPushButton("<-",gamePlay);
//Set GameWidget Parent
gameWidget->setParent(gamePlay);
//Create the layout for Gameplay view
QVBoxLayout* layout = new QVBoxLayout(gamePlay);
//Add both widgets in VBoxLayout
layout->addWidget(returnToGameChooserButton);
layout->addWidget(gameWidget);
//Set the layout
gamePlay->setLayout(layout);
//Connect clicked signal from return button to the returnToGameChooser signal
QObject::connect(returnToGameChooserButton,SIGNAL(clicked(bool)),this,SLOT(returnToGameChooser()));
//Connect moveEntered signal and slot
QObject::connect(gameWidget,SIGNAL(moveEntered(QString)),this,SLOT(moveEntered(QString)));
//Setup GameState
gameState->initializeGame();
gameWidget->setGameState(gameState->getGameState());
checkForComputerPlay();
gamePlayIndex = this->layout->addWidget(gamePlay);
//Makes it not a "Normal View"
this->setIsNormalView(false);
}
this->layout->setCurrentIndex(gamePlayIndex);
}
void GamePlay::resetBoard()
{
gameState->initializeGame();
gameWidget->setGameState(gameState->getGameState());
showGamePlay();
}
void GamePlay::showOptionsSelector()
{
if(optionsSelectorIndex < 0){
this->gameState = game->getGameState();
//Initialize GUI
QWidget* optionsView = new QWidget(this);
//Create button that returns user the the GameChooser view
QPushButton* returnToGameChooserButton = new QPushButton("<-",optionsView);
QVBoxLayout* layout = new QVBoxLayout(optionsView);
layout->addWidget(returnToGameChooserButton);
//Create buttons for player selection
playerSelection = new PlayerSelection(gameState->getValidNumberOfPlayers(),optionsView);
layout->addWidget(playerSelection);
//Create continue button
QPushButton* continueButton = new QPushButton("Continue",optionsView);
layout->addWidget(continueButton);
QObject::connect(continueButton,SIGNAL(clicked(bool)),this,SLOT(showGamePlay()));
//Set the layout
optionsView->setLayout(layout);
//Connect clicked signal from return button to the returnToGameChooser signal
QObject::connect(returnToGameChooserButton,SIGNAL(clicked(bool)),this,SLOT(returnToGameChooser()));
optionsSelectorIndex = this->layout->addWidget(optionsView);
//Makes it a "Normal View"
this->setIsNormalView(true);
}
this->layout->setCurrentIndex(optionsSelectorIndex);
}
void GamePlay::checkForComputerPlay()
{
int turn = gameState->getTurn();
if(playerConfiguration.mid(turn - 1,1).compare("c") == 0 && gameState->findWinners() == -1){//If it is the computer's turn
//Take the current time to determine when to stop the pause
QTime endTime = QTime::currentTime().addMSecs( movePause );
//Get the computer's move
QString computerMove = game->getComputerPlayer()->getMoveFromGameState(gameState->getGameState());
//Keep executing events until the endTime is reached
while( QTime::currentTime() < endTime )
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
//Send the computer's move to the GameWidget
moveEntered(computerMove);
}
}
void GamePlay::showGameOver()
{
if(gameOverIndex < 0){
QWidget* gameOverWidget = new QWidget(this);
QVBoxLayout* layout = new QVBoxLayout(gameOverWidget);
QString titleText = "Player " + QString::number(gameState->findWinners()) + " Won";
if(gameState->findWinners() == 0) titleText = "There Was A Tie";
QLabel* title = new QLabel(titleText,gameOverWidget);
layout->addWidget(title);
QPushButton* viewGame = new QPushButton("View Game", gameOverWidget);
QObject::connect(viewGame,SIGNAL(clicked(bool)),this,SLOT(showGamePlay()));
layout->addWidget(viewGame);
QPushButton* playAgain = new QPushButton("Play Again", gameOverWidget);
QObject::connect(playAgain,SIGNAL(clicked(bool)),this,SLOT(resetBoard()));
layout->addWidget(playAgain);
QPushButton* mainMenu = new QPushButton("Return to Main Menu", gameOverWidget);
QObject::connect(mainMenu,SIGNAL(clicked(bool)),this,SLOT(returnToGameChooser()));
layout->addWidget(mainMenu);
gameOverWidget->setLayout(layout);
gameOverIndex = this->layout->addWidget(gameOverWidget);
}
this->layout->setCurrentIndex(gameOverIndex);
}
void GamePlay::returnToGameChooser(){
emit returnToGameChooserClicked();
}
void GamePlay::moveEntered(QString move)
{
if(gameState->isValidMove(move) && gameState->findWinners() < 0){
gameState->makeMove(move);
gameWidget->makeMove(move);
gameWidget->setGameState(gameState->getGameState());
if(gameState->findWinners() != -1){
//Pause so that the player has time to view the board
//Take the current time to determine when to stop the pause
QTime endTime = QTime::currentTime().addMSecs( movePause );
//Keep executing events until the endTime is reached
while( QTime::currentTime() < endTime )
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
showGameOver();
return;
}
checkForComputerPlay();
}
}
| true |
b85640260d8d358bfd0d58056b33a3e925f777ba | C++ | kevinnguyeneng/c-simple-console | /Chapter1/ex1_4.cc | UTF-8 | 1,182 | 3.9375 | 4 | [] | no_license | #include<stdio.h>
int main(int argc, char *argv[]){
// create two arrays we care about
int ages[]= {23, 43, 12, 89, 2};
char *names[]={
"Alan", "Frank", "Marry",
"John", "Lisa"
};
// safely get the size of ages
int count = sizeof(ages)/sizeof(int);
int i =0;
// first way using indexing
for(i=0; i < count ; i++){
printf("%s have %d years alive.\n", names[i], ages[i]);
}
printf("---\n");
// setup the pointer to the start of the arrays
int *cur_age = ages;
char **cur_name = names;
// second way using the pointer
for(i=0; i<count; i++){
printf("%s is %d year old.\n",
*(cur_name+i), *(cur_age + i));
}
printf("---\n");
// third way, pointers are just array
for(i=0; i<count;i++){
printf("%s is %d year old.\n", cur_name[i], cur_age[i]);
}
// fourth way with pointers in a stupid complex way
for(cur_name=names, cur_age=ages;(cur_age-ages)<count; cur_name++,cur_age++){
printf("%s is %d year so far.\n", *cur_name, *cur_age);
}
return 0;
} | true |
9c97a0b0a56ba06e5b87f243e1c3c73c618c7aa1 | C++ | WolfieGo-Pro/C-Starterbook-2 | /switch_condition.cpp | UTF-8 | 1,569 | 3.5 | 4 | [] | no_license | /*
SWITCH IS LIKE 'ELSE IF' BUT HAS BEEN HIGHLY OPTIMIZED TO RUN CONDITIONAL STATEMENTS A BIT FASTER
IT ALSO LET'S THE PROGRAMMER 'CHOOSE BETWEEN VARIOUS POSSIBLE VALUES/CASES'
*/
#include "pch.h"
using namespace std;
// THIS IS WHERE I ALSO LEARNED ABOUT FUNCTIONS (AT O LEVEL)
int switch_condition() {
const string ls3{ "\n\t\t\t" };
cout << ls3 << "What would you like to do?" << endl;
string strange_menus[]{ "Do Nothin", "Study ? ", "Watch cat videos ? ", "Jerk off ? ", "Quit like a loser ? " };
for (short i = 0; i < sizeof(strange_menus) / sizeof(string); i++)
{
cout << ls3 << i << " " << strange_menus[i] << endl;
}
cout << ls3 << "Type the corresponding number: " << flush;
int user_input;
const int study{ 1 }; //Not necesarry, just wanted to use this variable as a means to change a case label
cin >> user_input;
switch (user_input)
{
default:
cout << ls3 << "Dude, at least type something" << endl;
break; //'break' function isn't necessary with the 'default' case
case 0: // The case label can be the name of the variable only if it's an int or char, set to constant and doesn't need a user's input
cout << ls3 << "Bruh, U Jobless" << endl;
break;
case study:
cout << ls3 << "Bruh, U are blessed. Go for it" << endl;
break;
case 2:
cout << ls3 << "Bruh, seriously?" << endl;
break;
case 3:
cout << ls3 << "Bruh, Couldn't think of anything else?" << endl;
break;
case 4:
cout << ls3 << "Bruh, U weak AF" << endl;
break;
}
exit(2);
} | true |
05947532f350ac7d621337b47cd3896a41ccb2a0 | C++ | Aleks-Ada/advanced-programming-2 | /src/board-renderer/board-renderer.cc | UTF-8 | 3,418 | 3.0625 | 3 | [] | no_license | #include <memory>
#include "board-renderer.h"
#include "shared.h"
void BoardRenderer::SetMode(const RenderMode render_mode) {
this->render_mode = render_mode;
}
std::string_view NewLine() {
return "\n";
}
std::string_view CellSeparator() {
return " ";
}
std::string_view BlankCell() {
return " ";
}
std::string_view HitMarker() {
return "●";
}
std::string_view MissMarker() {
return "X";
}
std::string_view MineMarker() {
return "M";
}
std::string Pad(const std::string& string, const int required_size) {
int actual_size = string.size();
if (string == "●") { // unicode wide strings converted to narrow strings have extra chars
actual_size = 1;
}
if (actual_size >= required_size) {
return string;
}
const int padding_letters_required = required_size - actual_size;
return string + std::string(padding_letters_required, ' ');
}
std::string BoatToString(const Boat& boat) {
return std::string() + boat.GetName().at(0);
}
bool BoardRenderer::ShouldRenderWide(const int column) const {
if (render_mode != SELF) {
return false;
}
for (int row = 1; row <= board.GetHeight(); ++row) {
const Location location(column, row);
const bool is_wide_cell = board.IsMine(location) && board.GetBoat(location).has_value();
const bool will_render_wide = !board.IsHit(location);
if (is_wide_cell && will_render_wide) {
return true;
}
}
return false;
}
std::string BoardRenderer::Render() const {
const int width = board.GetWidth();
const int height = board.GetHeight();
const int max_column_identifier_chars = CoordinateToLetter(board.GetWidth()).size();
const int max_row_identifier_chars = std::to_string(height).size();
auto rows = std::make_unique<std::string[]>(height + 1);
// Column 0, Row 0
rows[0] += std::string(max_row_identifier_chars, ' ');
// Column 0
for (int row = 1; row <= height; ++row) {
rows[row] += Pad(std::to_string(row), max_row_identifier_chars);
}
for (int column = 1; column <= width; ++column) {
constexpr static int wide_render_chars = 3;
const int max_render_width = ShouldRenderWide(column) ?
std::max(max_column_identifier_chars, wide_render_chars) :
max_column_identifier_chars;
// Row 0
rows[0] += CellSeparator();
rows[0] += Pad(CoordinateToLetter(column), max_render_width);
for (int row = 1; row <= height; ++row) {
const Location location(column, row);
std::string cell_marker;
if (board.HasShot(location)) {
if (board.IsHit(location)) {
cell_marker = HitMarker();
} else {
cell_marker = MissMarker();
}
} else if (render_mode == SELF) {
std::optional<Boat> boat = board.GetBoat(location);
if (boat.has_value()) {
cell_marker = BoatToString(boat.value());
if (board.IsMine(location)) {
cell_marker += "/";
cell_marker += MineMarker();
}
} else if (board.IsMine(location)) {
cell_marker = MineMarker();
} else {
cell_marker = BlankCell();
}
} else {
cell_marker = BlankCell();
}
rows[row] += CellSeparator();
rows[row] += Pad(cell_marker, max_render_width);
}
}
std::string render;
for (int row = 0; row <= height; ++row) {
render += rows[row];
render += "\n";
}
return render;
}
| true |
6f2a4d29760cddc3da6bb3e5b3a4ca48e486ff93 | C++ | Blackstar699/Warped | /game/environment.cpp | UTF-8 | 2,605 | 3.21875 | 3 | [] | no_license | #include "environment.h"
///affiche le background du jeu
void background(sf::RenderWindow& window, sf::Texture& texture){
sf::Sprite sprite(texture);
sprite.setPosition(0,0);
window.draw(sprite);
}
///affiche l'environnement correspondant aux données de la map en paramètre
void environment(sf::RenderWindow& window, const std::map<std::pair<int, int>, int>& map, sf::Vector2f player_pos, sf::Texture& texture){
sf::Sprite sprite(texture);
for(auto& ligne : map){
const int x = ligne.first.first, y = ligne.first.second, sprite_nbr = ligne.second;
if(sprite_nbr != -1 && !(x * 32 > player_pos.x + 1300 || x * 32 < player_pos.x - 1300 || y * 32 > player_pos.y + 500 || y * 32 < player_pos.y - 500)){
sprite = tileset1(sprite, sprite_nbr);
sprite.setPosition(sf::Vector2f(x * 32, y * 32));
window.draw(sprite);
}
}
}
///découpe correctement la tileset 1
sf::Sprite tileset1(sf::Sprite& sprite, int sprite_number){
sf::Vector2i position(0, 0);
position.x = sprite_number - floor(sprite_number / 12) * 12;
position.y = floor(sprite_number / 12);
sprite.setTextureRect(sf::IntRect(position.x * 32, position.y * 32, 32, 32));
return sprite;
}
///reset la vue en fonction de l'emplacement du personnage
void setPlayerView(sf::View& view, sf::Vector2i screen_size, sf::Vector2f player_pos){
view.reset(sf::FloatRect(0, 0, screen_size.x, screen_size.y));
sf::Vector2i position(screen_size.x/2, screen_size.y/2);
position.x = player_pos.x + 70 - screen_size.x/2.f;
position.y = player_pos.y + 66 - screen_size.y/1.5f;
if(position.x <= 0)
position.x = 0;
else if(position.x + screen_size.x >= 11776)
position.x = 11776 - screen_size.x;
if(position.y + screen_size.y >= 352)
position.y = 352 - screen_size.y;
view.reset(sf::FloatRect(position.x, position.y, screen_size.x, screen_size.y));
}
///met dans un vector les coordonnées de chaque élément de décors non traversable
vector<sf::Vector2i> untraversablesTileset1(std::map<std::pair<int, int>, int>& map, const vector<int>& untraversables_blocks){
vector<sf::Vector2i> vector;
for(auto& ligne : map){
const int x = ligne.first.first, y = ligne.first.second, sprite_nbr = ligne.second;
for(int untraversables_block : untraversables_blocks){
if(sprite_nbr == untraversables_block){
sf::Vector2i block(x * 32, y * 32);
vector.push_back(block);
break;
}
}
}
return vector;
}
| true |
acb20c8c0af616dddb68b50d270b43465be3d500 | C++ | dmingn/AOJ | /ALDS1/ALDS1_3_D.cpp | UTF-8 | 992 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
int main() {
string str;
cin >> str;
stack<uint32_t> s;
vector<pair<uint32_t, uint32_t>> v;
for (uint32_t i = 0; i < str.length(); i++) {
if (str[i] == '\\') {
s.push(i);
} else if (str[i] == '/' && !s.empty()) {
uint32_t j = s.top();
s.pop();
uint32_t area = i - j;
while (!v.empty() && v.back().first > j) {
area += v.back().second;
v.pop_back();
}
v.push_back(make_pair(j, area));
}
}
cout << accumulate(v.begin(), v.end(), 0, [](uint32_t sum, pair<uint32_t, uint32_t> p) {
return sum + p.second;
}) << endl;
cout << v.size();
for (pair<uint32_t, uint32_t> p : v) cout << " " << p.second;
cout << endl;
return 0;
}
| true |
f011abc1de87381d1624c36e79f08f74a0de5e7a | C++ | aduxbury0/C-UniModule | /Week 3/Week 3 Task 1/Week 3 Task 1/Source.cpp | UTF-8 | 2,564 | 4.21875 | 4 | [] | no_license | /* Week 3 Task 1 - Program that prints words mirrored from a single sentence input, the complexity being O(1^n) as the function calls only a single copy of itself for every iteration */
#include "stdafx.h"
#include "Source.h"
int main() {
string wordListInput;
string wordCount;
// Getting the sentence and the number of words within it
cout << "Please enter your list of words seperated by single spaces: " << endl;
getline(cin, wordListInput);
cout << endl << "Please enter the number of words in the sentence: " << endl;
getline(cin, wordCount);
//Creating Stringstream using the inputted sentence
stringstream stringStream1(wordListInput);
string word;
vector<string> newList; // This is the vector that will be used to store the reversed words
// Using the getline function with stringstream to get every word individually using the ' ' as a delimiter to indicate the end of the line
while (getline(stringStream1, word, ' ')) {
word = Mirroring(word, 0);
newList.push_back(word);
}
// Range based for loop, will iterate through every item in the vector and output the reversed words
for (auto i : newList) {
cout << i << ' ';
}
cout << endl;
system("PAUSE");
return 0;
}
/* This function is for mirroring an input word
Input: string word - the word that needs to be mirrored
int count - This is a counter of how many times the word has gone through the recursive process, it is used to determine which set of 2 letters in the word need swapping in this recursive step
Output: Returns the word with its letters swapped if the function determines that it has been fully mirrored, else it will recursively call itself again until that case is reached.
Base Case: startpoint and endpoint become equal or if startpoint > endpoint
*/
string Mirroring(string& word, int count) {
//determines which 2 letters need swapping by adding the count to the start point of the word and subtracting it from the end point
int startPoint = 0 + count;
int endPoint = (word.length() - count) - 1;
string newWord = word;
char charstore;
// Where the 2 letters in the word get swapped
if (startPoint < endPoint) {
charstore = newWord[startPoint];
newWord[startPoint] = newWord[endPoint];
newWord[endPoint] = charstore;
count++;
// Calls itself to check to see if the word has been completely mirrored, if yes it will return the word and if not it will repeat the process with the next letters
newWord = Mirroring(newWord, count);
return newWord;
}
else {
return word;
}
} | true |
225302dc63962fa4961bac6ad03e140285c03224 | C++ | akhileshs/oj-solutions | /antiblot.cpp | UTF-8 | 1,219 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<sstream>
#include<vector>
using namespace std;
vector<string> split(string s, string del = " "){
char *word, *buf, *delim;
vector<string> res;
delim=strdup(del.c_str());
buf = strdup(s.c_str());
for(word=strtok(buf,delim); word; word=strtok(0, delim))
res.push_back(string(word));
free(buf);
free(delim);
return res;
}
int str2int(const string &str){
stringstream ss(str);
int n;
ss>>n;
return n;
}
int main(){
int t,a,b;
scanf("%d\n\n",&t);
string input;
vector<string> parts, temp;
while(t--){
getline(cin, input);
scanf("\n");
parts = split(input, " +=");
if(parts[0].find("machula") != -1){
a=str2int(parts[1]);
b=str2int(parts[2]);
cout<<b-a<<" + "<<a<<" = "<<b<<endl;
}
else if(parts[1].find("machula") != -1){
a=str2int(parts[0]);
b=str2int(parts[2]);
cout<<a<<" + "<<b-a<<" = "<<b<<endl;
}
else if(parts[2].find("machula") != -1){
a=str2int(parts[0]);
b=str2int(parts[1]);
cout<<a<<" + "<<b<<" = "<<a+b<<endl;
}
else{
cout<<input<<endl;
}
}
}
| true |
93d9131593b1a5ae25a54cd70c3a569bb5d058a0 | C++ | lia-univali/ImageEvolution | /ImageEvolution/evolver.h | UTF-8 | 1,515 | 2.78125 | 3 | [] | no_license | #ifndef EVOLVER_H
#define EVOLVER_H
#include <cstdlib>
#include <vector>
#include <SFML/Graphics.hpp>
#include "solution.h"
#include <utility>
#include <functional>
class Evolver
{
public:
using ParentPair = std::pair<std::reference_wrapper<Solution>, std::reference_wrapper<Solution>>;
using Population = std::vector<Solution>;
private:
using uint = unsigned int;
double totalFitness;
uint populationSize = 1600;
uint threadCount = 8;
uint generation;
const sf::Uint8* target;
uint solutionLength;
Population population;
Evolver::ParentPair selectParents();
void mutate(Solution& solution);
Solution crossover(const Solution& a, const Solution& b);
uint selectRoulette(bool invert = false);
Population createChildren(uint count);
void sortPopulation();
static bool isAlpha(uint value);
Evolver::uint selectTournament(double pressure, uint count);
std::vector<Solution> loadSolutions(const std::string &path, sf::Vector2u size, unsigned int amount);
inline double calculateMutation();
public:
Evolver();
Evolver::Population generatePopulation(uint amount, uint solutionLength);
void evaluateSolution(Solution& solution);
void prepare(const sf::Uint8 *target, sf::Vector2u size, std::string path = std::string());
void evolve();
uint getGeneration() const;
Evolver::Population& getPopulation();
uint getSolutionLength() const;
unsigned int getPopulationSize() const;
};
#endif // EVOLVER_H
| true |
9c749c13ea9ca6dc2af6bda56bfa59ff432d10bf | C++ | tarang98/turtle_ROS | /solution.cpp | UTF-8 | 1,895 | 2.71875 | 3 | [] | no_license | #include "ros/ros.h"
#include "geometry_msgs/Twist.h"
const double PI = 3.14159265359;
// Initialize the node
int main(int argc, char **argv)
{
ros::init(argc, argv, "move_turtle");
ros::Rate rate(3);
//void move(double distance, int turn);
move(1.0, 1);
move(1.0, 3);
move(2.0, 3);
move(6.0, 1);
move(1.0, 2);
move(1.0, 3);
move(1.0, 3);
move(1.0, 1);
move(1.0, 1);
move(1.0, 2);
move(1.0, 3);
move(1.0, 3);
move(1.0, 1);
move(0.5, 3);
move(1.0, 1);
move(3.0, 2);
move(2.0, 2);
move(0.5, 3);
move(2.0, 3);
move(1.0, 1);
move(2.0, 1);
move(1.0, 3);
move(2.0, 3);
move(1.0, 1);
move(3.0, 1);
move(1.0, 2);
move(1.0, 1);
move(2.0, 3);
move(1.0, 1);
move(2.0, 1);
move(2.0, 2);
move(1.0, 1);
move(2.0, 1);
move(2.0, 3);
move(2.0, 3);
move(1.0, 3);
move(2.0, 3);
move(2.0, 2);
move(2.0, 1);
move(2.0, 1);
move(1.0, 3);
move(2.0, 3);
move(2.0, 2);
move(2.0, 3);
move(1.0, 3);
move(1.0, 3);
move(1.0, 1);
move(1.0, 1);
return 0;
/*
while (ros::ok()) {
for (int i
ROS_INFO("INFO");
pub.publish(msg);
rate.sleep();
}
*/
}
void move(double distance, int turn) {
// A publisher for the movement data
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 10);
// Drive forward at a given speed. The robot points up the x-axis.
// The default constructor will set all commands to 0
geometry_msgs::Twist msg;
if (ros::ok()) {
switch(turn) {
case 1:
msg.angular.z = PI/2;
break;
case 2:
msg.angular.z = PI;
break;
case 3:
msg.angular.z = 3*PI/2;
break;
}
msg.linear.x = 0.6 * 11.1 / 4.4;
ROS_INFO("INFO");
pub.publish(msg);
rate.sleep();
}
}
| true |
6d3533e736bcca624e9ac208b754fd422928beec | C++ | Deividy/lab | /cc/rpg/game.h | UTF-8 | 672 | 2.796875 | 3 | [] | no_license | #include <vector>
#include <string>
namespace rpg {
using namespace std;
class Player {
public:
Player (string name): m_name{name} {};
string name () const { return m_name; };
void name (string newName) { m_name = newName; };
private:
string m_name;
};
class Game {
public:
Game (vector<Player> players): m_players{players} {};
vector<Player> players () const { return m_players; };
void addPlayer (Player player);
private:
vector<Player> m_players;
};
class Story {};
class Action {};
class NPC {};
}
| true |
468ed6ea273e50e8e633cfd3f3dbf20ecb43e820 | C++ | funny07/leet-src | /linear_table/removeDuplicatesArrays.cpp | UTF-8 | 1,243 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0)
return 0;
bool same = false;
vector<int>::iterator iter_cur = nums.begin();
vector<int>::iterator iter = nums.begin();
for (++iter; iter!=nums.end(); ++iter)
{
if(*iter == *iter_cur)
{
if (!same)
iter_cur++;
same = true;
}
else{
if (!same)
iter_cur++;
else
*iter_cur = *iter;
same = false;
}
}
if (!same)
++iter_cur;
nums.erase(iter_cur, iter);
return nums.size();
}
};
int main()
{
Solution sln;
vector<int> vec;
int nums[] = {1,1,2,3};
for (int i=0; i<sizeof(nums)/sizeof(int);i++)
vec.push_back(nums[i]);
int length = sln.removeDuplicates(vec);
printf("vec.size() = %ld\n", vec.size());
for (vector<int>::iterator iter = vec.begin(); iter!=vec.end(); ++iter)
{
printf("%d ", *iter);
}
printf("\n");
return length;
} | true |
526f630ff693868f2e0d3050c651378ac2e4fa31 | C++ | EliottPal/CCP_Plazza_2019 | /src/Process.cpp | UTF-8 | 1,177 | 2.75 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** CCP_plazza_2019
** File description:
** Process
*/
#include "Process.hpp"
Process::Process(SharedMemory &mems, float multiplier, int maxCooks, int restock)
{
this->_mems = mems;
this->_multiplier = multiplier;
this->_maxCooks = maxCooks;
this->_restockTime = restock;
std::cout << "New kitchen " << std::endl;
}
pid_t Process::getProcessPid() const
{
return getpid();
}
void Process::mainLoop()
{
Kitchen kitchen(this->_multiplier, this->_maxCooks, this->_restockTime);
while (kitchen.getStatus(this->_mems)) {
if (kitchen.getCommand().compare(0, 6, "status") == 0) {
kitchen.printStatus();
this->_mems.sendMessage("Ok");
}
else if (kitchen.getCommand().compare(0, 4, "None") != 0) {
if (kitchen.addingCommand()) {
this->_mems.sendMessage("Ok");
usleep(50);
}
else {
this->_mems.sendMessage("Error");
usleep(50);
}
}
}
this->_mems.sendMessage("Destroy");
std::cout << "Kitchen Destroyed" << std::endl;
}
Process::~Process()
{
}
| true |
684b4d375e27d7f234a1d40a9984ea8a16b72a10 | C++ | vishu9266/DDUC-Work-c- | /array.cpp | UTF-8 | 1,351 | 3.59375 | 4 | [] | no_license | #include<iostream>
using namespace std;
int number_of_students, avg;
int marks[0];
int max1, max2, sum = 0;
void marks_storage(int number_of_students);
void show_me_marks(int number_of_students);
int average_marks(int number_of_students);
int highest_marks(int number_of_students);
int main() {
cout << "Enter total no. of students: ";
cin >> number_of_students;
max1 = marks[0];
marks_storage(number_of_students);
show_me_marks(number_of_students);
avg = average_marks(number_of_students);
max2 = highest_marks(number_of_students);
cout << "Average marks are: " << avg << endl;
cout << "Highest marks obtained is: " << max2 << endl;
return 0;
}
void marks_storage(int number_of_students) {
for (int i = 0; i<number_of_students; i++)
{
cout << "Enter the marks of student " << i + 1 << " :";
cin >> marks[i];
}
}
void show_me_marks(int number_of_students) {
for (int i = 0; i<number_of_students; i++)
{
cout << "Marks of student " << i + 1 << " is " << marks[i] << endl;
}
}
int average_marks(int number_of_students) {
for (int i = 0; i<number_of_students; i++)
{
sum = sum + marks[i];
}
sum = sum / number_of_students;
return sum;
}
int highest_marks(int number_of_students) {
for (int i = 1; i<number_of_students; i++)
{
if (max1<marks[i])
{
max1 = marks[i];
}
}
return max1;
} | true |
1cacda66991c3b971fc24a7a6248048fc67d9945 | C++ | johnnyVR/cpv-framework | /include/CPVFramework/Stream/BuffersInputStream.hpp | UTF-8 | 770 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <seastar/core/temporary_buffer.hh>
#include "./InputStreamBase.hpp"
namespace cpv {
/** Input stream that use given temporary buffers as data source */
class BuffersInputStream : public InputStreamBase {
public:
/** Read data from stream */
seastar::future<InputStreamReadResult> read() override;
/** Get the hint of total size of stream */
std::optional<std::size_t> sizeHint() const override;
/** For Reusable<> */
void freeResources();
/** For Reusable<> */
void reset(std::vector<seastar::temporary_buffer<char>>&& buffers);
/** Constructor */
BuffersInputStream();
private:
std::vector<seastar::temporary_buffer<char>> buffers_;
std::size_t sizeHint_;
std::size_t index_;
};
}
| true |
b2f81c424db560a61a5e0b8ffdbe59928488d183 | C++ | shamanDevel/cuMat | /cuMat/src/Errors.h | UTF-8 | 4,828 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef __CUMAT_ERRORS_H__
#define __CUMAT_ERRORS_H__
#include <cuda_runtime.h>
#include <exception>
#include <string>
#include <cstdarg>
#include <vector>
#include <stdexcept>
#include <stdio.h>
#include "Macros.h"
#include "Logging.h"
CUMAT_NAMESPACE_BEGIN
class cuda_error : public std::exception
{
private:
std::string message_;
public:
cuda_error(std::string message)
: message_(message)
{}
const char* what() const throw() override
{
return message_.c_str();
}
};
namespace internal {
class ErrorHelpers
{
public:
static std::string vformat(const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time. Be prepared to allocate dynamically if it doesn't fit.
size_t size = 1024;
char stackbuf[1024];
std::vector<char> dynamicbuf;
char *buf = &stackbuf[0];
va_list ap_copy;
while (1) {
// Try to vsnprintf into our buffer.
va_copy(ap_copy, ap);
int needed = vsnprintf(buf, size, fmt, ap);
va_end(ap_copy);
// NB. C99 (which modern Linux and OS X follow) says vsnprintf
// failure returns the length it would have needed. But older
// glibc and current Windows return -1 for failure, i.e., not
// telling us how much was needed.
if (needed <= (int)size && needed >= 0) {
// It fit fine so we're done.
return std::string(buf, (size_t)needed);
}
// vsnprintf reported that it wanted to write more characters
// than we allotted. So try again using a dynamic buffer. This
// doesn't happen very often if we chose our initial size well.
size = (needed > 0) ? (needed + 1) : (size * 2);
dynamicbuf.resize(size);
buf = &dynamicbuf[0];
}
}
//Taken from https://stackoverflow.com/a/69911/4053176
static std::string format(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
std::string buf = vformat(fmt, ap);
va_end(ap);
return buf;
}
//Taken from https://stackoverflow.com/a/69911/4053176
// Taken from https://codeyarns.com/2011/03/02/how-to-do-error-checking-in-cuda/
// and adopted
private:
static bool evalError(cudaError err, const char* file, const int line)
{
if (cudaErrorCudartUnloading == err) {
std::string msg = format("cudaCheckError() failed at %s:%i : %s\nThis error can happen in multi-threaded applications during shut-down and is ignored.\n",
file, line, cudaGetErrorString(err));
CUMAT_LOG_SEVERE(msg);
return false;
}
else if (cudaSuccess != err) {
std::string msg = format("cudaSafeCall() failed at %s:%i : %s\n",
file, line, cudaGetErrorString(err));
CUMAT_LOG_SEVERE(msg);
throw cuda_error(msg);
}
return true;
}
public:
static void cudaSafeCall(cudaError err, const char *file, const int line)
{
if (!evalError(err, file, line)) return;
#if CUMAT_VERBOSE_ERROR_CHECKING==1
//insert a device-sync
err = cudaDeviceSynchronize();
evalError(err, file, line);
#endif
}
static void cudaCheckError(const char *file, const int line)
{
cudaError err = cudaGetLastError();
if (!evalError(err, file, line)) return;
#if CUMAT_VERBOSE_ERROR_CHECKING==1
// More careful checking. However, this will affect performance.
err = cudaDeviceSynchronize();
evalError(err, file, line);
#endif
}
};
/**
* \brief Tests if the cuda library call wrapped inside the bracets was executed successfully, aka returned cudaSuccess
* \param err the error code
*/
#define CUMAT_SAFE_CALL( err ) CUMAT_NAMESPACE internal::ErrorHelpers::cudaSafeCall( err, __FILE__, __LINE__ )
/**
* \brief Issue this after kernel launches to check for errors in the kernel.
*/
#define CUMAT_CHECK_ERROR() CUMAT_NAMESPACE internal::ErrorHelpers::cudaCheckError( __FILE__, __LINE__ )
//TODO: find a better place in some Utility header
/**
* \brief Numeric type conversion with overflow check.
* If <code>CUMAT_ENABLE_HOST_ASSERTIONS==1</code>, this method
* throws an std::runtime_error if the conversion results in
* an overflow.
*
* If CUMAT_ENABLE_HOST_ASSERTIONS is not defined (default in release mode),
* this method simply becomes <code>static_cast</code>.
*
* Source: The C++ Programming Language 4th Edition by Bjarne Stroustrup
* https://stackoverflow.com/a/30114062/1786598
*
* \tparam Target the target type
* \tparam Source the source type
* \param v the source value
* \return the casted target value
*/
template<class Target, class Source>
CUMAT_STRONG_INLINE Target narrow_cast(Source v)
{
#if CUMAT_ENABLE_HOST_ASSERTIONS==1
auto r = static_cast<Target>(v); // convert the value to the target type
if (static_cast<Source>(r) != v)
throw std::runtime_error("narrow_cast<>() failed");
return r;
#else
return static_cast<Target>(v);
#endif
}
}
CUMAT_NAMESPACE_END
#endif | true |
95a506b31602e1abc2dc4728b34fdcb6681f5eb6 | C++ | dongfusong/TlvProject | /TestByteOrder.cpp | WINDOWS-1252 | 676 | 2.640625 | 3 | [] | no_license | /*
* TestByteOrder.cpp
*
* Created on: 2014924
* Author: Thoughtworks
*/
#include <gtest/gtest.h>
#include "ByteOrder.h"
#include <iostream>
using namespace std;
class TestByteOrder: public testing::Test {
public:
void SetUp() {
}
void TearDown() {
}
protected:
};
TEST_F(TestByteOrder, can_byte_order_us)
{
_UC buf[] = {
0x12,0x34,0x56,0x78
};
_UL value = 0;
ByteOrder::ntoh(buf, sizeof(buf), (_UC*)&value, sizeof(value));
EXPECT_EQ(0x12345678, value);
}
TEST_F(TestByteOrder, can_byte_order_uc)
{
_UC buf[] = {
0x12
};
_UC value = 0;
ByteOrder::ntoh(buf, sizeof(buf), (_UC*)&value, sizeof(value));
EXPECT_EQ(0x12, value);
}
| true |
ab59f1ac638ce16dbad7f0ae5bc2b814643b3ede | C++ | dayuyuhai/Haizei_class | /OJ/193.是否可以求和.cpp | UTF-8 | 697 | 2.796875 | 3 | [] | no_license | /*************************************************************************
> File Name: 193.是否可以求和.cpp
> Author: 北海望谷堆
> Mail: dayuyuhai@outlook.com
> Created Time: Wed 13 May 2020 03:00:48 PM CST
************************************************************************/
#include<iostream>
using namespace std;
int a[100005];
int find(int x, int l, int r) {
if (l > r) return 0;
int mid = (l + r) >> 1;
if (a[mid] == x) return 1;
if (a[mid] > x) r = mid - 1;
else l = mid + 1;
find(x, l, r);
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
int k, s;
cin >> k >> s;
s -= k;
cout << (find(s, 1, n) ? "YES" : "NO") << endl;
return 0;
}
| true |
8fa764eb442ed8c3305057931388182aed4db0c4 | C++ | mradwan80/Multithreads | /conditions.cpp | UTF-8 | 840 | 3.328125 | 3 | [] | no_license | //thread sleeps, until notified//
#include <thread>
#include <mutex>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
stack<int> S;
mutex mtx_push;
mutex mtx_pop;
mutex mtx;
condition_variable cond;
void stack_pop()
{
unique_lock<mutex> ulk(mtx);
cond.wait(ulk); //automatically unlocks the lock !!! waits for notify(), and the lock is re-acquired then. //
int val = S.top();
S.pop();
cout << "value: " << val << "\n";
}
void stack_push(int val)
{
unique_lock<mutex> ulk(mtx);
S.push(val);
cond.notify_one();
}
int main()
{
int n = 20;
vector<thread*> threads(n);
for (int i = 0; i < n / 2; i++)
{
threads[i] = new thread(stack_pop);
}
for (int i = n / 2; i < n; i++)
{
threads[i] = new thread(stack_push, i);
}
for (int i = 0; i < n; i++)
threads[i]->join();
} | true |
7637f8650d81808f1490ce3264f584aec83cc7e4 | C++ | RaphAbb/peercode | /hw0/Graph_1787.hpp | UTF-8 | 13,198 | 3.5 | 4 | [] | no_license | #ifndef CME212_GRAPH_HPP
#define CME212_GRAPH_HPP
/** @file Graph.hpp
* @brief An undirected graph type
*/
#include <algorithm>
#include <map>
#include <unordered_map>
// For the moment I am using a convenient Boost hashing function, but no Boost containers.
// I was told that this will be OK for HW0 although I will likely change it going forward.
#include <boost/functional/hash.hpp>
#include <cassert>
#include <iterator>
#include "CME212/Util.hpp"
#include "CME212/Point.hpp"
/** @class Graph
* @brief A template for 3D undirected graphs.
*
* Users can add and retrieve nodes and edges. Edges are unique (there is at
* most one edge between any pair of distinct nodes).
*/
class Graph {
private:
public:
//
// PUBLIC TYPE DEFINITIONS
//
/** Type of this graph. */
using graph_type = Graph;
/** Predeclaration of Node type. */
class Node;
/** Synonym for Node (following STL conventions). */
using node_type = Node;
/** Predeclaration of Edge type. */
class Edge;
/** Synonym for Edge (following STL conventions). */
using edge_type = Edge;
/** Type of indexes and sizes.
Return type of Graph::Node::index(), Graph::num_nodes(),
Graph::num_edges(), and argument type of Graph::node(size_type) */
using size_type = unsigned;
//
// CONSTRUCTORS AND DESTRUCTOR
//
/** Construct an empty graph. */
Graph() {
//Leaving 0 for invalid nodes and edges
next_NodeID_=1;
next_EdgeID_=1;
deletedNodes_=0;
deletedEdges_=0;
}
/** Default destructor */
~Graph() = default;
//
// NODES
//
/** @class Graph::Node
* @brief Class representing the graph's nodes.
*
* Node objects are used to access information about the Graph's nodes.
*/
class Node {
public:
/** Construct an invalid node.
*
* Valid nodes are obtained from the Graph class, but it
* is occasionally useful to declare an @i invalid node, and assign a
* valid node to it later. For example:
*
* @code
* Graph::node_type x;
* if (...should pick the first node...)
* x = graph.node(0);
* else
* x = some other node using a complicated calculation
* do_something(x);
* @endcode
*/
// Invalid nodes have an ID of 0
Node() : gr_(nullptr), uidN_(0) {}
/** Return this node's position. */
const Point& position() const {
// Ensure that this is a valid node
// I was unsure whether or not to 'trust' the user, so the assert
// statements have been left in. They do not noticeably slow the program
// even in the large case.
assert(uidN_>0 && gr_->nodeMap.find(uidN_)!=gr_->nodeMap.end());
return gr_->nodeMap.at(uidN_);
}
/** Return this node's index, a number in the range [0, graph_size). */
size_type index() const {
assert(uidN_>0 );
//Guaranteed to throw exception if out of bounds
return gr_->nodeIndices.at(uidN_);
}
/** Test whether this node and @a n are equal.
*
* Equal nodes have the same graph and the same index.
*/
bool operator==(const Node& n) const {
assert(uidN_>0 && n.uidN_>0);
// Two nodes with same uidN_ are guaranteed to have the same index
if (n.uidN_==uidN_ && n.gr_==this->gr_)
return true;
else
return false;
}
/** Test whether this node is less than @a n in a global order.
*
* This ordering function is useful for STL containers such as
* std::map<>. It need not have any geometric meaning.
*
* The node ordering relation must obey trichotomy: For any two nodes x
* and y, exactly one of x == y, x < y, and y < x is true.
*/
bool operator<(const Node& n) const {
assert(n.uidN_>0 && uidN_>0);
/** I chose to use the unique ID
* of the node for ordering.
*/
if(uidN_<n.uidN_)
return true;
else
return false;
}
private:
// No internal elements should change
const Graph* gr_;
// Unique ID allows retrieval of Position and index
const size_type uidN_;
Node(const Graph* gr, size_type uid) : uidN_(uid) {
gr_=const_cast<Graph*>(gr);
}
// Allow Graph to access Node's private member data and functions.
friend class Graph;
// Use this space to declare private data members and methods for Node
// that will not be visible to users, but may be useful within Graph.
// i.e. Graph needs a way to construct valid Node objects
};
/** Return the number of nodes in the graph.
*
* Complexity: O(1).
*/
size_type size() const {
return (size_type) nodeMap.size();
}
/** Synonym for size(). */
size_type num_nodes() const {
return size();
}
/** Add a node to the graph, returning the added node.
* @param[in] position The new node's position
* @post new num_nodes() == old num_nodes() + 1
* @post result_node.index() == old num_nodes()
*
* Complexity: O(1) amortized operations.
*/
Node add_node(const Point& position) {
// Adds node information to each relevant unordered_map,
// increments the ID counter, and returns the node.
nodeMap[next_NodeID_]=position;
// The deleted node counter makes sure the index is correct
nodeIndicesRev[next_NodeID_-1-deletedNodes_]=next_NodeID_;
nodeIndices[next_NodeID_]=next_NodeID_-1-deletedNodes_;
next_NodeID_++;
return Node(this, next_NodeID_-1);
}
/** Determine if a Node belongs to this Graph
* @return True if @a n is currently a Node of this Graph
*
* Complexity: O(1).
*/
bool has_node(const Node& n) const {
// If a Node come from different Graph, or is not in the current Graph
// it returns false.
if (this==n.gr_ && nodeMap.find(n.uidN_)!=nodeMap.end())
return true;
return false;
}
/** Return the node with index @a i.
* @pre 0 <= @a i < num_nodes()
* @post result_node.index() == i
*
* Complexity: O(1).
*/
Node node(size_type i) const {
assert(i<size());
return Node(this,nodeIndicesRev.at(i));
}
//
// EDGES
//
/** @class Graph::Edge
* @brief Class representing the graph's edges.
*
* Edges are order-insensitive pairs of nodes. Two Edges with the same nodes
* are considered equal if they connect the same nodes, in either order.
*/
class Edge {
public:
/** Construct an invalid Edge. */
Edge() : gr_(nullptr),n1_uid_(0),n2_uid_(0),uidE_(0){
// Reserve positive ID values for valid edges
}
/** Return a node of this Edge */
Node node1() const {
assert(n1_uid_>0 && gr_->nodeMap.find(n1_uid_)!=gr_->nodeMap.end());
Node n1{gr_,n1_uid_};
return n1;
}
/** Return the other node of this Edge */
Node node2() const {
assert(n2_uid_>0 && gr_->nodeMap.find(n2_uid_)!=gr_->nodeMap.end());
Node n2{gr_,n2_uid_};
return n2;
}
/** Test whether this edge and @a e are equal.
*
* Equal edges represent the same undirected edge between two nodes.
*/
bool operator==(const Edge& e) const {
if((node1()==e.node1() && node2()==e.node2())||
(node2()==e.node1() && node1()==e.node2()))
return true;
return false;
}
/** Test whether this edge is less than @a e in a global order.
*
* This ordering function is useful for STL containers such as
* std::map<>. It need not have any interpretive meaning.
*/
bool operator<(const Edge& e) const {
assert (e.n1_uid_>0 && e.n2_uid_>0);
// Use the unique ID for ordering
if (uidE_<e.uidE_)
return true;
return false;
}
private:
// Allow Graph to access Edge's private member data and functions.
friend class Graph;
// Use this space to declare private data members and methods for Edge
// that will not be visible to users, but may be useful within Graph.
// i.e. Graph needs a way to construct valid Edge objects
Edge(const Graph* gr, const size_type uidE, const size_type n1_uid, const size_type n2_uid)
: gr_(gr),n1_uid_(n1_uid),n2_uid_(n2_uid),uidE_(uidE){
}
// No internal elements should change
const Graph* gr_;
const size_type n1_uid_;
const size_type n2_uid_;
// Unique ID allows for retrieval of index and Nodes
const size_type uidE_;
};
/** Return the total number of edges in the graph.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
size_type num_edges() const {
return (size_type) edgeMap.size();
}
/** Return the edge with index @a i.
* @pre 0 <= @a i < num_edges()
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
Edge edge(size_type i) const {
assert(i<num_edges() && edgeIndicesRev.find(i)!=edgeIndicesRev.end());
size_type uid=edgeIndicesRev.at(i);
return Edge(this,uid,edgeMap.at(uid).first,edgeMap.at(uid).second);
}
/** Test whether two nodes are connected by an edge.
* @pre @a a and @a b are valid nodes of this graph
* @return True if for some @a i, edge(@a i) connects @a a and @a b.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
bool has_edge(const Node& a, const Node& b) const {
assert(has_node(a) && has_node(b));
// If the unique hash is found already in the map, the Edge exists
std::size_t hashE=hashNodes(a,b);
if (uidEMap.find(hashE)!=uidEMap.end())
return true;
return false;
}
/** Add an edge to the graph, or return the current edge if it already exists.
* @pre @a a and @a b are distinct valid nodes of this graph
* @return an Edge object e with e.node1() == @a a and e.node2() == @a b
* @post has_edge(@a a, @a b) == true
* @post If old has_edge(@a a, @a b), new num_edges() == old num_edges().
* Else, new num_edges() == old num_edges() + 1.
*
* Can invalidate edge indexes -- in other words, old edge(@a i) might not
* equal new edge(@a i). Must not invalidate outstanding Edge objects.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
Edge add_edge(const Node& a, const Node& b) {
assert(!(a==b)&& has_node(a) && has_node(b));
//Create a unique hash based on the passed Nodes
std::size_t eHash=hashNodes(a,b);
//Create an ordered pair of the Nodes
std::pair<size_type,size_type> edgePair;
if (a<b) {
edgePair=std::make_pair(a.uidN_,b.uidN_);
}
else {
edgePair=std::make_pair(b.uidN_,a.uidN_);}
//Attempt to insert the new Edge
auto outVals = uidEMap.insert({eHash,next_EdgeID_});
// Occurs if insert is successful
if (outVals.second){
// Save relevant values, used the number of deleted Edges
// to insure that the index is correct
edgeMap[next_EdgeID_]=edgePair;
edgeIndicesRev[next_EdgeID_-1-deletedEdges_]=next_EdgeID_;
next_EdgeID_++;
return Edge(this,next_EdgeID_-1,edgePair.first,edgePair.second);
}
// Occurs if the Edge already exists
else
return Edge(this,uidEMap[eHash], edgePair.first,edgePair.second);
}
/* Hash the unique IDs of two Node objects for use as a key */
// No Boost containers used
// Data structures will be likely refined in later assignments
// to avoid use of Boost here
std::size_t hashNodes(const Node& a, const Node& b) const{
std::size_t edgeHash=0;
if (a.uidN_<b.uidN_){
boost::hash_combine(edgeHash,a.uidN_);
boost::hash_combine(edgeHash,b.uidN_);
}
else{
boost::hash_combine(edgeHash,b.uidN_);
boost::hash_combine(edgeHash,a.uidN_);
}
return edgeHash;
}
/** Remove all nodes and edges from this graph.
* @post num_nodes() == 0 && num_edges() == 0
*
* Invalidates all outstanding Node and Edge objects.
*/
void clear() {
// Update the number of deleted Nodes and Edges
deletedNodes_+=(size_type) nodeMap.size();
deletedEdges_+=(size_type) edgeMap.size();
// All Nodes and Edges are invalidated since their
// unique IDs don't match the Graph's maps.
nodeMap.clear();
edgeMap.clear();
uidEMap.clear();
nodeIndicesRev.clear();
nodeIndices.clear();
edgeIndicesRev.clear();
}
private:
// Use this space for your Graph class's internals:
// helper functions, data members, and so forth.
// ID counters
size_type next_NodeID_;
size_type next_EdgeID_;
// Deletion counters
size_type deletedNodes_;
size_type deletedEdges_;
// unordered_maps for finding needed information in O(1) time
std::unordered_map<size_type,Point> nodeMap;
std::unordered_map<size_type,std::pair<size_type,size_type>> edgeMap;
std::unordered_map<std::size_t,size_type> uidEMap;
std::unordered_map<size_type,size_type> nodeIndicesRev;
std::unordered_map<size_type,size_type> nodeIndices;
std::unordered_map<size_type,size_type> edgeIndicesRev;
};
#endif // CME212_GRAPH_HPP
| true |
14d48a3d3388399d21d21f0543610d8d47de4ab9 | C++ | isaysthat/DrumTriggerModule | /UIArrayElement.h | UTF-8 | 1,148 | 3.109375 | 3 | [] | no_license | /*
UIArrayElement
This class is derived from UIElement. It stores a String and when updateLCD is called will print that String to the rowOccupied.
This element should not be selectable as it does not explicitly override the execute method.
Created by: Justin Read
11/19/2014
*/
#ifndef UIARRAYELEMENT_H
#define UIARRAYELEMENT_H
#include <Arduino.h>
#include "UIElement.h"
#define numPads 6
class UIArrayElement : public UIElement //indicates that this class is derived from UIElement
{
public://allows any class in the project to manipulate it
UIArrayElement(boolean isSelectable,
int row,
void (*inputPrinter)(String,int,int, boolean),
String inputText,
int *inputArray[numPads],
int &inputNumber,
int inputMin,
int inputMax,
int inputStep);
int stepStored;
int execute(int buttonPressed);
void updateLCD();
int *arrayStored[numPads];
int *numberStored;
int minNumber;
int maxNumber;
String displayedText;
void circularIntAdjuster(int adjustment, int lower, int upper);
};
#endif
| true |
c37d0cf4fbe5ed80348926fc7755cae320fd645c | C++ | pacman-project/gaussian-object-modelling | /include/gp/CovThinPlate.h | UTF-8 | 3,255 | 2.859375 | 3 | [] | no_license | /** @file CovThinPlate.h
*
*
* @author Claudio Zito
*
* @copyright Copyright (C) 2015 Claudio, University of Birmingham, UK
*
* @license This file copy is licensed to you under the terms described in
* the License.txt file included in this distribution.
*
* Refer to Gaussian process library for Machine Learning.
*
*/
#ifndef __GP__THINPLATE_H__
#define __GP__THINPLATE_H__
//------------------------------------------------------------------------------
#include "gp/Covs.h"
//------------------------------------------------------------------------------
namespace gp
{
//------------------------------------------------------------------------------
class ThinPlate : public BaseCovFunc
{
public:
/** Pointer to the Covariance function */
typedef boost::shared_ptr<ThinPlate> Ptr;
/** Descriptor file */
class Desc : public BaseCovFunc::Desc {
public:
/** Pointer to description file */
typedef boost::shared_ptr<ThinPlate::Desc> Ptr;
/** Hyper-parameters */
double length;
/** Default C'tor */
Desc() {
setToDefault();
}
/** Set values to default */
void setToDefault() {
BaseCovFunc::Desc::setToDefault();
inputDim = 3;
paramDim = 2;
length = 1.0;
}
/** Creates the object from the description. */
CREATE_FROM_OBJECT_DESC_0(ThinPlate, BaseCovFunc::Ptr)
/** Assert valid descriptor files */
bool isValid(){
if (!std::isfinite(length))
return false;
return true;
}
};
/** Get name of the covariance functions */
virtual std::string getName() const {
return "ThinPlate";
}
/** Compute the kernel */
virtual double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, const bool dirac = false) const {
const double EE = (x1 - x2).squaredNorm();
const double noise = dirac ? sn2 : .0;
return 2 * std::pow(EE, 3.0) - threeLength*pow(EE, 2.0) + length3;
}
//thin plate kernel = 2.*EE.^3 - 3.*(leng).* EE.^2 + (leng*ones(size(EE))).^3
inline double get(const Vec3& x1, const Vec3& x2) const {
const double EE = x1.distance(x2);
return 2*std::pow(EE, 3.0) - threeLength*pow(EE, 2.0) + length3;
}
/** thin plate kernel derivative = 6.*EE.^2 - 6.*(leng).* EE */
inline double getDiff(const Vec3& x1, const Vec3& x2) const {
const double EE = x1.distance(x2);
return 6 * std::pow(EE, 2.0) - 2 * threeLength * EE;
}
/** Update parameter vector.
* @param p new parameter vector */
virtual void setLogHyper(const Eigen::VectorXd &p) {
BaseCovFunc::setLogHyper(p);
threeLength = 3 * loghyper(0);
length3 = std::pow(loghyper(0), 3.0);
sn2 = loghyper(1) * loghyper(1); //2 * loghyper(1) * loghyper(1);//
}
~ThinPlate() {};
private:
/** Hyper-parameters */
double threeLength;
double length3;
/** Create from descriptor */
void create(const Desc& desc) {
BaseCovFunc::create(desc);
loghyper(0) = desc.length;
loghyper(1) = desc.noise;
threeLength = 3 * loghyper(0);
length3 = std::pow(loghyper(0), 3.0);
sn2 = loghyper(1) * loghyper(1); //2 * loghyper(1) * loghyper(1);//
}
ThinPlate() : BaseCovFunc() {}
};
//------------------------------------------------------------------------------
}
#endif
| true |
281a49c186a7031744d94874df139a416603b812 | C++ | fcoury/mechpad | /arduino/pedal/pedal.ino | UTF-8 | 2,289 | 3.15625 | 3 | [] | no_license | const int SWITCH_PIN = 8;
const long HOLD_WAIT = 700;
int clicks = 0;
int switchPressed = 0;
long firstPressed = -1;
long lastPressed;
bool isHeld = false;
void setup() {
Serial.begin(9600);
// sets pin to Input mode and activates the pullup resistor
// since the switch is wired on an active high fashion
pinMode(SWITCH_PIN, INPUT);
digitalWrite(SWITCH_PIN, HIGH);
}
void loop() {
// if the switch is no longer press (active HIGH)
// we can reset the isHeld flag and wait 10 seconds
if (digitalRead(SWITCH_PIN) == HIGH) {
isHeld = false;
delay(10);
}
// if the switch is held we don't need to detect
// clicks because it already handled the hold
if (isHeld) {
return;
}
// if the switch is pressed, turn on the flag
// and captures the time it was first pressed (regardless of check cycle)
// and when it was last pressed (within this press cycle)
if (digitalRead(SWITCH_PIN) == LOW) {
switchPressed = 1;
if (firstPressed == -1) {
firstPressed = millis();
}
lastPressed = millis();
}
// how long ago it was pressed on this 250ms cycle
long difference = millis() - lastPressed;
if (switchPressed == 1) {
// takes 50ms to consider a click
if (difference > 50) {
clicks++;
switchPressed = 0;
}
}
// how long ago it was pressed, regardless of the cycle
long firstDiff = millis() - firstPressed;
// if it was pressed 250ms ago or if we're holding it enough
// to consider it a hold
if (difference > 250 || firstDiff > HOLD_WAIT) {
// if it was pressed for longer then the time to consider a hold
if (firstPressed > -1 && firstDiff > HOLD_WAIT) {
// reset the press flag and click counter
switchPressed = 0;
clicks = 0;
// indicates we have a hold, and set the held flag
Serial.println("Hold");
isHeld = true;
} else {
// otherwise, if we had only one click within the cycle
if (clicks == 1) {
// consider it a Click
Serial.println("Click");
} else if (clicks == 2) {
// if we had 2, consider it a double click
Serial.println("DblClick");
}
}
// resets the click counter and the time when it was initially pressed
clicks = 0;
firstPressed = -1;
}
}
| true |
d8d642c0126c6184dc0c95b0f29bc6ce060911d7 | C++ | noahdelongpre/CS3331-ConcurrentComputing | /Program 5: Missionaries and Cannibals (Monitors)/boat-monitor.cpp | UTF-8 | 9,387 | 2.984375 | 3 | [] | no_license | //--------------------------------------------------------
// NAME: Noah de Longpre' User ID: nkdelong
// DUE DATE: 12/8/2017
// PROGRAM ASSIGNMENT 5
// FILE NAME: boat-monitor.cpp
// PROGRAM PURPOSE:
// Boat-monitor.cpp is the brains of the whole boat operation happens.
// This controls the Cannibals and Missionaries that get on the boat,
// as well as when the boat is ready and when it is done.
// This .cpp implements the blueprints laid out in the boat-monitor.h
// header file also submitted with this program.
//---------------------------------------------------------
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "thread.h"
#include <time.h>
//----------------------------------------------------
//FUNCTION: BoatMonitor
// This is the constructor for the boat monitor,
// it saves all of the information laid out in the header file
// to actual locations in memory for it to be used during runtime.
//PARAMETER USEAGE:
// loads: Originally the max number of loads the boat has to do.
//FUNCTION CALLED:
// None / N/A
//-----------------------------------------------------
BoatMonitor::BoatMonitor(int loads) : Monitor("Boat", HOARE) //BoatMonitor *boaty
{
//boat = boaty; //Pointer to the boat Monitor.
waiting = 0; //How many total people are waiting
onBoat =0; //How many are on the boat already
isBoatReady = 1; //Yes its Ready
canWait = 0; //Cannibals waiting
misWait = 0; //Missionaries waiting
Riding = new Condition("Riding");
BoatWaiting = new Condition("BoatWait");
CannibalHere = new Condition("CanHere");
MissionaryHere = new Condition("MisHere");
char types[3];
int boarding[3];
}
//---------------------------------------------------------
//FUCNTION BoatReady
// This function is the first monitor function that the boat thread runs.
// The function checks in a while loop if there exists a correct
// boat load of people to cross the river.
// If one exists, the boat releases the waiting people, and runs the boat.
//PARAMETER USAGE:
// currentLoad: Is passed from the boat thread, on what the current load
// is, and is meant for printing from the monitor.
//FUNCTION CALLED:
// PickThree(currentLoad)
// It passes the currentLoad to another function that checks
// a random sequence to see if a correct boat load exists.
//-------------------------------------------------------
void BoatMonitor::BoatReady(int currentLoad)
{
MonitorBegin();
char buf[1000];
int picked = 0;
int counter = 0;
while(1){
picked = PickThree(currentLoad);
//printf("************************What is picked: %d \n", picked);
if(picked == 1)
{
counter = 0;
break;
}
if(counter > 10)
{
counter = 0;
MonitorEnd();
MonitorBegin();
}
//printf("Counter = %d \n", counter);
counter++;
}
//PickThree(currentLoad);
if(onBoat < 3)
{
isBoatReady = 1; //Still ready to load
BoatWaiting->Wait();
}
isBoatReady = 0; //Boat is full, and is not ready to load
sprintf(buf, "***** Boat Load(%d): Passenger list (%c%d, %c%d, %c%d)\n", currentLoad +1, types[0], boarding[0], types[1], boarding[1], types[2], boarding[2]);
write(1, buf, strlen(buf));
MonitorEnd();
}
//---------------------------------------------------------------------
//FUNCTION BoatDone:
// This runs when the boat has finished its ride across the river
// and kicks everyone that was on the boat, off the boat.
//PARAMETER USEAGE:
// N/A, no parameters
//FUNCTION CALLED:
// N/A, no custom functions called.
//-------------------------------------------------------------------
void BoatMonitor::BoatDone()
{
MonitorBegin();
for(int i = 0 ; i< 3 ; i++)
Riding->Signal(); //Kick everyone currently on the boat, off.
MonitorEnd();
}
//-----------------------------------------------------------------
//FUNCTON CannibalArrives:
// This runs when the cannibal thread is ready to board the boat.
// He comes in, waits, and is released when the boat has
// a correct number of people to form a safe boat load over the river.
//PARAMETER USEAGE:
// who: The cannibal thread passes its number down so that it may be printed.
// For example, if cannibal 4 arrives, it needs to pass '4' down so it may be
// printed inside the monitor.
//FUCNTION CALLED:
// N/A, no custom functions called.
//---------------------------------------------------------------
void BoatMonitor::CannibalArrives(int who)
{
//who is the number of which cannibal arrived.
MonitorBegin();
char space[100];
char buf[1000];
strcpy(space, "");
for(int i = 0; i < who ; i++)
strcat(space, " "); //Load space with the spaces for this cannibal
sprintf(buf, "%s Cannibal %d arrives\n", space, who);
write(1, buf, strlen(buf));
waiting++; //I'm now waiting
canWait++; //I'm also a cannibal waiting
//printf("mis wait = %d \n can wait = %d \n waiting = %d \n", misWait, canWait, waiting);
CannibalHere->Wait(); //Wait for someone to let me go
waiting--; //No longer waiting
canWait--; //No longer a cannibal waiting
onBoat++; //I'm now getting on the boat
//printf("onBoat? = %d \n", onBoat);
//Testing to see which member of the boat I am.
if(onBoat == 1)
{
types[0] = 'c'; //I'm a cannibal getting in the first spot in the boat
boarding[0] = who; //What cannibal am I?
}
if(onBoat == 2)
{
types[1] = 'c'; //Cannibal taking the second spot
boarding[1] = who;
}
if(onBoat == 3) //Last person to get on the boat
{
types[2] = 'c'; //Cannibal taking the third spot.
boarding[2] = who;
BoatWaiting->Signal(); //Telling the boat to go
}
Riding->Wait(); //All processes wait here while the boat rides across
onBoat--; //Each Can or Mis will lower this as they get off the boat
MonitorEnd(); //Leave and continue
}
//-----------------------------------------------------------------------------
//FUNCTION MissionaryArrives:
// Works exactly like Cannibal arrives, only with the other type of
// passenger, the Missionary. Waits until the boat releases it when
// a safe boat trip exists.
//PARAMETER USEAGE:
// who: Which number thread is this Missionary, passed down from that
// missionary thread.
//FUCNTION CALLED:
// N/A, no custom function called.
//-----------------------------------------------------------------------------
void BoatMonitor::MissionaryArrives(int who)
{
MonitorBegin();
char space[100];
char buf[1000];
strcpy(space, "");
for(int i = 0 ; i < who ; i++)
strcat(space, " ");
sprintf(buf, "%s Missionary %d arrives\n", space, who);
write(1, buf, strlen(buf));
//Gotta wait
waiting++;
misWait++;
//printf("mis wait = %d \n can wait = %d \n waiting = %d \n", misWait, canWait, waiting);
MissionaryHere->Wait();
//Done waiting, someone released me
waiting--;
misWait--;
onBoat++; //Got on the boat
//printf("onBoat? = %d \n", onBoat);
if(onBoat == 1) //First one on
{
types[0] = 'm';
boarding[0] = who;
}
if(onBoat == 2)//Second one on
{
types[1] = 'm';
boarding[1] = who;
}
if(onBoat == 3)//Third one on
{
types[2] = 'm';
boarding[2] = who;
BoatWaiting->Signal();
}
Riding->Wait();
onBoat--;
MonitorEnd();
}
//-----------------------------------------------------------------------------
//FUNCTION PickThree:
// A custom function made to pick three people to get on the boat.
// It starts with a random number between 0 and 2. Based on which one,
// it checks one of the 3 safe boat rides. By making it random, it
// doesn't always check the same boat ride every time, which would make
// one boat more likely than the others.
//PARAMETER USEAGE:
// l : currentLoad passed to this so it can print things from the MONITOR.
//FUNCTION CALLED:
// rand()
//-----------------------------------------------------------------------------
int BoatMonitor::PickThree(int l)
{ //Randomly pick 3 people who are waiting and try to board
int rando = rand() % 3;
char buf[100];
int temp;
if(onBoat > 2)
return 1;
for(int i = 0 ; i < 3 ; i++)
{ //Checks through all three boat situations
if(rando == 0) //3 cannibals
{
if(canWait >= 3)
{
CannibalHere->Signal();
CannibalHere->Signal();
CannibalHere->Signal();
sprintf(buf, "MONITOR(%d): 3 Cannibals are selected.\n", l+1);
write(1, buf, strlen(buf));
return 1; //Don't continue the loop, you found the boat.
}
}
else if(rando == 1) //3 missionaries
{
if(misWait >= 3) //If more than two missionaries are waiting
{
MissionaryHere->Signal();
MissionaryHere->Signal();
MissionaryHere->Signal();
sprintf(buf, "MONITOR(%d): 3 Missionaries are selected.\n", l+1);
write(1, buf, strlen(buf));
return 1; //Don't continue the loop, you found the boat.
}
}
else if(rando == 2) //2 Missionaries and a Cannibal
{
if(misWait >= 2 && canWait >= 1) //If the correct amount is waiting
{
MissionaryHere->Signal();
MissionaryHere->Signal();
CannibalHere->Signal();
sprintf(buf, "MONITOR(%d): 2 Missionaries and a Cannibal are selected.\n", l+1);
write(1, buf, strlen(buf));
return 1; //Don't continue the loop, you found the boat.
}
}
//If the one rando happened to be also wasn't true, pick a new rando and go.
rando = (rando + 1) % 3; // This way it increments through 3 options in a different order
//Based on the first number.
}
return 0;
}
| true |
a22e27c0d430c448de19d38c9247ae772a32d807 | C++ | OzkanTopcan/Open_Ruche | /main.cpp | UTF-8 | 7,095 | 2.609375 | 3 | [] | no_license | /*--------------Librairies--------------*/
#include "mbed.h"
#include "platform/mbed_thread.h"
#include "DHT22.h"
#include "DS1820.h"
#include "Anemometer.h"
#include "HX711.h"
#include "message_1.h"
/*---------Prototypes fonctions---------*/
bool MesureDHT22();
bool MesureDS18B20();
bool MesureLumi();
bool MesureDirection();
bool MesureVitesse();
bool MesurePoids();
void MesureGlobale();
void ClignotterLed();
/*----------Variables globales----------*/
static float tempDHT;
static float humDHT;
static float tempDSB;
static float Direction;
static float Vitesse;
static float Lumi;
static float weight;
static float calibration_factor = 14200;
static int averageSamples = 10;
/*------------Flag capteurs-------------*/
static bool flagDHT22;
static bool flagDS18B20;
static bool flagDirection;
static bool flagVitesse;
static bool flagLumi;
static bool flagPoids;
/*------------Configurations------------*/
Serial device(PA_9, PA_10);
DHT22 sensorDHT22(PA_11);
DS1820 sensorDS1820(PA_8);
AnalogIn ain(PA_6);
AnalogIn sensorGirouette(PA_1);
CAnemometer sensorAnemo(PB_0, 1000);
DigitalOut gpo(PA_12);
AnalogIn scaleRaw(PA_4);
HX711 scale(PA_4, PA_12);
DigitalOut led(LED1);
/*------------Code principal------------*/
int main()
{
ClignotterLed();
scale.setScale(3000);
scale.tare();
scale.setOffset(1);
while(true) {
MesureGlobale();
//Message_1 msg1(tempDHT, tempDSB, 6.4, (Lumi)/10, 54, humDHT, 5.0); // instanciation du corps du message avec les données à envoyer
Message_1 msg1(tempDHT, tempDSB, Vitesse, (Lumi)/10, weight, humDHT, Direction); // instanciation du corps du message avec les données à envoyer
//Message_1 msg1(25.2, 25.3, 5.4, (2605)/10, 40.6, 50.2, 5.0); // instanciation du corps du message avec les données à envoyer
msg1.send();
ClignotterLed();
printf("message envoyé \r\n");
wait(720);
}
}
/*--------Definitions fonctions---------*/
void ClignotterLed(){
led = 1;
int i = 0;
for ( i = 0 ; i < 3 ; i++){
if(led == 1)
{
led =! led ;
wait(0.2);
}
}
void MesureGlobale(){
printf("\n\r+++++++++++Mesure Globale++++++++++++\n\r");
printf("\n\r----------------DHT22----------------\n\r");
flagDHT22 = MesureDHT22();
if (flagDHT22 == false){
wait(1);
flagDHT22 = MesureDHT22();
}
printf("\n\r---------------DS18B20---------------\n\r");
flagDS18B20 = MesureDS18B20();
if (flagDS18B20 == false){
flagDS18B20 = MesureDS18B20();
}
printf("\n\r--------------Direction--------------\n\r");
flagDirection = MesureDirection();
if (flagDirection == false){
wait(1);
flagDirection = MesureDirection();
}
printf("\n\r---------------Vitesse---------------\n\r");
flagVitesse = MesureVitesse();
if (flagVitesse == false){
flagVitesse = MesureVitesse();
}
printf("\n\r-------------Luminositée-------------\n\r");
flagLumi = MesureLumi();
if (flagLumi == false){
flagLumi = MesureLumi();
}
printf("\n\r----------------Poids----------------\n\r");
flagPoids = MesurePoids();
}
bool MesureDHT22() {
bool boule;
boule = sensorDHT22.sample();
if (boule) {
tempDHT = ((float)(sensorDHT22.getTemperature()))/10;
humDHT = ((float)(sensorDHT22.getHumidity()))/10;
printf("Température : %.2f \r\nHumiditée : %.2f \r\n" , tempDHT, humDHT);
return true;
}
else {
printf("DHT22 non détecté \r\n");
return false;
}
}
bool MesureDS18B20() {
int result = 0;
bool test = sensorDS1820.begin();
if (1) {
sensorDS1820.startConversion(); // start temperature conversion from analog to digital
wait(1); // let DS1820 complete the temperature conversion
result = sensorDS1820.read(tempDSB); // read temperature from DS1820 and perform cyclic redundancy check (CRC)
switch (result) {
case 0: // no errors -> 'temp' contains the value of measured temperature
printf("Température = %3.1f%°C \r\n", tempDSB);
return true;
case 1: // no sensor present -> 'temp' is not updated
printf("no sensor present \n\r");
return false;
case 2: // CRC error -> 'temp' is not updated
printf("CRC error\r\n");
return false;
}
}
else {
printf("DS18B20 non détecté \r\n");
return false;
}
return false;
}
bool MesureLumi() {
Lumi = (int)(8.606*exp(2.1*(ain.read()*3.3)));
printf("Luminosité = %3.1f Lux \r\n", Lumi);
return true;
}
bool MesureDirection(){
float Girouette = 0;
Girouette = (float)sensorGirouette.read()*100;
if ( Girouette >= 85 && Girouette <=86.99 ){
Direction = 0;
printf("Le vent souffle au nord \r\n");
return true;
}
if ( Girouette >= 72 && Girouette <=73.99 ){
Direction = 7;
printf("Le vent souffle au nord-ouest \r\n");
return true;
}
if ( Girouette >= 78 && Girouette <=79.99 ){
Direction = 1;
printf("Le vent souffle au nord-est \r\n");
return true;
}
if ( Girouette >= 90 && Girouette <=91.99 ){
Direction = 4;
printf("Le vent souffle au sud \r\n");
return true;
}
if ( Girouette >= 83 && Girouette <=84.99 ){
Direction = 3;
printf("Le vent souffle au sud-est \r\n");
return true;
}
if ( Girouette >= 76 && Girouette <=77.99 ){
Direction = 5;
printf("Le vent souffle au sud-ouest \r\n");
return true;
}
if ( Girouette >= 88 && Girouette <=89.99 ){
Direction = 2;
printf("Le vent souffle à l'est \r\n");
return true;
}
if ( Girouette >= 81 && Girouette <=82.99 ){
Direction = 6;
printf("Le vent souffle à l'ouest\r\n");
return true;
}
printf("girouette non détectée \r\n");
return false;
}
bool MesureVitesse(){
float somme = 0 ;
int j;
for ( j = 0; j < 100000; j++){
somme += sensorAnemo.GetCurrentWindSpeed();
}
somme /= 100000;
Vitesse = somme;
if (somme == 0){
printf("Pas de vent détecté \r\n");
return false;
}
printf("Vitesse du vent = %f m/s \r\n", Vitesse);
return true;
}
bool MesurePoids(){
scale.setScale(calibration_factor);
weight = scale.getGram()+43.9;
printf("Poids = %f kg \n\r",weight);
return true;
}
| true |
f526f5cd6ef6725405c913e325384eb981b49888 | C++ | vshymanskyy/O_oRT | /src/Core/File.h | UTF-8 | 2,998 | 3.21875 | 3 | [] | no_license | #pragma once
class File{
private:
FILE* mFile;
const char* mName;
bool mWrite, mOpened;
void Close() {
assert(mOpened);
mOpened = false;
fclose(mFile);
}
void Open() {
const char* mode = (mWrite)? "w+" : "r";
mFile = fopen(mName, mode);
mOpened = (mFile!=NULL);
assert(mOpened);
}
public:
File(const char* name, bool write = false)
: mName(name)
, mWrite(write)
{
Open();
}
~File() {
Close();
}
char* GetPath() {
const char* p_slash = strrchr(mName,'\\');
const ptrdiff_t count = p_slash-mName+1;
char* result = new char[count+1];
strncpy(result, mName, count);
result[count] = '\0';
return result;
}
char* GetName() {
const char* p_slash = strrchr(mName,'\\');
const char* p_dot = strrchr(mName,'.');
assert(p_dot>p_slash);
const ptrdiff_t count = p_dot-p_slash-1;
char* result = new char[count+1];
strncpy(result, p_slash+1, count);
result[count] = '\0';
return result;
}
char* GetExtension() {
const char* p_dot = strrchr(mName,'.');
const char* last = mName + strlen(mName);
const ptrdiff_t count = last-p_dot;
char* result = new char[count+1];
strncpy(result, p_dot+1, count);
result[count] = '\0';
return result;
}
int GetPosition() {
return ftell(mFile);
}
void SetPosition(int p) {
fseek(mFile, p, SEEK_SET);
}
void SetPositionDelta(int p) {
fseek(mFile, p, SEEK_CUR);
}
void SetPositionEnd(int p) {
fseek(mFile, p, SEEK_END);
}
int GetSize() {
const int current = GetPosition();
SetPositionEnd(0);
const int result = GetPosition();
SetPosition(current);
return result;
}
bool EoF() {
assert(mOpened);
return feof(mFile)?true:false;
}
real ReadFloat() {
assert(mOpened);
float val;
fscanf(mFile, "%f", &val);
return (real)val;
}
real ReadDouble() {
assert(mOpened);
double val;
fscanf(mFile, "%lf", &val);
return (real)val;
}
int ReadInt() {
assert(mOpened);
int val;
fscanf(mFile, "%d", &val);
return val;
}
char* ReadUntilAnyOf(const char* chars) {
assert(mOpened);
char* result = new char[1024];
char* ptr = result;
int c ;
while (!strchr(chars, c = fgetc(mFile))) {
*(ptr++) = c;
};
*ptr = '\0';
return result;
}
char* ReadWord() {
return ReadUntilAnyOf(" \t\n");
}
char* ReadLine() {
assert(mOpened);
char* result = new char[1024];
fgets(result,1023,mFile);
result[strlen(result)-1] = '\0';
return result;
}
void Write(const char* s) {
assert(mOpened);
assert(mWrite);
fputs(s, mFile);
}
void WriteLine(const char* s = "") {
assert(mOpened);
assert(mWrite);
fputs(s, mFile);
fputs("\n", mFile);
}
void WriteFloat(float val) {
assert(mOpened);
assert(mWrite);
fprintf(mFile, "%f", val);
}
void WriteInt(int val) {
assert(mOpened);
assert(mWrite);
fprintf(mFile, "%d", val);
}
};
| true |
10c0daa6841acbf763ece68b1bfb566f94eb324c | C++ | yefim/cis190 | /hw4/test.cpp | UTF-8 | 612 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "bigint.h"
using namespace std;
int main()
{
bool test[11];
BigInt a;
BigInt b(1);
BigInt c(1L);
BigInt d(a);
// unary
test[0] = a == +a;
test[1] = a == -a;
// arithmetic
test[2] = a + b == b;
test[3] = a - b == -b;
test[4] = a * b == a;
// assignment
a = BigInt(10);
test[5] = a == BigInt(10);
// comparisons
test[6] = a > b;
test[7] = a >= b;
test[8] = b < a;
test[9] = b <= a;
// conversions
test[10] = (int)a == 10;
for (int i = 0; i < 11; i++)
{
cout << i << ": " << test[i] << endl;
}
return 0;
}
| true |
928a49f8605a71b1965e5ae3c1a8d434c5b65cb1 | C++ | brliron/135tk | /th145arc/TFPKArchive.cpp | UTF-8 | 12,234 | 2.734375 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <unordered_map>
#include <list>
#include <forward_list>
#include <random>
#include <ctype.h>
#include "tasofroCrypt.h"
#include "TFPKArchive.h"
BOOL CreateDirectoryForPath(wchar_t* Path)
{
BOOL result = FALSE;
unsigned int length = wcslen(Path);
for(unsigned int i = 0; i < length; i++)
{
if(Path[i] == L'\\' || Path[i] == L'/')
{
Path[i] = 0;
result = CreateDirectoryW(Path,NULL);
Path[i] = L'\\';
}
}
return result;
}
// Normalized Hash
DWORD SpecialFNVHash(char *begin, char *end, DWORD initHash=0x811C9DC5u)
{
DWORD hash; // eax@1
DWORD ch; // esi@2
int inMBCS = 0;
for ( hash = initHash; begin != end; hash = (hash ^ ch) * 0x1000193 )
{
ch = *begin++;
if(!inMBCS && ( (unsigned char)ch >= 0x81u && (unsigned char)ch <= 0x9Fu || (unsigned char)ch+32 <= 0x1Fu )) inMBCS = 2;
if(!inMBCS)
{
ch = tolower(ch); // bad ass style but WORKS PERFECTLY!
if(ch == '/') ch = '\\';
}
else inMBCS--;
}
return hash * -1;
}
std::unordered_map<DWORD,std::string> fileHashToName;
int LoadFileNameList(const char* FileName)
{
FILE* fp = fopen(FileName,"rt");
if(!fp) return -1;
char FilePath[MAX_PATH] = {0};
while(fgets(FilePath,MAX_PATH,fp))
{
int tlen = strlen(FilePath);
while(tlen && FilePath[tlen-1] == '\n') FilePath[--tlen] = 0;
DWORD thash = SpecialFNVHash(FilePath,FilePath+tlen);
fileHashToName[thash] = FilePath;
}
fclose(fp);
return 0;
}
void UncryptBlock(BYTE* Data,DWORD FileSize,DWORD* Key)
{
BYTE* key = (BYTE*)Key;
BYTE aux[4];
for (int i = 0; i < 4; i++)
aux[i] = key[i];
for (DWORD i = 0; i < FileSize; i++)
{
BYTE tmp = Data[i];
Data[i] = Data[i] ^ key[i % 16] ^ aux[i % 4];
aux[i % 4] = tmp;
}
}
DWORD CryptBlock(BYTE* Data, DWORD FileSize, DWORD* Key, DWORD Aux)
{
BYTE* key = (BYTE*)Key;
BYTE* aux = (BYTE*)&Aux;
for (int i = FileSize - 1; i >= 0; i--)
{
BYTE unencByte = Data[i];
BYTE encByte = aux[i % 4];
Data[i] = aux[i % 4];
aux[i % 4] = unencByte ^ encByte ^ key[i % 16];
}
return Aux;
}
DWORD CryptBlock(BYTE* Data, DWORD FileSize, DWORD* Key)
{
DWORD Aux;
BYTE* tempCopy = new BYTE[FileSize];
memcpy(tempCopy, Data, FileSize);
Aux = CryptBlock(tempCopy, FileSize, Key, Key[0]); // This call seems to give the correct Aux value.
delete[] tempCopy;
return CryptBlock(Data, FileSize, Key, Aux);
}
struct MapStruct
{
HANDLE hFile;
HANDLE hMapping;
BYTE* pFile;
};
BYTE* map(const char* FileName, size_t size, MapStruct& mapStruct)
{
if (size == 0)
{
mapStruct.hFile = CreateFileA(FileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS,NULL);
mapStruct.hMapping = CreateFileMapping(mapStruct.hFile,NULL,PAGE_READONLY,0,GetFileSize(mapStruct.hFile,NULL),NULL);
mapStruct.pFile = (BYTE*)MapViewOfFile(mapStruct.hMapping,FILE_MAP_READ,0,0,0);
}
else
{
mapStruct.hFile = CreateFileA(FileName,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_FLAG_RANDOM_ACCESS,NULL);
mapStruct.hMapping = CreateFileMapping(mapStruct.hFile,NULL,PAGE_READWRITE,0,size,NULL);
mapStruct.pFile = (BYTE*)MapViewOfFile(mapStruct.hMapping,FILE_MAP_READ | FILE_MAP_WRITE,0,0,0);
}
if (mapStruct.hFile == INVALID_HANDLE_VALUE || mapStruct.hMapping == INVALID_HANDLE_VALUE || !mapStruct.pFile)
return 0;
return mapStruct.pFile;
}
void unmap(MapStruct& mapStruct)
{
UnmapViewOfFile(mapStruct.pFile);
CloseHandle(mapStruct.hMapping);
CloseHandle(mapStruct.hFile);
}
const wchar_t* guess_extension(const BYTE* bytes, size_t size)
{
const char* cbytes = (const char*)bytes; // for strcmp
if (size >= 73 && memcmp(cbytes, "#========================================================================", 73) == 0)
return L".pl";
if (size >= 12 && memcmp(cbytes, "RIFF", 4) == 0 && memcmp(cbytes + 8, "SFPL", 4) == 0)
return L".sfl";
if (size >= 6 && memcmp(cbytes, "\xFA\xFARIQS", 6) == 0)
return L".nut";
if (size >= 4 && memcmp(cbytes, "TFBM", 4) == 0)
return L".png";
if (size >= 4 && memcmp(cbytes, "\x89PNG", 4) == 0)
return L".png";
if (size >= 4 && memcmp(cbytes, "TFCS", 4) == 0)
return L".csv";
if (size >= 4 && memcmp(cbytes, "DDS ", 4) == 0)
return L".dds";
if (size >= 4 && memcmp(cbytes, "OggS", 4) == 0)
return L".ogg";
if (size >= 4 && memcmp(cbytes, "eft$", 4) == 0)
return L".eft";
if (size >= 4 && memcmp(cbytes, "TFWA", 4) == 0)
return L".wav";
if (size >= 4 && memcmp(cbytes, "TFPA", 4) == 0)
return L".bmp";
if (size >= 4 && memcmp(cbytes, "IBMB", 4) == 0)
return L".bmb";
if (size >= 4 && memcmp(cbytes, "MZ", 4) == 0)
return L".dll";
if (size >= 1 && bytes[0] == 17)
return L".pat";
return nullptr;
}
int ExtractAll(const char* ArchiveFileName,const char* OutputFolder)
{
MapStruct mapStruct;
BYTE* pPackage = map(ArchiveFileName, 0, mapStruct);
if(pPackage == NULL)
return 0;
DWORD Magic = *(DWORD*)pPackage;
if(Magic != 'KPFT')
{
printf("Error: the given file isn't a TFPK archive.\n");
return 0;
}
if (pPackage[4] != 1)
{
printf("Error: this tool works only with Touhou 14.5 and Touhou 15.5 archives.\n");
return 0;
}
DWORD cur = 5;
DWORD DirCount = 0;
Decrypt6432(pPackage+cur,(BYTE*)&DirCount,sizeof(DWORD));
cur += KEY_BYTESIZE;
// Ignore the dirlist if there is one
cur += DirCount * KEY_BYTESIZE;
if (DirCount > 0)
{
FNHEADER fnh;
Decrypt6432(pPackage+cur,(BYTE*)&fnh,sizeof(FNHEADER));
cur += KEY_BYTESIZE;
cur += fnh.BlockCnt * KEY_BYTESIZE; // Ignore the compressed files names list
}
LISTHEADER lh;
memset(&lh,0,sizeof(LISTHEADER));
Decrypt6432(pPackage+cur,(BYTE*)&lh,4);
cur += KEY_BYTESIZE;
TFPKLIST* FileList = new TFPKLIST[lh.FileCount];
memset(FileList,0,sizeof(TFPKLIST)*lh.FileCount);
for(DWORD i = 0;i < lh.FileCount;i++)
{
LISTITEM li;
Decrypt6432(pPackage+cur,(BYTE*)&li,sizeof(LISTITEM));
cur += KEY_BYTESIZE;
DWORD hash[2];
Decrypt6432(pPackage+cur,(BYTE*)hash,sizeof(DWORD) * 2);
FileList[i].NameHash = hash[0];
// hash[1] seems ignored.
cur += KEY_BYTESIZE;
Decrypt6432(pPackage+cur,(BYTE*)FileList[i].Key,sizeof(DWORD)*4);
cur += KEY_BYTESIZE;
FileList[i].Offset = li.Offset;
FileList[i].FileSize = li.FileSize;
FileList[i].FileSize ^= FileList[i].Key[0];
FileList[i].Offset ^= FileList[i].Key[1];
FileList[i].NameHash ^= FileList[i].Key[2];
for (int j = 0; j < 4; j++)
FileList[i].Key[j] *= -1; // GCC doesn't emit a warning for this ? Ok, fine.
try
{
FileList[i].FileName = (char*)fileHashToName.at(FileList[i].NameHash).c_str();
}
catch (...)
{
char* path = new char[13];
sprintf(path, "unk_%08lX", FileList[i].NameHash);
FileList[i].FileName = path;
}
}
DWORD FileBeginOffset = cur;
for(DWORD i = 0;i < lh.FileCount;i++)
{
BYTE* Data = new BYTE[FileList[i].FileSize+100];
memcpy(Data,pPackage+FileBeginOffset+FileList[i].Offset,FileList[i].FileSize);
UncryptBlock(Data,FileList[i].FileSize,FileList[i].Key);
char PathName[MAX_PATH] = {0};
sprintf(PathName,"%s\\%s",OutputFolder,FileList[i].FileName);
wchar_t unicodeName[MAX_PATH];
if (MultiByteToWideChar(932, MB_ERR_INVALID_CHARS, PathName, -1, unicodeName, MAX_PATH) == 0)
{
printf("Shift-JIS to Unicode conversion of %s failed (error %lu). Fallback to ASCII to Unicode conversion.\n", PathName, GetLastError());
for (int i = 0; i == 0 || PathName[i - 1]; i++)
unicodeName[i] = PathName[i];
}
if (strncmp(FileList[i].FileName, "unk_", 4) == 0)
{
const wchar_t *ext = guess_extension(Data, FileList[i].FileSize);
if (ext)
wcscat(unicodeName, ext);
}
CreateDirectoryForPath(unicodeName);
FILE* fp;
fp = _wfopen(unicodeName, L"wb");
fwrite(Data, FileList[i].FileSize, 1, fp);
delete[] Data;
fclose(fp);
printf("%lu%%\r", i * 100 / lh.FileCount);
}
delete[] FileList;
unmap(mapStruct);
return 1;
}
int BuildList(const wchar_t* BasePath, const wchar_t* Path, std::list<TFPKLIST>& FileList)
{
wchar_t FindPath[MAX_PATH] = {0};
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA FindData;
swprintf(FindPath,L"%S\\%S\\*.*", BasePath, Path);
hFind = FindFirstFile(FindPath,&FindData);
if(hFind == INVALID_HANDLE_VALUE) return -1;
int FileCount = 0;
do
{
if(wcscmp(FindData.cFileName,L".") == 0 || wcscmp(FindData.cFileName,L"..") == 0) continue;
if(FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
wchar_t NPath[MAX_PATH] = {0};
if (Path[0] == L'\0')
swprintf(NPath,L"%S",FindData.cFileName);
else
swprintf(NPath,L"%S\\%S",Path,FindData.cFileName);
BuildList(BasePath,NPath,FileList);
}
else
{
FileCount++;
wchar_t* PathName = new wchar_t[MAX_PATH];
swprintf(PathName, L"%S\\%S\\%S", BasePath, Path, FindData.cFileName);
char* FName = new char[MAX_PATH];
DWORD hash = 0;
if (Path[0] == L'\0')
{
if (wcsncmp(FindData.cFileName, L"unk_", 4) != 0)
sprintf(FName, "%S", FindData.cFileName);
else
swscanf(FindData.cFileName, L"unk_%08X", &hash);
}
else
sprintf(FName, "%S\\%S", Path, FindData.cFileName);
int len = strlen(FName);
TFPKLIST item;
memset(&item,0,sizeof(TFPKLIST));
item.Path = PathName;
item.FileName = FName;
if (hash != 0)
item.NameHash = hash;
else
item.NameHash = SpecialFNVHash(FName,FName+len);
FileList.push_front(item);
}
} while(FindNextFile(hFind,&FindData));
return 0;
}
int BuildArchive(const wchar_t* ArchiveFileName,const wchar_t* InputFolder)
{
std::list<TFPKLIST> FileList;
wprintf(L"Scanning files...");
BuildList(InputFolder, L"", FileList);
wprintf(L"Done.\nCalculating necessary metainfo...");
DWORD Offset = 0;
LISTHEADER lh;
memset(&lh,0,sizeof(LISTHEADER));
for(auto& it: FileList)
{
lh.FileCount++;
for(int i = 0;i < 4;i++) it.Key[i] = 0;
it.Offset = Offset;
HANDLE hFile = CreateFile(it.Path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
it.FileSize = GetFileSize(hFile,NULL);
CloseHandle(hFile);
Offset += it.FileSize;
}
DWORD PackageSize = 5 + 1*KEY_BYTESIZE + (1+lh.FileCount*3)*KEY_BYTESIZE + Offset;
wprintf(L"Done!\nWill generate a package file with %d files.\n",lh.FileCount);
wprintf(L"Generating encrypted file list...");
HANDLE hOutFile = CreateFile(ArchiveFileName,GENERIC_WRITE | GENERIC_READ,FILE_SHARE_WRITE | FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);
HANDLE hFileMapping = CreateFileMapping(hOutFile,NULL,PAGE_READWRITE,0,PackageSize,NULL);
BYTE* pPackage = (BYTE*)MapViewOfFile(hFileMapping,FILE_MAP_READ | FILE_MAP_WRITE,0,0,PackageSize);
*(DWORD*) pPackage = 'KPFT'; // Magic
pPackage[4] = 1;
DWORD cur = 5;
DWORD DirCount = 0;
Encrypt3264((BYTE*)&DirCount,pPackage+cur,sizeof(DWORD)); cur += KEY_BYTESIZE;
Encrypt3264((BYTE*)&lh,pPackage+cur,4); cur += KEY_BYTESIZE;
for(auto& it: FileList)
{
LISTITEM li;
li.Offset = it.Offset; li.FileSize = it.FileSize;
Encrypt3264((BYTE*)&li,pPackage+cur,sizeof(LISTITEM)); cur += KEY_BYTESIZE;
DWORD hash[2]; hash[0] = it.NameHash; hash[1] = 0;
Encrypt3264((BYTE*)hash,pPackage+cur,sizeof(DWORD)*2); cur += KEY_BYTESIZE;
Encrypt3264((BYTE*)&it.Key,pPackage+cur,sizeof(it.Key)); cur += KEY_BYTESIZE;
}
wprintf(L"Done.\nCopying files...\n");
int for_i = 0, for_max = FileList.size();
for(auto& it: FileList)
{
DWORD ReadBytes = 0;
HANDLE hIn = CreateFile(it.Path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
ReadFile(hIn,pPackage+cur,it.FileSize,&ReadBytes,NULL);
CloseHandle(hIn);
CryptBlock(pPackage+cur,it.FileSize,it.Key);
cur += it.FileSize;
printf("%d%%\r", for_i * 100 / for_max);
for_i++;
}
UnmapViewOfFile(pPackage);
CloseHandle(hFileMapping);
CloseHandle(hOutFile);
return 1;
}
| true |
590d2bfea846cd75f857a7b4ea0518a196ee1da0 | C++ | VaibhavVerma16113108/A2OJ-Ladders-Div2.A | /Watermelon.cpp | UTF-8 | 212 | 2.53125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
if(n&1 or n==2)
cout << "NO" << endl;
else
cout << "YES" << endl;
return 0;
} | true |
1f9e83f59c90242ada905d599b76994e061daf7c | C++ | mhk1436658453/Connect4 | /constant.h | UTF-8 | 2,048 | 2.703125 | 3 | [] | no_license | #ifndef CONSTANTS_H
#define CONSTANTS_H
#include <iostream>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::cin;
using namespace std::string_view_literals;
namespace constants
{
constexpr int b_h{ 6 }; // board height
constexpr int b_w{ 7 }; // board width
constexpr char empty_chess{ '_' }; // char for positions that is still empty on the borad
// constant for displaying the board
// chess size
constexpr int chessX{ 6 };
constexpr int chessY{ 3 };
// square size, plus 2 for some space between grid lines and the chess piece
constexpr int squareX = chessX + 2;
constexpr int squareY = chessY + 2;
// size of the displayed board on screen
constexpr int display_width = (b_w + 1) + b_w * squareX; // vertical lines + 7 for each grid
constexpr int display_height = (b_h + 1) + b_h * squareY; // horizonal lines + 7 for each grid
// color for printing in console
constexpr int default_color{ 15 }; // black background, white text
constexpr int red = 4;
constexpr int yellow = 6;
#pragma region game_msg
constexpr std::string_view welcome_msg = R""""(
___ _ ___
/ __\ ___ _ __ _ __ ___ ___ | |_ / __\ ___ _ _ _ __
/ / / _ \ | '_ \ | '_ \ / _ \ / __|| __| / _\ / _ \ | | | || '__|
/ /___ | (_) || | | || | | || __/| (__ | |_ / / | (_) || |_| || |
\____/ \___/ |_| |_||_| |_| \___| \___| \__| \/ \___/ \__,_||_|
)"""";
constexpr std::string_view win_msg = R""""(
_ _ _ _ _
__ __(_) _ __ / \ / \ / \ / \
\ \ /\ / /| || '_ \ / / / / / / / /
\ V V / | || | | |/\_/ /\_/ /\_/ /\_/
\_/\_/ |_||_| |_|\/ \/ \/ \/
)"""";
constexpr std::string_view draw_msg = R""""(
_
__| | _ __ __ _ __ __
/ _` || '__| / _` |\ \ /\ / /
| (_| || | | (_| | \ V V /
\__,_||_| \__,_| \_/\_/
)"""";
#pragma endregion game_msg
}
#endif
| true |
676df3c6499ee47d58669d3bfe88f2a056aebb4d | C++ | rezwan4029/UVA-CODES | /10321 - Polygon Intersection.cpp | UTF-8 | 7,606 | 2.640625 | 3 | [] | no_license | /*
AUST_royal.flush
*/
#include <bits/stdc++.h>
#define pb push_back
#define all(x) x.begin(),x.end()
#define ms(a,v) memset(a,v,sizeof a)
#define II ({int a; scanf("%d", &a); a;})
#define LL ({Long a; scanf("%lld", &a); a;})
#define DD ({double a; scanf("%lf", &a); a;})
#define EPS 1e-10
#define pi 3.1415926535897932384626433832795
using namespace std;
typedef long long Long;
typedef unsigned long long ull;
typedef vector<int> vi ;
typedef set<int> si;
typedef vector<Long>vl;
typedef pair<int,int>pii;
typedef pair<Long,Long>pll;
typedef pair<double,double>pdd;
#define forab(i, a, b) for (__typeof (b) i = (a) ; i <= b ; ++i)
#define rep(i, n) forab (i, 0, (n) - 1)
#define For(i, n) forab (i, 1, n)
#define rofba(i, a, b) for (__typeof (b)i = (b) ; i >= a ; --i)
#define per(i, n) rofba (i, 0, (n) - 1)
#define rof(i, n) rofba (i, 1, n)
#define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i)
const int MX = 1e5 + 7 ;
const int INF = 1e8 + 7;
struct point {
double x,y;
point(){
x = y = 0;
}
point(double x, double y) : x(x), y(y) {}
void input(){
scanf("%lf %lf",&x,&y);
}
point (const point &p) {
x = p.x, y = p.y;
}
void translate(double tx, double ty) {
x += tx;
y += ty;
}
point translate(point t) {
x += t.x;
y += t.y;
}
point operator+(point k){
return point(x + k.x , y + k.y );
}
point operator-(point k){
return point(x - k.x , y - k.y );
}
point operator*(double k) {
return point(k * x , k * y );
}
point operator/(double k) {
return point(x / k , y/k );
}
point rotleft(){
return point(-y,x);
}
point rotright(){
return point(y,-x);
}
point rotate(point p,double angle) {
point v(x - p.x , y-p.y );
double c = cos(angle) , s = sin(angle);
return point(p.x + v.x*c - v.y*s , p.y + v.x*s + v.y*c );
}
#define sqr(x) ((x)*(x))
double sqrdis(const point &b)const {
return sqr(x - b.x) + sqr(y - b.y);
}
double dis(const point &b)const {
return sqrt(sqrdis(b));
}
bool operator ==(const point &p)const {
return ((x==p.x) && (y==p.y));
}
bool collinear(const point &p1, const point &p2)const {
return (p1.y - y) * (p2.x - x) == (p2.y - y) * (p1.x - x);
}
double cross(const point &i)const
{
return x*i.y-y*i.x;
}
double dot(const point &i)const
{
return x*i.x+y*i.y;
}
bool in_box(const point &a, const point &b) const { // rectangle : a = leftDown , b = rightTop
double lox = min(a.x, b.x), hix = max(a.x, b.x);
double loy = min(a.y, b.y), hiy = max(a.y, b.y);
return x >= lox && x <= hix && y >= loy && y <= hiy; // remove = (eq) if strictly in box need
}
bool operator <(const point &p) const {
return x < p.x || (x == p.x && y < p.y);
} // sorting angle by x axis
/*
bool operator <(const point &p) const {
return y < p.y || (y == p.y && x < p.x);
} // sorting angle by y axis
*/
friend ostream& operator<<(ostream& out, const point& p) {
return out << '(' << p.x << ',' << p.y << ')' << endl;
}
};
int turn( point O , point A , point B){
double res = (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
if( res < 0 ) return -1 ; // O->A->B is a right turn
if( res > 0 ) return 1 ; // O->A->B is a left turn
return 0; // O->A->B is a straight line / co-linear
}
inline bool onsegment(const point &p1, const point &p2, const point &p3) {
point pmn, pmx;
pmn.x = min(p1.x, p2.x), pmn.y = min(p1.y, p2.y);
pmx.x = max(p1.x, p2.x), pmx.y = max(p1.y, p2.y);
return pmn.x <= p3.x && p3.x <= pmx.x && pmn.y <= p3.y && p3.y <= pmx.y;
}
inline bool Intersect(const point &p1, const point &p2, const point &p3, const point &p4, bool &on) {
int d1, d2, d3, d4;
d1 = turn(p3, p4, p1);
d2 = turn(p3, p4, p2);
d3 = turn(p1, p2, p3);
d4 = turn(p1, p2, p4);
on = false;
if(((d1 < 0 && d2 > 0) || (d1 > 0 && d2 < 0)) && ((d3 < 0 && d4 > 0) || (d3 > 0 && d4 < 0))) return true;
if( !d3 && onsegment(p1, p2, p3)) { on = true; return true; }
if( !d4 && onsegment(p1, p2, p4)) return true;
if( !d1 && onsegment(p3, p4, p1)) return true;
if( !d2 && onsegment(p3, p4, p2)) return true;
return false;
}
// compute intersection of line passing through a and b
// with line passing through c and d, assuming that unique
// intersection exists; for segment intersection, check if
// segments intersect first
// **use LinesParallel and LinesColliner to detect wether they intersect
point ComputeLineIntersection(point a, point b, point c, point d)
{
b = b - a ;
d = c - d ;
c = c - a ;
assert( b.dot(b) > EPS && d.dot(d) > EPS);
return a + b* c.cross(d) / b.cross(d) ;
}
bool PointInPoly( point Pt,vector<point> Pl){
long Rcross = 0; /* number of right edge/ray crossings */
long Lcross = 0; /* number of left edge/ray crossings */
int N = Pl.size() ;
/* Shift so that Pt is the origin. Note this destroys the polygon.*/
rep(i,N){
Pl[i].x = Pl[i].x - Pt.x ;
Pl[i].y = Pl[i].y - Pt.y ;
}
/* For each edge e=(i-1,i), see if crosses ray. */
rep(i,N){
/* First see if Pt=(0,0) is a vertex. */
if( Pl[i].x==0 and Pl[i].y==0 ) return 1;
long j = (i+N-1)%N;
bool Rstrad = (Pl[i].y>0) != (Pl[j].y>0);
bool Lstrad = (Pl[i].y<0) != (Pl[j].y<0);
/* if e "straddles" the x-axis... */
if( Rstrad or Lstrad ){
/* e straddles ray, so compute intersection with ray. */
double x = ( Pl[i].x*(double)Pl[j].y - Pl[j].x*(double)Pl[i].y) / (double)(Pl[j].y-Pl[i].y);
/* crosses ray if strictly positive intersection. */
if( Rstrad and x>0 ) Rcross++;
if( Lstrad and x<0 ) Lcross++;
}
}
/* Pt on the edge if left and right cross are not the same parity. */
if( (Rcross%2) != (Lcross%2) ) return 1;
/* Pt inside iff an odd number of crossings. */
if( (Rcross%2) == 1 ) return 1;
else return 0;
}
point Pt[MX];
int main(){
#ifdef LOCAL
freopen ("in.txt", "r", stdin);
#endif
int N , M ;
while( scanf("%d",&N) && N ){
vector<point>poly1(N) ;
rep(i,N) poly1[i].input();
scanf("%d",&M);
vector<point>poly2(M) ;
rep(i,M) poly2[i].input();
point A , B , C , D ;
bool onSegment;
int nn = 0 ;
for( int i = 0 , j = N - 1 ; i < N ; j = i++ ){
A = poly1[i];
B = poly1[j];
for( int k = 0 , l = M - 1 ; k < M ; l = k++ ){
C = poly2[k];
D = poly2[l];
if( Intersect(A,B,C,D,onSegment) ){
if( !onSegment ) Pt[ nn++] = ComputeLineIntersection(A,B,C,D) ;
}
}
}
rep(i,N) if( PointInPoly(poly1[i],poly2) ) Pt[ nn++ ] = poly1[i] ;
rep(i,M) if( PointInPoly(poly2[i],poly1) ) Pt[ nn++ ] = poly2[i] ;
if( nn == 0 ) {
puts("0") ;
continue ;
}
sort( Pt , Pt + nn );
int j = 0 ;
rep(i,nn){
if( fabs( Pt[i].x - Pt[j].x ) > EPS || fabs( Pt[i].y - Pt[j].y ) > EPS )
Pt[++j] = Pt[i];
}
nn = j + 1 ;
printf("%d\n",nn);
rep(i,nn) printf("%.2lf %.2lf\n",Pt[i].x , Pt[i].y );
}
}
| true |
63a93c472f2e97307d98d793bfed9a80929055a5 | C++ | rainingapple/algorithm-competition-code | /CCF-CSP/CCF-CSP/18-03-1.cpp | UTF-8 | 328 | 2.5625 | 3 | [] | no_license | //#include<iostream>
//using namespace std;
//int main() {
// int flag, point = 0, ans = 0;
// while (cin >> flag) {
// if (flag == 0) {
// break;
// }
// else if (flag == 1) {
// point = 0;
// ans += 1;
// }
// else {
// point += 2;
// ans += point;
// }
// }
// cout << ans;
// return 0;
//} | true |
d3f70a553c9fa7afce456bf2f0bb81a9d8907551 | C++ | szqh97/test | /cpp/c11/shared_weak_ptr.cpp | UTF-8 | 430 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <memory>
using namespace std;
struct Linker
{
weak_ptr<Linker> link;
// shared_ptr<Linker> link; // error while use shared_ptr,
};
void Dowork()
{
shared_ptr<Linker> l1(new Linker());
shared_ptr<Linker> l2(new Linker());
l1->link = l2;
l2->link = l1;
}
int main ( int argc, char *argv[] )
{
Dowork();
return 0;
} /* ---------- end of function main ---------- */
| true |
741655a5a7f9e06b866740472033856a8e860793 | C++ | forkingpath/snowdevice | /extern/PCG-BSPDungeonGen/include/PCG-BSPDungeonGen/Dungeon.h | UTF-8 | 1,397 | 2.671875 | 3 | [
"MIT"
] | permissive | #ifndef PCG_DUNGEON_H
#define PCG_DUNGEON_H
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <random>
#include <string>
#include "AABB.h"
#include "Node.h"
typedef AABB Room;
typedef std::vector<Vec2> Path;
typedef std::vector<unsigned int> GridLine;
typedef std::vector<std::vector<unsigned int> > Grid;
/*! Class representing a randomly generated dungeon
*/
class Dungeon {
public:
Dungeon(std::string seed, int width, int height);
~Dungeon();
enum TILE_TYPE {
Empty = 0, Floor = 1, Corridor = 2, Entrance = 3, Exit = 4, Door = 5, Treasure = 6, Monster = 7, Trap = 8
};
private:
int mWidth;
int mHeight;
int mUnitSquare;
std::mt19937 mRandGen;
std::uniform_real_distribution<float> mUniDistr;
std::seed_seq mSeedSeq;
std::string mSeedString;
std::vector<Room> mRooms;
std::vector<Path> mCorridors;
std::vector<Vec2> mTreasures;
std::vector<Vec2> mMonsters;
std::vector<Vec2> mTraps;
Vec2 mEntrance;
Vec2 mExit;
Grid mGrid;
Node<AABB> mRootNode;
public:
void Generate(void);
Grid GetGrid(void);
private:
void ClearGrid();
void SplitSpace(Node<AABB> *node);
void FindRoomsDigCorridors();
void PlaceEntranceAndExit();
void BakeFloor();
void PlaceDoors();
void PlaceTreasureAndMonsters();
void BakeDetails();
};
#endif
| true |
e438e10fae47c06b52aa57dc9f52756022f6ded5 | C++ | prakhar-agarwal/SemGen-cpp | /include/semsim/annotation/Ontology.h | UTF-8 | 2,579 | 2.984375 | 3 | [] | no_license | #include "../definitions/ReferenceOntologies.h"
#include <string>
#include <vector>
namespace semsim { namespace definitions { class ReferenceOntologies; } }
namespace semsim
{
namespace annotation
{
using ReferenceOntology = semsim::definitions::ReferenceOntologies::ReferenceOntology;
/**
* Class representing identifier information about an ontology.
* This includes the ontology's full name, BioPortal namespace,
* textual description, etc.
*/
class Ontology
{
private:
std::wstring fullname;
std::wstring nickname;
std::wstring bioportalnamespace;
std::vector<std::wstring> namespaces = std::vector<std::wstring>();
std::wstring description;
/**
* @param name Full name of ontology
* @param abrev Nickname of ontology
* @param ns Array of namespaces used for this ontology
* @param desc Textual description of ontology
* @param bpns BioPortal namespace of the ontology
*/
public:
Ontology(const std::wstring &name, const std::wstring &abrev, std::vector<std::wstring> &ns, const std::wstring &desc, const std::wstring &bpns);
/**
* @param name Full name of ontology
* @param abrev Nickname of ontology
* @param ns Array of namespaces used for this ontology
* @param desc Textual description of ontology
*/
Ontology(const std::wstring &name, const std::wstring &abrev, std::vector<std::wstring> &ns, const std::wstring &desc);
/**
* Constructor for creating an {@link Ontology} class
* from a {@link ReferenceOntology} class
* @param ro The {@link ReferenceOntology} that will have
* its information copied to this class.
*/
Ontology(ReferenceOntology ro);
/**
* @param nspace Namespace to test for association with the ontology
* @return Whether the namespace is in the array of namespaces associated
* with this ontology
*/
virtual bool hasNamespace(const std::wstring &nspace);
/**
* @return Full name of ontology
*/
virtual std::wstring getFullName();
/**
* @return Nickname of ontology
*/
virtual std::wstring getNickName();
/**
* @return The BioPortal namespace of the ontology
*/
virtual std::wstring getBioPortalNamespace();
/**
* @return The set of namespaces associated with the ontology
*/
virtual std::vector<std::wstring> getNameSpaces();
/**
* @return A free-text description of the ontology
*/
virtual std::wstring getDescription();
};
}
} | true |
bc246b801d02e5c44f9de6763b4f527c123ae057 | C++ | TommyTeaVee/HelixGame | /project/helix.cpp | UTF-8 | 7,522 | 2.546875 | 3 | [] | no_license | // helix.cpp
// implementazione dei metodi definiti in helix.h
#include <stdio.h>
#include <math.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include "helix.h"
#include "point3.h"
#include "mesh.h"
#include "objects.h"
// variabili globali di tipo mesh
Mesh carlinga((char *)"./objects/elicottero_carlinga_vera.obj");
Mesh elica((char *)"./objects/elicottero_elica.obj");
Mesh elicaPR((char *)"./objects/elicottero_elica2.obj");
Mesh finestre((char *)"./objects/elicottero_finestre.obj");
extern bool useEnvmap; // var globale esterna: per usare l'evnrionment mapping
extern bool useShadow; // var globale esterna: per generare l'ombra
extern int punteggio; // punteggio del giocatore
/*****************************************************************************/
/* da invocare quando e' stato premuto/rilasciato il tasto numero "keycode" */
/*****************************************************************************/
void Controller::EatKey(int keycode, int* keymap, bool pressed_or_released) {
for (int i=0; i<NKEYS; i++) {
if (keycode == keymap[i])
key[i] = pressed_or_released;
}
}
/*************************************************************/
/* da invocare quando e' stato premuto/rilasciato un jbutton */
/*************************************************************/
void Controller::Joy(int keymap, bool pressed_or_released) {
key[keymap] = pressed_or_released;
}
/***************************************************/
/* funzione che prepara tutto per usare un env map */
/***************************************************/
void SetupEnvmapTexture() {
// facciamo binding con la texture 1
glBindTexture(GL_TEXTURE_2D, 1);
glEnable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_GEN_S); // abilito la generazione automatica delle coord texture S e T
glEnable(GL_TEXTURE_GEN_T);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); // Env map
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glColor3f(1,1,1); // metto il colore neutro (viene moltiplicato col colore texture, componente per componente)
glDisable(GL_LIGHTING); // disabilito il lighting OpenGL standard (lo faccio con la texture)
}
/***************************************************************/
// DoStep: facciamo un passo di fisica (a delta_t costante)
// Indipendente dal rendering.
// Ricordiamoci che possiamo LEGGERE ma mai SCRIVERE
// la struttura controller da DoStep
/***************************************************************/
void Helix::DoStep(){
// computiamo l'evolversi dell'elicottero
static int i=5;
float vxm, vym, vzm; // velocita' in spazio elicottero
// da vel frame mondo a vel frame elicottero
float cosf = cos(facing*M_PI/180.0);
float sinf = sin(facing*M_PI/180.0);
vxm = +cosf*vx - sinf*vz;
vym = vy;
vzm = +sinf*vx + cosf*vz;
// gestione dello sterzo
if (controller.key[Controller::LEFT]) sterzo += velSterzo;
if (controller.key[Controller::RIGHT]) sterzo -= velSterzo;
if (controller.key[Controller::UP]) py += velVolante;
if (controller.key[Controller::DOWN]) py -= velVolante;
if (py < 0) py = 0; // l'elicottero non sprofonda nel terreno
sterzo*=velRitornoSterzo; // ritorno a volante dritto
if (controller.key[Controller::ACC]) vzm-=accMax; // accelerazione in avanti
if (controller.key[Controller::DEC]) vzm+=accMax; // accelerazione indietro
if(py == 0) vzm = 0; // se l'elicottero è a terra non può muoversi
// attirti (semplificando)
vxm*=attritoX;
vym*=attritoY;
vzm*=attritoZ;
// l'orientamento dell'elicottero' segue quello dello sterzo
// (a seconda della velocita' sulla z)
facing = facing - (vzm*grip)*sterzo;
// ritorno a vel coord mondo
vx = +cosf*vxm + sinf*vzm;
vy = vym;
vz = -sinf*vxm + cosf*vzm;
// posizione = posizione + velocita * delta t (ma delta t e' costante)
px+=vx;
py+=vy;
pz+=vz;
/* imposto i limiti del mondo di gioco */
if(pz >= 61) pz = 61;
if(pz <= -61) pz = -61;
if(px >= 61) px = 61;
if(px <= -61) px = -61;
if(py >= 45) py = 45;
}
/***********************/
/* init del controller */
/***********************/
void Controller::Init(){
for (int i=0; i<NKEYS; i++)
key[i] = false;
}
/***************************/
/* init della classe Helix */
/***************************/
void Helix::Init(){
// inizializzo lo stato dell'elicottero
// posizione e orientamento
px = 0;
py = 0;
pz = 0;
facing = 0;
// stato
sterzo = 0;
// velocita' attuale
vx = 0;
vy = 0;
vz = 0;
// inizializzo la struttura di controllo
controller.Init();
velSterzo = 2.4; // A
velRitornoSterzo = 0.93; // B, sterzo massimo = A*B / (1-B)
velVolante = 0.04;
accMax = 0.0011;
// attriti: percentuale di velocita' che viene mantenuta
// 1 = no attrito
// <<1 = attrito grande
attritoZ = 0.991; // piccolo attrito sulla Z (nel senso di rotolamento delle ruote)
attritoX = 0.8; // grande attrito sulla X (per evitare slittamento)
attritoY = 1.0; // attrito sulla y nullo
// Nota: vel max = accMax*attritoZ / (1-attritoZ)
raggioRuotaA = 0.25;
raggioRuotaP = 0.35;
grip = 0.45;
}
/***************************************************************/
// funzione che disegna tutti i pezzi dell'elicottero
// (carlinga + eliche + finestre e base)
// (da invocarsi due volte: per l'elicottero, e per la sua ombra)
// (se usecolor e' falso, NON sovrascrive il colore corrente
// e usa quello stabilito prima di chiamare la funzione)
/***************************************************************/
void Helix::RenderAllParts(bool usecolor, float mozzo) const{
// disegna la carliga con una mesh
glPushMatrix();
// patch: riscaliamo la mesh di 1/10
glScalef(-0.02,0.02,-0.02);
glPushMatrix();
if(usecolor) glColor3f(.1,.1,.1);
glRotatef(25*mozzo,0,1,0);
elica.RenderNxF();
glPopMatrix();
glPushMatrix();
if(usecolor) glColor3f(.1,.1,.1);
glTranslatef(0, +elicaPR.Center().Y(), +elicaPR.Center().Z());
glRotatef(20*mozzo,1,0,0);
glTranslatef(0, -elicaPR.Center().Y(), -elicaPR.Center().Z() );
elicaPR.RenderNxF();
glPopMatrix();
glPushMatrix();
if(usecolor) glColor3f(.9,.9,.9);
finestre.RenderNxF();
glPopMatrix();
if (!useEnvmap) {
if (usecolor)
glColor3f(0,0,0.40);
}
else {
if (usecolor)
SetupEnvmapTexture();
}
glPushMatrix();
carlinga.RenderNxV();
glDisable(GL_TEXTURE_2D);
if (usecolor)
glEnable(GL_LIGHTING);
glPopMatrix();
glPopMatrix();
}
/*********************/
/* disegna a schermo */
/*********************/
void Helix::Render(float mozzo) const{
// sono nello spazio mondo
glPushMatrix();
glTranslatef(px,py,pz);
glRotatef(facing, 0,1,0);
// sono nello spazio elicottero
RenderAllParts(true, mozzo);
// ombra!
if(useShadow) {
glTranslatef(0,-py,0);
glScalef(1-py/50,1-py/50,1-py/50);
glColor3f(0.4,0.4,0.4); // colore fisso
glTranslatef(0,0.01,0); // alzo l'ombra di un epsilon per evitare z-fighting con il pavimento
glScalef(1.01,0,1.01); // appiattisco sulla Y, ingrandisco dell'1% sulla Z e sulla X
glDisable(GL_LIGHTING); // niente lighing per l'ombra
RenderAllParts(false, mozzo); // disegno l'elicottero appiattito
glEnable(GL_LIGHTING);
}
glPopMatrix();
glPopMatrix();
}
| true |
6e3628fb25a74669107b8dcdf45197871018bed6 | C++ | bahmad30/Blackjack-AI | /tests/test_deck.cc | UTF-8 | 3,506 | 3.59375 | 4 | [] | no_license | #include <catch2/catch.hpp>
#include "deck.h"
namespace blackjack {
TEST_CASE("Deck constructor") {
Deck deck;
std::vector<Card> cards = deck.GetCardsInDeck();
SECTION("52 cards") {
REQUIRE(cards.size() == 52);
}
SECTION("No cards in table") {
REQUIRE(deck.GetCardsOnTable().empty());
}
SECTION("Correct ranks") {
int sum = 0;
for (Card &card : cards) {
sum += card.GetRank();
}
REQUIRE(sum == 364);
}
SECTION("Correct suits") {
int diamonds = 0;
int spades = 0;
int hearts = 0;
int clubs = 0;
for (Card &card : cards) {
if (card.GetSuit() == 'D') {
diamonds++;
} else if (card.GetSuit() == 'S') {
spades++;
} else if (card.GetSuit() == 'H') {
hearts++;
} else if (card.GetSuit() == 'C') {
clubs++;
}
}
REQUIRE(diamonds == 13);
REQUIRE(spades == 13);
REQUIRE(hearts == 13);
REQUIRE(clubs == 13);
}
}
TEST_CASE("Shuffle") {
Deck deck;
std::vector<Card> before = deck.GetCardsInDeck();
deck.Shuffle();
std::vector<Card> after = deck.GetCardsInDeck();
SECTION("Cards in different order") {
bool different_order = false;
for (size_t i = 0; i < after.size(); i++) {
if (before[i].GetRank() != after[i].GetRank() || before[i].GetSuit() != after[i].GetSuit()) {
different_order = true;
}
}
REQUIRE(different_order);
}
}
TEST_CASE("Display card") {
Deck deck;
SECTION("Cards in deck loses correct card") {
Card drawn = deck.DrawCard();
bool present = false;
for (Card &card : deck.GetCardsInDeck()) {
if (card.GetRank() == drawn.GetRank() && card.GetSuit() == drawn.GetSuit()) {
present = true;
}
}
REQUIRE(!present);
}
SECTION("Cards on table gets correct card") {
Card drawn = deck.DrawCard();
bool present = false;
for (Card &card : deck.GetCardsOnTable()) {
if (card.GetRank() == drawn.GetRank() && card.GetSuit() == drawn.GetSuit()) {
present = true;
}
}
REQUIRE(present);
}
SECTION("Multiple draws") {
deck.DrawCard();
deck.DrawCard();
REQUIRE(deck.GetCardsInDeck().size() == 50);
REQUIRE(deck.GetCardsOnTable().size() == 2);
}
SECTION("Display from empty deck") {
while (!deck.GetCardsInDeck().empty()) {
deck.DrawCard();
}
REQUIRE_THROWS_AS(deck.DrawCard(), std::invalid_argument);
}
}
TEST_CASE("Reset") {
Deck deck;
deck.DrawCard();
deck.DrawCard();
Card drawn1 = deck.GetCardsOnTable()[0];
Card drawn2 = deck.GetCardsOnTable()[1];
deck.Reset();
SECTION("Correct cards are transferred") {
bool first_present = false;
bool second_present = false;
for (Card &card : deck.GetCardsInDeck()) {
if (card.GetRank() == drawn1.GetRank() && card.GetSuit() == drawn1.GetSuit()) {
first_present = true;
} else if (card.GetRank() == drawn2.GetRank() && card.GetSuit() == drawn2.GetSuit()) {
second_present = true;
}
}
REQUIRE((first_present && second_present));
}
}
} // namespace blackjack | true |
c143a3b50e595caa6a67caa4fbdac7c84ed2f746 | C++ | niuxu18/logTracker-old | /second/download/mutt/gumtree/mutt_repos_function_60_last_repos.cpp | UTF-8 | 215 | 2.578125 | 3 | [] | no_license | static int pad (FILE *f, int col, int i)
{
char fmt[8];
if (col < i)
{
snprintf (fmt, sizeof(fmt), "%%-%ds", i - col);
fprintf (f, fmt, "");
return (i);
}
fputc (' ', f);
return (col + 1);
} | true |
d72d47b09f8c27dae98719df69fe8de602996729 | C++ | 6Kwecky6/Cpp2020 | /Oving4/Part2.h | UTF-8 | 1,538 | 2.828125 | 3 | [] | no_license | //
// Created by Kwecky on 13/09/2020.
//
#ifndef OVING4_PART2_H
#define OVING4_PART2_H
#include <gtkmm.h>
class Window : public Gtk::Window {
public:
Gtk::VBox vbox;
Gtk::Entry firstNameEntry;
Gtk::Entry lastNameEntry;
Gtk::Button button;
Gtk::Label resultText;
Gtk::Label firstNameText;
Gtk::Label lastNameText;
Window() {
firstNameText.set_text("First name");
lastNameText.set_text("Last name");
button.set_label("Combine names");
button.set_sensitive(false);
vbox.pack_start(firstNameText);
vbox.pack_start(firstNameEntry);
vbox.pack_start(lastNameText);
vbox.pack_start(lastNameEntry); //Add the widget entry to vbox
vbox.pack_start(button); //Add the widget button to vbox
vbox.pack_start(resultText); //Add the widget resultText to vbox
add(vbox); //Add vbox to window
show_all(); //Show all widgets
lastNameEntry.signal_changed().connect([this]() {
button.set_sensitive(!(firstNameEntry.get_text().compare("") == 0 || lastNameEntry.get_text().compare("") == 0));
});
firstNameEntry.signal_changed().connect([this]() {
button.set_sensitive(!(firstNameEntry.get_text().compare("") == 0 || lastNameEntry.get_text().compare("") == 0));
});
button.signal_clicked().connect([this]() {
resultText.set_text("Name: " + firstNameEntry.get_text() + ", " + lastNameEntry.get_text());
});
}
};
#endif //OVING4_PART2_H
| true |
65871e86d1ec5f8a9dd61e80696ef0109fd34d1e | C++ | Antoniano1963/vscode_cpp | /Week2/Test8.cpp | UTF-8 | 289 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include "big_operation.h"
using namespace std;
int main(){
string str1;
cin >> str1;
string str2;
cin >> str2;
big number1 = big(str1);
big number2 = big(str2);
big result = number1 + number2;
cout << result.print();
} | true |
f14529d4832f01b00e434d1b253995fbbaa83a36 | C++ | alumican/ofxCommand | /src/command/Serial.h | UTF-8 | 884 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "CommandList.h"
namespace cmd {
class Serial : public CommandList {
// ----------------------------------------
//
// MEMBER
//
// ----------------------------------------
public:
protected:
private:
Command* currentCommand;
int position;
// ----------------------------------------
//
// METHOD
//
// ----------------------------------------
public:
Serial();
Serial(const vector<Command*>& commands);
~Serial();
virtual void insert(const vector<Command*>& commands);
int getPosition() const;
virtual void _notifyBreak();
virtual void _notifyReturn();
protected:
virtual void runFunction(Command* command);
virtual void interruptFunction(Command* command);
virtual void resetFunction(Command* command);
private:
void next();
void currentCommandCompleteHandler(Command& command);
};
}
| true |
b089101484e18eecd4395f8f5c63bfebd9f50bae | C++ | y2kiah/icarus | /Icarus/source/Resource/Impl/ResHandle.inl | UTF-8 | 2,930 | 2.875 | 3 | [] | no_license | /* ResHandle.inl
Author: Jeff Kiah
Orig.Date: 06/01/2012
*/
#pragma once
#include "Resource/ResCache.h"
// class ResHandle
///// TEMPLATE FUNCTIONS /////
/*---------------------------------------------------------------------
load is used to retrieve a resource from disk or the cache (if
available) in a sychronous manner. When this blocking call returns,
the resource will be available, or the loading process will have
failed. Returns true on success, false on error.
---------------------------------------------------------------------*/
template <typename TResource>
inline bool ResHandle::load(const wstring &resPath)
{
size_t i = resPath.find_first_of(L"/\\"); // find the first slash or backslash
if (i == string::npos) { // if no slash found, cannot find the source so return false
debugWPrintf(L"ResHandle.load: Error: invalid path in load: \"%s\"\n", resPath.c_str());
return false;
}
mSource = resPath.substr(0, i);
mName = resPath.substr(i+1);
// safely grab the ResCacheManager instance
ResCacheManagerPtr rcm(sResCacheManager.lock());
if (!rcm) {
debugWPrintf(L"ResHandle.load: Error: ResCacheManager pointer is null: \"%s\"\n", resPath.c_str());
return false;
}
return rcm->load<TResource>(*this);
}
/*---------------------------------------------------------------------
tryLoad is used to retrieve a resource from disk or the cache (if
available) in an asynchronous manner. When this non-blocking call
returns, if the resource was already in the cache, it will be
available, and otherwise, a job to load it will be queued for a
worker thread to do the loading. A process should be created to
monitor the resource handle for the completion or failure of the
loading.
---------------------------------------------------------------------*/
template <typename TResource>
inline ResLoadResult ResHandle::tryLoad(const wstring &resPath)
{
size_t i = resPath.find_first_of(L"/\\"); // find the first slash or backslash
if (i == string::npos) { // if no slash found, cannot find the source so return false
debugWPrintf(L"ResHandle.tryLoad: Error: invalid path in load: \"%s\"\n", resPath.c_str());
return ResLoadResult_Error;
}
mSource = resPath.substr(0, i);
mName = resPath.substr(i+1);
// safely grab the ResCacheManager instance
ResCacheManagerPtr rcm(sResCacheManager.lock());
if (!rcm) {
debugWPrintf(L"ResHandle.tryLoad: Error: ResCacheManager pointer is null: \"%s\"\n", resPath.c_str());
return ResLoadResult_Error;
}
return rcm->tryLoad<TResource>(*this);
}
// class Resource
/*---------------------------------------------------------------------
Primarily used for resource injection where the cache pointer is
not set any other way. This is called from addToCache methods.
---------------------------------------------------------------------*/
inline void Resource::setResCache(const ResCachePtr &resCachePtr)
{
mResCacheWeakPtr = resCachePtr;
}
| true |