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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4384f8bdccb8aece3adbdf1b9ba06081cb6a3539 | C++ | naveensharma27/CodeForces | /16A.cpp | UTF-8 | 700 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
int n,m,i;
bool checkR(string flag[])
{
for(int i=0;i<n;i++)
{
char c = flag[i][0];
for(int j=1;j<m;j++)
{
if(flag[i][j] !=c)
{
return false;
}
}
}
return true;
}
bool checkC(string flag[])
{
for(int i=1;i<n-1;i++)
{
if((flag[i][0] == flag[i-1][0]) || (flag[i][0] == flag[i+1][0]))
{
return false;
}
}
return true;
}
int main()
{
cin>>n>>m;
string flag[n];
for(i=0;i<n;i++)
{
cin>>flag[i];
}
if(checkC(flag) && checkR(flag))
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
return 0;
}
| true |
b98625626d8b67445a3c481c9330ec4d384577c7 | C++ | llNeeleshll/CPP | /functions/pass_ref.cpp | UTF-8 | 733 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include<vector>
#include<string>
using namespace std;
void change(int &a);
void pass_by_ref(vector<string> &v);
void print_vector(const vector<string> &v);
int main(){
int a{50};
cout<<"Value before passing : "<<a<<endl;
change(a);
cout<<"Value after passing : "<<a<<endl;
vector<string> v {"Neelesh", "Is", "Awesome"};
cout<<endl<<"Value before passing : ";
print_vector(v);
pass_by_ref(v);
cout<<endl<<"Value after passing : ";
print_vector(v);
return 0;
}
void change(int &a){
a = 100;
}
void pass_by_ref(vector<string> &v){
v.clear();
}
void print_vector(const vector<string> &v){
for(auto i: v){
cout<<i<<" ";
}
cout<<endl;
} | true |
fa2f2376ca824f82fca74b11161591a050a57741 | C++ | Jacob-Zackaria/Graphics-Engine | /src/LODModel.h | UTF-8 | 1,466 | 2.59375 | 3 | [] | no_license | #ifndef LOD_MODEL_H
#define LOD_MODEL_H
#include "Model.h"
#include "GraphicObjectBase.h"
class LODModel
{
public:
enum class Name
{
TROLL,
SMALL_TROLL,
SEAGULL,
WIZARD,
BOAT,
FLOWER,
FISH,
UFO,
ORIGAMI_TREE,
UNDEFINED
};
LODModel(const LODModel&) = delete; // Copy constructor
LODModel(LODModel&&) = default; // Move constructor
LODModel& operator=(const LODModel&) & = default; // Copy assignment operator
LODModel& operator=(LODModel&&) & = default; // Move assignment operator
~LODModel();
LODModel(GraphicObjectBase* newGraphBase, Matrix& newWorld);
void Add(Model* newModel, float switchLength = 0.0f);
//void Remove();
const Vect GetWorldPos() const;
const float GetActiveLength() const;
const float GetPrevActiveLength() const;
void NextLod();
void PrevLod();
const bool isNextLodNull() const;
const bool isPrevLodNull() const;
Name getName() const;
void setName(LODModel::Name name);
//-----links----
void setNext(LODModel* newNext);
void setPrev(LODModel* newPrev);
LODModel* getNext() const;
LODModel* getPrev() const;
private:
void privAddToFront(Model* node, Model*& head);
void privRemove(Model* pNewData, Model*& pHead);
LODModel::Name name;
Model* pModelHead;
Model* active;
GraphicObjectBase* pGraphBase;
Matrix mWorld;
// links
LODModel* pNext;
LODModel* pPrev;
};
#endif LOD_MODEL_H | true |
6271a25fa2959e8ef9b2f92bfbebbb29bfa9a25b | C++ | cxrasdfg/json_yacc_lex | /json.cpp | UTF-8 | 11,255 | 2.984375 | 3 | [
"MIT"
] | permissive | /**
* Created by theppsh on 17-5-7.
*/
#include "json.hpp"
json_ast::pNode json_ast::AllocNode(const ASTType type) {
return std::make_shared<json::JsonObject>(type);
}
json_ast::pNode json_ast::CreateString(const char *str, const int leng) {
auto result = AllocNode(ASTType::AT_STRING);
result->string_val.resize(leng);
std::memcpy(const_cast<char*>(result->string_val.data()),str,leng);
return result;
}
json_ast::pNode json_ast::CreateInt(const char *str, const int leng) {
auto result = AllocNode(ASTType::AT_INT);
std::sscanf(str,"%d",&result->int_val);
return result;
}
json_ast::pNode json_ast::CreateDouble(const char *str, const int leng) {
auto result = AllocNode(ASTType::AT_DOUBLE);
std::sscanf(str,"%lf",&result->double_val);
return result;
}
/**
* convert '\b' '\f' '\n' '\r' '\t' '\\' '\"'
* @param raw_string
* @return
*/
std::string json_ast::RawToString(const std::string &raw_string) {
auto clip_str= raw_string.substr(1,raw_string.size()-2);
std::string result;
for(unsigned long i=0;i<clip_str.size();i++){
auto ch = clip_str[i];
if(ch=='\\'){
if(i==clip_str.size()-1){
throw json::JsonException("json parser error: '\\'' should be followed as the '\\r' '\\f' '\\n' '\\r' '\\t' '\\\\' '\\\"' ");
}else{
i++;
auto next_ch = clip_str[i];
switch (next_ch){
case 'b':
{
result.push_back('\b');
}
break;
case 'f':
{
result.push_back('\f');
}
break;
case 'n':
{
result.push_back('\n');
}
break;
case 'r':
{
result.push_back('\r');
}
break;
case 't':
{
result.push_back('\t');
}
break;
case '\\':
{
result.push_back('\\');
}
break;
case '\"':
{
result.push_back('\"');
}
break;
default:
throw json::JsonException("json parser error: '\\'' should be followed as the '\\r' '\\f' '\\n' '\\r' '\\t' '\\\\' '\\\"' ");
break;
}
}
}else{
result.push_back(ch);
}
}
return result;
}
std::string json_ast::StringToRaw(const std::string &string) {
std::string result;
result.push_back('\"');
for(auto ch:string){
switch (ch){
case '\b':
{
result.push_back('\\');
result.push_back('b');
}
break;
case '\f':
{
result.push_back('\\');
result.push_back('f');
}
break;
case '\n':
{
result.push_back('\\');
result.push_back('n');
}
break;
case '\r':
{
result.push_back('\\');
result.push_back('r');
}
break;
case '\t':
{
result.push_back('\\');
result.push_back('t');
}
break;
case '\\':
{
result.push_back('\\');
result.push_back('\\');
}
break;
case '\"':
{
result.push_back('\\');
result.push_back('\"');
}
break;
default:
result.push_back(ch);
break;
}
}
result.push_back('\"');
return result;
}
json_ast::ASTNode::~ASTNode() {}
json_ast::ASTNode::ASTNode(ASTType type):type(type) {}
void json_ast::ASTNode::ShowTree() {
ShowTreeHelp(this);
}
void json_ast::ASTNode::ShowTreeHelp(ASTNode *ptr) {
std::cout<<json::JsonToString(ptr);
}
json::JsonException::JsonException(const std::string &__arg) : runtime_error(__arg) {
}
void json ::JsonToStringHelp(json_ast::ASTNode *ptr, std::string &result) {
if(ptr!= nullptr){
using namespace json_ast;
auto &dict_children = ptr->dict_children;
auto &array_children = ptr->array_children;
switch(ptr->type){
case json_ast::ASTType ::AT_INT:
{
//std::cout<<ptr->int_val;
result.append(std::to_string(ptr->int_val));
}
break;
case ASTType ::AT_DOUBLE:
{
//std::cout<<ptr->double_val;
result.append(std::to_string(ptr->double_val));
}
break;
case ASTType ::AT_STRING:
{
//std::cout<<StringToRaw(ptr->string_val);
result.append(StringToRaw(ptr->string_val));
}
break;
case ASTType ::AT_DICT:
{
//std::cout<<"{"/**<<std::endl*/;
result.push_back('{');
int i=0;
for(auto elem : dict_children){
//std::cout<<StringToRaw(elem.first)<<":";
result.append(StringToRaw((elem.first)));
result.push_back(':');
JsonToStringHelp(elem.second.get(),result);
if((++i)!=dict_children.size())
//std::cout<<","/**<<std::endl*/;
result.push_back(',');
}
//std::cout<<"}"/**<<std::endl*/;
result.push_back('}');
}
break;
case ASTType ::AT_ARRAY:
{
//std::cout<<"["/**<<std::endl*/;
result.push_back('[');
int i=0;
for(auto elem:array_children){
JsonToStringHelp(elem.get(),result);
if((++i)!=array_children.size())
//std::cout<<","/**<<std::endl*/;
result.push_back(',');
}
//std::cout<<"]"/**<<std::endl*/;
result.push_back(']');
}
break;
}
}
}
std::string json::JsonToString(json_ast::ASTNode *ptr) {
std::string result;
JsonToStringHelp(ptr,result);
return result;
}
std::string json::JsonToString(std::shared_ptr<json_ast::ASTNode> ptr) {
std::string result;
JsonToStringHelp(ptr.get(),result);
return result;
}
json::JsonObject& json::JsonObject::DictInsert(const std::string &name, PJsonObject pJson) {
if(type != json::JsonObjectType::AT_DICT){
throw json::JsonException("JsonObject invokes error: only dictionary can invoke DictInsert...");
}
dict_children.insert(std::make_pair(name, std::dynamic_pointer_cast<json_ast::ASTNode>(pJson)));
return *this;
}
json::PJsonObject json::JsonObject::DictGet(const std::string &key) {
if(type != json::JsonObjectType::AT_DICT){
throw json::JsonException("JsonObject invokes error: only dictionary can invoke DictGet...");
}
auto result= dict_children.find(key);
if(result!= dict_children.end()){
return std::dynamic_pointer_cast<JsonObject>(result->second);
}
return nullptr;
}
std::vector<std::string > json::JsonObject::DictKeys() {
if(type != json::JsonObjectType::AT_DICT){
throw json::JsonException("JsonObject invokes error: only dictionary can invoke DictKeys...");
}
std::vector<std::string > result;
for(auto elem :dict_children){
result.push_back(elem.first);
}
return result;
}
std::vector<json:: PJsonObject> json::JsonObject::DictValues() {
if(type != json::JsonObjectType::AT_DICT){
throw json::JsonException("JsonObject invokes error: only dictionary can invoke DictValues...");
}
std::vector<json:: PJsonObject> result;
for(auto elem :dict_children){
result.push_back(std::dynamic_pointer_cast<json::JsonObject>(elem.second));
}
return result;
}
json::JsonObject& json::JsonObject::ArrayInsert(PJsonObject pJson, int _pos) {
if(type != json::JsonObjectType::AT_ARRAY){
throw json::JsonException("JsonObject invokes error: only array can invoke ArrayInsert...");
}
if(_pos==-1){
array_children.push_back(std::dynamic_pointer_cast<json_ast::ASTNode>(pJson));
}
else if(_pos>=0){
array_children.insert(array_children.begin()+_pos,std::dynamic_pointer_cast<json_ast::ASTNode>(pJson));
}
return *this;
}
json::PJsonObject json::JsonObject::ArrayGet(int _pos) {
if(type != json::JsonObjectType::AT_ARRAY){
throw json::JsonException("JsonObject invokes error: only array can invoke ArrayGet...");
}
if(_pos>=0 && _pos< array_children.size()){
return std::dynamic_pointer_cast<json::JsonObject>(array_children[_pos]);
}
return nullptr;
}
int json::JsonObject::Int(){
if(type != json::JsonObjectType::AT_INT){
throw json::JsonException("JsonObject type converts error: int...");
}
return int_val;
}
double json::JsonObject:: Double(){
if(type != json::JsonObjectType::AT_DOUBLE){
throw json::JsonException("JsonObject type converts error: double...");
}
return double_val;
}
std::string json::JsonObject::String() {
if(type != json::JsonObjectType::AT_STRING){
throw json::JsonException("JsonObject type converts error: string...");
}
return string_val;
}
std::string json::JsonObject::JsonToString() {
return json::JsonToString(this);
}
json::JsonObject::JsonObject(json_ast::ASTType type) : ASTNode(type) {}
json::JsonObject::~JsonObject() {}
json:: PJsonObject json::PJson(const int x) {
auto result = json_ast::AllocNode(json_ast::ASTType::AT_INT);
result->int_val=x;
return std::dynamic_pointer_cast<json::JsonObject>(result);
}
json:: PJsonObject json::PJson(const char *x) {
auto result = json_ast::AllocNode(json_ast::ASTType::AT_STRING);
result->string_val=x;
return std::dynamic_pointer_cast<json::JsonObject>(result);
}
json:: PJsonObject json::PJson(const double x) {
auto result = json_ast::AllocNode(json_ast::ASTType::AT_DOUBLE);
result->double_val=x;
return std::dynamic_pointer_cast<json::JsonObject>(result);
}
json:: PJsonObject json::PJson(const std::string &x) {
auto result = json_ast::AllocNode(json_ast::ASTType::AT_STRING);
result->string_val=x;
return std::dynamic_pointer_cast<json::JsonObject>(result);
}
json::PJsonObject json::CreateJsonObject(const JsonObjectType type) {
return std::make_shared<JsonObject>(type);
}
| true |
ab80b1dc53fc1cbf3bb8794642c61de1931c13e3 | C++ | implementedrobotics/Nomad | /Hardware/Actuator/NomadBLDC/FirmwareG4/NomadBLDC/RingBuffer.cpp | UTF-8 | 2,581 | 2.625 | 3 | [
"MIT"
] | permissive | /*
* RingBuffer.cpp
*
* Created on: April 6, 2020
* Author: Quincy Jones
*
* Copyright (c) <2020> <Quincy Jones - quincy@implementedrobotics.com/>
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
// Primary Include
#include "RingBuffer.h"
// C System Files
#include <cstring>
// C++ System Files
// Project Includes
RingBuffer::RingBuffer(size_t buffer_size) : head_(0),
tail_(0),
buffer_size_(buffer_size),
full_(false)
{
buffer_ = new float[buffer_size](); // Init with zeros
}
bool RingBuffer::empty() const
{
return (!full_ && (head_ == tail_));
}
bool RingBuffer::full() const
{
return full_;
}
void RingBuffer::reset()
{
head_ = tail_;
full_ = false;
memset(buffer_, 0, sizeof(float) * buffer_size_);
}
size_t RingBuffer::capacity() const
{
return buffer_size_;
}
size_t RingBuffer::size() const
{
size_t size = buffer_size_;
if (!full_)
{
if (head_ >= tail_)
{
size = head_ - tail_;
}
else
{
size = buffer_size_ + head_ - tail_;
}
}
return size;
}
float RingBuffer::peak()
{
return buffer_[tail_];
}
float RingBuffer::get()
{
if (empty())
{
return 0.0f;
}
//Read data and advance the tail (we now have a free space)
auto val = buffer_[tail_];
full_ = false;
//tail_ = (tail_ + 1) % buffer_size_;
if (++tail_ >= buffer_size_)
tail_ = 0;
return val;
}
| true |
b746e2173fd0eef79db7aaf2afcc509c7bb2de2a | C++ | fvazquezf/7542_TpFinal | /client/commands/CreateGame.h | UTF-8 | 412 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef CREATEGAME_H
#define CREATEGAME_H
#include "Command.h"
class CreateGame : public Command{
private:
std::string gameName;
std::string mapName;
public:
explicit CreateGame(std::string gameName, std::string mapName);
void serialize(std::function<void (std::vector<unsigned char>)> &callback,
const Protocol& protocol) override;
~CreateGame() override;
};
#endif
| true |
d5ca4e66980c7c177fceeb34d7c4576554fb5ef8 | C++ | TimTam725/Atcoder | /その他/nazo/a.cpp | UTF-8 | 207 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
float A,B,T;
cin>>A>>B>>T;
T+=0.5;
int i,sum;
sum=0;
for(i=1;A*i<=T;i++){
sum+=B;
}
cout<<sum<<endl;
}
| true |
e328b6a6c11cf447474f94ad9e4231e94fb0940c | C++ | AkVaya/CP_Solutions | /Codeforces/832B.cpp | UTF-8 | 1,505 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
string s,t;
bool check = true;
unordered_set<char> allowed;
cin>>s>>t;
int q,ind = -1;
for(auto i : s){
allowed.insert(i);
}
for (int i = 0; i < t.length(); ++i)
{
if(t[i]=='*'){
ind = i;
break;
}
}
cin>>q;
while(q--){
cin>>s;
if((ind==-1 && s.length()!=t.length())){
cout<<"NO\n";
continue;
}
check=true;
if(ind==-1){
for (int i = 0; i < s.length(); ++i)
{
if(t[i]!='?' && s[i]!=t[i]){
check=false;
break;
}
else{
if(allowed.find(s[i])==allowed.end()){
check=true;
break;
}
}
}
}
else{
if(s.length()<t.length()-1){
cout<<"NO\n";
continue;
}
for (int i = 0; i < ind; ++i)
{
if(t[i]!='?' && s[i]!=t[i]){
check=false;
break;
}
else{
if(t[i]=='?' && allowed.find(s[i])==allowed.end()){
check=false;
break;
}
}
}
auto it1=s.end(),it2=t.end();
it1--;
it2--;
while(it1>=s.begin() && it2>=t.begin() && *it2!='*'){
//cout<<*it1<<' '<<*it2<<endl;
if(*it2!='?' && *it1!=*it2){
check=false;
break;
}
else{
if(*it2=='?' && allowed.find(*it1)==allowed.end()){
check=false;
break;
}
}
--it1;
--it2;
}
it2 = s.begin()+ind;
while(it2<=it1){
if(allowed.find(*it2)!=allowed.end()){
check=false;
break;
}
it2++;
}
}
//cout<<s<<' ';
cout<<(check ? "YES\n" : "NO\n");
}
return 0;
} | true |
b819eb03394b83462afea00614ccc90827cb3f56 | C++ | cowtony/ACM | /XJOJ/Documents/Too hard - Haven't solved/164/164 WA.cpp | UTF-8 | 484 | 3.21875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int GCD(int a,int b)
{
if(b==0)return a;
else return GCD(b,a%b);
}
int LCM(int a,int b)
{
return a/GCD(a,b)*b;
}
int Factor(int n,int k)
{
int count=0;
for(int i=2;i<=n/2;i++)
{
int lcm=LCM(i,i^k);
if(lcm==0)lcm=99999999;
count+=n/i-1-n/lcm;
}
return count;
}
int main()
{
int a,b,n;
while(cin>>a>>b>>n)
{
cout<<Factor(a+b,n)-Factor(a-1,n)<<endl;
}
}
| true |
fa3bbecacf5357378509e2e10a490d54148257ee | C++ | idemb/idemb | /ID/IndexValuePair.hpp | UTF-8 | 483 | 3.28125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | #pragma once
#include <iostream>
struct IndexValuePair {
size_t m_index;
double m_value;
IndexValuePair(size_t i= 0, double v=0.0) : m_index(i), m_value(v) { }
friend std::ostream& operator<<(std::ostream& os, const IndexValuePair& pair) {
return os << "index = " << pair.m_index << " value = " << pair.m_value << "\n";
}
bool operator==(const IndexValuePair& other) const {
return ((m_index == other.m_index) && (m_value == other.m_value));
}
};
| true |
090a3866172065354559bd9858498007af09c9ad | C++ | macbury/mqtt_led_strip | /led_strip.ino | UTF-8 | 4,413 | 2.59375 | 3 | [] | no_license | #include <EEPROM.h>
#include <Adafruit_NeoPixel.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include "credentials.c"
#include "SingleColor.h"
#include "SinColor.h"
#include "RainbowColor.h"
#include "DualColor.h"
#include "FireEffect.h"
const int JSON_BUFFER_SIZE = JSON_OBJECT_SIZE(10);
const char* CMD_ON = "ON";
const char* CMD_OFF = "OFF";
WiFiClient espClient;
PubSubClient client(espClient);
#include "iot.h"
Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIN_LED_STRIP, NEO_GRB + NEO_KHZ800);
LedState currentState;
Effect * effect;
void on_mqtt_message(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("] ");
/**
* Transform this to more normal stuff like array of char not a bytefuck
*/
char message[length + 1];
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
message[length] = '\0';
if (String(MQTT_RESET_TOPIC) == topic) {
if (String(message) == CMD_ON) {
Serial.println("Enable OTA");
setupOTA();
} else {
Serial.println("Reseting ESP!");
ESP.restart();
}
return;
}
if (String(MQTT_DEEP_SLEEP_TOPIC) == topic) {
Serial.println("Starting deep sleep");
return;
}
Serial.println(message);
if (processJson(message)) {
sendCurrentState();
return;
}
}
/**
* Parse out everything about action
*/
boolean processJson(char * rawJson) {
StaticJsonBuffer<JSON_BUFFER_SIZE> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(rawJson);
if (!root.success()) {
Serial.println(rawJson);
Serial.println("json is fucked up!");
return false;
}
currentState.enabled = root["state"] == CMD_ON;
if (root.containsKey("effect")) {
LedState transitionState = effect->getCurrentState();
delete effect;
Serial.print("Changing effect to");
if (root["effect"] == "FireEffect") {
effect = new FireEffect();
} else if (root["effect"] == "DualColor") {
effect = new DualColor();
} else if (root["effect"] == "RainbowColor") {
effect = new RainbowColor();
} else if (root["effect"] == "SinColor") {
effect = new SinColor();
} else {
Serial.println("Unsuported effect, fallback to default");
effect = new SingleColor();
}
effect->resume(transitionState);
}
if (root.containsKey("color")) {
currentState.red = root["color"]["r"];
currentState.green = root["color"]["g"];
currentState.blue = root["color"]["b"];
}
if (root.containsKey("brightness")) {
currentState.brightness = root["brightness"];
}
if (currentState.enabled) {
effect->begin(currentState);
} else {
effect->end();
}
return true;
}
/**
* Inform mqtt component in home assistant about light state
*/
void sendCurrentState() {
StaticJsonBuffer<JSON_BUFFER_SIZE> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["state"] = currentState.enabled ? CMD_ON : CMD_OFF;
JsonObject& color = root.createNestedObject("color");
color["r"] = currentState.red;
color["g"] = currentState.green;
color["b"] = currentState.blue;
root["brightness"] = currentState.brightness;
root["effect"] = effect->name();
char buffer[root.measureLength() + 1];
root.printTo(buffer, sizeof(buffer));
Serial.println("Sending current state:");
Serial.println(buffer);
client.publish(MQTT_STATE_TOPIC, buffer, true);
}
void updateLeds() {
if (effect->update(strip)) {
delay(33);
} else {
delay(500);
}
}
void setup() {
Serial.begin(115200);
currentState = { 255, 255, 255, 100, false };
pinMode(BUILTIN_LED, INPUT);
strip.begin();
strip.setBrightness(0);
strip.show();
client.setServer(MQTT_HOST, MQTT_PORT);
client.setCallback(on_mqtt_message);
effect = new SingleColor();
}
void onConnect() {
Serial.print("Subscribing: ");
Serial.println(MQTT_SET_TOPIC);
client.subscribe(MQTT_SET_TOPIC);
Serial.println(MQTT_RESET_TOPIC);
client.subscribe(MQTT_RESET_TOPIC);
Serial.println(MQTT_DEEP_SLEEP_TOPIC);
client.subscribe(MQTT_DEEP_SLEEP_TOPIC);
sendCurrentState();
}
void loop() {
if (client.connected()) {
client.loop();
ArduinoOTA.handle();
} else {
if (ensureMqttConnection()) {
onConnect();
}
}
}
| true |
d76a72381d870824ffad6e5387cf8e4ba4ea068b | C++ | pR1smm/MPEG | /MPEG/Image.h | UTF-8 | 1,184 | 3.046875 | 3 | [] | no_license | //
// Image.h
// MotionVectorizer
//
// Created by Klaus Ulhaas on 21.05.14.
// Copyright (c) 2014 Klaus Ulhaas. All rights reserved.
//
#ifndef __MotionVectorizer__Image__
#define __MotionVectorizer__Image__
#include <string>
class Image {
protected:
int width, height; // Dimensions of the image
int depth; // Image depth in Bits
unsigned char* data; // Image data
int size; // Image data size
public:
Image();
// shallow copy
Image(Image& img);
// deep copy
Image clone();
// allocates data buffer and sets memory to zero
Image(int width, int height, int depth=8);
// loads a grayscale image
bool loadPGM(std::string filename);
// writes a grayscale image
bool writePGM(std::string filename);
// returns the image buffer
unsigned char* getBuffer() {return data;}
void setBuffer(unsigned char myData[]) { data = myData;}
int getWidth() const { return width; }
int getHeight() const { return height; }
int getDepth() const { return depth; }
int getSize() const { return size; }
};
#endif /* defined(__MotionVectorizer__Image__) */
| true |
e55ea4d43d91450d02400f5d1284d476130454c2 | C++ | zhuhaijun753/FDTtools | /Delivery_Master_2016-09-16/ToolsuiteSource/FDTUI/SchedulerAnalysis/SchedulerTaskModel.cpp | UTF-8 | 3,202 | 2.5625 | 3 | [] | no_license | #include "SchedulerTaskModel.h"
#include "Project.h"
#include "Task.h"
#include <QAbstractTableModel>
#include <QList>
SchedulerTaskModel::SchedulerTaskModel(const Project& project)
{
project.GetAllTasks(m_unchangedTasks);
Reset();
}
void SchedulerTaskModel::Reset()
{
beginResetModel();
m_tasks.clear();
foreach (const Task* task, m_unchangedTasks)
{
m_tasks.append(new Task(task->InitFunction, task->Runnable, task->StartupDelay, task->Periodicity));
}
endResetModel();
}
int SchedulerTaskModel::rowCount(const QModelIndex& parent) const
{
if (parent.isValid()) return 0;
return m_tasks.count();
}
int SchedulerTaskModel::columnCount(const QModelIndex& parent) const
{
if (parent.isValid()) return 0;
return SchedulerTaskColumnCount;
}
QVariant SchedulerTaskModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::EditRole)) return QVariant();
const Task* task = m_tasks.at(index.row());
switch (index.column())
{
case RunnableFunctionColumn:
return QVariant::fromValue(task->Runnable);
case StartupDelayColumn:
return QVariant::fromValue(task->StartupDelay);
case PeriodicityColumn:
return QVariant::fromValue(task->Periodicity);
default:
return QVariant();
}
}
QVariant SchedulerTaskModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole || orientation != Qt::Horizontal) return QVariant();
switch (section)
{
case RunnableFunctionColumn:
return QVariant("Task Runnable");
case StartupDelayColumn:
return QVariant("Startup delay");
case PeriodicityColumn:
return QVariant("Periodicity");
default:
return QVariant();
}
}
Qt::ItemFlags SchedulerTaskModel::flags(const QModelIndex& index) const
{
if (!index.isValid()) return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
switch (index.column())
{
case StartupDelayColumn:
case PeriodicityColumn:
return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
default:
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
}
bool SchedulerTaskModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid() || role != Qt::EditRole) return false;
switch (index.column())
{
case PeriodicityColumn:
if (value.canConvert(QVariant::Int) && value.toInt() > 0)
{
m_tasks.at(index.row())->Periodicity = value.toInt();
emit dataChanged(index, index, QVector<int>() << role);
return true;
}
return false;
case StartupDelayColumn:
if (value.canConvert(QVariant::Int))
{
m_tasks.at(index.row())->StartupDelay = value.toInt();
emit dataChanged(index, index, QVector<int>() << role);
return true;
}
return false;
default:
return false;
}
}
| true |
52aaee00759719224cb326bf9553af817d682175 | C++ | rapman1986/Programming_Principles_and_Practice_using_Cpp | /Chapter_05/Exercises/13.cpp | UTF-8 | 5,008 | 3.984375 | 4 | [] | no_license | // Bulls and Cows game
#include "std_lib_facilities.h"
void WelcomeMessage();
void PlayGame();
vector<int> GetUserInput(int);
vector<int> BuildDigitsVector(int, int);
vector<int> BuildValueToGuess(int);
int GetLength();
bool CheckGuess(vector<int>, vector<int>);
bool CheckForRepeatedDigits(vector<int>);
int main()
{
WelcomeMessage();
PlayGame();
return 0;
}
// Welcome message
void WelcomeMessage()
{
cout << "\t\t### Wellcome to Bulls and Cows game ###\n";
cout << "You need to guess some number. The digits appears only once in sequnce, and number can`t start with 0\n";
cout << "For example: the number that you need to guess is 1234, if you enter 1378, you will get "
<< "1 Bulls for 1 and 1 Cows for 3\n";
cout << "#################################################################################################\n";
cout << endl;
}
// Main game function that controliing all logic and game flow
void PlayGame()
{
bool play_game = true; // play game flag
bool play_stage = true; //. check if stage is finished
vector<int> value_to_guess; // number that user need to guess
int value_length;
vector<int> user_guess; // user guess
// main game loop
while (play_game)
{
// Get length for value to guess
value_length = GetLength();
// Build value to guess
value_to_guess = BuildValueToGuess(value_length);
// Player plays the game
cout << "\nWe generated number for you with " << value_length << " digits.\n";
cout << "Try to guess it!!\n";
while (play_stage)
{
user_guess = GetUserInput(value_length);
play_stage = CheckGuess(user_guess, value_to_guess);
}
play_stage = true; // reset play srage for new game
// check if user whant to start new stage
cout << "You guessed the number, it was ";
for (int i = 0; i < value_to_guess.size(); i++) cout << value_to_guess[i];
cout << endl;
cout << "Start new game? Y/N ";
while (true)
{
char answer;
cin >> answer;
if (answer != 'Y' && answer != 'N' && answer != 'y' && answer != 'n')
cout << "Wrong input, try again\n";
else
{
if (answer == 'n' || answer == 'N') play_game = false;
break;
}
}
}
cout << "\t\tGame Over!\n";
}
// Get user input and check it for errors
vector<int> GetUserInput(int value_length)
{
int user_num;
bool is_correct = false;
vector<int> user_guess;
while (!is_correct)
{
cout << "Enter your guess, " << value_length << " digits number: ";
cin >> user_num;
// build digits vector, and return vector
user_guess = BuildDigitsVector(user_num, value_length);
// check if user entered right length number
if (user_guess.size() != value_length)
{
cerr << "Error: Wrong number length. Try again\n";
continue;
}
// check for repeated digits, and return true or false
is_correct = CheckForRepeatedDigits(user_guess);
}
return user_guess;
}
vector<int> BuildDigitsVector(int user_num, int value_length)
{
vector<int> temp;
vector<int> user_guess;
while(user_num != 0)
{
int digit = user_num % 10;
temp.push_back(digit);
user_num /= 10;
}
for (int i = temp.size(); i > 0; i--)
user_guess.push_back(temp[i - 1]);
return user_guess;
}
vector<int> BuildValueToGuess(int value_length)
{
vector<int> value_to_guess;
for (int i = 0; i < value_length;)
{
srand(value_length);
int num = randint(0, 9);
if (i == 0 && num == 0) // check if first digit choosed to be 0, it is wrong
continue;
// check for repeated digit
bool is_repeated = false;
for (int j = 0; j < value_to_guess.size(); j++)
if (value_to_guess[j] == num)
{
is_repeated = true;
break;
}
// if all okay, push the number to vector, and continue
if (!is_repeated)
{
value_to_guess.push_back(num);
i++;
}
}
return value_to_guess;
}
int GetLength()
{
int value_length;
cout << "Enter the lenght for value that you whant to guess.\n";
cout << "Minimu value is 4 and maximum value is 10. The more length the harder game will be.\n";
while (true)
{
cin >> value_length;
if (value_length < 4 || value_length > 10)
cout << "Wrong length, try again\t";
else
break;
}
return value_length;
}
bool CheckGuess(vector<int> user_guess, vector<int> value_to_guess)
{
bool play_stage = true;
int bulls = 0, cows = 0;
for (int i = 0; i < user_guess.size(); i++)
for (int j = 0; j < value_to_guess.size(); j++)
if (user_guess[i] == value_to_guess[j])
if (i == j)
bulls++;
else
cows++;
if (bulls == value_to_guess.size()) play_stage = false; // user finished the game
else
cout << "Bulls = " << bulls << "; Cows = " << cows << endl;
return play_stage;
}
bool CheckForRepeatedDigits(vector<int> user_guess)
{
bool is_correct = true;
// check for repeated digits
for (int i = 0; i < user_guess.size(); i++)
for (int j = i + 1; j < user_guess.size(); j++)
if (user_guess[i] == user_guess[j])
is_correct = false;
if (!is_correct) cerr << "Error: You entered number with repeated digits\n";
return is_correct;
}
| true |
b19d0074659f644077a7619f12b3f19dba4644e8 | C++ | rajatgirotra/study | /cpp/BOOST/mpl/20.cpp | UTF-8 | 2,972 | 3.28125 | 3 | [] | no_license | /*
* Some very important stuff to follow.
*
* 1) A placeholder
*
* A placeholder is just a typedef for the template argument number.
*
* typedef arg<1> _1; //meaning argument number 1.
* typedef arg<2> _2; //meaning argument number 2.
* typedef arg<3> _3; // ditto
* .....
* typedef arg<n> _n; where n is BOOST_MPL_LIMIT_METAFUNCTION_ARITY
*
*
* Always say using namespace boost::mpl::placeholders; to use _1, _2, etc..
* See example below
*
* Before we see placeholders, we'll see two more simple metafunctions.
*
* PLACEHOLDER EXPRESSION
*
* A placeholder expression is a type that is either a placeholder (_1, _2 etc) or
* is a template specialization with atleast one argument that itself is a PLACEHOLDER EXPRESSION.
* Eg:
* _
* _1
* _2
* plus<_, int_<2> >
*
*
* Metafunction - You already know this. A class or class template with a nested typedef with name "type"
*
* Metafunction class - A metafunction class is a class or class template with a nested metafunction called "apply".
* This is used in high-order template metaprogramming as you will see later.
*
*
* So remember both what is a PLACEHOLDER EXPRESSION and WHAT IS A METAFUNCTION CLASS.
*
* Lambda Expression - When you see the term "Lambda expression" it means either a PLACEHOLDER EXPRESSION
* or a METAFUNCTION CLASS. It can refer to either of them. A NUMBER OF high-order metafunctions take lambda expressions
* as a template parameter; this means that it can be a placeholder expression or a metafunction class
*
* apply<> and apply_wrap<>.
* Both these metafunctions must be in used in variadic forms,
* ie applyn<F, A1, A2.. An> and apply_wrapn<F, A1, A2.. , An>
*
* apply_wrapn<F, A1, A2, .., An> - Very simple, when you are sure that F is a METAFUNCTION CLASS; you can call
* apply_wrapn. It just calls F::apply with arguments A1, A2, .. , An
*
* If you are not sure if F is a METAFUNCTION CLASS or a PLACEHOLDER EXPRESSION, you can use applyn<> instead.
* We'll see later what applyn<> does to figure out if F is a PE or a MC.
*
*/
#include <iostream>
#include <boost/mpl/apply_wrap.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
namespace mpl = boost::mpl;
struct f0
{
struct apply
{
typedef char type;
};
};
struct g0
{
template <typename T = int>
struct apply
{
typedef T type;
};
};
struct f2
{
template <typename T1, typename T2>
struct apply
{
typedef T2 type;
};
};
typedef mpl::apply_wrap0<f0>::type r1;
typedef mpl::apply_wrap1<g0, double>::type r2;
typedef mpl::apply_wrap2<f2, int, char>::type r3;
typedef mpl::apply2<f2, int, char>::type r4;
int main()
{
BOOST_MPL_ASSERT (( boost::is_same <r1, char> ));
BOOST_MPL_ASSERT (( boost::is_same <r2, double> ));
BOOST_MPL_ASSERT (( boost::is_same <r3, char> ));
BOOST_MPL_ASSERT (( boost::is_same <r4, char> ));
return 0;
}
| true |
7dc609464451618020f2963ffd42f16cefed0e89 | C++ | apassi99/Joystick | /Wifly/main.cpp | UTF-8 | 580 | 2.59375 | 3 | [] | no_license | //
// main.cpp
// TestXbee
//
// Created by Arjun Passi on 5/4/15.
// Copyright (c) 2015 Arjun Passi. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <thread>
#include "USBDevice.h"
#define USB_PORT "/dev/tty.usbserial-A5025UHW"
void readStringFromXbee() {
USBDevice usb(USB_PORT);
char buf[255];
while (true) {
if ( usb.readString(&buf[0]) )
std::cout << buf << std::endl;
}
}
int main(int argc, const char * argv[]) {
std::thread first (readStringFromXbee);
while (true) { }
return 0;
}
| true |
5551ad37acb356038b2eb1db2f2ca2d90a744988 | C++ | TheRedLady/Data-Structures-Pract | /Binary Ordered Tree/main.cpp | UTF-8 | 242 | 2.65625 | 3 | [] | no_license | #include "BinaryOrderedTree.h"
int main()
{
BOT<int> tree;
tree.insert(5);
tree.insert(8);
tree.insert(3);
tree.insert(2);
tree.insert(7);
tree.insert(-1);
tree.insert(9);
tree.print();
tree.remove(5);
tree.print();
return 0;
} | true |
0d8683791263f13a7414baa9c33d285dcbe4a3a8 | C++ | anagorko/zpk2015 | /grupa3/lukaszdm/p1/czy.cpp | MacCentralEurope | 377 | 2.734375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
/* 10 5 18 9 30 15 48 24...
9 30 15 48 24....
8 4 2 1
7 24 12 6 3 12 6 3
100 50 25 78 39 120 60 30 15 tylko potgi dwojki*/
long long c;
cin >>c;
while(c%2==0 && c!=1)
c/=2;
if(c==1)
cout << "TAK" << endl;
else
cout << "NIE" << endl;
}
| true |
2868db0f3c8e54c93b48413c872287084efcc921 | C++ | Knabin/AlgorithmQ | /Chapter2/main_50.cpp | UTF-8 | 738 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int h, w, i, j, t;
int height, width, max = -2147000000;
int p1, p2;
cin >> h >> w;
vector<vector<int>> vInt;
vector<int> temp;
for (i = 0; i < h; ++i)
{
temp.clear();
temp.resize(w);
for (j = 0; j < w; ++j)
{
cin >> temp[j];
}
vInt.push_back(temp);
}
cin >> height >> width;
for (i = 0; i <= h - height; ++i)
{
for (j = 0; j <= w - width; ++j)
{
p1 = 0;
p2 = 0;
t = 0;
while (true)
{
if (p2 >= width)
{
++p1;
p2 = 0;
}
if (p1 >= height) break;
t += vInt[i + p1][j + p2];
p2++;
}
if (max < t) max = t;
}
}
cout << max << endl;
return 0;
}
| true |
64b92e23551a65204099497d733061189e39bc9e | C++ | DevilBot000/cpploader | /cppencoder/cppencoder.cpp | UTF-8 | 829 | 2.78125 | 3 | [] | no_license | #include <windows.h>
#include <iostream>
void encode(LPCSTR inFilename, LPCSTR outFilename)
{
char buf[4096];
HANDLE inFile = CreateFile(inFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
int size = GetFileSize(inFile, NULL);
DWORD bytesRead = 0;
ReadFile(inFile, buf, size, &bytesRead, NULL);
CloseHandle(inFile);
for (int i = 0; i != sizeof(buf) / sizeof(buf[0]); i++) {
buf[i] = buf[i] ^ 'a';
}
HANDLE outFile = CreateFile(outFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
DWORD bytesWrite = 0;
WriteFile(outFile, buf, size, &bytesWrite, NULL);
CloseHandle(outFile);
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cout << "cppencoder.exe calc.bin enc.bin" << std::endl;
}
else {
encode(argv[1], argv[2]);
}
return 0;
} | true |
1df2988b6429e3050d6d447086ada1df9a0eeb39 | C++ | Space0726/Algorithm | /baekjoon/2231.cc | UTF-8 | 423 | 2.765625 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int main() {
int n, div_sum;
scanf("%d", &n);
int min_div = n;
for (int x = n-1; x >= n/2; x--) {
div_sum = x;
for (int i = 10; i <= x*10; i *= 10)
div_sum += (x % i)/(i / 10);
if (div_sum == n)
min_div = x;
}
if (min_div == n)
printf("0\n");
else
printf("%d\n", min_div);
return 0;
}
| true |
e6b4dc66187a9f96fbbd55216630d8f35223f9e9 | C++ | seongwon-kang/Elsword-Source-2014 | /KncTools/FileBackup/KLogManager.h | UHC | 10,063 | 2.5625 | 3 | [
"MIT"
] | permissive | /** @file
@author cruise@kogsoft.com
*/
#ifndef _KOG_KLOGMANAGER_H_
#define _KOG_KLOGMANAGER_H_ "$Id: KLogManager.h,v 1.8 2003/02/11 03:13:24 cvs Exp $"
#pragma once // for _MSC_VER > 1000
#include <string>
#include <cstdio>
#include <cstdarg>
#include <windows.h>
#include <vector>
#include "KSingleton.h"
/** Log Message Manager.
α ۼ ÿ ʿ log message ϰ ٷ
manager class̴. ⺻, log message ߿䵵 , 0 (
߿) ~ NUM_LEVEL-1 ( ߿) . level 0 level
1 error (ýۿ critical error ǹ) warning (ڰ
˾ƾ warning ǹ) ϰ, level αӰ
̳ Ÿ ϰ ϴ log message Ѵ.
log message αӿ ˸ ũ 4 Ͽ.
<ul>
<li> ܼ (console output, F_CONSOLE) : console program
Ͼ, stderr log message Ѵ.
<li> (debugger output, F_DEBUG) : MS Visual Studio
ȯ濡 â Ѵ.
<li> (file output, F_FILE) : α
밡ϰ, Ͽ Ѵ. ̸
BeginFileOutput(...) Լ Ѵ.
<li> ý ̺Ʈ α (system Event Log, F_EVENT) : Windows ý
̺Ʈ ڿ д. ٸ ýۿ
remote ؼ ͵ ϴ.
α ϴ, α ĺڰ ʿ , ĺڴ
BeginEventLogOutput(...) Լ Ѵ.
</ul>
Ǵ level ,
ְ, log level log , ش level
̸ 鿡 , log Ѵ.
⺻ level, ܼ, , on ǰ, ý
̺Ʈ off Ǿ ִ. ̳ ý ̺Ʈ flag on
Ű ̿ܿ, BeginFileOuput(...) ̳ BeginEventLogOutput(...)
Լ ȣ ʿ Ѵ.
<BLOCKQUOTE> (Prefix) (User-provided message)
[(FileName,LineNumber)] </BLOCKQUOTEIP> ¸ . <b>(Prefix)</b>
ش level prefix ǹϰ, level 0
level 1 ؼ "ERROR: " "Warning: " ⺻ ,
level NULL string ⺻ . <b>(User-provided
message)</b> ڰ ϰ ϴ message, printf-style
Լ Ѵ. ̵ Լ Ǵ long-typeԼ (Լ ̸
'L' ÷ Լ) , ̵ long-type Լ
κп C preprocessor ϴ __FILE__ __LINE__ ũ
߰ Ѵ.
@verbinclude testKLogManager.cpp
*/
class KLogManager
{
public:
/** Default constructor. */
_DLLAPI KLogManager(void);
/** Destructor. */
_DLLAPI ~KLogManager(void);
private:
/** Copy constructor: DISABLED. */
_DLLAPI KLogManager(const KLogManager&);
/** Assignment operator: DISABLED. */
_DLLAPI void operator=(const KLogManager&);
public:
/** String representation. */
_DLLAPI std::string ToString(void) const;
// BEGIN / END FOR FILE AND SYSTEM EVENT LOG OUTPUT ****************
/** Begin log ouptut to the file pszFileName. */
_DLLAPI void BeginFileOutput(const char* pszFileName);
/** End log output to the file. */
_DLLAPI void EndFileOutput(void);
/** Begin log output to the system Event Log with program name. */
_DLLAPI void BeginEventLogOutput(const char* pszProgName);
/** End log output to the system Event Log. */
_DLLAPI void EndEventLogOutput(void);
// OUTPUT METHOD ***************************************************
/** Set the output method for a level. */
_DLLAPI void SetOutputMethod(int iLevel, int iFlag);
/** Set the output method for a range of levels [iLevelStart..iLevelEnd]. */
_DLLAPI void SetOutputMethod(int iLevelStart, int iLevelEnd, int iFlag);
/** Get the current output method for a given level. */
_DLLAPI int GetOutputMethod(int iLevel) const;
// OUTPUT PREFIX ***************************************************
/** Set the output string prefix for a level. */
_DLLAPI void SetOutputPrefix(int iLevel, const char* szPrefix);
/** Set the output string prefix for a range of levels [iLevelStart..iLevelEnd]. */
_DLLAPI void SetOutputPrefix(int iLevelStart, int iLevelEnd, const char* szPrefix);
/** Get the current output string prefix for a given level. */
_DLLAPI const char* GetOutputPrefix(int iLevel) const;
// EVENT TYPE FOR SYSTEM EVENT LOG OUTPUT **************************
/** Set the event type of system Event Log for a level. */
_DLLAPI void SetEventType(int iLevel, WORD wEventType);
/** Set the event type of system Event Log for a range of levels [iLevelStart..iLevelEnd]. */
_DLLAPI void SetEventType(int iLevelStart, int iLevelEnd, WORD wEventType);
/** Get the current event type of system Event Log for a given level. */
_DLLAPI WORD GetEventType(int iLevel) const;
// LOG MESSAGE OUTPUT **********************************************
/** Log message output, printf-style. */
_DLLAPI const char* Log(int iLevel, const char* szFormat, ...);
/** Log message output, for a HRESULT value. */
_DLLAPI const char* Log(int iLevel, HRESULT hr, ...);
/** Preset __FILE__ and __LINE__ for LogL(...) functions. */
_DLLAPI inline void Preset(const char* szFile, int iLine) { m_pszFile = szFile; m_iLine = iLine; }
/** Log message output, printf-style, with __FILE__ and __LINE__ information. */
_DLLAPI const char* LogL(int iLevel, const char* szFormat, ...);
/** Log message output, for a HRESULT value, with __FILE__ and __LINE__ information. */
_DLLAPI const char* LogL(int iLevel, HRESULT hr, ...);
// DEPRECATED ******************************************************
/** Set the program name and register the Event Log source. */
_DLLAPI void SetProgramName(const char* szProgName);
/** Set the output file for the log messages. */
_DLLAPI void SetOutputFile(const char* szFileName);
private:
/** Internal function: iLevel ʿ return. */
_DLLAPI bool NeedOutput(int iLevel) const;
/** Internal function: m_aszBuffer message . */
_DLLAPI void MakeMessage(int iLevel, const char* szFormat, va_list vaList);
/** Internal function: m_aszBuffer __FILE__, __LINE__ ߰Ѵ. */
_DLLAPI void AppendMessage(const char* szFile, int iLine);
/** Internal function: m_aszBuffer ִ message output method鿡 Ѵ. */
_DLLAPI void OutputMessage(int iLevel);
public:
enum
{
ALL_LEVEL = -1, ///< When used for level, indicating all levels.
NUM_LEVEL = 10, ///< Number of valid levels.
// flags for SetOutputMethod(...)
F_NONE = 0, ///< No output method.
F_CONSOLE = 0x01, ///< Console output method is turning on.
F_DEBUG = 0x02, ///< Debugger window output method is turning on.
F_FILE = 0x04, ///< File output method is turning on.
F_EVENT = 0x08, ///< Event Log output method is turning on.
F_ALL = F_FILE | F_DEBUG | F_EVENT | F_CONSOLE, ///< Turning on all output methods.
// event types for SetEventType(...)
ET_ERROR = EVENTLOG_ERROR_TYPE,
ET_WARNING = EVENTLOG_WARNING_TYPE,
ET_INFORMATION = EVENTLOG_INFORMATION_TYPE,
};
private:
std::vector<char>* m_pvecBuffer; ///< Main buffer for printf-style processing.
const char* m_apszEventString[1]; ///< Directing m_aszBuffer for ::ReportEvent(...).
const char* m_apszPrefix[NUM_LEVEL]; ///< Prefix strings for each level.
int m_iPrefixLen[NUM_LEVEL]; ///< Length of prefix strigns for each level.
bool m_bNeedOut[NUM_LEVEL]; ///< True iff a level needs any output.
bool m_bConOut[NUM_LEVEL]; ///< True iff a level needs console output.
bool m_bDebugOut[NUM_LEVEL]; ///< True iff a level needs debugger window output.
bool m_bFileOut[NUM_LEVEL]; ///< True iff a level needs file output.
bool m_bEventOut[NUM_LEVEL]; ///< True iff a level needs system event log output.
WORD m_wEventType[NUM_LEVEL]; ///< Event type for system event log.
FILE* m_pFile; ///< File pointer for the output.
HANDLE m_hEventLog; ///< Handle for system event log.
const char* m_pszFile; ///< Temporary storage for __FILE__
int m_iLine; ///< Temporary storage for __LINE__
char m_szFileName[_MAX_FNAME];
};
#if ! defined(KLOG_OFF)
#define pSKLogManager KSingleton<KLogManager>::GetInstance()
/** Log message output, printf-style.
ũ Լ ǵǰ, printf-style , θ ݵ
KLOG((1, "message %d", number)) , ȣ ѷ ξ Ѵ.
*/
#define KLOG(x) pSKLogManager->Log x
/** Log message output, printf-style, with __FILE__ and __LINE__ information.
ũ Լ ǵǰ, printf-style , θ ݵ
KLOGL((1, "message %d", number)) , ȣ ѷ ξ Ѵ.
*/
#define KLOGL(x) pSKLogManager->Preset(__FILE__, __LINE__); pSKLogManager->LogL x
#else
#define pSKLogManager KSingleton<KLogManager>::GetInstance()
#define KLOG(x) ((void)0)
#define KLOGL(x) ((void)0)
#endif
#endif // _KOG_KLOGMANAGER_H_
| true |
a6c4add4065647c1242ebfe7a90ca9a481ee32c1 | C++ | faical-yannick-congo/BPad | /software/computer/push.ino | WINDOWS-1252 | 20,589 | 2.921875 | 3 | [] | no_license | /*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange
*/
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
// variables for the display
#define I2C_ADDR 0x3F // Define I2C Address where the PCF8574A is
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
int n = 1;
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
// --------------- end display var ----------------
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int buttonPin2 = 7; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the red LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonPushCounter2 = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int buttonState2 = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int lastButtonState2 = 0; // previous state of the button
int lcdCursor = 0;
// ascii char var
int charCode = 0;
void setup() {
// setup the LCD
lcd.begin (20,4);
lcdCursor = 0;
// Switch on the backlight
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
lcd.setBacklight(HIGH);
lcd.home ();
lcd.print("B pad");
//--------------------
// setup the buttons
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the button 2 pin as a input:
pinMode(buttonPin2, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
// set the LCD button
lcdCursor++;
lcdCursor = lcdCursor % 20 ;
charCode = charCode * 10 + 1;
buttonPushCounter++;
lcd.setCursor ( lcdCursor, 1 );
lcd.print("1");
Serial.println("cursor");
Serial.println(lcdCursor);
Serial.println("charCode");
Serial.println(charCode);
Serial.println("on 1");
Serial.print("number of button 1 pushes: ");
Serial.println(buttonPushCounter);
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off 1");
}
}
// ----------------------------
// compare the buttonState to its previous state
if (buttonState2 != lastButtonState2) {
// if the state has changed, increment the counter
if (buttonState2 == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
// set the LCD button
lcdCursor++;
lcdCursor = lcdCursor % 20 ;
charCode = charCode * 10;
buttonPushCounter2++;
lcd.setCursor ( lcdCursor, 1 );
lcd.print("0");
Serial.println("cursor");
Serial.println(lcdCursor);
Serial.println("charCode");
Serial.println(charCode);
Serial.println("on 2");
Serial.print("number of button 2 pushes: ");
Serial.println(buttonPushCounter2);
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off 2");
}
}
// --------------------------
// save the current state as the last state,
//for next time through the loop
// for the 2 buttons
lastButtonState = buttonState;
lastButtonState2 = buttonState2;
String resultString = convertToAscii(charCode);
Serial.println("char is ");
Serial.println(resultString);
lcd.setCursor ( 0, 3 );
lcd.print(" ");
lcd.setCursor ( 0, 3 );
lcd.print(resultString);
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
String convertToAscii(int x)
{
String charAsci="";
switch(x){
case 0:
charAsci = "NULL";
break;
case 1:
charAsci = "SOH";
break;
case 10:
charAsci = "STX";
break;
case 11:
charAsci = "EXT";
break;
case 100:
charAsci = "EOT";
break;
case 101:
charAsci = "ENQ";
break;
case 110:
charAsci = "ACK";
break;
case 111:
charAsci = "BEL";
break;
case 1000:
charAsci = "BS";
break;
case 1001:
charAsci = "TAB";
break;
case 1010:
charAsci = "LF";
break;
case 1011:
charAsci = "VT";
break;
case 1100:
charAsci = "FF";
break;
case 1101:
charAsci = "CR";
break;
case 1110:
charAsci = "SO";
break;
case 1111:
charAsci = "SI";
break;
case 10000:
charAsci = "DLE";
break;
case 10001:
charAsci = "DC1";
break;
case 10010:
charAsci = "DC2";
break;
case 10011:
charAsci = "DC3";
break;
case 10100:
charAsci = "DC4";
break;
case 10101:
charAsci = "NAK";
break;
case 10110:
charAsci = "SYN";
break;
case 10111:
charAsci = "ETB";
break;
case 11000:
charAsci = "CAN";
break;
case 11001:
charAsci = "EM";
break;
case 11010:
charAsci = "SUB";
break;
case 11011:
charAsci = "ESC";
break;
case 11100:
charAsci = "FS";
break;
case 11101:
charAsci = "GS";
break;
case 11110:
charAsci = "RS";
break;
case 11111:
charAsci = "US";
break;
case 100000:
charAsci = "SPACE";
break;
case 100001:
charAsci = "!";
break;
case 100010:
charAsci = "\"";
break;
case 100011:
charAsci = "#";
break;
case 100100:
charAsci = "$";
break;
case 100101:
charAsci = "%";
break;
case 100110:
charAsci = "&";
break;
case 100111:
charAsci = "\'";
break;
case 101000:
charAsci = "(";
break;
case 101001:
charAsci = ")";
break;
case 101010:
charAsci = "*";
break;
case 101011:
charAsci = "+";
break;
case 101100:
charAsci = ",";
break;
case 101101:
charAsci = "-";
break;
case 101110:
charAsci = ".";
break;
case 101111:
charAsci = "/";
break;
case 110000:
charAsci = "0";
break;
case 110001:
charAsci = "1";
break;
case 110010:
charAsci = "2";
break;
case 110011:
charAsci = "3";
break;
case 110100:
charAsci = "4";
break;
case 110101:
charAsci = "5";
break;
case 110110:
charAsci = "6";
break;
case 110111:
charAsci = "7";
break;
case 111000:
charAsci = "8";
break;
case 111001:
charAsci = "9";
break;
case 111010:
charAsci = ":";
break;
case 111011:
charAsci = ";";
break;
case 111100:
charAsci = "<";
break;
case 111101:
charAsci = "=";
break;
case 111110:
charAsci = ">";
break;
case 111111:
charAsci = "?";
break;
case 1000000:
charAsci = "aro"; // was arobase
break;
case 1000001:
charAsci = "A";
break;
case 1000010:
charAsci = "B";
break;
case 1000011:
charAsci = "C";
break;
case 1000100:
charAsci = "D";
break;
case 1000101:
charAsci = "E";
break;
case 1000110:
charAsci = "F";
break;
case 1000111:
charAsci = "G";
break;
case 1001000:
charAsci = "H";
break;
case 1001001:
charAsci = "I";
break;
case 1001010:
charAsci = "J";
break;
case 1001011:
charAsci = "K";
break;
case 1001100:
charAsci = "L";
break;
case 1001101:
charAsci = "M";
break;
case 1001110:
charAsci = "N";
break;
case 1001111:
charAsci = "O";
break;
case 1010000:
charAsci = "P";
break;
case 1010001:
charAsci = "Q";
break;
case 1010010:
charAsci = "R";
break;
case 1010011:
charAsci = "S";
break;
case 1010100:
charAsci = "T";
break;
case 1010101:
charAsci = "U";
break;
case 1010110:
charAsci = "V";
break;
case 1010111:
charAsci = "W";
break;
case 1011000:
charAsci = "X";
break;
case 1011001:
charAsci = "Y";
break;
case 1011010:
charAsci = "Z";
break;
case 1011011:
charAsci = "[";
break;
case 1011100:
charAsci = "LOL";
break;
case 1011101:
charAsci = "]";
break;
case 1011110:
charAsci = "?";
break;
case 1011111:
charAsci = "";
break;
/*case 1100000:
charAsci = "`";
break;*/
case 1100001:
charAsci = "a";
break;
case 1100010:
charAsci = "b";
break;
case 1100011:
charAsci = "c";
break;
case 1100100:
charAsci = "d";
break;
case 1100101:
charAsci = "e";
break;
case 1100110:
charAsci = "f";
break;
case 1100111:
charAsci = "g'";
break;
case 1101000:
charAsci = "h";
break;
case 1101001:
charAsci = "i";
break;
case 1101010:
charAsci = "j";
break;
case 1101011:
charAsci = "k";
break;
case 1101100:
charAsci = "l";
break;
case 1101101:
charAsci = "m";
break;
case 1101110:
charAsci = "n";
break;
case 1101111:
charAsci = "o";
break;
case 1110000:
charAsci = "p";
break;
case 1110001:
charAsci = "q";
break;
case 1110010:
charAsci = "r";
break;
case 1110011:
charAsci = "s";
break;
case 1110100:
charAsci = "t";
break;
case 1110101:
charAsci = "u";
break;
case 1110110:
charAsci = "v";
break;
case 1110111:
charAsci = "w";
break;
case 1111000:
charAsci = "x";
break;
case 1111001:
charAsci = "y";
break;
case 1111010:
charAsci = "z";
break;
case 1111011:
charAsci = "{";
break;
case 1111100:
charAsci = "|";
break;
case 1111101:
charAsci = "}";
break;
case 1111110:
charAsci = "~";
break;
case 1111111:
charAsci = "DEL";
/*break;
case 10000000:
charAsci = "";
break;
case 10000001:
charAsci = "";
break;
case 10000010:
charAsci = "";
break;
case 10000011:
charAsci = "";
break;
case 10000100:
charAsci = "";
break;
case 10000101:
charAsci = "";
break;
case 10000110:
charAsci = "";
break;
case 10000111:
charAsci = "";
break;
case 10001000:
charAsci = "";
break;
case 10001001:
charAsci = "";
break;
case 10001010:
charAsci = "";
break;
case 10001011:
charAsci = "";
break;
case 10001100:
charAsci = "";
break;
case 10001101:
charAsci = "";
break;
case 10001110:
charAsci = "";
break;
case 10001111:
charAsci = "";
break;
case 10010000:
charAsci = "";
break;
case 10010001:
charAsci = "";
break;
case 10010010:
charAsci = "";
break;
case 10010011:
charAsci = "";
break;
case 10010100:
charAsci = "";
break;
case 10010101:
charAsci = "";
break;
case 10010110:
charAsci = "";
break;
case 10010111:
charAsci = "";
break;
case 10011000:
charAsci = "";
break;
case 10011001:
charAsci = "";
break;
case 10011010:
charAsci = "";
break;
case 10011011:
charAsci = "155";
break;
case 10011100:
charAsci = "";
break;
case 10011101:
charAsci = "";
break;
case 10011110:
charAsci = "158";
break;
case 10011111:
charAsci = "?";
break;
case 10100000:
charAsci = "";
break;
case 10100001:
charAsci = "";
break;
case 10100010:
charAsci = "";
break;
case 10100011:
charAsci = "";
break;
case 10100100:
charAsci = "";
break;
case 10100101:
charAsci = ""; */
break;
case 10100110:
charAsci = "166";
break;
case 10100111:
charAsci = "?";
/*break;
case 10101000:
charAsci = "";*/
break;
case 10101001:
charAsci = "169";
/*break;
case 10101010:
charAsci = "";*/
break;
case 10101011:
charAsci = "171";
break;
case 10101100:
charAsci = "172";
/*break;
case 10101101:
charAsci = "";*/
break;
case 10101110:
charAsci = "";
break;
case 10101111:
charAsci = "";
break;
case 10110000:
charAsci = "176";
break;
case 10110001:
charAsci = "177";
break;
case 10110010:
charAsci = "178";
break;
case 10110011:
charAsci = "179";
break;
case 10110100:
charAsci = "180";
break;
case 10110101:
charAsci = "181";
break;
case 10110110:
charAsci = "182";
break;
case 10110111:
charAsci = "183";
break;
case 10111000:
charAsci = "184";
break;
case 10111001:
charAsci = "185";
break;
case 10111010:
charAsci = "186";
break;
case 10111011:
charAsci = "187";
break;
case 10111100:
charAsci = "188";
break;
case 10111101:
charAsci = "189";
break;
case 10111110:
charAsci = "190";
break;
case 10111111:
charAsci = "191";
break;
case 11000000:
charAsci = "192";
break;
case 11000001:
charAsci = "193";
break;
case 11000010:
charAsci = "194";
break;
case 11000011:
charAsci = "195";
break;
case 11000100:
charAsci = "196";
break;
case 11000101:
charAsci = "197";
break;
case 11000110:
charAsci = "198";
break;
case 11000111:
charAsci = "199";
break;
case 11001000:
charAsci = "200";
break;
case 11001001:
charAsci = "201";
break;
case 11001010:
charAsci = "202";
break;
case 11001011:
charAsci = "203";
break;
case 11001100:
charAsci = "204";
break;
case 11001101:
charAsci = "205";
break;
case 11001110:
charAsci = "206";
break;
case 11001111:
charAsci = "207";
break;
case 11010001:
charAsci = "208";
break;
case 11010000:
charAsci = "209";
break;
case 11010010:
charAsci = "210";
break;
case 11010011:
charAsci = "211";
break;
case 11010100:
charAsci = "212";
break;
case 11010101:
charAsci = "213";
break;
case 11010110:
charAsci = "214";
break;
case 11010111:
charAsci = "215";
break;
case 11011000:
charAsci = "216";
break;
case 11011001:
charAsci = "217";
break;
case 11011010:
charAsci = "218";
break;
case 11011011:
charAsci = "219";
break;
case 11011100:
charAsci = "220";
break;
case 11011101:
charAsci = "221";
break;
case 11011110:
charAsci = "222";
break;
case 11011111:
charAsci = "223";
break;
case 11100000:
charAsci = "";
break;
case 11100010:
charAsci = "226";
/*break;
case 11100011:
charAsci = "?";
break;
case 11100100:
charAsci = "?";
break;
case 11100101:
charAsci = "229";
break;
case 11100110:
charAsci = "";*/
break;
case 11100111:
charAsci = "231";
break;
case 11101000:
charAsci = "232";
break;
case 11101001:
charAsci = "233";
/*break;
case 11101010:
charAsci = "?";*/
break;
case 11101011:
charAsci = "235";
/*break;
case 11101100:
charAsci = "?";*/
break;
case 11101101:
charAsci = "237";
break;
case 11101110:
charAsci = "238";
break;
case 11101111:
charAsci = "239";
break;
case 11110000:
charAsci = "240";
/*break;
case 11110001:
charAsci = "";
break;
case 11110010:
charAsci = "?";
break;
case 11110011:
charAsci = "?";*/
break;
case 11110100:
charAsci = "244";
break;
case 11110101:
charAsci = "245";
break;
case 11110110:
charAsci = "";
break;
case 11110111:
charAsci = "?";
break;
case 11111000:
charAsci = "?";
break;
case 11111001:
charAsci = "?";
break;
case 11111010:
charAsci = "";
/*break;
case 11111011:
charAsci = "?";*/
break;
case 11111100:
charAsci = "252";
break;
case 11111101:
charAsci = "253";
break;
case 11111110:
charAsci = "254";
break;
case 11111111:
charAsci = "255";
default:
charAsci = "";
}
return charAsci ;
} | true |
64b2e7d3ecf1f25e9311f42e8d26f62d7e70a32e | C++ | chosh95/STUDY | /BaekJoon/2020/후위 표기식2 (1935번).cpp | UTF-8 | 943 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
#include <stack>
using namespace std;
int N;
double number[26];
string origin;
stack<double> operand;
int main()
{
cin >> N;
cin >> origin;
for (int numberIndex = 0; numberIndex < N; numberIndex++)
cin >> number[numberIndex];
for (int originIndex = 0; originIndex < origin.size(); originIndex++) {
if (origin[originIndex] >= 'A' && origin[originIndex] <= 'Z')
operand.push(number[origin[originIndex] - 'A']);
else {
double lastNum = operand.top();
operand.pop();
double firstNum = operand.top();
operand.pop();
if (origin[originIndex] == '+')
operand.push(firstNum + lastNum);
else if (origin[originIndex] == '-')
operand.push(firstNum - lastNum);
else if (origin[originIndex] == '*')
operand.push(firstNum * lastNum);
else
operand.push(firstNum / lastNum);
}
}
cout << fixed;
cout.precision(2);
cout << operand.top();
} | true |
5e51fa9f9429451ee08bbeb9c9681f255dbe3148 | C++ | HimanshuSourav/Practice-Programs | /ValidParenthesis.cpp | UTF-8 | 1,526 | 3.9375 | 4 | [] | no_license | /*
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
*/
#include <stack>
class Solution {
public:
bool isStartingBracket(char ch)
{
if(
ch == '(' ||
ch == '{' ||
ch == '['
) return true;
else
return false;
}
bool isStackTopMatch(char A, char B)
{
if(
A == '(' && B == ')' ||
A == '{' && B == '}' ||
A == '[' && B == ']'
) return true;
else
return false;
}
bool isValid(string s)
{
string:: iterator it;
stack<char> st;
for(it = s.begin(); it!= s.end(); it++)
{
if(isStartingBracket(*it))
{
st.push(*it);
}
else if(!st.empty())
{
if( isStackTopMatch(st.top(),*it) )
st.pop();
else
return false;
}
else
{
return false;
}
}
if(st.empty())
return true;
else
return false;
}
};
| true |
d1ccf0f4e5fc6a1fe49e0560a81d92f7413a64fd | C++ | Emanil/Lab3 | /Task6/Task6.cpp | UTF-8 | 2,164 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int vector_Alternatives(int userInp, string wordInp, string userYN, vector<string>& vector) {
int len = 0, i = 0;
switch (userInp) {
case 1:
cout << "Are you sure? [Y/N] ";
cin >> userYN;
if (userYN == "y" || userYN == "Y") {
vector.clear();
}
break;
case 2:
while (true) {
cout << "Insert a name [Q=quit]: ";
cin >> wordInp;
if (wordInp == "q" || wordInp == "Q")
break;
else {
vector.insert(vector.end(), wordInp);
}
}
break;
case 3:
cout << "Search for a name: ";
cin >> wordInp;
len = wordInp.length(); // Lenght of the search
for (int i = 0; i < vector.size(); i++) { // Do for the whole vector
auto currentWord = vector.at(i);
for (int n = 0; n < len; n++) {
if (wordInp[n] == currentWord[n] && n == len - 1) { // If characters of the word in the vector and search are the same for len, found
cout << "Found: " << currentWord << " ";
}
}
}
break;
case 4:
cout << "Delete the name: ";
cin >> wordInp;
do {
try { // Know this from try and except in python
if (wordInp == vector.at(i)) {
vector.erase(vector.begin() + i);
cout << "Deleted!" << endl;
break;
}
}
catch (const std::exception&) { // Catch if "i" goes out of range
cout << "Not found." << endl;
break;
}
i++;
} while (wordInp != vector.at(i));
break;
case 5: // Prints every word
cout << "<";
for (auto i = vector.begin(); i != vector.end(); i++) {
cout << *i;
if (i != vector.end() - 1) {
cout << ", ";
}
}
cout << ">" << endl;
break;
case 6:
default:
return false;
}
}
int main() {
int userInp = 1;
string wordInp, userYN;
vector<string> vector;
while (userInp) {
cout << endl;
cout << "MENU:" << endl;
cout << "1: Initialise vector" << endl;
cout << "2: Insert" << endl;
cout << "3: Search" << endl;
cout << "4: Delete" << endl;
cout << "5: Print" << endl;
cout << "6: Quit" << endl;
cout << endl;
cout << "Input: ";
cin >> userInp;
userInp = vector_Alternatives(userInp, wordInp, userYN, vector);
}
return(0);
} | true |
2a0e7c93edd9e9b52657b1ebf8c2f3b989a0fd82 | C++ | Resethel/Purple-Rain | /src/GUI/Slider.cpp | UTF-8 | 7,997 | 2.828125 | 3 | [
"Unlicense"
] | permissive | //
// Slider.cpp
// Purple-Rain
//
#include "Slider.hpp"
namespace GUI
{
////////// Constructor & Destructor
Slider::Slider()
: mBody(sf::Vector2f(0,0))
, mSlider(sf::Vector2f(0,0))
, mTitle()
, mMinValue(0)
, mMaxValue(100)
, mDisplayTitle(true)
, mMinorStep(15)
, mDragOffset(0)
{
utils::centerOrigin<sf::RectangleShape>(mBody);
utils::centerOrigin<sf::RectangleShape>(mSlider);
mBody.setFillColor(mColor);
mSlider.setFillColor(mColor);
}
Slider::~Slider()
{}
////////// Methods
void Slider::handleEvent(const sf::Event& event)
{
switch( event.type )
{
case sf::Event::MouseLeft:
deselect();
break;
case sf::Event::MouseMoved:
// Check if the mouse is inside of the buttons bounds.
if(getSliderBounds().contains(event.mouseMove.x, event.mouseMove.y))
{
if(!isSelected()) // Check for entry event.
select();
}
else if(isSelected() and !isActive()) // Check for leave event.
{
deselect();
}
else if(isActive()) // mouving the slider.
{
int x = event.mouseMove.x;
//int y = event.mouseMove.y;
auto steps = (mMaxValue - mMinValue)/mMinorStep;
auto sliderRect = getSliderBounds();
auto sliderCenterX = sliderRect.left + sliderRect.width/2.f;
auto stepDistance = (getBounds().width - sliderRect.width) / steps;
auto delta = static_cast<float>(x) - sliderCenterX;// - mDragOffset;
while(delta < (-stepDistance/2))
{
//mSlider.move(-stepDistance,0);
setValue(getValue() - mMinorStep);
delta += stepDistance;
}
while(delta > (stepDistance/2))
{
//mSlider.move(stepDistance,0);
setValue(getValue() + mMinorStep);
delta -= stepDistance;
}
}
break;
case sf::Event::MouseButtonPressed:
if(getSliderBounds().contains(event.mouseButton.x, event.mouseButton.y) and !isActive())
{
activate();
// calculate drag offset
auto x = event.mouseButton.x;
mDragOffset = static_cast<float>(x) - getSliderBounds().left + getSliderBounds().width/2.f;
}
break;
case sf::Event::MouseButtonReleased:
// Only process as a click when mouse button has been pressed inside the widget before.
if(isActive())
{
// When released inside the widget, the event can be considered a click.
if(contains(event.mouseButton.x, event.mouseButton.y))
{
deactivate();
select();
}
else
{
deactivate();
deselect();
}
}
break;
case sf::Event::KeyPressed:
if( isSelected() and event.key.code == sf::Keyboard::BackSpace)
{
activate();
}
break;
case sf::Event::KeyReleased:
if( isSelected() and isActive())
{
if(event.key.code == sf::Keyboard::BackSpace)
{
deactivate();
}
}
break;
default:
break;
}
}
void Slider::activate()
{
Component::activate();
HSL col(TurnToHSL(mColor));
col.Luminance -= 10;
mSlider.setFillColor(col.TurnToRGB());
// TODO: change sprite
}
void Slider::deactivate()
{
Component::deactivate();
mSlider.setFillColor(mColor);
// TODO: change sprite
}
void Slider::select()
{
Component::select();
HSL col(TurnToHSL(mColor));
col.Luminance += 20;
mSlider.setFillColor(col.TurnToRGB());
}
void Slider::deselect()
{
Component::deselect();
mSlider.setFillColor(mColor);
}
////////// Getters
bool Slider::isSelectable() const
{
return true;
}
sf::FloatRect Slider::getBounds() const
{
sf::FloatRect bounds;
bounds = mBody.getGlobalBounds();
bounds.height = mSlider.getGlobalBounds().height;
return this->getTransform().transformRect(bounds);
}
int Slider::getValue() const
{
return mValue;
}
////////// Setters
void Slider::displayTitle(const bool& display)
{
mDisplayTitle = display;
}
void Slider::setColor(const sf::Color& color)
{
mColor = color;
HSL bodyColor = TurnToHSL(color);
HSL outlineColor = TurnToHSL(color);
bodyColor.Luminance -= 20;
outlineColor.Luminance -= 40;
mBody.setFillColor(bodyColor.TurnToRGB());
mBody.setOutlineColor(outlineColor.TurnToRGB());
outlineColor.Luminance += 20;
mSlider.setFillColor(mColor);
mSlider.setOutlineColor(outlineColor.TurnToRGB());
}
void Slider::setSize(const sf::Vector2f& size)
{
auto bodySize = size;
bodySize.y *= 2/5.f;
mBody.setSize(bodySize);
auto sliderSize = size;
sliderSize.x /= 10.f;
mSlider.setSize(sliderSize);
mBody.setOutlineThickness(std::ceil(bodySize.y/20.f));
mSlider.setOutlineThickness(std::ceil(bodySize.y/20.f));
utils::centerOrigin<sf::RectangleShape>(mBody);
utils::centerOrigin<sf::RectangleShape>(mSlider);
positionTitle();
}
void Slider::setStep(const int& step)
{
mMinorStep = step;
}
void Slider::setRange(const int& min, const int& max)
{
mMinValue = min;
mMaxValue = max;
}
void Slider::setTitleFont(const sf::Font &font)
{
mTitle.setFont(font);
positionTitle();
}
void Slider::setTitleCharacterSize(const unsigned& size)
{
mTitle.setCharacterSize(size);
positionTitle();
}
void Slider::setTitleString(const std::string& text)
{
mTitle.setString(text);
positionTitle();
}
void Slider::setValue(const int& value)
{
mValue = utils::clamp<int>(value, mMinValue, mMaxValue);
auto step = (getBounds().width - getSliderBounds().width) / (mMaxValue - mMinValue);
mSlider.setPosition(mBody.getGlobalBounds().left + getSliderBounds().width/2.f + mValue*step , 0);
}
////////// Internal Handling
sf::FloatRect Slider::getSliderBounds() const
{
return this->getTransform().transformRect(mSlider.getGlobalBounds());
}
void Slider::positionTitle()
{
if(mTitle.getFont())
{
utils::centerOrigin<sf::Text>(mTitle);
auto origin = mTitle.getOrigin();
auto height = mTitle.getGlobalBounds().height;
mTitle.setOrigin(0, origin.y);
mTitle.setPosition(-mBody.getOrigin().x, -((getBounds().height + height)/2.f + 5));
}
}
////////// Draw
void Slider::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= this->getTransform();
target.draw(mBody, states);
target.draw(mSlider, states);
if(mDisplayTitle)
target.draw(mTitle, states);
}
}
| true |
8cfa5960d24db7936db9d4e922ea92acb2d4b56d | C++ | UzL-ITS/cipherfix | /taint-tracking/src/bdd_tag.cpp | UTF-8 | 5,156 | 2.734375 | 3 | [
"MIT"
] | permissive | // TODO: support multiple thread
#include "bdd_tag.h"
#include "debug.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stack>
#define VEC_CAP (1 << 16)
#define LB_WIDTH BDD_LB_WIDTH
#define MAX_LB ((1 << LB_WIDTH) - 1)
#define LB_MASK MAX_LB
#define LEN_LB BDD_LEN_LB
#define ROOT 0
BDDTag::BDDTag() {
nodes.reserve(VEC_CAP);
nodes.emplace_back(ROOT, 0, 0);
};
BDDTag::~BDDTag()= default;;
lb_type BDDTag::alloc_node(lb_type parent, tag_off begin, tag_off end) {
lb_type lb = nodes.size();
if (lb < MAX_LB) {
nodes.emplace_back(parent, begin, end);
return lb;
} else {
return ROOT;
}
}
lb_type BDDTag::insert_n_zeros(lb_type cur_lb, size_t num,
lb_type last_one_lb) {
while (num != 0) {
lb_type next = nodes[cur_lb].left;
size_t next_size = nodes[next].get_seg_size();
if (next == 0) {
tag_off off = nodes[cur_lb].seg.end;
lb_type new_lb = alloc_node(last_one_lb, off, off + num);
nodes[cur_lb].left = new_lb;
cur_lb = new_lb;
num = 0;
} else if (next_size > num) {
tag_off off = nodes[cur_lb].seg.end;
lb_type new_lb = alloc_node(last_one_lb, off, off + num);
nodes[cur_lb].left = new_lb;
cur_lb = new_lb;
nodes[next].seg.begin = off + num;
num = 0;
} else {
cur_lb = next;
num -= next_size;
}
}
return cur_lb;
}
lb_type BDDTag::insert_n_ones(lb_type cur_lb, size_t num, lb_type last_one_lb) {
while (num != 0) {
lb_type next = nodes[cur_lb].right;
tag_off last_end = nodes[cur_lb].seg.end;
if (next == 0) {
tag_off off = last_end;
lb_type new_lb = alloc_node(last_one_lb, off, off + num);
nodes[cur_lb].right = new_lb;
cur_lb = new_lb;
num = 0;
} else {
tag_off next_end = nodes[next].seg.end;
size_t next_size = next_end - last_end;
if (next_size > num) {
tag_off off = last_end;
lb_type new_lb = alloc_node(last_one_lb, off, off + num);
nodes[cur_lb].right = new_lb;
nodes[new_lb].right = next;
nodes[next].parent = new_lb;
nodes[next].seg.begin = off + num;
cur_lb = new_lb;
num = 0;
} else {
cur_lb = next;
num -= next_size;
}
}
}
return cur_lb;
}
lb_type BDDTag::insert(tag_off pos) {
lb_type cur_lb = insert_n_zeros(ROOT, pos, ROOT);
cur_lb = insert_n_ones(cur_lb, 1, ROOT);
return cur_lb;
}
void BDDTag::set_sign(lb_type lb) { nodes[lb].seg.sign = true; }
bool BDDTag::get_sign(lb_type lb) { return nodes[lb].seg.sign; }
void BDDTag::set_size(lb_type lb, size_t size) {
nodes[lb].seg.end += (size - 1);
}
lb_type BDDTag::combine(lb_type l1, lb_type l2) {
if (l1 == 0)
return l2;
if (l2 == 0 || l1 == l2)
return l1;
bool has_len_lb = BDD_HAS_LEN_LB(l1) || BDD_HAS_LEN_LB(l2);
l1 = l1 & LB_MASK;
l2 = l2 & LB_MASK;
if (l1 > l2) {
lb_type tmp = l2;
l2 = l1;
l1 = tmp;
}
// get all the segments
std::stack<lb_type> lb_st;
lb_type last_begin = MAX_LB;
while (l1 > 0 && l1 != l2) {
tag_off b1 = nodes[l1].seg.begin;
tag_off b2 = nodes[l2].seg.begin;
if (b1 < b2) {
if (b2 < last_begin) {
lb_st.push(l2);
last_begin = b2;
}
l2 = nodes[l2].parent;
} else {
if (b1 < last_begin) {
lb_st.push(l1);
last_begin = b1;
}
l1 = nodes[l1].parent;
}
}
lb_type cur_lb;
if (l1 > 0) {
cur_lb = l1;
} else {
cur_lb = l2;
}
while (!lb_st.empty()) {
tag_seg cur_seg = nodes[cur_lb].seg;
lb_type next = lb_st.top();
lb_st.pop();
tag_seg next_seg = nodes[next].seg;
if (cur_seg.end >= next_seg.begin) {
if (next_seg.end > cur_seg.end) {
size_t size = next_seg.end - cur_seg.end;
cur_lb = insert_n_ones(cur_lb, size, cur_lb);
}
} else {
lb_type last_lb = cur_lb;
size_t gap = next_seg.begin - cur_seg.end;
cur_lb = insert_n_zeros(cur_lb, gap, last_lb);
size_t size = next_seg.end - next_seg.begin;
cur_lb = insert_n_ones(cur_lb, size, last_lb);
}
if (next_seg.sign) {
nodes[cur_lb].seg.sign = true;
}
}
if (has_len_lb) {
cur_lb |= LEN_LB;
}
return cur_lb;
}
const std::vector<tag_seg> BDDTag::find(lb_type lb) {
lb = lb & LB_MASK;
std::vector<tag_seg> tag_list;
tag_off last_begin = MAX_LB;
while (lb > 0) {
if (nodes[lb].seg.begin < last_begin) {
tag_list.push_back(nodes[lb].seg);
last_begin = nodes[lb].seg.begin;
}
lb = nodes[lb].parent;
}
if (tag_list.size() > 1) {
std::reverse(tag_list.begin(), tag_list.end());
}
return tag_list;
};
std::string BDDTag::to_string(lb_type lb) {
lb = lb & LB_MASK;
std::string ss = "";
ss += "{";
std::vector<tag_seg> tags = find(lb);
char buf[100];
for (auto & tag : tags) {
sprintf(buf, "(%d, %d) ", tag.begin, tag.end);
std::string s(buf);
ss += s;
}
ss += "}";
return ss;
}
void BDDTag::clearAll() {
nodes.clear();
nodes.reserve(VEC_CAP);
nodes.emplace_back(ROOT, 0, 0);
}
| true |
ec954912e357e217edff2eeb8476b9ab2d8c1ca9 | C++ | zeta1999/minicore | /include/minicore/util/exception.h | UTF-8 | 3,819 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef FGC_EXCEPTION_H__
#define FGC_EXCEPTION_H__
#include <stdexcept>
#include <string>
#include <iostream> // for std::cerr;
namespace minicore {
inline namespace exception {
struct verbose_runtime_error: public std::runtime_error {
// Sometimes exception messages aren't emitted by the stdlib, so we're ensuring they are
template<typename...A>
verbose_runtime_error(A &&...a): std::runtime_error(std::forward<A>(a)...) {
std::cerr << "What: " << this->what() << '\n';
}
};
class NotImplementedError: public verbose_runtime_error {
public:
template<typename... Args>
NotImplementedError(Args &&...args): verbose_runtime_error(std::forward<Args>(args)...) {}
NotImplementedError(): verbose_runtime_error("NotImplemented.") {}
};
class UnsatisfiedPreconditionError: public verbose_runtime_error {
public:
UnsatisfiedPreconditionError(std::string msg): verbose_runtime_error(std::string("Unsatisfied precondition: ") + msg) {}
UnsatisfiedPreconditionError(): verbose_runtime_error("Unsatisfied precondition.") {}
};
static int require(bool condition, std::string s, int ec=0) {
if(!condition) {
if(ec) throw verbose_runtime_error(s + " Error code: " + std::to_string(ec));
else throw verbose_runtime_error(s);
}
return ec;
}
static int validate(bool condition, std::string s, int ec=0) {
if(!condition) {
if(ec) throw std::invalid_argument(s + " Error code: " + std::to_string(ec));
else throw std::invalid_argument(s);
}
return ec;
}
static int precondition_require(bool condition, std::string s, int ec=0) {
if(!condition) {
if(ec) throw UnsatisfiedPreconditionError(s + " Error code: " + std::to_string(ec));
else throw UnsatisfiedPreconditionError(s);
}
return ec;
}
class UnsatisfiedPostconditionError: public verbose_runtime_error {
public:
UnsatisfiedPostconditionError(std::string msg): verbose_runtime_error(std::string("Unsatisfied precondition: ") + msg) {}
UnsatisfiedPostconditionError(): verbose_runtime_error("Unsatisfied precondition.") {}
};
static int postcondition_require(bool condition, std::string s, int ec=0) {
if(!condition) {
if(ec) throw UnsatisfiedPostconditionError(s + " Error code: " + std::to_string(ec));
else throw UnsatisfiedPostconditionError(s);
}
return ec;
}
#ifndef MN_THROW_RUNTIME
#define MN_THROW_RUNTIME(x) do { std::cerr << x; std::exit(1);} while(0)
#endif
#ifndef PREC_REQ_EC
#define PREC_REQ_EC(condition, s, ec) \
::minicore::exception::precondition_require(condition, std::string(s) + '[' + __FILE__ + '|' + __PRETTY_FUNCTION__ + "|#L" + std::to_string(__LINE__) + "] Failing condition: \"" + #condition + '"', ec)
#endif
#ifndef PREC_REQ
#define PREC_REQ(condition, s) PREC_REQ_EC(condition, s, 0)
#endif
#ifndef POST_REQ_EC
#define POST_REQ_EC(condition, s, ec) \
::minicore::exception::postcondition_require(condition, std::string(s) + '[' + __FILE__ + '|' + __PRETTY_FUNCTION__ + "|#L" + std::to_string(__LINE__) + "] Failing condition: \"" + #condition + '"', ec)
#endif
#ifndef POST_REQ
#define POST_REQ(condition, s) POST_REQ_EC(condition, s, 0)
#endif
#ifndef MINOCORE_REQUIRE
#define MINOCORE_REQUIRE(condition, s) \
::minicore::exception::require(condition, std::string(s) + '[' + __FILE__ + '|' + __PRETTY_FUNCTION__ + "|#L" + std::to_string(__LINE__) + "] Failing condition: \"" + #condition + '"')
#endif
#ifndef MINOCORE_VALIDATE
#define MINOCORE_VALIDATE(condition) \
::minicore::exception::validate(condition, std::string("[") + __FILE__ + '|' + __PRETTY_FUNCTION__ + "|#L" + std::to_string(__LINE__) + "] Failing condition: \"" + #condition + '"')
#endif
} // inline namespace exception
} // namespace minicore
#endif /* FGC_EXCEPTION_H__ */
| true |
c9ed3c57b6b307103f241d48038b5db3d9de3047 | C++ | justdone32/EvHttpServer | /evhttpserver/EvHttpThread.cpp | UTF-8 | 1,569 | 2.546875 | 3 | [] | no_license | #include "EvHttpServer.h"
#include "EvHttpThread.h"
namespace ustd
{
// public
EvHttpThread::EvHttpThread (const evutil_socket_t& evsock, EvHttpServer* server)
: http_server_ (nullptr)
, evbase_ (nullptr)
, evsock_ (evsock)
, server_ (server)
, has_start_ (false)
{
}
EvHttpThread::~EvHttpThread (void)
{
stop ();
}
void
EvHttpThread::run (void)
{
evbase_ = event_base_new();
const int flags = LEV_OPT_REUSEABLE | LEV_OPT_THREADSAFE;
evconnlistener* listener = evconnlistener_new (evbase_, nullptr, nullptr, flags, 0, evsock_);
if(!listener)
{
printf("listen port error");
return;
}
http_server_ = evhttp_new (evbase_);
evhttp_set_max_headers_size (http_server_, server_->getMaxHeadersSize ());
evhttp_set_max_body_size (http_server_, server_->getMaxBodySize ());
evhttp_set_allowed_methods(http_server_, EVHTTP_REQ_POST);
evhttp_bound_socket* bound_socket = evhttp_bind_listener (http_server_, listener);
if (!bound_socket)
{
printf("bind error");
return;
}
server_->registerCallbacks (http_server_);
evconnlistener_enable (listener);
has_start_ = true;
event_base_dispatch (evbase_);
}
bool
EvHttpThread::hasStart (void)
{
return has_start_;
}
void
EvHttpThread::stop (void)
{
if (!has_start_)
{
return;
}
if (evbase_)
{
event_base_loopexit (evbase_, nullptr);
}
if (http_server_)
{
evhttp_free (http_server_);
http_server_ = nullptr;
}
if (evbase_)
{
event_base_free (evbase_);
evbase_ = nullptr;
}
}
void
EvHttpThread::waitUntilStart (void)
{
while (!hasStart ())
{
pthread_yield();
}
}
} | true |
4e3b0b6fe5a7958d2e472f4b65827d3ce5a0caef | C++ | mohandarsi/CPlusPlus | /EmScripten/Tetris/src/Game.h | UTF-8 | 524 | 2.65625 | 3 | [] | no_license | #pragma once
#include "raylib-cpp.hpp"
#include<memory>
#include "Board.h"
#include "Block.h"
#include "Timer.h"
class Game
{
public:
Game(int width, int height);
void run();
void gameLoop();
private:
void input();
void update();
void draw();
void drawBlock();
bool moveCurrentBlock(const raylib::Vector2& normalizedPosition);
void placeCurrentBlock();
private:
raylib::Window m_window;
Board m_board;
std::unique_ptr<Block> m_currentBlock;
Timer m_slideTimer;
Timer m_xmoveTimer;
Timer m_ymoveTimer;
};
| true |
2a14d21da3b78a92a6d1d860d4e8aef61fe84aa5 | C++ | Andrew22674/examen2clase | /Cuadrado.h | UTF-8 | 293 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Figura.h"
class Cuadrado : public Figura{
private:
double base;
double altura;
public:
Cuadrado();
//recibe solo un double porque la base y la altura van a ser igual
Cuadrado(string, double);
string toString();
double Area();
virtual ~Cuadrado();
};
| true |
a76b5b1ffbaea4ff7d082911d0b8441a34b9c87d | C++ | Job-Colab/Coding-Preparation | /Day-124/Lawrance.cpp | UTF-8 | 273 | 2.59375 | 3 | [] | no_license | int solve(vector<int>& prices, int k) {
int ans = 0;
sort(prices.begin(), prices.end());
for(int i : prices) {
k -= i;
if(k < 0) break;
else ++ans;
}
return ans;
}
// This can be further optimized by using quickselect algorithm
| true |
ddde1dddcb89ebc213ed9ce220e64aa77dbfb292 | C++ | anvesh649/programming-revamp | /InterviewBit/Arrays/Find Permutation.cpp | UTF-8 | 1,226 | 3.40625 | 3 | [] | no_license | void swap_array(vector<int> &A, int start, int end)
{
int n = (end - start) + 1;
for(int i = 0; i < n/2; i++)
{
swap(A[start], A[end]);
start++;
end--;
}
}
vector<int> Solution::findPerm(const string A, int B) {
vector<int> result;
int start = 0, end = 0;
for(int i = 0; i < B; i++)
{
result.push_back(i + 1);
}
for(int i = 0; i < B - 1; i++)
{
if(A[i] == 'D')
{
start = i;
end = i;
while((i < B - 1) && A[i] == 'D')
{
end = i;
i++;
}
swap_array(result, start, end + 1);
}
}
return result;
}
// Another Solution:
vector Solution::findPerm(const string A, int B) {
vector<int> result;
int current_smallest = 1;
int current_largest = B;
for(int i = 0; i < A.size(); i++){
if(A[i] == 'I'){
result.push_back(current_smallest);
current_smallest++;
}else{
result.push_back(current_largest);
current_largest--;
}
}
if(A[ A.size() - 1] == 'I'){
result.push_back(current_smallest);
}else{
result.push_back(current_largest);
}
return result;
}
| true |
ec51e93553a2e431fc8a5f653e9ad731360e29de | C++ | TheMecz/ATS_programming | /1_Introduccion_entrada_y_salida/Ejercicio_1.cpp | UTF-8 | 540 | 4 | 4 | [] | no_license | /*Ejericio 1. Escriba un programa que lea de la entrada estándar dos números y muestre en la salida estándar su suma,
* resta, multiplicación y división.
* */
#include <iostream>
using namespace std;
int main() {
float num1, num2;
cout<<"Digite un numero: "; cin>>num1;
cout<<"Digite otro numero: "; cin>>num2;
cout<<"La suma es: "<<num1+num2<<endl;
cout<<"La resta es: "<<num1-num2<<endl;
cout<<"La multiplicacion es: "<<num1*num2<<endl;
cout<<"La division es: "<<num1/num2<<endl;
return 0;
}
| true |
a577441f365adf0655c11a2052482c06cda8db36 | C++ | taejin0323/Algorithm_Study | /programmer/07.collatz.cpp | UTF-8 | 361 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int collatz(long num)
{
int answer = 0;
while (num > 1) {
if (num % 2 == 0) {
num = num / 2;
}
else {
num = (num * 3) + 1;
}
answer++;
if (answer == 500) {
answer = -1;
break;
}
}
return answer;
}
int main()
{
int testCase = 6;
int testAnswer = collatz(testCase);
cout << testAnswer;
} | true |
a579cd86e303ad822c567378ca7958e95560b162 | C++ | LuckyResistor/CatProtect | /CatProtect/SDCard.h | UTF-8 | 4,266 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
//
// A SD-Card Access library for asynchronous timed access in timer interrupts
// --------------------------------------------------------------------------
// (c)2014 by Lucky Resistor. http://luckyresistor.me
// Licensed under the MIT license. See file LICENSE for details.
//
//
// I developed this library to allow perfectly timed audio output, which
// requires that the data from the SD card is loaded in small chunks to
// create the right timing when playing the samples.
//
// This library assumes the chip select for the SD-Card is on Pin 10.
// The library is tested with the AdaFruit Data Logging Shield.
//
#include <SPI.h>
/// Enable debugging via Serial. You have to setup the serial port before calling initialize().
///
//#define SDCARD_DEBUG
/// Use the SPI transactions for all read calls.
/// If not defined, it is assumed one huge SPI.transaction for the whole read process.
/// Only the CS signal is handled.
///
//#define SDCARD_USE_SPI_TRANSACTIONS
namespace lr {
/// The SD Card access class for asynchronous SD Card access.
///
class SDCard
{
public:
/// Errors
///
enum Error : uint8_t {
NoError = 0,
Error_TimeOut = 1,
Error_SendIfCondFailed = 2,
Error_ReadOCRFailed = 3,
Error_SetBlockLengthFailed = 4,
Error_ReadSingleBlockFailed = 5,
Error_ReadFailed = 6,
Error_UnknownMagic = 7,
};
/// The status of a command.
///
enum Status : uint8_t {
StatusReady = 0, ///< The call was successful and the card is ready.
StatusWait = 1, ///< You have to wait, the card is busy
StatusError = 2, ///< There was an error. Check error() for details.
StatusEndOfBlock = 3, ///< Reached the end of the block.
};
/// A single directory entry.
///
struct DirectoryEntry {
uint32_t startBlock; ///< The start block of the file in blocks.
uint32_t fileSize; ///< The size of the file in bytes.
char *fileName; ///< Null terminated filename ascii.
DirectoryEntry *next; ///< The next entry, or a null pointer at the end.
};
public:
/// Initialize the library and the SD-Card.
/// This call needs some time until the SD-Card is ready for read. It
/// should be placed in the setup() method.
///
/// @return StatusReady on succes, StatusError on any error.
///
Status initialize();
/// Read the SD Card Directory in HCDI format
///
/// @return StatusReady on success, StatusError on any error.
///
Status readDirectory();
/// Find a file with the given name
///
/// @return The found directory entry, or 0 if no such file was found.
///
const DirectoryEntry* findFile(const char *fileName);
/// Start reading the given block.
///
/// @param block The block in (512 byte blocks).
/// @return StatusWait = call again, StatusError = there was an error,
/// StatusReady = reading of the block has started, call readData().
///
Status startRead(uint32_t block);
/// Start reading from given block until stopRead() is called.
///
/// @param startBlock The first block in (512 byte blocks).
/// @return StatusWait = call again, StatusError = there was an error,
/// StatusReady = reading of the block has started, call readData().
///
Status startMultiRead(uint32_t startBlock);
/// Read data if ready.
///
/// @param buffer The buffer to read the data into.
/// @param byteCount in: The number of bytes to read, out: the actual number of read bytes.
/// @return StatusReady on success, StatusError is there was an error,
/// StatusEndOfBlock if the end of the block was reached.
///
Status readData(uint8_t *buffer, uint16_t *byteCount);
/// Start the fast reading.
///
void startFastRead();
/// Super fast data multi read.
///
/// For extreme situations. It always reads 4 bytes to the given address.
///
/// @param buffer A pointer to the buffer to write 4 bytes.
/// @return StatusWait if no bytes were written, StatusReady if bytes were written.
///
Status readFast4(uint8_t *buffer);
/// End reading data.
///
/// You have to call this method in any case. This is a blocking call and
/// and can take a while.
///
/// @return StatusReady = success, block read ended.
///
Status stopRead();
/// Get the last error
///
Error error();
};
/// The global instance to access the SD Card
///
extern SDCard sdCard;
}
| true |
ffb0f27bf4f199a1f3bbfafb853a76be3e7c2bc8 | C++ | kenschenke/Mak_Writing_Compilers_and_Interpreters | /Mak_Writing_Compiler_2nd_Ed/Chapter07/Ver_1/XREF2.CPP | UTF-8 | 2,317 | 2.578125 | 3 | [] | no_license | //fig 7-15
// *************************************************************
// * *
// * Program 7-1: Cross-Referencer II *
// * *
// * Generate a cross-reference listing that includes *
// * information about each identifier. *
// * *
// * FILE: prog7-1/xref2.cpp *
// * *
// * USAGE: xref2 <source file> *
// * *
// * <source file> name of the source file *
// * *
// * -x turn on cross-referencing *
// * *
// * Copyright (c) 1996 by Ronald Mak *
// * For instructional purposes only. No warranties. *
// * *
// *************************************************************
#include <iostream.h>
#include <string.h>
#include "common.h"
#include "error.h"
#include "buffer.h"
#include "symtab.h"
#include "parser.h"
//--------------------------------------------------------------
// main
//--------------------------------------------------------------
void main(int argc, char *argv[])
{
extern int xrefFlag;
//--Check the command line arguments.
if ((argc != 2) && (argc != 3)) {
cerr << "Usage: xref2 <source file> [-x]" << endl;
AbortTranslation(abortInvalidCommandLineArgs);
}
//--Set the cross-referencing flag.
xrefFlag = (argc == 3) && (strcmp(argv[2], "-x") == 0);
//--Create the parser for the source file,
//--and then parse the file.
TParser *pParser = new TParser(new TSourceBuffer(argv[1]));
pParser->Parse();
delete pParser;
//--Print the cross-reference.
if (xrefFlag) {
list.PutLine();
list.PutLine("***** Cross-Reference *****");
list.PutLine();
globalSymtab.Print();
}
}
//endfig
| true |
def02453401b85530b7c1d91904e71518a758987 | C++ | Haecriver/ProjetISIMA-dotr | /src/line.hpp | UTF-8 | 1,810 | 2.984375 | 3 | [] | no_license | #ifndef LINE_HPP
#define LINE_HPP
#include <vector>
#include <iostream>
#include <vector>
#include <algorithm>
#include "linePoint.hpp"
#include "axe.hpp"
class Line{
private:
std::vector<LinePoint*> pts; // Liste des points passant par cette droite
long double a; // Coefficient a de l'equation y = ax + b
long double b; // Biais de l'equation y = ax + b
long double theta;
Point pivot;
Point other;
const static unsigned NB_POINTS = 4; // Nombre de points contenus par droite
constexpr static double EPSILON_THETA = 2.0; // Marge erreur
constexpr static double EPSILON_THETA_MAX = 3.0; // Marge erreur max
constexpr static double EPSILON_CROSS_RATIO = 0.20;
double crossRatio; // Cross ratio de la droite
const Axe* axe;
public:
// Contructeurs
Line();
Line(double pA, double pB);
Line(Point p1, Point p2);
bool getIncludedPoints(std::vector<LinePoint>& allPoints, bool careBelongsToLine=true);
bool getIncludedPointsPolar(std::vector<LinePoint>& allPoints);
bool sameCrossRatio(double pCrossRatio, double epsilon = EPSILON_CROSS_RATIO) const{
return (crossRatio > pCrossRatio - epsilon)
&& (crossRatio < pCrossRatio + epsilon);
}
void computeCrossRatio();
double getCrossRatio(){
return crossRatio;
}
void setAxe(const Axe* paxe){
axe = paxe;
}
const Axe* getAxe(){
return axe;
}
// Setter/Getter
const std::vector<LinePoint*>& getPts() const{
return pts;
}
// Setter/Getter
void setPts(std::vector<LinePoint*> ppts){
pts.clear();
for(unsigned i=0; i<ppts.size() ; i++){
pts.push_back(ppts[i]);
}
}
bool firstPointsHasGoodRatio(double ratioPoint);
void reversePoints(){
std::reverse(pts.begin(),pts.end());
}
};
#endif
| true |
bded18aaf73a915cc94c5c49ac27e369b1e7f488 | C++ | bar4411/DIJKSTERA | /main.cpp | UTF-8 | 316 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include "Graph.cpp"
#include "Graph.h"
using namespace std;
int main() {
int size;
cout << "Enter the size of graph: ";
cin >>size;
Graph g(size);
//g.dijisktra(1);
cout << "The average shortest path in a graph is: " << g.getAvergeShortestPaths()<<endl;
return 0;
} | true |
1f5ca965617e88bce557f93bfe67e1f9b57e77da | C++ | chromium/chromium | /chrome/browser/offline_items_collection/offline_content_aggregator_factory.h | UTF-8 | 1,922 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_OFFLINE_ITEMS_COLLECTION_OFFLINE_CONTENT_AGGREGATOR_FACTORY_H_
#define CHROME_BROWSER_OFFLINE_ITEMS_COLLECTION_OFFLINE_CONTENT_AGGREGATOR_FACTORY_H_
#include <memory>
#include "components/keyed_service/core/simple_keyed_service_factory.h"
class SimpleFactoryKey;
namespace base {
template <typename T>
class NoDestructor;
} // namespace base
namespace offline_items_collection {
class OfflineContentAggregator;
} // namespace offline_items_collection
// This class is the main access point for an OfflineContentAggregator. It is
// responsible for building the OfflineContentAggregator and associating it with
// a particular SimpleFactoryKey.
class OfflineContentAggregatorFactory : public SimpleKeyedServiceFactory {
public:
// Returns a singleton instance of an OfflineContentAggregatorFactory.
static OfflineContentAggregatorFactory* GetInstance();
// Returns the OfflineContentAggregator associated with |key| or creates and
// associates one if it doesn't exist.
static offline_items_collection::OfflineContentAggregator* GetForKey(
SimpleFactoryKey* key);
OfflineContentAggregatorFactory(const OfflineContentAggregatorFactory&) =
delete;
OfflineContentAggregatorFactory& operator=(
const OfflineContentAggregatorFactory&) = delete;
private:
friend base::NoDestructor<OfflineContentAggregatorFactory>;
OfflineContentAggregatorFactory();
~OfflineContentAggregatorFactory() override;
// SimpleKeyedServiceFactory implementation.
std::unique_ptr<KeyedService> BuildServiceInstanceFor(
SimpleFactoryKey* key) const override;
SimpleFactoryKey* GetKeyToUse(SimpleFactoryKey* key) const override;
};
#endif // CHROME_BROWSER_OFFLINE_ITEMS_COLLECTION_OFFLINE_CONTENT_AGGREGATOR_FACTORY_H_
| true |
d4c7c4e14f7ebe99924e8ea01637b114dd46aab0 | C++ | MKCA06/SDE_Sheet_Striver | /Day-17_Binary_Tree/right_view.cpp | UTF-8 | 707 | 3.625 | 4 | [] | no_license | /*
Problem Link: https://leetcode.com/problems/binary-tree-right-side-view/
*/
void findRightView(TreeNode* root, int level, int &max_level, vector<int> &results) {
// base case
if(!root)
return;
// new node (rightmost) of each new level
if(level > max_level) {
results.push_back(root->val);
max_level = level;
}
// recursive calls: right subtree first
findRightView(root->right, level + 1, max_level, results);
findRightView(root->left, level + 1, max_level, results);
}
vector<int> rightSideView(TreeNode* root) {
int max_level = -1;
vector<int> results;
findRightView(root, 0, max_level, results);
return results;
} | true |
75eee43b548437a7d59e742d1c82c3656848d399 | C++ | KuboCh/RUN-LISP | /LISP-Interpreter/False.cpp | UTF-8 | 290 | 2.6875 | 3 | [] | no_license | #include "False.h"
#include "DataType.h"
#include "Environment.h"
False::False() {
}
False::False(const False& orig) {
}
False::~False() {
}
/*
* False is (surprisingly) false.
*/
DataType* False::eval(Environment* e) {
return this;
}
void False::print(){
cout << "false";
}
| true |
3e1c0286ae3d12b63ad32823528b22302c246987 | C++ | exapde/Exasim | /Applications/NavierStokes/OAT15A/sources/exasim4.0/kernel/solution/solution.h | UTF-8 | 1,038 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef __SOLUTION_H__
#define __SOLUTION_H__
class CSolution {
private:
public:
CDiscretization disc; // spatial discretization class
CPreconditioner prec; // precondtioner class
CSolver solv; // linear and nonlinear solvers
// constructor
CSolution(string filein, string fileout, Int mpiprocs, Int mpirank, Int ompthreads, Int omprank, Int backend)
: disc(filein, fileout, mpiprocs, mpirank, ompthreads, omprank, backend),
prec(disc, backend),
solv(disc, backend){ };
// destructor
~CSolution(){ };
// solve steady-state problems
void SteadyProblem(Int backend);
// advance the solution to the next time step using DIRK and BDF schemes
void TimeStepping(dstype time, Int istep, Int backend);
// solve time-dependent problems
void UnsteadyProblem(Int backend);
// solve both steady-state and time-dependent problems
void SolveProblem(Int backend);
};
#endif
| true |
ed0292cc19f30e1fee8d503dc658a29d98b4de24 | C++ | Chlebnik/KIV-OS | /src/kivos.cpp | UTF-8 | 2,967 | 2.671875 | 3 | [] | no_license | // HelloWorld2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
int main()
{
Kernel kernelInstance;
Kernel *kernel = &kernelInstance;
File* initialDrive = kernel->LoadFileSystem();
/*cout << response << endl;
cout << initialDrive->GetAbsolutePath() << endl;
cout << response << endl;
cout << subfolder1->GetAbsolutePath() << endl;
File* subfolder2 = kernel->CreateNewFile("sub2", FOLDER_ATT, subfolder1, response);
cout << response << endl;
cout << subfolder2->GetAbsolutePath() << endl;
File* tmpDrive = kernel->GetFile("c:/", NULL, response);
cout << response << "tmp drive" << endl;
cout << tmpDrive->GetAbsolutePath() << endl;
vector<File*> files = tmpDrive->GetChildren();
for (vector<File*>::iterator iterator = files.begin(); iterator != files.end(); ++iterator)
{
cout << "*****************" << endl;
cout << (*iterator)->GetName() << endl;
cout << "*****************" << endl;
}
File* tmp = kernel->GetFile("c:/sub1", NULL, response);
cout << response << endl;
cout << tmp->GetAbsolutePath() << endl;
File* tmp2 = kernel->GetFile("c:/sub1/sub2", NULL, response);
cout << response << endl;
cout << tmp2->GetAbsolutePath() << endl;
response = kernel->RemoveFile(tmp2);
cout << response << endl;
if (tmp2 != NULL)
{
cout << "Weird" << endl;
}
else
{
cout << "OK" << endl;
}
AbstractInput* input = new StandardInput(kernel);
AbstractOutput* output = new StandardOutput(kernel);
AbstractOutput* errorOutput = new StandardOutput(kernel);
shared_ptr<ofstream> fileOutput(new ofstream("D:/testOut.txt"));
AbstractOutput* outputFile = new FileOutput(fileOutput, kernel);
shared_ptr<ifstream> fileInput(new ifstream("D:/test.txt"));
if (!fileInput)
{
// todo error
exit(1);
}*/
//AbstractInput* input = new FileInput(fileInput, kernel);
int shellPid = kernel->Execute(0, initialDrive, "shell", "", STANDARD_TYPE, "", STANDARD_TYPE, "");
vector<int> tmpVector;
tmpVector.push_back(shellPid);
kernel->WaitForChildren(tmpVector);
/*AbstractProcess* cd = new Shell(1, 0, kernel);
cd->Init(input, output, errorOutput, "");
cd->Run();
cd->Join();*/
//
/*AbstractProcess* shell = new Shell(0, kernel);
shell->Init(input2, output, errorOutput, {});
shell->Run();*/
/*AbstractProcess* sortProcess = new Sort(0, kernel);
sortProcess->Init(input, output, errorOutput, {});
sortProcess->Run();*/
//AbstractInput* inputPipe = new PipeInput(1, kernel);
//AbstractOutput* outputPipe = new PipeOutput(1, kernel);
//Pipe* pipe = new Pipe()
//pipeMap[1] = pipe;
//AbstractProcess* randProcess = new Rand(0, kernel);
//AbstractProcess* sortProcess = new Sort(1, kernel);
//randProcess->Init(input, outputPipe, errorOutput, {});
//sortProcess->Init(inputPipe, outputFile, errorOutput, {});
//thread t1(&AbstractProcess::Run,randProcess);
//thread t2(&AbstractProcess::Run, sortProcess);
//t1.join();
//t2.join();
return 0;
}
| true |
924561db7bf32c8839c39e1d7c756be2c95704fe | C++ | Hanseunghoon/TAVE_4_2_Algorithm_study | /HSH/1주차/설탕배달.cpp | UTF-8 | 248 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
int main() {
int s, B = 0;
scanf("%d", &s);
while (1) {
if (s % 5 == 0) {
printf("%d", s / 5 + B);
break;
}
else if (s <= 0) {
printf("-1");
break;
}
s -= 3;
B++;
}
return 0;
} | true |
c7dba0b26c46b72447ca048188075f74f49e2bbd | C++ | DamienHenderson/GEC-Engine | /HAPI_Start/Quad.hpp | UTF-8 | 424 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "FrameBuffer.hpp"
#include "Types.hpp"
#include "Utils.hpp"
#ifndef QUAD_HPP
#define QUAD_HPP
class Quad
{
public:
Quad(const Vertex& v1, const Vertex& v2, const Vertex& v3, const Vertex& v4, vec4 < u8 > colour) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), colour_(colour)
{
}
void Render(FrameBuffer & fb) const;
private:
vec4 < u8 > colour_;
Vertex v1_, v2_, v3_, v4_;
};
#endif // !QUAD_HPP
| true |
745b686183b236ae71dc9b502e4ee9c7aa5865ff | C++ | librahu/Algorithm | /leetcode/leetcode_10.cpp | UTF-8 | 1,299 | 3.21875 | 3 | [] | no_license | /**
* Solution : dp
* 1. s[i] == p[j] : dp[i][j] = dp[i-1][j-1];
* 2. p[j] == '.' : dp[i][j] = dp[i-1][j-1];
* 3. p[j] == '*':
* 1) p[j-1] != s[i] : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
* 2) p[j-1] == s[i] or p[j-1] == '.'
* dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a
* or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a
* or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty
* space : O(n^2)
* time : O(n^2)
*/
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<bool> > dp(s.length()+1, vector<bool>(p.length()+1, false));
dp[0][0] = true;
for(int j = 0; j < p.size(); j++){
if(p[j]=='*' && dp[0][j-1])
dp[0][j+1] = true;
}
for(int i = 0; i < s.size(); i++){
for(int j = 0; j < p.size(); j++){
if(s[i] == p[j] || p[j] == '.')
dp[i+1][j+1] = dp[i][j];
if(p[j] == '*'){
if(s[i] != p[j-1] && p[j-1] != '.')
dp[i+1][j+1] = dp[i+1][j-1];
else
dp[i+1][j+1] = (dp[i+1][j-1] || dp[i+1][j] || dp[i][j+1]);
}
}
}
return dp[s.length()][p.length()];
}
};
| true |
1af645518daa733614f1c19d71d7ac406fdb0e2a | C++ | catboost/catboost | /library/cpp/cppparser/parser.cpp | UTF-8 | 17,944 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include <util/generic/hash.h>
#include <util/string/cast.h>
#include <util/generic/hash_set.h>
#include <util/generic/yexception.h>
#include "parser.h"
//#define DEBUG_ME 1
TCppSaxParser::TText::TText()
: Offset(0)
{
}
TCppSaxParser::TText::TText(ui64 offset)
: Offset(offset)
{
}
TCppSaxParser::TText::TText(const TString& data, ui64 offset)
: Data(data)
, Offset(offset)
{
}
TCppSaxParser::TText::~TText() = default;
void TCppSaxParser::TText::Reset() noexcept {
Offset += Data.length();
Data.clear();
}
TCppSaxParser::TWorker::TWorker() noexcept = default;
TCppSaxParser::TWorker::~TWorker() = default;
class TCppSaxParser::TImpl {
enum EState {
Code,
CommentBegin,
String,
Character,
OneLineComment,
MultiLineComment,
MultiLineCommentEnd,
Preprocessor
};
public:
typedef TCppSaxParser::TText TText;
typedef TCppSaxParser::TWorker TWorker;
inline TImpl(TWorker* worker)
: State_(Code)
, Worker_(worker)
, SkipNext_(false)
, Line_(0)
, Column_(0)
{
Worker_->DoStart();
}
inline ~TImpl() = default;
inline void Write(const void* data, size_t len) {
ProcessInput((const char*)data, len);
}
inline void Finish() {
if (!Text_.Data.empty()) {
switch (State_) {
case Code:
Worker_->DoCode(Text_);
break;
case Preprocessor:
Worker_->DoPreprocessor(Text_);
break;
case OneLineComment:
Worker_->DoOneLineComment(Text_);
break;
default:
ThrowError();
}
}
Worker_->DoEnd();
}
private:
inline void ProcessInput(const char* data, size_t len) {
EState savedState = Code;
while (len) {
const char ch = *data;
if (ch == '\n') {
++Line_;
Column_ = 0;
} else {
++Column_;
}
#if DEBUG_ME
Cerr << "char: " << ch << Endl;
Cerr << "state before: " << (unsigned int)State_ << Endl;
#endif
retry:
switch (State_) {
case Code: {
savedState = Code;
switch (ch) {
case '/':
State_ = CommentBegin;
break;
case '"':
Action(ch);
State_ = String;
break;
case '\'':
Action(ch);
State_ = Character;
break;
case '#':
Action(ch);
State_ = Preprocessor;
break;
default:
Text_.Data += ch;
break;
}
break;
}
case CommentBegin: {
switch (ch) {
case '/':
State_ = savedState;
savedState = Code;
Action("//");
State_ = OneLineComment;
break;
case '*':
State_ = savedState;
Action("/*");
State_ = MultiLineComment;
break;
default:
Text_.Data += '/';
State_ = savedState;
goto retry;
}
break;
}
case OneLineComment: {
switch (ch) {
case '\n':
Action(ch);
State_ = Code;
break;
default:
Text_.Data += ch;
break;
}
break;
}
case MultiLineComment: {
switch (ch) {
case '*':
Text_.Data += ch;
State_ = MultiLineCommentEnd;
break;
case '\n':
Text_.Data += ch;
savedState = Code;
break;
default:
Text_.Data += ch;
break;
}
break;
}
case MultiLineCommentEnd: {
switch (ch) {
case '/':
Text_.Data += ch;
Action();
State_ = savedState;
break;
default:
State_ = MultiLineComment;
goto retry;
}
break;
}
case String: {
switch (ch) {
case '"':
Text_.Data += ch;
if (SkipNext_) {
SkipNext_ = false;
} else {
if (savedState == Code) {
Action();
}
State_ = savedState;
}
break;
case '\\':
Text_.Data += ch;
SkipNext_ = !SkipNext_;
break;
default:
Text_.Data += ch;
SkipNext_ = false;
break;
}
break;
}
case Character: {
switch (ch) {
case '\'':
Text_.Data += ch;
if (SkipNext_) {
SkipNext_ = false;
} else {
if (savedState == Code) {
Action();
}
State_ = savedState;
}
break;
case '\\':
Text_.Data += ch;
SkipNext_ = !SkipNext_;
break;
default:
Text_.Data += ch;
SkipNext_ = false;
break;
}
break;
}
case Preprocessor: {
savedState = Preprocessor;
switch (ch) {
case '/':
State_ = CommentBegin;
break;
case '\'':
Text_.Data += ch;
State_ = Character;
break;
case '"':
Text_.Data += ch;
State_ = String;
break;
case '\n':
Text_.Data += ch;
if (SkipNext_) {
SkipNext_ = false;
} else {
Action();
savedState = Code;
State_ = Code;
}
break;
case '\\':
Text_.Data += ch;
SkipNext_ = true;
break;
default:
Text_.Data += ch;
SkipNext_ = false;
break;
}
break;
}
default:
ThrowError();
}
#if DEBUG_ME
Cerr << "state after: " << (unsigned int)State_ << Endl;
#endif
++data;
--len;
}
}
inline void Action(char ch) {
Action();
Text_.Data += ch;
}
inline void Action(const char* st) {
Action();
Text_.Data += st;
}
inline void Action() {
switch (State_) {
case Code:
Worker_->DoCode(Text_);
break;
case OneLineComment:
Worker_->DoOneLineComment(Text_);
break;
case MultiLineCommentEnd:
Worker_->DoMultiLineComment(Text_);
break;
case Preprocessor:
Worker_->DoPreprocessor(Text_);
break;
case String:
Worker_->DoString(Text_);
break;
case Character:
Worker_->DoCharacter(Text_);
break;
default:
ThrowError();
}
Text_.Reset();
}
inline void ThrowError() const {
ythrow yexception() << "can not parse source(line = " << (unsigned)Line_ + 1 << ", column = " << (unsigned)Column_ + 1 << ")";
}
private:
EState State_;
TWorker* Worker_;
TText Text_;
bool SkipNext_;
ui64 Line_;
ui64 Column_;
};
TCppSaxParser::TCppSaxParser(TWorker* worker)
: Impl_(new TImpl(worker))
{
}
TCppSaxParser::~TCppSaxParser() = default;
void TCppSaxParser::DoWrite(const void* data, size_t len) {
Impl_->Write(data, len);
}
void TCppSaxParser::DoFinish() {
Impl_->Finish();
}
TCppSimpleSax::TCppSimpleSax() noexcept {
}
TCppSimpleSax::~TCppSimpleSax() = default;
void TCppSimpleSax::DoCode(const TText& text) {
static const char char_types[] = {
2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
static const char CWHITESPACE = 0;
static const char CIDENTIFIER = 1;
static const char CSYNTAX = 2;
enum EState {
WhiteSpace = CWHITESPACE,
Identifier = CIDENTIFIER,
Syntax = CSYNTAX
};
EState state = Identifier;
TText cur(text.Offset);
for (const auto& it : text.Data) {
const unsigned char ch = *(const unsigned char*)(&it);
const char type = char_types[ch];
switch (state) {
case Identifier: {
switch (type) {
case CIDENTIFIER:
cur.Data += ch;
break;
default:
if (!cur.Data.empty()) {
DoIdentifier(cur);
}
cur.Reset();
cur.Data += ch;
state = (EState)type;
break;
}
break;
}
case WhiteSpace: {
switch (type) {
case CWHITESPACE:
cur.Data += ch;
break;
default:
DoWhiteSpace(cur);
cur.Reset();
cur.Data += ch;
state = (EState)type;
break;
}
break;
}
case Syntax: {
switch (type) {
case CSYNTAX:
cur.Data += ch;
break;
default:
DoSyntax(cur);
cur.Reset();
cur.Data += ch;
state = (EState)type;
break;
}
break;
}
}
}
if (!cur.Data.empty()) {
switch (state) {
case Identifier:
DoIdentifier(cur);
break;
case WhiteSpace:
DoWhiteSpace(cur);
break;
case Syntax:
DoSyntax(cur);
break;
}
}
}
class TCppFullSax::TImpl {
typedef THashSet<TString> TKeyWords;
class TRegExp {
public:
inline TRegExp(const char*) {
}
inline bool Match(const TString& /*s*/) const noexcept {
return false;
}
};
public:
inline TImpl()
: OctNumber_("^[+-]?0[0-7]+$")
, HexNumber_("^[+-]?0x[0-9A-Fa-f]+$")
, DecNumber_("^[+-]?[0-9]+$")
, FltNumber_("^[+-]?[0-9]*\\.[0-9]*$")
{
AddKeyword("extern");
AddKeyword("static");
AddKeyword("inline");
AddKeyword("volatile");
AddKeyword("asm");
AddKeyword("const");
AddKeyword("mutable");
AddKeyword("char");
AddKeyword("signed");
AddKeyword("unsigned");
AddKeyword("int");
AddKeyword("short");
AddKeyword("long");
AddKeyword("double");
AddKeyword("float");
AddKeyword("bool");
AddKeyword("class");
AddKeyword("struct");
AddKeyword("union");
AddKeyword("void");
AddKeyword("auto");
AddKeyword("throw");
AddKeyword("try");
AddKeyword("catch");
AddKeyword("for");
AddKeyword("do");
AddKeyword("if");
AddKeyword("else");
AddKeyword("while");
AddKeyword("switch");
AddKeyword("case");
AddKeyword("default");
AddKeyword("goto");
AddKeyword("break");
AddKeyword("continue");
AddKeyword("virtual");
AddKeyword("template");
AddKeyword("typename");
AddKeyword("enum");
AddKeyword("public");
AddKeyword("private");
AddKeyword("protected");
AddKeyword("using");
AddKeyword("namespace");
AddKeyword("typedef");
AddKeyword("true");
AddKeyword("false");
AddKeyword("return");
AddKeyword("new");
AddKeyword("delete");
AddKeyword("operator");
AddKeyword("friend");
AddKeyword("this");
}
inline ~TImpl() = default;
inline void AddKeyword(const TString& keyword) {
KeyWords_.insert(keyword);
}
inline bool IsKeyword(const TString& s) {
return KeyWords_.find(s) != KeyWords_.end();
}
inline bool IsOctNumber(const TString& s) {
return OctNumber_.Match(s);
}
inline bool IsHexNumber(const TString& s) {
return HexNumber_.Match(s);
}
inline bool IsDecNumber(const TString& s) {
return DecNumber_.Match(s);
}
inline bool IsFloatNumber(const TString& s) {
return FltNumber_.Match(s);
}
private:
const TRegExp OctNumber_;
const TRegExp HexNumber_;
const TRegExp DecNumber_;
const TRegExp FltNumber_;
TKeyWords KeyWords_;
};
TCppFullSax::TCppFullSax()
: Impl_(new TImpl())
{
}
TCppFullSax::~TCppFullSax() = default;
void TCppFullSax::AddKeyword(const TString& keyword) {
Impl_->AddKeyword(keyword);
}
void TCppFullSax::DoIdentifier(const TText& text) {
if (Impl_->IsKeyword(text.Data)) {
DoKeyword(text);
} else if (Impl_->IsOctNumber(text.Data)) {
DoOctNumber(text);
} else if (Impl_->IsHexNumber(text.Data)) {
DoHexNumber(text);
} else if (Impl_->IsDecNumber(text.Data)) {
DoDecNumber(text);
} else if (Impl_->IsFloatNumber(text.Data)) {
DoFloatNumber(text);
} else {
DoName(text);
}
}
void TCppFullSax::DoEnd() {
}
void TCppFullSax::DoStart() {
}
void TCppFullSax::DoString(const TText&) {
}
void TCppFullSax::DoCharacter(const TText&) {
}
void TCppFullSax::DoWhiteSpace(const TText&) {
}
void TCppFullSax::DoKeyword(const TText&) {
}
void TCppFullSax::DoName(const TText&) {
}
void TCppFullSax::DoOctNumber(const TText&) {
}
void TCppFullSax::DoHexNumber(const TText&) {
}
void TCppFullSax::DoDecNumber(const TText&) {
}
void TCppFullSax::DoFloatNumber(const TText&) {
}
void TCppFullSax::DoSyntax(const TText&) {
}
void TCppFullSax::DoOneLineComment(const TText&) {
}
void TCppFullSax::DoMultiLineComment(const TText&) {
}
void TCppFullSax::DoPreprocessor(const TText&) {
}
| true |
617f261204273b8e37219d26435c6b5b2591f431 | C++ | pio2725/Discrete-Structure | /Parser.cpp | UTF-8 | 6,700 | 2.828125 | 3 | [] | no_license | #include "Parser.h"
Parser::Parser()
{
position = -1;
}
Parser::~Parser()
{
}
Datalog Parser::Parse(std::vector<Token> tokens)
{
//copying the vector
this->tokens = tokens;
try
{
//datalog parser
DatalogParser();
if (tokens.at(position + 1).getTokentype() != EOFILE)
{
//std::cout << position << " " << tokens.size() << std::endl;
throw tokens.at(position + 1);
}
//printing out
//datalog.ToString();
//return datalog;
}
catch (Token tk)
{
//std::cout << "Failure!" << std::endl;
//std::cout << " ";
//tk.ToString();
}
//find extra token
//std::cout << position << tokens.size() << std::endl;
return datalog;
}
void Parser::Match(TokenType tk)
{
//Check if next token is what we want?
++position; //next position
if (tokens.at(position).getTokentype() != tk)
{
throw tokens.at(position);
}
}
void Parser::DatalogParser()
{
bool isfact = false;
if (NextTokentype() != SCHEMES)
{
throw tokens.at(0);
}
Match(SCHEMES);
Match(COLON);
ParseSchemes();
//Facts not required
if (NextTokentype() == FACTS)
{
isfact = true;
Match(FACTS);
Match(COLON);
ParseFactList();
}
//Rules not required
if (NextTokentype() == RULES && isfact)
{
Match(RULES);
Match(COLON);
ParseRuleList();
}
else
{
throw tokens.at(position + 1);
}
//Queries required
if (NextTokentype() != QUERIES)
{
throw tokens.at(position + 1);
}
Match(QUERIES);
Match(COLON);
ParseQueries();
ParseQueriesList();
}
void Parser::ParseQueries()
{
if (NextTokentype() != ID)
{
throw tokens.at(position + 1);
}
ParsePredQ();
Match(Q_MARK);
}
void Parser::ParseQueriesList()
{
if (NextTokentype() == ID)
{
ParseQueries();
ParseQueriesList();
}
}
void Parser::ParseRuleList()
{
if (NextTokentype() == ID)
{
ParseRules();
ParseRuleList();
}
}
void Parser::ParseRules()
{
ParseHeadPred();
Match(COLON_DASH);
ParsePred();
ParsePredList();
Match(PERIOD);
//rule one line
datalog.addRules(rule);
rule.bodyPredClear();
}
void Parser::ParsePredList()
{
if (NextTokentype() == COMMA)
{
Match(COMMA);
ParsePred();
ParsePredList();
}
}
void Parser::ParsePred()
{
Match(ID);
pred.setName(tokens.at(position).getValue());
Match(LEFT_PAREN);
ParseParam();
ParseParamList();
Match(RIGHT_PAREN);
rule.setBodyPred(pred);
pred.clearVec(); // clear
}
void Parser::ParseParamList()
{
if (NextTokentype() == COMMA)
{
Match(COMMA);
ParseParam();
ParseParamList();
}
}
void Parser::ParseParam()
{
if (NextTokentype() == STRING)
{
Match(STRING);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
else if (NextTokentype() == ID)
{
Match(ID);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
else if (NextTokentype() == LEFT_PAREN)
{
ParseExpression();
}
else
{
//double check!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
throw tokens.at(position + 1);
}
}
void Parser::ParseExpression()
{
Match(LEFT_PAREN);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
ParseParam();
ParseOperator();
ParseParam();
Match(RIGHT_PAREN);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
void Parser::ParseOperator()
{
if (NextTokentype() == ADD)
{
Match(ADD);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
else if (NextTokentype() == MULTIPLY)
{
Match(MULTIPLY);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
}
void Parser::ParseHeadPred()
{
Match(ID);
pred.setName(tokens.at(position).getValue());
Match(LEFT_PAREN);
Match(ID);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
ParseIdList();
Match(RIGHT_PAREN);
rule.setHeadPred(pred);
pred.clearVec();
}
void Parser::ParseSchemes()
{
if (NextTokentype() == FACTS || NextTokentype() == RULES || NextTokentype() == QUERIES)
{
throw tokens.at(position + 1);
}
Match(ID);
pred.setName(tokens.at(position).getValue());
Match(LEFT_PAREN);
Match(ID);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
ParseIdList();
Match(RIGHT_PAREN);
//one predicate
datalog.addSchemes(pred);
pred.clearVec(); // clear
ParseSchemeList();
}
void Parser::ParseIdList()
{
//dealing with lamda
if (tokens.at(position + 1).getTokentype() == COMMA)
{
Match(COMMA);
Match(ID);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
ParseIdList();
}
}
void Parser::ParseSchemeList()
{
if (tokens.at(position + 1).getTokentype() == ID)
{
ParseSchemes();
ParseSchemeList();
}
}
void Parser::ParseFacts()
{
Match(ID);
pred.setName(tokens.at(position).getValue());
Match(LEFT_PAREN);
Match(STRING);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
datalog.addDomain(tokens.at(position).getValue());
ParseStringList();
Match(RIGHT_PAREN);
Match(PERIOD);
datalog.addFacts(pred);
pred.clearVec(); // clear pred
}
void Parser::ParseStringList()
{
if (NextTokentype() == COMMA)
{
Match(COMMA);
Match(STRING);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
datalog.addDomain(tokens.at(position).getValue());
ParseStringList();
}
}
void Parser::ParseFactList()
{
//called first
if (NextTokentype() == ID)
{
ParseFacts();
ParseFactList();
}
}
TokenType Parser::NextTokentype()
{
return tokens.at(position + 1).getTokentype();
}
void Parser::ParsePredQ()
{
Match(ID);
pred.setName(tokens.at(position).getValue());
Match(LEFT_PAREN);
ParseParamQ();
ParseParamListQ();
Match(RIGHT_PAREN);
datalog.addQueries(pred);
pred.clearVec(); // clear
}
void Parser::ParseParamQ()
{
if (NextTokentype() == STRING)
{
Match(STRING);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
else if (NextTokentype() == ID)
{
Match(ID);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
}
else if (NextTokentype() == LEFT_PAREN)
{
ParseExpressionQ();
}
else
{
//double check!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
throw tokens.at(position + 1);
}
}
void Parser::ParseParamListQ()
{
if (NextTokentype() == COMMA)
{
Match(COMMA);
ParseParamQ();
ParseParamListQ();
}
}
void Parser::ParseExpressionQ()
{
Match(LEFT_PAREN);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
ParseParamQ();
ParseOperator();
ParseParamQ();
Match(RIGHT_PAREN);
pm.SetToken(tokens.at(position));
pred.addParam(pm);
} | true |
c149ddabd8b370019ab150c377547b644056e54b | C++ | piyush2011257/GFG | /AMAZON/165_sde2/r2_q1_using_trie.cpp | UTF-8 | 2,477 | 3.3125 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
struct trie
{ char data;
string word;
struct trie* child[26];
trie( char d=0 )
{ data=d;
word.clear();
for ( int i=0; i<26; i++ )
child[i]=NULL;
}
};
struct trie* insert ( struct trie* root, char *word, int pos, char *words );
void print_trie ( trie *root );
const int len=11;
int main()
{ struct trie *root[26]={NULL};
// All small letter words assumed
char ch[len][10]={ {"bota"},
{"boat"},
{"bat"},
{"tab"},
{"raman"},
{"cat"},
{"tac"},
{"manra"},
{"act"},
{"mar"},
{"ram"},
};
for ( int i=0; i<len; i++ )
{ char tmp[10];
strcpy(tmp,ch[i]);
sort(tmp,tmp+strlen(tmp));
//cout<<"tmp: "<<tmp<<" "<<tmp[0]-'a'<<endl;
root[tmp[0]-'a'] = insert ( root[tmp[0]-'a'], tmp, 0, ch[i] );
}
for ( int i=0; i<26; i++ )
{ if ( root[i] != NULL )
{ printf("Strings starting with: %c\n",i+'a');
print_trie(root[i]);
printf("\n");
}
}
return 0;
}
void print_trie ( trie *root )
{ if ( root->word.length() > 0 )
cout<<"{"<<root->word<<"}\n";
for ( int i=0; i<26; i++ )
if ( root->child[i] != NULL )
print_trie(root->child[i]);
}
struct trie* insert ( struct trie* root, char *word, int pos, char *words )
{ if ( root == NULL && word[pos] != '\0' )
{ trie *tmp=new trie(word[pos]);
if ( word[pos+1] == '\0' )
{ if ( tmp->word.length() == 0 )
tmp->word = words;
else
{ tmp->word += " ";
tmp->word += words;
}
return tmp;
}
else
{ tmp->child[word[pos+1]-'a']= insert(tmp->child[word[pos+1]-'a'], word, pos+1, words);
return tmp;
}
}
if ( word[pos] == '\0' ) // not encountered actually due to earlier check at pos-1
return NULL;
if ( word[pos+1] == '\0' )
{ if ( root->word.length() == 0 )
root->word = words;
else
{ root->word += " ";
root->word +=words;
}
return root;
}
else
{ root->child[word[pos+1]-'a']= insert(root->child[word[pos+1]-'a'], word, pos+1, words);
return root;
}
}
/*
e.g.
bat -> abt
tab -> abt
raman -> aanmr
amran -> aamnr
rom -> mor
mor -> mor
a a n m r (raman, amran)
b t ( bat, tab )
m o r ( rom.mor)
*/
| true |
23b48e91a6a4afd77ead33bc9bc5229d9fa939e1 | C++ | Tomato1107/particle_filter_cuda | /src/classify.cpp | UTF-8 | 2,986 | 2.546875 | 3 | [
"MIT"
] | permissive |
#include "particle_filter_fast.h"
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/parse.h>
int main(int argc, char **argv)
{
int cudaDevice = 0;
float normal_vectors_search_radius = 0.2f;
float curvature_threshold = 0;
float ground_Z_coordinate_threshold = 1;
int number_of_points_needed_for_plane_threshold =5;
int max_number_considered_in_INNER_bucket = 100;
int max_number_considered_in_OUTER_bucket = 100;
pcl::console::parse_argument (argc, argv, "-cuda", cudaDevice);
pcl::console::parse_argument (argc, argv, "-nsr", normal_vectors_search_radius);
pcl::console::parse_argument (argc, argv, "-ct", curvature_threshold);
pcl::console::parse_argument (argc, argv, "-z", ground_Z_coordinate_threshold);
pcl::console::parse_argument (argc, argv, "-nppt", number_of_points_needed_for_plane_threshold);
pcl::console::parse_argument (argc, argv, "-inner", max_number_considered_in_INNER_bucket);
pcl::console::parse_argument (argc, argv, "-outer", max_number_considered_in_OUTER_bucket);
std::cout << "use case: Classify given poincloud to make it usable in particle filter" << std::endl;
std::cout << "-cuda : used cuda device : " << cudaDevice << std::endl;
std::cout << "-nsr : normal_vectors_search_radius : " << normal_vectors_search_radius << std::endl;
std::cout << "-ct : curvature_threshold : " << curvature_threshold << std::endl;
std::cout << "-z : ground_Z_coordinate_threshold : " << ground_Z_coordinate_threshold << std::endl;
std::cout << "-nppt : number_of_points_needed_for_plane_threshold : " << number_of_points_needed_for_plane_threshold << std::endl;
std::cout << "-inner: max_number_considered_in_INNER_bucket default: " << max_number_considered_in_INNER_bucket << std::endl;
std::cout << "-outer: max_number_considered_in_OUTER_bucket default: " << max_number_considered_in_OUTER_bucket << std::endl;
std::vector<int> ind_pcd;
ind_pcd = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");
if(ind_pcd.size()!=2)
{
std::cout << "give input.pcd output.pcd" << std::endl;
return -1;
}
std::string inputCloudFn (argv[ind_pcd[0]]);
std::string outputCloudFn (argv[ind_pcd[1]]);
std::cout << "input pointcloud : " << inputCloudFn << std::endl;
std::cout << "output pointcloud : " << outputCloudFn << std::endl;
pcl::PointCloud<pcl::PointXYZ> input;
pcl::PointCloud<Semantic::PointXYZL> output;
pcl::io::loadPCDFile(inputCloudFn, input);
CPointcloudClassifier classifier(cudaDevice,
normal_vectors_search_radius,
curvature_threshold,
ground_Z_coordinate_threshold,
number_of_points_needed_for_plane_threshold,
max_number_considered_in_INNER_bucket,
max_number_considered_in_OUTER_bucket);
classifier.classify(input, output);
std::cout << "saving \n";
pcl::io::savePCDFile(outputCloudFn, output);
}
| true |
8359f722822bfe7544519bb80a93d51632084a26 | C++ | aliaksei-ivanou-by/Coursera_Yandex_c-plus-plus-modern-development | /01 White/Week 02/Lessons/01 White_Week 02_Lesson 06.cpp | UTF-8 | 837 | 3.59375 | 4 | [] | no_license | // Основы разработки на C++: белый пояс. Вторая неделя
// Контейнер vector. Векторы, часть 1
#include "iostream"
#include "vector"
#include "string"
using namespace std;
void PrintVector(const vector<string>& v)
{
for (string s : v)
{
cout << s << '\n';
}
}
int main()
{
int n1;
cin >> n1;
vector<string> v1(n1);
for (string& s1 : v1)
{
cin >> s1;
}
PrintVector(v1);
cout << "\n\n";
int n2;
cin >> n2;
vector<string> v2;
int i2 = 0;
while (i2 < n2)
{
string s2;
cin >> s2;
v2.push_back(s2);
cout << "Current size = " << v2.size() << '\n';
++i2;
}
PrintVector(v2);
cout << "\n\n";
int n3;
cin >> n3;
vector<string> v3;
for (int i3 = 0; i3 < n3; ++i3)
{
string s3;
cin >> s3;
v3.push_back(s3);
}
PrintVector(v3);
return 0;
}
| true |
dc9ef4e62fa14daec7bf657f1d2d20115d3f57c6 | C++ | martincap94/LatticeBoltzmann | /LatticeBoltzmann/Utils.h | UTF-8 | 1,452 | 3.53125 | 4 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \file Utils.h
* \author Martin Cap
* \date 2018/12/23
* \brief Defines utility functions that may be used anywhere in the application.
*
* Defines utility functions that may be used anywhere in the application.
*
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
// Trimming functions taken from: https://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string
// answer by user Galik
/// Trim from left.
inline std::string& ltrim(std::string& s, const char* t = " \t\n\r\f\v") {
s.erase(0, s.find_first_not_of(t));
return s;
}
/// Trim from right.
inline std::string& rtrim(std::string& s, const char* t = " \t\n\r\f\v") {
s.erase(s.find_last_not_of(t) + 1);
return s;
}
/// Trim from left & right.
inline std::string& trim(std::string& s, const char* t = " \t\n\r\f\v") {
return ltrim(rtrim(s, t), t);
}
// copying versions
/// Trim from left.
inline std::string ltrim_copy(std::string s, const char* t = " \t\n\r\f\v") {
return ltrim(s, t);
}
/// Trim from right.
inline std::string rtrim_copy(std::string s, const char* t = " \t\n\r\f\v") {
return rtrim(s, t);
}
/// Trim from left & right.
inline std::string trim_copy(std::string s, const char* t = " \t\n\r\f\v") {
return trim(s, t);
}
| true |
6202b98cde383127ff267eb16afec54ac2c92b1b | C++ | aryangulati/Hacktoberfest2021 | /Contributions/cpp/Kadane's_Algo.cpp | UTF-8 | 434 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int currSum = 0;
int maxSum = INT_MIN;
for(int i=0;i<n;i++){
currSum += a[i];
if(currSum < 0){
currSum = 0;
}
maxSum = max(maxSum, currSum);
}
cout<<maxSum<<endl;
return 0;
} | true |
64f01555d5abee6713b1f94904c90598a758387d | C++ | ktp-forked-repos/AlgorithmLibrary | /Includes/NumberTheory.h | UTF-8 | 3,321 | 2.765625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Core.h"
template<typename T>
T fastpow(const T& a, int p) {
if (p==0)
return T(1);
T tmp=fastpow(a, p/2);
if (p%2)
return tmp*tmp*a;
return tmp*tmp;
}
/*
Adjust Formaula
xgcd(a,b) solves ax+by=gcd(a,b)=g
ax+by=c satisfied iff c=g*k
so, do x*=k and y*=k.
if (x,y) is one of root, (x+t*b/g, y-t*a/g) is also root.(t is arbitary integer)
if x and y have bounds, solve that inequalities.
For example, I have one lbx(lower bound x) and one lby(lower bound y).
I will find the root which is the closest to lbx.
solve x+t*b/g<lbx and x+t*b/g>=lbx consecutively.
then, all of big x go to small, and next all small thing go to big|equal to lbx
now, we got proper t for lbx, and check if y-t*a/g>=lby.(cuz (x,y)->(x+t*b/g, y-t*a/g))
if it is not satisfied, solve inequality for y similarly.
if adjusted x for satisfying y is not satisfied, this formula has no solution.
Maybe simpler solution exist. see (jung2381187, koosaga)'s code at boj_11661
linearity?
*/
struct XGCD{i64 g; i64 x; i64 y;};
XGCD xgcd(i64 a, i64 b) {
if (b==0)
return {a,1,0};
auto res = xgcd(b, a%b);
return {res.g, res.y, res.x-(a/b)*res.y};
}
XGCD XGCDtolb(XGCD a, i64 lbx, i64 lby){
if(0)
throw "no root";
return {};
//return minimum a which satisfies lb<a
}
XGCD XGCDtoub(XGCD a, i64 ubx, i64 uby){
if(0)
throw "no root";
return {};
//return maximum a which satisfies a<ub
}
vector<i64> factorization(i64 n){
i64 cur=n;
vector<i64> ret;
for(i64 i=2; i*i<=n; i++)
while (!(cur%i)){
cur/=i;
ret.push_back(i);
}
if (cur>1)
ret.push_back(cur);
return ret;
}
vector<i64> divisors(i64 n){
vector<i64> ret, tmp;
for(i64 i=1; i*i<=n; i++){
if (n%i==0){
ret.push_back(i);
if (i!=n/i)
tmp.push_back(n/i);
}
}
reverse(tmp.begin(), tmp.end());
ret.insert(ret.end(), tmp.begin(), tmp.end());
return ret;
}
//nloglog(n)
vector<bool> sieve_prime(int ub){
vector<bool> ret(ub, true);
ret[0]=ret[1]=false;
for (i64 i=2; i*i<ub; i++) {
if (!ret[i])
continue;
for (i64 j=i*i; j<ub; j+=i)
ret[j]=false;
}
return ret;
}
//nlogn (harmony series)
//can apply to calculate (low constant factor)sieve_numdiv, sieve_sumdiv, etc.
vector<vector<int>> sieve_divs(int ub){
vector<vector<int>> ret(ub);
for (i64 i=4; i<ub; i++) {
for (i64 j=i; j<ub; j+=i)
ret[j].push_back(i);
}
return ret;
}
int eulerphi(int n){return 0;}
//floor(log(n))
int lgf(i64 n, int base=2){
int ret=0;
while (n)
n/=base, ret++;
return ret-1;
}
//ceil(log(n))
int lgc(i64 n, int base=2) {
int ret=0;
int rem=0;
while (n)
rem+=n%base, n/=base, ret++;
return ret-(rem<=1);
}
int sqrt_f(i64 n){
i64 i=1;
while(i*i<=n)
i++;
return i-1;
}
int sqrt_c(i64 n){
i64 i=1;
while(i*i<n)
i++;
return i;
}
template<typename T>
vector<T> factorials(T n){
vector<T> ret(int(n)+1);
ret[0]=1;
cfor(i, 1, n)
ret[i]=ret[i-1]*i;
return ret;
}
//recommanded T=ModNum. i64 can easily overflow.
template<typename T>
T binom(T n, T k){
if(k>n/2)
return binom(n, n-k);
if(k==0)
return 1;
auto f=factorials(n);
return f[int(n)]/(f[int(k)]*f[int(n-k)]);
}
template<typename T>
vector<vector<T>> binom_dp(T n, T k){
vector<vector<T>> ret(n, vector<T>(k));
return ret;
}
vector<int> to_digits(i64 n){
vector<int> ret;
while(n)
ret.push_back(n%10), n/=10;
return ret;
} | true |
9679d04ef7337520490de657b7daa63cb3e2c94a | C++ | USTC-CS-Course-Resource/Algorithm-HWs-and-Labs | /labs/exp3/exp3.2-merge.cpp | UTF-8 | 1,121 | 3.09375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <climits>
using namespace std;
constexpr int MAX_N = 200;
int time_costs[MAX_N][MAX_N] = {0};
int sum_costs[MAX_N][MAX_N] = {0};
int lengths[MAX_N] = {0};
void min_merge_time(int* lengths, int i, int j) {
if (i == j) return;
int min_time = INT_MAX;
for (int k = i; k < j; k++) {
if (time_costs[i][k] == 0) min_merge_time(lengths, i, k);
if (time_costs[k+1][j] == 0) min_merge_time(lengths, k+1, j);
if (sum_costs[i][k] == 0) {
for (int m = i; m <= k; m++) {
sum_costs[i][k] += lengths[m];
}
}
if (sum_costs[k+1][j] == 0) {
for (int m = k+1; m <= j; m++) {
sum_costs[k+1][j] += lengths[m];
}
}
min_time = min(min_time, time_costs[i][k] + time_costs[k+1][j] + (sum_costs[i][k] + sum_costs[k+1][j]));
}
time_costs[i][j] = min_time;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", lengths + i);
}
min_merge_time(lengths, 0, n-1);
printf("%d\n", time_costs[0][n-1]);
} | true |
9fab5ee1091bcb37457acc41649d6b67ac15b802 | C++ | jamiepg1/ta | /C++/lab/lab05/tsk03.cpp | UTF-8 | 310 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "ccc_time.cpp"
void addTime(Time& t, int h){
t.add_seconds(h*3600);
}
int main(){
int h;
cout<<"number of hours"<<endl;
cin>>h;
Time now;
addTime(now,h);
cout<<now.get_hours()<<":"<<now.get_minutes()<<":"<<now.get_seconds()<<endl;
} | true |
7ba7bc93ec1f8cd25e25edc394d4a9be071d0b40 | C++ | CuteyThyme/CSU_CS_Experiment | /实验课设代码/计算机图形学/实验三/Trace/src/fileio/buffer.cpp | UTF-8 | 3,027 | 3.359375 | 3 | [
"MIT"
] | permissive | /*
The Buffer class is essentially a wrapper for an istream.
It is here mainly to keep track of the current file location
(line number, column number) to print intelligent error messages.
If you find yourself changing stuff in this file, you're probably
doing something wrong.
*/
#include <string>
#include "buffer.h"
#include "../parser/Parser.h"
//////////////////////////////////////////////////////////////////////////
//
// Buffer::Buffer(FILE*,...) constructor
//
// This constructor sets up the initial state that we need in order
// to read files.
//
Buffer::Buffer(istream& is, bool printChars, bool printLines)
: inStream( is )
{
PositionInCurrentLine = Line.begin();
LineNumber = 0;
ColNumber = 0;
LastPrintedLine = 0;
_printChars = printChars;
_printLines = printLines;
_bHasData = false;
}
//////////////////////////////////////////////////////////////////////////
//
// char Buffer::GetCh() private method
//
// GetCh() gets a new character from the buffer and returns it
//
char Buffer::GetCh() {
if (!inStream) {
return '\0';
}
// test for data
if ( !_bHasData )
{
// Nothing has been read-in yet, so read the first line
GetLine();
if ( !_bHasData )
{
return '\0';
}
}
else
{
// advance position
PositionInCurrentLine++;
ColNumber++;
}
while (PositionInCurrentLine == Line.end() || Line.empty()) {
// need to read another line of input from the file
GetLine();
if (!inStream) {
return '\0';
}
}
// extract character from line buffer
char CurrentCh = *PositionInCurrentLine;
if (_printChars) {
std::cout << "Read character `" << CurrentCh << "'" << std::endl;
}
return CurrentCh;
}
//////////////////////////////////////////////////////////////////////////
//
// void Buffer::GetLine() private method
//
// GetLine() reads a new line from the file into the Line buffer
// variable. It also handles listings, if necessary. Returns are false
// for EOF or true for got a new buffer.
//
// This function is weak, in that it can't handle arbitrarily long lines
// in a file. Ideally it would be rewritten so that it can do this fine.
// The real difficulty is in being able to print out, on demand, the whole
// line of input, of arbitrary length.
//
void Buffer::GetLine() {
std::getline(inStream, Line);
Line.append( "\n" ); // because iostreams strip out the end-of-line char
PositionInCurrentLine = Line.begin();
_bHasData = ( PositionInCurrentLine != Line.end() && !Line.empty() );
ColNumber = 0;
LineNumber ++;
if (_printLines) PrintLine( std::cout );
}
//////////////////////////////////////////////////////////////////////////
//
// void Buffer::PrintLine() method
//
// This method displays the current line on the screen.
//
void Buffer::PrintLine( ostream& out ) const {
if (LineNumber > LastPrintedLine) {
out << "# " << Line << std::endl;
LastPrintedLine = LineNumber;
}
}
| true |
1a1a1f4a69c5f5f66924e175cc8a48d69294355e | C++ | olderor/advanced3 | /main.h | UTF-8 | 6,134 | 4.0625 | 4 | [] | no_license | #pragma once
#include <iostream>
#include <istream>
#include <vector>
#include <string>
#include <utility>
struct treap {
public:
// Initialization - create new treap with elements from 1 up to size.
// Parameter const int size - number of elements in the array.
explicit treap(const int size);
// Initialization - create new treap.
// Parameter std::vector<int> &values - elements in the array.
explicit treap(std::vector<int> &values);
// Function reorder - move subsegment to the start of the array.
// Parameter const int left - left position in the array.
// Parameter const int right - right position in the array.
void reorder(const int left, const int right);
// Function get_elements - retrieve elements from the treap in the correct order.
// Return std::vector<int> - list of elements.
std::vector<int> get_elements();
// Function get_description - get description of the treap - print array.
// Parameter std::string separator - elements in the treap will be separeted by this string.
// Return std::string - description of the array.
std::string get_description(const std::string separator = " ");
private:
// Implicit treap node structure.
struct node {
// Field size - number of childs in the node.
int size;
// Field value - value that the node stores.
const int value;
// Pointer to the left child.
node *left = nullptr;
// Pointer to the right child.
node *right = nullptr;
// Initialization.
node();
// Initialization with given value.
explicit node(const int value);
};
// Pointer to the root element in the tree.
node *root = nullptr;
// Function build - create new treap.
// Parameter const int left - left bulding border.
// Parameter const int right - right bulding border.
// Parameter std::vector<int> &values - elements in the array.
// Return node* - pointer to the created treap.
node* build(
const int left,
const int right,
std::vector<int> &values);
// Function update - update size of the node.
// Parameter node *root - pointer to the node that must be updated.
void update(node *root);
// Function size - find number of childs in the node.
// Returns size of the node (if node is not exist, returns 0).
int size(node *root);
// Function merge - merge two treaps into new one.
// Parameter node *left - pointer to the first treap.
// Parameter node *right - pointer to the second treap.
// Parameter node *&result - node where should be stored the result of the merging.
void merge(node *left, node *right, node *&result);
// Function split - split treap into two treaps by position in the array.
// Parameter node *root - pointer to the treap that should be split.
// Parameter node *&left - node where should be stored the first treap.
// Parameter node *&right - node where should be stored the second treap.
// Parameter const int position - position in the array.
void split(node *root, node *&left, node *&right, const int position);
// Function insert - insert new element into array by its position.
// Parameter node *&root - pointer to the treap,
// where should be stored the result of inserting.
// Parameter node *item - node to insert.
// Parameter const int position - position in the array.
void insert(node *&root, node *item, const int position);
// Function reorder - move subsegment to the start of the array.
// Parameter node *root - pointer to the treap.
// Parameter const int left - left position in the array.
// Parameter const int right - right position in the array.
// Return node* - pointer to the result of moving.
node* reorder(node *root, const int left, const int right);
// Function get_elements - insert elements from the node to the list.
// Parameter node *root - pointer to the treap.
// Parameter std::vector<int> &elements - list, where elements should be stored.
void get_elements(node *root, std::vector<int> &elements);
// Function get_description - get description of the node - print array.
// Parameter node *root - treap to print.
// Return std::string - description of the array.
std::string get_description(node *root);
};
// Struct query.
// Used for describing the given query with left and right indexes.
struct query {
public:
// Field int left_position - left index.
int left_position;
// Field int right_position - right index.
int right_position;
// Default initialization that gives indexes value 0.
query();
// Initialization with given indexes.
query(const int left, const int right);
};
// Function solve - solve given problem.
// Parameter const int size - number of elements in the array.
// Parameter const int queries_count - number of queries.
// Parameter std::vector<query> &queries - list of queries,
// that contains left and right indexes of each query.
// Return std::vector<int> - elements after processing queries.
std::vector<int> solve(
const int size,
const int queries_count,
std::vector<query> &queries);
// Function read_data - process input.
// Parameter std::istream &_Istr - input stream.
// Parameter const int size - number of elements in the array.
// Parameter const int queries_count - number of queries.
// Parameter std::vector<query> &queries - list of queries,
// that contains left and right indexes of each query.
void read_data(
std::istream &_Istr,
int &size,
int &queries_count,
std::vector<query> &queries);
// Function write_data - process output.
// Parameter std::ostream &_Ostr - output stream.
// Parameter std::vector<int> &data - list of integer data to write.
void write_data(
std::ostream &_Ostr,
std::vector<int> &data);
// Main function.
int main();
| true |
7152f3e8b5fa24ad7e48f8c737d883fb421d7823 | C++ | gganetlepage/CVRP | /VRPwConstraintsonCheckerboard/client.cpp | UTF-8 | 632 | 2.828125 | 3 | [] | no_license | #include "client.h"
#include <iostream>
#include <fstream>
using namespace std;
Client::Client(int positionX, int posiitionY, int demande):
m_positionX(positionX), m_positionY(posiitionY), m_demande(demande)
{
}
void Client::showClient() const
{
cout << m_positionX <<" "<<m_positionY<<" "<<m_demande<<endl;
}
void Client::ecritureClient(ofstream& monflux) const {
monflux << m_positionX <<" "<<m_positionY<<" "<<m_demande<<endl;
}
int Client::getPositionX() const
{
return m_positionX;
}
int Client::getPositionY() const
{
return m_positionY;
}
int Client::getDemande() const
{
return m_demande;
}
| true |
93aebf06b063117ae8208e02efa20f6b12ad0b5c | C++ | khare1872/CP | /Another_Dividing_Number_Problem.cpp | UTF-8 | 1,003 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long int solve(int n)
{
long long int ans=0;
while (n % 2 == 0)
{
ans++;
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i + 2)
{
while (n % i == 0)
{
ans++;
n = n/i;
}
}
if (n > 2){
ans++;
}
return ans;
}
int main() {
int t;
cin>>t;
while(t--){
long long int a,b,k;
cin>>a>>b>>k;
if(k==1){
if(a==b){
cout<<"NO"<<endl;
continue;
}
else if(a%b==0 || b%a==0){
cout<<"YES"<<endl;
continue;
}
else{
cout<<"NO"<<endl;
continue;
}
}
else {
int ans= solve(a);
ans+=solve(b);
if(ans>=k) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}
| true |
4d1cc241910fb55ad3fafef7d00a491ef9ae152f | C++ | ryanxunhuan/Sequential_Experimental_Design | /src/tools.cpp | UTF-8 | 10,435 | 2.984375 | 3 | [] | no_license | #include "tools.h"
/* Functions with templates are defined in header file. */
// void randMultivariateNormal(vector< vector<double> > const &sqrtCov,
// gsl_rng const * generator, vector<double> &sample)
// {
// /* Initialization. */
// unsigned int length(sqrtCov.size());
// vector<double> indep1DGaussians;
// indep1DGaussians.assign(length, 0.0);
// /* Construct W, a vector of independent N(0,1) rv's. */
// for (unsigned int i = 0; i < length; i++)
// indep1DGaussians[i] = gsl_ran_gaussian(generator, 1.0);
// /* Matrix-vector multiplication. */
// mvProduct(sqrtCov, indep1DGaussians, sample);
// }
double vectorNorm(vector<double> const &vectorRef, int const normChoice)
{
/* Initializations. */
double normValue(0.0);
unsigned int length(vectorRef.size());
switch (normChoice)
{
case 0:
/* Inifinity norm (does not return position of the maximum
* element). */
normValue = fabs(vectorRef[0]);
for (unsigned int i = 1; i < length; i++)
normValue = max<double>(normValue, fabs(vectorRef[i]));
break;
case 1:
/* 1-norm. */
for (unsigned int i = 0; i < length; i++)
normValue += fabs(vectorRef[i]);
break;
case 2:
/* 2-norm. */
for (unsigned int i = 0; i < length; i++)
normValue += pow(vectorRef[i], 2);
normValue = sqrt(normValue);
break;
default:
cout << "Error: vector norm choice " << normChoice
<< " not available." << endl;
exit(1);
}
return normValue;
}
int nCr(int const n, int const r)
{
/* Initializations. */
int largerDenom = max<int>(r, n - r);
int smallerDenom = n - largerDenom;
int result(1);
/* Cancel the larger of the denominator terms. */
for (int i = largerDenom; i < n; i++)
{
result *= i + 1;
if (result < 0)
return -1;
}
/* Final result. */
result /= int(tgamma(smallerDenom + 1));
return result;
}
// int binarySearch(double const query, double const * const refList,
// int const nLength, double const dCompTol)
// {
// /* Initializations. */
// int first(0), last(nLength-1);
// while (first <= last)
// {
// int mid = (first + last) / 2; /* Compute mid-point. */
// if (query - refList[mid] > dCompTol)
// first = mid + 1; /* Repeat search in top half. */
// else if (query - refList[mid] < -dCompTol)
// last = mid - 1; /* Repeat search in bottom half. */
// else
// return mid; /* Found it, return position. */
// }
// return -1; /* Failed to find key. */
// }
// void threeTermLegendre(double const x, int const maxDegree,
// double* const P)
// {
// /* Compute term via 3-term recursive formula. */
// for (int i = 0; i < maxDegree + 1; i++)
// {
// if (i == 0)
// P[0] = 1.0;
// else if (i == 1)
// P[1] = x;
// else
// P[i] = ((2.0 * double(i - 1) + 1.0) * x * P[i - 1]
// - double(i - 1) * P[i - 2]) / double(i);
// }
// }
// void threeTermHermite(double const x, int const maxDegree,
// double* const P)
// {
// /* Compute term via 3-term recursive formula. */
// for (int i = 0; i < maxDegree + 1; i++)
// {
// if (i == 0)
// P[0] = 1.0;
// else if (i == 1)
// P[1] = x;
// else
// P[i] = x * P[i - 1] - double(i - 1) * P[i - 2];
// }
// }
// void threeTermLegendreDerivatives(double const x, int const maxDegree,
// double const * const P, double* const dP)
// {
// /* Compute term via direct differentiation of the 3-term recursive
// * formula. */
// for (int i = 0; i < maxDegree + 1; i++)
// {
// if (i == 0)
// dP[0] = 0.0;
// else if (i == 1)
// dP[1] = 1.0;
// else
// dP[i] = ((2.0 * double(i - 1) + 1.0) * P[i - 1]
// + (2.0 * double(i - 1) + 1.0) * x * dP[i - 1]
// - double(i - 1) * dP[i - 2]) / double(i);
// }
// }
// void threeTermHermiteDerivatives(double const x, int const maxDegree,
// double const * const P, double* const dP)
// {
// /* Compute term via direct differentiation of the 3-term recursive
// * formula. */
// for (int i = 0; i < maxDegree + 1; i++)
// {
// if (i == 0)
// dP[0] = 0.0;
// else if (i == 1)
// dP[1] = 1.0;
// else
// dP[i] = double(i) * P[i - 1];
// }
// }
// void eigSymTridiag(int const &nLength, double* const diagonal,
// double* const subdiagonal, double const &abstol,
// double* const eigenVals, double* const eigenVecs,
// int* const ifailOut, double* const work, int* const iwork)
// {
// /* Memory allocation and initializations. */
// char jobzIn('V'), rangeIn('A');
// double vlIn(0.0), vuIn(0.0), abstolIn(abstol);
// int nIn(nLength), ilIn(0), iuIn(0), ldzIn(nLength), mOut(0), infoOut(0);
// /* Compute eigenvalue and eigenvectors. */
// dstevx_(jobzIn, rangeIn, nIn, diagonal, subdiagonal, vlIn, vuIn, ilIn, iuIn,
// abstolIn, mOut, eigenVals, eigenVecs, ldzIn, work, iwork, ifailOut,
// infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DSTEVX LAPACK function returned error. " << endl;
// exit(1);
// }
// }
// void mvProduct(int const nLength1, int const nLength2, double* const * const A,
// double* const xIn, double* const yOut)
// {
// /* Initialization. */
// char transIn('T');
// int mIn(nLength1), nIn(nLength2), ldaIn(nLength1), incxIn(1), incyIn(1);
// double alphaIn(1.0), betaIn(0.0);
// /* Matrix-vector multiplication. */
// dgemv_(transIn, mIn, nIn, alphaIn, A[0], ldaIn, xIn, incxIn, betaIn,
// yOut, incyIn);
// }
// void choleskyDecomp(int const nLength, double const * const * const A,
// double* const * const cholesky)
// {
// /* Initializations. */
// char uploIn('U');
// int infoOut(0), nIn(nLength), ldaIn(nLength);
// for (int i = 0; i < nLength; i++)
// {
// for (int j = 0; j < nLength; j++)
// {
// if (j <= i)
// cholesky[i][j] = A[i][j];
// else
// cholesky[i][j] = 0.0;
// }
// }
// /* Cholesky decomposition. */
// dpotrf_(uploIn, nIn, cholesky[0], ldaIn, infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DPOTRF LAPACK function returned error. " << endl;
// exit(1);
// }
// }
// double invCondNumber(int const length, double* const * const A,
// int* const ipivOut, double* const work, int* const iwork)
// {
// /* Initializations. */
// char normIn('1');
// double rcondOut(0.0);
// int nIn(length), ldaIn(length), infoOut(0);
// /* Compute norm of matrix. */
// double anormIn = dlange_(normIn, nIn, nIn, A[0], ldaIn, work);
// /* LU-factorize of matrix. */
// dgetrf_(nIn, nIn, A[0], ldaIn, ipivOut, infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DGETRF LAPACK function returned error. " << endl;
// exit(1);
// }
// /* Estimate inverse condition number. */
// dgecon_(normIn, nIn, A[0], ldaIn, anormIn, rcondOut, work, iwork,
// infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DGECON LAPACK function returned error. " << endl;
// exit(1);
// }
// return rcondOut;
// }
// void solveBandedLinearSystem(int const nLength, int const nSubdiagonals,
// int const nSuperdiagonals, double const * const * const A,
// double* const * const ABIn,
// int* const ipivOut, double* const uIn)
// {
// /* Initialization. */
// int nIn(nLength), klIn(nSubdiagonals), kuIn(nSuperdiagonals), nrhsIn(1);
// int ldabIn(2 * klIn + kuIn + 1), ldbIn(nLength), infoOut(0);
// /* Create LAPACK-requested LHS matrix format. Note the transpose. */
// for (int i = 0; i < nLength * (2 * klIn + kuIn + 1); i++)
// ABIn[0][i] = 0.0;
// for (int j = 0; j < nLength; j++)
// {
// for (int i = max(0, j - kuIn); i < min(nLength, j + 1 + klIn); i++)
// ABIn[j][klIn + kuIn + i - j] = A[i][j];
// }
// /* Solve a banded linear system. */
// dgbsv_(nIn, klIn, kuIn, nrhsIn, ABIn[0], ldabIn, ipivOut, uIn, ldbIn,
// infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DGBSV LAPACK function returned error code "
// << infoOut << ". " << endl;
// exit(1);
// }
// }
// void solveBandedLinearSystemFromLU(int const nLength, int const nSubdiagonals,
// int const nSuperdiagonals,
// double * const * const AB,
// int* const ipivIn, double* const bIn)
// {
// /* Initialization. */
// char trans('N');
// int nIn(nLength), klIn(nSubdiagonals), kuIn(nSuperdiagonals), nrhsIn(1);
// int ldabIn(2 * klIn + kuIn + 1), ldbIn(nLength), infoOut(0);
// /* Solve a banded linear system from available LU. */
// dgbtrs_(trans, nIn, klIn, kuIn, nrhsIn, AB[0], ldabIn, ipivIn, bIn, ldbIn,
// infoOut);
// if (infoOut != 0)
// {
// cout << "Error: DGBTRS LAPACK function returned error code "
// << infoOut << ". " << endl;
// exit(1);
// }
// }
/* Note: ATrans, B will be over-written. ATrans is also stored in the
* transposed form of the actual algebraic form of the A matrix, due
* to LAPACK needs. */
void linearLeastSquares(vector< vector<double> > &ATrans,
vector<double> &sOut, vector<double> &B,
vector<double> &work, int const workLength,
vector<double> &soln)
{
/* Note that ATrans is the transposed matrix. */
unsigned int nCols = ATrans.size();
unsigned int nRows = ATrans[0].size();
int mIn(nRows), nIn(nCols), nrhsIn(1), ldaIn(nRows), ldbIn(nRows);
double rcondIn(-1.0);
int rankOut(0), lwork(workLength), infoOut(0);
static double** ATransDblPtr = new double*[nCols];
static double* ATransPtr = new double[nCols * nRows];
ATransDblPtr[0] = ATransPtr;
for (unsigned int i = 1; i < nCols; i++)
ATransDblPtr[i] = ATransDblPtr[i - 1] + nRows;
for (unsigned int i = 0; i < nCols; i++)
{
for (unsigned int j = 0; j < nRows; j++)
ATransDblPtr[i][j] = ATrans[i][j];
}
/* Solve linear least squares problem. */
dgelss_(mIn, nIn, nrhsIn, ATransPtr, ldaIn, &(B[0]), ldbIn, &(sOut[0]),
rcondIn, rankOut, &(work[0]), lwork, infoOut);
/* Extract the solution part from the B vector. */
for (unsigned int i = 0; i < nCols; i++)
soln[i] = B[i];
if (infoOut != 0)
{
cout << "Error: DGELSS LAPACK function returned error code "
<< infoOut << ". " << endl;
exit(1);
}
}
| true |
4d1e14246c4116ab0a796761ff6507208f76b9da | C++ | AllexSmartHouse/ASNPRouter | /software/STM32RouterArduinoSketch/PortHandler.h | UTF-8 | 2,201 | 2.65625 | 3 | [] | no_license | #ifndef PORT_HANDLER_H
#define PORT_HANDLER_H
#include <Arduino.h>
#include "ProtocolListener.h"
const uint8_t START_CHAR_POS = 0;
const uint8_t ADDRESS_POS = 1;
const uint8_t LENGTH_POS = 2;
const uint8_t DATA_START_POS = 3;
const uint8_t SYS_MSG = 0;
const uint8_t BROADCAST_ADDRESS = 0x00;
const uint8_t START_CHAR_LOW = 0x04;
const uint8_t START_CHAR_HIGH = 0x05;
//HIGH PRIORITY. ALL ADDRESSES, 2 BYTE DATA, SYSMSG PING CHECKSUM
const uint8_t PING_BROADCAST[6] = {START_CHAR_HIGH, BROADCAST_ADDRESS,0x02, 0x00, 0x00, START_CHAR_HIGH +BROADCAST_ADDRESS +0x02 +0x00 +0x00};
class cPortHandler{
public:
static const long SEND_BUFFER_SIZE = 2048;
static const long HALF_SEND_BUFFER_SIZE = SEND_BUFFER_SIZE / 2;
static const long PACKAGE_SERVICE_DATA_SIZE = 1+1+1+1; //PACKAGE_START_CHAR + ADDRESS + DATA_SIZE + CHECKSUM
static const long MAX_PACKAGE_DATA_SIZE = 255;
static const long PACKAGE_BUFFER_SIZE = MAX_PACKAGE_DATA_SIZE + PACKAGE_SERVICE_DATA_SIZE;
enum eWaitState{
WAIT_START,
WAIT_ADDRESS,
WAIT_LENGTH,
WAIT_CHECKSUM
};
void receive(uint8_t data, bool clear);
private:
uint8_t* m_SendBuffer;
int m_SendBufferSize;
uint8_t* m_ReceiveBuffer;
int m_ReceiveBufferSize;
uint8_t m_Checksum;
eWaitState m_ReceiverState;
SerialUART* m_Stream;
cProtocolListenersList m_ListenersList;
bool m_Overflow;
bool m_DataError;
long m_TimeFromLastData;
public:
cPortHandler(SerialUART* serial);
~cPortHandler(){
delete [] m_SendBuffer;
delete [] m_ReceiveBuffer;
}
void queuePackage(const uint8_t* data);
bool startSending();
bool processData(long dt);
uint8_t* getReceivedPackage(){
return m_ReceiveBuffer;
}
void clearReceivedPackage(){
m_ReceiveBufferSize = 0;
}
void setAddressEnable(uint8_t address){
m_ListenersList.setAddressEnable(address);
}
bool isOverflow(){return m_Overflow;}
bool isDataError(){return m_DataError;}
};
#endif
| true |
428dc8af82d065424449ad617c18c5737e2a2d31 | C++ | archylex/Nebula-Psi | /NebulaPsi/Classes/Weapon.cpp | UTF-8 | 2,235 | 2.734375 | 3 | [] | no_license | #include "Weapon.h"
// Create missile sprite
Weapon *Weapon::create(string _name, bool _isEnemy, int _type) {
Weapon *_weapon = new Weapon();
if(_weapon && _weapon->initialize(_name, _isEnemy, _type)) {
_weapon->autorelease();
return _weapon;
}
CC_SAFE_DELETE(_weapon);
return nullptr;
}
// Property initialization
bool Weapon::initialize(string _name, bool _isEnemy, int _type) {
// Missile type (fire or plasma)
typeWeapon = _type;
// isDead
isDead = false;
// Speed from public variables (config)
speed = PublicVariables::Instance()->getMissileSpeed();
// Set image
this->setSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(_name));
// Set anchor point
this->setAnchorPoint(Vec2(0.5f, 0.5f));
// Create emitter
string emitterName[] = { "MissileEmitter.png", "PlasmaEmitter.png" };
emitter = Sprite::createWithSpriteFrameName(emitterName[typeWeapon]);
emitter->setAnchorPoint(Vec2(0.5f, 1.0f));
emitter->setPosition(this->getContentSize().width/2, 0.0f);
this->addChild(emitter);
// Emitter animation
auto little = ScaleTo::create(0.2f, 1.5f);
auto big = ScaleTo::create(0.2f, 1.0f, 2.7f);
auto seq = Sequence::create(little, big, NULL);
auto anim = RepeatForever::create(seq);
emitter->runAction(anim);
// Whose missile
if (_isEnemy) {
// Rotate missile
this->setRotation(180);
// Inverse path
speed *= -1;
}
return true;
}
// Update missile
void Weapon::update(float dt) {
this->setPosition(Vec2(this->getPosition().x, this->getPosition().y + speed * dt));
}
// Set missile position
void Weapon::setStartPosition(Vec2 _pos) {
this->setPosition(_pos);
}
// Get missile y-position
float Weapon::getYPosition() {
return this->getPosition().y;
}
// Get missile type (fire or plasma)
int Weapon::getType() {
return typeWeapon;
}
// Set isDead
void Weapon::setIsDead() {
isDead = true;
}
bool Weapon::getIsDead() {
return isDead;
}
// Pause particle system
void Weapon::pauseParticle() {
emitter->pause();
}
// Resume particle system
void Weapon::resumeParticle() {
emitter->resume();
}
| true |
fed31a0fcd70a9740752813350165cb6f6239b30 | C++ | davidcorne/cpp-sandbox | /MutableReferences.cpp | UTF-8 | 1,479 | 2.78125 | 3 | [] | no_license | //=============================================================================
//
//
#include <UnitCpp.h>
class NonConstClass;
//=============================================================================
class MutableReference {
public:
MutableReference(NonConstClass& r);
int calculate() const;
// Note: const.
MutableReference(const MutableReference&) = delete;
MutableReference& operator=(const MutableReference&) = delete;
private:
NonConstClass& m_r;
};
//=============================================================================
class NonConstClass {
public:
void change_value();
// Note: non-const.
private:
int m_int;
};
//=============================================================================
MutableReference::MutableReference(NonConstClass& r)
: m_r(r)
{
}
//=============================================================================
int MutableReference::calculate() const
{
m_r.change_value();
return 5;
}
//=============================================================================
void NonConstClass::change_value()
{
m_int = 5;
}
//=============================================================================
TEST(MutableReferences, )
{
NonConstClass c;
MutableReference r(c);
r.calculate();
}
//=============================================================================
int main(int argc, char** argv)
{
return UnitCpp::TestRegister::test_register().run_tests_interactive(argc, argv);
}
| true |
1f641412f1155af37fe2dd917babd3caf64360c9 | C++ | yangzebin001/OJ | /POJ/POJ1426B.cpp | UTF-8 | 491 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
typedef unsigned long long ULL;
int n;
void bfs(int n){
int ans = 1;
queue<ULL> q;
while(!q.empty()) q.pop();
q.push(ans);
while(q.size()){
ULL i = q.front();q.pop();
if(i % n == 0){
printf("%llu\n",i);
return;
}
q.push(i*10);
q.push(i*10+1);
}
}
int main(){
while(~scanf("%d",&n) && n){
bfs(n);
}
return 0;
} | true |
1c27cf60ef2f70dd76517bdf30d4e5d9c09b4a64 | C++ | lostsoul3/DS-Algo | /triplestep.cpp | UTF-8 | 516 | 3.390625 | 3 | [] | no_license | /*
A child can run 1,2,3 steps at a time. count no. of ways a child can run.
*/
#include <bits/stdc++.h>
using namespace std;
int countways(int n,vector<int> m)
{
if(n<0)
return 0;
else if(n==0)
return 1;
else if(m[n]>-1)
return m[n];
else
{
m[n] = countways(n-1,m)+countways(n-2,m)+countways(n-3,m);
return m[n];
}
}
int main() {
int n;
cin>>n;
vector<int> m;
for(int i=0;i<=n;i++)
{
m.push_back(-1);
}
cout<<countways(n,m);
return 0;
}
| true |
1e8a498f78c71871cbf59dc3db5828b1a6bb7248 | C++ | DandelionLU/code-camp | /backup/2/leetcode/c++/all-elements-in-two-binary-search-trees.cpp | UTF-8 | 1,868 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/leetcode/all-elements-in-two-binary-search-trees.html .
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> getAllElements(TreeNode *root1, TreeNode *root2) {
auto nums1 = getAllElements(root1);
auto nums2 = getAllElements(root2);
vector<int> res;
int i = 0, j = 0, m = nums1.size(), n = nums2.size();
while (i < m && j < n) {
if (nums1[i] <= nums2[j]) {
res.push_back(nums1[i]);
i++;
} else {
res.push_back(nums2[j]);
j++;
}
}
while (i < m) {
res.push_back(nums1[i]);
i++;
}
while (j < n) {
res.push_back(nums2[j]);
j++;
}
return res;
}
vector<int> getAllElements(TreeNode *root) {
if (root == nullptr) {
return vector<int>();
}
auto lefts = getAllElements(root->left);
auto rights = getAllElements(root->right);
lefts.push_back(root->val);
lefts.insert(lefts.end(), rights.begin(), rights.end());
return lefts;
}
};
| true |
7ae252754b682bbf9dd466de780c4663e509a15d | C++ | Gapex/CppPrimer | /Chapter7/7.21.cpp | UTF-8 | 2,259 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
class Sales_data;
std::istream &read(std::istream &in, Sales_data &ref);
std::ostream &print(std::ostream &out, const Sales_data &ref2C);
Sales_data add(const Sales_data &lh, const Sales_data &rh);
class Sales_data
{
std::string bookNo;
unsigned units_sold;
double revenue;
double price;
//friend声明
friend std::istream &read(std::istream &in, Sales_data &ref);
friend std::ostream &print(std::ostream &out, const Sales_data &ref2C);
friend Sales_data add(const Sales_data &lh, const Sales_data &rh);
public:
std::string isbn() const { return bookNo; }
Sales_data &combine(const Sales_data &rhs);
//因为需要提供其他构造函数,因此也需要定义自己的默认构造函数
Sales_data() = default; //隐式inline
Sales_data(std::istream &in) //从输入流读入,类内定义,称为隐式inline
{
read(in, *this);
}
Sales_data(std::string bookNo);
Sales_data(std::string bookNo, unsigned units_sold, double price);
};
Sales_data &Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
price = revenue / units_sold;
return *this;
}
std::istream &read(std::istream &in, Sales_data &ref)
{
in >> ref.bookNo >> ref.units_sold >> ref.price;
ref.revenue = ref.units_sold * ref.price;
return in;
}
std::ostream &print(std::ostream &out, const Sales_data &ref2C)
{
out << ref2C.bookNo << " "
<< ref2C.units_sold << ' '
<< ref2C.revenue << ' '
<< ref2C.price;
}
Sales_data add(const Sales_data &lh, const Sales_data &rh)
{
Sales_data ans = lh;
ans.combine(rh);
return ans;
}
using std::cin;
using std::cout;
using std::endl;
int main()
{
Sales_data total(cin);
if (cin)
{
Sales_data trans(cin);
while (cin)
{
if (trans.isbn() == total.isbn())
{
total = add(total, trans);
}
else
{
print(cout, total) << endl;
total = trans;
}
trans = Sales_data(cin);
}
print(cout, total) << endl;
}
return 0;
} | true |
3e510db8b53f1b1a7445367b173bdbe45e2f26e6 | C++ | HENRYHKll/gb_cxx_oop | /lesson3/main.cxx | UTF-8 | 10,945 | 3.625 | 4 | [] | no_license | #include <cstdint>
#include <iostream>
/*
Создать абстрактный класс Figure (фигура). Его наследниками являются классы
Parallelogram (параллелограмм) и Circle (круг). Класс Parallelogram — базовый
для классов Rectangle (прямоугольник), Square (квадрат), Rhombus (ромб). Для
всех классов создать конструкторы. Для класса Figure добавить чисто виртуальную
функцию area() (площадь). Во всех остальных классах переопределить эту функцию,
исходя из геометрических формул нахождения площади.
*/
class Figure
{
protected:
double m_a;
public:
Figure(double a)
: m_a(a)
{
}
virtual int area() = 0;
};
class Parallelogram : public Figure
{
protected:
double m_b;
public:
Parallelogram(double b, double a)
: Figure(a)
, m_b(b){};
int area() override { return m_a * m_b; }
};
class Circle : public Figure
{
double m_p = 3.14;
public:
Circle(double r)
: Figure(r){};
int area() override { return m_a * m_p; };
};
class Rectangle : public Parallelogram
{
public:
Rectangle(double b, double a)
: Parallelogram(b, a){};
int area() override { return m_a * m_b; }
};
class Square : public Parallelogram
{
public:
Square(double b, double a)
: Parallelogram(b, a){};
int area() override { return m_a * m_b; }
};
class Rhombus : public Parallelogram
{
public:
Rhombus(double b, double a)
: Parallelogram(b, a){};
int area() override { return m_a * m_b; }
};
void task1()
{
Parallelogram a(3, 6);
Circle b(3.3);
Rectangle c(7, 4);
Square d(5, 5);
Rhombus f(3, 9);
std::cout << "Parallelogram " << a.area() << " area " << std::endl;
std::cout << "Circle " << b.area() << " area " << std::endl;
std::cout << "Rectangle " << c.area() << " area " << std::endl;
std::cout << "Square " << d.area() << " area " << std::endl;
std::cout << "Rhombus " << f.area() << " area " << std::endl;
}
/*
Создать класс Car (автомобиль) с полями company (компания) и model (модель).
Классы-наследники: PassengerCar (легковой автомобиль) и Bus (автобус). От этих
классов наследует класс Minivan (минивэн). Создать конструкторы для каждого из
классов, чтобы они выводили данные о классах. Создать объекты для каждого из
классов и посмотреть, в какой последовательности выполняются конструкторы.
Обратить внимание на проблему «алмаз смерти». Примечание: если использовать
виртуальный базовый класс, то объект самого "верхнего" базового класса создает
самый "дочерний" класс.
*/
class Car
{
protected:
std::string m_company, m_model;
public:
Car(std::string company, std::string model)
: m_company(company)
, m_model(model){};
virtual void print()
{
std::cout << "Class Car"
<< " " << m_company << " " << m_model << std::endl;
};
};
class PassengerCar : public virtual Car
{
public:
PassengerCar(std::string company, std::string model)
: Car(company, model){};
void print() override
{
std::cout << "Class PassengerCar"
<< " " << m_company << " " << m_model << std::endl;
};
};
class Bus : public virtual Car
{
public:
Bus(std::string company, std::string model)
: Car(company, model){};
void print() override
{
std::cout << "Class Bus"
<< " " << m_company << " " << m_model << std::endl;
};
};
class Minivan : public PassengerCar, public Bus
{
public:
Minivan(std::string company, std::string model)
: PassengerCar(company, model)
, Bus(company, model)
, Car(company, model){};
void print() override
{
std::cout << "Class Minivan"
<< " " << m_company << " " << m_model << std::endl;
}
};
void task2()
{
Car aa("Mercedes-Benz", "V-Class");
PassengerCar a("Mercedes-Benz", "V-Class");
Bus b("Mercedes-Benz", "V-Class");
Minivan c("Mercedes-Benz", "V-Class");
aa.print();
a.print();
b.print();
c.print();
}
/*
Создать класс: Fraction (дробь). Дробь имеет числитель и знаменатель (например,
3/7 или 9/2). Предусмотреть, чтобы знаменатель не был равен 0.
Перегрузить:
* математические бинарные операторы (+, -, *, /) для выполнения действий с
дробями
* унарный оператор (-)
* логические операторы сравнения двух дробей (==, !=, <, >, <=, >=).
Примечание: Поскольку операторы < и >=, > и <= — это логические
противоположности, попробуйте перегрузить один через другой. Продемонстрировать
использование перегруженных операторов.
*/
class Fraction
{
int m_numerator, m_denominator;
public:
Fraction(int numerator, int denominator)
{
if (denominator != 0)
{
m_numerator = numerator;
m_denominator = denominator;
}
else
throw std::runtime_error("ERROR! Denominator can't be 0");
}
friend Fraction operator+(const Fraction& d1, const Fraction& d2);
friend Fraction operator-(const Fraction& d1, const Fraction& d2);
friend Fraction operator*(const Fraction& d1, const Fraction& d2);
friend Fraction operator/(const Fraction& d1, const Fraction& d2);
friend bool operator>(const Fraction& d1, const Fraction& d2);
friend bool operator>=(const Fraction& d1, const Fraction& d2);
friend bool operator<(const Fraction& d1, const Fraction& d2);
friend bool operator<=(const Fraction& d1, const Fraction& d2);
friend bool operator!=(const Fraction& d1, const Fraction& d2);
friend bool operator==(const Fraction& d1, const Fraction& d2);
Fraction operator-() const { return Fraction(-m_numerator, m_denominator); }
void print() { std::cout << m_numerator << "/" << m_denominator << " "; }
int getNumerator() { return m_numerator; }
int getDenominator() { return m_denominator; }
};
Fraction operator+(const Fraction& d1, const Fraction& d2)
{
return Fraction(
(d1.m_numerator * d2.m_denominator + d2.m_numerator * d1.m_denominator),
d1.m_denominator * d2.m_denominator);
}
Fraction operator-(const Fraction& d1, const Fraction& d2)
{
return Fraction(
(d1.m_numerator * d2.m_denominator - d2.m_numerator * d1.m_denominator),
d1.m_denominator * d2.m_denominator);
}
Fraction operator*(const Fraction& d1, const Fraction& d2)
{
return Fraction(d1.m_numerator * d2.m_numerator,
d1.m_denominator * d2.m_denominator);
}
Fraction operator/(const Fraction& d1, const Fraction& d2)
{
return Fraction(d1.m_numerator * d2.m_denominator,
d1.m_denominator * d2.m_numerator);
}
bool operator>(const Fraction& d1, const Fraction& d2)
{
return ((d1.m_numerator / d1.m_denominator) >
(d2.m_numerator / d2.m_denominator));
}
bool operator>=(const Fraction& d1, const Fraction& d2)
{
return ((d1.m_numerator / d1.m_denominator) >=
(d2.m_numerator / d2.m_denominator));
}
bool operator<(const Fraction& d1, const Fraction& d2)
{
return !((d1.m_numerator / d1.m_denominator) >=
(d2.m_numerator / d2.m_denominator));
}
bool operator<=(const Fraction& d1, const Fraction& d2)
{
return !((d1.m_numerator / d1.m_denominator) >
(d2.m_numerator / d2.m_denominator));
}
bool operator!=(const Fraction& d1, const Fraction& d2)
{
return !((d1.m_numerator / d1.m_denominator) ==
(d2.m_numerator / d2.m_denominator));
}
bool operator==(const Fraction& d1, const Fraction& d2)
{
return ((d1.m_numerator / d1.m_denominator) ==
(d2.m_numerator / d2.m_denominator));
}
void task3()
{
Fraction a(1, 2);
Fraction b(1, 3);
Fraction Sum = a + b;
Fraction Sub = a - b;
Fraction Div = a / b;
Fraction Mult = a * b;
Fraction Unar = -a;
bool w1 = a == b;
bool w2 = a != b;
bool w3 = a < b;
bool w4 = a > b;
bool w5 = a <= b;
bool w6 = a >= b;
Sum.print();
Sub.print();
Div.print();
Mult.print();
Unar.print();
}
/*
Создать класс Card, описывающий карту в игре БлэкДжек. У этого класса должно
быть три поля: масть, значение карты и положение карты (вверх лицом или
рубашкой). Сделать поля масть и значение карты типом перечисления (enum).
Положение карты - тип bool. Также в этом классе должно быть два метода: метод
Flip(), который переворачивает карту, т.е. если она была рубашкой вверх, то он
ее поворачивает лицом вверх, и наоборот. метод GetValue(), который возвращает
значение карты, пока можно считать, что туз = 1.
*/
class Card
{
public:
enum SUIT
{
HEART,
CLUB,
DIAMOND,
SPADE
};
enum VALUE
{
ACE = 1,
TWO = 2,
THREE = 3,
FOUR = 4,
FIVE = 5,
SIX = 6,
SEVEN = 7,
EIGHT = 8,
NINE = 9,
TEN = 10,
JACK = 10,
QUEN = 10,
KING = 10
};
private:
SUIT m_suit;
VALUE m_value;
bool m_position;
public:
Card(SUIT s = CLUB, VALUE v = ACE, bool position = 0)
: m_suit(s)
, m_value(v)
, m_position(position)
{
}
bool Flip() { m_position = !(m_position); }
int GetValue()
{
int value = 0;
if (m_position)
{
value = m_value;
}
return value;
}
};
int main(int argc, char** args)
{
task1();
task2();
task3();
}
| true |
793d7fc65acb8cc5d4e8ded262f029bbeda5a913 | C++ | HongJungWan/KSA | /Module01. 컴퓨터과학 심화/Ch10. 배열과 포인터/예제10_2.cpp | UTF-8 | 243 | 3.15625 | 3 | [] | no_license |
// 예제 10-2. 배열명 역할을 하는 포인터
#include <stdio.h>
int main(void) {
int ary[3];
int *pa = ary;
int i;
*pa = 10;
*(pa+1) = 20;
pa[2] =pa[0]+pa[1];
for (i=0; i<3; i++);
{
printf("%5d", pa[i]);
}
return 0;
}
| true |
cbb4640e667e4ae1bfb8a0882a606b607952bec4 | C++ | AdhaarSharma/DSA | /PrefixUniqueRowBooleanMatrix/main.cpp | UTF-8 | 762 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ROW 4
#define COL 5
void findUniqueRows(int M[ROW][COL]){
for(int i=0; i<ROW; i++){
int flag=0;
for(int j=0; j<i; j++){
flag=1;
for(int k=0; k<COL; k++)
if(M[i][k]!=M[j][k])
flag=0;
if(flag==1)
break;
}
if(flag==0){
for(int k=0; k<COL; k++)
cout<<M[i][k]<<" ";
cout<<endl;
}
}
}
// Driver Code
int main()
{
int M[ROW][COL] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 0, 0}};
findUniqueRows(M);
return 0;
}
| true |
8fd2086b558848537754a7d65e711b5e4ce99c2f | C++ | Basez/Agnostik-Engine | /include/common/i_logger.hpp | UTF-8 | 826 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
namespace AGN
{
enum class ELoggerOutputType
{
Window = 1,
Internal = 2, // TODO: create internal console (shown inside the main render window)
OutputDebug = 4, // windows only, shows logs in visual studio console
};
enum class ELogTimeType
{
RunningTime,
SystemTime
};
class ILogger
{
public:
virtual ~ILogger(){};
virtual void init(ELogTimeType a_timeType, uint8_t a_outputTypes) = 0;
virtual void cleanup() = 0;
virtual void info(const char *a_info, ...) = 0;
virtual void debug(const char *a_debugInfo, ...) = 0;
virtual void warning(const char *a_warning, ...) = 0;
virtual void error(const char *a_error, ...) = 0;
static const int MAX_LOG_BUFFER = 2048;
};
}
// reference to the global logger (implemented in platform specific class)
extern AGN::ILogger& g_log;
| true |
dbd18493dcb9b3c58a638339f0518cd06f5244e5 | C++ | MagiaGroz/Algorithms | /Sort/MID-EXAMPLES/SHOPPING.cpp | UTF-8 | 483 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> vec;
int n,x;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
vec.push_back(x);
}
sort(vec.begin(),vec.end());
double res;
int i=0;
while(vec.size()!=1){
if(i==vec.size()-1){
sort(vec.begin(),vec.end());
i=0;
}
vec[i+1]=vec[i]+vec[i+1];
res+=vec[i+1]*0.05;
vec.erase(vec.begin()+i);
cout<<vec[i]<<" ";
i++;
}
printf("%.6lf",res);
return 0;
}
| true |
c17bc9a736fffbc7e215de6b141d96e18b168cc8 | C++ | johnsietsma/AIE_OpenGLTutorials | /AIEOpenGL/src/UtilitySystems/World.cpp | UTF-8 | 2,992 | 2.75 | 3 | [] | no_license | #include "World.h"
#include "Gizmos.h"
#include "gl_core_4_4.h"
#include <GLFW\glfw3.h>
#include <iostream>
World::World()
{
m_houseLocation = glm::vec3(10, 0, -10);
m_treeLocation = glm::vec3(-10, 0, -10);
m_foodLocation = glm::vec3(10, 0, 10);
m_waterLocation = glm::vec3(0, 0, 10);
m_restedLocation = glm::vec3(-10, 0, 10);
m_uiHouseCurrentLogs = 4;
m_uiHouseLogsRequired = 10;
m_fRestedInteractTime = 1.0f;
m_fWaterInteractTime = 2.0f;
m_fFoodInteractTime = 2.0f;
m_fHouseInteractTime = 3.0;
m_fTreeInteractTime = 1.0f;
m_fLastFoodInteractTime = 0.0f;
m_fLastWaterInteractTime = 0.0f;
m_fLastRestedInteractTime = 0.0f;
m_fLastHouseInteractTime = 0.0f;
m_fLastTreeInteractTime = 0.0f;
}
World::~World()
{
}
void World::render()
{
Gizmos::addSphere(m_foodLocation, 1, 8, 8, glm::vec4(1, 0, 0, 1));
Gizmos::addSphere(m_waterLocation, 1, 8, 8, glm::vec4(0, 0, 1, 1));
Gizmos::addSphere(m_restedLocation, 1, 8, 8, glm::vec4(0, 1, 1, 1));
float m_fHouseHeight = 3 * ((float)m_uiHouseCurrentLogs / m_uiHouseLogsRequired);
glm::vec4 houseColor = (m_uiHouseCurrentLogs >= m_uiHouseLogsRequired) ? glm::vec4(0, 1, 0, 1) : glm::vec4(1, 1, 0, 1);
Gizmos::addAABBFilled(m_houseLocation + glm::vec3(0, m_fHouseHeight, 0), glm::vec3(3, m_fHouseHeight, 2), houseColor);
Gizmos::addCylinderFilled(m_treeLocation, 1, 2, 8, glm::vec4(0, 1, 0, 1));
}
void World::addLogToHouse()
{
if (m_uiHouseCurrentLogs < m_uiHouseLogsRequired)
m_uiHouseCurrentLogs++;
}
bool World::interactWithFood()
{
float fCurrentTime = (float)glfwGetTime();
if (fCurrentTime >= m_fLastFoodInteractTime + m_fFoodInteractTime)
{
m_fLastFoodInteractTime = fCurrentTime;
return true;
}
return false;
}
bool World::interactWithWater()
{
float fCurrentTime = (float)glfwGetTime();
if (fCurrentTime >= m_fLastWaterInteractTime + m_fWaterInteractTime)
{
m_fLastWaterInteractTime = fCurrentTime;
return true;
}
return false;
}
bool World::interactWithRested()
{
float fCurrentTime = (float)glfwGetTime();
if (fCurrentTime >= m_fLastRestedInteractTime + m_fRestedInteractTime)
{
m_fLastRestedInteractTime = fCurrentTime;
return true;
}
return false;
}
bool World::interactWithTree()
{
float fCurrentTime = (float)glfwGetTime();
if (fCurrentTime >= m_fLastTreeInteractTime + m_fTreeInteractTime)
{
m_fLastTreeInteractTime = fCurrentTime;
return true;
}
return false;
}
bool World::interactWithHouse()
{
float fCurrentTime = (float)glfwGetTime();
if (fCurrentTime >= m_fLastHouseInteractTime + m_fHouseInteractTime)
{
m_fLastHouseInteractTime = fCurrentTime;
return true;
}
return false;
}
glm::vec3 World::getRestedLocation() const
{
return m_restedLocation;
}
glm::vec3 World::getFoodLocation() const
{
return m_foodLocation;
}
glm::vec3 World::getWaterLocation() const
{
return m_waterLocation;
}
glm::vec3 World::getTreeLocation() const
{
return m_treeLocation;
}
glm::vec3 World::getHouseLocation() const
{
return m_houseLocation;
}
| true |
b899418acd63c350812ee591bdc51270afbeb49b | C++ | seanbaxter/circle | /fmt/test3.cxx | UTF-8 | 951 | 3.59375 | 4 | [] | no_license | #include "format.hxx"
enum class shape_t {
circle,
square,
octagon,
triangle,
};
int main() {
shape_t shapes[] {
shape_t::square,
shape_t::octagon,
shape_t::triangle,
(shape_t)27
};
// Print the enums in the array with default settings. The enumerator names
// are printed when available.
"shapes = {shapes}\n"_print;
// Center the enum names and use '~' to fill.
"shapes = {shapes:~^15}\n"_print;
// Use reflection to print all enum names in a loop.
"Your enum names are:\n"_print;
int counter = 0;
@meta for enum(shape_t e : shape_t)
"{counter++}: {@enum_name(e)}\n"_print;
// Print all enum names using format pack expansion. This puts them
// all in a collection.
"enum names = {...@enum_names(shape_t)}\n"_print;
// Use 12-character width and center. This applies to
// each element in the pack expansion.
"enum names = {...@enum_names(shape_t):^12}\n"_print;
return 0;
} | true |
8625c5070b19bcd9b5cf86513b48b2a0d19b7b57 | C++ | paulngouchet/CrackingTheCodingInterviewHackerRank | /crackingTheCodingInterview/leftRotation.cpp | UTF-8 | 1,315 | 3.265625 | 3 | [] | no_license | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
// Left rotations
// 1 2 3 4 5 -> 2 3 4 5 1 -> 3 4 5 1 2 -> 4 5 1 2 3 -> 5 1 2 3 4
vector<int> array_left_rotation(vector<int> a, int n, int k) {
// n is the number of element of the array -> a.size()
// K number of left rotation
vector<int> finalVector = a;
for(int i = 0 ; i < k ; i++)
{
finalVector.push_back(finalVector[0]); //copies the first element at the last position
finalVector.erase(finalVector.begin()); // erases the first element and the code just keeps going until it iterates the number of left rotations rotations
}
return finalVector;
}
int main(){
int n;
int k;
cin >> n >> k;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
vector<int> output = array_left_rotation(a, n, k);
for(int i = 0; i < n;i++)
cout << output[i] << " ";
cout << endl;
return 0;
}
| true |
64b7f29c84413be92d64750033cab327397a3cbb | C++ | markoczy/2DGameSDK | /Project_2DGameSDK/include/2DGameSDK/core/asset/SoundBufferCache.h | UTF-8 | 1,078 | 2.703125 | 3 | [
"MIT"
] | permissive | /**
* @file SoundBufferCache.h
* @author Aleistar Markoczy (a.markoczy@gmail.com)
* @brief SoundBufferCache class
* @version 1.0
* @date 2020-01-15
*
* @copyright Copyright (c) 2020
*
*/
#ifndef __SOUND_BUFFER_CACHE_H__
#define __SOUND_BUFFER_CACHE_H__
#include <SFML/Audio.hpp>
#include <2DGameSDK/core/asset/ResourceCache.h>
#include <2DGameSDK/dll/gamesdk_dll.h>
namespace game {
/**
* @brief Loads and Caches SFML SoundBuffer Objects
*
*/
class GAMESDK_DLL SoundBufferCache : public ResourceCache<sf::SoundBuffer*> {
/**
* @brief Function that loads or creates the requested SFML SoundBuffer
*
* @param identifier The unique identifier of the SoundBuffer
*
* @return The SFML SoundBuffer
*/
sf::SoundBuffer* createResource(const std::string& identifier);
/**
* @brief Functions that destroys the given SFML SoundBuffer
*
* @param resource The SoundBuffer to destroy
*/
virtual void destroyResource(sf::SoundBuffer* resource);
};
} // namespace game
#endif | true |
d04632cb357d8b809c5209d7f6a20450021ca5a3 | C++ | jbenipal/dstl | /edge.h | UTF-8 | 385 | 2.921875 | 3 | [] | no_license | #pragma once
namespace dstl {
typedef unsigned int vertex;
typedef int weight;
class Edge {
public:
Edge(vertex n, weight w, Edge *next = nullptr)
: node(n)
, weight(w)
, next(next) {}
vertex node;
weight weight;
Edge* next;
Edge* operator++() {
return next;
}
};
} | true |
1f83c733041db0022557ec2f063e801d8cb11db3 | C++ | jdleesmiller/twenty48 | /ext/twenty48/policy_reader.cxx | UTF-8 | 701 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "policy_reader.hpp"
namespace twenty48 {
policy_reader_t::policy_reader_t(const char *pathname)
: is(pathname, std::ios::in | std::ios::binary), data(0), offset(0)
{ }
void policy_reader_t::skip(size_t num_states) {
size_t byte_offset = num_states / 4;
is.seekg(byte_offset);
for (size_t i = 0; i < num_states % 4; ++i) {
read();
}
}
direction_t policy_reader_t::read() {
if (offset % 4 == 0) {
is.read(reinterpret_cast<char *>(&data), sizeof(data));
if (!is) {
throw std::runtime_error("policy_reader_t: read failed");
}
offset = 1;
} else {
offset += 1;
}
int shift = 2 * (4 - offset);
return (direction_t)((data >> shift) & 0x3);
}
}
| true |
9969fcd58845d6119226f7d34392529805a73218 | C++ | cubeman99/SEAL | /src/graphics/VertexData.h | UTF-8 | 10,447 | 3.015625 | 3 | [
"MIT"
] | permissive | #ifndef _VERTEX_DATA_H_
#define _VERTEX_DATA_H_
#include <graphics/Color.h>
#include "OpenGLIncludes.h"
#include <math/Vector2f.h>
#include <math/Vector3f.h>
#include <math/Matrix4f.h>
#include <assert.h>
//-----------------------------------------------------------------------------
// Standard vertex formats for models
//-----------------------------------------------------------------------------
// The format in which vertex lists or vertex element arrays are organized
// into primitives.
struct VertexPrimitiveType
{
typedef int value_type;
enum
{
POINTS = 0,
LINES,
LINE_STRIP,
LINE_LOOP, // A single line loop
TRIANGLES,
TRIANGLE_STRIP,
TRIANGLE_FAN,
QUADS,
QUAD_STRIP,
POLYGON, // This is a *single* polygon
NUM_VERTEX_PRIMITIVE_TYPES
};
};
struct PrimitiveList
{
int m_firstIndex;
int m_numIndices;
PrimitiveList() {}
PrimitiveList(int firstIndex, int indexCount) :
m_firstIndex(firstIndex),
m_numIndices(indexCount)
{}
};
//-----------------------------------------------------------------------------
// Standard vertex formats for models
//-----------------------------------------------------------------------------
struct VertexType
{
enum
{
POSITION = 0x1, // All vertices should have a position.
NORMAL = 0x2,
TEX_COORD = 0x4,
COLOR = 0x8,
};
};
// These locations are important for vertex shaders!!
struct VertexAttribLocations
{
enum
{
POSITION = 0, // layout (location = 0) in vec3 a_vertPos;
NORMAL = 1, // layout (location = 1) in vec3 a_vertNorm;
TEX_COORD = 2, // layout (location = 2) in vec2 a_vertTexCoord;
COLOR = 3, // layout (location = 3) in vec4 a_vertColor;
};
};
#define DECLARE_VERTEX_TYPE(_type) \
enum { kVertexType = _type }
struct VertexPosTexNormCol
{
Vector3f position;
Vector2f texCoord;
Vector3f normal;
Vector4f color;
VertexPosTexNormCol()
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION |
VertexType::TEX_COORD |
VertexType::NORMAL |
VertexType::COLOR);
};
// A vertex with a position, texture coordinate, and normal.
struct VertexPosTexNorm
{
Vector3f position;
Vector2f texCoord;
Vector3f normal;
VertexPosTexNorm()
{}
VertexPosTexNorm(const Vector3f& position, const Vector2f& texCoord, const Vector3f& normal) :
position(position), texCoord(texCoord), normal(normal)
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION |
VertexType::TEX_COORD |
VertexType::NORMAL);
};
struct VertexPosTexCol
{
Vector3f position;
Vector2f texCoord;
Vector4f color;
VertexPosTexCol()
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION |
VertexType::TEX_COORD |
VertexType::COLOR);
};
struct VertexPosNormCol
{
Vector3f position;
Vector3f normal;
Vector4f color;
VertexPosNormCol()
{}
VertexPosNormCol(const Vector3f& position) :
position(position)
{}
VertexPosNormCol(const Vector3f& position, const Vector3f& normal, const Vector4f& color) :
position(position), normal(normal), color(color)
{}
VertexPosNormCol(const Vector3f& position, const Vector3f& normal, const Color& color) :
position(position), normal(normal), color(color.ToVector4f())
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION |
VertexType::NORMAL |
VertexType::COLOR);
};
// A vertex with a position and texture coordinate.
struct VertexPosTex
{
Vector3f position;
Vector2f texCoord;
VertexPosTex(float x, float y, float z, float u, float v) :
position(x, y, z),
texCoord(u, v)
{}
VertexPosTex(const Vector3f& position, const Vector2f& texCoord) :
position(position),
texCoord(texCoord)
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION | VertexType::TEX_COORD);
};
struct VertexPosNorm
{
Vector3f position;
Vector3f normal;
VertexPosNorm()
{}
VertexPosNorm(const Vector3f& position, const Vector3f& normal) :
position(position),
normal(normal)
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION | VertexType::NORMAL);
};
struct VertexPosCol
{
Vector3f position;
Vector4f color;
VertexPosCol() {}
VertexPosCol(const Vector3f& position) :
position(position)
{}
VertexPosCol(const Vector3f& position, const Vector4f& color) :
position(position), color(color)
{}
VertexPosCol(const Vector3f& position, const Color& color) :
position(position), color(color.ToVector4f())
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION | VertexType::COLOR);
};
struct VertexPos
{
Vector3f position;
VertexPos(float x, float y, float z) :
position(x, y, z)
{}
VertexPos(const Vector3f& position) :
position(position)
{}
DECLARE_VERTEX_TYPE(VertexType::POSITION);
};
//-----------------------------------------------------------------------------
// OpenGL Vertex Buffer
//-----------------------------------------------------------------------------
// An object for storing a buffer of vertices interlaced a particlar set of
// attributes.
class VertexBuffer
{
friend class Renderer;
public:
// Constructors/destructor.
VertexBuffer();
~VertexBuffer();
// Accessors.
int GetVertexCount() const;
// Mutators.
template <class T>
void SetVertices(int numVertices, const T* vertices);
private:
public:
int m_numVertices; // The number of vertices in the vertex buffer.
int m_bufferSize; // The size in bytes of the vertex buffer.
unsigned int m_glVertexBuffer; // The ID for the OpenGL vertex buffer.
unsigned int m_glVertexArray; // The ID for the OpenGL vertex array object.
unsigned int m_vertexType;
};
//-----------------------------------------------------------------------------
// OpenGL Index Buffer
//-----------------------------------------------------------------------------
// An object for storing a buffer of indices that refers to the indices of
// elements inside another buffer (usually a vertex buffer).
class IndexBuffer
{
friend class Renderer;
public:
// Constructors/destructor.
IndexBuffer();
~IndexBuffer();
// Accessors.
unsigned int GetIndexCount() const;
// Mutators.
void SetIndices(unsigned int numIndices, const unsigned int* pIndices);
private:
public:
unsigned m_numIndices;
unsigned int m_glIndexBuffer; // The ID for the OpenGL index buffer.
};
//-----------------------------------------------------------------------------
// Vertex Data
//-----------------------------------------------------------------------------
class VertexData
{
public:
VertexData();
VertexData(unsigned int start, unsigned int count);
~VertexData();
void BufferVertices(int numVertices, const VertexPosTex* vertices)
{
m_vertexStart = 0;
m_vertexCount = numVertices;
m_vertexBuffer.SetVertices(numVertices, vertices);
}
void BufferVertices(int numVertices, const VertexPosTexNorm* vertices)
{
m_vertexStart = 0;
m_vertexCount = numVertices;
m_vertexBuffer.SetVertices(numVertices, vertices);
}
template <class T>
void BufferVertices(int numVertices, const T* vertices)
{
m_vertexStart = 0;
m_vertexCount = numVertices;
m_vertexBuffer.SetVertices(numVertices, vertices);
}
void SetVertexRange(unsigned int start, unsigned int count)
{
m_vertexStart = start;
m_vertexCount = count;
}
inline void SetVertexStart(unsigned int start) { m_vertexStart = start; }
inline void SetVertexCount(unsigned int count) { m_vertexCount = count; }
inline unsigned int GetStart() const { return m_vertexStart; }
inline unsigned int GetCount() const { return m_vertexCount; }
inline VertexBuffer* GetVertexBuffer() { return &m_vertexBuffer; }
public:
unsigned int m_vertexStart;
unsigned int m_vertexCount;
VertexBuffer m_vertexBuffer;
};
//-----------------------------------------------------------------------------
// Index Data
//-----------------------------------------------------------------------------
class IndexData
{
public:
IndexData();
IndexData(unsigned int start, unsigned int count);
~IndexData();
void BufferIndices(unsigned int numIndices, const unsigned int* indices)
{
m_indexStart = 0;
m_indexCount = numIndices;
m_indexBuffer.SetIndices(numIndices, indices);
}
void SetIndexRange(unsigned int start, unsigned int count)
{
m_indexStart = start;
m_indexCount = count;
}
inline void SetIndexStart(unsigned int start) { m_indexStart = start; }
inline void SetIndexCount(unsigned int count) { m_indexCount = count; }
inline unsigned int GetStart() const { return m_indexStart; }
inline unsigned int GetCount() const { return m_indexCount; }
inline IndexBuffer* GetIndexBuffer() { return &m_indexBuffer; }
public:
unsigned int m_indexStart;
unsigned int m_indexCount;
IndexBuffer m_indexBuffer;
};
template <class T>
void VertexBuffer::SetVertices(int numVertices, const T* vertices)
{
glBindBuffer(GL_ARRAY_BUFFER, m_glVertexBuffer);
// Buffer the vertex data.
int newBufferSize = numVertices * sizeof(T);
if (m_bufferSize < 0)
{
// Buffer new vertices.
glBufferData(GL_ARRAY_BUFFER, newBufferSize, vertices, GL_STATIC_DRAW);
m_bufferSize = newBufferSize;
}
else
{
// Buffer over existing vertices.
assert(newBufferSize <= m_bufferSize);//, "You cannot increase the buffer size"); // We mustn't increase the buffer size.
glBufferSubData(GL_ARRAY_BUFFER, 0, newBufferSize, vertices);
}
// Set the attribute locations.
glBindVertexArray(m_glVertexArray);
unsigned int offset = 0;
int sizeOfVertex = sizeof(T);
m_vertexType = T::kVertexType;
if (m_vertexType & VertexType::POSITION)
{
glEnableVertexAttribArray(VertexAttribLocations::POSITION);
glVertexAttribPointer(VertexAttribLocations::POSITION, 3, GL_FLOAT, GL_FALSE, sizeOfVertex, (void*) offset);
offset += sizeof(Vector3f);
}
if (m_vertexType & VertexType::TEX_COORD)
{
glEnableVertexAttribArray(VertexAttribLocations::TEX_COORD);
glVertexAttribPointer(VertexAttribLocations::TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeOfVertex, (void*) offset);
offset += sizeof(Vector2f);
}
if (m_vertexType & VertexType::NORMAL)
{
glEnableVertexAttribArray(VertexAttribLocations::NORMAL);
glVertexAttribPointer(VertexAttribLocations::NORMAL, 3, GL_FLOAT, GL_FALSE, sizeOfVertex, (void*) offset);
offset += sizeof(Vector3f);
}
if (m_vertexType & VertexType::COLOR)
{
glEnableVertexAttribArray(VertexAttribLocations::COLOR);
glVertexAttribPointer(VertexAttribLocations::COLOR, 4, GL_FLOAT, GL_FALSE, sizeOfVertex, (void*) offset);
offset += sizeof(Vector4f);
}
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
m_numVertices = numVertices;
}
#endif // _VERTEX_DATA_H_ | true |
10fbd883dbaabd77409bfd6a12ac4f47f0328405 | C++ | AVRGroup/Telepresence | /Projeto Telepresenca/ButtonControl/ButtonControl.ino | UTF-8 | 1,393 | 2.96875 | 3 | [] | no_license |
#include <Servo.h> //Biblioteca Servo
#include <time.h>
Servo motor1;
Servo motor2;//variavel servo
int angulo1,angulo2; //angulo inicial do motor
int anguloBase;//Posicionamento Inicial
double unidadeBaseGiro;//Segundos por Grau
double tempoDeGiro;
int lixo,i=0,val[6];
String dado;
char command;
void setup(){
Serial.begin(9600);//frequência da porta serial
motor1.attach(6);//Motor ligado no pino 6
motor2.attach(7);
angulo1=90; //angulo inicial do motor
angulo2=90;
motor1.write(angulo1);
motor2.write(angulo2);
anguloBase=0;//Posicionamento Inicial
unidadeBaseGiro=3.35;//Milisegundos por Grau
tempoDeGiro=0;
i=0;
}
/*int getInt(String texto)
{
int temp = texto.length() + 1;
char buffer[temp];
texto.toCharArray(buffer, temp);
int num = atoi(buffer);
return num;
}*/
void loop(){
if(Serial.available() > 0){ //verifica se existe comunicação com a porta seria)
command = Serial.read();
if (command == 'w')
{
if(angulo2<180)
angulo2 += 2;
motor2.write(angulo2);
}
if (command == 's')
{
if(angulo2>0)
angulo2 -= 2;
motor2.write(angulo2);
}
if (command == 'a')
{
if(angulo1<180)
angulo1+=2;
motor1.write(angulo1);
} if (command == 'd')
{
if(angulo1>0)
angulo1-=2;
motor1.write(angulo1);
}
}
}
| true |
697eeeb55d6e5f9c4d0b9e5ce7906b5e53653750 | C++ | topcodingwizard/code | /zerojudge/d550_2.cpp | UTF-8 | 692 | 2.65625 | 3 | [] | no_license | #include <math.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main() {
int M[3], P[3];
while (scanf("%d%d%d%d%d%d", &P[0], &P[1], &P[2], &M[0], &M[1], &M[2])) {
if (M[0] == 0 && M[1] == 0 && M[2] == 0 && P[0] == 0 && P[1] == 0 &&
P[2] == 0)
break;
int KP = max(0, P[1] - M[2]), KM = max(0, M[1] - P[2]);
if (KM == 0 || (KP != 0 && (int)ceil((double)M[0] / KP) <=
(int)ceil((double)P[0] / KM)))
printf("You win in %d round(s).\n", (int)ceil((double)M[0] / KP));
else
printf("You lose in %d round(s).\n", (int)ceil((double)P[0] / KM));
}
}
| true |
0bba9d0b54edae59c4bb1bb99131e55e5ed12a17 | C++ | KriSWhitch/Fundamentals-of-Algorithmization-and-Programming-Second-Semester | /lab16/px/dop4/HashTable.cpp | WINDOWS-1251 | 1,996 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include "HashTable.h"
using namespace std;
HashTable::HashTable(const int &size) : arr(size), size(size) {}
HashTable::~HashTable() {
arr.clear();
}
void HashTable::insert(const Element &elem) { //
int hash = -1;
hash = computeHash(elem.year, 0);
if (find(elem) == -1) arr[hash].push_back(elem);
}
void HashTable::erase(const Element &elem) { //
int hash = computeHash(elem.year, 0);
// arr[hash].begin() - (, STL) hash
// ,
if (hash != -1) arr[hash].erase(arr[hash].begin() + find(elem));
}
int HashTable::find(const Element &elem) const { //
int hash = computeHash(elem.year, 0);
for (int i = 0; i < arr[hash].size(); i++) {
if (arr[hash][i] == elem) return i;
}
return -1;
}
void HashTable::displayTable() const { //
for (int i = 0; i < size; i++) {
for (int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j].year << " | " << arr[i][j].productName << " | " << endl;
}
}
}
int HashTable::computeHash(const int &key, const int &index) const {
return multiplicativeHash(key, index);
}
int HashTable::universalHash(const int &key, const int &index) const {
int hash1 = 0, hash2 = 0;
int tmp = key;
for (int i = 1; tmp; i++) {
hash1 += (tmp % 10) * i;
tmp /= 10;
}
hash2 = (hash1 + 5 * index + 3 * index * index) % size;
return hash2;
}
int HashTable::modulusHash(const int &key, const int &index) const {
const int MOD = 100000007;
return (key + index) % MOD;
}
int HashTable::multiplicativeHash(const int &key, const int &index) const {
const double GOLD = (sqrt(5) - 1) / 2;
return (int)(size * fmod(key * GOLD, 1) + index) % size;
}
| true |
4c1d9380aa37ec4d240c1f3f907e871a5b17c836 | C++ | Qkvad/AffiliationRecommendation | /social_network/main.cpp | UTF-8 | 3,425 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fstream>
#include "config.h"
#include "User.h"
#include "Group.h"
#include "Crawler.h"
void createUsers(std::list<User>* Users)
{
for(int i=0; i<NUMBER_OF_USERS; i++)
Users->push_back(User(i+1, "User"));
std::cout << "Users list created."<< std::endl;
}
void createGroups(std::list<Group>* groups)
{
for(int i=0; i<NUMBER_OF_GROUPS; i++)
groups->push_back(Group(i+1, "group"));
std::cout << "Group list created."<< std::endl;
}
User* chooseRandomUser(std::list<User>* Users)
{
std::list<User>::iterator iter = Users->begin();
int k = std::rand() % NUMBER_OF_USERS;
std::advance(iter, k);
return &(*iter);
}
int main()
{
std::list<User> allUsers;
std::list<Group> allGroups;
std::list<User>::iterator u_it;
std::list<Group>::iterator g_it;
createUsers(&allUsers);
createGroups(&allGroups);
srand (time(NULL));
for(g_it = allGroups.begin(); g_it != allGroups.end(); g_it++)
g_it->addRandomMembers(&allUsers);
std::cout << std::endl << "Groups filled." << std::endl << std::endl;
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++)
u_it->addRandomFriends(&allUsers);
std::cout << "Users friended."<< std::endl << std::endl;
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++) {
u_it->printFriends();
u_it->printGroups();
std::cout << std::endl;
}
for(g_it = allGroups.begin(); g_it != allGroups.end(); g_it++) {
g_it->printMembers();
}
/******************************************************************************************************************/
int uSize = allUsers.size();
int nonZero = 0;
std::ofstream matrixS;
matrixS.open ("S.mtx");
matrixS << "%%MatrixMarket matrix coordinate real general\n";
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++)
for (std::list<User*>::iterator f_it = u_it->friends.begin(); f_it != u_it->friends.end(); f_it++)
nonZero++;
matrixS << uSize << " " << uSize << " "<< nonZero << std::endl;
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++)
for (std::list<User*>::iterator f_it = u_it->friends.begin(); f_it != u_it->friends.end(); f_it++)
matrixS << u_it->id << " " << (*f_it)->id << " 1\n";
matrixS.close();
std::cout << "users by users matrix S created."<< std::endl << std::endl;
int gSize = allGroups.size();
nonZero = 0;
std::ofstream matrixA;
matrixA.open ("A.mtx");
matrixA << "%%MatrixMarket matrix coordinate real general\n";
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++)
for (std::list<Group*>::iterator g_it = u_it->groups.begin(); g_it != u_it->groups.end(); g_it++)
nonZero++;
matrixA << uSize << " " << gSize << " "<< nonZero << std::endl;
for(u_it = allUsers.begin(); u_it != allUsers.end(); u_it++)
for (std::list<Group*>::iterator g_it = u_it->groups.begin(); g_it != u_it->groups.end(); g_it++)
matrixA << u_it->id << " " << (*g_it)->id << " 1\n";
matrixA.close();
std::cout << "users by groups matrix A created."<< std::endl;
/*
Crawler crawl;
crawl.startCrawlWith(chooseRandomUser(&allUsers));
crawl.crawlEntireStack();
crawl.printFinding();
*/
return 0;
}
| true |
7d8d6cbef137cc7a72391f99c4981c870ed048b2 | C++ | csu-anzai/CAU_CodingStudy | /HDY/2751_HDY_baekjoon.cpp | UTF-8 | 470 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <vector>
#include <functional>
using namespace std;
void printArr(int arr[], int arr_size) {
for (int i = 0; i < arr_size; i++)
cout << arr[i] << "\n";
}
int arr[1000001] = { 0, };
int main() {
priority_queue <int,vector<int>,greater<int>> q;
int N;
cin >> N;
for(int i=0;i<N;i++){
int tmp;
cin >> tmp;
q.push(tmp);
}
for (int i = 0; i < N; i++) {
cout << q.top();
q.pop();
}
} | true |
e867ee224d988826fd3f3f13a8d0b12f62fcb6a3 | C++ | 6Kwecky6/Ovinger1819 | /src/cppOvinger/oving3/oving_3/main.cpp | UTF-8 | 4,126 | 3.8125 | 4 | [] | no_license | #include <iostream>
//Oppg. 1
class Circle {
public:
Circle(double radius_); //Stor C, skal ha samme navn som klasse
double get_area() const; //double i stedet for int
double get_circumference() const;
private: //Private skal stå over variabelen, med kolonne
const double pi = 3.141592; //Flyttet inn i klassen
double radius;
}; //Semikolonne
Circle::Circle(double radius_) : radius(radius_) {} //inn parameteren skal assignes til klasse parameteren
double Circle::get_area() const { //Vi returnerer en constant, og velger double i stedet for int
return pi * radius * radius;
}
double Circle::get_circumference() const { //Git funksjonen en retur type
double circumference = 2.0 * pi * radius; //Deklarerer circumference
return circumference;
}
//Oppg.3
class Commodity {
public:
Commodity(const std::string &name_, int id_, double price_);
const std::string &get_name() const;
double get_price(double q) const;
double get_price() const;
int get_id() const;
void set_price(double price);
void set_id(int id);
double get_price_with_sales_tax(double q) const;
private:
std::string name;
int id;
double price;
double tax = 1.4;
};
Commodity::Commodity(const std::string &name_, int id_, double price_) : name(name_), id(id_), price(price_) {}
const std::string &Commodity::get_name() const {
return name;
}
double Commodity::get_price() const {
return price;
}
double Commodity::get_price(double q) const {
return price * q;
}
double Commodity::get_price_with_sales_tax(double q) const {
return q * price * tax;
}
int Commodity::get_id() const {
return id;
}
void Commodity::set_id(int id_) {
id = id_;
}
void Commodity::set_price(double price_) {
price = price_;
}
int main() {
//Oppg. 2
Circle circle(5);
double area = circle.get_area();
std::cout << "Arealet er lik " << area << std::endl;
double circumference = circle.get_circumference();
std::cout << "Omkretsen er lik " << circumference << std::endl;
//Oppg. 3
const double quantity = 2.5;
Commodity commodity("Norvegia", 123, 73.50);
std::cout << "Varenavn: " << commodity.get_name() << ", varenr: " << commodity.get_id() << " Pris pr enhet: " << commodity.get_price() << std::endl;
std::cout << "Kilopris: " << commodity.get_price() << std::endl;
std::cout << "Prisen for " << quantity << " kg er " << commodity.get_price(quantity) << " uten moms" << std::endl;
std::cout << "Prisen for " << quantity << " kg er " << commodity.get_price_with_sales_tax(quantity) << " med moms" << std::endl;
commodity.set_price(79.60);
std::cout << "Ny kilopris: " << commodity.get_price() << std::endl;
std::cout << "Prisen for " << quantity << " kg er " << commodity.get_price(quantity) << " uten moms" << std::endl;
std::cout << "Prisen for " << quantity << " kg er " << commodity.get_price_with_sales_tax(quantity) << " med moms" << std::endl;
//Oppg. 4 a)
std::string word1, word2, word3;
std::cin >> word1 >> word2 >> word3;
//b)
std::string sentence = word1 + " " + word2 + " " + word3 + ".";
//c)
std::cout << "Word1: " << word1.length() << std::endl
<< "Word2: " << word2.length() << std::endl
<< "Word3: " << word3.length() << std::endl
<< "Sentence: " << sentence.length() << std::endl;
//d)
std::string sentence2 = sentence;
//e)
for (int i = 9; i < 11; i++) {
sentence2[i] = 'X';
}
std::cout << "Sentence1: " << sentence << std::endl
<< "Sentence2: " << sentence2 << std::endl;
//f)
std::string sentence_start = " ";
for (int i = 0; i < 5; i++) {
sentence_start[i] = sentence[i];
}
std::cout << "Sentence complete: " << sentence << std::endl
<< "Sentence start: " << sentence_start << std::endl;
std::cout << "Sentence contains 'hallo': " << (sentence.find("hallo") != std::string::npos) << std::endl;
for (size_t i = 0; i < sentence.length(); i++) {
if ((sentence[i] == 'e') && (sentence[i + 1] == 'r')) {
std::cout << "Found 'er' at index " << i << std::endl;
}
}
} | true |
8affce6a5c088964437d638dca8d2e4e13f26e25 | C++ | asutton/banjo | /banjo/scope.hpp | UTF-8 | 2,832 | 3.015625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2015-2016 Andrew Sutton
// All rights reserved
#ifndef BANJO_SCOPE_HPP
#define BANJO_SCOPE_HPP
#include "hashing.hpp"
#include "overload.hpp"
namespace banjo
{
// -------------------------------------------------------------------------- //
// Scope definitions
// Maps names to overload sets.
using Name_map = std::unordered_map<Name const*, Overload_set, Name_hash, Name_eq>;
// A scope defines a maximal lexical region of text where an entity may be
// referred to without qualification. Scope objects are associated with the
// term defining their enclosing region of text.
//
// TODO: Do all scopes have an associated term? Probably.
struct Scope
{
using Binding = Name_map::value_type;
// Construct a new scope with the given parent. This is
// used to create scopes that are not affiliated with a
// declaration.
Scope(Scope& p)
: parent(&p), cxt(nullptr)
{ }
// Construct a scope having the given parent and affiliated with
// the declaration.
Scope(Scope& p, Term& t)
: parent(&p), cxt(&t)
{ }
virtual ~Scope() { }
// Returns the enclosing scope, if any. Only the global namespace does
// not have an enclosing scope.
Scope const* enclosing_scope() const { return parent; }
Scope* enclosing_scope() { return parent; }
// Returns the syntactic construct that defines the scope.
Term const& context() const { return *cxt; }
Term& context() { return *cxt; }
// Create a name binding for the given declaration. Behavior
// is undefined if a name binding already exists.
//
// TODO: Assert that `n` is a form of simple id.
Binding& bind(Decl& d);
Binding& bind(Name const&, Decl&);
// Return the binding for the given symbol, or nullptr
// if no such binding exists.
Overload_set const* lookup(Name const& n) const;
Overload_set* lookup(Name const& n);
// Returns 1 if the name is bound and 0 otherwise.
std::size_t count(Name const& n) const { return names.count(&n); }
Scope* parent;
Term* cxt;
Name_map names;
};
// Bind n to `d` in this scope.
//
// Note that the addition of declarations to an overload set
// must be handled by semantic rules.
inline Scope::Binding&
Scope::bind(Name const& n, Decl& d)
{
lingo_assert(count(n) == 0);
auto ins = names.insert({&n, {d}});
return *ins.first;
}
// Returns the binding for n, if any.
inline Overload_set const*
Scope::lookup(Name const& n) const
{
auto iter = names.find(&n);
if (iter != names.end())
return &iter->second;
else
return nullptr;
}
inline Overload_set*
Scope::lookup(Name const& n)
{
auto iter = names.find(&n);
if (iter != names.end())
return &iter->second;
else
return nullptr;
}
// Debugging
std::ostream& operator<<(std::ostream&, Scope const&);
} // namespace banjo
#endif
| true |
f12d1aada546c33ec7648ab453f4944a4ec36b43 | C++ | HiroakiIMAI/SimpleObjectDrawingLibrary | /SODL_sample_03_MultiViewPort/SODL_sample_03_MultiViewPort_main.cpp | SHIFT_JIS | 15,841 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive | #define _USE_MATH_DEFINES
#include <math.h>
#include <iostream>
#include "SimpleObjectDrawingLibrary.h"
#pragma comment( lib, "SimpleObjectDrawingLibrary.lib" )
// CũGCAXݒ肷
namespace sodl = SmplObjDrwLib;
// AvP[ṼO[oV{appl[Xy[XɎ߂
namespace app {
const int WINDOW_SIZE_X = 1280;
const int WINDOW_SIZE_Y = 960;
float ax_J1 = 0.0 * (M_PI / 180); // [rad]
float ax_J2 = 45.0 * (M_PI / 180); // [rad]
float ax_J3 = 90.0 * (M_PI / 180); // [rad]
float ax_J4 = 0.0 * (M_PI / 180); // [rad]
float ax_J5 = 45.0 * (M_PI / 180); // [rad]
float ax_J6 = 0.0 * (M_PI / 180); // [rad]
void keyFunc(unsigned char key, int u, int v);
// ̑̃Tu
std::string GetModulePath(); // st@C̃pX擾
};
//================================================================
//
// <Summary> AvP[ṼGg|Cg
// <Description>
//================================================================
int main(int argc, char ** argv)
{
//////////////////////////////////////////////////////
//
// AvP[V̏
//
//////////////////////////////////////////////////////
//-----------------------------------------------------
// Cu̕`}l[W
//-----------------------------------------------------
// ̎_ŃCuɂOpenGLReLXg쐬A
// OpenGL̃EBhE\
sodl::DrawingManager::initMngr( &argc, argv, app::WINDOW_SIZE_X, app::WINDOW_SIZE_Y);
// `}l[WɃR[obNݒ肷
sodl::drwMngr->SetKeyboardFunc(app::keyFunc);
//-----------------------------------------------------
// r[|[gƃJ̐ݒ
//-----------------------------------------------------
// r[|[gƃJ͕`}l[WdrwMngr̃\bhĒljłB
// ̎_ŕ`}l[Wshared_ptrƂĕێ̂
// main\[Xshared_ptr͕svɂȂ_Ŕjč\ȂB
{
//-----------------------------------------------------
// r[|[g1
//-----------------------------------------------------
{
// ftHg̃r[|[g͕`}l[W̏ɃCX^XA
// viewPorts[0]std::shared_ptrŕێĂB
// ꎞϐɎăTCY֘AtꂽJݒ𑀍삷
// r[|[g1ւshared_ptr擾
auto vp1 = sodl::drwMngr->viewPorts[0];
// r[|[g1̃TCYݒ肷
// EBhE4̈Ƀr[|[g
// (OpenGL摜Wnɏ]̂ŁAEBhE_AY+AEX+)
vp1->setVpSize(
0, // left
app::WINDOW_SIZE_Y / 2, // bottom
app::WINDOW_SIZE_X / 2, // width
app::WINDOW_SIZE_Y / 2 // height
);
// r[|[g1Ɋ֘AtꂽJւshared_ptr擾
auto cam1 = vp1->getCam();
// J̈ʒuݒ肷
cam1->camPos = Eigen::Vector3f(600.f, -2000.f, 300.f);
// J̎BeΏۈʒuݒ肷
cam1->camTgt = Eigen::Vector3f(0.f, 0.f, 0.f);
// J̃Y[䗦ݒ肷
cam1->zoomRatio = 0.8;
// Jݒf邽߂ɁAJēxr[|[g1Ɋ֘At
vp1->attachCam(cam1);
}
//-----------------------------------------------------
// r[|[g2
//-----------------------------------------------------
{
// r[|[gljB
// ljꂽr[|[gCX^X
// drwMngr->viewPorts[]ɂshared_ptrĕێ
auto vp2 = sodl::drwMngr->addViewPort("vp2");
// EBhE4ËɃr[|[g
vp2->setVpSize(
app::WINDOW_SIZE_X / 2, // left
app::WINDOW_SIZE_Y / 2, // bottom
app::WINDOW_SIZE_X / 2, // width
app::WINDOW_SIZE_Y / 2 // height
);
// r[|[g2Ɋ֘AtꂽJւshared_ptr擾
auto cam2 = vp2->getCam();
// ʐ}Be
cam2->camPos = Eigen::Vector3f(0.f, -0.f, 5000.f);
cam2->camTgt = Eigen::Vector3f(0.f, 0.f, 0.f);
cam2->camUpVec = Eigen::Vector3f(0.f, 1.f, 0.f);
// J̃Y[䗦ݒ肷
cam2->zoomRatio = 0.3;
// Jݒf邽߂ɁAJēxr[|[g1Ɋ֘At
vp2->attachCam(cam2);
}
//-----------------------------------------------------
// r[|[g3
//-----------------------------------------------------
{
// r[|[gljB
auto vp3 = sodl::drwMngr->addViewPort("vp3");
// EBhE4̈Ƀr[|[g
vp3->setVpSize(
0, // left
0, // bottom
app::WINDOW_SIZE_X / 2, // width
app::WINDOW_SIZE_Y / 2 // height
);
// r[|[g3Ɋ֘AtꂽJւshared_ptr擾
auto cam3 = vp3->getCam();
// ʐ}Be
cam3->camPos = Eigen::Vector3f(-1000.f, 0.f, 0.f);
cam3->camTgt = Eigen::Vector3f(0.f, 0.f, 0.f);
cam3->camUpVec = Eigen::Vector3f(0.f, 0.f, 1.f);
// J̃Y[䗦ݒ肷
cam3->zoomRatio = 0.3;
// Jݒf邽߂ɁAJēxr[|[g1Ɋ֘At
vp3->attachCam(cam3);
}
//-----------------------------------------------------
// r[|[g4
//-----------------------------------------------------
{
// r[|[gljB
auto vp4 = sodl::drwMngr->addViewPort("vp4");
// EBhE4ËɃr[|[g
vp4->setVpSize(
app::WINDOW_SIZE_X / 2, // left
0, // bottom
app::WINDOW_SIZE_X / 2, // width
app::WINDOW_SIZE_Y / 2 // height
);
// r[|[g4Ɋ֘AtꂽJւshared_ptr擾
auto cam4 = vp4->getCam();
// ʐ}Be
cam4->camPos = Eigen::Vector3f(0.f, -1000.f, 0.f);
cam4->camTgt = Eigen::Vector3f(0.f, 0.f, 0.f);
cam4->camUpVec = Eigen::Vector3f(0.f, 0.f, 1.f);
// J̃Y[䗦ݒ肷
cam4->zoomRatio = 0.3;
// Jݒf邽߂ɁAJēxr[|[g1Ɋ֘At
vp4->attachCam(cam4);
}
}
//-----------------------------------------------------
// [hWn_AJ1~6WnIuWFNg`
// J1~6Wn6{bgA[̊e߂̈ʒup\
//-----------------------------------------------------
// [hW_`
auto World_Origin = sodl::CoordChainObj::create("World_Origin");
World_Origin->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 0.f);
// J1(Joint1)WnIuWFNg쐬A[hWnɃA^b`
auto J1_Crd = sodl::CoordChainObj::create("J1_Crd", World_Origin);
// J1Wn̐eWnɑItZbgʂݒ肷
J1_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 30.f);
// J2WnIuWFNg쐬Ae(J1)WnɃA^b`
auto J2_Crd = sodl::CoordChainObj::create("J2_Crd", J1_Crd);
// J2Wn̐eWnɑItZbgʂݒ肷
J2_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 230.f);
// J3WnIuWFNg쐬AeWnɃA^b`
auto J3_Crd = sodl::CoordChainObj::create("J3_Crd", J2_Crd);
// J3Wn̐eWnɑItZbgʂݒ肷
J3_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 320.f);
// J4WnIuWFNg쐬AeWnɃA^b`
auto J4_Crd = sodl::CoordChainObj::create("J4_Crd", J3_Crd);
// J4Wn̐eWnɑItZbgʂݒ肷
J4_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 200.f);
// J5WnIuWFNg쐬AeWnɃA^b`
auto J5_Crd = sodl::CoordChainObj::create("J5_Crd", J4_Crd);
// J5Wn̐eWnɑItZbgʂݒ肷
J5_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 120.f);
// J6WnIuWFNg쐬
auto J6_Crd = sodl::CoordChainObj::create("J6_Crd", J5_Crd);
// J6Wn̐eWnɑItZbgʂݒ肷
J6_Crd->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 50.f);
{
//-----------------------------------------------------
// 3Df`p̃IuWFNg쐬
// 6{bgA[̊e߂\eWn
// {bgA[̊eN3DfA^b`B
//-----------------------------------------------------
std::string exePath = app::GetModulePath();
// {bg̃f[h`IuWFNgA[hWn_ɃA^b`
auto RobotBase = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\BasePlate.stl", "RobotBase", World_Origin);
// S1(sholder1)̃f[h`IuWFNgAJ1WnɃA^b`
auto RobotSholder1 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\S1.stl", "S1", J1_Crd);
// S2̃f[h`IuWFNgAJ2WnɃA^b`
auto RobotSholder2 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\S2.stl", "S2", J2_Crd);
// S2f̕\ʒu邽߂ɁAe(J2)WnɑWnItZbgݒ肷
RobotSholder2->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, -90.f);
// E1(elbow1)̃f[h`IuWFNgAJ3WnɃA^b`
auto RobotElbow1 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\E1.stl", "E1", J3_Crd);
// f̕\ʒu邽߂ɁAeWnɑWnItZbgݒ肷
RobotElbow1->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, -70.f);
// W1(Wrist1)̃f[h`IuWFNgAJ4WnɃA^b`
auto RobotWrist1 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\W1.stl", "W1", J4_Crd);
// f̕\ʒu邽߂ɁAeWnɑWnItZbgݒ肷
RobotWrist1->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 0.f);
// W2(Wrist2)̃f[h`IuWFNgAJ5WnɃA^b`
auto RobotWrist2 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\W2.stl", "W2", J5_Crd);
// f̕\ʒu邽߂ɁAeWnɑWnItZbgݒ肷
RobotWrist2->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, -50.f);
// W3(Wrist3)̃f[h`IuWFNgAJ6WnɃA^b`
auto RobotWrist3 = sodl::CoordChain3dMdl::create(exePath + "\\3dModel\\SimpleRobot6Ax\\W3.stl", "W3", J6_Crd);
// f̕\ʒu邽߂ɁAeWnɑWnItZbgݒ肷
RobotWrist3->CrdTrs.translation() = Eigen::Vector3f(0.f, 0.f, 0.f);
//-----------------------------------------------------
// `IuWFNg`ΏۂƂĕ`}l[Wɓo^
//-----------------------------------------------------
// `WnA`}l[W̎`ԂɃZbg
sodl::drwMngr->AddObjTree_ToDrwSpace(World_Origin);
// ŕ`ԂɒljIuWFNǵAshared_ptrƂdrwMngrɋL邽߁A
// ANZXKvȂAmain\[Xshared_ptr͂ŔjĂ܂Ă\ȂB
}
//////////////////////////////////////////////////////
//
// C[v
//
//////////////////////////////////////////////////////
while(1)
{
//-----------------------------------------------------
// L[͂ōXVϐlɂāA`IuWFNg̍WϊsXV
//-----------------------------------------------------
J1_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J1, UnitZ).matrix();
J2_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J2, UnitX).matrix();
J3_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J3, UnitX).matrix();
J4_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J4, UnitZ).matrix();
J5_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J5, UnitX).matrix();
J6_Crd->CrdTrs.linear() = Eigen::AngleAxisf(app::ax_J6, UnitZ).matrix();
//-----------------------------------------------------
// `}l[W`XVs
//-----------------------------------------------------
sodl::drwMngr->drawUpdt();
Sleep(10);
}
return 0;
}
namespace app {
//================================================================
//
// <Summary> L[쎞̃R[obN
// <Description>
//================================================================
void keyFunc(unsigned char key, int u, int v)
{
const float KEY_MOT_UNIT = 5.f;
const float CNV_DEG2RAD = (M_PI / 180.f);
switch (key) {
case '\033': // '\033' ESC ASCII R[h
exit(0);
break;
case '1':
ax_J1 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case '2':
ax_J2 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case '3':
ax_J3 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case '4':
ax_J4 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case '5':
ax_J5 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case '6':
ax_J6 += KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 'q':
ax_J1 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 'w':
ax_J2 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 'e':
ax_J3 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 'r':
ax_J4 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 't':
ax_J5 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
case 'y':
ax_J6 -= KEY_MOT_UNIT * CNV_DEG2RAD;
break;
default:
break;
}
}
//================================================================
//
// <Summary> st@C̃pX擾
// <Description>
//================================================================
std::string GetModulePath()
{
// st@C̃pX
std::string modulePath = "";
// hCuAfBNgAt@CAgq
char path[MAX_PATH], drive[MAX_PATH], dir[MAX_PATH], fname[MAX_PATH], ext[MAX_PATH];
// st@C̃t@CpX擾
if (GetModuleFileNameA(NULL, path, MAX_PATH) != 0)
{
// t@CpX
_splitpath_s(path, drive, dir, fname, ext);
// hCuƃfBNgĎst@CpXƂ
modulePath = std::string(drive) + std::string(dir);
}
return modulePath;
}
};
| true |
20256f8085b1d051bb536b0ee10f08e254719d13 | C++ | cppnuts-yt/pthread | /threadCpp/excercise/Thread.cpp | UTF-8 | 253 | 2.78125 | 3 | [] | no_license | #include "Thread.h"
using namespace std;
void * Thread::dispatch(void * arg){
static_cast<Thread*> (arg)->run();
}
void Thread::start(){
pthread_create(&thread_handle,NULL,dispatch,this);
}
void Thread::join(){
pthread_join(thread_handle,NULL);
} | true |
b02fb7004e69b8ede5cf90e22442cd6fdabba484 | C++ | turbide/BlurParser | /Parser/ParserTable.h | UTF-8 | 1,227 | 3.09375 | 3 | [
"MIT"
] | permissive | /**
* @author Blurred-9L
* @file ParserTable.h
*/
#ifndef PARSER_TABLE_H
#define PARSER_TABLE_H
class ParserTableKey;
class ParserTableAction;
/**
* @class ParserTable
*
* @brief Base class used to abstract the required operations
* for the implementation of an LR Table.
*/
class ParserTable {
protected:
/// Fills the LR Table.
virtual void fillTable() = 0;
public:
/**
* @enum ActionType
*
* @brief Defines values for all 4 action types : shift,
* reduce, change and accept.
*/
enum ActionType {
SHIFT,
REDUCE,
CHANGE,
ACCEPT
};
/// ParserTable constructor.
ParserTable();
/// Checks if the table has the given key.
virtual bool hasKey(const ParserTableKey & key) const = 0;
/// Gets the action related to the given key.
virtual ParserTableAction * getAction(const ParserTableKey & key) const = 0;
/// Gets the length of a rule on the grammar used.
virtual int getRuleLength(int ruleNumber) = 0;
/// Gets the non-terminal type on the left side of the production on a rule.
virtual int getNonTerminalType(int ruleNumber) = 0;
};
#endif /// NOT PARSER_TABLE_H
| true |
8a9584c3dc0d27d9ac186d75786058179975015f | C++ | jamornsriwasansak/wurstrenderer | /src/common/math/spectrum.h | UTF-8 | 1,430 | 2.734375 | 3 | [] | no_license | #pragma once
#include "vecmath.h"
#if __AVX2__
using RgbSpectrum = Math::VecSimd4<3, 1001>;
#else
using RgbSpectrum = Math::VecPrim<double, 3, 1001>;
#endif
struct SpectrumConvertUtil
{
static inline double FromSrgb(const double v)
{
if (v <= 0.04045) return v * (1.0 / 12.92);
return std::pow((v + 0.055) * (1.0 / 1.055), 2.4);
}
static RgbSpectrum SpectrumFromSrgb(const double r, const double g, const double b)
{
return RgbSpectrum(FromSrgb(r), FromSrgb(g), FromSrgb(b));
}
static RgbSpectrum SpectrumFromRgb(const double r, const double g, const double b)
{
return RgbSpectrum(r, g, b);
}
static RgbSpectrum SpectrumFromRg(const Vec2 & v)
{
return RgbSpectrum(v[0], v[1], 0.0);
}
static RgbSpectrum SpectrumFromRgb(const Vec3 & v)
{
return RgbSpectrum(v[0], v[1], v[2]);
}
static Vec3 Vec3FromSpectrum(const RgbSpectrum & spectrum)
{
return Vec3(spectrum[0], spectrum[1], spectrum[2]);
}
static std::vector<RgbSpectrum> SpectrumsFromRgbs(const std::vector<Vec3> & rgbs)
{
std::vector<RgbSpectrum> results(rgbs.size());
for (Uint i = 0;i < rgbs.size();i++) { results[i] = SpectrumFromRgb(rgbs[i]); }
return results;
}
static std::vector<Vec3> Vec3sFromSpectrums(const std::vector<RgbSpectrum> & spectrums)
{
std::vector<Vec3> results(spectrums.size());
for (Uint i = 0;i < spectrums.size();i++) { results[i] = Vec3FromSpectrum(spectrums[i]); }
return results;
}
};
| true |
b29e4463e8b62f102e8400115f9f7b18021d6af9 | C++ | Choi-Young-Hoon/cpp-design-pattern | /Composite.cpp | UHC | 1,519 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <list>
/*
* ü ü о ϳ ̽ ٷ ְ Ѵ.
* ü(Leaf) (Comosite) Ʈ Ͽ ϳ ̽ ϵ ̴.
*/
// Component ̽
class Component {
public:
virtual void Operation() = 0;
virtual void Add(Component* pComponent) {}
virtual void Remove(Component* pComponent) {}
virtual Component* GetChild(int i) { return 0; }
};
// Leaf Ŭ
class Leaf : public Component {
public:
virtual void Operation() override {
std::cout << "Leaf Operation" << std::endl;
}
};
// Composite Ŭ (ü )
class Composite : public Component {
public:
virtual void Operation() override {
for (auto& iter : m_List) {
iter->Operation();
}
}
virtual void Add(Component* pComponent) override {
m_List.push_back(pComponent);
}
virtual void Remove(Component* pComponent) override {
m_List.remove(pComponent);
}
virtual Component* GetChild(int nIndex) override {
int nListIndex = 0;
for (auto& iter : m_List) {
if (nListIndex == nIndex) {
return iter;
}
nListIndex++;
}
return NULL;
}
private:
std::list<Component*> m_List;
};
int main(void) {
Leaf leafA,
leafB;
Composite composite;
composite.Add(&leafA);
composite.Add(&leafB);
composite.Operation();
return 0;
} | true |
4a125067b8e8437a4abb0a5a095c7a08af8a1dc0 | C++ | fourglod/iOSDevelopment | /iOS_Developer/DevelopGuide_iOS/DevelopGuide_iOS/dwvlt_v3.0_0522/M3Core_iOS4/source/MPFDrawer/System/Linux/XdwFileIOLinux.h | UTF-8 | 4,681 | 2.5625 | 3 | [] | no_license | /**
* @file XdwFileIOLinux.h
* @brief XdwFileIOLinuxクラスの定義
*
* @author DPC DS&S STD T31G Tomohiro Yamada <Tomohiro.Yamada@fujiexreox.co.jp>
* @date 2002-3-29
* @version 1.0
* $Id: XdwFileIOLinux.h,v 1.5 2009/12/22 08:11:29 chikyu Exp $
*
* Copyright (C) 2002 Fuji Xerox Co., Ltd.
*/
#ifndef _XDW_FILE_IO_LINUX_H_
#define _XDW_FILE_IO_LINUX_H_
/* インターフェースのIncludeファイル */
#include "System/SystemIF/XdwFileIO.h"
/**
* @brief 標準ファイルIOをラップするクラス
*
* XdwFileIOインターフェースの実装クラス<br>
* 各メソッドは標準ファイルIO関数のままである<br>
* Windows CEでは、基本的にはサポートされていない<br>
* そのためWindows CE上では、これらのメソッドはエラーを返す
*/
class XdwFileIOLinux : public XdwFileIO
{
public:
/********************************************/
/* メソッド */
/**
* @brief デフォルトコンストラクタ
*/
XdwFileIOLinux();
/**
* @brief デストラクタ
*/
virtual ~XdwFileIOLinux();
/**
* @brief ファイルを開く
*
* fopenと動作は同一
*
* @param file_name プラットフォーム依存の文字列でファイル名
* @param mode オープンモード
*
* @return ファイルハンドル。定義は見せない。<br>
* @return エラー時はNULLコード
*/
virtual void* Open(void* file_name, char* mode);
/**
* @brief ファイルを閉じる
*
* fcloseと動作は同一
*
* @param file ファイルハンドル
*
* @return なし
*/
virtual void Close(void* file);
/**
* @brief ファイルから指定されたバッファに読み込む
*
* freadと動作は同一
*
* @param buffer バッファ
* @param size 一度に読み込むサイズ
* @param n 読み込む回数
* @param file ファイルハンドル
*
* @return ファイルからバッファに読み込んだ回数
*/
virtual long Read(void* buffer, long size, long n, void* file);
/**
* @brief 指定されたバッファからファイルに書き込む
*
* fwirteと動作は同一<br>
*
* @param buffer バッファ
* @param size 一度に書き込むサイズ
* @param n 書き込む回数
* @param file ファイルハンドル
*
* @return ファイルからバッファに書き込んだ回数
*/
virtual long Write(void* buffer, long size, long n, void* file);
/**
* @brief ファイルの現在位置を、指定されたモードでオフセット分移動する
*
* fseekと動作は同一<br>
*
* @param file ファイルハンドル
* @param offset オフセット
* @param mode XdwFileIO::SeekModeを参照
*
* @return 成功の場合は0、失敗の場合は0以外
*/
virtual int Seek(void* file, long offset, XdwFileIO::SeekMode mode);
/**
* @brief ファイルの現在位置を、ファイル先頭からのbyte数で知らせる
*
* ftellと動作は同一<br>
*
* @param file ファイルハンドル
*
* @return ファイル先頭位置からの現在位置のbyte数
*/
virtual long Tell(void* file);
/**
* @brief 一時記憶用のファイル名を取得する際に必要なByte数を取得する
*
* @return 一時記憶用のファイル名を取得する際に必要なByte数
*/
virtual long GetTmpNamSize();
/**
* @brief 一時記憶用のファイルを作成するための、ファイル名を取得する
*
* tmpnamと動作は同一<br>
*
* @param name TmpNamメソッドが作成した名前を書き込むバッファ<br>
* 必ず指定しなければならない
*
* @return 引数nameのポインタ<br>
* @return エラー時はNULLコード。
*/
virtual void* TmpNam(void* name);
/**
* @brief 指定されたファイル名のファイルを削除する
*
* removeと動作は同一
*
* @param filename 削除するファイル名
*
* @retval 0 成功
* @retval 0以外 失敗
*/
virtual int Remove(void* filename);
/**
* @brief 一時記憶用のファイルを作成する
* 省メモリ対策 新規追加 09/07/02 M.Chikyu
*
* tmpfileと動作は同一<br>
*
* @return 一時ファイルのFILEポインタ<br>
* @return エラー時はNULLコード。
*/
virtual void* TmpFile(void);
};
#endif
| true |
6d2cf5857f29b1f99ddbe6731ed2bd73a3b3ba7a | C++ | physbuzz/quantumbounce | /quantum.cpp | UTF-8 | 4,066 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
#include "ImageUtil.h"
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
//The space 0<x<L, 0<y<L is discretized into D*D cells.
const int D=512;
const double L=200;
const double dx=L/D;
const double dt=dx*dx*0.4; //Stability condition is dt/dx^2<0.5 ?
//Store the real and imaginary parts of the wavefunction
vector<double> rev(D*D,0);
vector<double> imv(D*D,0);
//numerical code is in lines 112-155, the rest is just utility / plotting code.
//Some string manipulation functions for saving files. pad_int(1234,5) returns "01234".
std::string pad_int(int arg, int padcount) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(padcount) << arg;
return ss.str();
}
//Returns a file name in the form of "prefix00###suffix". For example "image0032.bmp"
std::string getFilename(std::string prefix, int num, int padcount, std::string suffix) {
return prefix + pad_int(num, padcount) + suffix;
}
//From https://gist.github.com/fairlight1337/4935ae72bcbcc1ba5c72
void HSVtoRGB(float& fR, float& fG, float& fB, float& fH, float& fS, float& fV) {
float fC = fV * fS; // Chroma
float fHPrime = fmod(fH / 60.0, 6);
float fX = fC * (1 - fabs(fmod(fHPrime, 2) - 1));
float fM = fV - fC;
if(0 <= fHPrime && fHPrime < 1) {
fR = fC;
fG = fX;
fB = 0;
} else if(1 <= fHPrime && fHPrime < 2) {
fR = fX;
fG = fC;
fB = 0;
} else if(2 <= fHPrime && fHPrime < 3) {
fR = 0;
fG = fC;
fB = fX;
} else if(3 <= fHPrime && fHPrime < 4) {
fR = 0;
fG = fX;
fB = fC;
} else if(4 <= fHPrime && fHPrime < 5) {
fR = fX;
fG = 0;
fB = fC;
} else if(5 <= fHPrime && fHPrime < 6) {
fR = fC;
fG = 0;
fB = fX;
} else {
fR = 0;
fG = 0;
fB = 0;
}
fR += fM;
fG += fM;
fB += fM;
}
/* Plotting Code */
void saveImage(int n){
int imgs=D;
DoubleImage ampx(imgs,imgs);
DoubleImage ampy(imgs,imgs);
DoubleImage ct(imgs,imgs);
for(int i=0;i<D;i++){
for(int j=0;j<D;j++){
ampx.increase((i*imgs)/D,(j*imgs)/D,rev[D*i+j]);
ampy.increase((i*imgs)/D,(j*imgs)/D,imv[D*i+j]);
ct.increase((i*imgs)/D,(j*imgs)/D,1);
}
}
Image img(imgs,imgs);
for(int i=0;i<imgs;i++){
for(int j=0;j<imgs;j++){
if(ct.get(i,j)==0)
continue; //possible only if imgs>D
float x=float(ampx.get(i,j)/ct.get(i,j));
float y=float(ampy.get(i,j)/ct.get(i,j));
float amp=900*float(x*x+y*y);
if(amp>1)
amp=1;
float phase=float(180.0/M_PI*(atan2(y,x)+M_PI));
float saturation=0.9;
float r,g,b;
HSVtoRGB(r,g,b,phase,saturation,amp);
img.put(i,j,floatToRGB(r,g,b));
}
}
img.save(getFilename("out/img",n,3,".bmp"));
}
void zeroWavefunction(){
rev= vector<double>(D*D,0);
imv=vector<double>(D*D,0);
}
double re(int i, int j){
if(i>=0 && i<D && j>=0 && j<D)
return rev[D*i+j];
return 0;
}
double im(int i, int j){
if(i>=0 && i<D && j>=0 && j<D)
return imv[D*i+j];
return 0;
}
double V(double x,double y){
return (y)*0.007;
}
void step(){
for(int i=0;i<D;i++){
for(int j=0;j<D;j++){
rev[D*i+j]=rev[D*i+j]-0.5*dt*(im(i+1,j)+im(i-1,j)+im(i,j+1)+im(i,j-1)-4*imv[D*i+j])/(dx*dx)+dt*V(dx*i,dx*j)*im(i,j);
}
}
for(int i=0;i<D;i++){
for(int j=0;j<D;j++){
imv[D*i+j]=imv[D*i+j]+0.5*dt*(re(i+1,j)+re(i-1,j)+re(i,j+1)+re(i,j-1)-4*rev[D*i+j])/(dx*dx)-dt*V(dx*i,dx*j)*re(i,j);
}
}
}
void addGaussian(double x0, double y0, double vx0, double vy0, double sigma){
for(int i=0;i<D;i++){
for(int j=0;j<D;j++){
double x=i*dx,y=j*dx;
double amplitude=exp(-((x-x0)*(x-x0)+(y-y0)*(y-y0))/(2*sigma*sigma))/sqrt(M_PI*sigma*sigma);
double phase=vx0*x+vy0*y;
rev[D*i+j]+=amplitude*cos(phase);
imv[D*i+j]+=amplitude*sin(phase);
}
}
}
int main() {
addGaussian(100,150,0.2,0.2,10);
for(int n=0;n<300;n++){
saveImage(n);
for(int k=0;k<100;k++){
step();
}
}
return 0;
}
| true |
d0c25cf5bd227e2171cd98499039c730384e441e | C++ | Hyukli/leetcode | /762.cpp | UTF-8 | 780 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int countPrimeSetBits(int L, int R) {
vector<int> p={2,3,5,7,11,13,17,19,23,29,31};
int ans=0;
for(int i=L;i<=R;i++)
{
if(isp(p,i))
{
ans++;
}
}
return ans;
}
private:
bool isp(vector<int> p,int k)
{
int t=0;
while(k!=0)
{
t+=(k%2);
k/=2;
}
for(int i=0;i<p.size();i++)
{
if(t==p[i])
{
return true;
}
}
return false;
}
};
int main()
{
Solution s;
int l,r;
cin>>l>>r;
cout<<s.countPrimeSetBits(l,r)<<endl;
return 0;
}
| true |
bd98747364870564f2d78cd2a8705abf34070250 | C++ | AustinStephens/CPPSemester2 | /Lab 11-C/Phone.cpp | UTF-8 | 952 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include "Phone.h"
using std::cout;
using std::endl;
using std::setw;
using std::setfill;
using std::ostream;
Phone::Phone()
{
setPhone(0,0,0,false);
}
Phone::Phone(int a, int e, int n, bool u)
{
setPhone(a,e,n,u);
}
void Phone::setPhone(int area, int ex, int num, bool unlist)
{
unlisted = unlist;
if (area < 0 || area > 999) area = 0;
areaCode = area;
if (ex < 0 || ex > 999) ex = 0;
exchange = ex;
if (num < 0 || num > 9999) num = 0;
number = num;
}
void Phone::pntPhone() const
{
cout << "(" << setfill('0') << setw(3) << areaCode << ")" << setw(3) << exchange << "-" << setw(4) << number << " is " << (unlisted ? "unlisted" : "listed") << endl;
}
void Phone::dial() const
{
cout << areaCode << exchange << number << endl;
}
void Phone::unlist()
{
unlisted = true;
}
void Phone::list()
{
unlisted = false;
}
ostream &operator <<(ostream &stream, const Phone &obj)
{
obj.pntPhone();
}
| true |
a3a2a8bca5d557c2a6de1144749109c892abb8e3 | C++ | mp5557/multithread_utility | /main/test_ring_buffer.cpp | UTF-8 | 773 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <ring_buffer.h>
int main() {
RingBuffer<int> ring_buffer(3);
ring_buffer.Push(1);
fmt::print("after push 1: {}\n", fmt::join(ring_buffer, ","));
ring_buffer.Push(2);
fmt::print("after push 2: {}\n", fmt::join(ring_buffer, ","));
ring_buffer.Push(3);
fmt::print("after push 3: {}\n", fmt::join(ring_buffer, ","));
ring_buffer.Push(4);
fmt::print("after push 4: {}\n", fmt::join(ring_buffer, ","));
auto iter = std::find_if(ring_buffer.begin(), ring_buffer.end(),
[](int x) { return x > 2; });
fmt::print("find iter {}\n", *iter);
ring_buffer.Remove(iter);
fmt::print("after remove: {}\n", fmt::join(ring_buffer, ","));
}
| true |
daa288baee1d7f7b9771eb204f63a1578e405d62 | C++ | xunzhang/lcode | /leetcode/remove-nth-node-from-end-of-list.cc | UTF-8 | 595 | 3.265625 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *it1 = head, *it2 = head;
int i = 0;
for(; i < n && it2->next; ++i) it2 = it2->next;
if(i < n) {
head = head->next;
delete it1;
return head;
}
while(it2->next) { it1 = it1->next; it2 = it2->next; }
ListNode *save = it1->next;
it1->next = it1->next->next;
delete save;
return head;
}
};
| true |