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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cd3a20d1061d1e2afb991e13f0d8bf8e77943600 | C++ | warmwhiten/PS | /BOJ/14000/14501_퇴사.cpp | UTF-8 | 520 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int N;
int d[16], T[15], P[15];
int result = -1;
void input()
{
scanf_s("%d", &N);
for (int i = 0; i < N; i++)
{
scanf_s("%d %d", &T[i], &P[i]);
}
}
void DP()
{
for (int i = 0; i < N; i++)
{
if (i + T[i] <= N)
{
d[i + T[i]] = max(d[i + T[i]], d[i] + P[i]);
result = max(result, d[i + T[i]]);
}
d[i + 1] = max(d[i + 1], d[i]);
result = max(result, d[i + 1]);
}
}
int main()
{
input();
DP();
printf("%d", result);
return 0;
} | true |
a422a883e0702602ff6b21016f2c760b8c37bbbf | C++ | SarmadTanveer/spectrum-analyzer | /Visualizer_1/Visualizer_1.ino | UTF-8 | 2,982 | 2.890625 | 3 | [] | no_license | #include "FastLED.h"
#include <AudioAnalyzer.h>
Analyzer Audio = Analyzer(4,5,5);//Strobe pin ->4 RST pin ->5 Analog Pin ->5
//Analyzer Audio = Analyzer();//Strobe->4 RST->5 Analog->0
int FreqVal[7];// Read Stored Values
int LedFreq[7];// Mapped read values to control num leds on
// Matrix size
#define NUM_ROWS 16
#define NUM_COLS 16
// LEDs pin
#define DATA_PIN 6
//Switch
#define SWITCH 3
// LED brightness
#define BRIGHTNESS 30
//Number of LEDs
#define NUM_LEDS NUM_ROWS * NUM_COLS
//First Band
#define BAND_1_start 16
#define BAND_1_stop 47
//Second Band
#define BAND_2_start 48
#define BAND_2_stop 79
//Third Band
#define BAND_3_start 80
#define BAND_3_stop 111
//Fourth Band
#define BAND_4_start 112
#define BAND_4_stop 143
//Fifth Band
#define BAND_5_start 144
#define BAND_5_stop 175
//Sixth Band
#define BAND_6_start 176
#define BAND_6_stop 207
//Seventh Band
#define BAND_7_start 208
#define BAND_7_stop 239
// Define the array of leds
CRGBArray<NUM_LEDS> leds;
void setup() {
Serial.begin(57600);
//Analyzer Initialization
Audio.Init();//Init module
//Matrix Initialization
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
//Switch Initialization
pinMode(SWITCH, INPUT);
}
void loop() {
//Analyzer Driver
Audio.ReadFreq(FreqVal);//Return 7 values of 7 bands pass filiter
//Frequency(Hz):63 160 400 1K 2.5K 6.25K 16K
//FreqVal[]: 0 1 2 3 4 5 6
for(int i=0;i<7;i++)
{
FreqVal[i] = FreqVal[i]-100;
LedFreq[i] = map(max(FreqVal[i],0), 0, 350, 0, 16);
LedFreq[i] = constrain(LedFreq[i], 0, 16);
Serial.print(LedFreq[i]);
if(i<6) Serial.print(",");
else Serial.println();
}
//Led Driver
////band 1
leds(BAND_1_start,BAND_1_start+LedFreq[0]) = CRGB::Red;
leds(BAND_1_stop,BAND_1_stop-LedFreq[0]) = CRGB::Red;
////band 2
leds(BAND_2_start,BAND_2_start+LedFreq[1]) = CRGB::Blue;
leds(BAND_2_stop,BAND_2_stop-LedFreq[1]) = CRGB::Blue;
////band 3
leds(BAND_3_start,BAND_3_start+LedFreq[2]) = CRGB::White;
leds(BAND_3_stop,BAND_3_stop-LedFreq[2]) = CRGB::White;
////band 4
leds(BAND_4_start,BAND_4_start+LedFreq[3]) = CRGB::Yellow;
leds(BAND_4_stop,BAND_4_stop-LedFreq[3]) = CRGB::Yellow;
//band 5
leds(BAND_5_start,BAND_5_start+LedFreq[4]) = CRGB::Purple;
leds(BAND_5_stop,BAND_5_stop-LedFreq[4]) = CRGB::Purple;
//band 6
leds(BAND_6_start,BAND_6_start+LedFreq[5]) = CRGB::Green;
leds(BAND_6_stop,BAND_6_stop-LedFreq[5]) = CRGB::Green;
////band 7
leds(BAND_7_start,BAND_7_start+LedFreq[6]) = CRGB::Orange;
leds(BAND_7_stop,BAND_7_stop-LedFreq[6]) = CRGB::Orange;
FastLED.show();
delay(60); //Sampling Rate
FastLED.clear();
}
| true |
ebd790003d89de12c36685f8d6b1d700cad9bcc4 | C++ | Stenodyon/TUNG_Router | /src/graphics.cpp | UTF-8 | 3,561 | 2.796875 | 3 | [] | no_license | #include "graphics.hpp"
#include <exception>
#define SIZE 20
#define PEG_SIZE 10
#define WIN_SIZE 32 * SIZE
GraphicsOutput::GraphicsOutput(int width, int height)
: width(width), height(height)
{
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
throw std::runtime_error("SDL: " + std::string(SDL_GetError()));
}
window = SDL_CreateWindow("TUNG Router", 100, 100, WIN_SIZE, WIN_SIZE, SDL_WINDOW_SHOWN);
if (window == nullptr)
{
std::string msg = "SDL: " + std::string(SDL_GetError());
SDL_Quit();
throw std::runtime_error(msg);
}
render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (render == nullptr)
{
std::string msg = "SDL: " + std::string(SDL_GetError());
SDL_Quit();
throw std::runtime_error(msg);
}
SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
SDL_RenderClear(render);
SDL_RenderPresent(render);
}
GraphicsOutput::~GraphicsOutput()
{
SDL_DestroyRenderer(render);
SDL_DestroyWindow(window);
SDL_Quit();
}
void GraphicsOutput::to_window_space(int & x, int & y)
{
double ratio_x = (double)32 / width;
double ratio_y = (double)32 / height;
x *= ratio_x; y *= ratio_y;
}
void GraphicsOutput::to_window_space(SDL_Rect & rect)
{
double ratio_x = (double)32 / width;
double ratio_y = (double)32 / height;
rect.x *= ratio_x; rect.y *= ratio_y;
rect.w *= ratio_x; rect.h *= ratio_y;
}
void GraphicsOutput::clear()
{
SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
SDL_RenderClear(render);
}
void GraphicsOutput::draw_map(const grid<int> & map)
{
SDL_SetRenderDrawColor(render, 0, 255, 0, 255);
auto [width, height] = map.get_size();
for(int_t y = 0; y < height; y++)
{
for(int_t x = 0; x < width; x++)
{
const int value = map[{x, y}];
if(value == 1)
{
SDL_Rect rect{(int)x * SIZE, (int)y * SIZE, SIZE, SIZE};
to_window_space(rect);
SDL_RenderFillRect(render, &rect);
}
}
}
}
void GraphicsOutput::draw_path(const std::vector<vi2> & path)
{
if(path.empty())
return;
SDL_SetRenderDrawColor(render, 255, 0, 0, 127);
{
const auto& pos = path[0];
SDL_Rect peg{
(int)pos.x * SIZE + (SIZE - PEG_SIZE) / 2,
(int)pos.y * SIZE + (SIZE - PEG_SIZE) / 2,
PEG_SIZE,
PEG_SIZE};
to_window_space(peg);
SDL_RenderFillRect(render, &peg);
}
for(uint_t i = 1; i < path.size(); i++)
{
const auto& pos = path[i];
const auto& prev = path[i-1];
SDL_Rect peg{
(int)pos.x * SIZE + (SIZE - PEG_SIZE) / 2,
(int)pos.y * SIZE + (SIZE - PEG_SIZE) / 2,
PEG_SIZE,
PEG_SIZE};
to_window_space(peg);
SDL_RenderFillRect(render, &peg);
int x1 = pos.x * SIZE + SIZE / 2;
int y1 = pos.y * SIZE + SIZE / 2;
int x2 = prev.x * SIZE + SIZE / 2;
int y2 = prev.y * SIZE + SIZE / 2;
to_window_space(x1, y1); to_window_space(x2, y2);
SDL_RenderDrawLine(render, x1, y1, x2, y2);
}
}
void GraphicsOutput::present()
{
SDL_RenderPresent(render);
}
void GraphicsOutput::loop()
{
SDL_RenderPresent(render);
bool looping = true;
while(looping)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
looping = false;
}
SDL_Delay(60);
}
}
| true |
862034909352a0c9a596cd12c0dc5370b2b59640 | C++ | Towerthousand/BiomeNoise | /game/BiomeConst.hpp | UTF-8 | 553 | 2.859375 | 3 | [] | no_license | #ifndef BIOMECONST_HPP
#define BIOMECONST_HPP
#include "BiomeFunction.hpp"
class BiomeConst final : public BiomeFunction {
public:
BiomeConst(std::mt19937* generator, int biome) : BiomeFunction(generator), biome(biome) {
}
virtual ~BiomeConst() {
}
std::vector<int> getBiomeData(int px, int pz, int sx, int sz) const override {
(void) px;
(void) pz;
return std::vector<int>(sx*sz, biome);
}
private:
const int biome = 0;
};
#endif // BIOMECONST_HPP
| true |
776909d94cd4c951875b0e06ae42f4f1094e5bf7 | C++ | tensorflow/tensorflow | /tensorflow/core/lib/strings/ordered_code.h | UTF-8 | 4,039 | 2.71875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// This module provides routines for encoding a sequence of typed
// entities into a string. The resulting strings can be
// lexicographically compared to yield the same comparison value that
// would have been generated if the encoded items had been compared
// one by one according to their type.
//
// More precisely, suppose:
// 1. string A is generated by encoding the sequence of items [A_1..A_n]
// 2. string B is generated by encoding the sequence of items [B_1..B_n]
// 3. The types match; i.e., for all i: A_i was encoded using
// the same routine as B_i
// Then:
// Comparing A vs. B lexicographically is the same as comparing
// the vectors [A_1..A_n] and [B_1..B_n] lexicographically.
//
// Furthermore, if n < m, the encoding of [A_1..A_n] is a strict prefix of
// [A_1..A_m] (unless m = n+1 and A_m is the empty string encoded with
// WriteTrailingString, in which case the encodings are equal).
//
// This module is often useful when generating multi-part sstable
// keys that have to be ordered in a particular fashion.
#ifndef TENSORFLOW_CORE_LIB_STRINGS_ORDERED_CODE_H_
#define TENSORFLOW_CORE_LIB_STRINGS_ORDERED_CODE_H_
#include <string>
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace strings {
class OrderedCode {
public:
// -------------------------------------------------------------------
// Encoding routines: each one of the following routines append
// one item to "*dest" in an encoding where larger values are
// ordered lexicographically after smaller values.
static void WriteString(string* dest, StringPiece str);
static void WriteNumIncreasing(string* dest, uint64 num);
static void WriteSignedNumIncreasing(string* dest, int64_t num);
// -------------------------------------------------------------------
// Decoding routines: these extract an item earlier encoded using
// the corresponding WriteXXX() routines above. The item is read
// from "*src"; "*src" is modified to point past the decoded item;
// and if "result" is non-NULL, "*result" is modified to contain the
// result. In case of string result, the decoded string is appended to
// "*result". Returns true if the next item was read successfully, false
// otherwise.
static bool ReadString(StringPiece* src, string* result);
static bool ReadNumIncreasing(StringPiece* src, uint64* result);
static bool ReadSignedNumIncreasing(StringPiece* src, int64_t* result);
// Helper for testing: corrupt "*str" by changing the kth item separator
// in the string.
static void TEST_Corrupt(string* str, int k);
// Helper for testing.
// SkipToNextSpecialByte is an internal routine defined in the .cc file
// with the following semantics. Return a pointer to the first byte
// in the range "[start..limit)" whose value is 0 or 255. If no such
// byte exists in the range, returns "limit".
static const char* TEST_SkipToNextSpecialByte(const char* start,
const char* limit);
private:
// This has only static methods, so disallow construction entirely
OrderedCode();
TF_DISALLOW_COPY_AND_ASSIGN(OrderedCode);
};
} // namespace strings
} // namespace tensorflow
#endif // TENSORFLOW_CORE_LIB_STRINGS_ORDERED_CODE_H_
| true |
8e30e001d1ad9fde11447c6cf866443ae63056ae | C++ | antonioguerrerocarrillo/1DESARROLLO-DE-APLICACIONES-MULTIPLATAFORMA | /1DAM/programacion en c++/ejercicios y practicas/minipractica UD5 bingo/yobingo.cpp | UTF-8 | 10,176 | 3.09375 | 3 | [] | no_license |
//
// juego del bingo
//
//
// Created by Antonio Guerrero y Pedro Infantes 02/02/2018
//
//
#include <iostream>
#define BLACK_COLOR "\033[1;30m"
#define RED_COLOR "\033[1;31m"
#define GREEN_COLOR "\033[1;32m"
#define YELLOW_COLOR "\033[1;33m"
#define BLUE_COLOR "\033[1;34m"
#define PURPLE_COLOR "\033[1;35m"
#define CYAN_COLOR "\033[1;36m"
#define WHITE_COLOR "\033[1;39m"
#define RESTORE_DEFAULT_COLOR "\033[0m"
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include<time.h>
//libreria de los numeros aleatorios srand
#include<stdlib.h>
#include <cstdlib>
using namespace std;
const int DIM_FIL_CARTON = 5; // utiles de la fila del carton
const int DIM_COL_CARTON = 11; //utiles de la columna del carton
const int DIM_bola=100;
int generarbola(int vector_bola[], int util_bola){
srand(time(NULL));
int bola= rand()%90;
bool encontrado=false;
for(int i = 0; i < util_bola ; i++ ){
if(vector_bola[i]==bola)
{
encontrado=true;
}
}
if(encontrado==true)
{
return bola;
vector_bola[util_bola]=bola;
util_bola++;
}
}
/**
* @brief Módulo que vamos a realizar la comprobacion de line
* @brief Módulo que vamor a ordenar de menor a mayor la matriz.
* @param pasamos el vector[]
* @param util_col para saber las columnas que necesitamos maximas.
* @vers 1.0
*/
int ordenacionvector(int vector[],int util_col){
int menor=0;
int aux=0;
for(int i =0;i<util_col-1;i++){
for(int j=0;i<util_col-1;j++){
if(vector[j]<vector[i]){
menor=j;
aux=vector[i];
vector[i]=vector[menor];
vector[menor]=aux;
}
}
}
}
/**
* @brief Módulo este modulo va agenerar el carton haciendo los numeros aleatorios entre el 1 a 99,
* @param matriz llamada carton y [columna del carton] que ya hemos creado en el main
* @param util_col para saber las columnas que necesitamos maximas.
* @param util_fil las filas del carton contando con las partes de decoracion
* @param en este modulo tambien vamos a ordenar los numeros y para ello vamos a usar un do while. para que lo use en el bucle de
* de las filas,
* @param ordenar los numeros de menor a mayor por filas. con un numero min(minimo), med(media) y max (maximo)
* @post realizar todo para pasarlo a la funcion de mostrar ya listo.
* @vers 2.0
*/
void generarCarton(char carton[][DIM_COL_CARTON], int util_col, int util_fil ){
//srand sirve para que genere numeros aleatorios y el 100 en base a srand te selecciona unos numeros predeterminados;
srand(time(NULL));
int DIM = 100;
int vector [DIM]; //vector local.
int util_vector = util_fil; // util del vector local
//Lo hacemos a la inversa para poder imprimir el vector ordenado
for (int c = 1; c < DIM_COL_CARTON; c++){ //bucle de la fila
int min = 100;
int max = 0;
int med=0;
do{
for (int f = 1; f < DIM_FIL_CARTON; f++){ //bucle de la columna.
//num = 1 + rand() % (100 - 1);
//carton[f][c] = num;
int num=rand()%10+10*(c-1);
if(num <= min){
if(min!=90){
med=min;
}
min= num;
}
if(num >=max){
if(max!=0){
med=max;
}
max=num;
}
}
carton[1][c] = min; // la posicion 1 de la matriz y el numero mas pequeño
carton[2][c] = med; // la posicion 2 de la matriz donde estara la mitad
carton[3][c] = max; // la posicion 3 de la matriz donde pondremos el numero max
}while(min==med || med==max || min==max);
}
}
/**
* @brief Módulo que vamos a usar para rellenar el carton poniendole la de coracion pertinente y necesaria.
* @param matriz llamada carton y [columna del carton] que ya hemos creado en el main
* @param util_col para saber las columnas que necesitamos maximas.
* @param util_fil las filas del carton contando con las partes de decoracion
* @param rrellenar la parte izquierda del vector, superior, inferior y derecha.
* @post despues lo pasaremos a imprimircarton
* @vers 2.0
*/
void rellenarcarton (char carton[][DIM_COL_CARTON], int util_col, int util_fil) {
//1 º) Rellenamos el marco superior
for (int c=0; c < DIM_COL_CARTON; c++)
carton[0][c] = '=';
//2 º) Rellenamos marco izquierdo
int s = 0;
for (int f=1; f < DIM_FIL_CARTON; f++){
carton[f][0] = '|'; // el sÃmbolo gráfico de las dos barras
if(s==0){
carton[f][1] = 'x';
s++;
}
//else if(s == 1 && f == 3){
//}
}
//3 º) Rellenamos marco derecho
for (int f=1; f < DIM_FIL_CARTON; f++)
carton[f][util_col+1] = '|'; // el sÃmbolo gráfico de las dos barras
//4 º) Rellenamos marco inferior
for (int c=0; c < DIM_COL_CARTON; c++)
carton[util_fil+1][c] = '=';
}
//5 º) Tocamos las esquinas para ponerlas bonitas
//6 º) Rellenamos los números
// Aquà tendrÃan que llamar a módulos para ir generando las columnas de números
// En total 15 números en el cartón
// No pueden existir columnas sin número y la columna tiene que tener como máximo un número.
// Cada columna genera números aleatorios entre su rango
/**
* @brief modulo para mostrar por pantalla. tambien rellenamos el carton, pondremos bonito, y le pondremos las x dentro de el.
* @param matriz llamada carton y [columna del carton] que ya hemos creado en el main, la pasamos como constante.
* @post mostrar el carton por patanlla ya creado.
*/
void imprimirCarton(const char carton[][DIM_COL_CARTON]){
for (int f = 0; f < DIM_FIL_CARTON; f++){
for (int c = 0; c < DIM_COL_CARTON; c++){
if(c==0 || f==0|| c==DIM_COL_CARTON-1|| f==DIM_FIL_CARTON-1)
cout << GREEN_COLOR << carton[f][c] << RESTORE_DEFAULT_COLOR<<"\t";
else
//El caracter char lo convertimos en numeros con el int para que nos de el número
if(carton[f][c] == 'x'){
cout << GREEN_COLOR << carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
} else {
cout << GREEN_COLOR << (int)carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
}
//cout << GREEN_COLOR << (int)carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
// para devolverlo en tipo int
}
cout << endl;
}
}
/**
* @brief modulo que imprime la bola tachar el numero y cambiar la matriz el numero y cambiar por un $
* @param le pasamos la bola .
* @post mostrar el carton por patanlla ya creado.
*/
void imprimirCartonbola(const char carton[][DIM_COL_CARTON]){
for (int f = 0; f < DIM_FIL_CARTON; f++){
for (int c = 0; c < DIM_COL_CARTON; c++){
if(c==0 || f==0|| c==DIM_COL_CARTON-1|| f==DIM_FIL_CARTON-1)
cout << GREEN_COLOR << carton[f][c] << RESTORE_DEFAULT_COLOR<<"\t";
else
//El caracter char lo convertimos en numeros con el int para que nos de el número
if(carton[f][c] == 'x'){
cout << GREEN_COLOR << carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
} else {
cout << GREEN_COLOR << (int)carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
}
//cout << GREEN_COLOR << (int)carton[f][c] << RESTORE_DEFAULT_COLOR<< "\t";
// para devolverlo en tipo int
}
cout << endl;
}
}
/**
* @brief modulo que vamos a meter las x dentro del carton
* @param matriz llamada carton y [columna del carton] que ya hemos creado en el main, la pasamos como constante.
* @post mostrar el carton ya con las x incluidas.
*/
void meterX(char carton [DIM_FIL_CARTON][DIM_COL_CARTON],int util_col, int util_fil){
for (int c = 0; c < DIM_COL_CARTON; c++){ //bucle de la fila
if(c%2==0)
{
}else
{
}
}
}
/**
@brief hacemos los menus aqui mostraremos al usuario a que programa queremos ir pulsando la tecla correspondiente
@param para el menu usamos el switch
@pre no tenemos que usar
@return no tiene return.
@post introduce [i] para imprimirCarton el carton, [j] para jugar solo, [v] para jugar 2 personas: y [s] para salir
**/
char menu_en_pantalla (char carton [DIM_FIL_CARTON][DIM_COL_CARTON],int util_col, int util_fil, int vector_bola[], int util_bola) {
char menu ;
do{ //filtro
cout << " introduce [i] para imprimirCarton el carton, [j] para jugar solo, [v] para jugar 2 personas: y [s] para salir" << endl;
cin >> menu;
}
while(menu!='i' && menu!= 'j'&& menu !='v' && menu !='s');
switch (menu) {
case 'i':
generarCarton(carton, util_col, util_fil);
rellenarcarton ( carton, util_col, util_fil);
imprimirCarton(carton);
meterX(carton,util_col,util_fil);
generarbola(vector_bola, util_bola);
imprimirCarton(carton);
break;
case 'a':
//invocacion de la variable para que lo coja y el sepa donde se tiene que ir al pulsar
break;
case 'n':
break;
case 's':
break;
}
}
int main(){
const int TOTAL_NUMEROS_CARTON = 15;
char carton [DIM_FIL_CARTON][DIM_COL_CARTON];
int vector_bola[DIM_bola];
int util_bola = 0;
int util_col = 9;
int util_fil = 3;
menu_en_pantalla (carton, util_col, util_fil, vector_bola, util_bola);
//generarCarton(carton, util_col, util_fil);
//algoritmoSeleccion(int Vector[],int util)
//imprimirCarton(carton);
}
| true |
d92e95685d7248dd1047447620ba76d156786ea7 | C++ | OpenNuvoton/ISPTool | /NuvoISP/CScopedMutex.hpp | UTF-8 | 2,477 | 2.890625 | 3 | [] | no_license | #if !defined(_CMUTEX2_H_)
#define _CMUTEX2_H_
class CMutex2
{
public:
CMutex2()
: m_bLocked(FALSE)
, m_uLockCount(0)
, m_dwThread(-1)
{
m_hMutex = ::CreateMutex(NULL, FALSE, NULL);
}
virtual ~CMutex2()
{
::ReleaseMutex(m_hMutex);
}
void Lock()
{
if (!m_bLocked || m_dwThread != ::GetCurrentThreadId())
//if (m_dwThread != ::GetCurrentThreadId())
{
::WaitForSingleObject(m_hMutex, INFINITE);
m_dwThread = ::GetCurrentThreadId();
m_bLocked = TRUE;
}
++m_uLockCount;
}
void Unlock()
{
if (--m_uLockCount == 0) {
m_bLocked = FALSE;
// m_dwThread = -1;
::ReleaseMutex(m_hMutex);
}
}
void Recursive_Lock(unsigned int uLockCount)
{
while (uLockCount-- != 0) {
Lock();
}
Unlock();
}
unsigned int Recursive_Unlock()
{
Lock();
unsigned int uRet = m_uLockCount;
unsigned int uLockCount = m_uLockCount;
while (uLockCount-- != 0) {
Unlock();
}
return uRet;
}
unsigned int GetLockCount() const
{
return m_uLockCount;
}
protected:
BOOL m_bLocked;
DWORD m_dwThread;
HANDLE m_hMutex;
unsigned int m_uLockCount;
};
class ScopedMutex
{
public:
explicit ScopedMutex(CMutex2 &mutex, BOOL bUnlock = FALSE)
: m_bUnlock(bUnlock)
, m_pMutex(&mutex)
{
if (m_bUnlock) {
m_uLockCount = m_pMutex->Recursive_Unlock();
} else {
m_pMutex->Lock();
//DGB_PRINTF("In lock id = %d, count = %d\n", (int)GetCurrentThreadId(), m_pMutex->GetLockCount());
//DGB_PRINTF("In lock %d, id = %d\n", line, (int)GetCurrentThreadId());
//DGB_PRINTF("In lock, %x, %d\n", &hMutex, GetTickCount());
}
}
virtual ~ScopedMutex()
{
//DGB_PRINTF("In unlock, id = %d, count = %d\n", (int)GetCurrentThreadId(), m_pMutex->GetLockCount());
//DGB_PRINTF("In unlock, %d\n", GetTickCount());
//::ReleaseMutex(m_hMutex); //Unlock
if (m_bUnlock) {
m_pMutex->Recursive_Lock(m_uLockCount);
} else {
m_pMutex->Unlock();
}
}
protected:
CMutex2 *m_pMutex;
BOOL m_bUnlock;
unsigned int m_uLockCount;
};
#endif // #if !defined(_CMUTEX2_H_) | true |
be72b852f2cd992a0e1a7e6faeb7a50ca268e992 | C++ | juiceme/libQtSpotify | /listmodels/listmodelbase.h | UTF-8 | 1,948 | 3 | 3 | [] | no_license | #ifndef LISTMODELBASE_H
#define LISTMODELBASE_H
#include <QtCore/QAbstractListModel>
#include <QtCore/QList>
#include <QtCore/QVariant>
/***
Abstract list model class, uses std::shared_pointer to objects it stores.
ItemType Requirements:
-ItemType should have a dataChanged() signal which is emitted whenever data
changes, except when it changed from within setData() then it is optional.
-ItemType should inherit from public std::enable_shared_from_this<ItemType>.
*/
template <class ItemType> class ListModelBase : public QAbstractListModel
{
public:
explicit ListModelBase(QObject *parent=nullptr);
virtual ~ListModelBase();
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
void appendRow(ItemType * item);
void appendRows(const QList<ItemType *> &items);
void insertRow(int row, ItemType *item);
void replaceData(const QList<ItemType *> &newData);
ItemType *takeRow(int row);
ItemType *find(const QString &id) const;
QModelIndex indexFromItem(const ItemType *item) const;
virtual void clear();
bool isEmpty() const { return m_dataList.isEmpty(); }
ItemType *at(int index) const { return m_dataList.at(index); }
int count() const { return m_dataList.count(); }
void reserve(int size) { m_dataList.reserve(size);}
using iterator = typename QList<ItemType *>::Iterator;
using const_iterator = typename QList<ItemType *>::ConstIterator;
iterator begin() { return m_dataList.begin(); }
const_iterator begin() const { return m_dataList.begin(); }
const_iterator cbegin() const { return m_dataList.cbegin(); }
iterator end() { return m_dataList.end(); }
const_iterator end() const { return m_dataList.end(); }
const_iterator cend() const { return m_dataList.cend(); }
protected:
QList<ItemType *> m_dataList;
protected slots:
void itemDataChanged();
};
#include "listmodelbase.cpp"
#endif // LISTMODELBASE_H
| true |
b77c441361da806206eb321dbf6c0b918ddc96ab | C++ | lmns1314HuHu/ACM_record | /字符串/HDU_5782_字符串_exkmp.cpp | UTF-8 | 2,140 | 2.640625 | 3 | [] | no_license | /**==================================
| Author: YunHao
| OJ:
| Kind:
| Date:
| Describe:
|
|
=================================**/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
int n;
char s1[10010];
char s2[10010];
int num1[150];
int num2[150];
int nxt1[10010];
int nxt2[10010];
int ex1[10010];
int ex2[10010];
bool cmp(int* num1, int* num2){
for (int i = 0; i < 150; i++){
if(num1[i] != num2[i])
return false;
}
return true;
}
void exkmp(char s1[], char s2[], int next[], int ex[]){
int i, j, p;
for (i = 0, j = 0, p = -1; s1[i] != '\0'; i++, j++, p--){
if(p == -1){
j = 0;
do
p++;
while(s1[i+p] != '\0' && s1[i+p] == s2[j+p]);
ex[i] = p;
}
else if(next[j] < p)
ex[i] = next[j];
else if(next[j] > p)
ex[i] = p;
else{
j = 0;
while(s1[i + p] != '\0' && s1[i+p] == s2[j+p]) p++;
ex[i] = p;
}
}
ex[i] = 0;
}
int main()
{
while(~scanf("%s", s1)){
scanf("%s", s2);
memset(num1, 0, sizeof num1);
memset(num2, 0, sizeof num2);
nxt1[0] = 0;
exkmp(s1 + 1, s1, nxt1, nxt1 + 1);
exkmp(s2, s1, nxt1, ex2);
nxt2[0] = 0;
exkmp(s2 + 1, s2, nxt2, nxt2 + 1);
exkmp(s1, s2, nxt2, ex1);
int len1 = strlen(s1), len2 = strlen(s2);
for (int i = 0; i < len1; i++){
num1[s1[i]]++;
num2[s2[i]]++;
if(cmp(num1, num2)){
bool flag = false;
for (int j = 0; j <= i; j++){
if(ex2[j] < i - j + 1) continue;
if(ex1[i - j + 1] < j) continue;
flag = true;
break;
}
if(flag) printf("1");
else printf("0");
}
else{
printf("0");
}
}
printf("\n");
}
return 0;
}
| true |
07d5197b1793827c74900b36866798657bae8f20 | C++ | formerStudent/POJ | /1000/1002.cpp | UTF-8 | 1,763 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <list>
#include <string>
using namespace std;
//A, B, C -> 2
//D, E, F -> 3
//G, H, I -> 4
//J, K, L -> 5
//M, N, O -> 6
//P, R, S -> 7
//T, U, V -> 8
//W, X, Y -> 9
int main()
{
char in[200]{ 0 };
list<string> data;
int n;
cin >> n;
if (n > 100000)
return -1;
while (n--)
{
string out;
cin >> in;
for (int i = 0, j = 0; i < strlen(in); i++)
{
if (in[i] >= '0'&&in[i] <= '9')
{
out += in[i];
}
else
{
switch (in[i])
{
case 'A':
case 'B':
case 'C':
out += '2';
break;
case 'D':
case 'E':
case 'F':
out += '3';
break;
case 'G':
case 'H':
case 'I':
out += '4';
break;
case 'J':
case 'K':
case 'L':
out += '5';
break;
case 'M':
case 'N':
case 'O':
out += '6';
break;
case 'P':
case 'R':
case 'S':
out += '7';
break;
case 'T':
case 'U':
case 'V':
out += '8';
break;
case 'W':
case 'X':
case 'Y':
out += '9';
break;
default:
break;
}
}
}
if (out.length() != 7)
continue;
data.push_back(out);
}
data.sort();
int count = 0;
string str = data.front();
for (list<string>::iterator it = data.begin(); it != data.end(); it++)
{
if (str == *it)
count++;
else
{
if (count >= 2)
{
str.insert(3, 1, '-');
cout << str << " " << count << endl;
}
str = *it;
count = 1;
}
}
if (count >= 2)
{
str.insert(3, 1, '-');
cout << str << " " << count << endl;
}
int num = data.size();
data.unique();
//cout << num << " " << data.size() << endl;
if (num == data.size())
cout << "No duplicates." << endl;
//system("pause");
return 0;
} | true |
2780e0afbdec302ff0326b2677bba061ef67689a | C++ | prateek1802/Codechef | /cheglove.cpp | UTF-8 | 865 | 2.8125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<climits>
#include<math.h>
#include<vector>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int f[n],g[n];
for(int i=0;i<n;i++)
{
cin>>f[i];
}
for(int i=0;i<n;i++)
{
cin>>g[i];
}
int front=0,back=0;
for(int i=0;i<n;i++)
{
if(g[i]>=f[i])
{
front++;
}
if(g[n-i-1]>=f[i])
{
back++;
}
}
if(front==n&&back==n)
cout<<"both"<<endl;
else if(front==n)
cout<<"front"<<endl;
else if(back==n)
cout<<"back"<<endl;
else
cout<<"none"<<endl;
}
return 0;
} | true |
a68a713ee2890535b3e17f56b27971623454eeb1 | C++ | ericksav21/Maestria | /Semestre 3/Programacion y algoritmos 2/Problemas/UVA_10849/main.cpp | UTF-8 | 560 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t, q, n;
int r1, c1, r2, c2;
cin >> t;
while(t--) {
cin >> q >> n;
for(int i = 0; i < q; i++) {
cin >> r1 >> c1 >> r2 >> c2;
int r_abs = abs(r1 - r2);
int c_abs = abs(c1 - c2);
if((r_abs + c_abs) % 2 != 0) {
cout << "no move\n";
continue;
}
if(r_abs == 0 && c_abs == 0) {
cout << "0\n";
}
else if(r_abs == c_abs) {
cout << "1\n";
}
else {
cout << "2\n";
}
}
}
return 0;
} | true |
fc4169e4da1fd1e389ba62cdebae7c1961ebeb05 | C++ | rpuntaie/c-examples | /r/b2.cpp | UTF-8 | 871 | 3.265625 | 3 | [
"MIT"
] | permissive | /*
g++ -std=c++20 -o ../_build/r/b2.exe r/b2.cpp && (cd ../_build/r;./b2.exe)
*/
#include <iostream>
#include <map>
#include <string>
using namespace std;
// Driver Code
int main()
{
// Key-value pair declared inside
// Map data structure
map<string, string> fav_lang{
{ "John", "Java" },
{ "Alex", "C++" },
{ "Peter", "Python" }
};
// Structure binding concept used
// position and success are used
// in place of first and second
auto[process, success]
= fav_lang.insert({ "Henry",
"Golang" });
// Check boolean value of success
if (success) {
cout << "Insertion done!!"
<< endl;
}
// Iterate over map
for (const auto & [ name, lang ] : fav_lang) {
cout << name << ":"
<< lang << endl;
}
return 0;
}
| true |
80e0d1e4f48df5e9c8f7c8761250a7864b99196a | C++ | ske-ableton/public_sscce | /plugins-using-typeid/mydependency.h | UTF-8 | 551 | 2.609375 | 3 | [] | no_license |
#pragma once
#include "mydependency_export.h"
#include <typeinfo>
#include <cassert>
template <typename T>
T* registerType();
MYDEPENDENCY_EXPORT void* registerTypeInternal(const std::type_info & typeinfo, void* def);
MYDEPENDENCY_EXPORT void* lookupTypeInternal(const std::type_info & typeinfo);
template <typename T>
inline T* registerType()
{
void* ptr = lookupTypeInternal(typeid(T));
if (ptr == nullptr)
{
ptr = registerTypeInternal(typeid(T), new T);
assert (ptr != nullptr);
}
return static_cast<T*>(ptr);
}
| true |
1f36c2ceed3644b12a31b743d03353a19bc01bb1 | C++ | Muhahambr/labhero | /2dGames/LabHero.cpp | UTF-8 | 3,199 | 2.953125 | 3 | [] | no_license | #include "SFML/Graphics.hpp"
#include "LabHero.h"
#include "helpers.h"
using namespace sf;
LabHeroGame::LabHeroGame()
{
tiles_tex = new Texture();
tile = new Sprite();
hero_tex = new Texture();
hero_sprite = new Sprite();
//tile
tiles_tex->loadFromFile("images/Hero/tilearea.png");
tile->setTexture(*tiles_tex);
tile->setTextureRect(IntRect(0, 224, 64, 64));
//hero sprite
hero_tex->loadFromFile("images/Hero/remakertp01.png", IntRect(6 * 32, 0, 3 * 32, 4 * 48));
hero_sprite->setTexture(*hero_tex);
// Declare and create a new render-window
window = new RenderWindow(sf::VideoMode(cellSize*gridWidth, cellSize*gridHeight), "SFML window");
}
LabHeroGame::~LabHeroGame()
{
}
void LabHeroGame::Draw()
{
window->clear();
DrawMap();
DrawHero();
// End the current frame and display its contents on screen
window->display();
}
void LabHeroGame::DrawMap()
{
for (int i = 0; i < gridWidth; i++)
{
for (int j = 0; j < gridHeight; j++)
{
tile->setPosition(i * cellSize, j * cellSize);
window->draw(*tile);
}
}
}
void LabHeroGame::DrawHero()
{
//draw char
hero_sprite->setPosition(PixelCoords.x + 16, PixelCoords.y + 6 );
hero_sprite->setTextureRect(IntRect((frame_counter / 6 % 3) * 32, 0, 32, 48));
window->draw(*hero_sprite);
}
void LabHeroGame::GetInput()
{
if (Keyboard::isKeyPressed(Keyboard::Right) && state == EHeroState::idle)
{
state = EHeroState::run;
SetNewDestination(CellCoords(1, 0) );
}
if (Keyboard::isKeyPressed(Keyboard::Left) && state == EHeroState::idle)
{
state = EHeroState::run;
SetNewDestination(CellCoords(-1, 0));
}
if (Keyboard::isKeyPressed(Keyboard::Up) && state == EHeroState::idle)
{
state = EHeroState::run;
SetNewDestination(CellCoords(0, -1));
}
if (Keyboard::isKeyPressed(Keyboard::Down) && state == EHeroState::idle)
{
state = EHeroState::run;
SetNewDestination(CellCoords(0, 1));
}
if (Keyboard::isKeyPressed(Keyboard::Escape))
window->close();
}
void LabHeroGame::SetNewDestination(CellCoords dir)
{
next_cell = current_cell + dir;
path = cellSize;
}
V2 LabHeroGame::GetMoveDirection()
{
return (next_cell - current_cell).NormalAsV2();
}
void LabHeroGame::MoveHero()
{
if (state == EHeroState::run)
{
PixelCoords = PixelCoords + GetMoveDirection() * moveSpeed * deltaTime;
path -= moveSpeed * deltaTime;
if (path <= 0)
{
current_cell = next_cell;
PixelCoords = V2(current_cell.i*cellSize, current_cell.j*cellSize);
state = EHeroState::idle;
}
}
}
void LabHeroGame::Tick()
{
MoveHero();
}
void LabHeroGame::Run()
{
Clock clock;
float oldTime = clock.getElapsedTime().asSeconds();
// Limit the framerate to 60 frames per second (this step is optional)
window->setFramerateLimit(60);
// The main loop - ends as soon as the window is closed
while (window->isOpen())
{
deltaTime = clock.getElapsedTime().asSeconds() - oldTime;
oldTime = clock.getElapsedTime().asSeconds();
// Event processing
sf::Event event;
while (window->pollEvent(event))
{
// Request for closing the window
if (event.type == sf::Event::Closed)
window->close();
}
frame_counter++;
GetInput();
Tick();
Draw();
}
}
| true |
7c019af21b458a950bb95675ff05f75df7d1d535 | C++ | commandblock2/snake_the_game | /core/include/snake_the_game.h | UTF-8 | 1,633 | 3.3125 | 3 | [] | no_license | #pragma once
#include <atomic>
#include <chrono>
#include <list>
#include <vector>
#include <mutex>
namespace snake_the_game
{
using namespace std::literals::chrono_literals;
enum class direction
{
up, down, left, right
};
enum class block
{
death, food, none
};
class game
{
public:
//type alias section
using point = std::pair<int, int>;
//point::first stands for x(horizontal),second for y
// x positive -> horizontal right, y positive -> verticle down
protected:
//constant section
const int width, height;
const std::chrono::milliseconds regular_interval;
const std::chrono::milliseconds fast_interval;
private:
//private data section
std::list<point> body; //front is head and back is tail
std::vector<point> food;
mutable std::mutex rwlock;
bool gameover = false;
int length_to_strech;
//atomic
std::atomic<direction> direction_{direction::right};
std::atomic<bool> instant_tick{false};
std::atomic<std::chrono::milliseconds> interval;
public:
game(const int width = 20, const int height = 20,
const int length_strech_per_food = 3,
const std::chrono::milliseconds regular_interval = 500ms,
const std::chrono::milliseconds fast_interval = 200ms);
protected:
void exec();
const std::list<point> get_snake_body() const;
const std::vector<point> get_food() const;
//const snake_the_game::direction& get_direction() const;
void on_key_down(snake_the_game::direction d);
void on_key_up();
bool game_over();
private:
const point cauculate_next_pos();
void advance_snake();
block check_available(const point& position) const;
};
}
| true |
e671fda517450a32edd337db97c516ff64948d0b | C++ | stockdillon/operating_systems | /proj09/backup.cpp | UTF-8 | 15,184 | 3.1875 | 3 | [] | no_license | /*
Dillon Stock stockdil@basset
2017-04-03
proj08.student.c
Your Comments
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <string.h>
#include <fstream>
#include <vector>
#include <algorithm>
using std::cout; using std::endl;
using namespace std;
struct process{
public:
unsigned pid;
unsigned priority;
unsigned burstNum;
unsigned burstTime;
unsigned blockedTime;
unsigned arrivalTime = 0;
unsigned currentState = 0;
unsigned cumulativeTimes[4] = {};
unsigned remainingBursts = burstNum; // the number of bursts left before process halts
unsigned remainingDuration = 0; // amount of time before process is blocked/halted
unsigned turnaround = 0;
unsigned entered_ready = 0;
//double normalizedTurnaround = 0;
//bool haltRequest = false;
//bool blockRequest = false;
vector<unsigned> ticksNew;
vector<unsigned> ticksReady;
vector<unsigned> ticksRunning;
vector<unsigned> ticksBlocked;
/*
bool operator<(const process& other) const
{
return (this->arrivalTime < other.arrivalTime);
}
*/
};
// To display all appropriate process statistics before releasing it from memory
void exitDisplay(const process& p1, unsigned clock){
cout << "PID: " << p1.pid << endl;
cout << "Priority: " << p1.priority << endl;
cout << "Number of CPU bursts: " << p1.burstNum << endl;
cout << "Burst Time (in ticks): " << p1.burstTime << endl;
cout << "Blocked Time (in ticks): " << p1.blockedTime << endl;
cout << "Arrival Time (in ticks since start of simulation): " << p1.arrivalTime << endl;
cout << "Departure time: " << clock << endl;
cout << "Cumulative time in the New state: " << p1.cumulativeTimes[0] << endl;
cout << "Cumulative time in the Ready state: "<< p1.cumulativeTimes[1] << endl;
cout << "Cumulative time in the Running state: "<< p1.cumulativeTimes[2] << endl;
cout << "Cumulative time in the Blocked state: "<< p1.cumulativeTimes[3] << endl;
cout << "Turnaround time: " << p1.turnaround << endl;
//cout << "Normalized turnaround time: " << p1.normalizedTurnaround << endl;
//cout << "Normalized Turnaround Time: " << (p1.turnaround/p1.cumulativeTimes[2]) << endl;
double normalizedTurnaround = (p1.turnaround/double(p1.cumulativeTimes[2]));
cout << "Normalized Turnaround Time: " << setprecision(3) << normalizedTurnaround << endl;
////////////////////////////////// Comment out ///////////////////////////////////////////////////////////////////
/*
cout << "Ticks spent in New state: "; for(auto& tick : p1.ticksNew) cout << tick << " "; cout << endl;
cout << "Ticks spent in Ready state: "; for(auto& tick : p1.ticksReady) cout << tick << " "; cout << endl;
cout << "Ticks spent in Running state: "; for(auto& tick : p1.ticksRunning) cout << tick << " "; cout << endl;
cout << "Ticks spent in Blocked state: "; for(auto& tick : p1.ticksBlocked) cout << tick << " "; cout << endl;
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cout << endl;
}
// First compares arrival time
// breaks ties using process ID
bool arrival_compare(const process& p1, const process& p2){
if(p1.arrivalTime != p2.arrivalTime){
return p1.arrivalTime < p2.arrivalTime;
}
return p1.pid < p2.pid;
}
// First compares priority,
// To break priority ties, we give preference to the process which has been ready the longest
// Finally we break ties using process ID
bool priority_compare(const process& p1, const process& p2){
if(p1.priority != p2.priority){
return (p1.priority < p2.priority);
}
if(p1.entered_ready != p2.entered_ready){
return (p1.entered_ready < p2.entered_ready);
}
return p1.pid < p2.pid;
}
bool duration_compare(const process& p1, const process& p2){
return p1.remainingDuration < p2.remainingDuration;
}
// To display all process info for each process in a vector of processes
void display_process_info(vector<struct process>& processes){
for(const auto& p1 : processes){
cout << p1.pid << " " << p1.priority << " " << p1.burstNum << " " << p1.burstTime << " " << p1.blockedTime << " " << p1.arrivalTime << endl;
}
}
int main(int argc, char *argv[], char** variables)
{
//cout << "argc: " << argc << endl; // *** remove ***
if(argc != 3){
cout << "Invalid number of arguments... (expected 3) Ending program." << endl;
return -1;
}
ifstream infile(argv[2]);
if(!infile){
cout << "Invalid file name received... Exiting program" << endl;
return -1;
}
string N_error_test = argv[1];
for(char c : N_error_test){
if( c - '0' < 0 || c - '0' > 9){
cout << "Invalid argument for N (expected a positive integer or 0)... quitting program" << endl;
return 0;
}
}
int N = stoi(string(argv[1]), nullptr, 10);
//cout << "N: " << N << endl; // *** remove
string cpuStr;
string pcbStr;
string tickStr;
unsigned cpuNum;
unsigned pcbNum;
unsigned tickNum;
string alg;
getline(infile,cpuStr);
getline(infile, pcbStr);
getline(infile, tickStr);
getline(infile, alg);
cout << "Number of CPUs: " << cpuStr << endl;
cout << "Number of PCBs: " << pcbStr << endl;
cout << "Length of simulation (in ticks): " << tickStr << endl;
cout << "Short-term scheduling algorithm: " << alg << endl << endl;
std::transform(alg.begin(), alg.end(), alg.begin(), ::toupper);
cpuNum = stoi(cpuStr, nullptr, 10);
pcbNum = stoi(pcbStr, nullptr, 10);
tickNum = stoi(tickStr, nullptr, 10);
//vector<struct process> all;
vector<struct process> batch;
vector<struct process> newProcesses;
vector<struct process> ready;
vector<struct process> blocked;
vector<struct process> running;
struct process p1;
while(infile >> p1.pid){
infile >> p1.priority >> p1.burstNum >> p1.burstTime >> p1.blockedTime >> p1.arrivalTime;
p1.remainingBursts = p1.burstNum; // *************************8
batch.push_back(p1);
}
if(alg != "FCFS" && alg != "PRIORITY"){
cout << "Invalid placement algorithm selected (expected 'FCFS' or 'Priority')... Exiting program" << endl;
return -1;
}
std::sort(batch.begin(), batch.end(), arrival_compare);
/* This should not be included for sorting the original batch, as the algorithm
* is 'non-preemptive' and does not know of a given process until it arrives
else if(alg == "Priority"){
//cout << "Sorting using Priority... " << endl;
std::sort(batch.begin(), batch.end(), priority_compare);
}
*/
//for(unsigned i=1; i<=tickNum; i++){
unsigned clock = 0;
while(clock < tickNum){
//cout << "i: " << i << " -----------------------------" << endl << endl;
if(!running.empty()){
//cout << "sorting running processes by remaining duration... " << endl;
std::sort(running.begin(), running.end(), duration_compare);
//cout << "processing request issued by the process (pid: " << running[0].pid << ") in Running state" << endl;
//cout << "remaining duration of running[0] : " << running[0].remainingDuration << endl;
//cout << "remaining (cpu) bursts of running[0] : " << running[0].remainingBursts << endl;
if(running[0].remainingDuration == 0){
if(running[0].remainingBursts > 0){
//cout << "Running process requested BLOCK." << endl;
running[0].currentState = 3;
//cout << "bursts left : " << running[0].remainingBursts << endl;
running[0].remainingDuration = running[0].blockedTime;
blocked.push_back(running[0]);
running.erase(running.begin());
cpuNum++;
}
else if(running[0].remainingBursts == 0){
//cout << "Running process requested HALT." << endl;
running[0].turnaround = clock - running[0].arrivalTime;
exitDisplay(running[0], clock);
//cout << "clock: " << clock << endl;
//cout << "running[0].arrivalTime: " << running[0].arrivalTime << endl;
//cout << "running[0].turnaround: " << running[0].turnaround << endl;
running.erase(running.begin());
pcbNum++;
cpuNum++;
}
}
}
if(!blocked.empty()){
//cout << "sorting blocked processes by remaining duration... " << endl;
std::sort(blocked.begin(), blocked.end(), duration_compare);
//cout << "checking if process in blocked state should become unblocked..." << endl;
//cout << "remaining duration (to stay blocked) : " << blocked[0].remainingDuration << endl;
//if(blocked[0].remainingDuration == 0){
while(!blocked.empty() && blocked[0].remainingDuration == 0){
//cout << "unblocking process..." << endl;
blocked[0].currentState = 1;
blocked[0].entered_ready = clock;
ready.push_back(blocked[0]);
blocked.erase(blocked.begin());
}
}
if(!batch.empty()){
//cout << "found a process in the batch, must move to NEW processes" << endl;
//if(clock == batch[0].arrivalTime){
while(clock == batch[0].arrivalTime && !batch.empty()){
//cout << "process (pid: " << batch[0].pid << ") in batch has arrived... adding it to NEW processes (clock: " << clock << ")" << endl;
batch[0].currentState = 0;
//batch[0].cumulativeTimes[batch[0].currentState]++;
newProcesses.push_back(batch[0]);
batch.erase(batch.begin());
}
}
if(pcbNum > 0){
//if(!newProcesses.empty()){
while(!newProcesses.empty() && pcbNum > 0){
//cout << "allocating PCB to new process (pid: " << newProcesses[0].pid << ")" << endl;
newProcesses[0].currentState = 0;
ready.push_back(newProcesses[0]);
newProcesses.erase(newProcesses.begin());
pcbNum--;
}
}
if(!ready.empty()){
//cout << "ready process found." << endl;
/*
if(alg == "FCFS"){
sort(ready.begin(), ready.end(), arrival_compare);
}
*/
if(alg == "PRIORITY"){
sort(ready.begin(), ready.end(), priority_compare);
}
//if(running.empty() || running.size() < cpuNum){
while(running.empty() || running.size() < cpuNum){
//cout << "moving process from ready ---> to running" << endl;
ready[0].remainingDuration = ready[0].burstTime;
//cout << "ready[0].remainingBursts : " << ready[0].remainingBursts << endl;
ready[0].remainingBursts--;
//cout << "moved process to 'running' with " << ready[0].remainingBursts << " burst left... " << endl; //******
ready[0].currentState = 1;
running.push_back(ready[0]);
ready.erase(ready.begin());
cpuNum--;
}
}
for(auto& p : newProcesses){
p.cumulativeTimes[0]++;
//cout << "time in new state: " << p.cumulativeTimes[0] << endl;
p.ticksNew.push_back(clock);
}
for(auto& p : ready){
p.cumulativeTimes[1]++;
//cout << "time in ready state: " << p.cumulativeTimes[1] << endl;
p.ticksReady.push_back(clock);
}
for(auto& p : running){
p.cumulativeTimes[2]++;
//cout << "time in running state: " << p.cumulativeTimes[2] << endl;
p.remainingDuration--;
//cout << "remaining duration (pid: " << p.pid << ") in running state: " << p.remainingDuration << endl;
p.ticksRunning.push_back(clock);
}
for(auto& p : blocked){
p.cumulativeTimes[3]++;
//cout << "time in blocked state: " << p.cumulativeTimes[3] << endl;
p.remainingDuration--;
//cout << "remaining duration (pid: " << p.pid << ") in blocked state: " << p.remainingDuration << endl;
p.ticksBlocked.push_back(clock);
}
clock++;
if(N > 0 && clock % N == 0 && clock != 0){
cout << "Displaying Process Statuses... (Tick: " << clock << ")" << endl;
cout << "New process IDs: ";
for(auto& p : newProcesses){
cout << p.pid << ", ";
}
cout << endl;
cout << "Ready process IDs: ";
for(auto& p : ready){
cout << p.pid << ", ";
}
cout << endl;
cout << "Running process IDs: ";
for(auto& p : running){
cout << p.pid << ", ";
}
cout << endl;
cout << "Blocked process IDs: ";
for(auto& p : blocked){
cout << p.pid << ", ";
}
cout << endl;
cout << endl;
}
}
/*
* To Complete:
* Read Requirement Number 5 on the Project 9 description...
* 'Non-Preemptive FCFS scheduling' versus 'Non-Preemptive Priority scheduling'
*/
/*
cout << "pid: " << pid << endl;
cout << "priority: " << priority << endl;
cout << "burstNum: " << burstNum << endl;
cout << "burstTime: " << burstTime << endl;
cout << "blockedTime: " << blockedTime << endl;
cout << "arrivalTime: " << arrivalTime << endl;
*/
/*
cout << endl;
cout << "Displaying parameters... (end of program)" << endl; // ***
cout << "pid: " << p1.pid << endl;
cout << "priority: " << p1.priority << endl;
cout << "burstNum: " << p1.burstNum << endl;
cout << "burstTime: " << p1.burstTime << endl;
cout << "blockedTime: " << p1.blockedTime << endl;
cout << "arrivalTime: " << p1.arrivalTime << endl;
cout << "Departure time: " << clock << endl;
cout << "Cumulative time in the New state: " << p1.cumulativeTimes[0] << endl;
cout << "Cumulative time in the Ready state: "<< p1.cumulativeTimes[1] << endl;
cout << "Cumulative time in the Running state: "<< p1.cumulativeTimes[2] << endl;
cout << "Cumulative time in the Blocked state: "<< p1.cumulativeTimes[3] << endl;
*/
}
| true |
2dfaf74ec5f7ce0da6cd992880d3ea2c86659f9f | C++ | rfdnl/fyp-engine | /Subsystem/Component/Graphics/RectangleRenderer.hpp | UTF-8 | 1,679 | 2.8125 | 3 | [] | no_license | #ifndef RECTANGLE_RENDERER_HPP
#define RECTANGLE_RENDERER_HPP
#include <memory>
#include "VertexArray.hpp"
#include "VertexBuffer.hpp"
#include "IndexBuffer.hpp"
#include "VertexBufferLayout.hpp"
#include "Shader.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
class RectangleRenderer{
std::shared_ptr<VertexArray> va; //
std::shared_ptr<VertexBuffer> vb; //
std::shared_ptr<IndexBuffer> ib; //
std::shared_ptr<VertexBufferLayout> layout = std::make_shared<VertexBufferLayout>();
std::shared_ptr<Shader> shader; //
//glm::vec3 translation = glm::vec3(0, 0, 0);
glm::mat4 proj = glm::ortho(0.0f, 960.0f, 0.0f, 540.0f, -1.0f, 1.0f);
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
public:
RectangleRenderer(){
float position[] = {
-0.5f, -0.5f, // 0
0.5f, -0.5f, // 1
0.5f, 0.5f, // 2
-0.5f, 0.5f // 3
};
unsigned int indices[] = {
0, 1, 2,
2, 3, 0
};
va = std::make_shared<VertexArray>();
vb = std::make_shared<VertexBuffer>(position, 4 * 2 * sizeof(float));
layout->Push<float>(2);
va->AddBuffer(*vb, *layout);
ib = std::make_shared<IndexBuffer>(indices, 3 * 2);
shader = std::make_shared<Shader>("shader/Basic.shader");
shader->Bind();
shader->SetUniform4f("myColor", 0.5f, 0.3f, 0.8f, 1.0f);
va->Unbind();
vb->Unbind();
ib->Unbind();
shader->Unbind();
}
~RectangleRenderer(){}
void Draw(glm::vec3 translation, glm::vec4 rgba){
shader->Bind();
va->Bind();
ib->Bind();
glCall(glDrawElements(GL_TRIANGLES, ib->GetCount(), GL_UNSIGNED_INT, nullptr));
}
};
#endif // RECTANGLE_RENDERER_HPP
| true |
23c5757e55c89619d29d44794cd52dc2770dd7ba | C++ | carlpatt/college-projects | /CS117 Programming 2/practiceSet1-1.cpp | UTF-8 | 243 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct Student {
int idNumver;
int asmissionYear;
float gpa;
};
int main() {
Student s1 = {346789, 2014, 3.89};
Student s2 = {980077, 2015};
return 0;
}
| true |
0386d16c29aa52b08245ea4da20f2090fabd7b85 | C++ | spencerparkin/Junk | /3DPortalSystem/spencer.cpp | UTF-8 | 1,476 | 2.65625 | 3 | [] | no_license | // spencer.cpp
// Programmed by Spencer T. Parkin
#include <glut.h>
#include "spencer.h"
#include "cell.h"
#include "macros.h"
#include "camera.h"
#include "main.h"
#include "wall.h"
Spencer *spencer = 0;
Spencer::Spencer()
{
// These should get loaded in the map.
t_walk[0] = 0;
t_walk[1] = 0;
t_walk[2] = 0;
t_walk[3] = 0;
t_stand = 0;
prev_x = prev_y = 0.f;
anim_frame = 0.f;
}
Spencer::~Spencer()
{
}
// I'm drawn only if the camera is
// not in 1st person mode.
void Spencer::Draw(fovi *f)
{
glLineWidth(2.f);
glBegin(GL_LINES);
glColor3f(0.f, 0.f, 0.f);
glVertex3f(x, y, -WALL_HEIGHT / 2.f + 0.1f);
glVertex3f(x + cos(this->f.heading), y + sin(this->f.heading), -WALL_HEIGHT / 2.f + 0.1f);
glEnd();
glLineWidth(1.f);
if(cam->mode != CAM_MODE_1ST_PERSON)
Entity::Draw(f);
}
// Normally the user-input would be read
// and dealt with from this routine, but
// since we're using an event-driven callback
// model thingy using GLUT, all the code to
// control this entity is in main.cpp. So
// here I'm putting the animation code.
void Spencer::Drive(void)
{
// This code is pretty cheesy, but it works okay.
if(prev_x == x && prev_y == y && anim_frame == 0.f)
t = t_stand;
else
{
int index = int(anim_frame) % 4;
t = t_walk[index];
static const float walk_fps = 3.f; // Go at 3 walk-animation-frames per second.
anim_frame += walk_fps / FPS;
if(anim_frame >= 4.f)
anim_frame = 0.f;
prev_x = x;
prev_y = y;
}
}
// endof spencer.cpp | true |
e90e1948ee13aaf32891e080b88dc1aacf029e73 | C++ | sedoy-jango-2/Coffe-check | /journal.h | UTF-8 | 892 | 2.59375 | 3 | [] | no_license | #ifndef JOURNAL_H
#define JOURNAL_H
#include "basenote.h"
#include "note.h"
#include "testnote.h"
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QDateTime>
class Journal
{
public:
Journal();
Journal(const Journal ©write);
BaseNote ** mass;
BaseNote &operator[](int i);
int size();
void deleteElement(int index);
void addTestElement(int index, TestNote addElement);
void addRegularElement(int index, Note addElement);
void readFromF(QString nameOfFile);
void writeToF(QString fname);
void show(int i);
bool isEmpty();
bool getIsCorrect();
int getCoffeeVolume();
void setIsCorrect(TestNote note);
~Journal();
private:
bool isCorrect;
int coffeeValume;
int cupValue;
int sizeOfMass;
int currentSize;
void resize();
int coffeeSize(int currentValume);
};
#endif // JOURNAL_H
| true |
732d7aa7faf0f00f44991bd0e6f78872b95ad2e5 | C++ | zackkk/leetcode | /Length of Last Word.cpp | UTF-8 | 355 | 3.140625 | 3 | [] | no_license | class Solution {
public:
// use s[i]
int lengthOfLastWord(const char *s) {
if(s == NULL) return 0;
int right = strlen(s) - 1;
while(s[right] == ' ') right--;
if(right < 0) return 0;
int left = right;
while(left - 1 >= 0 && s[left-1] != ' ') left--;
return right - left + 1;
}
}; | true |
9b3980d9df5297ce57fc04594add5ac6b40cefdf | C++ | rushingJustice/C-programming-and-matlab-projects | /Finite Elements - Direct Sitffness Methods/Programs from E-book/Example13_4_2/main.cpp | UTF-8 | 777 | 3.1875 | 3 | [] | no_license | /* Example 13.4.2
Copyright(c) 2005-08, S. D. Rajan
Object-Oriented Numerical Analysis
*/
#include <iostream>
#include "myaddlibrary.h"
int main ()
{
// define a pointer variable to a function
// with a specified signature
float (CMyAddLibrary::*ptAddFunction) (float, float) = NULL;
CMyAddLibrary MAL1;
// assign the address of the function
ptAddFunction = &CMyAddLibrary::AddSimpleTwo;
// use the function
std::cout << "Simple addition gives "
<< (MAL1.*ptAddFunction)(2.3f, 3.4f) << '\n';
// pass the pointer variable as an argument
MAL1.Use_In_A_Function (ptAddFunction);
// reassign and reuse
ptAddFunction = &CMyAddLibrary::AddSquareTwo;
MAL1.Use_In_A_Function (ptAddFunction);
return 0;
}
| true |
615e6d5b02454edaacfde0ef424bf9c9c49121d9 | C++ | nozdrenkov/sp | /codeforces/gcpc-2015/k.cpp | UTF-8 | 784 | 2.984375 | 3 | [] | no_license | string rot(const string &s) {
string t = s;
reverse(all(t));
for (auto &c : t) {
if (c == '3' || c == '4' || c == '7') return "";
if (c == '6') c = '9';
else if (c == '9') c = '6';
}
return t;
}
LL toLL(const string &s) {
istringstream is(s);
LL x; is >> x;
return x;
}
bool prime(LL x) {
if (x < 2) return false;
if (x > 2 && x % 2 == 0) return false;
for (LL d = 2; d * d <= x; ++d) {
if (x % d == 0) {
return false;
}
}
return true;
}
bool solve() {
string a; cin >> a;
if (!prime(toLL(a))) return false;
string b = rot(a);
if (b == "") return false;
if (!prime(toLL(b))) return false;
return true;
}
int main() {
cout << (solve() ? "yes" : "no") << endl;
return 0;
}
| true |
22ba496e35390937fc61f1b92483d15a81931023 | C++ | cenariusxz/ACM-Coding | /zoj/13/C.cpp | UTF-8 | 1,892 | 3.09375 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int pos[10],lab[10];
int num[10];
void s1(){
int d;
scanf("%d%d%d%d%d",&d,&num[1],&num[2],&num[3],&num[4]);
if(d==1||d==2){
pos[1]=2;
lab[1]=num[2];
}
if(d==3){
pos[1]=3;
lab[1]=num[3];
}
if(d==4){
pos[1]=4;
lab[1]=num[4];
}
printf("%d %d\n",pos[1],lab[1]);
}
void s2(){
int d;
scanf("%d%d%d%d%d",&d,&num[1],&num[2],&num[3],&num[4]);
if(d==1){
for(int i=1;i<=4;++i){
if(num[i]==4){
pos[2]=i;
lab[2]=num[i];
}
}
}
if(d==2||d==4){
pos[2]=pos[1];
lab[2]=num[pos[1]];
}
if(d==3){
pos[2]=1;
lab[2]=num[1];
}
printf("%d %d\n",pos[2],lab[2]);
}
void s3(){
int d;
scanf("%d%d%d%d%d",&d,&num[1],&num[2],&num[3],&num[4]);
if(d==1){
for(int i=1;i<=4;++i){
if(num[i]==lab[2]){
pos[3]=i;
lab[3]=num[i];
}
}
}
if(d==2){
for(int i=1;i<=4;++i){
if(num[i]==lab[1]){
pos[3]=i;
lab[3]=num[i];
}
}
}
if(d==3){
pos[3]=3;
lab[3]=num[3];
}
if(d==4){
for(int i=1;i<=4;++i){
if(num[i]==4){
pos[3]=i;
lab[3]=num[i];
}
}
}
printf("%d %d\n",pos[3],lab[3]);
}
void s4(){
int d;
scanf("%d%d%d%d%d",&d,&num[1],&num[2],&num[3],&num[4]);
if(d==1){
pos[4]=pos[1];
lab[4]=num[pos[1]];
}
if(d==2){
pos[4]=1;
lab[4]=num[1];
}
if(d==3||d==4){
pos[4]=pos[2];
lab[4]=num[pos[2]];
}
printf("%d %d\n",pos[4],lab[4]);
}
void s5(){
int d;
scanf("%d%d%d%d%d",&d,&num[1],&num[2],&num[3],&num[4]);
if(d==1||d==2){
for(int i=1;i<=4;++i){
if(num[i]==lab[d]){
pos[5]=i;
lab[5]=num[i];
}
}
}
if(d==3){
for(int i=1;i<=4;++i){
if(num[i]==lab[4]){
pos[5]=i;
lab[5]=num[i];
}
}
}
if(d==4){
for(int i=1;i<=4;++i){
if(num[i]==lab[3]){
pos[5]=i;
lab[5]=num[i];
}
}
}
printf("%d %d\n",pos[5],lab[5]);
}
int main(){
int T;
scanf("%d",&T);
while(T--){
s1();
s2();
s3();
s4();
s5();
}
}
| true |
e67fc19519143280c2cf6ad9474f620dc72e7e95 | C++ | Matheusbafutto/needle_in_haystack | /main.cpp | UTF-8 | 793 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{ string needle, haystack[51],a = "que";
int i = 0;
cout << "Enter String to be found:" <<endl;
cin >> needle;
cout << "Enter array of strings." << endl;
cout << "(write";
cout << " stop to terminate filling the array)";
while (a != "stop"){
cin >> haystack[i];
a = haystack[i];
i++;
}
for (i = 0; i < 50; i++){
a = haystack[i];
if (a == needle){
cout << "The was detected on";
cout << " position " << i ;
cout << " on the haystack"<< endl;
break;
}
}
if (a != needle){
cout << "No such string found." << endl;
}
return 0;
}
| true |
3f7416b058235abf3b143cc9c13f69be7b396657 | C++ | hvotheraccount/Simple-Stock | /Super Simple Stock/StockLibrary/Stock/PreferredStock.cpp | UTF-8 | 516 | 2.703125 | 3 | [] | no_license | #include "PreferredStock.h"
#include "..\Exceptions\Exceptions.h"
namespace simplestock
{
PreferredStock::PreferredStock(const std::string& stockSymbol, double lastDividend, double parValue, double fixedDividend) :
AbstractStock(stockSymbol, lastDividend, parValue),
fixedDividend_(fixedDividend)
{
}
PreferredStock::~PreferredStock()
{
}
double PreferredStock::calculateDividendYield(double price)
{
if (!price)
throw DivideByZeroException();
return (fixedDividend_ * parValue_) / price;
}
} | true |
f08a28a69ffdaaf9136735040b60185f57b74827 | C++ | shri314/resolver | /include/dns/r_code.h | UTF-8 | 3,136 | 2.703125 | 3 | [] | no_license | #pragma once
#include <ostream>
namespace dns
{
enum class r_code_t : uint8_t
{
no_error = 0, /* No Error, [RFC1035] */
form_err = 1, /* Format Error, [RFC1035] */
serv_fail = 2, /* Server Failure, [RFC1035] */
nx_domain = 3, /* Non-Existent Domain, [RFC1035] */
not_imp = 4, /* Not Implemented, [RFC1035] */
refused = 5, /* Query Refused, [RFC1035] */
yx_domain = 6, /* Name Exists when it should not, [RFC2136][RFC6672] */
yx_rrset = 7, /* RR Set Exists when it should not, [RFC2136] */
nx_rrset = 8, /* RR Set that should exist does not, [RFC2136] */
not_auth = 9, /* Server Not Authoritative for zone, [RFC2136], Not Authorized, [RFC2845] */
not_zone = 10, /* Name not contained in zone, [RFC2136] */
bad_vers = 16, /* Bad OPT Version, [RFC6891] */
bad_sig = 16, /* TSIG Signature Failure, [RFC2845] */
bad_key = 17, /* Key not recognized, [RFC2845] */
bad_time = 18, /* Signature out of time window, [RFC2845] */
bad_mode = 19, /* Bad TKEY Mode, [RFC2930] */
bad_name = 20, /* Duplicate key name, [RFC2930] */
bad_alg = 21, /* Algorithm not supported, [RFC2930] */
bad_trunc = 22, /* Bad Truncation, [RFC4635] */
bad_cookie = 23, /* Bad/missing Server Cookie, [RFC7873] */
/* unassigned = 11-15, */
/* unassigned = 24-3840, */
/* reserved = 3841-4095, private use, [RFC6895] */
/* unassigned = 4096-65534, */
/* reserved = 65535, can be allocated by Standards Action, [RFC6895] */
};
std::ostream& operator<<(std::ostream& os, r_code_t rhs)
{
switch(rhs)
{
case r_code_t::no_error:
return os << "no_error";
case r_code_t::form_err:
return os << "form_err";
case r_code_t::serv_fail:
return os << "serv_fail";
case r_code_t::nx_domain:
return os << "nx_domain";
case r_code_t::not_imp:
return os << "not_imp";
case r_code_t::refused:
return os << "refused";
case r_code_t::yx_domain:
return os << "yx_domain";
case r_code_t::yx_rrset:
return os << "yx_rrset";
case r_code_t::nx_rrset:
return os << "nx_rrset";
case r_code_t::not_auth:
return os << "not_auth";
case r_code_t::not_zone:
return os << "not_zone";
case r_code_t::bad_vers:
return os << "bad_vers|bad_sig";
case r_code_t::bad_key:
return os << "bad_key";
case r_code_t::bad_time:
return os << "bad_time";
case r_code_t::bad_mode:
return os << "bad_mode";
case r_code_t::bad_name:
return os << "bad_name";
case r_code_t::bad_alg:
return os << "bad_alg";
case r_code_t::bad_trunc:
return os << "bad_trunc";
case r_code_t::bad_cookie:
return os << "bad_cookie";
}
return os << static_cast<unsigned>(rhs);
}
}
| true |
611bd33619eda088cc02f11fca29a507f2bdb0f4 | C++ | deepbluev7/mtxclient | /include/mtx/events/encryption.hpp | UTF-8 | 641 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace mtx {
namespace events {
namespace state {
//! Content of the `m.room.encryption` event.
//
//! A client can enable encryption to a room by sending this event.
struct Encryption
{
//! Defines which encryption algorithm should be used for encryption.
//! Currently only m.megolm.v1-aes-sha2 is permitted.
std::string algorithm = "m.megolm.v1.aes-sha2";
};
void
from_json(const json &obj, Encryption &encryption);
void
to_json(json &obj, const Encryption &encryption);
} // namespace state
} // namespace events
} // namespace mtx
| true |
2bd203949e740b0058fd3cfc670a3a87006fc9ba | C++ | phongvcao/CP_Contests_Solutions | /cpp/Codeforces/301-350/344A_Magnets.cc | UTF-8 | 1,213 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <tr1/memory>
class Magnet {
public:
Magnet();
Magnet(int left, int right);
int left;
int right;
};
Magnet::Magnet() :
left(0),
right(0)
{
}
Magnet::Magnet(int left, int right) :
left(left),
right(right)
{
}
int main(int argc, char **argv) {
long long int n = 0;
// Read the first line
std::string line = "";
if (std::getline(std::cin, line)) {
std::stringstream ss(line);
ss >> n;
}
std::vector<std::tr1::shared_ptr<Magnet> > magnetsVector;
// Read the next n lines
while (std::getline(std::cin, line)) {
int left = line[0] - '0';
int right = line[1] - '0';
std::tr1::shared_ptr<Magnet> ptr(new Magnet(left, right));
magnetsVector.push_back(ptr);
--n;
if (n == 0) break;
}
long long int blocksCount = 0;
// Logic starts here
for (unsigned int i = 0; i != magnetsVector.size() - 1; ++i) {
if (magnetsVector[i]->right == magnetsVector[i + 1]->left) {
++blocksCount;
}
}
std::cout << ++blocksCount;
return 0;
}
| true |
0d68e031ebc50741efa1b7b2f72387e8f30665ac | C++ | cssanjay/ninja | /standAlone/largestNumberFromArray.cpp | UTF-8 | 315 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int compareFunction(string a, string b){
string ab = a.append(b);
string ba = b.append(a);
return ab.compare(ba)>0 ? 1:0;
}
void printLargest(vector<string> arr){
sort(arr.begin(), arr.end(), compareFunction);
for(int i = 0; i < arr.size(); i++)
cout << arr[i];
} | true |
91901b0ea0e37229374babb7854b9b8291b5102d | C++ | anbhimi/osrm-backend | /include/engine/datafacade/shared_memory_datafacade.hpp | UTF-8 | 3,472 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef SHARED_MEMORY_DATAFACADE_HPP
#define SHARED_MEMORY_DATAFACADE_HPP
// implements all data storage when shared memory _IS_ used
#include "storage/shared_barriers.hpp"
#include "storage/shared_datatype.hpp"
#include "storage/shared_memory.hpp"
#include "engine/datafacade/contiguous_internalmem_datafacade_base.hpp"
namespace osrm
{
namespace engine
{
namespace datafacade
{
/**
* This datafacade uses an IPC shared memory block as the data location.
* Many SharedMemoryDataFacade objects can be created that point to the same shared
* memory block.
*/
class SharedMemoryDataFacade : public ContiguousInternalMemoryDataFacadeBase
{
protected:
std::unique_ptr<storage::SharedMemory> m_large_memory;
std::shared_ptr<storage::SharedBarriers> shared_barriers;
storage::SharedDataType data_region;
unsigned shared_timestamp;
SharedMemoryDataFacade() {}
public:
// this function handle the deallocation of the shared memory it we can prove it will not be
// used anymore. We crash hard here if something goes wrong (noexcept).
virtual ~SharedMemoryDataFacade() noexcept
{
// Now check if this is still the newest dataset
boost::interprocess::sharable_lock<boost::interprocess::named_upgradable_mutex>
current_regions_lock(shared_barriers->current_region_mutex,
boost::interprocess::defer_lock);
boost::interprocess::scoped_lock<boost::interprocess::named_sharable_mutex> exclusive_lock(
data_region == storage::REGION_1 ? shared_barriers->region_1_mutex
: shared_barriers->region_2_mutex,
boost::interprocess::defer_lock);
// if this returns false this is still in use
if (current_regions_lock.try_lock() && exclusive_lock.try_lock())
{
if (storage::SharedMemory::RegionExists(data_region))
{
auto shared_region = storage::makeSharedMemory(storage::CURRENT_REGION);
const auto current_timestamp =
static_cast<const storage::SharedDataTimestamp *>(shared_region->Ptr());
// check if the memory region referenced by this facade needs cleanup
if (current_timestamp->region == data_region)
{
util::Log(logDEBUG) << "Retaining data with shared timestamp "
<< shared_timestamp;
}
else
{
storage::SharedMemory::Remove(data_region);
}
}
}
}
SharedMemoryDataFacade(const std::shared_ptr<storage::SharedBarriers> &shared_barriers_,
storage::SharedDataType data_region_,
unsigned shared_timestamp_)
: shared_barriers(shared_barriers_), data_region(data_region_), shared_timestamp(shared_timestamp_)
{
util::Log(logDEBUG) << "Loading new data with shared timestamp " << shared_timestamp;
BOOST_ASSERT(storage::SharedMemory::RegionExists(data_region));
m_large_memory = storage::makeSharedMemory(data_region);
InitializeInternalPointers(*reinterpret_cast<storage::DataLayout *>(m_large_memory->Ptr()),
reinterpret_cast<char *>(m_large_memory->Ptr()) + sizeof(storage::DataLayout));
}
};
}
}
}
#endif // SHARED_MEMORY_DATAFACADE_HPP
| true |
cdaf5d1c474835f471201018f4f93a08d43d98f1 | C++ | Jemoba/CSC412-CourseProject | /CourseProject/Pilot.cpp | UTF-8 | 2,976 | 2.953125 | 3 | [] | no_license | #include "Pilot.h"
Pilot:: Pilot(NXShield& nxt){
pnxshield = &nxt;
maxSpeed = 100;
currentSpeed = 0;
steerAngle = 0;
}
Pilot:: Pilot(NXShield& nxt, int ms){
pnxshield = &nxt;
maxSpeed = ms;
currentSpeed = 0;
steerAngle = 0;
}
void Pilot::fullStop(){
pnxshield->bank_a.motorStop(SH_Motor_1, SH_Next_Action_Brake);
}
void Pilot::slowStop(){
while(currentSpeed >= 1){
currentSpeed = currentSpeed - (currentSpeed/8);
pnxshield->bank_a.motorRunUnlimited(SH_Motor_1, SH_Direction_Forward, currentSpeed);
delay(50);
}
pnxshield->bank_a.motorStop(SH_Motor_1, SH_Next_Action_Brake);
}
void Pilot::driveAtSpeed(int s){
if(s > maxSpeed || s == -1)
currentSpeed = maxSpeed;
else
currentSpeed = s;
// Set drive motor running
pnxshield->bank_a.motorRunUnlimited(SH_Motor_1, SH_Direction_Forward, currentSpeed);
}
// Recieves a degree amount to turn; left degrees are negative, right are positive;
// Degree 0 is at center steer
void Pilot::turn(int turnDelta, int turnSpeed){
int turnAngle = steerAngle + turnDelta;
// Make sure no overturning
if(turnAngle < -60){
turnDelta = -60 - steerAngle;
steerAngle = -60;
} else if(turnAngle > 60){
turnDelta = 60 - steerAngle;
steerAngle = 60;
}else {
steerAngle = steerAngle + turnDelta;
}
if(turnDelta <0){
pnxshield->bank_a.motorRunDegrees(SH_Motor_2,
SH_Direction_Reverse,
turnSpeed,
turnDelta,
SH_Completion_Dont_Wait,
SH_Next_Action_Brake);
}else if(turnDelta > 0){
pnxshield->bank_a.motorRunDegrees(SH_Motor_2,
SH_Direction_Forward,
turnSpeed,
turnDelta,
SH_Completion_Dont_Wait,
SH_Next_Action_Brake);
}
}
void Pilot::centerSteer(){
if(steerAngle < 0){
pnxshield->bank_a.motorRunDegrees(SH_Motor_2,
SH_Direction_Forward,
currentSpeed/2,
steerAngle,
SH_Completion_Dont_Wait,
SH_Next_Action_Brake);
}else if(steerAngle >0){
pnxshield->bank_a.motorRunDegrees(SH_Motor_2,
SH_Direction_Reverse,
currentSpeed/2,
steerAngle,
SH_Completion_Dont_Wait,
SH_Next_Action_Brake);
}
steerAngle = 0;
}
void Pilot::setMaxSpeed(int ms){
maxSpeed = ms;
}
int Pilot::getMaxSpeed(){
return maxSpeed;
}
void Pilot::resetMotors()
{
pnxshield->bank_a.motorReset();
}
| true |
44fda3078fb76538c4a7b37d9b5cb5f25223fbcd | C++ | nkhoit/McHAB-1 | /Arduino/Bitstream.cpp | UTF-8 | 697 | 2.765625 | 3 | [] | no_license | #include "Bitstream.h"
void sendToSerial(unsigned short value)
{
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value);
}
void sendToSerial(short value)
{
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value);
}
void sendToSerial(unsigned long value)
{
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value);
}
void sendToSerial(long value)
{
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value & 0xff);
value = value >> 8;
Serial.write(value);
}
| true |
39873327a5500604c6dd8b12a9da2b4a05c1ef37 | C++ | Thordreck/design-patterns-cpp | /proxy_virtual/src/main.cpp | UTF-8 | 853 | 3.53125 | 4 | [
"MIT"
] | permissive | #include <string>
#include <sstream>
#include <iostream>
#include <memory>
struct Image
{
virtual void draw() = 0;
};
struct Bitmap : public Image
{
Bitmap(const std::string& filename)
{
std::cout << "Loading bitmap from " << filename << std::endl;
}
void draw() override
{
std::cout << "Drawing bitmap" << std::endl;
}
};
struct LazyBitmap : public Image
{
LazyBitmap(const std::string filename)
: filename(filename)
{}
void draw() override
{
if(!bitmap)
{
bitmap = std::make_unique<Bitmap>(filename);
}
bitmap->draw();
}
private:
std::string filename;
std::unique_ptr<Bitmap> bitmap;
};
int main()
{
//Bitmap bmp { "pokemon.png" };
LazyBitmap bmp { "pokemon.png" };
bmp.draw();
return 0;
}
| true |
7688408d0190699875defeb8256e6337a97b7f6a | C++ | luigidcsoares/L-programming-language | /src/lexer/dfa.cpp | UTF-8 | 12,718 | 3.09375 | 3 | [] | no_license | /**
* @author: Gabriel Luciano
* @author: Geovane Fonseca
* @author: Luigi Domenico
*/
#include <algorithm>
#include <iostream>
#include <regex>
#include <sstream>
#include "core/global.hpp"
#include "core/type.hpp"
#include "core/token.hpp"
#include "lexer/dfa.hpp"
#include "lexer/lexer.hpp"
#include "utils/regex.hpp"
using namespace core;
namespace lexer {
/**
* Implementations of all language machine states
*/
int state0(char c, std::stringstream &lexeme) {
int next_state = 0;
// Skipping whitespace.
if (utils::is_whitespace(c)) return next_state;
// Concatenate char to the lexeme.
lexeme << c;
// Identifier and reserved words.
if (utils::is_letter(c)) next_state = 1;
else if (c == '_' || c == '.') next_state = 2;
// Comment or division.
else if (c == '/') next_state = 3;
// Greater (than or equal).
else if (c == '>') next_state = 6;
// Less (than or equal) or not equal.
else if (c == '<') next_state = 7;
// Const.
else if (c == '"') next_state = 14;
else if (c == '\'') next_state = 9;
else if (utils::is_digit_not_zero(c)) next_state = 8;
else if (c == '0') next_state = 11;
// Unit symbols are symbols made by only one char and have
// a direct transition from initial state (0) to final
// state (15).
else if (utils::is_unit_symbol(c)) {
// We guarantee that these symbols are in the table since
// they have to be inserted in the beginning of the program.
// Thus, no need to check for null case.
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(p->token, lexeme.str(), p);
next_state = 15;
}
// If the character read was EOF we can safely assume
// that our compilation process ended correctly. We're setting
// the global lexical register token field as EOFL for handling
// the end of parser and thus the end of program. There's no
// need to save EOF in table of symbols so we're setting addr
// field as NULL.
else if (c == EOF) {
g_lex_reg.fill(Token::EOFL, "eof", NULL);
next_state = 15;
}
// Lexeme unidentified.
else {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
return next_state;
}
int state1(char c, std::stringstream &lexeme) {
int next_state = 1;
if (utils::is_letter(c) || utils::is_digit(c) ||
c == '_' || c == '.') {
lexeme << c;
} else {
// L is case insensitive.
std::string lower_lex = lexeme.str();
std::transform(
lower_lex.begin(), lower_lex.end(),
lower_lex.begin(), ::tolower
);
// Search for the lexeme.
TSymbolElem *p = g_tab_symbol.search(lower_lex);
Token tok;
// If the search returns null this is a new identifier
// and thus must be inserted in the table.
if (p == NULL) {
tok = Token::Id;
TSymbolElem elem(lexeme.str(), tok);
p = g_tab_symbol.insert(lower_lex, elem);
}
// Else we just need to get that token to pass to
// the lexical register.
else tok = p->token;
g_lex_reg.fill(tok, lower_lex, p);
// Put character back to be read again and go to the
// final state.
g_source.file.putback(c);
next_state = 15;
}
return next_state;
}
int state2(char c, std::stringstream &lexeme) {
int next_state = 2;
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Since we didn't reach EOF, we can go on.
else if (utils::is_letter(c) || utils::is_digit(c))
next_state = 1;
else if (c != '.' && c != '_') {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
return next_state;
}
int state3(char c, std::stringstream &lexeme) {
int next_state;
if (c == '*') {
lexeme.str("");
next_state = 4;
} else {
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(p->token, lexeme.str(), p);
// Put character back to be read again.
g_source.file.putback(c);
next_state = 15;
}
return next_state;
}
int state4(char c, std::stringstream &lexeme) {
int next_state = 4;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
else if (c == '*') next_state = 5;
return next_state;
}
int state5(char c, std::stringstream &lexeme) {
int next_state = 5;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
else if (c == '/') next_state = 0;
else if (c != '*') next_state = 4;
return next_state;
}
int state6(char c, std::stringstream &lexeme) {
// Token: >=
if (c == '=') lexeme << c;
// Token: >
// Put character back to be read again.
else g_source.file.putback(c);
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(p->token, lexeme.str(), p);
return 15;
}
int state7(char c, std::stringstream &lexeme) {
// Token: <= or <>
if (c == '>' || c == '=') lexeme << c;
// Token: <
// Put character back to be read again.
else g_source.file.putback(c);
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(p->token, lexeme.str(), p);
return 15;
}
int state8(char c, std::stringstream &lexeme) {
int next_state = 8;
if (utils::is_digit(c)) lexeme << c;
else {
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(Token::Const, lexeme.str(),
Type::Integer, 0);
// Put character back to be read again.
g_source.file.putback(c);
next_state = 15;
}
return next_state;
}
int state9(char c, std::stringstream &lexeme) {
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Since this state represents a alphanum char, we know
// that every valid char will be accepted, so no need
// for checking this.
return 10;
}
int state10(char c, std::stringstream &lexeme) {
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Handling unidentified lexeme.
else if (c != '\'') {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(Token::Const, lexeme.str(), Type::Char, 0);
return 15;
}
int state11(char c, std::stringstream &lexeme) {
int next_state;
if (utils::is_digit(c)) {
lexeme << c;
next_state = 8;
} else if (c == 'X' || c == 'x') {
lexeme << c;
next_state = 12;
} else {
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(Token::Const, lexeme.str(),
Type::Integer, 0);
// Put character back to be read again.
g_source.file.putback(c);
next_state = 15;
}
return next_state;
}
int state12(char c, std::stringstream &lexeme) {
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Handling unidentified lexeme.
else if (!utils::is_hexa(c)) {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
return 13;
}
int state13(char c, std::stringstream &lexeme) {
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Handling unidentified lexeme.
else if (!utils::is_hexa(c)) {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(Token::Const, lexeme.str(), Type::Char, 0);
return 15;
}
int state14(char c, std::stringstream &lexeme) {
int next_state = 14;
lexeme << c;
// Handling unexpected EOF.
if (c == EOF) {
std::stringstream err;
err << g_source.curr_line << ":fim de arquivo nao esperado.";
throw std::runtime_error(err.str());
}
// Handling unidentified lexeme.
else if (c == '$' || c == '\r' || c == '\n') {
std::stringstream err;
err << g_source.curr_line << ":lexema nao identificado ["
<< lexeme.str() << "].";
// Showing newline properly.
std::string s = err.str();
s = std::regex_replace(s, std::regex("\r"), "\\r");
s = std::regex_replace(s, std::regex("\n"), "\\n");
throw std::runtime_error(s);
}
// If we read a second quote, it is a valid string.
else if (c == '"') {
TSymbolElem *p = g_tab_symbol.search(lexeme.str());
g_lex_reg.fill(Token::Const, lexeme.str(),
Type::String, lexeme.str().length() - 2);
next_state = 15;
}
return next_state;
}
}
| true |
1fe659b1ff8615517e5e261ebd89208ec70ffcbd | C++ | reaper-oss/sws | /Fingers/RprNode.h | UTF-8 | 1,901 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #ifndef RPRNODE_HXX
#define RPRNODE_HXX
class RprNode {
public:
virtual ~RprNode() {}
RprNode *getParent();
void setParent(RprNode *parent);
std::string toReaper();
virtual void toReaper(std::ostringstream &oss, int indent) = 0;
virtual int childCount() const = 0;
virtual RprNode *getChild(int index) const = 0;
virtual RprNode *findChildByToken(const std::string &) const = 0;
virtual void addChild(RprNode *node) = 0;
virtual void addChild(RprNode *node, int index) {}
virtual void removeChild(int index) = 0;
void setValue(const std::string &value);
const std::string &getValue() const;
private:
std::string mValue;
RprNode *mParent;
};
class RprPropertyNode : public RprNode {
public:
RprPropertyNode(const std::string &value);
~RprPropertyNode() {}
int childCount() const override { return 0; }
RprNode *getChild(int index) const override { return nullptr; }
RprNode *findChildByToken(const std::string &) const override { return nullptr; }
void addChild(RprNode *node) override {}
void removeChild(int index) override {}
private:
void toReaper(std::ostringstream &oss, int indent) override;
};
class RprParentNode : public RprNode {
public:
static RprNode *createItemStateTree(const char *itemState);
RprParentNode(const char *value);
RprParentNode(const RprNode&) = delete;
~RprParentNode();
int childCount() const override;
RprNode *getChild(int index) const override;
RprNode *findChildByToken(const std::string &) const override;
void addChild(RprNode *node) override;
void addChild(RprNode *node, int index) override;
void removeChild(int index) override;
private:
RprParentNode& operator=(const RprNode&);
void toReaper(std::ostringstream &oss, int indent) override;
std::vector<RprNode *> mChildren;
};
#endif /* RPRNODE_HXX */
| true |
e3c47c3f6606d5f2b7226283bf35ebd2400de91e | C++ | CreepSore/HACKMAN-3 | /src/kfw/Hacks.cpp | UTF-8 | 1,649 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "k-framework.h"
kfw::core::IBaseHack::IBaseHack(std::string identifier, std::string hrIdentifier)
{
this->identifier = std::move(identifier);
this->hrIdentifier = std::move(hrIdentifier);
this->manager = nullptr; // Gets set during registration inside the HackManager
}
kfw::core::HackManager::HackManager() {
hacks = new std::vector<IBaseHack*>();
}
kfw::core::HackManager::~HackManager() {
delete hacks;
}
void kfw::core::HackManager::registerHack(IBaseHack* hack) const {
if (doesIdentifierExist(hack->identifier))
{
return;
}
hacks->push_back(hack);
hack->onRegister();
}
void kfw::core::HackManager::unregisterHack(const std::string& identifier) const {
auto ir = hacks->begin();
while (ir != hacks->end())
{
IBaseHack* hack = *ir;
if (hack->identifier != identifier) {
++ir;
continue;
}
hack->onUnregister();
hacks->erase(ir);
delete hack;
return;
}
}
kfw::core::IBaseHack* kfw::core::HackManager::getHackByIdentifier(const std::string& identifier) const {
for (auto hack : *hacks)
{
if (hack->identifier == identifier) return hack;
}
return nullptr;
}
bool kfw::core::HackManager::doesIdentifierExist(const std::string& identifier) const {
return getHackByIdentifier(identifier) != nullptr;
}
bool kfw::core::HackManager::onEvent(std::string event, void* args) const {
bool result = false;
for (IBaseHack* hack : *hacks)
{
if (hack->onEvent(event, args))
{
result = true;
}
}
return result;
}
| true |
02365b87282526b3ea46449ada88721ea7437574 | C++ | BMajs996/Problem-Solving-in-Data-Structures-and-Algorithms-using-Cpp | /Heap/HeapEx.cpp | UTF-8 | 11,290 | 3.828125 | 4 | [] | no_license |
#include <string>
#include <vector>
#include <iostream>
#include <limits>
#include <queue>
#include <functional> // for greater<int>
#include <exception>
#include <algorithm>
#include <cmath>
int main1() {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
int arr[] = { 1, 2, 10, 8, 7, 3, 4, 6, 5, 9 };
int value;
for (int i : arr) {
pq.push(i);
}
std::cout << "\n Dequeue elements of Priority Queue ::";
while (pq.empty() == false) {
value = pq.top();
pq.pop();
std::cout << " " << value;
}
return 0;
}
int KthSmallest(int arr[], int size, int k) {
std::sort(arr, arr+size);
return arr[k - 1];
}
int KthSmallest2(int arr[], int size, int k) {
int i = 0;
int value = 0;
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
for (i = 0; i < size; i++) {
pq.push(arr[i]);
}
i = 0;
while (i < size && i < k) {
value = pq.top();
pq.pop();
i += 1;
}
return value;
}
bool isMinHeap(int arr[], int size) {
int lchild, rchild;
// last element index size - 1
for (int parent = 0; parent < (size / 2 + 1); parent++) {
lchild = parent * 2 + 1;
rchild = parent * 2 + 2;
// heap property check.
if (((lchild < size) && (arr[parent] > arr[lchild])) || ((rchild < size) && (arr[parent] > arr[rchild])))
return false;
}
return true;
}
bool isMaxHeap(int arr[], int size) {
int lchild, rchild;
// last element index size - 1
for (int parent = 0; parent < (size / 2 + 1); parent++) {
lchild = parent * 2 + 1;
rchild = lchild + 1;
// heap property check.
if (((lchild < size) && (arr[parent] < arr[lchild])) || ((rchild < size) && (arr[parent] < arr[rchild])))
return false;
}
return true;
}
int main2() {
int arr[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "Kth Smallest :: " << KthSmallest(arr, 8, 3) << std::endl;
int arr2[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "Kth Smallest :: " << KthSmallest2(arr2, 8, 3) << std::endl;
int arr3[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "isMaxHeap :: " << isMaxHeap(arr3, 8) << std::endl;
int arr4[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "isMinHeap :: " << isMinHeap(arr4, 8) << std::endl;
std::sort(arr4, arr4 + sizeof(arr4)/sizeof(int));
std::cout << "isMinHeap :: " << isMinHeap(arr4, 8) << std::endl;
return 0;
}
int KSmallestProduct(int arr[], int size, int k) {
std::sort(arr, arr+size);// , size, 1);
int product = 1;
for (int i = 0; i < k; i++)
product *= arr[i];
return product;
}
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void QuickSelectUtil(int arr[], int lower, int upper, int k) {
if (upper <= lower)
return;
int pivot = arr[lower];
int start = lower;
int stop = upper;
while (lower < upper) {
while (lower < upper && arr[lower] <= pivot) {
lower++;
}
while (lower <= upper && arr[upper] > pivot) {
upper--;
}
if (lower < upper) {
swap(arr, upper, lower);
}
}
swap(arr, upper, start); // upper is the pivot position
if (k < upper)
QuickSelectUtil(arr, start, upper - 1, k); // pivot -1 is the upper for left sub array.
if (k > upper)
QuickSelectUtil(arr, upper + 1, stop, k); // pivot + 1 is the lower for right sub array.
}
int KSmallestProduct3(int arr[], int size, int k) {
QuickSelectUtil(arr, 0, size - 1, k);
int product = 1;
for (int i = 0; i < k; i++)
product *= arr[i];
return product;
}
int KSmallestProduct2(int arr[], int size, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
int i = 0;
int product = 1;
for (i = 0; i < size; i++) {
pq.push(arr[i]);
}
i = 0;
while (i < size && i < k) {
product *= pq.top();
pq.pop();
i += 1;
}
return product;
}
int main3() {
int arr[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "Kth Smallest product:: " << KSmallestProduct(arr, 8, 3) << std::endl;
int arr2[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "Kth Smallest product:: " << KSmallestProduct2(arr2, 8, 3) << std::endl;
int arr3[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
std::cout << "Kth Smallest product:: " << KSmallestProduct3(arr3, 8, 3) << std::endl;
}
void PrintLargerHalf(int arr[], int size) {
std::sort(arr, arr+size);// , size, 1);
for (int i = size / 2; i < size; i++)
std::cout << (arr[i]);
std::cout << std::endl;
}
void PrintLargerHalf2(int arr[], int size) {
int product = 1;
int value;
std::priority_queue<int, std::vector<int>, std::less<int>> pq;;
for (int i = 0; i < size; i++) {
pq.push(arr[i]);
}
int half = size/2;
for (int i = 0; i < half; i++){
value = pq.top();
pq.pop();
std::cout << value;
}
std::cout << std::endl;
}
void PrintLargerHalf3(int arr[], int size) {
QuickSelectUtil(arr, 0, size - 1, size / 2);
for (int i = size / 2; i < size; i++)
std::cout << arr[i];
std::cout << std::endl;
}
int main4() {
int arr[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
PrintLargerHalf(arr, 8);
int arr2[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
PrintLargerHalf2(arr2, 8);
int arr3[] = { 8, 7, 6, 5, 7, 5, 2, 1 };
PrintLargerHalf3(arr3, 8);
return 0;
}
void sortK(int arr[], int size, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
int i = 0;
for (i = 0; i < size; i++) {
pq.push(arr[i]);
}
int* output = new int[size];
int index = 0;
for (i = k; i < size; i++) {
output[index++] = pq.top();
pq.pop();
pq.push(arr[i]);
}
while (pq.size() > 0)
output[index++] = pq.top();
pq.pop();
for (i = k; i < size; i++) {
arr[i] = output[i];
}
std::cout << output << std::endl;
}
// Testing Code
int main5() {
int k = 3;
int arr[] = { 1, 5, 4, 10, 50, 9 };
int size = sizeof(arr)/sizeof(int);
sortK(arr, size, k);
return 0;
}
int ChotaBhim(int cups[], int size) {
int time = 60;
std::sort(cups, cups+size);
int total = 0;
int index, temp;
while (time > 0) {
total += cups[0];
cups[0] = ceil(cups[0] / 2.0);
index = 0;
temp = cups[0];
while (index < size - 1 && temp < cups[index + 1]) {
cups[index] = cups[index + 1];
index += 1;
}
cups[index] = temp;
time -= 1;
}
std::cout << "Total : " << total << std::endl;
return total;
}
int ChotaBhim2(int cups[], int size) {
int time = 60;
std::sort(cups, cups + size);
int total = 0;
int i, temp;
while (time > 0) {
total += cups[0];
cups[0] = ceil(cups[0] / 2.0);
i = 0;
// Insert into proper location.
while (i < size - 1) {
if (cups[i] > cups[i + 1])
break;
temp = cups[i];
cups[i] = cups[i + 1];
cups[i + 1] = temp;
i += 1;
}
time -= 1;
}
std::cout << "Total : " << total << std::endl;
return total;
}
int ChotaBhim3(int cups[], int size) {
int time = 60;
std::priority_queue<int, std::vector<int>, std::less<int>> pq;;
int i = 0;
for (i = 0; i < size; i++) {
pq.push(cups[i]);
}
int total = 0;
int value;
while (time > 0) {
value = pq.top();
pq.pop();
total += value;
value = std::ceil(value / 2.0);
pq.push(value);
time -= 1;
}
std::cout << "Total : " << total << std::endl;
return total;
}
int JoinRopes(int ropes[], int size) {
std::sort(ropes, ropes+size, std::greater<>());
int total = 0;
int value = 0;
int temp, index;
int length = size;
while (length >= 2) {
value = ropes[length - 1] + ropes[length - 2];
total += value;
index = length - 2;
while (index > 0 && ropes[index - 1] < value) {
ropes[index] = ropes[index - 1];
index -= 1;
}
ropes[index] = value;
length--;
}
std::cout << "Total : " << total << std::endl;
return total;
}
int JoinRopes2(int ropes[], int size) {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
int i = 0;
for (i = 0; i < size; i++) {
pq.push(ropes[i]);
}
int total = 0;
int value = 0;
while (pq.size() > 1) {
value = pq.top();
pq.pop();
value += pq.top();
pq.pop();
pq.push(value);
total += value;
}
std::cout << "Total : " << total << std::endl;
return total;
}
int main6() {
int cups[] = { 2, 1, 7, 4, 2 };
ChotaBhim(cups, 5);
int cups2[] = { 2, 1, 7, 4, 2 };
ChotaBhim2(cups2, 5);
int cups3[] = { 2, 1, 7, 4, 2 };
ChotaBhim3(cups3, 5);
int ropes[] = { 2, 1, 7, 4, 2 };
JoinRopes(ropes, 5);
int rope2[] = { 2, 1, 7, 4, 2 };
JoinRopes2(rope2, 5);
return 0;
}
/*
* int kthAbsDiff(int arr[], int size, int k) { Sort(arr, size,1);
* int diff[1000]; int index = 0; for (int i = 0; i < size - 1; i++) { for (int
* j = i + 1; j < size; j++) diff[index++] = abs(arr[i] - arr[j]); } Sort(diff,
* index); return diff[k - 1]; }
*
* int kthAbsDiff(int arr[], int size, int k) { Sort(arr, size, 1); Heap hp; int
* value = 0;
*
* for (int i = k + 1; i < size - 1; i++) HeapAdd(&hp,(abs(arr[i] - arr[i + 1]),
* i, i + 1)); heapify(hp);
*
* for (int i = 0; i < k; i++) { tp = heapq.heappop(hp); value = tp[0]; src =
* tp[1]; dst = tp[2]; if (dst + 1 < size) heapq.heappush(hp, (abs(arr[src] -
* arr[dst + 1]), src, dst + 1)); } return value; }
*
* int main7() { int arr[] = { 1, 2, 3, 4 };
* std::cout << "", kthAbsDiff(arr, 4, 5)); return 0; }
*/
int kthLargestStream(int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;;
int size = 0;
int data = 0;
while (true) {
std::cout << "Enter data: ";
// data = System.in.read();
if (size < k - 1)
pq.push(data);
else {
if (size == k - 1)
pq.push(data);
else if (pq.top() < data) {
pq.push(data);
pq.pop();
}
std::cout << "Kth larges element is :: " << pq.top() << std::endl;
}
size += 1;
}
}
int main8() {
kthLargestStream(3);
return 0;
}
/*
* int minJumps(int arr[], int size) { int *jumps = (int
* *)malloc(sizeof(int) * size); //all jumps to maxint. int steps, j; jumps[0] =
* 0;
*
* for (int i = 0; i < size; i++) { steps = arr[i]; // error checks can be added
* hear. j = i + 1; while (j <= i + steps && j < size) { jumps[j] =
* min(jumps[j], jumps[i] + 1); j += 1; } std::cout << "%s", jumps); }
* return jumps[size - 1]; } int main2() { int arr[]
* = {1, 4, 3, 7, 6, 1, 0, 3, 5, 1, 10}; std::cout << "%d", minJumps(arr,
* sizeof(arr) / sizeof(int))); return 0; }
*/ | true |
ffd4f16606bfc46d7c20ba583cf54a5409a37fce | C++ | adityasbg/ds-and-algo- | /number_theory/gcd_n_no.cpp | UTF-8 | 340 | 2.90625 | 3 | [] | no_license |
#include<iostream>
#define ll int
using namespace std;
ll gcd (ll a , ll b ){
if(b==0){
return a;
}
else
return gcd(b,a%b);
}
int main(){
int n;
int a[50];
cin>>n;
for(int i =0 ;i<n ;i++){
cin>>a[i];
}
int result =a[0];
for(int i =1 ; i<n ;i++)
{
result= gcd(result ,a[i]);
}
cout<< result;
}
| true |
79d0b6b2b7f57c66bc71275618287597684dd5c7 | C++ | countryhu/algorithm | /now_coder/cracking_the_code_interview/9_recursion/5_getPermutation.cc | UTF-8 | 2,238 | 3.859375 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
/**
题目描述
编写一个方法,确定某字符串的所有排列组合。
给定一个string A和一个int n,代表字符串和其长度,
请返回所有该字符串字符的排列,保证字符串长度小于等于11且字符串中字符均为大写英文字符,
排列中的字符串按字典序从大到小排序。(不合并重复字符串)
测试样例:
"ABC"
返回:
["CBA","CAB","BCA","BAC","ACB","ABC"]
-------
题目分析
**/
class Permutation {
public:
vector<std::string> getPermutation(string A) {
vector<std::string> permutations;
myGetPermutation(A, &permutations);
std::sort(permutations.begin(), permutations.end(), [](const std::string& lhs, const std::string& rhs) {
return lhs > rhs;
});
return permutations;
}
private:
void myGetPermutation(const std::string& A, vector<std::string>* permutations) {
permutations->clear();
if (A.empty()) {
permutations->push_back(A);
return;
}
vector<string> littlePermutations;
myGetPermutation(A.substr(0, A.size() - 1), &littlePermutations);
for (size_t i = 0; i < littlePermutations.size(); ++i) {
auto& permutation = littlePermutations[i];
for (size_t j = 0; j <= permutation.size(); ++j) {
std::string newPermutation;
newPermutation.append(permutation.substr(0, j));
newPermutation.push_back(A[A.size() - 1]);
newPermutation.append(permutation.substr(j, permutation.size() - j));
permutations->push_back(newPermutation);
}
}
}
};
int main() {
// 样例
{
Permutation obj;
vector<std::string> ret = obj.getPermutation("ABC");
for (auto& val : ret) {
std::cout << val << " ";
}
std::cout << std::endl;
}
{
Permutation obj;
vector<std::string> ret = obj.getPermutation("");
for (auto& val : ret) {
std::cout << val << " ";
}
std::cout << std::endl;
}
{
Permutation obj;
vector<std::string> ret = obj.getPermutation("A");
for (auto& val : ret) {
std::cout << val << " ";
}
std::cout << std::endl;
}
return 0;
}
| true |
e0d8adbaddb361d1c43f761d8767eb96151f6e5f | C++ | dream-overflow/o3d | /include/o3d/gui/widgetdrawsimple.h | UTF-8 | 1,599 | 2.8125 | 3 | [] | no_license | /**
* @file widgetdrawsimple.h
* @brief Simple Drawing Mode for Widgets.
* @author RinceWind
* @date 2006-10-11
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#ifndef _O3D_WIDGETDRAWSIMPLE_H
#define _O3D_WIDGETDRAWSIMPLE_H
#include "widgetdrawmode.h"
namespace o3d {
//---------------------------------------------------------------------------------------
//! @class WidgetDrawSimple
//-------------------------------------------------------------------------------------
//! Simple Drawing Mode for Widgets.
//---------------------------------------------------------------------------------------
class O3D_API WidgetDrawSimple : public WidgetDrawMode
{
public:
//! default constructor
WidgetDrawSimple(Context *context, BaseObject *pParent);
//! copy constructor
WidgetDrawSimple(WidgetDrawSimple &dup);
//! destructor
virtual ~WidgetDrawSimple();
//! Get the type of the widget mode
virtual DrawModeType getType() const { return SIMPLE_MODE; }
//! Set the data set
inline void setData(Int32 x, Int32 y, Int32 width, Int32 height)
{
m_WidgetSet.x = x;
m_WidgetSet.y = y;
m_WidgetSet.width = width;
m_WidgetSet.height = height;
}
//! Get the data set
inline const WidgetDataSet& getData() const { return m_WidgetSet; }
//! Get base width/height
Int32 getWidgetWidth() const;
Int32 getWidgetHeight() const;
//! draw directly into the current buffer
void draw(Int32 x, Int32 y, Int32 width, Int32 height);
protected:
WidgetDataSet m_WidgetSet;
};
} // namespace o3d
#endif // _O3D_WIDGETDRAWSIMPLE_H
| true |
a7715cc05788664f75c9ab2fa628590ba6775dcf | C++ | peti/librfc2822 | /test/date.cpp | UTF-8 | 4,541 | 2.578125 | 3 | [] | no_license | /*
* Copyright (c) 2006-2008 Peter Simons <simons@cryp.to>
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held liable
* for any damages arising from the use of this software.
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty
* provided the copyright notice and this notice are preserved.
*/
#include "rfc2822/date.hpp"
#include "rfc2822/skipper.hpp"
#include <algorithm>
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
using namespace std;
using namespace rfc2822;
inline char const * parse_date(time_t & result, char const * begin, char const * end)
{
BOOST_REQUIRE(begin <= end);
timestamp tstamp;
spirit::parse_info<> const r = parse(begin, end, date_p[spirit::assign_a(tstamp)], skipper_p);
if (r.hit)
{
result = mktime(&tstamp);
if (result != time_t(-1))
{
result += tstamp.tzoffset;
return r.stop;
}
}
return NULL;
}
inline char const * parse_date(time_t & result, char const * cstr)
{
return parse_date(result, cstr, cstr + strlen(cstr));
}
struct test_case
{
char const * input;
bool success;
char const * output;
};
test_case const tests[] =
{
{ "12 \r\n (te \\( (HEU12) st) (\r\n )\t JUN \t 82", true, "1982-06-12 00:00:00" },
{ "12 jUN 1982", true, "1982-06-12 00:00:00" },
{ "1 jAN 1970", true, "1970-01-01 00:00:00" },
{ "31 dec 1969 23:59:59", true, "1969-12-31 23:59:59" },
{ "31 dec 99999999999999999999999999999999999999999", false, "" },
{ "Thu, 4 Sep 1973 14:12:17", true, "1973-09-04 14:12:17" },
{ "Tho, 4 Sep 1973 14:12", false, "" },
{ "Thu, 31 Sep 1973 14:12", true, "1973-10-01 14:12:00" },
{ "Thu, 31 (\r)Sep 1973 14:12", false, "" },
{ "Thu, 1 Aug 2002 12:34:55 -1234", true, "2002-08-01 00:00:55" },
{ "17 Mar 2017 00:00:13 +1234", true, "2017-03-17 12:34:13" },
{ "17 Mar 2017 00:00:13 1234", false, "" },
{ "1 Jan 2000 00:00:00 Ut", true, "2000-01-01 00:00:00" },
{ "1 Jan 2000 00:00:00 GmT", true, "2000-01-01 00:00:00" },
{ "1 Jan 2000 00:00:00 est", true, "1999-12-31 19:00:00" },
{ "1 Jan 2000 00:00:00 edt", true, "1999-12-31 20:00:00" },
{ "1 Jan 2000 00:00:00 cst", true, "1999-12-31 18:00:00" },
{ "1 Jan 2000 00:00:00 pdt", true, "1999-12-31 17:00:00" },
{ "1 Jan 2000 00:00:00 Z", true, "2000-01-01 00:00:00" },
{ "1 Jan 2000 00:00:00 m", true, "1999-12-31 12:00:00" },
{ "1 Jan 2000 00:00:00 Y", true, "2000-01-01 12:00:00" }
};
static int offset_to_gmt;
struct runner
{
char buf[1024];
time_t tstamp;
struct tm* tmstamp;
void operator()(test_case const & test)
{
char const * const endp = parse_date(tstamp, test.input);
if (endp && *endp == '\0')
{
tstamp -= offset_to_gmt;
tmstamp = gmtime(&tstamp);
size_t len = strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tmstamp);
BOOST_REQUIRE(len > 0);
BOOST_REQUIRE(test.success);
BOOST_REQUIRE_EQUAL(string(buf), string(test.output));
}
else
{
BOOST_REQUIRE(!test.success);
}
}
};
BOOST_AUTO_TEST_CASE( test_rfc2822_date_parser )
{
// Init timezone.
{
time_t nowlocal = time(0);
struct tm* tmp = gmtime(&nowlocal);
time_t nowgmt = mktime(tmp);
offset_to_gmt = nowgmt - nowlocal;
}
// Run test cases.
for_each(tests, tests + (sizeof(tests) / sizeof(test_case)), runner());
// Format current time into a string and check whether the parser
// returns the same result.
time_t now = time(0);
tm* gmtnow = gmtime(&now);
time_t new_now;
char buf[1024];
BOOST_REQUIRE(strftime(buf, sizeof(buf), "%d %b %Y %T GMT", gmtnow) != 0);
BOOST_REQUIRE(parse_date(new_now, buf));
new_now -= offset_to_gmt;
BOOST_REQUIRE_EQUAL(now, new_now);
}
| true |
b1221fd034991c5de3391e88248073490d651f79 | C++ | blaze6950/Polymorphism | /Inheritance/Seller.h | UTF-8 | 381 | 2.890625 | 3 | [] | no_license | #pragma once
#include "Header.h"
class Seller : public Employee
{
public:
Seller();
Seller(string name, string surname, int age, string department);
~Seller()
{
#ifdef TEST
cout << "~Seller()" << endl;
#endif
}
void SetDepartment(string department);
string GetDepartment() const
{
return _department;
}
virtual void Print();
private:
string _department;
};
| true |
b0c93f42028c26d9a53725841de6e25cb5c5f9f1 | C++ | savvynavi/Intro-to-cpp | /operator overloading/operator overloading question 1/operator overloading question 1/position.cpp | UTF-8 | 2,544 | 3.578125 | 4 | [] | no_license | #include"position.h"
Position::Position(){
m_x = 5.0f;
m_y = 5.0f;
}
Position::Position(float x, float y){
m_x = x;
m_y = y;
}
Position::~Position(){
}
float Position::getX(){
return m_x;
}
float Position::getY(){
return m_y;
}
void Position::setX(float x){
m_x = x;
}
void Position::setY(float y){
m_y = y;
}
//overloading the '+' operator
Position Position::operator+(Position &other){
Position tmp;
tmp.setX(this -> getX() + other.getX());
tmp.setY(this -> getY() + other.getY());
return tmp;
}
//overloading the '-' operator
Position Position::operator-(Position &other){
Position tmp;
tmp.setX(this->getX() - other.getX());
tmp.setY(this->getY() - other.getY());
return tmp;
}
//overloading the += operator
Position Position::operator+=(Position &other){
this->setX(this -> getX() + other.getX());
this->setY(this->getY() + other.getY());
return *this;
}
//overloading -+ operator
Position Position::operator-=(Position &other){
this -> setX(this -> getX() - other.getX());
this -> setY(this -> getY() - other.getY());
return *this;
}
//overloading == operator
bool Position::operator==(Position &other){
return ((this -> getX() == other.getX()) && (this -> getY() == other.getY()));
}
//overload the / operator
Position Position::operator/(Position &other){
Position tmp;
tmp.setX(this->getX() / other.getX());
tmp.setY(this->getY() / other.getY());
return tmp;
}
//overload the * operator
Position Position::operator*(Position &other){
Position tmp;
tmp.setX(this->getX() * other.getX());
tmp.setY(this->getY() * other.getY());
return tmp;
}
//overloading the *= operator
Position Position::operator*=(Position &other){
this->setX(this->getX() * other.getX());
this->setY(this->getY() * other.getY());
return *this;
}
//overloading the /= operator
Position Position::operator/=(Position &other){
this->setX(this->getX() / other.getX());
this->setY(this->getY() / other.getY());
return *this;
}
//overloading the -- operator prefix
Position &Position::operator--(){
this->setX(this -> getX() - 1.0f);
this->setY(this->getY() - 1.0f);
return *this;
}
//overloading the ++ operator prefix
Position &Position::operator++(){
this->setX(this->getX() + 1.0f);
this->setY(this->getY() + 1.0f);
return *this;
}
//overloading the -- operator postfix
Position Position::operator--(int z){
Position tmp(*this);
this -> operator--();
return tmp;
}
//overloading the ++ operator postfix
Position Position::operator++(int z){
Position tmp(*this);
this -> operator++();
return tmp;
} | true |
e43dde818e3a407dd59f19fdc2c0aa88c4bf723f | C++ | kamyu104/LeetCode-Solutions | /C++/unique-substrings-with-equal-digit-frequency.cpp | UTF-8 | 748 | 2.71875 | 3 | [
"MIT"
] | permissive | // Time: O(n^2)
// Space: O(n^2)
// rolling hash
class Solution {
public:
int equalDigitFrequency(string s) {
static const int MOD = 1e9 + 7;
static const int D = 27;
unordered_set<int> lookup;
for (int i = 0; i < size(s); ++i) {
unordered_map<int, int> cnt;
int64_t h = 0;
int max_cnt = 0;
for (int j = i; j < size(s); ++j) {
const int d = s[j] - '0' + 1;
h = (h * D + d) % MOD;
++cnt[d];
max_cnt = max(max_cnt, cnt[d]);
if (size(cnt) * max_cnt == j - i + 1) {
lookup.emplace(h);
}
}
}
return size(lookup);
}
};
| true |
09d698794287a5e79e85bfbc016b7b57420b7bc0 | C++ | WolfireGames/overgrowth | /Projects/bullet3-2.89/examples/Experiments/ImplicitCloth/stan/vec3n.h | UTF-8 | 11,369 | 3.171875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"Zlib"
] | permissive | //
// Big Vector and Sparse Matrix Classes
//
// (c) S Melax 2006
//
// The focus is on 3D applications, so
// the big vector is an array of float3s
// and the matrix class uses 3x3 blocks.
//
// This file includes both:
// - basic non-optimized version
// - an expression optimized version
//
// Optimized Expressions
//
// We want to write sweet looking code such as V=As+Bt with big vectors.
// However, we dont want the extra overheads with allocating memory for temps and excessing copying.
// Instead of a full Template Metaprogramming approach, we explicitly write
// classes to specifically handle all the expressions we are likely to use.
// Most applicable lines of code will be of the same handful of basic forms,
// but with different parameters for the operands.
// In the future, if we ever need a longer expression with more operands,
// then we will just add whatever additional building blocks that are necessary - not a big deal.
// This approach is much simpler to develop, debug and optimize (restrict keyword, simd etc)
// than template metaprogramming is. We do not rely on the implementation
// of a particular compiler to be able to expand extensive nested inline codes.
// Additionally, we reliably get our optimizations even within a debug build.
// Therefore we believe that our Optimized Expressions
// are a good compromise that give us the best of both worlds.
// The code within those important algorithms, which use this library,
// can now remain clean and readable yet still execute quickly.
//
#ifndef SM_VEC3N_H
#define SM_VEC3N_H
#include "vecmath.h"
#include "array.h"
//#include <malloc.h>
//template <class T> void * vec4<T>::operator new[](size_t n){ return _mm_malloc(n,64); }
//template <class T> void vec4<T>::operator delete[](void *a) { _mm_free(a); }
struct HalfConstraint
{
float3 n;
int vi;
float s, t;
HalfConstraint(const float3 &_n, int _vi, float _t) : n(_n), vi(_vi), s(0), t(_t) {}
HalfConstraint() : vi(-1) {}
};
class float3Nx3N
{
public:
class Block
{
public:
float3x3 m;
int r, c;
float unused[16];
Block() {}
Block(short _r, short _c) : r(_r), c(_c) { m.x = m.y = m.z = float3(0, 0, 0); }
};
Array<Block> blocks; // the first n blocks use as the diagonal.
int n;
void Zero();
void InitDiagonal(float d);
void Identity() { InitDiagonal(1.0f); }
float3Nx3N() : n(0) {}
float3Nx3N(int _n) : n(_n)
{
for (int i = 0; i < n; i++) blocks.Add(Block((short)i, (short)i));
}
template <class E>
float3Nx3N &operator=(const E &expression)
{
expression.evalequals(*this);
return *this;
}
template <class E>
float3Nx3N &operator+=(const E &expression)
{
expression.evalpluseq(*this);
return *this;
}
template <class E>
float3Nx3N &operator-=(const E &expression)
{
expression.evalmnuseq(*this);
return *this;
}
};
class float3N : public Array<float3>
{
public:
float3N(int _count = 0)
{
SetSize(_count);
}
void Zero();
void Init(const float3 &v); // sets each subvector to v
template <class E>
float3N &operator=(const E &expression)
{
expression.evalequals(*this);
return *this;
}
template <class E>
float3N &operator+=(const E &expression)
{
expression.evalpluseq(*this);
return *this;
}
template <class E>
float3N &operator-=(const E &expression)
{
expression.evalmnuseq(*this);
return *this;
}
float3N &operator=(const float3N &V)
{
this->copy(V);
return *this;
}
};
int ConjGradient(float3N &X, float3Nx3N &A, float3N &B);
int ConjGradientFiltered(float3N &X, const float3Nx3N &A, const float3N &B, const float3Nx3N &S, Array<HalfConstraint> &H);
int ConjGradientFiltered(float3N &X, const float3Nx3N &A, const float3N &B, const float3Nx3N &S);
inline float3N &Mul(float3N &r, const float3Nx3N &m, const float3N &v)
{
int i;
for (i = 0; i < r.count; i++) r[i] = float3(0, 0, 0);
for (i = 0; i < m.blocks.count; i++)
{
r[m.blocks[i].r] += m.blocks[i].m * v[m.blocks[i].c];
}
return r;
}
inline float dot(const float3N &a, const float3N &b)
{
float d = 0;
for (int i = 0; i < a.count; i++)
{
d += dot(a[i], b[i]);
}
return d;
}
inline void float3Nx3N::Zero()
{
for (int i = 0; i < blocks.count; i++)
{
blocks[i].m = float3x3(0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
inline void float3Nx3N::InitDiagonal(float d)
{
for (int i = 0; i < blocks.count; i++)
{
blocks[i].m = (blocks[i].c == blocks[i].r) ? float3x3(d, 0, 0, 0, d, 0, 0, 0, d) : float3x3(0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
inline void float3N::Zero()
{
for (int i = 0; i < count; i++)
{
element[i] = float3(0, 0, 0);
}
}
inline void float3N::Init(const float3 &v)
{
for (int i = 0; i < count; i++)
{
element[i] = v;
}
}
#ifdef WE_LIKE_SLOW_CODE
// Unoptimized Slow Basic Version of big vector operators.
// Uses typical implmentation for operators +/-*=
// These operators cause lots of unnecessary construction, memory allocation, and copying.
inline float3N operator+(const float3N &a, const float3N &b)
{
float3N r(a.count);
for (int i = 0; i < a.count; i++) r[i] = a[i] + b[i];
return r;
}
inline float3N operator*(const float3N &a, const float &s)
{
float3N r(a.count);
for (int i = 0; i < a.count; i++) r[i] = a[i] * s;
return r;
}
inline float3N operator/(const float3N &a, const float &s)
{
float3N r(a.count);
return Mul(r, a, 1.0f / s);
}
inline float3N operator-(const float3N &a, const float3N &b)
{
float3N r(a.count);
for (int i = 0; i < a.count; i++) r[i] = a[i] - b[i];
return r;
}
inline float3N operator-(const float3N &a)
{
float3N r(a.count);
for (int i = 0; i < a.count; i++) r[i] = -a[i];
return r;
}
inline float3N operator*(const float3Nx3N &m, const float3N &v)
{
float3N r(v.count);
return Mul(r, m, v);
}
inline float3N &operator-=(float3N &A, const float3N &B)
{
assert(A.count == B.count);
for (int i = 0; i < A.count; i++) A[i] -= B[i];
return A;
}
inline float3N &operator+=(float3N &A, const float3N &B)
{
assert(A.count == B.count);
for (int i = 0; i < A.count; i++) A[i] += B[i];
return A;
}
#else
// Optimized Expressions
class exVneg
{
public:
const float3N &v;
exVneg(const float3N &_v) : v(_v) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] = -v[i];
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] += -v[i];
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] -= -v[i];
}
};
class exVaddV
{
public:
const float3N &a;
const float3N &b;
exVaddV(const float3N &_a, const float3N &_b) : a(_a), b(_b) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] = a[i] + b[i];
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] += a[i] + b[i];
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] -= a[i] + b[i];
}
};
class exVsubV
{
public:
const float3N &a;
const float3N &b;
exVsubV(const float3N &_a, const float3N &_b) : a(_a), b(_b) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] = a[i] - b[i];
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] += a[i] - b[i];
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] -= a[i] - b[i];
}
};
class exVs
{
public:
const float3N &v;
const float s;
exVs(const float3N &_v, const float &_s) : v(_v), s(_s) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] = v[i] * s;
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] += v[i] * s;
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < v.count; i++) r[i] -= v[i] * s;
}
};
class exAsaddB
{
public:
const float3N &a;
const float3N &b;
const float s;
exAsaddB(const float3N &_a, const float &_s, const float3N &_b) : a(_a), s(_s), b(_b) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] = a[i] * s + b[i];
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] += a[i] * s + b[i];
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] -= a[i] * s + b[i];
}
};
class exAsaddBt
{
public:
const float3N &a;
const float3N &b;
const float s;
const float t;
exAsaddBt(const float3N &_a, const float &_s, const float3N &_b, const float &_t) : a(_a), s(_s), b(_b), t(_t) {}
void evalequals(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] = a[i] * s + b[i] * t;
}
void evalpluseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] += a[i] * s + b[i] * t;
}
void evalmnuseq(float3N &r) const
{
for (int i = 0; i < a.count; i++) r[i] -= a[i] * s + b[i] * t;
}
};
class exMv
{
public:
const float3Nx3N &m;
const float3N &v;
exMv(const float3Nx3N &_m, const float3N &_v) : m(_m), v(_v) {}
void evalequals(float3N &r) const { Mul(r, m, v); }
};
class exMs
{
public:
const float3Nx3N &m;
const float s;
exMs(const float3Nx3N &_m, const float &_s) : m(_m), s(_s) {}
void evalequals(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m = m.blocks[i].m * s;
}
void evalpluseq(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m += m.blocks[i].m * s;
}
void evalmnuseq(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m -= m.blocks[i].m * s;
}
};
class exMAsMBt
{
public:
const float3Nx3N &a;
const float s;
const float3Nx3N &b;
const float t;
exMAsMBt(const float3Nx3N &_a, const float &_s, const float3Nx3N &_b, const float &_t) : a(_a), s(_s), b(_b), t(_t) {}
void evalequals(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m = a.blocks[i].m * s + b.blocks[i].m * t;
}
void evalpluseq(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m += a.blocks[i].m * s + b.blocks[i].m * t;
}
void evalmnuseq(float3Nx3N &r) const
{
for (int i = 0; i < r.blocks.count; i++) r.blocks[i].m -= a.blocks[i].m * s + b.blocks[i].m * t;
}
};
inline exVaddV operator+(const float3N &a, const float3N &b) { return exVaddV(a, b); }
inline exVsubV operator+(const exVneg &E, const float3N &b) { return exVsubV(b, E.v); }
inline exVsubV operator-(const float3N &a, const float3N &b) { return exVsubV(a, b); }
inline exVs operator*(const float3N &V, const float &s) { return exVs(V, s); }
inline exVs operator*(const exVs &E, const float &s) { return exVs(E.v, E.s * s); }
inline exAsaddB operator+(const exVs &E, const float3N &b) { return exAsaddB(E.v, E.s, b); }
inline exAsaddB operator+(const float3N &b, const exVs &E) { return exAsaddB(E.v, E.s, b); }
inline exAsaddB operator-(const float3N &b, const exVs &E) { return exAsaddB(E.v, -E.s, b); }
inline exAsaddBt operator+(const exVs &Ea, const exVs &Eb) { return exAsaddBt(Ea.v, Ea.s, Eb.v, Eb.s); }
inline exAsaddBt operator-(const exVs &Ea, const exVs &Eb) { return exAsaddBt(Ea.v, Ea.s, Eb.v, -Eb.s); }
inline exMv operator*(const float3Nx3N &m, const float3N &v) { return exMv(m, v); }
inline exMs operator*(const exMs &E, const float &s) { return exMs(E.m, E.s * s); }
inline exMs operator*(const float3Nx3N &m, const float &s) { return exMs(m, s); }
inline exMAsMBt operator+(const exMs &Ea, const exMs &Eb) { return exMAsMBt(Ea.m, Ea.s, Eb.m, Eb.s); }
inline exMAsMBt operator-(const exMs &Ea, const exMs &Eb) { return exMAsMBt(Ea.m, Ea.s, Eb.m, -Eb.s); }
#endif
#endif
| true |
7a041c3bab21df65d30d3350d51e352e402bd02b | C++ | hpaucar/OOP-C-plus-plus-repo | /Material/CPP_Primer_Plus_Book/Ch.14.2/Ch.14_2 - Exercise 05 - abstr_emp/Support.cpp | UTF-8 | 4,809 | 3.015625 | 3 | [
"MIT"
] | permissive | //*******************************
//
// C++ Template Program - Support Files
//
//*******************************
//*******************************
//
// Standard Header
//
//*******************************
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "header.h"
using namespace std;
//***************************************************************************************************
//
// Support Program Section
//
//***************************************************************************************************
/*****************************************************************************/
// class abstr_emp
// std::string fname; // abstr_emp's first name
// std::string lname; // abstr_emp's last name
// std::string job;
abstr_emp::abstr_emp()
{
fname = "N/A";
lname = "N/A";
job = "N/A";
}
abstr_emp::abstr_emp(const std::string & fn, const std::string & ln, const std::string & j) : fname(fn),lname(ln),job(j)
{
}
void abstr_emp::ShowAll() const // labels and shows all data
{
cout << endl;
cout << "First Name: " << fname << endl;
cout << "Last Name: " << lname << endl;
cout << "Job: " << job << endl;
}
void abstr_emp::SetAll() // prompts user for values
{
cout << "First Name? ";
getline(cin,fname);
cout << "Last Name? ";
getline(cin,lname);
cout << "Job Type? ";
getline(cin,job);
}
std::ostream & operator<<(std::ostream & os, const abstr_emp & e)
{
os << e.lname << ", " << e.fname << ", Job: " << e.job;
return os;
}
// just displays first and last name
abstr_emp::~abstr_emp() // virtual base class
{
}
/*****************************************************************************/
// class employee : public abstr_emp
employee::employee() : abstr_emp()
{
}
employee::employee(const std::string & fn, const std::string & ln,const std::string & j) : abstr_emp(fn,ln,j)
{
}
void employee::ShowAll() const
{
abstr_emp::ShowAll();
}
void employee::SetAll()
{
abstr_emp::SetAll();
}
/*****************************************************************************/
// class manager: virtual public abstr_emp
// Private:
// int inchargeof; // number of abstr_emps managed
// Protected:
// int InChargeOf() const { return inchargeof; } // output
// int & InChargeOf(){ return inchargeof; } // input
manager::manager() : abstr_emp()
{
}
manager::manager(const std::string & fn, const std::string & ln,const std::string & j, int ico) : abstr_emp(fn,ln,j), inchargeof(ico)
{
}
manager::manager(const abstr_emp & e, int ico) : abstr_emp(e), inchargeof(ico)
{
}
manager::manager(const manager & m) : abstr_emp(m), inchargeof(m.inchargeof)
{
}
void manager::ShowAll() const
{
abstr_emp::ShowAll();
cout << "ICO: " << inchargeof << endl;
}
void manager::SetAll()
{
abstr_emp::SetAll();
cout << "ICO? ";
cin >> inchargeof;
}
/*****************************************************************************/
// class fink: virtual public abstr_emp
// private:
// std::string reportsto; // to whom fink reports
// protected:
// const std::string ReportsTo() const { return reportsto; }
// std::string & ReportsTo(){ return reportsto; }
fink::fink() : abstr_emp()
{
}
fink::fink(const std::string & fn, const std::string & ln,const std::string & j, const std::string & rpo) : abstr_emp(fn,ln,j), reportsto(rpo)
{
}
fink::fink(const abstr_emp & e, const std::string & rpo) : abstr_emp(e), reportsto(rpo)
{
}
fink::fink(const fink & e) : abstr_emp(e), reportsto(e.reportsto)
{
}
void fink::ShowAll() const
{
abstr_emp::ShowAll();
cout << "RPO: " << reportsto << endl;
}
void fink::SetAll()
{
abstr_emp::SetAll();
cout << "RPO? ";
cin >> reportsto;
}
/*****************************************************************************/
// class highfink: public manager, public fink // management fink
highfink::highfink() : abstr_emp(), manager(), fink()
{
}
highfink::highfink(const std::string & fn, const std::string & ln,const std::string & j, const std::string & rpo,int ico) : abstr_emp(fn,ln,j), manager(fn,ln,j,ico), fink(fn,ln,j,rpo)
{
}
highfink::highfink(const abstr_emp & e, const std::string & rpo, int ico) : abstr_emp(e)
{
ReportsTo() = rpo;
InChargeOf() = ico;
}
highfink::highfink(const fink & f, int ico) : abstr_emp(f), fink(f)
{
InChargeOf() = ico;
}
highfink::highfink(const manager & m, const std::string & rpo) : abstr_emp(m), manager(m)
{
ReportsTo() = rpo;
}
highfink::highfink(const highfink & h) : abstr_emp(h), manager(h), fink(h)
{
}
void highfink::ShowAll() const
{
abstr_emp::ShowAll();
cout << "ICO: " << InChargeOf() << endl;
cout << "RPO: " << ReportsTo() << endl;
}
void highfink::SetAll()
{
abstr_emp::SetAll();
cout << "ICO? ";
cin >> InChargeOf();
cout << "RPO? ";
cin >> ReportsTo();
}
| true |
a688297b6e0545d49b04db99e37642d5213793b0 | C++ | saifullah3396/team-nust-robocup | /Src/TNRSModules/VisionModule/include/FeatureExtraction/RegionSegmentation.h | UTF-8 | 3,765 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file FeatureExtraction/RegionSegmentation.h
*
* This file declares the class for segmenting the image into different
* regions for further processing.
*
* @author <A href="mailto:saifullah3396@gmail.com">Saifullah</A>
* @author AbdulRehman
* @date 5 Mar 2018
*/
#pragma once
#include "VisionModule/include/FeatureExtraction/FeatureExtraction.h"
#include "VisionModule/include/ColorHandler.h"
/*class ScanHorizontal : public ParallelLoopBody
{
public:
ScanHorizontal(const Mat &img) : image(image)
{
}
virtual void operator ()(const Range& range) const
{
for (int r = range.start; r < range.end; r++)
{
int i = r / image.cols;
int j = r % image.cols;
image.ptr<uchar>(i)[j] = 128;
}
}
ScanHorizontal& operator=(const ScanHorizontal&) {
return *this;
};
private:
Mat ℑ
};*/
class FieldExtraction;
class BallExtraction;
class GoalExtraction;
/**
* @class RegionSegmentation
* @brief The class for extracting field from the input image.
*/
class RegionSegmentation : public FeatureExtraction, public DebugBase
{
INIT_DEBUG_BASE_(
//! Option to send total module time.
(int, sendTime, 0),
//! Option to draw regions on incoming image.
(int, drawRegions, 0),
)
public:
/**
* Constructor
*
* @param visionModule: pointer to parent VisionModule
*/
RegionSegmentation(VisionModule* visionModule);
/**
* Destructor
*/
~RegionSegmentation()
{
}
//! Derived from FeatureExtraction
void
processImage();
void
setFieldExtraction(const boost::shared_ptr<FieldExtraction>& fieldExt)
{
this->fieldExt = fieldExt;
}
void
setBallExtraction(const boost::shared_ptr<BallExtraction>& ballExt)
{
this->ballExt = ballExt;
}
void
setGoalExtraction(const boost::shared_ptr<GoalExtraction>& goalExt)
{
this->goalExt = goalExt;
}
vector<Point>&
getBorderPoints()
{
return borderPoints;
}
int&
getFieldAvgHeight()
{
return avgHeight;
}
int&
getFieldMinBestHeight()
{
return minBestHeight;
}
//vector<ScannedLinePtr>& getVerGoalLines() { return verGoalLines; }
//vector<ScannedLinePtr>& getVerBallLines() { return verBallLines; }
//vector<ScannedLinePtr>& getHorBallLines() { return horBallLines; }
vector<ScannedLinePtr>&
getVerRobotLines()
{
return verRobotLines;
}
vector<ScannedLinePtr>&
getHorRobotLines()
{
return horRobotLines;
}
vector<ScannedLinePtr>&
getVerJerseyLinesOurs()
{
return verJerseyLinesOurs;
}
vector<ScannedLinePtr>&
getHorJerseyLinesOurs()
{
return horJerseyLinesOurs;
}
vector<ScannedLinePtr>&
getVerJerseyLinesOpps()
{
return verJerseyLinesOpps;
}
vector<ScannedLinePtr>&
getHorJerseyLinesOpps()
{
return horJerseyLinesOpps;
}
private:
int scanStepLow;
int scanStepHigh;
int vScanLimitIdx;
int hScanLimitIdx;
duration<double> timeSpan;
vector<ScannedLinePtr> horRobotLines;
//vector<ScannedLinePtr> horBallLines;
vector<ScannedLinePtr> horJerseyLinesOurs;
vector<ScannedLinePtr> horJerseyLinesOpps;
//vector<ScannedLinePtr> verGoalLines;
vector<ScannedLinePtr> verRobotLines;
//vector<ScannedLinePtr> verBallLines;
vector<ScannedLinePtr> verJerseyLinesOurs;
vector<ScannedLinePtr> verJerseyLinesOpps;
vector<Point> borderPoints;
int avgHeight;
int minBestHeight;
//! Field Extraction module object
boost::shared_ptr<FieldExtraction> fieldExt;
//! Ball Extraction module object
boost::shared_ptr<BallExtraction> ballExt;
//! Goal Extraction module object
boost::shared_ptr<GoalExtraction> goalExt;
};
| true |
288cff321257bf2bbef2ab93284eafba848c202c | C++ | Abiggg/practice | /cpp/map/use.cpp | UTF-8 | 608 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, string> student;
student.insert(pair<string, string>("num0", "zhangsan"));
student.insert(map<string, string>::value_type("num1", "lisi"));
student.insert(pair<string, string>("num0", "testaa"));
student["num2"] = "test4";
student["num4"] = "test5";
map<string, string>::iterator it;
for(it = student.begin();it != student.end(); it++) {
cout<<it->first << "=>" << it->second <<endl;
}
cout<<"find num0"<<student.find("num0")<<endl;
cout<<"map size"<<student.size()<<endl;
cout<<"hello world"<<endl;
}
| true |
2f9f520833ae7187621c951c7157de90b551a0a1 | C++ | adarshyoga/TaskProf_RegionDiffSched | /tests/demo_code/tests/detect_primes_threads.cpp | UTF-8 | 1,642 | 3.3125 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <assert.h>
#define NUM_THREADS 4
size_t* primes[NUM_THREADS];
size_t num_primes[NUM_THREADS];
struct args {
int tid;
int lb;
int ub;
};
bool IsPrime(size_t num) {
if (num <= 1) return false; // zero and one are not prime
for (size_t i=2; i*i<=num; i++) {
if (num % i == 0) return false;
}
return true;
}
void* check_primes(void *args) {
struct args* arguments = (struct args*)args;
for (size_t i = arguments->lb; i < arguments->ub; i++) {
if (IsPrime(i)) {
primes[arguments->tid][num_primes[arguments->tid]] = i;
num_primes[arguments->tid]++;
}
}
}
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cout << "Format: ./detect_primes <range_begin> <range_end>" << std::endl;
return 0;
}
size_t range_begin = strtoul(argv[1], NULL, 0);
size_t range_end = strtoul(argv[2], NULL, 0);
assert(range_end > range_begin);
pthread_t threadpool[NUM_THREADS];
struct args arguments[NUM_THREADS];
for (unsigned int i = 0; i < NUM_THREADS; i++) {
primes[i] = new size_t[range_end-range_begin];
arguments[i].tid = i;
arguments[i].lb = ((range_end-range_begin)/NUM_THREADS)*i;
arguments[i].ub = ((range_end-range_begin)/NUM_THREADS)*(i+1);
pthread_create(&threadpool[i], NULL, check_primes, &arguments[i]);
}
for (unsigned int i = 0; i < NUM_THREADS; i++) {
pthread_join(threadpool[i], NULL);
}
std::ofstream report;
report.open("primes.txt");
for (unsigned int i = 0; i < NUM_THREADS; i++) {
for (size_t j = 0; j < num_primes[i]; j++)
report << primes[i][j] << " ";
}
}
| true |
1ae79ada0f7bb5a54d947086ebd4f544c4865a6a | C++ | shizhonghao/leetcode | /387.cpp | UTF-8 | 827 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int firstUniqChar(string s)
{
int result = s.length()+1;
char ch;
map<char,int> last;
map<char,int> cnt;
map<char,int> ::iterator it;
for(int i=0;i<s.length();i++)
{
last[s[i]] = i;
cnt[s[i]]++;
}
for(it=cnt.begin();it!=cnt.end();it++)
{
if(it->second==1)
{
if(last[it->first]<result)
{
result = last[it->first];
}
}
}
if(result == s.length()+1)
{
result = -1;
}
return result;
}
};
int main()
{
Solution s;
cout << s.firstUniqChar("loveleetcode") << endl;
return 0;
}
| true |
6b2e2b48f4d563bfcb64fdc29a0220f4734f1dd9 | C++ | djperrone/SpaceAdventures_2.0 | /SpaceAdventures_2.0/src/GameManagers/CollisionManager.cpp | UTF-8 | 3,107 | 2.703125 | 3 | [] | no_license |
#include "sapch.h"
#include "Math/Vector2d.h"
#include "CollisionManager.h"
#include "ObjectTemplates/Character.h"
#include "ObjectTemplates/GameObject.h"
#include "MyObjects/Asteroid.h"
CollisionManager::CollisionManager(std::list<std::shared_ptr<Character>>* objList, std::list<std::unique_ptr<Asteroid>>* asteroidList)
: m_ObjectList(objList), m_AsteroidList(asteroidList)
{
}
CollisionManager::CollisionManager()
: m_AsteroidList(nullptr), m_ObjectList(nullptr)
{
}
void CollisionManager::Tick()
{
//std::cout << "col man tick " <<(m_ObjectList->size())<<"\n";
for (auto it = std::begin(*m_ObjectList); it != std::end(*m_ObjectList); it++)
{
for (auto otherIt = std::begin(*m_ObjectList); otherIt != std::end(*m_ObjectList); otherIt++)
{
if (IsColliding(it->get(), otherIt->get()) && !IsOnSameTeam(it->get(), otherIt->get()))
{
HandleCollisionEvent(it->get(), otherIt->get());
std::cout << "collision!\n";
}
}
for (auto otherIt = std::begin(*m_AsteroidList); otherIt != std::end(*m_AsteroidList); otherIt++)
{
if (IsColliding(it->get(), otherIt->get()) && !IsOnSameTeam(it->get(), otherIt->get()))
{
HandleCollisionEvent(it->get(), otherIt->get());
std::cout << "collision!\n";
}
}
}
for (auto it = std::begin(*m_AsteroidList); it != std::end(*m_AsteroidList); it++)
{
//std::cout << "Asteroidsadasdasdasd\n";
for (auto otherIt = std::begin(*m_AsteroidList); otherIt != std::end(*m_AsteroidList); otherIt++)
{
if (IsColliding(it->get(), otherIt->get()) && !IsOnSameTeam(it->get(), otherIt->get()))
{
HandleCollisionEvent(it->get(), otherIt->get());
std::cout << "collision!\n";
}
}
for (auto otherIt = std::begin(*m_ObjectList); otherIt != std::end(*m_ObjectList); otherIt++)
{
if (IsColliding(it->get(), otherIt->get()) && !IsOnSameTeam(it->get(), otherIt->get()))
{
HandleCollisionEvent(it->get(), otherIt->get());
std::cout << "collision!\n";
}
}
}
/*for (int i = 0; i < m_ObjectList.size(); i++)
{
}*/
}
void CollisionManager::HandleCollisionEvent(Character* current, Character* other)
{
std::cout << "collission detected!\n";
current->Attack(other);
//other->Attack(current);
}
bool CollisionManager::IsOnSameTeam(Character* current, Character* other)
{
//std::cout << "current team: " << static_cast<std::size_t>(current->GetTeam()) << ", other team: " << static_cast<std::size_t>(other->GetTeam()) << std::endl;
return current->GetTeam() == other->GetTeam();
}
bool CollisionManager::IsColliding(Character* current, Character* other)
{
if (current->GetRightBound() >= other->GetLeftBound() &&
other->GetRightBound() >= current->GetLeftBound() &&
current->GetUpperBound() >= other->GetLowerBound() &&
other->GetUpperBound() >= current->GetLowerBound())
{
return true;
}
return false;
}
bool CollisionManager::IsColliding(Actor* current, Vector2i pos)
{
if (pos.x >= current->GetLeftBound() &&
pos.x <= current->GetRightBound() &&
pos.y >= current->GetLowerBound() &&
pos.y <= current->GetUpperBound())
{
return true;
}
return false;
}
| true |
2e60b67bc3ffd14fc0f0ebaa9504bbaf1ad4da8f | C++ | ReeniePie/SDI | /Source Code/Image Annotator/Image Annotator/AnnotationsFile.cpp | UTF-8 | 3,525 | 3 | 3 | [] | no_license | #include "AnnotationsFile.h"
#include "iostream"
void AnnotationsFile::newShape()
{
}
void AnnotationsFile::save()
{
std::ofstream file(annotationsFilePath);
file << numOfImages << std::endl;
if (file)
{
for (int i = 0; i < numOfImages; i++)
{
int t = 0;//shape types counter
int p = 0;//shape points counter
file << imageFilenames[i]<<std::endl;
file << numOfShapes[i] << std::endl;
for (int j = 0; j < numOfShapes[i]; j++)
{
file << shapeTypes[t] << std::endl;
if (shapeTypes[t] == "Quadrilaterous")
{
for (int k = 0; k < 4; k++)
{
file << std::to_string(shapePoints[p][0]) << std::endl;
file << std::to_string(shapePoints[p][1]) << std::endl;
p++;
}
}
else if (shapeTypes[t] == "Triangle")
{
for (int k = 0; k < 3; k++)
{
file << std::to_string(shapePoints[p][0]) << std::endl;
file << std::to_string(shapePoints[p][1]) << std::endl;
p++;
}
}
else if (shapeTypes[t] == "Pentagon")
{
for (int k = 0; k < 5; k++)
{
file << std::to_string(shapePoints[p][0]) << std::endl;
file << std::to_string(shapePoints[p][1]) << std::endl;
p++;
}
}
else if (shapeTypes[t] == "Octagon")
{
for (int k = 0; k < 8; k++)
{
file << std::to_string(shapePoints[p][0]) << std::endl;
file << std::to_string(shapePoints[p][1]) << std::endl;
p++;
}
}
else
{
std::cout << "Error message" << std::endl;
}
t++;
}
}
}
else
{
std::cout << "No file created";
}
}
void AnnotationsFile::open()
{
std::ifstream testFile(annotationsFilePath);
std::string x;
if (testFile)
{
//file does exist
getline(testFile, x);
numOfImages = std::stoi(x);
for (int i = 0; i < numOfImages; i++)
{
int t = 0;//shape types counter
int p = 0;//shape points counter
getline(testFile, x);
imageFilenames.push_back(x);
getline(testFile, x);
numOfShapes.push_back(std::stoi(x));
for (int j = 0; j < numOfShapes[i]; j++)
{
getline(testFile, x);
shapeTypes.push_back(x);
if (shapeTypes.back() == "Quadrilaterous")
{
for (int k = 0; k < 4; k++)
{
getline(testFile, x);
int X = std::stoi(x);
getline(testFile, x);
int Y = std::stoi(x);
shapePoints.push_back({ X, Y });
p++;
}
}
else if (shapeTypes.back() == "Triangle")
{
for (int k = 0; k < 3; k++)
{
getline(testFile, x);
int X = std::stoi(x);
getline(testFile, x);
int Y = std::stoi(x);
shapePoints.push_back({ X, Y });
p++;
}
}
else if (shapeTypes.back() == "Pentagon")
{
for (int k = 0; k < 5; k++)
{
getline(testFile, x);
int X = std::stoi(x);
getline(testFile, x);
int Y = std::stoi(x);
shapePoints.push_back({ X, Y });
p++;
}
}
else if (shapeTypes.back() == "Octagon")
{
for (int k = 0; k < 8; k++)
{
getline(testFile, x);
int X = std::stoi(x);
getline(testFile, x);
int Y = std::stoi(x);
shapePoints.push_back({ X, Y });
p++;
}
}
else
{
std::cout << "Incorrect shape name";
}
t++;
}
}
}
else
{
//file doesn't exist
bool save = true;
}
}
bool AnnotationsFile::rename()
{
return false;
}
bool AnnotationsFile::autoSave()
{
return false;
}
| true |
9880a101d36fb7d2e5af2baa61bb82e628f9b829 | C++ | madhav-bits/Coding_Practice | /leetAllOOneDataStruc.cpp | UTF-8 | 7,493 | 3.640625 | 4 | [] | no_license | /*
*
//***********************************************************432. All O`one Data Structure.****************************************************
Implement a data structure supporting the following operations:
Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this
function does nothing. Key is guaranteed to be a non-empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".
Challenge: Perform all these in O(1) time complexity.
*******************************************************************TEST CASES:************************************************************
//These are the examples I had created, tweaked and worked on.
["AllOne","getMaxKey","getMinKey"]
[[],[],[]]
["AllOne","inc", "inc", "dec","getMaxKey","getMinKey"]
[[],["yo"],["yo"],["yo"],[],[]]
["AllOne","inc", "inc", "dec","getMaxKey","getMinKey"]
[[],["yo"],["bro"],["yo"],[],[]]
["AllOne","inc","dec","getMaxKey","getMinKey","inc","getMaxKey","getMinKey"]
[[],["hello"],["hello"],[],[],["leet"],[],[]]
["AllOne","inc","inc","getMaxKey","getMinKey","inc","getMaxKey","getMinKey"]
[[],["hello"],["hello"],[],[],["leet"],[],[]]
["AllOne","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","inc","dec","getMinKey"]
[[],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["b"],["b"],["c"],["c"],[]]
["AllOne","inc","inc","inc","inc","inc","dec","dec","getMaxKey","getMinKey"]
[[],["a"],["b"],["b"],["b"],["b"],["b"],["b"],[],[]]
// Time Complexity: O(1).
// Space Complexity: O(n).
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//*****************************************************THIS IS LEET ACCEPTED CODE.***********************************************
// Time Complexity: O(1).
// Space Complexity: O(n).
// This algorithm is HashMap based. Here, as we need operations of cost O(1), we take HashMap for writing, reading, searching. Here, we maintain
// two maps, one to maintain strings whose #occurances are same, other is to track the #occurances of each string. For every inc/dec. we try to
// udpate minm, maxm variables. When, putting a str, we try to update the maxm. with #occurances of curr. string, for minm: the curr. string
// may be minm, or some other may be minm. If curr. str is minm, then #strings with #occurances as minm will be zero now, so we inc. the minm
// by one. If the curr. string inc. may be minm, so try to update it #occur. of curr. str.
// For dec. If curr. str is the only str with #occur. as maxm value, then we dec. the maxm. val. For minm, if the curr. str is the only str with
// min. count and count>1, then. we dec. the minm. by one. If minm. is 1 and curr. str is the only one, then we have to look for the first key
// in the map(least count among rem. strs). If minm. is >1 and curr. str is the only str, then dec. minm. by 1.
class AllOne {
public:
/** Initialize your data structure here. */
map<int, unordered_set<string>>m; // Tracks strs with same #occurances.
unordered_map<string,int>occur; // Tracks count of each str.
int minm,maxm; // Tracks minm, maxm #occurances.
AllOne() {
minm=0; // Init. all global vars.
maxm=0;
m=map<int, unordered_set<string>>();
occur=unordered_map<string,int>();
}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
void inc(string key) {
// cout<<"INc. key with str: "<<key<<endl;
occur[key]++; // INc. the #occurances.
int len=occur[key];
m[len].insert(key); // Inserting curr. str to #occurances key in map.
if(len>maxm) maxm=len; // Updating maxm. var.
if(len>1){ // If str had prev. occured.
m[len-1].erase(key); // Remove curr. str from prev. #occurances.
if(m[len-1].size()==0) m.erase(len-1); // If now there are no strs with prev. count, remove that count key.
}
if(occur[key]<minm) minm=occur[key]; // If updated count<minm, update minm. var.(A str not a minm count str earlier).
else if(m.count(minm)==0) minm++; // If curr. str is the only minm. count str, then inc. minm. value.
// cout<<"minm: "<<minm<<" and map size: "<<m[minm].size()<<" and maxm: "<<maxm<<endl;
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key) {
// cout<<"Dec. key with str: "<<key<<endl;
// cout<<"Beginning minm: "<<minm<<" and maxm: "<<maxm<<endl;
if(occur.count(key)==0) return ; // If str not present, return.
int len=occur[key]; // Get #earlier occurances.
// cout<<"len: "<<len<<endl;
m[len].erase(key); // Removing str from list of earlier #occurances.
if(m[len].size()==0) m.erase(len); // If this is only str with earlier count, remove that count key.
if(m.count(maxm)==0) maxm--; // If curr. str is the only maxm. count str earlier, dec. maxm. count.
if(len==1) occur.erase(key); // If curr. str had occured once, earlier then remove str from map.
else{ // If curr. str occured>1.
m[len-1].insert(key); // Insert the str. in the new #occurances list.
occur[key]--; // Dec. the #occurances value.
}
if(minm==1 && m.count(minm)==0) minm=m.size()>0? m.begin()->first:0;// If curr. str is the only minm. count str with count 1, then get least count(key).
else if(minm>1 && m.count(minm)==0) minm--; // If curr. str is the only str with minm. count>1, then dec. minm. by 1.
// cout<<"minm: "<<minm<<" and maxm: "<<maxm<<endl;
// cout<<"minm: "<<minm<<" and map size: "<<m[minm].size()<<" and maxm: "<<maxm<<endl;
}
/** Returns one of the keys with maximal value. */
string getMaxKey() {
// cout<<"Getting max. key."<<endl;
if(m.size()==0) return ""; // If map is empty, return empty string.
auto it=m[maxm].begin(); // Return first str in the maxm. #occurances list.
return *it;
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
// cout<<"Getting minm. key."<<endl;
if(m.size()==0) return ""; // If map is empty, return empty string.
auto it=m[minm].begin(); // Return first str in the minm. #occurances list.
return *it;
}
};
/**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* string param_3 = obj.getMaxKey();
* string param_4 = obj.getMinKey();
*/ | true |
be94571e6cb27058a701d769f61ecadaaf73e37d | C++ | zuanfeng/C_learn | /data_structure/graph/shortpath/graph.cpp | UTF-8 | 1,315 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include "queue.h"
#include "head.h"
#define MAX 20
int visited[MAX];
void (* VisitFunc)(int v);
void DFS(ALGraph G,int v){
int w;
visited[v] = 1;
VisitFunc(v);
for(w = FirstAdjVex(G,v);w >= 0;w = NextAdjVex(G,v,w))
if(!visited[w]) DFS(G,w);
}
void DFSTraverse(ALGraph &G,void (* visit)(int v)){
VisitFunc = visit;
int v;
for(v = 0;v < G.vexnum;++v) visited[v] = 0;
for(v = 0;v < G.vexnum;++v)
{
if(!visited[v]) DFS(G,v);
}
printf("\b\b \n");
}
void BFS(ALGraph G,void (*visit)(int v),int begin)
{
for(int v = 0;v < G.vexnum;++v)
{
visited[v] = 0;
}
SqQueue Q;
InitQueue(Q);
for(int v = begin;v < G.vexnum;++v)
{
if(!visited[v])
{
visited[v] = 1;
visit(v);
EnQueue(Q,v);
while(!is_Empty(Q))
{
int u = -1;
DeQueue(Q,u);
for(int w = FirstAdjVex(G,u);w >= 0;w = NextAdjVex(G,u,w))
{
if(!visited[w])
{
visited[w] = 1;
visit(w);
EnQueue(Q,w);
}
}
}
}
}
printf("\b\b ");
printf("\n");
}
int main(){
ALGraph G;
input(G);
int begin;
printf("Where are you want to begin?\n");
scanf("%d",&begin);
printf("BFS traverse:");
BFS(G,visit,begin);
// printf("DFS traverse:");
// DFSTraverse(G,visit);
return 0;
}
| true |
47c7fa79a99eef93c81f49d83dff8ea33c682dab | C++ | ssjf409/PS | /라인/6.cpp | UTF-8 | 1,675 | 2.71875 | 3 | [] | no_license | #include <string>
#include <vector>
#include <map>
#include <queue>
using namespace std;
map<string, string> comp_want;
map<string, int> comp_cnt;
map<string, queue<char>> app_want;
// map<string, int> app_cnt;
vector<string> stov(string str) {
int prev = -1;
int cur = 0;
vector<string> v;
while(true) {
prev = cur;
cur = str.find(' ', prev);
v.push_back(str.substr(prev, cur - prev));
if(cur == -1) break;
cur++;
}
return v;
}
vector<string> solution(vector<string> companies, vector<string> applicants) {
vector<string> answer;
for(int i = 0; i < companies.size(); i++) {
vector<string> data = stov(companies[i]);
comp_want[data[0]] = data[1];
comp_cnt[data[0]] = stoi(data[2]);
}
for(int i = 0; i < applicants.size(); i++) {
vector<string> data = stov(applicants[i]);
queue<char> q;
for(int j = 0; j < stoi(data[2]); j++) {
q.push(data[1][j]);
}
app_want[data[0]] = q;
}
map<string, int>::iterator compIter;
map<string, queue<char>>::iterator iter;
while(true) {
// for(compIter = comp)
for(iter = app_want.begin(); iter != app_want.end(); iter++) {
string name = iter->first;
char wantComp = '.';
if(!(iter->second).empty()) {
wantComp = (iter->second).front();
(iter->second).pop();
}
if(wantComp != '.') {
}
}
}
return answer;
} | true |
dcfea17fa7ed081e8d189b422db97e35dc5a257c | C++ | Kokoster/gp4viewer | /gp4viewer/src/note.cpp | UTF-8 | 6,054 | 2.8125 | 3 | [] | no_license | #include "note.h"
#include <iostream>
#include <fstream>
GraceNote readGraceNote(std::ifstream& inputStream) {
GraceNote graceNote = {
.fret = 0,
.dynamic = 0,
.transition = 0,
.duration = 0
};
graceNote.fret = readData<char>(inputStream);
graceNote.dynamic = readData<char>(inputStream);
graceNote.transition = readData<char>(inputStream);
graceNote.duration = readData<char>(inputStream);
return graceNote;
}
Trill readTrill(std::ifstream& inputStream) {
Trill trill = {
.fret = 0,
.period = 0
};
trill.fret = readData<char>(inputStream);
trill.period = readData<char>(inputStream);
return trill;
}
NoteEffects readNoteEffects(std::ifstream& inputStream) {
NoteEffects effects = {
.tremolo = 0,
.slide = 0,
.harmonics = 0,
.letRing = false,
.hammerPull = false,
.handVibrato = false,
.palmMute = false,
.isStaccato = false
};
effects.header1 = readData<NoteEffectsHeader1>(inputStream);
effects.header2 = readData<NoteEffectsHeader2>(inputStream);
if (effects.header1.containsBend) {
effects.bend = readBend(inputStream);
}
if (effects.header1.containsGraceNote) {
effects.graceNote = readGraceNote(inputStream);
}
if (effects.header2.tremoloPicking) {
effects.tremolo = readData<char>(inputStream);
}
if (effects.header2.containsSlide) {
effects.slide = readData<char>(inputStream);
}
if (effects.header2.harmonics) {
effects.harmonics = readData<char>(inputStream);
}
if (effects.header2.containsTrill) {
effects.trill = readTrill(inputStream);
}
if (effects.header1.letRing) {
effects.letRing = true;
}
if (effects.header1.containsHammerPull) {
effects.hammerPull = true;
}
if (effects.header2.handVibrato){
effects.handVibrato = true;
}
if (effects.header2.palmMute) {
effects.palmMute = true;
}
if (effects.header2.playedStaccato) {
effects.isStaccato = true;
}
return effects;
}
Note readNote(std::ifstream& inputStream) {
Note note {
.type = 0,
.timeDuration = 0,
.nTuplet = 0,
.dynamic = 0,
.fretNumber = 0,
.leftFingering = 0,
.rightFingering = 0,
.isAccentuated = false
};
note.header = readData<NoteHeader>(inputStream);
// std::cout << std::hex;
// std::cout << "note header: " << *reinterpret_cast<int*>(¬e.header) << std::endl;
// std::cout << std::dec;
if (note.header.containsType) {
note.type = readData<char>(inputStream); // CHANGE: short -> char
}
if (note.header.timeIndependentDuration) {
note.timeDuration = readData<char>(inputStream);
note.nTuplet = readData<char>(inputStream);
}
if (note.header.hasDynamic) {
note.dynamic = readData<char>(inputStream);
}
if (note.header.containsType) {
note.fretNumber = readData<char>(inputStream);
}
if (note.header.fingering) {
note.leftFingering = readData<char>(inputStream);
note.rightFingering = readData<char>(inputStream);
}
if (note.header.isAccentuated) {
note.isAccentuated = true;
}
if (note.header.containsEffects) {
note.effects = readNoteEffects(inputStream);
}
return note;
}
Chord readChord(std::ifstream& inputStream, Note* notes) {
Chord chord = readData<Chord>(inputStream);
if (*reinterpret_cast<int*>(&chord) == 0) {
return chord;
}
// std::cout << std::hex;
// std::cout << "tab: " << *reinterpret_cast<int*>(&tab) << std::endl;
// std::cout << std::dec;
if (chord.firstStr) {
// std::cout << "reading first note" << std::endl;
notes[5] = readNote(inputStream);
}
if (chord.secondStr) {
// std::cout << "reading second note" << std::endl;
notes[4] = readNote(inputStream);
}
if (chord.thirdStr) {
// std::cout << "reading third note" << std::endl;
notes[3] = readNote(inputStream);
}
if (chord.fourthStr) {
// std::cout << "reading fourth note" << std::endl;
notes[2] = readNote(inputStream);
}
if (chord.fifthStr) {
// std::cout << "reading fifth note" << std::endl;
notes[1] = readNote(inputStream);
}
if (chord.sixthStr) {
// std::cout << "reading sixth note" << std::endl;
notes[0] = readNote(inputStream);
}
return chord;
}
void printNoteEffects(const NoteEffects& effects) {
std::cout << "header1 " << std::hex << (int)*reinterpret_cast<const char*>(&effects.header1) << std::endl;
std::cout << "header2 " << std::hex << (int)*reinterpret_cast<const char*>(&effects.header2) << std::endl;
std::cout << std::dec;
if (effects.header1.containsBend) {
std::cout << "contains bend" << std::endl;
printBend(effects.bend);
}
}
void printNote(const Note& note) {
if (note.header.containsType) {
std::cout << "type: " << (int)note.type << std::endl;
}
if (note.header.timeIndependentDuration) {
std::cout << "time duration: " << (int)note.timeDuration << std::endl;
std::cout << "tuplet: " << (int)note.nTuplet << std::endl;
}
if (note.header.hasDynamic) {
std::cout << "dynamic: " << (int)note.dynamic << std::endl;
}
if (note.header.containsType) {
std::cout << "fret number: " << (int)note.fretNumber << std::endl;
}
if (note.header.fingering) {
std::cout << "fingering: " << (int)note.leftFingering << " " << note.rightFingering << std::endl;
}
if (note.header.isAccentuated) {
std::cout << "is Accentuated" << std::endl;
}
if (note.header.containsEffects) {
std::cout << "contains effects" << std::endl;
printNoteEffects(note.effects);
}
} | true |
330a9b478e4b5ac74a05b2bc6fb274ee0c71f404 | C++ | JoeCrouch/TextAdventure | /src/menu/mainMenu.cpp | UTF-8 | 3,045 | 3.265625 | 3 | [] | no_license |
#include <iostream>
#include <stdlib.h>
#include "mainMenu.h"
#include "stringManager.h"
using std::cout;
using std::endl;
using std::cin;
using std::getline;
MainMenu& MainMenu::instance() {
static MainMenu instance;
return instance;
}
void MainMenu::printTitle() {
cout
<< StringManager::repeatedSymbol(MENU_WIDTH, "_") << endl
<< StringManager::centerLine(MENU_WIDTH, "Text Adventure", "|") << endl
<< StringManager::repeatedSymbol(MENU_WIDTH, "_") << endl << endl;
}
void MainMenu::printMenuOptions() {
cout
<< StringManager::repeatedSymbol(MENU_WIDTH, "=") << endl
<< StringManager::centerLine(MENU_WIDTH, "", "||") << endl;
for (int i = 0; i < MENU_OPTIONS.size(); i++) {
MenuOption* option = MENU_OPTIONS[i];
string optionName = option->name();
cout << StringManager::centerLine(MENU_WIDTH, "-- " + optionName, "||") << endl;
}
cout
<< StringManager::centerLine(MENU_WIDTH, "", "||") << endl
<< StringManager::repeatedSymbol(MENU_WIDTH, "=") << endl;
}
MenuOption* MainMenu::readOption() {
MenuOption* chosenOption = NULL;
int entryFailures = 0;
cout << "\n\nType Your Choosen Option From Menu: " << endl;
while (chosenOption == NULL) {
string input = string("");
getline(cin, input);
for (int i = 0; i < MENU_OPTIONS.size(); i++) {
MenuOption* option = MENU_OPTIONS[i];
if (StringManager::equalIgnoreCase(option->name(), input)) {
chosenOption = option;
break;
}
}
if (chosenOption == NULL) {
printRepeatInputMessage(entryFailures);
entryFailures++;
}
}
return chosenOption;
}
void MainMenu::printRepeatInputMessage(int entryFailures) {
switch (entryFailures) {
case 0:
cout << "Invalid option try again:" << endl;
break;
case 1:
cout << "Still Invalid try copy and paste? " << endl;
break;
case 2:
cout << "This really isn't rocket science! Enter an option from the list above:" << endl;
break;
case 3:
cout << "Last chance stop being stoopid:" << endl;
break;
case 4:
cout
<< "Congratulations you lose the game before even beginning" << endl
<< StringManager::repeatedSymbol(MENU_WIDTH, "=") << endl
<< StringManager::centerLine(MENU_WIDTH, "", "||") << endl
<< StringManager::centerLine(MENU_WIDTH, " GAME OVER", "||") << endl
<< StringManager::centerLine(MENU_WIDTH, "", "||") << endl
<< StringManager::repeatedSymbol(MENU_WIDTH, "=") << endl << endl;
exit(EXIT_FAILURE);
default:
break;
}
}
const int MainMenu::MENU_WIDTH = 50;
const vector<MenuOption*> MainMenu::MENU_OPTIONS {&(NewGame::instance()), &(LoadGame::instance())};
| true |
86630c588150b126bf0a1eeb97d97cae9bdce0cf | C++ | rikonek/zut | /semestr_2/zaawansowane_programowanie_obiektowe_c++/iostreams.cpp | UTF-8 | 495 | 3.796875 | 4 | [] | no_license | // Implement a program that
// reads N values from command line
// reads N floating point values
// checks if values are given in ascending/descending order
// if ascending multiply, descending add
#include <iostream>
#include <vector>
int main()
{
unsigned int number=0;
std::vector<float> a;
std::cout << "Enter number: ";
std::cin >> number;
std::cout << "Give a numbers: ";
for(unsigned int i=0; i<number; i++)
{
std::cin >> a[i];
}
return 0;
} | true |
4140e6f1643711f95a5b363ee78ea49c51836269 | C++ | MrPerfekt/Car | /src/libraries/Car/PartialAdjustmentCalculation.h | UTF-8 | 928 | 2.671875 | 3 | [] | no_license | /*!
Copyright 2013 Andreas Gruber
*/
#ifndef PARTIAL_ADJUSTMENT_CALCULATION
#define PARTIAL_ADJUSTMENT_CALCULATION
#include "DefineLib.h"
#include "AdjustmentCalculation.h"
class PartialAdjustmentCalculation : public AdjustmentCalculation{
private:
double currentValue;
double currentResult;
protected:
void prepareValue();
public:
PartialAdjustmentCalculation();
PartialAdjustmentCalculation(double lowerLimit,double upperLimit);
/*!
param value The input value
return The wanted result
*/
void setValue(double value);
/*!
return The wanted result of the last getValue command
*/
double getResult();
/*!
param value The input value
param measuredResult The result of the value.
param measuredResult The correct result of the value.
*/
void correctValue(double value, double measuredResult);
/*!
Corrects the last value at the pararmeter of getValue
*/
void correctLastValue(double mesuredResult);
};
#endif | true |
c24580d0fc58c502a93d1dfa94b4055d5a456042 | C++ | 15831944/slefConference | /court/court/Include/RSMTMCU/AVDataPacket.h | UTF-8 | 3,116 | 2.53125 | 3 | [] | no_license | #ifndef __AVDATAPACKET_H__
#define __AVDATAPACKET_H__
//##ModelId=43A0F9F202FD
class AFX_EXT_CLASS AVDataOutPacket
{
public:
//##ModelId=43A0F9F202FE
AVDataOutPacket(bool bAutoDelete=true,int nBufferLength=1024)
:m_pBuffer(NULL)
,m_nBufferLength(nBufferLength)
,m_bAutoDelete(bAutoDelete)
{
m_pBuffer=(unsigned char*)malloc(m_nBufferLength);
if (m_pBuffer==NULL)
{
m_nBufferLength=0;
}
Reset();
}
//##ModelId=43A0F9F20301
virtual~AVDataOutPacket(void)
{
if (m_pBuffer && m_bAutoDelete)
{
free(m_pBuffer);
m_pBuffer=NULL;
}
}
//##ModelId=43A0F9F20304
void Reset()
{
m_pCursor = m_pBuffer;
}
//##ModelId=43A0F9F2030D
unsigned char *GetData()
{
return m_pBuffer;
}
//##ModelId=43A0F9F2030E
int GetLength()
{
int n;
n=(int)(m_pCursor - m_pBuffer);
return n;
}
//##ModelId=43A0F9F2030F
void Write16(unsigned short w);
//##ModelId=43A0F9F20311
void Write32(unsigned int dw);
//##ModelId=43A0F9F20313
void Write64(unsigned long lw);
//##ModelId=43A0F9F2031D
void WriteData(unsigned char *buf, unsigned int n);
//##ModelId=43A0F9F20320
void WriteString(const char *str, unsigned int n);
//##ModelId=43A0F9F20323
AVDataOutPacket &operator <<(unsigned char b);
//##ModelId=43A0F9F2032C
AVDataOutPacket &operator <<(unsigned short w);
//##ModelId=43A0F9F2032E
AVDataOutPacket &operator <<(unsigned int dw);
//##ModelId=43A0F9F20330
AVDataOutPacket &operator <<(unsigned long lw);
//##ModelId=43A0F9F20332
AVDataOutPacket &operator <<(const char *str);
//##ModelId=43A0F9F2033C
unsigned char *Skip(int delta)
{
m_pCursor += delta;
return (m_pCursor - delta);
}
//##ModelId=43A0F9F2033E
unsigned char *SetCursor(unsigned char *pCur)
{
unsigned char *pOld = m_pCursor;
m_pCursor = pCur;
return pOld;
}
protected:
//##ModelId=43A0F9F20340
unsigned char* m_pBuffer;
//##ModelId=43A0F9F20341
unsigned int m_nBufferLength;
//##ModelId=43A0F9F2034B
unsigned char* m_pCursor;
//##ModelId=43A0F9F2034C
bool m_bAutoDelete;
};
//##ModelId=43A0F9F2035B
class AFX_EXT_CLASS AVDataInPacket
{
public:
//##ModelId=43A0F9F2035C
AVDataInPacket(char *d, int n)
{
m_pCursor = m_pData = (unsigned char *) d;
m_nDataLen = n;
}
//##ModelId=43A0F9F2036B
AVDataInPacket &operator >>(unsigned char &b);
//##ModelId=43A0F9F2036D
AVDataInPacket &operator >>(unsigned short &w);
//##ModelId=43A0F9F2036F
AVDataInPacket &operator >>(unsigned int &dw);
//##ModelId=43A0F9F20371
AVDataInPacket &operator >>(unsigned long &lw);
//##ModelId=43A0F9F20373
AVDataInPacket &operator >>(const char* &str);
//##ModelId=43A0F9F2037B
AVDataInPacket &operator >>(char* str);
//##ModelId=43A0F9F2037D
unsigned int Read64();
//##ModelId=43A0F9F2037E
unsigned int Read32();
//##ModelId=43A0F9F2037F
unsigned short Read16();
//##ModelId=43A0F9F20380
unsigned char *ReadData(int &n);
//##ModelId=43A0F9F2038A
int GetLength()
{
return m_nDataLen;
}
protected:
//##ModelId=43A0F9F2038B
unsigned char *m_pData;
//##ModelId=43A0F9F2038C
unsigned char *m_pCursor;
//##ModelId=43A0F9F2038D
int m_nDataLen;
};
#endif
| true |
f21c001f02d2d4c849b0de1efd0f3064f487e062 | C++ | kuroyam/Sketch | /Projects/Sketch/src/Scenes/Sketch170418.cpp | UTF-8 | 807 | 2.765625 | 3 | [] | no_license | //
// Sketch170418.cpp
// Sketch
//
// Created by Shun Kuroda on 2017/04/18.
//
//
#include "Sketch170418.hpp"
void Sketch170418::setup() {
ofSetWindowShape(500, 500);
ofBackground(255);
}
void Sketch170418::update() {
for_each(inks.begin(), inks.end(), [](Ink& ink){
ink.update();
});
}
void Sketch170418::draw() {
for_each(inks.begin(), inks.end(), [](Ink& ink){
ink.draw();
});
}
void Sketch170418::mouseDragged(int x, int y, int button) {
if (button == OF_MOUSE_BUTTON_LEFT) {
inks.push_back(Ink(ofPoint(x, y)));
}
}
void Sketch170418::mousePressed(int x, int y, int button) {
if (button == OF_MOUSE_BUTTON_LEFT) {
inks.push_back(Ink(ofPoint(x, y)));
} else if (button == OF_MOUSE_BUTTON_RIGHT) {
inks.clear();
}
}
| true |
b45ff886ec4704d8b0083ed20536ee5a415562f5 | C++ | ytw0728/BOJ | /6086.cpp | UHC | 1,326 | 2.796875 | 3 | [] | no_license | // ǮĿ ˰ / ī ˰
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define LAST_POINT 'Z'-'A'+1
#define WHOLE 'z' - 'a' + 'Z' - 'A' + 2
using namespace std;
int pipes[WHOLE+1][WHOLE+1];
int visited[WHOLE+1];
int past_point[WHOLE+1];
void back(int start, int water) {
if (start != 1) {
int end = past_point[start];
pipes[start][end] += water;
pipes[end][start] -= water;
back(end,water);
}
}
int dfs( int p, int water) {
if (p == LAST_POINT) return water;
visited[p] = 1;
int temp_water = water;
for (int i = 1; i <= WHOLE; i++) {
temp_water = water;
if (pipes[p][i] > 0 && !visited[i]) {
temp_water = min(water, pipes[p][i]);
past_point[i] = p;
int temp = 0;
if ( temp = dfs(i,temp_water) ) {
return temp;
}
}
}
return 0;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char a, b; int c;
scanf(" %c %c %d", &a, &b, &c);
if ('A' <= a && a <= 'Z') a = a - 'A' + 1;
else a = a - 'a' + 1 + 26;
if ('A' <= b && b <= 'Z') b = b - 'A' + 1;
else b = b - 'a' + 1 + 26;
pipes[a][b] += c;
}
int result = 0;
int temp = 0;
while ( temp = dfs(1, 1000)) {
result += temp;
memset(visited, 0, sizeof(int) * (WHOLE + 1));
back(LAST_POINT,temp);
}
printf("%d", result);
return 0;
} | true |
d1aa7e4b3be7ba0a0c75d75b416f7e0a16e4b8f4 | C++ | alanwj/mines-solver | /mines/solver/local.cpp | UTF-8 | 5,907 | 2.859375 | 3 | [] | no_license | #include "mines/solver/local.h"
#include <cstddef>
#include <queue>
#include <tuple>
#include <vector>
#include "mines/compat/make_unique.h"
#include "mines/game/grid.h"
namespace mines {
namespace solver {
namespace local {
namespace {
class LocalSolver : public Solver {
public:
LocalSolver(const Game& game) : grid_(game.GetRows(), game.GetCols()) {
grid_.ForEach([this](std::size_t row, std::size_t col, Cell& cell) {
cell.adjacent_covered = CountAdjacentCells(row, col);
});
}
~LocalSolver() final = default;
void NotifyEvent(const Event& event) final {
if (!grid_.IsValid(event.row, event.col)) {
return;
}
Cell& cell = grid_(event.row, event.col);
cell.adjacent_mines = event.adjacent_mines;
switch (event.type) {
case Event::Type::UNCOVER:
cell.state = CellState::UNCOVERED;
UpdateAdjacentCovered(event.row, event.col);
QueueAnalyze(event.row, event.col);
QueueAnalyzeAdjacent(event.row, event.col);
break;
case Event::Type::FLAG:
cell.state = CellState::FLAGGED;
UpdateAdjacentFlags(event.row, event.col, true);
QueueAnalyzeAdjacent(event.row, event.col);
break;
case Event::Type::UNFLAG:
cell.state = CellState::COVERED;
UpdateAdjacentFlags(event.row, event.col, false);
QueueAnalyzeAdjacent(event.row, event.col);
break;
case Event::Type::WIN:
// No new knowledge.
break;
case Event::Type::LOSS:
cell.state = CellState::LOSING_MINE;
break;
case Event::Type::IDENTIFY_MINE:
cell.state = CellState::MINE;
break;
case Event::Type::IDENTIFY_BAD_FLAG:
cell.state = CellState::BAD_FLAG;
break;
}
}
std::vector<Action> Analyze() final {
std::vector<Action> actions;
while (!aq_.empty()) {
std::size_t row = std::get<0>(aq_.front());
std::size_t col = std::get<1>(aq_.front());
aq_.pop();
actions = AnalyzeCell(row, col);
if (!actions.empty()) {
break;
}
}
return actions;
}
private:
// Counts the number of adjacent cells.
std::size_t CountAdjacentCells(std::size_t row, std::size_t col) const {
return grid_.ForEachAdjacent(
row, col, [this](std::size_t row, std::size_t col) { return true; });
}
// Updates the adjacent cells to subtract one from their adjacent_covered
// count. This should be called in response to an UNCOVER event.
void UpdateAdjacentCovered(std::size_t row, std::size_t col) {
grid_.ForEachAdjacent(row, col, [this](std::size_t row, std::size_t col) {
--grid_(row, col).adjacent_covered;
return false;
});
}
// Updates the adjacent cells to add or subtract one from their adjacent_flags
// count. This should be called in response to a FLAG or UNFLAG event.
void UpdateAdjacentFlags(std::size_t row, std::size_t col, bool flag) {
grid_.ForEachAdjacent(row, col,
[this, flag](std::size_t row, std::size_t col) {
grid_(row, col).adjacent_flags += flag ? 1 : -1;
return false;
});
}
// Flags adjacent cells that are covered.
std::vector<Action> FlagAdjacentCovered(std::size_t row,
std::size_t col) const {
std::vector<Action> a;
grid_.ForEachAdjacent(row, col,
[this, &a](std::size_t row, std::size_t col) {
if (grid_(row, col).state == CellState::COVERED) {
a.push_back(Action{Action::Type::FLAG, row, col});
}
return false;
});
return a;
}
// Queues a cell to be analyzed. Does nothing for cells that are covered or
// have no adjacent mines.
void QueueAnalyze(std::size_t row, std::size_t col) {
const Cell& cell = grid_(row, col);
if (cell.adjacent_mines != 0 && cell.state == CellState::UNCOVERED) {
aq_.push(std::make_tuple(row, col));
}
}
// Queues analysis of adjacent cells.
void QueueAnalyzeAdjacent(std::size_t row, std::size_t col) {
grid_.ForEachAdjacent(row, col, [this](std::size_t row, std::size_t col) {
QueueAnalyze(row, col);
return false;
});
}
// Analyzes a cell and returns a (possibly empty) set of actions to perform.
std::vector<Action> AnalyzeCell(std::size_t row, std::size_t col) {
if (!grid_.IsValid(row, col)) {
return std::vector<Action>();
}
const Cell& cell = grid_(row, col);
// We only analyze cells that are uncovered with at least one adjacent mine.
if (cell.adjacent_mines == 0 || cell.state != CellState::UNCOVERED) {
return std::vector<Action>();
}
if (cell.adjacent_mines == cell.adjacent_flags) {
return std::vector<Action>{Action{Action::Type::CHORD, row, col}};
}
if (cell.adjacent_mines == cell.adjacent_covered) {
return FlagAdjacentCovered(row, col);
}
return std::vector<Action>();
}
// Represents the solver's knowledge about a cell.
struct Cell {
CellState state = CellState::COVERED;
// The number of adjacent mines.
// Only valid if the state is UNCOVERED.
std::size_t adjacent_mines = 0;
// The number of adjacent cells that are flagged.
std::size_t adjacent_flags = 0;
// The number of adjacent cells that are still covered.
// Note: This number will be computed in in the constructor.
std::size_t adjacent_covered = 0;
};
Grid<Cell> grid_;
// The queue of cells to analyze.
std::queue<std::tuple<std::size_t, std::size_t>> aq_;
};
} // namespace
std::unique_ptr<Solver> New(const Game& game) {
return MakeUnique<LocalSolver>(game);
}
} // namespace local
} // namespace solver
} // namespace mines
| true |
fc8ad5655e3224387c9431fe81970622c6349727 | C++ | pcw109550/problem-solving | /LeetCode/xor-queries-of-a-subarray.cpp | UTF-8 | 606 | 3.546875 | 4 | [] | no_license | // 1310. XOR Queries of a Subarray
#include <iostream>
#include <vector>
class Solution {
public:
std::vector<int> xorQueries(std::vector<int>& arr, std::vector<std::vector<int> >& queries) {
// O(N)
std::vector<int> result;
int N = arr.size();
std::vector<int> D (N + 1, 0);
for (int i = 1; i <= N; i++)
D[i] = D[i - 1] ^ arr[i - 1];
for (auto query : queries)
result.emplace_back(D[query[0]] ^ D[query[1] + 1]);
return result;
}
};
int main(void) {
Solution s;
} | true |
27476ef097fe7f1a1703ccf87b5680695279285f | C++ | rajat-29/PRE-UCA | /MULTIPLE DERIVED CLASS/MULTILPLE INHERTIANCE CONSTRUCTOR.cpp | UTF-8 | 737 | 3.75 | 4 | [] | no_license | #include<iostream>
using namespace std;
class base
{
public:
int a;
base(int x)
{
a=x;
cout<<"BASE CONSTRUCTOR CALLED"<<endl;
}
~base()
{
cout<<"BASE DESTRUCTOR CALLED"<<endl;
}
};
class derive:public base
{
public:
int b;
derive(int x,int y):base(x)
{
b=y;
cout<<"DERIVE CONSTRUCTOR CALLED"<<endl;
}
~derive()
{
cout<<"DERIVE DESTRUCTOR CALLED"<<endl;
}
};
class derive2:public derive
{
public:
int c;
derive2(int x,int y,int z):derive(x,y)
{
c=z;
cout<<"DERIVE2 CONSTRUCTOR CALLED"<<endl;
}
~derive2()
{
cout<<"DERIVE2 DESTRUCTOR CALLED"<<endl;
}
void show()
{
cout<<a<<" "<<b<<" "<<c<<endl;
}
};
int main()
{
derive2 ob(2,3,4);
ob.show();
}
| true |
3ad0c56e4873634412890d7a911a6ffac67f43bc | C++ | 1026minjae/BaekjoonAlgorithm | /11866.cpp | UTF-8 | 584 | 2.796875 | 3 | [] | no_license | #include <cstdio>
int main() {
int N, K, i, cnt = 0, cnt2, cursor;
int *people;
scanf("%d %d",&N,&K);
people = new int[N];
for(i=0;i<N;i++)
people[i] = i+1;
cursor = K-1;
printf("<");
while(true) {
printf("%d",people[cursor]);
people[cursor] = 0;
if(++cnt >= N)
break;
printf(", ");
for(cnt2 = 0; cnt2 < K;) {
cursor = (cursor + 1) % N;
if(people[cursor] != 0) ++cnt2;
}
}
printf(">");
delete [] people;
return 0;
} | true |
6b94d028ff6ba83b432dfc3feb63840f66cf2930 | C++ | Artexety/inflatecpp | /source/adler32.cc | UTF-8 | 1,468 | 2.75 | 3 | [
"MIT"
] | permissive | #include "adler32.h"
unsigned int adler32_z(unsigned int adler, const unsigned char *buf, unsigned int len)
{
unsigned long sum2;
unsigned n;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == NULL)
return 1L;
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD28(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf);
buf += 16;
}
while (len--) {
adler += *buf++;
sum2 += adler;
}
MOD(adler);
MOD(sum2);
}
/* return recombined sums */
return adler | (sum2 << 16);
}
| true |
3e3dfa02950571f60e7e21e4b685166c424affd5 | C++ | ajmarin/coding | /uva/Volume CVII/10789.cpp | UTF-8 | 757 | 2.53125 | 3 | [] | no_license | /////////////////////////////////
// 10789 - Prime Frequency
/////////////////////////////////
#include<cstdio>
#include<cstring>
bool sieve[2005];
unsigned int cnum,i,j,tnum;
unsigned short int oc[128];
char ans[100], line[2005],tail;
int main(void){
memset(sieve,1,sizeof(sieve));
sieve[0] = sieve[1] = 0;
for(i = 4; i < 2005; i+=2) sieve[i] = 0;
for(i = 3; i < 45; i+=2)
if(sieve[i]) for(j=i*i;j<2005;j+=i) sieve[j] = 0;
scanf("%u\n",&cnum);
while(cnum--){
tnum++; tail = 0; gets(line);
memset(oc,0,sizeof(oc));
for(i = 0; line[i]; i++)
oc[line[i]]++;
for(i = 48; i < 123; i++)
if(sieve[oc[i]]) ans[tail++] = i;
ans[tail] = 0;
if(tail) printf("Case %u: %s\n",tnum,ans);
else printf("Case %u: empty\n",tnum);
}
return 0;
}
| true |
46419a43535634b0ae50f87d84aa129e0d8cc433 | C++ | skyformat99/RedisClusterClient | /src/RedisNode.h | UTF-8 | 1,283 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef __REDISNODE_H__
#define __REDISNODE_H__
#include <string>
#include "hiredis.h"
#include <memory>
#include <functional>
#include <list>
#include <chrono>
typedef std::shared_ptr<redisReply> ReplySptr;
typedef std::function<void(redisReply *, const char *command)> PipelineCommandCallback;
struct PipelineNode
{
PipelineNode()
{
callback = nullptr;
command.clear();
}
PipelineNode(PipelineNode && src) :
callback(src.callback),
command(src.command)
{
src.callback = nullptr;
src.command.clear();
}
PipelineCommandCallback callback;
std::string command;
};
class RedisNode
{
friend class RedisNodePool;
public:
RedisNode(std::string host, uint64_t port);
~RedisNode();
bool initialize();
bool connect();
bool keepAlive();
ReplySptr RedisCommand(const char *command, va_list &ap);
ReplySptr RedisCommand(const char *command);
void freeReply(redisReply * reply);
int RedisAppendCommand(PipelineCommandCallback callback, const char *command, va_list& ap);
void processPipeline();
private:
redisContext *mContext;
std::string mHost;
uint64_t mPort;
std::list<PipelineNode> mPipelineNodes;
std::chrono::system_clock::time_point mLastOperationTimestamp;
};
#endif //__REDISNODE_H__ | true |
bfff97ace471b53246a37fe44c1a747b99e1bf03 | C++ | tktk2104/TktkLib | /TktkDirectX12GameLib/TktkDX12WrappingLib/inc/TktkDX12Wrapper/Resource/Buffer/Constant/ConstantBuffer.h | SHIFT_JIS | 1,344 | 2.5625 | 3 | [] | no_license | #ifndef CONSTANT_BUFFER_H_
#define CONSTANT_BUFFER_H_
#include <TktkContainer/HeapArray/HeapArray.h>
#include "ConstantBufferData.h"
namespace tktk
{
// uConstantBufferDatavǗNX
class ConstantBuffer
{
public:
ConstantBuffer(unsigned int constantBufferNum);
~ConstantBuffer() = default;
public:
// uConstantBufferDataṽCX^X
void create(unsigned int id, ID3D12Device* device, unsigned int constantBufferTypeSize, const void* constantBufferDataTopPos);
// w̒萔obt@gpāÃfBXNv^nhɒ萔obt@r[
void createCbv(unsigned int id, ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE heapHandle) const;
// w̒萔obt@XV
// Abv[hobt@VKɍ쐬Ãobt@玩gɃRs[閽߂R}hXgɓo^
void updateBuffer(unsigned int id, ID3D12Device* device, ID3D12GraphicsCommandList* commandList, unsigned int constantBufferTypeSize, const void* constantBufferDataTopPos);
// SẴAbv[hp̃obt@폜
void deleteUploadBufferAll();
private:
HeapArray<ConstantBufferData> m_constantBufferDataArray;
};
}
#endif // !CONSTANT_BUFFER_H_ | true |
ec48356e745a4fc02c6cbb4b70f7b7ba1a83ee61 | C++ | spencerparkin/Junk | /Cornucopia/Code/Nodes/BoundedFloatPairNode.h | UTF-8 | 1,422 | 2.921875 | 3 | [] | no_license | // BoundedFloatPairNode.h
namespace Cornucopia
{
//=================================================================================
// This is like the bounded float node, but maintains a pair of values constrained
// in such a way that one must always be less then or equal to the other. You could
// think of it as a bounded compact interval.
class CORNUCOPIA_API BoundedFloatPairNode : public Node
{
DECL_CORNUCOPIA_CLASSINFO( BoundedFloatPairNode );
public:
BoundedFloatPairNode( void );
virtual ~BoundedFloatPairNode( void );
virtual bool ReadFromTable( lua_State* L, Context& context ) override;
virtual bool WriteToTable( lua_State* L, Context& context ) const override;
virtual bool Copy( const Node* node, Context& context, const CopyParameters& copyParameters ) override;
struct Data
{
double min, max;
double minValue, maxValue;
bool IsValid( void ) const;
bool operator==( const Data& data ) const;
};
bool Set( const Data& data );
void Get( Data& data ) const;
virtual std::string GetValueToDisplayString( void ) const override;
virtual ValueStringError GetValueToString( std::string& valueString ) const override;
virtual ValueStringError SetValueFromString( const std::string& valueString ) override;
virtual ValueStringError GetValueAsStringHelp( std::string& helpString ) const override;
private:
Data data;
};
}
// BoundedFloatPairNode.h | true |
e129e3d8b80221e5f687b8a6f7f193ec49e369ac | C++ | tuonii/notspot_sim_cpp | /src/notspot_controller/include/notspot_controller/StandController.hpp | UTF-8 | 1,325 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* StandController.hpp
* Author: lnotspotl
*/
#pragma once
#include <Eigen/Core>
#include <sensor_msgs/Joy.h>
#include "notspot_controller/StateCommand.hpp"
class StandController{
public:
// StandController class constructor - set default stance,
StandController(Eigen::Matrix<float, 3, 4> def_stance);
// ROS joystick callback - update state and other variables
void updateStateCommand(const sensor_msgs::Joy::ConstPtr& msg,
State& state, Command& command);
// Main run function, return leg positions in the base_link_world frame
Eigen::Matrix<float, 3, 4> run(State& state, Command& command);
private:
// robot's default stance
Eigen::Matrix<float, 3, 4> def_stance;
// return default_stance
Eigen::Matrix<float, 3, 4> default_stance();
// Controller step - return new leg positions
Eigen::Matrix<float, 3, 4> step(State& state, Command& command);
// FR leg position in the X direction
float FR_X;
// FR leg position in the Y direction
float FR_Y;
// FL leg position in the X direction
float FL_X;
// FL leg position in the Y direction
float FL_Y;
// maximal leg reach
float max_reach;
};
| true |
b57e125f97486654b66e2c6d13c37bb3a3a34cea | C++ | YunlongNie/BayDR | /CauEst2.cpp | UTF-8 | 1,251 | 2.59375 | 3 | [] | no_license |
/**
Causal <- apply(CSample,1,function(x)
{
tem <- phi0+phi2/sqrt(K)*(sum(x[seq(1,((r-2)*K),by=r)])-0.5*K)+
lambda2/sqrt(K)*(sum(x[seq(3,(r*K),by=r)]*x[seq(4,(r*K),by=r)])-Mean34*K)
(inv.logit(tem+phi1+lambda1/sqrt(K)*(sum(x[seq(2,(r*K),by=r)])-0.5*K)) - inv.logit(tem))
}
)
*/
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector CauEstC2(NumericMatrix CSample, double phi0, double phi1,double phi2,
double lambda1,double lambda2, int r,int K,double mean34) {
int nrow=CSample.nrow();
NumericVector out(nrow);
for (int i=0;i<nrow;++i)
{
double s1=0,s2=0,s34=0;
for (int j=0;j<K;++j)
{
s1+=CSample(i,0+j*r);
s2+=CSample(i,1+j*r);
s34+=CSample(i,2+j*r)*CSample(i,3+j*r);
}
double tp,tp2;
tp = phi0+phi2/sqrt(K)*(s1-0.5*K)+lambda2/sqrt(K)*(s34-mean34*K);
tp2 = tp+phi1+lambda1/sqrt(K)*(s2-0.5*K);
out[i]=exp(tp2)/(exp(tp2)+1) - exp(tp)/(exp(tp)+1) ;
}
return out;
}
/**
CausalEst <- function(K=2,r=6,rho=0.3,phi0=0.2,phi1=1,phi2=1,lambda1=1,lambda2=0,CSample) {
Z <- rnorm(10000,0,1)
Mean34 <- mean((1-pnorm((rho^(-1)-1)^(-0.5)*Z,0,1))^2)
causal2 <- CauEstC(CSample,phi0,phi1,phi2,lambda1,lambda2,r,K,Mean34)
mean(Causal)
}
*/
| true |
0d1027f3c8d7cc9f2b64117062f37e7b95b5357f | C++ | visualizersdotnl/cookiedough | /code/fast-cosine.h | UTF-8 | 1,227 | 2.59375 | 3 | [
"MIT"
] | permissive |
// cookiedough -- fast (co)sine
#pragma once
constexpr unsigned kFastCosTabLog2Size = 10; // Equals size of 1024
constexpr unsigned kFastCosTabSize = (1 << kFastCosTabLog2Size);
extern double g_fastCosTab[kFastCosTabSize+1];
void InitializeFastCosine();
// [0..1] equals [0..2PI]
CKD_INLINE static float fastcosf(double x)
{
// Cosine is symmetrical around 0, let's get rid of negative values
x = fabs(x);
// Convert [0..k2PI] to [1..2]
constexpr auto phaseScale = 1.f/k2PI;
const auto phase = 1.0 + x*phaseScale;
const auto phaseAsInt = *reinterpret_cast<const unsigned long long *>(&phase);
const int exponent = (phaseAsInt >> 52) - 1023;
constexpr auto fractBits = 32 - kFastCosTabLog2Size;
constexpr auto fractScale = 1 << fractBits;
constexpr auto fractMask = fractScale - 1;
const auto significand = (unsigned int)((phaseAsInt << exponent) >> (52 - 32));
const auto index = significand >> fractBits;
const int fract = significand & fractMask;
const auto left = g_fastCosTab[index];
const auto right = g_fastCosTab[index+1];
const auto fractMix = fract*(1.0/fractScale);
return float(left + (right-left) * fractMix);
}
CKD_INLINE static float fastsinf(double x) { return fastcosf(x-0.25); }
| true |
c95c4635409c551987643a114de7e0c7b95959c3 | C++ | Aaryankamboj/Data-Structures-and-algorithms | /dynamically_initialization_of_2D_Arrays.cpp | UTF-8 | 492 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<random>
using namespace std;
int main(){
int row, col;
cin >> row >> col;
int **arr=new int*[row];
for(int i=0; i<row; i++){
arr[i]= new int[col];
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
arr[i][j] = rand()%100;
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout<<arr[i][j]<<" ";
}cout<<endl;
delete[] arr[i];
}
delete [] arr;
} | true |
22a7de68c8f8965de1284f09087080223b2961da | C++ | renardbebe/myPOJ | /1363.Rails.cpp | UTF-8 | 827 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <stack>
#include <deque>
using namespace std;
int a[1001];
int main () {
int n;
while(cin >> n) {
if(n == 0) break;
while(1) {
memset(a,0,sizeof(a));
deque<int>q;
stack<int>s;
cin >> a[0];
if(a[0] == 0) break;
q.push_front(a[0]);
for(int i = 1; i < n; i++) {
cin >> a[i];
q.push_front(a[i]);
}
for(int i = n; i >= 1;) {
if(!q.empty() && q.front() == i) {
q.pop_front();
i--;
}
else if(!s.empty() && (s.top() == i)) {
s.pop();
i--;
}
else {
if(!q.empty()) {
s.push(q.front());
q.pop_front();
}
else break;
}
}
if(s.empty()) cout << "Yes\n";
else cout << "No\n";
}
cout << endl;
}
return 0;
}
| true |
d850b3f84a9fcffded71c7b90f5fd38827cddad6 | C++ | zjkmxy/algo-problems | /平成26年/其他图论/POJ1659 Havel定理(顶点度数构图).cpp | UTF-8 | 1,158 | 2.75 | 3 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<sstream>
#include<queue>
#include<vector>
using namespace std;
#define MAXN 20
struct DATA
{
int deg;
int lab;
}arr[MAXN];
typedef DATA *PDATA;
int n;
int mat[MAXN][MAXN];
int comp(const void *A, const void *B)
{
return PDATA(B)->deg - PDATA(A)->deg;
}
bool domain()
{
int i, j;
scanf("%d",&n);
for(i=0;i<n;i++)
{
arr[i].lab = i;
scanf("%d",&arr[i].deg);
}
memset(mat, 0, sizeof(mat));
qsort(arr, n, sizeof(DATA), comp);
for(i=0;i<n;i++)
{
for(j=i+1;j<n && arr[i].deg>0;j++)
{
arr[j].deg--;
arr[i].deg--;
if(arr[j].deg < 0)
return false;
mat[arr[i].lab][arr[j].lab] = 1;
mat[arr[j].lab][arr[i].lab] = 1;
}
if(arr[i].deg > 0)
return false;
qsort(arr+i+1, n-i-1, sizeof(DATA), comp);
}
return true;
}
int main()
{
int t, i, j;
scanf("%d",&t);
while(t--)
{
if(!domain())
{
printf("NO\n");
if(t>0)
printf("\n");
continue;
}
printf("YES\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(j==0?"%d":" %d",mat[i][j]);
}
printf("\n");
}
if(t>0)
printf("\n");
}
return 0;
} | true |
3416eeb81680d40288c63edb8805c0c2575423f4 | C++ | E-TD/CSE_190_Virtual_Reality | /Cave Simulator/Minimal/Cam.cpp | UTF-8 | 3,589 | 3.0625 | 3 | [] | no_license | #include "Cam.h"
Cam::Cam() {
// Default camera parameters
cam_pos = glm::vec3(0.0f, 0.0f, 20.0f); // e | Position of camera
cam_look_at = glm::vec3(0.0f, 0.0f, 0.0f); // d | This is where the camera looks at
cam_up = glm::vec3(0.0f, 1.0f, 0.0f); // up | What orientation "up" is
toWorld = glm::mat4(1.0f);
direction = cam_look_at - cam_pos;
direction = normalize(direction);
}
Cam::~Cam() {}
void Cam::moveVV(glm::vec3 currPos) {
glm::vec3 dir = - currPos + cursorPos; // current mouse position minus previous mouse position
glm::vec3 curruntPos(currPos.x, currPos.y, currPos.z);
glm::vec3 zplane(0.0f, 0.0f, -1.0f);
//std::cout << "currPos: "<< currPos.x << currPos.y << currPos.z << std::endl;
//std::cout << "cursorPos: " << cursorPos.x << cursorPos.y << cursorPos.z << std::endl;
float bel = length(dir); // find length of curr - prev
if (bel > 0.0001) { // if length of curr - prev is substantial
glm::vec4 direct(direction, 1.0f);
float rotAngle = 0.0f;
// find rotation angle in y axis
rotAngle = asin(dir.y / 2.0f) * 2.0f;
rotAngle = (rotAngle * 180.0f) / 3.141592653f; //converts radians to degrees
glm::vec3 crossr = glm::cross(glm::vec3(0.0f, 1.0f, 0.0f), direction);
glLoadIdentity(); // load the identity matrix onto the matrix stack
glRotatef(rotAngle, crossr.x, crossr.y, crossr.z); // rotate this identity matrix by angleor degrees around axisor
//glMultMatrixf((GLfloat *)&toWorld[0][0]); // multiply this rotated matrix by the toWorld matrix
glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *)&toWorld[0][0]); // overwrite the toWorld matrix with this new matrix
direct = toWorld * direct; // translate camera look at val by rotAngle degrees about the y axis
// find angle of rotation in x axis
rotAngle = asin(dir.x / 2.0f) * 2.0f;
rotAngle = (rotAngle * 180.0f) / 3.141592653f; //converts radians to degrees
glLoadIdentity(); // load the identity matrix onto the matrix stack
glRotatef(rotAngle, 0.0f, 1.0f, 0.0f); // rotate this identity matrix by angleor degrees around axisor
//glMultMatrixf((GLfloat *)&toWorld[0][0]); // multiply this rotated matrix by the toWorld matrix
glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *)&toWorld[0][0]); // overwrite the toWorld matrix with this new matrix
direct = toWorld * direct; // translate direct (which was previously translated) by x degrees
direction = glm::vec3(direct.x, direct.y, direct.z);
cam_look_at = cam_pos + direction;
}
cursorPos = curruntPos; // set prev mouse position to new mouse position for next mouse movement
}
void Cam::translate(int ver) {
if (ver == 0) {//"W"
cam_pos = cam_pos + (direction);
cam_look_at = cam_look_at + (direction);
}
else if (ver == 1) {//"A"
//std::cout << "A\n";
glm::vec3 du = glm::cross(cam_up, direction);
cam_pos = cam_pos + (du);
cam_look_at = cam_look_at + (du);
}
else if (ver == 2) {//"s"
//std::cout << "S\n";
cam_pos = cam_pos - (direction);
cam_look_at = cam_look_at - (direction);
}
else if (ver == 3) {//"D"
//std::cout << "D\n";
glm::vec3 du = glm::cross(cam_up, direction);
cam_pos = cam_pos - (du);
cam_look_at = cam_look_at - (du);
}
}
void Cam::reset() {
// Default camera parameters
cam_pos = glm::vec3(0.0f, 0.0f, 20.0f); // e | Position of camera
cam_look_at = glm::vec3(0.0f, 0.0f, 19.0f); // d | This is where the camera looks at
cam_up = glm::vec3(0.0f, 1.0f, 0.0f); // up | What orientation "up" is
toWorld = glm::mat4(1.0f);
direction = cam_look_at - cam_pos;
direction = normalize(direction);
}
| true |
499f615a6cb01a77d4129ae29288f17b5ec298e7 | C++ | clangen/autom8 | /src/app/util/ConsoleLogger.cpp | UTF-8 | 2,366 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "ConsoleLogger.h"
#include <cursespp/SimpleScrollAdapter.h>
#include <app/util/Message.h>
#include <f8n/str/util.h>
#include <time.h>
using namespace f8n;
using namespace f8n::runtime;
using namespace autom8::app;
using namespace cursespp;
static const int MESSAGE_LOG = autom8::app::message::CreateType();
static std::string timestamp() {
time_t rawtime = { 0 };
char buffer[64] = { 0 };
time(&rawtime);
#ifdef WIN32
struct tm timeinfo = { 0 };
localtime_s(&timeinfo, &rawtime);
strftime(buffer, sizeof(buffer), "%T", &timeinfo);
#else
struct tm* timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%T", timeinfo);
#endif
return std::string(buffer);
}
struct LogMessage: public message::BaseMessage {
std::string logValue;
LogMessage(IMessageTarget* target, const std::string& value)
: BaseMessage(target, MESSAGE_LOG, 0, 0) {
this->logValue = value;
}
};
ConsoleLogger::ConsoleLogger(IMessageQueue& messageQueue)
: messageQueue(messageQueue) {
this->adapter = std::make_shared<SimpleScrollAdapter>();
this->adapter->SetSelectable(true);
messageQueue.Register(this);
}
ConsoleLogger::~ConsoleLogger() {
messageQueue.Unregister(this);
}
void ConsoleLogger::verbose(const std::string& tag, const std::string& string) {
this->FormatAndDispatch(tag, "v", string);
}
void ConsoleLogger::info(const std::string& tag, const std::string& string) {
this->FormatAndDispatch(tag, "i", string);
}
void ConsoleLogger::warning(const std::string& tag, const std::string& string) {
this->FormatAndDispatch(tag, "w", string);
}
void ConsoleLogger::error(const std::string& tag, const std::string& string) {
this->FormatAndDispatch(tag, "e", string);
}
void ConsoleLogger::FormatAndDispatch(
const std::string& tag, const std::string& level, const std::string& str)
{
const std::string formatted = str::format(
"%s [%s] [%s] %s", timestamp().c_str(), level.c_str(), tag.c_str(), str.c_str());
this->messageQueue.Post(std::make_shared<LogMessage>(this, formatted));
}
void ConsoleLogger::ProcessMessage(IMessage& message) {
if (message.Type() == MESSAGE_LOG) {
this->adapter->AddEntry(static_cast<LogMessage*>(&message)->logValue);
}
}
ConsoleLogger::AdapterPtr ConsoleLogger::Adapter() {
return this->adapter;
}
| true |
55e39af2a384d503009c9db88feb8c8cf7a3f5f9 | C++ | goodann/AlgorithmsStudy | /SSK/Algorithms/04String/07.Pangrams.cpp | UTF-8 | 1,060 | 2.65625 | 3 | [] | no_license | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
vector<int> count(26);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string str;
getline(cin,str);
for(int i=0;i<str.size();i++){
if(str[i]>='a' && str[i]<='z')
count[str[i]-'a']++;
if(str[i]>='A' && str[i]<='Z')
count[str[i]-'A']++;
}
bool isPangram=true;
for(int i=0;i<26;i++){
//cout<<(char)(i+'a')<<count[i]<<" ";
if(count[i]==0){
isPangram=false;
break;
}
}
if(isPangram)
cout<<"pangram"<<endl;
else
cout<<"not pangram"<<endl;
return 0;
}
| true |
95c1ba7606daf8f31e7d44fd927407e0616c3719 | C++ | nrghosh/Data-Structures | /Trees/BST-Height.cpp | UTF-8 | 441 | 3.21875 | 3 | [] | no_license | /*
Height of a BST
The tree node has data, left child tree and right child tree
class Node {
int data;
Node* left;
Node* right;
};
*/
int height(Node* root){
if(root == NULL){
return -1;
} else {
int lHeight = height(root->left);
int rHeight = height(root->right);
if(lHeight >= rHeight){
return lHeight+1;
} else {
return rHeight+1;
}
}
}
| true |
9ef0d388386e1d857cc8a1288727cc7dc03d5d39 | C++ | kongakong/StackoverflowCode | /c++/SO-60052050/main.cpp | UTF-8 | 226 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int var;
cout << "What size do you want to choose: "<< endl;
cin >> var;
int arr[var];
arr[0] = 10;
cout << arr[0] << endl;
}
| true |
13251931148b697fbbedccdf28c42cccf1105da7 | C++ | victorleal/lab_poo_bilheteria | /Bilhete.h | UTF-8 | 853 | 2.53125 | 3 | [] | no_license | /*
* File: Bilhete.h
* Author: victorleal
*
* Created on 8 de Outubro de 2012, 20:31
*/
#ifndef BILHETE_H
#define BILHETE_H
#include "PersistentObject.h"
#include "Cliente.h"
#include "Espetaculo.h"
#include "Pagamento.h"
class Bilhete : public PersistentObject {
private:
Cliente cliente;
string codigoBilhete;
Espetaculo espetaculo;
Pagamento pagamento;
protected:
string getClassName();
string serialize();
void unserialize();
public:
Bilhete();
Cliente getCliente();
string getCodigoBilhete();
Espetaculo getEspetaculo();
Pagamento getPagamento();
void setCodigoBilhete(string);
void setEspetaculo(Espetaculo);
void setCliente(Cliente);
void setPagamento(Pagamento);
void show();
};
#endif /* BILHETE_H */
| true |
ea6a9b9db362b77490ccf2b917e283bfecb1a51c | C++ | epics-extensions/ea-cpp | /src/common/storage/CtrlInfo.cpp | UTF-8 | 7,658 | 2.796875 | 3 | [] | no_license | // epics
#include <cvtFast.h>
// tools
#include "tools/GenericException.h"
#include "tools/string2cp.h"
#include "tools/Conversions.h"
// storage
#include "storage/CtrlInfo.h"
CtrlInfo::CtrlInfo() {
size_t additional_buffer = 10;
_infobuf.reserve(sizeof(CtrlInfoData) + additional_buffer);
CtrlInfoData *info = _infobuf.mem();
info->type = Invalid;
//sizeof (DbrCount) + sizeof(DbrType);
info->size = 2 + 2;
}
CtrlInfo::CtrlInfo(const CtrlInfo &rhs)
{
const CtrlInfoData *rhs_info = rhs._infobuf.mem();
_infobuf.reserve(rhs_info->size);
CtrlInfoData *info = _infobuf.mem();
memcpy(info, rhs_info, rhs_info->size);
}
CtrlInfo & CtrlInfo::operator = (const CtrlInfo &rhs)
{
const CtrlInfoData *rhs_info = rhs._infobuf.mem();
_infobuf.reserve(rhs_info->size);
CtrlInfoData *info = _infobuf.mem();
memcpy(info, rhs_info, rhs_info->size);
return *this;
}
bool CtrlInfo::operator == (const CtrlInfo &rhs) const
{
const CtrlInfoData *rhs_info = rhs._infobuf.mem();
const CtrlInfoData *info = _infobuf.mem();
// memcmp over the full info should start by comparing
// the size & type fields and work in any case,
// but valgrind complained about use of uninitialized
// memory, so now it's explicit:
return info->size == rhs_info->size &&
info->type == rhs_info->type &&
memcmp(&info->value, &rhs_info->value,
rhs_info->size - 2*sizeof(uint16_t)) == 0;
}
CtrlInfo::Type CtrlInfo::getType() const
{ return (CtrlInfo::Type) (_infobuf.mem()->type);}
int32_t CtrlInfo::getPrecision() const
{
if (getType() == Numeric)
return _infobuf.mem()->value.analog.prec;
return 0;
}
const char *CtrlInfo::getUnits() const
{
if (getType() == Numeric)
return _infobuf.mem()->value.analog.units;
return "";
}
float CtrlInfo::getDisplayHigh() const
{ return _infobuf.mem()->value.analog.disp_high; }
float CtrlInfo::getDisplayLow() const
{ return _infobuf.mem()->value.analog.disp_low; }
float CtrlInfo::getHighAlarm() const
{ return _infobuf.mem()->value.analog.high_alarm; }
float CtrlInfo::getHighWarning() const
{ return _infobuf.mem()->value.analog.high_warn; }
float CtrlInfo::getLowWarning() const
{ return _infobuf.mem()->value.analog.low_warn; }
float CtrlInfo::getLowAlarm() const
{ return _infobuf.mem()->value.analog.low_alarm; }
size_t CtrlInfo::getNumStates() const
{
if (getType() == Enumerated)
return _infobuf.mem()->value.index.num_states;
return 0;
}
void CtrlInfo::setNumeric(
int32_t prec, const stdString &units,
float disp_low, float disp_high,
float low_alarm, float low_warn, float high_warn, float high_alarm)
{
size_t len = units.length();
size_t size = sizeof(CtrlInfoData) + len;
_infobuf.reserve(size);
CtrlInfoData *info = _infobuf.mem();
info->type = Numeric;
info->size = size;
info->value.analog.disp_high = disp_high;
info->value.analog.disp_low = disp_low;
info->value.analog.low_warn = low_warn;
info->value.analog.low_alarm = low_alarm;
info->value.analog.high_warn = high_warn;
info->value.analog.high_alarm = high_alarm;
info->value.analog.prec = prec;
string2cp (info->value.analog.units, units, len+1);
}
void CtrlInfo::setEnumerated(size_t num_states, char *strings[])
{
size_t i, len = 0;
for (i=0; i<num_states; i++) // calling strlen twice for each string...
len += strlen(strings[i]) + 1;
allocEnumerated (num_states, len);
for (i=0; i<num_states; i++)
setEnumeratedString(i, strings[i]);
}
void CtrlInfo::allocEnumerated(size_t num_states, size_t string_len)
{
// actually this is too big...
size_t size = sizeof(CtrlInfoData) + string_len;
_infobuf.reserve(size);
CtrlInfoData *info = _infobuf.mem();
info->type = Enumerated;
info->size = size;
info->value.index.num_states = num_states;
char *enum_string = info->value.index.state_strings;
*enum_string = '\0';
}
// Must be called after allocEnumerated()
// AND must be called in sequence,
// i.e. setEnumeratedString (0, ..
// setEnumeratedString (1, ..
void CtrlInfo::setEnumeratedString(size_t state, const char *string)
{
CtrlInfoData *info = _infobuf.mem();
if (info->type != Enumerated ||
state >= (size_t)info->value.index.num_states)
return;
char *enum_string = info->value.index.state_strings;
size_t i;
for (i=0; i<state; i++) // find this state string...
enum_string += strlen(enum_string) + 1;
strcpy(enum_string, string);
}
// After allocEnumerated() and a sequence of setEnumeratedString ()
// calls, this method recalcs the total size
// and checks if the buffer is sufficient (Debug version only)
void CtrlInfo::calcEnumeratedSize ()
{
size_t i, len, total=sizeof(CtrlInfoData);
CtrlInfoData *info = _infobuf.mem();
char *enum_string = info->value.index.state_strings;
for (i=0; i<(size_t)info->value.index.num_states; i++)
{
len = strlen(enum_string) + 1;
enum_string += len;
total += len;
}
info->size = total;
LOG_ASSERT(total <= _infobuf.capacity());
}
void CtrlInfo::formatDouble(double value, stdString &result) const
{
if (getType() != Numeric)
{
result = "<enumerated>";
return;
}
char buf[200];
if (cvtDoubleToString(value, buf, getPrecision()) >= 200)
result = "<too long>";
else
result = buf;
}
const char *CtrlInfo::getState(size_t state, size_t &len) const
{
if (getType() != Enumerated)
return 0;
const CtrlInfoData *info = _infobuf.mem();
const char *enum_string = info->value.index.state_strings;
size_t i=0;
do
{
len = strlen(enum_string);
if (i == state)
return enum_string;
enum_string += len + 1;
++i;
}
while (i < (size_t)info->value.index.num_states);
len = 0;
return 0;
}
void CtrlInfo::getState(size_t state, stdString &result) const
{
size_t len;
const char *text = getState(state, len);
if (text)
{
result.assign(text, len);
return;
}
char buffer[80];
sprintf(buffer, "<Undef: %u>", (unsigned int)state);
result = buffer;
}
bool CtrlInfo::parseState(const char *text,
const char **next, size_t &state) const
{
const char *state_text;
size_t i, len;
for (i=0; i<getNumStates(); ++i)
{
state_text = getState(i, len);
if (! state_text)
{
LOG_MSG("CtrlInfo::parseState: missing state %zu", i);
return false;
}
if (!strncmp(text, state_text, len))
{
state = i;
if (next)
*next = text + len;
return true;
}
}
return false;
}
void CtrlInfo::show(FILE *f) const
{
if (getType() == Numeric)
{
fprintf(f, "CtrlInfo: Numeric\n");
fprintf(f, "Display : %g ... %g\n", getDisplayLow(), getDisplayHigh());
fprintf(f, "Alarm : %g ... %g\n", getLowAlarm(), getHighAlarm());
fprintf(f, "Warning : %g ... %g\n", getLowWarning(), getHighWarning());
fprintf(f, "Prec : %ld '%s'\n", (long)getPrecision(), getUnits());
}
else if (getType() == Enumerated)
{
fprintf(f, "CtrlInfo: Enumerated\n");
fprintf(f, "States:\n");
size_t i, len;
for (i=0; i<getNumStates(); ++i)
{
fprintf(f, "\tstate='%s'\n", getState(i, len));
}
}
else
fprintf(f, "CtrlInfo: Unknown\n");
}
| true |
a6c07db3a06bcdcc2fd8808846220d206cde1a38 | C++ | zeliard/MCServer | /src/BlockEntities/BlockEntity.cpp | UTF-8 | 2,784 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive |
// BlockEntity.cpp
// Implements the cBlockEntity class that is the common ancestor for all block entities
#include "Globals.h"
#include "BeaconEntity.h"
#include "BlockEntity.h"
#include "ChestEntity.h"
#include "CommandBlockEntity.h"
#include "DispenserEntity.h"
#include "DropperEntity.h"
#include "EnderChestEntity.h"
#include "FlowerPotEntity.h"
#include "FurnaceEntity.h"
#include "HopperEntity.h"
#include "MobHeadEntity.h"
#include "MobSpawnerEntity.h"
#include "JukeboxEntity.h"
#include "NoteEntity.h"
#include "SignEntity.h"
cBlockEntity * cBlockEntity::CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World)
{
switch (a_BlockType)
{
case E_BLOCK_BEACON: return new cBeaconEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_CHEST: return new cChestEntity (a_BlockX, a_BlockY, a_BlockZ, a_World, a_BlockType);
case E_BLOCK_COMMAND_BLOCK: return new cCommandBlockEntity(a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_DISPENSER: return new cDispenserEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_DROPPER: return new cDropperEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_ENDER_CHEST: return new cEnderChestEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_FLOWER_POT: return new cFlowerPotEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_FURNACE: return new cFurnaceEntity (a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_World);
case E_BLOCK_HEAD: return new cMobHeadEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_HOPPER: return new cHopperEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_MOB_SPAWNER: return new cMobSpawnerEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_JUKEBOX: return new cJukeboxEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_LIT_FURNACE: return new cFurnaceEntity (a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_World);
case E_BLOCK_SIGN_POST: return new cSignEntity (a_BlockType, a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_TRAPPED_CHEST: return new cChestEntity (a_BlockX, a_BlockY, a_BlockZ, a_World, a_BlockType);
case E_BLOCK_WALLSIGN: return new cSignEntity (a_BlockType, a_BlockX, a_BlockY, a_BlockZ, a_World);
case E_BLOCK_NOTE_BLOCK: return new cNoteEntity (a_BlockX, a_BlockY, a_BlockZ, a_World);
}
LOGD("%s: Requesting creation of an unknown block entity - block type %d (%s)",
__FUNCTION__, a_BlockType, ItemTypeToString(a_BlockType).c_str()
);
ASSERT(!"Requesting creation of an unknown block entity");
return nullptr;
}
| true |
74191342dc0978ae2413228e83acf06d42125fa2 | C++ | antimasingh070/CodeChef | /MyCode/Find Second Largest.cpp | UTF-8 | 294 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <limits.h>
using namespace std;
int main() {
int a[3],max=INT_MIN,smax=INT_MIN,i;
cin>>a[0]>>a[1]>>a[2];
for(i=0; i<3; i++)
{
if(a[i]>max){
smax=max;
max=a[i];}
else if(a[i]>smax){
smax=a[i];}
}
cout<<smax<<endl;
return 0;
}
| true |
572f66647fcf170bd5b7bdd5e74be0102b452f3a | C++ | jlechem/RetroGaming | /RetroGaming/MontyHall.cpp | UTF-8 | 1,731 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | /*
This file is part of {{ RetroGaming }}.
Copyright [2019] [Justin LeCheminant]
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 "MontyHall.h"
MontyHall::MontyHall()
{
_name = "Monty Hall Simulation";
_description = "Monty hall simulation for the 3 door game on Win, Lose, or Draw!";
}
MontyHall::~MontyHall()
{
}
void MontyHall::play()
{
auto iterations = 1000000;
auto first_choice_wins = 0.0;
auto second_choice_wins = 0.0;
char doors[3]{ 'a', 'b', 'c' };
cout << "Welcome to the Monty Hall Simulator" << endl
<< "This example shows the odss from picking the second door in a Win, Lose, or Draw bonus round" << endl << endl;
for (auto i = 0; i < iterations; i++)
{
auto winner = doors[getRandomNumber(2)];
auto pick = doors[getRandomNumber(2)];
if (winner == pick)
{
first_choice_wins++;
}
else
{
second_choice_wins++;
}
}
cout
<< "Total iterations: " << iterations << endl
<< "First Pick Wins: " << first_choice_wins << endl
<< "Second Pick Wins: " << second_choice_wins << endl
<< fixed << setprecision(2)
<< "Probability of first choice win: " << (first_choice_wins / iterations ) << endl
<< "Probability of second choice win: " << (second_choice_wins / iterations) << endl << endl;
}
| true |
0c339dd5a3b5b80605f7e9dbcd9e392ca1447150 | C++ | cesarl/ThreadsMessagePassing | /TMP/TMP/src/dispatcher.hpp | UTF-8 | 753 | 2.59375 | 3 | [] | no_license | #pragma once
#include "queue.hpp"
namespace TMQ
{
struct MessageBase;
class Dispatcher
{
private:
TMQ::Queue *_queue;
bool _chained;
Dispatcher(const Dispatcher &) = delete;
Dispatcher &operator=(const Dispatcher &) = delete;
template < typename _Dispatcher
, typename _Message
, typename _Func>
friend class TemplateDispatcher;
void waitAndDispatch();
bool dispatch(MessageBase* &msg);
public:
Dispatcher(Dispatcher &&o);
explicit Dispatcher(TMQ::Queue *queue);
template < typename _Message
, typename _Func>
TemplateDispatcher<Dispatcher, _Message, _Func>
handle(_Func &&f)
{
return TemplateDispatcher<Dispatcher, _Message, _Func>(_queue, this, std::forward<_Func>(f));
}
~Dispatcher();
};
} | true |
f82ab52e590fe46ad65e331f3f3928dd05292783 | C++ | Vovtshik/project_ex_11.14 | /SourceE1114.cpp | UTF-8 | 2,295 | 3.828125 | 4 | [] | no_license | #include "../std_lib_facilities.h"
void in_file_text(string& name_file, vector<string>&vs); // The function of reading text from file to vector.
void number_characters_each_category(const string&s, int& al, int& sp, int& di); // The function for counting the characters of each category in a string and passing the results by reference in arguments.
void out_file_string(const string& nout, string& nin, const int& al, const int& sp, const int& di); // Function for outputting to the file the results of counting characters of each category:
int main()
{
vector<string>vs;
cout << "Enter file name to read text:\n";
string name_in;
cin >> name_in;
in_file_text(name_in, vs);
int alpha = 0;
int space = 0;
int digit = 0;
for(string s: vs)
{
number_characters_each_category(s, alpha, space, digit);
}
cout << "Enter a file name to record the character counts for each category:\n";
string name_out;
cin >> name_out;
out_file_string(name_out, name_in, alpha, space, digit);
return 0;
}
void in_file_text(string& name_file, vector<string>&vs)
{
ifstream ist(name_file);
if(!ist) error("Unable to open input file ", name_file);
ist.exceptions(ist.exceptions() | ios_base::badbit);
string new_line = "\n";
for(string temp; getline(ist, temp);)
{
{
stringstream ss(temp);
for(string s; ss >> s;)
{
vs.push_back(s);
}
}
if(!ist.eof())
vs.push_back(new_line);
}
}
void number_characters_each_category( const string&s, int& al, int& sp, int& di)
{
for(char ch: s)
{
if(isspace(ch))
++sp;
else if(isalpha(ch))
++al;
else if(isdigit(ch))
++di;
else
continue;
}
}
void out_file_string(const string& nout, string& nin, const int& al, const int& sp, const int& di)
{
ofstream ost{nout};
if (!ost) error("Unable to open output file ", nout);
ost << "In the text from the " << nin << " file, the number of characters in the categories: letters - " << al << "; whitespace characters - " << sp << "; decimal digits - " << di << ".\n";
} | true |
e2a85e58b88293fe64c7ec2e03ffa76c078fd970 | C++ | JuntaoLiu01/LeetCode | /Array/3SC.cpp | UTF-8 | 856 | 3.296875 | 3 | [] | no_license | #include <vector>
#include <algorithm>
#include <stdlib.h>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if(nums.size() < 3)
return 0;
sort(nums.begin(),nums.end());
int closestSum = nums[0]+nums[1]+nums[2];
for(int i = 0;i < nums.size()-2;i++){
int second = i+1,third = nums.size()-1;
while(second < third){
int curSum = nums[i]+nums[second]+nums[third];
if (curSum == target)
return curSum;
if(abs(target - curSum) < abs(target - closestSum))
closestSum = curSum;
if(curSum < target)
second++;
else
third--;
}
}
return closestSum;
}
}; | true |
25e58aa6cf532a2c2f801a121378c9112f828408 | C++ | sumnerjj/6.172 | /proj6/icache.h | UTF-8 | 877 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef ICACHE_H
#define ICACHE_H
#include <cmath>
#include "util.h"
class ICache
{
private:
struct Sample
{
Point3D pos;
Vector3D norm;
double invR0;
double r0;
double tolerance;
Colour irr;
bool has_irr;
Sample *next;
Sample(Point3D& pos, Vector3D& norm);
Sample(Point3D& pos, Vector3D& norm, double r0, Colour& irr, double tolerance);
~Sample();
double weight(Sample& x);
Colour getIrradiance(Sample& x);
};
Sample *first;
double tolerance;
double invTolerance;
double minSpacing;
double maxSpacing;
double find(Sample& x);
friend struct ICache::Sample;
public:
ICache(double tolerance, double minSpacing);
~ICache();
void insert(Point3D& p, Vector3D& n, double r0, Colour& irr);
bool getIrradiance(Point3D& p, Vector3D& n, Colour *c);
};
#endif
| true |
f4b2d1313f86eec96acc8a27452e40b87e4fe974 | C++ | AlekseyChi/cpp_project2020 | /sort_race/shakersortbyTolstykh.cpp | UTF-8 | 1,065 | 3.453125 | 3 | [] | no_license | #include <vector>
#include <string>
using namespace std;
vector<int> ShakerSort_Tolstykh(vector<int> data) {
int left = 0;
int right = data.size() - 1;
while (left <= right) {
for (int i = right; i > left; --i) {
if (data[i - 1] > data[i]) {
swap(data[i - 1], data[i]);
}
}
++left;
for (int i = left; i < right; ++i) {
if (data[i] > data[i + 1]) {
swap(data[i], data[i + 1]);
}
}
--right;
}
return data;
}
vector<double> ShakerSortdouble_Tolstykh(vector<double> data) {
int left = 0;
int right = data.size() - 1;
while (left <= right) {
for (int i = right; i > left; --i) {
if (data[i - 1] > data[i]) {
swap(data[i - 1], data[i]);
}
}
++left;
for (int i = left; i < right; ++i) {
if (data[i] > data[i + 1]) {
swap(data[i], data[i + 1]);
}
}
--right;
}
return data;
}
| true |
379a6ccaea8af4da84d14e92b401b99accb2659f | C++ | sahilranadive/Public-Private-Keys | /rsa.cpp | UTF-8 | 3,219 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <time.h>
#include <math.h>
#include <vector>
using namespace std;
int generatePrime(int num){
int flag = 0;
for(int i = 2; i <= num-1; i++){
if(num%i == 0)
break;
if(i == num-1)
return num;
}
return generatePrime(num+1);
}
int gcd(int a, int b)
{
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Function to return LCM of two numbers
int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
int generateSmall(int small, int large){
small = generatePrime(small);
while(large%small == 0){
small = generatePrime(small+1);
}
return small;
}
int modInverse(int a, int m)
{
a = a%m;
for (int x=1; x<m; x++)
if ((a*x) % m == 1)
return x;
}
long long moduloMultiplication(long long a,
long long b,
long long mod)
{
long long res = 0; // Initialize result
// Update a if it is more than
// or equal to mod
a %= mod;
while (b)
{
// If b is odd, add a with result
if (b & 1)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
int main(){
srand(time(0));
string str;
cin>>str;
vector<int> to_encrypt;
long long int number = 0;
for (int i = 0; i < str.size(); i++){
to_encrypt.push_back(str[i]-96);
//cout<<to_encrypt[i];
number = number*100 + to_encrypt[i];
}
cout<<"converted to number: "<<number<<endl;
long long int test1 = rand()%98 + pow(10,str.size());
long long int test2 = rand()%98 +pow(10,str.size());
long long int test3 = rand()%6 + 2;
long long int p1 = generatePrime(test1);
long long int p2 = generatePrime(test2);
cout<<"first number: "<<p1<<"\n"<<"second number: "<<p2<<endl;
long long int a_for_public = p1*p2;
int phi_for_private = lcm(p1-1,p2-1);
int b_for_public = generateSmall(test3,phi_for_private);
cout<<"a_for_public:"<<a_for_public<<"\t"<<"b_for_public:"<<b_for_public<<endl;
int k = 2; //to generate private key
int d_for_private = modInverse(b_for_public,phi_for_private);
cout<<"phi_for_private:"<<phi_for_private<<"\t"<<"d_for_private:"<<d_for_private<<endl;
long long int encrypted_data = 1;
for(int i = 0; i < b_for_public; i++){
encrypted_data = moduloMultiplication(encrypted_data,number,a_for_public);
//cout<<encrypted_data<<endl;
//encrypted_data = encrypted_data%a_for_public;
}
cout<<"encrypted_data: "<<encrypted_data<<endl;
long long int decrypted_data = 1;
long long int multiplier = encrypted_data;
for(int i = 0; i < d_for_private; i++){
decrypted_data = moduloMultiplication(decrypted_data,multiplier,a_for_public);
//decrypted_data = decrypted_data%a_for_public;
//cout<<decrypted_data<<endl;
}
//decrypted_data = decrypted_data*multiplier;
cout<<"decrypted_data: "<<decrypted_data<<endl;
}
| true |
48e5f4a9adce965973141feac0d023213a4ec78a | C++ | AugustRush/2017demo | /ARPhysics-master/Engine/Spring.h | UTF-8 | 2,609 | 2.828125 | 3 | [
"MIT"
] | permissive | //
// Spring.h
//
// Created by Adrian Russell on 25/03/2014.
// Copyright (c) 2014 Adrian Russell. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software. Permission is granted to anyone to
// use this software for any purpose, including commercial applications, and to
// alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source
// distribution.
//
#ifndef __ARPhysics__Spring_H__
#define __ARPhysics__Spring_H__
#include "Constraint.h"
/*! A constraint that acts like a spring allowing a body to be attached to a static point or another body. */
class Spring : public Constraint {
public:
/*! The value to give as fail length if you do not want to spring to ever fail. */
static const float SpringDoNotFail;
/*!
Constructs a new spring that attaches two bodies.
@param a
The first body.
@param b
The second body.
@param stiffness
The stiffness of the spring.
@param restLength
The length at which the spring is at rest.
@param failLength
The length at which the spring should fail and call the fail callback.
@discussion The spring can not remove itself when it fails; the specfied failCallBack must remove it.
*/
Spring(Body *a, Body *b, float stiffness, float restLength, float failLength = SpringDoNotFail);
/*! Spring destructor. */
~Spring();
/*! Solve the constraint.
@param dt
The delta time to solve the constaint for.
*/
void solve(float dt);
/*! Set the function to be called in the event that the spring extends past the fail length.
@param failCallBack
The function to call if/when the spring extends past the fail length.
*/
void setCallBack(std::function<void(Spring *)> failCallBack);
private:
float stiffness;
float restLength;
float failLength;
std::function<void(Spring *)> failCallBack;
};
#endif
| true |
16c1263fbe9b8bdb14b851af6a08f4c861636216 | C++ | we-l-ee/CastAway | /BBM412/BBM412/Moveable.h | UTF-8 | 1,059 | 2.875 | 3 | [] | no_license | #pragma once
#include <glm\ext.hpp>
#include "stddef.hpp"
class Moveable
{
protected:
glm::vec3 position;
Directions dir;
glm::mat4 translation;
glm::mat4 rotation;
glm::quat quat;
void pitch(float angle);
void yaw(float angle);
void roll(float angle);
void pitchAround(float angle, const glm::vec3 & vector);
void yawAround(float angle, const glm::vec3 & vector);
void rollAround(float angle, const glm::vec3 & vector);
public:
Moveable(const glm::vec3 & _pos = glm::vec3{ 0,0,0 } );
virtual void reset( const glm::mat4 & matrix );
virtual void reset( const glm::mat4 & trans, const glm::mat4 & rot );
virtual void translate(glm::vec3 displacement);
virtual void translate(float x, float y, float z);
virtual void translateOn(float x, float y, float z, const Directions & _dir );
virtual void rotate(float x, float y, float z);
virtual void rotateAround(float x, float y, float z, const Directions & dir );
glm::mat4 calculateModelMatrix();
virtual ~Moveable()=default;
};
| true |
294f8ef0302b39823eaa8c1f6e558d1090ece17f | C++ | claywjames/compression | /bytebuffer.hpp | UTF-8 | 519 | 2.953125 | 3 | [] | no_license | #ifndef BYTE_BUFFER_HPP
#define BYTE_BUFFER_HPP
#include <fstream>
class byteBuffer {
private:
unsigned char writeBuffer, readBuffer;
int bitsWritten, bitsRead;
public:
byteBuffer() : writeBuffer(0), readBuffer(0), bitsWritten(0), bitsRead(0) {}
void write(bool bit, std::ostream & output);
void write(unsigned char byte, std::ostream & output);
void outputBuffer(std::ostream & output);
bool read(std::istream & input);
unsigned char readByte(std::istream & input);
};
#endif | true |
65441b0727b27ca412da7d24eb6b83371974b16a | C++ | ciskavriezenga/CSD2_CPP_1920 | /CSD2b/session3/sine/writeToFile.cpp | UTF-8 | 1,028 | 3.546875 | 4 | [] | no_license | #include "writeToFile.h"
WriteToFile::WriteToFile(std::string fileName, bool overwrite)
{
// check if we are allowed to overwrite file
if(!overwrite) {
if(fileExists(fileName)){
std::cout << "\n------WriteToFile::WriteToFile------"
<< "File already exists, not allowed to overwrite!\n";
// NOTE: for now, simple solution: EXIT
throw "WriteToFile::WriteToFile - not able to open file: it already exists and not allowed to overwrite it.";
}
}
openFile(fileName);
}
WriteToFile::~WriteToFile()
{
file.close();
}
bool WriteToFile::write(std::string text)
{
if(file.is_open())
{
file << text;
return true;
} else return false;
}
bool WriteToFile::fileExists(const std::string& fileName)
{
// create a variable of type "struct stat"
struct stat buffer;
//check if file exists
if (stat(fileName.c_str(), &buffer) != -1)
{
return true;
}
return false;
}
bool WriteToFile::openFile(std::string fileName)
{
file.open(fileName);
return file.is_open();
}
| true |
d751ca9c59f9f22edaa0befa427ca95d3b42c97a | C++ | RealChaser/Cpp_Lecture | /C++_4/11_일관된초기화.cpp | UHC | 611 | 3.421875 | 3 | [] | no_license | // 11_ϰʱȭ- 205 page
struct Point { int x, y; };
class Complex
{
int re, im;
public:
Complex(int a, int b) : re(a), im(b) {}
};
int main()
{
/*
int n1 = 0;
int n2(0);
int x[3] = { 1,2,3 };
Point p = { 1,2 };
Complex c(1, 1);
*/
// (ü) ϳ ʱȭ ʱȭ .
// "Uniform Initialize"
/*
// copy initialize
int n1{ 0 };
int n2{ 0 };
int x[3]{ 1,2,3 };
Point p{ 1,2 };
Complex c{ 1, 1 };
*/
// list initialize
int n1={ 0 };
int n2={ 0 };
int x[3]={ 1,2,3 };
Point p={ 1,2 };
Complex c={ 1, 1 };
}
| true |