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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f9e51f28f4c406af70c960fbd0771f91ad05560 | C++ | cms-sw/cmssw | /CondFormats/ESObjects/interface/ESADCToGeVConstant.h | UTF-8 | 822 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef CondFormats_ESObjects_ESADCToGeVConstant_H
#define CondFormats_ESObjects_ESADCToGeVConstant_H
#include "CondFormats/Serialization/interface/Serializable.h"
#include <iostream>
class ESADCToGeVConstant {
public:
ESADCToGeVConstant();
ESADCToGeVConstant(const float& ESvaluelow, const float& ESvaluehigh);
~ESADCToGeVConstant();
void setESValueLow(const float& value) { ESvaluelow_ = value; }
float getESValueLow() const { return ESvaluelow_; }
void setESValueHigh(const float& value) { ESvaluehigh_ = value; }
float getESValueHigh() const { return ESvaluehigh_; }
void print(std::ostream& s) const {
s << "ESADCToGeVConstant: ES low/high " << ESvaluelow_ << " / " << ESvaluehigh_ << " [GeV/ADC count]";
}
private:
float ESvaluelow_;
float ESvaluehigh_;
COND_SERIALIZABLE;
};
#endif
| true |
12fea55429f975ef087b18ea5eb5b6c8ad8c1480 | C++ | Leputa/TsingPA | /PA1/Company.cpp | GB18030 | 1,759 | 2.9375 | 3 | [] | no_license | #include <stdio.h>
const int Max=10000005;
const int MAXBUFFER = 1 << 20;
struct fastio {
char inbuf[MAXBUFFER];
char outbuf[MAXBUFFER];
fastio() {
setvbuf(stdin, inbuf, _IOFBF, MAXBUFFER);
setvbuf(stdout, outbuf, _IOFBF, MAXBUFFER);
}
}io;
class Employee{
public :
int code;
int num;
Employee(){
code=-1;
num=0;
}
};
class Company{
private:
int num=0;
int tag[Max]={0};
public:
Employee employee[Max];
bool isLogIn(int id){
if(employee[id].code==-1)
return false;
else return true;
}
void LogIn(int id,int code){
if(!isLogIn(id)){
num++;
tag[num]=id;
employee[id].num=num;
}
else{
//tag[num]=id; // ҵ֮ǰnumڵ....
tag[employee[id].num]=id;
}
employee[id].code=code;
}
void LogOut(int id){
if(isLogIn(id)){
employee[id].code=-1;
num--;
}
}
void close(){
for(int i=1;i<=num;i++){
int id=tag[i];
employee[id].code=-1;
//employee[id].id=0;
}
num=0;
}
int getNum(){
return num;
}
int Query(int id){
return employee[id].code;
}
};
Company company;
int main(){
int n;
int m;
int cnt=0;
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
char tmp;
while (scanf("%c", &tmp) && tmp!= 'I' && tmp!= 'O'&& tmp!= 'C'&& tmp!= 'N'&& tmp!= 'Q');//տոس
if(tmp=='I'){
int id;
int code;
scanf("%d %d",&id,&code);
company.LogIn(id,code);
}
if(tmp=='O'){
int id;
scanf("%d",&id);
company.LogOut(id);
}
if(tmp=='C')
company.close();
if(tmp=='N'){
cnt+=company.getNum();
}
if(tmp=='Q'){
int id;
scanf("%d",&id);
cnt+=company.Query(id);
}
}
printf("%d",cnt);
return 0;
}
| true |
2012d2a3cdb5336804f8c44d76656c1092efaa9d | C++ | halex2005/pjsettings | /tests/pjsettings-jsoncpp.tests.cpp | UTF-8 | 14,148 | 2.859375 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | #include <boost/filesystem/operations.hpp>
#include <catch/catch.hpp>
#include <iostream>
#include <pjsettings-jsoncpp.h>
#include <pjsua2/endpoint.hpp>
#include "SimpleClass.h"
using namespace Json;
using namespace pj;
using namespace pjsettings;
SCENARIO("read json from string", "[jsoncpp]")
{
const char *jsonString = "{\n"
" \"intValue\": 14,\n"
" \"stringValue\": \"string\",\n"
" \"doubleValue\": 2.5,\n"
" \"trueBool\": true,\n"
" \"falseBool\": false,\n"
" \"simpleClass\": {\n"
" \"intValue\": 15,\n"
" \"stringValue\": \"string\"\n"
" },\n"
" \"stringsArray\": [ \"string\", \"other string\" ],\n"
" \"boolArray\": [ true, false ],\n"
" \"simpleClassArray\": [\n"
" { \"intValue\": 16 },\n"
" { \"intValue\": 17 }\n"
" ],\n"
" \"simpleContainer\": {\n"
" \"simpleClass\": { \"intValue\": 18 }\n"
" },\n"
" \"intArray\": [ 19, 20 ],\n"
" \"arrayOfStringVectors\": [\n"
" [ \"first\", \"second\" ],\n"
" [ \"third\", \"fourth\" ]\n"
" ]\n"
"}";
JsonCppDocument doc;
try
{
doc.loadString(jsonString);
}
catch (Error &err)
{
std::cerr << err.info(true) << std::endl;
throw;
}
SECTION("read simple data types")
{
ContainerNode &node = doc.getRootContainer();
SECTION("read integer")
{
int intValue;
NODE_READ_INT(node, intValue);
CHECK(14 == intValue);
}
SECTION("read double")
{
double doubleValue;
NODE_READ_FLOAT(node, doubleValue);
CHECK(2.5 == doubleValue);
}
SECTION("read string")
{
std::string stringValue;
NODE_READ_STRING(node, stringValue);
CHECK("string" == stringValue);
}
WHEN("read bool")
{
THEN("true bool")
{
bool trueBool = false;
NODE_READ_BOOL(node, trueBool);
CHECK(true == trueBool);
}
THEN("false bool")
{
bool falseBool = true;
NODE_READ_BOOL(node, falseBool);
CHECK(false == falseBool);
}
}
SECTION("read string vector")
{
StringVector stringsArray;
NODE_READ_STRINGV(node, stringsArray);
REQUIRE(2 == stringsArray.size());
CHECK("string" == stringsArray[0]);
CHECK("other string" == stringsArray[1]);
}
}
SECTION("read from array")
{
SECTION("read array of objects")
{
ContainerNode arrayNode = doc.readArray("simpleClassArray");
std::vector<SimpleClass> data;
while (arrayNode.hasUnread())
{
SimpleClass obj("simpleClass");
arrayNode.readObject(obj);
data.push_back(obj);
}
REQUIRE(2 == data.size());
CHECK(data[0].intValue == 16);
CHECK(data[1].intValue == 17);
}
SECTION("read int array")
{
ContainerNode arrayNode = doc.readArray("intArray");
std::vector<int> data;
while (arrayNode.hasUnread())
{
data.push_back(arrayNode.readInt());
}
REQUIRE(2 == data.size());
CHECK(data[0] == 19);
CHECK(data[1] == 20);
}
SECTION("read string array")
{
ContainerNode arrayNode = doc.readArray("stringsArray");
std::vector<std::string> data;
while (arrayNode.hasUnread())
{
data.push_back(arrayNode.readString());
}
REQUIRE(2 == data.size());
CHECK("string" == data[0]);
CHECK("other string" == data[1]);
}
SECTION("read bool array")
{
ContainerNode arrayNode = doc.readArray("boolArray");
std::vector<bool> data;
while (arrayNode.hasUnread())
{
data.push_back(arrayNode.readBool());
}
REQUIRE(2 == data.size());
CHECK(true == data[0]);
CHECK(false == data[1]);
}
SECTION("read StringVector array")
{
ContainerNode arrayNode = doc.readArray("arrayOfStringVectors");
std::vector<StringVector> data;
while (arrayNode.hasUnread())
{
data.push_back(arrayNode.readStringVector());
}
REQUIRE(2 == data.size());
CHECK(data[0].size() == 2);
CHECK(data[0][0] == "first");
CHECK(data[0][1] == "second");
CHECK(data[1].size() == 2);
CHECK(data[1][0] == "third");
CHECK(data[1][1] == "fourth");
}
SECTION("read array in array")
{
ContainerNode arrayNode = doc.readArray("arrayOfStringVectors");
std::vector<std::string> data;
while (arrayNode.hasUnread())
{
ContainerNode subNode = arrayNode.readArray("vector");
while (subNode.hasUnread())
{
data.push_back(subNode.readString("add"));
}
}
REQUIRE(4 == data.size());
CHECK(data[0] == "first");
CHECK(data[1] == "second");
CHECK(data[2] == "third");
CHECK(data[3] == "fourth");
}
}
SECTION("read object")
{
SimpleClass simpleClass("simpleClass");
doc.readObject(simpleClass);
CHECK(simpleClass.intValue == 15);
CHECK(simpleClass.stringValue == "string");
}
SECTION("read container")
{
ContainerNode node = doc.readContainer("simpleContainer");
SimpleClass simpleClass("simpleClass");
node.readObject(simpleClass);
CHECK(simpleClass.intValue == 18);
}
}
SCENARIO("jsoncpp read pjsip LogConfig", "[jsoncpp]")
{
SECTION("read ordered config values")
{
const char *jsonString = "{\n"
" \"LogConfig\": {\n"
" \"msgLogging\": 1,\n"
" \"level\": 5,\n"
" \"consoleLevel\": 4,\n"
" \"decor\": 25328,\n"
" \"filename\": \"pjsip.log\",\n"
" \"fileFlags\": 0\n"
" }\n"
"}";
JsonCppDocument doc;
doc.loadString(jsonString);
LogConfig config;
doc.readObject(config);
CHECK(1 == config.msgLogging);
CHECK(5 == config.level);
CHECK(4 == config.consoleLevel);
CHECK("pjsip.log" == config.filename);
}
SECTION("read unordered config values")
{
const char *xmlString = "{\n"
" \"LogConfig\": {\n"
" \"filename\": \"pjsip.log\",\n"
" \"level\": 5,\n"
" \"consoleLevel\": 4\n"
" }\n"
"}";
JsonCppDocument doc;
doc.loadString(xmlString);
LogConfig config;
doc.readObject(config);
CHECK(5 == config.level);
CHECK(4 == config.consoleLevel);
CHECK("pjsip.log" == config.filename);
}
}
SCENARIO("jsoncpp from file", "[jsoncpp]")
{
const char *filename = "test-config-jsoncpp.json";
JsonCppDocument doc;
doc.loadFile(filename);
LogConfig config;
doc.readObject(config);
CHECK(5 == config.level);
CHECK(4 == config.consoleLevel);
CHECK("pjsip.log" == config.filename);
}
bool contains_string(JsonCppDocument &doc, const std::string &search)
{
std::string result = doc.saveString();
bool expression = result.find(search) != std::string::npos;
if (!expression)
{
std::cout << "substring " << search << " not found in serialized document:" << std::endl << result << std::endl;
}
return expression;
}
SCENARIO("jsoncpp to string", "[jsoncpp]")
{
JsonCppDocument doc(true);
SECTION("write simple data types")
{
ContainerNode &node = doc.getRootContainer();
SECTION("empty document")
{
CHECK(contains_string(doc, "{}"));
}
SECTION("write integer")
{
int intValue = 14;
NODE_WRITE_INT(node, intValue);
CHECK(contains_string(doc, "{\"intValue\":14}"));
}
SECTION("write double")
{
double doubleValue = 2.5;
NODE_WRITE_FLOAT(node, doubleValue);
CHECK(contains_string(doc, "{\"doubleValue\":2.5}"));
}
SECTION("write string")
{
std::string stringValue = "string";
NODE_WRITE_STRING(node, stringValue);
CHECK(contains_string(doc, "{\"stringValue\":\"string\"}"));
}
WHEN("write bool")
{
THEN("true bool")
{
bool trueBool = true;
NODE_WRITE_BOOL(node, trueBool);
CHECK(contains_string(doc, "{\"trueBool\":true}"));
}
THEN("false bool")
{
bool falseBool = false;
NODE_WRITE_BOOL(node, falseBool);
CHECK(contains_string(doc, "{\"falseBool\":false}"));
}
}
SECTION("write string vector")
{
StringVector stringsArray;
stringsArray.push_back("string");
stringsArray.push_back("other string");
NODE_WRITE_STRINGV(node, stringsArray);
CHECK(contains_string(doc, "{\"stringsArray\":[\"string\",\"other string\"]}"));
}
SECTION("write container")
{
ContainerNode node = doc.writeNewContainer("simpleContainer");
WHEN("empty container")
{
CHECK(contains_string(doc, "{\"simpleContainer\":{}}"));
}
WHEN("one attribute")
{
node.writeInt("intValue", 21);
CHECK(contains_string(doc, "{\"simpleContainer\":{\"intValue\":21}}"));
}
WHEN("container inside")
{
node.writeNewContainer("subContainer");
CHECK(contains_string(doc, "{\"simpleContainer\":{\"subContainer\":{}}}"));
}
WHEN("array inside")
{
node.writeNewArray("subArray");
CHECK(contains_string(doc, "{\"simpleContainer\":{\"subArray\":[]}}"));
}
}
SECTION("write object")
{
SimpleClass simpleClass("simpleClass", 15, "string");
doc.writeObject(simpleClass);
CHECK(contains_string(doc, "{\"simpleClass\":{\"intValue\":15,\"stringValue\":\"string\"}}"));
}
}
SECTION("write to array")
{
ContainerNode arrayNode = doc.writeNewArray("arrayNode");
SECTION("empty array")
{
CHECK(contains_string(doc, "{\"arrayNode\":[]}"));
}
SECTION("write int to array")
{
arrayNode.writeInt("int", 19);
CHECK(contains_string(doc, "{\"arrayNode\":[19]}"));
}
SECTION("write double to array")
{
arrayNode.writeNumber("float", 2.5);
CHECK(contains_string(doc, "{\"arrayNode\":[2.5]}"));
}
SECTION("write string to array")
{
arrayNode.writeString("string", "some string");
CHECK(contains_string(doc, "{\"arrayNode\":[\"some string\"]}"));
}
SECTION("write bool to array")
{
WHEN("true bool")
{
arrayNode.writeBool("boolean", true);
CHECK(contains_string(doc, "{\"arrayNode\":[true]}"));
}
WHEN("false bool")
{
arrayNode.writeBool("boolean", false);
CHECK(contains_string(doc, "{\"arrayNode\":[false]}"));
}
}
SECTION("write StringVector to array")
{
StringVector s1;
s1.push_back("first");
s1.push_back("second");
arrayNode.writeStringVector("stringVector", s1);
CHECK(contains_string(doc, "{\"arrayNode\":[[\"first\",\"second\"]]}"));
}
SECTION("write container to array")
{
arrayNode.writeNewContainer("simple");
CHECK(contains_string(doc, "{\"arrayNode\":[{}]}"));
}
SECTION("write object to array")
{
SimpleClass simpleClass("simple", 16, "string");
arrayNode.writeObject(simpleClass);
CHECK(contains_string(doc, "{\"arrayNode\":[{\"intValue\":16,\"stringValue\":\"string\"}]}"));
}
SECTION("write array in array")
{
ContainerNode subArray = arrayNode.writeNewArray("subArray");
subArray.writeInt("int", 20);
CHECK(contains_string(doc, "{\"arrayNode\":[[20]]}"));
}
}
}
SCENARIO("jsoncpp write pjsip LogConfig", "[jsoncpp]")
{
LogConfig config;
config.filename = "pjsip.log";
config.consoleLevel = 1;
config.level = 2;
JsonCppDocument doc;
doc.writeObject(config);
SECTION("write to string")
{
size_t npos = std::string::npos;
CHECK(contains_string(doc, "\"LogConfig\" :"));
CHECK(contains_string(doc, "\"filename\" : \"pjsip.log\""));
CHECK(contains_string(doc, "\"consoleLevel\" : 1"));
CHECK(contains_string(doc, "\"level\" : 2"));
}
SECTION("write to file")
{
using namespace boost::filesystem;
char const *filename = "test-save-LogConfig-to-file.json";
remove(filename);
CHECK(!exists(filename));
doc.saveFile(filename);
REQUIRE(exists(filename));
}
}
| true |
3c8cd695d2c1c5e1abecf7b0fad1260fff54d4c9 | C++ | mviseu/Coursera_algorithms_I | /Week5/interval_tree/IntervalTree.h | UTF-8 | 1,091 | 3.265625 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
struct Interval {
Interval(int low, int high) : lo(low), hi(high) {}
int lo;
int hi;
};
bool operator==(const Interval& lhs, const Interval& rhs);
bool operator!=(const Interval& lhs, const Interval& rhs);
std::ostream& operator<<(std::ostream& os, const Interval& interv);
bool StartsBefore(const Interval& lhs, const Interval& rhs);
int GetMaxEndPoint(const Interval& lhs, const Interval& rhs);
struct Node {
Node(const Interval& interv, int maxPoint, std::unique_ptr<Node> lf, std::unique_ptr<Node> ri) : interval(interv), maxEndPoint(maxPoint), left(std::move(lf)), right(std::move(ri)) {}
Interval interval;
int maxEndPoint;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
};
class IntervalTree {
public:
bool Find(const Interval& interv) const;
void Delete(const Interval& interv);
void Insert(const Interval& interv);
std::vector<Interval> AllOverlappingIntervals(const Interval& interv) const;
private:
std::unique_ptr<Node> m_root = nullptr;
};
| true |
2391710dea1e679ad76644b2b32fd3f4a49610fe | C++ | rishup132/Codeforces-Solutions | /educational/round1/B.cpp | UTF-8 | 602 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
int m;
cin >> m;
while(m--)
{
int x,y,k;
cin >> x >> y >> k;
x--;
y--;
k %= (y-x+1);
string t = "";
for(int i=0;i<x;i++)
t += s[i];
int temp = y-x+1-k;
for(int i=y-k+1;k>0;k--,i++)
t += s[i];
for(int i=x;temp>0;temp--,i++)
t += s[i];
for(int i=y+1;i<s.size();i++)
t += s[i];
s = t;
//cout << s << endl;
}
cout << s << endl;
} | true |
67bd6561a73d2ad03edc8f280b07951f4d07b030 | C++ | JosiasWerly/Gumball | /GumballCore/WidgetOverlay.hpp | UTF-8 | 2,407 | 2.640625 | 3 | [] | no_license | #ifndef _widgetoverlay
#define _widgetoverlay
#include "RenderSystem.hpp"
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
class WidgetOverlay;
class Widget;
class WidgetOverlay :
public IRenderOverlay {
friend class Widget;
ImGuiIO *guiIO = nullptr;
std::list<Widget *> elements;
public:
WidgetOverlay();
void onAttach() override;
void onDetach() override;
void onRender(const double &deltaTime) override;
WidgetOverlay &operator<<(Widget *element);
WidgetOverlay &operator>>(Widget *element);
};
//TODO: add a default name to IWidget::Name, since every entity needs a name
//TODO: implement an event based, we're handling by pooling everything...
class Widget {
friend class WidgetOverlay;
friend class WidgetContainer;
bool isVisible = true;
WidgetContainer *parent = nullptr;
public:
virtual void render(const double &deltaTime);
void setVisibility(bool newVisible);
Inline bool getVisibility() const { return isVisible; }
Inline WidgetContainer *getParent() const { return parent; }
};
class WidgetContainer : public Widget {
list<Widget *> children;
public:
WidgetContainer() = default;
virtual void render(const double &deltaTime) override;
virtual void beginDraw();
virtual void endDraw();
WidgetContainer &operator<<(Widget *child);
WidgetContainer &operator>>(Widget *child);
void addChildren(list<Widget *> children);
void delChildren(list<Widget *> children);
Inline bool hasChild(Widget *child) const { return std::find(children.begin(), children.end(), child) != std::end(children); };
};
class UserWidget : public WidgetContainer {
public:
UserWidget() = default;
//possible methods to implement on child of this class
//virtual void render(const double &deltaTime) {}
//virtual void beginDraw() {}
//virtual void endDraw() {}
};
namespace UI {
class Text : public Widget {
public:
string text = "Text";
Text() = default;
void render(const double &deltaTime);
};
class InputText : public Widget {
char inBuffer[256] = {};
string str;
public:
void render(const double &deltaTime);
bool getInput(string &out) const;
};
class Button : public Widget {
bool clicked = false;
public:
string text = "Button";
Button() = default;
void render(const double &deltaTime);
Inline bool isClicked() { return clicked; }
};
};
#endif // !_widgetoverlay | true |
d18b9a00db6d24203ea37c9dec090caa361365b1 | C++ | MrBattary/darkest-castle | /src/game/systems/collisionSubsystems/EnemyCollision.cpp | UTF-8 | 3,414 | 2.53125 | 3 | [
"MIT"
] | permissive | //
// Created by Battary on 03.08.2020.
//
#include "game/systems/collisionSubsystems/EnemyCollision.h"
void EnemyCollision::updateData(ecs::World& world, std::shared_ptr<ecs::Entity> first,
std::shared_ptr<ecs::Entity> second) {
auto playerPosComp = first->getComponent<LocationComponent>();
auto playerPrevPosComp = first->getComponent<PreviousLocationComponent>();
auto playerDirComp = first->getComponent<DirectionComponent>();
auto playerInvComp = first->getComponent<InventoryComponent>();
auto playerStatComp = first->getComponent<StatsComponent>();
auto interfaceSys = world.getSystem<InterfaceUpdateSystem>();
auto enemyPosComp = second->getComponent<LocationComponent>();
auto enemyPrevPosComp = second->getComponent<PreviousLocationComponent>();
auto enemyInvComp = second->getComponent<InventoryComponent>();
auto enemyStatComp = second->getComponent<StatsComponent>();
auto playerDamage = playerStatComp->getStat("+Attack")->value_ - enemyStatComp->getStat("+Defence")->value_;
if (playerDamage < 1) playerDamage = 1;
auto enemyDamage = enemyStatComp->getStat("+Attack")->value_ - playerStatComp->getStat("+Defence")->value_;
if (enemyDamage < 1) enemyDamage = 1;
int playerDamageTaken{0}, enemyDamageTaken{0};
if (!interfaceSys->containElement("End level")) {
playerStatComp->getStat("Damage")->value_ += enemyDamage;
enemyStatComp->getStat("Damage")->value_ += playerDamage;
playerDamageTaken = playerStatComp->getStat("Damage")->value_;
enemyDamageTaken = enemyStatComp->getStat("Damage")->value_;
auto logBox = interfaceSys->getElement<PlayerRealtimeLogBox>();
logBox->addData("Damage [color=green]Dealt: " + std::to_string(playerDamage) + "[/color]");
logBox->addData("[color=red] Received: " + std::to_string(enemyDamage) + "[/color] ");
}
if (playerDamageTaken >= playerStatComp->getStat("+Health")->value_) {
world.purgeEntity(second->getID());
if (!interfaceSys->containElement("End game")) interfaceSys->createElement<EndGameBox>(world);
if (!interfaceSys->containElement("Leaderboard")) interfaceSys->createElement<LeaderboardBox>();
} else {
if (enemyDamageTaken > enemyStatComp->getStat("+Health")->value_) {
world.purgeEntity(second->getID());
} else {
if (playerDirComp->direction_ == DirectionComponent::NOWHERE) {
enemyPosComp->column_ = enemyPrevPosComp->columnPrevious_;
enemyPosComp->row_ = enemyPrevPosComp->rowPrevious_;
} else {
if (playerDirComp->direction_ == DirectionComponent::UPWARD ||
playerDirComp->direction_ == DirectionComponent::DOWNWARD) {
playerPosComp->row_ = playerPrevPosComp->rowPrevious_;
}
if (playerDirComp->direction_ == DirectionComponent::LEFTWARD ||
playerDirComp->direction_ == DirectionComponent::RIGHTWARD) {
playerPosComp->column_ = playerPrevPosComp->columnPrevious_;
}
}
}
}
}
void EnemyCollision::updateSubsystem(ecs::World& world, std::shared_ptr<ecs::Entity> first,
std::shared_ptr<ecs::Entity> second) {
std::string firstName = first->getEntityName();
std::string secondName = second->getEntityName();
if (secondName == "Enemy") {
updateData(world, first, second);
} else {
updateData(world, second, first);
}
world.updateWorldList();
}
| true |
d8fdf1429d991c11d62bcecaaab637cb8e4dde60 | C++ | yananliu000/Projects | /GlarekEngineProject/Engine/Engine/Source/Application/Graphic/SFMLGraphic.cpp | UTF-8 | 5,579 | 2.609375 | 3 | [] | no_license | #ifdef _SFML
#include <SFML/Graphics.hpp>
#include "SFMLGraphic.h"
#include "../Window/IWindow.h"
#include "../Texture/SFMLSprite.h"
#include "../Texture/SFMLTexture.h"
#include "../../Utility/MyLogger.h"
//Warning: sfml-graphic-s-d works for debug x64
// -d not
using Engine::SFMLGraphic;
sf::RenderWindow* SFMLGraphic::m_spRenderer = nullptr;
bool Engine::SFMLGraphic::Init(IWindow * pWindow)
{
//get sfml window from iwindow
m_spRenderer = reinterpret_cast<sf::RenderWindow*>(pWindow->GetNativeWindow());
if (!m_spRenderer || !m_spRenderer->isOpen())
{
g_Logger.write(MyLogger::LogLevel::System_Error, "Fail loading SFML_pRenderer.");
}
return true;
}
void Engine::SFMLGraphic::StartDrawing(Color baseColor)
{
m_spRenderer->clear(sf::Color(baseColor.red, baseColor.green, baseColor.blue, baseColor.alpha));
}
void Engine::SFMLGraphic::EndDrawing()
{
m_spRenderer->display();
}
bool Engine::SFMLGraphic::Draw(ISprite * pSprite, Rect & srcRect, Rect & desRect)
{
//get sfmlsprite
sf::Sprite* pToDraw = reinterpret_cast<sf::Sprite*>(pSprite->GetNativeSprite());
//set the rects
pToDraw->setTextureRect(sf::IntRect(i32(srcRect.x), i32(srcRect.y), i32(srcRect.w), i32(srcRect.h)));
pToDraw->setPosition(sf::V2f(float(desRect.x),float(desRect.y)));
pToDraw->setScale(sf::V2f((desRect.w / float(srcRect.w)), float(desRect.h / float(srcRect.h))));
//pToDraw->setScale(sf::V2f(1,1));
//sfml render
m_spRenderer->draw(*pToDraw);
return true;
}
std::shared_ptr<Engine::ISprite> Engine::SFMLGraphic::GetSprite(const char * filepath)
{
//check sprite map
auto spriteMapItr = m_pSpriteMap.find(filepath);
if (spriteMapItr == m_pSpriteMap.end()) //not in sprite map
{
//check texture map
auto textureMapItr = m_pTextureMap.find(filepath);
if (textureMapItr == m_pTextureMap.end()) //neither in texture map
{
std::unique_ptr<SFMLTexture> pTexture = std::make_unique<SFMLTexture>();
if (pTexture->Init(filepath))
{
//load the new texture
textureMapItr = m_pTextureMap.emplace(filepath, std::move(pTexture)).first;
}
else
{
//fail loading texture
g_Logger.write(MyLogger::LogLevel::Game_Error, "Fail loading SFML_Texture.");
return nullptr;
}
}
//create the sprite use the texture
//if find texture succeeded: textureMapItr is the right texture
//if failed: is the new created texture
std::shared_ptr<SFMLSprite> pSprite = std::make_shared<SFMLSprite>();
if (!pSprite->Init(textureMapItr->second.get()))
{
g_Logger.write(MyLogger::LogLevel::Game_Error, "Fail loading SFML_Sprite.");
}
spriteMapItr = m_pSpriteMap.emplace(filepath, std::move(pSprite)).first;
}
//if have it in the sprite map: return the right sprite
//if not: return the new created sprite
return spriteMapItr->second;
}
void Engine::SFMLGraphic::DrawCircle(const V2f center, f32 radius, const Color color)
{
sf::CircleShape shape(radius);
shape.setOrigin({center.x, center.y});
shape.setOutlineColor(sf::Color(color.red, color.green, color.blue, color.alpha));
m_spRenderer->draw(shape);
}
void Engine::SFMLGraphic::DrawPolygon(const V2f* points, i32 pointCount, const Color color)
{
sf::ConvexShape convex;
convex.setPointCount(pointCount);
for (int i = 0; i < pointCount; ++i)
{
convex.setPoint(i, {points[i].x* kPixelsPerMeter,points[i].y* kPixelsPerMeter });
}
convex.setOutlineColor(sf::Color(color.red, color.green, color.blue, color.alpha));
convex.setOutlineThickness(1);
convex.setFillColor(sf::Color(color.red, color.green, color.blue, 50));
m_spRenderer->draw(convex);
}
void Engine::SFMLGraphic::DrawSegment(const V2f p1, const V2f p2, const Color color)
{
sf::Vertex line[] =
{
sf::Vertex({p1.x, p1.y}),
sf::Vertex({p2.x, p2.y})
};
line->color = sf::Color(color.red, color.green, color.blue, color.alpha);
m_spRenderer->draw(line, 2, sf::Lines);
}
void Engine::SFMLGraphic::DrawSegments(const V2f * points, i32 pointCount, const Color color)
{
g_Logger.write(MyLogger::LogLevel::System_Error, "SFML does not support DrawSegments");
}
void Engine::SFMLGraphic::DrawRect(const V2f wh, const V2f position, const Color color)
{
sf::RectangleShape rectangle({ wh.x, wh.y });
rectangle.setPosition({ position.x, position.y });
rectangle.setOutlineColor(sf::Color(color.red, color.green, color.blue, color.alpha));
m_spRenderer->draw(rectangle);
}
void Engine::SFMLGraphic::DrawFilledRect(const V2f wh, const V2f position, const Color color)
{
sf::RectangleShape rectangle({ wh.x, wh.y });
rectangle.setPosition({ position.x, position.y });
rectangle.setOutlineColor(sf::Color(color.red, color.green, color.blue, color.alpha));
rectangle.setFillColor(sf::Color(color.red, color.green, color.blue, color.alpha));
m_spRenderer->draw(rectangle);
}
void Engine::SFMLGraphic::DrawPoint(const V2f position, const Color color)
{
g_Logger.write(MyLogger::LogLevel::System_Error, "SFML does not support DrawPoint");
}
void Engine::SFMLGraphic::DrawPoints(const std::vector<V2f> position, i32 pointCount, const Color color)
{
g_Logger.write(MyLogger::LogLevel::System_Error, "SFML does not support DrawPoints");
}
V2f Engine::SFMLGraphic::GetMousePosition()
{
auto p = sf::Mouse::getPosition(*m_spRenderer);
return V2f(p.x, p.y);
}
Color Engine::SFMLGraphic::GetRenderDrawColor()
{
g_Logger.write(MyLogger::LogLevel::System_Error, "SFML does not support GetRenderDrawColor");
return Color();
}
void Engine::SFMLGraphic::SetRenderDrawColor(Color* color)
{
g_Logger.write(MyLogger::LogLevel::System_Error, "SFML does not support SetRenderDrawColor");
}
#endif | true |
486d415ea82c8353ae65246c86a205a62f3c2e4a | C++ | DaeunSim/coding-practice | /HackerRank/30 Days of Code (C++)/Day 05 Loop/Solution.cpp | UTF-8 | 450 | 2.71875 | 3 | [] | no_license | /*
Author: https://www.hackerrank.com/profile/AvmnuSng
Difficulty: Easy
Submitted By: https://www.hackerrank.com/challenges/30-loops/leaderboard
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (n < 2 || n > 20)
return 0;
for (int i = 1; i <= 10; i ++) {
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}
| true |
ffeb8eceeaa8f85312204f01415e6c1432330206 | C++ | bradelement/coding_exercise | /leetcode-master/055/main.cpp | UTF-8 | 281 | 2.625 | 3 | [] | no_license | class Solution {
public:
bool canJump(vector<int>& nums) {
int max_pos = 0;
for (int i=0; i<nums.size(); i++) {
if (i > max_pos) return false;
max_pos = max(max_pos, nums[i]+i);
}
return true;
}
}; | true |
03c1130afab35065e556aebf2231fb9da6817edf | C++ | colemancda/rhubarb-lip-sync | /src/animation/Viseme.cpp | UTF-8 | 1,712 | 2.703125 | 3 | [
"LicenseRef-scancode-other-permissive",
"WTFPL",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | #include "Viseme.h"
VisemeOption::VisemeOption(Shape shape) :
VisemeOption(shape, shape, shape, shape, shape)
{}
VisemeOption::VisemeOption(Shape nearB, Shape nearC, Shape nearD, Shape nearE, Shape nearF) :
VisemeOption(nearB, nearB, nearC, nearD, nearE, nearF, nearB, nearC, nearB)
{}
VisemeOption::VisemeOption(Shape nearA, Shape nearB, Shape nearC, Shape nearD, Shape nearE, Shape nearF, Shape nearG, Shape nearH, Shape nearX) :
shapes{ nearA, nearB, nearC, nearD, nearE, nearF, nearG, nearH, nearX }
{
static_assert(static_cast<int>(Shape::EndSentinel) == 9, "Shape definition has changed.");
}
Shape VisemeOption::getShape(Shape context) const {
return shapes.at(static_cast<int>(context));
}
bool VisemeOption::operator==(const VisemeOption& rhs) const {
return shapes == rhs.shapes;
}
bool VisemeOption::operator!=(const VisemeOption& rhs) const {
return !operator==(rhs);
}
Viseme::Viseme(const VisemeOption& option) :
options{ { 0_cs, option } }
{}
Viseme::Viseme(const VisemeOption& option1, centiseconds threshold, const VisemeOption& option2) :
options{ { 0_cs, option1 }, { threshold, option2 } }
{}
Viseme::Viseme(const VisemeOption& option1, centiseconds threshold1, const VisemeOption& option2, centiseconds threshold2, const VisemeOption& option3) :
options{ { 0_cs, option1 },{ threshold1, option2 }, { threshold2, option3 } }
{}
Shape Viseme::getShape(centiseconds duration, Shape context) const {
VisemeOption option = std::prev(options.upper_bound(duration))->second;
return option.getShape(context);
}
bool Viseme::operator==(const Viseme& rhs) const {
return options == rhs.options;
}
bool Viseme::operator!=(const Viseme& rhs) const {
return !operator==(rhs);
}
| true |
de4147498acf1ed336f21bc5e88f4a30d82a85f5 | C++ | jylongzhao/MyReXueShaCheng | /Classes/BgMapFloorTile.cpp | UTF-8 | 1,169 | 2.5625 | 3 | [] | no_license | #include "BgMapFloorTile.h"
BgMapFloorTile::BgMapFloorTile():m_fileName(NULL),m_sprite(NULL),m_nIsDisplay(false){
}
BgMapFloorTile::~BgMapFloorTile(){
CC_SAFE_DELETE(m_fileName);
}
void BgMapFloorTile::displayImageView(){
if(m_nIsDisplay==false){
m_nIsDisplay=true;
CCTextureCache::sharedTextureCache()->addImageAsync(m_fileName->getCString(), this, callfuncO_selector(BgMapFloorTile::initWithImageView));
}
}
void BgMapFloorTile::hideImageView()
{
if (m_nIsDisplay)
{
m_nIsDisplay = false;
if (m_sprite)
{
m_sprite->removeFromParent();
m_sprite = NULL;
}
CCTextureCache::sharedTextureCache()->removeTextureForKey(m_fileName->getCString());
}
}
void BgMapFloorTile::initWithImageView(CCTexture2D* texture)
{
if (m_sprite == NULL)
{
m_sprite = CCSprite::createWithTexture(texture);
m_sprite->setAnchorPoint(CCPointZero);
this->addChild(m_sprite);
}
}
void BgMapFloorTile::IntelligentDisplay(CCRect& showRect, CCRect& hideRect)
{
CCPoint point = ccpAdd(this->getPosition(), OFF_SIZE);
if (showRect.containsPoint(point))
{
this->displayImageView();
}
if (!hideRect.containsPoint(point))
{
this->hideImageView();
}
} | true |
517ca75903af50e788ac753d7cf21b3294ce0aff | C++ | pastacolsugo/coderfarm-2021-avanzato | /lezioni/lezione1/ois_streetlights/ois_streetlights_70.cpp | UTF-8 | 835 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");
int main() {
int n, m, k;
fin >> n >> m >> k;
// leggo i valori delle lampade
vector<int> v(n);
for(int &i : v) {
fin >> i;
}
// contiene la risposta (answer)
int ans = 0;
// per ogni "finestra" lunga M, conto le luci accese, poi accendo partendo da destra
for(int i = 0; i + m - 1 < n; i++) {
int accese = 0;
for(int j = i; j < i + m; j++)
accese += v[j];
// finché non ne ho accese abbastanza, cerco lanterne spente da accendere
for(int j = i + m - 1; j >= i && accese < k; j--) {
if(v[j] == 0) {
v[j] = 1;
accese++;
ans++;
}
}
}
fout << ans;
} | true |
d599c44d1c7bcac28ee85f5f103e9abc44f4d21d | C++ | Marinovsky/AlgorithmsUN2021I | /Data Structures/week3_hash_tables/3_hash_substring/hash_substring.cpp | UTF-8 | 2,271 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
typedef unsigned long long ull;
struct Data {
string pattern, text;
};
Data read_input() {
Data data;
std::cin >> data.pattern >> data.text;
return data;
}
long long mulmod(long long a, long long b, long long mod){
long long res=0;
a=a%mod;
while(b>0){
if(b%2==1){
res=(res+a)%mod;
}
a=(a*2)%mod;
b=b/2;
}
return res%mod;
}
int hash_func(const string& s){
static const size_t multiplier = 263; //x
static const size_t prime = 1000000007;//prime number
unsigned long long hash = 0;
for (int i = static_cast<int> (s.size()) - 1; i >= 0; --i)
hash = (mulmod(hash, multiplier, prime) + s[i]) % prime;
return hash;
}
vector<long long> precomputeHashes(string t, int p_len){
vector<long long> H(t.length()-p_len +1, 0);
long long p=1000000007;
long long x=263;
string s = t.substr(t.length()-p_len, p_len);
//cout<<s<<endl;
H[t.length()-p_len]=hash_func(s);
//cout<<H[t.length()-p_len]<<endl;
long long y=1;
for(int i=1;i<=p_len;i++){
y=mulmod(y, x, p);
}
//cout<<y<<endl;
for(int i=t.length()-p_len-1;i>=0;i--){
H[i]=((mulmod(x, int(H[i+1]), p)+t[i]-mulmod(y, t[i+p_len], p))%p+p)%p;
//cout<<"- "<<H[i]<<" - "<<mulmod(x, int(H[i+1]),p)<<" "<<int(t[i])<<" "<<mulmod(y, t[i+p_len], p)<<endl;
}
return H;
}
vector<int> Rabin_Karp(string t, string p){
vector<int> result;
long long phash=hash_func(p);
vector<long long> H=precomputeHashes(t, p.length());
for(int i=0;i<=(t.length()-p.length());i++){
if(phash==H[i]){
if(t.substr(i, p.length())==p){
result.push_back(i);
}
}
}
return result;
}
void print_occurrences(const std::vector<int>& output) {
for (size_t i = 0; i < output.size(); ++i)
std::cout << output[i] << " ";
std::cout << "\n";
}
int main() {
std::ios_base::sync_with_stdio(false);
Data temp=read_input();
print_occurrences(Rabin_Karp(temp.text, temp.pattern));
return 0;
}
| true |
2acbd826effa887e42d0fca3d8b0eb390fcc97e6 | C++ | agabrielson/MatlabOpenSSL | /mexRandom.cpp | UTF-8 | 3,504 | 2.90625 | 3 | [] | no_license | /* mexEVP_Decrypt.cpp
* Examples:
* reference readme.txt
*
* Notes:
* Lots - reference readme.txt
*
* To Build:
* Reference buildMex
*
* Author:
* Anthony Gabrielson
* agabrielson@me.com
* 3/30/2010
*
* Modifications:
*
*/
#include "mex.h"
#include "matlabIO.hpp"
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <string>
using namespace std;
void select_random_key(char *key, int b);
void select_random_iv(char *iv, int b);
int seed_prng(void);
void help();
/*
* mexFunction: Matlab entry function into this C code
* Inputs:
* int nlhs: Number of left hand arguments (output)
* mxArray *plhs[]: The left hand arguments (output)
* int nrhs: Number of right hand arguments (inputs)
* const mxArray *prhs[]: The right hand arguments (inputs)
*
* Notes:
* (Left) goes_out = foo(goes_in); (Right)
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
bool keySet = false, ivSet = false;
char key[EVP_MAX_KEY_LENGTH] = "this's my key";
char iv[EVP_MAX_IV_LENGTH] = "my iv";
string cmd;
for (int inputProc = 0; inputProc < nrhs; ) {
getStr( &prhs[inputProc++], cmd );
if (cmd == "key") {
keySet = true;
} else if(cmd == "iv") {
ivSet = true;
}else{
printf("Input Confusion: %s\n",cmd.c_str());
mexErrMsgTxt( cmd.c_str() );
}
}
if( keySet == false && ivSet == false ){
help();
return;
}
//OpenSSL automatically manages PRNG entropy (see function notes)
//if (!seed_prng()){
// mexPrintf("seed_prng()...\n");
// return;
//}
select_random_key(key, EVP_MAX_KEY_LENGTH);
select_random_iv(iv, EVP_MAX_IV_LENGTH);
//Send the data back to Matlab.
int output = 0;
if( keySet == true )
sendType(&plhs[output++], key, EVP_MAX_KEY_LENGTH, 1);
if( ivSet == true )
sendType(&plhs[output++], iv, EVP_MAX_IV_LENGTH, 1);
}
/*
* select_random_key: Computes a Psuedo Random Key
* Inputs:
* char *: The key to be computed
* int: The length of the key to be computed
*
* Notes:
* This function is from the OpenSSL book
*/
void select_random_key(char *key, int b)
{
RAND_bytes((unsigned char *) key, b);
//for (int i = 0; i < b - 1; i++)
// printf("%02X:", key[i]);
//printf("%02X\n", key[b - 1]);
}
/*
* select_random_iv: Computes a Psuedo Random IV
* Inputs:
* char *: The key to be computed
* int: The length of the key to be computed
*
* Notes:
* This function is from the OpenSSL book
*/
void select_random_iv(char *iv, int b)
{
RAND_pseudo_bytes((unsigned char *) iv, b);
}
/*
* seed_prng: Seed the random number generator
* Inputs:
*
* Notes:
* The OpenSSL code already uses /dev/urandom if
* available as well as other sources. On Windows
* it uses CryptGenRandom() among other things.
*/
int seed_prng(void)
{
#ifdef _WIN32
RAND_screen();
return 1;
#else
return RAND_load_file("/dev/urandom", 1024);
#endif
}
void help()
{
mexPrintf("mexRandom:\n");
mexPrintf("\tkey: Generate a key\n");
mexPrintf("\tiv: Generate a iv\n");
mexPrintf("If generating both a key and an iv the first return\n\tvalue will be the key and the second will be the iv.\n");
}
| true |
f6d44cd0d2b27b4b1cc45009f25b9ae8057b7a6f | C++ | praneyrai/Online-Judge-Solns | /SPOJ/PIE.cpp | UTF-8 | 867 | 2.59375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
const double pi = acos(-1);
const double eps = 0.0000001;
int n, r[10010], f;
bool func(double v) {
int cnt = 0;
for (int i = 0; i < n; i++) {
double kk = 1.0 * pi * r[i] * r[i] / v;
cnt += (int)kk;
}
if (cnt >= f + 1) return true;
return false;
}
void binary_search() {
double lo = eps , hi = 1e18;
while (hi - lo > eps) {
double mid = (lo + hi) / 2;
if (func(mid)) lo = mid;
else hi = mid;
// cout << fixed << setprecision(10) << lo << ' ' << fixed << setprecision(10) << hi << '\n';
}
printf("%.4lf\n", lo);
}
int main() {
int t; cin >> t;
while (t--) {
cin >> n >> f;
for (int i = 0; i < n; i++) cin >> r[i];
binary_search();
}
} | true |
cc3b77dc4d2a8640423f1d8c07f0d98c9b7814ae | C++ | ZihengZZH/Project_Cpp | /ConsoleGame_Dice/main.cpp | UTF-8 | 4,107 | 3.65625 | 4 | [] | no_license | #include <sstream>
#include <iomanip>
#include "autotest.h"
#include "autoplayer.h"
#include "player.h"
using namespace std;
/*
The sequence of the game should be specified explicitly
maybe in the generic sequence with which they were created
*/
// Function to receive a valid integer input
inline int get_integer(int min, int max, std::string prompt) {
int ret_integer;
string str_number;
while (true) {
cout << prompt;
getline(cin, str_number); // Get string input
stringstream convert(str_number); // Turn the string into a stream
if (convert >> ret_integer && !(convert >> str_number)
&& ret_integer <= max && ret_integer >= min)
return ret_integer;
cin.clear(); // In case an error occurs with cin (eof(), etc)
cerr << "Input must be integer in range ["
<< min << "," << max << "]. Please try again.\n";
}
}
// Function to show the conditions for auto test
inline void show_vector(vector<int> vec, string name) {
cout << "\nThe conditions for " << name << " is as follows" << endl;
for (auto i : vec) {
cout << " " << i;
}
cout << endl;
}
int main() {
// The variables for main functions
int player_num, auto_running, gain_value, throw_value;
string player_name, line;
vector<string> player_names;
vector<player> players;
vector<autoplayer> autoplayers;
// All the test conditions
vector<int> gain_vals = { 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 }; //20
vector<int> throw_vals = { 1,2,3,4,5,6,7,8,9,10 }; //10
vector<int> point_vals = { 50, 100, 150 }; //150
// 16*10*11*5000 = 8,800,000
cout << " --------------------------------------------\n"
<< "| " << setw(30) << " DICE GAME FOR ELEC362" << setw(15) << "|\n"
<< " --------------------------------------------\n"
<< "It is a dice game called Pig, "
<< "first described in print by John Scarne in 1945.\n"
<< "This game supports automatical running with two strategies.\n"
<< "First is to hold at specific gain and "
<< "the other is to hold after specific number of throws\n"
<< "------------------------------------------------------------\n"
<< "What game would you like to play\n"
<< "1. multiplayer mode\n"
<< "2. autoplayer mode\n"
<< "other autotest the game\n";
// Receive the input securely
getline(cin, line);
stringstream ss(line);
ss >> auto_running;
if (auto_running == 1) {
player_num = get_integer(2, 20, "How many of you want to join in? ");
cout << endl;
// Initialise the players with specified name
for (int i = 0; i < player_num; i++) {
cout << "Please enter No " << i << " player name ";
cin >> player_name;
player_names.push_back(player_name);
}
// Start the game
player* start = new player(player_names);
start->begin();
}
else if (auto_running == 2) {
gain_value = get_integer(1, 50, "Please input gain value for strategy GAIN ");
throw_value = get_integer(1, 20, "Please input throw value for strategy THROW ");
autoplayer* start = new autoplayer(gain_value, throw_value, 100);
start->begin();
}
else {
clock_t t;
t = clock();
show_vector(gain_vals, "GAIN values");
show_vector(throw_vals, "THROW values");
show_vector(point_vals, "Point to win");
// Start the auto game
autotest* result = new autotest("start");
result->statistics_ppl(gain_vals, throw_vals, point_vals);
t = clock() - t;
printf("It took me %d clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
/* NOTICE
There are two statistics functions to get the results of auto game
One of them is called statistics, which runs the auto game in serial fashion and consumes time
The other is called statistics_ppl, which runs the auto game in parallel fashion and saves time
The statistics_ppl disable cout because parallel computing causes disorder in outstream
*/
}
system("pause");
return 0;
}
/*
data scale 36,000
parallel 38s
serial 80s
data scale 24,000
parallel 21s
serial 46s
data scale 2,400,000
parallel 2583s
*/ | true |
6be7325762b947c2b8c955c4a59c37262f255b1e | C++ | ikr/exercism | /cpp/allergies/allergies.cpp | UTF-8 | 853 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "allergies.h"
#include <unordered_map>
namespace {
const std::unordered_map<std::string, unsigned int> bitcodes_by_substance{
{"eggs", 1}, {"peanuts", 2}, {"shellfish", 4}, {"strawberries", 8},
{"tomatoes", 16}, {"chocolate", 32}, {"pollen", 64}, {"cats", 128}};
} // namespace
namespace allergies {
allergy_test::allergy_test(const unsigned int code) : m_code(code) {}
bool allergy_test::is_allergic_to(const std::string &substance) const {
return m_code & bitcodes_by_substance.at(substance);
}
std::unordered_set<std::string> allergy_test::get_allergies() const {
std::unordered_set<std::string> answer;
for (auto substance_and_code : bitcodes_by_substance)
if (substance_and_code.second & m_code)
answer.insert(substance_and_code.first);
return answer;
}
} // namespace allergies
| true |
b9813e27c9b5b215a10dd24a343cd7fc0bea69e9 | C++ | yojoecool/ArchitectureProjects | /pipeSim.cpp | UTF-8 | 14,001 | 2.671875 | 3 | [] | no_license | /*
* Added:
* NOP Counter
* IC
* C
* Branch now adds a NOP - Done seperately from the normal NOP for 2 reasons:
* 1. Easy way to avoid increasing currentText
* 2. Easier to add things to this NOP if we need to, since it is a seperate case
* Fetch has been changed to handle this new NOP
* opA and opB have been added to the id_ex struct
* ADDI, ADD, SUBI, and LB now use opA and opB instead of rSrc1 and rSrc2
* Decode and Execute now use opA and opB instead of rSrc1 and rSrc2
*/
#include <stdio.h>
#include <stdint.h>
#include <iomanip>
#include "GPRMem.cpp"
uint16_t reg[32];
bool userMode = true;
int currentText = 0;
bool isBranching = false;
int NOPcounter = 0;
int IC = 0;
bool branchFound = false; // was the last instruction decoded a branch
bool addNop = false; // add a NOP to current cycle
// ADDI Rdest, Rsrc1, Imm
uint16_t addi(uint16_t opA, uint16_t imm) {
return opA + imm;
}
// ADD Rdest, Rsrc1, Rsrc2
uint16_t add(uint16_t opA, uint16_t opB) {
return opA + opB;
}
// SUBI Rdest, Rsrc1, Imm
uint16_t subi(uint16_t opA, uint16_t imm) {
return opA - imm;
}
// LA Rdest, label
void la(unsigned char rDest, uint16_t label) {
reg[(int) rDest] = label;
}
// LB Rdest, offset(Rsrc1)
uint16_t lb(uint16_t opA) {
return (uint16_t)memory[opA];
}
//case END
void end() {
userMode = false;
}
// SYSCALL
// 4 -> printf
// 8 -> scanf
// 10 -> end the program
void syscall(bool memPhase) {
int i;
char input_string[(int)reg[30]];
int memLocation;
switch ((int)reg[29]) {
case 1:
if (!memPhase) {
cout << (int16_t)reg[4] << endl;
}
break;
case 4:
if (memPhase) {
i = (int)reg[30];
while ((int)memory[i] != 0) {
cout << memory[i];
i++;
}
printf("\n");
}
break;
case 8:
if (memPhase) {
cout << "Enter a string: ";
std::fgets(input_string, (int)reg[31], stdin);
memLocation = (int)reg[30];
for (int i = 0; i < (int)reg[31]; i++) {
memory[memLocation + i] = input_string[i];
}
}
break;
case 10:
userMode = false;
break;
}
}
// Latches
struct id_ex {
int opCode;
unsigned char rSrc1;
unsigned char rSrc2;
unsigned char rDest;
uint16_t opA;
uint16_t opB;
uint16_t imm;
uint16_t label; // new PC for branches
id_ex(int opCode = 13, unsigned char rSrc1 = '\0', unsigned char rSrc2 = '\0', unsigned char rDest = '\0',
uint16_t opA = 0, uint16_t opB = 0, uint16_t imm = 0, uint16_t label = 0) :
opCode (opCode), rSrc1 (rSrc1), rSrc2 (rSrc2), rDest (rDest), opA (opA), opB (opB), imm (imm), label (label) {}
};
struct ex_mem {
int opCode;
uint16_t ALU_out;
unsigned char rDest;
ex_mem(int opCode = 13, uint16_t ALU_out = 0, unsigned char rDest = '\0') :
opCode (opCode), ALU_out (ALU_out), rDest (rDest) {}
};
// WHAT IS MDR
struct mem_wb {
int opCode;
uint16_t ALU_out;
unsigned char rDest;
mem_wb(int opCode = 13, uint16_t ALU_out = 0, unsigned char rDest = '\0') :
opCode (opCode), ALU_out (ALU_out), rDest (rDest) {}
};
// instruction register
int if_id_new = 0;
int if_id_old = 0;
// [opcode, rs, rt, rd, operand A, operand B, immediate or offset, new PC for branches]
id_ex* id_ex_new = new id_ex;
id_ex* id_ex_old = new id_ex;
// [op code, ALU out, rd]
ex_mem* ex_mem_new = new ex_mem;
ex_mem* ex_mem_old = new ex_mem;
// [op code, MDR?, ALU out, rd]
mem_wb* mem_wb_new = new mem_wb;
mem_wb* mem_wb_old = new mem_wb;
// method for forwarding
void forwarding() {
if (ex_mem_new->rDest == id_ex_new->rSrc1) {
id_ex_new->opA = ex_mem_new->ALU_out;
}
else if (ex_mem_old->rDest == id_ex_new->rSrc1) {
id_ex_new->opA = ex_mem_old->ALU_out;
}
if (ex_mem_new->rDest == id_ex_new->rSrc2) {
id_ex_new->opB = ex_mem_new->ALU_out;
}
else if (ex_mem_old->rDest == id_ex_new->rSrc2) {
id_ex_new->opB = ex_mem_old->ALU_out;
}
}
// Stages
// Fetch: use current value in PC to index memory and retrieve instruction
// put instruction into if/id
void fetch() {
if_id_old = if_id_new;
if (branchFound) {
addNop = true;
branchFound = false;
}
else if_id_new = currentText;
}
// Decode: reads zero, one, or two values out of register file
// stores value in id/ex
void decode() {
// Move new to old
id_ex_old->opCode = id_ex_new->opCode;
id_ex_old->rSrc1 = id_ex_new->rSrc1;
id_ex_old->rSrc2 = id_ex_new->rSrc2;
id_ex_old->rDest = id_ex_new->rDest;
id_ex_old->opA = id_ex_new->opA;
id_ex_old->opB = id_ex_new->opB;
id_ex_old->imm = id_ex_new->imm;
id_ex_old->label = id_ex_new->label;
id_ex_new->opCode = (int)memory[if_id_new];
if (addNop) id_ex_new->opCode = 14;
if (id_ex_new->opCode != 0) IC++;
switch (id_ex_new->opCode) {
case 0: // label
currentText += 1;
break;
case 1: // addi
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->rSrc1 = memory[if_id_new + 2];
id_ex_new->imm = memory[if_id_new + 3] << 8;
id_ex_new->imm |= memory[if_id_new + 4];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
forwarding();
currentText += 5;
break;
case 2: // b
id_ex_new->label = memory[if_id_new + 1] << 8;
id_ex_new->label |= memory[if_id_new + 2];
branchFound = true;
currentText = id_ex_new->label;
break;
case 3: // beqz
id_ex_new->rSrc1 = memory[if_id_new + 1];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
id_ex_new->label = memory[if_id_new + 2] << 8;
id_ex_new->label |= memory[if_id_new + 3];
forwarding();
branchFound = true;
if ((int)id_ex_new->opA == 0) currentText = id_ex_new->label;
else currentText += 4;
break;
case 4: // bge
id_ex_new->rSrc1 = memory[if_id_new + 1];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
id_ex_new->rSrc2 = memory[if_id_new + 2];
id_ex_new->opB = reg[(int)id_ex_new->rSrc2];
id_ex_new->label = memory[if_id_new + 3] << 8;
id_ex_new->label |= memory[if_id_new + 4];
branchFound = true;
forwarding();
if ((int16_t)id_ex_new->opA >= (int16_t)id_ex_new->opB) currentText = id_ex_new->label;
else currentText += 5;
break;
case 5: // bne
id_ex_new->rSrc1 = memory[if_id_new + 1];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
id_ex_new->rSrc2 = memory[if_id_new + 2];
id_ex_new->opB = reg[(int)id_ex_new->rSrc2];
id_ex_new->label = memory[if_id_new + 3] << 8;
id_ex_new->label |= memory[if_id_new + 4];
forwarding();
branchFound = true;
if (id_ex_new->opA != id_ex_new->opB) currentText = id_ex_new->label;
else currentText += 5;
break;
case 6: // la
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->label = memory[if_id_new + 2] << 8;
id_ex_new->label |= memory[if_id_new + 3];
currentText += 4;
break;
case 7: // lb
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->imm = memory[if_id_new + 2]; //offset
id_ex_new->rSrc1 = memory[if_id_new + 3];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
forwarding();
currentText += 4;
break;
case 8: // li
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
id_ex_new->imm = memory[if_id_new + 2] << 8;
id_ex_new->imm |= memory[if_id_new + 3];
forwarding();
currentText += 4;
break;
case 9: // subi
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->rSrc1 = memory[if_id_new + 2];
id_ex_new->imm = memory[if_id_new + 3] << 8;
id_ex_new->imm |= memory[if_id_new + 4];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
forwarding();
currentText += 5;
break;
case 10: // syscall
currentText += 1;
break;
case 11: // NOP
currentText += 1;
NOPcounter += 1;
break;
case 12: // add
id_ex_new->rDest = memory[if_id_new + 1];
id_ex_new->rSrc1 = memory[if_id_new + 2];
id_ex_new->rSrc2 = memory[if_id_new + 3];
id_ex_new->opA = reg[(int)id_ex_new->rSrc1];
id_ex_new->opB = reg[(int)id_ex_new->rSrc2];
forwarding();
currentText += 4;
break;
case 14: // added NOP
NOPcounter += 1;
addNop = false;
break;
default:
break;
}
}
// Execute: execute operation
// put result in ex/mem
// For Branches, ALU_out = 1 for true, 0 for false
void execute() {
// move new to old
ex_mem_old->opCode = ex_mem_new->opCode;
ex_mem_old->ALU_out = ex_mem_new->ALU_out;
ex_mem_old->rDest = ex_mem_new->rDest;
ex_mem_new->opCode = id_ex_new->opCode;
switch (ex_mem_new->opCode) {
case 1: // addi
ex_mem_new->ALU_out = addi(id_ex_new->opA, id_ex_new->imm);
ex_mem_new->rDest = id_ex_new->rDest;
break;
case 6: // la
ex_mem_new->ALU_out = id_ex_new->label;
ex_mem_new->rDest = id_ex_new->rDest;
break;
case 7: // lb
ex_mem_new->ALU_out = lb(id_ex_new->opA);
ex_mem_new->rDest = id_ex_new->rDest;
break;
case 8: // li
ex_mem_new->ALU_out = id_ex_new->imm;
ex_mem_new->rDest = id_ex_new->rDest;
break;
case 9: // subi
ex_mem_new->ALU_out = subi(id_ex_new->opA, id_ex_new->imm);
ex_mem_new->rDest = id_ex_new->rDest;
break;
case 10: // syscall
syscall(false);
break;
case 12: // add
ex_mem_new->ALU_out = add(id_ex_new->opA, id_ex_new->opB);
ex_mem_new->rDest = id_ex_new->rDest;
break;
default:
break;
}
}
// Memory: if instruction in mem is r-type then the mem/wb should buffer the result held in ex/mem
void memStage() {
mem_wb_old->opCode = mem_wb_new->opCode;
mem_wb_old->ALU_out = mem_wb_new->ALU_out;
mem_wb_old->rDest = mem_wb_new->rDest;
mem_wb_new->opCode = ex_mem_new->opCode;
switch (mem_wb_new->opCode) {
case 1: // addi
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
case 6: // la
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
case 7: // lb
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
case 8: // li
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
case 9: // subi
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
case 10:
syscall(true);
break;
case 12: // add
mem_wb_new->ALU_out = ex_mem_new->ALU_out;
mem_wb_new->rDest = ex_mem_new->rDest;
break;
default:
break;
}
}
// Write-Back: puts results of R-type instrction or a load into the register file
// value comes from mem/wb
void write_back() {
switch (mem_wb_new->opCode) {
case 1: // addi
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
case 6: // la
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
case 7: // lb
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
case 8: // li
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
case 9: // subi
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
case 12: // add
reg[(int)mem_wb_new->rDest] = mem_wb_new->ALU_out;
break;
default:
break;
}
}
int main() {
string fileName;
char getNextLine[100];
cout << "Please enter a file name: ";
cin >> fileName;
fgets(getNextLine, 100, stdin);
GPRMem tempMem = GPRMem(fileName);
int C = 0;
while (userMode) {
write_back();
memStage();
execute();
decode();
fetch();
C += 2;
}
cout << "\nInstruction Count: " << IC << "\tCycles: " << C << "\tNOP Count: " << NOPcounter << endl;
return 0;
}
| true |
e2290ce697b0f619cfcdce3268fb89c1c91c35fc | C++ | zhuwenboa/data_struct | /data/leetcode/codecc字节/113.cpp | UTF-8 | 1,186 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum)
{
if(!root)
return {};
vector<vector<int>> ans;
vector<int> cur;
backtrack(root, cur, ans, targetSum);
return ans;
}
void backtrack(TreeNode* node, vector<int>& cur, vector<vector<int>>& ans, int target)
{
if(node->val == target && !node->left && !node->right)
{
cur.emplace_back(node->val);
ans.emplace_back(cur);
cur.pop_back();
return;
}
cur.emplace_back(node->val);
if(node->left)
backtrack(node->left, cur, ans, target - node->val);
if(node->right)
backtrack(node->right, cur, ans, target - node->val);
cur.pop_back();
}
}; | true |
ddd910a0ea7fd66572f368ebe0c717e6e51b1158 | C++ | souravs17031999/data_structures_algorithms | /LINKED LISTS/doubly_linked_list_inserting_deletion.cpp | UTF-8 | 2,320 | 4.1875 | 4 | [] | no_license | // program for Insertion and deletion of nodes in doubly linked lists
// @author sourav kumar , 08-02-2019
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
node *prev;
};
class linked_list{
private:
node *head;
public:
linked_list(){
head = NULL;
}
void insert_beg(int n){
node *new_node = new node;
new_node-> data = n;
new_node->prev = NULL;
new_node->next = NULL;
if(head == NULL){
head = new_node;
return;
}
head->prev = new_node;
new_node->next = head;
head = new_node;
}
void display(){
node *ptr = head;
node *temp;
while(ptr != NULL){
cout << ptr->data << " ";
temp = ptr;
ptr = ptr->next;
}
cout << endl;
while(temp != NULL){
cout << temp->data << " ";
temp = temp->prev;
}
}
void insert_at(int p , int n){
node *new_node = new node;
new_node->data = n;
new_node->prev = NULL;
new_node->next = NULL;
node *ptr = head;
while(ptr != NULL){
if(ptr->data == p){
break;
}
ptr = ptr->next;
}
new_node->next = ptr->next;
ptr->next = new_node;
new_node->prev = ptr;
if(new_node->next != NULL){
new_node->next->prev = new_node;
}
}
void insert_last(int n){
node *new_node = new node;
new_node->data = n;
new_node->next = NULL;
if(head == NULL){
new_node->prev = NULL;
head = new_node;
return;
}
node *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new_node;
new_node->prev = ptr;
}
void delete_at(int n){
if(head == NULL){
cout << "empty list , underflow" << endl;
return;
}
node *ptr = head;
node *temp;
while(ptr != NULL){
if(ptr->next->data == n){
temp = ptr->next->next;
break;
}
ptr = ptr->next;
}
delete ptr->next;
ptr->next = temp;
temp->prev = ptr;
}
};
int main(){
linked_list a;
a.insert_beg(35);
a.insert_beg(30);
a.insert_beg(25);
a.insert_beg(20);
a.insert_beg(10);
a.insert_beg(5);
a.insert_at(25,28);
a.insert_last(40);
a.delete_at(25);
a.display();
}
| true |
33610ef3d701720fa24984fa1e0b2204c7947296 | C++ | jonathan2222/SimpleLUACompiler | /AST/Symbols.hh | UTF-8 | 771 | 2.890625 | 3 | [] | no_license | #ifndef SYMBOLS_HH
#define SYMBOLS_HH
#include <unordered_map>
#include <string>
#include "Data.hh"
class BBlock;
struct Symbol
{
Symbol() {}
Symbol(Data::Type type) { data.type = type; }
unsigned int size = 0;
int arg = -1; // arg < 0: no argument, else argument at position arg.
std::string toString() const;
bool operator==(const Symbol& other) const;
Data data;
BBlock* funcBlock = nullptr;
};
class Node;
class Symbols
{
public:
Symbols(Node* parent) : parent(parent) {}
virtual ~Symbols() {}
bool hasKey(std::string key);
void insert(std::string key, Symbol sym);
Symbol get(std::string key);
void removeKey(std::string key);
void print(unsigned depth) const;
std::unordered_map<std::string, Symbol> map;
Node* parent = nullptr;
};
#endif | true |
bead5df562e9c0c34920943e1a8e235259d56e06 | C++ | T4G2/grx | /core/src/nodes/camera_node.cpp | UTF-8 | 4,796 | 2.546875 | 3 | [] | no_license | /**
* @file camera_node.cpp
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2021-05-22
*/
#include "camera_node.hpp"
#include "glm/gtx/transform.hpp"
#include "scene.hpp"
#include "GLFW/glfw3.h"
#include <glm/gtc/type_ptr.hpp>
#include "scene_manager.hpp"
#include "iapplication.hpp"
void CameraNode::init() {
width = instance.get_scene()->get_scene_manager().app.width;
height = instance.get_scene()->get_scene_manager().app.height;
if (is_active) {
instance.get_scene()->activeCamera = this;
if (projection_type == ProjectionType::Perspective) {
projection_matrix = glm::perspective(fov, static_cast<float>(width) / height, z_close, z_far);
}
}
}
void CameraNode::update(float delta) {
//add_pos(glm::vec3(0, 0, -1) * delta);
if (_updated_position) {
BaseNode::update(delta);
glm::vec3 r_global_vec3 = get_global_rotation_direction();
glm::mat4 rot_matrix = glm::mat4(1.0f);
rot_matrix = glm::rotate(r_global_vec3.x, glm::vec3(1,0,0)) * rot_matrix;
rot_matrix = glm::rotate(r_global_vec3.y, glm::vec3(0,1,0)) * rot_matrix;
rot_matrix = glm::rotate(r_global_vec3.z, glm::vec3(0,0,1)) * rot_matrix;
glm::vec4 look_at4 = rot_matrix * glm::vec4(1.0, 0.0, 0.0, 1.0);
glm::vec4 up4 = rot_matrix * glm::vec4(0.0, 1.0, 0.0, 1.0);
glm::vec3 look_at3 = glm::vec3(look_at4);
glm::vec3 up3 = glm::vec3(up4);
camera_matrix = glm::inverse(local_space_matrix);
//camera_matrix = glm::lookAt(get_global_pos(), get_global_pos() + look_at3, up3 );
}
}
void CameraNode::draw() {
}
void CameraNode::input(input_struct event) {
BaseNode::input(event); // propagate to children
}
void CameraNode::uniform_projection_matrix(GLuint location) {
glUniformMatrix4fv(location, 1, 0, glm::value_ptr(projection_matrix));
}
void CameraNode::uniform_view_matrix(GLuint location) {
glUniformMatrix4fv(location, 1, 0, glm::value_ptr(camera_matrix));
}
void CameraNode::uniform_eye_pos_vec3(GLuint location) {
auto pos = this->get_global_pos();
glUniform3f(location, pos.x, pos.y , pos.z );
}
void CameraNode::init_custom_toml(BaseNodeInstance::toml_properties_t props) {
BaseNode::init_custom_toml(props);
for (auto& [name, obj] : props) {
//std::cout << "\t" << name << "\n";
if (prop_func.contains(name)) {
(this->*prop_func.at(name))(obj);
}
}
};
void CameraNode::init_fov(toml_value data) {
if (data.is_floating()) {
fov = static_cast<float>(data.as_floating());
return;
}
if (data.is_integer()) {
fov = static_cast<float>(data.as_integer());
return;
}
std::cerr << "WARNING, fov in <" << name << "> is not a float or int. example: fov = 90.5\n";
return;
}
void CameraNode::init_projection_type(toml_value data) {
if (!data.is_string()) {
std::cerr << "WARNING, projection type in <" << name << "> is not a string. example: projection_type = \"perspective\"\n";
return;
}
std::string name = data.as_string();
if (name == "perspective") {
projection_type = ProjectionType::Perspective;
return;
}
if (name == "orthogonal") {
projection_type = ProjectionType::Orthogonal;
return;
}
std::cerr << "WARNING, projection type in <" << name << "> is not a valid string. valid strings = {\"perspective\", \"orthogonal\"}\n";
}
void CameraNode::init_auto_size(toml_value data){
if (!data.is_boolean()) {
std::cerr << "WARNING, init_auto_size in <" << name << "> is not a boolean. example: init_auto_size = true/false\n";
return;
}
bool is_auto_size = data.as_boolean();
}
void CameraNode::init_active(toml_value data) {
if (!data.is_boolean()) {
std::cerr << "WARNING, init_active in <" << name << "> is not a boolean. example: init_auto_size = true/false\n";
return;
}
is_active = true;
}
void CameraNode::init_size(toml_value data) {
if (! data.is_array()) {
std::cerr << "WARNING, size in <" << name << "> is not a array. example: size = [1455, 124]\n";
return;
}
auto array = data.as_array();
if (array.size() != 2) {
std::cerr << "WARNING, size in <" << name << "> is array but has no size of 2. example: size = [1455, 124]\n";
return;
}
if (!array.at(0).is_integer() || !array.at(0).is_integer()) {
std::cerr << "WARNING, size in <" << name << "> is array of size 2 , but has no int,int inside. example: size = [1455, 124]\n";
return;
}
width = static_cast<int>(array.at(0).as_integer());
height = static_cast<int>(array.at(1).as_integer());
}
| true |
24b20a16fb406d28e0f34fe81564d7913fe4c952 | C++ | sebacagnoni/juegoDeLaVida | /TPI-toroide/tests/EJ13_vistaTrasladadaTEST.cpp | UTF-8 | 2,417 | 3 | 3 | [] | no_license | #include "../ejercicios.h"
#include "gtest/gtest.h"
#include <algorithm>
using namespace std;
TEST(vistaTrasladadaTEST, muevoTerceraFilaParaArriba){
toroide t1 = {
{true, false, false}, // 1
{false, true, false}, // 2
{false, false, true}};// 3
toroide t2 = {
{false, false, true}, // 3
{true, false, false}, // 1
{false, true, false}};// 2
bool res = vistaTrasladada(t1, t2);
EXPECT_TRUE(res);
}
TEST(vistaTrasladadaTEST, DiagonalVsTodoTrue){
toroide t1 = {
{true, false, false},
{false, true, false},
{false, false, true}};
toroide t2 = {
{true, true, true},
{true, true, true},
{true, true, true}};
bool res = vistaTrasladada(t1, t2);
EXPECT_FALSE(res);
}
/*********************************************************************/
TEST(vistaTrasladadaTEST, TresMovArribaYDosMovAlaIzquierda){
toroide t1 = {
// 0 //1 //2 //3 //4
{false, true, true, false, false}, // 0
{false, false, false, false, false}, // 1
{false, false, true, false, false}, // 2
{true, false, true, true, true } // 3
};
toroide t2 = {
//2 //3 //4 //0 //1
{true, true, true, true, false}, //3
{true, false, false, false, true }, //0
{false, false, false, false, false}, //1
{true, false, false, false, false} //2
};
bool res = vistaTrasladada(t1, t2);
EXPECT_TRUE(res);
}
TEST(vistaTrasladadaTEST, TresMovALaDerecha){
toroide t1 = {
// 0 //1 //2 //3 //4
{true, true, true, false, false}, // 0
{false, true, false, false, false}, // 1
{false, false, true, false, false}, // 2
{true, false, true, true, true } // 3
};
toroide t2 = {
// 2 //3 //4 //0 //1
{true, false, false, true, true}, // 0
{false, false, false, false, true}, // 1
{true, false, false, false, false}, // 2
{true, true, true, true, false} // 3
};
bool res = vistaTrasladada(t1, t2);
EXPECT_TRUE(res);
} | true |
c94a42289010744b49c2515645894b90fd5203a8 | C++ | GregoryAlbarian/PunnettSquares | /Gene.cpp | UTF-8 | 281 | 2.90625 | 3 | [] | no_license | #include "Gene.h"
Gene::Gene(char allele1, char allele2)
{
this->allele1=&allele1;
this->allele2=&allele2;
}
Gene::~Gene()
{
delete allele1;
delete allele2;
}
char Gene::getAllele1()
{
return *allele1;
}
char Gene::getAllele2()
{
return *allele2;
} | true |
d77b2c84aa4bff767c9f092f6cc81ca9ea873adb | C++ | Herbet-filho/pet_fera | /Entrega_final/src/classes_animal/mamifero_exotico.cpp | UTF-8 | 1,296 | 2.71875 | 3 | [] | no_license | #include "mamifero_exotico.hpp"
MamiferoExotico::MamiferoExotico(){}
MamiferoExotico::MamiferoExotico(string nutricao, string risco_extincao, bool periculosidade,
string id, string especie, string sexo, string fecundacao,
string pelagem, string deslocamento, string regiao):
Mamifero(nutricao, risco_extincao, periculosidade, id, especie, sexo, fecundacao,
pelagem, deslocamento), Exotico(regiao){}
MamiferoExotico::~MamiferoExotico(){}
ostream&
MamiferoExotico::print(ostream &o){
o << "Espécie: "<< this->getEspecie() << endl
<< "Classe: Mamifero" << endl
<< "Tipo: Exotico" << endl
<< "ID: " << this->getId() << endl
<<"Nutrição: "<< this->getNutricao() << endl
<<"Periculosidade: "<< this->getPericulosidadeNivel() << endl
<<"Risco de extinção: "<< this->getRisco_extincao() << endl
<<"Deslocamento: " << this->getDeslocamento() << endl
<<"Pelagem: " << this->getPelagem() << endl
<<"Tratador responsável: " << this->getNomeTratador()<< endl
<<"Veterinário responsável: "<< this->getNomeVeterinario() << endl
<<"Região originária do animal: " << this->getRegiao() << endl;
return o;
} | true |
1c4a347a5ced8f46d74895788a7416407fcb6826 | C++ | Gyubin-Lee/MineSweeper | /Array_ver/cellChained.h | UTF-8 | 2,077 | 3.4375 | 3 | [] | no_license | #ifndef C_CHAIN_H
#define C_CHAIN_H
#include "cell.h"
#include <iostream>
class cellChain;
class cellNode
{
friend class cellChain;
public:
cellNode(Cell *cell_)
{
cell = cell_;
next = 0;
down = 0;
}
private:
Cell *cell;
cellNode *next;
cellNode *down;
};
class cellChain
{
public:
cellChain()
{
first = 0;
}
void addHeadLast(Cell *newData)
{
if (!first)
{
cellNode *newNode = new cellNode(newData);
first = newNode;
}
else
{
cellNode *temp = first;
cellNode *prev;
while (temp)
{
prev = temp;
temp = temp->down;
}
cellNode *newNode = new cellNode(newData);
prev->down = newNode;
}
}
void addItemLast(int headIndex, Cell *newData)
{
int i = 0;
cellNode *temp = first;
while (i < headIndex)
{
temp = temp->down;
i++;
}
cellNode *prev;
while (temp)
{
prev = temp;
temp = temp->next;
}
cellNode *newNode = new cellNode(newData);
prev->next = newNode;
}
Cell *returnCell(int row, int col)
{
int i = 0;
int j = 0;
cellNode *temp = first;
while (i < row)
{
temp = temp->down;
i++;
}
while (j < col)
{
temp = temp->next;
j++;
}
return temp->cell;
}
void printCellType()
{
cellNode *tempHead = first;
while (tempHead)
{
cellNode *tempItem = tempHead;
while (tempItem)
{
std::cout << tempItem->cell->cellType;
std::cout << " ";
tempItem = tempItem->next;
}
std::cout << std::endl;
tempHead = tempHead->down;
}
}
private:
cellNode *first;
};
#endif | true |
089c8b76f841db211873cbce0f0a53cdf62a05c0 | C++ | RiverHamster/OI-Works | /testpack/wen/2018.1.4/src/吕毅/elephant.cpp | UTF-8 | 395 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int main()
{
freopen("elephant.in","r",stdin);
freopen("elephant.out","w",stdout);
int t,n;
cin>>t;
while(t--)
{
int ans=0;
cin>>n;
while(1)
{
if(n-10>=0){n-=10;ans++;}else break;
}
while(1)
{
if(n-5>=0){n-=5;ans++;}else break;
}
while(1)
{
if(n-1>=0){n-=1;ans++;}else break;
}
cout<<ans<<endl;
}
} | true |
52602ea81f710ce70ba54cd12aeb456b128315ca | C++ | jatin0101/Montecarlo-simulations | /MonteCarlo.cpp | UTF-8 | 973 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
int timesteps = 30;
int volatility = 2; //2 %
int max_simulations = 5000;
float starting_price = 600;
float path[max_simulations][timesteps+1];
// Timesteps + 1 is for the starting price at Day 0 to be at the start of every array
srand(time(0));
for(int j=0;j<max_simulations;j++) path[j][0]=starting_price;
for(int p=0;p<max_simulations;p++)
{
for(int i=1;i<=timesteps;i++)
{
float rand_rate=(float)(rand()-RAND_MAX/2)*volatility*2/RAND_MAX;
path[p][i]=path[p][i-1]*(1+rand_rate/100);
}
}
ofstream outputfile;
outputfile.open("paths.txt");
for(int i = 0; i<max_simulations; i++)
{
for(int j = 0; j<(timesteps+1); j++)
{
outputfile<<path[i][j]<<" ";
}
outputfile<<endl;
}
outputfile.close();
} | true |
4d486f47e6295b71116acce020b9ab9ab2ef6d8c | C++ | harshadmanglani/Coursework | /OOPL/Virtual_Functions.cpp | UTF-8 | 1,669 | 3.765625 | 4 | [] | no_license |
/
*
Inheritance and virtual functions
*/
#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int width;
int height;
public:
virtual void displayArea()=0; //pure virtual function
void setWidth() {
cout<<"Enter parameter 2: "; cin>>width; cout<<endl;
}
void setHeight() {
cout<<"Enter parameter 1: "; cin>>height; cout<<endl;
}
};
// Derived class
class Rectangle: public Shape
{
public:
void displayArea() {
double area = (width * height);
cout<< " \n Area of the rectangle is " << area<<endl;
}
};
class Circle :public Shape
{
public:
void displayArea()
{
double area = 3.14*width*width;
cout<< " \n Area of the circle is " << area<<endl;
}
};
class Triangle :public Shape
{
public:
void displayArea()
{
double area = 0.5*height*width;
cout << " \n Area of the triangle is "<< area<<endl;
}
};
int main(void) {
int c = 0;
Shape* p;
while(c!=4){
cout<<"\n\n1. Rectangle\n2. Traingle\n3. Circle\n4. Quit\n";
cout<<"Enter your choice: ";
cin>>c;
cout<<endl;
switch(c){
case 1:
p = new Rectangle();
p->setHeight();
p->setWidth();
p->displayArea();
delete p;
break;
case 2:
p = new Triangle();
p->setHeight();
p->setWidth();
p->displayArea();
delete p;
break;
case 3:
p = new Circle();
p->setWidth();
p->displayArea();
delete p;
break;
case 4:
break;
}
}
return 0;
}
| true |
3cb6ce4a6388de6ce151a9e18bb90756737477ea | C++ | sfofgalaxy/Summary-of-Software-Engineering-Coursework-in-Zhejiang-University | /2大二/面向对象程序设计/project/3170105860_彭子帆/source code/oop_image/oop_image/contrast.cpp | UTF-8 | 843 | 2.59375 | 3 | [] | no_license | #include"menu.h"
#include"factor.h"
#include"header.h"
void Menu::contrast_funtion()
{
int pixels = image->width() * image->height();
unsigned int *data = (unsigned int *)image->bits();
int red, green, blue, nRed, nGreen, nBlue;
float param = 1 / (1 - contrast_value) - 1;
for (int i = 0; i < pixels; ++i)
{
nRed = qRed(data[i]);
nGreen = qGreen(data[i]);
nBlue = qBlue(data[i]);
red = nRed + (nRed - 127) * param;
red = (red < 0x00) ? 0x00 : (red > 0xff) ? 0xff : red;
green = nGreen + (nGreen - 127) * param;
green = (green < 0x00) ? 0x00 : (green > 0xff) ? 0xff : green;
blue = nBlue + (nBlue - 127) * param;
blue = (blue < 0x00) ? 0x00 : (blue > 0xff) ? 0xff : blue;
data[i] = qRgba(red, green, blue, qAlpha(data[i]));
}
}
| true |
be30b3d3b22a45366781aa27484be9dc02af9d9a | C++ | themagex1/DreamOS | /Pamiec.cpp | UTF-8 | 3,811 | 2.703125 | 3 | [] | no_license | //Made by Gregory Matczak
#include "Pamiec.hpp"
#include "PCB.hpp"
#include "Includes.hpp"
//funkcja koduj�ca adres
unsigned int Pamiec::zakoduj_adres(unsigned int index_strony, unsigned int offset)
{
return (index_strony << WIELKOSC_STRONY_WYKLADNIK) + offset;
}
//funkcja dekoduj�ca adres
void Pamiec::dekoduj_adres(int& adres, unsigned int* index_strony, unsigned int* offset)
{
*offset = adres & MASKA_OFFSET;
*index_strony = (adres >> WIELKOSC_STRONY_WYKLADNIK);
}
//konstruktor klasy pami��
Pamiec::Pamiec(std::shared_ptr<VirtualMemory> virtualMemory)
{
for (int i = 0; i < 128; i++) ram[i] = 126; //~
pamiec_ram = std::make_shared<std::array<char, 128>>(ram);
this->virtualMemory = virtualMemory;
}
//funkcja zapisuj�ca pojedynczy bajt w pami�ci pod podanym adresem, w przypadku blednego adresu wyrzucany jest wyjatek
void Pamiec::zapisz_do_ramu(int adres, std::string wartosc, std::shared_ptr<PCB> pcb)
{
//sprawdz_adres(adres, pcb->tablicaStron);
unsigned int index, offset;
int space = adres - pcb->tablicaStron->size() * 8 + wartosc.length() + 1;
int pages = ceil((double)wartosc.length() / 8);
dekoduj_adres(adres, &index, &offset);
if (space <= 0)
{
if (!pcb->tablicaStron->at(index).isFree)
{
virtualMemory->write_to_virtual(pcb, wartosc, adres);
for (int i = 0; i < 8; i++)
{
pamiec_ram->at(pcb->tablicaStron->at(index).Frame * 8 + i) = virtualMemory->ExchangeSpace[pcb->GetPID()][index].data[i];
}
return;
}
}
else if (space > 0)
{
virtualMemory->make_bigger(space, pcb);
}
virtualMemory->write_to_virtual(pcb, wartosc, adres);
for (int i = pages; i >= 0; i--)
{
virtualMemory->load_to_ram(pamiec_ram, pcb->tablicaStron->size() - (i + 1), pcb->GetPID(), pcb->tablicaStron);
}
}
//funkcja odczytujaca bajt z poda danego adresu, w przypadku blednego adresu wyrzucany jest wyjatek
unsigned char Pamiec::czytaj_bajt(int adres, std::shared_ptr<PCB> pcb)
{
sprawdz_adres(adres, pcb->tablicaStron);
unsigned int index, offset;
index = adres / 8;
offset = adres % 8;
int numer_ramki;
if (!pcb->tablicaStron->at(index).isFree)
{
numer_ramki = pcb->tablicaStron->at(index).Frame;
virtualMemory->LRU_update(numer_ramki);
}
else
{
numer_ramki = virtualMemory->load_to_ram(pamiec_ram, index, pcb->GetPID(), pcb->tablicaStron);
}
unsigned int pierwszy_bajt_ramki = numer_ramki * WIELKOSC_RAMKI;
return pamiec_ram->at(pierwszy_bajt_ramki + offset);
}
//funkcja zwalniaj�ca podany blok pami�ci, adres musi wskazywa� na pocz�tek strony(offset=0), w przypadku blednego adresu wyrzucany jest wyjatek
void Pamiec::zwolnij_pamiec(std::shared_ptr<PCB> pcb)
{
int frame;
for (int i = 0; i < pcb->tablicaStron->size(); i++)
{
if (!pcb->tablicaStron->at(i).isFree)
{
frame = pcb->tablicaStron->at(i).Frame;
for (int j = 0; j < 8; j++)
{
pamiec_ram->at((frame * 8) + j) = '~';
}
}
}
virtualMemory->erase(pcb->GetPID());
}
void Pamiec::pokaz_ram()
{
std::cout << "|------------------|Pamiec RAM|------------------|\n" << std::endl;
for (int i = 1; i <= 128; i++)
{
if (i % 8 == 0)std::cout << "\n";
if (pamiec_ram->at(i - 1) == '~') std::cout << i - 1 << ":[ ] ";
else std::cout << i - 1 << ":[" << pamiec_ram->at(i - 1) << "] ";
}
std::cout << std::endl << "|------------------------------------------------|\n";
}
//metoda sprawdzaj�ca poprawno�� adresu(na u�ytek wewn�trzny)
void Pamiec::sprawdz_adres(int& adres, std::shared_ptr<std::vector<PageData>> pageTable)
{
unsigned int index_strony;
unsigned int offset;
dekoduj_adres(adres, &index_strony, &offset);
if (index_strony >= pageTable->size())
{
throw std::invalid_argument("nieprawidlowy numer strony");
}
if (offset > WIELKOSC_STRONY)
{
throw std::invalid_argument("offset wykracza poza strone");
}
} | true |
364501efddf6b52e97534ec4e67237da493b22fc | C++ | MarkZH/Genetic_Chess | /src/Moves/Move.cpp | UTF-8 | 6,728 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "Moves/Move.h"
#include <cassert>
#include <cctype>
#include <string>
#include "Game/Board.h"
#include "Game/Square.h"
#include "Game/Game_Result.h"
#include "Game/Piece.h"
#include "Utility/String.h"
Move::Move(const Square start, const Square end) noexcept : origin(start), destination(end)
{
assert(start.inside_board());
assert(end.inside_board());
assert(start != end);
}
void Move::side_effects(Board&) const noexcept
{
}
bool Move::is_legal(const Board& board) const noexcept
{
assert(board.piece_on_square(start()));
assert(board.piece_on_square(start()).color() == board.whose_turn());
assert(board.piece_on_square(start()).can_move(this));
if(const auto attacked_piece = board.piece_on_square(end()))
{
if( ! can_capture() || board.whose_turn() == attacked_piece.color())
{
return false;
}
}
return move_specific_legal(board) && ! board.king_is_in_check_after_move(*this);
}
bool Move::move_specific_legal(const Board&) const noexcept
{
return true;
}
bool Move::can_capture() const noexcept
{
return able_to_capture;
}
Square Move::start() const noexcept
{
return origin;
}
Square Move::end() const noexcept
{
return destination;
}
Square_Difference Move::movement() const noexcept
{
return end() - start();
}
int Move::file_change() const noexcept
{
return end().file() - start().file();
}
int Move::rank_change() const noexcept
{
return end().rank() - start().rank();
}
std::string Move::algebraic(const Board& board) const noexcept
{
return algebraic_base(board) + result_mark(board);
}
std::string Move::algebraic_base(const Board& board) const noexcept
{
const auto original_piece = board.piece_on_square(start());
auto record_file = original_piece.type() == Piece_Type::PAWN && board.move_captures(*this);
auto record_rank = false;
for(auto other_move : board.legal_moves())
{
if(other_move->start() == start())
{
continue;
}
const auto new_piece = board.piece_on_square(other_move->start());
if(original_piece == new_piece && end() == other_move->end())
{
if(other_move->start().file() != start().file() && ! record_file)
{
record_file = true;
}
else if(other_move->start().rank() != start().rank())
{
record_rank = true;
}
}
}
auto move_record = original_piece.pgn_symbol();
if(record_file) { move_record += start().file(); }
if(record_rank) { move_record += std::to_string(start().rank()); }
if(board.move_captures(*this)) { move_record += 'x'; }
move_record += end().text();
return move_record;
}
std::string Move::result_mark(Board board) const noexcept
{
const auto result = board.play_move(*this);
if(board.king_is_in_check())
{
if(result.winner() == Winner_Color::NONE)
{
return "+";
}
else
{
return "#";
}
}
else
{
return {};
}
}
std::string Move::coordinates() const noexcept
{
const auto result = start().text() + end().text();
if(promotion_piece_symbol())
{
return result + String::tolower(promotion_piece_symbol());
}
else
{
return result;
}
}
bool Move::is_en_passant() const noexcept
{
return is_en_passant_move;
}
bool Move::is_castle() const noexcept
{
return is_castling_move;
}
Piece Move::promotion() const noexcept
{
return {};
}
char Move::promotion_piece_symbol() const noexcept
{
return '\0';
}
size_t Move::attack_index() const noexcept
{
return attack_index(movement());
}
size_t Move::attack_index(const Square_Difference& move) noexcept
{
constexpr auto xx = size_t(-1); // indicates invalid moves and should never be returned
constexpr size_t array_width = 15;
// file change
// -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7
static constexpr size_t indices[] = { 0, xx, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, xx, 2, // 7
xx, 0, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, 2, xx, // 6
xx, xx, 0, xx, xx, xx, xx, 1, xx, xx, xx, xx, 2, xx, xx, // 5
xx, xx, xx, 0, xx, xx, xx, 1, xx, xx, xx, 2, xx, xx, xx, // 4
xx, xx, xx, xx, 0, xx, xx, 1, xx, xx, 2, xx, xx, xx, xx, // 3
xx, xx, xx, xx, xx, 0, 15, 1, 8, 2, xx, xx, xx, xx, xx, // 2
xx, xx, xx, xx, xx, 14, 0, 1, 2, 9, xx, xx, xx, xx, xx, // 1
3, 3, 3, 3, 3, 3, 3, xx, 4, 4, 4, 4, 4, 4, 4, // 0 rank change
xx, xx, xx, xx, xx, 13, 5, 6, 7, 10, xx, xx, xx, xx, xx, // -1
xx, xx, xx, xx, xx, 5, 12, 6, 11, 7, xx, xx, xx, xx, xx, // -2
xx, xx, xx, xx, 5, xx, xx, 6, xx, xx, 7, xx, xx, xx, xx, // -3
xx, xx, xx, 5, xx, xx, xx, 6, xx, xx, xx, 7, xx, xx, xx, // -4
xx, xx, 5, xx, xx, xx, xx, 6, xx, xx, xx, xx, 7, xx, xx, // -5
xx, 5, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, 7, xx, // -6
5, xx, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, xx, 7}; // -7
assert(-7 <= move.rank_change && move.rank_change <= 7);
assert(-7 <= move.file_change && move.file_change <= 7);
const auto i = array_width*(7 - move.rank_change) + (move.file_change + 7);
assert(indices[i] < 16);
return indices[i];
}
Square_Difference Move::attack_direction_from_index(const size_t index) noexcept
{
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
static constexpr int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1, 1, 2, 2, 1, -1, -2, -2, -1};
static constexpr int dy[] = { 1, 1, 1, 0, 0, -1, -1, -1, 2, 1, -1, -2, -2, -1, 1, 2};
return {dx[index], dy[index]};
}
void Move::set_capturing_ability(const bool capturing_ability) noexcept
{
able_to_capture = capturing_ability;
}
void Move::mark_as_en_passant() noexcept
{
is_en_passant_move = true;
}
void Move::mark_as_castling() noexcept
{
is_castling_move = true;
}
| true |
2b3b423b03344ee3754f8da4e288d5e7072a024c | C++ | lucaschf/LP-2021 | /Lpas/Lpas/Lpas/MaquinaExecucao.cpp | UTF-8 | 7,509 | 2.796875 | 3 | [] | no_license | #include "MaquinaExecucao.h"
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include "Utils.h"
#include "Constants.h"
MaquinaExecucao::MaquinaExecucao()
{
numeroDeProgramas = 0;
registrador = 0;
}
bool MaquinaExecucao::carregar(Programa programa)
{
if ((numeroDeProgramas >= NUMERO_MAXIMO_DE_PROGRAMAS))
throw(MACHINE_MEMORY_FULL);
if (pesquisarPrograma(programa.getNome()) != ENDERECO_INVALIDO)
return false;
memoria[numeroDeProgramas++] = programa;
return true;
}
void MaquinaExecucao::replace(string old, Programa programa)
{
auto targetPosition = pesquisarPrograma(old);
if (targetPosition == ENDERECO_INVALIDO)
throw PROGRAM + " '" + old + "' " + NOT_LOADED;
if (pesquisarPrograma(programa.getNome()) != ENDERECO_INVALIDO)
throw THERE_IS_ALREADY_A_PROGRAM + " '" + programa.getNome() + "' " + LOADED;
memoria[targetPosition] = programa;
}
int MaquinaExecucao::getNumeroDeProgramas()
{
return numeroDeProgramas;
}
unsigned short MaquinaExecucao::pesquisarPrograma(string nome)
{
for (unsigned short i = 0; i < numeroDeProgramas; i++) {
if (memoria[i].getNome().compare(nome) == 0 || memoria[i].getNome().compare(nome + LPAS_EXTENSION) == 0)
return i;
}
return ENDERECO_INVALIDO;
}
Programa MaquinaExecucao::obterPrograma(unsigned short endereco)
{
if (endereco < numeroDeProgramas)
return memoria[endereco];
return Programa();
}
ErroExecucao MaquinaExecucao::executarPrograma(unsigned short endereco)
{
variablesMapping.clear();
allocatedVariables = 0;
Programa programa = obterPrograma(endereco);
cout << endl << WHITE_SPACES << PROGRAM << " '" << programa.getNome() << "' " << UP_AND_RUNNING << endl << endl;
if (programa.getNumeroDeInstrucoes() == 0) // nothing to do
{
cout << NO_INSTRUCTIONS << endl;
return ErroExecucao();
}
registrador = 0; // resets the recorder
currentLine = 0; // back to the first line of the program
while (currentLine < programa.getNumeroDeInstrucoes()) {
try {
string parameterizedInstruction = programa.obterInstrucao(currentLine);
auto error = ErroExecucao(parameterizedInstruction, programa.getNome(),
currentLine, Erro::INSTRUCAO_LPAS_INVALIDA);
// check if is a comment line meaning that is nothing to do
if (Utils::startsWith(Utils::trim(parameterizedInstruction), ";")) {
currentLine++;
continue;
}
int argsBegin = parameterizedInstruction.find_first_of(" ");
if (!Utils::contains(parameterizedInstruction, " ")) // pottentialy a non parameterized instruction
argsBegin = parameterizedInstruction.find_first_of(";");
auto instruction = static_cast<Instruction>(
obterCodigoInstrucao(parameterizedInstruction.substr(0, argsBegin)));
if (instruction == HALT) {
error.setErro(Erro::EXECUCAO_BEM_SUCEDIDA);
return error;
}
if (argsBegin != string::npos) { // args passed
unsigned short address = ENDERECO_INVALIDO;
int arg = 0;
auto err = retriveVariableAndLiteralFromArgs(
instruction,
extractArgs(parameterizedInstruction.substr(argsBegin + 1)),
address,
arg
);
if (err != Erro::EXECUCAO_BEM_SUCEDIDA)
{
error.setErro(err);
return error;
}
if (executarInstrucao(instruction, address, arg) == USHRT_MAX)
{
error.setErro(Erro::INSTRUCAO_LPAS_INVALIDA);
return error;
}
}
else // no argument given
{
error.setErro(Erro::ARGUMENTO_INSTRUCAO_LPAS_AUSENTE);
return error;
}
}
catch (...) {
throw "Failed to execute instruction at line: " + currentLine;
}
}
return ErroExecucao();
}
Erro MaquinaExecucao::retriveVariableAndLiteralFromArgs(Instruction instruction, vector<string> args,
unsigned short& address, int& param)
{
// number of maximum known arguments for an instruction in this case MOV has the greatest number of args (2)
const int maxArgsKnown = 2;
auto expectedArgs = requiredArgs(instruction);
// there are too many or too few arguments for an instruction or several instructions on the same line
if (args.size() != expectedArgs || args.size() > maxArgsKnown) {
return (args.size() > expectedArgs ? Erro::MUITAS_INSTRUCOES : Erro::ARGUMENTO_INSTRUCAO_LPAS_AUSENTE);
}
for (string argument : args) {
auto strArg = Utils::trim(argument);
if (isAcceptedVariableName(strArg)) // arg is a variable
{
auto it = variablesMapping.find(strArg);
if (it == variablesMapping.end())
{
if (variablesMapping.size() == NUMERO_MAXIMO_DE_VARIAVEIS)
{
return Erro::MUITAS_INSTRUCOES;
}
variablesMapping.insert(make_pair(strArg, allocatedVariables));
variaveis[allocatedVariables] = 0;
if (address == ENDERECO_INVALIDO)
address = allocatedVariables;
else
param = allocatedVariables;
allocatedVariables++;
}
else {
if (address == ENDERECO_INVALIDO)
address = it->second;
else
param = variaveis[it->second];
}
}
else { // arg is a literal
try {
param = stoi(strArg);
}
catch (...) {
return Erro::SIMBOLO_INVALIDO;
}
}
}
return Erro::EXECUCAO_BEM_SUCEDIDA;
}
ErroExecucao MaquinaExecucao::getErroExecucao()
{
return erroExecucao;
}
unsigned short MaquinaExecucao::obterCodigoInstrucao(string instrucao)
{
auto it = instructionCodes.find(instrucao);
if (it == instructionCodes.end())
return USHRT_MAX;
return it->second;
}
void MaquinaExecucao::definirErroExecucao(string nomePrograma, string instrucao, unsigned short linha, Erro erro)
{
erroExecucao = ErroExecucao(instrucao, nomePrograma, linha, erro);
}
unsigned short MaquinaExecucao::executarInstrucao(unsigned short codigoInstrucao,
unsigned short enderecoVariavel, int argumento)
{
currentLine++;
switch (codigoInstrucao)
{
case JUMP:
currentLine = argumento;
break;
case JPNEG:
if (registrador < 0)
currentLine = argumento;
break;
case JPZERO:
if (registrador == 0)
currentLine = argumento;
break;
case READ:
cout << WHITE_SPACES << VALUE << ": ";
cin >> variaveis[enderecoVariavel];
break;
case WRITE:
cout << WHITE_SPACES << variaveis[enderecoVariavel] << endl;
break;
case MOV:
variaveis[enderecoVariavel] = argumento;
break;
case LOAD:
registrador = variaveis[enderecoVariavel];
break;
case STORE:
variaveis[enderecoVariavel] = registrador;
break;
case ADD:
registrador += (enderecoVariavel != ENDERECO_INVALIDO ?
variaveis[enderecoVariavel] : argumento);
break;
case SUB:
registrador -= (enderecoVariavel != ENDERECO_INVALIDO ?
variaveis[enderecoVariavel] : argumento);
break;
case MUL:
registrador *= (enderecoVariavel != ENDERECO_INVALIDO ?
variaveis[enderecoVariavel] : argumento);
break;
case DIV:
registrador /= (enderecoVariavel != ENDERECO_INVALIDO ?
variaveis[enderecoVariavel] : argumento);
break;
case RDIV:
registrador = registrador % (enderecoVariavel != ENDERECO_INVALIDO ?
variaveis[enderecoVariavel] : argumento);
break;
case HALT:
break;
default:
return USHRT_MAX;
}
return codigoInstrucao;
}
vector<string> MaquinaExecucao::extractArgs(string instructionArgs)
{
auto noComments = instructionArgs.substr(0, instructionArgs.find_first_of(";"));
return Utils::tokenize(noComments, ',', true);
}
bool MaquinaExecucao::isAcceptedVariableName(string arg)
{
return !Utils::isInteger(arg) && Utils::isUppercase(arg);
}
size_t MaquinaExecucao::requiredArgs(Instruction instruction)
{
if (instruction == HALT)
return 0;
return instruction == Instruction::MOV ? 2 : 1;
} | true |
588f6140894bffc07d70262df4c7354a6327bc62 | C++ | thomaslandry1/ComplexVectors | /ComplexVector.cpp | UTF-8 | 3,119 | 3.078125 | 3 | [] | no_license | //
// Created by Thomas Landry on 5/17/17.
//
#include "ComplexVector.h"
#include <iostream>
#include <iomanip>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
const int PRECISION = 1;
const int WIDTH = 2;
ComplexVector::ComplexVector() {
}
ComplexVector::ComplexVector(double a, double b, double c, double d,
double e, double f, double g, double h)
: VectorParts_({ Complex(a, b), Complex(c, d),
Complex(e, f), Complex(g, h) }) {
}
ComplexVector::ComplexVector(const ComplexVector& copy)
: VectorParts_(copy.VectorParts_) {
}
ComplexVector::~ComplexVector() {
}
void ComplexVector::print() const {
auto& end = *(VectorParts_.rbegin());
cout << " <" << *this << " >\n";
}
void ComplexVector::computeSequence(int n) {
std::ofstream outFile("ComplexSequence.txt", std::ios::app);
// base case
if (n == 0) {
VectorParts_.push_back(Complex(1, 1));
}
//recursive sequence setup
Complex num(Areal_ * (n + 1), Bimag_ * (n + 1));
Complex den(Creal_, Dimag_ * ((n + 1) * (n + 1)));
Complex result = num / den * VectorParts_[n];
if (n != 5) {
VectorParts_.push_back(result);
computeSequence(n + 1);
} else {
outFile << "{" << *this << " } ";
outFile.close();
}
}
const ComplexVector operator+(const ComplexVector& lhs, const ComplexVector& rhs) {
std::vector<Complex>::const_iterator rhsIter = rhs.VectorParts_.begin();
ComplexVector newVector;
for (auto i : lhs.VectorParts_) {
Complex result;
newVector.VectorParts_.push_back(i + *rhsIter);
++rhsIter;
}
return newVector;
}
const ComplexVector operator-(const ComplexVector& lhs, const ComplexVector& rhs) {
std::vector<Complex>::const_iterator rhsIter = rhs.VectorParts_.begin();
ComplexVector newVector;
for (auto i : lhs.VectorParts_) {
Complex result;
newVector.VectorParts_.push_back(i - *rhsIter);
++rhsIter;
}
return newVector;
}
const ComplexVector operator*(const ComplexVector& lhs, const ComplexVector& rhs) {
std::vector<Complex>::const_iterator rhsIter = rhs.VectorParts_.begin();
ComplexVector newVector;
for (auto i : lhs.VectorParts_) {
Complex result;
newVector.VectorParts_.push_back(i * *rhsIter);
++rhsIter;
}
return newVector;
}
const ComplexVector operator/(const ComplexVector& lhs, const ComplexVector& rhs) {
std::vector<Complex>::const_iterator rhsIter = rhs.VectorParts_.begin();
ComplexVector newVector;
for (auto i : lhs.VectorParts_) {
Complex result;
newVector.VectorParts_.push_back(i / *rhsIter);
++rhsIter;
}
return newVector;
}
std::ostream& operator<<(std::ostream& os, const ComplexVector& rhs) {
//iterator to reverse beginning of vector
//needed because ranged based for loops unable to offer index of current
auto& end = *(rhs.VectorParts_.rbegin());
cout.setf(std::ios::fixed);
cout.precision(PRECISION);
for (auto& i : rhs.VectorParts_) {
os << setw(WIDTH) << i;
if (&i != &end) {
os << setw(WIDTH) << " , ";
} else {
os << "";
}
}
return os;
}
| true |
b12b598d86d0acf9e75028db69be81f928d0ddd8 | C++ | sirraghavgupta/cpp-data-structures-and-algorithms | /concepts/DP_reduceNumTo1.cpp | UTF-8 | 1,776 | 3.59375 | 4 | [] | no_license | /*##############################################################################
AUTHOR : RAGHAV GUPTA
DATE : 28 November 2019
AIM : find the minimum number of steps required to reduce a number to 1
operations permited are -
/ by 3
/ by 2
subtract 1
STATUS : !!! success !!!
##############################################################################*/
#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9; // infinity
int reduceNum_normal(int n){
// without memoization, normal recursion
// TC = O(3^n) - ver bad.
// Base case
if(n==1)
return 0;
// Rec Case
int q1=inf, q2=inf, q3=inf;
if(n%3 == 0)
q1 = 1 + reduceNum_normal(n/3);
if(n%2 == 0)
q2 = 1 + reduceNum_normal(n/2);
q3 = 1 + reduceNum_normal(n-1);
int ans = min(q1, min(q2, q3));
return ans;
}
int memo[10000];
int reduceNum_memoized(int n){
// TC = O(N)
// Base case
if(n==1)
return 0;
// avoid recomputation
if(memo[n] != -1)
return memo[n];
// Rec Case
int q1=inf, q2=inf, q3=inf;
if(n%3 == 0)
q1 = 1 + reduceNum_memoized(n/3);
if(n%2 == 0)
q2 = 1 + reduceNum_memoized(n/2);
q3 = 1 + reduceNum_memoized(n-1);
memo[n] = min(q1, min(q2, q3));
return memo[n];
}
int reduceNum_pureDP(int n){
// bottom up DP
// TC = O(N)
int dp[n+1];
dp[0] = 0;
dp[1] = 0;
dp[2] = 1;
dp[3] = 1;
for(int num = 4; num<=n; num++){
int q1=inf, q2=inf, q3=inf;
if(num%3==0)
q1 = 1+dp[num/3];
if(num%2==0)
q2 = 1+dp[num/2];
q3 = 1+dp[num-1];
dp[num] = min(q1, min(q2, q3));
}
return dp[n];
}
int main(){
int n;
cin>>n;
fill(memo, memo+n+1, -1); // initialise the usable part of array to -1 initially.
// cout<<reduceNum_normal(n)<<endl;
// cout<<reduceNum_memoized(n)<<endl;
cout<<reduceNum_pureDP(n)<<endl;
return 0;
}
| true |
d7b9717a646a59f41d9589bd2fac7c7bc4d4cf7c | C++ | Pacharoth/TP | /ex1.cpp | UTF-8 | 2,026 | 4.0625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Element{
int data;
Element *next;
};
struct List{
int n;
Element *head;
Element *tail;
};
//create empty list
List *createList(){
List *ls;
ls= new List();
ls->n =0;
ls->head=NULL;
ls->tail=NULL;
return ls;
}
//create function to insert all number to begin
void changeToBegin(List *ls,int newData);
//create display list
void displayList(List *l);
//add to end list
void endOfList(List *ls,int dataNew);
int main(){
List *l;
l =createList();
cout<<"\t\tFirst output:\n";
changeToBegin(l,7);
changeToBegin(l,1);
cout<<"\t\t";
displayList(l);
cout<<"\t\tSecond output:\n";
endOfList(l,0);
endOfList(l,4);
cout<<"\t\t";
displayList(l);
}
//create function to insert all number to begin
void changeToBegin(List *ls,int newData){
Element *e;
//create e is element
e = new Element();
//e data equal to parameter newdata
e->data =newData;
//e next is head of list
e->next=ls->head;
//connect list head to next element by pointer
ls->head=e;
if (ls->n==0)
{//if ls have n==0 so tail of list equal to e which is next elelement
ls->tail =e;
}
ls->n=ls->n+1;
}
//Display list
void displayList(List *l){
Element *tmp;
tmp =l->head;
while (tmp!=NULL)//run to null
{
//after display to data which store value
// it will go to next element to display next element
cout<<tmp->data<<" ";
tmp = tmp->next;
}
cout<<endl;
}
//add to end ofo list
void endOfList(List *ls,int dataNew){
Element *e;
e=new Element();
if (ls->n==0)
{
ls->head=e;
ls->tail=e;
}else
{
e->data = dataNew;//equal data
e->next = NULL;//next of element set null
ls->tail->next=e;//list tail go next until null
ls->tail = e;//the way it run to tail of list so the value of end is tail of list
ls->n=ls->n+1;
}
} | true |
6ecc8820d9add25cec6bdefdfa4ee0b1b2613897 | C++ | Zamidation/CSE4600_HW1 | /Part 2/pipe4.cpp | UTF-8 | 1,534 | 3.078125 | 3 | [] | no_license | //pipe4.cpp (data producer)
//To run code
//g++ pipe4.cpp -o pipe4
//g++ pipe5.cpp -o pipe5
// ./pipe4 "write message here."
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int data_processed;
int file_pipes[2];
char userinput[100]; //uninitialized bc we'll be getting user input
char buffer[BUFSIZ + 1];
pid_t fork_result;
strcpy(userinput, argv[1]); //copies the first argv[1] into userinput
for(int i = 2; i < argc; i++) //for loop to grab the other argv[i] in order to be able to send a message
{
strcat(userinput, " "); //to have a whitespace in between words
strcat(userinput, argv[i]); //the idea for this loop came from the youtube video https://youtu.be/aP1ijjeZc24
}
memset(buffer, '\0', sizeof(buffer));
if (pipe(file_pipes) == 0) { //creates pipe
fork_result = fork();
if (fork_result == (pid_t)-1) { //fork fails
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
if (fork_result == 0) { //child
sprintf(buffer, "%d", file_pipes[0]);
(void)execl("pipe5", "pipe5", buffer, (char *)0);
exit(EXIT_FAILURE);
}
else { //parent
data_processed = write(file_pipes[1], &userinput, strlen(userinput));
printf("%d - Sending message with %d bytes: %s\n", getpid(), data_processed, buffer);
}
}
exit(EXIT_SUCCESS);
}
| true |
29be40530b53a10064b4055a33e250e692baa216 | C++ | ellynhan/challenge100-codingtest-study | /hall_of_fame/c0np4nn4/boj/cpp/2_slv/slv5_4673/self_number.cpp | UTF-8 | 587 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int get_self_num(int a) {
int res = a;
while (a > 0) {
res += (a % 10);
a /= 10;
}
return res;
}
int main() {
int num_table[10001];
for (int i = 0; i < 10001; i++) {
num_table[i] = i;
}
for (int i = 1; i < 10001; i++) {
int t = i;
if (num_table[t] == -1)
continue;
while (get_self_num(t) < 10000) {
t = get_self_num(t);
num_table[t] = -1;
}
}
for (int i = 1; i < 10000; i++) {
if (num_table[i] != -1) {
cout << num_table[i] << endl;
}
}
return 0;
}
| true |
340de447df92509c4571e8b4704e2d6cc741395d | C++ | NoahNode/AlgorithmsLinkedList | /practical7/ArrayList.h | UTF-8 | 6,847 | 3.859375 | 4 | [] | no_license | /**
* ArrayList.h
*
* Generic Dynamic ArrayList based on array
* with advanced copy and equality operators
* @author Aiden McCaughey
* @email a.mccaughey@ulster.ac.uk
* @version 1.2
*/
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include "Array.h"
#include <exception>
#include <iostream>
template <class T>
class ArrayList {
public:
explicit ArrayList(int size=100);
ArrayList(const ArrayList<T> & other);
void operator=(const ArrayList<T> & other);
bool operator==(const ArrayList<T> & other) const;
bool operator!=(const ArrayList<T> & other) const;
void clear();
void add(const T & value);
void add(int pos, const T & value);
void remove(int pos);
void set(int pos, const T & value);
T get(int pos) const;
int find(const T & value) const;
int size() const;
bool isEmpty() const;
void print(std::ostream & os) const;
// Immutable List processing functions
ArrayList<T> reverse() const;
ArrayList<T> take(int n) const;
ArrayList<T> drop(int n) const;
ArrayList<T> concat(const ArrayList<T> & other) const;
ArrayList<T> mid(int start, int count) const;
private:
Array<T> data;
int count;
};
// --------------- ArrayList Implementation -----------------------
// Default Constructor
template <class T>
ArrayList<T>::ArrayList(int size) : data(size), count{ 0 } {}
// PostCondition: construct ArrayList as a duplicate of c
template <class T>
ArrayList<T>::ArrayList(const ArrayList<T> & other): data(other.data), count(other.count) {}
// PostCondition: assign c to ArrayList
template<class T>
void ArrayList<T>::operator=(const ArrayList<T> & other)
{
data = other.data;
count = other.count;
}
// PostCondition: returns true if ArrayLists are identical, false otherwise
template <class T>
bool ArrayList<T>::operator==(const ArrayList<T> & other) const
{
bool same=true;
if (size() != other.size()) {
same = false;
}
for(int i=0; same && i<size(); i++) {
if (get(i) != other.get(i)) {
same = false;
}
}
return same;
}
// PostCondition: returns true if ArrayLists are not equal, false otherwise
template <class T>
bool ArrayList<T>::operator!=(const ArrayList<T> & other) const
{
return !operator== (other);
}
// PostCondition: return length of ArrayList
template<class T>
int ArrayList<T>::size() const {
return count;
}
// PreCondition: pos is a valid ArrayList position and ArrayList is not full
// PostCondition: inserts element value at specified position in ArrayList
template<class T>
void ArrayList<T>::add(int pos, const T & value) {
if (pos < 0 || pos > count) {
throw std::out_of_range("ArrayList: invalid postion: " + std::to_string(pos));
}
// either throw execption if no room left in list
//if (count >= data.length())
// throw std::overflow_error("ArrayList: overflow");
// or increase size of ArrayList if required
if (count >= data.length()) {
data.resize(data.length() * 2);
}
// make room for new element
for (int i = count; i > pos; i--) {
data[i] = data[i - 1];
}
// insert element in position
data[pos] = value;
// increment number of items in ArrayList
count++;
}
// PreCondition: ArrayList is not full
// PostCondition: value added to end of ArrayList
template<class T>
void ArrayList<T>::add(const T & value) {
add(size(), value);
}
// PreCondition: pos is a valid ArrayList position
// PostCondition: remove element at specified position in ArrayList
template<class T>
void ArrayList<T>::remove(int pos) {
if (pos < 0 || pos >= count) {
throw std::out_of_range("ArrayList: invalid postion: " + std::to_string(pos));
}
// fill gap by moving elements down
for (int i = pos; i < count - 1; i++) {
data[i] = data[i + 1];
}
count--; // decrease length
}
// PreCondition: pos is a valid ArrayList position
// PostCondition: retrieves element at specified position in ArrayList
template<class T>
T ArrayList<T>::get(int pos) const {
if (pos < 0 || pos >= count) {
throw std::out_of_range("ArrayList: invalid postion: " + std::to_string(pos));
}
return data[pos];
}
// PreCondition: pos is a valid ArrayList position
// PostCondition: updates element at specified position in ArrayList
template<class T>
void ArrayList<T>::set(int pos, const T & value) {
if (pos < 0 || pos >= count) {
throw std::out_of_range("ArrayList: invalid postion: " + std::to_string(pos));
}
data[pos] = value;
}
// PostCondition: returns postion of e in ArrayList or -1 if not found
template<class T>
int ArrayList<T>::find(const T & value) const {
for(int i=0; i<size(); i++) {
if (get(i) == value) {
return i;
}
}
return -1;
}
// PostCondition: prints contents of ArrayList to standard output
template<class T>
void ArrayList<T>::print(std::ostream & os) const {
os << "[ ";
for(int i = 0; i < size(); i++) {
os << get(i) << " ";
}
os << "]";
}
// PostCondition: ArrayList is emptied len == 0;
template<class T>
void ArrayList<T>::clear() {
count = 0; // reset length to zero
}
//PostCondition: returns length of ArrayList
template<class T>
bool ArrayList<T>::isEmpty() const {
return (count == 0);
}
template<class T>
ArrayList<T> ArrayList<T>::reverse() const
{
ArrayList<T> r(size());
for (int i = size()-1; i >= 0; i--) {
r.add(get(i));
}
return r;
}
template<class T>
ArrayList<T> ArrayList<T>::take(int n) const
{
if (n < 0 || n > size()) {
throw std::out_of_range("ArrayList: invalid number of elements to take: " + std::to_string(n));
}
ArrayList<T> t(n);
for (int i = 0; i < n; i++) {
t.add(get(i));
}
return t;
}
template<class T>
ArrayList<T> ArrayList<T>::drop(int n) const
{
if (n < 0 || n > size()) {
throw std::out_of_range("ArrayList: invalid number of elements to drop: " + std::to_string(n));
}
// return mid(n, size()-n); // drop(2) [1,2,3]
ArrayList<T> d(size()-n);
for (int i = n; i < size(); i++) {
d.add(get(i));
}
return d;
}
template<class T>
ArrayList<T> ArrayList<T>::concat(const ArrayList<T> & other) const
{
ArrayList<T> n(size() + other.size());
for (int i = 0; i < size(); i++) {
n.add(get(i));
}
for (int i = 0; i < other.size(); i++) {
n.add(other.get(i));
}
return n;
}
// PreCondition: start >= 0 && start < size() && count <= (size() - start)
template<class T>
ArrayList<T> ArrayList<T>::mid(int start, int count) const
{
if (start < 0 || start >= size() || count > size() - start) {
throw std::out_of_range("ArrayList: mid(" + std::to_string(start) + "," + std::to_string(count) + ") invalid");
}
//ArrayList<T> m(count - start);
//for (int i = start; i < start + count; i++) {
// m.add(get(i));
//}
//return m;
return drop(start).take(count);
}
// PreCondition: None
// PostCondition: overload << operator to output ArrayList on ostream
template <class T>
std::ostream& operator <<(std::ostream& output, const ArrayList<T>& l) {
l.print(output);
return output; // for multiple << operators.
}
#endif /* ArrayList_H*/ | true |
f035272c61391feab4ab6a962752ade93b69575f | C++ | yangjietadie/db | /sqlite3/sqlite3query.hpp | UTF-8 | 955 | 2.65625 | 3 | [] | no_license | /*
** Copyright (C) 2015 Wang Yaofu
** All rights reserved.
**
**Author:Wang Yaofu voipman@qq.com
**Description: The header file of class Sqlite3Query.
*/
#pragma once
#include <vector>
#include <string>
#include "sqlite3.h"
// START_NAMESPACE
class Sqlite3Query {
public:
enum Status {
OK,
FAILED,
NORESULT
};
Sqlite3Query();
Sqlite3Query(const std::string& dbPath);
int open(const std::string& dbPath);
virtual ~Sqlite3Query();
int start_transaction();
int rollback();
int commit();
// for CREATE,UPDATE,DELETE,SELECT SQL etc.
int execute(const std::string& query, bool isSelect = false);
// for SELECT SQL.
int select(const std::string& query);
int next(std::vector<char*>& row);
std::string getDbPath();
sqlite3* getDb();
protected:
sqlite3* db_;
std::string dbPath_;
char** results_;
int rows_;
int columns_;
int rowOffset_;
};
// END_NAMESPACE
| true |
68b115f87e30f565cb02e04d3fa0f165081c3451 | C++ | Bltzz/CPP_300 | /cpp_d13_2019/ex04/Toy.cpp | UTF-8 | 1,184 | 3.046875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** cpp_pool
** File description:
** Toy.cpp
*/
#include "Toy.hpp"
Toy::Toy() : type(BASIC_TOY), name("toy"), pic(Picture()) {}
Toy::Toy(ToyType const type, std::string name, std::string const pic) : type(type), name(name), pic(Picture(pic)) {}
Toy::Toy(Toy const &t) : name(t.name), type(t.type), pic(t.pic) {}
Toy::~Toy(){}
void Toy::setName(std::string const &name){
this->name = name;
}
bool Toy::setAscii(std::string const &file){
return (this->pic.getPictureFromFile(file));
}
Toy::ToyType Toy::getType() const{
return this->type;
}
std::string Toy::getName() const{
return this->name;
}
std::string Toy::getAscii() const{
return this->getPicture().getData();
}
void Toy::speak(std::string statement){
std::cout << this->getName() << " \"" << statement << "\"" << std::endl;
}
Toy &Toy::operator<<(std::string newStr){
this->pic.setData(newStr);
return *this;
}
std::ostream &operator<<(std::ostream& os, Toy const &t){
os << t.getName() << "\n" << t.getAscii() << std::endl;
return os;
}
Toy &Toy::operator=(const Toy &t){
this->name = t.getName();
this->pic = t.pic;
return *this;
} | true |
96592b9d8e901dce624ff4dc0ce30e80aff4fd1a | C++ | samumartinf/Cplusplus | /Second Assignment/Assignment2.cpp | UTF-8 | 4,721 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <sstream>
#include <vector>
#include <fstream>
using std::vector;
using namespace std;
//Classes
class DNA_DB{
public:
string fileName;
DNA_DB();
string getFileName(){
return fileName;
}
void setFileName(string name){
fileName = name;
}
};
DNA_DB::DNA_DB(){ //constructor for the class object
return;
};
//Functions used
std::vector<DNA_DB> loadFiles(std::vector<DNA_DB> dna_db);
void firstMenu(vector<DNA_DB> dna_db);
bool secondMenu(vector<DNA_DB> dna_db, int fileNum);
//Main Function
int main(){
vector<DNA_DB> dna_db;
dna_db.clear(); //Clear the vector before use
dna_db = loadFiles(dna_db);
firstMenu(dna_db);
return 0;
}
//Load files function: fills the vector<DNA_DB> with the names of the files
vector<DNA_DB> loadFiles(vector<DNA_DB> dna_db){
string fileNames; //string to save the string with coma separated input
cout << "DNA Sequence Database Software\nSpecify the name of DNA sequence file names you would like to load. For multiple files, add a \",\" between each file name. \n>";
getline(cin,fileNames,'\n') ; //Get the whole input from the user and save it as fileNames
//cutting the string into separated names
istringstream ssFileNames(fileNames); //Creating a istringstream for the cutting of the sring
string tempString;
int i = 0; //initialize counter
while(getline(ssFileNames, tempString, ',')) {
if (tempString[0] == ' '){ //Remove the first space (if it exists) between the coma and the file name
tempString = tempString.substr(1, tempString.size()-1);
}
dna_db.push_back(DNA_DB()); //initialising the class object
dna_db[i].setFileName(tempString); //set name for the object
std::cout << dna_db[i].fileName << '\n';
i++;
}
return dna_db;
}
//Display the menu and return the option chosen
void firstMenu(vector<DNA_DB> dna_db){
bool stayInMenu = true;
char answer;
do{
cout << "Select one of the following options:" << '\n';
cout << " (S) Summary of the statistics of the DNA database" << '\n';
for (size_t i = 0; i < dna_db.size(); i++) {
cout << " (" << i+1 << ") Analyse " << dna_db[i].getFileName() << '\n';
}
cout << " (Q) Quit" << '\n';
cin >> answer;
switch (answer) {
case 'q':
case 'Q':
stayInMenu = false;
break;
case 's':
case 'S':
//Call function to summarize the data
cout << "summarize selected" << '\n'; //Debugging purposes
break;
default:
//Loop through the number of databases loaded, if not found, return the user to the first menu
int selectedFile = (int)answer - 49; //Convert the character to the integer we expect
std::cout << "selectedFile = " << selectedFile << '\n';
if ((selectedFile <= dna_db.size()) && (selectedFile >= 0)){ //
cout << "jump to second menu using database: " << dna_db[selectedFile].getFileName() << '\n'; //this is not being loaded
ifstream selectedFastaFile;
selectedFastaFile.open()
stayInMenu = secondMenu(dna_db, selectedFile);
break;
}
}
} while(stayInMenu);
//An assumption of an input of only one character is made
}
bool secondMenu(vector<DNA_DB> dna_db, int fileNum){
char answer;
bool quit = false;
bool stayInMenu = true;
do {
cout << "Select one of the following options:" << '\n';
cout << " (H) Help\n (S) Summary statistics of the DNA sequence" << '\n';
cout << " (1) Analyse gap region\n (2) Analyse code region\n (3) Analyse base pair range" << '\n';
cout << " (4) Find DNA sequence by manual input\n (5) Find DNA sequence by file input\n (R) Return to previous menu" << '\n';
cout << " (Q) Quit" << '\n';
cin >> answer;
switch (answer) {
case 'H':
case 'h':
//print reference
cout << "Code Base Description\nG Guanine\nA Adenine\nT Thymine (Uracil in RNA)\nC Cytosine\nR Purine (A or G)\nY Pyrimidine (C or T or U)\nM Amino (A or C)\nK Ketone (G or T)\nS Strong interaction (C or G)\nW Weak interaction (A or T)\nH Not-G (A or C or T) H follows G in the alphabet\nB Not-A (C or G or T) B follows A in the alphabet\nV Not-T (not-U) (A or C or G) V follows U in the alphabet\nD Not-C (A or G or T) D follows C in the alphabet\nN Any(A or C or G or T)\n\n" << '\n';
//Maybe implement something to wait for user input before printing again the menu?
break;
case 'S':
case 's':
summarizeSequence();
}
selectedFastaFile.close();
} while(stayInMenu);
return quit;
}
void summarizeSequence(){
string str;
cout << getline(selectedFastaFile, str, '\n') << '\n';
}
| true |
fab31c9021dbc75f812f272ad73971f3da0998e5 | C++ | Dhruv-m-Shah/Competitive-Programming | /DMOJ/Stalactities/Stalactities.cpp | UTF-8 | 1,682 | 2.515625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long BIT[251][251][251];
long long ASIZE, num1, num2, num3, num4, num5, i, j, q, x1, y1, z1, x2, y2, z2;
char hold;
void update(long long x, long long y,long long z, long long val)
{
for(long long i = x; i<=ASIZE;i+=(i&-i))
{
for(long long j = y; j<=ASIZE;j+=(j&-j))
{
for(long long k = z; k<=ASIZE;k+=(k&-k))
{
BIT[i][j][k]+=val;
}
}
}
}
long long query(long long x, long long y, long long z)
{
long long sum = 0;
for(long long i = x;i>0;i-=(i&-i))
{
for(long long j = y;j>0;j-=(j&-j))
{
for(long long k = z; k>0; k-=(k&-k))
{
sum+=BIT[i][j][k];
}
}
}
return sum;
}
int main()
{
cin.sync_with_stdio(0);
cin.tie(0);
cin>>ASIZE;
cin>>q;
long long finalans = 0;
for(long long u = 0; u<q; u++)
{
cin>>hold;
if (hold == 'C')
{
cin>>num1>>num2>>num3>>num4;
update(num1, num2, num3,-1*(query(num1, num2, num3)-query(num1-1, num2,num3)-query(num1, num2-1, num3) + query(num1-1, num2-1, num3)-query(num1, num2, num3-1)+query(num1-1, num2, num3-1)+query(num1, num2-1, num3-1)-query(num1-1, num2-1, num3-1)));
update(num1, num2, num3, num4);
}
if (hold == 'S')
{
cin>>x1>>y1>>z1>>x2>>y2>>z2;
finalans += query(x2, y2, z2)-query(x1-1, y2,z2)-query(x2, y1-1, z2) + query(x1-1, y1-1, z2)-query(x2, y2, z1-1)+query(x1-1, y2, z1-1)+query(x2, y1-1, z1-1)-query(x1-1, y1-1, z1-1);
}
}
cout<<finalans<<endl;
}
| true |
12c63d9ab609edbd1b6b89114d6df1c3aabbf51f | C++ | Zuprex/CS103-Parameters | /CS103-Parameters.cpp | UTF-8 | 213 | 2.765625 | 3 | [] | no_license |
#include <iostream>
int minimumNum(int Array[], int max ) {
int minValue = 100;
}
int main()
{
const int maxCap = 5;
int value[maxCap] = { 1,2,3,4,5 };
minimumNum(value, maxCap);
} | true |
4a42d1c78669bc2348cb0df17cfe9ad578fb11d2 | C++ | sbhonde1/apex_simulator | /lsq_entry.cpp | UTF-8 | 3,297 | 2.59375 | 3 | [] | no_license | //
// @author: sonu
// @date: 12/10/18.
//
#include "lsq_entry.h"
#include "helper.h"
using namespace std;
int LSQ_entry::getM_index() const {
return m_index;
}
LSQ_entry::LSQ_entry(int which_ins, int dest_reg, int store_reg,
int store_reg_value, int is_store_reg_valid) {
this->m_which_ins = which_ins;
this->m_dest_reg = dest_reg;
this->m_store_reg = store_reg;
this->m_store_reg_value = store_reg_value;
this->m_is_register_valid = is_store_reg_valid;
}
void LSQ_entry::setM_index(int m_index) {
LSQ_entry::m_index = m_index;
}
int LSQ_entry::getM_status() const {
return m_status;
}
void LSQ_entry::setM_status(int m_status) {
LSQ_entry::m_status = m_status;
}
int LSQ_entry::getM_which_ins() const {
return m_which_ins;
}
void LSQ_entry::setM_which_ins(int m_which_ins) {
LSQ_entry::m_which_ins = m_which_ins;
}
int LSQ_entry::getM_memory_addr() const {
return m_memory_addr;
}
void LSQ_entry::setM_memory_addr(int m_memory_addr) {
LSQ_entry::m_memory_addr = m_memory_addr;
}
bool LSQ_entry::getM_is_memory_addr_valid() const {
return m_is_memory_addr_valid;
}
void LSQ_entry::setM_is_memory_addr_valid(int m_is_memory_addr_valid) {
LSQ_entry::m_is_memory_addr_valid = m_is_memory_addr_valid;
}
int LSQ_entry::getM_dest_reg() const {
return m_dest_reg;
}
void LSQ_entry::setM_dest_reg(int m_dest_reg) {
LSQ_entry::m_dest_reg = m_dest_reg;
}
int LSQ_entry::getM_store_reg() const {
return m_store_reg;
}
void LSQ_entry::setM_store_reg(int m_store_reg) {
LSQ_entry::m_store_reg = m_store_reg;
}
bool LSQ_entry::getM_store_src1_data_valid() const {
return m_is_register_valid;
}
void LSQ_entry::setM_store_src1_data_valid(int m_is_register_valid) {
LSQ_entry::m_is_register_valid = m_is_register_valid;
}
int LSQ_entry::getM_store_reg_value() const {
return m_store_reg_value;
}
void LSQ_entry::setM_store_reg_value(int m_store_reg_value) {
LSQ_entry::m_store_reg_value = m_store_reg_value;
}
LSQ_entry &LSQ_entry::operator=(const LSQ_entry &lsq) {
if (this == &lsq) {
return *this;
}
allocated = lsq.allocated;
m_index = lsq.m_index;
m_pc = lsq.m_pc;
m_status = lsq.m_status;
m_which_ins = lsq.m_which_ins;
m_memory_addr = lsq.m_memory_addr;
m_is_memory_addr_valid = lsq.m_is_memory_addr_valid;
m_dest_reg = lsq.m_dest_reg;
m_store_reg = lsq.m_store_reg;
m_is_register_valid = lsq.m_is_register_valid;
m_store_reg_value = lsq.m_store_reg_value;
CFID = lsq.CFID;
return *this;
}
ostream& operator<<(ostream& out, const LSQ_entry* lsq) {
out << "m_index: " << lsq->getM_index() << endl;
out << "m_pc: " << lsq->getM_pc() << endl;
out << "m_status: " << lsq->getM_status() << endl;
out << "m_which_ins: " << lsq->getM_which_ins() << endl;
out << "m_memory_addr: " << lsq->getM_memory_addr() << endl;
out << "m_is_memory_addr_valid: " << lsq->getM_is_memory_addr_valid()
<< endl;
out << "m_dest_reg: " << lsq->getM_dest_reg() << endl;
out << "m_store_reg: " << lsq->getM_store_reg() << endl;
out << "m_is_register_valid: " << lsq->getM_store_src1_data_valid() << endl;
out << "m_store_reg_value: " << lsq->getM_store_reg_value() << endl;
out << "m_store_reg_value: " << lsq->CFID << endl;
return out;
}
int LSQ_entry::getM_pc() const {
return m_pc;
}
void LSQ_entry::setM_pc(int m_pc) {
LSQ_entry::m_pc = m_pc;
}
| true |
558a0412a90ddfb0fe8583033f32bf58b75d4b33 | C++ | misch-da/roof | /game/gamepanel.cpp | UTF-8 | 2,298 | 2.53125 | 3 | [] | no_license | #include "gamepanel.h"
#include "../game/objects/bulletbehavior.h"
GamePanel::GamePanel(QWidget *parent) : QWidget(parent)
{
health_txt.setText("health:");
health_txt.setAlignment(Qt::AlignRight);
health_count.setText("--");
health_count.setAlignment(Qt::AlignLeft);
weapon_txt.setText("weapon:");
weapon_txt.setAlignment(Qt::AlignRight);
weapon_count.setText("pistol");
weapon_count.setAlignment(Qt::AlignLeft);
ammunition_txt.setText("ammunition:");
ammunition_txt.setAlignment(Qt::AlignRight);
ammunition_count.setText("--");
ammunition_count.setAlignment(Qt::AlignLeft);
level_txt.setText("level:");
level_txt.setAlignment(Qt::AlignRight);
level_count.setText("--");
level_count.setAlignment(Qt::AlignLeft);
score_txt.setText("score:");
score_txt.setAlignment(Qt::AlignRight);
score_count.setText("--");
score_count.setAlignment(Qt::AlignLeft);
layout.setMargin(0);
layout.setSpacing(0);
layout.addWidget(&health_txt);
layout.addWidget(&health_count);
layout.addWidget(&weapon_txt);
layout.addWidget(&weapon_count);
layout.addWidget(&ammunition_txt);
layout.addWidget(&ammunition_count);
layout.addWidget(&level_txt);
layout.addWidget(&level_count);
layout.addWidget(&score_txt);
layout.addWidget(&score_count);
setLayout(&layout);
show();
}
void GamePanel::setParam(const DataEngine data)
{
QString str;
str.setNum(data.my->getHealth());
health_count.setText(str);
str.clear();
switch(data.my->getWeapon()){
case PISTOL:
weapon_count.setText("pistol");
break;
case UZI:
weapon_count.setText("uzi");
break;
case ROCKET:
weapon_count.setText("rocket");
break;
case WALL_WEAPON:
weapon_count.setText("wall");
break;
default:
break;
}
BulletBehavior * weapon = *data.my->my_weapon;
str.setNum(weapon->getAmmunition());
if(weapon->getWeapon() == PISTOL){
ammunition_count.setText("--");
}
else{
ammunition_count.setText(str);
}
str.clear();
str.setNum(data.level + 1);
level_count.setText(str);
str.clear();
str.setNum(data.score);
score_count.setText(str);
str.clear();
}
| true |
68b730e2263c075a41251373bc3b1377e20bdc7a | C++ | CedricGuillemet/Shatter | /Shatter.cpp | UTF-8 | 20,018 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "Shatter.h"
#include <math.h>
#include <float.h>
#include <assert.h>
#include <memory.h>
struct Vec4
{
public:
Vec4(const Vec4& other) : x(other.x), y(other.y), z(other.z), w(other.w)
{
}
Vec4()
{
}
Vec4(float _x, float _y, float _z = 0.f, float _w = 0.f) : x(_x), y(_y), z(_z), w(_w)
{
}
Vec4(int _x, int _y, int _z = 0, int _w = 0) : x((float)_x), y((float)_y), z((float)_z), w((float)_w)
{
}
Vec4(float v) : x(v), y(v), z(v), w(v)
{
}
void Lerp(const Vec4& v, float t)
{
x += (v.x - x) * t;
y += (v.y - y) * t;
z += (v.z - z) * t;
w += (v.w - w) * t;
}
void LerpColor(const Vec4& v, float t)
{
for (int i = 0; i < 4; i++)
(*this)[i] = sqrtf(((*this)[i] * (*this)[i]) * (1.f - t) + (v[i] * v[i]) * (t));
}
void Lerp(const Vec4& v, const Vec4& v2, float t)
{
*this = v;
Lerp(v2, t);
}
inline void Set(float v)
{
x = y = z = w = v;
}
inline void Set(float _x, float _y, float _z = 0.f, float _w = 0.f)
{
x = _x;
y = _y;
z = _z;
w = _w;
}
inline Vec4& operator-=(const Vec4& v)
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
return *this;
}
inline Vec4& operator+=(const Vec4& v)
{
x += v.x;
y += v.y;
z += v.z;
w += v.w;
return *this;
}
inline Vec4& operator*=(const Vec4& v)
{
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
return *this;
}
inline Vec4& operator*=(float v)
{
x *= v;
y *= v;
z *= v;
w *= v;
return *this;
}
inline Vec4 operator*(float f) const;
inline Vec4 operator-() const;
inline Vec4 operator-(const Vec4& v) const;
inline Vec4 operator+(const Vec4& v) const;
inline Vec4 operator*(const Vec4& v) const;
inline const Vec4& operator+() const
{
return (*this);
}
inline float Length() const
{
return sqrtf(x * x + y * y + z * z);
};
inline float LengthSq() const
{
return (x * x + y * y + z * z);
};
inline Vec4 Normalize()
{
(*this) *= (1.f / Length() + FLT_EPSILON);
return (*this);
}
inline Vec4 Normalize(const Vec4& v)
{
this->Set(v.x, v.y, v.z, v.w);
this->Normalize();
return (*this);
}
inline int LongestAxis() const
{
int res = 0;
res = (fabsf((*this)[1]) > fabsf((*this)[res])) ? 1 : res;
res = (fabsf((*this)[2]) > fabsf((*this)[res])) ? 2 : res;
return res;
}
inline void Cross(const Vec4& v)
{
Vec4 res;
res.x = y * v.z - z * v.y;
res.y = z * v.x - x * v.z;
res.z = x * v.y - y * v.x;
x = res.x;
y = res.y;
z = res.z;
w = 0.f;
}
inline void Cross(const Vec4& v1, const Vec4& v2)
{
x = v1.y * v2.z - v1.z * v2.y;
y = v1.z * v2.x - v1.x * v2.z;
z = v1.x * v2.y - v1.y * v2.x;
w = 0.f;
}
inline float Dot(const Vec4& v) const
{
return (x * v.x) + (y * v.y) + (z * v.z) + (w * v.w);
}
void IsMaxOf(const Vec4& v)
{
x = (v.x > x) ? v.x : x;
y = (v.y > y) ? v.y : y;
z = (v.z > z) ? v.z : z;
w = (v.w > w) ? v.z : w;
}
void IsMinOf(const Vec4& v)
{
x = (v.x > x) ? x : v.x;
y = (v.y > y) ? y : v.y;
z = (v.z > z) ? z : v.z;
w = (v.w > w) ? z : v.w;
}
bool IsInside(const Vec4& min, const Vec4& max) const
{
if (min.x > x || max.x < x || min.y > y || max.y < y || min.z > z || max.z < z)
return false;
return true;
}
Vec4 Symetrical(const Vec4& v) const
{
Vec4 res;
float dist = SignedDistanceTo(v);
res = v;
res -= (*this) * dist * 2.f;
return res;
}
/*void transform(const Mat4x4& matrix);
void transform(const Vec4 & s, const Mat4x4& matrix);
*/
//void TransformVector(const Mat4x4& matrix);
//void TransformPoint(const Mat4x4& matrix);
/*
void TransformVector(const Vec4& v, const Mat4x4& matrix)
{
(*this) = v;
this->TransformVector(matrix);
}
void TransformPoint(const Vec4& v, const Mat4x4& matrix)
{
(*this) = v;
this->TransformPoint(matrix);
}
*/
// quaternion slerp
// void slerp(const Vec4 &q1, const Vec4 &q2, float t );
inline float SignedDistanceTo(const Vec4& point) const;
float& operator[](size_t index)
{
return ((float*)&x)[index];
}
const float& operator[](size_t index) const
{
return ((float*)&x)[index];
}
float x, y, z, w;
};
inline Vec4 Vec4::operator*(float f) const
{
return Vec4(x * f, y * f, z * f, w * f);
}
inline Vec4 Vec4::operator-() const
{
return Vec4(-x, -y, -z, -w);
}
inline Vec4 Vec4::operator-(const Vec4& v) const
{
return Vec4(x - v.x, y - v.y, z - v.z, w - v.w);
}
inline Vec4 Vec4::operator+(const Vec4& v) const
{
return Vec4(x + v.x, y + v.y, z + v.z, w + v.w);
}
inline Vec4 Vec4::operator*(const Vec4& v) const
{
return Vec4(x * v.x, y * v.y, z * v.z, w * v.w);
}
inline float Vec4::SignedDistanceTo(const Vec4& point) const
{
return (point.Dot(Vec4(x, y, z))) - w;
}
inline Vec4 Normalized(const Vec4& v)
{
Vec4 res;
res = v;
res.Normalize();
return res;
}
inline Vec4 Cross(const Vec4& v1, const Vec4& v2)
{
Vec4 res;
res.x = v1.y * v2.z - v1.z * v2.y;
res.y = v1.z * v2.x - v1.x * v2.z;
res.z = v1.x * v2.y - v1.y * v2.x;
res.w = 0.f;
return res;
}
inline Vec3 Cross(const Vec3& v1, const Vec3& v2)
{
Vec3 res;
res.x = v1.y * v2.z - v1.z * v2.y;
res.y = v1.z * v2.x - v1.x * v2.z;
res.z = v1.x * v2.y - v1.y * v2.x;
return res;
}
inline float Dot(const Vec4& v1, const Vec4& v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
Vec4 BuildPlan(const Vec4& p_point1, const Vec4& p_normal)
{
Vec4 normal, res;
normal.Normalize(p_normal);
res.w = normal.Dot(p_point1);
res.x = normal.x;
res.y = normal.y;
res.z = normal.z;
return res;
}
Vec3 Lerp(const Vec3& A, const Vec3& B, float t)
{
return {
A.x + (B.x - A.x) * t,
A.y + (B.y - A.y) * t,
A.z + (B.z - A.z) * t
};
}
float SquaredDistance(const Vec3& A, const Vec3& B)
{
return (A.x - B.x) * (A.x - B.x) +
(A.y - B.y) * (A.y - B.y) +
(A.z - B.z) * (A.z - B.z);
}
Vec3 NormDirection(const Vec3& A, const Vec3& B)
{
Vec3 dir = {
B.x - A.x,
B.y - A.y,
B.z - A.z
};
float invLength = 1.f / sqrtf(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z);
dir.x *= invLength;
dir.y *= invLength;
dir.z *= invLength;
return dir;
}
Vec3 Normalized(const Vec3& vector)
{
Vec3 dir = vector;
float invLength = 1.f / sqrtf(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z);
dir.x *= invLength;
dir.y *= invLength;
dir.z *= invLength;
return dir;
}
Vec3 TriangleNormal(const Vec3 pos[3])
{
Vec3 dirA = NormDirection(pos[0], pos[1]);
Vec3 dirB = NormDirection(pos[0], pos[2]);
Vec3 norm = Normalized(Cross(dirA, dirB));
return norm;
}
float Dot(const Vec3& A, const Vec3& B)
{
return A.x * B.x + A.y * B.y + A.z * B.z;
}
uint16_t scratchIndexA[65536];
Vec3 scratchPosA[65536];
uint16_t scratchIndexB[65536];
Vec3 scratchPosB[65536];
template<typename T> void Swap(T& A, T& B)
{
T temp{ A };
A = B;
B = temp;
}
void ComputeBBox(const Vec3* positions, size_t positionCount, Vec3& bbMin, Vec3& bbMax)
{
bbMin = { FLT_MAX, FLT_MAX, FLT_MAX };
bbMax = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
for (size_t i = 0; i < positionCount; i++)
{
const Vec3 position = positions[i];
bbMin.x = (bbMin.x < position.x) ? bbMin.x : position.x;
bbMin.y = (bbMin.y < position.y) ? bbMin.y : position.y;
bbMin.z = (bbMin.z < position.z) ? bbMin.z : position.z;
bbMax.x = (bbMax.x > position.x) ? bbMax.x : position.x;
bbMax.y = (bbMax.y > position.y) ? bbMax.y : position.y;
bbMax.z = (bbMax.z > position.z) ? bbMax.z : position.z;
}
}
template<int count>uint8_t GetSides(const Vec3* pos, const Vec4& plan, float* distances, int& onPlanCount, int* onPlanIndex )
{
onPlanCount = 0;
uint8_t ret = 0;
for (int i = 0; i < count; i++)
{
distances[i] = plan.SignedDistanceTo(Vec4(pos[i].x, pos[i].y, pos[i].z));
}
// get dominant sign
int positive = 0;
int negative = 0;
for (int i = 0; i < count; i++)
{
if (distances[i] > FLT_EPSILON)
{
positive ++;
}
if (distances[i] < -FLT_EPSILON)
{
negative ++;
}
}
for (int i = 0; i < count; i++)
{
if (fabsf(distances[i]) < FLT_EPSILON)
{
distances[i] = FLT_EPSILON * ((positive>negative) ? 1.f : -1.f);
onPlanIndex[onPlanCount] = i;
onPlanCount ++;
}
}
assert(onPlanCount != 3); // TODO : handle case all on plane
for (int i = 0; i < count; i++)
{
ret |= (distances[i] > 0.f) ? (1 << i) : 0;
}
return ret;
}
void SortSegments(std::vector<Segment>& segments, size_t currentIndex, size_t& sortedSegmentIndex, size_t* sortedSegments, bool* sortedSegmentUsed)
{
Vec3 startPosA = segments[currentIndex].mA;
Vec3 endPosA = segments[currentIndex].mB;
float bestSqDistance = FLT_MAX;
int bestIndex = -1;
for (size_t index = 0; index < segments.size(); index++)
{
if (index == currentIndex || sortedSegmentUsed[index])
{
continue;
}
Vec3 startPosB = segments[index].mA;
Vec3 endPosB = segments[index].mB;
float sqDistance = SquaredDistance(endPosA, startPosB);
if (sqDistance < bestSqDistance)
{
bestSqDistance = sqDistance;
bestIndex = int(index);
}
}
if (bestIndex>0)
{
sortedSegments[sortedSegmentIndex++] = bestIndex;
sortedSegmentUsed[bestIndex] = true;
SortSegments(segments, bestIndex, sortedSegmentIndex, sortedSegments, sortedSegmentUsed);
}
}
void SortSegments(std::vector<Segment>& segments)
{
assert(segments.size() < 1024);
size_t sortedSegments[1024];
size_t sortedSegmentIndex = 1;
bool sortedSegmentUsed[1024] = {};
sortedSegmentUsed[0] = true;
sortedSegments[0] = 0;
SortSegments(segments, 0, sortedSegmentIndex, sortedSegments, sortedSegmentUsed);
if (sortedSegmentIndex != segments.size())
{
segments.clear();
return;
}
std::vector<Segment> res;
res.resize(segments.size());
for (size_t i = 0; i < sortedSegmentIndex; i++)
{
res[i] = segments[sortedSegments[i]];
}
segments = res;
}
void ClipMesh(const Vec3* positions, const unsigned int positionCount, const uint16_t* indices, const unsigned int indexCount,
Vec3* positionsOut, unsigned int& positionCountOut, uint16_t* indicesOut, unsigned int& indexCountOut,
std::vector<Segment>& segmentsOut,
const Vec4 plan)
{
indexCountOut = 0;
positionCountOut = 0;
std::vector<Segment> segments = segmentsOut;
for (unsigned int i = 0; i < indexCount; i += 3)
{
Vec3 trianglePos[3];
for (int t = 0; t < 3; t++)
{
const uint16_t index = indices[i + t];
trianglePos[t] = positions[index];
}
float distances[3];
int onPlanCount;
int onPlanIndex[3];
const uint8_t sides = GetSides<3>(trianglePos, plan, distances, onPlanCount, onPlanIndex);
if (sides == 0)
{
// append triangle
for (int t = 0; t < 3; t++)
{
positionsOut[positionCountOut] = trianglePos[t];
indicesOut[indexCountOut++] = positionCountOut;
positionCountOut++;
}
if (onPlanCount == 2)
{
assert(SquaredDistance(trianglePos[onPlanIndex[0]], trianglePos[onPlanIndex[1]]) > FLT_EPSILON);
if (onPlanIndex[0] == 0 && onPlanIndex[1] == 1)
{
segments.push_back({ trianglePos[1], trianglePos[0] });
}
else if (onPlanIndex[0] == 0 && onPlanIndex[1] == 2)
{
segments.push_back({ trianglePos[0], trianglePos[2] });
}
else if (onPlanIndex[0] == 1 && onPlanIndex[1] == 2)
{
segments.push_back({ trianglePos[2], trianglePos[1] });
}
else
{
assert(0);
}
}
}
else if (sides == 7)
{
// skip
}
else
{
// cut triangle
Segment currentSegment;
Vec3 cutPos[4];
int cutCount = 0;
for (int t = 0; t < 3; t++)
{
const int indexA = t;
const int indexB = (t + 1) % 3;
const float distanceA = distances[indexA];
const float distanceB = distances[indexB];
const bool isInA = distanceA < 0.f;
const bool isAOnPlane = fabsf(distanceA) <= FLT_EPSILON;
const bool isInB = distanceB < 0.f;
if (isInA && !isAOnPlane)
{
cutPos[cutCount++] = trianglePos[t];
}
if (isInA != isInB)
{
float len = fabsf(distanceB - distanceA);
float t = fabsf(distanceA) / len;
const Vec3& posA = trianglePos[indexA];
const Vec3& posB = trianglePos[indexB];
const Vec3 cut = Lerp(posA, posB, t);
if (isInA)
{
currentSegment.mB = cut;
}
else
{
currentSegment.mA = cut;
}
cutPos[cutCount] = cut;
cutCount++;
}
}
segments.push_back(currentSegment);
// generate triangles
assert(cutCount == 3 || cutCount == 4);
static const int localIndex[] = { 0, 1, 2, 0, 2, 3 };
const int localIndexCount = (cutCount == 3) ? 3 : 6;
for (int t = 0; t < localIndexCount; t++)
{
positionsOut[positionCountOut] = cutPos[localIndex[t]];
indicesOut[indexCountOut++] = positionCountOut;
positionCountOut++;
}
}
}
segmentsOut = segments;
}
std::vector<Vec3> SegmentsToVertices(const std::vector<Segment>& shape)
{
std::vector<Vec3> res;
if (shape.size() < 3)
{
return res;
}
Vec3 lastDir = NormDirection(shape.back().mA, shape.back().mB);
for (size_t i = 0; i < shape.size(); i++)
{
Vec3 currentDir = NormDirection(shape[i].mA, shape[i].mB);
float dt = Dot(currentDir, lastDir);
lastDir = currentDir;
if (dt < (1.f-FLT_EPSILON))
{
res.push_back(shape[i].mA);
}
}
return res;
}
void ClipSegments(std::vector<Segment>& segments, const Vec4 plan, std::vector<Segment>& segmentsForPlan)
{
std::vector<Segment> segmentsOut;
uint32_t pointOnPlanCount = 0;
Vec3 pointOnPlanA, pointOnPlanB;
for (auto& segment : segments)
{
float distances[2];
int onPlanCount;
int onPlanIndex[3];
const uint8_t sides = GetSides<2>(&segment.mA, plan, distances, onPlanCount, onPlanIndex);
if (sides == 0)
{
// append segment
if (onPlanCount != 2)
{
segmentsOut.push_back(segment);
}
if (onPlanCount == 1)
{
if (onPlanIndex[0] == 0)
{
pointOnPlanB = segment.mA;
}
else
{
pointOnPlanA = segment.mB;
}
pointOnPlanCount++;
}
}
else if (sides == 3)
{
// skip
}
else
{
const float distanceA = distances[0];
const float distanceB = distances[1];
const bool isInA = distanceA < 0.f;
const bool isInB = distanceB < 0.f;
if (isInA != isInB)
{
float len = fabsf(distanceB - distanceA);
float t = fabsf(distanceA) / len;
const Vec3& posA = segment.mA;
const Vec3& posB = segment.mB;
Vec3 cutPos = Lerp(posA, posB, t);
if (isInA)
{
segmentsOut.push_back({ posA, cutPos });
pointOnPlanA = cutPos;
}
else
{
segmentsOut.push_back({ cutPos, posB });
pointOnPlanB = cutPos;
}
pointOnPlanCount++;
assert(pointOnPlanCount < 3);
}
}
}
assert(pointOnPlanCount == 0 || pointOnPlanCount == 2);
if (pointOnPlanCount == 2)
{
segmentsOut.push_back({ pointOnPlanA, pointOnPlanB });
segmentsForPlan.push_back({ pointOnPlanB, pointOnPlanA });
}
segments = segmentsOut;
}
void ShapeToTriangles(const std::vector<Vec3>& shape, Vec3* positionsOut, unsigned int& positionCountOut, uint16_t* indicesOut, unsigned int& indexCountOut)
{
if (shape.size() > 2)
{
Vec3 posOrigin = shape[0];
for (size_t index = 1; index < (shape.size() - 1); index++)
{
Vec3 posA = shape[index];
Vec3 posB = shape[index + 1];
positionsOut[positionCountOut] = posOrigin;
indicesOut[indexCountOut++] = positionCountOut;
positionCountOut++;
positionsOut[positionCountOut] = posA;
indicesOut[indexCountOut++] = positionCountOut;
positionCountOut++;
positionsOut[positionCountOut] = posB;
indicesOut[indexCountOut++] = positionCountOut;
positionCountOut++;
}
}
}
ShatterMeshes Shatter(const Vec3* impacts, const unsigned int impactCount, const Vec3* positions, const unsigned int positionCount, const uint16_t* indices, const unsigned int indexCount)
{
ShatterMeshes result{};
for (size_t impactIndexA = 0; impactIndexA < impactCount; impactIndexA++)
{
memcpy(scratchIndexA, indices, indexCount * sizeof(uint16_t));
memcpy(scratchPosA, positions, positionCount * sizeof(Vec3));
Vec3* positionsIn = scratchPosA;
unsigned int positionCountIn = positionCount;
uint16_t* indicesIn = scratchIndexA;
unsigned int indexCountIn = indexCount;
Vec3* positionsOut = scratchPosB;
uint16_t* indicesOut = scratchIndexB;
unsigned int positionCountOut, indexCountOut;
std::vector<std::vector<Segment>> meshSegments;
meshSegments.resize(impactCount);
for (size_t impactIndexB = 0; impactIndexB < impactCount; impactIndexB++)
{
if (impactIndexA == impactIndexB)
{
continue;
}
// plan
Vec4 impactA(impacts[impactIndexA].x, impacts[impactIndexA].y, impacts[impactIndexA].z);
Vec4 impactB(impacts[impactIndexB].x, impacts[impactIndexB].y, impacts[impactIndexB].z);
Vec4 plan = BuildPlan((impactA + impactB) * 0.5f, (impactB - impactA).Normalize());
for (size_t shapeIndex = 0;shapeIndex < impactIndexB; shapeIndex++)
{
auto& segments = meshSegments[shapeIndex];
if (segments.size() > 2)
{
ClipSegments(segments, plan, meshSegments[impactIndexB]);
}
}
ClipMesh(positionsIn, positionCountIn, indicesIn, indexCountIn,
positionsOut, positionCountOut, indicesOut, indexCountOut,
meshSegments[impactIndexB],
//segments,
plan);
Swap(positionsIn, positionsOut);
Swap(indicesIn, indicesOut);
indexCountIn = indexCountOut;
positionCountIn = positionCountOut;
}
// from seg to triangles
for (auto& segments : meshSegments)
{
if (segments.size() > 2)
{
SortSegments(segments);
auto vertices = SegmentsToVertices(segments);
ShapeToTriangles(vertices, positionsIn, positionCountIn, indicesIn, indexCountIn);
}
}
if (indexCountIn && positionCountIn)
{
result.mShatteredMeshCount++;
auto newShatteredMeshes = new ShatteredMesh[result.mShatteredMeshCount];
if (result.mShatteredMeshCount > 1)
{
memcpy(newShatteredMeshes, result.mShatteredMeshes, sizeof(ShatteredMesh) * (result.mShatteredMeshCount - 1));
}
result.mShatteredMeshes = newShatteredMeshes;
auto& mesh = result.mShatteredMeshes[result.mShatteredMeshCount-1];
mesh.mIndexCount = indexCountIn;
mesh.mPositionCount = positionCountIn;
mesh.mIndices = new uint16_t[indexCountIn];
memcpy(mesh.mIndices, indicesIn, indexCountIn * sizeof(uint16_t));
mesh.mPositions = new Vec3[positionCountIn];
memcpy(mesh.mPositions, positionsIn, positionCountIn * sizeof(Vec3));
ComputeBBox(mesh.mPositions, positionCountIn, mesh.mBBMin, mesh.mBBMax);
auto center = mesh.GetBBoxCenter();
for (size_t i = 0; i < positionCountIn; i++)
{
mesh.mPositions[i].x -= center.x;
mesh.mPositions[i].y -= center.y;
mesh.mPositions[i].z -= center.z;
}
/*
mesh.mShapes.resize(meshSegments.size());
for (size_t i = 0;i< meshSegments.size();i++)
{
if (meshSegments[i].size() > 2)
{
mesh.mShapes[i].mSegments = meshSegments[i];
}
}
*/
}
}
return result;
}
void ComputeExplosion(const Vec3& explosionSource, const Vec3& explosionDirection, const Vec3& debrisPosition, Vec3& debrisDirection, float& debrisForce, Vec3& debrisTorqueAxis)
{
debrisDirection = NormDirection(explosionSource, debrisPosition);
debrisForce = Dot(explosionDirection, debrisDirection);
debrisTorqueAxis = Normalized(Cross(explosionDirection, debrisDirection));
}
void rotationAxis(const Vec3& axis, float angle, float *m)
{
float length2 = axis.x * axis.x + axis.y * axis.y + axis.z * axis.z;
/*
if (length2 < FLOAT_EPSILON)
{
identity();
return;
}
*/
Vec3 n = axis;// * (1.f / sqrtf(length2));
float s = sinf(angle);
float c = cosf(angle);
float k = 1.f - c;
float xx = n.x * n.x * k + c;
float yy = n.y * n.y * k + c;
float zz = n.z * n.z * k + c;
float xy = n.x * n.y * k;
float yz = n.y * n.z * k;
float zx = n.z * n.x * k;
float xs = n.x * s;
float ys = n.y * s;
float zs = n.z * s;
m[0 * 4 + 0] = xx;
m[0 * 4 + 1] = xy + zs;
m[0 * 4 + 2] = zx - ys;
m[0 * 4 + 3] = 0.f;
m[1 * 4 + 0] = xy - zs;
m[1 * 4 + 1] = yy;
m[1 * 4 + 2] = yz + xs;
m[1 * 4 + 3] = 0.f;
m[2 * 4 + 0] = zx + ys;
m[2 * 4 + 1] = yz - xs;
m[2 * 4 + 2] = zz;
m[2 * 4 + 3] = 0.f;
m[3 * 4 + 0] = 0.f;
m[3 * 4 + 1] = 0.f;
m[3 * 4 + 2] = 0.f;
m[3 * 4 + 3] = 1.f;
}
| true |
fd325d06da346f4301af231bdf44bdc446f461a7 | C++ | yaoyaoding/hidet-artifacts | /include/hidet/logging.h | UTF-8 | 949 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <iostream>
#include <sstream>
#include <hidet/common.h>
struct ErrorState {
bool has_error;
std::string error_msg;
static ErrorState *global();
};
struct HidetException: std::exception {
std::string file;
int line;
std::string msg;
HidetException(std::string file, int line, std::string msg):file(file), line(line), msg(msg){}
const char * what() const noexcept override {
static std::string what_msg;
what_msg = this->file + ":" + std::to_string(this->line) + " " + this->msg;
return what_msg.c_str();
}
};
DLL void hidet_set_last_error(const char *msg);
DLL const char * hidet_get_last_error();
#define API_BEGIN() try {
/*body*/
#define API_END(ret) } catch (const HidetException& e) { \
hidet_set_last_error(e.what()); \
return ret; \
}
| true |
89708f7395afb15f184280aba852120cca5903ff | C++ | juanfrandm98/PR_ED_2019 | /p3/solucion/pila_max_int/include/pila_max.h | UTF-8 | 3,035 | 3.625 | 4 | [] | no_license | /**
* @file pila_max.h
* @brief Fichero cabecera del TDA Pila max
*
* Gestiona una secuencia de elementos con facilidades para la inserción y
* borrado de elementos en un extremo.
*
*/
#ifndef __Pila_max_H__
#define __Pila_max_H__
#include "cola.h"
#include "pareja.h"
#include <cassert>
/**
*
* @brief T.D.A. Pila_max
*
*
* Una instancia @e v del tipo de dato abstracto Pila_max sobre un tipo @c int es
* una lista de pares de elementos <int,int> con un funcionamiento @e LIFO (Last In
* First Out). En una pila, las operaciones de inserción y borrado de elementos
* tienen lugar en uno de los extremos denominado @e Tope. Una Pila_max de longitud
* @e n la denotamos:
*
* - [<a1,max{a1...an}>,<a2,max{a2...an}>,<a3,max{a3...an}>,...,<an,an>]
*
* donde @e ai es el elemento de la posición i-ésima y @e max{ai...aj} es el máximo
* del conjunto de * elementos que van desde @e ai hasta @e aj.
*
* En esta pila, tendremos acceso únicamente al elemento del @e Tope, es decir,
* a @e an. El borrado o consulta de un elemento será sobre @e an, y la
* inserción de un nuevo elemento se hará sobre éste, quedando el elemento
* insertado como @e Tope de la pila.
*
* Si @e n == 0, diremos que la pila está vacía.
*
* El espacio requerido para el almacenamiento es O(n), donde n es el número de
* elementos de la Pila_max.
*
* @author Juan Francisco Díaz Moreno
* @date Octubre 2019
*
*/
class Pila_max {
private:
Cola<Pareja> elementos; ///< Cola de elementos
int maximo; ///< Elemento máximo actual
public:
// -------------------- Constructores -------------------- //
/**
*
* @brief Constructor por defecto
*
*/
Pila_max() {
maximo = 0;
}
/**
*
* @brief Constructor de copias
* @param original La Pila_max de la que se hará la copia.
*
*/
Pila_max( const Pila_max & original );
// -------------------- Destructor -------------------- //
/**
*
* @brief Destructor
*
*/
~Pila_max(){
maximo = 0;
}
// -------------------- Funciones -------------------- //
/**
*
* @brief Operador de asignación
* @param otra La Pila_max que se va a asignar.
*
*/
Pila_max & operator= ( const Pila_max & otra );
/**
*
* @brief Comprueba si la pila está vacía
*
*/
bool empty() const;
/**
*
* @brief Devuelve el tamaño de la pila
*
*/
int size() const;
/**
*
* @brief Devuelve el elemento del tope de la pila
*
*/
Pareja top();
/**
*
* @brief Devuelve el elemento del tope de la pila constante
*
*/
const Pareja & top() const;
/**
*
* @brief Añade un elemento encima del tope de la pila
* @param nuevo Elemento que se va a añadir
*
*/
void push( const int & nuevo );
/**
*
* @brief Quita el elemento del tope de la pila
*
*/
void pop();
friend ostream & operator<< ( ostream & os, const Pila_max & p );
};
#endif // __Pila_max_H__ | true |
093d8027f1877aa0a1e34b6318902d179e015a92 | C++ | Raghavan098/competitive-programming | /algos/Aho.cpp | UTF-8 | 680 | 2.53125 | 3 | [] | no_license | const int ms = 400;
const int eps = 10;
int c = 1;
int trie[ms][eps];
int fail[ms];
int addWord(std::string str) {
int on = 0;
for(auto ch : str) {
if(trie[on][ch - 'a'] == 0) {
trie[on][ch - 'a'] = c++;
}
on = trie[on][ch - 'a'];
}
return on;
}
void buildAho() {
std::queue<int> q;
q.push(0);
while(!q.empty()) {
int on = q.front();
q.pop();
for(int i = 0; i < eps; i++) {
int to = trie[on][i];
if(to != 0) {
if(on != 0) {
fail[to] = trie[fail[on]][i];
}
q.push(to);
} else {
trie[on][i] = trie[fail[on]][i];
}
// std::cout << "from " << on << " to " << trie[on][i] << " using " << char(i + 'a') << '\n';
}
}
}
| true |
ebc171147ef6635fc56dc60134c8cceccc2d5808 | C++ | sinomiko/56wlk | /cmmse/lab/libsource4/connectpool/output/strategy.h | GB18030 | 4,585 | 2.578125 | 3 | [] | no_license | /***************************************************************************
*
*
**************************************************************************/
/**
* @file strategy.h
* @brief
*
**/
#ifndef __STRATEGY_H_
#define __STRATEGY_H_
#include "connection.h"
namespace comcm{
enum{
//--- errer code for ConnectionRequest.err ---
REQ_OK = 0,
REQ_SVR_FULL,
REQ_CONN_FAILED,
REQ_SVR_DISABLE,
REQ_SVR_SELECT_FAIL
};
enum{
//--- error code for Connetion::setErrno / getErrno
ERR_OK = 0,
ERR_TALK_FAIL, //ʧ
ERR_DEAD_LIKE, //ӣܷ͡
ERR_OTHER
};
enum{
CONN_FREE = 1
};
class ConnectionRequest{
public:
int key; /**< hashοֵ */
int nthRetry; /**< ڼԣ0ʾһѡ */
int serverID; /**< һѡserverID */
int err; /**< һӵĴϢ */
Connection * conn; /**< һõConnection(ΪNULL) */
const char * tag; /**< ָtag */
ConnectionRequest(){};
virtual ~ConnectionRequest(){};
};
//--------------------------------------------------------------------
class Strategy{
protected:
ConnectManager * _mgr;
BasicLogAdapter * _log;
time_t _last_reload;
public:
//ConnectManagerѡȡһ̨Server
/**
* @brief 麯ConnectManagerѡȡһ̨server
* Ϊඨ
* ˲ConnectManagerãڵʱѼӶConnectManagerĶ
* áͣserverԶԵ̨serverһЩд
*
*
* @param [in/out] req : const ConnectionRequest*
* @return int
* @retval
* @see
**/
virtual int selectServer(const ConnectionRequest * req);
//֪ͨһ¼
/**
* @brief ֪ͨһ¼
* ֪ͨãStrategyоδ֪ͨ
* 磺eve = CONN_FREE;ʾһConnection黹
* ˽ӿڵֻǸ֪ѣstrategyԲ֪ͨ
*
* @param [in] conn : Connection*
* @param [in] eve : int
* @return int
* @retval
* @see
**/
virtual int notify(Connection * conn, int eve);
/**
* @brief ²״̬
*
* һЩûҪƲԵ״̬õĸ
* ڲԵӰ
*
* @return 0Ϊɹ 0ʧ
**/
virtual int update();
/**
* @brief ԼManager
* һ㲻Ҫûô˽ӿ
*
* @return int
* @retval
* @see
**/
int setManager(ConnectManager * ); //Manager
/**
* @brief ȡManager
*
* @return const ConnectManager*
* @retval
* @see
**/
const ConnectManager * getManager();
Strategy();
virtual ~Strategy();
};
//--------------------------------------------------------------------
class HealthyChecker{
protected:
ConnectManager * _mgr;
BasicLogAdapter * _log;
pthread_t _tid;
bool _single_thread;
friend void * thread_worker(void * pd);
struct AsyncWorker{
int seconds;
HealthyChecker * checker;
bool run;
}_worker;
public:
//ConnectManagerѡȡһ̨Server
/**
* @brief ԼManagerserverǷǽ
* Ϊ
*
* @return int
* @retval
* @see
**/
virtual int healthyCheck();
//һרŵ߳healthyCheck
/**
* @brief һµִ̣߳this->healthyCheck();
*
* @param [in] seconds : int ʱ (seconds)
* @return int
* @retval
* @see
**/
int startSingleThread(int seconds = 5);
/**
* @brief ֹԼ߳
*
* @return void
* @retval
* @see
**/
void joinThread();
/**
* @brief ҵManager
* һûҪô˽ӿ
*
* @return int
* @retval
* @see
**/
int setManager(ConnectManager *);
/**
* @brief ȡManager
*
* @return const ConnectManager*
* @retval
* @see
**/
const ConnectManager * getManager();
HealthyChecker();
virtual ~HealthyChecker();
};
}//namespace comcm
#endif //__STRATEGY_H_
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| true |
984dbc775053bcfa7aaa8610ed9aea233422c29a | C++ | Johnny0179/ccr4 | /src/robot/r5_controllers/r5_controllers.h | UTF-8 | 944 | 2.515625 | 3 | [] | no_license | #pragma once
#include "inter_core_com.h"
class r5_controllers
{
private:
/* data */
// motor id
static const u8 kUpPalm_ID = 1;
static const u8 kUpWheel_ID = 2;
static const u8 kPulley1_ID = 3;
static const u8 kPulley2_ID = 4;
static const u8 kDownClaw1_ID = 5;
static const u8 kDownClaw2_ID = 6;
// control frequency
float control_freq_KHz_;
// controller command
controllers_cmd controllers_cmd_;
// controller modes
static const u8 kIdle = 0;
static const u8 kHold = 1;
static const u8 kLoose = 2;
static const u8 kMove = 3;
static const u8 kFollow = 4;
static const u8 kPull = 5;
public:
explicit r5_controllers(float control_freq_KHz) : control_freq_KHz_(control_freq_KHz) {}
~r5_controllers();
// periodic control loop
void ControllersCmdPoll(void);
// set controller mode
void SetMode(const u8 &controller_id, const u8 &mode);
};
| true |
2f2a1f0664e8a900af931106a64dad483dd74952 | C++ | MaGnsio/100-days-of-code | /Problems/Codeforces/Codeforces Round #674 (Div. 3)/E. Rock, Paper, Scissors.cpp | UTF-8 | 1,049 | 2.6875 | 3 | [] | no_license | //https://codeforces.com/problemset/problem/1426/E
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
ll mod = 1e9 + 7;
int main ()
{
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
int n;
cin >> n;
vector<int> a(3), b(3);
for (auto& elem : a) cin >> elem;
for (auto& elem : b) cin >> elem;
int ans1 = INT_MAX;
int ans2 = min (a[0], b[1]) + min (a[1], b[2]) + min (a[2], b[0]);
vector<pair<int, int>> ord;
ord.push_back ({0, 0});
ord.push_back ({0, 2});
ord.push_back ({1, 0});
ord.push_back ({1, 1});
ord.push_back ({2, 1});
ord.push_back ({2, 2});
sort (ord.begin (), ord.end ());
do
{
vector<int> a1 = a, b1 = b;
for (int i = 0; i < ord.size (); ++i)
{
int cnt = min (a1[ord[i].F], b1[ord[i].S]);
a1[ord[i].F] -= cnt;
b1[ord[i].S] -= cnt;
}
int cur = min(a1[0], b1[1]) + min(a1[1], b1[2]) + min(a1[2], b1[0]);
ans1 = min(ans1, cur);
} while (next_permutation (ord.begin (), ord.end ()));
cout << ans1 << " " << ans2;
}
| true |
246d0ec3937000eb1c43411a4c1187443aed8903 | C++ | guzhen518/TryEngine | /Common/TryLinkList.cpp | GB18030 | 4,093 | 3.1875 | 3 | [] | no_license | #include "TryLinkList.h"
CLinkList::CLinkList()
{
}
CLinkList::~CLinkList()
{
}
LinkNode* CLinkList::CreateNode(int nData)
{
LinkNode* pNode = new LinkNode(nData);
return pNode;
}
bool CLinkList::AddNode(int nData)
{
LinkNode* pAddNode = CreateNode(nData);
if (NULL == pAddNode )
{
return false;
}
LinkNode* pCurrNode = m_pLinkRoot;
while (!pCurrNode)
{
pCurrNode = pCurrNode->pNext;
}
if ( NULL == pCurrNode)
{
pCurrNode = pAddNode;
}
else
{
pCurrNode->pNext = pAddNode;
}
return true;
}
bool CLinkList::RemoveNode(int nKey)
{
if (NULL == m_pLinkRoot )
{
return false;
}
LinkNode* pPreNode = NULL;
LinkNode* pRemoveNode = m_pLinkRoot;
while (NULL != pRemoveNode && pRemoveNode->nData == nKey )
{
pPreNode = pRemoveNode;
pRemoveNode = pRemoveNode->pNext;
}
if (pRemoveNode->nData != nKey )
{
return false;
}
LinkNode* pNext = pRemoveNode->pNext;
delete pRemoveNode;
pPreNode->pNext = pNext;
return true;
}
LinkNode* CLinkList::ReverseNode(LinkNode* pHead)
{
if (NULL == pHead || NULL == pHead->pNext )
{
return NULL;
}
LinkNode* pPre = NULL;
while (NULL != pHead )
{
LinkNode* pNext = pHead->pNext;
pHead->pNext = pPre;
pPre = pHead;
pHead = pNext;
}
return pPre;
}
//Ľ˼·͵3⡸ĵ k ڵ㡹ơ
//ijȣȻмڵ˳λá
//ҪֻɨһνأЧĽⷨ͵3һ
//ָͨɡָͷڵ㿪ʼһָÿƶ
//һÿƶһֱָƵβڵ㣬ôָ뼴
LinkNode* CLinkList::GetMiddleNode()
{
if (NULL == m_pLinkRoot )
{
return NULL;
}
LinkNode* pSlow = NULL;
LinkNode* pFast = NULL;
pSlow = pFast = m_pLinkRoot;
while (NULL != pFast && NULL != pFast->pNext )
{
pSlow = pSlow->pNext;
pFast = pFast->pNext->pNext;
}
return pSlow;
}
//ָͨ룬ֱͷڵһÿƶһһƶ
//ָƶٶȲһڻôָһڻ
bool CLinkList::HasCircle(LinkNode* pHead, LinkNode*& pCirNode)
{
if (NULL == pHead )
{
return false;
}
LinkNode* pSlow = NULL;
LinkNode* pFast = NULL;
pSlow = pFast = pHead;
while (NULL != pFast && NULL != pFast->pNext )
{
pFast = pFast->pNext->pNext;
pSlow = pSlow->pNext;
if (pSlow == pFast )
{
pCirNode = pSlow;
return true;
}
}
return false;
}
LinkNode* CLinkList::GetNodeByK(int k)
{
if (k <= 0 )
{
return NULL;
}
LinkNode* pSlow = NULL;
LinkNode* pFast = NULL;
pSlow = pFast = m_pLinkRoot;
int nLoop = k;
for (; nLoop > 0; --nLoop)
{
pFast = pFast->pNext;
}
if (nLoop > 0)
{
return NULL;
}
while (NULL != pFast )
{
pFast = pFast->pNext;
pSlow = pSlow->pNext;
}
return pSlow;
}
// ֪ p2 ÿp1 ÿһķʽߣ p2 p1 غϣȷ˵л·ˡ
//p2صͷߣÿβ2ˣ1ô p1 p2 ٴʱǻ·ˡ
LinkNode* CLinkList::FindLoopNode()
{
if (NULL == m_pLinkRoot )
{
return NULL;
}
LinkNode* pSlow = NULL;
LinkNode* pFast = NULL;
pFast = pSlow = m_pLinkRoot;
while (NULL != pFast && NULL != pFast->pNext )
{
pFast = pFast->pNext->pNext;
pSlow = pSlow->pNext;
if (pSlow == pFast )
{
break;
}
}
if (pSlow != pFast )
{
return NULL;
}
pFast = m_pLinkRoot;
while (pFast != pSlow )
{
pFast = pFast->pNext;
pSlow = pSlow->pNext;
}
return pFast;
}
LinkNode* CLinkList::ReverseNodeT(LinkNode* pHead)
{
if (NULL == pHead )
{
return NULL;
}
LinkNode* pNewHead = NULL;
while (NULL != pHead )
{
LinkNode* pNextNode = pHead->pNext;
pHead->pNext = pNewHead;
pNewHead = pHead;
pHead = pNextNode;
}
return pNewHead;
}
| true |
2a70857a1b66e65532f965f767d58515f1e488a6 | C++ | ysoftman/test_code | /cpp/korean_code_in_utf8_test.cpp | UTF-8 | 763 | 2.828125 | 3 | [
"MIT"
] | permissive | // ysoftman
// utf-8 인코딩으로 한글(11172자) 출력
#include <stdio.h>
using namespace std;
int main()
{
// utf-8 한글을 파일로 출력
FILE *fp = fopen("utf8-hangul.txt", "w");
// 한글 유니코드(UCS) 0xAC00(가) ~ 0xD7A3(힣) 11172자 -> utf-8 인코딩으로 변환
char hangul[3];
int cnt = 0;
for (unsigned short i = 0xAC00; i <= 0xD7A3; i++)
{
// 참고
// http://www.codeguru.com/cpp/misc/misc/multi-lingualsupport/article.php/c10451/The-Basics-of-UTF8.htm
hangul[0] = ((char)(0xE0 | i >> 12));
hangul[1] = ((char)(0x80 | i >> (6 & 0x3F)));
hangul[2] = ((char)(0x80 | (i & 0x3F)));
fprintf(fp, "%X = %c%c%c\n", i, hangul[0], hangul[1], hangul[2]);
++cnt;
}
printf("cnt = %d\n", cnt);
fclose(fp);
return 0;
}
| true |
45f7018cc88100ab485a1fa21e0409f6a695252e | C++ | maidoufu/Coursera | /Structure/Week6_2.cpp | UTF-8 | 1,876 | 3.578125 | 4 | [] | no_license | //
// BST.cpp
// Structure
//
// Created by Song on 1/13/16.
// Copyright © 2016 Song. All rights reserved.
//
#include <iostream>
using namespace std;
template <class T>
struct BSTNode
{
BSTNode(const T& e, BSTNode* le=0, BSTNode* ri=0 )
{
el=e;left=le;right=ri;
}
T el;
BSTNode<T>*left;
BSTNode<T>*right;
};
template <class T>
class BSTTree
{
public:
BSTTree(){root=0;}
~BSTTree(){}
bool search(const T& e);
void insert(const T& e);
void preorder(){preorder(root);}
void postorder(){postorder(root);}
private:
BSTNode<T>* root;
void preorder(BSTNode<T> *p);
void postorder(BSTNode<T>* p);
};
template <class T>
bool BSTTree<T>::search(const T& e)
{
BSTNode<T>* p=root;
while (p!=0)
{
if (p->el==e) return true;
else if(e<p->el) p=p->left;
else p=p->right;
}
return false;
}
template <class T>
void BSTTree<T>::insert(const T& e)
{
BSTNode<T>*p=root,*prev=root;
while (p!=0)
{
if (e<p->el)
{prev=p;p=p->left;}
else if(e>p->el)
{
prev=p;
p=p->right;
}
}
if (root==0) root=new BSTNode<T>(e);
else if (e<prev->el)
prev->left= new BSTNode<T>(e);
else prev->right=new BSTNode<T>(e);
}
template<class T>
void BSTTree<T>::postorder(BSTNode<T>* p)
{
if (p!=0)
{
postorder(p->left);
postorder(p->right);
cout<<p->el<<" ";
}
}
template<class T>
void BSTTree<T>::preorder(BSTNode<T>* p)
{
if (p!=0)
{
cout<<p->el<<" ";
preorder(p->left);
preorder(p->right);
}
}
int main()
{
BSTTree<int> bs;
int num;
char ch;
while (cin>>num)
{
if (!bs.search(num))
bs.insert(num);
cin.get(ch);
if (ch=='\n') break;
}
bs.preorder();
cout<<endl;
}
| true |
068575acfdab7479297bd3f26a2fd3ba012d4bd9 | C++ | lambdai/ssl-impl | /test/test_common.cc | UTF-8 | 959 | 2.78125 | 3 | [] | no_license | #include "test_common.h"
#include <stdio.h>
#include <stdlib.h>
#include "gtest/gtest.h"
void EXPECT_HEX_EQ(const std::vector<unsigned int> &lhs,
const std::string &rhs) {
const unsigned char *display_hash =
reinterpret_cast<const unsigned char *>(lhs.data());
std::vector<char> display(lhs.size() * 4 * 2 + 32, '0');
for (int i = 0; i < (lhs.size() * 4); i++) {
sprintf(display.data() + i * 2, "%.02x", display_hash[i]);
}
std::string display_as_string(display.begin(), display.begin() + rhs.size());
EXPECT_EQ(display_as_string, rhs);
}
void EXPECT_HEX_EQ(const std::vector<unsigned char> &lhs,
const std::string &rhs) {
std::vector<char> display(lhs.size() * 2 + 32, '0');
for (int i = 0; i < lhs.size(); i++) {
sprintf(display.data() + i * 2, "%.02x", lhs[i]);
}
std::string display_as_string(display.begin(), display.begin() + rhs.size());
EXPECT_EQ(display_as_string, rhs);
} | true |
57f0a43405d2e69dcc262f6a48f45db7f1c9813f | C++ | kuonanhong/UVa-2 | /11952 - Arithmetic.cpp | UTF-8 | 22,859 | 2.90625 | 3 | [] | no_license | /**
UVa 11952 - Arithmetic
by Rico Tiongson
Submitted: June 13, 2013
Accepted 0.015s C++
O(16) time
*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<functional>
using namespace std;
#define BIGINT_CONTAINER deque<int>
#define B_FOR for( unsigned i(0); i<size(); ++i )
// #define BIGINT_EXCEPTION
static const char* _base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//for exception handling
#ifdef BIGINT_EXCEPTION
class BigInt_Exception{
int id;
string kind, desc, func;
public:
BigInt_Exception():id(0), desc("DEFAULT EXCEPTION"), func("NONE"){what();}
BigInt_Exception(int ID,const char* KIND,const char* DESC,const char* FUNC):id(ID),kind(KIND),desc(DESC),func(FUNC){what();}
void what()const{
cerr << " __________________________________________________________________ " << endl;
cerr << " # " << endl;
cerr << " # BigInt exception #" << id << " occured :: " << kind << endl;
cerr << " # " << endl;
cerr << " # Description: ";
cerr << left << desc << endl << " # " << endl;
cerr << " # handled when method \"" << func << "\" was called." << endl;
cerr << " # " << endl;
cerr << " #_________________________________________________________________ " << endl;
cerr << endl;
cerr << "Program has been forcibly terminated ----- @Exception handling by rico B-)" << endl;
cerr << " " << endl;
cerr << " " << endl;
// throw BigInt_Exception();
}
};
#endif
class BigInt{
BIGINT_CONTAINER v;
#ifdef BIGINT_PUBLIC
public:
#endif
int BASE_CASE( char c )const{ return c<'A' ? c-'0' : ( c<'a' ? c-'A'+10 : c-'a' + 10 ); }
template<class Type> BigInt& INTEGRAL_ASSIGN( Type _ ){
clear();
if( _ < 0 ){
signbit = true;
_ = -_;
}
while( _ ){
push_left( _%BASE );
_ /= BASE;
}
return *this;
}
template<class Comparator> bool T_COMPARE( const BigInt& _, Comparator cmp, bool whenEqual )const{
B_FOR if( digit(i)!=_.digit(i) ) return cmp( digit(i), _.digit(i) );
return whenEqual;
}
bool U_COMPARE( const BigInt& _ )const{
if( size() == _.size() ) return T_COMPARE( _, less<int>(), false );
return size() < _.size();
}
bool S_COMPARE( const BigInt& _ )const{
if( signbit != _.signbit ) return signbit;
return U_COMPARE( _ );
}
BigInt& ACCUMULATE( const BigInt& _ ){
push_left( 0, _.size()-size() );
for( unsigned i=0; i<_.size(); ++i ) v[i] += _.get(i);
return *this;
}
BigInt& DECCUMULATE( const BigInt& _ ){
bool u = U_COMPARE( _ );
push_left( 0, _.size()-size() );
for( unsigned i=0; i<_.size(); ++i ) v[i] -= _.get(i);
if(u){
signbit = !signbit;
B_FOR v[i] = -v[i];
}
return *this;
}
BigInt& CARRY(){
int hold(0);
B_FOR{
v[i]+=hold;
hold = v[i]/BASE;
v[i]%=BASE;
}
while(hold){
push_left(hold%BASE);
hold/=BASE;
}
return *this;
}
BigInt& UNCARRY(){
int hold(0);
B_FOR{
v[i]+=hold;
if(v[i]<0){
hold = v[i]/BASE-1;
v[i] = BASE+v[i]%BASE;
}
else hold = 0;
}
return *this;
}
template<class Type> pair<BigInt,Type> NUMBER_DIV( Type _ )const{
#ifdef BIGINT_EXCEPTION
if(!_)
throw BigInt_Exception(1,"Arithmetic Exception","Division by Zero","private : BigInt::NUMBER_DIV( Type )");
#endif
BigInt ans;
ans.BASE = BASE;
ans.signbit = (signbit!=(_<0));
Type hold=0;
int k;
for(unsigned i=0;i<size();++i){
hold*=BASE;
hold+=digit(i);
k = hold/_;
ans.push_right(k);
hold-=_*k;
}
ans.trim_left();
return pair<BigInt,Type>( ans, hold );
}
template<class Type> BigInt NUMBER_DIVISION( Type _ )const{
#ifdef BIGINT_EXCEPTION
if(!_)
throw BigInt_Exception(1,"Arithmetic Exception","Division by Zero","private : BigInt::NUMBER_DIVISION( Type )");
#endif
BigInt ans;
ans.signbit = (signbit!=(_<0));
ans.BASE = BASE;
Type hold=0;
int k;
for(unsigned i=0;i<size();++i){
hold*=BASE;
hold+=digit(i);
k = hold/_;
ans.push_right(k);
hold-=_*k;
}
ans.trim_left();
return ans;
}
template<class Type> BigInt NUMBER_MOD( Type _ )const{
#ifdef BIGINT_EXCEPTION
if(!_)
throw BigInt_Exception(1,"Arithmetic Exception","Modulo by Zero","private : BigInt::NUMBER_MOD( Type )");
#endif
BigInt ans;
ans.signbit = (signbit!=(_<0));
ans.BASE = BASE;
Type hold=0;
int k;
for(unsigned i=0;i<size();++i){
hold*=BASE;
hold+=digit(i);
k = hold/_;
ans.push_right(k);
hold-=_*k;
}
return hold;
}
#ifndef BIGINT_PUBLIC
public:
#endif
static int use_base;
bool signbit;
int BASE;
//methods
BigInt& assign( const BigInt& _ ){
v = _.v;
signbit = _.signbit;
if( BASE != _.BASE ) toBase( BASE );
return *this;
}
BigInt& assign( const string& _ ){
clear();
if( !_.empty() ){
unsigned i(0);
if( _[i]=='-' ){
++i;
signbit = true;
}
for( ; i<_.size(); ++i ) push_right( BASE_CASE( _[i] ) );
trim_left();
if(empty()) signbit = false;
}
return *this;
}
BigInt& assign( const char* _ ){
clear();
unsigned i=0;
if( _[i]=='-' ){
++i;
signbit = true;
}
for( ; _[i]!='\0'; ++i ) push_right( BASE_CASE( _[i] ) );
trim_left();
if(empty()) signbit = false;
return *this;
}
BigInt& assign( const char& _ ){
clear();
push_left( BASE_CASE( _ ) );
return *this;
}
BigInt& assign( int _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( short _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( long _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( long long _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( unsigned _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( unsigned short _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( unsigned long _ ){ return INTEGRAL_ASSIGN( _ ); }
BigInt& assign( unsigned long long _ ){ return INTEGRAL_ASSIGN( _ ); }
template<class Type> BigInt& assign( const Type& _, int b ){
#ifdef BIGINT_EXCEPTION
if( b < 2 ) throw BigInt_Exception(2,"InvalidBase Exception","Base < 2","BigInt::assign( Type, int )");
else if( b >61 ) throw BigInt_Exception(2,"InvalidBase Exception","Base > 61","BigInt::assign( Type, int )");
#endif
int hold = BASE;
BASE = b;
return assign( _ ).toBase( hold );
}
void clear(){
v.clear();
signbit = false;
}
BigInt& push_left( int _ ){
#ifdef BIGINT_EXCEPTION
if( _>=BASE ) throw BigInt_Exception(2,"InvalidBase Exception","Trying to assign Base greater than expected","BigInt::push_left( int )");
#endif
v.push_back( _ );
return *this;
}
BigInt& push_left( int _, int pad ){ while( pad>0 ){ push_left( _ ); --pad; } return *this; }
BigInt& push_right( int _ ){
#ifdef BIGINT_EXCEPTION
if( _>=BASE ) throw BigInt_Exception(2,"InvalidBase Exception","Trying to assign Base greater than expected","BigInt::push_right( int )");
#endif
v.push_front( _ );
return *this;
}
BigInt& push_right( int _, int pad ){ while( pad>0 ){ push_right( _ ); --pad; } return *this; }
BigInt& pop_left(){ v.pop_back(); return *this; }
BigInt& pop_left( int pad ){ while( !empty() && pad>0 ){ pop_left(); --pad; } return *this; }
BigInt& pop_right(){ v.pop_front(); return *this; }
BigInt& pop_right( int pad ){ while( !empty() && pad>0 ){ pop_right(); --pad; } return *this; }
BigInt& trim( int _=0 ){ return trim_left( _ ).trim_right( _ ); }
BigInt& trim_left( int _=0 ){ while( !empty() && left()==_ ) pop_left(); return *this; }
BigInt& trim_right( int _=0 ){ while( !empty() && right()==_ ) pop_right(); return *this; }
//constr
BigInt(): BASE(use_base) {
#ifdef BIGINT_EXCEPTION
if( use_base < 2 ) throw BigInt_Exception(2,"InvalidBase Exception","Base < 2","static BigInt::use_base");
else if( use_base >61 ) throw BigInt_Exception(2,"InvalidBase Exception","Base > 61","static BigInt::use_base");
#endif
clear();
}
template<class Type> BigInt( const Type& _ ): BASE(use_base) { assign( _ ); }
template<class Type> BigInt( const Type& _, int b ):BASE( b ) { assign( _ ); }
//convert
BigInt base( int b )const{
#ifdef BIGINT_EXCEPTION
if( b < 2 ) throw BigInt_Exception(2,"InvalidBase Exception","Base < 2","BigInt::base( int )");
else if( b >61 ) throw BigInt_Exception(2,"InvalidBase Exception","Base > 61","BigInt::base( int )");
#endif
BigInt Copy = *this;
return Copy.toBase( b );
}
BigInt operator()( int b )const{ return base( b ); }
BigInt& toBase( int b ){
#ifdef BIGINT_EXCEPTION
if( b < 2 ) throw BigInt_Exception(2,"InvalidBase Exception","Base < 2","BigInt::toBase( int )");
else if( b >61 ) throw BigInt_Exception(2,"InvalidBase Exception","Base > 61","BigInt::toBase( int )");
#endif
BigInt ans;
ans.BASE = b;
ans.signbit = signbit;
pair<BigInt,int> DIV;
while(!empty()){
DIV = div( b );
*this = DIV.first;
ans.push_left( DIV.second );
}
return *this = ans;
}
template<class Type> vector<Type> to_vector(){ return vector<Type>( v.rbegin(), v.rend() ); }
template<class Type> list<Type> to_list(){ return list<Type>( v.rbegin(), v.rend() ); }
template<class Type> deque<Type> to_deque(){ return deque<Type>( v.rbegin(), v.rend() ); }
template<class Type> Type u_to()const{
Type ans = 0;
B_FOR{
ans *= BASE;
ans += digit(i);
}
return ans;
}
template<class Type> Type u_to( int b )const{ return base( b ).u_to<Type>(); }
template<class Type> Type to()const{
if(signbit) return -u_to<Type>();
return u_to<Type>();
}
template<class Type> Type to( int b )const{ return base( b ).to<Type>(); }
operator bool()const{ return !empty(); }
operator char()const;
operator short()const{ return to<short>(); }
operator int()const{ return to<int>(); }
operator long()const{ return to<long>(); }
operator long long()const{ return to<long long>(); }
operator unsigned short()const{ return u_to<unsigned short>(); }
operator unsigned()const{ return u_to<unsigned>(); }
operator unsigned long()const{ return u_to<unsigned long>(); }
operator unsigned long long()const{ return u_to<unsigned long long>(); }
operator string()const;
//accessors
BIGINT_CONTAINER& access(){ return v; }
bool& sign(){ return signbit; }
unsigned size()const{ return v.size(); }
unsigned length()const{ return v.size(); }
bool empty()const{ return v.empty(); }
int get( unsigned _ )const{
#ifdef BIGINT_EXCEPTION
if(_>=size()) throw BigInt_Exception(3,"OutOfRange Exception","Index Out of Range","BigInt::get( unsigned )");
#endif
return v[_];
}//from ones digit
int digit( unsigned _ )const{
#ifdef BIGINT_EXCEPTION
if(_>=size()) throw BigInt_Exception(3,"OutOfRange Exception","Index Out of Range","BigInt::digit( unsigned )");
#endif
return v[ size()-_-1 ];
} //from most significant digit
int& left(){
#ifdef BIGINT_EXCEPTION
if(empty()) throw BigInt_Exception(3,"OutOfRange Exception","Force Access on Empty Container","BigInt::left( )");
#endif
return v.back();
}
int& right(){
#ifdef BIGINT_EXCEPTION
if(empty()) throw BigInt_Exception(3,"OutOfRange Exception","Force Access on Empty Container","BigInt::right( )");
#endif
return v.front();
}
int& operator[]( unsigned _ ){
#ifdef BIGINT_EXCEPTION
if(empty()) throw BigInt_Exception(3,"OutOfRange Exception","Force Access on Empty Container","BigInt::operator[] ( unsigned )");
#endif
return v[_];
}
BigInt operator-()const{
BigInt Copy = *this;
Copy.signbit = !signbit;
return Copy;
}
BigInt& operator+=( const BigInt& _ ){
if( signbit != _.signbit ){
signbit = !signbit;
operator-=( _ );
signbit = !signbit;
}
else ACCUMULATE( _ ).CARRY().trim_left();
return *this;
}
BigInt& operator++(){
if(empty()){
signbit = false;
push_left(1);
return *this;
}
if(signbit){
for(unsigned i=0;i<size();++i){
if(--v[i]==-1) v[i] = BASE-1;
else return trim_left();
}
}
else{
for(unsigned i=0;i<size();++i){
if(++v[i]==BASE) v[i]=0;
else return *this;
}
push_left(1);
}
return *this;
}
BigInt& operator++( int _ ){ return operator++(); } //ignore post
template<class Type> BigInt operator+( const Type& _ )const{ return (BigInt(*this)+=_); }
BigInt& operator-=( const BigInt& _ ){
if( signbit != _.signbit ){
signbit = !signbit;
operator+=( _ );
signbit = !signbit;
}
else DECCUMULATE ( _ ).UNCARRY().trim_left();
return *this;
}
BigInt& operator--(){
signbit = !signbit;
operator++();
if(!empty())
signbit = !signbit;
return *this;
}
BigInt& operator--( int _ ){ return operator--(); } //ignore post
template<class Type> BigInt operator-( const Type& _ )const{ return (BigInt(*this)-=_); }
template<class Type> BigInt& operator*=( const Type& _ ){ return *this = operator*( _ ); }
BigInt operator*( const BigInt& _ )const{
if(BASE!=_.BASE) return operator*(_.base(BASE));
BigInt ans,temp;
ans.BASE = BASE;
if(size()<_.size()){
for(unsigned int i=0;i<size();++i)
ans += _.operator*(get(i)).push_right(0,i);
}
else{
for(unsigned int i=0;i<_.size();++i){
ans += operator*(_.get(i)).push_right(0,i);
}
}
ans.signbit = (signbit!=_.signbit);
return ans;
}
BigInt operator*( int _ )const{
if(!_) return 0;
BigInt ans;
ans.BASE = BASE;
if(_<0){
_=-_;
ans.signbit = !signbit;
}
else ans.signbit = signbit;
if(_!=1){
int hold=0;
for(unsigned i=0;i<size();++i){
hold += _*get(i);
ans.push_left(hold%BASE);
hold/=BASE;
}
if(hold) ans.push_left(hold);
}
else ans = *this;
return ans;
}
template<class Type> pair<BigInt, Type> div( const Type& _ )const{ return NUMBER_DIV( _ ); }
pair<BigInt,BigInt> div( const BigInt& _ )const{
#ifdef BIGINT_EXCEPTION
if(!_) throw BigInt_Exception(1,"Arithmetic Exception","Division by Zero","BigInt::div( const BigInt& )");
#endif
if(empty()) return pair<BigInt,BigInt>(*this,*this);
if(_.size()<18u) return NUMBER_DIV( _.to<long long>());
if(BASE!=_.BASE) return div(_.base(BASE));
if( U_COMPARE(_) ){
BigInt ans;
ans.BASE = BASE;
return pair<BigInt,BigInt>(ans,signbit!=_.signbit?-*this:*this);
}
BigInt ans,hold,temp;
long SMALL = 0,HOLDER;
for(unsigned i=_.size()-4u;i<_.size();++i){
SMALL*=_.BASE;
SMALL+=_.get(i);
}
ans.BASE = hold.BASE = BASE;
hold.signbit = _.signbit;
int val;
B_FOR{
hold.push_right( digit(i) );
if( hold.U_COMPARE( _ ) ){
ans.push_right( 0 );
}
else{
//estimate
//fix binary
HOLDER = 0;
for( unsigned j=_.size()-4u;j<hold.size();++j ){
HOLDER*=hold.BASE;
HOLDER+=hold.get(j);
}
val = HOLDER/SMALL;
// cerr << endl << ans << endl;
temp = _*(val);
while( temp<=hold ){
temp+=_;
++val;
}
ans.push_right( val-1 );
hold-=(temp-=_);
}
}
ans.trim_left();
if(!ans.empty())
ans.signbit = (signbit!=_.signbit);
if(hold.empty()) hold.signbit = false;
else hold.signbit = (signbit!=_.signbit);
return pair<BigInt,BigInt>(ans,hold);
}
pair<BigInt,BigInt> div( const string& _ )const{ return div(BigInt(_)); }
pair<BigInt,BigInt> div( const char* _ )const{ return div(BigInt(_)); }
BigInt operator/( const BigInt& _ )const{
#ifdef BIGINT_EXCEPTION
if(!_) throw BigInt_Exception(1,"Arithmetic Exception","Division by Zero","BigInt::operator/( const BigInt& )");
#endif
if(empty()) return *this;
if(_.size()<18u) return NUMBER_DIVISION(_.to<long long>());
if(BASE!=_.BASE) return operator/(_.base(BASE));
if( U_COMPARE(_) ){
BigInt ans;
ans.BASE = BASE;
return ans;
}
BigInt ans,hold,temp;
long SMALL = 0,HOLDER;
for(unsigned i=_.size()-4u;i<_.size();++i){
SMALL*=_.BASE;
SMALL+=_.get(i);
}
ans.BASE = hold.BASE = BASE;
hold.signbit = _.signbit;
int val;
B_FOR{
hold.push_right( digit(i) );
if( hold.U_COMPARE( _ ) ){
ans.push_right( 0 );
}
else{
//estimate
//fix binary
HOLDER = 0;
for( unsigned j=_.size()-4u;j<hold.size();++j ){
HOLDER*=hold.BASE;
HOLDER+=hold.get(j);
}
val = HOLDER/SMALL;
// cerr << endl << ans << endl;
temp = _*(val);
while( temp<=hold ){
temp+=_;
++val;
}
ans.push_right( val-1 );
hold-=(temp-=_);
}
}
ans.trim_left();
if(!ans.empty())
ans.signbit = (signbit!=_.signbit);
return ans;
}
BigInt operator/( const string& _ )const{ return operator/(BigInt(_)); }
BigInt operator/( const char* _ )const{ return operator/(BigInt(_)); }
template<class Type> BigInt operator/( const Type& _ )const{ return NUMBER_DIVISION(_); }
template<class Type> BigInt& operator/=( const Type& _ )const{ return *this = operator/(_); }
BigInt operator%( const BigInt& _ )const{
#ifdef BIGINT_EXCEPTION
if(!_) throw BigInt_Exception(1,"Arithmetic Exception","Modulo by Zero","BigInt::operator%( const BigInt& )");
#endif
if(empty()) return *this;
if(_.size()<18u) return NUMBER_MOD(_.to<long long>());
if(BASE!=_.BASE) return operator%(_.base(BASE));
if( U_COMPARE( _ ) ) return signbit!=_.signbit?-*this:*this;
BigInt ans,hold,temp;
long SMALL = 0,HOLDER;
for(unsigned i=_.size()-4u;i<_.size();++i){
SMALL*=_.BASE;
SMALL+=_.get(i);
}
ans.BASE = hold.BASE = BASE;
hold.signbit = _.signbit;
int val;
B_FOR{
hold.push_right( digit(i) );
if( hold.U_COMPARE( _ ) ){
ans.push_right( 0 );
}
else{
//estimate
//fix binary
HOLDER = 0;
for( unsigned j=_.size()-4u;j<hold.size();++j ){
HOLDER*=hold.BASE;
HOLDER+=hold.get(j);
}
val = HOLDER/SMALL;
temp = _*(val);
while(temp<=hold){
temp+=_;
++val;
}
ans.push_right( val-1 );
hold-=(temp-=_);
}
}
if(hold.empty()) hold.signbit = false;
else hold.signbit = (signbit!=_.signbit);
return hold;
}
BigInt operator%( const string& _ )const{ return operator%(BigInt(_)); }
BigInt operator%( const char* _ )const{ return operator%(BigInt(_)); }
template<class Type> BigInt operator%( const Type& _ )const{ return NUMBER_MOD(_); }
template<class Type> BigInt& operator%=( const Type& _ ){ return *this = operator%(_); }
bool operator<( const BigInt& _ )const{
if( BASE != _.BASE ) return operator<(_.base(BASE));
return S_COMPARE( _ );
}
template<class Type> bool operator<( const Type& _ )const{ return operator<(BigInt(_)); }
bool operator<=( const BigInt& _ )const{
if( signbit != _.signbit ) return signbit;
if( BASE != _.BASE ) return operator<=(_.base(BASE));
if( size() == _.size() ) return T_COMPARE( _, less<int>(), true );
return size() < _.size();
}
template<class Type> bool operator<=( const Type& _ )const{ return operator<=(BigInt(_)); }
template<class Type> bool operator>( const Type& _ )const{ return _.operator<(*this); }
template<class Type> bool operator>=( const Type& _ ) const{ return _.operator<=(*this); }
bool operator==( const BigInt& _ )const{ return signbit==_.signbit && BASE==_.BASE && v==_.v; }
template<class Type> bool operator==( const Type& _ )const{ return operator==(BigInt(_)); }
template<class Type> bool operator!=( const Type& _ )const{ return !(operator==(_)); }
bool operator!()const{ return empty(); }
BigInt operator^( int _ )const{
if(!_) return BigInt(1);
BigInt POW = operator^(_/2);
if(_%2) return operator*(POW*POW);
return POW*POW;
}
BigInt& operator^=( int _ ){ return *this = operator^(_); }
BigInt& operator=( const BigInt& _ ){
v = _.v;
signbit = _.signbit;
BASE = _.BASE;
return *this;
}
};
template<> string BigInt::to<string>()const{
if(empty()) return "0";
string ans;
if(signbit) ans.push_back('-');
B_FOR ans.push_back( _base[digit(i)] );
return ans;
}
template<> char* BigInt::to<char*>()const{
char* c = new char[size()+2];
char *p = c;
if(empty()){
c[0] = '0';
c[1] = '\0';
return c;
}
p=c;
if(signbit){
*p= '-';
++p;
}
for(unsigned i=0;i<size();++i){
*p = digit(i)+'0';
p++;
}
*p = '\0';
return c;
}
template<> char BigInt::to<char>()const{ if(empty()) return '0'; return _base[get(0)]; }
BigInt::operator char()const{ return to<char>(); }
BigInt::operator string()const{ return to<string>(); }
istream& operator>>( istream& in, BigInt& _ ){
string buffer;
in >> buffer;
_.assign(buffer);
return in;
}
ostream& operator<<( ostream& out, const BigInt& _ ){ return out << string(_); }
int BigInt::use_base = 10;
/** END BigInt v1.1 **/
/** IsosceleS 2013(c) **/
BigInt a, b, c;
char d[3][7];
int n, i, j, k, len[3];
bool haszero;
void maxBase(){
i = '1';
haszero = false;
for( j=0; j<3; ++j ){
for( k=0; k<len[j]; ++k ){
if( i<d[j][k] ) i=d[j][k];
else if(!haszero){
if( d[j][k]=='0' ) haszero = true;
}
}
}
i -= '/';
}
bool one(){
for( j=0; j<3; ++j ){
len[j] = strlen(d[j]);
for( k=0; k<len[j]; ++k ){
if( d[j][k]!='1' ) return false;
}
}
return len[0] + len[1] == len[2];
}
int main(){
scanf("%d", &n);
while( n ){
scanf( "%s + %s = %s", d[0], d[1], d[2] );
if( one() ) puts("1");
else{
for( i=2; i<19; ++i ){
BigInt::use_base = i;
if( BigInt( d[0] ) + BigInt( d[1] ) == BigInt( d[2] ) ) break;
}
if( i==19 ) puts("0");
else printf("%d\n",i);
}
--n;
}
}
| true |
d8b5bacd2433c8de17cd7882a27d582b904dd74e | C++ | AIS-Bonn/stillleben | /src/animator.cpp | UTF-8 | 1,358 | 2.84375 | 3 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Animate a 6D pose
// Author: Max Schwarz <max.schwarz@ais.uni-bonn.de>
#include <stillleben/animator.h>
#include <Corrade/Containers/Array.h>
#include <Magnum/Math/Quaternion.h>
#include <stdexcept>
using namespace Magnum;
namespace sl
{
Animator::Animator(const std::vector<Matrix4>& poses, unsigned int ticks)
: m_totalTicks{ticks}
{
if(poses.size() < 2)
throw std::invalid_argument("Need at least two poses to animate...");
Containers::Array<std::pair<unsigned int, Vector3>> positions(poses.size());
Containers::Array<std::pair<unsigned int, Quaternion>> orientations(poses.size());
std::size_t idx = 0;
unsigned int time = 0;
for(auto& pose : poses)
{
time = idx * ticks / (poses.size()-1);
positions[idx] = {time, pose.translation()};
orientations[idx] = {time, Quaternion::fromMatrix(pose.rotationScaling())};
idx++;
}
m_positionTrack = Animation::Track<unsigned int, Vector3>{std::move(positions), Animation::Interpolation::Linear};
m_orientationTrack = Animation::Track<unsigned int, Quaternion>{std::move(orientations), Animation::Interpolation::Linear};
}
Matrix4 Animator::operator()()
{
auto position = m_positionTrack.at(m_index);
auto orientation = m_orientationTrack.at(m_index);
m_index++;
return Matrix4::from(orientation.toMatrix(), position);
}
}
| true |
363f599c471c691253d23b175f56e3c8f22df8d6 | C++ | consistent-loser/Dynamic-Programming | /weight job scheduling.cpp | UTF-8 | 1,337 | 2.828125 | 3 | [] | no_license | // weighted job scheduling using dynamic programming
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
pair<int,int>a[n]; // first for the ending time and second for the starting time
map<pair<int,int>,int>m; //map for storinfg the weights
for(int i=0;i<n;i++){
pair<int,int>p;
cin>>p.second>>p.first;
a[i]=p;
}
for(int i=0;i<n;i++){
int temp;
cin>>temp;
m[a[i]]=temp;
}
sort(a,a+n); // sort the jobs wrt increasing ending time
int dp[n];
for(int i=0;i<n;i++){
dp[i]=m[a[i]]; //initially max job performed =1
}
int tot_max=INT_MIN;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(a[i].second>=a[j].first){ // if job i and job j doesnt overlap
dp[i]=max(dp[i],m[a[i]]+dp[j]); //do somethiing
tot_max=max(dp[i],tot_max);
}
}
}
/* for(int i=0;i<n;i++){
cout<<dp[i]<<" ";
}*/
cout<<tot_max<<endl;
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~****************PEACE OUT***********************~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
| true |
44d6d1fccdfc1462aa75c752b32ace71bf414343 | C++ | randreshg/RayTracer_Javeriana | /Anexo 3. RayTracer software/RayTracer/src/RayTracing/Scene.cpp | UTF-8 | 1,313 | 3.546875 | 4 | [] | no_license | /*---------------------------------CLASS DEFINITION--------------------------------*/
class Scene
{
public:
/*----------------------------------ATTRIBUTES---------------------------------*/
Color background;
Array<Primitive*> primitives;
Array<Light> lights;
/*----------------------------------FUNCTIONS----------------------------------*/
void addPrimitive(Primitive *p){primitives.push_back(p);}
void addLight(Light l){lights.push_back(l);}
void print()
{
cout<<"SCENE INFO:"<<endl;
cout<<"\n-Background color [R G B]: "; background.print(); cout<<endl;
cout<<"\n-Objects info:"<<endl;
for(unsigned int i= 0; i< primitives.size(); i++)
primitives[i]->print();
cout<<"\n-Lights sources info: "<<endl;
for(unsigned int i= 0; i< lights.size(); i++)
lights[i].print();
}
/*--------------------------------CONSTRUCTORS---------------------------------*/
Scene(){};
Scene(Color bkg, Array<Primitive*> primitives, Array<Light> lights)
{
this->background = bkg;
this->primitives = primitives;
this->lights = lights;
}
Scene(const Scene &s)
{
background = s.background;
primitives = s.primitives;
lights = s.lights;
}
};
| true |
a894d76aceb1dd5298ad1058928378e1c02ddaaf | C++ | jeffamaxey/Heston-Hull-White | /HestonHullWhiteFiniteDifference/Schemes/European/Examples/BaseADIScheme/A3.h | UTF-8 | 1,787 | 2.53125 | 3 | [] | no_license | #ifndef HESTONHULLWHITEFINITEDIFFERENCE_SCHEMES_EUROPEAN_EXAMPLES_BASEADISCHEME_A3_H
#define HESTONHULLWHITEFINITEDIFFERENCE_SCHEMES_EUROPEAN_EXAMPLES_BASEADISCHEME_A3_H
// A3 implements the calculation of the partial terms in the r-direction the Heston-Hull-White PDE using an explicit scheme.
#include <memory>
#include <vector>
#include <HestonHullWhiteFiniteDifference/DiscretizationExamples/ADIDiscretization/ADIDiscretization.h>
#include "HestonHullWhiteFiniteDifference/GridExamples/ThreeDimensionalGrid/threedimensionalgrid.h"
namespace heston_hull_white {
namespace finite_difference {
namespace tests {
template<typename GridType> class A3Tester;
}
namespace examples {
template<typename GridType>
class A3 {
friend class tests::A3Tester<GridType>;
public:
// TODO: perhaps I should just take a reference to the discretization?
A3(const double lambda, const double eta, const double theta_t, std::shared_ptr<const ADIDiscretization> discretization);
// TransformGrid computes the sume of the r-direction partials at each point of the grid
// TODO: This should be faster if the loops were:
// Outer: r
// Inner: s
// Inner Inner: v
// possibly switching s and v based on memory considerations
GridType TransformGrid(const GridType& vec);
void TransformGridInPlace(GridType& vec);
std::vector<std::array<double, 3 >> GetMatrix() const {
return condensed_a3_matrix_;
}
private:
std::size_t num_ss_;
std::size_t num_vs_;
std::size_t num_rs_;
std::vector<std::array<double, 3>> condensed_a3_matrix_;
};
}
}
}
#include "HestonHullWhiteFiniteDifference/Schemes/European/Examples/BaseADIScheme/src/A3.tpp"
#endif | true |
3fc46715a7a13b8c473c98e568d51e8270e30729 | C++ | SilvanVR/DX | /DX/Common/src/Include/OS/Threading/thread_pool.h | UTF-8 | 3,574 | 3.28125 | 3 | [] | no_license | #pragma once
/**********************************************************************
class: ThreadPool (thread_pool.h)
author: S. Hau
date: October 21, 2017
Manages a bunch of threads via a job system. A job is basically
just a function. A job will be executed by an arbitrary thread.
When adding a new job the job itself will be returned, so the
calling thread can wait until this specific job has been executed.
@Considerations:
- Support "Persistens Jobs", aka jobs running in a while(true) loop.
For now all jobs have to have a clear end.
- Add a batch of jobs simultanously. Wait for a batch.
- Fetch memory for jobs from an custom allocator
(No dynamic allocations via shared-ptr)
**********************************************************************/
#include "thread.h"
namespace OS {
//----------------------------------------------------------------------
#define MAX_POSSIBLE_THREADS 32
//**********************************************************************
// Manages a bunch of threads.
//**********************************************************************
class ThreadPool
{
static U8 s_hardwareConcurrency;
public:
//----------------------------------------------------------------------
// Create a new threadpool with the specified amount of threads.
// @Params:
// "numThreads": Number of threads to create.
//----------------------------------------------------------------------
ThreadPool(U8 numThreads = (s_hardwareConcurrency - 1));
~ThreadPool();
//----------------------------------------------------------------------
U8 numThreads() const { return m_numThreads; }
U8 maxHardwareConcurrency() const { return s_hardwareConcurrency; }
//----------------------------------------------------------------------
// Waits until all jobs has been executed. After this call, all threads
// will be idle and no job is left in the queue.
//----------------------------------------------------------------------
void waitForThreads();
//----------------------------------------------------------------------
// Adds a new job. The job will executed by an arbitrary thread.
// @Params:
// "job": Job/Task to execute.
//----------------------------------------------------------------------
JobPtr addJob(const std::function<void()>& job);
//----------------------------------------------------------------------
Thread& operator[] (U32 index){ ASSERT( index < m_numThreads ); return (*m_threads[index]); }
private:
Thread* m_threads[MAX_POSSIBLE_THREADS];
U8 m_numThreads;
JobQueue m_jobQueue;
//----------------------------------------------------------------------
// Wait until all threads have finished their execution and terminates them.
//----------------------------------------------------------------------
void _TerminateThreads();
//----------------------------------------------------------------------
ThreadPool(const ThreadPool& other) = delete;
ThreadPool& operator = (const ThreadPool& other) = delete;
ThreadPool(ThreadPool&& other) = delete;
ThreadPool& operator = (ThreadPool&& other) = delete;
};
} // end namespaces
| true |
5e26613193d6dd3860873954dbd0d443705a7183 | C++ | Akamatsu21/CardCutter | /main.cpp | UTF-8 | 1,694 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <QDir>
#include <QImage>
const QString DIR(QDir::currentPath() + "/");
const int COLS = 10;
const int ROWS = 7;
int main(int argc, char *argv[])
{
if(argc != 2)
{
std::cout << "Need exactly one argument! Please provide the name of the file." << std::endl;
return 1;
}
QString source = QString::fromLatin1(argv[1], strlen(argv[1]));
std::cout << "Parsing file " << source.toStdString() << ".jpg" << std::endl;
QString destination(DIR + source);
QImage image(destination + ".jpg");
if(image.isNull())
{
std::cout << "Error reading image!" << std::endl;
return 2;
}
if(QDir(destination).exists())
{
std::cout << "Folder with this name already exists!" << std::endl;
return 3;
}
bool success = QDir(DIR).mkdir(source);
if(!success)
{
std::cout << "Error creating directory." << std::endl;
return 4;
}
int width = image.width() / COLS;
int height = image.height() / ROWS;
int counter = 0;
for(int i = 0; i < ROWS; ++i)
{
for(int k = 0; k < COLS; ++k)
{
QImage card = image.copy(k * width, i * height, width, height);
++counter;
success = card.save(destination + "/" + QString::number(counter) + ".jpg");
if(success)
{
std::cout << "Card " << QString::number(counter).toStdString() << " saved successfully" << std::endl;
}
else
{
std::cout << "Error saving card " << QString::number(counter).toStdString() << std::endl;
}
}
}
return 0;
}
| true |
1c48eb037188eb4acee318bf096c50393a570168 | C++ | D3E0/RTA | /Solved/Multi-University Training Contest/H-Diff-prime Pairs.cpp | UTF-8 | 984 | 2.875 | 3 | [] | no_license | //============================================================================
//Name:牛客多校第三场 H Diff-prime Pairs 素数筛
//https://www.nowcoder.com/acm/contest/141/H
//============================================================================
#include<iostream>
#include<cstring>
using namespace std;
const int N = 700000;
bool notprime[int(1e7 + 10)];
int prime[N];
int main() {
int cnt = 0, n;
cin >> n;
memset(notprime, 0, sizeof(notprime));
for (int i = 2; i <= n; i++) {
if (!notprime[i]) {
prime[cnt++] = i;
for (int j = i * i; j <= n; j += i) {
notprime[j] = true;
}
}
}
long long ans = 0;
// 每一个素数 x 可以与前面的i个素数组成素数对,
// 并且 kx(kx <= n) 也可以与前面的i个素数组成素数对;
for (int i = 0; prime[i] != 0; i++) {
ans += n / prime[i] * i;
}
cout << ans * 2 << endl;
return 0;
}
| true |
bcd35b1beaadcae5c1aeef3b7b7a8d9c0f68b21f | C++ | luckycoder-git/PUBG-Cheat-By-huoji-and-Lee | /ConsoleApplication1/scm.cpp | UTF-8 | 2,000 | 2.5625 | 3 | [] | no_license | #include "stdafx.h"
#include <stdio.h>
BOOL ScmCreateService(
_Out_ PHANDLE ServiceHandle,
_In_ LPCWSTR ServiceName,
_In_opt_ LPCWSTR DisplayName,
_In_ LPCWSTR BinPath,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG ServiceType,
_In_ ULONG StartType,
_In_ ULONG ErrorControl
)
{
SC_HANDLE Scm;
WCHAR QualifiedPath[MAX_PATH + 2];
Scm = OpenSCManagerW(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if(!Scm)
return FALSE;
swprintf_s(QualifiedPath, MAX_PATH + 2, L"%ws", BinPath);
*ServiceHandle = CreateServiceW(
Scm,
ServiceName, DisplayName,
DesiredAccess,
ServiceType, StartType,
ErrorControl, QualifiedPath,
NULL, NULL, NULL, NULL, NULL
);
CloseServiceHandle(Scm);
return *ServiceHandle != NULL;
}
BOOL ScmDeleteService(
_In_ HANDLE ServiceHandle
)
{
return DeleteService((SC_HANDLE)ServiceHandle);
}
BOOL ScmOpenServiceHandle(
_Out_ PHANDLE ServiceHandle,
_In_ LPCWSTR ServiceName,
_In_ ACCESS_MASK DesiredAccess
)
{
SC_HANDLE Scm;
Scm = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
if(!Scm)
return FALSE;
*ServiceHandle = OpenService(Scm, ServiceName, DesiredAccess);
CloseServiceHandle(Scm);
return *ServiceHandle != NULL;
}
BOOL ScmCloseServiceHandle(
_In_ HANDLE ServiceHandle
)
{
return CloseServiceHandle((SC_HANDLE)ServiceHandle);
}
BOOL ScmStartService(
_In_ HANDLE ServiceHandle
)
{
return StartServiceW((SC_HANDLE)ServiceHandle, 0, NULL);
}
BOOL ScmPauseService(
_In_ HANDLE ServiceHandle
)
{
SERVICE_STATUS ServiceStatus;
return ControlService((SC_HANDLE)ServiceHandle, SERVICE_CONTROL_PAUSE, &ServiceStatus);
}
BOOL ScmResumeService(
_In_ HANDLE ServiceHandle
)
{
SERVICE_STATUS ServiceStatus;
return ControlService((SC_HANDLE)ServiceHandle, SERVICE_CONTROL_CONTINUE, &ServiceStatus);
}
BOOL ScmStopService(
_In_ HANDLE ServiceHandle
)
{
SERVICE_STATUS ServiceStatus;
return ControlService((SC_HANDLE)ServiceHandle, SERVICE_CONTROL_STOP, &ServiceStatus);
} | true |
8de335c61ec566f1003251b447ee4263e0d19dad | C++ | bhargavchippada/CompilersLab | /lab5/test.cpp | UTF-8 | 710 | 2.78125 | 3 | [] | no_license | // #include <stdio.h>
int remake(int z, float u){
float x, y;
u = y;
z = 2;
return 0;
}
// int remake(int z, int u, float y){
// return 3.0*4;
// }
float swap(int p, int q){
int x;
x=1;
return 1;
}
int main()
{
int x, y;
// float z;
int p[4][5];
// int k[4];
y = 5;
x = y;
// t = x;
p[2][3] = 5;
// p[2][p[1][1]] = remake(1,2.0); // corrupts the value
// p[2][remake(1,2.0)] = remake(1,2.0); // corrupts the value of ebx
// printf("%f\n", p[2][3]);
// y = x + p[1][2];
p[3][3] = remake(3,4);
// swap(p[1][2], p[3][4]);
//swap = 30;
// int z[200];
// y = p[1][1];
// while(x < 4) x = x + 1;
// for (x=0.5; x <10; x++);
// if (y >1) {x=x-1; y=y+1; if (1) ; else ;} else ;
}
| true |
dc49351fd3c24f882ab051acc63f482454be0222 | C++ | K00226160/2019-c-plus-plus | /lect08-02-overidingboss/lect08-02-overidingboss/main.cpp | UTF-8 | 235 | 2.5625 | 3 | [] | no_license | #include "Enemy.h"
#include "overridingboss.h"
int main()
{
cout << "Enemy object:\n";
Enemy anEnemy;
anEnemy.Taunt();
anEnemy.Attack();
cout << "\n\nBoss object:\n";
Boss aBoss;
aBoss.Taunt();
aBoss.Attack();
return 0;
}
| true |
ad40ed5ec0148e578811dd9c4c337851a82ff76a | C++ | kevin57545/Shopping-Platform | /ShoppingPlatform.cpp | UTF-8 | 32,545 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <fstream>
using namespace std;
class Commodity;
class Store;
class InputHandler;
class InputHandler {
public:
/*
* The function is used to read a full line into a string variable.
* It read the redundant '\n' character to prevent the problem of getline function.
* There is an overload version which can read from the specified data stream.
* INPUT: None, or fstream
* RETURN: Full line input by user
* */
static string readWholeLine() {
string input;
cin.get();
getline(cin, input);
return input;
}
static string readWholeLine(fstream& file) {
string input;
file.get();
getline(file, input);
return input;
}
/*
* This function is used to configure whether the input string is a number
* INPUT: A string
* RETURN: Bool. True if input string is a number, otherwise false.
*/
static bool isNum(string& str) {
for (int i = 0; i < str.size(); i++) {
if (!isdigit(str[i])) {
return false;
}
}
return true;
}
/*
* Check the input string is a valid number.
* First check the input is a number or not, then identify whether it is bigger than 0
* INPUT: string
* RETURN: bool
*/
static bool isValidNum(string& str) {
if (!isNum(str) || (isNum(str) && stoi(str) <= 0))
return false;
return true;
}
/*
* Get a number from the user. This function will check the input validation.
* INPUT: none
* OUTPUT: integer, the input number
*/
static int numberInput() {
string input;
cin >> input;
while (!isValidNum(input)) {
cout << "Please input again your input is NOT an integer or is lower than or equal to 0:" << endl;
cin >> input;
}
return stoi(input);
}
/*
* This function is used in function getInput. Check the input range is inside the specified range
*/
static int inputCheck(string input, int maxChoiceLen, bool noZero) {
// Change input to the general integer
int choice = 0;
for (int i = 0; i < input.size(); i++) {
if (isdigit(input[i])) {
choice = choice * 10 + (input[i] - '0');
}
else {
return -1;
}
}
if (noZero) {
return (choice <= maxChoiceLen && choice > 0) ? choice : -1;
}
else {
return (choice <= maxChoiceLen && choice >= 0) ? choice : -1;
}
}
/*
* Get the input from the user, and limit the input between the range [0, maxChoiceLen].
* If noZero is signaled. Then the range will be [1, maxChoiceLen]
* INPUT: integer, bool(option)
* OUTPUT: integer, the choice number
*/
static int getInput(int maxChoiceLen, bool noZero = false) {
string input;
cin >> input;
int choice = inputCheck(input, maxChoiceLen, noZero);
while (choice == -1) {
cout << "your input is wrong, please input again:" << endl;
cin >> input;
choice = inputCheck(input, maxChoiceLen, noZero);
}
return choice;
}
};
/*
* Commodity is about an item which the user can buy and the manager can add or delete.
* ATTRIBUTE:
* price: The price of the commodity, an integer.
* description: The text which describe the commodity detail, a string.
* commodityName: The name of the commodity, a string.
*/
class Commodity {
protected:
int price;
string description;
string commodityName;
int number = 0;
int classifi;
Commodity* ptr;
public:
~Commodity() = default;
Commodity() {
price = 0;
description = "";
commodityName = "";
}
Commodity(int price, string commodityName, string description) {
this->price = price;
this->commodityName = commodityName;
this->description = description;
}
/*
* This method will show the full information of the commodity to user interface.
* There is a overloading version, with an argument amount which will output the information with the amount
* INPUT: None, or an integer specify the amount of this commodity
* RETURN: None
*/
virtual void detail() {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "description: " << description << endl;
cout << "----------------------------" << endl;
}
virtual void detail(int amount) {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "description: " << description << endl;
cout << "x " << amount << endl;
cout << "----------------------------" << endl;
}
/*
* Use this function to get the information data from the user, this will init the object.
* INPUT: none
* OUTPUT: none
*/
virtual void userSpecifiedCommodity() {
cout << "Please input the commodity name:" << endl;
commodityName = InputHandler::readWholeLine();
cout << "Please input the commodity price:" << endl;
price = InputHandler::numberInput();
cout << "Please input the detail of the commodity:" << endl;
description = InputHandler::readWholeLine();
}
/*
* Save and load function is used to write the data to the file or read the data from the file.
* According to the input parameter fstream, they complete the I/O on the specified file.
* There have no definition of those method, because it is used to be override in the derived class.
* INPUT: fstream
* OUTPUT: none
*/
virtual void save(fstream& file) {}
virtual void load(fstream& file) {}
/*
* The getter function of commodityName
*/
string getName() {
return commodityName;
}
/*
* The getter function of price
*/
int getPrice() {
return price;
}
void addNum() {
number++;
}
void resetNum() {
number = 0;
}
void writeptr(Commodity* a)
{
ptr = a;
}
int getNum() {
return number;
}
Commodity* readptr()
{
return ptr;
}
int classification() {
return classifi;
}
};
class ComputerMonitor : public Commodity {
protected:
string ratio;
int size;
string res;
int rate;
ComputerMonitor* ptr;
public:
~ComputerMonitor() = default;
ComputerMonitor() {
price = 0;
description = "";
commodityName = "";
ratio = "";
size = 0;
res = "";
rate = 0;
}
virtual void detail() {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "aspect ratio: " << ratio << endl;
cout << "panel size: " << size << " inch" << endl;
cout << "panel resolution: " << res << endl;
cout << "refresh rate: " << rate << "Hz" << endl;
cout << "description: " << description << endl;
cout << "----------------------------" << endl;
}
virtual void detail(int amount) {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "aspect ratio: " << ratio << endl;
cout << "panel size: " << size << " inch" << endl;
cout << "panel resolution: " << res << endl;
cout << "refresh rate: " << rate << "Hz" << endl;
cout << "description: " << description << endl;
cout << "x " << amount << endl;
cout << "----------------------------" << endl;
}
virtual void userSpecifiedCommodity() {
cout << "Please input the commodity name:" << endl;
commodityName = InputHandler::readWholeLine();
cout << "Please input the commodity price:" << endl;
price = InputHandler::numberInput();
cout << "What is the aspect ratio of this monitor?(e.g. 16:9,21:9...)" << endl;
ratio = InputHandler::readWholeLine();
cout << "What is the panel size of this monitor?(inch)" << endl;
size = InputHandler::numberInput();
cout << "What is the panel resolution of this monitor?(e.g. 1920*1080,4k...)" << endl;
res = InputHandler::readWholeLine();
cout << "What is the refresh rate of this monitor?(Hz)" << endl;
rate = InputHandler::numberInput();
cout << "Please input the detail of the commodity:" << endl;
description = InputHandler::readWholeLine();
}
void save(fstream& file) {
file << commodityName << endl << price << endl << ratio << endl << size
<< endl << res << endl << rate << endl << description << endl;
}
void load(fstream& file) {
getline(file, commodityName);
file >> price;
ratio = InputHandler::readWholeLine(file);
file >> size;
res = InputHandler::readWholeLine(file);
file >> rate;
description = InputHandler::readWholeLine(file);
}
int classification() {
classifi = 0;
return classifi;
}
};
class Mouse : public Commodity {
protected:
int DPI;
int button;
string LED;
int weight;
int classifi = 1;
Mouse* ptr;
public:
~Mouse() = default;
Mouse() {
price = 0;
description = "";
commodityName = "";
DPI = 0;
button = 0;
LED = "";
weight = 0;
}
virtual void detail() {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "Max DPI: " << DPI << endl;
cout << "The number of buttons: " << button << endl;
cout << "LED Light: " << LED << endl;
cout << "weight: " << weight << "g" << endl;
cout << "description: " << description << endl;
cout << "----------------------------" << endl;
}
virtual void detail(int amount) {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "Max DPI: " << DPI << endl;
cout << "The number of buttons: " << button << endl;
cout << "LED Light: " << LED << endl;
cout << "weight: " << weight << "g" << endl;
cout << "description: " << description << endl;
cout << "x " << amount << endl;
cout << "----------------------------" << endl;
}
virtual void userSpecifiedCommodity() {
cout << "Please input the commodity name:" << endl;
commodityName = InputHandler::readWholeLine();
cout << "Please input the commodity price:" << endl;
price = InputHandler::numberInput();
cout << "What is the Max DPI of this mouse?" << endl;
DPI = InputHandler::numberInput();
cout << "How many buttons are there on this mouse?" << endl;
button = InputHandler::numberInput();
cout << "What is the LED Light of this monitor?(e.g. RGB,none...)" << endl;
LED = InputHandler::readWholeLine();
cout << "How much does this mouse weigh?(g)" << endl;
weight = InputHandler::numberInput();
cout << "Please input the detail of the commodity:" << endl;
description = InputHandler::readWholeLine();
}
void save(fstream& file) {
file << commodityName << endl << price << endl << DPI << endl << button << endl
<< LED << endl << weight << endl << description << endl;
}
void load(fstream& file) {
getline(file, commodityName);
file >> price >> DPI >> button;
LED = InputHandler::readWholeLine(file);
file >> weight;
description = InputHandler::readWholeLine(file);
}
int classification() {
classifi = 1;
return classifi;
}
};
class USB : public Commodity {
protected:
string type;
int capacity;
int read;
int write;
int classifi = 2;
USB* ptr;
public:
~USB() = default;
USB() {
price = 0;
description = "";
commodityName = "";
type = "";
capacity = 0;
read = 0;
write = 0;
}
virtual void detail() {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "USB type: " << type << endl;
cout << "capacity: " << capacity << " GB" << endl;
cout << "Max Read Speed: " << read << " MB/s" << endl;
cout << "Max Write Speed: " << read << " MB/s" << endl;
cout << "description: " << description << endl;
cout << "----------------------------" << endl;
}
virtual void detail(int amount) {
cout << commodityName << endl;
cout << "price: " << price << endl;
cout << "USB type: " << type << endl;
cout << "capacity: " << capacity << " GB" << endl;
cout << "Max Read Speed: " << read << " MB/s" << endl;
cout << "Max Write Speed: " << read << " MB/s" << endl;
cout << "description: " << description << endl;
cout << "x " << amount << endl;
cout << "----------------------------" << endl;
}
virtual void userSpecifiedCommodity() {
cout << "Please input the commodity name:" << endl;
commodityName = InputHandler::readWholeLine();
cout << "Please input the commodity price:" << endl;
price = InputHandler::numberInput();
cout << "What is the USB Type of this USB?" << endl;
type = InputHandler::readWholeLine();
cout << "What is the storage capacity of this USB?(GB)" << endl;
capacity = InputHandler::numberInput();
cout << "What is the Max Read Speed of this USB?(MB/s)" << endl;
read = InputHandler::numberInput();
cout << "What is the Max Write Speed of this USB?(MB/s)" << endl;
write = InputHandler::numberInput();
cout << "Please input the detail of the commodity:" << endl;
description = InputHandler::readWholeLine();
}
void save(fstream& file) {
file << commodityName << endl << price << endl << type << endl << capacity << endl
<< read << endl << write << endl << description << endl;
}
void load(fstream& file) {
getline(file, commodityName);
file >> price;
type = InputHandler::readWholeLine(file);
file >> capacity >> read >> write;
description = InputHandler::readWholeLine(file);
}
int classification() {
classifi = 2;
return classifi;
}
};
/*
* This is a list storing the existing commodity in the store.
*/
class CommodityList {
private:
vector<Commodity*> commoditylist[3];
vector<Commodity*>::iterator it;
Commodity* temp;
public:
CommodityList() {
}
/*
* Print the full information of the commodities inside the list
* INPUT: None
* RETURN: None
*/
void showCommoditiesDetail() {
int Num = 0;
cout << "Computer Monitor type:" << endl;
for (int i = 0; i < commoditylist[0].size(); i++) {
cout << ++Num << ". ";
commoditylist[0].at(i)->detail();
}
cout << "Mouse type:" << endl;
for (int i = 0; i < commoditylist[1].size(); i++) {
cout << ++Num << ". ";
commoditylist[1].at(i)->detail();
}
cout << "USB type:" << endl;
for (int i = 0; i < commoditylist[2].size(); i++) {
cout << ++Num << ". ";
commoditylist[2].at(i)->detail();
}
}
/*
* Print only the commodity name of the commodities inside the list
* INPUT: None
* RETURN: None
*/
void showCommoditiesName() {
int Num = 0;
cout << "Computer Monitor type:" << endl;
for (int i = 0; i < commoditylist[0].size(); i++) {
cout << ++Num << ". " << commoditylist[0].at(i)->getName() << endl;
}
cout << "Mouse type:" << endl;
for (int i = 0; i < commoditylist[1].size(); i++) {
cout << ++Num << ". " << commoditylist[1].at(i)->getName() << endl;
}
cout << "USB type:" << endl;
for (int i = 0; i < commoditylist[2].size(); i++) {
cout << ++Num << ". " << commoditylist[2].at(i)->getName() << endl;
}
}
/*
* Check whether the list is empty or not
* INPUT: None
* RETURN: Bool. True if the list is empty, otherwise false
*/
bool empty() {
if (commoditylist[0].empty() == true && commoditylist[1].empty() == true && commoditylist[2].empty() == true)
return true;
else return false;
}
/*
* Return the size(or length) of the list
* INPUT: None
* RETURN: Integer. List size
*/
int size() {
int size = 0;
for (int i = 0; i < 3; i++)
{
size = size + commoditylist[i].size();
}
return size;
}
/*
* Return a commodity object at specified position
* INPUT: Integer. The index of that commodity
* RETURN: Commodity. The wanted commodity object
*/
Commodity* get(int index) {
int find = 0;
Commodity* ptr;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < commoditylist[i].size(); j++)
{
if (find == index) {
ptr = commoditylist[i][j];
return ptr;
}
else find++;
}
}
}
/*
* Push a new commodity object into the list
* INPUT: Commodity. The object need to be pushed
* RETURN: None
*/
void add(Commodity* newCommodity, string& cat) {
if (cat == "ComputerMonitor")
commoditylist[0].push_back(newCommodity);
else if (cat == "Mouse")
commoditylist[1].push_back(newCommodity);
else
commoditylist[2].push_back(newCommodity);
}
/*
* Check the input commodity object is existing inside the list
* INPUT: Commodity. The object need to be checked
* OUTPUT: Bool. True if the object existing, otherwise false
*/
bool isExist(Commodity* commodity) {
int i;
for (int i = 0; i < 3; i++) {
it = commoditylist[i].begin();
for (int j = 0; j < commoditylist[i].size(); j++)
{
if (commodity->getName() == (*(it + j))->getName())
return true;
}
}
return false;
}
/*
* Remove an object specified by the position
* INPUT: Integer. The position of the object which need to be removed
* OUTPUT: None
*/
void remove(int index) {
int find = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < commoditylist[i].size(); j++)
{
if (find == index) {
it = commoditylist[i].begin();
commoditylist[i].erase(it + j);
return;
}
else find++;
}
}
}
void save() {
fstream savefile;
for (int i = 0; i < 3; i++) {
if (i == 0) {
savefile.open("ComputerMonitor.txt", ios_base::out);
}
else if (i == 1) {
savefile.open("Mouse.txt", ios_base::out);
}
else if (i == 2) {
savefile.open("USB.txt", ios_base::out);
}
for (int j = 0; j < commoditylist[i].size(); j++) {
commoditylist[i][j]->save(savefile);
}
savefile.close();
}
}
void load() {
fstream loadfile;
int i;
string a;
for (i = 0; i < 3; i++) {
if (i == 0) {
a = "ComputerMonitor";
loadfile.open("ComputerMonitor.txt", ios_base::in);
if(!loadfile) continue;
}
else if (i == 1) {
a = "Mouse";
loadfile.open("Mouse.txt", ios_base::in);
if(!loadfile) continue;
}
else if (i == 2) {
a = "USB";
loadfile.open("USB.txt", ios_base::in);
if(!loadfile) continue;
}
while (loadfile.eof() != true) {
if (i == 0) {
temp = new ComputerMonitor;
}
else if (i == 1) {
temp = new Mouse;
}
else if (i == 2) {
temp = new USB;
}
temp->load(loadfile);
if (!loadfile.fail()) {
add(temp, a);
}
}
loadfile.close();
}
}
};
/*
* The shopping cart is used to store the commodities user wanted.
*/
class ShoppingCart {
private:
vector<Commodity*> shoppingcart;
vector<Commodity*>::iterator it;
public:
/*
* Push an commodity object into the cart.
* INPUT: Commodity. The object need to be pushed.
* OUTPUT: None.
*/
void push(Commodity* entry) {
int i;
for (i = 0; i < shoppingcart.size(); i++)
{
if (shoppingcart[i]->getName() == entry->getName()) {
shoppingcart[i]->addNum();
return;
}
}
shoppingcart.push_back(entry);
entry->resetNum();
shoppingcart[i]->addNum();
}
/*
* Show the content of the cart to user interface.
* INPUT: None.
* OUTPUT: None.
*/
void showCart() {
int Num = 0;
for (int i = 0; i < shoppingcart.size(); i++) {
Num++;
cout << Num << "." << endl;
shoppingcart[i]->detail(shoppingcart[i]->getNum());
}
}
/*
* Return the cart size. (The same object must be seen as one entry)
* INPUT: None.
* OUTPUT: Integer. The cart size.
*/
int size() {
int size = 0;
for (int i = 0; i < shoppingcart.size(); i++)
{
size++;
}
return size;
}
/*
* Remove an entry from the cart including the amount of the commodity.
* INPUT: The order of the entry.
* OUTPUT: None.
*/
void remove(int index) {
it = shoppingcart.begin();
shoppingcart.erase(it + index);
return;
}
/*
* Check the total amount of price for the user and clear the list after checkout.
* INPUT: None.
* OUTPUT: Integer. The total price.
*/
int checkOut() {
int total = 0;
for (int i = 0; i < shoppingcart.size(); i++) {
total = total + (shoppingcart[i]->getPrice() * shoppingcart[i]->getNum());
}
shoppingcart.clear();
return total;
}
/*
* Check if the cart have nothing inside.
* INPUT: None.
* OUTPUT: Bool. True if the cart is empty, otherwise false.
*/
bool empty() {
if (shoppingcart.empty() == true)
return true;
else return false;
}
};
/*
* The Store class manage the flow of control, and the interface showing to the user.
* Store use status to choose the interface to show.
*/
class Store {
private:
enum UMode { USER, MANAGER } userStatus;
enum SMode { OPENING, DECIDING, SHOPPING, CART_CHECKING, CHECK_OUT, MANAGING, CLOSE } storeStatus;
CommodityList commodityList;
ShoppingCart cart;
void commodityInput() {
Commodity* ptr;
cout << "Which type of commodity you want to add?" << endl;
cout << "1. Computer Monitor, 2. Mouse, 3. USB" << endl;
int choice = InputHandler::getInput(3);
string a;
if (choice == 1) {
ptr = new ComputerMonitor();
a = "ComputerMonitor";
ptr->userSpecifiedCommodity();
if (commodityList.isExist(ptr)) {
cout << "[WARNING] " << ptr->getName() << " is exist in the store. If you want to edit it, please delete it first" << endl;
}
else {
commodityList.add(ptr, a);
}
}
else if (choice == 2) {
Mouse* ptr = new Mouse;
ptr->userSpecifiedCommodity();
a = "Mouse";
if (commodityList.isExist(ptr)) {
cout << "[WARNING] " << ptr->getName() << " is exist in the store. If you want to edit it, please delete it first" << endl;
}
else {
commodityList.add(ptr, a);
}
}
else {
USB* ptr = new USB;
ptr->userSpecifiedCommodity();
a = "USB";
if (commodityList.isExist(ptr)) {
cout << "[WARNING] " << ptr->getName() << " is exist in the store. If you want to edit it, please delete it first" << endl;
}
else {
commodityList.add(ptr, a);
}
}
}
void deleteCommodity() {
if (commodityList.empty()) {
cout << "No commodity inside the store" << endl;
return;
}
int choice;
cout << "There are existing commodity in our store:" << endl;
commodityList.showCommoditiesName();
cout << "Or type 0 to regret" << endl
<< "Which one do you want to delete?" << endl;
choice = InputHandler::getInput(commodityList.size());
if (choice != 0) {
commodityList.remove(choice - 1);
}
}
void showCommodity() {
if (commodityList.empty()) {
cout << "No commodity inside the store" << endl;
return;
}
cout << "Here are all commodity in our store:" << endl;
commodityList.showCommoditiesDetail();
cout << endl;
}
void askMode() {
string input;
cout << "Are you a general user or a manager?" << endl
<< "1. general user, 2. manager" << endl
<< "Or type 0 to close the store" << endl;
int choice = InputHandler::getInput(2);
userStatus = (choice == 2) ? UMode::MANAGER : UMode::USER;
if (choice == 0) {
storeStatus = SMode::CLOSE;
}
else if (userStatus == UMode::USER) {
storeStatus = SMode::DECIDING;
}
else if (userStatus == UMode::MANAGER) {
storeStatus = SMode::MANAGING;
}
}
void decideService() {
string input;
cout << "Below are our service:" << endl
<< "1. Buy the commodity you want" << endl
<< "2. Check your shopping cart" << endl
<< "3. Check out" << endl
<< "Or type 0 to exit user mode" << endl
<< "You may choose what you need:" << endl;
int choice = InputHandler::getInput(3);
if (choice == 1) {
storeStatus = SMode::SHOPPING;
}
else if (choice == 2) {
storeStatus = SMode::CART_CHECKING;
}
else if (choice == 3) {
storeStatus = SMode::CHECK_OUT;
}
else if (choice == 0) {
storeStatus = SMode::OPENING;
}
}
void chooseCommodity() {
string input;
showCommodity();
cout << "Or input 0 to exit shopping" << endl;
int choice = InputHandler::getInput(commodityList.size());
// Push the commodity into shopping cart here
if (choice == 0) {
storeStatus = SMode::DECIDING;
}
else {
cart.push(commodityList.get(choice - 1));
}
}
void showCart() {
if (cart.empty()) {
cout << "Your shopping cart is empty" << endl;
storeStatus = SMode::DECIDING;
return;
}
int choice;
do {
cout << "Here is the current cart content:" << endl;
cart.showCart();
cout << "Do you want to delete the entry from the cart?" << endl
<< "1. yes, 2. no" << endl;
choice = InputHandler::getInput(2, true);
if (choice == 1) {
cout << "Which one do you want to delete(type the commodity index)?" << endl
<< "Or type 0 to regret" << endl;
int index = InputHandler::getInput(cart.size());
if (index == 0) {
break;
}
cart.remove(index - 1);
}
} while (choice == 1);
cout << "Do you want to checkout?" << endl
<< "1. yes, 2. No, I want to buy more" << endl;
choice = InputHandler::getInput(2, true);
if (choice == 1) {
storeStatus = SMode::CHECK_OUT;
}
else {
storeStatus = SMode::DECIDING;
}
}
void checkOut() {
if (cart.empty()) {
cout << "Your shopping cart is empty, nothing can checkout" << endl;
}
else {
cout << "Here is the current cart content:" << endl;
cart.showCart();
cout << "Are you sure you want to buy all of them?" << endl
<< "1. Yes, sure, 2. No, I want to buy more" << endl;
int choice = InputHandler::getInput(2, true);
if (choice == 1) {
int amount = cart.checkOut();
cout << "Total Amount: " << amount << endl;
cout << "Thank you for your coming!" << endl;
cout << "------------------------------" << endl << endl;
}
}
storeStatus = SMode::DECIDING;
}
void managerInterface() {
cout << "Here are some manager services you can use:" << endl
<< "1. Add new commodity" << endl
<< "2. Delete commodity from the commodity list" << endl
<< "3. Show all existing commodity" << endl
<< "Or type 0 to exit manager mode" << endl
<< "Which action do you need?" << endl;
int choice = InputHandler::getInput(3);
if (choice == 1) {
commodityInput();
}
else if (choice == 2) {
deleteCommodity();
}
else if (choice == 3) {
showCommodity();
}
else if (choice == 0) {
storeStatus = SMode::OPENING;
}
}
void userInterface() {
if (storeStatus == SMode::OPENING) {
askMode();
}
else if (storeStatus == SMode::DECIDING) {
decideService();
}
else if (storeStatus == SMode::SHOPPING) {
chooseCommodity();
}
else if (storeStatus == SMode::CART_CHECKING) {
showCart();
}
else if (storeStatus == SMode::CHECK_OUT) {
checkOut();
}
else if (storeStatus == SMode::MANAGING) {
managerInterface();
}
else if (storeStatus == SMode::CLOSE) {
return;
}
}
public:
Store() {
userStatus = UMode::USER;
storeStatus = SMode::CLOSE;
}
void open() {
commodityList.load();
storeStatus = SMode::OPENING;
while (storeStatus != SMode::CLOSE) {
userInterface();
}
commodityList.save();
}
};
int main() {
Store csStore;
csStore.open();
return 0;
}
| true |
fff17935182a5283075bb7ab8fd804637b64e064 | C++ | fuzzpault/UIndy-CSCI240-2018 | /W15-HashTables/Lab15-HashTable-Starter/HashTable.h | UTF-8 | 2,205 | 3.578125 | 4 | [] | no_license | #ifndef HASHTABLE_H
#define HASHTABLE_H
/* Name: // Fill me in
Date: Dec 3, 2018
Desc: Hash table implementation
*/
#include <string>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include <vector>
using namespace std;
struct TableEntry_t{
string thing;
bool stored;
};
class HashTable{
private:
// Fill me in
vector<TableEntry_t> table;
unsigned my_size;
public:
HashTable(){
my_size = 0;
table = vector<TableEntry_t>(20);
for(unsigned i = 0; i < 20; i++){
table[i].stored = false;
table[i].thing = "";
}
}
unsigned size() const{
return my_size;
}
float loadFactor() const{
unsigned count = 0;
for(unsigned i = 0; i < table.size(); i++){
if(table[i].stored)count++;
}
return (float)count / (float)table.size();
}
void insert(const string &thing){
unsigned loc = myHash(thing) % table.size();
if(table[loc].stored && table[loc].thing == thing)return; // Already there!
unsigned loop_start = loc;
while(table[loc].stored){
loc++;
loc = loc % table.size();
if(loc == loop_start){
cout << "Table is full!" << endl;
return; // Can't be stored, table full!
}
}
table[loc].stored = true;
table[loc].thing = thing;
my_size++;
}
bool contains(const string &thing) const{
unsigned loc = myHash(thing) % table.size();
unsigned loop_start = loc;
while(table[loc].stored){
if(table[loc].thing == thing)return true;
loc++;
loc = loc % table.size();
if(loc == loop_start)return false; // Can't be found, table full!
}
return false;
}
void remove(const string &thing){
// Fill me in.
}
private:
unsigned myHash(const string &thing) const{
unsigned c = 0;
for(unsigned i = 0; i < thing.length(); i++){
c = c + thing[i];
}
return c;
}
};
#endif
| true |
c4a4929f784b3aad5fe5feadd9687f7849e47254 | C++ | Lee-DongWon/Baekjoon_Problems | /2753.cpp | UTF-8 | 319 | 2.546875 | 3 | [] | no_license | #include <stdio.h>
int main() {
int n;
int result;
scanf("%d", &n);
if (n % 4 != 0) {
result = 0;
}
else {
if (n % 100 != 0) {
result = 1;
}
else {
if (n % 400 == 0) {
result = 1;
}
else {
result = 0;
}
}
}
printf("%d", result);
return 0;
} | true |
ee5d2f540515c222b32ac23b0a7af748e6a6ae40 | C++ | rahuls-19/c | /cut_rod.cpp | UTF-8 | 578 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
using namespace std;
int cut_rod(int p[],int n);
int memo_cut_rod_aux(int p[],int n,int r[]);
int main(void){
int p[100];
int n,i,t;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
t=cut_rod(p,n);
printf("%d",t);
return 0;
}
int cut_rod(int p[],int n){
int r[100],i;
for(i=1;i<=n;i++)
r[i]=-1;
return memo_cut_rod_aux(p,n,r);
}
int memo_cut_rod_aux(int p[],int n,int r[]){
int i,q;
if(r[n]>=0)
return r[n];
if(n==0)
q = 0;
else
q=-1;
for(i=1;i<=n;i++)
q=max(q,p[i]+memo_cut_rod_aux(p,n-i,r));
r[n]=q;
return q;
}
| true |
ff828a2272c925625b655f9d9ff0f8a3f2c5aaaf | C++ | BITXUJI/C---primer--code-note | /numbered-p448.cpp | UTF-8 | 598 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <cstdlib>
class numbered
{
public:
numbered() : mysn(std::rand()) {}
numbered(const numbered &s) : mysn(std::rand()) {}
numbered &operator=(const numbered &s)
{
mysn = std::rand();
return *this;
}
int mysn;
};
void f(const numbered &s) { std::cout << s.mysn << std::endl; }
int main(int argc, char const *argv[])
{
// numbered a, b = a, c = b;
numbered a, b, c;
b = a;
c = a;
std::cout << a.mysn << " " << b.mysn << " " << c.mysn << std::endl;
f(a);
f(b);
f(c);
return 0;
}
| true |
a4115ebca92242d1b8f112d433eb390e2058137c | C++ | AljonViray/CPP_Coursework | /proj3/HashMap.cpp | UTF-8 | 9,236 | 3.359375 | 3 | [] | no_license | // HashMap.cpp
//
// Code made by Aljon Viray, ID: 86285526
// ICS 45C Winter 2019
// Project #3: Maps and Legends
#include "HashMap.hpp"
namespace
{
unsigned int myHasher(const std::string& string)
{
unsigned int hashNumber = 0;
//Sum up ascii/int value of each character in the string
for (int i = 0; i < string.length(); i++)
{
hashNumber += (int)(string[i]);
}
//Return raw hash number
return hashNumber;
}
unsigned int getHashIndex(const HashMap::HashFunction& hasher, const std::string& key, const int& numOfBuckets)
{
unsigned int i = (hasher(key) % numOfBuckets);
return i;
}
}
////////////////////////////////////////////
//Constructor 1 (Uses myHasher)
HashMap::HashMap()
: hasher{myHasher}, numOfBuckets{initialBucketCount}, hashmapSize{0}
{
//Create new dynamically-allocated array of Node pointers/linked lists (aka "buckets")
bucketArray = new Node*[numOfBuckets];
//Fill bucketArray with null pointers
fillWithNull(numOfBuckets, bucketArray);
}
//Constructor 2 (Uses given hasher from unit tests or graders)
HashMap::HashMap(HashFunction hasher)
: hasher{hasher}, numOfBuckets{initialBucketCount}, hashmapSize{0}
{
bucketArray = new Node*[numOfBuckets];
fillWithNull(numOfBuckets, bucketArray);
}
//Destructor
HashMap::~HashMap()
{
clearAll();
delete[] bucketArray;
}
//Copy Constructor
HashMap::HashMap(const HashMap& hm)
: hasher{hm.hasher}, numOfBuckets{hm.numOfBuckets}, hashmapSize{hm.hashmapSize}
{
bucketArray = new Node*[numOfBuckets];
fillWithNull(numOfBuckets, bucketArray);
copyBucketArray(numOfBuckets, hm.bucketArray, bucketArray);
}
//Assignment Operator
HashMap& HashMap::operator=(const HashMap& hm)
{
if(this != &hm)
{
//Destruct/Delete this HashMap's contents
this->~HashMap();
//Overwrite bucketArray
bucketArray = new Node*[numOfBuckets];
fillWithNull(numOfBuckets, bucketArray);
copyBucketArray(numOfBuckets, hm.bucketArray, bucketArray);
//Overwrite attributes
hasher = hm.hasher;
hashmapSize = hm.hashmapSize;
numOfBuckets = hm.numOfBuckets;
}
//Return the overwritten HashMap object
return *this;
}
////////////////////////////////////////////
//Public Functions
void HashMap::add(const std::string& key, const std::string& value)
{
if (contains(key) == false)
{
if (loadFactor() >= 0.8)
{
//Remember original size between rehashing process, since no Nodes are deleted
int x = size();
rehashBucketArray(numOfBuckets, bucketArray);
hashmapSize = x;
}
//Create new Node at "head" of linked list, with given values
addNode(key, value, bucketArray, getHashIndex(hasher, key, numOfBuckets));
// Print out memory address & array index of new Node
// std::cout << "New Node = " << bucketArray[getHashIndex(hasher, key, numOfBuckets)] << std::endl;
// std::cout << key << " --> " << getHashIndex(hasher, key, numOfBuckets) << std::endl;
printAllNodes(numOfBuckets, bucketArray);
//Add 1 "pair of key/value" to the HashMap
hashmapSize++;
}
}
void HashMap::remove(const std::string& key)
{
if(contains(key) == true)
{
//Note: Saying bucketArray[i] gives THE NODE ITSELF, not pointer
const int i = getHashIndex(hasher, key, numOfBuckets);
Node* savedNode;
//Checks if head/first Node of bucket/linked list is to be removed
if(bucketArray[i]->key == key)
{
//Remember the next Node's position
savedNode = bucketArray[i]->next;
//Delete current Node
delete bucketArray[i];
//Set current Node to point to the the one we saved earlier
bucketArray[i] = savedNode;
hashmapSize--;
}
//Iterate through bucket/linked list at index i to find key
else
{
Node* currentNode = bucketArray[i];
while(currentNode->key != key && currentNode != nullptr)
{
//Remember current Node to re-link things later
savedNode = currentNode;
//Move on to next node
currentNode = currentNode->next;
}
//Once while loop finishes, that means we found the key we wanted
//The prev Node's next is set to the to-be-deleted Node's next.
//AKA the linked list skips the node we are about to delete
savedNode->next = currentNode->next;
//The Node we wanted is deleted
delete currentNode;
hashmapSize--;
}
printAllNodes(numOfBuckets, bucketArray);
}
}
bool HashMap::contains(const std::string& key) const
{
// Look at the bucket associated with the key
Node* currentNode = bucketArray[getHashIndex(hasher, key, numOfBuckets)];
while(currentNode != nullptr)
{
if(currentNode->key == key)
{
return true;
break;
}
currentNode = currentNode->next;
}
return false;
}
std::string HashMap::value(const std::string& key) const
{
if(contains(key) == false)
{
return "";
}
else
{
// Look at the bucket associated with the key
Node* currentNode = bucketArray[getHashIndex(hasher, key, numOfBuckets)];
while(currentNode != nullptr)
{
if(currentNode->key == key)
{
break;
}
else
{
currentNode = currentNode->next;
}
}
return currentNode->value;
}
}
unsigned int HashMap::size() const
{
return hashmapSize;
}
unsigned int HashMap::bucketCount() const
{
return numOfBuckets;
}
double HashMap::loadFactor() const
{
double x = size();
return (x / bucketCount());
}
unsigned int HashMap::maxBucketSize() const
{
int max = 0, temp = 0;
for(int i = 0; i < numOfBuckets; i++)
{
Node* currentNode = bucketArray[i];
//Add 1 for every non-null Node
while(currentNode != nullptr)
{
temp++;
currentNode = currentNode->next;
}
//Replace current max amount, if applicable
if(temp > max)
{
max = temp;
}
temp = 0;
}
return max;
}
////////////////////////////////
//Private Functions
void HashMap::fillWithNull(const unsigned int& numOfBuckets, Node**& bucketArray)
{
for (int i = 0; i < numOfBuckets; i++)
{
bucketArray[i] = nullptr;
}
}
void HashMap::addNode(const std::string& key, const std::string& value, Node**& bucketArray, const int i)
{
//Initialize new Node struct
Node* newNode = new Node;
//Fill new Node with given values
newNode->key = key;
newNode->value = value;
newNode->next = bucketArray[i]; //Next equals the new "head" for that bucket/linked list
//Place a new Node in the current position
bucketArray[i] = newNode;
}
void HashMap::rehashBucketArray(unsigned int& numOfBuckets, Node**& bucketArray)
{
//Doubles and adds 1 to numOfBuckets
unsigned int newNumOfBuckets = (numOfBuckets*2) + 1;
//Create new bucketArray & initialize it
Node** newBucketArray = new Node*[newNumOfBuckets];
fillWithNull(newNumOfBuckets, newBucketArray);
//Go through old bucketArray, take its Nodes' data, and rehash Nodes to newBucketArray
copyBucketArray(numOfBuckets, bucketArray, newBucketArray);
//Overwrite variables
this->~HashMap();
numOfBuckets = newNumOfBuckets;
bucketArray = newBucketArray;
}
void HashMap::copyBucketArray(const unsigned int& numOfBuckets, Node** const oldBucketArray, Node**& newBucketArray)
{
for (int i = 0; i < numOfBuckets; i++)
{
Node* currentNode = oldBucketArray[i];
while(currentNode != nullptr)
{
addNode(currentNode->key, currentNode->value, newBucketArray, getHashIndex(hasher, currentNode->key, numOfBuckets));
currentNode = currentNode->next;
}
}
}
//For testing purposes
void HashMap::printAllNodes(const unsigned int& numOfBuckets, Node**& bucketArray) const
{
for(int i = 0; i < numOfBuckets; i++)
{
Node* currentNode = bucketArray[i];
std::cout << i << ") " << currentNode;
while(currentNode != nullptr)
{
currentNode = currentNode->next;
std::cout << " --> " << currentNode;
}
std::cout << std::endl;
}
}
//Helper Function
void HashMap::clearAll()
{
for(int i = 0; i < numOfBuckets; i++)
{
Node* currentNode = bucketArray[i];
Node* savedNode;
//Finds every key in order and removes them normally
while(currentNode != nullptr)
{
savedNode = currentNode->next;
delete currentNode;
currentNode = savedNode;
}
bucketArray[i] = nullptr;
}
//Reset size
hashmapSize = 0;
} | true |
41a25c2704cc63903c697559d166baa204652aec | C++ | kylechow2580/GreyPhotoGenerator | /main.cpp | UTF-8 | 968 | 2.59375 | 3 | [] | no_license | #include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
using namespace cv;
int main(){
string folderName = "Input/";
cout << "Num of photo: ";
int num;
cin >> num;
cout << "Output format: ";
string format;
cin >> format;
for(int i=1;i<=num;i++)
{
stringstream ss;
ss << folderName << i << ".jpg";
string filename = ss.str();
Mat image = imread(filename);
Mat gray_image;
cvtColor( image, gray_image, CV_BGR2GRAY);
imshow("Image",image);
stringstream outputss;
outputss << "Output/" << i << format;
string outputfilename = outputss.str();
imwrite(outputfilename,gray_image);
}
cout << "All files converted completely" << endl;
}
| true |
bee788fcd03928336e6c556972cf88b091027d23 | C++ | DASnoeken/cppLinAlg | /MatrixException.h | UTF-8 | 311 | 2.71875 | 3 | [] | no_license | #pragma once
#include <string>
#include <exception>
class MatrixException: public std::exception
{
public:
MatrixException(const char* name);
const char* getWhat() const;
std::string toString();
friend std::ostream& operator<<(std::ostream& os, const MatrixException& me);
private:
std::string _what;
};
| true |
15ff35b7769957fde378b2f4b249228aa5aa4895 | C++ | leroy-0/Piscine_CPP | /cpp_d10/ex01/Character.cpp | UTF-8 | 1,554 | 2.9375 | 3 | [] | no_license | //
// Character.cpp for Project-Master in /home/tekm/tek1/cpp_d10/ex01
//
// Made by leroy_0
// Login <leroy_0@epitech.eu>
//
// Started on Fri Jan 13 13:07:10 2017 leroy_0
// Last update Fri Jan 13 13:07:10 2017 leroy_0
//
#include <iostream>
#include <string>
#include "Character.hh"
#include "AWeapon.hh"
Character::Character(const std::string name)
{
this->_ap = 40;
this->_name = name;
this->_weapon = NULL;
}
Character::~Character() {}
const std::string& Character::getName() const
{
return (this->_name);
}
int Character::getAP() const
{
return (this->_ap);
}
AWeapon *Character::getWeapon() const
{
return (this->_weapon);
}
void Character::recoverAP()
{
this->_ap += 10;
if (this->_ap > 40)
this->_ap = 40;
}
void Character::equip(AWeapon *weapon)
{
this->_weapon = weapon;
}
void Character::attack(AEnemy *enemy)
{
if (this->_ap >= this->_weapon->getAPCost())
{
std::cout << this->getName() << " attacks " << enemy->getType() << " with a " << this->_weapon->getName() << std::endl;
this->_ap -= this->_weapon->getAPCost();
this->getWeapon()->attack();
enemy->takeDamage(this->_weapon->getDamage());
if (enemy->getHP() <= 0)
enemy->~AEnemy();
}
}
std::ostream& operator<<(std::ostream & os, const Character & character)
{
if (character.getWeapon())
os << character.getName() << " has " << character.getAP() << " AP and wields a " << character.getWeapon()->getName() << std::endl;
else
os << character.getName() << " has " << character.getAP() << " and is unarmed" << std::endl;
return (os);
} | true |
be0e598d9dc5c007a68f040329d1d1d8a78a9627 | C++ | weld-project/clamor | /clamor/net-util.h | UTF-8 | 1,104 | 3.1875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef NET_UTIL_H
#define NET_UTIL_H
#include <boost/functional/hash.hpp>
#include <stdint.h>
#include <string>
typedef struct Addr {
std::string ip;
uint32_t port;
Addr() {
ip = "";
port = 0;
}
Addr(std::string s_ip, uint32_t s_port) {
ip = s_ip;
port = s_port;
}
std::string str() const {
return ip + ":" + std::to_string(port);
}
std::string str_port() const {
return std::to_string(port);
}
bool operator==(const Addr &other) {
return ip == other.ip && port == other.port;
}
} Addr;
inline Addr empty_addr() {
Addr ret;
ret.ip = "";
ret.port = 0;
return ret;
}
inline bool operator==(const Addr & lhs, const Addr & rhs) {
return ((lhs.ip == rhs.ip) &&
(lhs.port == rhs.port));
}
inline bool operator!=(const Addr & lhs, const Addr & rhs) {
return ((lhs.ip != rhs.ip) ||
(lhs.port != rhs.port));
}
template<>
struct std::hash<Addr> {
std::size_t operator()(const Addr& a) const {
size_t h = 0;
boost::hash_combine(h, a.ip);
boost::hash_combine(h, a.port);
return h;
}
};
#endif // NET_UTIL_H
| true |
2d8ce537343ba9d1dcecde98207bca79de41b215 | C++ | lurker0/PEkernel | /project/pipe_windbg/pipe_windbg/pipe_windbg.cpp | GB18030 | 1,721 | 2.59375 | 3 | [] | no_license | // pipe_windbg.cpp : ̨Ӧóڵ㡣
//
// NamedPipe_host.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include "windows.h"
HANDLE gPipeHnd = NULL;
BOOLEAN
BlComInitialize(
UINT8 PortNumber,
UINT32 BaudRate
)
{
return TRUE;
}
BOOLEAN
BlComSendByte(
UINT8 PortNumber,
UINT8 Byte
)
{
DWORD dwWritten;
if (!WriteFile(gPipeHnd, &Byte, 1, &dwWritten, NULL))
{
printf("WriteFile failed\n");
return FALSE;
}
return TRUE;
}
BOOLEAN
BlComDataAvailable(
UINT8 PortNumber
)
{
return TRUE;
}
UINT8
BlComReceiveByte(
UINT8 PortNumber
)
{
UINT8 byte=0;
DWORD dwWritten;
if (!ReadFile(gPipeHnd, &byte, 1, &dwWritten, NULL))
{
printf("ReadFile failed\n");
return 0;
}
return byte;
}
#define THE_PIPE L"\\\\.\\pipe\\testpipe"
VOID
BlKdInitialize(
VOID
);
BOOLEAN
BlKdPrintf(
PCSTR Format,
...
);
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hOut;
WCHAR buf[1024];
DWORD len;
DWORD dwWritten;
hOut = CreateNamedPipe(THE_PIPE, // Name
PIPE_ACCESS_DUPLEX | WRITE_DAC, // OpenMode
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // PipeMode
2, // MaxInstances
1024, // OutBufferSize
1024, // InBuffersize
2000, // TimeOut
NULL); // Security
if (hOut == INVALID_HANDLE_VALUE)
{
printf("Could not create the pipe\n");
exit(1);
}
printf("hPipe=%p\n", hOut);
wprintf(L"pipe:%s\n",THE_PIPE);
gPipeHnd = hOut;
printf("connect...\n");
ConnectNamedPipe(hOut, NULL);
printf("...connected\n");
BlKdInitialize();
for (int i = 0; i < 50; i++)
{
BlKdPrintf("Test Pipe %d\n", i );
}
DisconnectNamedPipe(hOut);
CloseHandle(hOut);
return 0;
}
| true |
4d70beda01ae6c842992bbcd5e1b3f0bca632024 | C++ | Rasec09/Algorithms_and_Data_Structures | /Graph/TopologicalSort.cpp | UTF-8 | 2,512 | 2.96875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
const int INF = 1e9;
vector<vi> AdjList;
vi dfs_num, topologicalSort, dist, numPaths;
void OrdenTopologico(int u) {
dfs_num[u] = 1;
for (int i = 0; i < AdjList[u].size(); ++i) {
int v = AdjList[u][i];
if (dfs_num[v] == -1)
OrdenTopologico(v);
}
topologicalSort.push_back(u);
}
// Orden topologico lexicograficamente menor
vi topologicalSort(vector<vi> &AdjList, int V) {
vi orden;
vi in_degree(V, 0);
for (int i = 0; i < V; i++) {
for (int j = 0; j < AdjList[i].size(); j++) {
in_degree[AdjList[i][j]]++;
}
}
priority_queue<int, vector<int>, greater<int> > q;
for (int i = 0; i < V; i++)
if (in_degree[i] == 0)
q.push(i);
while (!q.empty()) {
int v = q.top();
q.pop();
orden.push_back(v);
for (int i = 0; i < AdjList[v].size(); i++) {
in_degree[AdjList[v][i]]--;
if (in_degree[AdjList[v][i]] == 0)
q.push(AdjList[v][i]);
}
}
return orden;
}
//Caminos mas largo en un DAG desde la fuente s requiere el topoSort
int longestPath(int V, int s) {
dist.assign(V, -INF); //Cambiar -INF por 0 si no hay fuente
dist[s] = 0;
for (int i = 0; i < topologicalSort.size(); i++) {
int u = topologicalSort[i];
if (dist[u] != -INF) { //Quitar este if si no hay fuente
for (int j = 0; j < AdjList[u].size(); j++) {
int v = AdjList[u][j];
if (dist[v] < dist[u] + 1) // Cambiar el < a > para el camino mas corto
dist[v] = dist[u] + 1;
}
}
}
int longest = -INF;
for (int i = 0; i < dist.size(); i++) {
longest = max(longest, dist[i]);
}
return longest;
}
//Cuenta el numero de caminos en un DAG requiere el topoSort
int countPaths(int V) {
numPaths.assign(V, 0);
numPaths[0] = 1;
for (int i = 0; i < topologicalSort.size(); i++) {
int u = topologicalSort[i];
for (int j = 0; j < AdjList[u].size(); j++) {
int v = AdjList[u][j];
numPaths[v] += numPaths[u];
}
}
int paths = 0;
for (int i = 0; i < AdjList.size(); i++)
if (AdjList[i].empty())
paths += numPaths[i];
return paths;
}
int main() {
int V, E, u, v;
scanf("%d %d", &V, &E);
AdjList.assign(V, vi());
while (E--) {
scanf("%d %d", &u, &v);
AdjList[u].push_back(v);
}
dfs_num.assign(V, -1);
topologicalSort.clear();
for (int i = 0; i < V; ++i)
if (dfs_num[i] == -1)
OrdenTopologico(i);
reverse(topologicalSort.begin(), topologicalSort.end());
for (int i = 0; i < topologicalSort.size(); ++i) {
printf("%d ", topologicalSort[i]);
}
printf("\n");
return 0;
}
| true |
2fef8509603abd2f25feb30dc29715da256dc93c | C++ | MatthewMcGonagle/ProgrammingExercises | /cpp/LeetCode002AddTwoNumbers/main.cpp | UTF-8 | 6,057 | 4.03125 | 4 | [] | no_license | /**
main.cpp
Author: Matthew McGonagle
LeetCode Problem 002: Add Two Numbers.
Numbers are represented as a linked list of digits in reverse order. The purpose is to then
make a function Solution::addTwoNumbers that will find the linked list representation of their sum.
Current solution passes as faster than amount between 37% and 55% of all cpp submissions.
**/
#include<iostream> // For testing.
#include<vector> // For constructing test examples.
#include<string>
#include<sstream>
/**
struct ListNode
Definition for singly-linked list. This is taken from LeetCode and must
be defined this way to count as a solution for LeetCode. It is a node
for a linked list.
@member val Value held by node.
@member next Pointer to next node.
**/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/**
class Solution
The class that implements our solution. The call and return structure of the member
function addTwoNumbers is specified by LeetCode.
**/
class Solution {
public:
/**
function addTwoNumbers
If exactly one of the input ListNode* is NULL, then just return the other.
Note this is NOT a copy of the other.
**/
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
private:
/**
function doCarry
Alter the sum of two digits and a carry to find the correct digit here and the
carry for the next digit.
@param sum Reference to the sum of the digits and carry for the current decimal place.
@return The new carry.
**/
inline int doCarry(int &sum);
/**
function carryOneNumber
Do the carries for when there is only one number left.
@param head Pointer to the last digit of the sum that these results will be
attached to.
@param num The list of digits to apply the carries to.
@param carry The carry to apply to the first digit.
**/
void carryOneNumber(ListNode* head, ListNode* num, int carry);
};
/**
function makeList
Turns a non-negative integer into a list for each digit in reverse order
(as specified by the LeetCode problem).
@param n The non-negative integer to turn into a list of digits.
@return The head of the list of the digits in reverse order.
**/
ListNode* makeList(unsigned int n);
/**
function printList
Print a list in order.
@param list The head of the list to print.
@return String representation of list.
**/
std::string printList(ListNode* list);
/**
function deleteList
Delete a list in order.
@param list The head of the list to delete.
**/
void deleteList(ListNode* list);
/////////////////////////////////////
//// main executable
////////////////////////////////////
int main() {
int a = 501049, b = 3209;
ListNode* aList = makeList(a), * bList = makeList(b), * sum;
Solution sol;
std::cout << "a = " << a << std::endl
<< "aList = " << printList(aList) << std::endl
<< "b = " << b << std::endl
<< "bList = " << printList(bList) << std::endl
<< "Testing sum" << std::endl;
sum = sol.addTwoNumbers(aList, bList);
std::cout << "Regular a + b = " << a + b << std::endl
<< "List a + b = " << printList(sum) << std::endl;
deleteList(aList);
return 0;
}
ListNode* Solution::addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* sum, * dummyHead;
int carry = 0, digit;
if (l1 == NULL && l2 == NULL)
return NULL;
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
dummyHead = new ListNode(0);
sum = dummyHead;
// Loop over the digits of both numbers until one is done.
while (l1 != NULL && l2 != NULL) {
sum -> next = new ListNode(0);
sum = sum -> next;
digit = carry;
digit += l1 -> val;
l1 = l1 -> next;
digit += l2 -> val;
l2 = l2 -> next;
carry = doCarry(digit);
sum -> val = digit;
}
// Now check to see if one number still has digits left, else deal with any remaining carry.
if (l1 != NULL)
carryOneNumber(sum, l1, carry);
else if (l2 != NULL)
carryOneNumber(sum, l2, carry);
else if (carry > 0) // Just need to add digit of '1'.
sum -> next = new ListNode(1);
// Clean up dummyHead.
sum = dummyHead -> next;
delete dummyHead;
return sum;
}
int Solution::doCarry(int &sum) {
// Avoid using more costly division and modulo operations.
// Sum of digits and carry is at most 19 (digit 9 + digit 9 + carry 1).
// So cheaper logic tells us the carry operation.
if (sum > 9) {
sum -= 10;
return 1;
}
else {
return 0;
}
}
void Solution::carryOneNumber(ListNode *head, ListNode* num, int carry) {
ListNode *newNum = head;
int digit;
while(num != NULL && carry != 0) {
newNum -> next = new ListNode(0);
newNum = newNum -> next;
digit = num -> val + carry;
carry = doCarry(digit);
newNum -> val = digit;
num = num -> next;
}
if(carry > 0)
newNum -> next = new ListNode(1);
else
newNum -> next = num;
}
ListNode* makeList(unsigned int n) {
ListNode* list = NULL, * head;
if(n == 0)
return new ListNode(0);
list = new ListNode(n % 10);
head = list;
n /= 10;
while(n > 0) {
list -> next = new ListNode( n % 10 );
list = list -> next;
n /= 10;
}
return head;
}
std::string printList(ListNode* list){
std::ostringstream output;
while(list != NULL) {
output << list -> val << ", ";
list = list -> next;
}
return output.str();
}
void deleteList(ListNode* list) {
ListNode* next;
while(list != NULL) {
next = list -> next;
delete list;
list = next;
}
}
| true |
36e67a34f0dc2275f157277cd03502d1b590610e | C++ | cuiopen/GameServer-11 | /tools/FileUtils.h | UTF-8 | 3,048 | 3.203125 | 3 | [] | no_license | /**
* @file FileUtils.h
* @brief 文件工具
* @author zhu peng cheng
* @version 1.0
* @date 2018-01-03
*/
#ifndef _FILE_UTILS_H
#define _FILE_UTILS_H
#include <INIReader.h>
#include <map>
#include <iostream>
#include <sys/stat.h> // stat()
//#include <sys/type.h> // S_IFDIR
//#include <
namespace GameTools
{
class FileUtils
{
public:
/**
* @brief 获取配置map
*
* @param file_path 配置文件路径
*
* @return
*/
static std::map<std::string, std::string> GetConfigMap(const std::string & file_path)
{
std::map<std::string, std::string> config_map;
// 打开配置文件
INIReader reader(file_path);
if(reader.ParseError() < 0)
{
std::cout << "Can't load " << file_path << std::endl;
return config_map;
}
// 网络配置
config_map["net.port"] = reader.Get("net", "port", "9999"); // 端口
// 消息队列
config_map["msg.maxsize"] = reader.Get("msg", "maxsize", "9999"); // 消息队列中最大消息数
// 数据库配置
config_map["db.ip"] = reader.Get("db", "ip", "127.0.0.1"); // 数据库地址
config_map["db.port"] = reader.Get("db", "port", "3306"); // 数据库端口
config_map["db.scheme"] = reader.Get("db", "name", "ddz"); // 数据库名
config_map["db.user"] = reader.Get("db", "user", "root"); // 数据库用户名
config_map["db.password"] = reader.Get("db", "password", "no080740"); // 数据库密码
config_map["db.maxpoolsize"] = reader.Get("db", "maxpoolsize", "10"); // 数据库池最大容量
config_map["db.reconnect"] = reader.Get("db", "reconnect", "true"); // 是否自动重连
config_map["db.checkinterval"] = reader.Get("db", "checkinterval", "10"); // 检查连接间隔
// 日志配置
config_map["log.level"] = reader.Get("log", "level", "trace"); // 日志输出等级
config_map["log.enableconsole"] = reader.Get("log", "enableconsole", "true"); // 控制台输出
config_map["log.async"] = reader.Get("log", "async", "false"); // 异步
config_map["log.queue_size"] = reader.Get("log", "queue_size", "4096"); // 异步输出队列大小
return config_map;
}
/**
* @brief 检查目录是否存在
*
* @param dir_path 目录路径
*
* @return
*/
static bool IsDirExist(const std::string & dir_path)
{
struct stat info;
// 读取文件信息
if(stat(dir_path.c_str(), &info) != 0)
return false;
// 检查是否目录
if(info.st_mode & S_IFDIR)
return true;
return false;
}
static void CreateDir(const std::string & dir_path)
{
mkdir(dir_path.c_str(), 0777);
}
};
}
#endif // _FILE_UTILS_H
| true |
f4a6aa59dcf4bf2a9e8c0806810788b8c97c99de | C++ | aasispaudel/Cplusplus-course-jacobs | /SEM_2/A1/try.cpp | UTF-8 | 575 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main () {
int** matrix = new int*[5];
for (int i = 0; i < 5; i++) {
matrix[i] = new int[8];
}
for (int i =0; i < 5; i++)
for (int j = 0; j < 10; j++)
matrix[i][j] = i*j;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
int** matrix2;
matrix2 = matrix;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
cout << matrix2[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
edc179ed9a2600c05d80bc26dbadf9e3153545e7 | C++ | thiagovas/QIF | /channel/vulnerability/guessing.h | UTF-8 | 1,071 | 2.703125 | 3 | [] | no_license | #ifndef _channel_vulnerability_guessing_h
#define _channel_vulnerability_guessing_h
#include "../channel.h"
#include "vulnerability.h"
namespace channel {
namespace vulnerability {
class Guessing : public Vulnerability {
public:
// V(X)
double VulnerabilityPrior(const Channel& channel) const override;
// V(Y)
double VulnerabilityOut(const Channel& channel) const override;
// V(X|Y)
double VulnerabilityPosterior(const Channel& channel) const override;
// V(Y|X)
double VulnerabilityReversePosterior(const Channel& channel) const override;
// V(X|Y) = max_{y} p(y) * V(X|Y=y)
double VulnerabilityMaxPosterior(const Channel& channel) const;
// V(Y|X) = max_{x} p(x) * V(Y|X=x)
double VulnerabilityMaxReversePosterior(const Channel& channel) const;
// L(X|Y) = V(X|Y) / V(X)
double LeakageMaxPosterior(const Channel& channel) const;
// L(Y|X) = V(Y|X) / V(Y)
double LeakageMaxReversePosterior(const Channel& channel) const;
};
} // namespace vulnerability
} // namespace channel
#endif
| true |
4f6e21696d0ae22065e4805547a6153af2c6895b | C++ | kuningfellow/Kuburan-CP | /yellowfellow-ac/UVA/10646/14229596_AC_0ms_0kB.cpp | UTF-8 | 506 | 2.578125 | 3 | [] | no_license | //UVA 10646 What is the Card?
#include <bits/stdc++.h>
using namespace std;
int main(){
int tc,kas=1;
cin>>tc;
while (tc--){
string ar[52];
for (int i=0;i<52;i++){
cin>>ar[i];
}
int y=0;
int ptr=51-25;
for (int i=0;i<3;i++){
int x=10;
if (ar[ptr][0]>='2'&&ar[ptr][0]<='9')x=ar[ptr][0]-'0';
ptr--;
y+=x;
ptr-=(10-x);
}
printf ("Case %d: ",kas++);
y--;
if (y<=ptr)cout<<ar[y]<<endl;
else cout<<ar[51-25+y-ptr]<<endl;
}
} | true |
4203894c095c9430189ff29fbafa21ccdf2f9590 | C++ | NathPrz/Intro-Cpp | /tinycar/mission5/question2.cpp | UTF-8 | 1,513 | 3.53125 | 4 | [] | no_license | //Programme pour gérer un panier
#include <iostream>
#include <string>
using namespace std;
//Fonction qui calcule et rajoute la TVA pour chaque accesoire.//
double calculePrixTTC(double prixHT)
{
double tva = 0.2;
return prixHT * (1 + tva);
}
int main()
{
//Inisialisation des pointeurs
string *accesoires = nullptr;
double *prixHT = nullptr;
double *prixTTC = nullptr;
//Definition de la taille des tableaux à l'aide de l'utilisateur
int quantiteDAccesoires;
cout << "Bonjour! Combien d'accesoires voulez vous ajouter au panier?";
cin >> quantiteDAccesoires;
accesoires = new string[quantiteDAccesoires];
prixHT = new double[quantiteDAccesoires];
prixTTC = new double[quantiteDAccesoires];
//Boucle qui demande à l'utilisateur les accesoires et leur prix pour inisialiser les tableaux
cout << "Veuillez indiquer l'information qui suive pour chaque accesoire:" << endl;
for (int indice = 0; indice < quantiteDAccesoires; indice++)
{
cout << "Nom: " << endl;
//cin >> accesoires[indice]; NE MARCHE PAS avec d'espaces vides
cin.ignore();
getline(cin, accesoires[indice]);
cout << "Prix HT: " << endl;
cin >> prixHT[indice];
//Appel de la fonction pour calculer le prix TTC, avec le prixHT en paramètre
prixTTC[indice] = calculePrixTTC(prixHT[indice]);
}
//Suppression de pointeurs
delete[] accesoires;
delete[] prixHT;
delete[] prixTTC;
return 0;
} | true |
17ed725dcc2f73ff8cfc66341185b37f97f64d4d | C++ | pablodavid97/cpp-projects | /Polynomial/Polynomial_Driver.cpp | UTF-8 | 1,917 | 3.390625 | 3 | [] | no_license | /*****************************************************
* Polynomial_Driver.cpp
*
* Manejador para pruebas de la clase Polynomial
*
* Crea varios objetos Polynomio y prueba sus
* capacidades.
*/
#include <iostream>
#include <cstdlib>
#include "Polynomial.h"
using namespace std;
Polynomial test1(int d);
Polynomial *test2(Polynomial &p);
void test3(int r, int d, int p);
int main(void)
{
int r = 100, d = 100, p = 100;
Polynomial result1(test1(10));
cout << "result1 : " << result1 << endl;
cout << "Evaluating Polynomial result1 in x = 2..." << endl;
double value = evaluate(result1, 2);
cout << "result1 in x = 2 is: " << value << endl;
Polynomial *result2 = test2(result1);
cout << "\n*result2: " << *result2 << endl;
cout << "Deleting result2..." << endl;
delete result2;
cout << "\nresult1 after deleting result2: " << result1 << endl;
test3(r, d, p);
}
Polynomial test1(int deg)
{
Polynomial retval(deg);
for(int i = 0; i <= deg; i++)
retval.setCoefficient(i, i+1);
return retval;
}
Polynomial *test2(Polynomial &p)
{
return new Polynomial(p);
}
void test3(int rounds, int degs, int numpolys)
{
Polynomial **pArray = new Polynomial *[numpolys];
cout << "Starting " << rounds << " rounds of "
<< numpolys << " operations...";
for(int i = 0; i < rounds; i++)
{
Polynomial sumtotal, difftotal, multtotal;
multtotal.setCoefficient(0, 1);
for(int j = 0; j < numpolys; j++)
{
pArray[j] = new Polynomial(degs);
for(int k = 0; k <= degs; k++)
pArray[j]->setCoefficient(k, rand() % 10 - 5);
sumtotal += *pArray[j];
difftotal -= *pArray[j];
multtotal *= *pArray[j];
}
for(int j = numpolys - 1; j >= 0; j--)
delete pArray[j];
if(i % 10)
cout << ".";
}
cout << "\nDone." << endl;
}
| true |
6c0a31f0a59a852a877bc5c19ad535a7c23bf43a | C++ | klanderfri/CardReaderLibrary | /CardReaderLibrary/WindowsMethods.cpp | UTF-8 | 3,748 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "WindowsMethods.h"
#include <iomanip>
#include <windows.h>
#include <Lmcons.h>
#include "boost\filesystem\path.hpp"
using namespace std;
WindowsMethods::WindowsMethods()
{
}
WindowsMethods::~WindowsMethods()
{
}
string WindowsMethods::ToString(const wstring &wstringToConvert)
{
//Implemented as suggested at:
//https://stackoverflow.com/a/3999597/1997617
if (wstringToConvert.empty()) { return string(); }
size_t originalWstringSizeInCharacters = wstringToConvert.size();
int requiredWstringBufferSizeInBytes
= WideCharToMultiByte(CP_ACP, 0,
&wstringToConvert[0], (int)originalWstringSizeInCharacters,
NULL, 0,
NULL, NULL);
string convertedString(requiredWstringBufferSizeInBytes, 0);
int bytesWrittenToWstringBuffer
= WideCharToMultiByte(CP_ACP, 0,
&wstringToConvert[0], (int)originalWstringSizeInCharacters,
&convertedString[0], requiredWstringBufferSizeInBytes,
NULL, NULL);
if (bytesWrittenToWstringBuffer != originalWstringSizeInCharacters) {
string message = "ERROR: Wrong number of characters converted!";
throw OperationException(message);
}
if (bytesWrittenToWstringBuffer == 0) {
string message = "ERROR: " + GetLastError();
throw OperationException(message);
}
return convertedString;
}
wstring WindowsMethods::ToWString(const string& stringToConvert) {
//Implemented as suggested at:
//https://stackoverflow.com/a/3999597/1997617
if (stringToConvert.empty()) { return wstring(); }
size_t originalStringSizeInCharacters = stringToConvert.size();
int requiredStringBufferSizeInBytes
= MultiByteToWideChar(CP_ACP, 0,
&stringToConvert[0], (int)originalStringSizeInCharacters,
NULL, 0);
wstring convertedWstring(requiredStringBufferSizeInBytes, 0);
int bytesWrittenToStringBuffer
= MultiByteToWideChar(CP_ACP, 0,
&stringToConvert[0], (int)originalStringSizeInCharacters,
&convertedWstring[0], requiredStringBufferSizeInBytes);
if (bytesWrittenToStringBuffer != originalStringSizeInCharacters) {
string message = "ERROR: Wrong number of characters converted!";
throw OperationException(message);
}
if (bytesWrittenToStringBuffer == 0) {
string message = "ERROR: " + GetLastError();
throw OperationException(message);
}
return convertedWstring;
}
wstring WindowsMethods::ToWString(const float& floatToConvert, int numberOfDecimals) {
//Implemented as suggested at
//https://stackoverflow.com/a/29200671/1997617
wstringstream stream;
stream << fixed << setprecision(numberOfDecimals) << floatToConvert;
wstring convertedString = stream.str();
return convertedString;
}
wstring WindowsMethods::AddToEndOfFilename(wstring originalFilename, wstring addition) {
if (addition.empty()) { return originalFilename; }
size_t pointPosition = originalFilename.rfind('.');
wstring filename = originalFilename.substr(0, pointPosition);
wstring extension = originalFilename.substr(pointPosition);
wstring newFilename = filename + addition + extension;
return newFilename;
}
wstring WindowsMethods::GetPathToExeParentDirectory() {
//Implemented as suggested at:
//https://gist.github.com/yoggy/1496617
boost::filesystem::path path(GetPathToExeFile());
wstring tmp = path.parent_path().wstring();
return path.parent_path().wstring() + L"\\";
}
wstring WindowsMethods::GetPathToExeFile() {
//Implemented as suggested at:
//https://gist.github.com/yoggy/1496617
wchar_t path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
return wstring(path);
}
wstring WindowsMethods::GetExeFileName()
{
//Implemented as suggested at:
//https://gist.github.com/yoggy/1496617
boost::filesystem::path path(GetPathToExeFile());
wstring tmp = path.filename().wstring();
return path.filename().wstring();
}
| true |
a11c437b12fba313eb122235651bdc9205bfb7b1 | C++ | Elvis2000717/Cpp | /并查集.cpp | GB18030 | 530 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class UnionFindSet
{
UnionFindSet(int n)
{
//ռ仹ʼ
_v.resize(n, -1);
}
int FindRoot(int x)
{
while (_v[x] >= 0)
{
x = _v[x];
}
return x;
}
bool Union(int x1, int x2)
{
int index1 = FindRoot(x1);
int index2 = FindRoot(x2);
//ͬĸ
if (index1 != index2)
{
return false;
}
_v[index1] += _v[index2];
_v[index2] = index1;
return true;
}
private:
vector<int> _v;
};
int main()
{
return 0;
} | true |
bf44e3a29c9a6a5b47992076ad50d34da77f29bc | C++ | FactorialN/chishiki | /include/computation/geometry/color.h | UTF-8 | 607 | 2.984375 | 3 | [] | no_license | /*
* This file defines the base class of color.
*/
#ifndef __COMPUTATION_GEOMETRY_COLOR_H__
#define __COMPUTATION_GEOMETRY_COLOR_H__
#include <computation/linear/linearhead.h>
/*
* Color class is from Vector class
*/
class Color : public Vector{
public:
/*
* Several Ways to Construct a Color Object
*/
Color():Vector(0.0f, 0.0f, 0.0f){}
Color(const float &x, const float &y, const float &z) : Vector(x, y, z){}
Color(const HomoVector& b) : Vector(b.x(), b.y(), b.z()){}
/*
* A method to convert float color to int RGBColor(0-255)
*/
Color toRGB();
};
#endif | true |
958460c551e72c6c6e9e71a9cabc8c86bb1cb241 | C++ | ZhenyingZhu/ClassicAlgorithms | /src/CPP/src/SolutionCollection.h | UTF-8 | 770 | 2.6875 | 3 | [] | no_license | #ifndef SRC_SOLUTIONCOLLECTION_H_
#define SRC_SOLUTIONCOLLECTION_H_
#include <vector>
namespace myutils {
class SmartPtr;
class SolutionCollection {
/* A singleton class
* Contain a vector of pointers of Solutions
*/
public:
static SolutionCollection* getInstance();
SolutionCollection() { }
~SolutionCollection() { }
void insertSolution(const SmartPtr&);
bool checkSolutions();
size_t solutionsNum();
private:
static SolutionCollection *instance;
std::vector<SmartPtr> solVec;
// Copy construction, don't define to avoid use by mistake
SolutionCollection(const SolutionCollection&);
SolutionCollection& operator=(const SolutionCollection&);
};
} // myutils
#endif /* SRC_SOLUTIONCOLLECTION_H_ */
| true |
1ec3aba6cb89b44623c8bc903fbefcbd909a44bd | C++ | samahuja642/competitive-programming | /atcoder/contest/1st contest/180.cpp | UTF-8 | 390 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie();
cout.tie();
string s;
cin>>s;
reverse(s.begin(),s.end());
for(int i=0;i<s.length();i++){
if(s[i]=='6'){
s[i]='9';
}
else if(s[i]=='9'){
s[i]='6';
}
}
cout<<s<<endl;
return 0;
} | true |
1947b95e6f4ae43be33eb1e8ad74e04d93d67b04 | C++ | prijuly2000/Data-Structure | /Assignment solution/Assignment 2/2/Node.cpp | UTF-8 | 373 | 3.484375 | 3 | [] | no_license | #include"Node.h"
Node::Node(Emp &employee)
{
this->employee=employee;//overload operator=
this->next=NULL;
}
Node *Node::getnext()
{
return next;
}
Emp Node::getdata()
{
return employee;
}
void Node::setnext(Node*next)
{
this->next=next;
}
void Node::display()
{
employee.display();
}
ostream & operator<<(ostream & o,Node & n )
{
o<<n.getdata();
return o;
} | true |
f2f9f7335b4072bf265ef91e4c6041d70eaf1346 | C++ | SorcererX/SepiaStream | /defs/sepia/comm/observerbase.h | UTF-8 | 2,220 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef SEPIA_COMM_OBSERVERBASE_H
#define SEPIA_COMM_OBSERVERBASE_H
// thread
#include <thread>
#include <mutex>
#include <condition_variable>
// containers
#include <vector>
#include <list>
#include <unordered_set>
// protobuf
#include "header.pb.h"
namespace sepia
{
namespace comm
{
class ObserverBase
{
public:
typedef struct {
std::shared_ptr< std::mutex > mutex;
std::shared_ptr< std::condition_variable > cond;
std::vector< char > buffer;
int32_t length;
Header header;
bool data_ready;
bool terminateReceiver;
} ThreadMessageData;
static bool threadReceiver();
static void stopThreadReceiver( std::thread::id a_threadId );
static void enableDebug( bool a_enable );
static bool routeMessageToThreads( const Header* a_header, char* a_buffer, const std::size_t a_size );
static bool resendAllSubscriptions();
static bool debugEnabled();
static std::string commName();
protected:
void initReceiver();
virtual void process( const Header* a_header, const char* a_buffer, std::size_t a_size ) = 0;
void addObserver( const std::string a_name, ObserverBase* a_Observer );
void removeObserver( const std::string a_name );
ObserverBase();
static bool routeToNode( std::thread::id a_node, const Header* a_header, char* a_buffer, const std::size_t a_size );
static bool handleReceive( const Header* a_header, const char* a_buffer, const std::size_t a_size );
static std::shared_ptr< std::mutex > sm_globalMutex;
private:
typedef std::map< std::string, ObserverBase* > ObserverMap;
typedef std::map< std::thread::id, ThreadMessageData > ThreadMap;
typedef std::map< std::string, std::unordered_set< std::thread::id > > MessageNameMap;
static MessageNameMap sm_messageNameToThread;
static thread_local ObserverMap stm_observers;
static thread_local ThreadMessageData* stm_ownData;
static ThreadMap sm_threadData;
static thread_local ObserverBase* stm_router;
static std::list< std::string > sm_subscriptionList;
static bool sm_debugEnabled;
static bool sm_gotIdResponse;
static std::string sm_commName;
};
}
}
#endif // SEPIA_COMM_OBSERVERBASE_H
| true |
bd875f919f654e88043c825f633c9b3b048366cc | C++ | yaojingguo/book-reading | /programming_pearls/column4/5.cc | UTF-8 | 334 | 3.390625 | 3 | [] | no_license | // http://en.wikipedia.org/wiki/Collatz_conjecture
#include <stdio.h>
bool even(int x)
{
return (x & 1) == 0;
}
void f(int x) {
printf("x:\n");
while (x != 1) {
printf(" %d\n", x);
if (even(x))
x /= 2;
else
x = 3 * x + 1;
}
}
int main(int argc, const char *argv[])
{
f(2);
f(7);
return 0;
}
| true |
81c4e92c1064eaff10bbd52a192ce43847439073 | C++ | wrren/piston | /user/library/include/piston/process/injector.h | UTF-8 | 3,724 | 3.359375 | 3 | [] | no_license | #ifndef PISTON_PROCESS_INJECTOR_H
#define PISTON_PROCESS_INJECTOR_H
#include <piston/core/types.h>
#include <piston/process/process.h>
#include <filesystem>
#include <exception>
namespace Piston
{
/**
* @brief Facilitates injection of shared libraries into processes.
*
*/
class Injector
{
public:
typedef Path LibraryPath;
typedef Path ExecutablePath;
typedef std::vector<String> ArgumentList;
enum class InjectMode
{
MODE_INJECT_NEW,
MODE_INJECT_RUNNING
};
class Exception : public std::exception
{
public:
/**
* @brief Construct a new injection exception object
*
* @param what Error message
*/
Exception(const std::string& what);
/**
* @brief Get the human-readable error message for this injection exception
*
* @return Exception message
*/
virtual const char* what() const noexcept override;
private:
std::string m_what;
};
/**
* @brief Attempt to inject the library at the given path into the process with the given ID
*
* @param library_path Path to the library to be injected into the target process
* @param process_id ID of the process into which the library should be injected
* @return true If injection succeeds
* @return false If injection fails
*/
static Injector Inject(const LibraryPath& library_path, Process::IDType process_id);
/**
* @brief Attempt to inject the library at the given path into a new instance of the executable at the given path.
*
* @param library_path Path to the library to be injected into the target executable
* @param executable_path Path to the executable into which the target library should be injected
* @param arguments Command-line arguments passed to the executable
* @return true If injection succeeds
* @return false If injection fails
*/
static Injector Inject(const LibraryPath& library_path, const ExecutablePath& executable_path, const ArgumentList& args = {});
/**
* @brief Get the injection mode for this injection
*
* @return Injection mode
*/
InjectMode GetMode() const;
/**
* @brief Get the path to the library being injected into the target executable or process.
*
* @return Path to the library being injected into the target executable or process.
*/
const LibraryPath& GetLibraryPath() const;
/**
* @brief Get the ID of the process into which a library has been injected.
*
* @return ID of the process into which a library has been injected.
*/
Process::IDType GetProcessID() const;
protected:
/**
* @brief Construct a new injector object
*
* @param mode Injection mode
* @param library_path Path to the library being injected into the target executable or process
* @param process_id Target process for injection
*/
Injector(InjectMode mode, const LibraryPath& library_path, Process::IDType process_id);
private:
/// Injection Mode
InjectMode mMode;
/// Path to the library being injected
LibraryPath mLibraryPath;
/// ID of the process into which the library is being injected
Process::IDType mProcessID;
};
} // namespace Piston
#endif // PISTON_PROCESS_INJECTOR_H | true |
d5dab8f0f4c2ad3f18917e7e5debb4277fd9e633 | C++ | fit087/scientific_programming | /binar.cpp | UTF-8 | 1,280 | 3.0625 | 3 | [] | no_license | /* @file binar.cpp
\brief arquivo binario
Vantagens menor espaco ocupado
Velocidade na Leitura ou escritura pois
poupa o parsing
Leitura direta nao sequencial
*/
#include <iostream> ///< Input and Output on screen and read keyboard
#include <fstream> ///< This library contains the methods for read and write on files
//#include <cstring>
#include <string> ///< This library contains the string type
//#include <iomanip>
using namespace std;
struct estructura
{
int nr;
//char cadena[26];
string cadena;
//char* cadena;
};
int main(int argc, char *argv[])
{
ofstream saida("out_binar.bin", ios::binary);
estructura variavel; ///<
variavel.nr = 5;
//variavel.cadena = "Hola ";
//variavel.cadena = "Hola";
//variavel.cadena = argv[1].c_str();
variavel.cadena = argv[1];
cout << variavel.cadena << endl;
//variavel.cadena = "Hola".c_str();
//variavel.cadena = "Hola\0";
//handle.method((char *) adress_in_memory, size)
// (char*)como sera tratado? como ponteiro para
//caracter (byte by byte) char *)
// sempre sera utilizado (char *) para
// ler byte por byte
saida.write((char *) &variavel, sizeof(estructura));
//system("pause");
}
| true |
4201ff14f1512640f119ece0ccc51b769382ed00 | C++ | william31212/uva | /uva579/uva579.cpp | UTF-8 | 629 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(void){
#ifndef ONLINE_JUDGE
freopen("uva579.in","r",stdin);
freopen("uva579.out","w",stdout);
#endif
float hour=0;
float min=0;
char garbage;
float tmp=0;
float ans=0;
while(cin >> hour >> garbage >> min){
if(hour==0 && min==0){
break;
}
hour = hour * 30;
tmp = min * 0.5;
hour+=tmp;
if(min==0){
min = 60;
}
min = min * 6;
ans = abs(hour-min);
if(ans==360){
ans = 0;
}
else if(ans >= 180){
ans = 360 - ans;
}
printf("%.3f\n",ans);
}
return 0;
} | true |
ae712e931de60e49f922411950c60303dcf854d2 | C++ | ferranmafe/PRO2-Text-Library | /Frase.cc | UTF-8 | 1,147 | 3.09375 | 3 | [] | no_license | /** @file Frase.cc
@brief Còdig de la classe Frase
*/
#include "Frase.hh"
Frase::Frase(){}
Frase::~Frase(){}
void Frase::modificar_frase( const list<string>& frase ){
//Canvia el contingut del paràmetre frase al que passem per referència.
this->frase = frase;
}
void Frase::modificar_n_paraules(int n_paraules){
//Canvia el contingut del paràmetre valor al que passem per referència.
this->n_paraules = n_paraules;
}
bool Frase::cerca_string(string paraula) const{
//Recorre la frase buscant la paraula passada per referència. Retornem true si la trobem, false en cas contrari
list<string>::const_iterator it = frase.begin();
while (it != frase.end()) {
if (*it == paraula) return true;
++it;
}
return false;
}
list<string> Frase::consultar_frase() const{
//Retorna la llista de strings que formen una frase
return frase;
}
int Frase::consultar_nparaules() const{
//Retorna un int que conté el nº de paraules d'una frase
return n_paraules;
}
| true |