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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
053fc3ffd63fc144bb56282996fab112cc691fc1 | C++ | hasiek/IVsem | /OJP/Tekstowa/Goal.h | UTF-8 | 242 | 2.625 | 3 | [] | no_license | #pragma once
class CGoal {
int x;
int y;
int side;
public:
CGoal();
CGoal(int x1, int y1, int side1);
void set_x(int x1);
void set_y(int y1);
void set_side(int side1);
int get_x();
int get_y();
int get_side();
~CGoal();
};
| true |
3f39e61068fabbe16fb73bbd61e0d99a25328826 | C++ | abhishekchandra2522k/CPPrograms | /Basic/perfect_number.cpp | UTF-8 | 544 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
// A perfect number is one whose sum of divisors is equal to the number itself
class Solution
{
public:
bool isPerfect(int n)
{
int sum = 1;
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (sum == n)
{
return true;
}
return false;
}
};
int main()
{
int n;
cin >> n;
Solution ob;
cout << ob.isPerfect(n) << endl;
return 0;
} | true |
daa55beb6ab0f9d6417ef93b5aaadc5b87438d12 | C++ | Kozoriz/PointClasteringTool | /src/Model/Common/ValueStamp.h | UTF-8 | 509 | 2.734375 | 3 | [] | no_license | #ifndef __VALUESTAMP__
#define __VALUESTAMP__
#include "utils/containers/string.h"
#include "utils/date_time.h"
#include "utils/containers/converters.h"
class ValueStamp
{
public:
enum class ValueType
{
CPU,
RAM,
IO_READ,
IO_WRITE
};
public:
utils::String ToString() const { return utils::date_time::GetDateTimeString("%F_%T", m_time) + " " + utils::ConvertToString(m_value); }
public:
double m_value;
std::chrono::system_clock::time_point m_time;
};
#endif // __VALUESTAMP__
| true |
7d64a7865b906312c3fa72f4c056285112068ce1 | C++ | Olney-James/CISS242 | /Employee/Employee/Employee.h | UTF-8 | 532 | 3.125 | 3 | [] | no_license | #ifndef EMPLOYEE_H
#define EMPLOYEE_H
#pragma once
#include <string>
#include <iostream>
using namespace std;
//Employee class declaration
class Employee {
public:
Employee(string n, int i, string d, string p) {
name = n;
idNumber = i;
department = d;
position = p;
}
Employee(string n, int i) {
name = n;
idNumber = i;
}
Employee() {
}
string name;
int idNumber;
string department;
string position;
void displayEmployee(Employee* const e);
void printElement(const string& s, const int& width);
};
#endif | true |
a4158b5b51c51abe446d9b549828c3ad6626202f | C++ | Ser123rus/AIP_semest2_homework_ANTONIUKss | /week14,15/week14,15_1(а)/Source.cpp | UTF-8 | 223 | 2.671875 | 3 | [] | no_license | #include <iostream>
int main() {
int masiv[101];
for (int i = 0; i < 101; i++) {
masiv[i] = rand() % 11;
}
for (int i = 0; i < 101 - 1; i++)
std::cout << i << " - " << masiv[i] << ", " << std::endl;
return 0;
} | true |
a4c8ad3b8c20eb66082aa3f0bd39afbe96ba4d87 | C++ | iitalics/Synth | /SynthManager.cpp | UTF-8 | 873 | 2.6875 | 3 | [] | no_license | #include "includes.h"
#include "Part.h"
#include "SynthManager.h"
SynthManager::SynthManager ()
{
parts.clear();
Time = 0;
}
SynthManager::~SynthManager ()
{
for (std::vector<Part*>::iterator i = parts.begin(); i != parts.end(); i++)
delete *i;
}
void SynthManager::AddPart (Part* part)
{
part->Manager = this;
parts.push_back(part);
}
Part* SynthManager::GetPart (std::string name)
{
for (std::vector<Part*>::iterator i = parts.begin(); i != parts.end(); i++)
if ((*i)->Name == name)
return *i;
return NULL;
}
void SynthManager::GetOutput (float* left, float* right)
{
*left = *right = 0;
for (std::vector<Part*>::iterator i = parts.begin(); i != parts.end(); i++)
{
(*i)->Update();
if ((*i)->GeneratesSound)
{
SoundPart* soundPart = (SoundPart*)*i;
*left = soundPart->OutputLeft();
*right = soundPart->OutputRight();
}
}
}
| true |
6f89588005198fdf402e151d0f7df9111bdfaa4e | C++ | Sunday361/leetcode | /leetcode_73.h | UTF-8 | 1,774 | 3.40625 | 3 | [] | no_license | //
// Created by panrenhua on 1/21/21.
//
#ifndef LEETCODE_LEETCODE_73_H
#define LEETCODE_LEETCODE_73_H
#include "allheaders.h"
/** 73. 矩阵置零
* 矩阵置零 将 [i, j] 所在的行列的头置为0, 随后扫描第一行和第一列
* 注意特殊点 [0, 0] 即 i = 0 或 j = 0 时 需要额外考虑
* */
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int c = 0, r = 0;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == 0 && i > 0 && j > 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}else if (matrix[i][j] == 0 && i == 0 && j > 0) {
r = 1;
matrix[0][j] = 0;
}else if (matrix[i][j] == 0 && j == 0 && i > 0) {
c = 1;
matrix[i][0] = 0;
}else if (matrix[i][j] == 0) {
c = r = 1;
}
}
}
for (int i = 1; i < matrix.size(); i++) {
if (matrix[i][0] == 0) {
for (auto& n : matrix[i]) {
n = 0;
}
}
}
for (int i = 1; i < matrix[0].size(); i++) {
if (matrix[0][i] == 0) {
for (int j = 0; j < matrix.size(); j++) {
matrix[j][i] = 0;
}
}
}
if (c) {
for (int i = 0; i < matrix.size(); i++) {
matrix[i][0] = 0;
}
}
if (r) {
for (int i = 0; i < matrix[0].size(); i++) {
matrix[0][i] = 0;
}
}
}
};
#endif //LEETCODE_LEETCODE_73_H
| true |
822ece9566f158df2078c89cfcaaa2dc73556b26 | C++ | geeooleea/palestradialgoritmi2018 | /intro-day1/soluzioni/easy2.cc | UTF-8 | 259 | 2.609375 | 3 | [] | no_license | #include<fstream>
using namespace std;
int main() {
ifstream in("input.txt");
ofstream fout("output.txt");
int N, a, b, out=-1;
in>>N;
for(int i=0;i<N;i++) {
in>>a>>b;
a+=b;
if(a%2==0) out=max(out, a);
}
fout<<out;
in.close();
fout.close();
}
| true |
7df70187363bfba25c96fc50094bb35ce2cc8777 | C++ | europaplus/CPP_modules | /CppModule03/ex04/ClapTrap.hpp | UTF-8 | 2,616 | 2.796875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: knfonda <knfonda@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/22 14:14:32 by knfonda #+# #+# */
/* Updated: 2021/03/22 15:38:17 by knfonda ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CLAPTRAP_H
# define CLAPTRAP_H
# include <iostream>
# include <string>
class ClapTrap{
protected:
unsigned int _hitPoint;
unsigned int _maxHitPoint;
unsigned int _energyPoints;
unsigned int _maxEnergyPoints;
unsigned int _level;
unsigned int _meleeAttackDamage;
unsigned int _rangedAttackDamage;
unsigned int _armorDamageReduction;
std::string _name;
public:
ClapTrap();
ClapTrap(
unsigned int hitPoint,
unsigned int maxHitPoint,
unsigned int energyPoints,
unsigned int maxEnergyPoints,
unsigned int level,
unsigned int meleeAttackDamage,
unsigned int rangedAttackDamage,
unsigned int armorDamageReduction,
std::string name);
ClapTrap(const ClapTrap ©);
~ClapTrap();
ClapTrap &operator=(const ClapTrap &ClapTrap);
void rangedAttack(std::string const &target);
void meleeAttack(std::string const &target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
std::string &getName();
unsigned int getHitPoint();
unsigned int getMaxHitPoint();
unsigned int getEnergyPoints();
unsigned int getMaxEnergyPoints();
unsigned int getLevel();
unsigned int getMeleeAttackDamage();
unsigned int getRangedAttackDamage();
unsigned int getArmorDamageReduction();
void setName(std::string name);
void setHitPoint(unsigned int hitPoint);
void setMaxHitPoint(unsigned int maxHitPoint);
void setEnergyPoints(unsigned int energyPoints);
void setMaxEnergyPoints(unsigned int maxEnergyPoints);
void setLevel(unsigned int level);
void setMeleeAttackDamage(unsigned int meleeAttackDamage);
void setRangedAttackDamage(unsigned int rangedAttackDamage);
void setArmorDamageReduction(unsigned int armorDamageReduction);
};
#endif
| true |
b53297d05d6fdfeeef01e03b344253fff303651a | C++ | jbsilva/Programming_Challenges | /URI/01133-resto_da_divisao.cpp | UTF-8 | 807 | 2.59375 | 3 | [] | no_license | // ============================================================================
//
// Filename: 01133-resto_da_divisao.cpp
//
// Description: URI 1133 - Resto da Divisão
//
// Version: 1.0
// Created: 09/30/2012 03:22:18 PM
// Revision: none
// Compiler: g++
//
// Author: Julio Batista Silva (351202), julio(at)juliobs.com
// Company: UFSCar
//
// ============================================================================
#include <cstdio>
int main()
{
int n1, n2, min, max;
scanf("%d %d", &n1, &n2);
if (n1 > n2)
{
max = n1;
min = n2;
}
else
{
max = n2;
min = n1;
}
for (int i = min + 1; i < max; i++)
if (i % 5 == 2 || i % 5 == 3)
printf("%d\n", i);
return 0;
}
| true |
e5f2551ccd3dc617a003b9b17f0cd144195b8579 | C++ | hyperion-project/hyperion.ng | /include/utils/FileUtils.h | UTF-8 | 2,141 | 2.6875 | 3 | [
"MIT",
"GPL-1.0-or-later",
"MPL-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-protobuf",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"OFL-1.1",
"GPL-2.0-only",
"Apache-2.0",
"Hippocratic-2.1",
"BSD-2-Clause",
"GPL-2.0-or-later",
"LicenseRef-scancode-hidapi"
] | permissive | #pragma once
// qt includes
#include <QFile>
#include <QString>
#include <QByteArray>
// util includes
#include "Logger.h"
namespace FileUtils {
QString getBaseName(const QString& sourceFile);
QString getDirName(const QString& sourceFile);
///
/// @brief remove directory recursive given by path
/// @param[in] path Path to directory
bool removeDir(const QString& path, Logger* log);
///
/// @brief check if the file exists
/// @param[in] path The file path to check
/// @param[in] log The logger of the caller to print errors
/// @param[in] ignError Ignore errors during file read (no log output)
/// @return true on success else false
///
bool fileExists(const QString& path, Logger* log, bool ignError=false);
///
/// @brief read a file given by path.
/// @param[in] path The file path to read
/// @param[out] data The read data o success
/// @param[in] log The logger of the caller to print errors
/// @param[in] ignError Ignore errors during file read (no log output)
/// @return true on success else false
///
bool readFile(const QString& path, QString& data, Logger* log, bool ignError=false);
///
/// write a file given by path.
/// @param[in] path The file path to read
/// @param[in] data The data to write
/// @param[in] log The logger of the caller to print errors
/// @return true on success else false
///
bool writeFile(const QString& path, const QByteArray& data, Logger* log);
///
/// @brief delete a file by given path
/// @param[in] path The file path to delete
/// @param[in] log The logger of the caller to print errors
/// @param[in] ignError Ignore errors during file delete (no log output)
/// @return true on success else false
///
bool removeFile(const QString& path, Logger* log, bool ignError=false);
///
/// @brief resolve the file error and print a message
/// @param[in] file The file which caused the error
/// @param[in] log The logger of the caller
///
void resolveFileError(const QFile& file, Logger* log);
}
| true |
7dcc4c8afb05c08d977a5ea9b1f24fc748989142 | C++ | Roy-kunal-96/Cpp_code_tutorial | /OPoverload2.cpp | UTF-8 | 592 | 3.609375 | 4 | [] | no_license | // Operator overloading
#include<iostream>
using namespace std;
class complex
{
int real;
int img;
public:
int set_val(int x,int y)
{
real=x;
img=y;
}
void display()
{
cout<<"complex no: "<<real<<" + "<<img<<"j"<<endl;
}
complex operator -()
{
complex temp;
temp.real=-real;
temp.img=-img;
return (temp);
}
};
int main()
{
complex c1,c2;
c1.set_val(5,6);
c1.display();
c2=-c1 ; //c2=c1.operator-();
c2.display();
return 0;
}
| true |
a09b7c59eea5de09eb894cd7fc7c4e03b687b357 | C++ | Michal-Fularz/ProjectEuler | /ProjectEuler/Problems_other.cpp | UTF-8 | 3,105 | 3.078125 | 3 | [
"MIT"
] | permissive | #include "ProjectEuler.h"
#include <iostream>
#include <list>
#include <vector>
#include <set>
#include <algorithm>
#include <numeric>
#include <functional>
#include <string>
#include "SupportFunctions.h"
using std::cout;
using std::cin;
using std::endl;
/*
St. Petersburg Lottery
Problem 499
A gambler decides to participate in a special lottery. In this lottery the gambler plays a series of one or more games.
Each game costs m pounds to play and starts with an initial pot of 1 pound. The gambler flips an unbiased coin. Every time a head appears, the pot is doubled and the gambler continues. When a tail appears, the game ends and the gambler collects the current value of the pot. The gambler is certain to win at least 1 pound, the starting value of the pot, at the cost of m pounds, the initial fee.
The gambler cannot continue to play if his fortune falls below m pounds.
Let pm(s) denote the probability that the gambler will never run out of money in this lottery given his initial fortune s and the cost per game m.
For example p2(2) ≈ 0.2522, p2(5) ≈ 0.6873 and p6(10 000) ≈ 0.9952 (note: pm(s) = 0 for s < m).
Find p15(109) and give your answer rounded to 7 decimal places behind the decimal point in the form 0.abcdefg.
*/
void Problem_499(void)
{
}
/*
Eight Divisors
Problem 501
The eight divisors of 24 are 1, 2, 3, 4, 6, 8, 12 and 24.
The ten numbers not exceeding 100 having exactly eight divisors are 24, 30, 40, 42, 54, 56, 66, 70, 78 and 88.
Let f(n) be the count of numbers not exceeding n with exactly eight divisors.
You are given f(100) = 10, f(1000) = 180 and f(10^6) = 224427.
Find f(10^12).
*/
void Problem_500(void)
{
// bruteforce solution is probably not an option
// 24: 1 * 2 * 3 * 4 * 6 * 8 * 12 * 24: 2*2*2*3
// 30: 1 * 2 * 3 * 5 * 6 * 10 * 15 * 30: 2*3*5
// 40: 1 * 2 * 4 * 5 * 8 * 10 * 20 * 40: 2*2*2*5
// 42: 1 * 2 * 3 * 6 * 7 * 14 * 21 * 42: 2*3*7
// 54: 1 * 2 * 3 * 6 * 9 * 18 * 27 * 54: 2*3*3*3
// 56: 1 * 2 *
// 66: 1 * 2 *
// 70: 1 * 2 * 5 * 7 * 10 * 14 * 35 * 70: 2*5*7
// 78: 1 * 2 *
// 88: 1 * 2 *
// ...
// 104: 1 * 2 * 3 * 6 * 17 * 34 * 51 * 104: 2*3*17
// ...
// 128: 1 * 2 * 4 * 8 * 16 * 32 * 64 * 128: 2*2*2*2*2*2*2
// ...
// 2187: 1 * 3 * 9 * 27 * 81 * 243 * 729 * 2187: 3*3*3*3*3*3*3
// solution:
// prepare the list of prime numbers and then:
// find all 7-elemnets: n*n*n*n*n*n*n
// fina all 4-elements: n*n*n*m
// find all 3-elements: n*m*o
// that are less than 10^12
// where n, m, o are prime numbers
// add sieve of Erastothenes for prime numbers generation (with static vector of prime numbers and static flag that checks if it was already invoked)
// or create appropriate class
int64_t upperBound = 1000;
int countOfNumbers = 0;
int64_t maxPrimeNumberRequired = upperBound / (2 * 3); // because 2*3*prime_number < upperBound
// idea:
// the for loop is not required - it is enough to find the largest prime_number for each triplet - then all lesser prime numbers can also be counted for that triplet
// eg. we have to find prime number that is closest to upperBound/(2*3)
} | true |
25162cf2d6e88bab879107711d24f58e733fe36c | C++ | SiYa2020/T-Watch-Projects | /7 T-Watch TFT_eSPI + LVGL/src/main.cpp | UTF-8 | 4,233 | 2.5625 | 3 | [
"MIT"
] | permissive | /* Switch between TFT_eSPI and LVGL screen on a TTGO T-Watch
* Landing page is created with TFT_eSPI library
* Arduino IDE or PlatformIO
*
* Step by step tutorials
* https://diyprojects.io/ttgo-t-watch-mix-lvgl-tft_espi-libraries-same-esp32-project/
* https://projetsdiy.fr/ttgo-t-watch-mixer-librairies-lvgl-tft_espi-projet-esp32/
* Licence : see licence file
* /
/* Arduino IDE - uncomment your watch */
//#define LILYGO_WATCH_2019_WITH_TOUCH
//#define LILYGO_WATCH_2019_NO_TOUCH
//#define LILYGO_WATCH_BLOCK
//#define LILYGO_WATCH_2020_V1
// Arduino IDE - uncomment to activate LVGL library
//#define LILYGO_WATCH_LVGL
/* PlatformIO -> Select your watch in platformio.ini file */
#include <Arduino.h>
#include <LilyGoWatch.h>
// Declare background image | Déclare l'image de fond
LV_IMG_DECLARE(WALLPAPER_1_IMG);
/**************************/
/* Static variables */
/**************************/
TTGOClass *ttgo = nullptr;
static lv_obj_t *lvglpage = NULL;
bool KeyPressed = false;
/**************************/
/* STATIC PROTOTYPES */
/**************************/
bool gotoLVGLPage();
static void event_handler(lv_obj_t * obj, lv_event_t event);
void buildTFTPage();
/**************************/
void setup() {
Serial.begin(115200);
ttgo = TTGOClass::getWatch();
// Initialize the hardware
ttgo->begin();
ttgo->lvgl_begin();
// Turn on the backlight | Allume le rétro-éclairage
ttgo->openBL();
// Build landing page | créé la page principale
buildTFTPage();
}
void loop() {
int16_t x, y;
if (ttgo->getTouch(x, y)) {
while (ttgo->getTouch(x, y)) {} // wait for user to release
if ( gotoLVGLPage() ) buildTFTPage();
}
}
void buildTFTPage(){
TFT_eSPI *tft = ttgo->tft;
tft->fillScreen(TFT_BLACK);
tft->setTextSize(2);
tft->setTextColor(TFT_WHITE);
tft->drawString("TFT_eSPI Screen", 0,0);
// Toucher l'écran pour sortir
tft->drawString("Touch screen to open LVGL page", 0,20);
}
// Create a screen with LVGL library | Créé un écran avec la librairie LVGL
bool gotoLVGLPage(){
KeyPressed = false;
// Container that contain all displayed elements. Makes it easier to show or hide the page
// Conteneur qui contient tous les élements affiché. Permet d'afficher ou masquer plus facilement la page
lvglpage = lv_cont_create( lv_scr_act(), NULL );
lv_obj_set_width( lvglpage, lv_disp_get_hor_res( NULL ) ); // Horizontal resolution | résolution horizontale
lv_obj_set_height( lvglpage, lv_disp_get_ver_res( NULL ) ); // Vertical resolution | résolution verticale
// Background Image | Image de fond
lv_obj_t * img1 = lv_img_create(lvglpage, NULL);
lv_img_set_src(img1, &WALLPAPER_1_IMG);
lv_obj_align(img1, NULL, LV_ALIGN_CENTER, 0, 0);
// Button in center of the screen | Bouton au centre de l'écran
lv_obj_t * btn1 = lv_btn_create(lvglpage, NULL);
lv_obj_set_event_cb(btn1, event_handler);
lv_obj_align(btn1, NULL, LV_ALIGN_CENTER, 0, 0);
// Display a circuar scrolling welcome message
// Affiche un message défilant de bienvenue
lv_obj_t * welcomemessage;
welcomemessage = lv_label_create(lvglpage, NULL);
lv_label_set_long_mode(welcomemessage, LV_LABEL_LONG_SROLL_CIRC); /*Circular scroll*/
lv_obj_set_width(welcomemessage, lv_disp_get_hor_res( NULL ));
lv_label_set_text(welcomemessage, "Welcome on LVGL Demo Screen for TTGO T-Wach");
lv_obj_align(welcomemessage, btn1, LV_ALIGN_CENTER, 0, -60);
// Button label | libellé du bouton
lv_obj_t * label;
label = lv_label_create(btn1, NULL);
lv_label_set_text(label, "Exit");
while (!KeyPressed) {lv_task_handler(); delay(20);} // Wait for touch
Serial.print("Exit LVGL page");
lv_obj_del(lvglpage);
return true;
}
// Switch screen button handler | Déclencheur du bouton pour passer d'un écran LVGL à TFT_eSPI
static void event_handler(lv_obj_t * obj, lv_event_t event){
// Important !! always test event to avoid multiple signals
// Il faut toujours tester l'évènement sinon plusieurs signaux sont envoyés dans la queue ce qui entraîne l'affichage de plusieurs écrans TFT_eSPI
if (event == LV_EVENT_CLICKED) {
Serial.println("event_handler => return main page");
KeyPressed = true;
}
}
| true |
1286eee282546816f736bec1b8fac8c06887c479 | C++ | Loflif/alpha-tankett | /tankett-server/source/serverEntityManager.cpp | UTF-8 | 5,922 | 2.75 | 3 | [] | no_license | #include "serverEntityManager.h"
namespace tankett {
serverEntityManager::serverEntityManager() {
createLevel();
createBulletBuffer();
createTankBuffer();
}
serverEntityManager::~serverEntityManager() {
}
void serverEntityManager::parseClientMessage(message_client_to_server message, uint8 clientID, const time& pDeltaRecieveTime) {
if (message.get_input(message_client_to_server::SHOOT)) {
fireBullet(tanks_[clientID]);
}
vector2 targetDirection = targetMoveDirection(message);
if (targetDirection.x_ != 0
&& targetDirection.y_ != 0) {
int i = 0;
}
float speed = 4 * pDeltaRecieveTime.as_seconds();
tanks_[clientID]->SetPosition(tanks_[clientID]->transform_.position_ + targetDirection * speed);
tanks_[clientID]->turretRotation_ = message.turret_angle;
}
void serverEntityManager::addEntity(IServerEntity& pEntity) {
entities_.push_back(&pEntity);
}
serverTank* serverEntityManager::getTank(int ID) {
return tanks_[ID];
}
void serverEntityManager::spawnTank(int id) {
tanks_[id]->SetPosition(SPAWN_POINTS[id]);
}
void serverEntityManager::update(time dt) {
for(IServerEntity* e : entities_) {
if(e->isEnabled) {
e->update(dt);
}
}
respawnTanks(dt);
}
void serverEntityManager::respawnTanks(time dt) {
for (serverTank* t : tanks_) {
if (!t->isAlive) {
t->respawnTime -= dt;
if (t->respawnTime.as_milliseconds() < 0) {
t->SetPosition(SPAWN_POINTS[t->id_]);
t->isEnabled = true;
t->isAlive = true;
t->respawnTime = time(RESPAWN_MILLISECONDS);
}
}
}
}
void serverEntityManager::resetTank(int ID) {
tanks_[ID]->isEnabled = false;
tanks_[ID]->SetPosition(SPAWN_POINTS[ID]);
tanks_[ID]->isAlive = true;
}
#pragma region Initialisation
void serverEntityManager::createLevel() {
int rows = std::extent<decltype(LEVEL), 0>::value; // Get the amount of rows
for (size_t row = 0; row < rows; row++) {
int column = 0;
for (TILE_TYPE type : LEVEL[row]) {
if (type == W) {
entities_.push_back(new serverTile(vector2((float)column, (float)row)));
}
column++;
}
}
}
vector2 serverEntityManager::targetMoveDirection(message_client_to_server message) {
if (message.get_input(message_client_to_server::UP) && message.get_input(message_client_to_server::RIGHT)) return { 0.7071f ,-0.7071f }; //Normalised Diagonal Vector
if (message.get_input(message_client_to_server::UP) && message.get_input(message_client_to_server::LEFT)) return { -0.7071f ,-0.7071f };
if (message.get_input(message_client_to_server::DOWN) && message.get_input(message_client_to_server::LEFT)) return { -0.7071f ,0.7071f };
if (message.get_input(message_client_to_server::DOWN) && message.get_input(message_client_to_server::RIGHT)) return { 0.7071f ,0.7071f };
if (message.get_input(message_client_to_server::RIGHT)) return { 1.0f ,0 };
if (message.get_input(message_client_to_server::LEFT)) return { -1.0f,0 };
if (message.get_input(message_client_to_server::UP)) return { 0,-1.0f };
if (message.get_input(message_client_to_server::DOWN)) return { 0, 1.0f };
return { 0,0 };
}
void serverEntityManager::createTankBuffer() {
for (int i = 0; i < 4; i++) {
serverTank* t = new serverTank(SPAWN_POINTS[i], (uint8)i);
entities_.push_back(t);
tanks_[i] = t;
}
}
void serverEntityManager::createBulletBuffer() {
for (int i = 0; i < BULLET_MAX_COUNT; i++) {
serverBullet* b = new serverBullet();
bullets_[i] = b;
entities_.push_back(b);
}
}
#pragma endregion
#pragma region CollisionHandling
void serverEntityManager::manageCollisions() {
for (int i = 0; i < entities_.size(); i++) {
for (int j = 0; j < entities_.size(); j++) {
if (isCollisionPair(entities_[i], entities_[j])) {
if ((j != i) && (checkCollision(entities_[i], entities_[j]))) {
if (entities_[i]->type_ == TANK || entities_[j]->type_ == TANK) {
int x = 0;
}
if (entities_[i]->isEnabled && entities_[j]->isEnabled) {
entities_[i]->onCollision(entities_[j]);
entities_[j]->onCollision(entities_[i]);
}
}
}
}
}
}
void serverEntityManager::disableAllTanks() {
for (serverTank* t : tanks_) {
t->isAlive = false;
t->SetPosition(SPAWN_POINTS[t->id_]);
t->isEnabled = false;
}
}
bool serverEntityManager::checkCollision(IServerEntity* firstEntity, IServerEntity* secondEntity) {
const rectangle firstRectangle = firstEntity->collider_;
const rectangle secondRectangle = secondEntity->collider_;
const float firstTop = firstRectangle.y_;
const float firstBottom = firstRectangle.y_ + firstRectangle.height_;
const float firstLeft = firstRectangle.x_;
const float firstRight = firstRectangle.x_ + firstRectangle.width_;
const float secondTop = secondRectangle.y_;
const float secondBottom = secondRectangle.y_ + secondRectangle.height_;
const float secondLeft = secondRectangle.x_;
const float secondRight = secondRectangle.x_ + secondRectangle.width_;
if (firstTop > secondBottom || firstBottom < secondTop || firstLeft > secondRight || firstRight < secondLeft) {
return false;
}
return true;
}
bool serverEntityManager::isCollisionPair(IServerEntity* pFirstEntity, IServerEntity* pSecondEntity) {
for (std::pair<ENTITY_TYPE, ENTITY_TYPE> p : collisionPairs_) {
if ((p.first == pFirstEntity->type_ && p.second == pSecondEntity->type_) ||
(p.first == pSecondEntity->type_ && p.second == pFirstEntity->type_)) {
return true;
}
}
return false;
}
void serverEntityManager::fireBullet(serverTank* t) {
if (t->shootingCooldown_ > 0
|| !t->isEnabled)
return;
for(serverBullet* b : bullets_) {
if(!b->isEnabled) {
vector2 tPos = t->transform_.position_;
b->fire(tPos, t->getAimVector(), t->getUnusedBulletID(), t->id_);
t->bullets_.push_back(b);
t->shootingCooldown_ = FIRE_RATE;
break;
}
}
}
#pragma endregion
}
| true |
5ab9964237d1625965b05bab75416aba290c9491 | C++ | iMajesticButter/BetaFrameworkProjects | /Asteroids/Source/Asteroids.cpp | UTF-8 | 3,935 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "Asteroids.h"
#include "Level1.h"
#include "Level2.h"
#include "PlayerShip.h"
#include <sstream>
//------------------------------------------------------------------------------
// Public Functions:
//------------------------------------------------------------------------------
// Creates an instance of the Asteroids level.
Asteroids::Asteroids() : Beta::Level("Asteroids"), asteroidSpawnInitial(3), asteroidSpawnMaximum(20), asteroidHighScore(0), time(0) {
}
// Load the resources associated with the Asteroids level.
void Asteroids::Load() {
EngineGetModule(Beta::GraphicsEngine)->SetBackgroundColor(Beta::Colors::Black);
}
// Initialize the memory associated with the Asteroids level.
void Asteroids::Initialize() {
UpdateScore();
asteroidWaveCount = 0;
asteroidSpawnCount = asteroidSpawnInitial;
Beta::GameObject* ship = new Beta::GameObject(Beta::ResourceGetArchetype("PlayerShip"));
playerShip = ship->GetComponent<PlayerShip>();
GetSpace()->GetObjectManager().AddObject(*ship);
EdgeDetectEffect = new Beta::PostEffect("edgedetect.frag");
EngineGetModule(Beta::GraphicsEngine)->PushEffect(*EdgeDetectEffect);
BloomEffect = new Beta::PostEffect("bloom.frag");
BloomEffect->GetProgram().SetUniform("resolution", EngineGetModule(Beta::WindowSystem)->GetResolution());
EngineGetModule(Beta::GraphicsEngine)->PushEffect(*BloomEffect);
ChromaticAberrationEffect = new Beta::PostEffect("chromaticaberration.frag");
EngineGetModule(Beta::GraphicsEngine)->PushEffect(*ChromaticAberrationEffect);
ScanlineEffect = new Beta::PostEffect("scanline.frag");
ScanlineEffect->GetProgram().SetUniform("in_time", time);
EngineGetModule(Beta::GraphicsEngine)->PushEffect(*ScanlineEffect);
WarpEffect = new Beta::PostEffect("warp.frag");
EngineGetModule(Beta::GraphicsEngine)->PushEffect(*WarpEffect);
}
// Update the Asteroids level.
// Params:
// dt = Change in time (in seconds) since the last game loop.
void Asteroids::Update(float dt) {
time += dt;
if (GetSpace()->GetObjectManager().GetObjectCount("Asteroid") == 0 || EngineGetModule(Beta::Input)->CheckTriggered('L')) {
SpawnAsteroidWave();
}
auto input = EngineGetModule(Beta::Input);
if (input->IsKeyDown('1')) {
GetSpace()->SetLevel<Level1>();
} else if (input->IsKeyDown('2')) {
GetSpace()->SetLevel<Level2>();
} else if (input->IsKeyDown('3')) {
GetSpace()->RestartLevel();
}
ScanlineEffect->GetProgram().SetUniform("in_time", time);
}
void Asteroids::Shutdown() {
EngineGetModule(Beta::GraphicsEngine)->PopEffect();
EngineGetModule(Beta::GraphicsEngine)->PopEffect();
EngineGetModule(Beta::GraphicsEngine)->PopEffect();
EngineGetModule(Beta::GraphicsEngine)->PopEffect();
EngineGetModule(Beta::GraphicsEngine)->PopEffect();
delete EdgeDetectEffect;
delete BloomEffect;
delete ChromaticAberrationEffect;
delete ScanlineEffect;
delete WarpEffect;
if (playerShip->GetPoints() > asteroidHighScore) {
asteroidHighScore = playerShip->GetPoints();
UpdateScore();
}
}
//------------------------------------------------------------------------------
// Private Functions:
//------------------------------------------------------------------------------
// Create a single asteroid object from the archetype
void Asteroids::SpawnAsteroid(void) {
Beta::GameObject* asteroid = new Beta::GameObject(Beta::ResourceGetArchetype("Asteroid"));
GetSpace()->GetObjectManager().AddObject(*asteroid);
}
// Create a group of asteroids
void Asteroids::SpawnAsteroidWave(void) {
++asteroidWaveCount;
for (unsigned i = 0; i < asteroidSpawnCount; ++i) {
SpawnAsteroid();
}
asteroidSpawnCount = asteroidSpawnCount <= asteroidSpawnMaximum ? asteroidSpawnCount + 1 : asteroidSpawnMaximum;
}
// Update the score string
void Asteroids::UpdateScore() {
std::stringstream strstm;
strstm << "High Score: " << asteroidHighScore;
EngineGetModule(Beta::WindowSystem)->SetWindowTitle(strstm.str());
} | true |
3f168253fbf2bc7cd1c7c51a72a4c1dcd77b23f3 | C++ | VakarisL/OOP_3Uzduotis | /Main/GenerateTestFile.cpp | UTF-8 | 1,119 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <chrono>
#include <fstream>
#include "../Main/Headers/GenerateTestFile.h"
/**
* @brief Generates a Test.txt file and fills it with pseuodo-random grade values between 1 and 10 in the form of:
* [name] [surname] [grade] [grade] [grade] [grade] [grade] [exam grade]
*
* @param amount [number of data entries to be generated]
*/
void generate_speed_test_file(int amount) {
std::mt19937 mt(static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<int> dist(1, 10);
std::ofstream TestFile;
try {
TestFile.open("Main/Resources/Test.txt", std::ofstream::out | std::ofstream::trunc);
if (TestFile.fail()) throw "Nepavyko sukurti failo testavimui ";
} catch (const char* e) {
std::cerr << e << amount << std::endl;
std::exit(EXIT_SUCCESS);
}
for (size_t i = 0; i < amount; i++) {
TestFile << "Vardas" << i + 1 << " Pavarde" << i + 1 << " ";
for (size_t j = 0; j < 5; j++) {
TestFile << dist(mt) << " ";
}
TestFile << dist(mt) << std::endl;
}
TestFile.close();
} | true |
527a075eb67211d4e9539061b01b91df0a3354fb | C++ | Ekwy/Spatial_Simulator | /Source/PhysicObject.h | UTF-8 | 2,816 | 3.28125 | 3 | [] | no_license | /// \brief Interface donnant des propriétés physique à un objet
#ifndef SOURCE_PHYSICOBJECT_H
#define SOURCE_PHYSICOBJECT_H
#include <stack>
#include <map>
#include "Material.h"
#include "MaterialManager.h"
#include "Vector3d.h"
#include "Material.h"
#include "MaterialManager.h"
#define FRICTION 0.005
class PhysicObject {
protected:
const double volume; ///< Volume de l'objet (m^3) déterminé à l'aide de Blender
const Material& material; ///< Matériau de l'objet
std::stack<Vector3d> forces; ///< Forces instantannée appliquées à l'objet
std::stack<Vector3d> torques; ///< Moments de force instantannés sur l'objet
Vector3d centerOfMass; ///< Centre de masse global de l'objet
double angularMass; ///< Moment d'inertie de l'objet
double totalMass; ///< Masse totale
/*
* aluminium : 2 700 kg/m^3
* Terre : 5 515 kg/m^3
* Mars : 3 934 kg/m^3
* Lune : 3 346 kg/m^3
*
* */
///\return Moment de force résultant
Vector3d getTotalTorques(){
Vector3d totalTorque;
while (!torques.empty()) {
totalTorque += torques.top();
torques.pop();
}
return totalTorque;
}
/// \return Force résultante
Vector3d getTotalForces() {
Vector3d totalForce;
while (!forces.empty()) {
totalForce += forces.top();
forces.pop();
}
return totalForce;
}
public:
Vector3d speed, ///< Déplacement au prochain frame
angularSpeed; ///< Déplacement angulaire au prochain frame
/// \param volume Valeur initiale du volume
/// \param material Materiel de l'objet
PhysicObject(const double& volume, const std::string& material)
: volume(volume), material(MaterialManager::getMaterial(material)), centerOfMass(Vector3d::ZERO) {}
/// \brief Mets à jour la vitesse à chaque tick
virtual void update(const double& levelRatio) {
speed *= 1. - levelRatio * FRICTION;
speed += (getTotalForces() / totalMass) * DELTATIME;
angularSpeed *= 1. - std::max(levelRatio, 0.1) * FRICTION;
angularSpeed += (getTotalTorques() / angularMass) * DELTATIME;
}
/// \brief Ajoute une force
/// \param force Vecteur de force en Newton
void addForce(const Vector3d& force, const Vector3d& applicationPoint) {
forces.push(force);
torques.push(force / (centerOfMass - applicationPoint));
}
///\brief Obtention de la densité de l'objet
///\return La densité (kg/m^3)
const double& getDensity() const {
return material.density;
}
/// \brief Masse de la pièce locale
double getLocalMass() const {
return volume * material.density;
}
///\brief Obtention du volume de l'objet
///\return Le volume (m^3)
const double& getVolume() const {
return volume;
}
///\brief Obtention de la position de l'objet
///\return Le vecteur position
virtual Vector3d getPosition() const = 0;
};
#endif //SOURCE_PHYSICOBJECT_H
| true |
1fb5865d400bd9736890ec75c826a01fa035eb09 | C++ | arduinonsk/T1 | /examples/readSensorsToSerial/readSensorsToSerial.ino | UTF-8 | 955 | 2.890625 | 3 | [] | no_license | // подключаем библиотеку
#include <t1.h>
// создаем объект класса Т1 и называем его telega
T1 telega = T1();
void setup(){
// стартуем последовательное соединение с ПК
// на скорости 19200
Serial.begin(19200);
}
void loop(){
// читаем значение с левого сенсора и печатаем
// без переноса строки
Serial.print("Left = ");
Serial.print(telega.readSensorL());
// читаем значение с правого сенсора и печатаем
// без переноса строки
Serial.print(" Right = ");
Serial.print(telega.readSensorR());
// читаем значение с сонара и печатаем
// с переносом строки
Serial.print(" RF = ");
Serial.println(telega.readSonar());
// задержка 100 миллисекунд
delay(100);
} | true |
817dc3b72193348cec207625092cbc63bc7f4927 | C++ | wgnet/wds_qt | /qtbase/src/3rdparty/angle/src/compiler/preprocessor/Input.cpp | UTF-8 | 1,272 | 2.625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
... | permissive | //
// Copyright (c) 2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "Input.h"
#include <algorithm>
#include <cassert>
#include <cstring>
namespace pp
{
Input::Input() : mCount(0), mString(0)
{
}
Input::Input(size_t count, const char *const string[], const int length[]) :
mCount(count),
mString(string)
{
mLength.reserve(mCount);
for (size_t i = 0; i < mCount; ++i)
{
int len = length ? length[i] : -1;
mLength.push_back(len < 0 ? std::strlen(mString[i]) : len);
}
}
size_t Input::read(char *buf, size_t maxSize)
{
size_t nRead = 0;
while ((nRead < maxSize) && (mReadLoc.sIndex < mCount))
{
size_t size = mLength[mReadLoc.sIndex] - mReadLoc.cIndex;
size = std::min(size, maxSize);
std::memcpy(buf + nRead, mString[mReadLoc.sIndex] + mReadLoc.cIndex, size);
nRead += size;
mReadLoc.cIndex += size;
// Advance string if we reached the end of current string.
if (mReadLoc.cIndex == mLength[mReadLoc.sIndex])
{
++mReadLoc.sIndex;
mReadLoc.cIndex = 0;
}
}
return nRead;
}
} // namespace pp
| true |
0f3dcdc969ee559b6000b2c0136528eddbeb746e | C++ | VibhorKanojia/LeetCode | /DiameterOfBT.cpp | UTF-8 | 638 | 3.25 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int pathLength(TreeNode * root){
if (root == NULL) return 0;
else return (1 + max(pathLength(root->right),pathLength(root->left)));
}
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root == NULL) return 0;
return max(pathLength(root->right) + pathLength(root->left), max(diameterOfBinaryTree(root->right), diameterOfBinaryTree(root->left)));
}
};
| true |
a8d01eeaedc652236240aaa9142236e746138477 | C++ | andreasjhkarlsson/ai5 | /AI5Runtime/HashMapVariant.h | UTF-8 | 1,157 | 2.6875 | 3 | [] | no_license | #pragma once
#include "variant.h"
#include "IteratorVariant.h"
#include <unordered_map>
#include "VariantReference.h"
class HashMapVariant :
public Variant
{
public:
friend class GC;
typedef std::unordered_map<VariantReference<>,VariantReference<>,VariantKeyHasher,VariantKeyComparator> VariantMap;
static const VARIANT_TYPE TYPE = HASH_MAP;
static HashMapVariant* Create();
~HashMapVariant(void);
virtual shared_string toString() const;
virtual std::wostream& format(std::wostream& stream) const;
void set(const VariantReference<>& key,VariantReference<>& value);
const VariantReference<>& get(const VariantReference<>& key);
virtual VariantReference<IteratorVariant> iterate() override;
virtual bool toBoolean() const;
std::unordered_map<VariantReference<>,VariantReference<>>* getMap();
private:
HashMapVariant(void);
VariantMap map;
class KeyIterator: public IteratorVariant
{
public:
KeyIterator(const VariantReference<HashMapVariant>& map);
virtual bool hasMore();
virtual VariantReference<> next();
private:
VariantMap::iterator it;
VariantReference<HashMapVariant> map;
};
};
| true |
23fe5facbb8e131cb8690d183450663c6be67d86 | C++ | bdamer/dukat | /include/dukat/renderstage2.h | UTF-8 | 682 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include "renderlayer2.h"
namespace dukat
{
// A render stage represents one or more layers rendering
// to the same screen buffer.
struct RenderStage2
{
const int id;
// list of layers ordered by priority
std::list<std::unique_ptr<RenderLayer2>> layers;
// composite program to render to intermediate target
// before compositing to screen buffer.
ShaderProgram* composite_program;
std::function<void(ShaderProgram*)> composite_binder;
std::unique_ptr<FrameBuffer> frame_buffer;
RenderStage2(int id) : id(id), composite_program(nullptr), composite_binder(nullptr), frame_buffer(nullptr) { }
~RenderStage2(void) { }
};
} | true |
dbd7a61076e67c8876ab9441ac0df4b1c250eded | C++ | wzj1988tv/code-imitator | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/Loud.Scream/3264486_5633382285312000_Loud.Scream.cpp | UTF-8 | 904 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for (int c = 1; c <= t; ++c) {
cout << "Case #" << c << ": ";
int n;
cin >> n;
int num = n;
vector<int> digs;
while (num > 0) {
digs.push_back(num % 10);
num /= 10;
}
reverse(digs.begin(), digs.end());
int last = 0;
int i = 0;
while (i < digs.size() && digs[i] >= last) {
last = digs[i];
++i;
}
if (i == digs.size())
cout << n << "\n";
else {
--i;
--digs[i];
for (int j = i + 1; j < digs.size(); ++j)
digs[j] = 9;
reverse(digs.begin(), digs.end());
while (digs.size() > 1 && digs.back() == 0)
digs.pop_back();
reverse(digs.begin(), digs.end());
for (auto to : digs)
cout << to;
cout << "\n";
}
}
return 0;
}
| true |
44fee0495ec2d8ddf3e8a1fe95aca121ed61b853 | C++ | Ragefart/Baum | /Baum/Node.h | UTF-8 | 394 | 2.796875 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class Node {
public:
Node();
Node(int startvalue);
Node(Node* a);
//Node(const Node* orig);
virtual ~Node();
Node* getleftchild();
Node* getrightchild();
int getvalue();
void setvalue(int newnumber);
void setleftchild(Node* left);
void setrightchild(Node* right);
private:
Node* leftChild;
Node* rightChild;
int value;
}; | true |
d54a4dde883a0fe16b4662deebf06612d1197763 | C++ | shoaibrain/cse1325--school-projects | /P03/bonus/fraction.h | UTF-8 | 907 | 2.96875 | 3 | [
"MIT"
] | permissive | #ifndef __FRACTION_H
#define __FRACTION_H
#include <vector>
#include <string>
#include <iostream>
#include <limits>
class Fraction
{
private:
int _n;
int _d;
public:
Fraction(int numerator=0, int denominator=1);
static int gcd(int a, int b);
void reduce();
//Multiplication Operator overloading
Fraction operator*(const Fraction &f2);
//Division operator overloading
Fraction operator/(const Fraction &f2);
//Addition operator overloading
Fraction operator+(const Fraction &f2);
//Subtraction operator overloading
//Fraction operator-(const Fraction &f2);
//Negate
//friend Fraction operator-() const;
//OutStream operator overloading
friend std::ostream& operator<<(std::ostream &out, const Fraction &f1);
//Instream operator overloading
friend std::istream& operator>>(std::istream &in, Fraction &f1);
void print();
};
#endif | true |
3ad6cd1e2755bae41b508c7208fa484e205cdfb1 | C++ | Isaak-Malers/MicroDrv | /Drivers.cpp | UTF-8 | 1,532 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "Arduino.h"
#include "Drivers.h"
Drivers::Drivers(int boardRevision)
{
_boardRevision = boardRevision;
//Allows for pinout changes with future board revisions.
switch(_boardRevision){
case 4:
_IN1 = 4;
_IN2 = 14;
_PWM1 = 5;
_IN3 = A1;
_IN4 = A0;
_PWM2 = 6;
_IN5 = 8;
_IN6 = 7;
_PWM3 = 9;
_IN7 = 15;
_IN8 = 16;
_PWM4 = 10;
_configuredForRunning = true;
default:
_configuredForRunning = false;
}
pinMode(_IN1, OUTPUT);
pinMode(_IN2, OUTPUT);
pinMode(_IN3, OUTPUT);
pinMode(_IN4, OUTPUT);
pinMode(_IN5, OUTPUT);
pinMode(_IN6, OUTPUT);
pinMode(_IN7, OUTPUT);
pinMode(_IN8, OUTPUT);
pinMode(_PWM1, OUTPUT);
pinMode(_PWM2, OUTPUT);
pinMode(_PWM3, OUTPUT);
pinMode(_PWM4, OUTPUT);
}
//Utility methods:
bool direction(int speed){
if(speed < 0){
return false;
}
return true;
}
int dutyCycle(int speed){
int constrained = constrain(speed, -100, 100);
int mapped = map(constrained, -100, 100, -255, 255);
int directionRemoved = abs(mapped);
return directionRemoved;
}
void SetMotor(int IN1, int IN2, int PWM, int speed){
analogWrite(PWM, 0);
bool dir = direction(speed);
digitalWrite(IN1, dir);
digitalWrite(IN2, !dir);
analogWrite(PWM, dutyCycle(speed));
}
void Drivers::SetM1(int speed){
SetMotor(_IN1, _IN2, _PWM1, speed);
}
void Drivers::SetM2(int speed){
SetMotor(_IN3, _IN4, _PWM2, speed);
}
void Drivers::SetM3(int speed){
SetMotor(_IN5, _IN6, _PWM3, speed);
}
void Drivers::SetM4(int speed){
SetMotor(_IN7, _IN8, _PWM4, speed);
} | true |
a8a6f30f006cd6a7fd9d50ca0145af0817d54b2b | C++ | ttalexander2/chroma-public | /Chroma/src/Chroma/Scene/ComponentRef.h | UTF-8 | 1,046 | 2.984375 | 3 | [] | no_license | #pragma once
#include "ECS.h"
#include "Scene.h"
#include "spdlog/fmt/ostr.h"
namespace Chroma
{
//Forward Declarations
class EntityRef;
template <class T>
class ComponentRef
{
friend class Scene;
public:
T* operator->() { return m_Ptr; }
Scene* GetScene() { return m_Scene; }
EntityID GetEntityID() { return m_Entity; }
bool IsNull() { return m_Ptr == nullptr || m_Scene == nullptr; }
template<typename OStream>
friend OStream& operator<<(OStream& os, const ComponentRef<T>& t)
{
return os << "Component: " << FindTypeName(typeid(T).name()) << " (Entity " << t.m_Entity << ")";
}
void Delete()
{
m_Scene->RemoveComponent(*this);
}
private:
ComponentRef<typename T>(T* ptr, EntityID id, Scene* scene)
: m_Ptr(ptr), m_Entity(id), m_Scene(scene)
{
}
static std::string FindTypeName(const std::string& str)
{
size_t i = str.find_last_of("::");
if (i >= str.size())
return str;
return str.substr(i+1);
}
private:
EntityID m_Entity;
T* m_Ptr;
Scene* m_Scene;
};
}
| true |
6502628bb783aa8c78296b078f981a91c89f39bf | C++ | kevinwall/GREMLINS | /include/SLPool.hpp | UTF-8 | 822 | 2.515625 | 3 | [] | no_license | #ifndef _SLPool_
#define _SLPool_
#include <iostream>
#include "StoragePool.hpp"
class SLPool: public StoragePool
{
public:
struct Header
{
unsigned int m_length;
Header() : m_length(0u){ /* Empty */ }
};
struct Block : public Header
{
enum { BlockSize = 16 };
union {
Block *m_next;
char m_raw [ BlockSize - sizeof(Header)]; // Talvez necessite colocar -sizeof(m_next).
};
Block() : Header(), m_next( nullptr ) { /* Empty */ };
};
private :
unsigned int m_n_blocks;
Block *m_pool;
Block m_sentinel;
public :
explicit SLPool ( size_t sizeByte);
~SLPool();
void * Allocate( size_t );
void * Allocate_Bestfit(size_t);
void Free( void * );
void MemoryDemonstration( void );
void MemoryMap(void);
};
#include "../src/SLPool.inl"
#endif | true |
8544202aeb381f5acb8ae08a913868a371fdd456 | C++ | finwarman/raytracer | /src/geometricobjects/geometricobject.cpp | UTF-8 | 740 | 3 | 3 | [] | no_license | // this file contains the definition of the class GeometricObject
#include "constants.h"
#include "rgbcolour.h" // todo - material
#include "geometricobject.h"
// default constructor
GeometricObject::GeometricObject(void) : colour(black) {}
// copy constructor
GeometricObject::GeometricObject(const GeometricObject &object)
{
colour = object.colour; // todo - pointer / null
}
// assignment operator
GeometricObject &GeometricObject::operator=(const GeometricObject &rhs)
{
if (this == &rhs)
{
return *this;
}
colour = rhs.colour;
return *this;
}
// destructor
GeometricObject::~GeometricObject() {}
// todo - if using pointer, delete object and set NULL
// todo - set colour?
// todo - set material
| true |
fcc1c006fac324b3b113bce55d91b3badee6861e | C++ | yebra06/core-examples | /c++/datastructures/linkedlist/list.cpp | UTF-8 | 2,731 | 3.578125 | 4 | [
"MIT"
] | permissive | #include "list.h"
#include "node.h"
using namespace std;
#include <iostream>
list::list()
: len(0), head(nullptr) {}
list::list(const list& other)
: len(other.len), head(nullptr) {
node* temp = other.get_head();
while (temp != nullptr) {
insert_last(temp->data);
temp = temp->next;
}
}
list::~list() {
delete_list();
}
list& list::operator=(list src) {
swap(head, src.head);
return *this;
}
void list::insert_first(const int& data) {
node* new_node = new node;
new_node->data = data;
new_node->next = head;
head = new_node;
++len;
}
void list::insert_last(const int& data) {
node* new_node = new node;
new_node->data = data;
new_node->next = nullptr;
if (!head) {
head = new_node;
} else {
node* curr = head;
while (curr->next != nullptr)
curr = curr->next;
curr->next = new_node;
}
++len;
}
void list::insert_at_position(int position, const int& data) {
// Note: 0 is index of first list item.
if (position > len || position < 0) {
return;
} else if (position == 0 || head == nullptr) {
insert_first(data);
return;
} else if (position == len) {
insert_last(data);
return;
}
node* new_node = new node;
new_node->data = data;
node* prev = nullptr;
node* curr = head;
for (int i = 0; i < position; i++) {
prev = curr;
curr = curr->next;
}
new_node->next = curr;
prev->next = new_node;
++len;
}
void list::concat(const list& l2) {
node* temp1 = head;
node* temp2 = l2.get_head();
while (temp1->next != nullptr)
temp1 = temp1->next;
while (temp2->next != nullptr) {
insert_last(temp2->data);
temp2 = temp2->next;
}
insert_last(temp2->data);
}
void list::delete_first() {
node* temp = head;
head = temp->next;
delete temp;
--len;
}
void list::delete_last() {
node* curr = head;
node* prev = nullptr;
while (curr->next != nullptr) {
prev = curr;
curr = curr->next;
}
delete curr;
prev->next = nullptr;
--len;
}
void list::delete_at_position(int position) {
if (position > len || position < 0) {
return;
} else if (position == 0) {
delete_first();
return;
} else if (position == len) {
delete_last();
return;
}
node* temp = nullptr;
node* curr = head;
for (int i = 0; i < position-1; i++)
curr = curr->next;
temp = curr->next;
delete temp;
curr->next = curr->next->next;
--len;
}
void list::delete_item(int item) {
int position = 0;
node* temp = head;
while (temp->next != nullptr && temp->data != item) {
position++;
temp = temp->next;
}
delete_at_position(position);
}
void list::delete_list() {
while (!is_empty())
delete_first();
}
int list::size() const {
return len;
}
bool list::is_empty() const {
return head == nullptr;
}
node* list::get_head() const {
return head;
}
| true |
be19f3367426c8bb7e5b16b6db9bc99d3b8a201d | C++ | rohitamrutkar1204/dsc-hacktoberfest-2021 | /Submissions/Trapping_Rain_Water/Sneha_Baser.cpp | UTF-8 | 1,823 | 3.546875 | 4 | [
"CC0-1.0"
] | permissive | //Trapping Rain Water problem
//Approach:
/*An element of the array can store water if there are higher bars on the left and right.
The amount of water to be stored in every element can be found out by finding the heights of bars on the left and right sides.
The idea is to compute the amount of water that can be stored in every element of the array.
The idea is to traverse every array element and find the highest bars on the left and right sides by
pre-compute the highest bar on the left and right of every bar in linear time.
for each index Take the smaller of two heights.
The difference between the smaller height and
height of the current element is the amount of water that can be stored in this array element.*/
//TimeComplexity: O(n)
//SpaceComplexity:O(n)
//DriverCode Starts
#include <bits/stdc++.h>
using namespace std;
//DriverCode Ends
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
int i;
if(n==0)
return 0;
if(n==1)
return 0;
int left[n];
int right[n];
left[0]=height[0];
for(i=1;i<n;i++)
left[i]=max(left[i-1],height[i]);
right[n-1]=height[n-1];
for(i=n-2;i>=0;i--)
right[i]=max(height[i],right[i+1]);
int watertrapp=0;
for(i=1;i<=n-2;i++)
watertrapp=watertrapp+min(left[i],right[i])-height[i];
return watertrapp;
}
};
// { Driver Code Starts.
int main(){
int t;
int n,x;
cin >> n;
vector<int>height;
Solution ob;
for(int i =0;i<n;i++){
cin>>x;
height.push_back(x);
}
cout << ob.trap(height) << endl;
return 0;
} // } Driver Code Ends | true |
7ed77f11c44a11af930b8ea2e96ccb52830d6ae5 | C++ | kim-hwi/Algorithm | /BFS/불!BFS.cpp | UTF-8 | 1,892 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<utility>
#include<queue>
using namespace std;
string board[1002];
//bool vis[1002][1002];
int distF[1002][1002];
int distJ[1002][1002];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int main (void){
queue<pair<int,int> > J;
queue<pair<int,int> > F;
int x,y;
cin>>x>>y;
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
distF[i][j]=-1;
distJ[i][j]=-1;
}
}
for(int i=0;i<x;i++){
cin>>board[i];
}
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
if(board[i][j]=='J'){
J.push(pair<int,int> (i,j));
distJ[i][j]=0;
}
if(board[i][j]=='F'){
F.push(pair<int,int> (i,j));
distF[i][j]=0;
}
}
}
while(!F.empty()){
pair<int,int> curF=F.front(); F.pop();
for(int dir=0;dir<4;dir++){
int Fx= curF.first+dx[dir];
int Fy= curF.second+dy[dir];
if(Fx<0||Fx>=x||Fy<0||Fy>=y) continue;
if(distF[Fx][Fy]>=0||board[Fx][Fy]=='#') continue;
distF[Fx][Fy]=distF[curF.first][curF.second]+1;
F.push(pair<int,int>(Fx,Fy));
}
}
while(!J.empty()){
pair<int,int> curJ=J.front(); J.pop();
for(int dir=0;dir<4;dir++){
int Jx= curJ.first+dx[dir];
int Jy= curJ.second+dy[dir];
if(Jx<0||Jx>=x||Jy<0||Jy>=y){
cout<<distJ[curJ.first][curJ.second]+1<<endl;
return 0;
}
if(distJ[Jx][Jy]>=0||board[Jx][Jy]=='#') continue;
if(distF[Jx][Jy] != -1 && distF[Jx][Jy] <= distJ[curJ.first][curJ.second]+1) continue;
distJ[Jx][Jy]=distJ[curJ.first][curJ.second]+1;
J.push(pair<int,int>(Jx,Jy));
}
}
cout << "IMPOSSIBLE";
}
| true |
1e357cca771cf586076d29d5af64b64925127fe9 | C++ | nhzc123/leetcode | /UniquePaths.cpp | UTF-8 | 577 | 3.015625 | 3 | [] | no_license | /**
* @file UniquePaths.cpp
* @brief
* @author charles.nhzc@gmail.com
* @version 1.0.0
* @date 2014-09-04
*/
class Solution {
public:
int uniquePaths(int m, int n) {
int dp[101][101];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < m; i ++){
dp[i][0] = 1;
}
for (int j = 0; j < n; j ++){
dp[0][j] = 1;
}
for (int i = 1; i < m; i ++){
for (int j = 1; j < n; j ++){
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m -1][n - 1];
}
};
| true |
055141648fe10e5605a134bdf123564f17fa728f | C++ | huoshan017/hs_common | /hs_packetworker.cpp | GB18030 | 3,384 | 2.84375 | 3 | [] | no_license | #include "hs_packetworker.h"
#include "hs_define.h"
#include "boost/asio.hpp"
#include <iostream>
using namespace std;
// ӳΪsizeİpacket_dataлȡûݰuser_data_offsetΪpacket_dataƫƣuser_data_sizeΪûݳ
int HSPacketWorker::DecodePacket(char* packet_data, size_t size, size_t& user_data_offset, size_t& user_data_size)
{
if (!packet_data)
return -1;
static size_t identify_number_size = sizeof(HS_NET_PACKET_IDENTIFY_NUMBER);
// Сڰͷ+ʶ볤ȣܿǰû0ȴһνպ
if (size < HS_NET_PACKET_HEADER_LENGTH + identify_number_size) {
cout << "ݳ" << size << "Сڰͷ(" << (int)HS_NET_PACKET_HEADER_LENGTH << ")+ʶ(" << identify_number_size << "), 0ȴ´ν" << endl;
return 0;
}
// ûݲܴHS_NET_PACKET_MAX_SIZE - (HS_NET_PACKET_HEDER_LENGTH + identify_number_size)
unsigned int pl = (unsigned int)boost::asio::detail::socket_ops::network_to_host_long((unsigned long)*((unsigned int*)&packet_data[0]));
if (pl > HS_NET_PACKET_MAX_SIZE - (HS_NET_PACKET_HEADER_LENGTH + identify_number_size)) {
cout << "ûݳ" << pl << "-ͷ-ʶ" << endl;
return -1;
}
// ʶ
unsigned int in = (unsigned int)boost::asio::detail::socket_ops::network_to_host_long((unsigned long)*((unsigned int*)&packet_data[0+HS_NET_PACKET_HEADER_LENGTH]));
if (in != HS_NET_PACKET_IDENTIFY_NUMBER) {
cout << "ʶ(" << in << ")ȷ" << endl;
return -1;
}
// Ȳȴһνٴ
if (size < pl + (HS_NET_PACKET_HEADER_LENGTH + identify_number_size)) {
cout << "ݳ" << size << "ҪΪ" << pl << "+(HS_NET_PACKET_HEDER_LENGTH + identify_number_size)ȴ´ν" << endl;
return 0;
}
user_data_offset = (HS_NET_PACKET_HEADER_LENGTH + identify_number_size);
user_data_size = pl;
return 1;
}
int HSPacketWorker::EncodePacket(const char* user_data, size_t size, char* out_data, size_t out_data_size, size_t& encode_size)
{
static size_t identify_number_size = sizeof(HS_NET_PACKET_IDENTIFY_NUMBER);
if (size + (HS_NET_PACKET_HEADER_LENGTH + identify_number_size) > HS_NET_PACKET_MAX_SIZE) {
cout << "ûݰ" << size + (HS_NET_PACKET_HEADER_LENGTH + identify_number_size) << "뷢ͻ" << endl;
return -1;
}
if (size + (HS_NET_PACKET_HEADER_LENGTH + identify_number_size) > out_data_size) {
cout << "ûݳ(Ҫϰͷ4ʶ볤4)" << size + HS_NET_PACKET_HEADER_LENGTH + identify_number_size << "˷ͻṩij" << out_data_size << endl;
return 0;
}
//
*((unsigned int*)out_data) = (unsigned int)boost::asio::detail::socket_ops::host_to_network_long((unsigned long)size);
// ʶ
*((unsigned int*)(out_data+HS_NET_PACKET_HEADER_LENGTH)) = (unsigned int)boost::asio::detail::socket_ops::host_to_network_long((unsigned long)HS_NET_PACKET_IDENTIFY_NUMBER);
//
memcpy(out_data + HS_NET_PACKET_HEADER_LENGTH + identify_number_size, user_data, size);
//
encode_size = size + (identify_number_size+HS_NET_PACKET_HEADER_LENGTH);
return 1;
} | true |
b94372b6c46d405ec24c9b84def41f8f4eded587 | C++ | luputona/Chapter_03 | /Chapter_03/NewObject.cpp | UTF-8 | 313 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
class Simple
{
public:
Simple()
{
cout << "I'm simple constructor!" << endl;
}
};
void main2()
{
cout << "case 1: ";
Simple *sp1 = new Simple;
cout << "case 2: ";
Simple *sp2 = (Simple*)malloc(sizeof(Simple) * 1);
delete sp1;
free(sp2);
} | true |
9af086149d200a15ea6cbb73a4941a903abc2062 | C++ | mariuszskon/UTCTF-20 | /reversing-babymips/main.cpp | UTF-8 | 1,557 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <signal.h>
#include <iomanip>
class nodebug {
public:
nodebug() {
if (ptrace(PTRACE_TRACEME, 0, 1, 0) == -1) {
*((unsigned int *)0) = 0xDEADBEEF;
}
}
};
nodebug nice_try;
class decryptme {
private:
char encrypted_string[78] = {
0x62, 0x6c, 0x7f, 0x76, 0x7a, 0x7b, 0x66, 0x73, 0x76, 0x50, 0x52, 0x7d,
0x40, 0x54, 0x55, 0x79, 0x40, 0x49, 0x47, 0x4d, 0x74, 0x19, 0x7b, 0x6a,
0x42, 0xa, 0x4f, 0x52, 0x7d, 0x69, 0x4f, 0x53, 0xc, 0x64, 0x10, 0xf,
0x1e, 0x4a, 0x67, 0x3, 0x7c, 0x67, 0x2, 0x6a, 0x31, 0x67, 0x61, 0x37,
0x7a, 0x62, 0x2c, 0x2c, 0xf, 0x6e, 0x17, 0x0, 0x16, 0xf, 0x16, 0xa,
0x6d, 0x62, 0x73, 0x25, 0x39, 0x76, 0x2e, 0x1c, 0x63, 0x78, 0x2b, 0x74,
0x32, 0x16, 0x20, 0x22, 0x44, 0x19};
int length = 78;
public:
void checkflag(std::string flag) {
if (flag.size() != 78) {
std::cout << "incorrect" << std::endl;
return;
}
for (int i = 0; i < flag.size(); i++) {
int cr = flag[i];
int br = cr ^ (i + 23);
if (br != encrypted_string[i]) {
std::cout << "incorrect" << std::endl;
return;
}
}
std::cout << "correct!" << std::endl;
}
};
__attribute__((constructor))
static void _csu_init() {
if (ptrace(PTRACE_TRACEME, 0, 1, 0) == -1) {
raise(SIGSEGV);
}
}
int main() {
std::string flag;
std::cout << "enter the flag" << std::endl;
std::cin >> flag;
decryptme flag_checker;
flag_checker.checkflag(flag);
}
| true |
e9fe1f44facfc0ba951a83eadb95811f245a7063 | C++ | diulianguo/leetcode | /0927leetcode/0927leetcode/54.cpp | UTF-8 | 1,110 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> res;
int x = matrix.size();
if (x == 0)
return res;
int y = matrix[0].size();
if (y == 0)
return res;
vector<vector<bool>> vis(x, vector<bool>(y));
int i = 0, j = -1, count = 0;
while (count < x*y){
while (j < y - 1 && !vis[i][j + 1]){
res.push_back(matrix[i][++j]);
vis[i][j] = true;
++count;
}
while (i < x - 1 && !vis[i + 1][j]){
res.push_back(matrix[++i][j]);
vis[i][j] = true;
++count;
}
while (j>0 && !vis[i][j - 1]){
res.push_back(matrix[i][--j]);
vis[i][j] = true;
++count;
}
while (i > 0 && !vis[i - 1][j]){
res.push_back(matrix[--i][j]);
vis[i][j] = true;
++count;
}
}
return res;
}
//int main()
//{
// vector<vector<int>> matrix =
// {};
// vector<int> res = spiralOrder(matrix);
// return 0;
//} | true |
dc9706e83d8ff366c64505185785cfeff4c00641 | C++ | azais-corentin/Bluetrackr | /firmware/common/common/blt/uart.cpp | UTF-8 | 576 | 2.625 | 3 | [
"MIT"
] | permissive | #include <blt/uart.hh>
#include <blt/hal_include.hh>
#include <string>
namespace blt::uart {
UART_HandleTypeDef* uart_handle = nullptr;
void init(UART_HandleTypeDef* huart) {
uart_handle = huart;
}
void transmit(uint8_t data) {
HAL_UART_Transmit(uart_handle, &data, 1, HAL_UART_TIMEOUT_VALUE);
}
void transmit(uint8_t* data, uint16_t len) {
HAL_UART_Transmit(uart_handle, data, len, HAL_UART_TIMEOUT_VALUE);
}
void transmit(std::string_view sv) {
std::string str{sv};
transmit(reinterpret_cast<uint8_t*>(str.data()), str.size());
}
} // namespace blt::uart | true |
f53ccfbb1146462fe63d4b41ba1ea83d1f73bf02 | C++ | golborneville/BOJAlgorithm | /BOJAlgorithm/2583영역구하기.cpp | UTF-8 | 1,231 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int res = 0;
vector<int> resar;
int M, N, K;
int arr[102][102];
int dy[4] = { 0,0,1,-1 };
int dx[4] = { 1,-1,0,0 };
int chk_area(int i, int j) {
queue<pair<int, int>> qu;
int sum = 1;
arr[i][j] = 1;
res++;
qu.push({ i,j });
while (!qu.empty()) {
pair<int, int> fr = qu.front();
qu.pop();
for (int k = 0; k < 4; k++) {
int nx = fr.first + dx[k]; int ny = fr.second + dy[k];
if (nx < 0 || ny < 0 || nx >= M || ny >= N)continue;
if (!arr[nx][ny]) {
qu.push({ nx,ny });
sum++;
arr[nx][ny] = 1;
}
}
}
return sum;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> M >> N >> K;
for (int i = 0; i < K; i++) {
int lx, ux, ly, uy;
cin >> lx >> ly >> ux >> uy;
for (int x = lx; x < ux; x++) {
for (int y = ly; y < uy; y++) {
arr[y][x] = 1;
}
}
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (!arr[i][j]) {
int areaval = chk_area(i, j);
resar.push_back(areaval);
}
}
}
sort(resar.begin(), resar.end());
cout << res << "\n";
for (int i = 0; i < resar.size(); i++) {
cout << resar[i] << " ";
}
return 0;
} | true |
3ac866e20e82b0475baf8cd3b700c1410ff2de67 | C++ | pranjularora/TypeBased-DependencyAnalysis | /NoSqlDB/noSqlDB.h | WINDOWS-1252 | 6,496 | 2.78125 | 3 | [] | no_license | #pragma once
/////////////////////////////////////////////////////////////////////////////
// NoSqlDb.h - key/value pair in-memory database //
// //
// ver 1.1 //
// ----------------------------------------------------------------------- //
// copyright Pranjul Arora, 2017 //
// All rights granted provided that this notice is retained //
// ----------------------------------------------------------------------- //
// Language: Visual C++, Visual Studio 2015 //
// Platform: Mac Book Pro, Core i5, MAC OS //
// Application: Project 2, CSE687 - Object Oriented Design //
// Author: Pranjul Arora, Syracuse University //
// (315) 949 9061, parora01@syr.edu //
/////////////////////////////////////////////////////////////////////////////
/*
* Module Operations:
* -------------------
* This package is for building a key/value pair noSql Database.or Dependency Table that creates dependency table based on the
* ananlysis done.
*
* Public Interface:
* -----------------
* This package contains:
* - noSqlDB template class that have functions -
* - keys --> gives all the exsiting keys in the ElementNoSqlDB
* - save --> save the current state of the Database
* - value --> gives the value of the given key
* - count --> gives size of DB
* - editElem --> edit element (metadata or data) of a particular key
* - deleteElem --> delete element of a particulat key
* - editInstance --> edit the complete instance corresponding to a key
*
* - Element template class that define properties which helps making database
*
* Required Files:
* ---------------
* CppProperties.h, CppProperties.cpp
*
*
* Build Process:
* --------------
* devenv CodeAnalyzer.sln /rebuild debug
*
* Maintenance History:
* --------------------
* ver 2.0 : 7th March 2017
* - second release
*
*/
#include "../CppProperties/CppProperties.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <unordered_map>
template<typename Data>
class ElementNoSqlDB
{
public:
using Name = std::string;
using Category = std::string;
using TimeDate = std::string;
using Children = std::vector<std::string>;
Property<Name> name;
Property<Category> category;
Property<TimeDate> timeDate;
Children children;
Property<Data> data;
std::string show();
};
// returns the ElementNoSqlDB<Data> template class by coverting it to string for display
template<typename Data>
std::string ElementNoSqlDB<Data>::show()
{
// show children when you've implemented them
std::ostringstream out;
int i = 0;
out.setf(std::ios::adjustfield, std::ios::left);
out << "\n " << std::setw(8) << "name" << " : " << name;
//out << "\n " << std::setw(8) << "category" << " : " << category;
//out << "\n " << std::setw(8) << "timeDate" << " : " << timeDate;
//out << "\n " << std::setw(8) << "data" << " : " << data;
out << "\n " << std::setw(8) << "children" << " : ";
for (std::vector<std::string>::iterator it = children.begin(); it != children.end(); ++it)
{
if (i != 0)
out << " " << std::setw(8) << " " << " : " << *it << "\n";
else
out << *it << "\n";
i++;
}
out << "\n";
return out.str();
}
// Class of template type to Create NoSql Database
template<typename Data>
class noSqlDB
{
public:
using Key = std::string;
using Keys = std::vector<Key>;
Keys keys();
bool save(Key key, ElementNoSqlDB<Data> elem);
ElementNoSqlDB<Data> value(Key key);
size_t count();
void deleteElem(Key key);
void editElem(Key key, Key editingValue, Key newChild);
void editInstance(Key key, ElementNoSqlDB<Data> newElement);
private:
using Item = std::pair<Key, ElementNoSqlDB<Data>>;
std::unordered_map<Key, ElementNoSqlDB<Data>> store;
};
// code for editing Value part of the database i.e. editing ElementNoSqlDB class values
template<typename Data>
void noSqlDB<Data>::editElem(Key key, Key newCategory, Key newChild)
{
if (store.find(key) != store.end())
{
// store[key] return value of the key, which is ElementNoSqlDB<Data> in our case
ElementNoSqlDB<Data> editElement = store[key];
editElement.category = newCategory;
editElement.data = "edited Data";
for (std::vector<std::string>::iterator it = editElement.children.begin(); it != editElement.children.end(); ++it)
{
if (*it == "arora")
*it = newChild;
}
store[key] = editElement;
}
else
{
std::cout << "Key Not Found";
}
}
// edit the whole instance of the class i.e. new ElementNoSqlDB<Data> will be assigned to the existing key
template<typename Data>
void noSqlDB<Data>::editInstance(Key key, ElementNoSqlDB<Data> newElement)
{
if (store.find(key) != store.end())
{
store[key] = newElement;
}
}
// Delete an element corresponding to a particular key
template<typename Data>
void noSqlDB<Data>::deleteElem(Key key)
{
if (store.find(key) != store.end())
{
store.erase(key);
Keys newKeys = keys();
for (Key newKey : newKeys)
{
ElementNoSqlDB<Data> editElement = store[newKey];
for (std::vector<std::string>::iterator it = editElement.children.begin(); it != editElement.children.end(); ++it)
{
if (*it == key)
it = editElement.children.erase(it);
}
store[newKey] = editElement;
}
}
}
// return all keys from the existing database
template<typename Data>
typename noSqlDB<Data>::Keys noSqlDB<Data>::keys()
{
Keys keys;
for (Item item : store)
{
keys.push_back(item.first);
}
return keys;
}
// Save to the Database
template<typename Data>
bool noSqlDB<Data>::save(Key key, ElementNoSqlDB<Data> elem)
{
if (store.find(key) != store.end())
return false;
store[key] = elem;
return true;
}
// Return value i.e. Element class corresponding to the key
template<typename Data>
ElementNoSqlDB<Data> noSqlDB<Data>::value(Key key)
{
if (store.find(key) != store.end())
return store[key];
return ElementNoSqlDB<Data>();
}
// Counts the size of the database
template<typename Data>
size_t noSqlDB<Data>::count()
{
return store.size();
} | true |
5b595a941fe737735da2b8ee97e86711b8318b4b | C++ | Pilaniya1/ProcessingShoppingList | /ProcessingShopingList.cpp | UTF-8 | 1,822 | 3.65625 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int m =50;
class ITEMS
{
int itemCode[m];
float itemPrice[m];
int count;
public:
void CNT(void){count =0;}//intilaizes count to 0
void getitem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};
void ITEMS::getitem(void) //assign values to data members of item
{
cout<<"Enter item code :";
cin>>itemCode[count];
cout<<"Enter item cost :";
cin>>itemPrice[count];
count++;
}
void ITEMS :: displaySum(void)//display total value of all items
{
float sum =0;
for(int i=0; i<count;i++)
sum=sum + itemPrice[i];
cout<<"\nTotal value :"<<sum<<"\n";
}
void ITEMS :: remove(void)//delete a specified item
{
int a;
cout<<"Enter item code :";
cin>>a;
for(int i=0; i<count;i++)
if(itemCode[i]==a)
itemPrice[i]=0;
}
void ITEMS :: displayItems(void)//display items
{
cout<<"\nCode Price\n";
for(int i=0; i=count;i++)
{
cout<<"\n"<<itemCode[i];
cout<<" "<<itemPrice[i];
}
cout<<"\n";
}
int main()
{
ITEMS order;
order.CNT();
int x;
do
{ //do...while loop
cout<<"\nYou can do the following;"
<<"Enter appropriate number \n";
cout<<"\n1: Add an item ";
cout<<"\n2: Display total value";
cout<<"\n3: Delete an item";
cout<<"\n4: Display all items";
cout<<"\n5: Quit";
cout<<"\n\nWhat is your option?";
cin>>x;
switch(x)
{
case 1 :order.getitem();break;
case 2 :order.displaySum();break;
case 3 :order.remove();break;
case 4 :order.displayItems();break;
case 5 :break;
default :cout<<"Error in input:try again\n";
}
}while(x!=5); //do..while ends
return 0;
} | true |
5f56152e971e8dfdc1e678818fe02a9fa5d2e7fc | C++ | SecMeant/pwr-snake | /TextureManager/TextureManager.hpp | UTF-8 | 3,305 | 2.734375 | 3 | [] | no_license | #ifndef TEXTUREMANAGER_H
#define TEXTUREMANAGER_H
#include "stdint.h"
#include <SFML/Graphics.hpp>
// Im not sure about correctness of below code.
// Maybe i should perform transform operations
// textures instead of adding each variant as
// separate file. TODO: maybe change it in future
struct SnakeHeadTex
{
sf::Texture left;
sf::Texture right;
sf::Texture up;
sf::Texture down;
constexpr static const char *leftPath =
"./assets/snake/head/snakeHeadLeft.png";
constexpr static const char *rightPath =
"./assets/snake/head/snakeHeadRight.png";
constexpr static const char *upPath =
"./assets/snake/head/snakeHeadUp.png";
constexpr static const char *downPath =
"./assets/snake/head/snakeHeadDown.png";
inline void loadTextures()
{
this->left.loadFromFile(this->leftPath);
this->right.loadFromFile(this->rightPath);
this->up.loadFromFile(this->upPath);
this->down.loadFromFile(this->downPath);
}
};
class TextureManager
{
private:
// Prevents from creating more than one TextureManager
static int32_t lifecount;
inline void loadTextures();
inline void loadFonts();
public:
// Textures
static sf::Texture brickBackgroundTex;
static sf::Texture waterandsandBackgroundTex;
static sf::Texture highscoresBackgroundTex;
static sf::Texture tileTexture;
static sf::Texture cherryTexture;
static sf::Texture redButtonDownTex;
static sf::Texture redButtonUpTex;
static sf::Texture yellowButtonDownTex;
static sf::Texture yellowButtonUpTex;
static sf::Texture blueButtonDownTex;
static sf::Texture blueButtonUpTex;
static sf::Texture blueSliderLeftTex;
static sf::Texture pypyTex;
static sf::Texture snakeBodyTex;
static SnakeHeadTex snakeHeadTex;
static sf::Font defaultFont;
static sf::Font mushyLove;
static constexpr const char *brickBackgroundTexPath
= "./assets/default-background.png";
static constexpr const char *waterandsandBackgroundTexPath
= "./assets/waterandsand-background.png";
static constexpr const char *highscoresBackgroundTexPath
= "./assets/highscores.png";
static constexpr const char *tileTexturePath
= "./assets/rocktile.png";
static constexpr const char *cherryTexturePath
= "./assets/cherry.png";
static constexpr const char *redButtonDownTexPath
= "./assets/red_button_down.png";
static constexpr const char *redButtonUpTexPath
= "./assets/red_button_up.png";
static constexpr const char *yellowButtonDownTexPath
= "./assets/yellow_button_down.png";
static constexpr const char *yellowButtonUpTexPath
= "./assets/yellow_button_up.png";
static constexpr const char *blueButtonDownTexPath
= "./assets/blue_button_down.png";
static constexpr const char *blueButtonUpTexPath
= "./assets/blue_button_up.png";
static constexpr const char *blueSliderLeftTexPath
= "./assets/blue_sliderLeft.png";
static constexpr const char *snakeHeadTexPath
= "./assets/snake/head/snakeHead.png";
static constexpr const char *snakeBodyTexPath
= "./assets/snake/body/snakeBody.png";
static constexpr const char *pypyTexPath
= "./assets/pypy.png";
static constexpr const char *defaultFontPath
= "./assets/font/orange_juice.ttf";
static constexpr const char *mushyLovePath
= "./assets/font/mushy_love.ttf";
TextureManager();
~TextureManager();
};
#endif // TEXTUREMANAGER_H
| true |
0b0dc1b0d4db7d685e711ad45cc69700b77b35b1 | C++ | ddizhang/ECSp1 | /directory.cpp | UTF-8 | 2,710 | 2.953125 | 3 | [] | no_license | //
// directory.cpp
//
//
// Created by Di Zhang on 15/1/15.
//
//
#include "directory.h"
/*void showPath(){
print()
}*/
creatDirectory(Directory *rootDir, int umask ){
rootDir->name = &"/";
rootDir->time = 0;
rootDir->dirPermit = creatPermission(7, umask)
}
void showPath(Directory *currentDirectory)
// Print current path
{
if (*(currentDirectory->ParentDir != NULL)) {
showPath(currentDirectory->ParentDir)
printf("%s/", *(currentDirectory->name))
} else {
printf("/")
}
};
bool mkdir(Directory *dir, char *name, int time, Directory *currentDirectory, int umask){
//some code serching for the name of new subdir in the array subdir
//cumsum = 0;
for (i = 0;i < len(dir->subDir); i++) {
if(name == currDir->subDir[i]) { // strcmp(st1, st2) do we have to use this??
printf("mkdir: cannot creat directory '%s': File exists/n", *name);
successMkdir = 0;
goto RETURN
}
}
dir->name = name;
dir->time = time;
dir->parentDir = currentDirectory;
dir->dirPermit = creatPermission(7, umask);
successMkdir = 1
}
RETURN: return(successMkdir)
}
/*have to rewrite!!
/*
mkdir(Directory* currDir, char *subDirName, int argcount, umask){
parentDir = *currDir
if (parentDir.numSubDir =3)
printf("mkdir: %s already contains the maximum number of directories \n", *(parentDir.name));
else {
struct Directory{ /* make a subdirectory
name = subDirName;
time = argcount;
ParentDir = currDir;
Permission = creatPermission(7, funix) /* ???
}subDir;
dir.numSubDir = dir.numSubDir + 1;
dir.subDir[0] = &subDirName;
/* change some parameters of current directory
}
return(subDir)s
}
mkdir(funix.currentDirectory)
*/
void ls(Directory *directory)
{
//if (no -l)
//rwx = Permission::printPermissions(Directory *directory)
//print
//else (-l)
};
cd(Directory* currDir, const char * arguments[]){
if (arguments[1] == '..') {
currDir = currDir->parentDir
}
else
cumsum = 0
for(i = 0, i < len(currDir->subDir), i++){
if(arguments[1] == currDir->subDir[i]) { // strcmp(st1, st2) do we have to use this??
currDir = currDir->subDir[i];
break;
}
else cumsum = cumsum + 1;
//printf("no such directory");
}
if (cumsum == len(currDir->subDir))
printf("no such directory");
}
| true |
e6ae8fe614a093bb26c2a4ea9b8dc134c48ab4a3 | C++ | fuzzwaz/ParticleShooter | /ParticleShooter/UI/HealthBar.h | UTF-8 | 957 | 2.578125 | 3 | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | //
// HealthBar.h
// Particle Shooter
//
// Created by Ramy Fawaz in 2021
// Copyright (c) 2021 Ramy Fawaz. All rights reserved.
//
#pragma once
#include "GraphicAssetResources.h"
#include "GraphicObject.h"
#include "PlayerInfo.h"
//Class representing the Player's health bar
class HealthBar : public GraphicObject
{
public:
HealthBar(const Vector2& position) : GraphicObject(position)
{
const int fullHealthPercentage = 100;
_graphicsController = std::make_shared<AnimatedSingleTextureGraphicsController>(&_propertyController, Resources::Graphics::HEALTH_BAR);
_graphicsController->SetAnimationFramePercent(fullHealthPercentage);
SetIsActive(true);
}
void Update(const PlayerInfo& playerInfo, const Vector2& cameraPosition, const InputState& input) override
{
GraphicObject::Update(playerInfo, cameraPosition, input);
_graphicsController->SetAnimationFramePercent(playerInfo._CurrentHealth); //Updates how full the health bar looks
}
};
| true |
4a7b98d253ac9e7340c6ab87506c1a9ef85a6524 | C++ | ankitpriyarup/online-judge | /kattis/familydag.cpp | UTF-8 | 1,874 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
constexpr int MAXN = 222;
using ll = long long;
vector<string> all_names;
vector<pair<string, string>> edges;
void reset() {
all_names.clear();
edges.clear();
}
void solve() {
sort(begin(all_names), end(all_names));
all_names.erase(unique(begin(all_names), end(all_names)), end(all_names));
int n = all_names.size();
vector<vector<int>> graph(n, vector<int>());
for (const auto& p : edges) {
int x = lower_bound(begin(all_names), end(all_names), p.first) - begin(all_names);
int y = lower_bound(begin(all_names), end(all_names), p.second) - begin(all_names);
graph[y].push_back(x);
}
for (int u = 0; u < n; ++u) {
// check for paradox
vector<char> vis(n, 0);
queue<int> q;
vis[u] = 1;
q.push(u);
bool paradox = false;
bool hilly = false;
while (!q.empty()) {
int v = q.front();
q.pop();
for (int w : graph[v]) {
if (vis[w]) {
hilly = true;
paradox |= (w == u);
} else {
vis[w] = true;
q.push(w);
}
}
}
if (paradox) {
cout << all_names[u] << " paradox" << endl;
} else if (hilly) {
cout << all_names[u] << " hillbilly" << endl;
}
}
cout << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string word, junk, desc;
while (cin >> word) {
if (word == "done") {
solve();
reset();
continue;
}
cin >> junk >> desc;
all_names.push_back(word);
all_names.push_back(desc);
edges.emplace_back(word, desc);
}
}
| true |
252cfdaf3e7de4687f60ad4dcdc5662a6191817e | C++ | SubhamChoudhury/Back_to_Basics | /Arrays/Sahil/cpp/cyclically_rotate_an_array_by_one.cpp | UTF-8 | 830 | 4.25 | 4 | [] | no_license | /*
* Given an array, cyclically rotate the array clockwise by one.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}
* */
#include <iostream>
#include <array>
using namespace std ;
int main() {
array<int, 5> arr = {1, 2, 3, 4, 5} ;
int number_to_rotation = 1 ; // here you can enter how many values you want it to rotate by
for(int i = 0 ; i < number_to_rotation ; i++) {
int temp = arr[0];
for(int j = 0 ; j < arr.size() ; j++) {
if(j+1 < arr.size()) {
int temp_2 = arr[j+1] ;
arr[j+1] = temp ;
temp = temp_2 ;
} else {
arr[0] = temp ;
}
}
}
for(int i : arr) {
cout << i << ", " ;
}
} | true |
ffad6b0393461d0a89b509f855be4788ed0e945a | C++ | DyslexikStonr240/backup | /Machine_Learning/ConvoNet/ConvNet/src/headers/node/InternalNode.h | UTF-8 | 3,174 | 2.875 | 3 | [] | no_license | #ifndef INTERNALNODE
#define INTERNALNODE
#include <Eigen/Dense>
#include "BaseNode.h"
class internalNode: public baseNode{
private:
baseNode& _previousNode;
public:
internalNode (baseNode& previousNode, int numberOfNeurons);
void backwardPass (float STEP_SIZE, float lambda);
void forwardPass ();
};
internalNode::internalNode(baseNode& previousNode, int numberOfNeurons) : baseNode(), _previousNode(previousNode){
_numberOfNeurons = numberOfNeurons;
_layer = _previousNode._layer + 1;
_previousNode = previousNode;
};
void internalNode::forwardPass(){
// We pass in the inputs and add an extra col on the end to fill it with 1's.
// We then make the weights matrix with the same number of rows as the inputs
// have columns. This means that we can dot the inputs with the weights and
// add in the biases in one operation. We also find the derivative of the ouputs
// with respect to the inputs*weights. This is so we can use it later to chain rule
// in backpropagation.
int numberOfInputNeurons = _previousNode._activations.rows();
if(!(_initialisationCheckFlag)){
auto random = [&](float x){
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<float> d(0, 1 / std::sqrt(numberOfInputNeurons));
return d(gen);
};
_weights = Eigen::MatrixXf::Zero(_previousNode._activations.cols(), _numberOfNeurons).unaryExpr(random);
_biases = Eigen::MatrixXf::Zero(_previousNode._activations.rows(), _numberOfNeurons).unaryExpr(random);
_initialisationCheckFlag = true;
}
auto sigFun = [](float x){
return static_cast<float>(1.0 / (1.0 + std::exp(-x)));
};
_activations = ((_previousNode._activations * _weights) + _biases).unaryExpr(sigFun);
}
void internalNode::backwardPass (float STEP_SIZE, float lambda){
auto invSigFunc = [](float x){
return static_cast<float>((x * (1.0 - x)));
};
// For each pass back through the neuron we need to chain rule the incoming gradients
// through the activation function. This is achieved by taking the derivative of
// the activation function with respect to the inputs and weights; we do this during the forward pass.
// After chain ruling the gradient is then split between the weights and the input values by multiplying it respectively.
// We need to be careful that we only multiply by the weights and not the biases (which have been combined with the weights matrix)
// to avoid pass gradients backwards with the wrong dimensions.
_gradients = _gradients.cwiseProduct(_activations.unaryExpr(invSigFunc));
//_gradients = gradients * (_weights.transpose());
_weights *= (1 - lambda * STEP_SIZE);
_weights -= STEP_SIZE * (_previousNode._activations.transpose() * _gradients);
_biases = STEP_SIZE * _gradients;
_previousNode._gradients = _gradients * (_weights.transpose());
}
#endif
| true |
0daa73cf21377ed1f8a6c1f6a5615997235b5549 | C++ | micro500/treasure-master-hack | /bruteforce/tm_64_8_test/tm_64_8_test.cpp | UTF-8 | 4,448 | 2.765625 | 3 | [] | no_license | #include "data_sizes.h"
#include "tm_64_8_test.h"
#include "tm_64_8.h"
#include "rng.h"
tm_64_8_test::tm_64_8_test()
{
this->rng_table = new uint16[256*256];
generate_rng_table(this->rng_table);
regular_rng_values = new uint8[0x10000 * 128];
generate_regular_rng_values_8(regular_rng_values, rng_table);
regular_rng_values_lo = new uint8[0x10000 * 128];
generate_regular_rng_values_8_lo(regular_rng_values_lo, rng_table);
regular_rng_values_hi = new uint8[0x10000 * 128];
generate_regular_rng_values_8_hi(regular_rng_values_hi, rng_table);
alg0_values = new uint8[0x10000 * 128];
generate_alg0_values_8(alg0_values, rng_table);
alg6_values = new uint8[0x10000 * 128];
generate_alg6_values_8(alg6_values, rng_table);
alg4_values_lo = new uint8[0x10000 * 128];
generate_alg4_values_8_lo(alg4_values_lo, rng_table);
alg4_values_hi = new uint8[0x10000 * 128];
generate_alg4_values_8_hi(alg4_values_hi, rng_table);
alg2_values = new uint64[0x10000];
generate_alg2_values_64_8(alg2_values, rng_table);
alg5_values = new uint64[0x10000];
generate_alg5_values_64_8(alg5_values, rng_table);
rng_seed_forward_1 = new uint16[256*256];
generate_seed_forward_1(rng_seed_forward_1, rng_table);
rng_seed_forward_128 = new uint16[256*256];
generate_seed_forward_128(rng_seed_forward_128, rng_table);
}
void tm_64_8_test::process_test_case(uint8 * test_case, uint16 * rng_seed, int algorithm)
{
uint8 working_code[128];
for (int i = 0; i < 128; i++)
{
working_code[i] = test_case[i];
}
if (algorithm == 0)
{
alg0((uint64*)working_code, (uint64*)alg0_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
else if (algorithm == 1)
{
alg1((uint64*)working_code, (uint64*)regular_rng_values_lo, (uint64*)regular_rng_values_hi, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
else if (algorithm == 2)
{
alg2((uint64*)working_code, (uint64*)alg2_values, *rng_seed);
*rng_seed = rng_seed_forward_1[*rng_seed];
}
else if (algorithm == 3)
{
alg3((uint64*)working_code, (uint64*)regular_rng_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
else if (algorithm == 4)
{
alg1((uint64*)working_code, (uint64*)alg4_values_lo, (uint64*)alg4_values_hi, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
else if (algorithm == 5)
{
alg5((uint64*)working_code, (uint64*)alg5_values, *rng_seed);
*rng_seed = rng_seed_forward_1[*rng_seed];
}
else if (algorithm == 6)
{
alg6((uint64*)working_code, (uint64*)alg6_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
else if (algorithm == 7)
{
alg7((uint64*)working_code);
}
for (int i = 0; i < 128; i++)
{
test_case[i] = working_code[i];
}
}
void tm_64_8_test::run_iterations(uint8 * test_case, uint16 * rng_seed, int algorithm, int iterations)
{
uint16 working_code[128];
for (int i = 0; i < 128; i++)
{
working_code[i] = test_case[i];
}
if (algorithm == 0)
{
for (int i = 0; i < iterations; i++)
{
alg0((uint64*)working_code, (uint64*)alg0_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
}
else if (algorithm == 1)
{
for (int i = 0; i < iterations; i++)
{
alg1((uint64*)working_code, (uint64*)regular_rng_values_lo, (uint64*)regular_rng_values_hi, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
}
else if (algorithm == 2)
{
for (int i = 0; i < iterations; i++)
{
alg2((uint64*)working_code, (uint64*)alg2_values, *rng_seed);
*rng_seed = rng_seed_forward_1[*rng_seed];
}
}
else if (algorithm == 3)
{
for (int i = 0; i < iterations; i++)
{
alg3((uint64*)working_code, (uint64*)regular_rng_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
}
else if (algorithm == 4)
{
for (int i = 0; i < iterations; i++)
{
alg1((uint64*)working_code, (uint64*)alg4_values_lo, (uint64*)alg4_values_hi, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
}
else if (algorithm == 5)
{
for (int i = 0; i < iterations; i++)
{
alg5((uint64*)working_code, (uint64*)alg5_values, *rng_seed);
*rng_seed = rng_seed_forward_1[*rng_seed];
}
}
else if (algorithm == 6)
{
for (int i = 0; i < iterations; i++)
{
alg6((uint64*)working_code, (uint64*)alg6_values, *rng_seed);
*rng_seed = rng_seed_forward_128[*rng_seed];
}
}
else if (algorithm == 7)
{
for (int i = 0; i < iterations; i++)
{
alg7((uint64*)working_code);
}
}
} | true |
4f05f6048d5ea24e69a1a9c70e70767db8100e0c | C++ | pts211/CS206 | /student.cpp | UTF-8 | 1,399 | 3.140625 | 3 | [] | no_license | #include "student.h"
Student::Student()
{
}
int Student::getId() const
{
return id;
}
void Student::setId(int value)
{
id = value;
}
QString Student::getUsername() const
{
return username;
}
void Student::setUsername(const QString &value)
{
username = value;
}
QString Student::getFirstName() const
{
return firstName;
}
void Student::setFirstName(const QString &value)
{
firstName = value;
}
QString Student::getLastName() const
{
return lastName;
}
void Student::setLastName(const QString &value)
{
lastName = value;
}
QString Student::getMajor() const
{
return major;
}
void Student::setMajor(const QString &value)
{
major = value;
}
QVector<Course> Student::getCourses() const
{
return courses;
}
void Student::setCourses(const QVector<Course> &value)
{
courses = value;
}
void Student::addCourse(Course value)
{
courses.push_back(value);
}
int Student::getTotalHours() {
int total = 0;
foreach(Course c, courses) {
total += c.getHours();
}
return total;
}
int Student::getHoursTowards(QVector<Course> other) {
int total = 0;
foreach(Course sC, courses) {
foreach(Course oC, other) {
if((sC.getNumber() == oC.getNumber()) && (sC.getDepartment().compare(oC.getDepartment()) == 0)){
total += oC.getHours();
}
}
}
return total;
}
| true |
f4ebccde714fc9c45ac0a02dcfe377dc42a9353a | C++ | achen9/ee590 | /hw5/null.hh | UTF-8 | 278 | 2.59375 | 3 | [] | no_license | #ifndef _NULL_H_
#define _NULL_H_
#include "object.hh"
class Null : public Object {
public:
Null() {}
Null * clone() { return new Null(*this); }
bool is_null() { return true; }
std::string stringify() { return std::string("null"); }
};
#endif
| true |
e142eb86d3169ce5fd877decc3627ddeeb49bf2d | C++ | ricardoferreira68/Introducao_programacao_em_c | /ordem_inversa.cpp | UTF-8 | 475 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void)
{
int i, numero[10];
system("clear");
for(i=0;i<10;i++)
{
cout << "Digite o "<<i+1<<"o número: ";
cin >> numero[i];
}
cout << endl;
cout << "Relação dos números na ordem inversa"<<endl;
cout << "-----------------------------------"<<endl;
for(i=9;i>=0;i--)
{
cout << numero[i] << endl;
}
cout << "-----------------------------------"<<endl;
return 0;
}
| true |
39bd384e6730aea41c5833dcf382aa6d1441d5f5 | C++ | GregLando113/GWToolboxpp | /GWToolbox/GWToolbox/Viewer.h | UTF-8 | 1,554 | 2.984375 | 3 | [] | no_license | #pragma once
#include <Windows.h>
#include <d3d9.h>
/*
This class represents a window on screen where you can draw.
It stores the view transformation and sets up matrices in RenderBegin()
*/
class Viewer {
public:
Viewer();
void RenderSetupClipping(IDirect3DDevice9* device);
void RenderSetupProjection(IDirect3DDevice9* device);
virtual void Render(IDirect3DDevice9* device) = 0;
inline int GetX() const { return location_x_; }
inline int GetY() const { return location_y_; }
inline int GetWidth() const { return width_; }
inline int GetHeight() const { return height_; }
inline void SetX(int x) { location_x_ = x; }
inline void SetY(int y) { location_y_ = y; }
inline void SetWidth(int width) { width_ = width; }
inline void SetHeight(int height) { height_ = height; }
inline void SetLocation(int x, int y) { location_x_ = x; location_y_ = y; }
inline void SetSize(int width, int height) { width_ = width; height_ = height; }
void Translate(float x, float y) {
translation_x_ += x;
translation_y_ += y;
}
inline void Scale(float amount) { scale_ *= amount; }
void SetTranslation(float x, float y) {
translation_x_ = x;
translation_y_ = y;
}
inline void SetScale(float scale) { scale_ = scale; }
inline float GetScale() const { return scale_; }
inline float GetTranslationX() const { return translation_x_; }
inline float GetTranslationY() const { return translation_y_; }
protected:
float translation_x_;
float translation_y_;
float scale_;
int location_x_;
int location_y_;
int width_;
int height_;
};
| true |
64b801d7d586ad6326aefbf1be4f8d0047e97dcd | C++ | kjnh10/pcl | /library/cpp/math/sieve.hpp | UTF-8 | 2,989 | 3.1875 | 3 | [] | no_license | #pragma once
#include "../header.hpp"
//%snippet.set('sieve')%
//%snippet.config({'alias':'prime_factor_by_sieve'})%
//%snippet.fold()%
struct Sieve {/*{{{*/
// エラトステネスのふるい O(NloglogN)
ll n; // n: max number for defined minfactor and primes
vector<ll> minfactor; // [-1, 2, 3, 2, 5, 2, 7, 2, 3, ....]
vector<ll> primes; // [2, 3, 5, .......]
vector<int> mobius; // メビウス関数値
Sieve(ll n = 1) : n(n), minfactor(n + 1), mobius(n + 1, 1) { /*{{{*/
minfactor[0] = minfactor[1] = -1;
for (ll p = 2; p <= n; ++p) {
if (minfactor[p]) continue;
primes.push_back(p);
minfactor[p] = p;
mobius[p] = -1;
for (ll x = p * p; x <= n; x += p) {
if (!minfactor[x]) minfactor[x] = p;
if ((x / p) % p == 0) mobius[x] = 0;
else mobius[x] *= -1;
}
}
} /*}}}*/
bool is_prime(ll x) {/*{{{*/
if (x <= n) return minfactor[x] == x;
return sz(factor_list(x)) == 1;
}/*}}}*/
vector<ll> factor_list(ll x) { /*{{{*/
assert(0 < x && x <= n*n); // これが満たされないと正しく計算されない可能性がある。
vector<ll> res;
if (x <= n) {
while (x != 1) {
res.push_back(minfactor[x]);
x /= minfactor[x];
}
}
else {
for (ll i = 0; primes[i] * primes[i] <= x; i++) {
while (x % primes[i] == 0) {
res.pb(primes[i]);
x /= primes[i];
}
}
if (x != 1) res.pb(x);
}
return res; // [2, 3, 3, 5, 5, 5.....]
} /*}}}*/
vector<pair<ll, ll>> prime_factor(ll x) { /*{{{*/
// just change fl vector to map form
vector<ll> fl = factor_list(x);
if (fl.size() == 0) return {};
vector<pair<ll, ll>> res = {mp(fl[0], 0)};
for (ll p : fl) {
if (res.back().first == p) {
res.back().second++;
} else {
res.emplace_back(p, 1);
}
}
return res; // [(2,1), (3,2), (5,3), .....]
} /*}}}*/
vector<ll> divisors(ll x) { // 高速約数列挙{{{
vector<ll> res({1});
auto ps = prime_factor(x);
// 約数列挙
for (auto p : ps) {
ll s = (ll)res.size();
for (ll i = 0; i < s; ++i) {
ll v = 1;
for (ll j = 0; j < p.second; ++j) {
v *= p.first;
res.push_back(res[i] * v);
}
}
}
return res;
}/*}}}*/
};/*}}}*/
Sieve sv(1e6);
// How to use
// sv.primes // 素数のリスト
// sv.prime_factor(x); // 素因数分解
//%snippet.end()%
| true |
e7be49c2d2fa58bfbcd983b96aadfd8cdd20be1c | C++ | M-Kobryn/MK-Electronic | /Produkt.h | UTF-8 | 964 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <list>
using namespace std;
class Produkt
{
string nazwa;
double cena;
string opis;
public:
friend bool operator==(const Produkt& T1, const Produkt& T2);
Produkt();
Produkt(string nazwa, double cena, string opis);
void zmiana_danych(string nazwa, double cena, string opis);
void Print();
};
class Magazyn
{
int pojemnosc;
string stan;
list<Produkt> spis;
public:
list<Produkt> get_spis();
Magazyn(int pojemnosc, string stan);
void Zaktualizuj();
bool Dostepnosc(Produkt przedmiot);
void Dodanie_Produktu(string nazwa, double cena, string opis);
void Dodanie_Produktu(Produkt przedmiot);
void Usuwanie_Produktu(string nazwa, double cena, string opis);
void Print_list();
};
class Domowienie
{
int ilosc;
Produkt item;
public:
bool zloznie_zamowienia_na_towar();
void aktualizacja_stanu_magazynu(Magazyn Mag);
}; | true |
d86dccef14dab17b2906bcb25facc8d8ee9cc472 | C++ | tursynbekoff/robotic_hand | /Control/Sample_i2c_slave/Sample_i2c_slave.ino | UTF-8 | 1,766 | 3.140625 | 3 | [] | no_license | // Include the required Wire library for I2C<br>#include <Wire.h>
#include <Wire.h>
int LED = 4;
int x = 0;
char c;
void setup() {
// Define the LED pin as Output
pinMode (LED, OUTPUT);
// Start the I2C Bus as Slave on address 9
Wire.begin(9);
// Attach a function to trigger when something is received.
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void receiveEvent(int howMany) {
while (1 < Wire.available()) { // loop through all but the last
c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
x = Wire.read(); // receive byte as an integer
Serial.println(x); // print the integer
}
void loop() {
// receiveEvent;
//If value received is 0 blink LED for 200 ms
if(c == 'a'){
if (x == 100) {
digitalWrite(LED, HIGH);
Serial.print(x);
// delay(200);
// digitalWrite(LED, LOW);
// delay(200);
}
//If value received is 3 blink LED for 400 ms
else if (x == 200) {
digitalWrite(LED, HIGH);
delay(40);
}
else if (x = 50){
digitalWrite(LED, LOW);
delay(40);
}
}else if(c == 'b'){
if (x == 100) {
digitalWrite(LED, HIGH);
Serial.print(x);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
//If value received is 3 blink LED for 400 ms
else if (x == 200) {
digitalWrite(LED, HIGH);
delay(400);
digitalWrite(LED, LOW);
delay(40);
digitalWrite(LED, HIGH);
delay(400);
}
else if (x = 50){
digitalWrite(LED, LOW);
delay(40);
}
}
}
| true |
39d649d6269caab8120770cbe9baf4dab41fe090 | C++ | Mabdel-03/CS163-RedBlackTreeDeletion | /Node.h | UTF-8 | 616 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
class Node{
public:
//these function declarations are all pretty self explanatory :)
Node(int);
int getVal();
void setVal(int);
Node* getRight();
Node* getLeft();
Node* getParent();
void setRight(Node*);
void setLeft(Node*);
void setParent(Node*);
int getColor();
void setColor(int);
Node* getGrandParent();
Node* getUncle();
Node* getSibling();
void rotateRight();
void rotateLeft();
~Node();
private:
Node* left;
Node* right;
Node* parent;
int color;
int val;
};
| true |
2b56c47682e85634275664d791348aab3d62752f | C++ | yeshasvitirupachuri/graph_hri | /aonode.h | UTF-8 | 1,566 | 2.953125 | 3 | [] | no_license | #ifndef AONODE_H
#define AONODE_H
#include <iostream>
#include <vector>
using namespace std;
// Definition Node Class
class aoNode{
public:
int nCost; //The initial node cost is same for all the nodes
int nIndex; //Node Index
int nHyperArcs; //Each node has fixed number of hyperarcs in the global graph
bool nComplete; //A node is complete if all its Hyperarcs direct to child nodes
bool nSolved; //Is the node solved
vector<int> parentIndex; //Can put under protected
struct hyperArcs{
int hIndex;
bool hType; //hyperArcs Type AND(1) or OR
int nChild; //Number of child
int hCost; //HyperArc Cost: Sum of child node costs + number of child nodes
//TODO Pointers from One Node Hyperarcs to child nodes
vector<aoNode**> childPointer; //This doesnt have to be a vector as hyperarc child nodes are only two
};
hyperArcs *hArcs;
aoNode(vector<char> &); //Default Constructor
aoNode();//Default Copy Constructor
virtual ~aoNode(); //Default Destructor
bool isTerminal(vector<char> &);
void completeNode(); //This is the routine for completing node with all the hyperArcs directed to Child Node
// void addSuccessor(Node<N>*);
// Node<N>* deleteSuccessor();
// Node<N>* getNext();
// void setCost();
// void iterateCost();
// void isComplete(); //Check if the node is completed with all the hyperarcs
// bool isSolved(); // Also can be used for terminal node
// bool isTerminal();
};
#endif
| true |
88ddc9854b0b1c2977dd8b5ec5bef045dc13f0a1 | C++ | XMJYever/learn_CPP_Primer_plus | /C++practice/practice13_4/practice13_4/tabtenn1.h | UTF-8 | 772 | 3.09375 | 3 | [] | no_license | // tabtenn1.h -- a table-tennis base class
#ifndef TABTENN1_H_
#define TABTENN1_H_
#include <string>
using std::string;
// base class
class TableTennisPlayer
{
private:
string firstname;
string lastname;
bool hasTable;
public:
TableTennisPlayer(const string & fn = "none",
const string & ln = "none", bool ht = false);
bool HasTable() const { return hasTable; }
void Name() const;
void ResetTable(bool v) { hasTable = v; }
};
// simple derived class
class RatingPlayer : public TableTennisPlayer
{
private:
unsigned int rating;
public:
RatingPlayer(unsigned int r = 0, const string &fn = "none",
const string &ln = "none", bool ht = false);
RatingPlayer(unsigned int r, TableTennisPlayer & tp);
unsigned int Rating() const { return rating; }
};
#endif | true |
fc41a33f049a1a8c0a3f6a4d30e1820c639c55d7 | C++ | sejinik/Discovering_modern_cpp | /c++03/hello42.cpp | UTF-8 | 222 | 2.546875 | 3 | [] | no_license | #include <iostream>
int main(){
std::cout<<"The answer to Ultimate Question of Life, \n"
<<"the Universe, and Everything is:"
<<std::endl<<6*7<<std::endl;
return 0;
} | true |
4320085ab16e4120365b9df85043f4368274f7d0 | C++ | babest/embedded-systems | /Blatt06/aufgabe6.1/aufgabe6.1.ino | UTF-8 | 7,699 | 2.84375 | 3 | [] | no_license | #include <SPI.h>
#include <SD.h>
extern unsigned char font[95][6];
int PIN_SCE = 4;
int PIN_RESET = 6;
int PIN_DC = 8;
int PIN_SDIN = 4;
int PIN_SCLK = 3;
int PIN_BGLIGHT = 10;
int PIN_SCE_SD = 52;
int LCD_C = LOW;
int LCD_D = HIGH;
const int LCD_X = 84;
const int LCD_Y = 48;
const int LCD_BANKS = LCD_Y / 8;
const int LCD_CHAR_WIDTH = 6;
const int LCD_CPL = LCD_X / LCD_CHAR_WIDTH;
unsigned int LCD_Buffer[LCD_BANKS][LCD_X];
unsigned int LCD_POS = 0;
const char* authors[][3] = {
{"Timon", "Back", "6526091"},
{"Fabian", "Behrendt", "6534523"},
{"Nicolai", "Staeger", "6537387"}
};
void setup(void)
{
// Init Pins
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_BGLIGHT, OUTPUT);
//Serial
Serial.begin(9600);
// LCD RESET
digitalWrite(PIN_RESET, HIGH);
delay(100);
digitalWrite(PIN_RESET, LOW);
delay(500);
digitalWrite(PIN_RESET, HIGH);
// LCD Lighting
digitalWrite(PIN_BGLIGHT, HIGH);
// LCD SPI
SPI.begin(PIN_SCE);
SPI.setClockDivider(PIN_SCLK, 84);
// LCD SPI INIT
sendCommand(0x21); // 0010 0001
sendCommand(0x14); // 0001 0100
sendCommand(0xB1); // Set Contrast E0 = 1110 0000
sendCommand(0x20); // 0010 0000
sendCommand(0x0C); // 0000 1100
//LCD Test Data
drawString(2, "<Hello World>");
drawString(3, "--Hello World--");
// SD Init
pinMode(PIN_SCE_SD, OUTPUT);
Serial.println(SD.begin(PIN_SCE_SD));
}
void clearDisplay()
{
for (int y = 0; y < LCD_BANKS; ++y) {
for (int x = 0; x < LCD_X; x++) {
setByte(x, y, 0);
}
}
flushLCD();
}
int setPixel(unsigned int x, unsigned int y, unsigned int value) {
if (x < LCD_X && y < LCD_Y) {
int yBank = y / 8;
int yOffset = y % 8;
// Set the bit in the byte
LCD_Buffer[yBank][x] ^= (-value ^ LCD_Buffer[yBank][x]) & (1 << yOffset);
return 0;
}
return -1;
}
int setByte(unsigned int x, unsigned int yBank, unsigned int value) {
if (x < LCD_X && yBank < LCD_BANKS) {
// Set the byte
LCD_Buffer[yBank][x] = value;
return 0;
}
return -1;
}
int drawChar(unsigned int x, unsigned int yBank, char character)
{
if (x < LCD_X && yBank < LCD_BANKS) {
unsigned char* letter = font[character - 32];
if (x < LCD_X && yBank < LCD_BANKS) {
for (int i = 0; i < 6; ++i) {
setByte(x + i, yBank, *(letter + i));
}
}
flushLCD();
return 0;
}
return -1;
}
int drawString(unsigned int yBank, const char* string)
{
if (strlen(string) <= LCD_CPL || yBank < LCD_BANKS) {
int xStartPos = (LCD_X - (strlen(string) * LCD_CHAR_WIDTH)) / 2;
for (int i = 0; i < strlen(string); ++i) {
drawChar(xStartPos + (i * LCD_CHAR_WIDTH), yBank, string[i]);
}
flushLCD();
return 0;
}
return -1;
}
int readImageHeader(const char* header, unsigned int* x, unsigned int* y)
{
*y = 0;
*x = 0;
*x = atoi(header);
for(int i = 0; i < strlen(header); i++)
{
if(header[i] == ',')
{
*y = atoi(header + i + 1);
return 0;
}
}
return -1;
}
int drawImage(char* rawData)
{
unsigned int imageSizeX, imageSizeY;
char* pch = strtok(rawData, "\n");
readImageHeader(pch, &imageSizeX, &imageSizeY);
unsigned int xOffset, yOffset;
xOffset = (LCD_X - imageSizeX) / 2;
yOffset = (LCD_Y - imageSizeY) / 2;
for(int y = 0; y < imageSizeY; y++)
{
for(int x = 0; x < imageSizeX; x++)
{
pch = strtok(NULL, ",\n");
setPixel(x+xOffset, y+yOffset, (*pch == '1') );
}
}
flushLCD();
}
int scrollString(unsigned int yBank, const char* string) {
//Temporärer String Buffer, der einmal komplett aufs Display passt
char drawStringBuffer[LCD_CPL + 1];
//Den temporären String Buffer terminieren (strlen muss funktionieren)
drawStringBuffer[LCD_CPL] = '\0';
//loopCounterMax definiert die Druchgänge in der Schleife [Scrollschritte]
unsigned int loopCounterMax = strlen(string);
if(loopCounterMax < LCD_CPL) {
//Der Text passt aufs Display? Dann kein Scrollen, nur anzeigen
loopCounterMax = 1;
} else if(LCD_CPL < strlen(string)) {
//Der Text muss gescrollt werden.
//Aber nur bis zum letzten Zeichen. Keine Leerzeichen am Ende
loopCounterMax-= LCD_CPL + 1;
}
//Den Text anzeigen
for(int i=0; i<loopCounterMax; i++) {
//Aktuellen Textausschnitt in den Buffer kopieren
strncpy(drawStringBuffer, string+i, LCD_CPL);
//Text auf dem Display anzeigen
drawString(yBank, drawStringBuffer);
//Dem Mensch die Chance lassen, den Text zu lesen
delay(250);
}
}
void sendCommand(unsigned int value) {
digitalWrite(PIN_DC, LCD_C);
SPI.transfer(PIN_SDIN, value);
}
void sendData(unsigned int value) {
digitalWrite(PIN_DC, LCD_D);
SPI.transfer(PIN_SDIN, value);
}
// Write the Buffer to the display
void flushLCD() {
for (int y = 0; y < LCD_BANKS; y++) {
for (int x = 0; x < LCD_X; x++) {
sendData(LCD_Buffer[y][x]);
}
}
}
// TODO: remove if not needed
void gotoXY(unsigned int x, unsigned int y)
{
if (x < LCD_X && y < LCD_Y) {
sendCommand(0x80 | x); //column
sendCommand(0x40 | y); //row
LCD_POS = (LCD_X * y) + x;
}
}
int readFileToBuffer(char* filename, char *buffer, unsigned int length) {
if (SD.exists(filename)) {
//File exists
//Open the file
File dataFile = SD.open(filename);
if (dataFile) {
//File is opened
//Counter for amount of bytes read from the file
unsigned int bytesRead = 0;
//Read the bytes as long as there are still bytes and the buffer is large enough
while (dataFile.available() && bytesRead < length) {
char character = dataFile.read();
*(buffer+bytesRead) = character;
bytesRead++;
}
//Terminate buffer
*(buffer+bytesRead) = '\n';
//Clean up
dataFile.close();
return bytesRead;
} else {
Serial.println("Cant open");
return -1;
}
}
Serial.println("Does not exist");
return -2;
}
void loop(void)
{
/*int imageTextLength = LCD_X * LCD_Y * 2 + 20;
char textContent[imageTextLength];
clearDisplay();
clearString(textContent, imageTextLength);
readFileToBuffer("TAMS.IMG", textContent, imageTextLength);
drawImage(textContent);
delay(1000);
clearDisplay();
clearString(textContent, imageTextLength);
readFileToBuffer("SMILE1.IMG", textContent, imageTextLength);
drawImage(textContent);
delay(1000);
clearDisplay();
clearString(textContent, imageTextLength);
readFileToBuffer("SMILE2.IMG", textContent, imageTextLength);
drawImage(textContent);
delay(1000);
clearDisplay();
clearString(textContent, imageTextLength);
readFileToBuffer("SMILE3.IMG", textContent, imageTextLength);
drawImage(textContent);
delay(1000);
return;*/
char textContent[200];
clearString(textContent, 200);
readFileToBuffer("TEXT1.TXT", textContent, 200);
scrollString(0, textContent);
clearString(textContent, 200);
readFileToBuffer("TEXT2.TXT", textContent, 200);
scrollString(1, textContent);
delay(2000);
return;
for (int i = 0; i < 3; ++i) {
clearDisplay();
drawString(1, authors[i][0]);
drawString(2, authors[i][1]);
drawString(3, authors[i][2]);
delay(5000);
}
}
void clearString(char* buffer, unsigned int length) {
for(int i=0; i<length;++i) {
buffer[i] = '\0';
}
}
void drawChessField()
{
// Create a chess field
for (int y = 0; y < LCD_Y; y = y + 2) {
for (int x = 0; x < LCD_X; x++) {
setPixel(x, y, x % 2);
setPixel(x, y + 1, (1 - (x % 2)));
}
}
flushLCD();
}
| true |
3a50b32709d515a82fb06552375c460c5877363b | C++ | Make-It-Work/RandomDungeon | /RandomDungeon/RandomDungeon/Enemy.cpp | UTF-8 | 1,611 | 3.25 | 3 | [] | no_license | #include "stdafx.h"
#include "Enemy.h"
#include <string>
#include <map>
#include <iostream>
Enemy::Enemy()
{
}
Enemy::~Enemy()
{
}
int Enemy::attack() {
std::cout << "Your enemy attacked, you lost " << strength << " of your health points"<< std::endl;
return strength;
}
bool Enemy::hit() {
if (level <= 4) {
health -= sensitivity;
if (checkAlive()) {
std::cout << "You have done a little damage to your enemy, but he's still alive" << std::endl;
return true;
}
else {
std::cout << "You killed the " << name << "." << std::endl;
return false;
}
}
else {
std::cout << "Your enemy blinks his eyes in shock, but is still as strong as before" << std::endl;
}
return checkAlive();
}
bool Enemy::stabbed(int weaponStrength) {
health -= weaponStrength;
if (checkAlive()) {
std::cout << "You have done a little damage to your enemy, but he's still alive" << std::endl;
return false;
}
else {
std::cout << "You killed the " << name << "." << std::endl;
return true;
}
}
bool Enemy::checkAlive() {
if (health <= 0) {
return false;
}
return true;
}
void Enemy::setProperties(std::map<std::string, std::string> props) {
for (auto kv : props) {
if (kv.first == "level") {
level = std::stoi(kv.second);
} else if (kv.first == "health") {
health = std::stoi(kv.second);
} else if (kv.first == "sensitivity") {
sensitivity = std::stoi(kv.second);
} else if (kv.first == "strength") {
strength = std::stoi(kv.second);
} else if (kv.first == "type") {
type = std::stoi(kv.second);
} else if (kv.first == "name") {
name = kv.second;
}
}
}
| true |
48215524b8da77d2c18a8b78650e3d20a8da468e | C++ | MTASZTAKI/ApertusVR | /core/sceneManager/network/3rdParty/raknet/DependentExtensions/DXTCompressor/Src/main.cpp | UTF-8 | 4,855 | 2.90625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "DXTCompressor.h"
/* ------------------------------------------------------------------------------------------------------------------------------------ */
bool LoadTGAFromFile( const char* pFilename, void **image, int* width, int* height )
{
typedef struct
{
char identsize;
char colourmaptype;
char imagetype;
unsigned short colourmapstart;
unsigned short colourmaplength;
char colourmapbits;
unsigned short xstart;
unsigned short ystart;
unsigned short width;
unsigned short height;
char bits;
char descriptor;
} TGA_HEADER;
// Open the file
FILE* pic;
if((pic=fopen( pFilename, "rb"))==NULL )
{
return false;
}
// Zero out the header
TGA_HEADER TGAheader;
memset(&TGAheader,0,sizeof(TGA_HEADER));
// Read the header
fread(&TGAheader.identsize,sizeof(char),1,pic);
fread(&TGAheader.colourmaptype,sizeof(char),1,pic);
fread(&TGAheader.imagetype,sizeof(char),1,pic);
fread(&TGAheader.colourmapstart,sizeof(unsigned short),1,pic);
fread(&TGAheader.colourmaplength,sizeof(unsigned short),1,pic);
fread(&TGAheader.colourmapbits,sizeof(char),1,pic);
fread(&TGAheader.xstart,sizeof(unsigned short),1,pic);
fread(&TGAheader.ystart,sizeof(unsigned short),1,pic);
fread(&TGAheader.width,sizeof(unsigned short),1,pic);
fread(&TGAheader.height,sizeof(unsigned short),1,pic);
fread(&TGAheader.bits,sizeof(char),1,pic);
fread(&TGAheader.descriptor,sizeof(char),1,pic);
*width = TGAheader.width;
*height = TGAheader.height;
int DataSize = TGAheader.width*TGAheader.height*4;
// Read the pixels
*image = new char[DataSize];
if ((TGAheader.descriptor>>5) & 1)
{
// Right side up
fread(*image, sizeof(char),DataSize, pic);
}
else
{
//Upside down
for (int row=TGAheader.height-1; row >=0; row--)
{
fread(((char*) (*image))+row*TGAheader.width*TGAheader.bits/8, TGAheader.bits/8, TGAheader.width, pic);
}
}
// Close the file
fclose(pic);
// TGA is stored on disk BGRA
// Endian swap bits so that the image is actually in RGBA format
if( TGAheader.bits == 32 )
{
unsigned char* pRunner = (unsigned char*)*image;
for( int i = 0; i < DataSize; i+=4 )
{
char color[4] =
{
pRunner[ 0 ],
pRunner[ 1 ],
pRunner[ 2 ],
pRunner[ 3 ],
};
pRunner[ 0 ] = color[ 2 ];
pRunner[ 1 ] = color[ 1 ];
pRunner[ 2 ] = color[ 0 ];
pRunner[ 3 ] = color[ 3 ];
pRunner += 4;
}
}
return true;
}
/* ------------------------------------------------------------------------------------------------------------------------------------ */
int main( int argc, const char* argv[] )
{
// Initialize the compressor
DXTCompressor::Initialize();
// Load sample .tga
void* pSourceData;
int w, h;
//bool bFileLoaded = LoadTGAFromFile( "1600x1200.tga", &pSourceData, &w, &h );
bool bFileLoaded = LoadTGAFromFile( "320x200.tga", &pSourceData, &w, &h );
if( bFileLoaded )
{
// Test performance
// const int numIterations = 100;
// for( int i = 0; i < numIterations; i++ )
// {
// // Compress the data
// void* pOutputData;
// int outputLength;
// bool bCompressSuccess = DXTCompressor::CompressRGBAImageData( DXT1, pSourceData, w, h, &pOutputData, &outputLength, false );
//
// // Clean up
// delete [] pOutputData;
// pOutputData = NULL;
// }
// Print total stats
// printf( "\n\n****Total stats on %d iterations****\n", numIterations );
// DXTCompressor::PrintPerformanceLog();
// Now test saving to DDS memory file
{
// Compress the data
// void* pCompressedOutput;
// int compressedOutputLength;
// bool bCompressSuccess = DXTCompressor::CompressRGBAImageData( DXT1, pSourceData, w, h, &pCompressedOutput, &compressedOutputLength, false );
char *outputData;
int bufferSize = DXTCompressor::GetBufferSize(DXT1,
w,
h);
int ddsHeaderSize = DXTCompressor::GetDDSHeaderSize();
outputData = (char*) malloc(bufferSize + ddsHeaderSize );
bool bCompressSuccess = DXTCompressor::CompressRGBAImageData(
DXT1,
pSourceData,
w,
h,
outputData+ddsHeaderSize, false );
if( bCompressSuccess )
{
// Save DDS file
// void* pOutputDDSFile;
// int outputDDSFileLength;
// DXTCompressor::WriteDDSMemoryFile( DXT1, w, h, pCompressedOutput, compressedOutputLength, &pOutputDDSFile, &outputDDSFileLength );
// Clean up
// delete [] pCompressedOutput;
// pCompressedOutput = NULL;
// delete [] pOutputDDSFile;
// pOutputDDSFile = NULL;
DXTCompressor::WriteDDSHeader(DXT1,
w,
h,
bufferSize,
outputData);
FILE *fp = fopen("DXTCompressorTGAtoDDS.dds", "wb");
fwrite(outputData,1,bufferSize + ddsHeaderSize,fp);
fclose(fp);
free(outputData);
}
}
}
// Shutdown the compressor
DXTCompressor::Shutdown();
return 0;
} | true |
c1d6a111756f9d6e8e6974d8233b160d417178f7 | C++ | Darling1116/Darling_1116 | /lesson_8_19/Algorithm_1/test_1.h | GB18030 | 988 | 3.53125 | 4 | [] | no_license | #pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <unordered_set>
using namespace std;
//һַsһ鵥dictжsǷÿոָһ
//ʹõеĵʶdictеĵʣпһʣ
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.empty())
return true; //ַҲҪ
//arrayʾǰiַָܷ
vector<bool> array(s.length() + 1, false);
array[0] = true;
for (int i = 1; i <= s.length(); i++){
for (int j = 0; j < i; j++){
//ǰjַԱָj-iеַdictҵ
if (array[j] && (dict.find(s.substr(j, i - j)) != dict.end())){
array[i] = true;
break;
}
}
}
return array[s.length()];
}
void test1_1(){
string s = "nowcode";
unordered_set<string> dict = {"now", "code"};
cout << wordBreak(s, dict) << endl;
} | true |
f745ce948c3f1062a66e2118aac15a366e30b113 | C++ | liuhangyang/Study_notes | /C++_code/第三章/34.cpp | UTF-8 | 929 | 2.765625 | 3 | [] | no_license | /*************************************************************************
> File Name: 34.cpp
> Author:yang
> Mail:yanglongfei@xiyoulinux.org
> Created Time: 2015年11月29日 星期日 09时38分27秒
************************************************************************/
#include<iostream>
int main(int argc,char *argv[])
{
int a[3][4]={};
int (*p)[4]=a;
using int_array=int[4]; //等价于typedef int int_array;
for( p=a;p!=a+3;p++){
for(int *q=*p;q!=*p+4;q++){
std::cout << *q<<" ";
}
std::cout << std::endl;
}
for( int (*p)[4]=std::begin(a);p!=std::end(a);p++){
for(int *q=std::begin(*p);q!=std::end(*p);q++){
std::cout << *q<<" ";
}
std::cout<<std::endl;
}
/*for(int_array *p=a;p!=a+3;p++){
for(int *q=*p;q!=*p+4;q++){
std::cout << *q<<" ";
}
std::cout<<std::endl;
}*/
return 0;
}
| true |
c7c8b834a4c63c85c72321993d1ca78b8b4e92da | C++ | XoDeR/DODCallback | /Src/Entity.cpp | UTF-8 | 563 | 2.8125 | 3 | [] | no_license | #include "Entity.h"
#include "Registry.h"
// to see the output
#include <iostream>
//
Entity::Entity(Registry& registry)
: registry(registry)
{
EntityCallback entityCallback;
typedef void(*VoidFunction)();
entityCallback.f = (VoidFunction)(&Entity::entityFunction);
entityCallback.instance = (void*)(this);
registry.registerEntityCallback(entityCallback);
}
void Entity::memberFunction(int a)
{
std::cout << a;
std::cin >> a; // for pause
}
void Entity::entityFunction(void* instance, int a)
{
static_cast<Entity*>(instance)->memberFunction(a);
}
| true |
2e1417e073922fe71285f748ffebefffd585eb97 | C++ | larnin/Awesome_rogue_tools | /Awesome_rogue_editor/src/Map/hitbox.h | UTF-8 | 783 | 2.625 | 3 | [] | no_license | #ifndef HITBOX_H
#define HITBOX_H
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <vector>
struct Line
{
Line(const sf::Vector2f & _pos1, const sf::Vector2f & _pos2)
: pos1(_pos1), pos2(_pos2) {}
sf::Vector2f pos1;
sf::Vector2f pos2;
Line move(const sf::Vector2f & delta) const;
bool sameAs(const Line & l, float epsilon);
};
class HitBox
{
public:
HitBox() = default;
~HitBox() = default;
void addLine(const Line & l);
sf::FloatRect globalRect() const;
HitBox transform(float rotation, bool xFlip, bool yFlip) const;
std::vector<Line> lines;
};
sf::VertexArray toRender(const HitBox & box, const sf::Color & color = sf::Color::White);
#endif // HITBOX_H
| true |
efb11c3b5396fc52bec7b5e770784c70dd88e51b | C++ | eliogovea/solutions_cp | /Kattis/oil2.cpp | UTF-8 | 2,311 | 2.703125 | 3 | [] | no_license | // https://icpc.kattis.com/problems/oil2
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2005;
inline int sign(LL x) {
if (x < 0) {
return -1;
}
if (x > 0) {
return 1;
}
return 0;
}
struct pt {
int x, y;
};
pt operator - (const pt &a, const pt &b) {
return (pt) {a.x - b.x, a.y - b.y};
}
LL cross(const pt &a, const pt &b) {
return (LL)a.x * b.y - (LL)a.y * b.x;
}
LL norm2(const pt &a) {
return (LL)a.x * a.x + (LL)a.y * a.y;
}
bool operator < (const pt &a, const pt &b) {
int c = sign(cross(a, b));
if (c != 0) {
return c > 0;
}
return norm2(a) < norm2(b);
}
struct event {
pt p;
int value;
};
bool operator < (const event &a, const event &b) {
int c = sign(cross(a.p, b.p));
if (c != 0) {
return c > 0;
}
return a.value > b.value;
}
int n;
int x0[N], x1[N], y[N];
LL solve(pt P) {
vector <event> E;
for (int i = 0; i < n; i++) {
if (y[i] == P.y) {
continue;
}
if (y[i] > P.y) {
pt P0 = (pt) {x0[i], y[i]} - P;
pt P1 = (pt) {x1[i], y[i]} - P;
if (P1 < P0) {
swap(P0, P1);
}
E.push_back((event) {P0, abs(x0[i] - x1[i])});
E.push_back((event) {P1, -abs(x0[i] - x1[i])});
} else {
pt P0 = P - (pt) {x0[i], y[i]};
pt P1 = P - (pt) {x1[i], y[i]};
if (P1 < P0) {
swap(P0, P1);
}
E.push_back((event) {P0, abs(x0[i] - x1[i])});
E.push_back((event) {P1, -abs(x0[i] - x1[i])});
}
}
sort(E.begin(), E.end());
LL cur = 0;
LL best = 0;
for (int i = 0; i < E.size(); i++) {
cur += (LL)E[i].value;
assert(cur >= 0);
best = max(best, cur);
}
return best;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
//freopen("input.txt", "r", stdin);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x0[i] >> x1[i] >> y[i];
}
LL ans = 0;
for (int i = 0; i < n; i++) {
ans = max(ans, solve((pt) {x0[i], y[i]}) + abs(x0[i] - x1[i]));
ans = max(ans, solve((pt) {x1[i], y[i]}) + abs(x0[i] - x1[i]));
}
cout << ans << "\n";
}
| true |
48cebc4a73d5f7793414d7c1bf2f2e3481117138 | C++ | anshu06468/lifecycle | /heap.cpp | UTF-8 | 1,144 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include <cmath>
using namespace std;
int count=0;
void print(int a[],int n)
{
for(int i=1;i<=n;i++)
cout<<i<<"\t"<<a[i]<<endl;
}
void heap(int a[],int k,int sz)
{ int l=2*k;
int r=2*k+1;
int largest=0;
if(l>sz && r>sz)
return;
if(l<=sz && a[l]>a[k]) {
count++;
largest=l;
}
else {
largest=k;
count++;}
if(r<=sz && a[r]>a[largest])
{
count++;
largest=r;
}
else if(a[r]<a[largest])
count++;
if(largest!=k)
{
int temp=a[k];
a[k]=a[largest];
a[largest]=temp;
}
else
return;
heap(a,largest,sz);
}
void Maxheap(int a[],int n)
{
int non_l=floor(n/2);
for(int i=non_l;i>=1;i--)
heap(a,i,n);
}
void sort(int a[],int n)
{
Maxheap(a,n);
for(int i=n;i>=2;i--)
{
int temp;
temp=a[1];
a[1]=a[i];
a[i]=temp;
heap(a,1,i-1);
}
}
int main()
{
int a[50],sz,root;
cout<<"Enter the number of elements\n";
cin>>sz;
cout<<"Enter the elements\n";
for(int i=1;i<=sz;i++)
cin>>a[i];
cout<<"array after sorting\n";
sort(a,sz);
cout<<"Index\tElement\n";
print(a,sz);
cout<<"no. of comparisons"<<count<<endl;
return 0;
}
| true |
c4045cdf23c0772c0bb5aa94ed3ee892a7178a59 | C++ | LiuYangMrLY/Cpp-Experiment | /special/5/CppExp.cpp | GB18030 | 1,356 | 3.34375 | 3 | [] | no_license | #include "Image.cpp"
#include <iostream>
using namespace std;
int main()
{
Image img;
img.Read("Fruits.jpg");
img.Write("FruitsCopy.jpg");
cvNamedWindow("Image", CV_WINDOW_AUTOSIZE);
img.Show("Image");
//·ת img.Flip(true)
img.Flip(true);
img.Show("Image");
// ҷת img.Filp(false)
img.Flip(false);
img.Show("Image");
// ͼŴ img.Resize(true)
img.Resize(true);
img.Show("Image");
//ͼС img.Resize(false)
img.Resize(false);
img.Show("Image");
//ȡͼijֵ,
cout << int(img.At(100, 100));
img.Set(0, 100, 100);
//ʹÿ캯µĶ
Image new_img(img);
//ȡָڵͼ,ʾ
new_img.Cut(100, 100, 200, 200);
new_img.Show("Cut_Image");
//תͼʾתǶΪ90ȵ
img.Rotate(90);
img.Show("Image");
//ͼľֵͷ
float m = 0;
float var = 0;
img.Mean_Variance(m, var);
cout << "ֵ" << m << endl;
cout << "" << var << endl;
//ͼ
Image img1("Baboon.jpg");
Image img2("Lena.jpg");
img1.Show("Image1");
img2.Show("Image2");
Swap(img1, img2);
img1.Show("Image1");
img2.Show("Image2");
return 0;
}
| true |
d2c832d6cb38de99f2638c3c145c76122b6d1f9f | C++ | Hybbon/spc | /roteiro00/spojbr_minhoca/main.cpp | UTF-8 | 799 | 3.578125 | 4 | [] | no_license | // A solução para o problema consiste em verificar o maior valor dentre as
// somas de cada coluna e de cada linha. O maior valor encontrado corresponde
// ao maior número de minhocas que pode ser coletado.
#include <iostream>
#include <vector>
int main(){
int n, m;
std::cin >> n >> m;
std::vector<int> columns(m);
int max_sum = 0;
for (int i = 0; i < n; i++){
int row_sum = 0;
for (int j = 0; j < m; j++){
int temp;
std::cin >> temp;
columns[j] += temp;
row_sum += temp;
}
if (row_sum > max_sum){
max_sum = row_sum;
}
}
for (int col_sum : columns){
if (col_sum > max_sum){
max_sum = col_sum;
}
}
std::cout << max_sum << '\n';
}
| true |
c2aec816af8975d0ac8824b218d40bada798af45 | C++ | Yumin2019/Tetris-Console | /Tetris Console/Object/CShapeS.cpp | UTF-8 | 1,255 | 3 | 3 | [] | no_license | #include "CShapeS.h"
CShapeS::CShapeS()
{
}
CShapeS::CShapeS(const CShapeS & s) :
CShape(s)
{
}
CShapeS::~CShapeS()
{
}
bool CShapeS::Init()
{
m_eShape = ST_S;
m_tShape[1][2] = '0';
m_tShape[1][3] = '0';
m_tShape[2][1] = '0';
m_tShape[2][2] = '0';
return true;
}
void CShapeS::Rotation(bool left)
{
if (left)
m_iRotation += 90;
else
m_iRotation -= 90;
if (m_iRotation == 360)
m_iRotation = 0;
else if (m_iRotation == -90)
m_iRotation = 270;
bool bRotation = false;
switch (m_iRotation)
{
case 0:
case 180:
if (IsRotation(1, 2) &&
IsRotation(1, 3) &&
IsRotation(2, 1) &&
IsRotation(2, 2))
{
memset(m_tShape, '1', 16);
m_tShape[1][2] = '0';
m_tShape[1][3] = '0';
m_tShape[2][1] = '0';
m_tShape[2][2] = '0';
bRotation = true;
}
break;
case 90:
case 270:
if (IsRotation(0, 2) &&
IsRotation(1, 2) &&
IsRotation(1, 3) &&
IsRotation(2, 3))
{
memset(m_tShape, '1', 16);
m_tShape[0][2] = '0';
m_tShape[1][2] = '0';
m_tShape[1][3] = '0';
m_tShape[2][3] = '0';
bRotation = true;
}
break;
}
if (!bRotation)
{
if (left)
m_iRotation -= 90;
else
m_iRotation += 90;
}
}
CShapeS * CShapeS::Clone()
{
return new CShapeS(*this);
}
| true |
bab6da83c3d9bfc8191cba07fc123ec76b54dd36 | C++ | sapsey19/2019CppProjects | /ProgLangHW3/main.cpp | UTF-8 | 1,887 | 3.46875 | 3 | [] | no_license | #include <string>
#include <fstream>
using namespace std;
ofstream out;
char token;
string expression;
int counter = 0;
int error = 0;
//function declarations
void exp();
void term();
void factor();
void number();
void digit();
void parse();
void getToken() {
token = expression[counter];
//if there's a space, ignore
if (token == ' ') {
counter++;
token = expression[counter];
}
//no need to print new line on first call
if (counter == 0)
out << "<getToken> " << token;
else if (counter < expression.length())
out << endl << "<getToken> " << token;
counter++;
}
void exp() {
if(isdigit(token))
out << " <exp> ";
term();
while (token == '+') {
getToken();
term();
}
}
void term() {
if(isdigit(token))
out << " <term> ";
factor();
while (token == '*') {
getToken();
factor();
}
}
void factor() {
if(isdigit(token))
out << " <factor> ";
if (token == '(') {
getToken();
if(isdigit(token))
out << " <factor> ";
exp();
if (token == ')')
getToken();
else
error = 1;
}
else
number();
}
void number() {
if(isdigit(token))
out << " <number> ";
digit();
while (isdigit(token))
digit();
}
void digit() {
if(isdigit(token))
out << " <digit> ";
if (isdigit(token))
getToken();
else
error = 2;
}
void parse() {
out << "<parse>" << endl;
getToken();
exp();
}
int main() {
ifstream in;
in.open("input.txt");
out.open("output.txt");
while(!in.eof()) {
getline(in, expression);
if(expression != "") {
parse();
switch (error) {
case 0: out << endl << "Parsed correctly!" << endl;
break;
case 1: out << endl << "Parse failed: Expected closing parentheses" << endl;
break;
case 2: out << endl << "Parse failed: Expected digit" << endl;
break;
}
//renint variables
counter = 0;
error = false;
out << endl;
}
}
in.close();
out.close();
return 0;
}
| true |
3e7b24f332f1c26a5a298edf9f7cd85585d2a29b | C++ | kidc2458/Q1 | /Q1-A/Q1-A.cpp | UTF-8 | 339 | 2.859375 | 3 | [] | no_license | // ConsoleApplication1.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include "pch.h"
#include <iostream>
int main()
{
for (int i = 0; i < 81; ++i)
std::cout << (i / 9 + 1) << " X " << (i % 9 + 1) << " = " << (i / 9 + 1)*(i % 9 + 1) << '\n';
return 0;
} | true |
cc2ca924b44b67b06848f0ea0d7dfcf783d28560 | C++ | d-cheung/EC527-Project | /Serial Code/FastHessian.cpp | UTF-8 | 10,778 | 2.84375 | 3 | [] | no_license | #include "IPoint.h"
#include <cmath>
#include <vector>
#include "FastHessian.h"
#include "IntegralImage.h"
// Static one-call do it all method
std::vector<IPoint> * FastHessian::getIpoints(float thresh, int octaves, int init_sample, IntegralImage * img)
{
FastHessian fh(thresh, octaves, init_sample, img);
return fh.getIpoints();
}
// Constructor with parameters
FastHessian::FastHessian(float thresh, int octaves, int init_sample, IntegralImage * img)
{
this->thresh = thresh;
this->octaves = octaves;
this->init_sample = init_sample;
this->img = img;
this->ipts = NULL;
this->responseMap = NULL;
}
FastHessian::~FastHessian()
{
if (responseMap != NULL) {
for (int ii = 0; ii < responseMap->size(); ii++)
delete (*responseMap)[ii];
delete responseMap;
}
}
// Find the image features and write into vector of features
std::vector<IPoint> * FastHessian::getIpoints()
{
// filter index map
int filter_map[5][4] = {{0,1,2,3}, {1,3,4,5}, {3,5,6,7}, {5,7,8,9}, {7,9,10,11}};
// Clear the vector of exisiting ipts
if (ipts == NULL) ipts = new std::vector<IPoint>();
else ipts->clear();
// Build the response map
buildResponseMap();
// Get the response layers
ResponseLayer * b, * m, * t;
for (int o = 0; o < octaves; ++o) for (int i = 0; i <= 1; ++i)
{
b = (*responseMap)[filter_map[o][i]];
m = (*responseMap)[filter_map[o][i+1]];
t = (*responseMap)[filter_map[o][i+2]];
// loop over middle response layer at density of the most
// sparse layer (always top), to find maxima across scale and space
for (int r = 0; r < t->height; ++r)
{
for (int c = 0; c < t->width; ++c)
{
if (isExtremum(r, c, *t, *m, *b))
{
interpolateExtremum(r, c, *t, *m, *b);
}
}
}
}
return ipts;
}
// Build map of DoH responses
void FastHessian::buildResponseMap()
{
// Calculate responses for the first 4 octaves:
// Oct1: 9, 15, 21, 27
// Oct2: 15, 27, 39, 51
// Oct3: 27, 51, 75, 99
// Oct4: 51, 99, 147,195
// Oct5: 99, 195,291,387
// Deallocate memory and clear any existing response layers
if (responseMap == NULL) responseMap = new std::vector<ResponseLayer *>();
else responseMap->clear();
// Get image attributes
int w = (img->Width / init_sample);
int h = (img->Height / init_sample);
int s = (init_sample);
// Calculate approximated determinant of hessian values
if (octaves >= 1)
{
responseMap->push_back(new ResponseLayer(w, h, s, 9));
responseMap->push_back(new ResponseLayer(w, h, s, 15));
responseMap->push_back(new ResponseLayer(w, h, s, 21));
responseMap->push_back(new ResponseLayer(w, h, s, 27));
}
if (octaves >= 2)
{
responseMap->push_back(new ResponseLayer(w / 2, h / 2, s * 2, 39));
responseMap->push_back(new ResponseLayer(w / 2, h / 2, s * 2, 51));
}
if (octaves >= 3)
{
responseMap->push_back(new ResponseLayer(w / 4, h / 4, s * 4, 75));
responseMap->push_back(new ResponseLayer(w / 4, h / 4, s * 4, 99));
}
if (octaves >= 4)
{
responseMap->push_back(new ResponseLayer(w / 8, h / 8, s * 8, 147));
responseMap->push_back(new ResponseLayer(w / 8, h / 8, s * 8, 195));
}
if (octaves >= 5)
{
responseMap->push_back(new ResponseLayer(w / 16, h / 16, s * 16, 291));
responseMap->push_back(new ResponseLayer(w / 16, h / 16, s * 16, 387));
}
// Extract responses from the image
for (unsigned int i = 0; i < responseMap->size(); ++i)
{
buildResponseLayer(*((*responseMap)[i]));
}
}
// Build Responses for a given ResponseLayer
void FastHessian::buildResponseLayer(ResponseLayer &rl)
{
int step = rl.step; // step size for this filter
int b = (rl.filter - 1) / 2; // border for this filter
int l = rl.filter / 3; // lobe for this filter (filter size / 3)
int w = rl.filter; // filter size
float inverse_area = (float)1.0 / (w * w); // normalisation factor
float Dxx, Dyy, Dxy;
for (int r, c, ar = 0, index = 0; ar < rl.height; ++ar)
{
for (int ac = 0; ac < rl.width; ++ac, index++)
{
// get the image coordinates
r = ar * step;
c = ac * step;
// Compute response components
Dxx = img->BoxIntegral(r - l + 1, c - b, 2 * l - 1, w)
- img->BoxIntegral(r - l + 1, c - l / 2, 2 * l - 1, l) * 3;
Dyy = img->BoxIntegral(r - b, c - l + 1, w, 2 * l - 1)
- img->BoxIntegral(r - l / 2, c - l + 1, l, 2 * l - 1) * 3;
Dxy = + img->BoxIntegral(r - l, c + 1, l, l)
+ img->BoxIntegral(r + 1, c - l, l, l)
- img->BoxIntegral(r - l, c - l, l, l)
- img->BoxIntegral(r + 1, c + 1, l, l);
// Normalise the filter responses with respect to their size
Dxx *= inverse_area;
Dyy *= inverse_area;
Dxy *= inverse_area;
// Get the determinant of hessian response & laplacian sign
rl.responses[index] = (Dxx * Dyy - (float)0.81 * Dxy * Dxy);
rl.laplacian[index] = (unsigned char)(Dxx + Dyy >= 0 ? 1 : 0);
}
}
}
// Test whether the point r,c in the middle layer is extremum in 3x3x3 neighbourhood
bool FastHessian::isExtremum(int r, int c, ResponseLayer &t, ResponseLayer &m, ResponseLayer &b)
{
// bounds check
int layerBorder = (t.filter + 1) / (2 * t.step);
if (r <= layerBorder || r >= t.height - layerBorder || c <= layerBorder || c >= t.width - layerBorder)
return false;
// check the candidate point in the middle layer is above thresh
float candidate = m.getResponse(r, c, t);
if (candidate < thresh)
return false;
for (int rr = -1; rr <= 1; ++rr)
{
for (int cc = -1; cc <= 1; ++cc)
{
// if any response in 3x3x3 is greater candidate not maximum
if (t.getResponse(r + rr, c + cc) >= candidate ||
((rr != 0 || cc != 0) && m.getResponse(r + rr, c + cc, t) >= candidate) ||
b.getResponse(r + rr, c + cc, t) >= candidate)
{
return false;
}
}
}
return true;
}
// Interpolate scale-space extrema to subpixel accuracy to form an image feature
void FastHessian::interpolateExtremum(int r, int c, ResponseLayer &t, ResponseLayer &m, ResponseLayer &b)
{
double * D = BuildDerivative(r, c, t, m, b);
double * H = BuildHessian(r, c, t, m, b);
double * Hi = Inverse(H);
if (Hi != NULL) {
double * Of = MMM_neg_3x3_3x1(Hi, D);
// get the offsets from the interpolation
double O[3] = { Of[0], Of[1], Of[2] };
// get the step distance between filters
int filterStep = (m.filter - b.filter);
// If point is sufficiently close to the actual extremum
if (fabs(O[0]) < (float)0.5 && fabs(O[1]) < (float)0.5 && fabs(O[2]) < (float)0.5)
{
IPoint ipt;
ipt.x = (float)((c + O[0]) * t.step);
ipt.y = (float)((r + O[1]) * t.step);
ipt.scale = (float)((0.1333f) * (m.filter + O[2] * filterStep));
ipt.laplacian = (int)(m.getLaplacian(r,c,t));
ipts->push_back(ipt);
}
delete[] Of;
delete[] Hi;
}
delete[] D;
delete[] H;
}
// Build Matrix of First Order Scale-Space derivatives
double * FastHessian::BuildDerivative(int r, int c, ResponseLayer &t, ResponseLayer &m, ResponseLayer &b)
{
double dx, dy, ds;
dx = (m.getResponse(r, c + 1, t) - m.getResponse(r, c - 1, t)) / (float)(2.0);
dy = (m.getResponse(r + 1, c, t) - m.getResponse(r - 1, c, t)) / (float)(2.0);
ds = (t.getResponse(r, c) - b.getResponse(r, c, t)) / (float)(2.0);
double * D = new double[3];
D[0] = dx;
D[1] = dy;
D[2] = ds;
return D;
}
// Build Hessian Matrix
double * FastHessian::BuildHessian(int r, int c, ResponseLayer &t, ResponseLayer &m, ResponseLayer &b)
{
double v, dxx, dyy, dss, dxy, dxs, dys;
v = m.getResponse(r, c, t);
dxx = m.getResponse(r, c + 1, t) + m.getResponse(r, c - 1, t) - 2 * v;
dyy = m.getResponse(r + 1, c, t) + m.getResponse(r - 1, c, t) - 2 * v;
dss = t.getResponse(r, c) + b.getResponse(r, c, t) - 2 * v;
dxy = (m.getResponse(r + 1, c + 1, t) - m.getResponse(r + 1, c - 1, t) -
m.getResponse(r - 1, c + 1, t) + m.getResponse(r - 1, c - 1, t)) / (float)(4.0);
dxs = (t.getResponse(r, c + 1) - t.getResponse(r, c - 1) -
b.getResponse(r, c + 1, t) + b.getResponse(r, c - 1, t)) / (float)(4.0);
dys = (t.getResponse(r + 1, c) - t.getResponse(r - 1, c) -
b.getResponse(r + 1, c, t) + b.getResponse(r - 1, c, t)) / (float)(4.0);
double * H = new double[9];
H[0] = dxx;
H[1] = dxy;
H[2] = dxs;
H[3] = dxy;
H[4] = dyy;
H[5] = dys;
H[6] = dxs;
H[7] = dys;
H[8] = dss;
return H;
}
// Return inverse of the Matrix m
double * FastHessian::Inverse(double * m)
{
double det = ((m[0]*m[4]*m[8]) + (m[1]*m[5]*m[6]) + (m[2]*m[3]*m[7]) -
(m[2]*m[4]*m[6]) - (m[1]*m[3]*m[8]) - (m[0]*m[5]*m[7]));
if (det == 0) return NULL;
double * invert = new double[9];
double A = (m[4] * m[8] - m[5] * m[7]) / det;
double B = -1 * (m[3] * m[8] - m[6] * m[5]) / det;
double C = (m[3] * m[7] - m[4] * m[6]) / det;
double D = -1 * (m[1] * m[8] - m[2] * m[7]) / det;
double E = (m[0] * m[8] - m[2] * m[6]) / det;
double F = -1 * (m[0] * m[7] - m[1] * m[6]) / det;
double G = (m[1] * m[5] - m[2] * m[4]) / det;
double H = -1 * (m[0] * m[5] - m[2] * m[3]) / det;
double K = (m[0] * m[4] - m[1] * m[3]) / det;
invert[0] = A;
invert[1] = D;
invert[2] = G;
invert[3] = B;
invert[4] = E;
invert[5] = H;
invert[6] = C;
invert[7] = F;
invert[8] = K;
return invert;
}
// Perform -1 * (A * B) where A is a 3x3 matrix and B is a 3x1 matrix
double * FastHessian::MMM_neg_3x3_3x1(double * A, double * B)
{
double * C = new double[3];
double a = -1 * (A[0] * B[0] + A[1] * B[1] + A[2] * B[2]);
double b = -1 * (A[3] * B[0] + A[4] * B[1] + A[5] * B[2]);
double c = -1 * (A[6] * B[0] + A[7] * B[1] + A[8] * B[2]);
C[0] = a;
C[1] = b;
C[2] = c;
return C;
}
FastHessian::ResponseLayer::ResponseLayer()
{
this->width = 0;
this->height = 0;
this->step = 0;
this->filter = 0;
this->responses = NULL;
this->laplacian = NULL;
}
FastHessian::ResponseLayer::ResponseLayer(int width, int height, int step, int filter)
{
this->width = width;
this->height = height;
this->step = step;
this->filter = filter;
responses = new float[width * height];
laplacian = new unsigned char[width * height];
}
FastHessian::ResponseLayer::~ResponseLayer()
{
if (responses != NULL)
delete [] responses;
if (laplacian != NULL)
delete [] laplacian;
}
unsigned char FastHessian::ResponseLayer::getLaplacian(int row, int column)
{
return laplacian[row * width + column];
}
unsigned char FastHessian::ResponseLayer::getLaplacian(int row, int column, ResponseLayer &src)
{
int scale = this->width / src.width;
return laplacian[(scale * row) * width + (scale * column)];
}
float FastHessian::ResponseLayer::getResponse(int row, int column)
{
return responses[row * width + column];
}
float FastHessian::ResponseLayer::getResponse(int row, int column, ResponseLayer &src)
{
int scale = this->width / src.width;
return responses[(scale * row) * width + (scale * column)];
}
| true |
034b8232f9b53db2ee9f5c9583f12ed9d4f7a1e4 | C++ | mahimahans111/cpp_codes | /trees/printLeafNodesFromPreorderTraversal.cc | UTF-8 | 1,275 | 3 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// -----------------------------------------------------
// This is a functional problem. Only this function has to be written.
// This function takes as input an array
// It should print the required output
vector<int> NGE(vector<int> &pre, int n){
vector<int> nge(n, -1);
stack<int> s;
nge[n-1] = -1;
s.push(n-1);
for(int i = n-2; i >= 0; i--){
while(s.size()>0 && pre[s.top()] <= pre[i]){
s.pop();
}
nge[i] = s.empty() ? -1 : s.top();
s.push(i);
}
return nge;
}
void helper(vector<int> &pre, int s, int e, vector<int> nge){
if(s > e) return;
if(s == e) cout << pre[s] << " ";
if(nge[s]!=-1 && nge[s] <= e){
helper(pre, s+1, nge[s]-1, nge);
helper(pre, nge[s], e, nge);
}
else{
helper(pre, s+1, e, nge);
}
}
void print(vector<int>& pre) {
int n = pre.size();
vector<int> nge = NGE(pre, n);
helper(pre, 0, n-1, nge);
//Write your code here
}
int main(int argc,char** argv) {
int n ;
cin>>n;
vector<int> a;
for (int i = 0; i <n; i++) {
int x;
cin>>x;
a.push_back(x);
}
print(a);
} | true |
55544b6780a97f612ce0d35772d8aa1f36b671a5 | C++ | Yashavanth-CP/Data-Structures-and-Algorithms | /poly/base_d.cpp | UTF-8 | 3,291 | 3.65625 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Base{
public:
Base(){
//std::cout <<" Base::Base() called "<< std::endl;
}
void print(){
std::cout << " Base:print() called" << std::endl;
}
void virtual print1() {
std::cout<<" Base:: print1() called" << std::endl;
}
};
class Derived : public Base{
public:
Derived(){
// std::cout << " Derived: Dervied() called" << std::endl;
}
# if 0
void print(){
std::cout << " Derived: print() called" << std::endl;
}
#endif
private:
void print1(){
std::cout<< " Derived: Print1() called" << std::endl;
}
};
int main(){
/* When the base class is a abstract class, then if the derived class does not implement the pure virtual functions of the
base class, then the derived class also becomes abstract */
// Base* bp = new Base();
// Derived* dp = new Derived();
/* no magic -- Derived class print is called- works */
// dp->print();
// bp = dp;
/* Only the base class functions are called when no virtual mechanism is used */
/* With virtual mechanism -- Dervied class functions are called-- since the compiler maintains the virtual table */
// bp->print();
/* Always the class pointers in the higher levels of the hiearchy can be assigned with the pointers of the derived class(Lower levels) */
/* Assigning the derived class pointers to the base classes pointers is not valid, since the derived class pointers have extra fields for the other
memebers( compile time error) */
//dp = bp;
/* Invalid -- since the dervice pointer is having some extra fields which becomes invalid and the
compiler gives an error */
std::cout<<" With Objects ----- > " <<std::endl;
Base bp;
Derived dp;
bp = dp;
bp.print();
bp.print1();
std::cout<< " With Object pointers --->" << std::endl;
/* Part 2 */
Base* bpo = new Derived();
bpo->print();/* Prints the derived class print since, the object slicing is done. That is, base class part of the dervied class is assiged to the
base class object */
//dpo = bpo; /* Invalid -- cannot assign the base class object to the derived class object, since the extra members of the derived class object become invalid and the compiler gives error */
bpo->print1();
return 0;
}
| true |
408e83013aa600756b67e33307067def8e2326a2 | C++ | WilliamNTN/Competitive-Programming | /google kickstart/kickstart 2018 - round B/a-nonine.cpp | UTF-8 | 866 | 2.53125 | 3 | [] | no_license |
// Correct for small
#include <bits/stdc++.h>
using namespace std;
#define LL long long int
#define pii pair<int,int>
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
const int maxN = 0;
LL t;
LL f,l;
LL solve(LL val){
vector<int> digits;
LL n = val;
while(n){
digits.pb(n%10);
n /=10;
}
LL ans = 0;
for(LL i = val-digits[0]; i <= val; i++){
if(i%9 == 0) continue;
int check = 1;
LL num = i;
while(num){
int d = num%10;
num /=10;
if(d == 9) check = 0;
}
if(check) ans++;
}
LL c = 0;
for(int i = 1; i < digits.size(); i++){
c += digits[i]*pow(9,i);
}
ans += (8*c)/9;
return ans;
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
cin>>t;
int count = 1;
while(t--){
cin>>f>>l;
LL ans = solve(l) - solve(f) + 1;
cout<<"Case #"<<count++<<": "<<ans<<endl;
}
return 0;
}
| true |
2de29dd3e596ada08491aa221fca0d33f2ca2931 | C++ | polmonroig/graph_percolation | /src/graph/grid.cpp | UTF-8 | 741 | 3.09375 | 3 | [] | no_license | #include "grid.h"
Grid::Grid(unsigned int num){
n = num;
}
std::string Grid::name() const{
return "grid2d";
}
Graph Grid::createGraph() const{
Graph g;
g.reserve(n * n);
// add vertices
for(auto i = 0; i < n * n; ++i){
g.addSite();
}
// O(|V|) |V| == n*n
for(auto i = 0; i < n - 1; ++i){
for(auto j = 0; j < n - 1; ++j){
auto pos = i * n + j;
g.addBond(pos, pos + 1);
g.addBond(pos, pos + n);
}
}
for(auto i = 1; i < n - 1; ++i) {
auto pos = n*(n-1)+i;
g.addBond(pos, pos + 1);
}
for(auto i = 1; i < n - 1; ++i) {
auto pos = n*i;
g.addBond(pos, pos + n);
}
return g; // graella
}
| true |
115f8be59e07192edcfec90d441358dcd7630e08 | C++ | Rakibul-CoU/Numerical-Analysis-3rd-Semester | /ramanuzan methods.cpp | UTF-8 | 1,162 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
double degree,arr[20],b[20];
double Function(int c)
{
int i;
double sum=0;
for(i=1;i<=3;i++)
{
sum+=arr[i]*b[c];
c--;
}
return sum;
}
int main()
{
int i,n,divider;
double accuracy,value;
cout<<"PLEASE, PRESS THE HIGHEST DEGREE OF THE EQUATION: ";
cin>>degree;
cout<<endl<<"PLEASE, PRESS THE ELEMENTS: ";
for(i=degree;i>=0;i--)
cin>>arr[i];
cout<<endl<<"PLEASE, PRESS THE ACCURACY LEVEL: ";
cin>>accuracy;
value=1/(pow(10,accuracy));
for(i=0;i<=degree;i++)
{
if(arr[i]!=0)
{
divider=i;
break;
}
}
int v=1,j=3;
double k;
k=arr[divider];
double before,now;
for(i=divider+1;i<=degree;i++)
arr[i]=(-1*arr[i])/k;
b[1]=1;
b[2]=arr[1];
b[3]=arr[1]*b[2]+arr[2]*b[1];
before=b[1]/b[2];
now=b[2]/b[3];
while(abs(now-before)>=value)
{
before=now;
b[j+1]=Function(j);
now=b[j]/b[j+1];
j=j+1;
}
cout<<endl<<now;
return 0;
}
| true |
8872d7841a25dd40a71dd39c8aee11119bbf93a3 | C++ | lanillo/QMSat-Satellite | /OBC/Tests/Steps/Peripherals/GPIO-evaluator.hpp | UTF-8 | 1,528 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | /*
* GPIO-evaluator.hpp
*
* Created on: 2018-03-10
* Author: Luis Anillo
*/
#ifndef GPIO_EVALUATOR_HPP_
#define GPIO_EVALUATOR_HPP_
#include "EFM32_GPIO.hpp"
#include "GPIO-mock.hpp"
#include <cstdio>
#define NUMBER_OF_BANKS 6
#define MASK 65535
class GPIOEvaluator
{
private:
//EFM32_GPIO m_UUT;
EFM32_GPIO m_UUT;
bool m_PinState;
public:
GPIOEvaluator();
~GPIOEvaluator() {};
// Initialise GPIO
/** @bdd the pin number is (?P<p_pinNumber>[-+]?\d+(\.\d+)?), a bank letter is (?P<p_bankLetter>[-+]?\d+(\.\d+)?), is an input and the type is (?P<p_typeIO>[-+]?\d+(\.\d+)?) */
void GPIOInitialiseInput(int p_pinNumber, int p_bankLetter, int p_typeIO);
/** @bdd the pin number is (?P<p_pinNumber>[-+]?\d+(\.\d+)?), a bank letter is (?P<p_bankLetter>[-+]?\d+(\.\d+)?), is an output and the type is (?P<p_typeIO>[-+]?\d+(\.\d+)?) */
void GPIOInitialiseOutput(int p_pinNumber, int p_bankLetter, int p_typeIO);
/** @bdd an initialization error flag is set */
bool verifyInitializeError();
/** @bdd a GPIO is instantiated as (?P<p_expectedInput>[-+]?\d+(\.\d+)?) */
bool verifyIOType(int p_expectedInput);
// Set GPIO State
/** @bdd the state of GPIO is (?P<p_expectedState>[-+]?\d+(\.\d+)?) since GPIO is set as a (?P<p_GPIOType>[-+]?\d+(\.\d+)?)*/
bool GPIOSetState(int p_expectedState, int p_GPIOType);
// Toggle GPIO
/** @bdd toggling the GPIO state */
bool GPIOtoggle();
// Update registers of the GPIO struct
void UpdateRegisters();
};
#endif /* GPIO_EVALUATOR_HPP_ */
| true |
0e11f334c82aeba87973b969fc68a353be6a4cc6 | C++ | arunjayabalan/SystemC | /Lab1_Task2/Lab1_Task2/channel.cpp | UTF-8 | 527 | 3.046875 | 3 | [] | no_license | #pragma once
#include "channel.h"
void channel::write(char c) {
if (num_elements == max)
wait(read_event);
data[(first + num_elements) % max] = c;
++num_elements;
//next_trigger(write_event);
write_event.notify();
}
void channel::read(char &c)
{
if (num_elements == 0)
wait(write_event);
c = data[first];
--num_elements;
first = (first + 1) % max;
//read_event.notify();
}
void channel::reset()
{
num_elements = first = 0;
}
int channel::num_available()
{
return num_elements;
} | true |
d3fac18d375118bc3037237854d95c79e957cb1a | C++ | xunshuidezhu/TinyWeb | /src/tiny_base/condition.h | UTF-8 | 1,569 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
*Author:GeneralSandman
*Code:https://github.com/GeneralSandman/TinyWeb
*E-mail:generalsandman@163.com
*Web:www.generalsandman.cn
*/
/*---Configer Class---
*We need to upgrade this class
*in order to handle config file error
****************************************
*
*/
#ifndef CONDITION_H
#define CONDITION_H
#include <tiny_base/api.h>
#include <tiny_base/mutex.h>
#include <boost/noncopyable.hpp>
#include <pthread.h>
class Condition : boost::noncopyable
{
private:
MutexLock &m_nMutexLock;
pthread_cond_t m_nCond;
public:
explicit Condition(MutexLock &mutex)
: m_nMutexLock(mutex)
{
int res = pthread_cond_init(&m_nCond, NULL);
if (res != 0)
handle_error("pthread_cond_init() error");
}
void wait()
{
pthread_cond_wait(&m_nCond,
m_nMutexLock.getPthreadMutex());
}
bool waitForSeconds(int second)
{
//if time out return true,
struct timespec abs;
clock_gettime(CLOCK_REALTIME, &abs);
abs.tv_sec += second;
return ETIMEDOUT == pthread_cond_timedwait(&m_nCond,
m_nMutexLock.getPthreadMutex(),
&abs);
}
void notify()
{
pthread_cond_signal(&m_nCond);
}
void notifyAll()
{
pthread_cond_broadcast(&m_nCond);
}
~Condition()
{
int res = pthread_cond_destroy(&m_nCond);
if (res != 0)
handle_error("pthread_cond_destroy() error");
}
};
#endif | true |
f863b51b1ef96f88502651543399525e49595d89 | C++ | blabla132/keepit-php | /temp/0w7b135tleVaMgEjadntVc3qnmQoVI2QAaNFV8PZRLNAboLuaL/Program 10.cpp | UTF-8 | 1,639 | 3.40625 | 3 | [] | no_license | //
// main.cpp
// Program 1
//
// Created by Liyang Zhang 2016 on 6/10/13.
// Copyright (c) 2013 Liyang Zhang 2016. All rights reserved.
//
//precompiler directives:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
int main( )
{
// ********************* PROBLEM 1 *********************
double a[5];
for (int i=0;i<5;i++) {
cout << "Please enter a number: ";
cin >> a[i];
}
cout << endl << "The average of your numbers is " << (a[0]+a[1]+a[2]+a[3]+a[4])/5 << "." << endl;
cout << endl;
// ********************* PROBLEM 2 *********************
for (int i=0;i<5;i++) {
cout << "Please enter a number: ";
cin >> a[i];
}
double product = a[0]*a[1]*a[2]*a[3]*a[4];
cout << endl << "The product of your numbers is " << product << "." << endl;
// ********************* PROBLEM 3 *********************
double sum = 0;
for (int i=25;i<=50;i++) {
sum += i;
}
cout << endl << "The sum of the consecutive integers from 25 to 50 is " << sum << "." << endl;
// ********************* PROBLEM 3 *********************
product = 1;
for (int i=3;i<=11;i+=2) {
product *= i;
}
cout << endl << "The product of the odd integers from 3 to 11 is " << product << "." << endl;
// ********************* PROBLEM 4 *********************
double frac = 1, decimal = 1;
for (int i=2;i<=6;i++) {
frac *= i;
decimal /= i;
}
cout << endl << "The product of 1/2, 1/3, 1/4, 1/5, and 1/6 is 1/" << frac << ", or " << decimal << "." << endl;
return 0;
}
| true |
d9bd5079c08ecb2ac7d73598f31246deecb19aae | C++ | guangpanqian/Chat | /ChatClient/Encrypter.cpp | UTF-8 | 1,209 | 2.671875 | 3 | [] | no_license | #include "StdAfx.h"
#include "Encrypter.h"
#include "..\include\Package\packetDef.h"
#include <iterator>
Encrypter::Encrypter(void)
{
encryption_DES.SetKey((const unsigned char*)(DES_KEY),DES::KEYLENGTH);
decryption_DES.SetKey((const unsigned char*)(DES_KEY),DES::KEYLENGTH);
}
Encrypter::~Encrypter(void)
{
}
void Encrypter::Encrypt(const string& szPlaintext,string&szCrpher )
{
Process(szPlaintext,szCrpher,ENCRYPTION);
}
void Encrypter::Decrypt(const string&szCrpher, string& szPlaintext)
{
Process(szCrpher,szPlaintext,DECRYPTION);
}
void Encrypter::Process(const string& strInput,string&strOutput,CipherDir cipherDir)
{
BlockTransformation *pProcesser = NULL;
if (ENCRYPTION == cipherDir)
pProcesser = &encryption_DES;
else
pProcesser = &decryption_DES;
unsigned char *pInput = new unsigned char[strInput.length()];
memcpy(pInput,strInput.c_str(),strInput.length());
int nBlockSize = strInput.length()/DES::BLOCKSIZE;
int nProcessedLength = 0;
for (int nBlockIndex = 0;nBlockIndex < nBlockSize;++nBlockIndex)
{
pProcesser->ProcessBlock(pInput + nBlockIndex*DES::BLOCKSIZE );
}
copy(pInput,pInput+strInput.length(),inserter(strOutput,strOutput.begin()));
delete[] pInput;
} | true |
56a06fcdaf009f641205de36635b4e07f6db3e7a | C++ | copydev/CodeForces | /Hello2020/A.cpp | UTF-8 | 467 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define REP(i,n) for(ll i = 0;i<n;++i)
int main() {
int n,m;
vector<string> strn;
vector<string> strm;
cin>>n>>m;
REP(i,n){
string s;
cin>>s;
strn.push_back(s);
}
REP(i,m){
string s;
cin>>s;
strm.push_back(s);
}
ll q;
cin>>q;
while(q--){
ll y;
cin>>y;
ll sn = (y-1)%n;
ll sm = (y-1)%m;
string ans = strn[sn] + strm[sm];
cout<<ans<<endl;
}
return 0;
} | true |
6528841f4971bac5497e969fc451a2124335e60e | C++ | akshitagupta15june/100daysofcode_hackerblock_akshita | /square_root_to_precision.cpp | UTF-8 | 682 | 2.828125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
double squareroot(long long int a,long long int p)
{
int s=0;
int e=a;
int mid;
double ans;
while(s<=e)
{
mid=(s+e)/2;
if(mid*mid==a)
{
ans=mid;
break;
}
if(mid*mid<a)
{
s=mid+1;
ans=mid;
}
else{
e=mid-1;
}
}
double inc=0.1;
for(int i=0;i<p;i++)
{
while(ans*ans<=a)
{
ans+=inc;
}
ans=ans-inc;
inc=inc/10;
}
return ans;
}
int main()
{
long long int a,b;
cin>>a>>b;
cout<<squareroot(a,b)<<endl;
return 0;
}
| true |
d24d3c16e14564c9e99d7e2c57e420041f3dcbf6 | C++ | ilkerhalil/CacheLib | /cachelib/navy/scheduler/tests/OrderedThreadPoolJobSchedulerTest.cpp | UTF-8 | 8,293 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Random.h>
#include <gtest/gtest.h>
#include <set>
#include <thread>
#include "cachelib/navy/scheduler/ThreadPoolJobScheduler.h"
#include "cachelib/navy/testing/SeqPoints.h"
namespace facebook {
namespace cachelib {
namespace navy {
namespace tests {
// order jobs with same type and ensure that they are executed in the
// enqueued order.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueSameType) {
uint64_t key = 5;
SeqPoints sp;
std::vector<int> order;
int seq = 0;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(1);
return JobExitCode::Done;
},
"", JobType::Write, key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(2);
return JobExitCode::Done;
},
"", JobType::Write, key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(3);
return JobExitCode::Done;
},
"", JobType::Write, key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
sp.wait(1);
sp.wait(2);
sp.wait(3);
for (int i = 1; i <= seq; i++) {
EXPECT_EQ(i, order[i - 1]);
}
}
// enqueue jobs with different job types for the same key. Ensure that the
// ordering is maintained.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueDiffType) {
std::array<JobType, 2> jobTypes = {JobType::Read, JobType::Write};
uint64_t key = 5;
SeqPoints sp;
std::vector<int> order;
int seq = 0;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
sp.wait(1);
sp.wait(2);
sp.wait(3);
for (int i = 1; i <= seq; i++) {
EXPECT_EQ(i, order[i - 1]);
}
}
// enqueue three jobs, check that two of them are spooled and calling finish
// should handle the draining of all the jobs, even with rescheduling.
TEST(OrderedThreadPoolJobScheduler, SpoolAndFinish) {
std::array<JobType, 2> jobTypes = {JobType::Read, JobType::Write};
uint64_t key = 5;
SeqPoints sp;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp]() {
sp.wait(0);
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp]() {
sp.wait(0);
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
return JobExitCode::Reschedule;
}
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
scheduler.finish();
sp.wait(1);
sp.wait(2);
sp.wait(3);
}
// ensure that the ordering is maintained with the rescheduling of the jobs.
// We enqueue three jobs for same key that can reschedule and ensure that
// after reschedule, the order is maintained as well.
TEST(OrderedThreadPoolJobScheduler, JobWithRetry) {
std::array<JobType, 3> jobTypes = {JobType::Read, JobType::Write,
JobType::Reclaim};
uint64_t key = 5;
SeqPoints sp;
std::atomic<uint64_t> numReschedules{0};
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
EXPECT_EQ(0, numReschedules);
sp.reached(0);
sp.wait(1);
EXPECT_GE(numReschedules, 2);
sp.wait(2);
EXPECT_GE(numReschedules, 4);
sp.wait(3);
EXPECT_EQ(6, numReschedules);
}
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueAndFinish) {
unsigned int numKeys = 10000;
std::atomic<int> numCompleted{0};
{
OrderedThreadPoolJobScheduler scheduler{3, 32, 10};
for (unsigned int i = 0; i < numKeys; i++) {
scheduler.enqueueWithKey(
[&]() {
++numCompleted;
return JobExitCode::Done;
},
"", JobType::Write, folly::Random::rand32());
}
scheduler.finish();
}
EXPECT_EQ(numCompleted, numKeys);
}
// enqueue a certain number of jobs and validate the stats for spooling are
// reflective of the behavior expected.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueMaxLen) {
unsigned int numKeys = 10000;
std::atomic<int> numCompleted{0};
SeqPoints sp;
sp.setName(0, "all enqueued");
unsigned int numQueues = 4;
OrderedThreadPoolJobScheduler scheduler{numQueues, 1, 10};
for (unsigned int i = 0; i < numKeys; i++) {
scheduler.enqueueWithKey(
[&]() {
sp.wait(0);
++numCompleted;
return JobExitCode::Done;
},
"", JobType::Read, folly::Random::rand32());
}
uint64_t numSpooled = 0;
uint64_t maxQueueLen = 0;
uint64_t pendingJobs = 0;
scheduler.getCounters([&](folly::StringPiece name, double stat) {
if (name == "navy_reader_max_queue_len") {
maxQueueLen = static_cast<uint64_t>(stat);
} else if (name == "navy_req_order_curr_spool_size") {
numSpooled = static_cast<uint64_t>(stat);
} else if (name == "navy_max_reader_pool_pending_jobs") {
pendingJobs = static_cast<uint64_t>(stat);
}
});
EXPECT_GE(numSpooled, 0);
uint64_t numQueued = numKeys - numSpooled;
EXPECT_LE(maxQueueLen, numQueued);
// we could have at most one job executing per Queue. So the total of
// pending jobs must not be off by more than numQueue when compared with
// total enqueued.
EXPECT_LE(numQueued - pendingJobs, numQueues);
sp.reached(0);
scheduler.finish();
EXPECT_EQ(numCompleted, numKeys);
}
} // namespace tests
} // namespace navy
} // namespace cachelib
} // namespace facebook
| true |
9118cb533bc9483c70297f7f6c72deb2af2b7e01 | C++ | nachobit/CodePLUS | /MP/VectorMatriz/MEMODinamica/matriz_med_varianza_amp.cpp | UTF-8 | 942 | 3.546875 | 4 | [] | no_license | //MEMORIA DINAMICA
//EJEMPLO NOTAS ALUMNOS MEDIA Y VARIANZA
#include <iostream>
using namespace std;
void LeerNotas(double *v, int n){
for (int i = 0; i < n; i++)
{
cout << "Introduce la nota " << i;
cin >> v[i];
}
}
double Media(const double *v, int n){
double m=0.0;
for (int i = 0; i < n; i++){
m+=v[i];
}
return m/n;
}
double Varianza(const double *v, int n){
double m=Media(v,n); //calculamos media
double s=0.0; //acumulamos
for (int i = 0; i < n; i++){
s+=(v[i]-m)*(v[i]-m);
}
return s/n;
}
void AmpliarM(int *&v, int &n){ //N Y V POR FERERENCIA
int *aux = new int[n+1];
for (int i = 0; i < n; i++)
aux[i]=v[i];
delete[]v;
v=aux;
n=n+1;
}
int main(){
int n; //nº alumnos
do{
cout << "Dime nº alumnos: ";
cin >> n;
}while(n <=0);
double *datos = new double [n];
LeerNotas(datos,n);
double m=Media(datos,n);
double v=Varianza(datos,n);
//AmpliarM(datos,n);
cout << "Media : " << m << "Varianza: " << v;
} | true |
0bb95a015a25e25bbda6c3590c1c2c821dba644a | C++ | EAxxx/EA872 | /examples/portaudio/01-playback.cpp | UTF-8 | 3,742 | 2.78125 | 3 | [] | no_license |
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <random>
#include "01-playback.hpp"
using namespace Audio;
Sample::Sample() {
}
Sample::~Sample() {
}
bool Sample::finished() {
if ( (this->position) >= (this->data.size())) return true;
else return false;
}
void Sample::load(const char *filename) {
std::string buffer;
float fdata;
std::ifstream input_file;
unsigned int count = 0;
input_file.open(filename, std::ios_base::in);
if (!input_file) {
std::cerr << "Arquivo " << filename << " nao encontrado" << std::endl;
return;
}
while (std::getline(input_file, buffer) ) {
std::stringstream(buffer) >> fdata;
(this->data).push_back(fdata);
count ++;
}
this->position = 0;
std::cerr << "Total: " << count << " samples" << std::endl;
}
unsigned int Sample::get_position() {
return this->position;
}
void Sample::set_position(unsigned int pos) {
this->position = pos;
}
std::vector<float> Sample::get_data() {
return this->data;
}
Player::Player() {
this->playing = false;
this->audio_sample = NULL;
}
void Player::pause() {
this->playing = false;
}
Player::~Player() {
}
Sample *Player::get_data() {
return this->audio_sample;
}
int mix_and_play (const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
Player *player = (Player*) userData;
float *buffer = (float *) outputBuffer;
Sample *s;
s = player->get_data();
if (s != NULL) {
std::vector<float> data = s->get_data();
unsigned int pos = s->get_position();
// Fill the buffer with samples!
for (int i=0; (i<framesPerBuffer); i++) {
if (pos < data.size())
buffer[i] = data[pos];
else
buffer[i] = 0;
i++;
pos+=2;
}
s->set_position(pos);
}
return 0;
}
void Player::play(Sample *audiosample) {
this->audio_sample = audiosample;
}
void Player::init() {
PaError err;
err = Pa_Initialize();
if( err != paNoError ) {
std::cerr << "Error on Pa_Initialize()" << std::endl;
return;
}
outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */
if (outputParameters.device == paNoDevice) {
std::cerr << "Error: No default output device on Pa_GetDefaultOutputDevice()" << std::endl;
return;
}
outputParameters.channelCount = 1; /* Mono output. */
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream( &stream,
NULL, /* No input. */
&outputParameters,
44100,
64, /* Frames per buffer. */
paClipOff, /* We won't output out of range samples so don't bother clipping them. */
mix_and_play,
this );
if( err != paNoError ) {
std::cerr << "Error on Pa_OpenStream()" << std::endl;
return;
}
err = Pa_StartStream( stream );
if( err != paNoError ) {
std::cerr << "Error on Pa_StartStream()" << std::endl;
return;
}
}
void Player::stop() {
PaError err;
err = Pa_StopStream( stream );
if( err != paNoError ) {
std::cerr << "Error on Pa_StopStream()" << std::endl;
return;
}
err = Pa_CloseStream( stream );
if( err != paNoError ) {
std::cerr << "Error on Pa_StopStream()" << std::endl;
return;
}
Pa_Terminate();
}
| true |
8956da4442eb57414eb998a631679c6059e0efea | C++ | FoFabien/mhse | /main.hpp | UTF-8 | 1,229 | 2.671875 | 3 | [] | no_license | #ifndef MAIN_HPP_INCLUDED
#define MAIN_HPP_INCLUDED
// compilation flag ****************
#define ENGINE_OS 1 // 1 = windows, 2 = linux, 3 = mac, others = undefined
// macro ***************************
#define cdelete(x) {delete x; x = NULL;}
#define adelete(x) {delete [] x; x = NULL;}
#define ABS(x) ((x)<0 ? -(x) : (x))
#define SGN(x) ((x)<0 ? -1 : 1)
// lib *****************************
#include <iostream>
#include <iterator>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>
#include <ctime>
#include <limits>
#include <locale>
#include <vector>
#include <map>
#include <stack>
#include <bitset>
#include <queue>
#include <set>
//important define *****************
#define LOGFILE_NAME "log.txt"
struct XYZ
{
XYZ(): x(0), y(0), z(0){};
XYZ(float a, float b, float c): x(a), y(b), z(c){};
XYZ(const XYZ &arg): x(arg.x), y(arg.y), z(arg.z){};
inline bool operator==(const XYZ& rhs){return (x == rhs.x && y == rhs.y && z == rhs.z);}
inline bool operator!=(const XYZ& rhs){return !(x == rhs.x && y == rhs.y && z == rhs.z);}
inline XYZ& operator=(XYZ arg) {x = arg.x; y = arg.y; z = arg.z; return *this;}
float x;
float y;
float z;
};
#endif // MAIN_HPP_INCLUDED
| true |
27f09bc7bfb4490c6572f9c42ebad660ae674525 | C++ | Rupisecter/JoanPatricioSalasRondon | /AlgebraAbstracta-Vigenere/Vigenere1/clase.h | UTF-8 | 4,413 | 2.859375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
using namespace std;
class Vigenere
{
private:
string clave;
public:
string abc;
Vigenere();
string cifrarabc(string msj);
string descifrarabc(string msj);
string cifraraqui(string msj);
string descifraraqui(string msj);
//string cifrarascii(string msj);
};
Vigenere::Vigenere()
{
abc = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ,.:";
clave = "flaco";
}
string Vigenere::cifrarabc(string msj)
{
int aux, aux2, aux3;
for (int i = 0, j = 0; i < msj.length(); ++i, ++j)
{
aux = abc.find(msj[i]);
if (!isalpha(msj[i]))
{
msj[i] = abc[aux];
j--;
}
else
{
if (islower(msj[i]))
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux + aux2) % 26;
msj[i] = abc[aux3];
}
else
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux + aux2) % 53;
msj[i] = abc[aux3];
}
}
}
return msj;
}
string Vigenere::descifrarabc(string msj)
{
int aux, aux2, aux3;
for (int i = 0, j = 0; i < msj.length(); ++i, ++j)
{
aux = abc.find(msj[i]);
if (!isalpha(msj[i]))
{
msj[i] = abc[aux];
j--;
}
else
{
if (islower(msj[i]))
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux - aux2 + 26) % 26;
msj[i] = abc[aux3];
}
else
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux - aux2 + 53) % 53;
msj[i] = abc[aux3];
}
}
}
return msj;
}
/*string Vigenere::cifrarascii(string msj)
{
int aux2,aux;
for(int i=0;i<msj.length();++i)
{
aux=int(msj[i]);
if(msj[i]==' ' or msj[i]==',' or msj[i]=='.')
{
msj[i]=msj[aux];
}
else
{
aux2=int(clave[i%clave.length()]);
cout<<aux<<" "<<msj[i]<<" "<<aux2<<" "<< clave[i%clave.length()]<<" "<<(aux2+aux+122)%122<<endl;
msj[i]=(aux2+aux+122)%122 ;
}
}
return msj;
}
*/
string Vigenere::cifraraqui(string msj)
{
int aux, aux2, aux3;
string msj2("aqui");
for (int i = 0, j = 0; i < msj.length(); ++i, ++j)
{
if (i % 9 == 0)
{
if (i != 0)
{
msj.insert(i, msj2);
}
}
aux = abc.find(msj[i]);
if (!isalpha(msj[i]))
{
msj[i] = abc[aux];
j--;
}
else
{
if (islower(msj[i]))
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux + aux2) % 26;
msj[i] = abc[aux3];
}
else
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux + aux2) % 53;
msj[i] = abc[aux3];
}
}
}
while(msj.length()%4!=0)
{
msj.append("w");
}
return msj;
}
string Vigenere::descifraraqui(string msj)
{
int aux, aux2, aux3;
string msj2("aqui");
while (msj[msj.length()-1] == 'w')
{
msj.erase(msj.length()-1, 1);
}
for (int i = 0, j = 0; i < msj.length(); ++i, ++j)
{
cout << msj[i] << endl;
aux = abc.find(msj[i]);
if (i %9 == 0)
{
if (i != 0)
{
msj.erase(i, 4);
}
}
if (!isalpha(msj[i]))
{
msj[i] = abc[aux];
j--;
}
else
{
if (islower(msj[i]))
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux - aux2 + 26) % 26;
msj[i] = abc[aux3];
}
else
{
aux2 = abc.find(clave[j % clave.length()]);
aux3 = (aux - aux2 + 53) % 53;
msj[i] = abc[aux3];
}
}
}
return msj;
} | true |
bfd0fc8ffd1b7aa641fb949ebd1da219a9f8dcee | C++ | AlexDmr/b207 | /Route 66/V3/slimlib-3.0/misc/sources/Tokenizer.cpp | UTF-8 | 1,760 | 3.09375 | 3 | [] | no_license | #include <Misc/Tokenizer.h>
//----------------------------------------------------------------------------------------
Tokenizer::Tokenizer(const char* string, const char *sep)
{
last = NULL;
firstToken = true;
this->string = NULL;
nbReadToken = 0;
if(sep != NULL)
{
this->sep.set(sep);
}
else
{
this->sep.set(" ");
}
if(string != NULL)
{
this->string = String::duplicate(string);
this->tokens.set(string);
}
}
//----------------------------------------------------------------------------------------
Tokenizer::~Tokenizer()
{
if(string != NULL) free(string);
}
//----------------------------------------------------------------------------------------
void Tokenizer::reset()
{
if(string != NULL) free(string);
nbReadToken = 0;
last = NULL;
firstToken = true;
string = String::duplicate(tokens.get());
}
//----------------------------------------------------------------------------------------
const char *Tokenizer::getNextToken(const char *sep)
{
if(sep != NULL)
{
this->sep.set(sep);
}
char *token;
if(firstToken)
{
firstToken = false;
token = strtok_r(string, this->sep.get(), &last);
}
else
{
token = strtok_r(NULL, this->sep.get(), &last);
}
if(token != NULL) nbReadToken++;
return token;
}
//----------------------------------------------------------------------------------------
void Tokenizer::addToken(const char *token)
{
tokens.concat(sep);
tokens.concat(token);
}
//----------------------------------------------------------------------------------------
long Tokenizer::getNbReadToken()
{
return nbReadToken;
}
//----------------------------------------------------------------------------------------
const char *Tokenizer::getTokens()
{
return tokens.get();
}
| true |
b35d43152d1273a6ff8f44ae51899802b05d40ab | C++ | nguyengiabk/programming_contest | /codeforces/149/149B.cpp | UTF-8 | 1,151 | 2.828125 | 3 | [] | no_license | #include<stdio.h>
int a[5], b[5];
int mu(int a, int n){
int i, kq=1;
for(i=0;i<n;i++){
kq*=a;
}
return kq;
}
int tinh(int p[], int n, int base){
int i,sum=0;
for(i=n-1;i>=0;i--){
sum+=p[i]*mu(base,n-i-1);
}
return sum;
}
int main(){
int i,na, nb, ma=0,mb=0,max,check=0;
char c;
i=0;
while((c=getchar())!=EOF){
if(c>='0' && c<'9') a[i++]=c-'0';
if(c>='A' && c<='Z') a[i++]=c-'A'+10;
if(a[i-1]>ma) ma=a[i-1];
if(c==':') break;
}
na=i;
i=0;
while((c=getchar())!=EOF){
if(c>='0' && c<'9') b[i++]=c-'0';
if(c>='A' && c<='Z') b[i++]=c-'A'+10;
if(b[i-1]>mb) mb=b[i-1];
if(c=='\n') break;
}
nb=i;
//for(i=0;i<na;i++) printf("%d \n", a[i]);
//for(i=0;i<nb;i++) printf("%d \n", b[i]);
if(ma>mb) max = ma+1;
else max = mb+1;
//printf("%d %d %d %d\n",na, nb,tinh(a,na,max), tinh(b,nb,max));
if(tinh(a,na,max)>23 || tinh(b,nb,max)>59){
printf("0\n");
return 0;
}
for(i=0;i<na-1;i++)
if(a[i]!=0) check =1;
for(i=0;i<nb-1;i++)
if(b[i]!=0) check =1;
if(check==0){
printf("-1\n");
return 0;
}
i=max;
while(tinh(a,na,i)<24 && tinh(b,nb,i)<60){
printf("%d ",i);
i++;
}
printf("\n");
return 0;
}
| true |
2fa6050310ef4d9959ab3ed10ad0ed7dd0df7220 | C++ | gonzalezerik/College-Programming-Assignments | /LAPC - CO SCI 575 C++ Programming Fundamentals For Computer Science/ICEs/ICE 4-25/AnalyzeNumberscpp.cpp | UTF-8 | 990 | 4 | 4 | [] | no_license | /*Erik Gonzalez
CO SCI 575
AnalyzeNumbers.cpp
calculates the sum, average, positive and negative numbers of a size-5 array entered by users. */
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int FIVE_NUMS = 5;
double num[FIVE_NUMS];
cout << "You can enter 5 integer numbers." << endl;
//input
for (int i = 0; i <= FIVE_NUMS - 1; i++)
{
cout << "Enter a new number: ";
cin >> num[i];
}
//proccessing
int sum = num[0] + num[1] + num[2] + num[3] + num[4];
cout << "Sum is " << sum << endl;
double average = (num[0] + num[1] + num[2] + num[3] + num[4]) / 5;
cout << "Average is " << average << endl;;
int positive = 0;
int negative = 0;
for (int o = 0; o <= FIVE_NUMS; o++)
{
if (num[o] > 0)
positive++;
else
{
negative++;
}
}
//outputs
cout << "Number of negative: " << negative - 1 << endl;
cout << "Number of positive: " << positive << endl;
system("pause");
return 0;
}
| true |
0c68cb9633de8724a821d7c9eb09e5b2db26c9f5 | C++ | gembancud/CompetitiveProgramming | /uva/problemsolvingparadigms/completesearch/harditerativethreeormore/sumsets/a2.cpp | UTF-8 | 1,985 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool cmp(vector<long long> a,vector<long long> b){
return (a[0]<b[0]);
}
int main(){
int n;
while(cin>>n){
if(n==0) break;
vector<long long> v(n);
for(auto&i:v) cin>>i;
vector<vector<long long>> ab;
vector<vector<long long>> dc;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
long long sum= v[i]+v[j];
long long dif= v[j]-v[i];
vector<long long> tmpab;
tmpab.push_back(sum);
tmpab.push_back(v[i]);
tmpab.push_back(v[j]);
ab.push_back(tmpab);
vector<long long> tmpdc;
tmpdc.push_back(dif);
tmpdc.push_back(v[i]);
tmpdc.push_back(v[j]);
dc.push_back(tmpdc);
}
}
sort(ab.begin(),ab.end(),cmp);
sort(dc.begin(),dc.end(),cmp);
vector<long long> abo;
vector<pair<long long,long long>> abp;
for(auto&i:ab){
abo.push_back(i[0]);
abp.push_back(make_pair(i[1],i[2]));
}
vector<long long> dco;
vector<pair<long long,long long>> dcp;
for(auto&i:dc){
dco.push_back(i[0]);
dcp.push_back(make_pair(i[1],i[2]));
}
long long mx= INT_MIN;
for(int i=0;i<abo.size();i++){
auto it = lower_bound(dco.begin(),dco.end(),abo[i]);
int idx =it - dco.begin();
if(abo[i] == dco[idx]){
if(
abp[i].first != dcp[idx].first &&
abp[i].first != dcp[idx].second &&
abp[i].second != dcp[idx].first &&
abp[i].second != dcp[idx].second
)
mx = max(mx,dcp[idx].second);
}
}
if(mx==INT_MIN) printf("no solution\n");
else cout << mx <<endl;
}
} | true |
a343879d83e18302f84d9dfa949352b8749eeda3 | C++ | sskender/hackerrank | /maximizing-xor.cpp | UTF-8 | 313 | 3.390625 | 3 | [] | no_license | #include <iostream>
int maxXOR(int l, int r)
{
int max = 0;
for (int i = l; i <= r; i++)
for (int j = i; j <= r; j++)
if ((i ^ j) > max) { max = i ^ j; }
return max;
}
int main()
{
int l, r; std::cin >> l >> r;
std::cout << maxXOR(l, r) << std::endl;
//system("pause");
return 0;
} | true |
14751c8323c4e05f6c4f0c5184667f0781ee7e7b | C++ | Digital-Safety-and-Security/rtamt-cpp | /source/node/stl_addition_node.hpp | UTF-8 | 1,495 | 3.203125 | 3 | [] | no_license | #ifndef STL_ADDITION_NODE_H
#define STL_ADDITION_NODE_H
#include <node/stl_node.hpp>
#include <node/stl_sample.hpp>
#include <visitor/stl_visitor.hpp>
#include <array>
namespace node {
/**
* @brief This class defines the Node for the
* STL Addition operation and implements the monitoring algorithm
* for computing it.
*
*/
class StlAdditionNode : public StlNode {
private:
/**
* @brief Array of two input (left and right) samples
*
*/
std::array<Sample, 2> in;
public:
/**
* @brief Constructor that sets the child node
*
* @param left_child STL node representing the subformula phi of the formula phi + psi.
* @param right_child STL node representing the subformula psi of the formula phi + psi.
*/
StlAdditionNode(StlNode* left_child, StlNode* right_child);
/**
* @brief Monitoring algorithm computing the addition
*
* @return node::Sample
*/
Sample update() override;
/**
* @brief Updates the input with new input samples (left and right).
*
* @param left left input sample.
* @param right right input sample.
*/
void addNewInput(Sample left, Sample right);
/**
* @brief Accepts STL Visitor and calls its visit function.
*
* @param v STL Visitor
*/
void accept(visitor::StlVisitor& v) override;
~StlAdditionNode() override = default;
/**
* @brief Reset the internal state of STL Addition node.
*
*/
void reset() override {}
};
} // namespace node
#endif /* STL_ADDITION_NODE_H */
| true |
748d18466df9852f151960c09f8904bff490f7d0 | C++ | eirikraha/FYS4150 | /warmup/warmup.cpp | UTF-8 | 1,920 | 3.140625 | 3 | [] | no_license | /* Fancy program */
#include <stdio.h> /* printf */
#include <math.h> /* mathfunctions */
#include <iostream> /* output */
#include <fstream> /* output to file */
#include <iomanip> /* pretty, pretty */
using namespace std;
int singleprec()
{
float hstop, dfdx2, dfdx3, x, h;
float fpluss, fnorm, fmin;
x = sqrt(2);
hstop = 1e-20;
ofstream myfile;
myfile.open("/home/eirik/Documents/Git/FYS4150/warmup/data/ex2cpp.txt");
for (h = 1; h > hstop; h /= 10)
{ fpluss = atan(x + h);
fnorm = atan(x);
fmin = atan(x - h);
dfdx2 = (fpluss - fnorm)/h;
dfdx3 = (fpluss - fmin)/(2.0*h);
cout << "dfdx2 = "<< setw(10) << dfdx2;
cout << ", dfdx3 = "<< setw(10) << dfdx3;
cout << ", h = "<< setw(10) << h << endl;
myfile << "dfdx2 = "<< setw(10) << dfdx2 << ", ";
myfile << ", dfdx3 = "<< setw(10) << dfdx3;
myfile << ", h = "<< setw(10) << h << endl;
}
return 0;
}
int doubleprec()
{
double hstop, dfdx2, dfdx3, x, h;
double fpluss, fnorm, fmin;
x = sqrt(2);
hstop = 1e-20;
ofstream myfile;
myfile.open("/home/eirik/Documents/Git/FYS4150/warmup/data/ex2cpp.txt", std::ios_base::app);
myfile << "\n";
for (h = 1; h > hstop; h /= 10)
{ fpluss = atan(x + h);
fnorm = atan(x);
fmin = atan(x - h);
dfdx2 = (fpluss - fnorm)/h;
dfdx3 = (fpluss - fmin)/(2.0*h);
cout << "dfdx2 = "<< setw(10) << dfdx2;
cout << ", dfdx3 = "<< setw(10) << dfdx3;
cout << ", h = "<< setw(10) << h << endl;
myfile << "dfdx2 = "<< setw(10) << dfdx2 << ", ";
myfile << ", dfdx3 = "<< setw(10) << dfdx3;
myfile << ", h = "<< setw(10) << h << endl;
}
myfile.close();
return 0;
}
int main(int argn, char** argv)
{
remove("/home/eirik/Documents/Git/FYS4150/warmup/data/ex2cpp.txt");
singleprec();
cout << "\n";
doubleprec();
return 0;
}
| true |
1cec67e4e04afe925d2b0fdc4bad2970c537eaa0 | C++ | Seongil-Shin/Algorithm | /백준/solutions/2206 벽수부고 이동하기/2206 벽부수고 이동하기.cpp | UTF-8 | 1,367 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <list>
using namespace std;
bool map[1000][1000];
int width, height, result = 2000000000;
int check[1000][1000];
list<pair<pair<int, int>, pair<bool, int>>> q;
int min(int a, int b) {
return a < b ? a : b;
}
void BFS();
void push(int r, int c, bool t, int s) {
bool temp = map[r][c] ? !t : t;
q.push_back({ {r, c}, {temp, s} });
check[r][c] = t ? 2 : 1;
}
bool isok(int r, int c, bool t) {
if ((!check[r][c] || (check[r][c] == 2 && !t)) && (!map[r][c] || !t))
return true;
return false;
}
int main() {
cin >> height >> width;
for (int i = 0; i < height; i++) {
string t;
cin >> t;
for (int j = 0; j < width; j++) {
map[i][j] = t[j] - '0';
}
}
BFS();
if (result == 2000000000)
cout << -1;
else
cout << result << endl;
}
void BFS() {
q.push_back({ {0,0}, {false, 0} });
check[0][0] = 1;
while (!q.empty()) {
int r = q.front().first.first, c = q.front().first.second, s = q.front().second.second;
bool t = q.front().second.first;
q.pop_front();
if (r == height - 1 && c == width - 1)
result = min(result, s + 1);
if (r > 0 && isok(r-1, c, t))
push(r - 1, c, t, s + 1);
if (r < height - 1 && isok(r+1, c, t))
push(r + 1, c, t, s + 1);
if (c > 0 && isok(r, c-1, t))
push(r, c - 1, t, s + 1);
if (c < width - 1 && isok(r, c + 1, t))
push(r, c + 1, t, s + 1);
}
return;
} | true |