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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b2fe7e5e0e167b6fe01040fd10c668965b6dc605 | C++ | lscooperlee/guitarbox | /drum/src/DrumkitPlayer.cpp | UTF-8 | 736 | 2.59375 | 3 | [] | no_license | #include "DrumkitPlayer.h"
#include "AudioPlayer.h"
#include "DrumPattern.h"
#include "Rhythm.h"
#include <chrono>
DrumkitPlayer::DrumkitPlayer(Rhythm &rhythm_, AudioPlayer &player_)
: rhythm(rhythm_), player(player_){};
void DrumkitPlayer::play(const DrumPattern &pattern_) {
pattern = pattern_;
auto call = [this]() { return callback(); };
auto hit_per_beat = std::get<1>(pattern.size());
rhythm.update(call, hit_per_beat);
}
#include <iostream>
void DrumkitPlayer::callback(void) {
std::cout << "Drumkit play: " << current_pattern << std::endl;
auto [beat, hit] = pattern.size();
player.play(pattern.data()[current_pattern]);
current_pattern = current_pattern >= beat * hit - 1 ? 0 : current_pattern + 1;
}
| true |
db69114006b85e825ec8c312439040eec0a3b23c | C++ | GuillaumeBouchetEpitech/experiment-md3-loader | /main.cpp | UTF-8 | 877 | 3.203125 | 3 | [] | no_license |
#include <iostream>
#include "Game.hh"
#include "RuntimeException.hh"
int main(int argc, char** argv, char** env)
{
static_cast<void>(argc);
static_cast<void>(argv);
bool display = false;
const std::string cmp("DISPLAY=:0.0");
const std::string cmp2("DISPLAY=:0");
for (int i = 0; env[i]; ++i)
if (cmp == env[i] || cmp2 == env[i])
{
display = true;
break;
}
if (!display)
std::cerr << "Bad environment (DISPLAY not present or valid)" << std::endl;
else
{
try
{
Game game;
game.Run();
}
catch (const RuntimeException &exeption)
{
std::cerr << exeption.what() << " in " << exeption.where() << std::endl;
}
catch (const std::bad_alloc &)
{
std::cerr << "Empty memory" << std::endl;
}
catch (...)
{
std::cerr << "Unknown error" << std::endl;
}
}
return (EXIT_SUCCESS);
}
| true |
5335f6328de8b551b48b8666eadaa9e0bd8483c8 | C++ | Gigahawk/cpen333 | /Assignments/Assignment 2/Assignment 2 - Part D, E/Assignment 2 - Part D/Logger.h | UTF-8 | 627 | 2.65625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include <stdarg.h>
using namespace std;
void show_log(bool enable);
class LogMgr {
public:
static LogMgr* get_instance() {
if (inst == nullptr) {
inst = new LogMgr();
}
return inst;
}
bool enable = true;
private:
static LogMgr* inst;
LogMgr() {}
};
class Logger
{
protected:
string log_name = "";
void log(const char* format, ...) {
LogMgr* lm = LogMgr::get_instance();
if (!lm->enable)
return;
printf("[%10s] ", log_name.c_str());
va_list argptr;
va_start(argptr, format);
vprintf(format, argptr);
va_end(argptr);
cout << endl;
}
};
| true |
df7916ce81c72a6315ce3492c77ec884c4daeb0c | C++ | CurrentResident/IncrediBoard | /Core/SuperModifier.h | UTF-8 | 5,772 | 2.734375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-stlport-4.5",
"LicenseRef-scancode-mit-old-style",
"BSL-1.0"
] | permissive | #ifndef SUPER_MODIFIER_H_
#define SUPER_MODIFIER_H_
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/iterator.hpp>
#include "BoardState.h"
#include "Decorators.h"
#include "Key.h"
#include "Platform.h"
namespace SuperModifier
{
struct PressKeys
{
BoardState& state;
bool active;
PressKeys(BoardState& io_state, bool i_isActive) : state(io_state), active(i_isActive) {}
template <uint8_t T_KEY_CODE>
void operator()(Key<T_KEY_CODE>) const
{
state.ChangeKeyState<T_KEY_CODE>(active);
}
template <uint8_t T_KEY_CODE, uint8_t T_MODIFIER>
void operator()(KeyModifier<T_KEY_CODE, T_MODIFIER>) const
{
state.ChangeModifierState<T_KEY_CODE, T_MODIFIER>(active);
}
};
enum StateEnum
{
DISABLED,
MONITORING_FOR_NO_KEYS_DOWN,
MONITORING_FOR_DOWN,
MONITORING_FOR_UP,
PRESSED,
RELEASE
};
void Toggle(StateEnum& io_state)
{
io_state = (io_state == SuperModifier::DISABLED ?
SuperModifier::MONITORING_FOR_NO_KEYS_DOWN :
SuperModifier::DISABLED);
}
template <typename ModifierKeyType, typename OtherKeysCollectionType>
struct Keys
{
Keys():
releaseTime (0),
state (DISABLED)
{}
unsigned long releaseTime;
StateEnum state;
typedef OtherKeysCollectionType OtherKeys;
};
struct UpdateState
{
UpdateState(BoardState& io_boardState) : boardState(io_boardState) {}
BoardState& boardState;
enum ResultEnum
{
NONE,
PRESS,
RELEASE
};
ResultEnum ProcessStateMachine(StateEnum& io_state, unsigned long& io_releaseTime, uint8_t modBit) const
{
ResultEnum result = NONE;
switch(io_state)
{
case MONITORING_FOR_NO_KEYS_DOWN:
if (boardState.m_modifiers == 0 and boardState.m_keyReportArray.size() == 0)
{
io_state = MONITORING_FOR_DOWN;
}
break;
case MONITORING_FOR_DOWN:
if (boardState.m_modifiers & ~modBit or
boardState.m_keyReportArray.size() != 0)
{
io_state = MONITORING_FOR_NO_KEYS_DOWN;
}
else
{
if (boardState.m_modifiers == modBit)
{
io_state = MONITORING_FOR_UP;
}
}
break;
case MONITORING_FOR_UP:
if (boardState.m_modifiers & ~modBit or
boardState.m_keyReportArray.size() != 0)
{
io_state = MONITORING_FOR_NO_KEYS_DOWN;
}
else
{
if (boardState.m_modifiers == 0)
{
io_state = PRESSED;
io_releaseTime = Platform::GetMsec() + 10;
result = PRESS;
}
}
break;
case PRESSED:
if (io_releaseTime < Platform::GetMsec())
{
result = RELEASE;
io_state = MONITORING_FOR_NO_KEYS_DOWN;
io_releaseTime = 0;
}
break;
case DISABLED:
default:
break;
}
return result;
}
template <typename ModifierKeyType, typename OtherKeysCollectionType>
void operator() (Keys<ModifierKeyType, OtherKeysCollectionType>& superMod) const
{
switch(ProcessStateMachine(superMod.state, superMod.releaseTime, ModifierKeyType::MODIFIER))
{
case PRESS:
boost::fusion::for_each(OtherKeysCollectionType(), PressKeys(boardState, true));
break;
case RELEASE:
boost::fusion::for_each(OtherKeysCollectionType(), PressKeys(boardState, false));
break;
default:
break;
}
}
};
};
template <typename SuperModKeysCollection>
class SuperModifierComponent : WithCommands
{
public:
void Process(BoardState& io_state)
{
boost::fusion::for_each(this->m_superModKeys, SuperModifier::UpdateState(io_state));
}
struct ToggleCommand : Console::BaseCommand
{
ToggleCommand() : Console::BaseCommand("supermod")
{ }
void operator()(Console& cons, SuperModifierComponent& me) const
{
boost::fusion::for_each(me.m_superModKeys,
[](auto& superMod)
{
SuperModifier::Toggle(superMod.state);
});
}
};
typedef boost::fusion::vector<ToggleCommand> Commands;
private:
SuperModKeysCollection m_superModKeys;
};
#endif
| true |
07957ba3f897fcf258fdb249a9ecf2abd21c0351 | C++ | hsleung95/gameStruct | /enemyChar.cpp | UTF-8 | 1,034 | 2.8125 | 3 | [] | no_license | //
// enemyChar.cpp
// gameStruct
//
// Created by Wilson Leung on 25/7/2017.
// Copyright © 2017年 Wilson Leung. All rights reserved.
//
#include "enemyChar.hpp"
#include <string>
#include <iostream>
enemyChar::enemyChar(){
expContain = maxHP * 0.5 + maxMP * 0.1 + attack * 4 + defense * 4;
eq = equipment();
eq.randomEquipment(1, *this);
}
float enemyChar::getExpContain(){ return expContain; }
void enemyChar::setExpContain(){ expContain = maxHP * 0.5 + maxMP * 0.1 + attack * 4 + defense * 4; }
void enemyChar::printStat(){
std::cout << "Enemy character value: " << endl;
gameChar::printStat();
std::cout << " exp: " << expContain << endl;
cout << endl;
}
void enemyChar::printEq(){
eq.printEq();
}
string enemyChar::getType(){ return "enemyChar";}
equipment enemyChar::getEquipment(){return eq;}
void enemyChar::randChar(string enemyName,int lv){
gameChar::randChar(lv);
expContain = maxHP * 0.5 + maxMP * 0.1 + attack * 4 + defense * 4;
eq.randomEquipment(lv, *this);
setName(enemyName);
setExpContain();
}
| true |
1afed8caaeccc575271e029d76c0573451043884 | C++ | GilgameshxZero/Computer-Monitor | /Computer Monitor/Utility.cpp | UTF-8 | 2,033 | 2.984375 | 3 | [] | no_license | #include "Utility.h"
namespace CM
{
namespace Utility
{
std::string IntToString (int number)
{
std::ostringstream outstream;
outstream << number;
return outstream.str ();
}
int StringToInt (std::string string)
{
std::istringstream instream (string);
int number;
instream >> number;
return number;
}
int WriteText (HWND hwnd, std::string screen_text, int font_size)
{
HBRUSH bk_brush, original_brush;
HDC hdc = GetDC (hwnd);
HFONT text_font, original_font;
RECT crect;
SIZE text_size;
//First, set the DC to the font of the words to print.
text_font = CreateFont (-MulDiv (font_size, GetDeviceCaps (hdc, LOGPIXELSY), 72), 0, 0, 0, 0, false, false, false, 0, 0, 0, 0, 0, "Verdana");
//If font creation failed, return immediately and exit program.
if (!text_font)
{
MessageBox (NULL, "Font creation failed!", "Error", MB_OK);
PostQuitMessage (-1);
return -1;
}
//Select font
original_font = reinterpret_cast<HFONT>(SelectObject (hdc, text_font));
//Set up the background brush to black, and use the DC to select it.
bk_brush = CreateSolidBrush (RGB (0,0,0));
original_brush = reinterpret_cast<HBRUSH>(SelectObject (hdc, bk_brush));
//Set the text color to white and the text background to black.
SetTextColor (hdc, RGB (255,255,255));
SetBkColor (hdc, RGB (0,0,0));
//Draw the words on the screen, centered, and paint the background.
GetClientRect (hwnd, &crect);
Rectangle (hdc, crect.left, crect.top, crect.right, crect.bottom);
GetTextExtentPoint32 (hdc, screen_text.c_str (), static_cast<int>(screen_text.length ()), &text_size);
TextOut (hdc, crect.right / 2 - text_size.cx / 2, crect.bottom / 2 - text_size.cy / 2, screen_text.c_str (), static_cast<int>(screen_text.length ()));
//Free up the DCs and objects.
SelectObject (hdc, original_font);
SelectObject (hdc, original_brush);
DeleteObject (text_font);
DeleteObject (bk_brush);
ReleaseDC (hwnd, hdc);
return 0;
}
}
} | true |
d555f9f18981f83d77577bd8d246841ef2abc3a2 | C++ | jjsuper/leetcode | /leetcode-viewer/solutions/361.bomb-enemy/bomb-enemy.cpp | UTF-8 | 941 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
if(grid.empty()) return 0;
int row=0;
vector<int> col(grid[0].size(), 0);
int result=0;
for(int i=0; i<grid.size(); ++i)
for(int j=0; j<grid[0].size(); ++j) {
if(!j || grid[i][j-1]=='W') {
row=0;
for(int k=j; k<grid[0].size() && grid[i][k]!='W'; ++k) {
row += grid[i][k]=='E';
}
}
if(!i || grid[i-1][j]=='W') {
col[j]=0;
for(int k=i; k<grid.size() && grid[k][j]!='W'; ++k) {
col[j] += grid[k][j]=='E';
}
}
if(grid[i][j]=='0')
result = max(result, row+col[j]);
}
return result;
}
}; | true |
1076c7baec8b7d9214f9bc48dff43e9bed6ec23b | C++ | ChestnutHeng/LeetCode | /103.binary-tree-zigzag-level-order-traversal.cpp | UTF-8 | 1,416 | 3.1875 | 3 | [] | no_license | /*
* @lc app=leetcode id=103 lang=cpp
*
* [103] Binary Tree Zigzag Level Order Traversal
*/
// @lc code=start
/**
* Definition for a binary tree node.
* 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>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root){
return ans;
}
deque<TreeNode*> q;
q.push_back(root);
//ans.push_back(vector<int>{root->val});
bool isLeft = true;
while(!q.empty()){
deque<TreeNode*> q2;
vector<int> l;
while(!q.empty()){
TreeNode *tra;
tra = q.front();
q.pop_front();
l.push_back(tra->val);
if(tra->left)q2.push_back(tra->left);
if(tra->right)q2.push_back(tra->right);
}
q = q2;
if(!isLeft){
reverse(l.begin(), l.end());
}
isLeft = !isLeft;
if(!l.empty()){
ans.push_back(l);
}
}
return ans;
}
};
// @lc code=end
| true |
c509aeb0a9fd676c87b65185714ae9bc79fe2273 | C++ | ullasreddy-chennuri/GeeksforGeeks | /Count zeros in a sorted matrix.cpp | UTF-8 | 1,953 | 4.125 | 4 | [] | no_license | /*
Given a Binary Square Matrix where each row and column of the matrix is sorted in ascending order.
Find the total number of Zeros present in the matrix.
Input:
The first line of input will be the no of test cases then T test cases will follow.
The second line of each test case contains an integer N denoting the dimension of the matrix.
Then in the next line are the space separated values of the matrix A[ ] [ ].
Output:
Print in a single line, the total number of zeros present in the given Binary Matrix.
User Task:
You don't need to read input or print anything. Your task is to complete the function countZeros()
which takes the Binary Matrix A[][] and its size N as inputs and returns an integer denoting the total number of Zeros present in the matrix.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1<=T<=50
1<=M,N<=1000
0<=A[][]<=1
Example:
Input
2
3
0 0 0 0 0 1 0 1 1
2
1 1 1 1
Output
6
0
Note:The Input/Ouput format and Example given are used for system's internal purpose,
and should be used by a user for Expected Output only. As it is a function problem,
hence a user should not read any input from stdin/console. The task is to complete the function specified,
and not to write the full code.
*/
int b_search(int arr[],int n){
int lo=0,hi=n-1;
int mid;
while(lo<=hi){
mid=(lo+hi)/2;
if(arr[mid]==1){
if(mid==0){
return mid;
}
if(mid>0 && arr[mid-1]==0){
return mid;
}else if(mid>0 && arr[mid-1]==1){
hi=mid-1;
}
}else{
lo=mid+1;
}
}
return -1;
}
int countZeros(int arr[MAX][MAX],int n)
{
//Your code here
int count=0;
for(int i=0;i<n;i++){
int k = b_search(arr[i],n);
if(k!=-1){
count+=k;
}else{
count+=n;
}
}
return count;
}
| true |
3db2401696f9872ff8d1e73208d79e74c5196841 | C++ | GoGoCom/ESP8266 | /1.3 sample/VariableAddress/VariableAddress.ino | UTF-8 | 1,026 | 2.5625 | 3 | [] | no_license |
long weight = 10000;
//char tname[5] = "nest";
char tname[5] = { 'n','e','s','t' };
static char day = 'a';
void test(int ar1, char ar2 )
{
day = 'b';
Serial.print("char day ");
Serial.println( (unsigned long ) &day, HEX);
Serial.print("int ar1 ");
Serial.println( (unsigned long ) &ar1, HEX);
Serial.print("char ar2 ");
Serial.println( (unsigned long ) &ar2, HEX);
}
void setup() {
const double pi = 3.14;
unsigned long long tt;
int score = 80;
delay(2000);
Serial.begin(9600);
Serial.println( sizeof(tt) );
test( 1, 'b' );
Serial.println((unsigned long ) &score, HEX);
Serial.println( sizeof(score));
Serial.print("long weight ");
Serial.println((unsigned long ) &weight, HEX);
Serial.println( sizeof(weight));
Serial.print("float pi ");
Serial.println((unsigned long ) &pi, HEX);
Serial.println( sizeof(pi));
Serial.print("tname ");
Serial.println((unsigned long ) &tname, HEX);
Serial.println( sizeof(tname));
}
void loop() {
// put your main code here, to run repeatedly:
}
| true |
2c17d0fec08cee7d8d555dcf28303c97532a6ead | C++ | Connor-Bowley/neuralNetwork | /include/MSILocations.h | UTF-8 | 1,477 | 2.609375 | 3 | [] | no_license | #include <string>
#include <map>
#include <unordered_map>
#include <vector>
struct Box
{
int32_t species_id;
int32_t x; // top left corner x
int32_t y; // top left corner y
int32_t w; // width
int32_t h; // height
int32_t cx; // center point x
int32_t cy; // center point y
int32_t ex; // bottom right corner x
int32_t ey; // bottom right corner y
uint64_t user_high, user_low;
bool matched = false; // whether we found a matching observation
bool hit = false; //whether we looked at this msi at all
Box();
Box(int32_t species_id, int32_t x, int32_t y, int32_t w, int32_t h, uint64_t user_high, uint64_t user_low);
void load(int32_t species_id, int32_t x, int32_t y, int32_t w, int32_t h, uint64_t user_high, uint64_t user_low);
std::string toString();
};
struct MSI
{
int msi;
bool used = false;
std::vector<Box> boxes;
//bmr => background_misclassified_percentages<species_id, ratio BG classified as species_id>
//for the species_id != BACKGROUND, it is the misclassified ratio
//for the species_id == BACKGROUND, it is the correctly classified ratio
// unordered_map<int,float> bmr;
std::unordered_map<int,int> bmc; // <species_id, pixel count of BG classified as species_id>
int totalBGCount = 0;
int numPixels;
std::string original_image_path = "";
MSI();
MSI(int msi, int numBoxes);
void init(int msi, int numBoxes);
};
void readLocationsFile(const char* filename, std::map<int,MSI> &locations);
int getMSI(std::string filename); | true |
54950ef83662d9b4d9af64ac810be19cbec9eadc | C++ | y2kiah/nebulous | /source/Render/Texture_D3D9.h | UTF-8 | 4,582 | 2.578125 | 3 | [] | no_license | /*----==== TEXTURE_D3D9.H ====----
Author: Jeff Kiah
Orig.Date: 06/21/2009
Rev.Date: 07/07/2009
--------------------------------*/
#pragma once
#include <string>
#include "Resource_D3D9.h"
#include "../Utility/Typedefs.h"
using std::string;
///// STRUCTURES /////
struct IDirect3DTexture9;
struct IDirect3DCubeTexture9;
struct IDirect3DVolumeTexture9;
struct _D3DXIMAGE_INFO;
/*=============================================================================
class Texture_D3D9
=============================================================================*/
class Texture_D3D9 : public Resource_D3D9 {
public:
///// DEFINITIONS /////
enum TextureType : int {
TextureType_None = 0,
TextureType_2D,
TextureType_3D,
TextureType_Cube
};
private:
///// VARIABLES /////
union {
IDirect3DTexture9 * mD3DTexture;
IDirect3DCubeTexture9 * mD3DCubeTexture;
IDirect3DVolumeTexture9 * mD3DVolumeTexture;
};
uint mWidth, mHeight;
TextureType mType;
///// FUNCTIONS /////
/*---------------------------------------------------------------------
Called in a lost device situation for non-managed textures only.
These will free and restore the resource.
---------------------------------------------------------------------*/
virtual void onDeviceLost() {}
virtual void onDeviceRestore() {}
public:
///// VARIABLES /////
/*---------------------------------------------------------------------
specifies the cache that will manager the resource
---------------------------------------------------------------------*/
static const ResCacheType sCacheType = ResCache_Material;
///// FUNCTIONS /////
// Accessors
bool initialized() const { return (mType != TextureType_None); }
uint width() const { return mWidth; }
uint height() const { return mHeight; }
IDirect3DTexture9 * getD3DTexture() const { return mD3DTexture; }
// Mutators
/*---------------------------------------------------------------------
Loads a texture directly from a file (not through the Resource-
Source interface. Use this with the cache injection method.
---------------------------------------------------------------------*/
bool loadFromFile(const string &filename, uint mipLevels, bool compress);
bool createTexture(const void *srcData, uint srcChannels, uint srcWidth, uint srcHeight,
//TextureDataFormat _format, TextureUsageMode _usage, TextureRepeatMode _repeat, TextureFilterMode _filter,
uint mipLevels, bool compress, const string &name);
/*---------------------------------------------------------------------
onLoad is called automatically by the resource caching system when
a resource is first loaded from disk and added to the cache. This
function takes important loading parameters directly from the file
like width, height, and format. The full mipmap chain will be
created. For DDS files, the number of levels is taken directly from
the file, so the only way to ensure mipmaps will not be generated
is to store the texture as DDS with only 1 level. For finer control
over the number of levels loaded, use one of the other load
functions and manually inject into the cache.
---------------------------------------------------------------------*/
virtual bool onLoad(const BufferPtr &dataPtr, bool async);
/*---------------------------------------------------------------------
releases the D3D9 texture resource and sets mInitialized false
---------------------------------------------------------------------*/
void clearImageData();
// Misc functions
void debugCheckReqs(const _D3DXIMAGE_INFO &imgInfo, uint mipLevels) const;
bool saveTextureToFile(const string &filename) const;
// Constructors
/*---------------------------------------------------------------------
constructor with this signature is required for the resource system
---------------------------------------------------------------------*/
explicit Texture_D3D9(const string &name, uint sizeB, const ResCachePtr &resCachePtr) :
Resource_D3D9(name, sizeB, resCachePtr),
mWidth(0), mHeight(0), mD3DTexture(0), mType(TextureType_None)
{}
/*---------------------------------------------------------------------
use this default constructor to create the texture without caching,
or for cache injection method.
---------------------------------------------------------------------*/
explicit Texture_D3D9() :
Resource_D3D9(),
mWidth(0), mHeight(0), mD3DTexture(0), mType(TextureType_None)
{}
// Destructor
~Texture_D3D9();
}; | true |
71c8939da67fbaf4f131730377a4508099b5ea2e | C++ | clairedemars1/Python_Interpreter_Partial | /turn_in/includes/symbolTable.h | UTF-8 | 931 | 2.859375 | 3 | [] | no_license | #ifndef SYMBOLTABLE__H
#define SYMBOLTABLE__H
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
class Literal;
class FuncNode;
class Node;
class SymbolTable {
// i.e. scope
public:
SymbolTable() : vars(), funcs(), enclosingScopeIndex(-1) {}
void setVar(const std::string& name, const Literal* var);
void setFunc(const std::string&name, const FuncNode* func);
void setEnclosingScopeIndex(int newVal){ enclosingScopeIndex = newVal; }
bool isPresentVar(const std::string& name) const;
bool isPresentFunc(const std::string& name) const;
const Literal* getVar(const std::string& name) const;
const Node* getFunc(const std::string& name) const;
int getEnclosingScopeIndex() const { return enclosingScopeIndex; }
void display() const;
private:
std::map<std::string, const Literal*> vars;
std::map<std::string, const FuncNode*> funcs;
int enclosingScopeIndex;
};
#endif
| true |
6b312888a714e31f0179c6e5efc8a604f6b34033 | C++ | mateuszkretek/c_cpp | /Zbiory/Zbiory/Zbiory/odczyt.cpp | WINDOWS-1250 | 3,750 | 3.3125 | 3 | [] | no_license | /** @file */
#include <fstream>
#include <iostream>
#include "funkcje.h"
using namespace std;
bool argument(int argc, char* argv[], string& name) // sprawdzanie poprawnoci argumentu programu
{
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-i") == 0)
{
++i;
if (i < argc)
{
name.assign(argv[i]);
}
}
}
if (name.length() == 0) // jeli nie podano nazwy pliku wejciowego
{
cout << "Nieprawidlowy argument wywolania programu" << endl;
cout << "Prawidlowy przelacznik wywolania:" << endl;
cout << "-i <plik wejsciowy z danymi>" << endl;
cout << "Plik powinien miec rozszerzenie .txt" << endl << endl;
cout << "Przykladowy sposob wywolania programu:" << endl;
cout << "Program.exe -i input.txt" << endl;
return false;
}
return true;
}
tree* odczyt(string fname, readZ& exit, bool& readed)
{
ifstream fin(fname);
if (!fin.is_open()) //czy plik otwarty
{
cout << "Nie udalo sie otworzyc pliku wejsciowego." << endl;
readed = false;
return nullptr;
}
if (fin.peek() == EOF) //czy plik nie jest pusty
{
cout << "Plik wejsciowy jest pusty" << endl;
readed = false;
return nullptr;
}
tree* pHead;
string name;
string filename;
string filetype;
char temp;
char left;
char right;
char element = {};
vector <readZ> vecZ;
vector <readO> vecO;
while (fin >> name)
{
if (name == "WEJSCIE:")
{
while (fin >> name)
{
if (name == "OPERACJE:") //czy naley przej do odczytu operacji
{
break;
}
if (fin >> temp >> filename >> filetype)
{
element = name[0];
for (int i = 0; i < vecZ.size();i++)
{
if (element == vecZ[i].name) // czy nie nastpuje powtrzenie nazwy zbioru
{
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
}
vecZ.push_back({ element, filename, filetype });
}
}
while (fin >> name)
{
if (name == "WYJSCIE:") //czy naley przej do odczytu danych pliku wyjciowego
{
break;
}
if (fin >> temp >> left >> temp >> right)
{
element = name[0];
if (element == left || element == right || left == right) // czy w linii operacji nie wystpuj powtrzenia
{
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
switch(temp) //czy pomidzy zbiorami znajduje sie poprawny znak
{
case '+':
case '*':
case '\\':
case '-':
break;
default:
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
for (int i = 0; i < vecZ.size(); i++)
{
if (element == vecZ[i].name) //czy nie nastpuje zdublowanie nazwy zbioru i operacji
{
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
}
for (int i = 0; i < vecO.size(); i++)
{
if (element == vecO[i].name || left == vecO[i].left || left == vecO[i].right || right == vecO[i].left || right == vecO[i].right) //czy nie powtarza sie nazwa operacji, lub czy nazwy zbiorw nie powtarzaj si midzy sob
{
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
}
vecO.push_back({ element,temp,left,right });
}
}
if (fin >> filename >> filetype >> temp >> name)
{
exit = { element,filename,filetype };
break;
}
}
}
if (fin.fail()) // czy plik odczyta sie poprawnie
{
cout << "Blad w pliku wejsciowym" << endl;
readed = false;
return nullptr;
}
fin.close();
pHead = generujDrzewo(vecZ, vecO, exit.name); //generowanie struktury danych programu
return pHead;
} | true |
061dc55945cee430f15e40f0b3d132910cc637b3 | C++ | acoustictime/CollegeCode | /Riverside Community College (RCC)/CIS-5/Data Files/Chapter 19/Source Code/linkedQueue/testProgLinkedQueue.cpp | UTF-8 | 547 | 3.515625 | 4 | [] | no_license | //Test Program linked queue
#include <iostream>
#include "linkedQueue.h"
using namespace std;
int main()
{
linkedQueueType<int> queue;
int x, y;
queue.initializeQueue();
x = 4;
y = 5;
queue.addQueue(x);
queue.addQueue(y);
x = queue.front();
queue.deleteQueue();
queue.addQueue(x + 5);
queue.addQueue(16);
queue.addQueue(x);
queue.addQueue(y - 3);
cout<<"Queue Elements: ";
while(!queue.isEmptyQueue())
{
cout << " " << queue.front();
queue.deleteQueue();
}
cout<<endl;
return 0;
} | true |
ccd2372981737355465bd99fdab50375dcc43fd0 | C++ | Hitonoriol/Methan0l | /src/util/containers.h | UTF-8 | 1,809 | 2.984375 | 3 | [] | no_license | #ifndef SRC_UTIL_CONTAINERS_H_
#define SRC_UTIL_CONTAINERS_H_
#include <type_traits>
#include <type.h>
#define FWD_VAL std::forward<T>(val)
#define LIST_T decltype(c.push_back(FWD_VAL), void())
#define SET_T decltype(c.insert(FWD_VAL), void())
namespace mtl
{
template<typename C>
using iterator_of = decltype(std::begin(std::declval<C&>()));
template<typename Container, typename Tuple>
inline auto from_tuple(Tuple &&tuple)
{
return std::apply([](auto &&... elems) {
Container result;
(result.push_back(std::forward<Value>(Value(elems))), ...);
return result;
}, std::forward<Tuple>(tuple));
}
template<typename C, typename T>
inline auto insert(C &c, T &&val) -> LIST_T
{
c.push_back(FWD_VAL);
}
template<typename C, typename T>
inline auto remove(C &c, T &&val) -> LIST_T
{
c.erase(std::remove(c.begin(), c.end(), FWD_VAL), c.end());
}
template<typename C>
inline auto remove(C &c, iterator_of<C> &it)
{
c.erase(it);
}
template<typename C, typename T>
inline auto insert(C &c, T &&val) -> SET_T
{
c.insert(FWD_VAL);
}
template<typename C, typename T>
inline auto remove(C &c, T &&val) -> SET_T
{
c.erase(FWD_VAL);
}
template<typename C, typename T>
inline bool contains(C &c, T &&val)
{
return std::find(std::begin(c), std::end(c), val) != std::end(c);
}
template<typename C>
inline auto pop(C &c)
{
auto elem = c.top();
c.pop();
return elem;
}
template<typename T, typename V>
inline Int index_of(T &&container, V &&value)
{
Int idx = 0;
for (auto &&elem : container) {
if (value == elem)
return idx;
}
return -1;
}
template<typename C>
Int value_container_hash_code(C &&container)
{
Int hash = container.size();
for (auto &v : container)
hash ^= v.hash_code() + 0x9e3779b9 + (hash << 6) + (hash >> 2);
return hash;
}
}
#endif /* SRC_UTIL_CONTAINERS_H_ */
| true |
87e9f3568392dbfcca92e245f3a7f56f58420480 | C++ | AccessDenied1/Competitive_Coding | /codechef/CHANDF2.cpp | UTF-8 | 2,378 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int cc(long x,long y,long l,long r)
{
long p = (x&l)*(y&l);
int gh = l;
for(long i = l+1;i<=r;i++)
{
long p_n = (x&i)*(y&i);
if(p_n > p)
{
p = p_n;
gh = i;
}
}
return gh;
}
string decToBinary(long n)
{
string s = "";
while (n > 0)
{
s = s + to_string(n % 2);
n = n / 2;
}
reverse(s.begin(),s.end());
return s;
}
long binaryToDecimal(string n)
{
string num = n;
long dec_value = 0;
long base = 1;
long len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
long calc(long z, long x, long y , long l)
{
long po = x|y;
int i = 0;
long newz = z;
//cout<<z<<endl;
//cout<<po<<endl;
while(po!=0)
{
//cout<<(po&1)<< " "<<(z&1)<<endl;
if(!(po&1) && ((z&1)))
{
//cout<<"yes for "<<i<<endl;
newz = newz - pow(2,i);
}
if(newz < l)
{
newz = newz+pow(2,i);
break;
}
po = po >>1;
z = z>>1;
i++;
}
return newz;
}
int main()
{
int t;
cin>>t;
while(t--)
{
long x,y,l,r;
cin>>x>>y>>l>>r;
long rr = r;
long s = 1;
if(x==0||y==0)
cout<<l<<endl;
else if((x|y) >= l && (x|y) <=r)
cout<<(x|y)<<endl;
else
{
//cout<<"x or y "<<decToBinary(x|y|l)<<endl;
vector<long> R2;
long long poww = 0;
long z = r;
long rr = r;
string R = decToBinary(r);
//cout<<"R = "<<R<<endl;
int len = R.size();
string dd = "" ;
string st = "";
for(int i=0;i<len;i++)
{
st +='1';
}
for(int i = 0 ;i<len;i++)
{
if(R[i] == '1')
{
dd = R.substr(0,i)+ "0";
if(i != len-1)
dd += st.substr(i+1,len-i-1);
//cout<<"dd = "<<dd<<endl;
long r2 = binaryToDecimal(dd);
//cout<<"doing "<<r2<<" and "<<(x|y)<<endl;
r2 = r2&(x|y|l);
if(r2<l)
continue;
R2.push_back(r2);
}
}
long fg = r&(x|y|l);
if(fg >= l )
R2.push_back(fg);
sort(R2.begin(),R2.end());
for(long r2 : R2)
{
//cout<<"r2 = "<<(r2)<<endl;
long long pow2 = (x&r2)*(y&r2);
if(pow2 > poww)
{
z = r2;
poww = pow2;
}
}
if(((x&z)*(y&z)) == 0)
cout<<l<<endl;
else
{
//cout<<"z = "<<z<<endl;
if(l!=0)
cout<<calc(z,x,y,l)<<endl;
else
cout<<z<<endl;
}
}
}
}
| true |
3a2e1008c6d5e9db7f62f1a0619a59c6536c9267 | C++ | markuskr/raytracer | /StandardOperatorFactory.cpp | UTF-8 | 7,038 | 2.6875 | 3 | [] | no_license | //----------------------------------------------------------------------
/// Filename: StandardOperatorFactory.cpp
/// Group: 20
/// \brief : factory for producing the standard operators
/// Last Changes: 22.06.2008
//----------------------------------------------------------------------
#include "StandardOperatorFactory.h"
#include "AddiOperator.h"
#include "AddfOperator.h"
#include "SubiOperator.h"
#include "SubfOperator.h"
#include "SqrtOperator.h"
#include "MuliOperator.h"
#include "MulfOperator.h"
#include "DiviOperator.h"
#include "DivfOperator.h"
#include "ArrayOperator.h"
#include "NegiOperator.h"
#include "NegfOperator.h"
#include "LessiOperator.h"
#include "LessfOperator.h"
#include "AcosOperator.h"
#include "ModiOperator.h"
#include "EqiOperator.h"
#include "EqfOperator.h"
#include "AsinOperator.h"
#include "ClampfOperator.h"
#include "SinOperator.h"
#include "CosOperator.h"
#include "FloorOperator.h"
#include "FracOperator.h"
#include "RealOperator.h"
#include "ArrayOperator.h"
#include "FunctionOperator.h"
#include "DupOperator.h"
#include "WhileOperator.h"
#include "PointOperator.h"
#include "GetxOperator.h"
#include "GetyOperator.h"
#include "GetzOperator.h"
#include "ApplyOperator.h"
#include "LengthOperator.h"
#include "GetOperator.h"
#include "IfOperator.h"
using std::string;
//----------------------------------------------------------------------
StandardOperatorFactory::StandardOperatorFactory(GMLInterpreter &interpreter)
: GMLOperatorFactory(interpreter)
{
}
//----------------------------------------------------------------------
int StandardOperatorFactory::createOperator(const string &gml_operator)
{
if (gml_operator.compare("acos") == 0)
{
return m_interpreter.registerOperator(new AcosOperator(m_interpreter.m_stack) );
}
else if (gml_operator.compare("addf") == 0)
{
return m_interpreter.registerOperator(new AddfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("addi") == 0)
{
return m_interpreter.registerOperator(new AddiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("dup") == 0)
{
return m_interpreter.registerOperator(new DupOperator(m_interpreter.m_stack) );
}
else if (gml_operator.compare("asin") == 0)
{
return m_interpreter.registerOperator(new AsinOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("clampf") == 0)
{
return m_interpreter.registerOperator(new ClampfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("cos") == 0)
{
return m_interpreter.registerOperator(new CosOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("divf") == 0)
{
return m_interpreter.registerOperator(new DivfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("divi") == 0)
{
return m_interpreter.registerOperator(new DiviOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("eqf") == 0)
{
return m_interpreter.registerOperator(new EqfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("eqi") == 0)
{
return m_interpreter.registerOperator(new EqiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("floor") == 0)
{
return m_interpreter.registerOperator(new FloorOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("frac") == 0)
{
return m_interpreter.registerOperator(new FracOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("lessf") == 0)
{
return m_interpreter.registerOperator(new LessfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("lessi") == 0)
{
return m_interpreter.registerOperator(new LessiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("modi") == 0)
{
return m_interpreter.registerOperator(new ModiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("mulf") == 0)
{
return m_interpreter.registerOperator(new MulfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("muli") == 0)
{
return m_interpreter.registerOperator(new MuliOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("negf") == 0)
{
return m_interpreter.registerOperator(new NegfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("negi") == 0)
{
return m_interpreter.registerOperator(new NegiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("real") == 0)
{
return m_interpreter.registerOperator(new RealOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("sin") == 0)
{
return m_interpreter.registerOperator(new SinOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("sqrt") == 0)
{
return m_interpreter.registerOperator(new SqrtOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("subf") == 0)
{
return m_interpreter.registerOperator(new SubfOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("subi") == 0)
{
return m_interpreter.registerOperator(new SubiOperator(m_interpreter.m_stack));
}
else if (gml_operator.compare("]") == 0)
{
return m_interpreter.registerOperator(new ArrayOperator(m_interpreter.m_stack, m_interpreter.m_arrays) );
}
else if (gml_operator.compare("}") == 0)
{
return m_interpreter.registerOperator(new FunctionOperator(m_interpreter.m_stack, m_interpreter.m_arrays) );
}
else if (gml_operator.compare("while") == 0)
{
return m_interpreter.registerOperator(new WhileOperator(m_interpreter.m_stack, m_interpreter.m_arrays, m_interpreter.m_operators, m_interpreter) );
}
else if (gml_operator.compare("point") == 0)
{
return m_interpreter.registerOperator(new PointOperator(m_interpreter.m_stack ));
}
else if (gml_operator.compare("getx") == 0)
{
return m_interpreter.registerOperator(new GetxOperator(m_interpreter.m_stack ));
}
else if (gml_operator.compare("gety") == 0)
{
return m_interpreter.registerOperator(new GetyOperator(m_interpreter.m_stack ));
}
else if (gml_operator.compare("getz") == 0)
{
return m_interpreter.registerOperator(new GetzOperator(m_interpreter.m_stack ));
}
else if (gml_operator.compare("apply") == 0)
{
return m_interpreter.registerOperator(new ApplyOperator(m_interpreter.m_stack, m_interpreter.m_arrays, m_interpreter) );
}
else if (gml_operator.compare("length") == 0)
{
return m_interpreter.registerOperator(new LengthOperator(m_interpreter.m_stack, m_interpreter.m_arrays, m_interpreter) );
}
else if (gml_operator.compare("get") == 0)
{
return m_interpreter.registerOperator(new GetOperator(m_interpreter.m_stack, m_interpreter.m_arrays) );
}
else if (gml_operator.compare("if") == 0)
{
return m_interpreter.registerOperator(new IfOperator(m_interpreter.m_stack, m_interpreter.m_arrays, m_interpreter) );
}
return -1;
}
//----------------------------------------------------------------------
void StandardOperatorFactory::init()
{
}
| true |
9722fd1a876169f12d6349586db72e19b35948a8 | C++ | sunbinbin1991/myfirstcode | /example/leetCode/187_findRepeatedDnaSequences.h | UTF-8 | 596 | 2.625 | 3 | [] | no_license | class Solution187 {
public:
vector<string> findRepeatedDnaSequences(string s) {
if(s.empty()) return {};
set<string> strSets;
set<string> res;
for (int i = 0; i <= s.size() - 10 && s.size() >= 10; i++){
string sub = s.substr(i, 10);
// cout << "sub :" << sub << endl;
if(strSets.find(sub) != strSets.end()){
res.insert(sub);
}
strSets.insert(sub);
}
vector<string> ans;
for(auto ss : res){
ans.push_back(ss);
}
return ans;
}
};
| true |
39f4a99788fa43cb90e670629be3792d9f2e7e8e | C++ | artcampo/2013_3D_unfinished_game | /Game/Entities/Ship/Ship.hpp | UTF-8 | 2,053 | 2.515625 | 3 | [] | no_license | #ifndef _SHIP_HPP_
#define _SHIP_HPP_
#include "dx_misc.hpp"
#include <memory>
class Physics;
class RigidBody;
class TimeForce;
class TimeTorque;
class ShipDescription{
public:
float fwdModule;
float bckModule;
float sidModule;
float pitchModule;
float yawModule;
};
class Ship {
public:
Ship( Physics& aPhysics,
const D3DXVECTOR3& aInitPosition,
const ShipDescription& aShipDesc );
~Ship();
void display() const;
void update( const float aLapsedTime );
void clearForces();
// move functions to be used by both player and IA
void moveFwd( const bool aMove, const float aLapsedTime );
void moveBck( const bool aMove, const float aLapsedTime );
void moveLft( const bool aMove, const float aLapsedTime );
void moveRgt( const bool aMove, const float aLapsedTime );
void pitchUp( const bool aMove, const float aLapsedTime );
void pitchDown( const bool aMove, const float aLapsedTime );
void turnRight( const bool aMove, const float aLapsedTime );
void turnLeft( const bool aMove, const float aLapsedTime );
int id() const;
// Render
public:
std::auto_ptr<RigidBody> mBody;
// Static description
private:
D3DXVECTOR3 mPointingDirection;
D3DXVECTOR3 mCrossDirection;
ShipDescription mShipDesc;
// Physics vars
private:
std::auto_ptr<TimeForce> mShipTForceForw;
std::auto_ptr<TimeForce> mShipTForceBack;
std::auto_ptr<TimeForce> mShipTForceLeft;
std::auto_ptr<TimeForce> mShipTForceRght;
std::auto_ptr<TimeTorque> mShipTTorqueUp;
std::auto_ptr<TimeTorque> mShipTTorqueDown;
std::auto_ptr<TimeTorque> mShipTTorqueLeft;
std::auto_ptr<TimeTorque> mShipTTorqueRight;
public:
D3DXVECTOR3 pointingUnit() const;
D3DXVECTOR3 movementVector() const;
private:
void updateCameraParameters();
friend class Ship_IA;
};
#endif //_SHIP_HPP_
| true |
c33822cc3f96cd710d9fd905b73456c2ab1772e0 | C++ | AvatarSenju/Competitive | /cpp/max-snake-matrix.cpp | UTF-8 | 501 | 3.0625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void amax(T &x, U y)
{
if (x < y)
x = y;
}
int mymax(vector<vector<int>> a,int i,int j,int n,int m)
{
if(i>=n || j>=m)
return 0;
return(a[i][j]+max(mymax(a,i+1,j,n,m),mymax(a,i,j+1,n,m)));
}
int main()
{
// int a[3][4]={0,3,1,1,2,0,0,4,1,5,3,1};
vector<vector<int>> vect ={{0,3,10,1},{2,0,0,4},{1,5,3,1}};
int p=mymax(vect,0,0,3,4);
cout<<p<<endl;
return 0;
} | true |
0c3e47b17a0fb4d09ce8b8c9a453088debc8f16f | C++ | StrategFirst/ConsoleColor | /consolecolor.hh | UTF-8 | 1,164 | 3.234375 | 3 | [] | no_license | #include <iostream> // std::ostream
#include <math.h> // abs
namespace console {
enum class mode { RGB , HSL , HSV };
class color {
private: //custom types
using color_component_t = unsigned int;
struct RGB {
color_component_t r;
color_component_t g;
color_component_t b;
};
private: //conversion methods
float math_mod(float a,float b);
RGB HSL_to_RGB(color_component_t H,color_component_t S,color_component_t L);
RGB HSV_to_RGB(color_component_t H,color_component_t S,color_component_t V);
private: //class fields
color_component_t _r,_g,_b;
public: //constructors
color(color_component_t const r,color_component_t const g,color_component_t const b);
color(color_component_t const x,color_component_t const y,color_component_t const z,mode const m);
~color() = default;
color(const color & origin) = default;
public: //operators
friend std::ostream & operator<< (std::ostream & os,color c);
public: //getters
color_component_t r() const { return _r; }
color_component_t g() const { return _g; }
color_component_t b() const { return _b; }
};
const std::string reset = "\033[0m";
};
| true |
d76931ab6874df8085725a897e25895042a59e99 | C++ | fengshen024/Algorithm | /aoapc_uva/aoapc-code/ch04/UVA512.cpp | UTF-8 | 3,400 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef struct Pos{
int x, y;
Pos(int _x=0, int _y=0): x(_x), y(_y){} // 默认值表示默认构造函数
// bool operator < (const Pos& b) const { // map需要排序,必须加const,否则编译报错
// if (x == b.x) return y < b.y;
// else return x < b.x;
// }
friend bool operator < (const Pos& a, const Pos& b) { // map需要排序
if (a.x == b.x) return a.y < b.y;
else return a.x < b.x;
}
} Pos;
map<Pos,Pos> mp1, mp2, mp3; // 当前位置->原始位置,操作模拟的中间变量,原始位置->最终位置
int r, c, op, n, t, num = 0;
string s;
vector<int> cnt(60);
int main() {
while(scanf("%d %d", &r, &c) == 2 && (r != 0 && c != 0)) {
scanf("%d", &op);
if (num != 0) puts("");
printf("Spreadsheet #%d\n", ++num);
mp1.clear(); // 清空
for (int i = 1; i <= r; i ++) { // 初始化:当前位置->原始位置
for (int j = 1; j <= c; j ++) {
mp1.insert({Pos{i,j}, Pos{i,j}});
}
}
while(op --) { // 操作
cin >>s;
if (s != "EX") { // 不为Exchange
cin >>n;
fill(cnt.begin(), cnt.end(), 0); // 初始化
set<int> rcset; // 要删除/插入的行列集合
while(n --) {
cin >>t; rcset.insert(t);
cnt[t] ++; // 统计每个序号出现次数
}
for (int i = 1; i < cnt.size(); i ++) cnt[i] += cnt[i-1]; // cnt[i]表示小于等于i的个数,用于计算最终行列号
for (auto p = mp1.begin(); p != mp1.end(); p ++) { // 遍历每个cell
if (s == "DR") { // 删除行
if (rcset.find(p->first.x) == rcset.end()) // 未找到,不被删除
mp2.insert({{p->first.x - cnt[p->first.x-1],p->first.y}, p->second}); // 插入记录
}
else if (s == "DC") { // 删除列
if (rcset.find(p->first.y) == rcset.end()) // 不被删除
mp2.insert({{p->first.x, p->first.y-cnt[p->first.y-1]}, p->second});
}
else if (s == "IR") { // 插入行
mp2.insert({{p->first.x+cnt[p->first.x], p->first.y}, p->second}); // 更新位置
}
else if (s == "IC") {
mp2.insert({{p->first.x,p->first.y+cnt[p->first.y]}, p->second}); // 更新位置
}
}
mp1 = mp2; mp2.clear(); // 更新当前位置关系
}
else {
int r1,c1,r2,c2;
cin >>r1 >>c1 >>r2 >>c2;
swap(mp1[{r1,c1}], mp1[{r2,c2}]); // 交换单元格,考虑交换单元格包含刚插入的
}
}
mp3.clear();
for (auto p : mp1) mp3.insert({p.second, p.first}); // 逆置:原始位置->最终位置
cin >>n;
int x, y;
while (n --) { // 处理查询
cin >>x >>y;
if (mp3.find({x,y}) == mp3.end()) printf("Cell data in (%d,%d) GONE\n", x, y);
else printf("Cell data in (%d,%d) moved to (%d,%d)\n", x, y, mp3[{x,y}].x, mp3[{x,y}].y);
}
}
return 0;
} | true |
58c3fb6ce199c1ddb4144feda61f92b8aae7a058 | C++ | true-dude/second | /cut_tree_2d_sum.cpp | WINDOWS-1251 | 2,925 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int log(int n){
int x = 1, c =0;
while (x < n){
x *= 2;
c ++;
}
return x;
}
void update(vector<vector <int>> &a, int x, int y, int inc){ //
int tx=x, ty = y;
while (tx > 0){
ty = y;
while (ty > 0){
a[tx][ty] += inc;
ty /= 2;
}
tx /= 2;
}
}
int get_sum_y(vector<vector <int>> &a, int l, int t, int b){
int ans = 0;
while (t < b){
if (t % 2 == 1){
ans += a[t][l];
t ++;
}
if (b % 2 == 0){
ans += a[b][l];
b --;
}
t /= 2;
b /= 2;
}
if (t==b){
ans += a[t][l];
cout << "t: " << t << " l: " << l << "\n\n";
}
return ans;
}
int get_sum_x(vector<vector <int>> &a, int l, int r, int t, int b){
int ans = 0;
while (l<r){
cout << "l: " << l << " r: " << r << "\n\n";
if (l % 2 == 1){
ans += get_sum_y(a, l, t, b);
l ++;
}
if (r % 2 == 0){
ans += get_sum_y(a, l, t, b);
r --;
}
l /= 2;
r /= 2;
}
if (l == r){
ans += get_sum_y(a, l, t, b);
}
return ans;
}
int main(){
int n, m, l, r, y, z, i, j, ky, kx, q, xn, xm, t, b;
cin >> n >> m;
xn = log(n);
xm = log(m);
vector <vector <int>> a(xn*2+3);//[xn*2+3][xm*2+3];
for (int i=0; i<xn*2+3; i++){ //
for (int j=0; j<xm*2+3; j++) a[i].push_back(0);
}
for (int i=0; i<n; i++){ //
for (int j=0; j<n; j++) cin >> a[i+xn][j+xm];
}
for (int i=2*xn-1; i>0; i--){ //
for (int j=2*xm-1; j>0; j--){
//a[i][j] = a[i*2][j*2] + a[i*2+1][j*2] + a[i*2][j*2+1] + a[i*2+1][j*2+1]; // ( !!!!)
//but i wiil do it, i belive in this
if (i < xn && j < xm) a[i][j] = a[i*2][j*2] + a[i*2+1][j*2] + a[i*2][j*2+1] + a[i*2+1][j*2+1];
if (i >= xn && j < xm) a[i][j] = a[i][j*2] + a[i][j*2+1];
if (j >= xm && i < xn) a[i][j] = a[i*2][j] + a[i*2+1][j];
if (j >= xm && i >= xn) a[i][j] = a[i][j];
}
}
for (auto i: a){
for (auto j:i) cout << j << " ";
cout << "\n";
}
cin >> z;
for (int i=0; i<z; i++){
cin >> ky >> kx >> q;
update(a, ky, kx, q);
}
cin >> z;
for (int i=0; i<z; i++){
cin >> l >> r >> t >> b;
cout << get_sum_x(a, l+xm-1, r+xm-1, t+xn-1, b+xn-1) << "\n";
}
}
//!!!!
| true |
83851b10c3e97b2aa81f7c2ba1901bc8e5ef7396 | C++ | dmatseku/piscine_cpp | /day03/ex01/ScavTrap.hpp | UTF-8 | 822 | 2.8125 | 3 | [] | no_license | #ifndef SCAVTRAP_HPP
#define SCAVTRAP_HPP
#include <string>
class ScavTrap
{
private:
unsigned int _hit_points;
unsigned int _max_hit_points;
unsigned int _energy_points;
unsigned int _max_energy_points;
unsigned int _level;
std::string _name;
unsigned int _melee_attack_damage;
unsigned int _ranged_attack_damage;
unsigned int _armor_damage_reduction;
public:
ScavTrap();
ScavTrap(std::string);
ScavTrap(ScavTrap const &);
~ScavTrap();
ScavTrap& operator=(ScavTrap const &);
void rangedAttack(std::string const &);
void meleeAttack(std::string const &);
void takeDamage(unsigned int);
void beRepaired(unsigned int);
void challengeNewcomer();
};
#endif | true |
8e506bdfad44a621f60c44b6228f98bdbc111813 | C++ | shuhua833/static | /static.cpp | UTF-8 | 195 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
void increment();
int main()
{
back:
increment();
getch();
goto back;
return 0;
}
void increment()
{
static int x=1;
printf("x:=%d\n",x);
x++;
}
| true |
d1d2bf6131ff0fc197cd55da0a378838fa4892eb | C++ | davnils/kattis-skeleton | /include/KattisTask.hpp | UTF-8 | 1,216 | 3.0625 | 3 | [] | no_license | /**
* KattisTask interface file.
* Part of the public kattis-skeleton project.
*/
#pragma once
#include <cassert>
#include <iostream>
/**
* Generic interface implemented by solvers, written for specific
* Kattis problems. Serves the purpose of cleaning up initialization,
* ensuring proper termination and reducing bloat.
*/
class KattisTask
{
public:
/**
* Constructor initializing efficient IO.
*/
KattisTask()
{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
}
/**
* Solver function called from main().
* Ensures that a non-zero return code is not propagated to
* the environment before making an assertion.
*
* @return Constant Zero.
*/
int solve()
{
auto ret = solveTask();
assert(ret == 0);
return(ret);
}
private:
/**
* Solver function implemented by the solver.
*
* @return Return code from the solver.
*/
virtual int solveTask() = 0;
};
/**
* Type of global task reference, should be declared by a solver
* (e.g. task_t g_task = TaskHelloWorld(); )
* Makefile ensures that the proper compilation unit is referenced.
*/
typedef KattisTask && task_t;
| true |
caa6d824924cce0c0fb30f7f346ca226c69781cd | C++ | lonski/amarlon | /src/actor/actor_actions/use_skill_action.cpp | UTF-8 | 693 | 2.53125 | 3 | [] | no_license | #include "use_skill_action.h"
#include <skill.h>
namespace amarlon {
UseSkillAction::UseSkillAction(SkillPtr skill, Target target)
: _skill(skill)
, _target(target)
{
}
UseSkillAction::~UseSkillAction()
{
}
ActorActionResult UseSkillAction::perform(ActorPtr user)
{
_user = user;
ActorActionResult r = ActorActionResult::Nok;
if ( _user && _skill )
{
r = _skill->use(_user, _target) ? ActorActionResult::Ok
: ActorActionResult::Nok;
}
return r;
}
ActorActionUPtr UseSkillAction::clone()
{
UseSkillActionUPtr cloned = std::make_unique<UseSkillAction>(_skill, _target);
cloned->_user = _user;
return std::move(cloned);
}
}
| true |
e37f198f9e37ae28217094913c21f75d3fb37cd7 | C++ | AniaRuchala/PSI | /perceptron/psi1/Neuron.cpp | WINDOWS-1250 | 1,649 | 3.15625 | 3 | [] | no_license | #include "Neuron.h"
#include <cstdlib>
#include <iostream>
#include <ctime>
double randFun(double fMin, double fMax){
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
Neuron::Neuron(){
srand(time(NULL));
waga = NULL;
funcAct = NULL;
}
Neuron::Neuron(int m_n) : n(m_n){
srand(time(NULL));
funcAct = NULL;
waga = new double[n];
for (int i = 0; i < n; i++){
waga[i] = randFun(0, 1);
}
}
Neuron::Neuron(int m_n, double *m_waga) : n(m_n), waga(m_waga){
funcAct = NULL;
srand(time(NULL));
}
void Neuron::setWaga(double *m_waga){
waga = m_waga;
}
void Neuron::setWaga(double x, int i){
if ((waga != NULL) && (i < n)){
waga[i] = x;
}
else{
throw "Error in setWagi";
}
}
void Neuron::setN(int m_n){
n = m_n;
}
void Neuron::setFuncAct(fun1 m_funkcjaAktywujca){
funcAct = m_funkcjaAktywujca;
}
void Neuron::setPochodna(fun1 m_pochodna){
pochodna = m_pochodna;
}
double Neuron::getWaga(int i){
if (waga != NULL && i < n){
return waga[i];
}
else{
throw "Error in getWaga";
}
}
double Neuron::start(double *m_inputs){
if (funcAct == 0) {
throw "Set activate function!";
}
double a = sumowanie(m_inputs);
return funcAct(a);
}
void Neuron::learn(double * input, double output){
if (funcAct == 0) {
throw "Set activate function!";
}
double ni = 0.5;
double result = this->start(input);
if (result != output){
for (int i = 0; i < n; i++){
waga[i] += ni*(output - result)*input[i];
}
}
}
double Neuron::sumowanie(double *m_input){
double amount = 0;
for (int i = 0; i < n; i++){
amount += waga[i] * m_input[i];
}
return amount;
}
Neuron::~Neuron(){
delete waga;
} | true |
c1e25b3a08f839a9ef9bfe670c8bbeeb55d52a34 | C++ | eslam-99/programming-abstractions | /Chapter_09/Exercise_07/9_07.cpp | UTF-8 | 3,600 | 3.234375 | 3 | [] | no_license | //
// File: 9_07.cpp
// Programming Abstractions C++
//
// Exercise Description:
//
// Created by Ben Mills on 10/8/14.
//
//
#include <stdio.h>
#include "cube.h"
#include "console.h"
#include "vector.h"
#include "set.h"
#include <stdlib.h>
#include "strlib.h"
using namespace std;
const int TOTAL_CUBES = 4;
const int MAX_ROTATION = 4;
const int TOTAL_SIDES_PER_CUBE = 6;
bool isUnique(Vector<char> vec);
bool solveInsanity(Vector<Cube> fourCubes, Vector<string> &answer, int cubeIndex, int rotationIndex, int sideIndex);
bool puzzleCheck(Vector<Cube> fourCubes, Vector<string> &answer, int cubeIndex, int rotationIndex, int sideIndex);
int main() {
Cube cubeA('G', 'W', 'B', 'B', 'R', 'G');
Cube cubeB('R', 'W', 'W', 'G', 'B', 'G');
Cube cubeC('W', 'R', 'R', 'W', 'B', 'G');
Cube cubeD('B', 'G', 'R', 'R', 'R', 'W');
Vector<Cube> fourCubes;
fourCubes += cubeA, cubeB, cubeC, cubeD;
Vector<int> sideIndex(TOTAL_CUBES);
Vector<string> answer(TOTAL_CUBES);
if (solveInsanity(fourCubes, answer, 0, 0, 0)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
bool solveInsanity(Vector<Cube> fourCubes, Vector<string> &answer, int cubeIndex, int rotationIndex, int sideIndex) {
cout << "CUBE INDEX: " << cubeIndex << endl;
if (cubeIndex >= TOTAL_CUBES) {
return true;
}
for (int s = 0; s < TOTAL_SIDES_PER_CUBE; s++) {
cout << "SIDE: " << s << endl;
for (int r = 0; r < MAX_ROTATION; r++) {
cout << "ROTATION: " << r << endl;
if (puzzleCheck(fourCubes, answer, cubeIndex, r, s)) {
if (solveInsanity(fourCubes, answer, cubeIndex + 1, r, s)) {
return true;
}
answer[cubeIndex] = "";
}
if (s == TOTAL_SIDES_PER_CUBE - 1 && r == MAX_ROTATION - 1) {
cubeIndex--;
cout << "CUBE INDEX: "<< cubeIndex << endl;
}
}
cout << endl;
}
return false;
}
bool puzzleCheck(Vector<Cube> fourCubes, Vector<string> &answer, int cubeIndex, int rotationIndex, int sideIndex) {
Vector<char> sideA;
Vector<char> sideB;
Vector<char> sideC;
Vector<char> sideD;
for (int i = 0; i <= cubeIndex; i++) {
if (i == cubeIndex) {
sideA += fourCubes[i].getRotationSides(sideIndex)[(rotationIndex + 0) % 4];
sideB += fourCubes[i].getRotationSides(sideIndex)[(rotationIndex + 1) % 4];
sideC += fourCubes[i].getRotationSides(sideIndex)[(rotationIndex + 2) % 4];
sideD += fourCubes[i].getRotationSides(sideIndex)[(rotationIndex + 3) % 4];
} else {
sideA += answer[i][0];
sideB += answer[i][1];
sideC += answer[i][2];
sideD += answer[i][3];
}
}
cout << "PUZZLE CHECK: " << sideA << " " << sideB << " " << sideC << " " << sideD << endl;
if (isUnique(sideA) && isUnique(sideB) && isUnique(sideC) && isUnique(sideD)) {
answer[cubeIndex] += sideA[cubeIndex];
answer[cubeIndex] += sideB[cubeIndex];
answer[cubeIndex] += sideC[cubeIndex];
answer[cubeIndex] += sideD[cubeIndex];
cout << "ANSWER: " << answer << endl;
cout << "GOT IT" << endl;
return true;
}
return false;
}
bool isUnique(Vector<char> vec) {
Set<char> test;
for (int i = 0; i < vec.size(); i++) {
test.add(vec[i]);
}
if (test.size() == vec.size()) {
return true;
} else {
return false;
}
}
| true |
baac241c716f175d47e7bc62453646a31927c618 | C++ | Nheko-Reborn/mtxclient | /include/mtx/responses/well-known.hpp | UTF-8 | 986 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
/// @file
/// @brief Response for .well-known lookup.
#include <optional>
#if __has_include(<nlohmann/json_fwd.hpp>)
#include <nlohmann/json_fwd.hpp>
#else
#include <nlohmann/json.hpp>
#endif
namespace mtx {
namespace responses {
//! The info about this server.
struct ServerInformation
{
//! Required. The base URL for client-server connections.
std::string base_url;
friend void from_json(const nlohmann::json &obj, ServerInformation &response);
};
//! Response from the `GET /.well-known/matrix/client` endpoint.
//! May also be returned from `POST /_matrix/client/r0/login`.
//
//! Gets discovery information about the domain
struct WellKnown
{
//! Required. Used by clients to discover homeserver information.
ServerInformation homeserver;
//! Used by clients to discover identity server information.
std::optional<ServerInformation> identity_server;
friend void from_json(const nlohmann::json &obj, WellKnown &response);
};
}
}
| true |
45cca9c3ac130771bd1291dd14f4174089b90569 | C++ | shoamco/Cpp-under-the-hood | /SmartPointer/Test/TestSharedtPointer.cpp | UTF-8 | 2,164 | 2.984375 | 3 | [] | no_license | //
// Created by shoam on 2/13/20.
//
#include "TestSmartPointer.h"
#include "SharedPointer.h"
void testControlBlock(){
std::cout<<"\n\n\n************** testControlBlock *******\n";
ReferenceCounter referenceCounter();
std::cout<<referenceCounter;
}
void testCtorSmartPtr(){
std::cout<<"\n\n\n************** testCtorSmartPtr *******\n";
SharedPointer<int> sharedPointer1(new int(5));
std::cout<<"sharedPointer1 "<<sharedPointer1.get()<<std::endl;
SharedPointer<int> sharedPointer2=sharedPointer1;
std::cout<<"sharedPointer2 "<<sharedPointer2.get()<<std::endl;
*sharedPointer2=10;
std::cout<<"after set sharedPointer1 "<<sharedPointer1.get()<<std::endl;
}
void testSmartPtrInScope(){
std::cout<<"\n\n\n************** testSmartPtrInScope *******\n";
SharedPointer<int> sharedPointer1(new int(5));
std::cout<<"sharedPointer1 "<<sharedPointer1.get()<<std::endl;
{
SharedPointer<int> sharedPointer2 = sharedPointer1;
std::cout << "sharedPointer2 " << sharedPointer2.get() << std::endl;
*sharedPointer2 = 10;
{
SharedPointer<int> sharedPointer3 = sharedPointer1;
std::cout << "sharedPointer3 " << sharedPointer3.get() << std::endl;
std::cout<<"end of scope \n";
}
std::cout<<"end of scope \n";
}
std::cout<<"after set sharedPointer1 "<<sharedPointer1.get()<<std::endl;
}
void testAssignmentOperator(){
std::cout<<"\n\n\n************** testAssignmentOperator *******\n";
SharedPointer<int> sharedPointer1(new int(5));
std::cout<<"sharedPointer1 "<<sharedPointer1.get()<<std::endl;
SharedPointer<int> sharedPointer2 = sharedPointer1;
std::cout << "sharedPointer2 " << sharedPointer2.get() << std::endl;
SharedPointer<int> sharedPointer3(new int(3));
std::cout << "sharedPointer3 " << sharedPointer3.get() << std::endl;
sharedPointer1 = sharedPointer3;
std::cout<<"\nsharedPointer1 after assignment operator "<<sharedPointer1.get()<<std::endl;
}
void testSmartPointer(){
testControlBlock();
testCtorSmartPtr();
testSmartPtrInScope();
testAssignmentOperator();
} | true |
e577ea9b9f20b2ab8c51e94e814483cc148424d9 | C++ | BrandeisMakerLab/Arduino_Education | /extras/Projects/workshopResults/Dariel_7-25-2019/Dariel_7-25-2019.ino | UTF-8 | 1,530 | 2.984375 | 3 | [] | no_license | //imports the library that must be used to run this program
#include <DHT.h>
#include <DHT_U.h>
#define BLUEPIN 4
#define REDPIN 3
//initializes the part so that the program knows what to expect to run
DHT dht(2, DHT22);
float initHumid;
void setup() {
//initialize serial port (allows for commuication with arduino by clicking on the magnifying glass
//on the top right corner of the window AFTER the program is uploaded
Serial.begin(9600);
// initialize digital pin LED_BUILTIN as an output.
pinMode(BLUEPIN, OUTPUT);
pinMode(REDPIN, OUTPUT);
//starts the loop
dht.begin();
initHumid = dht.readHumidity();
pinMode(2, OUTPUT);
}
void loop() {
float humidity = dht.readHumidity();
Serial.print("init");
Serial.println(initHumid);
Serial.print("Humidity: ");
Serial.println(humidity);
delay(500);
if (humidity > 50) { // the setup function runs once when you press reset or power the board
digitalWrite(3, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50);
} else {
digitalWrite(3, LOW); // turn the LED off by making the voltage LOW
delay(50);
}
}
/*void flash(){
loop;
loop;
loop;
loop;
loop;
loop;
loop;
}
// the loop function runs over and over again forever
void loop()
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(50); // wait for a second*/
| true |
7149df12ec6ec86390cbd5e6e2ac66e2a9f80835 | C++ | khantra/schoolwork | /Accelerated Intro to Programming/week6/boxSort.cpp | UTF-8 | 1,799 | 3.8125 | 4 | [] | no_license | /*********************************************************************
** Author:/ Khandakar Shadid
** Date: / 2/8/2017
** Description:/ Sorting an array of "Box" objects using a bubble sort.
**************** To do so I just had to edit the bubble sort to accept
**************** a Box object. I then tested it using random numbers.
*********************************************************************/
#include <iostream>
using namespace std;
#include "Box.hpp"
/*
#include <stdlib.h>
#include <time.h>
*/
void boxSort(Box array[], int size){
Box temp;
bool swap;
do{
swap = false;
for (int count = 0; count < (size - 1); count++){
if (array[count].getVolume() < array[count + 1].getVolume()){
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap); // Loop again if a swap occurred on this pass.
}
/*
void showArray(Box array[], int size){
for (int count = 0; count < size; count++)
cout <<"Box No."<<count <<" "<< array[count].getVolume() << " "<< endl;
}
int main()
{
Box box1(2.4, 7.1, 5.0);
Box box2 (4,5,5);
double volume1 = box1.getVolume();
double surfaceArea1 = box1.getSurfaceArea();
double volume2 = box2.getVolume();
double surfaceArea2 = box2.getSurfaceArea();
cout<<"volume1= "<<volume1<<"surfaceArea1= "<<surfaceArea1<<"volume2= "<<volume2<<"surfaceArea2= "<<surfaceArea2<<endl;
Box arr[20];
srand (time(NULL));
for(int i=0; i<20;i++){
double h=(i+1)*(rand() % 3) + 12, w=(i+1)*(rand() % 2) + 6,l=(i+1)*(rand() % 3) +7;
arr[i].setHeight(h);
arr[i].setWidth(w);
arr[i].setLength(l);
//cout<<"Box No."<<i <<" "<< " L: "<< l<< " W:"<< w<<" H:"<<h<<" volume: "<<arr[i].getVolume()<<endl;
}
showArray(arr, 20);
boxSort(arr, 20);
cout<<"Now Sorted:"<<endl;
showArray(arr, 20);
}
*/ | true |
c2ae966455af8b5c65991fdefa1c38d2d810da2e | C++ | cksharma/coding | /cpp/c++17/unordered_map/order.cpp | UTF-8 | 3,122 | 3.46875 | 3 | [] | no_license | #include <bits/stdc++.h>
class Order
{
public:
std::string ticker_; // name of the company, e.g., MSFT, IBM, GOOG
int userId_; // id of the user working on the order
std::string side_; // "BUY" - order to buy, "SELL" - order to sell
int qty_; // number of shares to buy/sell
double price_;
Order( std::string ticker,
int userId,
std::string side,
int qty, double price ) :
ticker_(ticker), userId_(userId), side_(side), qty_(qty), price_(price) {}
bool operator==(const Order& o1) const {
return ticker_ == o1.ticker_ && userId_ == o1.userId_;
}
};
std::ostream& operator<<(std::ostream& os, const Order& o1) {
os << o1.ticker_ << ", " << o1.price_ << "\n" ;
return os;
}
class Tuple {
public:
std::string ticker_;
int userId_;
Tuple(std::string ticker, int userId)
: ticker_(ticker), userId_(userId) {}
};
namespace std {
template<>
struct hash<Order> {
size_t operator()(const Order& order) const {
return hash<string>()(order.ticker_) + order.userId_;
}
};
}
struct OrderHasher
{
std::size_t operator()( const Order& order ) const {
return std::hash<std::string>()( order.ticker_)
+ std::hash<int>()(order.userId_);
}
};
struct OrderComparator
{
bool operator()( const Order& order1, const Order& order2 ) {
if( order1.ticker_ != order2.ticker_ ) return order1.ticker_ < order2.ticker_;
return order1.price_ < order2.price_;
}
};
//Q1) (Ticker, UserID) -> the list of orders with Order::ticker_ = Ticker that are worked by the user UserID (Order::userId_ == UserID)
void testInsertAndFetchO1()
{
Order order1( "MSFT", 1234, "B", 100, 100);
Order order2( "MSFT", 1234, "B", 100, 200);
Order order3( "APPL", 1234, "B", 100, 300);
Order order4( "MSFT", 1234, "B", 100, 400);
Order order5( "GOOG", 1234, "B", 100, 500);
Order order6( "GOOG", 1234, "B", 100, 600);
Order order7( "XYZZ", 1234, "B", 100, 600);
//std::set<Order, OrderComparator> uSet = {order1, order2, order3, order4, order5, order6 };
std::set<Order, OrderComparator> uSet = {order1, order4, order6, order7 };
std::cout << "USET size" << uSet.size() << std::endl;
std::unordered_set<Order, OrderHasher> hSet;
hSet.insert( order1 );
hSet.insert( order1 );
std::cout << "HASH" << std::endl;
auto it = hSet.find(order1);
if ( it != hSet.end() )
{
std::cout << *it << std::endl;
}
std::cout << "END" << std::endl;
Order orderLimit( "MSFT", 1234, "B", 100, 400);
for( auto k = uSet.begin(); k != uSet.end(); ++k) {
std::cout << *k << std::endl;
}
auto it1 = uSet.upper_bound( orderLimit );
if ( it1 != uSet.end() ) {
std::cout << "SET" << std::endl;
std::cout << *it1 << std::endl;
} else {
std::cout << "IMPOSSIBLE" << std::endl;
}
}
//Q2) (Ticker, Price) -> the order with the given Ticker having the lowest Order::price_ >= Price
int main()
{
testInsertAndFetchO1();
} | true |
2f325a82d07b1ed9fe91d094e5aa6711cb188555 | C++ | yuxiang660/little-bee-socket | /src/internal/EventTimerHandlerQueue.h | UTF-8 | 987 | 2.515625 | 3 | [] | no_license | #pragma once
#include "internal/system/EventModifierInterface.h"
#include "internal/system/EventTimerFd.h"
#include "internal/system/Event.h"
#include "internal/system/Timestamp.h"
#include "TimerHandler.h"
#include <map>
#include <vector>
namespace cbee
{
class EventTimerHandlerQueue
{
public:
EventTimerHandlerQueue(const EventModifierInterface& modifier);
~EventTimerHandlerQueue();
void addHandler(const TimerHandler& handler);
void cancelHandler(int id);
private:
EventTimerHandlerQueue(const EventTimerHandlerQueue&) = delete;
EventTimerHandlerQueue& operator=(const EventTimerHandlerQueue&) = delete;
void handleRead();
std::vector<TimerHandler> extractExpiredHandlers(Timestamp handleTime);
void triggerEvent(const std::vector<TimerHandler>& expiredHandlers, Timestamp handleTime);
private:
const EventModifierInterface& eventModifier;
const EventTimerFd fd;
Event event;
std::multimap<Timestamp, TimerHandler> handlerQueue;
};
}
| true |
c1cca1d1512fce6ea61f090c68ab651d3db4d588 | C++ | south-potato/poseidonos | /test/unit-tests/lib/counter_timeout_checker_test.cpp | UTF-8 | 1,136 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "src/lib/counter_timeout_checker.h"
#include <gtest/gtest.h>
namespace pos
{
TEST(CounterTimeoutChecker, CounterTimeoutChecker_)
{
//When: Create target object in stack
CounterTimeoutChecker ctc;
//Then: Do nothing
//When: Create target object in Heap
CounterTimeoutChecker* pCtc = new CounterTimeoutChecker();
delete pCtc;
//Then: Do nothing
}
TEST(CounterTimeoutChecker, SetTimeout_)
{
//Given
CounterTimeoutChecker ctc;
//When
ctc.SetTimeout(1);
//Then: Do nothing
}
TEST(CounterTimeoutChecker, CheckTimeout_)
{
//Given
CounterTimeoutChecker ctc;
//When: check default timeout status
//Then: timeout should occur since remaining count is 0
EXPECT_TRUE(ctc.CheckTimeout());
//When: set timeout count to 2
ctc.SetTimeout(2);
//Then: timeout should not occur (remaining count is 2)
EXPECT_FALSE(ctc.CheckTimeout());
//Then: timeout should not occur (remaining count is 1)
EXPECT_FALSE(ctc.CheckTimeout());
//Then: timeout should occur (remaining count is 0)
EXPECT_TRUE(ctc.CheckTimeout());
}
} // namespace pos
| true |
c6616f9f55f5601e3f744fa2a7236bb4bd9a59c9 | C++ | FinancialEngineerLab/quantnet-baruch-certificate-cpp | /Level 5_Inheritance_Generalisation_Specialisation/Section 3_5/Exercise 4/Exercise 4/TestExercise4.cpp | UTF-8 | 862 | 3.078125 | 3 | [] | no_license | //Test inheritance concepts.
#include <iostream>
#include "stdlib.h"
#include <ctime>
#include "Shape.h"
#include "Point.hpp"
#include "Line.hpp"
#include "Circle.hpp"
using namespace std;
using namespace Shihan;
using namespace CAD;
int main ()
{
srand( time(0)); //The pseudo-random number generator is initialized using the argument passed.
Shape* shapes[3]; // Still I can create the Shape pointers though Shape is an abstract base class.
//shapes[0] = new Shape; //I can't create instances of the Shape class. It is an abstract base class now.
shapes[0] = new Line;
shapes[1] = new Point;
shapes[2] = new Circle;
for(int i=0; i!=3;i++) shapes[i] -> Draw(); // Checking Draw() of concrete shapes like Line, Point and Circle.
cout <<""<<endl;
for(int i=0; i!=3; i++) delete shapes[i];
system("pause");
return 0;
} | true |
8e0f9bfaf8f04c8b1008bd5efc37d9794e8b3c22 | C++ | afikur/UVA-Solutions | /11799 Horror Dash.cpp | UTF-8 | 524 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int maximum(int *a, int n) {
int max_val = a[0];
for(int i=1; i<n; i++) {
if(max_val < a[i]) {
max_val = a[i];
}
}
return max_val;
}
int main()
{
int testCase, n, *a;
cin>>testCase;
for(int i = 1; i <= testCase; i++) {
cin>>n;
a = new int[n];
for(int j = 0; j < n; j++) {
cin>>a[j];
}
printf("Case %d: %d\n", i, maximum(a,n));
}
return 0;
}
| true |
c13b752c0a905c24bb9699f9fa271b544afeb6fa | C++ | jsl4980/Guessing | /src/mainwindow.cpp | UTF-8 | 1,984 | 2.765625 | 3 | [] | no_license | #include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "round.h"
#include <QStackedWidget>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_startButton_clicked()
{
// Switch pages to second page
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_goButton_clicked()
{
// Switch to the game page
setupRound();
ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_questionButton_clicked()
{
setQuestions(round->questionAsked());
}
void MainWindow::on_gameOverBtn_clicked()
{
round->guessRight();
if(round->isGameOver()) {
finishRound();
}
}
void MainWindow::on_clueBtn_clicked()
{
setClues(round->giveClue());
}
void MainWindow::on_startOverBtn_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::setupRound()
{
round = new Round();
setClues(round->getClues());
setQuestions(round->getQuestions());
ui->animalLabel->setText(QString::fromStdString(round->getAnimalName()));
QPixmap pic(":/images/resources/cat_cropped.jpeg");
ui->animalPicture->setPixmap(pic);
}
void MainWindow::finishRound()
{
// Change to finish window
ui->stackedWidget->setCurrentIndex(3);
// Print results
if(round->isGameWon()) {
ui->resultLabel->setText("Congratulations!");
ui->detailLabel->setText(QString("You guessed %1 in %2 questions!")
.arg(QString::fromStdString(round->getAnimalName()))
.arg(round->getQuestions()));
} else {
// Ran out of questions, todo later
}
// Delete the round
delete round;
}
void MainWindow::setQuestions(int q)
{
ui->questionLabel->setText(QString("Question Count: %1").arg(q));
}
void MainWindow::setClues(int c)
{
ui->clueCount->setText(QString("Clue Count: %1").arg(c));
}
| true |
a0a64a8648d2ba209ea92e8be70118c63ca55bbe | C++ | CSID-DGU/2018-2-CCD-Dreamocon-1 | /sketch_CAP_IRsend_dec11_2.ino | UTF-8 | 2,618 | 2.609375 | 3 | [] | no_license | #include <IRremote.h>
IRsend irsend;
int khz = 38;
void setup() {
//for sending IR
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("on");
turnOn();
delay(10000);
Serial.println("up");
tempUp();
delay(10000);
Serial.println("down");
tempDown();
delay(10000);
Serial.println("off");
turnOff();
delay(10000);
}
void turnOn(){
//remote 1 FF30CF
unsigned int turnon[] = {9100,4400, 600,550, 650,500, 650,550, 600,550, 600,550, 600,550, 600,550, 600,550, 600,1600, 600,1600, 650,1600, 600,1600, 650,1550, 650,1600, 650,1550, 650,1600, 650,500, 650,500, 650,1550, 650,1600, 650,500, 650,500, 650,500, 650,550, 600,1550, 650,1600, 650,500, 650,500, 650,1550, 650,1600, 600,1600, 650,1600, 600}; // NEC FF30CF
irsend.sendRaw (turnon, sizeof(turnon) / sizeof(turnon[0]) , khz); // Note the apporach used to automatically calcualate the size of the array;
}
void turnOff(){
//remote 0 FF42BD
unsigned int turnoff[] = {9000,4450, 600,550, 600,550, 600,550, 600,550, 600,550, 600,550, 550,600, 600,550, 600,1650, 550,1650, 600,1650, 550,1650, 600,1650, 550,1650, 600,1650, 550,1650, 600,550, 600,1650, 550,600, 550,600, 550,600, 550,600, 600,1600, 600,550, 600,1650, 550,600, 550,1650, 600,1650, 550,1650, 600,1650, 550,600, 550,1650, 600}; // NEC FF42BD
irsend.sendRaw (turnoff, sizeof(turnoff) / sizeof(turnoff[0]) , khz); // Note the apporach used to automatically calcualate the size of the array;
}
void tempUp(){
//remote 2 FF18E7
unsigned int tempup[] = {9050,4400, 650,550, 600,550, 600,550, 600,550, 600,550, 600,550, 600,550, 600,550, 600,1600, 600,1600, 650,1600, 600,1600, 650,1550, 650,1600, 650,1550, 650,1600, 600,550, 600,550, 600,550, 600,1600, 650,1600, 600,550, 600,550, 600,550, 600,1600, 650,1600, 600,1600, 650,550, 600,550, 600,1600, 600,1600, 600,1600, 600}; // NEC FF18E7
irsend.sendRaw (tempup, sizeof(tempup) / sizeof(tempup[0]) , khz); // Note the apporach used to automatically calcualate the size of the array;
}
void tempDown(){
//remote 3 FF7A85
unsigned int tempdown[] = {9050,4400, 650,550, 600,500, 650,500, 650,500, 650,500, 650,500, 650,500, 650,500, 650,1600, 600,1600, 650,1600, 600,1600, 650,1550, 650,1600, 650,1550, 650,1600, 600,550, 600,1600, 650,1600, 600,1600, 650,1600, 600,550, 600,1600, 650,500, 650,1600, 600,550, 550,600, 600,550, 600,550, 600,1600, 650,500, 650,1600, 600}; // NEC FF7A85
irsend.sendRaw (tempdown, sizeof(tempdown) / sizeof(tempdown[0]) , khz); // Note the apporach used to automatically calcualate the size of the array;
}
| true |
91175ddf41faac59d566a4f684c72a49e7073e29 | C++ | ProkopHapala/SimpleSimulationEngine | /cpp/tests/lua/test_Lua_callback.cpp | UTF-8 | 3,357 | 2.703125 | 3 | [
"MIT"
] | permissive | // see tutorial
// https://csl.name/post/lua-and-cpp/
#include <stdio.h>
#ifdef __cplusplus
# include <lua5.2/lua.hpp>
#else
# include <lua5.2/lua.h>
# include <lua5.2/lualib.h>
# include <lua5.2/lauxlib.h>
#endif
#include "Vec3.h"
#include "Mat3.h"
#include "LuaHelpers.h"
//lua_State *state = NULL;
extern "C"
int howdy(lua_State* state){
// The number of function arguments will be on top of the stack.
int args = lua_gettop(state);
printf("howdy() was called with %d arguments:\n", args);
for ( int n=1; n<=args; ++n) {
printf(" argument %d: '%s'\n", n, lua_tostring(state, n));
}
// Push the return value on top of the stack. NOTE: We haven't popped the
// input arguments to our function. To be honest, I haven't checked if we
// must, but at least in stack machines like the JVM, the stack will be
// cleaned between each function call.
lua_pushnumber(state, 123);
// Let Lua know how many return values we've passed
return 1;
}
void doSomePhysics(int n, Vec3d pos, Vec3d vel){
//printf( "%i (%g,%g,%g) (%g,%g,%g) \n", n, pos.x, pos.y, pos.z, vel.x, vel.y, vel.z );
Vec3d G = {0.0,0.0,-9.81};
double dt = 0.03;
double restitution = -1.0;
for(int i=0; i<n; i++){
vel.add_mul(G,dt);
pos.add_mul(vel,dt);
printf("%i pos=(%g,%g,%g) (%g,%g,%g)\n", i, pos.x, pos.y, pos.z, vel.x, vel.y, vel.z );
if( (pos.z<0)&&(vel.z<0) ) vel.z*=restitution;
}
};
void doSomePhysics2(int n, Vec3d pos, Mat3d mat){
printf( " -------------- \n" );
printf( " n=%i pos=(%g,%g,%g) \n", n, pos.x, pos.y, pos.z );
printf("mat = \n");
mat.print();
};
extern "C"
int l_doSomePhysics(lua_State* L){
// lua interface for doSomePhysics
Vec3d pos,vel;
int n = lua_tointeger(L, 1);
Lua::getVec3(L, 2, pos );
Lua::getVec3(L, 3, vel );
doSomePhysics(n,pos,vel);
//lua_pushnumber(L, 123);
return 3;
}
extern "C"
int l_doSomePhysics2(lua_State* L){
// lua interface for doSomePhysics
Vec3d pos;
Mat3d mat;
int n = lua_tointeger(L, 1);
Lua::getVec3(L, 2, pos );
Lua::getMat3(L, 3, mat );
doSomePhysics2(n,pos,mat);
Lua::dumpStack(L);
//Lua::pushnumber(L, 123);
return 3;
}
void print_error(lua_State* state) {
// The error message is on top of the stack.
// Fetch it, print it and then pop it off the stack.
const char* message = lua_tostring(state, -1);
puts(message);
lua_pop(state, 1);
}
void execute(lua_State* state, const char* filename){
// Make standard libraries available in the Lua object
luaL_openlibs(state);
int result;
// Load the program; this supports both source code and bytecode files.
result = luaL_loadfile(state, filename);
if ( result != LUA_OK ) { print_error(state); return; }
// Finally, execute the program by calling into it.
// Change the arguments if you're not running vanilla Lua code.
result = lua_pcall(state, 0, LUA_MULTRET, 0);
if ( result != LUA_OK ) { print_error(state); return; }
}
int main(int argc, char** argv){
lua_State *state = luaL_newstate();
lua_register(state, "doSomePhysics", l_doSomePhysics);
lua_register(state, "doSomePhysics2", l_doSomePhysics2);
//execute( state, "data/hello.lua" );
//execute( state, "data/callback.lua" );
execute( state, "data/doSomePhysics.lua" );
}
| true |
9b8cb312bda871e4a34a28f369c609e1b994c7bf | C++ | cjr310/leetcode | /494_Target Sum.cpp | UTF-8 | 2,064 | 3.703125 | 4 | [] | no_license | // You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
// Find out how many ways to assign symbols to make sum of integers equal to target S.
// Example 1:
// Input: nums is [1, 1, 1, 1, 1], S is 3.
// Output: 5
// Explanation:
// -1+1+1+1+1 = 3
// +1-1+1+1+1 = 3
// +1+1-1+1+1 = 3
// +1+1+1-1+1 = 3
// +1+1+1+1-1 = 3
// There are 5 ways to assign symbols to make the sum of nums be target 3.
// Note:
// The length of the given array is positive and will not exceed 20.
// The sum of elements in the given array will not exceed 1000.
// Your output answer is guaranteed to be fitted in a 32-bit integer.
#include <unordered_map>
#include <vector>
using namespace std;
//dfs
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int res=0;
helper(nums, S, 0, res );
return res;
}
void helper(vector<int>& nums, long S, int start, int& res){
if(start == nums.size()) {
if(S==0) res++; return;
}
helper(nums, S-nums[start], start+1, res);
helper(nums, S+nums[start], start+1, res);
}
};
//dp
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int n = nums.size();
vector<unordered_map<int, int>> dp(n+1);
dp[0][0] = 1;
for(int i=0; i<n; i++){
for(auto &a : dp[i]){
int sum = a.first, count = a.second;
dp[i+1][sum+nums[i]] += count;
dp[i+1][sum-nums[i]] += count;
}
}
return dp[n][S];
}
};
//思路:1.dfs 写个递归,记录当前位置以及剩余数的sum,
//2. dp 维护数组dp[i][j] 为到第i-1个数且和为j的所有情况数。
//dp转移方程 dp[i+1][sum+nums[i]] += count;
// dp[i+1][sum-nums[i]] += count;
//count的意思是 dp[n]下每个dp[n][j]的值,
//那么到i+1的时候把这些i的情况都加上 | true |
efdeaa5477f651de276192170a86af9129b0655d | C++ | kaliningleb25/stl | /lab8_1/main.cpp | UTF-8 | 1,125 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <math.h>
using namespace std;
/* Калинин Глеб (23531/21-1)
*
*
* Разработать программу, которая, используя только стандартные алгоритмы и функторы,
* умножает каждый элемент списка чисел с плавающей точкой на число PI
*/
class Mult {
public:
Mult():n(0),res(0) {};
void operator() (float n) {
res = n * M_PI;
cout << res << " ";
}
float getRes() {
return res;
}
private:
float n,res;
};
int main() {
vector<float> vec;
// Заполнение вектора:
for (int i = 0; i < 10; i++) {
vec.push_back(i * 0.1);
}
cout << "Исходный список:\n";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << "\n";
// Умножение каждого элемента списка на число Пи
cout << "Новый список\n";
(for_each(vec.begin(), vec.end(), Mult())).getRes();
return 0;
} | true |
009f677ccc1fceebd22743726c7f4a8064d6e524 | C++ | YurieCo/GO | /geomtest/Dot.cpp | UTF-8 | 1,081 | 2.65625 | 3 | [] | no_license | /*
* Dot.cpp
*
* Created on: 09-10-2011
* Author: ghik
*/
#include "commons.h"
#include "Dot.h"
#include <cairo/cairo.h>
Dot::Dot() {
}
Dot::Dot(double _x, double _y) :
x(_x), y(_y), size(POINT_SIZE) {
setColor(fillColor, lineColor);
}
Dot::~Dot() {
}
void Dot::draw(cairo_t *cr) const {
beginDraw(cr, x, y, rad(0));
applyLineColor(cr);
cairo_move_to(cr, size/fabs(zoom), 0);
cairo_arc(cr, 0, 0, size/fabs(zoom), 0, rad(360));
cairo_stroke_preserve(cr);
applyFillColor(cr);
cairo_fill(cr);
cairo_move_to(cr, 0, 0);
putLabel(cr);
cairo_stroke(cr);
endDraw(cr);
}
void Dot::registerDraggables(vector<Draggable*>& draggables) {
draggables.push_back(this);
}
bool Dot::drags(double x, double y) {
return dist(this->x, this->y, x, y) <= size/zoom;
}
void Dot::draggedTo(double x, double y) {
this->x = x;
this->y = y;
}
ostream& Dot::serialize(ostream& str) const {
str << "dot " << x << " " << y << " " << size << ' ' << label << endl;
return str;
}
ostream& Dot::raw_serialize(ostream& str) const {
return str << x << ' ' << y << endl;
}
| true |
08688c3244efe96fd0f0a2958a2630ccefc1af7b | C++ | MohitSingh2002/CompleteCpp | /Data Structires And Algorithms/7_graph/1_graph.cpp | UTF-8 | 4,435 | 3.21875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void printDFS(int**, int, int, bool*);
void printBFS(int**, int, int, bool*);
void printDFSUnconnectedGraph(int**, int);
void printBFSUnconnectedGraph(int**, int);
// bool hasPathDFS(int**, int, int, int, int*);
// bool hasPathDFS(int**, int, int, int);
int main() {
int numberOfNodes, numberOfEdges;
cin >> numberOfNodes >> numberOfEdges;
int **edges = new int*[numberOfNodes];
for (int i = 0; i < numberOfNodes; i++) {
edges[i] = new int[numberOfNodes];
for(int j = 0; j < numberOfNodes; j++) {
edges[i][j] = 0;
}
}
for(int i = 0; i < numberOfEdges; i++) {
int startingNode, endingNode;
cin >> startingNode >> endingNode;
edges[startingNode][endingNode] = 1;
edges[endingNode][startingNode] = 1;
}
// bool *visitedVertex = new bool[numberOfNodes];
// for(int i = 0; i < numberOfNodes; i++) {
// visitedVertex[i] = false;
// }
cout << "DFS :-" << " ";
// printDFS(edges, numberOfNodes, 0, visitedVertex);
printDFSUnconnectedGraph(edges, numberOfNodes);
cout << endl;
cout << "BFS :-" << " ";
// printBFS(edges, numberOfNodes, 0, visitedVertex);
printBFSUnconnectedGraph(edges, numberOfNodes);
cout << endl;
// cout << "Is their a path between 1 and 6 ? " << hasPathDFS(edges, numberOfNodes, 1, 6);
// delete[] visitedVertex;
for(int i = 0; i < numberOfNodes; i++) delete [] edges[i];
delete [] edges;
return 0;
}
void printDFS(int **edges, int n, int startingVertex, bool *visitedVertex) {
cout << startingVertex << " ";
visitedVertex[startingVertex] = true;
for(int i=0;i<n;i++) {
if(startingVertex == i) continue;
if(edges[startingVertex][i] == 1) {
if(visitedVertex[i]) continue;
printDFS(edges, n, i, visitedVertex);
}
}
// This is DFS (Depth First Search).
// Go in one direction untill it's end came.
}
void printBFS(int **edges, int n, int startingVertex, bool *visitedVertex) {
// bool *visitedVertex = new bool[n];
// for(int i=0;i<n;i++) {
// visitedVertex[i] = false;
// }
queue<int> pendingVertex;
pendingVertex.push(startingVertex);
visitedVertex[startingVertex] = true;
while(!pendingVertex.empty()) {
int currentVertex = pendingVertex.front();
pendingVertex.pop();
cout << currentVertex << " ";
for(int i = 0; i < n; i++) {
if(currentVertex == i) continue;
if(edges[currentVertex][i] == 1 && !visitedVertex[i]) {
pendingVertex.push(i);
visitedVertex[i] = true;
}
}
}
// This is BFS (Breadth First Search).
// Same as level order traversal in Trees.
}
void printDFSUnconnectedGraph(int **edges, int n) {
bool *visited = new bool[n];
for(int i=0;i<n;i++)
visited[i] = false;
for(int i=0;i<n;i++)
if(!visited[i])
printDFS(edges, n, i, visited);
delete [] visited;
}
void printBFSUnconnectedGraph(int **edges, int n) {
bool *visited = new bool[n];
for(int i=0;i<n;i++)
visited[i] = false;
for(int i=0;i<n;i++)
if(!visited[i])
printBFS(edges, n, i, visited);
delete [] visited;
}
// bool hasPathDFS(int **edges, int n, int startingVertex, int endingVertex, int *visited) {
// visited[startingVertex] = true;
// visited[endingVertex] = true;
// if(edges[startingVertex][endingVertex] == 1) {
// return true;
// }
// for(int i=startingVertex;i<=endingVertex;i++) {
// if(startingVertex == i) continue;
// if(edges[startingVertex][i] == 1) {
// if(visited[i]) continue;
// return hasPathDFS(edges, n, startingVertex, i, visited);
// }
// }
// }
// bool hasPathDFS(int **edges, int n, int startingVertex, int endingVertex) {
// bool *visited = new bool[n];
// for(int i=0;i<n;i++)
// visited[i] = false;
// return hasPathDFS(edges, n, startingVertex, endingVertex, visited);
// }
| true |
be4e06a1465ec00fa5df82791a4c7c7ecb020548 | C++ | zhanghuanzj/cpp | /剑指Offer/JZOffer44.cpp | UTF-8 | 520 | 3.1875 | 3 | [
"Apache-2.0"
] | permissive | class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
if(numbers.size()<5) return false;
int max = INT_MIN,min = INT_MAX;
int zeroCount = 0;
for(auto v : numbers)
{
if(v!=0)
{
if(v>max) max = v;
if(v<min) min = v;
}
else
{
++zeroCount;
}
}
if(max-min>4) return false;
if(zeroCount==4) return true;
vector<int> vec(5);
for(auto v : numbers)
{
if(v!=0)
{
++vec[v-min];
}
}
for(auto v : vec)
if(v>1) return false;
return true;
}
}; | true |
3b9c7df0e71dc7c6c621f5863d3c45b0429702d7 | C++ | EvanMorcom/Software | /src/software/primitive/stop_primitive.h | UTF-8 | 1,602 | 3.40625 | 3 | [
"LGPL-3.0-only"
] | permissive | #pragma once
#include "software/primitive/primitive.h"
class StopPrimitive : public Primitive
{
public:
static const std::string PRIMITIVE_NAME;
/**
* Creates a new Stop Primitive
*
* Stops the robot with the option to coast to a stop rather than stop immediately
*
* @param robot_id The id of the Robot to run this Primitive
* @param coast to coast to a stop or not
*/
explicit StopPrimitive(unsigned int robot_id, bool coast);
std::string getPrimitiveName() const override;
unsigned int getRobotId() const override;
/**
* Gets whether the robot should coast or not
*
* @return whether the robot should coast to a stop
*/
bool robotShouldCoast() const;
void accept(PrimitiveVisitor& visitor) const override;
/**
* Compares StopPrimitives for equality. StopPrimitives are considered equal if all
* their member variables are equal.
*
* @param other the StopPrimitive to compare with for equality
* @return true if the StopPrimitives are equal and false otherwise
*/
bool operator==(const StopPrimitive& other) const;
/**
* Compares StopPrimitives for inequality.
*
* @param other the StopPrimitive to compare with for inequality
* @return true if the StopPrimitives are not equal and false otherwise
*/
bool operator!=(const StopPrimitive& other) const;
private:
unsigned int robot_id;
// whether the robot should apply power to its wheels to stop
// or should stop naturally, not applying power
bool coast;
};
| true |
90e6d318fbc35d233e56464525e9feb5d3067af0 | C++ | 0003088/libelektra-qt-gui-test | /src/tools/kdb/merge.hpp | UTF-8 | 1,117 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef MERGE_HPP
#define MERGE_HPP
#include <command.hpp>
#include <kdb.hpp>
using namespace std;
class MergeCommand : public Command
{
kdb::KDB kdb;
public:
MergeCommand();
~MergeCommand();
virtual int execute (Cmdline const& cmdline);
virtual std::string getShortOptions()
{
return "iHtsvf";
}
virtual std::string getSynopsis()
{
return "[options] ourpath theirpath basepath resultpath";
}
virtual std::string getShortHelpText()
{
return "Three-way merge of KeySets.";
}
virtual std::string getLongHelpText()
{
return
"Does a three-way merge between keysets.\n"
"On success the resulting keyset will be saved to mergepath.\n"
"On unresolved conflicts nothing will be changed.\n"
"\n"
"Conflicts in a merge can be resolved using a strategy with -s.\n"
"\n"
"ourpath .. path to the keyset to serve as ours\n"
"theirpath .. path to the keyset to serve as theirs\n"
"basepath .. path to the base keyset\n"
"resultpath .. path without keys where the merged keyset will be saved\n"
" (use -b to override results)\n"
;
}
};
#endif
| true |
19f3d667ae90b4b7126047f05e3cff5e4f8358ea | C++ | shanky1947/Data-Structures-and-Algorithm | /Coding Ninjas/Binary Tree/4_mirror.cpp | UTF-8 | 1,110 | 3.859375 | 4 | [] | no_license | /*
Code : Mirror
Send Feedback
Mirror the given binary tree. That is, right child of every nodes should become left and left should become right.
Alt text
Note : You don't need to print or return the tree, just mirror it.
Input format :
Line 1 : Elements in level order form (separated by space)
(If any node does not have left or right child, take -1 in its place)
Output format : Elements in level order form (Every level in new line)
Sample Input 1:
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
Sample Output 1:
1
3 2
7 6 5 4
Sample Input 2:
5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1
Sample Output 2:
5
6 10
3 2
9
*/
void mirrorBinaryTree(BinaryTreeNode<int>* root) {
// Write your code here
if(root==NULL)
return;
BinaryTreeNode<int>* temp=root->left;
root->left=root->right;
root->right=temp;
mirrorBinaryTree(root->left);
mirrorBinaryTree(root->right);
}
/*
void mirrorBinaryTree(BinaryTreeNode<int>* root) {
if(root==NULL)
return;
swap(root->left->data,root->right->data);
mirrorBinaryTree(root->left);
mirrorBinaryTree(root->right);
}
*/ | true |
97da039966bd755f5ebbb2ea37c89e17c5e7f247 | C++ | ajayt6/AlgoPractice | /c++/WildCardMatch.cpp | UTF-8 | 1,002 | 3.09375 | 3 | [] | no_license | /*
https://leetcode.com/problems/wildcard-matching/
Not correct answer yet
*/
#include<iostream>
#include<string>
using namespace std;
bool isMatch(string s, string p) {
int i = 0, j = 0,starFlag=0,solidPointer = 0;
while (i < p.length() && j < s.length())
{
switch (p[i])
{
case '*':
i++;
starFlag = 1;
break;
case '?':
//handle case when starFlag is not set
if (starFlag == 1)
{
j++;
}
else
{
i++;
j++;
}
break;
default:
if (starFlag == 1)
{
starFlag = 0;
while (j < s.length() && s[j] != p[i])
{
j++;
}
if (j == s.length())
return false;
i++;
j++;
}
break;
}
}
if (j<s.length() || j>s.length())
return false;
else if (i < p.length())
return false;
return true;
}
int main()
{
string s, p;
cout << "Enter the string to be matched: ";
cin >> s;
cout << "Enter the format: ";
cin >> p;
cout<<"The output of isMatch function is: "<<isMatch(s, p);
getchar();
return 0;
} | true |
3cbc6873333b7908fa08ee3269319ca9f1d6758c | C++ | bryanlawsmith/Raytracing | /Raytracer (Offline)/KdTreeGeometry.cpp | UTF-8 | 3,962 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "KdTreeGeometry.h"
#include "KdTreeStackTraversal.h"
#include "KdTreeNode.h"
#include "NaiveSpatialMedian.h"
#include "SAH.h"
#include <MemoryAllocatorAligned.h>
#include <Geometry.h>
#include <cassert>
using namespace MathLib;
using namespace Assets;
using namespace Core;
namespace Raytracer
{
KdTreeGeometry::KdTreeGeometry(const StaticMesh& mesh) :
m_Triangles(nullptr)
{
Initialize(mesh);
}
KdTreeGeometry::~KdTreeGeometry()
{
FreeMemory();
}
void KdTreeGeometry::Initialize(const StaticMesh& mesh)
{
FreeMemory();
auto numVertices = mesh.GetNumVertices();
auto numIndices = mesh.GetNumIndices();
assert(0 == numIndices % 3);
auto vertexArray = mesh.GetVertexArray();
auto normalArray = mesh.GetNormalArray();
auto texCoordArray = mesh.GetTexCoordArray();
auto indexArray = mesh.GetIndexArray();
// Calculate and allocate required storage space.
m_NumTriangles = numIndices / 3;
m_Triangles = reinterpret_cast<Triangle*>(MemoryAllocatorAligned::Allocate((size_t)m_NumTriangles * sizeof(Triangle)));
for (unsigned int i = 0; i < numIndices; i += 3)
{
Triangle& currentTriangle = m_Triangles[i / 3];
for (unsigned int v = 0; v < 3; v++)
{
auto currentIndex = indexArray[i + v];
auto currentVertex = vertexArray + (currentIndex * 3);
auto currentNormal = normalArray + (currentIndex * 3);
auto currentTexCoord = texCoordArray + (currentIndex * 2);
currentTriangle.m_Vertices[v].m_Position.setXYZW(currentVertex[0], currentVertex[1], currentVertex[2], 1.0f);
currentTriangle.m_Vertices[v].m_Normal.setXYZW(currentNormal[0], currentNormal[1], currentNormal[2], 0.0f);
currentTriangle.m_Vertices[v].m_TexCoord.setXYZW(currentTexCoord[0], currentTexCoord[1], 0.0f, 0.0f);
}
}
// Calculate the bounding volume.
GeometryLib::CalculateBoundingVolume(vertexArray, numVertices, m_Bounds[AABB_EXTENTS_MIN], m_Bounds[AABB_EXTENTS_MAX]);
// Construct the kd tree.
{
using namespace KdTreeConstruction;
//KdTreeConstruction::NaiveSpatialMedian kdTreeBuilder;
KdTreeConstruction::SAH kdTreeBuilder(16, 16);
kdTreeBuilder.Construct(*this);
}
}
void KdTreeGeometry::FreeMemory()
{
if (nullptr != m_Triangles)
{
MemoryAllocatorAligned::Deallocate(reinterpret_cast<void*>(m_Triangles));
m_Triangles = nullptr;
}
m_NumTriangles = 0;
ResetKdTree();
}
void KdTreeGeometry::ResetKdTree()
{
if (nullptr != m_RootNode)
delete m_RootNode;
m_RootNode = nullptr;
}
bool KdTreeGeometry::Trace(const ray& intersectionRay, float* t, float* results) const
{
IKdTreeTraversal& traversalAlgorithm = KdTreeStackTraversal();
float u;
float v;
unsigned int intersectedTriangleIndex;
if (traversalAlgorithm.Traverse(*this, intersectionRay, &intersectedTriangleIndex, t, &u, &v))
{
// Shade result.
vector4 objectSpaceNormal;
objectSpaceNormal.setXYZW(0.0f, 0.0f, 0.0f, 0.0f);
vector4_addScaledVector(objectSpaceNormal, m_Triangles[intersectedTriangleIndex].m_Vertices[0].m_Normal, 1.0f - u - v, objectSpaceNormal);
vector4_addScaledVector(objectSpaceNormal, m_Triangles[intersectedTriangleIndex].m_Vertices[1].m_Normal, v, objectSpaceNormal);
vector4_addScaledVector(objectSpaceNormal, m_Triangles[intersectedTriangleIndex].m_Vertices[2].m_Normal, u, objectSpaceNormal);
vector4_normalize(objectSpaceNormal);
float lightFactor = vector4_dotProduct(objectSpaceNormal, vector4(0.0f, 1.0f, 0.0f, 0.0f));
if (lightFactor > 1.0f) lightFactor = 1.0f;
if (lightFactor < 0.0f) lightFactor = 0.0f;
results[0] = lightFactor;
results[1] = lightFactor;
results[2] = lightFactor;
results[3] = 1.0f;
return true;
}
return false;
}
Triangle const * KdTreeGeometry::GetTriangles() const
{
return m_Triangles;
}
unsigned int KdTreeGeometry::GetNumTriangles() const
{
return m_NumTriangles;
}
KdTreeNode* KdTreeGeometry::GetRootNode() const
{
return m_RootNode;
}
} | true |
a3fb3cdab05b99f303828d79d98af0fbcb10a7ce | C++ | sadanjon/meow | /src/entities/position_mesh/iposition_mesh_generator_factory.h | UTF-8 | 1,293 | 2.578125 | 3 | [] | no_license | #ifndef IPOSITION_MESH_GENERATOR_H
#define IPOSITION_MESH_GENERATOR_H
#include <memory>
#include "model.h"
namespace meow {
class IPositionMesh {
public:
IPositionMesh() {}
virtual ~IPositionMesh() {}
IPositionMesh(const IPositionMesh&) = delete;
IPositionMesh &operator=(const IPositionMesh &) = delete;
virtual const IndexList &getOriginalVertexIndicesAt(IndexType index) const = 0;
virtual std::shared_ptr<Mesh> getMesh() const = 0;
class VertexNotFound : std::exception {};
};
class IPositionMeshGenerator {
public:
IPositionMeshGenerator() {}
virtual ~IPositionMeshGenerator() {}
IPositionMeshGenerator(const IPositionMeshGenerator&) = delete;
IPositionMeshGenerator &operator=(const IPositionMeshGenerator&) = delete;
virtual std::shared_ptr<IPositionMesh> generate() = 0;
};
class IPositionMeshGeneratorFactory {
public:
IPositionMeshGeneratorFactory() {}
virtual ~IPositionMeshGeneratorFactory() {}
IPositionMeshGeneratorFactory(const IPositionMeshGeneratorFactory&) = delete;
IPositionMeshGeneratorFactory &operator=(const IPositionMeshGeneratorFactory&) = delete;
virtual std::shared_ptr<IPositionMeshGenerator> get(const Mesh &mesh) = 0;
};
} // namespace meow
#endif // IPOSITION_MESH_GENERATOR_H | true |
5e3bae6ab7982e421674cb5eb26ed076822ee4bd | C++ | Bolpat/Hermite | /src/hermite.cpp | UTF-8 | 14,686 | 2.640625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #include "polynomial.hpp"
#include <cstdlib>
#include <cctype> // isspace
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <utility> // pair
#include <map>
#include <vector>
using namespace std;
using namespace Modulus;
typedef Polynomial<double> Poly;
map<double, vector<double>> Table; // the table storing the input.
Poly P; // The generated Polynomial
vector<double> A; // The generated pre-coefficients
bool Verbose = false; // Comment on the actions.
bool Expanded = false, Decomposite = true; // see options.
int Width = 20; // Width of number formatting in tabualar output.
//const char ERROR[] = "\x1b[31;1mError\x1b[0m: ";
const char ERROR[] = "Error: ";
const char INTRO[] =
"The Interactive Hermite Interpolation Generator 0.1\n"
"by Q. F. Schroll @ github.com/Bolpat\n"
"NO WARRENTY, USE FOR ANY PURPOSE\n\n"
"Type in 'help' or 'h' for further information and how to use."
;
const char HELP[] =
"This program is interactive, i.e. it waits for you to type commands in.\n"
"Any command-line arguments will be trated as they were typed commands\n"
"in the interactive mode (only lacks some less relevant verbose output).\n\n"
"Before any form of evaluation, you have to load a file.\n"
"That file needs a form like:\n"
" x_1 y_1,1 y_1,2 ... y_1,n_1\n"
" x_2 y_2,1 y_2,2 ... y_2,n_2\n"
" ... \n"
" x_m y_m,1 y_m,2 ... y_m,n_m\n"
"where n_1, ..., n_m may vary, but all at least one,\n"
"and x_k preferably distinct (equal x_k override previous ones)\n"
"# indicates line comments if it is the first character in that line.\n"
"Empty lines are ok but ignored.\n\n"
"List of interactive commands:\n"
" 'h': Help. Shows this.\n"
" 'q': Quit. Immediately exit the program.\n"
" 'o': Options: Parameter option and parameters..\n"
" Example usage: 'o v +', 'o w 20'\n"
" Available options:\n"
" 'v': Verbose.\n"
" + : Set. Display all messages. (default after CLA processing)\n"
" - : Unset. Only display outputs and error messages. (default while\n"
" CLA processing)\n"
" 'w': Minimum width for numbers in tabular output.\n"
" 'p': Print polynomial decomposite, expanded, or both.\n"
" + : expanded, i.e. form of an x^n + ... + a_0 (default)\n"
" - : decomposite, i.e. form of b0 + b1(x - x1) + ... +\n"
" bn(x - x1)^k1...(x - xm)^km\n"
" 0 : both, i.e. '<decomposite> = <expanded>'\n"
" 'l': Load. Parameter filename. Load a file. This must be done first.\n"
" The command exists to reload the file or view another one\n"
" without exiting.\n"
" Any following commands expect a file to be loaded.\n"
" 'v': Values. Show the loaded values (data that has been loaded).\n"
" 'p': Polynomial. Show the definig term of the interpolation polynomial.\n"
" 'e': Evaluate: Parameter x. Evaluates the polynomial function at x.\n"
" 'd': Derivative: Replaces the active polynomial by its derivative.\n"
" 't': Value table: Parameters l, n, u. Evaluates the polynmial between\n"
" l and u with n steps (i.e. n + 1 places) between\n"
"Commands and options are indeed not really checked for existance.\n"
"Any word starting with one of the single letters suit.\n"
"The empty word is ignored.\n"
"Commands and paramerets are split with any white space:\n"
"'load data.txt eval 0' is like\n"
"'l data.txt e 0' or\n"
"'lunch data.txt eat 0'\n"
;
bool hermite_load(char const * const filename)
{
ifstream file(filename);
if (!file.good())
{
cerr << ERROR << "Cannot open file " << filename << "!\n";
return false;
}
double x, y;
vector<double> ys;
int i = 1;
for (string line; getline(file, line); ++i)
{
if (line == "" || line[0] == '#') continue;
istringstream iss(line);
if (!(iss >> x))
{
cerr << ERROR << "Cannot read x value in line " << i << "!\n";
goto fail;
}
int j = 1;
while (iss >> y)
{
ys.push_back(y);
++j; // expect j-th value next.
}
if (!iss.eof())
{
cerr << ERROR << "Cannot read y value no. " << j << " in line " << i << "!\n";
goto fail;
}
if (j < 2)
{
cerr << ERROR << "Value " << x << "in line " << i << " needs at least one value!";
goto fail;
}
Table[x] = move(ys);
}
if (Verbose) cout << "File '" << filename << "' successfully loaded." << endl;
return true;
fail:
Table.clear();
A.clear();
P = 0;
cerr << "Failing load reset state." << endl;
return false;
}
inline
void print_v(vector<double> const & v)
{
cout << '[';
if (!v.empty())
{
cout << setw(Width) << v.front();
for (std::size_t i = 1; i < v.size(); ++i)
cout << ',' << setw(Width) << v[i];
}
cout << ']';
}
void print_v(vector<vector<double>> const & v)
{
cout << "{\n";
if (!v.empty())
{
print_v(v.front());
for (std::size_t i = 1; i < v.size(); ++i)
{
cout << '\n';
print_v(v[i]);
}
}
cout << "\n}";
}
vector<double> hermite_ipol()
{
auto fac = [](auto n)
{
double r = 1.0;
for (decltype(n) i = 2; i < n; ++i) r *= i;
return r;
};
std::size_t n = 0; // size of the system aka. total # of ys in Table.
vector<double> xs;
vector<vector<double>> yss;
for (auto const & kvp : Table)
{
int i = n;
n += kvp.second.size();
xs.resize(n, kvp.first);
yss.resize(n, vector<double>(1, kvp.second.front()));
for (std::size_t k = 1; k < kvp.second.size(); ++k)
for (std::size_t j = k; j < kvp.second.size(); ++j)
yss[i + j].push_back(kvp.second[k] / fac(k+1));
}
for (std::size_t i = 1; i < n; ++i)
{
auto l = xs.begin();
auto r = l + i;
for (int j = i; r != xs.end(); ++l, ++r, ++j)
{
if (*r == *l) continue;
double y = (yss[j][i-1] - yss[j-1][i-1]) / (*r - *l);
yss[j].push_back(y);
}
}
if (Verbose) { print_v(yss); cout << "\nCoefficients successfully calulated." << endl; }
A = vector<double>(n);
for (std::size_t i = 0; i < n; ++i) A[i] = yss[i][i];
return xs;
}
bool interactive(istream & in)
{
auto ex_table = []() -> bool
{
if (Table.empty()) cerr << ERROR << "No file has been loaded." << endl;
return !Table.empty();
};
string command, opt;
if (in >> command)
switch (command[0])
{
case 'h': cout << HELP << endl; break;
case 'q': if (Verbose) cout << "Leaving." << endl; exit(0);
case 'o':
if (in >> opt)
{
switch (opt[0])
{
case 'v': if (in >> opt)
{
if (opt[0] == '+') { Verbose = true; cout << "Verbose on." << endl; }
else if (opt[0] == '-') Verbose = false;
else
{
cerr << ERROR << "Illegal option parameter; only '+' or '-' allowed.\n";
return false;
}
}
else
{
cerr << ERROR << "Failed to read option parameter.\n";
in.setstate(ios::goodbit);
return false;
}
break;
case 'a': if (in >> opt)
{
if (opt[0] == '0' || opt[0] == '+' || opt[0] == '-')
{
Expanded = (opt[0] == '0' || opt[0] == '+');
Decomposite = (opt[0] == '0' || opt[0] == '-');
}
else
{
cerr << ERROR << "Illegal option parameter; only '+' or '-' allowed.\n";
return false;
}
}
else
{
cerr << ERROR << "Failed to read option parameter.\n";
in.setstate(ios::goodbit);
return false;
}
break;
case 'w':
if (in >> Width)
{
if (Width < 1)
{
Width = 20;
if (Verbose) cout << "Negative number. Width set to 20 (default)." << endl;
}
else
if (Verbose) cout << "Negative number. Width set to " << Width << "." << endl;
}
else
{
if (in.eof()) cerr << ERROR << "No option parameter.\n";
else if (in.fail()) cerr << ERROR << "Illegal option parameter format. Must be positive number.\n";
in.setstate(ios::goodbit);
return false;
}
break;
default:
cerr << ERROR << "Unknown option '" << opt << "'.\n";
return false;
}
}
else
{
cerr << ERROR << "Failed to read option.\n";
in.setstate(ios::goodbit);
return false;
}
break;
case 'v': if (ex_table())
{
for (auto const & kvp : Table)
{
cout << setw(Width) << kvp.first << " : ";
for (auto const & y : kvp.second) cout << setw(Width) << y;
cout << '\n';
}
cout << endl;
}
break;
case 'l':
{
string s;
if ((in >> s) && hermite_load(s.c_str()))
{
auto x = hermite_ipol();
if (!A.size())
{
cerr << ERROR << "No coefficents generated. Sorry, this is an implementation error and not your fault." << endl;
return false;
}
Poly N = 1.0;
auto n = [&N, &x](int k) { return N *= Poly(1, 1) - x[k]; };
P = A.front();
for (std::size_t i = 1; i < A.size(); ++i) P += A[i] * n(i - 1);
if (Verbose) cout << "Polynomial successfully calculated." << endl;
}
else
{
cerr << ERROR << "Failed to read filename.\n";
in.setstate(ios::goodbit);
return false;
}
}
break;
case 'p': if (ex_table())
{
//TODO: Use A to print P in the form of a0 + a1(x - x0) + a2(x - x0)(x - x1) + ... + an(x - x1)...(x - xn)
if (Expanded)
{
cout << A[0];
auto itT = Table.begin();
auto itA = A.begin();
cout << *itA;
vector<pair<Poly, std::size_t>> Qds = { { Poly(1, 1) - itT->first, 1 } };
auto inc = [&itT, &Qds]()
{
if (Qds.back().second < itT->second.size())
++Qds.back().second;
else
Qds.push_back(pair{ Poly(1, 1) - (++itT)->first, 1 });
};
for (++itA; itA != A.end(); inc(), ++itA)
{
if (*itA == 0.0) continue;
if (*itA < 0.0) cout << " - " << -*itA;
else cout << " + " << *itA;
for (auto const & Qd : Qds) // Q: Poly, d: degree
{
auto const & Q = Qd.first;
auto const & d = Qd.second;
if (Q.is_monomial()) cout << ' ' << Q;
else cout << ' ' << '(' << Q << ')';
if (d > 1) cout << '^' << d;
}
}
if (Decomposite) cout << " = ";
else cout << '\n';
}
if (Decomposite) cout << P << endl;
}
break;
case 'e': if (ex_table())
{
double x;
if (in >> x)
{
cout << P(x) << endl;
}
else
{
cerr << ERROR << "Failed to interpret the parameter as IEEE-754 double number.\n";
in.setstate(ios::goodbit);
return false;
}
}
break;
case 'd': if (ex_table())
{
// Adapt A.
P = P.deriv();
cout << "Polynmial replaced by its derivative." << endl;
}
break;
case 't': if (ex_table())
{
double l, u;
int n;
if ((in >> l >> n >> u) && n > 0)
{
double const d = (u - l) / n;
for (int i = 0; i <= n; ++i)
{
double const x = l + i * d;
cout << setw(Width) << x << setw(Width) << P(x) << '\n';
}
cout << endl;
}
else
{
cerr << ERROR << "Failed to read Paramters. Must be double, positive integer, double.\n";
in.setstate(ios::goodbit);
return false;
}
}
break;
default:
cerr << ERROR << "Unknown command.\n";
}
return !in.eof();
}
int main(int argc, char ** argv)
{
if (argc < 2) cout << INTRO << endl;
stringstream str;
while (--argc && ++argv) str << *argv << ' ';
while (interactive(str)) { }
if (!str.eof())
{
cerr << "Some error occoured. Leaving." << endl;
return 1;
}
Verbose = true;
str = stringstream(); // reinitialize
string line;
do
{
cout << "hermite> " << flush;
if (!getline(cin, line)) break;
while (!line.empty() && isspace(line.back())) line.pop_back();
}
while (line.empty() || interactive(reinterpret_cast<stringstream &>(str << line << ' ')));
return 0;
} | true |
eeba01a8defa7e688f6132f73666d69e64ad9cd3 | C++ | sknjpn/From-the-Planet | /Region.h | UTF-8 | 1,613 | 2.59375 | 3 | [] | no_license | #pragma once
class PlanetManager;
class FacilityAsset;
class FacilityState;
class TerrainAsset;
class Road;
class Region
: public enable_shared_from_this<Region>
{
friend class PlanetManager;
Vec3 m_position;
Array<Vec3> m_polygon;
weak_ptr<PlanetManager> m_planet;
Array<weak_ptr<Region>> m_connecteds;
Array<shared_ptr<Road>> m_roads;
shared_ptr<TerrainAsset> m_terrainAsset;
shared_ptr<FacilityState> m_facilityState;
// for 探索
shared_ptr<Region> m_from;
double m_cost = 0.0;
void draw(const Mat4x4& mat, double d, Color color) const;
void drawLineString(const Mat4x4& mat, double d, Color color) const;
public:
bool mouseOver(const Mat4x4& mat) const;
void draw(const Mat4x4& mat) const;
void setFacilityState(const shared_ptr<FacilityState> facilityState) { m_facilityState = facilityState; }
double getArea(const Mat4x4& mat) const;
// get
const Vec3& getPosition() const { return m_position; }
// connection
void connect(const shared_ptr<Region>& to);
void disconnect(const shared_ptr<Region>& to);
bool hasConnection(const shared_ptr<Region>& region) const { return m_connecteds.any([®ion](const auto& c) { return c.lock() == region; }); }
// facility
void makeFacilityState(const shared_ptr<FacilityAsset>& facilityAsset);
const shared_ptr<FacilityState>& getFacilityState() const { return m_facilityState; }
Array<shared_ptr<Road>> getRouteTo(const shared_ptr<Region> to) const;
// road
void makeRoad(const shared_ptr<Region>& to);
bool hasRoad(const shared_ptr<Region>& to) const;
shared_ptr<Road> getRoad(const shared_ptr<Region>& to) const;
};
| true |
700397ad8bfb0e8285c02bd9b3432ad94b66def7 | C++ | JorgeAugusto/Cars_AI | /includes/line.h | UTF-8 | 1,349 | 3.296875 | 3 | [] | no_license | #ifndef LINE_H
#define LINE_H
#include <SFML/Graphics.hpp>
class Line
{
public:
sf::RectangleShape rectangle;
sf::CircleShape left;
sf::CircleShape right;
Line();
Line(const Line& line);
Line(const Vector& point_1, const Vector& point_2, const double& width, const sf::Color& color);
Line(const double& x_1, const double& y_1, const double& x_2, const double& y_2, const double& width, const sf::Color& color);
Line(const sf::Vector2i& point_1, const sf::Vector2i& point_2, const double& width, const sf::Color& color);
Line(const sf::Vector2f& point_1, const sf::Vector2f& point_2, const double& width, const sf::Color& color);
void operator=(const Line& line);
void set_point1(const Vector& point_1);
void set_point1(const double& x, const double& y);
void set_point1(const sf::Vector2i& point_1);
void set_point1(const sf::Vector2f& point_1);
void set_point2(const Vector& point_2);
void set_point2(const double& x, const double& y);
void set_point2(const sf::Vector2i& point_2);
void set_point2(const sf::Vector2f& point_2);
Vector get_point1() const;
Vector get_point2() const;
void set_width(const double& width);
double get_width() const;
void set_color(const sf::Color& color);
sf::Color get_color() const;
double get_length();
void draw(sf::RenderWindow& window);
};
#endif
| true |
0c1992c84f44f64faa634b68d6b187f30a9d8918 | C++ | yuzec/luogu | /P1739/main.cpp | UTF-8 | 318 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int ans=0;
char x;
cin>>x;
while(x!='@'&&ans>=0) {
if(x=='(')
++ans;
else if(x==')')
--ans;
cin>>x;
}
if(ans==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
| true |
56ba30f32e8872290a0f89fbec367e2ace7baa76 | C++ | Hector-Dominguez/myoelectric-473 | /src/SystemCode/xmcCode/CircularBuffer/MyoDataCollector.hpp | UTF-8 | 1,070 | 2.890625 | 3 | [] | no_license | //
// CircularBuffer.hpp
// CircularBuffer
//
// Created by Hector Dominguez on 10/24/18.
// Copyright © 2018 Hector Dominguez. All rights reserved.
//
#ifndef MyoDataCollector_hpp
#define MyoDataCollector_hpp
#include <stdio.h>
class FourTuple
{
public:
int thumb;
int index;
int middle;
int rp;
FourTuple() : thumb(0), index(0), middle(0), rp(0){}
};
//need to initialize the collection of data with SIZE readings for averages to
//make sense?
class MyoDataCollector
{
const int SIZE;
FourTuple * arrayPtr; //points to a dynamically allocated array of FIXED size
int recentIdx;//most recent data points
int oldestIdx;//oldest data points
FourTuple averages;
public:
//CTOR
MyoDataCollector(int size);
//DTOR
~MyoDataCollector();
//inserts sensor read values into the buffer of SIZE readings
void push(FourTuple readings);
//returns the "filtered" values aka the averages
FourTuple getFilteredY();
};
bool operator==(FourTuple a, FourTuple b);
#endif /* MyoDataCollector_hpp */
| true |
6af949b6f5439f2ca2420ffd3185a0d15757f6ba | C++ | dvphuonguyen/IT003.K26 | /BT_Tuan_5/Linear_Search_Closest/Source.cpp | UTF-8 | 697 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
struct arr {
int* A;
int c;
int n;
};
void input(arr& a) {
cin >> a.n;
a.c = a.n + 1;
a.A = new int[a.c];
for (int i = 0; i < a.n; ++i) {
cin >> a.A[i];
}
}
int Linear_Search(arr a, int x) {
int gan_nhat = 0;
int m = 200000000;
for (int i = 0; i < a.n; ++i) {
if (a.A[i] == x) return i;
if (abs(a.A[i] - x) < m)
{
m = abs(a.A[i] - x);
gan_nhat = i;
}
}
return gan_nhat;
}
int main() {
cin.tie(NULL);
std::ios_base::sync_with_stdio(false);
arr a, b;
input(a);
input(b);
for (int i = 0; i < b.n; ++i)
{
cout << Linear_Search(a, b.A[i]) << endl;
}
return 0;
} | true |
2ed8b62213d7c911c8b2e0f80bd2816ff244c079 | C++ | Tursh/OctoWorld | /src/States/DebugState.cpp | UTF-8 | 1,891 | 2.609375 | 3 | [] | no_license | /*
* DebugState.cpp
*
* Created by tursh on 8/16/20.
*/
#include <States/DebugState.h>
#include <GUI/Panel.h>
#include <GUI/GUIManager.h>
#include <IO/Input.h>
#include <GUI/Text/TextRenderer.h>
#include <Utils/TimeUtils.h>
namespace OW
{
using namespace CGE;
DebugState::DebugState()
{
IO::input::setYourOwnKeyCallBack(
std::bind(&DebugState::keyCallback, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3)
);
//The pause panel is simply so the mouse callback get stopped
pausePanel = new GUI::Panel({0, 0}, {0, 0}, CGE::GUI::IMAGE,
std::bind(&DebugState::keyCallback, this, nullptr,
std::placeholders::_1,
std::placeholders::_2), false);
pausePanel->setVisibility(false);
GUI::GUIManager::addComponent(pausePanel);
}
void DebugState::tick()
{
world.tick();
}
void DebugState::draw()
{
world.render();
GUI::Text::TextRenderer::renderText("FPS: " + std::to_string(Utils::getFPS()).substr(0, 4) + " TPS: " +
std::to_string(Utils::TPSClock::getTPS()).substr(0, 4), {0.66f, 0.95f},
0.1f,
glm::vec3(1, 1, 1),
false);
}
void DebugState::keyCallback(GLFWwindow *window, int key, int action)
{
if (key == GLFW_KEY_G && action == GLFW_PRESS)
CGE::IO::input::toggleGrabMouse();
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
pausePanel->setVisibility(!pausePanel->getVisibility());
CGE::IO::input::ungrabMouse();
}
}
} | true |
5c87a6b6551edeaf1a532584667464e0bace40d8 | C++ | mina37/Data-Mining | /Customer.h | UTF-8 | 890 | 3.265625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include<vector>
//implemented headers :
#include "dsList.h"
#include "Enums.h"
#include "string"
class Customer {
private:
Gender gen;
Place pl;
dsList<Product>prodList; //list of customer products
public:
//constructor :
Customer(int gInt, int pInt, dsList <Product> prList) {
gen = static_cast<Gender>(gInt);
pl = static_cast<Place>(pInt);
for (int i = 0;i<prList.get_size()+1;i++) {
prodList.insertoTail(prList.get(i));
}
prodList = prList;
}
////////////////////////////
//some getters :
Gender getGender()
{
return gen;
}
Place getPlace()
{
return pl;
}
dsList<Product>prodListReturn() {
return prodList;
}
//print all products in a list form :
void printProductsList() {
prodList.printList();
}
int getProductListSize() {
return prodList.get_size()+1;
}
//endOfclass.
};
| true |
c1118dddef7046e61cd60996d2a572a61b176c59 | C++ | venkatesh551/goals | /c++14/variadicTemplates/parameter_pack_loci.cpp | UTF-8 | 593 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
template <typename... Ts>
void createMap(Ts... args) {
std::map<Ts...> mp;
mp.insert (std::pair<Ts...>(args...));
auto lst = {std::pair<Ts...>(args, 'a')...};
for (auto ele : lst) {
mp.insert(ele);
}
for (auto ele : mp) {
std::cout << ele.first << " " << ele.second << std::endl;
}
std::vector<int> lst2 = {(Ts) args... };
for (int i = 0; i < lst2.size(); ++i){
std::cout << lst2[i] << " ";
}
std::cout << "\n";
}
int main() {
createMap(1, 'd');
return 0;
}
| true |
09350dde7ca72f11a583b01390382275ff133654 | C++ | J4m3sC95/CAN_LEDS | /ATtiny2313_LED_cube++/ATtiny2313_LED_cube++/LED_Cube.cpp | WINDOWS-1252 | 5,751 | 2.84375 | 3 | [] | no_license | /*
* LED_Cube.c
*
* Created: 15/09/2017 20:49:47
* Author: James
*/
#include "LED_Cube.h"
// Global Variables
volatile uint8_t interrupt_layer;
volatile uint16_t *display_buffer[3];
volatile uint16_t buffer0[4];
volatile uint16_t buffer1[4];
volatile uint8_t active_buffer;
void cube_setup(){
uint8_t n;
//turn outputs on
DDRD = 0x7F;
DDRB = 0xDF;
DDRA = 0x01;
// setup spi mode (not needed)
// USICR = 1<<USIWM0;
// disable chip
bitset(PORTA, PA0);
// initialise buffers
for(n = 0; n < 3; n++){
buffer0[n] = 0x1FF;
}
for(n = 0; n < 3; n++){
buffer1[n] = 0;
}
display_buffer[0] = buffer0;
display_buffer[1] = buffer1;
active_buffer = 0;
// setup timer
interrupt_layer = 2;
// normal mode
TCCR0A = (0<<WGM01) | (0<<WGM00);
// set clock prescaler to /64 to give 2ms interval
TCCR0B = (0<<CS02) | (1<<CS01) | (1<<CS00);
// set clock prescaler to /1024 to give 30ms interval
//TCCR0B = (1<<CS02) | (0<CS01) | (1<<CS00);
// enable overflow interrupt
bitset(TIMSK, TOIE0);
// enable global interrupts
sei();
// wait a bit then update the cube
_delay_ms(1000);
update_cube();
}
void layer_out(uint16_t layer){
PORTD = (PORTD & 0x80) | (layer & 0x7F);
PORTB = (PORTB & 0xFC) | ((layer >> 7) & 0x03);
}
void update_buffer(uint16_t layer[4]){
uint8_t n;
for(n = 0; n< 3; n++){
display_buffer[1-active_buffer][n] = layer[n];
}
}
void update_cube(){
active_buffer = 1 - active_buffer;
// delay to allow ISR to update itself (is this needed??)
//_delay_ms(10);
}
ISR(TIMER0_OVF_vect){
// clear previous active layer
bitclear(PORTB, interrupt_layer);
// increment and check for "overflow"
interrupt_layer++;
if(interrupt_layer == 5){
interrupt_layer = 2;
}
// load new column array
layer_out(display_buffer[active_buffer][interrupt_layer - 2]);
// set new active layer
bitset(PORTB, interrupt_layer);
}
// display class functions
display::display(void){
translate_distance = 0;
//int8_t n;
//for(n = 0; n<3; n++){
//output_buffer[n] = 0;
//}
}
void display::load_buffer(uint16_t *input_buffer){
uint8_t n;
for(n = 0; n< 3; n++){
output_buffer[n] = input_buffer[n];
}
}
void display::rotate(int8_t axis, int8_t direction){
transform(output_buffer, rotate_point, axis, direction, 0);
}
void display::mirror(int8_t plane){
transform(output_buffer, mirror_point, plane, 0, 0);
}
void display::translate(int8_t axis, int8_t direction, uint16_t *replacement){
uint8_t n;
uint16_t temp_buffer[4];
for(n=0; n< 3; n++){
temp_buffer[n] = replacement[n];
}
// translate existing buffer
transform(output_buffer, translate_point, axis, direction, 1);
// translate new buffer with an offset
transform(temp_buffer, translate_point, axis, direction, translate_distance - 2);
// combine the two and set to output
for(n=0; n< 3; n++){
output_buffer[n] |= temp_buffer[n];
}
translate_distance++;
}
void display::send_to_cube(){
update_buffer(output_buffer);
update_cube();
}
void transform(uint16_t *input_buffer, void (*funct)(uint8_t, int8_t, int8_t, int8_t*), int8_t arg1, int8_t arg2, int8_t arg3){
uint8_t n,m;
int8_t point[7];
uint16_t buffer[4];
/*
x0 = point[0]
y0 = point[1]
z0 = point[2]
x1 = point[3]
y1 = point[4]
z1 = point[5]
*/
// clear output buffer
for(n = 0; n<3; n++){
buffer[n] = 0;
}
// loop through layers (z axis 0 to 2)
for(n = 0; n < 3; n++){
// loop through bits to find 1s
for(m = 0; m < 9; m++){
if(input_buffer[n] & (1<<m)){
// when a 1 is found transform it to new location
point[0] = (m%3) - 1;;
point[1] = (m/3) - 1;
point[2] = n - 1;
/*** PERFORM TRANSLATION****/
funct(arg1, arg2, arg3, point);
//check if the value is ok
if(!((point[arg1+3] > 1) || (point[arg1+3] < -1))){
point[3]++;
point[4]++;
point[5]++;
// put new data in output buffer
buffer[point[5]] |= 1 << (point[3] + (point[4]*3));
}
}
}
}
for(n = 0; n< 3; n++){
input_buffer[n] = buffer[n];
}
}
// rotate 90
/*
void rotate_point(uint8_t axis, int8_t direction, int8_t *point){
switch(axis){
case XAXIS:
{
point[3] = point[0];
point[4] = -1*direction*point[2];
point[5] = direction*point[1];
}
break;
case YAXIS:
{
point[4] = point[1];
point[5] = -1*direction*point[0];
point[3] = direction*point[2];
}
break;
case ZAXIS:
{
point[5] = point[2];
point[3] = -1*direction*point[1];
point[4] = direction*point[0];
}
break;
}
}
*/
// rotate 45
void rotate_point(uint8_t axis, int8_t direction, int8_t arg3, int8_t *point){
uint8_t n;
switch(axis){
case XAXIS:
{
point[3] = point[0];
point[4] = point[1] - (direction*point[2]);
point[5] = direction*point[1] + point[2];
}
break;
case YAXIS:
{
point[4] = point[1];
point[5] = point[2] - (direction*point[0]);
point[3] = direction*point[2] + point[0];
}
break;
case ZAXIS:
{
point[5] = point[2];
point[3] = point[0] - (direction*point[1]);
point[4] = direction*point[0] + point[1];
}
break;
}
for(n = 3; n<6; n++){
if((point[n] > 1) || (point[n] < -1)){
point[n] = point[n] >> 1;
}
}
}
void mirror_point(uint8_t plane, int8_t arg2, int8_t arg3, int8_t *point){
point[3] = point[0];
point[4] = point[1];
point[5] = point[2];
point[plane+3] = -point[plane];
}
void translate_point(uint8_t axis, int8_t direction, int8_t offset, int8_t *point){
point[3] = point[0];
point[4] = point[1];
point[5] = point[2];
point[axis+3] = point[axis] + (direction*offset);
}
void composite(uint16_t *buffer1, uint16_t *buffer2){
uint16_t buffer[4];
uint8_t n;
for(n = 0; n < 3; n++){
buffer[n] = buffer1[n] | buffer2[n];
}
update_buffer(buffer);
update_cube();
}
| true |
66f8bb7b7dcf079fa55a1644a647cc4fc5db9828 | C++ | ECE3400Team17/ECE3400_Team17 | /Code/Milestone2/wall_detection/wall_detection.ino | UTF-8 | 1,906 | 2.75 | 3 | [] | no_license | #include <Servo.h>
#include "Adafruit_VL53L0X.h"
Adafruit_VL53L0X lox = Adafruit_VL53L0X();
Servo servoL;
Servo servoR;
int s2 = A2;
int s3 = A3;
int s0 = A0;
int s5 = A5;
int val0;
int val2;
int val3;
int val5;
int thres = 90;
void setup(){
Serial.begin(115200);
servoL.attach(10);
servoR.attach(11);
servoL.write(90);
servoR.write(90);
// wait until serial port opens for native USB devices
while (! Serial) {
delay(1);
}
Serial.println("Adafruit VL53L0X test");
if (!lox.begin()) {
Serial.println(F("Failed to boot VL53L0X"));
while(1);
}
// power
Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}
void loop(){
val0 = analogRead(s0);
val5 = analogRead(s5);
val2 = analogRead(s2);
val3 = analogRead(s3);
/*
Serial.println(val0);
Serial.println(val2);
Serial.println(val3);
Serial.println(val5);
Serial.println("\n");
delay(500);
*/
if(openwall()==1) {
turnleft();
}
else {
goStraight();
}
}
bool openwall() {
VL53L0X_RangingMeasurementData_t measure;
lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
if(measure.RangeStatus != 4 && measure.RangeMilliMeter < thres && measure.RangeMilliMeter != 0)
return 1;
else
return 0;
}
void goStraight() {
if ((val2>500)&&(val3>500)){
servoL.write(120);
servoR.write(60);
}
else if((val3<500)){
servoL.write(90);
servoR.write(60);
}
else if((val2<500)){
servoL.write(120);
servoR.write(90);
}
else{
servoL.write(90);
servoR.write(90);
}
}
void turnleft() {
//servoL.write(120);
//servoR.write(60);
//delay(100);
stay();
servoL.write(0);
servoR.write(0);
delay(800);
servoL.write(90);
servoR.write(90);
}
void stay() {
servoL.write(90);
servoR.write(90);
}
| true |
fdd0fde1d1597eeaf51c200d9186967b83a4244b | C++ | catterer/memsug | /include/text.hh | UTF-8 | 2,598 | 2.765625 | 3 | [] | no_license | #pragma once
#include <save.hh>
#include <unordered_map>
#include <set>
#include <vector>
namespace text {
using Number = std::string;
class Alphabet:
public std::unordered_map<std::string, uint8_t>,
public save::serializable
{
public:
static auto classic_ru() -> Alphabet;
static auto classic_en() -> Alphabet;
static auto by_name(const std::string&) -> Alphabet;
Alphabet(const save::blob& b) { load(b); }
Alphabet(std::vector<std::string>&& descriptor);
auto map(const std::string& word) const -> Number;
auto dump() const -> save::blob override;
void load(const save::blob&) override;
};
using WordId = uint32_t;
struct Word: public save::serializable {
Word(const save::blob& root) { load(root); }
Word(WordId id, const Number& number, const std::string& str):
id{id}, num{number}, str{str} {}
auto dump() const -> save::blob override;
void load(const save::blob&) override;
friend std::ostream& operator<<(std::ostream&, const Word&);
WordId id;
Number num;
std::string str;
};
class AdjMatrix:
public std::unordered_map<WordId, std::set<WordId>>,
public save::serializable
{
public:
using std::unordered_map<WordId, std::set<WordId>>::unordered_map;
AdjMatrix(const save::blob& root) { load(root); }
auto dump() const -> save::blob override;
void load(const save::blob&) override;
};
class DictEntry: public save::serializable {
public:
DictEntry(const Word& w): word_{w} {}
virtual ~DictEntry() = default;
auto dump() const -> save::blob override { return word_.dump(); }
void load(const save::blob& root) override { return word_.load(root); }
auto word() const -> const Word& { return word_; }
private:
Word word_;
};
class Dict:
public std::unordered_map<WordId, std::shared_ptr<DictEntry>>,
public save::dumpable
{
public:
using Idxstr = std::unordered_map<std::string, std::shared_ptr<DictEntry>>;
Dict(const save::blob&);
Dict(const Alphabet& ab): alphabet_{ab} {}
virtual ~Dict() = default;
auto dump() const -> save::blob override;
void update(const std::string& textfile);
void insert(const Word&);
void consider_sentence(const std::string&);
auto consider_word(const std::string&) -> WordId;
auto idxstr() const -> const Idxstr& { return idxstr_; }
auto adjmx() const -> const AdjMatrix& { return adjmx_; }
private:
static const size_t max_file_size_ = 100*1024*1024;
Alphabet alphabet_;
AdjMatrix adjmx_;
WordId last_id_{1};
Idxstr idxstr_;
};
}
| true |
36e124915dcf41353ea32990298cc7ed5eb42d5a | C++ | AbdelrahmanMohamedd/DataStructure-Assig1 | /A1_P6_20170148_20170301_20170379_/StudentName.h | UTF-8 | 373 | 2.59375 | 3 | [] | no_license | #ifndef STUDENTNAME_H
#define STUDENTNAME_H
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class StudentName
{
public:
StudentName();
void MakeName(const string&);
void Print();
bool Replace();
virtual ~StudentName();
private:
string name;
};
#endif // STUDENTNAME_H
| true |
31ba291963c2f1d2dd07af3971df90e5702927b0 | C++ | saket2508/DS | /selectionSort.cpp | UTF-8 | 815 | 3.71875 | 4 | [] | no_license | #include<iostream>
using namespace std;
void swapInt(int*a, int*b){
int temp = *a;
*a = *b;
*b = temp;
}
void SelectionSort(int*arr, int m){
for(int i=0;i<m-1;i++){
for(int j=i+1;j<m;j++){
if(arr[i]>arr[j]){
swapInt(arr+i,arr+j);
}
}
}
}
void getData(int*arr, int m){
cout << "Enter the elements one by one\n";
for(int i=0;i<m;i++){
cin >> arr[i];
}
}
void printData(int*arr, int m){
cout << "Array in sorted order is: ";
for(int i=0;i<m;i++){
cout << arr[i] << "\t";
}
}
int main(){
int m;
cout << "enter the size of the array" << endl;
cin>> m;
int*arr = new int[m];
getData(arr,m);
SelectionSort(arr,m);
printData(arr,m);
delete[]arr;
return 0;
}
| true |
d5e8802e279dde1db2c0a827fdb2653eb8835c72 | C++ | vlvanchin/learn | /learn_others/cpp/arraydemo.cpp | UTF-8 | 642 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main () {
int myarray [7] = {
12, 23,45,66,77,80,100
};
for (int c=0; c < sizeof(myarray)/sizeof(myarray[0]); c++) {
cout << "myarray [" << c << "] = " << myarray[c] << endl;
}
myarray [3] = 333;
cout << "modified array is " << endl;
for (unsigned int a=0; a < sizeof(myarray) / sizeof (myarray[a]); a++) {
cout << "myarray [" << a << "] = " << myarray[a] << endl;
}
cout << "myarray " << sizeof(myarray) << endl;
cout << "myarray actual " << sizeof(myarray[0]) << endl;
cout << "myarray lenght " << sizeof(myarray)/sizeof(myarray[0]) << endl;
return 0;
}
| true |
5c80daa2c425ddd00623bbb4e88a965d58abd058 | C++ | Mr-zhang-in-Harbin/LeetCode | /Easy/Find Pivot Index.cpp | UTF-8 | 425 | 2.71875 | 3 | [] | no_license | class Solution {
public:
int pivotIndex(vector<int>& nums) {
if (nums.size() <= 2)
return -1;
for (int i = 1;i < nums.size(); i++) {
nums[i] = nums [i] + nums[i-1];
}
long long int Res = nums[nums.size() - 1];
for (int i = 0;i < nums.size();i++)
if (Res - nums[i] == (i == 0 ? 0:nums[i-1]))
return i;
return -1;
}
};
| true |
9710e5c748e109cf81a6cbdd6504d2c4edc38346 | C++ | tyut-zhuran/cpp_learn | /202001/类和对象/类和对象/2继承方式.cpp | GB18030 | 1,038 | 3.15625 | 3 | [] | no_license | //# include <iostream>
//
//using namespace std;
//
//class Base
//{
//public:
// int m_A;
//protected:
// int m_B;
//private:
// int m_C;
//};
//
//
//class Class1:public Base
//{
//public:
// void func()
// {
// m_A = 1;//public-->public
// m_B = 2;//protected-->protected
// //m_C = 3;//private-->ɷ
// }
//};
//
//void testClass1()
//{
// Class1 class1;
// class1.m_A = 1;//public-->public
//}
//
//
//
//class Class2 :protected Base
//{
//public:
// void func()
// {
// m_A = 1;//public-->protected
// m_B = 2;//protected-->protected
// }
//};
//
//void testClass2()
//{
// Class2 cl;
// //cl.m_A = 2;//Ȩޣⲻɷ
//}
//
//
//
//class Class3 :private Base
//{
//public:
// void func()
// {
// m_A = 1;
// m_B = 2;//publicprotectedΪprivate
// }
//};
//
//void testClass3()
//{
// Class3 cl;
// //cl.m_A = 2;//privateȨⶼɷ
//}
//int main()
//{
//
//
// system("pause");
// return 0;
//}
//
| true |
6e0bcabd6d2f73c4787a6b2537e4fa5cecc3dbf3 | C++ | pantasito/Bomberman | /Bomberman/Object/Point.h | UTF-8 | 1,001 | 3.171875 | 3 | [] | no_license | // ☕ Привет
#pragma once
namespace Bomberman
{
namespace Object
{
struct Point {
int _row_num;
int _col_num;
Point(int row_num, int col_num) : _row_num(row_num), _col_num(col_num) {}
bool operator==(const Point point) const {
return (_row_num == point._row_num && _col_num == point._col_num);
}
bool operator!=(const Point point) const {
return (_row_num != point._row_num || _col_num != point._col_num);
}
Point operator*(int num) const {
return Point(_row_num * num, _col_num * num);
}
Point operator+(Point point) const {
return Point(point._row_num + _row_num, point._col_num + _col_num);
}
void operator+=(Point point) {
_row_num += point._row_num;
_col_num += point._col_num;
}
};
}
} | true |
a81bed8bb80eea5d4fd272e328bf0986bd5b9733 | C++ | mattrudder/AckZombies | /Src/AIStateGaseousFollow.cpp | UTF-8 | 2,447 | 2.53125 | 3 | [] | no_license | /**
* @file AIStateGaseousFollow.cpp
* @author Jonathan "Awesome" Zimmer
* @date Created April 7, 2006
*
* This file contains the implementation of the CAIStateGaseousFollow class
*/
#include "AIStateGaseousFollow.h"
#include "AIStateGaseousAttack.h"
#include "AIStatePathFollow.h"
#include "AIManager.h"
#include "Gaseous.h"
#define PATH_BACK poAIEntity->m_loPath.back()
#define PATH_FRONT poAIEntity->m_loPath.front()
#define GASEOUS_ATTACK_RADIUS 100.0f // this is squared
#define SPEED 10.0f
#ifndef NULL
#define NULL 0
#endif
/**
* CAIStateGaseousFollow::CAIStateGaseousFollow
* @date Modified May 4, 2006
*/
CAIStateGaseousFollow::CAIStateGaseousFollow(void)
{
setStateType(CAIState::AIS_GASEOUSFOLLOW);
memset(&m_vVelocity, 0, sizeof(D3DXVECTOR3));
}
/**
* CAIStateGaseousFollow::~CAIStateGaseousFollow
* @date Modified May 4, 2006
*/
CAIStateGaseousFollow::~CAIStateGaseousFollow(void)
{
}
/**
* CAIStateGaseousFollow::update
* @date Modified May 4, 2006
*/
void CAIStateGaseousFollow::update(CAIEntity* poAIEntity, CCharacter* poCharacter)
{
// right now this class is mostly the same as the zombie path follow
// but this would be the place to add something about trying to stay away
// from other enemies to avoid friendly fire
// check for a valid path, one with nodes in it
if (poAIEntity->m_loPath.empty())
{
// this is bad that there are no nodes to go to
// remove our influence
poCharacter->setVelocity(D3DXVECTOR3(0.0f, 0.0f, 0.0f));
// but not for now
((CEnemy*)(poCharacter))->setAIState(NULL);
return;
}
// GASEOUS SPECIFIC
///////////////////
// see if we are close enough
if (computeDistanceSquared(PATH_FRONT->getPosition(), poCharacter->getBV().centerPt) < GASEOUS_ATTACK_RADIUS)
{
// change to attack state
// remove influences
poCharacter->setVelocity(m_vVelocity);
((CEnemy*)(poCharacter))->setAIState(CAIStateGaseousAttack::getInstancePtr());
return;
}
///////////////////
CAIStatePathFollow::getInstancePtr()->followPath(poAIEntity, poCharacter, SPEED);
}
/**
* CAIStateGaseousFollow::enter
* @date Modified April 13, 2006
*/
void CAIStateGaseousFollow::enter(CAIEntity* poAIEntity, CCharacter* poCharacter)
{
}
/**
* CAIStateGaseousFollow::exit
* @date Modified April 13, 2006
*/
void CAIStateGaseousFollow::exit(CAIEntity* poAIEntity, CCharacter* poCharacter)
{
} | true |
b4eb5e0c1d0324779a90a1854773ed55682bcd87 | C++ | roomyroomy/algorithm | /algospot/PICNIC.cpp | UTF-8 | 1,394 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
using namespace std;
int C, N, M;
vector<set<int>> studentList(10);
int maskingCount = 0;
bool masking[10];
int traverseCase(int start = 0)
{
int result = 0;
if(start == 0)
{
for(int idxMask = 0; idxMask < 10; idxMask++)
masking[idxMask] = 0;
maskingCount = 0;
}
if(maskingCount >= N)
return 1;
for(int idxStudent = start; idxStudent < N; idxStudent++)
{
if(masking[idxStudent] == 0)
{
for(set<int>::iterator it = studentList[idxStudent].begin(); it != studentList[idxStudent].end(); it++)
{
if(masking[*it] == 0)
{
masking[idxStudent] = 1;
masking[*it] = 1;
maskingCount += 2;
result += traverseCase(idxStudent + 1);
masking[idxStudent] = 0;
masking[*it] = 0;
maskingCount -= 2;
}
}
}
}
return result;
}
int main()
{
cin >> C;
for(int idxCase = 0; idxCase < C; idxCase++)
{
for(int idxStudent = 0; idxStudent < 10; idxStudent++)
studentList[idxStudent].clear();
cin >> N >> M;
for(int idxPair = 0; idxPair < M; idxPair++)
{
int firstStudent, secondStudent;
int minStudent, maxStudent;
cin >> firstStudent >> secondStudent;
minStudent = min(firstStudent, secondStudent);
maxStudent = max(firstStudent, secondStudent);
studentList[minStudent].insert(maxStudent);
}
cout << traverseCase() << endl;
}
return 0;
}
| true |
90eeed0a7736de66008ea77e3e30da43d1148965 | C++ | Rolight/ACM_ICPC | /Not_Classified/ZOJ_1117.cpp | UTF-8 | 1,817 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
const int sigma_size = 27;
const int maxn = 8000;
struct TreeNode {
int lson,rson,data,id;
TreeNode(int lson = 0,int rson = 0,int data = -1,int id = 0):
lson(lson),rson(rson),data(data),id(id) {}
bool operator < (const TreeNode &x) const {
return data > x.data;
}
};
struct HaffumanTree {
int cnt[sigma_size],sz,root;
priority_queue<TreeNode> pq;
TreeNode pool[maxn];
string str;
HaffumanTree(string ss):str(ss) {
memset(cnt,0,sizeof(cnt));
while(!pq.empty()) pq.pop();
Construct();
sz = 0;
}
void Construct() {
int m = str.size();
for(int i = 0;i < m;i++) {
if(str[i] == '_') str[i] = 'Z' + 1;
cnt[str[i] - 'A']++;
}
for(int i = 0;i < sigma_size;i++) {
if(cnt[i]) {
sz++;
pool[sz] = TreeNode(0,0,cnt[i],sz);
pq.push(pool[sz]);
}
}
TreeBuild();
}
void TreeBuild() {
while(pq.size() > 1) {
TreeNode max1 = pq.top(); pq.pop();
TreeNode max2 = pq.top(); pq.pop();
TreeNode &new_node = pool[++sz];
new_node.lson = max1.id;
new_node.rson = max2.id;
new_node.data = max1.data + max2.data;
new_node.id = sz;
pq.push(new_node);
}
root = pq.top().id;
}
int dfs(int now,int deep) {
if(pool[now].lson + pool[now].rson == 0) {
return deep * pool[now].data;
}
return dfs(pool[now].lson,deep + 1) + dfs(pool[now].rson,deep + 1);
}
int solve() {
int ret = dfs(root,0);
if(ret == 0) ret = pool[root].data;
return ret;
}
};
int main() {
string buf;
while(cin >> buf) {
if(buf == "END") break;
HaffumanTree hf(buf);
int ori = buf.size() * 8,opt = hf.solve();
cout << fixed << setprecision(1);
cout << ori << " " << opt << " " << (double)ori / opt << endl;
}
return 0;
}
| true |
ecd17804a35ad9310d946fdbc75942fc468411dd | C++ | juliolugo96/competitive-programming | /codeforces/two_pointers/sereja_dima.cpp | UTF-8 | 451 | 2.84375 | 3 | [] | no_license | # include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a;
for (int i{0}; i < n; i++)
{
int p;
cin >> p;
a.push_back(p);
}
int i{0}, j{n - 1}, sereja{0}, dima{0};
while(i <= j)
{
sereja += max(a[i], a[j]);
a[i] > a[j] ? i++ : j--;
if (i > j) break;
dima += max(a[i], a[j]);
a[i] > a[j] ? i++ : j--;
}
cout << sereja << " " << dima << "\n";
return 0;
}
| true |
a1621ab65bb2bbd0fb4d88f3ee9b2c1dca982e17 | C++ | gembancud/CompetitiveProgramming | /uva/intro/getting started/easy/summingdigits/a.cpp | UTF-8 | 334 | 2.9375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int concat(int a){
int sum=0;
while(a/10!=0){
sum += a%10;
a/=10;
}
sum += a;
return sum;
}
int main(){
int n;
while(cin >>n){
if(n==0) break;
while(n>=10){
n = concat(n);
}
cout << n <<endl;
}
} | true |
ec6230e5527cbbd58fcecb0fe243c20d4d220e8e | C++ | thallium/acm-algorithm-template | /src/data_structure/fenwick_range_update.hpp | UTF-8 | 904 | 3.3125 | 3 | [] | no_license | #pragma once
#include <vector>
// fenwick tree with range update and range sum query
class fenwick_rg {
int n;
std::vector<int64_t> sum1, sum2;
void add(int i, int x) {
assert(i >= 0 && i < n);
i++;
int64_t v = (int64_t)i * x;
for (; i <= n; i += i & -i)
sum1[i] += x, sum2[i] += v;
}
public:
fenwick_rg(int n_) : n(n_), sum1(n + 1), sum2(n + 1) {}
// [l, r)
void add(int l, int r, int x) {
assert(l >= 0 && l < r && r <= n);
add(l, x);
if (r < n)
add(r, -x);
}
int64_t get(int p) {
assert(p >= 0 && p <= n);
int64_t res{};
for (int i = p; i; i -= i & -i)
res += (p + 1) * sum1[i] - sum2[i];
return res;
}
// [l, r)
int64_t get(int l, int r) {
assert(l >= 0 && l < r && r <= n);
return get(r) - get(l);
}
};
| true |
17b67f981bdac0175b7d5781f619dca2784aa3c5 | C++ | jacob-hegna/jhcrypto | /src/buffer.cpp | UTF-8 | 6,173 | 3.140625 | 3 | [] | no_license | /**
* buffer.cpp
* @author: jacob hegna <jacobhegna@gmail.com>
* @date: April 2017
* @comment: a high-level interface for a buffer of bytes
*/
#include "buffer.h"
const char jhc::buffer::b64_table[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
/**************************
******* CONSTRUCTORS ******
**************************/
jhc::buffer::buffer() {}
jhc::buffer::buffer(std::string str, jhc::encoding encoding) {
this->set(str, encoding);
}
jhc::buffer::buffer(std::vector<uint8_t> bytes)
: bytes(bytes)
{}
/**************************
****** PUBLIC METHODS *****
**************************/
void jhc::buffer::set(std::string data, jhc::encoding encoding) {
switch(encoding) {
case jhc::encoding::ASCII: set_as_ascii(data); break;
case jhc::encoding::HEX: set_as_hex(data); break;
case jhc::encoding::B64: set_as_b64(data); break;
}
}
std::string jhc::buffer::get(jhc::encoding encoding) const {
switch(encoding) {
case jhc::encoding::ASCII: return get_as_ascii();
case jhc::encoding::HEX: return get_as_hex();
case jhc::encoding::B64: return get_as_b64();
}
// should never be reached
return "";
}
void jhc::buffer::push(uint8_t byte) {
bytes.push_back(byte);
}
void jhc::buffer::push(jhc::buffer buf) {
bytes.insert(bytes.end(), buf.bytes.begin(), buf.bytes.end());
}
uint8_t jhc::buffer::at(uint loc) const {
return (loc < bytes.size()) ? bytes.at(loc) : 0;
}
jhc::buffer jhc::buffer::chunk(uint pos, uint len) const {
return jhc::buffer(
std::vector<uint8_t>(bytes.begin() + pos, bytes.begin() + pos + len)
);
}
uint jhc::buffer::size() const {
return bytes.size();
}
/**************************
****** STATIC METHODS *****
**************************/
uint8_t jhc::buffer::char_to_byte(char c) {
if(c >= '0' && c <= '9') {
return c - '0';
}
if(c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if(c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return 0;
}
char jhc::buffer::byte_to_char(uint8_t b) {
if(b >= 0 && b <= 9) {
return b + '0';
}
if(b >= 10 && b <= 15) {
return b + 'a' - 10;
}
return 0;
}
/**************************
**** OPERATOR OVERLOADS ***
**************************/
jhc::buffer jhc::buffer::operator^(const jhc::buffer& rhc) const {
std::vector<uint8_t> new_bytes;
if(this->bytes.size() != rhc.bytes.size()) {
// throw error
}
for(uint i = 0; i < this->bytes.size(); ++i) {
new_bytes.push_back(
this->bytes.at(i) ^ rhc.bytes.at(i)
);
}
return jhc::buffer(new_bytes);
}
jhc::buffer jhc::buffer::operator^(const char& c) const {
std::vector<uint8_t> new_bytes;
for(uint i = 0; i < this->bytes.size(); ++i) {
new_bytes.push_back(
this->bytes.at(i) ^ c
);
}
return jhc::buffer(new_bytes);
}
/**************************
***** GETTERS/SETTERS *****
**************************/
void jhc::buffer::set_as_ascii(std::string str) {
// reset the buffer
bytes.clear();
bytes.reserve(str.size());
for(uint i = 0; i < str.size(); ++i) {
bytes.push_back(str[i]);
}
}
void jhc::buffer::set_as_hex(std::string str) {
// reset the buffer
bytes.clear();
// ensure an even number of hex digits
if(str.size() % 2 == 1) str.insert(0, 1, '0');
bytes.reserve(str.size() / 2);
for(uint i = 0; i < str.size(); i += 2) {
bytes.push_back(0);
bytes[i/2] = jhc::buffer::char_to_byte(str[i]) << 4;
bytes[i/2] |= jhc::buffer::char_to_byte(str[i + 1]);
}
}
void jhc::buffer::set_as_b64(std::string str) {
static uint8_t b64_table_decode[256];
if(b64_table_decode[0] == 0) {
for(uint i = 0; i < 64; ++i) {
b64_table_decode[(unsigned char) jhc::buffer::b64_table[i]] = i;
}
}
uint buffer_length = (str.size() / 4) * 3;
// reset the buffer
bytes.clear();
bytes.reserve(buffer_length);
for(uint i = 0; i < str.size();) {
uint32_t sextet_a = str[i] == '=' ? 0 & i++ : b64_table_decode[str[i++]];
uint32_t sextet_b = str[i] == '=' ? 0 & i++ : b64_table_decode[str[i++]];
uint32_t sextet_c = str[i] == '=' ? 0 & i++ : b64_table_decode[str[i++]];
uint32_t sextet_d = str[i] == '=' ? 0 & i++ : b64_table_decode[str[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (bytes.size() < buffer_length) bytes.push_back((triple >> 2 * 8) & 0xFF);
if (bytes.size() < buffer_length) bytes.push_back((triple >> 1 * 8) & 0xFF);
if (bytes.size() < buffer_length) bytes.push_back((triple >> 0 * 8) & 0xFF);
}
}
std::string jhc::buffer::get_as_ascii() const {
return std::string(bytes.begin(), bytes.end());
}
std::string jhc::buffer::get_as_hex() const {
std::string hexstr;
for(uint8_t byte : bytes) {
hexstr += jhc::buffer::byte_to_char(byte >> 4);
hexstr += jhc::buffer::byte_to_char(byte & 0x0F);
}
return hexstr;
}
std::string jhc::buffer::get_as_b64() const {
std::string b64str;
for(int i = 0; i < bytes.size();) {
uint32_t octet_a = (i < bytes.size()) ? bytes[i++] : 0;
uint32_t octet_b = (i < bytes.size()) ? bytes[i++] : 0;
uint32_t octet_c = (i < bytes.size()) ? bytes[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
b64str += jhc::buffer::b64_table[(triple >> 3 * 6) & 0x3f];
b64str += jhc::buffer::b64_table[(triple >> 2 * 6) & 0x3f];
b64str += jhc::buffer::b64_table[(triple >> 1 * 6) & 0x3f];
b64str += jhc::buffer::b64_table[(triple >> 0 * 6) & 0x3f];
}
return b64str;
}
| true |
bb658d6bfdf0f62aec44bf0be408c54cbfce699e | C++ | Void13/GolovanovNotPrivate | /Lab2/BigInt.h | UTF-8 | 1,679 | 2.53125 | 3 | [] | no_license | #ifndef _H__BIGINT
#define _H__BIGINT
#include <memory.h>
#include <iostream>
#include <deque>
#include <string>
//#define DEBUG_CONSTR 1
class CBigInt
{
private:
typedef std::deque<char> CHARDEQ;
public:
CBigInt();
CBigInt(int const _nNumber);
CBigInt(std::string const _sNumber);
CBigInt(CBigInt const &_SourceNumber);
CBigInt(CBigInt &&_SourceNumber);
~CBigInt();
friend void ClearZeroes(CBigInt &_Number);
CBigInt const &operator+=(CBigInt const &_Second);
CBigInt const &operator-=(CBigInt const &_Second);
CBigInt const &operator*=(CBigInt const &_Second);
CBigInt const &operator=(CBigInt const &_Number);
CBigInt const &operator=(CBigInt &&_Number);
CBigInt const &operator--();
CBigInt const &operator++();
CBigInt const operator++(int);
CBigInt const operator--(int);
CBigInt const operator-() const;
CBigInt const operator+() const;
friend CBigInt const operator+(CBigInt const &_First, CBigInt const &_Second);
friend CBigInt const operator-(CBigInt const &_First, CBigInt const &_Second);
friend CBigInt const operator*(CBigInt const &_First, CBigInt const &_Second);
friend std::ostream &operator<<(std::ostream &_output, CBigInt const &_Number);
friend bool operator==(CBigInt const &_First, CBigInt const &_Second);
friend bool operator!=(CBigInt const &_First, CBigInt const &_Second);
friend bool operator<(CBigInt const &_First, CBigInt const &_Second);
friend bool operator>(CBigInt const &_First, CBigInt const &_Second);
friend bool operator<=(CBigInt const &_First, CBigInt const &_Second);
friend bool operator>=(CBigInt const &_First, CBigInt const &_Second);
private:
CHARDEQ *m_pNumber;
bool m_bIsNeg;
};
#endif | true |
14ec72d3b173fb8ab01db9f40516cbb9343af850 | C++ | iamslash/learntocode | /leetcode/MinimumAbsoluteDifferenceinBST/a.cpp | UTF-8 | 841 | 3.015625 | 3 | [] | no_license | /* Copyright (C) 2019 by iamslash */
#include <cstdio>
#include <limits>
#include <cstdlib>
#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 16ms 93.34% 21.7MB 100.00%
// inorder
// O(N) O(lgN)
class Solution {
private:
int prvVal = -1;
int minDif = std::numeric_limits<int>::max();
public:
void inOrder(TreeNode* u) {
// base
if (!u)
return;
// recursion
inOrder(u->left);
if (prvVal >= 0) {
int curDif = std::abs(u->val) - std::abs(prvVal);
minDif = std::min(minDif, curDif);
}
prvVal = u->val;
inOrder(u->right);
}
int getMinimumDifference(TreeNode* u) {
inOrder(u);
return minDif;
}
};
int main() {
return 0;
}
| true |
af9b7bbd8a5d0b84dce5488db48c5fc41f463efc | C++ | Sepsad/AP-FinalProject | /Money/Money.cpp | UTF-8 | 267 | 2.796875 | 3 | [] | no_license | #include "Money.h"
Money::Money(User* _user, Film* _film, int _amount)
{
user = _user; amount = _amount; film = _film;
}
User* Money::get_user()
{
return user;
}
Film* Money::get_film()
{
return film;
}
int Money::get_amount()
{
return amount;
}
| true |
4931a08d8edcde8d7678f23ad9323630bf4f6fdf | C++ | ttyang/sandbox | /sandbox/logging/boost/logging/detail/raw_doc/workflow.hpp | UTF-8 | 7,403 | 3.015625 | 3 | [
"BSL-1.0"
] | permissive | namespace boost { namespace logging {
/**
@page workflow Logging workflow
- @ref workflow_introduction
- @ref workflow_filter
- @ref workflow_processing
- @ref workflow_2a
- @ref workflow_2b
- @ref workflow_formatters_destinations
@section workflow_introduction Introduction
What happens when a message is written to the log?
- the message is filtered : is the filter enabled?
- if so (in other words, the log is turned on), process the message:
- gather the message
- write the message to the destination(s)
- if not (in other words, the log is turned off)
- completely ignore the message: <em>if the log is not enabled, no processing takes place</em>.
For instance, say you have:
@code
LDBG_ << "user count = " << some_func_taking_a_lot_of_cpu_time();
@endcode
If @c LDBG_ is disabled, everything after "LDBG_" is ignored. Thus, @c some_func_taking_a_lot_of_cpu_time() will not be called.
First of all, we have 2 concepts:
- logger : a "logical" log - something you write to; it knows its destination(s), that is, where to write to
- filter : this provides a way to say if a logger is enabled or not. Whatever that "way to say a logger is enabled or not" means,
is up to the designer of the filter class.
Note that the logger is a templated class, and the filter is a @ref namespace_concepts "namespace". I've provided
several implementations of the filter concept - you can use them, or define your own.
@section workflow_filter Step 1: Filtering the message
As said above, the filter just provides a way to say if a logger is enabled or not. The %logger and the %filter are completely
separated concepts. No %logger owns a %filter, or the other way around. You can have a %filter per %logger, but most likely
you'll have one %filter, and several loggers:
@code
// Example 1 : 1 filter, 1 logger
BOOST_DECLARE_LOG_FILTER(g_log_filter, filter::no_ts )
BOOST_DECLARE_LOG(g_l, logger_type)
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )
// Example 2 : 1 filter (containing a level), several loggers
BOOST_DECLARE_LOG_FILTER(g_log_level, level::holder )
BOOST_DECLARE_LOG(g_log_err, logger_type)
BOOST_DECLARE_LOG(g_log_app, logger_type)
BOOST_DECLARE_LOG(g_log_dbg, logger_type)
#define LDBG_ BOOST_LOG_USE_LOG_IF_LEVEL(g_log_dbg(), g_log_level(), debug )
#define LERR_ BOOST_LOG_USE_LOG_IF_LEVEL(g_log_err(), g_log_level(), error )
#define LAPP_ BOOST_LOG_USE_LOG_IF_LEVEL(g_log_app(), g_log_level(), info )
@endcode
Every time, before anything gets written to the log, the filter is asked if <em>it's enabled</em>. If so, the processing of the message takes place
(gathering the message and then writing it). Otherwise, the log message is completely ignored.
What <em>it's enabled</em> is depends on the filter class you use:
- if it's a simple class (filter::no_ts, filter::ts, filter::use_tss_with_cache), it's simply the @c is_enabled function (Example 1, above)
- if it's a more complex class, it's up to you
- for instance, the level::holder_no_ts exposes an <tt>is_enabled(level)</tt>, so you can ask if a certain level is enabled (Example 2, above)
Thus, logging takes place only if that certain level is enabled (@c debug for LDBG_, @c info for LAPP_, @c error for LERR_)
\n\n
@section workflow_processing Step 2: Processing the message
Once we've established that the logger is enabled, we'll @em process the message. This is divided into 2 smaller steps:
- gathering the message
- writing the message
@section workflow_2a Step 2A: Gathering the message
The meaning of "gathering the message" depends on your application. The message can:
- be a simple string,
- it can contain extra info, like: level, category, etc
- it can be written all at once, or using the cool "<<" operator
- or any combination of the above
Depending on your needs, gathering can be complex or not. However, it's completely decoupled from the other steps.
Gathering goes hand in hand with @ref macros_use "macros".
The cool thing is that you decide how the <i>Logging syntax</i> is - depending on how you want to gather the message.
All of the below are viable options:
@code
L_("reading " + word);
L_ << "this " << " is " << "cool";
L_(dbg) << "happily debugging";
L_(err,"chart")("Cannot load chart")(chart_path);
@endcode
How you gather your message, depends on how you @ref macros_use "#define L_ ...".
In other words, gathering the message means getting all the message in "one piece", so that it can be written. \n
See the
- the gather namespace - classes for gathering
- the gather::ostream_like - classes for gathering, using the cool "<<" operator
\n\n
@section workflow_2b Step 2B: Writing the message
Now that you have the message, you're ready to write it. Writing is done by calling @c operator() on the writer object.
What you choose as the writer object is completely up to you. It can be as simple as this:
@code
// dump message to cout
struct write_to_cout {
void operator()(const std::string & msg) const {
std::cout << msg << std::endl ;
}
};
typedef logger< gather::ostream_like::return_str<std::string>, write_to_cout> logger_type;
BOOST_DECLARE_LOG(g_single_log, logger_type)
BOOST_DECLARE_LOG_FILTER(g_filter, filter::no_ts)
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_single_log, g_filter->is_enabled() )
// usage
int i = 100;
L_ << "this is " << i << " times cooler than the average log";
@endcode
You can define your own types of writers. The %writer classes that come with this library are in <tt>namespace writer</tt>.
At this time, I've defined the concept of writer::format_write - writing using @ref manipulator "Formatters and Destinations".
Simply put, this means formatting the message, and then writing it to destination(s).
For each log, you decide how messages are formatted and to what destinations they are written. Example:
@code
typedef logger_format_write< > logger_type;
BOOST_DECLARE_LOG_FILTER(g_log_filter, filter::no_ts )
BOOST_DECLARE_LOG(g_l, logger_type)
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )
// add formatters : [idx] [time] message <enter>
g_l()->writer().add_formatter( formatter::idx() );
g_l()->writer().add_formatter( formatter::time("$hh:$mm.$ss ") );
g_l()->writer().add_formatter( formatter::append_newline() );
// add destinations : console, output debug window, and a file called "out.txt"
g_l()->writer().add_destination( destination::cout() );
g_l()->writer().add_destination( destination::dbg_window() );
g_l()->writer().add_destination( destination::file("out.txt") );
// usage
int i = 1;
L_ << "this is so cool " << i++;
L_ << "this is so cool again " << i++;
// possible output:
// [1] 12:32:10 this is so cool 1
// [2] 12:32:10 this is so cool again 2
@endcode
\n\n
@section workflow_formatters_destinations Workflow when using formatters and destinations
When using @ref manipulator "formatters and destinations", there are some steps you'll usually take.
Remember:
- formatter - allows formatting the message before writing it (like, prepending extra information - an index, the time, thread id, etc)
- destination - is a place where the message is to be written to (like, the console, a file, a socket, etc)
@copydoc common_usage_steps_fd
There are plenty of @ref common_scenarios "examples" together with @ref scenarios_code "code".
*/
}}
| true |
3023ef6bfcedaee7d94835438da8f1fa2300516d | C++ | lucasbivar/object-oriented-programming | /U2A5/11/Agenda.cpp | UTF-8 | 1,590 | 2.984375 | 3 | [] | no_license | #include "Agenda.h"
#include "Pessoa.h"
#include <iostream>
using std::cout;
using std::endl;
Agenda::Agenda(int tamanho){
this->quantidadeDeContatos = 0;
this->tamanhoDaAgenda = tamanho > 0 ? tamanho : 10;
this->agenda = new Pessoa*[tamanhoDaAgenda];
}
Agenda::~Agenda(){
for(int i = 0; i < quantidadeDeContatos; i++){
delete agenda[i];
}
delete [] agenda;
}
void Agenda::listarContatos() const {
cout << endl;
cout << "=-=-=-=-=-=-=-=AGENDA-=-=-=-=-=-=-=-=-=-=" << endl;
for(int i = 0; i < quantidadeDeContatos; i++){
agenda[i]->exibirPessoa();
}
cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
cout << endl;
}
void Agenda::buscarContato(const string termoDeBusca) const {
for(int i = 0; i < quantidadeDeContatos; i++){
if(agenda[i]->getNome() == termoDeBusca ||
agenda[i]->getCpfOrCnpj() == termoDeBusca){
agenda[i]->exibirPessoa();
break;
}
}
}
bool Agenda::removerContato(const string termoDeBusca){
int posicaoPessoa = -1;
for(int i = 0; i < quantidadeDeContatos; i++){
if(agenda[i]->getNome() == termoDeBusca ||
agenda[i]->getCpfOrCnpj() == termoDeBusca){
posicaoPessoa = i;
}
}
if(posicaoPessoa == -1) return false;
delete agenda[posicaoPessoa];
for(int i = posicaoPessoa+1; i < quantidadeDeContatos; i++){
agenda[i-1] = agenda[i];
}
quantidadeDeContatos--;
return true;
}
bool Agenda::adicionarContato(Pessoa* pessoa) {
if(quantidadeDeContatos < tamanhoDaAgenda){
agenda[quantidadeDeContatos++] = pessoa;
return true;
}
return false;
} | true |
2755552006aeb8db2d5282f4fd48f684835a05eb | C++ | lawu103/tiny_raytracer | /src/tiny_raytracer.cpp | UTF-8 | 5,054 | 2.9375 | 3 | [] | no_license | //============================================================================
// Name : tiny_raytracer.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "geometry.h"
#include "objects.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define EPSILON_F numeric_limits<float>::epsilon()
#define MAX_F numeric_limits<float>::max()
/*
* Converts a canvas xy position to a viewport xyz position
*/
Vec3f canvas_to_port(float canvasX, float canvasY, int canvasW, int canvasH, int portW, int portH, int portD) {
return Vec3f(canvasX*portW/canvasW, canvasY*portH/canvasH, portD);
}
/*
* Reflects R over N
*/
Vec3f reflect_ray(const Vec3f& R, const Vec3f& N) {
return 2*(R*N)*N - R;
}
/*
* Calculates total lighting on a point
*/
float compute_lighting(const Vec3f& dir, const Vec3f& P, const Vec3f& N, const size_t closestBallInd,
const vector<Sphere>& balls, const Light& ambientLight, const vector<DirectedLight>& directedLights) {
float i = ambientLight.get_intensity();
for (const DirectedLight& directedLight: directedLights) {
Vec3f L;
if (directedLight.is_point()) {
L = directedLight.get_v() - P;
} else {
L = -directedLight.get_v();
}
// Shadow
bool isShadowed = false;
for (const Sphere& ball: balls) {
float t = ball.ray_intersection(P, L);
if (t < MAX_F && t > 0) {
isShadowed = true;
break;
}
}
if (!isShadowed) {
// Diffuse
float NdotL = N*L;
if (NdotL > 0) {
i += directedLight.get_intensity() * NdotL/(N.length()*L.length());
}
// Specular
float s = balls[closestBallInd].get_specular();
if (s > 0) {
Vec3f R = reflect_ray(L, N);
Vec3f V = -dir;
float RdotV = R*V;
if (RdotV > 0) {
i += directedLight.get_intensity() * pow(RdotV/(R.length()*V.length()), s);
}
}
}
}
return i;
}
/*
* Returns the color a ray sees
*/
Vec3f trace_ray(const Vec3f& camera, const Vec3f& dir, const vector<Sphere>& balls, const Light& ambientLight,
const vector<DirectedLight>& directedLights, const int recurseLimit) {
float tmin = numeric_limits<float>::max();
Vec3f color = Vec3f(0, 0, 0);
int closestBallInd = -1;
for (size_t i = 0; i < balls.size(); ++i) {
float t = balls[i].ray_intersection(camera, dir);
if (t < tmin && t >= 0) {
tmin = t;
closestBallInd = i;
}
}
if (closestBallInd < 0) {
return color;
}
Vec3f P = camera + tmin*dir;
Vec3f N = P - balls[closestBallInd].get_center();
N = 1/N.length() * N;
float lighting = compute_lighting(dir, P, N, closestBallInd, balls, ambientLight, directedLights);
color = lighting*balls[closestBallInd].get_color();
float r = balls[closestBallInd].get_reflective();
if (recurseLimit > 0 && r > 0) {
Vec3f R = reflect_ray(-dir, N);
color = (1 - r)*color + r*trace_ray(P, R, balls, ambientLight, directedLights, recurseLimit - 1);
}
return Vec3f(min(255.f, color[0]), min(255.f, color[1]), min(255.f, color[2]));
}
int main() {
vector<Sphere> balls = {Sphere(Vec3f(0, -1, 3), 1, Vec3f(255, 0, 0), 500, 0.2),
Sphere(Vec3f(-2, 0, 4), 1, Vec3f(0, 255, 0), 10, 0.4),
Sphere(Vec3f(2, 0, 4), 1, Vec3f(0, 0, 255), 500, 0.3),
Sphere(Vec3f(0, -5001, 0), 5000, Vec3f(255, 255, 0), 1000, 0.5)};
// The sum of the intensities of our lights should be 1 if we don't want overexposure.
Light ambientLight(0.2);
vector<DirectedLight> directedLights = {DirectedLight(0.6, true, Vec3f(2, 1, 0)),
DirectedLight(0.2, false, Vec3f(-1, -4, -4))};
// The recursion limit for reflections
const int recurseLimit = 3;
// Camera position in world coordinates. x and y are planar with the screen, z is into the screen.
const Vec3f camera(0, 0, 0);
// Canvas dimensions in pixels.
const int canvasW = 1024;
const int canvasH = 1024;
// Viewport dimensions in world units. This should be proportionally the same as the canvas.
// Note that the viewport is always fixed centered to the camera, so portD is a depth that's
// relative to the camera.
const int portW = 1;
const int portH = 1;
const int portD = 1;
vector<Vec3f> framebuffer(canvasW*canvasH);
// Fill in color values
for (int j = 0; j < canvasH; ++j) {
for (int i = 0; i < canvasW; ++i) {
float canvasX = i - canvasW/2.f; // treat center of canvas as origin
float canvasY = canvasH/2.f - j;
Vec3f dir = canvas_to_port(canvasX, canvasY, canvasW, canvasH, portW, portH, portD);
Vec3f color = trace_ray(camera, dir, balls, ambientLight, directedLights, recurseLimit);
framebuffer[j*canvasW + i] = color;
}
}
// Output to file
ofstream ofs;
ofs.open("./test.ppm", ofstream::binary);
ofs << "P6\n" << canvasW << " " << canvasH << "\n255\n";
for (int i = 0; i < canvasW*canvasH; ++i) {
for (int j = 0; j < 3; ++j) {
ofs << (char)(framebuffer[i][j]);
}
}
ofs.close();
cout << "All done!" << endl;
return 0;
}
| true |
7d3bcb1c712e39f07959669699cdef34e296d723 | C++ | AndreasPatakis/Programs-Projects | /DataStructures_1(2o Semester)/Failed_17-18/dentro.cpp | UTF-8 | 2,635 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
class tour{
public:
int infos[4];
tour(){
fstream file;
file.open("t103.txt");
string line;
int p=0;
while(!file.eof()) {
getline(file,line);
istringstream iss(line);
string word;
if (p==0) {
for(int i=0;i<=3;i++){
iss >> word;
infos[i]=stoi(word);}}
else{break;}
p+=1;}}};
class hotel{
public:
int infos[7];
hotel(){
fstream file;
file.open("t103.txt");
string line;
int p=0;
while(!file.eof()) {
getline(file,line);
istringstream iss(line);
string word;
if (p==1) {
for(int i=0;i<=6;i++){
iss >> word;
infos[i]=stoi(word);}}
else if(p>1){break;}
p+=1;}}};
class diadromes{};
int p1=0;
class data{
public:
float infos[5];
int open[7];
int close[7];
data(){
int j1=-1;
int j2=-1;
p1+=1;
int q=0;
fstream file;
file.open("t103.txt");
string line;
while(!file.eof()) {
q+=1;
getline(file,line);
istringstream iss(line);
string word;
if(q!=1&&q!=2){
if (q==p1){
for(int y=0;y<=19;y++){
iss >> word;
if(y<=4){
infos[y]=stof(word);}
else if(y!=5){
if(y%2==0){j1+=1;
open[j1]=stoi(word);}
else{j2+=1;
close[j2]=stoi(word);}
}
}break;}}}}};
struct node
{
data x;
node *next;
//node* head;
};
node* head=new node;
node* first=new node;
void insert(data &sight){
node *temp=new node;
temp->x=sight;
temp->next=NULL;
head->next=temp;
//cout<<head->next<<endl;
//cout<<temp->data<<endl;
head=temp;
}
void print(){
node* temp=first;
temp=temp->next;
while(temp != NULL){
cout<<temp->x.infos[0]<<endl;
//cout<<temp->next<<endl;
temp=temp->next;
}
}
int main(){
first=head;
tour tour_infos;
hotel hotel_infos;
data sight[91];
//cout<<sight[90].infos[0];
//cout<<sight[100].infos[0]<<endl;
for(int i=0;i<=73;i++){
insert(sight[i]);}
print();
//cout<<sight[164].close[0];
//for (int i=0;i<=164;i++){
//insert(sight[i]);}
//cout<<endl;*/
return 0;
}
| true |
61580b35f9d7c476923061f6c1c01bd5c18cb611 | C++ | AriPerkkio/Bluetooth-And-Wifi-Scanner | /ServerBtWifiScan/src/Btresult.h | UTF-8 | 558 | 2.609375 | 3 | [] | no_license | /*
* Btresult.h
*
* Created on: 27.4.2016
* Author: AriPerkkio
*/
#ifndef BTRESULT_H_
#define BTRESULT_H_
#include <iostream> // for std
using namespace std;
class Btresult {
string name;
string address;
string type;
string rssi;
string location;
public:
Btresult(string, string, string, string, string);
virtual ~Btresult();
void printInfo();
string getName();
string getAddress();
string getType();
string getRssi();
string getLoc();
string toString();
bool operator==(const Btresult &first) const;
};
#endif /* BTRESULT_H_ */
| true |
b33aa426baabbe353def41e54fb1a46104f24665 | C++ | nikhil9402/lab_6_assignment | /lab_6_question03.cpp | UTF-8 | 427 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main () {
int arr[10],*p;
cout << "Enter the elements of the array; \n";
for (int i=0;i<10;i++)
{
cin >> arr[i];
}
cout << "The array is : \n";
//using normal index method
for (int i=0;i<10;i++)
{
cout << arr[i] << endl;
}
cout << "The array is : \n";
//using pointer method
for (int i=0;i<10;i++)
{
p=&arr[i];
cout << *p << endl;
}
return 0;
}
| true |
8a657493981d920adff409c398b126acdb98812c | C++ | michaeloverton/fourth-world-lasers | /tlc5947test/tlc5947test.ino | UTF-8 | 2,736 | 2.859375 | 3 | [] | no_license | /***************************************************
MUKE
****************************************************/
#include "Adafruit_TLC5947.h"
// How many boards do you have chained?
#define NUM_TLC5974 1
#define data 4
#define clock 5
#define latch 6
#define oe -1 // set to -1 to not use the enable pin (its optional)
Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);
int loopCount;
int mode = 3;
long previousMillis = 0; // will store last time LED was updated
long interval = 1000; // interval at which to blink (milliseconds)
int laserCount = 5; // total number of lasers
int intensity = 1;
void setup() {
Serial.begin(9600);
Serial.println("TLC5974 test");
tlc.begin();
loopCount = 0;
}
void loop() {
if (Serial.available() >= 2) {
int message = Serial.read();
if(message == 'T') {
interval = Serial.read();
//Serial.println(interval, DEC);
}
else if(message == 'M') {
mode = Serial.read();
//Serial.println(mode, DEC);
}
else if(message == 'I') {
intensity = Serial.read() / 5;
//Serial.println(intensity, DEC);
}
}
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
if(mode == 1) {
chase();
}
else if(mode == 2) {
strobe();
}
else if(mode == 3) {
twinkle();
}
}
}
void chase() {
for(int i = 0; i < laserCount; i++) {
if(i == loopCount) { //
tlc.setPWM(i, 4095);
tlc.write();
for(int j = 1; j < intensity; j++) {
int currentLaser = (i +j) % laserCount;
tlc.setPWM(currentLaser, 4095);
tlc.write();
}
}
else {
if(i < loopCount) {
tlc.setPWM(i, 0);
tlc.write();
}
else if(i >= loopCount + intensity) {
tlc.setPWM(i, 0);
tlc.write();
}
}
}
// increment or reset the count to zero
if(loopCount == laserCount -1) {
loopCount = 0;
}
else {
loopCount++;
}
}
void strobe() {
if(loopCount != 0) {
for(int i = 0; i < laserCount; i++) {
tlc.setPWM(i, 0);
tlc.write();
}
loopCount = 0;
}
else {
for(int i = 0; i < laserCount; i++) {
tlc.setPWM(i, 4095);
tlc.write();
}
loopCount++;
}
}
void twinkle() {
// turn off all lasers
for(int i = 0; i < laserCount; i++) {
tlc.setPWM(i, 0);
tlc.write();
}
// turn on random ones (based on intensity)
int randomLaser;
for(int i = 0; i < intensity; i++) {
randomLaser = (int) random(0, laserCount);
tlc.setPWM(randomLaser, 4095);
tlc.write();
}
}
| true |
1ca620adeea0dc14975038b0254675dc62d97344 | C++ | oPensyLar/karos-algos | /rosh-cplus/arg2_string_ptr.h | UTF-8 | 19,528 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
std::vector<int> *arg2_string_ptr = new std::vector<int>;
void initArg2_string_ptr()
{
// vector arg2_string_ptr
arg2_string_ptr->push_back(0xa5);
arg2_string_ptr->push_back(0xd9);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0x59);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xac);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0x95);
arg2_string_ptr->push_back(0xb6);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
arg2_string_ptr->push_back(0xf0);
arg2_string_ptr->push_back(0xad);
arg2_string_ptr->push_back(0xba);
arg2_string_ptr->push_back(0xd);
} | true |
bf86b4981ba894756887d8888fb674d8a7b5616e | C++ | leonardean/RayTracer | /Config.h | UTF-8 | 1,019 | 2.6875 | 3 | [] | no_license | #ifndef __CONFIG_H
#define __CONFIG_H
#include "Definition.h"
#include "SimpleString.h"
#pragma warning( push )
#pragma warning( disable : 4512 )
class Config {
private:
void * m_pVariables;
void * m_pSections;
const SimpleString m_sFileName;
SimpleString m_sCurrentSection;
bool m_bLoaded;
public:
bool GetByNameAsBoolean(const SimpleString & sName, bool bDefault) const;
double GetByNameAsFloat(const SimpleString & sName, double fDefault) const;
const SimpleString &GetByNameAsString(const SimpleString &sName, const SimpleString & sDefault) const;
int GetByNameAsInteger(const SimpleString &sName, int lDefault) const;
vector3d GetByNameAsVector(const SimpleString &sName, const vector3d& vDefault) const;
point GetByNameAsPoint(const SimpleString &sName, const point& ptDefault) const;
int SetSection(const SimpleString &sName);
~Config();
Config(const SimpleString &sFileName);
};
#pragma warning( pop )
#endif
| true |
63461cb3c37699ae3623a7000f786119e897bcc9 | C++ | muhammadbilalakbar021/Cplus_ | /prob14/test/unittest.cpp | UTF-8 | 6,091 | 3.125 | 3 | [
"MIT"
] | permissive | #include "../cash_debit_card.hpp"
#include "gtest_ext.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
TEST(CashCard, OutputFormatNormal) {
std::ostringstream test_output;
std::ostringstream test_input;
std::string name = generate_string(10);
int choice;
double amount_due, balance;
test_output << "Enter the total price: $";
test_input << 30.00 << "\n";
test_output << "Enter your name: ";
test_input << name << "\n";
test_output << "Choose the card you will be paying with:\n";
test_output << "1 - Cash Card\n";
test_output << "2 - Debit Card\n";
test_output << "Choice: ";
test_input << 1 << "\n";
test_output << "Enter the balance on your card: $";
test_input << 80.00 << "\n";
test_output << "The amount left on your card is $" << std::fixed
<< std::setprecision(2) << 50.00 << "\n";
std::string unittest_output = test_output.str();
std::string unittest_input = test_input.str();
ASSERT_EXECIO_EQ("main", unittest_input, unittest_output);
}
TEST(CashCard, OutputFormatOverdraw) {
std::ostringstream test_output;
std::ostringstream test_input;
std::string name = generate_string(10);
int choice;
double amount_due, balance;
test_output << "Enter the total price: $";
test_input << 30.00 << "\n";
test_output << "Enter your name: ";
test_input << name << "\n";
test_output << "Choose the card you will be paying with:\n";
test_output << "1 - Cash Card\n";
test_output << "2 - Debit Card\n";
test_output << "Choice: ";
test_input << 1 << "\n";
test_output << "Enter the balance on your card: $";
test_input << 25.00 << "\n";
test_output << "Insufficient funds\n";
test_output << "The amount left on your card is $" << std::fixed
<< std::setprecision(2) << 25.00 << "\n";
std::string unittest_output = test_output.str();
std::string unittest_input = test_input.str();
ASSERT_EXECIO_EQ("main", unittest_input, unittest_output);
}
TEST(DebitCard, OutputFormatNormal) {
std::ostringstream test_output;
std::ostringstream test_input;
std::string name = generate_string(10);
int choice;
double amount_due, balance;
test_output << "Enter the total price: $";
test_input << 30.00 << "\n";
test_output << "Enter your name: ";
test_input << name << "\n";
test_output << "Choose the card you will be paying with:\n";
test_output << "1 - Cash Card\n";
test_output << "2 - Debit Card\n";
test_output << "Choice: ";
test_input << 2 << "\n";
test_output << "Enter the balance on your card: $";
test_input << 80.00 << "\n";
test_output << "The amount left on your card is $" << std::fixed
<< std::setprecision(2) << 50.00 << "\n";
std::string unittest_output = test_output.str();
std::string unittest_input = test_input.str();
ASSERT_EXECIO_EQ("main", unittest_input, unittest_output);
}
TEST(DebitCard, OutputFormatOverdraw) {
std::ostringstream test_output;
std::ostringstream test_input;
std::string name = generate_string(10);
int choice;
double amount_due, balance;
test_output << "Enter the total price: $";
test_input << 30.00 << "\n";
test_output << "Enter your name: ";
test_input << name << "\n";
test_output << "Choose the card you will be paying with:\n";
test_output << "1 - Cash Card\n";
test_output << "2 - Debit Card\n";
test_output << "Choice: ";
test_input << 2 << "\n";
test_output << "Enter the balance on your card: $";
test_input << 25.00 << "\n";
test_output << "Overdraft Fee of $30.00 Incurred\n";
test_output << "The amount left on your card is $" << std::fixed
<< std::setprecision(2) << -35.00 << "\n";
std::string unittest_output = test_output.str();
std::string unittest_input = test_input.str();
ASSERT_EXECIO_EQ("main", unittest_input, unittest_output);
}
TEST(CashCard, AccessorsAndMutators) {
CashCard your_cash_card;
your_cash_card.setBalance(100.00);
your_cash_card.setName("testName");
ASSERT_EQ(your_cash_card.getBalance(), 100.00);
ASSERT_EQ(your_cash_card.getName(), "testName");
}
TEST(CashCard, DefaultConstructor) {
CashCard your_cash_card;
ASSERT_EQ(your_cash_card.getBalance(), 100.00);
ASSERT_EQ(your_cash_card.getName(), "John Doe");
}
TEST(CashCard, NonDefaultConstructor) {
std::string unittest_name = generate_string(12);
double unittest_balance = 120.00;
CashCard your_cash_card(unittest_balance, unittest_name);
ASSERT_EQ(your_cash_card.getBalance(), unittest_balance);
ASSERT_EQ(your_cash_card.getName(), unittest_name);
}
TEST(CashCard, Charge) {
CashCard your_cash_card;
your_cash_card.charge(30);
ASSERT_EQ(your_cash_card.getBalance(), 70.00);
your_cash_card.charge(30);
ASSERT_EQ(your_cash_card.getBalance(), 40.00);
ASSERT_SIO_EQ("", "Insufficient funds\n", { your_cash_card.charge(45.00); });
ASSERT_EQ(your_cash_card.getBalance(), 40.00);
}
TEST(DebitCard, AccessorsAndMutators) {
DebitCard your_debit_card;
your_debit_card.setBalance(100.00);
your_debit_card.setName("testName");
ASSERT_EQ(your_debit_card.getBalance(), 100.00);
ASSERT_EQ(your_debit_card.getName(), "testName");
}
TEST(DebitCard, DefaultConstructor) {
DebitCard your_debit_card;
ASSERT_EQ(your_debit_card.getBalance(), 100.00);
ASSERT_EQ(your_debit_card.getName(), "John Doe");
}
TEST(DebitCard, NonDefaultConstructor) {
std::string unittest_name = generate_string(12);
DebitCard your_debit_card(120, unittest_name);
ASSERT_EQ(your_debit_card.getBalance(), 120.00);
ASSERT_EQ(your_debit_card.getName(), unittest_name);
}
TEST(DebitCard, Charge) {
DebitCard your_debit_card;
your_debit_card.charge(30);
ASSERT_EQ(your_debit_card.getBalance(), 70.00);
your_debit_card.charge(30);
ASSERT_EQ(your_debit_card.getBalance(), 40.00);
ASSERT_SIO_EQ("", "Overdraft Fee of $30.00 Incurred\n",
{ your_debit_card.charge(45.00); });
double unittest_output = 40.00 - 45.00 - 30.00;
ASSERT_EQ(your_debit_card.getBalance(), unittest_output);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
b2ec9a69e334dd2a2cae319eae67a1eff3311b97 | C++ | vamsiteja/kr_sir | /kr sir/linked lists/linkedlists split.cpp | UTF-8 | 1,415 | 3.234375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct node
{int data;
struct node*next;
};
typedef struct node* lptr;
void pushend(lptr *l,int x)
{
lptr t=*l,t2=new node;t2->data=x;t2->next=NULL;
while(t->next!=NULL)
t=t->next;
t->next=t2;
}
void split(lptr *l1,lptr *l2)
{
lptr t1,t2;
int flag=1;
for(t1=*l1;t1!=NULL;t1=t1->next)
{
for(t2=*l2;t2!=NULL;t2=t2->next)
if(t1==t2)
{flag=0;break;
}
if(flag==0)
break;
}
lptr temp=*l2;
while(temp!=t2)
{
cout<<temp->data;
temp=temp->next;
}
}
int main()
{
int n,key;lptr l[2],temp[2];
for(int i=0;i<2;i++)
{
cout<<"enter the number of nodes u want to enter "<<endl;cin>>n;
int d;cout<<"enter the data of linked lists"<<i<<endl;cin>>d;
l[i]=new node;
l[i]->data=d;
l[i]->next=NULL;
for(int j=0;j<n-1;j++)
{cin>>d;
pushend(&l[i],d);
}
}
for(int j=0;j<2;j++)
{
temp[j]=l[j];
while(temp[j]->next!=NULL)
{
temp[j]=temp[j]->next;
}
}
for(int p=0;p<2;p++)
temp[p]->next=l[2];
for(int k=0;k<2;k++)
{ lptr temp=l[k];
cout<<k+1<<"loop is "<<endl;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
} cout<<endl;
}
split(&l[0],&l[1]);
return 0;
}
| true |
e57f8db9b0decf30aca8821550b59dc028723816 | C++ | Xsardas1000/Algorithms-and-Data-structures | /ht4-2.cpp | UTF-8 | 1,626 | 3.203125 | 3 | [] | no_license | //
// ht4-2.cpp
// sphere
//
// Created by Максим on 09.04.16.
// Copyright © 2016 Максим. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
/*Унимодальный массив
На вход подаётся число N ≤ 1000 и унимодальный массив a размера N: элементы a расположены таким образом, что
a[1] < a[2]
a[2] < a[3]
...
a[k - 1] < a[k] > a[k + 1]
a[k + 1] > a[k + 2]
a[k + 2] > a[k + 3]
...
a[N - 1] > a[N].
Требуется найти a[k]
Input format
N
a[1] a[2] ... a[N]
Output format
a[k]*/
using namespace:: std;
int main(int argc, const char * argv[]) {
int N;
cin >> N;
vector<int> a(N);
for (int i = 0; i < N; i++) {
cin >> a[i];
}
int left = 0, right = N - 1, res;
while (left <= right) {
if (left == right) {
res = a[left];
break;
}
int mid = (left + right) / 2;
if ((mid == 0 && a[mid] > a[mid + 1]) || (mid == N - 1 && a[mid] > a[mid - 1])) {
res = a[mid];
break;
}
if (a[mid] < a[mid + 1] && a[mid - 1] < a[mid]) {
left = mid + 1;
} else if (a[mid] > a[mid + 1] && a[mid] < a[mid - 1]) {
right = mid - 1;
} else if (a[mid] > a[mid - 1] && a[mid] > a[mid + 1]){
res = a[mid];
break;
}
}
cout << res << endl;
return 0;
} | true |
642b98874a4650770abe042e872eaa8f040c083f | C++ | Areustle/heasoft-6.20 | /Xspec/src/XSFunctions/vgaussDem.cxx | UTF-8 | 2,861 | 2.5625 | 3 | [] | no_license | #include <stlToCArrays.h>
#include <xsFortran.h>
#include <functionMap.h>
#include <XSUtil/Utils/XSutility.h>
#include <XSUtil/Numerics/Numerics.h>
#include <xsTypes.h>
#include <cmath>
void cxxsumdem(int itype, int swtch, const RealArray& energyArray, const RealArray& abundances, Real density, Real redshift, const RealArray& Tarray, const RealArray& demarray, int spectrumNumber, bool qtherm, Real velocity, RealArray& flux, RealArray& fluxErr, int& status);
// XSPEC model subroutine to calculate collisional plasma with a gaussian DEM
//
// Parameters:
// param(1) = Temperature mean
// param(2) = Temperature sigma
// param(3) = nH (cm^-3) Fixed at 1 for most applications
// param(4) = He abundance
// param(5) = C "
// param(6) = N "
// param(7) = O "
// param(8) = Ne "
// param(9) = Na "
// param(10)= Mg "
// param(11)= Al "
// param(12)= Si "
// param(13)= S "
// param(14)= Ar "
// param(15)= Ca "
// param(16)= Fe "
// param(17)= Ni "
// param(18)= redshift
// param(19) = switch(0=calculate MEKAL model, 1=interpolate MEKAL model,
// 2=AtomDB model)
void vgaussDem(const RealArray& energyArray, const RealArray& params,
int spectrumNumber, RealArray& flux, RealArray& fluxErr,
const string& initString)
{
using namespace XSutility;
using namespace Numerics;
const Real Tmean = params[0];
const Real Tsigma = params[1];
// *******************************************************************
// set up arrays of temperature and DEM values
// use nT temperature steps running from -nSig sigma to +nSig sigma
int nT = 21;
int nSig = 3.0;
RealArray Tarray(nT);
RealArray demarray(nT);
Real Tmin = Tmean - nSig*Tsigma;
if ( Tmin < 0.0 ) Tmin = 0.0;
Real Tdelta = 2 * nSig * Tsigma / nT;
for (int i=0; i<nT; i++) {
Real T1 = Tmin + Tdelta * i;
Real T2 = T1 + Tdelta;
Tarray[i] = 0.5 * (T1 + T2);
demarray[i] = erf((T2-Tmean)/Tsigma) - erf((T1-Tmean)/Tsigma);
}
// end of set up arrays of temperature and DEM values
// *******************************************************************
// set up all the variables to pass to sumdem
int swtch = static_cast<int>(params[18]);
const int itype=2;
const bool qtherm = false;
const Real velocity = 0.0;
const Real density = params[2];
const Real redshift = params[17];
RealArray abundances(14);
for (size_t i=0; i<abundances.size(); i++) abundances[i] = params[i+3];
int status=0;
cxxsumdem(itype, swtch, energyArray, abundances, density, redshift, Tarray,
demarray, spectrumNumber, qtherm, velocity, flux, fluxErr, status);
if (status != 0)
{
char msg[] = "***Error returned from SUMDEM called from vgaussDem";
xs_write(msg, 10);
}
}
| true |
a87af63906fd5225ab57da8ba3392fa95c92806b | C++ | simon0987/global_router | /src/router.cpp | UTF-8 | 10,003 | 2.9375 | 3 | [] | no_license | /**************************************************************************
* File [ main.cpp ]
* Author [ wlkb83 ]
* Synopsis [ demonstration for the usage of parser.h ]
* Usage [ ./parser [inputfileName] ]
* Date [ 2014/12/28 created ]
**************************************************************************/
#include "parser.h"
#include <iostream>
#include <vector>
#include <string.h>
#include <deque>
#include <fstream>
#include <algorithm>
#include <climits>
using namespace std;
//record the edge weight
typedef struct Weight_Matrix{
pair<int, int> u;
int weight;
int d;
}weight_matrix;
//record the routing path
typedef struct Route_Matrix{
pair<int, int> v;
}route_matrix;
void dijkstra(vector< vector < pair < int, int> > >,int, int, int,int);
void check_adjacency(pair<int,int>&,weight_matrix**,int**,int**,int,int,int);
void relaxation_y(pair<int,int>&,pair<int,int>&,weight_matrix**,int**,int,int,int);
void relaxation_x(pair<int,int>&,pair<int,int>&,weight_matrix**,int**,int,int,int);
bool compare_weight(pair<int,int>&,pair<int, int>&,weight_matrix**,int**,int);
int calculate_weight(int**,pair<int,int>&,int);
void addline(weight_matrix**,route_matrix**,vector< vector<pair<int, int> > >,int,int**,int**);
void write_to_file(vector< vector< pair< int, int> > >&, weight_matrix** ,route_matrix**, int);
//queue use for BFS
deque<pair< int,int> > queue;
ofstream outfile;
int main(int argc, char **argv)
{
if( argc < 3 ){ cout << "Usage: ./parser [input_file_name] [output_file_name]" << endl; return 1; }
outfile.open(argv[2],ios::trunc);
AlgParser parser;
// read the file in the first argument
if( ! parser.read( argv[1] ) ) { return 1; }
//build grid
int h = parser.gNumHTiles(), v = parser.gNumVTiles();
//capacity
int capacity = parser.gCapacity();
//num net
int num_net = parser.gNumNets();
//use pair to store the points of the nets
pair<int, int> tmp(0,0);
vector < pair < int, int > > tmp2(2,tmp);
vector< vector< pair < int, int > > >points(num_net,tmp2);
for (int idNet = 0; idNet < parser.gNumNets(); ++idNet){
pair<int, int> posS = parser.gNetStart( idNet );
pair<int, int> posE = parser.gNetEnd( idNet );
points[idNet][0] = posS;
points[idNet][1] = posE;
// cout << idNet << " " << posS.first << " " << posS.second << " "
// << posE.first << " " << posE.second << endl;
}
dijkstra(points, h, v, num_net, capacity);
outfile.close();
return 0;
}
void dijkstra(vector< vector< pair< int, int> > > start_and_end, int horizontal, int vertical,int net_num, int capacity){
int **trace_x = new int*[horizontal];
int **trace_y = new int*[horizontal];
for(int i = 0 ; i < horizontal;i++){
trace_x[i] = new int[vertical]();
trace_y[i] = new int[vertical]();
}
//for every net num
for(int i = 0 ; i < net_num;i++){
//open up weight matrix
weight_matrix** weight = new weight_matrix*[horizontal];
route_matrix ** route = new route_matrix*[horizontal];
for(int j = 0; j < horizontal;j++){
weight[j] = new weight_matrix[vertical];
route[j] = new route_matrix[vertical];
}
//initial weight matrix
for(int j = 0 ; j < horizontal;j++){
for(int k = 0; k < vertical;k++){
weight[j][k].weight = INT_MAX;
weight[j][k].d = 0;
}
}
//set starting point for weight matrix
weight[start_and_end[i][0].first][start_and_end[i][0].second].weight = 0;
weight[start_and_end[i][0].first][start_and_end[i][0].second].u.first = start_and_end[i][0].first;
weight[start_and_end[i][0].first][start_and_end[i][0].second].u.second = start_and_end[i][0].second;
//push starting point into queue
queue.push_back(start_and_end[i][0]);
while(!queue.empty()){
pair<int,int> pre_front = queue.front();
queue.pop_front();
check_adjacency(pre_front, weight, trace_x, trace_y, capacity, horizontal, vertical);
}
addline(weight, route, start_and_end, i, trace_x, trace_y);
write_to_file(start_and_end, weight, route, i);
}
}
void check_adjacency(pair<int ,int>&check_point,weight_matrix** weight, int **trace_x,int **trace_y,int capacity,int horizontal,int vertical){
pair<int,int> up(check_point.first,check_point.second + 1);
pair<int,int> down(check_point.first,check_point.second - 1);
pair<int,int> left(check_point.first-1,check_point.second);
pair<int,int> right(check_point.first + 1,check_point.second);
//check up point out of range or not
relaxation_y(check_point, up, weight, trace_y, capacity, horizontal, vertical);
relaxation_y(check_point, down, weight, trace_y, capacity, horizontal, vertical);
relaxation_x(check_point, right, weight, trace_x, capacity, horizontal, vertical);
relaxation_x(check_point, left, weight, trace_x, capacity, horizontal, vertical);
}
void relaxation_y(pair<int ,int> &check_point,pair<int,int> &point ,weight_matrix** weight,int **trace_y,int capacity,int horizontal,int vertical){
if(point.first >= 0 && point.first < horizontal && point.second >= 0 && point.second < vertical){
if(compare_weight(check_point, point, weight, trace_y, capacity)){
//v.d = u.d + w(u,v)
weight[point.first][point.second].weight = weight[check_point.first][check_point.second].weight + calculate_weight(trace_y, point, capacity);
weight[point.first][point.second].d = weight[check_point.first][check_point.second].d + 1;
weight[point.first][point.second].u.first = check_point.first;
weight[point.first][point.second].u.second = check_point.second;
if(find(queue.begin(), queue.end(), point) == queue.end()){
queue.push_back(point);
}
}
}
}
void relaxation_x(pair<int ,int> &check_point,pair<int,int> &point ,weight_matrix** weight, int **trace_x,int capacity,int horizontal,int vertical){
if(point.first >= 0 && point.first < horizontal && point.second >= 0 && point.second < vertical){
if(compare_weight(check_point, point, weight, trace_x, capacity)){
//v.d = u.d + w(u,v)
weight[point.first][point.second].weight = weight[check_point.first][check_point.second].weight + calculate_weight(trace_x, point, capacity);
//distance + 1
weight[point.first][point.second].d = weight[check_point.first][check_point.second].d + 1;
//adjust the previous node
weight[point.first][point.second].u.first = check_point.first;
weight[point.first][point.second].u.second = check_point.second;
if(find(queue.begin(), queue.end(), point) == queue.end()){
queue.push_back(point);
}
}
}
}
bool compare_weight(pair<int,int>& curr_point,pair<int, int>&next_point,weight_matrix **weight,int**trace_route,int capacity){
bool result = false;
// if v.d > u.d + w(u,v)
if(weight[next_point.first][next_point.second].weight > weight[curr_point.first][curr_point.second].weight + calculate_weight(trace_route, next_point, capacity)){
result = true;
}
return result;
}
int calculate_weight(int **trace_route,pair<int,int> &point,int capacity){
int weight = 1;
int demand = trace_route[point.first][point.second];
if(demand!=0){
weight = 2^demand;
if(demand >= capacity)
weight = 999;
}
return weight;
}
void addline(weight_matrix** w,route_matrix** r,vector< vector<pair<int, int> > > start_and_end,int i,int** trace_x,int** trace_y){
pair<int,int> previous;
pair<int,int> diff;
int end_x = start_and_end[i][1].first;
int end_y = start_and_end[i][1].second;
r[end_x][end_y].v.first = end_x;
r[end_x][end_y].v.second = end_y;
//traverse from the end point to the start point
while(end_x != start_and_end[i][0].first || end_y!= start_and_end[i][0].second){
previous.first = w[end_x][end_y].u.first;
previous.second = w[end_x][end_y].u.second;
diff.first = previous.first - end_x;
diff.second = previous.second - end_y;
//last line is vertical
if(diff.first == 0){
trace_y[end_x][end_y]++;
}
//last line is horizontal
else if(diff.second == 0){
trace_x[end_x][end_y]++;
}
//set the routing table
r[previous.first][previous.second].v.first = end_x;
r[previous.first][previous.second].v.second = end_y;
end_x = previous.first;
end_y = previous.second;
}
}
void write_to_file(vector< vector< pair< int, int> > >&start_and_end,weight_matrix** w, route_matrix** r, int i){
outfile << i << " " << w[start_and_end[i][1].first][start_and_end[i][1].second].d << endl;
// c:checking point n:next point
pair<int, int> check_point = start_and_end[i][0];
pair<int, int> next_point;
while( check_point.first != start_and_end[i][1].first|| check_point.second != start_and_end[i][1].second)
{
outfile << check_point.first << " " << check_point.second << " ";
next_point.first= r[check_point.first][check_point.second].v.first;
next_point.second = r[check_point.first][check_point.second].v.second;
outfile << next_point.first << " " << next_point.second << endl;
check_point.first = next_point.first;
check_point.second= next_point.second;
}
}
| true |
b2a79ba1a3e0d745b7de81e1b932a8c1fadc6e4a | C++ | Dyzing/Composition-images | /Composition-images/Composition-images/corona.cpp | UTF-8 | 4,915 | 2.671875 | 3 | [] | no_license | #include "Initialisation-Conversion.hpp"
#include "Filtres.hpp"
#include "Masques.hpp"
#include <windows.h>
#include <tuple>
#include<vector>
#include <numeric>
#include "corona.hpp"
int tolerance = 0;
int main(int argc, char* argv[])
{
std::cout << std::endl << "---------------------" << std::endl << "Initialisation du Programme" << std::endl << "---------------------" << std::endl;
Image* tabImage;
std::list<std::string> files;
std::string fading = "";
int overlaps = -1, distances = -1;
bool parDefaut = true;
std::string jpeg = argv[argc - 1];
getParams(argc, argv, files, fading, overlaps, distances, parDefaut);
int nbFichiers = files.size();
std::cout << "Parametres recuperes, Nombre de fichiers a traiter : " << nbFichiers << std::endl << "Option Fading : " << fading << std::endl << "Option Overlap : " << overlaps << std::endl << "Option Distance : " << distances << std::endl << "Option Tolerance : " << tolerance << std::endl;
tabImage = initImage(files); // Tableau comportant la liste d'images passe en parametres
int width = tabImage[0].getWidth(); //Largeur
int height = tabImage[0].getHeight(); //Hauteur
std::cout << "---------------------" << std::endl << "Creation de l'image de fond sans les sujets en cours" << std::endl << "---------------------" << std::endl;
Pixels** Mediane = median_images(tabImage, nbFichiers,width,height); //Application de la mediane
Pixels** MedianewithBlur = FlouGaussien(Mediane, width, height); // Mediane avec le flou Gaussien applique
std::cout << "---------------------" << std::endl << "Creation de l'image de fond sans les sujets Termine" << std::endl << "---------------------" << std::endl;
Image MedianeImg(width, height);
MedianeImg.setTabPixels(Mediane);
MedianeImg.setName("../Photos/Mediane.jpg");
MedianeImg.saveImg();
Image MedianeWithBlurImg(width, height);
MedianeWithBlurImg.setTabPixels(MedianewithBlur);
MedianeWithBlurImg.setName("../Photos/MedianeWithBlur.jpg");
MedianeWithBlurImg.saveImg();
std::cout << "---------------------" << std::endl << "Extraction des sujets" << std::endl << "---------------------" << std::endl;
std::cout << "---------------------" << std::endl << "Application des filtres pour le rendu final" << std::endl << "---------------------" << std::endl;
//fading
if (fading == "opaque" ) {
std::cout << "---------------------" << std::endl << "Application du filtre opaque" << std::endl << "---------------------" << std::endl;
Pixels** MedianeAndMasque = MultiMasque(MedianewithBlur, tabImage, nbFichiers, Mediane, width, height);
Image MasqueAppliquer(width,height, jpeg);
MasqueAppliquer.setTabPixels(MedianeAndMasque);
MasqueAppliquer.saveImg();
}
if (fading == "plus") {
std::cout << "---------------------" << std::endl << "Application du filtre plus" << std::endl << "---------------------" << std::endl;
Image fading_jpeg_front(width, height, jpeg);
fading_jpeg_front.setTabPixels(Fading_front(tabImage, Mediane, nbFichiers, width, height));
fading_jpeg_front.saveImg();
}
if (fading == "moins") {
std::cout << "---------------------" << std::endl << "Application du filtre moins" << std::endl << "---------------------" << std::endl;
Image fading_jpeg_back(width, height, jpeg);
fading_jpeg_back.setTabPixels(Fading_back(tabImage, Mediane, nbFichiers, width, height));
fading_jpeg_back.saveImg();
}
if (overlaps > -1) {
std::cout << "---------------------" << std::endl << "Application du Overlap" << std::endl << "---------------------" << std::endl;
Image overleapJPG(width, height, jpeg);
Pixels** overleapTab = overlap(MedianewithBlur, tabImage, nbFichiers, Mediane, width, height, overlaps);
overleapJPG.setTabPixels(overleapTab);
overleapJPG.saveImg();
}
if (distances != -1) {
std::cout << "---------------------" << std::endl << "Application de la distance" << std::endl << "---------------------" << std::endl;
Image dist(width, height, jpeg);
dist.setTabPixels(distance(MedianewithBlur, tabImage, nbFichiers, Mediane, width, height, distances));
dist.saveImg();
}
if (parDefaut == true) {
std::cout << "---------------------" << std::endl << "Insertion des masques par defaut" << std::endl << "---------------------" << std::endl;
Pixels** MedianeAndMasque = MultiMasque(MedianewithBlur, tabImage, nbFichiers, Mediane, width, height);
Image MasqueAppliquer(width, height, jpeg);
MasqueAppliquer.setTabPixels(MedianeAndMasque);
MasqueAppliquer.saveImg();
}
std::cout << "---------------------" << std::endl << "Integration sur l'image de fond terminer" << std::endl << "---------------------" << std::endl;
std::cout << "---------------------" << std::endl << "Programme termine" << std::endl << "---------------------" << std::endl;
std::cout << "---------------------" << std::endl << "Made by Cedric Chopin / Guillaume Trem / Etienne Gibiat" << std::endl << "---------------------" << std::endl;
} | true |
2f8b42eba303c6a33a9cea101dabaa87f4aa8bce | C++ | institution/nn5 | /src/ext/fail.hpp | UTF-8 | 817 | 2.78125 | 3 | [] | no_license | #pragma once
#include <stdlib.h>
#include <cassert>
#include "format.hpp"
namespace ext{
extern bool FAIL_THROWS;
template <class... Args>
[[noreturn]]
void fail(char const* fmt, Args... args) {
print(stderr, fmt, args...);
if (FAIL_THROWS) {
throw std::exception();
}
else {
assert(0);
exit(-1);
}
//exit(-1);
}
[[noreturn]]
inline void fail(char const* fmt) {
// use printf so we can use this to report errors in print/string library
std::fputs(fmt , stderr);
if (FAIL_THROWS) {
throw std::exception();
}
else {
assert(0);
exit(-1);
}
//exit(-1);
}
[[noreturn]]
inline void fail() {
//print(stderr, fmt, args...);
if (FAIL_THROWS) {
throw std::exception();
}
else {
assert(0);
exit(-1);
}
//exit(-1);
}
}
| true |
ce83401596055c8b964628eec5fe38ea62d3b48c | C++ | lonelam/SolveSet | /cf853C.cpp | UTF-8 | 2,265 | 2.640625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int inf = 0x3f3f3f3f;
const int maxn = 200000 + 100;
struct node
{
int L, R;
int l, r;
int val;
node() : L(-1), R(-1), l(-1), r(-1), val(0) {}
node (int _l, int _r) : L(-1), R(-1),l(_l), r(_r), val(0) {}
};
const int S = (int) 7e6;
node tree[S];
int tot;
//range : left inclusive right exclusive
int build(int l, int r)
{
int v = tot++;
tree[v] = node(l, r);
//leaf
if (l + 1 == r) return v;
//get child range
int mid = (l + r) / 2;
//restore children
tree[v].L = build(l, mid);
tree[v].R = build(mid, r);
return v;
}
int setVal(int v, int p, int x)
{
//not in the chain
if (p < tree[v].l || tree[v].r <= p) return v;
//new node
int u = tot++;
tree[u] = tree[v];
//leaf
if (tree[v].L == -1)
{
tree[u].val = x;
return u;
}
tree[u].L = setVal(tree[v].L, p, x);
tree[u].R = setVal(tree[v].R, p, x);
//sum
tree[u].val = tree[tree[u].L].val + tree[tree[u].R].val;
return u;
}
int getSum(int v, int l, int r)
{
//in range
if (l <= tree[v].l && tree[v].r <= r)
{
return tree[v].val;
}
//out of range
if (l >= tree[v].r || tree[v].l >= r)
{
return 0;
}
return getSum(tree[v].L, l, r) + getSum(tree[v].R, l, r);
}
//the only difference between cols is a chain
int roots[maxn];
int n, q;
int main()
{
scanf("%d%d", &n, &q);
roots[0] = build(0, n);
for (int i = 0; i < n; i++)
{
int p;
scanf("%d", &p);
p--;
// no two marked squares share the same row or the same col
roots[i+1] = setVal(roots[i], p, 1);
}
while(q--)
{
int x1, x2, y1, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
x1--;
y1--;
ll ans = (ll)n * (n - 1);
ans -= (ll)x1 * (x1 - 1);
ans -= (ll) y1 * (y1 - 1);
ans -= (ll) (n - x2 - 1) * (n - x2);
ans -= (ll) (n - y2 - 1) * (n - y2);
ll cnt = getSum(roots[x1], 0, y1);
ans += cnt *( cnt - 1);
cnt = getSum(roots[x1], y2, n);
ans += cnt *( cnt - 1);
cnt = y1 - getSum(roots[x2], 0, y1);
ans += cnt *( cnt - 1);
cnt = (n - y2) - getSum(roots[x2], y2, n);
ans += cnt *( cnt - 1);
printf("%lld\n", ans / 2LL);
}
}
| true |
2020e652d5d35e5fa7d5bd6c0f0be4bac5d6fd46 | C++ | asibatian/CS205 | /Assignment4/main.cpp | UTF-8 | 644 | 3.1875 | 3 | [] | no_license | //main.cpp
#include <iostream>
#include "matrix.hpp"
using namespace std;
int main()
{
float a[6]={1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f};
float b[6]={1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
Matrix A = Matrix(2, 3, a);
Matrix B = Matrix(3, 2, b);
Matrix C = A*B;
cout << "Matrix C = " << C << endl;
Matrix D = 2*A;
cout << "Matrix D = " << D << endl;
Matrix E = A*3;
cout << "Matrix E = " << E << endl;
Matrix F = Matrix(2, 3, a);
Matrix G = Matrix(2, 3, b);
Matrix H = (F+G);
cout << "Matrix H = " << H << endl;
Matrix I = (F-G);
cout << "Matrix I = " << I << endl;
return 0;
} | true |
a4e056c354ee399c24dfde28af620bf336886e8c | C++ | qiuqingyun/shuffle | /src/Mod_p.h | UTF-8 | 2,045 | 3.015625 | 3 | [] | no_license | #ifndef MOD_P_H_
#define MOD_P_H_
#include "G_mem.h"
#include <NTL/ZZ.h>
NTL_CLIENT
class Mod_p : public G_mem {
private:
ZZ val; //Value of the element
ZZ mod; //Modular value
public:
//Constructors and destructor
Mod_p();
Mod_p(long p);
Mod_p(ZZ p);
Mod_p(long v, long p);
Mod_p(ZZ v, long p);
Mod_p(long v, ZZ p);
Mod_p(ZZ v, ZZ p);
virtual ~Mod_p();
//Functions to change parameters
void set_mod(long p);
void set_mod(ZZ p);
void set_val(long v);
void set_val(ZZ v);
//Access to the parameters
ZZ get_mod() const;
ZZ get_val() const;
//operators
void operator =(const Mod_p& el);
Mod_p operator +(const Mod_p& el) const;
Mod_p operator -(const Mod_p& el) const;
Mod_p operator +() const;
Mod_p operator -() const;
Mod_p operator *(const Mod_p& b) const;
Mod_p operator /(const Mod_p& b) const;
Mod_p& operator ++();
Mod_p operator ++(int);
Mod_p& operator --();
Mod_p operator --(int);
bool operator ==(const Mod_p& b) const;
bool operator !=(const Mod_p& b) const;
bool operator <(const Mod_p& b) const;
bool operator >(const Mod_p& b) const;
bool operator <=(const Mod_p& b) const;
bool operator >=(const Mod_p& b) const;
Mod_p& operator +=(const Mod_p& b);
Mod_p& operator -=(const Mod_p& b);
Mod_p& operator *=(const Mod_p& b);
Mod_p& operator /=(const Mod_p& b);
void toModP(string s);
friend ostream& operator<<(ostream& os, const Mod_p& b);
friend istream& operator>>(istream& is, Mod_p& b);
//Returns the inverse of an element
Mod_p inv();
static Mod_p inv(const Mod_p& el);
static void inv(Mod_p& a, const Mod_p& el);
//multiplication and exponentiation functions
static void mult(Mod_p& a, const Mod_p& b, const Mod_p& c);
Mod_p expo(const long e);
Mod_p expo(const ZZ e);
static void expo(Mod_p& a, const Mod_p& b, const long e);
static void expo(Mod_p& a, const Mod_p& b, const ZZ e);
static Mod_p expo(Mod_p& a, long e);
static Mod_p expo(Mod_p& a, ZZ e);
};
#endif /* MOD_P_H_ */
| true |